2017-07-31 15:28:06 +00:00
|
|
|
package reload
|
|
|
|
|
|
|
|
import (
|
|
|
|
"crypto/tls"
|
2017-12-15 22:33:55 +00:00
|
|
|
"crypto/x509"
|
|
|
|
"encoding/pem"
|
|
|
|
"errors"
|
2017-07-31 15:28:06 +00:00
|
|
|
"fmt"
|
2017-12-15 22:33:55 +00:00
|
|
|
"io/ioutil"
|
2017-07-31 15:28:06 +00:00
|
|
|
"sync"
|
2017-12-15 22:33:55 +00:00
|
|
|
|
|
|
|
"github.com/hashicorp/errwrap"
|
2017-07-31 15:28:06 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
// ReloadFunc are functions that are called when a reload is requested
|
|
|
|
type ReloadFunc func(map[string]interface{}) error
|
|
|
|
|
|
|
|
// CertificateGetter satisfies ReloadFunc and its GetCertificate method
|
|
|
|
// satisfies the tls.GetCertificate function signature. Currently it does not
|
|
|
|
// allow changing paths after the fact.
|
|
|
|
type CertificateGetter struct {
|
|
|
|
sync.RWMutex
|
|
|
|
|
|
|
|
cert *tls.Certificate
|
|
|
|
|
2017-12-15 22:33:55 +00:00
|
|
|
certFile string
|
|
|
|
keyFile string
|
|
|
|
passphrase string
|
2017-07-31 15:28:06 +00:00
|
|
|
}
|
|
|
|
|
2017-12-15 22:33:55 +00:00
|
|
|
func NewCertificateGetter(certFile, keyFile, passphrase string) *CertificateGetter {
|
2017-07-31 15:28:06 +00:00
|
|
|
return &CertificateGetter{
|
2017-12-15 22:33:55 +00:00
|
|
|
certFile: certFile,
|
|
|
|
keyFile: keyFile,
|
|
|
|
passphrase: passphrase,
|
2017-07-31 15:28:06 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (cg *CertificateGetter) Reload(_ map[string]interface{}) error {
|
2017-12-15 22:33:55 +00:00
|
|
|
certPEMBlock, err := ioutil.ReadFile(cg.certFile)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
keyPEMBlock, err := ioutil.ReadFile(cg.keyFile)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// Check for encrypted pem block
|
|
|
|
keyBlock, _ := pem.Decode(keyPEMBlock)
|
|
|
|
if keyBlock == nil {
|
2018-04-09 18:35:21 +00:00
|
|
|
return errors.New("decoded PEM is blank")
|
2017-12-15 22:33:55 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
if x509.IsEncryptedPEMBlock(keyBlock) {
|
|
|
|
keyBlock.Bytes, err = x509.DecryptPEMBlock(keyBlock, []byte(cg.passphrase))
|
|
|
|
if err != nil {
|
|
|
|
return errwrap.Wrapf("Decrypting PEM block failed {{err}}", err)
|
|
|
|
}
|
|
|
|
keyPEMBlock = pem.EncodeToMemory(keyBlock)
|
|
|
|
}
|
|
|
|
|
|
|
|
cert, err := tls.X509KeyPair(certPEMBlock, keyPEMBlock)
|
2017-07-31 15:28:06 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
cg.Lock()
|
|
|
|
defer cg.Unlock()
|
|
|
|
|
|
|
|
cg.cert = &cert
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (cg *CertificateGetter) GetCertificate(clientHello *tls.ClientHelloInfo) (*tls.Certificate, error) {
|
|
|
|
cg.RLock()
|
|
|
|
defer cg.RUnlock()
|
|
|
|
|
|
|
|
if cg.cert == nil {
|
|
|
|
return nil, fmt.Errorf("nil certificate")
|
|
|
|
}
|
|
|
|
|
|
|
|
return cg.cert, nil
|
|
|
|
}
|