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 resource'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.

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

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.

And the list goes on...

Should be:

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.

Test it:

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.

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!

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

Last updated