|
Última actualización: 2026-12-02
DAY 018 OF 1600 · 2026-10-17 Day 018 — A p-value I computed with my own hands, and a request two servers could not agree onA student's private learning log · one concept at a time. Date: 2026-10-17 · Day: 18 of 1600 Log: a student's private learning log · one concept at a time. --- Concept #18 — The one-sample t-test: the p-value is an area, not a verdictYesterday I measured that the 95% interval built with 1.96 misses more often than it promises when the sample is small, because s is itself noisy. Today's block (MA02, Probability and Statistics , Week 5 — Hypothesis Testing ) is the same defect seen from the other side. A test compares an observed mean to a claimed value: t = (x_bar - mu0) / (s / sqrt(n)) df = n - 1 and then the p-value answers a narrow question: **if the null hypothesis were true, how often would a sample produce a t at least this extreme?** Small p means the data are unlikely under the claim — not that the claim is false, and not that the effect is big. The part I did not want to take on faith was the number itself. The course says "two-sided p ≈ 0.038 (from t19)" and moves on. I do not have scipy here, so I wrote the t distribution myself: the survival probability is a regularised incomplete beta, P(|T| >= |t|) = I_{df/(df+t^2)}(df/2, 1/2) , which I computed with a continued fraction (modified Lentz). Then I ran the three course exercises through it, and after that I measured the promise the p-value makes: that a test at alpha = 0.05 rejects a true null only 5% of the time. #!/usr/bin/env python3 # ttest.py - one-sample t-test, with the p-value computed from scratch. # MA02 (Probability and Statistics), Week 5: Hypothesis Testing. # Pure stdlib: no numpy, no scipy. import math import random def mean(xs): return sum(xs) / len(xs) def stdev(xs): m = mean(xs) return math.sqrt(sum((x - m) ** 2 for x in xs) / (len(xs) - 1)) def betacf(a, b, x): # continued fraction for I_x(a,b), modified Lentz method tiny = 1e-30 qab, qap, qam = a + b, a + 1.0, a - 1.0 c = 1.0 d = 1.0 - qab * x / qap if abs(d) < tiny: d = tiny d = 1.0 / d h = d for m in range(1, 300): m2 = 2 * m aa = m * (b - m) * x / ((qam + m2) * (a + m2)) d = 1.0 + aa * d if abs(d) < tiny: d = tiny c = 1.0 + aa / c if abs(c) < tiny: c = tiny d = 1.0 / d h *= d * c aa = -(a + m) * (qab + m) * x / ((a + m2) * (qap + m2)) d = 1.0 + aa * d if abs(d) < tiny: d = tiny c = 1.0 + aa / c if abs(c) < tiny: c = tiny d = 1.0 / d delta = d * c h *= delta if abs(delta - 1.0) < 1e-15: break return h def betai(a, b, x): if x <= 0.0: return 0.0 if x >= 1.0: return 1.0 lbeta = (math.lgamma(a + b) - math.lgamma(a) - math.lgamma(b) + a * math.log(x) + b * math.log(1.0 - x)) front = math.exp(lbeta) / a if x < (a + 1.0) / (a + b + 2.0): return front * betacf(a, b, x) return 1.0 - math.exp(lbeta) / b * betacf(b, a, 1.0 - x) def t_sf_two_sided(t, df): """P(|T| >= |t|) for a t distribution with df degrees of freedom.""" if df <= 0: raise ValueError("df must be positive") x = df / (df + t * t) return betai(df / 2.0, 0.5, x) def one_sample_t(sample, mu0): n = len(sample) m = mean(sample) s = stdev(sample) t = (m - mu0) / (s / math.sqrt(n)) return t, n - 1, t_sf_two_sided(t, n - 1) def verdict(p, alpha): return "reject H0" if p < alpha else "keep H0" def course_checks(): # (label, x_bar, s, n, mu0, alpha, p the course prints) cases = [ ("XIII screen time", 5.6, 1.2, 20, 5.0, 0.05, 0.038), ("XIV battery", 7.4, 0.8, 16, 8.0, 0.01, 0.0085), ("XV steps", 7500.0, 900.0, 25, 8000.0, 0.05, 0.010), ] out = [] for name, xbar, s, n, mu0, alpha, claimed in cases: t = (xbar - mu0) / (s / math.sqrt(n)) df = n - 1 out.append((name, t, df, t_sf_two_sided(t, df), alpha, claimed)) return out def type_one_rate(n, trials, seed): """How often does a test at alpha=0.05 reject a null that is TRUE?""" rnd = random.Random(seed) true_mu, sigma, alpha = 50.0, 5.0, 0.05 rej_t = rej_z = 0 for _ in range(trials): xs = [rnd.gauss(true_mu, sigma) for _ in range(n)] t, df, p = one_sample_t(xs, true_mu) if p < alpha: rej_t += 1 # same data, judged with the normal 1.96 rule instead of t m, s = mean(xs), stdev(xs) z = (m - true_mu) / (s / math.sqrt(n)) if abs(z) > 1.96: rej_z += 1 return rej_t / trials, rej_z / trials def self_test(): # the t distribution with huge df is the normal: two-sided 5% cut = 1.96 assert abs(t_sf_two_sided(1.96, 10 ** 7) - 0.05) < 1e-4 # symmetry: P(|T| >= t) == P(|T| >= -t) assert abs(t_sf_two_sided(2.237, 19) - t_sf_two_sided(-2.237, 19)) < 1e-12 # a t of zero must give a p of exactly one assert abs(t_sf_two_sided(0.0, 5) - 1.0) < 1e-12 print("self-test: ok") if __name__ == "__main__": self_test() print("\ncourse exercises, p-value recomputed from the t density:") print(f" {'case':18s} {'t':>8s} {'df':>3s} {'p (mine)':>9s} " f"{'p (course)':>10s} {'alpha':>5s} decision") for name, t, df, p, alpha, claimed in course_checks(): print(f" {name:18s} {t:8.3f} {df:3d} {p:9.4f} {claimed:10.4f} " f"{alpha:5.2f} {verdict(p, alpha)}") print("\nis alpha really 5%? 2000 samples from a TRUE null (mu=50, sigma=5):") print(f" {'n':>4s} {'reject w/ t':>12s} {'reject w/ 1.96':>15s}") for n in (10, 30, 100): rt, rz = type_one_rate(n, 2000, seed=n) print(f" {n:4d} {rt*100:11.1f}% {rz*100:14.1f}%") print("\none worked example (n=20, seed=3, true mu=50, sigma=5):") rnd = random.Random(3) xs = [rnd.gauss(50.0, 5.0) for _ in range(20)] t, df, p = one_sample_t(xs, 52.0) print(f" x_bar = {mean(xs):.3f} s = {stdev(xs):.3f} n = {len(xs)}") print(f" H0: mu = 52 t = {t:.3f} df = {df} p = {p:.4f}" f" -> {verdict(p, 0.05)}") Real output: self-test: ok course exercises, p-value recomputed from the t density: case t df p (mine) p (course) alpha decision XIII screen time 2.236 19 0.0375 0.0380 0.05 reject H0 XIV battery -3.000 15 0.0090 0.0085 0.01 reject H0 XV steps -2.778 24 0.0105 0.0100 0.05 reject H0 is alpha really 5%? 2000 samples from a TRUE null (mu=50, sigma=5): n reject w/ t reject w/ 1.96 10 5.1% 8.2% 30 5.0% 5.7% 100 5.7% 6.0% one worked example (n=20, seed=3, true mu=50, sigma=5): x_bar = 49.707 s = 4.772 n = 20 H0: mu = 52 t = -2.149 df = 19 p = 0.0447 -> reject H0 What I understood from it: three things, in order of how much they cost me. First, my p-values agree with the course to three decimals on two of three cases, and on the battery case the course prints 0.0085 while the exact value is 0.0090 . It is a rounding in the material, not a different method, and the decision is unchanged (both are below alpha = 0.01 ). I only know that because I computed it — reading the summary would have left me trusting a number I could not regenerate. Second, the test I built keeps its promise: 5.1%, 5.0%, 5.7% of true nulls got rejected at alpha = 0.05 , across n = 10, 30, 100. That is what a p-value is worth — a calibrated error rate, not a proof. Third, and this is the one that closes yesterday's loop: judged with the same data but the 1.96 rule instead of the t quantile, the rejection rate at n = 10 is 8.2% , not 5%. Yesterday the 95% interval covered the truth 91.8% of the time; today the same defect produces 8.2% false rejections. `91.8 + 8.2 = 100`. They are not two bugs, they are one number seen from two sides, and both come from using a multiplier that assumes I know sigma when I only have s . The n = 100 row showing 5.7% is not a second bug either — 2000 trials at a true 5% has a standard error of about 0.5 points, so that is noise. I would rather write "noise" than invent a story for it. --- Security #18 — HTTP request smuggling, CL.TE: two parsers, one buffer (CWE-444)Every bug so far was wrong inside one component. This one is wrong between two: a proxy in front and an application behind it, both reading the same bytes, disagreeing about where one request ends. HTTP offers two ways to say how long a body is — Content-Length (a count) and Transfer-Encoding: chunked (an in-band terminator). When both headers appear, the specification lets a server choose, and if the front-end and the back-end choose differently, the bytes the front counts as body are bytes the back-end executes as a new request . The direction I built is CL.TE : the front-end trusts Content-Length , the back-end prefers Transfer-Encoding: chunked . The attacker puts the chunked terminator first, so the back-end finishes the request early and keeps the rest of the "body" pending in its buffer. When the next visitor's bytes arrive on that reused upstream connection, they complete the hidden request — and the visitor, who asked for a public page, receives the answer to the hidden one. The pattern I studied: POST /public HTTP/1.1 Host: victim-site Content-Length: 52 <- front-end counts this many bytes: "body" Transfer-Encoding: chunked <- back-end stops at the 0 chunk right here 0 <- back-end: request done, anonymous POST answered GET /admin HTTP/1.1 Host: victim-site X-Fill: <- no blank line: this stays pending The hidden request has no terminating blank line on purpose. It is completed later, by the next visitor's request line, which lands inside its headers. The front-end's access control never sees GET /admin as a request — it saw it as body bytes of a harmless POST. What I understood about preventing it: the bug does not exist in either parser alone; it exists in the disagreement , so a fix on one side is not a fix. The reliable rule is that a message with both framings is malformed, and a proxy that forwards should re-frame what it forwards instead of passing the ambiguity along: # FIXED: refuse to guess. Ambiguous framing is rejected, and the proxy # forwards with a single framing it computed itself. if "transfer-encoding" in headers and "content-length" in headers: return b"HTTP/1.1 400 Bad Request\r\nContent-Length: 0\r\n\r\n" Sandbox check (two localhost sockets in /tmp — a front-end with an ACL on /admin and a back-end without one, one reused upstream connection; no external target, no real host): self-test: ok vulnerable front-end (trusts Content-Length, ACL on /admin) --- run A --- 1) attacker sends a POST whose 'body' carries the hidden prefix [back-end] 47 bytes pending in buffer: b'GET /admin HTTP/1.1\r\nHost: victim-site\r\nX-Fill:' attacker got: HTTP/1.1 200 OK 2) visitor asks for /public on the same upstream connection visitor got: HTTP/1.1 200 OK visitor body: 'ADMIN AREA: 12 invoices, 3 unpaid' fixed front-end (rejects ambiguous framing) --- run B --- 1) attacker sends a POST whose 'body' carries the hidden prefix [front] 400 ambiguous framing rejected (/public) attacker got: HTTP/1.1 400 Bad Request 2) visitor asks for /public on the same upstream connection visitor got: HTTP/1.1 200 OK visitor body: 'public page: hello' What I understood: in run A the visitor never asked for /admin and never received a redirect — they received the admin page with a 200 . The front-end's ACL was not bypassed in the sense of being tricked; it was simply **not in the loop**, because the request it blocked was a different request than the one that executed. The 47 bytes sitting in the back-end buffer are the whole bug: state that one component owns and the other does not know about. That is also the limit of what this proves. Smuggling requires a hop — proxy, load balancer, CDN — and connection reuse between them. A single server talking directly to clients has nobody to disagree with. And the impact depends entirely on what sits behind that hop: bypassing an ACL, poisoning a cache, or handing one user another user's response. I built the ACL-bypass shape because it is the one I can prove in twenty lines on loopback. Anything beyond loopback is not my business to test, and the fix is the same either way: one framing, decided by the proxy, and a 400 when the message is ambiguous. --- Day 18 notesConcept #18: t distribution and p-value computed from scratch, matched all three course exercises (0.0090 vs the course's printed 0.0085), Type I error measured at 5.1/5.0/5.7% vs 8.2% for the 1.96 rule at n=10. ✔ Security #18: CL.TE request smuggling reproduced on loopback only — visitor asking for /public received the admin page; blocked by rejecting ambiguous framing. ✔ 1582 days left. One at a time. Written by my own daily machine, checked by me. · Day 018 of 1600 · Matías Rathgeb [ inicio ] [ proyectos ] [ posts ] [ daylog ] Página estática. Sin cookies, sin javascript, sin fuentes externas. Contacto: ver inicio. |