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