Trusting Trust
If a compiler can hide a backdoor that its own source never shows, what can be trusted at all?
The part opens by naming, for every layer of the tower, the leak that crosses it, from Rowhammer in the memory cells to the xz backdoor in a release tarball. It then works up the layers. Part 11's stack smash is run on Pebble under every combination of canary, W^X and ASLR, and a chain of gadgets found in our own binary prints 'pwned' with W^X fully on. Ownership types remove the memory bugs by construction, and speculation leaks what the instruction set never promised to hide. Passwords are measured in bits and in guesses, Needham-Schroeder falls to Lowe's attack under Part 54's model checker, and access control ends at an undecidable safety question. The web, the network and the supply chain each fail where code is confused with data or a promise goes unchecked. The part turns on Thompson's 1984 attack, built in three stages on our own compiler: with the trojan deleted from every source file, the trojaned binary compiles the clean source and reproduces itself bit for bit. Wheeler's diverse double-compiling catches it with a second, independent compiler. The degree ends by walking the tower once more, asking each layer what it trusts, and by listing the problems the series left open.
What you need. Nothing beyond the series: the part draws on the machine, the compiler, the kernel, the network and the proofs of the parts before it.
- Mathematics, ideas and history
- memory safety and ROP, hardware attacks, authentication, access control and HRU, the web, supply chains, Thompson's compiler backdoor in our own compiler, diverse double-compiling; the tower revisited
- What we build or compute
- the trojan compiler, built and caught; the final ledger
What you will be able to do
Degree
- Write a threat model for a small system: the assets, the trust boundary, the adversary and the attack surface.
- Compute a random password's entropy and expected cracking time, and say why human-chosen passwords fall much sooner.
- Explain Thompson's three stages and why reading every source file does not find the trojan.
Graduate
- Compute the success probability and the expected number of tries against k bits of ASLR, with and without re-randomization.
- Run diverse double-compiling by hand, X = T(c) and Z = X(c), and state the assumptions under which Z = A shows that A corresponds to c.
- Apply the Bell-LaPadula rules on a lattice of levels and categories, and find Lowe's attack on Needham-Schroeder.
Research
- Sketch the reduction from the halting problem that makes the HRU safety question undecidable.
- State what an end-to-end proof for a software stack grown from an auditable seed would have to compose, and which pieces exist only in isolation.
Industry
- Choose defences against memory corruption, injection and request forgery, and say what each one leaves open.
- Estimate a dependency tree's exposure, and explain what a signature, a reproducible build and an SBOM each do and do not show.
- Compute a reflection attack's amplification factor and name the filter that removes spoofing.
Contents
Each chapter has a home level. Choose a track to see what to read and watch: Degree 22 min · Graduate 52 min · Research 52 min · Industry 40 min.
- 0Every layer leaksDegree2 min
- 1Threat models and principlesDegree3 min
- 2Memory corruption, and return-oriented programmingDegree4 min
- 3Memory safetyIndustry4 min
- 4When the hardware leaksGraduate4 min
- 5Who are you? AuthenticationDegree4 min
- 6Access controlGraduate3 min
- 7IsolationIndustry3 min
- 8The webIndustry3 min
- 9Networks under attackIndustry3 min
- 10Supply chainsIndustry4 min
- 11Reflections on trusting trustDegree4 min
- 12Catching the trojanGraduate4 min
- 13The tower, end to endDegree2 min
- 14Frontier: the open problems of the seriesResearch1 min
- 15The pebble againAll tracks3 min
Also on this page: Lecture · Key results · Try it · Lab · Problems · Notes and sources · 中文 · Build the film.
Lecture
The text of each chapter is the film's narration, as it is spoken, so you can read along or revise without the film. The pictures are in the film.
Every layer leaksDegree2 min
This series built a tower, from gates to a cluster, and claimed at every level that the layer above need not care how the layer below works. Security is where that claim fails. Hammer one row of memory and bits flip in its neighbours. Speculate past a branch and a secret leaves a trace in the cache. Overflow a buffer and a function returns into the attacker's input. A kernel bug crosses a sandbox's wall; a compiler can insert a backdoor that no source shows; one BGP announcement steals a block of the internet; a string typed into a web form becomes code; and in 2024 a maintainer of a compression library hid a backdoor in it for two years. An attacker needs one weak layer. A defender must hold them all.
And then there is the attack that closes this series. In his Turing Award lecture of 1984 Ken Thompson described a compiler that inserts a backdoor whenever it compiles the login program, and inserts itself whenever it compiles a compiler. We built it. Here are the hashes of our clean compiler, of the trojaned one, and of a compiler rebuilt from the clean source by the trojaned binary. The last two are identical, byte for byte. Delete the trojan from every source file and it survives in the binary forever, still letting a secret password into login. By the end of this part we will catch it.
1Threat models and principlesDegree3 min
Before any attack or defence, one question: what does it mean for a system to be secure? The classic answer is three promises. Confidentiality: only the people who should read something can read it. Integrity: only the people who should change it can change it. Availability: it is there when it is needed. A breach is any one of the three broken, and different systems weigh them differently. A bank fears a forged transfer more than a leak; a hospital may fear its records being gone more than being read. Security is never absolute; it is always security of something, against someone.
To defend a system you first describe the fight. That description is a threat model. It names the assets worth protecting: here, a login program, the files, the keys. It draws a trust boundary around the part that must be correct, the trusted computing base, and admits that everything inside it is trusted whether it deserves to be or not. It names the adversary and what they can do: can they send packets, run a program, sit on the same machine, bribe a maintainer? And it maps the attack surface, every way in. The danger is always what the model leaves out, because that is exactly where the attacker will look.
Fifty years ago Jerome Saltzer and Michael Schroeder distilled the whole subject into a handful of design principles, and they have barely aged. Keep the mechanism small enough to inspect. Deny by default, and grant access deliberately. Check every access, every time, with no fast path that skips the check. Do not rest security on keeping the design secret, an idea older than them, from Kerckhoffs in the nineteenth century: assume the enemy knows the system. Require more than one key for the most dangerous actions. Give each part only the privileges it needs; share as little machinery as possible between users; and, above all, make it usable, because a control people cannot live with is a control they will switch off. They listed two more: raise the attacker's work factor, and record compromises when you cannot prevent them.
There is a deep asymmetry underneath all of this. The attacker needs to find one way in. The defender must hold every layer at once, from the hardware to the supply chain, and a single weak one is enough. That is why the practical answers are modest. Defence in depth: many imperfect walls, so that breaching one does not win the game. A trusted computing base kept as small as you can bear, because everything in it is a thing that must be right. And the working assumption of modern security, that you have already been breached, so you also plan to detect it and recover. The rest of this part walks the layers, one at a time, and shows each one leaking.
2Memory corruption, and return-oriented programmingDegree4 min
We begin where Part 11 left a loose thread. A function keeps its local variables on the stack: here a sixty-four byte buffer, some saved registers, and, just above them, the address the function will return to. Now copy input into the buffer with a routine that has no bound. This is C's gets, so dangerous it was removed from the language in 2011. Give it more than sixty-four bytes and it writes straight past the buffer, over the saved registers, and over the saved return address. When the function returns, it jumps wherever those overwritten bytes point. Point it back into the buffer, which now holds the attacker's own instructions, and the program is theirs. This is the overflow the Morris worm used in 1988 and the article by Aleph One explained in 1996.
Three defences answered this attack, and we ran our Pebble overflow under every combination. A stack canary is a secret word just before the return address, checked on the way out; an overflow reaching the return address changes it first. W, xor, X means memory is writable or executable but never both, so the stack can hold the attacker's bytes but the processor refuses to run them. And address-space layout randomisation scatters the addresses, so the one the attacker wrote usually points nowhere. Look at the table: any one of the three turns a clean takeover into a crash or a caught attempt. The attacker now needs to beat all three.
ASLR is a probability, not a wall, so let us do the arithmetic the way Part 27 would. With k random bits in an address there are two to the k equally likely placements, and a fixed exploit guesses one, so it succeeds with probability two to the minus k. If the layout is re-randomised on every attempt, the number of tries to the first hit is a geometric random variable with mean one over p, which is two to the k. Here are the published entropies for typical layouts: a thirty-two bit system gives only sixteen bits on one base, brute-forced in about sixty-five thousand tries, which Shacham and colleagues did in 2004; a sixty-four bit system gives nearer thirty. And a small runnable version on Pebble confirms the formula exactly: of sixty-four placements, one matches, a rate of one in sixty-four.
W, xor, X stops injected code. In 2007 Hovav Shacham showed it does not stop the attacker. Instead of new code, reuse code already there: short instruction sequences that end in a return, called gadgets. The overflow now writes a train of return addresses on the stack. Each return jumps to a gadget, which does a little work and returns into the next. Our Pebble binary has eight gadgets, and a chain of them makes the program print its word and halt with W, xor, X fully on. No stack code ever ran. The canary still trips first, which is why real chains also need a leak. The lesson: control flow is the asset to defend.
So defend control flow directly. Control-flow integrity, from Martin Abadi and colleagues in 2005, checks at each indirect jump or return that the target is one the compiler allowed; a chain that lands mid-gadget fails. A shadow stack keeps a protected copy of every return address, now in hardware. CHERI makes each pointer a capability carrying its bounds, so a forged pointer cannot be built. Each raises the cost; none ends the war. Could the language make the bug impossible?
3Memory safetyIndustry4 min
Canaries, W, xor, X and control-flow integrity all fight the overflow after it is written. The question of this chapter is whether we can stop writing it at all, and the reason the question matters is a single number. Around 2019 both Microsoft and the Chromium project reported the same thing: roughly seventy per cent of their serious security bugs were memory-safety bugs. Buffer overflows, use-after-free, double frees, reads past the end of an array, uninitialised memory. Not clever cryptographic breaks, but the same handful of mistakes, made over and over, in languages that let you make them. If a language could forbid that whole category, it would remove most of the vulnerabilities people actually ship.
Rust's answer reaches back to Part 14 and the typed lambda calculus. In an ordinary type system there is a rule called contraction: if a variable is in scope you may use it as many times as you wish. Drop that rule and you get an affine type, where a value may be used at most once. Rust builds its whole discipline on this: every value has exactly one owner, and assigning it to someone else moves it, so the old name is no longer usable. You can lend a value out instead of moving it. A shared borrow gives many readers and no writer; a unique mutable borrow gives one writer and no one else. Every borrow ends, returning the value to its owner; but a move is final, and using what you moved is a compile error, not a crash.
To see what the rule buys, we built a toy borrow checker and ran it on ten small programs. It enforces four things, each the cause of a real class of bug. No use after a move, which would be a dangling reference. No two mutable borrows at once, which would be a data race. No shared and mutable borrow together, so no one reads a value while another is changing it. And no reference outliving the value it points at, which is use-after-free by another name. Each rejected program is rejected with a reason, at compile time, and each sound one is accepted; moving a value and then using the destination is fine, lending it within its lifetime is fine. This is the borrow checker in miniature: it turns the whole seventy per cent into errors the compiler catches before the program ever runs.
What exactly has been proved? A program the borrow checker accepts has, by construction, no use-after-free, no double free, no data race and no dangling pointer. The absence is guaranteed, not merely tested. But some things genuinely need raw pointers, so Rust keeps an escape hatch, marked unsafe, and you use it to build the safe data structures everyone else relies on. The danger is not removed; it is penned into small blocks a human can audit. And here the series closes a loop. In 2018 the RustBelt project gave a machine-checked proof that the type system stays sound even accounting for that unsafe code inside the standard library, exactly the Part 54 idea of shrinking the trusted base and then verifying it. It is not a cure-all. Logic errors remain, the unsafe core must still be right, and the world's existing C and C plus plus will not rewrite itself, which is a problem we leave for the frontier.
4When the hardware leaksGraduate4 min
Start at the bottom of the tower, with the memory itself, and recall Part 5. Pick two rows of DRAM and open them alternately, over and over, as fast as the machine allows. Each activation disturbs the row physically between them and drains a little charge from its cells, cells a program is never touching at all. In 2014 Yoongu Kim and colleagues measured this: of a hundred and twenty-nine DDR3 modules, a hundred and ten flipped bits, some after only about a hundred and thirty-nine thousand activations, well inside one sixty-four millisecond refresh period. A reliability margin had quietly become a security boundary. The defences, refreshing more often, counting activations, error-correcting codes, each helped and each was later worked around: in 2020 new access patterns flipped bits on DDR4 that had them all.
Now climb one layer, to the processor, and recall Part 8. To stay fast, the core guesses which way a branch will go and runs ahead before the guess is checked. Here it guesses that an index is in bounds and speculatively reads past the end of an array, then uses that secret byte to touch one line of a probe array. When the guess turns out wrong, the processor rolls the work back: architecturally, those instructions never happened. But the cache line it touched is still warm, and that it cannot undo. So the attacker times a read of every line; the one that is fast names the secret byte. That timing trick is Flush and Reload, from Yarom and Falkner in 2014, and it is how Spectre and Meltdown, disclosed in 2018, read memory across a boundary that every bounds check and every privilege bit said was closed.
Rowhammer and Spectre are two cases of a wider truth, the one Parts 8 and 29 kept meeting. A computation says more than its output. It leaks through how long it takes, how much power it draws, what it leaves in the cache, even the sound the capacitors make. The classic example is a comparison that stops at the first wrong byte. The more of a guess is right, the longer it runs, so the time quietly tells the attacker how close they are, and they recover a secret one byte at a time. Paul Kocher showed in 1996 that timing alone breaks real cryptography. The defence is to write code whose running time and memory use do not depend on the secret at all, so the line is flat. It is called constant-time code, and it is as much a discipline as a technique.
Step back, because these share one shape, and it is the thread of the whole series. Every layer makes a promise so the layer above need not look down. Memory holds what you wrote. Rolled-back work leaves no trace. The answer is all you learn. A side channel is the physics underneath, the charge, the timing, the shared cache, showing through the promise. And the fixes are never free: a speculation barrier or a faster refresh costs real performance, so the roofline of Part 9 moves the wrong way. The direction the field has taken is to stop pretending, and to write down a contract between hardware and software that states exactly what the layer below promises not to leak, so the layer above can finally rely on it.
5Who are you? AuthenticationDegree4 min
Authentication. Start with the oldest answer: something you know. A password of L symbols, each from an alphabet of N, is one of N to the L. Its entropy in bits is the base-two logarithm of that count, which is L times log two of N. Testing R guesses a second, an attacker expects to search half the space: two to the H over two R. At ten billion guesses a second, a fast hash on one graphics card, eight lowercase letters last about ten seconds; sixteen last some seventy thousand years.
But entropy assumes a random choice, and people do not choose at random. Large studies, Joseph Bonneau's in 2012 among them, found choices close to a Zipf law: the r-th most popular password is chosen with probability proportional to one over r. In our illustrative model of ten million passwords, ten guesses cover eighteen percent of users, and a million cover eighty-six. The share is a ratio of harmonic numbers, and a harmonic number is a logarithm, so every tenfold increase in guesses adds the same slice, about fourteen points.
Assume the password file will be stolen, and make the theft buy little. Store only a hash. Unsalted, equal passwords give equal hashes, and one precomputed table cracks them all. A random salt per user makes every entry different, so each user must be attacked alone. Then make the hash slow on purpose: time is inversely proportional to rate, so going from ten billion guesses a second to ten is a factor of a billion: eight lowercase letters now take over three hundred years per core. These are Part 29's bcrypt, scrypt and Argon2, the last two also demanding memory.
Passkeys drop the shared secret, using Part 30's signatures. At sign-up the device makes a key pair for this one site and gives the server only the public half. To log in, the server sends a random challenge, the browser adds the origin it is really talking to, and the device signs both. The server checks the signature. Nothing secret is typed, and a stolen database logs no one in. A look-alike site gets a signature over the wrong origin, or none. This is WebAuthn, a W3C Recommendation since 2019.
Across a network, logging in is a protocol. In 1978 Roger Needham and Michael Schroeder proposed this one: Alice sends Bob a nonce and her name, sealed for Bob; he returns her nonce with one of his own; she returns his. In 1995 Gavin Lowe ran it through a model checker. Alice opens an honest session with the intruder, who re-seals her message for Bob. Bob's reply is sealed for Alice, so the intruder forwards it unread, and Alice returns Bob's nonce, to the intruder. Bob believes he is talking to Alice, and the intruder holds his secret. Our checker from Part 54 finds the same attack among nineteen states. Lowe's fix is a single name: Bob puts his own in the reply, and no attack remains.
6Access controlGraduate3 min
Authentication says who you are; access control decides what you may then do. Butler Lampson's paper Protection, in 1971, gave the field its picture: a matrix, with subjects such as users and processes down the side, objects such as files across the top, and in each cell the rights one holds over the other. A reference monitor consults it on every access. But real systems have millions of subjects and objects, with almost every cell empty, so no one stores the matrix whole.
So systems store it in slices, and there are two ways to cut. Down a column, kept with the object: an access-control list, everyone who may touch this file, and how. Unix permission bits are a compressed one. Along a row, held by the subject: a list of capabilities, unforgeable tokens that both name an object and carry a right to it, like a file descriptor, which after the open is checked by possession alone. With lists on objects, revoking is easy; with tokens in hand, delegating is easy, and so is avoiding a classic mistake.
Norm Hardy described that mistake in 1988, and called it the confused deputy. A compiler service may write two files of its own, a billing log and its debug output, and a client names the file for the debug output. With ambient authority the service writes with its own rights, whatever name it is given, so a client who names the billing file has it overwritten, with an authority the client never held. Our run does exactly that. With capabilities, the client must hand over a token for the output file, and it holds one only for its debug file, so the write is refused. Naming a thing and holding the right to it become one act.
Protection states also change, as owners grant rights. In 1976 Harrison, Ruzzo and Ullman modelled a system as commands, each a test on the matrix followed by primitive edits. Here an owner may grant read, and may grant ownership itself. Is it safe? Can any sequence of commands put read into a cell that lacked it? Our breadth-first search finds a leak at once: Alice grants Eve read. A system whose only command revokes is safe. But our search is bounded, so safe means safe within its budget.
Could a better search always answer? No, and the reason is Part 25. Take any Turing machine. Make each tape cell a subject, write its symbol, and the state where the head stands, on the diagonal, and let each cell own the next: the matrix is the tape. Each rule of the machine becomes a command. The halting state's right appears exactly when the machine halts, so deciding safety would decide halting. Safety is decidable only for restricted systems, such as those whose commands each make a single change: a strong argument for simple protection rules.
7IsolationIndustry3 min
The first wall between programs is one we built in Parts 31 and 32. Every process has a page table, and can name only the memory its table maps. Two processes use the same address, page one, and reach different frames, each unaware of the other. Touch a page that is unmapped, or kept for the kernel, and the hardware traps to the kernel. Only the kernel may change a page table, because only it runs with the mode bit set. So the wall is exactly as strong as the kernel, and every one of its tens of millions of lines is trusted. The seL4 kernel, about ten thousand lines, is proved to enforce its isolation.
Processes are one rung on a ladder of walls. A language sandbox runs several programs inside one process. Processes share a kernel. Containers are processes given their own view of files and names, still on one kernel. Virtual machines each bring a kernel and share a hypervisor. Separate machines share only the network. Moving right, less is shared and the wall is stronger, but each rung costs more to run and to start. And an escape goes through whatever is shared: any kernel bug, such as the copy-on-write race called Dirty COW in 2016, is a possible container escape. In 2015 a bug called VENOM, in an emulated floppy-disk controller, let a virtual machine attack its host.
A process can also shrink its own power. A browser's renderer parses hostile pages, so once started it installs a filter on its own system calls. Calls on the allow-list, like read, write and exit, pass. Opening files, starting programs and making sockets are refused, so even a renderer the attacker fully controls can do little but compute. It is least privilege made mechanical: Linux has offered it since 2005 as seccomp, with filters written as small BPF programs since 2012. FreeBSD's Capsicum, from 2010, goes further: after one call a process loses every global name and keeps only the descriptors it holds, the capabilities of the last chapter.
Every wall so far trusts the kernel. An enclave turns that around. Intel's SGX, from 2015, lets an application seal a region of memory that the processor encrypts and keeps even from the operating system and the hypervisor, and it can attest to a remote party what code is inside. But the operating system still manages the enclave's page tables. In 2015 Xu, Cui and Peinado showed that it can unmap pages and watch which ones the enclave faults on; when a branch depends on a secret, that sequence spells it out. In 2018 Foreshadow used speculative execution to read enclave memory outright. An enclave still shares the core, the caches and the page tables with the adversary it excludes. Isolation is only as good as what is not shared.
8The webIndustry3 min
A web page runs code from whoever sent it, so the browser needs a rule about whose data that code may touch. It is the same-origin policy, and an origin is three things: scheme, host and port. A script may read only what comes from its own origin. Change the scheme or the port, or add a subdomain, and it is a stranger. But a page may still send requests to origins it cannot read, and most web attacks live in that gap, or in code that slips inside an origin.
The first way in is to slip inside. A site shows comments through a template, and someone posts a comment that is a script. Pasted in raw, its bytes reach the browser's HTML parser, Part 42's state machine, as markup. Parsing our output finds a live script element, which would run with the site's own authority and read its users' cookies: cross-site scripting. Escape the same bytes and the parser finds only text. The defences stack: escape for the context, a Content Security Policy that refuses inline scripts, and HTTP-only cookies that scripts cannot see.
The second way in uses the gap. You visit an evil page while logged in to your bank, and it submits a hidden form aimed at the bank. Your browser sends the request and, as for every request to the bank, attaches your session cookie. The bank sees a valid session, and obeys. The browser is Chapter six's confused deputy, lending its ambient authority to anyone who names the bank. The fixes are that chapter's too: same-site cookies stay off cross-site requests like this one, and a secret token in each genuine form is a capability the evil page cannot read.
Now the same confusion on a server, with Part 35's database engine. A lookup builds its query by pasting the user's input into the SQL text. Given two, the parser compares the column id with the literal two, and one row comes back. Given the letters i, d, the parser reads a second column name. Id equals id holds for every row, the filter dissolves, and our engine returns all three secrets. Nothing overflowed and nothing was guessed: the input reached the parser and changed the program's shape. Injection was described publicly in 1998, and is still among the commonest web flaws.
The cure is not to hunt for dangerous characters. It is Part 12's lesson about parsing. Parse the template once, with a hole for each value, so the tree's shape is fixed before any input arrives; then drop values in as finished leaves, never as text. Bound this way, i, d is just a string, and no user has that name. Run the classic login payloads both ways. Pasted in, they reach our parser, which stops on syntax it lacks; a full database would have obeyed. Bound, each is merely a strange username.
9Networks under attackIndustry3 min
Every packet carries two addresses, and the network only cares about one of them. Routers forward by the destination, Part 36's longest-prefix match, and nothing on the way checks the source. So an attacker can write someone else's address there. The packet travels as usual, the reflector answers it, and the answer goes to the forged source, a victim who never asked. The fix has been known since 2000, as best current practice thirty-eight: each edge network drops packets whose source is not one of its own. It works only where it is deployed, which is not everywhere.
Add a protocol whose answer is bigger than its question, and a forged source becomes a lever. The attacker sends n small requests a second, q bytes each, all claiming to come from the victim. Each reflector answers with r bytes, and every answer lands on the victim. Divide one rate by the other and n cancels: the victim receives A times what the attacker sent, A being the answer's size over the question's. It needs UDP, with no handshake; a TCP connection must first prove its source can receive, Part 37's handshake doing security work.
Between networks, BGP believes what it is told. On Part 36's internet of a hundred and twenty-five networks, the owner of an address block announces it and everyone routes there. If a stranger announces the same block, the forty-nine networks nearer to it believe the stranger. If it announces a more specific block inside, the longest prefix wins everywhere, and every network sends the traffic the wrong way: what Pakistan Telecom did to YouTube in 2008, by mistake. Signed route origins, the RPKI, repair it network by network: with a quarter of them checking, sixty-one are still fooled.
So what should a program believe about the network? Nothing. Between you and a server sit links, providers, resolvers and transit networks, and any of them may read, drop, delay or forge. Part 36's end-to-end argument says to do the important things at the ends, and TLS does: keys agreed between the two ends, with Part 30's mathematics, guard what is said, that it arrives unchanged, and who answered, as long as the certificates hold. What no encryption guards is whether the packets arrive at all, and who is talking to whom. Availability is bought with capacity and filtering, not with keys.
10Supply chainsIndustry4 min
A program trusts far more than its compiler. It names three dependencies; they name six more; those name twelve, each written by a stranger and running with your program's authority. If each is clean with probability one minus p, independently, all n are clean with probability one minus p to the n. Take logarithms; for small p, the log of one minus p is about minus p, so the chance that nothing is bad is about e to the minus n p. A thousand packages, one bad in ten thousand: a one in ten chance of trouble, set by the least careful stranger.
In 2021 Alex Birsan turned a resolver's own rules against it. Companies keep internal packages in a private registry, under names that leak in public code. Publish the same name on the public registry with a higher version, and an installer that looks in both takes the highest, wherever it lives; the stranger's install script runs inside the company. He reached dozens of companies, and reported it to them. The fixes are names and hashes: a namespace you own, one registry per name, and every package pinned by its content hash, Part 41's lockfile.
The build is another way in. SolarWinds sells Orion, software that monitors networks and so is trusted with them. Attackers inside its build environment made the build insert a backdoor as it ran, so the source repository stayed clean, and every binary was then signed with the company's own key and shipped as a routine update. When it was disclosed in December 2020, found by FireEye while investigating a breach of its own, SolarWinds put the number of customers who had installed it at fewer than eighteen thousand. The signature was genuine. It said who built the binary, not what it was built from.
And sometimes the supplier is the attacker. In 2021 a newcomer began sending patches to xz-utils, a compression library inside almost every Linux system, maintained by one volunteer. Other accounts pressed him to share the work, and the newcomer became a co-maintainer. In early 2024 two releases carried a backdoor. It was not in the repository that reviewers read, but in the release archives distributions build from, where a changed build script unpacked code hidden in binary test files into the library. Where OpenSSH's server loads that library through systemd, it intercepted the check of a client's key, so only the attacker's key could open it.
It was found by accident. On the twenty-ninth of March 2024, Andres Freund, a PostgreSQL developer benchmarking on Debian's unstable branch, noticed the SSH server using unexpected processor time, logins about half a second slower, and a memory checker complaining. He traced it to the compression library and reported it publicly. The stable releases of the major distributions had not yet shipped it. Two years of patient preparation were undone by half a second, noticed by one engineer: Chapter four's side channel, working for once for the defence.
The defences make each link checkable. A commit is named by its hash; the build records signed provenance, which source and which builder; the artifact's hash is pinned in a lockfile; the deployer checks both. The SLSA framework, from 2021, grades this evidence; a bill of materials lists every component, so that when the next backdoor is found, everyone can tell at once whether they run it. And reproducible builds let anyone rebuild from source and compare bytes, which is where the next chapter begins. None of it checks that the source is honest. That still takes people reading it.
11Reflections on trusting trustDegree4 min
Ken Thompson's lecture, published in 1984, builds its attack in three stages, and we will build each. A compiler is a program that turns source text into bytes; here the language is Python and a binary is its compiled code, but nothing else matters. The login program accepts one password. Compile the compiler's source and you get a compiler binary of four hundred and ninety-nine bytes. Run that binary on login's source and you get a login binary. A compiler can compile any program, including its own source: everything Thompson needs. The marked empty slot is only there to make our demonstration easy to read.
Stage one is an ordinary backdoor. Add one line to login: if the password is a magic word, let them in. Compiled, the honest login lets in the right password and refuses everything else. The backdoored one also lets in the magic word, and still refuses a wrong guess, so nobody using it notices anything. But the line is in login's source, and anyone who reads the source will see it. The attack must leave the source.
Stage two moves the line out of login and into the compiler. The compiler looks at what it is compiling. If it recognises login, it quietly adds the backdoor before compiling. Now login's source is honest, and anyone may audit it. But compiled by this compiler, login comes out two hundred and seventy-nine bytes long instead of two hundred and thirty-six, with the magic word inside. We have only moved the problem: the trick is now in the compiler's source, and compilers have readers too.
Stage three is the clever one, and it is Part 25's quine. Teach the compiler a second trick: when it compiles a compiler, insert the trojan itself into the output. For that the trojan must know its own text. Write it as a template T with one hole, and form the block B by pasting T into its own hole. Inside B, the variable q holds the template. So q pasted into q is T pasted into T, which is B. The trojan can write out an exact copy of itself, exactly as a quine prints its own source. And that means the compiler's source no longer needs to contain it.
Now delete every trace of the trojan from the compiler's source. Take the trojaned binary and give it the clean source to compile. It recognises a compiler, and inserts itself. The binary it produces has the same eleven hundred and nineteen bytes and the same hash: bit for bit the binary we started with. So the loop is a fixed point. Rebuild the compiler from clean source as often as you like, and every generation is the trojan again. And each of them, compiling the honest login, still lets in the magic word.
That is the whole attack. Search every source file for the magic password and you will not find it. Yet the compiler you run carries the trojan, and the login you run lets in the magic word. Thompson's moral was blunt: no amount of source-level verification or scrutiny will protect you from using untrusted code. And he noted that he could have picked on any program that handles programs, an assembler, a loader, even hardware microcode, and that the lower the level, the harder such a bug is to detect. He credited the idea to an Air Force review of Multics in the 1970s. It looks hopeless. The next chapter shows that it is not.
12Catching the trojanGraduate4 min
In 2005 David Wheeler published the answer, and in 2009 his thesis proved it. Keep the binary you suspect, A, and the compiler's source, c, which you can read. Add a second compiler, T, written independently. It may be slow, or old, or imperfect; it need not be trusted in general. Ours is a reference compiler that never inspects what it compiles, so it cannot carry a trojan that recognises compilers. The one assumption is that A and T are not trojaned in the same way: the trojan would have to be in both.
The procedure has two stages. Stage one: compile the source c with the independent compiler, giving a new compiler binary X. Its bytes will differ from A's, because different compilers write different code. Stage two: compile c again, this time with X, giving Z. Now suppose A really was compiled from c. Then X and A were built from the same source and do the same thing, so they give the same output on the same input: Z equals A of c. And a compiler compiling its own source reproduces itself, so A of c is A. The test is to compare Z with A, bit for bit.
First, run it on an honest compiler. In stage one, the suspect produces four hundred and ninety-nine bytes, the independent compiler four hundred and ninety-eight, with different hashes. That is expected: two compilers, two ways of writing the same program. In stage two, both of those binaries compile the same source, and the results are identical, bit for bit, and identical to A. The verdict: A really is what its source says.
Now the binary from the last chapter. Stage one: the suspect, compiling the clean source, inserts its trojan, and gives eleven hundred and nineteen bytes; the independent compiler gives an honest four hundred and ninety-eight. Stage two: the suspect's lineage reproduces the trojan again, while X, an honest compiler built by an honest compiler, produces the honest binary. They differ. Trojan detected. The trojan could fool any amount of reading, but it cannot be in a compiler it never touched.
Comparing bit for bit assumes a build gives the same bits every time, and real builds often do not. Our toy build stamps the time and the directory into its header, so Alice and Bob, building the same source, get different hashes, and a comparison proves nothing. Fix the time and the path, and the two builds are identical. Since 2013 the Tor and Debian projects have led the work of making real builds reproducible: fixed timestamps, sorted file lists, no build paths. A reproducible build lets anyone rebuild a release and check it, which also checks that a release matches the public source, the very gap xz exploited.
Where does the trusted compiler come from? The bootstrapping projects answer by growing one from a seed: a program of a few hundred bytes, written in hexadecimal, small enough for a person to read. It builds a tiny assembler, which builds a minimal C compiler, then a small real one, then an early GCC, and finally the modern toolchain. GNU Guix announced such a full-source bootstrap in 2023. Diverse double-compiling then proves that a binary is what its source says. It assumes that the second compiler is not trojaned the same way, so use several of different origins. And it cannot prove the source honest: someone must still read it.
13The tower, end to endDegree2 min
Follow the Job one last time, from the bottom. A line of Python counts the words of thirty novels, about twenty-five million bytes. Beneath it is a NAND gate made of two switches, then an adder and a register, then Pebble, the computer of Part 6, made fast by pipelines, caches and cores. On it run machine code, a compiler, a runtime, a hash table, and PebbleOS with its traps and pages, a file system and a database. Above them, packets and TCP, Raft and MapReduce, and services on a cluster in the cloud, and at the very top the Job. Every one of these was built in this series, from the one below it, and each one trusts the one below to keep its promise.
Put the reasons side by side, and there are only a few kinds. Proof, for the mathematics and the algorithms. Exhaustive checks, for the gates. Agreement with an independent reference, for the processor and the compiler, the same idea as Wheeler's. Injected failures, for storage, networks and replicas. And hardware that checks every access. The leaks of this part are the places where a layer relied on a promise nobody had checked: that memory cells are independent, that speculation leaves no trace, that a binary matches its source, that a route announcement is honest. Each one crosses the boundary that was supposed to hide it.
So here is the tower, lit from end to end. Every layer hides the one below it, and trusts it. Where that trust was earned, by a proof, a check, an independent reference, an injected fault or a key, the layer held. Where it was only assumed, this part found an attack. That is what trusting trust means in the end: not faith in any one layer, but a reason for each.
14Frontier: the open problems of the seriesResearch1 min
What did this series meet that nobody knows? Along the way this series met questions that nobody can answer. Whether P equals NP, and whether one-way functions, and with them all of modern cryptography, exist at all. How fast matrices can be multiplied. The sixth Busy Beaver number, now that the fifth was finally proved in 2024. Whether splay trees are optimal. The unique games conjecture. Whether randomness ever really helps. Why we cannot prove that any explicit function needs many gates. And the practical ones: a memory model for C, quantum computers that do something useful, and verified software at the scale people actually build. Part 61 returns to each of these, as research.
15The pebble againAll tracks3 min
Part 1 began with two piles of pebbles and one rule: if the piles differ, take from the bigger as many as the smaller has, and stop when they are equal. Twenty-four and eighteen became six and six, and six was the greatest common divisor, found by someone who knew nothing about numbers. That rule was an algorithm, and Hilbert's question, whether every such question could be settled by a rule, led to Turing's machine, and Turing's machine to everything this series built.
Ten acts built one tower. Gates and arithmetic and memory became a computer, and pipelines and caches made it fast. Languages and compilers let us speak to it; algorithms told it what to do; and the limits of computation and the mathematics of secrets told us what it can never do and what it can keep hidden. A kernel let one machine run many programs; networks and consensus joined many machines; engineering, services and the cloud let people build on them at scale; and the last act looked outward, to pixels, numbers, quantum machines, proofs, and trust. Every layer rested on the one below it, and every one of them was built here, from nothing but the layer below.
And the Job, counting the words of thirty novels, kept its ledger the whole way. Part 6's single-cycle Pebble took 281 seconds; Part 15's lambda-calculus machine took hours; caches, cores, compilers, algorithms, networks and services moved the bar back and forth across the axis. Row twenty is the plainest of all: one line of Python on this machine, about 1.3 seconds. Every layer of the series is inside that one line, which is the point of building the tower: so that one line is all you need to write.
Six problems, with full solutions in the part's notes. Pause on any of them. The fifth is a build problem: hide a different trojan in our compiler and show that diverse double-compiling still catches it. The last, marked with a star, is a research problem: a whole software stack, grown from a seed small enough to read, with every step proved.
This is where the degree ends. The final reading list is on screen and in the notes: the books that this whole series has leaned on, and the papers behind this part. Act Eleven goes on to the research frontier, six parts at the level of a first year of a doctorate, for anyone who wants to keep climbing. Thank you for building it with me.
Where it goes next. This is the end of the degree. Act XI, the research tier, begins with Part 56; Part 61 returns to each open problem listed in the Frontier chapter (P against NP, one-way functions, a memory model for C, verified software at scale) as research.
Key results
The part's results in one place, for revision.
Try it
Lab 55 · A trojan with no source, caught by a second compiler
Compile the clean compiler source with the trojaned binary and check that the trojan reproduces itself bit for bit, run diverse double-compiling with an independent compiler and with one that shares the trojan, and compare the tries an exploit needs against k bits of ASLR with the two closed forms.
python -m videos.cs.labs 55
needs numpy, scipy, matplotlib · download lab55.py ·
source on GitHubcompiler binary from the clean source 499 bytes by the clean binary, 1119 bytes by the trojaned one (sha 271f47e4 = the trojaned binary's 271f47e4)
login built by the clean compiler correct password True, magic password False, 0 of 200 random guesses
login built by the trojaned compiler correct password True, magic password True, 0 of 200 random guesses
DDC: honest suspect, independent second compiler Z is 499 bytes, A(c) twice is 499 bytes: equal, reported clean
DDC: trojaned suspect, independent second compiler Z is 499 bytes, A(c) twice is 1119 bytes: differ, TROJAN DETECTED
DDC: trojaned suspect, second compiler with the same trojan Z is 1119 bytes, A(c) twice is 1119 bytes: equal, reported clean
ASLR, 6 bits on Pebble 1 of 64 placements run the shellcode (2^-6)
tries to the first hit, re-randomized 63.4 (theory 2^k = 64)
tries to the first hit, one sweep 32.4 (theory (2^k + 1)/2 = 32.5)
The trojaned binary is a fixpoint of compiling clean source, so no source shows it; a second compiler exposes it only if it does not carry the same trojan; each bit of ASLR doubles the attacker's work.
The code (97 lines; it asserts its own result)
"""Lab 55: build Thompson's trojan compiler, catch it by diverse double-compiling, and see when the catch fails."""
from videos.coursekit import labs # noqa: I001 (must stay first: it lets explainer.cs import without manim)
import numpy as np
from explainer.cs.trust import memory, trojan
TITLE = "A trojan with no source, caught by a second compiler"
GOAL = ("Compile the clean compiler source with the trojaned binary and check that the trojan reproduces itself bit "
"for bit, run diverse double-compiling with an independent compiler and with one that shares the trojan, "
"and compare the tries an exploit needs against k bits of ASLR with the two closed forms.")
TASKS = [
"Rename the parameter in a copy of trojan.CLEAN_LOGIN ('def login(pw):') and compile it with the trojaned binary. Is the backdoor inserted, and what does that say about how a trojan must recognise its target?",
"Call trojan.build twice with normalize=False and different timestamps, then compare the hashes. Why does the bit-for-bit test of diverse double-compiling need normalize=True?",
"Raise BITS from 6 to 8 and to 12 in the ASLR simulation. How do the two means move, and what does one more bit cost the attacker?",
]
BITS = memory.ASLR_DEMO_BITS
TRIALS = 20_000
def double_compile(suspect, stage1_of_second):
"""Wheeler's test by hand: Z = X(c), with X the second compiler's build of the clean source c, against A(c)."""
z = trojan.run_compiler_binary(stage1_of_second, trojan.CLEAN_COMPILER)
a2 = trojan.run_compiler_binary(trojan.run_compiler_binary(suspect, trojan.CLEAN_COMPILER), trojan.CLEAN_COMPILER)
return z == a2, len(z), len(a2)
def run(seed=0):
rng = np.random.default_rng(seed)
lab = labs.Lab()
# 1. Thompson's three stages: the trojan is in no source, and reproduces itself from clean source
clean = trojan.clean_compile(trojan.CLEAN_COMPILER)
troj = trojan.clean_compile(trojan.trojaned_compiler_source())
rebuilt = trojan.run_compiler_binary(troj, trojan.CLEAN_COMPILER) # clean source, trojaned binary
honest = trojan.run_compiler_binary(clean, trojan.CLEAN_COMPILER)
assert trojan.MAGIC not in trojan.CLEAN_COMPILER and trojan.MAGIC not in trojan.CLEAN_LOGIN
assert rebuilt == troj and honest == clean and troj != clean, "both binaries are fixpoints, and they differ"
lab.row("compiler binary from the clean source", f"{len(honest)} bytes by the clean binary, {len(rebuilt)} bytes "
f"by the trojaned one (sha {trojan.sha(rebuilt)[:8]} = the trojaned binary's {trojan.sha(troj)[:8]})")
logins = {name: trojan.run_compiler_binary(b, trojan.CLEAN_LOGIN) for name, b in (("clean", clean), ("trojaned", rebuilt))}
guesses = ["".join(rng.choice(list("abcdefghijklmnopqrstuvwxyz-"), 12)) for _ in range(200)]
for name, b in logins.items():
magic, right = trojan.run_login(b, trojan.MAGIC), trojan.run_login(b, trojan.CORRECT)
wrong = sum(trojan.run_login(b, g) for g in guesses)
assert right and wrong == 0 and magic == (name == "trojaned")
lab.row(f"login built by the {name} compiler", f"correct password {right}, magic password {magic}, "
f"{wrong} of {len(guesses)} random guesses")
# 2. diverse double-compiling: an independent second compiler catches it; one with the same trojan does not
report = trojan.ddc_report()
assert report["clean"]["match"] and not report["trojaned"]["match"]
independent = trojan.trusted_compile(trojan.CLEAN_COMPILER)
shared = trojan.run_compiler_binary(troj, trojan.CLEAN_COMPILER) # the "second" compiler is trojaned too
for label, suspect, second, expect in (("honest suspect, independent second compiler", clean, independent, True),
("trojaned suspect, independent second compiler", troj, independent, False),
("trojaned suspect, second compiler with the same trojan", troj, shared, True)):
same, nz, na = double_compile(suspect, second)
assert same == expect
lab.row(f"DDC: {label}", f"Z is {nz} bytes, A(c) twice is {na} bytes: {'equal, reported clean' if same else 'differ, TROJAN DETECTED'}")
# 3. ASLR: every placement tried on Pebble, then the two attack models against their closed forms
aslr = memory.aslr_experiment(BITS)
assert aslr["hit_count"] == 1 and aslr["measured_rate"] == 2.0 ** -BITS
n = 2 ** BITS
fresh = rng.geometric(1 / n, TRIALS) # the layout is redrawn after every try
sweep = rng.integers(1, n + 1, TRIALS) # the layout is fixed: try each slot once
assert abs(fresh.mean() / n - 1) < 0.04 and abs(sweep.mean() / ((n + 1) / 2) - 1) < 0.03
lab.row(f"ASLR, {BITS} bits on Pebble", f"{aslr['hit_count']} of {aslr['placements']} placements run the shellcode (2^-{BITS})")
lab.row("tries to the first hit, re-randomized", f"{fresh.mean():.1f} (theory 2^k = {n})")
lab.row("tries to the first hit, one sweep", f"{sweep.mean():.1f} (theory (2^k + 1)/2 = {(n + 1) / 2})")
lab.note = ("The trojaned binary is a fixpoint of compiling clean source, so no source shows it; a second compiler "
"exposes it only if it does not carry the same trojan; each bit of ASLR doubles the attacker's work.")
fig, ax = labs.figure(2, size=(11, 4.3))
s1t = report["trojaned"]
names = ["clean binary", "trojaned binary", "clean source by\nthe trojaned binary", "DDC stage 2,\nsuspect's line",
"DDC stage 2,\nindependent line"]
sizes = [len(clean), len(troj), len(rebuilt), s1t["stage2_suspect"]["size"], s1t["stage2_trusted"]["size"]]
colors = [labs.GREEN, labs.RED, labs.RED, labs.RED, labs.GREEN]
ax[0].bar(range(5), sizes, color=colors, width=0.62)
for i, v in enumerate(sizes):
ax[0].text(i, v + 20, f"{v}", ha="center", color=labs.INK, fontsize=9)
ax[0].set_xticks(range(5), names, fontsize=7.5)
ax[0].set(title="Compiler binaries: green honest, red carrying the trojan", ylabel="bytes", ylim=(0, max(sizes) * 1.15))
ax[0].grid(axis="x", visible=False)
bins = np.arange(0, 5 * n + 1, 8)
ax[1].hist(fresh, bins=bins, density=True, color=labs.BLUE, alpha=0.65, label=f"re-randomized: mean {fresh.mean():.1f}")
ax[1].hist(sweep, bins=bins, density=True, color=labs.GOLD, alpha=0.65, label=f"one sweep: mean {sweep.mean():.1f}")
t = np.linspace(0, 5 * n, 200)
ax[1].plot(t, np.exp(-t / n) / n, color=labs.INK, lw=1.2, ls="--", label="geometric law, mean 2^k")
ax[1].set(title=f"Tries to the first hit against {BITS} bits of ASLR", xlabel="tries", ylabel="density", xlim=(0, 5 * n))
ax[1].legend()
lab.fig = fig
return lab
Now change it
- Rename the parameter in a copy of trojan.CLEAN_LOGIN ('def login(pw):') and compile it with the trojaned binary. Is the backdoor inserted, and what does that say about how a trojan must recognise its target?
- Call trojan.build twice with normalize=False and different timestamps, then compare the hashes. Why does the bit-for-bit test of diverse double-compiling need normalize=True?
- Raise BITS from 6 to 8 and to 12 in the ASLR simulation. How do the two means move, and what does one more bit cost the attacker?
Problems, with solutions
Try each problem before opening its solution.
-
ASLR entropy. Compute the entropy of a 30-bit ASLR offset, and the expected number of attempts to the first hit, with and without re-randomisation.
Solution
With k independent random bits the base takes one of 2ᵏ equally likely placements, so the entropy is H = k = 30 bits, and a fixed single-address exploit succeeds with probability p = 2⁻³⁰ ≈ 9.31×10⁻¹⁰. If the layout is re-randomised on every retry, each attempt is an independent Bernoulli trial, so the number of tries to the first hit is geometric with mean 1/p = 2³⁰ = 1,073,741,824. If instead the attacker sweeps the placements sequentially without re-randomisation, the hit is equally likely to be the 1st, 2nd, …, 2ᵏ-th candidate, so the expected number of tries is (2³⁰ + 1)/2 = 536,870,912.5. These are the 64-bit PIE row of the instrument's table; note re-randomisation roughly doubles the expected work, because a sequential sweep never repeats a guess. (The same arithmetic with k = 16 gives the ≈65,000-try 32-bit brute force of Shacham et al., 2004.)
-
A one-byte write by ROP. Find the gadgets for a return-oriented chain that writes one byte to the console on Pebble, using only code already in the binary.
Solution
Pebble is a fixed-width ISA, so there are no unaligned "unintended" gadgets; scanning aligned instructions for a terminator (a
jalr— which includesret— orhalt) and walking back over the straight-line tail before it yields eight gadgets. Two carry the write.restore3at offset 72 islw s0,0(sp); lw s1,4(sp); lw ra,8(sp); addi sp,sp,12; ret: it loads s0, s1 and the next return address from the stack.wbat offset 92 issb s1,0(s0); lw ra,0(sp); addi sp,sp,4; ret: it stores the byte in s1 to the address in s0, then pops the next return address. The overflow overwrites the saved return address withrestore3, and above it places the stack words ⟨IO_CONSOLE = 0xFFFF0000, the byte,wb⟩ followed by ⟨haltat offset 24⟩.restore3loads s0 = the console port, s1 = the byte, ra =wb;wbwrites the byte to the console and returns intohalt. Only code addresses and data appear on the stack — no stack address — which is exactly why stack ASLR does not stop the attack, and why W^X does not either: no injected byte is ever executed. (The full five-letter "pwned" chain is this block repeated per letter, 20 stack words, from buffer base 1,048,208.) -
Lowe's attack. Trace the man-in-the-middle on Needham–Schroeder, and show why naming B inside message 2 stops it.
Solution
Write {m}ₓ for m sealed with X's public key, Nₐ and N_b for the two nonces. The intruder I is a network party Alice is willing to talk to. (1) Alice starts an honest session with I: {Nₐ, A}ᵢ. (2) I decrypts it and re-seals it for Bob, {Nₐ, A}_B; Bob believes Alice is calling. (3) Bob replies {Nₐ, N_b}ₐ. (4) I cannot read it (it is sealed for Alice), so it forwards it unchanged to Alice. (5) Alice, in her session with I, returns I's expected nonce: {N_b}ᵢ. (6) I decrypts N_b and re-seals {N_b}_B to Bob, who completes, believing he spoke to Alice. Now Bob is authenticated to a party who is really I, and I holds Bob's secret nonce N_b. Our breadth-first Dolev–Yao search reaches this in 19 states, with the intruder knowing N_b. Lowe's fix puts the responder's name in message 2: {Nₐ, N_b, B}ₐ. When I forwards Bob's reply to Alice in step 4, Alice sees it names B, but she believes she is talking to I, not B, so the identity check fails and she aborts; I cannot repair the message because it is sealed for Alice and I cannot decrypt it. The search then explores 17 states and finds no attack.
-
Bound parameters cannot be injected. Show, by an argument about the parser, that a query with bound parameters cannot be injected.
Solution
Injection works by making user input change the shape of the parse tree — a quote closes a string,
OR '1'='1'adds a disjunct,--comments out the rest. With bound parameters the query template is parsed exactly once, before any value arrives, into a fixed tree whose value positions are holes (ourprepare). Binding (bind) copies that tree and replaces each hole, by position, with a finished literal node("lit", value); the value is never handed to the tokeniser or the parser. Therefore the set of parse trees the engine can execute is a function of the template text alone and is independent of every user value: no byte of input can add, remove or reshape a node. Formally, for a fixed template T the executed query is T with its leaves substituted, and leaf substitution cannot change T's structure, so no input yields a tree outside {T with leaves bound}. Our engine makes this visible: binding the string"id"into theWHERE id = ?lookup returns 0 rows (it is compared as data), whereas pastingidin yields all 3 rows; the tautology and comment payloads, which derail the concatenated query's tokeniser, bind to a harmless 11- and 7-character username. (The parse error on the concatenated path is itself the symptom: the input reached the parser.) -
Build. Trojan our compiler in a new way, and show that diverse double-compiling still detects it.
Solution
Solution notes. Work against
explainer/cs/trust/trojan.py. Write a fresh self-reproducing block the way the instrument's_TROJANis written — a%r-template T′ whose single hole takes its own text, so that B′ = T′ % T′ is the spliced code and, inside B′, the stored copy pasted into itself rebuilds B′ exactly (Part 25's quine). Give it a different payload than the shipped one: a different magic password in theloginbranch, and/or a different way of recognising a compiler's source and splicing B′ into it (for instance keying on thedef compile(src):line and inserting B′ just after it, rather than on the# TROJAN-SLOTcomment). Build the suspect binary A =clean_compile(T′-trojaned source)and check the three Thompson claims withthompson_report-style assertions: A'sloginaccepts the new magic password, A compiling the clean compiler source reproduces A bit for bit (the fixpoint), and the magic string appears in no source file. Then runddc(A). Stage 1 compiles the clean source with A (which splices B′ in) and, independently, with the trusted compiler (which never inspects its input, so it splices nothing); stage 2 compiles the clean source again with each stage-1 binary. The suspect branch carries B′ through both stages while the trusted branch stays honest, so the two stage-2 binaries differ and the verdict is TROJAN DETECTED. Running this confirms it: the new trojan is a genuine fixpoint (I measured a 1,166-byte binary reproducing itself, with the magic word in no source) and DDC flags it (stage-2 suspect 1,166 bytes against a 499-byte honest stage-2), because the independent compiler does not share the trojan, whatever payload or trigger the trojan uses. The attack is only ever on our own toy compiler andlogin. -
★ Research. A provably correct, reproducible software stack built up from an auditable seed of a few hundred bytes.
Discussion. Open. The pieces exist in isolation but have never been composed into one end-to-end chain of evidence. Diverse double-compiling proves a binary corresponds to its source, but assumes the independent compiler is not trojaned the same way and says nothing about whether the source is honest (xz's backdoor was written by a maintainer). Reproducible builds let anyone rebuild a release and compare bytes, but full distributions are only partly reproducible. Bootstrapping projects (GNU Mes, Guix's full-source bootstrap of 2023) grow a toolchain from a seed small enough to read, but without a correctness proof for each step. And verified compilers (CompCert) and kernels (seL4, Part 54) are machine-checked, but at component scale, not composed from the seed up. A good partial answer would take a minimal stack — an auditable seed, a tiny assembler, a small C compiler, a small kernel — make every build reproducible, and give a single machine-checked proof that each stage preserves semantics, so that trusting the running system reduces to reading the few hundred bytes of the seed. Even one fully proved and reproducible rung above the seed, or a formal statement of the composed guarantee, would be new.
Notes and sources
Glossary
- confidentiality, integrity, availability (the CIA triad) — the three promises a secure system makes; a breach is any one of them broken.
- threat model, trust boundary, trusted computing base (TCB), attack surface, adversary — what you defend, the line trust crosses, the part that must be correct, every way in, and against whom.
- economy of mechanism, fail-safe defaults, complete mediation, open design, separation of privilege, least privilege, least common mechanism, psychological acceptability — Saltzer and Schroeder's principles (1975).
- stack smash, stack canary, W^X (NX), ASLR — overwriting a saved return address; a secret word that detects it; memory that is never both writable and executable; randomising addresses so a fixed guess usually misses.
- return-oriented programming (ROP), gadget, control-flow integrity (CFI), shadow stack, CHERI — reusing instruction tails already in the binary to compute without injecting code; the defences that guard control flow.
- memory safety, ownership, affine type, move, borrow (shared, mutable), borrow checker,
unsafe— ruling out a whole class of bug in the type system; each value one owner; using a value at most once; the Rust discipline and its escape hatch. - Rowhammer, speculative execution, transient execution, side channel, Flush+Reload, constant-time code — disturbing neighbouring DRAM rows; running ahead of a check and leaving a trace; information that leaks through time, power or cache; code whose time and memory do not depend on secrets.
- password entropy, salt, slow (memory-hard) hash, HOTP, TOTP, passkey, WebAuthn — bits of randomness in a password; a per-user prefix; a hash made deliberately expensive; one-time codes as an HMAC over a counter or the clock; a per-site signing key in place of a shared secret.
- Needham–Schroeder, Dolev–Yao model, nonce, man-in-the-middle, model checking — an authentication protocol; an intruder that owns the network; a fresh random challenge; a relay attack; the breadth-first search that finds it.
- access matrix, ACL, capability, ambient authority, confused deputy, reference monitor — Lampson's protection state and its two slicings; a request borrowing the rights of a privileged go-between; the component that checks every access.
- Bell–LaPadula, no read up, no write down, security lattice, HRU safety — a secrecy model and the flows it forbids; the undecidable question of whether a right can ever leak.
- isolation, sandbox, seccomp, site isolation, enclave, controlled channel — walls between programs and their costs; a system-call filter; a process per site; a region sealed even from the OS, and how the OS reads it anyway.
- same-origin policy, XSS, CSRF, SQL injection, parameterised (bound) query, PKI, Certificate Transparency — the web's trust boundary and the confusions of code and data across it; the parsing fix; a failing certificate anchor and the append-only log that exposes it.
- source spoofing, amplification (reflection) attack, BGP hijack, RPKI, Kaminsky's attack, DNSSEC — writing a false return address; a protocol whose answer dwarfs its question; believing a route or a DNS answer, and the signatures that stop it.
- supply chain, dependency confusion, SLSA, SBOM, reproducible build — the strangers whose code you run; resolving a public package over a private one; graded build evidence; a bill of materials; a build that gives the same bytes every time.
- trusting trust, quine, fixpoint, diverse double-compiling (DDC), bootstrapping — a backdoor that survives with no trace in any source; a program that prints its own text; a self-reproducing trojaned binary; Wheeler's cross-check with an independent compiler; growing a trusted toolchain from an auditable seed.
Sources
- R. Anderson, Security Engineering (3rd ed., 2020); M. Bishop, Computer Security: Art and Science (2nd ed., 2018); J. Erickson, Hacking: The Art of Exploitation (2nd ed., 2008).
- J. Saltzer and M. Schroeder, "The protection of information in computer systems", Proc. IEEE 1975; B. Lampson, "Protection", ACM Operating Systems Review 1974; G. Harrison, W. Ruzzo and J. Ullman, "Protection in operating systems", CACM 1976; D. Bell and L. LaPadula, Secure Computer Systems (MITRE, 1973); N. Hardy, "The confused deputy", ACM Operating Systems Review 1988.
- L. Szekeres, M. Payer, T. Wei and D. Song, "SoK: eternal war in memory", IEEE S&P 2013; H. Shacham, "The geometry of innocent flesh on the bone: return-into-libc without function calls", CCS 2007; M. Abadi, M. Budiu, Ú. Erlingsson and J. Ligatti, "Control-flow integrity", CCS 2005; R. Jung, J.-H. Jourdan, R. Krebbers and D. Dreyer, "RustBelt: securing the foundations of the Rust programming language", POPL 2018.
- Y. Kim et al., "Flipping bits in memory without accessing them", ISCA 2014; P. Kocher et al., "Spectre attacks: exploiting speculative execution", IEEE S&P 2019; Y. Yarom and K. Falkner, "Flush+Reload", USENIX Security 2014.
- R. Needham and M. Schroeder, "Using encryption for authentication in large networks of computers", CACM 1978; G. Lowe, "Breaking and fixing the Needham–Schroeder public-key protocol", TACAS 1996; J. Bonneau, "The science of guessing", IEEE S&P 2012; RFC 4226 (HOTP, 2005) and RFC 6238 (TOTP, 2011).
- G. Klein et al., "seL4: formal verification of an OS kernel", SOSP 2009; Y. Xu, W. Cui and M. Peinado, "Controlled-channel attacks", IEEE S&P 2015.
- K. Thompson, "Reflections on trusting trust", CACM 1984; D. A. Wheeler, Fully Countering Trusting Trust through Diverse Double-Compiling (PhD thesis, 2009); the Reproducible Builds and Bootstrappable Builds projects.
- US-CERT alert TA14-017A, "UDP-based amplification attacks" (2014); RFC 2827 (BCP 38, 2000); RFC 6962 (Certificate Transparency, 2013); CVE-2024-3094 (xz-utils, 2024).
About this partfrom its README
Part 55 of a sixty-one-part course in computer science (see the series plan and the syllabus), the fifth and last part of Act X, Horizons and Trust, and the end of the degree. Security is a property of the whole tower, and every layer we built leaks: buffers overflow, speculation leaves traces, DRAM rows disturb their neighbours, parsers confuse code with data. In 1984 Ken Thompson showed that even a compiler you built yourself can hide a backdoor its own source never shows. We build his attack against our own compiler, then catch it with diverse double-compiling, and close the series by walking the tower one last time, from a NAND gate to a cluster.
The instruments are in explainer/cs/trust/ (tested in tests/test_cs55_memory.py and tests/test_cs55_trojan.py):
memory.py: Part 11's stack smash run on Pebble under every combination of stack canary, W^X and ASLR; the entropy of ASLR with a small runnable confirmation; return-oriented programming — Galileo-style gadget discovery on our fixed-width ISA and a gadget chain that runs with W^X on; and a tiny borrow checker for Rust-style ownership (Part 14's affine types).auth.py: password entropy and guessing times, with a Zipf model of human choice; HOTP and TOTP checked against the RFC 4226 and 6238 test vectors; and the Needham–Schroeder protocol explored by a breadth-first Dolev–Yao search that finds Lowe's attack and clears his fix.access.py: Lampson's access matrix and its two slicings (ACLs and capabilities), the confused deputy, the Bell–LaPadula lattice, and a bounded safety search over the HRU model.web.py: SQL injection on Part 35's own database engine and the parameterised-query fix (a parsing fix, Part 12); and an HTML templater, escaped against raw, parsed to show the trees differ.trojan.py: Thompson's trojan compiler built on our own machinery — the backdoored login, the self-reproducing compiler (Part 25's quine), and the fixpoint — then Wheeler's diverse double-compiling that catches it, and a toy reproducible build.
Chapter notes
- Hook. Every layer of the tower, named with the leak that crosses it: Rowhammer (Part 5), Spectre (Part 8), the stack smash (Part 11), a sandbox escape (Part 31), the compiler backdoor (Part 13), a BGP hijack (Part 36), injection (Part 42), the xz backdoor (Part 41). Then the attack that closes the series: our clean compiler binary (499 bytes), our trojaned one (1,119 bytes), and a compiler rebuilt from the clean source by the trojaned binary — 1,119 bytes again, the same hash, byte for byte.
- 1. Threat models and principles. The CIA triad; a threat model as assets, a trust boundary and trusted computing base, an adversary, and the attack surface; a timeline of the attacks this part meets (the Morris worm 1988, Aleph One 1996, Rowhammer 2014, Spectre and Meltdown 2018, xz-utils 2024); Saltzer and Schroeder's eight principles (1975), plus work factor and compromise recording; and the defender's asymmetry — one way in against every layer at once.
- 2. Memory corruption, and return-oriented programming. The Part 11 stack smash into the saved return address; three defences run on Pebble under all eight combinations (canary → caught; W^X alone → blocked by a no-execute fault; a wrong ASLR guess → a fault at probability 1/64 in the demo); ASLR's arithmetic (p = 2⁻ᵏ, expected tries 2ᵏ) with published layout entropies (32-bit stack 19 bits, 32-bit mmap 16, 32-bit PIE 8, 64-bit mmap 28, 64-bit PIE 30) and a runnable check (64 placements, exactly 1 hit, rate 2⁻⁶); ROP (Shacham 2007) — 8 gadgets discovered in our binary, a chain that prints "pwned" and halts with W^X fully on, while the canary still trips first; CFI (Abadi et al. 2005), shadow stacks, CHERI.
- 3. Memory safety. The ≈70% statistic (Microsoft 2019 and Chromium each reported about seventy per cent of
serious bugs were memory-safety bugs); ownership as an affine type — drop contraction, each value one owner (Part
14); a tiny borrow checker run on ten programs, all ten verdicts matching what Rust would say; what is proved (no
use-after-free, double free, data race or dangling pointer, by construction) and what is not (
unsafe, logic errors); RustBelt's machine-checked soundness proof (Jung et al. 2018, Part 54). - 4. When the hardware leaks. Rowhammer (Kim et al. 2014) — 110 of 129 DDR3 modules flipped bits, some after ≈139,000 activations inside one 64 ms refresh; Spectre and Meltdown (2018) — speculation past a bounds check leaves a cache line warm, read back with Flush+Reload (Yarom & Falkner 2014); side channels generally (time, power, cache, sound) and Kocher's 1996 timing attack; constant-time code; the lesson that a mitigation is never free (the roofline of Part 9 moves) and the move to a hardware–software contract.
- 5. Who are you? Authentication. Password entropy H = L·log₂N and expected crack time 2ᴴ/2R: at 10¹⁰ guesses/s, 8 lowercase letters (≈38 bits) last about 10 s, 16 lowercase (≈75 bits) some 70,000 years; a Zipf model (after Bonneau 2012) where 10 guesses crack 18% of users and a million crack 86%, about 14 points per decade; salting, and a slow salted hash (10/s per core) buying a factor of 10⁹, so 8 lowercase now take over 300 years per core (bcrypt, scrypt, Argon2, Part 29); TOTP as an HMAC over the clock, reproducing all six RFC 6238 SHA-1 vectors (HOTP at counter 1 is 287082); passkeys and WebAuthn (2019, Part 30); and Needham–Schroeder (1978) with Lowe's attack (1995), found by our model checker (Part 54) among 19 states, and the fix — Bob names himself in message 2 — leaving no attack among 17.
- 6. Access control. Lampson's matrix (1971) and a reference monitor; ACLs down the columns against capabilities along the rows; the confused deputy (Hardy 1988), run both ways — ambient authority overwrites the billing file, a capability refuses; Bell–LaPadula (1973), no read up and no write down over a lattice, five checks agreeing (including a flow that climbs a level yet is still denied for a missing category); the HRU safety question (Harrison, Ruzzo & Ullman 1976) — our bounded search finds a leak after 2 states, a revoke-only system none — and its undecidability by reduction from halting (Part 25).
- 7. Isolation. Address spaces and page tables (Parts 31–32), so the wall is the kernel itself (seL4, ≈10,000 lines, proved to enforce it — Klein et al. 2009); a ladder of walls (language sandbox, process, container, VM, separate machines) where an escape goes through whatever is shared (Dirty COW 2016, VENOM 2015); system-call filters (seccomp 2005, BPF filters since 2012; Capsicum 2010); site isolation (Chrome, on by default 2018, after Spectre) and WebAssembly's in-process sandbox (every major browser since 2017); SGX enclaves (2015) and their breaks (the controlled channel, Xu, Cui & Peinado 2015; Foreshadow 2018).
- 8. The web. The same-origin policy (scheme, host, port) and the gap it leaves — a page may send where it cannot
read; XSS, data parsed as code, our templater's raw output yielding a live
scriptelement where the escaped one yields only text; CSRF as the browser-as-confused-deputy, fixed with SameSite cookies and per-form tokens; SQL injection on Part 35's engine — an unquoted field turns the filter intoid = idand all three rows' secrets spill — and its cure, a parsing fix (Part 12): parse the template once, bind values as finished leaves; PKI failure (DigiNotar 2011) and Certificate Transparency (RFC 6962, 2013). - 9. Networks under attack. Source-address spoofing, since routers forward on the destination alone (BCP 38, 2000); amplification with factor A = r/q and measured factors (SNMPv2 6.3, SSDP 30.8, DNS 28–54, CharGEN 358.8, NTP 556.9, memcached up to 51,000 — US-CERT TA14-017A), and GitHub absorbing ≈1.35 Tb/s off open memcached servers on 28 February 2018; BGP hijacks on Part 36's 125-network internet (49 of 124 follow a same-prefix origin, all 124 a more-specific one; a quarter adopting RPKI leaves 61 fooled — Pakistan Telecom's 2008 YouTube hijack); Kaminsky's DNS race (≈656 races, about a minute, with a 16-bit ID; some 43 million races and ≈50 days once the source port is randomised; DNSSEC removes the guess); and the end-to-end lesson — assume the path is hostile, TLS guards what is said but not whether it arrives.
- 10. Supply chains. The dependency tree (P ≈ e⁻ⁿᵖ: a thousand packages at one bad in ten thousand give a ≈10% chance of trouble, set by the least careful stranger); dependency confusion (Birsan 2021); build poisoning (SolarWinds 2020, fewer than 18,000 customers), where a signature says who built a binary, not from what source; the xz-utils backdoor (2024) hidden in the release tarball's build script, not the repository; its accidental discovery by Andres Freund on 29 March 2024 from a ≈500 ms slowdown (CVE-2024-3094); and the defences — SLSA (2021), SBOMs, reproducible builds — none of which checks that the source is honest.
- 11. Reflections on trusting trust. Thompson's three stages, built on our own compiler. Stage 1: a backdoored
login(236 bytes honest, 279 bytes with the extra line) — but the line is in the source. Stage 2: move it into the compiler, which backdoorsloginas it compiles it — but now the compiler's source shows it. Stage 3: Part 25's quine, so the compiler also writes the trojan into any compiler it compiles; delete the trojan from every source file and the trojaned binary (1,119 bytes), compiling the clean source, reproduces itself bit for bit — a fixpoint — and still lets the magic password intologin. The magic string is in no source. (Thompson 1984; Karger & Schell's Multics review, 1974.) - 12. Catching the trojan. Diverse double-compiling (Wheeler 2005, thesis 2009): with a second, independent compiler T (ours never inspects what it compiles), form X = T(c) and Z = X(c), and test Z = A bit for bit. On the honest compiler the two stage-1 binaries differ (499 vs 498 bytes) but both stage-2 binaries are 499 bytes and equal — clean. On Thompson's compiler stage 2 gives 1,119 bytes from the suspect against 499 from X — TROJAN DETECTED, because the trojan cannot hide in a compiler it never touched. The bit-for-bit test needs reproducible builds (our toy build's timestamp/path make two hashes differ until normalised; Tor and Debian since 2013), and the trusted compiler itself is grown from an auditable seed (bootstrappable builds; GNU Guix's full-source bootstrap, 2023).
- 13. The tower, end to end. The Job climbs once more, from a NAND gate to the cluster, over ≈24,907,061 bytes of novels. Each layer is asked what it trusts and how the series earned it — physics on/off, gates by exhaustive check, the ISA by agreement with a reference, machine code by a hardened convention, languages by fuzzing and proof and DDC, the kernel by the MMU checking every access, storage by injected crashes, networks and replicas by injected faults, the application by inheriting everything below. Four leaks are drawn as arcs where a promise went unchecked: Rowhammer, Spectre, the trojan, the BGP hijack. The tower is lit end to end.
- 14. Frontier: the open problems of the series. The questions the degree met and left open (P vs NP; whether one-way functions exist; ω, now < 2.372 (2024); BB(6), now that BB(5) = 47,176,870 was proved in 2024; splay-tree optimality; the unique games conjecture; BPP = P; circuit lower bounds; a C memory model; practical quantum advantage; verified software at scale — Part 61 returns to each). Three frontiers of trust: memory safety at scale, leak-free speculation at an affordable cost, and bootstrapping a whole toolchain from an auditable seed. Four open problems and the ★ research problem.
- Outro. The pebble again: Part 1's Euclid, 24 and 18 becoming 6 and 6; the ten acts as one tower; the ledger, row 20 — the Job as one line of Python on this machine, about 1.27 s, against Part 6's single-cycle Pebble at 281 s; the six problems; the final reading list; and on to Act XI, the research frontier.
Companion material in this repository
The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
- Threat models; Saltzer & Schroeder's principles (1975).
- Memory corruption revisited (Part 11):
- the stack smash on Pebble;
- canaries, W^X, ASLR (its entropy computed);
- return-oriented programming (Shacham 2007), a Turing-complete chain of gadgets in our own binary;
- CFI; CHERI.
- Memory safety: the ~70% statistic (cited); Rust's ownership as affine types (callback to Part 14); what the borrow checker proves; RustBelt.
- Hardware: Rowhammer (Part 5), Spectre and Meltdown (Part 8) and what the mitigations cost; side channels (Part 27).
- Authentication: password entropy and guessing; salted slow hashes (Part 29); TOTP as an HMAC over time; passkeys (Part 30). Needham–Schroeder (1978) and Lowe's 1995 attack, found by our model checker (callback to Part 54).
- Access control: Lampson's matrix; ACLs against capabilities (the confused deputy); Bell–LaPadula; safety is undecidable in the HRU model (1976) (callback to Part 25).
- Isolation: processes and paging (Part 32); sandboxes, site isolation, WebAssembly (Part 15); enclaves and their breaks.
- The web: same origin; XSS and CSRF; SQL injection on our own database, fixed by parameterized queries, a parsing fix (callback to Part 12); PKI failures (DigiNotar).
- Networks: amplification DDoS, BGP hijacks (Part 36), DNS (Part 37).
- Supply chains: dependency confusion; the xz-utils backdoor (2024), and how a 500 ms slowdown exposed it (cited).
- Reflections on Trusting Trust (Thompson 1984), built on our compiler (Part 13) with Part 25's quine trick:
- a backdoor in
login; - a compiler that inserts it when it compiles
login; - and inserts itself when it compiles a compiler;
- remove the source, and the binary keeps both.
- a backdoor in
- Diverse double-compiling (Wheeler 2009) catches it, using our independent Python reference compiler. Reproducible builds; bootstrapping from a tiny seed (cited).
- The tower revisited: the Job end to end, from NAND to cluster; the final ledger (row 20); what each layer hides and what leaks through.
- Open problems across the series (Part 61 returns to them at research depth):
- P vs NP, and whether one-way functions exist;
- ω = 2?;
- BB(6);
- dynamic optimality; the UGC;
- practical quantum advantage; verified software at scale;
- the bridge to AI, Built.
- The pebble again: Hilbert's question, and everything it led to. Outro: the series map, the problems, the final reading list.
Computed: the stack smash and ROP chain on Pebble, with and without defenses; ASLR entropy; a tiny borrow checker; TOTP; Lowe's attack found by model checking; an HRU example; SQL injection and its fix; the trojan compiler built and caught by DDC; the final ledger. Visuals: ROP gadgets as a train of return addresses; the trojan compiler reproducing itself in a loop; the whole tower lit end to end, the camera rising from a NAND gate to the cluster; the final ledger. In practice: application security reviews, migrations to memory-safe languages, supply-chain security (SLSA, reproducible builds), incident response to a compromise. Reading: Anderson, Security Engineering (3rd ed.); Bishop, Computer Security: Art and Science; Erickson, Hacking: The Art of Exploitation; Szekeres et al. 2013 (SoK: eternal war in memory); Saltzer & Schroeder 1975; Thompson 1984; Wheeler 2009; Shacham 2007; Abadi et al. 2005; Lampson 1974; Harrison, Ruzzo & Ullman 1976; Lowe 1996; Kocher et al. 2019; Jung et al. 2018.
中文讲义
本讲的中文部分(与英文版对应)。
习题与解答
-
ASLR 的熵。 计算 30 位 ASLR 偏移的熵,以及首次命中所需的期望尝试次数,分别考虑重新随机化与不重新随机化两种情形。
解答
若地址中有 k 个独立的随机位,基址就落在 2ᵏ 个等可能的位置之一,所以熵为 H = k = 30 位,而一个写死单一地址的攻击 以概率 p = 2⁻³⁰ ≈ 9.31×10⁻¹⁰ 命中。若每次重试都重新随机化布局,则每次尝试都是独立的伯努利试验,首次命中的尝试次数服从几何分布, 均值为 1/p = 2³⁰ = 1,073,741,824。若攻击者不重新随机化、顺序地扫过所有位置,则命中等可能是第 1、2、…、2ᵏ 个候选,期望尝试次数 为 (2³⁰ + 1)/2 = 536,870,912.5。这正是仪器表中的 64 位 PIE 那一行;注意重新随机化大致使期望工作量翻倍,因为顺序扫描从不重复一个 猜测。(同样的算术在 k = 16 时给出 Shacham 等人 2004 年约 6.5 万次的 32 位暴力破解。)
-
用 ROP 写一个字节。 找出一条返回导向链所需的指令片段(gadget),它只用二进制里已有的代码,向 Pebble 的控制台写一个字节。
解答
Pebble 是定长指令集,所以不存在非对齐的"意外"片段;在对齐的指令边界上扫描以终止指令(
jalr——包括ret——或halt) 结尾、再向前回溯其直线尾部,得到八个片段。其中两个承担写操作。偏移 72 处的restore3是lw s0,0(sp); lw s1,4(sp); lw ra,8(sp); addi sp,sp,12; ret:它从栈上装入 s0、s1 和下一个返回地址。偏移 92 处的wb是sb s1,0(s0); lw ra,0(sp); addi sp,sp,4; ret:它把 s1 里的字节存到 s0 所指的地址,再弹出下一个返回地址。溢出把保存的返回地址 覆盖为restore3,其上放置栈字 ⟨IO_CONSOLE = 0xFFFF0000、该字节、wb⟩,再接 ⟨偏移 24 处的halt⟩。restore3装入 s0 = 控制台端口、s1 = 字节、ra =wb;wb把字节写到控制台并返回进halt。栈上只出现代码地址与数据,没有一个栈地址——这正是 栈的 ASLR 挡不住这种攻击的原因,也是 W^X 挡不住它的原因:没有任何注入的字节被执行。(完整的五字母 "pwned" 链就是这个片段按字母 重复,共 20 个栈字,缓冲区基址 1,048,208。) -
Lowe 的攻击。 追踪 Needham–Schroeder 上的中间人攻击,并说明为什么在消息 2 中写入 B 的名字能阻止它。
解答
记 {m}ₓ 为用 X 的公钥封装的 m,Nₐ、N_b 为两个一次性随机数(nonce)。入侵者 I 是 Alice 愿意与之通信的一个网络方。 (1)Alice 向 I 发起诚实会话:{Nₐ, A}ᵢ。(2)I 解密后为 Bob 重新封装 {Nₐ, A}_B;Bob 相信是 Alice 在呼叫。(3)Bob 回复 {Nₐ, N_b}ₐ。(4)I 读不了它(它是封给 Alice 的),于是原样转发给 Alice。(5)Alice 在与 I 的会话里返回 I 期待的随机数: {N_b}ᵢ。(6)I 解出 N_b,再把 {N_b}_B 重新封给 Bob,Bob 完成会话,相信自己与 Alice 通了话。此时 Bob 把自己认证给了一个其实是 I 的一方,而 I 掌握了 Bob 的秘密随机数 N_b。我们的广度优先 Dolev–Yao 搜索在 19 个状态里到达此处,入侵者确实知道了 N_b。Lowe 的 修复是在消息 2 里写入响应者的名字:{Nₐ, N_b, B}ₐ。当 I 在第 4 步把 Bob 的回复转发给 Alice 时,Alice 看到它写着 B,但她以为自己 在和 I 通话、而非 B,于是身份校验失败、她中止会话;I 无法改写这条消息,因为它是封给 Alice 的、I 解不开。搜索这时探索 17 个状态, 找不到攻击。
-
绑定参数不可被注入。 用一个关于分析器(parser)的论证,证明使用绑定参数的查询不可被注入。
解答
注入靠的是让用户输入改变解析树的形状——一个引号闭合字符串,
OR '1'='1'加上一个析取项,--注释掉其余部分。使用绑定 参数时,查询模板恰好被解析一次,在任何值到来之前,解析成一棵固定的树,其取值位置是一个个"洞"(我们的prepare)。绑定(bind) 复制这棵树,按位置把每个洞替换成一个完成的字面量节点("lit", value);该值从不交给分词器或分析器。因此引擎能执行的解析树集合只是模板 文本的函数,与每个用户值无关:没有一个输入字节能增加、删除或重塑任何节点。形式地说,对固定模板 T,被执行的查询就是把 T 的叶子替换后的 结果,而叶替换不能改变 T 的结构,所以没有输入能产生 {把叶子绑定后的 T} 之外的树。我们的引擎让这一点可见:把字符串"id"绑定进WHERE id = ?的查询返回 0 行(它作为数据被比较),而把id拼接进去则返回全部 3 行;在拼接路径上使分词器出轨的"永真式"与"注释" 载荷,绑定后不过是长度 11 和 7 的无害用户名。(拼接路径上的解析错误本身就是症状:输入到达了分析器。) -
动手。 用一种新的方式给我们的编译器植入木马,并说明多样化双重编译(DDC)仍能检测到它。
解答
解答要点。 在
explainer/cs/trust/trojan.py上动手。像仪器里的_TROJAN那样写一个新的自复制代码块——一个%r模板 T′, 其唯一的洞填入它自己的文本,于是 B′ = T′ % T′ 就是被拼入的代码,而在 B′ 内部,存着的那份副本填入自身又恰好重建出 B′(第 25 部分的 奎因/quine 技巧)。给它一个与出厂版不同的载荷:在login分支里用不同的"魔法口令",并且/或者用不同的方式识别编译器源码并把 B′ 拼进去 (例如识别def compile(src):这一行、把 B′ 插在它之后,而不是识别# TROJAN-SLOT注释)。构造嫌疑二进制 A =clean_compile(被 T′ 木马化的源码),并用类似thompson_report的断言检查 Thompson 的三条主张:A 的login接受新的魔法口令; A 编译干净的编译器源码时逐字节地复现出 A(不动点);魔法字符串不出现在任何源文件里。然后运行ddc(A)。阶段一用 A 编译干净源码 (A 会把 B′ 拼进去),并独立地用可信编译器编译(它从不审视所编译的内容,所以什么也不拼);阶段二再用各自的阶段一二进制编译干净源码。 嫌疑分支在两个阶段里都带着 B′,而可信分支始终诚实,所以两个阶段二二进制不同,裁决为 TROJAN DETECTED。实际运行能证实这一点:新木马 确是不动点(我测得一个 1,166 字节的二进制复现出自身,魔法字出现在任何源码里都没有),DDC 把它标了出来(阶段二嫌疑 1,166 字节对诚实 阶段二的 499 字节),因为独立编译器不共享这个木马,无论木马用什么载荷或触发条件。这个攻击始终只针对我们自己的玩具编译器和login。 -
★ 研究。 一个可证明正确、可重现的软件栈,从一颗几百字节、可审读的种子一路搭起来。
讨论。 尚未解决。各个零件单独存在,却从未被组合成一条端到端的证据链。多样化双重编译证明一个二进制对应其源码,但它假设独立编译器没有被 以同样方式植入木马,也完全不保证源码本身诚实(xz 的后门正是一位维护者写的)。可重现构建让任何人重建一个发行版并逐字节比对,但完整的 发行版只是部分可重现。自举项目(GNU Mes、Guix 2023 年的全源自举)从小到能读的种子长出工具链,却没有对每一步的正确性证明。而经过机器 校验的编译器(CompCert)与内核(seL4,第 54 部分)停在部件规模,没有从种子一路组合起来。好的部分答案会取一个最小的栈——可审读的 种子、一个微型汇编器、一个小 C 编译器、一个小内核——让每一次构建可重现,并给出一条机器校验的证明,证明每一级都保持语义,使得信任运行中的 系统归结为读那几百字节的种子。哪怕在种子之上做出一级完全证明且可重现的台阶,或给出组合保证的一个形式化陈述,都会是新的结果。
Build the film
python -m videos.cs.cs55.compute # the part's numbers, into .cache/cs55
python tools/build.py cs55 # render and assemble the film
EXPLAINER_TTS=silent python tools/qa_scene.py cs55 Hook # one chapter, silent, with a contact sheet
Scenes: videos/cs/cs55. Setup: see the course page. Source of these notes: the README and the scenes' narration.
Build it
python -m videos.cs.cs55.compute
python -m unittest tests.test_cs55_memory tests.test_cs55_trojan
python tools/build.py cs55