|
Última actualización: 2026-12-02
DAY 019 OF 1600 · 2026-10-18 Day 019 — A slope I can read as a sentence, and the hostname that gets checked before the one that gets fetchedA student's private learning log · one concept at a time. Date: 2026-10-18 · Day: 19 of 1600 Log: a student's private learning log · one concept at a time. --- Concept #19 — Simple linear regression: the slope is a sentence about units, and r only measures straightnessThe last four days were about deciding whether a difference is real: intervals, p-values, error rates. Today's block (MA02, Probability and Statistics , Week 6 — Simple Linear Regression & Correlation ) changes the question. Not "is this group different" but "for each extra hour of x , how much does y move". The line is fit by least squares, and the two coefficients are just sums: b1 = Sxy / Sxx Sxy = sum((x - x_bar)(y - y_bar)) Sxx = sum((x - x_bar)^2) b0 = y_bar - b1 * x_bar What matters to me is that b1 is not an abstract number. It carries units: points per hour, kcal per step, productivity points per hour of sleep. If I cannot say the sentence out loud with units, I do not understand the fit yet. And then there is r , which the course defines as the sample correlation. I had been treating it as "how good the model is". It is narrower than that: it measures how close the cloud is to a straight line. The curriculum notes this explicitly — r = 0 means no linear association, not no association. The course prints the answers for its exercises ( b1 = 3.883 , b0 = 50.300 , r ≈ 0.994 , SE(b1) = 0.155 , t = 24.998 ). I did not want to copy them, so I computed all of them from the raw pairs with plain sums and then asserted my numbers against the printed ones — if they disagreed, the post would not build. What I tried today: a regression from first principles (no numpy), checked against two exercises from the Week 6 slides, plus one dataset built to break the meaning of r . #!/usr/bin/env python3 # regress.py - least-squares line and r, computed from sums. No numpy. # MA02 (Probability and Statistics), Week 6: Simple Linear Regression & Correlation. import math def ols(xs, ys): n = len(xs) mx, my = sum(xs) / n, sum(ys) / n sxx = sum((x - mx) ** 2 for x in xs) syy = sum((y - my) ** 2 for y in ys) sxy = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) b1 = sxy / sxx b0 = my - b1 * mx ss_res = sum((y - (b0 + b1 * x)) ** 2 for x, y in zip(xs, ys)) s = math.sqrt(ss_res / (n - 2)) # residual standard error se_b1 = s / math.sqrt(sxx) # SE of the slope t = b1 / se_b1 r = sxy / math.sqrt(sxx * syy) # sample correlation return dict(n=n, mx=mx, my=my, b0=b0, b1=b1, r=r, r2=r * r, s=s, se_b1=se_b1, t=t, df=n - 2) def show(name, xs, ys, want): f = ols(xs, ys) print(f"{name}") print(f" n={f['n']} x_bar={f['mx']:.3f} y_bar={f['my']:.3f}") print(f" y_hat = {f['b0']:.3f} + {f['b1']:.3f} x") print(f" r={f['r']:.4f} r2={f['r2']:.4f} SE(b1)={f['se_b1']:.4f} " f"t={f['t']:.3f} df={f['df']}") for k, v in want.items(): got = f[k] flag = "OK" if abs(got - v) < 0.0015 else "MISMATCH" print(f" course says {k}={v:<8} -> computed {got:.4f} [{flag}]") print() return f # Exercise XVI: study hours vs exam score (the course prints b1=3.883, b0=50.300, r=0.994, t=24.998) x16 = [2, 3, 4, 5, 6, 6, 7, 8, 9, 10] y16 = [58, 62, 65, 68, 74, 76, 78, 82, 85, 88] f16 = show("Exercise XVI - study hours vs exam score", x16, y16, dict(b1=3.883, b0=50.300, r=0.994, se_b1=0.155, t=24.998)) # Exercise XVII: sleep vs productivity (course prints b1=0.742, b0=1.846, r=0.981, t=12.392) x17 = [5, 6, 6, 7, 7, 8, 8, 9] y17 = [5.5, 6.0, 6.5, 7.0, 7.2, 7.8, 8.0, 8.3] f17 = show("Exercise XVII - sleep vs productivity", x17, y17, dict(b1=0.742, b0=1.846, r=0.981, t=12.392)) # The trap: r = 0 does not mean "no relationship", only "no LINEAR one". xp = [-3, -2, -1, 0, 1, 2, 3] yp = [9, 4, 1, 0, 1, 4, 9] fp = ols(xp, yp) print("Parabola y = x^2 on x = -3..3") print(f" r={fp['r']:.4f} r2={fp['r2']:.4f} slope={fp['b1']:.4f}") print(f" every point sits exactly on y = x^2: " f"{all(y == x * x for x, y in zip(xp, yp))}") # Assert against the course so the post cannot drift from the printed answers. assert abs(f16["b1"] - 3.883) < 0.0015 and abs(f16["b0"] - 50.300) < 0.0015 assert abs(f16["r"] - 0.994) < 0.001 and abs(f16["t"] - 24.998) < 0.01 assert abs(f17["b1"] - 0.742) < 0.0015 and abs(f17["r"] - 0.981) < 0.001 assert abs(fp["r"]) < 1e-12 print("\nself-test: ok") Real output: Exercise XVI - study hours vs exam score n=10 x_bar=6.000 y_bar=73.600 y_hat = 50.300 + 3.883 x r=0.9937 r2=0.9874 SE(b1)=0.1553 t=24.998 df=8 course says b1=3.883 -> computed 3.8833 [OK] course says b0=50.3 -> computed 50.3000 [OK] course says r=0.994 -> computed 0.9937 [OK] course says se_b1=0.155 -> computed 0.1553 [OK] course says t=24.998 -> computed 24.9982 [OK] Exercise XVII - sleep vs productivity n=8 x_bar=7.000 y_bar=7.037 y_hat = 1.846 + 0.742 x r=0.9810 r2=0.9624 SE(b1)=0.0599 t=12.392 df=6 course says b1=0.742 -> computed 0.7417 [OK] course says b0=1.846 -> computed 1.8458 [OK] course says r=0.981 -> computed 0.9810 [OK] course says t=12.392 -> computed 12.3918 [OK] Parabola y = x^2 on x = -3..3 r=0.0000 r2=0.0000 slope=0.0000 every point sits exactly on y = x^2: True self-test: ok What I understood from it: the slope is a sentence with units — "+3.9 points per extra study hour", "+0.74 productivity points per extra hour of sleep" — and the t on that slope is the same signal-to-noise idea as yesterday, just with df = n - 2 because two parameters ate two degrees of freedom. The parabola is the part I will keep. Every single point lies exactly on y = x² ; there is no noise at all; and r = 0.0000 with r² = 0.0000 . A model that trusts r as "strength of relationship" concludes there is nothing there, on the one dataset where the relationship is perfect. So r is not a truth score — it is the fit of one specific shape. Before quoting it I have to look at the scatter, or I am measuring my assumption instead of the data. And r² = 0.987 on the study-hours data does not mean "98.7% correct". It means 98.7% of the variance in scores is explained by a straight line in hours — which says nothing about whether hours cause scores. That is the next trap, and the course points at it with the geolocation exercise (latitude and longitude correlate; neither causes the other — geography does). --- Security #19 — SSRF: the hostname that gets checked is not always the hostname that gets fetchedThe classes are add up: path traversal, mass assignment, operator injection, CRLF in headers, request smuggling. Today is the one where the application makes the request for the attacker: server-side request forgery. The shape is a feature that takes a URL from the user — import from URL, avatar by link, webhook test, PDF renderer, image proxy. The app fetches it. If the app can reach things the user cannot (a metadata endpoint, an internal admin panel, a database port, localhost services), then the user just borrowed the app's network position. The part I wanted to prove is that the guard people write first does not guard the thing that matters. A hostname allowlist is checked on the string the user submitted. Then the HTTP client follows a 302 — and the check is already two steps behind. The same hole shows up in address notation: 127.0.0.1 written as 2130706433 is the same host to the resolver and a completely different string to a denylist. The pattern I studied: # VULNERABLE: the check runs once, on the first host, before the client follows redirects. def fetch(url): host = urllib.parse.urlparse(url).hostname if host not in ALLOW: # <- "127.0.0.1" passes, it is our own app raise PermissionError return urllib.request.urlopen(url) # <- 302 to the internal service is followed silently Two variants of the naive guard, both defeated: guard A hostname allowlist -> attacker uses an allowed host that 302s inward guard B string denylist -> attacker writes the same IP as 2130706433 What I understood about preventing it: # FIXED: resolve, refuse internal address ranges, and re-check on every hop. def fetch(url, max_hops=3): for _ in range(max_hops + 1): host, port = parse(url) for addr in resolve(host, port): # all A/AAAA answers, not just the first if ip_address(addr).is_private or is_loopback(addr) or is_link_local(addr): raise PermissionError resp = open_without_following_redirects(url) if resp is a redirect: url = urljoin(url, resp.Location) # back to the top: resolve and check again continue return resp Three things had to be true at once for this to work: (1) the decision is made on the resolved address , not on the string, (2) every answer from the resolver is checked, not just the first, and (3) the check repeats after each redirect. Removing any one of the three reopens the hole — a redirect-follower with a good range check still lands internally, and a range check that runs once still misses hop two. A network-level egress policy on the app's own container is the belt to this suspenders. Sandbox check (two loopback servers in /tmp — a "public" app that redirects, and an "internal" service that answers with a fake token unless the request carries a trusted header; no external target, no real host): public app http://127.0.0.1:38067/ internal svc http://127.0.0.1:41955/ (reachable in-network only) [1] guard A = hostname allowlist. Attacker uses an ALLOWED app that 302s inward. host checked: 127.0.0.1 -> 200 'internal service: internal-admin-token=REDACTED' [2] guard B = denylist of strings (the usual 'fix'). Same address, decimal form. url: http://2130706433:41955/price host string seen: 2130706433 -> 200 'internal service: internal-admin-token=REDACTED' [3] resolved-and-range-checked fetcher against both payloads -> blocked: host 127.0.0.1 resolves to internal 127.0.0.1 -> blocked: host 2130706433 resolves to internal 127.0.0.1 [4] the internal caller itself (trusted code path, its own client) -> 200 'internal service: price feed ok' internal service counters: tagged=1 forged=2 self-test: ok What I understood: in both attacks the app did exactly what it was told, and it did it after passing its own check. The check was not wrong, it was in the wrong place in time — a decision about a URL, made before the URL became a different URL. That is the general shape I keep meeting this week: a validation that happens on the input and not on the thing the input turns into. Same family as the smuggling day (the front-end validated a request that was not the request that executed) and the CRLF day (the string was safe as data, and became a header when it moved one layer down). The honest limit: my "internal" service is on loopback, so what I proved is the bypass logic , not the reach of any real network. In the wild the same code reaches link-local metadata addresses ( 169.254.169.254 ), internal DNS names, and admin ports — which is exactly why the class is worth a CVE budget. I am not going to point any of this at anything that is not mine. --- Day 19 notesConcept #19: least squares from sums; matched both Week 6 exercises exactly (b1 3.8833 / 0.7417, r 0.9937 / 0.9810, t 24.998 / 12.392) and showed r = 0 on a perfect parabola. ✔ Security #19: SSRF via redirect and via decimal-notation address; blocked by resolve-then-range-check on every hop. Loopback sandbox only. ✔ 1581 days left. One at a time. Written by my own daily machine, checked by me. · Day 019 of 1600 · Matías Rathgeb [ inicio ] [ proyectos ] [ posts ] [ daylog ] Página estática. Sin cookies, sin javascript, sin fuentes externas. Contacto: ver inicio. |