eBPF-based security platform
testing: prove the register's events tell every history apart
Daniel Borkmannb41114a22ceb
diff --git a/Documentation/contribute/testing/proof-coverage.rst b/Documentation/contribute/testing/proof-coverage.rstindex 76caf4bf..fd3eaf22 100644--- a/Documentation/contribute/testing/proof-coverage.rst+++ b/Documentation/contribute/testing/proof-coverage.rst@@ -381,6 +381,16 @@ or shorter, and "lengths 0 to 6" every input of each of those lengths.- Every index and 64-byte value text- Stores only PCRs 0 to 23 and marks exactly that one, from 64 hexdigits; a refusal marks nothing+ * - ``chain-events``+ - ``chain_upatch_event()``, ``chain_key_event()``,+ ``chain_tree_event()``, ``chain_fold()``, ``chain_init_event()`` of+ an empty set+ - Names of 0 to 8 and 255 to 257 bytes; every payload, digest,+ sequence number and register+ - SHA-256 is given exactly the bytes of the Lean model+ ``Shirudo.Events``: the tag and its NUL, then the fixed fields, the+ name cut at 256 bytes and the sequence number most significant byte+ first; the event is the digest, or zeros with the error* - ``eventlog-records``- ``log_records()``- Logs of 0 to 32 bytes@@ -459,10 +469,36 @@ the model follows the C.* - ``Shirudo.Chain``, the register of :src:`util/chain.c`- ``register_injective``, ``register_tagged_injective``: equalregisters come from the same events, tagged the same, in the same- order; ``register_eq_foldl``: the register folds the events in the- order they came- - The hash is injective on (register, event) pairs and never yields- the initial value; the tagged event encoding is injective+ order; ``register_injective_on``: the same with the hash injective+ only on the pairs the two sequences fold; ``register_eq_foldl``: the+ register folds the events in the order they came+ - The hash is injective on the (register, event) pairs (for+ ``register_injective_on`` only those folded) and never yields the+ initial value; ``register_tagged_injective`` also takes the tagged+ encoding as injective, which ``Shirudo.Events`` proves+ - Review+ * - ``Shirudo.Events``, the event encodings of :src:`util/chain.c`+ - ``bytes_injective``: two admitted events hash the same bytes only+ when they are the same event; ``listing_injective``: the init+ event's listing spells one set while no name holds a newline;+ ``sorts_unique``: ``qsort()`` leaves a set of distinct names in one+ order; ``replay_injective_on``, ``replay_collision``,+ ``verify_sound``: equal registers come from the same typed events in+ the same order, or the strings hashed hold a SHA-256 collision or a+ string that hashes to zero; ``upatch_cut``, ``listing_newline``,+ ``sorts_tie``: where the domain ends+ - SHA-256 maps no two different strings the two histories hash to one+ digest and none to 32 zero bytes; names ``upatch_name_valid()``+ accepts of at most 256 bytes; sequence numbers of a ``__s64``+ - CBMC, ``chain-events``, names of up to 8 and of 255 to 257 bytes;+ the listing of a non-empty set and the NV extend by review+ * - ``Shirudo.Measured``, ``measured_event()`` of :src:`util/measured.c`+ - ``holds_iff``: ``measured_holds()`` finds a name and payload exactly+ when the last init, load or unload bearing on the name is its load+ with that payload; ``measuredSet_nodup``: each name once;+ ``measuredSet_init``: an init record starts the set over;+ ``holds_last_load``, ``not_holds_after_unload``+ - None- Review* - ``Shirudo.SemVer``, ``bpm_semver_compare()`` of:src:`util/bpm_package.c`@@ -489,8 +525,7 @@ lines, the evidence document beyond its PCRs, the config update record,the site configuration file and the config image's settings and tree.The ``.upatch`` reader, the TPM structures and the package, index andtree readers are covered part by part, as the table shows; what joins-those parts, and the event encoders of the register, which need a model-of SHA-256, have no proof.+those parts has no proof.Within the ``.upatch`` reader, the proofs cover its parts but not theircomposition: ``upatch_parse()`` and ``upatch_open_memory()`` join thediff --git a/Documentation/internals/measurement-register.rst b/Documentation/internals/measurement-register.rstindex 6725bf84..b51d3b5e 100644--- a/Documentation/internals/measurement-register.rst+++ b/Documentation/internals/measurement-register.rst@@ -213,6 +213,15 @@ purges follows as an ``upatch_unload`` with the reason ``key_revoke``.Revocations a config carries at boot are not individual events; the``init`` event's trust set reflects them.+Lean 4 proves that these encodings tell every two events apart, for+upatch names of every length ``upatch_name_valid()`` takes and every+sequence number, and that the ``init`` listing spells one set of distinct+names whatever order ``qsort()`` leaves. With the register's fold, equal+registers then come from the same events in the same order unless+SHA-256 collides among the strings the two histories hash. CBMC shows+that :src:`util/chain.c` hashes exactly the bytes the model encodes. The+proofs are in :doc:`/contribute/testing/proof-coverage`.+Eventlog--------diff --git a/Documentation/reference/formats/eventlog.rst b/Documentation/reference/formats/eventlog.rstindex 8c4a99bd..11e672f3 100644--- a/Documentation/reference/formats/eventlog.rst+++ b/Documentation/reference/formats/eventlog.rst@@ -261,6 +261,14 @@ this boot's records the same way:last ``init`` record and the records after it.- A boot without an ``init`` record has no replay.+The upatches this boot measured are folded from the same records: an+``init`` record starts the set over with its ``set``, and an+``upatch_load`` or ``upatch_unload`` record adds or removes its upatch.+Only an ``init`` record's ``set`` counts. Lean 4 proves the fold holds an+upatch exactly when the last record that bears on it, an ``init`` record+or a load or unload of it, leaves it loaded: its load, or an ``init``+record whose ``set`` lists it, with that payload.+``status`` compares the replay with the live register (condition``ChainIntact``, field ``tpm.chain_matches_eventlog`` in:doc:`status-json`). It also reports a mismatch when the register'sdiff --git a/Documentation/security/threat-model.rst b/Documentation/security/threat-model.rstindex 21255051..0f04ed62 100644--- a/Documentation/security/threat-model.rst+++ b/Documentation/security/threat-model.rst@@ -958,7 +958,8 @@ tree operations run without it.:Counters: ``TpmExtend``:Tests: ``t4002``, ``t4003``, ``t4102``, ``t4103``, ``t6115``,``t6122``, ``t6128``, ``t6143``, ``t6144``-:Proofs: ``Shirudo.Chain``, ``eventlog-records``, ``tpm-digest``+:Proofs: ``Shirudo.Chain``, ``Shirudo.Events``, ``Shirudo.Measured``,+ ``chain-events``, ``eventlog-records``, ``tpm-digest``:Residual: R4, R12, R20, U6, U8, U9T6 Boot window@@ -1119,7 +1120,7 @@ document can carry a software key's signatures (U1).:Tests: ``t4003``, ``t4004``, ``t4102``:Proofs: ``tpm-reader``, ``tpm-attest``, ``tpm-signature``,``tpm-public``, ``attest-pcr``, ``attest-fields``,- ``attest-name-digest``, ``Shirudo.Chain``+ ``attest-name-digest``, ``Shirudo.Chain``, ``Shirudo.Events``:Residual: R10, R11, U1, U8, U9.. _tm-t10:diff --git a/testing/proofs/cbmc/chain-events.c b/testing/proofs/cbmc/chain-events.cnew file mode 100644index 00000000..b619f8f1--- /dev/null+++ b/testing/proofs/cbmc/chain-events.c@@ -0,0 +1,274 @@+// SPDX-License-Identifier: BSD-2-Clause+/*+ * Copyright (c) 2026 Authors of shirudo+ *+ * The event encoders of util/chain.c against testing/proofs/lean4/+ * Shirudo/Events.lean, with SHA-256 modelled as recording what it is+ * given: for every name of LEN bytes, payload, digest, sequence number+ * and register, chain_upatch_event(), chain_key_event(),+ * chain_tree_event(), chain_fold() and chain_init_event() of an empty set+ * hand SHA-256 exactly the bytes of the model, and give its digest, or+ * zeros and its error.+ */++#include "proof.h"+#include "../../../util/malloc.c"+#include "../../../util/string.c"+/* The C converts a __s64 and cuts a __u64 to bytes on purpose. */+#pragma CPROVER check push+#pragma CPROVER check disable "conversion"+#include "../../../util/chain.c"+#pragma CPROVER check pop++/* The longest string an event hashes: a upatch of a 256-byte name. */+#define HASHED_MAX (sizeof("shirudo-unload") + 32 + UPATCH_NAME_MAX)++/* What the last hash was given and gave, and the one before it. */+static __u8 hashed[HASHED_MAX];+static size_t hashed_len, prev_len, calls;+static __u8 digest[32], prev_digest[32];++static int any_result(void)+{+ int ret;++ return ret;+}++static void begin(void)+{+ __CPROVER_assert(calls < 2, "no more than the hashes of an event");+ prev_len = hashed_len;+ memcpy(prev_digest, digest, 32);+ hashed_len = 0;+}++static void record(const void *data, size_t len)+{+ __CPROVER_assert(__CPROVER_r_ok(data, len), "hashes only its input");+ __CPROVER_assert(hashed_len + len <= HASHED_MAX,+ "no more than the longest event");+ memcpy(hashed + hashed_len, data, len);+ hashed_len += len;+}++/* A fresh digest each call, or a failure that leaves anything. */+static int give_digest(__u8 out[32])+{+ int ret = any_result();++ __CPROVER_assert(__CPROVER_w_ok(out, 32), "a digest's room");+ __CPROVER_havoc_slice(digest, 32);+ if (ret)+ __CPROVER_havoc_slice(out, 32);+ else+ memcpy(out, digest, 32);+ calls++;+ return ret;+}++int sha256_init(struct sha256_ctx *ctx)+{+ begin();+ return any_result();+}++int sha256_update(struct sha256_ctx *ctx, const void *data, size_t len)+{+ record(data, len);+ return any_result();+}++int sha256_final(struct sha256_ctx *ctx, __u8 out[32])+{+ return give_digest(out);+}++void sha256_free(struct sha256_ctx *ctx)+{+}++int sha256_buffer(const void *data, size_t len, __u8 out[32])+{+ begin();+ record(data, len);+ return give_digest(out);+}++static void start(void)+{+ calls = 0;+ hashed_len = 0;+}++/* The last digest on success, zeros on failure. */+static void check_result(int ret, size_t n_calls, const __u8 event[32])+{+ size_t i;++ __CPROVER_assert(ret || calls == n_calls, "the last hash is the event");+ for (i = 0; i < 32; i++)+ __CPROVER_assert(event[i] == (ret ? 0 : digest[i]),+ "the digest, or zeros on failure");+}++/* hashed[*at..] holds the tag's bytes and its NUL. */+static void check_tag(const char *tag, size_t *at)+{+ size_t i;++ for (i = 0; tag[i]; i++)+ __CPROVER_assert(hashed[*at + i] == (__u8)tag[i], "the tag");+ __CPROVER_assert(hashed[*at + i] == 0, "the tag's NUL");+ *at += i + 1;+}++static void check_bytes(const void *want, size_t len, size_t *at)+{+ const __u8 *w = want;+ size_t i;++ for (i = 0; i < len; i++)+ __CPROVER_assert(hashed[*at + i] == w[i], "the field's bytes");+ *at += len;+}++static void check_end(size_t at)+{+ __CPROVER_assert(hashed_len == at, "nothing more");+}++static char *any_name(void)+{+ char *name = any_bytes(LEN + 1);++ __CPROVER_assume(!name[LEN] && strnlen(name, LEN) == LEN);+ return name;+}++/*+ * upatchBytes: the tag and its NUL, the payload, and the name up to+ * strnlen(name, UPATCH_NAME_MAX).+ */+static void upatch_event(const char *tag)+{+ size_t cut = min_t(size_t, LEN, UPATCH_NAME_MAX), at = 0;+ __u8 *payload = any_bytes(32), event[32];+ char *name = any_name();+ int ret;++ start();+ ret = chain_upatch_event(tag, name, payload, event);+ if (!ret) {+ check_tag(tag, &at);+ check_bytes(payload, 32, &at);+ check_bytes(name, cut, &at);+ check_end(at);+ }+ check_result(ret, 1, event);+}++/* keyBytes: the tag and its NUL, then the certificate's digest. */+static void key_event(void)+{+ static const char tag[] = "shirudo-key-revoke";+ __u8 *cert = any_bytes(32), event[32];+ size_t at = 0;+ int ret;++ start();+ ret = chain_key_event(tag, cert, event);+ if (!ret) {+ check_tag(tag, &at);+ check_bytes(cert, 32, &at);+ check_end(at);+ }+ check_result(ret, 1, event);+}++/*+ * treeBytes: the tag and its NUL, be64 (u64OfS64 seq), which read back+ * most significant byte first is seq modulo 2^64, and the digest.+ */+static void tree_event(void)+{+ __u8 *operation = any_bytes(32), event[32];+ size_t at = 0, i;+ __u64 u, v = 0;+ __s64 seq;+ int ret;++ u = seq >= 0 ? (__u64)seq :+ (__u64)(seq + INT64_MAX + 1) + ((__u64)INT64_MAX + 1);+ start();+ ret = chain_tree_event(seq, operation, event);+ if (!ret) {+ check_tag("shirudo-tree", &at);+ for (i = 0; i < 8; i++)+ v = v * 256 + hashed[at + i];+ __CPROVER_assert(v == u,+ "seq modulo 2^64, most significant first");+ at += 8;+ check_bytes(operation, 32, &at);+ check_end(at);+ }+ check_result(ret, 1, event);+}++/* fold: the register and the event. */+static void fold(void)+{+ __u8 *chain = any_bytes(32), *event = any_bytes(32), was[32];+ size_t at = 0;+ int ret;++ memcpy(was, chain, 32);+ start();+ ret = chain_fold(chain, event);+ if (!ret) {+ check_bytes(was, 32, &at);+ check_bytes(event, 32, &at);+ check_end(at);+ }+ check_result(ret, 1, chain);+}++/*+ * chain_init_event() of an empty set: initBytes, the tag and its NUL, the+ * certificate digest, the digest of the empty listing and the tree root.+ */+static void init_event(void)+{+ __u8 *cert = any_bytes(32), *root = any_bytes(32);+ __u8 set_digest[32], event[32];+ struct measured_upatch set[1];+ size_t at = 0, i;+ int ret;++ start();+ ret = chain_init_event(cert, set, 0, root, set_digest, event);+ if (ret) {+ check_result(ret, 2, event);+ return;+ }+ __CPROVER_assert(prev_len == 0, "an empty listing");+ for (i = 0; i < 32; i++)+ __CPROVER_assert(set_digest[i] == prev_digest[i],+ "the listing's digest");+ check_tag("shirudo-init", &at);+ check_bytes(cert, 32, &at);+ check_bytes(prev_digest, 32, &at);+ check_bytes(root, 32, &at);+ check_end(at);+ check_result(ret, 2, event);+}++void harness(void)+{+ upatch_event("shirudo-upatch");+ upatch_event("shirudo-unload");+ key_event();+ tree_event();+ fold();+ init_event();+}diff --git a/testing/proofs/cbmc/proofs.list b/testing/proofs/cbmc/proofs.listindex 2ce68c0e..8baef00b 100644--- a/testing/proofs/cbmc/proofs.list+++ b/testing/proofs/cbmc/proofs.list@@ -72,3 +72,4 @@ bpm-tree-reader --unwind 6 --malloc-may-fail --malloc-fail-null LEN=0,1bpm-source-config --unwind 14bpm-oci-strings --unwind 9bpm-semver-model --slice-formula --unwind 1 --unwindset strlen.0:10,strcmp.0:10,strcspn.0:2,strcspn.1:4,digits.0:10,parse_base.0:10,parse_base.1:10,semver_parse.0:4,semver_identifiers.0:4,semver_identifiers.1:3,prerelease_compare.0:3,memchr.0:4,memcmp.0:4,bpm_semver_compare.0:4,strnlen.0:10,any_string.0:10,break_at.0:10,split_on.0:10,next_ident.0:4,numeral.0:8,numeric.0:8,ident_ok.0:4,identifiers.0:3,lex_bytes.0:10,memcmp_model.0:4,lex_idents.0:3,semver_model_compare.0:4 LEN=9+chain-events --unwind 258 LEN=0-8,255-257diff --git a/testing/proofs/lean4/Shirudo.lean b/testing/proofs/lean4/Shirudo.leanindex 58a6e13f..ccc4c332 100644--- a/testing/proofs/lean4/Shirudo.lean+++ b/testing/proofs/lean4/Shirudo.lean@@ -4,3 +4,5 @@import Shirudo.Numberimport Shirudo.Chainimport Shirudo.SemVer+import Shirudo.Events+import Shirudo.Measureddiff --git a/testing/proofs/lean4/Shirudo/Chain.lean b/testing/proofs/lean4/Shirudo/Chain.leanindex f4c8232b..be18f711 100644--- a/testing/proofs/lean4/Shirudo/Chain.lean+++ b/testing/proofs/lean4/Shirudo/Chain.lean@@ -10,6 +10,9 @@ signed. Assuming `H` is collision resistant, modelled as injective on(register, event) pairs and never yielding the initial value, and thetagged encoding of events likewise, equal registers mean the targetmeasured exactly the events the log shows, in that order.+`register_injective_on` asks the same of `H` only on the pairs the two+sequences fold, which a real hash can meet; `Shirudo.Events` proves the+encodings of util/chain.c injective and builds the end theorem on it.-/namespace Shirudo.Chain@@ -40,6 +43,43 @@ theorem register_injective (H : D → D → D) (init : D)have ⟨hr, he⟩ := hH _ _ _ _ hrw [he, register_injective H init hH hinit es fs hr]+/-- The (register, event) pairs `H` folds on the way to the register of+`events`, newest first. -/+def steps (H : D → D → D) (init : D) : List D → List (D × D)+ | [] => []+ | e :: es => (register H init es, e) :: steps H init es++/-- Equal registers come from equal event sequences when `H` maps no two+of the pairs the two sequences fold to one value, and none of them to the+initial value. Unlike `register_injective`, this asks nothing of `H` on+pairs neither sequence folds, which a hash with a 32-byte output can+meet. -/+theorem register_injective_on (H : D → D → D) (init : D) :+ ∀ l1 l2 : List D,+ (∀ p ∈ steps H init l1, ∀ q ∈ steps H init l2,+ H p.1 p.2 = H q.1 q.2 → p = q) →+ (∀ p ∈ steps H init l1 ++ steps H init l2, H p.1 p.2 ≠ init) →+ register H init l1 = register H init l2 → l1 = l2+ | [], [], _, _, _ => rfl+ | [], f :: fs, _, hinit, h =>+ absurd h.symm (hinit (register H init fs, f) (by simp [steps]))+ | e :: es, [], _, hinit, h =>+ absurd h (hinit (register H init es, e) (by simp [steps]))+ | e :: es, f :: fs, hH, hinit, h => by+ have hp := hH (register H init es, e) (by simp [steps])+ (register H init fs, f) (by simp [steps]) h+ simp only [Prod.mk.injEq] at hp+ have hrest : es = fs :=+ register_injective_on H init es fs+ (fun p hp' q hq => hH p (by simp [steps, hp']) q (by simp [steps, hq]))+ (fun p hp' => hinit p (by+ simp only [List.mem_append] at hp' ⊢+ rcases hp' with hp' | hp'+ · exact Or.inl (by simp [steps, hp'])+ · exact Or.inr (by simp [steps, hp'])))+ hp.1+ rw [hp.2, hrest]+theorem map_injective {α β : Type} (f : α → β) (hf : Function.Injective f) :∀ l1 l2 : List α, l1.map f = l2.map f → l1 = l2| [], [], _ => rfl@@ -49,6 +89,20 @@ theorem map_injective {α β : Type} (f : α → β) (hf : Function.Injective f)simp only [List.map_cons, List.cons.injEq] at hrw [hf h.1, map_injective f hf as bs h.2]+/-- `map_injective` for an `f` injective only between the elements of the+two lists. -/+theorem map_injective_on {α β : Type} (f : α → β) :+ ∀ l1 l2 : List α, (∀ a ∈ l1, ∀ b ∈ l2, f a = f b → a = b) →+ l1.map f = l2.map f → l1 = l2+ | [], [], _, _ => rfl+ | [], _ :: _, _, h => by simp at h+ | _ :: _, [], _, h => by simp at h+ | a :: as, b :: bs, hf, h => by+ simp only [List.map_cons, List.cons.injEq] at h+ rw [hf a (by simp) b (by simp) h.1,+ map_injective_on f as bs+ (fun x hx y hy => hf x (by simp [hx]) y (by simp [hy])) h.2]+/-- Equal registers come from the same tagged events, in the same order:an event can be neither left out, added, swapped for another nor moved. -/theorem register_tagged_injective (H : D → D → D) (init : D)diff --git a/testing/proofs/lean4/Shirudo/Events.lean b/testing/proofs/lean4/Shirudo/Events.leannew file mode 100644index 00000000..4eda7b94--- /dev/null+++ b/testing/proofs/lean4/Shirudo/Events.lean@@ -0,0 +1,785 @@+-- SPDX-License-Identifier: BSD-2-Clause+-- Copyright (c) 2026 Authors of shirudo++import Shirudo.Chain+import Shirudo.SemVer++/-!+The events of the measurement register, byte for byte as util/chain.c+hashes them. Every event is SHA-256 of a tag, its NUL and fixed fields:++- `chain_init_event()`: `"shirudo-init"`, the certificate set's digest,+ the digest of the listing of the restored set, one+ `"<payload hex> <name>\n"` line per upatch sorted by name, and the+ upatch tree's root;+- `chain_upatch_event()`: `"shirudo-upatch"` for a load or+ `"shirudo-unload"` for an unload, the payload digest and the name cut+ at `strnlen(name, UPATCH_NAME_MAX)`;+- `chain_key_event()`: `"shirudo-key-revoke"` and the certificate's+ digest;+- `chain_tree_event()`: `"shirudo-tree"`, the operation's sequence+ number, as a `__u64` most significant byte first, and its digest.++`chain_fold()`, and the TPM's NV extend, set the register to SHA-256 of+the register and the event, from 32 zero bytes before the first extend.++The model follows each function's buffer: `Fields.bytes` is what the C+hands SHA-256 for an event whose set is already hashed, `listing` the+string `chain_init_event()` builds, and `Event.digest` the event digest.+A byte is a `UInt8`, a digest 32 of them, a C string the bytes before its+NUL. testing/proofs/cbmc/chain-events.c checks that the C hashes exactly+`Fields.bytes` for every name of up to 8 bytes and of 255 to 257, every+payload, digest and sequence number, the init event of an empty set+included, and `fold` for every register and event.++On the domain the callers admit, upatch names that `upatch_name_valid()`+accepts of at most `UPATCH_NAME_MAX` bytes and sequence numbers a+`__s64` holds, `Fields.bytes` is injective (`bytes_injective`): the first+NUL ends the tag, no tag holds one and no two are equal, and every field+after it has a fixed length but the name, which runs to the end. The+listing is injective while no name holds a newline (`listing_injective`).+Outside that domain both fail: a name of more than `UPATCH_NAME_MAX`+bytes is cut (`upatch_cut`), and a name with a newline spells two+members (`listing_newline`). `qsort()` leaves a set whose names are+distinct in one order whatever order it came in (`sorts_unique`), so the+init event depends only on the upatches the set holds; with a name twice+it is `qsort()`'s choice (`sorts_tie`).++SHA-256 is a parameter. A function from byte strings onto 32-byte+digests is never injective, so the end theorem asks only that SHA-256+maps no two of the strings it was given to one digest and none to the+zero register (`replay_injective_on`). Then equal registers come from+the same typed events, in the same order. Read the other way+(`replay_collision`), two different histories that reach one register+hold a SHA-256 collision among the strings they hash, or a string that+hashes to 32 zero bytes: the result rests on SHA-256 alone.+`replay_injective` states it for an idealized injective hash, and+`verify_sound` as `attest verify` uses it.+-/++namespace Shirudo.Events+open Shirudo++/-! ### Bytes, digests and tags -/++/-- `UPATCH_NAME_MAX` of include/shirudo/upatch.h. -/+def nameMax : Nat := 256++/-- The bytes of a C string literal before its NUL. -/+def ascii (s : String) : List UInt8 := s.toList.map fun c => c.toNat.toUInt8++/-- A SHA-256 digest, and every other 32-byte field of an event. -/+structure Digest where+ bytes : List UInt8+ length_eq : bytes.length = 32++theorem Digest.ext_bytes {a b : Digest} (h : a.bytes = b.bytes) : a = b := by+ cases a+ cases b+ cases h+ rfl++/-- The register before its first extend: an NV extend index reads as+zeros of its digest's size until it is written. -/+def Digest.zero : Digest := ⟨List.replicate 32 0, by simp⟩++/-- The tags, as the callers pass them. -/+def tagInit : List UInt8 := ascii "shirudo-init"+def tagUpatch : List UInt8 := ascii "shirudo-upatch"+def tagUnload : List UInt8 := ascii "shirudo-unload"+def tagKeyRevoke : List UInt8 := ascii "shirudo-key-revoke"+def tagTree : List UInt8 := ascii "shirudo-tree"++/-- `strnlen(s, max)` of the C string whose bytes, up to its NUL, start+with `s`. -/+def strnlen (s : List UInt8) (max : Nat) : Nat :=+ min (s.takeWhile (· != 0)).length max++/-! ### What util/chain.c hashes -/++/-- An event as `chain_*_event()` hashes it: the init event's set is in+it as the digest of its listing. -/+inductive Fields where+ | init (cert setDigest treeRoot : Digest)+ | upatch (name : List UInt8) (payload : Digest)+ | unload (name : List UInt8) (payload : Digest)+ | keyRevoke (cert : Digest)+ | tree (seq : Int) (operation : Digest)++/-- `chain_init_event()`'s `tag` buffer: `"shirudo-init"` copied with its+NUL, then the certificate set's digest, the set's and the tree root. -/+def initBytes (cert setDigest treeRoot : Digest) : List UInt8 :=+ tagInit ++ [0] ++ cert.bytes ++ setDigest.bytes ++ treeRoot.bytes++/-- `chain_upatch_event()`'s buffer: `tag` and its NUL, the payload, and+the name up to `strnlen(name, UPATCH_NAME_MAX)`. -/+def upatchBytes (tag name : List UInt8) (payload : Digest) : List UInt8 :=+ tag ++ [0] ++ payload.bytes ++ name.take (strnlen name nameMax)++/-- `chain_key_event()`: what `sha256_2()` hashes, `tag` and its NUL, then+the certificate's digest. -/+def keyBytes (tag : List UInt8) (cert : Digest) : List UInt8 :=+ tag ++ [0] ++ cert.bytes++/-- `(__u64)seq`: C converts a negative `__s64` by adding 2^64. -/+def u64OfS64 (seq : Int) : Nat := (seq % 18446744073709551616).toNat++/-- The loop of `chain_tree_event()`: byte `i` is+`(__u8)(s >> (56 - 8 * i))`, the most significant first. -/+def be64 (s : Nat) : List UInt8 :=+ (List.range 8).map fun i => UInt8.ofNat (s >>> (56 - 8 * i))++/-- `chain_tree_event()`'s buffer: `"shirudo-tree"` with its NUL, the+sequence number and the operation's digest. -/+def treeBytes (seq : Int) (operation : Digest) : List UInt8 :=+ tagTree ++ [0] ++ be64 (u64OfS64 seq) ++ operation.bytes++/-- What the C hands SHA-256 for an event. -/+def Fields.bytes : Fields → List UInt8+ | .init c s r => initBytes c s r+ | .upatch n p => upatchBytes tagUpatch n p+ | .unload n p => upatchBytes tagUnload n p+ | .keyRevoke c => keyBytes tagKeyRevoke c+ | .tree s o => treeBytes s o++/-! ### The domain the callers admit -/++/-- A byte `upatch_name_valid()` accepts: `[A-Za-z0-9._-]`. -/+def nameChar (c : UInt8) : Bool :=+ (97 ≤ c && c ≤ 122) || (65 ≤ c && c ≤ 90) || (48 ≤ c && c ≤ 57) ||+ c == 46 || c == 95 || c == 45++/-- `upatch_name_valid()` of util/upatch.c: not empty, not starting with a+dot, and only bytes of `nameChar`. -/+def nameValid : List UInt8 → Bool+ | [] => false+ | c :: cs => c != 46 && (c :: cs).all nameChar++/-- The names that reach `chain_upatch_event()` and `chain_init_event()`+on a target and in `attest verify`: what `upatch_name_valid()` accepts,+in a buffer of `UPATCH_NAME_MAX + 1` bytes. -/+def NameAdmitted (n : List UInt8) : Prop :=+ nameValid n = true ∧ n.length ≤ nameMax++/-- What the encoding needs of a name: a C string that `strnlen()` does+not cut. The names `attest predict` reads with+`attest_parse_name_digest()`, of 1 to 256 bytes before the first `=`,+fit too, though `upatch_name_valid()` need not accept them. -/+def NameFits (n : List UInt8) : Prop := 0 ∉ n ∧ n.length ≤ nameMax++/-- A sequence number a `__s64` holds. -/+def S64 (seq : Int) : Prop :=+ -9223372036854775808 ≤ seq ∧ seq < 9223372036854775808++/-- The events the encoding is injective on. -/+def Fields.Fits : Fields → Prop+ | .upatch n _ => NameFits n+ | .unload n _ => NameFits n+ | .tree s _ => S64 s+ | _ => True++theorem nameValid_mem {n : List UInt8} (h : nameValid n = true) :+ ∀ c ∈ n, nameChar c = true := by+ cases n with+ | nil => simp [nameValid] at h+ | cons c cs =>+ simp only [nameValid, Bool.and_eq_true, List.all_eq_true] at h+ exact h.2++theorem nameChar_ne {c : UInt8} (h : nameChar c = true) : c ≠ 0 ∧ c ≠ 10 := by+ constructor <;> (rintro rfl; exact absurd h (by decide))++theorem NameAdmitted.fits {n : List UInt8} (h : NameAdmitted n) :+ NameFits n :=+ ⟨fun h0 => (nameChar_ne (nameValid_mem h.1 0 h0)).1 rfl, h.2⟩++theorem NameAdmitted.no_newline {n : List UInt8} (h : NameAdmitted n) :+ 10 ∉ n :=+ fun h10 => (nameChar_ne (nameValid_mem h.1 10 h10)).2 rfl++/-! ### Splitting the bytes -/++/-- Two strings that each run to a separator they do not hold, then go+on: the parts before and after it are equal. -/+theorem split_at (c : UInt8) :+ ∀ {a b r s : List UInt8}, c ∉ a → c ∉ b →+ a ++ c :: r = b ++ c :: s → a = b ∧ r = s+ | [], [], _, _, _, _, h => ⟨rfl, by simpa using h⟩+ | [], x :: b, _, _, _, hb, h => by+ simp only [List.nil_append, List.cons_append, List.cons.injEq] at h+ exact absurd (h.1 ▸ List.mem_cons_self) hb+ | x :: a, [], _, _, ha, _, h => by+ simp only [List.nil_append, List.cons_append, List.cons.injEq] at h+ exact absurd (h.1.symm ▸ List.mem_cons_self) ha+ | x :: a, y :: b, r, s, ha, hb, h => by+ simp only [List.cons_append, List.cons.injEq] at h+ have hrest := split_at c (a := a) (b := b) (r := r) (s := s)+ (fun hm => ha (List.mem_cons_of_mem x hm))+ (fun hm => hb (List.mem_cons_of_mem y hm)) h.2+ exact ⟨by rw [h.1, hrest.1], hrest.2⟩++theorem split_digest {a b : Digest} {r s : List UInt8}+ (h : a.bytes ++ r = b.bytes ++ s) : a = b ∧ r = s := by+ have h' := List.append_inj h (by rw [a.length_eq, b.length_eq])+ exact ⟨Digest.ext_bytes h'.1, h'.2⟩++theorem takeWhile_no_nul :+ ∀ l : List UInt8, 0 ∉ l → l.takeWhile (· != 0) = l+ | [], _ => rfl+ | x :: xs, h => by+ have hx : x ≠ 0 := fun hx => h (hx ▸ List.mem_cons_self)+ simp [hx,+ takeWhile_no_nul xs (fun hm => h (List.mem_cons_of_mem x hm))]++theorem strnlen_fits {n : List UInt8} (h : NameFits n) :+ n.take (strnlen n nameMax) = n := by+ rw [strnlen, takeWhile_no_nul n h.1, Nat.min_eq_left h.2]+ exact List.take_of_length_le (Nat.le_refl _)++theorem be64_length (s : Nat) : (be64 s).length = 8 := by+ simp [be64]++theorem ofNat_eq {a b : Nat} (h : UInt8.ofNat a = UInt8.ofNat b) :+ a % 256 = b % 256 := by+ have := congrArg UInt8.toNat h+ simpa using this++theorem be64_injective {s s' : Nat} (hs : s < 18446744073709551616)+ (hs' : s' < 18446744073709551616) (h : be64 s = be64 s') : s = s' := by+ simp only [be64, List.range, List.range.loop, List.map_cons, List.map_nil,+ List.cons.injEq, Nat.shiftRight_eq_div_pow] at h+ obtain ⟨h0, h1, h2, h3, h4, h5, h6, h7, -⟩ := h+ have e0 := ofNat_eq h0+ have e1 := ofNat_eq h1+ have e2 := ofNat_eq h2+ have e3 := ofNat_eq h3+ have e4 := ofNat_eq h4+ have e5 := ofNat_eq h5+ have e6 := ofNat_eq h6+ have e7 := ofNat_eq h7+ simp only [Nat.reducePow, Nat.reduceMul, Nat.reduceSub, Nat.pow_zero,+ Nat.div_one] at e0 e1 e2 e3 e4 e5 e6 e7+ omega++theorem u64OfS64_lt (seq : Int) : u64OfS64 seq < 18446744073709551616 := by+ unfold u64OfS64+ omega++theorem u64OfS64_injective {a b : Int} (ha : S64 a) (hb : S64 b)+ (h : u64OfS64 a = u64OfS64 b) : a = b := by+ unfold u64OfS64 at h+ unfold S64 at ha hb+ omega++/-! ### The encoding is injective -/++/-- The tag of an event. -/+def Fields.tag : Fields → List UInt8+ | .init .. => tagInit+ | .upatch .. => tagUpatch+ | .unload .. => tagUnload+ | .keyRevoke .. => tagKeyRevoke+ | .tree .. => tagTree++/-- What follows the tag's NUL. -/+def Fields.body : Fields → List UInt8+ | .init c s r => c.bytes ++ s.bytes ++ r.bytes+ | .upatch n p => p.bytes ++ n.take (strnlen n nameMax)+ | .unload n p => p.bytes ++ n.take (strnlen n nameMax)+ | .keyRevoke c => c.bytes+ | .tree s o => be64 (u64OfS64 s) ++ o.bytes++theorem Fields.bytes_eq (f : Fields) : f.bytes = f.tag ++ 0 :: f.body := by+ cases f <;>+ simp [Fields.bytes, Fields.tag, Fields.body, initBytes, upatchBytes,+ keyBytes, treeBytes]++theorem Fields.tag_no_nul (f : Fields) : 0 ∉ f.tag := by+ cases f <;> simp only [Fields.tag] <;> decide++/-- A tag names one kind of event: no two kinds share a tag. -/+theorem Fields.tag_kind {f g : Fields} (h : f.tag = g.tag) :+ f.ctorIdx = g.ctorIdx := by+ cases f <;> cases g <;> first+ | rfl+ | exact absurd h (by simp only [Fields.tag]; decide)++theorem Fields.body_injective {f g : Fields} (hf : f.Fits) (hg : g.Fits)+ (hk : f.ctorIdx = g.ctorIdx) (h : f.body = g.body) : f = g := by+ cases f <;> cases g <;> simp only [Fields.ctorIdx, Nat.reduceEqDiff] at hk <;>+ simp only [Fields.body, List.append_assoc] at h+ case init.init c s r c' s' r' =>+ obtain ⟨hc, h⟩ := split_digest h+ obtain ⟨hs, hr⟩ := split_digest h+ rw [hc, hs, Digest.ext_bytes hr]+ case upatch.upatch n p n' p' =>+ obtain ⟨hp, hn⟩ := split_digest h+ rw [strnlen_fits hf, strnlen_fits hg] at hn+ rw [hn, hp]+ case unload.unload n p n' p' =>+ obtain ⟨hp, hn⟩ := split_digest h+ rw [strnlen_fits hf, strnlen_fits hg] at hn+ rw [hn, hp]+ case keyRevoke.keyRevoke c c' =>+ rw [Digest.ext_bytes h]+ case tree.tree s o s' o' =>+ have h' := List.append_inj h (by rw [be64_length, be64_length])+ have hs := u64OfS64_injective hf hg+ (be64_injective (u64OfS64_lt s) (u64OfS64_lt s') h'.1)+ rw [hs, Digest.ext_bytes h'.2]++/-- Two events whose names `strnlen()` does not cut, and whose sequence+numbers a `__s64` holds, hash the same bytes only when they are the same+event. -/+theorem bytes_injective_of_fits {f g : Fields} (hf : f.Fits) (hg : g.Fits)+ (h : f.bytes = g.bytes) : f = g := by+ rw [Fields.bytes_eq, Fields.bytes_eq] at h+ have ⟨ht, hb⟩ := split_at 0 f.tag_no_nul g.tag_no_nul h+ exact Fields.body_injective hf hg (Fields.tag_kind ht) hb++/-- The events the callers admit: names `upatch_name_valid()` accepts of+at most `UPATCH_NAME_MAX` bytes, sequence numbers of a `__s64`. -/+def Fields.Admitted : Fields → Prop+ | .upatch n _ => NameAdmitted n+ | .unload n _ => NameAdmitted n+ | .tree s _ => S64 s+ | _ => True++theorem Fields.Admitted.fits {f : Fields} (h : f.Admitted) : f.Fits := by+ cases f with+ | upatch n p => exact NameAdmitted.fits h+ | unload n p => exact NameAdmitted.fits h+ | tree s o => exact h+ | init => trivial+ | keyRevoke => trivial++/-- On the domain the callers admit, two events hash the same bytes only+when they are the same event: no tag or field of one kind can pass for+another's, and a load for an unload, nor one name, payload, certificate,+sequence number or digest for another. -/+theorem bytes_injective {f g : Fields} (hf : f.Admitted) (hg : g.Admitted)+ (h : f.bytes = g.bytes) : f = g :=+ bytes_injective_of_fits hf.fits hg.fits h++/-- Outside the domain: two names that agree on their first+`UPATCH_NAME_MAX` bytes hash alike, the longer one cut. -/+theorem upatch_cut (tag n : List UInt8) (x : UInt8) (p : Digest)+ (hn : NameFits n) (hlen : n.length = nameMax) (hx : x ≠ 0) :+ upatchBytes tag (n ++ [x]) p = upatchBytes tag n p := by+ have hw := takeWhile_no_nul (n ++ [x]) (by+ simp only [List.mem_append, List.mem_singleton, not_or]+ exact ⟨hn.1, fun h0 => hx h0.symm⟩)+ have hcut := strnlen_fits hn+ simp only [upatchBytes, strnlen, hw, List.length_append, List.length_singleton,+ hlen] at hcut ⊢+ rw [hcut]+ simp [nameMax, hlen]++/-! ### The init event's set -/++/-- A member of the restored set: `struct measured_upatch`, its payload+already hex-encoded by `hex_encode()`. -/+structure Member where+ name : List UInt8+ payload : Digest++/-- `"0123456789abcdef"[n]` of `hex_encode()`. -/+def hexDigit (n : Nat) : UInt8 := (ascii "0123456789abcdef").getD n 0++/-- `hex_encode()` of util/hex.c: each byte as two lowercase digits, the+high nibble first. -/+def hexEncode (bs : List UInt8) : List UInt8 :=+ bs.flatMap fun b => [hexDigit (b.toNat >>> 4), hexDigit (b.toNat &&& 15)]++/-- One line of the listing: `"%s %s\n"` of the payload's hex and the+name. -/+def line (m : Member) : List UInt8 :=+ hexEncode m.payload.bytes ++ [32] ++ m.name ++ [10]++/-- The listing `chain_init_event()` hashes into the set's digest: the+lines of the set in the order `qsort()` left it. -/+def listing (set : List Member) : List UInt8 := set.flatMap line++theorem hexDigit_injective : ∀ a b : Fin 16,+ hexDigit a.val = hexDigit b.val → a = b := by+ decide++theorem hexByte_injective {a b : UInt8}+ (h : hexDigit (a.toNat >>> 4) = hexDigit (b.toNat >>> 4))+ (h' : hexDigit (a.toNat &&& 15) = hexDigit (b.toNat &&& 15)) : a = b := by+ have ha := a.toNat_lt+ have hb := b.toNat_lt+ have hand : ∀ n : Nat, n &&& 15 = n % 16 := fun n =>+ Nat.and_two_pow_sub_one_eq_mod n 4+ rw [hand, hand] at h'+ rw [Nat.shiftRight_eq_div_pow, Nat.shiftRight_eq_div_pow] at h+ have hi := hexDigit_injective ⟨a.toNat / 2 ^ 4, by omega⟩+ ⟨b.toNat / 2 ^ 4, by omega⟩ h+ have hl := hexDigit_injective ⟨a.toNat % 16, by omega⟩+ ⟨b.toNat % 16, by omega⟩ h'+ simp only [Fin.mk.injEq] at hi hl+ exact UInt8.toNat_inj.mp (by omega)++theorem hexEncode_length (bs : List UInt8) :+ (hexEncode bs).length = 2 * bs.length := by+ induction bs with+ | nil => rfl+ | cons b bs ih =>+ simp only [hexEncode, List.flatMap_cons, List.length_append,+ List.length_cons, List.length_nil] at ih ⊢+ rw [ih]+ omega++theorem hexEncode_injective :+ ∀ a b : List UInt8, hexEncode a = hexEncode b → a = b+ | [], [], _ => rfl+ | [], _ :: _, h => by simp [hexEncode] at h+ | _ :: _, [], h => by simp [hexEncode] at h+ | x :: xs, y :: ys, h => by+ simp only [hexEncode, List.flatMap_cons, List.cons_append, List.nil_append,+ List.cons.injEq] at h+ obtain ⟨h1, h2, h3⟩ := h+ rw [hexByte_injective h1 h2, hexEncode_injective xs ys h3]++theorem hexEncode_digest (d : Digest) : (hexEncode d.bytes).length = 64 := by+ rw [hexEncode_length, d.length_eq]++/-- While no name holds a newline, the listing spells one set: each line+is 64 hex digits, a space, and the name up to the newline. -/+theorem listing_injective :+ ∀ s t : List Member, (∀ m ∈ s, 10 ∉ m.name) → (∀ m ∈ t, 10 ∉ m.name) →+ listing s = listing t → s = t+ | [], [], _, _, _ => rfl+ | [], m :: _, _, _, h => by simp [listing, line] at h+ | m :: _, [], _, _, h => by simp [listing, line] at h+ | m :: ms, n :: ns, hs, ht, h => by+ simp only [listing, List.flatMap_cons, line, List.append_assoc,+ List.singleton_append] at h+ have h1 := List.append_inj h+ (by rw [hexEncode_digest, hexEncode_digest])+ have hp := Digest.ext_bytes (hexEncode_injective _ _ h1.1)+ have h1' := h1.2+ simp only [List.cons_append, List.cons.injEq, true_and] at h1'+ have h2 := split_at 10 (hs m (by simp)) (ht n (by simp)) h1'+ have hrest := listing_injective ms ns+ (fun x hx => hs x (by simp [hx])) (fun x hx => ht x (by simp [hx])) h2.2+ cases m+ cases n+ simp only at hp h2+ rw [hp, h2.1, hrest]++/-- Outside the domain: a name holding a newline and the hex of another+payload makes one member spell two. -/+theorem listing_newline (p q : Digest) (a b : List UInt8) :+ listing [⟨a ++ 10 :: hexEncode q.bytes ++ 32 :: b, p⟩] =+ listing [⟨a, p⟩, ⟨b, q⟩] := by+ simp [listing, line]++/-! ### The order `qsort()` leaves -/++/-- `member_cmp()`: `strcmp()` of the names. -/+def memberCmp (a b : Member) : Ordering :=+ SemVer.strcmp (a.name.map UInt8.toNat) (b.name.map UInt8.toNat)++/-- What `qsort()` with `member_cmp()` may leave of `set`: the same+members, none after one it compares above. -/+def Sorts (set out : List Member) : Prop :=+ out.Perm set ∧ out.Pairwise fun a b => memberCmp a b ≠ .gt++theorem strcmp_total : SemVer.TotalOrder SemVer.strcmp :=+ SemVer.lex_total SemVer.cmpNat_total++theorem memberCmp_eq {a b : Member} (h : memberCmp a b = .eq) :+ a.name = b.name := by+ have := (strcmp_total.eq_iff _ _).mp h+ exact Chain.map_injective UInt8.toNat (fun _ _ hxy => UInt8.toNat_inj.mp hxy)+ _ _ this++/-- In a list sorted by distinct names, each member compares below every+later one. -/+theorem sorted_strict {out : List Member}+ (hnd : (out.map Member.name).Nodup)+ (h : out.Pairwise fun a b => memberCmp a b ≠ .gt) :+ out.Pairwise fun a b => memberCmp a b = .lt := by+ have hne : out.Pairwise fun a b => a.name ≠ b.name := by+ have := List.pairwise_map.mp hnd+ exact this+ refine (h.and hne).imp ?_+ intro a b ⟨hgt, hn⟩+ cases hc : memberCmp a b+ · rfl+ · exact absurd (memberCmp_eq hc) hn+ · exact absurd hc hgt++theorem strict_unique :+ ∀ out out' : List Member, out.Perm out' →+ out.Pairwise (fun a b => memberCmp a b = .lt) →+ out'.Pairwise (fun a b => memberCmp a b = .lt) → out = out'+ | [], [], _, _, _ => rfl+ | [], _ :: _, hp, _, _ => absurd hp.length_eq (by simp)+ | _ :: _, [], hp, _, _ => absurd hp.length_eq (by simp)+ | a :: as, b :: bs, hp, h, h' => by+ rw [List.pairwise_cons] at h h'+ have hab : a = b := by+ apply Classical.byContradiction+ intro hne+ have ha : a ∈ bs := by+ have := hp.mem_iff.mp List.mem_cons_self+ rcases List.mem_cons.mp this with he | he+ · exact absurd he hne+ · exact he+ have hb : b ∈ as := by+ have := hp.mem_iff.mpr List.mem_cons_self+ rcases List.mem_cons.mp this with he | he+ · exact absurd he.symm hne+ · exact he+ have h1 : memberCmp b a = .gt := by+ have := h.1 b hb+ unfold memberCmp at this ⊢+ rw [strcmp_total.swap, this]+ rfl+ rw [h'.1 a ha] at h1+ cases h1+ subst hab+ rw [strict_unique as bs (List.Perm.cons_inv hp) h.2 h'.2]++/-- `chain_init_event()` sorts the set before it lists it: two sets of the+same upatches, each name once, in any order, give the same listing+whatever order `qsort()` leaves equal elements in, so the init event+depends only on which upatches the set holds. -/+theorem sorts_unique {s t out out' : List Member}+ (hnd : (s.map Member.name).Nodup) (hst : s.Perm t) (h : Sorts s out)+ (h' : Sorts t out') : out = out' := by+ have hnd1 : (out.map Member.name).Nodup := (h.1.map _).nodup_iff.mpr hnd+ have hnd2 : (out'.map Member.name).Nodup :=+ (h'.1.map _).nodup_iff.mpr ((hst.map _).nodup_iff.mp hnd)+ exact strict_unique out out' (h.1.trans (hst.trans h'.1.symm))+ (sorted_strict hnd1 h.2) (sorted_strict hnd2 h'.2)++/-- With a name twice, the order is `qsort()`'s: both orders of two+members of one name sort, and their listings differ unless the payloads+are equal. -/+theorem sorts_tie (n : List UInt8) (p q : Digest) :+ Sorts [⟨n, p⟩, ⟨n, q⟩] [⟨n, p⟩, ⟨n, q⟩] ∧+ Sorts [⟨n, p⟩, ⟨n, q⟩] [⟨n, q⟩, ⟨n, p⟩] ∧+ (listing [⟨n, p⟩, ⟨n, q⟩] = listing [⟨n, q⟩, ⟨n, p⟩] → p = q) := by+ have heq : memberCmp ⟨n, p⟩ ⟨n, q⟩ = .eq :=+ (strcmp_total.eq_iff _ _).mpr rfl+ have heq' : memberCmp ⟨n, q⟩ ⟨n, p⟩ = .eq :=+ (strcmp_total.eq_iff _ _).mpr rfl+ refine ⟨⟨List.Perm.refl _, by simp [heq]⟩,+ ⟨List.Perm.swap _ _ _, by simp [heq']⟩, fun h => ?_⟩+ simp only [listing, line, List.flatMap_cons, List.flatMap_nil,+ List.append_nil, List.append_assoc] at h+ have := List.append_inj h (by rw [hexEncode_digest, hexEncode_digest])+ exact Digest.ext_bytes (hexEncode_injective _ _ this.1)++/-! ### Typed events and the register -/++/-- An event the register measures, as the target means it: an init event+with its certificate set's digest, the restored set as `qsort()` left it+and the tree root; a load or an unload of a upatch; a key revocation; a+tree operation. -/+inductive Event where+ | init (cert : Digest) (set : List Member) (treeRoot : Digest)+ | load (name : List UInt8) (payload : Digest)+ | unload (name : List UInt8) (payload : Digest)+ | keyRevoke (cert : Digest)+ | tree (seq : Int) (operation : Digest)++/-- The events the callers admit. -/+def Event.Admitted : Event → Prop+ | .init _ s _ => ∀ m ∈ s, NameAdmitted m.name+ | .load n _ => NameAdmitted n+ | .unload n _ => NameAdmitted n+ | .keyRevoke _ => True+ | .tree s _ => S64 s++variable (sha : List UInt8 → Digest)++/-- What the C hashes for `e`, the init event's listing hashed into its+set digest. -/+def Event.fields : Event → Fields+ | .init c s r => .init c (sha (listing s)) r+ | .load n p => .upatch n p+ | .unload n p => .unload n p+ | .keyRevoke c => .keyRevoke c+ | .tree s o => .tree s o++/-- The event digest `chain_*_event()` gives. -/+def Event.digest (e : Event) : Digest := sha (e.fields sha).bytes++/-- `chain_fold()`, and the TPM's NV extend: the register and the event,+64 bytes, hashed. -/+def fold (r e : Digest) : Digest := sha (r.bytes ++ e.bytes)++/-- The register after `events`, oldest first, as `attest predict` and+`attest verify` replay it and the TPM extends it. -/+def replay (events : List Event) : Digest :=+ events.foldl (fun r e => fold sha r (e.digest sha)) Digest.zero++theorem replay_eq_register (events : List Event) :+ replay sha events =+ Chain.register (fold sha) Digest.zero+ (events.map (Event.digest sha)).reverse := by+ rw [Chain.register_eq_foldl, List.reverse_reverse, List.foldl_map]+ rfl++/-- Every string an event hands SHA-256: its bytes, and an init event's+listing. -/+def Event.inputs (e : Event) : List (List UInt8) :=+ match e with+ | .init _ s _ => [listing s, (e.fields sha).bytes]+ | _ => [(e.fields sha).bytes]++/-- Every string SHA-256 is given on the way to `replay events`: each+event's, and each fold's 64 bytes. -/+def inputs (events : List Event) : List (List UInt8) :=+ events.flatMap (Event.inputs sha) +++ (Chain.steps (fold sha) Digest.zero+ (events.map (Event.digest sha)).reverse).map+ fun p => p.1.bytes ++ p.2.bytes++theorem Event.admitted_fields {e : Event} (h : e.Admitted) :+ (e.fields sha).Admitted := by+ cases e with+ | init => trivial+ | load n p => exact h+ | unload n p => exact h+ | keyRevoke => trivial+ | tree s o => exact h++theorem Event.bytes_mem_inputs (e : Event) :+ (e.fields sha).bytes ∈ e.inputs sha := by+ cases e <;> simp [Event.inputs]++/-- Two admitted events with one digest are the same event, unless+SHA-256 maps two different strings among those the events hash to one+digest. -/+theorem Event.digest_injective_on (a b : Event) (ha : a.Admitted)+ (hb : b.Admitted)+ (hsha : ∀ m ∈ a.inputs sha ++ b.inputs sha,+ ∀ m' ∈ a.inputs sha ++ b.inputs sha, sha m = sha m' → m = m')+ (h : a.digest sha = b.digest sha) : a = b := by+ have hbytes := hsha _ (List.mem_append_left _ (a.bytes_mem_inputs sha))+ _ (List.mem_append_right _ (b.bytes_mem_inputs sha)) h+ have hf := bytes_injective (a.admitted_fields sha ha)+ (b.admitted_fields sha hb) hbytes+ cases a <;> cases b <;> simp only [Event.fields, reduceCtorEq] at hf+ case init.init c s r c' s' r' =>+ simp only [Fields.init.injEq] at hf+ obtain ⟨hc, hs, hr⟩ := hf+ have hl := hsha (listing s) (by simp [Event.inputs])+ (listing s') (by simp [Event.inputs]) hs+ have := listing_injective s s'+ (fun m hm => NameAdmitted.no_newline (ha m hm))+ (fun m hm => NameAdmitted.no_newline (hb m hm)) hl+ rw [hc, this, hr]+ all_goals+ first+ | (simp only [Fields.upatch.injEq] at hf; rw [hf.1, hf.2])+ | (simp only [Fields.unload.injEq] at hf; rw [hf.1, hf.2])+ | (simp only [Fields.keyRevoke.injEq] at hf; rw [hf])+ | (simp only [Fields.tree.injEq] at hf; rw [hf.1, hf.2])++/-- Equal registers come from the same admitted events, in the same order,+when SHA-256 maps no two different strings the two histories hash to one+digest and none of them to the zero register. -/+theorem replay_injective_on (l1 l2 : List Event)+ (h1 : ∀ e ∈ l1, e.Admitted) (h2 : ∀ e ∈ l2, e.Admitted)+ (hsha : ∀ m ∈ inputs sha l1 ++ inputs sha l2,+ ∀ m' ∈ inputs sha l1 ++ inputs sha l2, sha m = sha m' → m = m')+ (hzero : ∀ m ∈ inputs sha l1 ++ inputs sha l2, sha m ≠ Digest.zero)+ (h : replay sha l1 = replay sha l2) : l1 = l2 := by+ rw [replay_eq_register, replay_eq_register] at h+ have hsteps : ∀ (l : List Event) p,+ p ∈ Chain.steps (fold sha) Digest.zero+ (l.map (Event.digest sha)).reverse →+ p.1.bytes ++ p.2.bytes ∈ inputs sha l := by+ intro l p hp+ exact List.mem_append_right _ (List.mem_map.mpr ⟨p, hp, rfl⟩)+ have hevent : ∀ (l : List Event) e, e ∈ l → ∀ m ∈ e.inputs sha,+ m ∈ inputs sha l := by+ intro l e he m hm+ exact List.mem_append_left _ (List.mem_flatMap.mpr ⟨e, he, hm⟩)+ have hregs := Chain.register_injective_on (fold sha) Digest.zero _ _+ (fun p hp q hq hpq => by+ have he := hsha _ (List.mem_append_left _ (hsteps l1 p hp))+ _ (List.mem_append_right _ (hsteps l2 q hq)) hpq+ obtain ⟨h1', h2'⟩ := split_digest he+ exact Prod.ext h1' (Digest.ext_bytes h2'))+ (fun p hp => by+ rcases List.mem_append.mp hp with hp | hp+ · exact hzero _ (List.mem_append_left _ (hsteps l1 p hp))+ · exact hzero _ (List.mem_append_right _ (hsteps l2 p hp)))+ h+ rw [List.reverse_inj] at hregs+ exact Chain.map_injective_on _ l1 l2+ (fun a ha b hb hab => Event.digest_injective_on sha a b (h1 a ha) (h2 b hb)+ (fun m hm m' hm' => hsha m+ (by+ rcases List.mem_append.mp hm with hm | hm+ · exact List.mem_append_left _ (hevent l1 a ha m hm)+ · exact List.mem_append_right _ (hevent l2 b hb m hm))+ m'+ (by+ rcases List.mem_append.mp hm' with hm' | hm'+ · exact List.mem_append_left _ (hevent l1 a ha m' hm')+ · exact List.mem_append_right _ (hevent l2 b hb m' hm')))+ hab)+ hregs++/-- Two different admitted histories that reach one register hold a+SHA-256 collision among the strings they hash, or a string that hashes to+the zero register. -/+theorem replay_collision (l1 l2 : List Event)+ (h1 : ∀ e ∈ l1, e.Admitted) (h2 : ∀ e ∈ l2, e.Admitted)+ (hne : l1 ≠ l2) (h : replay sha l1 = replay sha l2) :+ (∃ m ∈ inputs sha l1 ++ inputs sha l2,+ ∃ m' ∈ inputs sha l1 ++ inputs sha l2, m ≠ m' ∧ sha m = sha m') ∨+ ∃ m ∈ inputs sha l1 ++ inputs sha l2, sha m = Digest.zero := by+ apply Classical.byContradiction+ intro hno+ apply hne+ apply replay_injective_on sha l1 l2 h1 h2 _ _ h+ · intro m hm m' hm' he+ apply Classical.byContradiction+ intro hmm+ exact hno (Or.inl ⟨m, hm, m', hm', hmm, he⟩)+ · intro m hm hz+ exact hno (Or.inr ⟨m, hm, hz⟩)++/-- For an idealised SHA-256, injective and never the zero register,+equal registers come from the same admitted events in the same order. -/+theorem replay_injective (hsha : ∀ m m', sha m = sha m' → m = m')+ (hzero : ∀ m, sha m ≠ Digest.zero) (l1 l2 : List Event)+ (h1 : ∀ e ∈ l1, e.Admitted) (h2 : ∀ e ∈ l2, e.Admitted)+ (h : replay sha l1 = replay sha l2) : l1 = l2 :=+ replay_injective_on sha l1 l2 h1 h2 (fun m _ m' _ => hsha m m')+ (fun m _ => hzero m) h++/-- What `attest verify` concludes. The evidence's records carry digests+`ds`: the init record's equals the init event the operator expects for+the certificates, set and tree root given, and each later record's+derives from its fields, so `ds` are the digests of `expected`. They+replay to the register the TPM certified, which the TPM extended by the+target's `history`. Then the target measured exactly `expected`, unless+SHA-256 collides on the strings the two hash or maps one to zero. -/+theorem verify_sound (expected history : List Event) (ds : List Digest)+ (value : Digest)+ (hexpected : ∀ e ∈ expected, e.Admitted)+ (hhistory : ∀ e ∈ history, e.Admitted)+ (hderive : ds = expected.map (Event.digest sha))+ (hreplay : ds.foldl (fold sha) Digest.zero = value)+ (hcertified : replay sha history = value)+ (hsha : ∀ m ∈ inputs sha expected ++ inputs sha history,+ ∀ m' ∈ inputs sha expected ++ inputs sha history,+ sha m = sha m' → m = m')+ (hzero : ∀ m ∈ inputs sha expected ++ inputs sha history,+ sha m ≠ Digest.zero) :+ expected = history := by+ apply replay_injective_on sha expected history hexpected hhistory hsha hzero+ rw [hcertified, ← hreplay, hderive, List.foldl_map]+ rfl++end Shirudo.Eventsdiff --git a/testing/proofs/lean4/Shirudo/Measured.lean b/testing/proofs/lean4/Shirudo/Measured.leannew file mode 100644index 00000000..24b8da83--- /dev/null+++ b/testing/proofs/lean4/Shirudo/Measured.lean@@ -0,0 +1,414 @@+-- SPDX-License-Identifier: BSD-2-Clause+-- Copyright (c) 2026 Authors of shirudo++/-!+The measured set of util/measured.c: the upatches the eventlog records as+loaded, each with the payload of its load. `eventlog_upatches()` and+`eventlog_boot_upatches()` of util/eventlog.c walk the records in order+and call `measured_event()` for each load and unload they measure: an+init record gives `EVENTLOG_UPATCH_INIT`, which starts the set over, then+a load for each upatch of its set, an `upatch_load` record a load and an+`upatch_unload` record an unload. The walk stops at the first error, and+`measured_set_log()` and `measured_set_boot()` fail with it.++`measured_event()` keeps the set in an array: a load overwrites the+payload of the entry of its name, or appends one and refuses a 4097th+with `-ENOSPC`, and refuses with `-EINVAL` what does not fit an entry; an+unload moves the last entry into the place of the one of its name.+`measured_holds()` looks for an entry of a name and payload. `init`+restores an archive only when the set holds its name and payload, and+`status` and the next upatch command undo a pin or an archive it does+not hold.++The model follows `measured_event()` statement by statement on a list for+the array, its length for `s->n`. For every sequence of events the fold+accepts, the set holds each name at most once (`measuredSet_nodup`), and+holds a name with a payload exactly when the last event that bears on+the name, an init or a load or unload of it, is a load of it with that+payload (`holds_iff`): an upatch is in the set when its last load is+followed by neither an unload of it nor an init record, with that load's+payload, whatever payload the unload names. An init record starts the+set over (`measuredSet_init`): what comes before it changes the set only+by failing, so `measured_set_log()` gives the set of the last init on.+`Record.events` is what `upatches_line()` makes of each record shirudo+writes, a set only in an init record.+-/++namespace Shirudo.Measured++/-- `MEASURED_MAX` of util/measured.c. -/+def measuredMax : Nat := 4096++/-- `UPATCH_NAME_MAX`: an entry's name holds this many bytes and a NUL. -/+def nameMax : Nat := 256++/-- `2 * UPATCH_PAYLOAD_HASH_LEN`: the payload's hex digits an entry+holds before its NUL. -/+def payloadHexMax : Nat := 64++/-- `enum eventlog_upatch_event` with the name and payload hex the walk+passes; a C string is its bytes before the NUL. -/+inductive Event where+ | init+ | load (name payloadHex : List UInt8)+ | unload (name payloadHex : List UInt8)+deriving DecidableEq++/-- `struct measured_entry`. -/+structure Entry where+ name : List UInt8+ payloadHex : List UInt8+deriving DecidableEq++/-- The errors `measured_event()` returns. -/+inductive Error where+ | nospc+ | inval+deriving DecidableEq++/-- The loop of `measured_event()` that looks for `name`: the index of the+first entry of that name, or `s->n` when there is none. -/+def find (s : List Entry) (name : List UInt8) : Nat :=+ s.findIdx fun e => e.name == name++/-- `s->entries[i] = s->entries[--s->n]`. -/+def swapRemove (s : List Entry) (i : Nat) : List Entry :=+ match s.getLast? with+ | some last => (s.set i last).dropLast+ | none => s++/-- `measured_event()`. -/+def measuredEvent (s : List Entry) : Event → Except Error (List Entry)+ | .init => .ok []+ | .unload name _ =>+ if find s name < s.length then .ok (swapRemove s (find s name))+ else .ok s+ | .load name payloadHex =>+ if find s name = s.length ∧ s.length = measuredMax then .error .nospc+ else if nameMax < name.length ∨ payloadHexMax < payloadHex.length then+ .error .inval+ else if find s name < s.length then+ .ok (s.set (find s name) ⟨name, payloadHex⟩)+ else .ok (s ++ [⟨name, payloadHex⟩])++/-- `measured_set_fold()`: the events in order from an empty set, stopping+at the first error. -/+def measuredSet (events : List Event) : Except Error (List Entry) :=+ events.foldlM measuredEvent []++/-- `measured_holds()`. -/+def measuredHolds (s : List Entry) (name payloadHex : List UInt8) : Bool :=+ s.any fun e => e.name == name && e.payloadHex == payloadHex++/-- Whether an event bears on `name`: an init, which starts the set over,+or a load or an unload of that name. -/+def Event.about (name : List UInt8) : Event → Bool+ | .init => true+ | .load n _ => n == name+ | .unload n _ => n == name++/-- The last of `events` that bears on `name`. -/+def lastAbout (name : List UInt8) (events : List Event) : Option Event :=+ (events.filter (Event.about name)).getLast?++/-! ### The array operations -/++theorem find_lt_iff (s : List Entry) (name : List UInt8) :+ find s name < s.length ↔ ∃ e ∈ s, e.name = name := by+ simp [find, List.findIdx_lt_length]++theorem find_name {s : List Entry} {name : List UInt8}+ (h : find s name < s.length) : s[find s name].name = name := by+ have := List.findIdx_getElem (w := h)+ simp only [beq_iff_eq] at this+ exact this++/-- The entry `find()` stops at splits the array. -/+theorem find_split {s : List Entry} {name : List UInt8}+ (h : find s name < s.length) :+ ∃ pre x post, s = pre ++ x :: post ∧ pre.length = find s name ∧+ x.name = name :=+ ⟨s.take (find s name), s[find s name], s.drop (find s name + 1),+ by rw [← List.drop_eq_getElem_cons h, List.take_append_drop],+ by simp [Nat.min_eq_left (Nat.le_of_lt h)],+ find_name h⟩++theorem set_split (pre post : List Entry) (x v : Entry) :+ (pre ++ x :: post).set pre.length v = pre ++ v :: post := by+ simp++theorem swapRemove_split (pre post : List Entry) (x : Entry) :+ (swapRemove (pre ++ x :: post) pre.length).Perm (pre ++ post) := by+ rcases List.eq_nil_or_concat post with rfl | ⟨post', last, rfl⟩+ · simp [swapRemove]+ · simp only [List.concat_eq_append, swapRemove]+ have hl : (pre ++ x :: (post' ++ [last])).getLast? = some last := by+ rw [← List.cons_append, ← List.append_assoc]+ simp only [List.getLast?_append, List.getLast?_singleton, Option.some_or]+ simp only [hl]+ rw [set_split]+ have hd : (pre ++ last :: (post' ++ [last])).dropLast =+ pre ++ last :: post' := by+ rw [← List.cons_append, ← List.append_assoc, List.dropLast_concat]+ rw [hd, ← List.append_assoc]+ exact List.perm_middle.trans (List.perm_append_singleton _ _).symm++theorem nodup_split {pre post : List Entry} {x : Entry}+ (h : ((pre ++ x :: post).map Entry.name).Nodup) :+ ((pre ++ post).map Entry.name).Nodup ∧+ ∀ y ∈ pre ++ post, y.name ≠ x.name := by+ have hp := (List.perm_middle (a := x) (l₁ := pre) (l₂ := post)).map+ Entry.name+ rw [hp.nodup_iff, List.map_cons, List.nodup_cons] at h+ refine ⟨h.2, fun y hy hyx => h.1 ?_⟩+ exact List.mem_map.mpr ⟨y, hy, hyx⟩++theorem mem_split_ne {pre post : List Entry} {x y : Entry}+ (hne : y.name ≠ x.name) : y ∈ pre ++ x :: post ↔ y ∈ pre ++ post := by+ simp only [List.mem_append, List.mem_cons]+ constructor+ · rintro (h | rfl | h)+ · exact Or.inl h+ · exact absurd rfl hne+ · exact Or.inr h+ · rintro (h | h)+ · exact Or.inl h+ · exact Or.inr (Or.inr h)++theorem nodup_split_set {pre post : List Entry} {x v : Entry}+ (h : ((pre ++ x :: post).map Entry.name).Nodup) (hv : v.name = x.name) :+ ((pre ++ v :: post).map Entry.name).Nodup := by+ simpa [hv] using h++/-! ### One event -/++/-- What `measured_event()` does to the set: names stay distinct, and the+set holds a name with a payload afterwards exactly when the event bears+on the name and is a load of it with that payload, or does not bear on+it and the set held them before. -/+theorem measuredEvent_spec {s s' : List Entry} {e : Event}+ (hnd : (s.map Entry.name).Nodup) (h : measuredEvent s e = .ok s') :+ (s'.map Entry.name).Nodup ∧+ ∀ name p, ⟨name, p⟩ ∈ s' ↔+ if e.about name then e = .load name p else ⟨name, p⟩ ∈ s := by+ cases e with+ | init =>+ simp only [measuredEvent, Except.ok.injEq] at h+ subst h+ simp [Event.about]+ | unload n q =>+ simp only [measuredEvent] at h+ by_cases hf : find s n < s.length+ · simp only [hf, ite_true, Except.ok.injEq] at h+ obtain ⟨pre, x, post, hs, hlen, hx⟩ := find_split hf+ rw [← hlen, hs] at h+ subst h+ subst hs+ have hp := swapRemove_split pre post x+ obtain ⟨hnd', hne⟩ := nodup_split hnd+ refine ⟨(hp.map Entry.name).nodup_iff.mpr hnd', fun name p => ?_⟩+ rw [hp.mem_iff]+ by_cases hn : n = name+ · subst hn+ simp only [Event.about, beq_self_eq_true, ite_true, reduceCtorEq,+ iff_false]+ exact fun hm => hne _ hm hx.symm+ · have hb : (n == name) = false := by simpa using hn+ simp only [Event.about, hb, Bool.false_eq_true, ite_false]+ exact (mem_split_ne (by simp; rw [hx]; exact Ne.symm hn)).symm+ · simp only [hf, ite_false, Except.ok.injEq] at h+ subst h+ refine ⟨hnd, fun name p => ?_⟩+ by_cases hn : n = name+ · subst hn+ simp only [Event.about, beq_self_eq_true, ite_true, reduceCtorEq,+ iff_false]+ exact fun hm => hf ((find_lt_iff _ _).mpr ⟨_, hm, rfl⟩)+ · have hb : (n == name) = false := by simpa using hn+ simp [Event.about, hb]+ | load n q =>+ simp only [measuredEvent] at h+ split at h+ · cases h+ split at h+ · cases h+ by_cases hf : find s n < s.length+ · simp only [hf, ite_true, Except.ok.injEq] at h+ obtain ⟨pre, x, post, hs, hlen, hx⟩ := find_split hf+ rw [← hlen, hs, set_split] at h+ subst h+ subst hs+ obtain ⟨_, hne⟩ := nodup_split hnd+ refine ⟨nodup_split_set hnd (by simp [hx]), fun name p => ?_⟩+ by_cases hn : n = name+ · subst hn+ simp only [Event.about, beq_self_eq_true, ite_true, Event.load.injEq,+ true_and]+ rw [List.mem_append, List.mem_cons, Entry.mk.injEq]+ constructor+ · rintro (hm | ⟨-, rfl⟩ | hm)+ · exact absurd hx.symm (hne _ (List.mem_append_left _ hm))+ · rfl+ · exact absurd hx.symm (hne _ (List.mem_append_right _ hm))+ · rintro rfl+ exact Or.inr (Or.inl ⟨rfl, rfl⟩)+ · have hb : (n == name) = false := by simpa using hn+ simp only [Event.about, hb, Bool.false_eq_true, ite_false]+ rw [mem_split_ne (by simp; exact Ne.symm hn),+ mem_split_ne (by simp; rw [hx]; exact Ne.symm hn)]+ · simp only [hf, ite_false, Except.ok.injEq] at h+ subst h+ have hnone : ∀ x ∈ s, x.name ≠ n := fun x hx hxn =>+ hf ((find_lt_iff _ _).mpr ⟨x, hx, hxn⟩)+ refine ⟨?_, fun name p => ?_⟩+ · rw [List.map_append, List.nodup_append]+ refine ⟨hnd, by simp, ?_⟩+ intro a ha b hb+ simp only [List.map_cons, List.map_nil, List.mem_singleton] at hb+ obtain ⟨x, hx, rfl⟩ := List.mem_map.mp ha+ rw [hb]+ exact hnone x hx+ · rw [List.mem_append, List.mem_singleton]+ by_cases hn : n = name+ · subst hn+ have : (⟨n, p⟩ : Entry) ∉ s := fun hm => hnone _ hm rfl+ simp [Event.about, this, eq_comm]+ · have hb : (n == name) = false := by simpa using hn+ simp [Event.about, hb, Ne.symm hn]++/-! ### The fold -/++theorem measuredSet_append (es : List Event) (e : Event) :+ measuredSet (es ++ [e]) = measuredSet es >>= fun s => measuredEvent s e :=+ by simp [measuredSet, List.foldlM_append]++theorem lastAbout_append (name : List UInt8) (es : List Event) (e : Event) :+ lastAbout name (es ++ [e]) =+ if e.about name then some e else lastAbout name es := by+ unfold lastAbout+ rw [List.filter_append]+ by_cases h : e.about name <;> simp [h, List.getLast?_append]++/-- For every sequence of events the fold accepts, the set it gives holds+each name at most once, and holds a name with a payload exactly when the+last event bearing on the name is a load of it with that payload. -/+theorem measuredSet_spec :+ ∀ (events : List Event) (s : List Entry), measuredSet events = .ok s →+ (s.map Entry.name).Nodup ∧+ ∀ name p, ⟨name, p⟩ ∈ s ↔ lastAbout name events = some (.load name p)+ := by+ intro events+ rw [← List.reverse_reverse events]+ induction events.reverse with+ | nil =>+ intro s h+ simp only [List.reverse_nil, measuredSet, List.foldlM_nil, pure,+ Except.pure, Except.ok.injEq] at h+ subst h+ simp [lastAbout]+ | cons e rs ih =>+ intro s h+ rw [List.reverse_cons] at h ⊢+ generalize rs.reverse = es at h ih ⊢+ rw [measuredSet_append] at h+ cases hes : measuredSet es with+ | error err => simp [hes, Except.bind, bind] at h+ | ok s0 =>+ simp only [hes] at h+ obtain ⟨hnd0, hmem0⟩ := ih s0 hes+ obtain ⟨hnd, hstep⟩ := measuredEvent_spec hnd0 h+ refine ⟨hnd, fun name p => ?_⟩+ rw [hstep, lastAbout_append]+ by_cases ha : e.about name+ · simp [ha]+ · simp [ha, hmem0]++/-- Each upatch appears in the measured set once at most. -/+theorem measuredSet_nodup {events : List Event} {s : List Entry}+ (h : measuredSet events = .ok s) : (s.map Entry.name).Nodup :=+ (measuredSet_spec events s h).1++theorem measuredHolds_iff (s : List Entry) (name p : List UInt8) :+ measuredHolds s name p = true ↔ ⟨name, p⟩ ∈ s := by+ simp only [measuredHolds, List.any_eq_true, Bool.and_eq_true, beq_iff_eq]+ constructor+ · rintro ⟨⟨n, q⟩, hm, rfl, rfl⟩+ exact hm+ · intro hm+ exact ⟨_, hm, rfl, rfl⟩++/-- What `init` relies on to restore an archive: `measured_holds()` finds a+name and payload in the set exactly when the last event that bears on the+name, a load or an unload of it or an init record, is a load of it with+that payload. -/+theorem holds_iff {events : List Event} {s : List Entry}+ (h : measuredSet events = .ok s) (name p : List UInt8) :+ measuredHolds s name p = true ↔+ lastAbout name events = some (.load name p) := by+ rw [measuredHolds_iff]+ exact (measuredSet_spec events s h).2 name p++theorem lastAbout_tail (name : List UInt8) (pre post : List Event) (e : Event)+ (he : e.about name = true) (hpost : ∀ x ∈ post, x.about name = false) :+ lastAbout name (pre ++ e :: post) = some e := by+ unfold lastAbout+ have : post.filter (Event.about name) = [] :=+ List.filter_eq_nil_iff.mpr (fun x hx => by simp [hpost x hx])+ simp [List.filter_append, he, this]++/-- A load that no later unload of its upatch and no later init record+follows is in the set with its payload. -/+theorem holds_last_load {pre post : List Event} {s : List Entry}+ {name p : List UInt8} (h : measuredSet (pre ++ .load name p :: post) = .ok s)+ (hpost : ∀ x ∈ post, x.about name = false) :+ measuredHolds s name p = true :=+ (holds_iff h name p).mpr (lastAbout_tail name pre post _ (by simp [Event.about])+ hpost)++/-- After an unload of an upatch, which no later load of it follows, the+set holds it with no payload, whatever payload the unload names. -/+theorem not_holds_after_unload {pre post : List Event} {s : List Entry}+ {name q : List UInt8}+ (h : measuredSet (pre ++ .unload name q :: post) = .ok s)+ (hpost : ∀ x ∈ post, x.about name = false) (p : List UInt8) :+ measuredHolds s name p = false := by+ have hl := lastAbout_tail name pre post (.unload name q)+ (by simp [Event.about]) hpost+ cases hh : measuredHolds s name p+ · rfl+ · rw [holds_iff h, hl] at hh+ cases hh++/-- An init record starts the set over: the events before it change the+set only by failing. -/+theorem measuredSet_init (pre post : List Event) :+ measuredSet (pre ++ .init :: post) =+ measuredSet pre >>= fun _ => measuredSet post := by+ simp only [measuredSet, List.foldlM_append, List.foldlM_cons, measuredEvent]+ cases List.foldlM measuredEvent [] pre <;> rfl++/-- The events `upatches_line()` gives for each record shirudo writes. -/+inductive Record where+ | init (set : List (List UInt8 × List UInt8))+ | upatchLoad (name payloadHex : List UInt8)+ | upatchUnload (name payloadHex : List UInt8)+ | other++def Record.events : Record → List Event+ | .init set => .init :: set.map fun m => .load m.1 m.2+ | .upatchLoad n p => [.load n p]+ | .upatchUnload n p => [.unload n p]+ | .other => []++/-- `measured_set_log()` over a log of records: the set holds an upatch+with a payload exactly when the last init record, load or unload that+bears on it is its load with that payload, or an init record that lists+it, last with that payload. -/+theorem holds_records {records : List Record} {s : List Entry}+ (h : measuredSet (records.flatMap Record.events) = .ok s)+ (name p : List UInt8) :+ measuredHolds s name p = true ↔+ lastAbout name (records.flatMap Record.events) = some (.load name p) :=+ holds_iff h name p++end Shirudo.Measured