Wednesday, March 2, 2011

Time-of-Check-to-Time-of-Use (TOCTOU) attacks on Linux file systems

TOCTOU attack need exploit a race condition in a setuid program

setuid and setgid are Unix access rights flags that allow users to run an executable with the permissions of the executable's owner or group

Example1

buggy setuid program                             attacker 
 
                                      // create a file the attacker can access
                                      touch /home/attack/bad
// check user permissions to file
if (access("/home/attack/bad", R_OK) != 0) 
{
       exit(1);
}
                                      // remove file
                                      rm /home/attacker/bad

                                         // create a symbolic to link secrets
                                         ln -s /top/secret /home/attack/bad
// use file
fd = open("/home/attacker/bad", O_RDONLY);
// Do something about fd...
 
Example2
buggy setuid program                               attacker

                                    // create a symbolic link to a file the attacker can access
                                    ln -s /home/attack/bad /home/attack/symlink
   // check user permissions to file
   if (access("/home/attack/symlink", R_OK) != 0) {
       exit(1);
   }
                                    // update symbolic link to a secret file
                                    ln -sf /top/secret /home/attack/symlink
   // use file
   fd = open("/home/attacker/symlink", O_RDONLY);
   // Do something about fd...
 
 
Why does this work?
1. access check the real user ID permission, not the effective ID permission.
2. open will check the file permission, but it use effective ID permission, since it is a setuid program, it will open the file with program owner's permission
Why TOCTOU target at setuid program?
1. setuid always has this pattern: check permission use access(), then open() the file
2. setuid could open the file using program ower's permission. see man 2 open and man 2 access

more information please see this link

1 comment:

Alessandro Carminati said...

In theory it seems a simple, straight forward method.
But eventually I found a lot of practical problems in put it in place.
As you pointed out, you have a reason in do it, if your target is a suid one.
But as suid file, it has a many protections:
you cant ptrace it and you can't send it signals.
to make a long story short, you can't control it.
The only way I found to exploit this vulnerability, which implies a lot of luck, is bruteforce the race, which means launch something which would change the target file hoping the kernel will schedule it in the right moment.
Am I missing anything in this puzzle?