Building a Honeypot & Intrusion Detection System: Hands-On Project

Traditional perimeter firewalls and signature-based Intrusion Detection Systems (IDS) generate thousands of noisy alerts daily, forcing security analysts to separate benign internet background radiation from genuine targeted attacks. A Honeypot flips this detection model: because no legitimate user or production service ever has a reason to connect to a decoy asset, every single packet, login attempt, or HTTP request hitting a honeypot is high-fidelity malicious activity.

In this hands-on project, you will build a modular, container-isolated Honeypot and real-time Intrusion Detection System (IDS) in Python that emulates vulnerable SSH and HTTP administrative surfaces, captures attacker credentials and exploit payloads as structured JSON telemetry, triggers real-time IDS signature alerts, and enforces strict network egress containment.

Honeypot & IDS Architecture: Design Comparison

Before writing code, select the right interaction depth and isolation boundaries so attackers can be observed without compromising your host infrastructure:

Architectural DimensionLow-Interaction Honeypot (This Project)High-Interaction Honeypot
Emulation DepthSimulates TCP banners, fake SSH auth prompts, and decoy HTTP login endpointsFull OS / vulnerable application stack instrumented with kernel telemetry
Compromise RiskMinimal — no real shell or underlying OS execution exposedHigh — requires strict hypervisor snapshots, VLAN isolation, and egress scrubbing
Resource FootprintSingle Python asyncio/threaded container (< 64 MB RAM)Dedicated VM cluster (2 GB - 8 GB RAM per node)
Primary Telemetry CapturedSource IPs, brute-force credential wordlists, automated scanner fingerprints, exploit payloadsPost-exploitation lateral movement, binary droppers, C2 beaconing behavior
IDS IntegrationInline signature matching + behavioral threshold alerting (JSONL / SIEM stream)Host-based EDR + network packet capture (PCAP / Zeek / Suricata)
TEXT
+-----------------------------------------------------------------------------------+
|                 ISOLATED HONEYPOT & INTRUSION DETECTION ARCHITECTURE              |
+-----------------------------------------------------------------------------------+
|                                                                                   |
|  [External Attacker / Botnet]                                                     |
|         |                                   |                                     |
|         | Port 2222 (Decoy SSH)             | Port 8080 (Decoy Admin HTTP)        |
|         v                                   v                                     |
|  +-----------------------------------------------------------------------------+  |
|  |               DOCKER ISOLATED NETWORK (internal: true / Zero Egress)        |  |
|  |                                                                             |  |
|  |  +---------------------------------+   +---------------------------------+  |  |
|  |  |     SSH Deception Listener      |   |    HTTP Deception Listener      |  |  |
|  |  | (Fake OpenSSH Banner & Auth Log)|   | (/admin, /.env, /wp-login.php)  |  |  |
|  |  +---------------------------------+   +---------------------------------+  |  |
|  |                  |                                       |                  |  |
|  |                  +-------------------+-------------------+                  |  |
|  |                                      |                                      |  |
|  |                                      v                                      |  |
|  |  +-----------------------------------------------------------------------+  |  |
|  |  |                  REAL-TIME IDS DETECTION & ALERT ENGINE               |  |  |
|  |  |  - Signature Rules: SQLi, Path Traversal, Command Injection, Scanners |  |  |
|  |  |  - Behavioral Rules: Brute-Force Velocity (> 5 attempts / 60s)        |  |  |
|  |  +-----------------------------------------------------------------------+  |  |
|  +--------------------------------------|--------------------------------------+  |
|                                         | Append-Only JSONL Volume              |
|                                         v                                         |
|  +-----------------------------------------------------------------------------+  |
|  |          TELEMETRY STORAGE & THREAT INTEL OUTPUT (alerts.jsonl)             |  |
|  +-----------------------------------------------------------------------------+  |
+-----------------------------------------------------------------------------------+

Project Structure

Create a clean workspace for the honeypot listeners, IDS rule engine, and Docker isolation configuration:

TEXT
honeypot-ids/
├── ids_engine.py          # Signature & behavioral anomaly detection engine
├── honeypot_server.py     # Concurrent SSH & HTTP deception listeners
├── Dockerfile             # Unprivileged, read-only container image
├── docker-compose.yml     # Egress-blocked network & resource limits
└── logs/                  # Host-mounted directory for JSONL telemetry

Step 1: Building the Real-Time IDS Detection Engine (ids_engine.py)

The IDS engine inspects every normalized interaction event emitted by the decoy listeners. It evaluates two layers of detection:

  1. Signature-Based Payload Inspection: Matches HTTP paths, headers, and bodies against regex signatures for SQL injection, directory traversal (../), shell command injection, and sensitive file probing (/.env, /.git/config).
  2. Behavioral Velocity Tracking: Uses a sliding time window (collections.deque) per source IP to detect automated credential-stuffing and brute-force attacks.
Python
from collections import defaultdict, deque
from datetime import datetime, timezone
import json
from pathlib import Path
import re
import threading
import time
from typing import Any


SIGNATURES: list[tuple[str, str, re.Pattern[str]]] = [
    (
        "SIG-1001",
        "Path Traversal / Sensitive File Probe",
        re.compile(r"(\.\./|\.\.\\|/etc/passwd|/\.env|/\.git/config|wp-config\.php)", re.IGNORECASE),
    ),
    (
        "SIG-1002",
        "SQL Injection Attempt",
        re.compile(r"(\bUNION\s+SELECT\b|\bOR\s+1=1\b|'\s*OR\s*'1'='1|--\s*$)", re.IGNORECASE),
    ),
    (
        "SIG-1003",
        "OS Command Injection / Shell Dropper",
        re.compile(r"(;|\||`|\$\()\s*(wget|curl|bash|sh|nc|python3?|perl|chmod\s+\+x)", re.IGNORECASE),
    ),
    (
        "SIG-1004",
        "Known Automated Vulnerability Scanner",
        re.compile(r"(sqlmap|nikto|masscan|zgrab|nmap|nuclei|gobuster)", re.IGNORECASE),
    ),
]


class IntrusionDetectionEngine:
    def __init__(self, log_path: Path, brute_force_threshold: int = 5, window_seconds: int = 60) -> None:
        self.log_path = log_path
        self.log_path.parent.mkdir(parents=True, exist_ok=True)
        self.brute_force_threshold = brute_force_threshold
        self.window_seconds = window_seconds
        self._ip_timestamps: dict[str, deque[float]] = defaultdict(deque)
        self._lock = threading.Lock()

    def _check_brute_force(self, src_ip: str, now_mono: float) -> bool:
        history = self._ip_timestamps[src_ip]
        history.append(now_mono)
        cutoff = now_mono - self.window_seconds
        while history and history[0] < cutoff:
            history.popleft()
        return len(history) >= self.brute_force_threshold

    def inspect_and_log(self, event: dict[str, Any]) -> dict[str, Any]:
        src_ip = event.get("src_ip", "0.0.0.0")
        inspectable_blob = json.dumps(event.get("payload", {}), sort_keys=True)
        matched_alerts: list[dict[str, str]] = []

        # 1. Signature matching against captured payload
        for sig_id, description, pattern in SIGNATURES:
            if pattern.search(inspectable_blob):
                matched_alerts.append({"rule_id": sig_id, "description": description})

        # 2. Behavioral sliding-window rate detection
        with self._lock:
            is_brute_force = self._check_brute_force(src_ip, time.monotonic())
            if is_brute_force:
                matched_alerts.append({
                    "rule_id": "BEH-2001",
                    "description": f"High-velocity brute-force/scan (>= {self.brute_force_threshold} events in {self.window_seconds}s)",
                })

            enriched_event = {
                "timestamp": datetime.now(timezone.utc).isoformat(),
                "severity": "CRITICAL" if matched_alerts else "HIGH",
                "alerts": matched_alerts,
                **event,
            }

            with self.log_path.open("a", encoding="utf-8") as fh:
                fh.write(json.dumps(enriched_event) + "\n")

        alert_summary = ", ".join(a["rule_id"] for a in matched_alerts) if matched_alerts else "DECOY_CONTACT"
        print(f"[{enriched_event['severity']}] {src_ip} -> {event['service']} ({alert_summary})")
        return enriched_event

Step 2: Implementing Multi-Protocol Deception Listeners (honeypot_server.py)

Next, build two lightweight deception services in Python:

  • Decoy SSH Service (port 2222): Advertises a realistic SSH-2.0-OpenSSH_8.9p1 Ubuntu-3ubuntu0.6 banner, reads the client's SSH version string, logs connection attempts, and forces clean socket timeouts to prevent resource exhaustion (Slowloris/tarpit defense).
  • Decoy HTTP Admin Portal (port 8080): Serves a convincing fake Internal Infrastructure Control Panel login form, captures submitted usernames, passwords, User-Agent strings, and query parameters, and feeds them directly into IntrusionDetectionEngine.
Python
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
import socket
import socketserver
import threading
from urllib.parse import parse_qs, urlparse

from ids_engine import IntrusionDetectionEngine


SSH_BANNER = b"SSH-2.0-OpenSSH_8.9p1 Ubuntu-3ubuntu0.6\r\n"

FAKE_LOGIN_HTML = """<!DOCTYPE html>
<html lang="en">
<head><meta charset="utf-8"><title>Internal Ops Portal - Sign In</title></head>
<body style="font-family: sans-serif; max-width: 420px; margin: 80px auto;">
  <h2>Infrastructure Control Plane</h2>
  <p style="color: #b91c1c;">Invalid session or unauthorized access attempt logged.</p>
  <form method="POST" action="/admin/login">
    <label>Username:<br><input type="text" name="username" required></label><br><br>
    <label>Password:<br><input type="password" name="password" required></label><br><br>
    <button type="submit">Authenticate</button>
  </form>
</body>
</html>
"""


class ThreadedTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer):
    allow_reuse_address = True
    daemon_threads = True


class SSHHoneypotHandler(socketserver.BaseRequestHandler):
    ids_engine: IntrusionDetectionEngine

    def handle(self) -> None:
        self.request.settimeout(5.0)
        src_ip, src_port = self.client_address[0], self.client_address[1]
        client_banner = ""
        try:
            self.request.sendall(SSH_BANNER)
            raw = self.request.recv(256)
            client_banner = raw.decode("utf-8", errors="replace").strip()
        except (socket.timeout, OSError):
            pass

        self.ids_engine.inspect_and_log({
            "service": "ssh-decoy",
            "src_ip": src_ip,
            "src_port": src_port,
            "payload": {"client_banner": client_banner or "<no-banner>"},
        })


def create_http_handler(ids_engine: IntrusionDetectionEngine):
    class HTTPHoneypotHandler(BaseHTTPRequestHandler):
        server_version = "Apache/2.4.52 (Ubuntu)"
        sys_version = ""

        def _record_request(self, body_data: str = "") -> None:
            parsed = urlparse(self.path)
            form_fields = parse_qs(body_data) if body_data else {}
            ids_engine.inspect_and_log({
                "service": "http-decoy",
                "src_ip": self.client_address[0],
                "src_port": self.client_address[1],
                "payload": {
                    "method": self.command,
                    "path": parsed.path,
                    "query": parsed.query,
                    "user_agent": self.headers.get("User-Agent", ""),
                    "form_data": {k: v[0] for k, v in form_fields.items()},
                },
            })

        def do_GET(self) -> None:
            self._record_request()
            self.send_response(200)
            self.send_header("Content-Type", "text/html; charset=utf-8")
            self.end_headers()
            self.wfile.write(FAKE_LOGIN_HTML.encode("utf-8"))

        def do_POST(self) -> None:
            content_length = min(int(self.headers.get("Content-Length", 0)), 4096)
            body = self.rfile.read(content_length).decode("utf-8", errors="replace")
            self._record_request(body_data=body)
            self.send_response(401)
            self.send_header("Content-Type", "text/html; charset=utf-8")
            self.end_headers()
            self.wfile.write(FAKE_LOGIN_HTML.encode("utf-8"))

        def log_message(self, format: str, *args) -> None:
            # Suppress noisy default stderr access logs; handled by IDS JSONL logger
            return

    return HTTPHoneypotHandler


if __name__ == "__main__":
    engine = IntrusionDetectionEngine(log_path=Path("logs/alerts.jsonl"))

    SSHHoneypotHandler.ids_engine = engine
    ssh_server = ThreadedTCPServer(("0.0.0.0", 2222), SSHHoneypotHandler)
    http_server = ThreadingHTTPServer(("0.0.0.0", 8080), create_http_handler(engine))

    threading.Thread(target=ssh_server.serve_forever, daemon=True).start()
    print("Honeypot & IDS active -> SSH Decoy on :2222 | HTTP Decoy on :8080")
    http_server.serve_forever()

Step 3: Safe Containment with Hardened Docker Isolation (Dockerfile & docker-compose.yml)

Never run a honeypot as root on a host OS with outbound internet access. If an attacker discovers an interpreter flaw, an uncontained honeypot can be turned into a DDoS pivot or lateral-movement proxy. Lock down the container with:

  • Non-root user (UID 10001)
  • read_only: true root filesystem
  • cap_drop: [ALL]
  • Strict CPU and memory quotas to absorb volumetric connection floods

Dockerfile

DOCKERFILE
FROM python:3.12-slim

RUN useradd --uid 10001 --create-home --shell /usr/sbin/nologin honeypot
WORKDIR /app

COPY ids_engine.py honeypot_server.py ./
RUN mkdir -p /app/logs && chown -R honeypot:honeypot /app

USER honeypot
EXPOSE 2222 8080

CMD ["python3", "-u", "honeypot_server.py"]

docker-compose.yml

YAML
services:
  honeypot-ids:
    build: .
    container_name: codecrown-honeypot-ids
    restart: unless-stopped
    read_only: true
    user: "10001:10001"
    cap_drop:
      - ALL
    security_opt:
      - no-new-privileges:true
    ports:
      - "2222:2222"
      - "8080:8080"
    volumes:
      - ./logs:/app/logs:rw
    deploy:
      resources:
        limits:
          cpus: "0.50"
          memory: 128M

Step 4: Running & Validating IDS Detections

Start the isolated honeypot container and simulate reconnaissance, credential stuffing, and exploit probing from a local test terminal:

Bash
# 1. Build and launch the hardened honeypot container
docker compose up -d --build

# 2. Simulate an SSH scanner banner grab
nc -w 2 127.0.0.1 2222

# 3. Simulate a sensitive file traversal probe (triggers SIG-1001)
curl -i "http://127.0.0.1:8080/../../.env"

# 4. Simulate a credential brute-force + SQL injection payload (triggers SIG-1002)
curl -s -X POST "http://127.0.0.1:8080/admin/login" \
  -A "sqlmap/1.8.4" \
  -d "username=admin' OR '1'='1&password=Password123!"

# 5. Inspect structured JSONL alerts emitted by the IDS engine
cat logs/alerts.jsonl | python3 -m json.tool

Sample IDS Alert Output (logs/alerts.jsonl)

JSON
{
  "timestamp": "2026-11-29T00:01:14.819204+00:00",
  "severity": "CRITICAL",
  "alerts": [
    {
      "rule_id": "SIG-1002",
      "description": "SQL Injection Attempt"
    },
    {
      "rule_id": "SIG-1004",
      "description": "Known Automated Vulnerability Scanner"
    }
  ],
  "service": "http-decoy",
  "src_ip": "172.18.0.1",
  "src_port": 51482,
  "payload": {
    "method": "POST",
    "path": "/admin/login",
    "query": "",
    "user_agent": "sqlmap/1.8.4",
    "form_data": {
      "username": "admin' OR '1'='1",
      "password": "Password123!"
    }
  }
}

Common Mistakes

  • Exposing a honeypot on the same subnet as production databases: Always deploy honeypots in an isolated DMZ or dedicated VPC subnet with firewall rules blocking all outbound (egress) connections except encrypted log forwarding to your SIEM.
  • Accepting unbounded HTTP bodies or hanging TCP sockets: Without strict socket.settimeout() calls and Content-Length caps (<= 4096 bytes), a single Slowloris script can exhaust Python worker threads and crash telemetry collection.
  • Logging raw attacker input directly to an unescaped web dashboard: Attackers frequently embed Cross-Site Scripting (<script>) payloads inside HTTP User-Agent headers or SSH banners specifically targeting analysts viewing honeypot logs in browser interfaces. Always store logs as structured JSON and HTML-escape any rendered UI fields.

Summary

Combining a low-interaction SSH/HTTP honeypot with a real-time signature and behavioral IDS engine transforms unsolicited internet traffic into zero-false-positive threat intelligence. By capping socket timeouts, streaming structured JSONL alerts, and running the listeners inside a read-only, capability-dropped, unprivileged Docker container, you gain high-fidelity visibility into attacker tactics without exposing underlying infrastructure.