government / lisp2gov / cert.go

@ 9d8c149e89e015823df22a42b5d70029e7e44e25 | history


package lisp2gov

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

// The default window in force. 9999-12-31 is RFC 5280's value for a
// certificate with no well-defined expiration.
var (
	defaultEffective = time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC)
	defaultExpires   = time.Date(9999, 12, 31, 23, 59, 59, 0, time.UTC)
)

// signer is a certificate together with the key that signs the next one.
type signer struct {
	cert *x509.Certificate
	key  ed25519.PrivateKey
}

// newAnchor makes the self-signed trust anchor. It carries no policies:
// the policy tree starts below it, at cert 1.
func newAnchor(seed [32]byte, program string) (signer, error) {
	key := keyForDepth(seed, 0)
	pub := key.Public().(ed25519.PublicKey)
	tmpl := &x509.Certificate{
		SerialNumber:          big.NewInt(1),
		Subject:               pkix.Name{CommonName: "GOVERNMENT Anchor", Organization: []string{program}},
		NotBefore:             defaultEffective,
		NotAfter:              defaultExpires,
		BasicConstraintsValid: true,
		IsCA:                  true,
		KeyUsage:              x509.KeyUsageCertSign | x509.KeyUsageCRLSign,
		SubjectKeyId:          keyID(pub),
		AuthorityKeyId:        keyID(pub),
	}
	return create(tmpl, tmpl, pub, key, key)
}

// newCert makes the cert at depth i, issued by parent. Every cert but the
// last is a CA, because each one signs the next; the last one signs
// nothing.
func newCert(seed [32]byte, program string, i int, last bool, policies []x509.OID, mappings []x509.PolicyMapping, parent signer) (signer, error) {
	key := keyForDepth(seed, i)
	pub := key.Public().(ed25519.PublicKey)
	tmpl := &x509.Certificate{
		SerialNumber:          big.NewInt(int64(i + 1)),
		Subject:               pkix.Name{CommonName: fmt.Sprintf("GOVERNMENT Depth %d", i), Organization: []string{program}},
		NotBefore:             defaultEffective,
		NotAfter:              defaultExpires,
		BasicConstraintsValid: true,
		IsCA:                  !last,
		KeyUsage:              x509.KeyUsageCertSign | x509.KeyUsageCRLSign,
		SubjectKeyId:          keyID(pub),
	}
	if last {
		tmpl.KeyUsage = x509.KeyUsageDigitalSignature
	}
	if last && len(mappings) > 0 {
		// RFC 5280 never processes mappings in the last cert (6.1.4 runs
		// only for certs 1..n-1), so any here would be silently dead.
		return signer{}, fmt.Errorf("cert %d is the last one and cannot carry mappings", i)
	}
	if len(policies) > 0 {
		infos := make([]policyInfo, len(policies))
		for j, p := range policies {
			infos[j] = policyInfo{id: p}
		}
		ext, err := certificatePoliciesExtension(infos)
		if err != nil {
			return signer{}, err
		}
		tmpl.ExtraExtensions = append(tmpl.ExtraExtensions, ext)
	}
	if len(mappings) > 0 {
		ext, err := policyMappingsExtension(mappings)
		if err != nil {
			return signer{}, err
		}
		tmpl.ExtraExtensions = append(tmpl.ExtraExtensions, ext)
	}
	return create(tmpl, parent.cert, pub, parent.key, key)
}

func create(tmpl, parent *x509.Certificate, pub ed25519.PublicKey, signWith, own ed25519.PrivateKey) (signer, error) {
	// Ed25519 signatures use no randomness, and the serial is set, so rand
	// is never read and the output is deterministic.
	der, err := x509.CreateCertificate(rand.Reader, tmpl, parent, pub, signWith)
	if err != nil {
		return signer{}, err
	}
	cert, err := x509.ParseCertificate(der)
	if err != nil {
		return signer{}, err
	}
	return signer{cert, own}, nil
}

// keyID is RFC 7093 method 1: the leftmost 160 bits of the SHA-256 of the
// public key. Go would compute a key id for CA certs on its own, but not for
// the last cert, and its choice of hash has changed between releases;
// setting it here keeps every cert's bytes the same across Go versions.
func keyID(pub ed25519.PublicKey) []byte {
	sum := sha256.Sum256(pub)
	return sum[:20]
}

func encodePEM(header string, certs []*x509.Certificate) []byte {
	var b bytes.Buffer
	b.WriteString(header)
	for _, c := range certs {
		pem.Encode(&b, &pem.Block{Type: "CERTIFICATE", Bytes: c.Raw})
	}
	return b.Bytes()
}