xref: /aosp_15_r20/external/ltp/testcases/kernel/security/dirtyc0w_shmem/dirtyc0w_shmem.c (revision 49cdfc7efb34551c7342be41a7384b9c40d7cab7)
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 #include "pgsize_helpers.h"
26 
27 #define TMP_DIR "tmp_dirtyc0w_shmem"
28 #define TEST_FILE TMP_DIR"/testfile"
29 #define STR "this is not a test\n"
30 
31 static uid_t nobody_uid;
32 static gid_t nobody_gid;
33 static volatile bool child_early_exit;
34 
sighandler(int sig)35 static void sighandler(int sig)
36 {
37 	if (sig == SIGCHLD) {
38 		child_early_exit = true;
39 		return;
40 	}
41 
42 	_exit(0);
43 }
44 
setup(void)45 static void setup(void)
46 {
47 	struct passwd *pw;
48 
49 	umask(0);
50 
51 	pw = SAFE_GETPWNAM("nobody");
52 
53 	nobody_uid = pw->pw_uid;
54 	nobody_gid = pw->pw_gid;
55 
56 	SAFE_MKDIR(TMP_DIR, 0664);
57 	SAFE_MOUNT(TMP_DIR, TMP_DIR, "tmpfs", 0, NULL);
58 }
59 
dirtyc0w_shmem_test(void)60 static void dirtyc0w_shmem_test(void)
61 {
62 	bool failed = false;
63 	int pid;
64 	char c;
65 
66 	SAFE_FILE_PRINTF_PGSIZE_EMULATION(TEST_FILE, STR);
67 	SAFE_CHMOD(TEST_FILE, 0444);
68 
69 	pid = SAFE_FORK();
70 	if (!pid) {
71 		SAFE_SETGID(nobody_gid);
72 		SAFE_SETUID(nobody_uid);
73 		SAFE_EXECLP("dirtyc0w_shmem_child", "dirtyc0w_shmem_child", NULL);
74 	}
75 
76 	TST_CHECKPOINT_WAIT(0);
77 
78 	SAFE_SIGNAL(SIGCHLD, sighandler);
79 	do {
80 		usleep(100000);
81 
82 		SAFE_FILE_SCANF(TEST_FILE, "%c", &c);
83 
84 		if (c != 't') {
85 			failed = true;
86 			break;
87 		}
88 	} while (tst_remaining_runtime() && !child_early_exit);
89 	SAFE_SIGNAL(SIGCHLD, SIG_DFL);
90 
91 	SAFE_KILL(pid, SIGUSR1);
92 	tst_reap_children();
93 	SAFE_UNLINK(TEST_FILE);
94 
95 	if (child_early_exit)
96 		tst_res(TINFO, "Early child process exit");
97 	else if (failed)
98 		tst_res(TFAIL, "Bug reproduced!");
99 	else
100 		tst_res(TPASS, "Bug not reproduced");
101 }
102 
cleanup(void)103 static void cleanup(void)
104 {
105 	SAFE_UMOUNT(TMP_DIR);
106 }
107 
108 static struct tst_test test = {
109 	.needs_checkpoints = 1,
110 	.forks_child = 1,
111 	.needs_root = 1,
112 	.max_runtime = 120,
113 	.setup = setup,
114 	.cleanup = cleanup,
115 	.test_all = dirtyc0w_shmem_test,
116 	.tags = (const struct tst_tag[]) {
117 		{"linux-git", "5535be309971"},
118 		{"CVE", "2022-2590"},
119 		{}
120 	}
121 };
122