On October 21st, 2016 the kernel which is used by millions of devices in the world faced a major bug which could cause the whole open source world foundation to cave in. It was the discovery of Dirty COW (Dirty copy-on-write) which had been a bug lurking in the famous Linux kernel since version 2.6.22 in 2007.
Dirty COW is a privilege escalation bug in the Linux kernel. Since the Linux kernel is used across many different devices and systems - including embedded, mobile (Android), virtualization and cloud platforms (Docker, AWS ), and IoT devices, the impact could be huge.
To understand how the flaw works, we first need to understand how the memory is handled by Linux kernel.
The logical memory consists of 4k blocks of contiguous memory locations called pages. These pages are mapped to physical memory pages by a translation table in the CPU.
Suppose there are two processes which read from the same physical memory location.
As long as reading continues, the physical memory page will not alter. When one process tries to modify or write something to the physical memory, the kernel comes in action and makes a copy of the physical page and will give it to the process which is supposed to modify the page.
So the modification will be on the copy of the memory page instead of the original page. This is called copy-on-write or COW. Remember, the sole responsibility of a kernel is to allocate memory for the processes so that they don't interfere with each other. So far so good. But there is a race condition occurring when the kernel makes a copy of the original page and writes to it. A race condition occurs when two or more threads can access shared data and they try to change it at the same time.
Dirty COW exploits work by tricking the kernel into a race condition in the copy-on-write mechanism. To understand the exploit, you need a root owned file which has read access to unprivileged users. Now I will explain the important code portions of the exploit. The full formed code can be found here