xref: /linux/tools/testing/selftests/seccomp/seccomp_bpf.c (revision 4fd18fc38757217c746aa063ba9e4729814dc737)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
4  *
5  * Test code for seccomp bpf.
6  */
7 
8 #define _GNU_SOURCE
9 #include <sys/types.h>
10 
11 /*
12  * glibc 2.26 and later have SIGSYS in siginfo_t. Before that,
13  * we need to use the kernel's siginfo.h file and trick glibc
14  * into accepting it.
15  */
16 #if !__GLIBC_PREREQ(2, 26)
17 # include <asm/siginfo.h>
18 # define __have_siginfo_t 1
19 # define __have_sigval_t 1
20 # define __have_sigevent_t 1
21 #endif
22 
23 #include <errno.h>
24 #include <linux/filter.h>
25 #include <sys/prctl.h>
26 #include <sys/ptrace.h>
27 #include <sys/user.h>
28 #include <linux/prctl.h>
29 #include <linux/ptrace.h>
30 #include <linux/seccomp.h>
31 #include <pthread.h>
32 #include <semaphore.h>
33 #include <signal.h>
34 #include <stddef.h>
35 #include <stdbool.h>
36 #include <string.h>
37 #include <time.h>
38 #include <limits.h>
39 #include <linux/elf.h>
40 #include <sys/uio.h>
41 #include <sys/utsname.h>
42 #include <sys/fcntl.h>
43 #include <sys/mman.h>
44 #include <sys/times.h>
45 #include <sys/socket.h>
46 #include <sys/ioctl.h>
47 #include <linux/kcmp.h>
48 #include <sys/resource.h>
49 
50 #include <unistd.h>
51 #include <sys/syscall.h>
52 #include <poll.h>
53 
54 #include "../kselftest_harness.h"
55 #include "../clone3/clone3_selftests.h"
56 
57 /* Attempt to de-conflict with the selftests tree. */
58 #ifndef SKIP
59 #define SKIP(s, ...)	XFAIL(s, ##__VA_ARGS__)
60 #endif
61 
62 #ifndef PR_SET_PTRACER
63 # define PR_SET_PTRACER 0x59616d61
64 #endif
65 
66 #ifndef PR_SET_NO_NEW_PRIVS
67 #define PR_SET_NO_NEW_PRIVS 38
68 #define PR_GET_NO_NEW_PRIVS 39
69 #endif
70 
71 #ifndef PR_SECCOMP_EXT
72 #define PR_SECCOMP_EXT 43
73 #endif
74 
75 #ifndef SECCOMP_EXT_ACT
76 #define SECCOMP_EXT_ACT 1
77 #endif
78 
79 #ifndef SECCOMP_EXT_ACT_TSYNC
80 #define SECCOMP_EXT_ACT_TSYNC 1
81 #endif
82 
83 #ifndef SECCOMP_MODE_STRICT
84 #define SECCOMP_MODE_STRICT 1
85 #endif
86 
87 #ifndef SECCOMP_MODE_FILTER
88 #define SECCOMP_MODE_FILTER 2
89 #endif
90 
91 #ifndef SECCOMP_RET_ALLOW
92 struct seccomp_data {
93 	int nr;
94 	__u32 arch;
95 	__u64 instruction_pointer;
96 	__u64 args[6];
97 };
98 #endif
99 
100 #ifndef SECCOMP_RET_KILL_PROCESS
101 #define SECCOMP_RET_KILL_PROCESS 0x80000000U /* kill the process */
102 #define SECCOMP_RET_KILL_THREAD	 0x00000000U /* kill the thread */
103 #endif
104 #ifndef SECCOMP_RET_KILL
105 #define SECCOMP_RET_KILL	 SECCOMP_RET_KILL_THREAD
106 #define SECCOMP_RET_TRAP	 0x00030000U /* disallow and force a SIGSYS */
107 #define SECCOMP_RET_ERRNO	 0x00050000U /* returns an errno */
108 #define SECCOMP_RET_TRACE	 0x7ff00000U /* pass to a tracer or disallow */
109 #define SECCOMP_RET_ALLOW	 0x7fff0000U /* allow */
110 #endif
111 #ifndef SECCOMP_RET_LOG
112 #define SECCOMP_RET_LOG		 0x7ffc0000U /* allow after logging */
113 #endif
114 
115 #ifndef __NR_seccomp
116 # if defined(__i386__)
117 #  define __NR_seccomp 354
118 # elif defined(__x86_64__)
119 #  define __NR_seccomp 317
120 # elif defined(__arm__)
121 #  define __NR_seccomp 383
122 # elif defined(__aarch64__)
123 #  define __NR_seccomp 277
124 # elif defined(__riscv)
125 #  define __NR_seccomp 277
126 # elif defined(__csky__)
127 #  define __NR_seccomp 277
128 # elif defined(__hppa__)
129 #  define __NR_seccomp 338
130 # elif defined(__powerpc__)
131 #  define __NR_seccomp 358
132 # elif defined(__s390__)
133 #  define __NR_seccomp 348
134 # elif defined(__xtensa__)
135 #  define __NR_seccomp 337
136 # elif defined(__sh__)
137 #  define __NR_seccomp 372
138 # else
139 #  warning "seccomp syscall number unknown for this architecture"
140 #  define __NR_seccomp 0xffff
141 # endif
142 #endif
143 
144 #ifndef SECCOMP_SET_MODE_STRICT
145 #define SECCOMP_SET_MODE_STRICT 0
146 #endif
147 
148 #ifndef SECCOMP_SET_MODE_FILTER
149 #define SECCOMP_SET_MODE_FILTER 1
150 #endif
151 
152 #ifndef SECCOMP_GET_ACTION_AVAIL
153 #define SECCOMP_GET_ACTION_AVAIL 2
154 #endif
155 
156 #ifndef SECCOMP_GET_NOTIF_SIZES
157 #define SECCOMP_GET_NOTIF_SIZES 3
158 #endif
159 
160 #ifndef SECCOMP_FILTER_FLAG_TSYNC
161 #define SECCOMP_FILTER_FLAG_TSYNC (1UL << 0)
162 #endif
163 
164 #ifndef SECCOMP_FILTER_FLAG_LOG
165 #define SECCOMP_FILTER_FLAG_LOG (1UL << 1)
166 #endif
167 
168 #ifndef SECCOMP_FILTER_FLAG_SPEC_ALLOW
169 #define SECCOMP_FILTER_FLAG_SPEC_ALLOW (1UL << 2)
170 #endif
171 
172 #ifndef PTRACE_SECCOMP_GET_METADATA
173 #define PTRACE_SECCOMP_GET_METADATA	0x420d
174 
175 struct seccomp_metadata {
176 	__u64 filter_off;       /* Input: which filter */
177 	__u64 flags;             /* Output: filter's flags */
178 };
179 #endif
180 
181 #ifndef SECCOMP_FILTER_FLAG_NEW_LISTENER
182 #define SECCOMP_FILTER_FLAG_NEW_LISTENER	(1UL << 3)
183 #endif
184 
185 #ifndef SECCOMP_RET_USER_NOTIF
186 #define SECCOMP_RET_USER_NOTIF 0x7fc00000U
187 
188 #define SECCOMP_IOC_MAGIC		'!'
189 #define SECCOMP_IO(nr)			_IO(SECCOMP_IOC_MAGIC, nr)
190 #define SECCOMP_IOR(nr, type)		_IOR(SECCOMP_IOC_MAGIC, nr, type)
191 #define SECCOMP_IOW(nr, type)		_IOW(SECCOMP_IOC_MAGIC, nr, type)
192 #define SECCOMP_IOWR(nr, type)		_IOWR(SECCOMP_IOC_MAGIC, nr, type)
193 
194 /* Flags for seccomp notification fd ioctl. */
195 #define SECCOMP_IOCTL_NOTIF_RECV	SECCOMP_IOWR(0, struct seccomp_notif)
196 #define SECCOMP_IOCTL_NOTIF_SEND	SECCOMP_IOWR(1,	\
197 						struct seccomp_notif_resp)
198 #define SECCOMP_IOCTL_NOTIF_ID_VALID	SECCOMP_IOW(2, __u64)
199 
200 struct seccomp_notif {
201 	__u64 id;
202 	__u32 pid;
203 	__u32 flags;
204 	struct seccomp_data data;
205 };
206 
207 struct seccomp_notif_resp {
208 	__u64 id;
209 	__s64 val;
210 	__s32 error;
211 	__u32 flags;
212 };
213 
214 struct seccomp_notif_sizes {
215 	__u16 seccomp_notif;
216 	__u16 seccomp_notif_resp;
217 	__u16 seccomp_data;
218 };
219 #endif
220 
221 #ifndef SECCOMP_IOCTL_NOTIF_ADDFD
222 /* On success, the return value is the remote process's added fd number */
223 #define SECCOMP_IOCTL_NOTIF_ADDFD	SECCOMP_IOW(3,	\
224 						struct seccomp_notif_addfd)
225 
226 /* valid flags for seccomp_notif_addfd */
227 #define SECCOMP_ADDFD_FLAG_SETFD	(1UL << 0) /* Specify remote fd */
228 
229 struct seccomp_notif_addfd {
230 	__u64 id;
231 	__u32 flags;
232 	__u32 srcfd;
233 	__u32 newfd;
234 	__u32 newfd_flags;
235 };
236 #endif
237 
238 struct seccomp_notif_addfd_small {
239 	__u64 id;
240 	char weird[4];
241 };
242 #define SECCOMP_IOCTL_NOTIF_ADDFD_SMALL	\
243 	SECCOMP_IOW(3, struct seccomp_notif_addfd_small)
244 
245 struct seccomp_notif_addfd_big {
246 	union {
247 		struct seccomp_notif_addfd addfd;
248 		char buf[sizeof(struct seccomp_notif_addfd) + 8];
249 	};
250 };
251 #define SECCOMP_IOCTL_NOTIF_ADDFD_BIG	\
252 	SECCOMP_IOWR(3, struct seccomp_notif_addfd_big)
253 
254 #ifndef PTRACE_EVENTMSG_SYSCALL_ENTRY
255 #define PTRACE_EVENTMSG_SYSCALL_ENTRY	1
256 #define PTRACE_EVENTMSG_SYSCALL_EXIT	2
257 #endif
258 
259 #ifndef SECCOMP_USER_NOTIF_FLAG_CONTINUE
260 #define SECCOMP_USER_NOTIF_FLAG_CONTINUE 0x00000001
261 #endif
262 
263 #ifndef SECCOMP_FILTER_FLAG_TSYNC_ESRCH
264 #define SECCOMP_FILTER_FLAG_TSYNC_ESRCH (1UL << 4)
265 #endif
266 
267 #ifndef seccomp
268 int seccomp(unsigned int op, unsigned int flags, void *args)
269 {
270 	errno = 0;
271 	return syscall(__NR_seccomp, op, flags, args);
272 }
273 #endif
274 
275 #if __BYTE_ORDER == __LITTLE_ENDIAN
276 #define syscall_arg(_n) (offsetof(struct seccomp_data, args[_n]))
277 #elif __BYTE_ORDER == __BIG_ENDIAN
278 #define syscall_arg(_n) (offsetof(struct seccomp_data, args[_n]) + sizeof(__u32))
279 #else
280 #error "wut? Unknown __BYTE_ORDER?!"
281 #endif
282 
283 #define SIBLING_EXIT_UNKILLED	0xbadbeef
284 #define SIBLING_EXIT_FAILURE	0xbadface
285 #define SIBLING_EXIT_NEWPRIVS	0xbadfeed
286 
287 static int __filecmp(pid_t pid1, pid_t pid2, int fd1, int fd2)
288 {
289 #ifdef __NR_kcmp
290 	errno = 0;
291 	return syscall(__NR_kcmp, pid1, pid2, KCMP_FILE, fd1, fd2);
292 #else
293 	errno = ENOSYS;
294 	return -1;
295 #endif
296 }
297 
298 /* Have TH_LOG report actual location filecmp() is used. */
299 #define filecmp(pid1, pid2, fd1, fd2)	({		\
300 	int _ret;					\
301 							\
302 	_ret = __filecmp(pid1, pid2, fd1, fd2);		\
303 	if (_ret != 0) {				\
304 		if (_ret < 0 && errno == ENOSYS) {	\
305 			TH_LOG("kcmp() syscall missing (test is less accurate)");\
306 			_ret = 0;			\
307 		}					\
308 	}						\
309 	_ret; })
310 
311 TEST(kcmp)
312 {
313 	int ret;
314 
315 	ret = __filecmp(getpid(), getpid(), 1, 1);
316 	EXPECT_EQ(ret, 0);
317 	if (ret != 0 && errno == ENOSYS)
318 		SKIP(return, "Kernel does not support kcmp() (missing CONFIG_CHECKPOINT_RESTORE?)");
319 }
320 
321 TEST(mode_strict_support)
322 {
323 	long ret;
324 
325 	ret = prctl(PR_SET_SECCOMP, SECCOMP_MODE_STRICT, NULL, NULL, NULL);
326 	ASSERT_EQ(0, ret) {
327 		TH_LOG("Kernel does not support CONFIG_SECCOMP");
328 	}
329 	syscall(__NR_exit, 0);
330 }
331 
332 TEST_SIGNAL(mode_strict_cannot_call_prctl, SIGKILL)
333 {
334 	long ret;
335 
336 	ret = prctl(PR_SET_SECCOMP, SECCOMP_MODE_STRICT, NULL, NULL, NULL);
337 	ASSERT_EQ(0, ret) {
338 		TH_LOG("Kernel does not support CONFIG_SECCOMP");
339 	}
340 	syscall(__NR_prctl, PR_SET_SECCOMP, SECCOMP_MODE_FILTER,
341 		NULL, NULL, NULL);
342 	EXPECT_FALSE(true) {
343 		TH_LOG("Unreachable!");
344 	}
345 }
346 
347 /* Note! This doesn't test no new privs behavior */
348 TEST(no_new_privs_support)
349 {
350 	long ret;
351 
352 	ret = prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
353 	EXPECT_EQ(0, ret) {
354 		TH_LOG("Kernel does not support PR_SET_NO_NEW_PRIVS!");
355 	}
356 }
357 
358 /* Tests kernel support by checking for a copy_from_user() fault on NULL. */
359 TEST(mode_filter_support)
360 {
361 	long ret;
362 
363 	ret = prctl(PR_SET_NO_NEW_PRIVS, 1, NULL, 0, 0);
364 	ASSERT_EQ(0, ret) {
365 		TH_LOG("Kernel does not support PR_SET_NO_NEW_PRIVS!");
366 	}
367 	ret = prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, NULL, NULL, NULL);
368 	EXPECT_EQ(-1, ret);
369 	EXPECT_EQ(EFAULT, errno) {
370 		TH_LOG("Kernel does not support CONFIG_SECCOMP_FILTER!");
371 	}
372 }
373 
374 TEST(mode_filter_without_nnp)
375 {
376 	struct sock_filter filter[] = {
377 		BPF_STMT(BPF_RET|BPF_K, SECCOMP_RET_ALLOW),
378 	};
379 	struct sock_fprog prog = {
380 		.len = (unsigned short)ARRAY_SIZE(filter),
381 		.filter = filter,
382 	};
383 	long ret;
384 
385 	ret = prctl(PR_GET_NO_NEW_PRIVS, 0, NULL, 0, 0);
386 	ASSERT_LE(0, ret) {
387 		TH_LOG("Expected 0 or unsupported for NO_NEW_PRIVS");
388 	}
389 	errno = 0;
390 	ret = prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &prog, 0, 0);
391 	/* Succeeds with CAP_SYS_ADMIN, fails without */
392 	/* TODO(wad) check caps not euid */
393 	if (geteuid()) {
394 		EXPECT_EQ(-1, ret);
395 		EXPECT_EQ(EACCES, errno);
396 	} else {
397 		EXPECT_EQ(0, ret);
398 	}
399 }
400 
401 #define MAX_INSNS_PER_PATH 32768
402 
403 TEST(filter_size_limits)
404 {
405 	int i;
406 	int count = BPF_MAXINSNS + 1;
407 	struct sock_filter allow[] = {
408 		BPF_STMT(BPF_RET|BPF_K, SECCOMP_RET_ALLOW),
409 	};
410 	struct sock_filter *filter;
411 	struct sock_fprog prog = { };
412 	long ret;
413 
414 	filter = calloc(count, sizeof(*filter));
415 	ASSERT_NE(NULL, filter);
416 
417 	for (i = 0; i < count; i++)
418 		filter[i] = allow[0];
419 
420 	ret = prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
421 	ASSERT_EQ(0, ret);
422 
423 	prog.filter = filter;
424 	prog.len = count;
425 
426 	/* Too many filter instructions in a single filter. */
427 	ret = prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &prog, 0, 0);
428 	ASSERT_NE(0, ret) {
429 		TH_LOG("Installing %d insn filter was allowed", prog.len);
430 	}
431 
432 	/* One less is okay, though. */
433 	prog.len -= 1;
434 	ret = prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &prog, 0, 0);
435 	ASSERT_EQ(0, ret) {
436 		TH_LOG("Installing %d insn filter wasn't allowed", prog.len);
437 	}
438 }
439 
440 TEST(filter_chain_limits)
441 {
442 	int i;
443 	int count = BPF_MAXINSNS;
444 	struct sock_filter allow[] = {
445 		BPF_STMT(BPF_RET|BPF_K, SECCOMP_RET_ALLOW),
446 	};
447 	struct sock_filter *filter;
448 	struct sock_fprog prog = { };
449 	long ret;
450 
451 	filter = calloc(count, sizeof(*filter));
452 	ASSERT_NE(NULL, filter);
453 
454 	for (i = 0; i < count; i++)
455 		filter[i] = allow[0];
456 
457 	ret = prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
458 	ASSERT_EQ(0, ret);
459 
460 	prog.filter = filter;
461 	prog.len = 1;
462 
463 	ret = prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &prog, 0, 0);
464 	ASSERT_EQ(0, ret);
465 
466 	prog.len = count;
467 
468 	/* Too many total filter instructions. */
469 	for (i = 0; i < MAX_INSNS_PER_PATH; i++) {
470 		ret = prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &prog, 0, 0);
471 		if (ret != 0)
472 			break;
473 	}
474 	ASSERT_NE(0, ret) {
475 		TH_LOG("Allowed %d %d-insn filters (total with penalties:%d)",
476 		       i, count, i * (count + 4));
477 	}
478 }
479 
480 TEST(mode_filter_cannot_move_to_strict)
481 {
482 	struct sock_filter filter[] = {
483 		BPF_STMT(BPF_RET|BPF_K, SECCOMP_RET_ALLOW),
484 	};
485 	struct sock_fprog prog = {
486 		.len = (unsigned short)ARRAY_SIZE(filter),
487 		.filter = filter,
488 	};
489 	long ret;
490 
491 	ret = prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
492 	ASSERT_EQ(0, ret);
493 
494 	ret = prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &prog, 0, 0);
495 	ASSERT_EQ(0, ret);
496 
497 	ret = prctl(PR_SET_SECCOMP, SECCOMP_MODE_STRICT, NULL, 0, 0);
498 	EXPECT_EQ(-1, ret);
499 	EXPECT_EQ(EINVAL, errno);
500 }
501 
502 
503 TEST(mode_filter_get_seccomp)
504 {
505 	struct sock_filter filter[] = {
506 		BPF_STMT(BPF_RET|BPF_K, SECCOMP_RET_ALLOW),
507 	};
508 	struct sock_fprog prog = {
509 		.len = (unsigned short)ARRAY_SIZE(filter),
510 		.filter = filter,
511 	};
512 	long ret;
513 
514 	ret = prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
515 	ASSERT_EQ(0, ret);
516 
517 	ret = prctl(PR_GET_SECCOMP, 0, 0, 0, 0);
518 	EXPECT_EQ(0, ret);
519 
520 	ret = prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &prog, 0, 0);
521 	ASSERT_EQ(0, ret);
522 
523 	ret = prctl(PR_GET_SECCOMP, 0, 0, 0, 0);
524 	EXPECT_EQ(2, ret);
525 }
526 
527 
528 TEST(ALLOW_all)
529 {
530 	struct sock_filter filter[] = {
531 		BPF_STMT(BPF_RET|BPF_K, SECCOMP_RET_ALLOW),
532 	};
533 	struct sock_fprog prog = {
534 		.len = (unsigned short)ARRAY_SIZE(filter),
535 		.filter = filter,
536 	};
537 	long ret;
538 
539 	ret = prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
540 	ASSERT_EQ(0, ret);
541 
542 	ret = prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &prog);
543 	ASSERT_EQ(0, ret);
544 }
545 
546 TEST(empty_prog)
547 {
548 	struct sock_filter filter[] = {
549 	};
550 	struct sock_fprog prog = {
551 		.len = (unsigned short)ARRAY_SIZE(filter),
552 		.filter = filter,
553 	};
554 	long ret;
555 
556 	ret = prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
557 	ASSERT_EQ(0, ret);
558 
559 	ret = prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &prog);
560 	EXPECT_EQ(-1, ret);
561 	EXPECT_EQ(EINVAL, errno);
562 }
563 
564 TEST(log_all)
565 {
566 	struct sock_filter filter[] = {
567 		BPF_STMT(BPF_RET|BPF_K, SECCOMP_RET_LOG),
568 	};
569 	struct sock_fprog prog = {
570 		.len = (unsigned short)ARRAY_SIZE(filter),
571 		.filter = filter,
572 	};
573 	long ret;
574 	pid_t parent = getppid();
575 
576 	ret = prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
577 	ASSERT_EQ(0, ret);
578 
579 	ret = prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &prog);
580 	ASSERT_EQ(0, ret);
581 
582 	/* getppid() should succeed and be logged (no check for logging) */
583 	EXPECT_EQ(parent, syscall(__NR_getppid));
584 }
585 
586 TEST_SIGNAL(unknown_ret_is_kill_inside, SIGSYS)
587 {
588 	struct sock_filter filter[] = {
589 		BPF_STMT(BPF_RET|BPF_K, 0x10000000U),
590 	};
591 	struct sock_fprog prog = {
592 		.len = (unsigned short)ARRAY_SIZE(filter),
593 		.filter = filter,
594 	};
595 	long ret;
596 
597 	ret = prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
598 	ASSERT_EQ(0, ret);
599 
600 	ret = prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &prog);
601 	ASSERT_EQ(0, ret);
602 	EXPECT_EQ(0, syscall(__NR_getpid)) {
603 		TH_LOG("getpid() shouldn't ever return");
604 	}
605 }
606 
607 /* return code >= 0x80000000 is unused. */
608 TEST_SIGNAL(unknown_ret_is_kill_above_allow, SIGSYS)
609 {
610 	struct sock_filter filter[] = {
611 		BPF_STMT(BPF_RET|BPF_K, 0x90000000U),
612 	};
613 	struct sock_fprog prog = {
614 		.len = (unsigned short)ARRAY_SIZE(filter),
615 		.filter = filter,
616 	};
617 	long ret;
618 
619 	ret = prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
620 	ASSERT_EQ(0, ret);
621 
622 	ret = prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &prog);
623 	ASSERT_EQ(0, ret);
624 	EXPECT_EQ(0, syscall(__NR_getpid)) {
625 		TH_LOG("getpid() shouldn't ever return");
626 	}
627 }
628 
629 TEST_SIGNAL(KILL_all, SIGSYS)
630 {
631 	struct sock_filter filter[] = {
632 		BPF_STMT(BPF_RET|BPF_K, SECCOMP_RET_KILL),
633 	};
634 	struct sock_fprog prog = {
635 		.len = (unsigned short)ARRAY_SIZE(filter),
636 		.filter = filter,
637 	};
638 	long ret;
639 
640 	ret = prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
641 	ASSERT_EQ(0, ret);
642 
643 	ret = prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &prog);
644 	ASSERT_EQ(0, ret);
645 }
646 
647 TEST_SIGNAL(KILL_one, SIGSYS)
648 {
649 	struct sock_filter filter[] = {
650 		BPF_STMT(BPF_LD|BPF_W|BPF_ABS,
651 			offsetof(struct seccomp_data, nr)),
652 		BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, __NR_getpid, 0, 1),
653 		BPF_STMT(BPF_RET|BPF_K, SECCOMP_RET_KILL),
654 		BPF_STMT(BPF_RET|BPF_K, SECCOMP_RET_ALLOW),
655 	};
656 	struct sock_fprog prog = {
657 		.len = (unsigned short)ARRAY_SIZE(filter),
658 		.filter = filter,
659 	};
660 	long ret;
661 	pid_t parent = getppid();
662 
663 	ret = prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
664 	ASSERT_EQ(0, ret);
665 
666 	ret = prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &prog);
667 	ASSERT_EQ(0, ret);
668 
669 	EXPECT_EQ(parent, syscall(__NR_getppid));
670 	/* getpid() should never return. */
671 	EXPECT_EQ(0, syscall(__NR_getpid));
672 }
673 
674 TEST_SIGNAL(KILL_one_arg_one, SIGSYS)
675 {
676 	void *fatal_address;
677 	struct sock_filter filter[] = {
678 		BPF_STMT(BPF_LD|BPF_W|BPF_ABS,
679 			offsetof(struct seccomp_data, nr)),
680 		BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, __NR_times, 1, 0),
681 		BPF_STMT(BPF_RET|BPF_K, SECCOMP_RET_ALLOW),
682 		/* Only both with lower 32-bit for now. */
683 		BPF_STMT(BPF_LD|BPF_W|BPF_ABS, syscall_arg(0)),
684 		BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K,
685 			(unsigned long)&fatal_address, 0, 1),
686 		BPF_STMT(BPF_RET|BPF_K, SECCOMP_RET_KILL),
687 		BPF_STMT(BPF_RET|BPF_K, SECCOMP_RET_ALLOW),
688 	};
689 	struct sock_fprog prog = {
690 		.len = (unsigned short)ARRAY_SIZE(filter),
691 		.filter = filter,
692 	};
693 	long ret;
694 	pid_t parent = getppid();
695 	struct tms timebuf;
696 	clock_t clock = times(&timebuf);
697 
698 	ret = prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
699 	ASSERT_EQ(0, ret);
700 
701 	ret = prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &prog);
702 	ASSERT_EQ(0, ret);
703 
704 	EXPECT_EQ(parent, syscall(__NR_getppid));
705 	EXPECT_LE(clock, syscall(__NR_times, &timebuf));
706 	/* times() should never return. */
707 	EXPECT_EQ(0, syscall(__NR_times, &fatal_address));
708 }
709 
710 TEST_SIGNAL(KILL_one_arg_six, SIGSYS)
711 {
712 #ifndef __NR_mmap2
713 	int sysno = __NR_mmap;
714 #else
715 	int sysno = __NR_mmap2;
716 #endif
717 	struct sock_filter filter[] = {
718 		BPF_STMT(BPF_LD|BPF_W|BPF_ABS,
719 			offsetof(struct seccomp_data, nr)),
720 		BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, sysno, 1, 0),
721 		BPF_STMT(BPF_RET|BPF_K, SECCOMP_RET_ALLOW),
722 		/* Only both with lower 32-bit for now. */
723 		BPF_STMT(BPF_LD|BPF_W|BPF_ABS, syscall_arg(5)),
724 		BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, 0x0C0FFEE, 0, 1),
725 		BPF_STMT(BPF_RET|BPF_K, SECCOMP_RET_KILL),
726 		BPF_STMT(BPF_RET|BPF_K, SECCOMP_RET_ALLOW),
727 	};
728 	struct sock_fprog prog = {
729 		.len = (unsigned short)ARRAY_SIZE(filter),
730 		.filter = filter,
731 	};
732 	long ret;
733 	pid_t parent = getppid();
734 	int fd;
735 	void *map1, *map2;
736 	int page_size = sysconf(_SC_PAGESIZE);
737 
738 	ASSERT_LT(0, page_size);
739 
740 	ret = prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
741 	ASSERT_EQ(0, ret);
742 
743 	ret = prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &prog);
744 	ASSERT_EQ(0, ret);
745 
746 	fd = open("/dev/zero", O_RDONLY);
747 	ASSERT_NE(-1, fd);
748 
749 	EXPECT_EQ(parent, syscall(__NR_getppid));
750 	map1 = (void *)syscall(sysno,
751 		NULL, page_size, PROT_READ, MAP_PRIVATE, fd, page_size);
752 	EXPECT_NE(MAP_FAILED, map1);
753 	/* mmap2() should never return. */
754 	map2 = (void *)syscall(sysno,
755 		 NULL, page_size, PROT_READ, MAP_PRIVATE, fd, 0x0C0FFEE);
756 	EXPECT_EQ(MAP_FAILED, map2);
757 
758 	/* The test failed, so clean up the resources. */
759 	munmap(map1, page_size);
760 	munmap(map2, page_size);
761 	close(fd);
762 }
763 
764 /* This is a thread task to die via seccomp filter violation. */
765 void *kill_thread(void *data)
766 {
767 	bool die = (bool)data;
768 
769 	if (die) {
770 		prctl(PR_GET_SECCOMP, 0, 0, 0, 0);
771 		return (void *)SIBLING_EXIT_FAILURE;
772 	}
773 
774 	return (void *)SIBLING_EXIT_UNKILLED;
775 }
776 
777 enum kill_t {
778 	KILL_THREAD,
779 	KILL_PROCESS,
780 	RET_UNKNOWN
781 };
782 
783 /* Prepare a thread that will kill itself or both of us. */
784 void kill_thread_or_group(struct __test_metadata *_metadata,
785 			  enum kill_t kill_how)
786 {
787 	pthread_t thread;
788 	void *status;
789 	/* Kill only when calling __NR_prctl. */
790 	struct sock_filter filter_thread[] = {
791 		BPF_STMT(BPF_LD|BPF_W|BPF_ABS,
792 			offsetof(struct seccomp_data, nr)),
793 		BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, __NR_prctl, 0, 1),
794 		BPF_STMT(BPF_RET|BPF_K, SECCOMP_RET_KILL_THREAD),
795 		BPF_STMT(BPF_RET|BPF_K, SECCOMP_RET_ALLOW),
796 	};
797 	struct sock_fprog prog_thread = {
798 		.len = (unsigned short)ARRAY_SIZE(filter_thread),
799 		.filter = filter_thread,
800 	};
801 	int kill = kill_how == KILL_PROCESS ? SECCOMP_RET_KILL_PROCESS : 0xAAAAAAAAA;
802 	struct sock_filter filter_process[] = {
803 		BPF_STMT(BPF_LD|BPF_W|BPF_ABS,
804 			offsetof(struct seccomp_data, nr)),
805 		BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, __NR_prctl, 0, 1),
806 		BPF_STMT(BPF_RET|BPF_K, kill),
807 		BPF_STMT(BPF_RET|BPF_K, SECCOMP_RET_ALLOW),
808 	};
809 	struct sock_fprog prog_process = {
810 		.len = (unsigned short)ARRAY_SIZE(filter_process),
811 		.filter = filter_process,
812 	};
813 
814 	ASSERT_EQ(0, prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0)) {
815 		TH_LOG("Kernel does not support PR_SET_NO_NEW_PRIVS!");
816 	}
817 
818 	ASSERT_EQ(0, seccomp(SECCOMP_SET_MODE_FILTER, 0,
819 			     kill_how == KILL_THREAD ? &prog_thread
820 						     : &prog_process));
821 
822 	/*
823 	 * Add the KILL_THREAD rule again to make sure that the KILL_PROCESS
824 	 * flag cannot be downgraded by a new filter.
825 	 */
826 	if (kill_how == KILL_PROCESS)
827 		ASSERT_EQ(0, seccomp(SECCOMP_SET_MODE_FILTER, 0, &prog_thread));
828 
829 	/* Start a thread that will exit immediately. */
830 	ASSERT_EQ(0, pthread_create(&thread, NULL, kill_thread, (void *)false));
831 	ASSERT_EQ(0, pthread_join(thread, &status));
832 	ASSERT_EQ(SIBLING_EXIT_UNKILLED, (unsigned long)status);
833 
834 	/* Start a thread that will die immediately. */
835 	ASSERT_EQ(0, pthread_create(&thread, NULL, kill_thread, (void *)true));
836 	ASSERT_EQ(0, pthread_join(thread, &status));
837 	ASSERT_NE(SIBLING_EXIT_FAILURE, (unsigned long)status);
838 
839 	/*
840 	 * If we get here, only the spawned thread died. Let the parent know
841 	 * the whole process didn't die (i.e. this thread, the spawner,
842 	 * stayed running).
843 	 */
844 	exit(42);
845 }
846 
847 TEST(KILL_thread)
848 {
849 	int status;
850 	pid_t child_pid;
851 
852 	child_pid = fork();
853 	ASSERT_LE(0, child_pid);
854 	if (child_pid == 0) {
855 		kill_thread_or_group(_metadata, KILL_THREAD);
856 		_exit(38);
857 	}
858 
859 	ASSERT_EQ(child_pid, waitpid(child_pid, &status, 0));
860 
861 	/* If only the thread was killed, we'll see exit 42. */
862 	ASSERT_TRUE(WIFEXITED(status));
863 	ASSERT_EQ(42, WEXITSTATUS(status));
864 }
865 
866 TEST(KILL_process)
867 {
868 	int status;
869 	pid_t child_pid;
870 
871 	child_pid = fork();
872 	ASSERT_LE(0, child_pid);
873 	if (child_pid == 0) {
874 		kill_thread_or_group(_metadata, KILL_PROCESS);
875 		_exit(38);
876 	}
877 
878 	ASSERT_EQ(child_pid, waitpid(child_pid, &status, 0));
879 
880 	/* If the entire process was killed, we'll see SIGSYS. */
881 	ASSERT_TRUE(WIFSIGNALED(status));
882 	ASSERT_EQ(SIGSYS, WTERMSIG(status));
883 }
884 
885 TEST(KILL_unknown)
886 {
887 	int status;
888 	pid_t child_pid;
889 
890 	child_pid = fork();
891 	ASSERT_LE(0, child_pid);
892 	if (child_pid == 0) {
893 		kill_thread_or_group(_metadata, RET_UNKNOWN);
894 		_exit(38);
895 	}
896 
897 	ASSERT_EQ(child_pid, waitpid(child_pid, &status, 0));
898 
899 	/* If the entire process was killed, we'll see SIGSYS. */
900 	EXPECT_TRUE(WIFSIGNALED(status)) {
901 		TH_LOG("Unknown SECCOMP_RET is only killing the thread?");
902 	}
903 	ASSERT_EQ(SIGSYS, WTERMSIG(status));
904 }
905 
906 /* TODO(wad) add 64-bit versus 32-bit arg tests. */
907 TEST(arg_out_of_range)
908 {
909 	struct sock_filter filter[] = {
910 		BPF_STMT(BPF_LD|BPF_W|BPF_ABS, syscall_arg(6)),
911 		BPF_STMT(BPF_RET|BPF_K, SECCOMP_RET_ALLOW),
912 	};
913 	struct sock_fprog prog = {
914 		.len = (unsigned short)ARRAY_SIZE(filter),
915 		.filter = filter,
916 	};
917 	long ret;
918 
919 	ret = prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
920 	ASSERT_EQ(0, ret);
921 
922 	ret = prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &prog);
923 	EXPECT_EQ(-1, ret);
924 	EXPECT_EQ(EINVAL, errno);
925 }
926 
927 #define ERRNO_FILTER(name, errno)					\
928 	struct sock_filter _read_filter_##name[] = {			\
929 		BPF_STMT(BPF_LD|BPF_W|BPF_ABS,				\
930 			offsetof(struct seccomp_data, nr)),		\
931 		BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, __NR_read, 0, 1),	\
932 		BPF_STMT(BPF_RET|BPF_K, SECCOMP_RET_ERRNO | errno),	\
933 		BPF_STMT(BPF_RET|BPF_K, SECCOMP_RET_ALLOW),		\
934 	};								\
935 	struct sock_fprog prog_##name = {				\
936 		.len = (unsigned short)ARRAY_SIZE(_read_filter_##name),	\
937 		.filter = _read_filter_##name,				\
938 	}
939 
940 /* Make sure basic errno values are correctly passed through a filter. */
941 TEST(ERRNO_valid)
942 {
943 	ERRNO_FILTER(valid, E2BIG);
944 	long ret;
945 	pid_t parent = getppid();
946 
947 	ret = prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
948 	ASSERT_EQ(0, ret);
949 
950 	ret = prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &prog_valid);
951 	ASSERT_EQ(0, ret);
952 
953 	EXPECT_EQ(parent, syscall(__NR_getppid));
954 	EXPECT_EQ(-1, read(0, NULL, 0));
955 	EXPECT_EQ(E2BIG, errno);
956 }
957 
958 /* Make sure an errno of zero is correctly handled by the arch code. */
959 TEST(ERRNO_zero)
960 {
961 	ERRNO_FILTER(zero, 0);
962 	long ret;
963 	pid_t parent = getppid();
964 
965 	ret = prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
966 	ASSERT_EQ(0, ret);
967 
968 	ret = prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &prog_zero);
969 	ASSERT_EQ(0, ret);
970 
971 	EXPECT_EQ(parent, syscall(__NR_getppid));
972 	/* "errno" of 0 is ok. */
973 	EXPECT_EQ(0, read(0, NULL, 0));
974 }
975 
976 /*
977  * The SECCOMP_RET_DATA mask is 16 bits wide, but errno is smaller.
978  * This tests that the errno value gets capped correctly, fixed by
979  * 580c57f10768 ("seccomp: cap SECCOMP_RET_ERRNO data to MAX_ERRNO").
980  */
981 TEST(ERRNO_capped)
982 {
983 	ERRNO_FILTER(capped, 4096);
984 	long ret;
985 	pid_t parent = getppid();
986 
987 	ret = prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
988 	ASSERT_EQ(0, ret);
989 
990 	ret = prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &prog_capped);
991 	ASSERT_EQ(0, ret);
992 
993 	EXPECT_EQ(parent, syscall(__NR_getppid));
994 	EXPECT_EQ(-1, read(0, NULL, 0));
995 	EXPECT_EQ(4095, errno);
996 }
997 
998 /*
999  * Filters are processed in reverse order: last applied is executed first.
1000  * Since only the SECCOMP_RET_ACTION mask is tested for return values, the
1001  * SECCOMP_RET_DATA mask results will follow the most recently applied
1002  * matching filter return (and not the lowest or highest value).
1003  */
1004 TEST(ERRNO_order)
1005 {
1006 	ERRNO_FILTER(first,  11);
1007 	ERRNO_FILTER(second, 13);
1008 	ERRNO_FILTER(third,  12);
1009 	long ret;
1010 	pid_t parent = getppid();
1011 
1012 	ret = prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
1013 	ASSERT_EQ(0, ret);
1014 
1015 	ret = prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &prog_first);
1016 	ASSERT_EQ(0, ret);
1017 
1018 	ret = prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &prog_second);
1019 	ASSERT_EQ(0, ret);
1020 
1021 	ret = prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &prog_third);
1022 	ASSERT_EQ(0, ret);
1023 
1024 	EXPECT_EQ(parent, syscall(__NR_getppid));
1025 	EXPECT_EQ(-1, read(0, NULL, 0));
1026 	EXPECT_EQ(12, errno);
1027 }
1028 
1029 FIXTURE(TRAP) {
1030 	struct sock_fprog prog;
1031 };
1032 
1033 FIXTURE_SETUP(TRAP)
1034 {
1035 	struct sock_filter filter[] = {
1036 		BPF_STMT(BPF_LD|BPF_W|BPF_ABS,
1037 			offsetof(struct seccomp_data, nr)),
1038 		BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, __NR_getpid, 0, 1),
1039 		BPF_STMT(BPF_RET|BPF_K, SECCOMP_RET_TRAP),
1040 		BPF_STMT(BPF_RET|BPF_K, SECCOMP_RET_ALLOW),
1041 	};
1042 
1043 	memset(&self->prog, 0, sizeof(self->prog));
1044 	self->prog.filter = malloc(sizeof(filter));
1045 	ASSERT_NE(NULL, self->prog.filter);
1046 	memcpy(self->prog.filter, filter, sizeof(filter));
1047 	self->prog.len = (unsigned short)ARRAY_SIZE(filter);
1048 }
1049 
1050 FIXTURE_TEARDOWN(TRAP)
1051 {
1052 	if (self->prog.filter)
1053 		free(self->prog.filter);
1054 }
1055 
1056 TEST_F_SIGNAL(TRAP, dfl, SIGSYS)
1057 {
1058 	long ret;
1059 
1060 	ret = prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
1061 	ASSERT_EQ(0, ret);
1062 
1063 	ret = prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &self->prog);
1064 	ASSERT_EQ(0, ret);
1065 	syscall(__NR_getpid);
1066 }
1067 
1068 /* Ensure that SIGSYS overrides SIG_IGN */
1069 TEST_F_SIGNAL(TRAP, ign, SIGSYS)
1070 {
1071 	long ret;
1072 
1073 	ret = prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
1074 	ASSERT_EQ(0, ret);
1075 
1076 	signal(SIGSYS, SIG_IGN);
1077 
1078 	ret = prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &self->prog);
1079 	ASSERT_EQ(0, ret);
1080 	syscall(__NR_getpid);
1081 }
1082 
1083 static siginfo_t TRAP_info;
1084 static volatile int TRAP_nr;
1085 static void TRAP_action(int nr, siginfo_t *info, void *void_context)
1086 {
1087 	memcpy(&TRAP_info, info, sizeof(TRAP_info));
1088 	TRAP_nr = nr;
1089 }
1090 
1091 TEST_F(TRAP, handler)
1092 {
1093 	int ret, test;
1094 	struct sigaction act;
1095 	sigset_t mask;
1096 
1097 	memset(&act, 0, sizeof(act));
1098 	sigemptyset(&mask);
1099 	sigaddset(&mask, SIGSYS);
1100 
1101 	act.sa_sigaction = &TRAP_action;
1102 	act.sa_flags = SA_SIGINFO;
1103 	ret = sigaction(SIGSYS, &act, NULL);
1104 	ASSERT_EQ(0, ret) {
1105 		TH_LOG("sigaction failed");
1106 	}
1107 	ret = sigprocmask(SIG_UNBLOCK, &mask, NULL);
1108 	ASSERT_EQ(0, ret) {
1109 		TH_LOG("sigprocmask failed");
1110 	}
1111 
1112 	ret = prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
1113 	ASSERT_EQ(0, ret);
1114 	ret = prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &self->prog);
1115 	ASSERT_EQ(0, ret);
1116 	TRAP_nr = 0;
1117 	memset(&TRAP_info, 0, sizeof(TRAP_info));
1118 	/* Expect the registers to be rolled back. (nr = error) may vary
1119 	 * based on arch. */
1120 	ret = syscall(__NR_getpid);
1121 	/* Silence gcc warning about volatile. */
1122 	test = TRAP_nr;
1123 	EXPECT_EQ(SIGSYS, test);
1124 	struct local_sigsys {
1125 		void *_call_addr;	/* calling user insn */
1126 		int _syscall;		/* triggering system call number */
1127 		unsigned int _arch;	/* AUDIT_ARCH_* of syscall */
1128 	} *sigsys = (struct local_sigsys *)
1129 #ifdef si_syscall
1130 		&(TRAP_info.si_call_addr);
1131 #else
1132 		&TRAP_info.si_pid;
1133 #endif
1134 	EXPECT_EQ(__NR_getpid, sigsys->_syscall);
1135 	/* Make sure arch is non-zero. */
1136 	EXPECT_NE(0, sigsys->_arch);
1137 	EXPECT_NE(0, (unsigned long)sigsys->_call_addr);
1138 }
1139 
1140 FIXTURE(precedence) {
1141 	struct sock_fprog allow;
1142 	struct sock_fprog log;
1143 	struct sock_fprog trace;
1144 	struct sock_fprog error;
1145 	struct sock_fprog trap;
1146 	struct sock_fprog kill;
1147 };
1148 
1149 FIXTURE_SETUP(precedence)
1150 {
1151 	struct sock_filter allow_insns[] = {
1152 		BPF_STMT(BPF_RET|BPF_K, SECCOMP_RET_ALLOW),
1153 	};
1154 	struct sock_filter log_insns[] = {
1155 		BPF_STMT(BPF_LD|BPF_W|BPF_ABS,
1156 			offsetof(struct seccomp_data, nr)),
1157 		BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, __NR_getpid, 1, 0),
1158 		BPF_STMT(BPF_RET|BPF_K, SECCOMP_RET_ALLOW),
1159 		BPF_STMT(BPF_RET|BPF_K, SECCOMP_RET_LOG),
1160 	};
1161 	struct sock_filter trace_insns[] = {
1162 		BPF_STMT(BPF_LD|BPF_W|BPF_ABS,
1163 			offsetof(struct seccomp_data, nr)),
1164 		BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, __NR_getpid, 1, 0),
1165 		BPF_STMT(BPF_RET|BPF_K, SECCOMP_RET_ALLOW),
1166 		BPF_STMT(BPF_RET|BPF_K, SECCOMP_RET_TRACE),
1167 	};
1168 	struct sock_filter error_insns[] = {
1169 		BPF_STMT(BPF_LD|BPF_W|BPF_ABS,
1170 			offsetof(struct seccomp_data, nr)),
1171 		BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, __NR_getpid, 1, 0),
1172 		BPF_STMT(BPF_RET|BPF_K, SECCOMP_RET_ALLOW),
1173 		BPF_STMT(BPF_RET|BPF_K, SECCOMP_RET_ERRNO),
1174 	};
1175 	struct sock_filter trap_insns[] = {
1176 		BPF_STMT(BPF_LD|BPF_W|BPF_ABS,
1177 			offsetof(struct seccomp_data, nr)),
1178 		BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, __NR_getpid, 1, 0),
1179 		BPF_STMT(BPF_RET|BPF_K, SECCOMP_RET_ALLOW),
1180 		BPF_STMT(BPF_RET|BPF_K, SECCOMP_RET_TRAP),
1181 	};
1182 	struct sock_filter kill_insns[] = {
1183 		BPF_STMT(BPF_LD|BPF_W|BPF_ABS,
1184 			offsetof(struct seccomp_data, nr)),
1185 		BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, __NR_getpid, 1, 0),
1186 		BPF_STMT(BPF_RET|BPF_K, SECCOMP_RET_ALLOW),
1187 		BPF_STMT(BPF_RET|BPF_K, SECCOMP_RET_KILL),
1188 	};
1189 
1190 	memset(self, 0, sizeof(*self));
1191 #define FILTER_ALLOC(_x) \
1192 	self->_x.filter = malloc(sizeof(_x##_insns)); \
1193 	ASSERT_NE(NULL, self->_x.filter); \
1194 	memcpy(self->_x.filter, &_x##_insns, sizeof(_x##_insns)); \
1195 	self->_x.len = (unsigned short)ARRAY_SIZE(_x##_insns)
1196 	FILTER_ALLOC(allow);
1197 	FILTER_ALLOC(log);
1198 	FILTER_ALLOC(trace);
1199 	FILTER_ALLOC(error);
1200 	FILTER_ALLOC(trap);
1201 	FILTER_ALLOC(kill);
1202 }
1203 
1204 FIXTURE_TEARDOWN(precedence)
1205 {
1206 #define FILTER_FREE(_x) if (self->_x.filter) free(self->_x.filter)
1207 	FILTER_FREE(allow);
1208 	FILTER_FREE(log);
1209 	FILTER_FREE(trace);
1210 	FILTER_FREE(error);
1211 	FILTER_FREE(trap);
1212 	FILTER_FREE(kill);
1213 }
1214 
1215 TEST_F(precedence, allow_ok)
1216 {
1217 	pid_t parent, res = 0;
1218 	long ret;
1219 
1220 	parent = getppid();
1221 	ret = prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
1222 	ASSERT_EQ(0, ret);
1223 
1224 	ret = prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &self->allow);
1225 	ASSERT_EQ(0, ret);
1226 	ret = prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &self->log);
1227 	ASSERT_EQ(0, ret);
1228 	ret = prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &self->trace);
1229 	ASSERT_EQ(0, ret);
1230 	ret = prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &self->error);
1231 	ASSERT_EQ(0, ret);
1232 	ret = prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &self->trap);
1233 	ASSERT_EQ(0, ret);
1234 	ret = prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &self->kill);
1235 	ASSERT_EQ(0, ret);
1236 	/* Should work just fine. */
1237 	res = syscall(__NR_getppid);
1238 	EXPECT_EQ(parent, res);
1239 }
1240 
1241 TEST_F_SIGNAL(precedence, kill_is_highest, SIGSYS)
1242 {
1243 	pid_t parent, res = 0;
1244 	long ret;
1245 
1246 	parent = getppid();
1247 	ret = prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
1248 	ASSERT_EQ(0, ret);
1249 
1250 	ret = prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &self->allow);
1251 	ASSERT_EQ(0, ret);
1252 	ret = prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &self->log);
1253 	ASSERT_EQ(0, ret);
1254 	ret = prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &self->trace);
1255 	ASSERT_EQ(0, ret);
1256 	ret = prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &self->error);
1257 	ASSERT_EQ(0, ret);
1258 	ret = prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &self->trap);
1259 	ASSERT_EQ(0, ret);
1260 	ret = prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &self->kill);
1261 	ASSERT_EQ(0, ret);
1262 	/* Should work just fine. */
1263 	res = syscall(__NR_getppid);
1264 	EXPECT_EQ(parent, res);
1265 	/* getpid() should never return. */
1266 	res = syscall(__NR_getpid);
1267 	EXPECT_EQ(0, res);
1268 }
1269 
1270 TEST_F_SIGNAL(precedence, kill_is_highest_in_any_order, SIGSYS)
1271 {
1272 	pid_t parent;
1273 	long ret;
1274 
1275 	parent = getppid();
1276 	ret = prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
1277 	ASSERT_EQ(0, ret);
1278 
1279 	ret = prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &self->allow);
1280 	ASSERT_EQ(0, ret);
1281 	ret = prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &self->kill);
1282 	ASSERT_EQ(0, ret);
1283 	ret = prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &self->error);
1284 	ASSERT_EQ(0, ret);
1285 	ret = prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &self->log);
1286 	ASSERT_EQ(0, ret);
1287 	ret = prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &self->trace);
1288 	ASSERT_EQ(0, ret);
1289 	ret = prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &self->trap);
1290 	ASSERT_EQ(0, ret);
1291 	/* Should work just fine. */
1292 	EXPECT_EQ(parent, syscall(__NR_getppid));
1293 	/* getpid() should never return. */
1294 	EXPECT_EQ(0, syscall(__NR_getpid));
1295 }
1296 
1297 TEST_F_SIGNAL(precedence, trap_is_second, SIGSYS)
1298 {
1299 	pid_t parent;
1300 	long ret;
1301 
1302 	parent = getppid();
1303 	ret = prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
1304 	ASSERT_EQ(0, ret);
1305 
1306 	ret = prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &self->allow);
1307 	ASSERT_EQ(0, ret);
1308 	ret = prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &self->log);
1309 	ASSERT_EQ(0, ret);
1310 	ret = prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &self->trace);
1311 	ASSERT_EQ(0, ret);
1312 	ret = prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &self->error);
1313 	ASSERT_EQ(0, ret);
1314 	ret = prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &self->trap);
1315 	ASSERT_EQ(0, ret);
1316 	/* Should work just fine. */
1317 	EXPECT_EQ(parent, syscall(__NR_getppid));
1318 	/* getpid() should never return. */
1319 	EXPECT_EQ(0, syscall(__NR_getpid));
1320 }
1321 
1322 TEST_F_SIGNAL(precedence, trap_is_second_in_any_order, SIGSYS)
1323 {
1324 	pid_t parent;
1325 	long ret;
1326 
1327 	parent = getppid();
1328 	ret = prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
1329 	ASSERT_EQ(0, ret);
1330 
1331 	ret = prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &self->allow);
1332 	ASSERT_EQ(0, ret);
1333 	ret = prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &self->trap);
1334 	ASSERT_EQ(0, ret);
1335 	ret = prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &self->log);
1336 	ASSERT_EQ(0, ret);
1337 	ret = prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &self->trace);
1338 	ASSERT_EQ(0, ret);
1339 	ret = prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &self->error);
1340 	ASSERT_EQ(0, ret);
1341 	/* Should work just fine. */
1342 	EXPECT_EQ(parent, syscall(__NR_getppid));
1343 	/* getpid() should never return. */
1344 	EXPECT_EQ(0, syscall(__NR_getpid));
1345 }
1346 
1347 TEST_F(precedence, errno_is_third)
1348 {
1349 	pid_t parent;
1350 	long ret;
1351 
1352 	parent = getppid();
1353 	ret = prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
1354 	ASSERT_EQ(0, ret);
1355 
1356 	ret = prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &self->allow);
1357 	ASSERT_EQ(0, ret);
1358 	ret = prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &self->log);
1359 	ASSERT_EQ(0, ret);
1360 	ret = prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &self->trace);
1361 	ASSERT_EQ(0, ret);
1362 	ret = prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &self->error);
1363 	ASSERT_EQ(0, ret);
1364 	/* Should work just fine. */
1365 	EXPECT_EQ(parent, syscall(__NR_getppid));
1366 	EXPECT_EQ(0, syscall(__NR_getpid));
1367 }
1368 
1369 TEST_F(precedence, errno_is_third_in_any_order)
1370 {
1371 	pid_t parent;
1372 	long ret;
1373 
1374 	parent = getppid();
1375 	ret = prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
1376 	ASSERT_EQ(0, ret);
1377 
1378 	ret = prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &self->log);
1379 	ASSERT_EQ(0, ret);
1380 	ret = prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &self->error);
1381 	ASSERT_EQ(0, ret);
1382 	ret = prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &self->trace);
1383 	ASSERT_EQ(0, ret);
1384 	ret = prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &self->allow);
1385 	ASSERT_EQ(0, ret);
1386 	/* Should work just fine. */
1387 	EXPECT_EQ(parent, syscall(__NR_getppid));
1388 	EXPECT_EQ(0, syscall(__NR_getpid));
1389 }
1390 
1391 TEST_F(precedence, trace_is_fourth)
1392 {
1393 	pid_t parent;
1394 	long ret;
1395 
1396 	parent = getppid();
1397 	ret = prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
1398 	ASSERT_EQ(0, ret);
1399 
1400 	ret = prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &self->allow);
1401 	ASSERT_EQ(0, ret);
1402 	ret = prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &self->log);
1403 	ASSERT_EQ(0, ret);
1404 	ret = prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &self->trace);
1405 	ASSERT_EQ(0, ret);
1406 	/* Should work just fine. */
1407 	EXPECT_EQ(parent, syscall(__NR_getppid));
1408 	/* No ptracer */
1409 	EXPECT_EQ(-1, syscall(__NR_getpid));
1410 }
1411 
1412 TEST_F(precedence, trace_is_fourth_in_any_order)
1413 {
1414 	pid_t parent;
1415 	long ret;
1416 
1417 	parent = getppid();
1418 	ret = prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
1419 	ASSERT_EQ(0, ret);
1420 
1421 	ret = prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &self->trace);
1422 	ASSERT_EQ(0, ret);
1423 	ret = prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &self->allow);
1424 	ASSERT_EQ(0, ret);
1425 	ret = prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &self->log);
1426 	ASSERT_EQ(0, ret);
1427 	/* Should work just fine. */
1428 	EXPECT_EQ(parent, syscall(__NR_getppid));
1429 	/* No ptracer */
1430 	EXPECT_EQ(-1, syscall(__NR_getpid));
1431 }
1432 
1433 TEST_F(precedence, log_is_fifth)
1434 {
1435 	pid_t mypid, parent;
1436 	long ret;
1437 
1438 	mypid = getpid();
1439 	parent = getppid();
1440 	ret = prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
1441 	ASSERT_EQ(0, ret);
1442 
1443 	ret = prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &self->allow);
1444 	ASSERT_EQ(0, ret);
1445 	ret = prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &self->log);
1446 	ASSERT_EQ(0, ret);
1447 	/* Should work just fine. */
1448 	EXPECT_EQ(parent, syscall(__NR_getppid));
1449 	/* Should also work just fine */
1450 	EXPECT_EQ(mypid, syscall(__NR_getpid));
1451 }
1452 
1453 TEST_F(precedence, log_is_fifth_in_any_order)
1454 {
1455 	pid_t mypid, parent;
1456 	long ret;
1457 
1458 	mypid = getpid();
1459 	parent = getppid();
1460 	ret = prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
1461 	ASSERT_EQ(0, ret);
1462 
1463 	ret = prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &self->log);
1464 	ASSERT_EQ(0, ret);
1465 	ret = prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &self->allow);
1466 	ASSERT_EQ(0, ret);
1467 	/* Should work just fine. */
1468 	EXPECT_EQ(parent, syscall(__NR_getppid));
1469 	/* Should also work just fine */
1470 	EXPECT_EQ(mypid, syscall(__NR_getpid));
1471 }
1472 
1473 #ifndef PTRACE_O_TRACESECCOMP
1474 #define PTRACE_O_TRACESECCOMP	0x00000080
1475 #endif
1476 
1477 /* Catch the Ubuntu 12.04 value error. */
1478 #if PTRACE_EVENT_SECCOMP != 7
1479 #undef PTRACE_EVENT_SECCOMP
1480 #endif
1481 
1482 #ifndef PTRACE_EVENT_SECCOMP
1483 #define PTRACE_EVENT_SECCOMP 7
1484 #endif
1485 
1486 #define IS_SECCOMP_EVENT(status) ((status >> 16) == PTRACE_EVENT_SECCOMP)
1487 bool tracer_running;
1488 void tracer_stop(int sig)
1489 {
1490 	tracer_running = false;
1491 }
1492 
1493 typedef void tracer_func_t(struct __test_metadata *_metadata,
1494 			   pid_t tracee, int status, void *args);
1495 
1496 void start_tracer(struct __test_metadata *_metadata, int fd, pid_t tracee,
1497 	    tracer_func_t tracer_func, void *args, bool ptrace_syscall)
1498 {
1499 	int ret = -1;
1500 	struct sigaction action = {
1501 		.sa_handler = tracer_stop,
1502 	};
1503 
1504 	/* Allow external shutdown. */
1505 	tracer_running = true;
1506 	ASSERT_EQ(0, sigaction(SIGUSR1, &action, NULL));
1507 
1508 	errno = 0;
1509 	while (ret == -1 && errno != EINVAL)
1510 		ret = ptrace(PTRACE_ATTACH, tracee, NULL, 0);
1511 	ASSERT_EQ(0, ret) {
1512 		kill(tracee, SIGKILL);
1513 	}
1514 	/* Wait for attach stop */
1515 	wait(NULL);
1516 
1517 	ret = ptrace(PTRACE_SETOPTIONS, tracee, NULL, ptrace_syscall ?
1518 						      PTRACE_O_TRACESYSGOOD :
1519 						      PTRACE_O_TRACESECCOMP);
1520 	ASSERT_EQ(0, ret) {
1521 		TH_LOG("Failed to set PTRACE_O_TRACESECCOMP");
1522 		kill(tracee, SIGKILL);
1523 	}
1524 	ret = ptrace(ptrace_syscall ? PTRACE_SYSCALL : PTRACE_CONT,
1525 		     tracee, NULL, 0);
1526 	ASSERT_EQ(0, ret);
1527 
1528 	/* Unblock the tracee */
1529 	ASSERT_EQ(1, write(fd, "A", 1));
1530 	ASSERT_EQ(0, close(fd));
1531 
1532 	/* Run until we're shut down. Must assert to stop execution. */
1533 	while (tracer_running) {
1534 		int status;
1535 
1536 		if (wait(&status) != tracee)
1537 			continue;
1538 		if (WIFSIGNALED(status) || WIFEXITED(status))
1539 			/* Child is dead. Time to go. */
1540 			return;
1541 
1542 		/* Check if this is a seccomp event. */
1543 		ASSERT_EQ(!ptrace_syscall, IS_SECCOMP_EVENT(status));
1544 
1545 		tracer_func(_metadata, tracee, status, args);
1546 
1547 		ret = ptrace(ptrace_syscall ? PTRACE_SYSCALL : PTRACE_CONT,
1548 			     tracee, NULL, 0);
1549 		ASSERT_EQ(0, ret);
1550 	}
1551 	/* Directly report the status of our test harness results. */
1552 	syscall(__NR_exit, _metadata->passed ? EXIT_SUCCESS : EXIT_FAILURE);
1553 }
1554 
1555 /* Common tracer setup/teardown functions. */
1556 void cont_handler(int num)
1557 { }
1558 pid_t setup_trace_fixture(struct __test_metadata *_metadata,
1559 			  tracer_func_t func, void *args, bool ptrace_syscall)
1560 {
1561 	char sync;
1562 	int pipefd[2];
1563 	pid_t tracer_pid;
1564 	pid_t tracee = getpid();
1565 
1566 	/* Setup a pipe for clean synchronization. */
1567 	ASSERT_EQ(0, pipe(pipefd));
1568 
1569 	/* Fork a child which we'll promote to tracer */
1570 	tracer_pid = fork();
1571 	ASSERT_LE(0, tracer_pid);
1572 	signal(SIGALRM, cont_handler);
1573 	if (tracer_pid == 0) {
1574 		close(pipefd[0]);
1575 		start_tracer(_metadata, pipefd[1], tracee, func, args,
1576 			     ptrace_syscall);
1577 		syscall(__NR_exit, 0);
1578 	}
1579 	close(pipefd[1]);
1580 	prctl(PR_SET_PTRACER, tracer_pid, 0, 0, 0);
1581 	read(pipefd[0], &sync, 1);
1582 	close(pipefd[0]);
1583 
1584 	return tracer_pid;
1585 }
1586 
1587 void teardown_trace_fixture(struct __test_metadata *_metadata,
1588 			    pid_t tracer)
1589 {
1590 	if (tracer) {
1591 		int status;
1592 		/*
1593 		 * Extract the exit code from the other process and
1594 		 * adopt it for ourselves in case its asserts failed.
1595 		 */
1596 		ASSERT_EQ(0, kill(tracer, SIGUSR1));
1597 		ASSERT_EQ(tracer, waitpid(tracer, &status, 0));
1598 		if (WEXITSTATUS(status))
1599 			_metadata->passed = 0;
1600 	}
1601 }
1602 
1603 /* "poke" tracer arguments and function. */
1604 struct tracer_args_poke_t {
1605 	unsigned long poke_addr;
1606 };
1607 
1608 void tracer_poke(struct __test_metadata *_metadata, pid_t tracee, int status,
1609 		 void *args)
1610 {
1611 	int ret;
1612 	unsigned long msg;
1613 	struct tracer_args_poke_t *info = (struct tracer_args_poke_t *)args;
1614 
1615 	ret = ptrace(PTRACE_GETEVENTMSG, tracee, NULL, &msg);
1616 	EXPECT_EQ(0, ret);
1617 	/* If this fails, don't try to recover. */
1618 	ASSERT_EQ(0x1001, msg) {
1619 		kill(tracee, SIGKILL);
1620 	}
1621 	/*
1622 	 * Poke in the message.
1623 	 * Registers are not touched to try to keep this relatively arch
1624 	 * agnostic.
1625 	 */
1626 	ret = ptrace(PTRACE_POKEDATA, tracee, info->poke_addr, 0x1001);
1627 	EXPECT_EQ(0, ret);
1628 }
1629 
1630 FIXTURE(TRACE_poke) {
1631 	struct sock_fprog prog;
1632 	pid_t tracer;
1633 	long poked;
1634 	struct tracer_args_poke_t tracer_args;
1635 };
1636 
1637 FIXTURE_SETUP(TRACE_poke)
1638 {
1639 	struct sock_filter filter[] = {
1640 		BPF_STMT(BPF_LD|BPF_W|BPF_ABS,
1641 			offsetof(struct seccomp_data, nr)),
1642 		BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, __NR_read, 0, 1),
1643 		BPF_STMT(BPF_RET|BPF_K, SECCOMP_RET_TRACE | 0x1001),
1644 		BPF_STMT(BPF_RET|BPF_K, SECCOMP_RET_ALLOW),
1645 	};
1646 
1647 	self->poked = 0;
1648 	memset(&self->prog, 0, sizeof(self->prog));
1649 	self->prog.filter = malloc(sizeof(filter));
1650 	ASSERT_NE(NULL, self->prog.filter);
1651 	memcpy(self->prog.filter, filter, sizeof(filter));
1652 	self->prog.len = (unsigned short)ARRAY_SIZE(filter);
1653 
1654 	/* Set up tracer args. */
1655 	self->tracer_args.poke_addr = (unsigned long)&self->poked;
1656 
1657 	/* Launch tracer. */
1658 	self->tracer = setup_trace_fixture(_metadata, tracer_poke,
1659 					   &self->tracer_args, false);
1660 }
1661 
1662 FIXTURE_TEARDOWN(TRACE_poke)
1663 {
1664 	teardown_trace_fixture(_metadata, self->tracer);
1665 	if (self->prog.filter)
1666 		free(self->prog.filter);
1667 }
1668 
1669 TEST_F(TRACE_poke, read_has_side_effects)
1670 {
1671 	ssize_t ret;
1672 
1673 	ret = prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
1674 	ASSERT_EQ(0, ret);
1675 
1676 	ret = prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &self->prog, 0, 0);
1677 	ASSERT_EQ(0, ret);
1678 
1679 	EXPECT_EQ(0, self->poked);
1680 	ret = read(-1, NULL, 0);
1681 	EXPECT_EQ(-1, ret);
1682 	EXPECT_EQ(0x1001, self->poked);
1683 }
1684 
1685 TEST_F(TRACE_poke, getpid_runs_normally)
1686 {
1687 	long ret;
1688 
1689 	ret = prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
1690 	ASSERT_EQ(0, ret);
1691 
1692 	ret = prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &self->prog, 0, 0);
1693 	ASSERT_EQ(0, ret);
1694 
1695 	EXPECT_EQ(0, self->poked);
1696 	EXPECT_NE(0, syscall(__NR_getpid));
1697 	EXPECT_EQ(0, self->poked);
1698 }
1699 
1700 #if defined(__x86_64__)
1701 # define ARCH_REGS		struct user_regs_struct
1702 # define SYSCALL_NUM(_regs)	(_regs).orig_rax
1703 # define SYSCALL_RET(_regs)	(_regs).rax
1704 #elif defined(__i386__)
1705 # define ARCH_REGS		struct user_regs_struct
1706 # define SYSCALL_NUM(_regs)	(_regs).orig_eax
1707 # define SYSCALL_RET(_regs)	(_regs).eax
1708 #elif defined(__arm__)
1709 # define ARCH_REGS		struct pt_regs
1710 # define SYSCALL_NUM(_regs)	(_regs).ARM_r7
1711 # ifndef PTRACE_SET_SYSCALL
1712 #  define PTRACE_SET_SYSCALL   23
1713 # endif
1714 # define SYSCALL_NUM_SET(_regs, _nr)	\
1715 		EXPECT_EQ(0, ptrace(PTRACE_SET_SYSCALL, tracee, NULL, _nr))
1716 # define SYSCALL_RET(_regs)	(_regs).ARM_r0
1717 #elif defined(__aarch64__)
1718 # define ARCH_REGS		struct user_pt_regs
1719 # define SYSCALL_NUM(_regs)	(_regs).regs[8]
1720 # ifndef NT_ARM_SYSTEM_CALL
1721 #  define NT_ARM_SYSTEM_CALL 0x404
1722 # endif
1723 # define SYSCALL_NUM_SET(_regs, _nr)				\
1724 	do {							\
1725 		struct iovec __v;				\
1726 		typeof(_nr) __nr = (_nr);			\
1727 		__v.iov_base = &__nr;				\
1728 		__v.iov_len = sizeof(__nr);			\
1729 		EXPECT_EQ(0, ptrace(PTRACE_SETREGSET, tracee,	\
1730 				    NT_ARM_SYSTEM_CALL, &__v));	\
1731 	} while (0)
1732 # define SYSCALL_RET(_regs)	(_regs).regs[0]
1733 #elif defined(__riscv) && __riscv_xlen == 64
1734 # define ARCH_REGS		struct user_regs_struct
1735 # define SYSCALL_NUM(_regs)	(_regs).a7
1736 # define SYSCALL_RET(_regs)	(_regs).a0
1737 #elif defined(__csky__)
1738 # define ARCH_REGS		struct pt_regs
1739 #  if defined(__CSKYABIV2__)
1740 #   define SYSCALL_NUM(_regs)	(_regs).regs[3]
1741 #  else
1742 #   define SYSCALL_NUM(_regs)	(_regs).regs[9]
1743 #  endif
1744 # define SYSCALL_RET(_regs)	(_regs).a0
1745 #elif defined(__hppa__)
1746 # define ARCH_REGS		struct user_regs_struct
1747 # define SYSCALL_NUM(_regs)	(_regs).gr[20]
1748 # define SYSCALL_RET(_regs)	(_regs).gr[28]
1749 #elif defined(__powerpc__)
1750 # define ARCH_REGS		struct pt_regs
1751 # define SYSCALL_NUM(_regs)	(_regs).gpr[0]
1752 # define SYSCALL_RET(_regs)	(_regs).gpr[3]
1753 # define SYSCALL_RET_SET(_regs, _val)				\
1754 	do {							\
1755 		typeof(_val) _result = (_val);			\
1756 		/*						\
1757 		 * A syscall error is signaled by CR0 SO bit	\
1758 		 * and the code is stored as a positive value.	\
1759 		 */						\
1760 		if (_result < 0) {				\
1761 			SYSCALL_RET(_regs) = -_result;		\
1762 			(_regs).ccr |= 0x10000000;		\
1763 		} else {					\
1764 			SYSCALL_RET(_regs) = _result;		\
1765 			(_regs).ccr &= ~0x10000000;		\
1766 		}						\
1767 	} while (0)
1768 # define SYSCALL_RET_SET_ON_PTRACE_EXIT
1769 #elif defined(__s390__)
1770 # define ARCH_REGS		s390_regs
1771 # define SYSCALL_NUM(_regs)	(_regs).gprs[2]
1772 # define SYSCALL_RET_SET(_regs, _val)			\
1773 		TH_LOG("Can't modify syscall return on this architecture")
1774 #elif defined(__mips__)
1775 # include <asm/unistd_nr_n32.h>
1776 # include <asm/unistd_nr_n64.h>
1777 # include <asm/unistd_nr_o32.h>
1778 # define ARCH_REGS		struct pt_regs
1779 # define SYSCALL_NUM(_regs)				\
1780 	({						\
1781 		typeof((_regs).regs[2]) _nr;		\
1782 		if ((_regs).regs[2] == __NR_O32_Linux)	\
1783 			_nr = (_regs).regs[4];		\
1784 		else					\
1785 			_nr = (_regs).regs[2];		\
1786 		_nr;					\
1787 	})
1788 # define SYSCALL_NUM_SET(_regs, _nr)			\
1789 	do {						\
1790 		if ((_regs).regs[2] == __NR_O32_Linux)	\
1791 			(_regs).regs[4] = _nr;		\
1792 		else					\
1793 			(_regs).regs[2] = _nr;		\
1794 	} while (0)
1795 # define SYSCALL_RET_SET(_regs, _val)			\
1796 		TH_LOG("Can't modify syscall return on this architecture")
1797 #elif defined(__xtensa__)
1798 # define ARCH_REGS		struct user_pt_regs
1799 # define SYSCALL_NUM(_regs)	(_regs).syscall
1800 /*
1801  * On xtensa syscall return value is in the register
1802  * a2 of the current window which is not fixed.
1803  */
1804 #define SYSCALL_RET(_regs)	(_regs).a[(_regs).windowbase * 4 + 2]
1805 #elif defined(__sh__)
1806 # define ARCH_REGS		struct pt_regs
1807 # define SYSCALL_NUM(_regs)	(_regs).regs[3]
1808 # define SYSCALL_RET(_regs)	(_regs).regs[0]
1809 #else
1810 # error "Do not know how to find your architecture's registers and syscalls"
1811 #endif
1812 
1813 /*
1814  * Most architectures can change the syscall by just updating the
1815  * associated register. This is the default if not defined above.
1816  */
1817 #ifndef SYSCALL_NUM_SET
1818 # define SYSCALL_NUM_SET(_regs, _nr)		\
1819 	do {					\
1820 		SYSCALL_NUM(_regs) = (_nr);	\
1821 	} while (0)
1822 #endif
1823 /*
1824  * Most architectures can change the syscall return value by just
1825  * writing to the SYSCALL_RET register. This is the default if not
1826  * defined above. If an architecture cannot set the return value
1827  * (for example when the syscall and return value register is
1828  * shared), report it with TH_LOG() in an arch-specific definition
1829  * of SYSCALL_RET_SET() above, and leave SYSCALL_RET undefined.
1830  */
1831 #if !defined(SYSCALL_RET) && !defined(SYSCALL_RET_SET)
1832 # error "One of SYSCALL_RET or SYSCALL_RET_SET is needed for this arch"
1833 #endif
1834 #ifndef SYSCALL_RET_SET
1835 # define SYSCALL_RET_SET(_regs, _val)		\
1836 	do {					\
1837 		SYSCALL_RET(_regs) = (_val);	\
1838 	} while (0)
1839 #endif
1840 
1841 /* When the syscall return can't be changed, stub out the tests for it. */
1842 #ifndef SYSCALL_RET
1843 # define EXPECT_SYSCALL_RETURN(val, action)	EXPECT_EQ(-1, action)
1844 #else
1845 # define EXPECT_SYSCALL_RETURN(val, action)		\
1846 	do {						\
1847 		errno = 0;				\
1848 		if (val < 0) {				\
1849 			EXPECT_EQ(-1, action);		\
1850 			EXPECT_EQ(-(val), errno);	\
1851 		} else {				\
1852 			EXPECT_EQ(val, action);		\
1853 		}					\
1854 	} while (0)
1855 #endif
1856 
1857 /*
1858  * Some architectures (e.g. powerpc) can only set syscall
1859  * return values on syscall exit during ptrace.
1860  */
1861 const bool ptrace_entry_set_syscall_nr = true;
1862 const bool ptrace_entry_set_syscall_ret =
1863 #ifndef SYSCALL_RET_SET_ON_PTRACE_EXIT
1864 	true;
1865 #else
1866 	false;
1867 #endif
1868 
1869 /*
1870  * Use PTRACE_GETREGS and PTRACE_SETREGS when available. This is useful for
1871  * architectures without HAVE_ARCH_TRACEHOOK (e.g. User-mode Linux).
1872  */
1873 #if defined(__x86_64__) || defined(__i386__) || defined(__mips__)
1874 # define ARCH_GETREGS(_regs)	ptrace(PTRACE_GETREGS, tracee, 0, &(_regs))
1875 # define ARCH_SETREGS(_regs)	ptrace(PTRACE_SETREGS, tracee, 0, &(_regs))
1876 #else
1877 # define ARCH_GETREGS(_regs)	({					\
1878 		struct iovec __v;					\
1879 		__v.iov_base = &(_regs);				\
1880 		__v.iov_len = sizeof(_regs);				\
1881 		ptrace(PTRACE_GETREGSET, tracee, NT_PRSTATUS, &__v);	\
1882 	})
1883 # define ARCH_SETREGS(_regs)	({					\
1884 		struct iovec __v;					\
1885 		__v.iov_base = &(_regs);				\
1886 		__v.iov_len = sizeof(_regs);				\
1887 		ptrace(PTRACE_SETREGSET, tracee, NT_PRSTATUS, &__v);	\
1888 	})
1889 #endif
1890 
1891 /* Architecture-specific syscall fetching routine. */
1892 int get_syscall(struct __test_metadata *_metadata, pid_t tracee)
1893 {
1894 	ARCH_REGS regs;
1895 
1896 	EXPECT_EQ(0, ARCH_GETREGS(regs)) {
1897 		return -1;
1898 	}
1899 
1900 	return SYSCALL_NUM(regs);
1901 }
1902 
1903 /* Architecture-specific syscall changing routine. */
1904 void __change_syscall(struct __test_metadata *_metadata,
1905 		    pid_t tracee, long *syscall, long *ret)
1906 {
1907 	ARCH_REGS orig, regs;
1908 
1909 	/* Do not get/set registers if we have nothing to do. */
1910 	if (!syscall && !ret)
1911 		return;
1912 
1913 	EXPECT_EQ(0, ARCH_GETREGS(regs)) {
1914 		return;
1915 	}
1916 	orig = regs;
1917 
1918 	if (syscall)
1919 		SYSCALL_NUM_SET(regs, *syscall);
1920 
1921 	if (ret)
1922 		SYSCALL_RET_SET(regs, *ret);
1923 
1924 	/* Flush any register changes made. */
1925 	if (memcmp(&orig, &regs, sizeof(orig)) != 0)
1926 		EXPECT_EQ(0, ARCH_SETREGS(regs));
1927 }
1928 
1929 /* Change only syscall number. */
1930 void change_syscall_nr(struct __test_metadata *_metadata,
1931 		       pid_t tracee, long syscall)
1932 {
1933 	__change_syscall(_metadata, tracee, &syscall, NULL);
1934 }
1935 
1936 /* Change syscall return value (and set syscall number to -1). */
1937 void change_syscall_ret(struct __test_metadata *_metadata,
1938 			pid_t tracee, long ret)
1939 {
1940 	long syscall = -1;
1941 
1942 	__change_syscall(_metadata, tracee, &syscall, &ret);
1943 }
1944 
1945 void tracer_seccomp(struct __test_metadata *_metadata, pid_t tracee,
1946 		    int status, void *args)
1947 {
1948 	int ret;
1949 	unsigned long msg;
1950 
1951 	/* Make sure we got the right message. */
1952 	ret = ptrace(PTRACE_GETEVENTMSG, tracee, NULL, &msg);
1953 	EXPECT_EQ(0, ret);
1954 
1955 	/* Validate and take action on expected syscalls. */
1956 	switch (msg) {
1957 	case 0x1002:
1958 		/* change getpid to getppid. */
1959 		EXPECT_EQ(__NR_getpid, get_syscall(_metadata, tracee));
1960 		change_syscall_nr(_metadata, tracee, __NR_getppid);
1961 		break;
1962 	case 0x1003:
1963 		/* skip gettid with valid return code. */
1964 		EXPECT_EQ(__NR_gettid, get_syscall(_metadata, tracee));
1965 		change_syscall_ret(_metadata, tracee, 45000);
1966 		break;
1967 	case 0x1004:
1968 		/* skip openat with error. */
1969 		EXPECT_EQ(__NR_openat, get_syscall(_metadata, tracee));
1970 		change_syscall_ret(_metadata, tracee, -ESRCH);
1971 		break;
1972 	case 0x1005:
1973 		/* do nothing (allow getppid) */
1974 		EXPECT_EQ(__NR_getppid, get_syscall(_metadata, tracee));
1975 		break;
1976 	default:
1977 		EXPECT_EQ(0, msg) {
1978 			TH_LOG("Unknown PTRACE_GETEVENTMSG: 0x%lx", msg);
1979 			kill(tracee, SIGKILL);
1980 		}
1981 	}
1982 
1983 }
1984 
1985 FIXTURE(TRACE_syscall) {
1986 	struct sock_fprog prog;
1987 	pid_t tracer, mytid, mypid, parent;
1988 	long syscall_nr;
1989 };
1990 
1991 void tracer_ptrace(struct __test_metadata *_metadata, pid_t tracee,
1992 		   int status, void *args)
1993 {
1994 	int ret;
1995 	unsigned long msg;
1996 	static bool entry;
1997 	long syscall_nr_val, syscall_ret_val;
1998 	long *syscall_nr = NULL, *syscall_ret = NULL;
1999 	FIXTURE_DATA(TRACE_syscall) *self = args;
2000 
2001 	/*
2002 	 * The traditional way to tell PTRACE_SYSCALL entry/exit
2003 	 * is by counting.
2004 	 */
2005 	entry = !entry;
2006 
2007 	/* Make sure we got an appropriate message. */
2008 	ret = ptrace(PTRACE_GETEVENTMSG, tracee, NULL, &msg);
2009 	EXPECT_EQ(0, ret);
2010 	EXPECT_EQ(entry ? PTRACE_EVENTMSG_SYSCALL_ENTRY
2011 			: PTRACE_EVENTMSG_SYSCALL_EXIT, msg);
2012 
2013 	/*
2014 	 * Some architectures only support setting return values during
2015 	 * syscall exit under ptrace, and on exit the syscall number may
2016 	 * no longer be available. Therefore, save the initial sycall
2017 	 * number here, so it can be examined during both entry and exit
2018 	 * phases.
2019 	 */
2020 	if (entry)
2021 		self->syscall_nr = get_syscall(_metadata, tracee);
2022 
2023 	/*
2024 	 * Depending on the architecture's syscall setting abilities, we
2025 	 * pick which things to set during this phase (entry or exit).
2026 	 */
2027 	if (entry == ptrace_entry_set_syscall_nr)
2028 		syscall_nr = &syscall_nr_val;
2029 	if (entry == ptrace_entry_set_syscall_ret)
2030 		syscall_ret = &syscall_ret_val;
2031 
2032 	/* Now handle the actual rewriting cases. */
2033 	switch (self->syscall_nr) {
2034 	case __NR_getpid:
2035 		syscall_nr_val = __NR_getppid;
2036 		/* Never change syscall return for this case. */
2037 		syscall_ret = NULL;
2038 		break;
2039 	case __NR_gettid:
2040 		syscall_nr_val = -1;
2041 		syscall_ret_val = 45000;
2042 		break;
2043 	case __NR_openat:
2044 		syscall_nr_val = -1;
2045 		syscall_ret_val = -ESRCH;
2046 		break;
2047 	default:
2048 		/* Unhandled, do nothing. */
2049 		return;
2050 	}
2051 
2052 	__change_syscall(_metadata, tracee, syscall_nr, syscall_ret);
2053 }
2054 
2055 FIXTURE_VARIANT(TRACE_syscall) {
2056 	/*
2057 	 * All of the SECCOMP_RET_TRACE behaviors can be tested with either
2058 	 * SECCOMP_RET_TRACE+PTRACE_CONT or plain ptrace()+PTRACE_SYSCALL.
2059 	 * This indicates if we should use SECCOMP_RET_TRACE (false), or
2060 	 * ptrace (true).
2061 	 */
2062 	bool use_ptrace;
2063 };
2064 
2065 FIXTURE_VARIANT_ADD(TRACE_syscall, ptrace) {
2066 	.use_ptrace = true,
2067 };
2068 
2069 FIXTURE_VARIANT_ADD(TRACE_syscall, seccomp) {
2070 	.use_ptrace = false,
2071 };
2072 
2073 FIXTURE_SETUP(TRACE_syscall)
2074 {
2075 	struct sock_filter filter[] = {
2076 		BPF_STMT(BPF_LD|BPF_W|BPF_ABS,
2077 			offsetof(struct seccomp_data, nr)),
2078 		BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, __NR_getpid, 0, 1),
2079 		BPF_STMT(BPF_RET|BPF_K, SECCOMP_RET_TRACE | 0x1002),
2080 		BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, __NR_gettid, 0, 1),
2081 		BPF_STMT(BPF_RET|BPF_K, SECCOMP_RET_TRACE | 0x1003),
2082 		BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, __NR_openat, 0, 1),
2083 		BPF_STMT(BPF_RET|BPF_K, SECCOMP_RET_TRACE | 0x1004),
2084 		BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, __NR_getppid, 0, 1),
2085 		BPF_STMT(BPF_RET|BPF_K, SECCOMP_RET_TRACE | 0x1005),
2086 		BPF_STMT(BPF_RET|BPF_K, SECCOMP_RET_ALLOW),
2087 	};
2088 	struct sock_fprog prog = {
2089 		.len = (unsigned short)ARRAY_SIZE(filter),
2090 		.filter = filter,
2091 	};
2092 	long ret;
2093 
2094 	/* Prepare some testable syscall results. */
2095 	self->mytid = syscall(__NR_gettid);
2096 	ASSERT_GT(self->mytid, 0);
2097 	ASSERT_NE(self->mytid, 1) {
2098 		TH_LOG("Running this test as init is not supported. :)");
2099 	}
2100 
2101 	self->mypid = getpid();
2102 	ASSERT_GT(self->mypid, 0);
2103 	ASSERT_EQ(self->mytid, self->mypid);
2104 
2105 	self->parent = getppid();
2106 	ASSERT_GT(self->parent, 0);
2107 	ASSERT_NE(self->parent, self->mypid);
2108 
2109 	/* Launch tracer. */
2110 	self->tracer = setup_trace_fixture(_metadata,
2111 					   variant->use_ptrace ? tracer_ptrace
2112 							       : tracer_seccomp,
2113 					   self, variant->use_ptrace);
2114 
2115 	ret = prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
2116 	ASSERT_EQ(0, ret);
2117 
2118 	if (variant->use_ptrace)
2119 		return;
2120 
2121 	ret = prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &prog, 0, 0);
2122 	ASSERT_EQ(0, ret);
2123 }
2124 
2125 FIXTURE_TEARDOWN(TRACE_syscall)
2126 {
2127 	teardown_trace_fixture(_metadata, self->tracer);
2128 }
2129 
2130 TEST(negative_ENOSYS)
2131 {
2132 	/*
2133 	 * There should be no difference between an "internal" skip
2134 	 * and userspace asking for syscall "-1".
2135 	 */
2136 	errno = 0;
2137 	EXPECT_EQ(-1, syscall(-1));
2138 	EXPECT_EQ(errno, ENOSYS);
2139 	/* And no difference for "still not valid but not -1". */
2140 	errno = 0;
2141 	EXPECT_EQ(-1, syscall(-101));
2142 	EXPECT_EQ(errno, ENOSYS);
2143 }
2144 
2145 TEST_F(TRACE_syscall, negative_ENOSYS)
2146 {
2147 	negative_ENOSYS(_metadata);
2148 }
2149 
2150 TEST_F(TRACE_syscall, syscall_allowed)
2151 {
2152 	/* getppid works as expected (no changes). */
2153 	EXPECT_EQ(self->parent, syscall(__NR_getppid));
2154 	EXPECT_NE(self->mypid, syscall(__NR_getppid));
2155 }
2156 
2157 TEST_F(TRACE_syscall, syscall_redirected)
2158 {
2159 	/* getpid has been redirected to getppid as expected. */
2160 	EXPECT_EQ(self->parent, syscall(__NR_getpid));
2161 	EXPECT_NE(self->mypid, syscall(__NR_getpid));
2162 }
2163 
2164 TEST_F(TRACE_syscall, syscall_errno)
2165 {
2166 	/* Tracer should skip the open syscall, resulting in ESRCH. */
2167 	EXPECT_SYSCALL_RETURN(-ESRCH, syscall(__NR_openat));
2168 }
2169 
2170 TEST_F(TRACE_syscall, syscall_faked)
2171 {
2172 	/* Tracer skips the gettid syscall and store altered return value. */
2173 	EXPECT_SYSCALL_RETURN(45000, syscall(__NR_gettid));
2174 }
2175 
2176 TEST_F(TRACE_syscall, skip_after)
2177 {
2178 	struct sock_filter filter[] = {
2179 		BPF_STMT(BPF_LD|BPF_W|BPF_ABS,
2180 			offsetof(struct seccomp_data, nr)),
2181 		BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, __NR_getppid, 0, 1),
2182 		BPF_STMT(BPF_RET|BPF_K, SECCOMP_RET_ERRNO | EPERM),
2183 		BPF_STMT(BPF_RET|BPF_K, SECCOMP_RET_ALLOW),
2184 	};
2185 	struct sock_fprog prog = {
2186 		.len = (unsigned short)ARRAY_SIZE(filter),
2187 		.filter = filter,
2188 	};
2189 	long ret;
2190 
2191 	/* Install additional "errno on getppid" filter. */
2192 	ret = prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &prog, 0, 0);
2193 	ASSERT_EQ(0, ret);
2194 
2195 	/* Tracer will redirect getpid to getppid, and we should see EPERM. */
2196 	errno = 0;
2197 	EXPECT_EQ(-1, syscall(__NR_getpid));
2198 	EXPECT_EQ(EPERM, errno);
2199 }
2200 
2201 TEST_F_SIGNAL(TRACE_syscall, kill_after, SIGSYS)
2202 {
2203 	struct sock_filter filter[] = {
2204 		BPF_STMT(BPF_LD|BPF_W|BPF_ABS,
2205 			offsetof(struct seccomp_data, nr)),
2206 		BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, __NR_getppid, 0, 1),
2207 		BPF_STMT(BPF_RET|BPF_K, SECCOMP_RET_KILL),
2208 		BPF_STMT(BPF_RET|BPF_K, SECCOMP_RET_ALLOW),
2209 	};
2210 	struct sock_fprog prog = {
2211 		.len = (unsigned short)ARRAY_SIZE(filter),
2212 		.filter = filter,
2213 	};
2214 	long ret;
2215 
2216 	/* Install additional "death on getppid" filter. */
2217 	ret = prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &prog, 0, 0);
2218 	ASSERT_EQ(0, ret);
2219 
2220 	/* Tracer will redirect getpid to getppid, and we should die. */
2221 	EXPECT_NE(self->mypid, syscall(__NR_getpid));
2222 }
2223 
2224 TEST(seccomp_syscall)
2225 {
2226 	struct sock_filter filter[] = {
2227 		BPF_STMT(BPF_RET|BPF_K, SECCOMP_RET_ALLOW),
2228 	};
2229 	struct sock_fprog prog = {
2230 		.len = (unsigned short)ARRAY_SIZE(filter),
2231 		.filter = filter,
2232 	};
2233 	long ret;
2234 
2235 	ret = prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
2236 	ASSERT_EQ(0, ret) {
2237 		TH_LOG("Kernel does not support PR_SET_NO_NEW_PRIVS!");
2238 	}
2239 
2240 	/* Reject insane operation. */
2241 	ret = seccomp(-1, 0, &prog);
2242 	ASSERT_NE(ENOSYS, errno) {
2243 		TH_LOG("Kernel does not support seccomp syscall!");
2244 	}
2245 	EXPECT_EQ(EINVAL, errno) {
2246 		TH_LOG("Did not reject crazy op value!");
2247 	}
2248 
2249 	/* Reject strict with flags or pointer. */
2250 	ret = seccomp(SECCOMP_SET_MODE_STRICT, -1, NULL);
2251 	EXPECT_EQ(EINVAL, errno) {
2252 		TH_LOG("Did not reject mode strict with flags!");
2253 	}
2254 	ret = seccomp(SECCOMP_SET_MODE_STRICT, 0, &prog);
2255 	EXPECT_EQ(EINVAL, errno) {
2256 		TH_LOG("Did not reject mode strict with uargs!");
2257 	}
2258 
2259 	/* Reject insane args for filter. */
2260 	ret = seccomp(SECCOMP_SET_MODE_FILTER, -1, &prog);
2261 	EXPECT_EQ(EINVAL, errno) {
2262 		TH_LOG("Did not reject crazy filter flags!");
2263 	}
2264 	ret = seccomp(SECCOMP_SET_MODE_FILTER, 0, NULL);
2265 	EXPECT_EQ(EFAULT, errno) {
2266 		TH_LOG("Did not reject NULL filter!");
2267 	}
2268 
2269 	ret = seccomp(SECCOMP_SET_MODE_FILTER, 0, &prog);
2270 	EXPECT_EQ(0, errno) {
2271 		TH_LOG("Kernel does not support SECCOMP_SET_MODE_FILTER: %s",
2272 			strerror(errno));
2273 	}
2274 }
2275 
2276 TEST(seccomp_syscall_mode_lock)
2277 {
2278 	struct sock_filter filter[] = {
2279 		BPF_STMT(BPF_RET|BPF_K, SECCOMP_RET_ALLOW),
2280 	};
2281 	struct sock_fprog prog = {
2282 		.len = (unsigned short)ARRAY_SIZE(filter),
2283 		.filter = filter,
2284 	};
2285 	long ret;
2286 
2287 	ret = prctl(PR_SET_NO_NEW_PRIVS, 1, NULL, 0, 0);
2288 	ASSERT_EQ(0, ret) {
2289 		TH_LOG("Kernel does not support PR_SET_NO_NEW_PRIVS!");
2290 	}
2291 
2292 	ret = seccomp(SECCOMP_SET_MODE_FILTER, 0, &prog);
2293 	ASSERT_NE(ENOSYS, errno) {
2294 		TH_LOG("Kernel does not support seccomp syscall!");
2295 	}
2296 	EXPECT_EQ(0, ret) {
2297 		TH_LOG("Could not install filter!");
2298 	}
2299 
2300 	/* Make sure neither entry point will switch to strict. */
2301 	ret = prctl(PR_SET_SECCOMP, SECCOMP_MODE_STRICT, 0, 0, 0);
2302 	EXPECT_EQ(EINVAL, errno) {
2303 		TH_LOG("Switched to mode strict!");
2304 	}
2305 
2306 	ret = seccomp(SECCOMP_SET_MODE_STRICT, 0, NULL);
2307 	EXPECT_EQ(EINVAL, errno) {
2308 		TH_LOG("Switched to mode strict!");
2309 	}
2310 }
2311 
2312 /*
2313  * Test detection of known and unknown filter flags. Userspace needs to be able
2314  * to check if a filter flag is supported by the current kernel and a good way
2315  * of doing that is by attempting to enter filter mode, with the flag bit in
2316  * question set, and a NULL pointer for the _args_ parameter. EFAULT indicates
2317  * that the flag is valid and EINVAL indicates that the flag is invalid.
2318  */
2319 TEST(detect_seccomp_filter_flags)
2320 {
2321 	unsigned int flags[] = { SECCOMP_FILTER_FLAG_TSYNC,
2322 				 SECCOMP_FILTER_FLAG_LOG,
2323 				 SECCOMP_FILTER_FLAG_SPEC_ALLOW,
2324 				 SECCOMP_FILTER_FLAG_NEW_LISTENER,
2325 				 SECCOMP_FILTER_FLAG_TSYNC_ESRCH };
2326 	unsigned int exclusive[] = {
2327 				SECCOMP_FILTER_FLAG_TSYNC,
2328 				SECCOMP_FILTER_FLAG_NEW_LISTENER };
2329 	unsigned int flag, all_flags, exclusive_mask;
2330 	int i;
2331 	long ret;
2332 
2333 	/* Test detection of individual known-good filter flags */
2334 	for (i = 0, all_flags = 0; i < ARRAY_SIZE(flags); i++) {
2335 		int bits = 0;
2336 
2337 		flag = flags[i];
2338 		/* Make sure the flag is a single bit! */
2339 		while (flag) {
2340 			if (flag & 0x1)
2341 				bits ++;
2342 			flag >>= 1;
2343 		}
2344 		ASSERT_EQ(1, bits);
2345 		flag = flags[i];
2346 
2347 		ret = seccomp(SECCOMP_SET_MODE_FILTER, flag, NULL);
2348 		ASSERT_NE(ENOSYS, errno) {
2349 			TH_LOG("Kernel does not support seccomp syscall!");
2350 		}
2351 		EXPECT_EQ(-1, ret);
2352 		EXPECT_EQ(EFAULT, errno) {
2353 			TH_LOG("Failed to detect that a known-good filter flag (0x%X) is supported!",
2354 			       flag);
2355 		}
2356 
2357 		all_flags |= flag;
2358 	}
2359 
2360 	/*
2361 	 * Test detection of all known-good filter flags combined. But
2362 	 * for the exclusive flags we need to mask them out and try them
2363 	 * individually for the "all flags" testing.
2364 	 */
2365 	exclusive_mask = 0;
2366 	for (i = 0; i < ARRAY_SIZE(exclusive); i++)
2367 		exclusive_mask |= exclusive[i];
2368 	for (i = 0; i < ARRAY_SIZE(exclusive); i++) {
2369 		flag = all_flags & ~exclusive_mask;
2370 		flag |= exclusive[i];
2371 
2372 		ret = seccomp(SECCOMP_SET_MODE_FILTER, flag, NULL);
2373 		EXPECT_EQ(-1, ret);
2374 		EXPECT_EQ(EFAULT, errno) {
2375 			TH_LOG("Failed to detect that all known-good filter flags (0x%X) are supported!",
2376 			       flag);
2377 		}
2378 	}
2379 
2380 	/* Test detection of an unknown filter flags, without exclusives. */
2381 	flag = -1;
2382 	flag &= ~exclusive_mask;
2383 	ret = seccomp(SECCOMP_SET_MODE_FILTER, flag, NULL);
2384 	EXPECT_EQ(-1, ret);
2385 	EXPECT_EQ(EINVAL, errno) {
2386 		TH_LOG("Failed to detect that an unknown filter flag (0x%X) is unsupported!",
2387 		       flag);
2388 	}
2389 
2390 	/*
2391 	 * Test detection of an unknown filter flag that may simply need to be
2392 	 * added to this test
2393 	 */
2394 	flag = flags[ARRAY_SIZE(flags) - 1] << 1;
2395 	ret = seccomp(SECCOMP_SET_MODE_FILTER, flag, NULL);
2396 	EXPECT_EQ(-1, ret);
2397 	EXPECT_EQ(EINVAL, errno) {
2398 		TH_LOG("Failed to detect that an unknown filter flag (0x%X) is unsupported! Does a new flag need to be added to this test?",
2399 		       flag);
2400 	}
2401 }
2402 
2403 TEST(TSYNC_first)
2404 {
2405 	struct sock_filter filter[] = {
2406 		BPF_STMT(BPF_RET|BPF_K, SECCOMP_RET_ALLOW),
2407 	};
2408 	struct sock_fprog prog = {
2409 		.len = (unsigned short)ARRAY_SIZE(filter),
2410 		.filter = filter,
2411 	};
2412 	long ret;
2413 
2414 	ret = prctl(PR_SET_NO_NEW_PRIVS, 1, NULL, 0, 0);
2415 	ASSERT_EQ(0, ret) {
2416 		TH_LOG("Kernel does not support PR_SET_NO_NEW_PRIVS!");
2417 	}
2418 
2419 	ret = seccomp(SECCOMP_SET_MODE_FILTER, SECCOMP_FILTER_FLAG_TSYNC,
2420 		      &prog);
2421 	ASSERT_NE(ENOSYS, errno) {
2422 		TH_LOG("Kernel does not support seccomp syscall!");
2423 	}
2424 	EXPECT_EQ(0, ret) {
2425 		TH_LOG("Could not install initial filter with TSYNC!");
2426 	}
2427 }
2428 
2429 #define TSYNC_SIBLINGS 2
2430 struct tsync_sibling {
2431 	pthread_t tid;
2432 	pid_t system_tid;
2433 	sem_t *started;
2434 	pthread_cond_t *cond;
2435 	pthread_mutex_t *mutex;
2436 	int diverge;
2437 	int num_waits;
2438 	struct sock_fprog *prog;
2439 	struct __test_metadata *metadata;
2440 };
2441 
2442 /*
2443  * To avoid joining joined threads (which is not allowed by Bionic),
2444  * make sure we both successfully join and clear the tid to skip a
2445  * later join attempt during fixture teardown. Any remaining threads
2446  * will be directly killed during teardown.
2447  */
2448 #define PTHREAD_JOIN(tid, status)					\
2449 	do {								\
2450 		int _rc = pthread_join(tid, status);			\
2451 		if (_rc) {						\
2452 			TH_LOG("pthread_join of tid %u failed: %d\n",	\
2453 				(unsigned int)tid, _rc);		\
2454 		} else {						\
2455 			tid = 0;					\
2456 		}							\
2457 	} while (0)
2458 
2459 FIXTURE(TSYNC) {
2460 	struct sock_fprog root_prog, apply_prog;
2461 	struct tsync_sibling sibling[TSYNC_SIBLINGS];
2462 	sem_t started;
2463 	pthread_cond_t cond;
2464 	pthread_mutex_t mutex;
2465 	int sibling_count;
2466 };
2467 
2468 FIXTURE_SETUP(TSYNC)
2469 {
2470 	struct sock_filter root_filter[] = {
2471 		BPF_STMT(BPF_RET|BPF_K, SECCOMP_RET_ALLOW),
2472 	};
2473 	struct sock_filter apply_filter[] = {
2474 		BPF_STMT(BPF_LD|BPF_W|BPF_ABS,
2475 			offsetof(struct seccomp_data, nr)),
2476 		BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, __NR_read, 0, 1),
2477 		BPF_STMT(BPF_RET|BPF_K, SECCOMP_RET_KILL),
2478 		BPF_STMT(BPF_RET|BPF_K, SECCOMP_RET_ALLOW),
2479 	};
2480 
2481 	memset(&self->root_prog, 0, sizeof(self->root_prog));
2482 	memset(&self->apply_prog, 0, sizeof(self->apply_prog));
2483 	memset(&self->sibling, 0, sizeof(self->sibling));
2484 	self->root_prog.filter = malloc(sizeof(root_filter));
2485 	ASSERT_NE(NULL, self->root_prog.filter);
2486 	memcpy(self->root_prog.filter, &root_filter, sizeof(root_filter));
2487 	self->root_prog.len = (unsigned short)ARRAY_SIZE(root_filter);
2488 
2489 	self->apply_prog.filter = malloc(sizeof(apply_filter));
2490 	ASSERT_NE(NULL, self->apply_prog.filter);
2491 	memcpy(self->apply_prog.filter, &apply_filter, sizeof(apply_filter));
2492 	self->apply_prog.len = (unsigned short)ARRAY_SIZE(apply_filter);
2493 
2494 	self->sibling_count = 0;
2495 	pthread_mutex_init(&self->mutex, NULL);
2496 	pthread_cond_init(&self->cond, NULL);
2497 	sem_init(&self->started, 0, 0);
2498 	self->sibling[0].tid = 0;
2499 	self->sibling[0].cond = &self->cond;
2500 	self->sibling[0].started = &self->started;
2501 	self->sibling[0].mutex = &self->mutex;
2502 	self->sibling[0].diverge = 0;
2503 	self->sibling[0].num_waits = 1;
2504 	self->sibling[0].prog = &self->root_prog;
2505 	self->sibling[0].metadata = _metadata;
2506 	self->sibling[1].tid = 0;
2507 	self->sibling[1].cond = &self->cond;
2508 	self->sibling[1].started = &self->started;
2509 	self->sibling[1].mutex = &self->mutex;
2510 	self->sibling[1].diverge = 0;
2511 	self->sibling[1].prog = &self->root_prog;
2512 	self->sibling[1].num_waits = 1;
2513 	self->sibling[1].metadata = _metadata;
2514 }
2515 
2516 FIXTURE_TEARDOWN(TSYNC)
2517 {
2518 	int sib = 0;
2519 
2520 	if (self->root_prog.filter)
2521 		free(self->root_prog.filter);
2522 	if (self->apply_prog.filter)
2523 		free(self->apply_prog.filter);
2524 
2525 	for ( ; sib < self->sibling_count; ++sib) {
2526 		struct tsync_sibling *s = &self->sibling[sib];
2527 
2528 		if (!s->tid)
2529 			continue;
2530 		/*
2531 		 * If a thread is still running, it may be stuck, so hit
2532 		 * it over the head really hard.
2533 		 */
2534 		pthread_kill(s->tid, 9);
2535 	}
2536 	pthread_mutex_destroy(&self->mutex);
2537 	pthread_cond_destroy(&self->cond);
2538 	sem_destroy(&self->started);
2539 }
2540 
2541 void *tsync_sibling(void *data)
2542 {
2543 	long ret = 0;
2544 	struct tsync_sibling *me = data;
2545 
2546 	me->system_tid = syscall(__NR_gettid);
2547 
2548 	pthread_mutex_lock(me->mutex);
2549 	if (me->diverge) {
2550 		/* Just re-apply the root prog to fork the tree */
2551 		ret = prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER,
2552 				me->prog, 0, 0);
2553 	}
2554 	sem_post(me->started);
2555 	/* Return outside of started so parent notices failures. */
2556 	if (ret) {
2557 		pthread_mutex_unlock(me->mutex);
2558 		return (void *)SIBLING_EXIT_FAILURE;
2559 	}
2560 	do {
2561 		pthread_cond_wait(me->cond, me->mutex);
2562 		me->num_waits = me->num_waits - 1;
2563 	} while (me->num_waits);
2564 	pthread_mutex_unlock(me->mutex);
2565 
2566 	ret = prctl(PR_GET_NO_NEW_PRIVS, 0, 0, 0, 0);
2567 	if (!ret)
2568 		return (void *)SIBLING_EXIT_NEWPRIVS;
2569 	read(0, NULL, 0);
2570 	return (void *)SIBLING_EXIT_UNKILLED;
2571 }
2572 
2573 void tsync_start_sibling(struct tsync_sibling *sibling)
2574 {
2575 	pthread_create(&sibling->tid, NULL, tsync_sibling, (void *)sibling);
2576 }
2577 
2578 TEST_F(TSYNC, siblings_fail_prctl)
2579 {
2580 	long ret;
2581 	void *status;
2582 	struct sock_filter filter[] = {
2583 		BPF_STMT(BPF_LD|BPF_W|BPF_ABS,
2584 			offsetof(struct seccomp_data, nr)),
2585 		BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, __NR_prctl, 0, 1),
2586 		BPF_STMT(BPF_RET|BPF_K, SECCOMP_RET_ERRNO | EINVAL),
2587 		BPF_STMT(BPF_RET|BPF_K, SECCOMP_RET_ALLOW),
2588 	};
2589 	struct sock_fprog prog = {
2590 		.len = (unsigned short)ARRAY_SIZE(filter),
2591 		.filter = filter,
2592 	};
2593 
2594 	ASSERT_EQ(0, prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0)) {
2595 		TH_LOG("Kernel does not support PR_SET_NO_NEW_PRIVS!");
2596 	}
2597 
2598 	/* Check prctl failure detection by requesting sib 0 diverge. */
2599 	ret = seccomp(SECCOMP_SET_MODE_FILTER, 0, &prog);
2600 	ASSERT_NE(ENOSYS, errno) {
2601 		TH_LOG("Kernel does not support seccomp syscall!");
2602 	}
2603 	ASSERT_EQ(0, ret) {
2604 		TH_LOG("setting filter failed");
2605 	}
2606 
2607 	self->sibling[0].diverge = 1;
2608 	tsync_start_sibling(&self->sibling[0]);
2609 	tsync_start_sibling(&self->sibling[1]);
2610 
2611 	while (self->sibling_count < TSYNC_SIBLINGS) {
2612 		sem_wait(&self->started);
2613 		self->sibling_count++;
2614 	}
2615 
2616 	/* Signal the threads to clean up*/
2617 	pthread_mutex_lock(&self->mutex);
2618 	ASSERT_EQ(0, pthread_cond_broadcast(&self->cond)) {
2619 		TH_LOG("cond broadcast non-zero");
2620 	}
2621 	pthread_mutex_unlock(&self->mutex);
2622 
2623 	/* Ensure diverging sibling failed to call prctl. */
2624 	PTHREAD_JOIN(self->sibling[0].tid, &status);
2625 	EXPECT_EQ(SIBLING_EXIT_FAILURE, (long)status);
2626 	PTHREAD_JOIN(self->sibling[1].tid, &status);
2627 	EXPECT_EQ(SIBLING_EXIT_UNKILLED, (long)status);
2628 }
2629 
2630 TEST_F(TSYNC, two_siblings_with_ancestor)
2631 {
2632 	long ret;
2633 	void *status;
2634 
2635 	ASSERT_EQ(0, prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0)) {
2636 		TH_LOG("Kernel does not support PR_SET_NO_NEW_PRIVS!");
2637 	}
2638 
2639 	ret = seccomp(SECCOMP_SET_MODE_FILTER, 0, &self->root_prog);
2640 	ASSERT_NE(ENOSYS, errno) {
2641 		TH_LOG("Kernel does not support seccomp syscall!");
2642 	}
2643 	ASSERT_EQ(0, ret) {
2644 		TH_LOG("Kernel does not support SECCOMP_SET_MODE_FILTER!");
2645 	}
2646 	tsync_start_sibling(&self->sibling[0]);
2647 	tsync_start_sibling(&self->sibling[1]);
2648 
2649 	while (self->sibling_count < TSYNC_SIBLINGS) {
2650 		sem_wait(&self->started);
2651 		self->sibling_count++;
2652 	}
2653 
2654 	ret = seccomp(SECCOMP_SET_MODE_FILTER, SECCOMP_FILTER_FLAG_TSYNC,
2655 		      &self->apply_prog);
2656 	ASSERT_EQ(0, ret) {
2657 		TH_LOG("Could install filter on all threads!");
2658 	}
2659 	/* Tell the siblings to test the policy */
2660 	pthread_mutex_lock(&self->mutex);
2661 	ASSERT_EQ(0, pthread_cond_broadcast(&self->cond)) {
2662 		TH_LOG("cond broadcast non-zero");
2663 	}
2664 	pthread_mutex_unlock(&self->mutex);
2665 	/* Ensure they are both killed and don't exit cleanly. */
2666 	PTHREAD_JOIN(self->sibling[0].tid, &status);
2667 	EXPECT_EQ(0x0, (long)status);
2668 	PTHREAD_JOIN(self->sibling[1].tid, &status);
2669 	EXPECT_EQ(0x0, (long)status);
2670 }
2671 
2672 TEST_F(TSYNC, two_sibling_want_nnp)
2673 {
2674 	void *status;
2675 
2676 	/* start siblings before any prctl() operations */
2677 	tsync_start_sibling(&self->sibling[0]);
2678 	tsync_start_sibling(&self->sibling[1]);
2679 	while (self->sibling_count < TSYNC_SIBLINGS) {
2680 		sem_wait(&self->started);
2681 		self->sibling_count++;
2682 	}
2683 
2684 	/* Tell the siblings to test no policy */
2685 	pthread_mutex_lock(&self->mutex);
2686 	ASSERT_EQ(0, pthread_cond_broadcast(&self->cond)) {
2687 		TH_LOG("cond broadcast non-zero");
2688 	}
2689 	pthread_mutex_unlock(&self->mutex);
2690 
2691 	/* Ensure they are both upset about lacking nnp. */
2692 	PTHREAD_JOIN(self->sibling[0].tid, &status);
2693 	EXPECT_EQ(SIBLING_EXIT_NEWPRIVS, (long)status);
2694 	PTHREAD_JOIN(self->sibling[1].tid, &status);
2695 	EXPECT_EQ(SIBLING_EXIT_NEWPRIVS, (long)status);
2696 }
2697 
2698 TEST_F(TSYNC, two_siblings_with_no_filter)
2699 {
2700 	long ret;
2701 	void *status;
2702 
2703 	/* start siblings before any prctl() operations */
2704 	tsync_start_sibling(&self->sibling[0]);
2705 	tsync_start_sibling(&self->sibling[1]);
2706 	while (self->sibling_count < TSYNC_SIBLINGS) {
2707 		sem_wait(&self->started);
2708 		self->sibling_count++;
2709 	}
2710 
2711 	ASSERT_EQ(0, prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0)) {
2712 		TH_LOG("Kernel does not support PR_SET_NO_NEW_PRIVS!");
2713 	}
2714 
2715 	ret = seccomp(SECCOMP_SET_MODE_FILTER, SECCOMP_FILTER_FLAG_TSYNC,
2716 		      &self->apply_prog);
2717 	ASSERT_NE(ENOSYS, errno) {
2718 		TH_LOG("Kernel does not support seccomp syscall!");
2719 	}
2720 	ASSERT_EQ(0, ret) {
2721 		TH_LOG("Could install filter on all threads!");
2722 	}
2723 
2724 	/* Tell the siblings to test the policy */
2725 	pthread_mutex_lock(&self->mutex);
2726 	ASSERT_EQ(0, pthread_cond_broadcast(&self->cond)) {
2727 		TH_LOG("cond broadcast non-zero");
2728 	}
2729 	pthread_mutex_unlock(&self->mutex);
2730 
2731 	/* Ensure they are both killed and don't exit cleanly. */
2732 	PTHREAD_JOIN(self->sibling[0].tid, &status);
2733 	EXPECT_EQ(0x0, (long)status);
2734 	PTHREAD_JOIN(self->sibling[1].tid, &status);
2735 	EXPECT_EQ(0x0, (long)status);
2736 }
2737 
2738 TEST_F(TSYNC, two_siblings_with_one_divergence)
2739 {
2740 	long ret;
2741 	void *status;
2742 
2743 	ASSERT_EQ(0, prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0)) {
2744 		TH_LOG("Kernel does not support PR_SET_NO_NEW_PRIVS!");
2745 	}
2746 
2747 	ret = seccomp(SECCOMP_SET_MODE_FILTER, 0, &self->root_prog);
2748 	ASSERT_NE(ENOSYS, errno) {
2749 		TH_LOG("Kernel does not support seccomp syscall!");
2750 	}
2751 	ASSERT_EQ(0, ret) {
2752 		TH_LOG("Kernel does not support SECCOMP_SET_MODE_FILTER!");
2753 	}
2754 	self->sibling[0].diverge = 1;
2755 	tsync_start_sibling(&self->sibling[0]);
2756 	tsync_start_sibling(&self->sibling[1]);
2757 
2758 	while (self->sibling_count < TSYNC_SIBLINGS) {
2759 		sem_wait(&self->started);
2760 		self->sibling_count++;
2761 	}
2762 
2763 	ret = seccomp(SECCOMP_SET_MODE_FILTER, SECCOMP_FILTER_FLAG_TSYNC,
2764 		      &self->apply_prog);
2765 	ASSERT_EQ(self->sibling[0].system_tid, ret) {
2766 		TH_LOG("Did not fail on diverged sibling.");
2767 	}
2768 
2769 	/* Wake the threads */
2770 	pthread_mutex_lock(&self->mutex);
2771 	ASSERT_EQ(0, pthread_cond_broadcast(&self->cond)) {
2772 		TH_LOG("cond broadcast non-zero");
2773 	}
2774 	pthread_mutex_unlock(&self->mutex);
2775 
2776 	/* Ensure they are both unkilled. */
2777 	PTHREAD_JOIN(self->sibling[0].tid, &status);
2778 	EXPECT_EQ(SIBLING_EXIT_UNKILLED, (long)status);
2779 	PTHREAD_JOIN(self->sibling[1].tid, &status);
2780 	EXPECT_EQ(SIBLING_EXIT_UNKILLED, (long)status);
2781 }
2782 
2783 TEST_F(TSYNC, two_siblings_with_one_divergence_no_tid_in_err)
2784 {
2785 	long ret, flags;
2786 	void *status;
2787 
2788 	ASSERT_EQ(0, prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0)) {
2789 		TH_LOG("Kernel does not support PR_SET_NO_NEW_PRIVS!");
2790 	}
2791 
2792 	ret = seccomp(SECCOMP_SET_MODE_FILTER, 0, &self->root_prog);
2793 	ASSERT_NE(ENOSYS, errno) {
2794 		TH_LOG("Kernel does not support seccomp syscall!");
2795 	}
2796 	ASSERT_EQ(0, ret) {
2797 		TH_LOG("Kernel does not support SECCOMP_SET_MODE_FILTER!");
2798 	}
2799 	self->sibling[0].diverge = 1;
2800 	tsync_start_sibling(&self->sibling[0]);
2801 	tsync_start_sibling(&self->sibling[1]);
2802 
2803 	while (self->sibling_count < TSYNC_SIBLINGS) {
2804 		sem_wait(&self->started);
2805 		self->sibling_count++;
2806 	}
2807 
2808 	flags = SECCOMP_FILTER_FLAG_TSYNC | \
2809 		SECCOMP_FILTER_FLAG_TSYNC_ESRCH;
2810 	ret = seccomp(SECCOMP_SET_MODE_FILTER, flags, &self->apply_prog);
2811 	ASSERT_EQ(ESRCH, errno) {
2812 		TH_LOG("Did not return ESRCH for diverged sibling.");
2813 	}
2814 	ASSERT_EQ(-1, ret) {
2815 		TH_LOG("Did not fail on diverged sibling.");
2816 	}
2817 
2818 	/* Wake the threads */
2819 	pthread_mutex_lock(&self->mutex);
2820 	ASSERT_EQ(0, pthread_cond_broadcast(&self->cond)) {
2821 		TH_LOG("cond broadcast non-zero");
2822 	}
2823 	pthread_mutex_unlock(&self->mutex);
2824 
2825 	/* Ensure they are both unkilled. */
2826 	PTHREAD_JOIN(self->sibling[0].tid, &status);
2827 	EXPECT_EQ(SIBLING_EXIT_UNKILLED, (long)status);
2828 	PTHREAD_JOIN(self->sibling[1].tid, &status);
2829 	EXPECT_EQ(SIBLING_EXIT_UNKILLED, (long)status);
2830 }
2831 
2832 TEST_F(TSYNC, two_siblings_not_under_filter)
2833 {
2834 	long ret, sib;
2835 	void *status;
2836 	struct timespec delay = { .tv_nsec = 100000000 };
2837 
2838 	ASSERT_EQ(0, prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0)) {
2839 		TH_LOG("Kernel does not support PR_SET_NO_NEW_PRIVS!");
2840 	}
2841 
2842 	/*
2843 	 * Sibling 0 will have its own seccomp policy
2844 	 * and Sibling 1 will not be under seccomp at
2845 	 * all. Sibling 1 will enter seccomp and 0
2846 	 * will cause failure.
2847 	 */
2848 	self->sibling[0].diverge = 1;
2849 	tsync_start_sibling(&self->sibling[0]);
2850 	tsync_start_sibling(&self->sibling[1]);
2851 
2852 	while (self->sibling_count < TSYNC_SIBLINGS) {
2853 		sem_wait(&self->started);
2854 		self->sibling_count++;
2855 	}
2856 
2857 	ret = seccomp(SECCOMP_SET_MODE_FILTER, 0, &self->root_prog);
2858 	ASSERT_NE(ENOSYS, errno) {
2859 		TH_LOG("Kernel does not support seccomp syscall!");
2860 	}
2861 	ASSERT_EQ(0, ret) {
2862 		TH_LOG("Kernel does not support SECCOMP_SET_MODE_FILTER!");
2863 	}
2864 
2865 	ret = seccomp(SECCOMP_SET_MODE_FILTER, SECCOMP_FILTER_FLAG_TSYNC,
2866 		      &self->apply_prog);
2867 	ASSERT_EQ(ret, self->sibling[0].system_tid) {
2868 		TH_LOG("Did not fail on diverged sibling.");
2869 	}
2870 	sib = 1;
2871 	if (ret == self->sibling[0].system_tid)
2872 		sib = 0;
2873 
2874 	pthread_mutex_lock(&self->mutex);
2875 
2876 	/* Increment the other siblings num_waits so we can clean up
2877 	 * the one we just saw.
2878 	 */
2879 	self->sibling[!sib].num_waits += 1;
2880 
2881 	/* Signal the thread to clean up*/
2882 	ASSERT_EQ(0, pthread_cond_broadcast(&self->cond)) {
2883 		TH_LOG("cond broadcast non-zero");
2884 	}
2885 	pthread_mutex_unlock(&self->mutex);
2886 	PTHREAD_JOIN(self->sibling[sib].tid, &status);
2887 	EXPECT_EQ(SIBLING_EXIT_UNKILLED, (long)status);
2888 	/* Poll for actual task death. pthread_join doesn't guarantee it. */
2889 	while (!kill(self->sibling[sib].system_tid, 0))
2890 		nanosleep(&delay, NULL);
2891 	/* Switch to the remaining sibling */
2892 	sib = !sib;
2893 
2894 	ret = seccomp(SECCOMP_SET_MODE_FILTER, SECCOMP_FILTER_FLAG_TSYNC,
2895 		      &self->apply_prog);
2896 	ASSERT_EQ(0, ret) {
2897 		TH_LOG("Expected the remaining sibling to sync");
2898 	};
2899 
2900 	pthread_mutex_lock(&self->mutex);
2901 
2902 	/* If remaining sibling didn't have a chance to wake up during
2903 	 * the first broadcast, manually reduce the num_waits now.
2904 	 */
2905 	if (self->sibling[sib].num_waits > 1)
2906 		self->sibling[sib].num_waits = 1;
2907 	ASSERT_EQ(0, pthread_cond_broadcast(&self->cond)) {
2908 		TH_LOG("cond broadcast non-zero");
2909 	}
2910 	pthread_mutex_unlock(&self->mutex);
2911 	PTHREAD_JOIN(self->sibling[sib].tid, &status);
2912 	EXPECT_EQ(0, (long)status);
2913 	/* Poll for actual task death. pthread_join doesn't guarantee it. */
2914 	while (!kill(self->sibling[sib].system_tid, 0))
2915 		nanosleep(&delay, NULL);
2916 
2917 	ret = seccomp(SECCOMP_SET_MODE_FILTER, SECCOMP_FILTER_FLAG_TSYNC,
2918 		      &self->apply_prog);
2919 	ASSERT_EQ(0, ret);  /* just us chickens */
2920 }
2921 
2922 /* Make sure restarted syscalls are seen directly as "restart_syscall". */
2923 TEST(syscall_restart)
2924 {
2925 	long ret;
2926 	unsigned long msg;
2927 	pid_t child_pid;
2928 	int pipefd[2];
2929 	int status;
2930 	siginfo_t info = { };
2931 	struct sock_filter filter[] = {
2932 		BPF_STMT(BPF_LD|BPF_W|BPF_ABS,
2933 			 offsetof(struct seccomp_data, nr)),
2934 
2935 #ifdef __NR_sigreturn
2936 		BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, __NR_sigreturn, 7, 0),
2937 #endif
2938 		BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, __NR_read, 6, 0),
2939 		BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, __NR_exit, 5, 0),
2940 		BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, __NR_rt_sigreturn, 4, 0),
2941 		BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, __NR_nanosleep, 5, 0),
2942 		BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, __NR_clock_nanosleep, 4, 0),
2943 		BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, __NR_restart_syscall, 4, 0),
2944 
2945 		/* Allow __NR_write for easy logging. */
2946 		BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, __NR_write, 0, 1),
2947 		BPF_STMT(BPF_RET|BPF_K, SECCOMP_RET_ALLOW),
2948 		BPF_STMT(BPF_RET|BPF_K, SECCOMP_RET_KILL),
2949 		/* The nanosleep jump target. */
2950 		BPF_STMT(BPF_RET|BPF_K, SECCOMP_RET_TRACE|0x100),
2951 		/* The restart_syscall jump target. */
2952 		BPF_STMT(BPF_RET|BPF_K, SECCOMP_RET_TRACE|0x200),
2953 	};
2954 	struct sock_fprog prog = {
2955 		.len = (unsigned short)ARRAY_SIZE(filter),
2956 		.filter = filter,
2957 	};
2958 #if defined(__arm__)
2959 	struct utsname utsbuf;
2960 #endif
2961 
2962 	ASSERT_EQ(0, pipe(pipefd));
2963 
2964 	child_pid = fork();
2965 	ASSERT_LE(0, child_pid);
2966 	if (child_pid == 0) {
2967 		/* Child uses EXPECT not ASSERT to deliver status correctly. */
2968 		char buf = ' ';
2969 		struct timespec timeout = { };
2970 
2971 		/* Attach parent as tracer and stop. */
2972 		EXPECT_EQ(0, ptrace(PTRACE_TRACEME));
2973 		EXPECT_EQ(0, raise(SIGSTOP));
2974 
2975 		EXPECT_EQ(0, close(pipefd[1]));
2976 
2977 		EXPECT_EQ(0, prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0)) {
2978 			TH_LOG("Kernel does not support PR_SET_NO_NEW_PRIVS!");
2979 		}
2980 
2981 		ret = prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &prog, 0, 0);
2982 		EXPECT_EQ(0, ret) {
2983 			TH_LOG("Failed to install filter!");
2984 		}
2985 
2986 		EXPECT_EQ(1, read(pipefd[0], &buf, 1)) {
2987 			TH_LOG("Failed to read() sync from parent");
2988 		}
2989 		EXPECT_EQ('.', buf) {
2990 			TH_LOG("Failed to get sync data from read()");
2991 		}
2992 
2993 		/* Start nanosleep to be interrupted. */
2994 		timeout.tv_sec = 1;
2995 		errno = 0;
2996 		EXPECT_EQ(0, nanosleep(&timeout, NULL)) {
2997 			TH_LOG("Call to nanosleep() failed (errno %d)", errno);
2998 		}
2999 
3000 		/* Read final sync from parent. */
3001 		EXPECT_EQ(1, read(pipefd[0], &buf, 1)) {
3002 			TH_LOG("Failed final read() from parent");
3003 		}
3004 		EXPECT_EQ('!', buf) {
3005 			TH_LOG("Failed to get final data from read()");
3006 		}
3007 
3008 		/* Directly report the status of our test harness results. */
3009 		syscall(__NR_exit, _metadata->passed ? EXIT_SUCCESS
3010 						     : EXIT_FAILURE);
3011 	}
3012 	EXPECT_EQ(0, close(pipefd[0]));
3013 
3014 	/* Attach to child, setup options, and release. */
3015 	ASSERT_EQ(child_pid, waitpid(child_pid, &status, 0));
3016 	ASSERT_EQ(true, WIFSTOPPED(status));
3017 	ASSERT_EQ(0, ptrace(PTRACE_SETOPTIONS, child_pid, NULL,
3018 			    PTRACE_O_TRACESECCOMP));
3019 	ASSERT_EQ(0, ptrace(PTRACE_CONT, child_pid, NULL, 0));
3020 	ASSERT_EQ(1, write(pipefd[1], ".", 1));
3021 
3022 	/* Wait for nanosleep() to start. */
3023 	ASSERT_EQ(child_pid, waitpid(child_pid, &status, 0));
3024 	ASSERT_EQ(true, WIFSTOPPED(status));
3025 	ASSERT_EQ(SIGTRAP, WSTOPSIG(status));
3026 	ASSERT_EQ(PTRACE_EVENT_SECCOMP, (status >> 16));
3027 	ASSERT_EQ(0, ptrace(PTRACE_GETEVENTMSG, child_pid, NULL, &msg));
3028 	ASSERT_EQ(0x100, msg);
3029 	ret = get_syscall(_metadata, child_pid);
3030 	EXPECT_TRUE(ret == __NR_nanosleep || ret == __NR_clock_nanosleep);
3031 
3032 	/* Might as well check siginfo for sanity while we're here. */
3033 	ASSERT_EQ(0, ptrace(PTRACE_GETSIGINFO, child_pid, NULL, &info));
3034 	ASSERT_EQ(SIGTRAP, info.si_signo);
3035 	ASSERT_EQ(SIGTRAP | (PTRACE_EVENT_SECCOMP << 8), info.si_code);
3036 	EXPECT_EQ(0, info.si_errno);
3037 	EXPECT_EQ(getuid(), info.si_uid);
3038 	/* Verify signal delivery came from child (seccomp-triggered). */
3039 	EXPECT_EQ(child_pid, info.si_pid);
3040 
3041 	/* Interrupt nanosleep with SIGSTOP (which we'll need to handle). */
3042 	ASSERT_EQ(0, kill(child_pid, SIGSTOP));
3043 	ASSERT_EQ(0, ptrace(PTRACE_CONT, child_pid, NULL, 0));
3044 	ASSERT_EQ(child_pid, waitpid(child_pid, &status, 0));
3045 	ASSERT_EQ(true, WIFSTOPPED(status));
3046 	ASSERT_EQ(SIGSTOP, WSTOPSIG(status));
3047 	ASSERT_EQ(0, ptrace(PTRACE_GETSIGINFO, child_pid, NULL, &info));
3048 	/*
3049 	 * There is no siginfo on SIGSTOP any more, so we can't verify
3050 	 * signal delivery came from parent now (getpid() == info.si_pid).
3051 	 * https://lkml.kernel.org/r/CAGXu5jJaZAOzP1qFz66tYrtbuywqb+UN2SOA1VLHpCCOiYvYeg@mail.gmail.com
3052 	 * At least verify the SIGSTOP via PTRACE_GETSIGINFO.
3053 	 */
3054 	EXPECT_EQ(SIGSTOP, info.si_signo);
3055 
3056 	/* Restart nanosleep with SIGCONT, which triggers restart_syscall. */
3057 	ASSERT_EQ(0, kill(child_pid, SIGCONT));
3058 	ASSERT_EQ(0, ptrace(PTRACE_CONT, child_pid, NULL, 0));
3059 	ASSERT_EQ(child_pid, waitpid(child_pid, &status, 0));
3060 	ASSERT_EQ(true, WIFSTOPPED(status));
3061 	ASSERT_EQ(SIGCONT, WSTOPSIG(status));
3062 	ASSERT_EQ(0, ptrace(PTRACE_CONT, child_pid, NULL, 0));
3063 
3064 	/* Wait for restart_syscall() to start. */
3065 	ASSERT_EQ(child_pid, waitpid(child_pid, &status, 0));
3066 	ASSERT_EQ(true, WIFSTOPPED(status));
3067 	ASSERT_EQ(SIGTRAP, WSTOPSIG(status));
3068 	ASSERT_EQ(PTRACE_EVENT_SECCOMP, (status >> 16));
3069 	ASSERT_EQ(0, ptrace(PTRACE_GETEVENTMSG, child_pid, NULL, &msg));
3070 
3071 	ASSERT_EQ(0x200, msg);
3072 	ret = get_syscall(_metadata, child_pid);
3073 #if defined(__arm__)
3074 	/*
3075 	 * FIXME:
3076 	 * - native ARM registers do NOT expose true syscall.
3077 	 * - compat ARM registers on ARM64 DO expose true syscall.
3078 	 */
3079 	ASSERT_EQ(0, uname(&utsbuf));
3080 	if (strncmp(utsbuf.machine, "arm", 3) == 0) {
3081 		EXPECT_EQ(__NR_nanosleep, ret);
3082 	} else
3083 #endif
3084 	{
3085 		EXPECT_EQ(__NR_restart_syscall, ret);
3086 	}
3087 
3088 	/* Write again to end test. */
3089 	ASSERT_EQ(0, ptrace(PTRACE_CONT, child_pid, NULL, 0));
3090 	ASSERT_EQ(1, write(pipefd[1], "!", 1));
3091 	EXPECT_EQ(0, close(pipefd[1]));
3092 
3093 	ASSERT_EQ(child_pid, waitpid(child_pid, &status, 0));
3094 	if (WIFSIGNALED(status) || WEXITSTATUS(status))
3095 		_metadata->passed = 0;
3096 }
3097 
3098 TEST_SIGNAL(filter_flag_log, SIGSYS)
3099 {
3100 	struct sock_filter allow_filter[] = {
3101 		BPF_STMT(BPF_RET|BPF_K, SECCOMP_RET_ALLOW),
3102 	};
3103 	struct sock_filter kill_filter[] = {
3104 		BPF_STMT(BPF_LD|BPF_W|BPF_ABS,
3105 			offsetof(struct seccomp_data, nr)),
3106 		BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, __NR_getpid, 0, 1),
3107 		BPF_STMT(BPF_RET|BPF_K, SECCOMP_RET_KILL),
3108 		BPF_STMT(BPF_RET|BPF_K, SECCOMP_RET_ALLOW),
3109 	};
3110 	struct sock_fprog allow_prog = {
3111 		.len = (unsigned short)ARRAY_SIZE(allow_filter),
3112 		.filter = allow_filter,
3113 	};
3114 	struct sock_fprog kill_prog = {
3115 		.len = (unsigned short)ARRAY_SIZE(kill_filter),
3116 		.filter = kill_filter,
3117 	};
3118 	long ret;
3119 	pid_t parent = getppid();
3120 
3121 	ret = prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
3122 	ASSERT_EQ(0, ret);
3123 
3124 	/* Verify that the FILTER_FLAG_LOG flag isn't accepted in strict mode */
3125 	ret = seccomp(SECCOMP_SET_MODE_STRICT, SECCOMP_FILTER_FLAG_LOG,
3126 		      &allow_prog);
3127 	ASSERT_NE(ENOSYS, errno) {
3128 		TH_LOG("Kernel does not support seccomp syscall!");
3129 	}
3130 	EXPECT_NE(0, ret) {
3131 		TH_LOG("Kernel accepted FILTER_FLAG_LOG flag in strict mode!");
3132 	}
3133 	EXPECT_EQ(EINVAL, errno) {
3134 		TH_LOG("Kernel returned unexpected errno for FILTER_FLAG_LOG flag in strict mode!");
3135 	}
3136 
3137 	/* Verify that a simple, permissive filter can be added with no flags */
3138 	ret = seccomp(SECCOMP_SET_MODE_FILTER, 0, &allow_prog);
3139 	EXPECT_EQ(0, ret);
3140 
3141 	/* See if the same filter can be added with the FILTER_FLAG_LOG flag */
3142 	ret = seccomp(SECCOMP_SET_MODE_FILTER, SECCOMP_FILTER_FLAG_LOG,
3143 		      &allow_prog);
3144 	ASSERT_NE(EINVAL, errno) {
3145 		TH_LOG("Kernel does not support the FILTER_FLAG_LOG flag!");
3146 	}
3147 	EXPECT_EQ(0, ret);
3148 
3149 	/* Ensure that the kill filter works with the FILTER_FLAG_LOG flag */
3150 	ret = seccomp(SECCOMP_SET_MODE_FILTER, SECCOMP_FILTER_FLAG_LOG,
3151 		      &kill_prog);
3152 	EXPECT_EQ(0, ret);
3153 
3154 	EXPECT_EQ(parent, syscall(__NR_getppid));
3155 	/* getpid() should never return. */
3156 	EXPECT_EQ(0, syscall(__NR_getpid));
3157 }
3158 
3159 TEST(get_action_avail)
3160 {
3161 	__u32 actions[] = { SECCOMP_RET_KILL_THREAD, SECCOMP_RET_TRAP,
3162 			    SECCOMP_RET_ERRNO, SECCOMP_RET_TRACE,
3163 			    SECCOMP_RET_LOG,   SECCOMP_RET_ALLOW };
3164 	__u32 unknown_action = 0x10000000U;
3165 	int i;
3166 	long ret;
3167 
3168 	ret = seccomp(SECCOMP_GET_ACTION_AVAIL, 0, &actions[0]);
3169 	ASSERT_NE(ENOSYS, errno) {
3170 		TH_LOG("Kernel does not support seccomp syscall!");
3171 	}
3172 	ASSERT_NE(EINVAL, errno) {
3173 		TH_LOG("Kernel does not support SECCOMP_GET_ACTION_AVAIL operation!");
3174 	}
3175 	EXPECT_EQ(ret, 0);
3176 
3177 	for (i = 0; i < ARRAY_SIZE(actions); i++) {
3178 		ret = seccomp(SECCOMP_GET_ACTION_AVAIL, 0, &actions[i]);
3179 		EXPECT_EQ(ret, 0) {
3180 			TH_LOG("Expected action (0x%X) not available!",
3181 			       actions[i]);
3182 		}
3183 	}
3184 
3185 	/* Check that an unknown action is handled properly (EOPNOTSUPP) */
3186 	ret = seccomp(SECCOMP_GET_ACTION_AVAIL, 0, &unknown_action);
3187 	EXPECT_EQ(ret, -1);
3188 	EXPECT_EQ(errno, EOPNOTSUPP);
3189 }
3190 
3191 TEST(get_metadata)
3192 {
3193 	pid_t pid;
3194 	int pipefd[2];
3195 	char buf;
3196 	struct seccomp_metadata md;
3197 	long ret;
3198 
3199 	/* Only real root can get metadata. */
3200 	if (geteuid()) {
3201 		SKIP(return, "get_metadata requires real root");
3202 		return;
3203 	}
3204 
3205 	ASSERT_EQ(0, pipe(pipefd));
3206 
3207 	pid = fork();
3208 	ASSERT_GE(pid, 0);
3209 	if (pid == 0) {
3210 		struct sock_filter filter[] = {
3211 			BPF_STMT(BPF_RET|BPF_K, SECCOMP_RET_ALLOW),
3212 		};
3213 		struct sock_fprog prog = {
3214 			.len = (unsigned short)ARRAY_SIZE(filter),
3215 			.filter = filter,
3216 		};
3217 
3218 		/* one with log, one without */
3219 		EXPECT_EQ(0, seccomp(SECCOMP_SET_MODE_FILTER,
3220 				     SECCOMP_FILTER_FLAG_LOG, &prog));
3221 		EXPECT_EQ(0, seccomp(SECCOMP_SET_MODE_FILTER, 0, &prog));
3222 
3223 		EXPECT_EQ(0, close(pipefd[0]));
3224 		ASSERT_EQ(1, write(pipefd[1], "1", 1));
3225 		ASSERT_EQ(0, close(pipefd[1]));
3226 
3227 		while (1)
3228 			sleep(100);
3229 	}
3230 
3231 	ASSERT_EQ(0, close(pipefd[1]));
3232 	ASSERT_EQ(1, read(pipefd[0], &buf, 1));
3233 
3234 	ASSERT_EQ(0, ptrace(PTRACE_ATTACH, pid));
3235 	ASSERT_EQ(pid, waitpid(pid, NULL, 0));
3236 
3237 	/* Past here must not use ASSERT or child process is never killed. */
3238 
3239 	md.filter_off = 0;
3240 	errno = 0;
3241 	ret = ptrace(PTRACE_SECCOMP_GET_METADATA, pid, sizeof(md), &md);
3242 	EXPECT_EQ(sizeof(md), ret) {
3243 		if (errno == EINVAL)
3244 			SKIP(goto skip, "Kernel does not support PTRACE_SECCOMP_GET_METADATA (missing CONFIG_CHECKPOINT_RESTORE?)");
3245 	}
3246 
3247 	EXPECT_EQ(md.flags, SECCOMP_FILTER_FLAG_LOG);
3248 	EXPECT_EQ(md.filter_off, 0);
3249 
3250 	md.filter_off = 1;
3251 	ret = ptrace(PTRACE_SECCOMP_GET_METADATA, pid, sizeof(md), &md);
3252 	EXPECT_EQ(sizeof(md), ret);
3253 	EXPECT_EQ(md.flags, 0);
3254 	EXPECT_EQ(md.filter_off, 1);
3255 
3256 skip:
3257 	ASSERT_EQ(0, kill(pid, SIGKILL));
3258 }
3259 
3260 static int user_notif_syscall(int nr, unsigned int flags)
3261 {
3262 	struct sock_filter filter[] = {
3263 		BPF_STMT(BPF_LD|BPF_W|BPF_ABS,
3264 			offsetof(struct seccomp_data, nr)),
3265 		BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, nr, 0, 1),
3266 		BPF_STMT(BPF_RET|BPF_K, SECCOMP_RET_USER_NOTIF),
3267 		BPF_STMT(BPF_RET|BPF_K, SECCOMP_RET_ALLOW),
3268 	};
3269 
3270 	struct sock_fprog prog = {
3271 		.len = (unsigned short)ARRAY_SIZE(filter),
3272 		.filter = filter,
3273 	};
3274 
3275 	return seccomp(SECCOMP_SET_MODE_FILTER, flags, &prog);
3276 }
3277 
3278 #define USER_NOTIF_MAGIC INT_MAX
3279 TEST(user_notification_basic)
3280 {
3281 	pid_t pid;
3282 	long ret;
3283 	int status, listener;
3284 	struct seccomp_notif req = {};
3285 	struct seccomp_notif_resp resp = {};
3286 	struct pollfd pollfd;
3287 
3288 	struct sock_filter filter[] = {
3289 		BPF_STMT(BPF_RET|BPF_K, SECCOMP_RET_ALLOW),
3290 	};
3291 	struct sock_fprog prog = {
3292 		.len = (unsigned short)ARRAY_SIZE(filter),
3293 		.filter = filter,
3294 	};
3295 
3296 	ret = prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
3297 	ASSERT_EQ(0, ret) {
3298 		TH_LOG("Kernel does not support PR_SET_NO_NEW_PRIVS!");
3299 	}
3300 
3301 	pid = fork();
3302 	ASSERT_GE(pid, 0);
3303 
3304 	/* Check that we get -ENOSYS with no listener attached */
3305 	if (pid == 0) {
3306 		if (user_notif_syscall(__NR_getppid, 0) < 0)
3307 			exit(1);
3308 		ret = syscall(__NR_getppid);
3309 		exit(ret >= 0 || errno != ENOSYS);
3310 	}
3311 
3312 	EXPECT_EQ(waitpid(pid, &status, 0), pid);
3313 	EXPECT_EQ(true, WIFEXITED(status));
3314 	EXPECT_EQ(0, WEXITSTATUS(status));
3315 
3316 	/* Add some no-op filters for grins. */
3317 	EXPECT_EQ(seccomp(SECCOMP_SET_MODE_FILTER, 0, &prog), 0);
3318 	EXPECT_EQ(seccomp(SECCOMP_SET_MODE_FILTER, 0, &prog), 0);
3319 	EXPECT_EQ(seccomp(SECCOMP_SET_MODE_FILTER, 0, &prog), 0);
3320 	EXPECT_EQ(seccomp(SECCOMP_SET_MODE_FILTER, 0, &prog), 0);
3321 
3322 	/* Check that the basic notification machinery works */
3323 	listener = user_notif_syscall(__NR_getppid,
3324 				      SECCOMP_FILTER_FLAG_NEW_LISTENER);
3325 	ASSERT_GE(listener, 0);
3326 
3327 	/* Installing a second listener in the chain should EBUSY */
3328 	EXPECT_EQ(user_notif_syscall(__NR_getppid,
3329 				     SECCOMP_FILTER_FLAG_NEW_LISTENER),
3330 		  -1);
3331 	EXPECT_EQ(errno, EBUSY);
3332 
3333 	pid = fork();
3334 	ASSERT_GE(pid, 0);
3335 
3336 	if (pid == 0) {
3337 		ret = syscall(__NR_getppid);
3338 		exit(ret != USER_NOTIF_MAGIC);
3339 	}
3340 
3341 	pollfd.fd = listener;
3342 	pollfd.events = POLLIN | POLLOUT;
3343 
3344 	EXPECT_GT(poll(&pollfd, 1, -1), 0);
3345 	EXPECT_EQ(pollfd.revents, POLLIN);
3346 
3347 	/* Test that we can't pass garbage to the kernel. */
3348 	memset(&req, 0, sizeof(req));
3349 	req.pid = -1;
3350 	errno = 0;
3351 	ret = ioctl(listener, SECCOMP_IOCTL_NOTIF_RECV, &req);
3352 	EXPECT_EQ(-1, ret);
3353 	EXPECT_EQ(EINVAL, errno);
3354 
3355 	if (ret) {
3356 		req.pid = 0;
3357 		EXPECT_EQ(ioctl(listener, SECCOMP_IOCTL_NOTIF_RECV, &req), 0);
3358 	}
3359 
3360 	pollfd.fd = listener;
3361 	pollfd.events = POLLIN | POLLOUT;
3362 
3363 	EXPECT_GT(poll(&pollfd, 1, -1), 0);
3364 	EXPECT_EQ(pollfd.revents, POLLOUT);
3365 
3366 	EXPECT_EQ(req.data.nr,  __NR_getppid);
3367 
3368 	resp.id = req.id;
3369 	resp.error = 0;
3370 	resp.val = USER_NOTIF_MAGIC;
3371 
3372 	/* check that we make sure flags == 0 */
3373 	resp.flags = 1;
3374 	EXPECT_EQ(ioctl(listener, SECCOMP_IOCTL_NOTIF_SEND, &resp), -1);
3375 	EXPECT_EQ(errno, EINVAL);
3376 
3377 	resp.flags = 0;
3378 	EXPECT_EQ(ioctl(listener, SECCOMP_IOCTL_NOTIF_SEND, &resp), 0);
3379 
3380 	EXPECT_EQ(waitpid(pid, &status, 0), pid);
3381 	EXPECT_EQ(true, WIFEXITED(status));
3382 	EXPECT_EQ(0, WEXITSTATUS(status));
3383 }
3384 
3385 TEST(user_notification_with_tsync)
3386 {
3387 	int ret;
3388 	unsigned int flags;
3389 
3390 	ret = prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
3391 	ASSERT_EQ(0, ret) {
3392 		TH_LOG("Kernel does not support PR_SET_NO_NEW_PRIVS!");
3393 	}
3394 
3395 	/* these were exclusive */
3396 	flags = SECCOMP_FILTER_FLAG_NEW_LISTENER |
3397 		SECCOMP_FILTER_FLAG_TSYNC;
3398 	ASSERT_EQ(-1, user_notif_syscall(__NR_getppid, flags));
3399 	ASSERT_EQ(EINVAL, errno);
3400 
3401 	/* but now they're not */
3402 	flags |= SECCOMP_FILTER_FLAG_TSYNC_ESRCH;
3403 	ret = user_notif_syscall(__NR_getppid, flags);
3404 	close(ret);
3405 	ASSERT_LE(0, ret);
3406 }
3407 
3408 TEST(user_notification_kill_in_middle)
3409 {
3410 	pid_t pid;
3411 	long ret;
3412 	int listener;
3413 	struct seccomp_notif req = {};
3414 	struct seccomp_notif_resp resp = {};
3415 
3416 	ret = prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
3417 	ASSERT_EQ(0, ret) {
3418 		TH_LOG("Kernel does not support PR_SET_NO_NEW_PRIVS!");
3419 	}
3420 
3421 	listener = user_notif_syscall(__NR_getppid,
3422 				      SECCOMP_FILTER_FLAG_NEW_LISTENER);
3423 	ASSERT_GE(listener, 0);
3424 
3425 	/*
3426 	 * Check that nothing bad happens when we kill the task in the middle
3427 	 * of a syscall.
3428 	 */
3429 	pid = fork();
3430 	ASSERT_GE(pid, 0);
3431 
3432 	if (pid == 0) {
3433 		ret = syscall(__NR_getppid);
3434 		exit(ret != USER_NOTIF_MAGIC);
3435 	}
3436 
3437 	EXPECT_EQ(ioctl(listener, SECCOMP_IOCTL_NOTIF_RECV, &req), 0);
3438 	EXPECT_EQ(ioctl(listener, SECCOMP_IOCTL_NOTIF_ID_VALID, &req.id), 0);
3439 
3440 	EXPECT_EQ(kill(pid, SIGKILL), 0);
3441 	EXPECT_EQ(waitpid(pid, NULL, 0), pid);
3442 
3443 	EXPECT_EQ(ioctl(listener, SECCOMP_IOCTL_NOTIF_ID_VALID, &req.id), -1);
3444 
3445 	resp.id = req.id;
3446 	ret = ioctl(listener, SECCOMP_IOCTL_NOTIF_SEND, &resp);
3447 	EXPECT_EQ(ret, -1);
3448 	EXPECT_EQ(errno, ENOENT);
3449 }
3450 
3451 static int handled = -1;
3452 
3453 static void signal_handler(int signal)
3454 {
3455 	if (write(handled, "c", 1) != 1)
3456 		perror("write from signal");
3457 }
3458 
3459 TEST(user_notification_signal)
3460 {
3461 	pid_t pid;
3462 	long ret;
3463 	int status, listener, sk_pair[2];
3464 	struct seccomp_notif req = {};
3465 	struct seccomp_notif_resp resp = {};
3466 	char c;
3467 
3468 	ret = prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
3469 	ASSERT_EQ(0, ret) {
3470 		TH_LOG("Kernel does not support PR_SET_NO_NEW_PRIVS!");
3471 	}
3472 
3473 	ASSERT_EQ(socketpair(PF_LOCAL, SOCK_SEQPACKET, 0, sk_pair), 0);
3474 
3475 	listener = user_notif_syscall(__NR_gettid,
3476 				      SECCOMP_FILTER_FLAG_NEW_LISTENER);
3477 	ASSERT_GE(listener, 0);
3478 
3479 	pid = fork();
3480 	ASSERT_GE(pid, 0);
3481 
3482 	if (pid == 0) {
3483 		close(sk_pair[0]);
3484 		handled = sk_pair[1];
3485 		if (signal(SIGUSR1, signal_handler) == SIG_ERR) {
3486 			perror("signal");
3487 			exit(1);
3488 		}
3489 		/*
3490 		 * ERESTARTSYS behavior is a bit hard to test, because we need
3491 		 * to rely on a signal that has not yet been handled. Let's at
3492 		 * least check that the error code gets propagated through, and
3493 		 * hope that it doesn't break when there is actually a signal :)
3494 		 */
3495 		ret = syscall(__NR_gettid);
3496 		exit(!(ret == -1 && errno == 512));
3497 	}
3498 
3499 	close(sk_pair[1]);
3500 
3501 	memset(&req, 0, sizeof(req));
3502 	EXPECT_EQ(ioctl(listener, SECCOMP_IOCTL_NOTIF_RECV, &req), 0);
3503 
3504 	EXPECT_EQ(kill(pid, SIGUSR1), 0);
3505 
3506 	/*
3507 	 * Make sure the signal really is delivered, which means we're not
3508 	 * stuck in the user notification code any more and the notification
3509 	 * should be dead.
3510 	 */
3511 	EXPECT_EQ(read(sk_pair[0], &c, 1), 1);
3512 
3513 	resp.id = req.id;
3514 	resp.error = -EPERM;
3515 	resp.val = 0;
3516 
3517 	EXPECT_EQ(ioctl(listener, SECCOMP_IOCTL_NOTIF_SEND, &resp), -1);
3518 	EXPECT_EQ(errno, ENOENT);
3519 
3520 	memset(&req, 0, sizeof(req));
3521 	EXPECT_EQ(ioctl(listener, SECCOMP_IOCTL_NOTIF_RECV, &req), 0);
3522 
3523 	resp.id = req.id;
3524 	resp.error = -512; /* -ERESTARTSYS */
3525 	resp.val = 0;
3526 
3527 	EXPECT_EQ(ioctl(listener, SECCOMP_IOCTL_NOTIF_SEND, &resp), 0);
3528 
3529 	EXPECT_EQ(waitpid(pid, &status, 0), pid);
3530 	EXPECT_EQ(true, WIFEXITED(status));
3531 	EXPECT_EQ(0, WEXITSTATUS(status));
3532 }
3533 
3534 TEST(user_notification_closed_listener)
3535 {
3536 	pid_t pid;
3537 	long ret;
3538 	int status, listener;
3539 
3540 	ret = prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
3541 	ASSERT_EQ(0, ret) {
3542 		TH_LOG("Kernel does not support PR_SET_NO_NEW_PRIVS!");
3543 	}
3544 
3545 	listener = user_notif_syscall(__NR_getppid,
3546 				      SECCOMP_FILTER_FLAG_NEW_LISTENER);
3547 	ASSERT_GE(listener, 0);
3548 
3549 	/*
3550 	 * Check that we get an ENOSYS when the listener is closed.
3551 	 */
3552 	pid = fork();
3553 	ASSERT_GE(pid, 0);
3554 	if (pid == 0) {
3555 		close(listener);
3556 		ret = syscall(__NR_getppid);
3557 		exit(ret != -1 && errno != ENOSYS);
3558 	}
3559 
3560 	close(listener);
3561 
3562 	EXPECT_EQ(waitpid(pid, &status, 0), pid);
3563 	EXPECT_EQ(true, WIFEXITED(status));
3564 	EXPECT_EQ(0, WEXITSTATUS(status));
3565 }
3566 
3567 /*
3568  * Check that a pid in a child namespace still shows up as valid in ours.
3569  */
3570 TEST(user_notification_child_pid_ns)
3571 {
3572 	pid_t pid;
3573 	int status, listener;
3574 	struct seccomp_notif req = {};
3575 	struct seccomp_notif_resp resp = {};
3576 
3577 	ASSERT_EQ(unshare(CLONE_NEWUSER | CLONE_NEWPID), 0) {
3578 		if (errno == EINVAL)
3579 			SKIP(return, "kernel missing CLONE_NEWUSER support");
3580 	};
3581 
3582 	listener = user_notif_syscall(__NR_getppid,
3583 				      SECCOMP_FILTER_FLAG_NEW_LISTENER);
3584 	ASSERT_GE(listener, 0);
3585 
3586 	pid = fork();
3587 	ASSERT_GE(pid, 0);
3588 
3589 	if (pid == 0)
3590 		exit(syscall(__NR_getppid) != USER_NOTIF_MAGIC);
3591 
3592 	EXPECT_EQ(ioctl(listener, SECCOMP_IOCTL_NOTIF_RECV, &req), 0);
3593 	EXPECT_EQ(req.pid, pid);
3594 
3595 	resp.id = req.id;
3596 	resp.error = 0;
3597 	resp.val = USER_NOTIF_MAGIC;
3598 
3599 	EXPECT_EQ(ioctl(listener, SECCOMP_IOCTL_NOTIF_SEND, &resp), 0);
3600 
3601 	EXPECT_EQ(waitpid(pid, &status, 0), pid);
3602 	EXPECT_EQ(true, WIFEXITED(status));
3603 	EXPECT_EQ(0, WEXITSTATUS(status));
3604 	close(listener);
3605 }
3606 
3607 /*
3608  * Check that a pid in a sibling (i.e. unrelated) namespace shows up as 0, i.e.
3609  * invalid.
3610  */
3611 TEST(user_notification_sibling_pid_ns)
3612 {
3613 	pid_t pid, pid2;
3614 	int status, listener;
3615 	struct seccomp_notif req = {};
3616 	struct seccomp_notif_resp resp = {};
3617 
3618 	ASSERT_EQ(prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0), 0) {
3619 		TH_LOG("Kernel does not support PR_SET_NO_NEW_PRIVS!");
3620 	}
3621 
3622 	listener = user_notif_syscall(__NR_getppid,
3623 				      SECCOMP_FILTER_FLAG_NEW_LISTENER);
3624 	ASSERT_GE(listener, 0);
3625 
3626 	pid = fork();
3627 	ASSERT_GE(pid, 0);
3628 
3629 	if (pid == 0) {
3630 		ASSERT_EQ(unshare(CLONE_NEWPID), 0);
3631 
3632 		pid2 = fork();
3633 		ASSERT_GE(pid2, 0);
3634 
3635 		if (pid2 == 0)
3636 			exit(syscall(__NR_getppid) != USER_NOTIF_MAGIC);
3637 
3638 		EXPECT_EQ(waitpid(pid2, &status, 0), pid2);
3639 		EXPECT_EQ(true, WIFEXITED(status));
3640 		EXPECT_EQ(0, WEXITSTATUS(status));
3641 		exit(WEXITSTATUS(status));
3642 	}
3643 
3644 	/* Create the sibling ns, and sibling in it. */
3645 	ASSERT_EQ(unshare(CLONE_NEWPID), 0) {
3646 		if (errno == EPERM)
3647 			SKIP(return, "CLONE_NEWPID requires CAP_SYS_ADMIN");
3648 	}
3649 	ASSERT_EQ(errno, 0);
3650 
3651 	pid2 = fork();
3652 	ASSERT_GE(pid2, 0);
3653 
3654 	if (pid2 == 0) {
3655 		ASSERT_EQ(ioctl(listener, SECCOMP_IOCTL_NOTIF_RECV, &req), 0);
3656 		/*
3657 		 * The pid should be 0, i.e. the task is in some namespace that
3658 		 * we can't "see".
3659 		 */
3660 		EXPECT_EQ(req.pid, 0);
3661 
3662 		resp.id = req.id;
3663 		resp.error = 0;
3664 		resp.val = USER_NOTIF_MAGIC;
3665 
3666 		ASSERT_EQ(ioctl(listener, SECCOMP_IOCTL_NOTIF_SEND, &resp), 0);
3667 		exit(0);
3668 	}
3669 
3670 	close(listener);
3671 
3672 	EXPECT_EQ(waitpid(pid, &status, 0), pid);
3673 	EXPECT_EQ(true, WIFEXITED(status));
3674 	EXPECT_EQ(0, WEXITSTATUS(status));
3675 
3676 	EXPECT_EQ(waitpid(pid2, &status, 0), pid2);
3677 	EXPECT_EQ(true, WIFEXITED(status));
3678 	EXPECT_EQ(0, WEXITSTATUS(status));
3679 }
3680 
3681 TEST(user_notification_fault_recv)
3682 {
3683 	pid_t pid;
3684 	int status, listener;
3685 	struct seccomp_notif req = {};
3686 	struct seccomp_notif_resp resp = {};
3687 
3688 	ASSERT_EQ(unshare(CLONE_NEWUSER), 0);
3689 
3690 	listener = user_notif_syscall(__NR_getppid,
3691 				      SECCOMP_FILTER_FLAG_NEW_LISTENER);
3692 	ASSERT_GE(listener, 0);
3693 
3694 	pid = fork();
3695 	ASSERT_GE(pid, 0);
3696 
3697 	if (pid == 0)
3698 		exit(syscall(__NR_getppid) != USER_NOTIF_MAGIC);
3699 
3700 	/* Do a bad recv() */
3701 	EXPECT_EQ(ioctl(listener, SECCOMP_IOCTL_NOTIF_RECV, NULL), -1);
3702 	EXPECT_EQ(errno, EFAULT);
3703 
3704 	/* We should still be able to receive this notification, though. */
3705 	EXPECT_EQ(ioctl(listener, SECCOMP_IOCTL_NOTIF_RECV, &req), 0);
3706 	EXPECT_EQ(req.pid, pid);
3707 
3708 	resp.id = req.id;
3709 	resp.error = 0;
3710 	resp.val = USER_NOTIF_MAGIC;
3711 
3712 	EXPECT_EQ(ioctl(listener, SECCOMP_IOCTL_NOTIF_SEND, &resp), 0);
3713 
3714 	EXPECT_EQ(waitpid(pid, &status, 0), pid);
3715 	EXPECT_EQ(true, WIFEXITED(status));
3716 	EXPECT_EQ(0, WEXITSTATUS(status));
3717 }
3718 
3719 TEST(seccomp_get_notif_sizes)
3720 {
3721 	struct seccomp_notif_sizes sizes;
3722 
3723 	ASSERT_EQ(seccomp(SECCOMP_GET_NOTIF_SIZES, 0, &sizes), 0);
3724 	EXPECT_EQ(sizes.seccomp_notif, sizeof(struct seccomp_notif));
3725 	EXPECT_EQ(sizes.seccomp_notif_resp, sizeof(struct seccomp_notif_resp));
3726 }
3727 
3728 TEST(user_notification_continue)
3729 {
3730 	pid_t pid;
3731 	long ret;
3732 	int status, listener;
3733 	struct seccomp_notif req = {};
3734 	struct seccomp_notif_resp resp = {};
3735 	struct pollfd pollfd;
3736 
3737 	ret = prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
3738 	ASSERT_EQ(0, ret) {
3739 		TH_LOG("Kernel does not support PR_SET_NO_NEW_PRIVS!");
3740 	}
3741 
3742 	listener = user_notif_syscall(__NR_dup, SECCOMP_FILTER_FLAG_NEW_LISTENER);
3743 	ASSERT_GE(listener, 0);
3744 
3745 	pid = fork();
3746 	ASSERT_GE(pid, 0);
3747 
3748 	if (pid == 0) {
3749 		int dup_fd, pipe_fds[2];
3750 		pid_t self;
3751 
3752 		ASSERT_GE(pipe(pipe_fds), 0);
3753 
3754 		dup_fd = dup(pipe_fds[0]);
3755 		ASSERT_GE(dup_fd, 0);
3756 		EXPECT_NE(pipe_fds[0], dup_fd);
3757 
3758 		self = getpid();
3759 		ASSERT_EQ(filecmp(self, self, pipe_fds[0], dup_fd), 0);
3760 		exit(0);
3761 	}
3762 
3763 	pollfd.fd = listener;
3764 	pollfd.events = POLLIN | POLLOUT;
3765 
3766 	EXPECT_GT(poll(&pollfd, 1, -1), 0);
3767 	EXPECT_EQ(pollfd.revents, POLLIN);
3768 
3769 	EXPECT_EQ(ioctl(listener, SECCOMP_IOCTL_NOTIF_RECV, &req), 0);
3770 
3771 	pollfd.fd = listener;
3772 	pollfd.events = POLLIN | POLLOUT;
3773 
3774 	EXPECT_GT(poll(&pollfd, 1, -1), 0);
3775 	EXPECT_EQ(pollfd.revents, POLLOUT);
3776 
3777 	EXPECT_EQ(req.data.nr, __NR_dup);
3778 
3779 	resp.id = req.id;
3780 	resp.flags = SECCOMP_USER_NOTIF_FLAG_CONTINUE;
3781 
3782 	/*
3783 	 * Verify that setting SECCOMP_USER_NOTIF_FLAG_CONTINUE enforces other
3784 	 * args be set to 0.
3785 	 */
3786 	resp.error = 0;
3787 	resp.val = USER_NOTIF_MAGIC;
3788 	EXPECT_EQ(ioctl(listener, SECCOMP_IOCTL_NOTIF_SEND, &resp), -1);
3789 	EXPECT_EQ(errno, EINVAL);
3790 
3791 	resp.error = USER_NOTIF_MAGIC;
3792 	resp.val = 0;
3793 	EXPECT_EQ(ioctl(listener, SECCOMP_IOCTL_NOTIF_SEND, &resp), -1);
3794 	EXPECT_EQ(errno, EINVAL);
3795 
3796 	resp.error = 0;
3797 	resp.val = 0;
3798 	EXPECT_EQ(ioctl(listener, SECCOMP_IOCTL_NOTIF_SEND, &resp), 0) {
3799 		if (errno == EINVAL)
3800 			SKIP(goto skip, "Kernel does not support SECCOMP_USER_NOTIF_FLAG_CONTINUE");
3801 	}
3802 
3803 skip:
3804 	EXPECT_EQ(waitpid(pid, &status, 0), pid);
3805 	EXPECT_EQ(true, WIFEXITED(status));
3806 	EXPECT_EQ(0, WEXITSTATUS(status)) {
3807 		if (WEXITSTATUS(status) == 2) {
3808 			SKIP(return, "Kernel does not support kcmp() syscall");
3809 			return;
3810 		}
3811 	}
3812 }
3813 
3814 TEST(user_notification_filter_empty)
3815 {
3816 	pid_t pid;
3817 	long ret;
3818 	int status;
3819 	struct pollfd pollfd;
3820 	struct __clone_args args = {
3821 		.flags = CLONE_FILES,
3822 		.exit_signal = SIGCHLD,
3823 	};
3824 
3825 	ret = prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
3826 	ASSERT_EQ(0, ret) {
3827 		TH_LOG("Kernel does not support PR_SET_NO_NEW_PRIVS!");
3828 	}
3829 
3830 	pid = sys_clone3(&args, sizeof(args));
3831 	ASSERT_GE(pid, 0);
3832 
3833 	if (pid == 0) {
3834 		int listener;
3835 
3836 		listener = user_notif_syscall(__NR_mknodat, SECCOMP_FILTER_FLAG_NEW_LISTENER);
3837 		if (listener < 0)
3838 			_exit(EXIT_FAILURE);
3839 
3840 		if (dup2(listener, 200) != 200)
3841 			_exit(EXIT_FAILURE);
3842 
3843 		close(listener);
3844 
3845 		_exit(EXIT_SUCCESS);
3846 	}
3847 
3848 	EXPECT_EQ(waitpid(pid, &status, 0), pid);
3849 	EXPECT_EQ(true, WIFEXITED(status));
3850 	EXPECT_EQ(0, WEXITSTATUS(status));
3851 
3852 	/*
3853 	 * The seccomp filter has become unused so we should be notified once
3854 	 * the kernel gets around to cleaning up task struct.
3855 	 */
3856 	pollfd.fd = 200;
3857 	pollfd.events = POLLHUP;
3858 
3859 	EXPECT_GT(poll(&pollfd, 1, 2000), 0);
3860 	EXPECT_GT((pollfd.revents & POLLHUP) ?: 0, 0);
3861 }
3862 
3863 static void *do_thread(void *data)
3864 {
3865 	return NULL;
3866 }
3867 
3868 TEST(user_notification_filter_empty_threaded)
3869 {
3870 	pid_t pid;
3871 	long ret;
3872 	int status;
3873 	struct pollfd pollfd;
3874 	struct __clone_args args = {
3875 		.flags = CLONE_FILES,
3876 		.exit_signal = SIGCHLD,
3877 	};
3878 
3879 	ret = prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
3880 	ASSERT_EQ(0, ret) {
3881 		TH_LOG("Kernel does not support PR_SET_NO_NEW_PRIVS!");
3882 	}
3883 
3884 	pid = sys_clone3(&args, sizeof(args));
3885 	ASSERT_GE(pid, 0);
3886 
3887 	if (pid == 0) {
3888 		pid_t pid1, pid2;
3889 		int listener, status;
3890 		pthread_t thread;
3891 
3892 		listener = user_notif_syscall(__NR_dup, SECCOMP_FILTER_FLAG_NEW_LISTENER);
3893 		if (listener < 0)
3894 			_exit(EXIT_FAILURE);
3895 
3896 		if (dup2(listener, 200) != 200)
3897 			_exit(EXIT_FAILURE);
3898 
3899 		close(listener);
3900 
3901 		pid1 = fork();
3902 		if (pid1 < 0)
3903 			_exit(EXIT_FAILURE);
3904 
3905 		if (pid1 == 0)
3906 			_exit(EXIT_SUCCESS);
3907 
3908 		pid2 = fork();
3909 		if (pid2 < 0)
3910 			_exit(EXIT_FAILURE);
3911 
3912 		if (pid2 == 0)
3913 			_exit(EXIT_SUCCESS);
3914 
3915 		if (pthread_create(&thread, NULL, do_thread, NULL) ||
3916 		    pthread_join(thread, NULL))
3917 			_exit(EXIT_FAILURE);
3918 
3919 		if (pthread_create(&thread, NULL, do_thread, NULL) ||
3920 		    pthread_join(thread, NULL))
3921 			_exit(EXIT_FAILURE);
3922 
3923 		if (waitpid(pid1, &status, 0) != pid1 || !WIFEXITED(status) ||
3924 		    WEXITSTATUS(status))
3925 			_exit(EXIT_FAILURE);
3926 
3927 		if (waitpid(pid2, &status, 0) != pid2 || !WIFEXITED(status) ||
3928 		    WEXITSTATUS(status))
3929 			_exit(EXIT_FAILURE);
3930 
3931 		exit(EXIT_SUCCESS);
3932 	}
3933 
3934 	EXPECT_EQ(waitpid(pid, &status, 0), pid);
3935 	EXPECT_EQ(true, WIFEXITED(status));
3936 	EXPECT_EQ(0, WEXITSTATUS(status));
3937 
3938 	/*
3939 	 * The seccomp filter has become unused so we should be notified once
3940 	 * the kernel gets around to cleaning up task struct.
3941 	 */
3942 	pollfd.fd = 200;
3943 	pollfd.events = POLLHUP;
3944 
3945 	EXPECT_GT(poll(&pollfd, 1, 2000), 0);
3946 	EXPECT_GT((pollfd.revents & POLLHUP) ?: 0, 0);
3947 }
3948 
3949 TEST(user_notification_addfd)
3950 {
3951 	pid_t pid;
3952 	long ret;
3953 	int status, listener, memfd, fd;
3954 	struct seccomp_notif_addfd addfd = {};
3955 	struct seccomp_notif_addfd_small small = {};
3956 	struct seccomp_notif_addfd_big big = {};
3957 	struct seccomp_notif req = {};
3958 	struct seccomp_notif_resp resp = {};
3959 	/* 100 ms */
3960 	struct timespec delay = { .tv_nsec = 100000000 };
3961 
3962 	memfd = memfd_create("test", 0);
3963 	ASSERT_GE(memfd, 0);
3964 
3965 	ret = prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
3966 	ASSERT_EQ(0, ret) {
3967 		TH_LOG("Kernel does not support PR_SET_NO_NEW_PRIVS!");
3968 	}
3969 
3970 	/* Check that the basic notification machinery works */
3971 	listener = user_notif_syscall(__NR_getppid,
3972 				      SECCOMP_FILTER_FLAG_NEW_LISTENER);
3973 	ASSERT_GE(listener, 0);
3974 
3975 	pid = fork();
3976 	ASSERT_GE(pid, 0);
3977 
3978 	if (pid == 0) {
3979 		if (syscall(__NR_getppid) != USER_NOTIF_MAGIC)
3980 			exit(1);
3981 		exit(syscall(__NR_getppid) != USER_NOTIF_MAGIC);
3982 	}
3983 
3984 	ASSERT_EQ(ioctl(listener, SECCOMP_IOCTL_NOTIF_RECV, &req), 0);
3985 
3986 	addfd.srcfd = memfd;
3987 	addfd.newfd = 0;
3988 	addfd.id = req.id;
3989 	addfd.flags = 0x0;
3990 
3991 	/* Verify bad newfd_flags cannot be set */
3992 	addfd.newfd_flags = ~O_CLOEXEC;
3993 	EXPECT_EQ(ioctl(listener, SECCOMP_IOCTL_NOTIF_ADDFD, &addfd), -1);
3994 	EXPECT_EQ(errno, EINVAL);
3995 	addfd.newfd_flags = O_CLOEXEC;
3996 
3997 	/* Verify bad flags cannot be set */
3998 	addfd.flags = 0xff;
3999 	EXPECT_EQ(ioctl(listener, SECCOMP_IOCTL_NOTIF_ADDFD, &addfd), -1);
4000 	EXPECT_EQ(errno, EINVAL);
4001 	addfd.flags = 0;
4002 
4003 	/* Verify that remote_fd cannot be set without setting flags */
4004 	addfd.newfd = 1;
4005 	EXPECT_EQ(ioctl(listener, SECCOMP_IOCTL_NOTIF_ADDFD, &addfd), -1);
4006 	EXPECT_EQ(errno, EINVAL);
4007 	addfd.newfd = 0;
4008 
4009 	/* Verify small size cannot be set */
4010 	EXPECT_EQ(ioctl(listener, SECCOMP_IOCTL_NOTIF_ADDFD_SMALL, &small), -1);
4011 	EXPECT_EQ(errno, EINVAL);
4012 
4013 	/* Verify we can't send bits filled in unknown buffer area */
4014 	memset(&big, 0xAA, sizeof(big));
4015 	big.addfd = addfd;
4016 	EXPECT_EQ(ioctl(listener, SECCOMP_IOCTL_NOTIF_ADDFD_BIG, &big), -1);
4017 	EXPECT_EQ(errno, E2BIG);
4018 
4019 
4020 	/* Verify we can set an arbitrary remote fd */
4021 	fd = ioctl(listener, SECCOMP_IOCTL_NOTIF_ADDFD, &addfd);
4022 	/*
4023 	 * The child has fds 0(stdin), 1(stdout), 2(stderr), 3(memfd),
4024 	 * 4(listener), so the newly allocated fd should be 5.
4025 	 */
4026 	EXPECT_EQ(fd, 5);
4027 	EXPECT_EQ(filecmp(getpid(), pid, memfd, fd), 0);
4028 
4029 	/* Verify we can set an arbitrary remote fd with large size */
4030 	memset(&big, 0x0, sizeof(big));
4031 	big.addfd = addfd;
4032 	fd = ioctl(listener, SECCOMP_IOCTL_NOTIF_ADDFD_BIG, &big);
4033 	EXPECT_EQ(fd, 6);
4034 
4035 	/* Verify we can set a specific remote fd */
4036 	addfd.newfd = 42;
4037 	addfd.flags = SECCOMP_ADDFD_FLAG_SETFD;
4038 	fd = ioctl(listener, SECCOMP_IOCTL_NOTIF_ADDFD, &addfd);
4039 	EXPECT_EQ(fd, 42);
4040 	EXPECT_EQ(filecmp(getpid(), pid, memfd, fd), 0);
4041 
4042 	/* Resume syscall */
4043 	resp.id = req.id;
4044 	resp.error = 0;
4045 	resp.val = USER_NOTIF_MAGIC;
4046 	EXPECT_EQ(ioctl(listener, SECCOMP_IOCTL_NOTIF_SEND, &resp), 0);
4047 
4048 	/*
4049 	 * This sets the ID of the ADD FD to the last request plus 1. The
4050 	 * notification ID increments 1 per notification.
4051 	 */
4052 	addfd.id = req.id + 1;
4053 
4054 	/* This spins until the underlying notification is generated */
4055 	while (ioctl(listener, SECCOMP_IOCTL_NOTIF_ADDFD, &addfd) != -1 &&
4056 	       errno != -EINPROGRESS)
4057 		nanosleep(&delay, NULL);
4058 
4059 	memset(&req, 0, sizeof(req));
4060 	ASSERT_EQ(ioctl(listener, SECCOMP_IOCTL_NOTIF_RECV, &req), 0);
4061 	ASSERT_EQ(addfd.id, req.id);
4062 
4063 	resp.id = req.id;
4064 	resp.error = 0;
4065 	resp.val = USER_NOTIF_MAGIC;
4066 	EXPECT_EQ(ioctl(listener, SECCOMP_IOCTL_NOTIF_SEND, &resp), 0);
4067 
4068 	/* Wait for child to finish. */
4069 	EXPECT_EQ(waitpid(pid, &status, 0), pid);
4070 	EXPECT_EQ(true, WIFEXITED(status));
4071 	EXPECT_EQ(0, WEXITSTATUS(status));
4072 
4073 	close(memfd);
4074 }
4075 
4076 TEST(user_notification_addfd_rlimit)
4077 {
4078 	pid_t pid;
4079 	long ret;
4080 	int status, listener, memfd;
4081 	struct seccomp_notif_addfd addfd = {};
4082 	struct seccomp_notif req = {};
4083 	struct seccomp_notif_resp resp = {};
4084 	const struct rlimit lim = {
4085 		.rlim_cur	= 0,
4086 		.rlim_max	= 0,
4087 	};
4088 
4089 	memfd = memfd_create("test", 0);
4090 	ASSERT_GE(memfd, 0);
4091 
4092 	ret = prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
4093 	ASSERT_EQ(0, ret) {
4094 		TH_LOG("Kernel does not support PR_SET_NO_NEW_PRIVS!");
4095 	}
4096 
4097 	/* Check that the basic notification machinery works */
4098 	listener = user_notif_syscall(__NR_getppid,
4099 				      SECCOMP_FILTER_FLAG_NEW_LISTENER);
4100 	ASSERT_GE(listener, 0);
4101 
4102 	pid = fork();
4103 	ASSERT_GE(pid, 0);
4104 
4105 	if (pid == 0)
4106 		exit(syscall(__NR_getppid) != USER_NOTIF_MAGIC);
4107 
4108 
4109 	ASSERT_EQ(ioctl(listener, SECCOMP_IOCTL_NOTIF_RECV, &req), 0);
4110 
4111 	ASSERT_EQ(prlimit(pid, RLIMIT_NOFILE, &lim, NULL), 0);
4112 
4113 	addfd.srcfd = memfd;
4114 	addfd.newfd_flags = O_CLOEXEC;
4115 	addfd.newfd = 0;
4116 	addfd.id = req.id;
4117 	addfd.flags = 0;
4118 
4119 	/* Should probably spot check /proc/sys/fs/file-nr */
4120 	EXPECT_EQ(ioctl(listener, SECCOMP_IOCTL_NOTIF_ADDFD, &addfd), -1);
4121 	EXPECT_EQ(errno, EMFILE);
4122 
4123 	addfd.newfd = 100;
4124 	addfd.flags = SECCOMP_ADDFD_FLAG_SETFD;
4125 	EXPECT_EQ(ioctl(listener, SECCOMP_IOCTL_NOTIF_ADDFD, &addfd), -1);
4126 	EXPECT_EQ(errno, EBADF);
4127 
4128 	resp.id = req.id;
4129 	resp.error = 0;
4130 	resp.val = USER_NOTIF_MAGIC;
4131 
4132 	EXPECT_EQ(ioctl(listener, SECCOMP_IOCTL_NOTIF_SEND, &resp), 0);
4133 
4134 	/* Wait for child to finish. */
4135 	EXPECT_EQ(waitpid(pid, &status, 0), pid);
4136 	EXPECT_EQ(true, WIFEXITED(status));
4137 	EXPECT_EQ(0, WEXITSTATUS(status));
4138 
4139 	close(memfd);
4140 }
4141 
4142 /*
4143  * TODO:
4144  * - expand NNP testing
4145  * - better arch-specific TRACE and TRAP handlers.
4146  * - endianness checking when appropriate
4147  * - 64-bit arg prodding
4148  * - arch value testing (x86 modes especially)
4149  * - verify that FILTER_FLAG_LOG filters generate log messages
4150  * - verify that RET_LOG generates log messages
4151  */
4152 
4153 TEST_HARNESS_MAIN
4154