government / lisp2gov / cert.go

@ 844f0e3dd48aea4963c188d8ad2ed9749ed3e7f0 | history


package lisp2gov

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

	"government/ast"
	"government/sexpr"
)

// 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]
}

// encodePEM writes the certs as PEM blocks after a header. Text outside
// PEM blocks is ignored by readers, so the header can carry the source.
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()
}

// firstProgram is the step-18 experiment: a program whose forms are all
// atoms, so its tree has depth 1. That needs only the anchor and cert 1,
// with each form as a policy, and no mappings, so Go can write every byte
// itself. Compile replaces it once the policy extensions are hand-encoded.
func firstProgram(seed [32]byte, name, src string) ([]byte, error) {
	forms, err := sexpr.ReadAll(src)
	if err != nil {
		return nil, err
	}
	tree, err := ast.ToTree(forms)
	if err != nil {
		return nil, err
	}
	layers, err := ast.Layer(tree)
	if err != nil {
		return nil, err
	}
	if layers.Depth() != 1 {
		return nil, fmt.Errorf("firstProgram handles depth 1 only; %q has depth %d", src, layers.Depth())
	}
	var policies []x509.OID
	for _, n := range layers.Nodes[0] {
		oid, err := n.OID()
		if err != nil {
			return nil, err
		}
		policies = append(policies, oid)
	}

	anchor, err := newAnchor(seed, name)
	if err != nil {
		return nil, err
	}
	cert1, err := newCert(seed, name, 1, true, policies, nil, anchor)
	if err != nil {
		return nil, err
	}
	header := "; " + name + ".gov\n" + src + "\n\n"
	return encodePEM(header, []*x509.Certificate{anchor.cert, cert1.cert}), nil
}