14 min read Web & Application Security Attacks & Network Defense (10 / 13)
Part 3 — Attacks & Network Defense

Lesson 13.10 — Web Application Security (OWASP Top 10)

Dissecting Web App & API Flaws: Broken Access Control, SQL Injection, XSS, CSRF, and Modern Defensive Architectures

What You Will Master

By the end of this lesson, you will grasp the client-server request lifecycle, database trust boundaries, and the defensive engineering required to eliminate pervasive OWASP Top 10 vulnerabilities:

  • Web architecture & request-response trust boundaries
  • Broken Access Control (IDOR, horizontal & vertical privilege escalation)
  • SQL Injection (SQLi) mechanics & Parameterized Query / Prepared Statements
  • Cross-Site Scripting (XSS): Stored, Reflected, DOM-based XSS & Output Encoding
  • Cross-Site Request Forgery (CSRF): Ambient credentials & Anti-CSRF tokens
  • Cookie Security Attributes: HttpOnly, Secure, & SameSite (Lax/Strict)
  • Additional OWASP risks: Security Misconfigurations, Insecure Uploads, SSRF
  • Secure development rules & Content Security Policy (CSP) headers
  • 3-Tab Interactive Web Security Defense Workbench (Zero-Quiz Lab)

1 Introduction: How Websites Are Compromised

In the modern digital economy, Web Applications and APIs are the central nervous system powering online banking, e-commerce, healthcare portals, SaaS platforms, and enterprise administration.

Imagine you operate an e-commerce platform. Customers register accounts, add products to carts, checkout via payment gateways, and review order invoices. Visually, the web application functions flawlessly. But behind the scenes, consider what happens if any of the following scenarios occur:

1. Unauthorized Data Peeking (IDOR)

A customer views their invoice at /order/101, alters the URL to /order/102, and instantly gains full access to another stranger's shipping address and purchased items.

2. Database Hijacking (SQLi)

Instead of searching for a product name, an attacker types a malicious quote sequence (' OR 1=1 --) into the search bar, dumping the entire database credentials table.

3. Browser Code Injection (XSS)

A malicious actor leaves an innocent-looking product review embedded with a hidden script tag, silently harvesting session cookies from every user who views that review page.

Defining Web Application Security

Web Application Security is the holistic engineering practice of protecting web servers, backend application business logic, REST/GraphQL APIs, databases, and client-side browser runtime environments from unauthorized access, logic manipulation, code injection, and sensitive data exposure. Network firewalls alone cannot protect a web application; defensive rigor must be implemented within application source code, API controllers, and database access layers.

2 How Web Applications Work: Architecture & Trust Boundaries

Understanding how vulnerabilities arise requires examining the lifecycle of client-server requests and identifying where trust boundaries must be strictly enforced:

Web Application Request-Response & Validation Pipeline
1. Client / Browser (Frontend)

HTML, CSS, and JavaScript. Renders UI components and initiates HTTP requests via Fetch or Axios.

⚠️ Untrusted Zone: Client-side code runs entirely on user devices. Client validation can be bypassed effortlessly!
2. Backend / API Gateway

Node.js, Python, Go, Java, etc. Executes business logic, enforces authentication, and validates authorization.

🛡️ The Fortress: Every input must be validated, sanitized, and authorization verified strictly server-side.
3. Database & Storage

PostgreSQL, MySQL, MongoDB, Redis, etc. Persists records and executes data retrieval queries.

🔒 Query Isolation: Only parameterized queries permitted. Dynamic raw string concatenation is forbidden.

3 Broken Access Control (OWASP Top 1 Vulnerability)

Broken Access Control ranks #1 on the OWASP Top 10. It occurs when an application fails to properly enforce restrictions on what authenticated users are allowed to do, permitting them to view, edit, or delete data belonging to other users or elevate their administrative privileges.

Real-World Example: Insecure Direct Object Reference (IDOR)

Suppose a logged-in user requests their billing receipt via https://shop.com/api/invoice?id=5001. If the user alters the query parameter to ?id=5002, and the server validates only that the user is logged in—without confirming whether invoice 5002 belongs to the requester—sensitive customer records are leaked.

Horizontal Privilege Escalation:

A standard user (User A) accesses or modifies private records (e.g., bank statements, profile drafts) belonging to another peer user (User B) having identical privilege levels.

Vertical Privilege Escalation:

A standard customer or junior employee crafts requests to invoke privileged administrator endpoints (e.g., /admin/users/delete) due to missing role checks on API routes.

Core Principles to Prevent Broken Access Control:

  • Server-Side Record Ownership Validation: Always include user ownership checks in queries: WHERE id = :orderId AND user_id = :currentUserId.
  • Default Deny Principle: Unless explicitly permitted, deny access to every API endpoint, administrative function, and data object by default (HTTP 403 Forbidden).
  • Zero Reliance on Frontend Obfuscation: Hiding a button or menu in HTML/CSS provides zero protection; the backend API must authoritatively enforce role-based access.
  • Eliminate Predictable Sequential IDs: Replace auto-incrementing integer IDs (1, 2, 3) with cryptographically random UUID v4 strings to eliminate enumeration.

4 SQL Injection (SQLi): Database Hijacking

SQL Injection (SQLi) occurs when untrusted user input is directly concatenated into a dynamic SQL query string without sanitization or parameterization. This allows an attacker to break out of data context, manipulate SQL query grammar, and execute arbitrary database instructions.

Vulnerable Concatenation vs. Secure Parameterized Query
❌ Highly Vulnerable (Raw String Concatenation):
// Attacker input: ' OR '1'='1
const query = "SELECT * FROM users WHERE user = '" + userInput + "' AND pass = '" + passInput + "'";
// Executed SQL:
// SELECT * FROM users WHERE user = '' OR '1'='1' ...
// Result: Admin logged in without password!
✅ Secure Architecture (Prepared Statements):
// Query grammar compiled ahead of time
const query = "SELECT * FROM users WHERE user = ? AND pass = ?";
db.execute(query, [userInput, passInput]);
// Result: User input treated strictly as 
// literal data values, NEVER as executable code!

Severe Impacts of SQL Injection:

Authentication Bypass:

Logging into administrator or executive accounts without knowledge of passwords.

Mass Data Exfiltration:

Using UNION-based SQLi to extract password hashes, credit card records, and PII tables.

Database Sabotage:

Executing DROP TABLE, writing backdoors, or obtaining remote OS shell execution.

5 Cross-Site Scripting (XSS): Client-Side Execution

Cross-Site Scripting (XSS) occurs when an application includes untrusted user input directly into rendered web pages without proper contextual encoding or sanitization. The victim's browser interprets the injected markup as legitimate script, executing it within the victim's session context.

Three Primary Flavors of XSS:

1. Stored XSS (Persistent)

The most dangerous. Malicious script is permanently stored in the backend database (e.g., comments, profiles). Every subsequent visitor viewing that page executes the script automatically.

2. Reflected XSS (Non-Persistent)

Script is carried within request parameters (e.g., ?search=<script>...). When a victim clicks a phishing link, the server immediately reflects the payload back in the rendered response.

3. DOM-based XSS

Occurs entirely within client-side JavaScript without altering server responses. Client code unsafely writes data from URL sinks to DOM execution sinks using innerHTML or eval().

Modern Engineering Countermeasures for XSS:

1. Context-Aware Output Encoding:

Encode HTML entities prior to rendering: convert < to &lt;, > to &gt;, preventing the parser from treating input as markup.

2. Safe DOM Manipulation APIs:

Never use unsafe element.innerHTML. Always use safe properties like element.textContent or frameworks that auto-escape (e.g., React JSX).

3. Content Security Policy (CSP):

Enforce HTTP response headers like Content-Security-Policy: default-src 'self', blocking untrusted external scripts and inline script execution.

4. HttpOnly Cookie Flags:

Mark session cookies with HttpOnly. Even if XSS triggers in the browser, JavaScript cannot access or exfiltrate the session cookie.

6 Cross-Site Request Forgery (CSRF): Ambient Credential Exploitation

Cross-Site Request Forgery (CSRF) is an attack that tricks a victim's authenticated browser into issuing unauthorized state-changing requests (such as transferring funds or changing email credentials) to a trusted target web application.

Why CSRF Occurs (The Ambient Credential Problem): Web browsers automatically attach stored Session Cookies to any outgoing HTTP request directed at that domain, regardless of which origin website initiated the request. The target server sees valid session cookies and assumes the legitimate user intended the action!

Two Core Pillars of CSRF Defense:

1. Anti-CSRF Synchronizer Tokens:

Require a unique, cryptographically random, unpredictable token (X-CSRF-Token) with every state-changing request (POST/PUT/DELETE). Cross-origin malicious sites cannot read or forge this token.

2. SameSite Cookie Attributes:

Configure session cookies with SameSite=Lax or SameSite=Strict. Browsers will refuse to attach the cookie to cross-site requests, effectively neutralizing CSRF.

7 Additional Critical Web Vulnerabilities (OWASP Top 10)

Beyond access control, SQLi, and XSS, enterprise web systems regularly confront several other severe application-level threats:

1. Insecure File Upload

Allowing users to upload files without rigorous validation can lead to malicious web shells (shell.php) being uploaded and executed directly via browser URL. Mitigations: rename files, whitelist extensions, verify magic bytes, and store outside the web root on object storage.

2. Server-Side Request Forgery (SSRF)

Tricking the backend web server into making HTTP requests to internal networks or cloud metadata instances (http://169.254.169.254/latest/meta-data/). Attackers can steal IAM temporary credentials and compromise cloud infrastructure.

3. Security Misconfiguration

Leaving debug mode enabled in production, revealing detailed stack traces, leaving cloud buckets publicly readable, or retaining factory-default administrator credentials.

4. Vulnerable & Outdated Components

Building web software on third-party NPM, Python, or Java libraries containing known Common Vulnerabilities and Exposures (CVEs). Modern teams must run continuous dependency auditing (npm audit, Snyk).

Hands-on Lab

Web Application Security Defense Workbench

SQL Injection vs Prepared Statements, XSS Output Encoding, and CSRF Token Validation

Zero-Quiz Practical Lab

SQL Injection vs. Parameterized Query Simulator

Inject test payloads into the username field and observe backend evaluation under raw concatenation vs prepared statements.

Defense Mode:
Test Payloads:
DATABASE EXECUTION TRACE: ⚠️ AUTHENTICATION BYPASSED!
Generated Query:

SELECT * FROM users WHERE user = 'admin' OR '1'='1' AND pass = 'randompass123'

Database Verdict:

Because condition ('1'='1') is tautologically TRUE, the database returned the first record (Administrator) despite an invalid password. Attack Succeeded!

9 Lesson Summary

Key takeaways and architectural defense patterns covered in this lesson:

1. Broken Access Control Defense

Authentication is not authorization. Every backend API endpoint must authoritatively enforce record ownership (WHERE id = :id AND user_id = :uid).

2. Parameterized SQL Queries

Never concatenate raw user strings into SQL queries. Always use Prepared Statements to ensure the database treats input strictly as literal values.

3. XSS & Output Sanitization

Perform contextual output encoding, use safe DOM APIs (textContent), enforce CSP headers, and mark cookies as HttpOnly.

4. CSRF Tokens & SameSite

Configure cookies with SameSite=Lax/Strict and require unpredictable synchronizer tokens on state-changing POST/PUT requests.

5. Secure File Upload Architecture

Rename uploads with random UUIDs, whitelist verified extensions, validate magic bytes, and store outside the public web root.

6. Continuous OWASP Hygiene

Security is an ongoing architectural practice. Perform continuous dependency audits (npm audit) and regular automated vulnerability scanning.

Authoritative References & Standards:

OWASP Top 10:2025, OWASP SQL Injection Prevention Cheat Sheet, OWASP Cross-Site Scripting Prevention Cheat Sheet, OWASP Cross-Site Request Forgery Prevention Cheat Sheet, and NIST SP 800-95 (Guide to Secure Web Services).