trace.c 11 KB

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