trace.c 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  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 <string.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. #ifdef __amd64__
  45. #define reg_syscall_nr _offsetof(struct user, regs.orig_rax)
  46. #elif defined(__i386__)
  47. #define reg_syscall_nr _offsetof(struct user, regs.orig_eax)
  48. #elif defined(__mips)
  49. # ifndef EF_REG2
  50. # define EF_REG2 8
  51. # endif
  52. #define reg_syscall_nr (EF_REG2 / 4)
  53. #elif defined(__arm__)
  54. #include <asm/ptrace.h> /* for PTRACE_SET_SYSCALL */
  55. #define reg_syscall_nr _offsetof(struct user, regs.uregs[7])
  56. # if defined(__ARM_EABI__)
  57. # define reg_retval_nr _offsetof(struct user, regs.uregs[0])
  58. # endif
  59. #elif defined(__PPC__)
  60. #define reg_syscall_nr _offsetof(struct user, regs.gpr[0])
  61. #define reg_retval_nr _offsetof(struct user, regs.gpr[3])
  62. #else
  63. #error tracing is not supported on this architecture
  64. #endif
  65. enum mode {
  66. UTRACE,
  67. SECCOMP_TRACE,
  68. } mode = UTRACE;
  69. struct tracee {
  70. struct uloop_process proc;
  71. int in_syscall;
  72. };
  73. static struct tracee tracer;
  74. static int syscall_count[SYSCALL_COUNT];
  75. static int violation_count;
  76. static struct blob_buf b;
  77. static int debug;
  78. char *json = NULL;
  79. int ptrace_restart;
  80. static void set_syscall(const char *name, int val)
  81. {
  82. int i;
  83. for (i = 0; i < SYSCALL_COUNT; i++) {
  84. int sc = syscall_index_to_number(i);
  85. if (syscall_name(sc) && !strcmp(syscall_name(sc), name)) {
  86. syscall_count[i] = val;
  87. return;
  88. }
  89. }
  90. }
  91. struct syscall {
  92. int syscall;
  93. int count;
  94. };
  95. static int cmp_count(const void *a, const void *b)
  96. {
  97. return ((struct syscall*)b)->count - ((struct syscall*)a)->count;
  98. }
  99. static void print_syscalls(int policy, const char *json)
  100. {
  101. void *c, *d, *e;
  102. int i;
  103. if (mode == UTRACE) {
  104. set_syscall("rt_sigaction", 1);
  105. set_syscall("sigreturn", 1);
  106. set_syscall("rt_sigreturn", 1);
  107. set_syscall("exit_group", 1);
  108. set_syscall("exit", 1);
  109. }
  110. struct syscall sorted[SYSCALL_COUNT];
  111. for (i = 0; i < SYSCALL_COUNT; i++) {
  112. sorted[i].syscall = syscall_index_to_number(i);
  113. sorted[i].count = syscall_count[i];
  114. }
  115. qsort(sorted, SYSCALL_COUNT, sizeof(sorted[0]), cmp_count);
  116. blob_buf_init(&b, 0);
  117. blobmsg_add_string(&b, "defaultAction", "SCMP_ACT_KILL_PROCESS");
  118. c = blobmsg_open_array(&b, "syscalls");
  119. d = blobmsg_open_table(&b, "");
  120. e = blobmsg_open_array(&b, "names");
  121. for (i = 0; i < SYSCALL_COUNT; i++) {
  122. int sc = sorted[i].syscall;
  123. if (!sorted[i].count)
  124. break;
  125. if (syscall_name(sc)) {
  126. if (debug)
  127. printf("syscall %d (%s) was called %d times\n",
  128. sc, syscall_name(sc), sorted[i].count);
  129. blobmsg_add_string(&b, NULL, syscall_name(sc));
  130. } else {
  131. ULOG_ERR("no name found for syscall(%d)\n", sc);
  132. }
  133. }
  134. blobmsg_close_array(&b, e);
  135. blobmsg_add_string(&b, "action", "SCMP_ACT_ALLOW");
  136. blobmsg_close_table(&b, d);
  137. blobmsg_close_array(&b, c);
  138. if (json) {
  139. FILE *fp = fopen(json, "w");
  140. if (fp) {
  141. fprintf(fp, "%s\n", blobmsg_format_json_indent(b.head, true, 0));
  142. fclose(fp);
  143. ULOG_INFO("saving syscall trace to %s\n", json);
  144. } else {
  145. ULOG_ERR("failed to open %s\n", json);
  146. }
  147. } else {
  148. printf("%s\n",
  149. blobmsg_format_json_indent(b.head, true, 0));
  150. }
  151. }
  152. static void report_seccomp_vialation(pid_t pid, unsigned syscall)
  153. {
  154. char buf[200];
  155. snprintf(buf, sizeof(buf), "/proc/%d/cmdline", pid);
  156. int f = open(buf, O_RDONLY);
  157. int r = read(f, buf, sizeof(buf) - 1);
  158. if (r >= 0)
  159. buf[r] = 0;
  160. else
  161. strcpy(buf, "unknown?");
  162. close(f);
  163. if (violation_count < INT_MAX)
  164. violation_count++;
  165. int i = syscall_index(syscall);
  166. if (i >= 0) {
  167. syscall_count[i]++;
  168. ULOG_ERR("%s[%u] tried to call non-whitelisted syscall: %s (see %s)\n",
  169. buf, pid, syscall_name(syscall), json);
  170. } else {
  171. ULOG_ERR("%s[%u] tried to call non-whitelisted syscall: %d (see %s)\n",
  172. buf, pid, syscall, json);
  173. }
  174. }
  175. static void tracer_cb(struct uloop_process *c, int ret)
  176. {
  177. struct tracee *tracee = container_of(c, struct tracee, proc);
  178. int inject_signal = 0;
  179. /* We explicitely check for events in upper 16 bits, because
  180. * musl (as opposed to glibc) does not report
  181. * PTRACE_EVENT_STOP as WIFSTOPPED */
  182. if (WIFSTOPPED(ret) || (ret >> 16)) {
  183. if (WSTOPSIG(ret) & 0x80) {
  184. if (!tracee->in_syscall) {
  185. int syscall = ptrace(PTRACE_PEEKUSER, c->pid, reg_syscall_nr);
  186. int i = syscall_index(syscall);
  187. if (i >= 0) {
  188. syscall_count[i]++;
  189. if (debug)
  190. fprintf(stderr, "%s()\n", syscall_name(syscall));
  191. } else if (debug) {
  192. fprintf(stderr, "syscal(%d)\n", syscall);
  193. }
  194. }
  195. tracee->in_syscall = !tracee->in_syscall;
  196. } else if ((ret >> 8) == (SIGTRAP | (PTRACE_EVENT_FORK << 8)) ||
  197. (ret >> 8) == (SIGTRAP | (PTRACE_EVENT_VFORK << 8)) ||
  198. (ret >> 8) == (SIGTRAP | (PTRACE_EVENT_CLONE << 8))) {
  199. struct tracee *child = calloc(1, sizeof(struct tracee));
  200. unsigned long msg;
  201. ptrace(PTRACE_GETEVENTMSG, c->pid, 0, &msg);
  202. child->proc.pid = msg;
  203. child->proc.cb = tracer_cb;
  204. ptrace(ptrace_restart, child->proc.pid, 0, 0);
  205. uloop_process_add(&child->proc);
  206. if (debug)
  207. fprintf(stderr, "Tracing new child %d\n", child->proc.pid);
  208. } else if ((ret >> 16) == PTRACE_EVENT_STOP) {
  209. /* Nothing special to do here */
  210. } else if ((ret >> 8) == (SIGTRAP | (PTRACE_EVENT_SECCOMP << 8))) {
  211. int syscall = ptrace(PTRACE_PEEKUSER, c->pid, reg_syscall_nr);
  212. #if defined(__arm__)
  213. ptrace(PTRACE_SET_SYSCALL, c->pid, 0, -1);
  214. ptrace(PTRACE_POKEUSER, c->pid, reg_retval_nr, -ENOSYS);
  215. #else
  216. ptrace(PTRACE_POKEUSER, c->pid, reg_syscall_nr, -1);
  217. #endif
  218. report_seccomp_vialation(c->pid, syscall);
  219. } else {
  220. inject_signal = WSTOPSIG(ret);
  221. if (debug)
  222. fprintf(stderr, "Injecting signal %d into pid %d\n",
  223. inject_signal, tracee->proc.pid);
  224. }
  225. } else if (WIFEXITED(ret) || (WIFSIGNALED(ret) && WTERMSIG(ret))) {
  226. if (tracee == &tracer) {
  227. uloop_end(); /* Main process exit */
  228. } else {
  229. if (debug)
  230. fprintf(stderr, "Child %d exited\n", tracee->proc.pid);
  231. free(tracee);
  232. }
  233. return;
  234. }
  235. ptrace(ptrace_restart, c->pid, 0, inject_signal);
  236. uloop_process_add(c);
  237. }
  238. static void sigterm_handler(int signum)
  239. {
  240. /* When we receive SIGTERM, we forward it to the tracee. After
  241. * the tracee exits, trace_cb() will be called and make us
  242. * exit too. */
  243. kill(tracer.proc.pid, SIGTERM);
  244. }
  245. int main(int argc, char **argv, char **envp)
  246. {
  247. int status, ch, policy = EPERM;
  248. pid_t child;
  249. /* When invoked via seccomp-trace symlink, work as seccomp
  250. * violation logger rather than as syscall tracer */
  251. if (strstr(argv[0], "seccomp-trace"))
  252. mode = SECCOMP_TRACE;
  253. while ((ch = getopt(argc, argv, "f:p:")) != -1) {
  254. switch (ch) {
  255. case 'f':
  256. json = optarg;
  257. break;
  258. case 'p':
  259. policy = atoi(optarg);
  260. break;
  261. }
  262. }
  263. if (!json)
  264. json = getenv("SECCOMP_FILE");
  265. argc -= optind;
  266. argv += optind;
  267. if (!argc)
  268. return -1;
  269. if (getenv("TRACE_DEBUG"))
  270. debug = 1;
  271. unsetenv("TRACE_DEBUG");
  272. child = fork();
  273. if (child == 0) {
  274. char **_argv = calloc(argc + 1, sizeof(char *));
  275. char **_envp;
  276. char *preload = NULL;
  277. const char *old_preload = getenv("LD_PRELOAD");
  278. int newenv = 0;
  279. int envc = 0;
  280. int ret;
  281. memcpy(_argv, argv, argc * sizeof(char *));
  282. while (envp[envc++])
  283. ;
  284. _envp = calloc(envc + 2, sizeof(char *));
  285. switch (mode) {
  286. case UTRACE:
  287. preload = "/lib/libpreload-trace.so";
  288. newenv = 1;
  289. break;
  290. case SECCOMP_TRACE:
  291. preload = "/lib/libpreload-seccomp.so";
  292. newenv = 2;
  293. if (asprintf(&_envp[1], "SECCOMP_FILE=%s", json ? json : "") < 0)
  294. ULOG_ERR("failed to allocate SECCOMP_FILE env: %m\n");
  295. kill(getpid(), SIGSTOP);
  296. break;
  297. }
  298. if (asprintf(&_envp[0], "LD_PRELOAD=%s%s%s", preload,
  299. old_preload ? ":" : "",
  300. old_preload ? old_preload : "") < 0)
  301. ULOG_ERR("failed to allocate LD_PRELOAD env: %m\n");
  302. memcpy(&_envp[newenv], envp, envc * sizeof(char *));
  303. ret = execve(_argv[0], _argv, _envp);
  304. ULOG_ERR("failed to exec %s: %m\n", _argv[0]);
  305. free(_argv);
  306. free(_envp);
  307. return ret;
  308. }
  309. if (child < 0)
  310. return -1;
  311. waitpid(child, &status, WUNTRACED);
  312. if (!WIFSTOPPED(status)) {
  313. ULOG_ERR("failed to start %s\n", *argv);
  314. return -1;
  315. }
  316. /* Initialize uloop to catch all ptrace stops from now on. */
  317. uloop_init();
  318. int ptrace_options = PTRACE_O_TRACEFORK | PTRACE_O_TRACEVFORK | PTRACE_O_TRACECLONE;
  319. switch (mode) {
  320. case UTRACE:
  321. ptrace_options |= PTRACE_O_TRACESYSGOOD;
  322. ptrace_restart = PTRACE_SYSCALL;
  323. break;
  324. case SECCOMP_TRACE:
  325. ptrace_options |= PTRACE_O_TRACESECCOMP;
  326. ptrace_restart = PTRACE_CONT;
  327. break;
  328. }
  329. if (ptrace(PTRACE_SEIZE, child, 0, ptrace_options) == -1) {
  330. ULOG_ERR("PTRACE_SEIZE: %m\n");
  331. return -1;
  332. }
  333. if (ptrace(ptrace_restart, child, 0, SIGCONT) == -1) {
  334. ULOG_ERR("ptrace_restart: %m\n");
  335. return -1;
  336. }
  337. tracer.proc.pid = child;
  338. tracer.proc.cb = tracer_cb;
  339. uloop_process_add(&tracer.proc);
  340. signal(SIGTERM, sigterm_handler); /* Override uloop's SIGTERM handler */
  341. uloop_run();
  342. uloop_done();
  343. switch (mode) {
  344. case UTRACE:
  345. if (!json)
  346. if (asprintf(&json, "/tmp/%s.%u.json", basename(*argv), child) < 0)
  347. ULOG_ERR("failed to allocate output path: %m\n");
  348. break;
  349. case SECCOMP_TRACE:
  350. if (!violation_count)
  351. return 0;
  352. if (asprintf(&json, "/tmp/%s.%u.violations.json", basename(*argv), child) < 0)
  353. ULOG_ERR("failed to allocate violations output path: %m\n");
  354. break;
  355. }
  356. print_syscalls(policy, json);
  357. return 0;
  358. }