From 08d18f132c5d9f341f6e8592e2b6155936b08b48 Mon Sep 17 00:00:00 2001 From: Adam Siwiec <73085927+adamsiwiec1@users.noreply.github.com> Date: Mon, 19 Oct 2026 10:54:04 -0400 Subject: [PATCH] Make the AiTM cookie demo path runnable end to end MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The shipped demo-cookie phishlet pointed proxy_hosts, login, and auth_tokens all at demo-cookie.local.phishkit — the same host as the lure. evilginx dialed itself, failed to clone the upstream cert, and never captured a session. ensure-destination also scaffolded a colliding demo-cookie-local-phishkit yaml. start-lure reported "did not bind HTTPS port 443" while evilginx was already LISTEN, because the probe only used lsof (often missing). make setup never installed screen or pexpect, which configure_lure needs. This change: - Rewrites demo-cookie.yaml so upstream is cookie-origin.local.phishkit (distinct from the lure host). - Adds make demo-cookie-https: HTTPS mock on 127.0.0.2:443 (same port, other IP, so it does not collide with evilginx on 127.0.0.1). - Fixes the bind probe to try a real TCP connect, then ss, then lsof, with FileNotFoundError handling and a longer timeout plus grace re-check. - Extends make setup to install scripts/requirements.txt into venv and to document screen + setcap for :443/:53. - Reuses the shipped demo-cookie phishlet for demo hosts instead of scaffolding a colliding name. - Fixes upstream_domain for compound public suffixes (.co.uk, github.io, local.phishkit, …) so phishlet generation does not strip to co.uk. Tests: - engagement::tests (incl. co.uk / github.io / local.phishkit eTLD+1) - engagement::demo_phishlet_tests::demo_cookie_phishlet_does_not_self_proxy - destination::demo_reuse_tests::shipped_demo_cookie_hosts_reuse_demo_cookie_phishlet - scripts/test-https-bind-probe.sh (free port / listening / late bind) Run: cargo test -p phishkit-core --lib && bash scripts/test-https-bind-probe.sh Result: 10 rust passed; 3 bind-probe checks passed. --- Makefile | 27 +++++++- crates/phishkit-core/src/destination.rs | 38 ++++++++++- crates/phishkit-core/src/engagement.rs | 75 +++++++++++++++++++++ demos/cookie/README.md | 35 ++++++---- demos/cookie/server.ts | 47 +++++++++++-- kit/evilginx/phishlets/demo-cookie.yaml | 21 +++--- kit/evilginx/scripts/configure_lure.py | 59 +++++++++++++--- scripts/test-https-bind-probe.sh | 89 +++++++++++++++++++++++++ 8 files changed, 351 insertions(+), 40 deletions(-) create mode 100755 scripts/test-https-bind-probe.sh diff --git a/Makefile b/Makefile index 45456f7..3e15b31 100755 --- a/Makefile +++ b/Makefile @@ -73,6 +73,18 @@ help: demo-cookie: @(cd demos && npm install --silent && npm run demo:cookie) + +# HTTPS upstream mock on 127.0.0.2:443 for AiTM dry-run (distinct from lure host). +# Requires cap_net_bind_service on node (or root). Pairs with phishlet demo-cookie. +demo-cookie-https: + @mkdir -p run; \ + HOST=127.0.0.2 PORT=443 DEMO_COOKIE_TLS=1 \ + (cd demos && npm install --silent && npx --yes tsx cookie/server.ts) & echo $$! > run/demo-cookie-https.pid; \ + echo "demo-cookie HTTPS → https://127.0.0.2:443 (cookie-origin.local.phishkit)"; \ + echo "Add to /etc/hosts: 127.0.0.2 cookie-origin.local.phishkit"; \ + echo "Lure host stays: 127.0.0.1 demo-cookie.local.phishkit" + + demo-firebase: @(cd demos && npm install --silent && npm run demo:firebase) @@ -162,7 +174,20 @@ setup: @export PATH="$$HOME/.cargo/bin:$$PATH"; \ command -v cargo >/dev/null || { echo "cargo not found. Install Rust: https://rustup.rs (then restart the shell)"; exit 1; }; \ echo "==> desktop dependencies"; (cd apps/desktop && npm install); \ - echo "==> docs dependencies"; npm install + echo "==> docs dependencies"; npm install; \ + echo "==> evilginx runtime (screen + pexpect)"; \ + if ! command -v screen >/dev/null 2>&1; then \ + echo " screen not found — install with: sudo apt-get install -y screen (or brew install screen)"; \ + echo " AiTM start-lure will fail without it."; \ + else echo " screen: $$(command -v screen)"; fi; \ + if [ ! -x venv/bin/python3 ]; then python3 -m venv venv; fi; \ + ./venv/bin/pip -q install -r scripts/requirements.txt; \ + echo " pexpect: $$(./venv/bin/python3 -c 'import pexpect; print(pexpect.__version__)')"; \ + echo "==> privileged ports note"; \ + echo " evilginx binds :443 and :53. After build-evilginx, either run as root or:"; \ + echo " sudo setcap cap_net_bind_service=+ep kit/evilginx/run/evilginx"; \ + echo " For the cookie demo AiTM path also allow the HTTPS mock on 127.0.0.2:443:"; \ + echo " sudo setcap cap_net_bind_service=+ep \$$(command -v node) # or run make demo-cookie-https as root" # Run the supported desktop app. start: desktop diff --git a/crates/phishkit-core/src/destination.rs b/crates/phishkit-core/src/destination.rs index bd7fd1d..296a16a 100644 --- a/crates/phishkit-core/src/destination.rs +++ b/crates/phishkit-core/src/destination.rs @@ -127,6 +127,20 @@ pub fn ensure_destination( }) } +fn shipped_demo_phishlet(host: &str) -> Option<&'static str> { + let h = host.to_ascii_lowercase(); + if h == "demo-cookie.local.phishkit" + || h == "cookie-origin.local.phishkit" + || h.ends_with(".demo-cookie.local.phishkit") + { + return Some("demo-cookie"); + } + if h == "demo-firebase.local.phishkit" || h.ends_with(".demo-firebase.local.phishkit") { + return Some("demo-firebase"); + } + None +} + fn ensure_phishlet( target: &str, stack_info: &StackInfo, @@ -134,7 +148,11 @@ fn ensure_phishlet( ) -> AppResult { let root = kit_root()?; let host = normalize_target_host(target); - let name = phishlet_name_for_target(&host); + // Prefer the shipped demo phishlet over scaffolding a colliding + // demo-cookie-local-phishkit.yaml (C1). + let name = shipped_demo_phishlet(&host) + .map(|s| s.to_string()) + .unwrap_or_else(|| phishlet_name_for_target(&host)); let dest = root.join(format!("kit/evilginx/phishlets/{name}.yaml")); let stack = stack_info.stack.as_str(); @@ -184,3 +202,21 @@ fn ensure_phishlet( } phishlet::generate_phishlet(target, overwrite) } + +#[cfg(test)] +mod demo_reuse_tests { + use super::shipped_demo_phishlet; + + #[test] + fn shipped_demo_cookie_hosts_reuse_demo_cookie_phishlet() { + assert_eq!( + shipped_demo_phishlet("demo-cookie.local.phishkit"), + Some("demo-cookie") + ); + assert_eq!( + shipped_demo_phishlet("cookie-origin.local.phishkit"), + Some("demo-cookie") + ); + assert_eq!(shipped_demo_phishlet("app.acme.com"), None); + } +} diff --git a/crates/phishkit-core/src/engagement.rs b/crates/phishkit-core/src/engagement.rs index 80607e3..fedba0f 100644 --- a/crates/phishkit-core/src/engagement.rs +++ b/crates/phishkit-core/src/engagement.rs @@ -33,8 +33,50 @@ pub fn slugify(name: &str) -> String { } } +/// Multi-part public suffixes we treat as a single registrable unit (M1). +/// Not a full PSL, but covers the compound hosts that broke phishlet generation. +const MULTI_PART_PUBLIC_SUFFIXES: &[&str] = &[ + "co.uk", + "org.uk", + "ac.uk", + "gov.uk", + "com.au", + "net.au", + "org.au", + "co.nz", + "co.jp", + "com.br", + "com.mx", + "co.in", + "github.io", + "herokuapp.com", + "vercel.app", + "netlify.app", + "local.phishkit", +]; + +/// Registrable domain (approx eTLD+1). Handles compound public suffixes so +/// `app.acme.co.uk` → `acme.co.uk` instead of the naive `co.uk` (M1 / C1). pub fn upstream_domain(target_host: &str) -> String { let host = normalize_target_host(target_host); + if host.is_empty() { + return host; + } + let host_l = host.to_ascii_lowercase(); + for suffix in MULTI_PART_PUBLIC_SUFFIXES { + let dotted = format!(".{suffix}"); + if host_l == *suffix { + return host; + } + if let Some(rest) = host_l.strip_suffix(&dotted) { + // rest is labels left of the public suffix; take the last one + suffix. + let label = rest.rsplit('.').next().unwrap_or(rest); + if label.is_empty() { + return host; + } + return format!("{label}.{suffix}"); + } + } let parts: Vec<&str> = host.split('.').collect(); if parts.len() >= 3 { parts[parts.len() - 2..].join(".") @@ -217,8 +259,41 @@ mod tests { #[test] fn dryrun_and_landing_sub() { assert_eq!(upstream_domain("app.acme.com"), "acme.com"); + assert_eq!(upstream_domain("login.acme.co.uk"), "acme.co.uk"); + assert_eq!(upstream_domain("foo.bar.github.io"), "bar.github.io"); + assert_eq!( + upstream_domain("demo-cookie.local.phishkit"), + "demo-cookie.local.phishkit" + ); + assert_eq!( + upstream_domain("cookie-origin.local.phishkit"), + "cookie-origin.local.phishkit" + ); assert_eq!(default_dryrun_domain("app.acme.com"), "acme.phishkit"); assert_eq!(landing_sub("app.acme.com"), "app"); assert_eq!(landing_sub("acme.com"), ""); } } + +#[cfg(test)] +mod demo_phishlet_tests { + #[test] + fn demo_cookie_phishlet_does_not_self_proxy() { + let root = crate::kit::kit_root().expect("kit root"); + let yaml = std::fs::read_to_string(root.join("kit/evilginx/phishlets/demo-cookie.yaml")) + .expect("demo-cookie.yaml"); + // Upstream origin must be distinct from the lure hostname. + assert!( + yaml.contains("cookie-origin.local.phishkit"), + "demo-cookie.yaml must proxy to cookie-origin.local.phishkit" + ); + assert!( + !yaml.contains("domain: 'demo-cookie.local.phishkit'"), + "demo-cookie.yaml must not use the lure host as upstream domain" + ); + assert!( + yaml.contains("domain: 'cookie-origin.local.phishkit'"), + "proxy_hosts/login domain must be the origin host" + ); + } +} diff --git a/demos/cookie/README.md b/demos/cookie/README.md index b62cddf..1a419e4 100644 --- a/demos/cookie/README.md +++ b/demos/cookie/README.md @@ -1,17 +1,34 @@ -# Demo: portal (cookie session) (cookie session) +# Demo: portal (cookie session) ## Target notes | Field | Value | |-------|-------| -| Upstream mock | http://127.0.0.1:9080 | -| Start | `make demo-cookie` | -| Phishlet | `demo-cookie` (`kit/evilginx/phishlets/demo-cookie.yaml`) | -| Dry-run domain | `demo-cookie.local.phishkit` | +| HTTP mock (no AiTM) | http://127.0.0.1:9080 (`make demo-cookie`) | +| HTTPS origin (AiTM) | https://127.0.0.2:443 (`make demo-cookie-https`) | +| Upstream hostname | `cookie-origin.local.phishkit` → 127.0.0.2 | +| Lure hostname | `demo-cookie.local.phishkit` → 127.0.0.1 | +| Phishlet | `demo-cookie` | | Login path | `/login` | | Test user | `demo@phishkit.local` | | Test password | `demo-password` | +## /etc/hosts + +``` +127.0.0.1 demo-cookie.local.phishkit +127.0.0.2 cookie-origin.local.phishkit +``` + +## Privileged ports + +evilginx binds `:443` and `:53`. The HTTPS mock binds `127.0.0.2:443` so it does not collide with evilginx on `127.0.0.1`. + +```bash +sudo setcap cap_net_bind_service=+ep kit/evilginx/run/evilginx +sudo setcap cap_net_bind_service=+ep "$(command -v node)" +``` + ## Expected capture - **Credentials:** form POST fields `username` + `password` @@ -30,12 +47,4 @@ curl -s -c /tmp/pk-demo-cookie.jar -b /tmp/pk-demo-cookie.jar -L \ grep session /tmp/pk-demo-cookie.jar ``` -## Desktop Target - -1. `make desktop` -2. Create an assessment → add Target `demo-cookie.local.phishkit` -3. Import / select phishlet `demo-cookie` -4. Start destination with dry-run domain `demo-cookie.local.phishkit` -5. Apply `/etc/hosts` when prompted; open the lure in a fresh browser profile - Authorized dry-runs only. diff --git a/demos/cookie/server.ts b/demos/cookie/server.ts index ca623f4..b487bbf 100644 --- a/demos/cookie/server.ts +++ b/demos/cookie/server.ts @@ -2,7 +2,10 @@ * Cookie-session practice app for local phishkit dry-runs. * http://127.0.0.1:9080 — creds: demo@phishkit.local / demo-password */ -import { createServer, type IncomingMessage, type ServerResponse } from "node:http"; +import { createServer as createHttpServer, type IncomingMessage, type ServerResponse } from "node:http"; +import { createServer as createHttpsServer } from "node:https"; +import { existsSync, mkdirSync } from "node:fs"; +import { join } from "node:path"; import { createHmac, randomBytes } from "node:crypto"; import { parse as parseQuery } from "node:querystring"; @@ -110,7 +113,7 @@ function readBody(req: IncomingMessage): Promise { }); } -const server = createServer(async (req, res) => { +async function handle(req: IncomingMessage, res: ServerResponse) { const url = new URL(req.url ?? "/", `http://${req.headers.host ?? "localhost"}`); const path = url.pathname; console.log(`[demo-cookie] ${req.socket.remoteAddress} ${req.method} ${path}`); @@ -177,10 +180,44 @@ const server = createServer(async (req, res) => { } send(res, 404, "not found\n", "text/plain; charset=utf-8"); -}); +} + + + + +const USE_TLS = process.env.DEMO_COOKIE_TLS === "1" || process.env.DEMO_COOKIE_TLS === "true"; + +function selfSignedCert(): { key: string; cert: string } { + const { readFileSync } = require("node:fs") as typeof import("node:fs"); + const { spawnSync } = require("node:child_process") as typeof import("node:child_process"); + const dir = join(process.cwd(), "..", "run"); + try { mkdirSync(dir, { recursive: true }); } catch { /* ignore */ } + const keyPath = join(dir, "demo-cookie-key.pem"); + const certPath = join(dir, "demo-cookie-cert.pem"); + if (!(existsSync(keyPath) && existsSync(certPath))) { + const subj = "/CN=cookie-origin.local.phishkit"; + const gen = spawnSync( + "openssl", + ["req", "-x509", "-newkey", "rsa:2048", "-keyout", keyPath, "-out", certPath, "-days", "365", "-nodes", "-subj", subj], + { encoding: "utf8" }, + ); + if (gen.status !== 0) { + throw new Error(`openssl self-signed cert failed: ${gen.stderr || gen.stdout}`); + } + } + return { key: readFileSync(keyPath, "utf8"), cert: readFileSync(certPath, "utf8") }; +} + +const server = USE_TLS + ? createHttpsServer(selfSignedCert(), (req, res) => { void handle(req, res); }) + : createHttpServer((req, res) => { void handle(req, res); }); server.listen(PORT, HOST, () => { - console.log(`demo-cookie listening on http://${HOST}:${PORT}`); - console.log(` login: http://${HOST}:${PORT}/login`); + const scheme = USE_TLS ? "https" : "http"; + console.log(`demo-cookie listening on ${scheme}://${HOST}:${PORT}`); + console.log(` login: ${scheme}://${HOST}:${PORT}/login`); console.log(` creds: ${DEMO_USER} / ${DEMO_PASS}`); + if (USE_TLS) { + console.log(" hosts: 127.0.0.2 cookie-origin.local.phishkit"); + } }); diff --git a/kit/evilginx/phishlets/demo-cookie.yaml b/kit/evilginx/phishlets/demo-cookie.yaml index 85b29b9..b85f97a 100644 --- a/kit/evilginx/phishlets/demo-cookie.yaml +++ b/kit/evilginx/phishlets/demo-cookie.yaml @@ -1,26 +1,27 @@ # ============================================================================= -# demo-cookie — cookie-session dry-run against demos/cookie +# demo-cookie — cookie-session AiTM dry-run against demos/cookie # ============================================================================= # -# Upstream mock: http://127.0.0.1:9080 (make demo-cookie) -# Dry-run domain: demo-cookie.local.phishkit +# Lure host (evilginx): demo-cookie.local.phishkit → 127.0.0.1 +# Upstream origin (mock): cookie-origin.local.phishkit → 127.0.0.2 +# +# Start the HTTPS mock (needs cap_net_bind_service on node, or root): +# make demo-cookie-https # # Auth shape: POST /login (form) → Set-Cookie: session=… → /dashboard # Test creds: demo@phishkit.local / demo-password # -# Note: the mock speaks HTTP on :9080. For a full evilginx proxy dry-run you -# still need a reachable HTTPS upstream (or tunnel the mock). This phishlet is -# the capture-surface template and validates cleanly; exercise the mock directly -# or via the desktop Target notes in demos/cookie/. +# The upstream domain MUST differ from the lure hostname. Using the same host +# for both makes evilginx dial itself and never capture a session (C1). # ============================================================================= min_ver: '3.0.0' proxy_hosts: - - {phish_sub: '', orig_sub: '', domain: 'demo-cookie.local.phishkit', session: true, is_landing: true, auto_filter: true} + - {phish_sub: '', orig_sub: '', domain: 'cookie-origin.local.phishkit', session: true, is_landing: true, auto_filter: true} auth_tokens: - - domain: '.demo-cookie.local.phishkit' + - domain: '.cookie-origin.local.phishkit' keys: - 'session' - 'access_token,opt' @@ -38,5 +39,5 @@ credentials: type: 'post' login: - domain: 'demo-cookie.local.phishkit' + domain: 'cookie-origin.local.phishkit' path: '/login' diff --git a/kit/evilginx/scripts/configure_lure.py b/kit/evilginx/scripts/configure_lure.py index c194c46..3369621 100644 --- a/kit/evilginx/scripts/configure_lure.py +++ b/kit/evilginx/scripts/configure_lure.py @@ -350,25 +350,64 @@ def _resolve_lure_path(ops: dict) -> str: first_path = f"/{first_path}" if first_path else _pick_lure_path(phishlet) return lure_from_config(dryrun_domain, phishlet) or f"https://{landing_host}{first_path}" -def _https_port_listening() -> bool: - probe = subprocess.run( - ["lsof", "-nP", "-iTCP:443", "-sTCP:LISTEN", "-t"], - capture_output=True, - text=True, - check=False, - ) - return bool(probe.stdout.strip()) +def _https_port_listening(port: int = 443) -> bool: + """True when something is accepting TCP on `port`. + + Prefer a real connect to 127.0.0.1 (works without lsof/ss and matches what a + browser will hit). Fall back to `ss` / `lsof` for environments where connect + is filtered. Previously we only used `lsof`, which is often missing and + produced false "did not bind" failures while evilginx was already LISTEN. + """ + import socket + try: + with socket.create_connection(("127.0.0.1", port), timeout=0.35): + return True + except OSError: + pass + + try: + ss = subprocess.run( + ["ss", "-ltn"], + capture_output=True, + text=True, + check=False, + ) + if ss.returncode == 0 and ss.stdout: + needle = f":{port} " + for line in ss.stdout.splitlines(): + if "LISTEN" in line and (needle in line or line.rstrip().endswith(f":{port}")): + return True + except FileNotFoundError: + pass -def _wait_https_port(timeout_sec: float = 12.0) -> None: + try: + lsof = subprocess.run( + ["lsof", "-nP", f"-iTCP:{port}", "-sTCP:LISTEN", "-t"], + capture_output=True, + text=True, + check=False, + ) + return bool(lsof.stdout and lsof.stdout.strip()) + except FileNotFoundError: + return False + + +def _wait_https_port(timeout_sec: float = 25.0) -> None: deadline = time.time() + timeout_sec while time.time() < deadline: if _https_port_listening(): return time.sleep(0.25) + # Final re-check after a short grace: the process may have bound in the + # last tick, and a single missed probe should not fail a healthy start. + time.sleep(0.5) + if _https_port_listening(): + return raise ConfigureError( "evilginx did not bind HTTPS port 443 in time — " - "check evilginx.log (port in use or need elevated privileges)." + "check evilginx.log (port in use, or grant cap_net_bind_service / run as root). " + "See docs: privileged ports for :443/:53." ) diff --git a/scripts/test-https-bind-probe.sh b/scripts/test-https-bind-probe.sh new file mode 100755 index 0000000..4be689b --- /dev/null +++ b/scripts/test-https-bind-probe.sh @@ -0,0 +1,89 @@ +#!/usr/bin/env bash +# Smoke/unit tests for the evilginx HTTPS bind probe (C1 false-negative fix). +set -euo pipefail +cd "$(dirname "$0")/.." +python3 - <<'PY' +import importlib.util +import socket +import threading +import time +import traceback +from pathlib import Path + +SCRIPT = Path("kit/evilginx/scripts/configure_lure.py") +spec = importlib.util.spec_from_file_location("configure_lure", SCRIPT) +mod = importlib.util.module_from_spec(spec) +assert spec.loader is not None +spec.loader.exec_module(mod) + +failures = 0 + +def check(name, fn): + global failures + try: + fn() + print(f"ok {name}") + except Exception as e: + failures += 1 + print(f"FAIL {name}: {e}") + traceback.print_exc() + +def test_false_when_free(): + s = socket.socket() + s.bind(("127.0.0.1", 0)) + port = s.getsockname()[1] + s.close() + time.sleep(0.05) + assert mod._https_port_listening(port) is False + +def test_true_when_listening(): + srv = socket.socket() + srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + srv.bind(("127.0.0.1", 0)) + srv.listen(1) + port = srv.getsockname()[1] + def _accept(): + try: + c, _ = srv.accept() + c.close() + except OSError: + pass + t = threading.Thread(target=_accept, daemon=True) + t.start() + try: + assert mod._https_port_listening(port) is True + finally: + srv.close() + t.join(timeout=1) + +def test_late_bind(): + srv = socket.socket() + srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + srv.bind(("127.0.0.1", 0)) + port = srv.getsockname()[1] + def _late(): + time.sleep(0.4) + try: + srv.listen(1) + c, _ = srv.accept() + c.close() + except OSError: + pass + t = threading.Thread(target=_late, daemon=True) + t.start() + ok = False + deadline = time.time() + 3 + while time.time() < deadline: + if mod._https_port_listening(port): + ok = True + break + time.sleep(0.1) + srv.close() + t.join(timeout=1) + assert ok + +check("false_when_free", test_false_when_free) +check("true_when_listening", test_true_when_listening) +check("late_bind", test_late_bind) +raise SystemExit(failures) +PY