7

I'm testing a buffer overflow exploitation but when I compile my code, gcc uses memory alignment and the extra bytes added by the compiler force me to deal with this padding.

Is there a way to compile the code with gcc without padding?

This is the overflow achieved with padding but I want a clear view of it without compiler garbage:

(gdb) x/60x 0xbffff450
0xbffff450: 0xbffff460  0x00000001  0x00000000  0x00000001
0xbffff460: *0x41414141 0x41414141  0x41414141  0x41414141[buffer begins]
0xbffff470: 0x41414141  0x41414141  0x41414141  0x41414141
0xbffff480: 0x41414141  0x41414141  0x41414141  0x41414141
0xbffff490: 0x41414141  0x41414141  0x41414141  0x41414141*[buffer ends]
0xbffff4a0: 0x41414141  0x41414141  0x41414141 [0x0804851c][Return Address]

Regards

Edit:

This is the code I'm compiling:

#include <stdio.h>

char *secret = "pepito";

void go_shell(){
    char *shell = "/bin/sh";
    char *cmd[] = { "/bin/sh", 0 };
    printf("¿Quieres jugar a un juego?...\n");
    setreuid(0);
    execve(shell,cmd,0);
}

int authorize(){
    char password[64];
    printf("Escriba la contraseña: ");
    gets(password);
    if (!strcmp(password,secret))
        return 1;
    else
        return 0;
}

int main(){
    if (authorize()){
        printf("Acceso permitido\n");
        go_shell();
    } else{
        printf("Acceso denegado\n");
    }
    return 0;
}
user207421
  • 305,947
  • 44
  • 307
  • 483
Nucklear
  • 478
  • 5
  • 21
  • Possibly related question: http://stackoverflow.com/questions/18341540/no-memory-alignment-with-gcc . –  Oct 15 '13 at 09:43
  • You can use `#define packed_data __attribute__((__packed__))` and prefix your structs with it – janisz Oct 15 '13 at 11:21
  • @janisz In my code I don't use data structs, the padding is applied to the var password 64 bytes long. – Nucklear Oct 15 '13 at 13:08
  • Oh, I see. I can't check it right now but have you tried [-fno-align-commons](http://gcc.gnu.org/onlinedocs/gfortran/Code-Gen-Options.html) – janisz Oct 15 '13 at 14:21
  • @janisz This is the output of GCC: cc1: warning: command line option ‘-fno-align-commons’ is valid for Fortran but not for C [enabled by default] – Nucklear Oct 15 '13 at 14:28
  • @janisz Also this is the memory with the buffer filled with 64 A http://pastebin.com/qnMf29PQ . Notice that after the buffer, there are 8Bytes of junk plus EBP and finally the return address. – Nucklear Oct 15 '13 at 14:46

1 Answers1

5

Yes, you need to adjust how gcc allocates stack space. By default, it attempts to keep the stack aligned on 16-byte boundaries since certain instructions (SSE*) require it. If you specify -mpreferred-stack-boundary=2 on the command line when you compile, gcc will keep the stack aligned to 2^2=4, which what you were expecting since you are using a 32-bit environment.

Dwayne Towell
  • 8,154
  • 4
  • 36
  • 49