repositories

NixDaemon

NixOS pentest workstation as one flake — IceBreaker's successor

clonegit clone https://git.daemon-sec.xyz/NixDaemon.git
dmnfuzz.shShell565 lines23.3 KiBraw download
# dmnfuzz — ffuf/dnsx wrapper with automatic vhost-baseline calibration.
# Also installed as `dnsfuzz` (helpers.nix).
#
#   dmnfuzz vhost [-t <ip|host>] [-d <domain>] [opts]   virtual hosts (Host: header)
#   dmnfuzz dns   [-t <ns-ip>]   [-d <domain>] [opts]   AXFR, then subdomain brute
#   dmnfuzz dir   [-u <url> | -t <ip>] [opts]           directory / file brute
#   dmnfuzz auto  [-t <ip>]      [-d <domain>] [opts]   vhost, then dir the apex + each hit
#
# Defaults come from the active htbbox: -t is $TARGET; -d is the box's domain,
# else its first hostname, else the shortest /etc/hosts name for $TARGET. So on
# an active box `dmnfuzz auto` alone is enough. Results land in
# $BOXDIR/recon/dmnfuzz-*.txt unless -o says otherwise.
#
# vhost: before the scan it fires a few random, guaranteed-nonexistent Host
# headers, learns the default-vhost response signature (size/words/lines) and
# filters exactly that — so you only see genuinely distinct vhosts instead of
# a flood of 200/Size:900 noise. Falls back through -fw/-fl to ffuf's -ac when
# the default response varies. If the probes get no HTTP answer at all it
# stops there: wrong port/scheme or a dead VPN, not "no vhosts".
#
# dir: fingerprints the base first (Server / X-Powered-By). IIS is
# case-insensitive, so it switches to the -lowercase wordlist and drops IIS's
# device-name noise (con, aux, nul …  -> aspxerrorpath). If the base redirects
# to a path on the same host (dev.pov.htb/ -> /portfolio/), that path is
# scanned too. -X (on in auto) adds the stack's extensions (aspx,asp / php /
# jsp) when no -x is given.
#
# dns: asks the box's own nameserver (-t, -p default 53): first a zone transfer
# (dig AXFR), then a dnsx brute of the wordlist with wildcard filtering.
#
# Common opts:
#   -w FILE   wordlist (default per mode, from $seclists / $WORDLISTS/seclists)
#   -p PORT   port (default 80, 443 with --https; dns mode: 53)
#   --https   TLS        -k   ignore cert errors
#   -x EXT    dir: comma list (php,txt,html)   -X  dir: extensions from the fingerprint
#   -r        dir: recurse (depth 2)
#   -T N      threads (default 50)        -o FILE  save the clean result list
#   --add-hosts  record names: `htbbox host` on the active box, else /etc/hosts (sudo)
#   -H 'H: v'    extra header (repeatable)             -s   quieter banner
#   -- ARGS      everything after -- goes to ffuf (or dnsx) untouched
#
# ffuf, jq, curl, dig and dnsx are runtime inputs from helpers.nix. htbbox and
# sudo are used from the system PATH (a store copy of htbbox would read another
# $STATE; sudo must be the setuid wrapper).

# writeShellApplication supplies the shebang and shell options (see helpers.nix
# — dmnfuzz runs with nounset+pipefail, NOT errexit, because the control flow
# relies on non-zero returns).

C_H=; C_OK=; C_WARN=; C_ERR=; C_DIM=; C_B=; C_R=
if [[ -t 1 ]]; then
  C_H=$'\e[38;5;183m'; C_OK=$'\e[38;5;115m'; C_WARN=$'\e[38;5;215m'
  C_ERR=$'\e[38;5;210m'; C_DIM=$'\e[38;5;245m'; C_B=$'\e[1m'; C_R=$'\e[0m'
fi
say()  { printf '%s[*]%s %s\n' "$C_H" "$C_R" "$*"; }
ok()   { printf '%s[+]%s %s\n' "$C_OK" "$C_R" "$*"; }
warn() { printf '%s[!]%s %s\n' "$C_WARN" "$C_R" "$*" >&2; }
die()  { printf '%s[x]%s %s\n' "$C_ERR" "$C_R" "$*" >&2; exit 1; }

usage() {
  cat <<'EOF'
dmnfuzz — ffuf/dnsx wrapper with automatic vhost-baseline calibration

  dmnfuzz vhost [-t <ip|host>] [-d <domain>] [opts]   virtual hosts (Host: header)
  dmnfuzz dns   [-t <ns-ip>]   [-d <domain>] [opts]   AXFR, then subdomain brute
  dmnfuzz dir   [-u <url> | -t <ip>] [opts]           directory / file brute
  dmnfuzz auto  [-t <ip>]      [-d <domain>] [opts]   vhost, then dir the apex + each hit

  -t defaults to $TARGET, -d to the box's domain / hostnames / /etc/hosts.
  Results go to $BOXDIR/recon/dmnfuzz-*.txt on an active box.

opts: -w FILE  -p PORT  --https  -k  -x php,txt  -X  -r  -T N  -o FILE
      --add-hosts  -H 'Name: val' (repeatable)  -s  -- <raw ffuf/dnsx args>
EOF
  exit "${1:-0}"
}

# ---------- wordlists ----------
# pentest-wordlists puts SecLists at $WORDLISTS/seclists and paths.nix exports
# it as $seclists; /usr/share/seclists is for running this outside NixDaemon.
SECLISTS_DIRS=()
[[ -n "${seclists:-}" ]] && SECLISTS_DIRS+=("$seclists")
[[ -n "${WORDLISTS:-}" ]] && SECLISTS_DIRS+=("$WORDLISTS/seclists" "$WORDLISTS")
SECLISTS_DIRS+=("$HOME/pentesting/wordlists/seclists" /usr/share/seclists)
pick_wordlist() {
  local d rel
  for rel in "$@"; do
    for d in "${SECLISTS_DIRS[@]}"; do
      [[ -f "$d/$rel" ]] && { printf '%s\n' "$d/$rel"; return 0; }
    done
  done
  return 0
}
dns_wordlist() { pick_wordlist Discovery/DNS/subdomains-top1million-5000.txt; }
dir_wordlist() {
  if [[ "$1" == iis ]]; then
    pick_wordlist Discovery/Web-Content/raft-medium-directories-lowercase.txt \
      Discovery/Web-Content/DirBuster-2007_directory-list-lowercase-2.3-medium.txt
  fi
  pick_wordlist Discovery/Web-Content/raft-medium-directories.txt \
    Discovery/Web-Content/DirBuster-2007_directory-list-2.3-medium.txt \
    Discovery/Web-Content/directory-list-2.3-medium.txt
}

# ---------- options ----------
MODE=""; DOMAIN=""; URL=""; PORT=""; WL_USER=""; EXT=""
TARGET="${TARGET:-}"   # htbbox exports the current box's IP as $TARGET
HTTPS=0; INSECURE=0; RECURSE=0; AUTOEXT=0; THREADS=50; OUTFILE=""; ADDHOSTS=0; QUIET=0
EXTRA_HEADERS=(); PASSTHRU=()
VHOSTS_FOUND=""
TMP="$(mktemp -d "${TMPDIR:-/tmp}/dmnfuzz.XXXXXX")"; trap 'rm -rf "$TMP"' EXIT

[[ $# -lt 1 ]] && usage 1
MODE="$1"; shift
case "$MODE" in
  vhost|dns|dir|auto) ;;
  -h|--help|help) usage 0 ;;
  *) die "unknown mode '$MODE' (vhost|dns|dir|auto)" ;;
esac
[[ "$MODE" == auto ]] && AUTOEXT=1

need() { [[ $# -ge 2 && -n "$2" ]] || die "option $1 needs a value"; }
while [[ $# -gt 0 ]]; do
  case "$1" in
    -t) need "$@"; TARGET="$2"; shift 2 ;;
    -d) need "$@"; DOMAIN="$2"; shift 2 ;;
    -u) need "$@"; URL="$2";    shift 2 ;;
    -p) need "$@"; PORT="$2";   shift 2 ;;
    -w) need "$@"; WL_USER="$2"; shift 2 ;;
    -x) need "$@"; EXT="$2";    shift 2 ;;
    -T) need "$@"; THREADS="$2"; shift 2 ;;
    -o) need "$@"; OUTFILE="$2"; shift 2 ;;
    -H) need "$@"; EXTRA_HEADERS+=("$2"); shift 2 ;;
    -X) AUTOEXT=1; shift ;;
    -r) RECURSE=1; shift ;;
    -k) INSECURE=1; shift ;;
    --https) HTTPS=1; shift ;;
    --add-hosts) ADDHOSTS=1; shift ;;
    -s) QUIET=1; shift ;;
    -h|--help) usage 0 ;;
    --) shift; PASSTHRU=("$@"); break ;;
    *) die "unknown option '$1' (raw ffuf flags go after --)" ;;
  esac
done
[[ -n "$WL_USER" && ! -f "$WL_USER" ]] && die "wordlist not found: $WL_USER"
[[ "$THREADS" =~ ^[0-9]+$ ]] || die "bad thread count '$THREADS'"

# A pasted URL as -t: keep only the host.
TARGET="${TARGET#*://}"; TARGET="${TARGET%%/*}"

# ---------- the active box ----------
# Only trusted when -t is the box's own IP, so a manual -t elsewhere never
# writes into the wrong box.
BOX_ON=0
if command -v htbbox >/dev/null 2>&1 && [[ -n "$TARGET" ]] \
   && [[ "$(htbbox json ip 2>/dev/null)" == "$TARGET" ]]; then
  BOX_ON=1
fi
box_json() { [[ $BOX_ON -eq 1 ]] && htbbox json "$1" 2>/dev/null; }

# The shortest name /etc/hosts maps to $TARGET: the apex (pov.htb), not dev.pov.htb.
hosts_apex() {
  awk -v ip="$1" '!/^[[:space:]]*#/ && $1 == ip {for (i=2; i<=NF; i++) if ($i ~ /\./) print $i}' \
    /etc/hosts 2>/dev/null | awk '{print length, $0}' | sort -n | head -1 | cut -d' ' -f2-
}
DOMAIN_FROM=""
if [[ -z "$DOMAIN" && "$MODE" != dir ]]; then
  DOMAIN="$(box_json domain)"; DOMAIN_FROM="box domain"
  if [[ -z "$DOMAIN" ]]; then
    DOMAIN="$(box_json hostnames | jq -r 'sort_by(length) | .[0] // empty' 2>/dev/null)"; DOMAIN_FROM="box hostnames"
  fi
  if [[ -z "$DOMAIN" && -n "$TARGET" ]]; then
    if [[ "$TARGET" =~ ^[0-9.]+$ ]]; then
      DOMAIN="$(hosts_apex "$TARGET")"; DOMAIN_FROM="/etc/hosts"
    else
      DOMAIN="$TARGET"; DOMAIN_FROM="-t"
    fi
  fi
fi

SCHEME="http"; [[ $HTTPS -eq 1 ]] && SCHEME="https"
if [[ -z "$PORT" ]]; then
  if [[ "$MODE" == dns ]]; then PORT=53; elif [[ $HTTPS -eq 1 ]]; then PORT=443; else PORT=80; fi
fi
[[ "$PORT" =~ ^[0-9]+$ ]] || die "bad port '$PORT'"

# Default save location: the box's recon dir.
RECON=""
if [[ -z "$OUTFILE" && $BOX_ON -eq 1 && -n "${BOXDIR:-}" && -d "$BOXDIR" ]]; then
  RECON="$BOXDIR/recon"; mkdir -p "$RECON" 2>/dev/null || RECON=""
fi
outfile_for() {   # $1 = what (vhosts, dns, dir-<host>)
  if [[ -n "$OUTFILE" ]]; then printf '%s\n' "$OUTFILE"
  elif [[ -n "$RECON" ]]; then printf '%s/dmnfuzz-%s.txt\n' "$RECON" "$1"
  fi
}

FFUF_COMMON=(-t "$THREADS" -timeout 10 -of json -noninteractive)
CURL_COMMON=(-s -m 10 -o /dev/null -D -)
[[ $INSECURE -eq 1 ]] && { FFUF_COMMON+=(-k); CURL_COMMON+=(-k); }
if [[ ${#EXTRA_HEADERS[@]} -gt 0 ]]; then
  for h in "${EXTRA_HEADERS[@]}"; do FFUF_COMMON+=(-H "$h"); CURL_COMMON+=(-H "$h"); done
fi

banner() {
  [[ $QUIET -eq 1 ]] && return 0
  printf '%s%s┌─ dmnfuzz · %s ─────────────────────────%s\n' "$C_B" "$C_H" "$MODE" "$C_R"
}

hostport() {
  local h="$1"
  if { [[ $HTTPS -eq 0 && "$PORT" == 80 ]] || [[ $HTTPS -eq 1 && "$PORT" == 443 ]]; }; then
    printf '%s\n' "$h"
  else
    printf '%s:%s\n' "$h" "$PORT"
  fi
}

need_target() { [[ -n "$TARGET" ]] || die "$MODE mode needs -t <ip>  (or an active box: htbbox use <box>)"; }
need_domain() {
  [[ -n "$DOMAIN" ]] || die "$MODE mode needs -d <domain>  (e.g. pov.htb; or htbbox host pov.htb once)"
  [[ -n "$DOMAIN_FROM" ]] && say "domain   $DOMAIN  (from $DOMAIN_FROM)"
  DOMAIN_FROM=""
}
use_wordlist() {  # $1 = mode default; sets WL
  WL="${WL_USER:-$1}"
  [[ -n "$WL" && -f "$WL" ]] || die "wordlist not found: ${WL:-<none; looked in ${SECLISTS_DIRS[*]}; use -w>}"
}

# ---------- names ----------
# The clean list of names in $1 (one per line): print, save, record.
report_names() {
  local hosts="$1" what="$2" f
  f="$(outfile_for "$what")"
  [[ -n "$f" ]] && { printf '%s\n' "$hosts" > "$f"; ok "list saved -> $f"; }
  if [[ $ADDHOSTS -eq 1 ]]; then
    add_to_hosts "$hosts"
  else
    printf '\n'
    if [[ $BOX_ON -eq 1 ]]; then
      say "record them:  htbbox host $DOMAIN $(printf '%s' "$hosts" | tr '\n' ' ')"
    else
      say "add to /etc/hosts:"
      printf '%s  %s %s%s\n' "$C_DIM" "$TARGET" "$(printf '%s' "$hosts" | tr '\n' ' ')" "$C_R"
    fi
    say "or re-run with --add-hosts"
  fi
}

add_to_hosts() {
  local hosts="$1" ip="$TARGET"
  local -a new=()
  [[ "$ip" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]] || { warn "-t is not an IP; skipping /etc/hosts"; return 0; }
  # On the active box, htbbox owns /etc/hosts: it records the names in
  # box.json (and the domain if unset) and re-points the hosts block.
  if [[ $BOX_ON -eq 1 ]]; then
    local -a names; mapfile -t names <<< "$hosts"
    say "htbbox host $DOMAIN ${names[*]}"
    htbbox host "$DOMAIN" "${names[@]}" && ok "recorded in box.json + /etc/hosts"
    return 0
  fi
  local h
  while read -r h; do
    [[ -z "$h" ]] && continue
    # Exact, case-insensitive name match on non-comment lines.
    awk -v h="$h" 'BEGIN{h=tolower(h)} /^[[:space:]]*#/{next}
      {for (i=2; i<=NF; i++) if (tolower($i) == h) f=1} END{exit !f}' /etc/hosts 2>/dev/null && continue
    new+=("$h")
  done <<< "$hosts"
  [[ ${#new[@]} -eq 0 ]] && { ok "/etc/hosts already current"; return 0; }
  local line="$ip ${new[*]}"
  say "appending to /etc/hosts (sudo): $line"
  printf '%s\n' "$line" | sudo tee -a /etc/hosts >/dev/null && ok "added ${#new[@]} name(s)"
}

# ---------- VHOST ----------
# Prints the ffuf filter for the default-vhost response, AC when it varies,
# or DEAD when none of the probes got an HTTP answer at all.
calibrate_vhost() {
  local base="$1" cal="$TMP/cal.txt" caljson="$TMP/cal.json" i
  for i in 1 2 3 4 5; do printf 'dmnfz%s%s\n' "$i" "$RANDOM$RANDOM"; done > "$cal"
  ffuf "${FFUF_COMMON[@]}" -s \
    -w "$cal:FUZZ" -u "$SCHEME://$(hostport "$base")/" \
    -H "Host: FUZZ.$DOMAIN" -mc all -o "$caljson" >/dev/null 2>&1 || true
  local n; n="$(jq -r '.results | length' "$caljson" 2>/dev/null || printf '0')"
  [[ "$n" =~ ^[0-9]+$ && "$n" -gt 0 ]] || { printf 'DEAD\n'; return 0; }
  local sizes words lines
  sizes="$(jq -r '[.results[].length] | unique | @csv' "$caljson" 2>/dev/null)"
  words="$(jq -r '[.results[].words]  | unique | @csv' "$caljson" 2>/dev/null)"
  lines="$(jq -r '[.results[].lines]  | unique | @csv' "$caljson" 2>/dev/null)"
  if [[ "$sizes" == *,* ]]; then
    if [[ "$words" != *,* && -n "$words" ]]; then printf -- '-fw %s\n' "$words"; return 0; fi
    if [[ "$lines" != *,* && -n "$lines" ]]; then printf -- '-fl %s\n' "$lines"; return 0; fi
    printf 'AC\n'; return 0
  fi
  [[ -n "$sizes" ]] && { printf -- '-fs %s\n' "$sizes"; return 0; }
  printf 'AC\n'
}

run_vhost() {
  need_target; banner; need_domain; use_wordlist "$(dns_wordlist)"
  say "target   $SCHEME://$(hostport "$TARGET")/   Host: FUZZ.$DOMAIN"
  say "wordlist $WL"

  say "calibrating default-vhost baseline…"
  local filt; filt="$(calibrate_vhost "$TARGET")"
  local -a FILTER=()
  case "$filt" in
    DEAD)
      die "no HTTP answer from $SCHEME://$(hostport "$TARGET")/ — wrong -p, need --https (-k), or VPN down?" ;;
    AC)
      warn "default response varies — using ffuf auto-calibration (-ac)"
      FILTER=(-ac) ;;
    *)
      ok "baseline ${filt% *}=${filt#* } — filtering it out"
      read -r -a FILTER <<< "$filt" ;;
  esac

  local out="$TMP/vhost.json"
  ffuf "${FFUF_COMMON[@]}" \
    -w "$WL:FUZZ" -u "$SCHEME://$(hostport "$TARGET")/" \
    -H "Host: FUZZ.$DOMAIN" -mc all "${FILTER[@]}" "${PASSTHRU[@]}" -o "$out" 2>/dev/null || true

  local n; n="$(jq -r '.results | length' "$out" 2>/dev/null || printf '0')"
  printf '\n'
  if [[ ! "$n" =~ ^[0-9]+$ || "$n" -eq 0 ]]; then
    warn "no distinct vhosts found (bigger wordlist? right -p? try: dmnfuzz dns)"
    return 1
  fi
  ok "$n distinct vhost(s):"
  jq -r '.results[] | "\(.input.FUZZ)\t[\(.status) · size \(.length) · words \(.words) · lines \(.lines)]\(if .redirectlocation != "" then " -> " + .redirectlocation else "" end)"' "$out" \
    | sort -u | while IFS=$'\t' read -r name meta; do
        printf '  %s%-28s%s %s%s%s\n' "$C_OK$C_B" "$name.$DOMAIN" "$C_R" "$C_DIM" "$meta" "$C_R"
      done

  local hosts; hosts="$(jq -r '.results[].input.FUZZ' "$out" | sort -u | sed "s/\$/.$DOMAIN/")"
  report_names "$hosts" "vhosts-$DOMAIN"
  VHOSTS_FOUND="$hosts"
  return 0
}

# ---------- DNS ----------
run_dns() {
  need_target; banner; need_domain; use_wordlist "$(dns_wordlist)"
  [[ "$TARGET" =~ ^[0-9.]+$ ]] || warn "-t '$TARGET' is not an IP; it is used as the nameserver"
  say "nameserver $TARGET:$PORT"
  say "wordlist   $WL"

  if ! dig +short +time=3 +tries=1 -p "$PORT" SOA "$DOMAIN" @"$TARGET" >/dev/null 2>&1; then
    die "no DNS answer from $TARGET:$PORT (DNS not open there, or VPN down?)"
  fi

  local found="$TMP/dns-names.txt"; : > "$found"

  say "trying zone transfer (AXFR)…"
  local axfr="$TMP/axfr.txt"
  dig +noall +answer +time=5 +tries=1 -p "$PORT" AXFR "$DOMAIN" @"$TARGET" > "$axfr" 2>/dev/null || true
  if grep -q 'IN' "$axfr" && ! grep -qi 'transfer failed' "$axfr"; then
    ok "zone transfer allowed — $(wc -l < "$axfr") record(s):"
    sed 's/^/  /' "$axfr"
    [[ -n "$RECON" ]] && cp "$axfr" "$RECON/dmnfuzz-axfr-$DOMAIN.txt"
    awk '{print tolower($1)}' "$axfr" | sed 's/\.$//' >> "$found"
  else
    say "AXFR refused — brute-forcing instead"
  fi

  # Wildcard check by hand: dnsx's -wd ignores -r and drops every result
  # against a private nameserver. Two random names that both resolve mean a
  # wildcard; any brute hit answering with exactly those addresses is noise.
  local wild="" r1 r2
  r1="$(dig +short +time=3 +tries=1 -p "$PORT" A "dmnfz$RANDOM$RANDOM.$DOMAIN" @"$TARGET" 2>/dev/null | grep -E '^[0-9.]+$' | sort | paste -sd, -)"
  r2="$(dig +short +time=3 +tries=1 -p "$PORT" A "dmnfz$RANDOM$RANDOM.$DOMAIN" @"$TARGET" 2>/dev/null | grep -E '^[0-9.]+$' | sort | paste -sd, -)"
  if [[ -n "$r1" && "$r1" == "$r2" ]]; then
    wild="$r1"; warn "wildcard DNS: *.$DOMAIN -> $wild — filtering that answer out"
  fi

  say "brute-forcing subdomains with dnsx…"
  local raw="$TMP/dns-raw.jsonl" out="$TMP/dns.jsonl"
  dnsx -silent -j -a -aaaa -cname -resp -retry 2 -t "$THREADS" \
    -d "$DOMAIN" -w "$WL" -r "$TARGET:$PORT" "${PASSTHRU[@]}" > "$raw" 2>/dev/null || true
  jq -c --arg w "$wild" 'select($w == "" or (((.a // []) | sort | join(",")) != $w))' "$raw" > "$out" 2>/dev/null || true
  if [[ -s "$out" ]]; then
    printf '\n'; ok "$(jq -s 'length' "$out") name(s) resolve:"
    jq -r '"\(.host)\t\(([.a[]?, .aaaa[]?, (.cname[]? | "CNAME " + .)]) | join(", "))"' "$out" \
      | sort -u | while IFS=$'\t' read -r name addrs; do
          printf '  %s%-28s%s %s%s%s\n' "$C_OK$C_B" "$name" "$C_R" "$C_DIM" "$addrs" "$C_R"
        done
    jq -r '.host' "$out" >> "$found"
  fi

  # Records like the zone apex, _srv names and wildcards do not belong in hosts.
  local hosts
  hosts="$(grep -v -e '^_' -e '\*' "$found" | grep -i "\.$DOMAIN\$" | sort -u)"
  printf '\n'
  [[ -n "$hosts" ]] || { warn "no subdomains found (bigger wordlist? try: dmnfuzz vhost)"; return 1; }
  ok "$(wc -l <<< "$hosts") unique subdomain(s)"
  report_names "$hosts" "dns-$DOMAIN"
  return 0
}

# ---------- DIR ----------
# One GET of $1 (URL) with optional Host $2; sets FP_STATUS, FP_LOC,
# FP_SERVER, FP_POWERED and STACK (iis | php | jsp | "").
fingerprint() {
  local url="$1" vhost="${2:-}" hdrs
  local -a hh=(); [[ -n "$vhost" ]] && hh=(-H "Host: $vhost")
  hdrs="$(curl "${CURL_COMMON[@]}" "${hh[@]}" "$url" 2>/dev/null | tr -d '\r')"
  FP_STATUS="$(sed -n '1s/^HTTP\/[0-9.]* \([0-9]*\).*/\1/p' <<< "$hdrs")"
  FP_LOC="$(sed -n 's/^[Ll]ocation: *//p' <<< "$hdrs" | head -1)"
  FP_SERVER="$(sed -n 's/^[Ss]erver: *//p' <<< "$hdrs" | head -1)"
  FP_POWERED="$(sed -n 's/^[Xx]-[Pp]owered-[Bb]y: *//p' <<< "$hdrs" | paste -sd' ' -)"
  local all cookies
  cookies="$(grep -i '^set-cookie:' <<< "$hdrs" | tr '[:upper:]' '[:lower:]')"
  all="${FP_SERVER,,} ${FP_POWERED,,} $cookies"
  STACK=""
  case "$all" in
    *iis*|*asp.net*|*aspnet*) STACK=iis ;;
    *php*)                    STACK=php ;;
    *tomcat*|*jsessionid*|*servlet*|*jsp*) STACK=jsp ;;
  esac
}

# If a redirect from base $1 stays on the same host, print the directory it
# lands in (/portfolio/), else nothing.
same_host_landing() {
  local loc="$1" host="$2" path
  [[ -z "$loc" ]] && return 0
  if [[ "$loc" == *://* ]]; then
    local lh="${loc#*://}"; lh="${lh%%/*}"; lh="${lh%%:*}"
    [[ "${lh,,}" == "${host%%:*}" || "$lh" == "$TARGET" ]] || return 0
    path="/${loc#*://*/}"; [[ "$loc" == *://*/* ]] || path="/"
  else
    path="$loc"
  fi
  path="${path%%\?*}"
  [[ "$path" == */ ]] || path="${path%/*}/"
  [[ "$path" == "/" || "$path" != /* ]] && return 0
  printf '%s\n' "$path"
}

# One ffuf pass over $URL$1; appends display rows to $TMP/rows.tsv. $3 is the
# landing path the base redirects to, if any.
dir_pass() {
  local sub="$1" shown="$2" land="${3:-}" out="$TMP/dir.json"
  rm -f "$out"
  ffuf "${FFUF_COMMON[@]}" "${HOSTHDR[@]}" \
    -w "$WL:FUZZ" -u "${URL}${sub#/}FUZZ" \
    -mc 200,204,301,302,307,308,401,403,405,500 -ac \
    "${EXTARGS[@]}" "${RECARGS[@]}" "${PASSTHRU[@]}" -o "$out" 2>/dev/null || true
  # IIS answers DOS device names (con, aux, nul, prn, com1, lpt1 …) with an
  # error redirect; they are never real content.
  # A catch-all that re-prefixes the landing path (dev.pov.htb/x ->
  # /portfolio/x) is the redirect, not content: drop it.
  jq -r --arg s "$shown" --arg land "$land" --arg sub "${sub#/}" '.results[]
    | select((.redirectlocation | test("aspxerrorpath"; "i")) | not)
    | select($land == "" or (.redirectlocation | sub("^https?://[^/]+"; "") | ascii_downcase)
        != (($land + (.url | sub("^https?://[^/]+/"; "") | ltrimstr($sub))) | ascii_downcase))
    | select((.input.FUZZ | ascii_downcase | test("^(con|aux|nul|prn|com[0-9]|lpt[0-9])(\\..*)?$")) | not)
    | "\(.status)\t\(.length)\t\(if $s == "" then .url else (.url | sub("^https?://[^/]+"; $s)) end)\t\(.redirectlocation)"' \
    "$out" 2>/dev/null >> "$TMP/rows.tsv" || true
}

# $1 (optional): a vhost to scan through $TARGET with a Host: header, so auto
# mode works before the names are in /etc/hosts.
run_dir() {
  local vhost="${1:-}" shown host
  HOSTHDR=()
  if [[ -n "$vhost" ]]; then
    URL="$SCHEME://$(hostport "$TARGET")/"; HOSTHDR=(-H "Host: $vhost")
    shown="$SCHEME://$(hostport "$vhost")"; host="$vhost"
  else
    if [[ -z "$URL" ]]; then
      if [[ -n "$TARGET" ]]; then URL="$SCHEME://$(hostport "$TARGET")/"; else die "dir mode needs -u <url> (or -t/-p, or an active box)"; fi
    fi
    [[ "$URL" == *://* ]] || URL="$SCHEME://$URL"
    [[ "$URL" != */ ]] && URL="$URL/"
    shown=""; host="${URL#*://}"; host="${host%%/*}"
    # -H 'Host: dev.pov.htb' names the real host for redirect handling.
    local h
    for h in "${EXTRA_HEADERS[@]}"; do
      [[ "${h,,}" == host:* ]] && { host="${h#*:}"; host="${host// /}"; shown="$SCHEME://$host"; }
    done
  fi
  banner

  fingerprint "$URL" "$vhost"
  [[ -n "$FP_STATUS" ]] || { warn "no HTTP answer from ${shown:-${URL%/}}/ — skipping"; return 1; }
  say "base     ${shown:-${URL%/}}/  [$FP_STATUS${FP_LOC:+ -> $FP_LOC}]  ${FP_SERVER:-?}${FP_POWERED:+ · $FP_POWERED}"

  local dflt; dflt="$(dir_wordlist "$STACK" | head -1)"
  use_wordlist "$dflt"
  [[ "$STACK" == iis && -z "$WL_USER" ]] && say "IIS is case-insensitive — using the lowercase list"
  say "wordlist $WL"

  local ext="$EXT"
  if [[ -z "$ext" ]]; then
    local sugg=""
    case "$STACK" in iis) sugg="aspx,asp,txt" ;; php) sugg="php,txt" ;; jsp) sugg="jsp,do,txt" ;; esac
    if [[ -n "$sugg" && $AUTOEXT -eq 1 ]]; then ext="$sugg"
    elif [[ -n "$sugg" ]]; then say "stack looks like $STACK — try -x $sugg (or -X)"
    fi
  fi
  EXTARGS=(); [[ -n "$ext" ]] && { ext="${ext//./}"; EXTARGS=(-e ".${ext//,/,.}"); say "extensions .${ext//,/ .}"; }
  RECARGS=(); [[ $RECURSE -eq 1 ]] && { RECARGS=(-recursion -recursion-depth 2); say "recursion on (depth 2)"; }

  : > "$TMP/rows.tsv"
  local -a subs=("")
  local land; land="$(same_host_landing "$FP_LOC" "${host,,}")"
  if [[ -n "$land" ]]; then
    say "base redirects to $land — scanning it too"
    subs+=("$land")
  fi
  local s
  for s in "${subs[@]}"; do
    say "fuzzing  ${shown:-${URL%/}}${s:-/}FUZZ"
    dir_pass "$s" "$shown" "$land"
  done

  local rows="$TMP/rows-sorted.tsv"
  sort -u "$TMP/rows.tsv" > "$rows"
  local n; n="$(wc -l < "$rows")"
  printf '\n'
  [[ "$n" -gt 0 ]] || { warn "no hits (try -x / -X, or another wordlist)"; return 1; }
  ok "$n path(s):"
  local st len u loc col
  while IFS=$'\t' read -r st len u loc; do
    col="$C_OK"
    [[ "$st" =~ ^30 ]] && col="$C_WARN"
    [[ "$st" =~ ^40 ]] && col="$C_DIM"
    [[ -n "$loc" ]] && loc=" -> $loc"
    printf '  %s%s%s  %s%-6s%s  %s%s%s%s\n' "$col" "$st" "$C_R" "$C_DIM" "$len" "$C_R" "$u" "$C_DIM" "$loc" "$C_R"
  done < "$rows"
  local f; f="$(outfile_for "dir-${host%%:*}")"
  if [[ -n "$f" ]]; then
    if [[ -n "$OUTFILE" ]]; then cut -f3 "$rows" >> "$f"; else cut -f3 "$rows" > "$f"; fi
    ok "paths saved -> $f"
  fi
  return 0
}

# ---------- AUTO ----------
run_auto() {
  run_vhost || true
  # The apex itself first (pov.htb), then every vhost found.
  local -a scan=()
  [[ -n "$DOMAIN" ]] && scan+=("$DOMAIN")
  local vh
  while read -r vh; do [[ -n "$vh" ]] && scan+=("$vh"); done <<< "$VHOSTS_FOUND"
  [[ -n "$OUTFILE" ]] && : > "$OUTFILE.paths"
  [[ -n "$OUTFILE" ]] && OUTFILE="$OUTFILE.paths"
  printf '\n'; say "dir-scanning ${scan[*]} (via Host: header)…"
  MODE="dir"
  for vh in "${scan[@]}"; do
    printf '\n%s── %s ──%s\n' "$C_H" "$vh" "$C_R"
    run_dir "$vh" || true
  done
  return 0
}

case "$MODE" in
  vhost) run_vhost ;;
  dns)   run_dns ;;
  dir)   run_dir ;;
  auto)  run_auto ;;
esac