government / src / lisp2gov / repeal.go

@ 761f3b207460ae5814dd76a326ce14777e29e659 | history


package lisp2gov

import (
	"bytes"
	"crypto/rand"
	"crypto/x509"
	"encoding/pem"
	"fmt"
	"math/big"
	"time"
)

type RepealOptions struct {
	// Seed is the key the program was compiled with; nil means
	// DefaultSeed. The repeal is signed by the anchor, whose key is this
	// seed.
	Seed *[32]byte
	// Reason is a CRLReason code (see ratify.Reasons).
	Reason int
	// At is when the repeal takes effect: the revocation time. A time in
	// the future schedules the repeal.
	At time.Time
	// LastUpdate is when the CRL is made (RFC 5280's thisUpdate, which
	// OpenSSL prints as "Last Update"), and NextUpdate is when it goes
	// stale. A CRL is only trusted until its nextUpdate, so a permanent
	// repeal should have a far-off one.
	LastUpdate, NextUpdate time.Time
}

// Repeal makes a CRL that repeals a program, given its certs in depth
// order. Revoking any cert breaks the chain, so one depth is enough; it is
// always depth 1, the cert the anchor issued, because by RFC 5280 a cert
// is revoked by its own issuer. The CRL is then signed with the author's
// own key, and reads as the author striking down what they ratified.
func Repeal(certs []*x509.Certificate, opts RepealOptions) ([]byte, error) {
	if len(certs) < 2 {
		return nil, fmt.Errorf("a program has at least 2 certs, got %d", len(certs))
	}
	seed := DefaultSeed
	if opts.Seed != nil {
		seed = *opts.Seed
	}
	anchor, revoked := certs[0], certs[1]
	key := keyForDepth(seed, 0)
	pub, err := x509.MarshalPKIXPublicKey(key.Public())
	if err != nil {
		return nil, err
	}
	if !bytes.Equal(pub, anchor.RawSubjectPublicKeyInfo) {
		return nil, fmt.Errorf("this key did not compile the program: the anchor has a different key")
	}
	if !opts.NextUpdate.After(opts.LastUpdate) {
		return nil, fmt.Errorf("the CRL's next update (%s) must come after its last update (%s)",
			opts.NextUpdate.UTC().Format(time.RFC3339), opts.LastUpdate.UTC().Format(time.RFC3339))
	}

	tmpl := &x509.RevocationList{
		// A CRL number should grow with each CRL an issuer publishes; the
		// issue time in seconds does, and keeps the output deterministic.
		Number:     big.NewInt(opts.LastUpdate.Unix()),
		ThisUpdate: opts.LastUpdate.UTC(),
		NextUpdate: opts.NextUpdate.UTC(),
		RevokedCertificateEntries: []x509.RevocationListEntry{{
			SerialNumber:   revoked.SerialNumber,
			RevocationTime: opts.At.UTC(),
			ReasonCode:     opts.Reason,
		}},
	}
	// Ed25519 signing reads no randomness, so rand is never used.
	der, err := x509.CreateRevocationList(rand.Reader, tmpl, anchor, key)
	if err != nil {
		return nil, err
	}
	return pem.EncodeToMemory(&pem.Block{Type: "X509 CRL", Bytes: der}), nil
}