github.com/breml/rootcerts@v0.2.16/rootcerts.go (about)

     1  //go:generate go run generate_data.go
     2  
     3  // Package rootcerts provides an embedded copy of the "Mozilla Included CA
     4  // Certificate List" (https://wiki.mozilla.org/CA/Included_Certificates),
     5  // more specifically the "PEM of Root Certificates in Mozilla's Root Store with
     6  // the Websites (TLS/SSL) Trust Bit Enabled"
     7  // (https://ccadb-public.secure.force.com/mozilla/IncludedRootsPEMTxt?TrustBitsInclude=Websites).
     8  // The "Mozilla Included CA Certificate List" is maintained as part of the
     9  // Common CA Database effort (https://golang.org/pkg/crypto/x509/).
    10  // If this package is imported anywhere in the program, then if the crypto/x509
    11  // package cannot find the system certificate pool, it will use this embedded
    12  // information.
    13  //
    14  // Additionally, the usage of this embedded information can be forced by setting
    15  // the the environment variable `GO_ROOTCERTS_ENABLE=1` while  running a
    16  // program, which includes this package.
    17  //
    18  // Importing this package will increase the size of a program by about 250 KB.
    19  //
    20  // This package should normally be imported by a program's main package, not by
    21  // a library. Libraries normally shouldn't decide whether to include the
    22  // "Mozilla Included CA Certificate List" in a program.
    23  package rootcerts
    24  
    25  import (
    26  	"crypto/x509"
    27  	"os"
    28  	_ "unsafe" // for go:linkname
    29  
    30  	"github.com/breml/rootcerts/embedded"
    31  )
    32  
    33  const forceEnableEnvVar = "GO_ROOTCERTS_ENABLE"
    34  
    35  //go:linkname systemRoots crypto/x509.systemRoots
    36  var systemRoots *x509.CertPool
    37  
    38  func init() {
    39  	// Ensure x509.SystemCertPool is executed once
    40  	x509.SystemCertPool() // nolint: errcheck
    41  
    42  	if systemRoots != nil && len(systemRoots.Subjects()) > 0 && os.Getenv(forceEnableEnvVar) != "1" {
    43  		return
    44  	}
    45  
    46  	roots := x509.NewCertPool()
    47  	roots.AppendCertsFromPEM([]byte(embedded.MozillaCACertificatesPEM()))
    48  	systemRoots = roots
    49  }