parent:
f98307e213f9f3c11b00c8edc3c367c315b9819a
nmyk <nick@nmyk.io>
2026-11-14T17:02:07-05:00
ratify: add trust anchor check
diff --git a/DESIGN.md b/DESIGN.md
index 91a0fc34905f28667fdff91e8c98e3d335c362a1..fadae80f2ad29f0c9a68cfa1d8263eb3ed0a2b66 100644
--- a/DESIGN.md
+++ b/DESIGN.md
@@ -309,7 +309,7 @@ | `gov2lisp` | Decompiler: AST back to Lisp text |
### Ratification steps
-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.
+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 (else `E-FOREIGN`).
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`).
diff --git a/cmd/government/anchor.go b/cmd/government/anchor.go
new file mode 100644
index 0000000000000000000000000000000000000000..4540145e2c288a7699fd2753da47e5d976c55e0b
--- /dev/null
+++ b/cmd/government/anchor.go
@@ -0,0 +1,45 @@
+package main
+
+import (
+ "flag"
+ "os"
+
+ "government/ratify"
+)
+
+// anchorFlag is -anchor, shared by run and verify: a file holding the only
+// key a program's anchor may have. It accepts a public key PEM, a cert, or
+// another .gov file ratified by the same author.
+type anchorFlag struct {
+ path string
+ pin ratify.Pin
+}
+
+func addAnchorFlag(fs *flag.FlagSet) *anchorFlag {
+ a := &anchorFlag{}
+ fs.Var(a, "anchor", "only accept programs whose anchor key matches the one in `file` (a public key, cert or .gov)")
+ return a
+}
+
+func (a *anchorFlag) String() string {
+ if a == nil {
+ return ""
+ }
+ return a.path
+}
+
+func (a *anchorFlag) Set(path string) error {
+ data, err := os.ReadFile(path)
+ if err != nil {
+ return err
+ }
+ pin, err := ratify.LoadPin(data)
+ if err != nil {
+ return err
+ }
+ a.path, a.pin = path, pin
+ return nil
+}
+
+// Pin is nil when -anchor was not given.
+func (a *anchorFlag) Pin() ratify.Pin { return a.pin }
diff --git a/cmd/government/anchor_test.go b/cmd/government/anchor_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..1a75b6494a700496395d215e10e06630bd823c83
--- /dev/null
+++ b/cmd/government/anchor_test.go
@@ -0,0 +1,51 @@
+package main
+
+import (
+ "flag"
+ "io"
+ "os"
+ "path/filepath"
+ "testing"
+
+ "government/lisp2gov"
+ "government/ratify"
+)
+
+func TestAnchorFlag(t *testing.T) {
+ dir := t.TempDir()
+ prog := filepath.Join(dir, "p.gov")
+ out, err := lisp2gov.Compile("(+ 1 2)", lisp2gov.Options{})
+ if err != nil {
+ t.Fatal(err)
+ }
+ os.WriteFile(prog, out, 0o644)
+ junk := filepath.Join(dir, "junk.txt")
+ os.WriteFile(junk, []byte("not a key"), 0o644)
+
+ parse := func(args ...string) (*anchorFlag, error) {
+ fs := flag.NewFlagSet("test", flag.ContinueOnError)
+ fs.SetOutput(io.Discard)
+ a := addAnchorFlag(fs)
+ return a, fs.Parse(args)
+ }
+
+ a, err := parse()
+ if err != nil || a.Pin() != nil {
+ t.Errorf("no -anchor: pin %v, err %v; want none", a.Pin(), err)
+ }
+
+ a, err = parse("-anchor", prog)
+ if err != nil {
+ t.Fatal(err)
+ }
+ certs, _ := ratify.Load(out)
+ if err := ratify.CheckPin(certs[0], a.Pin()); err != nil {
+ t.Errorf("pin from the program itself: %v", err)
+ }
+
+ for _, bad := range []string{junk, filepath.Join(dir, "missing.pem")} {
+ if _, err := parse("-anchor", bad); err == nil {
+ t.Errorf("-anchor %s accepted", bad)
+ }
+ }
+}
diff --git a/ratify/anchor.go b/ratify/anchor.go
new file mode 100644
index 0000000000000000000000000000000000000000..692b6cd3744e0bdc4211665dbc90f4d6ff545b92
--- /dev/null
+++ b/ratify/anchor.go
@@ -0,0 +1,78 @@
+package ratify
+
+import (
+ "bytes"
+ "crypto/sha256"
+ "crypto/x509"
+ "encoding/hex"
+ "encoding/pem"
+ "fmt"
+)
+
+// Pin is a trusted public key, as DER-encoded SubjectPublicKeyInfo.
+//
+// A trust anchor is really a key, not a certificate: what makes the anchor
+// cert trustworthy is only that its key is one you already trust. So a pin
+// names the key alone, and survives re-ratification: a program recompiled
+// with new dates or text gets a new anchor cert but keeps its author's key.
+type Pin []byte
+
+// LoadPin reads a pin from PEM: a PUBLIC KEY block, a single CERTIFICATE,
+// or a whole .gov file, whose anchor's key is used.
+func LoadPin(data []byte) (Pin, error) {
+ block, _ := pem.Decode(data)
+ if block == nil {
+ return nil, fmt.Errorf("no PEM block found")
+ }
+ switch block.Type {
+ case "PUBLIC KEY":
+ key, err := x509.ParsePKIXPublicKey(block.Bytes)
+ if err != nil {
+ return nil, err
+ }
+ return marshalKey(key)
+ case "CERTIFICATE":
+ if len(beginLine.FindAll(data, -1)) == 1 {
+ cert, err := x509.ParseCertificate(block.Bytes)
+ if err != nil {
+ return nil, err
+ }
+ return Pin(cert.RawSubjectPublicKeyInfo), nil
+ }
+ certs, err := Load(data)
+ if err != nil {
+ return nil, err
+ }
+ ordered, err := Order(certs)
+ if err != nil {
+ return nil, err
+ }
+ return Pin(ordered[0].RawSubjectPublicKeyInfo), nil
+ }
+ return nil, fmt.Errorf("a %s block cannot be a pin; want PUBLIC KEY or CERTIFICATE", block.Type)
+}
+
+// marshalKey re-encodes a parsed key, so a pin is always in the same DER
+// form Go writes into certificates, whatever tool produced the PEM.
+func marshalKey(key any) (Pin, error) {
+ der, err := x509.MarshalPKIXPublicKey(key)
+ if err != nil {
+ return nil, err
+ }
+ return Pin(der), nil
+}
+
+// Fingerprint is the SHA-256 of the key's SubjectPublicKeyInfo, the usual
+// way to name a key in a sentence.
+func Fingerprint(spki []byte) string {
+ sum := sha256.Sum256(spki)
+ return hex.EncodeToString(sum[:])
+}
+
+// CheckPin checks that the anchor's key is the pinned one.
+func CheckPin(anchor *x509.Certificate, pin Pin) error {
+ if bytes.Equal(anchor.RawSubjectPublicKeyInfo, pin) {
+ return nil
+ }
+ return errorf(ErrForeign, "ratified by key %s, not the pinned key %s", Fingerprint(anchor.RawSubjectPublicKeyInfo), Fingerprint(pin))
+}
diff --git a/ratify/anchor_test.go b/ratify/anchor_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..ec7fc6133537db09d7775a5fac9b353d1c33293e
--- /dev/null
+++ b/ratify/anchor_test.go
@@ -0,0 +1,126 @@
+package ratify
+
+import (
+ "crypto/x509"
+ "encoding/pem"
+ "testing"
+ "time"
+
+ "government/lisp2gov"
+)
+
+func pemOf(typ string, der []byte) []byte {
+ return pem.EncodeToMemory(&pem.Block{Type: typ, Bytes: der})
+}
+
+func encodeChain(certs []*x509.Certificate) []byte {
+ var out []byte
+ for _, c := range certs {
+ out = append(out, pemOf("CERTIFICATE", c.Raw)...)
+ }
+ return out
+}
+
+func mustPin(t *testing.T, data []byte) Pin {
+ t.Helper()
+ pin, err := LoadPin(data)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return pin
+}
+
+func TestPinSurvivesReratification(t *testing.T) {
+ // Same keys, different dates and a different program: a new anchor
+ // cert, but the same anchor key.
+ v1 := testChain(t, 2, nil)
+ v2 := testChain(t, 3, func(d int, tmpl *x509.Certificate) {
+ tmpl.NotBefore = time.Date(2030, 1, 1, 0, 0, 0, 0, time.UTC)
+ tmpl.Subject.Organization = []string{"amended"}
+ })
+ if string(v1[0].Raw) == string(v2[0].Raw) {
+ t.Fatal("the two anchors are the same cert")
+ }
+ for name, pin := range map[string]Pin{
+ "anchor cert": mustPin(t, pemOf("CERTIFICATE", v1[0].Raw)),
+ "public key": mustPin(t, pemOf("PUBLIC KEY", v1[0].RawSubjectPublicKeyInfo)),
+ "whole .gov": mustPin(t, encodeChain(v1)),
+ "shuffled .gov": mustPin(t, encodeChain([]*x509.Certificate{v1[2], v1[0], v1[1]})),
+ } {
+ if err := CheckPin(v2[0], pin); err != nil {
+ t.Errorf("pin from %s: %v", name, err)
+ }
+ }
+}
+
+func TestPinRejectsAnotherSeed(t *testing.T) {
+ seed := [32]byte{42}
+ mine, err := lisp2gov.Compile("(+ 1 2)", lisp2gov.Options{})
+ if err != nil {
+ t.Fatal(err)
+ }
+ theirs, err := lisp2gov.Compile("(+ 1 2)", lisp2gov.Options{Seed: &seed})
+ if err != nil {
+ t.Fatal(err)
+ }
+ pin := mustPin(t, mine)
+ certs, err := Load(theirs)
+ if err != nil {
+ t.Fatal(err)
+ }
+ checkCode(t, "another seed", CheckPin(certs[0], pin), ErrForeign, "not the pinned key "+Fingerprint(pin))
+}
+
+func TestLoadPinRejects(t *testing.T) {
+ for name, data := range map[string][]byte{
+ "empty": nil,
+ "not PEM": []byte("hello"),
+ "private key": pemOf("PRIVATE KEY", []byte{1, 2, 3}),
+ "bad key": pemOf("PUBLIC KEY", []byte{1, 2, 3}),
+ "bad cert": pemOf("CERTIFICATE", []byte{1, 2, 3}),
+ } {
+ if _, err := LoadPin(data); err == nil {
+ t.Errorf("%s: accepted as a pin", name)
+ }
+ }
+}
+
+// TestRatify is Phase 4's milestone: a good program is accepted, and a
+// tampered, expired or foreign one is refused.
+func TestRatify(t *testing.T) {
+ good, err := lisp2gov.Compile("(define sq (lambda (x) (* x x))) (sq 12)", lisp2gov.Options{})
+ if err != nil {
+ t.Fatal(err)
+ }
+ now := time.Date(2026, 11, 14, 0, 0, 0, 0, time.UTC)
+ pin := mustPin(t, good)
+
+ certs, err := Ratify(good, Options{At: now, Pin: pin})
+ if err != nil {
+ t.Fatalf("good program: %v", err)
+ }
+ if len(certs) != 5 {
+ t.Errorf("%d certs, want 5", len(certs))
+ }
+
+ loaded, _ := Load(good)
+ tampered := append([]*x509.Certificate(nil), loaded...)
+ tampered[3] = flipByte(t, loaded[3], loaded[3].Signature)
+
+ seed := [32]byte{42}
+ foreign, err := lisp2gov.Compile("(define sq (lambda (x) (* x x))) (sq 12)", lisp2gov.Options{Seed: &seed})
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ checkCode(t, "tampered", ratifyErr(encodeChain(tampered), Options{At: now}), ErrTampered, "depth 3")
+ checkCode(t, "expired", ratifyErr(good, Options{At: time.Date(10000, 1, 1, 0, 0, 0, 0, time.UTC)}), ErrLapsed, "expired 9999-12-31T23:59:59Z")
+ checkCode(t, "not yet in force", ratifyErr(good, Options{At: time.Date(1999, 1, 1, 0, 0, 0, 0, time.UTC)}), ErrNotInForce, "takes effect 2000-01-01")
+ checkCode(t, "foreign", ratifyErr(foreign, Options{At: now, Pin: pin}), ErrForeign, "not the pinned key")
+ checkCode(t, "foreign without a pin", ratifyErr(foreign, Options{At: now}), "", "")
+}
+
+func ratifyErr(data []byte, opts Options) error {
+ _, err := Ratify(data, opts)
+ return err
+}
diff --git a/ratify/error.go b/ratify/error.go
index df70e89d416afe7a2d143a20a74882a6647ede72..0d3d03fc98d6031cd7f9f5ecaf683837af118e0d 100644
--- a/ratify/error.go
+++ b/ratify/error.go
@@ -15,6 +15,9 @@ // ErrNotInForce: the check time is before the program takes effect.
ErrNotInForce = "E-NOT-IN-FORCE"
// ErrLapsed: the check time is after the program expired.
ErrLapsed = "E-LAPSED"
+ // ErrForeign: the program is ratified by a key other than the pinned
+ // one.
+ ErrForeign = "E-FOREIGN"
)
type Error struct {
diff --git a/ratify/ratify.go b/ratify/ratify.go
new file mode 100644
index 0000000000000000000000000000000000000000..23b066a7edf8c5bdc45598621636cc653627764f
--- /dev/null
+++ b/ratify/ratify.go
@@ -0,0 +1,40 @@
+package ratify
+
+import (
+ "crypto/x509"
+ "time"
+)
+
+type Options struct {
+ // At is the time to check validity at.
+ At time.Time
+ // Pin, if set, is the only key the program's anchor may have. Without
+ // one, the anchor inside the file is trusted, so ratification checks
+ // that the program is internally consistent, not who wrote it.
+ Pin Pin
+}
+
+// Ratify loads a .gov file and runs every ratification check that comes
+// before policy processing. It returns the certs in depth order.
+func Ratify(data []byte, opts Options) ([]*x509.Certificate, error) {
+ certs, err := Load(data)
+ if err != nil {
+ return nil, err
+ }
+ certs, err = Order(certs)
+ if err != nil {
+ return nil, err
+ }
+ if opts.Pin != nil {
+ if err := CheckPin(certs[0], opts.Pin); err != nil {
+ return nil, err
+ }
+ }
+ if err := CheckChain(certs); err != nil {
+ return nil, err
+ }
+ if err := CheckValidity(certs, opts.At); err != nil {
+ return nil, err
+ }
+ return certs, nil
+}