tlscommon

package
v0.46.2 Latest Latest
Warning

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

Go to latest
Published: Jul 20, 2026 License: Apache-2.0 Imports: 24 Imported by: 85

Documentation

Index

Constants

View Source
const (
	TLSClientAuthNone     TLSClientAuth = TLSClientAuth(tls.NoClientCert)
	TLSClientAuthOptional               = TLSClientAuth(tls.VerifyClientCertIfGiven)
	TLSClientAuthRequired               = TLSClientAuth(tls.RequireAndVerifyClientCert)
)

Variables

View Source
var (
	// ErrNotACertificate indicates a PEM file to be loaded not being a valid
	// PEM file or certificate.
	ErrNotACertificate = errors.New("file is not a certificate")

	// ErrCertificateNoKey indicate a configuration error with missing key file
	ErrKeyUnspecified = errors.New("key file not configured")

	// ErrKeyNoCertificate indicate a configuration error with missing certificate file
	ErrCertificateUnspecified = errors.New("certificate file not configured")
)
View Source
var (
	// TLSVersionMax is the max TLS version supported.
	TLSVersionMax = TLSVersion13

	// TLSVersionDefaultMin is the minimal default TLS version that is
	// enabled by default. TLSVersionDefaultMin is >= TLSVersionMin
	TLSVersionDefaultMin = TLSVersion12

	// TLSVersionDefaultMax is the max default TLS version that
	// is enabled by default.
	TLSVersionDefaultMax = TLSVersionMax
)
View Source
var ErrCAPinMissmatch = errors.New("provided CA certificate pins doesn't match any of the certificate authorities used to validate the certificate")

ErrCAPinMissmatch is returned when no pin is matched in the verified chain.

View Source
var (
	ErrMissingPeerCertificate = errors.New("missing peer certificates")
)
View Source
var TLSDefaultVersions = []TLSVersion{
	TLSVersion12,
	TLSVersion13,
}

TLSDefaultVersions list of versions of TLS we should support.

View Source
var (
	// TLSVersionMin is the min TLS version supported.
	TLSVersionMin = TLSVersion11
)

Functions

func CertDiagString added in v0.9.12

func CertDiagString(cert *x509.Certificate) string

CertDiagString returns a diagnostics string describing the passed certificate

func Fingerprint

func Fingerprint(certificate *x509.Certificate) string

Fingerprint takes a certificate and create a hash of the DER encoded public key.

func IsPEMString

func IsPEMString(s string) bool

IsPEMString returns true if the provided string match a PEM formatted certificate. try to pem decode to validate.

func LoadCertificate

func LoadCertificate(config *CertificateConfig, logger *logp.Logger) (*tls.Certificate, error)

LoadCertificate will load a certificate from disk and return a tls.Certificate or error

func LoadCertificateAuthorities

func LoadCertificateAuthorities(CAs []string, logger *logp.Logger) (*x509.CertPool, []error)

LoadCertificateAuthorities read the slice of CAcert and return a Certpool.

func ReadPEMFile

func ReadPEMFile(log *logp.Logger, s, passphrase string) ([]byte, error)

ReadPEMFile reads a PEM formatted string either from disk or passed as a plain text starting with a "-" and decrypt it with the provided password and return the raw content. Encrypted PKCS#1 PEM blocks are decrypted with a deprecation warning. To treat them as an error, use LoadCertificate with DisableLegacyPEMSupport set on the CertificateConfig.

func ResolveCipherSuite

func ResolveCipherSuite(cipher uint16) string

ResolveCipherSuite takes the integer representation and return the cipher name.

func ResolveTLSVersion

func ResolveTLSVersion(v uint16) string

ResolveTLSVersion takes the integer representation and return the name.

func SetInsecureDefaults added in v0.17.5

func SetInsecureDefaults()

This function is used to avoid a breaking change on previous releases.

Types

type CAReloader added in v0.43.0

type CAReloader struct {
	// contains filtered or unexported fields
}

CAReloader periodically reloads CA certificate files from disk. On each call to GetCertPool, it checks whether the reload interval has elapsed and, if so, re-reads the CA files from disk. Invalid or unreadable files are skipped, preserving the last successfully loaded pool.

func NewCAReloader added in v0.43.0

func NewCAReloader(caPaths []string, reloadInterval time.Duration, logger *logp.Logger) (*CAReloader, error)

NewCAReloader creates a CAReloader for the given CA file paths. Inline PEM strings are also accepted and will be included on every reload (they never change, but are needed to build a complete pool). An initial load is performed; an error is returned only if no CA could be loaded at all.

func (*CAReloader) AddTrustedCert added in v0.43.0

func (r *CAReloader) AddTrustedCert(cert *x509.Certificate)

AddTrustedCert registers a certificate so it is included in every pool returned by GetCertPool, surviving reloads from disk. Duplicate certs (by raw bytes) are ignored.

func (*CAReloader) GetCertPool added in v0.43.0

func (r *CAReloader) GetCertPool() *x509.CertPool

GetCertPool returns the current CA certificate pool, reloading from disk if the reload interval has elapsed. The returned pool is a snapshot: callers should not cache it across handshakes but instead call GetCertPool each time to pick up reloaded CAs. It is safe for concurrent use.

func (*CAReloader) IsDynamic added in v0.43.0

func (r *CAReloader) IsDynamic() bool

IsDynamic reports that CAReloader provides a dynamically reloaded pool.

type CertReloader added in v0.37.0

type CertReloader struct {
	// contains filtered or unexported fields
}

CertReloader periodically reloads TLS certificate and key files from disk. On each call to GetCertificate (i.e., on each TLS handshake), it checks whether the reload interval has elapsed and, if so, re-reads the files from disk. Invalid cert/key pairs are logged and skipped, preserving the last successfully loaded certificate.

This design follows the OpenTelemetry Collector's configtls approach: no file watchers or extra goroutines — just a time check on the handshake hot path.

func NewCertReloader added in v0.37.0

func NewCertReloader(certPath, keyPath string, logger *logp.Logger, opts ...CertReloaderOption) (*CertReloader, error)

NewCertReloader creates a CertReloader for the given cert and key file paths. It performs an initial load of the certificate pair, returning an error if the initial load fails.

func (*CertReloader) GetCertificate added in v0.37.0

func (r *CertReloader) GetCertificate(_ *tls.ClientHelloInfo) (*tls.Certificate, error)

GetCertificate returns the current certificate, reloading from disk if the reload interval has elapsed. It is safe for concurrent use and is intended to be used with tls.Config.GetCertificate.

func (*CertReloader) GetClientCertificate added in v0.43.0

func (r *CertReloader) GetClientCertificate(_ *tls.CertificateRequestInfo) (*tls.Certificate, error)

GetClientCertificate returns the current certificate, reloading from disk if the reload interval has elapsed. It is safe for concurrent use and is intended to be used with tls.Config.GetClientCertificate.

type CertReloaderOption added in v0.37.0

type CertReloaderOption func(*CertReloader)

CertReloaderOption is a functional option for configuring a CertReloader.

func WithDisableLegacyPEMSupport added in v0.43.0

func WithDisableLegacyPEMSupport(disable bool) CertReloaderOption

WithDisableLegacyPEMSupport configures whether encrypted PKCS#1 PEM keys should be treated as an error instead of a deprecation warning.

func WithPassphrase added in v0.41.1

func WithPassphrase(passphrase string) CertReloaderOption

WithPassphrase sets the passphrase used to decrypt encrypted private keys.

func WithReloadInterval added in v0.37.0

func WithReloadInterval(d time.Duration) CertReloaderOption

WithReloadInterval sets how often the certificate files are re-read from disk. If not specified, a default of 5 seconds is used.

type CertificateConfig

type CertificateConfig struct {
	Certificate             string `config:"certificate" yaml:"certificate,omitempty"`
	Key                     string `config:"key" yaml:"key,omitempty"`
	Passphrase              string `config:"key_passphrase" yaml:"key_passphrase,omitempty"`
	PassphrasePath          string `config:"key_passphrase_path" yaml:"key_passphrase_path,omitempty"`
	DisableLegacyPEMSupport bool   `config:"disable_legacy_pem_support" yaml:"disable_legacy_pem_support,omitempty"`
}

CertificateConfig define a common set of fields for a certificate.

func (*CertificateConfig) Validate

func (c *CertificateConfig) Validate() error

Validate validates the CertificateConfig

type CertificateReload added in v0.37.0

type CertificateReload struct {
	Enabled        *bool         `config:"enabled" yaml:"enabled,omitempty"`
	ReloadInterval time.Duration `config:"reload_interval" yaml:"reload_interval,omitempty"`
}

CertificateReload is the configuration for hot-reloading TLS certificates. Use DefaultCertificateReload to get a value with sensible defaults (enabled, 5 s reload interval).

func DefaultCertificateReload added in v0.37.0

func DefaultCertificateReload() CertificateReload

DefaultCertificateReload returns a CertificateReload with sensible defaults: enabled with a 5-second reload interval.

func (*CertificateReload) IsEnabled added in v0.37.0

func (c *CertificateReload) IsEnabled() bool

IsEnabled returns true unless certificate reload has been explicitly disabled.

type CipherSuite

type CipherSuite uint16

func (CipherSuite) String

func (cs CipherSuite) String() string

func (*CipherSuite) Unpack

func (cs *CipherSuite) Unpack(i any) error

func (*CipherSuite) Validate added in v0.18.10

func (cs *CipherSuite) Validate() error

type Config

type Config struct {
	Enabled              *bool                   `config:"enabled" yaml:"enabled,omitempty"`
	VerificationMode     TLSVerificationMode     `config:"verification_mode" yaml:"verification_mode"` // one of 'none', 'full', 'certificate' and 'strict'
	Versions             []TLSVersion            `config:"supported_protocols" yaml:"supported_protocols,omitempty"`
	CipherSuites         []CipherSuite           `config:"cipher_suites" yaml:"cipher_suites,omitempty"`
	CAs                  []string                `config:"certificate_authorities" yaml:"certificate_authorities,omitempty"`
	Certificate          CertificateConfig       `config:",inline" yaml:",inline"`
	CurveTypes           []TLSCurveType          `config:"curve_types" yaml:"curve_types,omitempty"`
	Renegotiation        TLSRenegotiationSupport `config:"renegotiation" yaml:"renegotiation"`
	CASha256             []string                `config:"ca_sha256" yaml:"ca_sha256,omitempty"`
	CATrustedFingerprint string                  `config:"ca_trusted_fingerprint" yaml:"ca_trusted_fingerprint,omitempty"`
	CertificateReload    CertificateReload       `config:"certificate_reload" yaml:"certificate_reload,omitempty"`
}

Config defines the user configurable options in the yaml file.

func (*Config) DiagCerts added in v0.9.12

func (c *Config) DiagCerts() func() []byte

DiagCerts returns a diagnostics hook callback that will validate if the certifiactes (cert + key, and CAs) present in the config are valid.

func (*Config) IsEnabled

func (c *Config) IsEnabled() bool

IsEnabled returns true if the `enable` field is set to true in the yaml.

func (*Config) Validate

func (c *Config) Validate() error

Validate values the TLSConfig struct making sure certificate sure we have both a certificate and a key.

type PEMReader

type PEMReader struct {
	// contains filtered or unexported fields
}

PEMReader allows to read a certificate in PEM format either through the disk or from a string.

func NewPEMReader

func NewPEMReader(certificate string) (*PEMReader, error)

NewPEMReader returns a new PEMReader.

func (*PEMReader) Close

func (p *PEMReader) Close() error

Close closes the target io.ReadCloser.

func (*PEMReader) Read

func (p *PEMReader) Read(b []byte) (n int, err error)

Read read bytes from the io.ReadCloser.

func (*PEMReader) String

func (p *PEMReader) String() string

type ServerConfig

type ServerConfig struct {
	Enabled           *bool               `config:"enabled" yaml:"enabled,omitempty"`
	VerificationMode  TLSVerificationMode `config:"verification_mode" yaml:"verification_mode,omitempty"` // one of 'none', 'full', 'strict', 'certificate'
	Versions          []TLSVersion        `config:"supported_protocols" yaml:"supported_protocols,omitempty"`
	CipherSuites      []CipherSuite       `config:"cipher_suites" yaml:"cipher_suites,omitempty"`
	CAs               []string            `config:"certificate_authorities" yaml:"certificate_authorities,omitempty"`
	Certificate       CertificateConfig   `config:",inline" yaml:",inline"`
	CurveTypes        []TLSCurveType      `config:"curve_types" yaml:"curve_types,omitempty"`
	ClientAuth        *TLSClientAuth      `config:"client_authentication" yaml:"client_authentication,omitempty"` //`none`, `optional` or `required`
	CASha256          []string            `config:"ca_sha256" yaml:"ca_sha256,omitempty"`
	CertificateReload CertificateReload   `config:"certificate_reload" yaml:"certificate_reload,omitempty"`
}

ServerConfig defines the user configurable tls options for any TCP based service.

func (*ServerConfig) DiagCerts added in v0.9.12

func (c *ServerConfig) DiagCerts() func() []byte

DiagCerts returns a diagnostics hook callback that will validate if the certifiactes (cert + key, and CAs) present in the config are valid.

Implementation is mostly a copy of Config.DiagCerts

func (*ServerConfig) IsEnabled

func (c *ServerConfig) IsEnabled() bool

IsEnabled returns true if the `enable` field is set to true in the yaml.

func (*ServerConfig) Unpack

func (c *ServerConfig) Unpack(cfg config.C) error

Unpack unpacks the TLS Server configuration.

func (*ServerConfig) Validate

func (c *ServerConfig) Validate() error

Validate values the TLSConfig struct making sure certificate sure we have both a certificate and a key.

type TLSClientAuth added in v0.7.4

type TLSClientAuth int

func (TLSClientAuth) MarshalText added in v0.7.4

func (m TLSClientAuth) MarshalText() ([]byte, error)

func (TLSClientAuth) String added in v0.7.4

func (m TLSClientAuth) String() string

func (*TLSClientAuth) Unpack added in v0.7.4

func (m *TLSClientAuth) Unpack(in any) error

type TLSConfig

type TLSConfig struct {

	// List of allowed SSL/TLS protocol versions. Connections might be dropped
	// after handshake succeeded, if TLS version in use is not listed.
	Versions []TLSVersion

	// Configure SSL/TLS verification mode used during handshake. By default
	// VerifyFull will be used.
	Verification TLSVerificationMode

	// List of certificate chains to present to the other side of the
	// connection.
	Certificates []tls.Certificate

	// List of supported cipher suites. If nil, a default list provided by the
	// implementation will be used.
	CipherSuites []CipherSuite

	// Types of elliptic curves that will be used in an ECDHE handshake. If empty,
	// the implementation will choose a default.
	CurvePreferences []tls.CurveID

	// Renegotiation controls what types of renegotiation are supported.
	// The default, never, is correct for the vast majority of applications.
	Renegotiation tls.RenegotiationSupport

	// ClientAuth controls how we want to verify certificate from a client, `none`, `optional` and
	// `required`, default to required. Do not affect TCP client.
	ClientAuth tls.ClientAuthType

	// CASha256 is the CA certificate pin, this is used to validate the CA that will be used to trust
	// the server certificate.
	CASha256 []string

	// CATrustedFingerprint is the HEX encoded fingerprint of a CA certificate. If present in the chain
	// this certificate will be added to the list of trusted CAs (RootCAs) during the handshake.
	CATrustedFingerprint string

	// ServerName is the remote server we're connecting to. It can be a hostname or IP address.
	ServerName string

	Logger *logp.Logger
	// contains filtered or unexported fields
}

TLSConfig is the interface used to configure a tcp client or server from a `Config`

func LoadTLSConfig

func LoadTLSConfig(config *Config, logger *logp.Logger) (*TLSConfig, error)

LoadTLSConfig will load a certificate from config with all TLS based keys defined. If Certificate and CertificateKey are configured, client authentication will be configured. If no CAs are configured, the host CA will be used by go built-in TLS support.

func LoadTLSServerConfig

func LoadTLSServerConfig(config *ServerConfig, logger *logp.Logger) (*TLSConfig, error)

LoadTLSServerConfig tranforms a ServerConfig into a `tls.Config` to be used directly with golang network types.

func (*TLSConfig) BuildModuleClientConfig

func (c *TLSConfig) BuildModuleClientConfig(host string, options ...TLSOption) *tls.Config

BuildModuleClientConfig takes the TLSConfig and transform it into a `tls.Config`.

func (*TLSConfig) BuildServerConfig

func (c *TLSConfig) BuildServerConfig(host string) *tls.Config

BuildServerConfig takes the TLSConfig and transform it into a `tls.Config` for server side connections.

func (*TLSConfig) ToConfig

func (c *TLSConfig) ToConfig() *tls.Config

ToConfig generates a tls.Config object. Note, you must use BuildModuleClientConfig to generate a config with ServerName set, use that method for servers with SNI. By default VerifyConnection is set to client mode.

type TLSCurveType added in v0.29.0

type TLSCurveType tls.CurveID

func (*TLSCurveType) Unpack added in v0.29.0

func (ct *TLSCurveType) Unpack(i any) error

func (*TLSCurveType) Validate added in v0.29.0

func (ct *TLSCurveType) Validate() error

type TLSOption added in v0.24.0

type TLSOption interface {
	// contains filtered or unexported methods
}

func WithLogger added in v0.24.0

func WithLogger(logger *logp.Logger) TLSOption

type TLSRenegotiationSupport

type TLSRenegotiationSupport tls.RenegotiationSupport

func (TLSRenegotiationSupport) MarshalText

func (r TLSRenegotiationSupport) MarshalText() ([]byte, error)

func (TLSRenegotiationSupport) MarshalYAML

func (r TLSRenegotiationSupport) MarshalYAML() (any, error)

func (TLSRenegotiationSupport) String

func (r TLSRenegotiationSupport) String() string

func (*TLSRenegotiationSupport) Unpack

func (r *TLSRenegotiationSupport) Unpack(i any) error

type TLSSettings added in v0.24.0

type TLSSettings struct {
	// contains filtered or unexported fields
}

type TLSVerificationMode

type TLSVerificationMode uint8

TLSVerificationMode represents the type of verification to do on the remote host: `none`, `certificate`, `full` and `strict` - we default to `full`. Internally this option is transformed into the `insecure` field in the `tls.Config` struct.

const (
	VerifyFull TLSVerificationMode = iota
	VerifyNone
	VerifyCertificate
	VerifyStrict
)

Constants of the supported verification mode.

func (TLSVerificationMode) MarshalText

func (m TLSVerificationMode) MarshalText() ([]byte, error)

MarshalText marshal the verification mode into a human readable value.

func (TLSVerificationMode) String

func (m TLSVerificationMode) String() string

func (*TLSVerificationMode) Unpack

func (m *TLSVerificationMode) Unpack(in any) error

Unpack unpacks the input into a TLSVerificationMode.

func (*TLSVerificationMode) Validate added in v0.9.2

func (m *TLSVerificationMode) Validate() error

type TLSVersion

type TLSVersion uint16

TLSVersion type for TLS version.

const (
	TLSVersion10 TLSVersion = tls.VersionTLS10
	TLSVersion11 TLSVersion = tls.VersionTLS11
	TLSVersion12 TLSVersion = tls.VersionTLS12
	TLSVersion13 TLSVersion = tls.VersionTLS13
)

Define all the possible TLS version.

func (TLSVersion) Details

func (v TLSVersion) Details() *TLSVersionDetails

Details returns a a ProtocolAndVersions struct containing detailed version metadata.

func (TLSVersion) String

func (v TLSVersion) String() string

func (*TLSVersion) Unpack

func (v *TLSVersion) Unpack(i interface{}) error

Unpack transforms the string into a constant.

func (*TLSVersion) Validate added in v0.9.2

func (v *TLSVersion) Validate() error

type TLSVersionDetails

type TLSVersionDetails struct {
	Version  string
	Protocol string
	Combined string
}

Intended for ECS's tls.version_protocol_field, which does not include numeric version and should be lower case

func (TLSVersionDetails) String

func (pv TLSVersionDetails) String() string

Jump to

Keyboard shortcuts

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