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 pw = SAFE_GETPWNAM("nobody");
49
50 nobody_uid = pw->pw_uid;
51 nobody_gid = pw->pw_gid;
52 }
53
dirtyc0w_test(void)54 void dirtyc0w_test(void)
55 {
56 int i, fd, pid, fail = 0;
57 char c;
58
59 /* Create file */
60 fd = SAFE_OPEN(FNAME, O_WRONLY|O_CREAT|O_EXCL, 0444);
61 SAFE_WRITE(1, fd, STR, sizeof(STR)-1);
62 SAFE_CLOSE(fd);
63
64 pid = SAFE_FORK();
65
66 if (!pid) {
67 SAFE_SETGID(nobody_gid);
68 SAFE_SETUID(nobody_uid);
69 SAFE_EXECLP("dirtyc0w_child", "dirtyc0w_child", NULL);
70 }
71
72 TST_CHECKPOINT_WAIT(0);
73 for (i = 0; i < 100; i++) {
74 usleep(10000);
75
76 SAFE_FILE_SCANF(FNAME, "%c", &c);
77
78 if (c != 't') {
79 fail = 1;
80 break;
81 }
82 }
83
84 SAFE_KILL(pid, SIGUSR1);
85 tst_reap_children();
86 SAFE_UNLINK(FNAME);
87
88 if (fail)
89 tst_res(TFAIL, "Bug reproduced!");
90 else
91 tst_res(TPASS, "Bug not reproduced");
92 }
93
94 static struct tst_test test = {
95 .needs_checkpoints = 1,
96 .forks_child = 1,
97 .needs_root = 1,
98 .setup = setup,
99 .test_all = dirtyc0w_test,
100 .tags = (const struct tst_tag[]) {
101 {"linux-git", "4ceb5db9757a"},
102 {"linux-git", "9be0eaffa3ac"},
103 {}
104 }
105 };
106