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