Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[WIP] *: watch tls certificate changes #45

Closed
wants to merge 2 commits into from
Closed
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
9 changes: 6 additions & 3 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ require (
github.com/coreos/go-oidc v0.0.0-20181101194249-66476e026701 // indirect
github.com/docker/docker v0.0.0-20180612054059-a9fbbdc8dd87 // indirect
github.com/evanphx/json-patch v0.0.0-20180908160633-36442dbdb585 // indirect
github.com/fsnotify/fsnotify v1.4.7
github.com/ghodss/yaml v1.0.0
github.com/go-openapi/jsonpointer v0.19.0 // indirect
github.com/go-openapi/jsonreference v0.19.0 // indirect
Expand Down Expand Up @@ -41,11 +42,13 @@ require (
github.com/prometheus/procfs v0.0.0-20170519190837-65c1f6f8f0fc // indirect
github.com/sirupsen/logrus v0.0.0-20170822132746-89742aefa4b2 // indirect
github.com/spf13/pflag v1.0.3
golang.org/x/crypto v0.0.0-20180808211826-de0752318171 // indirect
golang.org/x/net v0.0.0-20190119204137-ed066c81e75e
golang.org/x/crypto v0.0.0-20190611184440-5c40567a22f8 // indirect
golang.org/x/net v0.0.0-20190613194153-d28f0bde5980
golang.org/x/oauth2 v0.0.0-20170412232759-a6bd8cefa181 // indirect
golang.org/x/sync v0.0.0-20190423024810-112230192c58 // indirect
golang.org/x/sys v0.0.0-20190616124812-15dcb6c0061f // indirect
golang.org/x/text v0.3.2 // indirect
golang.org/x/time v0.0.0-20161028155119-f51c12702a4d // indirect
golang.org/x/tools v0.0.0-20190614205625-5aca471b1d59 // indirect
google.golang.org/appengine v1.4.0 // indirect
gopkg.in/airbrake/gobrake.v2 v2.0.9 // indirect
gopkg.in/gemnasium/logrus-airbrake-hook.v2 v2.1.2 // indirect
Expand Down
16 changes: 16 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -100,22 +100,38 @@ github.com/stretchr/testify v1.2.2 h1:bSDNvY7ZPG5RlJ8otE/7V6gMiyenm9RtJ7IUVIAoJ1
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
golang.org/x/crypto v0.0.0-20180808211826-de0752318171 h1:vYogbvSFj2YXcjQxFHu/rASSOt9sLytpCaSkiwQ135I=
golang.org/x/crypto v0.0.0-20180808211826-de0752318171/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20190611184440-5c40567a22f8 h1:1wopBVtVdWnn03fZelqdXTqk7U7zPQCb+T4rbU9ZEoU=
golang.org/x/crypto v0.0.0-20190611184440-5c40567a22f8/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20181005035420-146acd28ed58/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20190119204137-ed066c81e75e h1:MDa3fSUp6MdYHouVmCCNz/zaH2a6CRcxY3VhT/K3C5Q=
golang.org/x/net v0.0.0-20190119204137-ed066c81e75e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190613194153-d28f0bde5980 h1:dfGZHvZk057jK2MCeWus/TowKpJ8y4AmooUzdBSR9GU=
golang.org/x/net v0.0.0-20190613194153-d28f0bde5980/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/oauth2 v0.0.0-20170412232759-a6bd8cefa181 h1:/4OaQ4bC66Oq9JDhUnxTjBGt8XBhDuwgMRXHgvfcCUY=
golang.org/x/oauth2 v0.0.0-20170412232759-a6bd8cefa181/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20190423024810-112230192c58 h1:8gQV6CLnAEikrhgkHFbMAEhagSSnXWGV915qUMm9mrU=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e h1:o3PsSEY8E4eXWkXrIP9YJALUkVZqzHJT5DOasTyn8Vs=
golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190616124812-15dcb6c0061f h1:25KHgbfyiSm6vwQLbM3zZIe1v9p/3ea4Rz+nnM5K/i4=
golang.org/x/sys v0.0.0-20190616124812-15dcb6c0061f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.2 h1:tW2bmiBqwgJj/UpqtC8EpXEZVYOwU0yG4iWbprSVAcs=
golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
golang.org/x/time v0.0.0-20161028155119-f51c12702a4d h1:TnM+PKb3ylGmZvyPXmo9m/wktg7Jn/a/fNmr33HSj8g=
golang.org/x/time v0.0.0-20161028155119-f51c12702a4d/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20190614205625-5aca471b1d59 h1:QjA/9ArTfVTLfEhClDCG7SGrZkZixxWpwNCDiwJfh88=
golang.org/x/tools v0.0.0-20190614205625-5aca471b1d59/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc=
google.golang.org/appengine v1.4.0 h1:/wp5JvzpHIxhs/dumFmF7BXTf3Z+dd4uXta4kVyO508=
google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4=
gopkg.in/airbrake/gobrake.v2 v2.0.9 h1:7z2uVWwn7oVeeugY1DtlPAy5H+KYgB1KeKTnqjNatLo=
Expand Down
19 changes: 18 additions & 1 deletion main.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ import (
"github.com/brancz/kube-rbac-proxy/pkg/authn"
"github.com/brancz/kube-rbac-proxy/pkg/authz"
"github.com/brancz/kube-rbac-proxy/pkg/proxy"
rbac_proxy_tls "github.com/brancz/kube-rbac-proxy/pkg/tls"
)

type config struct {
Expand Down Expand Up @@ -233,6 +234,21 @@ func main() {
}

srv.TLSConfig.Certificates = []tls.Certificate{cert}
} else {
glog.Info("Reading certificate files")
ctx, cancel := context.WithCancel(context.Background())
r, err := rbac_proxy_tls.NewCertReloader(cfg.tls.certFile, cfg.tls.keyFile)
if err != nil {
glog.Fatalf("Failed to initialize certificate reloader: %v", err)
}

srv.TLSConfig.GetCertificate = r.GetCertificate

gr.Add(func() error {
return r.Watch(ctx)
}, func(error) {
cancel()
})
}

version, err := tlsVersion(cfg.tls.minVersion)
Expand Down Expand Up @@ -260,7 +276,8 @@ func main() {

gr.Add(func() error {
glog.Infof("Listening securely on %v", cfg.secureListenAddress)
return srv.ServeTLS(l, cfg.tls.certFile, cfg.tls.keyFile)
tlsListener := tls.NewListener(l, srv.TLSConfig)
return srv.Serve(tlsListener)
}, func(err error) {
if err := srv.Shutdown(context.Background()); err != nil {
glog.Errorf("failed to gracefully shutdown server: %v", err)
Expand Down
172 changes: 172 additions & 0 deletions pkg/tls/reloader.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,172 @@
/*
Copyright 2017 Frederic Branczyk 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 tls

import (
"context"
"crypto/tls"
"fmt"
"os"
"path/filepath"
"sync"

"github.com/fsnotify/fsnotify"
"github.com/golang/glog"
)

// CertReloader is the struct that parses a certificate/key pair,
// providing a goroutine safe GetCertificate method to retrieve the parsed content.
//
// The GetCertificate signature is compatible with https://golang.org/pkg/crypto/tls/#Config.GetCertificate
// and can be used to hot-reload a certificate/key pair.
//
// For hot-reloading the Watch method must be started explicitly.
type CertReloader struct {
certPath, keyPath string

// contains the watch targets (keys)
// and the watch locations (values)
watchables map[string]string

mu sync.RWMutex // protects the fields below
cert *tls.Certificate
}

func NewCertReloader(certPath, keyPath string) (*CertReloader, error) {
watchables := make(map[string]string)

w, in, err := newWatchable(certPath)
if err != nil {
return nil, fmt.Errorf("error adding cert watchable: %v", err)
}
watchables[w] = in

w, in, err = newWatchable(keyPath)
if err != nil {
return nil, fmt.Errorf("error adding key watchable: %v", err)
}
watchables[w] = in

r := &CertReloader{
certPath: certPath,
keyPath: keyPath,
watchables: watchables,
}

if err := r.reload(); err != nil {
return nil, fmt.Errorf("error loading certificates: %v", err)
}

return r, nil
}

func newWatchable(target string) (watchable, in string, _ error) {
// simple case: the target is a file.
// in that case we watch for changes in its own directory.
watchable = filepath.Clean(target)
in, _ = filepath.Split(target)
in = filepath.Clean(in)

stat, err := os.Lstat(target)
if err != nil {
return "", "", fmt.Errorf("lstat on %q failed: %v", target, err)
}

// k8s case: the target is a symlink.
// Here, we watch the intermediate symlink (named `..data`)
// in the same directory as the target.
if stat.Mode()&os.ModeSymlink != 0 {
dest, err := os.Readlink(target)
if err != nil {
return "", "", fmt.Errorf("lstat on %q failed: %v", target, err)

}

watchable, _ = filepath.Split(dest)
watchable = filepath.Clean(watchable)
}

return
}

// Watch watches the configured certificate and key path and blocks the current goroutine
// until the scenario context is done or an error occurred during reloading.
func (r *CertReloader) Watch(ctx context.Context) error {
watcher, err := fsnotify.NewWatcher()
if err != nil {
return fmt.Errorf("error creating fsnotify watcher: %v", err)
}

for _, v := range r.watchables {
glog.V(4).Infof("watching: %q", v)

if err := watcher.Add(v); err != nil {
return fmt.Errorf("error adding watchable: %v", err)
}
}

for {
select {
case <-ctx.Done():
return nil

case event := <-watcher.Events:
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I wonder if we, in addition should add a ticker anyways. I am not sure we have 100% guarantees to catch all file system events, cc @lucab.

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Curious: for this very case, why not just read the files once per minute and apply if they changed? For other cases I agree that reloading as quickly as possible when available makes perfect sense, but here we have a lot of time to apply cert rotation anyways no?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

sounds good yes, this will simplify a lot of things and we don't have to think about edge cases 👍 let me implement a ticker-only based approach here and reuse the implemented logic here for prometheus-config-reloader.

glog.V(5).Infof("watcher event %v", event)

if _, ok := r.watchables[filepath.Clean(event.Name)]; !ok {
continue
}

if event.Op&(fsnotify.Write|fsnotify.Create) == 0 {
continue
}

case err := <-watcher.Errors:
glog.Errorf("watch failed: %v", err)
continue
}

if err := r.reload(); err != nil {
return fmt.Errorf("reloading failed: %v", err)
}
}
}

func (r *CertReloader) reload() error {
r.mu.Lock()
defer r.mu.Unlock()

glog.V(4).Info("reloading key ", r.keyPath, " certificate ", r.certPath)

cert, err := tls.LoadX509KeyPair(r.certPath, r.keyPath)
if err != nil {
return fmt.Errorf("error loading certificate: %v", err)
}

r.cert = &cert
return nil
}

// GetCertificate returns the current valid certificate.
// The ClientHello message is ignored
// and is just there to be compatible with https://golang.org/pkg/crypto/tls/#Config.GetCertificate.
func (r *CertReloader) GetCertificate(_ *tls.ClientHelloInfo) (*tls.Certificate, error) {
r.mu.RLock()
defer r.mu.RUnlock()

return r.cert, nil
}
Loading