-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
Copy pathconfiguration.go
2931 lines (2623 loc) · 93.5 KB
/
configuration.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
/*
* Teleport
* Copyright (C) 2023 Gravitational, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
// Package config provides facilities for configuring Teleport daemons
// including
// - parsing YAML configuration
// - parsing CLI flags
package config
import (
"context"
"crypto/x509"
"errors"
"io"
"log/slog"
"maps"
"net"
"net/url"
"os"
"path/filepath"
"reflect"
"regexp"
"runtime"
"slices"
"strconv"
"strings"
"time"
"unicode"
"github.com/go-ldap/ldap/v3"
"github.com/gravitational/trace"
kyaml "k8s.io/apimachinery/pkg/util/yaml"
"github.com/gravitational/teleport"
"github.com/gravitational/teleport/api/client/webclient"
"github.com/gravitational/teleport/api/constants"
"github.com/gravitational/teleport/api/types"
"github.com/gravitational/teleport/lib"
"github.com/gravitational/teleport/lib/automaticupgrades"
"github.com/gravitational/teleport/lib/backend"
"github.com/gravitational/teleport/lib/backend/lite"
"github.com/gravitational/teleport/lib/backend/memory"
"github.com/gravitational/teleport/lib/client"
"github.com/gravitational/teleport/lib/defaults"
"github.com/gravitational/teleport/lib/integrations/externalauditstorage/easconfig"
"github.com/gravitational/teleport/lib/integrations/samlidp/samlidpconfig"
"github.com/gravitational/teleport/lib/limiter"
"github.com/gravitational/teleport/lib/modules"
"github.com/gravitational/teleport/lib/multiplexer"
"github.com/gravitational/teleport/lib/pam"
"github.com/gravitational/teleport/lib/service/servicecfg"
"github.com/gravitational/teleport/lib/services"
"github.com/gravitational/teleport/lib/tlsca"
"github.com/gravitational/teleport/lib/utils"
awsutils "github.com/gravitational/teleport/lib/utils/aws"
logutils "github.com/gravitational/teleport/lib/utils/log"
)
// CommandLineFlags stores command line flag values, it's a much simplified subset
// of Teleport configuration (which is fully expressed via YAML config file)
type CommandLineFlags struct {
// --name flag
NodeName string
// --auth-server flag
AuthServerAddr []string
// --token flag
AuthToken string
// --join-method flag
JoinMethod string
// CAPins are the SKPI hashes of the CAs used to verify the Auth Server.
CAPins []string
// --listen-ip flag
ListenIP net.IP
// --advertise-ip flag
AdvertiseIP string
// --config flag
ConfigFile string
// --apply-on-startup contains the path of a YAML manifest whose resources should be
// applied on startup. Unlike the bootstrap flag, the resources are always applied,
// even if the cluster is already initialized. Existing resources will be updated.
ApplyOnStartupFile string
// Bootstrap flag contains a YAML file that defines a set of resources to bootstrap
// a cluster.
BootstrapFile string
// ConfigString is a base64 encoded configuration string
// set by --config-string or TELEPORT_CONFIG environment variable
ConfigString string
// --roles flag
Roles string
// -d flag
Debug bool
// --insecure-no-tls flag
DisableTLS bool
// --labels flag
Labels string
// --pid-file flag
PIDFile string
// DiagnosticAddr is listen address for diagnostic endpoint
DiagnosticAddr string
// PermitUserEnvironment enables reading of ~/.tsh/environment
// when creating a new session.
PermitUserEnvironment bool
// Insecure mode is controlled by --insecure flag and in this mode
// Teleport won't check certificates when connecting to trusted clusters
// It's useful for learning Teleport (following quick starts, etc).
InsecureMode bool
// FIPS mode means Teleport starts in a FedRAMP/FIPS 140-2 compliant
// configuration.
FIPS bool
// SkipVersionCheck allows Teleport to connect to auth servers that
// have an earlier major version number.
SkipVersionCheck bool
// AppName is the name of the application to proxy.
AppName string
// AppURI is the internal address of the application to proxy.
AppURI string
// AppCloud is set if application is proxying Cloud API
AppCloud string
// AppPublicAddr is the public address of the application to proxy.
AppPublicAddr string
// DatabaseName is the name of the database to proxy.
DatabaseName string
// DatabaseDescription is a free-form database description.
DatabaseDescription string
// DatabaseProtocol is the type of the proxied database e.g. postgres or mysql.
DatabaseProtocol string
// DatabaseURI is the address to connect to the proxied database.
DatabaseURI string
// DatabaseCACertFile is the database CA cert path.
DatabaseCACertFile string
// DatabaseAWSRegion is an optional database cloud region e.g. when using AWS RDS.
DatabaseAWSRegion string
// DatabaseAWSAccountID is an optional AWS account ID e.g. when using Keyspaces.
DatabaseAWSAccountID string
// DatabaseAWSAssumeRoleARN is an optional AWS IAM role ARN to assume when accessing the database.
DatabaseAWSAssumeRoleARN string
// DatabaseAWSExternalID is an optional AWS external ID used to enable assuming an AWS role across accounts.
DatabaseAWSExternalID string
// DatabaseAWSRedshiftClusterID is Redshift cluster identifier.
DatabaseAWSRedshiftClusterID string
// DatabaseAWSRDSInstanceID is RDS instance identifier.
DatabaseAWSRDSInstanceID string
// DatabaseAWSRDSClusterID is RDS cluster (Aurora) cluster identifier.
DatabaseAWSRDSClusterID string
// DatabaseAWSElastiCacheGroupID is the ElastiCache replication group identifier.
DatabaseAWSElastiCacheGroupID string
// DatabaseAWSMemoryDBClusterName is the MemoryDB cluster name.
DatabaseAWSMemoryDBClusterName string
// DatabaseAWSSessionTags is the AWS STS session tags.
DatabaseAWSSessionTags string
// DatabaseGCPProjectID is GCP Cloud SQL project identifier.
DatabaseGCPProjectID string
// DatabaseGCPInstanceID is GCP Cloud SQL instance identifier.
DatabaseGCPInstanceID string
// DatabaseADKeytabFile is the path to Kerberos keytab file.
DatabaseADKeytabFile string
// DatabaseADKrb5File is the path to krb5.conf file.
DatabaseADKrb5File string
// DatabaseADDomain is the Active Directory domain for authentication.
DatabaseADDomain string
// DatabaseADSPN is the database Service Principal Name.
DatabaseADSPN string
// DatabaseMySQLServerVersion is the MySQL server version reported to a client
// if the value cannot be obtained from the database.
DatabaseMySQLServerVersion string
// ProxyServer is the url of the proxy server to connect to.
ProxyServer string
// OpenSSHConfigPath is the path of the file to write agentless configuration to.
OpenSSHConfigPath string
// RestartOpenSSH indicates whether openssh should be restarted or not.
RestartOpenSSH bool
// RestartCommand is the command to use when restarting sshd
RestartCommand string
// CheckCommand is the command to use when checking sshd config validity
CheckCommand string
// Address is the ip address of the OpenSSH node.
Address string
// AdditionalPrincipals is a list of additional principals to include in the SSH cert.
AdditionalPrincipals string
// Directory to store
DataDir string
// IntegrationConfDeployServiceIAMArguments contains the arguments of
// `teleport integration configure deployservice-iam` command
IntegrationConfDeployServiceIAMArguments IntegrationConfDeployServiceIAM
// IntegrationConfAWSAppAccessIAMArguments contains the arguments of
// `teleport integration configure aws-app-access-iam` command
IntegrationConfAWSAppAccessIAMArguments IntegrationConfAWSAppAccessIAM
// IntegrationConfEC2SSMIAMArguments contains the arguments of
// `teleport integration configure ec2-ssm-iam` command
IntegrationConfEC2SSMIAMArguments IntegrationConfEC2SSMIAM
// IntegrationConfEKSIAMArguments contains the arguments of
// `teleport integration configure eks-iam` command
IntegrationConfEKSIAMArguments IntegrationConfEKSIAM
// IntegrationConfAWSOIDCIdPArguments contains the arguments of
// `teleport integration configure awsoidc-idp` command
IntegrationConfAWSOIDCIdPArguments IntegrationConfAWSOIDCIdP
// IntegrationConfListDatabasesIAMArguments contains the arguments of
// `teleport integration configure listdatabases-iam` command
IntegrationConfListDatabasesIAMArguments IntegrationConfListDatabasesIAM
// IntegrationConfExternalAuditStorageArguments contains the arguments of the
// `teleport integration configure externalauditstorage` command
IntegrationConfExternalAuditStorageArguments easconfig.ExternalAuditStorageConfiguration
// IntegrationConfAccessGraphAWSSyncArguments contains the arguments of
// `teleport integration configure access-graph aws-iam` command
IntegrationConfAccessGraphAWSSyncArguments IntegrationConfAccessGraphAWSSync
// IntegrationConfAccessGarphAzureSyncArguments contains the arguments of
// `teleport integration configure access-graph azure` command
IntegrationConfAccessGraphAzureSyncArguments IntegrationConfAccessGraphAzureSync
// IntegrationConfAzureOIDCArguments contains the arguments of
// `teleport integration configure azure-oidc` command
IntegrationConfAzureOIDCArguments IntegrationConfAzureOIDC
// IntegrationConfSAMLIdPGCPWorkforceArguments contains the arguments of
// `teleport integration configure samlidp gcp-workforce` command
IntegrationConfSAMLIdPGCPWorkforceArguments samlidpconfig.GCPWorkforceAPIParams
// LogLevel is the new application's log level.
LogLevel string
// Profiles comma-separated list of pprof profiles to be collected.
Profiles string
// ProfileSeconds defines the time the pprof will be collected.
ProfileSeconds int
// DisableDebugService disables the debug service.
DisableDebugService bool
}
// IntegrationConfAccessGraphAWSSync contains the arguments of
// `teleport integration configure access-graph aws-iam` command.
type IntegrationConfAccessGraphAWSSync struct {
// Role is the AWS Role associated with the Integration
Role string
// AccountID is the AWS account ID.
AccountID string
// AutoConfirm skips user confirmation of the operation plan if true.
AutoConfirm bool
}
// IntegrationConfAccessGraphAzureSync contains the arguments of
// `teleport integration configure access-graph azure` command.
type IntegrationConfAccessGraphAzureSync struct {
// ManagedIdentity is the principal performing the discovery
ManagedIdentity string
// RoleName is the name of the Azure Role to create and assign to the managed identity
RoleName string
// SubscriptionID is the Azure subscription containing resources for sync
SubscriptionID string
// AutoConfirm skips user confirmation of the operation plan if true
AutoConfirm bool
}
// IntegrationConfAzureOIDC contains the arguments of
// `teleport integration configure azure-oidc` command
type IntegrationConfAzureOIDC struct {
// ProxyPublicAddr is the publicly-reachable URL of the Teleport Proxy.
// It is used as the OIDC issuer URL, as well as for SAML URIs.
ProxyPublicAddr string
// AuthConnectorName is the name of the SAML connector that will be created on Teleport side.
AuthConnectorName string
// AccessGraphEnabled is a flag indicating that access graph integration is requested.
// When this is true, the integration script will produce
// a cache file necessary for TAG synchronization.
AccessGraphEnabled bool
// SkipOIDCConfiguration is a flag indicating that OIDC configuration should be skipped.
SkipOIDCConfiguration bool
}
// IntegrationConfDeployServiceIAM contains the arguments of
// `teleport integration configure deployservice-iam` command
type IntegrationConfDeployServiceIAM struct {
// Cluster is the teleport cluster name.
Cluster string
// Name is the integration name.
Name string
// Region is the AWS Region used to set up the client.
Region string
// Role is the AWS Role associated with the Integration
Role string
// TaskRole is the AWS Role to be used by the deployed service.
TaskRole string
// AccountID is the AWS account ID.
AccountID string
// AutoConfirm skips user confirmation of the operation plan if true.
AutoConfirm bool
}
// IntegrationConfAWSAppAccessIAM contains the arguments of
// `teleport integration configure aws-app-access-iam` command
type IntegrationConfAWSAppAccessIAM struct {
// RoleName is the AWS Role associated with the Integration
RoleName string
// AccountID is the AWS account ID.
AccountID string
// AutoConfirm skips user confirmation of the operation plan if true.
AutoConfirm bool
}
// IntegrationConfEC2SSMIAM contains the arguments of
// `teleport integration configure ec2-ssm-iam` command
type IntegrationConfEC2SSMIAM struct {
// RoleName is the AWS Role associated with the Integration
RoleName string
// Region is the AWS Region used to set up the client.
Region string
// SSMDocumentName is the SSM Document to be created that will run the installer script.
SSMDocumentName string
// ProxyPublicURL is Proxy's Public URL.
// This is used fetch the installer script.
// No trailing / is expected.
// Eg https://tenant.teleport.sh
ProxyPublicURL string
// ClusterName is the Teleport cluster name.
// Used for resource tagging.
ClusterName string
// IntegrationName is the Teleport AWS OIDC Integration name.
// Used for resource tagging.
IntegrationName string
// AccountID is the AWS account ID.
AccountID string
// AutoConfirm skips user confirmation of the operation plan if true.
AutoConfirm bool
}
// IntegrationConfEKSIAM contains the arguments of
// `teleport integration configure eks-iam` command
type IntegrationConfEKSIAM struct {
// Region is the AWS Region used to set up the client.
Region string
// Role is the AWS Role associated with the Integration
Role string
// AccountID is the AWS account ID.
AccountID string
// AutoConfirm skips user confirmation of the operation plan if true.
AutoConfirm bool
}
// IntegrationConfAWSOIDCIdP contains the arguments of
// `teleport integration configure awsoidc-idp` command
type IntegrationConfAWSOIDCIdP struct {
// Cluster is the teleport cluster name.
Cluster string
// Name is the integration name.
Name string
// Role is the AWS Role to associate with the Integration
Role string
// ProxyPublicURL is the IdP Issuer URL (Teleport Proxy Public Address).
// Eg, https://<tenant>.teleport.sh
ProxyPublicURL string
// AutoConfirm skips user confirmation of the operation plan if true.
AutoConfirm bool
// PolicyPreset is the name of a pre-defined policy statement which will be
// assigned to the AWS Role associate with the OIDC integration.
PolicyPreset string
}
// IntegrationConfListDatabasesIAM contains the arguments of
// `teleport integration configure listdatabases-iam` command
type IntegrationConfListDatabasesIAM struct {
// Region is the AWS Region used to set up the client.
Region string
// Role is the AWS Role associated with the Integration
Role string
// AccountID is the AWS account ID.
AccountID string
// AutoConfirm skips user confirmation of the operation plan if true.
AutoConfirm bool
}
// ReadConfigFile reads /etc/teleport.yaml (or whatever is passed via --config flag)
// and overrides values in 'cfg' structure
func ReadConfigFile(cliConfigPath string) (*FileConfig, error) {
configFilePath := defaults.ConfigFilePath
// --config tells us to use a specific conf. file:
if cliConfigPath != "" {
configFilePath = cliConfigPath
if !utils.FileExists(configFilePath) {
return nil, trace.NotFound("file %s is not found", configFilePath)
}
}
// default config doesn't exist? quietly return:
if !utils.FileExists(configFilePath) {
slog.InfoContext(context.Background(), "not using a config file")
return nil, nil
}
slog.DebugContext(context.Background(), "reading config file", "config_file", configFilePath)
return ReadFromFile(configFilePath)
}
// ReadResources loads a set of resources from a file.
func ReadResources(filePath string) ([]types.Resource, error) {
reader, err := utils.OpenFileAllowingUnsafeLinks(filePath)
if err != nil {
return nil, trace.Wrap(err)
}
defer reader.Close()
decoder := kyaml.NewYAMLOrJSONDecoder(reader, defaults.LookaheadBufSize)
var resources []types.Resource
for {
var raw services.UnknownResource
err := decoder.Decode(&raw)
if err != nil {
if errors.Is(err, io.EOF) {
break
}
return nil, trace.Wrap(err)
}
rsc, err := services.UnmarshalResource(raw.Kind, raw.Raw)
if err != nil {
return nil, trace.Wrap(err)
}
resources = append(resources, rsc)
}
return resources, nil
}
// ApplyFileConfig applies configuration from a YAML file to Teleport
// runtime config
//
// ApplyFileConfig is used by both teleport and tctl binaries.
func ApplyFileConfig(fc *FileConfig, cfg *servicecfg.Config) error {
var err error
// no config file? no problem
if fc == nil {
return nil
}
applyConfigVersion(fc, cfg)
// merge file-based config with defaults in 'cfg'
if fc.Auth.Disabled() {
cfg.Auth.Enabled = false
}
if fc.SSH.Disabled() {
cfg.SSH.Enabled = false
}
if fc.Proxy.Disabled() {
cfg.Proxy.Enabled = false
}
if fc.Kube.Enabled() {
cfg.Kube.Enabled = true
}
if fc.Apps.Disabled() {
cfg.Apps.Enabled = false
}
if fc.Databases.Disabled() {
cfg.Databases.Enabled = false
}
if fc.Metrics.Disabled() {
cfg.Metrics.Enabled = false
}
if fc.WindowsDesktop.Disabled() {
cfg.WindowsDesktop.Enabled = false
}
if fc.Debug.Disabled() {
cfg.DebugService.Enabled = false
}
if fc.AccessGraph.Enabled {
cfg.AccessGraph.Enabled = true
if fc.AccessGraph.Endpoint == "" {
return trace.BadParameter("access_graph.endpoint is required when access graph integration is enabled")
}
cfg.AccessGraph.Addr = fc.AccessGraph.Endpoint
cfg.AccessGraph.CA = fc.AccessGraph.CA
// TODO(tigrato): change this behavior when we drop support for plain text connections
cfg.AccessGraph.Insecure = fc.AccessGraph.Insecure
}
applyString(fc.NodeName, &cfg.Hostname)
// apply "advertise_ip" setting:
advertiseIP := fc.AdvertiseIP
if advertiseIP != "" {
if _, _, err := utils.ParseAdvertiseAddr(advertiseIP); err != nil {
return trace.Wrap(err)
}
cfg.AdvertiseIP = advertiseIP
}
cfg.PIDFile = fc.PIDFile
if err := applyAuthOrProxyAddress(fc, cfg); err != nil {
return trace.Wrap(err)
}
if err := applyTokenConfig(fc, cfg); err != nil {
return trace.Wrap(err)
}
if fc.Global.DataDir != "" {
cfg.DataDir = fc.Global.DataDir
cfg.Auth.StorageConfig.Params["path"] = cfg.DataDir
}
// If a backend is specified, override the defaults.
if fc.Storage.Type != "" {
// If the alternative name "dir" is given, update it to "lite".
if fc.Storage.Type == lite.AlternativeName {
fc.Storage.Type = lite.GetName()
}
cfg.Auth.StorageConfig = fc.Storage
// backend is specified, but no path is set, set a reasonable default
_, pathSet := cfg.Auth.StorageConfig.Params[defaults.BackendPath]
if cfg.Auth.StorageConfig.Type == lite.GetName() && !pathSet {
if cfg.Auth.StorageConfig.Params == nil {
cfg.Auth.StorageConfig.Params = make(backend.Params)
}
cfg.Auth.StorageConfig.Params[defaults.BackendPath] = filepath.Join(cfg.DataDir, defaults.BackendDir)
}
} else {
// Set a reasonable default.
cfg.Auth.StorageConfig.Params[defaults.BackendPath] = filepath.Join(cfg.DataDir, defaults.BackendDir)
}
// apply logger settings
err = applyLogConfig(fc.Logger, cfg)
if err != nil {
return trace.Wrap(err)
}
ctx := context.Background()
if fc.CachePolicy.TTL != "" {
slog.WarnContext(ctx, "cache.ttl config option is deprecated and will be ignored, caches no longer attempt to anticipate resource expiration")
}
if fc.CachePolicy.Type == memory.GetName() {
slog.DebugContext(ctx, "cache.type config option is explicitly set to memory")
} else if fc.CachePolicy.Type != "" {
slog.WarnContext(ctx, "cache.type config option is deprecated and will be ignored, caches are always in memory in this version")
}
// apply cache policy for node and proxy
cachePolicy, err := fc.CachePolicy.Parse()
if err != nil {
return trace.Wrap(err)
}
cfg.CachePolicy = *cachePolicy
// Apply (TLS) cipher suites and (SSH) ciphers, KEX algorithms, and MAC
// algorithms.
if len(fc.CipherSuites) > 0 {
cipherSuites, err := utils.CipherSuiteMapping(fc.CipherSuites)
if err != nil {
return trace.Wrap(err)
}
cfg.CipherSuites = cipherSuites
}
if fc.Ciphers != nil {
cfg.Ciphers = fc.Ciphers
}
if fc.KEXAlgorithms != nil {
cfg.KEXAlgorithms = fc.KEXAlgorithms
}
if fc.MACAlgorithms != nil {
cfg.MACAlgorithms = fc.MACAlgorithms
}
if fc.CASignatureAlgorithm != nil {
slog.WarnContext(ctx, "ca_signing_algo config option is deprecated and will be removed in a future release, Teleport defaults to rsa-sha2-512")
}
// Read in how nodes will validate the CA. A single empty string in the file
// conf should indicate no pins.
if err = cfg.ApplyCAPins(fc.CAPin); err != nil {
return trace.Wrap(err)
}
// Set diagnostic address
if fc.DiagAddr != "" {
// Validate address
parsed, err := utils.ParseAddr(fc.DiagAddr)
if err != nil {
return trace.Wrap(err)
}
cfg.DiagnosticAddr = *parsed
}
// apply connection throttling:
limiters := []*limiter.Config{
&cfg.SSH.Limiter,
&cfg.Auth.Limiter,
&cfg.Proxy.Limiter,
&cfg.Databases.Limiter,
&cfg.Kube.Limiter,
&cfg.WindowsDesktop.ConnLimiter,
}
for _, l := range limiters {
if fc.Limits.MaxConnections > 0 {
l.MaxConnections = fc.Limits.MaxConnections
}
for _, rate := range fc.Limits.Rates {
l.Rates = append(l.Rates, limiter.Rate{
Period: rate.Period,
Average: rate.Average,
Burst: rate.Burst,
})
}
}
// Apply configuration for "auth_service", "proxy_service", "ssh_service",
// and "app_service" if they are enabled.
if fc.Auth.Enabled() {
err = applyAuthConfig(fc, cfg)
if err != nil {
return trace.Wrap(err)
}
}
if fc.Proxy.Enabled() {
err = applyProxyConfig(fc, cfg)
if err != nil {
return trace.Wrap(err)
}
}
if fc.SSH.Enabled() {
err = applySSHConfig(fc, cfg)
if err != nil {
return trace.Wrap(err)
}
}
if fc.Kube.Enabled() {
if err := applyKubeConfig(fc, cfg); err != nil {
return trace.Wrap(err)
}
}
if fc.Apps.Enabled() {
if err := applyAppsConfig(fc, cfg); err != nil {
return trace.Wrap(err)
}
}
if fc.Databases.Enabled() {
if err := applyDatabasesConfig(fc, cfg); err != nil {
return trace.Wrap(err)
}
}
if fc.Metrics.Enabled() {
if err := applyMetricsConfig(fc, cfg); err != nil {
return trace.Wrap(err)
}
}
if fc.WindowsDesktop.Enabled() {
if err := applyWindowsDesktopConfig(fc, cfg); err != nil {
return trace.Wrap(err)
}
}
if fc.Tracing.Enabled() {
if err := applyTracingConfig(fc, cfg); err != nil {
return trace.Wrap(err)
}
}
if fc.Discovery.Enabled() {
if err := applyDiscoveryConfig(fc, cfg); err != nil {
return trace.Wrap(err)
}
}
if fc.Okta.Enabled() {
if err := applyOktaConfig(fc, cfg); err != nil {
return trace.Wrap(err)
}
}
if fc.Jamf.Enabled() {
if err := applyJamfConfig(fc, cfg); err != nil {
return trace.Wrap(err)
}
}
return nil
}
func applyAuthOrProxyAddress(fc *FileConfig, cfg *servicecfg.Config) error {
switch cfg.Version {
// For config versions v1 and v2, the auth_servers field can point to an auth
// server or a proxy server
case defaults.TeleportConfigVersionV1, defaults.TeleportConfigVersionV2:
// config file has auth servers in there?
if len(fc.AuthServers) > 0 {
var parsedAddresses []utils.NetAddr
for _, as := range fc.AuthServers {
addr, err := utils.ParseHostPortAddr(as, defaults.AuthListenPort)
if err != nil {
return trace.Wrap(err)
}
parsedAddresses = append(parsedAddresses, *addr)
}
if err := cfg.SetAuthServerAddresses(parsedAddresses); err != nil {
return trace.Wrap(err)
}
}
if fc.AuthServer != "" {
return trace.BadParameter("auth_server is supported from config version v3 onwards")
}
if fc.ProxyServer != "" {
return trace.BadParameter("proxy_server is supported from config version v3 onwards")
}
// From v3 onwards, either auth_server or proxy_server should be set
case defaults.TeleportConfigVersionV3:
if len(fc.AuthServers) > 0 {
return trace.BadParameter("config v3 has replaced auth_servers with either auth_server or proxy_server")
}
haveAuthServer := fc.AuthServer != ""
haveProxyServer := fc.ProxyServer != ""
if haveProxyServer && haveAuthServer {
return trace.BadParameter("only one of auth_server or proxy_server should be set")
}
if haveAuthServer {
addr, err := utils.ParseHostPortAddr(fc.AuthServer, defaults.AuthListenPort)
if err != nil {
return trace.Wrap(err)
}
cfg.SetAuthServerAddress(*addr)
}
if haveProxyServer {
if fc.Proxy.Enabled() {
return trace.BadParameter("proxy_server can not be specified when proxy service is enabled")
}
addr, err := utils.ParseHostPortAddr(fc.ProxyServer, defaults.HTTPListenPort)
if err != nil {
return trace.Wrap(err)
}
cfg.ProxyServer = *addr
}
}
return nil
}
func applyLogConfig(loggerConfig Log, cfg *servicecfg.Config) error {
logger, level, err := logutils.Initialize(logutils.Config{
Output: loggerConfig.Output,
Severity: loggerConfig.Severity,
Format: loggerConfig.Format.Output,
ExtraFields: loggerConfig.Format.ExtraFields,
EnableColors: utils.IsTerminal(os.Stderr),
})
if err != nil {
return trace.Wrap(err)
}
cfg.Logger = logger
cfg.LoggerLevel = level
return nil
}
// applyAuthConfig applies file configuration for the "auth_service" section.
func applyAuthConfig(fc *FileConfig, cfg *servicecfg.Config) error {
var err error
if fc.Auth.KubeconfigFile != "" {
const warningMessage = "The auth_service no longer needs kubeconfig_file. It has " +
"been moved to proxy_service section. This setting is ignored."
slog.WarnContext(context.Background(), warningMessage)
}
cfg.Auth.PROXYProtocolMode = multiplexer.PROXYProtocolUnspecified
if fc.Auth.ProxyProtocol != "" {
val := multiplexer.PROXYProtocolMode(fc.Auth.ProxyProtocol)
if err := validatePROXYProtocolValue(val); err != nil {
return trace.Wrap(err)
}
cfg.Auth.PROXYProtocolMode = val
}
if fc.Auth.ListenAddress != "" {
addr, err := utils.ParseHostPortAddr(fc.Auth.ListenAddress, int(defaults.AuthListenPort))
if err != nil {
return trace.Wrap(err)
}
cfg.Auth.ListenAddr = *addr
if len(cfg.AuthServerAddresses()) == 0 {
cfg.SetAuthServerAddress(*addr)
}
}
for _, t := range fc.Auth.ReverseTunnels {
tun, err := t.ConvertAndValidate()
if err != nil {
return trace.Wrap(err)
}
cfg.ReverseTunnels = append(cfg.ReverseTunnels, tun)
}
if len(fc.Auth.PublicAddr) != 0 {
addrs, err := utils.AddrsFromStrings(fc.Auth.PublicAddr, defaults.AuthListenPort)
if err != nil {
return trace.Wrap(err)
}
cfg.Auth.PublicAddrs = addrs
}
// read in cluster name from file configuration and create services.ClusterName
cfg.Auth.ClusterName, err = fc.Auth.ClusterName.Parse()
if err != nil {
return trace.Wrap(err)
}
// read in static tokens from file configuration and create services.StaticTokens
if fc.Auth.StaticTokens != nil {
cfg.Auth.StaticTokens, err = fc.Auth.StaticTokens.Parse()
if err != nil {
return trace.Wrap(err)
}
}
// read in and set authentication preferences
if fc.Auth.Authentication != nil {
cfg.Auth.Preference, err = fc.Auth.Authentication.Parse()
if err != nil {
return trace.Wrap(err)
}
}
if fc.Auth.MessageOfTheDay != "" {
cfg.Auth.Preference.SetMessageOfTheDay(fc.Auth.MessageOfTheDay)
}
if fc.Auth.DisconnectExpiredCert != nil {
cfg.Auth.Preference.SetOrigin(types.OriginConfigFile)
cfg.Auth.Preference.SetDisconnectExpiredCert(fc.Auth.DisconnectExpiredCert.Value)
}
// Set cluster audit configuration from file configuration.
auditConfigSpec, err := services.ClusterAuditConfigSpecFromObject(fc.Storage.Params)
if err != nil {
return trace.Wrap(err)
}
auditConfigSpec.Type = fc.Storage.Type
cfg.Auth.AuditConfig, err = types.NewClusterAuditConfig(*auditConfigSpec)
if err != nil {
return trace.Wrap(err)
}
// Only override networking configuration if some of its fields are
// specified in file configuration.
if fc.Auth.hasCustomNetworkingConfig() {
cfg.Auth.NetworkingConfig, err = types.NewClusterNetworkingConfigFromConfigFile(types.ClusterNetworkingConfigSpecV2{
ClientIdleTimeout: fc.Auth.ClientIdleTimeout,
ClientIdleTimeoutMessage: fc.Auth.ClientIdleTimeoutMessage,
WebIdleTimeout: fc.Auth.WebIdleTimeout,
KeepAliveInterval: fc.Auth.KeepAliveInterval,
KeepAliveCountMax: fc.Auth.KeepAliveCountMax,
SessionControlTimeout: fc.Auth.SessionControlTimeout,
ProxyListenerMode: fc.Auth.ProxyListenerMode,
RoutingStrategy: fc.Auth.RoutingStrategy,
TunnelStrategy: fc.Auth.TunnelStrategy,
ProxyPingInterval: fc.Auth.ProxyPingInterval,
CaseInsensitiveRouting: fc.Auth.CaseInsensitiveRouting,
SSHDialTimeout: fc.Auth.SSHDialTimeout,
})
if err != nil {
return trace.Wrap(err)
}
}
// Only override session recording configuration if either field is
// specified in file configuration.
if fc.Auth.hasCustomSessionRecording() {
cfg.Auth.SessionRecordingConfig, err = types.NewSessionRecordingConfigFromConfigFile(types.SessionRecordingConfigSpecV2{
Mode: fc.Auth.SessionRecording,
ProxyChecksHostKeys: fc.Auth.ProxyChecksHostKeys,
})
if err != nil {
return trace.Wrap(err)
}
}
if err := applyKeyStoreConfig(fc, cfg); err != nil {
return trace.Wrap(err)
}
// read in and set the license file path (not used in open-source version)
switch licenseFile := fc.Auth.LicenseFile; {
case licenseFile == "":
cfg.Auth.LicenseFile = filepath.Join(cfg.DataDir, defaults.LicenseFile)
case filepath.IsAbs(licenseFile):
cfg.Auth.LicenseFile = licenseFile
default:
cfg.Auth.LicenseFile = filepath.Join(cfg.DataDir, licenseFile)
}
cfg.Auth.LoadAllCAs = fc.Auth.LoadAllCAs
// Setting this to true at all times to allow self hosting
// of plugins that were previously cloud only.
cfg.Auth.HostedPlugins.Enabled = true
cfg.Auth.HostedPlugins.OAuthProviders, err = fc.Auth.HostedPlugins.OAuthProviders.Parse()
if err != nil {
return trace.Wrap(err)
}
if fc.Auth.AccessMonitoring != nil {
if err := fc.Auth.AccessMonitoring.CheckAndSetDefaults(); err != nil {
return trace.Wrap(err, "failed to validate access monitoring config")
}
cfg.Auth.AccessMonitoring = fc.Auth.AccessMonitoring
}
return nil
}
func applyKeyStoreConfig(fc *FileConfig, cfg *servicecfg.Config) error {
if fc.Auth.CAKeyParams == nil {
return nil
}
if fc.Auth.CAKeyParams.PKCS11 != nil {
if fc.Auth.CAKeyParams.GoogleCloudKMS != nil {
return trace.BadParameter("cannot set both pkcs11 and gcp_kms in file config")
}
if fc.Auth.CAKeyParams.AWSKMS != nil {
return trace.BadParameter("cannot set both pkcs11 and aws_kms in file config")
}
return trace.Wrap(applyPKCS11Config(fc.Auth.CAKeyParams.PKCS11, cfg))
}
if fc.Auth.CAKeyParams.GoogleCloudKMS != nil {
if fc.Auth.CAKeyParams.AWSKMS != nil {
return trace.BadParameter("cannot set both gpc_kms and aws_kms in file config")
}
return trace.Wrap(applyGoogleCloudKMSConfig(fc.Auth.CAKeyParams.GoogleCloudKMS, cfg))
}
if fc.Auth.CAKeyParams.AWSKMS != nil {
return trace.Wrap(applyAWSKMSConfig(fc.Auth.CAKeyParams.AWSKMS, cfg))
}
return nil
}
func applyPKCS11Config(pkcs11Config *PKCS11, cfg *servicecfg.Config) error {
if pkcs11Config.ModulePath != "" {
fi, err := utils.StatFile(pkcs11Config.ModulePath)
if err != nil {
return trace.Wrap(err)
}
const worldWritableBits = 0o002
if fi.Mode().Perm()&worldWritableBits != 0 {
return trace.Errorf(
"PKCS11 library (%s) must not be world-writable",
pkcs11Config.ModulePath,
)
}
cfg.Auth.KeyStore.PKCS11.Path = pkcs11Config.ModulePath
}
cfg.Auth.KeyStore.PKCS11.TokenLabel = pkcs11Config.TokenLabel
cfg.Auth.KeyStore.PKCS11.SlotNumber = pkcs11Config.SlotNumber
cfg.Auth.KeyStore.PKCS11.PIN = pkcs11Config.PIN
if pkcs11Config.PINPath != "" {
if pkcs11Config.PIN != "" {