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