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