Debian Codegraph @

modules/caddypki/ca.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 caddypki
16
17 import (
18 "crypto"
19 "crypto/x509"
20 "encoding/json"
21 "errors"
22 "fmt"
23 "io/fs"
24 "path"
25 "sync"
26 "time"
27
28 "github.com/caddyserver/certmagic"
29 "github.com/smallstep/certificates/authority"
30 "github.com/smallstep/certificates/db"
31 "github.com/smallstep/truststore"
32 "go.uber.org/zap"
33
34 "github.com/caddyserver/caddy/v2"
35 )
36
37 // CA describes a certificate authority, which consists of
38 // root/signing certificates and various settings pertaining
39 // to the issuance of certificates and trusting them.
40 type CA struct {
41 // The user-facing name of the certificate authority.
42 Name string `json:"name,omitempty"`
43
44 // The name to put in the CommonName field of the
45 // root certificate.
46 RootCommonName string `json:"root_common_name,omitempty"`
47
48 // The name to put in the CommonName field of the
49 // intermediate certificates.
50 IntermediateCommonName string `json:"intermediate_common_name,omitempty"`
51
52 // The lifetime for the intermediate certificates
53 IntermediateLifetime caddy.Duration `json:"intermediate_lifetime,omitempty"`
54
55 // Whether Caddy will attempt to install the CA's root
56 // into the system trust store, as well as into Java
57 // and Mozilla Firefox trust stores. Default: true.
58 InstallTrust *bool `json:"install_trust,omitempty"`
59
60 // The root certificate to use; if null, one will be generated.
61 Root *KeyPair `json:"root,omitempty"`
62
63 // The intermediate (signing) certificate; if null, one will be generated.
64 Intermediate *KeyPair `json:"intermediate,omitempty"`
65
66 // How often to check if intermediate (and root, when applicable) certificates need renewal.
67 // Default: 10m.
68 MaintenanceInterval caddy.Duration `json:"maintenance_interval,omitempty"`
69
70 // The fraction of certificate lifetime (0.0–1.0) after which renewal is attempted.
71 // For example, 0.2 means renew when 20% of the lifetime remains (e.g. ~73 days for a 1-year cert).
72 // Default: 0.2.
73 RenewalWindowRatio float64 `json:"renewal_window_ratio,omitempty"`
74
75 // Optionally configure a separate storage module associated with this
76 // issuer, instead of using Caddy's global/default-configured storage.
77 // This can be useful if you want to keep your signing keys in a
78 // separate location from your leaf certificates.
79 StorageRaw json.RawMessage `json:"storage,omitempty" caddy:"namespace=caddy.storage inline_key=module"`
80
81 // The unique config-facing ID of the certificate authority.
82 // Since the ID is set in JSON config via object key, this
83 // field is exported only for purposes of config generation
84 // and module provisioning.
85 ID string `json:"-"`
86
87 storage certmagic.Storage
88 root *x509.Certificate
89 interChain []*x509.Certificate
90 interKey crypto.Signer
91 mu *sync.RWMutex
92
93 rootCertPath string // mainly used for logging purposes if trusting
94 log *zap.Logger
95 ctx caddy.Context
96 }
97
98 // Provision sets up the CA.
99 func (ca *CA) Provision(ctx caddy.Context, id string, log *zap.Logger) error {
100 ca.mu = new(sync.RWMutex)
101 ca.log = log.Named("ca." + id)
102 ca.ctx = ctx
103
104 if id == "" {
105 return fmt.Errorf("CA ID is required (use 'local' for the default CA)")
106 }
107 ca.mu.Lock()
108 ca.ID = id
109 ca.mu.Unlock()
110
111 if ca.StorageRaw != nil {
112 val, err := ctx.LoadModule(ca, "StorageRaw")
113 if err != nil {
114 return fmt.Errorf("loading storage module: %v", err)
115 }
116 cmStorage, err := val.(caddy.StorageConverter).CertMagicStorage()
117 if err != nil {
118 return fmt.Errorf("creating storage configuration: %v", err)
119 }
120 ca.storage = cmStorage
121 }
122 if ca.storage == nil {
123 ca.storage = ctx.Storage()
124 }
125
126 if ca.Name == "" {
127 ca.Name = defaultCAName
128 }
129 if ca.RootCommonName == "" {
130 ca.RootCommonName = defaultRootCommonName
131 }
132 if ca.IntermediateCommonName == "" {
133 ca.IntermediateCommonName = defaultIntermediateCommonName
134 }
135 if ca.IntermediateLifetime == 0 {
136 ca.IntermediateLifetime = caddy.Duration(defaultIntermediateLifetime)
137 }
138 if ca.MaintenanceInterval == 0 {
139 ca.MaintenanceInterval = caddy.Duration(defaultMaintenanceInterval)
140 }
141 if ca.RenewalWindowRatio <= 0 || ca.RenewalWindowRatio > 1 {
142 ca.RenewalWindowRatio = defaultRenewalWindowRatio
143 }
144
145 // load the certs and key that will be used for signing
146 var rootCert *x509.Certificate
147 var rootCertChain, interCertChain []*x509.Certificate
148 var rootKey, interKey crypto.Signer
149 var err error
150 if ca.Root != nil {
151 if ca.Root.Format == "" || ca.Root.Format == "pem_file" {
152 ca.rootCertPath = ca.Root.Certificate
153 }
154 rootCertChain, rootKey, err = ca.Root.Load()
155 rootCert = rootCertChain[0]
156 } else {
157 ca.rootCertPath = "storage:" + ca.storageKeyRootCert()
158 rootCert, rootKey, err = ca.loadOrGenRoot()
159 }
160 if err != nil {
161 return err
162 }
163
164 if ca.Intermediate != nil {
165 interCertChain, interKey, err = ca.Intermediate.Load()
166 } else {
167 actualRootLifetime := time.Until(rootCert.NotAfter)
168 if time.Duration(ca.IntermediateLifetime) >= actualRootLifetime {
169 return fmt.Errorf("intermediate certificate lifetime must be less than actual root certificate lifetime (%s)", actualRootLifetime)
170 }
171
172 interCertChain, interKey, err = ca.loadOrGenIntermediate(rootCert, rootKey)
173 }
174 if err != nil {
175 return err
176 }
177
178 ca.mu.Lock()
179 ca.root, ca.interChain, ca.interKey = rootCert, interCertChain, interKey
180 ca.mu.Unlock()
181
182 return nil
183 }
184
185 // RootCertificate returns the CA's root certificate (public key).
186 func (ca CA) RootCertificate() *x509.Certificate {
187 ca.mu.RLock()
188 defer ca.mu.RUnlock()
189 return ca.root
190 }
191
192 // RootKey returns the CA's root private key. Since the root key is
193 // not cached in memory long-term, it needs to be loaded from storage,
194 // which could yield an error.
195 func (ca CA) RootKey() (crypto.Signer, error) {
196 _, rootKey, err := ca.loadOrGenRoot()
197 return rootKey, err
198 }
199
200 // IntermediateCertificateChain returns the CA's intermediate
201 // certificate chain.
202 func (ca CA) IntermediateCertificateChain() []*x509.Certificate {
203 ca.mu.RLock()
204 defer ca.mu.RUnlock()
205 return ca.interChain
206 }
207
208 // IntermediateKey returns the CA's intermediate private key.
209 func (ca CA) IntermediateKey() crypto.Signer {
210 ca.mu.RLock()
211 defer ca.mu.RUnlock()
212 return ca.interKey
213 }
214
215 // NewAuthority returns a new Smallstep-powered signing authority for this CA.
216 // Note that we receive *CA (a pointer) in this method to ensure the closure within it, which
217 // executes at a later time, always has the only copy of the CA so it can access the latest,
218 // renewed certificates since NewAuthority was called. See #4517 and #4669.
219 func (ca *CA) NewAuthority(authorityConfig AuthorityConfig) (*authority.Authority, error) {
220 // get the root certificate and the issuer cert+key
221 rootCert := ca.RootCertificate()
222
223 // set up the signer; cert/key which signs the leaf certs
224 var signerOption authority.Option
225 if authorityConfig.SignWithRoot {
226 // if we're signing with root, we can just pass the
227 // cert/key directly, since it's unlikely to expire
228 // while Caddy is running (long lifetime)
229 var issuerCert *x509.Certificate
230 var issuerKey crypto.Signer
231 issuerCert = rootCert
232 var err error
233 issuerKey, err = ca.RootKey()
234 if err != nil {
235 return nil, fmt.Errorf("loading signing key: %v", err)
236 }
237 signerOption = authority.WithX509Signer(issuerCert, issuerKey)
238 } else {
239 // if we're signing with intermediate, we need to make
240 // sure it's always fresh, because the intermediate may
241 // renew while Caddy is running (medium lifetime)
242 signerOption = authority.WithX509SignerFunc(func() ([]*x509.Certificate, crypto.Signer, error) {
243 issuerChain := ca.IntermediateCertificateChain()
244 issuerCert := issuerChain[0]
245 issuerKey := ca.IntermediateKey()
246 ca.log.Debug("using intermediate signer",
247 zap.String("serial", issuerCert.SerialNumber.String()),
248 zap.String("not_before", issuerCert.NotBefore.String()),
249 zap.String("not_after", issuerCert.NotAfter.String()))
250 return issuerChain, issuerKey, nil
251 })
252 }
253
254 opts := []authority.Option{
255 authority.WithConfig(&authority.Config{
256 AuthorityConfig: authorityConfig.AuthConfig,
257 }),
258 signerOption,
259 authority.WithX509RootCerts(rootCert),
260 }
261
262 // Add a database if we have one
263 if authorityConfig.DB != nil {
264 opts = append(opts, authority.WithDatabase(*authorityConfig.DB))
265 }
266 auth, err := authority.NewEmbedded(opts...)
267 if err != nil {
268 return nil, fmt.Errorf("initializing certificate authority: %v", err)
269 }
270
271 return auth, nil
272 }
273
274 func (ca CA) loadOrGenRoot() (rootCert *x509.Certificate, rootKey crypto.Signer, err error) {
275 if ca.Root != nil {
276 rootChain, rootSigner, err := ca.Root.Load()
277 if err != nil {
278 return nil, nil, err
279 }
280 return rootChain[0], rootSigner, nil
281 }
282 rootCertPEM, err := ca.storage.Load(ca.ctx, ca.storageKeyRootCert())
283 if err != nil {
284 if !errors.Is(err, fs.ErrNotExist) {
285 return nil, nil, fmt.Errorf("loading root cert: %v", err)
286 }
287
288 // TODO: should we require that all or none of the assets are required before overwriting anything?
289 rootCert, rootKey, err = ca.genRoot()
290 if err != nil {
291 return nil, nil, fmt.Errorf("generating root: %v", err)
292 }
293 }
294
295 if rootCert == nil {
296 rootCert, err = pemDecodeCertificate(rootCertPEM)
297 if err != nil {
298 return nil, nil, fmt.Errorf("parsing root certificate PEM: %v", err)
299 }
300 }
301 if rootKey == nil {
302 rootKeyPEM, err := ca.storage.Load(ca.ctx, ca.storageKeyRootKey())
303 if err != nil {
304 return nil, nil, fmt.Errorf("loading root key: %v", err)
305 }
306 rootKey, err = certmagic.PEMDecodePrivateKey(rootKeyPEM)
307 if err != nil {
308 return nil, nil, fmt.Errorf("decoding root key: %v", err)
309 }
310 }
311
312 return rootCert, rootKey, nil
313 }
314
315 func (ca CA) genRoot() (rootCert *x509.Certificate, rootKey crypto.Signer, err error) {
316 repl := ca.newReplacer()
317
318 rootCert, rootKey, err = generateRoot(repl.ReplaceAll(ca.RootCommonName, ""))
319 if err != nil {
320 return nil, nil, fmt.Errorf("generating CA root: %v", err)
321 }
322 rootCertPEM, err := pemEncodeCert(rootCert.Raw)
323 if err != nil {
324 return nil, nil, fmt.Errorf("encoding root certificate: %v", err)
325 }
326 err = ca.storage.Store(ca.ctx, ca.storageKeyRootCert(), rootCertPEM)
327 if err != nil {
328 return nil, nil, fmt.Errorf("saving root certificate: %v", err)
329 }
330 rootKeyPEM, err := certmagic.PEMEncodePrivateKey(rootKey)
331 if err != nil {
332 return nil, nil, fmt.Errorf("encoding root key: %v", err)
333 }
334 err = ca.storage.Store(ca.ctx, ca.storageKeyRootKey(), rootKeyPEM)
335 if err != nil {
336 return nil, nil, fmt.Errorf("saving root key: %v", err)
337 }
338
339 return rootCert, rootKey, nil
340 }
341
342 func (ca CA) loadOrGenIntermediate(rootCert *x509.Certificate, rootKey crypto.Signer) (interCertChain []*x509.Certificate, interKey crypto.Signer, err error) {
343 var interCert *x509.Certificate
344 interCertPEM, err := ca.storage.Load(ca.ctx, ca.storageKeyIntermediateCert())
345 if err != nil {
346 if !errors.Is(err, fs.ErrNotExist) {
347 return nil, nil, fmt.Errorf("loading intermediate cert: %v", err)
348 }
349
350 // TODO: should we require that all or none of the assets are required before overwriting anything?
351 interCert, interKey, err = ca.genIntermediate(rootCert, rootKey)
352 if err != nil {
353 return nil, nil, fmt.Errorf("generating new intermediate cert: %v", err)
354 }
355
356 interCertChain = append(interCertChain, interCert)
357 }
358
359 if len(interCertChain) == 0 {
360 interCertChain, err = pemDecodeCertificateChain(interCertPEM)
361 if err != nil {
362 return nil, nil, fmt.Errorf("decoding intermediate certificate PEM: %v", err)
363 }
364 }
365
366 if interKey == nil {
367 interKeyPEM, err := ca.storage.Load(ca.ctx, ca.storageKeyIntermediateKey())
368 if err != nil {
369 return nil, nil, fmt.Errorf("loading intermediate key: %v", err)
370 }
371 interKey, err = certmagic.PEMDecodePrivateKey(interKeyPEM)
372 if err != nil {
373 return nil, nil, fmt.Errorf("decoding intermediate key: %v", err)
374 }
375 }
376
377 return interCertChain, interKey, nil
378 }
379
380 func (ca CA) genIntermediate(rootCert *x509.Certificate, rootKey crypto.Signer) (interCert *x509.Certificate, interKey crypto.Signer, err error) {
381 repl := ca.newReplacer()
382
383 interCert, interKey, err = generateIntermediate(repl.ReplaceAll(ca.IntermediateCommonName, ""), rootCert, rootKey, time.Duration(ca.IntermediateLifetime))
384 if err != nil {
385 return nil, nil, fmt.Errorf("generating CA intermediate: %v", err)
386 }
387 interCertPEM, err := pemEncodeCert(interCert.Raw)
388 if err != nil {
389 return nil, nil, fmt.Errorf("encoding intermediate certificate: %v", err)
390 }
391 err = ca.storage.Store(ca.ctx, ca.storageKeyIntermediateCert(), interCertPEM)
392 if err != nil {
393 return nil, nil, fmt.Errorf("saving intermediate certificate: %v", err)
394 }
395 interKeyPEM, err := certmagic.PEMEncodePrivateKey(interKey)
396 if err != nil {
397 return nil, nil, fmt.Errorf("encoding intermediate key: %v", err)
398 }
399 err = ca.storage.Store(ca.ctx, ca.storageKeyIntermediateKey(), interKeyPEM)
400 if err != nil {
401 return nil, nil, fmt.Errorf("saving intermediate key: %v", err)
402 }
403
404 return interCert, interKey, nil
405 }
406
407 func (ca CA) storageKeyCAPrefix() string {
408 return path.Join("pki", "authorities", certmagic.StorageKeys.Safe(ca.ID))
409 }
410
411 func (ca CA) storageKeyRootCert() string {
412 return path.Join(ca.storageKeyCAPrefix(), "root.crt")
413 }
414
415 func (ca CA) storageKeyRootKey() string {
416 return path.Join(ca.storageKeyCAPrefix(), "root.key")
417 }
418
419 func (ca CA) storageKeyIntermediateCert() string {
420 return path.Join(ca.storageKeyCAPrefix(), "intermediate.crt")
421 }
422
423 func (ca CA) storageKeyIntermediateKey() string {
424 return path.Join(ca.storageKeyCAPrefix(), "intermediate.key")
425 }
426
427 func (ca CA) newReplacer() *caddy.Replacer {
428 repl := caddy.NewReplacer()
429 repl.Set("pki.ca.name", ca.Name)
430 return repl
431 }
432
433 // installRoot installs this CA's root certificate into the
434 // local trust store(s) if it is not already trusted. The CA
435 // must already be provisioned.
436 func (ca CA) installRoot() error {
437 // avoid password prompt if already trusted
438 if trusted(ca.root) {
439 ca.log.Info("root certificate is already trusted by system",
440 zap.String("path", ca.rootCertPath))
441 return nil
442 }
443
444 ca.log.Warn("installing root certificate (you might be prompted for password)",
445 zap.String("path", ca.rootCertPath))
446
447 return truststore.Install(ca.root,
448 truststore.WithDebug(),
449 truststore.WithFirefox(),
450 truststore.WithJava(),
451 )
452 }
453
454 // AuthorityConfig is used to help a CA configure
455 // the underlying signing authority.
456 type AuthorityConfig struct {
457 SignWithRoot bool
458
459 // TODO: should we just embed the underlying authority.Config struct type?
460 DB *db.AuthDB
461 AuthConfig *authority.AuthConfig
462 }
463
464 const (
465 // DefaultCAID is the default CA ID.
466 DefaultCAID = "local"
467
468 defaultCAName = "Caddy Local Authority"
469 defaultRootCommonName = "{pki.ca.name} - {time.now.year} ECC Root"
470 defaultIntermediateCommonName = "{pki.ca.name} - ECC Intermediate"
471
472 defaultRootLifetime = 24 * time.Hour * 30 * 12 * 10
473 defaultIntermediateLifetime = 24 * time.Hour * 7
474 defaultMaintenanceInterval = 10 * time.Minute
475 defaultRenewalWindowRatio = 0.2
476 )