government / src / ratify / chain_test.go

@ a94ce18dbaa3c27d01f1491d51ec12c5767daf6d | history


package ratify

import (
	"bytes"
	"crypto/ed25519"
	"crypto/sha256"
	"crypto/x509"
	"crypto/x509/pkix"
	"encoding/asn1"
	"errors"
	"fmt"
	"math/big"
	"math/rand"
	"strings"
	"testing"
	"time"

	"nmyk.io/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)
	}
}