-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
584 lines (486 loc) · 12 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
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"
"github.com/hashicorp/golang-lru"
"github.com/rancher/norman/types/set"
"github.com/rancher/norman/types/slice"
"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"
)
type ListenConfigStorage interface {
Update(*v3.ListenConfig) (*v3.ListenConfig, error)
Get(namespace, name string) (*v3.ListenConfig, 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) *Server {
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{}
for key, cert := range s.certs {
certs[key] = certToString(cert)
}
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 {
return serverNameCert, nil
}
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 {
conf := &tls.Config{
GetCertificate: s.getCertificate,
PreferServerCipherSuites: true,
}
listener, err := s.newListener(s.httpsPort, conf)
if err != nil {
return err
}
server := &http.Server{
Handler: s.Handler(),
ErrorLog: log.New(logrus.StandardLogger().Writer(), "", 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(logrus.StandardLogger().Writer(), "", 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) {
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 {
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"},
}
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
}