Skip to content

Commit 08d8a59

Browse files
Network component should refresh certificates if they expire
A single process openshift start node has both kubelet and network. Kubelet rotates its client certs - network does not. Until we split out network we need to do something minimal to ensure the cert is refreshed. Use the same code as the kubelet, but when the cert expires check disk and see if it was refreshed. That should work for bootstrapped environments because the file is updated.
1 parent 7968b96 commit 08d8a59

File tree

2 files changed

+219
-0
lines changed

2 files changed

+219
-0
lines changed

pkg/cmd/server/kubernetes/network/network_config.go

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,16 +3,20 @@ package network
33
import (
44
"fmt"
55
"net"
6+
"time"
67

78
miekgdns "github.com/miekg/dns"
89

10+
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
11+
utilwait "k8s.io/apimachinery/pkg/util/wait"
912
kclientset "k8s.io/client-go/kubernetes"
1013
"k8s.io/kubernetes/pkg/apis/componentconfig"
1114
kclientsetexternal "k8s.io/kubernetes/pkg/client/clientset_generated/clientset"
1215
kclientsetinternal "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset"
1316
kinternalinformers "k8s.io/kubernetes/pkg/client/informers/informers_generated/internalversion"
1417

1518
configapi "github.com/openshift/origin/pkg/cmd/server/api"
19+
"github.com/openshift/origin/pkg/cmd/server/kubernetes/network/transport"
1620
"github.com/openshift/origin/pkg/dns"
1721
"github.com/openshift/origin/pkg/network"
1822
networkclient "github.com/openshift/origin/pkg/network/generated/internalclientset"
@@ -48,6 +52,12 @@ func New(options configapi.NodeConfig, clusterDomain string, proxyConfig *compon
4852
if err != nil {
4953
return nil, err
5054
}
55+
// if a client cert is specified, when the certificate expires attempt to refresh it from disk
56+
if len(kubeConfig.TLSClientConfig.KeyFile) > 0 && len(kubeConfig.TLSClientConfig.CertFile) > 0 {
57+
if err := transport.RefreshCertificateAfterExpiry(utilwait.NeverStop, 10*time.Second, kubeConfig); err != nil {
58+
utilruntime.HandleError(fmt.Errorf("Unable to enable client certificate rotation for network components: %v", err))
59+
}
60+
}
5161
internalKubeClient, err := kclientsetinternal.NewForConfig(kubeConfig)
5262
if err != nil {
5363
return nil, err
Lines changed: 209 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,209 @@
1+
/*
2+
Copyright 2017 The Kubernetes Authors.
3+
4+
Licensed under the Apache License, Version 2.0 (the "License");
5+
you may not use this file except in compliance with the License.
6+
You may obtain a copy of the License at
7+
8+
http://www.apache.org/licenses/LICENSE-2.0
9+
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
15+
*/
16+
17+
// Extracted from k8s.io/kubernetes/pkg/kubelet/certificate/transport.go, will be removed
18+
// when openshift-sdn and the network components move out of the Kubelet. Is intended ONLY
19+
// to provide certificate rollover until 3.8/3.9.
20+
package transport
21+
22+
import (
23+
"context"
24+
"crypto/tls"
25+
"fmt"
26+
"net"
27+
"net/http"
28+
"sync"
29+
"time"
30+
31+
"github.com/golang/glog"
32+
33+
utilnet "k8s.io/apimachinery/pkg/util/net"
34+
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
35+
"k8s.io/apimachinery/pkg/util/wait"
36+
restclient "k8s.io/client-go/rest"
37+
)
38+
39+
// RefreshCertificateAfterExpiry instruments a restconfig with a transport that checks
40+
// disk to reload expired certificates.
41+
//
42+
// The config must not already provide an explicit transport.
43+
//
44+
// The returned transport periodically checks the manager to determine if the
45+
// certificate has changed. If it has, the transport shuts down all existing client
46+
// connections, forcing the client to re-handshake with the server and use the
47+
// new certificate.
48+
//
49+
// stopCh should be used to indicate when the transport is unused and doesn't need
50+
// to continue checking the manager.
51+
func RefreshCertificateAfterExpiry(stopCh <-chan struct{}, period time.Duration, clientConfig *restclient.Config) error {
52+
if clientConfig.Transport != nil {
53+
return fmt.Errorf("there is already a transport configured")
54+
}
55+
tlsConfig, err := restclient.TLSConfigFor(clientConfig)
56+
if err != nil {
57+
return fmt.Errorf("unable to configure TLS for the rest client: %v", err)
58+
}
59+
if tlsConfig == nil {
60+
tlsConfig = &tls.Config{}
61+
}
62+
manager := &certificateManager{config: *clientConfig, minimumRefresh: period}
63+
tlsConfig.Certificates = nil
64+
tlsConfig.GetClientCertificate = func(requestInfo *tls.CertificateRequestInfo) (*tls.Certificate, error) {
65+
cert := manager.Current()
66+
if cert == nil {
67+
return &tls.Certificate{Certificate: nil}, nil
68+
}
69+
return cert, nil
70+
}
71+
72+
// Custom dialer that will track all connections it creates.
73+
t := &connTracker{
74+
dialer: &net.Dialer{Timeout: 30 * time.Second, KeepAlive: 30 * time.Second},
75+
conns: make(map[*closableConn]struct{}),
76+
}
77+
78+
lastCert := manager.Current()
79+
go wait.Until(func() {
80+
curr := manager.Current()
81+
if curr == nil || lastCert == curr {
82+
// Cert hasn't been rotated.
83+
return
84+
}
85+
lastCert = curr
86+
87+
glog.Infof("certificate rotation detected, shutting down client connections to start using new credentials")
88+
// The cert has been rotated. Close all existing connections to force the client
89+
// to reperform its TLS handshake with new cert.
90+
//
91+
// See: https://github.com/kubernetes-incubator/bootkube/pull/663#issuecomment-318506493
92+
t.closeAllConns()
93+
}, period, stopCh)
94+
95+
clientConfig.Transport = utilnet.SetTransportDefaults(&http.Transport{
96+
Proxy: http.ProxyFromEnvironment,
97+
TLSHandshakeTimeout: 10 * time.Second,
98+
TLSClientConfig: tlsConfig,
99+
MaxIdleConnsPerHost: 25,
100+
DialContext: t.DialContext, // Use custom dialer.
101+
})
102+
103+
// Zero out all existing TLS options since our new transport enforces them.
104+
clientConfig.CertData = nil
105+
clientConfig.KeyData = nil
106+
clientConfig.CertFile = ""
107+
clientConfig.KeyFile = ""
108+
clientConfig.CAData = nil
109+
clientConfig.CAFile = ""
110+
clientConfig.Insecure = false
111+
return nil
112+
}
113+
114+
// certificateManager reloads the requested certificate from disk when requested.
115+
type certificateManager struct {
116+
config restclient.Config
117+
minimumRefresh time.Duration
118+
119+
lock sync.Mutex
120+
cert *tls.Certificate
121+
lastCheck time.Time
122+
}
123+
124+
// Current retrieves the latest certificate from disk if it exists, or nil if
125+
// no certificate could be found. The last successfully loaded certificate will be
126+
// returned.
127+
func (m *certificateManager) Current() *tls.Certificate {
128+
m.lock.Lock()
129+
defer m.lock.Unlock()
130+
131+
// check whether the cert has expired and whether we've waited long enough since our last
132+
// check to look again
133+
cert := m.cert
134+
if cert != nil {
135+
now := time.Now()
136+
if now.After(m.cert.Leaf.NotAfter) {
137+
if now.Sub(m.lastCheck) > m.minimumRefresh {
138+
cert = nil
139+
m.lastCheck = now
140+
}
141+
}
142+
}
143+
144+
// load the cert from disk
145+
if cert == nil {
146+
c, err := tls.LoadX509KeyPair(m.config.CertFile, m.config.KeyFile)
147+
if err != nil {
148+
utilruntime.HandleError(fmt.Errorf("Unable to load client certificate key pair from disk: %v", err))
149+
return nil
150+
}
151+
m.cert = &c
152+
}
153+
return m.cert
154+
}
155+
156+
// connTracker is a dialer that tracks all open connections it creates.
157+
type connTracker struct {
158+
dialer *net.Dialer
159+
160+
mu sync.Mutex
161+
conns map[*closableConn]struct{}
162+
}
163+
164+
// closeAllConns forcibly closes all tracked connections.
165+
func (c *connTracker) closeAllConns() {
166+
c.mu.Lock()
167+
conns := c.conns
168+
c.conns = make(map[*closableConn]struct{})
169+
c.mu.Unlock()
170+
171+
for conn := range conns {
172+
conn.Close()
173+
}
174+
}
175+
176+
func (c *connTracker) DialContext(ctx context.Context, network, address string) (net.Conn, error) {
177+
conn, err := c.dialer.DialContext(ctx, network, address)
178+
if err != nil {
179+
return nil, err
180+
}
181+
182+
closable := &closableConn{Conn: conn}
183+
184+
// Start tracking the connection
185+
c.mu.Lock()
186+
c.conns[closable] = struct{}{}
187+
c.mu.Unlock()
188+
189+
// When the connection is closed, remove it from the map. This will
190+
// be no-op if the connection isn't in the map, e.g. if closeAllConns()
191+
// is called.
192+
closable.onClose = func() {
193+
c.mu.Lock()
194+
delete(c.conns, closable)
195+
c.mu.Unlock()
196+
}
197+
198+
return closable, nil
199+
}
200+
201+
type closableConn struct {
202+
onClose func()
203+
net.Conn
204+
}
205+
206+
func (c *closableConn) Close() error {
207+
go c.onClose()
208+
return c.Conn.Close()
209+
}

0 commit comments

Comments
 (0)