1

I am trying to exploit the vulnerability in printf

#include <stdio.h>
int main()
{
  int a = 1, b = 2, c = 3, d = 4;
  printf("%d %d %d %d");
}
  1. a, b, c, d are pushed onto the stack.
  2. printf arguments are pushed onto stack and then return address
  3. Now, printf would increment the SP up from "%d%d%d%d" to reach arguments.
  4. But, as there are no arguments it should reach main local variables a then b ...

But, the output of the above is random large values

-1000081144 - 10000081128 4197428 4197568 -842270912

Q1: What are these values in the output. What is wrong in my understanding?

Q2: How to correct my code above to print the values of local variables in main function from printf? (by exploiting the vulnerabilty of printf)

codey modey
  • 983
  • 2
  • 10
  • 23

1 Answers1

4

There is no guarantee that the variables will be at the right location on the stack. You could inspect the stack (gdb) and see their proper addresses but that would hardly be a generic solution.

cnicutar
  • 178,505
  • 25
  • 365
  • 392
  • Okay, I agree with you. How do you visualize the stack frame. It is part of main memory, abstractly part of virtual memory. Now when we say SP is pointing to something. Then how many bytes is SP pointing too? and when I do SP+1, how many bytes the SP pointer moves ahead? – codey modey Feb 24 '14 at 09:08
  • 1
    @codeymodey Fire up `gdb` and say `break main`. Then try stepping (`step` or `stepi`), do `info frame`, `x/16x $rsp` etc. – cnicutar Feb 24 '14 at 09:11
  • x/16x $rsp works, also if I print whole stack by too many %d, I start seeing the values eventually. Also, a quick question why are these values above of different sizes (-1000081144 - 10000081128 4197428 4197568 -842270912)? – codey modey Feb 24 '14 at 09:22
  • 1
    @codeymodey What do you mean, different sizes ? They're all the same size (32 bits likely), but in decimal you usually don't print the leading 0s. – cnicutar Feb 24 '14 at 09:26
  • Okay, I got it. Also, how many bytes a SP points to in general? 4 bytes? – codey modey Feb 24 '14 at 09:30
  • @codeymodey sp, esp and rsp are just addresses. How many bytes they point to is something that the program decides, i.e. how many bytes it reads from the location. – cnicutar Feb 24 '14 at 09:42