Última actualización: 2026-12-02

DAY 008 OF 1600 · 2026-09-18

Day 008 — The model that memorises instead of learning

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

Concept #8 — Overfitting, and why a model must be checked on data it never saw

Yesterday's k-means and the gradient-descent day before were both about getting a model. Today is about the question I kept skipping: **how do I know the model is actually good?** The course (MA01, Model Evaluation and Validation) gives the honest answer, and it is uncomfortable: *a model that scores perfectly on the data it was trained on may be worthless.* The idea is overfitting . If I let a model be flexible enough, it can bend itself to hit every single training point — noise included. It has not learned the pattern , it has memorised the accidents . On data it has never seen, it then falls apart. The textbook way to catch this is to never score the model on the same rows it learned from . Split the data: fit on the train set, grade on a held-out test set. The gap between the two is the whole lesson. A flexible model drives train error toward zero; test error drops for a while, then turns around and climbs. That turning point is the sweet spot — and the thing I would never see if I only looked at training error. What I tried today: fit polynomials of growing degree to a noisy sine curve, and watch train error keep falling while test error starts rising. The least-squares solve (normal equations + Gaussian elimination, with partial pivoting) is written by hand — no libraries, so I can actually see what "fitting" is. #!/usr/bin/env python3 # overfit.py — overfitting demo: train error vs test error. # MA01 (Machine Learning), model evaluation block. Pure stdlib. import math import random def solve(matrix, rhs): """Solve A x = b via Gaussian elimination with partial pivoting.""" n = len(matrix) a = [row[:] + [rhs[i]] for i, row in enumerate(matrix)] for col in range(n): piv = max(range(col, n), key=lambda r: abs(a[r][col])) if abs(a[piv][col]) < 1e-12: raise ValueError("singular matrix") a[col], a[piv] = a[piv], a[col] for r in range(col + 1, n): factor = a[r][col] / a[col][col] for c in range(col, n + 1): a[r][c] -= factor * a[col][c] x = [0.0] * n for r in range(n - 1, -1, -1): s = a[r][n] - sum(a[r][c] * x[c] for c in range(r + 1, n)) x[r] = s / a[r][r] return x def poly_fit(xs, ys, degree): """Least-squares fit of a polynomial of given degree.""" m = degree + 1 xtx = [[0.0] * m for _ in range(m)] xty = [0.0] * m for x, y in zip(xs, ys): powers = [x ** k for k in range(m)] for i in range(m): xty[i] += powers[i] * y for j in range(m): xtx[i][j] += powers[i] * powers[j] return solve(xtx, xty) def poly_predict(coeffs, x): return sum(c * (x ** k) for k, c in enumerate(coeffs)) def rmse(coeffs, xs, ys): errs = [(poly_predict(coeffs, x) - y) ** 2 for x, y in zip(xs, ys)] return math.sqrt(sum(errs) / len(errs)) random.seed(42) TRUE = math.sin # 20 training points on [-3, 3] ... xs_train = [-3 + 6 * i / 19 for i in range(20)] ys_train = [TRUE(x) + random.gauss(0, 0.15) for x in xs_train] # ... and 20 fresh test points the model has never seen. xs_test = [-3 + 6 * (i + 0.5) / 20 for i in range(20)] ys_test = [TRUE(x) + random.gauss(0, 0.15) for x in xs_test] print(f"{'degree':>6} | {'train RMSE':>10} | {'test RMSE':>10}") print("-" * 34) for degree in (1, 3, 5, 9, 15): coeffs = poly_fit(xs_train, ys_train, degree) print(f"{degree:>6} | {rmse(coeffs, xs_train, ys_train):>10.4f} " f"| {rmse(coeffs, xs_test, ys_test):>10.4f}") Real output ( python3 overfit.py , Python 3.11.15): degree | train RMSE | test RMSE ---------------------------------- 1 | 0.4619 | 0.3932 3 | 0.1192 | 0.1430 5 | 0.0956 | 0.1620 9 | 0.0684 | 0.1874 15 | 0.0341 | 0.2313 What I understood from it: exactly the shape the theory predicts. Going from degree 1 to 3, both errors dropped (train 0.4619 → 0.1192, test 0.3932 → 0.1430) — the model was genuinely learning the curve. But past degree 3 they split apart : training error kept sliding down to 0.0341, while test error turned around and climbed to 0.2313 — worse than the plain degree-3 fit. The degree-15 model is not smarter; it is *memorising the 20 noise points* I fed it, and I can only see that because I graded it on 20 rows it never saw. If I had trusted training error, I would have shipped the worst model on the board. That is the trap: **the number that looks the best on the data you trained on is often the number that lies the most.** ---

Security #8 — JWT signature bypass (CWE-347)

What I learned about this topic — contained, sandbox only, no live targets: A JWT (JSON Web Token) is three base64 chunks joined by dots: header.payload.signature . The header names the signing algorithm ( alg ), the payload carries the claims ( {"sub": "alice", "role": "user"} ), and the signature is what proves the payload was not tampered with. The whole point of the token is that the server signs it with a key the client never sees. The class of bug — **CWE-347, improper verification of a cryptographic signature — appears when the server lets the token's own header** tell it how to verify. Two classic flavours:

alg: none — the header declares no signature. A careless verifier

reads alg , sees "none", and accepts the payload as-is, with an empty signature. The attacker forges any claim (e.g. role: admin ) without ever learning the secret.

algorithm confusion — the server is configured for RS256 (public-key)

but a library accepts HS256 (shared-key); the attacker signs with the public key as if it were the HMAC secret. The root cause is the same in both: **the attacker controls the alg field, so the attacker controls the verification logic.** I reproduced the none case in my own sandbox (/tmp), with two hand-written toy verifiers — one that trusts the header, one that fixes it. No network, no real target. The pattern I studied: # VULNERABLE: alg is read from attacker-controlled header header = json.loads(b64d(header_b64)) if header["alg"] == "none": # attacker sets this to "none" return json.loads(b64d(payload_b64)) # accepted, no signature check expected = hmac.new(SECRET, f"{header_b64}.{payload_b64}", hashlib.sha256) if hmac.compare_digest(b64d(sig_b64), expected.digest()): return json.loads(b64d(payload_b64)) What I understood about preventing it: pin the algorithm on the server , never from the token, and make the signature check mandatory — no branch can skip it. Compare with a constant-time function so the check itself does not leak. If only one algorithm is ever issued, an allowlist of exactly that one is the fix. # SAFE: server chooses the algorithm; header cannot override it header = json.loads(b64d(header_b64)) if header.get("alg") != "HS256": # allowlist — "none" is rejected raise ValueError("unsupported alg") expected = hmac.new(SECRET, f"{header_b64}.{payload_b64}", hashlib.sha256) if not hmac.compare_digest(b64d(sig_b64), expected.digest()): raise ValueError("invalid signature") Sandbox check (local only, /tmp, hand-made verifiers, no real tokens): $ python3 jwt_bypass.py legit user token : user forged token : eyJhbG...In0. (header alg=none, empty signature) vulnerable verifier says: {'sub': 'mallory', 'role': 'admin'} FIXED verifier says: REJECTED -> unsupported alg What I understood: the vulnerable verifier handed me role: admin without me knowing the secret at all — I only had to set alg to none and blank the signature. That is the lesson: the secret protects nothing if the server lets the attacker choose how it is checked. The forged token took a handful of bytes and zero crypto, which is why "we sign our tokens" means nothing on its own — the verification path is the real security boundary, and alg: none is the door that gets left open when nobody pins it. The fixed verifier rejected the exact same bytes with one line: an allowlist that says the algorithm is the server's decision, not the token's. ---

Day 8 notes

Concept #8: overfitting shown by hand — train RMSE fell to 0.0341 while test RMSE rose to 0.2313. ✔ Security #8: JWT signature bypass (CWE-347) understood, sandbox only (/tmp), no live targets. ✔ 1592 days left. One at a time.

Written by my own daily machine, checked by me.

← Back to the index

· Day 008 of 1600 · Matías Rathgeb


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


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