certutil

package
v1.20210818.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 18, 2021 License: MIT Imports: 14 Imported by: 0

Documentation

Overview

Package certutil contains helpers for working with x509 certificates.

The most common use case is parsing and evaluating key details of the cert like the "NotAfter" date.

Index

Constants

View Source
const (
	BlockTypeCertificate   = "CERTIFICATE"
	BlockTypeRSAPrivateKey = "RSA PRIVATE KEY"
)

BlockTypes

View Source
const (
	DefaultCANotAfterYears     = 10
	DefaultClientNotAfterYears = 1
	DefaultServerNotAfterYears = 5
)

Not After defaults.

View Source
const (
	ErrInvalidCertPEM ex.Class = "failed to add cert to pool as pem"
)

Errors

View Source
const (
	ErrTLSPathsUnset ex.Class = "tls cert or key path unset; cannot continue"
)

Error constants.

Variables

View Source
var DefaultOptionsCertificateAuthority = CertOptions{
	Certificate: x509.Certificate{
		IsCA:                  true,
		KeyUsage:              x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign,
		BasicConstraintsValid: true,
	},
	NotAfterProvider: func() time.Time { return time.Now().UTC().AddDate(DefaultCANotAfterYears, 0, 0) },
}

DefaultOptionsCertificateAuthority are the default options for certificate authorities.

View Source
var DefaultOptionsClient = CertOptions{
	Certificate: x509.Certificate{
		ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
		KeyUsage:    x509.KeyUsageDigitalSignature,
	},
	NotAfterProvider: func() time.Time { return time.Now().UTC().AddDate(DefaultClientNotAfterYears, 0, 0) },
}

DefaultOptionsClient are the default create cert options for client certificates.

View Source
var DefaultOptionsServer = CertOptions{
	Certificate: x509.Certificate{
		ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
		KeyUsage:    x509.KeyUsageDigitalSignature,
	},
	NotAfterProvider: func() time.Time { return time.Now().UTC().AddDate(DefaultServerNotAfterYears, 0, 0) },
}

DefaultOptionsServer are the default create cert options for server certificates.

Functions

func BytesWithError

func BytesWithError(bytes []byte, err error) ([]byte, error)

BytesWithError returns a bytes error response with the error as an ex.

func CommonNamesForCertPEM

func CommonNamesForCertPEM(certPEM []byte) ([]string, error)

CommonNamesForCertPEM returns the common names from a cert pair.

func CreateCertPool added in v1.20201204.1

func CreateCertPool(keyPairs ...KeyPair) (*x509.CertPool, error)

CreateCertPool extends an empty pool with a given set of certs.

func ExtendSystemCertPool added in v1.20201204.1

func ExtendSystemCertPool(keyPairs ...KeyPair) (*x509.CertPool, error)

ExtendSystemCertPool extends the system ca pool with a given list of ca cert key pairs.

func MustBytes

func MustBytes(contents []byte, err error) []byte

MustBytes panics on an error or returns the contents.

func NewClientTLSConfig added in v1.20201204.1

func NewClientTLSConfig(clientCert KeyPair, certificateAuthorities []KeyPair) (*tls.Config, error)

NewClientTLSConfig returns a new client tls config. This is useful for making mutual tls calls to servers that require it.

func ParseCertPEM

func ParseCertPEM(certPem []byte) (output []*x509.Certificate, err error)

ParseCertPEM parses the cert portion of a cert pair.

func ReadFiles

func ReadFiles(files ...string) (data [][]byte, err error)

ReadFiles reads a list of files as bytes.

func ReadPrivateKeyPEMFromPath added in v1.20201204.1

func ReadPrivateKeyPEMFromPath(keyPath string) (*rsa.PrivateKey, error)

ReadPrivateKeyPEMFromPath reads a private key pem from a given path.

func ResolveCertOptions added in v1.20201204.1

func ResolveCertOptions(createOptions *CertOptions, options ...CertOption) error

ResolveCertOptions resolves the common create cert options.

Types

type CertBundle

type CertBundle struct {
	PrivateKey      *rsa.PrivateKey
	PublicKey       *rsa.PublicKey
	Certificates    []x509.Certificate
	CertificateDERs [][]byte
}

CertBundle is the packet of information for a certificate.

func CreateCertificateAuthority added in v1.20201204.1

func CreateCertificateAuthority(options ...CertOption) (*CertBundle, error)

CreateCertificateAuthority creates a ca cert bundle from a given set of options. The cert bundle can be used to generate client and server certificates.

func CreateClient

func CreateClient(commonName string, ca *CertBundle, options ...CertOption) (*CertBundle, error)

CreateClient creates a client cert bundle associated with a given common name.

The CA must be passed in as a CertBundle.

Example:

ca, err := certutil.NewCertBundle(certutil.KeyPairFromPaths("ca.crt", "ca.key"))
if err != nil {
	return err
}
client, err := CreateClient("foo.bar.com", ca)

func CreateSelfServerCert added in v1.20201204.1

func CreateSelfServerCert(commonName string, options ...CertOption) (*CertBundle, error)

CreateSelfServerCert creates a self signed server certificate bundle.

func CreateServer

func CreateServer(commonName string, ca *CertBundle, options ...CertOption) (*CertBundle, error)

CreateServer creates a ca cert bundle.

func NewCertBundle

func NewCertBundle(keyPair KeyPair) (*CertBundle, error)

NewCertBundle returns a new cert bundle from a given key pair, which can denote the raw PEM encoded contents of the public and private key portions of the cert, or paths to files. The CertBundle itself is the parsed public key, private key, and individual certificates for the pair.

func (CertBundle) CertPEM added in v1.20201204.1

func (cb CertBundle) CertPEM() ([]byte, error)

CertPEM returns the cert portion of the certificate DERs as a byte array.

func (CertBundle) CertPool

func (cb CertBundle) CertPool() (*x509.CertPool, error)

CertPool returns the bundle as a cert pool.

func (CertBundle) CommonNames

func (cb CertBundle) CommonNames() ([]string, error)

CommonNames returns the cert bundle common name(s).

func (*CertBundle) GenerateKeyPair added in v1.20201204.1

func (cb *CertBundle) GenerateKeyPair() (output KeyPair, err error)

GenerateKeyPair returns a serialized key pair for the cert bundle.

func (CertBundle) KeyPEM added in v1.20201204.1

func (cb CertBundle) KeyPEM() ([]byte, error)

KeyPEM returns the cert portion of the certificate DERs as a byte array.

func (*CertBundle) MustGenerateKeyPair added in v1.20201204.1

func (cb *CertBundle) MustGenerateKeyPair() KeyPair

MustGenerateKeyPair returns a serialized version of the bundle as a key pair and panics if there is an error.

func (CertBundle) ServerConfig added in v1.20210402.2

func (cb CertBundle) ServerConfig() (*tls.Config, error)

ServerConfig returns a tls.Config for this bundle as a server certificate.

func (*CertBundle) WithParent

func (cb *CertBundle) WithParent(parent *CertBundle)

WithParent adds a parent certificate to the certificate chain. It is used typically to add the certificate authority.

func (CertBundle) WriteCertPem

func (cb CertBundle) WriteCertPem(w io.Writer) error

WriteCertPem writes the public key portion of the cert to a given writer.

func (CertBundle) WriteKeyPem

func (cb CertBundle) WriteKeyPem(w io.Writer) error

WriteKeyPem writes the certificate key as a pem.

type CertFileWatcher added in v1.20201204.1

type CertFileWatcher struct {
	*async.Latch

	Certificate *tls.Certificate

	CertPath     string
	KeyPath      string
	PollInterval time.Duration

	OnReload func(*CertFileWatcher, error)
}

CertFileWatcher reloads a cert key pair when there is a change, e.g. cert renewal

func NewCertFileWatcher added in v1.20201204.1

func NewCertFileWatcher(certPath, keyPath string, opts ...CertFileWatcherOption) (*CertFileWatcher, error)

NewCertFileWatcher creates a new CertReloader object with a reload delay

func (*CertFileWatcher) GetCertificate added in v1.20201204.1

func (cw *CertFileWatcher) GetCertificate(_ *tls.ClientHelloInfo) (*tls.Certificate, error)

GetCertificate gets the cached certificate, it blocks when the `cert` field is being updated

func (*CertFileWatcher) PollIntervalOrDefault added in v1.20201204.1

func (cw *CertFileWatcher) PollIntervalOrDefault() time.Duration

PollIntervalOrDefault returns the polling interval or a default.

func (*CertFileWatcher) Reload added in v1.20201204.1

func (cw *CertFileWatcher) Reload() (err error)

Reload forces the reload of the underlying certificate.

func (*CertFileWatcher) Start added in v1.20201204.1

func (cw *CertFileWatcher) Start() error

Start watches the cert and triggers a reload on change

func (*CertFileWatcher) Stop added in v1.20201204.1

func (cw *CertFileWatcher) Stop() error

Stop stops the watcher.

type CertFileWatcherOption added in v1.20201204.1

type CertFileWatcherOption func(*CertFileWatcher) error

CertFileWatcherOption is an option for a cert watcher.

func OptCertFileWatcherOnReload added in v1.20201204.1

func OptCertFileWatcherOnReload(handler func(*CertFileWatcher, error)) CertFileWatcherOption

OptCertFileWatcherOnReload sets the on reload handler. If you need to capture *every* reload of the cert, including the initial one in the constructor you must use this option.

func OptCertFileWatcherPollInterval added in v1.20201204.1

func OptCertFileWatcherPollInterval(d time.Duration) CertFileWatcherOption

OptCertFileWatcherPollInterval sets the poll interval .

type CertManager

type CertManager struct {
	sync.RWMutex
	TLSConfig   *tls.Config
	ClientCerts map[string][]byte
}

CertManager is a pool of client certs.

func NewCertManager

func NewCertManager(options ...CertManagerOption) *CertManager

NewCertManager returns a new cert manager.

func NewCertManagerWithKeyPairs

func NewCertManagerWithKeyPairs(server KeyPair, certificateAuthorities []KeyPair, clients ...KeyPair) (*CertManager, error)

NewCertManagerWithKeyPairs returns a new cert pool from key pairs.

func (*CertManager) AddClientCert

func (cm *CertManager) AddClientCert(clientCert []byte) error

AddClientCert adds a client cert to the bunde and refreshes the bundle.

func (*CertManager) ClientCertUIDs

func (cm *CertManager) ClientCertUIDs() (output []string)

ClientCertUIDs returns all the client cert uids.

func (*CertManager) GetConfigForClient

func (cm *CertManager) GetConfigForClient(sni *tls.ClientHelloInfo) (config *tls.Config, _ error)

GetConfigForClient gets a tls config for a given client hello.

func (*CertManager) HasClientCert

func (cm *CertManager) HasClientCert(uid string) (has bool)

HasClientCert returns if the manager has a client cert.

func (*CertManager) RefreshClientCerts added in v1.20201204.1

func (cm *CertManager) RefreshClientCerts() error

RefreshClientCerts reloads the client cert bundle.

func (*CertManager) RemoveClientCert

func (cm *CertManager) RemoveClientCert(uid string) error

RemoveClientCert removes a client cert by uid.

func (*CertManager) UpdateClientCerts

func (cm *CertManager) UpdateClientCerts(clientCerts map[string][]byte) error

UpdateClientCerts sets the client cert bundle fully.

type CertManagerOption added in v1.20201204.1

type CertManagerOption func(*CertManager)

CertManagerOption is an option for a cert manager.

func OptCertManagerClientCerts added in v1.20201204.1

func OptCertManagerClientCerts(client *x509.CertPool) CertManagerOption

OptCertManagerClientCerts sets a field on the cert manager.

func OptCertManagerRootCAs added in v1.20201204.1

func OptCertManagerRootCAs(pool *x509.CertPool) CertManagerOption

OptCertManagerRootCAs sets a field on the cert manager.

func OptCertManagerServerCerts added in v1.20201204.1

func OptCertManagerServerCerts(server ...tls.Certificate) CertManagerOption

OptCertManagerServerCerts sets a field on the cert manager.

type CertOption added in v1.20201204.1

type CertOption func(*CertOptions) error

CertOption is an option for creating certs.

func OptAddDNSNames added in v1.20201204.1

func OptAddDNSNames(dnsNames ...string) CertOption

OptAddDNSNames adds valid dns names for the cert.

func OptDNSNames added in v1.20201204.1

func OptDNSNames(dnsNames ...string) CertOption

OptDNSNames sets valid dns names for the cert.

func OptIsCA added in v1.20201204.1

func OptIsCA(isCA bool) CertOption

OptIsCA sets the is certificate authority flag.

func OptKeyUsage added in v1.20201204.1

func OptKeyUsage(keyUsage x509.KeyUsage) CertOption

OptKeyUsage sets the key usage flags.

func OptNotAfter added in v1.20201204.1

func OptNotAfter(notAfter time.Time) CertOption

OptNotAfter sets the not after time.

func OptNotBefore added in v1.20201204.1

func OptNotBefore(notBefore time.Time) CertOption

OptNotBefore sets the not before time.

func OptPrivateKey added in v1.20201204.1

func OptPrivateKey(privateKey *rsa.PrivateKey) CertOption

OptPrivateKey sets the private key to use when generating the certificate. If this option isn't provided, a new one is generated.

func OptPrivateKeyFromPath added in v1.20201204.1

func OptPrivateKeyFromPath(path string) CertOption

OptPrivateKeyFromPath reads a private key from a given path and parses it as PKCS1PrivateKey.

func OptSerialNumber added in v1.20201204.1

func OptSerialNumber(serialNumber *big.Int) CertOption

OptSerialNumber sets the serial number for the certificate. If this option isn't provided, a random one is generated.

func OptSubjectAlternateNames added in v1.20201204.1

func OptSubjectAlternateNames(dnsNames ...string) CertOption

OptSubjectAlternateNames sets the subject alternate names.

func OptSubjectCommonName added in v1.20201204.1

func OptSubjectCommonName(commonName string) CertOption

OptSubjectCommonName sets the subject common name.

func OptSubjectCountry added in v1.20201204.1

func OptSubjectCountry(country ...string) CertOption

OptSubjectCountry sets the subject country names.

func OptSubjectLocality added in v1.20201204.1

func OptSubjectLocality(locality ...string) CertOption

OptSubjectLocality sets the subject locality names.

func OptSubjectOrganization added in v1.20201204.1

func OptSubjectOrganization(organization ...string) CertOption

OptSubjectOrganization sets the subject organization names.

func OptSubjectProvince added in v1.20201204.1

func OptSubjectProvince(province ...string) CertOption

OptSubjectProvince sets the subject province names.

type CertOptions added in v1.20201204.1

type CertOptions struct {
	x509.Certificate
	PrivateKey        *rsa.PrivateKey
	NotBeforeProvider func() time.Time
	NotAfterProvider  func() time.Time
}

CertOptions are required arguments when creating certificates.

type KeyPair

type KeyPair struct {
	Cert     string `json:"cert,omitempty" yaml:"cert,omitempty"`
	CertPath string `json:"certPath,omitempty" yaml:"certPath,omitempty"`
	Key      string `json:"key,omitempty" yaml:"key,omitempty"`
	KeyPath  string `json:"keyPath,omitempty" yaml:"keyPath,omitempty"`
}

KeyPair is an x509 pem key pair as strings.

func NewKeyPairFromPaths added in v1.20201204.1

func NewKeyPairFromPaths(certPath, keyPath string) KeyPair

NewKeyPairFromPaths returns a key pair from paths.

func (KeyPair) CertBytes

func (kp KeyPair) CertBytes() ([]byte, error)

CertBytes returns the key pair cert bytes.

func (KeyPair) IsCertPath added in v1.20201204.1

func (kp KeyPair) IsCertPath() bool

IsCertPath returns if the keypair cert is a path.

func (KeyPair) IsKeyPath added in v1.20201204.1

func (kp KeyPair) IsKeyPath() bool

IsKeyPath returns if the keypair key is a path.

func (KeyPair) IsZero

func (kp KeyPair) IsZero() bool

IsZero returns if the key pair is set or not.

func (KeyPair) KeyBytes

func (kp KeyPair) KeyBytes() ([]byte, error)

KeyBytes returns the key pair key bytes.

func (KeyPair) String

func (kp KeyPair) String() (output string)

String returns a string representation of the key pair.

func (KeyPair) TLSCertificate added in v1.20201204.1

func (kp KeyPair) TLSCertificate() (*tls.Certificate, error)

TLSCertificate returns the KeyPair as a tls.Certificate.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL