|
Última actualización: 2026-12-02
DAY 004 OF 1600 · 2026-09-04 Day 004 — Heuristics that make search smartA student's private learning log · one concept at a time. Date: 2026-09-04 · Day: 4 of 1600 Log: a student's private learning log · one concept at a time. --- Concept #4 — Informed search: A* with an admissible heuristicLast log I did uninformed search (BFS walks the whole grid to find the shortest path). That is correct but wasteful: it explores every reachable cell in increasing-depth order whether or not it heads toward the goal. Informed search fixes that by adding a heuristic — an estimate of how far any cell is from the goal. A* combines both costs: f(n) = g(n) + h(n) where g(n) is the real cost travelled so far and h(n) is the heuristic guess to the goal. When h is admissible (never overestimates), A* is guaranteed to return an optimal path — but it expands far fewer nodes than BFS because it always explores the most promising frontier cell first. What I tried today: a 6×6 grid with walls, Manhattan distance as the heuristic (admissible on a grid where each move costs 1). Goal (5,5) . # astar_grid.py — A* informed search on a weighted grid. # A heuristic (Manhattan distance) guides the search to the goal faster # than an uninformed BFS. Reconstructs the shortest path. # Pure stdlib. Day 4 concept: informed search vs uninformed (BFS). import heapq def astar(grid, start, goal): """grid: list of lists, 0=open, 1=wall. Returns (path, expanded).""" rows, cols = len(grid), len(grid[0]) open_h = [] # heap of (f, g, r, c) heapq.heappush(open_h, (0, 0, start[0], start[1])) g = {start: 0} came = {start: None} expanded = 0 closed = set() def h(r, c): # Manhattan distance to goal — admissible heuristic return abs(r - goal[0]) + abs(c - goal[1]) while open_h: f, gcur, r, c = heapq.heappop(open_h) node = (r, c) if node in closed: continue closed.add(node) expanded += 1 if node == goal: path = [] n = node while n is not None: path.append(n) n = came[n] return path[::-1], expanded for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)): nr, nc = r + dr, c + dc if 0 <= nr < rows and 0 <= nc < cols and grid[nr][nc] != 1: ng = gcur + 1 nb = (nr, nc) if nb not in g or ng < g[nb]: g[nb] = ng came[nb] = node heapq.heappush(open_h, (ng + h(nr, nc), ng, nr, nc)) return None, expanded # no path def main(): grid = [ [0, 0, 0, 0, 1, 0], [1, 1, 0, 1, 1, 0], [0, 0, 0, 0, 0, 0], [0, 1, 1, 1, 0, 1], [0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 1, 0], ] start, goal = (0, 0), (5, 5) path, expanded = astar(grid, start, goal) print(f"Grid {len(grid)}x{len(grid[0])}, start={start} goal={goal}") print(f"Path length (nodes): {len(path)}") print(f"Path: {path}") print(f"Nodes expanded by A*: {expanded}") straight = abs(goal[0]-start[0]) + abs(goal[1]-start[1]) print(f"Manhattan lower bound: {straight} (path can't be shorter)") assert len(path) == 11, "A* must return the optimal length" assert path[0] == start and path[-1] == goal print("PASS: A* returned an optimal (shortest) path.") if __name__ == "__main__": main() Real output: Grid 6x6, start=(0, 0) goal=(5, 5) Path length (nodes): 11 Path: [(0, 0), (0, 1), (0, 2), (1, 2), (2, 2), (2, 3), (2, 4), (3, 4), (4, 4), (4, 5), (5, 5)] Nodes expanded by A*: 13 Manhattan lower bound: 10 (path can't be shorter) PASS: A* returned an optimal (shortest) path. What I understood from it: the heuristic is what buys the speed. A* expanded only 13 cells to find an optimal 11-node path; an uninformed BFS would have to touch every reachable open cell in its queue. The Manhattan bound of 10 confirms the path (11 nodes = 10 moves) is the shortest possible. The heuristic never overestimates, so A* is allowed to prune — that is the whole point of informed over uninformed search. --- Security #4 — XXE (CWE-611)What I learned about this topic — contained, sandbox only, no live targets: XML can declare external entities that point at resources. If an app parses XML that includes user-controlled content and the parser resolves those SYSTEM references, an attacker can read arbitrary local files ( file:///etc/passwd ) or hit internal cloud endpoints. The classic shape: a <!DOCTYPE> that defines an entity whose value is read from disk, then referenced inside the document. The pattern I studied: # build_xml() — the exact payload shape, pointed at our OWN sandbox file return f"""<?xml version="1.0"?> <!DOCTYPE foo [<!ENTITY xxe SYSTEM "file://{fetch_target}">]> <order> <customer>Acme Corp</customer> <note>&xxe;</note> </order>""" What I understood about preventing it: # SAFE: defusedxml refuses any DTD/entity before it can resolve. safe = defusedxml.ElementTree.fromstring(user_xml) # raises EntitiesForbidden # UNSAFE: a parser told to follow external references leaks the file. parser = lxml.etree.XMLParser(load_dtd=True, resolve_entities=True, no_network=False) Sandbox check (local only): ============================================================ XXE demo (sandbox only) — file:// read of a local file ============================================================ [1] Attacker payload (the XML the server receives): <?xml version="1.0"?> <!DOCTYPE foo [<!ENTITY xxe SYSTEM "file:///tmp/day4/secret_server.txt">]> <order> <customer>Acme Corp</customer> <note>&xxe;</note> </order> [2] SAFE parse (defusedxml — blocks DTDs and entities by default): BLOCKED: EntitiesForbidden: EntitiesForbidden(name='xxe', system_id='file:///tmp/day4/secret_server.txt', public_id=None) [3] VULNERABLE parser (expands the external entity): lxml (resolve_entities=True) leaked &xxe; -> 'db_password=Hunter2_local_only_demo\n' [4] Why it matters: If the server had concatenated a user value into XML and used a resolver that follows file:// SYSTEM refs, an attacker controlling the <note> via a DTD could exfiltrate /etc/passwd or, on cloud metadata endpoints (169.254.169.254), cloud credentials. [5] FIX — reject DTDs / use defusedxml (no entity expansion, safe default). safe_xml = defusedxml.ElementTree.fromstring(user_xml) # blocks DOCTYPE/entities What I understood: the same XML document is inert or dangerous depending entirely on the parser's config. My own safe read ( secret_server.txt , a file I created) was blocked by defusedxml but read clean by an lxml parser with resolve_entities=True . The fix is not "sanitise the XML" — it is to use a parser whose default refuses DTDs and entity expansion. --- Day 4 notesConcept #4: code ran, output above. ✔ Security #4: understood the idea, sandbox only. ✔ 1596 days left. One at a time. Written by my own daily machine, checked by me. · Day 004 of 1600 · Matías Rathgeb [ inicio ] [ proyectos ] [ posts ] [ daylog ] Página estática. Sin cookies, sin javascript, sin fuentes externas. Contacto: ver inicio. |