9.3.1. Secure Coding Principles and OWASP Top 10
💡 First Principle: Secure coding principles are defensive defaults: assume every input is hostile, every error path matters, and every access must be verified. Applied consistently, they eliminate whole vulnerability classes structurally instead of leaving them to be discovered and patched one at a time. Using parameterized queries everywhere prevents SQL injection across thousands of code paths at once; hunting for injection bugs one by one never finishes.
OWASP Top 10:2025, the current edition:
| Rank | Category | Root Cause | Prevention |
|---|---|---|---|
| A01 | Broken Access Control (now includes SSRF) | Missing or inconsistent authorization checks; server fetches attacker-chosen URLs | Deny by default; enforce on the server for every request and object; allowlist outbound destinations |
| A02 | Security Misconfiguration | Default credentials; unnecessary features; verbose errors; permissive cloud settings | Hardened baselines; configuration as code; automated configuration scanning |
| A03 | Software Supply Chain Failures | Vulnerable, outdated or compromised dependencies, build systems and distribution | SCA; SBOM; pinned, verified dependencies; secured pipeline (9.4.2, 9.5.1) |
| A04 | Cryptographic Failures | Weak algorithms, poor key management, sensitive data unprotected | Current algorithms (AES, SHA-256 or stronger); proper key management; encrypt at rest and in transit |
| A05 | Injection (including XSS) | Untrusted input interpreted as code or commands | Parameterized queries; context-specific output encoding; allowlist validation |
| A06 | Insecure Design | Missing threat model; no security architecture | Threat modeling in design; secure design patterns; abuse cases |
| A07 | Authentication Failures | Weak passwords; missing MFA; session mismanagement | MFA; credential-stuffing protection; secure session handling |
| A08 | Software or Data Integrity Failures | Untrusted deserialization; unsigned updates; unverified code sources | Verify signatures and integrity; never deserialize untrusted data without checks |
| A09 | Security Logging and Alerting Failures | Events not logged, or logged with no alert anyone acts on | Log security-relevant events; protect log integrity; alert into the SIEM and respond |
| A10 | Mishandling of Exceptional Conditions | Improper error handling; failing open; logic errors under abnormal conditions | Fail secure; handle errors where they occur; generic error messages; roll back incomplete transactions |
What changed from the 2021 edition: SSRF (A10:2021) was folded into Broken Access Control; Vulnerable and Outdated Components (A06:2021) was broadened into Software Supply Chain Failures; Mishandling of Exceptional Conditions is new; Security Misconfiguration rose from fifth to second, and Injection fell from third to fifth. Older material may still quote 2021 ranks; what matters is the vulnerability class and its control, not the number.
Core secure coding principles:
- Input validation: validate all input on the server. Allowlist validation (define what IS allowed) is stronger than denylist validation (define what is NOT allowed), because a denylist cannot anticipate every malicious input. Validate type, length, range and format.
- Path traversal: input such as
../../etc/passwdwalks out of the intended directory when a filename is concatenated into a path. Canonicalize the path and confirm it stays inside the permitted base directory, or map user choices to server-side identifiers. - Output encoding: encode output for the context where it is rendered (HTML, URL, JavaScript), so user-supplied data is treated as data, not executable code.
- Parameterized queries: the definitive defense against SQL injection. Prepared statements separate SQL code from data, so the database treats user input as a literal value, never as SQL.
- Fail secure: when an error occurs, deny access rather than grant it. An access check that throws an exception must end in "deny", never fall through to the code that grants access (A10:2025).
- Secure defaults: ship in the most secure configuration. Debug mode, verbose errors and default admin accounts stay off unless explicitly enabled.
- Least privilege in code: a web process does not run as root or administrator, and its database account has only the permissions it needs (SELECT for read operations, not DBA rights).
- Defense in depth: layer controls so one failure is not fatal: input validation plus parameterized queries plus a least-privilege database account; authentication plus authorization plus audit logging.
Attacks that abuse the browser's trust:
| Attack | What it abuses | How it works | Prevention |
|---|---|---|---|
| Cross-site scripting (XSS) | The user's trust in the site | Attacker script runs in other users' browsers. Reflected: payload in the request is echoed back. Stored: payload saved and served to every viewer. DOM-based: client-side script writes the payload into the page without the server's involvement | Context-specific output encoding; Content Security Policy as a second layer; HttpOnly session cookies limit what script can steal (6.3.2) |
| Cross-site request forgery (CSRF) | The site's trust in the user's browser | A malicious page makes the victim's browser send a request to a site where they are logged in; the browser attaches the session cookie automatically | Anti-CSRF tokens; SameSite cookies; Origin or Referer checks; re-authentication for sensitive actions |
An XSS flaw also defeats CSRF tokens, because injected script running in the site's own origin can read the token. Fix XSS first.
Memory safety vulnerabilities:
| Vulnerability | Mechanism | Prevention |
|---|---|---|
| Buffer overflow | Input exceeds allocated memory and overwrites adjacent data, including the return address on the stack, redirecting execution to attacker code | Memory-safe languages (Rust, Go, Java); bounds checking; ASLR; DEP/NX; stack canaries |
| Integer overflow | Arithmetic exceeds the data type's capacity and wraps to an unexpected value, often a too-small buffer size | Safe integer libraries; range validation before arithmetic |
| Format string | User input used directly as the format argument of functions such as printf | Fixed format strings, with user data passed as arguments |
The buffer overflow mitigations differ in kind. A stack canary is a random value placed before the return address and checked before the function returns, so an overwrite is detected; DEP/NX marks the stack non-executable; ASLR randomizes where code and data sit in memory. These raise the cost of exploitation (return-oriented programming works around DEP); only bounds checking or a memory-safe language removes the flaw.
Race conditions (time of check to time of use, TOCTOU): the state of a resource changes between the moment it is checked and the moment it is used. Examples: an attacker swaps a checked file path for a symbolic link to a system file before a privileged program opens it; two simultaneous withdrawals each pass the balance check before either is recorded. Prevention: make check and use one atomic operation, act on the opened handle rather than the path, lock shared resources, and use database transactions with an appropriate isolation level.
⚠️ Exam Trap: SQL injection is prevented by parameterized queries, not by input filtering alone. Filtering (stripping single quotes, escaping special characters) can be bypassed with encoding, alternative syntax or second-order injection. The exam tests whether you know the structural defense (parameterized queries) versus the brittle one (filtering).
Reflection Question: A code review reveals that a web application constructs SQL queries by concatenating user input directly into the query string. The developer argues this is safe because the application strips single quotes from all input before concatenation. Explain why this defense is insufficient, provide a specific bypass technique, and describe the correct architectural fix that eliminates SQL injection structurally.