forked from gravitational/teleport
/
fileconf.go
1968 lines (1698 loc) · 68.9 KB
/
fileconf.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
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright 2015-2021 Gravitational, 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
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 config
import (
"bytes"
"crypto/tls"
"encoding/base64"
"errors"
"fmt"
"io"
"io/fs"
"net"
"net/url"
"os"
"strings"
"time"
"github.com/gravitational/trace"
log "github.com/sirupsen/logrus"
"golang.org/x/crypto/acme"
"golang.org/x/crypto/ssh"
"gopkg.in/yaml.v2"
"github.com/zmb3/teleport"
"github.com/zmb3/teleport/api/constants"
"github.com/zmb3/teleport/api/types"
"github.com/zmb3/teleport/api/types/installers"
apiutils "github.com/zmb3/teleport/api/utils"
"github.com/zmb3/teleport/api/utils/tlsutils"
"github.com/zmb3/teleport/lib/backend"
"github.com/zmb3/teleport/lib/bpf"
"github.com/zmb3/teleport/lib/client"
"github.com/zmb3/teleport/lib/defaults"
"github.com/zmb3/teleport/lib/pam"
restricted "github.com/zmb3/teleport/lib/restrictedsession"
"github.com/zmb3/teleport/lib/service"
"github.com/zmb3/teleport/lib/services"
"github.com/zmb3/teleport/lib/sshutils/x11"
"github.com/zmb3/teleport/lib/utils"
)
// FileConfig structre represents the teleport configuration stored in a config file
// in YAML format (usually /etc/teleport.yaml)
//
// Use config.ReadFromFile() to read the parsed FileConfig from a YAML file.
type FileConfig struct {
Version string `yaml:"version,omitempty"`
Global `yaml:"teleport,omitempty"`
Auth Auth `yaml:"auth_service,omitempty"`
SSH SSH `yaml:"ssh_service,omitempty"`
Proxy Proxy `yaml:"proxy_service,omitempty"`
Kube Kube `yaml:"kubernetes_service,omitempty"`
// Apps is the "app_service" section in Teleport file configuration which
// defines application access configuration.
Apps Apps `yaml:"app_service,omitempty"`
// Databases is the "db_service" section in Teleport configuration file
// that defines database access configuration.
Databases Databases `yaml:"db_service,omitempty"`
// Metrics is the "metrics_service" section in Teleport configuration file
// that defines the metrics service configuration
Metrics Metrics `yaml:"metrics_service,omitempty"`
// WindowsDesktop is the "windows_desktop_service" that defines the
// configuration for Windows Desktop Access.
WindowsDesktop WindowsDesktopService `yaml:"windows_desktop_service,omitempty"`
// Tracing is the "tracing_service" section in Teleport configuration file
Tracing TracingService `yaml:"tracing_service,omitempty"`
// Discovery is the "discovery_service" section in the Teleport
// configuration file
Discovery Discovery `yaml:"discovery_service,omitempty"`
}
// ReadFromFile reads Teleport configuration from a file. Currently only YAML
// format is supported
func ReadFromFile(filePath string) (*FileConfig, error) {
f, err := os.Open(filePath)
if err != nil {
if errors.Is(err, fs.ErrPermission) {
return nil, trace.Wrap(err, "failed to open file for Teleport configuration: %v. Ensure that you are running as a user with appropriate permissions.", filePath)
}
return nil, trace.Wrap(err, "failed to open file for Teleport configuration at %v", filePath)
}
defer f.Close()
return ReadConfig(f)
}
// ReadFromString reads values from base64 encoded byte string
func ReadFromString(configString string) (*FileConfig, error) {
data, err := base64.StdEncoding.DecodeString(configString)
if err != nil {
return nil, trace.BadParameter(
"configuration should be base64 encoded: %v", err)
}
return ReadConfig(bytes.NewBuffer(data))
}
// ReadConfig reads Teleport configuration from reader in YAML format
func ReadConfig(reader io.Reader) (*FileConfig, error) {
// read & parse YAML config:
bytes, err := io.ReadAll(reader)
if err != nil {
return nil, trace.Wrap(err, "failed reading Teleport configuration")
}
var fc FileConfig
if err := yaml.UnmarshalStrict(bytes, &fc); err != nil {
// Remove all newlines in the YAML error, to avoid escaping when printing.
return nil, trace.BadParameter("failed parsing the config file: %s", strings.Replace(err.Error(), "\n", "", -1))
}
if err := fc.CheckAndSetDefaults(); err != nil {
return nil, trace.BadParameter("failed to parse Teleport configuration: %v", err)
}
return &fc, nil
}
// SampleFlags specifies standalone configuration parameters
type SampleFlags struct {
// ClusterName is an optional cluster name
ClusterName string
// LicensePath adds license path to config
LicensePath string
// ACMEEmail is acme email
ACMEEmail string
// ACMEEnabled turns on ACME
ACMEEnabled bool
// Version is the Teleport Configuration version.
Version string
// PublicAddr sets the hostport the proxy advertises for the HTTP endpoint.
PublicAddr string
// KeyFile is a TLS key file
KeyFile string
// CertFile is a TLS Certificate file
CertFile string
// DataDir is a path to a directory where Teleport keep its data
DataDir string
// AuthToken is a token to register with an auth server
AuthToken string
// Roles is a list of comma-separated roles to create a config file with
Roles string
// AuthServer is the address of the auth server
AuthServer string
// ProxyAddress is the address of the proxy
ProxyAddress string
// AppName is the name of the application to start
AppName string
// AppURI is the internal address of the application to proxy
AppURI string
// NodeLabels is list of labels in the format `foo=bar,baz=bax` to add to newly created nodes.
NodeLabels string
// CAPin is the SKPI hash of the CA used to verify the Auth Server. Can be
// a single value or a list.
CAPin string
// JoinMethod is the method that will be used to join the cluster, either "token", "iam" or "ec2"
JoinMethod string
// NodeName is the name of the teleport node
NodeName string
}
// MakeSampleFileConfig returns a sample config to start
// a standalone server
func MakeSampleFileConfig(flags SampleFlags) (fc *FileConfig, err error) {
if (flags.KeyFile == "") != (flags.CertFile == "") { // xor
return nil, trace.BadParameter("please provide both --key-file and --cert-file")
}
if flags.ACMEEnabled {
if flags.ClusterName == "" {
return nil, trace.BadParameter("please provide --cluster-name when using ACME, for example --cluster-name=example.com")
}
if flags.CertFile != "" {
return nil, trace.BadParameter("could not use --key-file/--cert-file when ACME is enabled")
}
}
conf := service.MakeDefaultConfig()
var g Global
if flags.NodeName != "" {
g.NodeName = flags.NodeName
} else {
g.NodeName = conf.Hostname
}
g.Logger.Output = "stderr"
g.Logger.Severity = "INFO"
g.Logger.Format.Output = "text"
g.DataDir = flags.DataDir
if g.DataDir == "" {
g.DataDir = defaults.DataDir
}
joinMethod := flags.JoinMethod
if joinMethod == "" && flags.AuthToken != "" {
joinMethod = string(types.JoinMethodToken)
}
g.JoinParams = JoinParams{
TokenName: flags.AuthToken,
Method: types.JoinMethod(joinMethod),
}
if flags.AuthServer != "" && flags.ProxyAddress != "" {
return nil, trace.BadParameter("--proxy and --auth-server cannot both be set")
}
if flags.Version == defaults.TeleportConfigVersionV3 {
// User has specifically asked for version 3 so we should trust their
// specified values.
if flags.ProxyAddress != "" {
g.ProxyServer = flags.ProxyAddress
} else if flags.AuthServer != "" {
g.AuthServer = flags.AuthServer
}
} else if flags.Version == "" {
// User has not requested a specific version, so we should try for v3
// and fallback to v2.
if flags.ProxyAddress != "" {
g.ProxyServer = flags.ProxyAddress
} else if flags.AuthServer != "" {
// For Teleport 11, if `--auth-server` is provided, we generate a V2
// configuration and in `onConfigDump` output a stern warning if
// there is a chance that this is a Proxy.
// This ensures we do not break people relying on `--auth-server`.
addr, err := utils.ParseAddr(flags.AuthServer)
if err != nil {
return nil, trace.Wrap(err)
}
// Check port to determine if this is obviously an auth server
// and if not, downgrade to config v2.
if addr.Port(0) == defaults.AuthListenPort {
g.AuthServer = flags.AuthServer
} else {
g.AuthServers = []string{flags.AuthServer}
flags.Version = defaults.TeleportConfigVersionV2
}
}
} else {
// User has requested a version prior to v3, so we should only accept
// --auth-server.
if flags.ProxyAddress != "" {
return nil, trace.BadParameter("--proxy cannot be used with configuration versions older than v3")
} else if flags.AuthServer != "" {
g.AuthServers = []string{flags.AuthServer}
}
}
g.CAPin = strings.Split(flags.CAPin, ",")
roles := roleMapFromFlags(flags)
// SSH config:
s, err := makeSampleSSHConfig(conf, flags, roles[defaults.RoleNode])
if err != nil {
return nil, trace.Wrap(err)
}
// Auth config:
a := makeSampleAuthConfig(conf, flags, roles[defaults.RoleAuthService])
// sample proxy config:
p, err := makeSampleProxyConfig(conf, flags, roles[defaults.RoleProxy])
if err != nil {
return nil, trace.Wrap(err)
}
// Apps config:
apps, err := makeSampleAppsConfig(conf, flags, roles[defaults.RoleApp])
if err != nil {
return nil, trace.Wrap(err)
}
// DB config:
var dbs Databases
if roles[defaults.RoleDatabase] {
// keep it disable since `teleport configure` don't have all the necessary flags
// for this kind of resource
dbs.EnabledFlag = "no"
}
// WindowsDesktop config:
var d WindowsDesktopService
if roles[defaults.RoleWindowsDesktop] {
// keep it disable since `teleport configure` don't have all the necessary flags
// for this kind of resource
d.EnabledFlag = "no"
}
// If user via params or logic has suggested a version, then use that,
// otherwise default to the latest version.
version := flags.Version
if version == "" {
version = defaults.TeleportConfigVersionV3
}
fc = &FileConfig{
Version: version,
Global: g,
Proxy: p,
SSH: s,
Auth: a,
Apps: apps,
Databases: dbs,
WindowsDesktop: d,
}
return fc, nil
}
func makeSampleSSHConfig(conf *service.Config, flags SampleFlags, enabled bool) (SSH, error) {
var s SSH
if enabled {
s.EnabledFlag = "yes"
s.ListenAddress = conf.SSH.Addr.Addr
s.Commands = []CommandLabel{
{
Name: "hostname",
Command: []string{"hostname"},
Period: time.Minute,
},
}
labels, err := client.ParseLabelSpec(flags.NodeLabels)
if err != nil {
return s, trace.Wrap(err)
}
s.Labels = labels
} else {
s.EnabledFlag = "no"
}
return s, nil
}
func makeSampleAuthConfig(conf *service.Config, flags SampleFlags, enabled bool) Auth {
var a Auth
if enabled {
a.ListenAddress = conf.Auth.ListenAddr.Addr
a.ClusterName = ClusterName(flags.ClusterName)
a.EnabledFlag = "yes"
if flags.LicensePath != "" {
a.LicenseFile = flags.LicensePath
}
// from config v2 onwards, we support `proxy_listener_mode`, so we set it to `multiplex`
if flags.Version != defaults.TeleportConfigVersionV1 {
a.ProxyListenerMode = types.ProxyListenerMode_Multiplex
}
} else {
a.EnabledFlag = "no"
}
return a
}
func makeSampleProxyConfig(conf *service.Config, flags SampleFlags, enabled bool) (Proxy, error) {
var p Proxy
if enabled {
p.EnabledFlag = "yes"
p.ListenAddress = conf.Proxy.SSHAddr.Addr
if flags.ACMEEnabled {
p.ACME.EnabledFlag = "yes"
p.ACME.Email = flags.ACMEEmail
// ACME uses TLS-ALPN-01 challenge that requires port 443
// https://letsencrypt.org/docs/challenge-types/#tls-alpn-01
p.PublicAddr = apiutils.Strings{net.JoinHostPort(flags.ClusterName, fmt.Sprintf("%d", teleport.StandardHTTPSPort))}
p.WebAddr = net.JoinHostPort(defaults.BindIP, fmt.Sprintf("%d", teleport.StandardHTTPSPort))
}
if flags.PublicAddr != "" {
// default to 443 if port is not specified
publicAddr, err := utils.ParseHostPortAddr(flags.PublicAddr, teleport.StandardHTTPSPort)
if err != nil {
return Proxy{}, trace.Wrap(err)
}
p.PublicAddr = apiutils.Strings{publicAddr.String()}
// use same port for web addr
webPort := publicAddr.Port(teleport.StandardHTTPSPort)
p.WebAddr = net.JoinHostPort(defaults.BindIP, fmt.Sprintf("%d", webPort))
}
if flags.KeyFile != "" && flags.CertFile != "" {
if _, err := tls.LoadX509KeyPair(flags.CertFile, flags.KeyFile); err != nil {
return Proxy{}, trace.Wrap(err, "failed to load x509 key pair from --key-file and --cert-file")
}
p.KeyPairs = append(p.KeyPairs, KeyPair{
PrivateKey: flags.KeyFile,
Certificate: flags.CertFile,
})
}
} else {
p.EnabledFlag = "no"
}
return p, nil
}
func makeSampleAppsConfig(conf *service.Config, flags SampleFlags, enabled bool) (Apps, error) {
var apps Apps
// assume users want app role if they added app name and/or uri but didn't add app role
if enabled || flags.AppURI != "" || flags.AppName != "" {
if flags.AppURI == "" || flags.AppName == "" {
return Apps{}, trace.BadParameter("please provide both --app-name and --app-uri")
}
apps.EnabledFlag = "yes"
apps.Apps = []*App{
{
Name: flags.AppName,
URI: flags.AppURI,
},
}
}
return apps, nil
}
func roleMapFromFlags(flags SampleFlags) map[string]bool {
// if no roles are provided via CLI, return the default roles
if flags.Roles == "" {
return map[string]bool{
defaults.RoleProxy: true,
defaults.RoleNode: true,
defaults.RoleAuthService: true,
}
}
roles := splitRoles(flags.Roles)
m := make(map[string]bool)
for _, r := range roles {
m[r] = true
}
return m
}
// DebugDumpToYAML allows for quick YAML dumping of the config
func (conf *FileConfig) DebugDumpToYAML() string {
bytes, err := yaml.Marshal(&conf)
if err != nil {
panic(err)
}
return string(bytes)
}
// CheckAndSetDefaults sets defaults and ensures that the ciphers, kex
// algorithms, and mac algorithms set are supported by golang.org/x/crypto/ssh.
// This ensures we don't start Teleport with invalid configuration.
func (conf *FileConfig) CheckAndSetDefaults() error {
conf.Auth.defaultEnabled = true
conf.Proxy.defaultEnabled = true
conf.SSH.defaultEnabled = true
conf.Kube.defaultEnabled = false
if conf.Version == "" {
conf.Version = defaults.TeleportConfigVersionV1
}
var sc ssh.Config
sc.SetDefaults()
for _, c := range conf.Ciphers {
if !apiutils.SliceContainsStr(sc.Ciphers, c) {
return trace.BadParameter("cipher algorithm %q is not supported; supported algorithms: %q", c, sc.Ciphers)
}
}
for _, k := range conf.KEXAlgorithms {
if !apiutils.SliceContainsStr(sc.KeyExchanges, k) {
return trace.BadParameter("KEX algorithm %q is not supported; supported algorithms: %q", k, sc.KeyExchanges)
}
}
for _, m := range conf.MACAlgorithms {
if !apiutils.SliceContainsStr(sc.MACs, m) {
return trace.BadParameter("MAC algorithm %q is not supported; supported algorithms: %q", m, sc.MACs)
}
}
if err := checkAndSetDefaultsForAWSMatchers(conf.Discovery.AWSMatchers); err != nil {
return trace.Wrap(err)
}
if err := checkAndSetDefaultsForAzureMatchers(conf.Discovery.AzureMatchers); err != nil {
return trace.Wrap(err)
}
if err := checkAndSetDefaultsForGCPMatchers(conf.Discovery.GCPMatchers); err != nil {
return trace.Wrap(err)
}
return nil
}
// checkAndSetDefaultsForAWSMatchers sets the default values for discovery AWS matchers
// and validates the provided types.
func checkAndSetDefaultsForAWSMatchers(matcherInput []AWSMatcher) error {
for i := range matcherInput {
matcher := &matcherInput[i]
for _, serviceType := range matcher.Types {
if !apiutils.SliceContainsStr(constants.SupportedAWSDiscoveryServices, serviceType) {
return trace.BadParameter("discovery service type does not support %q, supported resource types are: %v",
serviceType, constants.SupportedAWSDiscoveryServices)
}
}
if matcher.Tags == nil || len(matcher.Tags) == 0 {
matcher.Tags = map[string]apiutils.Strings{types.Wildcard: {types.Wildcard}}
}
if matcher.InstallParams == nil {
matcher.InstallParams = &InstallParams{
JoinParams: JoinParams{
TokenName: defaults.IAMInviteTokenName,
Method: types.JoinMethodIAM,
},
ScriptName: installers.InstallerScriptName,
}
} else {
if method := matcher.InstallParams.JoinParams.Method; method == "" {
matcher.InstallParams.JoinParams.Method = types.JoinMethodIAM
} else if method != types.JoinMethodIAM {
return trace.BadParameter("only IAM joining is supported for EC2 auto-discovery")
}
if token := matcher.InstallParams.JoinParams.TokenName; token == "" {
matcher.InstallParams.JoinParams.TokenName = defaults.IAMInviteTokenName
}
if installer := matcher.InstallParams.ScriptName; installer == "" {
matcher.InstallParams.ScriptName = installers.InstallerScriptName
}
}
if matcher.SSM.DocumentName == "" {
matcher.SSM.DocumentName = defaults.AWSInstallerDocument
}
}
return nil
}
// checkAndSetDefaultsForAzureMatchers sets the default values for discovery Azure matchers
// and validates the provided types.
func checkAndSetDefaultsForAzureMatchers(matcherInput []AzureMatcher) error {
for i := range matcherInput {
matcher := &matcherInput[i]
if len(matcher.Types) == 0 {
return trace.BadParameter("At least one Azure discovery service type must be specified, the supported resource types are: %v",
constants.SupportedAzureDiscoveryServices)
}
for _, serviceType := range matcher.Types {
if !apiutils.SliceContainsStr(constants.SupportedAzureDiscoveryServices, serviceType) {
return trace.BadParameter("Azure discovery service type does not support %q resource type; supported resource types are: %v",
serviceType, constants.SupportedAzureDiscoveryServices)
}
}
if apiutils.SliceContainsStr(matcher.Regions, types.Wildcard) || len(matcher.Regions) == 0 {
matcher.Regions = []string{types.Wildcard}
}
if apiutils.SliceContainsStr(matcher.Subscriptions, types.Wildcard) || len(matcher.Subscriptions) == 0 {
matcher.Subscriptions = []string{types.Wildcard}
}
if apiutils.SliceContainsStr(matcher.ResourceGroups, types.Wildcard) || len(matcher.ResourceGroups) == 0 {
matcher.ResourceGroups = []string{types.Wildcard}
}
if len(matcher.ResourceTags) == 0 {
matcher.ResourceTags = map[string]apiutils.Strings{
types.Wildcard: {types.Wildcard},
}
}
}
return nil
}
// checkAndSetDefaultsForGCPMatchers sets the default values for GCP matchers
// and validates the provided types.
func checkAndSetDefaultsForGCPMatchers(matcherInput []GCPMatcher) error {
for i := range matcherInput {
matcher := &matcherInput[i]
if len(matcher.Types) == 0 {
return trace.BadParameter("At least one GCP discovery service type must be specified, the supported resource types are: %v",
constants.SupportedGCPDiscoveryServices)
}
for _, serviceType := range matcher.Types {
if !apiutils.SliceContainsStr(constants.SupportedGCPDiscoveryServices, serviceType) {
return trace.BadParameter("GCP discovery service type does not support %q resource type; supported resource types are: %v",
serviceType, constants.SupportedGCPDiscoveryServices)
}
}
if apiutils.SliceContainsStr(matcher.Locations, types.Wildcard) || len(matcher.Locations) == 0 {
matcher.Locations = []string{types.Wildcard}
}
if apiutils.SliceContainsStr(matcher.ProjectIDs, types.Wildcard) {
return trace.BadParameter("GCP discovery service project_ids does not support wildcards; please specify at least one value in project_ids.")
}
if len(matcher.ProjectIDs) == 0 {
return trace.BadParameter("GCP discovery service project_ids does cannot be empty; please specify at least one value in project_ids.")
}
if len(matcher.Tags) == 0 {
matcher.Tags = map[string]apiutils.Strings{
types.Wildcard: {types.Wildcard},
}
}
}
return nil
}
// JoinParams configures the parameters for Simplified Node Joining.
type JoinParams struct {
TokenName string `yaml:"token_name"`
Method types.JoinMethod `yaml:"method"`
}
// ConnectionRate configures rate limiter
type ConnectionRate struct {
Period time.Duration `yaml:"period"`
Average int64 `yaml:"average"`
Burst int64 `yaml:"burst"`
}
// ConnectionLimits sets up connection limiter
type ConnectionLimits struct {
MaxConnections int64 `yaml:"max_connections"`
MaxUsers int `yaml:"max_users"`
Rates []ConnectionRate `yaml:"rates,omitempty"`
}
// LegacyLog contains the old format of the 'format' field
// It is kept here for backwards compatibility and should always be maintained
// The custom yaml unmarshaler should automatically convert it into the new
// expected format.
type LegacyLog struct {
// Output defines where logs go. It can be one of the following: "stderr", "stdout" or
// a path to a log file
Output string `yaml:"output,omitempty"`
// Severity defines how verbose the log will be. Possible values are "error", "info", "warn"
Severity string `yaml:"severity,omitempty"`
// Format lists the output fields from KnownFormatFields. Example format: [timestamp, component, caller]
Format []string `yaml:"format,omitempty"`
}
// Log configures teleport logging
type Log struct {
// Output defines where logs go. It can be one of the following: "stderr", "stdout" or
// a path to a log file
Output string `yaml:"output,omitempty"`
// Severity defines how verbose the log will be. Possible values are "error", "info", "warn"
Severity string `yaml:"severity,omitempty"`
// Format defines the logs output format and extra fields
Format LogFormat `yaml:"format,omitempty"`
}
// LogFormat specifies the logs output format and extra fields
type LogFormat struct {
// Output defines the output format. Possible values are 'text' and 'json'.
Output string `yaml:"output,omitempty"`
// ExtraFields lists the output fields from KnownFormatFields. Example format: [timestamp, component, caller]
ExtraFields []string `yaml:"extra_fields,omitempty"`
}
func (l *Log) UnmarshalYAML(unmarshal func(interface{}) error) error {
// the next two lines are needed because of an infinite loop issue
// https://github.com/go-yaml/yaml/issues/107
type logYAML Log
log := (*logYAML)(l)
if err := unmarshal(log); err != nil {
if _, ok := err.(*yaml.TypeError); !ok {
return err
}
var legacyLog LegacyLog
if lerr := unmarshal(&legacyLog); lerr != nil {
// return the original unmarshal error
return err
}
l.Output = legacyLog.Output
l.Severity = legacyLog.Severity
l.Format.Output = "text"
l.Format.ExtraFields = legacyLog.Format
return nil
}
return nil
}
// Global is 'teleport' (global) section of the config file
type Global struct {
NodeName string `yaml:"nodename,omitempty"`
DataDir string `yaml:"data_dir,omitempty"`
PIDFile string `yaml:"pid_file,omitempty"`
JoinParams JoinParams `yaml:"join_params,omitempty"`
// v1, v2
AuthServers []string `yaml:"auth_servers,omitempty"`
// AuthToken is the old way of configuring the token to be used by the
// node to join the Teleport cluster. `JoinParams.TokenName` should be
// used instead with `JoinParams.JoinMethod = types.JoinMethodToken`.
AuthToken string `yaml:"auth_token,omitempty"`
// v3
AuthServer string `yaml:"auth_server,omitempty"`
ProxyServer string `yaml:"proxy_server,omitempty"`
Limits ConnectionLimits `yaml:"connection_limits,omitempty"`
Logger Log `yaml:"log,omitempty"`
Storage backend.Config `yaml:"storage,omitempty"`
AdvertiseIP string `yaml:"advertise_ip,omitempty"`
CachePolicy CachePolicy `yaml:"cache,omitempty"`
// CipherSuites is a list of TLS ciphersuites that Teleport supports. If
// omitted, a Teleport selected list of defaults will be used.
CipherSuites []string `yaml:"ciphersuites,omitempty"`
// Ciphers is a list of SSH ciphers that the server supports. If omitted,
// the defaults will be used.
Ciphers []string `yaml:"ciphers,omitempty"`
// KEXAlgorithms is a list of SSH key exchange (KEX) algorithms that the
// server supports. If omitted, the defaults will be used.
KEXAlgorithms []string `yaml:"kex_algos,omitempty"`
// MACAlgorithms is a list of SSH message authentication codes (MAC) that
// the server supports. If omitted the defaults will be used.
MACAlgorithms []string `yaml:"mac_algos,omitempty"`
// CASignatureAlgorithm is ignored but ketp for config backwards compat
CASignatureAlgorithm *string `yaml:"ca_signature_algo,omitempty"`
// CAPin is the SKPI hash of the CA used to verify the Auth Server. Can be
// a single value or a list.
CAPin apiutils.Strings `yaml:"ca_pin"`
// DiagAddr is the address to expose a diagnostics HTTP endpoint.
DiagAddr string `yaml:"diag_addr"`
}
// CachePolicy is used to control local cache
type CachePolicy struct {
// Type is for cache type `sqlite` or `in-memory`
Type string `yaml:"type,omitempty"`
// EnabledFlag enables or disables cache
EnabledFlag string `yaml:"enabled,omitempty"`
// TTL sets maximum TTL for the cached values
TTL string `yaml:"ttl,omitempty"`
}
// Enabled determines if a given "_service" section has been set to 'true'
func (c *CachePolicy) Enabled() bool {
if c.EnabledFlag == "" {
return true
}
enabled, _ := apiutils.ParseBool(c.EnabledFlag)
return enabled
}
// Parse parses cache policy from Teleport config
func (c *CachePolicy) Parse() (*service.CachePolicy, error) {
out := service.CachePolicy{
Enabled: c.Enabled(),
}
if err := out.CheckAndSetDefaults(); err != nil {
return nil, trace.Wrap(err)
}
return &out, nil
}
// Service is a common configuration of a teleport service
type Service struct {
defaultEnabled bool
EnabledFlag string `yaml:"enabled,omitempty"`
ListenAddress string `yaml:"listen_addr,omitempty"`
}
// Configured determines if a given "_service" section has been specified
func (s *Service) Configured() bool {
return s.EnabledFlag != ""
}
// Enabled determines if a given "_service" section has been set to 'true'
func (s *Service) Enabled() bool {
if !s.Configured() {
return s.defaultEnabled
}
v, err := apiutils.ParseBool(s.EnabledFlag)
if err != nil {
return false
}
return v
}
// Disabled returns 'true' if the service has been deliberately turned off
func (s *Service) Disabled() bool {
if !s.Configured() {
return !s.defaultEnabled
}
return !s.Enabled()
}
// Auth is 'auth_service' section of the config file
type Auth struct {
Service `yaml:",inline"`
// ProxyProtocol enables support for HAProxy proxy protocol version 1 when it is turned 'on'.
// Verify whether the service is in front of a trusted load balancer.
// The default value is 'on'.
ProxyProtocol string `yaml:"proxy_protocol,omitempty"`
// ClusterName is the name of the CA who manages this cluster
ClusterName ClusterName `yaml:"cluster_name,omitempty"`
// StaticTokens are pre-defined host provisioning tokens supplied via config file for
// environments where paranoid security is not needed
//
// Each token string has the following format: "role1,role2,..:token",
// for exmple: "auth,proxy,node:MTIzNGlvemRmOWE4MjNoaQo"
StaticTokens StaticTokens `yaml:"tokens,omitempty"`
// Authentication holds authentication configuration information like authentication
// type, second factor type, specific connector information, etc.
Authentication *AuthenticationConfig `yaml:"authentication,omitempty"`
// SessionRecording determines where the session is recorded:
// node, node-sync, proxy, proxy-sync, or off.
SessionRecording string `yaml:"session_recording,omitempty"`
// ProxyChecksHostKeys is used when the proxy is in recording mode and
// determines if the proxy will check the host key of the client or not.
ProxyChecksHostKeys *types.BoolOption `yaml:"proxy_checks_host_keys,omitempty"`
// LicenseFile is a path to the license file. The path can be either absolute or
// relative to the global data dir
LicenseFile string `yaml:"license_file,omitempty"`
// FOR INTERNAL USE:
// ReverseTunnels is a list of SSH tunnels to 3rd party proxy services (used to talk
// to 3rd party auth servers we trust)
ReverseTunnels []ReverseTunnel `yaml:"reverse_tunnels,omitempty"`
// PublicAddr sets SSH host principals and TLS DNS names to auth
// server certificates
PublicAddr apiutils.Strings `yaml:"public_addr,omitempty"`
// ClientIdleTimeout sets global cluster default setting for client idle timeouts
ClientIdleTimeout types.Duration `yaml:"client_idle_timeout,omitempty"`
// DisconnectExpiredCert provides disconnect expired certificate setting -
// if true, connections with expired client certificates will get disconnected
DisconnectExpiredCert *types.BoolOption `yaml:"disconnect_expired_cert,omitempty"`
// SessionControlTimeout specifies the maximum amount of time a node can be out
// of contact with the auth server before it starts terminating controlled sessions.
SessionControlTimeout types.Duration `yaml:"session_control_timeout,omitempty"`
// KubeconfigFile is an optional path to kubeconfig file,
// if specified, teleport will use API server address and
// trusted certificate authority information from it
KubeconfigFile string `yaml:"kubeconfig_file,omitempty"`
// KeepAliveInterval set the keep-alive interval for server to client
// connections.
KeepAliveInterval types.Duration `yaml:"keep_alive_interval,omitempty"`
// KeepAliveCountMax set the number of keep-alive messages that can be
// missed before the server disconnects the client.
KeepAliveCountMax int64 `yaml:"keep_alive_count_max,omitempty"`
// ClientIdleTimeoutMessage is sent to the client when the inactivity timeout
// expires. The empty string implies no message should be sent prior to
// disconnection.
ClientIdleTimeoutMessage string `yaml:"client_idle_timeout_message,omitempty"`
// MessageOfTheDay is a banner that a user must acknowledge during a `tsh login`.
MessageOfTheDay string `yaml:"message_of_the_day,omitempty"`
// WebIdleTimeout sets global cluster default setting for WebUI client
// idle timeouts
WebIdleTimeout types.Duration `yaml:"web_idle_timeout,omitempty"`
// CAKeyParams configures how CA private keys will be created and stored.
CAKeyParams *CAKeyParams `yaml:"ca_key_params,omitempty"`
// ProxyListenerMode is a listener mode user by the proxy.
ProxyListenerMode types.ProxyListenerMode `yaml:"proxy_listener_mode,omitempty"`
// RoutingStrategy configures the routing strategy to nodes.
RoutingStrategy types.RoutingStrategy `yaml:"routing_strategy,omitempty"`
// TunnelStrategy configures the tunnel strategy used by the cluster.
TunnelStrategy *types.TunnelStrategyV1 `yaml:"tunnel_strategy,omitempty"`
// ProxyPingInterval defines in which interval the TLS routing ping message
// should be sent. This is applicable only when using ping-wrapped
// connections, regular TLS routing connections are not affected.
ProxyPingInterval types.Duration `yaml:"proxy_ping_interval,omitempty"`
// LoadAllCAs tells tsh to load the CAs for all clusters when trying
// to ssh into a node, instead of just the CA for the current cluster.
LoadAllCAs bool `yaml:"load_all_cas,omitempty"`
}
// CAKeyParams configures how CA private keys will be created and stored.
type CAKeyParams struct {
// PKCS11 configures a PKCS#11 HSM to be used for all CA private key generation and
// storage.
PKCS11 *PKCS11 `yaml:"pkcs11,omitempty"`
// GoogleCloudKMS configures Google Cloud Key Management Service to to be used for
// all CA private key crypto operations.
GoogleCloudKMS *GoogleCloudKMS `yaml:"gcp_kms,omitempty"`
}
// PKCS11 configures a PKCS#11 HSM to be used for private key generation and
// storage.
type PKCS11 struct {
// ModulePath is the path to the PKCS#11 library.
ModulePath string `yaml:"module_path"`
// TokenLabel is the CKA_LABEL of the HSM token to use. Set this or
// SlotNumber to select a token.
TokenLabel string `yaml:"token_label,omitempty"`
// SlotNumber is the slot number of the HSM token to use. Set this or
// TokenLabel to select a token.
SlotNumber *int `yaml:"slot_number,omitempty"`
// Pin is the raw pin for connecting to the HSM. Set this or PinPath to set
// the pin.
Pin string `yaml:"pin,omitempty"`
// PinPath is a path to a file containing a pin for connecting to the HSM.
// Trailing newlines will be removed, other whitespace will be left. Set
// this or Pin to set the pin.
PinPath string `yaml:"pin_path,omitempty"`
}
// GoogleCloudKMS configures Google Cloud Key Management Service to to be used for
// all CA private key crypto operations.
type GoogleCloudKMS struct {
// KeyRing is the GCP key ring where all keys generated by this auth server
// should be held. This must be the fully qualified resource name of the key
// ring, including the project and location, e.g.
// projects/teleport-project/locations/us-west1/keyRings/teleport-keyring
KeyRing string `yaml:"keyring"`
// ProtectionLevel specifies how cryptographic operations are performed.
// For more information, see https://cloud.google.com/kms/docs/algorithms#protection_levels
// Supported options are "HSM" and "SOFTWARE".
ProtectionLevel string `yaml:"protection_level"`
}
// TrustedCluster struct holds configuration values under "trusted_clusters" key
type TrustedCluster struct {
// KeyFile is a path to a remote authority (AKA "trusted cluster") public keys
KeyFile string `yaml:"key_file,omitempty"`
// AllowedLogins is a comma-separated list of user logins allowed from that cluster
AllowedLogins string `yaml:"allow_logins,omitempty"`
// TunnelAddr is a comma-separated list of reverse tunnel addresses to
// connect to
TunnelAddr string `yaml:"tunnel_addr,omitempty"`
}
type ClusterName string
func (c ClusterName) Parse() (types.ClusterName, error) {
if string(c) == "" {
return nil, nil
}
return services.NewClusterNameWithRandomID(types.ClusterNameSpecV2{
ClusterName: string(c),
})
}
type StaticTokens []StaticToken
func (t StaticTokens) Parse() (types.StaticTokens, error) {
var provisionTokens []types.ProvisionTokenV1
for _, st := range t {
tokens, err := st.Parse()
if err != nil {
return nil, trace.Wrap(err)