Skip to content

hypnguyen1209/offensive-claude / skills/web-pentest

web-pentest

Flagged

Use when pentesting a web application or API — injection, XSS/CSP, SSRF/cloud-metadata, HTTP desync & cache poisoning, SSTI/prototype-pollution/deserialization, JWT/OAuth/GraphQL/IDOR, business logic & single-packet race

scripts/session_entropy.py

View on GitHub
#!/usr/bin/env python3
"""session_entropy.py - offensive session/token predictability analyzer (stdlib only).

Harvest many session tokens (repeat login, register test accounts, capture guest tokens) and feed them
here to decide whether they are forgeable: encoding/structure detection, per-position charset + Shannon
entropy across the sample, and sequential-counter detection. Complements Burp Sequencer for quick triage
and for tokens Sequencer does not parse. See references/auth-api-access-control.md.

INPUT (tokens in capture order - order matters for sequential detection):
  session_entropy.py --tokens t1,t2,t3
  session_entropy.py --file tokens.txt        # one per line
  session_entropy.py --json '["t1","t2"]'
  cat tokens.txt | session_entropy.py         # stdin, one per line

EVIDENCE BAR: a PREDICTABLE verdict is a lead, not proof. [CONFIRMED] needs a forged/predicted token that
authenticates as ANOTHER user (or a demonstrably tiny keyspace) - not "entropy looks low". CWE-330/331.

Exit: 0 tokens look random (given the sample), 3 predictable (structured/sequential/low-entropy),
      2 error (no or malformed input).
"""
from __future__ import annotations

import argparse
import base64
import json
import math
import re
import sys
from dataclasses import dataclass, field
from typing import Optional

_UUID = re.compile(r"^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", re.I)
_HEX = re.compile(r"^[0-9a-f]+$", re.I)
_B64URL = re.compile(r"^[A-Za-z0-9_-]+={0,2}$")
_B64 = re.compile(r"^[A-Za-z0-9+/]+={0,2}$")
_DIGITS = re.compile(r"^[0-9]+$")


def _shannon(chars: list) -> float:
    """Shannon entropy (bits) of a multiset of characters."""
    if not chars:
        return 0.0
    n = len(chars)
    freq: dict = {}
    for c in chars:
        freq[c] = freq.get(c, 0) + 1
    return -sum((f / n) * math.log2(f / n) for f in freq.values())


def classify(tok: str) -> str:
    if _UUID.match(tok):
        # UUID v1 is time+MAC based (predictable); v4 is random
        return "uuid-v1(time-based!)" if tok[14] == "1" else f"uuid-v{tok[14]}"
    if tok.count(".") == 2 and all(_B64URL.match(p or "x") for p in tok.split(".")):
        return "jwt"
    if _DIGITS.match(tok):
        return "numeric"
    if _HEX.match(tok):
        return "hex"
    if _B64URL.match(tok) and not _B64.match(tok):
        return "base64url"
    if _B64.match(tok):
        return "base64"
    return "opaque"


def _as_int(tok: str, kind: str) -> Optional[int]:
    """Best-effort integer view of a token, for sequential-counter detection."""
    try:
        if kind == "numeric":
            return int(tok)
        if kind == "hex":
            return int(tok, 16)
        if kind in ("base64", "base64url"):
            pad = "-_" if kind == "base64url" else "+/"
            raw = base64.b64decode(tok + "=" * (-len(tok) % 4), altchars=pad.encode(), validate=False)
            return int.from_bytes(raw, "big") if raw else None
    except (ValueError, base64.binascii.Error):
        return None
    return None


@dataclass
class Report:
    n: int = 0
    kinds: dict = field(default_factory=dict)
    length_constant: bool = False
    lengths: list = field(default_factory=list)
    est_bits: float = 0.0
    fixed_positions: int = 0
    varying_positions: int = 0
    sequential: bool = False
    seq_detail: str = ""
    verdict: str = "unknown"
    reasons: list = field(default_factory=list)
    low_sample: bool = False

    def to_dict(self) -> dict:
        d = self.__dict__.copy()
        d["est_bits"] = round(self.est_bits, 1)
        return d


def analyze(tokens: list) -> Report:
    toks = [t.strip() for t in tokens if t and t.strip()]
    r = Report(n=len(toks))
    if r.n == 0:
        raise ValueError("no tokens provided")
    for t in toks:
        k = classify(t)
        r.kinds[k] = r.kinds.get(k, 0) + 1
    r.lengths = sorted({len(t) for t in toks})
    r.length_constant = len(r.lengths) == 1
    r.low_sample = r.n < 20

    # per-position charset + entropy across the sample (bounded by log2(n) with a small sample)
    minlen = min(len(t) for t in toks)
    for i in range(minlen):
        col = [t[i] for t in toks]
        h = _shannon(col)
        r.est_bits += h
        if len(set(col)) == 1:
            r.fixed_positions += 1
        else:
            r.varying_positions += 1

    # sequential-counter detection over capture order
    dominant = max(r.kinds, key=r.kinds.get)
    ints = [_as_int(t, classify(t)) for t in toks]
    ints = [x for x in ints if x is not None]
    if len(ints) == len(toks) and len(ints) >= 3:
        deltas = [b - a for a, b in zip(ints, ints[1:])]
        if all(d == deltas[0] for d in deltas) and deltas[0] != 0:
            r.sequential = True
            r.seq_detail = f"constant delta {deltas[0]} (perfect counter)"
        elif all(d > 0 for d in deltas) or all(d < 0 for d in deltas):
            r.sequential = True
            r.seq_detail = "monotonic (timestamp/counter-like)"

    # verdict
    if any(k.startswith("uuid-v1") for k in r.kinds):
        r.reasons.append("UUIDv1 is time+MAC based (predictable)")
    if r.sequential:
        r.reasons.append(f"sequential: {r.seq_detail}")
    if r.fixed_positions and r.varying_positions and r.varying_positions <= 6:
        r.reasons.append(f"only {r.varying_positions} of {minlen} char positions vary (tiny keyspace)")
    if not r.low_sample and r.est_bits < 64:
        r.reasons.append(f"estimated variability ~{r.est_bits:.0f} bits over {minlen} positions (< 64)")
    if dominant == "jwt":
        r.reasons.append("JWT structure - check alg/none & key confusion with jwt_forge.py, not entropy")

    r.verdict = "predictable" if any(x for x in r.reasons if not x.startswith("JWT")) else "random-looking"
    if r.low_sample and r.verdict == "random-looking":
        r.reasons.append(f"only {r.n} samples - collect >=20 before trusting 'random'")
    return r


def _print(r: Report) -> None:
    print(f"tokens: {r.n}  kinds: {', '.join(f'{k}={v}' for k, v in sorted(r.kinds.items()))}")
    print(f"length: {'constant ' + str(r.lengths[0]) if r.length_constant else 'varies ' + str(r.lengths)}")
    print(f"positions: {r.fixed_positions} fixed / {r.varying_positions} varying   "
          f"est. variability ~{r.est_bits:.0f} bits" + ("  (LOW SAMPLE)" if r.low_sample else ""))
    if r.sequential:
        print(f"sequential: YES - {r.seq_detail}")
    print(f"\nVERDICT: {r.verdict.upper()}")
    for why in r.reasons:
        print(f"  - {why}")
    if r.verdict == "predictable":
        print("  => try to PREDICT/FORGE another user's token, then prove it authenticates (CWE-330).")


def _read_tokens(args) -> list:
    if args.tokens:
        return args.tokens.split(",")
    if args.json:
        data = json.loads(args.json)
        if not isinstance(data, list):
            raise ValueError("--json must be a JSON array of strings")
        return [str(x) for x in data]
    if args.file:
        with open(args.file, "r", encoding="utf-8") as fh:
            return fh.read().splitlines()
    if not sys.stdin.isatty():
        return sys.stdin.read().splitlines()
    raise ValueError("no input: use --tokens / --file / --json or pipe tokens on stdin")


def main(argv: Optional[list] = None) -> int:
    p = argparse.ArgumentParser(description="Session/token predictability analyzer (stdlib).")
    p.add_argument("--tokens", help="comma-separated tokens (in capture order)")
    p.add_argument("--file", help="file with one token per line")
    p.add_argument("--json", help="JSON array of tokens")
    p.add_argument("--out-json", action="store_true", help="emit the report as JSON")
    args = p.parse_args(argv)
    try:
        toks = _read_tokens(args)
        r = analyze(toks)
    except (OSError, ValueError, json.JSONDecodeError) as exc:
        print(f"error: {exc}", file=sys.stderr)
        return 2
    if args.out_json:
        print(json.dumps(r.to_dict(), indent=2))
    else:
        _print(r)
    return 3 if r.verdict == "predictable" else 0


if __name__ == "__main__":
    raise SystemExit(main())
rea-analysis-optimizationmorluto/reaOptimize REA providers and shared analysis workflows for agent context, latency, CPU, and memory while preserving correctness and Evidence. Use for analysis bottlenecks and cache or query design; CI/test-suite optimization belongs to rea-ci-tests-audit.Stars: 472kUpdated Claude CodeCodexVerifiedInstall
rea-ci-tests-auditmorluto/reaAudit REA CI and test suites for correctness, fixture drift, false passes, and measured performance; use for suite or workflow investigations and efficiency changes, rather than ordinary feature testing or a single test failure.Stars: 472kUpdated Claude CodeCodexVerifiedInstall
rea-tool-designmorluto/reaAudit, investigate, design, or change REA investigation tools, CLI/MCP contracts, provider capabilities, and Evidence semantics.Stars: 472kUpdated Claude CodeCodexVerifiedInstall
ponytail-auditDietrichGebert/ponytailQuality audit of the whole repo: bugs, security, real load, missing tests, speed, and what to delete. Most important first.Stars: 194kUpdated Claude CodeCodexVerifiedInstall