// 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 #include #include #include #include #include #include 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; }