mirror of
https://github.com/hanzoai/pki.git
synced 2026-11-03 18:08:14 +00:00
212 lines
5.7 KiB
Go
212 lines
5.7 KiB
Go
package certutil
|
|
|
|
import (
|
|
"bytes"
|
|
"crypto/x509"
|
|
"crypto/x509/pkix"
|
|
"os"
|
|
"slices"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/cockroachdb/errors"
|
|
"github.com/effective-security/xlog"
|
|
)
|
|
|
|
// BundleStatus is designated for various status reporting.
|
|
type BundleStatus struct {
|
|
// A list of SKIs of expiring certificates
|
|
ExpiringSKIs []string `json:"expiring_SKIs"`
|
|
// A list of untrusted root store names
|
|
Untrusted []string `json:"untrusted_root_stores"`
|
|
// A list of human readable warning messages based on the bundle status.
|
|
Messages []string `json:"messages"`
|
|
|
|
Code int `json:"code"`
|
|
}
|
|
|
|
// IsExpiring returns true if bundle is expiring in less than 30 days
|
|
func (b *BundleStatus) IsExpiring() bool {
|
|
return len(b.ExpiringSKIs) > 0
|
|
}
|
|
|
|
// IsUntrusted returns true if the cert's issuers are not trusted
|
|
func (b *BundleStatus) IsUntrusted() bool {
|
|
return len(b.Untrusted) > 0
|
|
}
|
|
|
|
// A Bundle contains a certificate and its trust chain. It is intended
|
|
// to store the most widely applicable chain, with shortness an
|
|
// explicit goal.
|
|
type Bundle struct {
|
|
// Chain does not include the root anchor
|
|
Chain []*x509.Certificate
|
|
Cert *x509.Certificate
|
|
IssuerCert *x509.Certificate
|
|
RootCert *x509.Certificate
|
|
Issuer *pkix.Name
|
|
Subject *pkix.Name
|
|
IssuerID string
|
|
SubjectID string
|
|
Expires time.Time
|
|
Hostnames []string
|
|
CertPEM string
|
|
CACertsPEM string
|
|
RootCertPEM string
|
|
}
|
|
|
|
// ExpiresInHours returns the time until Expires truncated toward zero to
|
|
// whole hours: 90 minutes is 1h, and an expiry 90 minutes ago is -1h
|
|
// (XPKI-045).
|
|
func (b *Bundle) ExpiresInHours() time.Duration {
|
|
return b.Expires.Sub(time.Now().UTC()) / time.Hour * time.Hour
|
|
}
|
|
|
|
// VerifyBundleFromPEM constructs and verifies the cert chain
|
|
func VerifyBundleFromPEM(certPEM, intCAPEM, rootPEM []byte, opt ...Option) (bundle *Bundle, status *BundleStatus, err error) {
|
|
b, err := NewBundlerFromPEM(rootPEM, intCAPEM, opt...)
|
|
if err != nil {
|
|
err = errors.WithMessage(err, "failed to create bundler")
|
|
return
|
|
}
|
|
|
|
c, err := b.ChainFromPEM(certPEM, nil, "")
|
|
if err != nil {
|
|
err = errors.WithMessage(err, "failed to bundle")
|
|
return
|
|
}
|
|
return BuildBundle(c)
|
|
}
|
|
|
|
// BuildBundle returns the Bundle and BundleStatus of a Chain built by a
|
|
// Bundler. A nil c or c.Cert returns an error; a nil c.Status is treated as
|
|
// an empty status, and a nil c.Root (a Force chain) leaves RootCert and
|
|
// RootCertPEM empty (XPKI-042).
|
|
func BuildBundle(c *Chain) (bundle *Bundle, status *BundleStatus, err error) {
|
|
if c == nil {
|
|
return nil, nil, errors.New("chain is nil")
|
|
}
|
|
if c.Cert == nil {
|
|
return nil, nil, errors.Wrap(ErrNoCertificates, "chain has no leaf certificate")
|
|
}
|
|
cs := c.Status
|
|
if cs == nil {
|
|
cs = &BundleStatus{}
|
|
}
|
|
|
|
var pemCert, pemRoot, pemCA string
|
|
|
|
pemCert, err = EncodeToPEMString(false, c.Cert)
|
|
if err != nil {
|
|
return nil, nil, errors.WithMessage(err, "failed to encode cert to PEM")
|
|
}
|
|
|
|
pemRoot, err = EncodeToPEMString(false, c.Root)
|
|
if err != nil {
|
|
return nil, nil, errors.WithMessage(err, "failed to encode root cert to PEM")
|
|
}
|
|
|
|
if len(c.Chain) > 1 {
|
|
pemCA, err = EncodeToPEMString(false, c.Chain[1:]...)
|
|
if err != nil {
|
|
return nil, nil, errors.WithMessage(err, "failed to encode CA chain to PEM")
|
|
}
|
|
}
|
|
|
|
bundle = &Bundle{
|
|
Chain: c.Chain,
|
|
Cert: c.Cert,
|
|
RootCert: c.Root,
|
|
IssuerCert: FindIssuer(c.Cert, c.Chain, c.Root),
|
|
Issuer: c.Issuer,
|
|
IssuerID: GetIssuerID(c.Cert),
|
|
Subject: c.Subject,
|
|
SubjectID: GetSubjectID(c.Cert),
|
|
Expires: c.Expires,
|
|
Hostnames: c.Hostnames,
|
|
CertPEM: pemCert,
|
|
CACertsPEM: pemCA,
|
|
RootCertPEM: pemRoot,
|
|
}
|
|
|
|
if len(cs.Messages) > 0 {
|
|
logger.KV(xlog.WARNING, "CN", c.Cert.Subject.CommonName, "messages", strings.Join(cs.Messages, ";"))
|
|
}
|
|
if len(cs.ExpiringSKIs) > 0 {
|
|
logger.KV(xlog.WARNING, "CN", c.Cert.Subject.CommonName, "ExpiringSKIs", strings.Join(cs.ExpiringSKIs, ";"))
|
|
}
|
|
if len(cs.Untrusted) > 0 {
|
|
logger.KV(xlog.WARNING, "CN", c.Cert.Subject.CommonName, "Untrusted", strings.Join(cs.Untrusted, ";"))
|
|
}
|
|
|
|
status = &BundleStatus{
|
|
Code: cs.Code,
|
|
ExpiringSKIs: cs.ExpiringSKIs,
|
|
Untrusted: cs.Untrusted,
|
|
Messages: cs.Messages,
|
|
}
|
|
|
|
return
|
|
}
|
|
|
|
// LoadAndVerifyBundleFromPEM constructs and verifies the cert chain
|
|
func LoadAndVerifyBundleFromPEM(certFile, intCAFile, rootFile string, opt ...Option) (*Bundle, *BundleStatus, error) {
|
|
var err error
|
|
var certPEM, intCAPEM, rootPEM []byte
|
|
|
|
certPEM, err = os.ReadFile(certFile)
|
|
if err != nil {
|
|
return nil, nil, errors.WithStack(err)
|
|
}
|
|
|
|
if intCAFile != "" {
|
|
intCAPEM, err = os.ReadFile(intCAFile)
|
|
if err != nil {
|
|
return nil, nil, errors.WithStack(err)
|
|
}
|
|
}
|
|
|
|
if rootFile != "" {
|
|
rootPEM, err = os.ReadFile(rootFile)
|
|
if err != nil {
|
|
return nil, nil, errors.WithStack(err)
|
|
}
|
|
}
|
|
|
|
return VerifyBundleFromPEM(certPEM, intCAPEM, rootPEM, opt...)
|
|
}
|
|
|
|
// FindIssuer returns an issuer cert
|
|
func FindIssuer(crt *x509.Certificate, chain []*x509.Certificate, root *x509.Certificate) *x509.Certificate {
|
|
if root != nil && bytes.Equal(crt.RawIssuer, root.RawSubject) {
|
|
return root
|
|
}
|
|
for _, c := range chain {
|
|
if c != nil && bytes.Equal(crt.RawIssuer, c.RawSubject) {
|
|
return c
|
|
}
|
|
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// SortBundlesByExpiration returns a new slice of bundles sorted by Expires in
|
|
// descending order. The sort is stable, so bundles with the same Expires keep
|
|
// their input order, and nil bundles go last. The caller's slice is not
|
|
// reordered; the bundles themselves are shared (XPKI-038).
|
|
func SortBundlesByExpiration(bundles []*Bundle) []*Bundle {
|
|
sorted := slices.Clone(bundles)
|
|
slices.SortStableFunc(sorted, func(a, b *Bundle) int {
|
|
switch {
|
|
case a == nil && b == nil:
|
|
return 0
|
|
case a == nil:
|
|
return 1
|
|
case b == nil:
|
|
return -1
|
|
}
|
|
return b.Expires.Compare(a.Expires)
|
|
})
|
|
return sorted
|
|
}
|