LogAudit.cpp 15 KB

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