cloudflare/cloudflared
Publicmirrored from https://github.com/cloudflare/cloudflaredAvailable
tlsconfig/certreloader.go
53lines · modecode
| 1 | package tlsconfig |
| 2 | |
| 3 | import ( |
| 4 | "crypto/tls" |
| 5 | "fmt" |
| 6 | "sync" |
| 7 | |
| 8 | "github.com/getsentry/raven-go" |
| 9 | ) |
| 10 | |
| 11 | // CertReloader can load and reload a TLS certificate from a particular filepath. |
| 12 | // Hooks into tls.Config's GetCertificate to allow a TLS server to update its certificate without restarting. |
| 13 | type CertReloader struct { |
| 14 | sync.Mutex |
| 15 | certificate *tls.Certificate |
| 16 | certPath string |
| 17 | keyPath string |
| 18 | } |
| 19 | |
| 20 | // NewCertReloader makes a CertReloader. It loads the cert during initialization to make sure certPath and keyPath are valid |
| 21 | func NewCertReloader(certPath, keyPath string) (*CertReloader, error) { |
| 22 | cr := new(CertReloader) |
| 23 | cr.certPath = certPath |
| 24 | cr.keyPath = keyPath |
| 25 | if err := cr.LoadCert(); err != nil { |
| 26 | return nil, err |
| 27 | } |
| 28 | return cr, nil |
| 29 | } |
| 30 | |
| 31 | // Cert returns the TLS certificate most recently read by the CertReloader. |
| 32 | func (cr *CertReloader) Cert(clientHello *tls.ClientHelloInfo) (*tls.Certificate, error) { |
| 33 | cr.Lock() |
| 34 | defer cr.Unlock() |
| 35 | return cr.certificate, nil |
| 36 | } |
| 37 | |
| 38 | // LoadCert loads a TLS certificate from the CertReloader's specified filepath. |
| 39 | // Call this after writing a new certificate to the disk (e.g. after renewing a certificate) |
| 40 | func (cr *CertReloader) LoadCert() error { |
| 41 | cr.Lock() |
| 42 | defer cr.Unlock() |
| 43 | |
| 44 | cert, err := tls.LoadX509KeyPair(cr.certPath, cr.keyPath) |
| 45 | |
| 46 | // Keep the old certificate if there's a problem reading the new one. |
| 47 | if err != nil { |
| 48 | raven.CaptureError(fmt.Errorf("Error parsing X509 key pair: %v", err), nil) |
| 49 | return err |
| 50 | } |
| 51 | cr.certificate = &cert |
| 52 | return nil |
| 53 | } |
| 54 | |