parent:
21ba553f2ac9aed7435e6a7744c2a33c37c9dec8
nmyk <nick@nmyk.io>
2026-11-14T17:37:04-05:00
add government verify
diff --git a/cmd/government/main.go b/cmd/government/main.go
index cb9a709144b5d5e109ce15b20199f4ddfa92a9a0..476ed21345b83a5d9b17becb00f991094f74efc0 100644
--- a/cmd/government/main.go
+++ b/cmd/government/main.go
@@ -1,6 +1,6 @@
// Command government runs GOVERNMENT programs.
//
-// verify and repeal arrive in later steps of PLAN.md. The other subcommands arrive in later steps
+// repeal arrives in a later step of PLAN.md. The other subcommands arrive in later steps
// of PLAN.md.
package main
@@ -25,9 +25,9 @@ compile transpile Lisp source to .gov
run ratify, decode and evaluate a .gov program
tree print the policy tree
decompile print equivalent Lisp source
+ verify ratify and decode only, and print a certificate of ratification
not yet implemented:
- verify ratify and decode only
repeal write a CRL repealing one depth of a program
`
@@ -49,6 +49,8 @@ case "tree":
return tree(args[1:], stdout, stderr)
case "decompile":
return decompile(args[1:], stdout, stderr)
+ case "verify":
+ return verify(args[1:], stdout, stderr)
case "help", "-h", "-help", "--help":
fmt.Fprint(stdout, usage)
return exitOK
diff --git a/cmd/government/verify.go b/cmd/government/verify.go
new file mode 100644
index 0000000000000000000000000000000000000000..e59e4d6036ff6591436359c8d101b5fb58fbf5d1
--- /dev/null
+++ b/cmd/government/verify.go
@@ -0,0 +1,70 @@
+package main
+
+import (
+ "bytes"
+ "crypto/x509"
+ "flag"
+ "fmt"
+ "io"
+ "strings"
+ "time"
+
+ "government/lisp2gov"
+ "government/program"
+ "government/ratify"
+)
+
+// verify answers "is this program lawful?" without asking "what does it
+// do?": it runs every check run does, decodes the program, and stops
+// before evaluating anything.
+func verify(args []string, stdout, stderr io.Writer) int {
+ fs := flag.NewFlagSet("verify", flag.ContinueOnError)
+ fs.SetOutput(stderr)
+ lf := addLoadFlags(fs)
+ fs.Usage = func() {
+ fmt.Fprintln(stderr, "usage: government verify prog.gov [-at time] [-anchor file] [-max-nodes n]")
+ fs.PrintDefaults()
+ }
+ path, data, ok := oneFile(fs, args, stderr)
+ if !ok {
+ return exitInvalid
+ }
+ p, err := program.Load(data, lf.programOptions())
+ if err != nil {
+ fmt.Fprintf(stderr, "%s: %v\n", path, err)
+ return exitInvalid
+ }
+ fmt.Fprint(stdout, certificate(p))
+ return exitOK
+}
+
+// certificate is the certificate of ratification: who ratified the
+// program, by which key, when it is in force, and how big it is.
+func certificate(p *program.Program) string {
+ anchor := p.Certs[0]
+ author := anchor.Subject.CommonName
+ if names := anchor.EmailAddresses; len(names) > 0 {
+ author += " <" + names[0] + ">"
+ }
+ if isDefaultKey(anchor) {
+ // The default seed is public, so anyone could have made this.
+ author = "nobody in particular (default key)"
+ }
+ start, end, _, _ := ratify.Window(p.Certs)
+
+ var b strings.Builder
+ b.WriteString("CERTIFICATE OF RATIFICATION\n\n")
+ row := func(k, v string) { fmt.Fprintf(&b, " %-12s %s\n", k, v) }
+ row("Program", strings.Join(anchor.Subject.Organization, ", "))
+ row("Ratified by", author)
+ row("Key", "SHA-256 "+ratify.Fingerprint(anchor.RawSubjectPublicKeyInfo))
+ row("In force", start.UTC().Format(time.RFC3339)+" to "+end.UTC().Format(time.RFC3339))
+ row("Depth", fmt.Sprintf("%d (a trust anchor and %d more certificates)", p.Depth(), p.Depth()))
+ row("Nodes", fmt.Sprint(p.Nodes))
+ return b.String()
+}
+
+func isDefaultKey(anchor *x509.Certificate) bool {
+ want, err := x509.MarshalPKIXPublicKey(lisp2gov.DefaultAnchorKey())
+ return err == nil && bytes.Equal(anchor.RawSubjectPublicKeyInfo, want)
+}
diff --git a/cmd/government/verify_test.go b/cmd/government/verify_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..e77b70d9db4a5b9765736180b49809189d8f8b85
--- /dev/null
+++ b/cmd/government/verify_test.go
@@ -0,0 +1,125 @@
+package main
+
+import (
+ "encoding/pem"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "government/lisp2gov"
+)
+
+func TestVerifyPrintsCertificate(t *testing.T) {
+ gov := compileTo(t, t.TempDir(), "worked", "(+ 1 (* 2 3))")
+ code, stdout, stderr := runCmd("verify", gov)
+ if code != exitOK {
+ t.Fatalf("exit %d: %s", code, stderr)
+ }
+ for _, want := range []string{
+ "CERTIFICATE OF RATIFICATION",
+ "Program worked",
+ "Ratified by nobody in particular (default key)",
+ "Key SHA-256 ",
+ "In force 2000-01-01T00:00:00Z to 9999-12-31T23:59:59Z",
+ "Depth 3 ",
+ "Nodes 7\n",
+ } {
+ if !strings.Contains(stdout, want) {
+ t.Errorf("missing %q in\n%s", want, stdout)
+ }
+ }
+}
+
+func TestVerifyNamesARealAuthor(t *testing.T) {
+ seed := [32]byte{7}
+ data, err := lisp2gov.Compile("1", lisp2gov.Options{Name: "mine", Seed: &seed})
+ if err != nil {
+ t.Fatal(err)
+ }
+ gov := filepath.Join(t.TempDir(), "mine.gov")
+ os.WriteFile(gov, data, 0o644)
+ _, stdout, _ := runCmd("verify", gov)
+ if !strings.Contains(stdout, "Ratified by GOVERNMENT Anchor\n") {
+ t.Errorf("a program from its own seed is not reported by its anchor:\n%s", stdout)
+ }
+}
+
+// pemBlocks splits a .gov file into its DER blocks.
+func pemBlocks(t *testing.T, path string) [][]byte {
+ t.Helper()
+ data, err := os.ReadFile(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var out [][]byte
+ for {
+ var b *pem.Block
+ b, data = pem.Decode(data)
+ if b == nil {
+ return out
+ }
+ out = append(out, b.Bytes)
+ }
+}
+
+func writeBlocks(t *testing.T, dir, name string, blocks [][]byte, typ ...string) string {
+ t.Helper()
+ var out []byte
+ for i, der := range blocks {
+ ty := "CERTIFICATE"
+ if i < len(typ) && typ[i] != "" {
+ ty = typ[i]
+ }
+ out = append(out, pem.EncodeToMemory(&pem.Block{Type: ty, Bytes: der})...)
+ }
+ path := filepath.Join(dir, name+".gov")
+ os.WriteFile(path, out, 0o644)
+ return path
+}
+
+// TestVerifyRefusesPhase4Mutations runs the Phase 4 failure cases through
+// the command: each one exits 2 and names its error. Mutations that need a
+// re-signed cert (clearing IsCA, adding a critical extension) are in
+// ratify's own tests, which can sign.
+func TestVerifyRefusesPhase4Mutations(t *testing.T) {
+ dir := t.TempDir()
+ gov := compileTo(t, dir, "p", "(+ 1 (* 2 3))")
+ blocks := pemBlocks(t, gov)
+
+ flipped := append([][]byte(nil), blocks...)
+ der := append([]byte(nil), blocks[2]...)
+ der[len(der)-1] ^= 0xff // the last byte of the signature
+ flipped[2] = der
+
+ seed := [32]byte{3}
+ foreignData, _ := lisp2gov.Compile("(+ 1 (* 2 3))", lisp2gov.Options{Name: "p", Seed: &seed})
+ foreign := filepath.Join(dir, "foreign.gov")
+ os.WriteFile(foreign, foreignData, 0o644)
+
+ tests := []struct {
+ name string
+ args []string
+ want string
+ }{
+ {"flipped signature byte", []string{"verify", writeBlocks(t, dir, "flipped", flipped)}, "E-TAMPERED: clause at depth 2"},
+ {"dropped depth", []string{"verify", writeBlocks(t, dir, "dropped", [][]byte{blocks[0], blocks[1], blocks[3]})}, "E-CHAIN"},
+ {"duplicated cert", []string{"verify", writeBlocks(t, dir, "dup", append(append([][]byte(nil), blocks...), blocks[1]))}, "E-CHAIN"},
+ {"private key block", []string{"verify", writeBlocks(t, dir, "key", append(append([][]byte(nil), blocks...), []byte{1}), "", "", "", "", "PRIVATE KEY")}, "E-MALFORMED"},
+ {"expired", []string{"verify", gov, "-at", "9999-12-31T23:59:59.5Z"}, "E-LAPSED"},
+ {"not yet in force", []string{"verify", gov, "-at", "1999-12-31T23:59:59Z"}, "E-NOT-IN-FORCE"},
+ {"foreign key", []string{"verify", foreign, "-anchor", gov}, "E-FOREIGN"},
+ }
+ for _, tt := range tests {
+ code, stdout, stderr := runCmd(tt.args...)
+ if code != exitInvalid || !strings.Contains(stderr, tt.want) || stdout != "" {
+ t.Errorf("%s: exit %d, stderr %q, stdout %q; want exit %d and %q", tt.name, code, stderr, stdout, exitInvalid, tt.want)
+ }
+ }
+
+ // Order is not a mutation: a shuffled file is the same program.
+ shuffled := writeBlocks(t, dir, "shuffled", [][]byte{blocks[3], blocks[1], blocks[0], blocks[2]})
+ if code, _, stderr := runCmd("verify", shuffled); code != exitOK {
+ t.Errorf("shuffled file: exit %d, %s", code, stderr)
+ }
+}
diff --git a/lisp2gov/keys.go b/lisp2gov/keys.go
index ea6a10c6b58af51f6d6bf444c95e3c6e86ee2faf..fae567c8e0f2ca4b76d24b6cd435bda5514298de 100644
--- a/lisp2gov/keys.go
+++ b/lisp2gov/keys.go
@@ -24,3 +24,10 @@ h.Write([]byte("GOVERNMENT"))
h.Write([]byte(strconv.Itoa(i)))
return ed25519.NewKeyFromSeed(h.Sum(nil))
}
+
+// DefaultAnchorKey is the public key of programs compiled without an
+// author key, so tools can say when a program is signed by nobody in
+// particular.
+func DefaultAnchorKey() ed25519.PublicKey {
+ return keyForDepth(DefaultSeed, 0).Public().(ed25519.PublicKey)
+}
diff --git a/program/program.go b/program/program.go
index 17d183e3bcbf53c58cea38bc9f59cebf4a1aa31c..532d9803f578650b31784d39b8a6102839325543 100644
--- a/program/program.go
+++ b/program/program.go
@@ -7,6 +7,7 @@ // untrusted bytes; everything after it runs code that passed every check.
package program
import (
+ "crypto/x509"
"fmt"
"io"
"time"
@@ -37,11 +38,20 @@ }
// Program is a ratified, decoded program.
type Program struct {
- Forms []sexpr.Value
+ Forms []sexpr.Value
+ // Certs is the chain in depth order, anchor first.
+ Certs []*x509.Certificate
+ // Nodes is how many AST nodes the program has. A node shared by
+ // several parents counts once; the validator's copies do not count.
+ Nodes int
origins ast.Origins
depth map[*ast.Node]int
}
+// Depth is how many certificates hold the program, not counting the
+// anchor: the depth of its tree.
+func (p *Program) Depth() int { return len(p.Certs) - 1 }
+
// Load runs every check on a .gov file and decodes it. Any error it returns
// means the program may not run: a ratify, policy or decode error.
func Load(data []byte, opts Options) (*Program, error) {
@@ -65,9 +75,12 @@ forms, origins, err := ast.FromTree(tree)
if err != nil {
return nil, &Error{ErrDecode, err.Error()}
}
- p := &Program{Forms: forms, origins: origins, depth: map[*ast.Node]int{}}
+ p := &Program{Forms: forms, Certs: certs, origins: origins, depth: map[*ast.Node]int{}}
var walk func(n *ast.Node, d int)
walk = func(n *ast.Node, d int) {
+ if _, seen := p.depth[n]; seen {
+ return
+ }
p.depth[n] = d
for _, c := range n.Children {
walk(c, d+1)
@@ -76,6 +89,7 @@ }
for _, f := range tree.Forms {
walk(f, 1)
}
+ p.Nodes = len(p.depth)
return p, nil
}
diff --git a/ratify/validity.go b/ratify/validity.go
index 4a2d681381ff9c18bc1a645d0f425be6d925fdbd..f1961e89d7dd936b17d2ddceb2d1d6ae16793c12 100644
--- a/ratify/validity.go
+++ b/ratify/validity.go
@@ -5,25 +5,29 @@ "crypto/x509"
"time"
)
+// Window is when the program is in force: from the latest notBefore to
+// the earliest notAfter. Each cert carries its own validity window and all
+// are checked at once, so the program's window is their overlap. The
+// returned depths are the certs that set each end.
+func Window(certs []*x509.Certificate) (takesEffect, expires time.Time, startDepth, endDepth int) {
+ for i, c := range certs {
+ if c.NotBefore.After(certs[startDepth].NotBefore) {
+ startDepth = i
+ }
+ if c.NotAfter.Before(certs[endDepth].NotAfter) {
+ endDepth = i
+ }
+ }
+ return certs[startDepth].NotBefore, certs[endDepth].NotAfter, startDepth, endDepth
+}
+
// CheckValidity checks that at falls inside every cert's validity window.
-// Each cert carries its own window, so the program is in force only where
-// all of them overlap: from the latest notBefore to the earliest notAfter.
// RFC 5280 counts both ends as inside the window.
func CheckValidity(certs []*x509.Certificate, at time.Time) error {
if len(certs) == 0 {
return nil
}
- start, end := 0, 0
- for i, c := range certs {
- if c.NotBefore.After(certs[start].NotBefore) {
- start = i
- }
- if c.NotAfter.Before(certs[end].NotAfter) {
- end = i
- }
- }
- takesEffect, expires := certs[start].NotBefore, certs[end].NotAfter
-
+ takesEffect, expires, start, end := Window(certs)
if takesEffect.After(expires) {
return errorf(ErrLapsed, "never in force: depth %d expires %s, before depth %d takes effect %s",
end, stamp(expires), start, stamp(takesEffect))