Preventing Injection in Applications
A practical lesson on separating untrusted data from commands and output, combining prevention with impact reduction and systematic checks.
Keep Data Separate from Instructions
Keep Data Separate from Instructions
occurs when untrusted data is interpreted as part of a command or structured language instead of being handled strictly as data. SQL , operating-system command , and cross-site scripting (XSS) are examples. The central defense is to keep data separate from instructions, using controls suited to the interpreter and output context. Validation, error handling, or a security filter may contribute to defense, but none replaces safe construction and use of commands and output.
Bind database values; allowlist query structure
For database operations, use prepared statements or parameterized queries so supplied values are bound separately from SQL syntax. For example:
SELECT email FROM users WHERE id = ?
The ? is a value placeholder. Binding the supplied ID as a value keeps it from changing the query’s structure. By contrast, concatenating user input into SQL makes it part of the text being interpreted; manual escaping is not a substitute for parameterization.
Parameters generally represent values, not structural choices such as table names, column names, or sort directions. If a user can choose a sort key, map that choice to a small allowlist of fixed options. For example, accept only name, date, or status, and use the corresponding fixed query structure. This controls which structures can be selected rather than attempting to bind an identifier as if it were a value.
Parameterization prevents syntax , but it does not decide whether the requester is allowed to access a record. The application must check authorization independently.
Encode displayed data for its exact context
When untrusted data is displayed, encode it for the context in which it will be interpreted. HTML text, HTML attributes, JavaScript, CSS, and URLs have different parsing rules, so a generic “escape” operation is not sufficient. Prefer framework templates with automatic encoding, and render ordinary text through an encoded text output or text node rather than treating it as HTML. Avoid placing untrusted data in executable or otherwise dangerous contexts.
Encoding is applied when data is output. Pre-encoding everything when it is stored can cause double-encoding and still fail to cover the different contexts in which the data may later be used.
Encoding and sanitizing serve different needs. For ordinary text, encode it for the output context. If users are intentionally allowed to submit HTML, use a maintained HTML sanitizer configured for that purpose. In either case, the aim is to prevent untrusted content from being interpreted as instructions in its destination context.
Use Safer Interfaces and Validate Inputs
Use Safer Interfaces and Validate Inputs
A useful way to reduce risk is to avoid asking an interpreter to parse a command string when a can perform the operation directly. For example, use a filesystem library to create a directory instead of constructing a shell command. For database work, use a parameter-binding interface instead of assembling SQL text.
Sometimes a process does need to be launched. In that case, use a process API to pass a trusted executable and each argument separately, validate arguments according to that program’s requirements, and avoid a shell interpreter where possible. Separating arguments reduces command- risk, but it does not prevent argument or make an unsafe argument authorized. The program may still interpret an argument in an unintended way, or the requested action may still be disallowed.
Validate for the field’s intended use
Validate inputs against their expected type, format, range, and length as early as practical. Prefer allowlists where the set of acceptable choices is limited. For example, a sort key might be accepted only if it is name, date, or status. Reject malformed requests rather than trying to repair them ambiguously.
Validation is an additional layer: it complements parameterization and output encoding, but does not replace either. Validation rules should reflect the field’s purpose. Legitimate values may contain punctuation or non-ASCII characters, so rejecting those characters indiscriminately can exclude valid input without addressing the underlying need to keep data separate from instructions.
Limit Impact and Handle Errors Safely
Limit Impact and Handle Errors Safely
Even with preventive controls, consider what an application component could do if an flaw were exploited. limits the permissions of each component to what its task requires. For example, if an application only retrieves records, its database account should have read-only access rather than administrator privileges. Separate accounts or identities for distinct services and tasks where practical, and apply the same principle to operating-system processes and other resources.
limits the damage a successful could cause; it does not prevent the flaw itself. It is a consequence-limiting control, not a substitute for parameterized queries, safe APIs, or .
Keep user errors general and diagnostics protected
Give users clear, appropriately general error messages. Do not expose stack traces, SQL statements, file paths, framework details, or configuration data. Detailed database or parser errors can reveal implementation details and help an attacker identify possible points.
At the same time, retain useful diagnostic details in protected server-side logs so failures can be investigated. Control access to those logs and take care not to record secrets. Monitoring repeated errors and unusual failures can also help identify behavior that merits investigation. The balance is to avoid disclosing internal details to users without losing the protected information needed to understand and respond to problems.
Review and Test Defenses
Review and Test Defenses
Review the paths where untrusted data travels: does it reach a database query, another interpreter, or an output sink? At each destination, check that the control fits the context:
Confirm database values are bound as parameters and user-selectable SQL structure is mapped to allowlisted choices.
Check that untrusted output is encoded for its exact context, and that intentionally permitted HTML is handled with an appropriate sanitizer.
Verify that structured APIs are used where possible and that process arguments are passed separately and validated when a process must be launched.
Check that authorization is enforced independently of defenses.
Test both normal and malformed inputs. A malformed-input test can help reveal whether data is being interpreted as syntax, while normal-input tests help confirm that expected use remains supported. Also verify that reflects the field’s intended rules rather than indiscriminately excluding legitimate punctuation or non-ASCII characters.
Unexpected database or parser errors, unusual changes in query behavior, repeated malformed inputs, and unexpected child processes or command failures are potential indicators to investigate. They are not proof of an attack, and some attacks may produce no visible error. Treat them as prompts to inspect the relevant data-to-interpreter and data-to-output paths, not as conclusive evidence.
The overall review should confirm that the controls work together: safe construction and handling of commands and output prevent ; validation reinforces expected input rules; limits potential impact; and protected diagnostics support investigation without exposing internal details to users.
: A way of supplying data separately from the syntax of a database query.
: Giving users appropriately general errors while retaining protected diagnostic information for investigation.
: An observed failure or behavior that may warrant investigation for possible activity.