When I execute the shellcode in the main function, it works fine. However, when I execute it by other function called by main, it will cause Segmentation fault. As far as I know, function call should influence the stack, and the shellcode should be in the heap. Is there something wrong in my code?
The shellcode is generated by matesploit, and I use qemu-arm to run the program.
The code is:
#include <stdio.h>
#include <stdlib.h>
#include <memory.h>
// msfvenom -p linux/armle/exec CMD=/bin/pwd -f c
unsigned char buf[] =
"\x01\x30\x8f\xe2\x13\xff\x2f\xe1\x78\x46\x0a\x30\x01\x90\x01"
"\xa9\x92\x1a\x0b\x27\x01\xdf\x2f\x62\x69\x6e\x2f\x70\x77\x64";
void runShellCode(){
unsigned char *pShellCode = (unsigned char *)calloc(1, 4096);
memcpy(pShellCode, buf, sizeof(buf));
(*(void(*)()) pShellCode)();
}
int main(int argc, char *argv[])
{
// uncomment these lines it will work perfectly fine
// unsigned char *pShellCode = (unsigned char *)calloc(1, 4096);
// memcpy(pShellCode, buf, sizeof(buf));
// (*(void(*)()) pShellCode)();
runShellCode();
return 0;
}
The cmd to compile & run:
arm-linux-gnueabi-gcc test.c -o test_arm -static
qemu-arm test_arm
The disassembly code of the shellcode(which is uncorrect so I delete it)
Update the code with mmap() way. However, if the argment of the main() is void
, it works fine. While the argument is int argc, char *argv[]
, it will cause SEGV.
#include <stdio.h>
#include <stdlib.h>
#include <memory.h>
#include <sys/mman.h>
// msfvenom -p linux/armle/exec CMD=/bin/pwd -f c
unsigned char buf[] =
"\x01\x30\x8f\xe2\x13\xff\x2f\xe1\x78\x46\x0a\x30\x01\x90\x01"
"\xa9\x92\x1a\x0b\x27\x01\xdf\x2f\x62\x69\x6e\x2f\x70\x77\x64";
int main(int argc, char *argv[])
//int main(void)
{
unsigned char *pShellCode = (unsigned char *)calloc(1, 4096);
memcpy(pShellCode, buf, sizeof(buf));
void (*sc) () = NULL;
sc = mmap (0, 4096, PROT_READ|PROT_WRITE|PROT_EXEC, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
memcpy (sc, pShellCode, 4096);
__builtin___clear_cache (sc, sc + sizeof(sc));
sc();
return 0;
}