government / lisp2gov / repeal.go

@ bf971275d54b7235006309f4e84fd06723f4f70e | 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. Repealing needs it because the cert being repealed is
	// revoked by its issuer, the cert one depth up, whose key is derived
	// from 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
	// Issued is when the CRL is made (thisUpdate), 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.
	Issued, NextUpdate time.Time
}

// Repeal makes a CRL that revokes the cert at depth of a program, given
// its certs in depth order. Revoking any one depth breaks the chain, so it
// repeals the whole program.
//
// By RFC 5280 a cert is revoked by its own issuer: the CRL is signed by
// the cert at depth-1 (the anchor, for depth 1) and names the revoked cert
// by its serial number, which is unique only among that issuer's certs.
func Repeal(certs []*x509.Certificate, depth int, opts RepealOptions) ([]byte, error) {
	n := len(certs) - 1
	if depth < 1 || depth > n {
		return nil, fmt.Errorf("depth %d: the program has depths 1 to %d", depth, n)
	}
	seed := DefaultSeed
	if opts.Seed != nil {
		seed = *opts.Seed
	}
	issuer, revoked := certs[depth-1], certs[depth]
	key := keyForDepth(seed, depth-1)
	pub, err := x509.MarshalPKIXPublicKey(key.Public())
	if err != nil {
		return nil, err
	}
	if !bytes.Equal(pub, issuer.RawSubjectPublicKeyInfo) {
		return nil, fmt.Errorf("this key did not compile the program: depth %d's issuer has a different key", depth)
	}
	if !opts.NextUpdate.After(opts.Issued) {
		return nil, fmt.Errorf("the CRL would go stale (%s) before it is issued (%s)",
			opts.NextUpdate.UTC().Format(time.RFC3339), opts.Issued.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.Issued.Unix()),
		ThisUpdate: opts.Issued.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, issuer, key)
	if err != nil {
		return nil, err
	}
	return pem.EncodeToMemory(&pem.Block{Type: "X509 CRL", Bytes: der}), nil
}