-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
fileconf.go
1480 lines (1280 loc) · 51.8 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"
"fmt"
"io"
"io/ioutil"
"net"
"net/url"
"os"
"strings"
"time"
"golang.org/x/crypto/acme"
"golang.org/x/crypto/ssh"
"github.com/gravitational/teleport"
"github.com/gravitational/teleport/api/constants"
"github.com/gravitational/teleport/api/types"
apiutils "github.com/gravitational/teleport/api/utils"
"github.com/gravitational/teleport/api/utils/tlsutils"
"github.com/gravitational/teleport/lib/backend"
"github.com/gravitational/teleport/lib/bpf"
"github.com/gravitational/teleport/lib/defaults"
"github.com/gravitational/teleport/lib/pam"
restricted "github.com/gravitational/teleport/lib/restrictedsession"
"github.com/gravitational/teleport/lib/service"
"github.com/gravitational/teleport/lib/services"
"github.com/gravitational/teleport/lib/sshutils/x11"
"github.com/gravitational/teleport/lib/utils"
"github.com/gravitational/trace"
log "github.com/sirupsen/logrus"
"gopkg.in/yaml.v2"
)
var validCASigAlgos = []string{
ssh.SigAlgoRSA,
ssh.SigAlgoRSASHA2256,
ssh.SigAlgoRSASHA2512,
}
// 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"`
}
// 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 {
return nil, trace.Wrap(err, fmt.Sprintf("failed to open file: %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 := ioutil.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
}
// 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
g.NodeName = conf.Hostname
g.Logger.Output = "stderr"
g.Logger.Severity = "INFO"
g.Logger.Format.Output = "text"
g.DataDir = defaults.DataDir
// SSH config:
var s SSH
s.EnabledFlag = "yes"
s.ListenAddress = conf.SSH.Addr.Addr
s.Commands = []CommandLabel{
{
Name: "hostname",
Command: []string{"hostname"},
Period: time.Minute,
},
}
s.Labels = map[string]string{
"env": "example",
}
// Auth config:
var a Auth
a.ListenAddress = conf.Auth.SSHAddr.Addr
a.ClusterName = ClusterName(flags.ClusterName)
a.EnabledFlag = "yes"
if flags.LicensePath != "" {
a.LicenseFile = flags.LicensePath
}
if flags.Version == defaults.TeleportConfigVersionV2 {
a.ProxyListenerMode = types.ProxyListenerMode_Multiplex
}
// sample proxy config:
var p Proxy
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 nil, 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 nil, 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,
})
}
fc = &FileConfig{
Version: flags.Version,
Global: g,
Proxy: p,
SSH: s,
Auth: a,
}
return fc, nil
}
// 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 conf.CASignatureAlgorithm != nil && !apiutils.SliceContainsStr(validCASigAlgos, *conf.CASignatureAlgorithm) {
return trace.BadParameter("CA signature algorithm %q is not supported; supported algorithms: %q", *conf.CASignatureAlgorithm, validCASigAlgos)
}
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"`
AuthToken string `yaml:"auth_token,omitempty"`
JoinParams JoinParams `yaml:"join_params,omitempty"`
AuthServers []string `yaml:"auth_servers,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"`
SeedConfig *bool `yaml:"seed_config,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 an SSH Certificate Authority (CA) signature
// algorithm that the server uses for signing user and host certificates.
// If omitted, the default will be used.
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{
Type: c.Type,
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"`
// TrustedClustersFile is a file path to a file containing public CA keys
// of clusters we trust. One key per line, those starting with '#' are comments
// Deprecated: Remove in Teleport 2.4.1.
TrustedClusters []TrustedCluster `yaml:"trusted_clusters,omitempty"`
// OIDCConnectors is a list of trusted OpenID Connect Identity providers
// Deprecated: Remove in Teleport 2.4.1.
OIDCConnectors []OIDCConnector `yaml:"oidc_connectors,omitempty"`
// DynamicConfig determines when file configuration is pushed to the backend. Setting
// it here overrides defaults.
// Deprecated: Remove in Teleport 2.4.1.
DynamicConfig *bool `yaml:"dynamic_config,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"`
}
// CAKeyParams configures how CA private keys will be created and stored.
type CAKeyParams struct {
// PKCS11 configures a PKCS#11 HSM to be used for private key generation and
// storage.
PKCS11 PKCS11 `yaml:"pkcs11"`
}
// 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"`
}
// 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) {
staticTokens := []types.ProvisionTokenV1{}
for _, token := range t {
st, err := token.Parse()
if err != nil {
return nil, trace.Wrap(err)
}
staticTokens = append(staticTokens, *st)
}
return types.NewStaticTokens(types.StaticTokensSpecV2{
StaticTokens: staticTokens,
})
}
type StaticToken string
// Parse is applied to a string in "role,role,role:token" format. It breaks it
// apart and constructs a services.ProvisionToken which contains the token,
// role, and expiry (infinite).
func (t StaticToken) Parse() (*types.ProvisionTokenV1, error) {
parts := strings.Split(string(t), ":")
if len(parts) != 2 {
return nil, trace.BadParameter("invalid static token spec: %q", t)
}
roles, err := types.ParseTeleportRoles(parts[0])
if err != nil {
return nil, trace.Wrap(err)
}
token, err := utils.ReadToken(parts[1])
if err != nil {
return nil, trace.Wrap(err)
}
return &types.ProvisionTokenV1{
Token: token,
Roles: roles,
Expires: time.Unix(0, 0).UTC(),
}, nil
}
// AuthenticationConfig describes the auth_service/authentication section of teleport.yaml
type AuthenticationConfig struct {
Type string `yaml:"type"`
SecondFactor constants.SecondFactorType `yaml:"second_factor,omitempty"`
ConnectorName string `yaml:"connector_name,omitempty"`
U2F *UniversalSecondFactor `yaml:"u2f,omitempty"`
Webauthn *Webauthn `yaml:"webauthn,omitempty"`
RequireSessionMFA bool `yaml:"require_session_mfa,omitempty"`
LockingMode constants.LockingMode `yaml:"locking_mode,omitempty"`
// LocalAuth controls if local authentication is allowed.
LocalAuth *types.BoolOption `yaml:"local_auth"`
}
// Parse returns a types.AuthPreference (type, second factor, U2F).
func (a *AuthenticationConfig) Parse() (types.AuthPreference, error) {
var err error
var u *types.U2F
if a.U2F != nil {
u, err = a.U2F.Parse()
if err != nil {
return nil, trace.Wrap(err)
}
}
var w *types.Webauthn
if a.Webauthn != nil {
w, err = a.Webauthn.Parse()
if err != nil {
return nil, trace.Wrap(err)
}
}
return types.NewAuthPreferenceFromConfigFile(types.AuthPreferenceSpecV2{
Type: a.Type,
SecondFactor: a.SecondFactor,
ConnectorName: a.ConnectorName,
U2F: u,
Webauthn: w,
RequireSessionMFA: a.RequireSessionMFA,
LockingMode: a.LockingMode,
AllowLocalAuth: a.LocalAuth,
})
}
type UniversalSecondFactor struct {
AppID string `yaml:"app_id"`
Facets []string `yaml:"facets"`
DeviceAttestationCAs []string `yaml:"device_attestation_cas"`
}
func (u *UniversalSecondFactor) Parse() (*types.U2F, error) {
attestationCAs, err := getAttestationPEMs(u.DeviceAttestationCAs)
if err != nil {
return nil, trace.BadParameter("u2f.device_attestation_cas: %v", err)
}
return &types.U2F{
AppID: u.AppID,
Facets: u.Facets,
DeviceAttestationCAs: attestationCAs,
}, nil
}
type Webauthn struct {
RPID string `yaml:"rp_id,omitempty"`
AttestationAllowedCAs []string `yaml:"attestation_allowed_cas,omitempty"`
AttestationDeniedCAs []string `yaml:"attestation_denied_cas,omitempty"`
// Disabled has no effect, it is kept solely to not break existing
// configurations.
// DELETE IN 11.0, time to sunset U2F (codingllama).
Disabled bool `yaml:"disabled,omitempty"`
}
func (w *Webauthn) Parse() (*types.Webauthn, error) {
allowedCAs, err := getAttestationPEMs(w.AttestationAllowedCAs)
if err != nil {
return nil, trace.BadParameter("webauthn.attestation_allowed_cas: %v", err)
}
deniedCAs, err := getAttestationPEMs(w.AttestationDeniedCAs)
if err != nil {
return nil, trace.BadParameter("webauthn.attestation_denied_cas: %v", err)
}
if w.Disabled {
log.Warnf(`` +
`The "webauthn.disabled" setting is marked for removal and currently has no effect. ` +
`Please update your configuration to use WebAuthn. ` +
`Refer to https://goteleport.com/docs/access-controls/guides/webauthn/`)
}
return &types.Webauthn{
// Allow any RPID to go through, we rely on
// types.Webauthn.CheckAndSetDefaults to correct it.
RPID: w.RPID,
AttestationAllowedCAs: allowedCAs,
AttestationDeniedCAs: deniedCAs,
}, nil
}
func getAttestationPEMs(certOrPaths []string) ([]string, error) {
res := make([]string, len(certOrPaths))
for i, certOrPath := range certOrPaths {
pem, err := getAttestationPEM(certOrPath)
if err != nil {
return nil, err
}
res[i] = pem
}
return res, nil
}
func getAttestationPEM(certOrPath string) (string, error) {
_, parseErr := tlsutils.ParseCertificatePEM([]byte(certOrPath))
if parseErr == nil {
return certOrPath, nil // OK, valid inline PEM
}
// Try reading as a file and parsing that.
data, err := ioutil.ReadFile(certOrPath)
if err != nil {
// Don't use trace in order to keep a clean error message.
return "", fmt.Errorf("%q is not a valid x509 certificate (%v) and can't be read as a file (%v)", certOrPath, parseErr, err)
}
if _, err := tlsutils.ParseCertificatePEM(data); err != nil {
// Don't use trace in order to keep a clean error message.
return "", fmt.Errorf("file %q contains an invalid x509 certificate: %v", certOrPath, err)
}
return string(data), nil // OK, valid PEM file
}
// SSH is 'ssh_service' section of the config file
type SSH struct {
Service `yaml:",inline"`
Namespace string `yaml:"namespace,omitempty"`
Labels map[string]string `yaml:"labels,omitempty"`
Commands []CommandLabel `yaml:"commands,omitempty"`
PermitUserEnvironment bool `yaml:"permit_user_env,omitempty"`
PAM *PAM `yaml:"pam,omitempty"`
// PublicAddr sets SSH host principals for SSH service
PublicAddr apiutils.Strings `yaml:"public_addr,omitempty"`
// BPF is used to configure BPF-based auditing for this node.
BPF *BPF `yaml:"enhanced_recording,omitempty"`
// RestrictedSession is used to restrict access to kernel objects
RestrictedSession *RestrictedSession `yaml:"restricted_session,omitempty"`
// MaybeAllowTCPForwarding enables or disables TCP port forwarding. We're
// using a pointer-to-bool here because the system default is to allow TCP
// forwarding, we need to distinguish between an unset value and a false
// value so we can an override unset value with `true`.
//
// Don't read this value directly: call the AllowTCPForwarding method
// instead.
MaybeAllowTCPForwarding *bool `yaml:"port_forwarding,omitempty"`
// X11 is used to configure X11 forwarding settings
X11 *X11 `yaml:"x11,omitempty"`
}
// AllowTCPForwarding checks whether the config file allows TCP forwarding or not.
func (ssh *SSH) AllowTCPForwarding() bool {
if ssh.MaybeAllowTCPForwarding == nil {
return true
}
return *ssh.MaybeAllowTCPForwarding
}
// X11ServerConfig returns the X11 forwarding server configuration.
func (ssh *SSH) X11ServerConfig() (*x11.ServerConfig, error) {
// Start with default configuration
cfg := &x11.ServerConfig{Enabled: false}
if ssh.X11 == nil {
return cfg, nil
}
var err error
cfg.Enabled, err = apiutils.ParseBool(ssh.X11.Enabled)
if err != nil {
return nil, trace.Wrap(err)
}
if !cfg.Enabled {
return cfg, nil
}
cfg.MaxDisplay = x11.DefaultMaxDisplay
if ssh.X11.MaxDisplay != nil {
cfg.MaxDisplay = int(*ssh.X11.MaxDisplay)
// If set, max display must not be greater than the
// max display number supported by X Server
if cfg.MaxDisplay > x11.MaxDisplayNumber {
cfg.DisplayOffset = x11.MaxDisplayNumber
}
}
cfg.DisplayOffset = x11.DefaultDisplayOffset
if ssh.X11.DisplayOffset != nil {
cfg.DisplayOffset = int(*ssh.X11.DisplayOffset)
// If set, display offset must not be greater than the
// max display number
if cfg.DisplayOffset > cfg.MaxDisplay {
cfg.DisplayOffset = cfg.MaxDisplay
}
}
return cfg, nil
}
// CommandLabel is `command` section of `ssh_service` in the config file
type CommandLabel struct {
Name string `yaml:"name"`
Command []string `yaml:"command,flow"`
Period time.Duration `yaml:"period"`
}
// PAM is configuration for Pluggable Authentication Modules (PAM).
type PAM struct {
// Enabled controls if PAM will be used or not.
Enabled string `yaml:"enabled"`
// ServiceName is the name of the PAM policy to apply.
ServiceName string `yaml:"service_name"`
// UsePAMAuth specifies whether to trigger the "auth" PAM modules from the
// policy.
UsePAMAuth bool `yaml:"use_pam_auth"`
// Environment represents environment variables to pass to PAM.
// These may contain role-style interpolation syntax.
Environment map[string]string `yaml:"environment,omitempty"`
}
// Parse returns a parsed pam.Config.
func (p *PAM) Parse() *pam.Config {
serviceName := p.ServiceName
if serviceName == "" {
serviceName = defaults.ServiceName
}
enabled, _ := apiutils.ParseBool(p.Enabled)
return &pam.Config{
Enabled: enabled,
ServiceName: serviceName,
UsePAMAuth: p.UsePAMAuth,
Environment: p.Environment,
}
}
// BPF is configuration for BPF-based auditing.
type BPF struct {
// Enabled enables or disables enhanced session recording for this node.
Enabled string `yaml:"enabled"`
// CommandBufferSize is the size of the perf buffer for command events.
CommandBufferSize *int `yaml:"command_buffer_size,omitempty"`
// DiskBufferSize is the size of the perf buffer for disk events.
DiskBufferSize *int `yaml:"disk_buffer_size,omitempty"`
// NetworkBufferSize is the size of the perf buffer for network events.
NetworkBufferSize *int `yaml:"network_buffer_size,omitempty"`
// CgroupPath controls where cgroupv2 hierarchy is mounted.
CgroupPath string `yaml:"cgroup_path"`
}
// Parse will parse the enhanced session recording configuration.
func (b *BPF) Parse() *bpf.Config {
enabled, _ := apiutils.ParseBool(b.Enabled)
return &bpf.Config{
Enabled: enabled,
CommandBufferSize: b.CommandBufferSize,
DiskBufferSize: b.DiskBufferSize,
NetworkBufferSize: b.NetworkBufferSize,
CgroupPath: b.CgroupPath,
}
}
// RestrictedSession is a configuration for limiting access to kernel objects
type RestrictedSession struct {
// Enabled enables or disables enforcemant for this node.
Enabled string `yaml:"enabled"`
// EventsBufferSize is the size in bytes of the channel to report events
// from the kernel to us.
EventsBufferSize *int `yaml:"events_buffer_size,omitempty"`
}
// Parse will parse the enhanced session recording configuration.
func (r *RestrictedSession) Parse() (*restricted.Config, error) {
enabled, err := apiutils.ParseBool(r.Enabled)
if err != nil {
return nil, trace.Wrap(err)
}
return &restricted.Config{
Enabled: enabled,
EventsBufferSize: r.EventsBufferSize,
}, nil
}
// X11 is a configuration for X11 forwarding
type X11 struct {
// Enabled controls whether X11 forwarding requests can be granted by the server.
Enabled string `yaml:"enabled"`
// DisplayOffset tells the server what X11 display number to start from when
// searching for an open X11 unix socket for XServer proxies.
DisplayOffset *uint `yaml:"display_offset,omitempty"`
// DisplayOffset tells the server what X11 display number to stop at when
// searching for an open X11 unix socket for XServer proxies.
MaxDisplay *uint `yaml:"max_displays,omitempty"`
}
// Databases represents the database proxy service configuration.
//
// In the configuration file this section will be "db_service".
type Databases struct {
// Service contains common service fields.
Service `yaml:",inline"`
// Databases is a list of databases proxied by the service.
Databases []*Database `yaml:"databases"`