Another example that allows you to read the shellcode from a file
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <stdlib.h>
int main(int ac, char ** av){
void (*sc)(void);
int fd;
struct stat sbuf;
if (ac != 2){
fprintf(stderr, "Usage: %s <filename>", av[0]);
exit(EXIT_FAILURE);
}
if ((fd = open(av[1], O_RDONLY)) < 0){
perror("open()");
exit(EXIT_FAILURE);
}
if (fstat(fd,&sbuf)){
perror("fstat()");
exit(EXIT_FAILURE);
}
if ((sc = mmap(NULL, sbuf.st_size, PROT_READ |
PROT_WRITE |
PROT_EXEC,
MAP_PRIVATE, fd, 0)) == MAP_FAILED){
perror("mmap()");
exit(EXIT_FAILURE);
}
close(fd);
sc();
return 0;
}
Hello-world shellcode
[BITS 32]
push byte 0x0a
push "rld!"
push "o wo"
push "hell"
push byte 0x4
pop eax
xor ebx, ebx
mov ecx, esp
push byte 0xd
pop edx
int 0x80
xor eax, eax
inc eax
mov ebx, eax
int 0x80
chapp@chapp:~/code$ gcc sc.c -o sc -m32
chapp@chapp:~/code$ nasm hello.asm
chapp@chapp:~/code$ ./sc hello
hello world!