Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Session 2: Buffer Overflow

Caution

You don’t have the authorization to feed any of this content to any online LLM for any purpose. If for some reason, you need to interact with a LLM, you may use an open-source model on your local machine to feed the course content. See llama.cpp to install a CPU efficient LLM inference and use your own computer to ask your questions.

In the first practical session, we studied common bugs that arise when programming in memory-unsafe programming languages. Notably, we saw how misuse of C buffers can lead to buffer overflows. We’ll delve deeper into them and see how an adversary can exploit such a vulnerability.

x86 Stack Layout

As a quick reminder, and because it’s easier than using words, let’s visualize how the x86 stack works. Use the buttons below to navigate instruction by instruction.

#include <stdint.h>

void function(int32_t a) {
    int32_t b[] = { 3, a, 5 };
}

int main(void) {
    int32_t a = 1;
    int32_t b = 2;
    function(4);
    return 0;
}
function:
        pushl   %ebp
        movl    %esp, %ebp
        subl    $16, %esp
        movl    $3, -12(%ebp)
        movl    8(%ebp), %eax
        movl    %eax, -8(%ebp)
        movl    $5, -4(%ebp)
        movl    %ebp, %esp
        popl    %ebp
        ret
main:
        pushl   %ebp
        movl    %esp, %ebp
        subl    $16, %esp
        movl    $1, -4(%ebp)
        movl    $2, -8(%ebp)
        pushl   $4
        call    function
        addl    $4, %esp
        movl    $0, %eax
        movl    %ebp, %esp
        popl    %ebp
        ret
ebp = ????????
esp = ffffe000
eax = ????????

    esp ffffe000 ???????? <main's return address>
        ffffdffc ????????
        ffffdff8 ????????
        ffffdff4 ????????
        ffffdff0 ????????
        ffffdfec ????????
        ffffdfe8 ????????
        ffffdfe4 ????????
        ffffdfe0 ????????
        ffffdfdc ????????
        ffffdfd8 ????????
        ffffdfd4 ????????
        ffffdfd0 ????????

See the return address stored very close to the b buffer? That’s an interesting target for an adversary to overwrite.