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     pid_t pid = getpid();
226     pid_t tid = gettid();
227     uid_t uid = AID_LOGD;
228     static const char pid_str[] = " pid=";
229     char* pidptr = strstr(str, pid_str);
230     if (pidptr && isdigit(pidptr[sizeof(pid_str) - 1])) {
231         cp = pidptr + sizeof(pid_str) - 1;
232         pid = 0;
233         while (isdigit(*cp)) {
234             pid = (pid * 10) + (*cp - '0');
235             ++cp;
236         }
237         tid = pid;
238         uid = stats_->PidToUid(pid);
239         memmove(pidptr, cp, strlen(cp) + 1);
240     }
241 
242     bool info = strstr(str, " permissive=1") || strstr(str, " policy loaded ");
243     static std::string denial_metadata;
244     if ((fdDmesg >= 0) && initialized) {
245         struct iovec iov[4];
246         static const char log_info[] = { KMSG_PRIORITY(LOG_INFO) };
247         static const char log_warning[] = { KMSG_PRIORITY(LOG_WARNING) };
248         static const char newline[] = "\n";
249 
250         denial_metadata = auditParse(str, uid);
251         iov[0].iov_base = info ? const_cast<char*>(log_info) : const_cast<char*>(log_warning);
252         iov[0].iov_len = info ? sizeof(log_info) : sizeof(log_warning);
253         iov[1].iov_base = str;
254         iov[1].iov_len = strlen(str);
255         iov[2].iov_base = const_cast<char*>(denial_metadata.c_str());
256         iov[2].iov_len = denial_metadata.length();
257         iov[3].iov_base = const_cast<char*>(newline);
258         iov[3].iov_len = strlen(newline);
259 
260         writev(fdDmesg, iov, arraysize(iov));
261     }
262 
263     if (!main && !events) {
264         free(str);
265         return 0;
266     }
267 
268     log_time now(log_time::EPOCH);
269 
270     static const char audit_str[] = " audit(";
271     char* timeptr = strstr(str, audit_str);
272     if (timeptr && ((cp = now.strptime(timeptr + sizeof(audit_str) - 1, "%s.%q"))) &&
273         (*cp == ':')) {
274         memcpy(timeptr + sizeof(audit_str) - 1, "0.0", 3);
275         memmove(timeptr + sizeof(audit_str) - 1 + 3, cp, strlen(cp) + 1);
276     } else {
277         now = log_time(CLOCK_REALTIME);
278     }
279 
280     // log to events
281 
282     size_t str_len = strnlen(str, LOGGER_ENTRY_MAX_PAYLOAD);
283     if (((fdDmesg < 0) || !initialized) && !hasMetadata(str, str_len))
284         denial_metadata = auditParse(str, uid);
285     str_len = (str_len + denial_metadata.length() <= LOGGER_ENTRY_MAX_PAYLOAD)
286                   ? str_len + denial_metadata.length()
287                   : LOGGER_ENTRY_MAX_PAYLOAD;
288     size_t message_len = str_len + sizeof(android_log_event_string_t);
289 
290     unsigned int notify = 0;
291 
292     if (events) {  // begin scope for event buffer
293         uint32_t buffer[(message_len + sizeof(uint32_t) - 1) / sizeof(uint32_t)];
294 
295         android_log_event_string_t* event =
296             reinterpret_cast<android_log_event_string_t*>(buffer);
297         event->header.tag = htole32(AUDITD_LOG_TAG);
298         event->type = EVENT_TYPE_STRING;
299         event->length = htole32(str_len);
300         memcpy(event->data, str, str_len - denial_metadata.length());
301         memcpy(event->data + str_len - denial_metadata.length(),
302                denial_metadata.c_str(), denial_metadata.length());
303 
304         rc = logbuf->Log(LOG_ID_EVENTS, now, uid, pid, tid, reinterpret_cast<char*>(event),
305                          (message_len <= UINT16_MAX) ? (uint16_t)message_len : UINT16_MAX);
306         if (rc >= 0) {
307             notify |= 1 << LOG_ID_EVENTS;
308         }
309         // end scope for event buffer
310     }
311 
312     // log to main
313 
314     static const char comm_str[] = " comm=\"";
315     const char* comm = strstr(str, comm_str);
316     const char* estr = str + strlen(str);
317     const char* commfree = nullptr;
318     if (comm) {
319         estr = comm;
320         comm += sizeof(comm_str) - 1;
321     } else if (pid == getpid()) {
322         pid = tid;
323         comm = "auditd";
324     } else {
325         comm = commfree = stats_->PidToName(pid);
326         if (!comm) {
327             comm = "unknown";
328         }
329     }
330 
331     const char* ecomm = strchr(comm, '"');
332     if (ecomm) {
333         ++ecomm;
334         str_len = ecomm - comm;
335     } else {
336         str_len = strlen(comm) + 1;
337         ecomm = "";
338     }
339     size_t prefix_len = estr - str;
340     if (prefix_len > LOGGER_ENTRY_MAX_PAYLOAD) {
341         prefix_len = LOGGER_ENTRY_MAX_PAYLOAD;
342     }
343     size_t suffix_len = strnlen(ecomm, LOGGER_ENTRY_MAX_PAYLOAD - prefix_len);
344     message_len =
345         str_len + prefix_len + suffix_len + denial_metadata.length() + 2;
346 
347     if (main) {  // begin scope for main buffer
348         char newstr[message_len];
349 
350         *newstr = info ? ANDROID_LOG_INFO : ANDROID_LOG_WARN;
351         strlcpy(newstr + 1, comm, str_len);
352         strncpy(newstr + 1 + str_len, str, prefix_len);
353         strncpy(newstr + 1 + str_len + prefix_len, ecomm, suffix_len);
354         strncpy(newstr + 1 + str_len + prefix_len + suffix_len,
355                 denial_metadata.c_str(), denial_metadata.length());
356 
357         rc = logbuf->Log(LOG_ID_MAIN, now, uid, pid, tid, newstr,
358                          (message_len <= UINT16_MAX) ? (uint16_t)message_len : UINT16_MAX);
359 
360         if (rc >= 0) {
361             notify |= 1 << LOG_ID_MAIN;
362         }
363         // end scope for main buffer
364     }
365 
366     free(const_cast<char*>(commfree));
367     free(str);
368 
369     if (notify) {
370         if (rc < 0) {
371             rc = message_len;
372         }
373     }
374 
375     return rc;
376 }
377 
log(char * buf,size_t len)378 int LogAudit::log(char* buf, size_t len) {
379     char* audit = strstr(buf, " audit(");
380     if (!audit || (audit >= &buf[len])) {
381         return 0;
382     }
383 
384     *audit = '\0';
385 
386     int rc;
387     char* type = strstr(buf, "type=");
388     if (type && (type < &buf[len])) {
389         rc = logPrint("%s %s", type, audit + 1);
390     } else {
391         rc = logPrint("%s", audit + 1);
392     }
393     *audit = ' ';
394     return rc;
395 }
396 
getLogSocket()397 int LogAudit::getLogSocket() {
398     int fd = audit_open();
399     if (fd < 0) {
400         return fd;
401     }
402     if (audit_setup(fd, getpid()) < 0) {
403         audit_close(fd);
404         fd = -1;
405     }
406     return fd;
407 }
408