Memory safety

Language such as C/C++ are unsafe language because they do not provide a memory management and it's the developer who manage the memory. So needs to be careful when we allocate or deallocate the variable. Protect against leak memory avoid security breaches and that can lead to vulnerabilities. C languages do not check the bound and lead to vulnerabilities, so the memory is unsafe.

libc allocator (GNU) use malloc for allocating memory. malloc create a small portion of memory (called chunks) in the memory. If not bound checking is done, we can read data outside the memory allocated.

malloc implement a coalesce system for merging free space after a memory block has been freed.

To check the memory if safety, we can use different tools, such as: * Sanitizers * Valgrind * Purify

Vulnerabilities

  • Stack exhaustion -> run out of the stack space
  • Heap exhaustion -> allocate more than the amount available
  • Memory leak -> memory isn't freed
  • NULL pointer dereference -> access to an object which has been freed and the pointer is NULL
  • Dangling pointers -> the program has mistakenly free pointers on a live object
  • Buffer overflows -> corrupt the buffer
  • Heap data overwrite -> Kind of buffer overflow but for the Heap
  • Uninitialized reads -> Read data after it has been allocated. The data can be unsafe
  • Invalid frees -> Free the pointer
  • Double frees -> Recalls the free twice

Buffer overflow

NULL Pointer dereference

Dangling pointers

$ cat dangling.c
#include <stdio.h>
#include <stdlib.h>

int main(void){
    int *a = (int*)malloc(5);
    int *b = a;

    printf("%p\n", a);
    printf("%p\n", b);
    a[0] = 25;
    printf("%d\n", *a);
    printf("%d\n", *b);

    free(a);
    a = NULL;
    printf("%p\n", a);
    printf("%p\n", b);
    printf("%d\n", *a);
    printf("%d\n", *b);

    return 0;
}
$ gcc dangling.c -o dangling && ./dangling
0x5d54554d32a0
0x5d54554d32a0
25
25
(nil)
0x5d54554d32a0
Segmentation fault (core dumped)

Garbage collector

References

  • https://people.cs.umass.edu/~emery/pubs/fp014-berger.pdf
  • https://gee.cs.oswego.edu/dl/html/malloc.html
  • https://people.cs.umass.edu/~emery/pubs/ccs03-novark.pdf
  • https://owasp.org/www-community/vulnerabilities/Buffer_Overflow
  • https://www.ics.com/blog/recent-initiatives-improve-c-and-c-memory-safety
  • https://www.gnu.org/software/libc/manual/html_node/The-GNU-Allocator.html
  • https://www.hboehm.info/gc/
  • https://www.hboehm.info/gc/leak.html
  • https://owasp.org/www-community/vulnerabilities/Memory_leak
  • https://cs341.cs.illinois.edu/coursebook/Malloc
  • https://www.linuxjournal.com/article/6679
  • https://en.wikipedia.org/wiki/Boehm_garbage_collector
  • https://cwe.mitre.org/data/definitions/126.html
  • https://www.isg.rhul.ac.uk/sullivan/pubs/tr/technicalreport-ir-cs-73.pdf