tls

package
v0.77.0 Latest Latest
Warning

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

Go to latest
Published: Nov 15, 2026 License: Apache-2.0 Imports: 43 Imported by: 1

Documentation

Overview

Package tls provides utilities for working with TLS certificates and configurations.

Index

Examples

Constants

View Source
const (
	ACMEChallengeTLSALPN01 = "tls-alpn-01"
	ACMEChallengeDNS01     = "dns-01"
)

ACME challenge types accepted by ACMEConfig.Type.

Variables

This section is empty.

Functions

func CertificateFromKeyAndCertificateFiles added in v0.37.0

func CertificateFromKeyAndCertificateFiles(ctx context.Context, key, cert string, waitConfig FileWaitConfig) ([]tls.Certificate, error)

CertificateFromKeyAndCertificateFiles loads certificate and key from separate files.

func CertificatesFromSinglePEMFile added in v0.37.0

func CertificatesFromSinglePEMFile(ctx context.Context, singlePEMFile string, waitConfig FileWaitConfig) ([]tls.Certificate, error)

CertificatesFromSinglePEMFile loads certificate and key from a single PEM file.

func CreateAndSaveSelfSignedKeyPair

func CreateAndSaveSelfSignedKeyPair(config SelfSignedConfig, certPath, keyPath string) (*tls.Certificate, *x509.CertPool, error)

CreateAndSaveSelfSignedKeyPair creates and saves a self-signed key pair to files.

func CreateSelfSignedKeyPair

func CreateSelfSignedKeyPair(config SelfSignedConfig) (*tls.Certificate, *x509.CertPool, error)

CreateSelfSignedKeyPair creates a self-signed key pair in memory. pulled from inet.af/tcpproxy.

func LoadCertPoolFromFS added in v0.55.1

func LoadCertPoolFromFS(fsys fs.FS, certPoolPath string) (*x509.CertPool, error)

LoadCertPoolFromFS loads a certificate pool from a PEM file in the provided filesystem.

func LoadCertPoolFromFile

func LoadCertPoolFromFile(certPoolPath string) (*x509.CertPool, error)

LoadCertPoolFromFile loads a certificate pool from a PEM file.

func LoadKeyPairAndCertsFromFile

func LoadKeyPairAndCertsFromFile(path string) (*tls.Certificate, error)

LoadKeyPairAndCertsFromFile From: https://gist.github.com/ukautz/cd118e298bbd8f0a88fc LoadKeyPairAndCertsFromFile reads file, divides into key and certificates.

func LoadKeyPairFromFiles

func LoadKeyPairFromFiles(certPath, keyPath string) (*tls.Certificate, error)

LoadKeyPairFromFiles loads a TLS certificate and key pair from PEM files.

func LoadX509CertFromFile

func LoadX509CertFromFile(certPath string) (*x509.Certificate, error)

LoadX509CertFromFile loads an X.509 certificate from a PEM file.

func NewACMETLSConfig added in v0.65.0

func NewACMETLSConfig(ctx context.Context, c ACMEConfig) (*tls.Config, error)

NewACMETLSConfig obtains a certificate via ACME using the challenge type selected by c.Type, dispatching to the tls-alpn-01 (autocert-backed) or dns-01 (lego-backed) implementation.

func NewAutocertManagerFromConfig added in v0.37.0

func NewAutocertManagerFromConfig(c ACMEConfig) *autocert.Manager

NewAutocertManagerFromConfig creates an ACME autocert manager from the given config. Why the CA rejects a request or a validation is logged with zerolog's default context logger.

func NewClientTLSConfig added in v0.37.0

func NewClientTLSConfig(c ClientConfig) (*tls.Config, error)

NewClientTLSConfig creates a TLS configuration for a client from the given config.

Example

A server that reads its certificate from files, and a client that trusts it through a root CA file.

package main

import (
	"context"
	"fmt"
	"io"
	"net/http"
	"net/http/httptest"
	"os"
	"path/filepath"

	diotls "github.com/dioad/net/tls"
)

// selfSigned describes a certificate for a server reached at 127.0.0.1.
var selfSigned = diotls.SelfSignedConfig{
	Subject:  diotls.CertificateSubject{CommonName: "localhost"},
	SAN:      diotls.SANConfig{DNSNames: []string{"localhost"}, IPAddresses: []string{"127.0.0.1"}},
	Bits:     2048,
	Duration: "1h",
}

func main() {
	dir, err := os.MkdirTemp("", "tls-example-*")
	if err != nil {
		fmt.Println("temp dir:", err)

		return
	}
	defer func() { _ = os.RemoveAll(dir) }()

	certFile := filepath.Join(dir, "cert.pem")
	keyFile := filepath.Join(dir, "key.pem")
	if _, _, err := diotls.CreateAndSaveSelfSignedKeyPair(selfSigned, certFile, keyFile); err != nil {
		fmt.Println("key pair:", err)

		return
	}

	serverTLS, err := diotls.NewServerTLSConfig(context.Background(), diotls.ServerConfig{
		LocalConfig: diotls.LocalConfig{Certificate: certFile, Key: keyFile},
	})
	if err != nil {
		fmt.Println("server tls config:", err)

		return
	}
	clientTLS, err := diotls.NewClientTLSConfig(diotls.ClientConfig{RootCAFile: certFile})
	if err != nil {
		fmt.Println("client tls config:", err)

		return
	}

	server := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
		_, _ = io.WriteString(w, "hello over TLS")
	}))
	server.TLS = serverTLS
	server.StartTLS()
	defer server.Close()

	client := &http.Client{Transport: &http.Transport{TLSClientConfig: clientTLS}}
	req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, server.URL, nil)
	if err != nil {
		fmt.Println("request:", err)

		return
	}
	resp, err := client.Do(req)
	if err != nil {
		fmt.Println("get:", err)

		return
	}
	defer func() { _ = resp.Body.Close() }()
	body, _ := io.ReadAll(resp.Body)

	fmt.Println(resp.StatusCode, string(body))
}
Output:
200 hello over TLS

func NewLocalTLSConfig added in v0.37.0

func NewLocalTLSConfig(ctx context.Context, config LocalConfig) (*tls.Config, error)

NewLocalTLSConfig creates a TLS configuration from local certificate and key files.

func NewSelfSignedTLSConfig added in v0.37.0

func NewSelfSignedTLSConfig(config SelfSignedConfig) (*tls.Config, error)

NewSelfSignedTLSConfig creates a TLS configuration with a self-signed certificate.

func NewServerTLSConfig added in v0.37.0

func NewServerTLSConfig(ctx context.Context, c ServerConfig) (*tls.Config, error)

NewServerTLSConfig creates a TLS configuration for a server from the given config.

Example

A ServerConfig names one source for the server's certificate: ACME, a self-signed certificate made at startup, or local files. This one is self-signed.

package main

import (
	"context"
	"crypto/tls"
	"fmt"

	diotls "github.com/dioad/net/tls"
)

// selfSigned describes a certificate for a server reached at 127.0.0.1.
var selfSigned = diotls.SelfSignedConfig{
	Subject:  diotls.CertificateSubject{CommonName: "localhost"},
	SAN:      diotls.SANConfig{DNSNames: []string{"localhost"}, IPAddresses: []string{"127.0.0.1"}},
	Bits:     2048,
	Duration: "1h",
}

func main() {
	tlsConfig, err := diotls.NewServerTLSConfig(context.Background(), diotls.ServerConfig{
		SelfSigned:    selfSigned,
		TLSMinVersion: "TLS13",
	})
	if err != nil {
		fmt.Println("server tls config:", err)

		return
	}

	fmt.Println("minimum version:", tls.VersionName(tlsConfig.MinVersion))
}
Output:
minimum version: TLS 1.3

func SaveTLSCertificateToFile added in v0.37.6

func SaveTLSCertificateToFile(cert *tls.Certificate, filename string, perm int) error

SaveTLSCertificateToFile saves a tls.Certificate to a file: its whole certificate chain, leaf first, then its private key.

func SaveTLSCertificateToFiles

func SaveTLSCertificateToFiles(cert *tls.Certificate, certPath, keyPath string) error

SaveTLSCertificateToFiles saves a tls.Certificate to a certificate and key file. The certificate file holds the whole chain, leaf first, so a server that loads it sends clients the intermediates they need to verify the leaf.

Types

type ACMEConfig added in v0.65.0

type ACMEConfig struct {
	// Type selects the ACME challenge mechanism: ACMEChallengeTLSALPN01 or
	// ACMEChallengeDNS01. An absent/empty Type (the zero value) defaults to
	// ACMEChallengeTLSALPN01, so callers who only need TLS-ALPN-01 can omit
	// this field entirely.
	Type string `json:"type,omitempty" mapstructure:"type"`

	Email          string `json:"email,omitempty"           mapstructure:"email"`
	DirectoryURL   string `json:"directory_url,omitempty"   mapstructure:"directory-url"`
	CacheDirectory string `json:"cache_directory,omitempty" mapstructure:"cache-directory"`

	// Domains is, for Type=dns-01, the SANs to include on the single
	// certificate obtained upfront (may include wildcards, e.g.
	// "*.example.com"); for Type=tls-alpn-01 (default), the whitelist of
	// hosts autocert will provision certificates for on demand via
	// autocert.HostWhitelist. Wildcard entries are rejected for
	// tls-alpn-01 - TLS-ALPN-01 cannot validate wildcard identifiers (RFC
	// 8555 permits wildcards only via dns-01), and autocert's HostWhitelist
	// silently ignores such entries rather than erroring, so
	// NewACMETLSConfig validates this upfront instead.
	Domains []string `json:"domains,omitempty" mapstructure:"domains"`

	// DNS01 holds fields that apply only when Type is ACMEChallengeDNS01.
	DNS01 DNS01Options `json:"dns01,omitzero" mapstructure:"dns01,squash"`
}

ACMEConfig specifies parameters for obtaining a certificate via ACME, using either the tls-alpn-01 challenge (delegated to golang.org/x/crypto/acme/autocert) or the dns-01 challenge (a hand-rolled github.com/go-acme/lego/v5 client). The two challenge types share the same account identity and cache directory, but obtain certificates through entirely independent runtime implementations - only the config surface is unified here.

type CertificateSubject added in v0.37.0

type CertificateSubject struct {
	Country            []string `json:"country,omitzero"             mapstructure:"c"`
	Organization       []string `json:"organization,omitzero"        mapstructure:"o"`
	OrganizationalUnit []string `json:"organizational_unit,omitzero" mapstructure:"ou"`
	Locality           []string `json:"locality,omitzero"            mapstructure:"l"`
	Province           []string `json:"province,omitzero"            mapstructure:"st"`
	StreetAddress      []string `json:"street_address,omitzero"      mapstructure:"street"`
	PostalCode         []string `json:"postal_code,omitzero"         mapstructure:"postalcode"`
	SerialNumber       string   `json:"serial_number,omitzero"       mapstructure:"serialnumber"`
	CommonName         string   `json:"common_name,omitzero"         mapstructure:"cn"`
}

CertificateSubject defines X.509 certificate subject information.

type ClientConfig

type ClientConfig struct {
	RootCAFile         string `json:"root_ca_file,omitempty"         mapstructure:"root-ca-file"`
	Certificate        string `json:"certificate,omitempty"          mapstructure:"cert"`
	Key                string `json:"key,omitempty"                  mapstructure:"key"`
	InsecureSkipVerify bool   `json:"insecure_skip_verify,omitempty" mapstructure:"insecure-skip-verify"`
}

ClientConfig specifies TLS client configuration.

func (*ClientConfig) Check added in v0.72.0

func (c *ClientConfig) Check(findings *configcheck.Collector)

Check reports the problems in a tls-client block to findings, which should be positioned at the block: a client certificate needs both its cert and its key. A nil block is not set at this level and is not checked.

Example
package main

import (
	"fmt"

	"github.com/dioad/config/configcheck"
	dnt "github.com/dioad/net/tls"
)

func main() {
	cfg := dnt.ClientConfig{Certificate: "client.pem"}

	findings := configcheck.NewCollector()
	cfg.Check(findings.Field("tls-client"))

	fmt.Println(findings.Findings()[0])
}
Output:
tls-client: needs both cert and key for a client certificate

type ConfigFunc added in v0.37.0

type ConfigFunc func() (*tls.Config, error)

ConfigFunc is a function type that returns a TLS configuration.

func NewACMETLSConfigFunc added in v0.65.0

func NewACMETLSConfigFunc(ctx context.Context, c ACMEConfig) ConfigFunc

NewACMETLSConfigFunc creates a ConfigFunc for ACME certificate configuration. ctx bounds the lifetime of any background renewal goroutine started for the dns-01 challenge type, and is also passed to every ACME call made on this arm's behalf.

func NewLocalTLSConfigFunc added in v0.37.0

func NewLocalTLSConfigFunc(ctx context.Context, c LocalConfig) ConfigFunc

NewLocalTLSConfigFunc creates a ConfigFunc for loading certificates from local files.

func NewSelfSignedTLSConfigFunc added in v0.37.0

func NewSelfSignedTLSConfigFunc(c SelfSignedConfig) ConfigFunc

NewSelfSignedTLSConfigFunc creates a ConfigFunc for self-signed certificate configuration.

type DNS01Options added in v0.65.0

type DNS01Options struct {
	// PropagationTimeout bounds how long lego waits for DNS propagation of
	// the challenge TXT record. Zero uses lego's default (60s).
	PropagationTimeout time.Duration `json:"propagation_timeout,omitempty" mapstructure:"dns01-propagation-timeout"`

	// PollingInterval controls how often lego polls while waiting for
	// propagation. Zero uses lego's default (2s).
	PollingInterval time.Duration `json:"polling_interval,omitempty" mapstructure:"dns01-polling-interval"`

	// Provider performs Present/CleanUp of the ACME dns-01 challenge TXT
	// record. Must be set programmatically; it is not config-decodable.
	Provider challenge.Provider `json:"-" mapstructure:"-"`
}

DNS01Options specifies dns-01-only ACME parameters.

type FileWaitConfig added in v0.37.0

type FileWaitConfig struct {
	WaitInterval uint `json:"wait_interval,omitzero" mapstructure:"file-wait-interval"`
	WaitMax      uint `json:"wait_max,omitzero"      mapstructure:"file-wait-max"`
}

FileWaitConfig specifies wait parameters for loading certificate files.

type LocalConfig added in v0.37.0

type LocalConfig struct {
	SinglePEMFile string         `json:"single_pem_file,omitzero" mapstructure:"single-pem-file"`
	Certificate   string         `json:"certificate,omitzero"     mapstructure:"cert"`
	Key           string         `json:"key,omitzero"             mapstructure:"key"`
	FileWait      FileWaitConfig `json:"file_wait,omitzero"       mapstructure:"file-wait,squash"`
}

LocalConfig specifies local certificate and key file locations.

type SANConfig added in v0.37.0

type SANConfig struct {
	DNSNames    []string `json:"dns_names,omitzero"    mapstructure:"dns-names"`
	IPAddresses []string `json:"ip_addresses,omitzero" mapstructure:"ip-addresses"`
}

SANConfig specifies Subject Alternative Names for a certificate (DNS names and IP addresses).

type SelfSignedConfig

type SelfSignedConfig struct {
	Subject        CertificateSubject `json:"subject"                  mapstructure:"subject"`
	SAN            SANConfig          `json:"san"                      mapstructure:"san"`
	Duration       string             `json:"duration,omitzero"        mapstructure:"duration"`
	IsCA           bool               `json:"is_ca,omitzero"           mapstructure:"ca"`
	Bits           int                `json:"bits,omitzero"            mapstructure:"bits"`
	CacheDirectory string             `json:"cache_directory,omitzero" mapstructure:"cache-directory"`
	Alias          string             `json:"alias,omitzero"           mapstructure:"alias"`
}

SelfSignedConfig specifies parameters for generating a self-signed certificate.

type ServerConfig

type ServerConfig struct {
	ServerName string `json:"server_name,omitzero" mapstructure:"server-name"`

	ACME ACMEConfig `json:"acme" mapstructure:"acme"`

	SelfSigned SelfSignedConfig `json:"self_signed" mapstructure:"self-signed"`

	LocalConfig LocalConfig `json:"local" mapstructure:"local"`

	ClientAuthType string `json:"client_auth_type,omitzero" mapstructure:"client-auth-type"`
	ClientCAFile   string `json:"client_ca_file,omitzero"   mapstructure:"client-ca-file"`

	NextProtos    []string `json:"next_protos,omitzero"     mapstructure:"next-protos"`
	TLSMinVersion string   `json:"tls_min_version,omitzero" mapstructure:"tls-min-version"`
}

ServerConfig specifies TLS configuration for a server.

func (*ServerConfig) Check added in v0.72.0

func (c *ServerConfig) Check(findings *configcheck.Collector)

Check reports the problems in a tls-server block to findings, which should be positioned at the block. It mirrors what this package does with the block, so a config Check passes is one NewServerTLSConfig accepts and means what it says:

  • only the first of acme, self-signed and local that is set is used, in that order, so setting more than one leaves the others silently unused;
  • a local block needs a single-pem-file, or both a cert and a key, and not both forms;
  • client-ca-file is loaded whatever client-auth-type says, but client certificates are checked only when the type asks for it, so a CA file with no type reads as mutual TLS and enforces nothing;
  • an unrecognised client-auth-type is treated as NoClientCert.

A nil block is not set at this level and is not checked.

Example
package main

import (
	"fmt"

	"github.com/dioad/config/configcheck"
	dnt "github.com/dioad/net/tls"
)

func main() {
	cfg := dnt.ServerConfig{
		LocalConfig:  dnt.LocalConfig{Certificate: "server.pem"},
		ClientCAFile: "clients.pem",
	}

	findings := configcheck.NewCollector()
	cfg.Check(findings.Field("tls-server"))

	for _, f := range findings.Findings() {
		fmt.Println(f.Path)
	}
}
Output:
tls-server.local
tls-server.client-ca-file

func (*ServerConfig) RequiresClientCertificate added in v0.75.0

func (c *ServerConfig) RequiresClientCertificate() bool

RequiresClientCertificate reports whether the config makes every client present a certificate that verifies against client-ca-file, so that a listener using it authenticates its callers.

Jump to

Keyboard shortcuts

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