cybersecurity · intermediate · ~15 min

Is the file-access approach TOCTOU-safe?

Recognise the TOCTOU-safe pattern.

Challenge

Decide whether a file-access strategy avoids the time-of-check-to-time-of-use (TOCTOU) race: checking by path then re-opening by path lets an attacker swap the file in between.

Task

Implement int toctou_safe(const char *approach) that returns 1 for the safe strategies and 0 for the racy one:

  • "open-then-fstat" -> 1 (check the already-open descriptor)
  • "use-fd" -> 1 (operate on the open descriptor)
  • "stat-then-open" -> 0 (classic check-then-use race)

Input

  • approach: a NUL-terminated strategy name the grader provides (one of the three above).

Output

Returns 1 if the strategy is TOCTOU-safe, 0 otherwise.

Example

toctou_safe("open-then-fstat")   ->   1
toctou_safe("use-fd")            ->   1
toctou_safe("stat-then-open")    ->   0

Edge cases

  • Only the two safe names return 1; everything else returns 0.

Input format

A NUL-terminated strategy name approach.

Output format

1 for "open-then-fstat" or "use-fd"; 0 for "stat-then-open".

Constraints

Operating on the fd is safe; check-by-path then open-by-path is the race.

Starter code

#include <string.h>

int toctou_safe(const char *approach) {
    /* TODO */
    return 0;
}

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.