government / src / lisp2gov / cert.go

@ 25d85a34ec701b64fde8050571d39eaa9b8d1bbb | 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 (
	defaultNotBefore = time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC)
	defaultNotAfter  = 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
}

// profile is what every cert of one program shares: who signs it, what it
// is called, and when it is in force.
type profile struct {
	seed                [32]byte
	program             string
	author, email       string
	notBefore, notAfter time.Time
}

// newAnchor makes the self-signed trust anchor. It is signed with the
// author's own key and names the author, so it records who ratified the
// program. It carries no policies: the policy tree starts below it, at
// cert 1.
func newAnchor(p profile) (signer, error) {
	key := keyForDepth(p.seed, 0)
	pub := key.Public().(ed25519.PublicKey)
	cn := p.author
	if cn == "" {
		cn = "GOVERNMENT Anchor"
	}
	tmpl := &x509.Certificate{
		SerialNumber:          big.NewInt(1),
		Subject:               pkix.Name{CommonName: cn, Organization: []string{p.program}},
		NotBefore:             p.notBefore,
		NotAfter:              p.notAfter,
		BasicConstraintsValid: true,
		IsCA:                  true,
		KeyUsage:              x509.KeyUsageCertSign | x509.KeyUsageCRLSign,
		SubjectKeyId:          keyID(pub),
		AuthorityKeyId:        keyID(pub),
	}
	if p.email != "" {
		tmpl.EmailAddresses = []string{p.email}
	}
	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(p profile, i int, last bool, policies []policyInfo, mappings []x509.PolicyMapping, parent signer) (signer, error) {
	key := keyForDepth(p.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{p.program}},
		NotBefore:             p.notBefore,
		NotAfter:              p.notAfter,
		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 {
		ext, err := certificatePoliciesExtension(policies)
		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()
}