why is an allocated buffer stored on the stack and the heap?
I have this code which has a format string vulnerability in it:
#include <stdio.h>
int main() {
char buf[1024];
char secret1[64];
char flag[64];
char secret2[64];
// Read in first secret menu item
FILE *fd = fopen("secret-menu-item-1.txt", "r");
if (fd == NULL){
printf("'secret-menu-item-1.txt' file not found, aborting.\n");
return 1;
}
fgets(secret1, 64, fd);
// Read in the flag
fd = fopen("flag.txt", "r");
if (fd == NULL){
printf("'flag.txt' file not found, aborting.\n");
return 1;
}
fgets(flag, 64, fd);
// Read in second secret menu item
fd = fopen("secret-menu-item-2.txt", "r");
if (fd == NULL){
printf("'secret-menu-item-2.txt' file not found, aborting.\n");
return 1;
}
fgets(secret2, 64, fd);
printf("Give me your order and I'll read it back to you:\n");
fflush(stdout);
scanf("%1024s", buf);
printf("Here's your order: ");
printf(buf);
printf("\n");
fflush(stdout);
printf("Bye!\n");
fflush(stdout);
return 0;
}
How to exploit this vulnerability in order to read the flag content? (but as a process, how to find the exact location in the stack, and what input to provide to the program)
What I tried so far:
I found out where is the location of the input and it's in the 30th location.
So I tried to input %31$s
and forward, but all I got back is some string that is located on the heap, so I start searching while debugging on the heap, and found the secrets and the flag on the heap.
So I'm stuck because
- I do not know why the string that gets printed is on the heap?
- How exactly can I make
printf
to print the buffers from the heap?
Edit:
so I understand from the comments that the reason why those strings are in the heap is because fgets
is using the heap internally.
So i try to break before the printf
and I was mistaken and I found the location that printed in the stack (according the address instead of the string)
but when I change from %30$p
to %40$p
the output is the same.
I thought (and apparently I'm wrong again) that the change from 30 to 40 should print me the 40th (10th?) location on the stack.
what am I missing?
Another edit:
can I provide a negative value to the printf
(%-10$p
)?