1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3 * Copyright (c) 2016 Cyril Hrubis <chrubis@suse.cz>
4 */
5
6 /*
7 * This is a regression test for write race that allows unprivileged programs
8 * to change readonly files on the system.
9 *
10 * It has been fixed long time ago:
11 *
12 * commit 4ceb5db9757aaeadcf8fbbf97d76bd42aa4df0d6
13 * Author: Linus Torvalds <torvalds@g5.osdl.org>
14 * Date: Mon Aug 1 11:14:49 2005 -0700
15 *
16 * Fix get_user_pages() race for write access
17 *
18 * Then it reappeared and was fixed again in:
19 *
20 * commit 19be0eaffa3ac7d8eb6784ad9bdbc7d67ed8e619
21 * Author: Linus Torvalds <torvalds@linux-foundation.org>
22 * Date: Thu Oct 13 20:07:36 2016 GMT
23 *
24 * mm: remove gup_flags FOLL_WRITE games from __get_user_pages()
25 */
26
27 #include <sys/mman.h>
28 #include <fcntl.h>
29 #include <pthread.h>
30 #include <unistd.h>
31 #include <sys/stat.h>
32 #include <string.h>
33 #include <stdlib.h>
34 #include <pwd.h>
35
36 #include "tst_test.h"
37
38 #define FNAME "test"
39 #define STR "this is not a test\n"
40
41 static uid_t nobody_uid;
42 static gid_t nobody_gid;
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
dirtyc0w_test(void)56 void dirtyc0w_test(void)
57 {
58 int i, fd, pid, fail = 0;
59 char c;
60
61 /* Create file */
62 fd = SAFE_OPEN(FNAME, O_WRONLY|O_CREAT|O_EXCL, 0444);
63 SAFE_WRITE(1, fd, STR, sizeof(STR)-1);
64 SAFE_CLOSE(fd);
65
66 pid = SAFE_FORK();
67
68 if (!pid) {
69 SAFE_SETGID(nobody_gid);
70 SAFE_SETUID(nobody_uid);
71 SAFE_EXECLP("dirtyc0w_child", "dirtyc0w_child", NULL);
72 }
73
74 TST_CHECKPOINT_WAIT(0);
75 for (i = 0; i < 100; i++) {
76 usleep(10000);
77
78 SAFE_FILE_SCANF(FNAME, "%c", &c);
79
80 if (c != 't') {
81 fail = 1;
82 break;
83 }
84 }
85
86 SAFE_KILL(pid, SIGUSR1);
87 tst_reap_children();
88 SAFE_UNLINK(FNAME);
89
90 if (fail)
91 tst_res(TFAIL, "Bug reproduced!");
92 else
93 tst_res(TPASS, "Bug not reproduced");
94 }
95
96 static struct tst_test test = {
97 .needs_checkpoints = 1,
98 .forks_child = 1,
99 .needs_root = 1,
100 .setup = setup,
101 .test_all = dirtyc0w_test,
102 .tags = (const struct tst_tag[]) {
103 {"linux-git", "4ceb5db9757a"},
104 {"linux-git", "9be0eaffa3ac"},
105 {}
106 }
107 };
108