1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3 * Copyright (C) 2022 Red Hat, Inc.
4 */
5
6 /*\
7 * [Description]
8 *
9 * This is a regression test for a write race that allowed unprivileged programs
10 * to change readonly files located on tmpfs/shmem on the system using
11 * userfaultfd "minor fault handling" (CVE-2022-2590).
12 */
13
14 #include "config.h"
15
16 #include <pthread.h>
17 #include <unistd.h>
18 #include <sys/stat.h>
19 #include <string.h>
20 #include <stdlib.h>
21 #include <stdbool.h>
22 #include <pwd.h>
23
24 #include "tst_test.h"
25
26 #define TMP_DIR "tmp_dirtyc0w_shmem"
27 #define TEST_FILE TMP_DIR"/testfile"
28 #define STR "this is not a test\n"
29
30 static uid_t nobody_uid;
31 static gid_t nobody_gid;
32 static volatile bool child_early_exit;
33
sighandler(int sig)34 static void sighandler(int sig)
35 {
36 if (sig == SIGCHLD) {
37 child_early_exit = true;
38 return;
39 }
40
41 _exit(0);
42 }
43
setup(void)44 static void setup(void)
45 {
46 struct passwd *pw;
47
48 umask(0);
49
50 pw = SAFE_GETPWNAM("nobody");
51
52 nobody_uid = pw->pw_uid;
53 nobody_gid = pw->pw_gid;
54
55 SAFE_MKDIR(TMP_DIR, 0664);
56 SAFE_MOUNT(TMP_DIR, TMP_DIR, "tmpfs", 0, NULL);
57 }
58
dirtyc0w_shmem_test(void)59 static void dirtyc0w_shmem_test(void)
60 {
61 bool failed = false;
62 int pid;
63 char c;
64
65 SAFE_FILE_PRINTF(TEST_FILE, STR);
66 SAFE_CHMOD(TEST_FILE, 0444);
67
68 pid = SAFE_FORK();
69 if (!pid) {
70 SAFE_SETGID(nobody_gid);
71 SAFE_SETUID(nobody_uid);
72 SAFE_EXECLP("dirtyc0w_shmem_child", "dirtyc0w_shmem_child", NULL);
73 }
74
75 TST_CHECKPOINT_WAIT(0);
76
77 SAFE_SIGNAL(SIGCHLD, sighandler);
78 do {
79 usleep(100000);
80
81 SAFE_FILE_SCANF(TEST_FILE, "%c", &c);
82
83 if (c != 't') {
84 failed = true;
85 break;
86 }
87 } while (tst_remaining_runtime() && !child_early_exit);
88 SAFE_SIGNAL(SIGCHLD, SIG_DFL);
89
90 SAFE_KILL(pid, SIGUSR1);
91 tst_reap_children();
92 SAFE_UNLINK(TEST_FILE);
93
94 if (child_early_exit)
95 tst_res(TINFO, "Early child process exit");
96 else if (failed)
97 tst_res(TFAIL, "Bug reproduced!");
98 else
99 tst_res(TPASS, "Bug not reproduced");
100 }
101
cleanup(void)102 static void cleanup(void)
103 {
104 SAFE_UMOUNT(TMP_DIR);
105 }
106
107 static struct tst_test test = {
108 .needs_checkpoints = 1,
109 .forks_child = 1,
110 .needs_root = 1,
111 .max_runtime = 120,
112 .setup = setup,
113 .cleanup = cleanup,
114 .test_all = dirtyc0w_shmem_test,
115 .tags = (const struct tst_tag[]) {
116 {"linux-git", "5535be309971"},
117 {"CVE", "2022-2590"},
118 {}
119 }
120 };
121