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