cybersecurity · intermediate · ~15 min

Strip dangerous environment variables before exec

The env-scrubber pattern used by every setuid program.

Challenge

Flag an environment entry that a setuid binary must scrub before execve — inheriting LD_PRELOAD or IFS from an attacker is game over.

Task

Implement int is_dangerous_env(const char *kv) that returns 1 if the NAME=VALUE string kv has one of the dangerous names below immediately followed by =, else 0.

Dangerous names:

LD_PRELOAD  LD_LIBRARY_PATH  LD_AUDIT
DYLD_INSERT_LIBRARIES  DYLD_LIBRARY_PATH  DYLD_FORCE_FLAT_NAMESPACE
IFS

Input

  • kv: a single NAME=VALUE environment string (no newline) the grader passes.

Output

Returns int: 1 if kv's name part exactly matches a dangerous name and is followed by =, else 0.

Example

is_dangerous_env("LD_PRELOAD=/tmp/evil.so")   ->   1
is_dangerous_env("IFS= ")                      ->   1
is_dangerous_env("PATH=/usr/bin")              ->   0
is_dangerous_env("MY_LD_PRELOAD=x")            ->   0   (prefix only, not a match)
is_dangerous_env("LD_PRELOAD")                 ->   0   (no '=')
is_dangerous_env(NULL)                          ->   0

Edge cases

  • A name without a following = is not a match.
  • A longer name that merely contains a dangerous name (MY_LD_PRELOAD=) is not a match.
  • NULL or empty input returns 0.

Rules

  • Match the exact name followed by =; never partial-match (do not use strstr).

Why this matters

Setuid binaries that inherit LD_PRELOAD or LD_LIBRARY_PATH are owned. Stripping the dangerous variables BEFORE execve is the standard defence.

Input format

A single NAME=VALUE environment string kv (no newline).

Output format

An int: 1 if the name exactly matches a dangerous name followed by =, else 0.

Constraints

Match the exact name followed by =; never partial-match.

Starter code

int is_dangerous_env(const char *kv) { /* TODO */ (void)kv; return 0; }

Common mistakes

Using strstr — matches MY_LD_PRELOAD=... too. Use strncmp + '=' check.

Edge cases to handle

No '=' in input. Name without value (LD_PRELOAD=). Empty string.

Complexity

O(N * len) where N is list length.

Background lessons

Up next

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