1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3 * Copyright (c) 2020 FUJITSU LIMITED. All rights reserved.
4 * Author: Yang Xu <xuyang2018.jy@cn.fujitsu.com
5 *
6 * ptrace() returns -1 and sets errno to EPERM if tracer doesn't have
7 * CAP_SYS_PTRACE capability for the process. Such as nobody user.
8 */
9
10 #include <errno.h>
11 #include <signal.h>
12 #include <sys/wait.h>
13 #include <pwd.h>
14 #include <config.h>
15 #include <stdlib.h>
16 #include "ptrace.h"
17 #include "tst_test.h"
18
19 uid_t uid;
20
verify_ptrace(void)21 static void verify_ptrace(void)
22 {
23 int child_pid[2];
24
25 child_pid[0] = SAFE_FORK();
26 if (!child_pid[0])
27 pause();
28
29 child_pid[1] = SAFE_FORK();
30 if (!child_pid[1]) {
31 SAFE_SETUID(uid);
32 TEST(ptrace(PTRACE_ATTACH, child_pid[0], NULL, NULL));
33
34 if (TST_RET == 0) {
35 tst_res(TFAIL, "ptrace() succeeded unexpectedly");
36 exit(0);
37 }
38
39 if (TST_RET != -1) {
40 tst_res(TFAIL,
41 "Invalid ptrace() return value %ld", TST_RET);
42 exit(0);
43 }
44
45 if (TST_ERR == EPERM)
46 tst_res(TPASS | TTERRNO, "ptrace() failed as expected");
47 else
48 tst_res(TFAIL | TTERRNO, "ptrace() expected EPERM, but got");
49 exit(0);
50 }
51 SAFE_WAITPID(child_pid[1], NULL, 0);
52 SAFE_KILL(child_pid[0], SIGKILL);
53 SAFE_WAITPID(child_pid[0], NULL, 0);
54 }
55
setup(void)56 static void setup(void)
57 {
58 struct passwd *pw;
59
60 pw = SAFE_GETPWNAM("nobody");
61 uid = pw->pw_uid;
62 }
63
64 static struct tst_test test = {
65 .setup = setup,
66 .test_all = verify_ptrace,
67 .forks_child = 1,
68 .needs_root = 1,
69 };
70