1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
|
// Memory behind a protection key, used the ways a JIT uses its code space:
// read as soon as the key is made, handed to syscalls, watched, and read by
// a thread made later. Each step dies or fails if the tracer acts with other
// rights to that memory than the thread has. Where the CPU or the kernel
// has no protection keys it says so and exits 0.
#define _GNU_SOURCE
#include <fcntl.h>
#include <pthread.h>
#include <stdio.h>
#include <string.h>
#include <sys/mman.h>
#include <unistd.h>
#include <ztrace.h>
static char *page;
static int out;
// Made after the key: it has its maker's rights, to read and not to write.
__attribute__((noinline)) static void *reader(void *arg) {
(void)arg;
if (page[0] != 'p') return (void *)1;
return (void *)(long)(write(out, page, 10) != 10);
}
int main(void) {
int key = pkey_alloc(0, PKEY_DISABLE_WRITE);
if (key < 0) {
puts("no protection keys");
return 0;
}
page = mmap(NULL, 4096, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
if (pkey_mprotect(page, 4096, PROT_READ | PROT_WRITE, key)) return 1;
// The key came with the right to read.
if (page[0] != 0) return 2;
ztrace_watch(page, 64, "page");
out = open("/dev/null", O_WRONLY);
int zero = open("/dev/zero", O_RDONLY);
// With the right to write, the kernel may write there for us too...
pkey_set(key, 0);
if (read(zero, page, 16) != 16) return 3;
memcpy(page, "protected\n", 10);
// ... and without it, it may not.
pkey_set(key, PKEY_DISABLE_WRITE);
if (read(zero, page, 16) != -1) return 4;
if (write(out, page, 10) != 10) return 5;
// With no right at all the thread still runs, and the tracer still sees the page.
pkey_set(key, PKEY_DISABLE_ACCESS);
ztrace_mark("hidden", 0);
pkey_set(key, PKEY_DISABLE_WRITE);
pthread_t thread;
void *failed;
if (pthread_create(&thread, NULL, reader, NULL) || pthread_join(thread, &failed) || failed) return 6;
puts("protected");
return 0;
}
|