-
Notifications
You must be signed in to change notification settings - Fork 276
/
manager.go
466 lines (409 loc) · 12.2 KB
/
manager.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
// Package autocert implements automatic management of TLS certificates.
package autocert
import (
"context"
"crypto/tls"
"encoding/base64"
"errors"
"fmt"
"net"
"net/http"
"sort"
"sync"
"sync/atomic"
"time"
"github.com/caddyserver/certmagic"
"github.com/mholt/acmez/acme"
"github.com/rs/zerolog"
"go.uber.org/zap"
"github.com/pomerium/pomerium/config"
"github.com/pomerium/pomerium/internal/httputil"
"github.com/pomerium/pomerium/internal/log"
"github.com/pomerium/pomerium/internal/telemetry/metrics"
"github.com/pomerium/pomerium/internal/urlutil"
"github.com/pomerium/pomerium/pkg/cryptutil"
)
var (
errObtainCertFailed = errors.New("obtain cert failed")
errRenewCertFailed = errors.New("renew cert failed")
// RenewCert is not thread-safe
renewCertLock sync.Mutex
)
const (
ocspRespCacheSize = 50000
renewalInterval = time.Minute * 10
renewalTimeout = time.Hour
)
// Manager manages TLS certificates.
type Manager struct {
src config.Source
acmeTemplate certmagic.ACMEIssuer
mu sync.RWMutex
config *config.Config
certmagic *certmagic.Config
acmeMgr atomic.Pointer[certmagic.ACMEIssuer]
srv *http.Server
acmeTLSALPNListener net.Listener
*ocspCache
config.ChangeDispatcher
}
// New creates a new autocert manager.
func New(src config.Source) (*Manager, error) {
return newManager(context.Background(), src, certmagic.DefaultACME, renewalInterval)
}
func newManager(ctx context.Context,
src config.Source,
acmeTemplate certmagic.ACMEIssuer,
checkInterval time.Duration,
) (*Manager, error) {
ctx = log.WithContext(ctx, func(c zerolog.Context) zerolog.Context {
return c.Str("service", "autocert-manager")
})
ocspRespCache, err := newOCSPCache(ocspRespCacheSize)
if err != nil {
return nil, err
}
logger := log.ZapLogger().With(zap.String("service", "autocert"))
acmeTemplate.Logger = logger
mgr := &Manager{
src: src,
acmeTemplate: acmeTemplate,
ocspCache: ocspRespCache,
}
// set certmagic default storage cache, otherwise cert renewal loop will be based off
// certmagic's own default location
certmagicStorage, err := GetCertMagicStorage(ctx, src.GetConfig().Options.AutocertOptions.Folder)
if err != nil {
return nil, err
}
mgr.certmagic = certmagic.New(certmagic.NewCache(certmagic.CacheOptions{
GetConfigForCert: func(c certmagic.Certificate) (*certmagic.Config, error) {
return mgr.certmagic, nil
},
Logger: logger,
}), certmagic.Config{
Logger: logger,
Storage: certmagicStorage,
})
err = mgr.update(ctx, src.GetConfig())
if err != nil {
return nil, err
}
mgr.src.OnConfigChange(ctx, func(ctx context.Context, cfg *config.Config) {
err := mgr.update(ctx, cfg)
if err != nil {
log.Error(ctx).Err(err).Msg("autocert: error updating config")
return
}
cfg = mgr.GetConfig()
mgr.Trigger(ctx, cfg)
})
go func() {
ticker := time.NewTicker(checkInterval)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
err := mgr.renewConfigCerts(ctx)
if err != nil {
log.Error(ctx).Err(err).Msg("autocert: error updating config")
return
}
}
}
}()
return mgr, nil
}
func (mgr *Manager) getCertMagicConfig(ctx context.Context, cfg *config.Config) (*certmagic.Config, error) {
mgr.certmagic.MustStaple = cfg.Options.AutocertOptions.MustStaple
mgr.certmagic.OnDemand = nil // disable on-demand
var err error
mgr.certmagic.Storage, err = GetCertMagicStorage(ctx, cfg.Options.AutocertOptions.Folder)
if err != nil {
return nil, err
}
certs, err := cfg.AllCertificates()
if err != nil {
return nil, err
}
// add existing certs to the cache, and staple OCSP
for _, cert := range certs {
if err := mgr.certmagic.CacheUnmanagedTLSCertificate(ctx, cert, nil); err != nil {
return nil, fmt.Errorf("config: failed caching cert: %w", err)
}
}
acmeMgr := certmagic.NewACMEIssuer(mgr.certmagic, mgr.acmeTemplate)
err = configureCertificateAuthority(acmeMgr, cfg.Options.AutocertOptions)
if err != nil {
return nil, err
}
err = configureExternalAccountBinding(acmeMgr, cfg.Options.AutocertOptions)
if err != nil {
return nil, err
}
err = configureTrustedRoots(acmeMgr, cfg.Options.AutocertOptions)
if err != nil {
return nil, err
}
mgr.certmagic.Issuers = []certmagic.Issuer{acmeMgr}
mgr.acmeMgr.Store(acmeMgr)
return mgr.certmagic, nil
}
func (mgr *Manager) renewConfigCerts(ctx context.Context) error {
ctx, cancel := context.WithTimeout(ctx, renewalTimeout)
defer cancel()
mgr.mu.Lock()
defer mgr.mu.Unlock()
cfg := mgr.config
cm, err := mgr.getCertMagicConfig(ctx, cfg)
if err != nil {
return err
}
needsReload := false
var renew, ocsp []string
log.Debug(ctx).Strs("domains", sourceHostnames(cfg)).Msg("checking domains")
for _, domain := range sourceHostnames(cfg) {
cert, err := cm.CacheManagedCertificate(ctx, domain)
if err != nil {
// this happens for unmanaged certificates
continue
}
if cert.NeedsRenewal(cm) {
renew = append(renew, domain)
needsReload = true
}
if mgr.ocspCache.updated(domain, cert.OCSPStaple) {
ocsp = append(ocsp, domain)
needsReload = true
}
}
if !needsReload {
return nil
}
ctx = log.WithContext(ctx, func(c zerolog.Context) zerolog.Context {
if len(renew) > 0 {
c = c.Strs("renew_domains", renew)
}
if len(ocsp) > 0 {
c = c.Strs("ocsp_refresh", ocsp)
}
return c
})
log.Info(ctx).Msg("updating certificates")
cfg = mgr.src.GetConfig().Clone()
mgr.updateServer(ctx, cfg)
mgr.updateACMETLSALPNServer(ctx, cfg)
if err := mgr.updateAutocert(ctx, cfg); err != nil {
return err
}
mgr.config = cfg
mgr.Trigger(ctx, cfg)
return nil
}
func (mgr *Manager) update(ctx context.Context, cfg *config.Config) error {
cfg = cfg.Clone()
mgr.mu.Lock()
defer mgr.mu.Unlock()
defer func() { mgr.config = cfg }()
mgr.updateServer(ctx, cfg)
mgr.updateACMETLSALPNServer(ctx, cfg)
return mgr.updateAutocert(ctx, cfg)
}
// obtainCert obtains a certificate for given domain, use cached manager if cert exists there.
func (mgr *Manager) obtainCert(ctx context.Context, domain string, cm *certmagic.Config) (certmagic.Certificate, error) {
cert, err := cm.CacheManagedCertificate(ctx, domain)
if err != nil {
log.Info(ctx).Str("domain", domain).Msg("obtaining certificate")
err = cm.ObtainCertSync(ctx, domain)
if err != nil {
log.Error(ctx).Err(err).Msg("autocert failed to obtain client certificate")
return certmagic.Certificate{}, errObtainCertFailed
}
metrics.RecordAutocertRenewal()
cert, err = cm.CacheManagedCertificate(ctx, domain)
}
return cert, err
}
// renewCert attempts to renew given certificate.
func (mgr *Manager) renewCert(ctx context.Context, domain string, cert certmagic.Certificate, cm *certmagic.Config) (certmagic.Certificate, error) {
expired := time.Now().After(cert.Leaf.NotAfter)
log.Info(ctx).Str("domain", domain).Msg("renewing certificate")
renewCertLock.Lock()
err := cm.RenewCertSync(ctx, domain, false)
renewCertLock.Unlock()
if err != nil {
if expired {
return certmagic.Certificate{}, errRenewCertFailed
}
log.Warn(ctx).Err(err).Msg("renew client certificated failed, use existing cert")
}
return cm.CacheManagedCertificate(ctx, domain)
}
func (mgr *Manager) updateAutocert(ctx context.Context, cfg *config.Config) error {
if !cfg.Options.AutocertOptions.Enable {
mgr.acmeMgr.Store(nil)
return nil
}
cm, err := mgr.getCertMagicConfig(ctx, cfg)
if err != nil {
return err
}
for _, domain := range sourceHostnames(cfg) {
cert, err := mgr.obtainCert(ctx, domain, cm)
if err == nil && cert.NeedsRenewal(cm) {
cert, err = mgr.renewCert(ctx, domain, cert, cm)
}
if err != nil {
log.Error(ctx).Err(err).Msg("autocert: failed to obtain client certificate")
continue
}
log.Info(ctx).Strs("names", cert.Names).Msg("autocert: added certificate")
cfg.AutoCertificates = append(cfg.AutoCertificates, cert.Certificate)
}
metrics.RecordAutocertCertificates(cfg.AutoCertificates)
return nil
}
func (mgr *Manager) updateServer(ctx context.Context, cfg *config.Config) {
if mgr.srv != nil {
// nothing to do if the address hasn't changed
if mgr.srv.Addr == cfg.Options.HTTPRedirectAddr {
return
}
// close immediately, don't care about the error
_ = mgr.srv.Close()
mgr.srv = nil
}
if cfg.Options.HTTPRedirectAddr == "" {
return
}
redirect := httputil.RedirectHandler()
hsrv := &http.Server{
Addr: cfg.Options.HTTPRedirectAddr,
Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if mgr.handleHTTPChallenge(w, r) {
return
}
redirect.ServeHTTP(w, r)
}),
}
go func() {
log.Info(ctx).Str("addr", hsrv.Addr).Msg("starting http redirect server")
err := hsrv.ListenAndServe()
if err != nil {
log.Error(ctx).Err(err).Msg("failed to run http redirect server")
}
}()
mgr.srv = hsrv
}
func (mgr *Manager) updateACMETLSALPNServer(ctx context.Context, cfg *config.Config) {
addr := net.JoinHostPort("127.0.0.1", cfg.ACMETLSALPNPort)
if mgr.acmeTLSALPNListener != nil {
_ = mgr.acmeTLSALPNListener.Close()
mgr.acmeTLSALPNListener = nil
}
tlsConfig := mgr.certmagic.TLSConfig()
ln, err := tls.Listen("tcp", addr, tlsConfig)
if err != nil {
log.Error(ctx).Err(err).Msg("failed to run acme tls alpn server")
return
}
mgr.acmeTLSALPNListener = ln
go func() {
for {
conn, err := ln.Accept()
if errors.Is(err, net.ErrClosed) {
return
} else if err != nil {
continue
}
_ = conn.Close()
}
}()
}
func (mgr *Manager) handleHTTPChallenge(w http.ResponseWriter, r *http.Request) bool {
return mgr.acmeMgr.Load().HandleHTTPChallenge(w, r)
}
// GetConfig gets the config.
func (mgr *Manager) GetConfig() *config.Config {
mgr.mu.RLock()
defer mgr.mu.RUnlock()
return mgr.config
}
// configureCertificateAuthority configures the acmeMgr ACME Certificate Authority settings.
func configureCertificateAuthority(acmeMgr *certmagic.ACMEIssuer, opts config.AutocertOptions) error {
acmeMgr.Agreed = true
if opts.UseStaging {
acmeMgr.CA = acmeMgr.TestCA
}
if opts.CA != "" {
acmeMgr.CA = opts.CA // when a CA is specified, it overrides the staging setting
}
if opts.Email != "" {
acmeMgr.Email = opts.Email
} else {
acmeMgr.Email = " " // intentionally set to a space so that certmagic doesn't prompt for an email address
}
return nil
}
// configureExternalAccountBinding configures the acmeMgr ACME External Account Binding settings.
func configureExternalAccountBinding(acmeMgr *certmagic.ACMEIssuer, opts config.AutocertOptions) error {
if opts.EABKeyID != "" || opts.EABMACKey != "" {
acmeMgr.ExternalAccount = &acme.EAB{}
}
if opts.EABKeyID != "" {
acmeMgr.ExternalAccount.KeyID = opts.EABKeyID
}
if opts.EABMACKey != "" {
_, err := base64.RawURLEncoding.DecodeString(opts.EABMACKey)
if err != nil {
return fmt.Errorf("config: decoding base64-urlencoded MAC Key: %w", err)
}
acmeMgr.ExternalAccount.MACKey = opts.EABMACKey
}
return nil
}
// configureTrustedRoots configures the acmeMgr x509 roots to trust when communicating with an ACME CA.
func configureTrustedRoots(acmeMgr *certmagic.ACMEIssuer, opts config.AutocertOptions) error {
if opts.TrustedCA != "" {
// pool effectively contains the certificate(s) in the TrustedCA base64 PEM appended to the system roots
pool, err := cryptutil.GetCertPool(opts.TrustedCA, "")
if err != nil {
return fmt.Errorf("config: creating trusted certificate pool: %w", err)
}
acmeMgr.TrustedRoots = pool
}
if opts.TrustedCAFile != "" {
// pool effectively contains the certificate(s) in TrustedCAFile appended to the system roots
pool, err := cryptutil.GetCertPool("", opts.TrustedCAFile)
if err != nil {
return fmt.Errorf("config: creating trusted certificate pool: %w", err)
}
acmeMgr.TrustedRoots = pool
}
return nil
}
func sourceHostnames(cfg *config.Config) []string {
policies := cfg.Options.GetAllPolicies()
if len(policies) == 0 {
return nil
}
dedupe := map[string]struct{}{}
for _, p := range policies {
if u, _ := urlutil.ParseAndValidateURL(p.From); u != nil {
dedupe[u.Hostname()] = struct{}{}
}
}
if cfg.Options.AuthenticateURLString != "" {
if u, _ := cfg.Options.GetAuthenticateURL(); u != nil {
dedupe[u.Hostname()] = struct{}{}
}
}
var h []string
for k := range dedupe {
h = append(h, k)
}
sort.Strings(h)
return h
}