gcc -o pkru pkru.c
Last active
November 10, 2023 16:18
-
-
Save mbs0221/7c134e90d20b2564ee88e4c9376203c3 to your computer and use it in GitHub Desktop.
pkru example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
#include <sys/mman.h> | |
#include <sys/mman.h> | |
#include <sys/prctl.h> | |
#include <asm/prctl.h> | |
#include <sys/syscall.h> | |
#define PKEY_DISABLE_WRITE 0x1ull | |
int pkey_alloc(unsigned int flags, unsigned int access_rights) { | |
return syscall(__NR_pkey_alloc, flags, access_rights); | |
} | |
int pkey_free(int pkey) { | |
return syscall(__NR_pkey_free, pkey); | |
} | |
int pkey_mprotect(void *addr, size_t len, unsigned long prot, int pkey) { | |
return syscall(__NR_pkey_mprotect, addr, len, prot, pkey); | |
} | |
void test_pkey_mprotect() { | |
char *secret; | |
secret = mmap(NULL, getpagesize(), PROT_WRITE | PROT_READ, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0); | |
strncpy(secret, "The Magic Words are Squeamish Ossifrage.", 40); | |
int real_prot = PROT_NONE; | |
int pkey = pkey_alloc(0, PKEY_DISABLE_WRITE); | |
int ret = pkey_mprotect(secret, getpagesize(), real_prot, pkey); | |
printf("ret: %d\n", ret); | |
printf("secret: %s\n", secret); | |
pkey_free(pkey); | |
} | |
int main() { | |
test_pkey_mprotect(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment