1

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?

2
  • 2
    A google search led to this hint: hkopp.github.io/2024/03/geras-insecure-programming-challenges It suggests to overwrite the return address on the stack instead of simply overwriting cookie. Commented Sep 9, 2024 at 17:04
  • 1
    If you can get the hang of using GDB or some other debugger on the compiled code then you will have a powerful tool you can use to figure out what is happening under the hood. Commented Sep 9, 2024 at 17:16

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.