cybersecurity · intermediate · ~15 min

Detect risky SQL chars

Recognise common signs of SQL injection attempts in user-supplied data — as a logging/alerting heuristic, not a sanitiser.

Challenge

Scan a string for characters and sequences commonly seen in SQL-injection attempts — as a logging heuristic, not a defence.

Task

Implement int contains_sql_special(const char *s) that returns 1 if s contains any of: a single quote, a double quote, a semicolon, the two-character sequence --, or the two-character sequence that starts a SQL block comment (/*). Otherwise return 0. No main — the grader calls it.

Input

s: a NUL-terminated string to inspect.

Output

1 if any risky character or sequence is present, 0 if the string is clean.

Example

contains_sql_special("hello world")     ->   0
contains_sql_special("O'Brien")        ->   1   (single quote)
contains_sql_special("a;b")             ->   1   (semicolon)
contains_sql_special("a--b")            ->   1   (-- sequence)

Edge cases

  • Empty string returns 0.

Rules

  • This is a teaching/alerting heuristic only. The real defence against SQL injection is parameterised queries, never string concatenation.

Why this matters

Detecting SQL-special characters in user input is a (toy, defensive) first step toward understanding SQL injection. In real code you'd use parameterised queries, not blacklists — but the detection skill matters for audits.

Input format

A NUL-terminated string s to inspect.

Output format

1 if a risky character or sequence is present, else 0.

Constraints

Detection heuristic only; the real defence is parameterised queries.

Starter code

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

Common mistakes

Treating ' (single quote) but missing -- (comment), ; (statement separator), or \ (escape). Black-listing alone is unsafe in production — always parameterise.

Edge cases to handle

Empty input. Unicode escape sequences. Comment style --.

Complexity

O(strlen).

Background lessons

Up next

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