cybersecurity · intermediate · ~15 min

Detect world-writable files

`stat` and POSIX permission bits.

Challenge

Check whether a file is world-writable by inspecting its permission bits with stat.

Task

Implement int is_world_writable(const char *path) that returns 1 if the file at path has the world-writable bit (S_IWOTH) set, 0 if not, and -1 if stat fails. No main — the grader calls it.

Input

path: the file to inspect.

Output

1 (world-writable), 0 (not), or -1 (stat failed, e.g. the file does not exist).

Example

chmod 0666 file   ->   is_world_writable("file") = 1
chmod 0644 file   ->   is_world_writable("file") = 0
is_world_writable("does-not-exist")   ->   -1

Edge cases

  • A missing file (or any stat error) returns -1.

Rules

  • Use stat and test st.st_mode & S_IWOTH.

Input format

A file path.

Output format

1 if world-writable, 0 if not, -1 if stat fails.

Constraints

Use stat and test st_mode against S_IWOTH.

Starter code

#include <sys/stat.h>

int is_world_writable(const char *path) {
    /* TODO */
    return -1;
}

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