Debian Codegraph @

modules/caddytls/tls.go

raw symbols SCIP
1 // Copyright 2015 Matthew Holt and The Caddy Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 package caddytls
16
17 import (
18 "context"
19 "crypto/tls"
20 "encoding/json"
21 "fmt"
22 "log"
23 "net"
24 "net/http"
25 "runtime/debug"
26 "slices"
27 "strings"
28 "sync"
29 "time"
30
31 "github.com/caddyserver/certmagic"
32 "github.com/libdns/libdns"
33 "go.uber.org/zap"
34 "go.uber.org/zap/zapcore"
35
36 "github.com/caddyserver/caddy/v2"
37 "github.com/caddyserver/caddy/v2/internal"
38 "github.com/caddyserver/caddy/v2/modules/caddyevents"
39 )
40
41 func init() {
42 caddy.RegisterModule(TLS{})
43 caddy.RegisterModule(AutomateLoader{})
44 }
45
46 var (
47 certCache *certmagic.Cache
48 certCacheMu sync.RWMutex
49 )
50
51 // TLS provides TLS facilities including certificate
52 // loading and management, client auth, and more.
53 type TLS struct {
54 // Certificates to load into memory for quick recall during
55 // TLS handshakes. Each key is the name of a certificate
56 // loader module.
57 //
58 // The "automate" certificate loader module can be used to
59 // specify a list of subjects that need certificates to be
60 // managed automatically, including subdomains that may
61 // already be covered by a managed wildcard certificate.
62 // The first matching automation policy will be used
63 // to manage automated certificate(s).
64 //
65 // All loaded certificates get pooled
66 // into the same cache and may be used to complete TLS
67 // handshakes for the relevant server names (SNI).
68 // Certificates loaded manually (anything other than
69 // "automate") are not automatically managed and will
70 // have to be refreshed manually before they expire.
71 CertificatesRaw caddy.ModuleMap `json:"certificates,omitempty" caddy:"namespace=tls.certificates"`
72
73 // Configures certificate automation.
74 Automation *AutomationConfig `json:"automation,omitempty"`
75
76 // Configures session ticket ephemeral keys (STEKs).
77 SessionTickets *SessionTicketService `json:"session_tickets,omitempty"`
78
79 // Configures the in-memory certificate cache.
80 Cache *CertCacheOptions `json:"cache,omitempty"`
81
82 // Disables OCSP stapling for manually-managed certificates only.
83 // To configure OCSP stapling for automated certificates, use an
84 // automation policy instead.
85 //
86 // Disabling OCSP stapling puts clients at greater risk, reduces their
87 // privacy, and usually lowers client performance. It is NOT recommended
88 // to disable this unless you are able to justify the costs.
89 //
90 // EXPERIMENTAL. Subject to change.
91 DisableOCSPStapling bool `json:"disable_ocsp_stapling,omitempty"`
92
93 // Disables checks in certmagic that the configured storage is ready
94 // and able to handle writing new content to it. These checks are
95 // intended to prevent information loss (newly issued certificates), but
96 // can be expensive on the storage.
97 //
98 // Disabling these checks should only be done when the storage
99 // can be trusted to have enough capacity and no other problems.
100 //
101 // EXPERIMENTAL. Subject to change.
102 DisableStorageCheck bool `json:"disable_storage_check,omitempty"`
103
104 // Disables the automatic cleanup of the storage backend.
105 // This is useful when TLS is not being used to store certificates
106 // and the user wants run their server in a read-only mode.
107 //
108 // Storage cleaning creates two files: instance.uuid and last_clean.json.
109 // The instance.uuid file is used to identify the instance of Caddy
110 // in a cluster. The last_clean.json file is used to store the last
111 // time the storage was cleaned.
112 //
113 // EXPERIMENTAL. Subject to change.
114 DisableStorageClean bool `json:"disable_storage_clean,omitempty"`
115
116 // Enable Encrypted ClientHello (ECH). ECH protects the server name
117 // (SNI) and other sensitive parameters of a normally-plaintext TLS
118 // ClientHello during a handshake.
119 //
120 // EXPERIMENTAL: Subject to change.
121 EncryptedClientHello *ECH `json:"encrypted_client_hello,omitempty"`
122
123 // The default DNS provider module to use when a DNS module is needed.
124 //
125 // EXPERIMENTAL: Subject to change.
126 DNSRaw json.RawMessage `json:"dns,omitempty" caddy:"namespace=dns.providers inline_key=name"`
127
128 // The default DNS resolvers to use for TLS-related DNS operations, specifically
129 // for ACME DNS challenges and ACME server DNS validations.
130 // If not specified, the system default resolvers will be used.
131 //
132 // EXPERIMENTAL: Subject to change.
133 Resolvers []string `json:"resolvers,omitempty"`
134
135 dns any // technically, it should be any/all of the libdns interfaces (RecordSetter, RecordAppender, etc.)
136 certificateLoaders []CertificateLoader
137 automateNames map[string]struct{}
138 ctx caddy.Context
139 storageCleanTicker *time.Ticker
140 storageCleanStop chan struct{}
141 logger *zap.Logger
142 events *caddyevents.App
143
144 serverNames map[string]serverNameRegistration
145 serverNamesMu *sync.Mutex
146
147 // set of subjects with managed certificates,
148 // and hashes of manually-loaded certificates
149 // (managing's value is an optional issuer key, for distinction)
150 managing, loaded map[string]string
151 }
152
153 // CaddyModule returns the Caddy module information.
154 func (TLS) CaddyModule() caddy.ModuleInfo {
155 return caddy.ModuleInfo{
156 ID: "tls",
157 New: func() caddy.Module { return new(TLS) },
158 }
159 }
160
161 // Provision sets up the configuration for the TLS app.
162 func (t *TLS) Provision(ctx caddy.Context) error {
163 eventsAppIface, err := ctx.App("events")
164 if err != nil {
165 return fmt.Errorf("getting events app: %v", err)
166 }
167 t.events = eventsAppIface.(*caddyevents.App)
168 t.ctx = ctx
169 t.logger = ctx.Logger()
170 repl := caddy.NewReplacer()
171 t.managing, t.loaded = make(map[string]string), make(map[string]string)
172 t.serverNames = make(map[string]serverNameRegistration)
173 t.serverNamesMu = new(sync.Mutex)
174
175 // set up default DNS module, if any, and make sure it implements all the
176 // common libdns interfaces, since it could be used for a variety of things
177 // (do this before provisioning other modules, since they may rely on this)
178 if len(t.DNSRaw) > 0 {
179 dnsMod, err := ctx.LoadModule(t, "DNSRaw")
180 if err != nil {
181 return fmt.Errorf("loading overall DNS provider module: %v", err)
182 }
183 switch dnsMod.(type) {
184 case interface {
185 libdns.RecordAppender
186 libdns.RecordDeleter
187 libdns.RecordGetter
188 libdns.RecordSetter
189 }:
190 default:
191 return fmt.Errorf("DNS module does not implement the most common libdns interfaces: %T", dnsMod)
192 }
193 t.dns = dnsMod
194 }
195
196 // set up a new certificate cache; this (re)loads all certificates
197 cacheOpts := certmagic.CacheOptions{
198 GetConfigForCert: func(cert certmagic.Certificate) (*certmagic.Config, error) {
199 return t.getConfigForName(cert.Names[0]), nil
200 },
201 Logger: t.logger.Named("cache"),
202 }
203 if t.Automation != nil {
204 cacheOpts.OCSPCheckInterval = time.Duration(t.Automation.OCSPCheckInterval)
205 cacheOpts.RenewCheckInterval = time.Duration(t.Automation.RenewCheckInterval)
206 }
207 if t.Cache != nil {
208 cacheOpts.Capacity = t.Cache.Capacity
209 }
210 if cacheOpts.Capacity <= 0 {
211 cacheOpts.Capacity = 10000
212 }
213
214 certCacheMu.Lock()
215 if certCache == nil {
216 certCache = certmagic.NewCache(cacheOpts)
217 } else {
218 certCache.SetOptions(cacheOpts)
219 }
220 certCacheMu.Unlock()
221
222 // certificate loaders
223 val, err := ctx.LoadModule(t, "CertificatesRaw")
224 if err != nil {
225 return fmt.Errorf("loading certificate loader modules: %s", err)
226 }
227 for modName, modIface := range val.(map[string]any) {
228 if modName == "automate" {
229 // special case; these will be loaded in later using our automation facilities,
230 // which we want to avoid doing during provisioning
231 if automateNames, ok := modIface.(*AutomateLoader); ok && automateNames != nil {
232 if t.automateNames == nil {
233 t.automateNames = make(map[string]struct{})
234 }
235 repl := caddy.NewReplacer()
236 for _, sub := range *automateNames {
237 t.automateNames[repl.ReplaceAll(sub, "")] = struct{}{}
238 }
239 } else {
240 return fmt.Errorf("loading certificates with 'automate' requires array of strings, got: %T", modIface)
241 }
242 continue
243 }
244 t.certificateLoaders = append(t.certificateLoaders, modIface.(CertificateLoader))
245 }
246
247 // using the certificate loaders we just initialized, load
248 // manual/static (unmanaged) certificates - we do this in
249 // provision so that other apps (such as http) can know which
250 // certificates have been manually loaded, and also so that
251 // commands like validate can be a better test
252 certCacheMu.RLock()
253 magic := certmagic.New(certCache, certmagic.Config{
254 Storage: ctx.Storage(),
255 Logger: t.logger,
256 OnEvent: t.onEvent,
257 OCSP: certmagic.OCSPConfig{
258 DisableStapling: t.DisableOCSPStapling,
259 },
260 DisableStorageCheck: t.DisableStorageCheck,
261 })
262 certCacheMu.RUnlock()
263 for _, loader := range t.certificateLoaders {
264 certs, err := loader.LoadCertificates()
265 if err != nil {
266 return fmt.Errorf("loading certificates: %v", err)
267 }
268 for _, cert := range certs {
269 hash, err := magic.CacheUnmanagedTLSCertificate(ctx, cert.Certificate, cert.Tags)
270 if err != nil {
271 return fmt.Errorf("caching unmanaged certificate: %v", err)
272 }
273 t.loaded[hash] = ""
274 }
275 }
276
277 // on-demand permission module
278 if t.Automation != nil && t.Automation.OnDemand != nil && t.Automation.OnDemand.PermissionRaw != nil {
279 if t.Automation.OnDemand.Ask != "" {
280 return fmt.Errorf("on-demand TLS config conflict: both 'ask' endpoint and a 'permission' module are specified; 'ask' is deprecated, so use only the permission module")
281 }
282 val, err := ctx.LoadModule(t.Automation.OnDemand, "PermissionRaw")
283 if err != nil {
284 return fmt.Errorf("loading on-demand TLS permission module: %v", err)
285 }
286 t.Automation.OnDemand.permission = val.(OnDemandPermission)
287 }
288
289 // automation/management policies
290 if t.Automation == nil {
291 t.Automation = new(AutomationConfig)
292 }
293 t.Automation.defaultPublicAutomationPolicy = new(AutomationPolicy)
294 err = t.Automation.defaultPublicAutomationPolicy.Provision(t)
295 if err != nil {
296 return fmt.Errorf("provisioning default public automation policy: %v", err)
297 }
298 for n := range t.automateNames {
299 // if any names specified by the "automate" loader do not qualify for a public
300 // certificate, we should initialize a default internal automation policy
301 // (but we don't want to do this unnecessarily, since it may prompt for password!)
302 if certmagic.SubjectQualifiesForPublicCert(n) {
303 continue
304 }
305 t.Automation.defaultInternalAutomationPolicy = &AutomationPolicy{
306 IssuersRaw: []json.RawMessage{json.RawMessage(`{"module":"internal"}`)},
307 }
308 err = t.Automation.defaultInternalAutomationPolicy.Provision(t)
309 if err != nil {
310 return fmt.Errorf("provisioning default internal automation policy: %v", err)
311 }
312 break
313 }
314 for i, ap := range t.Automation.Policies {
315 err := ap.Provision(t)
316 if err != nil {
317 return fmt.Errorf("provisioning automation policy %d: %v", i, err)
318 }
319 }
320
321 // run replacer on ask URL (for environment variables) -- return errors to prevent surprises (#5036)
322 if t.Automation != nil && t.Automation.OnDemand != nil && t.Automation.OnDemand.Ask != "" {
323 t.Automation.OnDemand.Ask, err = repl.ReplaceOrErr(t.Automation.OnDemand.Ask, true, true)
324 if err != nil {
325 return fmt.Errorf("preparing 'ask' endpoint: %v", err)
326 }
327 perm := PermissionByHTTP{
328 Endpoint: t.Automation.OnDemand.Ask,
329 }
330 if err := perm.Provision(ctx); err != nil {
331 return fmt.Errorf("provisioning 'ask' module: %v", err)
332 }
333 t.Automation.OnDemand.permission = perm
334 }
335
336 // session ticket ephemeral keys (STEK) service and provider
337 if t.SessionTickets != nil {
338 err := t.SessionTickets.provision(ctx)
339 if err != nil {
340 return fmt.Errorf("provisioning session tickets configuration: %v", err)
341 }
342 }
343
344 // ECH (Encrypted ClientHello) initialization
345 if t.EncryptedClientHello != nil {
346 outerNames, err := t.EncryptedClientHello.Provision(ctx)
347 if err != nil {
348 return fmt.Errorf("provisioning Encrypted ClientHello components: %v", err)
349 }
350
351 // outer names should have certificates to reduce client brittleness
352 for _, outerName := range outerNames {
353 if outerName == "" {
354 continue
355 }
356 if !t.HasCertificateForSubject(outerName) {
357 if t.automateNames == nil {
358 t.automateNames = make(map[string]struct{})
359 }
360 t.automateNames[outerName] = struct{}{}
361 }
362 }
363 }
364
365 return nil
366 }
367
368 // Validate validates t's configuration.
369 func (t *TLS) Validate() error {
370 if t.Automation != nil {
371 // ensure that host aren't repeated; since only the first
372 // automation policy is used, repeating a host in the lists
373 // isn't useful and is probably a mistake; same for two
374 // catch-all/default policies
375 var hasDefault bool
376 hostSet := make(map[string]int)
377 for i, ap := range t.Automation.Policies {
378 if len(ap.subjects) == 0 {
379 if hasDefault {
380 return fmt.Errorf("automation policy %d is the second policy that acts as default/catch-all, but will never be used", i)
381 }
382 hasDefault = true
383 }
384 for _, h := range ap.subjects {
385 if first, ok := hostSet[h]; ok {
386 return fmt.Errorf("automation policy %d: cannot apply more than one automation policy to host: %s (first match in policy %d)", i, h, first)
387 }
388 hostSet[h] = i
389 }
390 }
391 }
392 if t.Cache != nil {
393 if t.Cache.Capacity < 0 {
394 return fmt.Errorf("cache capacity must be >= 0")
395 }
396 }
397 return nil
398 }
399
400 // Start activates the TLS module.
401 func (t *TLS) Start() error {
402 // warn if on-demand TLS is enabled but no restrictions are in place
403 if t.Automation.OnDemand == nil || (t.Automation.OnDemand.Ask == "" && t.Automation.OnDemand.permission == nil) {
404 for _, ap := range t.Automation.Policies {
405 if ap.OnDemand && ap.isWildcardOrDefault() {
406 if c := t.logger.Check(zapcore.WarnLevel, "YOUR SERVER MAY BE VULNERABLE TO ABUSE: on-demand TLS is enabled, but no protections are in place"); c != nil {
407 c.Write(zap.String("docs", "https://caddyserver.com/docs/automatic-https#on-demand-tls"))
408 }
409 break
410 }
411 }
412 }
413
414 // now that we are running, and all manual certificates have
415 // been loaded, time to load the automated/managed certificates
416 err := t.Manage(t.automateNames)
417 if err != nil {
418 return fmt.Errorf("automate: managing %v: %v", t.automateNames, err)
419 }
420
421 if t.EncryptedClientHello != nil {
422 echLogger := t.logger.Named("ech")
423
424 // publish ECH configs in the background; does not need to block
425 // server startup, as it could take a while; then keep keys rotated
426 go func() {
427 // publish immediately first
428 if err := t.publishECHConfigs(echLogger); err != nil {
429 echLogger.Error("publication(s) failed", zap.Error(err))
430 }
431
432 // then every so often, rotate and publish if needed
433 // (both of these functions only do something if needed)
434 for {
435 select {
436 case <-time.After(1 * time.Hour):
437 // ensure old keys are rotated out
438 t.EncryptedClientHello.configsMu.Lock()
439 err = t.EncryptedClientHello.rotateECHKeys(t.ctx, echLogger, false)
440 t.EncryptedClientHello.configsMu.Unlock()
441 if err != nil {
442 echLogger.Error("rotating ECH configs failed", zap.Error(err))
443 continue
444 }
445 err := t.publishECHConfigs(echLogger)
446 if err != nil {
447 echLogger.Error("publication(s) failed", zap.Error(err))
448 }
449 case <-t.ctx.Done():
450 return
451 }
452 }
453 }()
454 }
455
456 if !t.DisableStorageClean {
457 // start the storage cleaner goroutine and ticker,
458 // which cleans out expired certificates and more
459 t.keepStorageClean()
460 }
461
462 return nil
463 }
464
465 // Stop stops the TLS module and cleans up any allocations.
466 func (t *TLS) Stop() error {
467 // stop the storage cleaner goroutine and ticker
468 if t.storageCleanStop != nil {
469 close(t.storageCleanStop)
470 }
471 if t.storageCleanTicker != nil {
472 t.storageCleanTicker.Stop()
473 }
474 return nil
475 }
476
477 // Cleanup frees up resources allocated during Provision.
478 func (t *TLS) Cleanup() error {
479 // stop the session ticket rotation goroutine
480 if t.SessionTickets != nil {
481 t.SessionTickets.stop()
482 }
483
484 // if a new TLS app was loaded, remove certificates from the cache that are no longer
485 // being managed or loaded by the new config; if there is no more TLS app running,
486 // then stop cert maintenance and let the cert cache be GC'ed
487 if nextTLS, err := caddy.ActiveContext().AppIfConfigured("tls"); err == nil && nextTLS != nil {
488 nextTLSApp := nextTLS.(*TLS)
489
490 // compute which certificates were managed or loaded into the cert cache by this
491 // app instance (which is being stopped) that are not managed or loaded by the
492 // new app instance (which just started), and remove them from the cache
493 var noLongerManaged []certmagic.SubjectIssuer
494 var noLongerLoaded []string
495 reManage := make(map[string]struct{})
496 for subj, currentIssuerKey := range t.managing {
497 // It's a bit nuanced: managed certs can sometimes be different enough that we have to
498 // swap them out for a different one, even if they are for the same subject/domain.
499 // We consider "private" certs (internal CA/locally-trusted/etc) to be significantly
500 // distinct from "public" certs (production CAs/globally-trusted/etc) because of the
501 // implications when it comes to actual deployments: switching between an internal CA
502 // and a production CA, for example, is quite significant. Switching from one public CA
503 // to another, however, is not, and for our purposes we consider those to be the same.
504 // Anyway, if the next TLS app does not manage a cert for this name at all, definitely
505 // remove it from the cache. But if it does, and it's not the same kind of issuer/CA
506 // as we have, also remove it, so that it can swap it out for the right one.
507 if nextIssuerKey, ok := nextTLSApp.managing[subj]; !ok || nextIssuerKey != currentIssuerKey {
508 // next app is not managing a cert for this domain at all or is using a different issuer, so remove it
509 noLongerManaged = append(noLongerManaged, certmagic.SubjectIssuer{Subject: subj, IssuerKey: currentIssuerKey})
510
511 // then, if the next app is managing a cert for this name, but with a different issuer, re-manage it
512 if ok && nextIssuerKey != currentIssuerKey {
513 reManage[subj] = struct{}{}
514 }
515 }
516 }
517 for hash := range t.loaded {
518 if _, ok := nextTLSApp.loaded[hash]; !ok {
519 noLongerLoaded = append(noLongerLoaded, hash)
520 }
521 }
522
523 // remove the certs
524 certCacheMu.RLock()
525 certCache.RemoveManaged(noLongerManaged)
526 certCache.Remove(noLongerLoaded)
527 certCacheMu.RUnlock()
528
529 // give the new TLS app a "kick" to manage certs that it is configured for
530 // with its own configuration instead of the one we just evicted
531 if err := nextTLSApp.Manage(reManage); err != nil {
532 if c := t.logger.Check(zapcore.ErrorLevel, "re-managing unloaded certificates with new config"); c != nil {
533 c.Write(
534 zap.Strings("subjects", internal.MaxSizeSubjectsListForLog(reManage, 1000)),
535 zap.Error(err),
536 )
537 }
538 }
539 } else {
540 // no more TLS app running, so delete in-memory cert cache, if it was created yet
541 certCacheMu.RLock()
542 hasCache := certCache != nil
543 certCacheMu.RUnlock()
544 if hasCache {
545 certCache.Stop()
546 certCacheMu.Lock()
547 certCache = nil
548 certCacheMu.Unlock()
549 }
550 }
551
552 return nil
553 }
554
555 // Manage immediately begins managing subjects according to the
556 // matching automation policy. The subjects are given in a map
557 // to prevent duplication and also because quick lookups are
558 // needed to assess wildcard coverage, if any, depending on
559 // certain config parameters (with lots of subjects, computing
560 // wildcard coverage over a slice can be highly inefficient).
561 func (t *TLS) Manage(subjects map[string]struct{}) error {
562 // for a large number of names, we can be more memory-efficient
563 // by making only one certmagic.Config for all the names that
564 // use that config, rather than calling ManageAsync once for
565 // every name; so first, bin names by AutomationPolicy
566 policyToNames := make(map[*AutomationPolicy][]string)
567 for subj := range subjects {
568 ap := t.getAutomationPolicyForName(subj)
569 // by default, if a wildcard that covers the subj is also being
570 // managed, either by a previous call to Manage or by this one,
571 // prefer using that over individual certs for its subdomains;
572 // but users can disable this and force getting a certificate for
573 // subdomains by adding the name to the 'automate' cert loader
574 if t.managingWildcardFor(subj, subjects) {
575 if _, ok := t.automateNames[subj]; !ok {
576 continue
577 }
578 }
579 policyToNames[ap] = append(policyToNames[ap], subj)
580 }
581
582 // now that names are grouped by policy, we can simply make one
583 // certmagic.Config for each (potentially large) group of names
584 // and call ManageAsync just once for the whole batch
585 for ap, names := range policyToNames {
586 err := ap.magic.ManageAsync(t.ctx.Context, names)
587 if err != nil {
588 const maxNamesToDisplay = 100
589 if len(names) > maxNamesToDisplay {
590 names = append(names[:maxNamesToDisplay], fmt.Sprintf("(and %d more...)", len(names)-maxNamesToDisplay))
591 }
592 return fmt.Errorf("automate: manage %v: %v", names, err)
593 }
594 for _, name := range names {
595 // certs that are issued solely by our internal issuer are a little bit of
596 // a special case: if you have an initial config that manages example.com
597 // using internal CA, then after testing it you switch to a production CA,
598 // you wouldn't want to keep using the same self-signed cert, obviously;
599 // so we differentiate these by associating the subject with its issuer key;
600 // we do this because CertMagic has no notion of "InternalIssuer" like we
601 // do, so we have to do this logic ourselves
602 var issuerKey string
603 if len(ap.Issuers) == 1 {
604 if intIss, ok := ap.Issuers[0].(*InternalIssuer); ok && intIss != nil {
605 issuerKey = intIss.IssuerKey()
606 }
607 }
608 t.managing[name] = issuerKey
609 }
610 }
611
612 return nil
613 }
614
615 // managingWildcardFor returns true if the app is managing a certificate that covers that
616 // subject name (including consideration of wildcards), either from its internal list of
617 // names that it IS managing certs for, from the otherSubjsToManage which includes names
618 // that WILL be managed, or from names configured in the 'automate' loader.
619 func (t *TLS) managingWildcardFor(subj string, otherSubjsToManage map[string]struct{}) bool {
620 // TODO: we could also consider manually-loaded certs using t.HasCertificateForSubject(),
621 // but that does not account for how manually-loaded certs may be restricted as to which
622 // hostnames or ClientHellos they can be used with by tags, etc; I don't *think* anyone
623 // necessarily wants this anyway, but I thought I'd note this here for now (if we did
624 // consider manually-loaded certs, we'd probably want to rename the method since it
625 // wouldn't be just about managed certs anymore)
626
627 // IP addresses must match exactly
628 if ip := net.ParseIP(subj); ip != nil {
629 _, managing := t.managing[subj]
630 return managing
631 }
632
633 // replace labels of the domain with wildcards until we get a match from names
634 // already being managed, those about to be managed in this batch, or those
635 // configured for automation
636 labels := strings.Split(subj, ".")
637 for i := range labels {
638 if labels[i] == "*" {
639 continue
640 }
641 labels[i] = "*"
642 candidate := strings.Join(labels, ".")
643 if _, ok := t.managing[candidate]; ok {
644 return true
645 }
646 if _, ok := otherSubjsToManage[candidate]; ok {
647 return true
648 }
649 if _, ok := t.automateNames[candidate]; ok {
650 return true
651 }
652 }
653
654 return false
655 }
656
657 // RegisterServerNames registers the provided DNS names with the TLS app and
658 // associates them with the given HTTPS RR ALPN values, if any. This is
659 // currently used to auto-publish Encrypted ClientHello (ECH) configurations,
660 // if enabled. Use of this function by apps using the TLS app removes the need
661 // for the user to redundantly specify domain names in their configuration.
662 // This function separates hostname and port, keeping only the hostname, and
663 // filters IP addresses which can't be used with ECH.
664 //
665 // EXPERIMENTAL: This function and its semantics/behavior are subject to change.
666 func (t *TLS) RegisterServerNames(dnsNames, alpnValues []string) {
667 t.serverNamesMu.Lock()
668 defer t.serverNamesMu.Unlock()
669
670 for _, name := range dnsNames {
671 host, _, err := net.SplitHostPort(name)
672 if err != nil {
673 host = name
674 }
675 host = strings.ToLower(strings.TrimSpace(host))
676 if host == "" || certmagic.SubjectIsIP(host) {
677 continue
678 }
679
680 registration := t.serverNames[host]
681
682 if len(alpnValues) == 0 {
683 t.serverNames[host] = registration
684 continue
685 }
686
687 if registration.alpnValues == nil {
688 registration.alpnValues = make(map[string]struct{}, len(alpnValues))
689 }
690 for _, alpn := range alpnValues {
691 if alpn == "" {
692 continue
693 }
694 registration.alpnValues[alpn] = struct{}{}
695 }
696 t.serverNames[host] = registration
697 }
698 }
699
700 func (t *TLS) alpnValuesForServerNames(dnsNames []string) map[string][]string {
701 t.serverNamesMu.Lock()
702 defer t.serverNamesMu.Unlock()
703
704 result := make(map[string][]string, len(dnsNames))
705 for _, name := range dnsNames {
706 host, _, err := net.SplitHostPort(name)
707 if err != nil {
708 host = name
709 }
710 host = strings.ToLower(strings.TrimSpace(host))
711 if host == "" {
712 continue
713 }
714
715 registration, ok := t.serverNames[host]
716 if !ok || len(registration.alpnValues) == 0 {
717 continue
718 }
719 result[host] = OrderedHTTPSRRALPN(registration.alpnValues)
720 }
721
722 return result
723 }
724
725 // OrderedHTTPSRRALPN returns the HTTPS RR ALPN values in preferred order.
726 func OrderedHTTPSRRALPN(alpnSet map[string]struct{}) []string {
727 if len(alpnSet) == 0 {
728 return nil
729 }
730
731 knownOrder := append([]string{"h3"}, defaultALPN...)
732 ordered := make([]string, 0, len(alpnSet))
733 seen := make(map[string]struct{}, len(alpnSet))
734
735 for _, alpn := range knownOrder {
736 if _, ok := alpnSet[alpn]; ok {
737 ordered = append(ordered, alpn)
738 seen[alpn] = struct{}{}
739 }
740 }
741
742 if len(ordered) == len(alpnSet) {
743 return ordered
744 }
745
746 var remaining []string
747 for alpn := range alpnSet {
748 if _, ok := seen[alpn]; ok {
749 continue
750 }
751 remaining = append(remaining, alpn)
752 }
753 slices.Sort(remaining)
754
755 return append(ordered, remaining...)
756 }
757
758 type serverNameRegistration struct {
759 alpnValues map[string]struct{}
760 }
761
762 // HandleHTTPChallenge ensures that the ACME HTTP challenge or ZeroSSL HTTP
763 // validation request is handled for the certificate named by r.Host, if it
764 // is an HTTP challenge request. It requires that the automation policy for
765 // r.Host has an issuer that implements GetACMEIssuer() or is a *ZeroSSLIssuer.
766 func (t *TLS) HandleHTTPChallenge(w http.ResponseWriter, r *http.Request) bool {
767 acmeChallenge := certmagic.LooksLikeHTTPChallenge(r)
768 zerosslValidation := certmagic.LooksLikeZeroSSLHTTPValidation(r)
769
770 // no-op if it's not an ACME challenge request
771 if !acmeChallenge && !zerosslValidation {
772 return false
773 }
774
775 // try all the issuers until we find the one that initiated the challenge
776 ap := t.getAutomationPolicyForName(r.Host)
777
778 if acmeChallenge {
779 type acmeCapable interface{ GetACMEIssuer() *ACMEIssuer }
780
781 for _, iss := range ap.magic.Issuers {
782 if acmeIssuer, ok := iss.(acmeCapable); ok {
783 if acmeIssuer.GetACMEIssuer().issuer.HandleHTTPChallenge(w, r) {
784 return true
785 }
786 }
787 }
788
789 // it's possible another server in this process initiated the challenge;
790 // users have requested that Caddy only handle HTTP challenges it initiated,
791 // so that users can proxy the others through to their backends; but we
792 // might not have an automation policy for all identifiers that are trying
793 // to get certificates (e.g. the admin endpoint), so we do this manual check
794 if challenge, ok := certmagic.GetACMEChallenge(r.Host); ok {
795 return certmagic.SolveHTTPChallenge(t.logger, w, r, challenge.Challenge)
796 }
797 } else if zerosslValidation {
798 for _, iss := range ap.magic.Issuers {
799 if ziss, ok := iss.(*ZeroSSLIssuer); ok {
800 if ziss.issuer.HandleZeroSSLHTTPValidation(w, r) {
801 return true
802 }
803 }
804 }
805 }
806
807 return false
808 }
809
810 // AddAutomationPolicy provisions and adds ap to the list of the app's
811 // automation policies. If an existing automation policy exists that has
812 // fewer hosts in its list than ap does, ap will be inserted before that
813 // other policy (this helps ensure that ap will be prioritized/chosen
814 // over, say, a catch-all policy).
815 func (t *TLS) AddAutomationPolicy(ap *AutomationPolicy) error {
816 if t.Automation == nil {
817 t.Automation = new(AutomationConfig)
818 }
819 err := ap.Provision(t)
820 if err != nil {
821 return err
822 }
823 // sort new automation policies just before any other which is a superset
824 // of this one; if we find an existing policy that covers every subject in
825 // ap but less specifically (e.g. a catch-all policy, or one with wildcards
826 // or with fewer subjects), insert ap just before it, otherwise ap would
827 // never be used because the first matching policy is more general
828 for i, existing := range t.Automation.Policies {
829 // first see if existing is superset of ap for all names
830 var otherIsSuperset bool
831 outer:
832 for _, thisSubj := range ap.subjects {
833 for _, otherSubj := range existing.subjects {
834 if certmagic.MatchWildcard(thisSubj, otherSubj) {
835 otherIsSuperset = true
836 break outer
837 }
838 }
839 }
840 // if existing AP is a superset or if it contains fewer names (i.e. is
841 // more general), then new AP is more specific, so insert before it
842 if otherIsSuperset || len(existing.SubjectsRaw) < len(ap.SubjectsRaw) {
843 t.Automation.Policies = append(t.Automation.Policies[:i],
844 append([]*AutomationPolicy{ap}, t.Automation.Policies[i:]...)...)
845 return nil
846 }
847 }
848 // otherwise just append the new one
849 t.Automation.Policies = append(t.Automation.Policies, ap)
850 return nil
851 }
852
853 func (t *TLS) getConfigForName(name string) *certmagic.Config {
854 ap := t.getAutomationPolicyForName(name)
855 return ap.magic
856 }
857
858 // getAutomationPolicyForName returns the first matching automation policy
859 // for the given subject name. If no matching policy can be found, the
860 // default policy is used, depending on whether the name qualifies for a
861 // public certificate or not.
862 func (t *TLS) getAutomationPolicyForName(name string) *AutomationPolicy {
863 for _, ap := range t.Automation.Policies {
864 if len(ap.subjects) == 0 {
865 return ap // no host filter is an automatic match
866 }
867 for _, h := range ap.subjects {
868 if certmagic.MatchWildcard(name, h) {
869 return ap
870 }
871 }
872 }
873 if certmagic.SubjectQualifiesForPublicCert(name) || t.Automation.defaultInternalAutomationPolicy == nil {
874 return t.Automation.defaultPublicAutomationPolicy
875 }
876 return t.Automation.defaultInternalAutomationPolicy
877 }
878
879 // AllMatchingCertificates returns the list of all certificates in
880 // the cache which could be used to satisfy the given SAN.
881 func AllMatchingCertificates(san string) []certmagic.Certificate {
882 certCacheMu.RLock()
883 defer certCacheMu.RUnlock()
884 return certCache.AllMatchingCertificates(san)
885 }
886
887 func (t *TLS) HasCertificateForSubject(subject string) bool {
888 certCacheMu.RLock()
889 allMatchingCerts := certCache.AllMatchingCertificates(subject)
890 certCacheMu.RUnlock()
891 for _, cert := range allMatchingCerts {
892 // check if the cert is manually loaded by this config
893 if _, ok := t.loaded[cert.Hash()]; ok {
894 return true
895 }
896 // check if the cert is automatically managed by this config
897 for _, name := range cert.Names {
898 if _, ok := t.managing[name]; ok {
899 return true
900 }
901 }
902 }
903 return false
904 }
905
906 // keepStorageClean starts a goroutine that immediately cleans up all
907 // known storage units if it was not recently done, and then runs the
908 // operation at every tick from t.storageCleanTicker.
909 func (t *TLS) keepStorageClean() {
910 t.storageCleanTicker = time.NewTicker(t.storageCleanInterval())
911 t.storageCleanStop = make(chan struct{})
912 go func() {
913 defer func() {
914 if err := recover(); err != nil {
915 log.Printf("[PANIC] storage cleaner: %v\n%s", err, debug.Stack())
916 }
917 }()
918 t.cleanStorageUnits()
919 for {
920 select {
921 case <-t.storageCleanStop:
922 return
923 case <-t.storageCleanTicker.C:
924 t.cleanStorageUnits()
925 }
926 }
927 }()
928 }
929
930 func (t *TLS) cleanStorageUnits() {
931 storageCleanMu.Lock()
932 defer storageCleanMu.Unlock()
933
934 // TODO: This check might not be needed anymore now that CertMagic syncs
935 // and throttles storage cleaning globally across the cluster.
936 // The original comment below might be outdated:
937 //
938 // If storage was cleaned recently, don't do it again for now. Although the ticker
939 // calling this function drops missed ticks for us, config reloads discard the old
940 // ticker and replace it with a new one, possibly invoking a cleaning to happen again
941 // too soon. (We divide the interval by 2 because the actual cleaning takes non-zero
942 // time, and we don't want to skip cleanings if we don't have to; whereas if a cleaning
943 // took most of the interval, we'd probably want to skip the next one so we aren't
944 // constantly cleaning. This allows cleanings to take up to half the interval's
945 // duration before we decide to skip the next one.)
946 if !storageClean.IsZero() && time.Since(storageClean) < t.storageCleanInterval()/2 {
947 return
948 }
949
950 id, err := caddy.InstanceID()
951 if err != nil {
952 if c := t.logger.Check(zapcore.WarnLevel, "unable to get instance ID; storage clean stamps will be incomplete"); c != nil {
953 c.Write(zap.Error(err))
954 }
955 }
956 options := certmagic.CleanStorageOptions{
957 Logger: t.logger,
958 InstanceID: id.String(),
959 Interval: t.storageCleanInterval(),
960 OCSPStaples: true,
961 ExpiredCerts: true,
962 ExpiredCertGracePeriod: 24 * time.Hour * 14,
963 }
964
965 // start with the default/global storage
966 err = certmagic.CleanStorage(t.ctx, t.ctx.Storage(), options)
967 if err != nil {
968 // probably don't want to return early, since we should still
969 // see if any other storages can get cleaned up
970 if c := t.logger.Check(zapcore.ErrorLevel, "could not clean default/global storage"); c != nil {
971 c.Write(zap.Error(err))
972 }
973 }
974
975 // then clean each storage defined in ACME automation policies
976 if t.Automation != nil {
977 for _, ap := range t.Automation.Policies {
978 if ap.storage == nil {
979 continue
980 }
981 if err := certmagic.CleanStorage(t.ctx, ap.storage, options); err != nil {
982 if c := t.logger.Check(zapcore.ErrorLevel, "could not clean storage configured in automation policy"); c != nil {
983 c.Write(zap.Error(err))
984 }
985 }
986 }
987 }
988
989 // remember last time storage was finished cleaning
990 storageClean = time.Now()
991
992 t.logger.Info("finished cleaning storage units")
993 }
994
995 func (t *TLS) storageCleanInterval() time.Duration {
996 if t.Automation != nil && t.Automation.StorageCleanInterval > 0 {
997 return time.Duration(t.Automation.StorageCleanInterval)
998 }
999 return defaultStorageCleanInterval
1000 }
1001
1002 // onEvent translates CertMagic events into Caddy events then dispatches them.
1003 func (t *TLS) onEvent(ctx context.Context, eventName string, data map[string]any) error {
1004 evt := t.events.Emit(t.ctx, eventName, data)
1005 return evt.Aborted
1006 }
1007
1008 // CertificateLoader is a type that can load certificates.
1009 // Certificates can optionally be associated with tags.
1010 type CertificateLoader interface {
1011 LoadCertificates() ([]Certificate, error)
1012 }
1013
1014 // Certificate is a TLS certificate, optionally
1015 // associated with arbitrary tags.
1016 type Certificate struct {
1017 tls.Certificate
1018 Tags []string
1019 }
1020
1021 // AutomateLoader will automatically manage certificates for the names in the
1022 // list, including obtaining and renewing certificates. Automated certificates
1023 // are managed according to their matching automation policy, configured
1024 // elsewhere in this app.
1025 //
1026 // Technically, this is a no-op certificate loader module that is treated as
1027 // a special case: it uses this app's automation features to load certificates
1028 // for the list of hostnames, rather than loading certificates manually. But
1029 // the end result is the same: certificates for these subject names will be
1030 // loaded into the in-memory cache and may then be used.
1031 type AutomateLoader []string
1032
1033 // CaddyModule returns the Caddy module information.
1034 func (AutomateLoader) CaddyModule() caddy.ModuleInfo {
1035 return caddy.ModuleInfo{
1036 ID: "tls.certificates.automate",
1037 New: func() caddy.Module { return new(AutomateLoader) },
1038 }
1039 }
1040
1041 // CertCacheOptions configures the certificate cache.
1042 type CertCacheOptions struct {
1043 // Maximum number of certificates to allow in the
1044 // cache. If reached, certificates will be randomly
1045 // evicted to make room for new ones. Default: 10,000
1046 Capacity int `json:"capacity,omitempty"`
1047 }
1048
1049 // Variables related to storage cleaning.
1050 var (
1051 defaultStorageCleanInterval = 24 * time.Hour
1052
1053 storageClean time.Time
1054 storageCleanMu sync.Mutex
1055 )
1056
1057 // Interface guards
1058 var (
1059 _ caddy.App = (*TLS)(nil)
1060 _ caddy.Provisioner = (*TLS)(nil)
1061 _ caddy.Validator = (*TLS)(nil)
1062 _ caddy.CleanerUpper = (*TLS)(nil)
1063 )