government / ratify / anchor.go

@ c3dee802a4878505a60909c4f533fffbdfffc936 | history


package ratify

import (
	"bytes"
	"crypto/sha256"
	"crypto/x509"
	"encoding/hex"
	"encoding/pem"
	"fmt"
)

// Pin is a trusted public key, as DER-encoded SubjectPublicKeyInfo.
//
// A trust anchor is really a key, not a certificate: what makes the anchor
// cert trustworthy is only that its key is one you already trust. So a pin
// names the key alone, and survives re-ratification: a program recompiled
// with new dates or text gets a new anchor cert but keeps its author's key.
type Pin []byte

// LoadPin reads a pin from PEM: a PUBLIC KEY block, a single CERTIFICATE,
// or a whole .gov file, whose anchor's key is used.
func LoadPin(data []byte) (Pin, error) {
	block, _ := pem.Decode(data)
	if block == nil {
		return nil, fmt.Errorf("no PEM block found")
	}
	switch block.Type {
	case "PUBLIC KEY":
		key, err := x509.ParsePKIXPublicKey(block.Bytes)
		if err != nil {
			return nil, err
		}
		return marshalKey(key)
	case "CERTIFICATE":
		if len(beginLine.FindAll(data, -1)) == 1 {
			cert, err := x509.ParseCertificate(block.Bytes)
			if err != nil {
				return nil, err
			}
			return Pin(cert.RawSubjectPublicKeyInfo), nil
		}
		certs, err := Load(data)
		if err != nil {
			return nil, err
		}
		ordered, err := Order(certs)
		if err != nil {
			return nil, err
		}
		return Pin(ordered[0].RawSubjectPublicKeyInfo), nil
	}
	return nil, fmt.Errorf("a %s block cannot be a pin; want PUBLIC KEY or CERTIFICATE", block.Type)
}

// marshalKey re-encodes a parsed key, so a pin is always in the same DER
// form Go writes into certificates, whatever tool produced the PEM.
func marshalKey(key any) (Pin, error) {
	der, err := x509.MarshalPKIXPublicKey(key)
	if err != nil {
		return nil, err
	}
	return Pin(der), nil
}

// Fingerprint is the SHA-256 of the key's SubjectPublicKeyInfo, the usual
// way to name a key in a sentence.
func Fingerprint(spki []byte) string {
	sum := sha256.Sum256(spki)
	return hex.EncodeToString(sum[:])
}

// CheckPin checks that the anchor's key is the pinned one.
func CheckPin(anchor *x509.Certificate, pin Pin) error {
	if bytes.Equal(anchor.RawSubjectPublicKeyInfo, pin) {
		return nil
	}
	return errorf(ErrForeign, "ratified by key %s, not the pinned key %s", Fingerprint(anchor.RawSubjectPublicKeyInfo), Fingerprint(pin))
}