description: Input validation and injection defense (SQL/LDAP/OS), parameterization, prototype pollution
languages:
- c
- go
- html
- java
- javascript
- php
- powershell
- python
- ruby
- shell
- sql
- typescript
alwaysApply: false
rule_id: codeguard-0-input-validation-injection
Input Validation & Injection Defense
Ensure untrusted input is validated and never interpreted as code. Prevent injection across SQL, LDAP, OS commands, templating, and JavaScript runtime object graphs.
Core Strategy
- Validate early at trust boundaries with positive (allow‑list) validation and canonicalization.
- Treat all untrusted input as data, never as code. Use safe APIs that separate code from data.
- Parameterize queries/commands; escape only as last resort and context‑specific.
Validation Playbook
- Syntactic validation: enforce format, type, ranges, and lengths for each field.
- Semantic validation: enforce business rules (e.g., start ≤ end date, enum allow‑lists).
- Normalization: canonicalize encodings before validation; validate complete strings (regex anchors ^$); beware ReDoS.
- Free‑form text: define character class allow‑lists; normalize Unicode; set length bounds.
- Files: validate by content type (magic), size caps, and safe extensions; server‑generate filenames; scan; store outside web root.
SQL Injection Prevention
- Use prepared statements and parameterized queries for 100% of data access.
- Use bind variables for any dynamic SQL construction within stored procedures and never concatenate user input into SQL.
- Prefer least‑privilege DB users and views; never grant admin to app accounts.
- Escaping is fragile and discouraged; parameterization is the primary defense.
Example (Java PreparedStatement):
String custname = request.getParameter("customerName");
String query = "SELECT account_balance FROM user_data WHERE user_name = ? ";
PreparedStatement pstmt = connection.prepareStatement( query );
pstmt.setString( 1, custname);
ResultSet results = pstmt.executeQuery( );
LDAP Injection Prevention
- Always apply context‑appropriate escaping:
- DN escaping for
\ # + < > , ; " = and leading/trailing spaces
- Filter escaping for
* ( ) \ NUL
- Validate inputs with allow‑lists before constructing queries; use libraries that provide DN/filter encoders.
- Use least‑privilege LDAP connections with bind authentication; avoid anonymous binds for application queries.
OS Command Injection Defense
- Prefer built‑in APIs instead of shelling out (e.g., library calls over
exec).
- If unavoidable, use structured execution that separates command and arguments (e.g., ProcessBuilder). Do not invoke shells.
- Strictly allow‑list commands and validate arguments with allow‑list regex; exclude metacharacters (& | ; $ > < ` \ ! ' " ( ) and whitespace as needed).
- Use
-- to delimit arguments where supported to prevent option injection.
Example (Java ProcessBuilder):
ProcessBuilder pb = new ProcessBuilder("TrustedCmd", "Arg1", "Arg2");
Map<String,String> env = pb.environment();
pb.directory(new File("TrustedDir"));
Process p = pb.start();
Query Parameterization Guidance
- Use the platform’s parameterization features (JDBC PreparedStatement, .NET SqlCommand, Ruby ActiveRecord bind params, PHP PDO, SQLx bind, etc.).
- For stored procedures, ensure parameters are bound; never build dynamic SQL via string concatenation inside procedures.
Prototype Pollution (JavaScript)
- Developers should use
new Set() or new Map() instead of using object literals
- When objects are required, create with
Object.create(null) or { __proto__: null } to avoid inherited prototypes.
- Freeze or seal objects that should be immutable; consider Node
--disable-proto=delete as defense‑in‑depth.
- Avoid unsafe deep merge utilities; validate keys against allow‑lists and block
__proto__, constructor, prototype.
Caching and Transport
- Apply
Cache-Control: no-store on responses containing sensitive data; enforce HTTPS across data flows.
Implementation Checklist
- Central validators: types, ranges, lengths, enums; canonicalization before checks.
- 100% parameterization coverage for SQL; dynamic identifiers via allow‑lists only.
- LDAP DN/filter escaping in use; inputs validated prior to query.
- No shell invocation for untrusted input; if unavoidable, structured exec + allow‑list + regex validation.
- JS object graph hardened: safe constructors, blocked prototype paths, safe merge utilities.
- File uploads validated by content, size, and extension; stored outside web root and scanned.
Test Plan
- Static checks for string concatenation in queries/commands and dangerous DOM/merge sinks.
- Fuzzing for SQL/LDAP/OS injection vectors; unit tests for validator edge cases.
- Negative tests exercising blocked prototype keys and deep merge behavior.
1---2name: 381-control-set-03-input-validation-8f6d69d13description: <!-- Threat Modeling Skill | Version 3.0.3 (20260209a) | https://github.com/fr33d3m0n/threat-modeling | License: BSD-3-Clause -->4---5<!-- Threat Modeling Skill | Version 3.0.3 (20260209a) | https://github.com/fr33d3m0n/threat-modeling | License: BSD-3-Clause -->67---8description: Input validation and injection defense (SQL/LDAP/OS), parameterization, prototype pollution9languages:10- c11- go12- html13- java14- javascript15- php16- powershell17- python18- ruby19- shell20- sql21- typescript22alwaysApply: false23---2425rule_id: codeguard-0-input-validation-injection2627## Input Validation & Injection Defense2829Ensure untrusted input is validated and never interpreted as code. Prevent injection across SQL, LDAP, OS commands, templating, and JavaScript runtime object graphs.3031### Core Strategy32- Validate early at trust boundaries with positive (allow‑list) validation and canonicalization.33- Treat all untrusted input as data, never as code. Use safe APIs that separate code from data.34- Parameterize queries/commands; escape only as last resort and context‑specific.3536### Validation Playbook37- Syntactic validation: enforce format, type, ranges, and lengths for each field.38- Semantic validation: enforce business rules (e.g., start ≤ end date, enum allow‑lists).39- Normalization: canonicalize encodings before validation; validate complete strings (regex anchors ^$); beware ReDoS.40- Free‑form text: define character class allow‑lists; normalize Unicode; set length bounds.41- Files: validate by content type (magic), size caps, and safe extensions; server‑generate filenames; scan; store outside web root.4243### SQL Injection Prevention44- Use prepared statements and parameterized queries for 100% of data access.45- Use bind variables for any dynamic SQL construction within stored procedures and never concatenate user input into SQL.46- Prefer least‑privilege DB users and views; never grant admin to app accounts.47- Escaping is fragile and discouraged; parameterization is the primary defense.4849Example (Java PreparedStatement):50```java51String custname = request.getParameter("customerName");52String query = "SELECT account_balance FROM user_data WHERE user_name = ? "; 53PreparedStatement pstmt = connection.prepareStatement( query );54pstmt.setString( 1, custname);55ResultSet results = pstmt.executeQuery( );56```5758### LDAP Injection Prevention59- Always apply context‑appropriate escaping:60 - DN escaping for `\ # + < > , ; " =` and leading/trailing spaces61 - Filter escaping for `* ( ) \ NUL`62- Validate inputs with allow‑lists before constructing queries; use libraries that provide DN/filter encoders.63- Use least‑privilege LDAP connections with bind authentication; avoid anonymous binds for application queries.6465### OS Command Injection Defense66- Prefer built‑in APIs instead of shelling out (e.g., library calls over `exec`).67- If unavoidable, use structured execution that separates command and arguments (e.g., ProcessBuilder). Do not invoke shells.68- Strictly allow‑list commands and validate arguments with allow‑list regex; exclude metacharacters (& | ; $ > < ` \ ! ' " ( ) and whitespace as needed).69- Use `--` to delimit arguments where supported to prevent option injection.7071Example (Java ProcessBuilder):72```java73ProcessBuilder pb = new ProcessBuilder("TrustedCmd", "Arg1", "Arg2");74Map<String,String> env = pb.environment();75pb.directory(new File("TrustedDir"));76Process p = pb.start();77```7879### Query Parameterization Guidance80- Use the platform’s parameterization features (JDBC PreparedStatement, .NET SqlCommand, Ruby ActiveRecord bind params, PHP PDO, SQLx bind, etc.).81- For stored procedures, ensure parameters are bound; never build dynamic SQL via string concatenation inside procedures.8283### Prototype Pollution (JavaScript)84- Developers should use `new Set()` or `new Map()` instead of using object literals85- When objects are required, create with `Object.create(null)` or `{ __proto__: null }` to avoid inherited prototypes.86- Freeze or seal objects that should be immutable; consider Node `--disable-proto=delete` as defense‑in‑depth.87- Avoid unsafe deep merge utilities; validate keys against allow‑lists and block `__proto__`, `constructor`, `prototype`.8889### Caching and Transport90- Apply `Cache-Control: no-store` on responses containing sensitive data; enforce HTTPS across data flows.9192### Implementation Checklist93- Central validators: types, ranges, lengths, enums; canonicalization before checks.94- 100% parameterization coverage for SQL; dynamic identifiers via allow‑lists only.95- LDAP DN/filter escaping in use; inputs validated prior to query.96- No shell invocation for untrusted input; if unavoidable, structured exec + allow‑list + regex validation.97- JS object graph hardened: safe constructors, blocked prototype paths, safe merge utilities.98- File uploads validated by content, size, and extension; stored outside web root and scanned.99100### Test Plan101- Static checks for string concatenation in queries/commands and dangerous DOM/merge sinks.102- Fuzzing for SQL/LDAP/OS injection vectors; unit tests for validator edge cases.103- Negative tests exercising blocked prototype keys and deep merge behavior.