cybersecurity · intermediate · ~15 min

Detect shell metacharacters

Spot characters that break out of a shell command.

Challenge

Flag input that carries characters able to break out of a shell command — an audit signal for command injection.

Task

Implement int has_shell_meta(const char *s) that returns 1 if s contains any shell metacharacter, else 0.

The metacharacters are:

;  |  &  $  `  (  )  <  >  \n

Input

  • s: a NUL-terminated string the grader passes.

Output

Returns int: 1 if any listed metacharacter is present, else 0.

Example

has_shell_meta("ls; rm -rf /")   ->   1
has_shell_meta("a|b")            ->   1
has_shell_meta("report.txt")     ->   0

Edge cases

  • A clean string with no metacharacters returns 0.

Rules

  • Detection only. The real fix is to avoid the shell entirely (use execv with an argv array).

Input format

A NUL-terminated string s.

Output format

An int: 1 if s contains any shell metacharacter, else 0.

Constraints

Detection only — do not sanitise.

Starter code

#include <string.h>

int has_shell_meta(const char *s) {
    /* TODO */
    return 0;
}

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