# Time-of-Check to Time-of-Use (TOCTOU)

{% embed url="<https://www.youtube.com/watch?v=5g137gsB9Wk>" %}

{% embed url="<https://exploit.education/nebula/level-10/>" %}

Can occur when there is a time gap between a program checking for a condition and a program actually using something, and the thing it checked can be swapped out during that time gap.&#x20;

For example, if a program checks that a file is not owned by root, and will read that file if the check succeeds. If you have a normal file at `/tmp/exploit`, and during the time gap, you swap it out for a symlink to `/etc/shadow`, then `/etc/shadow` will be read. Note that the filename of the symlink will remain the same, just the location where it’s linking to will change.

This program is very useful for quickly swapping out files. It swaps the filenames of two provided files:&#x20;

{% embed url="<https://github.com/sroettger/35c3ctf_chals/blob/master/logrotate/exploit/rename.c>" %}

### Prevention

Get a file descriptor once and then keep using that file descriptor.&#x20;

{% embed url="<https://www.youtube.com/watch?v=1hScemFvnzw>" %}

If you really must use a file path twice (like in `system(cat ${file_path})`, or if you have to pass a file path to another program), then you can pass in `/proc/PROCESS_ID/fd/FILE_DESCRIPTOR_NUMBER`. That is a direct symlink to a file that was opened.&#x20;

Also, if the file name is changed, that was opened, then the symlink will also point to the changed filename - it’s a file descriptor, so it updates. Even if the file is deleted, you can still read from it, because the handle still exists.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://heinosass.gitbook.io/leet-sheet/binary-exploitation/time-of-check-to-time-of-use-toctou.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
