1 /*
2  * Verifies that the "vm.mmap_noexec_taint" sysctl is operational.
3  */
4 #include <errno.h>
5 #include <fcntl.h>
6 #include <stdio.h>
7 #include <stdlib.h>
8 #include <sys/mman.h>
9 #include <sys/types.h>
10 #include <sys/stat.h>
11 
err_sys(char * msg)12 void err_sys(char *msg)
13 {
14         perror(msg);
15         exit(1);
16 }
17 
err_quit(char * msg)18 void err_quit(char *msg)
19 {
20         fprintf(stderr, "FAIL: %s\n", msg);
21         exit(1);
22 }
23 
main(int argc,char * argv[])24 int main(int argc, char *argv[])
25 {
26         int fd;
27         int *arearw, *areaex;
28 
29         if (argc < 2)
30                 err_quit("need to pass a filename");
31 
32         if ((fd = open(argv[1], O_RDWR|O_CREAT|O_EXCL, S_IRWXU)) < 0)
33                 err_sys("open error");
34         lseek(fd, 100, SEEK_CUR);
35         write(fd, "A", 1);
36         if ((arearw = (int *)mmap(0, sizeof(int),
37                                   PROT_READ | PROT_WRITE, MAP_SHARED,
38                                   fd, 0)) == MAP_FAILED)
39                 err_sys("arearw mmap error");
40 
41         /* Make sure mmap with PROT_EXEC fails. */
42         if ((areaex = (int *)mmap(0, sizeof(int),
43                                   PROT_READ | PROT_EXEC, MAP_SHARED,
44                                   fd, 0)) != MAP_FAILED)
45                 err_quit("areaex mmap allowed PROT_EXEC");
46 
47         if ((areaex = (int *)mmap(0, sizeof(int),
48                                   PROT_READ, MAP_SHARED,
49                                   fd, 0)) == MAP_FAILED)
50                 err_sys("areaex mmap error");
51         if (mprotect(areaex, sizeof(int), PROT_READ | PROT_EXEC))
52                 err_sys("areaex mprotect error");
53         close(fd);
54 
55         /* Make sure we start zero-filled. */
56         if (*arearw != 0x0)
57                 err_quit("not zero-filled");
58 
59         /* Make sure we're sharing a memory area. */
60         *arearw = 0xfabecafe;
61         if (*arearw != *areaex)
62                 err_quit("memory regions are not shared");
63 
64         printf("pass\n");
65         return 0;
66 }
67