2019-07-01 01:07:58 +03: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-25 22:54:48 +03:00
|
|
|
package caddytls
|
|
|
|
|
|
|
|
import (
|
|
|
|
"crypto/tls"
|
|
|
|
"encoding/json"
|
|
|
|
"fmt"
|
2020-03-07 20:42:50 +03:00
|
|
|
"io/ioutil"
|
2020-05-12 20:36:20 +03:00
|
|
|
"log"
|
2019-04-25 22:54:48 +03:00
|
|
|
"net/http"
|
2020-03-07 20:42:50 +03:00
|
|
|
"os"
|
|
|
|
"path/filepath"
|
2020-05-12 20:36:20 +03:00
|
|
|
"runtime/debug"
|
2020-03-07 20:42:50 +03:00
|
|
|
"strings"
|
2019-09-18 01:00:15 +03:00
|
|
|
"sync"
|
2019-06-21 05:36:29 +03:00
|
|
|
"time"
|
2019-04-25 22:54:48 +03:00
|
|
|
|
2019-07-02 21:37:06 +03:00
|
|
|
"github.com/caddyserver/caddy/v2"
|
2020-03-07 09:15:25 +03:00
|
|
|
"github.com/caddyserver/certmagic"
|
2019-10-28 23:39:37 +03:00
|
|
|
"go.uber.org/zap"
|
2019-04-25 22:54:48 +03:00
|
|
|
)
|
|
|
|
|
|
|
|
func init() {
|
2019-08-21 19:46:35 +03:00
|
|
|
caddy.RegisterModule(TLS{})
|
2019-12-10 23:36:46 +03:00
|
|
|
caddy.RegisterModule(AutomateLoader{})
|
2019-04-25 22:54:48 +03:00
|
|
|
}
|
|
|
|
|
2019-12-10 23:36:46 +03:00
|
|
|
// TLS provides TLS facilities including certificate
|
|
|
|
// loading and management, client auth, and more.
|
2019-04-25 22:54:48 +03:00
|
|
|
type TLS struct {
|
2019-12-10 23:36:46 +03:00
|
|
|
// Caches certificates in memory for quick use during
|
|
|
|
// TLS handshakes. Each key is the name of a certificate
|
|
|
|
// loader module. All loaded certificates get pooled
|
|
|
|
// into the same cache and may be used to complete TLS
|
|
|
|
// handshakes for the relevant server names (SNI).
|
|
|
|
// Certificates loaded manually (anything other than
|
|
|
|
// "automate") are not automatically managed and will
|
|
|
|
// have to be refreshed manually before they expire.
|
|
|
|
CertificatesRaw caddy.ModuleMap `json:"certificates,omitempty" caddy:"namespace=tls.certificates"`
|
|
|
|
|
|
|
|
// Configures the automation of certificate management.
|
|
|
|
Automation *AutomationConfig `json:"automation,omitempty"`
|
|
|
|
|
|
|
|
// Configures session ticket ephemeral keys (STEKs).
|
|
|
|
SessionTickets *SessionTicketService `json:"session_tickets,omitempty"`
|
2019-04-25 22:54:48 +03:00
|
|
|
|
2020-06-05 20:14:39 +03:00
|
|
|
// Configures the in-memory certificate cache.
|
|
|
|
Cache *CertCacheOptions `json:"cache,omitempty"`
|
|
|
|
|
2019-04-25 22:54:48 +03:00
|
|
|
certificateLoaders []CertificateLoader
|
2019-12-10 23:36:46 +03:00
|
|
|
automateNames []string
|
2019-04-25 22:54:48 +03:00
|
|
|
certCache *certmagic.Cache
|
2019-06-14 20:58:28 +03:00
|
|
|
ctx caddy.Context
|
2019-09-18 01:00:15 +03:00
|
|
|
storageCleanTicker *time.Ticker
|
|
|
|
storageCleanStop chan struct{}
|
2019-10-28 23:39:37 +03:00
|
|
|
logger *zap.Logger
|
2019-04-25 22:54:48 +03:00
|
|
|
}
|
|
|
|
|
2019-08-21 19:46:35 +03:00
|
|
|
// CaddyModule returns the Caddy module information.
|
|
|
|
func (TLS) CaddyModule() caddy.ModuleInfo {
|
|
|
|
return caddy.ModuleInfo{
|
2019-12-10 23:36:46 +03:00
|
|
|
ID: "tls",
|
|
|
|
New: func() caddy.Module { return new(TLS) },
|
2019-08-21 19:46:35 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-04-26 21:35:39 +03:00
|
|
|
// Provision sets up the configuration for the TLS app.
|
2019-06-14 20:58:28 +03:00
|
|
|
func (t *TLS) Provision(ctx caddy.Context) error {
|
2019-05-17 01:05:38 +03:00
|
|
|
t.ctx = ctx
|
2019-10-28 23:39:37 +03:00
|
|
|
t.logger = ctx.Logger(t)
|
2019-05-17 01:05:38 +03:00
|
|
|
|
2019-09-30 18:07:43 +03:00
|
|
|
// set up a new certificate cache; this (re)loads all certificates
|
|
|
|
cacheOpts := certmagic.CacheOptions{
|
2020-03-07 09:15:25 +03:00
|
|
|
GetConfigForCert: func(cert certmagic.Certificate) (*certmagic.Config, error) {
|
|
|
|
return t.getConfigForName(cert.Names[0]), nil
|
2019-04-25 22:54:48 +03:00
|
|
|
},
|
2020-07-31 00:18:14 +03:00
|
|
|
Logger: t.logger.Named("cache"),
|
2019-09-30 18:07:43 +03:00
|
|
|
}
|
|
|
|
if t.Automation != nil {
|
|
|
|
cacheOpts.OCSPCheckInterval = time.Duration(t.Automation.OCSPCheckInterval)
|
|
|
|
cacheOpts.RenewCheckInterval = time.Duration(t.Automation.RenewCheckInterval)
|
|
|
|
}
|
2020-06-05 20:14:39 +03:00
|
|
|
if t.Cache != nil {
|
|
|
|
cacheOpts.Capacity = t.Cache.Capacity
|
|
|
|
}
|
2020-07-31 00:18:14 +03:00
|
|
|
if cacheOpts.Capacity <= 0 {
|
|
|
|
cacheOpts.Capacity = 10000
|
|
|
|
}
|
2019-09-30 18:07:43 +03:00
|
|
|
t.certCache = certmagic.NewCache(cacheOpts)
|
2019-04-25 22:54:48 +03:00
|
|
|
|
|
|
|
// certificate loaders
|
2019-12-10 23:36:46 +03:00
|
|
|
val, err := ctx.LoadModule(t, "CertificatesRaw")
|
|
|
|
if err != nil {
|
2020-03-07 09:15:25 +03:00
|
|
|
return fmt.Errorf("loading certificate loader modules: %s", err)
|
2019-12-10 23:36:46 +03:00
|
|
|
}
|
|
|
|
for modName, modIface := range val.(map[string]interface{}) {
|
|
|
|
if modName == "automate" {
|
2020-04-09 22:09:48 +03:00
|
|
|
// special case; these will be loaded in later using our automation facilities,
|
|
|
|
// which we want to avoid doing during provisioning
|
2020-01-06 18:10:20 +03:00
|
|
|
if automateNames, ok := modIface.(*AutomateLoader); ok && automateNames != nil {
|
|
|
|
t.automateNames = []string(*automateNames)
|
|
|
|
} else {
|
|
|
|
return fmt.Errorf("loading certificates with 'automate' requires array of strings, got: %T", modIface)
|
2019-12-10 23:36:46 +03:00
|
|
|
}
|
|
|
|
continue
|
2019-04-25 22:54:48 +03:00
|
|
|
}
|
2019-12-10 23:36:46 +03:00
|
|
|
t.certificateLoaders = append(t.certificateLoaders, modIface.(CertificateLoader))
|
2019-04-25 22:54:48 +03:00
|
|
|
}
|
|
|
|
|
2020-04-09 22:09:48 +03:00
|
|
|
// automation/management policies
|
|
|
|
if t.Automation == nil {
|
|
|
|
t.Automation = new(AutomationConfig)
|
|
|
|
}
|
|
|
|
t.Automation.defaultPublicAutomationPolicy = new(AutomationPolicy)
|
|
|
|
err = t.Automation.defaultPublicAutomationPolicy.Provision(t)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("provisioning default public automation policy: %v", err)
|
|
|
|
}
|
|
|
|
for _, n := range t.automateNames {
|
|
|
|
// if any names specified by the "automate" loader do not qualify for a public
|
|
|
|
// certificate, we should initialize a default internal automation policy
|
|
|
|
// (but we don't want to do this unnecessarily, since it may prompt for password!)
|
|
|
|
if certmagic.SubjectQualifiesForPublicCert(n) {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
t.Automation.defaultInternalAutomationPolicy = &AutomationPolicy{
|
2020-11-16 21:05:55 +03:00
|
|
|
IssuersRaw: []json.RawMessage{json.RawMessage(`{"module":"internal"}`)},
|
2020-04-09 22:09:48 +03:00
|
|
|
}
|
|
|
|
err = t.Automation.defaultInternalAutomationPolicy.Provision(t)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("provisioning default internal automation policy: %v", err)
|
|
|
|
}
|
|
|
|
break
|
|
|
|
}
|
|
|
|
for i, ap := range t.Automation.Policies {
|
|
|
|
err := ap.Provision(t)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("provisioning automation policy %d: %v", i, err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-05-30 08:11:46 +03:00
|
|
|
// session ticket ephemeral keys (STEK) service and provider
|
2019-09-30 18:07:43 +03:00
|
|
|
if t.SessionTickets != nil {
|
|
|
|
err := t.SessionTickets.provision(ctx)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("provisioning session tickets configuration: %v", err)
|
|
|
|
}
|
2019-05-30 08:11:46 +03:00
|
|
|
}
|
|
|
|
|
2019-06-21 05:36:29 +03:00
|
|
|
// on-demand rate limiting
|
2019-09-30 18:07:43 +03:00
|
|
|
if t.Automation != nil && t.Automation.OnDemand != nil && t.Automation.OnDemand.RateLimit != nil {
|
2019-10-21 21:03:51 +03:00
|
|
|
onDemandRateLimiter.SetMaxEvents(t.Automation.OnDemand.RateLimit.Burst)
|
|
|
|
onDemandRateLimiter.SetWindow(time.Duration(t.Automation.OnDemand.RateLimit.Interval))
|
2019-06-21 05:36:29 +03:00
|
|
|
} else {
|
2019-10-21 21:03:51 +03:00
|
|
|
// remove any existing rate limiter
|
|
|
|
onDemandRateLimiter.SetMaxEvents(0)
|
|
|
|
onDemandRateLimiter.SetWindow(0)
|
2019-06-21 05:36:29 +03:00
|
|
|
}
|
|
|
|
|
2019-08-09 21:05:47 +03:00
|
|
|
// load manual/static (unmanaged) certificates - we do this in
|
|
|
|
// provision so that other apps (such as http) can know which
|
2019-12-10 23:36:46 +03:00
|
|
|
// certificates have been manually loaded, and also so that
|
|
|
|
// commands like validate can be a better test
|
2019-06-27 01:03:29 +03:00
|
|
|
magic := certmagic.New(t.certCache, certmagic.Config{
|
2019-08-09 21:05:47 +03:00
|
|
|
Storage: ctx.Storage(),
|
2020-07-31 00:18:14 +03:00
|
|
|
Logger: t.logger,
|
2019-06-27 01:03:29 +03:00
|
|
|
})
|
2019-04-25 22:54:48 +03: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-24 21:16:10 +03:00
|
|
|
err := magic.CacheUnmanagedTLSCertificate(cert.Certificate, cert.Tags)
|
2019-04-25 22:54:48 +03:00
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("caching unmanaged certificate: %v", err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-03-07 20:42:50 +03:00
|
|
|
// TODO: TEMPORARY UNTIL RELEASE CANDIDATES:
|
|
|
|
// MIGRATE MANAGED CERTIFICATE ASSETS TO NEW PATH
|
|
|
|
err = t.moveCertificates()
|
|
|
|
if err != nil {
|
|
|
|
t.logger.Error("migrating certificates", zap.Error(err))
|
|
|
|
}
|
|
|
|
// END TODO: TEMPORARY.
|
|
|
|
|
2019-08-09 21:05:47 +03:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2020-03-13 20:06:08 +03:00
|
|
|
// Validate validates t's configuration.
|
|
|
|
func (t *TLS) Validate() error {
|
|
|
|
if t.Automation != nil {
|
|
|
|
// ensure that host aren't repeated; since only the first
|
|
|
|
// automation policy is used, repeating a host in the lists
|
2020-03-18 06:00:45 +03:00
|
|
|
// isn't useful and is probably a mistake; same for two
|
|
|
|
// catch-all/default policies
|
|
|
|
var hasDefault bool
|
2020-03-13 20:06:08 +03:00
|
|
|
hostSet := make(map[string]int)
|
|
|
|
for i, ap := range t.Automation.Policies {
|
2020-03-18 06:00:45 +03:00
|
|
|
if len(ap.Subjects) == 0 {
|
|
|
|
if hasDefault {
|
|
|
|
return fmt.Errorf("automation policy %d is the second policy that acts as default/catch-all, but will never be used", i)
|
|
|
|
}
|
|
|
|
hasDefault = true
|
|
|
|
}
|
2020-03-16 06:22:26 +03:00
|
|
|
for _, h := range ap.Subjects {
|
2020-03-13 20:06:08 +03:00
|
|
|
if first, ok := hostSet[h]; ok {
|
|
|
|
return fmt.Errorf("automation policy %d: cannot apply more than one automation policy to host: %s (first match in policy %d)", i, h, first)
|
|
|
|
}
|
|
|
|
hostSet[h] = i
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2020-06-05 20:14:39 +03:00
|
|
|
if t.Cache != nil {
|
|
|
|
if t.Cache.Capacity < 0 {
|
|
|
|
return fmt.Errorf("cache capacity must be >= 0")
|
|
|
|
}
|
|
|
|
}
|
2020-03-13 20:06:08 +03:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2019-08-09 21:05:47 +03:00
|
|
|
// Start activates the TLS module.
|
|
|
|
func (t *TLS) Start() error {
|
2019-12-10 23:36:46 +03:00
|
|
|
// now that we are running, and all manual certificates have
|
|
|
|
// been loaded, time to load the automated/managed certificates
|
|
|
|
err := t.Manage(t.automateNames)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("automate: managing %v: %v", t.automateNames, err)
|
2019-04-25 22:54:48 +03:00
|
|
|
}
|
|
|
|
|
2019-09-18 01:00:15 +03:00
|
|
|
t.keepStorageClean()
|
|
|
|
|
2019-04-25 22:54:48 +03:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Stop stops the TLS module and cleans up any allocations.
|
|
|
|
func (t *TLS) Stop() error {
|
2019-09-30 18:07:43 +03:00
|
|
|
// stop the storage cleaner goroutine and ticker
|
2019-10-03 08:39:32 +03:00
|
|
|
if t.storageCleanStop != nil {
|
|
|
|
close(t.storageCleanStop)
|
|
|
|
}
|
|
|
|
if t.storageCleanTicker != nil {
|
|
|
|
t.storageCleanTicker.Stop()
|
|
|
|
}
|
2019-09-30 18:07:43 +03:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Cleanup frees up resources allocated during Provision.
|
|
|
|
func (t *TLS) Cleanup() error {
|
2019-09-18 01:00:15 +03:00
|
|
|
// stop the certificate cache
|
2019-04-25 22:54:48 +03:00
|
|
|
if t.certCache != nil {
|
|
|
|
t.certCache.Stop()
|
|
|
|
}
|
2019-09-18 01:00:15 +03:00
|
|
|
|
|
|
|
// stop the session ticket rotation goroutine
|
2019-09-30 18:07:43 +03:00
|
|
|
if t.SessionTickets != nil {
|
|
|
|
t.SessionTickets.stop()
|
|
|
|
}
|
2019-09-18 01:00:15 +03:00
|
|
|
|
2019-04-25 22:54:48 +03:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Manage immediately begins managing names according to the
|
|
|
|
// matching automation policy.
|
|
|
|
func (t *TLS) Manage(names []string) error {
|
2020-02-14 21:14:52 +03:00
|
|
|
// for a large number of names, we can be more memory-efficient
|
|
|
|
// by making only one certmagic.Config for all the names that
|
2020-03-26 23:02:29 +03:00
|
|
|
// use that config, rather than calling ManageAsync once for
|
|
|
|
// every name; so first, bin names by AutomationPolicy
|
2020-02-14 21:14:52 +03:00
|
|
|
policyToNames := make(map[*AutomationPolicy][]string)
|
2019-04-25 22:54:48 +03:00
|
|
|
for _, name := range names {
|
|
|
|
ap := t.getAutomationPolicyForName(name)
|
2020-02-14 21:14:52 +03:00
|
|
|
policyToNames[ap] = append(policyToNames[ap], name)
|
|
|
|
}
|
|
|
|
|
|
|
|
// now that names are grouped by policy, we can simply make one
|
|
|
|
// certmagic.Config for each (potentially large) group of names
|
2020-03-26 23:02:29 +03:00
|
|
|
// and call ManageAsync just once for the whole batch
|
2020-02-14 21:14:52 +03:00
|
|
|
for ap, names := range policyToNames {
|
2020-03-26 23:02:29 +03:00
|
|
|
err := ap.magic.ManageAsync(t.ctx.Context, names)
|
2019-04-25 22:54:48 +03:00
|
|
|
if err != nil {
|
2020-02-14 21:14:52 +03:00
|
|
|
return fmt.Errorf("automate: manage %v: %v", names, err)
|
2019-04-25 22:54:48 +03:00
|
|
|
}
|
|
|
|
}
|
2020-02-14 21:14:52 +03:00
|
|
|
|
2019-04-25 22:54:48 +03:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// HandleHTTPChallenge ensures that the HTTP challenge is handled for the
|
2020-03-07 09:15:25 +03:00
|
|
|
// certificate named by r.Host, if it is an HTTP challenge request. It
|
2020-11-16 21:05:55 +03:00
|
|
|
// requires that the automation policy for r.Host has an issuer of type
|
|
|
|
// *certmagic.ACMEManager, or one that is ACME-enabled (GetACMEIssuer()).
|
2019-04-25 22:54:48 +03:00
|
|
|
func (t *TLS) HandleHTTPChallenge(w http.ResponseWriter, r *http.Request) bool {
|
|
|
|
if !certmagic.LooksLikeHTTPChallenge(r) {
|
|
|
|
return false
|
|
|
|
}
|
2020-11-16 21:05:55 +03:00
|
|
|
// try all the issuers until we find the one that initiated the challenge
|
2019-04-25 22:54:48 +03:00
|
|
|
ap := t.getAutomationPolicyForName(r.Host)
|
caddytls: Add support for ZeroSSL; add Caddyfile support for issuers (#3633)
* caddytls: Add support for ZeroSSL; add Caddyfile support for issuers
Configuring issuers explicitly in a Caddyfile is not easily compatible
with existing ACME-specific parameters such as email or acme_ca which
infer the kind of issuer it creates (this is complicated now because
the ZeroSSL issuer wraps the ACME issuer)... oh well, we can revisit
that later if we need to.
New Caddyfile global option:
{
cert_issuer <name> ...
}
Or, alternatively, as a tls subdirective:
tls {
issuer <name> ...
}
For example, to use ZeroSSL with an API key:
{
cert_issuser zerossl API_KEY
}
For now, that still uses ZeroSSL's ACME endpoint; it fetches EAB
credentials for you. You can also provide the EAB credentials directly
just like any other ACME endpoint:
{
cert_issuer acme {
eab KEY_ID MAC_KEY
}
}
All these examples use the new global option (or tls subdirective). You
can still use traditional/existing options with ZeroSSL, since it's
just another ACME endpoint:
{
acme_ca https://acme.zerossl.com/v2/DV90
acme_eab KEY_ID MAC_KEY
}
That's all there is to it. You just can't mix-and-match acme_* options
with cert_issuer, because it becomes confusing/ambiguous/complicated to
merge the settings.
* Fix broken test
This test was asserting buggy behavior, oops - glad this branch both
discovers and fixes the bug at the same time!
* Fix broken test (post-merge)
* Update modules/caddytls/acmeissuer.go
Fix godoc comment
Co-authored-by: Francis Lavoie <lavofr@gmail.com>
* Add support for ZeroSSL's EAB-by-email endpoint
Also transform the ACMEIssuer into ZeroSSLIssuer implicitly if set to
the ZeroSSL endpoint without EAB (the ZeroSSLIssuer is needed to
generate EAB if not already provided); this is now possible with either
an API key or an email address.
* go.mod: Use latest certmagic, acmez, and x/net
* Wrap underlying logic rather than repeating it
Oops, duh
* Form-encode email info into request body for EAB endpoint
Co-authored-by: Francis Lavoie <lavofr@gmail.com>
2020-08-11 17:58:06 +03:00
|
|
|
type acmeCapable interface{ GetACMEIssuer() *ACMEIssuer }
|
2020-11-16 21:05:55 +03:00
|
|
|
for _, iss := range ap.magic.Issuers {
|
|
|
|
if am, ok := iss.(acmeCapable); ok {
|
|
|
|
iss := am.GetACMEIssuer()
|
|
|
|
if certmagic.NewACMEManager(iss.magic, iss.template).HandleHTTPChallenge(w, r) {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
}
|
2020-03-07 09:15:25 +03:00
|
|
|
}
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
// AddAutomationPolicy provisions and adds ap to the list of the app's
|
2020-03-13 20:06:08 +03:00
|
|
|
// automation policies. If an existing automation policy exists that has
|
|
|
|
// fewer hosts in its list than ap does, ap will be inserted before that
|
|
|
|
// other policy (this helps ensure that ap will be prioritized/chosen
|
|
|
|
// over, say, a catch-all policy).
|
2020-03-07 09:15:25 +03:00
|
|
|
func (t *TLS) AddAutomationPolicy(ap *AutomationPolicy) error {
|
|
|
|
if t.Automation == nil {
|
|
|
|
t.Automation = new(AutomationConfig)
|
|
|
|
}
|
2020-03-21 05:25:46 +03:00
|
|
|
err := ap.Provision(t)
|
2020-03-07 09:15:25 +03:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2020-10-22 21:40:23 +03:00
|
|
|
// sort new automation policies just before any other which is a superset
|
|
|
|
// of this one; if we find an existing policy that covers every subject in
|
|
|
|
// ap but less specifically (e.g. a catch-all policy, or one with wildcards
|
|
|
|
// or with fewer subjects), insert ap just before it, otherwise ap would
|
|
|
|
// never be used because the first matching policy is more general
|
|
|
|
for i, existing := range t.Automation.Policies {
|
|
|
|
// first see if existing is superset of ap for all names
|
|
|
|
var otherIsSuperset bool
|
|
|
|
outer:
|
|
|
|
for _, thisSubj := range ap.Subjects {
|
|
|
|
for _, otherSubj := range existing.Subjects {
|
|
|
|
if certmagic.MatchWildcard(thisSubj, otherSubj) {
|
|
|
|
otherIsSuperset = true
|
|
|
|
break outer
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
// if existing AP is a superset or if it contains fewer names (i.e. is
|
|
|
|
// more general), then new AP is more specific, so insert before it
|
|
|
|
if otherIsSuperset || len(existing.Subjects) < len(ap.Subjects) {
|
2020-03-13 20:06:08 +03:00
|
|
|
t.Automation.Policies = append(t.Automation.Policies[:i],
|
2020-03-18 06:00:45 +03:00
|
|
|
append([]*AutomationPolicy{ap}, t.Automation.Policies[i:]...)...)
|
2020-03-13 20:06:08 +03:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
// otherwise just append the new one
|
2020-03-07 09:15:25 +03:00
|
|
|
t.Automation.Policies = append(t.Automation.Policies, ap)
|
|
|
|
return nil
|
2019-04-25 22:54:48 +03:00
|
|
|
}
|
|
|
|
|
2020-03-07 09:15:25 +03:00
|
|
|
func (t *TLS) getConfigForName(name string) *certmagic.Config {
|
2019-04-25 22:54:48 +03:00
|
|
|
ap := t.getAutomationPolicyForName(name)
|
2020-03-07 09:15:25 +03:00
|
|
|
return ap.magic
|
2019-04-25 22:54:48 +03:00
|
|
|
}
|
|
|
|
|
httpcaddyfile, caddytls: Multiple edge case fixes; add tests
- Create two default automation policies; if the TLS app is used in
isolation with the 'automate' certificate loader, it will now use
an internal issuer for internal-only names, and an ACME issuer for
all other names by default.
- If the HTTP Caddyfile adds an 'automate' loader, it now also adds an
automation policy for any names in that loader that do not qualify
for public certificates so that they will be issued internally. (It
might be nice if this wasn't necessary, but the alternative is to
either make auto-HTTPS logic way more complex by scanning the names in
the 'automate' loader, or to have an automation policy without an
issuer switch between default issuer based on the name being issued
a certificate - I think I like the latter option better, right now we
do something kind of like that but at a level above each individual
automation policies, we do that switch only when no automation
policies match, rather than when a policy without an issuer does
match.)
- Set the default LoggerName rather than a LoggerNames with an empty
host value, which is now taken literally rather than as a catch-all.
- hostsFromKeys, the function that gets a list of hosts from server
block keys, no longer returns an empty string in its resulting slice,
ever.
2020-04-08 23:46:44 +03:00
|
|
|
// getAutomationPolicyForName returns the first matching automation policy
|
|
|
|
// for the given subject name. If no matching policy can be found, the
|
|
|
|
// default policy is used, depending on whether the name qualifies for a
|
|
|
|
// public certificate or not.
|
2020-02-14 21:14:52 +03:00
|
|
|
func (t *TLS) getAutomationPolicyForName(name string) *AutomationPolicy {
|
2020-03-07 09:15:25 +03:00
|
|
|
for _, ap := range t.Automation.Policies {
|
2020-03-16 06:22:26 +03:00
|
|
|
if len(ap.Subjects) == 0 {
|
2020-03-07 09:15:25 +03:00
|
|
|
return ap // no host filter is an automatic match
|
|
|
|
}
|
2020-03-16 06:22:26 +03:00
|
|
|
for _, h := range ap.Subjects {
|
2020-03-26 23:01:38 +03:00
|
|
|
if certmagic.MatchWildcard(name, h) {
|
2019-04-25 22:54:48 +03:00
|
|
|
return ap
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2020-04-09 22:09:48 +03:00
|
|
|
if certmagic.SubjectQualifiesForPublicCert(name) || t.Automation.defaultInternalAutomationPolicy == nil {
|
httpcaddyfile, caddytls: Multiple edge case fixes; add tests
- Create two default automation policies; if the TLS app is used in
isolation with the 'automate' certificate loader, it will now use
an internal issuer for internal-only names, and an ACME issuer for
all other names by default.
- If the HTTP Caddyfile adds an 'automate' loader, it now also adds an
automation policy for any names in that loader that do not qualify
for public certificates so that they will be issued internally. (It
might be nice if this wasn't necessary, but the alternative is to
either make auto-HTTPS logic way more complex by scanning the names in
the 'automate' loader, or to have an automation policy without an
issuer switch between default issuer based on the name being issued
a certificate - I think I like the latter option better, right now we
do something kind of like that but at a level above each individual
automation policies, we do that switch only when no automation
policies match, rather than when a policy without an issuer does
match.)
- Set the default LoggerName rather than a LoggerNames with an empty
host value, which is now taken literally rather than as a catch-all.
- hostsFromKeys, the function that gets a list of hosts from server
block keys, no longer returns an empty string in its resulting slice,
ever.
2020-04-08 23:46:44 +03:00
|
|
|
return t.Automation.defaultPublicAutomationPolicy
|
|
|
|
}
|
|
|
|
return t.Automation.defaultInternalAutomationPolicy
|
2019-04-25 22:54:48 +03:00
|
|
|
}
|
|
|
|
|
2019-09-18 01:00:15 +03:00
|
|
|
// AllMatchingCertificates returns the list of all certificates in
|
2019-09-13 20:46:58 +03: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-09 21:05:47 +03:00
|
|
|
}
|
|
|
|
|
2020-07-08 19:59:49 +03:00
|
|
|
// keepStorageClean starts a goroutine that immediately cleans up all
|
|
|
|
// known storage units if it was not recently done, and then runs the
|
|
|
|
// operation at every tick from t.storageCleanTicker.
|
2019-09-18 01:00:15 +03:00
|
|
|
func (t *TLS) keepStorageClean() {
|
2019-09-30 18:07:43 +03:00
|
|
|
t.storageCleanTicker = time.NewTicker(storageCleanInterval)
|
|
|
|
t.storageCleanStop = make(chan struct{})
|
2019-09-18 01:00:15 +03:00
|
|
|
go func() {
|
2020-05-12 20:36:20 +03:00
|
|
|
defer func() {
|
|
|
|
if err := recover(); err != nil {
|
|
|
|
log.Printf("[PANIC] storage cleaner: %v\n%s", err, debug.Stack())
|
|
|
|
}
|
|
|
|
}()
|
2020-07-08 19:59:49 +03:00
|
|
|
t.cleanStorageUnits()
|
2019-09-18 01:00:15 +03:00
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case <-t.storageCleanStop:
|
|
|
|
return
|
|
|
|
case <-t.storageCleanTicker.C:
|
|
|
|
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
|
2020-07-31 00:18:14 +03:00
|
|
|
certmagic.CleanStorage(t.ctx, t.ctx.Storage(), options)
|
2019-09-18 01:00:15 +03:00
|
|
|
|
|
|
|
// then clean each storage defined in ACME automation policies
|
2019-09-30 18:07:43 +03:00
|
|
|
if t.Automation != nil {
|
|
|
|
for _, ap := range t.Automation.Policies {
|
2020-03-07 09:15:25 +03:00
|
|
|
if ap.storage != nil {
|
2020-07-31 00:18:14 +03:00
|
|
|
certmagic.CleanStorage(t.ctx, ap.storage, options)
|
2019-09-18 01:00:15 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
storageClean = time.Now()
|
|
|
|
|
2019-10-28 23:39:37 +03:00
|
|
|
t.logger.Info("cleaned up storage units")
|
2019-09-18 01:00:15 +03:00
|
|
|
}
|
|
|
|
|
2019-04-25 22:54:48 +03:00
|
|
|
// CertificateLoader is a type that can load certificates.
|
2019-06-24 21:16:10 +03:00
|
|
|
// Certificates can optionally be associated with tags.
|
2019-04-25 22:54:48 +03:00
|
|
|
type CertificateLoader interface {
|
2019-06-24 21:16:10 +03:00
|
|
|
LoadCertificates() ([]Certificate, error)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Certificate is a TLS certificate, optionally
|
|
|
|
// associated with arbitrary tags.
|
|
|
|
type Certificate struct {
|
|
|
|
tls.Certificate
|
|
|
|
Tags []string
|
2019-04-25 22:54:48 +03:00
|
|
|
}
|
|
|
|
|
2019-12-10 23:36:46 +03:00
|
|
|
// AutomateLoader is a no-op certificate loader module
|
|
|
|
// that is treated as a special case: it uses this app's
|
|
|
|
// automation features to load certificates for the
|
|
|
|
// list of hostnames, rather than loading certificates
|
|
|
|
// manually.
|
|
|
|
type AutomateLoader []string
|
|
|
|
|
|
|
|
// CaddyModule returns the Caddy module information.
|
|
|
|
func (AutomateLoader) CaddyModule() caddy.ModuleInfo {
|
|
|
|
return caddy.ModuleInfo{
|
|
|
|
ID: "tls.certificates.automate",
|
|
|
|
New: func() caddy.Module { return new(AutomateLoader) },
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-06-05 20:14:39 +03:00
|
|
|
// CertCacheOptions configures the certificate cache.
|
|
|
|
type CertCacheOptions struct {
|
|
|
|
// Maximum number of certificates to allow in the
|
|
|
|
// cache. If reached, certificates will be randomly
|
|
|
|
// evicted to make room for new ones. Default: 0
|
|
|
|
// (no limit).
|
|
|
|
Capacity int `json:"capacity,omitempty"`
|
|
|
|
}
|
|
|
|
|
2019-09-18 01:00:15 +03:00
|
|
|
// Variables related to storage cleaning.
|
|
|
|
var (
|
|
|
|
storageCleanInterval = 12 * time.Hour
|
|
|
|
|
|
|
|
storageClean time.Time
|
|
|
|
storageCleanMu sync.Mutex
|
|
|
|
)
|
|
|
|
|
2019-09-30 18:07:43 +03:00
|
|
|
// Interface guards
|
|
|
|
var (
|
|
|
|
_ caddy.App = (*TLS)(nil)
|
|
|
|
_ caddy.Provisioner = (*TLS)(nil)
|
2020-03-16 06:22:26 +03:00
|
|
|
_ caddy.Validator = (*TLS)(nil)
|
2019-09-30 18:07:43 +03:00
|
|
|
_ caddy.CleanerUpper = (*TLS)(nil)
|
|
|
|
)
|
|
|
|
|
2020-03-07 20:42:50 +03:00
|
|
|
// TODO: This is temporary until the release candidates
|
|
|
|
// (beta 16 changed the storage path for certificates),
|
|
|
|
// after which this function can be deleted
|
|
|
|
func (t *TLS) moveCertificates() error {
|
2020-03-14 04:14:49 +03:00
|
|
|
logger := t.logger.Named("automigrate")
|
2020-03-07 20:42:50 +03:00
|
|
|
|
2020-03-07 21:47:55 +03:00
|
|
|
baseDir := caddy.AppDataDir()
|
2020-03-07 20:42:50 +03:00
|
|
|
|
|
|
|
// if custom storage path was defined, use that instead
|
2020-03-07 21:47:55 +03:00
|
|
|
if fs, ok := t.ctx.Storage().(*certmagic.FileStorage); ok && fs.Path != "" {
|
|
|
|
baseDir = fs.Path
|
2020-03-07 20:42:50 +03:00
|
|
|
}
|
|
|
|
|
2020-03-07 21:47:55 +03:00
|
|
|
oldAcmeDir := filepath.Join(baseDir, "acme")
|
2020-03-07 20:42:50 +03:00
|
|
|
oldAcmeCas, err := ioutil.ReadDir(oldAcmeDir)
|
|
|
|
if err != nil {
|
|
|
|
if os.IsNotExist(err) {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
return fmt.Errorf("listing used ACME CAs: %v", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
// get list of used CAs
|
2020-04-09 00:31:51 +03:00
|
|
|
oldCANames := make([]string, 0, len(oldAcmeCas))
|
2020-03-07 20:42:50 +03:00
|
|
|
for _, fi := range oldAcmeCas {
|
|
|
|
if !fi.IsDir() {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
oldCANames = append(oldCANames, fi.Name())
|
|
|
|
}
|
|
|
|
|
|
|
|
for _, oldCA := range oldCANames {
|
|
|
|
// make new destination path
|
|
|
|
newCAName := oldCA
|
2020-03-07 21:47:55 +03:00
|
|
|
if strings.Contains(oldCA, "api.letsencrypt.org") &&
|
|
|
|
!strings.HasSuffix(oldCA, "-directory") {
|
2020-03-07 20:42:50 +03:00
|
|
|
newCAName += "-directory"
|
|
|
|
}
|
2020-03-07 21:47:55 +03:00
|
|
|
newBaseDir := filepath.Join(baseDir, "certificates", newCAName)
|
2020-03-07 20:42:50 +03:00
|
|
|
err := os.MkdirAll(newBaseDir, 0700)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("making new certs directory: %v", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
// list sites in old path
|
|
|
|
oldAcmeSitesDir := filepath.Join(oldAcmeDir, oldCA, "sites")
|
|
|
|
oldAcmeSites, err := ioutil.ReadDir(oldAcmeSitesDir)
|
|
|
|
if err != nil {
|
|
|
|
if os.IsNotExist(err) {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
return fmt.Errorf("listing sites: %v", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
if len(oldAcmeSites) > 0 {
|
2020-03-14 04:14:49 +03:00
|
|
|
logger.Warn("certificate storage path has changed; attempting one-time auto-migration",
|
2020-03-07 20:42:50 +03:00
|
|
|
zap.String("old_folder", oldAcmeSitesDir),
|
|
|
|
zap.String("new_folder", newBaseDir),
|
|
|
|
zap.String("details", "https://github.com/caddyserver/caddy/issues/2955"))
|
|
|
|
}
|
|
|
|
|
|
|
|
// for each site, move its folder and re-encode its metadata
|
|
|
|
for _, siteInfo := range oldAcmeSites {
|
|
|
|
if !siteInfo.IsDir() {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
// move the folder
|
|
|
|
oldPath := filepath.Join(oldAcmeSitesDir, siteInfo.Name())
|
|
|
|
newPath := filepath.Join(newBaseDir, siteInfo.Name())
|
2020-03-14 04:14:49 +03:00
|
|
|
logger.Info("moving certificate assets",
|
2020-03-07 20:42:50 +03:00
|
|
|
zap.String("ca", oldCA),
|
|
|
|
zap.String("site", siteInfo.Name()),
|
|
|
|
zap.String("destination", newPath))
|
|
|
|
err = os.Rename(oldPath, newPath)
|
|
|
|
if err != nil {
|
2020-03-14 04:14:49 +03:00
|
|
|
logger.Error("failed moving site to new path; skipping",
|
2020-03-07 20:42:50 +03:00
|
|
|
zap.String("old_path", oldPath),
|
|
|
|
zap.String("new_path", newPath),
|
|
|
|
zap.Error(err))
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
// re-encode metadata file
|
|
|
|
metaFilePath := filepath.Join(newPath, siteInfo.Name()+".json")
|
|
|
|
metaContents, err := ioutil.ReadFile(metaFilePath)
|
|
|
|
if err != nil {
|
2020-03-14 04:14:49 +03:00
|
|
|
logger.Error("could not read metadata file",
|
2020-03-07 20:42:50 +03:00
|
|
|
zap.String("filename", metaFilePath),
|
|
|
|
zap.Error(err))
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
if len(metaContents) == 0 {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
cr := certmagic.CertificateResource{
|
|
|
|
SANs: []string{siteInfo.Name()},
|
|
|
|
IssuerData: json.RawMessage(metaContents),
|
|
|
|
}
|
|
|
|
newMeta, err := json.MarshalIndent(cr, "", "\t")
|
|
|
|
if err != nil {
|
2020-03-14 04:14:49 +03:00
|
|
|
logger.Error("encoding new metadata file", zap.Error(err))
|
2020-03-07 20:42:50 +03:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
err = ioutil.WriteFile(metaFilePath, newMeta, 0600)
|
|
|
|
if err != nil {
|
2020-03-14 04:14:49 +03:00
|
|
|
logger.Error("writing new metadata file", zap.Error(err))
|
2020-03-07 20:42:50 +03:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// delete now-empty old sites dir (OK if fails)
|
|
|
|
os.Remove(oldAcmeSitesDir)
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|