• 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)51 LogAudit::LogAudit(LogBuffer* buf, int fdDmesg)
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     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 static auto populateDenialMap() {
114     std::map<std::tuple<std::string, std::string, std::string>, std::string> denial_to_bug;
115     // Order matters. Only the first occurrence of a
116     // (scontext, tcontext, tclass) combination is recorded.
117     for (const auto& bug_map_file :
118          {"/system_ext/etc/selinux/bug_map"s, "/vendor/etc/selinux/selinux_denial_metadata"s,
119           "/system/etc/selinux/bug_map"s}) {
120         std::string file_contents;
121         if (!android::base::ReadFileToString(bug_map_file, &file_contents)) {
122             continue;
123         }
124         int errors = 0;
125         for (const auto& line : android::base::Split(file_contents, "\n")) {
126             const auto fields = android::base::Tokenize(line, " ");
127             if (fields.empty() || android::base::StartsWith(fields.front(), '#')) {
128                 continue;
129             }
130             if (fields.size() == 4) {
131                 const std::string& scontext = fields[0];
132                 const std::string& tcontext = fields[1];
133                 const std::string& tclass = fields[2];
134                 const std::string& bug_num = fields[3];
135                 const auto [it, success] =
136                         denial_to_bug.try_emplace({scontext, tcontext, tclass}, bug_num);
137                 if (!success) {
138                     const auto& [key, value] = *it;
139                     LOG(WARNING) << "Ignored bug_map definition in " << bug_map_file << ": '"
140                                  << line
141                                  << "', (scontext, tcontext, tclass) denial combination is already "
142                                     "tagged with bug metadata '"
143                                  << value << "'";
144                 }
145             } else {
146                 LOG(ERROR) << "Ignored ill-formed bug_map definition in " << bug_map_file << ": '"
147                            << line << "'";
148                 ++errors;
149             }
150         }
151         if (errors) {
152             LOG(ERROR) << "Loaded bug_map file with " << errors << " errors: " << bug_map_file;
153         } else {
154             LOG(INFO) << "Loaded bug_map file: " << bug_map_file;
155         }
156     }
157     return denial_to_bug;
158 }
159 
denialParse(const std::string & denial,char terminator,const std::string & search_term)160 std::string LogAudit::denialParse(const std::string& denial, char terminator,
161                                   const std::string& search_term) {
162     size_t start_index = denial.find(search_term);
163     if (start_index != std::string::npos) {
164         start_index += search_term.length();
165         return denial.substr(
166             start_index, denial.find(terminator, start_index) - start_index);
167     }
168     return "";
169 }
170 
auditParse(const std::string & string,uid_t uid)171 std::string LogAudit::auditParse(const std::string& string, uid_t uid) {
172     // Allocate a static map object to memoize the loaded bug_map files.
173     static auto denial_to_bug = populateDenialMap();
174 
175     std::string result;
176     std::string scontext = denialParse(string, ':', "scontext=u:object_r:");
177     std::string tcontext = denialParse(string, ':', "tcontext=u:object_r:");
178     std::string tclass = denialParse(string, ' ', "tclass=");
179     if (scontext.empty()) {
180         scontext = denialParse(string, ':', "scontext=u:r:");
181     }
182     if (tcontext.empty()) {
183         tcontext = denialParse(string, ':', "tcontext=u:r:");
184     }
185     auto search = denial_to_bug.find({scontext, tcontext, tclass});
186     if (search != denial_to_bug.end()) {
187         result = " bug=" + search->second;
188     }
189 
190     // Ensure the uid name is not null before passing it to the bug string.
191     if (uid >= AID_APP_START && uid <= AID_APP_END) {
192         char* uidname = android::uidToName(uid);
193         if (uidname) {
194             result.append(" app="s + uidname);
195             free(uidname);
196         }
197     }
198     return result;
199 }
200 
logPrint(const char * fmt,...)201 int LogAudit::logPrint(const char* fmt, ...) {
202     if (fmt == nullptr) {
203         return -EINVAL;
204     }
205 
206     va_list args;
207 
208     char* str = nullptr;
209     va_start(args, fmt);
210     int rc = vasprintf(&str, fmt, args);
211     va_end(args);
212 
213     if (rc < 0) {
214         return rc;
215     }
216     char* cp;
217     // Work around kernels missing
218     // https://github.com/torvalds/linux/commit/b8f89caafeb55fba75b74bea25adc4e4cd91be67
219     // Such kernels improperly add newlines inside audit messages.
220     while ((cp = strchr(str, '\n'))) {
221         *cp = ' ';
222     }
223 
224     pid_t pid = getpid();
225     pid_t tid = gettid();
226     uid_t uid = AID_LOGD;
227     static const char pid_str[] = " pid=";
228     char* pidptr = strstr(str, pid_str);
229     if (pidptr && isdigit(pidptr[sizeof(pid_str) - 1])) {
230         cp = pidptr + sizeof(pid_str) - 1;
231         pid = 0;
232         while (isdigit(*cp)) {
233             pid = (pid * 10) + (*cp - '0');
234             ++cp;
235         }
236         tid = pid;
237         uid = android::pidToUid(pid);
238         memmove(pidptr, cp, strlen(cp) + 1);
239     }
240 
241     bool info = strstr(str, " permissive=1") || strstr(str, " policy loaded ");
242     static std::string denial_metadata;
243     if ((fdDmesg >= 0) && initialized) {
244         struct iovec iov[4];
245         static const char log_info[] = { KMSG_PRIORITY(LOG_INFO) };
246         static const char log_warning[] = { KMSG_PRIORITY(LOG_WARNING) };
247         static const char newline[] = "\n";
248 
249         denial_metadata = auditParse(str, uid);
250         iov[0].iov_base = info ? const_cast<char*>(log_info) : const_cast<char*>(log_warning);
251         iov[0].iov_len = info ? sizeof(log_info) : sizeof(log_warning);
252         iov[1].iov_base = str;
253         iov[1].iov_len = strlen(str);
254         iov[2].iov_base = const_cast<char*>(denial_metadata.c_str());
255         iov[2].iov_len = denial_metadata.length();
256         iov[3].iov_base = const_cast<char*>(newline);
257         iov[3].iov_len = strlen(newline);
258 
259         writev(fdDmesg, iov, arraysize(iov));
260     }
261 
262     if (!main && !events) {
263         free(str);
264         return 0;
265     }
266 
267     log_time now(log_time::EPOCH);
268 
269     static const char audit_str[] = " audit(";
270     char* timeptr = strstr(str, audit_str);
271     if (timeptr && ((cp = now.strptime(timeptr + sizeof(audit_str) - 1, "%s.%q"))) &&
272         (*cp == ':')) {
273         memcpy(timeptr + sizeof(audit_str) - 1, "0.0", 3);
274         memmove(timeptr + sizeof(audit_str) - 1 + 3, cp, strlen(cp) + 1);
275     } else {
276         now = log_time(CLOCK_REALTIME);
277     }
278 
279     // log to events
280 
281     size_t str_len = strnlen(str, LOGGER_ENTRY_MAX_PAYLOAD);
282     if (((fdDmesg < 0) || !initialized) && !hasMetadata(str, str_len))
283         denial_metadata = auditParse(str, uid);
284     str_len = (str_len + denial_metadata.length() <= LOGGER_ENTRY_MAX_PAYLOAD)
285                   ? str_len + denial_metadata.length()
286                   : LOGGER_ENTRY_MAX_PAYLOAD;
287     size_t message_len = str_len + sizeof(android_log_event_string_t);
288 
289     unsigned int notify = 0;
290 
291     if (events) {  // begin scope for event buffer
292         uint32_t buffer[(message_len + sizeof(uint32_t) - 1) / sizeof(uint32_t)];
293 
294         android_log_event_string_t* event =
295             reinterpret_cast<android_log_event_string_t*>(buffer);
296         event->header.tag = htole32(AUDITD_LOG_TAG);
297         event->type = EVENT_TYPE_STRING;
298         event->length = htole32(str_len);
299         memcpy(event->data, str, str_len - denial_metadata.length());
300         memcpy(event->data + str_len - denial_metadata.length(),
301                denial_metadata.c_str(), denial_metadata.length());
302 
303         rc = logbuf->Log(LOG_ID_EVENTS, now, uid, pid, tid, reinterpret_cast<char*>(event),
304                          (message_len <= UINT16_MAX) ? (uint16_t)message_len : UINT16_MAX);
305         if (rc >= 0) {
306             notify |= 1 << LOG_ID_EVENTS;
307         }
308         // end scope for event buffer
309     }
310 
311     // log to main
312 
313     static const char comm_str[] = " comm=\"";
314     const char* comm = strstr(str, comm_str);
315     const char* estr = str + strlen(str);
316     const char* commfree = nullptr;
317     if (comm) {
318         estr = comm;
319         comm += sizeof(comm_str) - 1;
320     } else if (pid == getpid()) {
321         pid = tid;
322         comm = "auditd";
323     } else {
324         comm = commfree = android::pidToName(pid);
325         if (!comm) {
326             comm = "unknown";
327         }
328     }
329 
330     const char* ecomm = strchr(comm, '"');
331     if (ecomm) {
332         ++ecomm;
333         str_len = ecomm - comm;
334     } else {
335         str_len = strlen(comm) + 1;
336         ecomm = "";
337     }
338     size_t prefix_len = estr - str;
339     if (prefix_len > LOGGER_ENTRY_MAX_PAYLOAD) {
340         prefix_len = LOGGER_ENTRY_MAX_PAYLOAD;
341     }
342     size_t suffix_len = strnlen(ecomm, LOGGER_ENTRY_MAX_PAYLOAD - prefix_len);
343     message_len =
344         str_len + prefix_len + suffix_len + denial_metadata.length() + 2;
345 
346     if (main) {  // begin scope for main buffer
347         char newstr[message_len];
348 
349         *newstr = info ? ANDROID_LOG_INFO : ANDROID_LOG_WARN;
350         strlcpy(newstr + 1, comm, str_len);
351         strncpy(newstr + 1 + str_len, str, prefix_len);
352         strncpy(newstr + 1 + str_len + prefix_len, ecomm, suffix_len);
353         strncpy(newstr + 1 + str_len + prefix_len + suffix_len,
354                 denial_metadata.c_str(), denial_metadata.length());
355 
356         rc = logbuf->Log(LOG_ID_MAIN, now, uid, pid, tid, newstr,
357                          (message_len <= UINT16_MAX) ? (uint16_t)message_len : UINT16_MAX);
358 
359         if (rc >= 0) {
360             notify |= 1 << LOG_ID_MAIN;
361         }
362         // end scope for main buffer
363     }
364 
365     free(const_cast<char*>(commfree));
366     free(str);
367 
368     if (notify) {
369         if (rc < 0) {
370             rc = message_len;
371         }
372     }
373 
374     return rc;
375 }
376 
log(char * buf,size_t len)377 int LogAudit::log(char* buf, size_t len) {
378     char* audit = strstr(buf, " audit(");
379     if (!audit || (audit >= &buf[len])) {
380         return 0;
381     }
382 
383     *audit = '\0';
384 
385     int rc;
386     char* type = strstr(buf, "type=");
387     if (type && (type < &buf[len])) {
388         rc = logPrint("%s %s", type, audit + 1);
389     } else {
390         rc = logPrint("%s", audit + 1);
391     }
392     *audit = ' ';
393     return rc;
394 }
395 
getLogSocket()396 int LogAudit::getLogSocket() {
397     int fd = audit_open();
398     if (fd < 0) {
399         return fd;
400     }
401     if (audit_setup(fd, getpid()) < 0) {
402         audit_close(fd);
403         fd = -1;
404     }
405     return fd;
406 }
407