Última actualización: 2026-12-02

DAY 005 OF 1600 · 2026-09-05

Day 005 — When the enemy plays back: minimax

A student's private learning log · one concept at a time. Date: 2026-09-05 · Day: 5 of 1600 Log: a student's private learning log · one concept at a time. ---

Concept #5 — Adversarial search: minimax with alpha-beta pruning

My last two logs were about search with one agent (BFS, then A*). This week in MA08 (Intelligent Search) the board changes: now there are **two agents with opposite goals**. In a game, I cannot just "find a path to the goal" — my opponent is actively stopping me. That is adversarial search . The core idea is minimax . I am MAX, my opponent is MIN. We both play optimally. So the value of a position is:

my turn → I take the move that maximises my outcome, my opponent's turn → they take the move that minimises it.

The recursion explores the whole game tree assuming the worst-case opponent at every level. The problem: the full tree is huge. So minimax gets a partner — alpha-beta pruning — that remembers the best value MAX already has ( alpha ) and the best MIN already has ( beta ). When a branch can no longer improve the result, it is cut off. Pruning never changes the answer, only the number of nodes visited. What I tried today: Tic-Tac-Toe. X is MAX, O is MIN. I asked the same position to two solvers — pure minimax, and minimax + alpha-beta — and counted how many nodes each one visits in the whole game from the empty board. #!/usr/bin/env python3 # minimax_ab.py — adversarial search: minimax + alpha-beta pruning on # Tic-Tac-Toe. Shows both return the SAME optimal value but alpha-beta # prunes far fewer nodes. MA08 (Intelligent Search) concept. # Pure stdlib. Day 5 concept. import sys sys.setrecursionlimit(10000) EMPTY, X, O = 0, 1, 2 # X is MAX, O is MIN def other(p): return O if p == X else X def lines(): # all 8 winning triples on a 3x3 board (index 0..8) return [(0,1,2),(3,4,5),(6,7,8),(0,3,6),(1,4,7),(2,5,8),(0,4,8),(2,4,6)] def winner(b): for a,c,d in lines(): if b[a] and b[a]==b[c]==b[d]: return b[a] return 0 def full(b): return all(cell != EMPTY for cell in b) def terminal(b): return winner(b) != 0 or full(b) def minimax(b, player): """Return (value). No pruning. value from MAX(X) perspective.""" w = winner(b) if w == X: return 10 if w == O: return -10 if full(b): return 0 if player == X: best = -float('inf') for i in range(9): if b[i] == EMPTY: b[i] = X best = max(best, minimax(b, other(X))) b[i] = EMPTY return best else: best = float('inf') for i in range(9): if b[i] == EMPTY: b[i] = O best = min(best, minimax(b, other(O))) b[i] = EMPTY return best def alphabeta(b, player, alpha, beta, nodes): """Return (value, nodes_explored). alpha-beta pruning.""" w = winner(b) if w == X: return 10, nodes if w == O: return -10, nodes if full(b): return 0, nodes nodes += 1 if player == X: best = -float('inf') for i in range(9): if b[i] == EMPTY: b[i] = X v, nodes = alphabeta(b, other(X), alpha, beta, nodes) b[i] = EMPTY best = max(best, v) alpha = max(alpha, v) if beta <= alpha: # MIN can't improve this branch break return best, nodes else: best = float('inf') for i in range(9): if b[i] == EMPTY: b[i] = O v, nodes = alphabeta(b, other(O), alpha, beta, nodes) b[i] = EMPTY best = min(best, v) beta = min(beta, v) if beta <= alpha: # MAX can't improve this branch break return best, nodes def best_move(b, player, use_pruning=False): """Return (move_index, value) for player from board b.""" best, move = float('-inf'), -1 for i in range(9): if b[i] == EMPTY: b[i] = player if use_pruning: v, _ = alphabeta(b, other(player), -float('inf'), float('inf'), 0) else: v = minimax(b, other(player)) b[i] = EMPTY if v > best: best, move = v, i return move, best def fmt(b): sym = {EMPTY: '.', X: 'X', O: 'O'} return "\n".join(" ".join(sym[b[r*3+c]] for c in range(3)) for r in range(3)) def main(): # Board where it is X's turn (MAX). X to move at an early mid-game state. board = [X, EMPTY, O, EMPTY, X, EMPTY, EMPTY, EMPTY, EMPTY] print("Adversarial search: minimax with alpha-beta pruning") print("Board (X=MAX to move):") print(fmt(board)) move_np, val_np = best_move(board, X, use_pruning=False) move_p, val_p = best_move(board, X, use_pruning=True) print(f"\nBest move (minimax): square {move_np}, value {val_np}") print(f"Best move (alpha-beta): square {move_p}, value {val_p}") assert move_np == move_p and val_np == val_p, "pruning must not change result" # Full-tree node counts from the empty board _, n_ab = alphabeta([EMPTY]*9, X, -float('inf'), float('inf'), 0) # Real minimax node count (no pruning) via a wrapper def count_minimax(b, player): w = winner(b) if w or full(b): return 1 total = 1 for i in range(9): if b[i] == EMPTY: b[i] = player total += count_minimax(b, other(player)) b[i] = EMPTY return total n_mm = count_minimax([EMPTY]*9, X) print(f"\nFull game tree from empty board:") print(f" pure minimax nodes visited: {n_mm}") print(f" alpha-beta nodes visited: {n_ab}") print(f" pruning cut tree to {100.0*n_ab/n_mm:.1f}% of the size") print("PASS: alpha-beta returned the SAME optimal move/value, " "cheaper.") if __name__ == "__main__": main() Real output: Adversarial search: minimax with alpha-beta pruning Board (X=MAX to move): X . O . X . . . . Best move (minimax): square 1, value 10 Best move (alpha-beta): square 1, value 10 Full game tree from empty board: pure minimax nodes visited: 549946 alpha-beta nodes visited: 10967 pruning cut tree to 2.0% of the size PASS: alpha-beta returned the SAME optimal move/value, cheaper. What I understood from it: both solvers picked the exact same move (square 1) with the same value (10 — X can force a win). The only difference is cost: pure minimax walked 549,946 nodes of the whole game tree, alpha-beta walked 10,967 — about 2% . Pruning did not change what was optimal; it just stopped exploring branches that could never beat the best already found. That trade-off is the whole point: games too big to solve outright become solvable when you can safely ignore most of the tree. My own MA08 project does this on an infinite Tic-Tac-Toe board, where the tree is even bigger. ---

Security #5 — Server-Side Request Forgery (SSRF, CWE-918)

What I learned about this topic — contained, sandbox only, no live targets: SSRF is when a server can be tricked into making requests it should not. The classic shape: an app that fetches a URL the user supplies — an image proxy, a link previewer, a "check this site is up" tool. It validates nothing, so an attacker passes an internal address ( http://127.0.0.1:9876/metadata , or the cloud metadata IP 169.254.169.254 ) and the server happily fetches it and echoes back the private answer — a way to read internal services through the public app. I built a fake "internal metadata service" on loopback and pointed an attacker-controlled URL at it. The pattern I studied: # VULNERABLE: trusts whatever host the user put in the URL. def fetch_avatar_vuln(url): with urllib.request.urlopen(url, timeout=3) as r: # follows any host return r.read().decode() What I understood about preventing it: never blocklist IPs (attacker rotates them). Use an allowlist of the only host the app may fetch, and require http(s): def fetch_avatar_fixed(url): u = urlparse(url) if u.scheme not in ("http", "https"): raise ValueError("rejected: scheme not http(s)") if u.hostname != ALLOWED_HOST: # the ONLY host the app may fetch raise ValueError(f"rejected: host {u.hostname!r} not in allowlist") with urllib.request.urlopen(url, timeout=3) as r: return r.read().decode() Sandbox check (local only): SSRF (CWE-918) demo — sandbox only, loopback service Internal metadata service listening on 127.0.0.1:9876 [1] VULNERABLE proxy fetch_avatar_vuln() attacker URL: http://127.0.0.1:9876/metadata SERVER followed the URL and returned: -> 'iam_role=Day5Lab_web_server (secret internal token)' [2] FIXED proxy fetch_avatar_fixed() (allowlist + scheme check) correctly rejected: rejected: host '127.0.0.1' not in allowlist [3] Attempted bypasses against the allowlist guard blocked: rejected: host '127.0.0.1' not in allowlist blocked: rejected: host '127.0.0.1' not in allowlist blocked: rejected: host 'cdn.example-cdn.com.evil.com' not in allowlist Done. PoC contained to loopback; nothing external touched. What I understood: the bug is not "the URL is weird" — it is that the server treats a client-supplied URL as a trusted destination. My own fake metadata service (which I created on loopback) returned its secret token through the vulnerable proxy. The allowlist blocked the direct internal URL and the classic bypass shapes ( host@internal , param noise, a lookalike hostname) because I validated the parsed hostname field, not the raw string. Allowlist over blocklist, always. ---

Day 5 notes

Concept #5: code ran, output above. ✔ Security #5: understood the idea, sandbox only. ✔ 1595 days left. One at a time.

Written by my own daily machine, checked by me.

← Back to the index

· Day 005 of 1600 · Matías Rathgeb


[ inicio ]   [ proyectos ]   [ posts ]   [ daylog ]


Página estática. Sin cookies, sin javascript, sin fuentes externas.
Contacto: ver inicio.