DEV Community

Cover image for Dirty COW exploit that broke linux in 2016
Advik Kant
Advik Kant

Posted on

Dirty COW exploit that broke linux in 2016

Introduction-

You may have heard of dirty COW (CVE-2016-5195) exploit if you are a seasoned veteran in the red teaming space. So what’s the big deal with it. Well back in 2016, this 150 lines of C code exploit would allow any attacker to gain root access to your Linux system with just exploiting a simple race condition.

Lets see what this vulnerability is all about

What is COW (Copy on Write)-

In Linux processes which share the same memory are treated as read-only mode as long as they point to the same page. When one of them wants to write to these only then the Linux kernel makes private copy of the file for that particular process. This is referred to as COW (Copy-on-Write).

Dirty COW vulnerability-

Now imagine if we want to write to /etc/passwd file on a Linux which stores user account information but we only have read permission and not any write permission how do we exploit this COW property.

Exploitation Overview-

Well here is how some attackers thought about exploiting it.

  1. Map the target file like (/etc/passwd) into memory so that we can exploit the COW property.
  2. Spawn two racing threads.

i) Thread A- tries to write into that memory but obviously kernel recognizes this and tries to get it the private copy.

ii) Thread B- Use madvise() function, this function basically tells the kernel to invalidate or remove the same memory page.

void *madviseThread(void *arg) {
int i, c = 0;
for(i = 0; i < 200000000; i++) {
        c += madvise(map, 100, MADV_DONTNEED);
}
printf("madvise %d\n\n", c);
}
Enter fullscreen mode Exit fullscreen mode
  1. This creates a race condition for the kernel as one thread is requesting a COW for the page and the other thread is trying to invalidate it.
  2. In the midst of this confusion, the kernel instead of handing the private copy of the page to the user, grants the write operations on the file.
  3. This way we can get a write operation on the /etc/passwd file and create a new root user and get full access to the Linux system. Here's the full exploit code https://www.exploit-db.com/exploits/40839.

Fix and Patches-

So in order to fix this mess they-

  1. tightened COW logic-

this basically ensured that the kernel would always create the private copy of memory page first no concurrent function like madvise() could interrupt it.

  1. Follow up architecture patches-

Some CPU architectures had some race conditions which were fixed.

Top comments (0)