/* Simple program to help you with common shellcode operations*/

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <errno.h>

int  decoder[] = {	//the decoder instructions , you dont want to change this :)
				    0x31,0xd2,0x31,0xc9,0x31,0xc0,0xeb
				   ,0x10,0x5e,0xb0,0x41,0xb1,0x23,0x30
				   ,0x06,0x46,0xfe,0xc9,0x38,0xd1,0x75
				   ,0xf7,0xeb,0x05,0xe8,0xeb
				   ,0xff,0xff,0xff
				 };
 
usage(char *progname) 
{	
	printf("\nTo execute shellcode : %s -e <file>\n", progname);
	printf("To print shellcode as C-like string : %s -p <file> \n", progname);
	printf("To xor shellcode: %s -x <file>  \n\n", progname);
	exit(1);
}


main(int argc, char **argv) 
{
	FILE *fp;
	void *code;
	int arg;
	int i;
	int l;
	int bperline = 15; // bytes to print per line
	int key = 'B';	   // the key we are xoring with	
	
 	struct stat sbuf;
 	long flen; 
 	void (*fptr)(void);
	

	printf("\n Schelper to help you with shellcodes by Aca\n\n");
	printf("\t anikolic@phearless.org\n");
	printf("\t http://www.phearless.org\n");
	printf("\t http://anikolic.phearless.org\n\n\n");

 	if(!(argc == 3)) usage(argv[0]);
 	if(stat(argv[2], &sbuf))
		{
		perror("stat");
		exit(1);
		}
	flen = (long) sbuf.st_size;
	if(!(code = malloc(flen))) 
		{
		perror("malloc");
		exit(1);
		}

 	if(!(fp = fopen(argv[2], "rb"))) 
		{
		perror("fopen");
		exit(1);
		}

	if(fread(code, 1, flen, fp) != flen) 
		{
		perror("fread");
		exit(1);
		}
 	if(fclose(fp)) 
		{
		perror("fclose");
		}

 	while ((arg = getopt (argc, argv, "e:p:x:")) != -1)
	{
 	switch (arg)
		{
 		case 'e':
 			printf("Executing shellcode...\n\n");
			fptr = (void (*)(void)) code;
 			(*fptr)();
 		break;
 	
		case 'p':
 			printf("\n Shellcode is %d bytes long: \n",flen);
 			printf("\nchar shellcode[] =\n");
 			l = bperline;
 			for(i = 0; i < flen; i++) 
				{
 				if(l >= bperline) 
					{
 					if(i) printf("\"\n");
 					printf( "\t\"");
 					l = 0;
 					}
 				l++;
 				printf("\\x%02x", ((unsigned char *)code)[i]);
 				}
 			printf("\";\n\n\n");
		break;
 	
		case 'x':
			printf("\n Encoding shellcode with key = 0x%x\n",key);
 			printf("\nchar shellcode[] =\n");
			l = bperline;
 			for(i = 0; i < sizeof(decoder)/4; i++) 
				{
				if(l >= bperline) 
					{
					if(i==0)printf("\n");
					else printf("\"\n");
					printf( "\t\"");
					l = 0;
					}
				l++;
				if(i==10)
					{
					printf("\\x%02x",key); // to change the key inside the decoder
					i++;
					}
				if(i==12)
					{
					printf("\\x%02x",flen); //to change the sc lenth in decoder
					i++;
					}
				printf("\\x%02x",decoder[i]);
				}
			l = bperline;
 			for(i = 0; i < flen;i++)
				{
				if(l>= bperline)
					{
					printf("\"\n");
					printf( "\t\"");
					l = 0;
					}
				l++;
				printf("\\x%02x",((unsigned char *)code)[i] ^= key);
				}
			printf("\";\n\n\n");
		break;

		default :
 			usage(argv[0]);
 		}
 	}
 	return 0;
 }



