Skip to content
This repository has been archived by the owner on Dec 7, 2020. It is now read-only.

Certificate Rotations #178

Merged
merged 2 commits into from
Jan 19, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ cover.out
tests/db.bolt
test.sock
tests/redis.conf
tests/*.csr

*.iml
config.yml
Expand Down
3 changes: 2 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@
#### **2.0.2**

FEATURES:
* adding the --enable-cors-global to switch on CORs header injects into every response [#PR174](https://github.com/gambol99/keycloak-proxy/pull/174)
* Adding the --enable-cors-global to switch on CORs header injects into every response [#PR174](https://github.com/gambol99/keycloak-proxy/pull/174)
* Adding the ability to reload the certificates when the change [#PR178](https://github.com/gambol99/keycloak-proxy/pull/178)

BUGS:
* Fixed the time.Duration flags in the reflection code [#PR173](https://github.com/gambol99/keycloak-proxy/pull/173)
Expand Down
5 changes: 5 additions & 0 deletions Godeps/Godeps.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

125 changes: 125 additions & 0 deletions rotation.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
/*
Copyright 2015 All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package main

import (
"crypto/tls"
"fmt"
"path"
"strings"
"sync"

log "github.com/Sirupsen/logrus"
"github.com/fsnotify/fsnotify"
)

type certificationRotation struct {
sync.RWMutex
// certificate holds the current issuing certificate
certificate tls.Certificate
// certificateFile is the path the certificate
certificateFile string
// the privateKeyFile is the path of the private key
privateKeyFile string
}

// newCertificateRotator creates a new certificate
func newCertificateRotator(cert, key string) (*certificationRotation, error) {
// step: attempt to load the certificate
certificate, err := tls.LoadX509KeyPair(cert, key)
if err != nil {
return nil, err
}
// step: are we watching the files for changes?
return &certificationRotation{
certificate: certificate,
certificateFile: cert,
privateKeyFile: key,
}, nil
}

// watch is responsible for adding a file notification and watch on the files for changes
func (c *certificationRotation) watch() error {
log.Infof("adding a file watch on the certificates, certificate: %s, key: %s", c.certificateFile, c.privateKeyFile)
watcher, err := fsnotify.NewWatcher()
if err != nil {
return err
}
// add the files to the watch list
for _, x := range []string{c.certificateFile, c.privateKeyFile} {
if err := watcher.Add(path.Dir(x)); err != nil {
return fmt.Errorf("unable to add watch on directory: %s, error: %s", path.Dir(x), err)
}
}

// step: watching for events
filewatchPaths := []string{c.certificateFile, c.privateKeyFile}
go func() {
log.Info("starting to watch changes to the tls certificate files")
for {
select {
case event := <-watcher.Events:
if event.Op&fsnotify.Write == fsnotify.Write {
// step: does the change effect our files?
if !containedIn(event.Name, filewatchPaths) {
continue
}
// step: we have to reload the certificate
log.WithFields(log.Fields{
"filename": event.Name,
"event": strings.ToLower(event.Op.String()),
}).Debugf("the certificate file has thrown a file event")

// step: reload the certificate
certificate, err := tls.LoadX509KeyPair(c.certificateFile, c.privateKeyFile)
if err != nil {
log.WithFields(log.Fields{
"filename": event.Name,
"error": err.Error(),
}).Error("unable to load the new certificate")
}
// step: load the new certificate
c.loadCertificate(certificate)
// step: print a debug message for us
log.Infof("replacing the server certifacte with updated version")
}
case err := <-watcher.Errors:
log.WithFields(log.Fields{
"error": err.Error(),
}).Error("recieved an error from the file watcher")
}
}
}()

return nil
}

// loadCertificate provides entrypoint to update the certificate
func (c *certificationRotation) loadCertificate(certifacte tls.Certificate) error {
c.Lock()
defer c.Unlock()
c.certificate = certifacte

return nil
}

// GetCertificate is responsible for retrieving
func (c *certificationRotation) GetCertificate(hello *tls.ClientHelloInfo) (*tls.Certificate, error) {
c.RLock()
defer c.RUnlock()

return &c.certificate, nil
}
75 changes: 75 additions & 0 deletions rotation_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
/*
Copyright 2015 All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package main

import (
"crypto/tls"
"testing"

"github.com/stretchr/testify/assert"
)

const (
testCertificateFile = "./tests/proxy.pem"
testPrivateKeyFile = "./tests/proxy-key.pem"
)

func newTestCertificateRotator(t *testing.T) *certificationRotation {
c, err := newCertificateRotator(testCertificateFile, testPrivateKeyFile)
assert.NotNil(t, c)
assert.Equal(t, testCertificateFile, c.certificateFile)
assert.Equal(t, testPrivateKeyFile, c.privateKeyFile)
if !assert.NoError(t, err) {
t.Fatalf("unable to create the certificate rotator, error: %s", err)
}

return c
}

func TestNewCeritifacteRotator(t *testing.T) {
c, err := newCertificateRotator(testCertificateFile, testPrivateKeyFile)
assert.NotNil(t, c)
assert.NoError(t, err)
}

func TestNewCeritifacteRotatorFailure(t *testing.T) {
c, err := newCertificateRotator("./tests/does_not_exist", testPrivateKeyFile)
assert.Nil(t, c)
assert.Error(t, err)
}

func TestGetCertificate(t *testing.T) {
c := newTestCertificateRotator(t)
assert.NotEmpty(t, c.certificate)
crt, err := c.GetCertificate(nil)
assert.NoError(t, err)
assert.NotEmpty(t, crt)
}

func TestLoadCertificate(t *testing.T) {
c := newTestCertificateRotator(t)
assert.NotEmpty(t, c.certificate)
c.loadCertificate(tls.Certificate{})
crt, err := c.GetCertificate(nil)
assert.NoError(t, err)
assert.Equal(t, &tls.Certificate{}, crt)
}

func TestWatchCertificate(t *testing.T) {
c := newTestCertificateRotator(t)
err := c.watch()
assert.NoError(t, err)
}
14 changes: 11 additions & 3 deletions server.go
Original file line number Diff line number Diff line change
Expand Up @@ -376,11 +376,19 @@ func createHTTPListener(config listenerConfig) (net.Listener, error) {
// step: does the socket require TLS?
if config.certificate != "" && config.privateKey != "" {
log.Infof("tls enabled, certificate: %s, key: %s", config.certificate, config.privateKey)
tlsConfig := &tls.Config{}
tlsConfig.Certificates = make([]tls.Certificate, 1)
if tlsConfig.Certificates[0], err = tls.LoadX509KeyPair(config.certificate, config.privateKey); err != nil {
// step: creating a certificate rotation
rotate, err := newCertificateRotator(config.certificate, config.privateKey)
if err != nil {
return nil, err
}
// step: start watching the files for changes
if err := rotate.watch(); err != nil {
return nil, err
}
tlsConfig := &tls.Config{
PreferServerCipherSuites: true,
GetCertificate: rotate.GetCertificate,
}
listener = tls.NewListener(listener, tlsConfig)

// step: are we doing mutual tls?
Expand Down
5 changes: 5 additions & 0 deletions vendor/github.com/fsnotify/fsnotify/.editorconfig

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions vendor/github.com/fsnotify/fsnotify/.gitignore

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

28 changes: 28 additions & 0 deletions vendor/github.com/fsnotify/fsnotify/.travis.yml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

46 changes: 46 additions & 0 deletions vendor/github.com/fsnotify/fsnotify/AUTHORS

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading