Simple explanation of how Dirty COW works?

You and 3 other people are studying for a test, using the same notes.

You say "I gotta go, I need to make a copy of these notes for myself that I can mark up... let me go make a copy!"

You take the notes to the photocopier, copy them, alter the original, and then take the modified original back to the rest of the group. That modified version is bad; you've altered some answers to be wrong.

The rest of the group is left studying off of a bad version of the notes, while you take the good version home.

You pass the test.

They fail.


The only nuance between this example and Dirty COW is that in Dirty COW you aren't supposed to be handed the original; the kernel makes the copy for you. But there's a race condition that mistakenly gives you access to the original when you ask for a copy. "Race condition" means "you can sneak in access to something you shouldn't have access to."


I'm not a linux kernel expert, but I am familiar with the concepts involved and I read Linus' comment and the diff. I'll give it a go - perhaps people can correct me if I get it wrong and we'll hash things out together.

Copy On Write is an internal memory concept where, primarily for performance reasons, operations that make a copy of a section of memory don't actually get their own copy unless and until they make a change to that memory - at which point, you quickly make their copy, make the change to that and hand it back to them. The advantage is that you don't have to do the work of making the copy unless and until they actually change it - faster, less memory usage, better caching.

The bug here is in the code that does that copying. It appears that there is a race condition in that copy (or actually in the bookkeeping around that copy). A race condition happens when two different processes or threads are accessing the same resource and step on each other. In this case, what happens is that the memory is flagged to be writeable before it is actually copied - if two threads are working very closely to each other, the second can take advantage of the writeable flag and actually write to the original memory, not the copy.

The exploit is that this lets a process elevate itself by getting write access to the kernel's own understanding of it. The kernel knows what user each process is running at - by taking a copy of that memory that kernel is using to store that info using Copy On Write, then using this Dirty COW bug, they can actually write the user info into the kernel's own copy. So they write that the process is being run as root.. and then they can do anything.

The demo program uses that to write to a file only writeable by root, but it could have done literally anything. The fix was to separate out a new flag saying they are doing a CopyOnWrite, instead of using the Write flag for both.