2019-07-01 06:07:58 +08:00
|
|
|
// Copyright 2015 Matthew Holt and The Caddy Authors
|
|
|
|
//
|
|
|
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
|
|
|
// you may not use this file except in compliance with the License.
|
|
|
|
// You may obtain a copy of the License at
|
|
|
|
//
|
|
|
|
// http://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
//
|
|
|
|
// Unless required by applicable law or agreed to in writing, software
|
|
|
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
|
|
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
|
|
// See the License for the specific language governing permissions and
|
|
|
|
// limitations under the License.
|
|
|
|
|
2019-04-26 03:54:48 +08:00
|
|
|
package caddytls
|
|
|
|
|
|
|
|
import (
|
|
|
|
"crypto/tls"
|
|
|
|
"encoding/json"
|
|
|
|
"fmt"
|
2019-09-18 06:00:15 +08:00
|
|
|
"log"
|
2019-04-26 03:54:48 +08:00
|
|
|
"net/http"
|
2019-09-18 06:00:15 +08:00
|
|
|
"sync"
|
2019-06-21 10:36:29 +08:00
|
|
|
"time"
|
2019-04-26 03:54:48 +08:00
|
|
|
|
2019-07-03 02:37:06 +08:00
|
|
|
"github.com/caddyserver/caddy/v2"
|
2019-09-13 07:31:10 +08:00
|
|
|
"github.com/go-acme/lego/v3/challenge"
|
2019-04-26 03:54:48 +08:00
|
|
|
"github.com/mholt/certmagic"
|
2019-06-21 10:36:29 +08:00
|
|
|
"golang.org/x/time/rate"
|
2019-04-26 03:54:48 +08:00
|
|
|
)
|
|
|
|
|
|
|
|
func init() {
|
2019-08-22 00:46:35 +08:00
|
|
|
caddy.RegisterModule(TLS{})
|
2019-04-26 03:54:48 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
// TLS represents a process-wide TLS configuration.
|
|
|
|
type TLS struct {
|
2019-05-30 13:11:46 +08:00
|
|
|
Certificates map[string]json.RawMessage `json:"certificates,omitempty"`
|
2019-08-10 02:05:47 +08:00
|
|
|
Automation AutomationConfig `json:"automation"`
|
|
|
|
SessionTickets SessionTicketService `json:"session_tickets"`
|
2019-04-26 03:54:48 +08:00
|
|
|
|
|
|
|
certificateLoaders []CertificateLoader
|
|
|
|
certCache *certmagic.Cache
|
2019-06-15 01:58:28 +08:00
|
|
|
ctx caddy.Context
|
2019-09-18 06:00:15 +08:00
|
|
|
storageCleanTicker *time.Ticker
|
|
|
|
storageCleanStop chan struct{}
|
2019-04-26 03:54:48 +08:00
|
|
|
}
|
|
|
|
|
2019-08-22 00:46:35 +08:00
|
|
|
// CaddyModule returns the Caddy module information.
|
|
|
|
func (TLS) CaddyModule() caddy.ModuleInfo {
|
|
|
|
return caddy.ModuleInfo{
|
|
|
|
Name: "tls",
|
|
|
|
New: func() caddy.Module { return new(TLS) },
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-04-27 02:35:39 +08:00
|
|
|
// Provision sets up the configuration for the TLS app.
|
2019-06-15 01:58:28 +08:00
|
|
|
func (t *TLS) Provision(ctx caddy.Context) error {
|
2019-05-17 06:05:38 +08:00
|
|
|
t.ctx = ctx
|
|
|
|
|
2019-04-26 03:54:48 +08:00
|
|
|
// set up the certificate cache
|
|
|
|
// TODO: this makes a new cache every time; better to only make a new
|
|
|
|
// cache (or even better, add/remove only what is necessary) if the
|
|
|
|
// certificates config has been updated
|
|
|
|
t.certCache = certmagic.NewCache(certmagic.CacheOptions{
|
|
|
|
GetConfigForCert: func(cert certmagic.Certificate) (certmagic.Config, error) {
|
|
|
|
return t.getConfigForName(cert.Names[0])
|
|
|
|
},
|
|
|
|
})
|
|
|
|
|
2019-05-30 13:11:46 +08:00
|
|
|
// automation/management policies
|
2019-04-26 03:54:48 +08:00
|
|
|
for i, ap := range t.Automation.Policies {
|
2019-06-05 12:43:21 +08:00
|
|
|
val, err := ctx.LoadModuleInline("module", "tls.management", ap.ManagementRaw)
|
2019-04-26 03:54:48 +08:00
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("loading TLS automation management module: %s", err)
|
|
|
|
}
|
2019-08-22 00:46:35 +08:00
|
|
|
t.Automation.Policies[i].Management = val.(ManagerMaker)
|
2019-09-15 08:05:45 +08:00
|
|
|
t.Automation.Policies[i].ManagementRaw = nil // allow GC to deallocate
|
2019-04-26 03:54:48 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
// certificate loaders
|
|
|
|
for modName, rawMsg := range t.Certificates {
|
|
|
|
if modName == automateKey {
|
|
|
|
continue // special case; these will be loaded in later
|
|
|
|
}
|
2019-05-17 06:05:38 +08:00
|
|
|
val, err := ctx.LoadModule("tls.certificates."+modName, rawMsg)
|
2019-04-26 03:54:48 +08:00
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("loading certificate module '%s': %s", modName, err)
|
|
|
|
}
|
|
|
|
t.certificateLoaders = append(t.certificateLoaders, val.(CertificateLoader))
|
|
|
|
}
|
|
|
|
|
2019-05-30 13:11:46 +08:00
|
|
|
// session ticket ephemeral keys (STEK) service and provider
|
|
|
|
err := t.SessionTickets.provision(ctx)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("provisioning session tickets configuration: %v", err)
|
|
|
|
}
|
|
|
|
|
2019-06-21 10:36:29 +08:00
|
|
|
// on-demand rate limiting
|
|
|
|
if t.Automation.OnDemand != nil && t.Automation.OnDemand.RateLimit != nil {
|
|
|
|
limit := rate.Every(time.Duration(t.Automation.OnDemand.RateLimit.Interval))
|
|
|
|
// TODO: Burst size is not updated, see https://github.com/golang/go/issues/23575
|
|
|
|
onDemandRateLimiter.SetLimit(limit)
|
|
|
|
} else {
|
|
|
|
// if no rate limit is specified, be sure to remove any existing limit
|
|
|
|
onDemandRateLimiter.SetLimit(0)
|
|
|
|
}
|
|
|
|
|
2019-08-10 02:05:47 +08:00
|
|
|
// load manual/static (unmanaged) certificates - we do this in
|
|
|
|
// provision so that other apps (such as http) can know which
|
|
|
|
// certificates have been manually loaded
|
2019-06-27 06:03:29 +08:00
|
|
|
magic := certmagic.New(t.certCache, certmagic.Config{
|
2019-08-10 02:05:47 +08:00
|
|
|
Storage: ctx.Storage(),
|
2019-06-27 06:03:29 +08:00
|
|
|
})
|
2019-04-26 03:54:48 +08:00
|
|
|
for _, loader := range t.certificateLoaders {
|
|
|
|
certs, err := loader.LoadCertificates()
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("loading certificates: %v", err)
|
|
|
|
}
|
|
|
|
for _, cert := range certs {
|
2019-06-25 02:16:10 +08:00
|
|
|
err := magic.CacheUnmanagedTLSCertificate(cert.Certificate, cert.Tags)
|
2019-04-26 03:54:48 +08:00
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("caching unmanaged certificate: %v", err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-09-18 06:00:15 +08:00
|
|
|
t.storageCleanTicker = time.NewTicker(storageCleanInterval)
|
|
|
|
t.storageCleanStop = make(chan struct{})
|
|
|
|
|
2019-08-10 02:05:47 +08:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Start activates the TLS module.
|
|
|
|
func (t *TLS) Start() error {
|
2019-04-26 03:54:48 +08:00
|
|
|
// load automated (managed) certificates
|
|
|
|
if automatedRawMsg, ok := t.Certificates[automateKey]; ok {
|
|
|
|
var names []string
|
|
|
|
err := json.Unmarshal(automatedRawMsg, &names)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("automate: decoding names: %v", err)
|
|
|
|
}
|
|
|
|
err = t.Manage(names)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("automate: managing %v: %v", names, err)
|
|
|
|
}
|
|
|
|
}
|
2019-09-15 08:05:45 +08:00
|
|
|
t.Certificates = nil // allow GC to deallocate
|
2019-04-26 03:54:48 +08:00
|
|
|
|
2019-09-18 06:00:15 +08:00
|
|
|
t.keepStorageClean()
|
|
|
|
|
2019-04-26 03:54:48 +08:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Stop stops the TLS module and cleans up any allocations.
|
|
|
|
func (t *TLS) Stop() error {
|
2019-09-18 06:00:15 +08:00
|
|
|
// stop the certificate cache
|
2019-04-26 03:54:48 +08:00
|
|
|
if t.certCache != nil {
|
|
|
|
t.certCache.Stop()
|
|
|
|
}
|
2019-09-18 06:00:15 +08:00
|
|
|
|
|
|
|
// stop the session ticket rotation goroutine
|
2019-05-30 13:11:46 +08:00
|
|
|
t.SessionTickets.stop()
|
2019-09-18 06:00:15 +08:00
|
|
|
|
|
|
|
// stop the storage cleaner goroutine and ticker
|
|
|
|
close(t.storageCleanStop)
|
|
|
|
t.storageCleanTicker.Stop()
|
|
|
|
|
2019-04-26 03:54:48 +08:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Manage immediately begins managing names according to the
|
|
|
|
// matching automation policy.
|
|
|
|
func (t *TLS) Manage(names []string) error {
|
|
|
|
for _, name := range names {
|
|
|
|
ap := t.getAutomationPolicyForName(name)
|
2019-05-17 06:05:38 +08:00
|
|
|
magic := certmagic.New(t.certCache, ap.makeCertMagicConfig(t.ctx))
|
2019-04-26 03:54:48 +08:00
|
|
|
err := magic.Manage([]string{name})
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("automate: manage %s: %v", name, err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// HandleHTTPChallenge ensures that the HTTP challenge is handled for the
|
|
|
|
// certificate named by r.Host, if it is an HTTP challenge request.
|
|
|
|
func (t *TLS) HandleHTTPChallenge(w http.ResponseWriter, r *http.Request) bool {
|
|
|
|
if !certmagic.LooksLikeHTTPChallenge(r) {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
ap := t.getAutomationPolicyForName(r.Host)
|
2019-05-17 06:05:38 +08:00
|
|
|
magic := certmagic.New(t.certCache, ap.makeCertMagicConfig(t.ctx))
|
2019-04-26 03:54:48 +08:00
|
|
|
return magic.HandleHTTPChallenge(w, r)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (t *TLS) getConfigForName(name string) (certmagic.Config, error) {
|
|
|
|
ap := t.getAutomationPolicyForName(name)
|
2019-05-17 06:05:38 +08:00
|
|
|
return ap.makeCertMagicConfig(t.ctx), nil
|
2019-04-26 03:54:48 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
func (t *TLS) getAutomationPolicyForName(name string) AutomationPolicy {
|
|
|
|
for _, ap := range t.Automation.Policies {
|
|
|
|
if len(ap.Hosts) == 0 {
|
|
|
|
// no host filter is an automatic match
|
|
|
|
return ap
|
|
|
|
}
|
|
|
|
for _, h := range ap.Hosts {
|
|
|
|
if h == name {
|
|
|
|
return ap
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// default automation policy
|
2019-09-13 07:31:54 +08:00
|
|
|
return AutomationPolicy{Management: new(ACMEManagerMaker)}
|
2019-04-26 03:54:48 +08:00
|
|
|
}
|
|
|
|
|
2019-09-18 06:00:15 +08:00
|
|
|
// AllMatchingCertificates returns the list of all certificates in
|
2019-09-14 01:46:58 +08:00
|
|
|
// the cache which could be used to satisfy the given SAN.
|
|
|
|
func (t *TLS) AllMatchingCertificates(san string) []certmagic.Certificate {
|
|
|
|
return t.certCache.AllMatchingCertificates(san)
|
2019-08-10 02:05:47 +08:00
|
|
|
}
|
|
|
|
|
2019-09-18 06:00:15 +08:00
|
|
|
// keepStorageClean immediately cleans up all known storage units
|
|
|
|
// if it was not recently done, and starts a goroutine that runs
|
|
|
|
// the operation at every tick from t.storageCleanTicker.
|
|
|
|
func (t *TLS) keepStorageClean() {
|
|
|
|
go func() {
|
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case <-t.storageCleanStop:
|
|
|
|
return
|
|
|
|
case <-t.storageCleanTicker.C:
|
|
|
|
t.cleanStorageUnits()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
t.cleanStorageUnits()
|
|
|
|
}
|
|
|
|
|
|
|
|
func (t *TLS) cleanStorageUnits() {
|
|
|
|
storageCleanMu.Lock()
|
|
|
|
defer storageCleanMu.Unlock()
|
|
|
|
|
|
|
|
if !storageClean.IsZero() && time.Since(storageClean) < storageCleanInterval {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
options := certmagic.CleanStorageOptions{
|
|
|
|
OCSPStaples: true,
|
|
|
|
ExpiredCerts: true,
|
|
|
|
ExpiredCertGracePeriod: 24 * time.Hour * 14,
|
|
|
|
}
|
|
|
|
|
|
|
|
// start with the default storage
|
|
|
|
certmagic.CleanStorage(t.ctx.Storage(), options)
|
|
|
|
|
|
|
|
// then clean each storage defined in ACME automation policies
|
|
|
|
for _, ap := range t.Automation.Policies {
|
|
|
|
if acmeMgmt, ok := ap.Management.(ACMEManagerMaker); ok {
|
|
|
|
if acmeMgmt.storage != nil {
|
|
|
|
certmagic.CleanStorage(acmeMgmt.storage, options)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
storageClean = time.Now()
|
|
|
|
|
|
|
|
log.Println("[INFO] tls: Cleaned up storage unit(s)")
|
|
|
|
}
|
|
|
|
|
2019-04-26 03:54:48 +08:00
|
|
|
// CertificateLoader is a type that can load certificates.
|
2019-06-25 02:16:10 +08:00
|
|
|
// Certificates can optionally be associated with tags.
|
2019-04-26 03:54:48 +08:00
|
|
|
type CertificateLoader interface {
|
2019-06-25 02:16:10 +08:00
|
|
|
LoadCertificates() ([]Certificate, error)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Certificate is a TLS certificate, optionally
|
|
|
|
// associated with arbitrary tags.
|
|
|
|
type Certificate struct {
|
|
|
|
tls.Certificate
|
|
|
|
Tags []string
|
2019-04-26 03:54:48 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
// AutomationConfig designates configuration for the
|
|
|
|
// construction and use of ACME clients.
|
|
|
|
type AutomationConfig struct {
|
|
|
|
Policies []AutomationPolicy `json:"policies,omitempty"`
|
2019-06-21 10:36:29 +08:00
|
|
|
OnDemand *OnDemandConfig `json:"on_demand,omitempty"`
|
2019-04-26 03:54:48 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
// AutomationPolicy designates the policy for automating the
|
|
|
|
// management of managed TLS certificates.
|
|
|
|
type AutomationPolicy struct {
|
2019-06-05 12:43:21 +08:00
|
|
|
Hosts []string `json:"hosts,omitempty"`
|
2019-06-21 22:52:15 +08:00
|
|
|
ManagementRaw json.RawMessage `json:"management,omitempty"`
|
2019-04-26 03:54:48 +08:00
|
|
|
|
2019-08-22 00:46:35 +08:00
|
|
|
Management ManagerMaker `json:"-"`
|
2019-04-26 03:54:48 +08:00
|
|
|
}
|
|
|
|
|
2019-06-21 10:36:29 +08:00
|
|
|
// makeCertMagicConfig converts ap into a CertMagic config. Passing onDemand
|
|
|
|
// is necessary because the automation policy does not have convenient access
|
|
|
|
// to the TLS app's global on-demand policies;
|
2019-06-15 01:58:28 +08:00
|
|
|
func (ap AutomationPolicy) makeCertMagicConfig(ctx caddy.Context) certmagic.Config {
|
2019-04-27 02:35:39 +08:00
|
|
|
// default manager (ACME) is a special case because of how CertMagic is designed
|
|
|
|
// TODO: refactor certmagic so that ACME manager is not a special case by extracting
|
|
|
|
// its config fields out of the certmagic.Config struct, or something...
|
2019-06-05 12:43:21 +08:00
|
|
|
if acmeMgmt, ok := ap.Management.(*ACMEManagerMaker); ok {
|
2019-05-17 06:05:38 +08:00
|
|
|
return acmeMgmt.makeCertMagicConfig(ctx)
|
2019-04-26 03:54:48 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
return certmagic.Config{
|
2019-08-22 00:46:35 +08:00
|
|
|
NewManager: ap.Management.NewManager,
|
2019-04-26 03:54:48 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// ChallengesConfig configures the ACME challenges.
|
|
|
|
type ChallengesConfig struct {
|
|
|
|
HTTP HTTPChallengeConfig `json:"http"`
|
|
|
|
TLSALPN TLSALPNChallengeConfig `json:"tls-alpn"`
|
2019-06-05 12:43:21 +08:00
|
|
|
DNSRaw json.RawMessage `json:"dns,omitempty"`
|
2019-04-26 03:54:48 +08:00
|
|
|
|
2019-06-05 12:43:21 +08:00
|
|
|
DNS challenge.Provider `json:"-"`
|
2019-04-26 03:54:48 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
// HTTPChallengeConfig configures the ACME HTTP challenge.
|
|
|
|
type HTTPChallengeConfig struct {
|
|
|
|
Disabled bool `json:"disabled,omitempty"`
|
|
|
|
AlternatePort int `json:"alternate_port,omitempty"`
|
|
|
|
}
|
|
|
|
|
|
|
|
// TLSALPNChallengeConfig configures the ACME TLS-ALPN challenge.
|
|
|
|
type TLSALPNChallengeConfig struct {
|
|
|
|
Disabled bool `json:"disabled,omitempty"`
|
|
|
|
AlternatePort int `json:"alternate_port,omitempty"`
|
|
|
|
}
|
|
|
|
|
|
|
|
// OnDemandConfig configures on-demand TLS, for obtaining
|
|
|
|
// needed certificates at handshake-time.
|
|
|
|
type OnDemandConfig struct {
|
2019-06-21 10:36:29 +08:00
|
|
|
RateLimit *RateLimit `json:"rate_limit,omitempty"`
|
|
|
|
Ask string `json:"ask,omitempty"`
|
|
|
|
}
|
|
|
|
|
|
|
|
// RateLimit specifies an interval with optional burst size.
|
|
|
|
type RateLimit struct {
|
|
|
|
Interval caddy.Duration `json:"interval,omitempty"`
|
|
|
|
Burst int `json:"burst,omitempty"`
|
2019-04-26 03:54:48 +08:00
|
|
|
}
|
|
|
|
|
2019-08-22 00:46:35 +08:00
|
|
|
// ManagerMaker makes a certificate manager.
|
|
|
|
type ManagerMaker interface {
|
|
|
|
NewManager(interactive bool) (certmagic.Manager, error)
|
2019-04-26 03:54:48 +08:00
|
|
|
}
|
|
|
|
|
2019-06-21 10:36:29 +08:00
|
|
|
// These perpetual values are used for on-demand TLS.
|
|
|
|
var (
|
|
|
|
onDemandRateLimiter = rate.NewLimiter(0, 1)
|
|
|
|
onDemandAskClient = &http.Client{
|
|
|
|
Timeout: 10 * time.Second,
|
|
|
|
CheckRedirect: func(req *http.Request, via []*http.Request) error {
|
|
|
|
return fmt.Errorf("following http redirects is not allowed")
|
|
|
|
},
|
|
|
|
}
|
|
|
|
)
|
|
|
|
|
2019-09-18 06:00:15 +08:00
|
|
|
// Variables related to storage cleaning.
|
|
|
|
var (
|
|
|
|
storageCleanInterval = 12 * time.Hour
|
|
|
|
|
|
|
|
storageClean time.Time
|
|
|
|
storageCleanMu sync.Mutex
|
|
|
|
)
|
|
|
|
|
2019-04-26 03:54:48 +08:00
|
|
|
const automateKey = "automate"
|