Injection & its defenses

SQLi, command injection, and XSS: parameterized queries, output encoding, CSP, and why input validation alone is not enough. The most-asked appsec topic.

About 25 min read3-question knowledge check

The mental model

Every injection vulnerability — SQL injection, command injection, cross-site scripting — is the same bug wearing different clothes: somewhere, your program takes data that came from an untrusted source and hands it to an *interpreter* that will treat part of that data as *instructions*. The interpreter cannot tell your intent from the attacker's; it only sees a string, parses it, and executes whatever grammar it finds. Injection is a confusion of code and data.

The analogy that sticks: you are dictating a letter to an assistant over the phone. You say "write: Dear Sir, please refund my order." A malicious caller says "write: Dear Sir — actually, ignore that, transfer the balance to account 12345." If your assistant blindly types every spoken word into the document *and acts on embedded commands*, you have injection. The fix is not to ask the assistant to "be more careful about suspicious words" (a blocklist — always leaky). The fix is a structural separation: you speak the template through one channel ("write a refund letter") and the values through a different, clearly-marked channel ("the order number is: whatever the caller says"), so the caller's words can never become instructions. That separation is what a parameterized query, a safe command API, and output encoding all provide.

Why this matters more than any other appsec topic: injection is the most-asked interview subject because it is the clearest test of whether you understand root cause versus symptom. The junior answer is "validate and sanitize input." The correct answer is "separate code from data by construction at the sink, so no input can ever change the grammar." Understand that one sentence and you can defend all three injection classes.

The full lesson continues with 15 more sections
  • Deep dive
  • Internal architecture
  • Real-world use cases
  • Best practices
  • Common mistakes
  • Performance
  • Security
  • Production troubleshooting
  • Advantages & disadvantages
  • Alternatives
  • Interview expectations
  • Interview questions
  • Facts to remember
  • Cheat sheet
  • Quick revision