Format String Exploits

This is an oldie but goodie. I’ve seen format string bugs in the past, and have even exploited a few using the “magic formula”. Today, I thought it would be a good time to actually sit down and figure out how they work. The below link is an excellent resource to anyone learning about these.

print shell code

From the book “Buffer Overflow Attacks” by Foster and others, I came across this very handy tool for testing developing shellcode.  It takes your assembly and puts it into a well commented C array to be tested by execution or simply printing to the screen.

To compile thes program, type gcc -o printshell printshellcode.c

Now, if you want to try out your shellcode assembly,

  • Type the instructions in a .S file
  • Execute nasm -o <filename> <filename>.S
    • To print the shellcode use printshellcode -p <filename>.
    • To execute the shellcode use printshellcode -e <filename>

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <errno.h>
/*Print message function*/
static void croak(const char *msg){
    fprintf(stderr, "%s\n", msg);

/*Usage funcion*/
static void usage(const char *prgnam){
    fprintf(stderr, "\nExecute code : %s -e \n", prgnam);

/*Signal error and bail out*/
 static void barf(const char *msg){

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

    FILE	*fp;
    void	*code;
    int		i,l,arg;
    int		m=15; /* max number of bytes on a line*/

    struct stat sbuf;
    long	flen; /*assume files are &lt; 2**32*/
    void	(*fptr)(void);

    if(argc &lt; 3) usage(argv[0]);
    if(stat(argv[2], &amp;sbuf)) barf(&quot;failed to stat file&quot;);
    flen = (long) sbuf.st_size;
    if(!(code = malloc(flen))) barf(&quot;failed to grab enough memory&quot;);
    if(!(fp = fopen(argv[2], &quot;rb&quot;))) barf(&quot;failed to open file&quot;);
    if(fclose(fp)) barf(&quot;failed to close file&quot;);

    while ((arg = getopt (argc, argv, &quot;e:p:&quot;)) != 1){
        case 'e':
          croak(&quot;Calling code ...&quot;);
          fptr = (void (*)(void)) code;
        case 'p':
          printf(&quot;\n/* The following shellcode is %d bytes long: */\n&quot;,flen);
          printf(&quot;\nchar shellcode[] = \n&quot;);
          l = m;
          for(i = 0; i= m){
              if(i) printf("\"\n");
              printf( "\t\"");
              l = 0;
            printf("\\x%02x", ((unsigned char *)code)[i]);

    return 0;