Documentation
¶
Overview ¶
The certs package provides functions for handling TLS certificates and keys.
The certs package provides functions for handling TLS certificates and keys.
The certs package provides functions for handling TLS certificates and keys.
Index ¶
- Constants
- func AddCertChainToKeyStore(h host.Host, path string, password config.Secret, alias string, key PrivateKey, ...) error
- func AddRootsToTrustStore(h host.Host, path string, password config.Secret, roots ...*x509.Certificate) error
- func CertificateComments(cert *x509.Certificate, titles ...string) []byte
- func CheckKeyMatch(key PrivateKey, cert *x509.Certificate) bool
- func IndexPrivateKey(keys []PrivateKey, cert *x509.Certificate) int
- func IsValidLeafCert(cert *x509.Certificate) bool
- func IsValidRootCA(cert *x509.Certificate) bool
- func IsValidSigningCA(cert *x509.Certificate) bool
- func ParseCertChain(cert ...*x509.Certificate) (leaf *x509.Certificate, intermediates []*x509.Certificate, ...)
- func PrivateKeyComments(key PrivateKey, titles ...string) []byte
- func PublicKey(key PrivateKey) (publicKey crypto.PublicKey, err error)
- func ReadCACertPool(h host.Host, path string) (pool *x509.CertPool, ok bool)
- func ReadCertPool(h host.Host, path string) (pool *x509.CertPool)
- func ReadCertificates(h host.Host, path string) (certs []*x509.Certificate, err error)
- func ReadCertificatesFrom(r io.Reader) (certs []*x509.Certificate, err error)
- func Template(cn string, options ...TemplateOption) (template *x509.Certificate)
- func UpdateCACertsFileFromTrustStore(h host.Host, truststorePath string, truststorePassword config.Secret, ...) (updated bool, err error)
- func UpdateCACertsFiles(h host.Host, basePath string, roots ...*x509.Certificate) (updated bool, err error)
- func Verify(certs ...*x509.Certificate) (ok bool)
- func WriteCertificates(h host.Host, certPath string, certs ...*x509.Certificate) (err error)
- func WriteCertificatesAndKeyTo(w io.Writer, key PrivateKey, certChain ...*x509.Certificate) (n int, err error)
- func WriteCertificatesTo(w io.Writer, certs ...*x509.Certificate) (n int, err error)
- func WriteNewRootCert(basefilepath string, cn string, keytype KeyType) (root *x509.Certificate, err error)
- func WriteNewSigningCert(basefilepath string, rootCert *x509.Certificate, rootKey PrivateKey, cn string) (signing *x509.Certificate, err error)
- func WriteNewSigningCertTo(w io.Writer, rootCert *x509.Certificate, rootKey PrivateKey, cn string) (n int, err error)
- func WritePrivateKey(h host.Host, keypath string, key PrivateKey) (err error)
- func WritePrivateKeyTo(w io.Writer, key PrivateKey) (n int, err error)
- func WritePublicKeyTo(w io.Writer, pubKey any) (n int, err error)
- func WriteTrustStore(h host.Host, path string, password config.Secret, roots ...*x509.Certificate) error
- type CertificateBundle
- type CreateCertOption
- type KeyStore
- type KeyType
- type PrivateKey
- func CreateCertificate(template, parent *x509.Certificate, signingKey PrivateKey, ...) (cert *x509.Certificate, key PrivateKey, err error)
- func DecodePEM(data ...[]byte) (leaf *x509.Certificate, intermediates, roots []*x509.Certificate, ...)
- func GenerateKey(keyType KeyType) (privateKey PrivateKey, publicKey any, err error)
- func ReadPrivateKey(h host.Host, file string) (key PrivateKey, err error)
- func ReadPrivateKeyFromPEM(pemData []byte) (key PrivateKey, err error)
- type TemplateOption
- func BasicConstraintsValid() TemplateOption
- func DNSNames(names ...string) TemplateOption
- func Days(days int) TemplateOption
- func EmailAddresses(emails ...string) TemplateOption
- func ExtKeyUsage(eku ...x509.ExtKeyUsage) TemplateOption
- func IPAddresses(ips ...string) TemplateOption
- func IsCA() TemplateOption
- func KeyUsage(ku x509.KeyUsage) TemplateOption
- func MaxPathLen(len int) TemplateOption
- func SANsFromCert(cert *x509.Certificate) TemplateOption
- func URIs(uris ...string) TemplateOption
Constants ¶
const ( PEMExtension = ".pem" KEYExtension = ".key" KeystoreExtension = ".db" )
const DefaultKeyType = ECDH
DefaultKeyType is the default key type
Variables ¶
This section is empty.
Functions ¶
func AddCertChainToKeyStore ¶
func AddCertChainToKeyStore(h host.Host, path string, password config.Secret, alias string, key PrivateKey, certChain ...*x509.Certificate) error
AddCertChainToKeyStore adds a private key and certificate chain to the keystore at the specified path on the given host. If the keystore does not exist, it is created. If password is nil, "changeit" is used.
The alias parameter specifies the alias under which to store the key and certificate chain.
Any existing entry with the same alias is deleted before adding the new key and certificate chain.
The certChain is not validated; the caller is responsible for ensuring that it is correct.
func AddRootsToTrustStore ¶
func AddRootsToTrustStore(h host.Host, path string, password config.Secret, roots ...*x509.Certificate) error
AddRootsToTrustStore adds the given root certificates to the truststore at the specified path on the given host. If the truststore does not exist, it is created. If password is nil, "changeit" is used.
Any existing entries with the same alias as a root certificate are deleted before adding the new root certificates. Aliases are derived from the Subject Common Name of each certificate.
Any certificates that are not root CAs are ignored.
func CertificateComments ¶
func CertificateComments(cert *x509.Certificate, titles ...string) []byte
CertificateComments returns a byte slice containing comments about the given x509 certificate. If titles are provided they are included at the top of the comments, if not a default title of "Certificate" is used.
func CheckKeyMatch ¶
func CheckKeyMatch(key PrivateKey, cert *x509.Certificate) bool
CheckKeyMatch returns true if the DER encoded private key matches the public key in the provided x509 certificate.
func IndexPrivateKey ¶
func IndexPrivateKey(keys []PrivateKey, cert *x509.Certificate) int
IndexPrivateKey tests the slice DER encoded private keys against the x509 cert and returns the index of the first match, or -1 if none of the keys match.
func IsValidLeafCert ¶
func IsValidLeafCert(cert *x509.Certificate) bool
IsValidLeafCert returns true if the provided certificate is a valid leaf certificate. A valid leaf certificate is not a CA, has the DigitalSignature key usage, has at least one extended key usage, and is between its NotBefore and NotAfter dates.
func IsValidRootCA ¶
func IsValidRootCA(cert *x509.Certificate) bool
IsValidRootCA returns true if the provided certificate is a valid root CA certificate. A valid root CA is self-signed and has appropriate basic constraints as well as either an empty AuthorityKeyId or one that matches the SubjectKeyId. It must also be between its NotBefore and NotAfter dates.
func IsValidSigningCA ¶
func IsValidSigningCA(cert *x509.Certificate) bool
IsValidSigningCA returns true if the provided certificate is a valid signing CA certificate. A valid signing CA is a CA certificate with appropriate basic constraints for signing (MaxPathLenZero) and is between its NotBefore and NotAfter dates.
func ParseCertChain ¶
func ParseCertChain(cert ...*x509.Certificate) (leaf *x509.Certificate, intermediates []*x509.Certificate, root *x509.Certificate, err error)
ParseCertChain tries to verify the provided certificate chain. It returns the leaf certificate, any intermediates and any root certificate found in the chain. It returns an error if verification fails. The first certificate in the certs provided is assumed to be the leaf certificate. The order of the remaining certificates does not matter.
func PrivateKeyComments ¶
func PrivateKeyComments(key PrivateKey, titles ...string) []byte
PrivateKeyComments returns a byte slice containing comments about the given private key. If titles are provided they are included at the top of the comments, if not a default title of "Private Key" is used.
func PublicKey ¶
func PublicKey(key PrivateKey) (publicKey crypto.PublicKey, err error)
PublicKey parses the DER encoded private key enclave and returns the public key if successful. It will first try as PKCS#8 and then PKCS#1 if that fails and finally as SEC1 (EC). Returns an error if parsing fails.
func ReadCACertPool ¶
ReadCACertPool reads a local PEM file containing CA certificates and returns a *x509.CertPool and the number of valid root CAs found. Any certificates that are not valid root CAs are skipped.
func ReadCertPool ¶
ReadCertPool returns a certificate pool loaded from the file on host h at path. If there is any error a nil pointer is returned.
func ReadCertificates ¶
ReadCertificates reads and parses all certificates from the PEM file on host h at path. If the files cannot be read an error is returned. If no certificates are found in the file then no error is returned. The returned certificates are not validated beyond the parsing functionality of the underlying Go crypto/x509 package.
func ReadCertificatesFrom ¶ added in v1.27.0
func ReadCertificatesFrom(r io.Reader) (certs []*x509.Certificate, err error)
ReadCertificatesFrom reads and parses all certificates from the given io.Reader. If the reader cannot be read an error is returned. If no certificates are found in the reader then no error is returned. The returned certificates are not validated beyond the parsing functionality of the underlying Go crypto/x509 package.
func Template ¶
func Template(cn string, options ...TemplateOption) (template *x509.Certificate)
Template creates a basic x509 certificate template with the given parameters. The caller can modify the template as needed before using it to create a certificate. If duration is zero, a default of 365 days is used.
func UpdateCACertsFileFromTrustStore ¶
func UpdateCACertsFileFromTrustStore(h host.Host, truststorePath string, truststorePassword config.Secret, caBundlePath string) (updated bool, err error)
UpdateCACertsFileFromTrustStore updates the CA bundle file at caBundlePath with any root CA certificates found in the truststore at truststorePath. If password is nil, "changeit" is used. It returns updated true if the CA bundle file was updated.
func UpdateCACertsFiles ¶
func UpdateCACertsFiles(h host.Host, basePath string, roots ...*x509.Certificate) (updated bool, err error)
UpdateCACertsFiles appends the given root certificates to the CA files at the specified basePath prefix on the given host. It writes both a PEM files and a Java truststore. It ensures that all the given certificates are present in the file, appending any that are missing. If the file does not exist or is empty, it will be created with the provided certificates. Returns true if the file was updated (certificates added or file created), false if no changes were made.
Returns an error if writing the file fails.
Any non-root CA or expired certificates in the provided certs slice are ignored. Additionally, any non-root CA or expired certificates already present in the existing root certificate file are removed.
The caller is responsible for locking access to the root cert file if concurrent access is possible.
func Verify ¶
func Verify(certs ...*x509.Certificate) (ok bool)
Verify verifies the provided certificates as a chain. It returns true if verification is successful. Only one leaf, zero or more intermediates and zero or one root certificate should be provided. If there is no leaf certificate then the first intermediate is used as the leaf. If there is only one or more root certificates then the function returns true.
func WriteCertificates ¶
WriteCertificates concatenate certs in PEM format and writes to path on host h. Certificates that are expired are skipped, only errors from writing the resulting file are returned. Any existing file is overwritten, and permissions are maintained as per os.WriteFile. Certificates are written in the order provided. Directories in the path are created with 0755 permissions if they do not already exist. The certificate file is created with 0644 permissions (before umask) unless a file already exists.
func WriteCertificatesAndKeyTo ¶
func WriteCertificatesAndKeyTo(w io.Writer, key PrivateKey, certChain ...*x509.Certificate) (n int, err error)
WriteCertificatesAndKeyTo writes the given certificate and optional private key in PEM format to the provided io.Writer. The total number of bytes written and any error encountered are returned.
func WriteCertificatesTo ¶
WriteCertificatesTo writes the given certificates in PEM format to the provided io.Writer. Certificates that are expired are skipped. The total number of bytes written and any error encountered are returned.
func WriteNewRootCert ¶
func WriteNewRootCert(basefilepath string, cn string, keytype KeyType) (root *x509.Certificate, err error)
WriteNewRootCert creates a new root certificate and private key and writes it locally with dir and file basefilepath with .pem and .key extensions. If overwrite is true then any existing certificate and key is overwritten.
func WriteNewSigningCert ¶
func WriteNewSigningCert(basefilepath string, rootCert *x509.Certificate, rootKey PrivateKey, cn string) (signing *x509.Certificate, err error)
WriteNewSigningCert creates a new signing certificate and private key with the path and file base name basefilepath. You must provide a valid root certificate and key in rootbasefilepath. If overwrite is true than any existing cert and key are overwritten.
The certificate is returned on success, but the private key is not.
func WriteNewSigningCertTo ¶
func WriteNewSigningCertTo(w io.Writer, rootCert *x509.Certificate, rootKey PrivateKey, cn string) (n int, err error)
WriteNewSigningCertTo creates a new signing certificate and private key signed by the given root certificate and key, writing the resulting private key and certificate in PEM format to the provided io.Writer. The total number of bytes written and any error encountered are returned.
func WritePrivateKey ¶
func WritePrivateKey(h host.Host, keypath string, key PrivateKey) (err error)
WritePrivateKey writes a DER encoded private key as a PKCS#8 encoded PEM file to path on host h. sets file permissions to 0600 (before umask). Directories in the path are created with 0755 permissions if they do not already exist. Any existing file is overwritten, and permissions are maintained as per os.WriteFile.
func WritePrivateKeyTo ¶
func WritePrivateKeyTo(w io.Writer, key PrivateKey) (n int, err error)
WritePrivateKeyTo writes the given private key in PEM format to the provided io.Writer. The total number of bytes written and any error encountered are returned.
func WriteTrustStore ¶
func WriteTrustStore(h host.Host, path string, password config.Secret, roots ...*x509.Certificate) error
WriteTrustStore writes the given root certificates to a keystore at the specified path on the given host. If password is nil, "changeit" is used. Any certificates that are not valid root CAs are ignored. Any existing file is overwritten.
Types ¶
type CertificateBundle ¶
type CertificateBundle struct {
Leaf *x509.Certificate
FullChain []*x509.Certificate
Root *x509.Certificate
Key PrivateKey
Valid bool
// RootIsSystem is true if the root certificate is from the system
// pool. We still add certs to the ca-bundle as the core Geneos
// components can only use one chain file.
RootIsSystem bool
}
CertificateBundle holds a leaf certificate and a certificate chain along with an optional private key (of the first cert in the chain, which is normally a leaf) and a root certificate. If there is no leaf certificate then Leaf is nil and FullChain[0] is the first intermediate, if any.
Valid should be set to true if the bundle has been verified as consistent from FullChain[0] to root and the private key applies FullChain[0] (but without revocation checks).
func P12ToCertBundle ¶
func P12ToCertBundle(pfxPath string, password config.Secret) (certBundle *CertificateBundle, err error)
func ParsePEM ¶
func ParsePEM(data ...[]byte) (bundle *CertificateBundle, err error)
ParsePEM parses PEM formatted data blocks and returns a CertificateBundle. If it contains a verifiable chain and a private key that matches the leaf certificate it then it sets Valid to true. Only if Valid is true can the order of the certificates be relied upon.
Encrypted private keys are not supported and will be skipped.
type CreateCertOption ¶ added in v1.27.0
type CreateCertOption func(*createCertOptions) error
func WithKeyType ¶
func WithKeyType(keytype KeyType) CreateCertOption
type KeyStore ¶
func ReadKeystore ¶
ReadKeystore returns a keystore.
If password is nil, "changeit" is used.
The file is first attempted to be read as a modern keystore, if that fails it is tried as a JCEKS formatted keystore.
func (*KeyStore) AddKeystoreKey ¶
func (k *KeyStore) AddKeystoreKey(alias string, key PrivateKey, password config.Secret, certs ...*x509.Certificate) (err error)
AddKeystoreKey adds a private key and certificates to the keystore.
If password is nil it uses "changeit" as the keystore password.
func (*KeyStore) AddTrustedCertificate ¶
func (k *KeyStore) AddTrustedCertificate(alias string, cert *x509.Certificate) (err error)
AddTrustedCertificate adds a trusted certificate to the keystore.
type KeyType ¶
type KeyType string
func ParsePrivateKey ¶
func ParsePrivateKey(key PrivateKey) (privatekey any, keytype KeyType, err error)
ParsePrivateKey parses the DER encoded private key enclave, first as PKCS#8 and then as a PKCS#1 and finally as SEC1 (EC) if that fails. It returns the private key or an error.
type PrivateKey ¶ added in v1.27.0
type PrivateKey []byte
func CreateCertificate ¶
func CreateCertificate(template, parent *x509.Certificate, signingKey PrivateKey, options ...CreateCertOption) (cert *x509.Certificate, key PrivateKey, err error)
CreateCertificate creates a new certificate and private key given the signing cert and key. Returns a certificate and private key. Keys are usually PKCS#8 encoded and so need parsing after unsealing.
To create a private key of a specific type, use the WithKeyType option. If the signing key is not nil and the WithKeyType option is not used then the new key will be of the same type as the signing key. If there is no signing key and the WithKeyType option is not used then a default key type will be used.
func DecodePEM ¶
func DecodePEM(data ...[]byte) (leaf *x509.Certificate, intermediates, roots []*x509.Certificate, keys []PrivateKey, err error)
DecodePEM decodes PEM formatted data and returns the first leaf certificate and slices of certificates (intermediates, roots) and private keys found. Encrypted private keys and other types of blocks are not supported and will be skipped. If there are no certificates or private keys found then empty clients are returned without error.
Unknown blocks are skipped.
func GenerateKey ¶
func GenerateKey(keyType KeyType) (privateKey PrivateKey, publicKey any, err error)
GenerateKey returns a PKCS#8 DER encoded private key as an enclave using the keyType specified.
func ReadPrivateKey ¶
func ReadPrivateKey(h host.Host, file string) (key PrivateKey, err error)
ReadPrivateKey reads file on host h as an unencrypted, PEM-encoded private key and saves the der format key
func ReadPrivateKeyFromPEM ¶
func ReadPrivateKeyFromPEM(pemData []byte) (key PrivateKey, err error)
ReadPrivateKeyFromPEM reads a PEM-encoded private key from the given byte slice and returns it as a PrivateKey. The input data should contain an unencrypted private key in PEM format. If the key cannot be found or parsed, an error is returned.
type TemplateOption ¶
type TemplateOption func(*templateOptions)
func BasicConstraintsValid ¶
func BasicConstraintsValid() TemplateOption
func DNSNames ¶
func DNSNames(names ...string) TemplateOption
func Days ¶
func Days(days int) TemplateOption
func EmailAddresses ¶
func EmailAddresses(emails ...string) TemplateOption
func ExtKeyUsage ¶
func ExtKeyUsage(eku ...x509.ExtKeyUsage) TemplateOption
func IPAddresses ¶
func IPAddresses(ips ...string) TemplateOption
func IsCA ¶
func IsCA() TemplateOption
func KeyUsage ¶
func KeyUsage(ku x509.KeyUsage) TemplateOption
func MaxPathLen ¶
func MaxPathLen(len int) TemplateOption
func SANsFromCert ¶
func SANsFromCert(cert *x509.Certificate) TemplateOption
SANsFromCert sets the Subject Alternative Names from an existing certificate
func URIs ¶
func URIs(uris ...string) TemplateOption