Skip to content

Instantly share code, notes, and snippets.

@RobertLarsen
Created March 20, 2015 12:58
Show Gist options
  • Save RobertLarsen/9b3f97ebb1da99e199e7 to your computer and use it in GitHub Desktop.
Save RobertLarsen/9b3f97ebb1da99e199e7 to your computer and use it in GitHub Desktop.
Program for testing shellcode
#include <fcntl.h>
#include <netinet/in.h>
#include <signal.h>
#include <stdio.h>
#include <sys/mman.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
static int create_server(unsigned short port) {
int server;
int flags;
#if defined(IPV6)
struct sockaddr_in6 addr;
server = socket(AF_INET6, SOCK_STREAM, 0);
if (server < 0) {
return -1;
}
flags = 1;
if (setsockopt(server, SOL_SOCKET, SO_REUSEADDR, &flags, sizeof(flags)) < 0) {
close(server);
return -1;
}
addr.sin6_family = AF_INET6;
addr.sin6_port = htons(port);
addr.sin6_addr = in6addr_any;
#else
struct sockaddr_in addr;
server = socket(AF_INET, SOCK_STREAM, 0);
if (server < 0) {
return -1;
}
flags = 1;
if (setsockopt(server, SOL_SOCKET, SO_REUSEADDR, &flags, sizeof(flags)) < 0) {
close(server);
return -1;
}
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = htonl(INADDR_ANY);
#endif
if (bind(server, (struct sockaddr*)&addr, sizeof(addr)) < 0) {
close(server);
return -1;
}
if (listen(server, 10) < 0) {
close(server);
return -1;
}
return server;
}
void child_died(int sig) {
wait(&sig);
}
int main(int argc, char ** argv) {
pid_t pid;
size_t len;
struct stat st;
int server, client, val, fd, r, total = 0;
struct timeval timeout = {1, 0};
unsigned short port;
int (*shellcode)();
if (argc > 1) {
if (stat(argv[1], &st) == 0) {
/* We have a file */
len = (st.st_size + 4096 - 1) & ~(4096-1);
if ((fd = open(argv[1], O_RDWR)) >= 0) {
if ((shellcode = mmap(NULL, len, PROT_READ | PROT_WRITE | PROT_EXEC, MAP_PRIVATE, fd, 0)) != MAP_FAILED) {
shellcode();
munmap(shellcode, len);
}
close(fd);
}
} else if ((port = atoi(argv[1])) >= 1024) {
/* We have a port */
signal(SIGCHLD, child_died);
shellcode = mmap(NULL, 4096 * 8, PROT_READ | PROT_WRITE | PROT_EXEC, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
if (shellcode == MAP_FAILED) {
fprintf(stderr, "Could not map memory.\n");
return 1;
}
if ((server = create_server(port)) >= 0) {
while ((client = accept(server, NULL, NULL)) >= 0) {
#if defined(FORK_SERVER)
pid = fork();
if (pid) {
/* Parent */
close(client);
} else {
/* Child */
close(server);
#endif
read(client, shellcode + total, 4096 * 8 - total);
val = shellcode();
close(client);
#if defined(FORK_SERVER)
}
#endif
}
} else {
fprintf(stderr, "Could not create server.\n");
}
munmap(shellcode, 4096 * 8);
} else {
fprintf(stderr, "%s is not a readable file and not a usable port.\n", argv[1]);
return 1;
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment