Code is here:
#include <stdio.h> #define NUM 0x11a int data = NUM; int main(int argc, char * argv[]) { struct{ unsigned long memoryAddress; char array[50]; } locals; locals.memoryAddress= 2; scanf("%lx", &locals.memoryAddress); scanf("%49s", locals.array); printf(locals.array); data += 5; printf("\n%d\n", data); if(data != NUM + 0x5){ printf("Print me!\n"); } return 0; } I should get "Print me!". It's format string attack and I use %n and gdb.
So how can I get memory address of data to overwrite it?
NUMtodataand adding 5 todatayou expectdatato be different fromNUM+5.%nallows to write the number of characters written so far to a variable. If there is no variable, or if you use the accurate displacement (e.g.%5$n) you can select an arbitrary address to write to from the stack (in this case OP wants to write todata). Since you have control over the format string you can "pack" the arbitrary address into the format string itself and then find the appropriate displacement to make%nuse that address and write what you want where you want (combining it with%NNNcto writeNNNcharacters before the%nis hit).