Skip to content

Instantly share code, notes, and snippets.

@securitytube
Created April 5, 2013 12:14
Show Gist options
  • Star 24 You must be signed in to star a gist
  • Fork 11 You must be signed in to fork a gist
  • Save securitytube/5318838 to your computer and use it in GitHub Desktop.
Save securitytube/5318838 to your computer and use it in GitHub Desktop.
C Program to test shellcode
#include<stdio.h>
#include<string.h>
unsigned char code[] = \
"\x31\xc0\x50\x68\x6e\x2f\x73\x68\x68\x2f\x2f\x62\x69\x89\xe3\x50\x89\xe2\x53\x89\xe1\xb0\x0b\xcd\x80";
main()
{
printf("Shellcode Length: %d\n", strlen(code));
int (*ret)() = (int(*)())code;
ret();
}
@jattboe
Copy link

jattboe commented Jan 27, 2022

Just put code in stack by initializing code as local variable

#include <stdio.h>
#include <string.h>

int main(){
    char code[] = "\x31\xc0\x50\x68\x6e\x2f\x73\x68\x68\x2f\x2f\x62\x69\x89\xe3\x50\x89\xe2\x53\x89\xe1\xb0\x0b\xcd\x80";
    printf("Shellcode length: %d\n", strlen(code));
    int (*ret)() = (int(*)())code;
    return ret();
}
  • gcc -fno-stack-protector -z execstack -m32 shellcode.c -o shellcode

@RobertLarsen
Copy link

RobertLarsen commented Feb 2, 2023

At least on my x64 the memory page is not executable (x86 only has r/w, x64 has r/w/x, thats why it always works on x86 and the problem does not occur there)

Not exactly. x86 also has r/w/x but the ELF loading code in the kernel (for x86 only) treats all readable memory as executable IF the stack was marked as executable. Which it is if either PT_GNU_STACK program header is missing in the ELF or if it is present and has the executable flag set. Which is why the -z execstack was important.
See:

Shameless self promotion: I made a tool for shellcode execution which you may want to use: https://github.com/RobertLarsen/RunShellcode

@zeredy879
Copy link

zeredy879 commented Aug 25, 2023

Here is another example to run x86 shellcode on x64 machine but specify the memory address where you want to load your shellcode:

# include <stdio.h>
# include <string.h>
# include <unistd.h>
# include <sys/mman.h>

# define EXEC_MEM ((void *) 0x80000000)

char shellcode[] = "{write your shellcode here}";

int main() {{
    mmap(EXEC_MEM, 0x1000, PROT_READ | PROT_WRITE | PROT_EXEC, MAP_ANONYMOUS | MAP_FIXED | MAP_PRIVATE, -1, 0);
    memcpy(EXEC_MEM, (void *)shellcode, strlen(shellcode)+1);
    (*(int (*)())EXEC_MEM)();
    return 0;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment