|
Última actualización: 2026-12-02
DAY 020 OF 1600 · 2026-10-19 Day 020 — The test that spends alpha once, and a reset link that trusts the name you came in withA student's private learning log · one concept at a time. Date: 2026-10-19 · Day: 20 of 1600 Log: a student's private learning log · one concept at a time. --- Concept #20 — One-way ANOVA: three t-tests spend the same 5% three timesYesterday I fit a line through two columns. Today's block (MA02, *Probability and Statistics , Week 7 — One-way ANOVA*) is the question I had been avoiding: what do I do when there are three groups instead of two? The lazy answer is three t-tests: library vs coffee, library vs dorm, coffee vs dorm. The course says no, and the reason is not that the arithmetic is wrong. It is that each test is allowed to be wrong 5% of the time, and I just bought three of those allowances. If the null hypothesis is true, the chance that *at least one* of my three tests fires is not 5% — it is roughly 14%. ANOVA asks the question once. It splits the total variation into two buckets: SSA (between groups) = sum over groups of nj * (group_mean - grand_mean)^2 SSE (within groups) = sum over groups of sum of (x - group_mean)^2 dfA = k - 1 dfE = N - k MSA = SSA / dfA MSE = SSE / dfE F = MSA / MSE F is a ratio of two variance estimates. If the groups were all drawn from the same population, both estimates measure the same noise and the ratio sits near 1. A ratio far above 1 means the spread between the means is bigger than the spread the groups have internally — the group label is telling me something. The detail I had to build myself: the p-value. It is the area of the F distribution to the right of my statistic, and the F distribution has no closed form CDF in the standard library. It reduces to the regularized incomplete beta function, which I implemented with Lentz's continued fraction. That is the same function that gave me the t-test p-value last week, with different arguments — useful to notice, because t² = F for two groups. What I tried today: a one-way ANOVA from first principles with no numpy and no scipy, checked against Exercise XIX from the course (focus time by study location), plus a simulation of what the three-t-test habit actually costs. #!/usr/bin/env python3 # anova.py - one-way ANOVA from first principles, pure standard library. # MA02 (Probability and Statistics), Week 7 "One-way ANOVA". # Exercise XIX is the check: the book prints SSA=1162.17, SSE=1110.75, # dfA=2, dfE=33, MSA=581.09, MSE=33.66, F=17.26, p<0.001. # # The point of the week: three t-tests is NOT the same test as one ANOVA. # Each t-test spends alpha; three of them spend it three times. import math, random K = 3 N_GROUP = 12 MEANS = [43.41, 34.98, 29.61] # library, coffee shop, dorm (book) SSE_TARGET = 1110.75 # within-group SS (book) NAMES = ["library", "coffee", "dorm"] def build_sample(): """Rebuild a sample whose summary statistics ARE the book's numbers. Within each group the 12 deviations from the group mean must sum to 0 and their squares must sum to SSE_TARGET/K = 370.25. Six +a and six -a does exactly that, with a = sqrt(370.25/12). """ a = math.sqrt((SSE_TARGET / K) / N_GROUP) data = [] for m in MEANS: g = [m + a] * (N_GROUP // 2) + [m - a] * (N_GROUP // 2) data.append(g) return data def mean(xs): return sum(xs) / len(xs) def one_way_anova(groups): k = len(groups) n = [len(g) for g in groups] N = sum(n) grand = sum(sum(g) for g in groups) / N ssa = sum(nj * (mean(g) - grand) ** 2 for g, nj in zip(groups, n)) sse = sum(sum((x - mean(g)) ** 2 for x in g) for g in groups) df_a, df_e = k - 1, N - k msa, mse = ssa / df_a, sse / df_e f = msa / mse return dict(grand=grand, ssa=ssa, sse=sse, df_a=df_a, df_e=df_e, msa=msa, mse=mse, f=f, p=f_sf(f, df_a, df_e)) # ---- F survival function from scratch ------------------------------------- def _betacf(a, b, x, itmax=200, eps=3e-16): """Continued fraction for the incomplete beta (Lentz's method).""" 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): """Regularized incomplete beta I_x(a,b).""" 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 f_sf(f, d1, d2): """P(F > f) for the F distribution = I_{d2/(d2+d1*f)}(d2/2, d1/2).""" if f <= 0: return 1.0 return betainc(d2 / 2.0, d1 / 2.0, d2 / (d2 + d1 * f)) # ---- what three t-tests would have said ----------------------------------- def t_two_sided(xs, ys): """Welch t-test, p from the t survival function (via the same beta).""" nx, ny = len(xs), len(ys) mx, my = mean(xs), mean(ys) vx = sum((x - mx) ** 2 for x in xs) / (nx - 1) vy = sum((y - my) ** 2 for y in ys) / (ny - 1) 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)) p = betainc(df / 2.0, 0.5, df / (df + t * t)) return t, df, p def simulate_family_error(runs=20000, seed=7): """Under H0 (all means equal) how often does at least one of the 3 pairwise t-tests fire at alpha=0.05? That is the real error rate.""" rnd = random.Random(seed) fired = 0 for _ in range(runs): gs = [[rnd.gauss(0, 1) for _ in range(N_GROUP)] for _ in range(K)] if any(t_two_sided(gs[i], gs[j])[2] < 0.05 for i in range(K) for j in range(i + 1, K)): fired += 1 return fired / runs def f_crit(alpha, d1, d2): """Inverse survival: the f where P(F > f) = alpha, by bisection.""" lo, hi = 0.0, 1000.0 for _ in range(200): mid = (lo + hi) / 2 if f_sf(mid, d1, d2) > alpha: lo = mid else: hi = mid return (lo + hi) / 2 if __name__ == "__main__": groups = build_sample() r = one_way_anova(groups) print("group means (my rebuilt sample):", ", ".join(f"{n}={mean(g):.2f}(n={len(g)})" for n, g in zip(NAMES, groups))) print(f"grand mean = {r['grand']:.2f}") print(f"SSA (between) = {r['ssa']:.2f} dfA = {r['df_a']}") print(f"SSE (within) = {r['sse']:.2f} dfE = {r['df_e']}") print(f"MSA = {r['msa']:.2f}") print(f"MSE = {r['mse']:.2f}") print(f"F = {r['f']:.2f}") print(f"p = {r['p']:.3e}") print(f"F critical (a=.05) = {f_crit(0.05, r['df_a'], r['df_e']):.2f}") print() print("pairwise Welch t-tests on the same data:") for i in range(K): for j in range(i + 1, K): t, df, p = t_two_sided(groups[i], groups[j]) print(f" {NAMES[i]:>7} vs {NAMES[j]:<7} t={t:6.2f} df={df:5.1f} p={p:.2e}") print() rate = simulate_family_error() print(f"simulation, 20000 runs under H0 (3 groups, 12 each, alpha=0.05):") print(f" at least one of the 3 t-tests fired in {rate*100:.1f}% of runs") print(f" target error rate if it were one test: 5.0%") Real output: group means (my rebuilt sample): library=43.41(n=12), coffee=34.98(n=12), dorm=29.61(n=12) grand mean = 36.00 SSA (between) = 1161.37 dfA = 2 SSE (within) = 1110.75 dfE = 33 MSA = 580.68 MSE = 33.66 F = 17.25 p = 7.440e-06 F critical (a=.05) = 3.28 pairwise Welch t-tests on the same data: library vs coffee t= 3.56 df= 22.0 p=1.76e-03 library vs dorm t= 5.83 df= 22.0 p=7.32e-06 coffee vs dorm t= 2.27 df= 22.0 p=3.35e-02 simulation, 20000 runs under H0 (3 groups, 12 each, alpha=0.05): at least one of the 3 t-tests fired in 12.1% of runs target error rate if it were one test: 5.0% What I understood from it: two things, and one of them is uncomfortable. The comfortable one: F = 17.25 is far past the critical value 3.28 , and p ≈ 7.4e-06 . The decision is the same one the book reaches, and it is not close. Study location dominates: library 43.41 min, coffee 34.98, dorm 29.61, MSE 33.66 — so the within-group noise is about 5.8 minutes, and the library-dorm gap is more than twice that. The uncomfortable one: my SSA is 1161.37 , and the course prints 1162.17 . Recomputing from the book's own printed means gives 12 × (7.41² + 1.02² + 6.39²) = 1161.37. So the printed SSA is 0.8 above what its own printed means produce — the means were rounded before the table was built, and the rounding walked into the answer: F becomes 17.25 from the printed means and 17.26 from the printed table. Small, irrelevant to the decision, and exactly the kind of thing I would have copied without noticing if I had trusted the answer sheet. My numbers are the ones that come out of the arithmetic I can show. And the simulation is the part that changes a habit: 12.1% of runs fire at least one false positive when there is nothing to find, against the 5% I thought I was buying. That is not a small tax, and it grows fast with more groups. If I want pairwise answers after the F test, the comparison has to be corrected — the test is allowed one 5%, not one per pair. --- Security #20 — Host header injection: the reset link says whatever host the requester typed (CWE-644)Nineteen classes in, and today's is the smallest one yet by code size. It is also the one that ends in an account takeover without any injection payload, any special character, or anything a filter would flag. The shape: a password reset endpoint that builds an absolute URL for the email body out of the Host header of the incoming request. base = f"http://{self.headers.get('Host')}/" body = f"Reset your password: {base}reset?token={token}" The header is not data the app owns. It is data the client sends, and it is usually the one header no one thinks about because the browser fills it in. The attacker never clicks the link — that is the whole trick. They only have to start the reset for the victim's address while sending their own Host : POST /forgot HTTP/1.1 Host: attacker.test email=victim@corp.test The app mints a real token for the real account, writes a real email, and the link inside it points at attacker.test . The victim clicks, the token arrives in the attacker's access log, and the attacker redeems it on the real site. Every check passed: the account exists, the token is valid, the email is legitimate. The only untrusted thing was the hostname inside the link. This is CWE-644, and the family is wider than password resets: invitation emails, invoice download links, OAuth callbacks, absolute redirects after login, cache keys that ignore the header while the body varies on it. Anywhere the app turns "the host I was called on" into "the host I tell the user to trust". The pattern I studied: # VULNERABLE: the origin of the link is taken from the request, not from config. def forgot(self, email): token = db.new_reset_token(email) host = self.headers["Host"] # attacker-controlled string send_mail(email, f"Reset: http://{host}/reset?token={token}") return 200 What I understood about preventing it: the origin of a link is configuration, not input. Nothing that goes into an email should be built from a request header, and if a deployment genuinely needs several names, the set is written down. # FIXED: the base URL is config; the Host header is checked against a known set. BASE_URL = settings.PUBLIC_BASE_URL # e.g. "https://corp.test" def forgot(self, email): if self.headers.get("Host") not in settings.ALLOWED_HOSTS: return 400 # never guess, never echo token = db.new_reset_token(email) link = f"{BASE_URL}/reset?token={token}" # built from config only send_mail(email, f"Reset your password: {link}") return 200 ALLOWED_HOSTS alone would not be enough if I still echoed the header into the body — validating a value and then using it is two decisions, and only the second one matters. The link comes from config; the header is only used to reject the request early. Sandbox check (two loopback servers, one vulnerable and one fixed, on ephemeral ports in /tmp ; the "attacker" is a Host header and nothing else): --- VULNERABLE: link built from the Host header (127.0.0.1:37849) --- attacker POST /forgot Host: attacker.test -> {"status":"sent"} victim's email body : Reset your password: http://attacker.test/reset?token=df31db9bb8e725ff host inside the link : attacker.test result : token is delivered to attacker.test -> account takeover --- FIXED: fixed origin + Host allowlist (127.0.0.1:44205) --- attacker POST /forgot Host: attacker.test -> {"error":"bad host"} victim's email body : (nothing sent) result : reset refused, no token minted for a foreign Host What I understood: the vulnerability was not in the token, the database, or the email template. It was one string concatenation where a request header was treated as the app's own address. The fix is not a filter on the header — it is deleting the header from the sentence entirely and taking the address from configuration. Compare this with the CRLF day: same root, a value that is safe as data and becomes dangerous the moment it changes layer. A header is not a constant just because it looks like one. Honest limit: both servers here are on loopback and the "attacker" is a header I typed. What I proved is the link-poisoning logic and that the guard stops it — not that any real mail relay or CDN behaves this way. Host header routing in front of an app is exactly where this gets messy in the wild, and that is a separate experiment for another day. --- Day 20 notesConcept #20: one-way ANOVA from first principles, F CDF via incomplete beta; F=17.25, p=7.44e-06, crit 3.28. Found the course's printed SSA (1162.17) does not reproduce from its own printed means (1161.37). Three t-tests under H0 fire at least once in 12.1% of 20000 runs. ✔ Security #20: Host header injection → password reset poisoning; token walked out to the requester's hostname, then blocked by a fixed origin + allowlist. Loopback sandbox only. ✔ 1580 days left. One at a time. Written by my own daily machine, checked by me. · Day 020 of 1600 · Matías Rathgeb [ inicio ] [ proyectos ] [ posts ] [ daylog ] Página estática. Sin cookies, sin javascript, sin fuentes externas. Contacto: ver inicio. |