government / ratify / chain.go

@ 53308ffa01ed91d41c6657b16c77ee7a97ad8d3b | history


package ratify

import (
	"crypto/x509"
	"encoding/asn1"
	"errors"
)

var (
	oidPolicyConstraints = asn1.ObjectIdentifier{2, 5, 29, 36}
	oidInhibitAnyPolicy  = asn1.ObjectIdentifier{2, 5, 29, 54}
)

// CheckChain checks a chain put in order by Order, the way RFC 5280 basic
// path processing does, minus validity dates and policies, which have their
// own steps. A depth is the cert's position: 0 is the anchor.
func CheckChain(certs []*x509.Certificate) error {
	for i, c := range certs {
		parent := c
		if i > 0 {
			parent = certs[i-1]
		}
		// CheckSignatureFrom also checks that the parent is a CA allowed
		// to sign certs, which is the other half of a valid link.
		if err := c.CheckSignatureFrom(parent); err != nil {
			var constraint x509.ConstraintViolationError
			if errors.As(err, &constraint) {
				return errorf(ErrChain, "depth %d: %s may not sign certificates (it must be a CA with keyCertSign)", i, name(parent))
			}
			if i == 0 {
				return errorf(ErrTampered, "the trust anchor fails its own signature check: %v", err)
			}
			return errorf(ErrTampered, "clause at depth %d fails signature check: %v", i, err)
		}
		if err := checkExtensions(i, c); err != nil {
			return err
		}
	}
	return nil
}

// checkExtensions rejects what GOVERNMENT does not process. A relying party
// that meets a critical extension it does not understand must refuse the
// cert, because the issuer marked it as changing the cert's meaning.
// policyConstraints and inhibitAnyPolicy are understood but not allowed:
// both would make policy processing drop or forbid nodes, and v1 keeps
// those counters out of the picture.
func checkExtensions(depth int, c *x509.Certificate) error {
	if len(c.UnhandledCriticalExtensions) > 0 {
		return errorf(ErrChain, "depth %d: unknown critical extension %v", depth, c.UnhandledCriticalExtensions[0])
	}
	for _, ext := range c.Extensions {
		switch {
		case ext.Id.Equal(oidPolicyConstraints):
			return errorf(ErrChain, "depth %d: policyConstraints is not allowed", depth)
		case ext.Id.Equal(oidInhibitAnyPolicy):
			return errorf(ErrChain, "depth %d: inhibitAnyPolicy is not allowed; certs 2..n depend on anyPolicy", depth)
		}
	}
	return nil
}