forked from rancher/rancher
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
710 lines (602 loc) · 17 KB
/
server.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
package dynamiclistener
import (
"context"
"crypto/md5"
"crypto/rsa"
"crypto/tls"
"crypto/x509"
"encoding/base64"
"encoding/hex"
"errors"
"fmt"
"log"
"net"
"net/http"
"reflect"
"sort"
"strconv"
"strings"
"sync"
"time"
lru "github.com/hashicorp/golang-lru"
"github.com/rancher/norman/types/set"
"github.com/rancher/norman/types/slice"
"github.com/rancher/rancher/pkg/settings"
v3 "github.com/rancher/types/apis/management.cattle.io/v3"
"github.com/sirupsen/logrus"
"golang.org/x/crypto/acme/autocert"
"k8s.io/client-go/util/cert"
)
const (
httpsMode = "https"
acmeMode = "acme"
)
var (
tlsVersions = map[string]uint16{
"1.2": tls.VersionTLS12,
"1.1": tls.VersionTLS11,
"1.0": tls.VersionTLS10,
}
// https://golang.org/pkg/crypto/tls/#pkg-constants
tlsCipherSuites = map[string]uint16{
"TLS_RSA_WITH_RC4_128_SHA": tls.TLS_RSA_WITH_RC4_128_SHA,
"TLS_RSA_WITH_3DES_EDE_CBC_SHA": tls.TLS_RSA_WITH_3DES_EDE_CBC_SHA,
"TLS_RSA_WITH_AES_128_CBC_SHA": tls.TLS_RSA_WITH_AES_128_CBC_SHA,
"TLS_RSA_WITH_AES_256_CBC_SHA": tls.TLS_RSA_WITH_AES_256_CBC_SHA,
"TLS_RSA_WITH_AES_128_CBC_SHA256": tls.TLS_RSA_WITH_AES_128_CBC_SHA256,
"TLS_RSA_WITH_AES_128_GCM_SHA256": tls.TLS_RSA_WITH_AES_128_GCM_SHA256,
"TLS_RSA_WITH_AES_256_GCM_SHA384": tls.TLS_RSA_WITH_AES_256_GCM_SHA384,
"TLS_ECDHE_ECDSA_WITH_RC4_128_SHA": tls.TLS_ECDHE_ECDSA_WITH_RC4_128_SHA,
"TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA": tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
"TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA": tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
"TLS_ECDHE_RSA_WITH_RC4_128_SHA": tls.TLS_ECDHE_RSA_WITH_RC4_128_SHA,
"TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA": tls.TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA,
"TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA": tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
"TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA": tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
"TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256": tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256,
"TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256": tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256,
"TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256": tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
"TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256": tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
"TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384": tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
"TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384": tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
"TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305": tls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
"TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305": tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
}
)
type ListenConfigStorage interface {
Update(*v3.ListenConfig) (*v3.ListenConfig, error)
Get(namespace, name string) (*v3.ListenConfig, error)
}
type ServerInterface interface {
Disable(config *v3.ListenConfig)
Enable(config *v3.ListenConfig) (bool, error)
Shutdown() error
}
type Server struct {
sync.Mutex
listenConfigStorage ListenConfigStorage
handler http.Handler
httpPort, httpsPort int
certs map[string]*tls.Certificate
ips *lru.Cache
listeners []net.Listener
servers []*http.Server
activeConfig *v3.ListenConfig
activeMode string
// dynamic config change on refresh
activeCert *tls.Certificate
activeCA *x509.Certificate
activeCAKey *rsa.PrivateKey
domains map[string]bool
tos []string
tosAll bool
}
func NewServer(ctx context.Context, listenConfigStorage ListenConfigStorage,
handler http.Handler, httpPort, httpsPort int) ServerInterface {
s := &Server{
listenConfigStorage: listenConfigStorage,
handler: handler,
httpPort: httpPort,
httpsPort: httpsPort,
certs: map[string]*tls.Certificate{},
}
s.ips, _ = lru.New(20)
go s.start(ctx)
return s
}
func (s *Server) updateIPs(savedIPs map[string]bool) map[string]bool {
if s.activeCert != nil || s.activeConfig == nil {
return savedIPs
}
cfg, err := s.listenConfigStorage.Get("", s.activeConfig.Name)
if err != nil {
return savedIPs
}
certs := map[string]string{}
s.Lock()
for key, cert := range s.certs {
certs[key] = certToString(cert)
}
s.Unlock()
if !reflect.DeepEqual(certs, cfg.GeneratedCerts) {
cfg = cfg.DeepCopy()
cfg.GeneratedCerts = certs
cfg, err = s.listenConfigStorage.Update(cfg)
if err != nil {
return savedIPs
}
}
allIPs := map[string]bool{}
for _, k := range s.ips.Keys() {
s, ok := k.(string)
if ok {
allIPs[s] = true
}
}
a, b, _ := set.Diff(allIPs, savedIPs)
if len(a) == 0 && len(b) == 0 {
return savedIPs
}
cfg.KnownIPs = nil
for k := range allIPs {
cfg = cfg.DeepCopy()
cfg.KnownIPs = append(cfg.KnownIPs, k)
}
_, err = s.listenConfigStorage.Update(cfg)
if err != nil {
return savedIPs
}
return allIPs
}
func (s *Server) start(ctx context.Context) {
savedIPs := map[string]bool{}
for {
savedIPs = s.updateIPs(savedIPs)
select {
case <-ctx.Done():
return
case <-time.After(5 * time.Second):
}
}
}
func (s *Server) Disable(config *v3.ListenConfig) {
if s.activeConfig == nil {
return
}
if s.activeConfig.UID == config.UID {
s.activeConfig = nil
}
}
func (s *Server) Enable(config *v3.ListenConfig) (bool, error) {
s.Lock()
defer s.Unlock()
if s.activeConfig != nil && s.activeConfig.CreationTimestamp.Before(&config.CreationTimestamp) {
return false, nil
}
s.domains = map[string]bool{}
for _, d := range config.Domains {
s.domains[d] = true
}
s.tos = config.TOS
s.tosAll = len(config.TOS) == 0 || slice.ContainsString(config.TOS, "auto")
if config.Key != "" && config.Cert != "" {
cert, err := tls.X509KeyPair([]byte(config.Cert), []byte(config.Key))
if err != nil {
return false, err
}
s.activeCert = &cert
}
if config.CACert != "" && config.CAKey != "" {
cert, err := tls.X509KeyPair([]byte(config.CACert), []byte(config.CAKey))
if err != nil {
return false, err
}
s.activeCAKey = cert.PrivateKey.(*rsa.PrivateKey)
x509Cert, err := x509.ParseCertificate(cert.Certificate[0])
if err != nil {
return false, err
}
s.activeCA = x509Cert
}
if s.activeConfig == nil || config.Mode != s.activeMode {
return true, s.reload(config)
}
return true, nil
}
func (s *Server) hostPolicy(ctx context.Context, host string) error {
s.Lock()
defer s.Unlock()
if s.domains[host] {
return nil
}
return errors.New("acme/autocert: host not configured")
}
func (s *Server) prompt(tos string) bool {
s.Lock()
defer s.Unlock()
if s.tosAll {
return true
}
return slice.ContainsString(s.tos, tos)
}
func (s *Server) Shutdown() error {
for _, listener := range s.listeners {
if err := listener.Close(); err != nil {
return err
}
}
s.listeners = nil
for _, server := range s.servers {
go server.Shutdown(context.Background())
}
s.servers = nil
return nil
}
func (s *Server) reload(config *v3.ListenConfig) error {
if err := s.Shutdown(); err != nil {
return err
}
switch config.Mode {
case acmeMode:
if err := s.serveACME(config); err != nil {
return err
}
case httpsMode:
if err := s.serveHTTPS(config); err != nil {
return err
}
}
for _, ipStr := range config.KnownIPs {
ip := net.ParseIP(ipStr)
if len(ip) > 0 {
s.ips.ContainsOrAdd(ipStr, ip)
}
}
for key, certString := range config.GeneratedCerts {
cert := stringToCert(certString)
if cert != nil {
s.certs[key] = cert
}
}
s.activeMode = config.Mode
s.activeConfig = config
return nil
}
func (s *Server) ipMapKey() string {
len := s.ips.Len()
keys := s.ips.Keys()
if len == 0 {
return fmt.Sprintf("local/%d", len)
} else if len == 1 {
return fmt.Sprintf("local/%s", keys[0])
}
sort.Slice(keys, func(i, j int) bool {
l, _ := keys[i].(string)
r, _ := keys[j].(string)
return l < r
})
if len < 6 {
return fmt.Sprintf("local/%v", keys)
}
digest := md5.New()
for _, k := range keys {
s, _ := k.(string)
digest.Write([]byte(s))
}
return fmt.Sprintf("local/%v", hex.EncodeToString(digest.Sum(nil)))
}
func (s *Server) getCertificate(hello *tls.ClientHelloInfo) (*tls.Certificate, error) {
s.Lock()
defer s.Unlock()
if s.activeCert != nil {
return s.activeCert, nil
}
mapKey := hello.ServerName
cn := hello.ServerName
dnsNames := []string{cn}
ipBased := false
var ips []net.IP
if cn == "" {
mapKey = s.ipMapKey()
ipBased = true
}
serverNameCert, ok := s.certs[mapKey]
if ok {
// check expiry time
certParsed, err := x509.ParseCertificate(serverNameCert.Certificate[0])
if err != nil {
logrus.Errorf("Error parsing cert: %v", err)
}
expiryTime := certParsed.NotAfter
currentTime := time.Now().UTC()
rotateBeforeStr := settings.RotateCertsIfExpiringInDays.Get()
rotateBefore, err := strconv.ParseInt(rotateBeforeStr, 10, 64)
if err != nil {
rotateBefore = 7
logrus.Errorf("Error in converting rotate cert setting: %v", err)
}
if expiryTime.Sub(currentTime) > (time.Hour * 24 * time.Duration(rotateBefore)) {
return serverNameCert, nil
}
logrus.Infof("Rancher server cert expires at %v, generating new cert", expiryTime)
}
if ipBased {
cn = "cattle"
for _, ipStr := range s.ips.Keys() {
ip := net.ParseIP(ipStr.(string))
if len(ip) > 0 {
ips = append(ips, ip)
}
}
}
cfg := cert.Config{
CommonName: cn,
Organization: s.activeCA.Subject.Organization,
Usages: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
AltNames: cert.AltNames{
DNSNames: dnsNames,
IPs: ips,
},
}
key, err := cert.NewPrivateKey()
if err != nil {
return nil, err
}
cert, err := cert.NewSignedCert(cfg, key, s.activeCA, s.activeCAKey)
if err != nil {
return nil, err
}
tlsCert := &tls.Certificate{
Certificate: [][]byte{
cert.Raw,
},
PrivateKey: key,
}
s.certs[mapKey] = tlsCert
return tlsCert, nil
}
func (s *Server) cacheIPHandler(handler http.Handler) http.Handler {
return http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) {
h, _, err := net.SplitHostPort(req.Host)
if err != nil {
h = req.Host
}
ip := net.ParseIP(h)
if len(ip) > 0 {
s.ips.ContainsOrAdd(h, ip)
}
handler.ServeHTTP(resp, req)
})
}
func (s *Server) serveHTTPS(config *v3.ListenConfig) error {
// Get configured minimal tls version
TLSMinVersion, err := lookupTLSVersion()
if err != nil {
return fmt.Errorf("Error while configuring minimal TLS version: %s", err)
}
// Get configured tls ciphers
TLSCiphers, err := lookupTLSCiphers()
if err != nil {
return fmt.Errorf("Error while configuring TLS ciphers: %s", err)
}
conf := &tls.Config{
GetCertificate: s.getCertificate,
PreferServerCipherSuites: true,
MinVersion: TLSMinVersion,
CipherSuites: TLSCiphers,
}
listener, err := s.newListener(s.httpsPort, conf)
if err != nil {
return err
}
logger := logrus.StandardLogger()
server := &http.Server{
Handler: s.Handler(),
ErrorLog: log.New(logger.WriterLevel(logrus.DebugLevel), "", log.LstdFlags),
}
if s.activeConfig == nil {
server.Handler = s.cacheIPHandler(server.Handler)
}
s.servers = append(s.servers, server)
s.startServer(listener, server)
httpListener, err := s.newListener(s.httpPort, nil)
if err != nil {
return err
}
httpServer := &http.Server{
Handler: httpRedirect(s.Handler()),
ErrorLog: log.New(logger.WriterLevel(logrus.DebugLevel), "", log.LstdFlags),
}
if s.activeConfig == nil {
httpServer.Handler = s.cacheIPHandler(httpServer.Handler)
}
s.servers = append(s.servers, httpServer)
s.startServer(httpListener, httpServer)
return nil
}
// Approach taken from letsencrypt, except manglePort is specific to us
func httpRedirect(next http.Handler) http.Handler {
return http.HandlerFunc(
func(rw http.ResponseWriter, r *http.Request) {
// In case a check requires HTTP 200 instead of HTTP 302
if strings.HasPrefix(r.URL.Path, "/ping") || strings.HasPrefix(r.URL.Path, "/healthz") {
next.ServeHTTP(rw, r)
return
}
if r.Header.Get("x-Forwarded-Proto") == "https" {
next.ServeHTTP(rw, r)
return
}
if r.Method != "GET" && r.Method != "HEAD" {
http.Error(rw, "Use HTTPS", http.StatusBadRequest)
return
}
target := "https://" + manglePort(r.Host) + r.URL.RequestURI()
http.Redirect(rw, r, target, http.StatusFound)
})
}
func manglePort(hostport string) string {
host, port, err := net.SplitHostPort(hostport)
if err != nil {
return hostport
}
portInt, err := strconv.Atoi(port)
if err != nil {
return hostport
}
portInt = ((portInt / 1000) * 1000) + 443
return net.JoinHostPort(host, strconv.Itoa(portInt))
}
func (s *Server) startServer(listener net.Listener, server *http.Server) {
go func() {
if err := server.Serve(listener); err != nil {
logrus.Errorf("server on %v returned err: %v", listener.Addr(), err)
}
}()
}
func (s *Server) Handler() http.Handler {
return s.handler
}
func (s *Server) newListener(port int, config *tls.Config) (net.Listener, error) {
addr := fmt.Sprintf(":%d", port)
l, err := net.Listen("tcp", addr)
if err != nil {
return nil, err
}
l = tcpKeepAliveListener{l.(*net.TCPListener)}
if config != nil {
l = tls.NewListener(l, config)
}
s.listeners = append(s.listeners, l)
logrus.Info("Listening on ", addr)
return l, nil
}
func (s *Server) serveACME(config *v3.ListenConfig) error {
// Get configured minimal tls version
TLSMinVersion, err := lookupTLSVersion()
if err != nil {
return fmt.Errorf("Error while configuring minimal TLS version: %s", err)
}
// Get configured tls ciphers
TLSCiphers, err := lookupTLSCiphers()
if err != nil {
return fmt.Errorf("Error while configuring TLS ciphers: %s", err)
}
manager := autocert.Manager{
Cache: autocert.DirCache("certs-cache"),
Prompt: s.prompt,
HostPolicy: s.hostPolicy,
}
conf := &tls.Config{
GetCertificate: func(hello *tls.ClientHelloInfo) (*tls.Certificate, error) {
if hello.ServerName == "localhost" || hello.ServerName == "" {
newHello := *hello
newHello.ServerName = config.Domains[0]
return manager.GetCertificate(&newHello)
}
return manager.GetCertificate(hello)
},
NextProtos: []string{"h2", "http/1.1"},
PreferServerCipherSuites: true,
MinVersion: TLSMinVersion,
CipherSuites: TLSCiphers,
}
httpsListener, err := s.newListener(s.httpsPort, conf)
if err != nil {
return err
}
httpListener, err := s.newListener(s.httpPort, nil)
if err != nil {
return err
}
httpServer := &http.Server{
Handler: manager.HTTPHandler(nil),
ErrorLog: log.New(logrus.StandardLogger().Writer(), "", log.LstdFlags),
}
s.servers = append(s.servers, httpServer)
go func() {
if err := httpServer.Serve(httpListener); err != nil {
logrus.Errorf("http server returned err: %v", err)
}
}()
httpsServer := &http.Server{
Handler: s.Handler(),
ErrorLog: log.New(logrus.StandardLogger().Writer(), "", log.LstdFlags),
}
s.servers = append(s.servers, httpsServer)
go func() {
if err := httpsServer.Serve(httpsListener); err != nil {
logrus.Errorf("https server returned err: %v", err)
}
}()
return nil
}
func stringToCert(certString string) *tls.Certificate {
parts := strings.Split(certString, "#")
if len(parts) != 2 {
return nil
}
cert, key := parts[0], parts[1]
keyBytes, err := base64.StdEncoding.DecodeString(key)
if err != nil {
return nil
}
rsaKey, err := x509.ParsePKCS1PrivateKey(keyBytes)
if err != nil {
return nil
}
certBytes, err := base64.StdEncoding.DecodeString(cert)
if err != nil {
return nil
}
return &tls.Certificate{
Certificate: [][]byte{certBytes},
PrivateKey: rsaKey,
}
}
func certToString(cert *tls.Certificate) string {
certString := base64.StdEncoding.EncodeToString(cert.Certificate[0])
keyString := base64.StdEncoding.EncodeToString(x509.MarshalPKCS1PrivateKey(cert.PrivateKey.(*rsa.PrivateKey)))
return certString + "#" + keyString
}
type tcpKeepAliveListener struct {
*net.TCPListener
}
func (ln tcpKeepAliveListener) Accept() (c net.Conn, err error) {
tc, err := ln.AcceptTCP()
if err != nil {
return
}
tc.SetKeepAlive(true)
tc.SetKeepAlivePeriod(3 * time.Minute)
return tc, nil
}
func lookupTLSVersion() (uint16, error) {
tlsVersionKeys := getKeysFromMap(tlsVersions)
settingsTLSMinVersion := settings.TLSMinVersion.Get()
if val, ok := tlsVersions[settingsTLSMinVersion]; ok {
return val, nil
}
return 0, fmt.Errorf("Invalid minimal TLS version [%s], must be one of: %s", settingsTLSMinVersion, strings.Join(tlsVersionKeys, " "))
}
func lookupTLSCiphers() ([]uint16, error) {
tlsCipherSuitesKeys := getKeysFromMap(tlsCipherSuites)
settingsTLSCiphers := settings.TLSCiphers.Get()
sliceTLSCiphers := strings.Split(settingsTLSCiphers, ",")
var TLSCiphers []uint16
for _, TLSCipher := range sliceTLSCiphers {
val, ok := tlsCipherSuites[strings.TrimSpace(TLSCipher)]
if !ok {
return []uint16{}, fmt.Errorf("Unsupported cipher [%s], must be one or more from: %s", TLSCipher, strings.Join(tlsCipherSuitesKeys, " "))
}
TLSCiphers = append(TLSCiphers, val)
}
return TLSCiphers, nil
}
func getKeysFromMap(input map[string]uint16) []string {
var keys []string
for key := range input {
keys = append(keys, key)
}
return keys
}