exécution du contenu d'une chaîne en c [duplicate]
Oct 08 2020
#include<stdio.h>
#include<stdlib.h>
char code[] ="\x52\x56\x57\x50\xB8\x41\x00\x00\x00\x50\xB8\x01\x00\x00\x00\xBF\x01\x00\x00\x00\x48\x89\xE6\xBA\x01\x00\x00\x00\x0F\x05\x58\x58\x5F\x5E\x5A\xC3";
int main(){
void(*func)() = (void (*)())code;
(*func)();
return 0 ;
}
ce que j'ai ici est une chaîne qui stocke un code binaire pour imprimer un caractère ('A'), je le passe comme un pointeur de fonction à func, puis j'essaye de l'exécuter. le résultat :
$ ./test
Segmentation fault (core dumped)
c'est le code d'assemblage:
0: 52 push rdx
1: 56 push rsi
2: 57 push rdi
3: 50 push rax
4: b8 41 00 00 00 mov eax,0x41
9: 50 push rax
a: b8 01 00 00 00 mov eax,0x1
f: bf 01 00 00 00 mov edi,0x1
14: 48 89 e6 mov rsi,rsp
17: ba 01 00 00 00 mov edx,0x1
1c: 0f 05 syscall
1e: 58 pop rax
1f: 58 pop rax
20: 5f pop rdi
21: 5e pop rsi
22: 5a pop rdx
23: c3 ret
Réponses
6 DavidRanieri Oct 07 2020 at 23:11
Comme indiqué par @WeatherVane, vous avez besoin d'une autorisation pour exécuter un segment de données, mprotect peut vous aider:
#include <stdio.h>
#include <sys/mman.h>
#include <stdint.h>
static char code[] = "\x52\x56\x57\x50\xB8\x41\x00\x00\x00\x50\xB8\x01\x00\x00"
"\x00\xBF\x01\x00\x00\x00\x48\x89\xE6\xBA\x01\x00\x00\x00"
"\x0F\x05\x58\x58\x5F\x5E\x5A\xC3";
int main(void)
{
uintptr_t page = (uintptr_t)code & -4095ULL;
mprotect((void *)page, 4096, PROT_READ | PROT_EXEC | PROT_WRITE);
void (*func)(void) = (void (*)(void))code;
func();
return 0;
}
Vous pouvez voir le résultat ( A) dans godbolt