# State Related CWEs

CWE-367: Time-of-check Time-of-use (TOCTOU) Race Condition.

1. The software checks the state of a resource before using that resource.
2. The r**esource's state can change between the check and the use** in a way that invalidates the results of the check.

This can cause the software to perform invalid actions when the resource is in an unexpected state.

## CWE-367 - TOCTOU

**Time-Of-Check, Time-Of-Use**

The software **checks the state of a resource (TOC)** before using that resource, but the **resource's state can change between the check and the use (TOU)** in a way that invalidates the results of the check.

This can cause the software **to perform invalid actions** when the resource is in an unexpected state.

```python
if os.access(filename):
    headers = {“Authorization: “ + getAuth(username)}
    f = open(filename, ‘r’)
    data = f.read()
    f.close()
    requests.post(URL, data=data, headers=headers)
```

<figure><img src="https://3744219775-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUaTnynVhA2CYjsGJT14j%2Fuploads%2FKyxRjJvayGfoccpGwmpk%2F2023-11-20_11-35.png?alt=media&#x26;token=f07b5046-81dd-422e-9c69-3a42a42d9bc6" alt=""><figcaption></figcaption></figure>

### Attack

Program run with elevated privileges (setuid):

* filename = data.txt

Result:

* Program will upload /etc/shadow

Access:

* Use the real uid/gid to test for access to _path_.

Open:

* Opens file using the effective uid/gid.

<figure><img src="https://3744219775-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUaTnynVhA2CYjsGJT14j%2Fuploads%2F220QGDBFnzprXSOzUgC7%2F2023-11-20_11-40.png?alt=media&#x26;token=1d60332f-1cda-4026-8e90-117602b2ab7e" alt=""><figcaption></figcaption></figure>

And the list goes on...

<figure><img src="https://3744219775-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUaTnynVhA2CYjsGJT14j%2Fuploads%2Fckon2U2FgAU2nZHz5RI0%2F2023-11-20_11-41.png?alt=media&#x26;token=a68283da-1e5e-4f16-9547-56939edcb16d" alt=""><figcaption></figcaption></figure>

Should be:

```python
user = get_user(username)    #get_user makes a single query
```

### Bad Logic

Some logic mistakes can create implicit TOCTOU errors.

* Not attacks, but software mistakes.

<figure><img src="https://3744219775-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUaTnynVhA2CYjsGJT14j%2Fuploads%2FkXyPUqvFAhQoGUo35fVj%2F2023-11-20_11-44.png?alt=media&#x26;token=0e3f2d55-b9b9-43ef-9811-de0379c4ec98" alt=""><figcaption></figcaption></figure>

Test it:

```python
import os
data = "My data records!”
f = open("file.txt", "w")
#os.unlink("file.txt")
f.write(data)
f.close()
```

### TOCTOU

In practice, TOCTOU is extremely prevalent.

* **dependent on system performance.**
  * Higher performance will make vulnerable windows smaller, but the attacker may have similar resources if running locally.
* **dependent on target** CPU architectures, compilers and flags.
  * The code produced may mask the vulnerability.
* hard to debug dynamically.
  * Behavior under a debugger will be different.
  * Subject to small timings.

Prevention.

* Assert that actions are serialized as expected: may require lower layer knowledge.
* Force serialization manually (for DBs and other shared objects).
* If possible, send macro ops to systems (whole transactions) which lock resources at source.
* Reduce the use of filenames to a single call, then use File Descriptors.

## CWE-365: Race Condition in Switch

The switch instruction is inherently dangerous as the expected behavior is very different from the actual behavior.

```c
switch(a){
    case 0: foo(); break;
    case 1: bar(); break;
    ...
    case n: zed(); break;
}
```

Issue:

1. “a” can change between comparisons.
2. “a” may be matched to an incorrect function.
3. “a” may not be matched!

```c
int f(int num) {
    int a = num;
    switch(a){
        case 0: foo(); break;
        case 1: bar(); break;
        case 3: zed(); break;
    }
}
```

<figure><img src="https://3744219775-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUaTnynVhA2CYjsGJT14j%2Fuploads%2F36biZPj6yRc5rWxDYoWR%2F2023-11-20_11-55.png?alt=media&#x26;token=043641e5-81ba-4d95-a275-a4f5e98bd004" alt=""><figcaption></figcaption></figure>
