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:
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.
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.
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:
HTML, CSS, and JavaScript. Renders UI components and initiates HTTP requests via Fetch or Axios.
Node.js, Python, Go, Java, etc. Executes business logic, enforces authentication, and validates authorization.
PostgreSQL, MySQL, MongoDB, Redis, etc. Persists records and executes data retrieval queries.
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.
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.
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.
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.
// 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!
// 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:
Logging into administrator or executive accounts without knowledge of passwords.
Using UNION-based SQLi to extract password hashes, credit card records, and PII tables.
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:
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.
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.
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:
Encode HTML entities prior to rendering: convert < to <, > to >, preventing the parser from treating input as markup.
Never use unsafe element.innerHTML. Always use safe properties like element.textContent or frameworks that auto-escape (e.g., React JSX).
Enforce HTTP response headers like Content-Security-Policy: default-src 'self', blocking untrusted external scripts and inline script execution.
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.
Two Core Pillars of CSRF Defense:
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.
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:
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.
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.
Leaving debug mode enabled in production, revealing detailed stack traces, leaving cloud buckets publicly readable, or retaining factory-default administrator credentials.
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).
Web Application Security Defense Workbench
SQL Injection vs Prepared Statements, XSS Output Encoding, and CSRF Token Validation
SQL Injection vs. Parameterized Query Simulator
Inject test payloads into the username field and observe backend evaluation under raw concatenation vs prepared statements.
SELECT * FROM users WHERE user = 'admin' OR '1'='1' AND pass = 'randompass123'
Because condition ('1'='1') is tautologically TRUE, the database returned the first record (Administrator) despite an invalid password. Attack Succeeded!
Cross-Site Scripting (XSS) & Contextual Encoding Lab
Enter a malicious JavaScript payload in the comment field and compare unencoded raw execution vs encoded DOM output.
The browser parser treated tags as executable HTML markup, firing the malicious script inside the victim's session.
By encoding markup entities, the browser renders the payload safely as benign literal text; zero code executes.
CSRF Simulation & Anti-CSRF Token Validation
Simulate a malicious third-party site sending unauthorized state-changing POST requests to an online banking portal.
The banking API automatically received the victim's ambient browser session cookie without requiring a secret Anti-CSRF token. $1,000 transferred without victim consent!
9 Lesson Summary
Key takeaways and architectural defense patterns covered in this lesson:
Authentication is not authorization. Every backend API endpoint must authoritatively enforce record ownership (WHERE id = :id AND user_id = :uid).
Never concatenate raw user strings into SQL queries. Always use Prepared Statements to ensure the database treats input strictly as literal values.
Perform contextual output encoding, use safe DOM APIs (textContent), enforce CSP headers, and mark cookies as HttpOnly.
Configure cookies with SameSite=Lax/Strict and require unpredictable synchronizer tokens on state-changing POST/PUT requests.
Rename uploads with random UUIDs, whitelist verified extensions, validate magic bytes, and store outside the public web root.
Security is an ongoing architectural practice. Perform continuous dependency audits (npm audit) and regular automated vulnerability scanning.
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).