diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 00000000000..7f2f4303320 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,123 @@ +name: release + +on: + workflow_dispatch: + push: + tags: + - "*" + +concurrency: ${{ github.workflow }}-${{ github.ref }} + +permissions: + contents: write + packages: write + +jobs: + build: + strategy: + fail-fast: false + matrix: + include: + - os: ubuntu-latest + target: linux-x64 + artifact: cyxwiz-linux-x64 + - os: ubuntu-latest + target: linux-arm64 + artifact: cyxwiz-linux-arm64 + - os: macos-14 + target: darwin-x64 + artifact: cyxwiz-darwin-x64 + - os: macos-latest + target: darwin-arm64 + artifact: cyxwiz-darwin-arm64 + - os: windows-latest + target: windows-x64 + artifact: cyxwiz-windows-x64 + + runs-on: ${{ matrix.os }} + + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - run: git fetch --force --tags + + - uses: oven-sh/setup-bun@v2 + with: + bun-version: 1.3.6 + + - name: Install dependencies + run: bun install + + - name: Build CLI + working-directory: packages/opencode + run: bun run build --single + env: + OPENCODE_VERSION: ${{ github.ref_name }} + + - name: Package Linux/macOS Binary + if: runner.os != 'Windows' + run: | + cd packages/opencode/dist + DIST_DIR=$(ls -d */ | head -1) + cd "$DIST_DIR/bin" + chmod +x opencode + mv opencode cyxwiz + tar -czvf ${{ matrix.artifact }}.tar.gz cyxwiz + mv ${{ matrix.artifact }}.tar.gz $GITHUB_WORKSPACE/ + + - name: Package Windows Binary + if: runner.os == 'Windows' + shell: pwsh + run: | + cd packages/opencode/dist + $distDir = Get-ChildItem -Directory | Select-Object -First 1 + cd "$($distDir.Name)/bin" + Rename-Item opencode.exe cyxwiz.exe + Compress-Archive -Path cyxwiz.exe -DestinationPath ${{ matrix.artifact }}.zip + Move-Item ${{ matrix.artifact }}.zip $env:GITHUB_WORKSPACE/ + + - name: Upload Artifact + uses: actions/upload-artifact@v4 + with: + name: ${{ matrix.artifact }} + path: | + ${{ matrix.artifact }}.tar.gz + ${{ matrix.artifact }}.zip + if-no-files-found: error + + release: + needs: build + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: Download all artifacts + uses: actions/download-artifact@v4 + with: + path: artifacts + + - name: Prepare release assets + run: | + mkdir -p release + find artifacts -type f \( -name "*.tar.gz" -o -name "*.zip" \) -exec mv {} release/ \; + ls -la release/ + + - name: Generate checksums + run: | + cd release + sha256sum * > checksums.sha256 + cat checksums.sha256 + + - name: Create Release + uses: softprops/action-gh-release@v2 + with: + tag_name: ${{ github.ref_name }} + name: Release ${{ github.ref_name }} + draft: false + prerelease: false + generate_release_notes: true + files: release/* + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/README.md b/README.md index d0ba487402f..7959c4f4671 100644 --- a/README.md +++ b/README.md @@ -1,113 +1,787 @@ -

- - - - - OpenCode logo - - -

-

The open source AI coding agent.

-

- Discord - npm - Build status -

+# Cyxwiz -[![OpenCode Terminal UI](packages/web/src/assets/lander/screenshot.png)](https://opencode.ai) +> **Your AI Security Partner** - Just describe what you need. No commands to memorize. No syntax to learn. + +[![Release](https://img.shields.io/github/v/release/code3hr/opencode?label=Download&color=green)](https://github.com/code3hr/opencode/releases/latest) +[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE) +[![Platform: Linux](https://img.shields.io/badge/Platform-Linux-FCC624)](https://www.linux.org/) +[![Platform: macOS](https://img.shields.io/badge/Platform-macOS-000000)](https://www.apple.com/macos/) +[![Platform: Windows](https://img.shields.io/badge/Platform-Windows-0078D6)](https://www.microsoft.com/windows) + +--- + +## Why Cyxwiz Exists + +Security testing shouldn't require memorizing hundreds of tool flags and command syntaxes. + +Think about it: **nmap** has 130+ options. **Nuclei** has dozens of flags. **SQLMap** has over 100 parameters. Now multiply that by the 30+ tools a typical assessment requires. That's not security work - that's a memorization exercise. + +**Cyxwiz takes a different approach.** Instead of learning tool syntax, you simply describe what you want to accomplish. The AI understands your intent and figures out which tools to use, how to chain them, and how to interpret the results. + +``` +You: "check if this server is vulnerable to log4j" + +Cyxwiz: Checking 192.168.1.10 for Log4Shell vulnerability... + [Running nuclei with CVE-2021-44228 templates] + + Found: CRITICAL - Log4Shell (CVE-2021-44228) confirmed + The server is vulnerable to remote code execution via JNDI injection. + + Recommendation: Upgrade log4j to 2.17.1+ or apply mitigations immediately. +``` + +No flags to remember. No syntax to look up. Just describe what you need. + +--- + +## What Cyxwiz Does + +Cyxwiz is an AI-powered security operations assistant. You talk to it in plain English, and it: + +1. **Understands your intent** - Whether you say "scan for open ports" or "what services are running" - same result +2. **Selects the right tools** - Picks nmap, nuclei, nikto, or whatever fits the task +3. **Chains operations intelligently** - Finds a web server? Automatically suggests vulnerability checks +4. **Explains results clearly** - No raw output dumps, just actionable insights +5. **Tracks everything** - Every finding, every command, ready for your report + +### Talk, Don't Type Commands + +Here's how a real conversation with Cyxwiz looks: + +``` +You: "I need to test this web application at https://target.com" + +Cyxwiz: I'll start with reconnaissance. Let me: + 1. Check what technologies it's running + 2. Look for common vulnerabilities + 3. Test the authentication mechanisms + + Starting now... + + [After scanning] + + Here's what I found: + - Running WordPress 5.8.1 (outdated - current is 6.4) + - 3 plugins with known vulnerabilities + - Admin login page exposed at /wp-admin + - No rate limiting on login attempts + + Want me to dig deeper into any of these? + +You: "yes, check those plugin vulnerabilities" + +Cyxwiz: Looking at the vulnerable plugins... + + CRITICAL: Contact Form 7 < 5.3.2 - Unrestricted file upload + HIGH: Elementor < 3.1.2 - Authenticated XSS + MEDIUM: WooCommerce < 5.2.0 - Information disclosure + + The file upload vulnerability is serious. With a valid form submission, + an attacker could upload malicious PHP files. + + Should I generate a detailed report with remediation steps? +``` + +### What You Can Ask + +Just describe what you need in your own words: + +- *"find all the web servers on this network"* +- *"is this site vulnerable to SQL injection?"* +- *"check the SSL configuration on our servers"* +- *"what users exist in this Active Directory domain?"* +- *"test if this API has authentication issues"* +- *"show me everything you've found so far"* +- *"write up a report for the client"* + +Cyxwiz understands context too. After scanning a network, you can say *"check that Apache server for vulnerabilities"* - it knows which one you mean. + +--- + +## Why Cyxwiz? Why Not Claude CLI or Other LLM Tools? + +Yes, Claude CLI, Cursor, and other LLM tools can run commands too. So what makes Cyxwiz different? + +### The Foundation: OpenCode Agent + +Cyxwiz is built on [OpenCode](https://github.com/sst/opencode), which provides a superior agent architecture compared to generic LLM CLIs: + +``` +┌─────────────────────────────────────────────────────────────────────────────┐ +│ Generic LLM CLI vs Cyxwiz (OpenCode-based) │ +├─────────────────────────────────┬───────────────────────────────────────────┤ +│ Generic LLM CLI │ Cyxwiz │ +├─────────────────────────────────┼───────────────────────────────────────────┤ +│ General-purpose agent │ Security-focused agent │ +│ Raw command output │ Parsed, structured findings │ +│ No domain knowledge │ Security tool expertise built-in │ +│ Basic bash execution │ Specialized tool integrations │ +│ Chat history only │ Findings database + audit trail │ +│ No scope awareness │ Governance & scope enforcement │ +│ Export chat transcript │ Professional pentest reports │ +└─────────────────────────────────┴───────────────────────────────────────────┘ +``` + +### What OpenCode Gives Us (That Others Don't) + +1. **Better Agent Control** - OpenCode's architecture gives finer control over LLM behavior, tool execution, and context management than Claude CLI's generic approach + +2. **Extensible Tool Framework** - Not just "run bash commands" but structured tool definitions with typed inputs/outputs + +3. **Session Persistence** - Real session management, not just chat history + +4. **Multi-LLM Support** - Claude, GPT-4, Gemini, local models - your choice + +### What Cyxwiz Adds on Top of OpenCode + +Cyxwiz extends OpenCode with a complete security operations layer: + +``` +┌─────────────────────────────────────────────────────────────────────────────┐ +│ Cyxwiz Security Layer │ +├─────────────────────────────────────────────────────────────────────────────┤ +│ │ +│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │ +│ │ Security │ │ Output │ │ Findings │ │ Report │ │ +│ │ Tools │ │ Parsers │ │ Database │ │ Engine │ │ +│ │ │ │ │ │ │ │ │ │ +│ │ nmap, nikto │ │ Extract CVEs │ │ Severity │ │ Executive │ │ +│ │ nuclei, etc │ │ Parse JSON │ │ OWASP cats │ │ Technical │ │ +│ │ 30+ tools │ │ Structure │ │ Evidence │ │ HTML/PDF/MD │ │ +│ └──────────────┘ └──────────────┘ └──────────────┘ └──────────────┘ │ +│ │ +│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │ +│ │ Governance │ │ Scope │ │ Audit │ │ +│ │ Engine │ │ Enforcement │ │ Trail │ │ +│ │ │ │ │ │ │ │ +│ │ Policy-based │ │ Authorized │ │ Compliance │ │ +│ │ approval │ │ targets only │ │ logging │ │ +│ └──────────────┘ └──────────────┘ └──────────────┘ │ +│ │ +└─────────────────────────────────────────────────────────────────────────────┘ +``` + +#### 1. Security Tool Integrations (30+ tools) + +| Category | Tools | What Cyxwiz Adds | +|----------|-------|---------------| +| **Network** | nmap, masscan | Service detection, port classification | +| **Web** | nikto, nuclei, gobuster, ffuf | Vuln detection, directory enumeration | +| **Exploitation** | searchsploit, msfconsole | Exploit matching, payload generation | +| **AD/LDAP** | ldapsearch, smbclient | User enum, share discovery | +| **API** | Custom scanners | OpenAPI parsing, JWT analysis | +| **Wireless** | aircrack-ng, reaver | WiFi assessment | +| **Cloud** | aws-cli, az, gcloud | Misconfig detection | + +#### 2. Intelligent Output Parsers + +OpenCode gives raw output. Cyxwiz parses it: + +``` +Raw nmap output: Cyxwiz parsed output: +─────────────────── ────────────────── +PORT STATE SERVICE { +80/tcp open http ──────► "port": 80, + "service": "http", + "product": "Apache", + "version": "2.4.41", + "cves": ["CVE-2021-41773"] + } +``` + +#### 3. Findings Database + +Not just command history - structured security findings: + +- **Severity Classification**: Critical, High, Medium, Low, Info +- **OWASP Categorization**: A01-A10 mapping +- **CVE Tracking**: Automatic CVE detection and linking +- **Evidence Storage**: Screenshots, request/response pairs +- **Remediation Tracking**: Fix status, verification + +#### 4. Governance Engine + +What OpenCode doesn't have: + +- **Scope Definition**: Define authorized targets (IPs, domains, ports) +- **Scope Enforcement**: Block scans against unauthorized targets +- **Policy Rules**: Require approval for destructive actions +- **Engagement Profiles**: Different rules for different assessments + +#### 5. Audit Trail + +Compliance-ready logging: + +``` +[2024-01-15 10:23:45] SCAN_START target=192.168.1.0/24 user=analyst1 +[2024-01-15 10:23:46] SCOPE_CHECK target=192.168.1.0/24 result=AUTHORIZED +[2024-01-15 10:23:47] TOOL_EXEC tool=nmap args="-sV -sC 192.168.1.0/24" +[2024-01-15 10:25:12] FINDING_NEW id=F001 severity=CRITICAL cve=CVE-2021-41773 +[2024-01-15 10:30:00] REPORT_GEN format=HTML findings=15 +``` + +#### 6. Report Generation + +Professional deliverables, not chat exports: + +| Report Type | Contents | Format | +|-------------|----------|--------| +| **Executive** | Risk summary, business impact | HTML, PDF | +| **Technical** | Full findings, evidence, remediation | Markdown, HTML | +| **Compliance** | Audit trail, scope verification | JSON, PDF | +| **Raw Data** | Machine-readable findings | JSON | + +#### 7. Continuous Monitoring + +Schedule recurring scans with diff detection: + +- Baseline establishment +- Change detection (new ports, services, vulns) +- Alert on critical changes +- Trend tracking over time + +#### 8. Web Dashboard + +Visual interface for findings management: + +- Real-time scan progress +- Interactive findings table +- Severity charts and statistics +- Report generation UI + +### Real Example: The Difference + +**Claude CLI:** +``` +You: "scan 192.168.1.10 for vulnerabilities" + +Claude: *runs nmap* + Here's the raw output: + PORT STATE SERVICE VERSION + 80/tcp open http Apache 2.4.41 + 443/tcp open ssl/http Apache 2.4.41 + ... + +You: "what vulnerabilities does it have?" + +Claude: *runs nikto* + Here's what nikto found: + + Server: Apache/2.4.41 + + /: The anti-clickjacking X-Frame-Options header is not present + ... + + [You manually track these, decide severity, write report] +``` + +**Cyxwiz:** +``` +You: "scan 192.168.1.10 for vulnerabilities" + +Cyxwiz: [Runs nmap → parses services] + [Runs nikto → extracts findings] + [Runs nuclei → matches CVEs] + [Classifies by severity] + [Stores in findings database] + + Scan complete. Found: + + CRITICAL (1): + - CVE-2021-41773: Apache path traversal → RCE possible + + HIGH (2): + - Missing security headers (X-Frame-Options, CSP) + - SSL certificate expires in 7 days + + MEDIUM (3): + - Directory listing enabled on /uploads + - Server version disclosed + - Outdated Apache version + + All 6 findings saved with evidence. + +You: "generate report" + +Cyxwiz: [Creates executive summary] + [Includes technical details] + [Adds remediation steps] + [Exports to HTML] + + Report ready: http://localhost:4096/reports/192.168.1.10-assessment.html +``` + +### Summary + +| Feature | Claude CLI | Cyxwiz | +|---------|------------|-----| +| **Agent Architecture** | Generic | OpenCode (superior control) | +| **Tool Integration** | Bash only | 30+ security tools with parsers | +| **Output Handling** | Raw text | Structured findings | +| **Severity Classification** | Manual | Automatic (Critical→Info) | +| **CVE Matching** | Manual lookup | Automatic detection | +| **Scope Control** | None | Governance engine | +| **Audit Trail** | Chat history | Compliance-ready logs | +| **Reports** | Copy-paste chat | Professional HTML/PDF | + +**Cyxwiz = OpenCode's superior agent + Security expertise + Findings management + Governance + Reporting** + +### Why Fork OpenCode? Why Not Build a Plugin? + +| As Plugin | As Fork (Platform) | +|-----------|-------------------| +| Limited by OpenCode's roadmap | Full control | +| Can't modify core UX | Customize everything | +| "Cyxwiz for OpenCode" | "Cyxwiz" | +| Tenant | Owner | +| Single product ceiling | Platform potential | + +**Key reasons we forked:** + +1. **Governance is core, not optional** - Cyxwiz needs scope enforcement and audit logging baked into every command execution. As a plugin, we'd be bolting security onto someone else's foundation. As a fork, governance IS the foundation. + +2. **We need to modify core UX** - Security workflows require approval prompts, findings panels, and audit trails integrated into the interface. Plugins can't touch core UI. + +3. **Platform potential** - Cyxwiz isn't just a pentest tool. It's designed to expand to SOC, DevOps, NetEng domains. A plugin would forever be "Cyxwiz for OpenCode." A fork becomes "Cyxwiz" - its own platform. + +4. **Independence** - OpenCode could change direction, deprecate plugin APIs, or make decisions that conflict with security use cases. Fork = we control our destiny. + +**What we inherited (for free):** CLI/TUI framework, Multi-LLM support (Claude, GPT, Gemini), Session management, Tool execution framework, Plugin system + +**What we added:** Governance engine, Scope enforcement, Audit logging, Security tool parsers (30+), Findings management, Report generation --- -### Installation +## What Cyxwiz Is NOT + +Let's be clear about boundaries: + +### Not a Replacement for Your Judgment + +Cyxwiz is a tool, not a security expert replacement. It doesn't: +- Make risk decisions for your organization +- Determine what's in scope for your engagement +- Replace the need to understand what you're doing +- Guarantee finding every vulnerability + +**You** are the security professional. Cyxwiz handles the tedious parts so you can focus on analysis and decisions. + +### Not for Malicious Use + +Cyxwiz is built for: +- Authorized penetration testing +- Security assessments with written permission +- CTF competitions and security research +- Learning and education + +It is NOT for: +- Unauthorized access to systems +- Attacking systems you don't own or have permission to test +- Any illegal activity + +**The tools Cyxwiz uses are powerful. Use them responsibly and legally.** + +### Not a Magic Button + +Cyxwiz won't: +- Automatically hack anything +- Replace proper methodology +- Skip the need for authorization +- Make you compliant just by running it + +It's an assistant that makes security work more efficient - not a shortcut around doing things properly. + +--- + +## Installation + +### Download Pre-built Binaries + +The easiest way to get started. Download for your platform: + +| Platform | Download | +|----------|----------| +| Linux (x64) | [cyxwiz-linux-x64.tar.gz](https://github.com/code3hr/opencode/releases/latest/download/cyxwiz-linux-x64.tar.gz) | +| Linux (ARM64) | [cyxwiz-linux-arm64.tar.gz](https://github.com/code3hr/opencode/releases/latest/download/cyxwiz-linux-arm64.tar.gz) | +| macOS (Intel) | [cyxwiz-darwin-x64.tar.gz](https://github.com/code3hr/opencode/releases/latest/download/cyxwiz-darwin-x64.tar.gz) | +| macOS (Apple Silicon) | [cyxwiz-darwin-arm64.tar.gz](https://github.com/code3hr/opencode/releases/latest/download/cyxwiz-darwin-arm64.tar.gz) | +| Windows (x64) | [cyxwiz-windows-x64.zip](https://github.com/code3hr/opencode/releases/latest/download/cyxwiz-windows-x64.zip) | ```bash -# YOLO -curl -fsSL https://opencode.ai/install | bash +# Linux/macOS +tar -xzf cyxwiz-*.tar.gz +chmod +x cyxwiz +./cyxwiz -# Package managers -npm i -g opencode-ai@latest # or bun/pnpm/yarn -scoop bucket add extras; scoop install extras/opencode # Windows -choco install opencode # Windows -brew install anomalyco/tap/opencode # macOS and Linux (recommended, always up to date) -brew install opencode # macOS and Linux (official brew formula, updated less) -paru -S opencode-bin # Arch Linux -mise use -g opencode # Any OS -nix run nixpkgs#opencode # or github:anomalyco/opencode for latest dev branch +# Windows +# Extract the zip and run cyxwiz.exe ``` -> [!TIP] -> Remove versions older than 0.1.x before installing. +### Build from Source -### Desktop App (BETA) +```bash +# Install Bun (JavaScript runtime) +curl -fsSL https://bun.sh/install | bash + +# Clone and build +git clone https://github.com/code3hr/opencode.git wiz +cd wiz +bun install +bun run --cwd packages/opencode src/index.ts +``` -OpenCode is also available as a desktop application. Download directly from the [releases page](https://github.com/anomalyco/opencode/releases) or [opencode.ai/download](https://opencode.ai/download). +### Required: API Key -| Platform | Download | -| --------------------- | ------------------------------------- | -| macOS (Apple Silicon) | `opencode-desktop-darwin-aarch64.dmg` | -| macOS (Intel) | `opencode-desktop-darwin-x64.dmg` | -| Windows | `opencode-desktop-windows-x64.exe` | -| Linux | `.deb`, `.rpm`, or AppImage | +Cyxwiz needs an AI provider to work. Set one of these: ```bash -# macOS (Homebrew) -brew install --cask opencode-desktop +export ANTHROPIC_API_KEY=sk-ant-... # Claude (recommended) +# or +export OPENAI_API_KEY=sk-... # GPT-4 ``` -#### Installation Directory +### Recommended: Security Tools -The install script respects the following priority order for the installation path: +For full functionality, have these tools installed (pre-installed on Kali/Parrot): -1. `$OPENCODE_INSTALL_DIR` - Custom installation directory -2. `$XDG_BIN_DIR` - XDG Base Directory Specification compliant path -3. `$HOME/bin` - Standard user binary directory (if exists or can be created) -4. `$HOME/.opencode/bin` - Default fallback +- **nmap** - Network scanning +- **nuclei** - Vulnerability scanning +- **nikto** - Web server scanning +- **gobuster** - Directory enumeration +- **sqlmap** - SQL injection testing + +Don't have them? Cyxwiz will tell you when it needs something. + +--- + +## Architecture + +``` +┌─────────────────────────────────────────────────────────────────────────────┐ +│ YOU (Security Professional) │ +│ │ +│ "scan this network" "check for vulnerabilities" "generate report" │ +└──────────────────────────────────┬───────────────────────────────────────────┘ + │ + ▼ +┌─────────────────────────────────────────────────────────────────────────────┐ +│ CYXWIZ │ +│ ┌─────────────────────────────────────────────────────────────────────┐ │ +│ │ AI Engine (Claude/GPT) │ │ +│ │ │ │ +│ │ • Understands natural language intent │ │ +│ │ • Plans tool sequences │ │ +│ │ • Interprets results │ │ +│ │ • Explains findings │ │ +│ └─────────────────────────────────────────────────────────────────────┘ │ +│ │ │ +│ ▼ │ +│ ┌─────────────────────────────────────────────────────────────────────┐ │ +│ │ Tool Orchestration │ │ +│ │ │ │ +│ │ Network Web API AD Reporting │ │ +│ │ Scanner Scanner Scanner Scanner Engine │ │ +│ └─────────────────────────────────────────────────────────────────────┘ │ +│ │ │ +└───────────────────────────────────┼──────────────────────────────────────────┘ + │ + ▼ +┌─────────────────────────────────────────────────────────────────────────────┐ +│ Security Tools (Kali/Parrot) │ +│ │ +│ nmap nuclei nikto gobuster sqlmap smbclient ldapsearch │ +│ │ +└─────────────────────────────────────────────────────────────────────────────┘ + │ + ▼ +┌─────────────────────────────────────────────────────────────────────────────┐ +│ TARGET SYSTEMS │ +│ (With your authorization) │ +└─────────────────────────────────────────────────────────────────────────────┘ +``` + +### Data Flow + +``` +┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ +│ Intent │ ──▶ │ Plan │ ──▶ │ Execute │ ──▶ │ Findings │ +│ │ │ │ │ │ │ │ +│ "scan │ │ 1. nmap │ │ Run each │ │ Store & │ +│ for web │ │ 2. nikto │ │ tool in │ │ classify │ +│ vulns" │ │ 3. nuclei│ │ sequence │ │ results │ +└──────────┘ └──────────┘ └──────────┘ └──────────┘ + │ + ▼ + ┌──────────┐ + │ Report │ + │ │ + │ Generate │ + │ HTML/PDF │ + └──────────┘ +``` + +--- + +## Running Modes + +Cyxwiz offers multiple interfaces to fit your workflow: + +``` +┌─────────────────────────────────────────────────────────────────┐ +│ INTERFACES │ +├─────────────────┬───────────────────┬───────────────────────────┤ +│ Terminal │ Web Server │ Dashboard │ +│ (Default) │ (--server) │ (Development) │ +├─────────────────┼───────────────────┼───────────────────────────┤ +│ ./cyxwiz │ ./cyxwiz --server│ bun run dashboard │ +│ │ │ │ +│ Interactive │ http://localhost │ http://localhost:5173 │ +│ CLI prompt │ :4096 │ (proxies to :4096) │ +│ │ │ │ +│ Best for: │ Best for: │ Best for: │ +│ Quick tasks, │ Team access, │ Development, │ +│ scripting │ remote work │ customization │ +└─────────────────┴───────────────────┴───────────────────────────┘ +``` + +### Terminal (Default) + +```bash +./cyxwiz +``` + +Interactive command-line interface. Type naturally and see results directly. + +### Web Server (Port 4096) + +```bash +./cyxwiz --server +``` + +Opens a web interface at **http://localhost:4096**. Features: +- Same AI assistant in a browser +- Real-time scan progress +- Interactive findings table +- Report viewing and export + +### Dashboard (Port 5173 - Development) ```bash -# Examples -OPENCODE_INSTALL_DIR=/usr/local/bin curl -fsSL https://opencode.ai/install | bash -XDG_BIN_DIR=$HOME/.local/bin curl -fsSL https://opencode.ai/install | bash +cd packages/opencode/src/dashboard +bun run dev +``` + +Development dashboard at **http://localhost:5173**. For contributors extending Cyxwiz. + +### Web Reports + +Reports are served through the web interface: + +``` +You: "generate a report" + +Cyxwiz: Report generated! + View at: http://localhost:4096/reports/assessment-2024-01-15.html ``` -### Agents +Features: +- Interactive severity charts +- Sortable findings table +- Evidence screenshots +- Export to PDF/HTML/Markdown + +--- + +## How It Works -OpenCode includes two built-in agents you can switch between with the `Tab` key. +### 1. You Describe, Cyxwiz Executes -- **build** - Default, full access agent for development work -- **plan** - Read-only agent for analysis and code exploration - - Denies file edits by default - - Asks permission before running bash commands - - Ideal for exploring unfamiliar codebases or planning changes +``` +You: "find subdomains for example.com" + +Cyxwiz: I'll enumerate subdomains using multiple methods... -Also, included is a **general** subagent for complex searches and multistep tasks. -This is used internally and can be invoked using `@general` in messages. + Found 47 subdomains: + - api.example.com (192.168.1.10) + - mail.example.com (192.168.1.11) + - dev.example.com (192.168.1.12) + - staging.example.com (192.168.1.13) + [... and 43 more] + + Notable: dev and staging are exposed to the internet. + Want me to scan these for vulnerabilities? +``` -Learn more about [agents](https://opencode.ai/docs/agents). +### 2. Cyxwiz Remembers Context -### Documentation +``` +You: "scan the staging server" + +Cyxwiz: Scanning staging.example.com (192.168.1.13)... + + [Cyxwiz remembers this from the previous subdomain scan] +``` + +### 3. Findings Are Tracked + +``` +You: "what have we found so far?" -For more info on how to configure OpenCode [**head over to our docs**](https://opencode.ai/docs). +Cyxwiz: Current findings for example.com assessment: + + CRITICAL (2): + - SQL injection on api.example.com/users + - Exposed admin panel on staging.example.com + + HIGH (5): + - Outdated TLS on mail.example.com + - Missing security headers (4 instances) + + MEDIUM (8): + [...] + + Total: 2 critical, 5 high, 8 medium, 12 low findings +``` + +### 4. Reports When You're Ready + +``` +You: "generate a report for the client" + +Cyxwiz: Generating executive report... + + Created: example-com-assessment-2024-01-15.html + + Includes: + - Executive summary + - Risk ratings + - All findings with evidence + - Remediation recommendations + - Technical appendix +``` + +--- -### Contributing +## Capabilities -If you're interested in contributing to OpenCode, please read our [contributing docs](./CONTRIBUTING.md) before submitting a pull request. +### Network Security +- Port scanning and service detection +- Network mapping and host discovery +- Protocol-specific testing (SMB, SNMP, DNS, LDAP) +- Credential testing and password auditing -### Building on OpenCode +### Web Application Security +- Vulnerability scanning (OWASP Top 10) +- Directory and file enumeration +- SSL/TLS configuration analysis +- CMS vulnerability detection (WordPress, Drupal, etc.) -If you are working on a project that's related to OpenCode and is using "opencode" as a part of its name; for example, "opencode-dashboard" or "opencode-mobile", please add a note to your README to clarify that it is not built by the OpenCode team and is not affiliated with us in any way. +### API Security +- OpenAPI/Swagger discovery and parsing +- Authentication bypass testing +- Injection testing (SQL, NoSQL, Command) +- JWT analysis and manipulation -### FAQ +### Active Directory +- User and group enumeration +- Kerberoasting and AS-REP roasting +- Trust relationship mapping +- Privilege escalation path finding -#### How is this different from Claude Code? +### Reporting +- Executive summaries (HTML/PDF) +- Technical reports (Markdown) +- Raw data export (JSON) +- Evidence preservation + +--- + +## Platform Support + +| Distribution | Status | Notes | +|--------------|--------|-------| +| **Kali Linux** | Fully Supported | All tools pre-installed | +| **Parrot OS** | Fully Supported | All tools pre-installed | +| **Ubuntu/Debian** | Supported | Install tools via apt | +| **Arch Linux** | Supported | Install tools via pacman | +| **macOS** | Supported | Install tools via homebrew | +| **Windows** | Supported | Install tools via chocolatey/manual | + +--- + +## Project Status + +Cyxwiz is under active development. Current capabilities: + +| Module | Status | Description | +|--------|--------|-------------| +| Core Framework | Complete | AI interaction, session management | +| Network Scanning | Complete | Nmap integration, service detection | +| Web Scanning | Complete | Nikto, Nuclei, Gobuster, SQLMap | +| API Security | Complete | OpenAPI, GraphQL, JWT analysis | +| Active Directory | Complete | User enum, Kerberoasting | +| Reporting | Complete | Multiple formats, evidence | +| Cloud Security | In Progress | AWS, Azure, GCP scanning | +| CI/CD Security | In Progress | Pipeline security analysis | +| Container Security | Planned | Docker, Kubernetes | + +--- + +## Documentation + +### Core Docs +| Document | Description | +|----------|-------------| +| [PROJECT.md](docs/PROJECT.md) | Platform architecture and vision | +| [PENTEST.md](docs/PENTEST.md) | Pentest module overview | +| [GOVERNANCE.md](docs/GOVERNANCE.md) | Policy and scope enforcement | +| [TODO.md](docs/TODO.md) | Development roadmap | +| [COMPARISON.md](docs/COMPARISON.md) | How Cyxwiz compares to other tools | + +### Module Documentation (Phases) +| Phase | Module | Description | +|-------|--------|-------------| +| [03](docs/PHASE03-pentest-agent-mvp.md) | Pentest Agent MVP | Core scanning foundation | +| [04](docs/PHASE04-multi-tool-parsers.md) | Multi-Tool Parsers | Nikto, Nuclei, Gobuster parsers | +| [05](docs/PHASE05-report-generation.md) | Report Generation | HTML, PDF, Markdown reports | +| [06](docs/PHASE06-continuous-monitoring.md) | Continuous Monitoring | Scheduled scans, diff detection | +| [07](docs/PHASE07-exploit-framework.md) | Exploit Framework | Metasploit, Searchsploit integration | +| [08](docs/PHASE08-web-app-scanner.md) | Web App Scanner | OWASP Top 10, crawling | +| [09](docs/PHASE09-api-security-scanner.md) | API Security | OpenAPI, GraphQL, JWT testing | +| [10](docs/PHASE10-network-infrastructure.md) | Network Infrastructure | SMB, SNMP, DNS, LDAP | +| [11](docs/PHASE11-cloud-security.md) | Cloud Security | AWS, Azure, GCP scanning | +| [12](docs/PHASE12-container-security.md) | Container Security | Docker, Kubernetes, CVE lookup | +| [13](docs/PHASE13-mobile-app-scanner.md) | Mobile App Scanner | Android/iOS analysis | +| [14](docs/PHASE14-wireless-scanner.md) | Wireless Scanner | WiFi security testing | +| [15](docs/PHASE15-social-engineering.md) | Social Engineering | Phishing, pretexting toolkit | +| [16](docs/PHASE16-post-exploitation.md) | Post-Exploitation | Privilege escalation, persistence | +| [17](docs/PHASE17-reporting-dashboard.md) | Reporting Dashboard | Web UI for findings | +| [18](docs/PHASE18-cicd-security.md) | CI/CD Security | Pipeline security analysis | + +--- + +## Contributing + +Contributions welcome! See [CONTRIBUTING.md](CONTRIBUTING.md). + +--- + +## Security + +Found a security issue? See [SECURITY.md](SECURITY.md). + +--- + +## License + +MIT License - See [LICENSE](LICENSE) + +--- -It's very similar to Claude Code in terms of capability. Here are the key differences: +## Acknowledgments -- 100% open source -- Not coupled to any provider. Although we recommend the models we provide through [OpenCode Zen](https://opencode.ai/zen); OpenCode can be used with Claude, OpenAI, Google or even local models. As models evolve the gaps between them will close and pricing will drop so being provider-agnostic is important. -- Out of the box LSP support -- A focus on TUI. OpenCode is built by neovim users and the creators of [terminal.shop](https://terminal.shop); we are going to push the limits of what's possible in the terminal. -- A client/server architecture. This for example can allow OpenCode to run on your computer, while you can drive it remotely from a mobile app. Meaning that the TUI frontend is just one of the possible clients. +- [OpenCode](https://github.com/sst/opencode) - The foundation we built upon +- [Anthropic](https://anthropic.com) - Claude AI +- The security community for the amazing open-source tools --- -**Join our community** [Discord](https://discord.gg/opencode) | [X.com](https://x.com/opencode) +**Cyxwiz** - *Security testing should be about security, not syntax.* diff --git a/bun.lock b/bun.lock index 0c1a8bb0674..3272d61ab89 100644 --- a/bun.lock +++ b/bun.lock @@ -249,10 +249,10 @@ }, }, "packages/opencode": { - "name": "opencode", + "name": "cyxwiz", "version": "1.1.21", "bin": { - "opencode": "./bin/opencode", + "cyxwiz": "./bin/cyxwiz", }, "dependencies": { "@actions/core": "1.11.1", @@ -306,6 +306,7 @@ "decimal.js": "10.5.0", "diff": "catalog:", "fuzzysort": "3.1.0", + "glob": "10.4.5", "gray-matter": "4.0.3", "hono": "catalog:", "hono-openapi": "catalog:", @@ -324,6 +325,7 @@ "vscode-jsonrpc": "8.2.1", "web-tree-sitter": "0.25.10", "xdg-basedir": "5.1.0", + "yaml": "2.7.0", "yargs": "18.0.0", "zod": "catalog:", "zod-to-json-schema": "3.24.5", @@ -474,7 +476,7 @@ }, "devDependencies": { "@types/node": "catalog:", - "opencode": "workspace:*", + "cyxwiz": "workspace:*", "typescript": "catalog:", }, }, @@ -2225,6 +2227,8 @@ "csstype": ["csstype@3.2.3", "", {}, "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ=="], + "cyxwiz": ["cyxwiz@workspace:packages/opencode"], + "data-uri-to-buffer": ["data-uri-to-buffer@4.0.1", "", {}, "sha512-0R9ikRb668HB7QDxT1vkpuUBtqc53YyAwMwGeUFKRojY/NWKvdZ+9UYtRfGmhqNbRkTSVpMbmyhXipFFv2cb/A=="], "data-view-buffer": ["data-view-buffer@1.0.2", "", { "dependencies": { "call-bound": "^1.0.3", "es-errors": "^1.3.0", "is-data-view": "^1.0.2" } }, "sha512-EmKO5V3OLXh1rtK2wgXRansaK1/mtVdTUEiEI0W8RkvgT05kfxaH29PliLnpLP73yYO6142Q72QNa8Wx/A5CqQ=="], @@ -2541,7 +2545,7 @@ "github-slugger": ["github-slugger@2.0.0", "", {}, "sha512-IaOQ9puYtjrkq7Y0Ygl9KDZnrf/aiUJYUpVf89y8kyaxbRG7Y1SrX/jaumrv81vc61+kiMempujsM3Yw7w5qcw=="], - "glob": ["glob@11.1.0", "", { "dependencies": { "foreground-child": "^3.3.1", "jackspeak": "^4.1.1", "minimatch": "^10.1.1", "minipass": "^7.1.2", "package-json-from-dist": "^1.0.0", "path-scurry": "^2.0.0" }, "bin": { "glob": "dist/esm/bin.mjs" } }, "sha512-vuNwKSaKiqm7g0THUBu2x7ckSs3XJLXE+2ssL7/MfTGPLLcrJQ/4Uq1CjPTtO5cCIiRxqvN6Twy1qOwhL0Xjcw=="], + "glob": ["glob@10.4.5", "", { "dependencies": { "foreground-child": "^3.1.0", "jackspeak": "^3.1.2", "minimatch": "^9.0.4", "minipass": "^7.1.2", "package-json-from-dist": "^1.0.0", "path-scurry": "^1.11.1" }, "bin": { "glob": "dist/esm/bin.mjs" } }, "sha512-7Bv8RF0k6xjo7d4A/PxYLbUCfb6c+Vpd2/mB2yRDlew7Jb5hEXiCD9ibfO7wpk8i4sevK6DFny9h7EYbM3/sHg=="], "glob-parent": ["glob-parent@5.1.2", "", { "dependencies": { "is-glob": "^4.0.1" } }, "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow=="], @@ -2797,7 +2801,7 @@ "iterate-value": ["iterate-value@1.0.2", "", { "dependencies": { "es-get-iterator": "^1.0.2", "iterate-iterator": "^1.0.1" } }, "sha512-A6fMAio4D2ot2r/TYzr4yUWrmwNdsN5xL7+HUiyACE4DXm+q8HtPcnFTp+NnW3k4N05tZ7FVYFFb2CR13NxyHQ=="], - "jackspeak": ["jackspeak@4.1.1", "", { "dependencies": { "@isaacs/cliui": "^8.0.2" } }, "sha512-zptv57P3GpL+O0I7VdMJNBZCu+BPHVQUk55Ft8/QCJjTVxrnJHuVuX/0Bl2A6/+2oyR/ZMEuFKwmzqqZ/U5nPQ=="], + "jackspeak": ["jackspeak@3.4.3", "", { "dependencies": { "@isaacs/cliui": "^8.0.2" }, "optionalDependencies": { "@pkgjs/parseargs": "^0.11.0" } }, "sha512-OGlZQpz2yfahA/Rd1Y8Cd9SIEsqvXkLVoSw/cgwhnhFMDbsQFeZYoJJ7bIZBS9BcamUW96asq/npPWugM+RQBw=="], "jimp": ["jimp@1.6.0", "", { "dependencies": { "@jimp/core": "1.6.0", "@jimp/diff": "1.6.0", "@jimp/js-bmp": "1.6.0", "@jimp/js-gif": "1.6.0", "@jimp/js-jpeg": "1.6.0", "@jimp/js-png": "1.6.0", "@jimp/js-tiff": "1.6.0", "@jimp/plugin-blit": "1.6.0", "@jimp/plugin-blur": "1.6.0", "@jimp/plugin-circle": "1.6.0", "@jimp/plugin-color": "1.6.0", "@jimp/plugin-contain": "1.6.0", "@jimp/plugin-cover": "1.6.0", "@jimp/plugin-crop": "1.6.0", "@jimp/plugin-displace": "1.6.0", "@jimp/plugin-dither": "1.6.0", "@jimp/plugin-fisheye": "1.6.0", "@jimp/plugin-flip": "1.6.0", "@jimp/plugin-hash": "1.6.0", "@jimp/plugin-mask": "1.6.0", "@jimp/plugin-print": "1.6.0", "@jimp/plugin-quantize": "1.6.0", "@jimp/plugin-resize": "1.6.0", "@jimp/plugin-rotate": "1.6.0", "@jimp/plugin-threshold": "1.6.0", "@jimp/types": "1.6.0", "@jimp/utils": "1.6.0" } }, "sha512-YcwCHw1kiqEeI5xRpDlPPBGL2EOpBKLwO4yIBJcXWHPj5PnA5urGq0jbyhM5KoNpypQ6VboSoxc9D8HyfvngSg=="], @@ -3183,8 +3187,6 @@ "openapi-types": ["openapi-types@12.1.3", "", {}, "sha512-N4YtSYJqghVu4iek2ZUvcN/0aqH1kRDuNqzcycDxhOUpg7GdvLa2F3DgS6yBNhInhv2r/6I0Flkn7CqL8+nIcw=="], - "opencode": ["opencode@workspace:packages/opencode"], - "opencontrol": ["opencontrol@0.0.6", "", { "dependencies": { "@modelcontextprotocol/sdk": "1.6.1", "@tsconfig/bun": "1.0.7", "hono": "4.7.4", "zod": "3.24.2", "zod-to-json-schema": "3.24.3" }, "bin": { "opencontrol": "bin/index.mjs" } }, "sha512-QeCrpOK5D15QV8kjnGVeD/BHFLwcVr+sn4T6KKmP0WAMs2pww56e4h+eOGHb5iPOufUQXbdbBKi6WV2kk7tefQ=="], "openid-client": ["openid-client@5.6.4", "", { "dependencies": { "jose": "^4.15.4", "lru-cache": "^6.0.0", "object-hash": "^2.2.0", "oidc-token-hash": "^5.0.3" } }, "sha512-T1h3B10BRPKfcObdBklX639tVz+xh34O7GjofqrqiAQdm7eHsQ00ih18x6wuJ/E6FxdtS2u3FmUGPDeEcMwzNA=="], @@ -3251,7 +3253,7 @@ "path-parse": ["path-parse@1.0.7", "", {}, "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw=="], - "path-scurry": ["path-scurry@2.0.1", "", { "dependencies": { "lru-cache": "^11.0.0", "minipass": "^7.1.2" } }, "sha512-oWyT4gICAu+kaA7QWk/jvCHWarMKNs6pXOGWKDTr7cw4IGcUbW+PeTfbaQiLGheFRpjo6O9J0PmyMfQPjH71oA=="], + "path-scurry": ["path-scurry@1.11.1", "", { "dependencies": { "lru-cache": "^10.2.0", "minipass": "^5.0.0 || ^6.0.2 || ^7.0.0" } }, "sha512-Xa4Nw17FS9ApQFJ9umLiJS4orGjm7ZzwUrwamcGQuHSzDyth9boKDaycYdDcZDuqYATXw4HFXgaqWTctW/v1HA=="], "path-to-regexp": ["path-to-regexp@6.3.0", "", {}, "sha512-Yhpw4T9C6hPpgPeA28us07OJeqZ5EzQTkbfwuhsUg0c237RomFoETJgmp2sa3F/41gfLE6G5cqcYwznmeEeOlQ=="], @@ -3919,7 +3921,7 @@ "yallist": ["yallist@4.0.0", "", {}, "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A=="], - "yaml": ["yaml@2.8.1", "", { "bin": { "yaml": "bin.mjs" } }, "sha512-lcYcMxX2PO9XMGvAJkJ3OsNMw+/7FKes7/hgerGUYWIoWu5j/+YQqcZr5JnPZWzOsEBgMbSbiSTn/dv/69Mkpw=="], + "yaml": ["yaml@2.7.0", "", { "bin": { "yaml": "bin.mjs" } }, "sha512-+hSoy/QHluxmC9kCIJyL/uyFmLmc+e5CFR5Wa+bpIhIj85LVb9ZH2nVnqrHoSvKogwODv0ClqZkmiSSaIH5LTA=="], "yargs": ["yargs@18.0.0", "", { "dependencies": { "cliui": "^9.0.1", "escalade": "^3.1.1", "get-caller-file": "^2.0.5", "string-width": "^7.2.0", "y18n": "^5.0.5", "yargs-parser": "^22.0.0" } }, "sha512-4UEqdc2RYGHZc7Doyqkrqiln3p9X2DZVxaGbwhn2pi7MrRagKaOcIKe8L3OxYcbhXLgLFUS3zAYuQjKBQgmuNg=="], @@ -4299,6 +4301,12 @@ "cross-spawn/which": ["which@2.0.2", "", { "dependencies": { "isexe": "^2.0.0" }, "bin": { "node-which": "./bin/node-which" } }, "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA=="], + "cyxwiz/@ai-sdk/anthropic": ["@ai-sdk/anthropic@2.0.57", "", { "dependencies": { "@ai-sdk/provider": "2.0.1", "@ai-sdk/provider-utils": "3.0.20" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-DREpYqW2pylgaj69gZ+K8u92bo9DaMgFdictYnY+IwYeY3bawQ4zI7l/o1VkDsBDljAx8iYz5lPURwVZNu+Xpg=="], + + "cyxwiz/@ai-sdk/openai": ["@ai-sdk/openai@2.0.89", "", { "dependencies": { "@ai-sdk/provider": "2.0.1", "@ai-sdk/provider-utils": "3.0.20" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-4+qWkBCbL9HPKbgrUO/F2uXZ8GqrYxHa8SWEYIzxEJ9zvWw3ISr3t1/27O1i8MGSym+PzEyHBT48EV4LAwWaEw=="], + + "cyxwiz/@ai-sdk/openai-compatible": ["@ai-sdk/openai-compatible@1.0.30", "", { "dependencies": { "@ai-sdk/provider": "2.0.1", "@ai-sdk/provider-utils": "3.0.20" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-thubwhRtv9uicAxSWwNpinM7hiL/0CkhL/ymPaHuKvI494J7HIzn8KQZQ2ymRz284WTIZnI7VMyyejxW4RMM6w=="], + "dot-prop/type-fest": ["type-fest@3.13.1", "", {}, "sha512-tLq3bSNx+xSpwvAJnzrK0Ep5CLNWjvFTOp71URMaAEWBfRb9nnJiBoUe0tF8bI4ZFO3omgBR6NvnbzVUT3Ly4g=="], "drizzle-kit/esbuild": ["esbuild@0.19.12", "", { "optionalDependencies": { "@esbuild/aix-ppc64": "0.19.12", "@esbuild/android-arm": "0.19.12", "@esbuild/android-arm64": "0.19.12", "@esbuild/android-x64": "0.19.12", "@esbuild/darwin-arm64": "0.19.12", "@esbuild/darwin-x64": "0.19.12", "@esbuild/freebsd-arm64": "0.19.12", "@esbuild/freebsd-x64": "0.19.12", "@esbuild/linux-arm": "0.19.12", "@esbuild/linux-arm64": "0.19.12", "@esbuild/linux-ia32": "0.19.12", "@esbuild/linux-loong64": "0.19.12", "@esbuild/linux-mips64el": "0.19.12", "@esbuild/linux-ppc64": "0.19.12", "@esbuild/linux-riscv64": "0.19.12", "@esbuild/linux-s390x": "0.19.12", "@esbuild/linux-x64": "0.19.12", "@esbuild/netbsd-x64": "0.19.12", "@esbuild/openbsd-x64": "0.19.12", "@esbuild/sunos-x64": "0.19.12", "@esbuild/win32-arm64": "0.19.12", "@esbuild/win32-ia32": "0.19.12", "@esbuild/win32-x64": "0.19.12" }, "bin": { "esbuild": "bin/esbuild" } }, "sha512-aARqgq8roFBj054KvQr5f1sFu0D65G+miZRCuJyJ0G13Zwx7vRar5Zhn2tkQNzIXcBrNVsv/8stehpj+GAjgbg=="], @@ -4333,7 +4341,7 @@ "gaxios/node-fetch": ["node-fetch@3.3.2", "", { "dependencies": { "data-uri-to-buffer": "^4.0.0", "fetch-blob": "^3.1.4", "formdata-polyfill": "^4.0.10" } }, "sha512-dRB78srN/l6gqWulah9SrxeYnxeddIG30+GOqK/9OlLVyLg3HPnr6SqOWTWOXKRwC2eGYCkZ59NNuSgvSrpgOA=="], - "glob/minimatch": ["minimatch@10.1.1", "", { "dependencies": { "@isaacs/brace-expansion": "^5.0.0" } }, "sha512-enIvLvRAFZYXJzkCYG5RKmPfrFArdLv+R+lbQ53BmIMLIry74bjKzX6iHAm8WYamJkhSSEabrWN5D97XnKObjQ=="], + "glob/minimatch": ["minimatch@9.0.5", "", { "dependencies": { "brace-expansion": "^2.0.1" } }, "sha512-G6T0ZX48xgozx7587koeX9Ys2NYy6Gmv//P89sEte9V9whIapMNF4idKxnW2QtCcLiTWlb/wfCabAtAFWhhBow=="], "globby/ignore": ["ignore@5.3.2", "", {}, "sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g=="], @@ -4373,12 +4381,6 @@ "nypm/tinyexec": ["tinyexec@1.0.2", "", {}, "sha512-W/KYk+NFhkmsYpuHq5JykngiOCnxeVL8v8dFnqxSD8qEEdRfXk1SDM6JzNqcERbcGYj9tMrDQBYV9cjgnunFIg=="], - "opencode/@ai-sdk/anthropic": ["@ai-sdk/anthropic@2.0.57", "", { "dependencies": { "@ai-sdk/provider": "2.0.1", "@ai-sdk/provider-utils": "3.0.20" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-DREpYqW2pylgaj69gZ+K8u92bo9DaMgFdictYnY+IwYeY3bawQ4zI7l/o1VkDsBDljAx8iYz5lPURwVZNu+Xpg=="], - - "opencode/@ai-sdk/openai": ["@ai-sdk/openai@2.0.89", "", { "dependencies": { "@ai-sdk/provider": "2.0.1", "@ai-sdk/provider-utils": "3.0.20" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-4+qWkBCbL9HPKbgrUO/F2uXZ8GqrYxHa8SWEYIzxEJ9zvWw3ISr3t1/27O1i8MGSym+PzEyHBT48EV4LAwWaEw=="], - - "opencode/@ai-sdk/openai-compatible": ["@ai-sdk/openai-compatible@1.0.30", "", { "dependencies": { "@ai-sdk/provider": "2.0.1", "@ai-sdk/provider-utils": "3.0.20" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-thubwhRtv9uicAxSWwNpinM7hiL/0CkhL/ymPaHuKvI494J7HIzn8KQZQ2ymRz284WTIZnI7VMyyejxW4RMM6w=="], - "opencontrol/@modelcontextprotocol/sdk": ["@modelcontextprotocol/sdk@1.6.1", "", { "dependencies": { "content-type": "^1.0.5", "cors": "^2.8.5", "eventsource": "^3.0.2", "express": "^5.0.1", "express-rate-limit": "^7.5.0", "pkce-challenge": "^4.1.0", "raw-body": "^3.0.0", "zod": "^3.23.8", "zod-to-json-schema": "^3.24.1" } }, "sha512-oxzMzYCkZHMntzuyerehK3fV6A2Kwh5BD6CGEJSVDU2QNEhfLOptf2X7esQgaHZXHZY0oHmMsOtIDLP71UJXgA=="], "opencontrol/@tsconfig/bun": ["@tsconfig/bun@1.0.7", "", {}, "sha512-udGrGJBNQdXGVulehc1aWT73wkR9wdaGBtB6yL70RJsqwW/yJhIg6ZbRlPOfIUiFNrnBuYLBi9CSmMKfDC7dvA=="], @@ -4399,7 +4401,7 @@ "parse5/entities": ["entities@6.0.1", "", {}, "sha512-aN97NXWF6AWBTahfVOIrB/NShkzi5H7F9r1s9mD3cDj4Ko5f2qhhVoYMibXF7GlLveb/D2ioWay8lxI97Ven3g=="], - "path-scurry/lru-cache": ["lru-cache@11.2.2", "", {}, "sha512-F9ODfyqML2coTIsQpSkRHnLSZMtkU8Q+mSfcaIyKwy58u+8k5nvAYeiNhsyMARvzNcXJ9QfWVrcPsC9e9rAxtg=="], + "path-scurry/lru-cache": ["lru-cache@10.4.3", "", {}, "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ=="], "pixelmatch/pngjs": ["pngjs@6.0.0", "", {}, "sha512-TRzzuFRRmEoSW/p1KVAmiOgPco2Irlah+bGFCeNfJXxxYGwSw7YwAOAcd7X28K/m5bjBWKsC29KyoMfHbypayg=="], @@ -4407,6 +4409,8 @@ "postcss-load-config/lilconfig": ["lilconfig@3.1.3", "", {}, "sha512-/vlFKAoH5Cgt3Ie+JLhRbwOsCQePABiU3tJ1egGvyQ+33R/vcwM2Zl2QR/LzjsBeItPt3oSVXapn+m4nQDvpzw=="], + "postcss-load-config/yaml": ["yaml@2.8.1", "", { "bin": { "yaml": "bin.mjs" } }, "sha512-lcYcMxX2PO9XMGvAJkJ3OsNMw+/7FKes7/hgerGUYWIoWu5j/+YQqcZr5JnPZWzOsEBgMbSbiSTn/dv/69Mkpw=="], + "prompts/kleur": ["kleur@3.0.3", "", {}, "sha512-eTIzlVOSUR+JxdDFepEYcBMtZ9Qqdef+rnzWdRZuMbOywu5tO2w2N7rqjoANZ5k9vywhL6Br1VRjUIgTQx4E8w=="], "raw-body/iconv-lite": ["iconv-lite@0.4.24", "", { "dependencies": { "safer-buffer": ">= 2.1.2 < 3" } }, "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA=="], @@ -4469,6 +4473,8 @@ "utif2/pako": ["pako@1.0.11", "", {}, "sha512-4hLB8Py4zZce5s4yd9XzopqwVv/yGNhV1Bl8NTmCq1763HeK2+EwVTv+leGeL13Dnh2wfbqowVPXCIO0z4taYw=="], + "vite-plugin-icons-spritesheet/glob": ["glob@11.1.0", "", { "dependencies": { "foreground-child": "^3.3.1", "jackspeak": "^4.1.1", "minimatch": "^10.1.1", "minipass": "^7.1.2", "package-json-from-dist": "^1.0.0", "path-scurry": "^2.0.0" }, "bin": { "glob": "dist/esm/bin.mjs" } }, "sha512-vuNwKSaKiqm7g0THUBu2x7ckSs3XJLXE+2ssL7/MfTGPLLcrJQ/4Uq1CjPTtO5cCIiRxqvN6Twy1qOwhL0Xjcw=="], + "vitest/tinyexec": ["tinyexec@1.0.2", "", {}, "sha512-W/KYk+NFhkmsYpuHq5JykngiOCnxeVL8v8dFnqxSD8qEEdRfXk1SDM6JzNqcERbcGYj9tMrDQBYV9cjgnunFIg=="], "vitest/vite": ["vite@7.1.10", "", { "dependencies": { "esbuild": "^0.25.0", "fdir": "^6.5.0", "picomatch": "^4.0.3", "postcss": "^8.5.6", "rollup": "^4.43.0", "tinyglobby": "^0.2.15" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "peerDependencies": { "@types/node": "^20.19.0 || >=22.12.0", "jiti": ">=1.21.0", "less": "^4.0.0", "lightningcss": "^1.21.0", "sass": "^1.70.0", "sass-embedded": "^1.70.0", "stylus": ">=0.54.8", "sugarss": "^5.0.0", "terser": "^5.16.0", "tsx": "^4.8.1", "yaml": "^2.4.2" }, "optionalPeers": ["@types/node", "jiti", "less", "lightningcss", "sass", "sass-embedded", "stylus", "sugarss", "terser", "tsx", "yaml"], "bin": { "vite": "bin/vite.js" } }, "sha512-CmuvUBzVJ/e3HGxhg6cYk88NGgTnBoOo7ogtfJJ0fefUWAxN/WDSUa50o+oVBxuIhO8FoEZW0j2eW7sfjs5EtA=="], @@ -4877,12 +4883,8 @@ "ansi-align/string-width/strip-ansi": ["strip-ansi@6.0.1", "", { "dependencies": { "ansi-regex": "^5.0.1" } }, "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A=="], - "archiver-utils/glob/jackspeak": ["jackspeak@3.4.3", "", { "dependencies": { "@isaacs/cliui": "^8.0.2" }, "optionalDependencies": { "@pkgjs/parseargs": "^0.11.0" } }, "sha512-OGlZQpz2yfahA/Rd1Y8Cd9SIEsqvXkLVoSw/cgwhnhFMDbsQFeZYoJJ7bIZBS9BcamUW96asq/npPWugM+RQBw=="], - "archiver-utils/glob/minimatch": ["minimatch@9.0.5", "", { "dependencies": { "brace-expansion": "^2.0.1" } }, "sha512-G6T0ZX48xgozx7587koeX9Ys2NYy6Gmv//P89sEte9V9whIapMNF4idKxnW2QtCcLiTWlb/wfCabAtAFWhhBow=="], - "archiver-utils/glob/path-scurry": ["path-scurry@1.11.1", "", { "dependencies": { "lru-cache": "^10.2.0", "minipass": "^5.0.0 || ^6.0.2 || ^7.0.0" } }, "sha512-Xa4Nw17FS9ApQFJ9umLiJS4orGjm7ZzwUrwamcGQuHSzDyth9boKDaycYdDcZDuqYATXw4HFXgaqWTctW/v1HA=="], - "astro/shiki/@shikijs/core": ["@shikijs/core@3.15.0", "", { "dependencies": { "@shikijs/types": "3.15.0", "@shikijs/vscode-textmate": "^10.0.2", "@types/hast": "^3.0.4", "hast-util-to-html": "^9.0.5" } }, "sha512-8TOG6yG557q+fMsSVa8nkEDOZNTSxjbbR8l6lF2gyr6Np+jrPlslqDxQkN6rMXCECQ3isNPZAGszAfYoJOPGlg=="], "astro/shiki/@shikijs/engine-javascript": ["@shikijs/engine-javascript@3.15.0", "", { "dependencies": { "@shikijs/types": "3.15.0", "@shikijs/vscode-textmate": "^10.0.2", "oniguruma-to-es": "^4.3.3" } }, "sha512-ZedbOFpopibdLmvTz2sJPJgns8Xvyabe2QbmqMTz07kt1pTzfEvKZc5IqPVO/XFiEbbNyaOpjPBkkr1vlwS+qg=="], @@ -4905,8 +4907,6 @@ "babel-plugin-module-resolver/glob/minipass": ["minipass@4.2.8", "", {}, "sha512-fNzuVyifolSLFL4NzpF+wEF4qrgqaaKX0haXPQEdQ7NKAN+WecoKMHV09YcuL/DHxrUsYQOK3MiuDf7Ip2OXfQ=="], - "babel-plugin-module-resolver/glob/path-scurry": ["path-scurry@1.11.1", "", { "dependencies": { "lru-cache": "^10.2.0", "minipass": "^5.0.0 || ^6.0.2 || ^7.0.0" } }, "sha512-Xa4Nw17FS9ApQFJ9umLiJS4orGjm7ZzwUrwamcGQuHSzDyth9boKDaycYdDcZDuqYATXw4HFXgaqWTctW/v1HA=="], - "body-parser/debug/ms": ["ms@2.0.0", "", {}, "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A=="], "cross-spawn/which/isexe": ["isexe@2.0.0", "", {}, "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw=="], @@ -4967,12 +4967,8 @@ "gray-matter/js-yaml/argparse": ["argparse@1.0.10", "", { "dependencies": { "sprintf-js": "~1.0.2" } }, "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg=="], - "js-beautify/glob/jackspeak": ["jackspeak@3.4.3", "", { "dependencies": { "@isaacs/cliui": "^8.0.2" }, "optionalDependencies": { "@pkgjs/parseargs": "^0.11.0" } }, "sha512-OGlZQpz2yfahA/Rd1Y8Cd9SIEsqvXkLVoSw/cgwhnhFMDbsQFeZYoJJ7bIZBS9BcamUW96asq/npPWugM+RQBw=="], - "js-beautify/glob/minimatch": ["minimatch@9.0.5", "", { "dependencies": { "brace-expansion": "^2.0.1" } }, "sha512-G6T0ZX48xgozx7587koeX9Ys2NYy6Gmv//P89sEte9V9whIapMNF4idKxnW2QtCcLiTWlb/wfCabAtAFWhhBow=="], - "js-beautify/glob/path-scurry": ["path-scurry@1.11.1", "", { "dependencies": { "lru-cache": "^10.2.0", "minipass": "^5.0.0 || ^6.0.2 || ^7.0.0" } }, "sha512-Xa4Nw17FS9ApQFJ9umLiJS4orGjm7ZzwUrwamcGQuHSzDyth9boKDaycYdDcZDuqYATXw4HFXgaqWTctW/v1HA=="], - "jsonwebtoken/jws/jwa": ["jwa@1.4.2", "", { "dependencies": { "buffer-equal-constant-time": "^1.0.1", "ecdsa-sig-formatter": "1.0.11", "safe-buffer": "^5.0.1" } }, "sha512-eeH5JO+21J78qMvTIDdBXidBd6nG2kZjg5Ohz/1fpa28Z4CcsWUzJ1ZZyFq/3z3N17aZy+ZuBoHljASbL1WfOw=="], "lazystream/readable-stream/safe-buffer": ["safe-buffer@5.1.2", "", {}, "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g=="], @@ -4995,12 +4991,8 @@ "readable-stream/buffer/ieee754": ["ieee754@1.2.1", "", {}, "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA=="], - "rimraf/glob/jackspeak": ["jackspeak@3.4.3", "", { "dependencies": { "@isaacs/cliui": "^8.0.2" }, "optionalDependencies": { "@pkgjs/parseargs": "^0.11.0" } }, "sha512-OGlZQpz2yfahA/Rd1Y8Cd9SIEsqvXkLVoSw/cgwhnhFMDbsQFeZYoJJ7bIZBS9BcamUW96asq/npPWugM+RQBw=="], - "rimraf/glob/minimatch": ["minimatch@9.0.5", "", { "dependencies": { "brace-expansion": "^2.0.1" } }, "sha512-G6T0ZX48xgozx7587koeX9Ys2NYy6Gmv//P89sEte9V9whIapMNF4idKxnW2QtCcLiTWlb/wfCabAtAFWhhBow=="], - "rimraf/glob/path-scurry": ["path-scurry@1.11.1", "", { "dependencies": { "lru-cache": "^10.2.0", "minipass": "^5.0.0 || ^6.0.2 || ^7.0.0" } }, "sha512-Xa4Nw17FS9ApQFJ9umLiJS4orGjm7ZzwUrwamcGQuHSzDyth9boKDaycYdDcZDuqYATXw4HFXgaqWTctW/v1HA=="], - "send/debug/ms": ["ms@2.0.0", "", {}, "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A=="], "string-width-cjs/strip-ansi/ansi-regex": ["ansi-regex@5.0.1", "", {}, "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ=="], @@ -5017,6 +5009,12 @@ "type-is/mime-types/mime-db": ["mime-db@1.52.0", "", {}, "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg=="], + "vite-plugin-icons-spritesheet/glob/jackspeak": ["jackspeak@4.1.1", "", { "dependencies": { "@isaacs/cliui": "^8.0.2" } }, "sha512-zptv57P3GpL+O0I7VdMJNBZCu+BPHVQUk55Ft8/QCJjTVxrnJHuVuX/0Bl2A6/+2oyR/ZMEuFKwmzqqZ/U5nPQ=="], + + "vite-plugin-icons-spritesheet/glob/minimatch": ["minimatch@10.1.1", "", { "dependencies": { "@isaacs/brace-expansion": "^5.0.0" } }, "sha512-enIvLvRAFZYXJzkCYG5RKmPfrFArdLv+R+lbQ53BmIMLIry74bjKzX6iHAm8WYamJkhSSEabrWN5D97XnKObjQ=="], + + "vite-plugin-icons-spritesheet/glob/path-scurry": ["path-scurry@2.0.1", "", { "dependencies": { "lru-cache": "^11.0.0", "minipass": "^7.1.2" } }, "sha512-oWyT4gICAu+kaA7QWk/jvCHWarMKNs6pXOGWKDTr7cw4IGcUbW+PeTfbaQiLGheFRpjo6O9J0PmyMfQPjH71oA=="], + "vitest/vite/esbuild": ["esbuild@0.25.12", "", { "optionalDependencies": { "@esbuild/aix-ppc64": "0.25.12", "@esbuild/android-arm": "0.25.12", "@esbuild/android-arm64": "0.25.12", "@esbuild/android-x64": "0.25.12", "@esbuild/darwin-arm64": "0.25.12", "@esbuild/darwin-x64": "0.25.12", "@esbuild/freebsd-arm64": "0.25.12", "@esbuild/freebsd-x64": "0.25.12", "@esbuild/linux-arm": "0.25.12", "@esbuild/linux-arm64": "0.25.12", "@esbuild/linux-ia32": "0.25.12", "@esbuild/linux-loong64": "0.25.12", "@esbuild/linux-mips64el": "0.25.12", "@esbuild/linux-ppc64": "0.25.12", "@esbuild/linux-riscv64": "0.25.12", "@esbuild/linux-s390x": "0.25.12", "@esbuild/linux-x64": "0.25.12", "@esbuild/netbsd-arm64": "0.25.12", "@esbuild/netbsd-x64": "0.25.12", "@esbuild/openbsd-arm64": "0.25.12", "@esbuild/openbsd-x64": "0.25.12", "@esbuild/openharmony-arm64": "0.25.12", "@esbuild/sunos-x64": "0.25.12", "@esbuild/win32-arm64": "0.25.12", "@esbuild/win32-ia32": "0.25.12", "@esbuild/win32-x64": "0.25.12" }, "bin": { "esbuild": "bin/esbuild" } }, "sha512-bbPBYYrtZbkt6Os6FiTLCTFxvq4tt3JKall1vRwshA3fdVztsLAatFaZobhkBC8/BrPetoa0oksYoKXoG4ryJg=="], "wrap-ansi-cjs/string-width/emoji-regex": ["emoji-regex@8.0.0", "", {}, "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A=="], @@ -5137,20 +5135,12 @@ "ansi-align/string-width/strip-ansi/ansi-regex": ["ansi-regex@5.0.1", "", {}, "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ=="], - "archiver-utils/glob/path-scurry/lru-cache": ["lru-cache@10.4.3", "", {}, "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ=="], - "astro/unstorage/h3/cookie-es": ["cookie-es@1.2.2", "", {}, "sha512-+W7VmiVINB+ywl1HGXJXmrqkOhpKrIiVZV6tQuV54ZyQC7MMuBt81Vc336GMLoHBq5hV/F9eXgt5Mnx0Rha5Fg=="], "astro/unstorage/h3/crossws": ["crossws@0.3.5", "", { "dependencies": { "uncrypto": "^0.1.3" } }, "sha512-ojKiDvcmByhwa8YYqbQI/hg7MEU0NC03+pSdEq4ZUnZR9xXpwk7E43SMNGkn+JxJGPFtNvQ48+vV2p+P1ml5PA=="], - "babel-plugin-module-resolver/glob/path-scurry/lru-cache": ["lru-cache@10.4.3", "", {}, "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ=="], - - "babel-plugin-module-resolver/glob/path-scurry/minipass": ["minipass@7.1.2", "", {}, "sha512-qOOzS1cBTWYF4BH8fVePDBOO9iptMnGUEZwNc/cMWnTV2nVLZ7VoNWEPHkYczZA0pdoA7dl6e7FL659nX9S2aw=="], - "esbuild-plugin-copy/chokidar/readdirp/picomatch": ["picomatch@2.3.1", "", {}, "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA=="], - "js-beautify/glob/path-scurry/lru-cache": ["lru-cache@10.4.3", "", {}, "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ=="], - "opencontrol/@modelcontextprotocol/sdk/express/accepts": ["accepts@2.0.0", "", { "dependencies": { "mime-types": "^3.0.0", "negotiator": "^1.0.0" } }, "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng=="], "opencontrol/@modelcontextprotocol/sdk/express/body-parser": ["body-parser@2.2.0", "", { "dependencies": { "bytes": "^3.1.2", "content-type": "^1.0.5", "debug": "^4.4.0", "http-errors": "^2.0.0", "iconv-lite": "^0.6.3", "on-finished": "^2.4.1", "qs": "^6.14.0", "raw-body": "^3.0.0", "type-is": "^2.0.0" } }, "sha512-02qvAaxv8tp7fBa/mw1ga98OGm+eCbqzJOKoRt70sLmfEEi+jyBYVTDGfCL/k06/4EMk/z01gCe7HoCH/f2LTg=="], @@ -5183,12 +5173,12 @@ "pkg-up/find-up/locate-path/path-exists": ["path-exists@3.0.0", "", {}, "sha512-bpC7GYwiDYQ4wYLe+FA8lhRjhQCMcQGuSgGGqDkg/QerRWw9CmGRT0iSOVRSZJ29NMLZgIzqaljJ63oaL4NIJQ=="], - "rimraf/glob/path-scurry/lru-cache": ["lru-cache@10.4.3", "", {}, "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ=="], - "tw-to-css/tailwindcss/chokidar/glob-parent": ["glob-parent@5.1.2", "", { "dependencies": { "is-glob": "^4.0.1" } }, "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow=="], "tw-to-css/tailwindcss/chokidar/readdirp": ["readdirp@3.6.0", "", { "dependencies": { "picomatch": "^2.2.1" } }, "sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA=="], + "vite-plugin-icons-spritesheet/glob/path-scurry/lru-cache": ["lru-cache@11.2.2", "", {}, "sha512-F9ODfyqML2coTIsQpSkRHnLSZMtkU8Q+mSfcaIyKwy58u+8k5nvAYeiNhsyMARvzNcXJ9QfWVrcPsC9e9rAxtg=="], + "vitest/vite/esbuild/@esbuild/aix-ppc64": ["@esbuild/aix-ppc64@0.25.12", "", { "os": "aix", "cpu": "ppc64" }, "sha512-Hhmwd6CInZ3dwpuGTF8fJG6yoWmsToE+vYgD4nytZVxcu1ulHpUQRAB1UJ8+N1Am3Mz4+xOByoQoSZf4D+CpkA=="], "vitest/vite/esbuild/@esbuild/android-arm": ["@esbuild/android-arm@0.25.12", "", { "os": "android", "cpu": "arm" }, "sha512-VJ+sKvNA/GE7Ccacc9Cha7bpS8nyzVv0jdVgwNDaR4gDMC/2TTRc33Ip8qrNYUcpkOHUT5OZ0bUcNNVZQ9RLlg=="], diff --git a/debian/changelog b/debian/changelog new file mode 100644 index 00000000000..519ea325feb --- /dev/null +++ b/debian/changelog @@ -0,0 +1,19 @@ +cyxwiz (1.1.0-1) unstable; urgency=medium + + * Initial release + * AI-powered security operations platform + * Natural language tool orchestration + * Governance engine with policy-based approval + * Scope enforcement for authorized targets + * Comprehensive audit logging + * Structured findings management + * Professional report generation + * Integrated security tools: + - Network scanning (nmap, masscan) + - Web scanning (nikto, nuclei, gobuster, ffuf) + - Active Directory enumeration + - SMB/SNMP/DNS/LDAP testing + - API security testing + - Credential testing + + -- code3hr Sat, 17 Jan 2026 12:00:00 +0000 diff --git a/debian/compat b/debian/compat new file mode 100644 index 00000000000..b1bd38b62a0 --- /dev/null +++ b/debian/compat @@ -0,0 +1 @@ +13 diff --git a/debian/control b/debian/control new file mode 100644 index 00000000000..77f572ddd2a --- /dev/null +++ b/debian/control @@ -0,0 +1,61 @@ +Source: cyxwiz +Section: utils +Priority: optional +Maintainer: code3hr +Build-Depends: debhelper-compat (= 13) +Standards-Version: 4.6.0 +Homepage: https://github.com/code3hr/opencode +Vcs-Browser: https://github.com/code3hr/opencode +Vcs-Git: https://github.com/code3hr/opencode.git +Rules-Requires-Root: no + +Package: cyxwiz +Architecture: all +Depends: ${misc:Depends} +Pre-Depends: curl +Recommends: nmap, + nikto, + nuclei, + gobuster, + ffuf, + sqlmap, + smbclient, + ldap-utils, + snmp, + dnsutils, + sslscan, + whatweb, + wfuzz, + hydra, + medusa, + enum4linux, + nbtscan, + onesixtyone, + masscan, + amass, + subfinder +Suggests: metasploit-framework, + burpsuite, + zaproxy +Description: AI-powered security operations platform + Cyxwiz is an AI-powered operations platform for security professionals. + It orchestrates 30+ security tools through natural language commands, + with governance, scope enforcement, and audit logging. + . + Built for Kali Linux and Parrot OS, Cyxwiz leverages the 600+ security + tools already installed on these distributions. + . + Features: + - Natural language tool orchestration + - Governance engine with policy-based approval + - Scope enforcement for authorized targets only + - Comprehensive audit logging + - Structured findings management + - Professional report generation + . + Supported tool categories: + - Reconnaissance: nmap, masscan, amass, subfinder + - Web Scanning: nikto, nuclei, gobuster, ffuf, sqlmap + - Network Analysis: SMB, SNMP, DNS, LDAP enumeration + - Active Directory: User/group enumeration, Kerberoasting + - API Security: OpenAPI parsing, JWT analysis diff --git a/debian/copyright b/debian/copyright new file mode 100644 index 00000000000..84ebaee5a78 --- /dev/null +++ b/debian/copyright @@ -0,0 +1,31 @@ +Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/ +Upstream-Name: cyxwiz +Upstream-Contact: code3hr +Source: https://github.com/code3hr/opencode + +Files: * +Copyright: 2024-2026 code3hr +License: MIT + +Files: debian/* +Copyright: 2026 code3hr +License: MIT + +License: MIT + Permission is hereby granted, free of charge, to any person obtaining a + copy of this software and associated documentation files (the "Software"), + to deal in the Software without restriction, including without limitation + the rights to use, copy, modify, merge, publish, distribute, sublicense, + and/or sell copies of the Software, and to permit persons to whom the + Software is furnished to do so, subject to the following conditions: + . + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + . + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/debian/cyxwiz.1 b/debian/cyxwiz.1 new file mode 100644 index 00000000000..dcf91b8bcda --- /dev/null +++ b/debian/cyxwiz.1 @@ -0,0 +1,123 @@ +.TH CYXWIZ 1 "January 2026" "cyxwiz 1.0.0" "User Commands" +.SH NAME +cyxwiz \- AI-powered security operations platform +.SH SYNOPSIS +.B cyxwiz +[\fIOPTIONS\fR] +.SH DESCRIPTION +.B Cyxwiz +is an AI-powered operations platform for security professionals. +It orchestrates 30+ security tools through natural language commands, +with governance, scope enforcement, and comprehensive audit logging. +.PP +Built for Kali Linux and Parrot OS, Cyxwiz leverages the security tools +already installed on these distributions. Instead of memorizing tool +syntax and manually orchestrating workflows, describe what you want +to accomplish in natural language. +.SH FEATURES +.TP +.B Natural Language Interface +Describe security testing tasks in plain English. Cyxwiz translates your +intent into the appropriate tool commands. +.TP +.B Governance Engine +Every action is evaluated against policies before execution. Define +what's allowed, what needs approval, and what's blocked. +.TP +.B Scope Enforcement +Define authorized targets (IPs, domains, ports). Cyxwiz prevents +accidental out-of-scope scanning. +.TP +.B Audit Trail +Every command, approval, and result is automatically logged for +compliance reporting. +.TP +.B Findings Management +Structured storage of all security findings with severity classification, +OWASP/CVE categorization, and remediation tracking. +.TP +.B Report Generation +Professional reports in Markdown, HTML, and JSON formats. +.SH SUPPORTED TOOLS +.SS Reconnaissance +nmap, masscan, amass, subfinder +.SS Web Scanning +nikto, nuclei, gobuster, ffuf, sqlmap, whatweb, wfuzz +.SS Network Analysis +SMB enumeration, SNMP walking, DNS zone transfers, LDAP enumeration +.SS Active Directory +User/group enumeration, Kerberoasting, AS-REP roasting +.SS API Security +OpenAPI parsing, JWT analysis, BOLA/IDOR testing +.SH EXAMPLES +.PP +Start Cyxwiz: +.RS +.B cyxwiz +.RE +.PP +Scan a network for open ports: +.RS +> scan 192.168.1.0/24 for open ports +.RE +.PP +Check for web vulnerabilities: +.RS +> scan https://target.com for OWASP Top 10 +.RE +.PP +Enumerate Active Directory: +.RS +> enumerate users in corp.local domain +.RE +.PP +Generate a report: +.RS +> generate executive report +.RE +.SH ENVIRONMENT +.TP +.B ANTHROPIC_API_KEY +API key for Claude AI (recommended). +.TP +.B OPENAI_API_KEY +API key for OpenAI GPT models (alternative). +.TP +.B CYXWIZ_CONFIG +Path to configuration file (optional). +.SH FILES +.TP +.I /usr/lib/cyxwiz/ +Cyxwiz installation directory. +.TP +.I /usr/share/doc/cyxwiz/ +Documentation files. +.TP +.I ~/.cyxwiz/ +User configuration and session data. +.SH SECURITY +.PP +Cyxwiz includes governance features specifically to prevent misuse: +.IP \(bu 2 +Scope enforcement blocks unauthorized targets +.IP \(bu 2 +Audit logging creates accountability +.IP \(bu 2 +Designed for authorized testing only +.PP +.B WARNING: +Only use Cyxwiz for authorized security testing. Unauthorized scanning +or testing is illegal and unethical. +.SH SEE ALSO +.BR nmap (1), +.BR nikto (1), +.BR sqlmap (1), +.BR nuclei (1) +.SH BUGS +Report bugs at: https://github.com/code3hr/opencode/issues +.SH AUTHOR +Written by code3hr. +.SH COPYRIGHT +Copyright \(co 2024-2026 code3hr. +.br +License: MIT diff --git a/debian/install b/debian/install new file mode 100644 index 00000000000..b08109c11c9 --- /dev/null +++ b/debian/install @@ -0,0 +1,4 @@ +packages/* usr/lib/cyxwiz/packages +docs/* usr/lib/cyxwiz/docs +package.json usr/lib/cyxwiz +README.md usr/share/doc/cyxwiz diff --git a/debian/postinst b/debian/postinst new file mode 100755 index 00000000000..a0fff82851b --- /dev/null +++ b/debian/postinst @@ -0,0 +1,76 @@ +#!/bin/bash +set -e + +case "$1" in + configure) + # Check if Bun is installed + if ! command -v bun &> /dev/null; then + echo "Installing Bun JavaScript runtime..." + curl -fsSL https://bun.sh/install | bash + + # Add bun to system PATH + if [ -f /root/.bun/bin/bun ]; then + ln -sf /root/.bun/bin/bun /usr/local/bin/bun + elif [ -f "$HOME/.bun/bin/bun" ]; then + ln -sf "$HOME/.bun/bin/bun" /usr/local/bin/bun + fi + fi + + # Install dependencies + echo "Installing Cyxwiz dependencies..." + cd /usr/lib/cyxwiz + bun install --production 2>/dev/null || true + + # Create cyxwiz executable wrapper + cat > /usr/bin/cyxwiz << 'WRAPPER' +#!/bin/bash +# Cyxwiz - AI-Powered Security Operations Platform + +CYXWIZ_HOME="/usr/lib/cyxwiz" + +# Ensure bun is in PATH +if [ -f "$HOME/.bun/bin/bun" ]; then + export PATH="$HOME/.bun/bin:$PATH" +elif [ -f "/root/.bun/bin/bun" ]; then + export PATH="/root/.bun/bin:$PATH" +fi + +# Check if bun is available +if ! command -v bun &> /dev/null; then + echo "Error: Bun runtime not found. Please install with:" + echo " curl -fsSL https://bun.sh/install | bash" + exit 1 +fi + +# Run Cyxwiz +exec bun run --cwd "$CYXWIZ_HOME/packages/opencode" src/index.ts "$@" +WRAPPER + + chmod +x /usr/bin/cyxwiz + + echo "" + echo "==============================================" + echo " Cyxwiz installed successfully!" + echo "==============================================" + echo "" + echo " Usage: cyxwiz" + echo "" + echo " Set your API key:" + echo " export ANTHROPIC_API_KEY=sk-ant-..." + echo " # or" + echo " export OPENAI_API_KEY=sk-..." + echo "" + echo " Documentation: /usr/share/doc/cyxwiz/" + echo "==============================================" + ;; + + abort-upgrade|abort-remove|abort-deconfigure) + ;; + + *) + echo "postinst called with unknown argument \`$1'" >&2 + exit 1 + ;; +esac + +exit 0 diff --git a/debian/postrm b/debian/postrm new file mode 100755 index 00000000000..dcf3ab25419 --- /dev/null +++ b/debian/postrm @@ -0,0 +1,21 @@ +#!/bin/bash +set -e + +case "$1" in + purge) + # Remove configuration and data + rm -rf /usr/lib/cyxwiz + rm -rf /var/lib/cyxwiz + rm -rf /var/log/cyxwiz + ;; + + remove|upgrade|failed-upgrade|abort-install|abort-upgrade|disappear) + ;; + + *) + echo "postrm called with unknown argument \`$1'" >&2 + exit 1 + ;; +esac + +exit 0 diff --git a/debian/prerm b/debian/prerm new file mode 100755 index 00000000000..eda48fa3179 --- /dev/null +++ b/debian/prerm @@ -0,0 +1,19 @@ +#!/bin/bash +set -e + +case "$1" in + remove|upgrade|deconfigure) + # Remove cyxwiz executable + rm -f /usr/bin/cyxwiz + ;; + + failed-upgrade) + ;; + + *) + echo "prerm called with unknown argument \`$1'" >&2 + exit 1 + ;; +esac + +exit 0 diff --git a/debian/rules b/debian/rules new file mode 100755 index 00000000000..ef52fce8be8 --- /dev/null +++ b/debian/rules @@ -0,0 +1,39 @@ +#!/usr/bin/make -f + +export DH_VERBOSE = 1 + +%: + dh $@ + +override_dh_auto_clean: + rm -rf node_modules + rm -rf packages/opencode/node_modules + rm -rf packages/opencode/dist + +override_dh_auto_build: + # Bun is installed via postinst if not present + @echo "Build will be performed during package installation" + +override_dh_auto_install: + # Create directory structure + mkdir -p debian/cyxwiz/usr/lib/cyxwiz + mkdir -p debian/cyxwiz/usr/bin + mkdir -p debian/cyxwiz/usr/share/doc/cyxwiz + mkdir -p debian/cyxwiz/usr/share/man/man1 + + # Copy source files + cp -r packages debian/cyxwiz/usr/lib/cyxwiz/ + cp -r docs debian/cyxwiz/usr/lib/cyxwiz/ + cp package.json debian/cyxwiz/usr/lib/cyxwiz/ + cp bun.lock debian/cyxwiz/usr/lib/cyxwiz/ 2>/dev/null || true + cp tsconfig.json debian/cyxwiz/usr/lib/cyxwiz/ 2>/dev/null || true + + # Copy documentation + cp README.md debian/cyxwiz/usr/share/doc/cyxwiz/ + cp LICENSE debian/cyxwiz/usr/share/doc/cyxwiz/ 2>/dev/null || true + + # Install man page + cp debian/cyxwiz.1 debian/cyxwiz/usr/share/man/man1/ + +override_dh_auto_test: + @echo "Skipping tests during package build" diff --git a/debian/source/format b/debian/source/format new file mode 100644 index 00000000000..89ae9db8f88 --- /dev/null +++ b/debian/source/format @@ -0,0 +1 @@ +3.0 (native) diff --git a/docs/CLAUDE.md b/docs/CLAUDE.md new file mode 100644 index 00000000000..8ee87449b12 --- /dev/null +++ b/docs/CLAUDE.md @@ -0,0 +1,346 @@ +# CLAUDE.md - Cyxwiz Project Context + +> This file contains essential context for AI assistants working on the Cyxwiz project. + +--- + +## What is Cyxwiz? + +Cyxwiz is a **multi-domain AI operations platform** for professionals who use command-line tools. It's being built by forking [OpenCode](https://github.com/anomalyco/opencode) (MIT licensed). + +**One-liner:** Speak intent, tools execute with governance, AI explains results - all auditable. + +--- + +## Core Concept + +Cyxwiz is NOT just another AI coding assistant. It's a **governed orchestration layer** for domain-specific tools. + +``` +Human Intent → LLM Translation → Governance Check → Tool Execution → Parsed Results → LLM Explanation +``` + +**Key differentiator:** Governance engine that enforces scope, requires approvals for dangerous commands, and creates audit trails. + +--- + +## Strategic Decisions Made + +| Decision | Choice | Rationale | +|----------|--------|-----------| +| Build vs Fork | Fork OpenCode | Get CLI/TUI/multi-LLM for free | +| Plugin vs Platform | Platform (own fork) | Full control, can grow unlimited | +| Language | TypeScript | Inherited from OpenCode | +| First domain | Pentest | Clear user (security consultants), clear tools | +| Target OS | Kali/Parrot Linux | 600+ tools pre-installed, zero friction | + +--- + +## Architecture Overview + +``` +┌─────────────────────────────────────────────────────────┐ +│ CYXWIZ PLATFORM │ +├─────────────────────────────────────────────────────────┤ +│ INHERITED (OpenCode): │ +│ CLI/TUI │ Multi-LLM │ Sessions │ Tool Exec │ Plugins │ +├─────────────────────────────────────────────────────────┤ +│ CYXWIZ CORE (we build): │ +│ Governance │ Scope Enforce │ Audit │ Findings │ Reports│ +├─────────────────────────────────────────────────────────┤ +│ DOMAIN AGENTS: │ +│ Pentest (MVP) │ SOC │ DevOps │ NetEng │ Community │ +└─────────────────────────────────────────────────────────┘ +``` + +--- + +## Tech Stack + +- **Language:** TypeScript (inherited from OpenCode) +- **Runtime:** Bun +- **State:** SQLite +- **LLM:** Multi-provider (Claude, GPT, Gemini, etc.) +- **Plugin System:** OpenCode plugins (extended) + +--- + +## Governance Engine (Core Feature) + +This is what makes Cyxwiz different from vanilla OpenCode or ChatGPT. + +**Before any command executes:** +1. **Scope Check** - Is target in allowed scope? +2. **Policy Check** - Is command auto-approved, needs approval, or blocked? +3. **Approval Flow** - Auto-execute or prompt user +4. **Audit Log** - Record everything regardless of outcome + +**Policy example:** +```typescript +{ + domain: "pentest", + autoApprove: ["nmap *", "nikto *", "ffuf *"], + requireApproval: ["metasploit *", "sqlmap --os-*"], + blocked: ["rm -rf *"] +} +``` + +--- + +## Target Users + +### MVP: Solo Security Consultant +- Does pentests, web app assessments +- Uses 5-15 tools per engagement +- Needs audit trail for reports +- Time = money + +### Future Domains: +- **SOC Analyst** - SIEM queries, threat intel, IOC checking +- **DevOps Engineer** - kubectl, terraform, ansible, cloud CLIs +- **Network Engineer** - Cisco/Juniper CLI, network scanners + +--- + +## Build Phases + +1. **Fork & Foundation** - Fork OpenCode, understand codebase +2. **Governance Engine** - Implement scope/policy/audit as core +3. **Pentest Agent MVP** - nmap + governance + findings +4. **Multi-Tool Pentest** - nikto, ffuf, nuclei, full workflow +5. **State & Reports** - Session persistence, exports +6. **Platform Polish** - Distribution, docs, community +7. **Multi-Domain** - SOC, DevOps, NetEng agents + +--- + +## Key Files + +- `docs/PROJECT.md` - Full project specification and roadmap +- `docs/CLAUDE.md` - This file (AI context) +- `docs/USAGE.md` - Development guide + +--- + +## Distribution Strategy + +**Primary target:** Kali Linux / Parrot OS + +These distros have 600+ security tools pre-installed. Cyxwiz becomes the intelligent orchestration layer: + +```bash +# On Kali, all tools ready +cyxwiz setup +> 47 tools detected. Cyxwiz is ready. + +cyxwiz pentest start --scope 10.0.0.0/24 +> scan for open ports +[APPROVED] Executing nmap... +``` + +**Goal:** Get Cyxwiz pre-installed in Kali/Parrot eventually. + +--- + +## What Cyxwiz Is NOT + +- Not building security tools (orchestrates existing ones) +- Not autonomous (human-in-the-loop always) +- Not a general AI assistant (domain-specific) +- Not a plugin on someone else's platform (we own it) + +--- + +## Code Style & Principles + +When contributing to Cyxwiz: + +1. **Governance is core** - Never bypass scope/policy checks +2. **Audit everything** - Every command attempt gets logged +3. **Parsers over LLM** - Use structured parsers for tool output, not LLM +4. **Human decides** - LLM suggests, human approves dangerous actions +5. **Domain-specific** - Each agent deeply understands its tools + +--- + +## Common Commands (When Built) + +```bash +# Start pentest engagement +cyxwiz pentest start --scope 10.0.0.0/24 --exclude 10.0.0.1 + +# Natural language interaction +> scan for open ports +> check web services for vulnerabilities +> generate report + +# View findings +cyxwiz findings list +cyxwiz findings export --format markdown + +# Check audit log +cyxwiz audit show +``` + +--- + +## OpenCode References + +Since Cyxwiz forks OpenCode, understand these: + +- [OpenCode GitHub](https://github.com/anomalyco/opencode) +- [OpenCode Docs](https://opencode.ai/docs/) +- [Agents](https://opencode.ai/docs/agents/) +- [Plugins](https://opencode.ai/docs/plugins/) +- [Custom Tools](https://opencode.ai/docs/custom-tools/) + +Key OpenCode concepts: +- **Agents** - Specialized AI assistants (we add domain agents) +- **Plugins** - Hook system with `tool.execute.before/after` +- **Tools** - TypeScript functions LLM can invoke +- **MCP** - Model Context Protocol for external integrations + +--- + +## Current Status + +**Phase:** Phase 16 Complete - Post-Exploitation Framework + +**Completed Phases:** + +| Phase | Module | Status | +|-------|--------|--------| +| 1-5 | Core Pentest Module | ✅ Complete | +| 6 | Parser Extensions (nikto, nuclei, gobuster, ffuf, sslscan) | ✅ Complete | +| 7 | Report Generation | ✅ Complete | +| 8 | Continuous Monitoring | ✅ Complete | +| 8b | Exploit Integration | ✅ Complete | +| 8c | Web Scanner | ✅ Complete | +| 9 | API Security Scanner | ✅ Complete | +| 10 | Network Infrastructure Scanner (AD, SMB, DNS, SNMP, LDAP) | ✅ Complete | +| 11 | Cloud Security Scanner (AWS, Azure, GCP) | ✅ Complete | +| 12 | Container Security Scanner + CVE Lookup | ✅ Complete | +| 13 | Mobile Application Scanner (Android/iOS) | ✅ Complete | +| 14 | Wireless Network Scanner (WiFi, Bluetooth, RFID) | ✅ Complete | +| 15 | Social Engineering Toolkit | ✅ Complete | +| 16 | Post-Exploitation Framework | ✅ Complete | + +**Pending Phases:** +- Phase 17: Reporting Dashboard (web-based interface) +- Phase 18: CI/CD Security Integration + +**Pentest Tools Available:** +- `nmap` - Network scanning with XML parsing +- `sectools` - 30+ security tool wrappers +- `report` - Security assessment reports (MD, HTML, JSON) +- `monitor` - Scheduled scans with diff detection +- `exploit` - Exploit matching and execution +- `webscan` - Web application security scanner +- `apiscan` - API security testing (OpenAPI, GraphQL) +- `netscan` - Network infrastructure (AD, SMB, DNS, SNMP, LDAP) +- `cloudscan` - Cloud security (AWS, Azure, GCP, compliance) +- `cve` - CVE lookup (NVD, OSV, CISA KEV) +- `containerscan` - Container/K8s security (Trivy, Grype) +- `mobilescan` - Mobile app security (Android APK, iOS IPA) +- `wirelessscan` - Wireless security (WiFi, Bluetooth, RFID/NFC) +- `soceng` - Social engineering toolkit +- `postexploit` - Post-exploitation framework + +**How to run (dev mode):** +```bash +export PATH="$HOME/.bun/bin:$PATH" +cd /home/mrcj/Desktop/wiz +bun run --cwd packages/opencode src/index.ts +``` + +--- + +## Codebase Structure (Key Findings) + +``` +/home/mrcj/Desktop/wiz/ +├── README.md # Cyxwiz README +├── docs/ +│ ├── PROJECT.md # Full specification +│ ├── CLAUDE.md # This file +│ ├── TODO.md # Development phases +│ ├── PHASE3-16.md # Phase documentation +│ └── PENTEST.md # Pentest module guide +├── packages/ +│ ├── opencode/src/ # Core CLI/TUI +│ │ ├── tool/ # Tool definitions +│ │ │ ├── tool.ts # Base tool definition +│ │ │ ├── bash.ts # Bash execution +│ │ │ ├── registry.ts # Tool registry (includes all pentest tools) +│ │ │ └── ... +│ │ ├── pentest/ # Pentest module (CYXWIZ CORE) +│ │ │ ├── types.ts # Core type definitions +│ │ │ ├── findings.ts # Security findings storage +│ │ │ ├── nmap-parser.ts # Nmap XML parsing +│ │ │ ├── nmap-tool.ts # Nmap tool +│ │ │ ├── sectools.ts # 30+ security tool wrappers +│ │ │ ├── parsers/ # Tool output parsers +│ │ │ ├── reports/ # Report generation +│ │ │ ├── monitoring/ # Continuous monitoring +│ │ │ ├── exploits/ # Exploit integration +│ │ │ ├── webscan/ # Web application scanner +│ │ │ ├── apiscan/ # API security scanner +│ │ │ ├── netscan/ # Network infrastructure (AD, SMB, DNS) +│ │ │ ├── cloudscan/ # Cloud security (AWS, Azure, GCP) +│ │ │ ├── cve/ # CVE lookup service +│ │ │ ├── containerscan/ # Container/K8s security +│ │ │ ├── mobilescan/ # Mobile app security +│ │ │ ├── wirelessscan/ # Wireless security +│ │ │ ├── soceng/ # Social engineering toolkit +│ │ │ └── postexploit/ # Post-exploitation framework +│ │ ├── plugin/ # Plugin loader +│ │ ├── permission/ # Permission system +│ │ ├── agent/ # Agent definitions +│ │ ├── session/ # Session management +│ │ └── config/ # Configuration +│ ├── plugin/ # Plugin SDK +│ │ └── src/index.ts # Hook definitions +│ └── sdk/ # Client SDK +└── [OpenCode config files] +``` + +## Governance Injection Points + +**Primary hook (packages/plugin/src/index.ts lines 176-187):** + +```typescript +"tool.execute.before"?: ( + input: { tool: string; sessionID: string; callID: string }, + output: { args: any }, +) => Promise + +"tool.execute.after"?: ( + input: { tool: string; sessionID: string; callID: string }, + output: { title: string; output: string; metadata: any }, +) => Promise +``` + +**Strategy:** +1. `tool.execute.before` → Check scope, check policy, require approval +2. `tool.execute.after` → Audit log, parse output, store findings + +--- + +## Mentor Mode + +The user has requested a "ruthless mentor" approach: +- Don't sugarcoat feedback +- Stress test all ideas before building +- Call out weak thinking directly +- Validate that we're solving real problems +- No vanity features - ship what matters + +--- + +## Questions to Ask Before Building Features + +1. Does this go through governance? (It should) +2. Is this audited? (It should be) +3. Does this serve the target user's workflow? +4. Is this the simplest solution? +5. Are we building platform or just tool? diff --git a/docs/COMPARISON.md b/docs/COMPARISON.md new file mode 100644 index 00000000000..990b00b5dfa --- /dev/null +++ b/docs/COMPARISON.md @@ -0,0 +1,264 @@ +# Cyxwiz vs Other Solutions + +How Cyxwiz compares to existing security tools and platforms, what makes it different, and what we're NOT trying to do. + +--- + +## Quick Comparison Matrix + +| Feature | Cyxwiz | Metasploit | Faraday | Cobalt Strike | Pentest GPT | Manual CLI | +|---------|-----|------------|---------|---------------|-------------|------------| +| Natural language interface | Yes | No | No | No | Yes | No | +| Tool orchestration | Yes | Partial | No | Yes | No | Manual | +| Governance/approval | Yes | No | No | No | No | No | +| Scope enforcement | Yes | No | No | No | No | No | +| Audit logging | Yes | Partial | Yes | Yes | No | Manual | +| Findings management | Yes | Partial | Yes | Yes | No | Manual | +| Report generation | Yes | Yes | Yes | Yes | No | Manual | +| Multi-tool support | 30+ | MSF only | Import | CS only | Advice only | Any | +| Open source | Yes | Yes | Yes | No | No | N/A | +| Offline capable | Yes | Yes | Yes | Yes | No | Yes | + +--- + +## Detailed Comparisons + +### vs Metasploit Framework + +**What Metasploit is:** The industry-standard exploitation framework with modules for scanning, exploitation, and post-exploitation. + +**How Cyxwiz is different:** +- Metasploit focuses on exploitation; Cyxwiz orchestrates reconnaissance through reporting +- Metasploit has its own module ecosystem; Cyxwiz leverages existing CLI tools (nmap, nikto, etc.) +- Metasploit requires learning MSF syntax; Cyxwiz uses natural language +- Cyxwiz has governance/scope enforcement; Metasploit does not + +**When to use Metasploit:** Deep exploitation, payload generation, post-exploitation +**When to use Cyxwiz:** Orchestrated assessments, compliance-focused testing, team environments + +--- + +### vs Faraday + +**What Faraday is:** Collaborative penetration testing and vulnerability management platform. + +**How Cyxwiz is different:** +- Faraday is a web-based collaboration platform; Cyxwiz is a CLI-first tool +- Faraday imports results from tools; Cyxwiz executes and orchestrates tools +- Faraday focuses on team collaboration; Cyxwiz focuses on individual productivity with AI +- Cyxwiz has natural language interface; Faraday uses traditional UI + +**When to use Faraday:** Team collaboration, vulnerability tracking, client reporting +**When to use Cyxwiz:** Solo assessments, rapid testing, learning, AI-assisted analysis + +--- + +### vs Cobalt Strike + +**What Cobalt Strike is:** Commercial adversary simulation and red team operations platform. + +**How Cyxwiz is different:** +- Cobalt Strike is for red team operations; Cyxwiz is for penetration testing +- Cobalt Strike focuses on stealth and persistence; Cyxwiz focuses on assessment +- Cobalt Strike is commercial ($5,900/year); Cyxwiz is open source (free) +- Cyxwiz has scope enforcement to prevent accidents; Cobalt Strike assumes operator expertise + +**When to use Cobalt Strike:** Red team engagements, adversary emulation, APT simulation +**When to use Cyxwiz:** Penetration testing, security assessments, compliance testing + +--- + +### vs PentestGPT / AI Chatbots + +**What PentestGPT is:** ChatGPT-based assistant that provides penetration testing guidance. + +**How Cyxwiz is different:** +- PentestGPT gives advice; Cyxwiz executes tools +- PentestGPT runs in browser; Cyxwiz runs locally on your machine +- PentestGPT can't see your environment; Cyxwiz operates within it +- Cyxwiz has governance and audit; PentestGPT is just a conversation +- Cyxwiz works offline with local LLMs; PentestGPT requires internet + +**When to use PentestGPT:** Learning, brainstorming, methodology questions +**When to use Cyxwiz:** Actual testing, tool execution, documented assessments + +--- + +### vs Manual CLI Usage + +**What manual CLI is:** Running nmap, nikto, sqlmap, etc. directly in terminal. + +**How Cyxwiz is different:** +- Manual requires memorizing syntax; Cyxwiz uses natural language +- Manual requires copy/paste between tools; Cyxwiz orchestrates automatically +- Manual has no built-in audit trail; Cyxwiz logs everything +- Manual has no scope enforcement; Cyxwiz prevents out-of-scope testing +- Manual findings are scattered; Cyxwiz centralizes and structures them + +**When to use manual CLI:** Quick one-off commands, custom scripts, learning tools +**When to use Cyxwiz:** Full assessments, compliance work, repeatable testing + +--- + +### vs Automation Frameworks (Ansible/Python Scripts) + +**What automation frameworks are:** Custom scripts or playbooks that automate security testing. + +**How Cyxwiz is different:** +- Automation requires writing code; Cyxwiz uses natural language +- Automation is rigid (follows scripts); Cyxwiz adapts via AI +- Automation requires maintenance; Cyxwiz leverages existing tools +- Cyxwiz provides governance layer; scripts run without guardrails + +**When to use automation:** Highly repeatable tasks, CI/CD integration, custom workflows +**When to use Cyxwiz:** Ad-hoc testing, varied engagements, interactive assessments + +--- + +## What Makes Cyxwiz Unique + +### 1. Natural Language Orchestration +No other tool lets you say "scan this network for web vulnerabilities and check for SQL injection" and have it orchestrate nmap, nikto, and sqlmap automatically. + +### 2. Governance First +Built-in policy engine that evaluates every action before execution. Define what's allowed, what needs approval, and what's blocked. Essential for compliance. + +### 3. Scope Enforcement +Accidentally scanning a production server or out-of-scope IP can end careers and contracts. Cyxwiz enforces scope at the platform level. + +### 4. Tool Agnostic +Not locked into one ecosystem. Cyxwiz orchestrates whatever tools you have installed - the same tools you already know and trust. + +### 5. Audit Trail by Default +Every command, every approval, every result - automatically logged. Export for compliance without extra effort. + +### 6. AI-Powered Analysis +Not just execution, but explanation. Cyxwiz helps interpret results, suggest next steps, and identify what matters. + +--- + +## What Cyxwiz is NOT + +### NOT a Replacement for Expertise + +Cyxwiz is a force multiplier, not a replacement for security knowledge. It helps experts work faster, not turn novices into experts overnight. + +- You still need to understand what the tools do +- You still need to interpret findings correctly +- You still need to make judgment calls +- AI suggestions are starting points, not final answers + +### NOT an Exploitation Framework + +Cyxwiz focuses on assessment, not exploitation: + +- No payload generation +- No C2 infrastructure +- No persistence mechanisms +- No evasion techniques + +For exploitation, use Metasploit, Cobalt Strike, or dedicated tools. + +### NOT a Vulnerability Scanner + +Cyxwiz orchestrates scanners but isn't one itself: + +- No custom vulnerability signatures +- No authenticated scanning logic +- No compliance check libraries + +For dedicated scanning, use Nessus, Qualys, or OpenVAS. + +### NOT a SIEM/SOC Platform + +Cyxwiz is for offensive testing, not defensive monitoring: + +- No log ingestion +- No alert correlation +- No incident response workflows + +For SOC operations, use Splunk, Elastic, or similar. + +### NOT Trying to Replace All Tools + +Cyxwiz orchestrates tools, not replaces them: + +- nmap is still nmap +- nikto is still nikto +- You can always drop to raw CLI + +We complement your toolkit, not compete with it. + +### NOT for Malicious Use + +Cyxwiz includes governance specifically to prevent misuse: + +- Scope enforcement blocks unauthorized targets +- Audit logging creates accountability +- Designed for authorized testing only + +--- + +## Target Users + +### Ideal Users + +- **Penetration testers** who want to work faster with AI assistance +- **Security consultants** who need documented, compliant assessments +- **Red team members** (reconnaissance phase) who need orchestration +- **Security engineers** learning offensive techniques +- **Bug bounty hunters** working within defined scopes + +### Not Ideal For + +- Script kiddies looking for push-button hacking +- Malicious actors (governance will frustrate you) +- Those who need deep exploitation capabilities +- Users who prefer GUI-only interfaces + +--- + +## Integration Philosophy + +Cyxwiz is designed to integrate, not isolate: + +``` +┌─────────────────────────────────────────────────────────────┐ +│ Your Workflow │ +├─────────────────────────────────────────────────────────────┤ +│ │ +│ ┌─────────┐ ┌─────────┐ ┌─────────────┐ │ +│ │ Cyxwiz │────▶│ Tools │────▶│ Faraday/ │ │ +│ │ (AI │ │ (nmap, │ │ Jira/etc │ │ +│ │ Orch) │ │ nikto) │ │ (collab) │ │ +│ └─────────┘ └─────────┘ └─────────────┘ │ +│ │ │ │ +│ ▼ ▼ │ +│ ┌─────────────────────────────────────────────┐ │ +│ │ Reports / Audit Logs │ │ +│ └─────────────────────────────────────────────┘ │ +│ │ +└─────────────────────────────────────────────────────────────┘ +``` + +- Use Cyxwiz for orchestration and execution +- Export findings to Faraday/Dradis for collaboration +- Generate reports for clients +- Integrate with ticketing systems + +--- + +## Summary + +| If you need... | Use... | +|----------------|--------| +| AI-orchestrated pentesting | **Cyxwiz** | +| Deep exploitation | Metasploit | +| Team collaboration | Faraday | +| Red team operations | Cobalt Strike | +| Learning/advice | PentestGPT | +| Vulnerability scanning | Nessus/OpenVAS | +| Custom automation | Ansible/Python | +| Quick one-off commands | Direct CLI | + +**Cyxwiz fills the gap between "I know what I want to do" and "now I have to remember 50 different tool syntaxes and manually track everything."** diff --git a/docs/DISTRIBUTION.md b/docs/DISTRIBUTION.md new file mode 100644 index 00000000000..6669c2630b5 --- /dev/null +++ b/docs/DISTRIBUTION.md @@ -0,0 +1,299 @@ +# Distribution Channels: Kali Linux & Parrot OS + +This document outlines the strategy for distributing Cyxwiz through the official Kali Linux and Parrot OS repositories. + +--- + +## Overview + +Both Kali Linux and Parrot OS use Debian-based packaging (.deb). To get Cyxwiz included in their official repositories, we need to: + +1. Create a proper Debian package +2. Meet their tool criteria +3. Submit through their official channels + +--- + +## Kali Linux Distribution + +### Official Documentation +- [Submitting Tools to Kali](https://www.kali.org/docs/tools/submitting-tools/) +- [Intro to Packaging](https://www.kali.org/docs/development/intro-to-packaging-example/) +- [Bug Tracker](https://bugs.kali.org/) + +### Requirements Checklist + +| Requirement | Status | Notes | +|-------------|--------|-------| +| `debian/` directory | DONE | Complete packaging created | +| Tagged release | DONE | v1.1.0 released | +| Clear license | DONE | MIT License | +| Homepage | DONE | GitHub repo | +| Documentation | DONE | README, docs/ | +| Dependencies listed | DONE | In debian/control | +| Installation instructions | DONE | In README | +| Usage examples | DONE | In README | +| Active development | DONE | Regular commits | +| Not duplicate of existing tool | DONE | Unique AI orchestration approach | +| Man page | DONE | debian/cyxwiz.1 | + +### Submission Information + +When submitting to Kali's bug tracker, we need: + +``` +Category: New Tool Requests +Severity: Minor +Priority: Normal + +Name: cyxwiz +Version: 1.0.0 (use tagged release) +Homepage: https://github.com/code3hr/opencode +Author: code3hr +License: MIT + +Description: +AI-powered security operations platform. Orchestrates 30+ security tools +through natural language. Features governance engine, scope enforcement, +audit logging, and structured findings management. + +Dependencies: +- bun (JavaScript runtime) +- nmap, nikto, nuclei, etc. (security tools - already in Kali) + +Similar Tools: +- None directly comparable (unique AI orchestration approach) +- Partially overlaps with: metasploit (automation), faraday (findings) + +Installation: +bun install && bun run build + +Usage: +$ cyxwiz +> scan 192.168.1.0/24 for vulnerabilities +``` + +### Kali Metapackage Target + +Cyxwiz should be included in: +- `kali-tools-top10` - Core tools +- `kali-tools-automation` - Automation category + +--- + +## Parrot OS Distribution + +### Official Documentation +- [Community Contributions](https://parrotsec.org/docs/introduction/community-contributions/) +- [GitLab Repository](https://gitlab.com/parrotsec) +- Contact: team@parrotsec.org + +### Requirements Checklist + +| Requirement | Status | Notes | +|-------------|--------|-------| +| GitLab account | TODO | Create account | +| Debian packaging | DONE | debian/ directory created | +| Debian standards compliance | DONE | Follows Debian policy | +| Email submission | DONE | Sent to team@parrotsec.org | +| Fork on personal repo | PENDING | Awaiting team response | +| Merge request | PENDING | Awaiting team response | + +### Submission Process + +1. **Email team@parrotsec.org** with: + - Project name: Cyxwiz + - Description: AI-powered security operations platform + - Sub-project: Security tools + - Contribution type: New tool package + +2. **Create GitLab fork** and prepare Debian package + +3. **Submit merge request** for review + +--- + +## Debian Packaging Requirements + +Both distributions require proper Debian packaging. Here's what we need: + +### Directory Structure (Implemented) + +``` +cyxwiz/ +├── debian/ +│ ├── changelog # Version history (1.0.0-1) +│ ├── compat # Debhelper compatibility (13) +│ ├── control # Package metadata +│ ├── copyright # MIT license information +│ ├── rules # Build instructions +│ ├── install # File installation paths +│ ├── postinst # Post-install script (Bun setup) +│ ├── prerm # Pre-removal script +│ ├── postrm # Post-removal script +│ ├── cyxwiz.1 # Man page +│ └── source/ +│ └── format # Source format (3.0 native) +├── packages/ +└── ... +``` + +### debian/control + +``` +Source: cyxwiz +Section: utils +Priority: optional +Maintainer: code3hr +Build-Depends: debhelper (>= 11) +Standards-Version: 4.5.0 +Homepage: https://github.com/code3hr/opencode + +Package: cyxwiz +Architecture: all +Depends: ${misc:Depends}, bun +Recommends: nmap, nikto, nuclei, gobuster, ffuf, sqlmap, + smbclient, ldap-utils, snmp, dnsutils +Description: AI-powered security operations platform + Cyxwiz is an AI-powered operations platform for security professionals. + It orchestrates 30+ security tools through natural language commands, + with governance, scope enforcement, and audit logging. + . + Features: + - Natural language tool orchestration + - Governance engine with policy-based approval + - Scope enforcement for authorized targets + - Comprehensive audit logging + - Structured findings management + - Professional report generation +``` + +### debian/rules + +```makefile +#!/usr/bin/make -f + +%: + dh $@ + +override_dh_auto_build: + bun install + bun run build + +override_dh_auto_install: + mkdir -p debian/cyxwiz/usr/lib/cyxwiz + cp -r dist/* debian/cyxwiz/usr/lib/cyxwiz/ + mkdir -p debian/cyxwiz/usr/bin + ln -s /usr/lib/cyxwiz/cyxwiz debian/cyxwiz/usr/bin/cyxwiz +``` + +--- + +## Action Items + +### Phase 1: Prepare Package (Priority: High) + +- [x] Create `debian/` directory with all required files +- [x] Write man page for cyxwiz +- [x] Create tagged release (v1.1.0) +- [x] Test package build locally +- [ ] Test installation on clean Kali VM +- [ ] Test installation on clean Parrot VM + +### Phase 2: Submit to Kali (Priority: High) + +- [x] Create account on bugs.kali.org +- [x] Submit new tool request (January 2026) +- [ ] Respond to reviewer feedback +- [ ] Iterate on packaging if needed + +### Phase 3: Submit to Parrot (Priority: High) + +- [ ] Create GitLab account +- [x] Email team@parrotsec.org (January 2026) +- [ ] Fork and prepare package +- [ ] Submit merge request +- [ ] Respond to reviewer feedback + +### Phase 4: Ongoing Maintenance + +- [ ] Monitor for security updates +- [ ] Update packages with new releases +- [ ] Respond to user issues +- [ ] Engage with community + +--- + +## Alternative Distribution Methods + +While working on official inclusion, we can also distribute via: + +### 1. Direct .deb Download + +Host .deb packages on GitHub releases for manual installation: + +```bash +wget https://github.com/code3hr/opencode/releases/download/v1.1.0/cyxwiz_1.1.0-1_all.deb +sudo dpkg -i cyxwiz_1.1.0-1_all.deb +sudo apt-get install -f # Install dependencies +``` + +### 2. APT Repository + +Host our own APT repository: + +```bash +# Add repository +echo "deb https://apt.cyxwiz.dev stable main" | sudo tee /etc/apt/sources.list.d/cyxwiz.list +wget -qO - https://apt.cyxwiz.dev/key.gpg | sudo apt-key add - + +# Install +sudo apt update +sudo apt install cyxwiz +``` + +### 3. Installation Script + +One-liner installation (current method): + +```bash +curl -fsSL https://cyxwiz.dev/install.sh | bash +``` + +### 4. Homebrew (for macOS users) + +```bash +brew tap code3hr/cyxwiz +brew install cyxwiz +``` + +--- + +## Timeline Estimate + +| Phase | Status | +|-------|--------| +| Debian packaging | COMPLETE | +| Kali submission | SUBMITTED (Jan 2026) | +| Kali review process | PENDING (2-4 weeks) | +| Parrot submission | SUBMITTED (Jan 2026) | +| Parrot review | PENDING (2-4 weeks) | +| Official inclusion | 1-3 months total | + +--- + +## Resources + +- [Debian Policy Manual](https://www.debian.org/doc/debian-policy/) +- [Debian New Maintainers' Guide](https://www.debian.org/doc/manuals/maint-guide/) +- [Kali Public Packaging](https://www.kali.org/docs/development/public-packaging/) +- [Lintian - Debian Package Checker](https://lintian.debian.org/) + +--- + +## Sources + +- [Kali Linux - Submitting Tools](https://www.kali.org/docs/tools/submitting-tools/) +- [Parrot OS - Community Contributions](https://parrotsec.org/docs/introduction/community-contributions/) +- [Kali Linux Bug Tracker](https://bugs.kali.org/) +- [Parrot GitLab](https://gitlab.com/parrotsec) diff --git a/docs/GOVERNANCE.md b/docs/GOVERNANCE.md new file mode 100644 index 00000000000..a0eea9f79e6 --- /dev/null +++ b/docs/GOVERNANCE.md @@ -0,0 +1,670 @@ +# Governance Engine Documentation + +The Governance Engine provides centralized control over AI tool executions in cyxwiz. It enforces scope restrictions, evaluates policy-based rules, and maintains comprehensive audit logs for all tool operations. + +--- + +## Table of Contents + +- [Overview](#overview) +- [Quick Start](#quick-start) +- [Architecture](#architecture) +- [Configuration Reference](#configuration-reference) +- [Module Reference](#module-reference) +- [Usage Examples](#usage-examples) +- [Integration Guide](#integration-guide) +- [Troubleshooting](#troubleshooting) + +--- + +## Overview + +### What is the Governance Engine? + +The Governance Engine is a security layer that intercepts all tool executions before they run. It provides: + +- **Scope Enforcement**: Restrict which IPs and domains tools can access +- **Policy Rules**: Define what actions to take for specific tools/commands +- **Audit Logging**: Complete audit trail of all tool executions +- **Real-time Events**: Bus events for monitoring and alerting + +### When to Use Governance + +Enable governance when you need to: + +- Restrict AI access to internal networks only +- Block access to production systems +- Auto-approve safe, read-only operations +- Maintain compliance audit trails +- Monitor tool usage patterns + +--- + +## Quick Start + +### 1. Enable Governance + +Add to your `opencode.jsonc` or project config: + +```jsonc +{ + "governance": { + "enabled": true, + "default_action": "require-approval" + } +} +``` + +### 2. Add Scope Restrictions + +Limit which networks the AI can access: + +```jsonc +{ + "governance": { + "enabled": true, + "scope": { + "ip": { + "allow": ["10.0.0.0/8", "192.168.0.0/16"] + }, + "domain": { + "allow": ["*.company.com", "github.com"], + "deny": ["*.prod.company.com"] + } + } + } +} +``` + +### 3. Add Policy Rules + +Define actions for specific tools: + +```jsonc +{ + "governance": { + "enabled": true, + "policies": [ + { + "description": "Auto-approve read-only tools", + "action": "auto-approve", + "tools": ["read", "glob", "grep"] + }, + { + "description": "Block dangerous commands", + "action": "blocked", + "tools": ["bash"], + "commands": ["rm -rf *", "sudo *"] + } + ], + "default_action": "require-approval" + } +} +``` + +--- + +## Architecture + +### Execution Flow + +``` +┌─────────────────────────────────────────────────────────────────┐ +│ Tool Execution Request │ +│ (bash, read, webfetch, etc.) │ +└─────────────────────────────────────────────────────────────────┘ + │ + ▼ +┌─────────────────────────────────────────────────────────────────┐ +│ 1. Target Extraction │ +│ Analyze tool arguments for IPs, domains, URLs │ +└─────────────────────────────────────────────────────────────────┘ + │ + ▼ +┌─────────────────────────────────────────────────────────────────┐ +│ 2. Scope Check │ +│ Verify targets against allow/deny lists │ +│ │ +│ ┌─────────────┐ ┌─────────────┐ │ +│ │ IP/CIDR │ │ Domain │ │ +│ │ Matching │ │ Wildcards │ │ +│ └─────────────┘ └─────────────┘ │ +└─────────────────────────────────────────────────────────────────┘ + │ + ┌───────────┴───────────┐ + │ │ + Scope Passed Scope Failed + │ │ + ▼ ▼ +┌───────────────────────────┐ ┌───────────────────────┐ +│ 3. Policy Evaluation │ │ DENIED │ +│ Match against rules │ │ (Scope Violation) │ +│ First match wins │ └───────────────────────┘ +└───────────────────────────┘ + │ + ┌───────────┼───────────┐ + │ │ │ + ▼ ▼ ▼ +┌───────────┐ ┌───────────┐ ┌───────────┐ +│ auto- │ │ require- │ │ blocked │ +│ approve │ │ approval │ │ │ +└───────────┘ └───────────┘ └───────────┘ + │ │ │ + ▼ ▼ ▼ + Execute Ask User DENIED + Directly Permission (Policy) + │ + ▼ +┌─────────────────────────────────────────────────────────────────┐ +│ 4. Audit Logging │ +│ Record outcome, publish bus events │ +└─────────────────────────────────────────────────────────────────┘ +``` + +### Module Structure + +``` +src/governance/ +├── index.ts # Main entry point, orchestration +├── types.ts # Zod schemas, TypeScript types +├── matcher.ts # Target extraction and pattern matching +├── scope.ts # IP/domain scope enforcement +├── policy.ts # Policy rule evaluation +└── audit.ts # Audit logging and events +``` + +--- + +## Configuration Reference + +### Full Schema + +```typescript +interface GovernanceConfig { + // Master switch - governance is disabled by default + enabled?: boolean // default: false + + // Network scope restrictions + scope?: { + ip?: { + allow?: string[] // CIDR patterns: ["10.0.0.0/8"] + deny?: string[] // Deny takes precedence + } + domain?: { + allow?: string[] // Wildcards: ["*.company.com"] + deny?: string[] // Deny takes precedence + } + } + + // Policy rules (evaluated in order, first match wins) + policies?: Array<{ + action: "auto-approve" | "require-approval" | "blocked" + tools?: string[] // Tool name patterns + commands?: string[] // Bash command patterns + targets?: string[] // Network target patterns + description?: string // For logs and auditing + }> + + // Action when no policy matches + default_action?: "auto-approve" | "require-approval" | "blocked" + // default: "require-approval" + + // Audit logging configuration + audit?: { + enabled?: boolean // default: true + storage?: "file" | "memory" // default: "file" + retention?: number // Days to keep logs + include_args?: boolean // Log tool arguments (privacy) + } +} +``` + +### Configuration Options + +#### `enabled` +- **Type**: `boolean` +- **Default**: `false` +- **Description**: Master switch for governance. Must be explicitly set to `true`. + +#### `scope.ip.allow` / `scope.ip.deny` +- **Type**: `string[]` +- **Format**: CIDR notation (`10.0.0.0/8`, `192.168.1.0/24`) +- **Description**: IP address restrictions. Deny rules are checked first. + +#### `scope.domain.allow` / `scope.domain.deny` +- **Type**: `string[]` +- **Format**: Wildcard patterns (`*.example.com`, `api.github.com`) +- **Description**: Domain restrictions. Deny rules are checked first. + +#### `policies[].action` +- **Type**: `"auto-approve" | "require-approval" | "blocked"` +- **Description**: + - `auto-approve`: Execute without user confirmation + - `require-approval`: Ask user for permission (existing behavior) + - `blocked`: Deny execution entirely + +#### `policies[].tools` +- **Type**: `string[]` +- **Format**: Wildcard patterns (`bash`, `read`, `mcp_*`) +- **Description**: Match tool names + +#### `policies[].commands` +- **Type**: `string[]` +- **Format**: Wildcard patterns (`ssh *`, `curl *`, `rm -rf *`) +- **Description**: Match bash command strings (only applies when tool is `bash`) + +#### `policies[].targets` +- **Type**: `string[]` +- **Format**: CIDR or wildcard patterns +- **Description**: Match extracted network targets + +#### `default_action` +- **Type**: `"auto-approve" | "require-approval" | "blocked"` +- **Default**: `"require-approval"` +- **Description**: Action when no policy matches + +#### `audit.storage` +- **Type**: `"file" | "memory"` +- **Default**: `"file"` +- **Description**: Where to store audit entries + +#### `audit.include_args` +- **Type**: `boolean` +- **Default**: `false` +- **Description**: Include tool arguments in audit logs (may contain sensitive data) + +--- + +## Module Reference + +### Types (`types.ts`) + +Core type definitions using Zod schemas. + +| Type | Description | +|------|-------------| +| `Outcome` | `"allowed"` \| `"denied"` \| `"pending-approval"` \| `"error"` | +| `TargetType` | `"ip"` \| `"cidr"` \| `"domain"` \| `"url"` \| `"unknown"` | +| `Target` | `{ raw: string, type: TargetType, normalized: string }` | +| `AuditEntry` | Complete audit record with id, timestamp, tool, outcome, etc. | +| `CheckRequest` | Input to `Governance.check()` | +| `CheckResult` | Output from `Governance.check()` | + +**Bus Events:** +- `governance.checked` - Published after every governance check +- `governance.policy_violation` - Published when a tool is denied + +### Matcher (`matcher.ts`) + +Target extraction and pattern matching utilities. + +| Function | Description | +|----------|-------------| +| `classifyTarget(raw)` | Classify string as IP, CIDR, domain, URL, or unknown | +| `extractTargets(tool, args)` | Extract network targets from tool arguments | +| `ipInCidr(ip, cidr)` | Check if IP falls within CIDR range | +| `matchTarget(target, pattern)` | Match target against pattern | + +**Tool-specific extraction:** +- `bash`: Analyzes command for URLs, IPs, SSH patterns (`user@host`), and common tools (curl, wget, ssh, etc.) +- `webfetch`: Extracts the `url` argument directly +- `websearch`: No network targets (search queries) +- Other tools: Scans all string argument values + +### Scope (`scope.ts`) + +Network scope enforcement. + +| Function | Description | +|----------|-------------| +| `check(targets, scope)` | Validate all targets against scope configuration | + +**Evaluation order:** +1. Check deny list first - if matches, immediately deny +2. Check allow list - if exists and doesn't match, deny +3. Default to allow + +### Policy (`policy.ts`) + +Policy rule evaluation. + +| Function | Description | +|----------|-------------| +| `evaluate(tool, args, targets, policies, defaultAction)` | Evaluate policies, return action | +| `describe(policy)` | Get human-readable policy description | + +**Matching rules (AND logic):** +- `tools`: Tool name must match at least one pattern +- `commands`: Bash command must match at least one pattern +- `targets`: At least one target must match at least one pattern + +**First match wins** - policy order matters! + +### Audit (`audit.ts`) + +Audit logging and querying. + +| Function | Description | +|----------|-------------| +| `record(entry, config)` | Record an audit entry | +| `list(config, options)` | Query audit entries with filters | +| `get(id)` | Get single audit entry by ID | +| `clearMemory()` | Clear in-memory buffer (testing) | +| `memoryCount()` | Get count of entries in memory | + +### Main (`index.ts`) + +Main entry point and orchestration. + +| Export | Description | +|--------|-------------| +| `Governance.check(request, config)` | Main governance check function | +| `Governance.isEnabled(config)` | Check if governance is enabled | +| `Governance.DeniedError` | Error thrown when tool is blocked | +| `Governance.Types` | Re-export of types namespace | +| `Governance.Scope` | Re-export of scope namespace | +| `Governance.Policy` | Re-export of policy namespace | +| `Governance.Audit` | Re-export of audit namespace | +| `Governance.Matcher` | Re-export of matcher namespace | + +--- + +## Usage Examples + +### Basic Governance Check + +```typescript +import { Governance } from "./governance" +import { Config } from "./config/config" + +const config = await Config.get() + +const result = await Governance.check( + { + sessionID: "session_abc", + callID: "call_123", + tool: "bash", + args: { command: "curl https://api.example.com/data" } + }, + config.governance +) + +if (!result.allowed) { + console.log(`Blocked: ${result.reason}`) + console.log(`Policy: ${result.matchedPolicy}`) +} +``` + +### Subscribe to Governance Events + +```typescript +import { Bus } from "./bus" +import { Governance } from "./governance" + +// Monitor all governance checks +Bus.subscribe(Governance.Types.Event.Checked, ({ entry }) => { + console.log(`[${entry.outcome}] ${entry.tool}`) + if (entry.targets.length > 0) { + console.log(` Targets: ${entry.targets.map(t => t.normalized).join(", ")}`) + } +}) + +// Alert on policy violations +Bus.subscribe(Governance.Types.Event.PolicyViolation, ({ entry, policy }) => { + sendAlert({ + title: "Governance Policy Violation", + tool: entry.tool, + policy: policy, + reason: entry.reason, + timestamp: entry.timestamp + }) +}) +``` + +### Query Audit Logs + +```typescript +import { Governance } from "./governance" + +// Get recent denied entries +const denied = await Governance.Audit.list(config.audit, { + limit: 50, + outcome: "denied" +}) + +for (const entry of denied) { + console.log(`${new Date(entry.timestamp).toISOString()} - ${entry.tool}`) + console.log(` Reason: ${entry.reason}`) + console.log(` Policy: ${entry.policy || "scope violation"}`) +} + +// Get all entries for a specific session +const sessionLogs = await Governance.Audit.list(config.audit, { + sessionID: "session_abc" +}) +``` + +### Custom Target Classification + +```typescript +import { Governance } from "./governance" + +// Classify a string +const target = Governance.Matcher.classifyTarget("192.168.1.100") +console.log(target) +// { raw: "192.168.1.100", type: "ip", normalized: "192.168.1.100" } + +// Check CIDR membership +const inRange = Governance.Matcher.ipInCidr("192.168.1.100", "192.168.0.0/16") +console.log(inRange) // true + +// Extract targets from bash command +const targets = Governance.Matcher.extractTargets("bash", { + command: "ssh admin@server.prod.company.com && curl https://api.example.com" +}) +// [ +// { raw: "server.prod.company.com", type: "domain", normalized: "server.prod.company.com" }, +// { raw: "https://api.example.com", type: "url", normalized: "api.example.com" } +// ] +``` + +--- + +## Integration Guide + +### How Governance Integrates with cyxwiz + +The governance engine hooks into the plugin system: + +``` +User Request → AI generates tool call → Plugin.trigger("tool.execute.before") + ↓ + Governance.check() + ↓ + ┌───────────┴───────────┐ + ↓ ↓ + Allowed Denied + ↓ ↓ + Execute tool Return error message + ↓ ↓ + Plugin.trigger("tool.execute.after") + ↓ + Return result to AI +``` + +### Files Modified for Integration + +| File | Integration Point | +|------|-------------------| +| `src/plugin/index.ts` | Governance check in `trigger()` function | +| `src/session/prompt.ts` | `GovernanceDeniedError` handling | +| `src/config/config.ts` | Governance schema in config | + +### Plugin Integration (`plugin/index.ts`) + +```typescript +export async function trigger(name, input, output) { + // Governance check before tool execution + if (name === "tool.execute.before") { + const config = await Config.get() + if (Governance.isEnabled(config.governance)) { + const result = await Governance.check( + { + tool: input.tool, + args: input.args, + sessionID: input.sessionID, + callID: input.callID, + }, + config.governance + ) + + if (!result.allowed) { + throw new Governance.DeniedError(result) + } + } + } + + // Continue with plugin hooks... +} +``` + +### Error Handling (`session/prompt.ts`) + +```typescript +async execute(args, options) { + try { + await Plugin.trigger("tool.execute.before", { tool, args, ... }) + } catch (err) { + if (err instanceof Governance.DeniedError) { + return { + output: `[GOVERNANCE DENIED] Tool "${tool}" was blocked. +Reason: ${err.result.reason} +Policy: ${err.result.matchedPolicy || "scope violation"}`, + metadata: { governance: { denied: true, ...err.result } } + } + } + throw err + } + + // Execute the tool... +} +``` + +--- + +## Troubleshooting + +### Common Issues + +#### "Governance disabled" in logs +**Cause**: Governance is not enabled in config. +**Solution**: Set `"enabled": true` in your governance config. + +#### Tools blocked unexpectedly +**Cause**: Scope or policy rules are too restrictive. +**Solution**: +1. Check audit logs: `Governance.Audit.list(config.audit, { outcome: "denied" })` +2. Review the `reason` field to understand why +3. Adjust scope or policies accordingly + +#### Policies not matching as expected +**Cause**: Policy order matters - first match wins. +**Solution**: Place more specific policies before general ones. + +```jsonc +// WRONG - general policy matches first +{ + "policies": [ + { "action": "require-approval", "tools": ["bash"] }, + { "action": "blocked", "tools": ["bash"], "commands": ["rm -rf *"] } + ] +} + +// CORRECT - specific policy first +{ + "policies": [ + { "action": "blocked", "tools": ["bash"], "commands": ["rm -rf *"] }, + { "action": "require-approval", "tools": ["bash"] } + ] +} +``` + +#### Targets not being extracted from bash commands +**Cause**: The command pattern isn't recognized. +**Solution**: The matcher looks for: +- URLs (`http://`, `https://`) +- IP addresses (`192.168.1.1`) +- CIDR notation (`10.0.0.0/8`) +- SSH patterns (`user@host`) +- Common tool invocations (`curl`, `wget`, `ssh`, etc.) + +If your command uses a different pattern, the target may not be extracted. + +### Debug Logging + +Enable debug logging to see governance decisions: + +```typescript +// In your config or environment +LOG_LEVEL=debug +``` + +This will show: +- Target extraction results +- Scope check details +- Policy matching process +- Audit entry creation + +### Testing Governance + +```typescript +// Test scope checking +const targets = [ + { raw: "10.0.0.5", type: "ip", normalized: "10.0.0.5" } +] +const scopeResult = Governance.Scope.check(targets, { + ip: { allow: ["10.0.0.0/8"] } +}) +console.log(scopeResult) // { allowed: true } + +// Test policy evaluation +const policyResult = Governance.Policy.evaluate( + "bash", + { command: "ls -la" }, + [], + [{ action: "auto-approve", tools: ["bash"], commands: ["ls *"] }], + "require-approval" +) +console.log(policyResult) // { action: "auto-approve", matchedPolicy: "Policy #1", ... } +``` + +--- + +## Appendix + +### Pattern Matching Reference + +| Pattern | Matches | Does Not Match | +|---------|---------|----------------| +| `*.example.com` | `api.example.com`, `www.example.com` | `example.com` | +| `example.com` | `example.com` | `api.example.com` | +| `10.0.0.0/8` | `10.1.2.3`, `10.255.255.255` | `11.0.0.0` | +| `192.168.1.0/24` | `192.168.1.1`, `192.168.1.255` | `192.168.2.1` | +| `ssh *` | `ssh user@host`, `ssh -p 22 host` | `sshd`, `openssh` | +| `curl *` | `curl https://api.com`, `curl -X POST` | `curling` | + +### Outcome Reference + +| Outcome | Description | Tool Executes? | +|---------|-------------|----------------| +| `allowed` | Auto-approved by policy | Yes | +| `pending-approval` | Requires user permission | If user approves | +| `denied` | Blocked by scope or policy | No | +| `error` | Error during governance check | No | + +### Event Reference + +| Event | When Published | Payload | +|-------|----------------|---------| +| `governance.checked` | After every check | `{ entry: AuditEntry }` | +| `governance.policy_violation` | When denied | `{ entry: AuditEntry, policy: string }` | diff --git a/docs/PENTEST.md b/docs/PENTEST.md new file mode 100644 index 00000000000..7693161d2ac --- /dev/null +++ b/docs/PENTEST.md @@ -0,0 +1,414 @@ +# Pentest Module Documentation + +This document describes the penetration testing module for cyxwiz, which provides security scanning, vulnerability assessment, and findings management capabilities. + +--- + +## Table of Contents + +- [Overview](#overview) +- [Architecture](#architecture) +- [Components](#components) +- [Tools](#tools) +- [Configuration](#configuration) +- [Usage](#usage) +- [Integration with Governance](#integration-with-governance) + +--- + +## Overview + +The pentest module provides penetration testing capabilities similar to what you would find on Kali Linux or Parrot OS. It integrates with the cyxwiz governance system to enforce scope restrictions and provides structured output with findings management. + +### Key Features + +- **Nmap Integration**: Full nmap support with XML output parsing +- **Security Tools Wrapper**: Access to 30+ common security tools +- **Findings Management**: Store, query, and track security findings +- **Governance Integration**: Scope enforcement for authorized targets +- **LLM Analysis**: AI-powered explanation of scan results + +--- + +## Architecture + +``` +┌─────────────────────────────────────────────────────────────────┐ +│ Pentest Module │ +│ │ +│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │ +│ │ Nmap Tool │ │ SecTools │ │ Findings │ │ +│ │ (scanning) │ │ (wrapper) │ │ (storage) │ │ +│ └──────┬──────┘ └──────┬──────┘ └──────┬──────┘ │ +│ │ │ │ │ +│ ▼ ▼ ▼ │ +│ ┌─────────────────────────────────────────────────┐ │ +│ │ NmapParser (XML parsing) │ │ +│ └─────────────────────────────────────────────────┘ │ +│ │ │ +│ ▼ │ +│ ┌─────────────────────────────────────────────────┐ │ +│ │ Governance (scope enforcement) │ │ +│ └─────────────────────────────────────────────────┘ │ +└─────────────────────────────────────────────────────────────────┘ +``` + +--- + +## Components + +### 1. Types (`types.ts`) + +Defines core types using Zod schemas: + +| Type | Description | +|------|-------------| +| `Severity` | Finding severity levels (critical, high, medium, low, info) | +| `FindingStatus` | Finding lifecycle status (open, confirmed, mitigated, false_positive) | +| `ScanType` | Types of scans (port, service, vuln, web, custom) | +| `PortState` | Port states from nmap (open, closed, filtered, etc.) | +| `Port` | Individual port scan result | +| `Host` | Host information with ports and OS detection | +| `ScanResult` | Complete scan result with all hosts | +| `Finding` | Security finding with severity and remediation | + +### 2. Nmap Parser (`nmap-parser.ts`) + +Parses nmap XML output into structured data: + +| Function | Purpose | +|----------|---------| +| `parse()` | Parse nmap XML into ScanResult | +| `formatResult()` | Format scan result as human-readable text | +| `summarize()` | Generate concise scan summary | + +### 3. Findings (`findings.ts`) + +Manages storage and retrieval of security findings: + +| Function | Purpose | +|----------|---------| +| `create()` | Create a new finding | +| `update()` | Update existing finding | +| `get()` | Retrieve finding by ID | +| `list()` | List findings with filters | +| `remove()` | Delete a finding | +| `saveScan()` | Save scan result | +| `getScan()` | Retrieve scan result | +| `listScans()` | List scan results | +| `analyzeAndCreateFindings()` | Auto-generate findings from scan | + +### 4. Nmap Tool (`nmap-tool.ts`) + +Dedicated nmap tool with full feature support: + +| Parameter | Description | +|-----------|-------------| +| `target` | IP, hostname, or CIDR range | +| `ports` | Port specification (e.g., "22,80,443") | +| `serviceDetection` | Enable -sV service detection | +| `timing` | Timing template (0-5) | +| `udpScan` | Include UDP scanning | +| `osDetection` | Enable OS detection | +| `scriptScan` | Run default NSE scripts | +| `analyzeFindings` | Auto-create findings | + +### 5. Security Tools (`sectools.ts`) + +Wrapper for 30+ common security tools: + +**Network Reconnaissance:** +- nmap, masscan, netcat (nc) + +**Web Scanning:** +- nikto, dirb, gobuster, ffuf, wpscan, whatweb, wafw00f + +**Vulnerability Scanning:** +- nuclei, searchsploit + +**SQL Injection:** +- sqlmap + +**SMB/Windows:** +- enum4linux, smbclient, crackmapexec, rpcclient + +**SSL/TLS:** +- sslscan, sslyze, testssl + +**DNS:** +- dnsenum, dnsrecon, fierce, dig, host, whois + +--- + +## Tools + +### Nmap Tool + +The `nmap` tool provides structured port scanning: + +```typescript +// Example nmap scan +const result = await nmap.execute({ + target: "192.168.1.1", + ports: "1-1000", + serviceDetection: true, + timing: 3, +}) + +// Result includes: +// - Parsed hosts and ports +// - Service information +// - Auto-generated findings +``` + +### SecTools Tool + +The `sectools` tool wraps common security utilities: + +```typescript +// Nikto web scan +const result = await sectools.execute({ + tool: "nikto", + target: "http://example.com", + args: "-Tuning 1", +}) + +// Gobuster directory scan +const result = await sectools.execute({ + tool: "gobuster", + target: "http://example.com", + args: "dir -w /usr/share/wordlists/dirb/common.txt", +}) + +// SSL analysis +const result = await sectools.execute({ + tool: "sslscan", + target: "example.com", +}) +``` + +--- + +## Configuration + +### Pentest Agent Permissions + +The pentest agent has pre-configured permissions for security tools: + +```typescript +bash: { + // Network reconnaissance + "nmap *": "allow", + "ping *": "allow", + "traceroute *": "allow", + "masscan *": "allow", + + // Web scanning + "nikto *": "allow", + "dirb *": "allow", + "gobuster *": "allow", + "sqlmap *": "allow", + + // SMB/Windows + "enum4linux *": "allow", + "smbclient *": "allow", + + // SSL/TLS + "sslscan *": "allow", + "sslyze *": "allow", + + // Blocked by default (too risky) + "hashcat *": "deny", + "john *": "deny", + "hydra *": "deny", +} +``` + +### Governance Scope + +Governance scope restrictions apply to all pentest tools: + +```json +{ + "governance": { + "enabled": true, + "scope": { + "ip": { + "allow": ["10.0.0.0/8", "192.168.0.0/16"], + "deny": ["0.0.0.0/8"] + }, + "domain": { + "allow": ["*.internal.company.com"], + "deny": ["*.prod.company.com"] + } + } + } +} +``` + +--- + +## Usage + +### Using the Pentest Agent + +The pentest agent can be invoked with `@pentest`: + +``` +@pentest Scan ports on 192.168.1.1 +@pentest Check web vulnerabilities on http://example.com +@pentest Enumerate SMB on 192.168.1.100 +@pentest Analyze SSL/TLS configuration on example.com +``` + +### Direct Tool Usage + +Tools can also be used directly: + +```typescript +// Nmap scan +const scanResult = await tools.nmap.execute({ + target: "192.168.1.0/24", + serviceDetection: true, +}) + +// Access findings +const findings = await Findings.list({}, { + sessionID: currentSession, + severity: "high", +}) +``` + +### Example Workflow + +1. **Network Discovery** + ``` + @pentest Discover hosts on 192.168.1.0/24 + ``` + +2. **Port Scanning** + ``` + @pentest Detailed port scan on discovered hosts + ``` + +3. **Service Enumeration** + ``` + @pentest Check for vulnerable services + ``` + +4. **Web Assessment** (if web servers found) + ``` + @pentest Run nikto and gobuster on web servers + ``` + +5. **Report Generation** + ``` + @pentest Summarize all findings with recommendations + ``` + +--- + +## Integration with Governance + +The pentest module integrates with governance for scope enforcement: + +### Target Validation + +Before any scan, targets are validated against governance scope: + +1. **IP/CIDR targets**: Checked against `scope.ip.allow` and `scope.ip.deny` +2. **Domain targets**: Checked against `scope.domain.allow` and `scope.domain.deny` +3. **URL targets**: Hostname extracted and checked against domain scope + +### Audit Trail + +All scans are recorded in the governance audit log: + +```typescript +// Audit entries include: +{ + tool: "nmap", + targets: ["192.168.1.1"], + outcome: "allowed", + duration: 5000, +} +``` + +### Policy Integration + +Governance policies can control pentest tool access: + +```json +{ + "policies": [ + { + "description": "Allow pentesting internal networks", + "action": "auto-approve", + "tools": ["nmap", "sectools"], + "targets": ["192.168.*", "10.*"] + }, + { + "description": "Block external scanning", + "action": "blocked", + "tools": ["nmap", "sectools"], + "targets": ["*.com", "*.org"] + } + ] +} +``` + +--- + +## Files + +| File | Purpose | +|------|---------| +| `types.ts` | Type definitions | +| `nmap-parser.ts` | Nmap XML parser | +| `findings.ts` | Findings storage | +| `nmap-tool.ts` | Nmap tool | +| `sectools.ts` | Security tools wrapper | +| `index.ts` | Module exports | +| `prompt/pentest.txt` | Agent system prompt | + +--- + +## Events + +The pentest module publishes bus events: + +| Event | Description | +|-------|-------------| +| `pentest.scan_started` | Scan has begun | +| `pentest.scan_completed` | Scan has finished | +| `pentest.finding_created` | New finding created | +| `pentest.finding_updated` | Finding was updated | + +--- + +## Testing + +Tests are located in `test/pentest/pentest.test.ts`: + +```bash +cd packages/opencode +bun test test/pentest/pentest.test.ts +``` + +Test coverage includes: +- Nmap XML parsing +- Findings CRUD operations +- Type validation +- Memory storage mode + +--- + +## Dependencies + +| Dependency | Usage | +|------------|-------| +| `Storage` | Finding persistence | +| `Bus` | Event publishing | +| `Identifier` | Unique ID generation | +| `Log` | Structured logging | +| `GovernanceMatcher` | Target classification | diff --git a/docs/PENTEST_CAPABILITIES.md b/docs/PENTEST_CAPABILITIES.md new file mode 100644 index 00000000000..aab282eb1fa --- /dev/null +++ b/docs/PENTEST_CAPABILITIES.md @@ -0,0 +1,617 @@ +# Cyxwiz Pentest Module - Capabilities Report + +**Generated:** 2026-01-17 +**Test Status:** 232+ tests passing, 0 failures +**Test Coverage:** 9 test files across all modules + +--- + +## Executive Summary + +The Cyxwiz pentest module is a comprehensive security testing framework integrated into the opencode CLI. It provides automated penetration testing capabilities including network scanning, web application testing, API security assessment, cloud security scanning (AWS, Azure, GCP), network infrastructure testing, exploit research, continuous monitoring, compliance checking, and professional report generation. + +--- + +## Module Overview + +### 1. Network Scanning (`nmap-tool`, `nmap-parser`) + +**Capabilities:** +- Port scanning and service detection +- OS fingerprinting +- Version detection +- Script scanning (NSE) +- XML/JSON output parsing +- Finding generation from scan results + +**Tool Actions:** +| Action | Description | +|--------|-------------| +| `scan` | Run Nmap scan with configurable options | +| `quick-scan` | Fast scan of common ports | +| `full-scan` | Comprehensive port and service scan | +| `vuln-scan` | Vulnerability-focused scan with NSE scripts | +| `parse` | Parse existing Nmap XML output | + +--- + +### 2. Web Application Scanning (`webscan`) + +**Capabilities:** +- Web crawling with configurable depth +- Form discovery and analysis +- Link extraction +- File upload detection +- Password field detection +- OWASP Top 10 2021 categorization + +**Components:** + +#### Web Crawler +- Configurable crawl depth and limits +- Form extraction with input analysis +- Link normalization and validation +- Rate limiting support + +#### Scan Profiles +| Profile | Description | +|---------|-------------| +| `quick` | Fast assessment, basic checks | +| `standard` | Normal pentest coverage | +| `thorough` | Comprehensive testing | +| `stealth` | Low-noise, evasive scanning | +| `aggressive` | Maximum coverage, higher risk | + +#### Parser Integrations +- **WPScan**: WordPress vulnerability scanning +- **WhatWeb**: Web technology fingerprinting +- **Nikto**: Web server vulnerability scanning +- **Nuclei**: Template-based vulnerability detection +- **Gobuster**: Directory/file brute-forcing +- **FFuf**: Web fuzzing +- **SSLScan**: SSL/TLS configuration analysis + +#### OWASP Categorization +Automatic categorization of findings into OWASP Top 10 2021: +- A01: Broken Access Control +- A02: Cryptographic Failures +- A03: Injection +- A04: Insecure Design +- A05: Security Misconfiguration +- A06: Vulnerable and Outdated Components +- A07: Identification and Authentication Failures +- A08: Software and Data Integrity Failures +- A09: Security Logging and Monitoring Failures +- A10: Server-Side Request Forgery (SSRF) + +--- + +### 3. API Security Scanner (`apiscan`) - Phase 9 + +**Capabilities:** +- API specification discovery and parsing +- Authentication mechanism testing +- Authorization vulnerability detection +- Injection testing +- OWASP API Top 10 2023 categorization + +#### API Discovery +- OpenAPI/Swagger 2.0 and 3.x parsing +- GraphQL introspection parsing +- Common API path probing +- Endpoint enumeration + +#### Authentication Testing + +**JWT Analysis:** +- Token decoding and claim extraction +- Algorithm weakness detection (none, HS256, etc.) +- Expiration validation +- Sensitive data in payload detection +- JKU/X5U header injection detection +- Attack vector suggestions: + - None algorithm attack + - Algorithm confusion (RS256 to HS256) + - Brute force for HMAC secrets + - Key injection via JKU/X5U + - Token replay + - Signature stripping + +**API Key Testing:** +- Key exposure detection +- Weak key patterns +- Key rotation issues + +**OAuth Testing:** +- Flow analysis +- Token leakage detection +- State parameter validation + +#### Authorization Testing + +**BOLA/IDOR Detection:** +- Object-level authorization testing +- Horizontal privilege escalation +- ID parameter manipulation + +**Privilege Escalation:** +- Vertical privilege testing +- Role-based access control bypass +- Admin endpoint access + +#### Injection Testing +- SQL injection (error-based, blind, time-based) +- NoSQL injection (MongoDB, etc.) +- Command injection (OS command execution) + +#### Scan Profiles +| Profile | Discovery | Auth Tests | Injection | BOLA | Use Case | +|---------|-----------|------------|-----------|------|----------| +| `discovery` | Full | None | None | No | Map API surface | +| `quick` | Basic | JWT decode | None | No | Fast assessment | +| `standard` | Full | All auth | SQL, NoSQL | Yes | Normal pentest | +| `thorough` | Full | All + fuzzing | All | Yes | Comprehensive | +| `passive` | Spec only | JWT decode | None | No | No active testing | +| `auth-focused` | Basic | All + brute | None | Yes | Auth-specific | + +#### OWASP API Top 10 2023 +- API1: Broken Object Level Authorization +- API2: Broken Authentication +- API3: Broken Object Property Level Authorization +- API4: Unrestricted Resource Consumption +- API5: Broken Function Level Authorization +- API6: Unrestricted Access to Sensitive Business Flows +- API7: Server Side Request Forgery +- API8: Security Misconfiguration +- API9: Improper Inventory Management +- API10: Unsafe Consumption of APIs + +--- + +### 4. Exploit Research (`exploits`) + +**Capabilities:** +- Searchsploit integration +- Metasploit module matching +- CVE correlation +- Exploit database searching + +#### Parser Integrations +- **Searchsploit**: Exploit-DB searching +- **Metasploit**: Module discovery and matching + +#### Features +- Automatic exploit matching based on findings +- CVE extraction from vulnerability data +- Exploit categorization by type +- Risk scoring based on exploit availability + +--- + +### 5. Cloud Security Scanner (`cloudscan`) - Phase 11 + +**Capabilities:** +- Multi-cloud security assessment (AWS, Azure, GCP) +- IAM and access control analysis +- Storage security evaluation +- Network security group analysis +- Compute resource security +- Compliance framework checking + +#### Supported Cloud Providers + +**AWS:** +- IAM users, roles, policies, MFA, access keys +- S3 bucket security (public access, encryption, versioning) +- Security Groups (ingress rules, sensitive ports) +- EC2 instances (IMDSv2, public IPs) +- Lambda functions (public access, secrets in env) + +**Azure:** +- RBAC (users, service principals, role assignments) +- Storage accounts (public access, HTTPS, encryption) +- Network Security Groups (ingress rules) +- VMs and Function Apps (managed identity) + +**GCP:** +- IAM service accounts and custom roles +- Cloud Storage (public access prevention, uniform access) +- Firewall rules (public ingress, sensitive ports) +- GCE instances and Cloud Functions + +#### Compliance Frameworks +| Framework | Description | +|-----------|-------------| +| CIS Benchmarks | Cloud security best practices | +| NIST | Cybersecurity Framework | +| PCI-DSS | Payment card security | +| HIPAA | Healthcare data protection | +| SOC2 | Service organization controls | +| GDPR | Data protection regulation | +| ISO 27001 | Information security management | + +#### Scan Profiles +| Profile | Discovery | Security | Compliance | External Tools | +|---------|-----------|----------|------------|----------------| +| `discovery` | yes | no | no | no | +| `quick` | yes | yes | no | no | +| `standard` | yes | yes | CIS | no | +| `thorough` | yes | yes | all | Prowler, ScoutSuite | +| `compliance` | yes | yes | all | no | +| `iam-focused` | yes | yes | CIS | no | +| `storage-focused` | yes | yes | CIS | no | +| `network-focused` | yes | yes | CIS | no | + +#### External Tool Integration +- **Prowler**: AWS/Azure/GCP security assessment +- **ScoutSuite**: Multi-cloud security auditing + +--- + +### 6. Continuous Monitoring (`monitoring`) + +**Capabilities:** +- Scheduled security scans +- Change detection and alerting +- Baseline comparison +- Automated notifications + +#### Components +- **Scheduler**: Cron-based scan scheduling +- **Runner**: Automated scan execution +- **Diff Engine**: Change detection between scans +- **Alerter**: Notification system for new findings + +#### Features +- Configurable scan intervals +- New vulnerability alerts +- Remediation tracking +- Historical trend analysis + +--- + +### 7. Report Generation (`reports`) + +**Capabilities:** +- Professional HTML reports +- Markdown report generation +- Executive and technical formats +- Customizable templates + +#### Report Types +| Type | Audience | Content Focus | +|------|----------|---------------| +| `executive` | Management | Risk summary, business impact | +| `technical` | Engineers | Detailed findings, evidence | +| `compliance` | Auditors | Standards mapping, remediation | + +#### HTML Report Features +- Responsive design +- Severity-based color coding +- Interactive charts +- Print-optimized styling +- Custom CSS support +- XSS-safe content escaping + +#### Report Sections +- Executive Summary +- Risk Assessment +- Severity Statistics +- Findings Table +- Detailed Findings with Evidence +- Remediation Summary +- Methodology +- Scope and Exclusions + +--- + +### 8. Findings Management + +**Capabilities:** +- Centralized finding storage +- Severity classification +- Status tracking +- Evidence attachment +- Remediation guidance + +#### Finding Attributes +- Unique ID +- Title and description +- Severity (critical, high, medium, low, info) +- Status (open, confirmed, fixed, false_positive) +- Target information +- Evidence and proof +- CVE references +- Remediation steps +- OWASP categorization + +--- + +## Test Coverage Report + +### Test Files and Results + +| Test File | Tests | Status | +|-----------|-------|--------| +| `apiscan.test.ts` | 66 | Pass | +| `webscan.test.ts` | 95 | Pass | +| `reports.test.ts` | 24 | Pass | +| `exploits.test.ts` | 18 | Pass | +| `findings.test.ts` | 12 | Pass | +| `monitoring.test.ts` | 10 | Pass | +| `parsers.test.ts` | 7 | Pass | +| **Total** | **232** | **Pass** | + +### Test Categories + +#### API Security Scanner Tests (66 tests) +- JWT Analysis: 18 tests + - Token decoding and claim extraction + - Expiration detection + - Algorithm weakness detection + - Sensitive data detection + - Attack vector generation +- OpenAPI Parser: 12 tests + - OpenAPI 3.x parsing + - Swagger 2.0 parsing + - Endpoint extraction + - Security scheme extraction +- GraphQL Parser: 14 tests + - Introspection parsing + - Type extraction + - Security pattern analysis +- Profiles: 10 tests +- Storage: 8 tests +- Type Validation: 4 tests + +#### Web Scanner Tests (95 tests) +- Web Crawler: 25 tests +- Form Extraction: 12 tests +- OWASP Categorization: 15 tests +- WPScan Parser: 10 tests +- WhatWeb Parser: 8 tests +- Storage Operations: 15 tests +- Orchestrator: 10 tests + +#### Report Generation Tests (24 tests) +- HTML Generation: 15 tests +- Markdown Generation: 6 tests +- Content Escaping: 3 tests + +--- + +## Architecture + +``` +src/pentest/ +├── index.ts # Main exports +├── types.ts # Core type definitions +├── findings.ts # Finding management +├── sectools.ts # Security tool integration +├── nmap-tool.ts # Nmap integration +├── nmap-parser.ts # Nmap output parsing +├── report-tool.ts # Report generation tool +│ +├── parsers/ # External tool parsers +│ ├── nikto.ts +│ ├── nuclei.ts +│ ├── gobuster.ts +│ ├── sslscan.ts +│ └── ffuf.ts +│ +├── webscan/ # Web scanning module +│ ├── crawler.ts # Web crawler +│ ├── orchestrator.ts # Scan coordination +│ ├── owasp.ts # OWASP categorization +│ ├── profiles.ts # Scan profiles +│ ├── storage.ts # Result persistence +│ ├── tool.ts # WebScanTool +│ └── parsers/ +│ ├── wpscan.ts +│ └── whatweb.ts +│ +├── apiscan/ # API scanning module +│ ├── discovery.ts # API discovery +│ ├── orchestrator.ts # Scan coordination +│ ├── profiles.ts # Scan profiles +│ ├── storage.ts # Result persistence +│ ├── tool.ts # ApiScanTool +│ ├── parsers/ +│ │ ├── openapi.ts # OpenAPI/Swagger parser +│ │ └── graphql.ts # GraphQL parser +│ ├── auth/ +│ │ ├── jwt.ts # JWT analysis +│ │ ├── apikey.ts # API key testing +│ │ └── oauth.ts # OAuth testing +│ ├── authz/ +│ │ ├── bola.ts # BOLA/IDOR detection +│ │ └── privilege.ts # Privilege escalation +│ └── injection/ +│ ├── sql.ts # SQL injection +│ ├── nosql.ts # NoSQL injection +│ └── command.ts # Command injection +│ +├── exploits/ # Exploit research module +│ ├── matcher.ts # Exploit matching +│ ├── storage.ts # Exploit database +│ ├── tool.ts # ExploitTool +│ └── parsers/ +│ ├── searchsploit.ts +│ └── metasploit.ts +│ +├── monitoring/ # Continuous monitoring +│ ├── scheduler.ts # Cron scheduling +│ ├── runner.ts # Scan execution +│ ├── diff.ts # Change detection +│ ├── alerter.ts # Notifications +│ ├── cron-parser.ts # Cron expression parsing +│ └── tool.ts # MonitorTool +│ +└── reports/ # Report generation + ├── html.ts # HTML reports + ├── markdown.ts # Markdown reports + └── types.ts # Report types +``` + +--- + +## Agent Tools + +The following tools are available to the AI agent: + +| Tool | Description | +|------|-------------| +| `nmap` | Network scanning and enumeration | +| `webscan` | Web application security scanning | +| `apiscan` | API security testing | +| `netscan` | Network infrastructure testing | +| `cloudscan` | Cloud security scanning (AWS, Azure, GCP) | +| `exploit` | Exploit research and matching | +| `monitor` | Continuous security monitoring | +| `report` | Security report generation | + +--- + +## Event System + +All modules emit events for real-time progress tracking: + +### API Scanner Events +- `pentest.apiscan.discovery_started` +- `pentest.apiscan.endpoint_discovered` +- `pentest.apiscan.spec_parsed` +- `pentest.apiscan.scan_started` +- `pentest.apiscan.endpoint_tested` +- `pentest.apiscan.auth_tested` +- `pentest.apiscan.injection_tested` +- `pentest.apiscan.vulnerability_found` +- `pentest.apiscan.scan_completed` + +### Web Scanner Events +- `pentest.webscan.crawl_started` +- `pentest.webscan.url_discovered` +- `pentest.webscan.form_discovered` +- `pentest.webscan.scan_started` +- `pentest.webscan.vulnerability_found` +- `pentest.webscan.scan_completed` + +### Cloud Scanner Events +- `pentest.cloudscan.scan_started` +- `pentest.cloudscan.scan_completed` +- `pentest.cloudscan.scan_failed` +- `pentest.cloudscan.discovery_started` +- `pentest.cloudscan.discovery_completed` +- `pentest.cloudscan.bucket_found` +- `pentest.cloudscan.public_bucket_found` +- `pentest.cloudscan.iam_user_found` +- `pentest.cloudscan.iam_role_found` +- `pentest.cloudscan.iam_policy_issue` +- `pentest.cloudscan.security_group_found` +- `pentest.cloudscan.insecure_rule_found` +- `pentest.cloudscan.instance_found` +- `pentest.cloudscan.function_found` +- `pentest.cloudscan.finding_detected` +- `pentest.cloudscan.compliance_violation` +- `pentest.cloudscan.compliance_complete` + +### Monitoring Events +- `pentest.monitoring.scan_scheduled` +- `pentest.monitoring.scan_started` +- `pentest.monitoring.scan_completed` +- `pentest.monitoring.diff_detected` +- `pentest.monitoring.alert_triggered` + +--- + +## Storage + +Persistent storage for all scan data: + +``` +pentest/ +├── findings/ # Security findings +├── webscan/ +│ ├── crawls/ # Crawl results +│ └── scans/ # Scan results +├── apiscan/ +│ ├── specs/ # API specifications +│ └── scans/ # Scan results +├── netscan/ +│ ├── scans/ # Network scan results +│ ├── hosts/ # Discovered hosts +│ └── credentials/ # Encrypted credentials +├── cloudscan/ +│ └── scans/ # Cloud scan results +├── exploits/ +│ └── matches/ # Exploit matches +├── monitoring/ +│ ├── schedules/ # Scheduled scans +│ └── baselines/ # Baseline comparisons +└── reports/ # Generated reports +``` + +--- + +## Usage Examples + +### API Security Scan +```typescript +import { ApiScanTool } from "./pentest/apiscan" + +// Discover and scan API +const result = await ApiScanTool.execute({ + action: "scan", + target: "https://api.example.com", + profile: "standard", + auth: { type: "jwt", token: "eyJ..." } +}) +``` + +### Web Application Scan +```typescript +import { WebScanTool } from "./pentest/webscan" + +// Crawl and scan website +const result = await WebScanTool.execute({ + action: "scan", + target: "https://example.com", + profile: "thorough", + depth: 3 +}) +``` + +### Generate Report +```typescript +import { generateHtmlReport } from "./pentest/reports" + +const html = generateHtmlReport({ + config: { title: "Security Assessment", type: "technical" }, + findings: [...], + target: { ... }, + scope: { ... } +}) +``` + +--- + +## Compliance Mapping + +The tool supports mapping findings to common compliance frameworks: + +- **OWASP Top 10 2021** (Web) +- **OWASP API Top 10 2023** (API) +- **CWE** (Common Weakness Enumeration) +- **CVE** (Common Vulnerabilities and Exposures) +- **CVSS** (Common Vulnerability Scoring System) + +--- + +## Future Enhancements + +Planned capabilities for future phases: +- Container security (Docker, Kubernetes) +- Mobile application testing +- Wireless network security +- Social engineering simulation +- Post-exploitation framework +- CI/CD security integration diff --git a/docs/PHASE03-pentest-agent-mvp.md b/docs/PHASE03-pentest-agent-mvp.md new file mode 100644 index 00000000000..8442b8ced75 --- /dev/null +++ b/docs/PHASE03-pentest-agent-mvp.md @@ -0,0 +1,326 @@ +# Phase 3: Pentest Agent MVP - Implementation Report + +This document describes what was implemented in Phase 3 of the cyxwiz project. + +--- + +## Overview + +Phase 3 delivered a penetration testing agent with security scanning capabilities, integrating with the governance system from Phase 2 for scope enforcement. + +**Goal:** Can run "scan ports on X" with governance and get explained results. + +**Status:** Complete + +--- + +## Deliverables + +### 1. Pentest Agent + +A new built-in agent `@pentest` was added with: + +- Specialized system prompt for security testing +- Pre-configured permissions for 30+ security tools +- Integration with governance scope enforcement +- Low temperature (0.3) for precise, technical responses + +**Usage:** +``` +@pentest Scan ports on 192.168.1.1 +@pentest Check web vulnerabilities on http://example.com +@pentest Analyze SSL configuration on example.com +``` + +### 2. Nmap Tool + +Dedicated `nmap` tool with full feature support: + +| Feature | Description | +|---------|-------------| +| XML Parsing | Automatic parsing of nmap XML output | +| Service Detection | -sV flag support | +| OS Detection | -O flag support | +| Script Scanning | -sC flag support | +| UDP Scanning | -sU flag support | +| Timing Control | T0-T5 timing templates | +| Findings Generation | Auto-create findings from results | + +**Parameters:** +- `target` - IP, hostname, or CIDR range +- `ports` - Port specification (e.g., "22,80,443") +- `serviceDetection` - Enable service version detection +- `timing` - Timing template (0-5) +- `udpScan` - Include UDP ports +- `osDetection` - Enable OS detection +- `scriptScan` - Run default NSE scripts +- `analyzeFindings` - Auto-generate findings + +### 3. Security Tools Wrapper (SecTools) + +A unified wrapper for common security tools: + +**Network Reconnaissance:** +- nmap, masscan, netcat (nc), ping, traceroute + +**Web Scanning:** +- nikto - Web server vulnerability scanner +- dirb, gobuster, ffuf - Directory brute forcing +- wpscan - WordPress security scanner +- whatweb - Web fingerprinting +- wafw00f - WAF detection + +**Vulnerability Scanning:** +- nuclei - Template-based scanner +- searchsploit - Exploit database search + +**SQL Injection:** +- sqlmap - Automated SQL injection + +**SMB/Windows:** +- enum4linux - SMB enumeration +- smbclient - SMB client +- crackmapexec - Network attack tool +- rpcclient - Windows RPC client + +**SSL/TLS:** +- sslscan, sslyze, testssl - SSL/TLS analysis + +**DNS:** +- dnsenum, dnsrecon, fierce - DNS enumeration +- dig, host, whois - DNS utilities + +**Blocked by Default (too risky):** +- hashcat, john - Password cracking +- hydra - Brute force attacks + +### 4. Findings Storage + +Persistent storage for security findings: + +| Function | Description | +|----------|-------------| +| `create()` | Create new finding | +| `update()` | Update finding status/severity | +| `get()` | Retrieve by ID | +| `list()` | Query with filters | +| `remove()` | Delete finding | +| `saveScan()` | Store scan results | +| `listScans()` | Query scan history | +| `analyzeAndCreateFindings()` | Auto-generate from scans | + +**Finding Properties:** +- ID, session ID, scan ID +- Title, description +- Severity (critical, high, medium, low, info) +- Status (open, confirmed, mitigated, false_positive) +- Target, port, protocol, service +- Evidence, remediation +- CVE references + +### 5. Nmap XML Parser + +Structured parsing of nmap XML output: + +- Host extraction (address, hostname, status) +- Port parsing (state, service, version) +- OS detection results +- Timing information +- Human-readable formatting +- Summary generation + +--- + +## Files Created + +``` +packages/opencode/src/pentest/ +├── index.ts # Module exports +├── types.ts # Zod schemas for types +├── nmap-parser.ts # Nmap XML parser +├── nmap-tool.ts # Nmap tool implementation +├── sectools.ts # Security tools wrapper +├── findings.ts # Findings storage +├── PENTEST.md # Module documentation +└── prompt/ + └── pentest.txt # Agent system prompt + +packages/opencode/test/pentest/ +└── pentest.test.ts # Test suite (21 tests) + +docs/ +├── PENTEST.md # Pentest documentation +└── TEST.md # Testing documentation +``` + +## Files Modified + +| File | Changes | +|------|---------| +| `src/agent/agent.ts` | Added pentest agent with permissions | +| `src/tool/registry.ts` | Registered nmap and sectools tools | + +--- + +## Integration Points + +### Governance Integration + +The pentest module integrates with Phase 2 governance: + +1. **Scope Enforcement**: All network targets validated against governance scope +2. **Policy Evaluation**: Tool execution checked against policies +3. **Audit Logging**: Scans recorded in governance audit trail + +Example governance config for pentesting: +```json +{ + "governance": { + "enabled": true, + "scope": { + "ip": { + "allow": ["10.0.0.0/8", "192.168.0.0/16"], + "deny": ["0.0.0.0/8"] + } + }, + "policies": [ + { + "action": "auto-approve", + "tools": ["nmap", "sectools"], + "targets": ["192.168.*"] + } + ] + } +} +``` + +### Permission System + +Pentest agent permissions: +```typescript +bash: { + "nmap *": "allow", + "nikto *": "allow", + "gobuster *": "allow", + "sqlmap *": "allow", + "enum4linux *": "allow", + "sslscan *": "allow", + // ... more tools + "hydra *": "deny", // Too risky + "hashcat *": "deny", // Too risky + "*": "ask", +} +``` + +--- + +## Test Coverage + +**Test File:** `test/pentest/pentest.test.ts` + +**Results:** +``` + 21 pass + 0 fail + 72 expect() calls +``` + +**Test Categories:** + +| Category | Tests | +|----------|-------| +| NmapParser | 7 tests - XML parsing, formatting | +| Findings | 11 tests - CRUD, filtering, analysis | +| PentestTypes | 3 tests - Schema validation | + +--- + +## Example Workflows + +### Basic Port Scan +``` +User: @pentest scan ports on 192.168.1.1 + +Agent: +1. Validates target against governance scope +2. Runs: nmap -sV -oX - 192.168.1.1 +3. Parses XML output +4. Generates findings for open ports +5. Returns formatted results with recommendations +``` + +### Web Application Assessment +``` +User: @pentest check web vulnerabilities on http://target.com + +Agent: +1. Runs whatweb for fingerprinting +2. Runs nikto for vulnerability scanning +3. Runs gobuster for directory enumeration +4. Analyzes results +5. Prioritizes findings by severity +6. Provides remediation recommendations +``` + +### Infrastructure Security Check +``` +User: @pentest full security assessment on 192.168.1.0/24 + +Agent: +1. Network discovery with nmap +2. Service enumeration on discovered hosts +3. SSL/TLS analysis on HTTPS services +4. SMB enumeration on Windows hosts +5. Comprehensive findings report +``` + +--- + +## Limitations + +1. **Tool Availability**: Tools must be installed on the system (Kali/Parrot) +2. **Root Required**: Some scans (OS detection, SYN scan) require root +3. **Network Access**: Scans require network connectivity to targets +4. **Governance Scope**: Only authorized targets can be scanned + +--- + +## Future Enhancements + +Potential improvements for future phases: + +1. **Metasploit Integration**: Add MSF module execution +2. **Burp Suite Integration**: Web app testing automation +3. **Report Generation**: Export findings to PDF/HTML +4. **Scheduling**: Scheduled recurring scans +5. **Comparison**: Compare scan results over time +6. **CVE Lookup**: Automatic CVE correlation + +--- + +## Commit + +``` +08a1a86d6 Add Pentest Agent MVP with security scanning tools +``` + +**Stats:** 13 files changed, 3,844 insertions + +--- + +## Dependencies + +| Dependency | Purpose | +|------------|---------| +| Governance Module | Scope enforcement | +| Storage Module | Findings persistence | +| Bus Module | Event publishing | +| Identifier Module | Unique ID generation | + +--- + +## Related Documentation + +- [PENTEST.md](./PENTEST.md) - Pentest module reference +- [GOVERNANCE.md](./GOVERNANCE.md) - Governance system +- [TEST.md](./TEST.md) - Testing guide diff --git a/docs/PHASE04-multi-tool-parsers.md b/docs/PHASE04-multi-tool-parsers.md new file mode 100644 index 00000000000..0349b1eaae8 --- /dev/null +++ b/docs/PHASE04-multi-tool-parsers.md @@ -0,0 +1,327 @@ +# Phase 4: Multi-Tool Parsers - Implementation Report + +This document describes what was implemented in Phase 4 of the cyxwiz project. + +--- + +## Overview + +Phase 4 added structured output parsers for common security tools, enabling automatic extraction of findings and formatted reporting from tool output. + +**Goal:** Parse security tool output into structured data for analysis and findings generation. + +**Status:** Complete + +--- + +## Deliverables + +### 1. Parser Framework + +A unified parser system located at `src/pentest/parsers/`: + +| Parser | Tool(s) | Output Formats | +|--------|---------|----------------| +| NiktoParser | nikto | JSON, Text | +| NucleiParser | nuclei | JSONL | +| GobusterParser | gobuster | JSON, Text | +| FfufParser | ffuf | JSON, Text | +| SslscanParser | sslscan, sslyze | XML, Text | + +Each parser provides: +- `parse(output, target)` - Extract structured data +- `format(result)` - Human-readable output +- `summarize(result)` - Brief summary +- `toFindings(result, sessionID, scanID)` - Generate security findings + +### 2. Nikto Parser + +Parses nikto web vulnerability scanner output: + +**Extracted Data:** +- Target host, IP, port +- Server banner +- Findings with OSVDB references +- URL and description for each finding + +**Finding Severity Classification:** +- Critical: SQL injection, RCE, command injection +- High: XSS, file inclusion, directory traversal +- Medium: OSVDB references, vulnerable/outdated +- Low: Information disclosure, headers + +### 3. Nuclei Parser + +Parses nuclei template-based scanner JSONL output: + +**Extracted Data:** +- Template ID and info +- Severity (critical, high, medium, low, info) +- Matched URLs +- CVE references +- Extracted results + +**Features:** +- Automatic severity summary +- CVE correlation +- Template reference tracking + +### 4. Gobuster Parser + +Parses gobuster directory/DNS brute force output: + +**Extracted Data:** +- Discovered paths +- HTTP status codes +- Response sizes +- Redirect locations + +**Finding Detection:** +- Git repository exposure (critical) +- Backup/SQL files (high) +- Admin panels (medium) +- Config files (high) +- Sensitive directories (medium) + +### 5. FFuf Parser + +Parses ffuf web fuzzer JSON output: + +**Extracted Data:** +- URL hits +- Status codes +- Response metrics (size, words, lines) +- Redirect locations + +**Features:** +- Sensitive path detection +- Status code grouping +- Response size analysis + +### 6. SSLScan Parser + +Parses SSL/TLS configuration scanner output: + +**Extracted Data:** +- Protocol support (SSL 2/3, TLS 1.0-1.3) +- Cipher suites with strength classification +- Certificate information +- Known vulnerabilities (Heartbleed, POODLE, etc.) + +**Finding Generation:** +- Deprecated protocols (SSL, TLS 1.0/1.1) +- Weak/insecure ciphers +- CVE vulnerabilities +- Certificate issues (expired, self-signed) + +--- + +## Files Created + +``` +packages/opencode/src/pentest/parsers/ +├── index.ts # Parser registry and exports +├── nikto.ts # Nikto output parser +├── nuclei.ts # Nuclei JSONL parser +├── gobuster.ts # Gobuster output parser +├── ffuf.ts # FFuf JSON parser +└── sslscan.ts # SSLScan/sslyze parser + +packages/opencode/test/pentest/ +└── parsers.test.ts # Parser test suite (25 tests) +``` + +## Files Modified + +| File | Changes | +|------|---------| +| `src/pentest/index.ts` | Added parser exports | +| `src/pentest/sectools.ts` | Integrated parsers for automatic parsing | + +--- + +## Integration + +### SecTools Integration + +The SecTools wrapper now automatically uses parsers when available: + +```typescript +// Automatic parsing in createToolFindings() +switch (tool) { + case "nikto": { + const result = NiktoParser.parse(output, target) + parsedFindings = NiktoParser.toFindings(result, sessionID, scanID) + break + } + case "nuclei": { + const result = NucleiParser.parse(output, target) + parsedFindings = NucleiParser.toFindings(result, sessionID, scanID) + break + } + // ... more tools +} +``` + +### Direct Usage + +Parsers can be used directly: + +```typescript +import { NiktoParser, NucleiParser } from "./pentest" + +// Parse nikto output +const niktoResult = NiktoParser.parse(output, "http://target.com") +console.log(NiktoParser.format(niktoResult)) + +// Parse nuclei output +const nucleiResult = NucleiParser.parse(jsonlOutput, "https://target.com") +const findings = NucleiParser.toFindings(nucleiResult, sessionID, scanID) +``` + +--- + +## Parser Output Examples + +### Nikto Formatted Output +``` +Nikto Scan Results for http://example.com +================================================== +Host: example.com (192.168.1.1) +Port: 80 +Server: Apache/2.4.41 (Ubuntu) + +FINDINGS (3) +-------------------------------------------------- +[OSVDB-3092] /admin/ + Admin directory found - potentially sensitive + +[OSVDB-877] /backup/ + Backup directory accessible + +/config.php + PHP configuration file exposed +``` + +### Nuclei Severity Summary +``` +Nuclei Scan Results for https://example.com +================================================== + +SEVERITY SUMMARY +------------------------------ + Critical: 1 + High: 2 + Medium: 5 + Low: 3 + Info: 10 + Total: 21 + +CRITICAL (1) +-------------------------------------------------- +[cve-2021-44228] Log4Shell RCE + URL: https://example.com/api + CVE: CVE-2021-44228 +``` + +### SSLScan Analysis +``` +SSL/TLS Scan Results for example.com:443 +================================================== + +PROTOCOL SUPPORT +------------------------------ + SSL 2.0: disabled + SSL 3.0: ENABLED ⚠️ + TLS 1.0: ENABLED ⚠️ + TLS 1.1: disabled + TLS 1.2: ENABLED + TLS 1.3: ENABLED + +CIPHER SUITES +------------------------------ + Strong: 8 + Weak/Insecure: 2 + Total: 10 + + WEAK CIPHERS: + TLSv1.2 RC4-SHA (128 bits) + TLSv1.2 DES-CBC3-SHA (112 bits) +``` + +--- + +## Test Coverage + +**Test File:** `test/pentest/parsers.test.ts` + +**Results:** +``` + 25 pass + 0 fail + 72 expect() calls +``` + +**Test Categories:** + +| Parser | Tests | +|--------|-------| +| NiktoParser | 5 tests - text/JSON parsing, formatting, findings | +| NucleiParser | 4 tests - JSONL parsing, CVE extraction, summary | +| GobusterParser | 5 tests - text/JSON parsing, sensitive path detection | +| FfufParser | 5 tests - JSON parsing, formatting, findings | +| SslscanParser | 6 tests - protocol detection, cipher analysis, CVE findings | + +--- + +## Severity Classification + +Each parser implements intelligent severity classification: + +| Severity | Examples | +|----------|----------| +| Critical | RCE, SQL injection, exposed .git repos, Heartbleed | +| High | XSS, file inclusion, backup files, deprecated SSL | +| Medium | OSVDB findings, deprecated TLS, admin panels | +| Low | Information disclosure, headers, self-signed certs | +| Info | Technology detection, service identification | + +--- + +## Future Enhancements + +Potential improvements: + +1. **Additional Parsers** + - WPScan (WordPress vulnerabilities) + - SQLMap (SQL injection findings) + - Enum4linux (SMB enumeration) + - Testssl.sh (detailed TLS analysis) + +2. **Enhanced Analysis** + - CVSS score calculation + - Exploit availability lookup + - Remediation priority scoring + +3. **Output Formats** + - Export to SARIF + - Export to CSV/Excel + - HTML report generation + +--- + +## Dependencies + +| Dependency | Purpose | +|------------|---------| +| Zod | Schema validation | +| PentestTypes | Finding type definitions | +| Findings | Finding persistence | + +--- + +## Related Documentation + +- [PHASE3.md](./PHASE3.md) - Pentest Agent MVP +- [PENTEST.md](./PENTEST.md) - Pentest module reference +- [GOVERNANCE.md](./GOVERNANCE.md) - Governance system diff --git a/docs/PHASE05-report-generation.md b/docs/PHASE05-report-generation.md new file mode 100644 index 00000000000..4f2f9eaedb7 --- /dev/null +++ b/docs/PHASE05-report-generation.md @@ -0,0 +1,435 @@ +# Phase 5: Report Generation - Implementation Report + +This document describes what was implemented in Phase 5 of the cyxwiz project. + +--- + +## Overview + +Phase 5 added security assessment report generation capabilities, enabling automated creation of professional reports in Markdown, HTML, and JSON formats from collected findings. + +**Goal:** Generate comprehensive security assessment reports from findings and scan data. + +**Status:** Complete + +--- + +## Deliverables + +### 1. Report Generation System + +A complete report generation system located at `src/pentest/reports/`: + +| Component | Purpose | +|-----------|---------| +| Types | Zod schemas for report configuration and data | +| Markdown Generator | Generates styled Markdown reports | +| HTML Generator | Generates styled HTML reports with charts | +| Reports Namespace | Public API for report generation | + +### 2. Report Types + +Four report types with different focuses: + +| Type | Focus | Use Case | +|------|-------|----------| +| Executive | High-level overview | Management briefings | +| Technical | Full details with evidence | Security team review | +| Compliance | Open issues for compliance | Audit requirements | +| Full | Complete data with raw scans | Archival/reference | + +### 3. Output Formats + +Three output formats supported: + +| Format | Features | +|--------|----------| +| Markdown | Portable, version-control friendly | +| HTML | Styled, printable, includes charts | +| JSON | Machine-readable, API integration | + +--- + +## Report Sections + +### Executive Summary +- Overall risk assessment (CRITICAL, HIGH, MEDIUM, LOW, INFORMATIONAL) +- Key statistics table +- Summary paragraph based on findings + +### Methodology +- Standard assessment methodology description +- Customizable methodology text +- Tool attribution + +### Scope +- In-scope targets +- Exclusions list +- Scope description + +### Findings Summary +- Table with all findings +- Severity badges +- Status tracking + +### Detailed Findings +- Grouped by severity (Critical → Info) +- Metadata table (severity, status, target, service) +- Description and evidence +- CVE references with NVD links +- Remediation guidance + +### Remediation Summary +- Immediate Action Required (Critical/High) +- Short-Term Remediation (Medium) +- Long-Term Improvements (Low/Info) + +### Appendix +- Raw scan data (optional) +- Command history +- Scan duration/timestamps + +--- + +## Files Created + +``` +packages/opencode/src/pentest/reports/ +├── index.ts # Reports namespace and main API +├── types.ts # Zod schemas for configuration +├── markdown.ts # Markdown report generator +└── html.ts # HTML report generator with CSS + +packages/opencode/src/pentest/ +└── report-tool.ts # Agent tool for report generation + +packages/opencode/test/pentest/ +└── reports.test.ts # Report generator tests (25+ tests) +``` + +## Files Modified + +| File | Changes | +|------|---------| +| `src/pentest/index.ts` | Added report exports | +| `src/tool/registry.ts` | Registered ReportTool | + +--- + +## API Reference + +### Reports Namespace + +```typescript +import { Reports } from "./pentest" + +// Generate a report +const report = await Reports.generate({ + title: "Q1 Security Assessment", + type: "technical", + format: "markdown", + organization: "Acme Corp", + assessor: "Security Team", +}, { + sessionID: "session_abc", + storage: "file", +}) + +// Write to file +await Bun.write("report.md", report.content) +``` + +### Convenience Methods + +```typescript +// Executive summary (critical/high only) +const exec = await Reports.generateExecutive({ + title: "Executive Summary", + format: "html", +}) + +// Full technical report +const tech = await Reports.generateTechnical({ + title: "Technical Report", + includeRawData: true, +}) + +// Compliance report (open issues only) +const compliance = await Reports.generateCompliance({ + title: "Compliance Report", + format: "html", +}) + +// Multiple formats at once +const reports = await Reports.generateMultiple( + { title: "Assessment Report" }, + ["markdown", "html", "json"] +) +``` + +### Configuration Options + +```typescript +interface ReportConfig { + title: string // Report title + type: "executive" | "technical" | "compliance" | "full" + format: "markdown" | "html" | "json" + organization?: string // Client/org name + assessor?: string // Tester name + dateRange?: { start: number; end: number } + scope?: { + targets: string[] + description?: string + exclusions?: string[] + } + severityFilter?: { + include?: Severity[] // Only include these + exclude?: Severity[] // Exclude these + minSeverity?: Severity // Minimum severity + } + statusFilter?: Status[] // Filter by status + includeRawData?: boolean // Include scan data + includeRemediation?: boolean // Include remediation + includeExecutiveSummary?: boolean + includeMethodology?: boolean + includeCharts?: boolean // HTML only + methodology?: string // Custom methodology text + customCss?: string // HTML custom CSS + headerContent?: string + footerContent?: string +} +``` + +--- + +## ReportTool (Agent Tool) + +The `report` tool allows the AI agent to generate reports: + +### Tool Parameters + +| Parameter | Type | Description | +|-----------|------|-------------| +| title | string | Report title | +| type | enum | executive, technical, compliance, full | +| format | enum | markdown, html, json | +| organization | string | Client name | +| assessor | string | Tester name | +| minSeverity | enum | Minimum severity filter | +| includeRawData | boolean | Include scan data | +| outputFile | string | Save to file path | + +### Example Usage + +``` +Use the report tool to generate an executive summary: +- type: executive +- format: html +- title: "Q1 2024 Assessment" +- organization: "Example Corp" +- outputFile: "/tmp/report.html" +``` + +--- + +## Output Examples + +### Markdown Report + +```markdown +# Security Assessment Report + +**Client:** Acme Corp +**Assessor:** Security Team +**Report Generated:** 1/15/2024, 2:30:00 PM +**Report ID:** report_l8x9m2_a1b2c3 + +--- + +## Executive Summary + +### Overall Risk Assessment: **CRITICAL** + +This security assessment identified **15 findings**, including **3 critical +or high severity issues** that require immediate attention. These +vulnerabilities could potentially allow unauthorized access, data breaches, +or system compromise if left unaddressed. + +### Key Statistics + +| Severity | Count | +|----------|-------| +| Critical | 1 | +| High | 2 | +| Medium | 5 | +| Low | 4 | +| Info | 3 | +| **Total** | **15** | +``` + +### HTML Report Features + +- Responsive design +- Color-coded severity badges +- Statistics cards +- Collapsible sections +- Print-friendly styles +- Chart visualization +- XSS-safe escaping + +### JSON Report Structure + +```json +{ + "config": { /* report configuration */ }, + "findings": [ /* array of findings */ ], + "scans": [ /* optional scan data */ ], + "severityStats": { + "critical": 1, + "high": 2, + "medium": 5, + "low": 4, + "info": 3, + "total": 15 + }, + "statusStats": { + "open": 12, + "confirmed": 2, + "mitigated": 1, + "false_positive": 0 + }, + "generatedAt": 1705337400000, + "reportId": "report_l8x9m2_a1b2c3" +} +``` + +--- + +## Test Coverage + +**Test File:** `test/pentest/reports.test.ts` + +**Test Categories:** + +| Category | Tests | +|----------|-------| +| Markdown Generator | 12 tests - sections, formatting, severity | +| HTML Generator | 8 tests - structure, styles, escaping | +| Report Types | 2 tests - executive vs technical | +| Remediation | 2 tests - priority grouping | + +**Test Scenarios:** +- All sections present in generated output +- Severity statistics correctly calculated +- Findings grouped by severity level +- Risk level determination (Critical → Informational) +- HTML escaping for XSS prevention +- Custom CSS injection +- Empty findings handling +- Organization/assessor metadata + +--- + +## Integration + +### With Findings System + +Reports automatically fetch findings from storage: + +```typescript +const report = await Reports.generate( + { title: "Assessment" }, + { + sessionID: "session_abc", // Filter by session + storage: "file", // Use file storage + } +) +``` + +### With Scan Data + +Include raw scan data in appendix: + +```typescript +const report = await Reports.generate({ + title: "Full Report", + type: "full", + includeRawData: true, // Includes scan commands/output +}) +``` + +### Severity Filtering + +Filter findings by severity: + +```typescript +// Executive: only high severity and above +const exec = await Reports.generateExecutive({ title: "Exec" }) + +// Custom filter +const report = await Reports.generate({ + title: "Critical Issues", + severityFilter: { + minSeverity: "critical", + }, +}) +``` + +--- + +## Severity Badge Reference + +| Severity | Markdown | HTML Class | +|----------|----------|------------| +| Critical | :red_circle: Critical | `severity-critical` | +| High | :orange_circle: High | `severity-high` | +| Medium | :yellow_circle: Medium | `severity-medium` | +| Low | :green_circle: Low | `severity-low` | +| Info | :blue_circle: Info | `severity-info` | + +--- + +## Future Enhancements + +Potential improvements: + +1. **Additional Formats** + - PDF generation (via headless browser) + - DOCX export + - SARIF for IDE integration + +2. **Enhanced Charts** + - Trend analysis over time + - Category breakdown + - CVSS distribution + +3. **Templates** + - Custom report templates + - Company branding + - Multi-language support + +4. **Collaboration** + - Report versioning + - Collaborative editing + - Comment system + +--- + +## Dependencies + +| Dependency | Purpose | +|------------|---------| +| Zod | Schema validation | +| PentestTypes | Finding type definitions | +| Findings | Finding retrieval | +| Tool | Agent tool framework | +| Log | Structured logging | + +--- + +## Related Documentation + +- [PHASE4.md](./PHASE4.md) - Multi-Tool Parsers +- [PHASE3.md](./PHASE3.md) - Pentest Agent MVP +- [PENTEST.md](./PENTEST.md) - Pentest module reference +- [GOVERNANCE.md](./GOVERNANCE.md) - Governance system diff --git a/docs/PHASE06-continuous-monitoring.md b/docs/PHASE06-continuous-monitoring.md new file mode 100644 index 00000000000..c530718efa4 --- /dev/null +++ b/docs/PHASE06-continuous-monitoring.md @@ -0,0 +1,381 @@ +# Phase 6: Continuous Monitoring - Implementation Report + +This document describes what was implemented in Phase 6 of the cyxwiz project. + +--- + +## Overview + +Phase 6 added continuous monitoring capabilities, enabling scheduled security scans with diff detection and alerting for new vulnerabilities. + +**Goal:** Automate recurring security scans and alert when new issues are discovered. + +**Status:** Complete + +--- + +## Features + +1. **Scheduled Scans**: Run security tools on interval or cron schedules +2. **Diff Detection**: Compare findings between runs, identify new/resolved issues +3. **Alerting**: Publish events when new vulnerabilities are discovered +4. **Multi-Tool Support**: Run any combination of nmap, nuclei, nikto, etc. + +--- + +## Module Structure + +``` +src/pentest/monitoring/ +├── index.ts # Main exports +├── types.ts # Zod schemas (Monitor, MonitorRun, Schedule) +├── events.ts # BusEvent definitions (12 events) +├── scheduler.ts # Timer-based scheduler with Instance state +├── cron-parser.ts # Lightweight cron expression parser +├── runner.ts # Monitor execution and tool invocation +├── diff.ts # Finding fingerprinting and comparison +├── alerter.ts # Alert handling (bus, log, webhook) +├── storage.ts # Monitor and run persistence +└── tool.ts # MonitorTool for agent interaction +``` + +--- + +## Data Models + +### Monitor + +```typescript +{ + id: string // Unique ID (mon_xxx) + name: string // Human-readable name + description?: string + sessionID: string // Parent session + targets: string[] // IPs, hostnames, URLs + tools: MonitorToolConfig[] // Tools to run + schedule: Schedule // Interval or cron + status: MonitorStatus // active, paused, disabled, error + alerts: AlertConfig // Alert settings + createdAt: number + lastRunAt?: number + nextRunAt?: number + runCount: number +} +``` + +### MonitorRun + +```typescript +{ + id: string // Unique ID (run_xxx) + monitorID: string + sessionID: string + startTime: number + endTime?: number + status: MonitorRunStatus // running, completed, failed, cancelled + scanIDs: string[] // Scans created + findingIDs: string[] // Findings created + newFindingIDs: string[] // New since last run + resolvedFindingIDs: string[] // Gone since last run + runNumber: number +} +``` + +### Schedule Types + +```typescript +// Interval-based (e.g., every hour) +{ type: "interval", intervalMs: 3600000, maxRuns?: 0 } + +// Cron-based (e.g., daily at 2 AM) +{ type: "cron", expression: "0 2 * * *", timezone?: string } +``` + +--- + +## Key Components + +### 1. Scheduler (`scheduler.ts`) + +- Uses native `setTimeout` with `.unref()` (no external dependencies) +- Instance-scoped state via `Instance.state()` +- Prevents concurrent runs of the same monitor +- Auto-reschedules after completion +- Supports max runs limit for interval schedules + +### 2. Cron Parser (`cron-parser.ts`) + +- Parses standard 5-field cron expressions: `minute hour dayOfMonth month dayOfWeek` +- Supports: wildcards (`*`), ranges (`1-5`), steps (`*/5`), lists (`1,3,5`) +- Calculates next run time +- Validates expressions +- Provides human-readable descriptions + +### 3. Diff Engine (`diff.ts`) + +- Fingerprints findings by: title (normalized), target (normalized), port, service, severity +- Uses SHA-256 hash for comparison +- Identifies: new, resolved, unchanged findings between runs +- Filters by minimum severity + +### 4. Alerter (`alerter.ts`) + +- Channels: bus (events), log (structured), webhook (HTTP POST) +- Severity filtering (alert only on high+ severity, etc.) +- Cooldown to prevent alert spam (default: 5 minutes) +- Webhook payload includes full finding details + +### 5. Monitor Runner (`runner.ts`) + +- Invokes existing tools (NmapTool, SecToolsTool) +- Creates minimal tool context for auto-approval +- Collects findings per run +- Performs diff against previous run +- Triggers alerts based on configuration + +--- + +## Events + +| Event | Description | +|-------|-------------| +| `pentest.monitor.scheduled` | Monitor scheduled for next execution | +| `pentest.monitor.run_started` | Run began | +| `pentest.monitor.run_completed` | Run finished with statistics | +| `pentest.monitor.run_failed` | Run failed with error | +| `pentest.monitor.paused` | Monitor was paused | +| `pentest.monitor.resumed` | Monitor was resumed | +| `pentest.monitor.cancelled` | Monitor was cancelled | +| `pentest.monitor.created` | New monitor created | +| `pentest.monitor.updated` | Monitor configuration changed | +| `pentest.monitor.deleted` | Monitor was deleted | +| `pentest.monitor.alert.new_vulnerabilities` | New findings detected | +| `pentest.monitor.alert.resolved` | Findings resolved | + +--- + +## MonitorTool Actions + +| Action | Description | +|--------|-------------| +| `create` | Create a new monitor with targets, tools, schedule | +| `list` | List all monitors with status | +| `get` | Get detailed monitor info and recent runs | +| `pause` | Pause a running monitor | +| `resume` | Resume a paused monitor | +| `delete` | Delete a monitor | +| `trigger` | Trigger an immediate scan | +| `status` | Get scheduler status (running, scheduled) | + +--- + +## Files Created + +``` +packages/opencode/src/pentest/monitoring/ +├── types.ts # 11 Zod schemas +├── events.ts # 12 BusEvent definitions +├── scheduler.ts # Scheduler with Instance state +├── cron-parser.ts # Cron expression parser +├── runner.ts # Monitor execution +├── diff.ts # Finding comparison +├── alerter.ts # Alert channels +├── storage.ts # Monitor/run persistence +├── tool.ts # MonitorTool for agents +└── index.ts # Module exports + +packages/opencode/test/pentest/ +└── monitoring.test.ts # 25+ tests +``` + +## Files Modified + +| File | Changes | +|------|---------| +| `src/pentest/index.ts` | Added monitoring exports | +| `src/tool/registry.ts` | Registered MonitorTool | + +--- + +## Usage Examples + +### Create a Monitor (Agent Tool) + +``` +action="create" +name="Daily Security Scan" +targets=["192.168.1.0/24", "https://app.example.com"] +tools=[ + { tool: "nmap", args: "-sV" }, + { tool: "nuclei", args: "-t cves/" } +] +scheduleType="cron" +cronExpression="0 2 * * *" +alertMinSeverity="medium" +``` + +### Programmatic Usage + +```typescript +import { createMonitor, Scheduler, MonitoringEvents } from "./pentest/monitoring" +import { Bus } from "./bus" + +// Create a monitor +const monitor = await createMonitor({ + name: "Hourly Port Scan", + sessionID: ctx.sessionID, + targets: ["10.0.0.1"], + tools: [{ tool: "nmap", createFindings: true }], + schedule: { type: "interval", intervalMs: 3600000 }, + alerts: { + enabled: true, + minSeverity: "high", + channels: ["bus", "webhook"], + webhookUrl: "https://slack.example.com/webhook", + }, +}) + +// Schedule it +await Scheduler.scheduleMonitor(monitor) + +// Subscribe to alerts +Bus.subscribe(MonitoringEvents.NewVulnerabilitiesDetected, (event) => { + console.log(`New vulnerabilities: ${event.summary.total}`) + console.log(`Critical: ${event.summary.critical}`) +}) +``` + +### Trigger Immediate Scan + +```typescript +const run = await Scheduler.triggerNow(monitorID) +console.log(`Found ${run.findingIDs.length} findings`) +console.log(`New: ${run.newFindingIDs.length}`) +console.log(`Resolved: ${run.resolvedFindingIDs.length}`) +``` + +--- + +## Storage Layout + +``` +pentest/monitoring/ + monitors/ + mon_abc123.json # Monitor configuration + mon_def456.json + runs/ + mon_abc123/ + run_xyz789.json # Run record with finding lists + run_uvw012.json +``` + +--- + +## Cron Expression Reference + +| Expression | Description | +|------------|-------------| +| `* * * * *` | Every minute | +| `0 * * * *` | Every hour | +| `0 0 * * *` | Daily at midnight | +| `0 2 * * *` | Daily at 2 AM | +| `0 */6 * * *` | Every 6 hours | +| `0 9-17 * * 1-5` | Hourly 9-5 on weekdays | +| `*/15 * * * *` | Every 15 minutes | +| `0 0 1 * *` | Monthly on the 1st | + +--- + +## Test Coverage + +**Test File:** `test/pentest/monitoring.test.ts` + +**Test Categories:** + +| Category | Tests | +|----------|-------| +| CronParser.parse | 7 tests - wildcards, values, ranges, steps, lists | +| CronParser.nextRun | 4 tests - next minute, hour, midnight, specific | +| CronParser.validate | 2 tests - valid/invalid expressions | +| CronParser.describe | 1 test - human-readable descriptions | +| DiffEngine.fingerprint | 4 tests - consistency, normalization | +| DiffEngine.compare | 6 tests - new, resolved, unchanged, mixed | +| DiffEngine.summarizeSeverity | 2 tests - counts, empty | +| DiffEngine.filterBySeverity | 1 test - minimum severity | + +--- + +## Alert Webhook Payload + +```json +{ + "type": "new_vulnerabilities", + "monitor": { + "id": "mon_abc123", + "name": "Daily Security Scan" + }, + "run": { + "id": "run_xyz789", + "number": 5 + }, + "findings": [ + { + "id": "finding_123", + "title": "SQL Injection in login form", + "severity": "critical", + "target": "https://app.example.com", + "port": 443 + } + ], + "summary": { + "critical": 1, + "high": 2, + "medium": 3, + "low": 0, + "info": 0, + "total": 6 + }, + "timestamp": 1705337400000 +} +``` + +--- + +## Dependencies + +- No external packages required +- Uses existing: Storage, Bus, NmapTool, SecToolsTool, Findings +- Native Node.js/Bun: setTimeout, crypto (SHA-256) + +--- + +## Future Enhancements + +1. **Advanced Scheduling** + - Timezone support for cron + - Schedule exceptions (skip holidays) + - Maintenance windows + +2. **Alert Channels** + - Email notifications + - Slack integration + - PagerDuty integration + +3. **Dashboard** + - Monitor status overview + - Trend graphs + - Alert history + +4. **Comparison Features** + - Cross-monitor diff + - Historical trend analysis + - Baseline comparisons + +--- + +## Related Documentation + +- [PHASE5.md](./PHASE5.md) - Report Generation +- [PHASE4.md](./PHASE4.md) - Multi-Tool Parsers +- [PHASE3.md](./PHASE3.md) - Pentest Agent MVP +- [PENTEST.md](./PENTEST.md) - Pentest module reference diff --git a/docs/PHASE07-exploit-framework.md b/docs/PHASE07-exploit-framework.md new file mode 100644 index 00000000000..1687328eb1b --- /dev/null +++ b/docs/PHASE07-exploit-framework.md @@ -0,0 +1,388 @@ +# Phase 7: Exploit Framework Integration - Implementation Report + +This document describes what was implemented in Phase 7 of the cyxwiz project. + +--- + +## Overview + +Phase 7 added exploit framework integration, enabling exploit search, matching, and safe execution with searchsploit and metasploit. + +**Goal:** Enable automated exploit matching for findings with comprehensive safety controls. + +**Status:** Complete + +--- + +## Features + +1. **Searchsploit Integration**: Parse Exploit-DB output, match by CVE/service +2. **Metasploit Integration**: Search MSF modules, get info, run checks +3. **Exploit Matching**: Auto-suggest exploits based on findings +4. **Safe Execution**: Dry-run default, mandatory confirmation, scope validation + +--- + +## Module Structure + +``` +src/pentest/exploits/ +├── index.ts # Module exports +├── types.ts # Zod schemas (12 types) +├── events.ts # BusEvent definitions (7 events) +├── matcher.ts # ExploitMatcher service +├── storage.ts # Match/execution persistence +├── tool.ts # ExploitTool for agent +└── parsers/ + ├── index.ts # Parser exports + ├── searchsploit.ts # Searchsploit output parser + └── metasploit.ts # MSF output parser +``` + +--- + +## Data Models + +### ExploitMatch + +```typescript +{ + id: string // Unique ID (match_xxx) + findingID: string // Associated finding + source: ExploitSource // exploit-db, metasploit, etc. + exploitID: string // EDB-ID or MSF module path + title: string // Exploit title + description?: string + type?: ExploitType // remote, local, webapps, etc. + rank?: ExploitRank // excellent, great, good, etc. + confidence: Confidence // high, medium, low + matchReason: string // Why this exploit matches + cve?: string[] // Associated CVEs + url?: string // Exploit-DB URL + path?: string // Local file path + status: MatchStatus // suggested, verified, tested, dismissed + createdAt: number + verifiedAt?: number +} +``` + +### SearchsploitEntry + +```typescript +{ + id: string // EDB-ID + title: string // Exploit title + path: string // Local file path + date?: string // Publication date + author?: string + type?: ExploitType + platform?: Platform + port?: number + cve?: string[] + verified?: boolean // Exploit-DB verified +} +``` + +### MetasploitModule + +```typescript +{ + name: string // Full module path + fullname?: string // Human-readable name + type: ExploitType + rank?: ExploitRank + disclosure_date?: string + description?: string + author?: string[] + references?: string[] + cve?: string[] + platforms?: Platform[] + options?: ModuleOption[] + check?: boolean // Has check method + privileged?: boolean +} +``` + +--- + +## Key Components + +### 1. SearchsploitParser (`parsers/searchsploit.ts`) + +- Parses JSON output from `searchsploit -j` +- Falls back to text parsing for plain output +- Extracts CVEs from codes and titles +- Maps platform and exploit type + +### 2. MetasploitParser (`parsers/metasploit.ts`) + +- Parses msfconsole search output +- Extracts module info from `info` command +- Maps module types (exploit, auxiliary, post, etc.) +- Maps rank (excellent, great, good, etc.) + +### 3. ExploitMatcher (`matcher.ts`) + +- Builds search queries from findings (CVE, service, version) +- Searches both searchsploit and metasploit +- Deduplicates by exploitID +- Ranks matches by confidence, MSF rank, CVE count + +### 4. ExploitStorage (`storage.ts`) + +- Saves and retrieves exploit matches +- Supports file and memory storage modes +- Saves execution results for audit +- Filters by findingID, source, status + +### 5. ExploitTool (`tool.ts`) + +- Agent-facing tool for exploit operations +- Actions: search, suggest, info, check, execute, list +- Scope validation via governance +- Dry-run default for execution +- Never auto-approves exploit commands + +--- + +## Events + +| Event | Description | +|-------|-------------| +| `pentest.exploit.search_completed` | Search finished | +| `pentest.exploit.suggestions_generated` | Matches found for finding | +| `pentest.exploit.match_updated` | Match status changed | +| `pentest.exploit.check_executed` | Check ran | +| `pentest.exploit.execution_dry_run` | Dry run performed | +| `pentest.exploit.execution_completed` | Real execution completed | +| `pentest.exploit.execution_failed` | Execution failed | + +--- + +## ExploitTool Actions + +| Action | Description | +|--------|-------------| +| `search` | Search exploit databases by keyword/CVE | +| `suggest` | Auto-suggest exploits for a finding | +| `info` | Get detailed module information | +| `check` | Run exploit check (verify without exploit) | +| `execute` | Execute exploit (dry-run default, requires confirmation) | +| `list` | List saved exploit matches | + +--- + +## Safety Requirements + +1. **Scope Validation**: All targets checked against GovernanceScope before any operation +2. **Permission System**: All commands go through ctx.ask() for user confirmation +3. **Dry-Run Default**: execute action defaults to dryRun=true +4. **Never Auto-Approve**: Exploit commands use `always: []` to prevent auto-approval +5. **Audit Trail**: All operations publish events and save execution results + +--- + +## Files Created + +``` +packages/opencode/src/pentest/exploits/ +├── types.ts # 12 Zod schemas +├── events.ts # 7 BusEvent definitions +├── matcher.ts # Exploit matching service +├── storage.ts # Match/execution persistence +├── tool.ts # ExploitTool for agents +├── index.ts # Module exports +└── parsers/ + ├── index.ts # Parser exports + ├── searchsploit.ts # Searchsploit parser + └── metasploit.ts # Metasploit parser + +packages/opencode/test/pentest/ +└── exploits.test.ts # 30+ tests +``` + +## Files Modified + +| File | Changes | +|------|---------| +| `src/pentest/index.ts` | Added exploit exports | +| `src/tool/registry.ts` | Registered ExploitTool | + +--- + +## Usage Examples + +### Search for Exploits (Agent Tool) + +``` +action="search" +query="apache 2.4" +source="both" +``` + +### Suggest Exploits for Finding + +``` +action="suggest" +findingID="finding_abc123" +``` + +### Get Module Info + +``` +action="info" +module="exploit/multi/http/apache_mod_cgi_bash_env_exec" +``` + +### Run Vulnerability Check + +``` +action="check" +module="exploit/linux/http/apache_path_traversal_rce" +target="192.168.1.1" +``` + +### Execute Exploit (Dry Run) + +``` +action="execute" +module="exploit/linux/http/apache_path_traversal_rce" +target="192.168.1.1" +dryRun=true +``` + +### Execute Exploit (Real) + +``` +action="execute" +module="exploit/linux/http/apache_path_traversal_rce" +target="192.168.1.1" +dryRun=false +options={"RPORT": 8080} +``` + +### Programmatic Usage + +```typescript +import { ExploitMatcher, ExploitStorage, ExploitEvents } from "./pentest/exploits" +import { Bus } from "./bus" + +// Match finding to exploits +const matches = await ExploitMatcher.matchFinding(finding, { + searchsploit: true, + metasploit: true, + limit: 10, +}) + +// Rank matches +const ranked = ExploitMatcher.rankMatches(matches) + +// Save matches +for (const match of ranked) { + await ExploitStorage.saveMatch(match) +} + +// Subscribe to events +Bus.subscribe(ExploitEvents.SuggestionsGenerated, (event) => { + console.log(`Found ${event.matchCount} exploits for ${event.findingID}`) +}) +``` + +--- + +## Storage Layout + +``` +pentest/exploits/ + matches/ + match_abc123.json # Exploit match records + executions/ + exec_xyz789.json # Execution audit records +``` + +--- + +## Matching Algorithm + +1. **CVE Matching (High Confidence)** + - Extract CVEs from finding + - Search both databases by CVE ID + - Mark matches as "high" confidence + +2. **Service/Version Matching (Medium Confidence)** + - Extract service name from finding + - Extract version from evidence field + - Map port to common service names + - Search by combined queries + +3. **Deduplication** + - Key by `source:exploitID` + - Keep first occurrence + +4. **Ranking** + - Sort by confidence (high > medium > low) + - Then by MSF rank (excellent > great > good > normal > average > low) + - Then by CVE count (more is better) + +--- + +## Test Coverage + +**Test File:** `test/pentest/exploits.test.ts` + +**Test Categories:** + +| Category | Tests | +|----------|-------| +| SearchsploitParser.parse | 3 tests - JSON, text, CVE extraction | +| SearchsploitParser.format | 2 tests - formatting, empty results | +| SearchsploitParser.toMatches | 1 test - match generation | +| MetasploitParser.parseSearch | 3 tests - parsing, CVE, auxiliary | +| MetasploitParser.format | 1 test - formatting | +| MetasploitParser.toMatches | 1 test - match generation | +| ExploitTypes schemas | 4 tests - validation | +| ExploitStorage | 8 tests - CRUD, filtering | +| ExploitMatcher.buildQueries | 3 tests - service, port, version | +| ExploitMatcher.rankMatches | 3 tests - confidence, rank, CVE | + +--- + +## Dependencies + +- No external packages required +- Uses existing: Storage, Bus, Findings, GovernanceScope, GovernanceMatcher +- CLI tools: searchsploit, msfconsole (must be installed) + +--- + +## Future Enhancements + +1. **Additional Sources** + - GitHub POC repositories + - Nuclei templates + - PacketStorm + - CVE Details + +2. **Enhanced Matching** + - Version range matching + - Platform-aware suggestions + - Exploit chain detection + +3. **Execution Features** + - Session management + - Payload customization + - Post-exploitation modules + +4. **Reporting** + - Exploit verification reports + - Attack path visualization + - Timeline of exploitation attempts + +--- + +## Related Documentation + +- [PHASE6.md](./PHASE6.md) - Continuous Monitoring +- [PHASE5.md](./PHASE5.md) - Report Generation +- [PHASE4.md](./PHASE4.md) - Multi-Tool Parsers +- [PENTEST.md](./PENTEST.md) - Pentest module reference diff --git a/docs/PHASE08-web-app-scanner.md b/docs/PHASE08-web-app-scanner.md new file mode 100644 index 00000000000..61667efb976 --- /dev/null +++ b/docs/PHASE08-web-app-scanner.md @@ -0,0 +1,418 @@ +# Phase 8: Web Application Scanner - Implementation Report + +This document describes what was implemented in Phase 8 of the cyxwiz project. + +--- + +## Overview + +Phase 8 added comprehensive web application scanning capabilities, including crawling, multi-tool orchestration, and OWASP categorization. + +**Goal:** Enable automated web application security scanning with coordinated tool execution. + +**Status:** Complete + +--- + +## Features + +1. **Web Crawler**: Discover URLs and forms using native fetch() with regex-based extraction +2. **Scan Orchestration**: Coordinate multiple security tools with pre-defined profiles +3. **OWASP Top 10 2021**: Categorize findings by OWASP Top 10 categories +4. **New Parsers**: WPScanParser and WhatWebParser for WordPress/fingerprinting + +--- + +## Module Structure + +``` +src/pentest/webscan/ +├── index.ts # Module exports +├── types.ts # Zod schemas (20+ types) +├── events.ts # BusEvent definitions (9 events) +├── crawler.ts # Web crawler with regex extraction +├── orchestrator.ts # Scan orchestration service +├── profiles.ts # Pre-defined scan profiles +├── storage.ts # Crawl/scan persistence +├── owasp.ts # OWASP categorization +├── tool.ts # WebScanTool for agent +└── parsers/ + ├── index.ts # Parser exports + ├── wpscan.ts # WPScan JSON parser + └── whatweb.ts # WhatWeb JSON parser +``` + +--- + +## Data Models + +### CrawlResult + +```typescript +{ + id: string + target: string // Base URL + urls: DiscoveredUrl[] // All discovered URLs + forms: DiscoveredForm[] // All discovered forms + stats: { + urlsDiscovered: number + urlsVisited: number + formsDiscovered: number + maxDepthReached: number + errorCount: number + duration: number + } + options: CrawlOptions + startedAt: number + completedAt?: number + status: Status // pending, running, completed, failed, stopped +} +``` + +### ScanResult + +```typescript +{ + id: string + target: string + profile: ProfileId // quick, standard, thorough, passive, custom + crawlID?: string + tools: ToolExecution[] + findings: string[] // Finding IDs + stats: { + urlsScanned: number + toolsRun: number + toolsFailed: number + findingsCount: number + criticalCount: number + highCount: number + mediumCount: number + lowCount: number + infoCount: number + duration: number + } + startedAt: number + completedAt?: number + status: Status +} +``` + +--- + +## Scan Profiles + +| Profile | Crawl | Tools | Use Case | +|---------|-------|-------|----------| +| `quick` | depth=1, max=50 | whatweb, nikto | Fast initial assessment | +| `standard` | depth=2, max=200 | whatweb, nikto, gobuster, nuclei | Normal pentest | +| `thorough` | depth=3, max=500 | All web tools | Comprehensive scan | +| `passive` | none | whatweb, wafw00f | No active testing | +| `custom` | configurable | user-selected | Custom configuration | + +--- + +## Key Components + +### 1. WebCrawler (`crawler.ts`) + +- Uses native `fetch()` for HTTP requests +- Regex-based link extraction (no DOM library) +- Regex-based form extraction with input detection +- Respects robots.txt when enabled +- URL normalization and same-origin filtering +- Configurable depth, URL limits, and delays + +### 2. ScanOrchestrator (`orchestrator.ts`) + +- Executes crawl if profile.crawl.enabled +- Runs tools sequentially with error handling +- Parses tool output to generate findings +- Aggregates statistics across tools +- Publishes events for progress tracking + +### 3. ScanProfiles (`profiles.ts`) + +- Pre-defined profiles for common scenarios +- Custom profile creation with overrides +- Per-tool options configuration + +### 4. OwaspCategorization (`owasp.ts`) + +- Pattern-based categorization using regex and keywords +- Maps findings to OWASP Top 10 2021 categories +- Confidence scoring based on match count +- CVE presence automatically maps to A06 + +### 5. WebScanTool (`tool.ts`) + +- Agent-facing tool for web scanning operations +- Actions: crawl, scan, quick-scan, full-scan, urls, forms, status, owasp, profiles +- Scope validation via GovernanceScope +- Permission requests for network/tool access + +### 6. Parsers + +- **WPScanParser**: Parses WPScan JSON output for WordPress vulnerabilities +- **WhatWebParser**: Parses WhatWeb JSON/text output for technology fingerprinting + +--- + +## Events + +| Event | Description | +|-------|-------------| +| `pentest.webscan.crawl_started` | Crawl began | +| `pentest.webscan.url_discovered` | New URL found | +| `pentest.webscan.form_discovered` | New form found | +| `pentest.webscan.crawl_completed` | Crawl finished | +| `pentest.webscan.scan_started` | Scan began | +| `pentest.webscan.tool_started` | Tool execution started | +| `pentest.webscan.tool_completed` | Tool execution finished | +| `pentest.webscan.tool_failed` | Tool execution failed | +| `pentest.webscan.scan_completed` | Scan finished | + +--- + +## WebScanTool Actions + +| Action | Description | +|--------|-------------| +| `crawl` | Crawl a target URL to discover pages/forms | +| `scan` | Run scan with specific profile | +| `quick-scan` | Quick scan (alias for quick profile) | +| `full-scan` | Thorough scan (alias for thorough profile) | +| `urls` | List discovered URLs from a crawl | +| `forms` | List discovered forms from a crawl | +| `status` | Get status of running crawl/scan | +| `owasp` | Categorize findings by OWASP Top 10 | +| `profiles` | List available scan profiles | + +--- + +## OWASP Top 10 2021 Categorization + +| Category | Detection Patterns | +|----------|-------------------| +| A01:2021 Broken Access Control | path traversal, IDOR, privilege escalation, CORS | +| A02:2021 Cryptographic Failures | SSL/TLS, weak cipher, plaintext, HSTS | +| A03:2021 Injection | SQLi, XSS, command injection, XXE, SSTI | +| A04:2021 Insecure Design | business logic, rate limit, race condition | +| A05:2021 Security Misconfiguration | default creds, debug mode, headers, directory listing | +| A06:2021 Vulnerable Components | outdated software, CVEs, known vulnerabilities | +| A07:2021 Auth Failures | weak passwords, session, brute force, enumeration | +| A08:2021 Data Integrity Failures | deserialization, CI/CD, supply chain | +| A09:2021 Logging Failures | missing logs, log injection, audit | +| A10:2021 SSRF | server-side request forgery | + +--- + +## Files Created + +``` +packages/opencode/src/pentest/webscan/ +├── types.ts # 20+ Zod schemas +├── events.ts # 9 BusEvent definitions +├── crawler.ts # Web crawler +├── orchestrator.ts # Scan orchestration +├── profiles.ts # Profile definitions +├── storage.ts # Persistence +├── owasp.ts # OWASP categorization +├── tool.ts # WebScanTool +├── index.ts # Module exports +└── parsers/ + ├── index.ts # Parser exports + ├── wpscan.ts # WPScan parser + └── whatweb.ts # WhatWeb parser + +packages/opencode/test/pentest/ +└── webscan.test.ts # 35+ tests + +docs/ +└── PHASE8.md # This documentation +``` + +## Files Modified + +| File | Changes | +|------|---------| +| `src/pentest/index.ts` | Added webscan exports | +| `src/tool/registry.ts` | Registered WebScanTool | + +--- + +## Usage Examples + +### Crawl a Target + +``` +action="crawl" +target="http://example.com" +maxDepth=2 +maxUrls=100 +``` + +### Quick Scan + +``` +action="quick-scan" +target="http://example.com" +``` + +### Standard Scan + +``` +action="scan" +target="http://example.com" +profile="standard" +``` + +### Full Scan + +``` +action="full-scan" +target="http://example.com" +``` + +### Custom Scan + +``` +action="scan" +target="http://example.com" +profile="custom" +tools=["nikto", "nuclei", "gobuster"] +``` + +### List URLs from Crawl + +``` +action="urls" +crawlID="crawl_abc123" +limit=50 +``` + +### OWASP Categorization + +``` +action="owasp" +scanID="scan_xyz789" +``` + +### Programmatic Usage + +```typescript +import { WebCrawler, ScanOrchestrator, ScanProfiles, OwaspCategorization } from "./pentest/webscan" + +// Crawl a target +const crawlResult = await WebCrawler.crawl("http://example.com", { + maxDepth: 2, + maxUrls: 200, +}) + +// Run a scan with profile +const scanResult = await ScanOrchestrator.scan( + "http://example.com", + ScanProfiles.Standard, + { sessionID: "session_123" } +) + +// Categorize findings +const owasp = await OwaspCategorization.categorize(scanResult.id) +console.log(OwaspCategorization.format(owasp)) +``` + +--- + +## Storage Layout + +``` +pentest/webscan/ + crawls/ + crawl_abc123.json # Crawl results + scans/ + scan_xyz789.json # Scan results +``` + +--- + +## Crawler Implementation + +The crawler uses native `fetch()` with regex-based extraction: + +```typescript +// Link extraction +const HREF_REGEX = /href=["']([^"'#]+)["']/gi + +// Form extraction +const FORM_REGEX = /]*>([\s\S]*?)<\/form>/gi +const INPUT_REGEX = /]*>/gi +``` + +Key features: +- Same-origin URL filtering +- JavaScript/mailto/tel link filtering +- Configurable robots.txt respect +- Include/exclude URL patterns +- Request delay between fetches +- Timeout per request + +--- + +## Test Coverage + +**Test File:** `test/pentest/webscan.test.ts` + +**Test Categories:** + +| Category | Tests | +|----------|-------| +| WebCrawler.extractLinks | 3 tests - href, relative, skip js/mailto | +| WebCrawler.extractForms | 3 tests - inputs, file upload, textarea/select | +| ScanProfiles | 5 tests - profiles, configuration, custom | +| WebScanStorage | 6 tests - crawl/scan CRUD, filters | +| WPScanParser | 4 tests - JSON parsing, findings, format | +| WhatWebParser | 4 tests - JSON/text parsing, findings | +| OwaspCategorization | 8 tests - category detection | +| WebScanTypes | 3 tests - schema validation | + +--- + +## Dependencies + +- No external packages (uses native fetch) +- Uses existing: Storage, Bus, Findings, GovernanceScope, GovernanceMatcher +- CLI tools: nikto, gobuster, ffuf, nuclei, wpscan, whatweb, wafw00f (must be installed) + +--- + +## Future Enhancements + +1. **Additional Tools** + - sqlmap integration with form fuzzing + - dirb/dirbuster support + - skipfish integration + +2. **Crawler Improvements** + - JavaScript rendering (headless browser) + - API endpoint discovery + - GraphQL introspection + - WebSocket detection + +3. **Scan Features** + - Authenticated scanning + - Session handling + - Rate limiting + - Parallel tool execution + +4. **Reporting** + - OWASP-focused reports + - Executive summaries + - Remediation priorities + +--- + +## Related Documentation + +- [PHASE7.md](./PHASE7.md) - Exploit Framework Integration +- [PHASE6.md](./PHASE6.md) - Continuous Monitoring +- [PHASE5.md](./PHASE5.md) - Report Generation +- [PENTEST.md](./PENTEST.md) - Pentest module reference diff --git a/docs/PHASE09-api-security-scanner.md b/docs/PHASE09-api-security-scanner.md new file mode 100644 index 00000000000..720b22cbae6 --- /dev/null +++ b/docs/PHASE09-api-security-scanner.md @@ -0,0 +1,292 @@ +# Phase 9: API Security Scanner + +## Overview + +The API Security Scanner module (`pentest/apiscan`) provides comprehensive API security testing capabilities including: + +- **API Discovery**: Auto-detection and parsing of OpenAPI/Swagger and GraphQL specifications +- **Authentication Testing**: JWT analysis, API key validation, OAuth flow testing +- **Authorization Testing**: BOLA/IDOR detection, privilege escalation checks +- **Injection Testing**: SQL, NoSQL, and command injection testing +- **OWASP API Top 10 2023**: Categorization of findings by API-specific OWASP categories + +## Module Structure + +``` +src/pentest/apiscan/ +├── index.ts # Module exports +├── types.ts # Zod schemas (25+ types) +├── events.ts # BusEvent definitions (10 events) +├── storage.ts # API spec/scan persistence +├── profiles.ts # Scan profile definitions +├── tool.ts # ApiScanTool for agent +├── orchestrator.ts # Scan workflow coordination +├── discovery.ts # API endpoint discovery +├── auth/ +│ ├── index.ts # Auth module exports +│ ├── jwt.ts # JWT analysis (decode, validate, attack vectors) +│ ├── apikey.ts # API key testing +│ └── oauth.ts # OAuth flow testing +├── authz/ +│ ├── index.ts # Authz module exports +│ ├── bola.ts # BOLA/IDOR detection +│ └── privilege.ts # Privilege escalation testing +├── injection/ +│ ├── index.ts # Injection module exports +│ ├── sql.ts # SQL injection testing +│ ├── nosql.ts # NoSQL injection testing +│ └── command.ts # Command injection testing +└── parsers/ + ├── index.ts # Parser exports + ├── openapi.ts # OpenAPI/Swagger spec parser + └── graphql.ts # GraphQL introspection parser +``` + +## Usage + +### API Discovery + +```typescript +import { ApiDiscovery } from "./pentest/apiscan" + +// Discover API endpoints from target +const result = await ApiDiscovery.discover("https://api.example.com", { + parseOpenApi: true, + parseGraphQL: true, + commonPaths: true, +}) + +// Parse a specific OpenAPI spec +const spec = await ApiDiscovery.parseOpenApiSpec( + "https://api.example.com/openapi.json", + "https://api.example.com" +) +``` + +### JWT Analysis + +```typescript +import { JwtAnalyzer } from "./pentest/apiscan" + +const token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." +const analysis = JwtAnalyzer.analyze(token) + +console.log(analysis.algorithm) // "HS256" +console.log(analysis.isExpired) // false +console.log(analysis.issues) // ["WARNING: Using symmetric algorithm..."] +console.log(analysis.attackVectors) // ["None algorithm: Try setting alg to 'none'..."] + +// Format for display +console.log(JwtAnalyzer.format(analysis)) + +// Create test tokens +const noneToken = JwtAnalyzer.createNoneAlgToken(analysis) +``` + +### Running Scans + +```typescript +import { ApiScanOrchestrator, ApiScanProfiles } from "./pentest/apiscan" + +// Quick scan +const result = await ApiScanOrchestrator.scan("https://api.example.com", { + profile: "quick", +}) + +// Scan with authentication +const result = await ApiScanOrchestrator.scan("https://api.example.com", { + profile: "standard", + auth: { + type: "jwt", + token: "eyJ...", + }, +}) + +// Custom profile +const customProfile = ApiScanProfiles.createCustom("standard", { + injectionTests: { enabled: true, sql: true, nosql: false, command: false }, + bolaTests: true, +}) +``` + +### Tool Actions + +The `apiscan` tool supports the following actions: + +| Action | Description | +|--------|-------------| +| `discover` | Discover API endpoints from target | +| `parse-spec` | Parse OpenAPI/Swagger specification | +| `parse-graphql` | Parse GraphQL introspection | +| `scan` | Run scan with specific profile | +| `quick-scan` | Quick scan (alias for quick profile) | +| `full-scan` | Thorough scan (alias for thorough profile) | +| `endpoints` | List discovered API endpoints | +| `jwt-analyze` | Analyze a JWT token for vulnerabilities | +| `auth-test` | Test authentication mechanisms | +| `bola-test` | Test for BOLA/IDOR vulnerabilities | +| `inject-test` | Test for injection vulnerabilities | +| `status` | Get status of running scan | +| `owasp-api` | Categorize findings by OWASP API Top 10 | + +## Scan Profiles + +| Profile | Discovery | Auth Tests | Injection | BOLA | Use Case | +|---------|-----------|------------|-----------|------|----------| +| `discovery` | full | none | none | no | Map API surface | +| `quick` | basic | jwt-decode | none | no | Fast assessment | +| `standard` | full | all auth | sql, nosql | yes | Normal pentest | +| `thorough` | full | all + fuzzing | all injection | yes | Comprehensive | +| `passive` | spec-only | jwt-decode | none | no | No active testing | +| `auth-focused` | basic | all + brute | none | yes | Auth-specific testing | +| `custom` | configurable | configurable | configurable | configurable | Custom configuration | + +## OWASP API Top 10 2023 Categories + +The scanner categorizes findings according to the OWASP API Security Top 10 2023: + +| Category | Detection Patterns | +|----------|-------------------| +| API1:2023 Broken Object Level Authorization | BOLA, IDOR, horizontal privilege | +| API2:2023 Broken Authentication | JWT issues, weak auth, session problems | +| API3:2023 Broken Object Property Level Authorization | Mass assignment, excessive data exposure | +| API4:2023 Unrestricted Resource Consumption | Rate limiting issues, DoS vectors | +| API5:2023 Broken Function Level Authorization | Vertical privilege escalation | +| API6:2023 Unrestricted Access to Sensitive Business Flows | Business logic bypass | +| API7:2023 Server Side Request Forgery | SSRF via API parameters | +| API8:2023 Security Misconfiguration | CORS, headers, verbose errors | +| API9:2023 Improper Inventory Management | Undocumented endpoints, old API versions | +| API10:2023 Unsafe Consumption of APIs | Third-party API trust issues | + +## Events + +The module emits the following events: + +| Event | Description | +|-------|-------------| +| `pentest.apiscan.discovery_started` | API discovery began | +| `pentest.apiscan.endpoint_discovered` | New endpoint found | +| `pentest.apiscan.spec_parsed` | OpenAPI/GraphQL spec parsed | +| `pentest.apiscan.scan_started` | Scan began | +| `pentest.apiscan.endpoint_tested` | Endpoint test completed | +| `pentest.apiscan.auth_tested` | Auth test completed | +| `pentest.apiscan.injection_tested` | Injection test completed | +| `pentest.apiscan.vulnerability_found` | Vulnerability discovered | +| `pentest.apiscan.scan_completed` | Scan finished | +| `pentest.apiscan.scan_failed` | Scan failed | + +## Storage + +API specifications and scan results are persisted in: + +``` +pentest/apiscan/ + specs/ + spec_abc123.json # Parsed API specs + scans/ + apiscan_xyz789.json # Scan results +``` + +## Data Types + +### ApiEndpoint + +```typescript +{ + id: string + path: string // /api/users/{id} + method: HttpMethod // GET, POST, PUT, DELETE, PATCH + summary?: string + description?: string + operationId?: string + parameters: ApiParameter[] + requestBody?: RequestBody + responses: ResponseSchema[] + security?: SecurityRequirement[] + tags?: string[] + deprecated?: boolean +} +``` + +### ApiSpec + +```typescript +{ + id: string + target: string // Base URL + type: "openapi" | "graphql" | "manual" + version?: string // OpenAPI version + title?: string + description?: string + endpoints: ApiEndpoint[] + securitySchemes: SecurityScheme[] + graphqlSchema?: GraphQLSchema + servers?: string[] + discoveredAt: number +} +``` + +### JwtAnalysis + +```typescript +{ + raw: string + header: Record + payload: Record + signature: string + algorithm: string + isExpired: boolean + expiresAt?: number + issuedAt?: number + issuer?: string + subject?: string + audience?: string | string[] + issues: string[] // Security issues found + attackVectors: string[] // Suggested attack vectors +} +``` + +### ApiScanResult + +```typescript +{ + id: string + target: string + specId?: string + profile: ProfileId + auth?: AuthConfig + endpoints: EndpointTestResult[] + jwtAnalysis?: JwtAnalysis + bolaResults?: BolaTestResult[] + injectionResults?: InjectionTestResult[] + findings: string[] // Finding IDs + stats: ScanStats + startedAt: number + completedAt?: number + status: Status + error?: string +} +``` + +## Testing + +Run the apiscan tests with: + +```bash +bun test test/pentest/apiscan.test.ts +``` + +The test suite covers: +- JWT decoding and analysis +- OpenAPI 2.0 and 3.x parsing +- GraphQL introspection parsing +- Profile configurations +- Storage operations +- Type validation + +## Dependencies + +The module uses: +- No external packages (uses native fetch, base64 decode) +- Existing modules: Storage, Bus, Findings, GovernanceScope +- Patterns from: webscan module (Tool.define, storage, events) diff --git a/docs/PHASE10-network-infrastructure.md b/docs/PHASE10-network-infrastructure.md new file mode 100644 index 00000000000..61cd2b5282f --- /dev/null +++ b/docs/PHASE10-network-infrastructure.md @@ -0,0 +1,527 @@ +# Phase 10: Network Infrastructure Scanner + +## Overview + +The Network Infrastructure Scanner module (`pentest/netscan`) provides comprehensive network infrastructure security testing capabilities including: + +- **Active Directory**: Domain enumeration, user/group/computer discovery, Kerberoasting, AS-REP roasting, trust enumeration +- **SMB**: Share enumeration, null session testing, SMB signing checks, vulnerability detection (EternalBlue, SMBGhost, PrintNightmare) +- **SNMP**: Community string brute-forcing, SNMP walking, write access testing +- **DNS**: Zone transfer attempts, subdomain enumeration, cache poisoning checks +- **LDAP**: Anonymous bind testing, enumeration, password policy extraction +- **Credentials**: Default credential testing, password spraying with lockout awareness + +## Module Structure + +``` +src/pentest/netscan/ +├── index.ts # Module exports +├── types.ts # Zod schemas (30+ types) +├── events.ts # BusEvent definitions (20+ events) +├── storage.ts # Scan/host/credential persistence +├── profiles.ts # Scan profile definitions +├── tool.ts # NetScanTool for agent +├── orchestrator.ts # Scan workflow coordination +├── parsers/ +│ ├── index.ts # Parser exports +│ ├── crackmapexec.ts # CrackMapExec output parser +│ ├── enum4linux.ts # Enum4linux-ng output parser +│ └── ldapsearch.ts # LDIF/ldapsearch output parser +├── smb/ +│ ├── index.ts # SMB module exports +│ ├── shares.ts # Share enumeration +│ ├── sessions.ts # Null/guest session testing +│ ├── signing.ts # SMB signing checks +│ └── vulns.ts # SMB vulnerability detection +├── dns/ +│ ├── index.ts # DNS module exports +│ ├── zone.ts # Zone transfer testing +│ ├── enum.ts # Subdomain enumeration +│ └── cache.ts # Cache poisoning checks +├── snmp/ +│ ├── index.ts # SNMP module exports +│ ├── community.ts # Community string testing +│ ├── walk.ts # SNMP tree walking +│ └── write.ts # SNMP write access testing +├── ldap/ +│ ├── index.ts # LDAP module exports +│ ├── bind.ts # Anonymous/authenticated bind +│ ├── enum.ts # LDAP enumeration +│ └── policy.ts # Password policy extraction +├── ad/ +│ ├── index.ts # AD module exports +│ ├── enumeration.ts # Domain enumeration +│ ├── kerberos.ts # Kerberoast/AS-REP roast +│ └── trusts.ts # Domain trust enumeration +└── creds/ + ├── index.ts # Credential module exports + ├── defaults.ts # Default credential database + └── spray.ts # Password spraying +``` + +## Usage + +### Active Directory Enumeration + +```typescript +import { ADEnumeration, Kerberos, DomainTrusts } from "./pentest/netscan" + +// Full AD enumeration +const result = await ADEnumeration.enumerate({ + dc: "192.168.1.10", + domain: "corp.local", + auth: { username: "user", password: "pass" }, +}) + +console.log(ADEnumeration.formatResults(result)) + +// Get specific objects +const users = await ADEnumeration.getUsers("192.168.1.10", { + username: "user", + password: "pass", + domain: "corp.local", +}) + +const groups = await ADEnumeration.getGroups("192.168.1.10", auth) +const computers = await ADEnumeration.getComputers("192.168.1.10", auth) + +// Find Kerberoastable accounts +const kerbResult = await Kerberos.findTargets({ + dc: "192.168.1.10", + domain: "corp.local", + auth: { username: "user", password: "pass" }, +}) + +console.log(`Kerberoastable: ${kerbResult.kerberoastTargets.length}`) +console.log(`AS-REP roastable: ${kerbResult.asrepTargets.length}`) + +// Enumerate domain trusts +const trusts = await DomainTrusts.enumerate({ + dc: "192.168.1.10", + domain: "corp.local", + auth: { username: "user", password: "pass" }, +}) +``` + +### SMB Testing + +```typescript +import { SMBShares, SMBSessions, SMBSigning, SMBVulns } from "./pentest/netscan" + +// Enumerate shares +const shares = await SMBShares.enumerate("192.168.1.10", { + auth: { username: "user", password: "pass" }, + checkAccess: true, +}) + +// Test null session +const nullResult = await SMBSessions.testNullSession("192.168.1.10") +console.log(`Null session allowed: ${nullResult.allowed}`) + +// Check SMB signing +const signing = await SMBSigning.check("192.168.1.10") +console.log(`SMB signing required: ${signing.required}`) + +// Check for vulnerabilities +const vulns = await SMBVulns.check("192.168.1.10", { + checks: ["ms17-010", "cve-2020-0796", "printnightmare"], +}) +``` + +### DNS Testing + +```typescript +import { DNSZone, DNSEnum } from "./pentest/netscan" + +// Attempt zone transfer +const zoneResult = await DNSZone.attemptTransfer("example.com", { + nameservers: ["ns1.example.com", "ns2.example.com"], +}) + +if (zoneResult.success) { + console.log(`Zone transfer successful! ${zoneResult.records.length} records`) +} + +// Subdomain enumeration +const subdomains = await DNSEnum.enumerate("example.com", { + bruteForce: true, + wordlist: ["www", "mail", "ftp", "dev", "staging"], +}) +``` + +### SNMP Testing + +```typescript +import { SNMPCommunity, SNMPWalk } from "./pentest/netscan" + +// Brute-force community strings +const bruteResult = await SNMPCommunity.bruteForce("192.168.1.1", { + communities: ["public", "private", "cisco", "secret"], +}) + +// SNMP walk with found community +if (bruteResult.validCommunities.length > 0) { + const walkResult = await SNMPWalk.walk("192.168.1.1", { + community: bruteResult.validCommunities[0], + }) +} +``` + +### LDAP Testing + +```typescript +import { LDAPBind, LDAPEnum, LDAPPolicy } from "./pentest/netscan" + +// Test anonymous bind +const bindResult = await LDAPBind.testAnonymous("192.168.1.10") +console.log(`Anonymous bind: ${bindResult.anonymous}`) + +// Enumerate LDAP +const ldapResult = await LDAPEnum.enumerate("192.168.1.10", { + baseDN: "DC=corp,DC=local", + auth: { username: "user", password: "pass" }, +}) + +// Extract password policy +const policy = await LDAPPolicy.extract("192.168.1.10", { + baseDN: "DC=corp,DC=local", +}) + +console.log(`Min password length: ${policy.minLength}`) +console.log(`Lockout threshold: ${policy.lockoutThreshold}`) +``` + +### Credential Testing + +```typescript +import { DefaultCreds, PasswordSpray } from "./pentest/netscan" + +// Test default credentials +const credResults = await DefaultCreds.test("192.168.1.10", "ssh", 22) + +// Password spray with lockout awareness +const sprayResult = await PasswordSpray.spray( + { host: "192.168.1.10", port: 445, service: "smb", domain: "CORP" }, + ["admin", "user1", "user2"], + ["Password1", "Welcome1", "Summer2024"], + { + delayBetweenPasswords: 30000, // 30 seconds between passwords + lockoutThreshold: 5, // Stop before lockout + observationWindow: 30, // Lockout window in minutes + } +) + +console.log(`Valid credentials: ${sprayResult.valid.length}`) +console.log(`Locked accounts: ${sprayResult.locked.length}`) +``` + +### Running Full Scans + +```typescript +import { NetScanOrchestrator, NetScanProfiles } from "./pentest/netscan" + +// Quick scan +const result = await NetScanOrchestrator.scan("192.168.1.0/24", { + profile: "quick", +}) + +// Full scan with authentication +const result = await NetScanOrchestrator.scan("192.168.1.0/24", { + profile: "thorough", + auth: { username: "user", password: "pass", domain: "CORP" }, +}) + +// AD-focused scan +const result = await NetScanOrchestrator.scan("192.168.1.10", { + profile: "ad-focused", + auth: { username: "user", password: "pass", domain: "CORP" }, +}) + +// Get scan status +const status = await NetScanOrchestrator.getStatus(result.id) +``` + +### Tool Actions + +The `netscan` tool supports the following actions: + +| Action | Description | +|--------|-------------| +| `discover` | Discover network hosts and services | +| `scan` | Run full scan with specified profile | +| `ad-enum` | Enumerate Active Directory domain | +| `ad-users` | List domain users | +| `ad-groups` | List domain groups | +| `ad-computers` | List domain computers | +| `ad-kerberoast` | Find Kerberoastable accounts | +| `ad-asrep` | Find AS-REP roastable accounts | +| `smb-shares` | Enumerate SMB shares | +| `smb-null` | Test null session access | +| `smb-signing` | Check SMB signing configuration | +| `smb-vulns` | Check for SMB vulnerabilities | +| `snmp-walk` | SNMP walk with community string | +| `snmp-brute` | Brute-force SNMP community strings | +| `dns-zone` | Attempt DNS zone transfer | +| `dns-enum` | Enumerate subdomains | +| `ldap-enum` | LDAP enumeration | +| `ldap-policy` | Extract password policy | +| `creds-default` | Test default credentials | +| `creds-spray` | Password spraying attack | +| `status` | Get scan status | +| `profiles` | List available scan profiles | + +## Scan Profiles + +| Profile | SMB | AD | SNMP | DNS | LDAP | Creds | Use Case | +|---------|-----|----|----- |-----|------|-------|----------| +| `discovery` | no | no | no | no | no | no | Host discovery only | +| `quick` | yes | no | no | no | yes | no | Fast assessment | +| `standard` | yes | yes | no | yes | yes | no | Normal pentest | +| `thorough` | yes | yes | yes | yes | yes | yes | Comprehensive | +| `stealth` | yes | no | no | no | yes | no | Low and slow | +| `ad-focused` | yes | yes | no | no | yes | no | AD-specific testing | +| `custom` | configurable | configurable | configurable | configurable | configurable | configurable | Custom configuration | + +## Vulnerability Checks + +### SMB Vulnerabilities + +| Vulnerability | CVE | Description | +|---------------|-----|-------------| +| EternalBlue | MS17-010 | Remote code execution in SMBv1 | +| SMBGhost | CVE-2020-0796 | Buffer overflow in SMBv3 compression | +| PrintNightmare | CVE-2021-34527 | Print Spooler RCE | +| PetitPotam | - | NTLM relay via MS-EFSRPC | + +### Kerberos Attacks + +| Attack | Target | Detection | +|--------|--------|-----------| +| Kerberoasting | Service accounts with SPNs | servicePrincipalName attribute | +| AS-REP Roasting | Accounts without preauth | userAccountControl DONT_REQUIRE_PREAUTH | + +## Events + +The module emits the following events: + +| Event | Description | +|-------|-------------| +| `pentest.netscan.scan_started` | Network scan began | +| `pentest.netscan.scan_completed` | Scan finished | +| `pentest.netscan.scan_failed` | Scan failed | +| `pentest.netscan.host_discovered` | New host found | +| `pentest.netscan.service_discovered` | Service detected | +| `pentest.netscan.ad_domain_found` | AD domain discovered | +| `pentest.netscan.ad_user_found` | Domain user enumerated | +| `pentest.netscan.ad_group_found` | Domain group enumerated | +| `pentest.netscan.kerberoast_target` | Kerberoastable account found | +| `pentest.netscan.asrep_target` | AS-REP roastable account found | +| `pentest.netscan.smb_share_found` | SMB share discovered | +| `pentest.netscan.null_session` | Null session allowed | +| `pentest.netscan.signing_disabled` | SMB signing not required | +| `pentest.netscan.vulnerability_found` | Vulnerability detected | +| `pentest.netscan.credential_found` | Valid credential discovered | +| `pentest.netscan.snmp_community_found` | Valid SNMP community string | +| `pentest.netscan.zone_transfer` | DNS zone transfer succeeded | +| `pentest.netscan.subdomain_found` | Subdomain discovered | +| `pentest.netscan.ldap_anonymous` | Anonymous LDAP bind allowed | +| `pentest.netscan.policy_weakness` | Password policy weakness | + +## Storage + +Network scan data is persisted in: + +``` +pentest/netscan/ + scans/ + netscan_abc123.json # Scan results + hosts/ + host_xyz789.json # Discovered hosts + credentials/ + cred_def456.enc # Encrypted credentials +``` + +Credentials are encrypted with AES-256-CBC before storage. + +## Data Types + +### DiscoveredHost + +```typescript +{ + id: string + ip: string + hostname?: string + mac?: string + os?: string + osVersion?: string + services: Service[] + domain?: string + isDomainController?: boolean + discoveredAt: number +} +``` + +### Service + +```typescript +{ + port: number + protocol: "tcp" | "udp" + service: string + version?: string + product?: string + extraInfo?: string +} +``` + +### ADUser + +```typescript +{ + dn: string + samAccountName: string + userPrincipalName?: string + displayName?: string + description?: string + enabled: boolean + adminCount: boolean + memberOf: string[] + servicePrincipalNames: string[] + dontRequirePreauth: boolean + lastLogon?: number + passwordLastSet?: number +} +``` + +### SMBShare + +```typescript +{ + name: string + type: "DISK" | "IPC" | "PRINT" | "DEVICE" + remark?: string + permissions: { + read: boolean + write: boolean + anonymous: boolean + } + sensitiveFiles?: string[] +} +``` + +### CredentialResult + +```typescript +{ + id: string + host: string + service: string + port: number + username: string + password?: string + hash?: string + method: "default" | "spray" | "brute" | "dump" + valid: boolean + admin: boolean + timestamp: number +} +``` + +### NetScanResult + +```typescript +{ + id: string + target: string + profile: ProfileId + status: "pending" | "running" | "completed" | "failed" + stats: { + hostsScanned: number + servicesFound: number + vulnerabilitiesFound: number + credentialsFound: number + } + findings: string[] + startedAt: number + completedAt?: number + error?: string +} +``` + +## External Tool Parsers + +The module includes parsers for common penetration testing tools: + +### CrackMapExec + +```typescript +import { CrackMapExecParser } from "./pentest/netscan" + +const output = `SMB 192.168.1.10 445 DC01 [+] CORP\\admin:Password123 (Pwn3d!)` +const results = CrackMapExecParser.parse(output) + +console.log(results.credentials) // Valid credentials found +console.log(results.shares) // Enumerated shares +console.log(results.hosts) // Host information +``` + +### Enum4linux + +```typescript +import { Enum4linuxParser } from "./pentest/netscan" + +const output = await runEnum4linux("192.168.1.10") +const results = Enum4linuxParser.parse(output) + +console.log(results.users) // Enumerated users +console.log(results.groups) // Enumerated groups +console.log(results.shares) // Enumerated shares +console.log(results.passwordPolicy) // Password policy +``` + +### Ldapsearch + +```typescript +import { LdapsearchParser } from "./pentest/netscan" + +const ldif = await runLdapsearch(...) +const results = LdapsearchParser.parse(ldif) + +console.log(results.entries) // LDAP entries +const users = LdapsearchParser.extractUsers(results) +``` + +## Testing + +Run the netscan tests with: + +```bash +bun test test/pentest/netscan.test.ts +``` + +The test suite covers: +- CrackMapExec output parsing +- Enum4linux output parsing +- LDIF/ldapsearch parsing +- Profile configurations +- Storage operations +- Type validation +- Password spray utilities + +## Dependencies + +The module uses external tools: +- `smbclient` - SMB share enumeration +- `rpcclient` - RPC enumeration +- `ldapsearch` - LDAP queries +- `dig`/`host` - DNS queries +- `snmpwalk`/`snmpget` - SNMP operations +- `nmap` - Service discovery +- `sshpass` - SSH credential testing +- `xfreerdp` - RDP credential testing +- `crackmapexec` - Multi-protocol testing + +Existing modules used: +- Storage, Bus, Findings, GovernanceScope +- Patterns from: apiscan module (Tool.define, storage, events) diff --git a/docs/PHASE11-cloud-security.md b/docs/PHASE11-cloud-security.md new file mode 100644 index 00000000000..1a446ba8e99 --- /dev/null +++ b/docs/PHASE11-cloud-security.md @@ -0,0 +1,689 @@ +# Phase 11: Cloud Security Scanner + +## Overview + +The Cloud Security Scanner module (`pentest/cloudscan`) provides comprehensive cloud infrastructure security testing capabilities across major cloud providers: + +- **AWS**: IAM analysis, S3 bucket security, Security Groups, EC2 instances, Lambda functions +- **Azure**: RBAC analysis, Storage accounts, Network Security Groups, VMs, Function Apps +- **GCP**: IAM/Service accounts, Cloud Storage, Firewall rules, GCE instances, Cloud Functions +- **Compliance**: CIS Benchmarks, NIST, PCI-DSS, HIPAA, SOC2, GDPR, ISO27001 +- **External Tools**: Prowler, ScoutSuite integration + +## Module Structure + +``` +src/pentest/cloudscan/ +├── index.ts # Module exports +├── types.ts # Zod schemas (40+ types) +├── events.ts # BusEvent definitions (25+ events) +├── storage.ts # Scan persistence +├── profiles.ts # Scan profile definitions +├── tool.ts # CloudScanTool for agent +├── orchestrator.ts # Scan workflow coordination +├── discovery.ts # Cloud resource enumeration +├── compliance.ts # Compliance framework checker +├── parsers/ +│ ├── index.ts # Parser exports +│ ├── aws-cli.ts # AWS CLI JSON parser +│ ├── azure-cli.ts # Azure CLI JSON parser +│ ├── gcloud.ts # gcloud CLI JSON parser +│ ├── prowler.ts # Prowler output parser +│ └── scoutsuite.ts # ScoutSuite output parser +├── aws/ +│ ├── index.ts # AWS module exports +│ ├── iam.ts # IAM enumeration & analysis +│ ├── s3.ts # S3 bucket security +│ ├── security-groups.ts # Security group analysis +│ ├── ec2.ts # EC2 instance security +│ └── lambda.ts # Lambda function security +├── azure/ +│ ├── index.ts # Azure module exports +│ ├── rbac.ts # RBAC analysis +│ ├── storage.ts # Storage account security +│ ├── nsg.ts # Network Security Groups +│ └── vm.ts # VM and Function App security +└── gcp/ + ├── index.ts # GCP module exports + ├── iam.ts # IAM & service accounts + ├── gcs.ts # Cloud Storage security + ├── firewall.ts # Firewall rule analysis + └── compute.ts # GCE & Cloud Functions +``` + +## Usage + +### AWS Security Scanning + +```typescript +import { AWSIAM, AWSS3, AWSSecurityGroups, AWSEC2, AWSLambda } from "./pentest/cloudscan" + +// IAM enumeration and analysis +const iamResult = await AWSIAM.enumerate("scan_123", { + profile: "production", + region: "us-east-1", +}) + +console.log(`Users: ${iamResult.users.length}`) +console.log(`Roles: ${iamResult.roles.length}`) +console.log(`Policies: ${iamResult.policies.length}`) +console.log(`Issues: ${iamResult.issues.length}`) + +// Check for users without MFA +const noMFA = await AWSIAM.getUsersWithoutMFA({ profile: "production" }) +console.log(`Users without MFA: ${noMFA.length}`) + +// Check for old access keys +const oldKeys = await AWSIAM.getUsersWithOldAccessKeys(90, { profile: "production" }) + +// S3 bucket security analysis +const s3Result = await AWSS3.enumerate("scan_123", { profile: "production" }) + +// Get public buckets +const publicBuckets = await AWSS3.getPublicBuckets({ profile: "production" }) +console.log(`Public buckets: ${publicBuckets.length}`) + +// Get unencrypted buckets +const unencrypted = await AWSS3.getUnencryptedBuckets({ profile: "production" }) + +// Security group analysis +const sgResult = await AWSSecurityGroups.enumerate("scan_123", { + profile: "production", + region: "us-east-1", +}) + +// Get groups with public SSH +const publicSSH = await AWSSecurityGroups.getGroupsWithPublicPort(22, { + profile: "production", + region: "us-east-1", +}) + +// EC2 instance analysis +const ec2Result = await AWSEC2.enumerate("scan_123", { + profile: "production", + region: "us-east-1", +}) + +// Get instances without IMDSv2 +const noIMDSv2 = await AWSEC2.getInstancesWithoutIMDSv2({ + profile: "production", + region: "us-east-1", +}) + +// Lambda function analysis +const lambdaResult = await AWSLambda.enumerate("scan_123", { + profile: "production", + region: "us-east-1", +}) + +// Get public Lambda functions +const publicFunctions = await AWSLambda.getPublicFunctions({ + profile: "production", + region: "us-east-1", +}) +``` + +### Azure Security Scanning + +```typescript +import { AzureRBAC, AzureStorage, AzureNSG, AzureVM } from "./pentest/cloudscan" + +// RBAC analysis +const rbacResult = await AzureRBAC.enumerate("scan_123", { + subscriptionId: "sub-123", +}) + +console.log(`Users: ${rbacResult.users.length}`) +console.log(`Service Principals: ${rbacResult.servicePrincipals.length}`) +console.log(`Role Assignments: ${rbacResult.roleAssignments.length}`) + +// Get high-privilege assignments +const highPriv = await AzureRBAC.getHighPrivilegeAssignments({ + subscriptionId: "sub-123", +}) + +// Storage account analysis +const storageResult = await AzureStorage.enumerate("scan_123", { + subscriptionId: "sub-123", +}) + +// Get storage accounts with public access +const publicStorage = await AzureStorage.getPublicStorageAccounts({ + subscriptionId: "sub-123", +}) + +// NSG analysis +const nsgResult = await AzureNSG.enumerate("scan_123", { + subscriptionId: "sub-123", +}) + +// Get NSGs with unrestricted ingress +const publicNSGs = await AzureNSG.getNSGsWithPublicIngress({ + subscriptionId: "sub-123", +}) + +// VM analysis +const vmResult = await AzureVM.enumerate("scan_123", { + subscriptionId: "sub-123", +}) + +// Get VMs without managed identity +const noIdentity = await AzureVM.getVMsWithoutManagedIdentity({ + subscriptionId: "sub-123", +}) +``` + +### GCP Security Scanning + +```typescript +import { GCPIAM, GCPGCS, GCPFirewall, GCPCompute } from "./pentest/cloudscan" + +// IAM analysis +const iamResult = await GCPIAM.enumerate("scan_123", { + projectId: "my-project", +}) + +console.log(`Service Accounts: ${iamResult.serviceAccounts.length}`) +console.log(`Custom Roles: ${iamResult.customRoles.length}`) +console.log(`IAM Bindings: ${iamResult.iamBindings.length}`) + +// Get service accounts with user-managed keys +const withKeys = await GCPIAM.getServiceAccountsWithKeys({ + projectId: "my-project", +}) + +// Get public IAM bindings +const publicBindings = await GCPIAM.getPublicBindings({ + projectId: "my-project", +}) + +// GCS bucket analysis +const gcsResult = await GCPGCS.enumerate("scan_123", { + projectId: "my-project", +}) + +// Get public buckets +const publicBuckets = await GCPGCS.getPublicBuckets({ + projectId: "my-project", +}) + +// Firewall analysis +const fwResult = await GCPFirewall.enumerate("scan_123", { + projectId: "my-project", +}) + +// Get rules with public ingress +const publicRules = await GCPFirewall.getRulesWithPublicIngress({ + projectId: "my-project", +}) + +// Compute analysis +const computeResult = await GCPCompute.enumerate("scan_123", { + projectId: "my-project", +}) + +// Get instances with default service account +const defaultSA = await GCPCompute.getInstancesWithDefaultSA({ + projectId: "my-project", +}) + +// Get public Cloud Functions +const publicFunctions = await GCPCompute.getPublicFunctions({ + projectId: "my-project", +}) +``` + +### Running Full Scans + +```typescript +import { CloudScanOrchestrator, CloudScanProfiles } from "./pentest/cloudscan" + +// Quick scan +const result = await CloudScanOrchestrator.quickScan({ + provider: "aws", + regions: ["us-east-1", "us-west-2"], + awsProfile: "production", +}) + +// Standard scan with compliance +const result = await CloudScanOrchestrator.scan({ + provider: "aws", + profile: "standard", + regions: ["us-east-1"], + complianceFrameworks: ["cis", "pci-dss"], + awsProfile: "production", +}) + +// Thorough scan with external tools +const result = await CloudScanOrchestrator.thoroughScan({ + provider: "aws", + regions: ["us-east-1"], + awsProfile: "production", + useProwler: true, + useScoutSuite: true, +}) + +// Focused scans +const iamResult = await CloudScanOrchestrator.iamScan({ + provider: "azure", + azureSubscription: "sub-123", +}) + +const storageResult = await CloudScanOrchestrator.storageScan({ + provider: "gcp", + gcpProject: "my-project", +}) + +const networkResult = await CloudScanOrchestrator.networkScan({ + provider: "aws", + regions: ["us-east-1"], + awsProfile: "production", +}) + +// Compliance-only scan +const complianceResult = await CloudScanOrchestrator.complianceScan({ + provider: "aws", + frameworks: ["cis", "nist", "hipaa"], + awsProfile: "production", +}) +``` + +### Compliance Checking + +```typescript +import { ComplianceChecker } from "./pentest/cloudscan" + +// Evaluate findings against CIS benchmarks +const cisResult = ComplianceChecker.evaluate( + "scan_123", + "aws", + "cis", + findings +) + +console.log(`Pass Rate: ${cisResult.summary.passRate}%`) +console.log(`Failed Checks: ${cisResult.summary.failed}`) + +// Evaluate multiple frameworks +const results = ComplianceChecker.evaluateAll( + "scan_123", + "aws", + ["cis", "nist", "pci-dss", "hipaa"], + findings +) + +// Get framework info +const info = ComplianceChecker.getFrameworkInfo("cis") +console.log(`${info.name} v${info.version}`) +``` + +### Discovery + +```typescript +import { CloudDiscovery } from "./pentest/cloudscan" + +// Check prerequisites +const prereqs = await CloudDiscovery.checkPrerequisites("aws") +console.log(`CLI Installed: ${prereqs.cliInstalled}`) +console.log(`Authenticated: ${prereqs.authenticated}`) + +// Get available regions +const regions = await CloudDiscovery.getRegions("aws") + +// Discover resources +const discovery = await CloudDiscovery.discover("scan_123", { + provider: "aws", + regions: ["us-east-1"], + awsProfile: "production", +}) + +console.log(`Total Resources: ${discovery.summary.totalResources}`) +console.log(`Users: ${discovery.resources.iam.users.length}`) +console.log(`Buckets: ${discovery.resources.storage.length}`) +console.log(`Security Groups: ${discovery.resources.network.securityGroups.length}`) +console.log(`Instances: ${discovery.resources.compute.instances.length}`) +``` + +### Tool Actions + +The `cloudscan` tool supports the following actions: + +| Action | Description | +|--------|-------------| +| `discover` | Enumerate cloud resources | +| `scan` | Run security scan with profile | +| `quick-scan` | Fast assessment | +| `full-scan` | Comprehensive scan with external tools | +| `iam-scan` | IAM/RBAC focused scan | +| `storage-scan` | Storage bucket focused scan | +| `network-scan` | Security group focused scan | +| `compliance` | Compliance framework check | +| `prowler` | Run Prowler tool | +| `scoutsuite` | Run ScoutSuite tool | +| `status` | Get scan status | +| `profiles` | List available scan profiles | +| `prerequisites` | Check CLI tools and auth | +| `regions` | List available regions | + +## Scan Profiles + +| Profile | Discovery | Security | Compliance | External Tools | Use Case | +|---------|-----------|----------|------------|----------------|----------| +| `discovery` | yes | no | no | no | Resource enumeration only | +| `quick` | yes | yes | no | no | Fast assessment | +| `standard` | yes | yes | yes (CIS) | no | Normal assessment | +| `thorough` | yes | yes | yes (all) | yes | Comprehensive audit | +| `compliance` | yes | yes | yes | no | Compliance-focused | +| `iam-focused` | yes | yes | yes | no | IAM-specific | +| `storage-focused` | yes | yes | yes | no | Storage-specific | +| `network-focused` | yes | yes | yes | no | Network-specific | +| `custom` | configurable | configurable | configurable | configurable | Custom configuration | + +## Security Checks + +### IAM Checks + +| Check | Provider | Severity | Description | +|-------|----------|----------|-------------| +| MFA Enabled | AWS/Azure | High | Users should have MFA enabled | +| No Root Access Keys | AWS | Critical | Root account should not have access keys | +| Access Key Rotation | All | Medium | Access keys should be rotated regularly | +| Least Privilege | All | Medium | Overly permissive policies detected | +| Public IAM Bindings | GCP | Critical | allUsers or allAuthenticatedUsers bindings | +| Service Account Keys | GCP | Medium | User-managed keys instead of workload identity | + +### Storage Checks + +| Check | Provider | Severity | Description | +|-------|----------|----------|-------------| +| No Public Access | All | High | Public access prevention not enforced | +| Encryption Enabled | All | High | Server-side encryption required | +| Versioning Enabled | All | Low | Object versioning for recovery | +| Access Logging | All | Medium | Access logging for audit | +| HTTPS Only | AWS/Azure | Medium | Require secure transport | +| Uniform Access | GCP | Medium | Uniform bucket-level access instead of ACLs | + +### Network Checks + +| Check | Provider | Severity | Description | +|-------|----------|----------|-------------| +| No Unrestricted Ingress | All | Critical | 0.0.0.0/0 on all ports | +| No SSH from Internet | All | High | Port 22 exposed to 0.0.0.0/0 | +| No RDP from Internet | All | High | Port 3389 exposed to 0.0.0.0/0 | +| No Database from Internet | All | Critical | MySQL/PostgreSQL/MongoDB exposed | +| VPC Flow Logs | All | Medium | Network flow logging enabled | + +### Compute Checks + +| Check | Provider | Severity | Description | +|-------|----------|----------|-------------| +| No Public IP | All | Medium | Instances without public IPs preferred | +| IMDSv2 Required | AWS | Medium | Instance metadata service v2 | +| Managed Identity | Azure | Medium | VMs using managed identity | +| No Default SA | GCP | Medium | Custom service account instead of default | +| No Secrets in Env | All | High | Secrets in function environment variables | + +## Compliance Frameworks + +| Framework | Description | Version | +|-----------|-------------|---------| +| `cis` | CIS Benchmarks | 2.0 | +| `nist` | NIST Cybersecurity Framework | 1.1 | +| `pci-dss` | Payment Card Industry DSS | 4.0 | +| `hipaa` | Health Insurance Portability | 2023 | +| `soc2` | Service Organization Control 2 | 2017 | +| `gdpr` | General Data Protection Regulation | 2018 | +| `iso27001` | Information Security Management | 2022 | +| `aws-foundational-security` | AWS Security Best Practices | 1.0 | +| `azure-security-benchmark` | Azure Security Benchmark | 3.0 | +| `gcp-security-foundations` | GCP Security Foundations | 1.0 | + +## Events + +The module emits the following events: + +| Event | Description | +|-------|-------------| +| `pentest.cloudscan.scan_started` | Cloud scan began | +| `pentest.cloudscan.scan_completed` | Scan finished | +| `pentest.cloudscan.scan_failed` | Scan failed | +| `pentest.cloudscan.discovery_started` | Resource discovery began | +| `pentest.cloudscan.discovery_completed` | Discovery finished | +| `pentest.cloudscan.bucket_found` | Storage bucket discovered | +| `pentest.cloudscan.public_bucket_found` | Public bucket detected | +| `pentest.cloudscan.iam_user_found` | IAM user enumerated | +| `pentest.cloudscan.iam_role_found` | IAM role enumerated | +| `pentest.cloudscan.iam_policy_issue` | IAM policy issue detected | +| `pentest.cloudscan.security_group_found` | Security group discovered | +| `pentest.cloudscan.insecure_rule_found` | Insecure firewall rule detected | +| `pentest.cloudscan.instance_found` | Compute instance discovered | +| `pentest.cloudscan.function_found` | Serverless function discovered | +| `pentest.cloudscan.finding_detected` | Security finding generated | +| `pentest.cloudscan.compliance_violation` | Compliance check failed | +| `pentest.cloudscan.compliance_complete` | Compliance evaluation finished | +| `pentest.cloudscan.external_tool_completed` | External tool finished | + +## Storage + +Cloud scan data is persisted in: + +``` +pentest/cloudscan/ + scans/ + cloudscan_abc123.json # Scan results +``` + +## Data Types + +### CloudScanResult + +```typescript +{ + id: string + provider: "aws" | "azure" | "gcp" + profile: string + status: "running" | "completed" | "failed" + startTime: number + endTime?: number + discovery: DiscoveryResult + findings: CloudFinding[] + compliance: ComplianceResult[] + summary: { + totalResources: number + totalFindings: number + bySeverity: { critical, high, medium, low, info } + byCategory: Record + } + errors: string[] +} +``` + +### CloudFinding + +```typescript +{ + id: string + provider: "aws" | "azure" | "gcp" + region?: string + severity: "critical" | "high" | "medium" | "low" | "info" + title: string + description: string + resourceType: string + resourceId: string + category: string + complianceFrameworks?: string[] + remediation?: string + foundAt: number + source: "scanner" | "prowler" | "scoutsuite" +} +``` + +### IAMPrincipal + +```typescript +{ + id: string + name: string + type: "user" | "role" | "service-account" | "group" + arn?: string + email?: string + createdAt?: number + lastUsed?: number + mfaEnabled?: boolean + accessKeys: AccessKey[] + attachedPolicies: string[] + inlinePolicies: string[] + groups?: string[] + issues: string[] +} +``` + +### StorageBucket + +```typescript +{ + id: string + name: string + provider: "aws" | "azure" | "gcp" + region?: string + createdAt?: number + publicAccessBlocked?: boolean + versioningEnabled?: boolean + loggingEnabled?: boolean + encryption?: { + enabled: boolean + keyId?: string + customerManaged?: boolean + } + accessLevel?: string + issues?: string[] +} +``` + +### SecurityGroup + +```typescript +{ + id: string + name: string + vpcId?: string + description?: string + rules: SecurityRule[] + hasPublicIngress: boolean + hasUnrestrictedIngress: boolean + tags?: Record +} +``` + +### ComplianceCheck + +```typescript +{ + id: string + framework: string + controlId: string + title: string + description: string + status: "pass" | "fail" | "unknown" + severity: "critical" | "high" | "medium" | "low" | "info" + resourceType: string + findings: string[] + remediation?: string +} +``` + +## External Tool Parsers + +### Prowler + +```typescript +import { ProwlerParser } from "./pentest/cloudscan" + +const output = await runProwler() +const findings = ProwlerParser.parseOutput(output, "aws") + +console.log(`Findings: ${findings.length}`) +``` + +### ScoutSuite + +```typescript +import { ScoutSuiteParser } from "./pentest/cloudscan" + +const output = await runScoutSuite() +const findings = ScoutSuiteParser.parseOutput(output, "aws") + +console.log(`Findings: ${findings.length}`) +``` + +## Testing + +Run the cloudscan tests with: + +```bash +bun test test/pentest/cloudscan.test.ts +``` + +The test suite covers: +- AWS CLI output parsing +- Azure CLI output parsing +- gcloud CLI output parsing +- Prowler output parsing +- ScoutSuite output parsing +- Profile configurations +- Storage operations +- Type validation +- Compliance checking + +## Dependencies + +The module uses external CLI tools: +- `aws` - AWS CLI for resource enumeration +- `az` - Azure CLI for resource enumeration +- `gcloud` - Google Cloud CLI for resource enumeration +- `prowler` - AWS/Azure/GCP security assessment +- `scout` - ScoutSuite multi-cloud security auditing + +Existing modules used: +- Storage, Bus, Log +- Patterns from: netscan, apiscan modules (Tool.define, storage, events) + +## Example Tool Usage + +```bash +# Check prerequisites +cloudscan prerequisites provider=aws + +# List available regions +cloudscan regions provider=aws + +# Resource discovery +cloudscan discover provider=aws regions=["us-east-1"] + +# Quick scan +cloudscan quick-scan provider=aws awsProfile=production + +# Full scan with external tools +cloudscan full-scan provider=aws regions=["us-east-1","us-west-2"] + +# IAM-focused scan +cloudscan iam-scan provider=azure azureSubscription=sub-123 + +# Storage-focused scan +cloudscan storage-scan provider=gcp gcpProject=my-project + +# Compliance scan +cloudscan compliance provider=aws frameworks=["cis","pci-dss","hipaa"] + +# Run Prowler +cloudscan prowler provider=aws awsProfile=production + +# Run ScoutSuite +cloudscan scoutsuite provider=aws + +# Check scan status +cloudscan status scanId=cloudscan_abc123 + +# List profiles +cloudscan profiles +``` diff --git a/docs/PHASE12-container-security.md b/docs/PHASE12-container-security.md new file mode 100644 index 00000000000..dbf58148a57 --- /dev/null +++ b/docs/PHASE12-container-security.md @@ -0,0 +1,619 @@ +# Phase 12: Container Security Scanner + CVE Lookup Service + +## Overview + +Phase 12 introduces two interconnected modules: + +1. **CVE Lookup Service** (`pentest/cve/`) - Shared utility for CVE enrichment across all scanners +2. **Container Security Scanner** (`pentest/containerscan/`) - Docker, Kubernetes, and registry security testing + +## Part A: CVE Lookup Service + +The CVE Lookup Service provides centralized vulnerability data enrichment from multiple authoritative sources. + +### Module Structure + +``` +src/pentest/cve/ +├── index.ts # Module exports +├── types.ts # Zod schemas for CVE data +├── cache.ts # File-based caching with TTL +├── lookup.ts # NVD, OSV, CISA KEV API integration +├── enricher.ts # Finding enrichment utilities +└── tool.ts # CVETool for agent +``` + +### External APIs + +| API | Purpose | Rate Limit | +|-----|---------|------------| +| NVD API 2.0 | Official NIST CVE database | 5 req/30s (no key), 50 req/30s (with key) | +| OSV API | Open Source Vulnerabilities | No limit | +| CISA KEV | Known Exploited Vulnerabilities | No limit | + +### Usage + +```typescript +import { CVELookup, CVECache, CVEEnricher } from "./pentest/cve" + +// Look up a single CVE +const cve = await CVELookup.lookup("CVE-2021-44228") +console.log(`CVSS: ${cve.cvss?.v3?.score}`) +console.log(`Severity: ${cve.cvss?.v3?.severity}`) +console.log(`In CISA KEV: ${cve.exploitability?.inKEV}`) + +// Bulk lookup +const cves = await CVELookup.bulkLookup([ + "CVE-2021-44228", + "CVE-2023-44487", + "CVE-2024-3094" +]) + +// Search CVEs by keyword +const results = await CVELookup.search({ + keyword: "log4j", + startDate: "2021-01-01", + severityType: "critical" +}) + +// Check against CISA KEV +const kevResults = await CVELookup.checkKEV(["CVE-2021-44228", "CVE-2023-44487"]) +console.log(`In KEV: ${kevResults.inKEV.length}`) + +// Enrich findings with CVE data +const enriched = await CVEEnricher.enrichFindings(findings, { + fetchMissing: true, + checkKEV: true +}) + +// Cache management +await CVECache.warmup(["CVE-2021-44228", "CVE-2023-44487"]) +const stats = await CVECache.getStats() +console.log(`Cache hits: ${stats.hits}, misses: ${stats.misses}`) +``` + +### Tool Actions + +| Action | Description | +|--------|-------------| +| `lookup` | Look up single CVE | +| `bulk-lookup` | Look up multiple CVEs | +| `search` | Search CVEs by keyword/product | +| `kev-check` | Check if CVEs are in CISA KEV | +| `enrich-findings` | Enrich findings with CVE data | +| `cache-stats` | Get cache statistics | +| `clear-cache` | Clear the CVE cache | + +### Data Types + +#### CVEData + +```typescript +{ + id: string // CVE-2024-1234 + description: string + cvss: { + v4?: { score: number; vector: string; severity: string } + v3?: { score: number; vector: string; severity: string } + v2?: { score: number; vector: string } + } + cwe: string[] // CWE-79, CWE-89 + references: string[] + publishedDate: string + lastModifiedDate: string + exploitability?: { + inKEV: boolean // CISA Known Exploited + hasPublicExploit: boolean + exploitMaturity: string + } + affected?: { + vendor: string + product: string + versions: string[] + }[] +} +``` + +--- + +## Part B: Container Security Scanner + +The Container Security Scanner provides comprehensive container and orchestration security testing. + +### Module Structure + +``` +src/pentest/containerscan/ +├── index.ts # Module exports +├── types.ts # ContainerScanTypes namespace +├── events.ts # ContainerScanEvents +├── storage.ts # Scan persistence +├── profiles.ts # Scan profiles +├── tool.ts # ContainerScanTool +├── orchestrator.ts # Scan coordination +├── parsers/ +│ ├── index.ts +│ ├── trivy.ts # Trivy JSON parser +│ ├── grype.ts # Grype JSON parser +│ ├── syft.ts # Syft SBOM parser +│ └── kubeaudit.ts # Kubeaudit parser +├── docker/ +│ ├── index.ts +│ ├── images.ts # Image enumeration & scanning +│ ├── containers.ts # Running container analysis +│ ├── config.ts # Docker daemon config audit +│ └── secrets.ts # Secret detection in images +├── kubernetes/ +│ ├── index.ts +│ ├── cluster.ts # Cluster enumeration +│ ├── pods.ts # Pod security analysis +│ ├── rbac.ts # RBAC analysis +│ ├── network.ts # Network policy analysis +│ ├── secrets.ts # K8s secrets audit +│ └── admission.ts # Admission controller checks +└── registry/ + ├── index.ts + ├── dockerhub.ts # Docker Hub integration + ├── ecr.ts # AWS ECR + ├── acr.ts # Azure ACR + ├── gcr.ts # Google GCR/Artifact Registry + └── scanner.ts # Registry scanning orchestration +``` + +### Usage + +#### Docker Image Scanning + +```typescript +import { DockerImages, DockerContainers, DockerConfig, DockerSecrets } from "./pentest/containerscan" + +// List local images +const images = await DockerImages.list() +console.log(`Found ${images.length} images`) + +// Scan an image for vulnerabilities +const scanResult = await DockerImages.scanWithTrivy("nginx:latest") +console.log(`Vulnerabilities: ${scanResult.vulnerabilities.length}`) + +// Scan with multiple tools +const fullResult = await DockerImages.scanImage("nginx:latest", { + useTrivy: true, + useGrype: true, + generateSBOM: true +}) + +// Generate SBOM +const sbom = await DockerImages.generateSBOM("nginx:latest") +console.log(`Components: ${sbom.components.length}`) + +// Analyze running containers +const containers = await DockerContainers.list() +const analysis = await DockerContainers.analyzeAll() +console.log(`Privileged containers: ${analysis.filter(c => c.privileged).length}`) + +// Audit Docker daemon configuration +const configFindings = await DockerConfig.audit() +console.log(`Config issues: ${configFindings.length}`) + +// Scan for secrets +const secrets = await DockerSecrets.scanImage("myapp:latest") +console.log(`Secrets found: ${secrets.length}`) +``` + +#### Kubernetes Security Scanning + +```typescript +import { + KubernetesCluster, + KubernetesPods, + KubernetesRBAC, + KubernetesNetwork, + KubernetesSecrets, + KubernetesAdmission +} from "./pentest/containerscan" + +// Check cluster connectivity +const connected = await KubernetesCluster.isConnected() +const clusterInfo = await KubernetesCluster.getInfo() +console.log(`Cluster: ${clusterInfo.name} (${clusterInfo.version})`) + +// Analyze pod security +const pods = await KubernetesPods.list() +const podAnalysis = await KubernetesPods.analyzeAll() +console.log(`Pods with issues: ${podAnalysis.filter(p => p.findings.length > 0).length}`) + +// Get privileged pods +const privilegedPods = await KubernetesPods.getPrivileged() +console.log(`Privileged pods: ${privilegedPods.length}`) + +// RBAC analysis +const rbacFindings = await KubernetesRBAC.analyze() +console.log(`RBAC issues: ${rbacFindings.length}`) + +// Get cluster-admin bindings +const clusterAdmins = await KubernetesRBAC.getClusterAdminBindings() +console.log(`Cluster-admin bindings: ${clusterAdmins.length}`) + +// Network policy analysis +const networkCoverage = await KubernetesNetwork.analyzeCoverage() +console.log(`Namespaces without policies: ${networkCoverage.unprotectedNamespaces.length}`) + +// Secrets analysis +const secretsAnalysis = await KubernetesSecrets.analyze() +console.log(`Secrets: ${secretsAnalysis.length}`) + +// Admission controller analysis +const admissionAnalysis = await KubernetesAdmission.analyze() +console.log(`PSA Enforced: ${admissionAnalysis.psaEnforced}`) +``` + +#### Registry Scanning + +```typescript +import { RegistryScanner, DockerHub, AWSECR, AzureACR, GoogleGCR } from "./pentest/containerscan" + +// Docker Hub +const hubImages = await DockerHub.listImages("myorg") +await DockerHub.scanRepository("myorg/myapp") + +// AWS ECR +const ecrImages = await AWSECR.listImages("my-repo", { region: "us-east-1" }) +const ecrFindings = await AWSECR.getFindings("my-repo", "sha256:abc123", { + region: "us-east-1" +}) + +// Azure ACR +const acrImages = await AzureACR.listImages("myacr", "my-repo") +await AzureACR.checkSecurity("myacr") + +// Google GCR/Artifact Registry +const gcrImages = await GoogleGCR.listImages("my-project") +const gcrVulns = await GoogleGCR.getVulnerabilities("my-project", "gcr.io/my-project/myapp@sha256:abc") + +// Registry scanning orchestration +const registryResult = await RegistryScanner.scanRegistry({ + type: "ecr", + url: "123456789.dkr.ecr.us-east-1.amazonaws.com", + name: "Production ECR", + authenticated: true, + region: "us-east-1" +}, { + scanVulnerabilities: true, + generateSBOM: true, + maxImages: 50 +}) +``` + +#### Running Full Scans + +```typescript +import { ContainerScanOrchestrator, ContainerScanProfiles } from "./pentest/containerscan" + +// Quick scan +const quickResult = await ContainerScanOrchestrator.scan({ + profile: "quick", + scanDocker: true, + scanKubernetes: false +}) + +// Standard scan with K8s +const standardResult = await ContainerScanOrchestrator.scan({ + profile: "standard", + scanDocker: true, + scanKubernetes: true, + complianceFrameworks: ["cis-docker"] +}) + +// Thorough scan with all tools +const thoroughResult = await ContainerScanOrchestrator.scan({ + profile: "thorough", + scanDocker: true, + scanKubernetes: true, + scanRegistries: ["ecr", "gcr"], + complianceFrameworks: ["cis-docker", "cis-kubernetes"] +}) + +// Image-only scan +const imageResult = await ContainerScanOrchestrator.scanImage("nginx:latest", { + useTrivy: true, + useGrype: true, + generateSBOM: true +}) + +// Runtime scan +const runtimeResult = await ContainerScanOrchestrator.scanRuntime() + +// Cluster scan +const clusterResult = await ContainerScanOrchestrator.scanCluster({ + rbac: true, + pods: true, + network: true, + secrets: true, + admission: true +}) + +// Compliance scan +const complianceResult = await ContainerScanOrchestrator.scanCompliance({ + framework: "cis-kubernetes", + kubeaudit: true +}) +``` + +### Tool Actions + +| Action | Description | +|--------|-------------| +| `discover` | Enumerate images, containers, registries | +| `scan` | Run security scan with profile | +| `scan-image` | Scan specific image for vulnerabilities | +| `scan-runtime` | Analyze running containers | +| `scan-registry` | Scan images in a registry | +| `scan-cluster` | Kubernetes cluster security audit | +| `sbom` | Generate SBOM for image | +| `compliance` | CIS Docker/Kubernetes benchmark | +| `status` | Get scan status | +| `profiles` | List available scan profiles | + +### Scan Profiles + +| Profile | Images | Runtime | K8s | Compliance | External Tools | +|---------|--------|---------|-----|------------|----------------| +| `discovery` | list | list | list | no | no | +| `quick` | trivy | basic | no | no | trivy | +| `standard` | trivy+grype | full | pods | CIS | trivy, grype | +| `thorough` | all | full | full | all | trivy, grype, kubeaudit | +| `compliance` | config | config | full | all | kubeaudit | +| `sbom-only` | sbom | no | no | no | syft | + +### Security Checks + +#### Docker Image Checks + +| Check | Severity | Description | +|-------|----------|-------------| +| Known CVEs | Varies | Vulnerabilities detected by Trivy/Grype | +| Outdated Base Image | Medium | Base image has known updates | +| Root User | Medium | Container runs as root | +| Exposed Secrets | Critical | API keys, passwords in image layers | +| Insecure Packages | High | Packages with known vulnerabilities | +| Missing Health Check | Low | No HEALTHCHECK instruction | + +#### Docker Runtime Checks + +| Check | Severity | Description | +|-------|----------|-------------| +| Privileged Container | Critical | --privileged flag used | +| Host Network | High | Host network namespace shared | +| Host PID/IPC | High | Host PID/IPC namespace shared | +| Sensitive Mounts | Critical | /etc, /var/run/docker.sock mounted | +| Added Capabilities | Medium | CAP_SYS_ADMIN, CAP_NET_RAW, etc. | +| No Resource Limits | Low | CPU/memory limits not set | +| Writable Root FS | Medium | Root filesystem not read-only | + +#### Kubernetes Checks + +| Check | Severity | Description | +|-------|----------|-------------| +| Privileged Pod | Critical | securityContext.privileged: true | +| Host Network/PID/IPC | High | hostNetwork/hostPID/hostIPC: true | +| Root User | Medium | runAsNonRoot: false or runAsUser: 0 | +| Cluster-Admin Binding | Critical | ClusterRoleBinding to cluster-admin | +| Wildcard Permissions | High | RBAC with "*" verbs or resources | +| Default Service Account | Medium | Default SA with automountServiceAccountToken | +| Missing Network Policy | Medium | Namespace without NetworkPolicy | +| Unencrypted Secrets | Medium | Secrets not encrypted at rest | +| No PSA Enforcement | Medium | Pod Security Admission not enforced | + +### Events + +| Event | Description | +|-------|-------------| +| `pentest.containerscan.scan_started` | Scan began | +| `pentest.containerscan.scan_completed` | Scan finished | +| `pentest.containerscan.scan_failed` | Scan failed | +| `pentest.containerscan.image_found` | Docker image discovered | +| `pentest.containerscan.container_found` | Running container discovered | +| `pentest.containerscan.vulnerability_found` | CVE detected in image | +| `pentest.containerscan.misconfiguration_found` | Security misconfiguration detected | +| `pentest.containerscan.secret_found` | Secret detected in image/container | +| `pentest.containerscan.sbom_generated` | SBOM generated for image | +| `pentest.containerscan.compliance_violation` | Compliance check failed | +| `pentest.containerscan.pod_found` | Kubernetes pod discovered | +| `pentest.containerscan.rbac_issue_found` | RBAC misconfiguration detected | +| `pentest.containerscan.network_policy_gap` | Network policy gap detected | +| `pentest.containerscan.registry_scan_completed` | Registry scan finished | + +### Storage + +Container scan data is persisted in: + +``` +pentest/containerscan/ + scans/ + containerscan_abc123.json # Scan results + sboms/ + nginx_latest.json # SBOM files + images/ + image_abc123.json # Image scan results +``` + +### Data Types + +#### ContainerScanResult + +```typescript +{ + id: string + profile: string + status: "pending" | "running" | "completed" | "failed" + startTime: number + endTime?: number + docker: { + images: ImageScanResult[] + containers: ContainerAnalysis[] + configFindings: ContainerFinding[] + } + kubernetes?: { + cluster: ClusterInfo + pods: PodAnalysis[] + rbac: RBACFinding[] + network: NetworkPolicyAnalysis + secrets: SecretAnalysis[] + admission: AdmissionAnalysis + } + registries?: RegistryScanResult[] + compliance?: ComplianceResult[] + findings: ContainerFinding[] + summary: { + totalImages: number + totalContainers: number + totalVulnerabilities: number + bySeverity: { critical, high, medium, low } + } +} +``` + +#### ContainerFinding + +```typescript +{ + id: string + category: "vulnerability" | "misconfiguration" | "secret" | "compliance" + severity: "critical" | "high" | "medium" | "low" | "info" + title: string + description: string + resource: { + type: "image" | "container" | "pod" | "cluster" | "registry" + name: string + namespace?: string + } + cve?: string + cvss?: number + remediation?: string + references?: string[] + detectedAt: number +} +``` + +#### ImageVulnerability + +```typescript +{ + id: string + cveId: string + severity: "critical" | "high" | "medium" | "low" | "unknown" + pkgName: string + installedVersion: string + fixedVersion?: string + title?: string + description?: string + cvss?: number + references?: string[] +} +``` + +### External Tool Commands + +```bash +# Trivy - Image vulnerability scanning +trivy image --format json --severity HIGH,CRITICAL nginx:latest + +# Grype - Image vulnerability scanning +grype nginx:latest -o json + +# Syft - SBOM generation +syft nginx:latest -o json + +# Kubeaudit - Kubernetes audit +kubeaudit all --json +``` + +### Example Tool Usage + +```bash +# Discover images and containers +containerscan discover + +# Scan a specific image +containerscan scan-image image=nginx:latest + +# Generate SBOM +containerscan sbom image=nginx:latest format=cyclonedx + +# Scan running containers +containerscan scan-runtime + +# Scan Kubernetes cluster +containerscan scan-cluster rbac=true pods=true network=true + +# Run compliance check +containerscan compliance framework=cis-docker + +# Scan a registry +containerscan scan-registry type=ecr region=us-east-1 + +# Full scan with profile +containerscan scan profile=thorough + +# Check scan status +containerscan status scanId=containerscan_abc123 + +# List profiles +containerscan profiles +``` + +--- + +## Dependencies + +### External Tools Required + +| Tool | Purpose | Installation | +|------|---------|--------------| +| `docker` | Docker CLI | https://docs.docker.com/get-docker/ | +| `kubectl` | Kubernetes CLI | https://kubernetes.io/docs/tasks/tools/ | +| `trivy` | Image vulnerability scanner | https://aquasecurity.github.io/trivy/ | +| `grype` | Dependency vulnerability scanner | https://github.com/anchore/grype | +| `syft` | SBOM generator | https://github.com/anchore/syft | +| `kubeaudit` | K8s security auditor | https://github.com/Shopify/kubeaudit | + +### APIs Used + +| API | URL | Purpose | +|-----|-----|---------| +| NVD API 2.0 | `https://services.nvd.nist.gov/rest/json/cves/2.0` | CVE data | +| OSV API | `https://api.osv.dev/v1` | Open source vulnerabilities | +| CISA KEV | `https://www.cisa.gov/sites/default/files/feeds/known_exploited_vulnerabilities.json` | Known exploited vulnerabilities | + +### Existing Module Dependencies + +- Storage, Bus, Log utilities +- Patterns from: cloudscan, netscan, apiscan modules + +--- + +## Testing + +Run the tests: + +```bash +# CVE module tests +bun test test/pentest/cve.test.ts + +# Container scanner tests +bun test test/pentest/containerscan.test.ts +``` + +## Integration + +Both tools are registered in `src/tool/registry.ts`: +- `CVETool` - Available as `cve` tool +- `ContainerScanTool` - Available as `containerscan` tool + +Exports available from `src/pentest/index.ts`: +- All CVE types, cache, lookup, enricher +- All container scan types, events, storage, profiles +- All parsers (Trivy, Grype, Syft, Kubeaudit) +- All Docker utilities (images, containers, config, secrets) +- All Kubernetes utilities (cluster, pods, rbac, network, secrets, admission) +- All registry integrations (Docker Hub, ECR, ACR, GCR) diff --git a/docs/PHASE13-mobile-app-scanner.md b/docs/PHASE13-mobile-app-scanner.md new file mode 100644 index 00000000000..3fc6f0ca43a --- /dev/null +++ b/docs/PHASE13-mobile-app-scanner.md @@ -0,0 +1,687 @@ +# Phase 13: Mobile Application Scanner + +## Overview + +Phase 13 introduces the **Mobile Application Scanner** (`pentest/mobilescan/`) - a comprehensive security analysis module for Android APK and iOS IPA files, providing OWASP Mobile Top 10 2024 coverage. + +## Module Structure + +``` +src/pentest/mobilescan/ +├── index.ts # Module exports +├── types.ts # MobileScanTypes namespace (Zod schemas) +├── events.ts # MobileScanEvents +├── storage.ts # Scan persistence +├── profiles.ts # Scan profiles +├── tool.ts # MobileScanTool for agent +├── orchestrator.ts # Scan coordination +├── parsers/ +│ ├── index.ts +│ ├── apktool.ts # APKTool output parser +│ ├── jadx.ts # JADX decompiled source parser +│ ├── mobsf.ts # MobSF JSON report parser +│ └── androguard.ts # Androguard analysis parser +├── android/ +│ ├── index.ts +│ ├── manifest.ts # AndroidManifest.xml analysis +│ ├── permissions.ts # Permission risk analysis +│ ├── components.ts # Activity/Service/Receiver analysis +│ └── security.ts # Crypto, storage, network analysis +├── ios/ +│ ├── index.ts +│ ├── plist.ts # Info.plist analysis +│ └── security.ts # Binary, keychain, ATS analysis +└── common/ + ├── index.ts + ├── ssl-pinning.ts # Certificate pinning detection + ├── root-detection.ts # Root/jailbreak detection + ├── obfuscation.ts # Code obfuscation analysis + ├── api-keys.ts # API key extraction with entropy + └── urls.ts # URL/endpoint extraction +``` + +## OWASP Mobile Top 10 2024 Coverage + +| ID | Category | Checks | +|----|----------|--------| +| M1 | Improper Credential Usage | Hardcoded credentials, insecure key storage, credentials in URLs | +| M2 | Inadequate Supply Chain Security | Third-party library analysis, known vulnerabilities | +| M3 | Insecure Authentication/Authorization | Weak auth patterns, missing session management | +| M4 | Insufficient Input/Output Validation | Input validation, SQL injection, path traversal | +| M5 | Insecure Communication | Missing SSL pinning, cleartext traffic, weak TLS | +| M6 | Inadequate Privacy Controls | Excessive permissions, data leakage, tracking | +| M7 | Insufficient Binary Protections | Missing PIE, no obfuscation, debug enabled | +| M8 | Security Misconfiguration | Backup enabled, debug mode, exported components | +| M9 | Insecure Data Storage | Cleartext storage, SQLite, SharedPreferences | +| M10 | Insufficient Cryptography | Weak algorithms, hardcoded keys, insecure random | + +## Usage + +### Basic Analysis + +```typescript +import { MobileScanOrchestrator, MobileScanProfiles } from "./pentest/mobilescan" + +// Full analysis with standard profile +const result = await MobileScanOrchestrator.analyze("/path/to/app.apk", { + profile: "standard" +}) + +console.log(`Platform: ${result.platform}`) +console.log(`Findings: ${result.findings.length}`) +console.log(`Secrets: ${result.secrets.length}`) +console.log(`URLs: ${result.urls.length}`) + +// Quick scan for critical issues +const quickResult = await MobileScanOrchestrator.quickScan("/path/to/app.apk") + +// Get scan status +const status = await MobileScanOrchestrator.getStatus(result.id) + +// List analyzed apps +const apps = await MobileScanOrchestrator.listApps() +``` + +### Android APK Analysis + +```typescript +import { ManifestAnalyzer, PermissionAnalyzer, ComponentAnalyzer, AndroidSecurityAnalyzer } from "./pentest/mobilescan" + +// Parse AndroidManifest.xml +const manifest = await ManifestAnalyzer.parseManifest("/path/to/extracted/AndroidManifest.xml") +console.log(`Package: ${manifest.packageName}`) +console.log(`Debuggable: ${manifest.debuggable}`) +console.log(`Allow Backup: ${manifest.allowBackup}`) +console.log(`Min SDK: ${manifest.minSdkVersion}`) + +// Analyze permissions +const permissions = PermissionAnalyzer.analyzePermissions(manifest.permissions) +console.log(`Total: ${permissions.total}`) +console.log(`Dangerous: ${permissions.dangerous}`) +console.log(`High Risk: ${permissions.highRisk.join(", ")}`) + +// Check unusual permission combinations +const unusual = PermissionAnalyzer.checkUnusualCombinations(manifest.permissions) +for (const combo of unusual) { + console.log(`[!] ${combo}`) +} + +// Analyze exported components +const compFindings = ComponentAnalyzer.analyzeExportedComponents( + manifest, + scanId, + appId, + "android" +) +console.log(`Component issues: ${compFindings.length}`) + +// Full Android security analysis +const securityFindings = await AndroidSecurityAnalyzer.analyzeAll( + extractedDir, + sourceFiles, + scanId, + appId +) +``` + +### iOS IPA Analysis + +```typescript +import { PlistAnalyzer, iOSSecurityAnalyzer } from "./pentest/mobilescan" + +// Parse Info.plist +const plist = await PlistAnalyzer.parsePlist("/path/to/extracted/Info.plist") +console.log(`Bundle ID: ${plist.bundleId}`) +console.log(`Version: ${plist.version}`) +console.log(`Min iOS: ${plist.minOSVersion}`) +console.log(`ATS Allows Arbitrary Loads: ${plist.atsSettings?.allowsArbitraryLoads}`) + +// Analyze ATS settings +const atsFindings = PlistAnalyzer.analyzeATSSettings( + plist.atsSettings, + scanId, + appId, + "ios" +) + +// Full iOS security analysis +const iosFindings = await iOSSecurityAnalyzer.analyzeAll( + extractedDir, + sourceFiles, + scanId, + appId +) +``` + +### Common Analysis Modules + +```typescript +import { + SSLPinningDetector, + RootDetector, + ObfuscationAnalyzer, + ApiKeyExtractor, + UrlExtractor +} from "./pentest/mobilescan" + +// SSL Pinning Detection +const sslResult = await SSLPinningDetector.detect(sourceFiles, "android") +console.log(`SSL Pinning Detected: ${sslResult.detected}`) +if (sslResult.implementation) { + console.log(`Implementation: ${sslResult.implementation}`) +} + +// Root/Jailbreak Detection +const rootResult = await RootDetector.detect(sourceFiles, "android") +console.log(`Root Detection: ${rootResult.detected}`) +console.log(`Methods: ${rootResult.methods.join(", ")}`) +console.log(`Strength: ${rootResult.strength}`) + +// Code Obfuscation Analysis +const obfResult = await ObfuscationAnalyzer.analyze(sourceFiles, "android") +console.log(`Obfuscation Detected: ${obfResult.detected}`) +console.log(`Tool: ${obfResult.tool}`) +console.log(`Strength: ${obfResult.strength}`) + +// API Key Extraction +const secrets = await ApiKeyExtractor.extractFromFiles(sourceFiles) +for (const secret of secrets) { + console.log(`[${secret.type}] ${secret.maskedValue}`) + console.log(` File: ${secret.location.file}:${secret.location.line}`) + console.log(` Confidence: ${secret.confidence}`) + console.log(` Entropy: ${secret.entropy}`) +} + +// URL Extraction +const urls = await UrlExtractor.extractFromFiles(sourceFiles) +const categorized = UrlExtractor.categorizeUrls(urls) +console.log(`API Endpoints: ${categorized.api.length}`) +console.log(`Internal URLs: ${categorized.internal.length}`) +console.log(`Insecure HTTP: ${categorized.insecure.length}`) +console.log(`With Credentials: ${categorized.withCredentials.length}`) +``` + +### Using Parsers + +```typescript +import { ApktoolParser, JadxParser, MobsfParser, AndroguardParser } from "./pentest/mobilescan" + +// Parse APKTool output +const apktoolManifest = ApktoolParser.parseManifest(manifestXml) +const apktoolStrings = ApktoolParser.parseStrings(stringsXml) + +// Parse JADX decompiled sources +const jadxStrings = JadxParser.extractStrings(sourceFiles) +const jadxUrls = JadxParser.extractUrls(sourceFiles) +const jadxApiKeys = await JadxParser.extractApiKeys(sourceFiles) + +// Parse MobSF report +const mobsfReport = MobsfParser.parseAndroidReport(jsonReport, scanId, appId) +console.log(`Findings: ${mobsfReport.findings.length}`) +console.log(`Secrets: ${mobsfReport.secrets.length}`) +console.log(`Security Score: ${mobsfReport.securityScore}`) + +// Parse Androguard output +const androguardResult = AndroguardParser.parseAnalysis(jsonOutput, scanId, appId, "android") +``` + +## Tool Actions + +| Action | Description | +|--------|-------------| +| `analyze` | Full analysis with specified profile | +| `quick-scan` | Fast scan for critical issues only | +| `manifest` | Analyze AndroidManifest.xml or Info.plist | +| `permissions` | Permission risk analysis | +| `network` | Network security configuration analysis | +| `storage` | Data storage security analysis | +| `crypto` | Cryptographic implementation review | +| `secrets` | Hardcoded secrets/API key detection | +| `ssl-pinning` | Certificate pinning detection | +| `binary` | Binary protection analysis | +| `components` | Exported components analysis (Android) | +| `decompile` | Decompile APK/IPA for manual review | +| `sbom` | Generate software bill of materials | +| `status` | Get scan status | +| `apps` | List analyzed apps | +| `findings` | Get findings for a scan | +| `profiles` | List available scan profiles | + +## Scan Profiles + +| Profile | Static Analysis | Decompile | External Tools | Use Case | +|---------|-----------------|-----------|----------------|----------| +| `discovery` | Manifest only | No | APKTool | Quick app identification | +| `quick` | Critical checks | No | APKTool | Fast triage scan | +| `standard` | Full analysis | Partial | APKTool, JADX | Regular security assessment | +| `thorough` | Full + libraries | Full | All tools | Comprehensive audit | +| `compliance` | OWASP checks | Full | MobSF | Compliance verification | + +## Security Checks + +### Android Checks + +| Check | Severity | OWASP | Description | +|-------|----------|-------|-------------| +| Debuggable App | Critical | M8 | android:debuggable="true" | +| Allow Backup | High | M9 | android:allowBackup="true" | +| Cleartext Traffic | High | M5 | usesCleartextTraffic="true" | +| Exported Components | Medium-Critical | M8 | Unprotected activities/services/receivers | +| Dangerous Permissions | Varies | M6 | READ_CONTACTS, CAMERA, LOCATION, etc. | +| Weak Crypto | High | M10 | DES, MD5, SHA1, ECB mode | +| Hardcoded Keys | Critical | M1 | API keys, secrets in code | +| Insecure Storage | High | M9 | MODE_WORLD_READABLE/WRITABLE | +| SQL Injection | High | M4 | Raw queries with concatenation | +| Missing SSL Pinning | Medium | M5 | No certificate pinning | +| Missing Root Detection | Low | M7 | No root/emulator detection | +| No Obfuscation | Low | M7 | Easily reverse-engineered | + +### iOS Checks + +| Check | Severity | OWASP | Description | +|-------|----------|-------|-------------| +| ATS Disabled | High | M5 | NSAllowsArbitraryLoads = YES | +| Missing PIE | High | M7 | Position Independent Executable disabled | +| Missing ARC | Medium | M7 | Automatic Reference Counting disabled | +| No Stack Canary | High | M7 | Stack smashing protection disabled | +| Symbols Not Stripped | Low | M7 | Debug symbols exposed | +| Weak Crypto | High | M10 | Insecure algorithms | +| Hardcoded Keys | Critical | M1 | API keys, secrets in code | +| Insecure Keychain | High | M9 | kSecAttrAccessibleAlways | +| Missing Jailbreak Detection | Low | M7 | No jailbreak detection | +| Insecure URL Schemes | Medium | M8 | Custom URL scheme vulnerabilities | + +## Events + +| Event | Description | +|-------|-------------| +| `pentest.mobilescan.scan_started` | Scan began | +| `pentest.mobilescan.scan_completed` | Scan finished | +| `pentest.mobilescan.scan_failed` | Scan failed | +| `pentest.mobilescan.app_analyzed` | App metadata extracted | +| `pentest.mobilescan.finding_detected` | Security issue found | +| `pentest.mobilescan.secret_found` | Hardcoded secret detected | +| `pentest.mobilescan.permission_risk` | Risky permission identified | +| `pentest.mobilescan.ssl_pinning_missing` | No SSL pinning detected | +| `pentest.mobilescan.component_exported` | Unprotected component found | + +## Data Types + +### MobileApp + +```typescript +{ + id: string // Unique app ID + sessionId: string // Session ID + platform: "android" | "ios" + name: string // App name + packageName: string // com.example.app or bundle ID + version: string + minSdkVersion?: number // Android only + targetSdkVersion?: number // Android only + minOSVersion?: string // iOS only + filePath: string + fileHash: string + size: number + analyzedAt: number +} +``` + +### MobileScanResult + +```typescript +{ + id: string + appId: string + app: MobileApp + profile: string + platform: "android" | "ios" + status: "pending" | "running" | "completed" | "failed" + findings: MobileFinding[] + manifest?: AndroidManifest | IOSPlist + permissions?: PermissionAnalysis + networkSecurity?: NetworkSecurityAnalysis + binaryProtections?: BinaryProtections + storageAnalysis?: StorageAnalysis + cryptoAnalysis?: CryptoAnalysis + rootDetection?: RootDetectionResult + obfuscation?: ObfuscationResult + secrets: ExtractedSecret[] + urls: ExtractedURL[] + libraries: ThirdPartyLibrary[] + stats: ScanStats + startTime: number + endTime?: number + error?: string +} +``` + +### MobileFinding + +```typescript +{ + id: string + scanId: string + appId: string + platform: "android" | "ios" + title: string + description: string + severity: "critical" | "high" | "medium" | "low" | "info" + owaspMobile: "M1" | "M2" | ... | "M10" + category: string // manifest, permissions, crypto, etc. + component?: string // Activity, Service, etc. + codeLocation?: { + file: string + line?: number + snippet?: string + } + evidence?: string + cwe?: string + cvss?: number + recommendation?: string + references?: string[] + falsePositive: boolean + verified: boolean + detectedAt: number +} +``` + +### ExtractedSecret + +```typescript +{ + id: string + type: "api_key" | "aws_key" | "gcp_key" | "firebase_key" | + "private_key" | "jwt_secret" | "oauth_secret" | + "database_credential" | "generic_secret" | ... + value: string + maskedValue: string + location: { + file: string + line?: number + snippet?: string + } + confidence: "high" | "medium" | "low" + entropy?: number + context?: string +} +``` + +## External Tools + +### Required Tools + +| Tool | Purpose | Command | Installation | +|------|---------|---------|--------------| +| APKTool | APK unpacking | `apktool d app.apk -o output/` | https://ibotpeaches.github.io/Apktool/ | +| JADX | Java decompilation | `jadx -d output/ app.apk` | https://github.com/skylot/jadx | + +### Optional Tools + +| Tool | Purpose | Command | Installation | +|------|---------|---------|--------------| +| MobSF | Full mobile analysis | REST API | https://github.com/MobSF/Mobile-Security-Framework-MobSF | +| Androguard | Python analysis | `androguard analyze app.apk` | https://github.com/androguard/androguard | +| aapt2 | APK metadata | `aapt2 dump badging app.apk` | Android SDK | +| dex2jar | DEX conversion | `d2j-dex2jar app.apk` | https://github.com/pxb1988/dex2jar | +| Frida | Dynamic analysis | `frida -U -f package` | https://frida.re/ | +| objection | Runtime manipulation | `objection explore` | https://github.com/sensepost/objection | + +## Example Use Cases + +### Use Case 1: Pre-Release Security Audit + +Perform a thorough security assessment before app release. + +```bash +# Full analysis with thorough profile +mobilescan analyze file=/path/to/release.apk profile=thorough + +# Check findings +mobilescan findings scanId=mobilescan_abc123 severity=critical + +# Generate SBOM for compliance +mobilescan sbom file=/path/to/release.apk +``` + +### Use Case 2: Quick Triage of Multiple Apps + +Quickly identify critical issues across multiple applications. + +```bash +# Quick scan each app +mobilescan quick-scan file=/path/to/app1.apk +mobilescan quick-scan file=/path/to/app2.apk +mobilescan quick-scan file=/path/to/app3.apk + +# List all analyzed apps +mobilescan apps +``` + +### Use Case 3: API Security Review + +Focus on API communication and secrets. + +```bash +# Check for hardcoded secrets +mobilescan secrets file=/path/to/app.apk + +# Analyze SSL pinning +mobilescan ssl-pinning file=/path/to/app.apk + +# Review network security config +mobilescan network file=/path/to/app.apk +``` + +### Use Case 4: Permission Audit + +Review app permissions for privacy compliance. + +```bash +# Analyze permissions +mobilescan permissions file=/path/to/app.apk +``` + +Example output: +``` +Permission Analysis +======================================== +Total Permissions: 15 +Dangerous: 5 +Normal: 8 +Signature: 2 +Custom: 0 + +High Risk Permissions: + [!] android.permission.READ_CONTACTS + [!] android.permission.ACCESS_FINE_LOCATION + [!] android.permission.CAMERA + +Unusual Combinations: + [!] App requests both CAMERA and RECORD_AUDIO without media features + [!] App requests SMS and CONTACTS - potential data harvesting + +Recommendations: + - Review necessity of READ_CONTACTS permission + - Consider using ACCESS_COARSE_LOCATION instead of ACCESS_FINE_LOCATION +``` + +### Use Case 5: Decompile for Manual Review + +Extract and decompile app for manual code review. + +```bash +# Decompile to directory +mobilescan decompile file=/path/to/app.apk outputDir=/tmp/decompiled + +# Manual review +ls /tmp/decompiled/ +# AndroidManifest.xml +# res/ +# smali/ +# sources/ (if JADX available) +``` + +### Use Case 6: iOS App Security Assessment + +Analyze iOS IPA file. + +```bash +# Full iOS analysis +mobilescan analyze file=/path/to/app.ipa profile=standard + +# Check binary protections +mobilescan binary file=/path/to/app.ipa +``` + +Example output: +``` +Binary Protection Analysis +======================================== +PIE (ASLR): Yes +ARC: Yes +Stack Canary: Yes +Symbols Stripped: No (symbols exposed) +Encrypted: Yes + +Root/Jailbreak Detection: + Detected: Yes + Methods: fileExistsAtPath, canOpenURL, fopen + Strength: medium + +Code Obfuscation: + Detected: No +``` + +### Use Case 7: Continuous Integration + +Integrate into CI/CD pipeline. + +```typescript +import { MobileScanOrchestrator } from "./pentest/mobilescan" + +async function securityGate(apkPath: string): Promise { + const result = await MobileScanOrchestrator.analyze(apkPath, { + profile: "quick" + }) + + const criticalFindings = result.findings.filter(f => f.severity === "critical") + const highFindings = result.findings.filter(f => f.severity === "high") + + if (criticalFindings.length > 0) { + console.error(`FAILED: ${criticalFindings.length} critical findings`) + for (const f of criticalFindings) { + console.error(` - ${f.title} (${f.owaspMobile})`) + } + return false + } + + if (highFindings.length > 5) { + console.error(`FAILED: Too many high-severity findings (${highFindings.length})`) + return false + } + + console.log("PASSED: Security gate checks") + return true +} +``` + +## Storage + +Scan data is persisted in: + +``` +pentest/mobilescan/ + scans/ + mobilescan_abc123.json # Scan results + apps/ + app_def456.json # App metadata + findings/ + finding_ghi789.json # Individual findings + secrets/ + secret_jkl012.json # Extracted secrets +``` + +## Testing + +Run the tests: + +```bash +bun test test/pentest/mobilescan.test.ts +``` + +## Integration + +The tool is registered in `src/tool/registry.ts`: +- `MobileScanTool` - Available as `mobilescan` tool + +Exports available from `src/pentest/index.ts`: +- All types: `MobileScanTypes` +- Events: `MobileScanEvents` +- Storage: `MobileScanStorage` +- Profiles: `MobileScanProfiles` +- Orchestrator: `MobileScanOrchestrator` +- Tool: `MobileScanTool` +- Parsers: `ApktoolParser`, `JadxParser`, `MobsfParser`, `AndroguardParser` +- Android: `ManifestAnalyzer`, `PermissionAnalyzer`, `ComponentAnalyzer`, `AndroidSecurityAnalyzer` +- iOS: `PlistAnalyzer`, `iOSSecurityAnalyzer` +- Common: `SSLPinningDetector`, `RootDetector`, `ObfuscationAnalyzer`, `ApiKeyExtractor`, `UrlExtractor` + +## API Key Detection Patterns + +The scanner detects the following secret patterns: + +| Type | Pattern | Example | +|------|---------|---------| +| AWS Access Key | `AKIA[0-9A-Z]{16}` | AKIAIOSFODNN7EXAMPLE | +| AWS Secret Key | `[A-Za-z0-9/+=]{40}` | wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY | +| Google API Key | `AIza[0-9A-Za-z_-]{35}` | AIzaSyDaGmWKa4JsXZ-HjGw7ISLn_3namBGewQe | +| Firebase Key | `AIza[0-9A-Za-z_-]{35}` | AIzaSyClzfrOzB818x55FASHvX4JuGQciR9lv7q | +| GitHub Token | `gh[pousr]_[A-Za-z0-9_]{36}` | ghp_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx | +| Private Key | `-----BEGIN.*PRIVATE KEY-----` | RSA, EC, DSA private keys | +| JWT Secret | High entropy strings in JWT context | - | +| Generic API Key | `[A-Za-z0-9_-]{20,}` with high entropy | - | + +## SSL Pinning Detection Patterns + +### Android + +| Implementation | Pattern | +|----------------|---------| +| OkHttp CertificatePinner | `CertificatePinner.Builder()` | +| Network Security Config | `pin-set` in XML | +| TrustManager | `X509TrustManager`, `checkServerTrusted` | +| Retrofit | `certificatePinner` | + +### iOS + +| Implementation | Pattern | +|----------------|---------| +| URLSession | `URLSessionDelegate`, `didReceiveChallenge` | +| TrustKit | `TrustKit`, `TSKPinningValidator` | +| Alamofire | `ServerTrustManager`, `PinnedCertificatesTrustEvaluator` | +| AFNetworking | `AFSecurityPolicy`, `pinnedCertificates` | + +## Root/Jailbreak Detection Patterns + +### Android Root Detection + +| Check | Description | +|-------|-------------| +| Su binary | `/system/xbin/su`, `/system/bin/su` | +| Superuser app | `/system/app/Superuser.apk` | +| Magisk | `magisk`, `MagiskManager` | +| Build tags | `test-keys` | +| Dangerous props | `ro.debuggable=1` | +| RW system | Writable system partition | + +### iOS Jailbreak Detection + +| Check | Description | +|-------|-------------| +| Cydia | `/Applications/Cydia.app` | +| Substrate | `/Library/MobileSubstrate` | +| SSH | `/usr/sbin/sshd`, `/usr/bin/ssh` | +| Apt | `/etc/apt` | +| URL schemes | `cydia://` | +| Fork | `fork()` behavior | diff --git a/docs/PHASE14-wireless-scanner.md b/docs/PHASE14-wireless-scanner.md new file mode 100644 index 00000000000..c7e10e2470c --- /dev/null +++ b/docs/PHASE14-wireless-scanner.md @@ -0,0 +1,625 @@ +# Phase 14: Wireless Network Scanner + +## Overview + +Phase 14 introduces the **Wireless Network Scanner** (`pentest/wirelessscan/`) - a comprehensive security scanner for WiFi, Bluetooth, and RFID/NFC technologies, providing vulnerability assessment and rogue device detection. + +## Module Structure + +``` +src/pentest/wirelessscan/ +├── index.ts # Module exports +├── types.ts # WirelessScanTypes namespace (Zod schemas) +├── events.ts # WirelessScanEvents +├── storage.ts # Scan persistence +├── profiles.ts # Scan profiles +├── tool.ts # WirelessScanTool for agent +├── orchestrator.ts # Scan coordination +├── parsers/ +│ ├── index.ts +│ ├── aircrack.ts # Aircrack-ng output parser +│ ├── kismet.ts # Kismet output parser +│ ├── bettercap.ts # Bettercap output parser +│ ├── ubertooth.ts # Ubertooth output parser +│ └── hcxtools.ts # Hcxtools output parser +├── wifi/ +│ ├── index.ts +│ ├── discovery.ts # WiFi network discovery +│ ├── security.ts # WPA/WPA2/WPA3 assessment +│ ├── rogue-ap.ts # Rogue AP and evil twin detection +│ ├── clients.ts # Client enumeration +│ ├── handshake.ts # Handshake capture and analysis +│ └── deauth.ts # Deauthentication detection +├── bluetooth/ +│ ├── index.ts +│ ├── discovery.ts # Bluetooth device discovery +│ ├── ble.ts # BLE service enumeration +│ ├── classic.ts # Classic Bluetooth scanning +│ ├── profiles.ts # Bluetooth profile analysis +│ └── vulnerabilities.ts # BlueBorne, KNOB, BIAS checks +└── rfid/ + ├── index.ts + ├── discovery.ts # RFID/NFC tag discovery + ├── readers.ts # Reader detection and enumeration + ├── cards.ts # Card type identification + ├── cloning.ts # Cloning vulnerability assessment + └── vulnerabilities.ts # RFID-specific vulnerabilities +``` + +## Capabilities + +### WiFi Security Assessment + +| Feature | Description | +|---------|-------------| +| Network Discovery | Enumerate all visible WiFi networks with metadata | +| WPA/WPA2 Assessment | Security configuration analysis | +| WPA3 Assessment | SAE and OWE implementation checks | +| KRACK Detection | Key Reinstallation Attack vulnerability | +| Dragonblood Detection | WPA3 implementation flaws | +| PMKID Capture | PMKID-based attack capability check | +| Rogue AP Detection | Identify unauthorized access points | +| Evil Twin Detection | Detect spoofed SSIDs | +| Client Enumeration | Connected client analysis with OUI lookup | +| Probe Analysis | Client probe request monitoring | +| Handshake Capture | WPA 4-way handshake capture and validation | +| Deauth Detection | Deauthentication attack monitoring | +| WPS Assessment | WPS security and lockout status | + +### Bluetooth Security Assessment + +| Feature | Description | +|---------|-------------| +| Device Discovery | Classic and BLE device enumeration | +| Service Enumeration | Bluetooth service and profile discovery | +| BlueBorne Detection | CVE-2017-0781 and related vulnerabilities | +| KNOB Attack | Key Negotiation of Bluetooth vulnerability | +| BIAS Attack | Bluetooth Impersonation Attack check | +| BLESA Attack | BLE Spoofing Attack vulnerability | +| BLE Security | BLE pairing and encryption analysis | +| Device Classification | Device type and manufacturer identification | + +### RFID/NFC Security Assessment + +| Feature | Description | +|---------|-------------| +| Tag Discovery | Automatic tag detection and identification | +| MIFARE Classic | Default key and crypto-1 vulnerability checks | +| MIFARE DESFire | Security level assessment | +| NTAG Support | NTAG213/215/216 analysis | +| HID Support | HID access card assessment | +| EM4100 Support | Low-frequency tag analysis | +| Cloning Assessment | Cloning vulnerability evaluation | +| Key Analysis | Key reuse and weak key detection | + +## Usage + +### Basic Wireless Scan + +```typescript +import { WirelessScanOrchestrator, WirelessScanProfiles } from "./pentest/wirelessscan" + +// Full wireless scan with standard profile +const result = await WirelessScanOrchestrator.scan({ + profile: "standard", + interface: "wlan0", + duration: 60 // seconds +}) + +console.log(`WiFi Networks: ${result.wifi.networks.length}`) +console.log(`Bluetooth Devices: ${result.bluetooth.devices.length}`) +console.log(`RFID Tags: ${result.rfid.tags.length}`) +console.log(`Findings: ${result.findings.length}`) + +// Get scan status +const status = await WirelessScanOrchestrator.getStatus(result.id) + +// List all scans +const scans = await WirelessScanOrchestrator.listScans() +``` + +### WiFi-Specific Scanning + +```typescript +import { WiFiDiscovery, WiFiSecurity, WiFiRogueAP, WiFiHandshake, WiFiClients } from "./pentest/wirelessscan" + +// Discover WiFi networks +const networks = await WiFiDiscovery.scan({ + interface: "wlan0mon", + duration: 30, + channels: [1, 6, 11] +}) + +for (const network of networks) { + console.log(`${network.essid} (${network.bssid})`) + console.log(` Channel: ${network.channel}`) + console.log(` Encryption: ${network.encryption}`) + console.log(` Signal: ${network.signal} dBm`) +} + +// Security assessment +const security = await WiFiSecurity.assess(network) +console.log(`WPA Version: ${security.wpaVersion}`) +console.log(`KRACK Vulnerable: ${security.krackVulnerable}`) +console.log(`PMKID Capturable: ${security.pmkidVulnerable}`) + +// Rogue AP detection +const rogueAPs = await WiFiRogueAP.detect({ + interface: "wlan0mon", + knownNetworks: ["Corp-WiFi", "Guest-WiFi"] +}) + +for (const rogue of rogueAPs) { + console.log(`[!] Rogue AP: ${rogue.essid} (${rogue.bssid})`) + console.log(` Type: ${rogue.type}`) // evil_twin, unauthorized, etc. + console.log(` Risk: ${rogue.risk}`) +} + +// Client enumeration +const clients = await WiFiClients.enumerate({ + interface: "wlan0mon", + bssid: "AA:BB:CC:DD:EE:FF" +}) + +for (const client of clients) { + console.log(`Client: ${client.mac}`) + console.log(` Vendor: ${client.vendor}`) + console.log(` Probes: ${client.probes.join(", ")}`) +} + +// Handshake capture +const handshake = await WiFiHandshake.capture({ + interface: "wlan0mon", + bssid: "AA:BB:CC:DD:EE:FF", + timeout: 120 +}) + +if (handshake.complete) { + console.log(`Handshake captured: ${handshake.file}`) + console.log(`Type: ${handshake.type}`) // 4-way, pmkid +} +``` + +### Bluetooth Scanning + +```typescript +import { BluetoothDiscovery, BluetoothBLE, BluetoothClassic, BluetoothVulnerabilities } from "./pentest/wirelessscan" + +// Discover Bluetooth devices +const devices = await BluetoothDiscovery.scan({ + duration: 30, + bleOnly: false, + classicOnly: false +}) + +for (const device of devices) { + console.log(`${device.name || "Unknown"} (${device.address})`) + console.log(` Type: ${device.type}`) // classic, ble, dual + console.log(` Class: ${device.deviceClass}`) + console.log(` Vendor: ${device.vendor}`) +} + +// BLE service enumeration +const services = await BluetoothBLE.enumerateServices(device.address) +for (const service of services) { + console.log(`Service: ${service.uuid}`) + console.log(` Name: ${service.name}`) + for (const char of service.characteristics) { + console.log(` Characteristic: ${char.uuid}`) + } +} + +// Vulnerability checks +const vulns = await BluetoothVulnerabilities.check(device) +console.log(`BlueBorne: ${vulns.blueBorne}`) +console.log(`KNOB: ${vulns.knob}`) +console.log(`BIAS: ${vulns.bias}`) +console.log(`BLESA: ${vulns.blesa}`) +``` + +### RFID/NFC Scanning + +```typescript +import { RFIDDiscovery, RFIDReaders, RFIDCards, RFIDCloning, RFIDVulnerabilities } from "./pentest/wirelessscan" + +// Detect readers +const readers = await RFIDReaders.detect() +for (const reader of readers) { + console.log(`Reader: ${reader.name}`) + console.log(` Type: ${reader.type}`) // proxmark3, acr122u, etc. + console.log(` Frequencies: ${reader.frequencies.join(", ")}`) +} + +// Discover tags +const tags = await RFIDDiscovery.scan({ + reader: readers[0].name, + frequency: "13.56mhz" +}) + +for (const tag of tags) { + console.log(`Tag: ${tag.uid}`) + console.log(` Type: ${tag.type}`) // mifare_classic, desfire, ntag, etc. + console.log(` Size: ${tag.size} bytes`) +} + +// Card analysis +const cardInfo = await RFIDCards.analyze(tag) +console.log(`Sectors: ${cardInfo.sectors}`) +console.log(`Keys Found: ${cardInfo.keysFound}`) +console.log(`Default Keys: ${cardInfo.defaultKeys}`) + +// Cloning assessment +const clonable = await RFIDCloning.assess(tag) +console.log(`Clonable: ${clonable.vulnerable}`) +console.log(`Method: ${clonable.method}`) +console.log(`Difficulty: ${clonable.difficulty}`) + +// Vulnerability checks +const rfidVulns = await RFIDVulnerabilities.check(tag) +console.log(`Crypto-1 Weak: ${rfidVulns.crypto1Weak}`) +console.log(`Default Keys: ${rfidVulns.defaultKeys}`) +console.log(`Replay Possible: ${rfidVulns.replayPossible}`) +``` + +### Using Parsers + +```typescript +import { AircrackParser, KismetParser, BettercapParser, UbertoothParser, HcxToolsParser } from "./pentest/wirelessscan" + +// Parse Aircrack-ng output +const airodumpOutput = await fs.readFile("/tmp/scan-01.csv", "utf-8") +const aircrackResult = AircrackParser.parseCSV(airodumpOutput) +console.log(`Networks: ${aircrackResult.networks.length}`) +console.log(`Clients: ${aircrackResult.clients.length}`) + +// Parse Kismet output +const kismetOutput = await fs.readFile("/tmp/kismet.json", "utf-8") +const kismetResult = KismetParser.parseJSON(kismetOutput) + +// Parse Bettercap output +const bettercapOutput = await fs.readFile("/tmp/bettercap.json", "utf-8") +const bettercapResult = BettercapParser.parseJSON(bettercapOutput) + +// Parse Ubertooth output +const ubertoothOutput = await fs.readFile("/tmp/ubertooth.txt", "utf-8") +const ubertoothResult = UbertoothParser.parse(ubertoothOutput) + +// Parse hcxtools output +const pmkidOutput = await fs.readFile("/tmp/pmkid.16800", "utf-8") +const hcxResult = HcxToolsParser.parsePMKID(pmkidOutput) +``` + +## Tool Actions + +| Action | Description | +|--------|-------------| +| `scan` | Full wireless scan with specified profile | +| `wifi` | WiFi-specific scanning | +| `bluetooth` | Bluetooth device scanning | +| `rfid` | RFID/NFC tag scanning | +| `interfaces` | List available wireless interfaces | +| `networks` | List discovered WiFi networks | +| `devices` | List discovered Bluetooth devices | +| `tags` | List discovered RFID/NFC tags | +| `security` | Security assessment for a scan | +| `rogue-ap` | Rogue AP and evil twin detection | +| `handshake` | Capture/analyze WPA handshakes | +| `baseline` | Manage network baselines | +| `report` | Generate scan report | +| `status` | Get scan status | +| `stop` | Stop a running scan | +| `profiles` | List available scan profiles | + +## Scan Profiles + +| Profile | WiFi | Bluetooth | RFID | Active Tests | Stealth | +|---------|------|-----------|------|--------------|---------| +| `discovery` | Passive scan | Discovery only | Read only | No | Yes | +| `quick` | Basic scan | Quick scan | Basic | Minimal | Partial | +| `standard` | Full passive | Full scan | Full read | No | Yes | +| `thorough` | Comprehensive | Deep scan | Full analysis | Some | No | +| `passive` | Listen only | Listen only | None | No | Yes | +| `active` | Full active | Active probe | Write tests | Yes | No | + +## Security Checks + +### WiFi Vulnerabilities + +| Vulnerability | CVE | Severity | Description | +|--------------|-----|----------|-------------| +| KRACK | CVE-2017-13077 | High | Key Reinstallation Attack | +| Dragonblood | CVE-2019-9494 | High | WPA3 SAE vulnerabilities | +| PMKID Attack | N/A | Medium | PMKID-based offline attack | +| WPS PIN | N/A | Medium | Weak WPS implementation | +| Hidden SSID | N/A | Low | SSID hiding (ineffective) | +| Open Network | N/A | High | No encryption | +| WEP | N/A | Critical | Broken encryption | +| WPA-TKIP | N/A | Medium | Deprecated cipher | + +### Bluetooth Vulnerabilities + +| Vulnerability | CVE | Severity | Description | +|--------------|-----|----------|-------------| +| BlueBorne | CVE-2017-0781 | Critical | RCE via Bluetooth | +| KNOB | CVE-2019-9506 | High | Key Negotiation weakness | +| BIAS | CVE-2020-10135 | High | Impersonation attack | +| BLESA | CVE-2020-9770 | Medium | BLE spoofing attack | +| BlueSmack | N/A | Medium | DoS attack | +| BlueSnarfing | N/A | High | Data theft | +| BlueJacking | N/A | Low | Unsolicited messages | + +### RFID Vulnerabilities + +| Vulnerability | Severity | Description | +|--------------|----------|-------------| +| Default Keys | Critical | Factory default keys in use | +| Crypto-1 Weak | Critical | MIFARE Classic crypto weakness | +| UID Cloning | High | UID-only authentication | +| Replay Attack | High | Captured data replay | +| Side Channel | Medium | Power analysis attacks | +| No Auth | Critical | No authentication required | + +## Events + +| Event | Description | +|-------|-------------| +| `pentest.wirelessscan.scan_started` | Scan initiated | +| `pentest.wirelessscan.scan_completed` | Scan finished | +| `pentest.wirelessscan.scan_failed` | Scan failed | +| `pentest.wirelessscan.network_discovered` | WiFi network found | +| `pentest.wirelessscan.device_discovered` | Bluetooth device found | +| `pentest.wirelessscan.tag_discovered` | RFID tag found | +| `pentest.wirelessscan.vulnerability_found` | Security issue detected | +| `pentest.wirelessscan.rogue_ap_detected` | Rogue AP identified | +| `pentest.wirelessscan.handshake_captured` | WPA handshake captured | +| `pentest.wirelessscan.deauth_detected` | Deauth attack detected | + +## Data Types + +### WiFiNetwork + +```typescript +{ + id: string + bssid: string // AP MAC address + essid: string // Network name + channel: number + frequency: number + band: "2.4ghz" | "5ghz" | "6ghz" + signal: number // dBm + quality: number // 0-100 + encryption: "open" | "wep" | "wpa" | "wpa2" | "wpa3" + cipher: "ccmp" | "tkip" | "wep" | "gcmp" + authentication: "psk" | "eap" | "sae" | "owe" | "open" + wps: boolean + wpsLocked: boolean + hidden: boolean + vendor: string + clients: string[] + pmkidVulnerable: boolean + firstSeen: number + lastSeen: number +} +``` + +### BluetoothDevice + +```typescript +{ + id: string + address: string // MAC address + name: string + type: "classic" | "ble" | "dual" + deviceClass: number + classDescription: string + vendor: string + rssi: number + services: BluetoothService[] + paired: boolean + connected: boolean + legacyPairing: boolean + vulnerabilities: string[] + firstSeen: number + lastSeen: number +} +``` + +### RFIDTag + +```typescript +{ + id: string + uid: string // Tag UID + type: "mifare_classic" | "mifare_desfire" | "ntag" | "hid" | "em4100" + frequency: "125khz" | "13.56mhz" + size: number // bytes + sectors: number + blocks: number + manufacturer: string + atqa: string // Answer to Request A + sak: string // Select Acknowledge + readable: boolean + writable: boolean + clonable: boolean + vulnerabilities: string[] + discoveredAt: number +} +``` + +### WirelessFinding + +```typescript +{ + id: string + scanId: string + type: "wifi" | "bluetooth" | "rfid" + target: string // BSSID, MAC, UID + title: string + description: string + severity: "critical" | "high" | "medium" | "low" | "info" + cve: string[] + cwe: string + recommendation: string + evidence: string + verified: boolean + detectedAt: number +} +``` + +## External Tools + +### Required Tools + +| Tool | Purpose | Installation | +|------|---------|--------------| +| Aircrack-ng | WiFi security suite | `apt install aircrack-ng` | +| iw | Wireless configuration | `apt install iw` | + +### Optional Tools + +| Tool | Purpose | Installation | +|------|---------|--------------| +| Kismet | Wireless detector | https://www.kismetwireless.net/ | +| Bettercap | Network attack tool | https://www.bettercap.org/ | +| Ubertooth | Bluetooth sniffer | https://github.com/greatscottgadgets/ubertooth | +| Proxmark3 | RFID tool | https://github.com/Proxmark/proxmark3 | +| hcxtools | WPA capture tools | https://github.com/ZerBea/hcxtools | +| hcxdumptool | Traffic capture | https://github.com/ZerBea/hcxdumptool | +| Bluez | Linux Bluetooth | `apt install bluez` | +| libnfc | NFC tools | `apt install libnfc-bin` | + +## Example Use Cases + +### Use Case 1: Corporate WiFi Audit + +```bash +# Full corporate WiFi assessment +wirelessscan scan profile=thorough interface=wlan0 duration=300 + +# Check for rogue APs +wirelessscan rogue-ap interface=wlan0mon ssid="Corp-WiFi" + +# Assess specific network +wirelessscan security bssid=AA:BB:CC:DD:EE:FF +``` + +### Use Case 2: Evil Twin Detection + +```bash +# Create baseline of known networks +wirelessscan baseline baselineAction=create baselineName=corporate + +# Monitor for evil twins +wirelessscan scan profile=passive interface=wlan0mon + +# Compare against baseline +wirelessscan baseline baselineAction=compare baselineName=corporate +``` + +### Use Case 3: WPA Handshake Capture + +```bash +# Start handshake capture +wirelessscan handshake interface=wlan0mon bssid=AA:BB:CC:DD:EE:FF + +# Check capture status +wirelessscan status scanId= +``` + +### Use Case 4: Bluetooth Device Audit + +```bash +# Scan for Bluetooth devices +wirelessscan bluetooth duration=60 + +# Check for vulnerabilities +wirelessscan devices +wirelessscan security scanId= +``` + +### Use Case 5: Access Card Assessment + +```bash +# Scan for RFID tags +wirelessscan rfid reader=proxmark3 frequency=13.56mhz + +# Analyze discovered cards +wirelessscan tags + +# Check cloning vulnerability +wirelessscan security scanId= +``` + +## Storage + +Scan data is persisted in: + +``` +pentest/wirelessscan/ + scans/ + wirelessscan_abc123.json # Scan results + networks/ + network_def456.json # WiFi networks + devices/ + device_ghi789.json # Bluetooth devices + tags/ + tag_jkl012.json # RFID tags + findings/ + finding_mno345.json # Security findings + baselines/ + corporate.json # Network baselines +``` + +## Testing + +Run the tests: + +```bash +bun test test/pentest/wirelessscan.test.ts +``` + +## Integration + +The tool is registered in `src/tool/registry.ts`: +- `WirelessScanTool` - Available as `wirelessscan` tool + +Exports available from `src/pentest/index.ts`: +- All types: `WirelessScanTypes` +- Events: `WirelessScanEvents` +- Storage: `WirelessScanStorage` +- Profiles: `WirelessScanProfiles` +- Orchestrator: `WirelessScanOrchestrator` +- Tool: `WirelessScanTool` +- Parsers: `AircrackParser`, `KismetParser`, `BettercapParser`, `UbertoothParser`, `HcxToolsParser` +- WiFi: `WiFiDiscovery`, `WiFiSecurity`, `WiFiRogueAP`, `WiFiClients`, `WiFiHandshake`, `WiFiDeauth` +- Bluetooth: `BluetoothDiscovery`, `BluetoothBLE`, `BluetoothClassic`, `BluetoothProfiles`, `BluetoothVulnerabilities` +- RFID: `RFIDDiscovery`, `RFIDReaders`, `RFIDCards`, `RFIDCloning`, `RFIDVulnerabilities` + +## Hardware Requirements + +### WiFi Scanning + +For passive scanning, any WiFi adapter works. For monitor mode and packet injection: + +| Adapter | Chipset | Monitor | Injection | +|---------|---------|---------|-----------| +| Alfa AWUS036ACH | RTL8812AU | Yes | Yes | +| Alfa AWUS036ACS | RTL8811AU | Yes | Yes | +| TP-Link TL-WN722N v1 | Atheros AR9271 | Yes | Yes | +| Panda PAU09 | Ralink RT5572 | Yes | Yes | + +### Bluetooth Scanning + +| Device | Type | Features | +|--------|------|----------| +| Built-in adapter | HCI | Basic scanning | +| Ubertooth One | BLE sniffer | Packet capture | +| CSR 4.0 dongle | HCI | Extended range | + +### RFID/NFC Scanning + +| Reader | Frequencies | Features | +|--------|-------------|----------| +| Proxmark3 | 125kHz, 13.56MHz | Full analysis | +| ACR122U | 13.56MHz | Basic NFC | +| Chameleon Mini | 13.56MHz | Emulation | diff --git a/docs/PHASE15-social-engineering.md b/docs/PHASE15-social-engineering.md new file mode 100644 index 00000000000..34d5c14c0ec --- /dev/null +++ b/docs/PHASE15-social-engineering.md @@ -0,0 +1,664 @@ +# Phase 15: Social Engineering Toolkit + +## Overview + +Phase 15 introduces the **Social Engineering Toolkit** (`pentest/soceng/`) - a comprehensive framework for authorized security testing, red team engagements, and security awareness training programs. + +> **IMPORTANT DISCLAIMER**: This module is intended for AUTHORIZED security testing ONLY. Unauthorized use against systems or individuals without explicit permission is illegal and unethical. Always ensure written authorization, compliance with applicable laws, proper scoping, and ethical handling of captured data. + +## Module Structure + +``` +src/pentest/soceng/ +├── index.ts # Module exports +├── types.ts # SocEngTypes namespace (Zod schemas) +├── events.ts # SocEngEvents +├── storage.ts # Campaign persistence +├── profiles.ts # Campaign profiles +├── tool.ts # SocEngTool for agent +├── orchestrator.ts # Campaign coordination +├── email/ +│ ├── index.ts +│ ├── generator.ts # Email content generation +│ ├── spoof.ts # Spoofing analysis +│ ├── headers.ts # Email header manipulation +│ └── validation.ts # SPF/DKIM/DMARC validation +├── phishing/ +│ ├── index.ts +│ ├── campaigns.ts # Campaign management +│ ├── templates.ts # Email templates +│ ├── landing.ts # Landing page templates +│ ├── payloads.ts # Phishing payloads +│ └── tracking.ts # Click/open tracking +├── pretexting/ +│ ├── index.ts +│ ├── scenarios.ts # Pretexting scenarios +│ ├── personas.ts # Social engineering personas +│ ├── scripts.ts # Call scripts with dialogue trees +│ └── osint.ts # OSINT integration +├── payloads/ +│ ├── index.ts +│ ├── usb.ts # USB drop payloads +│ ├── documents.ts # Malicious documents +│ ├── macros.ts # VBA macro payloads +│ └── hta.ts # HTA application payloads +├── recon/ +│ ├── index.ts +│ ├── email.ts # Email discovery +│ ├── organization.ts # Organization profiling +│ └── social.ts # Social media reconnaissance +└── awareness/ + ├── index.ts + ├── training.ts # Training modules + ├── metrics.ts # Awareness metrics + └── reporting.ts # Campaign reporting +``` + +## Capabilities + +### Email Security Assessment + +| Feature | Description | +|---------|-------------| +| SPF Validation | Sender Policy Framework configuration check | +| DKIM Validation | DomainKeys Identified Mail verification | +| DMARC Validation | Domain-based Message Authentication check | +| Spoofing Analysis | Email spoofing vulnerability assessment | +| Lookalike Domains | Generate typosquatting/lookalike domains | +| Header Analysis | Email header manipulation detection | + +### Phishing Campaign Management + +| Feature | Description | +|---------|-------------| +| Campaign Creation | Multi-type campaign setup and management | +| Target Import | CSV-based target list import | +| Email Templates | Pre-built and custom phishing templates | +| Landing Pages | Credential harvesting page templates | +| Click Tracking | Open, click, and submission tracking | +| Campaign Reports | Detailed statistics and reports | + +### Pretexting Framework + +| Feature | Description | +|---------|-------------| +| Scenario Library | Pre-built social engineering scenarios | +| Persona Management | Detailed persona profiles | +| Call Scripts | Dialogue trees with objection handlers | +| OSINT Integration | Reconnaissance data integration | +| Objection Handling | Response strategies for resistance | + +### Payload Generation + +| Feature | Description | +|---------|-------------| +| USB Drop | Rubber ducky and BadUSB payloads | +| Office Documents | Macro-enabled document payloads | +| VBA Macros | Custom macro payload generation | +| HTA Applications | HTML Application payloads | +| PDF Exploits | PDF-based payload templates | + +### OSINT Reconnaissance + +| Feature | Description | +|---------|-------------| +| Email Discovery | Email address enumeration | +| Organization Profiling | Company structure analysis | +| Social Media Recon | LinkedIn, Twitter, Facebook reconnaissance | +| Search Query Generation | Optimized OSINT search queries | +| Email Permutations | Email format guessing | + +### Security Awareness + +| Feature | Description | +|---------|-------------| +| Training Modules | Interactive training content | +| Awareness Metrics | Click rate, report rate calculation | +| Industry Benchmarks | Compare against industry standards | +| Executive Reports | Management-ready summaries | +| Quiz Generation | Phishing awareness quizzes | + +## Usage + +### Email Security Assessment + +```typescript +import { EmailValidation, EmailSpoof, EmailGenerator } from "./pentest/soceng" + +// Check domain email security +const security = await EmailValidation.checkDomain("example.com") +console.log(`SPF: ${security.spf.status}`) +console.log(`DKIM: ${security.dkim.status}`) +console.log(`DMARC: ${security.dmarc.status}`) +console.log(`Spoofable: ${security.spoofable}`) + +// Detailed spoofing assessment +const spoofAssessment = await EmailSpoof.assessSpoofability("example.com") +console.log(`Overall Risk: ${spoofAssessment.risk}`) +console.log(`Recommendations: ${spoofAssessment.recommendations.join(", ")}`) + +// Generate lookalike domains +const lookalikes = EmailGenerator.generateLookalikeDomains("example.com") +for (const domain of lookalikes) { + console.log(`${domain.domain} - ${domain.technique}`) +} +``` + +### Phishing Campaign Management + +```typescript +import { PhishingCampaigns, PhishingTemplates, PhishingLanding } from "./pentest/soceng" + +// Create a new campaign +const campaign = await PhishingCampaigns.create({ + name: "Security Awareness Q1 2024", + type: "credential-harvest", + profile: "awareness", + targets: [ + { email: "user1@company.com", firstName: "John", lastName: "Doe", department: "IT" }, + { email: "user2@company.com", firstName: "Jane", lastName: "Smith", department: "HR" }, + ], + templateId: "password-reset", + landingPageId: "microsoft-365", + senderProfile: { + name: "IT Security Team", + email: "security@company-it-support.com", + replyTo: "noreply@company.com" + }, + schedule: { + startTime: Date.now() + 86400000, // Start in 24 hours + sendRate: 10, // 10 emails per hour + randomize: true + } +}) + +console.log(`Campaign created: ${campaign.id}`) + +// List available templates +const templates = PhishingTemplates.list() +for (const template of templates) { + console.log(`${template.id}: ${template.name} (${template.category})`) +} + +// Generate custom template +const customEmail = PhishingTemplates.generate({ + templateId: "password-reset", + variables: { + companyName: "Acme Corp", + targetName: "John Doe", + urgency: "24 hours", + linkUrl: "https://tracking.example.com/xyz123" + } +}) + +// List landing pages +const landingPages = PhishingLanding.list() +for (const page of landingPages) { + console.log(`${page.id}: ${page.name} - ${page.type}`) +} + +// Get campaign statistics +const stats = await PhishingCampaigns.getStats(campaign.id) +console.log(`Sent: ${stats.sent}`) +console.log(`Opened: ${stats.opened} (${stats.openRate}%)`) +console.log(`Clicked: ${stats.clicked} (${stats.clickRate}%)`) +console.log(`Submitted: ${stats.submitted} (${stats.submitRate}%)`) +console.log(`Reported: ${stats.reported} (${stats.reportRate}%)`) +``` + +### Pretexting Scenarios + +```typescript +import { PretextingScenarios, PretextingPersonas, PretextingScripts } from "./pentest/soceng" + +// List available scenarios +const scenarios = PretextingScenarios.list() +for (const scenario of scenarios) { + console.log(`${scenario.id}: ${scenario.name}`) + console.log(` Category: ${scenario.category}`) + console.log(` Difficulty: ${scenario.difficulty}`) +} + +// Get scenario details +const scenario = PretextingScenarios.get("it-support") +console.log(`Scenario: ${scenario.name}`) +console.log(`Description: ${scenario.description}`) +console.log(`Pretext: ${scenario.pretext}`) +console.log(`Objectives: ${scenario.objectives.join(", ")}`) + +// List personas +const personas = PretextingPersonas.list() +for (const persona of personas) { + console.log(`${persona.id}: ${persona.name} (${persona.role})`) +} + +// Get persona details +const persona = PretextingPersonas.get("helpdesk-tech") +console.log(`Name: ${persona.name}`) +console.log(`Role: ${persona.role}`) +console.log(`Background: ${persona.background}`) +console.log(`Speech Patterns: ${persona.speechPatterns.join(", ")}`) + +// Get call script +const script = PretextingScripts.get("password-reset-call", { + targetName: "John", + companyName: "Acme Corp", + department: "IT Support" +}) +console.log(`Opening: ${script.opening}`) +console.log(`Key Points: ${script.keyPoints.join(", ")}`) +console.log(`Objection Handlers:`) +for (const [objection, response] of Object.entries(script.objectionHandlers)) { + console.log(` "${objection}" -> "${response}"`) +} +``` + +### OSINT Reconnaissance + +```typescript +import { EmailRecon, OrgRecon, SocialRecon } from "./pentest/soceng" + +// Generate email permutations +const emails = EmailRecon.generatePermutations({ + firstName: "John", + lastName: "Doe", + domain: "example.com" +}) +console.log(`Possible emails: ${emails.join(", ")}`) + +// Generate OSINT search queries +const queries = OrgRecon.generateSearchQueries("Acme Corporation") +console.log("Google Dorks:") +for (const query of queries.googleDorks) { + console.log(` ${query}`) +} +console.log("LinkedIn Queries:") +for (const query of queries.linkedin) { + console.log(` ${query}`) +} + +// Organization profiling queries +const orgQueries = OrgRecon.getProfilingQueries("example.com") +console.log(`Technology Stack: ${orgQueries.technology.join(", ")}`) +console.log(`Employee Discovery: ${orgQueries.employees.join(", ")}`) +``` + +### Security Awareness Training + +```typescript +import { AwarenessTraining, AwarenessMetrics, AwarenessReporting } from "./pentest/soceng" + +// List training modules +const modules = AwarenessTraining.listModules() +for (const module of modules) { + console.log(`${module.id}: ${module.title}`) + console.log(` Duration: ${module.duration} minutes`) + console.log(` Topics: ${module.topics.join(", ")}`) +} + +// Get training content +const content = AwarenessTraining.getContent("phishing-basics") +console.log(`Title: ${content.title}`) +console.log(`Sections: ${content.sections.length}`) + +// Calculate campaign metrics +const metrics = AwarenessMetrics.calculate(campaignStats) +console.log(`Click Rate: ${metrics.clickRate}%`) +console.log(`Report Rate: ${metrics.reportRate}%`) +console.log(`Phish-Prone Percentage: ${metrics.phishPronePercentage}%`) +console.log(`Industry Comparison: ${metrics.industryComparison}`) + +// Generate executive summary +const summary = AwarenessReporting.executiveSummary({ + campaignId: campaign.id, + includeRecommendations: true, + includeBenchmarks: true +}) +console.log(summary.markdown) +``` + +## Tool Actions + +| Category | Action | Description | +|----------|--------|-------------| +| Email | `email-security` | Assess domain email security (SPF/DKIM/DMARC) | +| Email | `spoof-assessment` | Assess spoofing vulnerability | +| Email | `lookalike-domains` | Generate lookalike domains | +| Phishing | `create-campaign` | Create a phishing campaign | +| Phishing | `list-campaigns` | List all campaigns | +| Phishing | `campaign-status` | Get campaign statistics | +| Phishing | `campaign-report` | Generate detailed report | +| Phishing | `import-targets` | Import targets from CSV | +| Templates | `list-templates` | List phishing email templates | +| Templates | `generate-template` | Generate email template | +| Templates | `list-landing-pages` | List landing page templates | +| Pretexting | `list-scenarios` | List pretexting scenarios | +| Pretexting | `scenario-details` | Get scenario details | +| Pretexting | `list-personas` | List available personas | +| Pretexting | `persona-details` | Get persona details | +| Pretexting | `get-script` | Get call script | +| Recon | `recon-queries` | Generate OSINT search queries | +| Recon | `email-permutations` | Generate email permutations | +| Awareness | `list-training` | List training modules | +| Awareness | `training-content` | Get training content | +| Awareness | `campaign-metrics` | Calculate awareness metrics | +| Awareness | `executive-summary` | Generate executive summary | +| Session | `start-session` | Start a new session | +| Session | `session-status` | Get session status | +| Session | `end-session` | End current session | + +## Campaign Types + +| Type | Description | Objective | +|------|-------------|-----------| +| `credential-harvest` | Fake login page | Capture credentials | +| `payload-delivery` | Malicious attachment | Deliver payload | +| `link-click` | Track link clicks | Measure susceptibility | +| `data-entry` | Form submission | Capture sensitive data | +| `callback` | Phone call request | Social engineering | +| `usb-drop` | Physical USB drop | Test physical security | +| `awareness-test` | Non-malicious test | Training purposes | + +## Phishing Templates + +### Email Templates + +| ID | Name | Category | +|----|------|----------| +| `password-reset` | Password Reset Required | IT Security | +| `account-verification` | Account Verification | Account Security | +| `document-shared` | Document Shared With You | Collaboration | +| `invoice-attached` | Invoice Attached | Finance | +| `hr-policy-update` | HR Policy Update | Human Resources | +| `executive-request` | Urgent Request from Executive | Business Email Compromise | +| `delivery-notification` | Package Delivery Update | Shipping | +| `voicemail-notification` | New Voicemail Message | Communications | + +### Landing Page Templates + +| ID | Name | Type | +|----|------|------| +| `microsoft-365` | Microsoft 365 Login | Credential Harvest | +| `google-workspace` | Google Workspace Login | Credential Harvest | +| `generic-login` | Generic Corporate Login | Credential Harvest | +| `webmail` | Webmail Access | Credential Harvest | +| `vpn-portal` | VPN Portal Login | Credential Harvest | +| `file-download` | File Download Page | Payload Delivery | +| `survey-form` | Survey/Feedback Form | Data Entry | + +## Pretexting Scenarios + +| ID | Name | Category | Difficulty | +|----|------|----------|------------| +| `it-support` | IT Support Call | Technical | Easy | +| `hr-benefits` | HR Benefits Update | HR | Easy | +| `vendor-invoice` | Vendor Invoice Query | Finance | Medium | +| `executive-assistant` | Executive Assistant | BEC | Medium | +| `security-audit` | Security Audit Team | Security | Hard | +| `new-employee` | New Employee Onboarding | HR | Easy | +| `building-maintenance` | Building Maintenance | Physical | Medium | +| `delivery-driver` | Delivery Driver | Physical | Easy | + +## Events + +| Event | Description | +|-------|-------------| +| `pentest.soceng.session_started` | Assessment session started | +| `pentest.soceng.session_ended` | Assessment session ended | +| `pentest.soceng.campaign_created` | Phishing campaign created | +| `pentest.soceng.campaign_launched` | Campaign started sending | +| `pentest.soceng.campaign_completed` | Campaign finished | +| `pentest.soceng.email_sent` | Phishing email sent | +| `pentest.soceng.email_opened` | Email opened (tracking pixel) | +| `pentest.soceng.link_clicked` | Phishing link clicked | +| `pentest.soceng.credential_captured` | Credentials submitted | +| `pentest.soceng.phish_reported` | User reported phishing | +| `pentest.soceng.payload_executed` | Payload was executed | + +## Data Types + +### PhishingCampaign + +```typescript +{ + id: string + name: string + type: "credential-harvest" | "payload-delivery" | "link-click" | ... + status: "draft" | "scheduled" | "running" | "paused" | "completed" + profile: string + targets: Target[] + templateId: string + landingPageId?: string + senderProfile: { + name: string + email: string + replyTo?: string + } + schedule: { + startTime: number + endTime?: number + sendRate: number + randomize: boolean + } + stats: CampaignStats + createdAt: number + launchedAt?: number + completedAt?: number +} +``` + +### Target + +```typescript +{ + id: string + email: string + firstName?: string + lastName?: string + department?: string + title?: string + manager?: string + customFields?: Record + status: "pending" | "sent" | "opened" | "clicked" | "submitted" | "reported" + events: TargetEvent[] +} +``` + +### PretextingScenario + +```typescript +{ + id: string + name: string + category: "technical" | "hr" | "finance" | "security" | "physical" + difficulty: "easy" | "medium" | "hard" + description: string + pretext: string + objectives: string[] + requiredInfo: string[] + suggestedPersona: string + keyTalkingPoints: string[] + objectionHandlers: Record + successIndicators: string[] + ethicalBoundaries: string[] +} +``` + +### AwarenessMetrics + +```typescript +{ + campaignId: string + totalTargets: number + emailsSent: number + emailsOpened: number + linksClicked: number + credentialsSubmitted: number + phishReported: number + openRate: number + clickRate: number + submitRate: number + reportRate: number + phishPronePercentage: number + industryBenchmark: { + clickRate: number + reportRate: number + } + departmentBreakdown: Record + timeToClick: { + average: number + median: number + fastest: number + } + recommendations: string[] +} +``` + +## Security Considerations + +### Ethical Guidelines + +1. **Authorization Required**: Always obtain written authorization before testing +2. **Scope Limits**: Stay within defined scope and rules of engagement +3. **Data Protection**: Handle captured credentials securely +4. **No Real Harm**: Never use captured data for malicious purposes +5. **Immediate Notification**: Report critical findings immediately +6. **Training Focus**: Emphasize awareness training over punishment + +### Data Handling + +- Captured credentials should be hashed or encrypted +- PII should be minimized and protected +- Campaign data should be retained only as long as necessary +- Results should be shared only with authorized personnel + +### Legal Compliance + +- Ensure compliance with GDPR, CCPA, and other privacy laws +- Follow anti-phishing regulations in your jurisdiction +- Document authorization and scope clearly +- Maintain audit trails for all activities + +## Example Use Cases + +### Use Case 1: Security Awareness Assessment + +```bash +# Check domain email security first +soceng email-security domain=example.com + +# Create awareness campaign +soceng create-campaign \ + campaignName="Q1 Awareness Test" \ + campaignType=awareness-test \ + templateId=password-reset \ + landingPageId=microsoft-365 + +# Import targets +soceng import-targets campaignId= file=/path/to/targets.csv + +# Monitor progress +soceng campaign-status campaignId= + +# Generate report +soceng campaign-report campaignId= + +# Get metrics +soceng campaign-metrics campaignId= + +# Executive summary +soceng executive-summary campaignId= +``` + +### Use Case 2: Red Team Engagement + +```bash +# OSINT reconnaissance +soceng recon-queries domain=target-company.com +soceng email-permutations firstName=John lastName=Doe domain=target-company.com + +# Assess spoofing potential +soceng spoof-assessment domain=target-company.com +soceng lookalike-domains domain=target-company.com + +# Prepare pretexting +soceng list-scenarios +soceng scenario-details scenarioId=it-support +soceng get-script scriptId=password-reset-call targetName=John +``` + +### Use Case 3: Employee Training Program + +```bash +# List training modules +soceng list-training + +# Get specific training content +soceng training-content moduleId=phishing-basics + +# Calculate metrics for completed campaign +soceng campaign-metrics campaignId= + +# Generate executive summary +soceng executive-summary campaignId= +``` + +## Storage + +Campaign data is persisted in: + +``` +pentest/soceng/ + sessions/ + session_abc123.json # Session data + campaigns/ + campaign_def456.json # Campaign configuration + targets/ + target_ghi789.json # Target information + events/ + event_jkl012.json # Tracking events + templates/ + custom_template_mno345.json # Custom templates + reports/ + report_pqr678.json # Generated reports +``` + +## Testing + +Run the tests: + +```bash +bun test test/pentest/soceng.test.ts +``` + +## Integration + +The tool is registered in `src/tool/registry.ts`: +- `SocEngTool` - Available as `soceng` tool + +Exports available from `src/pentest/index.ts`: +- All types: `SocEngTypes` +- Events: `SocEngEvents` +- Storage: `SocEngStorage` +- Profiles: `SocEngProfiles` +- Orchestrator: `SocEngOrchestrator` +- Tool: `SocEngTool` +- Email: `EmailGenerator`, `EmailSpoof`, `EmailHeaders`, `EmailValidation` +- Phishing: `PhishingCampaigns`, `PhishingTemplates`, `PhishingTracking`, `PhishingLanding`, `PhishingPayloads` +- Pretexting: `PretextingScenarios`, `PretextingPersonas`, `PretextingScripts`, `PretextingOSINT` +- Payloads: `USBPayloads`, `DocumentPayloads`, `MacroPayloads`, `HTAPayloads` +- Recon: `EmailRecon`, `OrgRecon`, `SocialRecon` +- Awareness: `AwarenessTraining`, `AwarenessMetrics`, `AwarenessReporting` + +## Industry Benchmarks + +Based on industry research, typical phishing metrics: + +| Metric | Average | Good | Excellent | +|--------|---------|------|-----------| +| Click Rate | 10-15% | 5-10% | <5% | +| Submit Rate | 3-5% | 1-3% | <1% | +| Report Rate | 10-20% | 20-40% | >40% | +| Time to Click | 1-4 hours | N/A | N/A | + +Source: Industry reports from KnowBe4, Proofpoint, and Verizon DBIR diff --git a/docs/PHASE16-post-exploitation.md b/docs/PHASE16-post-exploitation.md new file mode 100644 index 00000000000..4d38221522b --- /dev/null +++ b/docs/PHASE16-post-exploitation.md @@ -0,0 +1,762 @@ +# Phase 16: Post-Exploitation Framework + +## Overview + +Phase 16 introduces the **Post-Exploitation Framework** (`pentest/postexploit/`) - a guidance-based framework for privilege escalation, lateral movement, credential harvesting, persistence, data exfiltration, and cleanup during authorized penetration testing engagements. + +> **IMPORTANT**: This module provides GUIDANCE and INFORMATION for authorized penetration testing. It does not automatically execute exploits. All techniques are documented for educational purposes and authorized security assessments only. + +## Module Structure + +``` +src/pentest/postexploit/ +├── index.ts # Module exports +├── types.ts # PostExploitTypes namespace (Zod schemas) +├── events.ts # PostExploitEvents +├── storage.ts # Session persistence +├── profiles.ts # Assessment profiles +├── tool.ts # PostExploitTool for agent +├── orchestrator.ts # Workflow coordination +├── privesc/ +│ ├── index.ts +│ ├── linux.ts # Linux privesc (SUID, sudo, capabilities, kernel) +│ └── windows.ts # Windows privesc (services, registry, tokens, UAC) +├── lateral/ +│ ├── index.ts +│ ├── discovery.ts # Target discovery +│ ├── methods.ts # Movement methods (SMB, WMI, SSH, RDP) +│ └── paths.ts # Path analysis +├── creds/ +│ ├── index.ts +│ ├── discovery.ts # Credential location discovery +│ ├── linux.ts # Linux creds (shadow, SSH keys, configs) +│ └── windows.ts # Windows creds (SAM, LSASS, NTDS, DPAPI) +├── persistence/ +│ ├── index.ts +│ ├── catalog.ts # Mechanism catalog +│ ├── linux.ts # Linux persistence (cron, systemd, SSH keys) +│ └── windows.ts # Windows persistence (registry, tasks, WMI) +├── exfil/ +│ ├── index.ts +│ ├── targets.ts # Data target discovery +│ └── channels.ts # Exfil channels (DNS, HTTP, SSH, SMB) +├── cleanup/ +│ ├── index.ts +│ ├── artifacts.ts # Artifact tracking +│ ├── logs.ts # Log cleanup guidance +│ └── checklist.ts # Cleanup verification checklist +└── parsers/ + ├── index.ts + ├── linpeas.ts # LinPEAS output parser + └── winpeas.ts # WinPEAS output parser +``` + +## Capabilities + +### Privilege Escalation + +#### Linux Vectors + +| Category | Description | MITRE | +|----------|-------------|-------| +| SUID Binaries | Exploitable SUID binaries with GTFOBins references | T1548.001 | +| Sudo Misconfig | Sudo rule exploitation | T1548.003 | +| Capabilities | Linux capabilities abuse | T1068 | +| Cron Jobs | Writable cron job exploitation | T1053.003 | +| Kernel Exploits | Kernel vulnerability exploitation | T1068 | +| Service Abuse | Writable service files | T1574.010 | +| Path Hijacking | PATH environment exploitation | T1574.007 | +| Container Escape | Docker/container breakout | T1611 | + +#### Windows Vectors + +| Category | Description | MITRE | +|----------|-------------|-------| +| Service Exploits | Unquoted paths, weak permissions | T1574.010 | +| Registry Abuse | AlwaysInstallElevated, autorun | T1547.001 | +| Token Manipulation | SeImpersonate, SeDebug privileges | T1134 | +| UAC Bypass | FodHelper, EventVwr, CMSTP | T1548.002 | +| DLL Hijacking | Missing DLL exploitation | T1574.001 | +| Scheduled Tasks | Task file manipulation | T1053.005 | +| Stored Credentials | Credential Manager, DPAPI | T1555 | + +### Lateral Movement + +| Method | Ports | Description | MITRE | +|--------|-------|-------------|-------| +| SMB/PSExec | 445 | Remote command execution | T1021.002 | +| WMI | 135 | Windows Management Instrumentation | T1047 | +| WinRM | 5985/5986 | Windows Remote Management | T1021.006 | +| RDP | 3389 | Remote Desktop Protocol | T1021.001 | +| SSH | 22 | Secure Shell | T1021.004 | +| Pass-the-Hash | - | NTLM hash authentication | T1550.002 | +| Pass-the-Ticket | - | Kerberos ticket reuse | T1550.003 | +| DCOM | 135 | Distributed COM | T1021.003 | + +### Credential Harvesting + +#### Linux Locations + +| Source | Path | Access Level | Description | +|--------|------|--------------|-------------| +| Shadow | /etc/shadow | root | Password hashes | +| SSH Keys | ~/.ssh/ | user | Private keys | +| History | ~/.bash_history | user | Command history | +| Config Files | Various | user/root | Application credentials | +| Environment | /proc/*/environ | varies | Environment variables | +| Memory | /proc/*/maps | root | Process memory | + +#### Windows Locations + +| Source | Location | Access Level | Description | +|--------|----------|--------------|-------------| +| SAM | %SystemRoot%\System32\config\SAM | SYSTEM | Local account hashes | +| LSASS | Memory | SYSTEM | Live credentials | +| NTDS | %SystemRoot%\NTDS\ntds.dit | Domain Admin | Domain hashes | +| DPAPI | %AppData%\Microsoft\Protect | user | Protected secrets | +| Credential Manager | Credential Manager | user | Stored passwords | +| Browser | Various | user | Saved passwords | +| Kerberos | Memory | varies | Tickets | +| WiFi | netsh | admin | Network passwords | + +### Persistence Mechanisms + +#### Linux + +| Category | Location | Survival | Detection Risk | +|----------|----------|----------|----------------| +| Cron | /etc/crontab, /var/spool/cron | reboot | medium | +| Systemd | /etc/systemd/system | reboot | medium | +| Shell Profile | ~/.bashrc, ~/.profile | login | low | +| SSH Keys | ~/.ssh/authorized_keys | reboot | low | +| LD Preload | /etc/ld.so.preload | reboot | high | +| PAM | /etc/pam.d/ | reboot | high | +| Init Scripts | /etc/init.d/ | reboot | medium | +| Kernel Module | /lib/modules/ | reboot | high | + +#### Windows + +| Category | Location | Survival | Detection Risk | +|----------|----------|----------|----------------| +| Registry Run | HKLM/HKCU\...\Run | reboot | medium | +| Scheduled Task | Task Scheduler | reboot | medium | +| Service | services.msc | reboot | high | +| WMI Subscription | WMI Repository | reboot | low | +| Startup Folder | %AppData%\...\Startup | login | medium | +| DLL Hijack | Application directories | app restart | low | +| COM Hijack | Registry CLSID | app use | low | +| Print Monitor | Registry | reboot | high | + +### Data Exfiltration Channels + +| Channel | Stealth | Bandwidth | Description | +|---------|---------|-----------|-------------| +| DNS | high | low | DNS tunneling | +| HTTP/HTTPS | medium | high | Web-based exfil | +| ICMP | high | low | Ping tunneling | +| SSH | medium | high | Encrypted tunnel | +| SMB | low | high | File share transfer | +| Cloud | medium | high | Cloud storage APIs | +| Email | medium | medium | SMTP-based exfil | +| Steganography | high | low | Hidden in images | + +## Usage + +### Session Management + +```typescript +import { PostExploitOrchestrator, PostExploitProfiles } from "./pentest/postexploit" + +// Create a new post-exploitation session +const session = await PostExploitOrchestrator.createSession({ + target: "192.168.1.100", + platform: "linux", + currentUser: "www-data", + currentPrivilege: "user", + hostname: "webserver01", + profile: "standard" +}) + +console.log(`Session ID: ${session.id}`) +console.log(`Platform: ${session.platform}`) +console.log(`Profile: ${session.profile}`) + +// Get session status +const status = await PostExploitOrchestrator.getStatus(session.id) +console.log(`Privesc Vectors: ${status.privescVectors}`) +console.log(`Lateral Targets: ${status.lateralTargets}`) +console.log(`Credentials Found: ${status.credentialsDiscovered}`) + +// Complete session +await PostExploitOrchestrator.completeSession(session.id) +``` + +### Privilege Escalation Scan + +```typescript +import { Privesc, LinuxPrivesc, WindowsPrivesc } from "./pentest/postexploit" + +// Get discovery commands +const commands = Privesc.getDiscoveryCommands("linux") +console.log("Discovery Commands:") +for (const cmd of commands) { + console.log(` ${cmd}`) +} + +// Get SUID binary info +const suidBinaries = Privesc.getSUIDBinaryInfo() +for (const binary of suidBinaries) { + console.log(`${binary.name}:`) + console.log(` Technique: ${binary.technique}`) + console.log(` Commands: ${binary.commands.join("; ")}`) + console.log(` GTFOBins: ${binary.gtfobins}`) +} + +// Get sudo exploitation guidance +const sudoExploits = Privesc.getSudoInfo() +for (const exploit of sudoExploits) { + console.log(`${exploit.name}:`) + console.log(` Risk: ${exploit.risk}`) + console.log(` Technique: ${exploit.technique}`) +} + +// Windows service exploitation +const serviceVulns = Privesc.getServiceInfo() +for (const vuln of serviceVulns) { + console.log(`${vuln.name}: ${vuln.description}`) + console.log(` MITRE: ${vuln.mitre.join(", ")}`) +} + +// UAC bypass techniques +const uacBypasses = Privesc.getUACBypassInfo() +for (const bypass of uacBypasses) { + console.log(`${bypass.name}:`) + console.log(` Binary: ${bypass.binary}`) + console.log(` Detection Risk: ${bypass.detectionRisk}`) +} + +// Quick win checks +const quickWins = Privesc.getQuickWinChecks("linux") +for (const check of quickWins) { + console.log(` ${check}`) +} +``` + +### Lateral Movement Discovery + +```typescript +import { Lateral, LateralDiscovery, LateralMethods, LateralPaths } from "./pentest/postexploit" + +// Get discovery commands +const discoveryCommands = Lateral.getDiscoveryCommands("windows") +console.log("Network Discovery:") +for (const cmd of discoveryCommands) { + console.log(` ${cmd}`) +} + +// Get available methods +const methods = Lateral.getMethods("windows") +for (const method of methods) { + console.log(`${method.name}:`) + console.log(` Description: ${method.description}`) + console.log(` Detection Risk: ${method.detectionRisk}`) +} + +// Analyze target +const target = Lateral.analyzeTarget("192.168.1.50", [22, 445, 3389], "dc01") +console.log(`Target: ${target.host}`) +console.log(`Suggested Methods: ${target.suggestedMethods.join(", ")}`) + +// Create movement path +const path = Lateral.createPath("192.168.1.100", "192.168.1.50", "smb", { + credentials: "admin:hash", + credentialType: "hash" +}) +console.log(`Path: ${path.source} -> ${path.destination}`) + +// Quick reference +const quickRef = Lateral.getQuickReference() +console.log(quickRef) +``` + +### Credential Discovery + +```typescript +import { Creds, CredDiscovery, LinuxCreds, WindowsCreds } from "./pentest/postexploit" + +// Get credential locations +const locations = Creds.getLocations("linux") +for (const loc of locations) { + console.log(`${loc.source}:`) + console.log(` Path: ${loc.path}`) + console.log(` Access: ${loc.accessLevel}`) + console.log(` Expected Types: ${loc.expectedTypes.join(", ")}`) +} + +// Get quick commands +const quickCommands = Creds.getQuickCommands("windows") +console.log("Quick Credential Commands:") +for (const cmd of quickCommands) { + console.log(` ${cmd}`) +} + +// Get source-specific commands +const lsassCommands = Creds.getSourceCommands("windows", "lsass") +console.log("LSASS Extraction:") +for (const cmd of lsassCommands) { + console.log(` ${cmd}`) +} + +// Get recommended tools +const tools = Creds.getTools("windows") +console.log("Recommended Tools:") +for (const tool of tools) { + console.log(` - ${tool}`) +} + +// Priority order +const priority = Creds.getPriorityOrder("linux") +console.log("Priority Order:") +for (const item of priority) { + console.log(` ${item}`) +} +``` + +### Persistence Catalog + +```typescript +import { Persistence, PersistenceCatalog, LinuxPersistence, WindowsPersistence } from "./pentest/postexploit" + +// Get all mechanisms +const mechanisms = Persistence.getMechanisms("linux") +for (const mech of mechanisms) { + console.log(`${mech.name}:`) + console.log(` Category: ${mech.category}`) + console.log(` Location: ${mech.location}`) + console.log(` Privilege: ${mech.privilege}`) + console.log(` Survival: ${mech.survival}`) + console.log(` Detection Risk: ${mech.detectionRisk}`) + console.log(` MITRE: ${mech.mitre.join(", ")}`) +} + +// Get mechanism commands +const cronCommands = Persistence.getMechanismCommands("linux", "cron") +console.log("Cron Setup:") +for (const cmd of cronCommands.setup) { + console.log(` ${cmd}`) +} +console.log("Cron Cleanup:") +for (const cmd of cronCommands.cleanup) { + console.log(` ${cmd}`) +} + +// Get recommendations +const recommendations = Persistence.getRecommendations("windows", { + privilege: "admin", + stealth: true +}) +console.log("Recommended:") +for (const rec of recommendations) { + console.log(` - ${rec}`) +} +``` + +### Data Exfiltration + +```typescript +import { Exfil, DataTargets, ExfilChannels } from "./pentest/postexploit" + +// Get discovery commands +const exfilCommands = Exfil.getDiscoveryCommands("windows") +console.log("Data Discovery:") +for (const cmd of exfilCommands) { + console.log(` ${cmd}`) +} + +// Get stealthy channels +const stealthyChannels = Exfil.getStealthyChannels() +console.log(`Stealthy Channels: ${stealthyChannels.join(", ")}`) + +// Get high bandwidth channels +const highBwChannels = Exfil.getHighBandwidthChannels() +console.log(`High Bandwidth: ${highBwChannels.join(", ")}`) + +// Get channel details +const dnsDetails = Exfil.getChannelDetails("dns") +console.log(`DNS Exfil:`) +console.log(` Stealth: ${dnsDetails.stealth}`) +console.log(` Bandwidth: ${dnsDetails.bandwidth}`) +console.log(` Tools: ${dnsDetails.tools.join(", ")}`) + +// Quick reference +const exfilRef = Exfil.getQuickReference() +console.log(exfilRef) +``` + +### Cleanup and Artifact Tracking + +```typescript +import { Cleanup, ArtifactTracking, LogCleanup, CleanupChecklist } from "./pentest/postexploit" + +// Generate cleanup checklist +const checklist = Cleanup.generateChecklist("linux", session.artifacts, { + includeLogGuidance: true +}) + +for (const item of checklist) { + const status = item.verified ? "[x]" : "[ ]" + console.log(`${status} ${item.description}`) + console.log(` Command: ${item.command}`) + console.log(` Priority: ${item.priority}`) +} + +// Get log cleanup guidance +const logGuidance = Cleanup.formatLogGuidance("linux") +console.log(logGuidance) + +// Format artifacts +const artifactSummary = Cleanup.formatArtifacts(session.artifacts) +console.log(artifactSummary) + +// Get quick reference +const cleanupRef = Cleanup.getQuickReference("windows") +console.log(cleanupRef) +``` + +### LinPEAS/WinPEAS Parser + +```typescript +import { Parsers, LinPEASParser, WinPEASParser } from "./pentest/postexploit" + +// Parse LinPEAS output +const linpeasOutput = await fs.readFile("/tmp/linpeas_output.txt", "utf-8") +const linpeasResult = LinPEASParser.parse(linpeasOutput) + +console.log(`SUID Binaries: ${linpeasResult.suidBinaries.length}`) +console.log(`Sudo Entries: ${linpeasResult.sudoEntries.length}`) +console.log(`Capabilities: ${linpeasResult.capabilities.length}`) +console.log(`Interesting Files: ${linpeasResult.interestingFiles.length}`) + +// Extract privesc vectors +const vectors = LinPEASParser.extractPrivescVectors(linpeasResult) +for (const vector of vectors) { + console.log(`[${vector.risk}] ${vector.name}`) + console.log(` Category: ${vector.category}`) + console.log(` Technique: ${vector.technique}`) +} + +// Parse WinPEAS output +const winpeasOutput = await fs.readFile("/tmp/winpeas_output.txt", "utf-8") +const winpeasResult = WinPEASParser.parse(winpeasOutput) + +console.log(`Services: ${winpeasResult.services.length}`) +console.log(`Scheduled Tasks: ${winpeasResult.scheduledTasks.length}`) +console.log(`Token Privileges: ${winpeasResult.tokenPrivileges.length}`) +console.log(`Registry Issues: ${winpeasResult.registryIssues.length}`) + +// Auto-detect and parse +const autoResult = Parsers.parse("auto", output) +const formatted = Parsers.formatResults("auto", autoResult) +console.log(formatted) +``` + +## Tool Actions + +| Action | Description | +|--------|-------------| +| `session` | Create or manage a post-exploitation session | +| `privesc` | Scan for privilege escalation vectors | +| `lateral` | Discover lateral movement targets and paths | +| `creds` | Discover credential storage locations | +| `persist` | Catalog persistence mechanisms | +| `exfil` | Discover data targets and exfiltration channels | +| `cleanup` | Generate cleanup guidance and checklist | +| `parse` | Parse LinPEAS/WinPEAS output | +| `status` | Get session status and summary | +| `profiles` | List available assessment profiles | +| `assess` | Run full assessment based on profile | +| `list` | List sessions | + +## Assessment Profiles + +| Profile | Privesc | Lateral | Creds | Persist | Exfil | Cleanup | Stealth | +|---------|---------|---------|-------|---------|-------|---------|---------| +| `discovery` | basic | enum | passive | catalog | discover | track | yes | +| `quick` | critical | basic | passive | no | no | track | no | +| `standard` | full | full | guided | catalog | full | full | no | +| `thorough` | deep | deep | deep | catalog | full | full | no | +| `stealth` | passive | passive | passive | no | passive | full | yes | + +## Events + +| Event | Description | +|-------|-------------| +| `pentest.postexploit.session_started` | Session created | +| `pentest.postexploit.session_completed` | Session finished | +| `pentest.postexploit.privesc_vector_found` | Privesc vector discovered | +| `pentest.postexploit.lateral_target_discovered` | Lateral movement target found | +| `pentest.postexploit.credential_discovered` | Credential location found | +| `pentest.postexploit.persistence_opportunity` | Persistence option identified | +| `pentest.postexploit.data_target_found` | Sensitive data target discovered | +| `pentest.postexploit.artifact_created` | Artifact tracked | +| `pentest.postexploit.cleanup_guidance_generated` | Cleanup checklist created | + +## Data Types + +### PostExploitSession + +```typescript +{ + id: string + target: string + platform: "linux" | "windows" + currentUser: string + currentPrivilege: "user" | "admin" | "root" | "system" + hostname?: string + domain?: string + profile: ProfileId + status: "running" | "completed" | "failed" + privescVectors: PrivescVector[] + lateralTargets: LateralTarget[] + lateralPaths: LateralPath[] + credentialLocations: CredentialLocation[] + persistenceMechanisms: PersistenceMechanism[] + dataTargets: DataTarget[] + exfilChannels: ExfilChannel[] + artifacts: Artifact[] + startedAt: number + endedAt?: number +} +``` + +### PrivescVector + +```typescript +{ + id: string + category: "suid" | "sudo" | "kernel" | "cron" | "service" | "registry" | "token" | "uac_bypass" | ... + platform: "linux" | "windows" + name: string + description: string + risk: "critical" | "high" | "medium" | "low" + exploitability: "trivial" | "easy" | "moderate" | "difficult" + target: string + technique: string + commands: string[] + prerequisites: string[] + detectionRisk: "low" | "medium" | "high" + gtfobins?: string + lolbas?: string + mitre: string[] + discoveredAt: number +} +``` + +### LateralPath + +```typescript +{ + id: string + source: string + destination: string + method: "smb" | "wmi" | "ssh" | "rdp" | "winrm" | "pass_the_hash" | "pass_the_ticket" | ... + credentials?: string + credentialType?: "password" | "hash" | "ticket" | "key" + risk: "critical" | "high" | "medium" | "low" + detectionRisk: "low" | "medium" | "high" + commands: string[] + tested: boolean + successful: boolean + notes?: string + mitre: string[] + discoveredAt: number +} +``` + +### PersistenceMechanism + +```typescript +{ + id: string + category: PersistenceCategory + platform: "linux" | "windows" + name: string + description: string + location: string + privilege: "user" | "admin" | "system" + survival: "reboot" | "logout" | "service_restart" + detectionRisk: "low" | "medium" | "high" + commands: string[] + cleanup: string[] + indicators: string[] + mitre: string[] + catalogedAt: number +} +``` + +### Artifact + +```typescript +{ + id: string + sessionId: string + type: "file" | "process" | "registry" | "service" | "scheduled_task" | "user" | "log_entry" + path: string + description: string + host: string + createdBy: string + createdAt: number + cleaned: boolean + cleanedAt?: number + cleanupCommand?: string + verifyCommand?: string +} +``` + +## External Tools Integration + +### Recommended Tools + +| Tool | Platform | Purpose | +|------|----------|---------| +| LinPEAS | Linux | Privilege escalation enumeration | +| WinPEAS | Windows | Privilege escalation enumeration | +| pspy | Linux | Process monitoring without root | +| Mimikatz | Windows | Credential extraction | +| Rubeus | Windows | Kerberos operations | +| Impacket | Both | Network protocols toolkit | +| BloodHound | Windows | AD path analysis | +| PowerUp | Windows | PowerShell privesc checks | +| BeRoot | Both | Privesc scanner | + +### GTFOBins & LOLBAS + +- **GTFOBins**: https://gtfobins.github.io/ - Unix binaries exploitation +- **LOLBAS**: https://lolbas-project.github.io/ - Windows living-off-the-land binaries + +## Example Use Cases + +### Use Case 1: Linux Post-Exploitation + +```bash +# Create session +postexploit session target=192.168.1.100 platform=linux user=www-data + +# Scan for privilege escalation +postexploit privesc sessionId= + +# Parse LinPEAS output +postexploit parse tool=linpeas file=/tmp/linpeas.txt sessionId= + +# Discover credentials +postexploit creds sessionId= + +# Generate cleanup checklist +postexploit cleanup sessionId= +``` + +### Use Case 2: Windows Post-Exploitation + +```bash +# Create session +postexploit session target=192.168.1.50 platform=windows user=DOMAIN\\user privilege=user + +# Full assessment +postexploit assess sessionId= + +# Parse WinPEAS output +postexploit parse tool=winpeas file=C:\\temp\\winpeas.txt sessionId= + +# Discover lateral movement targets +postexploit lateral sessionId= + +# Get session status +postexploit status sessionId= +``` + +### Use Case 3: Stealth Assessment + +```bash +# Create stealth session +postexploit session target=10.0.0.100 platform=linux user=app profile=stealth + +# Run stealth assessment (passive only) +postexploit assess sessionId= + +# Track artifacts +postexploit status sessionId= + +# Comprehensive cleanup +postexploit cleanup sessionId= +``` + +## Storage + +Session data is persisted in: + +``` +pentest/postexploit/ + sessions/ + session_abc123.json # Session data + vectors/ + privesc_def456.json # Privesc vectors + paths/ + lateral_ghi789.json # Lateral paths + credentials/ + cred_jkl012.json # Credential locations + mechanisms/ + persist_mno345.json # Persistence mechanisms + artifacts/ + artifact_pqr678.json # Tracked artifacts +``` + +## Testing + +Run the tests: + +```bash +bun test test/pentest/postexploit.test.ts +``` + +## Integration + +The tool is registered in `src/tool/registry.ts`: +- `PostExploitTool` - Available as `postexploit` tool + +Exports available from `src/pentest/index.ts`: +- All types: `PostExploitTypes` +- Events: `PostExploitEvents` +- Storage: `PostExploitStorage` +- Profiles: `PostExploitProfiles` +- Orchestrator: `PostExploitOrchestrator` +- Tool: `PostExploitTool` +- Privesc: `Privesc`, `LinuxPrivesc`, `WindowsPrivesc` +- Lateral: `Lateral`, `LateralDiscovery`, `LateralMethods`, `LateralPaths` +- Creds: `Creds`, `CredDiscovery`, `LinuxCreds`, `WindowsCreds` +- Persistence: `Persistence`, `PersistenceCatalog`, `LinuxPersistence`, `WindowsPersistence` +- Exfil: `Exfil`, `DataTargets`, `ExfilChannels` +- Cleanup: `Cleanup`, `ArtifactTracking`, `LogCleanup`, `CleanupChecklist` +- Parsers: `Parsers`, `LinPEASParser`, `WinPEASParser` + +## MITRE ATT&CK Mapping + +All techniques are mapped to MITRE ATT&CK framework: + +| Tactic | Techniques | +|--------|------------| +| Privilege Escalation | T1548, T1068, T1134, T1574 | +| Lateral Movement | T1021, T1047, T1550 | +| Credential Access | T1003, T1552, T1555 | +| Persistence | T1053, T1547, T1543, T1546 | +| Collection | T1005, T1039, T1074 | +| Exfiltration | T1048, T1041, T1567 | +| Defense Evasion | T1070, T1112, T1564 | + +## Safety Design + +1. **Guidance-First**: Provides commands to understand, not automated execution +2. **Explicit Confirmation**: Artifact creation requires user confirmation +3. **Artifact Tracking**: All created artifacts tracked for cleanup +4. **Risk Assessment**: Each technique includes detection risk rating +5. **MITRE Mapping**: All techniques mapped to ATT&CK for reporting +6. **Cleanup Verification**: Comprehensive cleanup checklists diff --git a/docs/PHASE17-reporting-dashboard.md b/docs/PHASE17-reporting-dashboard.md new file mode 100644 index 00000000000..04009063b8a --- /dev/null +++ b/docs/PHASE17-reporting-dashboard.md @@ -0,0 +1,346 @@ +# Phase 17: Reporting Dashboard + +## Overview + +Phase 17 implements a full web-based reporting dashboard for the opencode pentest framework with real-time scan monitoring, finding trend visualization, executive summary generation, remediation tracking, and compliance mapping (PCI-DSS, HIPAA, SOC2). + +## Technology Stack + +- **Frontend**: SolidJS + Vite + Tailwind CSS +- **Backend**: Hono routes integrated with existing server +- **Real-time**: Server-Sent Events (SSE) for live updates +- **Charts**: Custom SVG-based charts (Pie, Line, Bar, Radar) +- **Routing**: @solidjs/router v0.15+ (file-based lazy loading) + +### Dependencies + +```json +{ + "solid-js": "^1.9.0", + "@solidjs/router": "^0.15.0", + "vite": "^6.0.0", + "vite-plugin-solid": "^2.11.0", + "tailwindcss": "^3.4.0", + "autoprefixer": "^10.4.0", + "postcss": "^8.5.0" +} +``` + +## Features + +### Dashboard Overview +- Total findings count with severity breakdown +- Critical/High open issues alert +- Scan activity (24h) +- Remediation metrics (7d mitigated, avg time to fix) +- Severity distribution pie chart +- Status distribution bar +- Finding trends line chart (30 days) +- Quick action cards + +### Findings Management +- List all findings with filters (severity, status, target) +- Finding detail panel with full information +- Status updates (confirm, mitigate, false positive) +- Real-time updates via SSE +- Delete functionality + +### Scans View +- List all scans with type, target, hosts, status, duration +- Active scan tracking with live indicator +- Scan detail panel with host/port information +- Real-time updates for running scans + +### Monitors View +- List all monitors with status, schedule, run count +- Trigger immediate runs +- Run history with findings count +- Running monitor indicators +- Monitor detail panel with configuration + +### Compliance Assessment +- Framework selection (PCI-DSS v4.0, HIPAA, SOC2) +- Auto-mapping findings to compliance controls +- Compliance scoring with percentage +- Category-level breakdown +- Radar chart visualization +- Control-level assessment details +- Gap identification + +### Report Generation +- Executive summary reports + - Risk score calculation + - Critical findings highlights + - Top targets analysis + - Recommendations generation +- Technical reports + - Findings grouped by target + - Full evidence and remediation +- Compliance reports + - Framework assessment results + - Compliance gaps + - Control-level details +- JSON export + +## File Structure + +``` +packages/opencode/src/dashboard/ +├── vite.config.ts +├── index.html +├── package.json +├── tsconfig.json +├── tailwind.config.js +├── postcss.config.js +├── src/ +│ ├── index.tsx +│ ├── App.tsx +│ ├── api/ +│ │ ├── client.ts # API client (fetch wrapper) +│ │ └── sse.ts # SSE event listener +│ ├── stores/ +│ │ ├── findings.ts # Findings state store +│ │ ├── scans.ts # Scans state store +│ │ ├── monitors.ts # Monitors state store +│ │ └── compliance.ts # Compliance state store +│ ├── components/ +│ │ ├── layout/ +│ │ │ ├── Sidebar.tsx +│ │ │ ├── Header.tsx +│ │ │ └── Layout.tsx +│ │ ├── charts/ +│ │ │ ├── SeverityPie.tsx +│ │ │ ├── TrendLine.tsx +│ │ │ ├── StatusBar.tsx +│ │ │ └── ComplianceRadar.tsx +│ │ └── shared/ +│ │ ├── SeverityBadge.tsx +│ │ ├── StatusBadge.tsx +│ │ └── DataTable.tsx +│ ├── pages/ +│ │ ├── Dashboard.tsx +│ │ ├── Findings.tsx +│ │ ├── Scans.tsx +│ │ ├── Monitors.tsx +│ │ ├── Compliance.tsx +│ │ └── Reports.tsx +│ └── styles/ +│ └── dashboard.css + +packages/opencode/src/server/ +├── server.ts # Modified - mounts dashboard routes +└── dashboard.ts # Dashboard API routes + +packages/opencode/src/pentest/compliance/ +├── types.ts # Compliance type definitions +├── frameworks/ +│ ├── index.ts # Framework registry +│ ├── pci-dss.ts # PCI-DSS v4.0 controls (~64) +│ ├── hipaa.ts # HIPAA controls (~42) +│ └── soc2.ts # SOC2 controls (~33) +├── mapper.ts # Finding-to-control mapper +├── scorer.ts # Compliance score calculator +└── index.ts # Module exports +``` + +## API Endpoints + +### Findings +``` +GET /pentest/findings # List with filters +GET /pentest/findings/:id # Get single finding +PATCH /pentest/findings/:id # Update status/notes +DELETE /pentest/findings/:id # Delete finding +``` + +### Scans +``` +GET /pentest/scans # List scans +GET /pentest/scans/:id # Get scan details +``` + +### Statistics +``` +GET /pentest/stats/overview # Dashboard overview stats +GET /pentest/stats/severity # Severity distribution +GET /pentest/stats/trends # Finding trends over time +``` + +### Monitors +``` +GET /pentest/monitors # List monitors +GET /pentest/monitors/:id # Get monitor details +POST /pentest/monitors/:id/run # Trigger immediate run +GET /pentest/monitors/:id/runs # Run history +``` + +### Reports +``` +POST /pentest/reports # Generate report +GET /pentest/reports/:id # Get report content +``` + +### Compliance +``` +GET /pentest/compliance/frameworks # List frameworks +GET /pentest/compliance/:framework # Get framework controls +GET /pentest/compliance/:framework/map # Finding-to-control mapping +POST /pentest/compliance/:framework/assess # Run assessment +``` + +## Real-time Integration + +Uses existing SSE at `/global/event` for live updates: + +```typescript +// Events subscribed: +"pentest.finding_created" -> Add to findings list +"pentest.finding_updated" -> Update finding in UI +"pentest.scan_started" -> Show active scan +"pentest.scan_completed" -> Refresh scan list +"pentest.monitor.run_started" -> Show running indicator +"pentest.monitor.run_completed" -> Update monitor history +"pentest.monitor.run_failed" -> Clear running indicator +``` + +## Compliance Frameworks + +### PCI-DSS v4.0 +- 12 requirement categories +- ~64 security controls +- Coverage: Network security, secure configurations, data protection, encryption, access control, logging, testing, policies + +### HIPAA Security Rule +- 5 safeguard categories (Administrative, Physical, Technical, Organizational, Policies) +- ~42 controls +- Coverage: Access control, audit controls, transmission security, integrity, authentication + +### SOC 2 +- 5 Trust Service Criteria (Security, Availability, Processing Integrity, Confidentiality, Privacy) +- ~33 controls +- Coverage: Risk assessment, monitoring, access control, incident response, change management + +## Auto-Mapping Logic + +Findings are mapped to controls via: +1. **Keyword matching** - Title, description against control keywords +2. **Service matching** - Finding service against control service list +3. **Severity alignment** - Finding severity matches control severity list +4. **CWE correlation** - CWE IDs in finding text matched to control CWEs + +Confidence levels: +- **High**: Score >= 25 (multiple strong matches) +- **Medium**: Score 15-24 (moderate matches) +- **Low**: Score < 15 (weak matches) + +## Development + +### Start Development Server +```bash +cd packages/opencode/src/dashboard +bun install +bun run dev +``` + +Development server runs at: `http://localhost:5173/dashboard/` + +### Build for Production +```bash +cd packages/opencode/src/dashboard +bun run build +``` + +Build output (~140 kB total): +- `dist/index.html` - Entry point +- `dist/assets/index-*.css` - Tailwind styles (~22 kB) +- `dist/assets/index-*.js` - Main bundle (~48 kB) +- `dist/assets/*.js` - Lazy-loaded page chunks + +### Access Dashboard (Production) +``` +http://localhost:4096/dashboard +``` + +Requires the main opencode server to be running to serve the API endpoints. + +## Types + +### Overview Stats Response +```typescript +interface OverviewStats { + findings: { + total: number + bySeverity: Record + byStatus: Record + openCriticalHigh: number + } + scans: { + total: number + last24h: number + activeMonitors: number + } + remediation: { + mitigatedLast7d: number + avgTimeToMitigate: number + } +} +``` + +### Compliance Assessment +```typescript +interface ComplianceAssessment { + framework: "pci-dss" | "hipaa" | "soc2" + timestamp: number + controls: Array<{ + control: ComplianceControl + status: "pass" | "fail" | "partial" | "not_assessed" + findings: string[] + notes?: string + }> + score: { + total: number + passed: number + failed: number + partial: number + notAssessed: number + percentage: number + } +} +``` + +## Integration Points + +1. **Server Integration**: Dashboard routes mounted in `server.ts` +2. **Pentest Module**: Compliance module exported from `pentest/index.ts` +3. **Storage**: Uses existing file-based storage at `["pentest", ...]` paths +4. **Events**: Integrates with existing Bus/SSE event system +5. **Monitoring**: Accesses monitor storage for scheduler integration + +## Summary + +| Component | Files | Description | +|-----------|-------|-------------| +| Frontend | 24 | SolidJS pages, components, stores, API client | +| Backend | 1 | Hono dashboard routes (~500 lines) | +| Compliance | 8 | Types, frameworks, mapper, scorer | +| **Total** | **33** | **~2,950 lines of code** | + +### Compliance Controls + +| Framework | Controls | Categories | +|-----------|----------|------------| +| PCI-DSS v4.0 | 64 | 12 requirements | +| HIPAA | 42 | 5 safeguards | +| SOC 2 | 33 | 5 Trust Service Criteria | +| **Total** | **139** | - | + +## Future Enhancements + +- PDF report export +- Custom compliance framework definitions +- Historical compliance trend tracking +- Email/Slack notifications +- Dark/light theme toggle +- Dashboard widget customization +- Finding comments/collaboration +- Bulk finding operations diff --git a/docs/PHASE18-cicd-security.md b/docs/PHASE18-cicd-security.md new file mode 100644 index 00000000000..ff55798ac05 --- /dev/null +++ b/docs/PHASE18-cicd-security.md @@ -0,0 +1,468 @@ +# Phase 18: CI/CD Security Integration + +## Overview + +Phase 18 implements a comprehensive CI/CD pipeline security scanner module for the pentest framework. It provides security analysis for GitHub Actions, GitLab CI, and Jenkins pipelines with support for secret detection, permission analysis, injection vulnerability detection, supply chain security checks, and SAST tool integration. + +## Features + +### Pipeline Providers + +- **GitHub Actions**: Full workflow YAML parsing with jobs, steps, permissions, triggers +- **GitLab CI/CD**: Pipeline parsing including stages, includes, variables, rules +- **Jenkins**: Declarative and scripted Jenkinsfile parsing with shared library detection + +### Security Checks + +| Check Category | Description | Severity Range | +|---------------|-------------|----------------| +| **Secrets** | Hardcoded API keys, tokens, passwords, private keys | Critical-Medium | +| **Permissions** | Overly permissive GITHUB_TOKEN, write-all access | Critical-Low | +| **Injection** | Command injection via PR titles/bodies, commit messages | Critical-High | +| **Supply Chain** | Unpinned actions, untrusted third-party dependencies | High-Medium | +| **Misconfiguration** | Self-hosted runner risks, missing security scans | High-Medium | + +### SAST Integration + +- **Semgrep**: Configurable rulesets for CI/CD security patterns +- **Gitleaks**: Secret detection with entropy analysis and git history scanning + +### Security Gates + +Configurable pass/fail criteria with: +- Severity thresholds (max critical, high, medium, low) +- Category-specific rules (fail on secrets, warn on supply chain) +- Custom rule definitions + +## Module Structure + +``` +packages/opencode/src/pentest/cicd/ +├── index.ts # Module exports +├── types.ts # Zod schemas (~450 lines) +├── events.ts # Bus events (~100 lines) +├── storage.ts # Persistence layer (~200 lines) +├── profiles.ts # Scan profiles (~180 lines) +├── orchestrator.ts # Main scan coordination (~350 lines) +├── tool.ts # Agent tool definition (~280 lines) +├── gates.ts # Security gate enforcement (~250 lines) +│ +├── providers/ +│ ├── index.ts # Provider exports +│ ├── base.ts # Base provider interface (~180 lines) +│ ├── github.ts # GitHub Actions analyzer (~350 lines) +│ ├── gitlab.ts # GitLab CI/CD analyzer (~300 lines) +│ └── jenkins.ts # Jenkins pipeline analyzer (~575 lines) +│ +├── checks/ +│ ├── index.ts # Check exports (~120 lines) +│ ├── secrets.ts # Secret detection (~270 lines) +│ ├── permissions.ts # Permission analysis (~280 lines) +│ ├── injection.ts # Command injection risks (~320 lines) +│ └── supply-chain.ts # Supply chain checks (~270 lines) +│ +└── sast/ + ├── index.ts # SAST orchestration (~280 lines) + ├── semgrep.ts # Semgrep integration (~410 lines) + └── gitleaks.ts # Gitleaks integration (~400 lines) + +Total: ~21 files, ~5,300+ lines +``` + +## Tool Usage + +### Actions + +```bash +# Discover CI/CD pipelines +cicd discover target="/path/to/repo" + +# Full security scan +cicd scan target="/path/to/repo" profile="standard" + +# Secret detection only +cicd check-secrets target="/path/to/repo" + +# Permission analysis only +cicd check-permissions target="/path/to/repo" + +# SAST tools +cicd sast target="/path/to/repo" tools=["semgrep","gitleaks"] + +# Security gate evaluation +cicd gate scanId="cicd_xxx" + +# List profiles +cicd profiles +``` + +### Scan Profiles + +| Profile | Checks | SAST | Gate | Use Case | +|---------|--------|------|------|----------| +| discovery | - | - | - | Enumerate pipelines only | +| quick | secrets, permissions | - | - | Fast assessment | +| standard | all checks | - | yes | Balanced scan | +| thorough | all checks | yes | yes | Full audit | +| compliance | all checks | - | yes | Regulatory checks | + +## Key Types + +### CICDScanResult + +```typescript +interface CICDScanResult { + id: string + target: string + profile: ProfileId + status: Status + pipelines: PipelineConfig[] + findings: CICDFinding[] + gateResult?: GateResult + sastResults: SASTResult[] + stats: ScanStats +} +``` + +### CICDFinding + +```typescript +interface CICDFinding { + id: string + category: FindingCategory // secrets | permissions | injection | supply-chain | ... + severity: Severity // critical | high | medium | low | info + title: string + description: string + file: string + line?: number + pipeline?: string + job?: string + remediation?: string + cwe?: string +} +``` + +### GateConfig + +```typescript +interface GateConfig { + enabled: boolean + blockOnCritical: boolean // Any critical = fail + blockOnHigh: boolean // Any high = fail + maxCritical: number // Threshold + maxHigh: number + maxMedium: number + rules: GateRule[] +} +``` + +## Security Check Details + +### Secret Detection Patterns + +| Pattern | Example | Severity | +|---------|---------|----------| +| GitHub Token | `ghp_xxxx...` | Critical | +| AWS Access Key | `AKIA...` | Critical | +| Private Key | `-----BEGIN PRIVATE KEY-----` | Critical | +| Generic API Key | `api_key: xxx` | Medium | +| High Entropy | Long random strings | Medium | + +### Dangerous GitHub Contexts (Injection) + +``` +github.event.pull_request.title +github.event.pull_request.body +github.event.issue.title +github.event.issue.body +github.event.comment.body +github.head_ref +github.event.head_commit.message +``` + +### Supply Chain Checks + +- Unpinned actions (using tags instead of SHA) +- Untrusted third-party actions +- `curl | bash` patterns +- Unpinned Docker images + +## Events + +| Event | Description | +|-------|-------------| +| `pentest.cicd.discovery_started` | Pipeline discovery begins | +| `pentest.cicd.pipeline_discovered` | Pipeline config found | +| `pentest.cicd.scan_started` | Security scan begins | +| `pentest.cicd.secret_detected` | Hardcoded secret found | +| `pentest.cicd.injection_risk` | Injection vulnerability found | +| `pentest.cicd.sast_completed` | SAST tools finished | +| `pentest.cicd.gate_evaluated` | Security gate result | +| `pentest.cicd.scan_completed` | Scan finished | + +## Default Security Gate Rules + +```typescript +{ + blockOnCritical: true, + blockOnHigh: false, + maxCritical: 0, + maxHigh: 5, + maxMedium: 20, + rules: [ + { id: "no-secrets", category: "secrets", action: "fail" }, + { id: "no-injection", category: "injection", action: "fail" }, + { id: "pin-actions", category: "supply-chain", action: "warn" }, + ] +} +``` + +## Integration with External Tools + +### Semgrep + +Requires installation: `pip install semgrep` + +Rulesets used: +- `p/github-actions` +- `p/gitlab` +- `p/supply-chain` +- `p/secrets` + +### Gitleaks + +Requires installation: `brew install gitleaks` or download from GitHub + +Features: +- Current state scanning (default) +- Git history scanning (optional) +- Custom configuration support + +## Code Examples + +### Basic Pipeline Discovery + +```typescript +import { CICDOrchestrator } from "./pentest/cicd" + +// Discover all CI/CD pipelines in a repository +const discovery = await CICDOrchestrator.discover("/path/to/repo") + +console.log(`Found ${discovery.pipelines.length} pipelines:`) +for (const pipeline of discovery.pipelines) { + console.log(` - ${pipeline.provider}: ${pipeline.path}`) +} +``` + +### Full Security Scan + +```typescript +import { CICDOrchestrator } from "./pentest/cicd" + +// Run a comprehensive security scan +const result = await CICDOrchestrator.scan({ + target: "/path/to/repo", + profile: "standard", +}) + +console.log(`Scan completed: ${result.status}`) +console.log(`Findings: ${result.findings.length}`) +console.log(` Critical: ${result.stats.bySeverity.critical}`) +console.log(` High: ${result.stats.bySeverity.high}`) + +// Check gate result +if (result.gateResult) { + console.log(`Gate: ${result.gateResult.status}`) + if (!result.gateResult.passed) { + console.log(`Blocked by: ${result.gateResult.failedRules.join(", ")}`) + } +} +``` + +### Secret Detection Only + +```typescript +import { SecretsCheck } from "./pentest/cicd/checks/secrets" +import { promises as fs } from "fs" + +const content = await fs.readFile(".github/workflows/ci.yml", "utf-8") +const result = SecretsCheck.detect(content, ".github/workflows/ci.yml") + +for (const finding of result.findings) { + console.log(`[${finding.severity}] ${finding.patternName}`) + console.log(` File: ${finding.file}:${finding.line}`) + console.log(` Value: ${finding.redacted}`) +} +``` + +### Check for Injection Vulnerabilities + +```typescript +import { InjectionCheck } from "./pentest/cicd/checks/injection" +import { GitHubProvider } from "./pentest/cicd/providers/github" + +const content = ` +name: PR Check +on: pull_request + +jobs: + check: + runs-on: ubuntu-latest + steps: + - run: echo "PR Title: \${{ github.event.pull_request.title }}" +` + +const parseResult = GitHubProvider.parse(content, ".github/workflows/pr.yml") +if (parseResult.success && parseResult.pipeline) { + const injection = InjectionCheck.detect(parseResult.pipeline) + + for (const finding of injection.findings) { + console.log(`[${finding.severity}] ${finding.title}`) + console.log(` ${finding.description}`) + console.log(` Remediation: ${finding.remediation}`) + } +} +``` + +### Supply Chain Analysis + +```typescript +import { SupplyChainCheck } from "./pentest/cicd/checks/supply-chain" + +const result = SupplyChainCheck.check(pipeline, { + requirePinning: true, + trustedPrefixes: ["actions/", "github/", "my-org/"], +}) + +console.log(`Actions analyzed: ${result.actionsAnalyzed}`) +console.log(`Unpinned: ${result.unpinnedActions}`) +console.log(`Untrusted: ${result.untrustedActions}`) + +for (const finding of result.findings) { + if (finding.severity === "high") { + console.log(`⚠️ ${finding.title}`) + console.log(` ${finding.remediation}`) + } +} +``` + +### SAST Integration + +```typescript +import { SASTOrchestrator } from "./pentest/cicd/sast" + +// Check tool availability +const available = await SASTOrchestrator.checkAvailability() +console.log("Available tools:", Object.entries(available) + .filter(([_, v]) => v).map(([k]) => k)) + +// Run SAST scan +const result = await SASTOrchestrator.run({ + tools: ["semgrep", "gitleaks"], + target: "/path/to/repo", + gitleaks: { + history: true, + depth: 50, + }, +}) + +console.log(`SAST completed in ${result.stats.duration}ms`) +console.log(`Total findings: ${result.stats.totalFindings}`) +``` + +### Custom Security Gate + +```typescript +import { SecurityGates } from "./pentest/cicd/gates" + +const gateConfig = { + enabled: true, + blockOnCritical: true, + blockOnHigh: true, + maxCritical: 0, + maxHigh: 0, + maxMedium: 10, + rules: [ + { id: "no-secrets", category: "secrets", action: "fail" }, + { id: "no-injection", category: "injection", action: "fail" }, + { id: "pin-actions", category: "supply-chain", action: "fail" }, + { id: "check-permissions", category: "permissions", action: "warn" }, + ], +} + +const gateResult = SecurityGates.evaluate(scanResult.findings, gateConfig) + +if (gateResult.passed) { + console.log("✅ Security gate PASSED") +} else { + console.log("❌ Security gate FAILED") + console.log(` Failed rules: ${gateResult.failedRules.length}`) + console.log(` Warnings: ${gateResult.warnedRules.length}`) +} +``` + +### Event Subscription + +```typescript +import { Bus } from "./bus" +import { CICDEvents } from "./pentest/cicd/events" + +// Subscribe to findings in real-time +Bus.subscribe(CICDEvents.SecretDetected, (event) => { + console.log(`🔐 Secret found: ${event.patternName}`) + console.log(` File: ${event.file}:${event.line}`) +}) + +Bus.subscribe(CICDEvents.InjectionRisk, (event) => { + console.log(`💉 Injection risk: ${event.type}`) + console.log(` Source: ${event.source}`) +}) + +Bus.subscribe(CICDEvents.GateEvaluated, (event) => { + const icon = event.passed ? "✅" : "❌" + console.log(`${icon} Gate ${event.status}: ${event.message}`) +}) +``` + +### Parsing Different Providers + +```typescript +import { GitHubProvider, GitLabProvider, JenkinsProvider } from "./pentest/cicd/providers" + +// GitHub Actions +const ghResult = GitHubProvider.parse(workflowYaml, ".github/workflows/ci.yml") + +// GitLab CI +const glResult = GitLabProvider.parse(gitlabCiYaml, ".gitlab-ci.yml") + +// Jenkins +const jkResult = JenkinsProvider.parse(jenkinsfile, "Jenkinsfile") + +// All providers implement the same interface +for (const result of [ghResult, glResult, jkResult]) { + if (result.success && result.pipeline) { + console.log(`Provider: ${result.pipeline.provider}`) + console.log(`Jobs: ${result.pipeline.jobs.length}`) + console.log(`Secrets referenced: ${result.pipeline.secrets.length}`) + } +} +``` + +## Future Enhancements + +- Azure DevOps pipeline support +- CircleCI pipeline support +- Tekton pipeline support +- ArgoCD security analysis +- GitHub Advanced Security integration +- Custom Semgrep rule authoring +- SARIF export format +- Integration with security dashboards + +## References + +- [GitHub Actions Security Hardening](https://docs.github.com/en/actions/security-guides/security-hardening-for-github-actions) +- [GitLab CI/CD Security](https://docs.gitlab.com/ee/ci/pipelines/pipeline_security.html) +- [Jenkins Security](https://www.jenkins.io/doc/book/security/) +- [GitHub Security Lab - Script Injection](https://securitylab.github.com/research/github-actions-untrusted-input/) +- [OWASP CI/CD Security](https://owasp.org/www-project-devsecops-guideline/) diff --git a/docs/PROJECT.md b/docs/PROJECT.md new file mode 100644 index 00000000000..b8a4dd13043 --- /dev/null +++ b/docs/PROJECT.md @@ -0,0 +1,584 @@ +# Cyxwiz - AI Operations Platform + +> A multi-domain AI operations platform for professionals who use command-line tools. Speak intent, tools execute with governance, AI explains results - all auditable. + +--- + +## Vision + +Cyxwiz is not a tool. **Cyxwiz is a platform.** + +Starting with security (pentest), expanding to SOC, DevOps, Network Engineering, and beyond. One platform, many domains, governed AI orchestration for all. + +--- + +## Strategic Foundation + +### Fork, Don't Build From Scratch + +Cyxwiz is built by forking [OpenCode](https://github.com/anomalyco/opencode) (MIT licensed). + +**What OpenCode gives us:** +- CLI/TUI framework (Bubble Tea) +- Multi-LLM support (Claude, GPT, Gemini, etc.) +- Session management +- Tool execution framework +- Plugin system +- SDK for integrations +- 70k+ stars of validation + +**What we add:** +- Governance engine (core, not plugin) +- Scope enforcement (core) +- Audit logging (core) +- Domain-specific agents +- Domain-specific tools with parsers +- Findings/state management +- Report generation +- Our own plugin ecosystem + +### Why Fork vs Plugin + +| As Plugin | As Fork (Platform) | +|-----------|-------------------| +| Limited by OpenCode's roadmap | Full control | +| Can't modify core UX | Customize everything | +| "Cyxwiz for OpenCode" | "Cyxwiz" | +| Tenant | Owner | +| Single product ceiling | Platform potential | + +--- + +## Platform Architecture + +``` +┌─────────────────────────────────────────────────────────────────┐ +│ CYXWIZ PLATFORM │ +│ (Forked from OpenCode, MIT) │ +├─────────────────────────────────────────────────────────────────┤ +│ │ +│ CORE FRAMEWORK (inherited from OpenCode): │ +│ ┌────────────────────────────────────────────────────────────┐ │ +│ │ CLI/TUI │ Multi-LLM │ Sessions │ Tool Exec │ Plugin System │ │ +│ └────────────────────────────────────────────────────────────┘ │ +│ │ +│ CYXWIZ CORE (our additions - NOT plugins): │ +│ ┌────────────────────────────────────────────────────────────┐ │ +│ │ │ │ +│ │ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │ │ +│ │ │ Governance │ │ Scope │ │ Audit │ │ │ +│ │ │ Engine │ │ Enforcement │ │ Logging │ │ │ +│ │ └──────────────┘ └──────────────┘ └──────────────┘ │ │ +│ │ │ │ +│ │ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │ │ +│ │ │ Findings │ │ Report │ │ Domain │ │ │ +│ │ │ Store │ │ Generation │ │ Registry │ │ │ +│ │ └──────────────┘ └──────────────┘ └──────────────┘ │ │ +│ │ │ │ +│ └────────────────────────────────────────────────────────────┘ │ +│ │ +│ DOMAIN AGENTS (pluggable, extensible): │ +│ ┌────────────────────────────────────────────────────────────┐ │ +│ │ │ │ +│ │ ┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐ │ │ +│ │ │ Pentest │ │ SOC │ │ DevOps │ │ NetEng │ ... │ │ +│ │ │ Agent │ │ Agent │ │ Agent │ │ Agent │ │ │ +│ │ └─────────┘ └─────────┘ └─────────┘ └─────────┘ │ │ +│ │ │ │ │ │ │ │ +│ │ ▼ ▼ ▼ ▼ │ │ +│ │ ┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐ │ │ +│ │ │ Tools │ │ Tools │ │ Tools │ │ Tools │ │ │ +│ │ │ nmap, │ │ splunk, │ │ kubectl │ │ cisco, │ │ │ +│ │ │ nikto │ │ elastic │ │ ansible │ │ juniper │ │ │ +│ │ └─────────┘ └─────────┘ └─────────┘ └─────────┘ │ │ +│ │ │ │ +│ └────────────────────────────────────────────────────────────┘ │ +│ │ +│ COMMUNITY PLUGINS (our ecosystem): │ +│ ┌────────────────────────────────────────────────────────────┐ │ +│ │ Third-party agents │ Custom tools │ Integrations │ ... │ │ +│ └────────────────────────────────────────────────────────────┘ │ +│ │ +└─────────────────────────────────────────────────────────────────┘ +``` + +--- + +## Tech Stack + +### Language: TypeScript + +OpenCode is TypeScript. We stay TypeScript. + +| Component | Technology | Source | +|-----------|------------|--------| +| Language | TypeScript | Inherited | +| Runtime | Bun | Inherited | +| CLI Framework | Cobra-style | Inherited | +| TUI | Bubble Tea (via JS bindings) | Inherited | +| Multi-LLM | OpenCode providers | Inherited | +| State | SQLite | Inherited + Extended | +| Plugin System | OpenCode plugins | Inherited + Extended | +| Tool Execution | Subprocess | Inherited | + +### What We Modify/Add + +| Component | Change | +|-----------|--------| +| Governance Engine | New - core feature | +| Scope Enforcement | New - core feature | +| Audit System | New - core feature | +| Findings Store | New - extended SQLite schema | +| Domain Registry | New - agent/tool management | +| Report Generator | New - export system | + +--- + +## Governance Engine (Core Feature) + +This is what differentiates Cyxwiz from vanilla OpenCode. + +### How It Works + +``` +┌─────────────────────────────────────────────────────────┐ +│ COMMAND LIFECYCLE │ +│ │ +│ User Intent │ +│ ↓ │ +│ LLM Translation → "nmap -sV 10.0.0.15" │ +│ ↓ │ +│ ┌─────────────────────────────────────┐ │ +│ │ GOVERNANCE CHECK │ │ +│ │ │ │ +│ │ 1. Scope Check │ │ +│ │ Is 10.0.0.15 in allowed scope? │ │ +│ │ │ │ +│ │ 2. Policy Check │ │ +│ │ Is nmap auto-approved? │ │ +│ │ Any dangerous flags? │ │ +│ │ │ │ +│ │ 3. Approval Flow │ │ +│ │ Auto-approve OR prompt user │ │ +│ │ │ │ +│ └─────────────────────────────────────┘ │ +│ ↓ │ +│ Execute (if approved) │ +│ ↓ │ +│ Audit Log (always) │ +│ ↓ │ +│ Parse Output → Findings Store │ +│ ↓ │ +│ LLM Explanation │ +└─────────────────────────────────────────────────────────┘ +``` + +### Policy Configuration (Per Domain) + +```typescript +// Example: Pentest domain policy +{ + domain: "pentest", + autoApprove: [ + "nmap *", + "nikto *", + "ffuf *", + "nuclei *", + "whois *", + "dig *", + "curl *" + ], + requireApproval: [ + "metasploit *", + "sqlmap --os-*", + "* --exploit *", + "* --exec *" + ], + blocked: [ + "rm -rf *", + "* > /dev/*" + ] +} +``` + +--- + +## Domain Agents + +### MVP: Pentest Agent + +**Target User:** Solo security consultant + +**Tools:** +| Tool | Purpose | Parser | +|------|---------|--------| +| nmap | Port scanning | XML parser | +| nikto | Web vuln scanning | Text parser | +| ffuf | Fuzzing | JSON parser | +| nuclei | Template scanning | JSON parser | +| whois | Domain recon | Text parser | +| dig | DNS queries | Text parser | +| metasploit | Exploitation | RPC parser | + +**Workflow:** +``` +cyxwiz pentest start --scope 10.0.0.0/24 --exclude 10.0.0.1 + +> "scan for open ports" +[nmap executes, findings stored] + +> "check web services for vulnerabilities" +[nikto + nuclei on discovered web ports] + +> "generate report" +[markdown/PDF export] +``` + +### Future: SOC Agent + +**Target User:** Security analyst + +**Tools:** +- Splunk queries +- Elastic search +- SIEM integrations +- Threat intel lookups +- IOC checking + +### Future: DevOps Agent + +**Target User:** DevOps engineer + +**Tools:** +- kubectl +- terraform +- ansible +- docker +- cloud CLIs (aws, gcloud, az) + +### Future: NetEng Agent + +**Target User:** Network engineer + +**Tools:** +- cisco IOS commands +- juniper CLI +- network scanners +- config parsers + +--- + +## Build Phases + +### Phase 1: Fork & Foundation +- [ ] Fork OpenCode repository +- [ ] Set up development environment +- [ ] Understand codebase structure +- [ ] Identify modification points for governance +- [ ] Create Cyxwiz branding/naming + +**Deliverable:** Building Cyxwiz from source, understanding the codebase. + +### Phase 2: Governance Engine +- [ ] Implement `tool.execute.before` hook for governance +- [ ] Build scope definition system +- [ ] Build policy configuration system +- [ ] Implement approval flow (auto/prompt/block) +- [ ] Implement audit logging + +**Deliverable:** Any command goes through governance check before execution. + +### Phase 3: Pentest Agent MVP +- [ ] Create pentest agent configuration +- [ ] Implement nmap tool with XML parser +- [ ] Implement scope enforcement for targets +- [ ] Basic findings storage +- [ ] LLM explanation of results + +**Deliverable:** Can run "scan ports on X" with governance and get explained results. + +### Phase 4: Multi-Tool Pentest +- [ ] Add nikto, ffuf, nuclei tools +- [ ] Add parsers for each +- [ ] Findings accumulation +- [ ] Cross-tool context (LLM knows all findings) + +**Deliverable:** Full recon workflow with multiple tools. + +### Phase 5: State & Reports +- [ ] Session persistence (resume engagements) +- [ ] Findings export (markdown, JSON) +- [ ] Report generation +- [ ] Engagement history + +**Deliverable:** Professional pentest workflow with deliverables. + +### Phase 6: Platform Polish +- [ ] Domain registry system +- [ ] Plugin system for community agents +- [ ] Documentation +- [ ] Distribution (npm, binary, docker) + +**Deliverable:** Cyxwiz v1.0 - platform ready for public use. + +### Phase 7+: Multi-Domain Expansion +- [ ] SOC agent +- [ ] DevOps agent +- [ ] NetEng agent +- [ ] Community contributions + +--- + +## UI Evolution + +Inherited from OpenCode, enhanced for Cyxwiz: + +### CLI (Default) +``` +$ cyxwiz pentest start --scope 10.0.0.0/24 +Starting engagement: external-pentest +Scope: 10.0.0.0/24 +Audit log: ~/.cyxwiz/audits/2024-01-15-001.log + +> scan for open ports on the entire scope +[Governance: APPROVED - nmap is auto-approved] +[Executing: nmap -sV -sC -oX /tmp/scan.xml 10.0.0.0/24] + +Found 12 hosts with open ports... +``` + +### TUI (Inherited from OpenCode) +``` +┌─────────────────────────────────────────────────────────┐ +│ Cyxwiz Pentest │ Scope: 10.0.0.0/24 │ Findings: 23 │ +├─────────────┬───────────────────┬───────────────────────┤ +│ TARGETS │ FINDINGS │ AUDIT LOG │ +│ │ │ │ +│ ● 10.0.0.15 │ ⚠ SSH outdated │ [14:23] nmap started │ +│ ● 10.0.0.20 │ ⚠ HTTP exposed │ [14:25] 12 hosts up │ +│ ○ 10.0.0.25 │ ✗ Default creds │ [14:30] nikto done │ +├─────────────┴───────────────────┴───────────────────────┤ +│ > check .15 for web vulnerabilities │ +└─────────────────────────────────────────────────────────┘ +``` + +### Web UI (Future) +- FastAPI backend +- HTMX → Svelte frontend +- Same core, different interface + +--- + +## What Success Looks Like + +### Phase 3 (MVP): +``` +$ cyxwiz pentest start --scope scanme.nmap.org + +> scan for open ports +[APPROVED] Executing nmap... + +Found 4 open ports on scanme.nmap.org: +- 22/tcp: OpenSSH 6.6.1 (protocol 2.0) +- 80/tcp: Apache httpd 2.4.7 +- 9929/tcp: Nping echo +- 31337/tcp: Elite backdoor (likely test) + +Recommendation: Investigate port 80 for web vulnerabilities. + +> ok do that +[APPROVED] Executing nikto... +``` + +### Phase 6 (v1.0): +``` +$ cyxwiz + +Available domains: + pentest - Security testing and assessment + soc - Security operations and monitoring (coming soon) + devops - Infrastructure and deployment (coming soon) + +$ cyxwiz pentest +$ cyxwiz soc +$ cyxwiz devops +``` + +--- + +## Market Evolution + +### Phase 1-5: Niche Tool +- Target: Solo security consultants +- Revenue: $5K-$20K/month +- Model: Open source + paid features + +### Phase 6+: Platform Play +- Target: Security teams, DevOps teams, IT departments +- Revenue: Platform potential +- Model: Open source core + enterprise features + marketplace + +### Long-term Moat +1. **Governance engine** - Differentiator from generic AI tools +2. **Domain expertise** - Deep integration with professional tools +3. **Audit compliance** - Enterprise requirement +4. **Community ecosystem** - Network effects from plugins + +--- + +## Distribution Strategy + +### The Kali/Parrot Advantage + +Security-focused Linux distributions like Kali and Parrot OS come with 600+ pre-installed security tools. Cyxwiz becomes the intelligent orchestration layer on top. + +``` +┌─────────────────────────────────────────────────────────┐ +│ KALI/PARROT + CYXWIZ │ +│ │ +│ Pre-installed (600+ tools): │ +│ ├─ nmap, nikto, metasploit, sqlmap, ffuf, nuclei │ +│ ├─ burpsuite, wireshark, john, hashcat, hydra │ +│ ├─ gobuster, dirb, wfuzz, amass, subfinder │ +│ └─ ... hundreds more │ +│ │ +│ What's missing: │ +│ └─ Intelligent orchestration ← CYXWIZ fills this gap │ +│ │ +│ Result: │ +│ └─ Junior analyst can use pro tools safely │ +│ └─ Senior analyst works 10x faster │ +│ └─ Everything audited and governed │ +└─────────────────────────────────────────────────────────┘ +``` + +### Integration Levels + +**Level 1: Manual Install (Day 1)** +```bash +# Works on any Kali/Parrot box +curl -fsSL https://cyxwiz.dev/install | bash +cyxwiz setup # Auto-detects available tools +``` + +**Level 2: Package Repository (Phase 6)** +```bash +# Submit to Kali repos +sudo apt update +sudo apt install cyxwiz +``` + +**Level 3: Pre-installed (Long-term Goal)** +- Partner with Offensive Security (Kali maintainers) +- Get Cyxwiz included in default installation +- Every Kali download = potential Cyxwiz user + +### Auto-Detection System + +Cyxwiz adapts to available tools: + +```typescript +// On first run or `cyxwiz setup` +const detectTools = async () => { + const detected = []; + + for (const tool of SUPPORTED_TOOLS) { + if (await commandExists(tool.binary)) { + detected.push({ + name: tool.name, + version: await getVersion(tool.binary), + parser: tool.parser, + status: 'available' + }); + } + } + + // Cyxwiz works with whatever is installed + // Full power on Kali, limited on vanilla Ubuntu + return detected; +}; +``` + +**Output example:** +``` +$ cyxwiz setup + +Detecting available tools... + +RECONNAISSANCE + ✓ nmap 7.94 Port scanning + ✓ amass 3.19 Subdomain enumeration + ✓ subfinder 2.5 Subdomain discovery + ✗ masscan Fast port scanning (not installed) + +WEB ANALYSIS + ✓ nikto 2.5 Web vulnerability scanner + ✓ ffuf 2.0 Web fuzzer + ✓ nuclei 2.9 Template-based scanner + ✓ sqlmap 1.7 SQL injection + +EXPLOITATION + ✓ metasploit 6.3 Exploitation framework + ✓ hydra 9.4 Password cracking + +47 tools available. Cyxwiz is ready. +``` + +### Distribution Channels + +| Platform | Method | Friction | Timeline | +|----------|--------|----------|----------| +| Any Linux | curl script | Low | Phase 3 | +| Kali/Parrot | apt package | Very low | Phase 6 | +| Kali/Parrot | Pre-installed | Zero | Phase 7+ | +| Docker | `docker run cyxwiz` | Low | Phase 5 | +| macOS | `brew install cyxwiz` | Low | Phase 6 | +| Windows/WSL | curl script | Medium | Phase 6 | + +### Why Kali/Parrot Teams Would Accept Cyxwiz + +| Their Priority | How Cyxwiz Helps | +|----------------|---------------| +| Beginner accessibility | Natural language interface | +| Tool discoverability | Cyxwiz suggests relevant tools | +| Professional use | Governance + audit trails | +| Community value | Open source (MIT) | +| Distro differentiation | No competitor has this | + +### The Pitch (When Ready) + +> "Cyxwiz is the missing brain for Kali Linux. Your 600+ tools, now accessible through natural language. Junior analysts work safely with built-in governance. Senior analysts work faster with intelligent orchestration. Every action audited for compliance. The AI layer your toolkit has been waiting for." + +--- + +## Risks & Mitigations + +| Risk | Mitigation | +|------|------------| +| OpenCode changes license | Already forked, MIT is irrevocable | +| OpenCode dies | We own our fork, continue independently | +| Can't keep up with OpenCode updates | Cherry-pick relevant updates only | +| TypeScript learning curve | OpenCode codebase is well-structured | +| Governance adds latency | Optimize hot paths, cache policy decisions | +| Multi-domain dilutes focus | Nail pentest first before expanding | + +--- + +## Open Questions + +- [ ] Cyxwiz branding (name, logo, domain) +- [ ] Open source model (MIT? Apache? AGPL for enterprise?) +- [ ] Community building strategy +- [ ] When to diverge significantly from OpenCode upstream +- [ ] Enterprise features for monetization + +--- + +## Next Step + +1. Fork OpenCode +2. Build locally +3. Explore codebase +4. Identify where to inject governance engine + +Start with understanding. Then modify. diff --git a/docs/SOCIAL_POST_TEMPLATE.md b/docs/SOCIAL_POST_TEMPLATE.md new file mode 100644 index 00000000000..24b65a55cd8 --- /dev/null +++ b/docs/SOCIAL_POST_TEMPLATE.md @@ -0,0 +1,235 @@ +# Cyxwiz - Social Media Post Templates + +## Short Version (Twitter/X, LinkedIn) + +``` +Tired of memorizing nmap flags, nikto options, and nuclei syntax? + +I built Cyxwiz - an AI-powered pentest assistant. Just describe what you need: + +"scan this network for web vulnerabilities" + +And it: +- Runs the right tools (nmap, nikto, nuclei) +- Parses the output +- Classifies findings by severity +- Generates professional reports + +Built on OpenCode agent. Open source. + +GitHub: https://github.com/code3hr/opencode +Download: https://github.com/code3hr/opencode/releases/latest + +#infosec #pentesting #cybersecurity #AI #opensource +``` + +--- + +## Medium Version (Reddit, Dev.to, Forums) + +``` +# Cyxwiz: Stop Memorizing Tool Syntax, Start Describing What You Need + +Hey everyone, + +I've been working on something I think the community might find useful. + +## The Problem + +As pentesters, we spend too much time on syntax: +- nmap has 130+ options +- nuclei has dozens of flags +- sqlmap has 100+ parameters + +Multiply by 30+ tools per assessment. That's not security work - that's a memorization exercise. + +## The Solution: Cyxwiz + +Cyxwiz is an AI-powered security assistant. You describe what you want in plain English: + +``` +You: "scan 192.168.1.0/24 for web vulnerabilities" + +Cyxwiz: [Runs nmap → finds web servers] + [Runs nikto → checks vulnerabilities] + [Runs nuclei → matches CVEs] + + Found 3 critical, 5 high, 8 medium findings. + All saved with evidence. Want a report? +``` + +## What Makes It Different? + +Built on OpenCode (superior agent architecture), Cyxwiz adds: + +- **30+ Security Tools** - nmap, nikto, nuclei, gobuster, sqlmap, etc. +- **Intelligent Parsers** - Extracts structured findings from raw output +- **Findings Database** - Severity classification, OWASP mapping, CVE tracking +- **Governance Engine** - Scope enforcement, audit trails +- **Report Generation** - Professional HTML/PDF reports + +## Not Another Wrapper + +Unlike basic LLM CLIs that just run commands, Cyxwiz: +- Actually understands security tool output +- Maintains persistent findings across sessions +- Prevents out-of-scope accidents +- Generates compliance-ready audit logs + +## Try It + +- GitHub: https://github.com/code3hr/opencode +- Download: https://github.com/code3hr/opencode/releases/latest +- Platforms: Linux, macOS, Windows + +It's open source (MIT). Would love feedback from the community. + +What features would you want to see? +``` + +--- + +## Long Version (Hacker News "Show HN", Blog Post) + +``` +# Show HN: Cyxwiz - AI-Powered Pentest Assistant (Open Source) + +I built Cyxwiz because I was tired of context-switching between remembering tool syntax and actually doing security work. + +## Background + +I've been doing security assessments for a while, and the workflow is always: +1. Remember the right tool for the job +2. Look up the flags (again) +3. Run the command +4. Parse the output manually +5. Copy findings to a spreadsheet +6. Repeat 100 times +7. Manually write the report + +## What Cyxwiz Does + +Cyxwiz lets you describe what you want in natural language: + +"check if this Apache server is vulnerable to path traversal" + +And it: +1. Selects the right tools (nuclei with CVE-2021-41773 templates) +2. Runs them with correct parameters +3. Parses the output into structured findings +4. Classifies by severity (Critical/High/Medium/Low) +5. Stores with evidence for the report +6. Generates professional reports when you're done + +## Technical Details + +Built on OpenCode (https://github.com/sst/opencode), which provides: +- Superior agent architecture vs generic LLM CLIs +- Extensible tool framework with typed I/O +- Multi-LLM support (Claude, GPT-4, Gemini, local models) + +Cyxwiz adds a security layer: +- 30+ tool integrations with output parsers +- Findings database with OWASP/CVE categorization +- Governance engine (scope enforcement, audit trails) +- Report generation (HTML, PDF, Markdown) + +## What It's NOT + +- Not a replacement for knowing what you're doing +- Not for unauthorized testing +- Not a magic "hack anything" button + +It's an assistant that handles the tedious parts so you can focus on analysis. + +## Stack + +- TypeScript/Bun +- Runs on Kali, Parrot, any Linux, macOS, Windows +- Requires API key (Claude recommended, GPT-4 works too) + +## Links + +- GitHub: https://github.com/code3hr/opencode +- Downloads: https://github.com/code3hr/opencode/releases/latest + +Open source, MIT licensed. Feedback welcome! +``` + +--- + +## Quick Demo Script (for Video/GIF) + +``` +# Terminal recording script + +$ ./cyxwiz + +> scan 10.0.0.5 for vulnerabilities + +[Cyxwiz runs nmap, detects Apache 2.4.41] +[Cyxwiz runs nikto, finds misconfigurations] +[Cyxwiz runs nuclei, matches CVE-2021-41773] + +Found 1 critical, 2 high, 3 medium findings. + +> show critical findings + +CRITICAL: CVE-2021-41773 - Apache Path Traversal +- Target: 10.0.0.5:80 +- Impact: Remote Code Execution +- Evidence: [response data] +- Remediation: Upgrade to Apache 2.4.51+ + +> generate report + +Report generated: assessment-2024-01-15.html +``` + +--- + +## Platform-Specific Tips + +### Reddit (r/netsec, r/pentesting) +- Don't be too salesy +- Focus on the problem you solved +- Ask for feedback +- Engage with comments + +### Hacker News +- Technical depth appreciated +- Mention the architecture +- Be honest about limitations +- "Show HN:" prefix for launches + +### Twitter/X +- Thread format works well +- Include a GIF/video demo +- Tag relevant accounts +- Use hashtags sparingly + +### LinkedIn +- More professional tone +- Mention business value +- Connect with security leaders + +### Product Hunt +- Need good visuals +- Schedule for Tuesday-Thursday +- Prepare for Q&A + +--- + +## Hashtags + +``` +#infosec #pentesting #cybersecurity #hacking #security +#bugbounty #redteam #AI #LLM #opensource #kalilinux +``` + +## Accounts to Tag (Twitter) + +``` +@offensive_con @defaboreal @NahamSec @staboreal +@TomNomNom @Jhaddix @inlocsec @InfoSecSherpa +``` diff --git a/docs/TEST.md b/docs/TEST.md new file mode 100644 index 00000000000..2dd0ac10484 --- /dev/null +++ b/docs/TEST.md @@ -0,0 +1,430 @@ +# Testing Documentation + +This document describes the testing approach, test structure, and how to run tests for cyxwiz. + +--- + +## Table of Contents + +- [Overview](#overview) +- [Running Tests](#running-tests) +- [Test Structure](#test-structure) +- [Governance Tests](#governance-tests) +- [Writing Tests](#writing-tests) +- [Coverage](#coverage) + +--- + +## Overview + +cyxwiz uses [Bun's built-in test runner](https://bun.sh/docs/cli/test) for unit and integration testing. Tests are located in the `packages/opencode/test/` directory and mirror the source structure. + +### Test Stack + +| Tool | Purpose | +|------|---------| +| Bun Test | Test runner and assertions | +| `bun:test` | Test framework imports (test, expect, describe) | +| Coverage | Built-in coverage reporting | + +--- + +## Running Tests + +### Prerequisites + +Ensure Bun is installed: + +```bash +# Install Bun +curl -fsSL https://bun.sh/install | bash + +# Verify installation +bun --version +``` + +### Run All Tests + +```bash +cd packages/opencode +bun test +``` + +### Run Specific Test File + +```bash +cd packages/opencode +bun test test/governance/governance.test.ts +``` + +### Run Tests Matching Pattern + +```bash +cd packages/opencode +bun test --test-name-pattern "classifyTarget" +``` + +### Run Tests with Coverage + +```bash +cd packages/opencode +bun test --coverage +``` + +### Watch Mode + +```bash +cd packages/opencode +bun test --watch +``` + +--- + +## Test Structure + +``` +packages/opencode/test/ +├── agent/ # Agent-related tests +├── cli/ # CLI command tests +├── config/ # Configuration tests +├── file/ # File operation tests +├── governance/ # Governance engine tests +│ ├── governance.test.ts # Main test suite +│ └── test-standalone.ts # Standalone test script +├── lsp/ # LSP integration tests +├── mcp/ # MCP protocol tests +├── permission/ # Permission system tests +├── plugin/ # Plugin system tests +├── provider/ # Provider tests +├── session/ # Session management tests +├── tool/ # Tool tests +├── util/ # Utility function tests +├── bun.test.ts # Bun test configuration +└── preload.ts # Test preload script +``` + +--- + +## Governance Tests + +The governance module has comprehensive test coverage across all submodules. + +### Test File + +`test/governance/governance.test.ts` + +### Test Results + +``` + 42 pass + 0 fail + 78 expect() calls +``` + +### Test Categories + +#### GovernanceMatcher Tests + +| Test | Description | +|------|-------------| +| `classifyTarget: IPv4 address` | Classifies "192.168.1.1" as IP | +| `classifyTarget: CIDR notation` | Classifies "10.0.0.0/8" as CIDR | +| `classifyTarget: domain` | Classifies "example.com" as domain | +| `classifyTarget: URL extracts hostname` | Extracts hostname from URLs | +| `classifyTarget: unknown` | Returns unknown for unrecognized strings | +| `classifyTarget: validates IP octets` | Rejects invalid IPs like "999.999.999.999" | +| `extractTargets: bash curl` | Extracts URL from curl commands | +| `extractTargets: bash ping` | Extracts IP from ping commands | +| `extractTargets: bash SSH` | Extracts host from SSH commands | +| `extractTargets: webfetch` | Extracts URL from webfetch tool | +| `extractTargets: websearch` | Returns empty for search queries | +| `extractTargets: deduplication` | Deduplicates same targets | +| `extractTargets: multiple targets` | Extracts multiple different targets | +| `ipInCidr: /8 range` | Tests /8 CIDR matching | +| `ipInCidr: /24 range` | Tests /24 CIDR matching | +| `ipInCidr: /32 single host` | Tests single host matching | +| `ipInCidr: /0 all IPs` | Tests match-all CIDR | +| `matchTarget: IP vs CIDR` | Matches IP against CIDR pattern | +| `matchTarget: domain wildcard` | Matches domain against wildcard | +| `matchTarget: exact domain` | Matches exact domain | + +#### GovernanceScope Tests + +| Test | Description | +|------|-------------| +| `allows when no scope` | Allows all when no config | +| `allows when no targets` | Allows when no targets extracted | +| `allows IP in allowed CIDR` | Allows IPs in allowed range | +| `denies IP not in range` | Denies IPs outside allowed range | +| `deny takes precedence` | Deny list overrides allow list | +| `allows domain matching` | Allows domains matching pattern | +| `denies domain in deny list` | Denies domains matching deny pattern | +| `fails on first violation` | Checks multiple targets, fails fast | + +#### GovernancePolicy Tests + +| Test | Description | +|------|-------------| +| `default action` | Returns default when no policies | +| `matches by tool name` | Matches policy by tool | +| `matches by tool wildcard` | Matches policy by tool pattern | +| `matches bash command` | Matches bash command patterns | +| `non-bash command filter` | Command filter only applies to bash | +| `matches by target` | Matches policy by target pattern | +| `first match wins` | Policy order determines outcome | +| `AND logic` | All conditions must match | +| `describe formatting` | Formats policy description | + +#### GovernanceAudit Tests + +| Test | Description | +|------|-------------| +| `records to memory` | Records audit entry to memory | +| `strips args` | Removes args when include_args=false | +| `lists entries` | Lists entries with filters | +| `memoryCount` | Returns correct entry count | +| `clearMemory` | Clears memory buffer | + +### Running Governance Tests + +```bash +cd packages/opencode + +# Run all governance tests +bun test test/governance/governance.test.ts + +# Run with coverage +bun test test/governance/governance.test.ts --coverage + +# Run specific test +bun test --test-name-pattern "ipInCidr" +``` + +### Standalone Test Script + +For environments without Bun's test runner, use the standalone script: + +```bash +cd packages/opencode +bun run test/governance/test-standalone.ts +``` + +This script runs the same tests without framework dependencies. + +--- + +## Writing Tests + +### Basic Test Structure + +```typescript +import { test, expect, describe, beforeEach } from "bun:test" +import { MyModule } from "../../src/mymodule" + +describe("MyModule", () => { + beforeEach(() => { + // Setup before each test + }) + + test("does something", () => { + const result = MyModule.doSomething() + expect(result).toBe(expectedValue) + }) + + test("handles edge case", () => { + expect(() => MyModule.badInput(null)).toThrow() + }) +}) +``` + +### Common Assertions + +```typescript +// Equality +expect(value).toBe(expected) // Strict equality +expect(value).toEqual(expected) // Deep equality + +// Truthiness +expect(value).toBeTruthy() +expect(value).toBeFalsy() +expect(value).toBeNull() +expect(value).toBeUndefined() +expect(value).toBeDefined() + +// Numbers +expect(value).toBeGreaterThan(n) +expect(value).toBeGreaterThanOrEqual(n) +expect(value).toBeLessThan(n) +expect(value).toBeLessThanOrEqual(n) + +// Strings +expect(string).toContain(substring) +expect(string).toMatch(/regex/) + +// Arrays +expect(array).toContain(item) +expect(array).toHaveLength(n) + +// Objects +expect(object).toHaveProperty("key") +expect(object).toHaveProperty("key", value) + +// Exceptions +expect(() => fn()).toThrow() +expect(() => fn()).toThrow("message") +expect(() => fn()).toThrow(ErrorType) + +// Async +await expect(promise).resolves.toBe(value) +await expect(promise).rejects.toThrow() +``` + +### Testing Async Code + +```typescript +test("async operation", async () => { + const result = await asyncFunction() + expect(result).toBe(expected) +}) + +test("async with beforeEach", async () => { + beforeEach(async () => { + await setup() + }) + + // Tests run after setup completes +}) +``` + +### Mocking + +```typescript +import { mock, spyOn } from "bun:test" + +test("with mock", () => { + const mockFn = mock(() => "mocked") + + const result = mockFn() + + expect(mockFn).toHaveBeenCalled() + expect(mockFn).toHaveBeenCalledTimes(1) + expect(result).toBe("mocked") +}) + +test("with spy", () => { + const spy = spyOn(object, "method") + + object.method() + + expect(spy).toHaveBeenCalled() +}) +``` + +--- + +## Coverage + +### Viewing Coverage + +Run tests with coverage flag: + +```bash +bun test --coverage +``` + +Output shows coverage by file: + +``` +---------------------------|---------|---------|------------------- +File | % Funcs | % Lines | Uncovered Line #s +---------------------------|---------|---------|------------------- +All files | 55.37 | 56.88 | + src/governance/types.ts | 100.00 | 100.00 | + src/governance/matcher.ts | 100.00 | 88.52 | 187-193,270-275 + src/governance/policy.ts | 100.00 | 96.59 | 237,258 + src/governance/scope.ts | 100.00 | 87.30 | 193-194,219-220 + src/governance/audit.ts | 80.00 | 56.31 | ... +---------------------------|---------|---------|------------------- +``` + +### Coverage Goals + +| Module | Target | +|--------|--------| +| Core governance | >90% functions, >80% lines | +| Utilities | >80% functions | +| Integration | >70% lines | + +### Improving Coverage + +1. Identify uncovered lines from coverage report +2. Add tests for edge cases and error paths +3. Test error handling and exception cases +4. Add integration tests for complex flows + +--- + +## Continuous Integration + +Tests run automatically on: + +- Pull request creation +- Push to main/dev branches +- Manual workflow trigger + +### CI Configuration + +Tests are configured in `.github/workflows/` to: + +1. Install dependencies with Bun +2. Run type checking +3. Run test suite +4. Report coverage + +--- + +## Troubleshooting + +### Common Issues + +#### "Cannot find module" Error + +Ensure you're in the correct directory: + +```bash +cd packages/opencode +bun test +``` + +#### Tests Timeout + +Increase timeout for slow tests: + +```typescript +test("slow test", async () => { + // ... +}, 30000) // 30 second timeout +``` + +#### Flaky Tests + +- Avoid relying on timing +- Use proper async/await +- Clean up state in beforeEach/afterEach +- Isolate tests from external dependencies + +#### Coverage Not Working + +Ensure bun version supports coverage: + +```bash +bun --version # Should be 1.0+ +``` + +--- + +## Resources + +- [Bun Test Documentation](https://bun.sh/docs/cli/test) +- [Bun Test API](https://bun.sh/docs/api/test) +- [Jest-compatible Matchers](https://bun.sh/docs/test/matchers) diff --git a/docs/TODO.md b/docs/TODO.md new file mode 100644 index 00000000000..5b005d40a92 --- /dev/null +++ b/docs/TODO.md @@ -0,0 +1,226 @@ +# Pentest Module Development Phases + +## Completed Phases + +### Phase 1-5: Core Pentest Module ✅ +- **types.ts** - Core type definitions using Zod schemas +- **nmap-parser.ts** - Nmap XML output parsing +- **findings.ts** - Security findings storage and management +- **nmap-tool.ts** - Dedicated nmap tool with full feature support +- **sectools.ts** - Wrapper for 30+ security tools + +### Phase 6: Parser Extensions ✅ +- **parsers/nikto.ts** - Nikto web scanner output parser +- **parsers/nuclei.ts** - Nuclei vulnerability scanner parser +- **parsers/gobuster.ts** - Gobuster directory enumeration parser +- **parsers/ffuf.ts** - Ffuf fuzzer output parser +- **parsers/sslscan.ts** - SSL/TLS scanner output parser + +### Phase 7: Report Generation ✅ +- **reports/** - Security assessment report generation +- **report-tool.ts** - Report tool for agents +- Supports Markdown, HTML, JSON output formats + +### Phase 8: Continuous Monitoring ✅ +- **monitoring/** - Scheduled scans with diff detection +- **monitoring/tool.ts** - Monitor tool for agents +- **monitoring/scheduler.ts** - Scan scheduling +- **monitoring/events.ts** - Monitoring events + +### Phase 8b: Exploit Integration ✅ +- **exploits/** - Exploit matching and execution +- **exploits/tool.ts** - Exploit tool for agents +- **exploits/matcher.ts** - CVE to exploit matching +- **exploits/events.ts** - Exploit events + +### Phase 8c: Web Scanner ✅ +- **webscan/** - Web application security scanner +- **webscan/tool.ts** - WebScan tool for agents +- **webscan/crawler.ts** - Web crawler +- **webscan/orchestrator.ts** - Scan coordination +- **webscan/events.ts** - WebScan events + +### Phase 9: API Security Scanner ✅ +Documentation: [PHASE9.md](PHASE9.md) + +- **apiscan/** - API security testing module +- API Discovery (OpenAPI/Swagger, GraphQL) +- Authentication Testing (JWT, API keys, OAuth) +- Authorization Testing (BOLA/IDOR, privilege escalation) +- Injection Testing (SQL, NoSQL, command injection) +- OWASP API Top 10 2023 categorization + +### Phase 10: Network Infrastructure Scanner ✅ +Documentation: [PHASE10.md](PHASE10.md) + +- **netscan/** - Network infrastructure security testing +- Active Directory enumeration (users, groups, computers, trusts) +- Kerberoasting and AS-REP roasting detection +- SMB testing (shares, null sessions, signing, vulnerabilities) +- DNS testing (zone transfers, subdomain enumeration) +- SNMP testing (community strings, SNMP walking) +- LDAP testing (anonymous bind, password policy) +- Credential testing (default creds, password spraying) + +### Phase 11: Cloud Security Scanner ✅ +Documentation: [PHASE11.md](PHASE11.md) + +- **cloudscan/** - Cloud infrastructure security testing +- AWS security assessment (IAM, S3, Security Groups, EC2, Lambda) +- Azure security assessment (RBAC, Storage, NSG, VMs, Function Apps) +- GCP security assessment (IAM, GCS, Firewall, GCE, Cloud Functions) +- Compliance checking (CIS, NIST, PCI-DSS, HIPAA, SOC2, GDPR, ISO27001) +- External tool integration (Prowler, ScoutSuite) + +### Phase 12: Container Security Scanner + CVE Lookup ✅ +Documentation: [PHASE12.md](PHASE12.md) + +- **cve/** - CVE Lookup Service +- NVD API 2.0, OSV API, CISA KEV integration +- CVE data caching with TTL +- Finding enrichment utilities +- **containerscan/** - Container and orchestration security +- Docker image vulnerability scanning (Trivy, Grype) +- SBOM generation (Syft) +- Kubernetes cluster security assessment +- Pod security, RBAC, network policy analysis +- Registry scanning (Docker Hub, ECR, ACR, GCR) +- CIS Docker/Kubernetes compliance + +### Phase 13: Mobile Application Scanner ✅ +Documentation: [PHASE13.md](PHASE13.md) + +- **mobilescan/** - Mobile app security testing +- Android APK analysis (manifest, permissions, components, crypto, storage, network) +- iOS IPA analysis (plist, entitlements, ATS, binary protections) +- OWASP Mobile Top 10 2024 coverage (M1-M10) +- API key/secret detection with entropy calculation +- SSL pinning detection +- Root/jailbreak detection +- Code obfuscation analysis +- URL extraction and categorization +- External tool integration (APKTool, JADX, MobSF, Androguard) +- Multiple scan profiles (discovery, quick, standard, thorough, compliance) + +### Phase 14: Wireless Network Scanner ✅ +Documentation: [PHASE14.md](PHASE14.md) + +- **wirelessscan/** - Wireless security testing +- WiFi network discovery and enumeration +- WPA/WPA2/WPA3 security assessment (KRACK, Dragonblood detection) +- Rogue access point and evil twin detection +- Client enumeration with OUI lookup +- Handshake capture and analysis +- Deauthentication attack detection +- Bluetooth security testing (Classic and BLE) +- BlueBorne, KNOB, BIAS, BLESA vulnerability checks +- RFID/NFC security assessment +- MIFARE Classic/DESFire, NTAG, HID, EM4100 support +- Cloning vulnerability assessment +- External tool integration (Aircrack-ng, Kismet, Bettercap, Ubertooth, Proxmark3) +- Multiple scan profiles (discovery, quick, standard, thorough, passive, active) + +### Phase 15: Social Engineering Toolkit ✅ +Documentation: [PHASE15.md](PHASE15.md) + +- **soceng/** - Social engineering toolkit for authorized security testing +- Email security assessment (SPF/DKIM/DMARC validation, spoofing analysis) +- Lookalike domain generation for awareness testing +- Phishing campaign management (credential harvest, payload delivery, awareness) +- Pre-built phishing templates (password reset, IT support, HR, executive) +- Landing page templates (Microsoft 365, Google, generic login) +- Pretexting scenarios with objection handlers +- Persona library for social engineering engagements +- Call scripts with dialogue trees and transitions +- Payload generation (USB drop, malicious documents, VBA macros, HTA) +- OSINT reconnaissance (email discovery, organization profiling, social media) +- Security awareness training modules with quizzes +- Awareness metrics and industry benchmarking +- Executive summary and campaign reporting +- Session management for tracking assessment progress + +### Phase 16: Post-Exploitation Framework ✅ +Documentation: [PHASE16.md](PHASE16.md) + +- **postexploit/** - Guidance-based post-exploitation framework +- Privilege escalation vectors (SUID, sudo, capabilities, kernel exploits for Linux; services, registry, tokens, UAC for Windows) +- GTFOBins and LOLBAS references with exploitation guidance +- Lateral movement discovery and path analysis (SMB, WMI, SSH, RDP, WinRM, pass-the-hash/ticket) +- Credential harvesting locations (shadow, SSH keys, SAM, LSASS, NTDS, DPAPI, browser creds) +- Persistence mechanism catalog (cron, systemd, registry, scheduled tasks, WMI subscriptions, services) +- Data exfiltration channels (DNS, HTTP, SSH, SMB, cloud, steganography) +- Cleanup and artifact tracking with verification checklists +- LinPEAS and WinPEAS output parsers with automatic vector extraction +- MITRE ATT&CK technique mapping for all operations +- Assessment profiles (discovery, quick, standard, thorough, stealth) +- Session management with comprehensive statistics + +### Phase 18: CI/CD Security Integration ✅ +Documentation: [PHASE18.md](PHASE18.md) + +- **cicd/** - CI/CD pipeline security scanner +- Pipeline discovery for GitHub Actions, GitLab CI, Jenkins +- Secret detection with regex patterns and entropy analysis +- Permission analysis for excessive/risky permissions +- Command injection vulnerability detection +- Supply chain security (unpinned actions, untrusted dependencies) +- SAST integration (Semgrep, Gitleaks) +- Security gate enforcement with configurable rules +- Multiple scan profiles (discovery, quick, standard, thorough, compliance) + +--- + +## Pending Phases + +### Phase 17: Reporting Dashboard 🔜 +- **dashboard/** - Web-based reporting interface +- Real-time scan monitoring +- Finding trend visualization +- Executive summary generation +- Remediation tracking +- Compliance mapping (PCI-DSS, HIPAA, SOC2) + +--- + +## Priority Matrix + +| Phase | Priority | Complexity | Dependencies | Status | +|-------|----------|------------|--------------|--------| +| Phase 11 (Cloud) | High | High | None | ✅ Complete | +| Phase 12 (Container) | High | Medium | Phase 11 | ✅ Complete | +| Phase 13 (Mobile) | Medium | High | None | ✅ Complete | +| Phase 14 (Wireless) | Low | Medium | None | ✅ Complete | +| Phase 15 (SocEng) | Low | Medium | None | ✅ Complete | +| Phase 16 (PostExploit) | Medium | High | Phase 10 | ✅ Complete | +| Phase 17 (Dashboard) | Medium | Medium | All | 🔜 Next | +| Phase 18 (CI/CD) | High | Low | Phase 11, 12 | ✅ Complete | + +--- + +## Test Coverage + +All completed phases have corresponding test files: + +| Phase | Test File | Status | +|-------|-----------|--------| +| Core | `test/pentest/pentest.test.ts` | ✅ Passing | +| Parsers | `test/pentest/parsers.test.ts` | ✅ Passing | +| Reports | `test/pentest/reports.test.ts` | ✅ Passing | +| Monitoring | `test/pentest/monitoring.test.ts` | ✅ Passing | +| Exploits | `test/pentest/exploits.test.ts` | ✅ Passing | +| WebScan | `test/pentest/webscan.test.ts` | ✅ Passing | +| ApiScan | `test/pentest/apiscan.test.ts` | ✅ Passing | +| NetScan | `test/pentest/netscan.test.ts` | ✅ Passing | +| CloudScan | `test/pentest/cloudscan.test.ts` | 🔜 Pending | +| CVE | `test/pentest/cve.test.ts` | 🔜 Pending | +| ContainerScan | `test/pentest/containerscan.test.ts` | 🔜 Pending | +| MobileScan | `test/pentest/mobilescan.test.ts` | 🔜 Pending | +| WirelessScan | `test/pentest/wirelessscan.test.ts` | 🔜 Pending | +| SocEng | `test/pentest/soceng.test.ts` | 🔜 Pending | +| PostExploit | `test/pentest/postexploit.test.ts` | 🔜 Pending | +| CICD | `test/pentest/cicd.test.ts` | 🔜 Pending | + +Run all tests: +```bash +bun test test/pentest/ +``` diff --git a/docs/TOOLS_QUICK_REFERENCE.md b/docs/TOOLS_QUICK_REFERENCE.md new file mode 100644 index 00000000000..f7437ddd038 --- /dev/null +++ b/docs/TOOLS_QUICK_REFERENCE.md @@ -0,0 +1,832 @@ +# Pentest Tools Quick Reference Guide + +Quick reference for all security testing tools available in the pentest module. + +--- + +## Table of Contents + +1. [SecTools - Security Tools Wrapper](#sectools---security-tools-wrapper) +2. [NetScan - Network Scanner](#netscan---network-scanner) +3. [WebScan - Web Application Scanner](#webscan---web-application-scanner) +4. [ApiScan - API Security Scanner](#apiscan---api-security-scanner) +5. [CloudScan - Cloud Security Scanner](#cloudscan---cloud-security-scanner) +6. [ContainerScan - Container Security Scanner](#containerscan---container-security-scanner) +7. [CVE - CVE Lookup Tool](#cve---cve-lookup-tool) +8. [Exploits - Exploit Search Tool](#exploits---exploit-search-tool) +9. [Monitor - Continuous Monitoring](#monitor---continuous-monitoring) +10. [Report - Report Generation](#report---report-generation) + +--- + +## SecTools - Security Tools Wrapper + +Unified interface to common penetration testing tools (nmap, nikto, nuclei, etc.). + +### Supported Tools + +| Category | Tools | +|----------|-------| +| Network Recon | nmap, masscan, netcat | +| Web Scanning | nikto, dirb, gobuster, ffuf, wpscan | +| Vulnerability | nuclei, searchsploit | +| SQL Injection | sqlmap | +| SMB/Windows | enum4linux, smbclient, crackmapexec | +| SSL/TLS | sslscan, sslyze, testssl | +| DNS | dnsenum, dnsrecon, fierce | + +### Parameters + +| Parameter | Type | Required | Description | +|-----------|------|----------|-------------| +| `tool` | string | Yes | Tool name (nmap, nikto, nuclei, etc.) | +| `target` | string | Yes | Target IP, hostname, or URL | +| `args` | string | No | Tool-specific arguments | +| `timeout` | number | No | Timeout in milliseconds | +| `createFindings` | boolean | No | Create findings from results (default: true) | + +### Examples + +``` +# Nikto web scan +sectools tool="nikto" target="http://example.com" args="-Tuning 1" + +# Gobuster directory enumeration +sectools tool="gobuster" target="http://example.com" args="dir -w /usr/share/wordlists/dirb/common.txt" + +# Enum4linux SMB enumeration +sectools tool="enum4linux" target="192.168.1.1" args="-a" + +# SSL scan +sectools tool="sslscan" target="example.com" + +# Nmap service scan +sectools tool="nmap" target="192.168.1.0/24" args="-sV -sC -p 1-1000" + +# Nuclei vulnerability scan +sectools tool="nuclei" target="http://example.com" args="-t cves/" +``` + +--- + +## NetScan - Network Scanner + +Comprehensive network infrastructure security scanner with AD, SMB, DNS, LDAP, and SNMP support. + +### Actions + +| Action | Description | +|--------|-------------| +| `discover` | Discover network hosts and services | +| `scan` | Run full scan with specified profile | +| `status` | Get scan status | +| `ad-enum` | Enumerate Active Directory domain | +| `ad-users` | Enumerate AD users | +| `ad-groups` | Enumerate AD groups | +| `ad-computers` | Enumerate AD computers | +| `ad-kerberoast` | Find Kerberoastable accounts | +| `ad-asrep` | Find AS-REP roastable accounts | +| `smb-shares` | Enumerate SMB shares | +| `smb-sessions` | Enumerate SMB sessions | +| `dns-zone` | Attempt DNS zone transfer | +| `dns-enum` | DNS enumeration | +| `ldap-search` | LDAP search | +| `ldap-policy` | Get password policy via LDAP | +| `snmp-walk` | SNMP enumeration | +| `snmp-brute` | SNMP community string brute force | +| `creds-spray` | Password spraying attack | +| `creds-check` | Check credentials | +| `creds-defaults` | Check for default credentials | + +### Profiles + +| Profile | Description | +|---------|-------------| +| `discovery` | Host discovery only | +| `quick` | Fast scan, common ports | +| `standard` | Balanced scan | +| `thorough` | Comprehensive scan | +| `stealth` | Low and slow | +| `ad-focused` | Active Directory focused | + +### Parameters + +| Parameter | Type | Required | Description | +|-----------|------|----------|-------------| +| `action` | string | Yes | Action to perform | +| `target` | string | Yes* | Target IP/range/hostname | +| `profile` | string | No | Scan profile | +| `username` | string | No | Authentication username | +| `password` | string | No | Authentication password | +| `domain` | string | No | AD domain name | +| `ports` | string | No | Port range (e.g., "1-1000") | +| `community` | string | No | SNMP community string | + +### Examples + +``` +# Discover hosts on network +netscan action="discover" target="192.168.1.0/24" + +# Full network scan +netscan action="scan" target="192.168.1.0/24" profile="standard" + +# AD enumeration with credentials +netscan action="ad-enum" target="dc.corp.local" domain="corp.local" username="admin" password="pass123" + +# Enumerate AD users +netscan action="ad-users" target="dc.corp.local" domain="corp.local" username="admin" password="pass123" + +# SMB share enumeration +netscan action="smb-shares" target="192.168.1.10" username="admin" password="pass123" + +# DNS zone transfer attempt +netscan action="dns-zone" target="ns1.example.com" domain="example.com" + +# Password spray attack +netscan action="creds-spray" target="192.168.1.10" domain="corp.local" username="userlist.txt" password="Spring2024!" + +# SNMP enumeration +netscan action="snmp-walk" target="192.168.1.1" community="public" + +# Check default credentials +netscan action="creds-defaults" target="192.168.1.1" +``` + +--- + +## WebScan - Web Application Scanner + +Web application security scanner with crawling, vulnerability detection, and OWASP reporting. + +### Actions + +| Action | Description | +|--------|-------------| +| `crawl` | Crawl website and discover pages | +| `scan` | Run security scan with profile | +| `quick-scan` | Fast vulnerability scan | +| `full-scan` | Comprehensive security scan | +| `owasp` | Generate OWASP Top 10 report | +| `status` | Get scan status | +| `profiles` | List available profiles | + +### Profiles + +| Profile | Description | +|---------|-------------| +| `discovery` | Crawl and enumerate only | +| `quick` | Fast common vulnerability checks | +| `standard` | Balanced security scan | +| `thorough` | Deep comprehensive scan | +| `api` | API-focused testing | +| `authenticated` | With authentication | + +### Parameters + +| Parameter | Type | Required | Description | +|-----------|------|----------|-------------| +| `action` | string | Yes | Action to perform | +| `target` | string | Yes* | Target URL | +| `profile` | string | No | Scan profile | +| `maxDepth` | number | No | Max crawl depth | +| `maxPages` | number | No | Max pages to crawl | +| `headers` | object | No | Custom HTTP headers | +| `cookies` | string | No | Session cookies | +| `scanId` | string | No | Scan ID for status/owasp | + +### Examples + +``` +# Crawl website +webscan action="crawl" target="http://example.com" maxDepth=3 + +# Quick vulnerability scan +webscan action="quick-scan" target="http://example.com" + +# Full security scan +webscan action="full-scan" target="http://example.com" + +# Scan with profile +webscan action="scan" target="http://example.com" profile="thorough" + +# Authenticated scan +webscan action="scan" target="http://example.com" profile="authenticated" cookies="session=abc123" + +# Generate OWASP report +webscan action="owasp" scanId="scan_abc123" + +# Check scan status +webscan action="status" scanId="scan_abc123" +``` + +--- + +## ApiScan - API Security Scanner + +API security scanner supporting OpenAPI, GraphQL, JWT analysis, BOLA, and injection testing. + +### Actions + +| Action | Description | +|--------|-------------| +| `discover` | Discover API endpoints | +| `parse-spec` | Parse OpenAPI/GraphQL spec | +| `jwt-analyze` | Analyze JWT token security | +| `scan` | Run API security scan | +| `quick-scan` | Fast API scan | +| `full-scan` | Comprehensive API scan | +| `status` | Get scan status | +| `profiles` | List available profiles | + +### Profiles + +| Profile | Description | +|---------|-------------| +| `discovery` | Endpoint discovery only | +| `quick` | Fast common checks | +| `standard` | Balanced API testing | +| `thorough` | Deep API security scan | +| `auth-focused` | Authentication/authorization focus | + +### Parameters + +| Parameter | Type | Required | Description | +|-----------|------|----------|-------------| +| `action` | string | Yes | Action to perform | +| `target` | string | Yes* | Base API URL | +| `specUrl` | string | No | OpenAPI/GraphQL spec URL | +| `token` | string | No | Bearer token for auth | +| `profile` | string | No | Scan profile | +| `headers` | object | No | Custom headers | + +### Examples + +``` +# Discover API endpoints +apiscan action="discover" target="http://api.example.com" + +# Parse OpenAPI spec +apiscan action="parse-spec" specUrl="http://api.example.com/openapi.json" + +# Parse GraphQL schema +apiscan action="parse-spec" specUrl="http://api.example.com/graphql" + +# Analyze JWT token +apiscan action="jwt-analyze" token="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." + +# Quick API scan +apiscan action="quick-scan" target="http://api.example.com" + +# Full scan with authentication +apiscan action="full-scan" target="http://api.example.com" token="Bearer eyJ..." + +# Scan with spec +apiscan action="scan" target="http://api.example.com" specUrl="http://api.example.com/openapi.json" profile="thorough" +``` + +--- + +## CloudScan - Cloud Security Scanner + +Multi-cloud security scanner for AWS, Azure, and GCP with compliance checking. + +### Actions + +| Action | Description | +|--------|-------------| +| `discover` | Discover cloud resources | +| `scan` | Run security scan | +| `quick-scan` | Fast security scan | +| `iam-scan` | IAM-focused scan | +| `storage-scan` | Storage security scan | +| `network-scan` | Network security scan | +| `compliance` | Compliance check | +| `prowler` | Run Prowler scan (AWS) | +| `scoutsuite` | Run ScoutSuite scan | +| `prerequisites` | Check tool prerequisites | +| `status` | Get scan status | +| `profiles` | List profiles | + +### Providers + +| Provider | Auth Method | +|----------|-------------| +| `aws` | AWS CLI profile or environment | +| `azure` | Azure CLI or service principal | +| `gcp` | GCP service account or gcloud | + +### Profiles + +| Profile | Description | +|---------|-------------| +| `discovery` | Resource enumeration only | +| `quick` | Fast security checks | +| `standard` | Balanced security scan | +| `thorough` | Comprehensive scan | +| `compliance` | Compliance-focused | + +### Compliance Frameworks + +- `cis` - CIS Benchmarks +- `nist` - NIST 800-53 +- `pci-dss` - PCI DSS +- `hipaa` - HIPAA +- `soc2` - SOC 2 +- `aws-foundational-security` - AWS Foundational Security + +### Parameters + +| Parameter | Type | Required | Description | +|-----------|------|----------|-------------| +| `action` | string | Yes | Action to perform | +| `provider` | string | Yes | Cloud provider (aws/azure/gcp) | +| `profile` | string | No | Scan profile | +| `regions` | array | No | Regions to scan | +| `awsProfile` | string | No | AWS CLI profile name | +| `azureSubscription` | string | No | Azure subscription ID | +| `gcpProject` | string | No | GCP project ID | +| `frameworks` | array | No | Compliance frameworks | + +### Examples + +``` +# Discover AWS resources +cloudscan action="discover" provider="aws" regions=["us-east-1","us-west-2"] + +# Full AWS security scan +cloudscan action="scan" provider="aws" profile="standard" + +# Quick Azure scan +cloudscan action="quick-scan" provider="azure" azureSubscription="sub-123" + +# GCP IAM scan +cloudscan action="iam-scan" provider="gcp" gcpProject="my-project" + +# AWS compliance check +cloudscan action="compliance" provider="aws" frameworks=["cis","pci-dss"] + +# Run Prowler on AWS +cloudscan action="prowler" provider="aws" awsProfile="prod" + +# Run ScoutSuite +cloudscan action="scoutsuite" provider="aws" + +# Check prerequisites +cloudscan action="prerequisites" provider="aws" +``` + +--- + +## ContainerScan - Container Security Scanner + +Container and Kubernetes security scanner with image vulnerability scanning and SBOM generation. + +### Actions + +| Action | Description | +|--------|-------------| +| `discover` | Discover images, containers, registries | +| `scan` | Run security scan with profile | +| `scan-image` | Scan specific container image | +| `scan-runtime` | Analyze running containers | +| `scan-registry` | Scan images in registry | +| `scan-cluster` | Kubernetes cluster audit | +| `sbom` | Generate SBOM for image | +| `compliance` | CIS Docker/K8s benchmark | +| `status` | Get scan status | +| `profiles` | List profiles | + +### Profiles + +| Profile | Description | +|---------|-------------| +| `discovery` | Enumerate only | +| `quick` | Fast vulnerability scan | +| `standard` | Balanced scan | +| `thorough` | Comprehensive scan | +| `compliance` | Compliance focus | +| `sbom-only` | SBOM generation only | + +### External Tools Used + +- **Trivy** - Image vulnerability scanning +- **Grype** - Dependency vulnerability scanning +- **Syft** - SBOM generation +- **Kubeaudit** - Kubernetes audit + +### Parameters + +| Parameter | Type | Required | Description | +|-----------|------|----------|-------------| +| `action` | string | Yes | Action to perform | +| `image` | string | No | Container image to scan | +| `profile` | string | No | Scan profile | +| `targets` | array | No | Multiple images to scan | +| `registry` | string | No | Registry URL | +| `kubeconfig` | string | No | Kubeconfig path | +| `namespace` | string | No | Kubernetes namespace | +| `framework` | string | No | Compliance framework | + +### Examples + +``` +# Discover local images and containers +containerscan action="discover" + +# Scan specific image +containerscan action="scan-image" image="nginx:latest" + +# Scan with Trivy and Grype +containerscan action="scan-image" image="myapp:v1.0" profile="thorough" + +# Analyze running containers +containerscan action="scan-runtime" + +# Kubernetes cluster security audit +containerscan action="scan-cluster" + +# Scan specific namespace +containerscan action="scan-cluster" namespace="production" + +# Generate SBOM +containerscan action="sbom" image="nginx:latest" + +# CIS Docker benchmark +containerscan action="compliance" framework="cis-docker" + +# CIS Kubernetes benchmark +containerscan action="compliance" framework="cis-kubernetes" + +# Full scan multiple images +containerscan action="scan" profile="thorough" targets=["nginx:latest","redis:7","postgres:15"] + +# Scan registry +containerscan action="scan-registry" registry="registry.example.com" +``` + +--- + +## CVE - CVE Lookup Tool + +CVE database lookup with NVD, OSV, and CISA KEV integration. + +### Actions + +| Action | Description | +|--------|-------------| +| `lookup` | Look up single CVE | +| `bulk-lookup` | Look up multiple CVEs | +| `search` | Search CVEs by keyword | +| `kev-check` | Check if CVEs are in CISA KEV | +| `enrich-findings` | Enrich findings with CVE data | + +### Data Sources + +- **NVD** - NIST National Vulnerability Database +- **OSV** - Open Source Vulnerabilities +- **CISA KEV** - Known Exploited Vulnerabilities + +### Parameters + +| Parameter | Type | Required | Description | +|-----------|------|----------|-------------| +| `action` | string | Yes | Action to perform | +| `cveId` | string | No | Single CVE ID | +| `cveIds` | array | No | Multiple CVE IDs | +| `keyword` | string | No | Search keyword | +| `product` | string | No | Product name for search | +| `vendor` | string | No | Vendor name for search | + +### Examples + +``` +# Lookup single CVE +cve action="lookup" cveId="CVE-2021-44228" + +# Bulk lookup multiple CVEs +cve action="bulk-lookup" cveIds=["CVE-2021-44228","CVE-2023-4911","CVE-2024-3094"] + +# Search by keyword +cve action="search" keyword="log4j" + +# Search by product +cve action="search" product="apache" vendor="apache" + +# Check if CVEs are in CISA KEV (actively exploited) +cve action="kev-check" cveIds=["CVE-2021-44228","CVE-2023-4911"] + +# Enrich findings with CVE data +cve action="enrich-findings" cveIds=["CVE-2021-44228","CVE-2023-4911"] +``` + +### Response Data + +CVE lookup returns: +- CVSS v2/v3 scores and vectors +- Severity rating +- Description +- CWE IDs +- References +- Affected products/versions +- CISA KEV status +- Public exploit availability + +--- + +## Exploits - Exploit Search Tool + +Search and manage exploits from ExploitDB and Metasploit. + +### Actions + +| Action | Description | +|--------|-------------| +| `search` | Search for exploits | +| `suggest` | Suggest exploits for a finding | +| `info` | Get exploit details | +| `check` | Check if target is vulnerable | +| `execute` | Execute exploit (with confirmation) | + +### Parameters + +| Parameter | Type | Required | Description | +|-----------|------|----------|-------------| +| `action` | string | Yes | Action to perform | +| `query` | string | No | Search query | +| `findingId` | string | No | Finding ID for suggestions | +| `module` | string | No | Exploit module path | +| `target` | string | No | Target for check/execute | +| `dryRun` | boolean | No | Simulate execution | +| `options` | object | No | Exploit options (RHOSTS, LHOST, etc.) | + +### Examples + +``` +# Search for Apache exploits +exploits action="search" query="apache 2.4" + +# Search for specific CVE +exploits action="search" query="CVE-2021-44228" + +# Suggest exploits for a finding +exploits action="suggest" findingId="finding_abc123" + +# Get exploit details +exploits action="info" module="exploit/linux/http/apache_mod_cgi_bash_env_exec" + +# Check if target is vulnerable +exploits action="check" module="exploit/linux/http/apache_mod_cgi_bash_env_exec" target="192.168.1.10" + +# Execute exploit (dry run) +exploits action="execute" module="exploit/linux/http/apache_mod_cgi_bash_env_exec" target="192.168.1.10" dryRun=true + +# Execute exploit (requires confirmation) +exploits action="execute" module="exploit/linux/http/apache_mod_cgi_bash_env_exec" target="192.168.1.10" options={"RHOSTS":"192.168.1.10","LHOST":"192.168.1.5"} +``` + +--- + +## Monitor - Continuous Monitoring + +Create and manage scheduled security scans with alerting. + +### Actions + +| Action | Description | +|--------|-------------| +| `create` | Create new monitor | +| `list` | List all monitors | +| `get` | Get monitor details | +| `pause` | Pause a monitor | +| `resume` | Resume a monitor | +| `delete` | Delete a monitor | +| `trigger` | Trigger immediate scan | +| `status` | Get scheduler status | + +### Schedule Types + +| Type | Description | +|------|-------------| +| `interval` | Run every N milliseconds | +| `cron` | Cron expression schedule | + +### Parameters + +| Parameter | Type | Required | Description | +|-----------|------|----------|-------------| +| `action` | string | Yes | Action to perform | +| `monitorID` | string | No | Monitor ID for operations | +| `name` | string | No | Monitor name (for create) | +| `description` | string | No | Monitor description | +| `targets` | array | No | Targets to scan | +| `tools` | array | No | Tools to run | +| `scheduleType` | string | No | "interval" or "cron" | +| `intervalMs` | number | No | Interval in milliseconds | +| `cronExpression` | string | No | Cron expression | +| `alertMinSeverity` | string | No | Min severity for alerts | + +### Examples + +``` +# Create daily nmap scan (every 24 hours) +monitor action="create" name="Daily Port Scan" targets=["192.168.1.0/24"] tools=[{"tool":"nmap","args":"-sV"}] scheduleType="interval" intervalMs=86400000 + +# Create vulnerability scan every 6 hours via cron +monitor action="create" name="Vuln Scan" targets=["https://example.com"] tools=[{"tool":"nuclei","args":"-t cves/"}] scheduleType="cron" cronExpression="0 */6 * * *" + +# Create weekly full scan +monitor action="create" name="Weekly Full Scan" targets=["192.168.1.0/24"] tools=[{"tool":"nmap"},{"tool":"nikto"}] scheduleType="cron" cronExpression="0 2 * * 0" alertMinSeverity="medium" + +# List all monitors +monitor action="list" + +# Get monitor details +monitor action="get" monitorID="mon_abc123" + +# Pause a monitor +monitor action="pause" monitorID="mon_abc123" + +# Resume a monitor +monitor action="resume" monitorID="mon_abc123" + +# Trigger immediate scan +monitor action="trigger" monitorID="mon_abc123" + +# Delete a monitor +monitor action="delete" monitorID="mon_abc123" + +# Get scheduler status +monitor action="status" +``` + +### Common Cron Expressions + +| Expression | Description | +|------------|-------------| +| `0 * * * *` | Every hour | +| `0 */6 * * *` | Every 6 hours | +| `0 0 * * *` | Daily at midnight | +| `0 2 * * 0` | Weekly Sunday 2am | +| `0 0 1 * *` | Monthly 1st at midnight | + +--- + +## Report - Report Generation + +Generate security assessment reports in various formats. + +### Report Types + +| Type | Description | +|------|-------------| +| `executive` | High-level summary for management | +| `technical` | Detailed with evidence and remediation | +| `compliance` | Formatted for compliance requirements | +| `full` | Complete report with all data | + +### Output Formats + +| Format | Description | +|--------|-------------| +| `markdown` | Markdown format | +| `html` | HTML format | +| `json` | JSON data export | + +### Parameters + +| Parameter | Type | Required | Description | +|-----------|------|----------|-------------| +| `type` | string | No | Report type (default: full) | +| `format` | string | No | Output format (default: markdown) | +| `title` | string | No | Report title | +| `sessionId` | string | No | Filter by session | +| `scanId` | string | No | Filter by scan | +| `minSeverity` | string | No | Minimum severity to include | +| `outputFile` | string | No | Save to file path | + +### Examples + +``` +# Generate executive summary in HTML +report type="executive" format="html" + +# Full technical report in markdown +report type="technical" format="markdown" + +# Compliance report +report type="compliance" format="html" title="Q1 2024 Security Assessment" + +# Export findings as JSON +report format="json" outputFile="/tmp/findings.json" + +# Report for specific session +report type="full" sessionId="session_abc123" + +# Report with severity filter +report type="technical" minSeverity="high" + +# Save HTML report to file +report type="full" format="html" outputFile="/tmp/security_report.html" +``` + +--- + +## Common Patterns + +### Sequential Workflow + +``` +# 1. Discover targets +netscan action="discover" target="192.168.1.0/24" + +# 2. Scan discovered hosts +netscan action="scan" target="192.168.1.0/24" profile="standard" + +# 3. Deep dive on interesting hosts +sectools tool="nmap" target="192.168.1.10" args="-sV -sC -A" + +# 4. Web scan if web services found +webscan action="full-scan" target="http://192.168.1.10" + +# 5. Check for known CVEs +cve action="search" keyword="apache 2.4.49" + +# 6. Generate report +report type="technical" format="html" +``` + +### Cloud Security Assessment + +``` +# 1. Check prerequisites +cloudscan action="prerequisites" provider="aws" + +# 2. Discover resources +cloudscan action="discover" provider="aws" regions=["us-east-1"] + +# 3. Run security scan +cloudscan action="scan" provider="aws" profile="thorough" + +# 4. Compliance check +cloudscan action="compliance" provider="aws" frameworks=["cis","pci-dss"] + +# 5. Generate report +report type="compliance" format="html" +``` + +### Container Security Pipeline + +``` +# 1. Scan image before deployment +containerscan action="scan-image" image="myapp:v1.0" + +# 2. Generate SBOM +containerscan action="sbom" image="myapp:v1.0" + +# 3. Check runtime security +containerscan action="scan-runtime" + +# 4. Kubernetes audit +containerscan action="scan-cluster" + +# 5. Compliance check +containerscan action="compliance" framework="cis-kubernetes" +``` + +### Continuous Monitoring Setup + +``` +# Create monitors for critical systems +monitor action="create" name="Prod Web Scan" targets=["https://prod.example.com"] tools=[{"tool":"nuclei"}] scheduleType="cron" cronExpression="0 */4 * * *" alertMinSeverity="medium" + +monitor action="create" name="Infra Port Scan" targets=["10.0.0.0/24"] tools=[{"tool":"nmap","args":"-sV -F"}] scheduleType="interval" intervalMs=86400000 + +# Check status +monitor action="status" +``` + +--- + +## Severity Levels + +All tools use consistent severity levels: + +| Level | Description | +|-------|-------------| +| `critical` | Immediate exploitation risk | +| `high` | Serious vulnerability | +| `medium` | Moderate risk | +| `low` | Minor issue | +| `info` | Informational finding | + +--- + +## Notes + +- All tools automatically create findings in the session +- Use `createFindings=false` to disable finding creation +- Results are persisted and can be retrieved later +- Use profiles to balance speed vs thoroughness +- External tools (nmap, nuclei, etc.) must be installed separately +- Cloud scans require appropriate CLI tools and credentials configured diff --git a/docs/USAGE.md b/docs/USAGE.md new file mode 100644 index 00000000000..739505b7b50 --- /dev/null +++ b/docs/USAGE.md @@ -0,0 +1,216 @@ +# Cyxwiz - Usage Guide + +Quick reference for development and running the project. + +--- + +## Prerequisites + +- **Bun** (v1.3.6+) +- **Git** +- **GitHub CLI** (gh) + +--- + +## Initial Setup (Already Done) + +```bash +# Install Bun +curl -fsSL https://bun.sh/install | bash +export PATH="$HOME/.bun/bin:$PATH" + +# Clone the fork +gh repo clone code3hr/opencode /home/mrcj/Desktop/wiz + +# Install dependencies +cd /home/mrcj/Desktop/wiz +bun install + +# Build +cd packages/opencode +bun run build +``` + +--- + +## Running OpenCode (Dev Mode) + +```bash +# Always set PATH first +export PATH="$HOME/.bun/bin:$PATH" + +# Navigate to project +cd /home/mrcj/Desktop/wiz + +# Run TUI +bun run --cwd packages/opencode src/index.ts + +# Run with a specific command +bun run --cwd packages/opencode src/index.ts --help +bun run --cwd packages/opencode src/index.ts --version + +# Run with a message (non-interactive) +bun run --cwd packages/opencode src/index.ts run "your message here" + +# Start headless server +bun run --cwd packages/opencode src/index.ts serve + +# Start web interface +bun run --cwd packages/opencode src/index.ts web +``` + +--- + +## Project Structure + +``` +/home/mrcj/Desktop/wiz/ +├── packages/ +│ ├── opencode/ # Core CLI/TUI (main focus) +│ │ ├── src/ +│ │ │ ├── tool/ # Tool definitions +│ │ │ ├── plugin/ # Plugin system +│ │ │ ├── agent/ # Agent definitions +│ │ │ ├── session/ # Session management +│ │ │ └── ... +│ │ └── bin/ +│ ├── plugin/ # Plugin SDK (@opencode-ai/plugin) +│ ├── sdk/ # Client SDK (@opencode-ai/sdk) +│ ├── console/ # Console app +│ ├── desktop/ # Desktop app +│ └── web/ # Web interface +├── PROJECT.md # Full specification +├── CLAUDE.md # AI context file +├── USAGE.md # This file +└── README.md # OpenCode readme +``` + +--- + +## Key Files for Cyxwiz Development + +| File | Purpose | +|------|---------| +| `packages/opencode/src/tool/tool.ts` | Base tool definition | +| `packages/opencode/src/tool/bash.ts` | Bash command execution | +| `packages/opencode/src/plugin/index.ts` | Plugin loader | +| `packages/plugin/src/index.ts` | Hook definitions (lines 176-187) | +| `packages/opencode/src/agent/` | Agent configurations | +| `packages/opencode/src/config/` | Configuration system | + +--- + +## Git Workflow + +```bash +# Always use bun in PATH for hooks +export PATH="$HOME/.bun/bin:$PATH" + +# Check status +cd /home/mrcj/Desktop/wiz +git status + +# Commit changes +git add . +git commit -m "Your message" + +# Push to your fork +git push origin dev + +# Pull latest from upstream (original OpenCode) +git fetch upstream +git merge upstream/dev +``` + +--- + +## Development Commands + +```bash +# From project root +cd /home/mrcj/Desktop/wiz + +# Install dependencies +bun install + +# Type check all packages +bun run typecheck + +# Build opencode package +cd packages/opencode +bun run build + +# Run tests (in opencode package) +bun test + +# Run dev mode +bun run dev +``` + +--- + +## Adding Governance (Phase 2) + +Location for new governance module: +``` +packages/opencode/src/governance/ +├── index.ts # Main exports +├── scope.ts # Scope checking +├── policy.ts # Policy enforcement +├── audit.ts # Audit logging +└── types.ts # TypeScript types +``` + +Hook integration point: +```typescript +// packages/plugin/src/index.ts (lines 176-187) + +"tool.execute.before"?: ( + input: { tool: string; sessionID: string; callID: string }, + output: { args: any }, +) => Promise + +"tool.execute.after"?: ( + input: { tool: string; sessionID: string; callID: string }, + output: { title: string; output: string; metadata: any }, +) => Promise +``` + +--- + +## Troubleshooting + +### "bun: command not found" +```bash +export PATH="$HOME/.bun/bin:$PATH" +``` + +### Pre-push hook fails +```bash +# Run with bun in PATH +export PATH="$HOME/.bun/bin:$PATH" +git push origin dev +``` + +### Permission denied +```bash +# If needed, fix permissions +chmod +x packages/opencode/bin/opencode +``` + +--- + +## Quick Reference + +```bash +# One-liner to start dev +export PATH="$HOME/.bun/bin:$PATH" && cd /home/mrcj/Desktop/wiz && bun run --cwd packages/opencode src/index.ts +``` + +--- + +## Links + +- **Fork:** https://github.com/code3hr/opencode +- **Upstream:** https://github.com/anomalyco/opencode +- **OpenCode Docs:** https://opencode.ai/docs/ diff --git a/package.json b/package.json index 9aa069d52cc..0f13d67d025 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "$schema": "https://json.schemastore.org/package.json", - "name": "opencode", + "name": "cyxwiz", "description": "AI-powered development tool", "private": true, "type": "module", @@ -77,7 +77,7 @@ }, "repository": { "type": "git", - "url": "https://github.com/anomalyco/opencode" + "url": "https://github.com/code3hr/opencode" }, "license": "MIT", "prettier": { diff --git a/packages/opencode/bin/opencode b/packages/opencode/bin/cyxwiz similarity index 86% rename from packages/opencode/bin/opencode rename to packages/opencode/bin/cyxwiz index e35cc00944d..00a75805ef3 100755 --- a/packages/opencode/bin/opencode +++ b/packages/opencode/bin/cyxwiz @@ -17,7 +17,7 @@ function run(target) { process.exit(code) } -const envPath = process.env.OPENCODE_BIN_PATH +const envPath = process.env.CYXWIZ_BIN_PATH if (envPath) { run(envPath) } @@ -44,8 +44,8 @@ let arch = archMap[os.arch()] if (!arch) { arch = os.arch() } -const base = "opencode-" + platform + "-" + arch -const binary = platform === "windows" ? "opencode.exe" : "opencode" +const base = "cyxwiz-" + platform + "-" + arch +const binary = platform === "windows" ? "cyxwiz.exe" : "cyxwiz" function findBinary(startDir) { let current = startDir @@ -74,7 +74,7 @@ function findBinary(startDir) { const resolved = findBinary(scriptDir) if (!resolved) { console.error( - 'It seems that your package manager failed to install the right version of the opencode CLI for your platform. You can try manually installing the "' + + 'It seems that your package manager failed to install the right version of the cyxwiz CLI for your platform. You can try manually installing the "' + base + '" package', ) diff --git a/packages/opencode/package.json b/packages/opencode/package.json index b2d5a8c7ba7..7af2ba43e94 100644 --- a/packages/opencode/package.json +++ b/packages/opencode/package.json @@ -1,7 +1,7 @@ { "$schema": "https://json.schemastore.org/package.json", "version": "1.1.21", - "name": "opencode", + "name": "cyxwiz", "type": "module", "license": "MIT", "private": true, @@ -18,7 +18,7 @@ "deploy": "echo 'Deploying application...' && bun run build && echo 'Deployment completed successfully'" }, "bin": { - "opencode": "./bin/opencode" + "cyxwiz": "./bin/cyxwiz" }, "exports": { "./*": "./src/*.ts" @@ -98,6 +98,7 @@ "decimal.js": "10.5.0", "diff": "catalog:", "fuzzysort": "3.1.0", + "glob": "10.4.5", "gray-matter": "4.0.3", "hono": "catalog:", "hono-openapi": "catalog:", @@ -116,6 +117,7 @@ "vscode-jsonrpc": "8.2.1", "web-tree-sitter": "0.25.10", "xdg-basedir": "5.1.0", + "yaml": "2.7.0", "yargs": "18.0.0", "zod": "catalog:", "zod-to-json-schema": "3.24.5" diff --git a/packages/opencode/src/agent/agent.ts b/packages/opencode/src/agent/agent.ts index 64875091916..2a796549c22 100644 --- a/packages/opencode/src/agent/agent.ts +++ b/packages/opencode/src/agent/agent.ts @@ -11,6 +11,7 @@ import PROMPT_COMPACTION from "./prompt/compaction.txt" import PROMPT_EXPLORE from "./prompt/explore.txt" import PROMPT_SUMMARY from "./prompt/summary.txt" import PROMPT_TITLE from "./prompt/title.txt" +import PROMPT_PENTEST from "../pentest/prompt/pentest.txt" import { PermissionNext } from "@/permission/next" import { mergeDeep, pipe, sortBy, values } from "remeda" import { Global } from "@/global" @@ -192,6 +193,82 @@ export namespace Agent { ), prompt: PROMPT_SUMMARY, }, + pentest: { + name: "pentest", + description: `Security testing specialist for penetration testing and vulnerability assessment. Use this agent to scan networks, identify open ports and services, discover security issues, and get remediation recommendations. Supports nmap, nikto, dirb, gobuster, sqlmap, nuclei, and other security tools with governance scope enforcement.`, + permission: PermissionNext.merge( + defaults, + PermissionNext.fromConfig({ + "*": "deny", + nmap: "allow", + sectools: "allow", + bash: { + // Network reconnaissance + "nmap *": "allow", + "ping *": "allow", + "traceroute *": "allow", + "host *": "allow", + "dig *": "allow", + "whois *": "allow", + "nc *": "allow", + "netcat *": "allow", + "ncat *": "allow", + "masscan *": "allow", + // Web scanning + "nikto *": "allow", + "dirb *": "allow", + "gobuster *": "allow", + "ffuf *": "allow", + "wpscan *": "allow", + "whatweb *": "allow", + "wafw00f *": "allow", + // Vulnerability scanning + "nuclei *": "allow", + "searchsploit *": "allow", + // SQL injection + "sqlmap *": "allow", + // SMB/Windows + "enum4linux *": "allow", + "smbclient *": "allow", + "rpcclient *": "allow", + "crackmapexec *": "allow", + "impacket-* *": "allow", + // SSL/TLS + "sslscan *": "allow", + "sslyze *": "allow", + "testssl *": "allow", + // DNS + "dnsenum *": "allow", + "dnsrecon *": "allow", + "fierce *": "allow", + // Other utilities + "curl *": "allow", + "wget *": "allow", + "hashcat *": "deny", // Password cracking - too risky + "john *": "deny", // Password cracking - too risky + "hydra *": "deny", // Brute force - too risky without explicit approval + "*": "ask", + }, + read: "allow", + grep: "allow", + glob: "allow", + webfetch: "allow", + websearch: "allow", + todoread: "deny", + todowrite: "deny", + external_directory: { + [Truncate.DIR]: "allow", + [Truncate.GLOB]: "allow", + }, + }), + user, + ), + prompt: PROMPT_PENTEST, + options: {}, + mode: "subagent", + native: true, + temperature: 0.3, + }, } for (const [key, value] of Object.entries(cfg.agent ?? {})) { diff --git a/packages/opencode/src/cli/cmd/mcp.ts b/packages/opencode/src/cli/cmd/mcp.ts index cdd741fbc75..7e0b46104e8 100644 --- a/packages/opencode/src/cli/cmd/mcp.ts +++ b/packages/opencode/src/cli/cmd/mcp.ts @@ -83,7 +83,7 @@ export const McpListCommand = cmd({ if (servers.length === 0) { prompts.log.warn("No MCP servers configured") - prompts.outro("Add servers with: opencode mcp add") + prompts.outro("Add servers with: cyxwiz mcp add") return } @@ -469,7 +469,7 @@ export const McpAddCommand = cmd({ if (type === "local") { const command = await prompts.text({ message: "Enter command to run", - placeholder: "e.g., opencode x @modelcontextprotocol/server-filesystem", + placeholder: "e.g., cyxwiz x @modelcontextprotocol/server-filesystem", validate: (x) => (x && x.length > 0 ? undefined : "Required"), }) if (prompts.isCancel(command)) throw new UI.CancelledError() diff --git a/packages/opencode/src/cli/cmd/pr.ts b/packages/opencode/src/cli/cmd/pr.ts index d6176572002..522dbbfd923 100644 --- a/packages/opencode/src/cli/cmd/pr.ts +++ b/packages/opencode/src/cli/cmd/pr.ts @@ -5,7 +5,7 @@ import { $ } from "bun" export const PrCommand = cmd({ command: "pr ", - describe: "fetch and checkout a GitHub PR branch, then run opencode", + describe: "fetch and checkout a GitHub PR branch, then run cyxwiz", builder: (yargs) => yargs.positional("number", { type: "number", @@ -63,15 +63,15 @@ export const PrCommand = cmd({ await $`git branch --set-upstream-to=${remoteName}/${headRefName} ${localBranchName}`.nothrow() } - // Check for opencode session link in PR body + // Check for cyxwiz session link in PR body if (prInfo && prInfo.body) { const sessionMatch = prInfo.body.match(/https:\/\/opncd\.ai\/s\/([a-zA-Z0-9_-]+)/) if (sessionMatch) { const sessionUrl = sessionMatch[0] - UI.println(`Found opencode session: ${sessionUrl}`) + UI.println(`Found cyxwiz session: ${sessionUrl}`) UI.println(`Importing session...`) - const importResult = await $`opencode import ${sessionUrl}`.nothrow() + const importResult = await $`cyxwiz import ${sessionUrl}`.nothrow() if (importResult.exitCode === 0) { const importOutput = importResult.text().trim() // Extract session ID from the output (format: "Imported session: ") @@ -88,23 +88,23 @@ export const PrCommand = cmd({ UI.println(`Successfully checked out PR #${prNumber} as branch '${localBranchName}'`) UI.println() - UI.println("Starting opencode...") + UI.println("Starting cyxwiz...") UI.println() - // Launch opencode TUI with session ID if available + // Launch cyxwiz TUI with session ID if available const { spawn } = await import("child_process") - const opencodeArgs = sessionId ? ["-s", sessionId] : [] - const opencodeProcess = spawn("opencode", opencodeArgs, { + const cyxwizArgs = sessionId ? ["-s", sessionId] : [] + const cyxwizProcess = spawn("cyxwiz", cyxwizArgs, { stdio: "inherit", cwd: process.cwd(), }) await new Promise((resolve, reject) => { - opencodeProcess.on("exit", (code) => { + cyxwizProcess.on("exit", (code) => { if (code === 0) resolve() - else reject(new Error(`opencode exited with code ${code}`)) + else reject(new Error(`cyxwiz exited with code ${code}`)) }) - opencodeProcess.on("error", reject) + cyxwizProcess.on("error", reject) }) }, }) diff --git a/packages/opencode/src/cli/cmd/run.ts b/packages/opencode/src/cli/cmd/run.ts index 54248f96f3d..48f7b8e3519 100644 --- a/packages/opencode/src/cli/cmd/run.ts +++ b/packages/opencode/src/cli/cmd/run.ts @@ -27,7 +27,7 @@ const TOOL: Record = { export const RunCommand = cmd({ command: "run [message..]", - describe: "run opencode with a message", + describe: "run cyxwiz with a message", builder: (yargs: Argv) => { return yargs .positional("message", { @@ -81,7 +81,7 @@ export const RunCommand = cmd({ }) .option("attach", { type: "string", - describe: "attach to a running opencode server (e.g., http://localhost:4096)", + describe: "attach to a running cyxwiz server (e.g., http://localhost:4096)", }) .option("port", { type: "number", diff --git a/packages/opencode/src/cli/cmd/serve.ts b/packages/opencode/src/cli/cmd/serve.ts index bee2c8f711f..4ac4ad8721a 100644 --- a/packages/opencode/src/cli/cmd/serve.ts +++ b/packages/opencode/src/cli/cmd/serve.ts @@ -6,14 +6,14 @@ import { Flag } from "../../flag/flag" export const ServeCommand = cmd({ command: "serve", builder: (yargs) => withNetworkOptions(yargs), - describe: "starts a headless opencode server", + describe: "starts a headless cyxwiz server", handler: async (args) => { if (!Flag.OPENCODE_SERVER_PASSWORD) { console.log("Warning: OPENCODE_SERVER_PASSWORD is not set; server is unsecured.") } const opts = await resolveNetworkOptions(args) const server = Server.listen(opts) - console.log(`opencode server listening on http://${server.hostname}:${server.port}`) + console.log(`cyxwiz server listening on http://${server.hostname}:${server.port}`) await new Promise(() => {}) await server.stop() }, diff --git a/packages/opencode/src/cli/cmd/tui/app.tsx b/packages/opencode/src/cli/cmd/tui/app.tsx index 1fea3f4b305..162fce184a5 100644 --- a/packages/opencode/src/cli/cmd/tui/app.tsx +++ b/packages/opencode/src/cli/cmd/tui/app.tsx @@ -221,20 +221,20 @@ function App() { if (!terminalTitleEnabled() || Flag.OPENCODE_DISABLE_TERMINAL_TITLE) return if (route.data.type === "home") { - renderer.setTerminalTitle("OpenCode") + renderer.setTerminalTitle("Cyxwiz") return } if (route.data.type === "session") { const session = sync.session.get(route.data.sessionID) if (!session || SessionApi.isDefaultTitle(session.title)) { - renderer.setTerminalTitle("OpenCode") + renderer.setTerminalTitle("Cyxwiz") return } // Truncate title to 40 chars max const title = session.title.length > 40 ? session.title.slice(0, 37) + "..." : session.title - renderer.setTerminalTitle(`OC | ${title}`) + renderer.setTerminalTitle(`Cyxwiz | ${title}`) } }) diff --git a/packages/opencode/src/cli/cmd/tui/attach.ts b/packages/opencode/src/cli/cmd/tui/attach.ts index 3f9285f631c..d885c56ccd7 100644 --- a/packages/opencode/src/cli/cmd/tui/attach.ts +++ b/packages/opencode/src/cli/cmd/tui/attach.ts @@ -3,7 +3,7 @@ import { tui } from "./app" export const AttachCommand = cmd({ command: "attach ", - describe: "attach to a running opencode server", + describe: "attach to a running cyxwiz server", builder: (yargs) => yargs .positional("url", { diff --git a/packages/opencode/src/cli/cmd/tui/component/logo.tsx b/packages/opencode/src/cli/cmd/tui/component/logo.tsx index 771962b75d1..15e2c5fc685 100644 --- a/packages/opencode/src/cli/cmd/tui/component/logo.tsx +++ b/packages/opencode/src/cli/cmd/tui/component/logo.tsx @@ -1,85 +1,39 @@ -import { TextAttributes, RGBA } from "@opentui/core" -import { For, type JSX } from "solid-js" -import { useTheme, tint } from "@tui/context/theme" - -// Shadow markers (rendered chars in parens): -// _ = full shadow cell (space with bg=shadow) -// ^ = letter top, shadow bottom (▀ with fg=letter, bg=shadow) -// ~ = shadow top only (▀ with fg=shadow) -const SHADOW_MARKER = /[_^~]/ - -const LOGO_LEFT = [` `, `█▀▀█ █▀▀█ █▀▀█ █▀▀▄`, `█__█ █__█ █^^^ █__█`, `▀▀▀▀ █▀▀▀ ▀▀▀▀ ▀~~▀`] - -const LOGO_RIGHT = [` ▄ `, `█▀▀▀ █▀▀█ █▀▀█ █▀▀█`, `█___ █__█ █__█ █^^^`, `▀▀▀▀ ▀▀▀▀ ▀▀▀▀ ▀▀▀▀`] +import { TextAttributes } from "@opentui/core" +import { For } from "solid-js" +import { useTheme } from "@tui/context/theme" + +const LOGO_LEFT = [ + ` _____ ____ __ `, + ` / __\\ \\ / /\\ \\/ / `, + `| (__ \\ V / > < `, + ` \\___| |_| /_/\\_\\ `, +] + +const LOGO_RIGHT = [ + `__ _____ ____`, + `\\ \\ / /_ _|_ /`, + ` \\ \\/\\/ / | | / / `, + ` \\_/\\_/ |___/___|`, +] export function Logo() { const { theme } = useTheme() - const renderLine = (line: string, fg: RGBA, bold: boolean): JSX.Element[] => { - const shadow = tint(theme.background, fg, 0.25) - const attrs = bold ? TextAttributes.BOLD : undefined - const elements: JSX.Element[] = [] - let i = 0 - - while (i < line.length) { - const rest = line.slice(i) - const markerIndex = rest.search(SHADOW_MARKER) - - if (markerIndex === -1) { - elements.push( - - {rest} - , - ) - break - } - - if (markerIndex > 0) { - elements.push( - - {rest.slice(0, markerIndex)} - , - ) - } - - const marker = rest[markerIndex] - switch (marker) { - case "_": - elements.push( - - {" "} - , - ) - break - case "^": - elements.push( - - ▀ - , - ) - break - case "~": - elements.push( - - ▀ - , - ) - break - } - - i += markerIndex + 1 - } - - return elements - } - return ( {(line, index) => ( - {renderLine(line, theme.textMuted, false)} - {renderLine(LOGO_RIGHT[index()], theme.text, true)} + + + {line} + + + + + {LOGO_RIGHT[index()]} + + )} diff --git a/packages/opencode/src/cli/cmd/tui/component/prompt/index.tsx b/packages/opencode/src/cli/cmd/tui/component/prompt/index.tsx index 9ad85d08f0e..b3efdf4cc72 100644 --- a/packages/opencode/src/cli/cmd/tui/component/prompt/index.tsx +++ b/packages/opencode/src/cli/cmd/tui/component/prompt/index.tsx @@ -51,7 +51,7 @@ export type PromptRef = { submit(): void } -const PLACEHOLDERS = ["Fix a TODO in the codebase", "What is the tech stack of this project?", "Fix broken tests"] +const PLACEHOLDERS = ["Scan this project for vulnerabilities", "Audit the authentication flow", "Check for OWASP top 10 issues"] export function Prompt(props: PromptProps) { let input: TextareaRenderable @@ -760,7 +760,7 @@ export function Prompt(props: PromptProps) { flexGrow={1} > + + + ` + const forms = WebCrawler.extractForms(html, "http://example.com") + + expect(forms[0].inputs.some((i) => i.name === "message" && i.type === "textarea")).toBe(true) + expect(forms[0].inputs.some((i) => i.name === "category" && i.type === "select")).toBe(true) + }) + }) +}) + +describe("ScanProfiles", () => { + test("has all required profiles", () => { + expect(ScanProfiles.all).toHaveLength(5) + expect(ScanProfiles.get("quick")).toBeDefined() + expect(ScanProfiles.get("standard")).toBeDefined() + expect(ScanProfiles.get("thorough")).toBeDefined() + expect(ScanProfiles.get("passive")).toBeDefined() + expect(ScanProfiles.get("custom")).toBeDefined() + }) + + test("quick profile has correct configuration", () => { + const quick = ScanProfiles.get("quick") + + expect(quick.crawl.enabled).toBe(true) + expect(quick.crawl.maxDepth).toBe(1) + expect(quick.crawl.maxUrls).toBe(50) + expect(quick.tools).toContain("whatweb") + expect(quick.tools).toContain("nikto") + }) + + test("passive profile disables crawling", () => { + const passive = ScanProfiles.get("passive") + + expect(passive.crawl.enabled).toBe(false) + expect(passive.tools).toContain("whatweb") + expect(passive.tools).toContain("wafw00f") + }) + + test("createCustom merges options", () => { + const custom = ScanProfiles.createCustom({ + crawl: { maxDepth: 5 }, + tools: ["nikto", "nuclei"], + }) + + expect(custom.id).toBe("custom") + expect(custom.crawl.maxDepth).toBe(5) + expect(custom.crawl.enabled).toBe(true) // From default + expect(custom.tools).toEqual(["nikto", "nuclei"]) + }) + + test("list returns formatted string", () => { + const list = ScanProfiles.list() + + expect(list).toContain("quick") + expect(list).toContain("standard") + expect(list).toContain("thorough") + expect(list).toContain("passive") + }) +}) + +describe("WebScanStorage", () => { + beforeEach(() => { + WebScanStorage.clearMemory() + }) + + afterEach(() => { + WebScanStorage.clearMemory() + }) + + describe("crawl operations", () => { + test("saves and retrieves crawl", async () => { + const crawl: Omit = { + target: "http://example.com", + urls: [ + { + url: "http://example.com/", + method: "GET", + statusCode: 200, + depth: 0, + discoveredAt: Date.now(), + }, + ], + forms: [], + stats: { + urlsDiscovered: 1, + urlsVisited: 1, + formsDiscovered: 0, + maxDepthReached: 0, + errorCount: 0, + duration: 1000, + }, + options: { maxDepth: 2, maxUrls: 100 } as WebScanTypes.CrawlOptions, + startedAt: Date.now(), + completedAt: Date.now(), + status: "completed", + } + + const saved = await WebScanStorage.saveCrawl(crawl, { storage: "memory" }) + expect(saved.id).toMatch(/^crawl_/) + + const retrieved = await WebScanStorage.getCrawl(saved.id, { storage: "memory" }) + expect(retrieved).not.toBeNull() + expect(retrieved!.target).toBe("http://example.com") + }) + + test("lists crawls with filters", async () => { + const crawl1: Omit = { + target: "http://example1.com", + urls: [], + forms: [], + stats: { + urlsDiscovered: 0, + urlsVisited: 0, + formsDiscovered: 0, + maxDepthReached: 0, + errorCount: 0, + duration: 0, + }, + options: {} as WebScanTypes.CrawlOptions, + startedAt: Date.now(), + status: "completed", + } + + const crawl2: Omit = { + target: "http://example2.com", + urls: [], + forms: [], + stats: { + urlsDiscovered: 0, + urlsVisited: 0, + formsDiscovered: 0, + maxDepthReached: 0, + errorCount: 0, + duration: 0, + }, + options: {} as WebScanTypes.CrawlOptions, + startedAt: Date.now() + 1000, + status: "failed", + } + + await WebScanStorage.saveCrawl(crawl1, { storage: "memory" }) + await WebScanStorage.saveCrawl(crawl2, { storage: "memory" }) + + const all = await WebScanStorage.listCrawls({ storage: "memory" }) + expect(all).toHaveLength(2) + + const completed = await WebScanStorage.listCrawls({ storage: "memory" }, { status: "completed" }) + expect(completed).toHaveLength(1) + expect(completed[0].target).toBe("http://example1.com") + }) + + test("deletes crawl", async () => { + const crawl: Omit = { + target: "http://example.com", + urls: [], + forms: [], + stats: { + urlsDiscovered: 0, + urlsVisited: 0, + formsDiscovered: 0, + maxDepthReached: 0, + errorCount: 0, + duration: 0, + }, + options: {} as WebScanTypes.CrawlOptions, + startedAt: Date.now(), + status: "completed", + } + + const saved = await WebScanStorage.saveCrawl(crawl, { storage: "memory" }) + const deleted = await WebScanStorage.deleteCrawl(saved.id, { storage: "memory" }) + expect(deleted).toBe(true) + + const retrieved = await WebScanStorage.getCrawl(saved.id, { storage: "memory" }) + expect(retrieved).toBeNull() + }) + }) + + describe("scan operations", () => { + test("saves and retrieves scan", async () => { + const scan: Omit = { + target: "http://example.com", + profile: "standard", + tools: [{ tool: "nikto", status: "completed", findingsCount: 5 }], + findings: ["finding_1", "finding_2"], + stats: { + urlsScanned: 10, + toolsRun: 1, + toolsFailed: 0, + findingsCount: 2, + criticalCount: 0, + highCount: 1, + mediumCount: 1, + lowCount: 0, + infoCount: 0, + duration: 5000, + }, + startedAt: Date.now(), + completedAt: Date.now(), + status: "completed", + } + + const saved = await WebScanStorage.saveScan(scan, { storage: "memory" }) + expect(saved.id).toMatch(/^scan_/) + + const retrieved = await WebScanStorage.getScan(saved.id, { storage: "memory" }) + expect(retrieved).not.toBeNull() + expect(retrieved!.profile).toBe("standard") + }) + }) +}) + +describe("WPScanParser", () => { + test("parses JSON output", () => { + const output = JSON.stringify({ + target_url: "http://wordpress.example.com", + version: { + number: "6.4.2", + status: "outdated", + vulnerabilities: [ + { + title: "WordPress < 6.5 - XSS Vulnerability", + fixed_in: "6.5", + references: { + cve: ["2024-1234"], + url: ["https://example.com/advisory"], + }, + cvss: { score: "6.1" }, + }, + ], + }, + plugins: { + "contact-form-7": { + version: { number: "5.8" }, + vulnerabilities: [], + }, + }, + users: { admin: { id: 1 }, editor: { id: 2 } }, + }) + + const result = WPScanParser.parse(output) + + expect(result.target).toBe("http://wordpress.example.com") + expect(result.version?.number).toBe("6.4.2") + expect(result.version?.vulnerabilities).toHaveLength(1) + expect(result.plugins?.["contact-form-7"]).toBeDefined() + expect(result.users).toContain("admin") + }) + + test("generates findings from vulnerabilities", () => { + const output = JSON.stringify({ + target_url: "http://wordpress.example.com", + version: { + number: "6.4.2", + vulnerabilities: [ + { + title: "Test Vulnerability", + fixed_in: "6.5", + cvss: { score: "7.5" }, + }, + ], + }, + }) + + const result = WPScanParser.parse(output) + const findings = WPScanParser.toFindings( + result, + "http://wordpress.example.com", + "session_test" + ) + + expect(findings).toHaveLength(1) + expect(findings[0].title).toBe("Test Vulnerability") + expect(findings[0].severity).toBe("high") // 7.5 CVSS = high + expect(findings[0].service).toBe("wordpress") + }) + + test("formats result for display", () => { + const output = JSON.stringify({ + target_url: "http://wordpress.example.com", + version: { number: "6.4.2", status: "latest" }, + plugins: { "akismet": { version: { number: "5.3" } } }, + }) + + const result = WPScanParser.parse(output) + const formatted = WPScanParser.format(result) + + expect(formatted).toContain("WordPress Version: 6.4.2") + expect(formatted).toContain("akismet") + }) + + test("summarizes result", () => { + const output = JSON.stringify({ + target_url: "http://wordpress.example.com", + version: { number: "6.4.2", vulnerabilities: [{}, {}] }, + plugins: { a: {}, b: {} }, + users: ["admin"], + }) + + const result = WPScanParser.parse(output) + const summary = WPScanParser.summarize(result) + + expect(summary).toContain("WordPress 6.4.2") + expect(summary).toContain("2 plugins") + expect(summary).toContain("2 vulnerabilities") + expect(summary).toContain("1 users") + }) +}) + +describe("WhatWebParser", () => { + test("parses JSON output", () => { + const output = JSON.stringify([ + { + target: "http://example.com", + http_status: 200, + plugins: { + Apache: { version: ["2.4.52"] }, + PHP: { version: ["8.1.2"] }, + WordPress: { version: ["6.4"] }, + HTTPServer: { string: ["Apache/2.4.52"] }, + }, + }, + ]) + + const results = WhatWebParser.parse(output) + + expect(results).toHaveLength(1) + expect(results[0].target).toBe("http://example.com") + expect(results[0].httpStatus).toBe(200) + expect(results[0].technologies.some((t) => t.name === "Apache")).toBe(true) + expect(results[0].technologies.some((t) => t.name === "PHP")).toBe(true) + }) + + test("parses text output fallback", () => { + const output = `http://example.com [200] Apache[2.4.52], PHP[8.1.2], WordPress[6.4]` + + const results = WhatWebParser.parseText(output) + + expect(results).toHaveLength(1) + expect(results[0].target).toBe("http://example.com") + expect(results[0].httpStatus).toBe(200) + expect(results[0].technologies.some((t) => t.name === "Apache")).toBe(true) + }) + + test("generates findings for outdated jQuery", () => { + const output = JSON.stringify([ + { + target: "http://example.com", + http_status: 200, + plugins: { + jQuery: { version: ["1.12.4"] }, + }, + }, + ]) + + const results = WhatWebParser.parse(output) + const findings = WhatWebParser.toFindings(results[0], "http://example.com", "session_test") + + const jqueryFinding = findings.find((f) => f.title.includes("jQuery")) + expect(jqueryFinding).toBeDefined() + expect(jqueryFinding!.severity).toBe("medium") + }) + + test("formats result for display", () => { + const output = JSON.stringify([ + { + target: "http://example.com", + http_status: 200, + plugins: { + Apache: { version: ["2.4.52"] }, + PHP: { version: ["8.1.2"] }, + }, + }, + ]) + + const results = WhatWebParser.parse(output) + const formatted = WhatWebParser.format(results[0]) + + expect(formatted).toContain("http://example.com") + expect(formatted).toContain("HTTP Status: 200") + expect(formatted).toContain("Apache") + expect(formatted).toContain("PHP") + }) +}) + +describe("OwaspCategorization", () => { + test("categorizes injection findings", () => { + const finding: PentestTypes.Finding = { + id: "finding_1", + sessionID: "session_1", + title: "SQL Injection in login form", + description: "The login form is vulnerable to SQL injection attacks allowing SQLi and command injection", + severity: "critical", + status: "open", + target: "http://example.com", + createdAt: Date.now(), + } + + const result = OwaspCategorization.categorizeFinding(finding) + + expect(result.category).toBe("A03:2021-Injection") + expect(result.confidence).toBe("high") // 3+ matches: sql injection pattern, sqli keyword, command keyword, injection keyword + }) + + test("categorizes XSS as injection", () => { + const finding: PentestTypes.Finding = { + id: "finding_2", + sessionID: "session_1", + title: "Cross-Site Scripting (XSS)", + description: "Reflected XSS in search parameter", + severity: "high", + status: "open", + target: "http://example.com", + createdAt: Date.now(), + } + + const result = OwaspCategorization.categorizeFinding(finding) + + expect(result.category).toBe("A03:2021-Injection") + }) + + test("categorizes SSL issues as cryptographic failures", () => { + const finding: PentestTypes.Finding = { + id: "finding_3", + sessionID: "session_1", + title: "Weak SSL/TLS Configuration", + description: "Server supports weak cipher suites", + severity: "medium", + status: "open", + target: "http://example.com", + createdAt: Date.now(), + } + + const result = OwaspCategorization.categorizeFinding(finding) + + expect(result.category).toBe("A02:2021-Cryptographic_Failures") + }) + + test("categorizes path traversal as broken access control", () => { + const finding: PentestTypes.Finding = { + id: "finding_4", + sessionID: "session_1", + title: "Path Traversal Vulnerability", + description: "File parameter allows path traversal", + severity: "high", + status: "open", + target: "http://example.com", + createdAt: Date.now(), + } + + const result = OwaspCategorization.categorizeFinding(finding) + + expect(result.category).toBe("A01:2021-Broken_Access_Control") + }) + + test("categorizes CVE findings as vulnerable components", () => { + const finding: PentestTypes.Finding = { + id: "finding_5", + sessionID: "session_1", + title: "Apache Struts RCE", + description: "Remote code execution vulnerability", + severity: "critical", + status: "open", + target: "http://example.com", + cve: ["CVE-2017-5638"], + createdAt: Date.now(), + } + + const result = OwaspCategorization.categorizeFinding(finding) + + expect(result.category).toBe("A06:2021-Vulnerable_and_Outdated_Components") + expect(result.confidence).toBe("high") + }) + + test("categorizes SSRF correctly", () => { + const finding: PentestTypes.Finding = { + id: "finding_6", + sessionID: "session_1", + title: "Server-Side Request Forgery", + description: "SSRF allows access to internal services", + severity: "high", + status: "open", + target: "http://example.com", + createdAt: Date.now(), + } + + const result = OwaspCategorization.categorizeFinding(finding) + + expect(result.category).toBe("A10:2021-Server-Side_Request_Forgery") + }) + + test("marks uncategorizable findings", () => { + const finding: PentestTypes.Finding = { + id: "finding_7", + sessionID: "session_1", + title: "Information Disclosure", + description: "Server returns detailed stack traces", + severity: "low", + status: "open", + target: "http://example.com", + createdAt: Date.now(), + } + + const result = OwaspCategorization.categorizeFinding(finding) + + // Should match A05 Security Misconfiguration + expect(result.category).toBe("A05:2021-Security_Misconfiguration") + }) + + test("getCategoryName returns human readable names", () => { + expect(OwaspCategorization.getCategoryName("A01:2021-Broken_Access_Control")).toBe("Broken Access Control") + expect(OwaspCategorization.getCategoryName("A03:2021-Injection")).toBe("Injection") + expect(OwaspCategorization.getCategoryName("Uncategorized")).toBe("Uncategorized") + }) +}) + +describe("WebScanTypes", () => { + test("validates CrawlOptions", () => { + const valid = WebScanTypes.CrawlOptions.parse({ + maxDepth: 3, + maxUrls: 500, + }) + + expect(valid.maxDepth).toBe(3) + expect(valid.maxUrls).toBe(500) + expect(valid.delay).toBe(100) // Default + expect(valid.followRedirects).toBe(true) // Default + }) + + test("validates ScanProfile", () => { + const valid = WebScanTypes.ScanProfile.parse({ + id: "custom", + name: "Custom Profile", + description: "Test profile", + crawl: { + enabled: true, + maxDepth: 2, + maxUrls: 100, + }, + tools: ["nikto", "nuclei"], + }) + + expect(valid.id).toBe("custom") + expect(valid.tools).toHaveLength(2) + }) + + test("validates OwaspCategory enum", () => { + const valid = WebScanTypes.OwaspCategory.parse("A03:2021-Injection") + expect(valid).toBe("A03:2021-Injection") + + expect(() => WebScanTypes.OwaspCategory.parse("Invalid")).toThrow() + }) +}) diff --git a/packages/opencode/tsconfig.json b/packages/opencode/tsconfig.json index 9067d84fd6a..31acfc5ceff 100644 --- a/packages/opencode/tsconfig.json +++ b/packages/opencode/tsconfig.json @@ -12,5 +12,6 @@ "@/*": ["./src/*"], "@tui/*": ["./src/cli/cmd/tui/*"] } - } + }, + "exclude": ["src/dashboard"] } diff --git a/packages/web/package.json b/packages/web/package.json index 3dd95ef1849..7927fcaf215 100644 --- a/packages/web/package.json +++ b/packages/web/package.json @@ -34,7 +34,7 @@ "toolbeam-docs-theme": "0.4.8" }, "devDependencies": { - "opencode": "workspace:*", + "cyxwiz": "workspace:*", "@types/node": "catalog:", "typescript": "catalog:" }