SECURITY ENGINEERING · PART 8 · WRITING SECURE CODE · CODE · 111 OF 229

Input Validation and Output Encoding Done Right

Most injection bugs come from two habits done wrong: trusting input and building output by string concatenation. This episode separates the two defenses, explains allowlist validation, why validation alone never stops injection, context-aware output encoding, parameterised queries for SQL, and the rule that fixes injection for good: keep code and data apart with APIs, not escaping.

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 9
  9. 10
  10. 11
  11. 12
  12. 13
  13. 14
  14. 15
  15. 16
  16. 17
  17. 18
  18. 19
  19. 20
  20. 21
  21. 22
  22. 23
  23. 24
  24. 25
  25. 26
  26. 27
  27. 28
  28. 29
  29. 30
  30. 31
  31. 32
  32. 33
  33. 34
  34. 35
  35. 36
  36. 37
  37. 38
  38. 39
  39. 40
  40. 41
  41. 42
  42. 43
  43. 44
  44. 45
  45. 46
  46. 47
  47. 48
  48. 49
  49. 50
  50. 51
  51. 52
  52. 53
  53. 54
  54. 55
  55. 56
  56. 57
  57. 58
  58. 59
  59. 60
  60. 61
  61. 62
  62. 63
  63. 64
  64. 106
  65. 107
  66. 108
  67. 109
  68. 110
  69. 111
  70. 112
  71. 113
  72. 114
  73. 115
  74. 116
  75. 117
  76. 118
  77. 119
  78. 120
  79. 121
  80. 122
  81. 123
  82. 124
  83. 125
  84. 126
  85. 127
  86. 128
  87. 129
  88. 130
  89. 131
  90. 132
  91. 133
  92. 134
  93. 135
  94. 136
  95. 137
  96. 138
  97. 139
  98. 140
  99. 141
  100. 142
  101. 143
  102. 144
1 / 10

Press play to hear the narration, or step through at your own pace.

Key takeaways

  • Validate input with allowlists
  • validation alone never stops injection
  • encode per context
  • parameterise queries

Notes

Two different jobs

The two defenses answer different questions. Validation asks: is this input well-formed and allowed? It runs when data arrives. Encoding, or parameterising, asks: how do I make this data safe for the specific place it is going, a database, an HTML page, a shell? It runs when data is used. People constantly confuse them, and try to stop injection with validation alone. You need both, and encoding at the point of use is the one that actually prevents injection.

Do not confuse them
  • validation: is this input well-formed and allowed? done when data arrives
  • encoding / parameterising: make data safe for a specific destination done when data is used
  • you need BOTH; neither replaces the other

Validate with allowlists

Validation should use an allowlist: define exactly what valid input looks like and reject everything else. An age is an integer from zero to a hundred and fifty. A country is one of a known set. A username matches a specific pattern. The opposite, a blocklist that tries to enumerate bad input, is always incomplete; attackers find the case you missed. Check type, length, range, format and set membership. And always validate on the server, because client-side checks are for user experience, not security.

Allowlist, not blocklist
  • allowlist: define the exact shape that is valid, reject the rest (age is 0-150; country is in this set)
  • blocklist: try to list bad input -> always incomplete
  • check type, length, range, format, set membership
  • validate on the server; client checks are UX only

Validation is not enough

Here is the insight that trips people up. The name O'Brien is perfectly valid input, but that apostrophe breaks a SQL query built by string concatenation. The comment with angle brackets may be legitimate text, but it is dangerous when placed in an HTML page. Validation cannot know the syntax rules of every place the data will go later. So you cannot validate your way out of injection. You make the data safe at each destination, which is encoding or parameterising.

The key insight
  • a name field: O'Brien is valid input
  • but O'Brien breaks a string- built SQL query
  • a comment: <b>hi</b> may be valid text, but dangerous in HTML
  • validation cannot know every destination's rules
  • so: make data safe AT the destination

Output encoding

Output encoding transforms data so it is treated as data, not code, in its destination. And it is context-specific: encoding for an HTML body differs from an HTML attribute, from JavaScript, from a URL. Angle brackets become HTML entities so the browser shows them instead of running them. Use your framework's encoder for the right context rather than hand-rolling it. Modern templating engines auto-escape by default, which handles most cross-site scripting; the danger is the places you turn escaping off.

Context-aware encoding
  • HTML body: HTML-encode (< becomes &lt;)
  • HTML attribute: attribute- encode
  • JavaScript: JS-encode / avoid
  • URL: URL-encode
  • use the framework's encoder for each context
  • auto-escaping templates do this for you; keep it on

Parameterise queries

For SQL the best defense is not encoding but parameterised queries, also called prepared statements. Instead of building a query string with the data inside it, you send the query with placeholders and the data separately. The database treats the parameters as pure data, never as command, so injection is impossible by construction. The rule is simple and absolute: never build a SQL statement by concatenating user input. The same idea applies to shell commands and other interpreters.

the one SQL rule
// NEVER build SQL by
// concatenation:
query = "... WHERE id = " + id;

// parameterise: code and data
// travel separately
stmt = conn.prepareStatement(
  "... WHERE id = ?");
stmt.setString(1, id);

Put it together

Put together, the pattern for every piece of untrusted input is: validate it on arrival with an allowlist, on the server. Then, when you use it, rely on safe APIs: parameterised queries for SQL, auto-escaping templates for HTML, passing arguments as a list rather than a shell string for commands. And encode for the exact output context where needed. One subtlety: canonicalise input first, decoding it to a single normal form before validating, so an attacker cannot hide an attack behind double-encoding.

The pattern for every input
  1. validate on arrival (allowlist, server-side)
  2. use safe APIs: parameterise SQL, auto-escape HTML, pass args to exec as a list
  3. encode for the exact output context
  4. canonicalise before validating (decode once)

Common mistakes

Mistakes. Relying on validation to stop injection instead of parameterising, which does not work. Blocklists of bad strings, which are always bypassable. Building SQL or shell commands by concatenation. Encoding for the wrong context, such as HTML-encoding data that goes into JavaScript. Turning off a template's auto-escaping with a raw or safe helper and forgetting why. And trusting client-side validation, which an attacker simply skips by calling the API directly.

Avoid these
  • validation instead of parameterising (not a fix)
  • blocklists of "bad" strings
  • building SQL or shell strings by concatenation
  • encoding for the wrong context
  • turning off auto-escaping with "raw" or "safe"
  • trusting client-side validation

Say it like this

In the interview: two separate defenses. I validate input with allowlists on the server to reject malformed data early. But validation does not prevent injection, because valid data like an apostrophe can still break a query. For injection I keep code and data apart: parameterised queries for SQL, auto-escaping templates with context encoding for HTML, and passing arguments as a list rather than a shell string for commands. Validation and encoding are complementary, not interchangeable.

In the interview
  • "Two defenses. Validate input
  • with allowlists on the server
  • to reject malformed data. But validation does not stop
  • injection; for that I keep
  • code and data apart: parameterised queries, auto- escaping templates with context encoding, args as a list for commands."

Interview questions

Q1What is the difference between input validation and output encoding?

Input validation checks that data arriving is well-formed and allowed, and rejects the rest. Output encoding transforms data so it is treated as data, not code, in a specific destination such as HTML or SQL. Both are needed; they are not interchangeable.

Q2Why is input validation alone not enough to stop injection?

Because valid input can still be dangerous in a given context: a name like O'Brien is legitimate but breaks a concatenated SQL query. Validation cannot know the syntax of every destination, so injection must be prevented where data is used.

Q3What is allowlist validation?

Validation that defines exactly what is acceptable, by type, length, range, format or membership in a known set, and rejects everything else. It is more robust than blocklisting, which tries to enumerate bad input and is always incomplete.

Q4What is a parameterised query?

A database query that uses placeholders for data and sends the values separately from the SQL, so the database treats them strictly as data. Also called a prepared statement, it prevents SQL injection by design and should always be used instead of string concatenation.

Q5What is context-aware output encoding?

Encoding chosen for the exact context the data lands in, because the rules differ for HTML body, HTML attributes, JavaScript, URLs and CSS. Using the wrong encoding for a context can leave a cross-site scripting hole.

Q6Should validation be done on the client or the server?

Always on the server, because clients can be bypassed by calling the API directly. Client-side validation is useful for user experience but provides no security guarantee on its own.

Q7What is canonicalisation and why does it matter for validation?

Converting input into a single standard form, such as decoding percent-encoding, before validating. Without it, attackers can hide malicious input behind multiple or mixed encodings that pass validation but are decoded dangerously later.

Q8How do you prevent cross-site scripting?

Primarily with context-aware output encoding, usually via a template engine's auto-escaping, plus input validation and a Content Security Policy as defence in depth. Avoid disabling auto-escaping and inserting untrusted data into dangerous sinks like innerHTML.