SQL Injection & XSS In Depth
65 min
SQL Injection
SQL injection occurs when user-supplied input is incorporated into database queries without proper sanitization, allowing attackers to manipulate the query logic.
SQL INJECTION EXAMPLES
══════════════════════════════════════════════
VULNERABLE CODE (PHP):
$query = "SELECT * FROM users WHERE username='" . $_GET["user"] . "'";
ATTACK PAYLOAD:
Username: admin'--
Query becomes: SELECT * FROM users WHERE username='admin'--'
Result: Comments out password check → Login bypass!
UNION ATTACK (Data extraction):
' UNION SELECT username,password,3 FROM users--
→ Appends results from users table
BLIND SQL INJECTION:
' AND 1=1-- → True (page loads normally)
' AND 1=2-- → False (page behaves differently)
→ Extract data one bit at a time
TOOL: sqlmap --url "http://target.com/page?id=1" --dbs
═════════════════════════════════════════════
Prevention: Parameterized Queries
SECURE CODE (PHP PDO):
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = ?");
$stmt->execute([$_GET["user"]]);
// Input is NEVER interpreted as SQL — always treated as literal data
Cross-Site Scripting (XSS)
XSS allows attackers to inject malicious scripts into web pages viewed by other users. The browser executes the script as if it came from the trusted website.
XSS TYPES
──────────────────────────────────────────────
Reflected XSS → Payload in URL/parameter; not stored
URL: /search?q=
Stored XSS → Payload saved in database; affects all viewers
Comment field:
DOM-based XSS → Client-side JS modifies DOM using untrusted input
location.hash processed without sanitization
Impact: Session hijacking, account takeover, keylogging,
drive-by malware download, defacement
──────────────────────────────────────────────
Prevention
- Output encoding — Encode special chars before rendering:
<→< - Content Security Policy (CSP) — HTTP header restricting script sources
- HTTPOnly flag — Prevents JavaScript access to session cookies
- Input validation — Whitelist acceptable input characters/formats