Secure coding for defenders: preventing SQL injection and XSS with the actual fixes
TL;DR. Two web bug classes still dominate beginner lessons: mixing untrusted data into SQL, and mixing untrusted data into HTML. The fixes are not “filters you add later.” They are parameterized queries (or an equivalent safe API) for the database, and context-aware encoding or a safe template engine for the page. This article shows what those fixes look like in ordinary code. It does not include exploit strings, attack payloads, or bypass tricks.
The rule that replaces a dozen myths
Untrusted data — anything from a form, a query string, a header, a file, or another service — must not be copied into a command or a document as if it were code you wrote. SQL is a command. HTML, and sometimes JavaScript or CSS, is a document with structure. The safe pattern is: keep the data in a parameter or a text node, and let a well-tested library apply the right encoding for that context.
Input “sanitising” that tries to delete suspicious characters is a weaker backup, not the primary control. Character sets, encodings and new syntax will surprise you. Frameworks already solved the common cases; your job is to use them, and to notice the places you went around them.
SQL: the fix is a parameter, not a string
The fragile pattern is building a statement with string formatting or concatenation, then sending that whole string to the database. Even a value you “trust today” can become untrusted after a feature change.
The standard fix is a parameterized query (prepared statement). The SQL text contains a placeholder; the value travels separately. A Python example with a common driver style:
# Authorized application code: the value never becomes part of the SQL text.
email = request.form.get("email", "")
cur.execute(
"SELECT id, name FROM accounts WHERE email = %s",
(email,),
)
row = cur.fetchone()
In other languages the names change (?, named parameters, or a query builder) and the idea does not. Use the official API of your driver or ORM. A second related fix is to avoid dynamic table or column names from user input; if a sort field must be chosen, map it through an allow-list of identifiers you defined, never by pasting a request field into the statement.
For changes (INSERT, UPDATE, DELETE) the same rule holds. For administrative tools, wrap the operation in authorization checks: being able to run a parameterised query is not the same as being allowed to change that row.
XSS: the fix is encoding in the right context
Cross-site scripting happens when untrusted text is interpreted as HTML or script in a browser. The usual fix on the server is to emit text through a template engine with auto-escaping enabled, or to encode explicitly for HTML body text.
A template-style fix (many engines have an equivalent; keep auto-escape on):
<!-- Safe default: the engine encodes the comment as text, not as markup. -->
<article>
<h2>{{ post.title }}</h2>
<p>{{ comment.body }}</p>
</article>
If you must build a fragment in code, encode for that context with a standard library, not with an ad-hoc replace:
from html import escape
def render_comment(body: str) -> str:
# HTML body context. Different contexts (attributes, URLs, JS) need different encoders.
return f"<p>{escape(body, quote=True)}</p>"
Three extra rules matter in practice:
- Do not turn escape off to “make rich text work,” unless you have a documented HTML sanitiser and a reason. Prefer Markdown or a tightly constrained editor, sanitised on the server.
- Attributes and URLs are different contexts. A value that is safe in a paragraph may not be safe in
hrefor in an inline event handler. Prefer not to put untrusted data in those places; if you must, use a library that encodes for that context, and allow-list URL schemes (httpsonly, for example). - A Content-Security-Policy (see the security-headers article in this series) reduces the damage if a bug slips through. It does not replace encoding.
Cookie flags (HttpOnly, Secure, SameSite) and a careful CORS policy help after the fact. They are complements.
A comparison you can put in a review
| Situation | Fragile habit | Fix to require in review |
|---|---|---|
| Look up a row by a form field | Concatenate the field into SQL | Parameter or ORM filter; no dynamic identifiers |
| Show a user comment on a page | Insert the string into HTML | Auto-escaped template or html.escape (or equivalent) |
| Optional sort or table name | Paste the request into the statement | Server-side allow-list of known names |
| Rich text in a comment | Disable escaping | Sanitiser you chose, plus CSP |
| Admin “run a report” box | Accept a fragment of SQL | Fixed queries, parameters only |
How to practise legally
Write a small application you own, add tests that the safe API is used, and use an official guided lab or a deliberately vulnerable application on a machine you control if you want to see the contrast. Do not test other people’s sites. Do not collect payload lists “for later.” If you work on a product, a code-review checklist and a linter or static rule that forbids string-built SQL will catch more than a late manual test.
When you write that checklist, keep production queries and customer data out of casual chat. SiberAI can help you phrase a short standard for the team. The security notes are why snippets should be fictional, and the quickstart is enough if you only need a writing workspace.
Key takeaways
- Untrusted data is not source code; keep it in parameters and text nodes.
- The SQL fix is a parameterized query or a safe query builder, plus allow-lists for identifiers.
- The XSS fix is context-aware encoding or a safe template, with CSP as defence in depth.
- Reviews should reject string-built SQL and “just this once” disabled escaping.
- Practise on applications you own or on official labs, never on a foreign site.
Last updated: November 2026.
FAQ
Q: Is an ORM automatically safe?
A: It is safe when you use its parameterised API. It is not safe if you pass a concatenated fragment into a raw-SQL helper. Read that helper’s documentation.
Q: Can I “just escape quotes” in SQL?
A: No. That is the old, brittle approach. Use the driver’s parameters.
Q: What about stored procedures?
A: They help only if the procedure itself uses parameters and does not concatenate inside the procedure body. The same rule applies one layer down.
Q: Does a web application firewall replace these fixes?
A: No. A WAF can be a useful net. Encoding and parameters are the fix in the product.
Q: How do I handle search boxes that need fuzzy matching?
A: Still use parameters. Build any wildcard characters in application code according to your database’s rules, then pass the completed pattern as a value, not as SQL text.
Q: Are these the only injection classes?
A: No. Command injection, LDAP, and template injection follow the same idea: do not paste untrusted strings into an interpreter. The two classes here are the ones most teams meet first.
Q: What should a reviewer ask on a pull request?
A: “Where does this value come from, and which API keeps it from becoming syntax?” If the answer is a format string, the review is not done.
Yorumlar
Yorum Gönder