Section 20.21

One connected exercise: from a publisher’s bytes to a retired key

This exercise joins the trees of this chapter into one continuous answer about one invented sensor gateway. It follows a decision program from the publisher’s bytes to its execution, and then follows the publisher’s authority through a stolen key, a power failure, a complete reset and the retirement of a key. Each of the 12 prompts below has a worked answer that gives enough arithmetic, invariants and counterexamples to make the mechanism clear, and names the tree that treats it in full. All numbers are invented teaching values.

The setting is the one all trees share. The publisher, the one party authorized to change the gateway’s policy, sends decision programs through a phone that only carries the bytes but can read, keep, change or resend them. Each program is eBPF §2.1 bytecode §2.4; the name eBPF began as an abbreviation of extended Berkeley Packet Filter and is no longer treated as an acronym. The gateway’s own software, the host, runs the program, the guest, inside a virtual machine §2.3 (VM), a part of the host that carries out the guest’s instructions one at a time, and the guest answers each management request with the verdict ALLOW or DENY. Requests carry a tag computed with HMAC §5.8 (hash-based message authentication code) under the active key KaK_a. The generation number gg counts key replacements: KaK_a belongs to generation 7, and the pending replacement KpK_p is to become generation 8. The recovery credential KrK_r may authorize a new active key, and the gateway tags its own replies with the confirmation key KcK_c.

  1. Define host protection separately for memory, control flow, work and policy correctness.

    Host protection consists of four separate properties, and each needs its own argument. Memory: every byte the guest reads or writes lies inside a region that the host granted for this run and has not taken back. Control flow: every jump lands on an instruction of the admitted program, and every call goes to a helper function §2.19, a host routine on the list the host offers to the guest; the guest never transfers control into the host’s own machine code. Work: every run is limited in instructions, helper calls and time, so the gateway keeps sampling its sensors and serving its radio. Policy correctness: each verdict is the one the publisher’s intended policy requires.

    The four properties are independent. A guest that answers DENY to every request satisfies the first three and still makes the gateway useless to its owner, which is a denial of service §1.28. A guest that loops until its instruction budget §2.32, a limit of 1000 guest instructions per run, runs out is memory safe and does stop, yet costs the full budget on every run. Tree 1 §20.1 states the memory property as a conditional theorem whose premises are admission of the checked bytes, the host’s contracts and a correct implementation, and Tree 10 §20.10 treats work and service.

  2. Identify the final admitted representation and prove that those are exactly the bytes executed.

    Trace the bytes. The publisher writes the program in the C programming language, a compiler such as Clang §12.17 translates it into eBPF bytecode, and the bytecode travels inside an ELF §12.6 (Executable and Linking Format) file, a standard container for instructions and information about them. On the gateway a loader takes the instructions out of the file and completes every instruction that still refers to something by name, a step called relocation §12.50. The final admitted representation is the instruction sequence after that last change, held in the buffer that the verifier, the checker that examines the program before it runs, has accepted.

    Binding execution to those bytes takes three steps: make every change that loading requires before verification; keep the checked copy in memory that nothing else can write until the program is discarded; and run that same copy. Otherwise the gateway has a time-of-check to time-of-use §9.26 (TOCTOU) error: it checked one set of bytes and runs another. A matching file name proves nothing, and a digest, a short fingerprint of the bytes, compared at two moments shows only that the bytes were equal at those two moments. If a just-in-time (JIT §2.14) compiler later translates the bytecode into the processor’s own machine code, that code consists of new bytes and needs its own argument, given in the fifth prompt. Tree 3 §20.3 walks through the actors and this counterexample.

  3. Explain the bounds proof, then break it with signedness, wraparound, lifetime or a helper’s effects.

    Let the host hand the guest a live object of n=64n = 64 bytes, numbered 0 to 63, whose start address is a multiple of 4, and let the guest read w=4w = 4 bytes at an unsigned offset oo chosen by the sender of the request, possibly an attacker. The largest safe start is n−w=64−4=60n - w = 64 - 4 = 60: at o=60o = 60 the read covers bytes 60 to 63, the last four. The guest refuses every o>60o > 60 and every oo that is not a multiple of 4. An unsigned oo is never negative, so every accepted oo satisfies 0≤o≤600 \le o \le 60, and the last byte read, at offset o+3o + 3, is at most 60+3=6360 + 3 = 63.

    Each break changes one premise. Signedness: if oo is signed, o=−4o = -4 passes both tests, because −4>60-4 > 60 is false and −4-4 is a multiple of 4, and the read covers the 4 bytes just before the object. Wraparound: a check written only as o+w>no + w > n, without the alignment §4.22 test, in unsigned 32-bit arithmetic, which keeps every result modulo 232=4,294,967,2962^{32} = 4{,}294{,}967{,}296, accepts o=232−2=4,294,967,294o = 2^{32} - 2 = 4{,}294{,}967{,}294. The true sum 4,294,967,2984{,}294{,}967{,}298 is stored as 4,294,967,298−4,294,967,296=24{,}294{,}967{,}298 - 4{,}294{,}967{,}296 = 2, the test 2>642 > 64 is false, and on a processor with 32-bit addresses the read starts 2 bytes before the object. An overflow-safe check never forms the sum: it requires w≤nw \le n and o≤n−wo \le n - w. Lifetime: if a helper frees the object between the check and the read, the arithmetic still passes, but the read is a use-after-free §4.6, an access to memory that may already hold another object.

    Name the premise that failed instead of calling every case an overflow. See Tree 5 §20.5, Tree 6 §20.6, the overflow-safe range check §4.17 and temporal memory safety §2.29.

  4. Switch the input from compiled C to handwritten eBPF assembly; explain why the boundary must remain the same.

    The gateway never sees C. It receives bytecode, and its verifier checks the final instructions that the VM will run. Handwritten eBPF assembly, a text form in which each line names one instruction, is turned by an assembler into the same kind of bytecode, which meets the same loader and the same verifier. Changing the author’s language changes who produces the bytes, not the checks on them. A bypass needs a gap in the gateway’s own path, such as a check made only on source code, a loading route that skips the verifier, or a bug in the verifier.

    Native Arm assembly, the readable form of the machine code of the gateway’s processor, gains nothing either: the VM decodes every submitted byte by the eBPF rules, so the bytes are either rejected as invalid eBPF or run as eBPF. Only a second route that runs native code, such as a facility for installing native functions, would change the trust boundary §1.3, and that route needs its own argument, for example confinement by a memory protection unit §6.8 (MPU), a circuit that restricts which addresses code may use. See Tree 3 and Tree 4 §20.4.

  5. Replace interpretation with just-in-time (JIT) compilation; identify the new correspondence obligation.

    An interpreter §2.13 carries out the bytecode one instruction at a time; a JIT compiler translates the bytecode into native machine instructions shortly before the first run. The verifier reasoned about the bytecode as RFC 9669 defines it, the eBPF specification in the Request for Comments (RFC) series of the Internet Engineering Task Force (IETF), but the processor now runs the translation. The obligation is that the native code does exactly what the specification says the accepted bytecode does, for every input: every result with the same width, signedness and wraparound; every memory access at the same address and of the same size, with every run-time check the safety argument relies on; every helper call with its arguments where the processor’s calling convention, its rule for passing arguments and results, expects them and the host’s registers left intact; and the same accounting against the instruction budget. The memory holding the native code must be writable only while the JIT compiler fills it, and executable but not writable afterwards.

    A single mismatch is enough to break the argument. The 8-bit value 0xFF becomes 255 when zero-extended to 64 bits and −1-1 when sign-extended, and the signed test “greater than 0” is true for 255 and false for −1-1, so two components that extend differently send the program down opposite branches. The obligation is met by proving the translator correct for all programs or by checking each translation against its bytecode, which is called translation validation §3.33; running the verifier again on the unchanged bytecode establishes neither. See Tree 9 §20.9 and truncation and extension §4.19.

  6. Keep memory safe but saturate the cooperative worker; add justified resource and timing premises.

    Let guest runs execute on a cooperative worker: a thread, an independently scheduled sequence of execution, that keeps the processor until it gives it up, so that no other thread can take the processor from it and only interrupt handlers §6.12 can. A memory-safe guest can still use its whole budget on every run, and when requests arrive back to back, such a guest keeps the worker busy all the time while every other job of that worker waits. A bound on one run adds parts that do not overlap, each an assumed upper limit and not a measurement: at most 1000 instructions of at most 2 microseconds each, 1000×2=20001000 \times 2 = 2000 microseconds; at most 2 helper calls of at most 300 microseconds each, 2×300=6002 \times 300 = 600 microseconds; 100 microseconds of fixed work; and at most 500 microseconds of interrupt §6.11 handling. One run therefore takes at most 2000+600+100+500=32002000 + 600 + 100 + 500 = 3200 microseconds, which is 3.2 milliseconds (ms). Each premise needs its own justification: the 2 microseconds must cover the slowest instruction, a per-run limit must enforce the 2 helper calls, no helper may wait without limit, the interrupt time must be bounded over a window at least as long as the run, and no work the guest starts may outlive its run.

    A run time is not a response time §9.32. If the gateway paces guest runs to at most one start every 4.5 ms, guest runs can occupy at most 3.2/4.5≈0.713.2 / 4.5 \approx 0.71, about 71%, of the processor. When three requests arrive together and are served in order, however, the third starts at 2×4.5=9.02 \times 4.5 = 9.0 ms and finishes at 9.0+3.2=12.29.0 + 3.2 = 12.2 ms: 9 ms of waiting plus 3.2 ms of running, which misses a 10 ms deadline by 12.2−10=2.212.2 - 10 = 2.2 ms. A response-time guarantee needs a model of arrivals, including the largest burst, in addition to the bound on each run.

    A rule that stops any operation after 40 seconds is a timeout §9.34: it limits how long the caller waits, not how long the work needs, so it is not a 40-second worst-case execution time §9.33 (WCET). See Tree 10, the instruction budget, fixed-priority response-time analysis §19.4.7 and scientific claims versus operational guards §13.31.

  7. Supply a hostile but correctly authenticated program; separate authorization §1.7 from admission.

    Three different decisions apply to every update object. Authentication §1.6: the HMAC tag recomputed with KaK_a over the covered bytes equals the received tag, which shows that some holder of KaK_a produced exactly those bytes. Authorization: the object names this gateway, asks for an operation that a holder of KaK_a may request, and is fresh, meaning that its sequence number exceeds the last one accepted. Admission: the program itself satisfies the gateway’s safety and resource rules, checked by the verifier, the list of permitted helpers and the instruction budget. In Tree 12 §20.12 the gateway accepts an object only when five checks all pass on one unchanging copy of its bytes: the bytes are well formed, the tag is authentic, the operation is permitted, the object is fresh, and the program is admitted.

    The cases show why the decisions stay separate. A genuine program from the publisher that reads 4 bytes starting at byte 7 of an 8-byte input buffer touches bytes 7 to 10; it passes authentication and fails admission, because bytes 8, 9 and 10 lie past the buffer’s last byte. A program tagged by a thief of KaK_a passes authentication; the VM still confines its memory accesses, but its verdicts can deny every request or allow the thief’s own. A harmless program from an outsider who lacks KaK_a is safe and is still refused. A recorded object that the phone resends keeps its valid tag, which shows only that a key holder made it once, not that the phone holds KaK_a now, and the freshness check §1.26 refuses it. See HMAC and bytecode authenticity versus safety §2.43.

  8. Trace the message’s exact authentication input, context and freshness state.

    The tag protects only the bytes it covers, so the covered input must contain every field that changes what the gateway does: the device identifier (ID), the key’s role, the operation, the generation gg, the request or transaction §8.7 number, the format version, every length and the program bytes. Suppose a format leaves the device ID outside the covered bytes and two gateways share KaK_a. The phone can change an update meant for the gateway with ID 0x0001 so that it names the gateway with ID 0x0002, and the second gateway recomputes the same valid tag and accepts the update without any forgery. The encoding must also be unambiguous: joined without separators or lengths, the field values 12 and 3 and the field values 1 and 23 both become the digits 123, and a tag over one is a tag over the other.

    Context includes the key’s purpose. The gateway tags its replies with the separate confirmation key KcK_c, so a reply that the phone sends back to the gateway never passes as a request tagged with KaK_a. Freshness needs state at the receiver: the gateway keeps the last accepted sequence number in storage that survives power loss and accepts only larger numbers, or it sends a fresh random challenge that the request must include. A nonce §5.18, a number meant to be used once, chosen by the sender proves nothing about age: the nonce in an old request is still old when the phone replays it. See Tree 13 §20.13, Tree 15 §20.15, authentication coverage §5.41 and why replay resistance needs state or a fresh challenge §17.10.

  9. Disclose first the active key, then the recovery key §5.31, then a shared root; redraw the remaining authority each time.

    Suppose, as in Tree 19 §20.19, that the publisher derives both keys from one root secret RR with a key derivation function §5.20 (KDF), an algorithm §14.1 that computes a key from a secret and a public label: Ka=KDF(R,“active-7”)K_a = \mathrm{KDF}(R, \text{``active-7''}) and Kr=KDF(R,“recovery”)K_r = \mathrm{KDF}(R, \text{``recovery''}). Damage spreads along derivation links, from a secret to every key computed from it, and along authority links, from a key to every key it can install or revoke. Active key: a thief of KaK_a can make every request that KaK_a authorizes, such as installing a program that denies everything, until the gateway stops accepting KaK_a. The repair delivers a new key under protection that does not depend on KaK_a and then revokes KaK_a. The gateway revokes it by raising its floor to 8; the floor is the lowest generation the gateway accepts, kept in a monotonic counter §8.28, a stored number that can only increase. Recovery key: a thief of KrK_r can install an active key of its own choosing, say as generation 9, without ever learning KaK_a, and can repeat this after every replacement, so the repair must replace KrK_r itself through a higher authority or through physical access to the gateway.

    Root: a thief of RR computes KaK_a, KrK_r and every future key with a public label, such as KDF(R,“active-8”)\mathrm{KDF}(R, \text{``active-8''}), so no message to the gateway can restore trust; only fresh random key material installed by an action outside the compromised keys, such as an operator with physical access, can. A new independent key protects later requests only if it is delivered and installed out of the attacker’s reach. Forward secrecy §5.33, which keeps the messages of earlier sessions secret after a later compromise, concerns encryption, and KaK_a encrypts nothing. See the recovery key and post-compromise security §5.34.

  10. Interrupt every persistent step of a key or update transition; decide authority from the evidence that survives.

    Use the storage model of Tree 18 §20.18: every record ends with a checksum §4.32, a short value computed over the record and written last, so a write cut short by power loss leaves a record that is detectably incomplete. Flash memory §6.6, storage that keeps its content without power, holds C7C_7, the record of KaK_a, and A7A_7, a commit record §8.21 naming it; a commit record is a small record whose complete presence declares a change in force. The key change §5.29 writes C8C_8, the record of KpK_p; then writes A8A_8, a commit record naming C8C_8; then raises the floor to 8; then switches the key in RAM (random-access memory, the working memory, which loses its content without power); and finally sends an acknowledgment tagged with KcK_c. At boot the gateway uses the newest complete commit record that names a complete key record.

    Check each cut, the point at which power fails. Until A8A_8 is complete, boot finds no complete commit record for generation 8 and uses KaK_a, perhaps with C8C_8 as a pending candidate. Once A8A_8 is complete, boot uses KpK_p and raises the floor to 8 itself if the counter still holds 7. The completed write of A8A_8 is therefore the single commit point, and no cut leaves the gateway between the two generations. A publisher that received no acknowledgment keeps both keys and asks the gateway for its current generation.

    The order of the writes matters. If the floor were raised to 8 before C8C_8 was complete, a cut could leave a floor of 8 and a usable key only for generation 7. Using KaK_a would break rollback protection §8.26, since 7<87 < 8; refusing everything would lock the owner out until a recovery with KrK_r. Silently returning to generation 7 is not a repair. See commit records and monotonic counters.

  11. Reinitialize the whole device; test the replay argument across the new lifecycle.

    A complete erase, such as a factory reset, removes the key records, the generation, the floor and the last accepted sequence number. Suppose the gateway is then set up again from the same root RR and the same device ID, with its count of accepted requests back at 0. It derives the same first key, and a request numbered 1 that an attacker recorded before the erase passes the freshness check again, because 1>01 > 0. The attacker has reinstalled an old policy without forging anything.

    The new lifecycle must differ in something the attacker cannot reproduce: new key material from a fresh random source; an epoch number, a count of complete erasures kept in storage that the erase cannot clear, mixed into every derived key and covered by every tag; or a lifecycle action by a trusted party outside the device. A context recomputed from unchanged inputs reproduces the same keys and protects nothing. Some losses cannot be repaired on the device at all. If one history in which KaK_a was never revoked and another in which the revocation records were lost leave identical storage, no rule that the device applies on its own is right in both, and only evidence from outside, such as a statement of the current generation that the publisher tags with KrK_r, can decide. See Tree 18 and lifecycle reset and replay §19.3.7.

  12. Retire the keys and identify every remaining copy or derived authority.

    Retirement, historical processing and destruction are three different events. Once generation 8 is active and the floor is 8, KaK_a is retired: the gateway refuses it for every new request. An auditor may still need KaK_a, say for 90 days, to verify archived log entries tagged with it. HMAC is a message authentication code §5.7 (MAC), in which the same key computes and checks tags, so whoever keeps KaK_a for that purpose can also forge entries that look old. The same questions apply to every other retired key, such as the confirmation key KcK_c once it is replaced.

    Destruction is a fact about every copy of the key and every way to recreate or use it, judged against a named attacker. Zeroing one buffer is not enough. Copies may remain in stack frames, processor registers and library buffers. An HMAC implementation may keep two precomputed internal states of its hash function, 32 bytes each for SHA-256 §5.2 (the Secure Hash Algorithm 2 with a 256-bit output), derived from the key and the two fixed constants called the inner and outer pads; these two states suffice to compute every tag without the key. Flash memory may keep an old record after a deletion, because a deletion often only marks a record as obsolete and erasing works only on whole blocks. Backups, logs and the publisher’s copy remain. The root RR recreates KaK_a as long as RR exists, and a service that holds KaK_a can still compute tags. A compiler may even remove a final zeroing write that nothing reads afterwards, unless the program uses a function whose write the compiler must keep, such as memset_explicit, added in the 2023 revision of the C standard, or explicit_bzero, offered by several C libraries.

    The honest result is a statement of the trust that remains, for example: KaK_a is gone from the gateway’s RAM and flash, verified by reading back the erased blocks; the publisher’s archive copy is destroyed on day 90; RR remains and can recreate KaK_a. See Tree 20 §20.20, Tree 16 §20.16 and secret zeroization §5.37.