...

Source file src/github.com/google/certificate-transparency-go/x509util/pem_cert_pool.go

Documentation: github.com/google/certificate-transparency-go/x509util

     1  // Copyright 2016 Google LLC. All Rights Reserved.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package x509util
    16  
    17  import (
    18  	"crypto/sha256"
    19  	"encoding/pem"
    20  	"errors"
    21  	"fmt"
    22  	"os"
    23  
    24  	"github.com/google/certificate-transparency-go/x509"
    25  	"k8s.io/klog/v2"
    26  )
    27  
    28  // String for certificate blocks in BEGIN / END PEM headers
    29  const pemCertificateBlockType string = "CERTIFICATE"
    30  
    31  // PEMCertPool is a wrapper / extension to x509.CertPool. It allows us to access the
    32  // raw certs, which we need to serve get-roots request and has stricter handling on loading
    33  // certs into the pool. CertPool ignores errors if at least one cert loads correctly but
    34  // PEMCertPool requires all certs to load.
    35  type PEMCertPool struct {
    36  	// maps from sha-256 to certificate, used for dup detection
    37  	fingerprintToCertMap map[[sha256.Size]byte]x509.Certificate
    38  	rawCerts             []*x509.Certificate
    39  	certPool             *x509.CertPool
    40  }
    41  
    42  // NewPEMCertPool creates a new, empty, instance of PEMCertPool.
    43  func NewPEMCertPool() *PEMCertPool {
    44  	return &PEMCertPool{fingerprintToCertMap: make(map[[sha256.Size]byte]x509.Certificate), certPool: x509.NewCertPool()}
    45  }
    46  
    47  // AddCert adds a certificate to a pool. Uses fingerprint to weed out duplicates.
    48  // cert must not be nil.
    49  func (p *PEMCertPool) AddCert(cert *x509.Certificate) {
    50  	fingerprint := sha256.Sum256(cert.Raw)
    51  	_, ok := p.fingerprintToCertMap[fingerprint]
    52  
    53  	if !ok {
    54  		p.fingerprintToCertMap[fingerprint] = *cert
    55  		p.certPool.AddCert(cert)
    56  		p.rawCerts = append(p.rawCerts, cert)
    57  	}
    58  }
    59  
    60  // Included indicates whether the given cert is included in the pool.
    61  func (p *PEMCertPool) Included(cert *x509.Certificate) bool {
    62  	fingerprint := sha256.Sum256(cert.Raw)
    63  	_, ok := p.fingerprintToCertMap[fingerprint]
    64  	return ok
    65  }
    66  
    67  // AppendCertsFromPEM adds certs to the pool from a byte slice assumed to contain PEM encoded data.
    68  // Skips over non certificate blocks in the data. Returns true if all certificates in the
    69  // data were parsed and added to the pool successfully and at least one certificate was found.
    70  func (p *PEMCertPool) AppendCertsFromPEM(pemCerts []byte) (ok bool) {
    71  	for len(pemCerts) > 0 {
    72  		var block *pem.Block
    73  		block, pemCerts = pem.Decode(pemCerts)
    74  		if block == nil {
    75  			break
    76  		}
    77  		if block.Type != pemCertificateBlockType || len(block.Headers) != 0 {
    78  			continue
    79  		}
    80  
    81  		cert, err := x509.ParseCertificate(block.Bytes)
    82  		if x509.IsFatal(err) {
    83  			klog.Warningf("error parsing PEM certificate: %v", err)
    84  			return false
    85  		}
    86  
    87  		p.AddCert(cert)
    88  		ok = true
    89  	}
    90  
    91  	return
    92  }
    93  
    94  // AppendCertsFromPEMFile adds certs from a file that contains concatenated PEM data.
    95  func (p *PEMCertPool) AppendCertsFromPEMFile(pemFile string) error {
    96  	pemData, err := os.ReadFile(pemFile)
    97  	if err != nil {
    98  		return fmt.Errorf("failed to load PEM certs file: %v", err)
    99  	}
   100  
   101  	if !p.AppendCertsFromPEM(pemData) {
   102  		return errors.New("failed to parse PEM certs file")
   103  	}
   104  	return nil
   105  }
   106  
   107  // Subjects returns a list of the DER-encoded subjects of all of the certificates in the pool.
   108  func (p *PEMCertPool) Subjects() (res [][]byte) {
   109  	return p.certPool.Subjects()
   110  }
   111  
   112  // CertPool returns the underlying CertPool.
   113  func (p *PEMCertPool) CertPool() *x509.CertPool {
   114  	return p.certPool
   115  }
   116  
   117  // RawCertificates returns a list of the raw bytes of certificates that are in this pool
   118  func (p *PEMCertPool) RawCertificates() []*x509.Certificate {
   119  	return p.rawCerts
   120  }
   121  

View as plain text