|
Última actualización: 2026-12-02
DAY 017 OF 1600 · 2026-10-15 Day 017 — The range that catches the truth most of the time, and what the missing times costA student's private learning log · one concept at a time. Date: 2026-10-15 · Day: 17 of 1600 Log: a student's private learning log · one concept at a time. --- Concept #17 — Confidence intervals: the 95% is the method, not the specific rangeI had been reading accuracy numbers and means as if they were facts. Today's block (MA02, Probability and Statistics , Week 2 — *Confidence Intervals & Uncertainty*) is about the honest version of a number: instead of reporting one estimate, report a range and say how often ranges built that way actually contain the truth. The trap the course spells out is the sentence almost everyone says: "there is a 95% probability that the true mean is inside this interval." That is wrong. The true mean is a fixed value — for a specific interval it is either in there (100%) or it is not (0%), and I do not get to see which. The 95% describes the procedure : if I built the interval the same way many times from many samples, about 95 out of 100 of those intervals would cover the true mean. Rather than trust that claim, I measured it. I simulated samples from a known distribution (true mean 50, sigma 5), built a 95% interval by the normal approximation mean ± 1.96 · s/√n , repeated it 2000 times, and counted how often the interval actually caught the true mean. Standard library only. #!/usr/bin/env python3 # confidence_interval.py - a confidence interval is a lasso, not a claim. # MA02 (Probability and Statistics), Week 2: Confidence Intervals & Uncertainty. # The course trap: "there is a 95% chance the true mean is in THIS interval" # is wrong. The true mean is fixed; the 95% describes the METHOD. If I built # the interval the same way 1000 times, ~950 would cover the true mean. # So instead of trusting the formula, I measured the coverage by simulation. # Pure stdlib, no numpy, no scipy. import math import random def mean(xs): return sum(xs) / len(xs) def stdev(xs, m): # sample standard deviation (n-1 denominator) return math.sqrt(sum((x - m) ** 2 for x in xs) / (len(xs) - 1)) def ci95(sample): # normal-approximation 95% CI: x_bar +/- z * s / sqrt(n), z = 1.96 m = mean(sample) s = stdev(sample, m) half = 1.96 * s / math.sqrt(len(sample)) return m - half, m + half def coverage(true_mean, n, trials, seed): rnd = random.Random(seed) hits = 0 widths = [] for _ in range(trials): sample = [rnd.gauss(true_mean, 5.0) for _ in range(n)] lo, hi = ci95(sample) widths.append(hi - lo) if lo <= true_mean <= hi: hits += 1 return hits / trials, mean(widths) def self_test(): s = [10.0] * 9 + [11.0] lo, hi = ci95(s) assert abs(mean(s) - (lo + hi) / 2) < 1e-9 # interval centred on the mean assert lo < mean(s) < hi # and it contains it print("self-test: ok") if __name__ == "__main__": self_test() TRUE = 50.0 print(f"true mean = {TRUE}, sigma = 5.0, nominal confidence = 95%, 2000 trials each") for n in (10, 30, 100): cov, w = coverage(TRUE, n, 2000, seed=n) print(f" n={n:3d}: coverage = {cov*100:.1f}% mean width = {w:.2f}") rnd = random.Random(7) sample = [rnd.gauss(TRUE, 5.0) for _ in range(30)] m = mean(sample) s = stdev(sample, m) lo, hi = ci95(sample) print("\nworked example (n=30, seed=7):") print(f" sample mean = {m:.3f}") print(f" sample sd = {s:.3f}") print(f" 95% CI = [{lo:.3f}, {hi:.3f}] (width {hi - lo:.3f})") print(f" true mean {TRUE} inside this one? {lo <= TRUE <= hi}") Real output: self-test: ok true mean = 50.0, sigma = 5.0, nominal confidence = 95%, 2000 trials each n= 10: coverage = 91.8% mean width = 6.04 n= 30: coverage = 94.3% mean width = 3.55 n=100: coverage = 94.0% mean width = 1.95 worked example (n=30, seed=7): sample mean = 50.171 sample sd = 4.273 95% CI = [48.642, 51.700] (width 3.058) true mean 50.0 inside this one? True What I understood from it: the width and the coverage pull against each other, exactly the way the course describes the trade-off. At n=100 the mean interval is only 1.95 wide and still catches the truth 94.0% of the time; at n=10 the interval has to be 6.04 wide to stay near the promise. More data buys a narrower range for the same confidence — that is the whole bargain. The part I did not expect: at n=10 the coverage came out 91.8% , not 95%. That is not a bug, it is a real limitation I had been ignoring. I used 1.96 (a number that is correct only when the sample standard deviation s is the population sigma), and with only ten points s is itself noisy and tends to be too small, so the interval is too tight and misses more often than it claims. The remedy is the t-distribution (a bigger multiplier that grows as n shrinks), which is why the course keeps saying the normal interval is an approximation. So the honest lesson is not "95% means 95%" — it is "a confidence interval is only as good as the assumption behind its multiplier." Same formula, honest audit of when it stops being true. --- Security #17 — CRLF injection / HTTP response splitting: a URL that ends the header block (CWE-113)The bugs I studied so far put something inside a value or changed its type . This one abuses the one character HTTP cannot ignore: the line break. In HTTP, a response is a status line, then headers, then a blank line, then the body. Headers are separated by CRLF ( \r\n ), and the blank line is two CRLFs. If a program copies user input into a header value and does not remove CR/LF from it, the input does not stay in the value — it **closes the header section and opens new header lines** the attacker chose. The classic shape is a redirect endpoint that builds Location: from a query parameter. Send a URL that still contains %0d%0a and the server decodes it into a real newline after the value has been placed in the header: GET /redirect?url=/home%0d%0aSet-Cookie:%20admin=1 HTTP/1.1 The pattern I studied: # VULNERABLE: user input goes into a header value with CR/LF still in it. # The extra CR/LF ends the header block; "Set-Cookie: admin=1" becomes a real # header the client believes came from the server. resp = ("HTTP/1.1 302 Found\r\n" f"Location: {target}\r\n" # target straight from ?url=, unsanitised "Content-Length: 0\r\n\r\n") What I understood about preventing it: a header value is not a string that can hold anything — CR and LF are structural and must never survive into it. The fix is to strip them (or percent-encode them) before the value is written, so the injected text stays inert inside the Location field where it means nothing. Framework header writers that reject \r / \n in values already do this; hand-built responses usually do not. # FIXED: a header value may never contain CR or LF. Strip them and the # injected text becomes garbage inside the value, not new headers. target = target.replace("\r", "").replace("\n", "") resp = ("HTTP/1.1 302 Found\r\n" f"Location: {target}\r\n" "Content-Length: 0\r\n\r\n") Sandbox check (local loopback socket server only, in /tmp; a hand-written raw request because library HTTP clients refuse to send CR/LF in a value — an attacker is not bound by that check): self-test: ok vulnerable server honest request: url=/home HTTP/1.1 302 Found Location: /home Content-Length: 0 -> injected headers: none attack request: url=/home%0d%0aSet-Cookie:%20admin=1%0d%0aX-Injected:%20yes HTTP/1.1 302 Found Location: /home Set-Cookie: admin=1 X-Injected: yes Content-Length: 0 -> injected headers: ['Set-Cookie', 'X-Injected'] fixed server honest request: url=/home HTTP/1.1 302 Found Location: /home Content-Length: 0 -> injected headers: none attack request: url=/home%0d%0aSet-Cookie:%20admin=1%0d%0aX-Injected:%20yes HTTP/1.1 302 Found Location: /homeSet-Cookie: admin=1X-Injected: yes Content-Length: 0 -> injected headers: none the honest request looks identical on both servers. the difference only appears when the value carries CR/LF bytes. What I understood: the honest request is byte-for-byte identical on the two servers — that is why the bug survives review. Nothing looks wrong because the developer only ever tests with clean values. The moment the value carries \r\n , the vulnerable server emits two headers the attacker wrote ( Set-Cookie: admin=1 , X-Injected: yes ), and a browser would honour the cookie as if the site had set it. The fixed server keeps the same bytes but they collapse into one useless Location value. This is not just header pollution: if the response body can be shaped too, the same trick splits the response and lets an attacker inject content the browser renders as the site. The lesson is narrower than "sanitise input" — it is that some characters are syntax , not data, and a header value is a place where a line break is always syntax. --- Day 17 notesConcept #17: confidence-interval coverage measured, output above (n=100 → 94.0% coverage, width 1.95; n=10 under-covers at 91.8%). ✔ Security #17: CRLF injection / response splitting reproduced, then blocked, on a localhost sandbox only. ✔ 1583 days left. One at a time. Written by my own daily machine, checked by me. · Day 017 of 1600 · Matías Rathgeb [ inicio ] [ proyectos ] [ posts ] [ daylog ] Página estática. Sin cookies, sin javascript, sin fuentes externas. Contacto: ver inicio. |