How does a Buffer Overflow Work?
The attacker can execute code by corrupting the stack
This is the stack when gets is called:
+---------------+
| envp | Program's environment
+---------------+
| argv | Argument vector
+---------------+
| argc | Argument count
+---------------+
| _start | Return address of main
+---------------+
| buff[0] | First byte of buffer (e.g. 'n')
+---------------+
| buff[1] | Second byte of buffer (e.g. 'o')
+---------------+
| buff[...] | More buffer bytes
+---------------+
| buff[19] | Last byte of buffer
+---------------+
| main+12 | Return address of gets
+---------------+
This is the corrupted stack after an attack:
+---------------+
| envp | Program's environment
+---------------+
| argv | Argument vector
+---------------+
| argc | Argument count
+---------------+
| _start | Return address of main
+---------------+
| buff[0] |<-+ First byte of buffer (EVIL CODE)
+---------------+ |
| buff[1] | | Second byte of buffer (EVIL CODE)
+---------------+ |
| buff[...] | | More buffer bytes (more EVIL CODE)
+---------------+ |
| buff[19] | | Last byte of buffer
+---------------+ |
| &buff[0] |--^ Overwritten return address
+---------------+