Secure coding: keep untrusted input from becoming code
Injection flaws occur when an interpreter treats untrusted input as commands or syntax. Learn to separate code from data with safe APIs, choose handling for SQL, browser, and shell contexts, and verify the result without sending attack payloads to a live system.
Secure coding: keep untrusted input from becoming code
Injection flaws arise when untrusted input reaches an interpreter such as SQL, a browser, or a shell and is processed as a command or syntax instead of data. The core practice is not to remove all input or replace special characters everywhere. Use APIs that separate code from data for each interpreter, then apply handling appropriate to the output destination.
This article does not repeat full explanations of SQL injection or XSS. It compares a shared decision process for developers who build or review web applications. It does not describe sending attack strings to a real system as a penetration test.
Why the boundary between data and commands matters
Programs receive values from sources they cannot fully trust, such as requests, files, databases, email, and other services. If a value is concatenated directly into an interpreter’s statement, part of it may be read as syntax rather than data. OWASP classifies SQL, ORM query languages, NoSQL, browser script rendering, LDAP, XPath, and operating-system commands as distinct injection contexts. CWE-74 describes the underlying weakness: input influenced by an upstream component is interpreted by a downstream component in a way that can change its syntax.
“Treat input as dangerous” is not a complete design rule. Trace both where a value came from and where it will be used. The same search term needs different defenses as a database value and as displayed HTML.
Choose defenses for the destination
| Destination | Preferred choice | Role of validation | Shortcut to avoid |
|---|---|---|---|
| SQL value | Parameterized query with bound values | Check length, format, and business rules | String concatenation or manual quote escaping |
| Dynamic table, column, or sort order | Fixed identifier or allowlisted application choice | Limit available choices | Assuming identifiers bind like ordinary values |
| HTML text | Framework output encoding or a text API such as textContent | Check business-approved input format | HTML-escaping every input in advance |
| User-authored HTML | Maintained HTML sanitizer configured for the product | Define allowed tags, attributes, and protocols | Removing a few tags with a regular expression |
| Shell or OS command | Library API instead of an external command, when possible | Validate arguments and filenames | Concatenating user text into a shell command |
| Command-line arguments | Structured API passing the program and each argument separately | Validate option and argument boundaries | Assuming validation is unnecessary because no shell is used |
Escaping and encoding must account for each interpreter’s syntax. SQL escaping does not make HTML safe, and HTML encoding does not do the same job for JavaScript or shell arguments. OWASP prefers parameterized or otherwise safe APIs; only when one is unavailable should code use that interpreter’s precise escaping syntax. Manual escaping is a poor default because a rule can be applied incorrectly or omit a context.
Safe patterns in common contexts
SQL: separate query structure from values
Do not insert a user’s search term directly into SQL text. Pass it as a bound parameter through the database driver so quotes or operators remain part of the value and cannot change query meaning. Dynamic table names or sort directions change SQL structure and usually cannot be bound as values; choose them from fixed application-owned options instead of user text.
An ORM or stored procedure is not automatically safe. Injection risk returns if a query string is assembled inside it. Parameterization also does not decide whether the caller may read or change matching rows; check authorization separately.
Browser: handle data for its rendering context
When displaying a user value as HTML text, prefer the framework’s default output encoding or a text-node API such as textContent. Browsers parse HTML, attributes, URLs, JavaScript, and CSS differently, so handling depends on the destination. For a URL attribute, check allowed protocols and URL policy as well as the attribute context. If the product accepts user-authored HTML, use a maintained sanitizer configured for the required features.
Do not escape a value once at input time and reuse that transformed value everywhere. The same value may later appear in HTML text, an attribute, a URL, or a log. Handle it at each use site for that context to reduce both double encoding and missed contexts. Content Security Policy is an additional browser defense, not a fix for unsafe rendering code.
Operating-system commands: reduce shell use
For tasks such as listing files or compressing data, use a library instead of an external command when possible. If a command is necessary, pass the program and arguments through a structured argument array so the shell does not re-parse a single command string. OWASP recommends structured passing together with input validation. Structured arguments do not automatically prevent option injection, so validate filenames, paths, and allowed options for the task. If supported, -- can mark the end of option parsing.
Execution APIs differ by platform in how they split arguments and invoke shells. Check your language and runtime’s official documentation, avoid interpolating values into one command string, and review logs because command output or errors may contain sensitive values.
Example: store and display a search term
Suppose a user submits a search term, the application stores it in a database, and a results page later displays it. When storing it, separate SQL structure from the search value with parameter binding. When displaying it, use the template’s default output encoding or a text API.
These are two different interpreter boundaries. SQL parameterization does not make HTML safe, and HTML output encoding does not protect the database query. A stored value still came from an untrusted source, so handle it for the destination when rendering it. This is an illustrative example, not a result verified against a particular product.
Review and verify a safe implementation
**Map sources and destinations.** Trace where the value came from—request, file, stored data, or external service—and each interpreter or output location it reaches.
**Choose the destination’s safe API.** Prefer APIs that separate code and data: query parameters, auto-encoding templates, text DOM APIs, sanitizers for authored markup, or libraries that avoid the shell.
**Separate structure from values.** Choose structural inputs such as dynamic table names, URL schemes, or command options from fixed choices or allowlists. Use validation as a supporting check for format and business rules.
**Check handling at the final use site.** Find whether a value reaches several destinations and ensure each uses encoding, validation, or sanitization appropriate to that destination. Do not assume handling it when stored is enough.
**Reduce privileges and execution impact.** Limit database accounts, OS processes, and file permissions to required operations. Safe boundaries are essential; least privilege can reduce the impact of a remaining defect.
**Verify with harmless tests and code review.** Use benign markers such as quotes or angle brackets that should not alter structure. Confirm the value remains text or a bound query value, then review rendered output, query behavior, errors, and logs. Do not send attack payloads to a live service; use an authorized test environment.
Commonly confused defenses
**Input validation alone prevents injection:** format checks help reject invalid business values, but valid characters can still be syntax in the wrong context. Safe APIs and destination handling are central.
**Removing special characters once makes data safe everywhere:** parsers differ. Blanket replacement can break legitimate input and does not protect another destination’s syntax.
**An ORM, stored procedure, or framework is automatically safe:** assembling query strings or using unsafe output APIs can remove protection. Review actual calls and template paths.
**A WAF or CSP replaces code fixes:** these supporting controls may block some attempts, but do not make application code preserve safe boundaries.
References
OWASP Cheat Sheet Series, [Injection Prevention Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Injection_Prevention_Cheat_Sheet.html) — validation, safe APIs, contextual escaping, and injection types.
OWASP Cheat Sheet Series, [SQL Injection Prevention Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/SQL_Injection_Prevention_Cheat_Sheet.html) — parameterization, dynamic identifiers, ORM use, and least privilege.
OWASP Cheat Sheet Series, [Cross Site Scripting Prevention Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html) — destination-specific handling and safe DOM APIs.
OWASP Cheat Sheet Series, [OS Command Injection Defense Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/OS_Command_Injection_Defense_Cheat_Sheet.html) — avoiding shells, structured arguments, and validation.
MITRE, [CWE-74: Improper Neutralization of Special Elements in Output Used by a Downstream Component](https://cwe.mitre.org/data/definitions/74.html) — downstream interpretation and injection impact.