Why This Matters#

Web applications are the most common attack surface. They’re internet-facing, complex, and handle sensitive data. Most breaches involve exploiting web application vulnerabilities.


OWASP Top 10 (2021)#

The Open Web Application Security Project’s definitive list of critical web risks:

#CategoryRoot Cause
A01Broken Access ControlMissing or bypassed authorization checks
A02Cryptographic FailuresWeak crypto, plaintext data, missing encryption
A03InjectionUntrusted data interpreted as code/commands
A04Insecure DesignFlawed architecture, missing threat model
A05Security MisconfigurationDefault configs, unnecessary features enabled
A06Vulnerable ComponentsOutdated libraries with known CVEs
A07Identification & Auth FailuresWeak passwords, broken session management
A08Software & Data Integrity FailuresUnsigned updates, insecure deserialization
A09Logging & Monitoring FailuresAttacks go undetected
A10Server-Side Request ForgeryServer makes requests to unintended targets

Injection Attacks#

SQL Injection#

The server treats user input as SQL code:

Login form: username = admin' --
Query: SELECT * FROM users WHERE username='admin' --' AND password='anything'
Result: Password check bypassed (commented out)

Types:

TypeBehaviorDetection
Classic (in-band)Error messages reveal dataVisible in response
Union-basedUNION SELECT extracts other tablesData in response
Blind (boolean)True/false responses leak data bit by bitResponse differences
Blind (time-based)SLEEP() reveals data via timingResponse time
Out-of-bandData sent to attacker’s serverDNS/HTTP callbacks

Prevention:

MethodEffectiveness
Parameterized queries (prepared statements)Complete prevention
ORM with parameterized queriesComplete prevention
Input validation (allowlist)Defense in depth
WAF rulesDetection layer (bypassable)
Least privilege DB userLimits damage

Command Injection#

User input executed as OS command:

Input: filename = "; rm -rf /"
Command: convert "; rm -rf /" output.png

Prevention: Never pass user input to shell commands. Use language APIs instead of exec()/system().

LDAP, NoSQL, Template Injection#

Same principle — untrusted data reaches an interpreter:

TypeTargetExample Payload
LDAP InjectionDirectory services*)(uid=*))(|(uid=*
NoSQL InjectionMongoDB, etc.{"$gt": ""}
Template Injection (SSTI)Jinja2, Twig, etc.{{7*7}} → 49

Cross-Site Scripting (XSS)#

Attacker injects JavaScript that executes in victim’s browser:

Types#

TypeStorageTriggerExample
ReflectedNone (URL parameter)Victim clicks crafted linksearch?q=<script>steal()</script>
StoredDatabaseAny user views the pageComment containing <script>
DOM-basedNone (client-side)Client JS processes URL unsafelydocument.write(location.hash)

Impact#

  • Steal session cookies → account takeover
  • Redirect to phishing page
  • Keylog user input
  • Modify page content (defacement, fake forms)
  • Cryptocurrency mining

Prevention#

DefenseMechanism
Output encodingEncode <>&"' before rendering in HTML
Content Security Policy (CSP)Browser blocks inline scripts, restricts sources
HTTPOnly cookiesJavaScript cannot access session cookies
Input validationReject unexpected characters (defense in depth)
Trusted TypesBrowser API preventing DOM XSS

Content Security Policy (CSP)#

Content-Security-Policy: 
  default-src 'self';
  script-src 'self' https://cdn.example.com;
  style-src 'self' 'unsafe-inline';
  img-src *;
  connect-src 'self' https://api.example.com;

Cross-Site Request Forgery (CSRF)#

Tricks an authenticated user’s browser into making unintended requests:

sequenceDiagram
    participant V as Victim (logged into bank)
    participant E as Evil Site
    participant B as Bank
    
    V->>E: Visits evil.com
    E->>V: Page with hidden form
    Note over V: Browser auto-submits form
    V->>B: POST /transfer?to=attacker&amount=10000
    Note over B: Valid session cookie attached
    B->>B: Transfer executed

Prevention#

DefenseHow It Works
CSRF TokenUnique token per session/request, validated server-side
SameSite CookiesSameSite=Strict or Lax prevents cross-origin cookie sending
Origin/Referer checkVerify request comes from your domain
Custom headersRequire X-Requested-With (AJAX only, not forms)

Server-Side Request Forgery (SSRF)#

Attacker makes the server fetch resources from unintended locations:

flowchart LR
    Attacker["Attacker"] -->|"url=http://169.254.169.254/..."| Server["Your Server"]
    Server -->|"Fetches"| Meta["Cloud Metadata<br/>(credentials!)"]
    Meta -->|"Returns IAM creds"| Server
    Server -->|"Returns to"| Attacker

Common Targets#

TargetWhat’s Exposed
Cloud metadata (169.254.169.254)IAM credentials, instance info
Internal services (localhost, 10.x.x.x)Admin panels, databases
Internal APIsUnauthenticated internal endpoints
File system (file://)Local files

Prevention#

DefenseMechanism
Allowlist URLs/domainsOnly permit known-good destinations
Block internal IP rangesDeny RFC 1918, link-local, localhost
IMDSv2 (AWS)Requires token for metadata access
Network segmentationServer can’t reach sensitive internal services
Disable unnecessary URL schemesBlock file://, gopher://, dict://

Broken Access Control#

The #1 OWASP risk. Users accessing resources or actions they shouldn’t:

Common Patterns#

VulnerabilityExample
IDOR (Insecure Direct Object Reference)/api/users/123 → change to /api/users/456
Missing function-level access controlRegular user accesses /admin/delete-user
Privilege escalationChange role=user to role=admin in request
Path traversal../../etc/passwd
CORS misconfigurationAccess-Control-Allow-Origin: * with credentials

Prevention#

DefenseImplementation
Server-side authorizationCheck permissions on EVERY request
Deny by defaultRequire explicit grants, not explicit denials
Indirect referencesUse UUIDs or mapped IDs, not sequential
Rate limitingPrevent enumeration attacks
Automated testingTest access control in CI/CD

Security Headers#

HTTP headers that instruct browsers to enable security features:

HeaderPurposeExample Value
Content-Security-PolicyControl resource loadingdefault-src 'self'
Strict-Transport-SecurityForce HTTPSmax-age=31536000; includeSubDomains
X-Content-Type-OptionsPrevent MIME sniffingnosniff
X-Frame-OptionsPrevent clickjackingDENY
Referrer-PolicyControl referrer infostrict-origin-when-cross-origin
Permissions-PolicyDisable browser featurescamera=(), microphone=()

API Security#

APIs have unique attack vectors beyond traditional web apps:

RiskDescriptionMitigation
Broken Object Level AuthAccess other users’ objects via IDAuthorize per-object
Broken AuthenticationWeak token validationOAuth 2.0, short-lived tokens
Excessive Data ExposureAPI returns more than neededResponse filtering, field selection
Lack of Rate LimitingBrute force, DoSRate limiting per user/IP
Mass AssignmentClient sets fields they shouldn’tExplicit allowlists for writable fields
InjectionSame as web appsInput validation, parameterized queries

Key Takeaways#

  1. Input is untrusted — validate, sanitize, and encode ALL user input
  2. Parameterized queries eliminate SQL injection entirely — no exceptions
  3. CSP is essential — it’s the strongest defense against XSS
  4. Authorization on every request — never trust client-side checks alone
  5. SSRF is cloud-critical — block metadata access, use IMDSv2
  6. Security headers are free — enable them all, they cost nothing
  7. APIs need the same rigor as web UIs — often they get less scrutiny