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