Exploit databaseDownload repository ZIP
GH-385b5c680f69d5684b1ae42f2afaa78f
0xcyberstan/cve-2026-42533-config-scanner
Sources for CVE-2026-42533
5 sourcesPreferred order: Exploit-DB, Metasploit, then GitHub repositories by stars. Open preferred source
Repository files2
0xcyberstan/cve-2026-42533-config-scannerRevision f7df3164cf3b
Files from this repository share one source choice. Supporting files may cover other vulnerabilities.
nginx_capture_clobber_scan.py
Python · 21,055 bytes#!/usr/bin/env python3
"""Scan nginx configs for the complex_value two-pass capture-clobbering bug class.
A location is vulnerable when a capture ($1..$9 or a named capture) and a
regex `map` variable share one two-pass buffer, with the capture evaluated
first. The map's PCRE match clobbers the shared capture state between the LEN
and VALUE passes, so the buffer is sized and written inconsistently -> heap
overflow (map subject longer than the capture) or uninitialised-heap disclosure
(shorter). Read-only: it flags config preconditions, it does not exploit.
Usage:
nginx_capture_clobber_scan.py /etc/nginx/nginx.conf
nginx_capture_clobber_scan.py /etc/nginx/ # dir: nginx.conf or *.conf
nginx_capture_clobber_scan.py conf --json
nginx_capture_clobber_scan.py conf --no-includes
Exit code: 1 if any vulnerable config is found, 0 otherwise, 2 on usage error.
"""
import argparse
import glob
import json
import os
import re
import sys
# Directives whose module builds ONE request buffer for the whole family, so a
# capture ref and a map ref can be split across separate directives.
FAMILY_SINKS = {
"proxy_set_header": "proxy", "proxy_set_body": "proxy",
"fastcgi_param": "fastcgi", "scgi_param": "scgi",
"uwsgi_param": "uwsgi", "grpc_set_header": "grpc",
}
# Two-pass sinks that get their own buffer per directive (both refs must be in
# the same value to be exploitable).
SINGLE_SINKS_HTTP = {
"return", "set", "add_header", "add_trailer", "error_page", "sub_filter",
"proxy_redirect", "proxy_cookie_path", "proxy_cookie_domain", "proxy_method",
"proxy_pass", "fastcgi_pass", "scgi_pass", "uwsgi_pass", "grpc_pass",
"root", "alias", "access_log", "index", "expires", "store",
"auth_basic_user_file", "proxy_cache_key", "rewrite",
"limit_req_zone", "limit_conn_zone", "add_before_body", "add_after_body",
}
SINGLE_SINKS_STREAM = {
"return", "set", "proxy_pass", "proxy_bind", "proxy_ssl_name",
"proxy_ssl_certificate", "proxy_ssl_certificate_key",
"proxy_upload_rate", "proxy_download_rate", "ssl_certificate",
"ssl_certificate_key", "access_log", "pass", "hash", "limit_conn_zone",
}
REF_RE = re.compile(r"\$\{?(\d+|[A-Za-z_]\w*)\}?")
NAMED_GROUP_RE = re.compile(r"\(\?P?<([A-Za-z_]\w*)>|\(\?'([A-Za-z_]\w*)'")
def regex_capture_info(pattern):
"""(has_positional_group, [named_group_names]) for a raw regex."""
stripped = re.sub(r"\\.", "", pattern) # drop escapes so "\(" isn't a group
named = [a or b for a, b in NAMED_GROUP_RE.findall(stripped)]
bare = re.sub(r"\(\?:|\(\?<[=!]|\(\?[=!]", "", stripped)
return "(" in bare, named
def value_refs(value):
return [(m.group(1), m.start()) for m in REF_RE.finditer(value)]
# --- config parsing --------------------------------------------------------
def tokenize(text, filename):
"""(value, line, is_string, filename) tokens; regex backslashes preserved."""
tokens, i, line, n = [], 0, 1, len(text)
while i < n:
c = text[i]
if c == "\n":
line += 1; i += 1
elif c in " \t\r":
i += 1
elif c == "#":
while i < n and text[i] != "\n":
i += 1
elif c in "{};":
tokens.append((c, line, False, filename)); i += 1
elif c in "\"'":
quote, i, buf, start = c, i + 1, [], line
while i < n and text[i] != quote:
if text[i] == "\\" and i + 1 < n:
nxt = text[i + 1]
buf.append(nxt if nxt in (quote, "\\") else "\\" + nxt)
line += nxt == "\n"; i += 2
else:
line += text[i] == "\n"; buf.append(text[i]); i += 1
i += 1
tokens.append(("".join(buf), start, True, filename))
else:
buf, start = [], line
while i < n and text[i] not in " \t\r\n{};#\"'":
buf.append(text[i]); i += 1
tokens.append(("".join(buf), start, False, filename))
return tokens
def resolve_include(pattern, incl_dir):
root = pattern if os.path.isabs(pattern) else os.path.join(incl_dir, pattern)
return sorted(p for p in glob.glob(root) if os.path.isfile(p))
def load_tokens(path, seen, follow, missing):
"""Tokenize a file, inlining `include` directives."""
try:
with open(path, errors="replace") as fh:
raw = tokenize(fh.read(), path)
except OSError as exc:
missing.append("%s (%s)" % (path, exc))
return []
out, i = [], 0
while i < len(raw):
v, ln, s, _ = raw[i]
if follow and v == "include" and not s:
j, arg = i + 1, None
while j < len(raw) and not (raw[j][0] == ";" and not raw[j][2]):
arg = arg or raw[j][0]; j += 1
if arg:
targets = resolve_include(arg, os.path.dirname(os.path.abspath(path)))
if not targets and not glob.has_magic(arg):
missing.append("%s (included from %s:%d)" % (arg, path, ln))
for t in targets:
ap = os.path.abspath(t)
if ap not in seen:
seen.add(ap)
out += load_tokens(t, seen, follow, missing)
i = j + 1
else:
out.append((v, ln, s, path)); i += 1
return out
class Node:
__slots__ = ("name", "args", "line", "file", "children")
def __init__(self, name, args, line, file):
self.name, self.args, self.line, self.file = name, args, line, file
self.children = None # list[Node] for a block, else None
def parse(tokens):
pos = 0
def block():
nonlocal pos
nodes, cur = [], []
while pos < len(tokens):
v, _, s, _ = tokens[pos]
if v == "{" and not s:
pos += 1
if not cur: # anonymous block: skip
block(); continue
node = Node(cur[0][0], [t[0] for t in cur[1:]], cur[0][1], cur[0][3])
node.children = block()
nodes.append(node); cur = []
elif v == "}" and not s:
pos += 1; return nodes
elif v == ";" and not s:
if cur:
nodes.append(Node(cur[0][0], [t[0] for t in cur[1:]],
cur[0][1], cur[0][3]))
cur = []; pos += 1
else:
cur.append(tokens[pos]); pos += 1
return nodes
return block()
# --- fact collection -------------------------------------------------------
class MapInfo:
__slots__ = ("var", "input_var", "has_pos", "named", "line", "file")
def __init__(self, var, input_var, has_pos, named, line, file):
self.var, self.input_var, self.has_pos = var, input_var, has_pos
self.named, self.line, self.file = named, line, file
def collect_maps(nodes, maps):
"""Fill `maps` (var -> MapInfo) for regex maps; return their named captures."""
named_all = set()
for node in nodes:
if node.name == "map" and len(node.args) >= 2:
has_pos, named = False, []
for kv in (node.children or []):
if kv.name.startswith("~"):
pat = kv.name[2:] if kv.name.startswith("~*") else kv.name[1:]
hp, nm = regex_capture_info(pat)
has_pos, named = has_pos or hp, named + nm
if has_pos or named or any(
kv.name.startswith("~") for kv in (node.children or [])):
var = node.args[1].lstrip("$").strip("{}")
prev = maps.get(var)
if prev:
has_pos = has_pos or prev.has_pos
named = list(set(named) | set(prev.named))
maps[var] = MapInfo(var, node.args[0], has_pos, named,
node.line, node.file)
named_all |= set(named)
if node.children is not None:
named_all |= collect_maps(node.children, maps)
return named_all
def node_capture_source(node):
"""(positional_source, {named}) contributed by one node's regex."""
named, pos = set(), False
regex = None
if node.name == "location" and node.args:
a0 = node.args[0]
if a0 in ("~", "~*") and len(node.args) >= 2:
regex = node.args[1]
elif a0.startswith("~"):
regex = a0[2:] if a0.startswith("~*") else a0[1:]
elif node.name == "server_name":
for a in node.args:
if a.startswith("~"):
hp, nm = regex_capture_info(a[2:] if a.startswith("~*") else a[1:])
pos, named = pos or hp, named | set(nm)
elif node.name == "rewrite" and node.args:
regex = node.args[0]
elif node.name == "if":
for a in node.args:
a = a.strip("()")
if "(" in re.sub(r"\\.", "", a):
hp, nm = regex_capture_info(a)
pos, named = pos or hp, named | set(nm)
if regex is not None:
hp, nm = regex_capture_info(regex)
pos, named = pos or hp, named | set(nm)
return pos, named
# --- analysis --------------------------------------------------------------
class Finding:
__slots__ = ("file", "line", "scope", "directive", "captures", "map_vars",
"triggers", "reason", "cleared")
def __init__(self, file, line, scope, directive, captures, map_vars,
triggers, reason, cleared=False):
self.file, self.line, self.scope, self.directive = file, line, scope, directive
self.captures, self.map_vars, self.triggers = captures, map_vars, triggers
self.reason, self.cleared = reason, cleared
def key(self):
return (self.file, self.line, self.directive, tuple(sorted(self.map_vars)))
def to_dict(self):
return {"file": self.file, "line": self.line, "scope": self.scope,
"directive": self.directive, "captures": self.captures,
"map_vars": self.map_vars, "triggers": self.triggers,
"reason": self.reason}
def classify_buffer(values, named_set, maps, has_pos_source):
"""Refs in one buffer -> (captures, map_vars, exploitable).
Exploitable iff some capture is followed by a map var that was not already
in effect before it: a regex map runs (and clobbers) once then caches, so a
later new map changes the state the VALUE pass sees versus the LEN pass.
"""
seq, caps, mvars = [], [], []
for order, val in enumerate(values):
for name, pos in value_refs(val):
if name.isdigit():
if has_pos_source and 1 <= int(name) <= 9:
caps.append("$" + name); seq.append((order, pos, "cap", None))
else:
if name in maps:
mvars.append("$" + name); seq.append((order, pos, "map", name))
if name in named_set:
caps.append("$" + name); seq.append((order, pos, "cap", None))
seq.sort()
exploitable = False
for i, (_, _, kind, _) in enumerate(seq):
if kind != "cap":
continue
before = {v for _, _, k, v in seq[:i] if k == "map"}
after = {v for _, _, k, v in seq[i + 1:] if k == "map"}
if after - before:
exploitable = True
break
return sorted(set(caps)), sorted(set(mvars)), exploitable
def scope_label(node):
if node.name == "location":
return "location " + " ".join(node.args)
if node.name == "server":
return "server (%s:%d)" % (os.path.basename(node.file), node.line)
return node.name
def map_label(mi):
named = " named=(%s)" % ",".join(mi.named) if mi.named else ""
return "$%s <- regex-map%s on %s [%s:%d]" % (
mi.var, named, mi.input_var, os.path.basename(mi.file), mi.line)
def analyze_scope(node, ancestors, module, maps, named_global, any_map_pos, out):
"""Check one location/server for the vulnerable pattern; append Findings."""
pos_source = any_map_pos
named_set = set(named_global)
for nd in ancestors + [node]:
ps, nm = node_capture_source(nd)
pos_source, named_set = pos_source or ps, named_set | nm
for child in (nd.children or []):
if child.name in ("rewrite", "if", "server_name"):
ps, nm = node_capture_source(child)
pos_source, named_set = pos_source or ps, named_set | nm
direct = [c for c in (node.children or []) if c.children is None]
label = scope_label(node)
# (A) family buffers. Inheritance is replace-if-set: a location that defines
# any directive of a family drops the inherited ones.
local, inherited = {}, {}
for c in direct:
if c.name in FAMILY_SINKS:
local.setdefault(FAMILY_SINKS[c.name], []).append(c)
for nd in reversed(ancestors):
for c in (nd.children or []):
if c.children is None and c.name in FAMILY_SINKS:
inherited.setdefault(FAMILY_SINKS[c.name], []).append(c)
for fam in set(local) | set(inherited):
dirs = sorted(local.get(fam) or inherited.get(fam, []),
key=lambda d: (d.file, d.line))
caps, mvars, hit = classify_buffer([" ".join(d.args) for d in dirs],
named_set, maps, pos_source)
if not (caps and mvars):
continue
trig = [map_label(maps[v.lstrip("$")]) for v in mvars if v.lstrip("$") in maps]
anchor = dirs[0]
if hit:
reason = ("Capture %s and regex-map %s share the single per-request "
"buffer of the '%s' family (config order), capture measured "
"before the map clobbers r->captures -> LEN/VALUE mismatch -> "
"heap OOB write or info leak. Refs may be in separate directives."
% (",".join(caps), ",".join(mvars), fam))
else:
reason = ("Capture and regex-map share the '%s' family buffer but every "
"map runs before the capture(s), so both passes agree. Not "
"exploitable but fragile, do not reorder." % fam)
out.append(Finding(anchor.file, anchor.line, label,
"%s (family buffer)" % fam, caps, mvars, trig,
reason, cleared=not hit))
# (B) single-value sinks: both refs must be in the same directive value.
single = SINGLE_SINKS_STREAM if module == "stream" else SINGLE_SINKS_HTTP
for c in direct:
if c.name not in single:
continue
caps, mvars, hit = classify_buffer([" ".join(c.args)],
named_set, maps, pos_source)
if not (caps and mvars):
continue
trig = [map_label(maps[v.lstrip("$")]) for v in mvars if v.lstrip("$") in maps]
if hit:
reason = ("Capture %s appears before regex-map %s in '%s'. The map's "
"PCRE match clobbers the shared captures between the LEN and "
"VALUE passes -> size mismatch -> heap OOB write or info leak."
% (",".join(caps), ",".join(mvars), c.name))
else:
reason = ("Capture and regex-map coexist in '%s' but the map runs first "
"(or is the same map on both sides), so both passes agree. Not "
"exploitable but fragile, do not reorder." % c.name)
out.append(Finding(c.file, c.line, label, c.name, caps, mvars, trig,
reason, cleared=not hit))
def walk(nodes, ancestors, module, maps, named_global, any_map_pos, out):
for node in nodes:
mod = node.name if node.name in ("http", "stream") else module
if node.name in ("location", "server") and node.children is not None:
analyze_scope(node, ancestors, mod, maps, named_global, any_map_pos, out)
if node.children is not None:
walk(node.children, ancestors + [node], mod, maps,
named_global, any_map_pos, out)
def scan(roots, follow_includes):
seen, missing, trees = set(), [], []
for root in roots:
ap = os.path.abspath(root)
if ap in seen:
continue
seen.add(ap)
toks = load_tokens(root, seen, follow_includes, missing)
if toks:
trees.append(parse(toks))
maps, named_global = {}, set()
for tree in trees:
named_global |= collect_maps(tree, maps)
any_map_pos = any(m.has_pos for m in maps.values())
results = []
for tree in trees:
walk(tree, [], None, maps, named_global, any_map_pos, results)
uniq = {}
for f in results:
uniq.setdefault(f.key(), f)
results = list(uniq.values())
findings = [f for f in results if not f.cleared]
cleared = [f for f in results if f.cleared]
return findings, cleared, maps, missing
def expand_roots(paths):
roots = []
for p in paths:
if os.path.isdir(p):
cand = os.path.join(p, "nginx.conf")
roots.append(cand) if os.path.isfile(cand) else roots.extend(
sorted(glob.glob(os.path.join(p, "**", "*.conf"), recursive=True)))
else:
roots.append(p)
return roots
# --- reporting -------------------------------------------------------------
def wrap(text, width, indent):
lines, cur = [], ""
for w in text.split():
if len(cur) + len(w) + 1 > width:
lines.append(cur); cur = w
else:
cur = (cur + " " + w).strip()
if cur:
lines.append(cur)
return ("\n" + indent).join(lines)
def report(findings, cleared, maps, missing, as_json):
if as_json:
print(json.dumps({
"vulnerable": bool(findings),
"findings": [f.to_dict() for f in findings],
"cleared_safe_order": [f.to_dict() for f in cleared],
"regex_maps": [map_label(m) for m in maps.values()],
"missing_includes": missing,
}, indent=2))
return
color = sys.stdout.isatty()
red = lambda s: "\033[91m" + s + "\033[0m" if color else s
dim = lambda s: "\033[90m" + s + "\033[0m" if color else s
print("nginx capture-clobber scan (complex_value two-pass bug)")
print("regex maps (clobber triggers): %d vulnerable: %d cleared: %d"
% (len(maps), len(findings), len(cleared)))
for m in maps.values():
print(" " + dim(map_label(m)))
if missing:
print("\nwarning: %d include(s) unreadable, coverage may be incomplete:"
% len(missing))
for m in missing[:20]:
print(" - " + m)
if findings:
print("\n" + red("%d vulnerable configuration(s):" % len(findings)))
for i, f in enumerate(findings, 1):
print("\n[%d] %s:%d" % (i, f.file, f.line))
print(" scope : " + f.scope)
print(" directive : " + f.directive)
print(" captures : " + ", ".join(f.captures))
print(" map vars : " + ", ".join(f.map_vars))
for t in f.triggers:
print(" trigger : " + t)
print(" why : " + wrap(f.reason, 64, " " * 16))
else:
print("\nNo vulnerable configurations found.")
if cleared:
print("\n" + dim("cleared (capture + regex-map coexist but map runs first "
"-> safe, do not reorder):"))
for f in cleared:
print(" - %s:%d %s [%s + %s]" % (f.file, f.line, f.scope,
",".join(f.captures), ",".join(f.map_vars)))
if findings:
print("\nremediation:")
print(" 1. Apply the vendor patch. This is the only complete fix.")
print(" 2. Interim: never use a regex `map` variable in the same location/")
print(" buffer as a $1..$9 or named capture; avoid reusing (?P<name>)")
print(" across regex maps; split capture and map refs out of the same")
print(" proxy_set_header / fastcgi_param / etc. family.")
def main(argv):
ap = argparse.ArgumentParser(
description="Scan nginx configs for the complex_value capture-clobbering bug.")
ap.add_argument("paths", nargs="+", help="nginx.conf file(s) or directory(ies)")
ap.add_argument("--json", action="store_true", help="machine-readable output")
ap.add_argument("--no-includes", action="store_true",
help="do not follow include directives")
args = ap.parse_args(argv)
roots = expand_roots(args.paths)
if not roots:
print("no config files found in: " + ", ".join(args.paths), file=sys.stderr)
return 2
findings, cleared, maps, missing = scan(roots, follow_includes=not args.no_includes)
report(findings, cleared, maps, missing, args.json)
return 1 if findings else 0
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))