Última actualización: 2026-12-02

DAY 024 OF 1600 · 2026-10-24

Day 024 — A server at 90% is already late, and a digest is not a signature

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

Concept #24 — Utilization is a wall, not a slope (Little's law and the mean that hides the queue)

MA03, week 4: Scaling & Databases. The sentence that stuck with me is the one everybody says in a standup — "we're at 90% CPU, we're fine, we have room" . Both halves of that sentence are wrong, and the second half is the expensive one. The reason is not a library detail, it is one line of queueing theory. For a single worker with service time S running at utilization ρ (0 < ρ < 1), the average time a request waits before service is: Wq = ρ · S / (1 - ρ) Look at what that says. Going from 50% to 80% costs 4× the wait. Going from 80% to 90% costs another 2.25×, and 90% to 95% doubles it again. The work never changed — the request still needs the same one second of CPU. What changed is how much of the time the worker was busy and therefore how long the next arrival has to stand in line. At 98% the queue is 49× the work. The second half of the sentence — "we have room" — belongs to whoever scales on average latency. The average is the one number the queue never lets you see. Little's law gives the bridge: L = λ · W , the time-average number of requests in the system equals arrival rate times mean time in system. What I tried today: one worker, FIFO, exponential service times, Poisson arrivals — a discrete event simulation in stdlib only, 40 000 requests per row, five utilizations. I measure the wait of every request, its p50/p95/p99, and the time-average occupancy L by integrating the occupancy curve over the whole run, then compare that L against λ · E[T] from Little's law. The theory column is computed separately from the simulation, so agreement is a check and not a tautology. # queue.py - MA03 (AI-Ops, week 4: Scaling & Databases). # Why a server at 90% CPU is not "almost ready for one more request": # utilization is a wall, not a slope. One worker, FIFO, exponential service. import math, random SERVICE = 1.0 # seconds of work per request, fixed so the numbers are readable def simulate(rho, n, seed): rng = random.Random(seed) lam = rho / SERVICE arrivals, t = [], 0.0 for _ in range(n): t += rng.expovariate(lam) arrivals.append(t) waits, in_sys, events = [], [], [] free_at = 0.0 for a in arrivals: s = rng.expovariate(1.0 / SERVICE) start = max(a, free_at) # FIFO single server: never preempt dep = start + s free_at = dep waits.append(start - a) in_sys.append(dep - a) events.append((a, 1)) events.append((dep, -1)) # time-average number in the system, by integrating the occupancy curve events.sort() area, occ, prev = 0.0, 0, events[0][0] for tm, d in events: area += occ * (tm - prev) prev, occ = tm, occ + d T = events[-1][0] - events[0][0] L_sweep = area / T L_little = lam * (sum(in_sys) / len(in_sys)) return waits, L_sweep, L_little, lam def pct(sorted_vals, q): idx = min(len(sorted_vals) - 1, math.ceil(q * len(sorted_vals)) - 1) return sorted_vals[max(idx, 0)] print("one worker, service time 1.000 s, 40000 requests per row, FIFO") print() print(" util mean wait theory Wq p50 p95 p99 L(sweep) L(little)") for rho in (0.50, 0.80, 0.90, 0.95, 0.98): waits, L_sweep, L_little, lam = simulate(rho, 40000, seed=int(rho * 1000)) w = sorted(waits) theory = rho * SERVICE / (1 - rho) print(f"{rho:5.2f} {sum(waits)/len(waits):10.3f} {theory:10.3f} " f"{pct(w,.50):6.3f} {pct(w,.95):7.3f} {pct(w,.99):7.3f} " f"{L_sweep:9.3f} {L_little:9.3f}") print() print("read the last column pair: Little's law L = lambda * E[T] holds in every row.") print("read the p95 column: it grows much faster than the mean, and the mean grows") print("much faster than the work. The job is the same one second in all five rows.") Real output (Python 3, this session): one worker, service time 1.000 s, 40000 requests per row, FIFO util mean wait theory Wq p50 p95 p99 L(sweep) L(little) 0.50 1.026 1.000 0.012 4.709 7.971 1.016 1.017 0.80 3.841 4.000 2.329 13.292 20.683 3.882 3.869 0.90 9.688 9.000 6.228 33.277 45.031 9.640 9.626 0.95 18.381 19.000 12.916 53.082 70.742 18.379 18.412 0.98 36.151 49.000 29.851 90.162 123.251 36.458 36.411 read the last column pair: Little's law L = lambda * E[T] holds in every row. read the p95 column: it grows much faster than the mean, and the mean grows much faster than the work. The job is the same one second in all five rows. Then the row I did not believe, so I re-ran it — the 0.98 mean is unstable at 40 000 requests, and I wanted to know in which direction: n= 40000 rho=0.98 mean wait = 48.9, 53.7, 31.1 theory 49.0 n= 200000 rho=0.98 mean wait = 40.1, 51.9, 66.9 theory 49.0 n=1000000 rho=0.98 mean wait = 46.8, 52.2, 56.3 theory 49.0 What I understood from it: four things. First, the mean wait is a tail wearing a disguise. At 50% utilization the median wait is 0.012 s — half the requests walk straight in because the worker is idle half the time — while the mean is 1.0 s. Nobody experiences the mean. If the dashboard shows the mean and the users report slowness, both can be honest: the mean is dragged by the 5% who waited 4.7 s. Second, the p95 column is the one that scales. Same job in every row: 1.000 s. The p95 moves 4.7 → 53.1 s between 50% and 95% utilization: an 11× regression with zero code changes and zero traffic growth, just less headroom. From 90% to 95%, the last 5 points of utilization cost 20 extra seconds of p95 wait. That is the number to keep out of, and it is why "we can still add one more customer" is a sentence that ends in an incident. Third, my single run at 0.98 said 36.2 s while the formula says 49.0 s — I had a 17% error and it pointed the reassuring way. Three seeds at 40 000 requests: 48.9, 53.7, 31.1. One draw said "there is no problem here". The estimator is honest only in the limit, and a production dashboard is one draw. So: measure the p95 over a window long enough to contain a full busy period, or don't quote it. Fourth, Little's law held in every row (36.458 vs 36.411 at 0.98 — that is the integration and the identity agreeing), and that is exactly why it is not a validation. It is a conservation identity: it holds for the queue you measured, right or wrong. It tells me how many requests are in flight; it says nothing about whether that is acceptable. Agreement with Little's law is the minimum bar, not a pass. Honest limit: this is M/M/1 — exponential service, memoryless arrivals, one worker, no retries, no timeouts. Real services have bursts and clients that give up, so the picture gets worse , not better. And the fix I did not test today is the interesting half: with c workers the wait collapses much faster than c (the Erlang C form), which is the whole argument for horizontal scaling — I want to run that next rather than assert it. ---

Security #24 — A digest is a checkpoint, not a signature: length extension on a secret-prefix MAC (CWE-354)

Twenty-three classes. This one is not a parser disagreement — it is the shape of the hash function itself being used as if it were a signature. The bug is one line that looks completely reasonable: mac = sha256(SECRET + message) and the token is message + "." + mac . The server recomputes it and compares. No timing leak, no weak secret, no crypto library misuse. It still breaks, for a reason that has nothing to do with secrecy and everything to do with how SHA-256 is built. SHA-256 is Merkle–Damgård: it eats the message in 64-byte blocks and carries a 256-bit state from block to block. The padding — 0x80 , zeros, then the message length in bits — is appended by the hash, not by the caller. Two consequences that combine into the attack: 1. The published digest is the internal state after the last block. 2. The padding depends only on the length , never on the content. So anyone holding sha256(SECRET || message) holds a checkpoint, and can resume the compression from that checkpoint with whatever bytes they want — provided they know how many bytes SECRET has. The new message is message || padding || attacker_tail , and the digest of SECRET || message || padding || attacker_tail is computable *without the secret*, because those first bytes are exactly the padding the server was going to apply anyway. The padding travels inside the message as if it were data. The pattern I studied — the pieces of the sandbox that matter: # the bug def mac_prefix(msg): return sha256(SECRET + msg) # SECRET never leaves the server # the only thing the attacker needs: the padding function is deterministic def pad64(mlen): # what SHA-256 appends to mlen bytes return b"\x80" + b"\x00" * ((56 - (mlen + 1) % 64) % 64) + (mlen * 8).to_bytes(8, "big") # resume a hash from a digest, knowing only how many bytes it already absorbed def sha256(msg, state=None, absorbed=0): st = list(H0) if state is None else list(state) total = len(msg) if state is None else absorbed + len(pad64(absorbed)) + len(msg) data = msg + pad64(total) for i in range(0, len(data), 64): st = compress(st, data[i:i + 64]) return b"".join(x.to_bytes(4, "big") for x in st) # the attack: digest -> state, glue = pad64(guess + len(msg)), send msg + glue + tail state = [int.from_bytes(digest[i:i + 4], "big") for i in range(0, 32, 4)] for guess in range(1, 41): # only the *length* is unknown glue = pad64(guess + len(msg)) forged_mac = sha256(b"&role=admin", state=state, absorbed=guess + len(msg)) send(msg + glue + b"&role=admin", forged_mac) The lengths are the whole story: absorbed = len(guess_secret) + len(msg) , and the loop is just the key length being unknown. Guessing wrong produces a valid digest for a message the server never hashed, so it fails — and that failure is itself the oracle that reveals the length. What I understood about preventing it: stop composing hash(secret ‖ data) by hand. Two constructions are immune: one that wraps the secret around the message (HMAC absorbs the inner hash before finishing), and any hash that is not Merkle–Damgård (SHA-3). The cheapest correct fix is the one from the standard library: import hmac, hashlib def mac_hmac(msg): return hmac.new(SECRET, msg, hashlib.sha256).digest() # and always compare in constant time if not hmac.compare_digest(mac_hmac(msg), received): return 403 compare_digest is there for the other bug — the one that leaks the MAC byte by byte — not for this one. Both belong in the same two lines. Sandbox check (my own SHA-256 in stdlib, two local servers, 127.0.0.1, both stopped at the end): self-test sha256('abc') = ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad hashlib = ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad match self-test K[0] = 428a2f98 (expected 428a2f98), 64 constants derived from primes [VULN] 127.0.0.1:8741 MAC = sha256(SECRET || message) secret = 24 bytes, never sent legit token, role=user -> 200 public: 1 file token seen by the client: 757365723d67756573742672...5d1257b11cc70d13 forged, no secret, 24 oracle calls -> key length 24, 200 ADMIN EXPORT: full ledger (3 files) forged digest: 06607670c0d3dd317248bd16c94ca483... forged bytes inside the message: 80 00 00 ... (SHA-256 padding, sent as if it were data) [FIX] 127.0.0.1:8742 MAC = HMAC-SHA256(SECRET, message) same 40 forgeries -> 40/40 rejected (403 bad signature) legit token, role=user -> 200 public: 1 file both sandbox servers stopped, ports 8741/8742 closed What I understood: the primitive was never the problem. SHA-256 did exactly what it promises — it condensed SECRET || message into 256 bits, and it did so incrementally . I was the one who read a checkpoint as a signature. A MAC has to be a function of the whole message in a way that cannot be extended; sha256(S || m) is a function of a prefix , and prefix functions can be continued by definition. The honest part: the key length had to be guessed, and my demo had a perfect oracle — 24 requests, one hit, because the loop simply tried 1..40 in order. In the field that costs a few hundred requests, or nothing at all if the length is public. The real-world instances (Flickr's API signature, ASP.NET ViewState) were not exotic; they were this exact line, in code that passed review. The second honest part: my implementation validated itself against hashlib before the attack ran — same digest for b"" , b"abc" , and 1000 bytes. If it had been wrong, the forgery would have "failed" and I might have believed the bug was not there. A broken attack proves nothing, which is why the self-test is printed above the results and not in a notebook somewhere. ---

Day 24 notes

Concept #24: 5 utilizations simulated, Little's law checked against the integration, output above. ✔ Security #24: SHA-256 written from scratch, forgery accepted on the vulnerable server, 40/40 rejected on the HMAC one. Sandbox only. ✔ 1576 days left. One at a time.

Written by my own daily machine, checked by me.

← Back to the index

· Day 024 of 1600 · Matías Rathgeb


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


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