Documentation
¶
Overview ¶
Package tlsutils provides TLS certificate loading and secure configuration utilities. Supports multiple certificate sources (file, Vault, Let's Encrypt), private key formats (PKCS#8, PKCS#1, SEC1), and enforces modern TLS 1.2+ defaults. ParsePrivateKeyPEM loads standalone signing keys using the same decryption and parsing path as TLS loading, including encrypted PKCS#8 and legacy PEM.
Example:
cert, _ := tlsutils.LoadFromFile("server.key", "server.crt", "password")
config := tlsutils.DefaultTLSConfig()
config.Certificates = []tls.Certificate{*cert}
caPool, _ := tlsutils.BuildCAPool(true, "custom-ca.crt")
config.RootCAs = caPool
Index ¶
- Variables
- func ApplyMinTLSVersion(tlsConfig *tls.Config, raw string) error
- func BuildCAPool(system bool, caPath ...string) (*x509.CertPool, error)
- func ClientTLSConfig(src clientCertificateSource, serverName string) *tls.Config
- func CloneCertificateWithOCSPStaple(cert *tls.Certificate, ocspStaple []byte) *tls.Certificate
- func DefaultClientTLSConfig(serverName string) *tls.Config
- func DefaultClientTLSConfigStrict(serverName string) *tls.Config
- func DefaultTLSConfig() *tls.Config
- func DefaultTLSConfigStrict() *tls.Config
- func DialContext(ctx context.Context, network, addr string, src clientCertificateSource, ...) (net.Conn, error)
- func LoadFromBytes(certPem, keyPem []byte, keyPassword string) (*tls.Certificate, error)
- func LoadFromConcatenatedFile(certKeyFilePath, keyPassword string) (*tls.Certificate, error)
- func LoadFromFile(keyPath, certPath, keyPassword string) (*tls.Certificate, error)
- func ParsePrivateKeyPEM(pemData []byte, password string) (crypto.Signer, error)
- func ResolveMinTLSVersion(s string) (uint16, bool)
- type OCSPStapler
- type PrivateKeyError
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ErrIncorrectPassword = errors.New("incorrect private key password")
ErrIncorrectPassword indicates a decryption failure identified as an incorrect password. Unauthenticated encryption cannot distinguish all corrupt keys from incorrect passwords. It also indicates an encrypted payload that decrypts but cannot be parsed as a private key.
var ErrInvalidPrivateKey = errors.New("invalid private key")
ErrInvalidPrivateKey indicates missing, malformed, unsupported, or excessively costly private key data. For encrypted keys, a decrypted payload that cannot be parsed instead returns ErrIncorrectPassword: unauthenticated encryption cannot always distinguish a wrong password from a corrupt key.
var ErrPasswordRequired = errors.New("private key password required")
ErrPasswordRequired indicates an encrypted key was supplied without a password.
Functions ¶
func ApplyMinTLSVersion ¶
ApplyMinTLSVersion resolves the YAML-supplied minVersion string into a tls.VersionTLSxx constant via ResolveMinTLSVersion and applies it to the provider-supplied tls.Config. When the operator pins TLS 1.3 the legacy 1.2 cipher list seeded by the provider is cleared so the resulting config matches DefaultTLSConfigStrict semantics — otherwise CipherSuites stays populated with 1.2-only entries that the stdlib silently ignores under TLS 1.3 and operators reading the config would assume those suites are still meaningful.
An empty minVersion (legacy callers, or YAML that omitted the field) is accepted as "leave the provider default in place"; any other unknown value is rejected so a typo (e.g. "v1.3") cannot silently fall back to the stdlib default.
func BuildCAPool ¶
BuildCAPool builds a certificate pool from CA certificate files. If a system is true, starts with the system's certificate pool. Additional CA certificates from caPath files are appended to the pool. Returns nil if no valid certificates are found.
Example:
pool, err := tlsutils.BuildCAPool(true, "ca1.crt", "ca2.crt")
if err != nil {
log.Fatal(err)
}
config.RootCAs = pool
func ClientTLSConfig ¶
ClientTLSConfig builds a TLS 1.3 client configuration that presents a client certificate supplied by src on every handshake, for mutual TLS on outgoing connections. The certificate is pulled per handshake, so a rotating source (file watcher, Vault lease) is reflected without rebuilding the config. serverName is used for SNI and server-certificate verification against the system roots; set RootCAs on the returned config to pin a private CA.
Example:
cfg := tlsutils.ClientTLSConfig(provider, "peer.internal")
conn, err := tls.Dial("tcp", "peer.internal:8443", cfg)
func CloneCertificateWithOCSPStaple ¶
func CloneCertificateWithOCSPStaple(cert *tls.Certificate, ocspStaple []byte) *tls.Certificate
CloneCertificateWithOCSPStaple creates a shallow copy of the certificate with the provided OCSP staple. This is useful when updating OCSP responses without modifying the original certificate.
func DefaultClientTLSConfig ¶
DefaultClientTLSConfig returns a secure default TLS configuration for client connections. The configuration enforces TLS 1.2+ and sets the server name for certificate validation. The serverName parameter is used for SNI and certificate verification.
Example:
config := tlsutils.DefaultClientTLSConfig("example.com")
conn, err := tls.Dial("tcp", "example.com:443", config)
func DefaultClientTLSConfigStrict ¶
DefaultClientTLSConfigStrict is the client-side counterpart of DefaultTLSConfigStrict. Use when you control both endpoints and want to force TLS 1.3 across the wire.
func DefaultTLSConfig ¶
DefaultTLSConfig returns a secure default TLS configuration. The configuration enforces TLS 1.2+ and uses modern cipher suites. Suitable for most server applications requiring secure connections.
Example:
config := tlsutils.DefaultTLSConfig()
config.Certificates = []tls.Certificate{cert}
server := &http.Server{TLSConfig: config}
func DefaultTLSConfigStrict ¶
DefaultTLSConfigStrict returns a server TLS configuration that requires TLS 1.3. Modern clients all support TLS 1.3; locking it as the minimum drops the long tail of weak suites the TLS 1.2 path allows and removes downgrade attack surface entirely. The CipherSuites field is intentionally left empty — for TLS 1.3 the stdlib enforces its own modern AEAD-only list and the TLS 1.2 pinned suites are ignored.
Example:
config := tlsutils.DefaultTLSConfigStrict()
config.Certificates = []tls.Certificate{cert}
server := &http.Server{TLSConfig: config}
func DialContext ¶
func DialContext(ctx context.Context, network, addr string, src clientCertificateSource, serverName string) (net.Conn, error)
DialContext opens a mutual-TLS connection to addr, presenting the client certificate from src. It is a thin convenience over ClientTLSConfig and tls.Dialer. An empty serverName lets the dialer derive it from addr.
Example:
conn, err := tlsutils.DialContext(ctx, "tcp", "peer.internal:8443", provider, "")
func LoadFromBytes ¶
func LoadFromBytes(certPem, keyPem []byte, keyPassword string) (*tls.Certificate, error)
LoadFromBytes loads a certificate and private key from raw PEM bytes. certPem may hold the full chain, leaf first; every certificate is kept. Certificates are read only from certPem and the private key only from keyPem. Supports multiple private key formats including PKCS#8, PKCS#1 (RSA), SEC1 (EC), and legacy-encrypted PEM formats. The keyPassword parameter is required for encrypted private keys and ignored for unencrypted keys.
Encrypted PKCS#8 keys follow the KDF allowlist and cost limits documented in ParsePrivateKeyPEM.
Example:
cert, err := tlsutils.LoadFromBytes(certPem, keyPem, "password")
if err != nil {
log.Fatal(err)
}
func LoadFromConcatenatedFile ¶
func LoadFromConcatenatedFile(certKeyFilePath, keyPassword string) (*tls.Certificate, error)
LoadFromConcatenatedFile loads a certificate and private key from a single file. The file should contain both the certificate and private key in PEM format; certificates after the leaf are kept as the chain. The keyPassword parameter is required for encrypted private keys.
Encrypted PKCS#8 keys follow the KDF allowlist and cost limits documented in ParsePrivateKeyPEM.
Example:
cert, err := tlsutils.LoadFromConcatenatedFile("server.pem", "password")
if err != nil {
log.Fatal(err)
}
func LoadFromFile ¶
func LoadFromFile(keyPath, certPath, keyPassword string) (*tls.Certificate, error)
LoadFromFile loads a certificate and private key from separate files. Supports multiple private key formats including PKCS#8, PKCS#1 (RSA), SEC1 (EC), and legacy-encrypted PEM formats. The keyPassword parameter is required for encrypted private keys and ignored for unencrypted keys.
Encrypted PKCS#8 keys follow the KDF allowlist and cost limits documented in ParsePrivateKeyPEM.
Example:
cert, err := tlsutils.LoadFromFile("server.key", "server.crt", "password")
if err != nil {
log.Fatal(err)
}
func ParsePrivateKeyPEM ¶ added in v0.2.0
ParsePrivateKeyPEM parses the first private key PEM block as a crypto.Signer. Certificates and other non-key blocks are skipped; missing or invalid keys return a *PrivateKeyError. Supported keys are Ed25519, ECDSA, and RSA in PKCS#8, PKCS#1, or SEC1 format, matching the TLS loading path. Password decrypts encrypted PKCS#8 and legacy encrypted PEM; it is ignored for unencrypted keys. An empty password is for unencrypted keys.
Encrypted PKCS#8 keys allow only PBKDF2 (1 to 10,000,000 iterations) and scrypt (128*N*r <= 1 GiB). Scrypt requires power-of-two N from 2 to 1,048,576, r from 1 to 32, p from 1 to 16, and N*r*p <= 8,388,608. Unsupported KDFs or excessive costs return ErrInvalidPrivateKey before decryption. These limits also apply to TLS loading and reject keys previously accepted without bounds.
Example ¶
package main
import (
"crypto/ed25519"
"crypto/rand"
"crypto/x509"
"encoding/pem"
"fmt"
"log"
tlsutils "github.com/altessa-s/go-tlsutils"
)
func main() {
_, key, err := ed25519.GenerateKey(rand.Reader)
if err != nil {
log.Fatal(err)
}
der, err := x509.MarshalPKCS8PrivateKey(key)
if err != nil {
log.Fatal(err)
}
data := pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: der})
signer, err := tlsutils.ParsePrivateKeyPEM(data, "")
if err != nil {
log.Fatal(err)
}
fmt.Printf("%T\n", signer)
}
Output: ed25519.PrivateKey
func ResolveMinTLSVersion ¶
ResolveMinTLSVersion translates a human-readable version string ("1.2" / "1.3") into the corresponding tls.VersionTLSxx constant. Empty or unrecognized inputs return the safe default (tls.VersionTLS12) and report ok=false so callers can reject the config rather than silently accept a typo that would otherwise be ignored. Mirrors the project's safety-mode pattern of fail-safe-on-unknown.
Recognized values (case-insensitive, leading/trailing space trimmed):
- "1.2", "tls1.2", "tlsv1.2" → tls.VersionTLS12
- "1.3", "tls1.3", "tlsv1.3" → tls.VersionTLS13
Types ¶
type OCSPStapler ¶
type OCSPStapler interface {
// GetOCSPStaple returns the OCSP staple for the given certificate.
// The context controls the HTTP request timeout and cancellation.
GetOCSPStaple(ctx context.Context, cert *tls.Certificate) ([]byte, error)
// RunRefreshAll refreshes all OCSP responses in the cache that need it.
// This method is designed to be called periodically via an external scheduler.
RunRefreshAll(ctx context.Context) error
}
OCSPStapler defines the interface for OCSP stapling functionality. OCSP stapling improves TLS handshake performance by including certificate revocation status in the TLS handshake, reducing client-side OCSP requests.
type PrivateKeyError ¶ added in v0.2.0
type PrivateKeyError struct {
Err error
}
PrivateKeyError describes a private key parsing failure. Unwrap exposes its sentinel cause for errors.Is: ErrInvalidPrivateKey, ErrIncorrectPassword, or ErrPasswordRequired. Messages never include key data or passwords.
func (*PrivateKeyError) Error ¶ added in v0.2.0
func (e *PrivateKeyError) Error() string
Error returns "parse private key", followed by the cause when there is one.
func (*PrivateKeyError) Unwrap ¶ added in v0.2.0
func (e *PrivateKeyError) Unwrap() error
Unwrap returns the parsing failure's cause.
Directories
¶
| Path | Synopsis |
|---|---|
|
internal
|
|
|
testhelpers
Package testhelpers holds the TLS test fixtures shared by the go-tlsutils packages: key generation, self-signed certificates, a test CA that signs leaves, and temporary PEM files.
|
Package testhelpers holds the TLS test fixtures shared by the go-tlsutils packages: key generation, self-signed certificates, a test CA that signs leaves, and temporary PEM files. |
|
Package ocsp provides OCSP stapling for TLS certificates with caching.
|
Package ocsp provides OCSP stapling for TLS certificates with caching. |
|
Package tlsproviders defines interfaces for TLS certificate providers.
|
Package tlsproviders defines interfaces for TLS certificate providers. |
|
file
Package tlsfile provides file-based TLS certificate provider with optional automatic reloading.
|
Package tlsfile provides file-based TLS certificate provider with optional automatic reloading. |
|
internal/certconfig
Package certconfig holds the reload steps shared by the TLS providers that load a certificate and republish it on change (file, S3): Build turns the loaded certificate into the server config to publish, with OCSP stapling installed before publication, and Notify signals a reload without blocking.
|
Package certconfig holds the reload steps shared by the TLS providers that load a certificate and republish it on change (file, S3): Build turns the loaded certificate into the server config to publish, with OCSP stapling installed before publication, and Notify signals a reload without blocking. |
|
internal/staplertest
Package staplertest holds test doubles shared by the TLS provider tests: a CountingStapler that records OCSP staple requests and Handshake, which drives one in-memory TLS handshake against a server config so the config's GetCertificate callback runs with a real handshake context.
|
Package staplertest holds test doubles shared by the TLS provider tests: a CountingStapler that records OCSP staple requests and Handshake, which drives one in-memory TLS handshake against a server config so the config's GetCertificate callback runs with a real handshake context. |
|
letsencrypt
Package tlsletsencrypt provides Let's Encrypt TLS certificate provider using HTTP-01 ACME challenges.
|
Package tlsletsencrypt provides Let's Encrypt TLS certificate provider using HTTP-01 ACME challenges. |
|
s3
module
|
|
|
vault
module
|
|
|
spiffe
module
|