Secure Coding in C · intermediate · ~15 min

Detect SQL-injection metacharacters in user input

Classify a candidate string as 'has SQL metacharacters' or 'safe-looking' — the validate-don't-build-strings half of SQL injection defence.

Overview

Walk the input once, look for single-quote, --, /*, ;, or case-insensitive UNION SELECT. Return 1 if any present.

Why it matters

Parameterised queries are the proper fix. But a metacharacter detector on the input layer adds defence in depth and gives you signal in your logs.

Lesson

Why this matters

The real defence against SQL injection is parameterised queries — never build SQL strings from user input. But on the way to that, defenders write input validators that flag suspicious metacharacters early, before the input even gets to the query layer.

This exercise teaches the metacharacter detector. The proper cure (prepared statements) is mentioned in the lesson but practiced separately.

What the function detects

  • single quotes (') — the classic injection delimiter
  • SQL comment markers (--, /*)
  • statement terminators (;)
  • common UNION-injection keywords (UNION SELECT, case-insensitive)

Your job

Implement int has_sqli_markers(const char *input) returning:

  • 0 — input contains no suspicious patterns
  • 1 — input contains at least one suspicious pattern

The function is a flagger, not a sanitiser. Real defence is parameterised queries — this just tells the application "this input deserves a second look".

Common mistakes

  • Trying to sanitise. Don't. Reject suspicious inputs; never escape them and pass them on.
  • Forgetting case-insensitive match for UNION SELECT. Use a tiny inline case-folding helper.
  • Walking past the NUL.

What this is NOT

  • A SQL parser. You're flagging metacharacters, not parsing intent.
  • A replacement for prepared statements. It's a layer, not the cure.

Summary

One-pass string walk. Flag, don't sanitise. The proper cure is prepared statements.

Practice with these exercises