#!/usr/bin/env python3
"""
triage-asan.py -- turn a pile of sanitizer reports into a list of distinct
                  defects, each classified.

Chapter 70 -- Vulnerability Research, scripts/

PURPOSE
    A fuzzing campaign produces crash artefacts. Artefacts are not defects: many
    artefacts map to one defect, one artefact can hide a second defect behind
    the first, and -- as chapter 70 section 3.7 measures -- a single defect can
    produce two or three reports that look nothing like each other.

    This script does the mechanical part of that reduction:

      1. Splits a file (or a directory of files) into individual reports.
      2. Extracts, for each: the error class, the access operation (READ or
         WRITE), the access size, the faulting address, the allocation it was
         adjacent to, and the stack.
      3. Computes a STACK HASH over the top N meaningful frames, so that
         reports from the same code site collapse into one bucket.
      4. Classifies each bucket: read or write, near-null or wild, adjacent or
         distant, and how much of the access looks attacker-influenced.

    It handles AddressSanitizer reports, UndefinedBehaviorSanitizer one-liners,
    and LeakSanitizer summaries. Both gcc's and clang's libsanitizer emit the
    same formats.

USAGE
    python3 -B triage-asan.py report.txt
    python3 -B triage-asan.py findings/*.txt
    python3 -B triage-asan.py --dir findings/
    ./fuzz_target crash-input 2>&1 | python3 -B triage-asan.py -
    python3 -B triage-asan.py --frames 5 --json report.txt

    --frames N   how many meaningful frames go into the stack hash (default 3)
    --json       machine-readable output instead of the table
    --verbose    print every report, not just one representative per bucket
    --dir D      treat D as a directory and read every file in it

    Use `python3 -B` so no __pycache__ is written next to the script.

REQUIREMENTS
    Python 3.7 or newer. No third-party packages, deliberately -- a triage tool
    that needs a virtualenv does not get run.

WHAT THIS WILL NOT TELL YOU
    * Whether a crash is exploitable. It deliberately emits no EXPLOITABLE /
      NOT_EXPLOITABLE verdict. Tools that do are wrong often enough that their
      output should never reach a report, and they systematically over-rate
      near-null writes and under-rate reads. What you get instead is the raw
      material for the assessment in chapter 70 section 3.8, which you make.
    * Whether the defect is in the target or in your harness. It prints the
      frames so you can see, and it flags when the top frame is in a file whose
      name looks like a harness, but it cannot know your project layout.
    * Whether the defect is REACHABLE. Nothing in a crash report answers that.
      Reachability is section 3.9 and it is established outside this tool.
    * How many defects you actually have. Stack hashing is a heuristic. It will
      merge two bugs that share a call site and split one bug reached by two
      paths. Treat the bucket count as a first approximation that a human then
      corrects -- which is the same relationship chapter 52 describes between a
      static sweep and a finding.
    * Anything about a crash it did not see. A campaign graded on exit codes
      misses UBSan-only findings entirely (section 3.7); feed it the LOG, not
      just the artefacts.
"""

import argparse
import hashlib
import json
import os
import re
import sys

# --------------------------------------------------------------------------
# Report splitting
#
# ASan brackets each report with a line of '=' characters. UBSan emits a single
# line with no delimiters at all, which is exactly why UBSan findings get lost:
# there is nothing to grep for that looks like a crash.
# --------------------------------------------------------------------------

ASAN_BANNER = re.compile(r"^={10,}\s*$")
ASAN_ERROR = re.compile(
    r"^\s*==(?P<pid>\d+)==\s*ERROR:\s*(?P<tool>\w+Sanitizer):\s*(?P<kind>[a-zA-Z0-9_-]+)"
    r"(?:\s+on\s+(?:unknown\s+)?address\s+(?P<addr>0x[0-9a-fA-F]+))?"
)
ASAN_ACCESS = re.compile(
    r"^\s*(?P<op>READ|WRITE)\s+of\s+size\s+(?P<size>\d+)\s+at\s+(?P<addr>0x[0-9a-fA-F]+)"
)
ASAN_REGION = re.compile(
    r"(?P<dist>\d+)\s+bytes\s+(?:to\s+the\s+)?(?P<side>right|left|inside)\s+of\s+"
    r"(?:the\s+)?(?P<rsize>\d+)-byte\s+region"
)
ASAN_REGION_INSIDE = re.compile(
    r"is\s+located\s+(?P<dist>\d+)\s+bytes\s+inside\s+of\s+(?P<rsize>\d+)-byte\s+region"
)
ASAN_FRAME = re.compile(
    r"^\s*#(?P<n>\d+)\s+0x[0-9a-fA-F]+\s+(?:in\s+(?P<func>.+?)\s+)?"
    r"(?P<loc>[^\s]+?)(?::(?P<line>\d+))?(?::\d+)?\s*$"
)
ASAN_SUMMARY = re.compile(r"^SUMMARY:\s*(?P<tool>\w+Sanitizer):\s*(?P<kind>[a-zA-Z0-9_-]+)")
UBSAN_LINE = re.compile(
    r"^(?P<file>[^\s:]+):(?P<line>\d+):(?P<col>\d+):\s*runtime error:\s*(?P<msg>.+)$"
)
LSAN_LEAK = re.compile(r"^(Direct|Indirect) leak of (?P<bytes>\d+) byte")

# Frames that carry no information about WHERE the bug is. Dropping them is the
# single most important decision in stack hashing: leave __interceptor_memcpy
# in and every overflow through memcpy collapses into one bucket.
NOISE_FRAME_PATTERNS = (
    "__interceptor_",
    "__asan_",
    "__ubsan_",
    "__sanitizer_",
    "sanitizer_common_interceptors",
    "asan_malloc_linux",
    "asan_interceptors",
    "ubsan_handlers",
    "_start",
    "__libc_start_main",
    "__libc_start_call_main",
    "libc.so",
    "ld-linux",
    "operator new",
    "operator delete",
    # _FORTIFY_SOURCE inlines memcpy through a static wrapper in this header,
    # so with fortification on, EVERY overflowing copy in the program reports
    # the same top frame -- a libc header, in a file the target does not own.
    # Measured on gcc 11.4 / glibc 2.35: without this entry the stack hash is
    # dominated by string_fortified.h:29 and the bucket's "top frame" column
    # points at libc rather than at the bug.
    "string_fortified.h",
    "bits/string",
    "bits/stdio",
)

# Files that are almost certainly the harness rather than the target. Used only
# to raise a flag for the human; the script does not act on it.
HARNESS_HINTS = ("fuzz", "harness", "driver", "LLVMFuzzer", "libfuzzer", "FuzzerLoop")

# Access classes that are reads-only by nature, for the note in the summary.
READ_ONLY_KINDS = ("use-after-poison",)


class Report(object):
    """One sanitizer report, parsed."""

    def __init__(self):
        self.tool = None            # AddressSanitizer / UndefinedBehaviorSanitizer / ...
        self.kind = None            # heap-buffer-overflow, SEGV, runtime error, ...
        self.op = None              # READ / WRITE / None
        self.size = None            # access size in bytes
        self.addr = None            # faulting address, int
        self.region_size = None     # size of the adjacent allocation
        self.region_dist = None     # distance from it
        self.region_side = None     # right / left / inside
        self.frames = []            # list of (func, loc, line)
        self.alloc_frames = []      # the allocation stack, when ASan prints one
        self.raw = []               # the report text, for --verbose
        self.source = None          # which file it came from
        self.ubsan_msg = None

    # -- derived properties ------------------------------------------------

    def meaningful_frames(self):
        """Frames that say something about where the bug is."""
        out = []
        for func, loc, line in self.frames:
            blob = "%s %s" % (func or "", loc or "")
            if any(p in blob for p in NOISE_FRAME_PATTERNS):
                continue
            if loc in (None, "", "??"):
                continue
            out.append((func, loc, line))
        return out

    def stack_hash(self, depth):
        """
        Hash the top `depth` meaningful frames.

        Function name plus source file plus line. The line number is included
        deliberately: it distinguishes two bugs in one function, at the cost of
        the hash changing whenever anyone edits the file above it. That is the
        right trade for a campaign against a fixed build, and the wrong one for
        a bug tracker that must span releases -- which is why the build is
        recorded alongside, not inferred from the hash.
        """
        frames = self.meaningful_frames()[:depth]
        if not frames:
            # Nothing usable. Fall back to the error kind so these still group
            # rather than each becoming its own singleton bucket.
            basis = "nostack|%s|%s" % (self.tool, self.kind)
        else:
            parts = []
            for func, loc, line in frames:
                parts.append("%s@%s:%s" % (func or "?", os.path.basename(loc or "?"),
                                           line if line is not None else "?"))
            basis = "|".join(parts)
        return hashlib.sha1(basis.encode("utf-8", "replace")).hexdigest()[:12]

    def looks_like_harness(self):
        frames = self.meaningful_frames()
        if not frames:
            return False
        top = "%s %s" % (frames[0][0] or "", frames[0][1] or "")
        return any(h.lower() in top.lower() for h in HARNESS_HINTS)

    # -- classification ----------------------------------------------------

    def address_class(self):
        """
        Where the faulting address sits. This is descriptive, not a verdict.

        The near-null band is the interesting distinction: a dereference of
        0x0 plus a small structure offset is almost always a null-pointer bug
        and almost always a denial of service only. A dereference of an address
        that looks like ASCII or like a repeated byte is a wild pointer that
        came from the input, and that is a completely different conversation.
        """
        if self.addr is None:
            return "unknown"
        a = self.addr
        if a < 0x10000:
            return "near-null"
        if a < 0x100000:
            return "low"
        # Repeated-byte or printable-ASCII addresses are the fingerprint of an
        # address built out of input bytes.
        b = a.to_bytes(8, "little").rstrip(b"\x00")
        if len(b) >= 4:
            if len(set(b)) == 1:
                return "wild (repeated byte 0x%02x -- looks input-derived)" % b[0]
            if all(0x20 <= c < 0x7F for c in b):
                try:
                    txt = b.decode("ascii")
                except UnicodeDecodeError:
                    txt = ""
                return "wild (printable %r -- looks input-derived)" % txt
        return "mapped"

    def distance_class(self):
        if self.region_dist is None:
            return "unknown"
        if self.region_side == "inside":
            return "inside the allocation (%d bytes in, %s-byte region)" % (
                self.region_dist, self.region_size)
        if self.region_dist == 0:
            return "adjacent (0 bytes past a %s-byte region)" % self.region_size
        if self.region_dist <= 64:
            return "near (%d bytes past a %s-byte region)" % (
                self.region_dist, self.region_size)
        return "distant (%d bytes past a %s-byte region)" % (
            self.region_dist, self.region_size)

    def control_signals(self):
        """
        Signals that bear on how much the attacker controls, each stated as an
        observation rather than a conclusion. The conclusion is section 3.8's
        job and it needs the source, which this script does not have.
        """
        sig = []
        if self.op == "WRITE":
            sig.append("WRITE -- changes program state; worth more than a read")
        elif self.op == "READ":
            sig.append("READ -- ask whether the value reaches an output the "
                       "attacker can observe; if so it is an info leak")
        if self.size is not None:
            if self.size > 16:
                sig.append("access size %d is larger than any scalar type, so "
                           "the length is almost certainly a variable, not a "
                           "constant -- check whether it comes from input"
                           % self.size)
            elif self.size in (1, 2, 4, 8):
                sig.append("access size %d matches a scalar type; the length "
                           "may be fixed even if the offset is not" % self.size)
        if self.region_dist == 0 and self.op == "WRITE":
            sig.append("write begins exactly at the end of the allocation -- "
                       "the most useful case for an attacker, because what "
                       "follows is predictable")
        ac = self.address_class()
        if ac == "near-null":
            sig.append("near-null address -- usually a denial of service only. "
                       "Say so rather than inflating it")
        elif ac.startswith("wild"):
            sig.append("address looks constructed from input bytes -- this is "
                       "a controlled pointer, not a stray one")
        if self.kind and "use-after-free" in self.kind:
            sig.append("use-after-free -- the questions are the width of the "
                       "window and whether the attacker can allocate into it")
        if self.kind and self.kind.startswith("SEGV") and self.op is None:
            sig.append("no access direction reported; read the disassembly at "
                       "the faulting PC to establish read or write")
        return sig


# --------------------------------------------------------------------------
# Parsing
# --------------------------------------------------------------------------

def parse_stream(text, source):
    """Yield Report objects found anywhere in `text`."""
    reports = []
    lines = text.splitlines()

    cur = None
    in_alloc_stack = False

    for raw in lines:
        line = raw.rstrip("\n")

        # --- UBSan: a single line, no delimiters. This is why they get lost.
        m = UBSAN_LINE.match(line)
        if m and cur is None:
            r = Report()
            r.tool = "UndefinedBehaviorSanitizer"
            r.kind = "runtime-error"
            r.ubsan_msg = m.group("msg").strip()
            r.frames = [(None, m.group("file"), int(m.group("line")))]
            r.raw = [line]
            r.source = source
            # UBSan messages carry their own sub-classification; keep it, since
            # "index N out of bounds" and "signed integer overflow" are very
            # different findings.
            msg = r.ubsan_msg.lower()
            if "out of bounds" in msg:
                r.kind = "ubsan-array-bounds"
                r.op = "READ/WRITE (UBSan does not say which)"
            elif "overflow" in msg:
                r.kind = "ubsan-integer-overflow"
            elif "null pointer" in msg:
                r.kind = "ubsan-null-deref"
            elif "misaligned" in msg:
                r.kind = "ubsan-misaligned"
            elif "shift" in msg:
                r.kind = "ubsan-shift"
            reports.append(r)
            continue

        m = ASAN_ERROR.match(line)
        if m:
            cur = Report()
            cur.tool = m.group("tool")
            cur.kind = m.group("kind")
            cur.source = source
            if m.group("addr"):
                cur.addr = int(m.group("addr"), 16)
            cur.raw.append(line)
            in_alloc_stack = False
            reports.append(cur)
            continue

        if cur is None:
            m = LSAN_LEAK.match(line)
            if m:
                cur = Report()
                cur.tool = "LeakSanitizer"
                cur.kind = "memory-leak"
                cur.size = int(m.group("bytes"))
                cur.source = source
                cur.raw.append(line)
                reports.append(cur)
            continue

        cur.raw.append(line)

        m = ASAN_ACCESS.match(line)
        if m:
            cur.op = m.group("op")
            cur.size = int(m.group("size"))
            cur.addr = int(m.group("addr"), 16)
            continue

        m = ASAN_REGION.search(line)
        if m:
            cur.region_dist = int(m.group("dist"))
            cur.region_side = m.group("side")
            cur.region_size = int(m.group("rsize"))
            continue
        m = ASAN_REGION_INSIDE.search(line)
        if m:
            cur.region_dist = int(m.group("dist"))
            cur.region_side = "inside"
            cur.region_size = int(m.group("rsize"))
            continue

        if "allocated by thread" in line or "freed by thread" in line or \
           "previously allocated by" in line:
            in_alloc_stack = True
            continue

        m = ASAN_FRAME.match(line)
        if m:
            func = m.group("func")
            loc = m.group("loc")
            line_no = int(m.group("line")) if m.group("line") else None
            frame = (func.strip() if func else None, loc, line_no)
            if in_alloc_stack:
                cur.alloc_frames.append(frame)
            else:
                cur.frames.append(frame)
            continue

        if ASAN_SUMMARY.match(line):
            cur = None
            in_alloc_stack = False
            continue

    return reports


# --------------------------------------------------------------------------
# Output
# --------------------------------------------------------------------------

def bucket(reports, depth):
    buckets = {}
    for r in reports:
        h = r.stack_hash(depth)
        buckets.setdefault(h, []).append(r)
    return buckets


def frame_line(frame):
    func, loc, line = frame
    where = loc if loc else "?"
    if line is not None:
        where = "%s:%d" % (where, line)
    return "%s  %s" % (func or "(unnamed)", where)


def print_table(buckets, depth, verbose):
    total = sum(len(v) for v in buckets.values())
    print("=" * 78)
    print("TRIAGE SUMMARY")
    print("=" * 78)
    print("reports parsed : %d" % total)
    print("distinct buckets: %d   (stack hash over %d meaningful frames)"
          % (len(buckets), depth))
    print("")
    print("%-14s %-6s %-26s %s" % ("BUCKET", "COUNT", "CLASS", "TOP FRAME"))
    print("-" * 78)

    order = sorted(buckets.items(), key=lambda kv: (-len(kv[1]), kv[0]))
    for h, rs in order:
        rep = rs[0]
        mf = rep.meaningful_frames()
        top = frame_line(mf[0]) if mf else "(no usable frames)"
        kind = rep.kind or "?"
        if rep.op in ("READ", "WRITE"):
            kind = "%s %s" % (kind, rep.op)
        print("%-14s %-6d %-26s %s" % (h, len(rs), kind[:26], top[:34]))

    print("")
    print("=" * 78)
    print("PER-BUCKET DETAIL")
    print("=" * 78)

    for h, rs in order:
        rep = rs[0]
        print("")
        print("--- bucket %s  (%d report%s) ---"
              % (h, len(rs), "" if len(rs) == 1 else "s"))
        print("  tool          : %s" % rep.tool)
        print("  class         : %s" % rep.kind)
        if rep.ubsan_msg:
            print("  ubsan message : %s" % rep.ubsan_msg)
        if rep.op:
            print("  operation     : %s%s" % (
                rep.op, "" if rep.size is None else " of size %d" % rep.size))
        if rep.addr is not None:
            print("  address       : 0x%x  [%s]" % (rep.addr, rep.address_class()))
        if rep.region_size is not None:
            print("  distance      : %s" % rep.distance_class())

        # Variation across the bucket. Two reports can share a code site and
        # still differ in access size or allocation size -- which is exactly
        # what happens when the attacker controls both the length and the
        # allocation, and it is a stronger signal than either report alone.
        sizes = sorted({r.size for r in rs if r.size is not None})
        regions = sorted({r.region_size for r in rs if r.region_size is not None})
        if len(sizes) > 1:
            print("  size varies   : %s across this bucket -- the access length"
                  % ", ".join(str(s) for s in sizes))
            print("                  is a VARIABLE the input controls, not a")
            print("                  constant. Strong signal; record it.")
        if len(regions) > 1:
            print("  region varies : %s -- the allocation being overflowed is"
                  % ", ".join(str(s) for s in regions))
            print("                  also input-influenced, so the attacker")
            print("                  chooses the size class. Record it too.")
        if rep.looks_like_harness():
            print("  !! WARNING    : the top meaningful frame looks like a")
            print("                  harness file. Read the stack before you")
            print("                  report this to anyone. See section 3.6.")
        print("  sources       : %s" % ", ".join(
            sorted({r.source for r in rs if r.source})) or "(stdin)")
        print("  stack (meaningful frames only):")
        mf = rep.meaningful_frames()
        if not mf:
            print("      (none -- the report had no frames with source information)")
        for i, f in enumerate(mf[:8]):
            marker = "->" if i < 1 else "  "
            print("   %s  #%d %s" % (marker, i, frame_line(f)))
        if rep.alloc_frames:
            print("  allocation site:")
            shown = 0
            for f in rep.alloc_frames:
                blob = "%s %s" % (f[0] or "", f[1] or "")
                if any(p in blob for p in NOISE_FRAME_PATTERNS):
                    continue
                print("      #%d %s" % (shown, frame_line(f)))
                shown += 1
                if shown >= 4:
                    break
        sigs = rep.control_signals()
        if sigs:
            print("  observations (NOT a verdict -- see section 3.8):")
            for s in sigs:
                # wrap at a sensible width without pulling in textwrap's
                # surprises around long tokens
                words, line = s.split(), "      - "
                for w in words:
                    if len(line) + len(w) + 1 > 76:
                        print(line)
                        line = "        " + w
                    else:
                        line += (w if line.endswith("- ") else " " + w)
                print(line)
        if verbose:
            print("  raw report:")
            for l in rep.raw:
                print("      | %s" % l)

    print("")
    print("=" * 78)
    print("This tool does not decide whether any of the above is exploitable,")
    print("and it cannot tell you whether any of it is REACHABLE. Both are")
    print("yours: chapter 70 sections 3.8 and 3.9.")
    print("=" * 78)


def to_json(buckets, depth):
    out = {"frames_hashed": depth, "buckets": []}
    for h, rs in sorted(buckets.items()):
        rep = rs[0]
        out["buckets"].append({
            "hash": h,
            "count": len(rs),
            "tool": rep.tool,
            "class": rep.kind,
            "operation": rep.op,
            "access_size": rep.size,
            "address": None if rep.addr is None else "0x%x" % rep.addr,
            "address_class": rep.address_class(),
            "region_size": rep.region_size,
            "region_distance": rep.region_dist,
            "region_side": rep.region_side,
            "ubsan_message": rep.ubsan_msg,
            "harness_suspected": rep.looks_like_harness(),
            "frames": [
                {"function": f[0], "file": f[1], "line": f[2]}
                for f in rep.meaningful_frames()[:8]
            ],
            "observations": rep.control_signals(),
            "sources": sorted({r.source for r in rs if r.source}),
        })
    return out


def main(argv):
    ap = argparse.ArgumentParser(
        description="Deduplicate and classify sanitizer reports.",
        epilog="This tool emits no exploitability verdict, on purpose.")
    ap.add_argument("files", nargs="*", help="report files, or - for stdin")
    ap.add_argument("--dir", help="read every file in this directory")
    ap.add_argument("--frames", type=int, default=3,
                    help="meaningful frames in the stack hash (default 3)")
    ap.add_argument("--json", action="store_true", help="JSON output")
    ap.add_argument("--verbose", action="store_true",
                    help="include the raw report text")
    args = ap.parse_args(argv[1:])

    paths = list(args.files)
    if args.dir:
        for name in sorted(os.listdir(args.dir)):
            p = os.path.join(args.dir, name)
            if os.path.isfile(p):
                paths.append(p)

    if not paths:
        ap.print_help()
        return 2

    reports = []
    for p in paths:
        if p == "-":
            reports.extend(parse_stream(sys.stdin.read(), "(stdin)"))
            continue
        try:
            with open(p, "r", encoding="utf-8", errors="replace") as fh:
                reports.extend(parse_stream(fh.read(), os.path.basename(p)))
        except OSError as exc:
            sys.stderr.write("cannot read %s: %s\n" % (p, exc))

    if not reports:
        sys.stderr.write(
            "no sanitizer reports found.\n"
            "  - ASan reports start with '==PID==ERROR: AddressSanitizer:'\n"
            "  - UBSan reports are a single 'runtime error:' line with no\n"
            "    banner at all, which is exactly why campaigns lose them.\n"
            "  - Did you capture stderr? Sanitizers write there, not stdout.\n")
        return 1

    buckets = bucket(reports, args.frames)

    if args.json:
        print(json.dumps(to_json(buckets, args.frames), indent=2))
    else:
        print_table(buckets, args.frames, args.verbose)
    return 0


if __name__ == "__main__":
    sys.exit(main(sys.argv))
