lectures.alex.balgavy.eu

Lecture notes from university.
git clone git://git.alex.balgavy.eu/lectures.alex.balgavy.eu.git
Log | Files | Refs | Submodules

buffer-overflow.md (1435B)


      1 +++
      2 title = 'Buffer Overflow'
      3 +++
      4 
      5 # Buffer overflow
      6 A basic example of a buffer overflow:
      7 
      8 ```c
      9 #include <stdio.h>
     10 #include <string.h>
     11 void hello(char *name) {
     12     char buf[16];
     13     strcpy(buf, name);
     14     printf("hello %s\n", buf);
     15 }
     16 int main(int argc, char **argv) {
     17     hello(argv[1]);
     18     return 0;
     19 }
     20 ```
     21 
     22 `buf` is limited to 16, but `strcpy` does not include that limit.
     23 So writing more characters (length > 15) will overwrite the lower parts of the stack -- frame pointer, return address.
     24 
     25 Three types of memory:
     26 - stack: local (non-static) variables, grows downwards (i.e. push decrements stack pointer)
     27 - heap: stores memory allocated by programmer via malloc, new, etc.
     28 - global: stores global and static variables
     29 
     30 In the code example, `buf` lives on the stack.
     31 
     32 Stack frames:
     33 - functions reserve part of stack for own use ("stack frame")
     34 - contains:
     35     - return address: where to continue after return
     36     - frame pointer: where is caller's stack frame
     37     - local variables
     38     - other temp storage needed by compiler
     39 
     40 So via this buffer overflow, the attacker can inject and run code, or run code already in the program.
     41 
     42 Without optimisations, return address is always `%ebp+8`.
     43 But we need to determine stack layout to see by how much we need to overflow buffer.
     44 
     45 E.g.:
     46 - target (return address): `%rbp+8`
     47 - overflowable buffer: `%rbp-16`
     48 - how many bytes before hitting the target: `(%rbp+8)-(%rbp-16) = 8 - -16 = 24`