government

commit 37b1f5914992b1c2410e634b80cb352b72e7f793

tree

parent:
29fbe69f4da4ce1dc5603c685ced1955b2808761

nmyk <nick@nmyk.io>

2026-11-14T16:55:02-05:00

ratify: add chain checks

diff --git a/DESIGN.md b/DESIGN.md
index 29154b0ca938183f5bb412de813e3fe6437afc5e..91a0fc34905f28667fdff91e8c98e3d335c362a1 100644
--- a/DESIGN.md
+++ b/DESIGN.md
@@ -29,13 +29,14 @@ Terminology used in this doc: *GOV* is the language's root OID arc; *red tape* is the copies of a leaf that the validator itself generates, through `anyPolicy`, to keep every leaf at the same depth; *ratify* means "pass path validation".
 
 ## Source format
 
-A `.gov` file is one UTF-8 text file of concatenated PEM `CERTIFICATE` blocks: a trust anchor first, then one certificate per tree depth, top-down.
+A `.gov` file is one UTF-8 text file of concatenated PEM `CERTIFICATE` blocks: a trust anchor and one certificate per tree depth. The compiler writes them anchor first, top-down; the interpreter accepts them in any order.
 
-- **Block 0** is the trust anchor (self-signed). It carries no policies.
-- **Blocks 1..n** are the certification path. Certificate *i* is issued by certificate *i−1* and carries every node at depth *i* of the tree. So *n* equals the program's AST depth.
+- **The trust anchor** is the one self-signed certificate. It carries no policies.
+- **The certification path** is every other certificate. The certificate at depth *i* is issued by the one at depth *i−1* and carries every node at depth *i* of the tree. So *n* equals the program's AST depth.
+- **Order.** The interpreter recovers each certificate's depth from the certificates themselves: it starts at the anchor and follows issuer links down. Every link is pinned by a signature, so the order cannot be forged, and a shuffled file runs exactly like the ordered one. A file that is not one clean chain (no anchor, two certificates issued by the same parent, a missing depth, an unrelated certificate) is an error.
 - Text outside PEM blocks is ignored, as PEM allows. The compiler writes nothing there by default (the program's name is already in every subject as `O=`). With `-source` it writes the original Lisp source, indented so no line of it can start a PEM block. The source is opt-in because the certs alone are the program, and the source may hold comments or code the author does not want to publish.
 - Any non-`CERTIFICATE` PEM block is an error.
-- Anchor-first order is deliberate: reading the file top to bottom reads the tree top to bottom. (Conventional PEM bundles are leaf-first.)
+- The compiler writes anchor first so that reading the file top to bottom reads the tree top to bottom (conventional PEM bundles are leaf-first). This is for human readers only.
 
 **Trust.** By default a program is self-ratified: the interpreter trusts the anchor inside the file, so validation checks internal consistency only. `government run -anchor gov-ca.pem prog.gov` additionally requires the anchor to match a given certificate, which gives code signing for free: only run programs ratified by your government.
 
@@ -291,7 +292,7 @@ - `Certificate.Policies` and `Certificate.PolicyMappings` are populated by `ParseCertificate`, and a critical policyMappings extension is not listed as unhandled.
 - **`CreateCertificate` does not emit `PolicyMappings` in 1.24.** It silently drops the field. The transpiler must DER-encode the extension itself and pass it through `ExtraExtensions`. A ~15-line hand encoder was enough in the prototype. The same is true of `policyConstraints`.
 - Ed25519 certificate signing is byte-for-byte deterministic.
 
-**Why not `x509.Verify`?** It builds its own paths (we need the exact file order), it does not expose the policy tree, and it is built around system-root semantics. `CheckSignatureFrom` gives us signatures plus the parent's CA and keyCertSign checks.
+**Why not `x509.Verify`?** It builds its own paths (we need exactly the path in the file), it does not expose the policy tree, and it is built around system-root semantics. `CheckSignatureFrom` gives us signatures plus the parent's CA and keyCertSign checks.
 
 ### Packages
 
@@ -308,10 +309,10 @@ | `gov2lisp` | Decompiler: AST back to Lisp text |
 
 ### Ratification steps
 
-1. Parse every PEM block; the first is the anchor and must be self-signed. With `-anchor`, its public key must match the pinned one.
-2. For each cert *i*: issuer equals subject of *i−1*; `CheckSignatureFrom(cert i−1)` passes (else `E-TAMPERED`); the check time (`-at`, default now) is inside its validity (else `E-NOT-IN-FORCE` or `E-LAPSED`).
-3. Certs 0..n−1 have basicConstraints CA:TRUE; no cert is self-issued (that would change `policy_mapping` counting).
-4. No unknown critical extensions; no `policyConstraints` or `inhibitAnyPolicy` (rejected in v1 to keep the counters trivial).
+1. Parse every PEM block (an unreadable file is `E-MALFORMED`). Order the certs: the anchor is the only self-issued cert, every other cert's issuer must be the subject of exactly one cert in the file, and no two certs may share a parent (else `E-CHAIN`). The anchor must be self-signed. With `-anchor`, its public key must match the pinned one.
+2. For each cert at depth *i*: `CheckSignatureFrom(cert at depth i−1)` passes (else `E-TAMPERED`); the check time (`-at`, default now) is inside its validity (else `E-NOT-IN-FORCE` or `E-LAPSED`).
+3. Certs at depths 0..n−1 are CAs allowed to sign certs (basicConstraints CA:TRUE and keyCertSign); no cert but the anchor is self-issued, since that would change `policy_mapping` counting (else `E-CHAIN`).
+4. No unknown critical extensions; no `policyConstraints` or `inhibitAnyPolicy`, rejected in v1 to keep the counters trivial (else `E-CHAIN`).
 5. With `-crl`: verify each CRL and reject any path cert it revokes (`E-REPEALED`, `E-STALE-REPEALS`).
 6. Run policy processing with the inputs in "The policy tree as AST", then the strict check.
 
@@ -447,7 +448,7 @@ | Shared subexpressions? | Allowed; evaluated on the DAG without unfolding | Policy tree |
 | `define` in lambda bodies? | Allowed at the start of the body; sequential, no mutual recursion | Semantics |
 | Who is trusted? | The file's own anchor (`-anchor` optional) | Source format |
 | Should programs expire? | Only when built with `-expires` | Civic features |
-| Cert order in the file? | Anchor first, top-down | Source format |
+| Cert order in the file? | Written anchor first, top-down; read in any order | Source format |
 | OID root? | UUID arc under `2.25` | OID encoding |
 | v1 extras? | No variadic lambdas; `if` without else returns `()`; add `strlen`, `strcat`, `str?` | Semantics, builtin table |
 | Which X.509 extras? | Effective dates, repeal by CRL, notes, authorship | Civic features |
diff --git a/PLAN.md b/PLAN.md
index a193832a6cf7656845d8a1efffe18f845ccd58ad..6898af1ac057aced46dd8a6ca2a39e947a4320c2 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -147,10 +147,10 @@ 23. **PEM loader** (`ratify`)
     - Build: `Load([]byte) ([]*x509.Certificate, error)`; ignore text between blocks; reject non-`CERTIFICATE` blocks and files with fewer than two certs.
     - Learn: PEM as base64-wrapped DER with labels; why the bytes inside are what gets signed, not the text.
     - Done when: files from step 22 load; a file with a `PRIVATE KEY` block is rejected.
-24. **Chain checks** (`ratify`)
-    - Build: for each cert *i*: issuer equals the subject of *i−1*, `CheckSignatureFrom` passes, parents are CA with keyCertSign, no cert is self-issued, no unknown critical extensions, and `policyConstraints` / `inhibitAnyPolicy` are absent.
-    - Learn: basic path processing (RFC 5280 §6.1.3 a–c, §6.1.4 k–n); why name chaining and signatures are separate checks; what a relying party must do with a critical extension it does not understand.
-    - Done when: a mutation table test (flip a signature byte, swap two certs, clear `IsCA`, add an unknown critical extension) gives `E-TAMPERED` or the specific chain error for each.
+24. **Ordering and chain checks** (`ratify`)
+    - Build: `Order`, which finds the anchor (the only self-issued cert) and follows issuer links to put every cert at its depth, rejecting a missing anchor, forks, gaps and unrelated certs (`E-CHAIN`); then for each cert *i*: `CheckSignatureFrom` passes (`E-TAMPERED`), parents are CA with keyCertSign, no cert but the anchor is self-issued, no unknown critical extensions, and `policyConstraints` / `inhibitAnyPolicy` are absent (`E-CHAIN`).
+    - Learn: basic path processing (RFC 5280 §6.1.3 a–c, §6.1.4 k–n); why name chaining and signatures are separate checks; how a chain's order is recoverable from the certs themselves; what a relying party must do with a critical extension it does not understand.
+    - Done when: a mutation table test (flip a signature byte, change a signed byte, clear `IsCA`, add an unknown critical extension, drop a depth, duplicate a cert, add a foreign cert) gives `E-TAMPERED` or `E-CHAIN` for each, and a shuffled file ratifies exactly like the ordered one.
 25. **Validity windows** (`ratify`)
     - Build: check every cert's `NotBefore`/`NotAfter` against the check time; the `-at` flag; `E-NOT-IN-FORCE` and `E-LAPSED`.
     - Learn: why validity is per certificate, so a chain's lifetime is the overlap; UTCTime vs GeneralizedTime (RFC 5280 §4.1.2.5 switches encodings at 2050, which is why 9999-12-31 works).
diff --git a/ratify/chain.go b/ratify/chain.go
new file mode 100644
index 0000000000000000000000000000000000000000..2eefc79fc49cacf11e773d17ffe1451ca5fd6441
--- /dev/null
+++ b/ratify/chain.go
@@ -0,0 +1,61 @@
+package ratify
+
+import (
+	"crypto/x509"
+	"encoding/asn1"
+	"errors"
+)
+
+var (
+	oidPolicyConstraints = asn1.ObjectIdentifier{2, 5, 29, 36}
+	oidInhibitAnyPolicy  = asn1.ObjectIdentifier{2, 5, 29, 54}
+)
+
+// CheckChain checks a chain put in order by Order, the way RFC 5280 basic
+// path processing does, minus validity dates and policies, which have their
+// own steps. A depth is the cert's position: 0 is the anchor.
+func CheckChain(certs []*x509.Certificate) error {
+	for i, c := range certs {
+		parent := c
+		if i > 0 {
+			parent = certs[i-1]
+		}
+		// CheckSignatureFrom also checks that the parent is a CA allowed
+		// to sign certs, which is the other half of a valid link.
+		if err := c.CheckSignatureFrom(parent); err != nil {
+			var constraint x509.ConstraintViolationError
+			if errors.As(err, &constraint) {
+				return errorf(ErrChain, "depth %d: %s may not sign certificates (it must be a CA with keyCertSign)", i, name(parent))
+			}
+			if i == 0 {
+				return errorf(ErrTampered, "the trust anchor fails its own signature check: %v", err)
+			}
+			return errorf(ErrTampered, "clause at depth %d fails signature check: %v", i, err)
+		}
+		if err := checkExtensions(i, c); err != nil {
+			return err
+		}
+	}
+	return nil
+}
+
+// checkExtensions rejects what GOVERNMENT does not process. A relying party
+// that meets a critical extension it does not understand must refuse the
+// cert, because the issuer marked it as changing the cert's meaning.
+// policyConstraints and inhibitAnyPolicy are understood but not allowed:
+// both would make policy processing drop or forbid nodes, and v1 keeps
+// those counters out of the picture.
+func checkExtensions(depth int, c *x509.Certificate) error {
+	if len(c.UnhandledCriticalExtensions) > 0 {
+		return errorf(ErrChain, "depth %d: unknown critical extension %v", depth, c.UnhandledCriticalExtensions[0])
+	}
+	for _, ext := range c.Extensions {
+		switch {
+		case ext.Id.Equal(oidPolicyConstraints):
+			return errorf(ErrChain, "depth %d: policyConstraints is not allowed", depth)
+		case ext.Id.Equal(oidInhibitAnyPolicy):
+			return errorf(ErrChain, "depth %d: inhibitAnyPolicy is not allowed; certs 2..n depend on anyPolicy", depth)
+		}
+	}
+	return nil
+}
diff --git a/ratify/chain_test.go b/ratify/chain_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..ef721faaf57d8f63f84098a3a89db5af3448e726
--- /dev/null
+++ b/ratify/chain_test.go
@@ -0,0 +1,199 @@
+package ratify
+
+import (
+	"bytes"
+	"crypto/ed25519"
+	"crypto/sha256"
+	"crypto/x509"
+	"crypto/x509/pkix"
+	"encoding/asn1"
+	"errors"
+	"fmt"
+	"math/big"
+	"math/rand"
+	"strings"
+	"testing"
+	"time"
+
+	"government/lisp2gov"
+)
+
+// testChain builds an anchor plus n certs shaped like the compiler's, and
+// lets a test change any template before it is signed. Mutations that need
+// a valid signature (clearing IsCA, adding an extension) go through here;
+// byte flips after signing are done on the finished DER.
+func testChain(t *testing.T, n int, mutate func(depth int, tmpl *x509.Certificate)) []*x509.Certificate {
+	t.Helper()
+	key := func(depth int) ed25519.PrivateKey {
+		seed := sha256.Sum256([]byte(fmt.Sprint("ratify test ", depth)))
+		return ed25519.NewKeyFromSeed(seed[:])
+	}
+	var certs []*x509.Certificate
+	for d := 0; d <= n; d++ {
+		tmpl := &x509.Certificate{
+			SerialNumber:          big.NewInt(int64(d + 1)),
+			Subject:               pkix.Name{CommonName: fmt.Sprintf("Depth %d", d), Organization: []string{"test"}},
+			NotBefore:             time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC),
+			NotAfter:              time.Date(9999, 12, 31, 23, 59, 59, 0, time.UTC),
+			BasicConstraintsValid: true,
+			IsCA:                  d < n,
+			KeyUsage:              x509.KeyUsageCertSign | x509.KeyUsageCRLSign,
+		}
+		if d == n {
+			tmpl.KeyUsage = x509.KeyUsageDigitalSignature
+		}
+		if mutate != nil {
+			mutate(d, tmpl)
+		}
+		parent, signer := tmpl, key(d)
+		if d > 0 {
+			parent, signer = certs[d-1], key(d-1)
+		}
+		der, err := x509.CreateCertificate(nil, tmpl, parent, key(d).Public(), signer)
+		if err != nil {
+			t.Fatalf("depth %d: %v", d, err)
+		}
+		c, err := x509.ParseCertificate(der)
+		if err != nil {
+			t.Fatal(err)
+		}
+		certs = append(certs, c)
+	}
+	return certs
+}
+
+// ratifyChain runs both steps on certs in the order given.
+func ratifyChain(certs []*x509.Certificate) error {
+	ordered, err := Order(certs)
+	if err != nil {
+		return err
+	}
+	return CheckChain(ordered)
+}
+
+func reparse(t *testing.T, der []byte) *x509.Certificate {
+	t.Helper()
+	c, err := x509.ParseCertificate(der)
+	if err != nil {
+		t.Fatalf("mutated cert no longer parses: %v", err)
+	}
+	return c
+}
+
+// flipByte returns c with the last byte of field inverted in its DER, so
+// the mutation lands in the part of the cert the test means.
+func flipByte(t *testing.T, c *x509.Certificate, field []byte) *x509.Certificate {
+	t.Helper()
+	i := bytes.Index(c.Raw, field)
+	if i < 0 {
+		t.Fatal("field not found in DER")
+	}
+	der := bytes.Clone(c.Raw)
+	der[i+len(field)-1] ^= 0xff
+	return reparse(t, der)
+}
+
+func compiledChain(t *testing.T, src string) []*x509.Certificate {
+	t.Helper()
+	out, err := lisp2gov.Compile(src, lisp2gov.Options{})
+	if err != nil {
+		t.Fatal(err)
+	}
+	certs, err := Load(out)
+	if err != nil {
+		t.Fatal(err)
+	}
+	return certs
+}
+
+func TestCompiledProgramsPass(t *testing.T) {
+	for _, src := range []string{"42", "(+ 1 2)", "(+ 1 (* 2 3))", "1 (a (b (c)))"} {
+		if err := ratifyChain(compiledChain(t, src)); err != nil {
+			t.Errorf("%s: %v", src, err)
+		}
+	}
+}
+
+func TestOrderIgnoresFileOrder(t *testing.T) {
+	certs := compiledChain(t, "1 (a (b (c (d))))")
+	r := rand.New(rand.NewSource(1))
+	for trial := 0; trial < 20; trial++ {
+		shuffled := append([]*x509.Certificate(nil), certs...)
+		r.Shuffle(len(shuffled), func(i, j int) { shuffled[i], shuffled[j] = shuffled[j], shuffled[i] })
+		ordered, err := Order(shuffled)
+		if err != nil {
+			t.Fatal(err)
+		}
+		for i := range certs {
+			if ordered[i] != certs[i] {
+				t.Fatalf("trial %d: depth %d is %s, want %s", trial, i, name(ordered[i]), name(certs[i]))
+			}
+		}
+		if err := CheckChain(ordered); err != nil {
+			t.Fatal(err)
+		}
+	}
+}
+
+func TestMutations(t *testing.T) {
+	base := testChain(t, 3, nil)
+	other := testChain(t, 1, func(d int, tmpl *x509.Certificate) {
+		tmpl.Subject.Organization = []string{"another program"}
+	})
+	unknownExt := pkix.Extension{Id: asn1.ObjectIdentifier{1, 2, 3, 4}, Critical: true, Value: []byte{0x05, 0x00}}
+	policyConstraints := pkix.Extension{Id: oidPolicyConstraints, Critical: true, Value: []byte{0x30, 0x03, 0x80, 0x01, 0x00}}
+	inhibitAny := pkix.Extension{Id: oidInhibitAnyPolicy, Critical: true, Value: []byte{0x02, 0x01, 0x00}}
+
+	with := func(depth int, f func(*x509.Certificate)) []*x509.Certificate {
+		return testChain(t, 3, func(d int, tmpl *x509.Certificate) {
+			if d == depth {
+				f(tmpl)
+			}
+		})
+	}
+	replace := func(certs []*x509.Certificate, i int, c *x509.Certificate) []*x509.Certificate {
+		out := append([]*x509.Certificate(nil), certs...)
+		out[i] = c
+		return out
+	}
+	without := func(certs []*x509.Certificate, i int) []*x509.Certificate {
+		return append(append([]*x509.Certificate(nil), certs[:i]...), certs[i+1:]...)
+	}
+
+	tests := []struct {
+		name  string
+		certs []*x509.Certificate
+		code  string
+		msg   string
+	}{
+		{"flip a signature byte", replace(base, 2, flipByte(t, base[2], base[2].Signature)), ErrTampered, "depth 2 fails signature"},
+		{"change a signed byte", replace(base, 2, flipByte(t, base[2], base[2].SubjectKeyId)), ErrTampered, "depth 2 fails signature"},
+		{"tamper with the anchor", replace(base, 0, flipByte(t, base[0], base[0].Signature)), ErrTampered, "trust anchor fails"},
+		{"clear IsCA", with(1, func(c *x509.Certificate) { c.IsCA = false }), ErrChain, "depth 2: CN=Depth 1,O=test may not sign"},
+		{"drop keyCertSign", with(2, func(c *x509.Certificate) { c.KeyUsage = x509.KeyUsageDigitalSignature }), ErrChain, "depth 3: CN=Depth 2,O=test may not sign"},
+		{"unknown critical extension", with(2, func(c *x509.Certificate) { c.ExtraExtensions = []pkix.Extension{unknownExt} }), ErrChain, "depth 2: unknown critical extension 1.2.3.4"},
+		{"policyConstraints", with(1, func(c *x509.Certificate) { c.ExtraExtensions = []pkix.Extension{policyConstraints} }), ErrChain, "depth 1: policyConstraints"},
+		{"inhibitAnyPolicy", with(1, func(c *x509.Certificate) { c.ExtraExtensions = []pkix.Extension{inhibitAny} }), ErrChain, "depth 1: inhibitAnyPolicy"},
+		{"self-issued cert in the path", with(2, func(c *x509.Certificate) { c.Subject = base[1].Subject }), ErrChain, "two self-issued certs (CN=Depth 0,O=test and CN=Depth 1,O=test)"},
+		{"drop a depth", without(base, 2), ErrChain, "CN=Depth 3,O=test was issued by CN=Depth 2,O=test, which is not in the file"},
+		{"duplicate a cert", append(append([]*x509.Certificate(nil), base...), base[2]), ErrChain, "two certs are named CN=Depth 2"},
+		{"foreign cert", append(append([]*x509.Certificate(nil), base...), other[1]), ErrChain, "issued by CN=Depth 0,O=another program, which is not in the file"},
+		{"foreign anchor only", append(append([]*x509.Certificate(nil), base...), other[0]), ErrChain, "two self-issued"},
+		{"no anchor", base[1:], ErrChain, "no trust anchor"},
+		{"two children of one parent", append(append([]*x509.Certificate(nil), base...), testChain(t, 1, func(d int, tmpl *x509.Certificate) {
+			if d == 1 {
+				tmpl.Subject.CommonName = "Depth 1 again"
+			}
+		})[1]), ErrChain, "both claim"},
+	}
+	for _, tt := range tests {
+		err := ratifyChain(tt.certs)
+		var e *Error
+		if !errors.As(err, &e) || e.Code != tt.code || !strings.Contains(e.Msg, tt.msg) {
+			t.Errorf("%s: error = %v, want %s containing %q", tt.name, err, tt.code, tt.msg)
+		}
+	}
+	if err := ratifyChain(base); err != nil {
+		t.Errorf("the unmutated chain fails: %v", err)
+	}
+}
diff --git a/ratify/doc.go b/ratify/doc.go
new file mode 100644
index 0000000000000000000000000000000000000000..969f414c49a29c17277aaa24ee80e23ad28864ea
--- /dev/null
+++ b/ratify/doc.go
@@ -0,0 +1,4 @@
+// Package ratify decides whether a .gov file may run: it loads the
+// certificates and checks the chain the way RFC 5280 path validation does,
+// up to but not including policy processing.
+package ratify
diff --git a/ratify/error.go b/ratify/error.go
new file mode 100644
index 0000000000000000000000000000000000000000..89cc43a4931a749575bf62cf71ad870cfa0ee2a2
--- /dev/null
+++ b/ratify/error.go
@@ -0,0 +1,25 @@
+package ratify
+
+import "fmt"
+
+// Ratification error codes. Every ratification failure exits with code 2.
+const (
+	// ErrMalformed: the file is not a readable certificate chain.
+	ErrMalformed = "E-MALFORMED"
+	// ErrChain: the certificates do not form one valid path from the
+	// anchor down.
+	ErrChain = "E-CHAIN"
+	// ErrTampered: a signature does not match the bytes it covers.
+	ErrTampered = "E-TAMPERED"
+)
+
+type Error struct {
+	Code string
+	Msg  string
+}
+
+func (e *Error) Error() string { return e.Code + ": " + e.Msg }
+
+func errorf(code, format string, args ...any) *Error {
+	return &Error{Code: code, Msg: fmt.Sprintf(format, args...)}
+}
diff --git a/ratify/load.go b/ratify/load.go
new file mode 100644
index 0000000000000000000000000000000000000000..8a8aff03435c7ab0eff7d4bfedc4adfe3ba5316e
--- /dev/null
+++ b/ratify/load.go
@@ -0,0 +1,50 @@
+package ratify
+
+import (
+	"crypto/x509"
+	"encoding/pem"
+	"regexp"
+)
+
+// beginLine matches the start of a PEM block: "-----BEGIN " at the start of
+// a line. pem.Decode silently skips a block it cannot decode and goes on to
+// the next one, which for a program would mean silently losing a depth, so
+// Load counts these lines and insists every one became a block.
+var beginLine = regexp.MustCompile(`(?m)^-----BEGIN `)
+
+// Load reads a .gov file into its certificates, anchor first. Text outside
+// PEM blocks is ignored, as PEM allows; that is where `government compile
+// -source` puts the Lisp source. The text is never trusted: what counts is
+// the DER inside each block, which is what the signatures cover.
+func Load(data []byte) ([]*x509.Certificate, error) {
+	var certs []*x509.Certificate
+	rest := data
+	for {
+		var block *pem.Block
+		block, rest = pem.Decode(rest)
+		if block == nil {
+			break
+		}
+		n := len(certs)
+		if block.Type != "CERTIFICATE" {
+			return nil, errorf(ErrMalformed, "block %d is a %s, not a CERTIFICATE", n, block.Type)
+		}
+		if len(block.Headers) > 0 {
+			return nil, errorf(ErrMalformed, "block %d has PEM headers; a certificate block has none", n)
+		}
+		cert, err := x509.ParseCertificate(block.Bytes)
+		if err != nil {
+			return nil, errorf(ErrMalformed, "block %d: %v", n, err)
+		}
+		certs = append(certs, cert)
+	}
+
+	if found := len(beginLine.FindAll(data, -1)); found != len(certs) {
+		return nil, errorf(ErrMalformed, "%d PEM blocks begin but only %d could be read", found, len(certs))
+	}
+	if len(certs) < 2 {
+		// A program needs a trust anchor and at least one depth.
+		return nil, errorf(ErrMalformed, "%d certificates; a program needs an anchor and at least one more", len(certs))
+	}
+	return certs, nil
+}
diff --git a/ratify/load_test.go b/ratify/load_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..303e8da75ef240768491b9088759c6941fec63ea
--- /dev/null
+++ b/ratify/load_test.go
@@ -0,0 +1,139 @@
+package ratify
+
+import (
+	"bytes"
+	"crypto/ed25519"
+	"crypto/x509"
+	"encoding/base64"
+	"encoding/pem"
+	"errors"
+	"os"
+	"path/filepath"
+	"strings"
+	"testing"
+
+	"government/lisp2gov"
+)
+
+func compile(t *testing.T, src string, opts lisp2gov.Options) []byte {
+	t.Helper()
+	out, err := lisp2gov.Compile(src, opts)
+	if err != nil {
+		t.Fatal(err)
+	}
+	return out
+}
+
+func wantMalformed(t *testing.T, name string, data []byte, msg string) {
+	t.Helper()
+	_, err := Load(data)
+	var e *Error
+	if !errors.As(err, &e) || e.Code != ErrMalformed || !strings.Contains(e.Msg, msg) {
+		t.Errorf("%s: error = %v, want %s containing %q", name, err, ErrMalformed, msg)
+	}
+}
+
+func TestLoadCompiledPrograms(t *testing.T) {
+	files, _ := filepath.Glob("../testdata/*.gov.lisp")
+	files = append(files, "../examples/sq.gov.lisp")
+	for _, file := range files {
+		src, err := os.ReadFile(file)
+		if err != nil {
+			t.Fatal(err)
+		}
+		for _, withSource := range []bool{false, true} {
+			data := compile(t, string(src), lisp2gov.Options{IncludeSource: withSource})
+			certs, err := Load(data)
+			if err != nil {
+				t.Errorf("%s (source %v): %v", file, withSource, err)
+				continue
+			}
+			if want := bytes.Count(data, []byte("-----BEGIN CERTIFICATE-----")); len(certs) != want {
+				t.Errorf("%s: %d certs, want %d", file, len(certs), want)
+			}
+		}
+	}
+}
+
+func TestLoadIgnoresTextBetweenBlocks(t *testing.T) {
+	data := compile(t, "(+ 1 2)", lisp2gov.Options{})
+	commented := "a comment before\n" + strings.ReplaceAll(string(data), "-----END CERTIFICATE-----\n", "-----END CERTIFICATE-----\nand one after each block\n")
+	a, err := Load(data)
+	if err != nil {
+		t.Fatal(err)
+	}
+	b, err := Load([]byte(commented))
+	if err != nil {
+		t.Fatal(err)
+	}
+	for i := range a {
+		if !bytes.Equal(a[i].Raw, b[i].Raw) {
+			t.Errorf("cert %d differs", i)
+		}
+	}
+}
+
+// TestLoadReadsDERNotText re-wraps every block's base64 at a different line
+// width. The text changes, the DER does not, so the same certs load and
+// the signatures still check: they cover the DER, not the PEM text.
+func TestLoadReadsDERNotText(t *testing.T) {
+	data := compile(t, "(+ 1 2)", lisp2gov.Options{})
+	orig, err := Load(data)
+	if err != nil {
+		t.Fatal(err)
+	}
+	var rewrapped bytes.Buffer
+	for _, c := range orig {
+		b64 := base64.StdEncoding.EncodeToString(c.Raw)
+		rewrapped.WriteString("-----BEGIN CERTIFICATE-----\n")
+		for len(b64) > 40 {
+			rewrapped.WriteString(b64[:40] + "\n")
+			b64 = b64[40:]
+		}
+		rewrapped.WriteString(b64 + "\n-----END CERTIFICATE-----\n")
+	}
+	if bytes.Equal(rewrapped.Bytes(), data) {
+		t.Fatal("rewrapping did not change the text")
+	}
+	certs, err := Load(rewrapped.Bytes())
+	if err != nil {
+		t.Fatal(err)
+	}
+	for i := 1; i < len(certs); i++ {
+		if err := certs[i].CheckSignatureFrom(certs[i-1]); err != nil {
+			t.Errorf("cert %d: %v", i, err)
+		}
+	}
+}
+
+func TestLoadRejects(t *testing.T) {
+	good := compile(t, "(+ 1 2)", lisp2gov.Options{})
+	blocks := strings.SplitAfter(string(good), "-----END CERTIFICATE-----\n")
+	blocks = blocks[:len(blocks)-1]
+
+	_, key, _ := ed25519.GenerateKey(nil)
+	pkcs8, _ := x509.MarshalPKCS8PrivateKey(key)
+	keyBlock := string(pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: pkcs8}))
+
+	brokenMiddle := blocks[0] + strings.Replace(blocks[1], "M", "!", 1) + blocks[2]
+	withHeaders := strings.Replace(string(good), "-----BEGIN CERTIFICATE-----\n", "-----BEGIN CERTIFICATE-----\nProc-Type: 4,ENCRYPTED\n\n", 1)
+	badDER := string(pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: []byte{0x30, 0x03, 1, 2, 3}}))
+
+	tests := []struct {
+		name string
+		data string
+		msg  string
+	}{
+		{"private key block", string(good) + keyBlock, "is a PRIVATE KEY"},
+		{"private key first", keyBlock + string(good), "block 0 is a PRIVATE KEY"},
+		{"only the anchor", blocks[0], "1 certificates"},
+		{"empty file", "", "0 certificates"},
+		{"text only", "(+ 1 2)\n", "0 certificates"},
+		{"corrupt base64 in the middle", brokenMiddle, "3 PEM blocks begin but only 2"},
+		{"PEM headers", withHeaders, "has PEM headers"},
+		{"not a certificate inside", blocks[0] + badDER, "block 1:"},
+	}
+	for _, tt := range tests {
+		wantMalformed(t, tt.name, []byte(tt.data), tt.msg)
+	}
+}
diff --git a/ratify/order.go b/ratify/order.go
new file mode 100644
index 0000000000000000000000000000000000000000..55cb6abe323582a96c9109486d719e6752adda56
--- /dev/null
+++ b/ratify/order.go
@@ -0,0 +1,77 @@
+package ratify
+
+import (
+	"bytes"
+	"crypto/x509"
+	"slices"
+)
+
+// Order puts certs in depth order, anchor first, whatever order the file
+// had them in. The anchor is the one self-issued cert; from it, each cert's
+// child is the one cert whose issuer is its subject. This relies only on
+// names, so CheckChain must still verify that every link is signed: a
+// forged link would name the right parent but fail its signature.
+//
+// Only the anchor may be self-issued. RFC 5280's policy_mapping counter
+// skips self-issued certs, so one in the path would make a cert's depth
+// differ from its position.
+func Order(certs []*x509.Certificate) ([]*x509.Certificate, error) {
+	var anchor *x509.Certificate
+	for _, c := range certs {
+		if !selfIssued(c) {
+			continue
+		}
+		if anchor != nil {
+			return nil, errorf(ErrChain, "two self-issued certs (%s and %s); only the trust anchor may be one", name(anchor), name(c))
+		}
+		anchor = c
+	}
+	if anchor == nil {
+		return nil, errorf(ErrChain, "no trust anchor: no cert is self-issued")
+	}
+
+	// childOf maps a parent's subject to the cert it issued.
+	childOf := map[string]*x509.Certificate{}
+	subjects := map[string]bool{}
+	for _, c := range certs {
+		if subjects[string(c.RawSubject)] {
+			return nil, errorf(ErrChain, "two certs are named %s", name(c))
+		}
+		subjects[string(c.RawSubject)] = true
+		if c == anchor {
+			continue
+		}
+		if other, ok := childOf[string(c.RawIssuer)]; ok {
+			return nil, errorf(ErrChain, "%s and %s both claim %s as their issuer; a program is a single path", name(other), name(c), c.Issuer)
+		}
+		childOf[string(c.RawIssuer)] = c
+	}
+
+	ordered := []*x509.Certificate{anchor}
+	for last := anchor; ; {
+		next, ok := childOf[string(last.RawSubject)]
+		if !ok {
+			break
+		}
+		ordered = append(ordered, next)
+		last = next
+	}
+	for _, c := range certs {
+		if slices.Contains(ordered, c) {
+			continue
+		}
+		if !subjects[string(c.RawIssuer)] {
+			return nil, errorf(ErrChain, "%s was issued by %s, which is not in the file; a depth is missing", name(c), c.Issuer)
+		}
+		return nil, errorf(ErrChain, "%s is not on the path from the trust anchor", name(c))
+	}
+	return ordered, nil
+}
+
+func selfIssued(c *x509.Certificate) bool {
+	return bytes.Equal(c.RawIssuer, c.RawSubject)
+}
+
+func name(c *x509.Certificate) string {
+	return c.Subject.String()
+}