trace.c 9.5 KB

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