trace.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  1. /*
  2. * Copyright (C) 2015 John Crispin <blogic@openwrt.org>
  3. *
  4. * This program is free software; you can redistribute it and/or modify
  5. * it under the terms of the GNU Lesser General Public License version 2.1
  6. * as published by the Free Software Foundation
  7. *
  8. * This program is distributed in the hope that it will be useful,
  9. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. * GNU General Public License for more details.
  12. */
  13. #define _GNU_SOURCE
  14. #include <fcntl.h>
  15. #include <stddef.h>
  16. #include <sys/ptrace.h>
  17. #include <sys/stat.h>
  18. #include <sys/types.h>
  19. #include <sys/user.h>
  20. #include <sys/wait.h>
  21. #include <unistd.h>
  22. #include <stdlib.h>
  23. #include <stdio.h>
  24. #include <errno.h>
  25. #include <libgen.h>
  26. #include <syslog.h>
  27. #include <limits.h>
  28. #ifndef PTRACE_EVENT_STOP
  29. /* PTRACE_EVENT_STOP is defined in linux/ptrace.h, but this header
  30. * collides with musl's sys/ptrace.h */
  31. #define PTRACE_EVENT_STOP 128
  32. #endif
  33. #ifndef PTRACE_EVENT_SECCOMP
  34. /* undefined with uClibc-ng */
  35. #define PTRACE_EVENT_SECCOMP 7
  36. #endif
  37. #include <libubox/ulog.h>
  38. #include <libubox/uloop.h>
  39. #include <libubox/blobmsg.h>
  40. #include <libubox/blobmsg_json.h>
  41. #include "../syscall-names.h"
  42. #define _offsetof(a, b) __builtin_offsetof(a,b)
  43. #define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0]))
  44. #if defined (__aarch64__)
  45. #include <linux/ptrace.h>
  46. #elif defined(__amd64__)
  47. #define reg_syscall_nr _offsetof(struct user, regs.orig_rax)
  48. #elif defined(__arm__)
  49. #include <asm/ptrace.h> /* for PTRACE_SET_SYSCALL */
  50. #define reg_syscall_nr _offsetof(struct user, regs.uregs[7])
  51. # if defined(__ARM_EABI__)
  52. # define reg_retval_nr _offsetof(struct user, regs.uregs[0])
  53. # endif
  54. #elif defined(__i386__)
  55. #define reg_syscall_nr _offsetof(struct user, regs.orig_eax)
  56. #elif defined(__mips)
  57. # ifndef EF_REG2
  58. # define EF_REG2 8
  59. # endif
  60. #define reg_syscall_nr (EF_REG2 / 4)
  61. #elif defined(__PPC__)
  62. #define reg_syscall_nr _offsetof(struct user, regs.gpr[0])
  63. #define reg_retval_nr _offsetof(struct user, regs.gpr[3])
  64. #else
  65. #error tracing is not supported on this architecture
  66. #endif
  67. enum mode {
  68. UTRACE,
  69. SECCOMP_TRACE,
  70. } mode = UTRACE;
  71. struct tracee {
  72. struct uloop_process proc;
  73. int in_syscall;
  74. };
  75. static struct tracee tracer;
  76. static int syscall_count[SYSCALL_COUNT];
  77. static int violation_count;
  78. static struct blob_buf b;
  79. static int debug;
  80. char *json = NULL;
  81. int ptrace_restart;
  82. static void set_syscall(const char *name, int val)
  83. {
  84. int i;
  85. for (i = 0; i < SYSCALL_COUNT; i++) {
  86. int sc = syscall_index_to_number(i);
  87. if (syscall_name(sc) && !strcmp(syscall_name(sc), name)) {
  88. syscall_count[i] = val;
  89. return;
  90. }
  91. }
  92. }
  93. struct syscall {
  94. int syscall;
  95. int count;
  96. };
  97. static int cmp_count(const void *a, const void *b)
  98. {
  99. return ((struct syscall*)b)->count - ((struct syscall*)a)->count;
  100. }
  101. static void print_syscalls(int policy, const char *json)
  102. {
  103. void *c, *d, *e;
  104. int i;
  105. char *tmp;
  106. if (mode == UTRACE) {
  107. set_syscall("rt_sigaction", 1);
  108. set_syscall("sigreturn", 1);
  109. set_syscall("rt_sigreturn", 1);
  110. set_syscall("exit_group", 1);
  111. set_syscall("exit", 1);
  112. }
  113. struct syscall sorted[SYSCALL_COUNT];
  114. for (i = 0; i < SYSCALL_COUNT; i++) {
  115. sorted[i].syscall = syscall_index_to_number(i);
  116. sorted[i].count = syscall_count[i];
  117. }
  118. qsort(sorted, SYSCALL_COUNT, sizeof(sorted[0]), cmp_count);
  119. blob_buf_init(&b, 0);
  120. blobmsg_add_string(&b, "defaultAction", "SCMP_ACT_KILL_PROCESS");
  121. c = blobmsg_open_array(&b, "syscalls");
  122. d = blobmsg_open_table(&b, "");
  123. e = blobmsg_open_array(&b, "names");
  124. for (i = 0; i < SYSCALL_COUNT; i++) {
  125. int sc = sorted[i].syscall;
  126. if (!sorted[i].count)
  127. break;
  128. if (syscall_name(sc)) {
  129. if (debug)
  130. printf("syscall %d (%s) was called %d times\n",
  131. sc, syscall_name(sc), sorted[i].count);
  132. blobmsg_add_string(&b, NULL, syscall_name(sc));
  133. } else {
  134. ULOG_ERR("no name found for syscall(%d)\n", sc);
  135. }
  136. }
  137. blobmsg_close_array(&b, e);
  138. blobmsg_add_string(&b, "action", "SCMP_ACT_ALLOW");
  139. blobmsg_close_table(&b, d);
  140. blobmsg_close_array(&b, c);
  141. if (json) {
  142. FILE *fp = fopen(json, "w");
  143. if (fp) {
  144. tmp = blobmsg_format_json_indent(b.head, true, 0);
  145. if (!tmp) {
  146. fclose(fp);
  147. return;
  148. }
  149. fprintf(fp, "%s\n", tmp);
  150. free(tmp);
  151. fclose(fp);
  152. ULOG_INFO("saving syscall trace to %s\n", json);
  153. } else {
  154. ULOG_ERR("failed to open %s\n", json);
  155. }
  156. } else {
  157. tmp = blobmsg_format_json_indent(b.head, true, 0);
  158. if (!tmp)
  159. return;
  160. printf("%s\n", tmp);
  161. free(tmp);
  162. }
  163. }
  164. static void report_seccomp_vialation(pid_t pid, unsigned syscall)
  165. {
  166. char buf[200];
  167. snprintf(buf, sizeof(buf), "/proc/%d/cmdline", pid);
  168. int f = open(buf, O_RDONLY);
  169. if (f < 0)
  170. return;
  171. int r = read(f, buf, sizeof(buf) - 1);
  172. buf[sizeof(buf) - 1] = '\0';
  173. if (r >= 0)
  174. buf[r] = 0;
  175. else
  176. strcpy(buf, "unknown?");
  177. close(f);
  178. if (violation_count < INT_MAX)
  179. violation_count++;
  180. int i = syscall_index(syscall);
  181. if (i >= 0) {
  182. syscall_count[i]++;
  183. ULOG_ERR("%s[%u] tried to call non-whitelisted syscall: %s (see %s)\n",
  184. buf, pid, syscall_name(syscall), json);
  185. } else {
  186. ULOG_ERR("%s[%u] tried to call non-whitelisted syscall: %d (see %s)\n",
  187. buf, pid, syscall, json);
  188. }
  189. }
  190. static void tracer_cb(struct uloop_process *c, int ret)
  191. {
  192. struct tracee *tracee = container_of(c, struct tracee, proc);
  193. int inject_signal = 0;
  194. /* We explicitely check for events in upper 16 bits, because
  195. * musl (as opposed to glibc) does not report
  196. * PTRACE_EVENT_STOP as WIFSTOPPED */
  197. if (WIFSTOPPED(ret) || (ret >> 16)) {
  198. if (WSTOPSIG(ret) & 0x80) {
  199. if (!tracee->in_syscall) {
  200. #ifdef __aarch64__
  201. int syscall = -1;
  202. struct ptrace_syscall_info ptsi = {.op=PTRACE_SYSCALL_INFO_ENTRY};
  203. if (ptrace(PTRACE_GET_SYSCALL_INFO, c->pid, sizeof(ptsi), &ptsi) != -1)
  204. syscall = ptsi.entry.nr;
  205. #else
  206. int syscall = ptrace(PTRACE_PEEKUSER, c->pid, reg_syscall_nr);
  207. #endif
  208. int i = syscall_index(syscall);
  209. if (i >= 0) {
  210. syscall_count[i]++;
  211. if (debug)
  212. fprintf(stderr, "%s()\n", syscall_name(syscall));
  213. } else if (debug) {
  214. fprintf(stderr, "syscal(%d)\n", syscall);
  215. }
  216. }
  217. tracee->in_syscall = !tracee->in_syscall;
  218. } else if ((ret >> 8) == (SIGTRAP | (PTRACE_EVENT_FORK << 8)) ||
  219. (ret >> 8) == (SIGTRAP | (PTRACE_EVENT_VFORK << 8)) ||
  220. (ret >> 8) == (SIGTRAP | (PTRACE_EVENT_CLONE << 8))) {
  221. struct tracee *child = calloc(1, sizeof(struct tracee));
  222. unsigned long msg;
  223. ptrace(PTRACE_GETEVENTMSG, c->pid, 0, &msg);
  224. child->proc.pid = msg;
  225. child->proc.cb = tracer_cb;
  226. ptrace(ptrace_restart, child->proc.pid, 0, 0);
  227. uloop_process_add(&child->proc);
  228. if (debug)
  229. fprintf(stderr, "Tracing new child %d\n", child->proc.pid);
  230. } else if ((ret >> 16) == PTRACE_EVENT_STOP) {
  231. /* Nothing special to do here */
  232. } else if ((ret >> 8) == (SIGTRAP | (PTRACE_EVENT_SECCOMP << 8))) {
  233. #ifdef __aarch64__
  234. int syscall = -1;
  235. struct ptrace_syscall_info ptsi = {.op=PTRACE_SYSCALL_INFO_SECCOMP};
  236. if (ptrace(PTRACE_GET_SYSCALL_INFO, c->pid, sizeof(ptsi), &ptsi) != -1)
  237. syscall = ptsi.entry.nr;
  238. #else
  239. int syscall = ptrace(PTRACE_PEEKUSER, c->pid, reg_syscall_nr);
  240. #if defined(__arm__)
  241. ptrace(PTRACE_SET_SYSCALL, c->pid, 0, -1);
  242. ptrace(PTRACE_POKEUSER, c->pid, reg_retval_nr, -ENOSYS);
  243. #else
  244. ptrace(PTRACE_POKEUSER, c->pid, reg_syscall_nr, -1);
  245. #endif
  246. #endif
  247. report_seccomp_vialation(c->pid, syscall);
  248. } else {
  249. inject_signal = WSTOPSIG(ret);
  250. if (debug)
  251. fprintf(stderr, "Injecting signal %d into pid %d\n",
  252. inject_signal, tracee->proc.pid);
  253. }
  254. } else if (WIFEXITED(ret) || (WIFSIGNALED(ret) && WTERMSIG(ret))) {
  255. if (tracee == &tracer) {
  256. uloop_end(); /* Main process exit */
  257. } else {
  258. if (debug)
  259. fprintf(stderr, "Child %d exited\n", tracee->proc.pid);
  260. free(tracee);
  261. }
  262. return;
  263. }
  264. ptrace(ptrace_restart, c->pid, 0, inject_signal);
  265. uloop_process_add(c);
  266. }
  267. static void sigterm_handler(int signum)
  268. {
  269. /* When we receive SIGTERM, we forward it to the tracee. After
  270. * the tracee exits, trace_cb() will be called and make us
  271. * exit too. */
  272. kill(tracer.proc.pid, SIGTERM);
  273. }
  274. int main(int argc, char **argv, char **envp)
  275. {
  276. int status, ch, policy = EPERM;
  277. pid_t child;
  278. /* When invoked via seccomp-trace symlink, work as seccomp
  279. * violation logger rather than as syscall tracer */
  280. if (strstr(argv[0], "seccomp-trace"))
  281. mode = SECCOMP_TRACE;
  282. while ((ch = getopt(argc, argv, "f:p:")) != -1) {
  283. switch (ch) {
  284. case 'f':
  285. json = optarg;
  286. break;
  287. case 'p':
  288. policy = atoi(optarg);
  289. break;
  290. }
  291. }
  292. if (!json)
  293. json = getenv("SECCOMP_FILE");
  294. argc -= optind;
  295. argv += optind;
  296. if (!argc)
  297. return -1;
  298. if (getenv("TRACE_DEBUG"))
  299. debug = 1;
  300. unsetenv("TRACE_DEBUG");
  301. child = fork();
  302. if (child == 0) {
  303. char **_argv = calloc(argc + 1, sizeof(char *));
  304. char **_envp;
  305. char *preload = NULL;
  306. const char *old_preload = getenv("LD_PRELOAD");
  307. int newenv = 0;
  308. int envc = 0;
  309. int ret;
  310. memcpy(_argv, argv, argc * sizeof(char *));
  311. while (envp[envc++])
  312. ;
  313. _envp = calloc(envc + 2, sizeof(char *));
  314. switch (mode) {
  315. case UTRACE:
  316. preload = "/lib/libpreload-trace.so";
  317. newenv = 1;
  318. break;
  319. case SECCOMP_TRACE:
  320. preload = "/lib/libpreload-seccomp.so";
  321. newenv = 2;
  322. if (asprintf(&_envp[1], "SECCOMP_FILE=%s", json ? json : "") < 0)
  323. ULOG_ERR("failed to allocate SECCOMP_FILE env: %m\n");
  324. kill(getpid(), SIGSTOP);
  325. break;
  326. }
  327. if (asprintf(&_envp[0], "LD_PRELOAD=%s%s%s", preload,
  328. old_preload ? ":" : "",
  329. old_preload ? old_preload : "") < 0)
  330. ULOG_ERR("failed to allocate LD_PRELOAD env: %m\n");
  331. memcpy(&_envp[newenv], envp, envc * sizeof(char *));
  332. ret = execve(_argv[0], _argv, _envp);
  333. ULOG_ERR("failed to exec %s: %m\n", _argv[0]);
  334. free(_argv);
  335. if (_envp[0])
  336. free(_envp[0]);
  337. if (newenv == 2 && _envp[1])
  338. free(_envp[1]);
  339. free(_envp);
  340. return ret;
  341. }
  342. if (child < 0)
  343. return -1;
  344. waitpid(child, &status, WUNTRACED);
  345. if (!WIFSTOPPED(status)) {
  346. ULOG_ERR("failed to start %s\n", *argv);
  347. return -1;
  348. }
  349. /* Initialize uloop to catch all ptrace stops from now on. */
  350. uloop_init();
  351. int ptrace_options = PTRACE_O_TRACEFORK | PTRACE_O_TRACEVFORK | PTRACE_O_TRACECLONE;
  352. switch (mode) {
  353. case UTRACE:
  354. ptrace_options |= PTRACE_O_TRACESYSGOOD;
  355. ptrace_restart = PTRACE_SYSCALL;
  356. break;
  357. case SECCOMP_TRACE:
  358. ptrace_options |= PTRACE_O_TRACESECCOMP;
  359. ptrace_restart = PTRACE_CONT;
  360. break;
  361. }
  362. if (ptrace(PTRACE_SEIZE, child, 0, ptrace_options) == -1) {
  363. ULOG_ERR("PTRACE_SEIZE: %m\n");
  364. return -1;
  365. }
  366. if (ptrace(ptrace_restart, child, 0, SIGCONT) == -1) {
  367. ULOG_ERR("ptrace_restart: %m\n");
  368. return -1;
  369. }
  370. tracer.proc.pid = child;
  371. tracer.proc.cb = tracer_cb;
  372. uloop_process_add(&tracer.proc);
  373. signal(SIGTERM, sigterm_handler); /* Override uloop's SIGTERM handler */
  374. uloop_run();
  375. uloop_done();
  376. switch (mode) {
  377. case UTRACE:
  378. if (!json)
  379. if (asprintf(&json, "/tmp/%s.%u.json", basename(*argv), child) < 0)
  380. ULOG_ERR("failed to allocate output path: %m\n");
  381. break;
  382. case SECCOMP_TRACE:
  383. if (!violation_count)
  384. return 0;
  385. if (asprintf(&json, "/tmp/%s.%u.violations.json", basename(*argv), child) < 0)
  386. ULOG_ERR("failed to allocate violations output path: %m\n");
  387. break;
  388. }
  389. print_syscalls(policy, json);
  390. return 0;
  391. }