Created
June 1, 2023 15:57
-
-
Save shitpoet/678183c54c531606f6b25b99620d56f1 to your computer and use it in GitHub Desktop.
How to execute an array of bytes as code on x86-64 under linux
This file contains hidden or 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 <stdint.h> | |
#include <sys/mman.h> | |
#include <unistd.h> | |
typedef int (*f)(int); | |
//typedef int (*f)(); | |
//uint8_t code[] = { | |
// 0x89, 0xc1, | |
// 0x0f, 0xaf, 0xc0, | |
// 0xc3 | |
//}; | |
//uint8_t code[] = { 0xC3 }; | |
//uint8_t code[] = { 0x48, 0xC7, 0xC0, 0x2A, 0x00, 0x00, 0x00, 0xC3 }; | |
//0: 48 83 c7 01 add rdi,0x1 | |
//4: 48 89 f8 mov rax,rdi | |
//7: c3 ret | |
uint8_t code[] = { 0x48, 0x83, 0xC7, 0x01, 0x48, 0x89, 0xF8, 0xC3 }; | |
int main() { | |
int pagesize = getpagesize(); | |
uint8_t* buffer = memalign(pagesize, pagesize); | |
if (buffer == NULL) { printf("memalign\n"); exit(1); } | |
printf("code size %d\n", sizeof(code)); | |
memcpy(buffer, code, sizeof(code)); | |
if (mprotect(buffer, pagesize, PROT_EXEC) != 0) { | |
printf("can not mprotect\n"); | |
exit(1); | |
} | |
//int r = ((f)buffer)(); | |
int r = ((f)buffer)(6); | |
printf("%d", r); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment