Exploit database

GH-abe2ad96b80b02d002d3372d650c1c9f

craigsblackie/cve-2026-88771-netscaler

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2026-88771

9 sources

Preferred order: Exploit-DB, Metasploit, then GitHub repositories by stars. Open preferred source

Repository files68Next files →

Files from this repository share one source choice. Supporting files may cover other vulnerabilities.

analysis/fde_function_diff.py

Python · 7,598 bytes
#!/usr/bin/env python3
"""Align stripped ELF functions using .eh_frame FDEs and normalized opcodes.

This is intentionally lightweight: it uses readelf to recover compiler-emitted
function ranges and Capstone to erase link-address noise.  It is useful for the
large, stripped NetScaler nsppe images where symbol-based comparison fails.
"""

from __future__ import annotations

import argparse
import hashlib
import json
import re
import struct
import subprocess
from collections import Counter
from difflib import SequenceMatcher
from pathlib import Path

from capstone import Cs, CS_ARCH_X86, CS_MODE_64
from capstone.x86 import X86_OP_IMM, X86_OP_MEM, X86_OP_REG


FDE_RE = re.compile(r"FDE cie=.* pc=([0-9a-f]+)\.\.([0-9a-f]+)")


def fde_ranges(path: Path) -> list[tuple[int, int]]:
    text = subprocess.check_output(
        ["readelf", "--debug-dump=frames", str(path)], text=True,
        errors="replace",
    )
    ranges = [(int(a, 16), int(b, 16)) for a, b in FDE_RE.findall(text)]
    # Some binaries contain duplicate FDE descriptions; preserve address order.
    return sorted(set(ranges))


def load_segments(path: Path) -> tuple[bytes, list[tuple[int, int, int]]]:
    data = path.read_bytes()
    ident = data[:16]
    if ident[:4] != b"\x7fELF" or ident[4] != 2 or ident[5] != 1:
        raise ValueError(f"{path}: expected little-endian ELF64")
    vals = struct.unpack_from("<HHIQQQIHHHHHH", data, 16)
    phoff, phentsize, phnum = vals[4], vals[8], vals[9]
    segments = []
    for i in range(phnum):
        off = phoff + i * phentsize
        p_type, p_flags, p_offset, p_vaddr, _, p_filesz, _, _ = struct.unpack_from(
            "<IIQQQQQQ", data, off
        )
        if p_type == 1 and p_filesz and (p_flags & 1):
            segments.append((p_vaddr, p_vaddr + p_filesz, p_offset))
    return data, segments


def va_bytes(data: bytes, segments: list[tuple[int, int, int]], start: int, end: int) -> bytes:
    for lo, hi, fileoff in segments:
        if lo <= start < end <= hi:
            pos = fileoff + start - lo
            return data[pos:pos + end - start]
    return b""


def normalized_function(md: Cs, code: bytes, address: int) -> str:
    result = []
    consumed = 0
    for ins in md.disasm(code, address):
        consumed += ins.size
        operands = []
        for op in ins.operands:
            if op.type == X86_OP_REG:
                operands.append("r:" + ins.reg_name(op.reg))
            elif op.type == X86_OP_IMM:
                # Branch destinations and link-time addresses are noise. Preserve
                # small scalar constants because bounds checks are security-relevant.
                value = op.imm
                if ins.group(1) or ins.group(2):  # jump or call groups
                    operands.append("target")
                elif -0x10000 <= value <= 0x10000:
                    operands.append(f"i:{value}")
                else:
                    operands.append("i:ADDR")
            elif op.type == X86_OP_MEM:
                mem = op.mem
                base = ins.reg_name(mem.base) if mem.base else "-"
                index = ins.reg_name(mem.index) if mem.index else "-"
                disp = mem.disp
                # NetScaler's statically linked globals are often addressed as
                # [reg + a large fixed image/BSS offset], not only RIP-relative.
                # Preserve ordinary structure fields, but erase offsets above
                # 8 KiB as link-layout noise.
                if base == "rip" or abs(disp) > 0x2000:
                    disp_s = "ADDR"
                else:
                    disp_s = str(disp)
                operands.append(f"m:{base}:{index}:{mem.scale}:{disp_s}")
            else:
                operands.append(f"o:{op.type}")
        result.append(ins.mnemonic + " " + ",".join(operands))
    if consumed != len(code):
        result.append(f"TRAILING:{len(code)-consumed}")
    return "\n".join(result)


def fingerprints(path: Path) -> list[dict[str, object]]:
    data, segments = load_segments(path)
    md = Cs(CS_ARCH_X86, CS_MODE_64)
    md.detail = True
    rows = []
    for start, end in fde_ranges(path):
        code = va_bytes(data, segments, start, end)
        if not code:
            continue
        norm = normalized_function(md, code, start)
        rows.append({
            "start": start,
            "end": end,
            "size": end - start,
            "raw": hashlib.sha256(code).hexdigest(),
            "norm": hashlib.sha256(norm.encode()).hexdigest(),
            "tokens": norm.count("\n") + 1,
        })
    return rows


def cached_fingerprints(path: Path, cache_dir: Path | None) -> list[dict[str, object]]:
    if cache_dir is None:
        return fingerprints(path)
    cache_dir.mkdir(parents=True, exist_ok=True)
    stat = path.stat()
    key = hashlib.sha256(
        f"{path.resolve()}:{stat.st_size}:{stat.st_mtime_ns}:v3".encode()
    ).hexdigest()[:20]
    cache = cache_dir / f"fde-{key}.json"
    if cache.exists():
        return json.loads(cache.read_text())
    rows = fingerprints(path)
    cache.write_text(json.dumps(rows, separators=(",", ":")))
    return rows


def main() -> int:
    ap = argparse.ArgumentParser()
    ap.add_argument("old", type=Path)
    ap.add_argument("new", type=Path)
    ap.add_argument("--report", type=Path)
    ap.add_argument("--cache-dir", type=Path)
    ap.add_argument("--context", type=int, default=2)
    args = ap.parse_args()

    old = cached_fingerprints(args.old, args.cache_dir)
    new = cached_fingerprints(args.new, args.cache_dir)
    old_counts = Counter(x["norm"] for x in old)
    new_counts = Counter(x["norm"] for x in new)
    # Repeated tiny thunk fingerprints confuse SequenceMatcher. Make unique
    # functions anchors; tag repeats with a neutral value.
    old_seq = [
        x["norm"] if old_counts[x["norm"]] <= 1 and new_counts[x["norm"]] <= 1 else "REPEAT"
        for x in old
    ]
    new_seq = [
        x["norm"] if old_counts[x["norm"]] <= 1 and new_counts[x["norm"]] <= 1 else "REPEAT"
        for x in new
    ]
    # Let SequenceMatcher suppress the deliberately common REPEAT token. With
    # autojunk disabled, thousands of identical compiler thunks cause O(n^2)
    # matching without adding useful anchors.
    matcher = SequenceMatcher(None, old_seq, new_seq, autojunk=True)
    opcodes = matcher.get_opcodes()

    lines = [
        f"old_functions={len(old)} new_functions={len(new)}",
        f"unique_normalized_matches={sum(1 for h,c in old_counts.items() if c == new_counts[h] == 1)}",
    ]
    changed = 0
    for tag, i1, i2, j1, j2 in opcodes:
        if tag == "equal":
            continue
        changed += 1
        lines.append(f"\n[{changed}] {tag} old[{i1}:{i2}] new[{j1}:{j2}]")
        for side, rows, lo, hi in (("OLD", old, i1, i2), ("NEW", new, j1, j2)):
            lines.append(side)
            first = max(0, lo - args.context)
            last = min(len(rows), hi + args.context)
            for index in range(first, last):
                row = rows[index]
                mark = "*" if lo <= index < hi else " "
                lines.append(
                    f" {mark} 0x{row['start']:x}..0x{row['end']:x} "
                    f"size={row['size']} tokens={row['tokens']} norm={str(row['norm'])[:12]}"
                )
    lines.insert(2, f"non_equal_regions={changed}")
    output = "\n".join(lines) + "\n"
    if args.report:
        args.report.write_text(output)
    else:
        print(output, end="")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())