-
Notifications
You must be signed in to change notification settings - Fork 130
/
config.go
670 lines (585 loc) · 22.4 KB
/
config.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
/*
Copyright NetFoundry Inc.
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
https://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 controller
import (
"bytes"
"crypto/tls"
"crypto/x509"
"fmt"
"github.com/hashicorp/go-hclog"
"github.com/michaelquigley/pfxlog"
"github.com/openziti/channel/v2"
"github.com/openziti/identity"
"github.com/openziti/storage/boltz"
"github.com/openziti/transport/v2"
transporttls "github.com/openziti/transport/v2/tls"
"github.com/openziti/ziti/common/config"
"github.com/openziti/ziti/common/pb/ctrl_pb"
"github.com/openziti/ziti/common/pb/mgmt_pb"
"github.com/openziti/ziti/controller/command"
"github.com/openziti/ziti/controller/db"
"github.com/openziti/ziti/controller/network"
"github.com/openziti/ziti/controller/raft"
"github.com/openziti/ziti/router/xgress"
"github.com/pkg/errors"
"gopkg.in/yaml.v2"
"math"
"os"
"strings"
"time"
)
const (
DefaultProfileMemoryInterval = 15 * time.Second
DefaultHealthChecksBoltCheckInterval = 30 * time.Second
DefaultHealthChecksBoltCheckTimeout = 20 * time.Second
DefaultHealthChecksBoltCheckInitialDelay = 30 * time.Second
DefaultRaftCommandHandlerMaxQueueSize = 1000
// DefaultTlsHandshakeRateLimiterEnabled is whether the tls handshake rate limiter is enabled by default
DefaultTlsHandshakeRateLimiterEnabled = false
// TlsHandshakeRateLimiterMinSizeValue is the minimum size that can be configured for the tls handshake rate limiter
// window range
TlsHandshakeRateLimiterMinSizeValue = 5
// TlsHandshakeRateLimiterMaxSizeValue is the maximum size that can be configured for the tls handshake rate limiter
// window range
TlsHandshakeRateLimiterMaxSizeValue = 10000
// TlsHandshakeRateLimiterMetricOutstandingCount is the name of the metric tracking how many tasks are in process
TlsHandshakeRateLimiterMetricOutstandingCount = "tls_handshake_limiter.in_process"
// TlsHandshakeRateLimiterMetricCurrentWindowSize is the name of the metric tracking the current window size
TlsHandshakeRateLimiterMetricCurrentWindowSize = "tls_handshake_limiter.window_size"
// TlsHandshakeRateLimiterMetricWorkTimer is the name of the metric tracking how long successful tasks are taking to complete
TlsHandshakeRateLimiterMetricWorkTimer = "tls_handshake_limiter.work_timer"
// DefaultTlsHandshakeRateLimiterMaxWindow is the default max size for the tls handshake rate limiter
DefaultTlsHandshakeRateLimiterMaxWindow = 1000
)
type Config struct {
Id *identity.TokenId
Raft *raft.Config
Network *network.Options
Db boltz.Db
Trace struct {
Handler *channel.TraceHandler
}
Profile struct {
Memory struct {
Path string
Interval time.Duration
}
CPU struct {
Path string
}
}
Ctrl struct {
Listener transport.Address
Options *CtrlOptions
}
HealthChecks struct {
BoltCheck struct {
Interval time.Duration
Timeout time.Duration
InitialDelay time.Duration
}
}
CommandRateLimiter command.RateLimiterConfig
TlsHandshakeRateLimiter command.AdaptiveRateLimiterConfig
src map[interface{}]interface{}
}
// CtrlOptions extends channel.Options to include support for additional, non-channel specific options
// (e.g. NewListener)
type CtrlOptions struct {
*channel.Options
NewListener *transport.Address
AdvertiseAddress *transport.Address
RouterHeartbeatOptions *channel.HeartbeatOptions
PeerHeartbeatOptions *channel.HeartbeatOptions
}
func (config *Config) Configure(sub config.Subconfig) error {
return sub.LoadConfig(config.src)
}
func LoadConfig(path string) (*Config, error) {
cfgBytes, err := os.ReadFile(path)
if err != nil {
return nil, err
}
cfgmap := make(map[interface{}]interface{})
if err = yaml.NewDecoder(bytes.NewReader(cfgBytes)).Decode(&cfgmap); err != nil {
return nil, err
}
config.InjectEnv(cfgmap)
if value, found := cfgmap["v"]; found {
if value.(int) != 3 {
panic("config version mismatch: see docs for information on config updates")
}
} else {
panic("no config version: see docs for information on config")
}
var identityConfig *identity.Config
if value, found := cfgmap["identity"]; found {
subMap := value.(map[interface{}]interface{})
identityConfig, err = identity.NewConfigFromMapWithPathContext(subMap, "identity")
if err != nil {
return nil, fmt.Errorf("could not parse root identity: %v", err)
}
if identityConfig.ServerCert == "" && identityConfig.ServerKey == "" {
identityConfig.ServerCert = identityConfig.Cert
identityConfig.ServerKey = identityConfig.Key
}
} else {
return nil, fmt.Errorf("identity section not found")
}
controllerConfig := &Config{
Network: network.DefaultOptions(),
src: cfgmap,
}
if id, err := identity.LoadIdentity(*identityConfig); err != nil {
return nil, fmt.Errorf("unable to load identity (%s)", err)
} else {
controllerConfig.Id = identity.NewIdentity(id)
if err := controllerConfig.Id.WatchFiles(); err != nil {
pfxlog.Logger().Warn("could not enable file watching on identity: %w", err)
}
}
if value, found := cfgmap["network"]; found {
if submap, ok := value.(map[interface{}]interface{}); ok {
if options, err := network.LoadOptions(submap); err == nil {
controllerConfig.Network = options
} else {
return nil, fmt.Errorf("invalid 'network' stanza (%s)", err)
}
} else {
pfxlog.Logger().Warn("invalid or empty 'network' stanza")
}
}
if value, found := cfgmap["raft"]; found {
if submap, ok := value.(map[interface{}]interface{}); ok {
controllerConfig.Raft = &raft.Config{}
controllerConfig.Raft.CommandHandlerOptions.MaxQueueSize = DefaultRaftCommandHandlerMaxQueueSize
if value, found := submap["dataDir"]; found {
controllerConfig.Raft.DataDir = value.(string)
} else {
return nil, errors.Errorf("raft dataDir configuration missing")
}
if value, found := submap["minClusterSize"]; found {
controllerConfig.Raft.MinClusterSize = uint32(value.(int))
}
if value, found := submap["bootstrapMembers"]; found {
if lst, ok := value.([]interface{}); ok {
for idx, val := range lst {
if member, ok := val.(string); ok {
controllerConfig.Raft.BootstrapMembers = append(controllerConfig.Raft.BootstrapMembers, member)
} else {
return nil, errors.Errorf("invalid bootstrapMembers value '%v'at index %v, should be array", idx, val)
}
}
} else {
return nil, errors.New("invalid bootstrapMembers value, should be array")
}
}
if value, found := submap["snapshotInterval"]; found {
if val, err := time.ParseDuration(fmt.Sprintf("%v", value)); err == nil {
controllerConfig.Raft.SnapshotInterval = &val
} else {
return nil, errors.Wrapf(err, "failed to parse raft.snapshotInterval value '%v", value)
}
}
if value, found := submap["commitTimeout"]; found {
if val, err := time.ParseDuration(fmt.Sprintf("%v", value)); err == nil {
controllerConfig.Raft.CommitTimeout = &val
} else {
return nil, errors.Wrapf(err, "failed to parse raft.commitTimeout value '%v", value)
}
}
if value, found := submap["electionTimeout"]; found {
if val, err := time.ParseDuration(fmt.Sprintf("%v", value)); err == nil {
controllerConfig.Raft.ElectionTimeout = &val
} else {
return nil, errors.Wrapf(err, "failed to parse raft.electionTimeout value '%v", value)
}
}
if value, found := submap["heartbeatTimeout"]; found {
if val, err := time.ParseDuration(fmt.Sprintf("%v", value)); err == nil {
controllerConfig.Raft.HeartbeatTimeout = &val
} else {
return nil, errors.Wrapf(err, "failed to parse raft.heartbeatTimeout value '%v", value)
}
}
if value, found := submap["leaderLeaseTimeout"]; found {
if val, err := time.ParseDuration(fmt.Sprintf("%v", value)); err == nil {
controllerConfig.Raft.LeaderLeaseTimeout = &val
} else {
return nil, errors.Wrapf(err, "failed to parse raft.leaderLeaseTimeout value '%v", value)
}
}
if value, found := submap["snapshotThreshold"]; found {
val := uint32(value.(int))
controllerConfig.Raft.SnapshotThreshold = &val
}
if value, found := submap["maxAppendEntries"]; found {
val := uint32(value.(int))
controllerConfig.Raft.MaxAppendEntries = &val
}
if value, found := submap["trailingLogs"]; found {
val := uint32(value.(int))
controllerConfig.Raft.TrailingLogs = &val
}
if value, found := submap["logLevel"]; found {
val := fmt.Sprintf("%v", value)
if hclog.LevelFromString(val) == hclog.NoLevel {
return nil, errors.Errorf("invalid value for raft.logLevel [%v]", val)
}
controllerConfig.Raft.LogLevel = &val
}
if value, found := submap["logFile"]; found {
val := fmt.Sprintf("%v", value)
options := *hclog.DefaultOptions
f, err := os.Create(val)
if err != nil {
return nil, errors.Wrapf(err, "unable to open raft log file [%v]", val)
}
options.Output = f
if controllerConfig.Raft.LogLevel != nil {
options.Level = hclog.LevelFromString(*controllerConfig.Raft.LogLevel)
}
controllerConfig.Raft.Logger = hclog.New(&options)
}
if value, found := cfgmap["commandHandler"]; found {
if chSubMap, ok := value.(map[interface{}]interface{}); ok {
if value, found := chSubMap["maxQueueSize"]; found {
controllerConfig.Raft.CommandHandlerOptions.MaxQueueSize = uint16(value.(int))
}
} else {
return nil, errors.New("invalid commandHandler value, should be map")
}
}
} else {
return nil, errors.Errorf("invalid raft configuration")
}
} else if value, found := cfgmap["db"]; found {
str, err := db.Open(value.(string))
if err != nil {
return nil, err
}
controllerConfig.Db = str
} else {
panic("controllerConfig must provide [db] or [raft]")
}
if value, found := cfgmap["trace"]; found {
if submap, ok := value.(map[interface{}]interface{}); ok {
if value, found := submap["path"]; found {
handler, err := channel.NewTraceHandler(value.(string), controllerConfig.Id.Token)
if err != nil {
return nil, err
}
handler.AddDecoder(&channel.Decoder{})
handler.AddDecoder(&ctrl_pb.Decoder{})
handler.AddDecoder(&xgress.Decoder{})
handler.AddDecoder(&mgmt_pb.Decoder{})
controllerConfig.Trace.Handler = handler
}
}
}
if value, found := cfgmap["profile"]; found {
if submap, ok := value.(map[interface{}]interface{}); ok {
if value, found := submap["memory"]; found {
if submap, ok := value.(map[interface{}]interface{}); ok {
if value, found := submap["path"]; found {
controllerConfig.Profile.Memory.Path = value.(string)
}
if value, found := submap["intervalMs"]; found {
controllerConfig.Profile.Memory.Interval = time.Duration(value.(int)) * time.Millisecond
} else {
controllerConfig.Profile.Memory.Interval = DefaultProfileMemoryInterval
}
}
}
if value, found := submap["cpu"]; found {
if submap, ok := value.(map[interface{}]interface{}); ok {
if value, found := submap["path"]; found {
controllerConfig.Profile.CPU.Path = value.(string)
}
}
}
}
}
if value, found := cfgmap["ctrl"]; found {
if submap, ok := value.(map[interface{}]interface{}); ok {
if value, found := submap["listener"]; found {
listener, err := transport.ParseAddress(value.(string))
if err != nil {
return nil, err
}
controllerConfig.Ctrl.Listener = listener
} else {
panic("controllerConfig must provide [ctrl/listener]")
}
controllerConfig.Ctrl.Options = &CtrlOptions{
Options: channel.DefaultOptions(),
PeerHeartbeatOptions: channel.DefaultHeartbeatOptions(),
RouterHeartbeatOptions: channel.DefaultHeartbeatOptions(),
}
if value, found := submap["options"]; found {
if submap, ok := value.(map[interface{}]interface{}); ok {
options, err := channel.LoadOptions(submap)
if err != nil {
return nil, err
}
controllerConfig.Ctrl.Options.Options = options
if val, found := submap["newListener"]; found {
if newListener, ok := val.(string); ok {
if newListener != "" {
if addr, err := transport.ParseAddress(newListener); err == nil {
controllerConfig.Ctrl.Options.NewListener = &addr
if err := verifyNewListenerInServerCert(controllerConfig, addr); err != nil {
return nil, err
}
} else {
return nil, fmt.Errorf("error loading newListener for [ctrl/options] (%v)", err)
}
}
} else {
return nil, errors.New("error loading newAddress for [ctrl/options] (must be a string)")
}
}
if val, found := submap["advertiseAddress"]; found {
if advertiseAddr, ok := val.(string); ok {
if advertiseAddr != "" {
addr, err := transport.ParseAddress(advertiseAddr)
if err != nil {
return nil, errors.Wrapf(err, "error parsing value '%v' for [ctrl/options/advertiseAddress]", advertiseAddr)
}
controllerConfig.Ctrl.Options.AdvertiseAddress = &addr
if controllerConfig.Raft != nil {
controllerConfig.Raft.AdvertiseAddress = addr
}
}
} else {
return nil, errors.New("error loading advertiseAddress for [ctrl/options] (must be a string)")
}
}
if value, found := submap["routerHeartbeats"]; found {
if submap, ok := value.(map[interface{}]interface{}); ok {
options, err := channel.LoadHeartbeatOptions(submap)
if err != nil {
return nil, err
}
controllerConfig.Ctrl.Options.RouterHeartbeatOptions = options
}
}
if value, found := submap["peerHeartbeats"]; found {
if submap, ok := value.(map[interface{}]interface{}); ok {
options, err := channel.LoadHeartbeatOptions(submap)
if err != nil {
return nil, err
}
controllerConfig.Ctrl.Options.PeerHeartbeatOptions = options
}
}
if err := controllerConfig.Ctrl.Options.Validate(); err != nil {
return nil, fmt.Errorf("error loading channel options for [ctrl/options] (%v)", err)
}
}
}
if controllerConfig.Raft != nil && controllerConfig.Raft.AdvertiseAddress == nil {
return nil, errors.New("[ctrl/options/advertiseAddress] is required when raft is enabled")
}
} else {
panic("controllerConfig [ctrl] section in unexpected format")
}
} else {
panic("controllerConfig must provide [ctrl]")
}
controllerConfig.HealthChecks.BoltCheck.Interval = DefaultHealthChecksBoltCheckInterval
controllerConfig.HealthChecks.BoltCheck.Timeout = DefaultHealthChecksBoltCheckTimeout
controllerConfig.HealthChecks.BoltCheck.InitialDelay = DefaultHealthChecksBoltCheckInitialDelay
if value, found := cfgmap["healthChecks"]; found {
if healthChecksMap, ok := value.(map[interface{}]interface{}); ok {
if value, found := healthChecksMap["boltCheck"]; found {
if boltMap, ok := value.(map[interface{}]interface{}); ok {
if value, found := boltMap["interval"]; found {
if val, err := time.ParseDuration(fmt.Sprintf("%v", value)); err == nil {
controllerConfig.HealthChecks.BoltCheck.Interval = val
} else {
return nil, errors.Wrapf(err, "failed to parse healthChecks.bolt.interval value '%v", value)
}
}
if value, found := boltMap["timeout"]; found {
if val, err := time.ParseDuration(fmt.Sprintf("%v", value)); err == nil {
controllerConfig.HealthChecks.BoltCheck.Timeout = val
} else {
return nil, errors.Wrapf(err, "failed to parse healthChecks.bolt.timeout value '%v", value)
}
}
if value, found := boltMap["initialDelay"]; found {
if val, err := time.ParseDuration(fmt.Sprintf("%v", value)); err == nil {
controllerConfig.HealthChecks.BoltCheck.InitialDelay = val
} else {
return nil, errors.Wrapf(err, "failed to parse healthChecks.bolt.initialDelay value '%v", value)
}
}
} else {
pfxlog.Logger().Warn("invalid [healthChecks.bolt] stanza")
}
}
} else {
pfxlog.Logger().Warn("invalid [healthChecks] stanza")
}
}
controllerConfig.CommandRateLimiter.Enabled = true
controllerConfig.CommandRateLimiter.QueueSize = command.DefaultLimiterSize
if value, found := cfgmap["commandRateLimiter"]; found {
if submap, ok := value.(map[interface{}]interface{}); ok {
if value, found := submap["enabled"]; found {
controllerConfig.CommandRateLimiter.Enabled = strings.EqualFold("true", fmt.Sprintf("%v", value))
}
if value, found := submap["maxQueued"]; found {
if intVal, ok := value.(int); ok {
v := int64(intVal)
if v < command.MinLimiterSize {
return nil, errors.Errorf("invalid value %v for commandRateLimiter, must be at least %v", value, command.MinLimiterSize)
}
if v > math.MaxUint32 {
return nil, errors.Errorf("invalid value %v for commandRateLimiter, must be at most %v", value, int64(math.MaxUint32))
}
controllerConfig.CommandRateLimiter.QueueSize = uint32(v)
} else {
return nil, errors.Errorf("invalid value %v for commandRateLimiter, must be integer value", value)
}
}
}
}
controllerConfig.TlsHandshakeRateLimiter.SetDefaults()
controllerConfig.TlsHandshakeRateLimiter.Enabled = DefaultTlsHandshakeRateLimiterEnabled
controllerConfig.TlsHandshakeRateLimiter.MaxSize = DefaultTlsHandshakeRateLimiterMaxWindow
controllerConfig.TlsHandshakeRateLimiter.QueueSizeMetric = TlsHandshakeRateLimiterMetricOutstandingCount
controllerConfig.TlsHandshakeRateLimiter.WindowSizeMetric = TlsHandshakeRateLimiterMetricCurrentWindowSize
controllerConfig.TlsHandshakeRateLimiter.WorkTimerMetric = TlsHandshakeRateLimiterMetricWorkTimer
if value, found := cfgmap["tls"]; found {
if tlsMap, ok := value.(map[interface{}]interface{}); ok {
if value, found := tlsMap["handshakeTimeout"]; found {
if val, err := time.ParseDuration(fmt.Sprintf("%v", value)); err == nil {
transporttls.SetSharedListenerHandshakeTimeout(val)
} else {
return nil, errors.Wrapf(err, "failed to parse tls.handshakeTimeout value '%v", value)
}
}
if err = loadTlsHandshakeRateLimiterConfig(&controllerConfig.TlsHandshakeRateLimiter, tlsMap); err != nil {
return nil, err
}
}
}
return controllerConfig, nil
}
func loadTlsHandshakeRateLimiterConfig(rateLimitConfig *command.AdaptiveRateLimiterConfig, cfgmap map[interface{}]interface{}) error {
if value, found := cfgmap["rateLimiter"]; found {
if submap, ok := value.(map[interface{}]interface{}); ok {
if err := command.LoadAdaptiveRateLimiterConfig(rateLimitConfig, submap); err != nil {
return err
}
if rateLimitConfig.MaxSize < TlsHandshakeRateLimiterMinSizeValue {
return errors.Errorf("invalid value %v for tls.rateLimiter.maxSize, must be at least %v",
rateLimitConfig.MaxSize, TlsHandshakeRateLimiterMinSizeValue)
}
if rateLimitConfig.MaxSize > TlsHandshakeRateLimiterMaxSizeValue {
return errors.Errorf("invalid value %v for tls.rateLimiter.maxSize, must be at most %v",
rateLimitConfig.MaxSize, TlsHandshakeRateLimiterMaxSizeValue)
}
if rateLimitConfig.MinSize < TlsHandshakeRateLimiterMinSizeValue {
return errors.Errorf("invalid value %v for tls.rateLimiter.minSize, must be at least %v",
rateLimitConfig.MinSize, TlsHandshakeRateLimiterMinSizeValue)
}
if rateLimitConfig.MinSize > TlsHandshakeRateLimiterMaxSizeValue {
return errors.Errorf("invalid value %v for tls.rateLimiter.minSize, must be at most %v",
rateLimitConfig.MinSize, TlsHandshakeRateLimiterMaxSizeValue)
}
} else {
return errors.Errorf("invalid type for tls.rateLimiter, should be map instead of %T", value)
}
}
return nil
}
// verifyNewListenerInServerCert verifies that the hostname (ip/dns) for addr is present as an IP/DNS SAN in the first
// certificate provided in the controller's identity server certificates. This is to avoid scenarios where
// newListener propagated to routers who will never be able to verify the controller's certificates due to SAN issues.
func verifyNewListenerInServerCert(controllerConfig *Config, addr transport.Address) error {
addrSplits := strings.Split(addr.String(), ":")
if len(addrSplits) < 3 {
return errors.New("could not determine newListener's host value, expected at least three segments")
}
host := addrSplits[1]
serverCerts := controllerConfig.Id.Identity.ServerCert()
if len(serverCerts) == 0 {
return errors.New("could not verify newListener value, server certificate for identity contains no certificates")
}
hostFound := false
for _, serverCert := range serverCerts {
for _, dnsName := range serverCert.Leaf.DNSNames {
if dnsName == host {
hostFound = true
break
}
}
if hostFound {
break
}
if !hostFound {
for _, ipAddresses := range serverCert.Leaf.IPAddresses {
if host == ipAddresses.String() {
hostFound = true
break
}
}
}
if hostFound {
break
}
}
if !hostFound {
return fmt.Errorf("could not find newListener [%s] host value [%s] in first certificate for controller identity", addr.String(), host)
}
return nil
}
type CertValidatingIdentity struct {
identity.Identity
}
func (self *CertValidatingIdentity) ClientTLSConfig() *tls.Config {
cfg := self.Identity.ClientTLSConfig()
cfg.VerifyConnection = self.VerifyConnection
return cfg
}
func (self *CertValidatingIdentity) ServerTLSConfig() *tls.Config {
cfg := self.Identity.ServerTLSConfig()
cfg.VerifyConnection = self.VerifyConnection
return cfg
}
func (self *CertValidatingIdentity) VerifyConnection(state tls.ConnectionState) error {
if len(state.PeerCertificates) == 0 {
return errors.New("no peer certificates provided")
}
log := pfxlog.Logger()
for _, cert := range state.PeerCertificates {
log.Infof("cert provided: CN: %v IsCA: %v", cert.Subject.CommonName, cert.IsCA)
}
options := x509.VerifyOptions{
Roots: self.Identity.CA(),
Intermediates: x509.NewCertPool(),
}
for _, cert := range state.PeerCertificates[1:] {
options.Intermediates.AddCert(cert)
}
result, err := state.PeerCertificates[0].Verify(options)
if err != nil {
pfxlog.Logger().WithError(err).Error("got error validating cert")
return err
}
log.Infof("got result: %v", result)
return nil
}