cybersecurity · intermediate · ~15 min · safe pentest lab

Detect command-injection characters in input

Recognize an injection attempt for logging / alerting purposes.

Challenge

Flag input that carries shell metacharacters — an indicator you can log or alert on when watching for command-injection attempts.

Task

Implement int contains_shell_special(const char *s) that returns 1 if s contains any of these shell metacharacters, else 0:

;  &  |  `  $  (  )  <  >  \n

Input

  • s: a NUL-terminated string the grader passes (a candidate command or argument).

Output

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

Example

contains_shell_special("hello")          ->   0
contains_shell_special("ls; rm -rf /")   ->   1
contains_shell_special("echo `whoami`")  ->   1
contains_shell_special("echo $HOME")     ->   1

Edge cases

  • A clean string with no metacharacters returns 0.
  • A NULL pointer returns 0.

Rules

  • This is detection, not sanitisation. The real fix for command injection is execvp with an explicit argv array — never escape-and-allow.

Input format

A NUL-terminated string s (a candidate command/argument).

Output format

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

Constraints

Detection only — do not attempt to sanitise the input.

Starter code

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

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