Skip to content

reconFTW is a tool designed to perform automated recon on a target domain by running the best set of tools to perform scanning and finding out vulnerabilities

changelog updated with everything for v4.0 big changes, in testing

six2dez19436d9c026f
diff --git a/.github/workflows/docker_nightly.yml b/.github/workflows/docker_nightly.yml
index d220095..f000529 100644
--- a/.github/workflows/docker_nightly.yml
+++ b/.github/workflows/docker_nightly.yml
@@ -41,3 +41,9 @@ jobs:
context: ./Docker
push: true
tags: six2dez/reconftw:main
+
+ - name: Verify image health
+ run: |
+ docker pull six2dez/reconftw:main
+ docker run --rm six2dez/reconftw:main --help
+ docker run --rm six2dez/reconftw:main --health-check
diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml
index a8b9280..961716a 100644
--- a/.github/workflows/tests.yml
+++ b/.github/workflows/tests.yml
@@ -2,88 +2,75 @@ name: tests
permissions:
contents: read
- issues: write
- pull-requests: write
- actions: read
- checks: read
- deployments: read
- discussions: read
- packages: read
- repository-projects: read
- security-events: read
- statuses: read
-on: [push, pull_request]
+on:
+ push:
+ pull_request:
+ workflow_dispatch:
+ inputs:
+ run_full_integration:
+ description: Run full integration suite
+ required: false
+ default: "false"
+ type: choice
+ options:
+ - "false"
+ - "true"
+ schedule:
+ - cron: "0 3 * * 0"
jobs:
shellcheck:
- name: ShellCheck
+ name: shellcheck
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
- - name: Install ShellCheck
- run: sudo apt-get install -y shellcheck
+ - name: Install shellcheck
+ run: sudo apt-get update && sudo apt-get install -y shellcheck
- - name: Run ShellCheck on reconftw.sh
- run: shellcheck -S warning reconftw.sh
+ - name: Run shellcheck
+ run: shellcheck -S warning reconftw.sh modules/*.sh lib/*.sh install.sh
- - name: Run ShellCheck on modules
- run: shellcheck -S warning modules/*.sh
- continue-on-error: true
-
- - name: Run ShellCheck on install.sh
- run: shellcheck -S warning install.sh
- continue-on-error: true
-
- unit-tests:
- name: Unit Tests
+ unit-fast:
+ name: unit-fast
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
- - name: Install bats-core
- run: |
- git clone https://github.com/bats-core/bats-core.git /tmp/bats
- sudo /tmp/bats/install.sh /usr/local
+ - name: Install dependencies
+ run: sudo apt-get update && sudo apt-get install -y bats jq
- name: Run unit tests
- run: bats tests/unit/*.bats
-
- tests:
- strategy:
- fail-fast: false
- matrix:
- os:
- - ubuntu-latest
-
- name: ${{ matrix.os }}
- runs-on: ${{ matrix.os }}
+ run: ./tests/run_tests.sh --unit
+ integration-smoke:
+ name: integration-smoke
+ runs-on: ubuntu-latest
+ needs:
+ - unit-fast
steps:
- - name: Install bash from homebrew
- if: ${{ startsWith(matrix.os, 'macos-') }}
- run: brew install bash
-
- name: Checkout code
uses: actions/checkout@v4
- with:
- fetch-depth: 0 # full history for git describe
- - name: Fetch tags
- run: git fetch --force --prune --tags
+ - name: Install dependencies
+ run: sudo apt-get update && sudo apt-get install -y bats jq
- - name: Install reconFTW
- shell: bash
- continue-on-error: true
- run: ./install.sh
+ - name: Run integration smoke tests
+ run: ./tests/run_tests.sh --smoke
+
+ integration-full:
+ name: integration-full
+ runs-on: ubuntu-latest
+ if: github.event_name == 'schedule' || (github.event_name == 'workflow_dispatch' && github.event.inputs.run_full_integration == 'true')
+ steps:
+ - name: Checkout code
+ uses: actions/checkout@v4
- - name: Check if all tools are installed
- shell: bash
- run: ./reconftw.sh --check-tools || true
+ - name: Install dependencies
+ run: sudo apt-get update && sudo apt-get install -y bats jq
- - name: Check if chromium dependencies are installed
- shell: bash
- run: nuclei -headless -id screenshot
+ - name: Run full integration tests
+ run: ./tests/run_tests.sh --integration
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b994ecb..76679f0 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,12 +5,12 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
-## [v4.0] - 2026-02-05 Major Release
+## [v4.0] - 2026-02-06
### Added
**Modular Architecture**
-- Split monolithic script into 8 focused modules under `modules/`:
+- Split monolithic script into focused modules under `modules/`:
- `core.sh` — lifecycle, logging, notifications, cleanup
- `modes.sh` — scan modes and argument parsing
- `subdomains.sh` — subdomain enumeration
@@ -19,124 +19,125 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- `osint.sh` — OSINT functions
- `axiom.sh` — Axiom fleet helpers
- `utils.sh` — shared utilities
-- Validation library at `lib/validation.sh` for input sanitization
-
-**New CLI Flags**
-- `--health-check` — system diagnostics before scanning
-- `--dry-run` — preview commands without execution
-- `--parallel` — run independent functions in parallel (faster, more RAM)
-- `--source-only` — source functions without running (for testing/scripting)
-
-**Robustness Features**
-- Circuit breaker pattern: auto-skip tools after repeated failures
-- Checkpoint system: resume scans from last successful phase
-- Adaptive rate limiting on 429/503 responses
-- Disk space pre-flight check (`MIN_DISK_SPACE_GB`)
-- Log rotation (`MAX_LOG_FILES`, `MAX_LOG_AGE_DAYS`)
-- Cleanup traps for graceful shutdown
-
-**Input Validation**
-- `sanitize_domain()` strips dangerous characters and converts to lowercase
-- `validate_file_exists()`, `validate_file_readable()` for `--list`, `--inscope`, etc.
-- `validate_custom_function()` ensures `-c` targets exist before execution
-
-**Testing**
-- 100+ bats tests covering unit, integration, and security scenarios
-- `tests/security/test_injection.bats` for command injection prevention
-- `tests/mocks/` for offline testing
-- Makefile targets: `make test`, `make lint`, `make test-security`
-
-**Other**
-- 6 new ASCII banners (#25-30)
-- `secrets.cfg` support (gitignored) for API keys
-- Performance timing summary at scan completion
-- DEEP mode helpers: `should_run_deep_*()` functions
-
-**Deep Wildcard Detection** (Based on DEF CON Subdomain Enumeration research)
-- `deep_wildcard_filter()` - Iterative wildcard detection at all subdomain levels
-- `DEEP_WILDCARD_FILTER` config option to enable/disable
-- Prevents false positives from nested wildcard DNS records
-
-**Time-Based Certificate Filtering**
-- `DNS_TIME_FENCE_DAYS` config option to filter crt.sh results by age
-- Recommended value: 90 days to focus on recent certificates
-- Set to 0 to disable (default, backward compatible)
-
-**Sensitive Domain Exclusion**
-- `EXCLUDE_SENSITIVE` config option to skip scanning sensitive domains
-- `config/sensitive_domains.txt` - Curated list of patterns to exclude:
- - Government domains (*.gov, *.gob.*, *.gouv.*)
- - Military domains (*.mil)
- - Education domains (*.edu)
- - Financial institutions
- - Healthcare organizations
-- `_is_sensitive_domain()` helper function for pattern matching
-
-**Parallelization Framework** (lib/parallel.sh)
-- `parallel_run()` - Run commands in parallel with configurable job limit
-- `parallel_funcs()` - Run bash functions in parallel subshells
-- `parallel_passive_enum()` - Parallel passive subdomain enumeration
-- `parallel_active_enum()` - Parallel active DNS checks
-- `parallel_postactive_enum()` - Parallel TLS/analytics (after resolution)
-- `parallel_brute_enum()` - Resource-limited parallel brute force
-- `parallel_web_vulns()` - Parallel web vulnerability scanning
-- `parallel_subdomains_full()` - Full parallelized subdomain orchestration
-
-**Common Utilities Library** (lib/common.sh)
-- `ensure_dirs()` - Create multiple directories safely
-- `safe_backup()` - Backup files with timestamps
-- `skip_notification()` - Standardized skip logging
-- `count_lines()`, `safe_count()` - Safe line counting
-- `dedupe_append()` - Append and deduplicate
-- `run_tool()` - Execute with timeout and error handling
-- `should_run_function()` - Checkpoint-aware function check
-
-**Integration Tests**
-- `tests/integration/test_full_flow.bats` - 17 tests for complete workflow
-- `tests/integration/test_checkpoint.bats` - 20 tests for resume functionality
-- Total test count: 164
-
-**Refactored Functions**
-- `subdomains_full()` decomposed into `_subdomains_init()`, `_subdomains_enumerate()`, `_subdomains_finalize()`
-- `webprobe_*()` uses shared helpers `_run_httpx()`, `_process_httpx_output()`
-- `--parallel` flag support for subdomain enumeration
+- Validation library at `lib/validation.sh` for input sanitization.
+- Shared libraries in `lib/common.sh` and `lib/parallel.sh`.
+
+**New CLI and Runtime Modes**
+- `--health-check` for system diagnostics.
+- `--dry-run` to preview commands.
+- `--parallel` to run independent functions in parallel.
+- `--no-parallel` to force sequential mode.
+- `--source-only` for sourcing/testing workflows.
+- Continuous monitoring mode:
+ - `--monitor`
+ - `--monitor-interval <minutes>`
+ - `--monitor-cycles <n>` (0 = infinite)
+- `--report-only` to rebuild report artifacts from existing outputs.
+- `--refresh-cache` to force cache refresh.
+- `--export json|html|csv|all` export pipeline.
+
+**Reporting and Output**
+- Consolidated reporting artifacts:
+ - `report/report.json`
+ - `report/index.html`
+ - `report/latest/report.json`
+ - `report/latest/index.html`
+- Export artifacts:
+ - JSONL: `report/findings_normalized.jsonl`, `report/export_all.jsonl`
+ - CSV: `report/subdomains.csv`, `report/webs.csv`, `report/hosts.csv`, `report/findings.csv`
+- Delta sections and timeline in report outputs.
+- Monitor history snapshots under `.incremental/history/<timestamp>/`.
+- Per-cycle alert summary at `.incremental/history/<timestamp>/alerts.json`.
+- Machine-readable run summary at `.log/perf_summary.json`.
+- Structured JSON logging support (`STRUCTURED_LOGGING=true`) with function/subfunction start/end events.
+
+**AI and Automation Enhancements**
+- AI report generation integrated with local models via `reconftw_ai`.
+- AI profiles: `executive`, `brief`, `bughunter`.
+- Structured AI output artifact: `ai_result/reconftw_analysis.json`.
+- Human AI report artifact: `ai_result/reconftw_analysis_<profile>_<timestamp>.md|txt`.
+- New AI configuration controls:
+ - `AI_EXECUTABLE`
+ - `AI_PROMPTS_FILE`
+ - `AI_MAX_CHARS_PER_FILE`
+ - `AI_MAX_FILES_PER_CATEGORY`
+ - `AI_REDACT`
+ - `AI_ALLOW_MODEL_PULL`
+ - `AI_STRICT`
+
+**Configuration and Profiles**
+- New profile configs:
+ - `config/reconftw_quick.cfg`
+ - `config/reconftw_full.cfg`
+ - `config/reconftw_stealth.cfg`
+- Port lists externalized for easier maintenance:
+ - `config/tls_ports.txt`
+ - `config/uncommon_ports_web.txt`
+- Typed cache TTL controls:
+ - `CACHE_MAX_AGE_DAYS_RESOLVERS`
+ - `CACHE_MAX_AGE_DAYS_WORDLISTS`
+ - `CACHE_MAX_AGE_DAYS_TOOLS`
+
+**Recon and Enumeration Enhancements**
+- ASN enumeration via `sub_asn()` using `asnmap`.
+- New `ASN_ENUM` option and outputs:
+ - `hosts/asn_numbers.txt`
+ - `hosts/asn_cidrs.txt`
+- Deep wildcard detection (`DEEP_WILDCARD_FILTER`) based on iterative wildcard checks.
+- Time-based certificate filtering (`DNS_TIME_FENCE_DAYS`).
+- Sensitive domain exclusion (`EXCLUDE_SENSITIVE`, `config/sensitive_domains.txt`).
+
+**Progress and UX**
+- Progress/ETA functions (`progress_init()`, `progress_step()`) integrated in recon flows.
+- Better quick-rescan and monitor UX with adjusted totals and explicit cycle behavior.
+
+**Testing and Tooling**
+- Expanded BATS test coverage (unit/integration/security) and mocks.
+- Integration tests for full flow and checkpoint behavior.
+- Additional test helpers/scripts for artifact and mode validation.
-### Fixed
-
-**Security**
-- Fixed unquoted variable in `file $1` → `file "$1"` (core.sh)
-- Fixed unquoted AI command variables (modes.sh)
-- Fixed unquoted HTTPX_FLAGS (web.sh)
-- Added NUMOFLINES validation with fallback to 0
-
-**Parallelization Order**
-- `sub_tls` and `sub_analytics` now run AFTER `sub_active` (require resolved subdomains)
-
-**List Mode (-l flag)**
-- Fixed bug where only first domain in target list was processed
-- Changed while loops to use dedicated file descriptor (FD 3)
-- Prevents internal commands from consuming stdin and breaking the loop
-- Now correctly processes all domains in the list sequentially
+### Changed
-**Others**
-- macOS compatibility: `stat`, `df`, `sed` commands now detect OS correctly
-- Syntax error in `vulns.sh` (pipe at wrong line position)
-- Timing summary crash when function names contained spaces
-- Readonly variable error when re-sourcing the script
-- Duplicate nuclei findings (domain vs URL targeting same host)
+- Main script reduced to entry-point style with modular delegation.
+- Module loading order updated to include shared libraries (`lib/common.sh`, `lib/parallel.sh`).
+- Replaced repetitive utility patterns with centralized helpers:
+ - `ensure_dirs()`
+ - `skip_notification()`
+ - `count_lines()`/`safe_count()`
+ - `run_tool()`
+ - `should_run_function()`
+- Profile configuration behavior changed to override-only semantics (preserving preloaded secrets/env).
+- Nuclei targeting adjusted to prioritize URL-with-protocol inputs and reduce duplicate host scans.
+- Parallel scheduler improved with backpressure signals from adaptive rate limiting.
+- Threading/performance tuning improved with `PERF_PROFILE` (`low|balanced|max`).
-### Changed
+### Fixed
-- Replaced 107 duplicate `mkdir -p` patterns with `ensure_dirs()`
-- Replaced skip notification printf patterns with `skip_notification()`
-- Module loading order updated to include lib/common.sh and lib/parallel.sh
-- Main script reduced from ~7000 to ~500 lines (entry point only)
-- Nuclei scans now use only URLs with protocol, avoiding duplicate scans
-- All API keys use env-var fallback pattern (`${VAR:-}`)
-- Interactsh process tracked by PID instead of `pkill -f`
+**Stability and Correctness**
+- List mode (`-l`) now processes all targets reliably (FD-safe loops).
+- Fixed syntax/runtime edge cases in module scripts.
+- Corrected timing/perf summary handling edge cases.
+- Resolved readonly/re-source issues in script lifecycle.
+- Fixed duplicate findings/reporting edge cases.
+- Corrected `sub_asn()` behavior to avoid redundant repeated runs.
+- Corrected host matching in WAF/slow-host grouping to literal-safe comparisons.
+- Parallel group failures now propagate correctly instead of being silently ignored.
+
+**CI/CD and Docker**
+- ShellCheck failures now fail CI (removed permissive `continue-on-error`).
+- Added Docker nightly verification steps (`--help`, `--health-check`).
+- Nightly image health-check failures now fail workflows.
+- Docker image security improved by generating Axiom SSH keys at runtime via `Docker/entrypoint.sh` instead of build-time.
+
+**Cross-platform/Operational Fixes**
+- Improved macOS compatibility for `stat`, `df`, and `sed` behavior.
+- Improved cache lifecycle behavior and runtime refresh handling.
+- Progress totals now correctly account for quick-rescan skips and execution model differences.
### Security
-- Removed all `eval` on user input
-- Input sanitization prevents shell metacharacter injection
-- Secrets redacted from logs when `SHOW_COMMANDS=true`
-- File permission checks for `secrets.cfg`
+
+- Removed unsafe `eval` usage on user-influenced input paths.
+- Hardened input sanitization against shell metacharacter injection.
+- Improved quoting and command construction across modules.
+- Secrets handling hardened (`secrets.cfg` checks, env fallback patterns, log redaction with command tracing).
+- Docker key handling moved to runtime generation to avoid shared-key risk across images.
diff --git a/Docker/Dockerfile b/Docker/Dockerfile
index c814c71..c439851 100644
--- a/Docker/Dockerfile
+++ b/Docker/Dockerfile
@@ -10,7 +10,7 @@ ARG LANGUAGE=en_US
###> Do NOT change anything beyond this point <###
##################################################
-FROM ubuntu:latest AS base
+FROM ubuntu:24.04 AS base
LABEL org.label-schema.name='reconftw'
LABEL org.label-schema.description='A simple script for full recon'
@@ -107,7 +107,7 @@ find /var/cache -type f -delete
find /var/log -type f -delete
find /tmp -type f -delete
rm -rf /root/.cache
-rm -rf /root/go
+rm -rf /root/go/pkg /root/go/src
eot
COPY github_tokens.txt /root/Tools/.github_tokens
@@ -118,15 +118,11 @@ RUN <<eot
#!/bin/bash
set -euxo pipefail
if [ "${INSTALL_AXIOM}" = "true" ]; then
- ###>> Regenerate SSH Keys <<###
apt update && apt install -y --no-install-recommends openssh-client
mkdir -p /root/.ssh
mkdir -p /root/.axiom/configs
- ssh-keygen -b 2048 -t rsa -f /root/.ssh/axiom_rsa -q -N ""
- cat /root/.ssh/axiom_rsa.pub > /root/.axiom/configs/authorized_keys
-
apt remove --purge -y openssh-client && apt autoremove -y && apt clean all
find /var/lib/apt/lists -type f -delete
find /var/cache -type f -delete
@@ -155,5 +151,8 @@ WORKDIR /reconftw
HEALTHCHECK --interval=60s --timeout=30s --retries=3 \
CMD ./reconftw.sh --health-check || exit 1
-ENTRYPOINT [ "./reconftw.sh" ]
+COPY entrypoint.sh /entrypoint.sh
+RUN chmod +x /entrypoint.sh
+
+ENTRYPOINT [ "/entrypoint.sh" ]
CMD [ "--help" ]
diff --git a/Docker/entrypoint.sh b/Docker/entrypoint.sh
new file mode 100644
index 0000000..e27b66c
--- /dev/null
+++ b/Docker/entrypoint.sh
@@ -0,0 +1,9 @@
+#!/bin/bash
+# Generate Axiom SSH keys at runtime if they don't exist
+if [[ "${INSTALL_AXIOM}" == "true" ]] && [[ ! -f /root/.ssh/axiom_rsa ]]; then
+ mkdir -p /root/.ssh /root/.axiom/configs
+ ssh-keygen -b 4096 -t rsa -f /root/.ssh/axiom_rsa -q -N ""
+ cat /root/.ssh/axiom_rsa.pub > /root/.axiom/configs/authorized_keys
+fi
+
+exec ./reconftw.sh "$@"
diff --git a/Makefile b/Makefile
index 620db8e..545cea3 100644
--- a/Makefile
+++ b/Makefile
@@ -1,12 +1,16 @@
GH_CLI := $(shell command -v gh 2> /dev/null)
PRIVATE_REPO := $(shell echo $${PRIV_REPO-reconftw-data})
-.PHONY: sync upload bootstrap rm lint lint-fix fmt test test-all test-security setup-dev help
+.PHONY: sync upload bootstrap rm lint lint-fix fmt test test-all test-security test-unit test-integration-smoke test-integration-full test-release-gate setup-dev help
help:
@echo "reconFTW Development Commands"
@echo ""
@echo " make test - Run unit tests"
+ @echo " make test-unit - Run unit tests"
+ @echo " make test-integration-smoke - Run integration smoke tests"
+ @echo " make test-integration-full - Run full integration tests"
+ @echo " make test-release-gate - Run release quality gate checks"
@echo " make test-all - Run all tests (unit + integration)"
@echo " make test-security - Run security tests"
@echo " make lint - Check code with shellcheck"
@@ -71,7 +75,31 @@ fmt:
test:
@if command -v bats >/dev/null 2>&1; then \
- bats tests/unit/*.bats; \
+ ./tests/run_tests.sh --unit; \
+ else \
+ echo "bats-core not found. Install: https://github.com/bats-core/bats-core"; \
+ exit 1; \
+ fi
+
+test-unit:
+ @if command -v bats >/dev/null 2>&1; then \
+ ./tests/run_tests.sh --unit; \
+ else \
+ echo "bats-core not found. Install: https://github.com/bats-core/bats-core"; \
+ exit 1; \
+ fi
+
+test-integration-smoke:
+ @if command -v bats >/dev/null 2>&1; then \
+ ./tests/run_tests.sh --smoke; \
+ else \
+ echo "bats-core not found. Install: https://github.com/bats-core/bats-core"; \
+ exit 1; \
+ fi
+
+test-integration-full:
+ @if command -v bats >/dev/null 2>&1; then \
+ ./tests/run_tests.sh --integration; \
else \
echo "bats-core not found. Install: https://github.com/bats-core/bats-core"; \
exit 1; \
@@ -87,12 +115,23 @@ test-security:
test-all:
@if command -v bats >/dev/null 2>&1; then \
- bats tests/unit/*.bats tests/security/*.bats; \
+ ./tests/run_tests.sh --all; \
else \
echo "bats-core not found. Install: https://github.com/bats-core/bats-core"; \
exit 1; \
fi
+test-release-gate:
+ @bash -n reconftw.sh modules/*.sh lib/*.sh
+ @./tests/run_tests.sh --unit
+ @./tests/run_tests.sh --smoke
+ @if [ -f Recon/*/.log/perf_summary.json ]; then \
+ latest=$$(ls -1t Recon/*/.log/perf_summary.json | head -n1); \
+ tests/bench/compare_baseline.sh tests/bench/baseline_metrics.json "$$latest"; \
+ else \
+ echo "[INFO] No perf summary found under Recon/*/.log; skipping perf regression gate"; \
+ fi
+
setup-dev:
@if command -v pre-commit >/dev/null 2>&1; then \
pre-commit install; \
diff --git a/README.md b/README.md
index dbc8b08..4158d40 100644
--- a/README.md
+++ b/README.md
@@ -198,6 +198,7 @@ reconFTW is packed with features to make reconnaissance thorough and efficient.
- **Hotlist Builder**: Scores and highlights the riskiest assets (`hotlist.txt`) based on new findings.
- **Command Tracing**: Toggle `SHOW_COMMANDS` to log every executed command into target logs for debugging.
- **Asset Store**: Appends findings to `assets.jsonl` for downstream automation when `ASSET_STORE` is enabled.
+- **Consolidated Report**: Auto-generates `report/report.json` and `report/index.html` at end of scan.
- **ARM Support**: Compatible with Raspberry Pi and ARM architectures (including MacOS MX).
- **Health Check**: Built-in system health check via `--health-check` (also used by Docker `HEALTHCHECK`).
- **Incremental Mode**: Only scan new findings since last run (`--incremental`).
@@ -205,7 +206,7 @@ reconFTW is packed with features to make reconnaissance thorough and efficient.
- **Structured Logging**: Optional JSON log output for advanced analysis (`STRUCTURED_LOGGING`).
- **Input Sanitization**: All user input is sanitized to prevent command injection.
- **Dry-Run Mode**: Preview what would be executed without running commands (`--dry-run`).
-- **Parallel Mode**: Run independent functions in parallel for faster scans (`--parallel`).
+- **Parallel Mode**: Run independent functions in parallel for faster scans (`--parallel`, disable with `--no-parallel`).
- **Modular Architecture**: Codebase split into 8 focused modules for maintainability.
- **Secrets Management**: Environment variables, `secrets.cfg`, and Docker runtime secrets (see [SECURITY.md](SECURITY.md)).
- **Circuit Breaker**: Automatically skips tools after repeated failures to avoid scan hangs.
@@ -416,7 +417,7 @@ The `reconftw.cfg` file controls the entire execution of reconFTW. It allows fin
- **Incremental Scanning**: Only scan new findings since last run (`INCREMENTAL_MODE`).
- **Notifications**: Set up Slack, Discord, or Telegram notifications (`NOTIFY_CONFIG`).
- **Axiom**: Configure distributed scanning and resolver paths (`AXIOM_FLEET_NAME`, `AXIOM_FLEET_COUNT`, `AXIOM_RESOLVERS_PATH`).
-- **AI Reporting**: Select AI model and report format (`AI_MODEL`, `AI_REPORT_TYPE`).
+- **AI Reporting**: Configure model/profile/format and context controls (`AI_MODEL`, `AI_REPORT_PROFILE`, `AI_REPORT_TYPE`, `AI_MAX_CHARS_PER_FILE`).
- **Advanced Web Checks**: Toggle GraphQL introspection, parameter discovery, WebSocket testing, gRPC probing, and IPv6 scanning.
- **Automation & Data**: Control quick rescan heuristics, asset logging, chunk sizes, hotlists, and debug tracing (`QUICK_RESCAN`, `ASSET_STORE`, `CHUNK_LIMIT`, `HOTLIST_TOP`, `SHOW_COMMANDS`).
- **Disk & Logging**: Pre-flight disk check (`MIN_DISK_SPACE_GB`), log rotation (`MAX_LOG_FILES`, `MAX_LOG_AGE_DAYS`), structured JSON logging (`STRUCTURED_LOGGING`).
@@ -455,6 +456,11 @@ MIN_DISK_SPACE_GB=0 # Minimum required disk space in GB before starting reconnai
# Incremental mode configuration
INCREMENTAL_MODE=false # Only scan new findings since last run (use --incremental flag to enable)
+MONITOR_MODE=false # Continuous monitor mode (enabled by --monitor)
+MONITOR_INTERVAL_MIN=60 # Minutes between monitoring cycles
+MONITOR_MAX_CYCLES=0 # 0 = run forever until interrupted
+ALERT_SUPPRESSION=true # Suppress repeated monitor alerts by fingerprint history
+ALERT_SEEN_FILE=".incremental/alerts_seen.hashes" # Store of seen alert fingerprints
# Adaptive rate limiting configuration
ADAPTIVE_RATE_LIMIT=false # Automatically adjust rate limits when encountering 429/503 errors (use --adaptive-rate flag to enable)
@@ -465,6 +471,10 @@ RATE_LIMIT_INCREASE_FACTOR=1.2 # Multiply rate by this on success (1.2 = 20% fas
# Cache configuration
CACHE_MAX_AGE_DAYS=30 # Maximum age in days for cached wordlists/resolvers (30 = 1 month)
+CACHE_MAX_AGE_DAYS_RESOLVERS=7 # Resolver cache TTL
+CACHE_MAX_AGE_DAYS_WORDLISTS=30 # Wordlist cache TTL
+CACHE_MAX_AGE_DAYS_TOOLS=14 # Tool cache TTL
+CACHE_REFRESH=false # Force-refresh cache (or use --refresh-cache)
# Log rotation
MAX_LOG_FILES=10 # Maximum number of log files to keep per target
@@ -634,15 +644,16 @@ HTTPX_FLAGS=" -follow-redirects -random-agent -status-code -silent -title -web-s
# HTTP options
HEADER="User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:72.0) Gecko/20100101 Firefox/72.0" # Default header
-# Threads
-FFUF_THREADS=40
-HTTPX_THREADS=50
-HTTPX_UNCOMMONPORTS_THREADS=100
-KATANA_THREADS=20
-BRUTESPRAY_THREADS=20
-BRUTESPRAY_CONCURRENCE=10
-DNSTAKE_THREADS=100
-DALFOX_THREADS=200
+# Threads (auto-scaled based on CPU cores, override to set fixed values)
+AVAILABLE_CORES=$(nproc 2>/dev/null || sysctl -n hw.ncpu 2>/dev/null || echo 4)
+FFUF_THREADS=$((AVAILABLE_CORES * 10))
+HTTPX_THREADS=$((AVAILABLE_CORES * 12))
+HTTPX_UNCOMMONPORTS_THREADS=$((AVAILABLE_CORES * 25))
+KATANA_THREADS=$((AVAILABLE_CORES * 5))
+BRUTESPRAY_THREADS=$((AVAILABLE_CORES * 5))
+BRUTESPRAY_CONCURRENCE=$((AVAILABLE_CORES * 2))
+DNSTAKE_THREADS=$((AVAILABLE_CORES * 25))
+DALFOX_THREADS=$((AVAILABLE_CORES * 50))
PUREDNS_PUBLIC_LIMIT=0 # Set between 2000 - 10000 if your router blows up, 0 means unlimited
PUREDNS_TRUSTED_LIMIT=400
PUREDNS_WILDCARDTEST_LIMIT=30
@@ -699,9 +710,16 @@ FARADAY_PASS="FARADAY_PASSWORD" # Faraday password
FARADAY_WORKSPACE="reconftw" # Faraday workspace
# AI
+AI_EXECUTABLE="python3" # Python executable fallback if reconftw_ai venv python is not available
AI_MODEL="llama3:8b" # Model to use
AI_REPORT_TYPE="md" # Report type to use (md, txt)
AI_REPORT_PROFILE="bughunter" # Report profile to use (executive, brief, or bughunter)
+AI_PROMPTS_FILE="" # Optional custom prompts file (empty uses reconftw_ai default)
+AI_MAX_CHARS_PER_FILE=50000 # Max chars loaded per file before truncation
+AI_MAX_FILES_PER_CATEGORY=200 # Max files loaded per category for AI context
+AI_REDACT=true # Redact sensitive indicators before AI analysis
+AI_ALLOW_MODEL_PULL=false # Allow reconftw_ai to auto-pull missing model
+AI_STRICT=false # Fail AI analysis if one or more categories have no data
# API & Advanced Web Checks
GRAPHQL_CHECK=true # Detect GraphQL endpoints and introspection
@@ -717,12 +735,15 @@ ARJUN_THREADS=10
# Data & Automation
ASSET_STORE=true # Append assets/findings to assets.jsonl
+EXPORT_FORMAT="" # Optional exporter at end of scan: json|html|csv|all
+REPORT_ONLY=false # Rebuild report artifacts from existing results (or use --report-only)
QUICK_RESCAN=false # Skip heavy steps if no new subdomains/webs
CHUNK_LIMIT=2000 # Split very large lists into chunks (urls, webs)
HOTLIST_TOP=50 # Number of top risky assets to highlight
# Performance
RESOLVER_IQ=false # Prefer fast/healthy resolvers (experimental)
+PERF_PROFILE="balanced" # low|balanced|max
# Intrusive controls (keep false by default)
INTRUSIVE=false # Enable intrusive cloud write/CORS tests (dangerous)
@@ -799,6 +820,13 @@ reconFTW supports multiple modes and options for flexible reconnaissance. Use th
| `--adaptive-rate` | Automatically adjust rate limits on errors (429/503) |
| `--dry-run` | Show what would be executed without running commands |
| `--parallel` | Run independent functions in parallel (faster, more RAM) |
+| `--no-parallel` | Force sequential execution even if parallel is enabled |
+| `--monitor` | Continuous monitoring mode (single target; `-w` supports `-l`) |
+| `--monitor-interval` | Minutes between monitor cycles |
+| `--monitor-cycles` | Stop after N cycles (0 = infinite) |
+| `--report-only` | Rebuild report artifacts without scanning |
+| `--refresh-cache` | Force refresh of cached resolvers/wordlists |
+| `--export` | Export artifacts: `json`, `html`, `csv`, or `all` |
### Example Usage
@@ -826,29 +854,54 @@ reconFTW supports multiple modes and options for flexible reconnaissance. Use th
./reconftw.sh -d target.com -r --parallel
```
-5. **Multi-Domain Recon**:
+5. **Force Sequential Mode**:
+
+ ```bash
+ ./reconftw.sh -d target.com -r --no-parallel
+ ```
+6. **Multi-Domain Recon**:
```bash
./reconftw.sh -m company -l domains.txt -r
```
-5. **Axiom Integration**:
+7. **Axiom Integration**:
```bash
./reconftw.sh -d target.com -r -v
```
-6. **Full Recon with Attacks (YOLO Mode)**:
+8. **Full Recon with Attacks (YOLO Mode)**:
```bash
./reconftw.sh -d target.com -a
```
-7. **Show Help**:
+9. **Show Help**:
```bash
./reconftw.sh -h
```
+10. **Force cache refresh**:
+ ```bash
+ ./reconftw.sh -d target.com -r --refresh-cache
+ ```
+
+11. **Export all report artifacts**:
+ ```bash
+ ./reconftw.sh -d target.com -r --export all
+ ```
+
+12. **Continuous monitoring (every 30m, 48 cycles)**:
+ ```bash
+ ./reconftw.sh -d target.com -r --monitor --monitor-interval 30 --monitor-cycles 48
+ ```
+
+13. **Rebuild reports only (no scan):**
+ ```bash
+ ./reconftw.sh -d target.com --report-only --export all
+ ```
+
**Full Guide**: See the [Usage Guide](https://github.com/six2dez/reconftw/wiki/2.-Usage-Guide).
---
@@ -887,13 +940,22 @@ reconFTW uses AI to generate detailed reports from scan results with the tool [r
- **Model**: Configurable AI model (e.g., `llama3:8b` via `AI_MODEL`).
- **Report Types**: Markdown or plain text (`AI_REPORT_TYPE`).
- **Profiles**: Executive, brief, or bug hunter (`AI_REPORT_PROFILE`).
+- **Structured Output**: `reconftw` stores a machine-readable report in `ai_result/reconftw_analysis.json`.
+- **Context Controls**: Bound input size using `AI_MAX_CHARS_PER_FILE` and `AI_MAX_FILES_PER_CATEGORY`.
+- **Safety Controls**: Toggle redaction and strict mode with `AI_REDACT` and `AI_STRICT`.
**Example**:
```yaml
+AI_EXECUTABLE="python3"
AI_MODEL="llama3:8b"
AI_REPORT_TYPE="md"
AI_REPORT_PROFILE="bughunter"
+AI_MAX_CHARS_PER_FILE=50000
+AI_MAX_FILES_PER_CATEGORY=200
+AI_REDACT=true
+AI_ALLOW_MODEL_PULL=false
+AI_STRICT=false
```
---
diff --git a/config/reconftw_full.cfg b/config/reconftw_full.cfg
new file mode 100644
index 0000000..9d6c87e
--- /dev/null
+++ b/config/reconftw_full.cfg
@@ -0,0 +1,100 @@
+# reconFTW Full Profile - Complete scan with all modules enabled
+# Usage: reconftw.sh -d target.com --config config/reconftw_full.cfg
+
+# Override-only profile.
+# Base config is already loaded by reconftw.sh before this file.
+
+# Enable everything
+OSINT=true
+GOOGLE_DORKS=true
+GITHUB_DORKS=true
+GITHUB_REPOS=true
+METADATA=true
+EMAILS=true
+DOMAIN_INFO=true
+IP_INFO=true
+API_LEAKS=true
+THIRD_PARTIES=true
+SPOOF=true
+MAIL_HYGIENE=true
+CLOUD_ENUM=true
+
+# Subdomains: all methods
+SUBDOMAINS_GENERAL=true
+SUBPASSIVE=true
+SUBCRT=true
+SUBBRUTE=true
+SUBSCRAPING=true
+SUBPERMUTE=true
+SUBIAPERMUTE=true
+SUBREGEXPERMUTE=true
+SUB_RECURSIVE_PASSIVE=true
+SUB_RECURSIVE_BRUTE=true
+SUBNOERROR=true
+SUBANALYTICS=true
+SUBTAKEOVER=true
+ZONETRANSFER=true
+S3BUCKETS=true
+DEEP_WILDCARD_FILTER=true
+
+# Web: full probing
+WEBPROBESIMPLE=true
+WEBPROBEFULL=true
+WEBSCREENSHOT=true
+VIRTUALHOSTS=true
+FAVICON=true
+
+# Host
+PORTSCANNER=true
+PORTSCAN_PASSIVE=true
+PORTSCAN_ACTIVE=true
+CDN_IP=true
+WAF_DETECTION=true
+GEO_INFO=true
+
+# URL and JS
+URL_CHECK=true
+URL_CHECK_PASSIVE=true
+URL_CHECK_ACTIVE=true
+URL_GF=true
+URL_EXT=true
+JSCHECKS=true
+
+# Fuzzing
+FUZZ=true
+IIS_SHORTNAME=true
+CMS_SCANNER=true
+WORDLIST=true
+ROBOTSWORDLIST=true
+PASSWORD_DICT=true
+
+# Vulnerabilities: all enabled
+VULNS_GENERAL=true
+XSS=true
+CORS=true
+TEST_SSL=true
+OPEN_REDIRECT=true
+SSRF_CHECKS=true
+CRLF_CHECKS=true
+LFI=true
+SSTI=true
+SQLI=true
+SQLMAP=true
+GHAURI=true
+BROKENLINKS=true
+SPRAY=true
+COMM_INJ=true
+PROTO_POLLUTION=true
+SMUGGLING=true
+WEBCACHE=true
+BYPASSER4XX=true
+FUZZPARAMS=true
+
+# Extras
+NUCLEICHECK=true
+GRAPHQL_CHECK=true
+GQLSPECTION=true
+PARAM_DISCOVERY=true
+GRPC_SCAN=true
+IPV6_SCAN=true
+DEEP=true
diff --git a/config/reconftw_quick.cfg b/config/reconftw_quick.cfg
new file mode 100644
index 0000000..631495e
--- /dev/null
+++ b/config/reconftw_quick.cfg
@@ -0,0 +1,63 @@
+# reconFTW Quick Profile - Passive-only, fast scan
+# Usage: reconftw.sh -d target.com --config config/reconftw_quick.cfg
+
+# Override-only profile.
+# Base config is already loaded by reconftw.sh before this file.
+
+# Disable active/intrusive modules
+SUBBRUTE=false
+SUBSCRAPING=false
+SUBPERMUTE=false
+SUBIAPERMUTE=false
+SUBREGEXPERMUTE=false
+SUB_RECURSIVE_BRUTE=false
+SUBNOERROR=false
+ZONETRANSFER=false
+DEEP_WILDCARD_FILTER=false
+
+# Web: passive only
+WEBPROBEFULL=false
+WEBSCREENSHOT=false
+VIRTUALHOSTS=false
+PORTSCANNER=false
+PORTSCAN_ACTIVE=false
+CDN_IP=false
+
+# URL checks: passive only
+URL_CHECK_ACTIVE=false
+JSCHECKS=false
+FUZZ=false
+IIS_SHORTNAME=false
+CMS_SCANNER=false
+WORDLIST=false
+ROBOTSWORDLIST=false
+PASSWORD_DICT=false
+
+# Disable all vulnerability checks
+VULNS_GENERAL=false
+XSS=false
+CORS=false
+TEST_SSL=false
+OPEN_REDIRECT=false
+SSRF_CHECKS=false
+CRLF_CHECKS=false
+LFI=false
+SSTI=false
+SQLI=false
+SQLMAP=false
+GHAURI=false
+BROKENLINKS=false
+SPRAY=false
+COMM_INJ=false
+PROTO_POLLUTION=false
+SMUGGLING=false
+WEBCACHE=false
+BYPASSER4XX=false
+FUZZPARAMS=false
+
+# Disable heavy extras
+GRAPHQL_CHECK=false
+PARAM_DISCOVERY=false
+GRPC_SCAN=false
+IPV6_SCAN=false
+NUCLEICHECK=false
diff --git a/config/reconftw_stealth.cfg b/config/reconftw_stealth.cfg
new file mode 100644
index 0000000..b52c55c
--- /dev/null
+++ b/config/reconftw_stealth.cfg
@@ -0,0 +1,105 @@
+# reconFTW Stealth Profile - Minimum noise, no active scanning
+# Usage: reconftw.sh -d target.com --config config/reconftw_stealth.cfg
+
+# Override-only profile.
+# Base config is already loaded by reconftw.sh before this file.
+
+# Passive OSINT only
+OSINT=true
+GOOGLE_DORKS=true
+GITHUB_DORKS=true
+GITHUB_REPOS=true
+METADATA=false
+EMAILS=true
+DOMAIN_INFO=true
+IP_INFO=true
+API_LEAKS=true
+THIRD_PARTIES=true
+SPOOF=true
+MAIL_HYGIENE=true
+CLOUD_ENUM=false
+
+# Subdomains: passive only, no DNS brute/active
+SUBDOMAINS_GENERAL=true
+SUBPASSIVE=true
+SUBCRT=true
+SUBBRUTE=false
+SUBSCRAPING=false
+SUBPERMUTE=false
+SUBIAPERMUTE=false
+SUBREGEXPERMUTE=false
+SUB_RECURSIVE_PASSIVE=true
+SUB_RECURSIVE_BRUTE=false
+SUBNOERROR=false
+SUBANALYTICS=true
+SUBTAKEOVER=false
+ZONETRANSFER=false
+S3BUCKETS=false
+DEEP_WILDCARD_FILTER=false
+REVERSE_IP=false
+
+# Web: minimal probing, low threads
+WEBPROBESIMPLE=true
+WEBPROBEFULL=false
+WEBSCREENSHOT=false
+VIRTUALHOSTS=false
+
+# Host: passive only
+FAVICON=false
+PORTSCANNER=true
+PORTSCAN_PASSIVE=true
+PORTSCAN_ACTIVE=false
+CDN_IP=true
+WAF_DETECTION=false
+GEO_INFO=true
+
+# URL: passive collection only
+URL_CHECK=true
+URL_CHECK_PASSIVE=true
+URL_CHECK_ACTIVE=false
+URL_GF=true
+URL_EXT=true
+JSCHECKS=false
+
+# No fuzzing or active testing
+FUZZ=false
+IIS_SHORTNAME=false
+CMS_SCANNER=false
+WORDLIST=false
+ROBOTSWORDLIST=false
+PASSWORD_DICT=false
+
+# No vulnerability scanning
+VULNS_GENERAL=false
+XSS=false
+CORS=false
+TEST_SSL=false
+OPEN_REDIRECT=false
+SSRF_CHECKS=false
+CRLF_CHECKS=false
+LFI=false
+SSTI=false
+SQLI=false
+SQLMAP=false
+GHAURI=false
+BROKENLINKS=false
+SPRAY=false
+COMM_INJ=false
+PROTO_POLLUTION=false
+SMUGGLING=false
+WEBCACHE=false
+BYPASSER4XX=false
+FUZZPARAMS=false
+
+# Nuclei: only safe templates
+NUCLEICHECK=true
+NUCLEI_SEVERITY="info,low"
+GRAPHQL_CHECK=false
+PARAM_DISCOVERY=false
+GRPC_SCAN=false
+IPV6_SCAN=false
+
+# Low rate limits for stealth
+NUCLEI_RATELIMIT=10
+HTTPX_RATELIMIT=5
+FFUF_RATELIMIT=10
diff --git a/config/tls_ports.txt b/config/tls_ports.txt
new file mode 100644
index 0000000..ec80db9
--- /dev/null
+++ b/config/tls_ports.txt
@@ -0,0 +1 @@
+21,22,25,80,110,135,143,261,271,324,443,448,465,563,614,631,636,664,684,695,832,853,854,990,993,989,992,994,995,1129,1131,1184,2083,2087,2089,2096,2221,2252,2376,2381,2478,2479,2482,2484,2679,2762,3077,3078,3183,3191,3220,3269,3306,3410,3424,3471,3496,3509,3529,3539,3535,3660,36611,3713,3747,3766,3864,3885,3995,3896,4031,4036,4062,4064,4081,4083,4116,4335,4336,4536,4590,4740,4843,4849,5443,5007,5061,5321,5349,5671,5783,5868,5986,5989,5990,6209,6251,6443,6513,6514,6619,6697,6771,7202,7443,7673,7674,7677,7775,8243,8443,8991,8989,9089,9295,9318,9443,9444,9614,9802,10161,10162,11751,12013,12109,14143,15002,16995,41230,16993,20003
diff --git a/config/uncommon_ports_web.txt b/config/uncommon_ports_web.txt
new file mode 100644
index 0000000..c6fa4e9
--- /dev/null
+++ b/config/uncommon_ports_web.txt
@@ -0,0 +1 @@
+81,300,591,593,832,981,1010,1311,1099,2082,2095,2096,2480,3000,3001,3002,3003,3128,3333,4243,4567,4711,4712,4993,5000,5104,5108,5280,5281,5601,5800,6543,7000,7001,7396,7474,8000,8001,8008,8014,8042,8060,8069,8080,8081,8083,8088,8090,8091,8095,8118,8123,8172,8181,8222,8243,8280,8281,8333,8337,8443,8500,8834,8880,8888,8983,9000,9001,9043,9060,9080,9090,9091,9092,9200,9443,9502,9800,9981,10000,10250,11371,12443,15672,16080,17778,18091,18092,20720,32000,55440,55672
diff --git a/lib/common.sh b/lib/common.sh
index 879bf15..5e0cc43 100644
--- a/lib/common.sh
+++ b/lib/common.sh
@@ -187,7 +187,9 @@ filter_and_process() {
local count=0
if [[ -s "$input" ]]; then
- count=$(grep "\\.${domain}$\\|^${domain}$" "$input" 2>/dev/null \
+ local escaped
+ escaped=$(escape_domain_regex "$domain")
+ count=$(grep "\\.${escaped}$\\|^${escaped}$" "$input" 2>/dev/null \
| anew "$output" 2>/dev/null \
| sed '/^$/d' \
| wc -l | tr -d ' ')
@@ -197,6 +199,77 @@ filter_and_process() {
echo "$count"
}
+###############################################################################
+# Domain Matching Helpers
+###############################################################################
+
+# Escape a domain name for safe use in grep regex patterns
+# Dots are literal in domain names but regex metacharacters
+# Usage: escaped=$(escape_domain_regex "example.com")
+escape_domain_regex() {
+ printf '%s' "$1" | sed 's/[.[\*^$()+?{|]/\\&/g'
+}
+
+# Grep lines matching a domain (as subdomain or exact match) with proper escaping
+# Usage: grep_domain input_file domain [extra_grep_flags...]
+# Matches: "*.domain" and "domain" exactly (anchored)
+grep_domain() {
+ local input="$1"
+ local raw_domain="$2"
+ shift 2
+ local escaped
+ escaped=$(escape_domain_regex "$raw_domain")
+ grep "$@" "\.${escaped}$\|^${escaped}$" "$input"
+}
+
+###############################################################################
+# Axiom/Local Execution Helper
+###############################################################################
+
+# Run a tool command, automatically choosing between local and axiom-scan
+# Usage: run_scan <input_file> <output_file> <tool_name> [tool_args...]
+# Example: run_scan .tmp/input.txt .tmp/output.txt subfinder -silent
+# With AXIOM: axiom-scan input -m tool args -o output $AXIOM_EXTRA_ARGS
+# Without: tool args < input > output (or with -o flag)
+run_scan() {
+ local input="$1"
+ local output="$2"
+ local tool="$3"
+ shift 3
+
+ if [[ ${AXIOM:-false} == true ]]; then
+ axiom-scan "$input" -m "$tool" "$@" -o "$output" $AXIOM_EXTRA_ARGS 2>>"$LOGFILE" >/dev/null
+ else
+ "$tool" "$@" -o "$output" <"$input" 2>>"$LOGFILE" >/dev/null
+ fi
+}
+
+###############################################################################
+# Function Gate Helper
+###############################################################################
+
+# Check if a function should run based on its flag and checkpoint
+# Usage: if should_run "FLAG_VAR_NAME"; then ... fi
+# Replaces the repeated pattern:
+# if { [[ ! -f "$called_fn_dir/.${FUNCNAME[0]}" ]] || [[ $DIFF == true ]]; } && [[ $FLAG == true ]]; then
+should_run() {
+ local flag_var="$1"
+ local func_name="${FUNCNAME[1]:-unknown}"
+ local checkpoint_file="${called_fn_dir:-.}/.${func_name}"
+
+ # Check if feature flag is enabled
+ if [[ "${!flag_var:-false}" != true ]]; then
+ return 1
+ fi
+
+ # Check if already processed (unless DIFF mode)
+ if [[ -f "$checkpoint_file" ]] && [[ ${DIFF:-false} != true ]]; then
+ return 1
+ fi
+
+ return 0
+}
+
###############################################################################
# Validation Helpers
###############################################################################
diff --git a/lib/parallel.sh b/lib/parallel.sh
index dfd7d4e..11ce9f8 100644
--- a/lib/parallel.sh
+++ b/lib/parallel.sh
@@ -16,6 +16,19 @@ PARALLEL_MAX_JOBS="${PARALLEL_MAX_JOBS:-4}"
# Track running PIDs for cleanup
declare -a _PARALLEL_PIDS=()
+_parallel_effective_max_jobs() {
+ local requested="${1:-$PARALLEL_MAX_JOBS}"
+ local pressure="${PARALLEL_PRESSURE_LEVEL:-normal}"
+ local effective="$requested"
+
+ # Backpressure: shrink concurrency when rate-limit pressure is high.
+ if [[ "$pressure" == "high" ]]; then
+ effective=$((requested / 2))
+ ((effective < 1)) && effective=1
+ fi
+ echo "$effective"
+}
+
###############################################################################
# Core Parallel Execution
###############################################################################
@@ -24,7 +37,8 @@ declare -a _PARALLEL_PIDS=()
# Usage: parallel_run max_jobs "cmd1" "cmd2" "cmd3" ...
# Example: parallel_run 4 "subfinder -d $domain" "amass enum -d $domain"
parallel_run() {
- local max_jobs="${1:-$PARALLEL_MAX_JOBS}"
+ local max_jobs
+ max_jobs=$(_parallel_effective_max_jobs "${1:-$PARALLEL_MAX_JOBS}")
shift
local -a pids=()
@@ -32,8 +46,8 @@ parallel_run() {
local running=0
for cmd in "$@"; do
- # Start command in background
- eval "$cmd" &
+ # Start command in background (use bash -c to avoid eval injection)
+ bash -c "$cmd" &
pids+=($!)
((running++))
@@ -52,7 +66,8 @@ parallel_run() {
# Usage: parallel_funcs max_jobs func1 func2 func3 ...
# Example: parallel_funcs 4 sub_passive sub_crt sub_active
parallel_funcs() {
- local max_jobs="${1:-$PARALLEL_MAX_JOBS}"
+ local max_jobs
+ max_jobs=$(_parallel_effective_max_jobs "${1:-$PARALLEL_MAX_JOBS}")
shift
local -a pids=()
diff --git a/modules/axiom.sh b/modules/axiom.sh
index f20b7c2..5afe5b1 100644
--- a/modules/axiom.sh
+++ b/modules/axiom.sh
@@ -40,8 +40,8 @@ function resolvers_update() {
if [[ ! -s $resolvers ]] || [[ $(find "$resolvers" -mtime +1 -print) ]]; then
notification "Resolvers seem older than 1 day\n Downloading new resolvers..." warn
- cached_download "${resolvers_url}" "$resolvers" "resolvers.txt"
- cached_download "${resolvers_trusted_url}" "$resolvers_trusted" "resolvers_trusted.txt"
+ cached_download_typed "${resolvers_url}" "$resolvers" "resolvers.txt" "resolvers"
+ cached_download_typed "${resolvers_trusted_url}" "$resolvers_trusted" "resolvers_trusted.txt" "resolvers"
notification "Resolvers updated\n" good
fi
fi
@@ -50,8 +50,8 @@ function resolvers_update() {
function resolvers_update_quick_local() {
if [[ $update_resolvers == true ]]; then
- cached_download "${resolvers_url}" "$resolvers" "resolvers.txt"
- cached_download "${resolvers_trusted_url}" "$resolvers_trusted" "resolvers_trusted.txt"
+ cached_download_typed "${resolvers_url}" "$resolvers" "resolvers.txt" "resolvers"
+ cached_download_typed "${resolvers_trusted_url}" "$resolvers_trusted" "resolvers_trusted.txt" "resolvers"
fi
}
diff --git a/modules/core.sh b/modules/core.sh
index 2d9a178..4195e65 100644
--- a/modules/core.sh
+++ b/modules/core.sh
@@ -499,6 +499,68 @@ function log_success() {
log_json "SUCCESS" "${FUNCNAME[1]:-main}" "$@"
}
+###############################################################################################################
+############################################ PROGRESS / ETA ###################################################
+###############################################################################################################
+
+_PROGRESS_TOTAL_STEPS=0
+_PROGRESS_CURRENT_STEP=0
+_PROGRESS_START_TIME=0
+
+# Initialize progress tracking
+# Usage: progress_init <total_steps> [total_est_seconds]
+function progress_init() {
+ _PROGRESS_TOTAL_STEPS=${1:-0}
+ _PROGRESS_CURRENT_STEP=0
+ _PROGRESS_START_TIME=$(date +%s)
+ _PROGRESS_TOTAL_EST=${2:-0}
+}
+
+# Adjust total progress steps at runtime (for conditional stage skipping)
+# Usage: progress_adjust_total <delta_steps>
+function progress_adjust_total() {
+ local delta="${1:-0}"
+ _PROGRESS_TOTAL_STEPS=$((_PROGRESS_TOTAL_STEPS + delta))
+ if [[ $_PROGRESS_TOTAL_STEPS -lt 1 ]]; then
+ _PROGRESS_TOTAL_STEPS=1
+ fi
+}
+
+# Advance progress and display ETA
+# Usage: progress_step <step_name>
+function progress_step() {
+ ((_PROGRESS_CURRENT_STEP++)) || true
+ local step_name="${1:-}"
+ local now elapsed remaining_steps avg_per_step eta_seconds eta_display pct
+
+ now=$(date +%s)
+ elapsed=$((now - _PROGRESS_START_TIME))
+ pct=0
+ eta_display="calculating..."
+
+ if [[ $_PROGRESS_TOTAL_STEPS -gt 0 ]]; then
+ pct=$(( (_PROGRESS_CURRENT_STEP * 100) / _PROGRESS_TOTAL_STEPS ))
+ remaining_steps=$((_PROGRESS_TOTAL_STEPS - _PROGRESS_CURRENT_STEP))
+
+ if [[ $_PROGRESS_CURRENT_STEP -gt 0 ]] && [[ $elapsed -gt 0 ]]; then
+ avg_per_step=$((elapsed / _PROGRESS_CURRENT_STEP))
+ eta_seconds=$((remaining_steps * avg_per_step))
+ if [[ $eta_seconds -ge 3600 ]]; then
+ eta_display="~$((eta_seconds / 3600))h $((eta_seconds % 3600 / 60))m"
+ elif [[ $eta_seconds -ge 60 ]]; then
+ eta_display="~$((eta_seconds / 60))m"
+ else
+ eta_display="~${eta_seconds}s"
+ fi
+ fi
+ fi
+
+ printf "%b[%s] Progress: [%d/%d] %d%% | ETA: %s | %s%b\n" \
+ "$bblue" "$(date +'%H:%M:%S')" \
+ "$_PROGRESS_CURRENT_STEP" "$_PROGRESS_TOTAL_STEPS" \
+ "$pct" "$eta_display" "$step_name" "$reset"
+}
+
###############################################################################################################
######################################### INCREMENTAL MODE ####################################################
###############################################################################################################
@@ -633,6 +695,215 @@ function incremental_report() {
"$bgreen" "$(date +'%Y-%m-%d %H:%M:%S')" "$report_file" "$reset"
}
+# Hash helper for alert fingerprinting.
+_hash_string() {
+ local input="$1"
+ if command -v sha256sum >/dev/null 2>&1; then
+ printf '%s' "$input" | sha256sum | awk '{print $1}'
+ else
+ printf '%s' "$input" | shasum -a 256 | awk '{print $1}'
+ fi
+}
+
+_monitor_mark_alert_seen() {
+ local category="$1"
+ local value="$2"
+ local seen_file="${ALERT_SEEN_FILE:-.incremental/alerts_seen.hashes}"
+ local fp
+ fp=$(_hash_string "${category}|${value}")
+ mkdir -p "$(dirname "$seen_file")"
+ touch "$seen_file"
+
+ if [[ "${ALERT_SUPPRESSION:-true}" == "true" ]] && grep -Fxq "$fp" "$seen_file"; then
+ return 1
+ fi
+ echo "$fp" >>"$seen_file"
+ return 0
+}
+
+_monitor_alert_summary() {
+ local snap="$1"
+ local critical_u=0 high_u=0 subs_u=0 webs_u=0
+ local critical_s=0 high_s=0 subs_s=0 webs_s=0
+ local line
+
+ if [[ -s "$snap/critical_new.txt" ]]; then
+ while IFS= read -r line; do
+ [[ -z "$line" ]] && continue
+ if _monitor_mark_alert_seen "critical" "$line"; then ((critical_u++)); else ((critical_s++)); fi
+ done <"$snap/critical_new.txt"
+ fi
+ if [[ -s "$snap/high_new.txt" ]]; then
+ while IFS= read -r line; do
+ [[ -z "$line" ]] && continue
+ if _monitor_mark_alert_seen "high" "$line"; then ((high_u++)); else ((high_s++)); fi
+ done <"$snap/high_new.txt"
+ fi
+ if [[ -s "$snap/subdomains_new.txt" ]]; then
+ while IFS= read -r line; do
+ [[ -z "$line" ]] && continue
+ if _monitor_mark_alert_seen "subdomain" "$line"; then ((subs_u++)); else ((subs_s++)); fi
+ done <"$snap/subdomains_new.txt"
+ fi
+ if [[ -s "$snap/webs_new.txt" ]]; then
+ while IFS= read -r line; do
+ [[ -z "$line" ]] && continue
+ if _monitor_mark_alert_seen "web" "$line"; then ((webs_u++)); else ((webs_s++)); fi
+ done <"$snap/webs_new.txt"
+ fi
+
+ if command -v jq >/dev/null 2>&1; then
+ jq -n \
+ --arg ts "$(date -Iseconds)" \
+ --arg cycle "${MONITOR_CYCLE:-0}" \
+ --argjson critical_new "$critical_u" \
+ --argjson high_new "$high_u" \
+ --argjson subdomains_new "$subs_u" \
+ --argjson webs_new "$webs_u" \
+ --argjson critical_suppressed "$critical_s" \
+ --argjson high_suppressed "$high_s" \
+ --argjson subdomains_suppressed "$subs_s" \
+ --argjson webs_suppressed "$webs_s" \
+ '{
+ timestamp:$ts,
+ cycle:($cycle|tonumber),
+ alerts:{
+ critical_new:$critical_new,
+ high_new:$high_new,
+ subdomains_new:$subdomains_new,
+ webs_new:$webs_new
+ },
+ suppressed:{
+ critical:$critical_suppressed,
+ high:$high_suppressed,
+ subdomains:$subdomains_suppressed,
+ webs:$webs_suppressed
+ }
+ }' >"$snap/alerts.json"
+ fi
+
+ printf '%s %s %s %s %s %s %s %s\n' \
+ "$critical_u" "$high_u" "$subs_u" "$webs_u" \
+ "$critical_s" "$high_s" "$subs_s" "$webs_s"
+}
+
+# Monitor snapshots and delta tracking.
+# Stores historical snapshots under .incremental/history/<timestamp>/ and computes deltas vs latest.
+function monitor_snapshot() {
+ [[ "${MONITOR_MODE:-false}" != "true" ]] && return 0
+
+ ensure_dirs .incremental/history || return 1
+ local ts snap prev_link prev_dir
+ ts=$(date +%Y%m%d_%H%M%S)
+ snap=".incremental/history/${ts}"
+ mkdir -p "$snap"
+
+ # Snapshot key artifacts for this cycle.
+ local src
+ for src in \
+ "subdomains/subdomains.txt" \
+ "webs/webs_all.txt" \
+ "nuclei_output/high.txt" \
+ "nuclei_output/critical.txt" \
+ "report/report.json" \
+ "hotlist.txt"; do
+ if [[ -s "$src" ]]; then
+ cp "$src" "$snap/$(basename "$src")"
+ fi
+ done
+
+ prev_link=".incremental/history/latest"
+ prev_dir=""
+ if [[ -L "$prev_link" || -d "$prev_link" ]]; then
+ prev_dir=$(cd "$prev_link" 2>/dev/null && pwd -P || true)
+ fi
+
+ local subs_new=0 webs_new=0 high_new=0 critical_new=0 delta_total=0
+ if [[ -n "$prev_dir" ]]; then
+ if [[ -s "$snap/subdomains.txt" ]] && [[ -s "$prev_dir/subdomains.txt" ]]; then
+ comm -13 <(sort -u "$prev_dir/subdomains.txt") <(sort -u "$snap/subdomains.txt") >"$snap/subdomains_new.txt"
+ subs_new=$(wc -l <"$snap/subdomains_new.txt" 2>/dev/null | tr -d ' ')
+ fi
+ if [[ -s "$snap/webs_all.txt" ]] && [[ -s "$prev_dir/webs_all.txt" ]]; then
+ comm -13 <(sort -u "$prev_dir/webs_all.txt") <(sort -u "$snap/webs_all.txt") >"$snap/webs_new.txt"
+ webs_new=$(wc -l <"$snap/webs_new.txt" 2>/dev/null | tr -d ' ')
+ fi
+ if [[ -s "$snap/high.txt" ]] && [[ -s "$prev_dir/high.txt" ]]; then
+ comm -13 <(sort -u "$prev_dir/high.txt") <(sort -u "$snap/high.txt") >"$snap/high_new.txt"
+ high_new=$(wc -l <"$snap/high_new.txt" 2>/dev/null | tr -d ' ')
+ fi
+ if [[ -s "$snap/critical.txt" ]] && [[ -s "$prev_dir/critical.txt" ]]; then
+ comm -13 <(sort -u "$prev_dir/critical.txt") <(sort -u "$snap/critical.txt") >"$snap/critical_new.txt"
+ critical_new=$(wc -l <"$snap/critical_new.txt" 2>/dev/null | tr -d ' ')
+ fi
+ else
+ # Baseline cycle: don't alert as "new", just record baseline.
+ subs_new=0
+ webs_new=0
+ high_new=0
+ critical_new=0
+ fi
+
+ subs_new=${subs_new:-0}
+ webs_new=${webs_new:-0}
+ high_new=${high_new:-0}
+ critical_new=${critical_new:-0}
+ delta_total=$((subs_new + webs_new + high_new + critical_new))
+ if command -v jq >/dev/null 2>&1; then
+ jq -n \
+ --arg ts "$(date -Iseconds)" \
+ --arg cycle "${MONITOR_CYCLE:-0}" \
+ --arg baseline "$( [[ -z "$prev_dir" ]] && echo true || echo false )" \
+ --argjson subs_new "$subs_new" \
+ --argjson webs_new "$webs_new" \
+ --argjson high_new "$high_new" \
+ --argjson critical_new "$critical_new" \
+ --argjson total_new "$delta_total" \
+ '{
+ timestamp:$ts,
+ cycle:($cycle|tonumber),
+ baseline:($baseline=="true"),
+ deltas:{
+ subdomains_new:$subs_new,
+ webs_new:$webs_new,
+ high_findings_new:$high_new,
+ critical_findings_new:$critical_new,
+ total_new:$total_new
+ }
+ }' >"$snap/delta.json"
+ fi
+
+ if [[ -z "$prev_dir" ]]; then
+ notification "Monitor baseline snapshot stored (${snap})" info
+ elif [[ "$delta_total" -gt 0 ]]; then
+ local alert_stats critical_u high_u subs_u webs_u critical_s high_s subs_s webs_s
+ alert_stats=$(_monitor_alert_summary "$snap")
+ read -r critical_u high_u subs_u webs_u critical_s high_s subs_s webs_s <<<"$alert_stats"
+
+ if [[ "${critical_u:-0}" -gt 0 || "${high_u:-0}" -gt 0 ]]; then
+ notification "[ALERT] New high-impact findings: critical=${critical_u:-0}, high=${high_u:-0}" warn
+ fi
+ if [[ "${subs_u:-0}" -gt 0 || "${webs_u:-0}" -gt 0 ]]; then
+ notification "New assets detected: subdomains=${subs_u:-0}, webs=${webs_u:-0}" good
+ fi
+ if [[ "${critical_u:-0}" -eq 0 && "${high_u:-0}" -eq 0 && "${subs_u:-0}" -eq 0 && "${webs_u:-0}" -eq 0 ]]; then
+ notification "Monitor detected deltas but all were suppressed by fingerprint history" info
+ fi
+ else
+ notification "Monitor cycle: no changes detected" info
+ fi
+
+ # Update latest snapshot pointer.
+ if [[ -L "$prev_link" || -d "$prev_link" ]]; then
+ rm -rf -- "$prev_link"
+ fi
+ ln -s "$ts" "$prev_link" 2>/dev/null || {
+ cp -R "$snap" "$prev_link"
+ }
+
+ return 0
+}
+
# Check if incremental mode should skip heavy operations
# Usage: incremental_should_skip
# Returns: 0 to skip, 1 to continue
@@ -807,24 +1078,26 @@ function start_func() {
notification "${2}" info
echo "[$current_date] Start function: ${1} " >>"${LOGFILE}"
start=$(date +%s)
+ log_json "INFO" "${1}" "Function started" "description=${2}"
}
function end_func() {
touch "$called_fn_dir/.${2}"
end=$(date +%s)
getElapsedTime "$start" "$end"
- # Record timing for performance summary
record_func_timing "${2}" "$((end - start))"
notification "${2} Finished in ${runtime}" info
echo "[$current_date] End function: ${2} " >>"${LOGFILE}"
printf "${bblue}[$current_date] ${1} ${reset}\n"
printf "${bgreen}#######################################################################${reset}\n"
+ log_json "SUCCESS" "${2}" "Function completed" "runtime=${runtime}" "duration_sec=$((end - start))"
}
function start_subfunc() {
notification " ${2}" info
echo "[$current_date] Start subfunction: ${1} " >>"${LOGFILE}"
start_sub=$(date +%s)
+ log_json "INFO" "${1}" "Subfunction started" "description=${2}"
}
function end_subfunc() {
@@ -833,6 +1106,7 @@ function end_subfunc() {
getElapsedTime "$start_sub" "$end_sub"
notification " ${1} in ${runtime}" good
echo "[$current_date] End subfunction: ${1} " >>"${LOGFILE}"
+ log_json "SUCCESS" "${2}" "Subfunction completed" "runtime=${runtime}" "duration_sec=$((end_sub - start_sub))"
}
function check_inscope() {
@@ -981,6 +1255,474 @@ function print_timing_summary() {
printf "%b#######################################################################%b\n\n" "$bgreen" "$reset"
}
+# Write machine-readable performance summary for dashboards/automation.
+# Output: .log/perf_summary.json
+function write_perf_summary() {
+ local summary_file="${dir}/.log/perf_summary.json"
+ local total=0
+ local fn dur
+
+ for fn in "${!FUNC_TIMINGS[@]}"; do
+ dur=${FUNC_TIMINGS[$fn]}
+ [[ "$dur" =~ ^[0-9]+$ ]] || continue
+ total=$((total + dur))
+ done
+
+ local subs_count webs_count hosts_count findings_count
+ subs_count=$(wc -l <"${dir}/subdomains/subdomains.txt" 2>/dev/null | tr -d ' ')
+ webs_count=$(wc -l <"${dir}/webs/webs_all.txt" 2>/dev/null | tr -d ' ')
+ hosts_count=$(wc -l <"${dir}/hosts/ips.txt" 2>/dev/null | tr -d ' ')
+ findings_count=$(find "${dir}/nuclei_output" -type f -name '*_json.txt' -exec cat {} + 2>/dev/null | wc -l | tr -d ' ')
+ subs_count=${subs_count:-0}
+ webs_count=${webs_count:-0}
+ hosts_count=${hosts_count:-0}
+ findings_count=${findings_count:-0}
+
+ # Build top functions by duration.
+ local top_json="[]"
+ local -a sorted_entries=()
+ for fn in "${!FUNC_TIMINGS[@]}"; do
+ dur=${FUNC_TIMINGS[$fn]}
+ [[ "$dur" =~ ^[0-9]+$ ]] || continue
+ sorted_entries+=("$dur|$fn")
+ done
+ if [[ ${#sorted_entries[@]} -gt 0 ]]; then
+ top_json=$(printf '%s\n' "${sorted_entries[@]}" \
+ | sort -t'|' -k1 -rn \
+ | head -n 15 \
+ | awk -F'|' '{printf "{\"function\":\"%s\",\"duration_sec\":%s}\n",$2,$1}' \
+ | jq -s '.')
+ fi
+
+ if command -v jq >/dev/null 2>&1; then
+ jq -n \
+ --arg ts "$(date -Iseconds)" \
+ --arg domain "${domain:-unknown}" \
+ --arg mode "${opt_mode:-unknown}" \
+ --arg profile "${PERF_PROFILE:-balanced}" \
+ --argjson total_sec "${total:-0}" \
+ --argjson subdomains "${subs_count:-0}" \
+ --argjson webs "${webs_count:-0}" \
+ --argjson hosts "${hosts_count:-0}" \
+ --argjson findings "${findings_count:-0}" \
+ --argjson top "${top_json}" \
+ '{
+ timestamp:$ts,
+ domain:$domain,
+ mode:$mode,
+ perf_profile:$profile,
+ total_duration_sec:$total_sec,
+ counts:{
+ subdomains:$subdomains,
+ webs:$webs,
+ hosts:$hosts,
+ findings:$findings
+ },
+ top_functions:$top
+ }' >"$summary_file"
+ else
+ printf '{"timestamp":"%s","domain":"%s","mode":"%s","perf_profile":"%s","total_duration_sec":%s}\n' \
+ "$(date -Iseconds)" "${domain:-unknown}" "${opt_mode:-unknown}" "${PERF_PROFILE:-balanced}" "${total:-0}" >"$summary_file"
+ fi
+}
+
+# Generate consolidated JSON + HTML report for the current scan.
+# Outputs:
+# - report/report.json
+# - report/index.html
+function generate_consolidated_report() {
+ ensure_dirs report || return 1
+
+ local report_json="report/report.json"
+ local report_html="report/index.html"
+ local subs_count webs_count hosts_count screenshots_count findings_total
+ local sev_info sev_low sev_medium sev_high sev_critical
+ local top_assets_json timeline_json links_json monitor_delta_json monitor_alerts_json
+
+ subs_count=$(wc -l <subdomains/subdomains.txt 2>/dev/null | tr -d ' ')
+ webs_count=$(wc -l <webs/webs_all.txt 2>/dev/null | tr -d ' ')
+ hosts_count=$(wc -l <hosts/ips.txt 2>/dev/null | tr -d ' ')
+ screenshots_count=$(find screenshots -type f -name '*.png' 2>/dev/null | wc -l | tr -d ' ')
+
+ sev_info=$(wc -l <nuclei_output/info_json.txt 2>/dev/null | tr -d ' ')
+ sev_low=$(wc -l <nuclei_output/low_json.txt 2>/dev/null | tr -d ' ')
+ sev_medium=$(wc -l <nuclei_output/medium_json.txt 2>/dev/null | tr -d ' ')
+ sev_high=$(wc -l <nuclei_output/high_json.txt 2>/dev/null | tr -d ' ')
+ sev_critical=$(wc -l <nuclei_output/critical_json.txt 2>/dev/null | tr -d ' ')
+
+ subs_count=${subs_count:-0}
+ webs_count=${webs_count:-0}
+ hosts_count=${hosts_count:-0}
+ screenshots_count=${screenshots_count:-0}
+ sev_info=${sev_info:-0}
+ sev_low=${sev_low:-0}
+ sev_medium=${sev_medium:-0}
+ sev_high=${sev_high:-0}
+ sev_critical=${sev_critical:-0}
+ findings_total=$((sev_info + sev_low + sev_medium + sev_high + sev_critical))
+
+ # Top assets from hotlist (if present)
+ if [[ -s hotlist.txt ]] && command -v jq >/dev/null 2>&1; then
+ top_assets_json=$(head -n "${HOTLIST_TOP:-50}" hotlist.txt \
+ | awk '{score=$1;$1=""; sub(/^ /,"",$0); printf "{\"asset\":\"%s\",\"score\":%s}\n",$0,score}' \
+ | jq -s '.')
+ else
+ top_assets_json="[]"
+ fi
+
+ # Timeline from structured log (preferred) or fallback from text log.
+ if [[ -n "${STRUCTURED_LOG_FILE:-}" ]] && [[ -s "${STRUCTURED_LOG_FILE}" ]] && command -v jq >/dev/null 2>&1; then
+ timeline_json=$(tail -n 80 "${STRUCTURED_LOG_FILE}" \
+ | jq -s 'map({timestamp:(.timestamp // ""), level:(.level // "INFO"), function:(.function // "unknown"), message:(.message // "")})')
+ elif [[ -s "${LOGFILE:-}" ]] && command -v jq >/dev/null 2>&1; then
+ timeline_json=$(tail -n 80 "${LOGFILE}" \
+ | awk -F'] ' '{
+ ts=$1; gsub(/^\[/,"",ts);
+ msg=$2;
+ if (msg ~ /Start function:/) { print "{\"timestamp\":\"" ts "\",\"level\":\"INFO\",\"function\":\"" msg "\",\"message\":\"started\"}" }
+ else if (msg ~ /End function:/) { print "{\"timestamp\":\"" ts "\",\"level\":\"SUCCESS\",\"function\":\"" msg "\",\"message\":\"completed\"}" }
+ }' \
+ | jq -s '.')
+ else
+ timeline_json="[]"
+ fi
+
+ # Quick links to important output files.
+ if command -v jq >/dev/null 2>&1; then
+ local link_path exists
+ links_json=$(
+ {
+ for entry in \
+ "Subdomains|subdomains/subdomains.txt" \
+ "Web Targets|webs/webs_all.txt" \
+ "Takeovers|webs/takeover.txt" \
+ "Nuclei Critical|nuclei_output/critical.txt" \
+ "Nuclei High|nuclei_output/high.txt" \
+ "Hotlist|hotlist.txt" \
+ "Performance Summary|.log/perf_summary.json" \
+ "Assets JSONL|assets.jsonl" \
+ "Screenshots Changed|screenshots/diff_changed.txt" \
+ "Latest Report JSON|report/latest/report.json" \
+ "Latest Report HTML|report/latest/index.html"; do
+ link_path="${entry#*|}"
+ exists=false
+ [[ -s "$link_path" ]] && exists=true
+ printf '{"name":"%s","path":"%s","exists":%s}\n' "${entry%%|*}" "$link_path" "$exists"
+ done
+ } | jq -s '.'
+ )
+ else
+ links_json="[]"
+ fi
+
+ if command -v jq >/dev/null 2>&1; then
+ if [[ -s ".incremental/history/latest/delta.json" ]]; then
+ monitor_delta_json=$(cat ".incremental/history/latest/delta.json")
+ else
+ monitor_delta_json='{}'
+ fi
+ if [[ -s ".incremental/history/latest/alerts.json" ]]; then
+ monitor_alerts_json=$(cat ".incremental/history/latest/alerts.json")
+ else
+ monitor_alerts_json='{}'
+ fi
+
+ jq -n \
+ --arg generated_at "$(date -Iseconds)" \
+ --arg domain "${domain:-unknown}" \
+ --arg mode "${opt_mode:-unknown}" \
+ --arg runtime "${runtime:-unknown}" \
+ --arg profile "${PERF_PROFILE:-balanced}" \
+ --arg quick_rescan "${QUICK_RESCAN:-false}" \
+ --arg incremental "${INCREMENTAL_MODE:-false}" \
+ --arg parallel "${PARALLEL_MODE:-true}" \
+ --arg axiom "${AXIOM:-false}" \
+ --argjson subs "$subs_count" \
+ --argjson webs "$webs_count" \
+ --argjson hosts "$hosts_count" \
+ --argjson screenshots "$screenshots_count" \
+ --argjson findings_total "$findings_total" \
+ --argjson sev_info "$sev_info" \
+ --argjson sev_low "$sev_low" \
+ --argjson sev_medium "$sev_medium" \
+ --argjson sev_high "$sev_high" \
+ --argjson sev_critical "$sev_critical" \
+ --argjson top_assets "$top_assets_json" \
+ --argjson timeline "$timeline_json" \
+ --argjson links "$links_json" \
+ --argjson delta "$monitor_delta_json" \
+ --argjson alerts "$monitor_alerts_json" \
+ '{
+ generated_at:$generated_at,
+ domain:$domain,
+ mode:$mode,
+ runtime:$runtime,
+ metadata:{
+ perf_profile:$profile,
+ quick_rescan:($quick_rescan == "true"),
+ incremental:($incremental == "true"),
+ parallel:($parallel != "false"),
+ axiom:($axiom == "true")
+ },
+ summary:{
+ subdomains:$subs,
+ webs:$webs,
+ hosts:$hosts,
+ screenshots:$screenshots,
+ findings_total:$findings_total
+ },
+ severities:{
+ info:$sev_info,
+ low:$sev_low,
+ medium:$sev_medium,
+ high:$sev_high,
+ critical:$sev_critical
+ },
+ top_assets:$top_assets,
+ timeline:$timeline,
+ links:$links,
+ delta_since_last:$delta,
+ alerts_last:$alerts
+ }' >"$report_json"
+ else
+ printf '{"generated_at":"%s","domain":"%s","mode":"%s","runtime":"%s"}\n' \
+ "$(date -Iseconds)" "${domain:-unknown}" "${opt_mode:-unknown}" "${runtime:-unknown}" >"$report_json"
+ fi
+
+ # HTML renderer with inlined JSON payload.
+ local report_payload
+ report_payload=$(jq -c '.' "$report_json" 2>/dev/null || echo '{}')
+ cat >"$report_html" <<EOF
+<!doctype html>
+<html lang="en">
+<head>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width,initial-scale=1" />
+ <title>reconFTW Report - ${domain}</title>
+ <style>
+ :root{--bg:#0b1320;--card:#111c2d;--text:#e8f0ff;--muted:#9ab0cc;--acc:#40c4ff;--ok:#32d583;--warn:#fdb022;--bad:#f97066}
+ body{margin:0;font-family:ui-sans-serif,system-ui,-apple-system,Segoe UI,Roboto,Ubuntu,sans-serif;background:linear-gradient(160deg,#0b1320,#0f1e35);color:var(--text)}
+ .wrap{max-width:1100px;margin:0 auto;padding:20px}
+ .grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(180px,1fr));gap:12px}
+ .card{background:var(--card);border:1px solid #1b2a44;border-radius:14px;padding:14px}
+ h1,h2{margin:.2rem 0 .6rem}
+ .muted{color:var(--muted);font-size:.92rem}
+ .kpi{font-size:1.6rem;font-weight:700}
+ table{width:100%;border-collapse:collapse}
+ th,td{padding:8px;border-bottom:1px solid #213451;text-align:left;font-size:.93rem}
+ a{color:var(--acc);text-decoration:none}
+ .sev{display:flex;gap:10px;flex-wrap:wrap}
+ .pill{padding:4px 10px;border-radius:999px;background:#15243b}
+ </style>
+</head>
+<body>
+ <div class="wrap">
+ <h1>reconFTW Consolidated Report</h1>
+ <div class="muted" id="meta"></div>
+ <div class="grid" id="kpis"></div>
+ <h2>Severities</h2>
+ <div class="sev" id="severities"></div>
+ <h2>Top Assets</h2>
+ <div class="card"><table><thead><tr><th>Asset</th><th>Score</th></tr></thead><tbody id="topAssets"></tbody></table></div>
+ <h2>Delta Since Last Run</h2>
+ <div class="sev" id="delta"></div>
+ <h2>Timeline</h2>
+ <div class="card"><table><thead><tr><th>Timestamp</th><th>Level</th><th>Function</th><th>Message</th></tr></thead><tbody id="timeline"></tbody></table></div>
+ <h2>Quick Links</h2>
+ <div class="card"><table><thead><tr><th>Name</th><th>Path</th></tr></thead><tbody id="links"></tbody></table></div>
+ </div>
+ <script>
+ const REPORT = ${report_payload};
+ const s = REPORT.summary || {};
+ const sev = REPORT.severities || {};
+ document.getElementById('meta').textContent =
+ "Domain: " + (REPORT.domain||"n/a") + " | Mode: " + (REPORT.mode||"n/a") + " | Runtime: " + (REPORT.runtime||"n/a") + " | Generated: " + (REPORT.generated_at||"");
+ const kpis = [
+ ["Subdomains", s.subdomains||0],["Webs", s.webs||0],["Hosts", s.hosts||0],["Screenshots", s.screenshots||0],["Findings", s.findings_total||0]
+ ];
+ document.getElementById('kpis').innerHTML = kpis.map(([k,v]) => '<div class="card"><div class="muted">'+k+'</div><div class="kpi">'+v+'</div></div>').join('');
+ document.getElementById('severities').innerHTML =
+ [["Critical",sev.critical||0],["High",sev.high||0],["Medium",sev.medium||0],["Low",sev.low||0],["Info",sev.info||0]]
+ .map(([k,v]) => '<span class="pill">'+k+': '+v+'</span>').join('');
+ document.getElementById('topAssets').innerHTML = (REPORT.top_assets||[]).map(x => '<tr><td>'+x.asset+'</td><td>'+x.score+'</td></tr>').join('') || '<tr><td colspan="2">No data</td></tr>';
+ const d = (REPORT.delta_since_last && REPORT.delta_since_last.deltas) ? REPORT.delta_since_last.deltas : {};
+ document.getElementById('delta').innerHTML =
+ [["New Subdomains",d.subdomains_new||0],["New Webs",d.webs_new||0],["New High",d.high_findings_new||0],["New Critical",d.critical_findings_new||0]]
+ .map(([k,v]) => '<span class="pill">'+k+': '+v+'</span>').join('');
+ document.getElementById('timeline').innerHTML = (REPORT.timeline||[]).slice(-40).reverse().map(x =>
+ '<tr><td>'+ (x.timestamp||'') +'</td><td>'+ (x.level||'') +'</td><td>'+ (x.function||'') +'</td><td>'+ (x.message||'') +'</td></tr>'
+ ).join('') || '<tr><td colspan="4">No data</td></tr>';
+ document.getElementById('links').innerHTML = (REPORT.links||[]).map(x => {
+ const mark = x.exists ? 'ok' : 'missing';
+ return '<tr><td>'+x.name+' ('+mark+')</td><td><a href="../'+x.path+'">'+x.path+'</a></td></tr>';
+ }).join('');
+ </script>
+</body>
+</html>
+EOF
+
+ # Stable latest report paths for automation/UI.
+ mkdir -p report/latest
+ cp "$report_json" report/latest/report.json 2>/dev/null || true
+ cp "$report_html" report/latest/index.html 2>/dev/null || true
+
+ notification "Consolidated report generated at report/index.html" info
+}
+
+# Escape a value for CSV output.
+_csv_escape() {
+ local v="${1:-}"
+ v=${v//\"/\"\"}
+ printf '"%s"' "$v"
+}
+
+# Normalize findings into line-delimited JSON for downstream automation.
+# Outputs:
+# - report/findings_normalized.jsonl
+# - report/assets.jsonl (copy of assets.jsonl if present)
+# - report/export_all.jsonl (assets + normalized findings)
+function export_findings_jsonl() {
+ ensure_dirs report || return 1
+ local out_norm="report/findings_normalized.jsonl"
+ local out_assets="report/assets.jsonl"
+ local out_merged="report/export_all.jsonl"
+ : >"$out_norm"
+
+ local sev f
+ for sev in info low medium high critical; do
+ f="nuclei_output/${sev}_json.txt"
+ [[ -s "$f" ]] || continue
+ if command -v jq >/dev/null 2>&1; then
+ jq -c --arg sev "$sev" '
+ {
+ type:"finding",
+ tool:"nuclei",
+ severity:(.info.severity // $sev),
+ template_id:(.["template-id"] // ""),
+ matcher_name:(.["matcher-name"] // ""),
+ finding_type:(.type // ""),
+ target:(.["matched-at"] // .host // ""),
+ host:(.host // ""),
+ name:(.info.name // ""),
+ tags:(.info.tags // []),
+ extracted_results:(.["extracted-results"] // []),
+ source_file:input_filename
+ }' "$f" >>"$out_norm" 2>/dev/null || true
+ else
+ while IFS= read -r line; do
+ [[ -z "$line" ]] && continue
+ printf '{"type":"finding","tool":"nuclei","severity":"%s","raw":"%s"}\n' \
+ "$sev" "$(printf '%s' "$line" | sed 's/"/\\"/g')" >>"$out_norm"
+ done <"$f"
+ fi
+ done
+
+ if [[ -s assets.jsonl ]]; then
+ cp assets.jsonl "$out_assets"
+ else
+ : >"$out_assets"
+ fi
+
+ cat "$out_assets" "$out_norm" >"$out_merged" 2>/dev/null || true
+}
+
+# Export CSV artifacts for quick triage.
+# Outputs:
+# - report/subdomains.csv
+# - report/webs.csv
+# - report/hosts.csv
+# - report/findings.csv
+function export_csv_artifacts() {
+ ensure_dirs report || return 1
+
+ # Subdomains CSV
+ {
+ printf "subdomain\n"
+ if [[ -s subdomains/subdomains.txt ]]; then
+ while IFS= read -r sub; do
+ [[ -z "$sub" ]] && continue
+ _csv_escape "$sub"; printf "\n"
+ done <subdomains/subdomains.txt
+ fi
+ } >report/subdomains.csv
+
+ # Webs CSV
+ {
+ printf "url,scheme,host\n"
+ if [[ -s webs/webs_all.txt ]]; then
+ while IFS= read -r url; do
+ [[ -z "$url" ]] && continue
+ local scheme host
+ scheme=$(printf '%s' "$url" | awk -F:// '{print $1}')
+ host=$(printf '%s' "$url" | awk -F/ '{print $3}' | sed 's/:.*$//')
+ _csv_escape "$url"; printf ","
+ _csv_escape "$scheme"; printf ","
+ _csv_escape "$host"; printf "\n"
+ done <webs/webs_all.txt
+ fi
+ } >report/webs.csv
+
+ # Hosts CSV
+ {
+ printf "ip\n"
+ if [[ -s hosts/ips.txt ]]; then
+ while IFS= read -r ip; do
+ [[ -z "$ip" ]] && continue
+ _csv_escape "$ip"; printf "\n"
+ done <hosts/ips.txt
+ fi
+ } >report/hosts.csv
+
+ # Findings CSV (prefer normalized JSONL)
+ if [[ ! -s report/findings_normalized.jsonl ]]; then
+ export_findings_jsonl
+ fi
+ if command -v jq >/dev/null 2>&1 && [[ -s report/findings_normalized.jsonl ]]; then
+ {
+ printf "tool,severity,template_id,name,target,host,finding_type,matcher_name\n"
+ jq -r '[.tool,.severity,.template_id,.name,.target,.host,.finding_type,.matcher_name] | @csv' report/findings_normalized.jsonl
+ } >report/findings.csv
+ else
+ {
+ printf "raw\n"
+ [[ -s report/findings_normalized.jsonl ]] && while IFS= read -r line; do _csv_escape "$line"; printf "\n"; done <report/findings_normalized.jsonl
+ } >report/findings.csv
+ fi
+}
+
+# Export orchestrator.
+# EXPORT_FORMAT values: json | html | csv | all
+function export_reports() {
+ local fmt="${EXPORT_FORMAT:-}"
+ [[ -z "$fmt" ]] && return 0
+
+ # Ensure base consolidated report exists for all export types.
+ [[ -s report/report.json && -s report/index.html ]] || generate_consolidated_report || true
+
+ case "$fmt" in
+ json)
+ export_findings_jsonl
+ notification "Exported JSON artifacts under report/" info
+ ;;
+ html)
+ notification "Exported HTML report at report/index.html" info
+ ;;
+ csv)
+ export_findings_jsonl
+ export_csv_artifacts
+ notification "Exported CSV artifacts under report/" info
+ ;;
+ all)
+ export_findings_jsonl
+ export_csv_artifacts
+ notification "Exported JSONL + CSV + HTML artifacts under report/" info
+ ;;
+ *)
+ notification "Unknown EXPORT_FORMAT '$fmt' (expected json|html|csv|all)" warn
+ ;;
+ esac
+}
+
function health_check() {
local failures=0
local warnings=0
diff --git a/modules/modes.sh b/modules/modes.sh
index a826a9b..08417ff 100644
--- a/modules/modes.sh
+++ b/modules/modes.sh
@@ -16,6 +16,7 @@ function start() {
# Validate configuration before starting
validate_config || exit $?
+ apply_performance_profile
# Check available disk space before starting (require at least 5GB by default)
local required_space_gb="${MIN_DISK_SPACE_GB:-5}"
@@ -39,7 +40,11 @@ function start() {
if [[ $upgrade_before_running == true ]]; then
${SCRIPTPATH}/install.sh --tools
fi
- tools_installed
+ if [[ "${MONITOR_MODE:-false}" == "true" ]] && [[ "${MONITOR_CYCLE:-1}" -gt 1 ]]; then
+ notification "Monitor cycle ${MONITOR_CYCLE}: skipping repeated tools check" info
+ else
+ tools_installed
+ fi
# Initialize incremental mode if enabled
incremental_init
@@ -110,6 +115,10 @@ function start() {
# Initialize cache for wordlists/resolvers
cache_init
+ cache_clean "${CACHE_MAX_AGE_DAYS:-30}" 2>>"${LOGFILE:-/dev/null}" || true
+ if [[ "${CACHE_REFRESH:-false}" == "true" ]]; then
+ notification "Cache refresh forced for this run" warn
+ fi
# init time saved estimator
TIME_SAVED_EST=0
@@ -127,7 +136,60 @@ function end() {
if [[ $opt_ai ]]; then
notification "[$(date +'%Y-%m-%d %H:%M:%S')] Sending ${domain} data to AI" info
mkdir -p "${dir}/ai_result" 2>>"${LOGFILE}"
- "${tools}/reconftw_ai/venv/bin/python3" "${tools}/reconftw_ai/reconftw_ai.py" --results-dir "${dir}" --output-dir "${dir}/ai_result" --model "${AI_MODEL}" --output-format "${AI_REPORT_TYPE}" --report-type "${AI_REPORT_PROFILE}" --prompts-file "${tools}/reconftw_ai/prompts.json" 2>>"${LOGFILE}" >/dev/null
+ local ai_script ai_prompts_file ai_venv_python ai_python ai_json_output ai_redact_flag ai_pull_flag ai_strict_flag
+ local -a ai_cmd
+ ai_script="${tools}/reconftw_ai/reconftw_ai.py"
+ ai_prompts_file="${AI_PROMPTS_FILE:-${tools}/reconftw_ai/prompts.json}"
+ ai_venv_python="${tools}/reconftw_ai/venv/bin/python3"
+ ai_python="${AI_EXECUTABLE:-python3}"
+ ai_json_output="${dir}/ai_result/reconftw_analysis.json"
+ ai_redact_flag="--redact"
+ ai_pull_flag=""
+ ai_strict_flag=""
+
+ if [[ "${AI_REDACT:-true}" != "true" ]]; then
+ ai_redact_flag="--no-redact"
+ fi
+ if [[ "${AI_ALLOW_MODEL_PULL:-false}" == "true" ]]; then
+ ai_pull_flag="--allow-model-pull"
+ fi
+ if [[ "${AI_STRICT:-false}" == "true" ]]; then
+ ai_strict_flag="--strict"
+ fi
+
+ if [[ -x "${ai_venv_python}" ]]; then
+ ai_python="${ai_venv_python}"
+ elif ! command -v "${ai_python}" >/dev/null 2>&1; then
+ notification "AI skipped: Python executable not found (${ai_python})" warn
+ ai_python=""
+ fi
+
+ if [[ -n "${ai_python}" && -f "${ai_script}" ]]; then
+ ai_cmd=(
+ "${ai_python}" "${ai_script}"
+ --results-dir "${dir}" \
+ --output-dir "${dir}/ai_result" \
+ --output-json "${ai_json_output}" \
+ --model "${AI_MODEL}" \
+ --output-format "${AI_REPORT_TYPE}" \
+ --report-type "${AI_REPORT_PROFILE}" \
+ --prompts-file "${ai_prompts_file}" \
+ --max-chars-per-file "${AI_MAX_CHARS_PER_FILE:-50000}" \
+ --max-files-per-category "${AI_MAX_FILES_PER_CATEGORY:-200}" \
+ "${ai_redact_flag}"
+ )
+ if [[ -n "${ai_pull_flag}" ]]; then
+ ai_cmd+=("${ai_pull_flag}")
+ fi
+ if [[ -n "${ai_strict_flag}" ]]; then
+ ai_cmd+=("${ai_strict_flag}")
+ fi
+ if ! "${ai_cmd[@]}" 2>>"${LOGFILE}" >/dev/null; then
+ notification "AI report failed; check ${LOGFILE} for details" warn
+ fi
+ elif [[ -n "${ai_python}" ]]; then
+ notification "AI skipped: reconftw_ai script not found at ${ai_script}" warn
+ fi
fi
find "$dir" -type f -empty -print | grep -v '.called_fn' | grep -v '.log' | grep -v '.tmp' | xargs -r rm -f -- 2>>"$LOGFILE" >/dev/null
@@ -218,6 +280,9 @@ function end() {
# Print performance timing summary
print_timing_summary
+ write_perf_summary
+ generate_consolidated_report || true
+ export_reports || true
}
@@ -332,23 +397,47 @@ function osint() {
function vulns() {
if [[ $VULNS_GENERAL == true ]]; then
- cors
- open_redirect
- ssrf_checks
- crlf_checks
- lfi
- ssti
- sqli
- xss
- command_injection
- prototype_pollution
- smuggling
- webcache
- spraying
- brokenLinks
- fuzzparams
- 4xxbypass
- test_ssl
+ if [[ "${PARALLEL_MODE:-true}" == "true" ]] && declare -f parallel_funcs &>/dev/null; then
+ # Parallel execution - group independent checks
+ printf "%b[*] Running vulnerability checks in parallel mode%b\n" "$bblue" "$reset"
+ if ! parallel_funcs 4 cors open_redirect crlf_checks xss; then
+ notification "Parallel vulns batch failed (group 1)" error
+ return 1
+ fi
+ if ! parallel_funcs 4 ssrf_checks lfi ssti sqli; then
+ notification "Parallel vulns batch failed (group 2)" error
+ return 1
+ fi
+ if ! parallel_funcs 3 command_injection prototype_pollution smuggling; then
+ notification "Parallel vulns batch failed (group 3)" error
+ return 1
+ fi
+ if ! parallel_funcs 3 webcache spraying brokenLinks; then
+ notification "Parallel vulns batch failed (group 4)" error
+ return 1
+ fi
+ fuzzparams
+ 4xxbypass
+ test_ssl
+ else
+ cors
+ open_redirect
+ ssrf_checks
+ crlf_checks
+ lfi
+ ssti
+ sqli
+ xss
+ command_injection
+ prototype_pollution
+ smuggling
+ webcache
+ spraying
+ brokenLinks
+ fuzzparams
+ 4xxbypass
+ test_ssl
+ fi
fi
}
@@ -420,54 +509,119 @@ function multi_osint() {
}
function recon() {
- domain_info
- ip_info
- emails
- google_dorks
- #github_dorks
- github_repos
- metadata
- apileaks
- third_party_misconfigs
- zonetransfer
- favicon
+ # Initialize progress tracking for selected execution model.
+ local progress_total
+ if [[ "${PARALLEL_MODE:-true}" == "true" ]] && declare -f parallel_funcs &>/dev/null; then
+ progress_total=24
+ else
+ progress_total=32
+ fi
+ progress_init "$progress_total"
+
+ if [[ "${PARALLEL_MODE:-true}" == "true" ]] && declare -f parallel_funcs &>/dev/null; then
+ progress_step "OSINT: domain_info, ip_info, emails, dorks"
+ if ! parallel_funcs 4 domain_info ip_info emails google_dorks; then
+ notification "Parallel OSINT batch failed (group 1)" error
+ return 1
+ fi
+ progress_step "OSINT: repos, metadata, api_leaks, 3rd_party"
+ if ! parallel_funcs 4 github_repos metadata apileaks third_party_misconfigs; then
+ notification "Parallel OSINT batch failed (group 2)" error
+ return 1
+ fi
+ progress_step "Zone transfer"
+ zonetransfer
+ progress_step "Favicon"
+ favicon
+ else
+ progress_step "domain_info"
+ domain_info
+ progress_step "ip_info"
+ ip_info
+ progress_step "emails"
+ emails
+ progress_step "google_dorks"
+ google_dorks
+ progress_step "github_repos"
+ #github_dorks
+ github_repos
+ progress_step "metadata"
+ metadata
+ progress_step "apileaks"
+ apileaks
+ progress_step "third_party_misconfigs"
+ third_party_misconfigs
+ progress_step "zonetransfer"
+ zonetransfer
+ progress_step "favicon"
+ favicon
+ fi
if [[ $AXIOM == true ]]; then
axiom_launch
axiom_selected
fi
+ progress_step "subdomains_full"
subdomains_full
+ progress_step "webprobe_full"
webprobe_full
+ progress_step "subtakeover"
subtakeover
remove_big_files
+ progress_step "s3buckets"
s3buckets
cloud_extra_providers
- screenshot
- # virtualhosts
- cdnprovider
- portscan
- geo_info
+
+ if [[ "${PARALLEL_MODE:-true}" == "true" ]] && declare -f parallel_funcs &>/dev/null; then
+ progress_step "screenshot, cdnprovider, portscan"
+ if ! parallel_funcs 3 screenshot cdnprovider portscan; then
+ notification "Parallel web/host batch failed" error
+ return 1
+ fi
+ progress_step "geo_info"
+ geo_info
+ else
+ progress_step "screenshot"
+ screenshot
+ # virtualhosts
+ progress_step "cdnprovider"
+ cdnprovider
+ progress_step "portscan"
+ portscan
+ progress_step "geo_info"
+ geo_info
+ fi
# Quick-rescan gating
subs_new=$(cat .tmp/subs_new_count 2>/dev/null || echo 1)
webs_new=$(cat .tmp/webs_new_count 2>/dev/null || echo 1)
if [[ $QUICK_RESCAN == true && $subs_new -eq 0 && $webs_new -eq 0 ]]; then
notification "Quick rescan: no new subs/webs; skipping heavy web stages" info
- # estimate time saved for skipped modules
+ progress_adjust_total -10
TIME_SAVED_EST=$((${TIME_SAVED_EST:-0} + \
${TIME_EST_WAF:-0} + ${TIME_EST_NUCLEI:-600} + ${TIME_EST_API:-300} + ${TIME_EST_GQL:-180} + \
${TIME_EST_FUZZ:-900} + ${TIME_EST_IIS:-60} + ${TIME_EST_URLCHECKS:-300} + ${TIME_EST_JSCHECKS:-300} + \
${TIME_EST_PARAM:-240} + ${TIME_EST_GRPC:-120}))
else
+ progress_step "waf_checks"
waf_checks
+ progress_step "nuclei_check"
nuclei_check
+ progress_step "graphql_scan"
graphql_scan
+ progress_step "fuzz"
fuzz
+ progress_step "iishortname"
iishortname
+ progress_step "urlchecks"
urlchecks
+ progress_step "jschecks"
jschecks
+ progress_step "websocket_checks"
websocket_checks
+ progress_step "param_discovery"
param_discovery
+ progress_step "grpc_reflection"
grpc_reflection
fi
@@ -475,10 +629,14 @@ function recon() {
axiom_shutdown
fi
+ progress_step "cms_scanner"
cms_scanner
+ progress_step "url_gf"
url_gf
+ progress_step "wordlist_gen"
wordlist_gen
wordlist_gen_roboxtractor
+ progress_step "password_dict"
password_dict
url_ext
}
@@ -852,10 +1010,146 @@ function zen_menu() {
end
}
+function monitor_mode() {
+ local selected_mode="${1:-r}"
+
+ if [[ -z "${selected_mode}" ]]; then
+ selected_mode="r"
+ fi
+
+ if [[ -n "${multi:-}" ]]; then
+ notification "Monitor mode does not support -m multi-target runs" error
+ return 1
+ fi
+ if [[ "${selected_mode}" != "w" ]] && [[ -n "${list:-}" ]]; then
+ notification "Monitor mode supports -l only with web mode (-w)" error
+ return 1
+ fi
+
+ if [[ -n "${dir_output:-}" ]]; then
+ notification "Monitor mode ignores -o output relocation to preserve incremental state" warn
+ unset dir_output
+ fi
+
+ if [[ ! "${MONITOR_INTERVAL_MIN:-}" =~ ^[0-9]+$ ]] || [[ "${MONITOR_INTERVAL_MIN:-0}" -lt 1 ]]; then
+ MONITOR_INTERVAL_MIN=60
+ fi
+ if [[ ! "${MONITOR_MAX_CYCLES:-}" =~ ^[0-9]+$ ]]; then
+ MONITOR_MAX_CYCLES=0
+ fi
+
+ INCREMENTAL_MODE=true
+ QUICK_RESCAN=true
+ DIFF=true
+ local interval_sec=$((MONITOR_INTERVAL_MIN * 60))
+ local cycle=0
+
+ notification "Monitor mode enabled (mode=${selected_mode}, interval=${MONITOR_INTERVAL_MIN}m, max_cycles=${MONITOR_MAX_CYCLES:-0})" info
+
+ while true; do
+ cycle=$((cycle + 1))
+ MONITOR_CYCLE=$cycle
+
+ notification "Monitor cycle ${cycle} started" info
+
+ case "$selected_mode" in
+ 'r')
+ start
+ recon
+ end
+ ;;
+ 's')
+ subs_menu
+ ;;
+ 'p')
+ passive
+ ;;
+ 'a')
+ export VULNS_GENERAL=true
+ all
+ ;;
+ 'w')
+ if [[ -n $list ]]; then
+ start
+ if [[ $list == /* ]]; then
+ cp "$list" "$dir/webs/webs.txt"
+ else
+ cp "${SCRIPTPATH}/$list" "$dir/webs/webs.txt"
+ fi
+ webs_menu
+ else
+ notification "Web mode in monitor requires -l list file" error
+ return 1
+ fi
+ ;;
+ 'n')
+ PRESERVE=true
+ start
+ osint
+ end
+ ;;
+ 'z')
+ zen_menu
+ ;;
+ *)
+ notification "Unsupported mode '${selected_mode}' for monitor. Use one of: r,s,p,a,w,n,z" error
+ return 1
+ ;;
+ esac
+
+ monitor_snapshot || true
+
+ if [[ "${MONITOR_MAX_CYCLES:-0}" -gt 0 ]] && [[ "$cycle" -ge "${MONITOR_MAX_CYCLES}" ]]; then
+ notification "Monitor finished after ${cycle} cycle(s)" good
+ break
+ fi
+
+ notification "Monitor cycle ${cycle} completed, sleeping ${MONITOR_INTERVAL_MIN} minute(s)" info
+ sleep "$interval_sec"
+ done
+}
+
+function report_only_mode() {
+ if [[ -z "${domain:-}" ]]; then
+ notification "Report-only mode requires -d <domain>" error
+ return 1
+ fi
+ if [[ -n "${list:-}" ]] || [[ -n "${multi:-}" ]]; then
+ notification "Report-only mode currently supports single-target only" error
+ return 1
+ fi
+
+ dir="${SCRIPTPATH}/Recon/$domain"
+ called_fn_dir="${dir}/.called_fn"
+ if [[ ! -d "$dir" ]]; then
+ notification "Target directory not found for report-only mode: $dir" error
+ return 1
+ fi
+
+ cd "$dir" || {
+ notification "Failed to enter target directory: $dir" error
+ return 1
+ }
+
+ mkdir -p .log report
+ NOW=$(date +"%F")
+ NOWT=$(date +"%T")
+ LOGFILE="${dir}/.log/${NOW}_${NOWT}_report_only.txt"
+ touch "$LOGFILE"
+ runtime="report-only"
+
+ notification "Report-only mode: rebuilding reports from existing artifacts" info
+ build_hotlist || true
+ write_perf_summary || true
+ generate_consolidated_report || true
+ export_reports || true
+ notification "Report-only rebuild completed for ${domain}" good
+}
+
function help() {
pt_header "Usage"
printf "\n Usage: $0 [-d domain.tld] [-m name] [-l list.txt] [-x oos.txt] [-i in.txt] "
- printf "\n [-r] [-s] [-p] [-a] [-w] [-n] [-z] [-c] [-y] [-h] [-f] [--ai] [--deep] [-o OUTPUT]\n\n"
+ printf "\n [-r] [-s] [-p] [-a] [-w] [-n] [-z] [-c] [-y] [-h] [-f] [--ai] [--deep] [--monitor] [--monitor-interval m] [--monitor-cycles n] [--report-only] [--refresh-cache] [--export fmt] [-o OUTPUT]\n\n"
printf " ${bblue}TARGET OPTIONS${reset}\n"
printf " -d domain.tld Target domain\n"
printf " -m company Target company name\n"
@@ -888,6 +1182,13 @@ function help() {
printf " --adaptive-rate Automatically adjust rate limits on errors (429/503)\n"
printf " --dry-run Show what would be executed without running commands\n"
printf " --parallel Run independent functions in parallel (faster but uses more resources)\n"
+ printf " --no-parallel Force sequential execution\n"
+ printf " --monitor Continuous monitoring mode (single target; -w supports -l)\n"
+ printf " --monitor-interval Minutes between cycles (default: 60)\n"
+ printf " --monitor-cycles Stop after N cycles (0 = infinite)\n"
+ printf " --report-only Rebuild report artifacts from existing Recon/<target>\n"
+ printf " --refresh-cache Force refresh of cached resolvers/wordlists\n"
+ printf " --export fmt Export artifacts: json|html|csv|all\n"
printf " \n"
printf " ${bblue}USAGE EXAMPLES${reset}\n"
printf " ${byellow}Perform full recon (without attacks):${reset}\n"
diff --git a/modules/subdomains.sh b/modules/subdomains.sh
index 831448e..525bd6c 100644
--- a/modules/subdomains.sh
+++ b/modules/subdomains.sh
@@ -200,6 +200,9 @@ _subdomains_init() {
NUMOFLINES_subs="0"
NUMOFLINES_probed="0"
+ # Escape domain for safe use in grep regex (dots are literal, not wildcards)
+ DOMAIN_ESCAPED=$(escape_domain_regex "$domain")
+
printf "%b#######################################################################%b\n\n" "$bgreen" "$reset"
if [[ $domain =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
@@ -255,17 +258,32 @@ _subdomains_enumerate() {
# Parallel execution using lib/parallel.sh
printf "%b[*] Running subdomain enumeration in parallel mode%b\n" "$bblue" "$reset"
+ # Phase 0: ASN enumeration (independent)
+ sub_asn
+
# Phase 1: Passive sources (all can run in parallel)
- parallel_funcs 4 sub_passive sub_crt
+ if ! parallel_funcs 4 sub_passive sub_crt; then
+ notification "Parallel subdomain batch failed (passive)" error
+ return 1
+ fi
# Phase 2: Active DNS resolution (parallel)
- parallel_funcs 3 sub_active sub_noerror sub_dns
+ if ! parallel_funcs 3 sub_active sub_noerror sub_dns; then
+ notification "Parallel subdomain batch failed (active)" error
+ return 1
+ fi
# Phase 3: Post-active (depend on resolved subdomains)
- parallel_funcs 2 sub_tls sub_analytics
+ if ! parallel_funcs 2 sub_tls sub_analytics; then
+ notification "Parallel subdomain batch failed (post-active)" error
+ return 1
+ fi
# Phase 4: Brute force (limited parallelism - resource intensive)
- parallel_funcs 2 sub_brute sub_permut sub_regex_permut sub_ia_permut
+ if ! parallel_funcs 2 sub_brute sub_permut sub_regex_permut sub_ia_permut; then
+ notification "Parallel subdomain batch failed (bruteforce/permutations)" error
+ return 1
+ fi
# Phase 5: Recursive and scraping (sequential - depends on previous results)
sub_recursive_passive
@@ -273,6 +291,7 @@ _subdomains_enumerate() {
sub_scraping
else
# Sequential execution (original behavior)
+ sub_asn
sub_passive
sub_crt
sub_active
@@ -361,8 +380,9 @@ _subdomains_finalize() {
# Usage: subdomains_full
# Uses PARALLEL_MODE global variable if set
function subdomains_full() {
- local parallel_flag=""
- [[ "${PARALLEL_MODE:-false}" == "true" ]] && parallel_flag="--parallel"
+ # Parallel mode is enabled by default; use PARALLEL_MODE=false to disable
+ local parallel_flag="--parallel"
+ [[ "${PARALLEL_MODE:-true}" == "false" ]] && parallel_flag=""
# Initialize
_subdomains_init || return 1
@@ -377,6 +397,60 @@ function subdomains_full() {
_subdomains_finalize
}
+function sub_asn() {
+ ensure_dirs .tmp subdomains hosts
+
+ if should_run "ASN_ENUM"; then
+ start_subfunc "${FUNCNAME[0]}" "Running: ASN Enumeration"
+
+ # Discover ASN/CIDR metadata for the current target domain.
+ if command -v asnmap &>/dev/null; then
+ local asn_json
+ asn_json=".tmp/asnmap_${domain}.json"
+ asnmap -d "$domain" -silent -j 2>>"$LOGFILE" >"$asn_json"
+
+ jq -r '.cidr // empty' "$asn_json" | sed '/^$/d' | sort -u >.tmp/asn_cidrs.txt
+ jq -r '.as_number // empty' "$asn_json" | sed '/^$/d' | sort -u >.tmp/asn_numbers.txt
+
+ if [[ -s .tmp/asn_cidrs.txt ]]; then
+ cp .tmp/asn_cidrs.txt hosts/asn_cidrs.txt
+ fi
+ if [[ -s .tmp/asn_numbers.txt ]]; then
+ cp .tmp/asn_numbers.txt hosts/asn_numbers.txt
+ fi
+
+ local cidr_count asn_count
+ cidr_count=$(wc -l <.tmp/asn_cidrs.txt 2>/dev/null | tr -d ' ')
+ asn_count=$(wc -l <.tmp/asn_numbers.txt 2>/dev/null | tr -d ' ')
+
+ printf "%b[%s] ASN enumeration found %s ASNs and %s CIDR ranges%b\n" \
+ "$bblue" "$(date +'%Y-%m-%d %H:%M:%S')" "${asn_count:-0}" "${cidr_count:-0}" "$reset"
+
+ # Optional: if asnmap yields discovered domains, feed them into subdomain pipeline.
+ jq -r '.domains[]? // empty' "$asn_json" \
+ | sed '/^$/d' \
+ | grep -E '^([a-zA-Z0-9\.\-]+\.)+[a-zA-Z]{1,}$' \
+ | grep "\.${DOMAIN_ESCAPED}$\|^${DOMAIN_ESCAPED}$" \
+ | sort -u \
+ | anew -q .tmp/subs_no_resolved.txt
+ if [[ -s .tmp/subs_no_resolved.txt ]]; then
+ printf "%b[%s] ASN sources added %s in-scope domains%b\n" \
+ "$bblue" "$(date +'%Y-%m-%d %H:%M:%S')" "$(wc -l <.tmp/subs_no_resolved.txt | tr -d ' ')" "$reset"
+ fi
+ else
+ printf "%b[!] asnmap not installed, skipping ASN enumeration%b\n" "$bred" "$reset"
+ fi
+
+ end_subfunc "${FUNCNAME[0]}" "${FUNCNAME[0]}"
+ else
+ if [[ $ASN_ENUM == false ]]; then
+ printf "\n${yellow}[$(date +'%Y-%m-%d %H:%M:%S')] ${FUNCNAME[0]} skipped due to configuration settings.${reset}\n"
+ else
+ printf "${yellow}[$(date +'%Y-%m-%d %H:%M:%S')] ${FUNCNAME[0]} already processed. To force, delete:\n $called_fn_dir/.${FUNCNAME[0]}${reset}\n\n"
+ fi
+ fi
+}
+
function sub_passive() {
ensure_dirs .tmp subdomains
@@ -554,7 +628,7 @@ function sub_active() {
fi
# Process subdomains and append new ones to subdomains.txt, count new lines
- if ! NUMOFLINES=$(grep "\.$domain$\|^$domain$" .tmp/subdomains_tmp.txt 2>>"$LOGFILE" \
+ if ! NUMOFLINES=$(grep "\.${DOMAIN_ESCAPED}$\|^${DOMAIN_ESCAPED}$" .tmp/subdomains_tmp.txt 2>>"$LOGFILE" \
| grep -E '^([a-zA-Z0-9\.\-]+\.)+[a-zA-Z]{1,}$' \
| anew subdomains/subdomains.txt | sed '/^$/d' | wc -l); then
printf "%b[!] Failed to process subdomains.%b\n" "$bred" "$reset"
@@ -595,7 +669,7 @@ function sub_tls() {
fi
if [[ -s ".tmp/subdomains_tlsx.txt" ]]; then
- grep "\.$domain$\|^$domain$" .tmp/subdomains_tlsx.txt \
+ grep "\.${DOMAIN_ESCAPED}$\|^${DOMAIN_ESCAPED}$" .tmp/subdomains_tlsx.txt \
| grep -aEo 'https?://[^ ]+' \
| sed "s/|__ //" | anew -q .tmp/subdomains_tlsx_clean.txt
fi
@@ -687,7 +761,7 @@ function sub_noerror() {
fi
# Process subdomains and append new ones to subdomains.txt, count new lines
- if ! NUMOFLINES=$(grep "\.$domain$\|^$domain$" .tmp/subs_noerror.txt 2>>"$LOGFILE" \
+ if ! NUMOFLINES=$(grep "\.${DOMAIN_ESCAPED}$\|^${DOMAIN_ESCAPED}$" .tmp/subs_noerror.txt 2>>"$LOGFILE" \
| grep -E '^([a-zA-Z0-9\.\-]+\.)+[a-zA-Z]{1,}$' \
| sed 's/^\*\.//' | anew subdomains/subdomains.txt | sed '/^$/d' | wc -l); then
printf "%b[!] Failed to process subdomains.%b\n" "$bred" "$reset"
@@ -732,12 +806,12 @@ function sub_dns() {
jq -r '.. | strings | select(test("^(\\d{1,3}\\.){3}\\d{1,3}$|^[0-9a-fA-F:]+$"))' <"subdomains/subdomains_dnsregs.json" \
| sort -u | hakip2host | awk '{print $3}' | unfurl -u domains \
- | sed -e 's/^\*\.//' -e 's/\.$//' -e '/\./!d' | grep "\.$domain$" \
+ | sed -e 's/^\*\.//' -e 's/\.$//' -e '/\./!d' | grep "\.${DOMAIN_ESCAPED}$" \
| grep -E '^([a-zA-Z0-9][-a-zA-Z0-9]*\.)+[a-zA-Z]{2,}$' | sort -u \
| anew -q .tmp/subdomains_dns.txt
for i in $(jq -r '.. | strings | select(test("^(\\d{1,3}\\.){3}\\d{1,3}$|^[0-9a-fA-F:]+$"))' <"subdomains/subdomains_dnsregs.json" | sort -u); do
- curl -s https://ip.thc.org/$i 2>>"$LOGFILE" | grep "\.$domain$" \
+ curl -s https://ip.thc.org/$i 2>>"$LOGFILE" | grep "\.${DOMAIN_ESCAPED}$" \
| grep -E '^([a-zA-Z0-9][-a-zA-Z0-9]*\.)+[a-zA-Z]{2,}$' | sort -u \
| anew -q .tmp/subdomains_dns.txt
done
@@ -781,7 +855,7 @@ function sub_dns() {
fi
fi
- if ! NUMOFLINES=$(grep "\.$domain$\|^$domain$" .tmp/subdomains_dns_resolved.txt 2>>"$LOGFILE" \
+ if ! NUMOFLINES=$(grep "\.${DOMAIN_ESCAPED}$\|^${DOMAIN_ESCAPED}$" .tmp/subdomains_dns_resolved.txt 2>>"$LOGFILE" \
| grep -E '^([a-zA-Z0-9\-\.]+\.)+[a-zA-Z]{1,}$' \
| anew subdomains/subdomains.txt | sed '/^$/d' | wc -l); then
printf "%b[!] Failed to count new subdomains.%b\n" "$bred" "$reset"
@@ -858,7 +932,7 @@ function sub_brute() {
fi
# Process subdomains and append new ones to subdomains.txt, count new lines
- if ! NUMOFLINES=$(grep "\.$domain$\|^$domain$" .tmp/subs_brute_valid.txt 2>>"$LOGFILE" \
+ if ! NUMOFLINES=$(grep "\.${DOMAIN_ESCAPED}$\|^${DOMAIN_ESCAPED}$" .tmp/subs_brute_valid.txt 2>>"$LOGFILE" \
| grep -E '^([a-zA-Z0-9\.\-]+\.)+[a-zA-Z]{1,}$' \
| sed 's/^\*\.//' | anew subdomains/subdomains.txt | sed '/^$/d' | wc -l); then
printf "%b[!] Failed to process subdomains.%b\n" "$bred" "$reset"
@@ -992,7 +1066,7 @@ function sub_scraping() {
sed_i '/^.\{2048\}./d' .tmp/katana.txt
cat .tmp/katana.txt | unfurl -u domains 2>>"$LOGFILE" \
- | grep "\.$domain$" \
+ | grep "\.${DOMAIN_ESCAPED}$" \
| grep -E '^([a-zA-Z0-9\.\-]+\.)+[a-zA-Z]{1,}$' \
| anew -q .tmp/scrap_subs.txt
fi
@@ -1012,7 +1086,7 @@ function sub_scraping() {
if [[ -s ".tmp/scrap_subs_resolved.txt" ]]; then
if ! NUMOFLINES=$(cat .tmp/scrap_subs_resolved.txt 2>>"$LOGFILE" \
- | grep "\.$domain$\|^$domain$" \
+ | grep "\.${DOMAIN_ESCAPED}$\|^${DOMAIN_ESCAPED}$" \
| grep -E '^([a-zA-Z0-9\.\-]+\.)+[a-zA-Z]{1,}$' \
| anew subdomains/subdomains.txt \
| tee .tmp/diff_scrap.txt \
@@ -1097,7 +1171,7 @@ function sub_analytics() {
fi
if [[ -s ".tmp/analytics_subs_tmp.txt" ]]; then
- grep "\.$domain$\|^$domain$" .tmp/analytics_subs_tmp.txt \
+ grep "\.${DOMAIN_ESCAPED}$\|^${DOMAIN_ESCAPED}$" .tmp/analytics_subs_tmp.txt \
| grep -E '^([a-zA-Z0-9\.\-]+\.)+[a-zA-Z]{1,}$' \
| sed "s/|__ //" | anew -q .tmp/analytics_subs_clean.txt
@@ -1278,7 +1352,7 @@ function sub_permut() {
fi
# Process subdomains and append new ones to subdomains.txt, count new lines
- if ! NUMOFLINES=$(grep "\.$domain$\|^$domain$" .tmp/permute_subs.txt 2>>"$LOGFILE" \
+ if ! NUMOFLINES=$(grep "\.${DOMAIN_ESCAPED}$\|^${DOMAIN_ESCAPED}$" .tmp/permute_subs.txt 2>>"$LOGFILE" \
| grep -E '^([a-zA-Z0-9\.\-]+\.)+[a-zA-Z]{1,}$' \
| anew subdomains/subdomains.txt | sed '/^$/d' | wc -l); then
printf "%b[!] Failed to process subdomains.%b\n" "$bred" "$reset"
@@ -1378,7 +1452,7 @@ function sub_regex_permut() {
fi
fi
- if ! NUMOFLINES=$(grep "\.$domain$\|^$domain$" .tmp/regulator.txt 2>>"$LOGFILE" \
+ if ! NUMOFLINES=$(grep "\.${DOMAIN_ESCAPED}$\|^${DOMAIN_ESCAPED}$" .tmp/regulator.txt 2>>"$LOGFILE" \
| grep -E '^([a-zA-Z0-9\.\-]+\.)+[a-zA-Z]{1,}$' \
| anew subdomains/subdomains.txt \
| sed '/^$/d' \
@@ -1459,7 +1533,7 @@ function sub_ia_permut() {
fi
fi
- if ! NUMOFLINES=$(grep "\.$domain$\|^$domain$" .tmp/subwiz_resolved.txt 2>>"$LOGFILE" \
+ if ! NUMOFLINES=$(grep "\.${DOMAIN_ESCAPED}$\|^${DOMAIN_ESCAPED}$" .tmp/subwiz_resolved.txt 2>>"$LOGFILE" \
| grep -E '^([a-zA-Z0-9\.\-]+\.)+[a-zA-Z]{1,}$' \
| anew subdomains/subdomains.txt \
| sed '/^$/d' \
@@ -1561,7 +1635,7 @@ function sub_recursive_passive() {
fi
if [[ -s ".tmp/passive_recurs_tmp.txt" ]]; then
- if ! NUMOFLINES=$(grep "\.$domain$\|^$domain$" .tmp/passive_recurs_tmp.txt 2>>"$LOGFILE" \
+ if ! NUMOFLINES=$(grep "\.${DOMAIN_ESCAPED}$\|^${DOMAIN_ESCAPED}$" .tmp/passive_recurs_tmp.txt 2>>"$LOGFILE" \
| grep -E '^([a-zA-Z0-9\.\-]+\.)+[a-zA-Z]{1,}$' \
| sed '/^$/d' \
| anew subdomains/subdomains.txt \
@@ -1754,7 +1828,7 @@ function sub_recursive_brute() {
# Process final results
if [[ -s ".tmp/brute_perm_recursive_final.txt" ]]; then
- if ! NUMOFLINES=$(grep "\.$domain$\|^$domain$" .tmp/brute_perm_recursive_final.txt 2>>"$LOGFILE" \
+ if ! NUMOFLINES=$(grep "\.${DOMAIN_ESCAPED}$\|^${DOMAIN_ESCAPED}$" .tmp/brute_perm_recursive_final.txt 2>>"$LOGFILE" \
| grep -E '^([a-zA-Z0-9\.\-]+\.)+[a-zA-Z]{1,}$' \
| sed '/^$/d' \
| anew subdomains/subdomains.txt \
diff --git a/modules/utils.sh b/modules/utils.sh
index f313d26..a2f9037 100644
--- a/modules/utils.sh
+++ b/modules/utils.sh
@@ -1,5 +1,5 @@
#!/bin/bash
-# shellcheck disable=SC2154 # Variables defined in reconftw.cfg
+# shellcheck disable=SC2154,SC2034 # Variables defined in reconftw.cfg and runtime globals shared across modules
# reconFTW - Utility functions module
# Contains: deleteOutScoped, cleanup, rotate_logs, sanitization, validation,
# getElapsedTime, retry, disk check, rate limiting, caching
@@ -131,6 +131,63 @@ function validate_config() {
return 0
}
+# Auto-tune concurrency knobs according to host resources and PERF_PROFILE.
+# Usage: apply_performance_profile
+function apply_performance_profile() {
+ # shellcheck disable=SC2034 # Thread/rate vars are consumed by sourced modules at runtime
+ local profile="${PERF_PROFILE:-balanced}"
+ local cores mem_gb
+
+ cores=$(nproc 2>/dev/null || sysctl -n hw.ncpu 2>/dev/null || echo 4)
+ if [[ "$OSTYPE" == "darwin"* ]]; then
+ mem_gb=$(( $(sysctl -n hw.memsize 2>/dev/null || echo 8589934592) / 1024 / 1024 / 1024 ))
+ else
+ mem_gb=$(( $(awk '/MemTotal/ {print $2}' /proc/meminfo 2>/dev/null || echo 8388608) / 1024 / 1024 ))
+ fi
+ [[ "$cores" =~ ^[0-9]+$ ]] || cores=4
+ [[ "$mem_gb" =~ ^[0-9]+$ ]] || mem_gb=8
+
+ case "$profile" in
+ low)
+ PARALLEL_MAX_JOBS=${PARALLEL_MAX_JOBS:-2}
+ FFUF_THREADS=$((cores * 4))
+ HTTPX_THREADS=$((cores * 5))
+ HTTPX_UNCOMMONPORTS_THREADS=$((cores * 10))
+ KATANA_THREADS=$((cores * 3))
+ DALFOX_THREADS=$((cores * 20))
+ ;;
+ max)
+ PARALLEL_MAX_JOBS=${PARALLEL_MAX_JOBS:-$((cores > 2 ? cores - 1 : 2))}
+ FFUF_THREADS=$((cores * 14))
+ HTTPX_THREADS=$((cores * 16))
+ HTTPX_UNCOMMONPORTS_THREADS=$((cores * 28))
+ KATANA_THREADS=$((cores * 6))
+ DALFOX_THREADS=$((cores * 60))
+ ;;
+ *)
+ PARALLEL_MAX_JOBS=${PARALLEL_MAX_JOBS:-$((cores > 1 ? cores / 2 : 1))}
+ FFUF_THREADS=$((cores * 10))
+ HTTPX_THREADS=$((cores * 12))
+ HTTPX_UNCOMMONPORTS_THREADS=$((cores * 25))
+ KATANA_THREADS=$((cores * 5))
+ DALFOX_THREADS=$((cores * 50))
+ ;;
+ esac
+
+ # Clamp aggressive defaults for low-memory hosts.
+ if [[ "$mem_gb" -lt 6 ]]; then
+ ((PARALLEL_MAX_JOBS > 2)) && PARALLEL_MAX_JOBS=2
+ ((FFUF_THREADS > 24)) && FFUF_THREADS=24
+ ((HTTPX_THREADS > 40)) && HTTPX_THREADS=40
+ ((HTTPX_UNCOMMONPORTS_THREADS > 80)) && HTTPX_UNCOMMONPORTS_THREADS=80
+ fi
+
+ ((PARALLEL_MAX_JOBS < 1)) && PARALLEL_MAX_JOBS=1
+ printf "%b[%s] PERF_PROFILE=%s | cores=%s mem=%sGB | jobs=%s ffuf=%s httpx=%s%b\n" \
+ "$bblue" "$(date +'%Y-%m-%d %H:%M:%S')" "$profile" "$cores" "$mem_gb" \
+ "$PARALLEL_MAX_JOBS" "$FFUF_THREADS" "$HTTPX_THREADS" "$reset"
+}
+
function getElapsedTime {
runtime=""
local T=$2-$1
@@ -340,6 +397,7 @@ MIN_RATE_LIMIT=10
MAX_RATE_LIMIT=500
RATE_LIMIT_BACKOFF_FACTOR=0.5
RATE_LIMIT_INCREASE_FACTOR=1.2
+PARALLEL_PRESSURE_LEVEL=${PARALLEL_PRESSURE_LEVEL:-normal}
# Detect rate limit errors in command output
# Usage: detect_rate_limit_error <output_file_or_string>
@@ -364,22 +422,24 @@ function adjust_rate_limit() {
case "$action" in
decrease)
new_limit=$(awk "BEGIN {printf \"%.0f\", $CURRENT_RATE_LIMIT * $RATE_LIMIT_BACKOFF_FACTOR}")
- if [ "$new_limit" -lt "$MIN_RATE_LIMIT" ]; then
- new_limit=$MIN_RATE_LIMIT
- fi
- CURRENT_RATE_LIMIT=$new_limit
- printf "%b[%s] Rate limit decreased to %d req/s due to errors%b\n" \
- "$yellow" "$(date +'%Y-%m-%d %H:%M:%S')" "$CURRENT_RATE_LIMIT" "$reset" | tee -a "$LOGFILE"
- ;;
+ if [ "$new_limit" -lt "$MIN_RATE_LIMIT" ]; then
+ new_limit=$MIN_RATE_LIMIT
+ fi
+ CURRENT_RATE_LIMIT=$new_limit
+ PARALLEL_PRESSURE_LEVEL="high"
+ printf "%b[%s] Rate limit decreased to %d req/s due to errors%b\n" \
+ "$yellow" "$(date +'%Y-%m-%d %H:%M:%S')" "$CURRENT_RATE_LIMIT" "$reset" | tee -a "$LOGFILE"
+ ;;
increase)
new_limit=$(awk "BEGIN {printf \"%.0f\", $CURRENT_RATE_LIMIT * $RATE_LIMIT_INCREASE_FACTOR}")
- if [ "$new_limit" -gt "$MAX_RATE_LIMIT" ]; then
- new_limit=$MAX_RATE_LIMIT
- fi
- CURRENT_RATE_LIMIT=$new_limit
- printf "%b[%s] Rate limit increased to %d req/s%b\n" \
- "$bgreen" "$(date +'%Y-%m-%d %H:%M:%S')" "$CURRENT_RATE_LIMIT" "$reset" >>"$LOGFILE"
- ;;
+ if [ "$new_limit" -gt "$MAX_RATE_LIMIT" ]; then
+ new_limit=$MAX_RATE_LIMIT
+ fi
+ CURRENT_RATE_LIMIT=$new_limit
+ PARALLEL_PRESSURE_LEVEL="normal"
+ printf "%b[%s] Rate limit increased to %d req/s%b\n" \
+ "$bgreen" "$(date +'%Y-%m-%d %H:%M:%S')" "$CURRENT_RATE_LIMIT" "$reset" >>"$LOGFILE"
+ ;;
esac
# Update tool-specific rate limits
@@ -570,13 +630,27 @@ function cache_init() {
mkdir -p "$CACHE_DIR"/{wordlists,resolvers,tools}
}
+# Resolve TTL per cache type.
+# Usage: cache_max_age_for_type <wordlists|resolvers|tools>
+function cache_max_age_for_type() {
+ case "${1:-tools}" in
+ resolvers) echo "${CACHE_MAX_AGE_DAYS_RESOLVERS:-${CACHE_MAX_AGE_DAYS:-30}}" ;;
+ wordlists) echo "${CACHE_MAX_AGE_DAYS_WORDLISTS:-${CACHE_MAX_AGE_DAYS:-30}}" ;;
+ tools|*) echo "${CACHE_MAX_AGE_DAYS_TOOLS:-${CACHE_MAX_AGE_DAYS:-30}}" ;;
+ esac
+}
+
# Check if cached file is still valid (less than 30 days old)
# Usage: cache_is_valid <cache_file>
# Returns: 0 if valid, 1 if expired or missing
function cache_is_valid() {
local cache_file="$1"
+ local cache_type="${2:-tools}"
+ local max_age_days
+ max_age_days=$(cache_max_age_for_type "$cache_type")
[[ ! -f "$cache_file" ]] && return 1
+ [[ "${CACHE_REFRESH:-false}" == "true" ]] && return 1
# Get file modification time in seconds since epoch
local file_mtime
@@ -598,7 +672,7 @@ function cache_is_valid() {
local file_age_seconds=$((current_time - file_mtime))
local file_age_days=$((file_age_seconds / 86400))
- if [ $file_age_days -lt ${CACHE_MAX_AGE_DAYS:-30} ]; then
+ if [ "$file_age_days" -lt "$max_age_days" ]; then
printf "%b[%s] Using cached file (age: %d days): %s%b\n" \
"$bgreen" "$(date +'%Y-%m-%d %H:%M:%S')" "$file_age_days" "$(basename "$cache_file")" "$reset" >>"$LOGFILE"
return 0
@@ -613,19 +687,27 @@ function cache_is_valid() {
# Usage: cached_download <url> <destination> [cache_name]
# If cache exists and is valid, copies from cache instead of downloading
function cached_download() {
+ cached_download_typed "$1" "$2" "${3:-$(basename "$1")}" "tools"
+}
+
+# Download file with typed cache support
+# Usage: cached_download_typed <url> <destination> [cache_name] [cache_type]
+function cached_download_typed() {
local url="$1"
local destination="$2"
local cache_name="${3:-$(basename "$url")}"
- local cache_file="$CACHE_DIR/$cache_name"
+ local cache_type="${4:-tools}"
+ local cache_file="$CACHE_DIR/$cache_type/$cache_name"
cache_init
# Check if we have valid cached version
- if cache_is_valid "$cache_file"; then
+ if cache_is_valid "$cache_file" "$cache_type"; then
cp "$cache_file" "$destination"
return 0
fi
+ mkdir -p "$(dirname "$cache_file")"
# Download fresh copy
printf "%b[%s] Downloading: %s%b\n" \
"$bblue" "$(date +'%Y-%m-%d %H:%M:%S')" "$(basename "$url")" "$reset"
diff --git a/modules/vulns.sh b/modules/vulns.sh
index 889b7a7..9db2b83 100644
--- a/modules/vulns.sh
+++ b/modules/vulns.sh
@@ -463,7 +463,7 @@ function test_ssl() {
if ! ensure_dirs hosts vulns; then return 1; fi
# Check if the function should run
- if { [[ ! -f "$called_fn_dir/.${FUNCNAME[0]}" ]] || [[ $DIFF == true ]]; } && [[ $TEST_SSL == true ]]; then
+ if should_run "TEST_SSL"; then
start_func "${FUNCNAME[0]}" "SSL Test"
diff --git a/modules/web.sh b/modules/web.sh
index 28f65ee..4f7f1ee 100644
--- a/modules/web.sh
+++ b/modules/web.sh
@@ -663,16 +663,98 @@ function waf_checks() {
}
+# Prepare WAF-aware target lists for nuclei scanning
+# Splits webs into WAF-protected and non-WAF lists for rate-limiting
+# Sets: WAF_LIST, NOWAF_LIST variables
+_nuclei_prepare_waf_lists() {
+ WAF_LIST=.tmp/webs_waf.txt
+ NOWAF_LIST=.tmp/webs_nowaf.txt
+
+ sort -u .tmp/webs_subs.txt -o .tmp/webs_subs.txt 2>/dev/null || true
+ : >"$WAF_LIST"
+ : >"$NOWAF_LIST"
+
+ if [[ -s webs/webs_wafs.txt ]]; then
+ cut -d';' -f1 webs/webs_wafs.txt | sed 's/https\?:\/\///' | sed 's/\/$//' | sort -u >.tmp/waf_hosts.txt
+ awk -F/ '{print $3}' .tmp/webs_subs.txt | sed 's/\:$//' | while read -r host; do
+ if grep -Fxq "$host" .tmp/waf_hosts.txt; then
+ awk -v h="$host" -F/ '{u=$3; sub(/:.*/,"",u); if (u==h) print $0}' .tmp/webs_subs.txt | anew -q "$WAF_LIST"
+ else
+ awk -v h="$host" -F/ '{u=$3; sub(/:.*/,"",u); if (u==h) print $0}' .tmp/webs_subs.txt | anew -q "$NOWAF_LIST"
+ fi
+ done
+ else
+ cp .tmp/webs_subs.txt "$NOWAF_LIST"
+ fi
+
+ # Include slow hosts (429/403) into WAF list as well
+ if [[ -s .tmp/slow_hosts.txt ]]; then
+ while read -r host; do
+ awk -v h="$host" -F/ '{u=$3; sub(/:.*/,"",u); if (u==h) print $0}' .tmp/webs_subs.txt | anew -q "$WAF_LIST"
+ done <.tmp/slow_hosts.txt
+ fi
+}
+
+# Parse nuclei JSON output to human-readable text and display results
+# Usage: _nuclei_parse_results severity_level
+_nuclei_parse_results() {
+ local crit="$1"
+ if [[ -s "nuclei_output/${crit}_json.txt" ]]; then
+ jq -r '["[" + .["template-id"] + (if .["matcher-name"] != null then ":" + .["matcher-name"] else "" end) + "] [" + .["type"] + "] [" + .info.severity + "] " + (.["matched-at"] // .host) + (if .["extracted-results"] != null then " " + (.["extracted-results"] | @json) else "" end)] | .[]' nuclei_output/${crit}_json.txt >nuclei_output/${crit}.txt
+ append_assets_from_file finding value nuclei_output/${crit}.txt
+ if [[ -s "nuclei_output/${crit}.txt" ]]; then
+ cat "nuclei_output/${crit}.txt"
+ fi
+ fi
+}
+
+# Run nuclei scan locally with WAF-aware rate limiting
+# Usage: _nuclei_scan_local
+_nuclei_scan_local() {
+ IFS=',' read -ra severity_array <<<"$NUCLEI_SEVERITY"
+
+ for crit in "${severity_array[@]}"; do
+ printf "${yellow}\n[$(date +'%Y-%m-%d %H:%M:%S')] Running: Nuclei Severity: $crit ${reset}\n\n"
+ # Non-WAF at default rate
+ if [[ -s $NOWAF_LIST ]]; then
+ run_command nuclei -l "$NOWAF_LIST" -severity "$crit" -nh -rl "$NUCLEI_RATELIMIT" -silent -retries 2 ${NUCLEI_EXTRA_ARGS} -t ${NUCLEI_TEMPLATES_PATH} -j -o "nuclei_output/${crit}_json.txt" 2>>"$LOGFILE" >/dev/null
+ fi
+ # WAF hosts at slower rate
+ if [[ -s $WAF_LIST ]]; then
+ local slow_rl
+ slow_rl=$((NUCLEI_RATELIMIT / 3 + 1))
+ run_command nuclei -l "$WAF_LIST" -severity "$crit" -nh -rl "$slow_rl" -silent -retries 2 ${NUCLEI_EXTRA_ARGS} -t ${NUCLEI_TEMPLATES_PATH} -j -o "nuclei_output/${crit}_waf_json.txt" 2>>"$LOGFILE" >/dev/null
+ [[ -s nuclei_output/${crit}_waf_json.txt ]] && cat nuclei_output/${crit}_waf_json.txt >>nuclei_output/${crit}_json.txt
+ fi
+ _nuclei_parse_results "$crit"
+ done
+ printf "\n\n"
+}
+
+# Run nuclei scan via Axiom distributed fleet
+# Usage: _nuclei_scan_axiom
+_nuclei_scan_axiom() {
+ IFS=',' read -ra severity_array <<<"$NUCLEI_SEVERITY"
+
+ for crit in "${severity_array[@]}"; do
+ printf "${yellow}\n[$(date +'%Y-%m-%d %H:%M:%S')] Running: Axiom Nuclei Severity: $crit. Check results in nuclei_output folder.${reset}\n\n"
+ run_command axiom-scan .tmp/webs_subs.txt -m nuclei \
+ --nuclei-templates "$NUCLEI_TEMPLATES_PATH" \
+ -severity "$crit" -nh -rl "$NUCLEI_RATELIMIT" \
+ -silent -retries 2 "$NUCLEI_EXTRA_ARGS" -j -o "nuclei_output/${crit}_json.txt" "$AXIOM_EXTRA_ARGS" 2>>"$LOGFILE" >/dev/null
+ _nuclei_parse_results "$crit"
+ done
+ printf "\n\n"
+}
+
function nuclei_check() {
# Create necessary directories
if ! ensure_dirs .tmp webs subdomains nuclei_output; then return 1; fi
# Check if the function should run
- if { [[ ! -f "$called_fn_dir/.${FUNCNAME[0]}" ]] || [[ $DIFF == true ]]; } && [[ $NUCLEICHECK == true ]]; then
+ if should_run "NUCLEICHECK"; then
start_func "${FUNCNAME[0]}" "Templates-based Web Scanner"
- #cent update -p ${NUCLEI_TEMPLATES_PATH} &>/dev/null
- # Update nuclei templates once per run
maybe_update_nuclei
# Handle multi mode and initialize subdomains.txt if necessary
@@ -687,110 +769,40 @@ function nuclei_check() {
fi
# Combine webs_all.txt targets (with protocol) - avoid duplicate scans
- # Note: subdomains without protocol would cause duplicate nuclei scans
if [[ ! -s ".tmp/webs_subs.txt" ]]; then
cat webs/webs_all.txt 2>>"$LOGFILE" | sort -u >.tmp/webs_subs.txt
fi
- # Prepare WAF-aware lists
- WAF_LIST=.tmp/webs_waf.txt
- NOWAF_LIST=.tmp/webs_nowaf.txt
- if [[ -s webs/webs_wafs.txt ]]; then
- cut -d';' -f1 webs/webs_wafs.txt | sed 's/https\?:\/\///' | sed 's/\/$//' | sort -u >.tmp/waf_hosts.txt
- awk -F/ '{print $3}' .tmp/webs_subs.txt | sed 's/\:$//' | while read -r host; do
- if grep -q "^$host$" .tmp/waf_hosts.txt; then
- grep "://${host}[:/\n]" .tmp/webs_subs.txt | anew -q "$WAF_LIST"
- else
- grep "://${host}[:/\n]" .tmp/webs_subs.txt | anew -q "$NOWAF_LIST"
- fi
- done
- else
- cp .tmp/webs_subs.txt "$NOWAF_LIST"
- fi
+ # Prepare WAF-aware lists and run scans
+ _nuclei_prepare_waf_lists
- # Include slow hosts (429/403) into WAF list as well
- if [[ -s .tmp/slow_hosts.txt ]]; then
- while read -r host; do
- grep "://${host}[:/\n]" .tmp/webs_subs.txt | anew -q "$WAF_LIST"
- done <.tmp/slow_hosts.txt
- fi
-
- # Check if AXIOM is enabled
if [[ $AXIOM != true ]]; then
- # Split severity levels into an array
- IFS=',' read -ra severity_array <<<"$NUCLEI_SEVERITY"
-
- for crit in "${severity_array[@]}"; do
- printf "${yellow}\n[$(date +'%Y-%m-%d %H:%M:%S')] Running: Nuclei Severity: $crit ${reset}\n\n"
- # Non-WAF at default rate
- if [[ -s $NOWAF_LIST ]]; then
- run_command nuclei -l "$NOWAF_LIST" -severity "$crit" -nh -rl "$NUCLEI_RATELIMIT" -silent -retries 2 ${NUCLEI_EXTRA_ARGS} -t ${NUCLEI_TEMPLATES_PATH} -j -o "nuclei_output/${crit}_json.txt" 2>>"$LOGFILE" >/dev/null
- fi
- # WAF hosts at slower rate
- if [[ -s $WAF_LIST ]]; then
- local slow_rl
- slow_rl=$((NUCLEI_RATELIMIT / 3 + 1))
- run_command nuclei -l "$WAF_LIST" -severity "$crit" -nh -rl "$slow_rl" -silent -retries 2 ${NUCLEI_EXTRA_ARGS} -t ${NUCLEI_TEMPLATES_PATH} -j -o "nuclei_output/${crit}_waf_json.txt" 2>>"$LOGFILE" >/dev/null
- [[ -s nuclei_output/${crit}_waf_json.txt ]] && cat nuclei_output/${crit}_waf_json.txt >>nuclei_output/${crit}_json.txt
- fi
- # Parse the JSON output and save the results to a text file
- if [[ -s "nuclei_output/${crit}_json.txt" ]]; then
- jq -r '["[" + .["template-id"] + (if .["matcher-name"] != null then ":" + .["matcher-name"] else "" end) + "] [" + .["type"] + "] [" + .info.severity + "] " + (.["matched-at"] // .host) + (if .["extracted-results"] != null then " " + (.["extracted-results"] | @json) else "" end)] | .[]' nuclei_output/${crit}_json.txt >nuclei_output/${crit}.txt
- # Asset store: append findings
- append_assets_from_file finding value nuclei_output/${crit}.txt
- # Display the results if the output file exists and is not empty
- if [[ -s "nuclei_output/${crit}.txt" ]]; then
- cat "nuclei_output/${crit}.txt"
- fi
- fi
- done
- printf "\n\n"
+ _nuclei_scan_local
else
- # Split severity levels into an array
- IFS=',' read -ra severity_array <<<"$NUCLEI_SEVERITY"
-
- for crit in "${severity_array[@]}"; do
- printf "${yellow}\n[$(date +'%Y-%m-%d %H:%M:%S')] Running: Axiom Nuclei Severity: $crit. Check results in nuclei_output folder.${reset}\n\n"
- # Run axiom-scan with nuclei module for each severity level
- run_command axiom-scan .tmp/webs_subs.txt -m nuclei \
- --nuclei-templates "$NUCLEI_TEMPLATES_PATH" \
- -severity "$crit" -nh -rl "$NUCLEI_RATELIMIT" \
- -silent -retries 2 "$NUCLEI_EXTRA_ARGS" -j -o "nuclei_output/${crit}_json.txt" "$AXIOM_EXTRA_ARGS" 2>>"$LOGFILE" >/dev/null
- # Parse the JSON output and save the results to a text file
- if [[ -s "nuclei_output/${crit}_json.txt" ]]; then
- jq -r '["[" + .["template-id"] + (if .["matcher-name"] != null then ":" + .["matcher-name"] else "" end) + "] [" + .["type"] + "] [" + .info.severity + "] " + (.["matched-at"] // .host) + (if .["extracted-results"] != null then " " + (.["extracted-results"] | @json) else "" end)] | .[]' nuclei_output/${crit}_json.txt >nuclei_output/${crit}.txt
-
- # Display the results if the output file exists and is not empty
- if [[ -s "nuclei_output/${crit}.txt" ]]; then
- cat "nuclei_output/${crit}.txt"
- fi
- fi
- done
- printf "\n\n"
+ _nuclei_scan_axiom
fi
# Faraday integration
if [[ $FARADAY == true ]]; then
- # Check if the Faraday server is running
if ! faraday-cli status 2>>"$LOGFILE" >/dev/null; then
printf "%b[!] Faraday server is not running. Skipping Faraday integration.%b\n" "$bred" "$reset"
else
- if [[ -s "nuclei_output/${crit}_json.txt" ]]; then
- faraday-cli tool report -w $FARADAY_WORKSPACE --plugin-id nuclei nuclei_output/${crit}_json.txt 2>>"$LOGFILE" >/dev/null
- fi
+ # Report all severity levels to Faraday
+ IFS=',' read -ra severity_array <<<"$NUCLEI_SEVERITY"
+ for crit in "${severity_array[@]}"; do
+ if [[ -s "nuclei_output/${crit}_json.txt" ]]; then
+ faraday-cli tool report -w "$FARADAY_WORKSPACE" --plugin-id nuclei "nuclei_output/${crit}_json.txt" 2>>"$LOGFILE" >/dev/null
+ fi
+ done
fi
fi
end_func "Results are saved in $domain/nuclei_output folder" "${FUNCNAME[0]}"
-
- # Emit plugin event
plugins_emit after_nuclei "$domain" "$dir"
else
- # Handle cases where NUCLEICHECK is false or the function has already been processed
if [[ $NUCLEICHECK == false ]]; then
pt_msg_warn "${FUNCNAME[0]} skipped due to configuration"
elif [[ $domain =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
- # Domain is an IP address; skip the function
return
else
pt_msg_warn "${FUNCNAME[0]} already processed. To force, delete ${called_fn_dir}/.${FUNCNAME[0]}"
@@ -887,75 +899,84 @@ function grpc_reflection() {
fi
}
+# Classify targets into normal and slow lists for adaptive fuzzing
+_fuzz_classify_targets() {
+ sort -u webs/webs_all.txt -o webs/webs_all.txt 2>/dev/null || true
+ : >.tmp/webs_slow.txt
+ : >.tmp/webs_normal.txt
+ if [[ -s .tmp/slow_hosts.txt ]]; then
+ while read -r host; do
+ awk -v h="$host" -F/ '{u=$3; sub(/:.*/,"",u); if (u==h) print $0}' webs/webs_all.txt | anew -q .tmp/webs_slow.txt
+ done <.tmp/slow_hosts.txt
+ comm -23 <(sort -u webs/webs_all.txt) <(sort -u .tmp/webs_slow.txt) >.tmp/webs_normal.txt
+ else
+ cp webs/webs_all.txt .tmp/webs_normal.txt
+ fi
+}
+
+# Run ffuf locally with interlace, handling normal and slow targets separately
+_fuzz_run_local() {
+ _fuzz_classify_targets
+
+ if [[ -s .tmp/webs_normal.txt ]]; then
+ interlace -tL .tmp/webs_normal.txt -threads ${INTERLACE_THREADS} -c "ffuf ${FFUF_FLAGS} -t ${FFUF_THREADS} -rate ${FFUF_RATELIMIT} -H \"${HEADER}\" -w ${fuzz_wordlist} -maxtime ${FFUF_MAXTIME} -u _target_/FUZZ -o _output_/_cleantarget_.json" -o "$dir/.tmp/fuzzing" 2>>"$LOGFILE" >/dev/null
+ fi
+
+ if [[ -s .tmp/webs_slow.txt ]]; then
+ local slow_threads=$((FFUF_THREADS / 3))
+ [[ $slow_threads -lt 5 ]] && slow_threads=5
+ local slow_rate=$FFUF_RATELIMIT
+ [[ ${FFUF_RATELIMIT:-0} -eq 0 ]] && slow_rate=50 || slow_rate=$((FFUF_RATELIMIT / 3 + 1))
+ interlace -tL .tmp/webs_slow.txt -threads ${INTERLACE_THREADS} -c "ffuf ${FFUF_FLAGS} -t ${slow_threads} -rate ${slow_rate} -H \"${HEADER}\" -w ${fuzz_wordlist} -maxtime ${FFUF_MAXTIME} -u _target_/FUZZ -o _output_/_cleantarget_.json" -o "$dir/.tmp/fuzzing" 2>>"$LOGFILE" >/dev/null
+ fi
+}
+
+# Run ffuf via axiom-scan and parse per-subdomain results
+_fuzz_run_axiom() {
+ cached_download_typed "${fuzzing_remote_list}" ".tmp/fuzzing_remote_list.txt" "onelistforallmicro.txt" "wordlists"
+ axiom-scan webs/webs_all.txt -m ffuf -wL .tmp/fuzzing_remote_list.txt -H "${HEADER}" $FFUF_FLAGS -s -maxtime $FFUF_MAXTIME -oJ "$dir/.tmp/ffuf-content.json" $AXIOM_EXTRA_ARGS 2>>"$LOGFILE" >/dev/null
+
+ while read -r sub; do
+ local sub_out
+ sub_out=$(echo "$sub" | sed -e 's|^[^/]*//||' -e 's|/.*$||')
+ [[ -s "$dir/.tmp/ffuf-content.json" ]] && jq -r 'try .results[] | "\(.status) \(.length) \(.url)"' "$dir/.tmp/ffuf-content.json" | grep "$sub" | sort -k1 | anew -q "fuzzing/${sub_out}.txt"
+ done <webs/webs_all.txt
+}
+
+# Merge all per-subdomain fuzzing results into fuzzing_full.txt
+_fuzz_merge_results() {
+ find "$dir/fuzzing/" -type f -iname "*.txt" -exec cat {} + 2>>"$LOGFILE" | sort -k1 | anew -q "$dir/fuzzing/fuzzing_full.txt"
+}
+
function fuzz() {
- # Create necessary directories
ensure_dirs .tmp/fuzzing webs fuzzing
- # Check if the function should run
if { [[ ! -f "$called_fn_dir/.${FUNCNAME[0]}" ]] || [[ $DIFF == true ]]; } && [[ $FUZZ == true ]] \
&& ! [[ $domain =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
start_func "${FUNCNAME[0]}" "Web Directory Fuzzing"
- # Handle multi mode and initialize subdomains.txt if necessary
+ # Handle multi mode initialization
if [[ -n $multi ]] && [[ ! -f "$dir/webs/webs.txt" ]]; then
- if ! printf "%b\n" "$domain" >"$dir/webs/webs.txt"; then
- printf "%b[!] Failed to create webs.txt.%b\n" "$bred" "$reset"
- fi
- if ! touch webs/webs_uncommon_ports.txt; then
- printf "%b[!] Failed to initialize webs_uncommon_ports.txt.%b\n" "$bred" "$reset"
- fi
+ printf "%b\n" "$domain" >"$dir/webs/webs.txt" || printf "%b[!] Failed to create webs.txt.%b\n" "$bred" "$reset"
+ touch webs/webs_uncommon_ports.txt 2>>"$LOGFILE" || true
fi
- # Combine webs.txt and webs_uncommon_ports.txt into webs_all.txt if it doesn't exist
if [[ ! -s "webs/webs_all.txt" ]]; then
cat webs/webs.txt webs/webs_uncommon_ports.txt 2>/dev/null | anew -q webs/webs_all.txt
fi
if [[ -s "webs/webs_all.txt" ]]; then
if [[ $AXIOM != true ]]; then
- # Split targets by slow hosts
- : >.tmp/webs_slow.txt
- : >.tmp/webs_normal.txt
- if [[ -s .tmp/slow_hosts.txt ]]; then
- while read -r host; do
- grep "://${host}[:/\n]" webs/webs_all.txt | anew -q .tmp/webs_slow.txt
- done <.tmp/slow_hosts.txt
- comm -23 <(sort -u webs/webs_all.txt) <(sort -u .tmp/webs_slow.txt) >.tmp/webs_normal.txt
- else
- cp webs/webs_all.txt .tmp/webs_normal.txt
- fi
-
- # Normal targets
- if [[ -s .tmp/webs_normal.txt ]]; then
- interlace -tL .tmp/webs_normal.txt -threads ${INTERLACE_THREADS} -c "ffuf ${FFUF_FLAGS} -t ${FFUF_THREADS} -rate ${FFUF_RATELIMIT} -H \"${HEADER}\" -w ${fuzz_wordlist} -maxtime ${FFUF_MAXTIME} -u _target_/FUZZ -o _output_/_cleantarget_.json" -o $dir/.tmp/fuzzing 2>>"$LOGFILE" >/dev/null
- fi
- # Slow targets with reduced threads/rate
- if [[ -s .tmp/webs_slow.txt ]]; then
- slow_threads=$((FFUF_THREADS / 3))
- [[ $slow_threads -lt 5 ]] && slow_threads=5
- slow_rate=$FFUF_RATELIMIT
- [[ ${FFUF_RATELIMIT:-0} -eq 0 ]] && slow_rate=50 || slow_rate=$((FFUF_RATELIMIT / 3 + 1))
- interlace -tL .tmp/webs_slow.txt -threads ${INTERLACE_THREADS} -c "ffuf ${FFUF_FLAGS} -t ${slow_threads} -rate ${slow_rate} -H \"${HEADER}\" -w ${fuzz_wordlist} -maxtime ${FFUF_MAXTIME} -u _target_/FUZZ -o _output_/_cleantarget_.json" -o $dir/.tmp/fuzzing 2>>"$LOGFILE" >/dev/null
- fi
- for sub in $(cat webs/webs_all.txt); do
- sub_out=$(echo $sub | sed -e 's|^[^/]*//||' -e 's|/.*$||')
- done
- find $dir/fuzzing/ -type f -iname "*.txt" -exec cat {} + 2>>"$LOGFILE" | sort -k1 | anew -q $dir/fuzzing/fuzzing_full.txt
+ _fuzz_run_local
else
- cached_download "${fuzzing_remote_list}" ".tmp/fuzzing_remote_list.txt" "onelistforallmicro.txt"
- axiom-scan webs/webs_all.txt -m ffuf -wL .tmp/fuzzing_remote_list.txt -H "${HEADER}" $FFUF_FLAGS -s -maxtime $FFUF_MAXTIME -oJ $dir/.tmp/ffuf-content.json $AXIOM_EXTRA_ARGS 2>>"$LOGFILE" >/dev/null
-
- for sub in $(cat webs/webs_all.txt); do
- sub_out=$(echo $sub | sed -e 's|^[^/]*//||' -e 's|/.*$||')
- [ -s "$dir/.tmp/ffuf-content.json" ] && cat $dir/.tmp/ffuf-content.json | jq -r 'try .results[] | "\(.status) \(.length) \(.url)"' | grep $sub | sort -k1 | anew -q fuzzing/${sub_out}.txt
- done
- find $dir/fuzzing/ -type f -iname "*.txt" -exec cat {} + 2>>"$LOGFILE" | sort -k1 | anew -q $dir/fuzzing/fuzzing_full.txt
+ _fuzz_run_axiom
fi
- end_func "Results are saved in $domain/fuzzing/*subdomain*.txt" ${FUNCNAME[0]}
+ _fuzz_merge_results
+ end_func "Results are saved in $domain/fuzzing/*subdomain*.txt" "${FUNCNAME[0]}"
else
- end_func "No $domain/webs/webs_all.txt file found, fuzzing skipped " ${FUNCNAME[0]}
+ end_func "No $domain/webs/webs_all.txt file found, fuzzing skipped " "${FUNCNAME[0]}"
fi
else
diff --git a/reconftw.cfg b/reconftw.cfg
index bc460f7..a468748 100644
--- a/reconftw.cfg
+++ b/reconftw.cfg
@@ -27,6 +27,11 @@ MIN_DISK_SPACE_GB=0 # Minimum required disk space in GB before starting reconnai
# Incremental mode configuration
INCREMENTAL_MODE=false # Only scan new findings since last run (use --incremental flag to enable)
+MONITOR_MODE=false # Continuous monitor mode (enabled by --monitor)
+MONITOR_INTERVAL_MIN=60 # Minutes between monitoring cycles
+MONITOR_MAX_CYCLES=0 # 0 = run forever until interrupted
+ALERT_SUPPRESSION=true # Suppress repeated monitor alerts using fingerprint history
+ALERT_SEEN_FILE=".incremental/alerts_seen.hashes" # Fingerprint store for alert suppression
# Adaptive rate limiting configuration
ADAPTIVE_RATE_LIMIT=false # Automatically adjust rate limits when encountering 429/503 errors (use --adaptive-rate flag to enable)
@@ -37,6 +42,10 @@ RATE_LIMIT_INCREASE_FACTOR=1.2 # Multiply rate by this on success (1.2 = 20% fas
# Cache configuration
CACHE_MAX_AGE_DAYS=30 # Maximum age in days for cached wordlists/resolvers (30 = 1 month)
+CACHE_MAX_AGE_DAYS_RESOLVERS=7 # Resolver cache TTL
+CACHE_MAX_AGE_DAYS_WORDLISTS=30 # Wordlist cache TTL
+CACHE_MAX_AGE_DAYS_TOOLS=14 # Tool metadata cache TTL
+CACHE_REFRESH=false # Force-refresh cached resources (can be enabled with --refresh-cache)
# Log rotation
MAX_LOG_FILES=10 # Maximum number of log files to keep per target
@@ -106,6 +115,7 @@ SUBDOMAINS_GENERAL=true # Enable or disable the whole Subdomains module
SUBPASSIVE=true # Passive subdomains search
SUBCRT=true # crtsh search
CTR_LIMIT=999999 # Limit the number of results
+ASN_ENUM=true # ASN enumeration with asnmap for CIDR discovery
DNS_TIME_FENCE_DAYS=0 # Filter crt.sh results to last N days (0 = disabled, recommended: 90)
DEEP_WILDCARD_FILTER=false # Enable deep wildcard detection to filter wildcards at all subdomain levels
EXCLUDE_SENSITIVE=false # Exclude sensitive domains (gov, mil, edu, banks) - see config/sensitive_domains.txt
@@ -125,7 +135,7 @@ SUB_RECURSIVE_BRUTE=false # Needs big disk space and time to resolve
ZONETRANSFER=true # Check zone transfer
S3BUCKETS=true # Check S3 buckets misconfigs
REVERSE_IP=false # Check reverse IP subdomain search (set True if your target is CIDR/IP)
-TLS_PORTS="21,22,25,80,110,135,143,261,271,324,443,448,465,563,614,631,636,664,684,695,832,853,854,990,993,989,992,994,995,1129,1131,1184,2083,2087,2089,2096,2221,2252,2376,2381,2478,2479,2482,2484,2679,2762,3077,3078,3183,3191,3220,3269,3306,3410,3424,3471,3496,3509,3529,3539,3535,3660,36611,3713,3747,3766,3864,3885,3995,3896,4031,4036,4062,4064,4081,4083,4116,4335,4336,4536,4590,4740,4843,4849,5443,5007,5061,5321,5349,5671,5783,5868,5986,5989,5990,6209,6251,6443,6513,6514,6619,6697,6771,7202,7443,7673,7674,7677,7775,8243,8443,8991,8989,9089,9295,9318,9443,9444,9614,9802,10161,10162,11751,12013,12109,14143,15002,16995,41230,16993,20003"
+TLS_PORTS=$(cat "${SCRIPTPATH}/config/tls_ports.txt" 2>/dev/null | tr -d '\n') # TLS ports for certificate grabbing
INSCOPE=false # Uses inscope tool to filter the scope, requires .scope file in reconftw folder
# Web detection
@@ -133,7 +143,7 @@ WEBPROBESIMPLE=true # Web probing on 80/443
WEBPROBEFULL=true # Web probing in a large port list
WEBSCREENSHOT=true # Webs screenshooting
VIRTUALHOSTS=false # Check virtualhosts by fuzzing HOST header
-UNCOMMON_PORTS_WEB="81,300,591,593,832,981,1010,1311,1099,2082,2095,2096,2480,3000,3001,3002,3003,3128,3333,4243,4567,4711,4712,4993,5000,5104,5108,5280,5281,5601,5800,6543,7000,7001,7396,7474,8000,8001,8008,8014,8042,8060,8069,8080,8081,8083,8088,8090,8091,8095,8118,8123,8172,8181,8222,8243,8280,8281,8333,8337,8443,8500,8834,8880,8888,8983,9000,9001,9043,9060,9080,9090,9091,9092,9200,9443,9502,9800,9981,10000,10250,11371,12443,15672,16080,17778,18091,18092,20720,32000,55440,55672"
+UNCOMMON_PORTS_WEB=$(cat "${SCRIPTPATH}/config/uncommon_ports_web.txt" 2>/dev/null | tr -d '\n') # Uncommon web ports for full probing
# Host
FAVICON=true # Check Favicon domain discovery
@@ -197,6 +207,10 @@ WEBCACHE=true # Check for Web Cache issues
BYPASSER4XX=true # Check for 4XX bypasses
FUZZPARAMS=true # Fuzz parameters values
+# Parallelization
+PARALLEL_MODE=true # Run independent functions in parallel (faster, uses more resources). Disable with --no-parallel or set false.
+PERF_PROFILE="balanced" # Performance profile: low|balanced|max
+
# Extra features
NOTIFICATION=false # Notification for every function
SOFT_NOTIFICATION=false # Only for start/end
@@ -213,17 +227,18 @@ FFUF_FLAGS=" -mc all -fc 404 -sf -noninteractive -of json" # Ffuf flags
HTTPX_FLAGS=" -follow-redirects -random-agent -status-code -silent -title -web-server -tech-detect -location -content-length" # Httpx flags for simple web probing
# HTTP options
-HEADER="User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:72.0) Gecko/20100101 Firefox/72.0" # Default header
-
-# Threads
-FFUF_THREADS=40
-HTTPX_THREADS=50
-HTTPX_UNCOMMONPORTS_THREADS=100
-KATANA_THREADS=20
-BRUTESPRAY_THREADS=20
-BRUTESPRAY_CONCURRENCE=10
-DNSTAKE_THREADS=100
-DALFOX_THREADS=200
+HEADER="User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:128.0) Gecko/20100101 Firefox/128.0" # Default header
+
+# Threads (auto-scaled based on CPU cores, override to set fixed values)
+AVAILABLE_CORES=$(nproc 2>/dev/null || sysctl -n hw.ncpu 2>/dev/null || echo 4)
+FFUF_THREADS=$((AVAILABLE_CORES * 10))
+HTTPX_THREADS=$((AVAILABLE_CORES * 12))
+HTTPX_UNCOMMONPORTS_THREADS=$((AVAILABLE_CORES * 25))
+KATANA_THREADS=$((AVAILABLE_CORES * 5))
+BRUTESPRAY_THREADS=$((AVAILABLE_CORES * 5))
+BRUTESPRAY_CONCURRENCE=$((AVAILABLE_CORES * 2))
+DNSTAKE_THREADS=$((AVAILABLE_CORES * 25))
+DALFOX_THREADS=$((AVAILABLE_CORES * 50))
PUREDNS_PUBLIC_LIMIT=0 # Set between 2000 - 10000 if your router blows up, 0 means unlimited
PUREDNS_TRUSTED_LIMIT=400
PUREDNS_WILDCARDTEST_LIMIT=30
@@ -275,14 +290,21 @@ AXIOM_EXTRA_ARGS="" # Leave empty if you don't want to add extra arguments
# Faraday-Server
FARADAY=false # Enable or disable Faraday integration
FARADAY_SERVER="http://localhost:5985" # Faraday server address
-FARADAY_USER="faraday" # Faraday user
-FARADAY_PASS="FARADAY_PASSWORD" # Faraday password
+FARADAY_USER="${FARADAY_USER:-faraday}" # Faraday user (set via env var or secrets.cfg)
+FARADAY_PASS="${FARADAY_PASS:-}" # Faraday password (set via env var or secrets.cfg, never hardcode)
FARADAY_WORKSPACE="reconftw" # Faraday workspace
# AI
+AI_EXECUTABLE="python3" # Python executable fallback if reconftw_ai venv python is not available
AI_MODEL="llama3:8b" # Model to use
AI_REPORT_TYPE="md" # Report type to use (md, txt)
AI_REPORT_PROFILE="bughunter" # Report profile to use (executive, brief, or bughunter)
+AI_PROMPTS_FILE="" # Optional custom prompts file for reconftw_ai (empty uses default prompts.json)
+AI_MAX_CHARS_PER_FILE=50000 # Max chars loaded per file before truncation
+AI_MAX_FILES_PER_CATEGORY=200 # Max files loaded per category for AI context
+AI_REDACT=true # Redact sensitive indicators before AI analysis
+AI_ALLOW_MODEL_PULL=false # Allow reconftw_ai to auto-pull missing model
+AI_STRICT=false # Fail AI analysis if one or more categories have no data
# API & Advanced Web Checks
GRAPHQL_CHECK=true # Detect GraphQL endpoints and introspection
@@ -298,6 +320,8 @@ ARJUN_THREADS=10
# Data & Automation
ASSET_STORE=true # Append assets/findings to assets.jsonl
+EXPORT_FORMAT="" # Export artifacts at end of scan: json|html|csv|all (empty = disabled)
+REPORT_ONLY=false # Rebuild reports from existing results without running scans (use --report-only)
QUICK_RESCAN=false # Skip heavy steps if no new subdomains/webs
CHUNK_LIMIT=2000 # Split very large lists into chunks (urls, webs)
HOTLIST_TOP=50 # Number of top risky assets to highlight
diff --git a/reconftw.sh b/reconftw.sh
index c256445..7ba26ac 100755
--- a/reconftw.sh
+++ b/reconftw.sh
@@ -111,7 +111,7 @@ if [[ $OSTYPE == "darwin"* ]]; then
PATH="$(brew --prefix gnu-sed)/libexec/gnubin:$PATH"
fi
-PROGARGS=$(getopt -o 'd:m:l:x:i:o:f:q:c:zrspanwvyh' --long 'domain:,list:,recon,subdomains,passive,all,web,osint,zen,deep,help,vps,ai,check-tools,health-check,quick-rescan,incremental,adaptive-rate,dry-run,parallel' -n 'reconFTW' -- "$@")
+PROGARGS=$(getopt -o 'd:m:l:x:i:o:f:q:c:zrspanwvyh' --long 'domain:,list:,recon,subdomains,passive,all,web,osint,zen,deep,help,vps,ai,check-tools,health-check,quick-rescan,incremental,adaptive-rate,dry-run,parallel,no-parallel,monitor,monitor-interval:,monitor-cycles:,refresh-cache,export:,report-only' -n 'reconFTW' -- "$@")
exit_status=$?
if [[ $exit_status -ne 0 ]]; then
@@ -313,6 +313,46 @@ while true; do
shift
continue
;;
+ '--no-parallel')
+ PARALLEL_MODE=false
+ shift
+ continue
+ ;;
+ '--monitor')
+ CLI_MONITOR_MODE=true
+ shift
+ continue
+ ;;
+ '--monitor-interval')
+ CLI_MONITOR_INTERVAL_MIN="$2"
+ shift 2
+ continue
+ ;;
+ '--monitor-cycles')
+ CLI_MONITOR_MAX_CYCLES="$2"
+ shift 2
+ continue
+ ;;
+ '--refresh-cache')
+ CLI_CACHE_REFRESH=true
+ shift
+ continue
+ ;;
+ '--export')
+ CLI_EXPORT_FORMAT="$2"
+ if [[ ! "$CLI_EXPORT_FORMAT" =~ ^(json|html|csv|all)$ ]]; then
+ printf "%b[%s] ERROR: Invalid --export value '%s' (allowed: json|html|csv|all)%b\n" \
+ "$bred" "$(date +'%Y-%m-%d %H:%M:%S')" "$CLI_EXPORT_FORMAT" "$reset" >&2
+ exit 1
+ fi
+ shift 2
+ continue
+ ;;
+ '--report-only')
+ CLI_REPORT_ONLY=true
+ shift
+ continue
+ ;;
'--help' | '-h')
break
;;
@@ -324,19 +364,6 @@ while true; do
esac
done
-# Initialize some variables
-#opt_deep="${opt_deep:=false}"
-#rate_limit="${rate_limit:=0}"
-#outOfScope_file="${outOfScope_file:=}"
-#inScope_file="${inScope_file:=}"
-#domain="${domain:=}"
-#multi="${multi:=}"
-#list="${list:=}"
-#opt_mode="${opt_mode:=}"
-#custom_function="${custom_function:=}"
-#AXIOM="${AXIOM:=false}"
-#AXIOM_POST_START="${AXIOM_POST_START:=}"
-#CUSTOM_CONFIG="${CUSTOM_CONFIG:=}"
# This is the first thing to do to read in alternate config
SCRIPTPATH="$(
@@ -354,11 +381,31 @@ SCRIPTPATH="$(
if [[ -s $CUSTOM_CONFIG ]]; then
# shellcheck source=/home/six2dez/Tools/reconftw/custom_config.cfg
. "${CUSTOM_CONFIG}" || {
- echo "Error importing reconftw.ctg"
+ echo "Error importing custom config"
exit 1
}
fi
+# Re-apply CLI overrides after config load (config defaults should not clobber CLI flags)
+if [[ "${CLI_MONITOR_MODE:-false}" == "true" ]]; then
+ MONITOR_MODE=true
+fi
+if [[ -n "${CLI_MONITOR_INTERVAL_MIN:-}" ]]; then
+ MONITOR_INTERVAL_MIN="${CLI_MONITOR_INTERVAL_MIN}"
+fi
+if [[ -n "${CLI_MONITOR_MAX_CYCLES:-}" ]]; then
+ MONITOR_MAX_CYCLES="${CLI_MONITOR_MAX_CYCLES}"
+fi
+if [[ "${CLI_CACHE_REFRESH:-false}" == "true" ]]; then
+ CACHE_REFRESH=true
+fi
+if [[ -n "${CLI_EXPORT_FORMAT:-}" ]]; then
+ EXPORT_FORMAT="${CLI_EXPORT_FORMAT}"
+fi
+if [[ "${CLI_REPORT_ONLY:-false}" == "true" ]]; then
+ REPORT_ONLY=true
+fi
+
if [[ $opt_deep ]]; then
DEEP=true
fi
@@ -370,7 +417,7 @@ if [[ $rate_limit ]]; then
fi
if [[ -n $outOfScope_file ]]; then
- isAsciiText $outOfScope_file
+ isAsciiText "$outOfScope_file"
if [[ "False" == "$IS_ASCII" ]]; then
printf "\n\n${bred} Out of Scope file is not a text file${reset}\n\n"
exit
@@ -378,7 +425,7 @@ if [[ -n $outOfScope_file ]]; then
fi
if [[ -n $inScope_file ]]; then
- isAsciiText $inScope_file
+ isAsciiText "$inScope_file"
if [[ "False" == "$IS_ASCII" ]]; then
printf "\n\n${bred} In Scope file is not a text file${reset}\n\n"
exit
@@ -431,6 +478,16 @@ else
flist=''
fi
+if [[ "${REPORT_ONLY:-false}" == "true" ]]; then
+ report_only_mode
+ exit
+fi
+
+if [[ "${MONITOR_MODE:-false}" == "true" ]]; then
+ monitor_mode "${opt_mode:-r}"
+ exit
+fi
+
case $opt_mode in
'r')
if [[ -n $multi ]]; then
@@ -561,15 +618,15 @@ case $opt_mode in
else
export DIFF=true
dir="${SCRIPTPATH}/Recon/$domain"
- cd $dir || {
+ cd "$dir" || {
echo "Failed to cd directory '$dir'"
exit 1
}
LOGFILE="${dir}/.log/${NOW}_${NOWT}.txt"
called_fn_dir=$dir/.called_fn
$custom_function
- cd ${SCRIPTPATH} || {
- echo "Failed to cd directory '$dir'"
+ cd "${SCRIPTPATH}" || {
+ echo "Failed to cd directory '${SCRIPTPATH}'"
exit 1
}
fi
diff --git a/tests.txt b/tests.txt
new file mode 100644
index 0000000..59b98e6
--- /dev/null
+++ b/tests.txt
@@ -0,0 +1,217 @@
+tests
+
+## 1) Validación base (rápida)
+
+ ./reconftw.sh --health-check
+ ./reconftw.sh --check-tools
+ bash -n reconftw.sh modules/*.sh lib/*.sh
+
+ Qué esperar:
+
+ - --health-check: estado general OK/WARN de entorno.
+ - --check-tools: lista de herramientas faltantes si hay problemas.
+ - bash -n: sin errores de sintaxis.
+
+ ———
+
+ ## 2) Tests automáticos nuevos (Plan D)
+
+ ./tests/run_tests.sh --unit
+ ./tests/run_tests.sh --smoke
+ ./tests/run_tests.sh --integration
+ ./tests/run_tests.sh --all
+
+ Qué esperar:
+
+ - --unit: valida funciones core, monitor snapshot, exports, perf profile.
+ - --smoke: valida flujos clave rápidos (--report-only, --export, monitor básico).
+ - --integration: suite completa.
+ - --all: unit + integración completa.
+
+ Opcional vía Makefile:
+
+ make test-unit
+ make test-integration-smoke
+ make test-integration-full
+ make test-release-gate
+
+ ———
+
+ ## 3) Pruebas funcionales CLI de features nuevas (rápidas)
+
+ Usa un target autorizado, por ejemplo TARGET=tu-dominio.com.
+
+ TARGET="tu-dominio.com"
+ ./reconftw.sh -d "$TARGET" -r --dry-run --export all --refresh-cache
+
+ Qué esperar:
+
+ - No ejecuta scan real (--dry-run), pero ves flujo y comandos.
+ - Debe aceptar flags nuevos sin errores.
+
+ ———
+
+ ## 4) Scan real corto para generar artefactos nuevos
+
+ TARGET="tu-dominio.com"
+ ./reconftw.sh -d "$TARGET" -p --export all
+
+ Qué esperar en Recon/$TARGET/:
+
+ - report/report.json
+ - report/index.html
+ - report/latest/report.json
+ - report/latest/index.html
+ - report/findings_normalized.jsonl
+ - report/export_all.jsonl
+ - report/*.csv
+ - .log/perf_summary.json
+
+ ———
+
+ ## 5) Validar --report-only
+
+ TARGET="tu-dominio.com"
+ ./reconftw.sh -d "$TARGET" --report-only --export all
+
+ Qué esperar:
+
+ - Rebuild de reportes sin lanzar recon.
+ - Mensaje de “report-only completed”.
+ - Se regeneran/actualizan archivos en report/.
+
+ ———
+
+ ## 6) Validar monitor continuo + deltas/alerts
+
+ TARGET="tu-dominio.com"
+ ./reconftw.sh -d "$TARGET" -r --monitor --monitor-interval 1 --monitor-cycles 2 --export all
+
+ Qué esperar:
+
+ - 2 ciclos y salida automática.
+ - En Recon/$TARGET/.incremental/history/latest/:
+ - delta.json
+ - alerts.json
+ - En report JSON:
+ - delta_since_last
+ - alerts_last
+
+ ———
+
+ ## 7) Validar perfiles/performance/cache
+
+ TARGET="tu-dominio.com"
+ ./reconftw.sh -d "$TARGET" -p -f config/reconftw_quick.cfg --export json
+ ./reconftw.sh -d "$TARGET" -p -f config/reconftw_full.cfg --export json
+ ./reconftw.sh -d "$TARGET" -p -f config/reconftw_stealth.cfg --export json
+
+ Qué esperar:
+
+ - Distinto comportamiento/velocidad según perfil.
+ - .log/perf_summary.json refleja perf_profile y duraciones.
+ - Con --refresh-cache, fuerza refresco de recursos cacheados.
+
+
+• Checklist corta y directa por artefacto:
+
+ 1. Recon/<target>/.log/perf_summary.json
+
+ - Campos: timestamp, domain, mode, perf_profile, total_duration_sec.
+ - counts con números >= 0.
+ - top_functions no vacío en scans reales.
+
+ 2. Recon/<target>/report/report.json
+
+ - Campos clave: summary, severities, links, top_assets.
+ - Si usaste monitor: delta_since_last y alerts_last presentes.
+ - summary.findings_total consistente con suma de severidades.
+
+ 3. Recon/<target>/report/index.html
+
+ - Abre bien en navegador.
+ - Debe mostrar KPIs, severidades, top assets y links.
+ - En modo monitor: bloque “Delta Since Last Run”.
+
+ 4. Recon/<target>/report/latest/report.json y Recon/<target>/report/latest/index.html
+
+ - Existen y se actualizan tras cada ejecución con reporte.
+ - Deben reflejar la última corrida.
+
+ 5. Recon/<target>/report/findings_normalized.jsonl
+
+ - Cada línea es JSON válido.
+ - Campos típicos: type, tool, severity, template_id, target.
+
+ 6. Recon/<target>/report/export_all.jsonl
+
+ - Contiene mezcla de assets.jsonl + findings normalizados.
+ - Archivo no vacío cuando hay datos.
+
+ 7. Recon/<target>/report/subdomains.csv
+
+ - Cabecera exacta: subdomain.
+ - Filas con subdominios sin columnas extra.
+
+ 8. Recon/<target>/report/webs.csv
+
+ - Cabecera: url,scheme,host.
+ - scheme y host coherentes con url.
+
+ 9. Recon/<target>/report/hosts.csv
+
+ - Cabecera: ip.
+ - IPs válidas (IPv4/IPv6 según tu scan).
+
+ 10. Recon/<target>/report/findings.csv
+
+ - Cabecera: tool,severity,template_id,name,target,host,finding_type,matcher_name.
+ - Al menos algunas filas si hubo findings de nuclei.
+
+ 11. Recon/<target>/.incremental/history/latest/delta.json (monitor/incremental)
+
+ - JSON válido.
+ - Contadores esperables: nuevos subdominios/webs/findings (>=0).
+
+ 12. Recon/<target>/.incremental/history/latest/alerts.json (monitor/incremental)
+
+ - JSON válido con resumen de alertas del ciclo.
+ - Si ALERT_SUPPRESSION=true, no debería repetir alertas idénticas en ciclos consecutivos.
+
+ 13. Recon/<target>/nuclei_output/*_json.txt
+
+ - Archivos por severidad (info, low, medium, high, critical).
+ - Líneas JSON válidas (una por finding).
+
+ 14. tests runner
+
+ - ./tests/run_tests.sh --unit|--smoke|--integration|--all deben terminar con “Tests passed for mode: ...”.
+ - Si falla uno, revisar primero output del test y luego rutas/artefactos esperados.
+
+ 15. release gate
+
+ - make test-release-gate:
+ - pasa sintaxis shell,
+ - corre unit + smoke,
+ - y si existe perf_summary.json, compara contra baseline sin regresión fuera del umbral.
+
+ Script batch:
+
+ - tests/check_artifacts_all.sh
+
+ Uso:
+
+ # Recorre todos los targets en Recon/
+ ./tests/check_artifacts_all.sh
+
+ # Directorio base custom
+ ./tests/check_artifacts_all.sh /ruta/a/Recon
+
+ # Checker custom (si lo mueves)
+ ./tests/check_artifacts_all.sh Recon ./tests/check_artifacts.sh
+
+ Salida:
+
+ - Te muestra validación por target.
+ - Al final resumen Passed/Failed.
+ - Devuelve exit code 1 si falla alguno (útil para CI).
\ No newline at end of file
diff --git a/tests/bench/baseline_metrics.json b/tests/bench/baseline_metrics.json
new file mode 100644
index 0000000..59f69f9
--- /dev/null
+++ b/tests/bench/baseline_metrics.json
@@ -0,0 +1,4 @@
+{
+ "total_duration_sec": 600,
+ "notes": "Synthetic baseline for CI gate; tune with real smoke baseline"
+}
diff --git a/tests/bench/compare_baseline.sh b/tests/bench/compare_baseline.sh
new file mode 100644
index 0000000..5aa7df3
--- /dev/null
+++ b/tests/bench/compare_baseline.sh
@@ -0,0 +1,37 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+BASELINE_FILE="${1:-tests/bench/baseline_metrics.json}"
+CURRENT_FILE="${2:-}"
+MAX_DEGRADATION_PCT="${MAX_DEGRADATION_PCT:-20}"
+
+if [[ -z "${CURRENT_FILE}" ]]; then
+ echo "Usage: $0 <baseline_json> <current_perf_summary_json>"
+ exit 2
+fi
+
+if [[ ! -f "$BASELINE_FILE" ]]; then
+ echo "[INFO] Baseline file not found ($BASELINE_FILE); skipping regression gate"
+ exit 0
+fi
+
+if [[ ! -f "$CURRENT_FILE" ]]; then
+ echo "[INFO] Current perf summary not found ($CURRENT_FILE); skipping regression gate"
+ exit 0
+fi
+
+base_total=$(jq -r '.total_duration_sec // 0' "$BASELINE_FILE" 2>/dev/null || echo 0)
+cur_total=$(jq -r '.total_duration_sec // 0' "$CURRENT_FILE" 2>/dev/null || echo 0)
+
+if [[ "$base_total" -le 0 || "$cur_total" -le 0 ]]; then
+ echo "[INFO] Non-positive timings in baseline/current; skipping regression gate"
+ exit 0
+fi
+
+allowed=$(( base_total + (base_total * MAX_DEGRADATION_PCT / 100) ))
+if [[ "$cur_total" -gt "$allowed" ]]; then
+ echo "[FAIL] Runtime regression: current=${cur_total}s baseline=${base_total}s allowed=${allowed}s"
+ exit 1
+fi
+
+echo "[OK] Runtime within threshold: current=${cur_total}s baseline=${base_total}s allowed=${allowed}s"
diff --git a/tests/check_artifacts.sh b/tests/check_artifacts.sh
new file mode 100644
index 0000000..9ad148c
--- /dev/null
+++ b/tests/check_artifacts.sh
@@ -0,0 +1,94 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+if [[ $# -lt 1 ]]; then
+ echo "Usage: $0 <target-domain>"
+ echo "Example: $0 example.com"
+ exit 2
+fi
+
+TARGET="$1"
+BASE="Recon/$TARGET"
+
+ok() { printf "[OK] %s\n" "$1"; }
+warn() { printf "[WARN] %s\n" "$1"; }
+fail() { printf "[FAIL] %s\n" "$1"; exit 1; }
+
+require_file() {
+ local f="$1"
+ [[ -f "$f" ]] || fail "Missing file: $f"
+ ok "Found file: $f"
+}
+
+check_json_file() {
+ local f="$1"
+ require_file "$f"
+ jq -e . "$f" >/dev/null 2>&1 || fail "Invalid JSON: $f"
+ ok "Valid JSON: $f"
+}
+
+check_jsonl_file() {
+ local f="$1"
+ require_file "$f"
+ if [[ ! -s "$f" ]]; then
+ warn "Empty JSONL: $f"
+ return 0
+ fi
+ local bad
+ bad=$(jq -c . "$f" >/dev/null 2>&1; echo $?)
+ [[ "$bad" -eq 0 ]] || fail "Invalid JSONL lines: $f"
+ ok "Valid JSONL: $f"
+}
+
+check_csv_header() {
+ local f="$1"
+ local h="$2"
+ require_file "$f"
+ local got
+ got="$(head -n1 "$f")"
+ [[ "$got" == "$h" ]] || fail "CSV header mismatch in $f (got: '$got', expected: '$h')"
+ ok "CSV header ok: $f"
+}
+
+[[ -d "$BASE" ]] || fail "Target directory not found: $BASE"
+ok "Target directory: $BASE"
+
+command -v jq >/dev/null 2>&1 || fail "jq is required"
+ok "jq available"
+
+check_json_file "$BASE/.log/perf_summary.json"
+check_json_file "$BASE/report/report.json"
+require_file "$BASE/report/index.html"
+ok "HTML report exists: $BASE/report/index.html"
+check_json_file "$BASE/report/latest/report.json"
+require_file "$BASE/report/latest/index.html"
+ok "Latest HTML report exists: $BASE/report/latest/index.html"
+
+check_jsonl_file "$BASE/report/findings_normalized.jsonl"
+check_jsonl_file "$BASE/report/export_all.jsonl"
+
+check_csv_header "$BASE/report/subdomains.csv" "subdomain"
+check_csv_header "$BASE/report/webs.csv" "url,scheme,host"
+check_csv_header "$BASE/report/hosts.csv" "ip"
+check_csv_header "$BASE/report/findings.csv" "tool,severity,template_id,name,target,host,finding_type,matcher_name"
+
+if [[ -f "$BASE/.incremental/history/latest/delta.json" ]]; then
+ check_json_file "$BASE/.incremental/history/latest/delta.json"
+else
+ warn "No monitor delta file (run monitor/incremental to generate): $BASE/.incremental/history/latest/delta.json"
+fi
+
+if [[ -f "$BASE/.incremental/history/latest/alerts.json" ]]; then
+ check_json_file "$BASE/.incremental/history/latest/alerts.json"
+else
+ warn "No monitor alerts file (run monitor/incremental to generate): $BASE/.incremental/history/latest/alerts.json"
+fi
+
+for sev in info low medium high critical; do
+ f="$BASE/nuclei_output/${sev}_json.txt"
+ if [[ -f "$f" ]]; then
+ check_jsonl_file "$f"
+ fi
+done
+
+ok "Artifact checks completed successfully for $TARGET"
diff --git a/tests/check_artifacts_all.sh b/tests/check_artifacts_all.sh
new file mode 100644
index 0000000..0e7a4d3
--- /dev/null
+++ b/tests/check_artifacts_all.sh
@@ -0,0 +1,53 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+BASE_DIR="${1:-Recon}"
+CHECKER="${2:-./tests/check_artifacts.sh}"
+
+if [[ ! -x "$CHECKER" ]]; then
+ echo "[FAIL] Checker not found or not executable: $CHECKER"
+ exit 2
+fi
+
+if [[ ! -d "$BASE_DIR" ]]; then
+ echo "[FAIL] Base directory not found: $BASE_DIR"
+ exit 2
+fi
+
+mapfile -t targets < <(find "$BASE_DIR" -mindepth 1 -maxdepth 1 -type d -exec basename {} \; | sort)
+
+if [[ ${#targets[@]} -eq 0 ]]; then
+ echo "[WARN] No targets found under: $BASE_DIR"
+ exit 0
+fi
+
+ok_count=0
+fail_count=0
+failed_targets=()
+
+for t in "${targets[@]}"; do
+ echo
+ echo "=== Checking target: $t ==="
+ if "$CHECKER" "$t"; then
+ ok_count=$((ok_count + 1))
+ else
+ fail_count=$((fail_count + 1))
+ failed_targets+=("$t")
+ fi
+done
+
+echo
+echo "=== Summary ==="
+echo "Total targets: ${#targets[@]}"
+echo "Passed: $ok_count"
+echo "Failed: $fail_count"
+
+if [[ $fail_count -gt 0 ]]; then
+ echo "Failed targets:"
+ for t in "${failed_targets[@]}"; do
+ echo "- $t"
+ done
+ exit 1
+fi
+
+echo "[OK] All targets passed artifact checks."
diff --git a/tests/fixtures/monitor_cycle1/nuclei_output/critical.txt b/tests/fixtures/monitor_cycle1/nuclei_output/critical.txt
new file mode 100644
index 0000000..e69de29
diff --git a/tests/fixtures/monitor_cycle1/nuclei_output/high.txt b/tests/fixtures/monitor_cycle1/nuclei_output/high.txt
new file mode 100644
index 0000000..015af59
--- /dev/null
+++ b/tests/fixtures/monitor_cycle1/nuclei_output/high.txt
@@ -0,0 +1 @@
+[tpl-high] [http] [high] https://a.example.com
diff --git a/tests/fixtures/monitor_cycle1/subdomains/subdomains.txt b/tests/fixtures/monitor_cycle1/subdomains/subdomains.txt
new file mode 100644
index 0000000..289be74
--- /dev/null
+++ b/tests/fixtures/monitor_cycle1/subdomains/subdomains.txt
@@ -0,0 +1,2 @@
+a.example.com
+b.example.com
diff --git a/tests/fixtures/monitor_cycle1/webs/webs_all.txt b/tests/fixtures/monitor_cycle1/webs/webs_all.txt
new file mode 100644
index 0000000..ff28331
--- /dev/null
+++ b/tests/fixtures/monitor_cycle1/webs/webs_all.txt
@@ -0,0 +1 @@
+https://a.example.com
diff --git a/tests/fixtures/monitor_cycle2/nuclei_output/critical.txt b/tests/fixtures/monitor_cycle2/nuclei_output/critical.txt
new file mode 100644
index 0000000..7eafacb
--- /dev/null
+++ b/tests/fixtures/monitor_cycle2/nuclei_output/critical.txt
@@ -0,0 +1 @@
+[tpl-crit] [http] [critical] https://c.example.com
diff --git a/tests/fixtures/monitor_cycle2/nuclei_output/high.txt b/tests/fixtures/monitor_cycle2/nuclei_output/high.txt
new file mode 100644
index 0000000..9ecdcf3
--- /dev/null
+++ b/tests/fixtures/monitor_cycle2/nuclei_output/high.txt
@@ -0,0 +1,2 @@
+[tpl-high] [http] [high] https://a.example.com
+[tpl-high2] [http] [high] https://c.example.com
diff --git a/tests/fixtures/monitor_cycle2/subdomains/subdomains.txt b/tests/fixtures/monitor_cycle2/subdomains/subdomains.txt
new file mode 100644
index 0000000..88eebce
--- /dev/null
+++ b/tests/fixtures/monitor_cycle2/subdomains/subdomains.txt
@@ -0,0 +1,3 @@
+a.example.com
+b.example.com
+c.example.com
diff --git a/tests/fixtures/monitor_cycle2/webs/webs_all.txt b/tests/fixtures/monitor_cycle2/webs/webs_all.txt
new file mode 100644
index 0000000..96987ec
--- /dev/null
+++ b/tests/fixtures/monitor_cycle2/webs/webs_all.txt
@@ -0,0 +1,2 @@
+https://a.example.com
+https://c.example.com
diff --git a/tests/helpers/common.bash b/tests/helpers/common.bash
new file mode 100644
index 0000000..229b516
--- /dev/null
+++ b/tests/helpers/common.bash
@@ -0,0 +1,14 @@
+#!/usr/bin/env bash
+set -eo pipefail
+
+setup_recon_env() {
+ local project_root
+ project_root="$(cd "$(dirname "$BATS_TEST_FILENAME")/../.." && pwd)"
+ export SCRIPTPATH="$project_root"
+ export tools="${tools:-$HOME/Tools}"
+ export LOGFILE="${LOGFILE:-/dev/null}"
+ export bred='' bblue='' bgreen='' byellow='' yellow='' reset=''
+ export NOTIFICATION=false
+ export AXIOM=false
+ source "$project_root/reconftw.sh" --source-only
+}
diff --git a/tests/integration/test_checkpoint.bats b/tests/integration/test_checkpoint.bats
index d777762..7e2a8e8 100644
--- a/tests/integration/test_checkpoint.bats
+++ b/tests/integration/test_checkpoint.bats
@@ -145,7 +145,7 @@ source_reconftw() {
touch "$called_fn_dir/.webprobe_simple"
# Clear all
- rm -f "$called_fn_dir"/.*
+ rm -f "$called_fn_dir"/.??*
local count
count=$(find "$called_fn_dir" -name ".*" -type f 2>/dev/null | wc -l)
diff --git a/tests/integration/test_export_cli.bats b/tests/integration/test_export_cli.bats
new file mode 100644
index 0000000..c4763fd
--- /dev/null
+++ b/tests/integration/test_export_cli.bats
@@ -0,0 +1,30 @@
+#!/usr/bin/env bats
+
+setup() {
+ local project_root
+ project_root="$(cd "$(dirname "$BATS_TEST_FILENAME")/../.." && pwd)"
+ export SCRIPTPATH="$project_root"
+ export TEST_DOMAIN="exportcli.example.com"
+ export TARGET_DIR="$SCRIPTPATH/Recon/$TEST_DOMAIN"
+ mkdir -p "$TARGET_DIR"/{subdomains,webs,hosts,nuclei_output,report,.log}
+ echo "a.$TEST_DOMAIN" > "$TARGET_DIR/subdomains/subdomains.txt"
+ echo "https://a.$TEST_DOMAIN" > "$TARGET_DIR/webs/webs_all.txt"
+ echo "1.1.1.1" > "$TARGET_DIR/hosts/ips.txt"
+ echo '{"template-id":"tpl-h","matcher-name":"m1","type":"http","info":{"severity":"high","name":"h"},"matched-at":"https://a.'"$TEST_DOMAIN"'"}' > "$TARGET_DIR/nuclei_output/high_json.txt"
+}
+
+after_each() {
+ rm -rf "$TARGET_DIR"
+}
+
+@test "export cli json creates jsonl artifacts" {
+ run timeout 30 bash "$SCRIPTPATH/reconftw.sh" -d "$TEST_DOMAIN" --report-only --export json
+ [ "$status" -eq 0 ]
+ [ -f "$TARGET_DIR/report/findings_normalized.jsonl" ]
+}
+
+@test "export cli csv creates csv artifacts" {
+ run timeout 30 bash "$SCRIPTPATH/reconftw.sh" -d "$TEST_DOMAIN" --report-only --export csv
+ [ "$status" -eq 0 ]
+ [ -f "$TARGET_DIR/report/findings.csv" ]
+}
diff --git a/tests/integration/test_monitor_mode.bats b/tests/integration/test_monitor_mode.bats
new file mode 100644
index 0000000..57a1f07
--- /dev/null
+++ b/tests/integration/test_monitor_mode.bats
@@ -0,0 +1,41 @@
+#!/usr/bin/env bats
+
+setup() {
+ local project_root
+ project_root="$(cd "$(dirname "$BATS_TEST_FILENAME")/../.." && pwd)"
+ export SCRIPTPATH="$project_root"
+ export TEST_DIR="$BATS_TEST_TMPDIR/monitor_int"
+ export domain="example.com"
+ export dir="$TEST_DIR/$domain"
+ mkdir -p "$dir"/{subdomains,webs,nuclei_output,report,.incremental/history,.log}
+ cd "$dir"
+
+ # shellcheck source=/dev/null
+ source "$SCRIPTPATH/reconftw.sh" --source-only
+ export MONITOR_MODE=true
+ export ALERT_SUPPRESSION=true
+}
+
+teardown() {
+ cd /
+ rm -rf "$TEST_DIR"
+}
+
+@test "monitor_snapshot creates history and delta artifacts" {
+ cp "$SCRIPTPATH/tests/fixtures/monitor_cycle1/subdomains/subdomains.txt" subdomains/subdomains.txt
+ cp "$SCRIPTPATH/tests/fixtures/monitor_cycle1/webs/webs_all.txt" webs/webs_all.txt
+ cp "$SCRIPTPATH/tests/fixtures/monitor_cycle1/nuclei_output/high.txt" nuclei_output/high.txt
+ : > nuclei_output/critical.txt
+ MONITOR_CYCLE=1 monitor_snapshot
+
+ cp "$SCRIPTPATH/tests/fixtures/monitor_cycle2/subdomains/subdomains.txt" subdomains/subdomains.txt
+ cp "$SCRIPTPATH/tests/fixtures/monitor_cycle2/webs/webs_all.txt" webs/webs_all.txt
+ cp "$SCRIPTPATH/tests/fixtures/monitor_cycle2/nuclei_output/high.txt" nuclei_output/high.txt
+ cp "$SCRIPTPATH/tests/fixtures/monitor_cycle2/nuclei_output/critical.txt" nuclei_output/critical.txt
+ MONITOR_CYCLE=2 run monitor_snapshot
+ [ "$status" -eq 0 ]
+
+ latest_dir=".incremental/history/$(readlink .incremental/history/latest)"
+ [ -f "$latest_dir/delta.json" ]
+ [ -f "$latest_dir/alerts.json" ]
+}
diff --git a/tests/integration/test_report_only.bats b/tests/integration/test_report_only.bats
new file mode 100644
index 0000000..f1f0019
--- /dev/null
+++ b/tests/integration/test_report_only.bats
@@ -0,0 +1,27 @@
+#!/usr/bin/env bats
+
+setup() {
+ local project_root
+ project_root="$(cd "$(dirname "$BATS_TEST_FILENAME")/../.." && pwd)"
+ export SCRIPTPATH="$project_root"
+ export TEST_DOMAIN="reportonly.example.com"
+ export TARGET_DIR="$SCRIPTPATH/Recon/$TEST_DOMAIN"
+ mkdir -p "$TARGET_DIR"/{subdomains,webs,hosts,nuclei_output,report,.log}
+ echo "a.$TEST_DOMAIN" > "$TARGET_DIR/subdomains/subdomains.txt"
+ echo "https://a.$TEST_DOMAIN" > "$TARGET_DIR/webs/webs_all.txt"
+ echo "1.1.1.1" > "$TARGET_DIR/hosts/ips.txt"
+ echo '{"template-id":"tpl-c","info":{"severity":"critical"},"matched-at":"https://a.'"$TEST_DOMAIN"'"}' > "$TARGET_DIR/nuclei_output/critical_json.txt"
+ echo "[tpl-c] [http] [critical] https://a.$TEST_DOMAIN" > "$TARGET_DIR/nuclei_output/critical.txt"
+}
+
+after_each() {
+ rm -rf "$TARGET_DIR"
+}
+
+@test "report-only rebuilds report artifacts" {
+ run timeout 30 bash "$SCRIPTPATH/reconftw.sh" -d "$TEST_DOMAIN" --report-only --export all
+ [ "$status" -eq 0 ]
+ [ -f "$TARGET_DIR/report/report.json" ]
+ [ -f "$TARGET_DIR/report/index.html" ]
+ [ -f "$TARGET_DIR/report/findings.csv" ]
+}
diff --git a/tests/mocks/sleep b/tests/mocks/sleep
new file mode 100644
index 0000000..748224c
--- /dev/null
+++ b/tests/mocks/sleep
@@ -0,0 +1,3 @@
+#!/usr/bin/env bash
+# test mock to avoid long sleeps in monitor tests
+exit 0
diff --git a/tests/run_tests.sh b/tests/run_tests.sh
index 212bb31..4016ea4 100644
--- a/tests/run_tests.sh
+++ b/tests/run_tests.sh
@@ -1,11 +1,22 @@
-#!/bin/bash
-# Run all reconFTW tests
+#!/usr/bin/env bash
+# Run reconFTW tests by scope.
# Requires: bats-core (https://github.com/bats-core/bats-core)
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
BATS="${BATS:-bats}"
+MODE="${1:---unit}"
+
+usage() {
+ cat <<EOF
+Usage: $0 [--unit|--smoke|--integration|--all]
+ --unit Run only unit tests
+ --smoke Run integration smoke subset
+ --integration Run full integration suite
+ --all Run unit + full integration suites
+EOF
+}
if ! command -v "$BATS" >/dev/null 2>&1; then
echo "bats-core not found. Install: https://github.com/bats-core/bats-core"
@@ -14,12 +25,60 @@ if ! command -v "$BATS" >/dev/null 2>&1; then
exit 1
fi
-echo "Running unit tests..."
-"$BATS" "$SCRIPT_DIR"/unit/*.bats
+if [[ -z "${BATS_SHELL:-}" ]]; then
+ for candidate in /opt/homebrew/bin/bash /usr/local/bin/bash /bin/bash; do
+ if [[ -x "$candidate" ]]; then
+ major="$("$candidate" -lc 'echo "${BASH_VERSINFO[0]}"' 2>/dev/null || echo 0)"
+ if [[ "$major" =~ ^[0-9]+$ ]] && [[ "$major" -ge 4 ]]; then
+ export BATS_SHELL="$candidate"
+ break
+ fi
+ fi
+ done
+fi
+
+run_unit() {
+ echo "Running unit tests..."
+ "$BATS" "$SCRIPT_DIR"/unit/*.bats
+}
-if [[ "${1:-}" == "--all" ]]; then
- echo "Running integration tests..."
+run_smoke() {
+ echo "Running integration smoke tests..."
+ "$BATS" \
+ "$SCRIPT_DIR"/integration/test_smoke.bats \
+ "$SCRIPT_DIR"/integration/test_report_only.bats \
+ "$SCRIPT_DIR"/integration/test_export_cli.bats \
+ "$SCRIPT_DIR"/integration/test_monitor_mode.bats
+}
+
+run_integration() {
+ echo "Running full integration tests..."
"$BATS" "$SCRIPT_DIR"/integration/*.bats
-fi
+}
+
+case "$MODE" in
+ --unit)
+ run_unit
+ ;;
+ --smoke)
+ run_smoke
+ ;;
+ --integration)
+ run_integration
+ ;;
+ --all)
+ run_unit
+ run_integration
+ ;;
+ -h|--help)
+ usage
+ exit 0
+ ;;
+ *)
+ echo "Unknown option: $MODE"
+ usage
+ exit 2
+ ;;
+esac
-echo "All tests passed."
+echo "Tests passed for mode: $MODE"
diff --git a/tests/unit/test_exports.bats b/tests/unit/test_exports.bats
new file mode 100644
index 0000000..97323db
--- /dev/null
+++ b/tests/unit/test_exports.bats
@@ -0,0 +1,52 @@
+#!/usr/bin/env bats
+
+setup() {
+ source "$(cd "$(dirname "$BATS_TEST_FILENAME")" && pwd)/../helpers/common.bash"
+ setup_recon_env
+
+ export TEST_DIR="$(mktemp -d)"
+ export domain="example.com"
+ export dir="$TEST_DIR/$domain"
+ mkdir -p "$dir"/{subdomains,webs,hosts,nuclei_output,report,.log}
+ cd "$dir"
+
+ echo "a.example.com" > subdomains/subdomains.txt
+ echo "https://a.example.com" > webs/webs_all.txt
+ echo "1.1.1.1" > hosts/ips.txt
+ echo '{"template-id":"tpl-h","matcher-name":"m1","type":"http","info":{"severity":"high","name":"High finding","tags":["x"]},"matched-at":"https://a.example.com","host":"a.example.com"}' > nuclei_output/high_json.txt
+ echo '{"type":"finding","value":"test","ts":"2026-01-01","source":"unit"}' > assets.jsonl
+ runtime="1 minutes 0 seconds"
+}
+
+teardown() {
+ cd /
+ rm -rf "$TEST_DIR"
+}
+
+@test "export_findings_jsonl creates normalized and merged jsonl" {
+ run export_findings_jsonl
+ [ "$status" -eq 0 ]
+ [ -f report/findings_normalized.jsonl ]
+ [ -f report/export_all.jsonl ]
+ grep -q '"tool":"nuclei"' report/findings_normalized.jsonl
+}
+
+@test "export_csv_artifacts writes expected csv files" {
+ run export_csv_artifacts
+ [ "$status" -eq 0 ]
+ [ -f report/subdomains.csv ]
+ [ -f report/webs.csv ]
+ [ -f report/hosts.csv ]
+ [ -f report/findings.csv ]
+ head -n1 report/findings.csv | grep -q "tool,severity"
+}
+
+@test "export_reports honors EXPORT_FORMAT=all" {
+ export EXPORT_FORMAT="all"
+ run export_reports
+ [ "$status" -eq 0 ]
+ [ -f report/index.html ]
+ [ -f report/report.json ]
+ [ -f report/findings.csv ]
+ [ -f report/export_all.jsonl ]
+}
diff --git a/tests/unit/test_monitor.bats b/tests/unit/test_monitor.bats
new file mode 100644
index 0000000..43fa164
--- /dev/null
+++ b/tests/unit/test_monitor.bats
@@ -0,0 +1,66 @@
+#!/usr/bin/env bats
+
+setup() {
+ source "$(cd "$(dirname "$BATS_TEST_FILENAME")" && pwd)/../helpers/common.bash"
+ setup_recon_env
+
+ export TEST_DIR="$(mktemp -d)"
+ export domain="example.com"
+ export dir="$TEST_DIR/$domain"
+ export MONITOR_MODE=true
+ export ALERT_SUPPRESSION=true
+ export ALERT_SEEN_FILE="$dir/.incremental/alerts_seen.hashes"
+ mkdir -p "$dir"/{subdomains,webs,nuclei_output,.incremental/history,report,.log}
+ cd "$dir"
+ runtime="1 minutes 0 seconds"
+}
+
+teardown() {
+ cd /
+ rm -rf "$TEST_DIR"
+}
+
+@test "monitor_snapshot creates baseline and latest pointer" {
+ cp "$SCRIPTPATH/tests/fixtures/monitor_cycle1/subdomains/subdomains.txt" subdomains/subdomains.txt
+ cp "$SCRIPTPATH/tests/fixtures/monitor_cycle1/webs/webs_all.txt" webs/webs_all.txt
+ cp "$SCRIPTPATH/tests/fixtures/monitor_cycle1/nuclei_output/high.txt" nuclei_output/high.txt
+ : > nuclei_output/critical.txt
+
+ export MONITOR_CYCLE=1
+ run monitor_snapshot
+ [ "$status" -eq 0 ]
+ [ -L .incremental/history/latest ] || [ -d .incremental/history/latest ]
+
+ latest_dir=".incremental/history/$(readlink .incremental/history/latest)"
+ [ -f "$latest_dir/delta.json" ]
+}
+
+@test "monitor_snapshot detects deltas between cycles" {
+ cp "$SCRIPTPATH/tests/fixtures/monitor_cycle1/subdomains/subdomains.txt" subdomains/subdomains.txt
+ cp "$SCRIPTPATH/tests/fixtures/monitor_cycle1/webs/webs_all.txt" webs/webs_all.txt
+ cp "$SCRIPTPATH/tests/fixtures/monitor_cycle1/nuclei_output/high.txt" nuclei_output/high.txt
+ : > nuclei_output/critical.txt
+ export MONITOR_CYCLE=1
+ monitor_snapshot
+
+ cp "$SCRIPTPATH/tests/fixtures/monitor_cycle2/subdomains/subdomains.txt" subdomains/subdomains.txt
+ cp "$SCRIPTPATH/tests/fixtures/monitor_cycle2/webs/webs_all.txt" webs/webs_all.txt
+ cp "$SCRIPTPATH/tests/fixtures/monitor_cycle2/nuclei_output/high.txt" nuclei_output/high.txt
+ cp "$SCRIPTPATH/tests/fixtures/monitor_cycle2/nuclei_output/critical.txt" nuclei_output/critical.txt
+ export MONITOR_CYCLE=2
+ run monitor_snapshot
+ [ "$status" -eq 0 ]
+
+ latest_dir=".incremental/history/$(readlink .incremental/history/latest)"
+ [ -f "$latest_dir/subdomains_new.txt" ]
+ [ -f "$latest_dir/webs_new.txt" ]
+ grep -q "c.example.com" "$latest_dir/subdomains_new.txt"
+}
+
+@test "alert fingerprint suppression deduplicates repeated alerts" {
+ export ALERT_SEEN_FILE="$dir/.incremental/alerts_seen.hashes"
+ run _monitor_mark_alert_seen "critical" "https://a.example.com"
+ [ "$status" -eq 0 ]
+ run _monitor_mark_alert_seen "critical" "https://a.example.com"
+ [ "$status" -eq 1 ]
+}
diff --git a/tests/unit/test_perf_profile.bats b/tests/unit/test_perf_profile.bats
new file mode 100644
index 0000000..3b56a49
--- /dev/null
+++ b/tests/unit/test_perf_profile.bats
@@ -0,0 +1,27 @@
+#!/usr/bin/env bats
+
+setup() {
+ source "$(cd "$(dirname "$BATS_TEST_FILENAME")" && pwd)/../helpers/common.bash"
+ setup_recon_env
+}
+
+@test "apply_performance_profile sets numeric values for low profile" {
+ export PERF_PROFILE="low"
+ unset PARALLEL_MAX_JOBS
+ run apply_performance_profile
+ [ "$status" -eq 0 ]
+ [[ "$PARALLEL_MAX_JOBS" =~ ^[0-9]+$ ]]
+ [[ "$FFUF_THREADS" =~ ^[0-9]+$ ]]
+ [ "$PARALLEL_MAX_JOBS" -ge 1 ]
+}
+
+@test "apply_performance_profile max profile is not lower than low profile ffuf" {
+ export PERF_PROFILE="low"
+ apply_performance_profile >/dev/null
+ low_ffuf="$FFUF_THREADS"
+
+ export PERF_PROFILE="max"
+ run apply_performance_profile
+ [ "$status" -eq 0 ]
+ [ "$FFUF_THREADS" -ge "$low_ffuf" ]
+}
diff --git a/tests/unit/test_reporting.bats b/tests/unit/test_reporting.bats
new file mode 100644
index 0000000..bce3e06
--- /dev/null
+++ b/tests/unit/test_reporting.bats
@@ -0,0 +1,51 @@
+#!/usr/bin/env bats
+
+setup() {
+ source "$(cd "$(dirname "$BATS_TEST_FILENAME")" && pwd)/../helpers/common.bash"
+ setup_recon_env
+
+ export TEST_DIR="$(mktemp -d)"
+ export domain="example.com"
+ export dir="$TEST_DIR/$domain"
+ mkdir -p "$dir"/{subdomains,webs,hosts,nuclei_output,screenshots,report,.log,.incremental/history}
+ cd "$dir"
+
+ echo "a.example.com" > subdomains/subdomains.txt
+ echo "https://a.example.com" > webs/webs_all.txt
+ echo "1.1.1.1" > hosts/ips.txt
+ echo "[tpl-c] [http] [critical] https://a.example.com" > nuclei_output/critical.txt
+ echo '{"template-id":"tpl-c","info":{"severity":"critical"},"matched-at":"https://a.example.com"}' > nuclei_output/critical_json.txt
+ echo "20 a.example.com" > hotlist.txt
+ runtime="5 minutes 0 seconds"
+}
+
+teardown() {
+ cd /
+ rm -rf "$TEST_DIR"
+}
+
+@test "generate_consolidated_report creates json and html" {
+ run generate_consolidated_report
+ [ "$status" -eq 0 ]
+ [ -f report/report.json ]
+ [ -f report/index.html ]
+ [ -f report/latest/report.json ]
+ [ -f report/latest/index.html ]
+ grep -q '"domain":"example.com"' report/report.json
+}
+
+@test "report includes delta_since_last when monitor data exists" {
+ mkdir -p .incremental/history/prev
+ cat > .incremental/history/prev/delta.json <<JSON
+{"deltas":{"subdomains_new":1,"webs_new":1,"high_findings_new":0,"critical_findings_new":1}}
+JSON
+ cat > .incremental/history/prev/alerts.json <<JSON
+{"alerts":{"critical_new":1,"high_new":0,"subdomains_new":1,"webs_new":1}}
+JSON
+ ln -s prev .incremental/history/latest
+
+ run generate_consolidated_report
+ [ "$status" -eq 0 ]
+ grep -q '"delta_since_last"' report/report.json
+ grep -q '"alerts_last"' report/report.json
+}