certmagic

package module
v0.0.0-...-f00a66c Latest Latest
Warning

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

Go to latest
Published: Dec 17, 2018 License: Apache-2.0 Imports: 39 Imported by: 0

README

CertMagic

Easy and Powerful TLS Automation

The same library used by the Caddy Web Server

Caddy's automagic TLS features, now for your own Go programs, in one powerful and easy-to-use library!

CertMagic is the most mature, robust, and capable ACME client integration for Go.

With CertMagic, you can add one line to your Go application to serve securely over TLS, without ever having to touch certificates.

Instead of:

// plaintext HTTP, gross 🤢
http.ListenAndServe(":80", mux)

Use CertMagic:

// encrypted HTTPS with HTTP->HTTPS redirects - yay! 🔒😍
certmagic.HTTPS([]string{"example.com"}, mux)

That line of code will serve your HTTP router mux over HTTPS, complete with HTTP->HTTPS redirects. It obtains and renews the TLS certificates. It staples OCSP responses for greater privacy and security. As long as your domain name points to your server, CertMagic will keep its connections secure.

Compared to other ACME client libraries for Go, only CertMagic supports the full suite of ACME features, and no other library matches CertMagic's maturity and reliability.

CertMagic - Automatic HTTPS using Let's Encrypt

Sponsored by Relica - Cross-platform local and cloud file backup:

Relica - Cross-platform file backup to the cloud, local disks, or other computers

Menu

Features

  • Fully automated certificate management including issuance and renewal
  • One-liner, fully managed HTTPS servers
  • Full control over almost every aspect of the system
  • HTTP->HTTPS redirects (for HTTP applications)
  • Solves all 3 ACME challenges: HTTP, TLS-ALPN, and DNS
  • Over 50 DNS providers work out-of-the-box (powered by lego!)
  • Pluggable storage implementations (default: file system)
  • Wildcard certificates (requires DNS challenge)
  • OCSP stapling for each qualifying certificate (done right)
  • Distributed solving of all challenges (works behind load balancers)
  • Supports "on-demand" issuance of certificates (during TLS handshakes!)
    • Custom decision functions
    • Hostname whitelist
    • Ask an external URL
    • Rate limiting
  • Optional event hooks to observe internal behaviors
  • Works with any certificate authority (CA) compliant with the ACME specification
  • Certificate revocation (please, only if private key is compromised)
  • Must-Staple (optional; not default)
  • Cross-platform support! Mac, Windows, Linux, BSD, Android...
  • Scales well to thousands of names/certificates per instance
  • Use in conjunction with your own certificates

Requirements

  1. Public DNS name(s) you control
  2. Server reachable from public Internet
    • Or use the DNS challenge to waive this requirement
  3. Control over port 80 (HTTP) and/or 443 (HTTPS)
    • Or they can be forwarded to other ports you control
    • Or use the DNS challenge to waive this requirement
    • (This is a requirement of the ACME protocol, not a library limitation)
  4. Persistent storage
    • Typically the local file system (default)
    • Other integrations available/possible

Before using this library, your domain names MUST be pointed (A/AAAA records) at your server (unless you use the DNS challenge)!

Installation

$ go get -u github.com/mholt/certmagic

Usage

Package Overview
Certificate authority

This library uses Let's Encrypt by default, but you can use any certificate authority that conforms to the ACME specification. Known/common CAs are provided as consts in the package, for example LetsEncryptStagingCA and LetsEncryptProductionCA.

The Config type

The certmagic.Config struct is how you can wield the power of this fully armed and operational battle station. However, an empty config is not a valid one! In time, you will learn to use the force of certmagic.New(certmagic.Config{...}) as I have.

Defaults

For every field in the Config struct, there is a corresponding package-level variable you can set as a default value. These defaults will be used when you call any of the high-level convenience functions like HTTPS() or Listen() or anywhere else a default Config is used. They are also used for any Config fields that are zero-valued when you call New().

You can set these values easily, for example: certmagic.Email = ... sets the email address to use for everything unless you explicitly override it in a Config.

Providing an email address

Although not strictly required, this is highly recommended best practice. It allows you to receive expiration emails if your certificates are expiring for some reason, and also allows the CA's engineers to potentially get in touch with you if something is wrong. I recommend setting certmagic.Email or always setting the Email field of the Config struct.

Development and Testing

Note that Let's Encrypt imposes strict rate limits at its production endpoint, so using it while developing your application may lock you out for a few days if you aren't careful!

While developing your application and testing it, use their staging endpoint which has much higher rate limits. Even then, don't hammer it: but it's much safer for when you're testing. When deploying, though, use their production CA because their staging CA doesn't issue trusted certificates.

To use staging, set certmagic.CA = certmagic.LetsEncryptStagingCA or set CA of every Config struct.

Examples

There are many ways to use this library. We'll start with the highest-level (simplest) and work down (more control).

First, we'll follow best practices and do the following:

// read and agree to your CA's legal documents
certmagic.Agreed = true

// provide an email address
certmagic.Email = "you@yours.com"

// use the staging endpoint while we're developing
certmagic.CA = certmagic.LetsEncryptStagingCA
Serving HTTP handlers with HTTPS
err := certmagic.HTTPS([]string{"example.com", "www.example.com"}, mux)
if err != nil {
	return err
}

This starts HTTP and HTTPS listeners and redirects HTTP to HTTPS!

Starting a TLS listener
ln, err := certmagic.Listen([]string{"example.com"})
if err != nil {
	return err
}
Getting a tls.Config
tlsConfig, err := certmagic.TLS([]string{"example.com"})
if err != nil {
	return err
}
Advanced use

For more control, you'll make and use a Config like so:

magic := certmagic.New(certmagic.Config{
	CA:     certmagic.LetsEncryptStagingCA,
	Email:  "you@yours.com",
	Agreed: true,
	// plus any other customization you want
})

// this obtains certificates or renews them if necessary
err := magic.Manage([]string{"example.com", "sub.example.com"})
if err != nil {
	return err
}

// to use its certificates and solve the TLS-ALPN challenge,
// you can get a TLS config to use in a TLS listener!
tlsConfig := magic.TLSConfig()

// if you already have a TLS config you don't want to replace,
// we can simply set its GetCertificate field and append the
// TLS-ALPN challenge protocol to the NextProtos
myTLSConfig.GetCertificate = magic.GetCertificate
myTLSConfig.NextProtos = append(myTLSConfig.NextProtos, tlsalpn01.ACMETLS1Protocol}

// the HTTP challenge has to be handled by your HTTP server;
// if you don't have one, you should have disabled it earlier
// when you made the certmagic.Config
httpMux = magic.HTTPChallengeHandler(httpMux)

Great! This example grants you much more flexibility for advanced programs. However, the vast majority of you will only use the high-level functions described earlier, especially since you can still customize them by setting the package-level defaults.

If you want to use the default configuration but you still need a certmagic.Config, you can call certmagic.Manage() directly to get one:

magic, err := certmagic.Manage([]string{"example.com"})
if err != nil {
	return err
}

And then it's the same as above, as if you had made the Config yourself.

Wildcard certificates

At time of writing (December 2018), Let's Encrypt only issues wildcard certificates with the DNS challenge.

Behind a load balancer (or in a cluster)

CertMagic runs effectively behind load balancers and/or in cluster/fleet environments. In other words, you can have 10 or 1,000 servers all serving the same domain names, all sharing certificates and OCSP staples.

To do so, simply ensure that each instance is using the same Storage. That is the sole criteria for determining whether an instance is part of a cluster.

The default Storage is implemented using the file system, so mounting the same shared folder is sufficient (see Storage for more on that)! If you need an alternate Storage implementation, feel free to use one, provided that all the instances use the same one. :)

See Storage and the associated godoc for more information!

The ACME Challenges

This section describes how to solve the ACME challenges. Challenges are how you demonstrate to the certificate authority some control over your domain name, thus authorizing them to grant you a certificate for that name. The great innovation of ACME is that verification by CAs can now be automated, rather than having to click links in emails (who ever thought that was a good idea??).

If you're using the high-level convenience functions like HTTPS(), Listen(), or TLS(), the HTTP and/or TLS-ALPN challenges are solved for you because they also start listeners. However, if you're making a Config and you start your own server manually, you'll need to be sure the ACME challenges can be solved so certificates can be renewed.

The HTTP and TLS-ALPN challenges are the defaults because they don't require configuration from you, but they require that your server is accessible from external IPs on low ports. If that is not possible in your situation, you can enable the DNS challenge, which will disable the HTTP and TLS-ALPN challenges and use the DNS challenge exclusively.

Technically, only one challenge needs to be enabled for things to work, but using multiple is good for reliability in case a challenge is discontinued by the CA. This happened to the TLS-SNI challenge in early 2018—many popular ACME clients such as Traefik and Autocert broke, resulting in downtime for some sites, until new releases were made and patches deployed, because they used only one challenge; Caddy, however—this library's forerunner—was unaffected because it also used the HTTP challenge. If multiple challenges are enabled, they are chosen randomly to help prevent false reliance on a single challenge type.

HTTP Challenge

Per the ACME spec, the HTTP challenge requires port 80, or at least packet forwarding from port 80. It works by serving a specific HTTP response that only the genuine server would have to a normal HTTP request at a special endpoint.

If you are running an HTTP server, solving this challenge is very easy: just wrap your handler in HTTPChallengeHandler or call SolveHTTPChallenge() inside your own ServeHTTP() method.

For example, if you're using the standard library:

mux := http.NewServeMux()
mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
	fmt.Fprintf(w, "Lookit my cool website over HTTPS!")
})

http.ListenAndServe(":80", magic.HTTPChallengeHandler(mux))

If wrapping your handler is not a good solution, try this inside your ServeHTTP() instead:

magic := certmagic.NewDefault()

func ServeHTTP(w http.ResponseWriter, req *http.Request) {
	if magic.HandleHTTPChallenge(w, r) {
		return // challenge handled; nothing else to do
	}
	...
}

If you are not running an HTTP server, you should disable the HTTP challenge or run an HTTP server whose sole job it is to solve the HTTP challenge.

TLS-ALPN Challenge

Per the ACME spec, the TLS-ALPN challenge requires port 443, or at least packet forwarding from port 443. It works by providing a special certificate using a standard TLS extension, Application Layer Protocol Negotiation (ALPN), having a special value. This is the most convenient challenge type because it usually requires no extra configuration and uses the standard TLS port which is where the certificates are used, also.

This challenge is easy to solve: just use the provided tls.Config when you make your TLS listener:

// use this to configure a TLS listener
tlsConfig := magic.TLSConfig()

Or make two simple changes to an existing tls.Config:

myTLSConfig.GetCertificate = magic.GetCertificate
myTLSConfig.NextProtos = append(myTLSConfig.NextProtos, tlsalpn01.ACMETLS1Protocol}

Then just make sure your TLS listener is listening on port 443:

ln, err := tls.Listen("tcp", ":443", myTLSConfig)
DNS Challenge

The DNS challenge is perhaps the most useful challenge because it allows you to obtain certificates without your server needing to be publicly accessible on the Internet, and it's the only challenge by which Let's Encrypt will issue wildcard certificates.

This challenge works by setting a special record in the domain's zone. To do this automatically, your DNS provider needs to offer an API by which changes can be made to domain names, and the changes need to take effect immediately for best results. CertMagic supports all of lego's DNS provider implementations! All of them clean up the temporary record after the challenge completes.

To enable it, just set the DNSProvider field on a certmagic.Config struct, or set the default certmagic.DNSProvider variable. For example, if my domains' DNS was served by DNSimple (they're great, by the way) and I set my DNSimple API credentials in environment variables:

import "github.com/xenolf/lego/providers/dns/dnsimple"

provider, err := dnsimple.NewProvider()
if err != nil {
	return err
}

certmagic.DNSProvider = provider

Now the DNS challenge will be used by default, and I can obtain certificates for wildcard domains. See the godoc documentation for the provider you're using to learn how to configure it. Most can be configured by env variables or by passing in a config struct. If you pass a config struct instead of using env variables, you will probably need to set some other defaults (that's just how lego works, currently):

PropagationTimeout: dns01.DefaultPollingInterval,
PollingInterval:    dns01.DefaultPollingInterval,
TTL:                dns01.DefaultTTL,

Enabling the DNS challenge disables the other challenges for that certmagic.Config instance.

On-Demand TLS

Normally, certificates are obtained and renewed before a listener starts serving, and then those certificates are maintained throughout the lifetime of the program. In other words, the certificate names are static. But sometimes you don't know all the names ahead of time. This is where On-Demand TLS shines.

Originally invented for use in Caddy (which was the first program to use such technology), On-Demand TLS makes it possible and easy to serve certificates for arbitrary names during the lifetime of the server. When a TLS handshake is received, CertMagic will read the Server Name Indication (SNI) value and either load and present that certificate in the ServerHello, or if one does not exist, it will obtain it from a CA right then-and-there.

Of course, this has some obvious security implications. You don't want to DoS a CA or allow arbitrary clients to fill your storage with spammy TLS handshakes. That's why, in order to enable On-Demand issuance, you'll need to set some limits or some policy to allow getting a certificate.

CertMagic provides several ways to enforce decision policies for On-Demand TLS, in descending order of priority:

  • A generic function that you write which will decide whether to allow the certificate request
  • A name whitelist
  • The ability to make an HTTP request to a URL for permission
  • Rate limiting

The simplest way to enable On-Demand issuance is to set the OnDemand field of a Config (or the default package-level value):

certmagic.OnDemand = &certmagic.OnDemandConfig{MaxObtain: 5}

This allows only 5 certificates to be requested and is the simplest way to enable On-Demand TLS, but is the least recommended. It prevents abuse, but only in the least helpful way.

The godoc describes how to use the other policies, all of which are much more recommended! :)

If OnDemand is set and Manage() is called, then the names given to Manage() will be whitelisted rather than obtained right away.

Storage

CertMagic relies on storage to store certificates and other TLS assets (OCSP staple cache, coordinating locks, etc). Persistent storage is a requirement when using CertMagic: ephemeral storage will likely lead to rate limiting on the CA-side as CertMagic will always have to get new certificates.

By default, CertMagic stores assets on the local file system in $HOME/.local/share/certmagic (and honors $XDG_DATA_HOME if set). CertMagic will create the directory if it does not exist. If writes are denied, things will not be happy, so make sure CertMagic can write to it!

The notion of a "cluster" or "fleet" of instances that may be serving the same site and sharing certificates, etc, is tied to storage. Simply, any instances that use the same storage facilities are considered part of the cluster. So if you deploy 100 instances of CertMagic behind a load balancer, they are all part of the same cluster if they share the same storage configuration. Sharing storage could be mounting a shared folder, or implementing some other distributed storage system such as a database server or KV store.

The easiest way to change the storage being used is to set certmagic.DefaultStorage to a value that satisfies the Storage interface. Keep in mind that a valid Storage must be able to implement some operations atomically in order to provide locking and synchronization.

If you write a Storage implementation, let us know and we'll add it to the project so people can find it!

Cache

All of the certificates in use are de-duplicated and cached in memory for optimal performance at handshake-time. This cache must be backed by persistent storage as described above.

Most applications will not need to interact with certificate caches directly. Usually, the closest you will come is to set the package-wide certmagic.DefaultStorage variable (before attempting to create any Configs). However, if your use case requires using different storage facilities for different Configs (that's highly unlikely and NOT recommended! Even Caddy doesn't get that crazy), you will need to call certmagic.NewCache() and pass in the storage you want to use, then get new Config structs with certmagic.NewWithCache() and pass in the cache.

Again, if you're needing to do this, you've probably over-complicated your application design.

FAQ

Can I use some of my own certificates while using CertMagic?

Yes, just call the relevant method on the Config to add your own certificate to the cache:

Keep in mind that unmanaged certificates are (obviously) not renewed for you, so you'll have to replace them when you do. However, OCSP stapling is performed even for unmanaged certificates that qualify.

Does CertMagic obtain SAN certificates?

Technically all certificates these days are SAN certificates because CommonName is deprecated. But if you're asking whether CertMagic issues and manages certificates with multiple SANs, the answer is no. But it does support serving them, if you provide your own.

How can I listen on ports 80 and 443? Do I have to run as root?

On Linux, you can use setcap to grant your binary the permission to bind low ports:

$ sudo setcap cap_net_bind_service=+ep /path/to/your/binary

and then you will not need to run with root privileges.

Contributing

We welcome your contributions! Please see our contributing guidelines for instructions.

Project History

CertMagic is the core of Caddy's advanced TLS automation code, extracted into a library. The underlying ACME client implementation is lego, which was originally developed for use in Caddy even before Let's Encrypt entered public beta in 2015.

In the years since then, Caddy's TLS automation techniques have been widely adopted, tried and tested in production, and served millions of sites and secured trillions of connections.

Now, CertMagic is the actual library used by Caddy. It's incredibly powerful and feature-rich, but also easy to use for simple Go programs: one line of code can enable fully-automated HTTPS applications with HTTP->HTTPS redirects.

Caddy is known for its robust HTTPS+ACME features. When ACME certificate authorities have had outages, in some cases Caddy was the only major client that didn't experience any downtime. Caddy can weather OCSP outages lasting days, or CA outages lasting weeks, without taking your sites offline.

Caddy was also the first to sport "on-demand" issuance technology, which obtains certificates during the first TLS handshake for an allowed SNI name.

Consequently, CertMagic brings all these (and more) features and capabilities right into your own Go programs.

You can watch a 2016 dotGo talk by the author of this library about using ACME to automate certificate management in Go programs:

Matthew Holt speaking at dotGo 2016 about ACME in Go

Credits and License

CertMagic is a project by Matthew Holt, who is the author; and various contributors, who are credited in the commit history of either CertMagic or Caddy.

CertMagic is licensed under Apache 2.0, an open source license. For convenience, its main points are summarized as follows (but this is no replacement for the actual license text):

  • The author owns the copyright to this code
  • Use, distribute, and modify the software freely
  • Private and internal use is allowed
  • License text and copyright notices must stay intact and be included with distributions
  • Any and all changes to the code must be documented

Documentation

Overview

Package certmagic automates the obtaining and renewal of TLS certificates, including TLS & HTTPS best practices such as robust OCSP stapling, caching, HTTP->HTTPS redirects, and more.

Its high-level API serves your HTTP handlers over HTTPS if you simply give the domain name(s) and the http.Handler; CertMagic will create and run the HTTPS server for you, fully managing certificates during the lifetime of the server. Similarly, it can be used to start TLS listeners or return a ready-to-use tls.Config -- whatever layer you need TLS for, CertMagic makes it easy. See the HTTPS, Listen, and TLS functions for that.

If you need more control, create a Config using New() and then call Manage() on the config; but you'll have to be sure to solve the HTTP and TLS-ALPN challenges yourself (unless you disabled them or use the DNS challenge) by using the provided Config.GetCertificate function in your tls.Config and/or Config.HTTPChallangeHandler in your HTTP handler.

See the package's README for more instruction.

Index

Examples

Constants

View Source
const (
	// HTTPChallengePort is the officially-designated port for
	// the HTTP challenge according to the ACME spec.
	HTTPChallengePort = 80

	// TLSALPNChallengePort is the officially-designated port for
	// the TLS-ALPN challenge according to the ACME spec.
	TLSALPNChallengePort = 443
)
View Source
const (
	LetsEncryptStagingCA    = "https://acme-staging-v02.api.letsencrypt.org/directory"
	LetsEncryptProductionCA = "https://acme-v02.api.letsencrypt.org/directory"
)

Some well-known CA endpoints available to use.

View Source
const (
	// DefaultRenewInterval is how often to check certificates for renewal.
	DefaultRenewInterval = 12 * time.Hour

	// DefaultRenewDurationBefore is how long before expiration to renew certificates.
	DefaultRenewDurationBefore = (24 * time.Hour) * 30

	// DefaultRenewDurationBeforeAtStartup is how long before expiration to require
	// a renewed certificate when the process is first starting up (see mholt/caddy#1680).
	DefaultRenewDurationBeforeAtStartup = (24 * time.Hour) * 7

	// DefaultOCSPInterval is how often to check if OCSP stapling needs updating.
	DefaultOCSPInterval = 1 * time.Hour
)

Variables

View Source
var (
	// The endpoint of the directory for the ACME
	// CA we are to use
	CA = LetsEncryptProductionCA

	// The email address to use when creating or
	// selecting an existing ACME server account
	Email string

	// The synchronization implementation - all
	// instances of certmagic in a cluster must
	// use the same value here, otherwise some
	// cert operations will not be properly
	// coordinated
	Sync Locker

	// Set to true if agreed to the CA's
	// subscriber agreement
	Agreed bool

	// Disable all HTTP challenges
	DisableHTTPChallenge bool

	// Disable all TLS-ALPN challenges
	DisableTLSALPNChallenge bool

	// How long before expiration to renew certificates
	RenewDurationBefore = DefaultRenewDurationBefore

	// How long before expiration to require a renewed
	// certificate when in interactive mode, like when
	// the program is first starting up (see
	// mholt/caddy#1680). A wider window between
	// RenewDurationBefore and this value will suppress
	// errors under duress (bad) but hopefully this duration
	// will give it enough time for the blockage to be
	// relieved.
	RenewDurationBeforeAtStartup = DefaultRenewDurationBeforeAtStartup

	// An optional event callback clients can set
	// to subscribe to certain things happening
	// internally by this config; invocations are
	// synchronous, so make them return quickly!
	OnEvent func(event string, data interface{})

	// The host (ONLY the host, not port) to listen
	// on if necessary to start a listener to solve
	// an ACME challenge
	ListenHost string

	// The alternate port to use for the ACME HTTP
	// challenge; if non-empty,  this port will be
	// used instead of HTTPChallengePort to spin up
	// a listener for the HTTP challenge
	AltHTTPPort int

	// The alternate port to use for the ACME
	// TLS-ALPN challenge; the system must forward
	// TLSALPNChallengePort to this port for
	// challenge to succeed
	AltTLSALPNPort int

	// The DNS provider to use when solving the
	// ACME DNS challenge
	DNSProvider challenge.Provider

	// The type of key to use when generating
	// certificates
	KeyType = certcrypto.RSA2048

	// The state needed to operate on-demand TLS
	OnDemand *OnDemandConfig

	// Add the must staple TLS extension to the
	// CSR generated by lego/acme
	MustStaple bool
)

Package defaults

View Source
var (
	// HTTPPort is the port on which to serve HTTP
	// and, by extension, the HTTP challenge (unless
	// AltHTTPPort is set).
	HTTPPort = 80

	// HTTPSPort is the port on which to serve HTTPS
	// and, by extension, the TLS-ALPN challenge
	// (unless AltTLSALPNPort is set).
	HTTPSPort = 443
)

Port variables must remain their defaults unless you forward packets from the defaults to whatever these are set to; otherwise ACME challenges will fail.

View Source
var (
	UserAgent   string
	HTTPTimeout = 30 * time.Second
)

Some default values passed down to the underlying lego client.

Functions

func HTTPS

func HTTPS(domainNames []string, mux http.Handler) error

HTTPS serves mux for all domainNames using the HTTP and HTTPS ports, redirecting all HTTP requests to HTTPS.

This high-level convenience function is opinionated and applies sane defaults for production use, including timeouts for HTTP requests and responses. To allow very long-lived requests or connections, you should make your own http.Server values and use this package's Listen(), TLS(), or Config.TLSConfig() functions to customize to your needs. For example, servers which need to support large uploads or downloads with slow clients may need to use longer timeouts, thus this function is not suitable.

Calling this function signifies your acceptance to the CA's Subscriber Agreement and/or Terms of Service.

Example

This is the simplest way for HTTP servers to use this package. Call HTTPS() with your domain names and your handler (or nil for the http.DefaultMux), and CertMagic will do the rest.

http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
	fmt.Fprintf(w, "Hello, HTTPS visitor!")
})

err := HTTPS([]string{"example.com", "www.example.com"}, nil)
if err != nil {
	log.Fatal(err)
}
Output:

func HostQualifies

func HostQualifies(hostname string) bool

HostQualifies returns true if the hostname alone appears eligible for automagic TLS. For example: localhost, empty hostname, and IP addresses are not eligible because we cannot obtain certificates for those names. Wildcard names are allowed, as long as they conform to CABF requirements (only one wildcard label, and it must be the left-most label).

func Listen

func Listen(domainNames []string) (net.Listener, error)

Listen manages certificates for domainName and returns a TLS listener.

Because this convenience function returns only a TLS-enabled listener and does not presume HTTP is also being served, the HTTP challenge will be disabled.

Calling this function signifies your acceptance to the CA's Subscriber Agreement and/or Terms of Service.

func TLS

func TLS(domainNames []string) (*tls.Config, error)

TLS enables management of certificates for domainNames and returns a valid tls.Config.

Because this is a convenience function that returns only a tls.Config, it does not assume HTTP is being served on the HTTP port, so the HTTP challenge is disabled (no HTTPChallengeHandler is necessary).

Calling this function signifies your acceptance to the CA's Subscriber Agreement and/or Terms of Service.

Types

type Cache

type Cache struct {
	// How often to check certificates for renewal
	RenewInterval time.Duration

	// How often to check if OCSP stapling needs updating
	OCSPInterval time.Duration
	// contains filtered or unexported fields
}

Cache is a structure that stores certificates in memory. Generally, there should only be one per process. However, complex applications that virtualize the concept of a "process" (such as Caddy, which virtualizes processes as "instances" so it can do graceful, in-memory reloads of its configuration) may use more of these per OS process.

Using just one cache per process avoids duplication of certificates across multiple configurations and makes maintenance easier.

An empty cache is INVALID and must not be used. Be sure to call NewCertificateCache to get one.

These should be very long-lived values, and must not be copied. Before all references leave scope to be garbage collected, ensure you call Stop() to stop maintenance maintenance on the certificates stored in this cache.

func NewCache

func NewCache(storage Storage) *Cache

NewCache returns a new, valid Cache backed by the given storage implementation. It also begins a maintenance goroutine for any managed certificates stored in this cache.

See the godoc for Cache to use it properly.

Note that all processes running in a cluster configuration must use the same storage value in order to share certificates. (A single storage value may be shared by multiple clusters as well.)

func (*Cache) RenewManagedCertificates

func (certCache *Cache) RenewManagedCertificates(interactive bool) error

RenewManagedCertificates renews managed certificates, including ones loaded on-demand. Note that this is done automatically on a regular basis; normally you will not need to call this.

func (*Cache) Stop

func (certCache *Cache) Stop()

Stop stops the maintenance goroutine for certificates in certCache.

type Certificate

type Certificate struct {
	tls.Certificate

	// Names is the list of names this certificate is written for.
	// The first is the CommonName (if any), the rest are SAN.
	Names []string

	// NotAfter is when the certificate expires.
	NotAfter time.Time

	// OCSP contains the certificate's parsed OCSP response.
	OCSP *ocsp.Response

	// The hex-encoded hash of this cert's chain's bytes.
	Hash string
	// contains filtered or unexported fields
}

Certificate is a tls.Certificate with associated metadata tacked on. Even if the metadata can be obtained by parsing the certificate, we are more efficient by extracting the metadata onto this struct.

func (Certificate) NeedsRenewal

func (c Certificate) NeedsRenewal() bool

NeedsRenewal returns true if the certificate is expiring soon or has expired.

type Config

type Config struct {
	// The endpoint of the directory for the ACME
	// CA we are to use
	CA string

	// The email address to use when creating or
	// selecting an existing ACME server account
	Email string

	// Set to true if agreed to the CA's
	// subscriber agreement
	Agreed bool

	// Disable all HTTP challenges
	DisableHTTPChallenge bool

	// Disable all TLS-ALPN challenges
	DisableTLSALPNChallenge bool

	// How long before expiration to renew certificates
	RenewDurationBefore time.Duration

	// How long before expiration to require a renewed
	// certificate when in interactive mode, like when
	// the program is first starting up (see
	// mholt/caddy#1680). A wider window between
	// RenewDurationBefore and this value will suppress
	// errors under duress (bad) but hopefully this duration
	// will give it enough time for the blockage to be
	// relieved.
	RenewDurationBeforeAtStartup time.Duration

	// An optional event callback clients can set
	// to subscribe to certain things happening
	// internally by this config; invocations are
	// synchronous, so make them return quickly!
	OnEvent func(event string, data interface{})

	// The host (ONLY the host, not port) to listen
	// on if necessary to start a listener to solve
	// an ACME challenge
	ListenHost string

	// The alternate port to use for the ACME HTTP
	// challenge; if non-empty,  this port will be
	// used instead of HTTPChallengePort to spin up
	// a listener for the HTTP challenge
	AltHTTPPort int

	// The alternate port to use for the ACME
	// TLS-ALPN challenge; the system must forward
	// TLSALPNChallengePort to this port for
	// challenge to succeed
	AltTLSALPNPort int

	// The DNS provider to use when solving the
	// ACME DNS challenge
	DNSProvider challenge.Provider

	// The type of key to use when generating
	// certificates
	KeyType certcrypto.KeyType

	// The state needed to operate on-demand TLS
	OnDemand *OnDemandConfig

	// Add the must staple TLS extension to the
	// CSR generated by lego/acme
	MustStaple bool
	// contains filtered or unexported fields
}

Config configures a certificate manager instance. An empty Config is not valid: use New() to obtain a valid Config.

func Manage

func Manage(domainNames []string) (cfg *Config, err error)

Manage obtains certificates for domainNames and keeps them renewed using the returned Config.

You will need to ensure that you use a TLS config that gets certificates from this Config and that the HTTP and TLS-ALPN challenges can be solved. The easiest way to do this is to use cfg.TLSConfig() as your TLS config and to wrap your HTTP handler with cfg.HTTPChallengeHandler(). If you don't have an HTTP server, you will need to disable the HTTP challenge.

If you already have a TLS config you want to use, you can simply set its GetCertificate field to cfg.GetCertificate.

Calling this function signifies your acceptance to the CA's Subscriber Agreement and/or Terms of Service.

func New

func New(cfg Config) *Config

New makes a valid config based on cfg and uses a default certificate cache. All calls to New() will use the same certificate cache.

func NewDefault

func NewDefault() *Config

NewDefault returns a new, valid, default config.

Calling this function signifies your acceptance to the CA's Subscriber Agreement and/or Terms of Service.

func NewWithCache

func NewWithCache(certCache *Cache, cfg Config) *Config

NewWithCache makes a valid new config based on cfg and uses the provided certificate cache. If certCache is nil, a new, default one will be created using DefaultStorage; or, if a default cache has already been created, it will be reused.

func (*Config) CacheManagedCertificate

func (cfg *Config) CacheManagedCertificate(domain string) (Certificate, error)

CacheManagedCertificate loads the certificate for domain into the cache, from the TLS storage for managed certificates. It returns a copy of the Certificate that was put into the cache.

This is a lower-level method; normally you'll call Manage() instead.

This method is safe for concurrent use.

func (*Config) CacheUnmanagedCertificatePEMBytes

func (cfg *Config) CacheUnmanagedCertificatePEMBytes(certBytes, keyBytes []byte) error

CacheUnmanagedCertificatePEMBytes makes a certificate out of the PEM bytes of the certificate and key, then caches it in memory.

This method is safe for concurrent use.

func (*Config) CacheUnmanagedCertificatePEMFile

func (cfg *Config) CacheUnmanagedCertificatePEMFile(certFile, keyFile string) error

CacheUnmanagedCertificatePEMFile loads a certificate for host using certFile and keyFile, which must be in PEM format. It stores the certificate in the in-memory cache.

This method is safe for concurrent use.

func (*Config) CacheUnmanagedTLSCertificate

func (cfg *Config) CacheUnmanagedTLSCertificate(tlsCert tls.Certificate) error

CacheUnmanagedTLSCertificate adds tlsCert to the certificate cache. It staples OCSP if possible.

This method is safe for concurrent use.

func (*Config) GetCertificate

func (cfg *Config) GetCertificate(clientHello *tls.ClientHelloInfo) (*tls.Certificate, error)

GetCertificate gets a certificate to satisfy clientHello. In getting the certificate, it abides the rules and settings defined in the Config that matches clientHello.ServerName. It first checks the in- memory cache, then, if the config enables "OnDemand", it accesses disk, then accesses the network if it must obtain a new certificate via ACME.

This method is safe for use as a tls.Config.GetCertificate callback.

func (*Config) HTTPChallengeHandler

func (cfg *Config) HTTPChallengeHandler(h http.Handler) http.Handler

HTTPChallengeHandler wraps h in a handler that can solve the ACME HTTP challenge. cfg is required, and it must have a certificate cache backed by a functional storage facility, since that is where the challenge state is stored between initiation and solution.

If a request is not an ACME HTTP challenge, h willl be invoked.

func (*Config) HandleHTTPChallenge

func (cfg *Config) HandleHTTPChallenge(w http.ResponseWriter, r *http.Request) bool

HandleHTTPChallenge uses cfg to solve challenge requests from an ACME server that were initiated by this instance or any other instance in this cluster (being, any instances using the same storage cfg does).

If the HTTP challenge is disabled, this function is a no-op.

If cfg is nil or if cfg does not have a certificate cache backed by usable storage, solving the HTTP challenge will fail.

It returns true if it handled the request; if so, the response has already been written. If false is returned, this call was a no-op and the request has not been handled.

func (*Config) Manage

func (cfg *Config) Manage(domainNames []string) error

Manage causes the certificates for domainNames to be managed according to cfg. If cfg is enabled for OnDemand, then this simply whitelists the domain names. Otherwise, the certificate(s) for each name are loaded from storage or obtained from the CA; and if loaded from storage, renewed if they are expiring or expired. It then caches the certificate in memory and is prepared to serve them up during TLS handshakes.

func (*Config) ObtainCert

func (cfg *Config) ObtainCert(name string, interactive bool) error

ObtainCert obtains a certificate for name using cfg, as long as a certificate does not already exist in storage for that name. The name must qualify and cfg must be flagged as Managed. This function is a no-op if storage already has a certificate for name.

It only obtains and stores certificates (and their keys), it does not load them into memory. If interactive is true, the user may be shown a prompt.

func (*Config) RenewCert

func (cfg *Config) RenewCert(name string, interactive bool) error

RenewCert renews the certificate for name using cfg. It stows the renewed certificate and its assets in storage if successful.

func (*Config) RevokeCert

func (cfg *Config) RevokeCert(domain string, interactive bool) error

RevokeCert revokes the certificate for domain via ACME protocol.

func (*Config) TLSConfig

func (cfg *Config) TLSConfig() *tls.Config

TLSConfig is an opinionated method that returns a recommended, modern TLS configuration that can be used to configure TLS listeners, which also supports the TLS-ALPN challenge and serves up certificates managed by cfg.

Unlike the package TLS() function, this method does not, by itself, enable certificate management for any domain names.

Feel free to further customize the returned tls.Config, but do not mess with the GetCertificate or NextProtos fields unless you know what you're doing, as they're necessary to solve the TLS-ALPN challenge.

type ErrNotExist

type ErrNotExist interface {
	error
}

ErrNotExist is returned by Storage implementations when a resource is not found. It is similar to os.IsNotExist except this is a type, not a variable.

type FileStorage

type FileStorage struct {
	Path string
}

FileStorage facilitates forming file paths derived from a root directory. It is used to get file paths in a consistent, cross-platform way or persisting ACME assets on the file system.

func (FileStorage) Delete

func (fs FileStorage) Delete(key string) error

Delete deletes the value at key. TODO: Delete any empty folders caused by this operation

func (FileStorage) Exists

func (fs FileStorage) Exists(key string) bool

Exists returns true if key exists in fs.

func (FileStorage) Filename

func (fs FileStorage) Filename(key string) string

Filename returns the key as a path on the file system prefixed by fs.Path.

func (FileStorage) List

func (fs FileStorage) List(prefix string, recursive bool) ([]string, error)

List returns all keys that match prefix.

func (FileStorage) Load

func (fs FileStorage) Load(key string) ([]byte, error)

Load retrieves the value at key.

func (FileStorage) Stat

func (fs FileStorage) Stat(key string) (KeyInfo, error)

Stat returns information about key.

func (FileStorage) Store

func (fs FileStorage) Store(key string, value []byte) error

Store saves value at key.

func (FileStorage) String

func (fs FileStorage) String() string

func (FileStorage) TryLock

func (fs FileStorage) TryLock(key string) (Waiter, error)

TryLock attempts to get a lock for name, otherwise it returns a Waiter value to wait until the other process is finished.

func (FileStorage) Unlock

func (fs FileStorage) Unlock(key string) error

Unlock releases the lock for name.

func (FileStorage) UnlockAllObtained

func (fs FileStorage) UnlockAllObtained()

UnlockAllObtained removes all locks obtained by this instance of fs.

type KeyBuilder

type KeyBuilder struct{}

KeyBuilder provides a namespace for methods that build keys and key prefixes, for addressing items in a Storage implementation.

var StorageKeys KeyBuilder

StorageKeys provides methods for accessing keys and key prefixes for items in a Storage. Typically, you will not need to use this because accessing storage is abstracted away for most cases. Only use this if you need to directly access TLS assets in your application.

func (KeyBuilder) CAPrefix

func (keys KeyBuilder) CAPrefix(ca string) string

CAPrefix returns the storage key prefix for the given certificate authority URL.

func (KeyBuilder) OCSPStaple

func (keys KeyBuilder) OCSPStaple(cert *Certificate, pemBundle []byte) string

OCSPStaple returns a key for the OCSP staple associated with the given certificate. If you have the PEM bundle handy, pass that in to save an extra encoding step.

func (KeyBuilder) SiteCert

func (keys KeyBuilder) SiteCert(ca, domain string) string

SiteCert returns the path to the certificate file for domain.

func (KeyBuilder) SiteMeta

func (keys KeyBuilder) SiteMeta(ca, domain string) string

SiteMeta returns the path to the domain's asset metadata file.

func (KeyBuilder) SitePrefix

func (keys KeyBuilder) SitePrefix(ca, domain string) string

SitePrefix returns a key prefix for items associated with the site using the given CA URL.

func (KeyBuilder) SitePrivateKey

func (keys KeyBuilder) SitePrivateKey(ca, domain string) string

SitePrivateKey returns the path to domain's private key file.

func (KeyBuilder) UserPrefix

func (keys KeyBuilder) UserPrefix(ca, email string) string

UserPrefix returns a key prefix for items related to the user with the given email for the given CA URL.

func (KeyBuilder) UserPrivateKey

func (keys KeyBuilder) UserPrivateKey(ca, email string) string

UserPrivateKey gets the path to the private key file for the user with the given email address on the given CA URL.

func (KeyBuilder) UserReg

func (keys KeyBuilder) UserReg(ca, email string) string

UserReg gets the path to the registration file for the user with the given email address for the given CA URL.

func (KeyBuilder) UsersPrefix

func (keys KeyBuilder) UsersPrefix(ca string) string

UsersPrefix returns a key prefix for items related to users associated with the given CA URL.

type KeyInfo

type KeyInfo struct {
	Key        string
	Modified   time.Time
	Size       int64
	IsTerminal bool // false for keys that only contain other keys (like directories)
}

KeyInfo holds information about a key in storage.

type Locker

type Locker interface {
	// TryLock will attempt to acquire the lock for key. If a
	// lock could be obtained, nil values are returned as no
	// waiting is required. If not (meaning another process is
	// already working on key), a Waiter value will be returned,
	// upon which you should Wait() until it is finished.
	//
	// The actual implementation of obtaining of a lock must be
	// an atomic operation so that multiple TryLock calls at the
	// same time always results in only one caller receiving the
	// lock. TryLock always returns without waiting.
	//
	// To prevent deadlocks, all implementations (where this concern
	// is relevant) should put a reasonable expiration on the lock in
	// case Unlock is unable to be called due to some sort of network
	// or system failure or crash.
	TryLock(key string) (Waiter, error)

	// Unlock releases the lock for key. This method must ONLY be
	// called after a successful call to TryLock where no Waiter was
	// returned, and only after the operation requiring the lock is
	// finished, even if it errored or timed out. It is INCORRECT to
	// call Unlock if any non-nil value was returned from a call to
	// TryLock or if Unlock was not called at all. Unlock should also
	// clean up any unused resources allocated during TryLock.
	Unlock(key string) error

	// UnlockAllObtained removes all locks obtained by this process,
	// upon which others may be waiting. The importer should call
	// this on shutdowns (and crashes, ideally) to avoid leaving stale
	// locks, but Locker implementations must NOT rely on this being
	// the case and should anticipate and handle stale locks. Errors
	// should be printed or logged, since there could be multiple,
	// with no good way to handle them anyway.
	UnlockAllObtained()
}

Locker facilitates synchronization of certificate tasks across machines and networks.

type OnDemandConfig

type OnDemandConfig struct {
	// If set, this function will be the absolute
	// authority on whether the hostname (according
	// to SNI) is allowed to try to get a cert.
	DecisionFunc func(name string) error

	// If no DecisionFunc is set, this whitelist
	// is the absolute authority as to whether
	// a certificate should be allowed to be tried.
	// Names are compared against SNI value.
	HostWhitelist []string

	// If no DecisionFunc or HostWhitelist are set,
	// then an HTTP request will be made to AskURL
	// to determine if a certificate should be
	// obtained. If the request fails or the response
	// is anything other than 2xx status code, the
	// issuance will be denied.
	AskURL *url.URL

	// If no DecisionFunc, HostWhitelist, or AskURL
	// are set, then only this many certificates may
	// be obtained on-demand; this field is required
	// if all others are empty, otherwise, all cert
	// issuances will fail.
	MaxObtain int32
	// contains filtered or unexported fields
}

OnDemandConfig contains some state relevant for providing on-demand TLS.

func (*OnDemandConfig) Allowed

func (o *OnDemandConfig) Allowed(name string) error

Allowed returns whether the issuance for name is allowed according to o.

type Storage

type Storage interface {
	// Locker provides atomic synchronization
	// operations, making Storage safe to share.
	Locker

	// Store puts value at key.
	Store(key string, value []byte) error

	// Load retrieves the value at key.
	Load(key string) ([]byte, error)

	// Delete deletes key.
	Delete(key string) error

	// Exists returns true if the key exists
	// and there was no error checking.
	Exists(key string) bool

	// List returns all keys that match prefix.
	// If recursive is true, non-terminal keys
	// will be enumerated (i.e. "directories"
	// should be walked); otherwise, only keys
	// prefixed exactly by prefix will be listed.
	List(prefix string, recursive bool) ([]string, error)

	// Stat returns information about key.
	Stat(key string) (KeyInfo, error)
}

Storage is a type that implements a key-value store. Keys are prefix-based, with forward slash '/' as separators and without a leading slash.

Processes running in a cluster will wish to use the same Storage value (its implementation and configuration) in order to share certificates and other TLS resources with the cluster.

Implementations of Storage must be safe for concurrent use.

var DefaultStorage Storage = defaultFileStorage

DefaultStorage is the default Storage implementation.

type Waiter

type Waiter interface {
	Wait()
}

Waiter is a type that can block until a lock is released.

Jump to

Keyboard shortcuts

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