@ 52e34195229c6f9cac00b26701541ddac8a02b66 | history
package ratify
import (
"crypto/x509"
"encoding/pem"
"regexp"
)
// beginLine matches the start of a PEM block: "-----BEGIN " at the start of
// a line. pem.Decode silently skips a block it cannot decode and goes on to
// the next one, which for a program would mean silently losing a depth, so
// Load counts these lines and insists every one became a block.
var beginLine = regexp.MustCompile(`(?m)^-----BEGIN `)
// Load reads a .gov file into its certificates, anchor first. Text outside
// PEM blocks is ignored, as PEM allows; that is where `government compile
// -source` puts the Lisp source. The text is never trusted: what counts is
// the DER inside each block, which is what the signatures cover.
func Load(data []byte) ([]*x509.Certificate, error) {
var certs []*x509.Certificate
rest := data
for {
var block *pem.Block
block, rest = pem.Decode(rest)
if block == nil {
break
}
n := len(certs)
if block.Type != "CERTIFICATE" {
return nil, errorf(ErrMalformed, "block %d is a %s, not a CERTIFICATE", n, block.Type)
}
if len(block.Headers) > 0 {
return nil, errorf(ErrMalformed, "block %d has PEM headers; a certificate block has none", n)
}
cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
return nil, errorf(ErrMalformed, "block %d: %v", n, err)
}
certs = append(certs, cert)
}
if found := len(beginLine.FindAll(data, -1)); found != len(certs) {
return nil, errorf(ErrMalformed, "%d PEM blocks begin but only %d could be read", found, len(certs))
}
if len(certs) < 2 {
// A program needs a trust anchor and at least one depth.
return nil, errorf(ErrMalformed, "%d certificates; a program needs an anchor and at least one more", len(certs))
}
return certs, nil
}