simplecert

package module
v1.8.8 Latest Latest
Warning

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

Go to latest
Published: Mar 29, 2024 License: MIT Imports: 31 Imported by: 19

README

     _                 _                    _
 ___(_)_ __ ___  _ __ | | ___  ___ ___ _ __| |_
/ __| | '_ ` _ \| '_ \| |/ _ \/ __/ _ \ '__| __|
\__ \ | | | | | | |_) | |  __/ (_|  __/ |  | |_
|___/_|_| |_| |_| .__/|_|\___|\___\___|_|   \__|
                |_|

Golang Library for automatic LetsEncrypt SSL Certificates

Go Report Card License Golang Linux macOS windows GoDoc

Obtains certificates automatically, and manages renewal and hot reload for your Golang application. It uses the LEGO Library to perform ACME challenges, and the mkcert utility to generate self-signed trusted certificates for local development.

Main goals:

  • ease of use: simplicity and integration with go standard library
  • transparency: products of intermediate steps are preserved, dedicated logfile for simplecert
  • flexibility: configurable design and cross platform support

UPDATE: The vendored lego version has been updated to v2.2.0 and now supports issuing wildcard certificates by using ACMEv2 challenges.

You need to supply the following data to simplecert: Domains, Contact Email and a Directory to store the certs in (CacheDir). On startup, call the simplecert.Init() function and pass your config. You will receive a certReloader instance, that has a GetCertificateFunc to allow hot reloading the cert upon renewal. See Usage for a detailed example.

A new certificate will be obtained automatically if the domains have changed, both in local and in production mode.

For more advanced usage, see the config section for all configuration options.

Index

Install

go get -u -v github.com/foomo/simplecert

API

Simplecert provides a few wrappers similar to http.ListenAndServe from the go standard library:

For running on a production server:

func ListenAndServeTLS(addr string, handler http.Handler, mail string, cleanup func(), domains ...string) error

For local development:

func ListenAndServeTLSLocal(addr string, handler http.Handler, cleanup func(), domains ...string) error

The custom wrapper allows to pass a simplecert.Config and a tls.Config:

func ListenAndServeTLSCustom(addr string, handler http.Handler, cfg *Config, tlsconf *tls.Config, cleanup func(), domains ...string) error

There is a util for redirecting HTTP requests to HTTPS:

func Redirect(w http.ResponseWriter, req *http.Request)

And a function to initialize simplecert after applying the desired configuration:

func Init(cfg *Config, cleanup func()) (*CertReloader, error)

The cleanup function will be called upon receiving the syscall.SIGINT or syscall.SIGABRT signal and can be used to stop your backend gracefully. If you don't need it, simpy pass nil.

Local Development

To make local development less of a pain, simplecert integrates mkcert, to obtain self signed certificates for your desired domains, trusted by your computer.

Follow the installation instructions to install the mkcert commandline tool.

In order to use simplecert for local development, set the Local field in the config to true.

Certificates generated for local development are not checked for expiry, the certificates generated by mkcert are valid for 10 years!

Important:

Using wildcard certificates in local mode does not work out of the box, since /etc/hosts doesn't support resolving wild card entries.

You'll have to use other services like dnsmasq. Just edit dnsmasq.conf and add the following line:

address=/yourdomain.com/127.0.0.1

This will resolve all requests to domains that end on yourdomain.com with 127.0.0.1.

Host Entries

To resolve the domain name for your certificate to your localhost, simplecert adds an entry for each domain name to your /etc/hosts file.

This can be disabled by setting the UpdateHosts field in the config to false.

Usage

Simplecert has a default configuration available: simplecert.Default

You will need to update the Domains, CacheDir and SSLEmail and you are ready to go.

// init simplecert
cfg := simplecert.Default
cfg.Domains = []string{"yourdomain.com", "www.yourdomain.com"}
cfg.CacheDir = "/etc/letsencrypt/live/yourdomain.com"
cfg.SSLEmail = "you@emailprovider.com"
cfg.DNSProvider = "cloudflare"
certReloader, err := simplecert.Init(cfg, nil)
if err != nil {
    log.Fatal("simplecert init failed: ", err)
}

// channel to handle errors
errChan := make(chan error)

// redirect HTTP to HTTPS
// CAUTION: This has to be done AFTER simplecert setup
// Otherwise Port 80 will be blocked and cert registration fails!
log.Println("starting HTTP Listener on Port 80")
go func(){
    errChan <- http.ListenAndServe(":80", http.HandlerFunc(simplecert.Redirect))
}()

// init strict tlsConfig with certReloader
// you could also use a default &tls.Config{}, but be warned this is highly insecure
// our foomo/tlsconfig provides a simple interface to configure the tls for different scenarios 
tlsconf := tlsconfig.NewServerTLSConfig(tlsconfig.TLSModeServerStrict)

// now set GetCertificate to the reloaders GetCertificateFunc to enable hot reload
tlsconf.GetCertificate = certReloader.GetCertificateFunc()

// init server
s := &http.Server{
    Addr:      ":443",
    TLSConfig: tlsconf,
}

// start serving in a new goroutine
go func() {
    errChan <- s.ListenAndServeTLS("", "")
}()

// fatal on any errors
log.Fatal(<-errChan)

Challenges

Simplecert uses the letsencrypt ACMEv2 API and supports HTTP, TLS and DNS Challenges.

For the DNS challenge, an API token of an provider must be exported as environment variable.

Graceful service shutdown and restart

In case of using the HTTP or TLS challenges, port 80 or 443 must temporarily be freed.

The simplecert.Config contains two functions that can be set to accomplish this:

  • WillRenewCertificate, called just before the certificate will be renewed.
  • DidRenewCertificate, called after the certificate was renewed.

These functions can be used to gracefully stop the running service, and bring it back up once the certificate renewal is complete.

If you want to exchange the certificates manually on disk and force the running service to reload them, simply send a SIGHUP signal to your running instance:

kill -HUP <pid>

Backup mechanism

Simplecert creates a backup of your old certificate when it is being renewed.

All data is stored in the configured CacheDir.

In case something goes wrong while renewing, simplecert will rollback to the original cert.

Configuration

You can pass a custom simplecert.Config to suit your needs.

Parameters are explained below.

// Config allows configuration of simplecert
type Config struct {

    // renew the certificate X hours before it expires
    // LetsEncrypt Certs are valid for 90 Days
    RenewBefore int

    // Interval for checking if cert is closer to expiration than RenewBefore
    CheckInterval time.Duration

    // SSLEmail for contact
    SSLEmail string

    // ACME Directory URL. 
    // Can be set to https://acme-staging.api.letsencrypt.org/directory for testing
    DirectoryURL string

    // Endpoints for webroot challenge
    // CAUTION: challenge must be received on port 80 and 443
    // if you choose different ports here you must redirect the traffic
    HTTPAddress string
    TLSAddress  string

    // UNIX Permission for the CacheDir and all files inside
    CacheDirPerm os.FileMode

    // Domains for which to obtain the certificate
    Domains []string

    // Path of the CacheDir
    CacheDir string

    // DNSProvider name for DNS challenges (optional)
    // see: https://godoc.org/github.com/go-acme/lego/providers/dns
    DNSProvider string

    // Local runmode
    Local bool

    // UpdateHosts adds the domains to /etc/hosts if running in local mode
    UpdateHosts bool

    // Handler funcs for graceful service shutdown and restoring
    WillRenewCertificate func()
    DidRenewCertificate  func()
    FailedToRenewCertificate func(error)
}

Examples

The examples directory contains two simple use cases.

A custom initialization:

go run examples/custom/main.go

And a simple example for local development with a locally trusted certificate (requires mkcert to be installed):

go run examples/simple/main.go

Debug

Simplecert writes all its logs to the simplecert.log file inside the configured cache directory.

It will contain information about certificate status and renewal, as well as errors that occured.

Troubleshooting

  • If you get an error that looks like the following during obtaining a certificate, please check your firewall configuration, and ensure the ports for performing the challenge (HTTP: 80, TLS: 443, DNS: 53) are reachable from the outside world.
urn:ietf:params:acme:error:connection :: Timeout during connect (likely firewall problem), url: ...
  • Dependency errors

The LEGO package imports various api clients for providing the DNS challenges - unfortunately this leads to frequent incompatibilities, in code that is not under our control. In case this happens usually googling the error message is sufficient to find the go module replace directive that pins the needed version. Please open an issue if you could not fix a dependency error on your own.

  • Container Pitfalls

Be careful with containers that are configured to automatically restart on errors! When obtaining (or storing) a certificate fails for whatever reason, and your container will crash and restart automatically, you might get blocked due to the letsencrypt APIs rate limits.

Another common pitfall is to forget mounting the cache directory into your container, this way simplecert will obtain a new cert on every deployment, which will also likely cause rate limit issues after a while.

You can read more about the letsencrypt API rate limits here: https://letsencrypt.org/docs/rate-limits/

License

MIT

Documentation

Index

Constants

View Source
const (
	EC256   = "P256"
	EC384   = "P384"
	RSA2048 = "2048"
	RSA4096 = "4096"
	RSA8192 = "8192"
)

Variables

View Source
var Default = &Config{

	RenewBefore: 30 * 24,

	CheckInterval: 2 * 24 * time.Hour,
	SSLEmail:      "",
	DirectoryURL:  "https://acme-v02.api.letsencrypt.org/directory",
	HTTPAddress:   ":80",
	TLSAddress:    ":443",
	CacheDirPerm:  0700,
	Domains:       []string{},
	CacheDir:      "letsencrypt",
	DNSProvider:   "",
	Local:         false,
	UpdateHosts:   true,
	DNSServers:    []string{},
	KeyType:       RSA2048,
}

Default contains a default configuration

Functions

func CheckConfig

func CheckConfig(c *Config) error

CheckConfig checks if config can be used to obtain a cert

func ListenAndServeTLS

func ListenAndServeTLS(addr string, handler http.Handler, mail string, cleanup func(), domains ...string) error

ListenAndServeTLS is a util to use simplecert in production

func ListenAndServeTLSCustom

func ListenAndServeTLSCustom(addr string, handler http.Handler, cfg *Config, tlsconf *tls.Config, cleanup func(), domains ...string) error

ListenAndServeTLSCustom allows to specify the simplecert and TLS configuration and does not redirect the traffic arriving at port 80

func ListenAndServeTLSLocal

func ListenAndServeTLSLocal(addr string, handler http.Handler, cleanup func(), domains ...string) error

ListenAndServeTLSLocal is a util to use simplecert for local development

func Redirect

func Redirect(w http.ResponseWriter, req *http.Request)

Redirect a request to HTTPS and strips the www. subdomain

Types

type CR

type CR struct {
	Domain            string `json:"domain"`
	CertURL           string `json:"certUrl"`
	CertStableURL     string `json:"certStableUrl"`
	PrivateKey        []byte `json:"privateKey"`
	Certificate       []byte `json:"certificate"`
	IssuerCertificate []byte `json:"issuerCertificate"`
	CSR               []byte `json:"csr"`
}

CR represents an ACME Certificate Resource It can be persisted on the FileSystem with all fields which cannot be done with acme.CertificateResource

type CertReloader

type CertReloader struct {
	sync.RWMutex
	// contains filtered or unexported fields
}

CertReloader manages a hot reload of a new cert

func Init

func Init(cfg *Config, cleanup func()) (*CertReloader, error)

Init obtains a new LetsEncrypt cert for the specified domains if there is none in cacheDir or loads an existing one. Certs will be auto renewed in the configured interval. 1. Check if we have a cached certificate, if yes kickoff renewal routine and return 2. No Cached Certificate found - make sure the supplied cacheDir exists 3. Create a new SSLUser and ACME Client 4. Obtain a new certificate 5. Save To Disk 6. Kickoff Renewal Routine

func NewCertReloader

func NewCertReloader(certPath, keyPath string, logFile *os.File, cleanup func()) (*CertReloader, error)

NewCertReloader returns a new CertReloader instance the optional cleanup func will be called when a syscall.SIGINT, syscall.SIGABRT is received

func (*CertReloader) GetCertificateFunc

func (reloader *CertReloader) GetCertificateFunc() func(*tls.ClientHelloInfo) (*tls.Certificate, error)

GetCertificateFunc is needed for hot reload

func (*CertReloader) ReloadNow added in v1.7.6

func (reloader *CertReloader) ReloadNow()

ReloadNow will force reloading the cert from disk

type CertStatus added in v1.6.9

type CertStatus struct {
	Domains     []string
	RenewBefore int
	Expires     int
}

func Status added in v1.6.9

func Status() *CertStatus

Status can be used to check the validity status of the certificate as well as the configured renewal interval in case of errors, they will simply be logged, but should not disrupt the service the actual error message will never be passed to the caller and only appear in the simplecert logs therefore always check if you received a result != nil when calling Status()

type Config

type Config struct {

	// renew the certificate X hours before it expires
	// LetsEncrypt Certs are valid for 90 Days
	RenewBefore int

	// Interval for checking if cert is closer to expiration than RenewBefore
	CheckInterval time.Duration

	// SSLEmail for contact
	SSLEmail string

	// ACME Directory URL. Can be set to https://acme-staging-v02.api.letsencrypt.org/directory for testing
	DirectoryURL string

	// Endpoints for webroot challenge
	// CAUTION: challenge must be received on port 80 and 443
	// if you choose different ports here you must redirect the traffic
	HTTPAddress string
	TLSAddress  string

	// UNIX Permission for the CacheDir and all files inside
	CacheDirPerm os.FileMode

	// Domains for which to obtain the certificate
	Domains []string

	// DNSServers overrides the dns resolvers to use for a dns challenge, this is handy if you have a split dns.
	DNSServers []string

	// Path of the CacheDir
	CacheDir string

	// DNSProvider name for DNS challenges (optional)
	// see: https://godoc.org/github.com/go-acme/lego/providers/dns
	DNSProvider string

	// Local runmode
	Local bool

	// UpdateHosts adds the domains to /etc/hosts if running in local mode
	UpdateHosts bool

	// KeyType represents the key algorithm as well as the key size or curve to use.
	KeyType string

	// Handler funcs for graceful service shutdown and restoring
	WillRenewCertificate     func()
	DidRenewCertificate      func()
	FailedToRenewCertificate func(error)
}

Config allows configuration of simplecert

type KeyType added in v1.8.4

type KeyType string

type SSLUser

type SSLUser struct {
	Email        string
	Registration *registration.Resource
	Key          *rsa.PrivateKey
}

SSLUser implements the ACME User interface

func (SSLUser) GetEmail

func (u SSLUser) GetEmail() string

GetEmail returns the users email

func (SSLUser) GetPrivateKey

func (u SSLUser) GetPrivateKey() crypto.PrivateKey

GetPrivateKey returns the users private key

func (SSLUser) GetRegistration

func (u SSLUser) GetRegistration() *registration.Resource

GetRegistration returns the users registration resource

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

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