|
| 1 | +/* |
| 2 | +Copyright The cert-manager Authors. |
| 3 | +
|
| 4 | +Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +you may not use this file except in compliance with the License. |
| 6 | +You may obtain a copy of the License at |
| 7 | +
|
| 8 | + http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +
|
| 10 | +Unless required by applicable law or agreed to in writing, software |
| 11 | +distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +See the License for the specific language governing permissions and |
| 14 | +limitations under the License. |
| 15 | +*/ |
| 16 | + |
| 17 | +package pki |
| 18 | + |
| 19 | +import ( |
| 20 | + "bytes" |
| 21 | + "crypto/sha256" |
| 22 | + "crypto/x509" |
| 23 | + "encoding/pem" |
| 24 | + "fmt" |
| 25 | + "slices" |
| 26 | + "time" |
| 27 | +) |
| 28 | + |
| 29 | +// CertPool is a set of certificates. |
| 30 | +type CertPool struct { |
| 31 | + certificates map[[32]byte]*x509.Certificate |
| 32 | + |
| 33 | + filterExpired bool |
| 34 | +} |
| 35 | + |
| 36 | +type Option func(*CertPool) |
| 37 | + |
| 38 | +func WithFilteredExpiredCerts(filterExpired bool) Option { |
| 39 | + return func(cp *CertPool) { |
| 40 | + cp.filterExpired = filterExpired |
| 41 | + } |
| 42 | +} |
| 43 | + |
| 44 | +// NewCertPool returns a new, empty CertPool. |
| 45 | +// It will deduplicate certificates based on their SHA256 hash. |
| 46 | +// Optionally, it can filter out expired certificates. |
| 47 | +func NewCertPool(options ...Option) *CertPool { |
| 48 | + certPool := &CertPool{ |
| 49 | + certificates: make(map[[32]byte]*x509.Certificate), |
| 50 | + } |
| 51 | + |
| 52 | + for _, option := range options { |
| 53 | + option(certPool) |
| 54 | + } |
| 55 | + |
| 56 | + return certPool |
| 57 | +} |
| 58 | + |
| 59 | +func (cp *CertPool) AddCert(cert *x509.Certificate) bool { |
| 60 | + if cert == nil { |
| 61 | + panic("adding nil Certificate to CertPool") |
| 62 | + } |
| 63 | + if cp.filterExpired && time.Now().After(cert.NotAfter) { |
| 64 | + return false |
| 65 | + } |
| 66 | + |
| 67 | + hash := sha256.Sum256(cert.Raw) |
| 68 | + cp.certificates[hash] = cert |
| 69 | + return true |
| 70 | +} |
| 71 | + |
| 72 | +// AddCertsFromPEM strictly validates a given input PEM bundle to confirm it contains |
| 73 | +// only valid CERTIFICATE PEM blocks. If successful, returns the validated PEM blocks with any |
| 74 | +// comments or extra data stripped. |
| 75 | +// |
| 76 | +// This validation is broadly similar to the standard library function |
| 77 | +// crypto/x509.CertPool.AppendCertsFromPEM - that is, we decode each PEM block at a time and parse |
| 78 | +// it as a certificate. |
| 79 | +// |
| 80 | +// The difference here is that we want to ensure that the bundle _only_ contains certificates, and |
| 81 | +// not just skip over things which aren't certificates. |
| 82 | +// |
| 83 | +// If, for example, someone accidentally used a combined cert + private key as an input to a trust |
| 84 | +// bundle, we wouldn't want to then distribute the private key in the target. |
| 85 | +// |
| 86 | +// In addition, the standard library AppendCertsFromPEM also silently skips PEM blocks with |
| 87 | +// non-empty Headers. We error on such PEM blocks, for the same reason as above; headers could |
| 88 | +// contain (accidental) private information. They're also non-standard according to |
| 89 | +// https://www.rfc-editor.org/rfc/rfc7468 |
| 90 | +// |
| 91 | +// Additionally, if the input PEM bundle contains no non-expired certificates, an error is returned. |
| 92 | +// TODO: Reconsider what should happen if the input only contains expired certificates. |
| 93 | +func (cp *CertPool) AddCertsFromPEM(pemData []byte) error { |
| 94 | + if pemData == nil { |
| 95 | + return fmt.Errorf("certificate data can't be nil") |
| 96 | + } |
| 97 | + |
| 98 | + ok := false |
| 99 | + for { |
| 100 | + var block *pem.Block |
| 101 | + block, pemData = pem.Decode(pemData) |
| 102 | + |
| 103 | + if block == nil { |
| 104 | + break |
| 105 | + } |
| 106 | + |
| 107 | + if block.Type != "CERTIFICATE" { |
| 108 | + // only certificates are allowed in a bundle |
| 109 | + return fmt.Errorf("invalid PEM block in bundle: only CERTIFICATE blocks are permitted but found '%s'", block.Type) |
| 110 | + } |
| 111 | + |
| 112 | + if len(block.Headers) != 0 { |
| 113 | + return fmt.Errorf("invalid PEM block in bundle; blocks are not permitted to have PEM headers") |
| 114 | + } |
| 115 | + |
| 116 | + certificate, err := x509.ParseCertificate(block.Bytes) |
| 117 | + if err != nil { |
| 118 | + // the presence of an invalid cert (including things which aren't certs) |
| 119 | + // should cause the bundle to be rejected |
| 120 | + return fmt.Errorf("invalid PEM block in bundle; invalid PEM certificate: %w", err) |
| 121 | + } |
| 122 | + |
| 123 | + if certificate == nil { |
| 124 | + return fmt.Errorf("failed appending a certificate: certificate is nil") |
| 125 | + } |
| 126 | + |
| 127 | + if cp.AddCert(certificate) { |
| 128 | + ok = true // at least one non-expired certificate was found in the input |
| 129 | + } |
| 130 | + } |
| 131 | + |
| 132 | + if !ok { |
| 133 | + return fmt.Errorf("no non-expired certificates found in input bundle") |
| 134 | + } |
| 135 | + |
| 136 | + return nil |
| 137 | +} |
| 138 | + |
| 139 | +// Get certificates quantity in the certificates pool |
| 140 | +func (cp *CertPool) Size() int { |
| 141 | + return len(cp.certificates) |
| 142 | +} |
| 143 | + |
| 144 | +func (cp *CertPool) PEM() string { |
| 145 | + if cp == nil || len(cp.certificates) == 0 { |
| 146 | + return "" |
| 147 | + } |
| 148 | + |
| 149 | + buffer := bytes.Buffer{} |
| 150 | + |
| 151 | + for _, cert := range cp.Certificates() { |
| 152 | + if err := pem.Encode(&buffer, &pem.Block{Type: "CERTIFICATE", Bytes: cert.Raw}); err != nil { |
| 153 | + return "" |
| 154 | + } |
| 155 | + } |
| 156 | + |
| 157 | + return string(bytes.TrimSpace(buffer.Bytes())) |
| 158 | +} |
| 159 | + |
| 160 | +func (cp *CertPool) PEMSplit() []string { |
| 161 | + if cp == nil || len(cp.certificates) == 0 { |
| 162 | + return nil |
| 163 | + } |
| 164 | + |
| 165 | + pems := make([]string, 0, len(cp.certificates)) |
| 166 | + for _, cert := range cp.Certificates() { |
| 167 | + pems = append(pems, string(bytes.TrimSpace(pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: cert.Raw})))) |
| 168 | + } |
| 169 | + |
| 170 | + return pems |
| 171 | +} |
| 172 | + |
| 173 | +// Get the list of all x509 Certificates in the certificates pool |
| 174 | +func (cp *CertPool) Certificates() []*x509.Certificate { |
| 175 | + hashes := make([][32]byte, 0, len(cp.certificates)) |
| 176 | + for hash := range cp.certificates { |
| 177 | + hashes = append(hashes, hash) |
| 178 | + } |
| 179 | + |
| 180 | + slices.SortFunc(hashes, func(i, j [32]byte) int { |
| 181 | + return bytes.Compare(i[:], j[:]) |
| 182 | + }) |
| 183 | + |
| 184 | + orderedCertificates := make([]*x509.Certificate, 0, len(cp.certificates)) |
| 185 | + for _, hash := range hashes { |
| 186 | + orderedCertificates = append(orderedCertificates, cp.certificates[hash]) |
| 187 | + } |
| 188 | + |
| 189 | + return orderedCertificates |
| 190 | +} |
0 commit comments