Debian Codegraph @

modules/caddytls/connpolicy.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 "crypto/x509"
21 "encoding/base64"
22 "encoding/json"
23 "encoding/pem"
24 "fmt"
25 "io"
26 "os"
27 "reflect"
28 "slices"
29 "strings"
30
31 "github.com/mholt/acmez/v3"
32 "go.uber.org/zap"
33 "go.uber.org/zap/zapcore"
34
35 "github.com/caddyserver/caddy/v2"
36 "github.com/caddyserver/caddy/v2/caddyconfig"
37 "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile"
38 )
39
40 func init() {
41 caddy.RegisterModule(LeafCertClientAuth{})
42 }
43
44 // ConnectionPolicies govern the establishment of TLS connections. It is
45 // an ordered group of connection policies; the first matching policy will
46 // be used to configure TLS connections at handshake-time.
47 type ConnectionPolicies []*ConnectionPolicy
48
49 // Provision sets up each connection policy. It should be called
50 // during the Validate() phase, after the TLS app (if any) is
51 // already set up.
52 func (cp ConnectionPolicies) Provision(ctx caddy.Context) error {
53 for i, pol := range cp {
54 // matchers
55 mods, err := ctx.LoadModule(pol, "MatchersRaw")
56 if err != nil {
57 return fmt.Errorf("loading handshake matchers: %v", err)
58 }
59 for _, modIface := range mods.(map[string]any) {
60 cp[i].matchers = append(cp[i].matchers, modIface.(ConnectionMatcher))
61 }
62
63 // enable HTTP/2 by default
64 if pol.ALPN == nil {
65 pol.ALPN = append(pol.ALPN, defaultALPN...)
66 }
67
68 // pre-build standard TLS config so we don't have to at handshake-time
69 err = pol.buildStandardTLSConfig(ctx)
70 if err != nil {
71 return fmt.Errorf("connection policy %d: building standard TLS config: %s", i, err)
72 }
73
74 if pol.ClientAuthentication != nil && len(pol.ClientAuthentication.VerifiersRaw) > 0 {
75 clientCertValidations, err := ctx.LoadModule(pol.ClientAuthentication, "VerifiersRaw")
76 if err != nil {
77 return fmt.Errorf("loading client cert verifiers: %v", err)
78 }
79 for _, validator := range clientCertValidations.([]any) {
80 cp[i].ClientAuthentication.verifiers = append(cp[i].ClientAuthentication.verifiers, validator.(ClientCertificateVerifier))
81 }
82 }
83
84 if len(pol.HandshakeContextRaw) > 0 {
85 modIface, err := ctx.LoadModule(pol, "HandshakeContextRaw")
86 if err != nil {
87 return fmt.Errorf("loading handshake context module: %v", err)
88 }
89 cp[i].handshakeContext = modIface.(HandshakeContext)
90 }
91 }
92
93 return nil
94 }
95
96 // TLSConfig returns a standard-lib-compatible TLS configuration which
97 // selects the first matching policy based on the ClientHello.
98 func (cp ConnectionPolicies) TLSConfig(ctx caddy.Context) *tls.Config {
99 // using ServerName to match policies is extremely common, especially in configs
100 // with lots and lots of different policies; we can fast-track those by indexing
101 // them by SNI, so we don't have to iterate potentially thousands of policies
102 // (TODO: this map does not account for wildcards, see if this is a problem in practice? look for reports of high connection latency with wildcard certs but low latency for non-wildcards in multi-thousand-cert deployments)
103 indexedBySNI := make(map[string]ConnectionPolicies)
104 if len(cp) > 30 {
105 for _, p := range cp {
106 for _, m := range p.matchers {
107 if sni, ok := m.(MatchServerName); ok {
108 for _, sniName := range sni {
109 // index for fast lookups during handshakes
110 indexName := asciiServerNameForMatch(sniName)
111 indexedBySNI[indexName] = append(indexedBySNI[indexName], p)
112 }
113 }
114 }
115 }
116 }
117
118 getConfigForClient := func(hello *tls.ClientHelloInfo) (*tls.Config, error) {
119 // filter policies by SNI first, if possible, to speed things up
120 // when there may be lots of policies
121 possiblePolicies := cp
122 if indexedPolicies, ok := indexedBySNI[asciiServerNameForMatch(hello.ServerName)]; ok {
123 possiblePolicies = indexedPolicies
124 }
125
126 policyLoop:
127 for _, pol := range possiblePolicies {
128 for _, matcher := range pol.matchers {
129 if !matcher.Match(hello) {
130 continue policyLoop
131 }
132 }
133 if pol.Drop {
134 return nil, fmt.Errorf("dropping connection")
135 }
136 return pol.TLSConfig, nil
137 }
138
139 return nil, fmt.Errorf("no server TLS configuration available for ClientHello: %+v", hello)
140 }
141
142 tlsCfg := &tls.Config{
143 MinVersion: tls.VersionTLS12,
144 GetConfigForClient: getConfigForClient,
145 }
146
147 // enable ECH, if configured
148 if tlsAppIface, err := ctx.AppIfConfigured("tls"); err == nil {
149 tlsApp := tlsAppIface.(*TLS)
150
151 if tlsApp.EncryptedClientHello != nil && len(tlsApp.EncryptedClientHello.configs) > 0 {
152 // if no publication was configured, we apply ECH to all server names by default,
153 // but the TLS app needs to know what they are in this case, since they don't appear
154 // in its config (remember, TLS connection policies are used by *other* apps to
155 // run TLS servers) -- we skip names with placeholders
156 if tlsApp.EncryptedClientHello.Publication == nil {
157 repl := caddy.NewReplacer()
158 for _, p := range cp {
159 var echNames []string
160 for _, m := range p.matchers {
161 if sni, ok := m.(MatchServerName); ok {
162 for _, name := range sni {
163 finalName := strings.ToLower(repl.ReplaceAll(name, ""))
164 echNames = append(echNames, finalName)
165 }
166 }
167 }
168 tlsApp.RegisterServerNames(echNames, p.ALPN)
169 }
170 }
171
172 tlsCfg.GetEncryptedClientHelloKeys = func(chi *tls.ClientHelloInfo) ([]tls.EncryptedClientHelloKey, error) {
173 tlsApp.EncryptedClientHello.configsMu.RLock()
174 defer tlsApp.EncryptedClientHello.configsMu.RUnlock()
175 return tlsApp.EncryptedClientHello.stdlibReady, nil
176 }
177 }
178 }
179
180 return tlsCfg
181 }
182
183 // ConnectionPolicy specifies the logic for handling a TLS handshake.
184 // An empty policy is valid; safe and sensible defaults will be used.
185 type ConnectionPolicy struct {
186 // How to match this policy with a TLS ClientHello. If
187 // this policy is the first to match, it will be used.
188 MatchersRaw caddy.ModuleMap `json:"match,omitempty" caddy:"namespace=tls.handshake_match"`
189 matchers []ConnectionMatcher
190
191 // How to choose a certificate if more than one matched
192 // the given ServerName (SNI) value.
193 CertSelection *CustomCertSelectionPolicy `json:"certificate_selection,omitempty"`
194
195 // The list of cipher suites to support. Caddy's
196 // defaults are modern and secure.
197 CipherSuites []string `json:"cipher_suites,omitempty"`
198
199 // The list of elliptic curves to support. Caddy's
200 // defaults are modern and secure.
201 Curves []string `json:"curves,omitempty"`
202
203 // Protocols to use for Application-Layer Protocol
204 // Negotiation (ALPN) during the handshake.
205 ALPN []string `json:"alpn,omitempty"`
206
207 // Minimum TLS protocol version to allow. Default: `tls1.2`
208 ProtocolMin string `json:"protocol_min,omitempty"`
209
210 // Maximum TLS protocol version to allow. Default: `tls1.3`
211 ProtocolMax string `json:"protocol_max,omitempty"`
212
213 // Reject TLS connections. EXPERIMENTAL: May change.
214 Drop bool `json:"drop,omitempty"`
215
216 // Enables and configures TLS client authentication.
217 ClientAuthentication *ClientAuthentication `json:"client_authentication,omitempty"`
218
219 // DefaultSNI becomes the ServerName in a ClientHello if there
220 // is no policy configured for the empty SNI value.
221 DefaultSNI string `json:"default_sni,omitempty"`
222
223 // FallbackSNI becomes the ServerName in a ClientHello if
224 // the original ServerName doesn't match any certificates
225 // in the cache. The use cases for this are very niche;
226 // typically if a client is a CDN and passes through the
227 // ServerName of the downstream handshake but can accept
228 // a certificate with the origin's hostname instead, then
229 // you would set this to your origin's hostname. Note that
230 // Caddy must be managing a certificate for this name.
231 //
232 // This feature is EXPERIMENTAL and subject to change or removal.
233 FallbackSNI string `json:"fallback_sni,omitempty"`
234
235 // Also known as "SSLKEYLOGFILE", TLS secrets will be written to
236 // this file in NSS key log format which can then be parsed by
237 // Wireshark and other tools. This is INSECURE as it allows other
238 // programs or tools to decrypt TLS connections. However, this
239 // capability can be useful for debugging and troubleshooting.
240 // **ENABLING THIS LOG COMPROMISES SECURITY!**
241 //
242 // This feature is EXPERIMENTAL and subject to change or removal.
243 InsecureSecretsLog string `json:"insecure_secrets_log,omitempty"`
244
245 // A module that can manipulate the context passed into CertMagic's
246 // certificate management functions during TLS handshakes.
247 // EXPERIMENTAL - subject to change or removal.
248 HandshakeContextRaw json.RawMessage `json:"handshake_context,omitempty" caddy:"namespace=tls.context inline_key=module"`
249 handshakeContext HandshakeContext
250
251 // TLSConfig is the fully-formed, standard lib TLS config
252 // used to serve TLS connections. Provision all
253 // ConnectionPolicies to populate this. It is exported only
254 // so it can be minimally adjusted after provisioning
255 // if necessary (like to adjust NextProtos to disable HTTP/2),
256 // and may be unexported in the future.
257 TLSConfig *tls.Config `json:"-"`
258 }
259
260 type HandshakeContext interface {
261 // HandshakeContext returns a context to pass into CertMagic's
262 // GetCertificate function used to serve, load, and manage certs
263 // during TLS handshakes. Generally you'll start with the context
264 // from the ClientHelloInfo, but you may use other information
265 // from it as well. Return an error to abort the handshake.
266 HandshakeContext(*tls.ClientHelloInfo) (context.Context, error)
267 }
268
269 func (p *ConnectionPolicy) buildStandardTLSConfig(ctx caddy.Context) error {
270 tlsAppIface, err := ctx.App("tls")
271 if err != nil {
272 return fmt.Errorf("getting tls app: %v", err)
273 }
274 tlsApp := tlsAppIface.(*TLS)
275
276 // fill in some "easy" default values, but for other values
277 // (such as slices), we should ensure that they start empty
278 // so the user-provided config can fill them in; then we will
279 // fill in a default config at the end if they are still unset
280 cfg := &tls.Config{
281 NextProtos: p.ALPN,
282 GetCertificate: func(hello *tls.ClientHelloInfo) (*tls.Certificate, error) {
283 // TODO: I don't love how this works: we pre-build certmagic configs
284 // so that handshakes are faster. Unfortunately, certmagic configs are
285 // comprised of settings from both a TLS connection policy and a TLS
286 // automation policy. The only two fields (as of March 2020; v2 beta 17)
287 // of a certmagic config that come from the TLS connection policy are
288 // CertSelection and DefaultServerName, so an automation policy is what
289 // builds the base certmagic config. Since the pre-built config is
290 // shared, I don't think we can change any of its fields per-handshake,
291 // hence the awkward shallow copy (dereference) here and the subsequent
292 // changing of some of its fields. I'm worried this dereference allocates
293 // more at handshake-time, but I don't know how to practically pre-build
294 // a certmagic config for each combination of conn policy + automation policy...
295 cfg := *tlsApp.getConfigForName(hello.ServerName)
296 if p.CertSelection != nil {
297 // you would think we could just set this whether or not
298 // p.CertSelection is nil, but that leads to panics if
299 // it is, because cfg.CertSelection is an interface,
300 // so it will have a non-nil value even if the actual
301 // value underlying it is nil (sigh)
302 cfg.CertSelection = p.CertSelection
303 }
304 cfg.DefaultServerName = p.DefaultSNI
305 cfg.FallbackServerName = p.FallbackSNI
306
307 // TODO: experimental: if a handshake context module is configured, allow it
308 // to modify the context before passing it into CertMagic's GetCertificate
309 ctx := hello.Context()
310 if p.handshakeContext != nil {
311 ctx, err = p.handshakeContext.HandshakeContext(hello)
312 if err != nil {
313 return nil, fmt.Errorf("handshake context: %v", err)
314 }
315 }
316
317 return cfg.GetCertificateWithContext(ctx, hello)
318 },
319 MinVersion: tls.VersionTLS12,
320 MaxVersion: tls.VersionTLS13,
321 }
322
323 // session tickets support
324 if tlsApp.SessionTickets != nil {
325 cfg.SessionTicketsDisabled = tlsApp.SessionTickets.Disabled
326
327 // session ticket key rotation
328 tlsApp.SessionTickets.register(cfg)
329 ctx.OnCancel(func() {
330 // do cleanup when the context is canceled because,
331 // though unlikely, it is possible that a context
332 // needing a TLS server config could exist for less
333 // than the lifetime of the whole app
334 tlsApp.SessionTickets.unregister(cfg)
335 })
336 }
337
338 // TODO: Clean up session ticket active locks in storage if app (or process) is being closed!
339
340 // add all the cipher suites in order, without duplicates
341 cipherSuitesAdded := make(map[uint16]struct{})
342 for _, csName := range p.CipherSuites {
343 csID := CipherSuiteID(csName)
344 if csID == 0 {
345 return fmt.Errorf("unsupported cipher suite: %s", csName)
346 }
347 if _, ok := cipherSuitesAdded[csID]; !ok {
348 cipherSuitesAdded[csID] = struct{}{}
349 cfg.CipherSuites = append(cfg.CipherSuites, csID)
350 }
351 }
352
353 // add all the curve preferences in order, without duplicates
354 curvesAdded := make(map[tls.CurveID]struct{})
355 for _, curveName := range p.Curves {
356 curveID := SupportedCurves[curveName]
357 if _, ok := curvesAdded[curveID]; !ok {
358 curvesAdded[curveID] = struct{}{}
359 cfg.CurvePreferences = append(cfg.CurvePreferences, curveID)
360 }
361 }
362
363 // ensure ALPN includes the ACME TLS-ALPN protocol
364 alpnFound := slices.Contains(p.ALPN, acmez.ACMETLS1Protocol)
365 if !alpnFound && (cfg.NextProtos == nil || len(cfg.NextProtos) > 0) {
366 cfg.NextProtos = append(cfg.NextProtos, acmez.ACMETLS1Protocol)
367 }
368
369 // min and max protocol versions
370 if (p.ProtocolMin != "" && p.ProtocolMax != "") && p.ProtocolMin > p.ProtocolMax {
371 return fmt.Errorf("protocol min (%x) cannot be greater than protocol max (%x)", p.ProtocolMin, p.ProtocolMax)
372 }
373 if p.ProtocolMin != "" {
374 cfg.MinVersion = SupportedProtocols[p.ProtocolMin]
375 }
376 if p.ProtocolMax != "" {
377 cfg.MaxVersion = SupportedProtocols[p.ProtocolMax]
378 }
379
380 // client authentication
381 if p.ClientAuthentication != nil {
382 if err := p.ClientAuthentication.provision(ctx); err != nil {
383 return fmt.Errorf("provisioning client CA: %v", err)
384 }
385 if err := p.ClientAuthentication.ConfigureTLSConfig(cfg); err != nil {
386 return fmt.Errorf("configuring TLS client authentication: %v", err)
387 }
388
389 // Prevent privilege escalation in case multiple vhosts are configured for
390 // this TLS server; we could potentially figure out if that's the case, but
391 // that might be complex to get right every time. Actually, two proper
392 // solutions could leave tickets enabled, but I am not sure how to do them
393 // properly without significant time investment; there may be new Go
394 // APIs that alloaw this (Wrap/UnwrapSession?) but I do not know how to use
395 // them at this time. TODO: one of these is a possible future enhancement:
396 // A) Prevent resumptions across server identities (certificates): binding the ticket to the
397 // certificate we would serve in a full handshake, or even bind a ticket to the exact SNI
398 // it was issued under (though there are proposals for session resumption across hostnames).
399 // B) Prevent resumptions falsely authenticating a client: include the realm in the ticket,
400 // so that it can be validated upon resumption.
401 cfg.SessionTicketsDisabled = true
402 }
403
404 if p.InsecureSecretsLog != "" {
405 filename, err := caddy.NewReplacer().ReplaceOrErr(p.InsecureSecretsLog, true, true)
406 if err != nil {
407 return err
408 }
409 filename, err = caddy.FastAbs(filename)
410 if err != nil {
411 return err
412 }
413 logFile, _, err := secretsLogPool.LoadOrNew(filename, func() (caddy.Destructor, error) {
414 w, err := os.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0o600)
415 return destructableWriter{w}, err
416 })
417 if err != nil {
418 return err
419 }
420 ctx.OnCancel(func() { _, _ = secretsLogPool.Delete(filename) })
421
422 cfg.KeyLogWriter = logFile.(io.Writer)
423
424 if c := tlsApp.logger.Check(zapcore.WarnLevel, "TLS SECURITY COMPROMISED: secrets logging is enabled!"); c != nil {
425 c.Write(zap.String("log_filename", filename))
426 }
427 }
428
429 setDefaultTLSParams(cfg)
430
431 p.TLSConfig = cfg
432
433 return nil
434 }
435
436 // SettingsEmpty returns true if p's settings (fields
437 // except the matchers) are all empty/unset.
438 func (p ConnectionPolicy) SettingsEmpty() bool {
439 return p.CertSelection == nil &&
440 p.CipherSuites == nil &&
441 p.Curves == nil &&
442 p.ALPN == nil &&
443 p.ProtocolMin == "" &&
444 p.ProtocolMax == "" &&
445 p.ClientAuthentication == nil &&
446 p.DefaultSNI == "" &&
447 p.FallbackSNI == "" &&
448 p.InsecureSecretsLog == ""
449 }
450
451 // SettingsEqual returns true if p's settings (fields
452 // except the matchers) are the same as q.
453 func (p ConnectionPolicy) SettingsEqual(q ConnectionPolicy) bool {
454 p.MatchersRaw = nil
455 q.MatchersRaw = nil
456 return reflect.DeepEqual(p, q)
457 }
458
459 // UnmarshalCaddyfile sets up the ConnectionPolicy from Caddyfile tokens. Syntax:
460 //
461 // connection_policy {
462 // alpn <values...>
463 // cert_selection {
464 // ...
465 // }
466 // ciphers <cipher_suites...>
467 // client_auth {
468 // ...
469 // }
470 // curves <curves...>
471 // default_sni <server_name>
472 // match {
473 // ...
474 // }
475 // protocols <min> [<max>]
476 // # EXPERIMENTAL:
477 // drop
478 // fallback_sni <server_name>
479 // insecure_secrets_log <log_file>
480 // }
481 func (cp *ConnectionPolicy) UnmarshalCaddyfile(d *caddyfile.Dispenser) error {
482 _, wrapper := d.Next(), d.Val()
483
484 // No same-line options are supported
485 if d.CountRemainingArgs() > 0 {
486 return d.ArgErr()
487 }
488
489 var hasCertSelection, hasClientAuth, hasDefaultSNI, hasDrop,
490 hasFallbackSNI, hasInsecureSecretsLog, hasMatch, hasProtocols bool
491 for nesting := d.Nesting(); d.NextBlock(nesting); {
492 optionName := d.Val()
493 switch optionName {
494 case "alpn":
495 if d.CountRemainingArgs() == 0 {
496 return d.ArgErr()
497 }
498 cp.ALPN = append(cp.ALPN, d.RemainingArgs()...)
499 case "cert_selection":
500 if hasCertSelection {
501 return d.Errf("duplicate %s option '%s'", wrapper, optionName)
502 }
503 p := &CustomCertSelectionPolicy{}
504 if err := p.UnmarshalCaddyfile(d.NewFromNextSegment()); err != nil {
505 return err
506 }
507 cp.CertSelection, hasCertSelection = p, true
508 case "client_auth":
509 if hasClientAuth {
510 return d.Errf("duplicate %s option '%s'", wrapper, optionName)
511 }
512 ca := &ClientAuthentication{}
513 if err := ca.UnmarshalCaddyfile(d.NewFromNextSegment()); err != nil {
514 return err
515 }
516 cp.ClientAuthentication, hasClientAuth = ca, true
517 case "ciphers":
518 if d.CountRemainingArgs() == 0 {
519 return d.ArgErr()
520 }
521 cp.CipherSuites = append(cp.CipherSuites, d.RemainingArgs()...)
522 case "curves":
523 if d.CountRemainingArgs() == 0 {
524 return d.ArgErr()
525 }
526 cp.Curves = append(cp.Curves, d.RemainingArgs()...)
527 case "default_sni":
528 if hasDefaultSNI {
529 return d.Errf("duplicate %s option '%s'", wrapper, optionName)
530 }
531 if d.CountRemainingArgs() != 1 {
532 return d.ArgErr()
533 }
534 _, cp.DefaultSNI, hasDefaultSNI = d.NextArg(), d.Val(), true
535 case "drop": // EXPERIMENTAL
536 if hasDrop {
537 return d.Errf("duplicate %s option '%s'", wrapper, optionName)
538 }
539 cp.Drop, hasDrop = true, true
540 case "fallback_sni": // EXPERIMENTAL
541 if hasFallbackSNI {
542 return d.Errf("duplicate %s option '%s'", wrapper, optionName)
543 }
544 if d.CountRemainingArgs() != 1 {
545 return d.ArgErr()
546 }
547 _, cp.FallbackSNI, hasFallbackSNI = d.NextArg(), d.Val(), true
548 case "insecure_secrets_log": // EXPERIMENTAL
549 if hasInsecureSecretsLog {
550 return d.Errf("duplicate %s option '%s'", wrapper, optionName)
551 }
552 if d.CountRemainingArgs() != 1 {
553 return d.ArgErr()
554 }
555 _, cp.InsecureSecretsLog, hasInsecureSecretsLog = d.NextArg(), d.Val(), true
556 case "match":
557 if hasMatch {
558 return d.Errf("duplicate %s option '%s'", wrapper, optionName)
559 }
560 matcherSet, err := ParseCaddyfileNestedMatcherSet(d)
561 if err != nil {
562 return err
563 }
564 cp.MatchersRaw, hasMatch = matcherSet, true
565 case "protocols":
566 if hasProtocols {
567 return d.Errf("duplicate %s option '%s'", wrapper, optionName)
568 }
569 if d.CountRemainingArgs() == 0 || d.CountRemainingArgs() > 2 {
570 return d.ArgErr()
571 }
572 _, cp.ProtocolMin, hasProtocols = d.NextArg(), d.Val(), true
573 if d.NextArg() {
574 cp.ProtocolMax = d.Val()
575 }
576 default:
577 return d.ArgErr()
578 }
579
580 // No nested blocks are supported
581 if d.NextBlock(nesting + 1) {
582 return d.Errf("malformed %s option '%s': blocks are not supported", wrapper, optionName)
583 }
584 }
585
586 return nil
587 }
588
589 // ClientAuthentication configures TLS client auth.
590 type ClientAuthentication struct {
591 // Certificate authority module which provides the certificate pool of trusted certificates
592 CARaw json.RawMessage `json:"ca,omitempty" caddy:"namespace=tls.ca_pool.source inline_key=provider"`
593 ca CA
594
595 // Deprecated: Use the `ca` field with the `tls.ca_pool.source.inline` module instead.
596 // A list of base64 DER-encoded CA certificates
597 // against which to validate client certificates.
598 // Client certs which are not signed by any of
599 // these CAs will be rejected.
600 TrustedCACerts []string `json:"trusted_ca_certs,omitempty"`
601
602 // Deprecated: Use the `ca` field with the `tls.ca_pool.source.file` module instead.
603 // TrustedCACertPEMFiles is a list of PEM file names
604 // from which to load certificates of trusted CAs.
605 // Client certificates which are not signed by any of
606 // these CA certificates will be rejected.
607 TrustedCACertPEMFiles []string `json:"trusted_ca_certs_pem_files,omitempty"`
608
609 // Deprecated: This field is deprecated and will be removed in
610 // a future version. Please use the `validators` field instead
611 // with the tls.client_auth.verifier.leaf module instead.
612 //
613 // A list of base64 DER-encoded client leaf certs
614 // to accept. If this list is not empty, client certs
615 // which are not in this list will be rejected.
616 TrustedLeafCerts []string `json:"trusted_leaf_certs,omitempty"`
617
618 // Client certificate verification modules. These can perform
619 // custom client authentication checks, such as ensuring the
620 // certificate is not revoked.
621 VerifiersRaw []json.RawMessage `json:"verifiers,omitempty" caddy:"namespace=tls.client_auth.verifier inline_key=verifier"`
622
623 verifiers []ClientCertificateVerifier
624
625 // The mode for authenticating the client. Allowed values are:
626 //
627 // Mode | Description
628 // -----|---------------
629 // `request` | Ask clients for a certificate, but allow even if there isn't one; do not verify it
630 // `require` | Require clients to present a certificate, but do not verify it
631 // `verify_if_given` | Ask clients for a certificate; allow even if there isn't one, but verify it if there is
632 // `require_and_verify` | Require clients to present a valid certificate that is verified
633 //
634 // The default mode is `require_and_verify` if any
635 // TrustedCACerts or TrustedCACertPEMFiles or TrustedLeafCerts
636 // are provided; otherwise, the default mode is `require`.
637 Mode string `json:"mode,omitempty"`
638
639 existingVerifyPeerCert func([][]byte, [][]*x509.Certificate) error
640 }
641
642 // UnmarshalCaddyfile parses the Caddyfile segment to set up the client authentication. Syntax:
643 //
644 // client_auth {
645 // mode [request|require|verify_if_given|require_and_verify]
646 // trust_pool <module> {
647 // ...
648 // }
649 // verifier <module>
650 // }
651 //
652 // If `mode` is not provided, it defaults to `require_and_verify` if `trust_pool` is provided.
653 // Otherwise, it defaults to `require`.
654 func (ca *ClientAuthentication) UnmarshalCaddyfile(d *caddyfile.Dispenser) error {
655 for d.NextArg() {
656 // consume any tokens on the same line, if any.
657 }
658 for nesting := d.Nesting(); d.NextBlock(nesting); {
659 subdir := d.Val()
660 switch subdir {
661 case "mode":
662 if d.CountRemainingArgs() > 1 {
663 return d.ArgErr()
664 }
665 if !d.Args(&ca.Mode) {
666 return d.ArgErr()
667 }
668 case "trusted_ca_cert":
669 caddy.Log().Warn("The 'trusted_ca_cert' field is deprecated. Use the 'trust_pool' field instead.")
670 if len(ca.CARaw) != 0 {
671 return d.Err("cannot specify both 'trust_pool' and 'trusted_ca_cert' or 'trusted_ca_cert_file'")
672 }
673 if !d.NextArg() {
674 return d.ArgErr()
675 }
676 ca.TrustedCACerts = append(ca.TrustedCACerts, d.Val())
677 case "trusted_leaf_cert":
678 if !d.NextArg() {
679 return d.ArgErr()
680 }
681 ca.TrustedLeafCerts = append(ca.TrustedLeafCerts, d.Val())
682 case "trusted_ca_cert_file":
683 caddy.Log().Warn("The 'trusted_ca_cert_file' field is deprecated. Use the 'trust_pool' field instead.")
684 if len(ca.CARaw) != 0 {
685 return d.Err("cannot specify both 'trust_pool' and 'trusted_ca_cert' or 'trusted_ca_cert_file'")
686 }
687 if !d.NextArg() {
688 return d.ArgErr()
689 }
690 filename := d.Val()
691 ders, err := convertPEMFilesToDER(filename)
692 if err != nil {
693 return d.WrapErr(err)
694 }
695 ca.TrustedCACerts = append(ca.TrustedCACerts, ders...)
696 case "trusted_leaf_cert_file":
697 if !d.NextArg() {
698 return d.ArgErr()
699 }
700 filename := d.Val()
701 ders, err := convertPEMFilesToDER(filename)
702 if err != nil {
703 return d.WrapErr(err)
704 }
705 ca.TrustedLeafCerts = append(ca.TrustedLeafCerts, ders...)
706 case "trust_pool":
707 if len(ca.TrustedCACerts) != 0 {
708 return d.Err("cannot specify both 'trust_pool' and 'trusted_ca_cert' or 'trusted_ca_cert_file'")
709 }
710 if !d.NextArg() {
711 return d.ArgErr()
712 }
713 modName := d.Val()
714 mod, err := caddyfile.UnmarshalModule(d, "tls.ca_pool.source."+modName)
715 if err != nil {
716 return d.WrapErr(err)
717 }
718 caMod, ok := mod.(CA)
719 if !ok {
720 return fmt.Errorf("trust_pool module '%s' is not a certificate pool provider", caMod)
721 }
722 ca.CARaw = caddyconfig.JSONModuleObject(caMod, "provider", modName, nil)
723 case "verifier":
724 if !d.NextArg() {
725 return d.ArgErr()
726 }
727
728 vType := d.Val()
729 modID := "tls.client_auth.verifier." + vType
730 unm, err := caddyfile.UnmarshalModule(d, modID)
731 if err != nil {
732 return err
733 }
734
735 _, ok := unm.(ClientCertificateVerifier)
736 if !ok {
737 return d.Errf("module '%s' is not a caddytls.ClientCertificateVerifier", modID)
738 }
739 ca.VerifiersRaw = append(ca.VerifiersRaw, caddyconfig.JSONModuleObject(unm, "verifier", vType, nil))
740 default:
741 return d.Errf("unknown subdirective for client_auth: %s", subdir)
742 }
743 }
744
745 // only trust_ca_cert or trust_ca_cert_file was specified
746 if len(ca.TrustedCACerts) > 0 {
747 fileMod := &InlineCAPool{}
748 fileMod.TrustedCACerts = append(fileMod.TrustedCACerts, ca.TrustedCACerts...)
749 ca.CARaw = caddyconfig.JSONModuleObject(fileMod, "provider", "inline", nil)
750 ca.TrustedCACertPEMFiles, ca.TrustedCACerts = nil, nil
751 }
752 return nil
753 }
754
755 func convertPEMFilesToDER(filename string) ([]string, error) {
756 certDataPEM, err := os.ReadFile(filename)
757 if err != nil {
758 return nil, err
759 }
760 var ders []string
761 // while block is not nil, we have more certificates in the file
762 for block, rest := pem.Decode(certDataPEM); block != nil; block, rest = pem.Decode(rest) {
763 if block.Type != "CERTIFICATE" {
764 return nil, fmt.Errorf("no CERTIFICATE pem block found in %s", filename)
765 }
766 ders = append(
767 ders,
768 base64.StdEncoding.EncodeToString(block.Bytes),
769 )
770 }
771 // if we decoded nothing, return an error
772 if len(ders) == 0 {
773 return nil, fmt.Errorf("no CERTIFICATE pem block found in %s", filename)
774 }
775 return ders, nil
776 }
777
778 func (clientauth *ClientAuthentication) provision(ctx caddy.Context) error {
779 if len(clientauth.CARaw) > 0 && (len(clientauth.TrustedCACerts) > 0 || len(clientauth.TrustedCACertPEMFiles) > 0) {
780 return fmt.Errorf("conflicting config for client authentication trust CA")
781 }
782
783 // convert all named file paths to inline
784 if len(clientauth.TrustedCACertPEMFiles) > 0 {
785 for _, fpath := range clientauth.TrustedCACertPEMFiles {
786 ders, err := convertPEMFilesToDER(fpath)
787 if err != nil {
788 return err
789 }
790 clientauth.TrustedCACerts = append(clientauth.TrustedCACerts, ders...)
791 }
792 }
793
794 // if we have TrustedCACerts explicitly set, create an 'inline' CA and return
795 if len(clientauth.TrustedCACerts) > 0 {
796 caPool := InlineCAPool{
797 TrustedCACerts: clientauth.TrustedCACerts,
798 }
799 err := caPool.Provision(ctx)
800 if err != nil {
801 return err
802 }
803 clientauth.ca = caPool
804 }
805
806 // if we don't have any CARaw set, there's not much work to do
807 if clientauth.CARaw == nil {
808 return nil
809 }
810 caRaw, err := ctx.LoadModule(clientauth, "CARaw")
811 if err != nil {
812 return err
813 }
814 ca, ok := caRaw.(CA)
815 if !ok {
816 return fmt.Errorf("'ca' module '%s' is not a certificate pool provider", ca)
817 }
818 clientauth.ca = ca
819
820 return nil
821 }
822
823 // Active returns true if clientauth has an actionable configuration.
824 func (clientauth ClientAuthentication) Active() bool {
825 return len(clientauth.TrustedCACerts) > 0 ||
826 len(clientauth.TrustedCACertPEMFiles) > 0 ||
827 len(clientauth.TrustedLeafCerts) > 0 || // TODO: DEPRECATED
828 len(clientauth.VerifiersRaw) > 0 ||
829 len(clientauth.Mode) > 0 ||
830 clientauth.CARaw != nil || clientauth.ca != nil
831 }
832
833 // ConfigureTLSConfig sets up cfg to enforce clientauth's configuration.
834 func (clientauth *ClientAuthentication) ConfigureTLSConfig(cfg *tls.Config) error {
835 // if there's no actionable client auth, simply disable it
836 if !clientauth.Active() {
837 cfg.ClientAuth = tls.NoClientCert
838 return nil
839 }
840
841 // enforce desired mode of client authentication
842 if len(clientauth.Mode) > 0 {
843 switch clientauth.Mode {
844 case "request":
845 cfg.ClientAuth = tls.RequestClientCert
846 case "require":
847 cfg.ClientAuth = tls.RequireAnyClientCert
848 case "verify_if_given":
849 cfg.ClientAuth = tls.VerifyClientCertIfGiven
850 case "require_and_verify":
851 cfg.ClientAuth = tls.RequireAndVerifyClientCert
852 default:
853 return fmt.Errorf("client auth mode not recognized: %s", clientauth.Mode)
854 }
855 } else {
856 // otherwise, set a safe default mode
857 if len(clientauth.TrustedCACerts) > 0 ||
858 len(clientauth.TrustedCACertPEMFiles) > 0 ||
859 len(clientauth.TrustedLeafCerts) > 0 ||
860 clientauth.CARaw != nil || clientauth.ca != nil {
861 cfg.ClientAuth = tls.RequireAndVerifyClientCert
862 } else {
863 cfg.ClientAuth = tls.RequireAnyClientCert
864 }
865 }
866
867 // enforce CA verification by adding CA certs to the ClientCAs pool
868 if clientauth.ca != nil {
869 cfg.ClientCAs = clientauth.ca.CertPool()
870 }
871
872 // TODO: DEPRECATED: Only here for backwards compatibility.
873 // If leaf cert is specified, enforce by adding a client auth module
874 if len(clientauth.TrustedLeafCerts) > 0 {
875 caddy.Log().Named("tls.connection_policy").Warn("trusted_leaf_certs is deprecated; use leaf verifier module instead")
876 var trustedLeafCerts []*x509.Certificate
877 for _, clientCertString := range clientauth.TrustedLeafCerts {
878 clientCert, err := decodeBase64DERCert(clientCertString)
879 if err != nil {
880 return fmt.Errorf("parsing certificate: %v", err)
881 }
882 trustedLeafCerts = append(trustedLeafCerts, clientCert)
883 }
884 clientauth.verifiers = append(clientauth.verifiers, LeafCertClientAuth{trustedLeafCerts: trustedLeafCerts})
885 }
886
887 // if a custom verification function already exists, wrap it
888 clientauth.existingVerifyPeerCert = cfg.VerifyPeerCertificate
889 cfg.VerifyConnection = clientauth.verifyConnection
890 return nil
891 }
892
893 // verifyConnection is for use as a tls.Config.VerifyConnection callback
894 // to do custom client certificate verification. It is intended for
895 // installation only by clientauth.ConfigureTLSConfig().
896 //
897 // Unlike VerifyPeerCertificate, VerifyConnection is called on every
898 // connection including resumed sessions, preventing session-resumption bypass.
899 func (clientauth *ClientAuthentication) verifyConnection(cs tls.ConnectionState) error {
900 rawCerts := make([][]byte, len(cs.PeerCertificates))
901 for i, cert := range cs.PeerCertificates {
902 rawCerts[i] = cert.Raw
903 }
904
905 // first use any pre-existing custom verification function
906 if clientauth.existingVerifyPeerCert != nil {
907 if err := clientauth.existingVerifyPeerCert(rawCerts, cs.VerifiedChains); err != nil {
908 return err
909 }
910 }
911 for _, verifier := range clientauth.verifiers {
912 if err := verifier.VerifyClientCertificate(rawCerts, cs.VerifiedChains); err != nil {
913 return err
914 }
915 }
916 return nil
917 }
918
919 // decodeBase64DERCert base64-decodes, then DER-decodes, certStr.
920 func decodeBase64DERCert(certStr string) (*x509.Certificate, error) {
921 derBytes, err := base64.StdEncoding.DecodeString(certStr)
922 if err != nil {
923 return nil, err
924 }
925 return x509.ParseCertificate(derBytes)
926 }
927
928 // setDefaultTLSParams sets the default TLS cipher suites, protocol versions,
929 // and server preferences of cfg if they are not already set; it does not
930 // overwrite values, only fills in missing values.
931 func setDefaultTLSParams(cfg *tls.Config) {
932 if len(cfg.CipherSuites) == 0 {
933 cfg.CipherSuites = getOptimalDefaultCipherSuites()
934 }
935
936 // Not a cipher suite, but still important for mitigating protocol downgrade attacks
937 // (prepend since having it at end breaks http2 due to non-h2-approved suites before it)
938 cfg.CipherSuites = append([]uint16{tls.TLS_FALLBACK_SCSV}, cfg.CipherSuites...)
939
940 if len(cfg.CurvePreferences) == 0 {
941 cfg.CurvePreferences = defaultCurves
942 }
943
944 // crypto/tls docs:
945 // "If EncryptedClientHelloKeys is set, MinVersion, if set, must be VersionTLS13."
946 if cfg.EncryptedClientHelloKeys != nil && cfg.MinVersion != 0 && cfg.MinVersion < tls.VersionTLS13 {
947 cfg.MinVersion = tls.VersionTLS13
948 }
949 }
950
951 // LeafCertClientAuth verifies the client's leaf certificate.
952 type LeafCertClientAuth struct {
953 LeafCertificateLoadersRaw []json.RawMessage `json:"leaf_certs_loaders,omitempty" caddy:"namespace=tls.leaf_cert_loader inline_key=loader"`
954 trustedLeafCerts []*x509.Certificate
955 }
956
957 // CaddyModule returns the Caddy module information.
958 func (LeafCertClientAuth) CaddyModule() caddy.ModuleInfo {
959 return caddy.ModuleInfo{
960 ID: "tls.client_auth.verifier.leaf",
961 New: func() caddy.Module { return new(LeafCertClientAuth) },
962 }
963 }
964
965 func (l *LeafCertClientAuth) Provision(ctx caddy.Context) error {
966 if l.LeafCertificateLoadersRaw == nil {
967 return nil
968 }
969 val, err := ctx.LoadModule(l, "LeafCertificateLoadersRaw")
970 if err != nil {
971 return fmt.Errorf("could not parse leaf certificates loaders: %s", err.Error())
972 }
973 trustedLeafCertloaders := []LeafCertificateLoader{}
974 for _, loader := range val.([]any) {
975 trustedLeafCertloaders = append(trustedLeafCertloaders, loader.(LeafCertificateLoader))
976 }
977 trustedLeafCertificates := []*x509.Certificate{}
978 for _, loader := range trustedLeafCertloaders {
979 certs, err := loader.LoadLeafCertificates()
980 if err != nil {
981 return fmt.Errorf("could not load leaf certificates: %s", err.Error())
982 }
983 trustedLeafCertificates = append(trustedLeafCertificates, certs...)
984 }
985 l.trustedLeafCerts = trustedLeafCertificates
986 return nil
987 }
988
989 // UnmarshalCaddyfile implements caddyfile.Unmarshaler.
990 func (l *LeafCertClientAuth) UnmarshalCaddyfile(d *caddyfile.Dispenser) error {
991 d.NextArg()
992
993 // accommodate the use of one-liners
994 if d.CountRemainingArgs() > 1 {
995 d.NextArg()
996 modName := d.Val()
997 mod, err := caddyfile.UnmarshalModule(d, "tls.leaf_cert_loader."+modName)
998 if err != nil {
999 return d.WrapErr(err)
1000 }
1001 vMod, ok := mod.(LeafCertificateLoader)
1002 if !ok {
1003 return fmt.Errorf("leaf module '%s' is not a leaf certificate loader", vMod)
1004 }
1005 l.LeafCertificateLoadersRaw = append(
1006 l.LeafCertificateLoadersRaw,
1007 caddyconfig.JSONModuleObject(vMod, "loader", modName, nil),
1008 )
1009 return nil
1010 }
1011
1012 // accommodate the use of nested blocks
1013 for nesting := d.Nesting(); d.NextBlock(nesting); {
1014 modName := d.Val()
1015 mod, err := caddyfile.UnmarshalModule(d, "tls.leaf_cert_loader."+modName)
1016 if err != nil {
1017 return d.WrapErr(err)
1018 }
1019 vMod, ok := mod.(LeafCertificateLoader)
1020 if !ok {
1021 return fmt.Errorf("leaf module '%s' is not a leaf certificate loader", vMod)
1022 }
1023 l.LeafCertificateLoadersRaw = append(
1024 l.LeafCertificateLoadersRaw,
1025 caddyconfig.JSONModuleObject(vMod, "loader", modName, nil),
1026 )
1027 }
1028 return nil
1029 }
1030
1031 func (l LeafCertClientAuth) VerifyClientCertificate(rawCerts [][]byte, _ [][]*x509.Certificate) error {
1032 if len(rawCerts) == 0 {
1033 return fmt.Errorf("no client certificate provided")
1034 }
1035
1036 remoteLeafCert, err := x509.ParseCertificate(rawCerts[0])
1037 if err != nil {
1038 return fmt.Errorf("can't parse the given certificate: %s", err.Error())
1039 }
1040
1041 if slices.ContainsFunc(l.trustedLeafCerts, remoteLeafCert.Equal) {
1042 return nil
1043 }
1044
1045 return fmt.Errorf("client leaf certificate failed validation")
1046 }
1047
1048 // PublicKeyAlgorithm is a JSON-unmarshalable wrapper type.
1049 type PublicKeyAlgorithm x509.PublicKeyAlgorithm
1050
1051 // UnmarshalJSON satisfies json.Unmarshaler.
1052 func (a *PublicKeyAlgorithm) UnmarshalJSON(b []byte) error {
1053 algoStr := strings.ToLower(strings.Trim(string(b), `"`))
1054 algo, ok := publicKeyAlgorithms[algoStr]
1055 if !ok {
1056 return fmt.Errorf("unrecognized public key algorithm: %s (expected one of %v)",
1057 algoStr, publicKeyAlgorithms)
1058 }
1059 *a = PublicKeyAlgorithm(algo)
1060 return nil
1061 }
1062
1063 // ConnectionMatcher is a type which matches TLS handshakes.
1064 type ConnectionMatcher interface {
1065 Match(*tls.ClientHelloInfo) bool
1066 }
1067
1068 // LeafCertificateLoader is a type that loads the trusted leaf certificates
1069 // for the tls.leaf_cert_loader modules
1070 type LeafCertificateLoader interface {
1071 LoadLeafCertificates() ([]*x509.Certificate, error)
1072 }
1073
1074 // ClientCertificateVerifier is a type which verifies client certificates.
1075 // It is called during verifyPeerCertificate in the TLS handshake.
1076 type ClientCertificateVerifier interface {
1077 VerifyClientCertificate(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error
1078 }
1079
1080 var defaultALPN = []string{"h2", "http/1.1"}
1081
1082 type destructableWriter struct{ *os.File }
1083
1084 func (d destructableWriter) Destruct() error { return d.Close() }
1085
1086 var secretsLogPool = caddy.NewUsagePool()
1087
1088 // Interface guards
1089 var (
1090 _ caddyfile.Unmarshaler = (*ClientAuthentication)(nil)
1091 _ caddyfile.Unmarshaler = (*ConnectionPolicy)(nil)
1092 _ caddyfile.Unmarshaler = (*LeafCertClientAuth)(nil)
1093 )
1094
1095 // ParseCaddyfileNestedMatcherSet parses the Caddyfile tokens for a nested
1096 // matcher set, and returns its raw module map value.
1097 func ParseCaddyfileNestedMatcherSet(d *caddyfile.Dispenser) (caddy.ModuleMap, error) {
1098 matcherMap := make(map[string]ConnectionMatcher)
1099
1100 tokensByMatcherName := make(map[string][]caddyfile.Token)
1101 for nesting := d.Nesting(); d.NextArg() || d.NextBlock(nesting); {
1102 matcherName := d.Val()
1103 tokensByMatcherName[matcherName] = append(tokensByMatcherName[matcherName], d.NextSegment()...)
1104 }
1105
1106 for matcherName, tokens := range tokensByMatcherName {
1107 dd := caddyfile.NewDispenser(tokens)
1108 dd.Next() // consume wrapper name
1109
1110 unm, err := caddyfile.UnmarshalModule(dd, "tls.handshake_match."+matcherName)
1111 if err != nil {
1112 return nil, err
1113 }
1114 cm, ok := unm.(ConnectionMatcher)
1115 if !ok {
1116 return nil, fmt.Errorf("matcher module '%s' is not a connection matcher", matcherName)
1117 }
1118 matcherMap[matcherName] = cm
1119 }
1120
1121 matcherSet := make(caddy.ModuleMap)
1122 for name, matcher := range matcherMap {
1123 jsonBytes, err := json.Marshal(matcher)
1124 if err != nil {
1125 return nil, fmt.Errorf("marshaling %T matcher: %v", matcher, err)
1126 }
1127 matcherSet[name] = jsonBytes
1128 }
1129
1130 return matcherSet, nil
1131 }