diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 98847864..1e506123 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -22,6 +22,12 @@ concurrency: env: CARGO_TERM_COLOR: always RUST_BACKTRACE: 1 + # Every feature a build can ship with, for the tests and coverage: not + # count-allocs (a diagnostic allocator) nor bench-no-middleware and + # bench-null-middleware (measurement builds that take the middleware chain + # out, under which the chain the release runs is not even compiled). + # Clippy still checks --all-features, so those compile too. + SHIPPING_FEATURES: pqc pqc-signatures metrics admin-api geoip acme legacy-pqc fips jobs: # ============================================================================= @@ -198,7 +204,7 @@ jobs: if: matrix.os == 'ubuntu-latest' env: PQCRYPTA_REQUIRE_REDIS: "1" - run: cargo test --all-features -- --nocapture + run: cargo test --features "$SHIPPING_FEATURES" -- --nocapture - name: Run unit tests (macOS) if: matrix.os == 'macos-latest' @@ -527,6 +533,40 @@ jobs: done < <(git rev-list "$BASE..$HEAD") exit $status + # ============================================================================= + # Shell + # ============================================================================= + # Every shell script against ShellCheck, the release pinned here and checked + # against its published digest, following what each one sources + # (.shellcheckrc). The pentest configuration template, config.demo.sh, is + # only ever sourced, so it is read through the scripts that source it, where + # its settings are used. + shellcheck: + name: ShellCheck + runs-on: ubuntu-latest + env: + SHELLCHECK_VERSION: v0.12.0 + SHELLCHECK_SHA256: 28827970d4166f58329182a0593f506ea54b40e34f18414ff43392baff9dc754 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: ShellCheck, the pinned release + run: | + curl -fsSL -o "$RUNNER_TEMP/shellcheck.tar.xz" \ + "https://github.com/koalaman/shellcheck/releases/download/$SHELLCHECK_VERSION/shellcheck-$SHELLCHECK_VERSION.linux.x86_64.tar.xz" + echo "$SHELLCHECK_SHA256 $RUNNER_TEMP/shellcheck.tar.xz" | sha256sum -c - + tar -xJf "$RUNNER_TEMP/shellcheck.tar.xz" -C "$RUNNER_TEMP" + echo "$RUNNER_TEMP/shellcheck-$SHELLCHECK_VERSION" >> "$GITHUB_PATH" + - name: Every script + run: | + shellcheck --version + git ls-files -z | while IFS= read -r -d '' f; do + case "$f" in vendor/*|pentests/config.demo.sh) continue ;; esac + case "$f" in *.sh) echo "$f"; continue ;; esac + head -1 "$f" | grep -qE '^#!(/bin/(ba)?sh|/usr/bin/env (ba)?sh)' && echo "$f" + done | xargs -r shellcheck + # ============================================================================= # Workflow security # ============================================================================= @@ -601,7 +641,7 @@ jobs: - name: Tests under coverage env: PQCRYPTA_REQUIRE_REDIS: "1" - run: cargo "+$NIGHTLY" llvm-cov --branch --all-features --ignore-filename-regex '(^|/)vendor/' --lcov --output-path lcov.info + run: cargo "+$NIGHTLY" llvm-cov --branch --features "$SHIPPING_FEATURES" --ignore-filename-regex '(^|/)vendor/' --lcov --output-path lcov.info - name: Summary run: | diff --git a/.github/workflows/release-please.yml b/.github/workflows/release-please.yml index 32189cbe..d8d4a2ae 100644 --- a/.github/workflows/release-please.yml +++ b/.github/workflows/release-please.yml @@ -55,23 +55,24 @@ jobs: # published, as immutable releases require. # The release PR is opened and updated with this workflow's GITHUB_TOKEN, # and GitHub starts no workflow for a push made with that token, so its - # commit would merge with neither CI nor CodeQL behind it. A - # workflow_dispatch made with the same token does start one: both run on the - # release branch, and their checks are on the commit the PR merges. + # commit would merge with none of the checks main requires behind it. A + # workflow_dispatch made with the same token does start one: CI, CodeQL, + # the dependency audit and the secret scan run on the release branch, and + # their checks are on the commit the PR merges. release-pr-checks: - name: CI and CodeQL on the release PR + name: The required checks on the release PR needs: release-please if: needs.release-please.outputs.prs_created == 'true' runs-on: ubuntu-latest permissions: - actions: write # start CI and CodeQL on the release branch + actions: write # start the required checks' workflows on the release branch steps: - name: Start them on the release branch env: GH_TOKEN: ${{ github.token }} BRANCH: ${{ fromJSON(needs.release-please.outputs.pr).headBranchName }} run: | - for workflow in ci.yml codeql.yml; do + for workflow in ci.yml codeql.yml cargo-deny.yml secret-scan.yml; do gh workflow run "$workflow" --repo "$GITHUB_REPOSITORY" --ref "$BRANCH" done diff --git a/.github/workflows/secret-scan.yml b/.github/workflows/secret-scan.yml index 86ccdfc1..1f5c7e3d 100644 --- a/.github/workflows/secret-scan.yml +++ b/.github/workflows/secret-scan.yml @@ -7,6 +7,9 @@ on: branches: [main] schedule: - cron: '0 3 * * 1' # Monday 03:00 UTC + # Release Please starts it on each release PR (release-please.yml), whose + # pushes start no workflow of their own + workflow_dispatch: # Read only unless a job asks for more permissions: diff --git a/.shellcheckrc b/.shellcheckrc new file mode 100644 index 00000000..662e2045 --- /dev/null +++ b/.shellcheckrc @@ -0,0 +1,2 @@ +external-sources=true +source-path=SCRIPTDIR diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 0948d703..b412fac9 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -43,7 +43,8 @@ git clone https://github.com/PQCrypta/pqcrypta-proxy.git cd pqcrypta-proxy cargo build cargo test # unit, integration and documentation tests -cargo test --all-features # what CI runs on Linux +cargo test --features "pqc pqc-signatures metrics admin-api geoip acme legacy-pqc fips" + # what CI runs on Linux: every feature a build ships with cargo run -- --config config/example-config.toml --validate ``` @@ -64,7 +65,7 @@ reaches, and each one for an hour a day. ```bash cargo fmt -p pqcrypta-proxy -- --check cargo clippy --all-targets --all-features -- -D warnings - cargo test --all-features + cargo test --features "pqc pqc-signatures metrics admin-api geoip acme legacy-pqc fips" ``` 4. Open a pull request against `main`. Describe what changes and why, and link the issue it addresses. A maintainer reviews it (below), and it @@ -128,8 +129,8 @@ that touch the code it reaches, and for an hour each day. The style guides are the [Rust Style Guide](https://doc.rust-lang.org/style-guide/) as rustfmt applies it, the [Rust API Guidelines](https://rust-lang.github.io/api-guidelines/), -and Clippy's lints; for GitHub Actions workflows, zizmor's. CI enforces -each of them. +and Clippy's lints; for shell, [ShellCheck](https://www.shellcheck.net/)'s; +for GitHub Actions workflows, zizmor's. CI enforces each of them. - rustfmt, and clippy with `all`, `pedantic` and `nursery` at warning level, every warning an error in CI ([`Cargo.toml`](Cargo.toml) `[lints]`, diff --git a/benchmarks/ack-ab.sh b/benchmarks/ack-ab.sh index 330484b8..a9824447 100755 --- a/benchmarks/ack-ab.sh +++ b/benchmarks/ack-ab.sh @@ -21,6 +21,7 @@ # Order flips on round parity: running A first every round confounds the binary # with the slot, and a null test on this rig put the slot effect at 3.7%. set -uo pipefail +# shellcheck source=benchlib.sh # the file this loads, as committed . /root/bench/benchlib.sh bench_guard_init export LD_LIBRARY_PATH=/opt/h3bench/lib diff --git a/benchmarks/bench-backend.sh b/benchmarks/bench-backend.sh index 2813c2ce..9b982bc6 100755 --- a/benchmarks/bench-backend.sh +++ b/benchmarks/bench-backend.sh @@ -14,6 +14,7 @@ # A backend that is not clear turns every cell it binds into a measurement of # nginx rather than of a proxy. set -uo pipefail +# shellcheck source=benchlib.sh # the file this loads, as committed . /root/bench/benchlib.sh bench_guard_init diff --git a/benchmarks/bench-handshake2.sh b/benchmarks/bench-handshake2.sh index 30caf77b..51bd5c04 100755 --- a/benchmarks/bench-handshake2.sh +++ b/benchmarks/bench-handshake2.sh @@ -20,7 +20,7 @@ set -uo pipefail # Shared guards — see benchlib.sh. Each exists because its absence produced a # confident wrong number that was believed for a while. -# shellcheck source=/root/bench/benchlib.sh +# shellcheck source=benchlib.sh . /root/bench/benchlib.sh bench_guard_init export LD_LIBRARY_PATH=/opt/h3bench/lib diff --git a/benchmarks/bench-routes.sh b/benchmarks/bench-routes.sh index 16a122d2..dc61a089 100755 --- a/benchmarks/bench-routes.sh +++ b/benchmarks/bench-routes.sh @@ -12,6 +12,7 @@ # source and allocated a lowercased copy of the path per route. After, each is # compiled once and the comparisons allocate nothing. set -uo pipefail +# shellcheck source=benchlib.sh # the file this loads, as committed . /root/bench/benchlib.sh bench_guard_init LOCK=/run/lock/pqc-bench.lock diff --git a/benchmarks/benchlib.sh b/benchmarks/benchlib.sh index 6332b75e..786b28e4 100755 --- a/benchmarks/benchlib.sh +++ b/benchmarks/benchlib.sh @@ -207,8 +207,11 @@ bench_assert_pinning() { # $1=pid $2=expected cpu list, e.g. 4-5 echo "pinning ok: pid $pid within $want" } +# The guards every benchmark starts with: enough file descriptors, the one +# lock (BENCH_LOCK, /run/lock/pqc-bench.lock unless set), and the proxies +# stopped however the run ends bench_guard_init() { bench_require_fds - bench_take_lock "${1:-/run/lock/pqc-bench.lock}" + bench_take_lock "${BENCH_LOCK:-/run/lock/pqc-bench.lock}" trap 'bench_stop_proxies' EXIT INT TERM } diff --git a/benchmarks/cycles.sh b/benchmarks/cycles.sh index e791472b..9bf81a5d 100755 --- a/benchmarks/cycles.sh +++ b/benchmarks/cycles.sh @@ -10,6 +10,7 @@ # cycles & instructions flat, IPC down -> cache/memory contention set -uo pipefail while fuser /run/lock/pqc-bench.lock >/dev/null 2>&1; do sleep 30; done +# shellcheck source=benchlib.sh # the file this loads, as committed . /root/bench/benchlib.sh bench_guard_init export LD_LIBRARY_PATH=/opt/h3bench/lib diff --git a/benchmarks/instr-ab.sh b/benchmarks/instr-ab.sh index 68e47a3c..c34aaa98 100755 --- a/benchmarks/instr-ab.sh +++ b/benchmarks/instr-ab.sh @@ -17,6 +17,7 @@ # Order flips on round parity so neither binary always runs in the same slot. set -uo pipefail while fuser /run/lock/pqc-bench.lock >/dev/null 2>&1; do sleep 30; done +# shellcheck source=benchlib.sh # the file this loads, as committed . /root/bench/benchlib.sh bench_guard_init export LD_LIBRARY_PATH=/opt/h3bench/lib diff --git a/benchmarks/instr.sh b/benchmarks/instr.sh index 00b7ec55..1b1707bc 100755 --- a/benchmarks/instr.sh +++ b/benchmarks/instr.sh @@ -13,6 +13,7 @@ # becomes the final headline number rather than the development feedback loop. set -uo pipefail while fuser /run/lock/pqc-bench.lock >/dev/null 2>&1; do sleep 30; done +# shellcheck source=benchlib.sh # the file this loads, as committed . /root/bench/benchlib.sh bench_guard_init export LD_LIBRARY_PATH=/opt/h3bench/lib diff --git a/benchmarks/launch-current.sh b/benchmarks/launch-current.sh index 1035021f..00bbf5d8 100755 --- a/benchmarks/launch-current.sh +++ b/benchmarks/launch-current.sh @@ -6,7 +6,7 @@ # Every benchmark /proxy-comparison/ quotes, on the build now deployed. set -uo pipefail -cd /root/bench +cd /root/bench || exit 1 export NOW_BIN=/root/bench/pqc-93256d06 STAMP=$(date +%Y%m%d_%H%M%S) matrix() { # $1=name $2=arms $3=reps [$4=ceiling] @@ -30,12 +30,12 @@ matrix cmp3 "haproxy lean-now pqc-full" 6 ceiling matrix feat2 "plumb feat" 4 matrix sec2 "sec-off sec-on" 4 BIN=$NOW_BIN RES=/root/bench/out/handshake-$STAMP ./run-handshake.sh -BIN=$NOW_BIN ./nd-ab.sh > /root/bench/out/nd-ab-$STAMP.log 2>&1 +BIN=$NOW_BIN ./nd-ab.sh > "/root/bench/out/nd-ab-$STAMP.log" 2>&1 BIN=$NOW_BIN RES=/root/bench/out/window-$STAMP ./window-study.sh -echo "########## all done $(date -Is)" > /root/bench/out/current-$STAMP.done +echo "########## all done $(date -Is)" > "/root/bench/out/current-$STAMP.done" # The consistency section: where the run-to-run spread comes from, re-asked on # the current build. for s in spread-confirm cycles stalls steal smt; do - BIN=$NOW_BIN ./$s.sh > /root/bench/out/$s-$STAMP.log 2>&1 + BIN=$NOW_BIN "./$s.sh" > "/root/bench/out/$s-$STAMP.log" 2>&1 done -echo "########## consistency done $(date -Is)" >> /root/bench/out/current-$STAMP.done +echo "########## consistency done $(date -Is)" >> "/root/bench/out/current-$STAMP.done" diff --git a/benchmarks/launch-rerun.sh b/benchmarks/launch-rerun.sh index 4372db01..11dc9686 100755 --- a/benchmarks/launch-rerun.sh +++ b/benchmarks/launch-rerun.sh @@ -11,7 +11,7 @@ # it finishes, into out/publish-$STAMP//, and out/publish-$STAMP.done # lists what finished. set -uo pipefail -cd /root/bench +cd /root/bench || exit 1 export NOW_BIN=/root/bench/pqc-fa8556d2 COMMIT=6d75ab9 STAMP=$(date +%Y%m%d_%H%M%S) @@ -39,20 +39,20 @@ publish() { echo "$1 $(date -Is)" >> "$PUB.done"; } if matrix cmp4 "haproxy lean-now pqc-full" 6 ceiling; then BINARY=$NOW_BIN FULL_ARM=pqc-full FULL_CONFIG=pqc-bench-full.toml \ - python3 export-bench.py out/cmp4-$STAMP cmp4- "$PUB/cmp4-$STAMP" lean-now $COMMIT >/dev/null && publish cmp4-$STAMP + python3 export-bench.py "out/cmp4-$STAMP" cmp4- "$PUB/cmp4-$STAMP" lean-now "$COMMIT" >/dev/null && publish "cmp4-$STAMP" fi if matrix feat3 "plumb feat" 4; then BINARY=$NOW_BIN BASE=plumb CONFS=pqc-bench.toml,pqc-bench-features.toml,nginx.conf \ - python3 export-bench.py out/feat3-$STAMP feat3- "$PUB/feat3-$STAMP" feat $COMMIT >/dev/null && publish feat3-$STAMP + python3 export-bench.py "out/feat3-$STAMP" feat3- "$PUB/feat3-$STAMP" feat "$COMMIT" >/dev/null && publish "feat3-$STAMP" fi if matrix sec3 "sec-off sec-on" 4; then BINARY=$NOW_BIN BASE=sec-off CONFS=pqc-sec-off.toml,pqc-sec-on.toml,nginx.conf \ - python3 export-bench.py out/sec3-$STAMP sec3- "$PUB/sec3-$STAMP" sec-on $COMMIT >/dev/null && publish sec3-$STAMP + python3 export-bench.py "out/sec3-$STAMP" sec3- "$PUB/sec3-$STAMP" sec-on "$COMMIT" >/dev/null && publish "sec3-$STAMP" fi -BIN=$NOW_BIN OUT=/root/bench/out/nd-ab-$STAMP.csv ./nd-ab.sh > /root/bench/out/nd-ab-$STAMP.log 2>&1 +BIN=$NOW_BIN OUT="/root/bench/out/nd-ab-$STAMP.csv" ./nd-ab.sh > "/root/bench/out/nd-ab-$STAMP.log" 2>&1 BIN=$NOW_BIN OUT=/root/bench/out/nd-h1-dist-$STAMP.txt ./nd-h1-dist.sh >/dev/null 2>&1 -if grep -q "^########## done" /root/bench/out/nd-ab-$STAMP.log; then +if grep -q "^########## done" "/root/bench/out/nd-ab-$STAMP.log"; then BINARY=$NOW_BIN DIST=/root/bench/out/nd-h1-dist-$STAMP.txt \ - python3 export-study.py nagle out/nd-ab-$STAMP.csv "$PUB/nagle-$STAMP" $COMMIT >/dev/null && publish nagle-$STAMP + python3 export-study.py nagle "out/nd-ab-$STAMP.csv" "$PUB/nagle-$STAMP" "$COMMIT" >/dev/null && publish "nagle-$STAMP" fi echo "all $(date -Is)" >> "$PUB.done" diff --git a/benchmarks/mw-ab.sh b/benchmarks/mw-ab.sh index b3fff2f6..6c074555 100755 --- a/benchmarks/mw-ab.sh +++ b/benchmarks/mw-ab.sh @@ -18,6 +18,7 @@ # header delta is measured too and the result is an UPPER BOUND on what removing # the layering alone would buy. set -uo pipefail +# shellcheck source=benchlib.sh # the file this loads, as committed . /root/bench/benchlib.sh bench_guard_init export LD_LIBRARY_PATH=/opt/h3bench/lib diff --git a/benchmarks/mw3-abc.sh b/benchmarks/mw3-abc.sh index 8551f7e9..d105b19e 100755 --- a/benchmarks/mw3-abc.sh +++ b/benchmarks/mw3-abc.sh @@ -21,6 +21,7 @@ # # Order rotates each round so no arm is permanently in the slow slot. set -uo pipefail +# shellcheck source=benchlib.sh # the file this loads, as committed . /root/bench/benchlib.sh bench_guard_init export LD_LIBRARY_PATH=/opt/h3bench/lib diff --git a/benchmarks/mw3.sh b/benchmarks/mw3.sh index 63380cb8..a27806a9 100755 --- a/benchmarks/mw3.sh +++ b/benchmarks/mw3.sh @@ -21,6 +21,7 @@ # # Order rotates each round so no arm is permanently in the slow slot. set -uo pipefail +# shellcheck source=benchlib.sh # the file this loads, as committed . /root/bench/benchlib.sh bench_guard_init export LD_LIBRARY_PATH=/opt/h3bench/lib diff --git a/benchmarks/nd-ab.sh b/benchmarks/nd-ab.sh index 9e8e57d0..ad0b661b 100755 --- a/benchmarks/nd-ab.sh +++ b/benchmarks/nd-ab.sh @@ -22,6 +22,7 @@ while fuser /run/lock/pqc-bench.lock >/dev/null 2>&1; do echo "waiting for the lock $(date -Is)"; sleep 120 done +# shellcheck source=benchlib.sh # the file this loads, as committed . /root/bench/benchlib.sh bench_guard_init export LD_LIBRARY_PATH=/opt/h3bench/lib diff --git a/benchmarks/nd-h1-dist.sh b/benchmarks/nd-h1-dist.sh index 4e6d7473..ffcfb09f 100755 --- a/benchmarks/nd-h1-dist.sh +++ b/benchmarks/nd-h1-dist.sh @@ -7,6 +7,7 @@ # Where the HTTP/1.1 Nagle stall comes from: the per-request time distribution # (min, max, mean, sd) with tcp_nodelay off, which the nd-ab CSV reduces to a mean. set -uo pipefail +# shellcheck source=benchlib.sh # the file this loads, as committed . /root/bench/benchlib.sh bench_guard_init export LD_LIBRARY_PATH=/opt/h3bench/lib diff --git a/benchmarks/onestream.sh b/benchmarks/onestream.sh index 29cde28d..a696933f 100755 --- a/benchmarks/onestream.sh +++ b/benchmarks/onestream.sh @@ -7,6 +7,7 @@ # The single-in-flight-stream cell, both proxies, current build. # This is the cell that read 385 req/s before the ACK fix. set -uo pipefail +# shellcheck source=benchlib.sh # the file this loads, as committed . /root/bench/benchlib.sh bench_guard_init export LD_LIBRARY_PATH=/opt/h3bench/lib @@ -16,7 +17,8 @@ cell() { # $1=label $2=port $3=alpn local pid c0 c1 t0 t1 out pid=$(ss -lntupH 2>/dev/null | grep ":$2" | grep -oP 'pid=\K[0-9]+' | head -1) c0=$(awk '{print $14+$15}' "/proc/$pid/stat"); t0=$(date +%s.%N) - out=$(taskset -c "$BENCH_GEN_CPUS" timeout 40 "$H2LOAD" $3 -c 10 -m 1 -t 6 \ + local -a alpn; read -ra alpn <<<"$3" # h2load's ALPN options, as words + out=$(taskset -c "$BENCH_GEN_CPUS" timeout 40 "$H2LOAD" "${alpn[@]}" -c 10 -m 1 -t 6 \ --duration=10 --warm-up-time="${WU:-$BENCH_WARMUP}" "https://bench.local:$2/1k" 2>/dev/null) t1=$(date +%s.%N); c1=$(awk '{print $14+$15}' "/proc/$pid/stat") echo "$out" | awk -v l="$1" -v a="$c0" -v b="$c1" -v s="$t0" -v e="$t1" ' diff --git a/benchmarks/queue-window.sh b/benchmarks/queue-window.sh index 9a4543b4..b8f90c63 100644 --- a/benchmarks/queue-window.sh +++ b/benchmarks/queue-window.sh @@ -9,14 +9,14 @@ # queue, so the page's two runs describe one build. Packaged into # out/publish-$STAMP/ with its own .done list. set -uo pipefail -cd /root/bench +cd /root/bench || exit 1 until grep -q '^all ' /root/bench/out/publish-20260925_132019.done 2>/dev/null; do sleep 300; done STAMP=$(date +%Y%m%d_%H%M%S) PUB=/root/bench/out/publish-$STAMP mkdir -p "$PUB" BIN=/root/bench/pqc-fa8556d2 RES=/root/bench/out/window-$STAMP ./window-study.sh >/dev/null 2>&1 -if grep -q '^########## done' /root/bench/out/window-$STAMP/run.log; then - BINARY=/root/bench/pqc-fa8556d2 python3 export-study.py window out/window-$STAMP "$PUB/window-$STAMP" 6d75ab9 >/dev/null \ +if grep -q '^########## done' "/root/bench/out/window-$STAMP/run.log"; then + BINARY=/root/bench/pqc-fa8556d2 python3 export-study.py window "out/window-$STAMP" "$PUB/window-$STAMP" 6d75ab9 >/dev/null \ && echo "window-$STAMP $(date -Is)" >> "$PUB.done" fi echo "all $(date -Is)" >> "$PUB.done" diff --git a/benchmarks/repeat.sh b/benchmarks/repeat.sh index 765396a5..716ea493 100755 --- a/benchmarks/repeat.sh +++ b/benchmarks/repeat.sh @@ -12,13 +12,13 @@ set -uo pipefail # Shared guards — see benchlib.sh. Each exists because its absence produced a # confident wrong number that was believed for a while. -# shellcheck source=/root/bench/benchlib.sh +# shellcheck source=benchlib.sh . /root/bench/benchlib.sh # Orchestrator only: bench-routes.sh takes the lock per invocation, so taking # it here as well would deadlock every child. Just raise the fd limit. bench_require_fds A=$1; B=$2; N=${3:-6} -for i in $(seq "$N"); do +for _ in $(seq "$N"); do BIN="$A" ./bench-routes.sh 2>/dev/null | tail -3 | awk -v t="A" "{print t, \$3}" BIN="$B" ./bench-routes.sh 2>/dev/null | tail -3 | awk -v t="B" "{print t, \$3}" done diff --git a/benchmarks/run-bench.sh b/benchmarks/run-bench.sh index ceba5e36..583a7166 100755 --- a/benchmarks/run-bench.sh +++ b/benchmarks/run-bench.sh @@ -14,7 +14,7 @@ set -uo pipefail # Shared guards — see benchlib.sh. Each exists because its absence produced a # confident wrong number that was believed for a while. -# shellcheck source=/root/bench/benchlib.sh +# shellcheck source=benchlib.sh . /root/bench/benchlib.sh bench_guard_init diff --git a/benchmarks/run-handshake.sh b/benchmarks/run-handshake.sh index 89678397..34f2a72d 100755 --- a/benchmarks/run-handshake.sh +++ b/benchmarks/run-handshake.sh @@ -21,6 +21,7 @@ # read off a connection with openssl s_client before each group is measured, # and the run refuses to continue if it is not the group asked for. set -uo pipefail +# shellcheck source=benchlib.sh # the file this loads, as committed . /root/bench/benchlib.sh bench_guard_init export LD_LIBRARY_PATH=/opt/h3bench/lib diff --git a/benchmarks/run-lean.sh b/benchmarks/run-lean.sh index d3048948..5efca08b 100755 --- a/benchmarks/run-lean.sh +++ b/benchmarks/run-lean.sh @@ -31,6 +31,7 @@ # REPS=4), so each arm spends one rep in each slot -- trap 11, the slot effect, # measured 3.7% on a null test, cancels instead of landing on one arm. set -uo pipefail +# shellcheck source=benchlib.sh # the file this loads, as committed . /root/bench/benchlib.sh bench_guard_init diff --git a/benchmarks/run-pqc-only.sh b/benchmarks/run-pqc-only.sh index 71446330..1fb71733 100755 --- a/benchmarks/run-pqc-only.sh +++ b/benchmarks/run-pqc-only.sh @@ -15,7 +15,7 @@ set -uo pipefail # Shared guards — see benchlib.sh. Each exists because its absence produced a # confident wrong number that was believed for a while. -# shellcheck source=/root/bench/benchlib.sh +# shellcheck source=benchlib.sh . /root/bench/benchlib.sh bench_guard_init diff --git a/benchmarks/run-sec.sh b/benchmarks/run-sec.sh index cb82b90c..6c007691 100755 --- a/benchmarks/run-sec.sh +++ b/benchmarks/run-sec.sh @@ -21,6 +21,7 @@ # published features figure compared a six-thread run against a one-thread run, # which is a comparison of two generators. set -uo pipefail +# shellcheck source=benchlib.sh # the file this loads, as committed . /root/bench/benchlib.sh bench_guard_init diff --git a/benchmarks/run_all.sh b/benchmarks/run_all.sh index 3350c3fb..1386e79d 100755 --- a/benchmarks/run_all.sh +++ b/benchmarks/run_all.sh @@ -9,7 +9,7 @@ # Order matters: the backend ceiling is measured first, because every number # after it is only meaningful if the backend is not the thing being measured. set -uo pipefail -cd /root/bench +cd /root/bench || exit 1 OUT=/root/bench/out STAMP=$(date +%Y%m%d_%H%M%S) RES="$OUT/res-$STAMP" diff --git a/benchmarks/run_matrix60.sh b/benchmarks/run_matrix60.sh index fa8199f0..6379b611 100755 --- a/benchmarks/run_matrix60.sh +++ b/benchmarks/run_matrix60.sh @@ -15,7 +15,7 @@ # passes plus a backend ceiling is most of a working day. That is the price of a # table whose third digit means something. set -uo pipefail -cd /root/bench +cd /root/bench || exit 1 OUT=/root/bench/out STAMP=$(date +%Y%m%d_%H%M%S) RES="$OUT/res-60s-$STAMP" diff --git a/benchmarks/smt.sh b/benchmarks/smt.sh index 0299d2a6..a836402f 100755 --- a/benchmarks/smt.sh +++ b/benchmarks/smt.sh @@ -17,10 +17,10 @@ # Generator moves to 8-11 in both arms so the comparison is fair. set -uo pipefail while fuser /run/lock/pqc-bench.lock >/dev/null 2>&1; do sleep 30; done +# shellcheck source=benchlib.sh # the file this loads, as committed . /root/bench/benchlib.sh bench_guard_init export LD_LIBRARY_PATH=/opt/h3bench/lib -OUT=/root/bench/out/variance GEN=8-11 run_arm() { # $1=cpus $2=label diff --git a/benchmarks/spread-cause.sh b/benchmarks/spread-cause.sh index a7b1f968..68924133 100755 --- a/benchmarks/spread-cause.sh +++ b/benchmarks/spread-cause.sh @@ -15,6 +15,7 @@ # restart : stop and start the proxy before each measurement (what A/B does now) # persist : one instance, N measurements back to back (what run-bench.sh does) set -uo pipefail +# shellcheck source=benchlib.sh # the file this loads, as committed . /root/bench/benchlib.sh bench_guard_init export LD_LIBRARY_PATH=/opt/h3bench/lib diff --git a/benchmarks/spread-confirm.sh b/benchmarks/spread-confirm.sh index e0212ade..343fa49b 100755 --- a/benchmarks/spread-confirm.sh +++ b/benchmarks/spread-confirm.sh @@ -10,6 +10,7 @@ # checked against HAProxy too — a change that improves only our own numbers is # not a fix to the harness, it is a thumb on the scale. set -uo pipefail +# shellcheck source=benchlib.sh # the file this loads, as committed . /root/bench/benchlib.sh bench_guard_init export LD_LIBRARY_PATH=/opt/h3bench/lib @@ -34,12 +35,12 @@ print(' %-10s median %9.0f min %9.0f max %9.0f spread %.2fx cv %.1f%%' bench_stop_proxies bench_spawn_proxy "${BIN:-/root/bench/pqcrypta-proxy}" /root/bench/conf/pqc-bench.toml -p=(); for i in $(seq "$N"); do p+=("$(measure 18444)"); done +p=(); for _ in $(seq "$N"); do p+=("$(measure 18444)"); done bench_stop_proxies report pqcrypta "${p[@]}" setsid taskset -c "$BENCH_PROXY_CPUS" haproxy -f /root/bench/conf/haproxy.cfg -db /dev/null 2>&1 9>&- & sleep 6 -h=(); for i in $(seq "$N"); do h+=("$(measure 18443)"); done +h=(); for _ in $(seq "$N"); do h+=("$(measure 18443)"); done bench_stop_proxies report haproxy "${h[@]}" diff --git a/benchmarks/spread-dur.sh b/benchmarks/spread-dur.sh index 67dda2ab..c766884c 100755 --- a/benchmarks/spread-dur.sh +++ b/benchmarks/spread-dur.sh @@ -11,6 +11,7 @@ # noise. If a longer warm-up and a longer measurement collapse the coefficient of # variation, the rig was simply measuring the transient. set -uo pipefail +# shellcheck source=benchlib.sh # the file this loads, as committed . /root/bench/benchlib.sh bench_guard_init export LD_LIBRARY_PATH=/opt/h3bench/lib @@ -22,7 +23,7 @@ arm() { # $1=duration $2=warmup bench_stop_proxies bench_spawn_proxy /root/bench/pqcrypta-proxy /root/bench/conf/pqc-bench.toml local vals=() - for i in $(seq "$N"); do + for _ in $(seq "$N"); do vals+=("$(taskset -c "$BENCH_GEN_CPUS" timeout $(( $1 + $2 + 40 )) "$H2LOAD" --h1 \ -c 10 -m 1 -t 6 --duration="$1" --warm-up-time="$2" \ "https://bench.local:18444/$BODY" 2>/dev/null | awk '/^finished in/ {print $4}')") diff --git a/benchmarks/spread-workers.sh b/benchmarks/spread-workers.sh index dbcb34c2..cf36e15a 100755 --- a/benchmarks/spread-workers.sh +++ b/benchmarks/spread-workers.sh @@ -14,6 +14,7 @@ # Throughput will drop with one worker. That is not the point — the point is the # coefficient of variation. set -uo pipefail +# shellcheck source=benchlib.sh # the file this loads, as committed . /root/bench/benchlib.sh bench_guard_init export LD_LIBRARY_PATH=/opt/h3bench/lib @@ -30,11 +31,11 @@ measure() { arm() { # $1=workers $2=cpus sed -e "s/^worker_threads = .*/worker_threads = $1/" /root/bench/conf/pqc-bench.toml \ - > /root/bench/conf/pqc-w$1.toml + > "/root/bench/conf/pqc-w$1.toml" bench_stop_proxies - BENCH_PROXY_CPUS="$2" bench_spawn_proxy /root/bench/pqcrypta-proxy /root/bench/conf/pqc-w$1.toml + BENCH_PROXY_CPUS="$2" bench_spawn_proxy /root/bench/pqcrypta-proxy "/root/bench/conf/pqc-w$1.toml" local vals=() - for i in $(seq "$N"); do vals+=("$(measure)"); done + for _ in $(seq "$N"); do vals+=("$(measure)"); done bench_stop_proxies python3 -c " import sys, statistics diff --git a/benchmarks/stalls.sh b/benchmarks/stalls.sh index 24b14d78..a7cc9280 100755 --- a/benchmarks/stalls.sh +++ b/benchmarks/stalls.sh @@ -11,6 +11,7 @@ # not own, which on a VM means another tenant set -uo pipefail while fuser /run/lock/pqc-bench.lock >/dev/null 2>&1; do sleep 30; done +# shellcheck source=benchlib.sh # the file this loads, as committed . /root/bench/benchlib.sh bench_guard_init export LD_LIBRARY_PATH=/opt/h3bench/lib diff --git a/benchmarks/steal.sh b/benchmarks/steal.sh index 0cd2d3a4..932a18d5 100755 --- a/benchmarks/steal.sh +++ b/benchmarks/steal.sh @@ -14,6 +14,7 @@ # pinned CPUs. set -uo pipefail while fuser /run/lock/pqc-bench.lock >/dev/null 2>&1; do sleep 30; done +# shellcheck source=benchlib.sh # the file this loads, as committed . /root/bench/benchlib.sh bench_guard_init export LD_LIBRARY_PATH=/opt/h3bench/lib diff --git a/benchmarks/tail-h1.sh b/benchmarks/tail-h1.sh index 956148af..45ce1634 100755 --- a/benchmarks/tail-h1.sh +++ b/benchmarks/tail-h1.sh @@ -6,6 +6,7 @@ # The HTTP/1.1 64 KB request-time tail on both proxies: h2load min/max/mean/sd. set -uo pipefail +# shellcheck source=benchlib.sh # the file this loads, as committed . /root/bench/benchlib.sh bench_guard_init export LD_LIBRARY_PATH=/opt/h3bench/lib diff --git a/benchmarks/window-study.sh b/benchmarks/window-study.sh index cd1d2f4c..d988ef50 100755 --- a/benchmarks/window-study.sh +++ b/benchmarks/window-study.sh @@ -9,6 +9,7 @@ # like-for-like arm, at 10 s / 2 s and at 60 s / 15 s. A short window that # flatters one proxy more than the other is a comparison of warm-up behaviour. set -uo pipefail +# shellcheck source=benchlib.sh # the file this loads, as committed . /root/bench/benchlib.sh bench_guard_init export LD_LIBRARY_PATH=/opt/h3bench/lib diff --git a/docs/CONFIG.md b/docs/CONFIG.md index a405608f..abd841b3 100644 --- a/docs/CONFIG.md +++ b/docs/CONFIG.md @@ -780,6 +780,8 @@ ML-inspired anomaly detection that learns normal traffic patterns. | `error_rate_threshold` | f64 | `0.7` | Error rate threshold (70%) to trigger suspicious | | `error_window_secs` | u64 | `60` | Error tracking sliding window (1 minute) | | `blocklist_dir` | path | `"/var/lib/pqcrypta-proxy/blocklists"` | Where a database sync writes `blocked_ips.json` (a JSON array of `{"ip", "expires_at"}`, an address or a CIDR, `expires_at` RFC 3339 or null); read every minute | +| `crawler_published_ranges` | bool | `true` | Verify crawlers against the address ranges their operators publish (Google, Bing, DuckDuckGo, Apple, OpenAI, Perplexity, Common Crawl, Ahrefs), fetched every six hours; off, by reverse DNS alone, which cannot verify DuckDuckBot | +| `crawler_ranges_cache` | path | `"/var/lib/pqcrypta-proxy/state/crawler-ranges.json"` | Where the published ranges are cached between refreshes and restarts, in a directory the proxy's account writes; `scripts/detect_bots_from_logs.sh` reads the default path | | `blocklist_files` | array[path] | `[]` | Further lists in the same format, read with `blocked_ips.json`: another source's, such as a fleet's shared bans. The proxy holds their union; an entry first named this round takes its list's expiry, one named by two lists the later; a ban no list names any more is released; a list that exists but does not read or parse releases nothing that round; a missing list names nothing | | `pentest_bypass_ips` | array[string] | `[]` | Authorised test sources: inspected by the WAF but never rate-limited or auto-banned. An entry is an address or a host name standing for the addresses it resolves to | | `host_resolver` | socket address? | `null` | A validating resolver, reached over TCP, for the host names in `pentest_bypass_ips`. Only an answer it authenticates (AD bit) counts, refreshed every minute; without one, a name matches nothing | @@ -798,6 +800,15 @@ A page load (a navigation, or a GET that accepts HTML) from an address a heurist | `max_number` | u64 | `100000` | The challenge's range; a browser computes on average half this many SHA-256 digests | | `pass_ttl_secs` | u64 | `3600` | How long a pass lets its browser through | | `secret` | string? | `null` | The key challenges and passes are signed with, shared by nodes that honour each other's passes (at least 32 characters). Unset: the process's own, so passes lapse on restart | +| `translations` | table | `{}` | The interstitial in other languages, one table per BCP 47 language tag; each message it leaves out is English's. The browser's `Accept-Language` chooses by weight and order (a region takes its language, a language its region's), English when it asks for none of them; the page carries the language in `lang` and `dir`, and the response `Vary: Accept-Language`. Keys: `dir` (`ltr` or `rtl`), `title`, `explanation`, `working`, `progress` (`{percent}`), `done` (`{seconds}`), `no_script`, `could_not_start`, `did_not_finish`, `could_not_run`; each at most 1000 bytes. Ready translations, and the English template, are in [challenge-translations/](challenge-translations/) | + +```toml +[security.challenge.translations.de] +title = "Ihr Browser wird geprüft" +explanation = "Der Datenverkehr aus Ihrem Netz wirkte automatisiert, daher bittet diese Seite Ihren Browser um etwa eine Sekunde Rechenarbeit, bevor es weitergeht. Nichts wird installiert oder gespeichert." +progress = "Wird geprüft… {percent} %" +done = "Fertig nach {seconds} s. Weiter…" +``` --- diff --git a/docs/challenge-translations/README.md b/docs/challenge-translations/README.md new file mode 100644 index 00000000..42429063 --- /dev/null +++ b/docs/challenge-translations/README.md @@ -0,0 +1,20 @@ +# Challenge page translations + +The page a browser sees when the proxy asks it for a proof of work +(`[security.challenge]`) is shown in the language its `Accept-Language` +asks for, from the translations an operator configures +(`security.challenge.translations`, [CONFIG.md](../CONFIG.md)). This +directory holds translations anyone can use: [en.toml](en.toml) is the +English text and the template. + +To add a language: + +1. Copy `en.toml` to `.toml`, named by the language's BCP 47 tag + (`de`, `fr`, `pt-BR`, `zh-Hant`). +2. Translate each value. Keep `{percent}` and `{seconds}` as they are, and + set `dir = "rtl"` for a language written right to left. +3. Open a pull request. A reviewer who reads the language is asked to check + it before it merges. + +Each value is at most 1000 bytes, which the proxy checks when it loads a +configuration. diff --git a/docs/challenge-translations/en.toml b/docs/challenge-translations/en.toml new file mode 100644 index 00000000..c537c425 --- /dev/null +++ b/docs/challenge-translations/en.toml @@ -0,0 +1,20 @@ +# SPDX-FileCopyrightText: 2025-2026 PQCrypta +# +# SPDX-License-Identifier: MIT OR Apache-2.0 + +# The challenge interstitial's English text, the template for a translation: +# copy it to .toml (a BCP 47 tag: de, fr, pt-BR, zh-Hant), translate +# each value, and keep {percent} and {seconds} as they are. An operator copies +# a file's keys into the proxy's configuration under +# [security.challenge.translations.]; a key left out is the English one. + +dir = "ltr" +title = "Checking your browser" +explanation = "Traffic from your network looked automated, so this site asks your browser for about a second of work before it continues. Nothing is installed or kept." +working = "Working…" +progress = "Working… {percent}%" +done = "Done in {seconds} s. Continuing…" +no_script = "This check needs JavaScript. Turn it on and reload the page." +could_not_start = "The check could not start. Reload the page to try again." +did_not_finish = "The check did not finish. Reload the page to try again." +could_not_run = "The check could not run in this browser. Reload the page to try again." diff --git a/docs/config-defaults.json b/docs/config-defaults.json index 4cbdb3d5..50846770 100644 --- a/docs/config-defaults.json +++ b/docs/config-defaults.json @@ -414,10 +414,12 @@ "enabled": false, "max_number": 100000, "pass_ttl_secs": 3600, - "secret": null + "secret": null, + "translations": {} }, "connection_timeout_secs": 30, "crawler_published_ranges": true, + "crawler_ranges_cache": "/var/lib/pqcrypta-proxy/state/crawler-ranges.json", "dos_protection": true, "error_4xx_threshold": 100, "error_pages_path_prefix": "", diff --git a/pentests/config.demo.sh b/pentests/config.demo.sh index d1c06f50..a044928d 100644 --- a/pentests/config.demo.sh +++ b/pentests/config.demo.sh @@ -140,10 +140,6 @@ TIMING_SAMPLES="${TIMING_SAMPLES:-50}" # Replace with a realistic current browser string for your target region. BROWSER_UA="${BROWSER_UA:-Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36}" -# Pre-built curl invocation with browser UA and silent flags. -# Used by scripts that perform web-application-level checks. -CURL_BROWSER="curl -sk -A '$BROWSER_UA'" - # Maximum response body size to read (bytes) — prevents hanging on large responses. MAX_BODY_BYTES="${MAX_BODY_BYTES:-102400}" # 100 KB diff --git a/pentests/run_all.sh b/pentests/run_all.sh index 8cf8ba92..5c3560b6 100755 --- a/pentests/run_all.sh +++ b/pentests/run_all.sh @@ -15,6 +15,7 @@ # bash run_all.sh --phase 2 # run only phase 2 SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +# shellcheck source=config.demo.sh # the file this loads, as committed source "$SCRIPT_DIR/config.sh" LOCAL_MODE=0 @@ -59,10 +60,6 @@ printf 'phase\tscript\tname\tstatus\tfindings\twarns\tduration_s\n' > "$TSV" # ── counters ────────────────────────────────────────────────────────────────── TOTAL=0; N_PASS=0; N_WARN=0; N_FAIL=0; N_ERROR=0 -declare -A SCRIPT_STATUS -declare -A SCRIPT_FINDINGS -declare -A SCRIPT_WARNS -declare -A SCRIPT_DURATION printf '═%.0s' $(seq 1 60) | tee "$REPORT"; echo "" | tee -a "$REPORT" echo " PQCrypta Pentest Suite — $(date)" | tee -a "$REPORT" @@ -125,11 +122,6 @@ run_test() { N_PASS=$((N_PASS+1)) fi - SCRIPT_STATUS["$name"]="$status" - SCRIPT_FINDINGS["$name"]="$findings" - SCRIPT_WARNS["$name"]="$warns" - SCRIPT_DURATION["$name"]="$elapsed" - printf '└─ [%-5s] findings=%-2s warns=%-2s time=%ds\n' \ "$status" "$findings" "$warns" "$elapsed" | tee -a "$REPORT" echo "" | tee -a "$REPORT" diff --git a/pentests/scope_guard.sh b/pentests/scope_guard.sh index 65ec0088..d501dc62 100755 --- a/pentests/scope_guard.sh +++ b/pentests/scope_guard.sh @@ -8,6 +8,7 @@ # Blocks accidental runs against non-whitelisted targets. SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +# shellcheck source=config.demo.sh # the file this loads, as committed source "$SCRIPT_DIR/config.sh" # ALLOWED_TARGETS defaults to TARGET + API_TARGET from config.sh. diff --git a/pentests/scripts/01_waf_bypass.sh b/pentests/scripts/01_waf_bypass.sh index a1e3f6cd..255ecd19 100755 --- a/pentests/scripts/01_waf_bypass.sh +++ b/pentests/scripts/01_waf_bypass.sh @@ -6,6 +6,7 @@ # WAF bypass probe - tests common evasion techniques against pqcrypta-proxy SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +# shellcheck source=../config.demo.sh # the file this loads, as committed source "$SCRIPT_DIR/../config.sh" OUT="$OUT/waf_bypass" mkdir -p "$OUT" @@ -71,8 +72,8 @@ done CMD_PAYLOADS=( '; cat /etc/passwd' '| whoami' - '`id`' - '$(id)' + $'`id`' + $'$(id)' '; ls -la /' ) diff --git a/pentests/scripts/02_bot_detection.sh b/pentests/scripts/02_bot_detection.sh index 7a3db73a..620e3c52 100755 --- a/pentests/scripts/02_bot_detection.sh +++ b/pentests/scripts/02_bot_detection.sh @@ -6,6 +6,7 @@ # Bot detection bypass - tests whether fake UAs, headless markers, missing headers slip through SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +# shellcheck source=../config.demo.sh # the file this loads, as committed source "$SCRIPT_DIR/../config.sh" OUT="$OUT/bot_detection" mkdir -p "$OUT" diff --git a/pentests/scripts/03_header_injection.sh b/pentests/scripts/03_header_injection.sh index 480ae09e..50a5393b 100755 --- a/pentests/scripts/03_header_injection.sh +++ b/pentests/scripts/03_header_injection.sh @@ -6,6 +6,7 @@ # Header injection / smuggling / spoofing tests SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +# shellcheck source=../config.demo.sh # the file this loads, as committed source "$SCRIPT_DIR/../config.sh" OUT="$OUT/headers" mkdir -p "$OUT" diff --git a/pentests/scripts/04_rate_limit.sh b/pentests/scripts/04_rate_limit.sh index 2df82bdd..c12097b4 100755 --- a/pentests/scripts/04_rate_limit.sh +++ b/pentests/scripts/04_rate_limit.sh @@ -6,6 +6,7 @@ # Rate limiting test - burst requests to trigger throttle SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +# shellcheck source=../config.demo.sh # the file this loads, as committed source "$SCRIPT_DIR/../config.sh" OUT="$OUT/rate_limit" mkdir -p "$OUT" @@ -14,7 +15,7 @@ echo '=== RATE LIMITING TESTS ===' | tee "$OUT/summary.txt" echo 'Sending 40 rapid requests to / ...' | tee -a "$OUT/summary.txt" declare -A counts -for i in $(seq 1 40); do +for _ in $(seq 1 40); do code=$(curl -sk -o /dev/null -w '%{http_code}' --max-time 5 "$TARGET/") counts[$code]=$(( ${counts[$code]:-0} + 1 )) done @@ -26,7 +27,7 @@ done echo '' | tee -a "$OUT/summary.txt" echo 'Sending 20 rapid POST to API /encrypt ...' | tee -a "$OUT/summary.txt" declare -A acounts -for i in $(seq 1 20); do +for _ in $(seq 1 20); do code=$(curl -sk -o /dev/null -w '%{http_code}' --max-time 5 -X POST -H 'Content-Type: application/json' -d '{"data":"test","algorithm":"classical"}' "$API_TARGET/encrypt") acounts[$code]=$(( ${acounts[$code]:-0} + 1 )) done diff --git a/pentests/scripts/05_api_auth.sh b/pentests/scripts/05_api_auth.sh index e56650d3..aaa2e6ee 100755 --- a/pentests/scripts/05_api_auth.sh +++ b/pentests/scripts/05_api_auth.sh @@ -6,6 +6,7 @@ # API authentication & authorization tests SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +# shellcheck source=../config.demo.sh # the file this loads, as committed source "$SCRIPT_DIR/../config.sh" OUT="$OUT/api_auth" mkdir -p "$OUT" diff --git a/pentests/scripts/06_tls_ssl.sh b/pentests/scripts/06_tls_ssl.sh index ecf43281..96d22089 100755 --- a/pentests/scripts/06_tls_ssl.sh +++ b/pentests/scripts/06_tls_ssl.sh @@ -6,20 +6,34 @@ # TLS/SSL configuration tests SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +# shellcheck source=../config.demo.sh # the file this loads, as committed source "$SCRIPT_DIR/../config.sh" OUT="$OUT/tls" mkdir -p "$OUT" echo '=== TLS/SSL TESTS ===' | tee "$OUT/summary.txt" -# Old TLS versions — 1.0/1.1 should be rejected at handshake (000 = EXPECTED/PASS) +# Old TLS versions: the client offers TLS 1.0 or 1.1 and nothing newer +# (--tlsv1.x is the floor, --tls-max the ceiling; at OpenSSL's default +# security level a client will not offer them at all, hence SECLEVEL=0). A +# server that refuses them answers with a protocol_version alert; one that +# accepts them answers HTTP. A client that could not offer them says so, and +# that is not a result about the server. echo '--- Old TLS Versions ---' | tee -a "$OUT/summary.txt" -for ver in '--tls-max 1.0' '--tls-max 1.1'; do - resp=$(curl -sk -o /dev/null -w '%{http_code}' --max-time 10 $ver "$TARGET/" 2>&1) - echo "[${resp}] TLS: $ver (EXPECTED 000 — server rejects TLS<1.2 at handshake)" | tee -a "$OUT/summary.txt" +for v in 1.0 1.1; do + out=$(curl -sS -k -o /dev/null -w '%{http_code}' --max-time 10 \ + "--tlsv$v" --tls-max "$v" --ciphers 'DEFAULT:@SECLEVEL=0' "$TARGET/" 2>&1) + rc=$? + if [ "$rc" -eq 0 ]; then + echo " [VULN] TLS $v accepted (HTTP ${out: -3})" + elif grep -qiE 'protocol version|alert' <<<"$out"; then + echo " [PASS] TLS $v refused by the server: $(head -1 <<<"$out")" + else + echo " [INFO] TLS $v not offered by this client (curl exit $rc): $(head -1 <<<"$out")" + fi | tee -a "$OUT/summary.txt" done for ver in '--tlsv1.2' '--tlsv1.3'; do - resp=$(curl -sk -o /dev/null -w '%{http_code}' --max-time 10 $ver "$TARGET/" 2>&1) + resp=$(curl -sk -o /dev/null -w '%{http_code}' --max-time 10 "$ver" "$TARGET/" 2>&1) echo "[$resp] TLS: $ver" | tee -a "$OUT/summary.txt" done diff --git a/pentests/scripts/07_advanced_smuggling.sh b/pentests/scripts/07_advanced_smuggling.sh index aa7c5592..eadb5449 100755 --- a/pentests/scripts/07_advanced_smuggling.sh +++ b/pentests/scripts/07_advanced_smuggling.sh @@ -9,6 +9,7 @@ # CL.TE / TE.CL / TE.TE obfuscation — proxy-specific immunity documented per RFC SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +# shellcheck source=../config.demo.sh # the file this loads, as committed source "$SCRIPT_DIR/../config.sh" OUT_FILE="$OUT/07_advanced_smuggling.txt" echo "=== 07. HTTP Request Smuggling ===" | tee "$OUT_FILE" @@ -139,7 +140,7 @@ echo "--- HTTP/2 Continuation Flood (CVE-2023-44487 / Rapid Reset variant) ---" # Send 20 rapid requests with RESET to probe for rapid-reset DoS surface # (benign probe — just measures if server handles rapid reconnects without crash) RESET_CODES="" -for i in $(seq 1 10); do +for _ in $(seq 1 10); do C=$(curl -sk --http2 -o /dev/null -w '%{http_code}' --max-time 3 "$TARGET/" 2>/dev/null) RESET_CODES="$RESET_CODES $C" done diff --git a/pentests/scripts/08_ssrf.sh b/pentests/scripts/08_ssrf.sh index 20af0e41..631bfa6c 100755 --- a/pentests/scripts/08_ssrf.sh +++ b/pentests/scripts/08_ssrf.sh @@ -6,6 +6,7 @@ # SSRF - test if proxy can be weaponized to hit internal services SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +# shellcheck source=../config.demo.sh # the file this loads, as committed source "$SCRIPT_DIR/../config.sh" OUT="$OUT/ssrf" mkdir -p "$OUT" diff --git a/pentests/scripts/09_cache_poison.sh b/pentests/scripts/09_cache_poison.sh index d900e637..d6ef33a6 100755 --- a/pentests/scripts/09_cache_poison.sh +++ b/pentests/scripts/09_cache_poison.sh @@ -6,6 +6,7 @@ # Web cache poisoning + cache deception SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +# shellcheck source=../config.demo.sh # the file this loads, as committed source "$SCRIPT_DIR/../config.sh" OUT="$OUT/cache_poison" mkdir -p "$OUT" diff --git a/pentests/scripts/10_crypto_api_fuzz.sh b/pentests/scripts/10_crypto_api_fuzz.sh index ae0347ff..fb783d60 100755 --- a/pentests/scripts/10_crypto_api_fuzz.sh +++ b/pentests/scripts/10_crypto_api_fuzz.sh @@ -6,14 +6,13 @@ # Cryptographic API fuzzing - malformed inputs, boundary conditions, type confusion SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +# shellcheck source=../config.demo.sh # the file this loads, as committed source "$SCRIPT_DIR/../config.sh" OUT="$OUT/crypto_fuzz" mkdir -p "$OUT" echo '=== CRYPTO API FUZZING ===' | tee "$OUT/summary.txt" -ALGOS=('classical' 'hybrid' 'post-quantum' 'ml-kem-1024' 'hqc-256' 'quad-layer') - # Malformed JSON echo '--- Malformed JSON ---' | tee -a "$OUT/summary.txt" MALFORMED=( @@ -40,7 +39,7 @@ echo '--- Algorithm Injection ---' | tee -a "$OUT/summary.txt" ALG_PAYLOADS=( '../../../etc/passwd' '; cat /etc/passwd' - '$(id)' + $'$(id)' 'classical; DROP TABLE keys' 'none' 'null' diff --git a/pentests/scripts/11_timing_oracle.sh b/pentests/scripts/11_timing_oracle.sh index 0b1f3d24..a324db91 100755 --- a/pentests/scripts/11_timing_oracle.sh +++ b/pentests/scripts/11_timing_oracle.sh @@ -5,10 +5,12 @@ # SPDX-License-Identifier: MIT OR Apache-2.0 # 11 - Timing Oracle Tests -# Methodology: 30-sample mean + stddev per group; signal is real if |diff| > 3*stddev +# Methodology: 50-sample mean + stddev per group, timed by curl itself; +# signal is real if |diff| > 3*stddev # Covers HTTP/1.1, HTTP/2, constant-time auth, padding oracle SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +# shellcheck source=../config.demo.sh # the file this loads, as committed source "$SCRIPT_DIR/../config.sh" OUT_FILE="$OUT/11_timing_oracle.txt" @@ -16,71 +18,78 @@ OUT_FILE="$OUT/11_timing_oracle.txt" # Remote internet jitter is ~20-50ms; local jitter is ~1-5ms # Default threshold = 3σ with min 15ms floor # --local threshold = 3σ with min 3ms floor (catches subtle constant-time violations) +echo "=== 11. Timing Oracle Tests ===" | tee "$OUT_FILE" LOCAL_MODE="${LOCAL_MODE:-0}" +# The floors and sample count config.sh sets (TIMING_FLOOR_LOCAL, +# TIMING_FLOOR_REMOTE, TIMING_SAMPLES); the floor is read by compare_groups' +# Python, so exported if [ "$LOCAL_MODE" = "1" ]; then - TIMING_FLOOR=3 - echo "Mode: LOCAL — timing floor 3ms (tight, for same-datacenter runs)" | tee -a "$OUT_FILE" + export TIMING_FLOOR="${TIMING_FLOOR_LOCAL:-3}" + echo "Mode: LOCAL — timing floor ${TIMING_FLOOR}ms (tight, for same-datacenter runs)" | tee -a "$OUT_FILE" else - TIMING_FLOOR=15 - echo "Mode: REMOTE — timing floor 15ms (guards against internet jitter)" | tee -a "$OUT_FILE" + export TIMING_FLOOR="${TIMING_FLOOR_REMOTE:-15}" + echo "Mode: REMOTE — timing floor ${TIMING_FLOOR}ms (guards against internet jitter)" | tee -a "$OUT_FILE" fi -echo "=== 11. Timing Oracle Tests ===" | tee "$OUT_FILE" -echo "Methodology: 50 samples per group, mean ± stddev, signal threshold = 3σ" | tee -a "$OUT_FILE" +SAMPLES="${TIMING_SAMPLES:-50}" +echo "Methodology: $SAMPLES samples per group, timed by curl, mean ± stddev, signal threshold = 3σ" | tee -a "$OUT_FILE" echo "" | tee -a "$OUT_FILE" # ── timing harness ──────────────────────────────────────────────────────────── # Returns space-separated list of ms timings sample_times() { local n="$1"; shift - local times="" - for i in $(seq 1 "$n"); do - T=$(python3 -c "import time; print(int(time.time()*1000))") - curl -sk -o /dev/null --max-time 15 "$@" 2>/dev/null - E=$(python3 -c "import time; print(int(time.time()*1000))") - times="$times $((E - T))" + local times="" t + for _ in $(seq 1 "$n"); do + # curl's own clock, from the start of the request to its last byte: no + # process start-up in the measurement + t=$(curl -sk -o /dev/null -w '%{time_total}' --max-time 15 "$@" 2>/dev/null) || continue + times="$times $(awk -v s="$t" 'BEGIN { printf "%.3f", s * 1000 }')" done echo "$times" } # Compute mean and stddev from space-separated ms list stats() { - python3 -c " -import sys, math, statistics -vals = [int(x) for x in sys.stdin.read().split() if x] -if not vals: print('N=0 mean=0 stddev=0'); sys.exit() + # The program is the heredoc, so the timings come in as an argument + local data; data=$(cat) + python3 - "$data" <<'PY' +import statistics, sys +vals = [float(x) for x in sys.argv[1].split() if x] +if not vals: + print('N=0 mean=0 stddev=0') + sys.exit() m = statistics.mean(vals) s = statistics.pstdev(vals) if len(vals) > 1 else 0 -print(f'N={len(vals)} mean={m:.1f}ms stddev={s:.1f}ms min={min(vals)}ms max={max(vals)}ms') -" +print(f'N={len(vals)} mean={m:.1f}ms stddev={s:.1f}ms min={min(vals):.1f}ms max={max(vals):.1f}ms') +PY } compare_groups() { # compare_groups "label_a" times_a "label_b" times_b - local la="$1" ta="$2" lb="$3" tb="$4" - python3 -c " -import sys, math, statistics -la,ta,lb,tb = sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4] -a = [int(x) for x in ta.split() if x] -b = [int(x) for x in tb.split() if x] -if not a or not b: print(' [SKIP] insufficient data'); sys.exit() + python3 - "$1" "$2" "$3" "$4" <<'PY' +import os, statistics, sys +la, ta, lb, tb = sys.argv[1:5] +a = [float(x) for x in ta.split() if x] +b = [float(x) for x in tb.split() if x] +if not a or not b: + print(' [SKIP] insufficient data') + sys.exit() ma, mb = statistics.mean(a), statistics.mean(b) -sa = statistics.pstdev(a) if len(a)>1 else 1 -sb = statistics.pstdev(b) if len(b)>1 else 1 +sa = statistics.pstdev(a) if len(a) > 1 else 1 +sb = statistics.pstdev(b) if len(b) > 1 else 1 diff = abs(ma - mb) -import os - floor = int(os.environ.get("TIMING_FLOOR", "15")) - threshold = 3 * max(sa, sb, floor) +floor = float(os.environ.get('TIMING_FLOOR', '15')) +threshold = 3 * max(sa, sb, floor) verdict = 'TIMING-LEAK' if diff > threshold else 'OK' print(f' [{verdict}] {la}: {ma:.1f}ms±{sa:.1f} vs {lb}: {mb:.1f}ms±{sb:.1f} diff={diff:.1f}ms threshold={threshold:.1f}ms') -" "$la" "$ta" "$lb" "$tb" +PY } -SAMPLES=50 # ── 1. API Key Timing Oracle ────────────────────────────────────────────────── echo "--- API Key Timing Oracle (HTTP/2, $SAMPLES samples each) ---" | tee -a "$OUT_FILE" echo " Sampling invalid key..." | tee -a "$OUT_FILE" -T_INVALID=$(sample_times $SAMPLES \ +T_INVALID=$(sample_times "$SAMPLES" \ -X POST --http2 \ -H 'Authorization: Bearer INVALID_KEY_XXXXXXXXXXX' \ -H 'Content-Type: application/json' \ @@ -89,7 +98,7 @@ T_INVALID=$(sample_times $SAMPLES \ echo " Invalid key: $(echo "$T_INVALID" | stats)" | tee -a "$OUT_FILE" echo " Sampling no-key (missing header)..." | tee -a "$OUT_FILE" -T_NOKEY=$(sample_times $SAMPLES \ +T_NOKEY=$(sample_times "$SAMPLES" \ -X POST --http2 \ -H 'Content-Type: application/json' \ -d '{"data":"test","algorithm":"classical"}' \ @@ -97,7 +106,7 @@ T_NOKEY=$(sample_times $SAMPLES \ echo " No key: $(echo "$T_NOKEY" | stats)" | tee -a "$OUT_FILE" echo " Sampling malformed key (wrong prefix)..." | tee -a "$OUT_FILE" -T_MALFORMED=$(sample_times $SAMPLES \ +T_MALFORMED=$(sample_times "$SAMPLES" \ -X POST --http2 \ -H 'Authorization: Basic INVALID_BASE64==' \ -H 'Content-Type: application/json' \ @@ -112,7 +121,7 @@ echo "" | tee -a "$OUT_FILE" # ── 2. Admin Login Username Enumeration ─────────────────────────────────────── echo "--- Admin Login Timing Oracle ($SAMPLES samples each) ---" | tee -a "$OUT_FILE" echo " Sampling likely-valid username 'admin'..." | tee -a "$OUT_FILE" -T_ADMIN=$(sample_times $SAMPLES \ +T_ADMIN=$(sample_times "$SAMPLES" \ -X POST --http2 \ -H 'Content-Type: application/x-www-form-urlencoded' \ -d 'username=admin&password=wrongpassword_xyz_pentest' \ @@ -120,7 +129,7 @@ T_ADMIN=$(sample_times $SAMPLES \ echo " 'admin': $(echo "$T_ADMIN" | stats)" | tee -a "$OUT_FILE" echo " Sampling nonexistent username..." | tee -a "$OUT_FILE" -T_NOUSER=$(sample_times $SAMPLES \ +T_NOUSER=$(sample_times "$SAMPLES" \ -X POST --http2 \ -H 'Content-Type: application/x-www-form-urlencoded' \ -d 'username=nonexistent_user_xyz_1234&password=wrongpassword_xyz_pentest' \ @@ -136,7 +145,7 @@ SHORT_B64="aGVsbG8=" # "hello" — too short, invalid ciphertext LONG_B64=$(python3 -c "import base64; print(base64.b64encode(b'X'*512).decode())") echo " Sampling short invalid ciphertext..." | tee -a "$OUT_FILE" -T_SHORT=$(sample_times $SAMPLES \ +T_SHORT=$(sample_times "$SAMPLES" \ -X POST --http2 \ -H 'Content-Type: application/json' \ -d "{\"data\":\"$SHORT_B64\",\"algorithm\":\"classical\"}" \ @@ -144,7 +153,7 @@ T_SHORT=$(sample_times $SAMPLES \ echo " Short (8b): $(echo "$T_SHORT" | stats)" | tee -a "$OUT_FILE" echo " Sampling long invalid ciphertext..." | tee -a "$OUT_FILE" -T_LONG=$(sample_times $SAMPLES \ +T_LONG=$(sample_times "$SAMPLES" \ -X POST --http2 \ -H 'Content-Type: application/json' \ -d "{\"data\":\"$LONG_B64\",\"algorithm\":\"classical\"}" \ @@ -157,11 +166,11 @@ echo "" | tee -a "$OUT_FILE" # ── 4. HTTP/1.1 vs HTTP/2 Timing Baseline ──────────────────────────────────── echo "--- Protocol Timing Baseline (HTTP/1.1 vs HTTP/2, $SAMPLES samples) ---" | tee -a "$OUT_FILE" echo " HTTP/1.1..." | tee -a "$OUT_FILE" -T_H1=$(sample_times $SAMPLES --http1.1 "$TARGET/") +T_H1=$(sample_times "$SAMPLES" --http1.1 "$TARGET/") echo " HTTP/1.1: $(echo "$T_H1" | stats)" | tee -a "$OUT_FILE" echo " HTTP/2..." | tee -a "$OUT_FILE" -T_H2=$(sample_times $SAMPLES --http2 "$TARGET/") +T_H2=$(sample_times "$SAMPLES" --http2 "$TARGET/") echo " HTTP/2: $(echo "$T_H2" | stats)" | tee -a "$OUT_FILE" compare_groups "HTTP/1.1" "$T_H1" "HTTP/2" "$T_H2" | tee -a "$OUT_FILE" @@ -170,11 +179,11 @@ echo "" | tee -a "$OUT_FILE" # ── 5. WAF Timing — blocked vs clean ───────────────────────────────────────── echo "--- WAF Timing Oracle (blocked vs clean, $SAMPLES samples) ---" | tee -a "$OUT_FILE" echo " Clean request..." | tee -a "$OUT_FILE" -T_CLEAN=$(sample_times $SAMPLES --http2 -A "$BROWSER_UA" "$TARGET/") +T_CLEAN=$(sample_times "$SAMPLES" --http2 -A "$BROWSER_UA" "$TARGET/") echo " Clean: $(echo "$T_CLEAN" | stats)" | tee -a "$OUT_FILE" echo " Blocked (SQLi) request..." | tee -a "$OUT_FILE" -T_BLOCKED=$(sample_times $SAMPLES --http2 -A "$BROWSER_UA" \ +T_BLOCKED=$(sample_times "$SAMPLES" --http2 -A "$BROWSER_UA" \ "$TARGET/?q=$(python3 -c "import urllib.parse; print(urllib.parse.quote(\"' OR 1=1--\"))")") echo " Blocked: $(echo "$T_BLOCKED" | stats)" | tee -a "$OUT_FILE" diff --git a/pentests/scripts/12_waf_evasion_advanced.sh b/pentests/scripts/12_waf_evasion_advanced.sh index f298acfb..083c97ea 100755 --- a/pentests/scripts/12_waf_evasion_advanced.sh +++ b/pentests/scripts/12_waf_evasion_advanced.sh @@ -6,6 +6,7 @@ # Advanced WAF evasion - encoding tricks, chunked bypass, unicode normalization SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +# shellcheck source=../config.demo.sh # the file this loads, as committed source "$SCRIPT_DIR/../config.sh" OUT="$OUT/waf_advanced" mkdir -p "$OUT" diff --git a/pentests/scripts/13_websocket.sh b/pentests/scripts/13_websocket.sh index d617b30a..6b67f522 100755 --- a/pentests/scripts/13_websocket.sh +++ b/pentests/scripts/13_websocket.sh @@ -6,6 +6,7 @@ # WebSocket/WebTransport security tests SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +# shellcheck source=../config.demo.sh # the file this loads, as committed source "$SCRIPT_DIR/../config.sh" OUT="$OUT/websocket" mkdir -p "$OUT" diff --git a/pentests/scripts/14_recon.sh b/pentests/scripts/14_recon.sh index 83f4669d..84adaa56 100755 --- a/pentests/scripts/14_recon.sh +++ b/pentests/scripts/14_recon.sh @@ -6,6 +6,7 @@ # Reconnaissance - fingerprinting, info disclosure, directory enumeration SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +# shellcheck source=../config.demo.sh # the file this loads, as committed source "$SCRIPT_DIR/../config.sh" OUT="$OUT/recon" mkdir -p "$OUT" diff --git a/pentests/scripts/15_auth_session.sh b/pentests/scripts/15_auth_session.sh index 2a1c4539..9d415fd5 100755 --- a/pentests/scripts/15_auth_session.sh +++ b/pentests/scripts/15_auth_session.sh @@ -6,6 +6,7 @@ # Red-team: Auth/session security — session fixation, token replay, brute force, MFA bypass SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +# shellcheck source=../config.demo.sh # the file this loads, as committed source "$SCRIPT_DIR/../config.sh" OUT="$OUT/auth_session" mkdir -p "$OUT" @@ -41,7 +42,7 @@ WRONG_PASS='pentest_wrong_pass_xyz!' sample_login_time() { local user="$1" local times="" - for i in $(seq 1 "$TIMING_N"); do + for _ in $(seq 1 "$TIMING_N"); do T=$(python3 -c "import time; print(int(time.time()*1000))") curl -sk -o /dev/null --max-time 15 \ -X POST -H 'Content-Type: application/x-www-form-urlencoded' \ diff --git a/pentests/scripts/16_business_logic.sh b/pentests/scripts/16_business_logic.sh index a71e5db8..bfacd903 100755 --- a/pentests/scripts/16_business_logic.sh +++ b/pentests/scripts/16_business_logic.sh @@ -9,6 +9,7 @@ # HTTP/1.1, HTTP/2, and HTTP/3 protocol variants included SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +# shellcheck source=../config.demo.sh # the file this loads, as committed source "$SCRIPT_DIR/../config.sh" OUT_FILE="$OUT/16_business_logic.txt" echo "=== 16. Business Logic ===" | tee "$OUT_FILE" @@ -28,8 +29,6 @@ if command -v hey >/dev/null 2>&1; then -d "$RACE_BODY" \ -t 15 "$RACE_URL" 2>&1) echo "$HEY_OUT" | grep -E '(Status|Responses|Requests/sec|200|429|500)' | sed 's/^/ /' | tee -a "$OUT_FILE" - # Check for duplicate keys (all 200 with same response = race vuln) - UNIQUE=$(echo "$HEY_OUT" | grep -c '"key"' || true) echo " hey summary complete" | tee -a "$OUT_FILE" else echo " hey not found — using curl & (higher jitter, less reliable for race detection)" | tee -a "$OUT_FILE" @@ -62,15 +61,19 @@ if command -v hey >/dev/null 2>&1; then -d "$ENC_BODY" -t 15 "$ENC_URL" 2>&1) echo "$HEY_ENC" | grep -E '(Status|200|429|500|Requests/sec)' | sed 's/^/ /' | tee -a "$OUT_FILE" else - declare -A ECODES - for i in $(seq 1 20); do - CODE=$(curl -sk -o /dev/null -w '%{http_code}' --http2 --max-time 10 \ + # Twenty at once, each writing its status to a file of its own: a variable + # set by a backgrounded command is set in its subshell, never here + CODES_DIR=$(mktemp -d) + for n in $(seq 1 20); do + curl -sk -o /dev/null -w '%{http_code}\n' --http2 --max-time 10 \ -X POST -H 'Content-Type: application/json' \ - -d "$ENC_BODY" "$ENC_URL" 2>/dev/null) & - ECODES[$CODE]=$((${ECODES[$CODE]:-0}+1)) + -d "$ENC_BODY" "$ENC_URL" > "$CODES_DIR/$n" 2>/dev/null & done wait - for CODE in "${!ECODES[@]}"; do echo " HTTP $CODE: ${ECODES[$CODE]}x" | tee -a "$OUT_FILE"; done + sort "$CODES_DIR"/* | uniq -c | while read -r count code; do + echo " HTTP $code: ${count}x" | tee -a "$OUT_FILE" + done + rm -rf "$CODES_DIR" fi echo "" | tee -a "$OUT_FILE" diff --git a/pentests/scripts/17_client_side_csp.sh b/pentests/scripts/17_client_side_csp.sh index b2b9cea8..fdd539fd 100755 --- a/pentests/scripts/17_client_side_csp.sh +++ b/pentests/scripts/17_client_side_csp.sh @@ -6,6 +6,7 @@ # Red-team: Client-side security — CSP analysis, supply chain, DOM clobbering SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +# shellcheck source=../config.demo.sh # the file this loads, as committed source "$SCRIPT_DIR/../config.sh" OUT="$OUT/client_side" mkdir -p "$OUT" diff --git a/pentests/scripts/18_resilience_chaos.sh b/pentests/scripts/18_resilience_chaos.sh index 2f5cc083..a921c19f 100755 --- a/pentests/scripts/18_resilience_chaos.sh +++ b/pentests/scripts/18_resilience_chaos.sh @@ -6,6 +6,7 @@ # Red-team: Resilience/chaos — retry storms, partial failure, cache desync, config stale SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +# shellcheck source=../config.demo.sh # the file this loads, as committed source "$SCRIPT_DIR/../config.sh" OUT="$OUT/resilience" mkdir -p "$OUT" @@ -14,7 +15,7 @@ echo '=== RESILIENCE & CHAOS RED-TEAM ===' | tee "$OUT/summary.txt" # Retry storm simulation (rapid reconnects without completing) echo '--- Connection Retry Storm (20 parallel half-open) ---' | tee -a "$OUT/summary.txt" -for i in $(seq 1 20); do +for _ in $(seq 1 20); do curl -sk -o /dev/null --max-time 2 --connect-timeout 1 "$TARGET/" &>/dev/null & done wait @@ -42,7 +43,7 @@ echo "[$r3] Accept: */*" | tee -a "$OUT/summary.txt" echo '' | tee -a "$OUT/summary.txt" echo '--- Rate Limit Cascade Test (80 rapid requests) ---' | tee -a "$OUT/summary.txt" declare -A rcounts -for i in $(seq 1 80); do +for _ in $(seq 1 80); do code=$(curl -sk -o /dev/null -w '%{http_code}' --max-time 3 "$TARGET/") rcounts[$code]=$(( ${rcounts[$code]:-0} + 1 )) done @@ -54,7 +55,7 @@ done echo '' | tee -a "$OUT/summary.txt" echo '--- Circuit Breaker Trip (repeated 404s) ---' | tee -a "$OUT/summary.txt" declare -A cbcounts -for i in $(seq 1 30); do +for _ in $(seq 1 30); do code=$(curl -sk -o /dev/null -w '%{http_code}' --max-time 5 "$TARGET/nonexistent-$RANDOM") cbcounts[$code]=$(( ${cbcounts[$code]:-0} + 1 )) done diff --git a/pentests/scripts/19_auth_hardening.sh b/pentests/scripts/19_auth_hardening.sh index bfbc60a3..4d1c5bab 100644 --- a/pentests/scripts/19_auth_hardening.sh +++ b/pentests/scripts/19_auth_hardening.sh @@ -7,6 +7,7 @@ # Authentication & Identity Hardening # Tests JWT abuse, session entropy, cookie security flags, credential hygiene SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +# shellcheck source=../config.demo.sh # the file this loads, as committed source "$SCRIPT_DIR/../config.sh" OUT="$OUT/auth_hardening" mkdir -p "$OUT" @@ -22,10 +23,10 @@ echo '--- Session Cookie Security Flags ---' | tee -a "$OUT/summary.txt" cookie_hdr=$(curl -sk -I --max-time 10 -A "$BROWSER" "$TARGET/" | grep -i 'set-cookie') if [ -n "$cookie_hdr" ]; then echo "$cookie_hdr" | tee -a "$OUT/summary.txt" - echo "$cookie_hdr" | grep -qi 'httponly' && echo " [PASS] HttpOnly present" || echo " [WARN] HttpOnly MISSING" | tee -a "$OUT/summary.txt" - echo "$cookie_hdr" | grep -qi 'secure' && echo " [PASS] Secure present" || echo " [WARN] Secure MISSING" | tee -a "$OUT/summary.txt" - echo "$cookie_hdr" | grep -qi 'samesite' && echo " [PASS] SameSite present" || echo " [WARN] SameSite MISSING" | tee -a "$OUT/summary.txt" - echo "$cookie_hdr" | grep -qi '__Secure-\|__Host-' && echo " [PASS] Cookie prefix hardened" || echo " [INFO] No __Secure-/__Host- prefix" | tee -a "$OUT/summary.txt" + if echo "$cookie_hdr" | grep -qi 'httponly'; then echo " [PASS] HttpOnly present"; else echo " [WARN] HttpOnly MISSING"; fi | tee -a "$OUT/summary.txt" + if echo "$cookie_hdr" | grep -qi 'secure'; then echo " [PASS] Secure present"; else echo " [WARN] Secure MISSING"; fi | tee -a "$OUT/summary.txt" + if echo "$cookie_hdr" | grep -qi 'samesite'; then echo " [PASS] SameSite present"; else echo " [WARN] SameSite MISSING"; fi | tee -a "$OUT/summary.txt" + if echo "$cookie_hdr" | grep -qi '__Secure-\|__Host-'; then echo " [PASS] Cookie prefix hardened"; else echo " [INFO] No __Secure-/__Host- prefix"; fi | tee -a "$OUT/summary.txt" else echo " [INFO] No Set-Cookie header on homepage" | tee -a "$OUT/summary.txt" fi @@ -40,25 +41,24 @@ NONE_TOKEN="${NONE_HDR}.${CLAIMS}." for ep in "/encrypt" "/decrypt" "/keys/generate" "/admin" "/users" "/config"; do resp=$(curl -sk -o /dev/null -w '%{http_code}' --max-time 8 -A "$BROWSER" \ -H "Authorization: Bearer $NONE_TOKEN" "$API_TARGET$ep") - [ "$resp" = "200" ] && echo " [!!!] JWT alg:none ACCEPTED on $ep" || echo " [PASS] $ep → $resp (rejected)" | tee -a "$OUT/summary.txt" + if [ "$resp" = "200" ]; then echo " [VULN] JWT alg:none ACCEPTED on $ep"; else echo " [PASS] $ep → $resp (rejected)"; fi | tee -a "$OUT/summary.txt" done # ── 3. JWT kid Header Injection ────────────────────────────────────────────── echo '' | tee -a "$OUT/summary.txt" echo '--- JWT kid Header Injection ---' | tee -a "$OUT/summary.txt" for kid_val in "../../etc/passwd" "' OR 1=1--" "/dev/null" "../../../../dev/null"; do - KID_HDR=$(printf "{\"alg\":\"HS256\",\"typ\":\"JWT\",\"kid\":\"$kid_val\"}" | python3 -c "import sys,base64; d=sys.stdin.read(); print(base64.urlsafe_b64encode(d.encode()).rstrip(b'=').decode())") + KID_HDR=$(printf '{"alg":"HS256","typ":"JWT","kid":"%s"}' "$kid_val" | python3 -c "import sys,base64; d=sys.stdin.read(); print(base64.urlsafe_b64encode(d.encode()).rstrip(b'=').decode())") KID_TOKEN="${KID_HDR}.${CLAIMS}.fakesig" resp=$(curl -sk -o /dev/null -w '%{http_code}' --max-time 8 -A "$BROWSER" \ -H "Authorization: Bearer $KID_TOKEN" "$API_TARGET/encrypt") - [ "$resp" = "200" ] && echo " [!!!] kid injection ACCEPTED: $kid_val" || echo " [PASS] kid='$kid_val' → $resp" | tee -a "$OUT/summary.txt" + if [ "$resp" = "200" ]; then echo " [VULN] kid injection ACCEPTED: $kid_val"; else echo " [PASS] kid='$kid_val' → $resp"; fi | tee -a "$OUT/summary.txt" done # ── 4. Weak JWT Secret Brute Force (common secrets) ───────────────────────── echo '' | tee -a "$OUT/summary.txt" echo '--- JWT Weak Secret Check ---' | tee -a "$OUT/summary.txt" WEAK_SECRETS=("secret" "password" "123456" "jwt_secret" "changeme" "supersecret" "qwerty") -WEAK_CLAIMS=$(printf '{"sub":"1","role":"user","exp":9999999999}') for secret in "${WEAK_SECRETS[@]}"; do token=$(python3 -c " import hmac, hashlib, base64, json @@ -71,7 +71,7 @@ print(f'{h}.{p}.{s}') [ -n "$token" ] && { resp=$(curl -sk -o /dev/null -w '%{http_code}' --max-time 8 -A "$BROWSER" \ -H "Authorization: Bearer $token" "$API_TARGET/encrypt") - [ "$resp" = "200" ] && echo " [!!!] WEAK SECRET '$secret' ACCEPTED" || echo " [PASS] secret='$secret' → $resp" | tee -a "$OUT/summary.txt" + if [ "$resp" = "200" ]; then echo " [VULN] WEAK SECRET '$secret' ACCEPTED"; else echo " [PASS] secret='$secret' → $resp"; fi | tee -a "$OUT/summary.txt" } done @@ -82,9 +82,11 @@ resp=$(curl -sk -o "$OUT/cred_url.txt" -w '%{http_code}' --max-time 8 -A "$BROWS "$API_TARGET/encrypt?api_key=test_key_12345&password=supersecret") # Only flag reflection if the server returns 2xx AND echoes the credential back if [ "$resp" = "200" ] || [ "$resp" = "201" ]; then - grep -qi 'test_key_12345\|supersecret' "$OUT/cred_url.txt" && \ - echo " [WARN] Credentials in URL reflected in response" | tee -a "$OUT/summary.txt" || \ - echo " [PASS] Credentials in URL not reflected ($resp)" | tee -a "$OUT/summary.txt" + if grep -qi 'test_key_12345\|supersecret' "$OUT/cred_url.txt"; then + echo " [WARN] Credentials in URL reflected in response" + else + echo " [PASS] Credentials in URL not reflected ($resp)" + fi | tee -a "$OUT/summary.txt" else echo " [PASS] Request rejected ($resp) — no credential reflection risk" | tee -a "$OUT/summary.txt" fi @@ -117,7 +119,7 @@ resp=$(curl -sk -o /dev/null -w '%{http_code}' --max-time 8 -A "$BROWSER" \ -X POST -H 'Content-Type: application/json' \ -d '{"refresh_token":"eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxIn0.fakesig"}' \ "$API_TARGET/auth/refresh") -[ "$resp" = "200" ] && echo " [!!!] Fake refresh token ACCEPTED" || echo " [PASS] Fake refresh token rejected ($resp)" | tee -a "$OUT/summary.txt" +if [ "$resp" = "200" ]; then echo " [VULN] Fake refresh token ACCEPTED"; else echo " [PASS] Fake refresh token rejected ($resp)"; fi | tee -a "$OUT/summary.txt" # ── 8. HTTP Auth Header Enumeration ───────────────────────────────────────── echo '' | tee -a "$OUT/summary.txt" diff --git a/pentests/scripts/20_authz_access_control.sh b/pentests/scripts/20_authz_access_control.sh index 9d6019f6..a53439e3 100644 --- a/pentests/scripts/20_authz_access_control.sh +++ b/pentests/scripts/20_authz_access_control.sh @@ -7,6 +7,7 @@ # Authorization & Access Control # Vertical/horizontal privilege escalation, IDOR, mass assignment, forced browsing SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +# shellcheck source=../config.demo.sh # the file this loads, as committed source "$SCRIPT_DIR/../config.sh" OUT="$OUT/authz_access_control" mkdir -p "$OUT" @@ -23,7 +24,7 @@ ADMIN_PATHS=("/admin" "/admin/users" "/admin/config" "/admin/logs" "/admin/keys" "/internal" "/internal/metrics" "/internal/config" "/debug" "/actuator") for path in "${ADMIN_PATHS[@]}"; do resp=$(curl -sk -o /dev/null -w '%{http_code}' --max-time 8 -A "$BROWSER" "$API_TARGET$path") - [ "$resp" = "200" ] && echo " [!!!] EXPOSED: $path ($resp)" || echo " [PASS] $path → $resp" | tee -a "$OUT/summary.txt" + if [ "$resp" = "200" ]; then echo " [VULN] EXPOSED: $path ($resp)"; else echo " [PASS] $path → $resp"; fi | tee -a "$OUT/summary.txt" done # ── 2. IDOR — Object Reference Enumeration ──────────────────────────────────── @@ -33,7 +34,7 @@ echo '--- IDOR Enumeration ---' | tee -a "$OUT/summary.txt" for id in "1" "2" "3" "0" "-1" "admin" "00000000-0000-0000-0000-000000000001" "null" "undefined"; do for ep in "/users/$id" "/keys/$id" "/api/keys/$id" "/api/users/$id" "/account/$id"; do resp=$(curl -sk -o /dev/null -w '%{http_code}' --max-time 6 -A "$BROWSER" "$API_TARGET$ep") - [ "$resp" = "200" ] && echo " [!!!] IDOR: $ep returned 200" | tee -a "$OUT/summary.txt" + [ "$resp" = "200" ] && echo " [VULN] IDOR: $ep returned 200" | tee -a "$OUT/summary.txt" done done echo " IDOR sweep complete" | tee -a "$OUT/summary.txt" @@ -59,8 +60,11 @@ PAYLOADS=( for payload in "${PAYLOADS[@]}"; do resp=$(curl -sk -o "$OUT/mass_assign.txt" -w '%{http_code}' --max-time 8 -A "$BROWSER" \ -X POST -H 'Content-Type: application/json' -d "$payload" "$API_TARGET/keys/generate") - grep -qi '"role"\s*:\s*"admin"\|"is_admin"\s*:\s*true\|admin.*true' "$OUT/mass_assign.txt" && \ - echo " [!!!] Mass assignment reflected: $resp" || echo " [PASS] $resp — mass assign fields not reflected" | tee -a "$OUT/summary.txt" + if grep -qi '"role"\s*:\s*"admin"\|"is_admin"\s*:\s*true\|admin.*true' "$OUT/mass_assign.txt"; then + echo " [VULN] Mass assignment reflected: $resp" + else + echo " [PASS] $resp — mass assign fields not reflected" + fi | tee -a "$OUT/summary.txt" done # ── 5. Forced Browsing / Directory Traversal to Restricted Resources ───────── @@ -75,7 +79,7 @@ RESTRICTED=( ) for path in "${RESTRICTED[@]}"; do resp=$(curl -sk -o /dev/null -w '%{http_code}' --max-time 8 -A "$BROWSER" "$API_TARGET$path") - [ "$resp" = "200" ] && echo " [!!!] EXPOSED: $path" || echo " [PASS] $path → $resp" | tee -a "$OUT/summary.txt" + if [ "$resp" = "200" ]; then echo " [VULN] EXPOSED: $path"; else echo " [PASS] $path → $resp"; fi | tee -a "$OUT/summary.txt" done # ── 6. HTTP Method Authorization Bypass ────────────────────────────────────── @@ -103,7 +107,10 @@ resp=$(curl -sk -o "$OUT/graphql.txt" -w '%{http_code}' --max-time 8 -A "$BROWSE -X POST -H 'Content-Type: application/json' \ -d '{"query":"{__schema{types{name}}}"}' \ "$API_TARGET/graphql") -grep -qi '__schema\|__type' "$OUT/graphql.txt" && \ - echo " [!!!] GraphQL introspection ENABLED ($resp)" || echo " [PASS] GraphQL introspection blocked/absent ($resp)" | tee -a "$OUT/summary.txt" +if grep -qi '__schema\|__type' "$OUT/graphql.txt"; then + echo " [VULN] GraphQL introspection ENABLED ($resp)" +else + echo " [PASS] GraphQL introspection blocked/absent ($resp)" +fi | tee -a "$OUT/summary.txt" cat "$OUT/summary.txt" diff --git a/pentests/scripts/21_supply_chain.sh b/pentests/scripts/21_supply_chain.sh index 2de11276..3e3d499c 100644 --- a/pentests/scripts/21_supply_chain.sh +++ b/pentests/scripts/21_supply_chain.sh @@ -7,6 +7,7 @@ # Supply Chain & Dependency Security (black-box perspective) # Checks for exposed dependency manifests, version disclosure, build artifacts SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +# shellcheck source=../config.demo.sh # the file this loads, as committed source "$SCRIPT_DIR/../config.sh" OUT="$OUT/supply_chain" mkdir -p "$OUT" @@ -33,7 +34,7 @@ for path in "${MANIFESTS[@]}"; do resp=$(curl -sk -o "$OUT/manifest_check.tmp" -w '%{http_code}' --max-time 8 -A "$BROWSER" "$TARGET$path") if [ "$resp" = "200" ]; then size=$(wc -c < "$OUT/manifest_check.tmp") - echo " [!!!] EXPOSED: $path ($size bytes)" | tee -a "$OUT/summary.txt" + echo " [VULN] EXPOSED: $path ($size bytes)" | tee -a "$OUT/summary.txt" head -3 "$OUT/manifest_check.tmp" | tee -a "$OUT/summary.txt" else echo " [PASS] $path → $resp" @@ -45,8 +46,12 @@ echo '' | tee -a "$OUT/summary.txt" echo '--- Version Disclosure in Headers ---' | tee -a "$OUT/summary.txt" headers=$(curl -sk -I --max-time 10 -A "$BROWSER" "$TARGET/") echo "$headers" | grep -iE 'Server:|X-Powered-By:|X-Generator:|X-Runtime:|X-Version:|X-App-Version:' | tee -a "$OUT/summary.txt" -echo "$headers" | grep -iE 'Server:|X-Powered-By:' | grep -qi '\d\.\d' && \ - echo " [WARN] Version number in header" || echo " [PASS] No version in Server/X-Powered-By" | tee -a "$OUT/summary.txt" +# A version is digits, a dot, digits (grep's basic syntax has no \d) +if echo "$headers" | grep -iE 'Server:|X-Powered-By:' | grep -qE '[0-9]+\.[0-9]+'; then + echo " [WARN] Version number in header" +else + echo " [PASS] No version in Server/X-Powered-By" +fi | tee -a "$OUT/summary.txt" echo '' | tee -a "$OUT/summary.txt" echo '--- Version Disclosure in API Responses ---' | tee -a "$OUT/summary.txt" @@ -81,7 +86,7 @@ for jsf in $js_files; do mapurl="${jsf_base}.map" resp=$(curl -sk -o /dev/null -w '%{http_code}' --max-time 8 -A "$BROWSER" "$mapurl") if [ "$resp" = "200" ]; then - echo " [!!!] Source map EXPOSED: $mapurl" | tee -a "$OUT/summary.txt" + echo " [VULN] Source map EXPOSED: $mapurl" | tee -a "$OUT/summary.txt" found_map=1 fi done @@ -101,7 +106,7 @@ BUILD_PATHS=( ) for path in "${BUILD_PATHS[@]}"; do resp=$(curl -sk -o /dev/null -w '%{http_code}' --max-time 8 -A "$BROWSER" "$TARGET$path") - [ "$resp" = "200" ] && echo " [!!!] EXPOSED: $path ($resp)" || echo " [PASS] $path → $resp" | tee -a "$OUT/summary.txt" + if [ "$resp" = "200" ]; then echo " [VULN] EXPOSED: $path ($resp)"; else echo " [PASS] $path → $resp"; fi | tee -a "$OUT/summary.txt" done # ── 5. Dependency Confusion Attack Surface ──────────────────────────────────── @@ -125,7 +130,7 @@ fi echo '' | tee -a "$OUT/summary.txt" echo '--- Subresource Integrity (SRI) Check ---' | tee -a "$OUT/summary.txt" page=$(curl -sk --max-time 10 -A "$BROWSER" "$TARGET/") -external_no_sri=$(echo "$page" | grep -oP ']*src="https?://(?!'"$(echo $TARGET | sed 's|https://||')"')[^"]*"[^>]*>' | grep -v 'integrity=') +external_no_sri=$(echo "$page" | grep -oP ']*src="https?://(?!'"${TARGET_HOST_ESCAPED}"')[^"]*"[^>]*>' | grep -v 'integrity=') if [ -n "$external_no_sri" ]; then echo " [WARN] External scripts WITHOUT SRI:" | tee -a "$OUT/summary.txt" echo "$external_no_sri" | head -5 | tee -a "$OUT/summary.txt" diff --git a/pentests/scripts/22_cloud_infrastructure.sh b/pentests/scripts/22_cloud_infrastructure.sh index bd16d575..a47ac416 100644 --- a/pentests/scripts/22_cloud_infrastructure.sh +++ b/pentests/scripts/22_cloud_infrastructure.sh @@ -7,6 +7,7 @@ # Cloud & Infrastructure Security # S3 buckets, cloud metadata endpoints, exposed cloud assets, secrets in env SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +# shellcheck source=../config.demo.sh # the file this loads, as committed source "$SCRIPT_DIR/../config.sh" OUT="$OUT/cloud_infrastructure" mkdir -p "$OUT" @@ -32,7 +33,7 @@ for meta_url in "${METADATA_URLS[@]}"; do resp=$(curl -sk -o "$OUT/meta_resp.tmp" -w '%{http_code}' --max-time 8 -A "$BROWSER" \ "$API_TARGET/encrypt?$param=$enc") grep -qi 'ami-id\|instance-id\|security-credentials\|computeMetadata\|access_key' "$OUT/meta_resp.tmp" && \ - echo " [!!!] CLOUD METADATA SSRF via ?$param: $meta_url" | tee -a "$OUT/summary.txt" + echo " [VULN] CLOUD METADATA SSRF via ?$param: $meta_url" | tee -a "$OUT/summary.txt" done done echo " Cloud metadata SSRF sweep complete" | tee -a "$OUT/summary.txt" @@ -51,7 +52,7 @@ for bucket in "${BUCKET_NAMES[@]}"; do resp=$(curl -sk -o "$OUT/s3_check.tmp" -w '%{http_code}' --max-time 8 \ "https://$bucket.s3.amazonaws.com/") case "$resp" in - 200) echo " [!!!] S3 BUCKET PUBLIC: $bucket" | tee -a "$OUT/summary.txt" ;; + 200) echo " [VULN] S3 BUCKET PUBLIC: $bucket" | tee -a "$OUT/summary.txt" ;; 403) echo " [PASS] $bucket — exists but access denied (403)" | tee -a "$OUT/summary.txt" ;; 404) echo " [INFO] $bucket — not found (404)" ;; *) echo " [INFO] $bucket — $resp" ;; @@ -74,7 +75,7 @@ for path in "${CRED_PATHS[@]}"; do resp=$(curl -sk -o "$OUT/cred_check.tmp" -w '%{http_code}' --max-time 8 -A "$BROWSER" "$TARGET$path") if [ "$resp" = "200" ]; then size=$(wc -c < "$OUT/cred_check.tmp") - echo " [!!!] CREDENTIAL FILE EXPOSED: $path ($size bytes)" | tee -a "$OUT/summary.txt" + echo " [VULN] CREDENTIAL FILE EXPOSED: $path ($size bytes)" | tee -a "$OUT/summary.txt" else echo " [PASS] $path → $resp" fi @@ -89,12 +90,12 @@ K8S_PATHS=( ) for path in "${K8S_PATHS[@]}"; do resp=$(curl -sk -o /dev/null -w '%{http_code}' --max-time 8 -A "$BROWSER" "$TARGET$path") - [ "$resp" = "200" ] && echo " [!!!] K8s API EXPOSED: $path" || echo " [PASS] $path → $resp" | tee -a "$OUT/summary.txt" + if [ "$resp" = "200" ]; then echo " [VULN] K8s API EXPOSED: $path"; else echo " [PASS] $path → $resp"; fi | tee -a "$OUT/summary.txt" done # Check default k8s ports for port in 6443 8443 10250 10255 2379 2380; do resp=$(curl -sk -o /dev/null -w '%{http_code}' --max-time 5 "https://${TARGET_HOST}:$port/") - [ "$resp" = "200" ] && echo " [!!!] K8s port OPEN: $port" || echo " [PASS] port $port → $resp" | tee -a "$OUT/summary.txt" + if [ "$resp" = "200" ]; then echo " [VULN] K8s port OPEN: $port"; else echo " [PASS] port $port → $resp"; fi | tee -a "$OUT/summary.txt" done # ── 5. Environment Variable Leakage via Endpoints ──────────────────────────── @@ -103,8 +104,11 @@ echo '--- Environment Variable Leakage ---' | tee -a "$OUT/summary.txt" for ep in "/env" "/environment" "/config" "/settings" "/debug/env" "/api/env" "/info" "/actuator/env"; do resp=$(curl -sk -o "$OUT/env_check.tmp" -w '%{http_code}' --max-time 8 -A "$BROWSER" "$API_TARGET$ep") if [ "$resp" = "200" ]; then - grep -qi 'DATABASE_URL\|SECRET_KEY\|AWS_\|PRIVATE_KEY\|PASSWORD\|TOKEN' "$OUT/env_check.tmp" && \ - echo " [!!!] SENSITIVE ENV VARS EXPOSED at $ep" || echo " [WARN] $ep is open (200) — check content" | tee -a "$OUT/summary.txt" + if grep -qi 'DATABASE_URL\|SECRET_KEY\|AWS_\|PRIVATE_KEY\|PASSWORD\|TOKEN' "$OUT/env_check.tmp"; then + echo " [VULN] SENSITIVE ENV VARS EXPOSED at $ep" + else + echo " [WARN] $ep is open (200) — check content" + fi | tee -a "$OUT/summary.txt" else echo " [PASS] $ep → $resp" fi @@ -113,10 +117,10 @@ done # ── 6. DNS Security: DNSSEC, SPF, DMARC, CAA ──────────────────────────────── echo '' | tee -a "$OUT/summary.txt" echo '--- DNS Security Records ---' | tee -a "$OUT/summary.txt" -dig +short TXT "_dmarc.$DOMAIN" | grep -qi 'v=DMARC1' && echo " [PASS] DMARC present" || echo " [WARN] DMARC missing" | tee -a "$OUT/summary.txt" -dig +short TXT "$DOMAIN" | grep -qi 'v=spf1' && echo " [PASS] SPF present" || echo " [WARN] SPF missing" | tee -a "$OUT/summary.txt" -dig +short CAA "$DOMAIN" | grep -q '.' && echo " [PASS] CAA record present: $(dig +short CAA $DOMAIN)" || echo " [WARN] No CAA record" | tee -a "$OUT/summary.txt" -dig +short DNSKEY "$DOMAIN" | grep -q '.' && echo " [PASS] DNSSEC enabled" || echo " [INFO] DNSSEC not detected (may be at registrar)" | tee -a "$OUT/summary.txt" +if dig +short TXT "_dmarc.$DOMAIN" | grep -qi 'v=DMARC1'; then echo " [PASS] DMARC present"; else echo " [WARN] DMARC missing"; fi | tee -a "$OUT/summary.txt" +if dig +short TXT "$DOMAIN" | grep -qi 'v=spf1'; then echo " [PASS] SPF present"; else echo " [WARN] SPF missing"; fi | tee -a "$OUT/summary.txt" +if dig +short CAA "$DOMAIN" | grep -q '.'; then echo " [PASS] CAA record present: $(dig +short CAA "$DOMAIN")"; else echo " [WARN] No CAA record"; fi | tee -a "$OUT/summary.txt" +if dig +short DNSKEY "$DOMAIN" | grep -q '.'; then echo " [PASS] DNSSEC enabled"; else echo " [INFO] DNSSEC not detected (may be at registrar)"; fi | tee -a "$OUT/summary.txt" # ── 7. Security.txt & Responsible Disclosure ──────────────────────────────── echo '' | tee -a "$OUT/summary.txt" diff --git a/pentests/scripts/23_client_side_js.sh b/pentests/scripts/23_client_side_js.sh index 71c6ef90..ccef804b 100755 --- a/pentests/scripts/23_client_side_js.sh +++ b/pentests/scripts/23_client_side_js.sh @@ -9,6 +9,7 @@ # prototype pollution via API, DOM XSS reflection vectors, SRI, service worker paths SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +# shellcheck source=../config.demo.sh # the file this loads, as committed source "$SCRIPT_DIR/../config.sh" OUT_FILE="$OUT/23_client_side_js.txt" @@ -29,7 +30,8 @@ do_test_headers() { local label="$1"; shift local out out=$(curl -sk -D - -o /dev/null "$@") - local code=$(echo "$out" | head -1 | grep -oP '\d{3}' | head -1) + local code + code=$(echo "$out" | head -1 | grep -oP '\d{3}' | head -1) printf '[%s] %s\n' "$code" "$label" | tee -a "$OUT_FILE" # Print security-relevant headers echo "$out" | grep -iE '^(x-frame-options|content-security-policy|x-content-type-options|cache-control|referrer-policy|permissions-policy|cross-origin|vary):' | sed 's/^/ /' | tee -a "$OUT_FILE" @@ -136,12 +138,14 @@ echo "--- Subresource Integrity (SRI) ---" | tee -a "$OUT_FILE" PAGE_HTML=$(curl -sk -A "$BROWSER_UA" "$TARGET/") SCRIPT_COUNT=$(echo "$PAGE_HTML" | grep -c ']+src="https?://(?!${TARGET_HOST_ESCAPED})[^"]+' | wc -l) -printf ' Script tags: %d | With SRI integrity attr: %d | External (non-${TARGET_HOST}): %d\n' \ - "$SCRIPT_COUNT" "$SRI_COUNT" "$EXTERNAL_SCRIPTS" | tee -a "$OUT_FILE" +# The target's own host, escaped for the regex, is spliced in between the +# single-quoted parts: inside them it would be matched as literal text +EXTERNAL_SCRIPTS=$(echo "$PAGE_HTML" | grep -oP ']+src="https?://(?!'"${TARGET_HOST_ESCAPED}"')[^"]+' | wc -l) +printf ' Script tags: %d | With SRI integrity attr: %d | External (non-%s): %d\n' \ + "$SCRIPT_COUNT" "$SRI_COUNT" "$TARGET_HOST" "$EXTERNAL_SCRIPTS" | tee -a "$OUT_FILE" if [ "$EXTERNAL_SCRIPTS" -gt 0 ]; then echo " [WARN] External scripts found without SRI:" | tee -a "$OUT_FILE" - echo "$PAGE_HTML" | grep -oP ']+src="https?://(?!${TARGET_HOST_ESCAPED})[^"]+"[^>]*>' | sed 's/^/ /' | tee -a "$OUT_FILE" + echo "$PAGE_HTML" | grep -oP ']+src="https?://(?!'"${TARGET_HOST_ESCAPED}"')[^"]+"[^>]*>' | sed 's/^/ /' | tee -a "$OUT_FILE" else echo " [OK] No cross-origin scripts detected" | tee -a "$OUT_FILE" fi diff --git a/pentests/scripts/24_data_privacy.sh b/pentests/scripts/24_data_privacy.sh index 2b7d438c..a4e1f806 100755 --- a/pentests/scripts/24_data_privacy.sh +++ b/pentests/scripts/24_data_privacy.sh @@ -9,6 +9,7 @@ # GDPR indicators, response data minimization, verbose error responses SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +# shellcheck source=../config.demo.sh # the file this loads, as committed source "$SCRIPT_DIR/../config.sh" OUT_FILE="$OUT/24_data_privacy.txt" @@ -29,7 +30,8 @@ do_body_check() { local label="$1"; local pattern="$2"; shift 2 local body body=$(curl -sk "$@") - local code=$(curl -sk -o /dev/null -w '%{http_code}' "$@") + local code + code=$(curl -sk -o /dev/null -w '%{http_code}' "$@") printf '[%s] %s\n' "$code" "$label" | tee -a "$OUT_FILE" if echo "$body" | grep -qiE "$pattern"; then echo " [WARN] Sensitive pattern found: $(echo "$body" | grep -ioE "$pattern" | head -3 | tr '\n' ' ')" | tee -a "$OUT_FILE" @@ -40,10 +42,12 @@ do_header_check() { local label="$1"; shift local headers headers=$(curl -sk -D - -o /dev/null "$@") - local code=$(echo "$headers" | head -1 | grep -oP '\d{3}' | head -1) + local code + code=$(echo "$headers" | head -1 | grep -oP '\d{3}' | head -1) printf '[%s] %s\n' "$code" "$label" | tee -a "$OUT_FILE" # Check Cache-Control on this endpoint - local cc=$(echo "$headers" | grep -i '^cache-control:' | head -1) + local cc + cc=$(echo "$headers" | grep -i '^cache-control:' | head -1) if [ -n "$cc" ]; then echo " Cache-Control: $(echo "$cc" | cut -d: -f2- | tr -d '\r')" | tee -a "$OUT_FILE" else @@ -98,7 +102,8 @@ check_sensitive_headers() { local label="$1"; shift local headers headers=$(curl -sk -D - -o /dev/null "$@") - local code=$(echo "$headers" | head -1 | grep -oP '\d{3}' | head -1) + local code + code=$(echo "$headers" | head -1 | grep -oP '\d{3}' | head -1) printf '[%s] %s\n' "$code" "$label" | tee -a "$OUT_FILE" # Check for info-leaking headers — only warn if a version number or known framework is disclosed for BAD in X-Powered-By X-AspNet-Version X-AspNetMvc-Version X-Generator X-Drupal X-WordPress X-Runtime; do @@ -110,8 +115,9 @@ check_sensitive_headers() { # Server header only flagged if it discloses version or known server software SERVER_VAL=$(echo "$headers" | grep -i "^Server:" | head -1) if [ -n "$SERVER_VAL" ]; then - echo "$SERVER_VAL" | grep -qiE '([0-9]+\.[0-9]+|apache|nginx|iis|lighttpd|tomcat|jetty|gunicorn|uvicorn|php|ruby|python)' && \ - echo " [WARN] $SERVER_VAL" | tee -a "$OUT_FILE" || true + if echo "$SERVER_VAL" | grep -qiE '([0-9]+\.[0-9]+|apache|nginx|iis|lighttpd|tomcat|jetty|gunicorn|uvicorn|php|ruby|python)'; then + echo " [WARN] $SERVER_VAL" | tee -a "$OUT_FILE" + fi fi # Check internal IPs in headers if echo "$headers" | grep -qiE '(127\.[0-9]+\.[0-9]+\.[0-9]+|10\.[0-9]+\.[0-9]+\.[0-9]+|192\.168\.[0-9]+\.[0-9]+|172\.(1[6-9]|2[0-9]|3[01])\.[0-9]+\.[0-9]+)'; then diff --git a/pentests/scripts/25_container_security.sh b/pentests/scripts/25_container_security.sh index bff4a704..a99c8947 100755 --- a/pentests/scripts/25_container_security.sh +++ b/pentests/scripts/25_container_security.sh @@ -9,6 +9,7 @@ # privileged endpoints, image registry, pod security, capabilities leakage SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +# shellcheck source=../config.demo.sh # the file this loads, as committed source "$SCRIPT_DIR/../config.sh" OUT_FILE="$OUT/25_container_security.txt" @@ -161,8 +162,11 @@ for FIELD in container docker kubernetes pod namespace node_name host_ip; do done # Check if hostname in response looks like a pod name (random suffix) HOSTNAME_IN=$(echo "$APP_RESP" | grep -ioP '"hostname"\s*:\s*"[^"]+"' | head -1) -[ -n "$HOSTNAME_IN" ] && echo " Hostname field: $HOSTNAME_IN" | tee -a "$OUT_FILE" || \ - echo " [OK] No hostname field in API response" | tee -a "$OUT_FILE" +if [ -n "$HOSTNAME_IN" ]; then + echo " Hostname field: $HOSTNAME_IN" +else + echo " [OK] No hostname field in API response" +fi | tee -a "$OUT_FILE" echo "" | tee -a "$OUT_FILE" echo "=== 25. Container Security COMPLETE ===" | tee -a "$OUT_FILE" diff --git a/pentests/scripts/26_cicd_pipeline.sh b/pentests/scripts/26_cicd_pipeline.sh index 512c2269..8b0b01c6 100755 --- a/pentests/scripts/26_cicd_pipeline.sh +++ b/pentests/scripts/26_cicd_pipeline.sh @@ -10,6 +10,7 @@ # OIDC token theft vectors, dependency substitution surface SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +# shellcheck source=../config.demo.sh # the file this loads, as committed source "$SCRIPT_DIR/../config.sh" OUT_FILE="$OUT/26_cicd_pipeline.txt" diff --git a/pentests/scripts/27_database_storage.sh b/pentests/scripts/27_database_storage.sh index 06bd3c3f..ca936f7f 100755 --- a/pentests/scripts/27_database_storage.sh +++ b/pentests/scripts/27_database_storage.sh @@ -10,6 +10,7 @@ # query timing inference, audit logging completeness SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +# shellcheck source=../config.demo.sh # the file this loads, as committed source "$SCRIPT_DIR/../config.sh" OUT_FILE="$OUT/27_database_storage.txt" @@ -104,11 +105,11 @@ echo "" | tee -a "$OUT_FILE" echo "--- NoSQL Injection ---" | tee -a "$OUT_FILE" # MongoDB operator injection NOSQL_PAYLOADS=( - '{"username":{"$gt":""},"password":{"$gt":""}}' - '{"username":{"$ne":"invalid"},"password":{"$ne":"invalid"}}' - '{"username":{"$regex":".*"},"password":{"$regex":".*"}}' - '{"username":{"$where":"1==1"}}' - '{"$or":[{"username":"admin"},{"username":"root"}],"password":{"$ne":""}}' + $'{"username":{"$gt":""},"password":{"$gt":""}}' + $'{"username":{"$ne":"invalid"},"password":{"$ne":"invalid"}}' + $'{"username":{"$regex":".*"},"password":{"$regex":".*"}}' + $'{"username":{"$where":"1==1"}}' + $'{"$or":[{"username":"admin"},{"username":"root"}],"password":{"$ne":""}}' ) for PAYLOAD in "${NOSQL_PAYLOADS[@]}"; do code=$(curl -sk -o /dev/null -w '%{http_code}' --max-time 5 \ @@ -165,7 +166,6 @@ echo "" | tee -a "$OUT_FILE" # ── 6. Object Storage Misconfiguration ─────────────────────────────────────── echo "--- Object Storage (S3 / GCS / Azure Blob) ---" | tee -a "$OUT_FILE" -HOST_BASE=$(echo "$HOST" | sed 's/^www\.//' | sed 's/\./\-/g') S3_VARIANTS=( "${PROJECT_NAME}" "${PROJECT_NAME}-backup" diff --git a/pentests/scripts/28_ai_llm.sh b/pentests/scripts/28_ai_llm.sh index 5db51c31..839b1c34 100755 --- a/pentests/scripts/28_ai_llm.sh +++ b/pentests/scripts/28_ai_llm.sh @@ -12,6 +12,7 @@ # verbatim retrieval, semantic boundary probing — black-box, no /embed endpoint) SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +# shellcheck source=../config.demo.sh # the file this loads, as committed source "$SCRIPT_DIR/../config.sh" OUT_FILE="$OUT/28_ai_llm.txt" @@ -340,7 +341,7 @@ echo "" | tee -a "$OUT_FILE" # Mass session enumeration (rate limit check on AI endpoint) echo "--- AI Endpoint Rate Limiting ---" | tee -a "$OUT_FILE" RATE_CODES="" -for i in $(seq 1 15); do +for _ in $(seq 1 15); do c=$(chat_code "ping" 2>/dev/null) RATE_CODES="$RATE_CODES $c" done diff --git a/pentests/scripts/29_xxe.sh b/pentests/scripts/29_xxe.sh index e221e2d4..341f7520 100755 --- a/pentests/scripts/29_xxe.sh +++ b/pentests/scripts/29_xxe.sh @@ -9,6 +9,7 @@ # Covers HTTP/1.1 and HTTP/2, OOB probes, blind XXE, XXE via SVG/DOCX wrappers SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +# shellcheck source=../config.demo.sh # the file this loads, as committed source "$SCRIPT_DIR/../config.sh" OUT_FILE="$OUT/29_xxe.txt" echo "=== 29. XXE Injection ===" | tee "$OUT_FILE" @@ -94,8 +95,11 @@ CODE=$(curl -sk --http2 -o /dev/null -w '%{http_code}' --max-time 10 -A "$BROWSE END=$(python3 -c "import time; print(int(time.time()*1000))") ELAPSED=$((END - START)) printf '[%s] Billion laughs entity expansion — %dms\n' "$CODE" "$ELAPSED" | tee -a "$OUT_FILE" -[ "$ELAPSED" -gt 8000 ] && echo " [WARN] Slow response — server may be expanding entities" | tee -a "$OUT_FILE" || \ - echo " [OK] Fast rejection — entity expansion not processed" | tee -a "$OUT_FILE" +if [ "$ELAPSED" -gt 8000 ]; then + echo " [WARN] Slow response — server may be expanding entities" +else + echo " [OK] Fast rejection — entity expansion not processed" +fi | tee -a "$OUT_FILE" echo "" | tee -a "$OUT_FILE" # ── 7. HTTP/1.1 vs HTTP/2 XXE consistency ──────────────────────────────────── diff --git a/pentests/scripts/30_ssti.sh b/pentests/scripts/30_ssti.sh index a890d793..9ca0f80d 100755 --- a/pentests/scripts/30_ssti.sh +++ b/pentests/scripts/30_ssti.sh @@ -11,6 +11,7 @@ # HTTP/1.1 and HTTP/2 covered SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +# shellcheck source=../config.demo.sh # the file this loads, as committed source "$SCRIPT_DIR/../config.sh" OUT_FILE="$OUT/30_ssti.txt" echo "=== 30. Server-Side Template Injection (SSTI) ===" | tee "$OUT_FILE" @@ -23,26 +24,26 @@ W() { printf '%s' "$1" | python3 -c "import sys,urllib.parse; print(urllib.parse # If the response contains the computed result, SSTI is confirmed SSTI_PROBES=( "{{7*7}}:49" - "${7*7}:49" + "\${7*7}:49" "<%= 7*7 %>:49" "#{7*7}:49" "*{7*7}:49" "@{7*7}:49" "{{7*'7'}}:7777777" "{#7*7#}:49" - "${{7*7}}:49" + "\${{7*7}}:49" "{php}echo(7*7);{/php}:49" "{% set x=7*7 %}{{x}}:49" "{{config}}:Config" "{{self}}:class" - "${T(java.lang.Runtime).getRuntime().exec('id')}:uid" + "\${T(java.lang.Runtime).getRuntime().exec('id')}:uid" "{{''.__class__.__mro__[1].__subclasses__()}}:object" ) check_ssti() { local label="$1" body="$2" expected="$3" if echo "$body" | grep -qF "$expected"; then - printf ' [VULN] Template evaluated! Expected "%s" found in response\n' "$expected" | tee -a "$OUT_FILE" + printf ' [VULN] %s: template evaluated, "%s" found in the response\n' "$label" "$expected" | tee -a "$OUT_FILE" fi } @@ -140,7 +141,7 @@ echo "" | tee -a "$OUT_FILE" echo "--- PHP Template Engine Probes (Smarty/Twig/Blade) ---" | tee -a "$OUT_FILE" PHP_PROBES=( '{php}echo 7*7;{/php}:49' - '{$smarty.version}:Smarty' + $'{$smarty.version}:Smarty' '{{dump()}}:array' '{if 1}rendered{/if}:rendered' '{% debug %}:debug' diff --git a/pentests/scripts/31_file_upload.sh b/pentests/scripts/31_file_upload.sh index 44b8c571..e001e18a 100755 --- a/pentests/scripts/31_file_upload.sh +++ b/pentests/scripts/31_file_upload.sh @@ -10,6 +10,7 @@ # Covers all upload endpoints: PDF tools api.php, any /upload paths SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +# shellcheck source=../config.demo.sh # the file this loads, as committed source "$SCRIPT_DIR/../config.sh" OUT_FILE="$OUT/31_file_upload.txt" echo "=== 31. File Upload Security ===" | tee "$OUT_FILE" @@ -46,13 +47,13 @@ do_upload() { TMPD=$(mktemp -d) # Legitimate PDF -printf '%PDF-1.4\n1 0 obj<>\nendobj\n' > "$TMPD/test.pdf" +printf '%%PDF-1.4\n1 0 obj<>\nendobj\n' > "$TMPD/test.pdf" # PHP webshell disguised as PDF -printf '%PDF-1.4\n' > "$TMPD/shell.pdf" +printf '%%PDF-1.4\n' "\$_GET[\"cmd\"]" > "$TMPD/shell.pdf" # PHP webshell with double extension -printf '' > "$TMPD/shell.php.pdf" +printf $'' > "$TMPD/shell.php.pdf" # PHP in .jpg printf '\xff\xd8\xff\xe0' > "$TMPD/shell.jpg" diff --git a/pentests/scripts/32_grpc_protobuf.sh b/pentests/scripts/32_grpc_protobuf.sh index 6c1121fd..e5f5424f 100644 --- a/pentests/scripts/32_grpc_protobuf.sh +++ b/pentests/scripts/32_grpc_protobuf.sh @@ -14,6 +14,7 @@ # auth bypass via gRPC metadata, message injection SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +# shellcheck source=../config.demo.sh # the file this loads, as committed source "$SCRIPT_DIR/../config.sh" OUT_FILE="$OUT/32_grpc_protobuf.txt" echo "=== 32. gRPC / Protobuf ===" | tee "$OUT_FILE" @@ -123,7 +124,7 @@ FUZZ_CASES=( for CASE in "${FUZZ_CASES[@]}"; do LABEL="${CASE%%:*}" PAYLOAD="${CASE#*:}" - CODE=$(printf "$PAYLOAD" | curl -sk --http2 -o /dev/null -w '%{http_code}' \ + CODE=$(printf '%b' "$PAYLOAD" | curl -sk --http2 -o /dev/null -w '%{http_code}' \ --max-time 8 -A "$BROWSER_UA" \ -X POST \ -H "Content-Type: application/grpc" \ @@ -146,9 +147,11 @@ for GWPATH in "${GRPC_WEB_PATHS[@]}"; do -H "X-Grpc-Web: 1" \ --data-binary $'\x00\x00\x00\x00\x00' \ "$TARGET$GWPATH" 2>/dev/null) - [ "$CODE" != "404" ] && [ "$CODE" != "301" ] && \ - printf ' [%s] gRPC-Web gateway: %s\n' "$CODE" "$GWPATH" | tee -a "$OUT_FILE" || \ - printf ' [%s] %s\n' "$CODE" "$GWPATH" | tee -a "$OUT_FILE" + if [ "$CODE" != "404" ] && [ "$CODE" != "301" ]; then + printf ' [%s] gRPC-Web gateway: %s\n' "$CODE" "$GWPATH" + else + printf ' [%s] %s\n' "$CODE" "$GWPATH" + fi | tee -a "$OUT_FILE" done echo "" | tee -a "$OUT_FILE" diff --git a/pentests/target_integrity_check.sh b/pentests/target_integrity_check.sh index 059a3578..ef445463 100755 --- a/pentests/target_integrity_check.sh +++ b/pentests/target_integrity_check.sh @@ -70,7 +70,7 @@ warn() { printf ' [WARN] %s\n' "$1"; WARN=$((WARN+1)); } db_scalar() { systemd-run --quiet --pipe --wait --collect \ -p LoadCredentialEncrypted="DB_PASS:$DB_CREDENTIAL" \ - php -r ' + php -r $' define("PQCRYPTA_ACCESS", true); require_once "/var/www/html/config/config.php"; require_once "/var/www/html/includes/db.php"; @@ -80,7 +80,7 @@ db_scalar() { $st->execute([":ip" => $argv[2]]); echo (string)$st->fetchColumn(); } catch (Throwable $e) { - fwrite(STDERR, get_class($e) . "\n"); + fwrite(STDERR, get_class($e) . "\\n"); exit(1); } ' "$1" "$TESTER_IP" 2>/dev/null @@ -113,7 +113,8 @@ check_fail2ban_ignore() { # contains it, or resolves to it local entries entries=$(fail2ban-client get "$JAIL" ignoreip 2>/dev/null | sed -E 's/^[|`]-[[:space:]]*//; s/^[[:space:]]+//' | grep -v '^These IP addresses' || true) - if python3 -I - "$TESTER_IP" $entries <<'PY' + local -a entry_list; read -ra entry_list <<<"$(tr '\n' ' ' <<<"$entries")" + if python3 -I - "$TESTER_IP" "${entry_list[@]}" <<'PY' import ipaddress, socket, sys tester = ipaddress.ip_address(sys.argv[1]) for entry in sys.argv[2:]: @@ -253,7 +254,8 @@ check_waf_counters() { fi local m; m=$(grep -E '^pqcrypta_waf_(requests|allowed|blocked|detected)_total' <<< "$metrics") if [[ -n "$m" ]]; then - ok "WAF counters readable:"; echo "$m" | sed 's/^/ /' + ok "WAF counters readable:" + while IFS= read -r line; do printf ' %s\n' "$line"; done <<<"$m" else warn "WAF counters not exposed (metrics feature off?)" fi diff --git a/scripts/delegated-credential-cert.sh b/scripts/delegated-credential-cert.sh index 68b810e7..736052f4 100755 --- a/scripts/delegated-credential-cert.sh +++ b/scripts/delegated-credential-cert.sh @@ -138,7 +138,7 @@ as_owner() { } # put MODE SOURCE TARGET: the file at TARGET, made with MODE, from SOURCE put() { - as_owner sh -c 'umask 077 && cat > "$2.new" && chmod "$1" "$2.new" && mv -f "$2.new" "$2"' \ + as_owner sh -c $'umask 077 && cat > "$2.new" && chmod "$1" "$2.new" && mv -f "$2.new" "$2"' \ sh "$1" "$3" <"$2" } # The key before the certificate: the resolver loads a domain by its .crt. diff --git a/scripts/deploy.sh b/scripts/deploy.sh index 31de951c..43fec905 100755 --- a/scripts/deploy.sh +++ b/scripts/deploy.sh @@ -106,11 +106,12 @@ for node in "$@"; do bash -c "$STEP" step "$staged" "$CONFIG" "$RUN_AS" "$VERSION" "$STAMP" "${OPENSSL_CHANGE:-}" else scp -q "$BIN" "$node:$staged" - # The step on the node's shell's standard input, its arguments quoted - # for that shell + # The step on the node's shell's standard input, its arguments set + # first, quoted for that shell: the command line ssh sends is only + # `bash -s`, with nothing of this side's in it args=$(printf '%q ' "$staged" "$CONFIG" "$RUN_AS" "$VERSION" "$STAMP" "${OPENSSL_CHANGE:-}") - remote="bash -s -- $args" - ssh "$node" "$remote" <<<"$STEP" + ssh "$node" 'bash -s' <<<"set -- $args +$STEP" fi done diff --git a/scripts/refresh_fingerprint_db.sh b/scripts/refresh_fingerprint_db.sh index 6f297640..bff6076b 100755 --- a/scripts/refresh_fingerprint_db.sh +++ b/scripts/refresh_fingerprint_db.sh @@ -126,8 +126,7 @@ update_geoip() { fi mkdir -p "${GEOIP_STAGE}" - GEOIP_OUT=$(geoipupdate -f "${GEOIP_CONF}" -d "${GEOIP_STAGE}" 2>&1) - if [ "$?" -ne 0 ]; then + if ! GEOIP_OUT=$(geoipupdate -f "${GEOIP_CONF}" -d "${GEOIP_STAGE}" 2>&1); then log "ERROR: geoipupdate failed (${GEOIP_OUT}) — existing GeoIP masters preserved" return fi @@ -270,10 +269,8 @@ TMP_CSV=$(mktemp /tmp/ja3_refresh_XXXXXX.csv) # load it half written TMP_JSON=$(mktemp "${DEST_DIR}/.ja3_refresh_XXXXXX.json") -cleanup() { - rm -f "${TMP_CSV}" "${TMP_JSON}" -} -trap cleanup EXIT +# Both removed however the run ends +trap 'rm -f "${TMP_CSV}" "${TMP_JSON}"' EXIT # Download curl -fsSL --max-time 30 "${SOURCE_URL}" -o "${TMP_CSV}" 2>&1 diff --git a/src/challenge.rs b/src/challenge.rs index 6a7b8941..f6c13805 100644 --- a/src/challenge.rs +++ b/src/challenge.rs @@ -30,7 +30,7 @@ //! [`PREFIX`], each with a Content-Security-Policy that admits nothing else: //! no inline script or style, no third party. -use std::collections::HashMap; +use std::collections::{BTreeMap, HashMap}; use std::net::IpAddr; use std::sync::atomic::{AtomicU64, Ordering}; use std::time::{SystemTime, UNIX_EPOCH}; @@ -414,9 +414,238 @@ pub fn is_navigation(method: &str, headers: &HeaderMap) -> bool { .any(|v| v.to_str().is_ok_and(|v| v.contains("text/html"))) } -/// The interstitial for `issued`. It is served at the address the browser -/// asked for, so once solved the script returns it there. -pub fn page(issued: &Issued) -> String { +/// The interstitial's text in one language, +/// `[security.challenge.translations.]`. A message left out is the +/// English one, so a translation can be partial. +#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(default)] +pub struct Messages { + /// The writing direction, `ltr` (left out) or `rtl` + pub dir: Option, + /// The page's title and heading + pub title: Option, + /// Why the browser is asked for work + pub explanation: Option, + /// The status before the work reports progress + pub working: Option, + /// The status as the work progresses; `{percent}` is the share done + pub progress: Option, + /// The status once solved; `{seconds}` is how long it took + pub done: Option, + /// Shown when JavaScript is off + pub no_script: Option, + /// The challenge could not be read + pub could_not_start: Option, + /// The work ended without a solution + pub did_not_finish: Option, + /// The browser could not run the work + pub could_not_run: Option, +} + +/// The page's text, resolved: a translation's messages, English's where it +/// has none +struct Text<'a> { + lang: &'a str, + dir: &'a str, + title: &'a str, + explanation: &'a str, + working: &'a str, + progress: &'a str, + done: &'a str, + no_script: &'a str, + could_not_start: &'a str, + did_not_finish: &'a str, + could_not_run: &'a str, +} + +impl<'a> Text<'a> { + fn of(translation: Option<(&'a str, &'a Messages)>) -> Self { + let m = translation.map(|(_, m)| m); + let or = |field: Option<&'a String>, english: &'static str| { + field.map_or(english, String::as_str) + }; + Self { + lang: translation.map_or("en", |(tag, _)| tag), + dir: or(m.and_then(|m| m.dir.as_ref()), "ltr"), + title: or(m.and_then(|m| m.title.as_ref()), "Checking your browser"), + explanation: or( + m.and_then(|m| m.explanation.as_ref()), + "Traffic from your network looked automated, so this site asks your browser for \ + about a second of work before it continues. Nothing is installed or kept.", + ), + working: or(m.and_then(|m| m.working.as_ref()), "Working\u{2026}"), + progress: or( + m.and_then(|m| m.progress.as_ref()), + "Working\u{2026} {percent}%", + ), + done: or( + m.and_then(|m| m.done.as_ref()), + "Done in {seconds} s. Continuing\u{2026}", + ), + no_script: or( + m.and_then(|m| m.no_script.as_ref()), + "This check needs JavaScript. Turn it on and reload the page.", + ), + could_not_start: or( + m.and_then(|m| m.could_not_start.as_ref()), + "The check could not start. Reload the page to try again.", + ), + did_not_finish: or( + m.and_then(|m| m.did_not_finish.as_ref()), + "The check did not finish. Reload the page to try again.", + ), + could_not_run: or( + m.and_then(|m| m.could_not_run.as_ref()), + "The check could not run in this browser. Reload the page to try again.", + ), + } + } +} + +/// The most language ranges an `Accept-Language` header is read for; a +/// longer one is read that far +const MAX_LANGUAGE_RANGES: usize = 32; + +/// The longest translated message, in bytes +pub const MAX_MESSAGE_BYTES: usize = 1000; + +/// The translation the browser's `Accept-Language` ranks highest. +/// +/// Ranges are taken by weight, then in the order the header lists them +/// (RFC 9110 §12.5.4). A range takes a translation of the same tag first, +/// then English when it asks for English, then a translation of the same +/// language (`de-AT` takes `de`, `pt` takes `pt-BR`). `None`, English, when +/// nothing configured is asked for, for `*`, and without the header. +pub fn negotiate<'a>( + accept_language: Option<&str>, + translations: &'a BTreeMap, +) -> Option<(&'a str, &'a Messages)> { + let header = accept_language?; + if translations.is_empty() { + return None; + } + let mut ranges: Vec<(u16, usize, &str)> = header + .split(',') + .take(MAX_LANGUAGE_RANGES) + .enumerate() + .filter_map(|(order, item)| { + let mut parts = item.split(';'); + let range = parts.next()?.trim(); + let weight = match parts.find_map(|p| p.trim().strip_prefix("q=")) { + Some(q) => qvalue(q)?, + None => 1000, + }; + (!range.is_empty() && weight > 0).then_some((weight, order, range)) + }) + .collect(); + ranges.sort_by(|a, b| b.0.cmp(&a.0).then(a.1.cmp(&b.1))); + for (_, _, range) in ranges { + if range == "*" { + return None; + } + if let Some((tag, m)) = translations + .iter() + .find(|(tag, _)| tag.eq_ignore_ascii_case(range)) + { + return Some((tag.as_str(), m)); + } + if same_language(range, "en") { + return None; + } + if let Some((tag, m)) = translations + .iter() + .find(|(tag, _)| same_language(range, tag)) + { + return Some((tag.as_str(), m)); + } + } + None +} + +/// Whether a language range and a tag name the same language: equal, or one +/// the other with subtags after it, ignoring case +fn same_language(range: &str, tag: &str) -> bool { + let extends = |short: &str, long: &str| { + long.len() > short.len() + && long.as_bytes()[short.len()] == b'-' + && long.as_bytes()[..short.len()].eq_ignore_ascii_case(short.as_bytes()) + }; + range.eq_ignore_ascii_case(tag) || extends(tag, range) || extends(range, tag) +} + +/// A qvalue (`0` to `1`, up to three decimals) in thousandths +fn qvalue(text: &str) -> Option { + let text = text.trim(); + let (whole, fraction) = text.split_once('.').unwrap_or((text, "")); + if fraction.len() > 3 || !fraction.bytes().all(|b| b.is_ascii_digit()) { + return None; + } + let thousandths: u16 = format!("{fraction:0<3}").parse().ok()?; + match whole { + "0" => Some(thousandths), + "1" if thousandths == 0 => Some(1000), + _ => None, + } +} + +/// Whether `tag` is a BCP 47 language tag the page can carry in its `lang`: +/// a language subtag of 2 to 8 letters, then subtags of 1 to 8 letters or +/// digits +fn is_language_tag(tag: &str) -> bool { + let mut subtags = tag.split('-'); + subtags.next().is_some_and(|language| { + (2..=8).contains(&language.len()) && language.bytes().all(|b| b.is_ascii_alphabetic()) + }) && subtags + .all(|s| (1..=8).contains(&s.len()) && s.bytes().all(|b| b.is_ascii_alphanumeric())) +} + +/// The configured translations, refused when one could not be served: a tag +/// that is not a language tag, a direction other than `ltr` or `rtl`, or a +/// message longer than [`MAX_MESSAGE_BYTES`]. +/// +/// # Errors +/// +/// The first translation that could not be served, and why. +pub fn validate_translations(translations: &BTreeMap) -> anyhow::Result<()> { + for (tag, m) in translations { + if !is_language_tag(tag) { + anyhow::bail!("security.challenge.translations: {tag:?} is not a BCP 47 language tag"); + } + if let Some(dir) = m.dir.as_deref().filter(|d| !matches!(*d, "ltr" | "rtl")) { + anyhow::bail!( + "security.challenge.translations.{tag}.dir is {dir:?}: it is \"ltr\" or \"rtl\"" + ); + } + for text in [ + &m.title, + &m.explanation, + &m.working, + &m.progress, + &m.done, + &m.no_script, + &m.could_not_start, + &m.did_not_finish, + &m.could_not_run, + ] + .into_iter() + .flatten() + { + if text.len() > MAX_MESSAGE_BYTES { + anyhow::bail!( + "security.challenge.translations.{tag}: a message is {} bytes, past {MAX_MESSAGE_BYTES}", + text.len() + ); + } + } + } + Ok(()) +} + +/// The interstitial for `issued`, in `translation`'s language or English's. +/// It is served at the address the browser asked for, so once solved the +/// script returns it there. +pub fn page(issued: &Issued, translation: Option<(&str, &Messages)>) -> String { + let text = Text::of(translation); let challenge = serde_json::json!({ "algorithm": "SHA-256", "challenge": issued.challenge, @@ -425,21 +654,36 @@ pub fn page(issued: &Issued) -> String { "signature": issued.signature, }) .to_string(); + // What the script shows as the work runs, in the page's language + let messages = serde_json::json!({ + "progress": text.progress, + "done": text.done, + "couldNotStart": text.could_not_start, + "didNotFinish": text.did_not_finish, + "couldNotRun": text.could_not_run, + }) + .to_string(); format!( - "\n\n\n\n\ + "\n\n\n\n\ \n\ - \nChecking your browser\n\ + \n{title}\n\ \n\ \n\ \n\n\n\ -
\n\ -

Checking your browser

\n\ -

Traffic from your network looked automated, so this site asks your browser for \ - about a second of work before it continues. Nothing is installed or kept.

\n\ -

Working…

\n\ - \n\ +
\n\ +

{title}

\n\ +

{explanation}

\n\ +

{working}

\n\ + \n\
\n\n\n", - escape_attribute(&challenge) + lang = escape_attribute(text.lang), + dir = escape_attribute(text.dir), + title = escape_attribute(text.title), + challenge = escape_attribute(&challenge), + messages = escape_attribute(&messages), + explanation = escape_attribute(text.explanation), + working = escape_attribute(text.working), + no_script = escape_attribute(text.no_script), ) } @@ -701,6 +945,179 @@ mod tests { assert!(!is_navigation("GET", &HeaderMap::new())); } + fn translations() -> BTreeMap { + let mut t = BTreeMap::new(); + t.insert( + "de".to_string(), + Messages { + title: Some("Ihr Browser wird geprüft".into()), + done: Some("Fertig in {seconds} s. Weiter\u{2026}".into()), + ..Messages::default() + }, + ); + t.insert( + "pt-BR".to_string(), + Messages { + title: Some("Verificando seu navegador".into()), + ..Messages::default() + }, + ); + t.insert( + "ar".to_string(), + Messages { + dir: Some("rtl".into()), + title: Some("&".into()), + ..Messages::default() + }, + ); + t + } + + #[test] + fn the_browser_chooses_the_language_by_weight_and_order() { + let t = translations(); + let lang = |header: Option<&str>| negotiate(header, &t).map(|(tag, _)| tag); + assert_eq!(lang(None), None, "no header, English"); + assert_eq!(lang(Some("de")), Some("de")); + assert_eq!( + lang(Some("DE-at, en;q=0.5")), + Some("de"), + "a region takes its language" + ); + assert_eq!( + lang(Some("pt")), + Some("pt-BR"), + "a language takes its region's" + ); + assert_eq!(lang(Some("en, de")), None, "English asked for first"); + assert_eq!( + lang(Some("fr;q=0.9, de;q=0.4, en;q=0.2")), + Some("de"), + "by weight" + ); + assert_eq!( + lang(Some("de;q=0.5, pt;q=0.5")), + Some("de"), + "equal weights, the browser's order" + ); + assert_eq!( + lang(Some("de;q=0, fr")), + None, + "q=0 is not acceptable; nothing else is configured" + ); + assert_eq!(lang(Some("*")), None); + assert_eq!( + lang(Some("de;q=2, pt")), + Some("pt-BR"), + "an invalid weight drops its range" + ); + assert_eq!(lang(Some("ja, ar")), Some("ar")); + assert_eq!(negotiate(Some("de"), &BTreeMap::new()), None); + // A header of many ranges is read for its first few + let long = format!("{}de", "xx, ".repeat(MAX_LANGUAGE_RANGES)); + assert_eq!(lang(Some(&long)), None); + } + + #[test] + fn a_translated_page_carries_its_language_direction_and_messages() { + let issued = Issued { + challenge: "c".into(), + max_number: 1, + salt: "s".into(), + signature: "x".into(), + }; + let t = translations(); + let de = page(&issued, negotiate(Some("de"), &t)); + assert!(de.contains("")); + assert!(de.contains("

Ihr Browser wird geprüft

")); + // What the translation leaves out is English + assert!(de.contains("This check needs JavaScript")); + assert!( + de.contains("Fertig in {seconds} s."), + "the script's messages ride in data-messages" + ); + let ar = page(&issued, negotiate(Some("ar"), &t)); + assert!(ar.contains("lang=\"ar\" dir=\"rtl\"")); + assert!( + ar.contains("

<b>&

"), + "an operator's text is escaped" + ); + assert!(page(&issued, None).contains("")); + } + + /// docs/challenge-translations/en.toml is the English the page shows, key + /// for key, and every translation beside it loads and could be served + #[test] + fn the_translation_template_is_the_english_text() { + let template: Messages = + toml::from_str(include_str!("../docs/challenge-translations/en.toml")).unwrap(); + let english = Text::of(None); + for (key, ours, template) in [ + ("dir", english.dir, &template.dir), + ("title", english.title, &template.title), + ("explanation", english.explanation, &template.explanation), + ("working", english.working, &template.working), + ("progress", english.progress, &template.progress), + ("done", english.done, &template.done), + ("no_script", english.no_script, &template.no_script), + ( + "could_not_start", + english.could_not_start, + &template.could_not_start, + ), + ( + "did_not_finish", + english.did_not_finish, + &template.did_not_finish, + ), + ( + "could_not_run", + english.could_not_run, + &template.could_not_run, + ), + ] { + assert_eq!(template.as_deref(), Some(ours), "{key}"); + } + let dir = concat!(env!("CARGO_MANIFEST_DIR"), "/docs/challenge-translations"); + let mut translations = BTreeMap::new(); + for entry in std::fs::read_dir(dir).unwrap() { + let path = entry.unwrap().path(); + if path.extension().is_some_and(|e| e == "toml") { + let tag = path.file_stem().unwrap().to_string_lossy().into_owned(); + let messages: Messages = toml::from_str(&std::fs::read_to_string(&path).unwrap()) + .unwrap_or_else(|e| panic!("{}: {e}", path.display())); + translations.insert(tag, messages); + } + } + validate_translations(&translations).unwrap(); + } + + #[test] + fn a_translation_that_could_not_be_served_is_refused() { + assert!(validate_translations(&translations()).is_ok()); + let one = |tag: &str, m: Messages| BTreeMap::from([(tag.to_string(), m)]); + assert!(validate_translations(&one("de-\"x", Messages::default())).is_err()); + assert!(validate_translations(&one("d", Messages::default())).is_err()); + assert!(validate_translations(&one( + "de", + Messages { + dir: Some("up".into()), + ..Messages::default() + } + )) + .is_err()); + let long = "x".repeat(MAX_MESSAGE_BYTES + 1); + assert!(validate_translations(&one( + "de", + Messages { + title: Some(long), + ..Messages::default() + } + )) + .is_err()); + assert!(validate_translations(&one("zh-Hant-TW", Messages::default())).is_ok()); + } + #[test] fn the_page_escapes_what_it_carries() { let issued = Issued { @@ -709,7 +1126,7 @@ mod tests { salt: "\">