Debian Codegraph @

modules/caddytls/acmeissuer.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/x509"
20 "encoding/json"
21 "fmt"
22 "net/http"
23 "net/url"
24 "os"
25 "strconv"
26 "strings"
27 "time"
28
29 "github.com/caddyserver/certmagic"
30 "github.com/caddyserver/zerossl"
31 "github.com/mholt/acmez/v3/acme"
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(ACMEIssuer{})
42 }
43
44 // ACMEIssuer manages certificates using the ACME protocol (RFC 8555).
45 type ACMEIssuer struct {
46 // The URL to the CA's ACME directory endpoint. Default:
47 // https://acme-v02.api.letsencrypt.org/directory
48 CA string `json:"ca,omitempty"`
49
50 // The URL to the test CA's ACME directory endpoint.
51 // This endpoint is only used during retries if there
52 // is a failure using the primary CA. Default:
53 // https://acme-staging-v02.api.letsencrypt.org/directory
54 TestCA string `json:"test_ca,omitempty"`
55
56 // Your email address, so the CA can contact you if necessary.
57 // Not required, but strongly recommended to provide one so
58 // you can be reached if there is a problem. Your email is
59 // not sent to any Caddy mothership or used for any purpose
60 // other than ACME transactions.
61 Email string `json:"email,omitempty"`
62
63 // Optionally select an ACME profile to use for certificate
64 // orders. Must be a profile name offered by the ACME server,
65 // which are listed at its directory endpoint.
66 //
67 // EXPERIMENTAL: Subject to change.
68 // See https://datatracker.ietf.org/doc/draft-aaron-acme-profiles/
69 Profile string `json:"profile,omitempty"`
70
71 // If you have an existing account with the ACME server, put
72 // the private key here in PEM format. The ACME client will
73 // look up your account information with this key first before
74 // trying to create a new one. You can use placeholders here,
75 // for example if you have it in an environment variable.
76 AccountKey string `json:"account_key,omitempty"`
77
78 // If using an ACME CA that requires an external account
79 // binding, specify the CA-provided credentials here.
80 ExternalAccount *acme.EAB `json:"external_account,omitempty"`
81
82 // Time to wait before timing out an ACME operation.
83 // Default: 0 (no timeout)
84 ACMETimeout caddy.Duration `json:"acme_timeout,omitempty"`
85
86 // Configures the various ACME challenge types.
87 Challenges *ChallengesConfig `json:"challenges,omitempty"`
88
89 // An array of files of CA certificates to accept when connecting to the
90 // ACME CA. Generally, you should only use this if the ACME CA endpoint
91 // is internal or for development/testing purposes.
92 TrustedRootsPEMFiles []string `json:"trusted_roots_pem_files,omitempty"`
93
94 // Preferences for selecting alternate certificate chains, if offered
95 // by the CA. By default, the first offered chain will be selected.
96 // If configured, the chains may be sorted and the first matching chain
97 // will be selected.
98 PreferredChains *ChainPreference `json:"preferred_chains,omitempty"`
99
100 // The validity period to ask the CA to issue a certificate for.
101 // Default: 0 (CA chooses lifetime).
102 // This value is used to compute the "notAfter" field of the ACME order;
103 // therefore the system must have a reasonably synchronized clock.
104 // NOTE: Not all CAs support this. Check with your CA's ACME
105 // documentation to see if this is allowed and what values may
106 // be used. EXPERIMENTAL: Subject to change.
107 CertificateLifetime caddy.Duration `json:"certificate_lifetime,omitempty"`
108
109 // Forward proxy module
110 NetworkProxyRaw json.RawMessage `json:"network_proxy,omitempty" caddy:"namespace=caddy.network_proxy inline_key=from"`
111
112 rootPool *x509.CertPool
113 logger *zap.Logger
114
115 template certmagic.ACMEIssuer // set at Provision
116 magic *certmagic.Config // set at PreCheck
117 issuer *certmagic.ACMEIssuer // set at PreCheck; result of template + magic
118 }
119
120 // CaddyModule returns the Caddy module information.
121 func (ACMEIssuer) CaddyModule() caddy.ModuleInfo {
122 return caddy.ModuleInfo{
123 ID: "tls.issuance.acme",
124 New: func() caddy.Module { return new(ACMEIssuer) },
125 }
126 }
127
128 // Provision sets up iss.
129 func (iss *ACMEIssuer) Provision(ctx caddy.Context) error {
130 iss.logger = ctx.Logger()
131
132 repl := caddy.NewReplacer()
133
134 // expand email address, if non-empty
135 if iss.Email != "" {
136 email, err := repl.ReplaceOrErr(iss.Email, true, true)
137 if err != nil {
138 return fmt.Errorf("expanding email address '%s': %v", iss.Email, err)
139 }
140 iss.Email = email
141 }
142
143 // expand CA endpoint, if non-empty
144 if iss.CA != "" {
145 ca, err := repl.ReplaceOrErr(iss.CA, true, true)
146 if err != nil {
147 return fmt.Errorf("expanding CA endpoint '%s': %v", iss.CA, err)
148 }
149 iss.CA = ca
150 }
151
152 // expand TestCA endpoint, if non-empty
153 if iss.TestCA != "" {
154 testca, err := repl.ReplaceOrErr(iss.TestCA, true, true)
155 if err != nil {
156 return fmt.Errorf("expanding TestCA endpoint '%s': %v", iss.TestCA, err)
157 }
158 iss.TestCA = testca
159 }
160
161 // expand EAB credentials, if non-empty
162 if iss.ExternalAccount != nil {
163 if iss.ExternalAccount.KeyID != "" {
164 keyID, err := repl.ReplaceOrErr(iss.ExternalAccount.KeyID, true, true)
165 if err != nil {
166 return fmt.Errorf("expanding EAB key ID '%s': %v", iss.ExternalAccount.KeyID, err)
167 }
168 iss.ExternalAccount.KeyID = keyID
169 }
170 if iss.ExternalAccount.MACKey != "" {
171 macKey, err := repl.ReplaceOrErr(iss.ExternalAccount.MACKey, true, true)
172 if err != nil {
173 return fmt.Errorf("expanding EAB MAC key (redacted): %v", err)
174 }
175 iss.ExternalAccount.MACKey = macKey
176 }
177 }
178
179 // expand account key, if non-empty
180 if iss.AccountKey != "" {
181 accountKey, err := repl.ReplaceOrErr(iss.AccountKey, true, true)
182 if err != nil {
183 return fmt.Errorf("expanding account key PEM '%s': %v", iss.AccountKey, err)
184 }
185 iss.AccountKey = accountKey
186 }
187
188 // expand DNS override domain, if non-empty
189 if iss.Challenges != nil && iss.Challenges.DNS != nil && iss.Challenges.DNS.OverrideDomain != "" {
190 overrideDomain, err := repl.ReplaceOrErr(iss.Challenges.DNS.OverrideDomain, true, true)
191 if err != nil {
192 return fmt.Errorf("expanding DNS override domain '%s': %v", iss.Challenges.DNS.OverrideDomain, err)
193 }
194 iss.Challenges.DNS.OverrideDomain = overrideDomain
195 }
196
197 // DNS challenge provider, if not already established
198 if iss.Challenges != nil && iss.Challenges.DNS != nil && iss.Challenges.DNS.solver == nil {
199 var prov certmagic.DNSProvider
200 if iss.Challenges.DNS.ProviderRaw != nil {
201 // a challenge provider has been locally configured - use it
202 val, err := ctx.LoadModule(iss.Challenges.DNS, "ProviderRaw")
203 if err != nil {
204 return fmt.Errorf("loading DNS provider module: %v", err)
205 }
206 prov = val.(certmagic.DNSProvider)
207 } else if tlsAppIface, err := ctx.AppIfConfigured("tls"); err == nil {
208 // no locally configured DNS challenge provider, but if there is
209 // a global DNS module configured with the TLS app, use that
210 tlsApp := tlsAppIface.(*TLS)
211 if tlsApp.dns != nil {
212 prov = tlsApp.dns.(certmagic.DNSProvider)
213 }
214 }
215 if prov == nil {
216 return fmt.Errorf("DNS challenge enabled, but no DNS provider configured")
217 }
218 iss.Challenges.DNS.solver = &certmagic.DNS01Solver{
219 DNSManager: certmagic.DNSManager{
220 DNSProvider: prov,
221 TTL: time.Duration(iss.Challenges.DNS.TTL),
222 PropagationDelay: time.Duration(iss.Challenges.DNS.PropagationDelay),
223 PropagationTimeout: time.Duration(iss.Challenges.DNS.PropagationTimeout),
224 Resolvers: iss.Challenges.DNS.Resolvers,
225 OverrideDomain: iss.Challenges.DNS.OverrideDomain,
226 Logger: iss.logger.Named("dns_manager"),
227 },
228 }
229 }
230
231 // add any custom CAs to trust store
232 if len(iss.TrustedRootsPEMFiles) > 0 {
233 iss.rootPool = x509.NewCertPool()
234 for _, pemFile := range iss.TrustedRootsPEMFiles {
235 pemData, err := os.ReadFile(pemFile)
236 if err != nil {
237 return fmt.Errorf("loading trusted root CA's PEM file: %s: %v", pemFile, err)
238 }
239 if !iss.rootPool.AppendCertsFromPEM(pemData) {
240 return fmt.Errorf("unable to add %s to trust pool: %v", pemFile, err)
241 }
242 }
243 }
244
245 var err error
246 iss.template, err = iss.makeIssuerTemplate(ctx)
247 if err != nil {
248 return err
249 }
250
251 return nil
252 }
253
254 func (iss *ACMEIssuer) makeIssuerTemplate(ctx caddy.Context) (certmagic.ACMEIssuer, error) {
255 template := certmagic.ACMEIssuer{
256 CA: iss.CA,
257 TestCA: iss.TestCA,
258 Email: iss.Email,
259 Profile: iss.Profile,
260 AccountKeyPEM: iss.AccountKey,
261 CertObtainTimeout: time.Duration(iss.ACMETimeout),
262 TrustedRoots: iss.rootPool,
263 ExternalAccount: iss.ExternalAccount,
264 NotAfter: time.Duration(iss.CertificateLifetime),
265 Logger: iss.logger,
266 }
267
268 if len(iss.NetworkProxyRaw) != 0 {
269 proxyMod, err := ctx.LoadModule(iss, "NetworkProxyRaw")
270 if err != nil {
271 return template, fmt.Errorf("failed to load network_proxy module: %v", err)
272 }
273 if m, ok := proxyMod.(caddy.ProxyFuncProducer); ok {
274 template.HTTPProxy = m.ProxyFunc()
275 } else {
276 return template, fmt.Errorf("network_proxy module is not `(func(*http.Request) (*url.URL, error))``")
277 }
278 }
279
280 if iss.Challenges != nil {
281 if iss.Challenges.HTTP != nil {
282 template.DisableHTTPChallenge = iss.Challenges.HTTP.Disabled
283 template.AltHTTPPort = iss.Challenges.HTTP.AlternatePort
284 }
285 if iss.Challenges.TLSALPN != nil {
286 template.DisableTLSALPNChallenge = iss.Challenges.TLSALPN.Disabled
287 template.AltTLSALPNPort = iss.Challenges.TLSALPN.AlternatePort
288 }
289 if iss.Challenges.DNS != nil {
290 template.DNS01Solver = iss.Challenges.DNS.solver
291 }
292 template.ListenHost = iss.Challenges.BindHost
293 if iss.Challenges.Distributed != nil {
294 template.DisableDistributedSolvers = !*iss.Challenges.Distributed
295 }
296 }
297
298 if iss.PreferredChains != nil {
299 template.PreferredChains = certmagic.ChainPreference{
300 Smallest: iss.PreferredChains.Smallest,
301 AnyCommonName: iss.PreferredChains.AnyCommonName,
302 RootCommonName: iss.PreferredChains.RootCommonName,
303 }
304 }
305
306 // ZeroSSL requires EAB, but we can generate that automatically (requires an email address be configured)
307 if strings.HasPrefix(iss.CA, "https://acme.zerossl.com/") {
308 template.NewAccountFunc = func(ctx context.Context, acmeIss *certmagic.ACMEIssuer, acct acme.Account) (acme.Account, error) {
309 if acmeIss.ExternalAccount != nil {
310 return acct, nil
311 }
312 var err error
313 acmeIss.ExternalAccount, acct, err = iss.generateZeroSSLEABCredentials(ctx, acct)
314 return acct, err
315 }
316 }
317
318 return template, nil
319 }
320
321 // SetConfig sets the associated certmagic config for this issuer.
322 // This is required because ACME needs values from the config in
323 // order to solve the challenges during issuance. This implements
324 // the ConfigSetter interface.
325 func (iss *ACMEIssuer) SetConfig(cfg *certmagic.Config) {
326 iss.magic = cfg
327 iss.issuer = certmagic.NewACMEIssuer(cfg, iss.template)
328 }
329
330 // PreCheck implements the certmagic.PreChecker interface.
331 func (iss *ACMEIssuer) PreCheck(ctx context.Context, names []string, interactive bool) error {
332 return iss.issuer.PreCheck(ctx, names, interactive)
333 }
334
335 // Issue obtains a certificate for the given csr.
336 func (iss *ACMEIssuer) Issue(ctx context.Context, csr *x509.CertificateRequest) (*certmagic.IssuedCertificate, error) {
337 return iss.issuer.Issue(ctx, csr)
338 }
339
340 // IssuerKey returns the unique issuer key for the configured CA endpoint.
341 func (iss *ACMEIssuer) IssuerKey() string {
342 return iss.issuer.IssuerKey()
343 }
344
345 // Revoke revokes the given certificate.
346 func (iss *ACMEIssuer) Revoke(ctx context.Context, cert certmagic.CertificateResource, reason int) error {
347 return iss.issuer.Revoke(ctx, cert, reason)
348 }
349
350 // GetACMEIssuer returns iss. This is useful when other types embed ACMEIssuer, because
351 // type-asserting them to *ACMEIssuer will fail, but type-asserting them to an interface
352 // with only this method will succeed, and will still allow the embedded ACMEIssuer
353 // to be accessed and manipulated.
354 func (iss *ACMEIssuer) GetACMEIssuer() *ACMEIssuer { return iss }
355
356 // GetRenewalInfo wraps the underlying GetRenewalInfo method and satisfies
357 // the CertMagic interface for ARI support.
358 func (iss *ACMEIssuer) GetRenewalInfo(ctx context.Context, cert certmagic.Certificate) (acme.RenewalInfo, error) {
359 return iss.issuer.GetRenewalInfo(ctx, cert)
360 }
361
362 // generateZeroSSLEABCredentials generates ZeroSSL EAB credentials for the primary contact email
363 // on the issuer. It should only be usedif the CA endpoint is ZeroSSL. An email address is required.
364 func (iss *ACMEIssuer) generateZeroSSLEABCredentials(ctx context.Context, acct acme.Account) (*acme.EAB, acme.Account, error) {
365 if strings.TrimSpace(iss.Email) == "" {
366 return nil, acme.Account{}, fmt.Errorf("your email address is required to use ZeroSSL's ACME endpoint")
367 }
368
369 if len(acct.Contact) == 0 {
370 // we borrow the email from config or the default email, so ensure it's saved with the account
371 acct.Contact = []string{"mailto:" + iss.Email}
372 }
373
374 endpoint := zerossl.BaseURL + "/acme/eab-credentials-email"
375 form := url.Values{"email": []string{iss.Email}}
376 body := strings.NewReader(form.Encode())
377
378 req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, body)
379 if err != nil {
380 return nil, acct, fmt.Errorf("forming request: %v", err)
381 }
382 req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
383 req.Header.Set("User-Agent", certmagic.UserAgent)
384
385 resp, err := http.DefaultClient.Do(req) //nolint:gosec // no SSRF since URL is from trusted config
386 if err != nil {
387 return nil, acct, fmt.Errorf("performing EAB credentials request: %v", err)
388 }
389 defer resp.Body.Close()
390
391 var result struct {
392 Success bool `json:"success"`
393 Error struct {
394 Code int `json:"code"`
395 Type string `json:"type"`
396 } `json:"error"`
397 EABKID string `json:"eab_kid"`
398 EABHMACKey string `json:"eab_hmac_key"`
399 }
400 err = json.NewDecoder(resp.Body).Decode(&result)
401 if err != nil {
402 return nil, acct, fmt.Errorf("decoding API response: %v", err)
403 }
404 if result.Error.Code != 0 {
405 // do this check first because ZeroSSL's API returns 200 on errors
406 return nil, acct, fmt.Errorf("failed getting EAB credentials: HTTP %d: %s (code %d)",
407 resp.StatusCode, result.Error.Type, result.Error.Code)
408 }
409 if resp.StatusCode != http.StatusOK {
410 return nil, acct, fmt.Errorf("failed getting EAB credentials: HTTP %d", resp.StatusCode)
411 }
412
413 if c := iss.logger.Check(zapcore.InfoLevel, "generated EAB credentials"); c != nil {
414 c.Write(zap.String("key_id", result.EABKID))
415 }
416
417 return &acme.EAB{
418 KeyID: result.EABKID,
419 MACKey: result.EABHMACKey,
420 }, acct, nil
421 }
422
423 // UnmarshalCaddyfile deserializes Caddyfile tokens into iss.
424 //
425 // ... acme [<directory_url>] {
426 // dir <directory_url>
427 // test_dir <test_directory_url>
428 // email <email>
429 // profile <profile_name>
430 // timeout <duration>
431 // disable_http_challenge
432 // disable_tlsalpn_challenge
433 // alt_http_port <port>
434 // alt_tlsalpn_port <port>
435 // eab <key_id> <mac_key>
436 // trusted_roots <pem_files...>
437 // dns <provider_name> [<options>]
438 // propagation_delay <duration>
439 // propagation_timeout <duration>
440 // resolvers <dns_servers...>
441 // dns_ttl <duration>
442 // dns_challenge_override_domain <domain>
443 // preferred_chains [smallest] {
444 // root_common_name <common_names...>
445 // any_common_name <common_names...>
446 // }
447 // }
448 func (iss *ACMEIssuer) UnmarshalCaddyfile(d *caddyfile.Dispenser) error {
449 d.Next() // consume issuer name
450
451 if d.NextArg() {
452 iss.CA = d.Val()
453 if d.NextArg() {
454 return d.ArgErr()
455 }
456 }
457
458 for d.NextBlock(0) {
459 switch d.Val() {
460 case "lifetime":
461 var lifetimeStr string
462 if !d.AllArgs(&lifetimeStr) {
463 return d.ArgErr()
464 }
465 lifetime, err := caddy.ParseDuration(lifetimeStr)
466 if err != nil {
467 return d.Errf("invalid lifetime %s: %v", lifetimeStr, err)
468 }
469 if lifetime < 0 {
470 return d.Errf("lifetime must be >= 0: %s", lifetime)
471 }
472 iss.CertificateLifetime = caddy.Duration(lifetime)
473
474 case "dir":
475 if iss.CA != "" {
476 return d.Errf("directory is already specified: %s", iss.CA)
477 }
478 if !d.AllArgs(&iss.CA) {
479 return d.ArgErr()
480 }
481
482 case "test_dir":
483 if !d.AllArgs(&iss.TestCA) {
484 return d.ArgErr()
485 }
486
487 case "email":
488 if !d.AllArgs(&iss.Email) {
489 return d.ArgErr()
490 }
491
492 case "profile":
493 if !d.AllArgs(&iss.Profile) {
494 return d.ArgErr()
495 }
496
497 case "timeout":
498 var timeoutStr string
499 if !d.AllArgs(&timeoutStr) {
500 return d.ArgErr()
501 }
502 timeout, err := caddy.ParseDuration(timeoutStr)
503 if err != nil {
504 return d.Errf("invalid timeout duration %s: %v", timeoutStr, err)
505 }
506 iss.ACMETimeout = caddy.Duration(timeout)
507
508 case "disable_http_challenge":
509 if d.NextArg() {
510 return d.ArgErr()
511 }
512 if iss.Challenges == nil {
513 iss.Challenges = new(ChallengesConfig)
514 }
515 if iss.Challenges.HTTP == nil {
516 iss.Challenges.HTTP = new(HTTPChallengeConfig)
517 }
518 iss.Challenges.HTTP.Disabled = true
519
520 case "disable_tlsalpn_challenge":
521 if d.NextArg() {
522 return d.ArgErr()
523 }
524 if iss.Challenges == nil {
525 iss.Challenges = new(ChallengesConfig)
526 }
527 if iss.Challenges.TLSALPN == nil {
528 iss.Challenges.TLSALPN = new(TLSALPNChallengeConfig)
529 }
530 iss.Challenges.TLSALPN.Disabled = true
531
532 case "distributed":
533 if !d.NextArg() {
534 return d.ArgErr()
535 }
536 if d.Val() != "false" {
537 return d.Errf("only accepted value is 'false'")
538 }
539 if iss.Challenges == nil {
540 iss.Challenges = new(ChallengesConfig)
541 }
542 if iss.Challenges.Distributed == nil {
543 iss.Challenges.Distributed = new(bool)
544 }
545
546 case "alt_http_port":
547 if !d.NextArg() {
548 return d.ArgErr()
549 }
550 port, err := strconv.Atoi(d.Val())
551 if err != nil {
552 return d.Errf("invalid port %s: %v", d.Val(), err)
553 }
554 if iss.Challenges == nil {
555 iss.Challenges = new(ChallengesConfig)
556 }
557 if iss.Challenges.HTTP == nil {
558 iss.Challenges.HTTP = new(HTTPChallengeConfig)
559 }
560 iss.Challenges.HTTP.AlternatePort = port
561
562 case "alt_tlsalpn_port":
563 if !d.NextArg() {
564 return d.ArgErr()
565 }
566 port, err := strconv.Atoi(d.Val())
567 if err != nil {
568 return d.Errf("invalid port %s: %v", d.Val(), err)
569 }
570 if iss.Challenges == nil {
571 iss.Challenges = new(ChallengesConfig)
572 }
573 if iss.Challenges.TLSALPN == nil {
574 iss.Challenges.TLSALPN = new(TLSALPNChallengeConfig)
575 }
576 iss.Challenges.TLSALPN.AlternatePort = port
577
578 case "eab":
579 iss.ExternalAccount = new(acme.EAB)
580 if !d.AllArgs(&iss.ExternalAccount.KeyID, &iss.ExternalAccount.MACKey) {
581 return d.ArgErr()
582 }
583
584 case "trusted_roots":
585 iss.TrustedRootsPEMFiles = d.RemainingArgs()
586
587 case "dns":
588 if iss.Challenges == nil {
589 iss.Challenges = new(ChallengesConfig)
590 }
591 if iss.Challenges.DNS == nil {
592 iss.Challenges.DNS = new(DNSChallengeConfig)
593 }
594 if d.NextArg() {
595 provName := d.Val()
596 unm, err := caddyfile.UnmarshalModule(d, "dns.providers."+provName)
597 if err != nil {
598 return err
599 }
600 iss.Challenges.DNS.ProviderRaw = caddyconfig.JSONModuleObject(unm, "name", provName, nil)
601 }
602
603 case "propagation_delay":
604 if !d.NextArg() {
605 return d.ArgErr()
606 }
607 delayStr := d.Val()
608 delay, err := caddy.ParseDuration(delayStr)
609 if err != nil {
610 return d.Errf("invalid propagation_delay duration %s: %v", delayStr, err)
611 }
612 if iss.Challenges == nil {
613 iss.Challenges = new(ChallengesConfig)
614 }
615 if iss.Challenges.DNS == nil {
616 iss.Challenges.DNS = new(DNSChallengeConfig)
617 }
618 iss.Challenges.DNS.PropagationDelay = caddy.Duration(delay)
619
620 case "propagation_timeout":
621 if !d.NextArg() {
622 return d.ArgErr()
623 }
624 timeoutStr := d.Val()
625 var timeout time.Duration
626 if timeoutStr == "-1" {
627 timeout = time.Duration(-1)
628 } else {
629 var err error
630 timeout, err = caddy.ParseDuration(timeoutStr)
631 if err != nil {
632 return d.Errf("invalid propagation_timeout duration %s: %v", timeoutStr, err)
633 }
634 }
635 if iss.Challenges == nil {
636 iss.Challenges = new(ChallengesConfig)
637 }
638 if iss.Challenges.DNS == nil {
639 iss.Challenges.DNS = new(DNSChallengeConfig)
640 }
641 iss.Challenges.DNS.PropagationTimeout = caddy.Duration(timeout)
642
643 case "resolvers":
644 if iss.Challenges == nil {
645 iss.Challenges = new(ChallengesConfig)
646 }
647 if iss.Challenges.DNS == nil {
648 iss.Challenges.DNS = new(DNSChallengeConfig)
649 }
650 iss.Challenges.DNS.Resolvers = d.RemainingArgs()
651 if len(iss.Challenges.DNS.Resolvers) == 0 {
652 return d.ArgErr()
653 }
654
655 case "dns_ttl":
656 if !d.NextArg() {
657 return d.ArgErr()
658 }
659 ttlStr := d.Val()
660 ttl, err := caddy.ParseDuration(ttlStr)
661 if err != nil {
662 return d.Errf("invalid dns_ttl duration %s: %v", ttlStr, err)
663 }
664 if iss.Challenges == nil {
665 iss.Challenges = new(ChallengesConfig)
666 }
667 if iss.Challenges.DNS == nil {
668 iss.Challenges.DNS = new(DNSChallengeConfig)
669 }
670 iss.Challenges.DNS.TTL = caddy.Duration(ttl)
671
672 case "dns_challenge_override_domain":
673 arg := d.RemainingArgs()
674 if len(arg) != 1 {
675 return d.ArgErr()
676 }
677 if iss.Challenges == nil {
678 iss.Challenges = new(ChallengesConfig)
679 }
680 if iss.Challenges.DNS == nil {
681 iss.Challenges.DNS = new(DNSChallengeConfig)
682 }
683 iss.Challenges.DNS.OverrideDomain = arg[0]
684
685 case "preferred_chains":
686 chainPref, err := ParseCaddyfilePreferredChainsOptions(d)
687 if err != nil {
688 return err
689 }
690 iss.PreferredChains = chainPref
691
692 default:
693 return d.Errf("unrecognized ACME issuer property: %s", d.Val())
694 }
695 }
696 return nil
697 }
698
699 func ParseCaddyfilePreferredChainsOptions(d *caddyfile.Dispenser) (*ChainPreference, error) {
700 chainPref := new(ChainPreference)
701 if d.NextArg() {
702 smallestOpt := d.Val()
703 if smallestOpt == "smallest" {
704 trueBool := true
705 chainPref.Smallest = &trueBool
706 if d.NextArg() { // Only one argument allowed
707 return nil, d.ArgErr()
708 }
709 if d.NextBlock(d.Nesting()) { // Don't allow other options when smallest == true
710 return nil, d.Err("No more options are accepted when using the 'smallest' option")
711 }
712 } else { // Smallest option should always be 'smallest' or unset
713 return nil, d.Errf("Invalid argument '%s'", smallestOpt)
714 }
715 }
716 for nesting := d.Nesting(); d.NextBlock(nesting); {
717 switch d.Val() {
718 case "root_common_name":
719 rootCommonNameOpt := d.RemainingArgs()
720 chainPref.RootCommonName = append(chainPref.RootCommonName, rootCommonNameOpt...)
721 if rootCommonNameOpt == nil {
722 return nil, d.ArgErr()
723 }
724 if chainPref.AnyCommonName != nil {
725 return nil, d.Err("Can't set root_common_name when any_common_name is already set")
726 }
727
728 case "any_common_name":
729 anyCommonNameOpt := d.RemainingArgs()
730 chainPref.AnyCommonName = append(chainPref.AnyCommonName, anyCommonNameOpt...)
731 if anyCommonNameOpt == nil {
732 return nil, d.ArgErr()
733 }
734 if chainPref.RootCommonName != nil {
735 return nil, d.Err("Can't set any_common_name when root_common_name is already set")
736 }
737
738 default:
739 return nil, d.Errf("Received unrecognized parameter '%s'", d.Val())
740 }
741 }
742
743 if chainPref.Smallest == nil && chainPref.RootCommonName == nil && chainPref.AnyCommonName == nil {
744 return nil, d.Err("No options for preferred_chains received")
745 }
746
747 return chainPref, nil
748 }
749
750 // ChainPreference describes the client's preferred certificate chain,
751 // useful if the CA offers alternate chains. The first matching chain
752 // will be selected.
753 type ChainPreference struct {
754 // Prefer chains with the fewest number of bytes.
755 Smallest *bool `json:"smallest,omitempty"`
756
757 // Select first chain having a root with one of
758 // these common names.
759 RootCommonName []string `json:"root_common_name,omitempty"`
760
761 // Select first chain that has any issuer with one
762 // of these common names.
763 AnyCommonName []string `json:"any_common_name,omitempty"`
764 }
765
766 // Interface guards
767 var (
768 _ certmagic.PreChecker = (*ACMEIssuer)(nil)
769 _ certmagic.Issuer = (*ACMEIssuer)(nil)
770 _ certmagic.Revoker = (*ACMEIssuer)(nil)
771 _ certmagic.RenewalInfoGetter = (*ACMEIssuer)(nil)
772 _ caddy.Provisioner = (*ACMEIssuer)(nil)
773 _ ConfigSetter = (*ACMEIssuer)(nil)
774 _ caddyfile.Unmarshaler = (*ACMEIssuer)(nil)
775 )