@ 01d409d8a4b83bc1592daf61e55e68fa43d77f1e | history
package ratify
import (
"bytes"
"crypto/x509"
"slices"
)
// Order puts certs in depth order, anchor first, whatever order the file
// had them in. The anchor is the one self-issued cert; from it, each cert's
// child is the one cert whose issuer is its subject. This relies only on
// names, so CheckChain must still verify that every link is signed: a
// forged link would name the right parent but fail its signature.
//
// Only the anchor may be self-issued. RFC 5280's policy_mapping counter
// skips self-issued certs, so one in the path would make a cert's depth
// differ from its position.
func Order(certs []*x509.Certificate) ([]*x509.Certificate, error) {
var anchor *x509.Certificate
for _, c := range certs {
if !selfIssued(c) {
continue
}
if anchor != nil {
return nil, errorf(ErrChain, "two self-issued certs (%s and %s); only the trust anchor may be one", name(anchor), name(c))
}
anchor = c
}
if anchor == nil {
return nil, errorf(ErrChain, "no trust anchor: no cert is self-issued")
}
// childOf maps a parent's subject to the cert it issued.
childOf := map[string]*x509.Certificate{}
subjects := map[string]bool{}
for _, c := range certs {
if subjects[string(c.RawSubject)] {
return nil, errorf(ErrChain, "two certs are named %s", name(c))
}
subjects[string(c.RawSubject)] = true
if c == anchor {
continue
}
if other, ok := childOf[string(c.RawIssuer)]; ok {
return nil, errorf(ErrChain, "%s and %s both claim %s as their issuer; a program is a single path", name(other), name(c), c.Issuer)
}
childOf[string(c.RawIssuer)] = c
}
ordered := []*x509.Certificate{anchor}
for last := anchor; ; {
next, ok := childOf[string(last.RawSubject)]
if !ok {
break
}
ordered = append(ordered, next)
last = next
}
for _, c := range certs {
if slices.Contains(ordered, c) {
continue
}
if !subjects[string(c.RawIssuer)] {
return nil, errorf(ErrChain, "%s was issued by %s, which is not in the file; a depth is missing", name(c), c.Issuer)
}
return nil, errorf(ErrChain, "%s is not on the path from the trust anchor", name(c))
}
return ordered, nil
}
func selfIssued(c *x509.Certificate) bool {
return bytes.Equal(c.RawIssuer, c.RawSubject)
}
func name(c *x509.Certificate) string {
return c.Subject.String()
}