1 /*
2  * Copyright (C) 2014 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include <ctype.h>
18 #include <endian.h>
19 #include <errno.h>
20 #include <limits.h>
21 #include <stdarg.h>
22 #include <stdint.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <sys/prctl.h>
26 #include <sys/uio.h>
27 #include <syslog.h>
28 
29 #include <fstream>
30 #include <sstream>
31 
32 #include <android-base/macros.h>
33 #include <log/log_properties.h>
34 #include <private/android_filesystem_config.h>
35 #include <private/android_logger.h>
36 
37 #include "LogAudit.h"
38 #include "LogBuffer.h"
39 #include "LogKlog.h"
40 #include "LogReader.h"
41 #include "LogUtils.h"
42 #include "libaudit.h"
43 
44 #define KMSG_PRIORITY(PRI)                               \
45     '<', '0' + LOG_MAKEPRI(LOG_AUTH, LOG_PRI(PRI)) / 10, \
46         '0' + LOG_MAKEPRI(LOG_AUTH, LOG_PRI(PRI)) % 10, '>'
47 
LogAudit(LogBuffer * buf,LogReader * reader,int fdDmesg)48 LogAudit::LogAudit(LogBuffer* buf, LogReader* reader, int fdDmesg)
49     : SocketListener(getLogSocket(), false),
50       logbuf(buf),
51       reader(reader),
52       fdDmesg(fdDmesg),
53       main(__android_logger_property_get_bool("ro.logd.auditd.main",
54                                               BOOL_DEFAULT_TRUE)),
55       events(__android_logger_property_get_bool("ro.logd.auditd.events",
56                                                 BOOL_DEFAULT_TRUE)),
57       initialized(false) {
58     static const char auditd_message[] = { KMSG_PRIORITY(LOG_INFO),
59                                            'l',
60                                            'o',
61                                            'g',
62                                            'd',
63                                            '.',
64                                            'a',
65                                            'u',
66                                            'd',
67                                            'i',
68                                            't',
69                                            'd',
70                                            ':',
71                                            ' ',
72                                            's',
73                                            't',
74                                            'a',
75                                            'r',
76                                            't',
77                                            '\n' };
78     write(fdDmesg, auditd_message, sizeof(auditd_message));
79 }
80 
onDataAvailable(SocketClient * cli)81 bool LogAudit::onDataAvailable(SocketClient* cli) {
82     if (!initialized) {
83         prctl(PR_SET_NAME, "logd.auditd");
84         initialized = true;
85     }
86 
87     struct audit_message rep;
88 
89     rep.nlh.nlmsg_type = 0;
90     rep.nlh.nlmsg_len = 0;
91     rep.data[0] = '\0';
92 
93     if (audit_get_reply(cli->getSocket(), &rep, GET_REPLY_BLOCKING, 0) < 0) {
94         SLOGE("Failed on audit_get_reply with error: %s", strerror(errno));
95         return false;
96     }
97 
98     logPrint("type=%d %.*s", rep.nlh.nlmsg_type, rep.nlh.nlmsg_len, rep.data);
99 
100     return true;
101 }
102 
hasMetadata(char * str,int str_len)103 static inline bool hasMetadata(char* str, int str_len) {
104     // need to check and see if str already contains bug metadata from
105     // possibility of stuttering if log audit crashes and then reloads kernel
106     // messages. Kernel denials that contain metadata will either end in
107     // "b/[0-9]+$" or "b/[0-9]+  duplicate messages suppressed$" which will put
108     // a '/' character at either 9 or 39 indices away from the end of the str.
109     return str_len >= 39 &&
110            (str[str_len - 9] == '/' || str[str_len - 39] == '/');
111 }
112 
populateDenialMap()113 std::map<std::string, std::string> LogAudit::populateDenialMap() {
114     std::ifstream bug_file("/vendor/etc/selinux/selinux_denial_metadata");
115     std::string line;
116     // allocate a map for the static map pointer in auditParse to keep track of,
117     // this function only runs once
118     std::map<std::string, std::string> denial_to_bug;
119     if (bug_file.good()) {
120         std::string scontext;
121         std::string tcontext;
122         std::string tclass;
123         std::string bug_num;
124         while (std::getline(bug_file, line)) {
125             std::stringstream split_line(line);
126             split_line >> scontext >> tcontext >> tclass >> bug_num;
127             denial_to_bug.emplace(scontext + tcontext + tclass, bug_num);
128         }
129     }
130     return denial_to_bug;
131 }
132 
denialParse(const std::string & denial,char terminator,const std::string & search_term)133 std::string LogAudit::denialParse(const std::string& denial, char terminator,
134                                   const std::string& search_term) {
135     size_t start_index = denial.find(search_term);
136     if (start_index != std::string::npos) {
137         start_index += search_term.length();
138         return denial.substr(
139             start_index, denial.find(terminator, start_index) - start_index);
140     }
141     return "";
142 }
143 
auditParse(const std::string & string,uid_t uid,std::string * bug_num)144 void LogAudit::auditParse(const std::string& string, uid_t uid,
145                           std::string* bug_num) {
146     static std::map<std::string, std::string> denial_to_bug =
147         populateDenialMap();
148     std::string scontext = denialParse(string, ':', "scontext=u:object_r:");
149     std::string tcontext = denialParse(string, ':', "tcontext=u:object_r:");
150     std::string tclass = denialParse(string, ' ', "tclass=");
151     if (scontext.empty()) {
152         scontext = denialParse(string, ':', "scontext=u:r:");
153     }
154     if (tcontext.empty()) {
155         tcontext = denialParse(string, ':', "tcontext=u:r:");
156     }
157     auto search = denial_to_bug.find(scontext + tcontext + tclass);
158     if (search != denial_to_bug.end()) {
159         bug_num->assign(" " + search->second);
160     } else {
161         bug_num->assign("");
162     }
163 
164     // Ensure the uid name is not null before passing it to the bug string.
165     if (uid >= AID_APP_START && uid <= AID_APP_END) {
166         char* uidname = android::uidToName(uid);
167         if (uidname) {
168             bug_num->append(" app=");
169             bug_num->append(uidname);
170             free(uidname);
171         }
172     }
173 }
174 
logPrint(const char * fmt,...)175 int LogAudit::logPrint(const char* fmt, ...) {
176     if (fmt == nullptr) {
177         return -EINVAL;
178     }
179 
180     va_list args;
181 
182     char* str = nullptr;
183     va_start(args, fmt);
184     int rc = vasprintf(&str, fmt, args);
185     va_end(args);
186 
187     if (rc < 0) {
188         return rc;
189     }
190     char* cp;
191     // Work around kernels missing
192     // https://github.com/torvalds/linux/commit/b8f89caafeb55fba75b74bea25adc4e4cd91be67
193     // Such kernels improperly add newlines inside audit messages.
194     while ((cp = strchr(str, '\n'))) {
195         *cp = ' ';
196     }
197 
198     while ((cp = strstr(str, "  "))) {
199         memmove(cp, cp + 1, strlen(cp + 1) + 1);
200     }
201     pid_t pid = getpid();
202     pid_t tid = gettid();
203     uid_t uid = AID_LOGD;
204     static const char pid_str[] = " pid=";
205     char* pidptr = strstr(str, pid_str);
206     if (pidptr && isdigit(pidptr[sizeof(pid_str) - 1])) {
207         cp = pidptr + sizeof(pid_str) - 1;
208         pid = 0;
209         while (isdigit(*cp)) {
210             pid = (pid * 10) + (*cp - '0');
211             ++cp;
212         }
213         tid = pid;
214         logbuf->wrlock();
215         uid = logbuf->pidToUid(pid);
216         logbuf->unlock();
217         memmove(pidptr, cp, strlen(cp) + 1);
218     }
219 
220     bool info = strstr(str, " permissive=1") || strstr(str, " policy loaded ");
221     static std::string denial_metadata;
222     if ((fdDmesg >= 0) && initialized) {
223         struct iovec iov[4];
224         static const char log_info[] = { KMSG_PRIORITY(LOG_INFO) };
225         static const char log_warning[] = { KMSG_PRIORITY(LOG_WARNING) };
226         static const char newline[] = "\n";
227 
228         auditParse(str, uid, &denial_metadata);
229         iov[0].iov_base = info ? const_cast<char*>(log_info) : const_cast<char*>(log_warning);
230         iov[0].iov_len = info ? sizeof(log_info) : sizeof(log_warning);
231         iov[1].iov_base = str;
232         iov[1].iov_len = strlen(str);
233         iov[2].iov_base = const_cast<char*>(denial_metadata.c_str());
234         iov[2].iov_len = denial_metadata.length();
235         iov[3].iov_base = const_cast<char*>(newline);
236         iov[3].iov_len = strlen(newline);
237 
238         writev(fdDmesg, iov, arraysize(iov));
239     }
240 
241     if (!main && !events) {
242         free(str);
243         return 0;
244     }
245 
246     log_time now(log_time::EPOCH);
247 
248     static const char audit_str[] = " audit(";
249     char* timeptr = strstr(str, audit_str);
250     if (timeptr &&
251         ((cp = now.strptime(timeptr + sizeof(audit_str) - 1, "%s.%q"))) &&
252         (*cp == ':')) {
253         memcpy(timeptr + sizeof(audit_str) - 1, "0.0", 3);
254         memmove(timeptr + sizeof(audit_str) - 1 + 3, cp, strlen(cp) + 1);
255         if (!isMonotonic()) {
256             if (android::isMonotonic(now)) {
257                 LogKlog::convertMonotonicToReal(now);
258             }
259         } else {
260             if (!android::isMonotonic(now)) {
261                 LogKlog::convertRealToMonotonic(now);
262             }
263         }
264     } else if (isMonotonic()) {
265         now = log_time(CLOCK_MONOTONIC);
266     } else {
267         now = log_time(CLOCK_REALTIME);
268     }
269 
270     // log to events
271 
272     size_t str_len = strnlen(str, LOGGER_ENTRY_MAX_PAYLOAD);
273     if (((fdDmesg < 0) || !initialized) && !hasMetadata(str, str_len))
274         auditParse(str, uid, &denial_metadata);
275     str_len = (str_len + denial_metadata.length() <= LOGGER_ENTRY_MAX_PAYLOAD)
276                   ? str_len + denial_metadata.length()
277                   : LOGGER_ENTRY_MAX_PAYLOAD;
278     size_t message_len = str_len + sizeof(android_log_event_string_t);
279 
280     log_mask_t notify = 0;
281 
282     if (events) {  // begin scope for event buffer
283         uint32_t buffer[(message_len + sizeof(uint32_t) - 1) / sizeof(uint32_t)];
284 
285         android_log_event_string_t* event =
286             reinterpret_cast<android_log_event_string_t*>(buffer);
287         event->header.tag = htole32(AUDITD_LOG_TAG);
288         event->type = EVENT_TYPE_STRING;
289         event->length = htole32(str_len);
290         memcpy(event->data, str, str_len - denial_metadata.length());
291         memcpy(event->data + str_len - denial_metadata.length(),
292                denial_metadata.c_str(), denial_metadata.length());
293 
294         rc = logbuf->log(
295             LOG_ID_EVENTS, now, uid, pid, tid, reinterpret_cast<char*>(event),
296             (message_len <= UINT16_MAX) ? (uint16_t)message_len : UINT16_MAX);
297         if (rc >= 0) {
298             notify |= 1 << LOG_ID_EVENTS;
299         }
300         // end scope for event buffer
301     }
302 
303     // log to main
304 
305     static const char comm_str[] = " comm=\"";
306     const char* comm = strstr(str, comm_str);
307     const char* estr = str + strlen(str);
308     const char* commfree = nullptr;
309     if (comm) {
310         estr = comm;
311         comm += sizeof(comm_str) - 1;
312     } else if (pid == getpid()) {
313         pid = tid;
314         comm = "auditd";
315     } else {
316         logbuf->wrlock();
317         comm = commfree = logbuf->pidToName(pid);
318         logbuf->unlock();
319         if (!comm) {
320             comm = "unknown";
321         }
322     }
323 
324     const char* ecomm = strchr(comm, '"');
325     if (ecomm) {
326         ++ecomm;
327         str_len = ecomm - comm;
328     } else {
329         str_len = strlen(comm) + 1;
330         ecomm = "";
331     }
332     size_t prefix_len = estr - str;
333     if (prefix_len > LOGGER_ENTRY_MAX_PAYLOAD) {
334         prefix_len = LOGGER_ENTRY_MAX_PAYLOAD;
335     }
336     size_t suffix_len = strnlen(ecomm, LOGGER_ENTRY_MAX_PAYLOAD - prefix_len);
337     message_len =
338         str_len + prefix_len + suffix_len + denial_metadata.length() + 2;
339 
340     if (main) {  // begin scope for main buffer
341         char newstr[message_len];
342 
343         *newstr = info ? ANDROID_LOG_INFO : ANDROID_LOG_WARN;
344         strlcpy(newstr + 1, comm, str_len);
345         strncpy(newstr + 1 + str_len, str, prefix_len);
346         strncpy(newstr + 1 + str_len + prefix_len, ecomm, suffix_len);
347         strncpy(newstr + 1 + str_len + prefix_len + suffix_len,
348                 denial_metadata.c_str(), denial_metadata.length());
349 
350         rc = logbuf->log(
351             LOG_ID_MAIN, now, uid, pid, tid, newstr,
352             (message_len <= UINT16_MAX) ? (uint16_t)message_len : UINT16_MAX);
353 
354         if (rc >= 0) {
355             notify |= 1 << LOG_ID_MAIN;
356         }
357         // end scope for main buffer
358     }
359 
360     free(const_cast<char*>(commfree));
361     free(str);
362 
363     if (notify) {
364         reader->notifyNewLog(notify);
365         if (rc < 0) {
366             rc = message_len;
367         }
368     }
369 
370     return rc;
371 }
372 
log(char * buf,size_t len)373 int LogAudit::log(char* buf, size_t len) {
374     char* audit = strstr(buf, " audit(");
375     if (!audit || (audit >= &buf[len])) {
376         return 0;
377     }
378 
379     *audit = '\0';
380 
381     int rc;
382     char* type = strstr(buf, "type=");
383     if (type && (type < &buf[len])) {
384         rc = logPrint("%s %s", type, audit + 1);
385     } else {
386         rc = logPrint("%s", audit + 1);
387     }
388     *audit = ' ';
389     return rc;
390 }
391 
getLogSocket()392 int LogAudit::getLogSocket() {
393     int fd = audit_open();
394     if (fd < 0) {
395         return fd;
396     }
397     if (audit_setup(fd, getpid()) < 0) {
398         audit_close(fd);
399         fd = -1;
400     }
401     return fd;
402 }
403