No description
  • Python 64.3%
  • JavaScript 29.5%
  • Shell 2.9%
  • CSS 2.8%
  • Dockerfile 0.4%
  • Other 0.1%
Find a file
Repository files (latest commit first)
Filename Latest commit message Latest commit date
2026-11-20 16:28:43 +01:00
backend Optimize LLM token usage with bounded history, expanded local emulation, and shared transition caching 2026-11-20 16:28:43 +01:00
frontend Improve payload hasher timeouts, User-Agent matching, and add URLhaus links 2026-11-08 17:51:04 +01:00
scripts Add isolated payload SHA-256 hasher, threat intel view, and security hardening 2026-11-08 15:32:52 +01:00
.env.example Enable map wheel zoom and cache stable session commands and groups 2026-11-08 02:18:04 +01:00
.gitignore Store persistent data and SSH keys in local bind directories 2026-11-08 01:40:43 +01:00
docker-compose.yml Add isolated payload SHA-256 hasher, threat intel view, and security hardening 2026-11-08 15:32:52 +01:00
pytest.ini Isolate SSH honeypot and route commands through stateful OpenRouter simulation 2026-11-08 00:02:33 +01:00
README.md Update architecture diagram and security documentation 2026-11-08 15:40:07 +01:00
SECURITY.md Update architecture diagram and security documentation 2026-11-08 15:40:07 +01:00

SSH Honeypot with LLM Backend

An AsyncSSH honeypot with an LLM-simulated shell, SQLite session history, and a live React dashboard. SSH commands are never executed on the host. Password authentication is intentionally permissive unless an allowlist is configured.

Deploy behind your reverse proxy

cp .env.example .env

Set these values in .env:

REVERSE_PROXY_NETWORK=your-existing-proxy-network
OPENROUTER_API_KEY=your-openrouter-api-key
OPENROUTER_MODEL=~deepseek/deepseek-flash-latest

REVERSE_PROXY_NETWORK must name an existing Docker network shared with your reverse proxy. Point the proxy to http://honeypot-frontend:8080, preserve the original Host header, enable WebSocket upgrades for /ws/, and protect the entire site with HTTPS and access control. The dashboard retains captured credentials, so its API and WebSocket feed need the same protection as the UI. Authentication belongs to your reverse proxy; the application has no separate dashboard login.

For an existing installation using named data volumes, follow the local-storage migration below before starting the updated stack. For a fresh installation:

docker compose up -d --build

honeypot-backend:local is built once by data-init; the gateway, payload hasher, SSH simulator, ingress, and API reuse that image with pull_policy: never. The frontend builds honeypot-frontend:local separately. Only these two services declare builds, avoiding parallel exports to the same image tag. Both builders use pull_policy: build, so Compose does not try to download application images from Docker Hub. Dockerfile base images are still downloaded as needed; no Docker login is required for these public bases.

Service Container / address Host port
Dashboard, API, live events honeypot-frontend:8080 on your proxy network None
Backend API honeypot-backend:8000 on the internal API network None
SSH ingress honeypot-ssh-ingress:2222 SSH_PORT, default 2222
SSH simulator honeypot-ssh, network_mode: none None
LLM gateway honeypot-llm-gateway, private Unix socket None
Payload hasher honeypot-payload-hasher, private Unix socket None

Only the frontend joins your external proxy network. It serves built static assets and forwards /api/ and /ws/ to the backend. Only SSH is published on the host; Vite is used for development and builds.

Connect with ssh -p 2222 root@SERVER_IP (substitute your configured SSH_PORT). Plain ssh SERVER_IP uses port 22 unless your client configuration overrides it. SSH negotiation and the password prompt do not call the LLM; inference starts when an authenticated client sends a command. Unused GSS/Kerberos hostname discovery and peer reverse DNS are explicitly disabled so they cannot block the networkless SSH role. The TCP ingress sends interactive packets without Nagle batching. If negotiation still pauses, use ssh -vvv -p 2222 root@SERVER_IP to identify the stage.

Persistent files use local directories under HONEYPOT_STORAGE_DIR (default ./storage, relative to docker-compose.yml):

Local path Contents
storage/data/ SQLite database, session evidence, and SQLite sidecars
storage/ssh-host-keys/ Private SSH host key

The default storage/ directory is Git-ignored. Keep any custom storage path outside Git. data-init prepares ownership for container UID/GID 10001 and directory permissions 0700; administrative access may be needed to inspect or back up these files on the host. The SSH key remains 0600 (verified as a regular, unlinked file) and is mounted read-only by SSH. The API mounts only the data directory, read-only. Shared SELinux labels are enabled for these bind mounts. Private ssh-ingress, llm-rpc, and hasher-rpc socket directories remain Docker-managed volumes. Schema migrations and historical password analysis run in the SSH writer before the read-only API starts.

To migrate an existing named-volume installation, run these commands from this repository using the same Docker context and Compose project name as the original deployment:

git pull
docker compose build
docker compose stop
python3 scripts/migrate-local-storage.py
docker compose up -d --build

The migration copies the project's legacy honeypot-data and, when present, ssh-host-keys volumes into empty local directories. It refuses running source containers, populated destinations, and symlinks. Legacy volumes remain unchanged. An older host key stored alongside the database is moved into the separate local key directory during initialization. Back up existing storage before upgrading. For consistent later backups, stop the stack and copy both local directories, then start it again.

Isolation and command handling

flowchart LR
    Internet -->|encrypted SSH| Ingress[SSH ingress]
    Ingress -->|private Unix stream| SSH[SSH simulator: no network]
    SSH -->|Unix RPC| Gateway[LLM gateway]
    Gateway -->|HTTPS| OpenRouter
    SSH -->|Unix RPC| Hasher[Payload hasher]
    Hasher -->|HTTP/HTTPS stream| Payloads[Attacker payload URLs]
    SSH -->|writes evidence| SQLite[(SQLite)]
    SQLite -->|read-only| API[Dashboard API]
    API --> Frontend
    Proxy[Your reverse proxy] -->|frontend:8080| Frontend
  • The SSH container has only loopback: no Internet/LAN routes, public ports, provider credentials, Docker socket, or privileged capabilities. Its host bind mounts are limited to the dedicated data directory and read-only key directory. The ingress passes only AF_UNIX streams, not Internet-capable sockets. Original peer addresses travel as metadata over a private, permission-restricted Unix control socket.
  • The ingress only relays encrypted bytes. It neither authenticates users nor interprets commands. Only its SSH port is published, with a global cap of 64 concurrent connections, a per-IP cap of 16 concurrent connections, and immediate half-closed relay teardown when the SSH simulator closes a session.
  • The LLM gateway holds provider credentials and outbound access. Its Unix API accepts bounded command/transcript/state data; commands cannot choose URLs, models, tools, or other services. Geolocation uses validated public IPs and a fixed HTTPS endpoint with a bounded cache.
  • The payload hasher (honeypot-payload-hasher) runs in a dedicated sandbox container on an isolated egress network (hasher-egress) with no database, host keys, LLM credentials, or writable files (RLIMIT_FSIZE=0). When an SSH command references HTTP(S) download URLs (curl, wget, fetch, aria2c, lwp-download, tftp, busybox), honeypot-ssh requests an asynchronous hash over /run/hasher/hasher.sock. The hasher resolves and pins global IP addresses (blocking private, loopback, link-local, and metadata IPs to prevent SSRF and DNS rebinding) and streams up to 10 MiB strictly in memory to compute the payload's SHA-256 digest without ever writing to disk or executing the file.
  • The API reads SQLite through a read-only volume and SQLite mode=ro. It has no SSH key, gateway socket, or hasher socket mount. It uses a bounded database event stream for live updates, and an internal network connects it only to the frontend.
  • All long-running services run as non-root, with read-only root filesystems, dropped capabilities, no-new-privileges, CPU/memory/PID/file-descriptor limits, and bounded temporary storage. SFTP, TCP/Unix forwarding, agent forwarding, and X11 forwarding are unavailable.

Incoming SSH exec requests and interactive lines are simulation data. Simple built-in and virtual-state commands (history, export, unset, env, printenv, echo, hostname, arch, basename, dirname, md5sum/sha*sum, base64, wc, head/tail, :, clear, reset, false) are resolved directly from the session's in-memory virtual state without calling the LLM. Cache misses go to the LLM as JSON; cache hits reuse a previously validated model response. The application never passes commands to a shell, interpreter, subprocess, or host filesystem API. Model output is parsed as a validated stdout, stderr, exit_code, cwd, and virtual state response (when state is unchanged or partially updated, omitted fields inherit the session's current state before validation). Virtual paths are strings; they are never opened on the host. Failed/malformed/truncated/provider responses retain the previous virtual state and return a generic error instead of silently succeeding.

Each authenticated connection has one fictional Ubuntu/root profile and a serialized transcript shared across its channels. Model calls include login metadata, terminal, hostname, virtual environment/files/processes, current directory, and context-changing historical turns (turns that did not alter cwd or state and had no unmodelled side effects are omitted from LLM prompts while retained in the session transcript and database). Historical turns retain exact commands, working directories, stdout, stderr, and exit codes without duplicating old state snapshots. The complete latest state is supplied once with the current command; replies omit state when unchanged or return the updated state. Sessions stop accepting inference when their 128-command or 256 KiB context budget is reached; model state is bounded to 32 KiB. Commands are limited to 8 KiB, authentication passwords to 8 KiB, concurrent SSH connections to 64, and lifetime to ten minutes. The model uses only synthetic decoy data, never real host files or captured authentication passwords.

Container isolation shares the host kernel. A dedicated VM remains appropriate for an Internet-facing honeypot; these controls do not claim protection from unknown kernel vulnerabilities. The default local-development combined role does not provide the Compose deployment's process/network separation.

Command cache

COMMAND_CACHE_ENABLED=true enables bounded memory-only LRU caching: 64 entries / 256 KiB per SSH connection plus a shared cross-session cache of 256 entries / 1 MiB. Context-independent inspection commands (uname, whoami, id, hostname, ssh -V, which, mount, systemctl, ip, ss, netstat, ping -c, /proc/cpuinfo, /proc/version, /etc/os-release, /etc/shadow, and commands the model flags with context_dependent=false) are cached globally across sessions regardless of cwd or mutable session files. State-dependent commands (pwd, cd, ls, cat, ps, df, free, env, find) are cached by command, working directory, virtual state, and non-volatile session profile (session_started_at and client_version are excluded). Safe /dev/null and 2>&1 redirections are permitted in cached commands. Cached commands still enter the database and complete transcript and count toward session limits.

Time-dependent read-only commands (date, uptime, w, who, last, dmesg, /proc/uptime) are cached across sessions on their first execution with matching context-changing history, while subsequent executions in the same session still call the model. Compound requests using &&, ||, semicolons, pipes, or newlines qualify when every command qualifies. Nothing is split into executable commands.

Read-only dynamic commands (such as $RANDOM, /dev/urandom, tail -f, or repeated date calls), modelled state changes (where state or cwd updates), and simple unknown commands that exit with 127 and unchanged state preserve existing cache entries. Unmodelled mutations (commands that succeed without changing state or cwd and are not marked context_dependent=false, such as chmod) clear the connection's cache and mark the session tainted so it stops using state-dependent cross-session cache entries. Provider errors and malformed/truncated responses are never cached. Set COMMAND_CACHE_ENABLED=false and recreate the SSH service to disable caching.

OpenRouter configuration

OpenRouter is the default provider. The exact model alias ~deepseek/deepseek-flash-latest follows the latest DeepSeek Flash release, so the serving model and its pricing can change without a deployment. See the model page.

Variable Default / purpose
LLM_PROVIDER openrouter; optional ollama remains supported
OPENROUTER_API_KEY Required when using OpenRouter; gateway only
OPENROUTER_MODEL ~deepseek/deepseek-flash-latest
OPENROUTER_BASE_URL https://openrouter.ai/api/v1
SSH_PORT Published host SSH port; container SSH port stays 2222
SSH_HOSTNAME ubuntu-server, shown in the simulated prompt
COMMAND_CACHE_ENABLED true; connection-local caching of stable commands/groups with matching virtual state
ALLOWED_USERS Empty accepts all; optional comma-separated user:password allowlist
LLM_SYSTEM_PROMPT Optional administrator scenario appended to mandatory simulation instructions; supports {hostname}
REVERSE_PROXY_NETWORK Required existing external Docker network

Requests have a 30-second total timeout, at most one SDK retry within that deadline, and up to eight concurrent LLM calls. Authentication passwords are not included in LLM prompts. Attacker-supplied conversation history stays in user/assistant messages. Provider failures return a generic shell error. There is no automatic switch to another model or application provider.

Every OpenRouter request sets provider.sort=throughput, preferring the eligible provider with the highest measured token-generation speed. Providers must support all requested parameters, including JSON responses. OpenRouter can try another eligible provider for the same model if the preferred endpoint fails. This is dynamic speed-based routing rather than a fixed provider name or a guarantee about each request's completion time. See OpenRouter provider sorting.

The obsolete direct OpenAI provider has been removed. Existing deployments using it should select LLM_PROVIDER=openrouter and configure the OpenRouter variables above. The openai Python package remains solely as the compatible HTTP SDK for OpenRouter/Ollama; it supplies no default model.

For an existing Ollama server, select LLM_PROVIDER=ollama, set OLLAMA_BASE_URL to a URL reachable from the LLM gateway, and choose OLLAMA_MODEL (default llama3.2). Prepare the model on that server yourself. There is no automatic switch to another model or application provider.

The former bundled ollama Compose profile has been removed: its pinned upstream image reported 34 known vulnerabilities, including unfixed OS and Go dependency issues during this update. Existing Ollama data volumes are left untouched. If upgrading an installation that ran the bundled profile, stop and remove its orphaned container after switching to OpenRouter: docker stop honeypot-ollama followed by docker rm honeypot-ollama. Compose does not automatically remove it. The provider client remains supported, but a separate Ollama server is outside this project's container security checks.

Suspected ssh-hole attempts

This project uses AsyncSSH rather than OpenSSH and does not implement the vulnerable musl crypt() authentication path. It deliberately accepts suspicious passwords into a simulated shell so attempts can be observed without installing a vulnerable SSH daemon.

The detector measures the UTF-8 bytes of the password delivered to AsyncSSH's authentication callback:

Password bytes Flag
0–256 No length-based flag
257–1,024 possible_sshole — Possible ssh-hole attempt
More than 1,024 oversized_password — Oversized password

These are investigation signals, not proof of attacker intent or a successful exploit. The underlying issue requires particular OpenSSH, musl, PAM, and account configurations; see the researcher's explanation and OpenSSH's release notes.

One database session represents one authenticated SSH connection. Multiple shell/exec channels share its ID. Authentication-only connections are saved even when the client never sends a command. In default mode all accepted passwords are retained; an explicit ALLOWED_USERS allowlist still rejects unmatched credentials. Rejected strict-mode attempts produce metadata-only application logs rather than accepted sessions.

The dashboard is organized into Overview, Insights, and Threat Intel views, and includes zero-command sessions, detection badges, password byte counts, session search, a flagged-session filter, pauseable live activity, loading/error states, and a possible ssh-hole counter. GET /api/sessions returns bounded 48-character password previews; full captured values are served only by GET /api/sessions/{id} and require an explicit Reveal action in the session evidence drawer. Replay includes model exit status and working directory. The Threat Intel view provides aggregated attacker IP reputation with direct VirusTotal IP lookup links alongside captured payload download URLs, their isolated in-memory SHA-256 hashes, payload byte sizes, content types, and VirusTotal file-hash/URL lookup links. The session map uses bundled Leaflet with HTTPS OpenStreetMap tiles, including city/street zoom, drag/pinch navigation, grouped session markers, time windows, active-session filtering, keyboard inspection, and opening session details. It shows up to 200 recent sessions with valid coordinates; IP locations are approximate, and private/unresolved IPs are omitted. Polling reconciles live updates without retaining stale locations indefinitely. Visible map tiles are loaded from OpenStreetMap without an API key, with attribution and the site's origin as referrer. Tile requests reveal the viewer's IP and viewed map area to the provider; session credentials, commands, and URL query strings are not included. Tile failures leave session markers and details usable. JavaScript, CSS, and fonts are served locally. Raw authentication passwords are excluded from application logs and live authentication events. Commands and their outputs are retained for replay. The frontend sets a restrictive Content Security Policy and the live endpoint rejects cross-origin browser connections.

The session list (GET /api/sessions, optional flagged=true), session detail, and IP detail responses include password_length_bytes and auth_flags. Command details additionally include exit_code and cwd. Threat intelligence endpoints (GET /api/threat-intel/ips and GET /api/threat-intel/payloads) return VirusTotal lookup links and isolated SHA-256 payload metadata. Live events include session_start, session_geo, command, payload_hashed, and session_end.

Development and validation

Use Python 3.14, uv 0.10.10, and Node 24 (Node 22.12 or newer is also supported).

uv venv --python 3.14
uv pip sync --require-hashes backend/requirements-dev.txt
.venv/bin/python -m pytest -q
.venv/bin/pip-audit --disable-pip --no-deps -r backend/requirements-dev.txt

cd frontend
npm ci
npm audit --audit-level=low
npm test
npm run build
npx playwright install chromium
npm run test:ui

For convenience-only combined backend development, create backend/data, set SSH_HOST_KEY_PATH=./data/ssh_host_key, and run uvicorn app.main:app from backend using your virtual environment. Export the desired LLM settings in that shell; Compose's root .env is not automatically loaded when running from backend. Run npm run dev from frontend; set DEV_BACKEND_URL=http://127.0.0.1:8000 for its HTTP and WebSocket proxy.

Runtime and development Python dependencies are hash-locked separately. To update them together:

uv pip compile backend/requirements.in --upgrade --generate-hashes --python-version 3.14 -o backend/requirements.txt
uv pip compile backend/requirements-dev.in --upgrade --constraint backend/requirements.txt --generate-hashes --python-version 3.14 -o backend/requirements-dev.txt

Commit both generated files. Frontend installs use npm ci and the committed package-lock.json. Base image digests and explicit Alpine security-update versions are pinned in the Dockerfiles; update them together when refreshing OS packages.

For a disposable Linux container integration test, build both images and run scripts/verify-deployment.sh against an empty Docker engine/context. It refuses existing test resources, creates temporary networks/volumes and a local storage directory, verifies legacy-volume migration, uses a local mock model with a placeholder key, checks stateful routing and network isolation, and removes its test resources afterward. It makes no paid inference requests. Never point it at a production project.

Run the dependency audits above after updates. Scan the built runtime images with Trivy:

trivy image --scanners vuln --severity UNKNOWN,LOW,MEDIUM,HIGH,CRITICAL --exit-code 1 honeypot-backend:local
trivy image --scanners vuln --severity UNKNOWN,LOW,MEDIUM,HIGH,CRITICAL --exit-code 1 honeypot-frontend:local

These commands fail on known findings, including unfixed vulnerabilities. No scheduled repository automation is configured. A clean scan only means no known vulnerabilities were reported by that database at that time, not that undiscovered flaws cannot exist.

Further improvements

  • Add configurable credential/session retention and encrypted off-host backups.
  • Enforce daily LLM spending and token budgets, with a deterministic response fallback.
  • Correlate password patterns, usernames, client versions, and commands across IPs to identify campaigns.
  • Export investigation indicators through structured JSON or a SIEM integration.
  • Add richer virtual file metadata (permissions, ownership, symlinks) and scenario-specific consistency evaluations.
  • Send append-only evidence to a separate collector so a compromised writer cannot alter historical records.

Deploy the honeypot in an isolated environment. SSH forwarding, agent forwarding, and X11 forwarding are disabled, and simulated downloads never run on the host.

License

MIT

Synthetic dashboard preview

Create a separate test database with 180 sessions, eight geographic origins, active and ended connections, authentication flags, and varied command transcripts:

.venv/bin/python scripts/seed-demo.py /tmp/honeypot-demo.db
SERVICE_ROLE=api DATABASE_URL='sqlite+aiosqlite:///file:/tmp/honeypot-demo.db?mode=ro&uri=true' .venv/bin/uvicorn app.main:app --app-dir backend --host 127.0.0.1 --port 8011

In another terminal:

cd frontend
DEV_BACKEND_URL=http://127.0.0.1:8011 npm run dev -- --host 127.0.0.1 --port 5181

Open http://127.0.0.1:5181. All records are synthetic; IPs and payload URLs use documentation ranges and reserved domains. The seed script refuses existing files. The preview API opens this database read-only and starts neither SSH nor LLM inference. Active sessions are fixed fixtures, not actual live connections. Use a new database filename to generate a fresh set of timestamps.