certificates

package
v1.22.0 Latest Latest
Warning

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

Go to latest
Published: Apr 17, 2026 License: MIT Imports: 18 Imported by: 0

README

Certificates Package

Go Version

Comprehensive TLS/SSL certificate management for secure communications in Go applications.


Table of Contents


Overview

The certificates package provides a complete solution for configuring TLS/SSL connections in Go applications. It offers type-safe configuration for certificates, cipher suites, elliptic curves, TLS versions, and client authentication modes.

Design Philosophy
  1. Type-Safe: Leverage Go generics and type wrappers for compile-time safety
  2. Flexible Input: Support for PEM strings, file paths, and structured configuration
  3. Security-First: Default to secure configurations with modern TLS standards
  4. Multi-Format: JSON, YAML, TOML, and CBOR encoding support
  5. Thread-Safe: All operations are safe for concurrent access

Key Features

  • Certificate Management: Load and manage certificate pairs (private key + certificate)
  • CA Management: Support for root CA and client CA certificate pools
  • TLS Version Control: Configure minimum and maximum TLS versions (1.0-1.3)
  • Cipher Suite Selection: Modern, secure cipher suites for TLS 1.2 and 1.3
  • Elliptic Curve Configuration: Support for X25519, P256, P384, and P521
  • Client Authentication: Five authentication modes from none to strict verification
  • Dynamic Configuration: Runtime configuration updates and rotation
  • Multiple Encodings: JSON, YAML, TOML, CBOR support for all types
  • Thread-Safe Operations: Concurrent access protection throughout

Installation

go get github.com/nabbar/golib/certificates

Requirements:

  • Go 1.18 or higher (for generics support)
  • No external dependencies beyond crypto/tls and encoding libraries

Architecture

Package Structure
certificates/
├── certificates        # Main package
│   ├── interface.go   # TLSConfig interface and types
│   ├── model.go       # Implementation
│   ├── config.go      # Configuration structures
│   └── tools.go       # Helper functions
└── Subpackages/
    ├── auth/          # Client authentication modes
    ├── ca/            # Certificate Authority management
    ├── certs/         # Certificate pair management
    ├── cipher/        # Cipher suite configuration
    ├── curves/        # Elliptic curve configuration
    └── tlsversion/    # TLS version management
Component Diagram
┌─────────────────────────────────────────────────┐
│              TLSConfig Interface                │
│   Main configuration for TLS connections        │
└───────────┬─────────────────────────────────────┘
            │
            ├──> Root CA Pool (ca.Cert)
            │    └─ x509.CertPool
            │
            ├──> Client CA Pool (ca.Cert)
            │    └─ x509.CertPool
            │
            ├──> Certificate Pairs (certs.Cert)
            │    └─ tls.Certificate
            │
            ├──> TLS Version (tlsversion.Version)
            │    ├─ Min: TLS 1.2 (recommended)
            │    └─ Max: TLS 1.3 (preferred)
            │
            ├──> Cipher Suites (cipher.Cipher)
            │    ├─ TLS 1.2: ECDHE+AES-GCM
            │    └─ TLS 1.3: AES-GCM, ChaCha20
            │
            ├──> Elliptic Curves (curves.Curves)
            │    ├─ X25519 (preferred)
            │    └─ P256, P384, P521
            │
            └──> Client Auth (auth.ClientAuth)
                 └─ NoClientCert, Request, Require, Verify, Strict
Type System
Type Package Purpose
TLSConfig certificates Main interface for TLS configuration
ClientAuth auth Client authentication modes
Cert (CA) ca Certificate Authority certificates
Cert (pairs) certs Certificate pairs (key + cert)
Cipher cipher TLS cipher suite identifiers
Curves curves Elliptic curve identifiers
Version tlsversion TLS protocol version

Quick Start

Basic Server Configuration
package main

import (
    "crypto/tls"
    "net/http"
    
    "github.com/nabbar/golib/certificates"
    "github.com/nabbar/golib/certificates/tlsversion"
)

func main() {
    // Create TLS configuration
    tlsConfig := certificates.New()
    
    // Set TLS versions
    tlsConfig.SetVersionMin(tlsversion.VersionTLS12)
    tlsConfig.SetVersionMax(tlsversion.VersionTLS13)
    
    // Add server certificate
    err := tlsConfig.AddCertificatePairFile("/path/to/key.pem", "/path/to/cert.pem")
    if err != nil {
        panic(err)
    }
    
    // Create HTTP server with TLS
    server := &http.Server{
        Addr:      ":443",
        TLSConfig: tlsConfig.TLS("example.com"),
    }
    
    server.ListenAndServeTLS("", "")
}
Client Configuration with mTLS
package main

import (
    "crypto/tls"
    "net/http"
    
    "github.com/nabbar/golib/certificates"
    "github.com/nabbar/golib/certificates/auth"
)

func main() {
    // Create client TLS configuration
    tlsConfig := certificates.New()
    
    // Add root CA to verify server
    err := tlsConfig.AddRootCAFile("/path/to/ca.pem")
    if err != nil {
        panic(err)
    }
    
    // Add client certificate for mTLS
    err = tlsConfig.AddCertificatePairFile("/path/to/client-key.pem", "/path/to/client-cert.pem")
    if err != nil {
        panic(err)
    }
    
    // Create HTTP client
    client := &http.Client{
        Transport: &http.Transport{
            TLSClientConfig: tlsConfig.TLS("server.example.com"),
        },
    }
    
    resp, err := client.Get("https://server.example.com")
    // ...
}
Configuration from Strings
// PEM-encoded certificate and key
keyPEM := `-----BEGIN RSA PRIVATE KEY-----
MIIEpAIBAAKCAQEA...
-----END RSA PRIVATE KEY-----`

certPEM := `-----BEGIN CERTIFICATE-----
MIIDXTCCAkWgAwIBAgIJ...
-----END CERTIFICATE-----`

tlsConfig := certificates.New()
err := tlsConfig.AddCertificatePairString(keyPEM, certPEM)
if err != nil {
    panic(err)
}

Subpackages

auth - Client Authentication Modes

Provides client authentication mode types for TLS connections.

Supported Modes:

  • NoClientCert: No client certificate required
  • RequestClientCert: Request but don't require client certificate
  • RequireAnyClientCert: Require any client certificate (unverified)
  • VerifyClientCertIfGiven: Verify client certificate if provided
  • RequireAndVerifyClientCert: Require and verify client certificate

Example:

import "github.com/nabbar/golib/certificates/auth"

authMode := auth.Parse("require")
tlsConfig.SetClientAuth(authMode)

Full auth package documentation →


ca - Certificate Authority Management

Manages CA certificates for verifying certificate chains.

Key Features:

  • Parse CA certificates from PEM strings or bytes
  • Support for certificate chains
  • Convert to x509.CertPool for TLS
  • Multiple encoding formats (JSON, YAML, TOML, CBOR)

Example:

import "github.com/nabbar/golib/certificates/ca"

caCert, err := ca.Parse(pemString)
if err != nil {
    log.Fatal(err)
}
pool := caCert.GetCertPool()

Full ca package documentation →


certs - Certificate Pair Management

Manages certificate pairs (private key + certificate) for TLS servers and clients.

Key Features:

  • Parse certificate pairs from PEM strings or files
  • Support for certificate chains
  • Multiple configuration formats (ConfigPair, ConfigChain)
  • Convert to tls.Certificate

Example:

import "github.com/nabbar/golib/certificates/certs"

cert, err := certs.Parse(keyPEM + "\n" + certPEM)
if err != nil {
    log.Fatal(err)
}
tlsCert := cert.GetTLS()

Full certs package documentation →


cipher - Cipher Suite Selection

Provides TLS cipher suite types and parsing for secure connections.

Supported Cipher Suites:

TLS 1.2:

  • RSA with AES-GCM
  • ECDHE-RSA with AES-GCM (forward secrecy)
  • ECDHE-ECDSA with AES-GCM (forward secrecy)
  • ECDHE with ChaCha20-Poly1305 (forward secrecy, mobile-optimized)

TLS 1.3:

  • AES-128-GCM-SHA256
  • AES-256-GCM-SHA384
  • ChaCha20-Poly1305-SHA256

Example:

import "github.com/nabbar/golib/certificates/cipher"

cipher := cipher.Parse("ECDHE-RSA-AES128-GCM-SHA256")
if cipher != cipher.Unknown {
    fmt.Println("Supported cipher:", cipher.String())
}

Full cipher package documentation →


curves - Elliptic Curve Configuration

Provides elliptic curve types for ECDHE cipher suites.

Supported Curves:

  • X25519: Modern, high-performance (preferred)
  • P256 (secp256r1): NIST curve, widely supported
  • P384 (secp384r1): NIST curve, higher security
  • P521 (secp521r1): NIST curve, maximum security

Example:

import "github.com/nabbar/golib/certificates/curves"

curve := curves.Parse("X25519")
tlsConfig.AddCurves(curve)

Full curves package documentation →


tlsversion - TLS Version Management

Provides TLS protocol version types and management.

Supported Versions:

  • VersionTLS10: TLS 1.0 (deprecated, not recommended)
  • VersionTLS11: TLS 1.1 (deprecated, not recommended)
  • VersionTLS12: TLS 1.2 (secure, widely supported)
  • VersionTLS13: TLS 1.3 (modern, most secure)

Example:

import "github.com/nabbar/golib/certificates/tlsversion"

minVer := tlsversion.Parse("1.2")
maxVer := tlsversion.Parse("1.3")
tlsConfig.SetVersionMin(minVer)
tlsConfig.SetVersionMax(maxVer)

Full tlsversion package documentation →


Configuration

TLSConfig Interface

The main TLSConfig interface provides comprehensive methods for configuring TLS connections:

Certificate Management:

  • AddCertificatePairString(key, cert string) error
  • AddCertificatePairFile(keyFile, certFile string) error
  • GetCertificatePair() []tls.Certificate
  • LenCertificatePair() int
  • CleanCertificatePair()

Root CA Management:

  • AddRootCA(rootCA ca.Cert) bool
  • AddRootCAString(rootCA string) bool
  • AddRootCAFile(pemFile string) error
  • GetRootCA() []ca.Cert
  • GetRootCAPool() *x509.CertPool

Client CA Management:

  • AddClientCAString(ca string) bool
  • AddClientCAFile(pemFile string) error
  • GetClientCA() []ca.Cert
  • GetClientCAPool() *x509.CertPool
  • SetClientAuth(auth.ClientAuth)

Version Control:

  • SetVersionMin(tlsversion.Version)
  • GetVersionMin() tlsversion.Version
  • SetVersionMax(tlsversion.Version)
  • GetVersionMax() tlsversion.Version

Cipher & Curve Configuration:

  • SetCipherList([]cipher.Cipher)
  • AddCiphers(...cipher.Cipher)
  • GetCiphers() []cipher.Cipher
  • SetCurveList([]curves.Curves)
  • AddCurves(...curves.Curves)
  • GetCurves() []curves.Curves

Advanced Options:

  • RegisterRand(io.Reader) - Custom randomness source
  • SetDynamicSizingDisabled(bool) - Control record sizing
  • SetSessionTicketDisabled(bool) - Control session resumption
  • TLS(serverName string) *tls.Config - Get final tls.Config
Configuration Examples

Minimal Server Configuration:

cfg := certificates.New()
cfg.AddCertificatePairFile("server-key.pem", "server-cert.pem")
tlsConfig := cfg.TLS("example.com")

Strict Server with mTLS:

cfg := certificates.New()
cfg.SetVersionMin(tlsversion.VersionTLS12)
cfg.SetVersionMax(tlsversion.VersionTLS13)
cfg.AddCertificatePairFile("server-key.pem", "server-cert.pem")
cfg.AddClientCAFile("client-ca.pem")
cfg.SetClientAuth(auth.RequireAndVerifyClientCert)
tlsConfig := cfg.TLS("example.com")

Client with Custom CA:

cfg := certificates.New()
cfg.AddRootCAFile("custom-ca.pem")
cfg.AddCertificatePairFile("client-key.pem", "client-cert.pem")
tlsConfig := cfg.TLS("")

Security Best Practices

TLS Version Selection

✅ Recommended Configuration:

cfg.SetVersionMin(tlsversion.VersionTLS12)  // Minimum TLS 1.2
cfg.SetVersionMax(tlsversion.VersionTLS13)  // Maximum TLS 1.3

Security Rationale:

  • TLS 1.0 and 1.1 are deprecated (RFC 8996)
  • TLS 1.2 provides wide compatibility
  • TLS 1.3 offers improved security and performance
Cipher Suite Selection

✅ Prefer ECDHE cipher suites for forward secrecy:

cipherSuites := []cipher.Cipher{
    cipher.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
    cipher.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
    cipher.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
    cipher.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
}
cfg.SetCipherList(cipherSuites)

❌ Avoid:

  • Non-ECDHE cipher suites (no forward secrecy)
  • Legacy cipher suites (RC4, 3DES, MD5)
  • Export-grade cryptography
Elliptic Curve Selection

✅ Recommended:

cfg.AddCurves(
    curves.X25519,  // Modern, fast, secure (preferred)
    curves.P256,    // NIST, widely supported
)

Security Notes:

  • X25519 offers best performance and security
  • P256 provides broad compatibility
  • Avoid P384/P521 unless required by policy
Certificate Management

✅ Best Practices:

  • Use strong key sizes (RSA 2048+, ECDSA P-256+)
  • Implement certificate rotation
  • Monitor certificate expiration
  • Use proper file permissions (0600 for private keys)
  • Store private keys securely (HSM, vault)

Example with Rotation:

func rotateCertificate(cfg certificates.TLSConfig) error {
    // Load new certificate
    err := cfg.AddCertificatePairFile("new-key.pem", "new-cert.pem")
    if err != nil {
        return err
    }
    
    // Remove old certificates
    cfg.CleanCertificatePair()
    
    return nil
}
Client Authentication

Security Levels:

Mode Use Case Security
NoClientCert Public services Low
RequestClientCert Optional auth Medium
RequireAnyClientCert Testing Medium
VerifyClientCertIfGiven Flexible auth Medium-High
RequireAndVerifyClientCert mTLS, high security High

✅ For high-security environments:

cfg.SetClientAuth(auth.RequireAndVerifyClientCert)
cfg.AddClientCAFile("trusted-clients-ca.pem")

Use Cases

HTTPS Web Server
package main

import (
    "net/http"
    "github.com/nabbar/golib/certificates"
    "github.com/nabbar/golib/certificates/tlsversion"
)

func main() {
    // Configure TLS
    tlsCfg := certificates.New()
    tlsCfg.SetVersionMin(tlsversion.VersionTLS12)
    tlsCfg.AddCertificatePairFile("server.key", "server.crt")
    
    // Create HTTPS server
    server := &http.Server{
        Addr:      ":443",
        TLSConfig: tlsCfg.TLS("example.com"),
        Handler:   http.DefaultServeMux,
    }
    
    server.ListenAndServeTLS("", "")
}
Microservice with mTLS
// Server side
serverCfg := certificates.New()
serverCfg.AddCertificatePairFile("service.key", "service.crt")
serverCfg.AddClientCAFile("clients-ca.pem")
serverCfg.SetClientAuth(auth.RequireAndVerifyClientCert)

// Client side
clientCfg := certificates.New()
clientCfg.AddRootCAFile("services-ca.pem")
clientCfg.AddCertificatePairFile("client.key", "client.crt")

client := &http.Client{
    Transport: &http.Transport{
        TLSClientConfig: clientCfg.TLS("service.example.com"),
    },
}
gRPC Service
import (
    "google.golang.org/grpc"
    "google.golang.org/grpc/credentials"
    "github.com/nabbar/golib/certificates"
)

tlsCfg := certificates.New()
tlsCfg.AddCertificatePairFile("grpc.key", "grpc.crt")
tlsCfg.AddRootCAFile("ca.pem")

creds := credentials.NewTLS(tlsCfg.TLS("grpc.example.com"))
server := grpc.NewServer(grpc.Creds(creds))
Database Connection
import (
    "database/sql"
    "crypto/tls"
    "github.com/go-sql-driver/mysql"
    "github.com/nabbar/golib/certificates"
)

tlsCfg := certificates.New()
tlsCfg.AddRootCAFile("db-ca.pem")
tlsCfg.AddCertificatePairFile("client.key", "client.crt")

mysql.RegisterTLSConfig("custom", tlsCfg.TLS(""))
db, err := sql.Open("mysql", "user:pass@tcp(host:3306)/db?tls=custom")

API Reference

Main Types

TLSConfig - Main interface for TLS configuration

type TLSConfig interface {
    // Certificate management
    AddCertificatePairString(key, crt string) error
    AddCertificatePairFile(keyFile, crtFile string) error
    GetCertificatePair() []tls.Certificate
    
    // CA management  
    AddRootCAString(rootCA string) bool
    AddRootCAFile(pemFile string) error
    GetRootCAPool() *x509.CertPool
    
    // Version control
    SetVersionMin(v tlsversion.Version)
    SetVersionMax(v tlsversion.Version)
    
    // Generate final config
    TLS(serverName string) *tls.Config
}
Factory Functions

New() - Create new TLSConfig

func New() TLSConfig
Subpackage Types

See individual subpackage documentation for detailed type information:


Testing

Test Suite: Ginkgo v2 + Gomega with comprehensive coverage

# Run all tests
go test ./...

# With coverage
go test -cover ./...

# With race detection
CGO_ENABLED=1 go test -race ./...

# Using Ginkgo CLI
go install github.com/onsi/ginkgo/v2/ginkgo@latest
ginkgo -r

Coverage by Package:

Package Coverage Specs
certificates ~70% 15
auth 73.0% 12
ca 68.5% 18
certs 47.8% 9
cipher 50.6% 12
curves 50.5% 9
tlsversion 54.5% 9

See TESTING.md for detailed testing documentation.


Contributing

Contributions are welcome! Please follow these guidelines:

Code Contributions:

  • Do not use AI to generate package implementation code
  • AI may assist with tests, documentation, and bug fixing
  • All contributions must pass go test -race
  • Follow existing code style and patterns
  • Add tests for new features

Documentation:

  • Update README.md for new features
  • Add examples for common use cases
  • Keep subpackage documentation synchronized

Security:

  • Report security issues privately
  • Follow responsible disclosure practices
  • Use secure defaults in new features

Pull Requests:

  • Provide clear description of changes
  • Reference related issues
  • Include test results
  • Update documentation

AI Transparency Notice

In accordance with Article 50.4 of the EU AI Act, AI assistance has been used for testing, documentation, and bug fixing under human supervision.


Resources

Documentation:

Tools:

Package Links:


License

MIT License - See LICENSE file for details.

Copyright (c) 2020 Nicolas JUHEL


Last Updated: 2025-11-07

Documentation

Overview

Package certificates provides comprehensive TLS/SSL certificate management for secure communications.

This package offers a complete solution for configuring TLS connections including certificate management, cipher suite selection, elliptic curve configuration, TLS version control, and client authentication.

Key Features:

  • Certificate management with support for files and in-memory certificates
  • Root CA and Client CA management for certificate verification
  • TLS version control (minimum/maximum version selection)
  • Cipher suite configuration with support for TLS 1.2 and 1.3
  • Elliptic curve configuration for ECDHE cipher suites
  • Client authentication modes (NoClientCert, RequestClientCert, RequireAnyClientCert, VerifyClientCertIfGiven, RequireAndVerifyClientCert)
  • Dynamic record sizing and session ticket controls
  • Thread-safe operations for concurrent access
  • Multiple encoding formats (JSON, YAML, TOML, CBOR)

Subpackages:

  • auth: Client authentication mode types and parsing
  • ca: Certificate Authority management and parsing
  • certs: Certificate pair management (private key + certificate)
  • cipher: TLS cipher suite selection and management
  • curves: Elliptic curve configuration for ECDHE
  • tlsversion: TLS version management and parsing

Example:

cfg := certificates.New()
cfg.SetVersionMin(tlsversion.VersionTLS12)
cfg.SetVersionMax(tlsversion.VersionTLS13)
cfg.AddRootCAFile("/path/to/ca.pem")
cfg.AddCertificatePairFile("/path/to/key.pem", "/path/to/cert.pem")
tlsConfig := cfg.TLS("example.com")

Index

Constants

View Source
const (
	ErrorParamEmpty liberr.CodeError = iota + liberr.MinPkgCertificate
	ErrorFileStat
	ErrorFileRead
	ErrorFileEmpty
	ErrorCertAppend
	ErrorCertKeyPairLoad
	ErrorCertKeyPairParse
	ErrorValidatorError
)

Variables

View Source
var Default = New()

Functions

func AddCACertificateContents deprecated

func AddCACertificateContents(caContent string) bool

Deprecated: use local config and no more globals default config.

func AddCACertificateFile deprecated

func AddCACertificateFile(caFile string) error

Deprecated: use local config and no more globals default config.

func AddCertificateContents deprecated

func AddCertificateContents(keyContents, certContents string) error

Deprecated: use local config and no more globals default config.

func AddCertificateFile deprecated

func AddCertificateFile(keyFile, certFile string) error

Deprecated: use local config and no more globals default config.

func AddCertificatePairFile deprecated added in v1.5.0

func AddCertificatePairFile(keyFile, crtFile string) error

Deprecated: use local config and no more globals default config.

func AddCertificatePairString deprecated added in v1.5.0

func AddCertificatePairString(key, crt string) error

Deprecated: use local config and no more globals default config.

func AddRootCAContents deprecated

func AddRootCAContents(rootContent string) bool

Deprecated: use local config and no more globals default config.

func AddRootCAFile deprecated

func AddRootCAFile(rootFile string) error

Deprecated: use local config and no more globals default config.

func AppendCertificates deprecated

func AppendCertificates(cert []tls.Certificate) []tls.Certificate

Deprecated: use local config and no more globals default config.

func CheckCertificates deprecated

func CheckCertificates() bool

Deprecated: use local config and no more globals default config.

func GetCertificates deprecated

func GetCertificates() []tls.Certificate

Deprecated: use local config and no more globals default config.

func GetClientCA deprecated

func GetClientCA() *x509.CertPool

Deprecated: use local config and no more globals default config.

func GetRootCA deprecated

func GetRootCA() *x509.CertPool

Deprecated: use local config and no more globals default config.

func GetTLSConfig deprecated

func GetTLSConfig(serverName string) *tls.Config

Deprecated: use local config and no more globals default config.

func GetTlsConfigCertificates deprecated

func GetTlsConfigCertificates() *tls.Config

Deprecated: use local config and no more globals default config.

func SetCipherList deprecated

func SetCipherList(cipher []uint16)

Deprecated: use local config and no more globals default config.

func SetClientAuth deprecated

func SetClientAuth(auth string)

Deprecated: use local config and no more globals default config.

func SetCurve deprecated

func SetCurve(curves []tls.CurveID)

Deprecated: use local config and no more globals default config.

func SetDynamicSizing deprecated

func SetDynamicSizing(enable bool)

Deprecated: use local config and no more globals default config.

func SetSessionTicket deprecated

func SetSessionTicket(enable bool)

Deprecated: use local config and no more globals default config.

func SetVersionMax deprecated

func SetVersionMax(vers uint16)

Deprecated: use local config and no more globals default config.

func SetVersionMin deprecated

func SetVersionMin(vers uint16)

Deprecated: use local config and no more globals default config.

func SystemRootCA added in v1.5.0

func SystemRootCA() *x509.CertPool

Types

type CertifOld added in v1.17.0

type CertifOld struct {
	Key string `mapstructure:"key" json:"key" yaml:"key" toml:"key"`
	Pem string `mapstructure:"pem" json:"pem" yaml:"pem" toml:"pem"`
}

type Config added in v1.5.0

type Config struct {
	CurveList            []tlscrv.Curves   `mapstructure:"curveList" json:"curveList" yaml:"curveList" toml:"curveList"`
	CipherList           []tlscpr.Cipher   `mapstructure:"cipherList" json:"cipherList" yaml:"cipherList" toml:"cipherList"`
	RootCA               []tlscas.Cert     `mapstructure:"rootCA" json:"rootCA" yaml:"rootCA" toml:"rootCA"`
	ClientCA             []tlscas.Cert     `mapstructure:"clientCA" json:"clientCA" yaml:"clientCA" toml:"clientCA"`
	Certs                []tlscrt.Certif   `mapstructure:"certs" json:"certs" yaml:"certs" toml:"certs"`
	VersionMin           tlsvrs.Version    `mapstructure:"versionMin" json:"versionMin" yaml:"versionMin" toml:"versionMin"`
	VersionMax           tlsvrs.Version    `mapstructure:"versionMax" json:"versionMax" yaml:"versionMax" toml:"versionMax"`
	AuthClient           tlsaut.ClientAuth `mapstructure:"authClient" json:"authClient" yaml:"authClient" toml:"authClient"`
	InheritDefault       bool              `mapstructure:"inheritDefault" json:"inheritDefault" yaml:"inheritDefault" toml:"inheritDefault"`
	DynamicSizingDisable bool              `mapstructure:"dynamicSizingDisable" json:"dynamicSizingDisable" yaml:"dynamicSizingDisable" toml:"dynamicSizingDisable"`
	SessionTicketDisable bool              `mapstructure:"sessionTicketDisable" json:"sessionTicketDisable" yaml:"sessionTicketDisable" toml:"sessionTicketDisable"`
}

func (*Config) GetConfigOld added in v1.17.8

func (c *Config) GetConfigOld() ConfigOld

func (*Config) New added in v1.5.0

func (c *Config) New() TLSConfig

func (*Config) NewFrom added in v1.5.0

func (c *Config) NewFrom(cfg TLSConfig) TLSConfig

nolint #gocognit

func (*Config) Validate added in v1.5.0

func (c *Config) Validate() liberr.Error

type ConfigOld added in v1.17.0

type ConfigOld struct {
	CurveList            []string    `mapstructure:"curveList" json:"curveList" yaml:"curveList" toml:"curveList"`
	CipherList           []string    `mapstructure:"cipherList" json:"cipherList" yaml:"cipherList" toml:"cipherList"`
	RootCAString         []string    `mapstructure:"rootCA" json:"rootCA" yaml:"rootCA" toml:"rootCA"`
	RootCAFile           []string    `mapstructure:"rootCAFiles" json:"rootCAFiles" yaml:"rootCAFiles" toml:"rootCAFiles"`
	ClientCAString       []string    `mapstructure:"clientCA" json:"clientCA" yaml:"clientCA" toml:"clientCA"`
	ClientCAFiles        []string    `mapstructure:"clientCAFiles" json:"clientCAFiles" yaml:"clientCAFiles" toml:"clientCAFiles"`
	CertPairString       []CertifOld `mapstructure:"certPair" json:"certPair" yaml:"certPair" toml:"certPair"`
	CertPairFile         []CertifOld `mapstructure:"certPairFiles" json:"certPairFiles" yaml:"certPairFiles" toml:"certPairFiles"`
	VersionMin           string      `mapstructure:"versionMin" json:"versionMin" yaml:"versionMin" toml:"versionMin"`
	VersionMax           string      `mapstructure:"versionMax" json:"versionMax" yaml:"versionMax" toml:"versionMax"`
	AuthClient           string      `mapstructure:"authClient" json:"authClient" yaml:"authClient" toml:"authClient"`
	InheritDefault       bool        `mapstructure:"inheritDefault" json:"inheritDefault" yaml:"inheritDefault" toml:"inheritDefault"`
	DynamicSizingDisable bool        `mapstructure:"dynamicSizingDisable" json:"dynamicSizingDisable" yaml:"dynamicSizingDisable" toml:"dynamicSizingDisable"`
	SessionTicketDisable bool        `mapstructure:"sessionTicketDisable" json:"sessionTicketDisable" yaml:"sessionTicketDisable" toml:"sessionTicketDisable"`
}

func (*ConfigOld) ToConfig added in v1.17.0

func (c *ConfigOld) ToConfig() Config

type FctHttpClient added in v1.10.0

type FctHttpClient func(def TLSConfig, servername string) *http.Client

FctHttpClient is a function type that creates an HTTP client with TLS configuration. It receives a TLS configuration and a server name, and returns a configured *http.Client.

type FctRootCA added in v1.13.10

type FctRootCA func() []string

FctRootCA is a function type that returns a list of root CA certificate paths or PEM strings.

type FctRootCACert added in v1.17.0

type FctRootCACert func() tlscas.Cert

FctRootCACert is a function type that returns a parsed root CA certificate.

type FctTLSDefault added in v1.10.0

type FctTLSDefault func() TLSConfig

FctTLSDefault is a function type that returns a default TLS configuration. It is useful for factory patterns or lazy initialization.

type TLSConfig added in v1.5.0

type TLSConfig interface {
	// RegisterRand sets the source of randomness for the TLS connection.
	// It can be used to rotate the randomness source for example.
	//
	// The rand parameter should implement the io.Reader interface.
	// The TLS connection will use this reader to generate randomness.
	// If the reader is nil, the TLS connection will use the default source of randomness.
	//
	// The TLS connection will use this reader to generate randomness
	// for the lifetime of the connection. To rotate the randomness source,
	// call RegisterRand with a new reader.
	//
	RegisterRand(rand io.Reader)

	// AddRootCA adds a root CA to the TLS configuration.
	// It returns true if the root CA was added successfully, false otherwise.
	//
	// The root CA is added to the TLS configuration's root CA pool.
	// The root CA pool is used to verify the identity of the server.
	//
	// The root CA parameter should be a parsed certificate.
	// To parse a certificate from a PEM file, use the tlscas.Parse function.
	//
	// The AddRootCA function does not check if the root CA is already in the pool.
	// If you want to avoid adding the same root CA twice, you should check the pool before adding the root CA.
	AddRootCA(rootCA tlscas.Cert) bool
	// AddRootCAString adds a root CA to the TLS configuration from a string.
	// It returns true if the root CA was added successfully, false otherwise.
	//
	// The root CA is added to the TLS configuration's root CA pool.
	// The root CA pool is used to verify the identity of the server.
	//
	// The rootCA parameter should be a PEM encoded certificate.
	// To parse a certificate from a PEM file, use the tlscas.Parse function.
	//
	// The AddRootCAString function does not check if the root CA is already in the pool.
	// If you want to avoid adding the same root CA twice, you should check the pool before adding the root CA.
	AddRootCAString(rootCA string) bool
	// AddRootCAFile adds a root CA to the TLS configuration from a PEM file.
	//
	// The root CA is added to the TLS configuration's root CA pool.
	// The root CA pool is used to verify the identity of the server.
	//
	// The pemFile parameter should be the path to a PEM file containing the root CA.
	//
	// The AddRootCAFile function does not check if the root CA is already in the pool.
	// If you want to avoid adding the same root CA twice, you should check the pool before adding the root CA.
	//
	// The AddRootCAFile function returns an error if the PEM file cannot be read or if the root CA in the PEM file is invalid.
	AddRootCAFile(pemFile string) error
	// GetRootCA returns the root CA pool as a slice of Cert.
	// The root CA pool is used to verify the identity of the server.
	// The returned slice is a copy of the root CA pool and does not reference the original pool.
	// Modifying the returned slice does not affect the original pool.
	// The returned slice is ordered by the order the root CAs were added to the pool.
	GetRootCA() []tlscas.Cert
	// GetRootCAPool returns the root CA pool as a *x509.CertPool.
	// The root CA pool is used to verify the identity of the server.
	// The returned *x509.CertPool is a copy of the root CA pool and does not reference the original pool.
	// Modifying the returned *x509.CertPool does not affect the original pool.
	// The returned *x509.CertPool is ordered by the order the root CAs were added to the pool.
	GetRootCAPool() *x509.CertPool

	// AddClientCAString adds a client CA to the TLS configuration from a PEM encoded string.
	//
	// The client CA is added to the TLS configuration's client CA pool.
	// The client CA pool is used to verify the identity of the client.
	//
	// The ca parameter should be a PEM encoded certificate.
	// To parse a certificate from a PEM file, use the tlscas.Parse function.
	//
	// The AddClientCAString function does not check if the client CA is already in the pool.
	// If you want to avoid adding the same client CA twice, you should check the pool before adding the client CA.
	//
	// The AddClientCAString function returns true if the client CA is successfully added and false otherwise.
	AddClientCAString(ca string) bool
	// AddClientCAFile adds a client CA to the TLS configuration from a PEM file.
	//
	// The client CA is added to the TLS configuration's client CA pool.
	// The client CA pool is used to verify the identity of the client.
	//
	// The pemFile parameter should be the path to a PEM file containing the client CA.
	//
	// The AddClientCAFile function does not check if the client CA is already in the pool.
	// If you want to avoid adding the same client CA twice, you should check the pool before adding the client CA.
	//
	// The AddClientCAFile function returns an error if the PEM file cannot be read or if the client CA in the PEM file is invalid.
	AddClientCAFile(pemFile string) error
	// GetClientCA returns the client CA pool as a slice of tlscas.Cert.
	//
	// The client CA pool is used to verify the identity of the client.
	//
	// The returned slice is ordered by the order the client CAs were added to the pool.
	// Modifying the returned slice does not affect the original pool.
	GetClientCA() []tlscas.Cert
	// GetClientCAPool returns the client CA pool as a *x509.CertPool.
	//
	// The client CA pool is used to verify the identity of the client.
	//
	// The returned *x509.CertPool is ordered by the order the client CAs were added to the pool.
	// Modifying the returned *x509.CertPool does not affect the original pool.
	GetClientCAPool() *x509.CertPool
	// SetClientAuth sets the client authentication requirements for the TLS connection.
	//
	// The a parameter should be a tlsaut.ClientAuth containing the client authentication requirements.
	// The client authentication requirements are used to verify the identity of the client.
	//
	// The SetClientAuth function does not check if the client authentication requirements are already set.
	// If you want to avoid setting the same client authentication requirements twice, you should check the current client authentication requirements before setting the new ones.
	SetClientAuth(a tlsaut.ClientAuth)

	// AddCertificatePairString adds a certificate pair to the TLS configuration from a string.
	//
	// The key parameter should be a PEM encoded private key.
	// The crt parameter should be a PEM encoded certificate.
	//
	// The AddCertificatePairString function does not check if the certificate pair is already in the pool.
	// If you want to avoid adding the same certificate pair twice, you should check the pool before adding the certificate pair.
	//
	// The AddCertificatePairString function returns an error if the PEM encoded string cannot be parsed into a valid certificate pair.
	//
	// The returned error is of type tlscrt.ParseError.
	//
	// The AddCertificatePairString function is used to add a new certificate pair to the TLS configuration.
	// It is used to rotate the certificate pair for example.
	//
	// The AddCertificatePairString function does not affect the currently active certificate pair.
	// The currently active certificate pair is only replaced when the TLS connection is re-established.
	//
	// The AddCertificatePairString function is thread-safe.
	// Multiple goroutines can call the AddCertificatePairString function at the same time without affecting the correctness of the TLS configuration.
	AddCertificatePairString(key, crt string) error
	// AddCertificatePairFile adds a certificate pair to the TLS configuration from a PEM file.
	//
	// The keyFile parameter should be the path to a PEM file containing the private key.
	// The crtFile parameter should be the path to a PEM file containing the certificate.
	//
	// The AddCertificatePairFile function does not check if the certificate pair is already in the pool.
	// If you want to avoid adding the same certificate pair twice, you should check the pool before adding the certificate pair.
	//
	// The AddCertificatePairFile function returns an error if the PEM file cannot be read or if the private key and the certificate in the PEM file are invalid.
	//
	// The returned error is of type tlscrt.ParseError.
	//
	// The AddCertificatePairFile function is used to add a new certificate pair to the TLS configuration.
	// It is used to rotate the certificate pair for example.
	//
	// The AddCertificatePairFile function does not affect the currently active certificate pair.
	// The currently active certificate pair is only replaced when the TLS connection is re-established.
	//
	// The AddCertificatePairFile function is thread-safe.
	// Multiple goroutines can call the AddCertificatePairFile function at the same time without affecting the correctness of the TLS configuration.
	AddCertificatePairFile(keyFile, crtFile string) error
	// LenCertificatePair returns the number of certificate pairs in the TLS configuration.
	//
	// The function is thread-safe.
	// Multiple goroutines can call the LenCertificatePair function at the same time without affecting the correctness of the TLS configuration.
	//
	// The returned value is the number of certificate pairs in the TLS configuration.
	// The returned value does not include the currently active certificate pair.
	// The returned value is zero if the TLS configuration does not contain any certificate pairs.
	LenCertificatePair() int
	// CleanCertificatePair removes all the certificate pairs from the TLS configuration.
	//
	// The CleanCertificatePair function does not affect the currently active certificate pair.
	// The currently active certificate pair is only replaced when the TLS connection is re-established.
	//
	// The CleanCertificatePair function is thread-safe.
	// Multiple goroutines can call the CleanCertificatePair function at the same time without affecting the correctness of the TLS configuration.
	CleanCertificatePair()
	// GetCertificatePair returns all the certificate pairs in the TLS configuration.
	//
	// The returned value is a slice of tls.Certificate.
	// The slice contains all the certificate pairs in the TLS configuration.
	// The slice does not include the currently active certificate pair.
	// The slice is empty if the TLS configuration does not contain any certificate pairs.
	GetCertificatePair() []tls.Certificate

	// SetVersionMin sets the minimum version of TLS supported by the TLS configuration.
	//
	// The minimum version of TLS is the lowest version of TLS that the TLS configuration will support.
	// The TLS configuration will not support any versions of TLS that are lower than the minimum version.
	// The TLS configuration will support all versions of TLS that are equal to or higher than the minimum version.
	//
	// The SetVersionMin function is thread-safe.
	// Multiple goroutines can call the SetVersionMin function at the same time without affecting the correctness of the TLS configuration.
	SetVersionMin(v tlsvrs.Version)
	// GetVersionMin returns the minimum version of TLS supported by the TLS configuration.
	//
	// The returned value is the minimum version of TLS supported by the TLS configuration.
	// The returned value is zero if the TLS configuration does not contain any version of TLS.
	// The returned value is the minimum version of TLS supported by the TLS configuration if the TLS configuration contains multiple versions of TLS.
	// The returned value does not include the version of TLS that is currently active.
	// The returned value is not affected by the version of TLS that is currently active.
	// The returned value is thread-safe.
	// Multiple goroutines can call the GetVersionMin function at the same time without affecting the correctness of the TLS configuration.
	GetVersionMin() tlsvrs.Version
	// SetVersionMax sets the maximum version of TLS supported by the TLS configuration.
	//
	// The function sets the maximum version of TLS supported by the TLS configuration to the specified version.
	//
	// The specified version is the maximum version of TLS supported by the TLS configuration.
	// The specified version must be a valid version of TLS.
	// The specified version must not be less than the minimum version of TLS supported by the TLS configuration.
	//
	// The SetVersionMax function does not affect the currently active version of TLS.
	// The currently active version of TLS is only replaced when the TLS connection is re-established.
	//
	// The SetVersionMax function is thread-safe.
	// Multiple goroutines can call the SetVersionMax function at the same time without affecting the correctness of the TLS configuration.
	SetVersionMax(v tlsvrs.Version)
	// GetVersionMax returns the maximum version of TLS supported by the TLS configuration.
	//
	// The returned value is the maximum version of TLS supported by the TLS configuration.
	// The returned value is zero if the TLS configuration does not contain any version of TLS.
	// The returned value is the maximum version of TLS supported by the TLS configuration if the TLS configuration contains multiple versions of TLS.
	// The returned value does not include the version of TLS that is currently active.
	// The returned value is not affected by the version of TLS that is currently active.
	// The returned value is thread-safe.
	// Multiple goroutines can call the GetVersionMax function at the same time without affecting the correctness of the TLS configuration.
	GetVersionMax() tlsvrs.Version

	// SetCipherList sets the list of ciphers in the TLS configuration.
	//
	// The ciphers to set are specified as a slice of tlscpr.Cipher.
	//
	// The SetCipherList function replaces the current list of ciphers in the TLS configuration.
	// If you want to add ciphers to the current list, you should use the AddCiphers function.
	//
	// The SetCipherList function is thread-safe.
	// Multiple goroutines can call the SetCipherList function at the same time without affecting the correctness of the TLS configuration.
	SetCipherList(c []tlscpr.Cipher)
	// AddCiphers adds one or more ciphers to the TLS configuration.
	//
	// The ciphers to add are specified as a variable number of arguments.
	// Each argument should be of type tlscpr.Cipher.
	//
	// The AddCiphers function does not check if the ciphers are already in the pool.
	// If you want to avoid adding the same ciphers twice, you should check the pool before adding the ciphers.
	//
	// The AddCiphers function is thread-safe.
	// Multiple goroutines can call the AddCiphers function at the same time without affecting the correctness of the TLS configuration.
	AddCiphers(c ...tlscpr.Cipher)
	// GetCiphers returns the list of ciphers in the TLS configuration.
	//
	// The returned value is a slice of tlscpr.Cipher.
	// The slice contains all the ciphers in the TLS configuration.
	// The slice is empty if the TLS configuration does not contain any ciphers.
	// The returned value is ordered by the order the ciphers were added to the configuration.
	// Modifying the returned slice does not affect the original configuration.
	GetCiphers() []tlscpr.Cipher

	// SetCurveList sets the list of curves in the TLS configuration.
	//
	// The list of curves is specified as a slice of tlscrv.Curves.
	//
	// The SetCurveList function replaces the current list of curves in the TLS configuration.
	// If you want to add curves to the current list, you should use the AddCurves function.
	//
	// The SetCurveList function is thread-safe.
	// Multiple goroutines can call the SetCurveList function at the same time without affecting the correctness of the TLS configuration.
	SetCurveList(c []tlscrv.Curves)
	// AddCurves adds one or more curves to the TLS configuration.
	//
	// The curves to add are specified as a variable number of arguments.
	// Each argument should be of type tlscrv.Curves.
	//
	// The AddCurves function does not check if the curves are already in the pool.
	// If you want to avoid adding the same curves twice, you should check the pool before adding the curves.
	//
	// The AddCurves function is thread-safe.
	// Multiple goroutines can call the AddCurves function at the same time without affecting the correctness of the TLS configuration.
	AddCurves(c ...tlscrv.Curves)
	// GetCurves returns the list of curves in the TLS configuration.
	//
	// The returned value is a slice of tlscrv.Curves.
	// The slice contains all the curves in the TLS configuration.
	// The slice is empty if the TLS configuration does not contain any curves.
	// The returned value is ordered by the order the curves were added to the configuration.
	// Modifying the returned slice does not affect the original configuration.
	GetCurves() []tlscrv.Curves

	// SetDynamicSizingDisabled sets the TLS configuration to disable or enable dynamic record sizing.
	//
	// Dynamic record sizing is a feature of TLS that allows the TLS connection to dynamically adjust the size of the records being sent.
	// By default, dynamic record sizing is enabled.
	//
	// The SetDynamicSizingDisabled function takes a boolean as an argument.
	// If the argument is true, dynamic record sizing is disabled.
	// If the argument is false, dynamic record sizing is enabled.
	//
	// The SetDynamicSizingDisabled function is thread-safe.
	// Multiple goroutines can call the SetDynamicSizingDisabled function at the same time without affecting the correctness of the TLS configuration.
	SetDynamicSizingDisabled(flag bool)
	// SetSessionTicketDisabled sets the TLS configuration to disable or enable session tickets.
	//
	// Session tickets are used to resume a TLS connection without needing to re-establish the entire connection.
	// By default, session tickets are enabled.
	//
	// The SetSessionTicketDisabled function takes a boolean as an argument.
	// If the argument is true, session tickets are disabled.
	// If the argument is false, session tickets are enabled.
	//
	// The SetSessionTicketDisabled function is thread-safe.
	// Multiple goroutines can call the SetSessionTicketDisabled function at the same time without affecting the correctness of the TLS configuration.
	SetSessionTicketDisabled(flag bool)

	// Clone returns a copy of the TLSConfig.
	//
	// The returned TLSConfig is safe for concurrent use.
	//
	// The returned TLSConfig is a copy of the TLSConfig.
	// Modifying the returned TLSConfig does not affect the original TLSConfig.
	// The returned TLSConfig is independent of the original TLSConfig.
	// The Clone function is thread-safe.
	// Multiple goroutines can call the Clone function at the same time without affecting the correctness of the TLS configuration.
	Clone() TLSConfig
	// TLS returns a TLS configuration based on the TLSConfig.
	//
	// The returned TLS configuration is safe for concurrent use.
	//
	// The returned TLS configuration is not a copy of the TLSConfig.
	// Instead, it is a reference to the TLSConfig.
	// Modifying the returned TLS configuration affects the TLSConfig.
	// The returned TLS configuration is the same as the TLSConfig.
	//
	// The serverName parameter is the name of the server for which the TLS configuration should be generated.
	// If the serverName parameter is empty, the TLS configuration is generated for an unknown server.
	TLS(serverName string) *tls.Config
	// TlsConfig returns a TLS configuration based on the TLSConfig.
	//
	// The returned TLS configuration is safe for concurrent use.
	//
	// The returned TLS configuration is not a copy of the TLSConfig.
	// Instead, it is a reference to the TLSConfig.
	// Modifying the returned TLS configuration affects the TLSConfig.
	// The returned TLS configuration is the same as the TLSConfig.
	//
	// The serverName parameter is the name of the server for which the TLS configuration is generated.
	// The serverName parameter is used to generate the TLS configuration.
	// The serverName parameter is optional and can be empty.
	// If the serverName parameter is empty, the TLS configuration is generated without a server name.
	TlsConfig(serverName string) *tls.Config
	// Config returns the TLS configuration.
	//
	// The returned TLSConfig is safe for concurrent use.
	//
	// The returned TLSConfig is not a copy of the default TLSConfig.
	// Instead, it is a reference to the default TLSConfig.
	// Modifying the returned TLSConfig affects the default TLSConfig.
	// The returned TLSConfig is the same as the default TLSConfig.
	//
	Config() *Config
}

TLSConfig is the main interface for configuring TLS connections. It provides methods for managing certificates, cipher suites, TLS versions, and other TLS parameters. All operations are thread-safe and can be called concurrently from multiple goroutines.

func New added in v1.5.0

func New() TLSConfig

New returns a new TLSConfig with default values.

The returned TLSConfig is safe for concurrent use.

The returned TLSConfig is not a copy of the default TLSConfig. Instead, it is a new TLSConfig with default values. Modifying the returned TLSConfig does not affect the default TLSConfig. The returned TLSConfig is independent of the default TLSConfig.

Directories

Path Synopsis
Package auth provides client authentication mode types and parsing for TLS connections.
Package auth provides client authentication mode types and parsing for TLS connections.
Package ca provides Certificate Authority (CA) certificate management and parsing.
Package ca provides Certificate Authority (CA) certificate management and parsing.
Package certs provides certificate pair (private key + certificate) management.
Package certs provides certificate pair (private key + certificate) management.
Package cipher provides TLS cipher suite selection and management.
Package cipher provides TLS cipher suite selection and management.
Package curves provides elliptic curve configuration for TLS connections.
Package curves provides elliptic curve configuration for TLS connections.
Package tlsversion provides TLS version management and parsing.
Package tlsversion provides TLS version management and parsing.

Jump to

Keyboard shortcuts

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