-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
Copy pathauth.go
5412 lines (4842 loc) · 178 KB
/
auth.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-2019 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 auth implements certificate signing authority and access control server
// Authority server is composed of several parts:
//
// * Authority server itself that implements signing and acl logic
// * HTTP server wrapper for authority server
// * HTTP client wrapper
package auth
import (
"bytes"
"context"
"crypto/rand"
"crypto/subtle"
"crypto/tls"
"crypto/x509"
"errors"
"fmt"
"math"
"math/big"
insecurerand "math/rand"
"os"
"sort"
"strings"
"sync"
"time"
"github.com/coreos/go-oidc/oauth2"
"github.com/google/uuid"
liblicense "github.com/gravitational/license"
"github.com/gravitational/trace"
"github.com/jonboulle/clockwork"
"github.com/prometheus/client_golang/prometheus"
"github.com/sirupsen/logrus"
"go.opentelemetry.io/otel/exporters/otlp/otlptrace"
"golang.org/x/crypto/ssh"
"golang.org/x/exp/slices"
"google.golang.org/protobuf/types/known/durationpb"
"github.com/gravitational/teleport"
"github.com/gravitational/teleport/api/client"
"github.com/gravitational/teleport/api/client/proto"
"github.com/gravitational/teleport/api/constants"
apidefaults "github.com/gravitational/teleport/api/defaults"
"github.com/gravitational/teleport/api/types"
apievents "github.com/gravitational/teleport/api/types/events"
"github.com/gravitational/teleport/api/types/wrappers"
apiutils "github.com/gravitational/teleport/api/utils"
"github.com/gravitational/teleport/api/utils/keys"
"github.com/gravitational/teleport/api/utils/retryutils"
apisshutils "github.com/gravitational/teleport/api/utils/sshutils"
"github.com/gravitational/teleport/lib/auth/keystore"
"github.com/gravitational/teleport/lib/auth/native"
wanlib "github.com/gravitational/teleport/lib/auth/webauthn"
"github.com/gravitational/teleport/lib/authz"
"github.com/gravitational/teleport/lib/backend"
"github.com/gravitational/teleport/lib/circleci"
"github.com/gravitational/teleport/lib/defaults"
"github.com/gravitational/teleport/lib/events"
"github.com/gravitational/teleport/lib/githubactions"
"github.com/gravitational/teleport/lib/gitlab"
"github.com/gravitational/teleport/lib/inventory"
kubeutils "github.com/gravitational/teleport/lib/kube/utils"
"github.com/gravitational/teleport/lib/kubernetestoken"
"github.com/gravitational/teleport/lib/limiter"
"github.com/gravitational/teleport/lib/loginrule"
"github.com/gravitational/teleport/lib/modules"
"github.com/gravitational/teleport/lib/observability/metrics"
"github.com/gravitational/teleport/lib/observability/tracing"
"github.com/gravitational/teleport/lib/release"
"github.com/gravitational/teleport/lib/services"
"github.com/gravitational/teleport/lib/services/local"
"github.com/gravitational/teleport/lib/session"
"github.com/gravitational/teleport/lib/srv/db/common/role"
"github.com/gravitational/teleport/lib/sshca"
"github.com/gravitational/teleport/lib/sshutils"
"github.com/gravitational/teleport/lib/tlsca"
usagereporter "github.com/gravitational/teleport/lib/usagereporter/teleport"
"github.com/gravitational/teleport/lib/utils"
"github.com/gravitational/teleport/lib/utils/interval"
vc "github.com/gravitational/teleport/lib/versioncontrol"
"github.com/gravitational/teleport/lib/versioncontrol/github"
uw "github.com/gravitational/teleport/lib/versioncontrol/upgradewindow"
)
const (
ErrFieldKeyUserMaxedAttempts = "maxed-attempts"
// MaxFailedAttemptsErrMsg is a user friendly error message that tells a user that they are locked.
MaxFailedAttemptsErrMsg = "too many incorrect attempts, please try again later"
)
const (
// githubCacheTimeout is how long Github org entries are cached.
githubCacheTimeout = time.Hour
// mfaDeviceNameMaxLen is the maximum length of a device name.
mfaDeviceNameMaxLen = 30
)
var ErrRequiresEnterprise = services.ErrRequiresEnterprise
// ServerOption allows setting options as functional arguments to Server
type ServerOption func(*Server) error
// NewServer creates and configures a new Server instance
func NewServer(cfg *InitConfig, opts ...ServerOption) (*Server, error) {
err := metrics.RegisterPrometheusCollectors(prometheusCollectors...)
if err != nil {
return nil, trace.Wrap(err)
}
if cfg.Trust == nil {
cfg.Trust = local.NewCAService(cfg.Backend)
}
if cfg.Presence == nil {
cfg.Presence = local.NewPresenceService(cfg.Backend)
}
if cfg.Provisioner == nil {
cfg.Provisioner = local.NewProvisioningService(cfg.Backend)
}
if cfg.Identity == nil {
cfg.Identity = local.NewIdentityService(cfg.Backend)
}
if cfg.Access == nil {
cfg.Access = local.NewAccessService(cfg.Backend)
}
if cfg.DynamicAccessExt == nil {
cfg.DynamicAccessExt = local.NewDynamicAccessService(cfg.Backend)
}
if cfg.ClusterConfiguration == nil {
clusterConfig, err := local.NewClusterConfigurationService(cfg.Backend)
if err != nil {
return nil, trace.Wrap(err)
}
cfg.ClusterConfiguration = clusterConfig
}
if cfg.Restrictions == nil {
cfg.Restrictions = local.NewRestrictionsService(cfg.Backend)
}
if cfg.Apps == nil {
cfg.Apps = local.NewAppService(cfg.Backend)
}
if cfg.Databases == nil {
cfg.Databases = local.NewDatabasesService(cfg.Backend)
}
if cfg.DatabaseServices == nil {
cfg.DatabaseServices = local.NewDatabaseServicesService(cfg.Backend)
}
if cfg.Kubernetes == nil {
cfg.Kubernetes = local.NewKubernetesService(cfg.Backend)
}
if cfg.Status == nil {
cfg.Status = local.NewStatusService(cfg.Backend)
}
if cfg.Events == nil {
cfg.Events = local.NewEventsService(cfg.Backend)
}
if cfg.AuditLog == nil {
cfg.AuditLog = events.NewDiscardAuditLog()
}
if cfg.Emitter == nil {
cfg.Emitter = events.NewDiscardEmitter()
}
if cfg.Streamer == nil {
cfg.Streamer = events.NewDiscardEmitter()
}
if cfg.WindowsDesktops == nil {
cfg.WindowsDesktops = local.NewWindowsDesktopService(cfg.Backend)
}
if cfg.SAMLIdPServiceProviders == nil {
cfg.SAMLIdPServiceProviders, err = local.NewSAMLIdPServiceProviderService(cfg.Backend)
if err != nil {
return nil, trace.Wrap(err)
}
}
if cfg.UserGroups == nil {
cfg.UserGroups, err = local.NewUserGroupService(cfg.Backend)
if err != nil {
return nil, trace.Wrap(err)
}
}
if cfg.ConnectionsDiagnostic == nil {
cfg.ConnectionsDiagnostic = local.NewConnectionsDiagnosticService(cfg.Backend)
}
if cfg.SessionTrackerService == nil {
cfg.SessionTrackerService, err = local.NewSessionTrackerService(cfg.Backend)
if err != nil {
return nil, trace.Wrap(err)
}
}
if cfg.AssertionReplayService == nil {
cfg.AssertionReplayService = local.NewAssertionReplayService(cfg.Backend)
}
if cfg.TraceClient == nil {
cfg.TraceClient = tracing.NewNoopClient()
}
if cfg.UsageReporter == nil {
cfg.UsageReporter = usagereporter.DiscardUsageReporter{}
}
if cfg.Okta == nil {
cfg.Okta, err = local.NewOktaService(cfg.Backend, cfg.Clock)
if err != nil {
return nil, trace.Wrap(err)
}
}
if cfg.Integrations == nil {
cfg.Integrations, err = local.NewIntegrationsService(cfg.Backend)
if err != nil {
return nil, trace.Wrap(err)
}
}
limiter, err := limiter.NewConnectionsLimiter(limiter.Config{
MaxConnections: defaults.LimiterMaxConcurrentSignatures,
})
if err != nil {
return nil, trace.Wrap(err)
}
if cfg.KeyStoreConfig.PKCS11 != (keystore.PKCS11Config{}) {
if !modules.GetModules().Features().HSM {
return nil, fmt.Errorf("PKCS11 HSM support requires a license with the HSM feature enabled: %w", ErrRequiresEnterprise)
}
cfg.KeyStoreConfig.PKCS11.HostUUID = cfg.HostUUID
} else if cfg.KeyStoreConfig.GCPKMS != (keystore.GCPKMSConfig{}) {
if !modules.GetModules().Features().HSM {
return nil, fmt.Errorf("Google Cloud KMS support requires a license with the HSM feature enabled: %w", ErrRequiresEnterprise)
}
cfg.KeyStoreConfig.GCPKMS.HostUUID = cfg.HostUUID
} else {
native.PrecomputeKeys()
cfg.KeyStoreConfig.Software.RSAKeyPairSource = native.GenerateKeyPair
}
cfg.KeyStoreConfig.Logger = log
keyStore, err := keystore.NewManager(context.Background(), cfg.KeyStoreConfig)
if err != nil {
return nil, trace.Wrap(err)
}
services := &Services{
Trust: cfg.Trust,
PresenceInternal: cfg.Presence,
Provisioner: cfg.Provisioner,
Identity: cfg.Identity,
Access: cfg.Access,
DynamicAccessExt: cfg.DynamicAccessExt,
ClusterConfiguration: cfg.ClusterConfiguration,
Restrictions: cfg.Restrictions,
Apps: cfg.Apps,
Kubernetes: cfg.Kubernetes,
Databases: cfg.Databases,
DatabaseServices: cfg.DatabaseServices,
AuditLogSessionStreamer: cfg.AuditLog,
Events: cfg.Events,
WindowsDesktops: cfg.WindowsDesktops,
SAMLIdPServiceProviders: cfg.SAMLIdPServiceProviders,
UserGroups: cfg.UserGroups,
SessionTrackerService: cfg.SessionTrackerService,
ConnectionsDiagnostic: cfg.ConnectionsDiagnostic,
Integrations: cfg.Integrations,
Okta: cfg.Okta,
StatusInternal: cfg.Status,
UsageReporter: cfg.UsageReporter,
}
closeCtx, cancelFunc := context.WithCancel(context.TODO())
as := Server{
bk: cfg.Backend,
clock: cfg.Clock,
limiter: limiter,
Authority: cfg.Authority,
AuthServiceName: cfg.AuthServiceName,
ServerID: cfg.HostUUID,
githubClients: make(map[string]*githubClient),
cancelFunc: cancelFunc,
closeCtx: closeCtx,
emitter: cfg.Emitter,
streamer: cfg.Streamer,
Unstable: local.NewUnstableService(cfg.Backend, cfg.AssertionReplayService),
Services: services,
Cache: services,
keyStore: keyStore,
traceClient: cfg.TraceClient,
fips: cfg.FIPS,
loadAllCAs: cfg.LoadAllCAs,
httpClientForAWSSTS: cfg.HTTPClientForAWSSTS,
}
as.inventory = inventory.NewController(&as, services, inventory.WithAuthServerID(cfg.HostUUID))
for _, o := range opts {
if err := o(&as); err != nil {
return nil, trace.Wrap(err)
}
}
if as.clock == nil {
as.clock = clockwork.NewRealClock()
}
as.githubOrgSSOCache, err = utils.NewFnCache(utils.FnCacheConfig{
TTL: githubCacheTimeout,
})
if err != nil {
return nil, trace.Wrap(err)
}
as.ttlCache, err = utils.NewFnCache(utils.FnCacheConfig{
TTL: time.Second * 3,
})
if err != nil {
return nil, trace.Wrap(err)
}
if as.ghaIDTokenValidator == nil {
as.ghaIDTokenValidator = githubactions.NewIDTokenValidator(
githubactions.IDTokenValidatorConfig{
Clock: as.clock,
},
)
}
if as.gitlabIDTokenValidator == nil {
as.gitlabIDTokenValidator, err = gitlab.NewIDTokenValidator(
gitlab.IDTokenValidatorConfig{
Clock: as.clock,
ClusterNameGetter: services,
},
)
if err != nil {
return nil, trace.Wrap(err)
}
}
if as.circleCITokenValidate == nil {
as.circleCITokenValidate = func(
ctx context.Context, organizationID, token string,
) (*circleci.IDTokenClaims, error) {
return circleci.ValidateToken(
ctx, as.clock, circleci.IssuerURLTemplate, organizationID, token,
)
}
}
if as.kubernetesTokenValidator == nil {
as.kubernetesTokenValidator = &kubernetestoken.Validator{}
}
return &as, nil
}
type Services struct {
services.Trust
services.PresenceInternal
services.Provisioner
services.Identity
services.Access
services.DynamicAccessExt
services.ClusterConfiguration
services.Restrictions
services.Apps
services.Kubernetes
services.Databases
services.DatabaseServices
services.WindowsDesktops
services.SAMLIdPServiceProviders
services.UserGroups
services.SessionTrackerService
services.ConnectionsDiagnostic
services.StatusInternal
services.Integrations
services.Okta
usagereporter.UsageReporter
types.Events
events.AuditLogSessionStreamer
}
// GetWebSession returns existing web session described by req.
// Implements ReadAccessPoint
func (r *Services) GetWebSession(ctx context.Context, req types.GetWebSessionRequest) (types.WebSession, error) {
return r.Identity.WebSessions().Get(ctx, req)
}
// GetWebToken returns existing web token described by req.
// Implements ReadAccessPoint
func (r *Services) GetWebToken(ctx context.Context, req types.GetWebTokenRequest) (types.WebToken, error) {
return r.Identity.WebTokens().Get(ctx, req)
}
// OktaClient returns the okta client.
func (r *Services) OktaClient() services.Okta {
return r
}
var (
generateRequestsCount = prometheus.NewCounter(
prometheus.CounterOpts{
Name: teleport.MetricGenerateRequests,
Help: "Number of requests to generate new server keys",
},
)
generateThrottledRequestsCount = prometheus.NewCounter(
prometheus.CounterOpts{
Name: teleport.MetricGenerateRequestsThrottled,
Help: "Number of throttled requests to generate new server keys",
},
)
generateRequestsCurrent = prometheus.NewGauge(
prometheus.GaugeOpts{
Name: teleport.MetricGenerateRequestsCurrent,
Help: "Number of current generate requests for server keys",
},
)
generateRequestsLatencies = prometheus.NewHistogram(
prometheus.HistogramOpts{
Name: teleport.MetricGenerateRequestsHistogram,
Help: "Latency for generate requests for server keys",
// lowest bucket start of upper bound 0.001 sec (1 ms) with factor 2
// highest bucket start of 0.001 sec * 2^15 == 32.768 sec
Buckets: prometheus.ExponentialBuckets(0.001, 2, 16),
},
)
// UserLoginCount counts user logins
UserLoginCount = prometheus.NewCounter(
prometheus.CounterOpts{
Name: teleport.MetricUserLoginCount,
Help: "Number of times there was a user login",
},
)
heartbeatsMissedByAuth = prometheus.NewGauge(
prometheus.GaugeOpts{
Name: teleport.MetricHeartbeatsMissed,
Help: "Number of heartbeats missed by auth server",
},
)
registeredAgents = prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Namespace: teleport.MetricNamespace,
Name: teleport.MetricRegisteredServers,
Help: "The number of Teleport services that are connected to an auth server by version.",
},
[]string{teleport.TagVersion},
)
migrations = prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Namespace: teleport.MetricNamespace,
Name: teleport.MetricMigrations,
Help: "Migrations tracks for each migration if it is active (1) or not (0).",
},
[]string{teleport.TagMigration},
)
prometheusCollectors = []prometheus.Collector{
generateRequestsCount, generateThrottledRequestsCount,
generateRequestsCurrent, generateRequestsLatencies, UserLoginCount, heartbeatsMissedByAuth,
registeredAgents, migrations,
}
)
// LoginHook is a function that will be called on a successful login. This will likely be used
// for enterprise services that need to add in feature specific operations after a user has been
// successfully authenticated. An example would be creating objects based on the user.
type LoginHook func(context.Context, types.User) error
// Server keeps the cluster together. It acts as a certificate authority (CA) for
// a cluster and:
// - generates the keypair for the node it's running on
// - invites other SSH nodes to a cluster, by issuing invite tokens
// - adds other SSH nodes to a cluster, by checking their token and signing their keys
// - same for users and their sessions
// - checks public keys to see if they're signed by it (can be trusted or not)
type Server struct {
lock sync.RWMutex
githubClients map[string]*githubClient
clock clockwork.Clock
bk backend.Backend
closeCtx context.Context
cancelFunc context.CancelFunc
samlAuthService SAMLService
oidcAuthService OIDCService
releaseService release.Client
loginRuleEvaluator loginrule.Evaluator
sshca.Authority
upgradeWindowStartHourGetter func(context.Context) (int64, error)
// AuthServiceName is a human-readable name of this CA. If several Auth services are running
// (managing multiple teleport clusters) this field is used to tell them apart in UIs
// It usually defaults to the hostname of the machine the Auth service runs on.
AuthServiceName string
// ServerID is the server ID of this auth server.
ServerID string
// Unstable implements Unstable backend methods not suitable
// for inclusion in Services.
Unstable local.UnstableService
// Services encapsulate services - provisioner, trust, etc. used by the auth
// server in a separate structure. Reads through Services hit the backend.
*Services
// Cache should either be the same as Services, or a caching layer over it.
// As it's an interface (and thus directly implementing all of its methods)
// its embedding takes priority over Services (which only indirectly
// implements its methods), thus any implemented GetFoo method on both Cache
// and Services will call the one from Cache. To bypass the cache, call the
// method on Services instead.
Cache
// privateKey is used in tests to use pre-generated private keys
privateKey []byte
// cipherSuites is a list of ciphersuites that the auth server supports.
cipherSuites []uint16
// limiter limits the number of active connections per client IP.
limiter *limiter.ConnectionsLimiter
// Emitter is events emitter, used to submit discrete events
emitter apievents.Emitter
// streamer is events sessionstreamer, used to create continuous
// session related streams
streamer events.Streamer
// keyStore manages all CA private keys, which may or may not be backed by
// HSMs
keyStore *keystore.Manager
// lockWatcher is a lock watcher, used to verify cert generation requests.
lockWatcher *services.LockWatcher
inventory *inventory.Controller
// githubOrgSSOCache is used to cache whether Github organizations use
// external SSO or not.
githubOrgSSOCache *utils.FnCache
// ttlCache is a generic ttl cache. typed keys must be used.
ttlCache *utils.FnCache
// traceClient is used to forward spans to the upstream collector for components
// within the cluster that don't have a direct connection to said collector
traceClient otlptrace.Client
// fips means FedRAMP/FIPS 140-2 compliant configuration was requested.
fips bool
// ghaIDTokenValidator allows ID tokens from GitHub Actions to be validated
// by the auth server. It can be overridden for the purpose of tests.
ghaIDTokenValidator ghaIDTokenValidator
// gitlabIDTokenValidator allows ID tokens from GitLab CI to be validated by
// the auth server. It can be overridden for the purpose of tests.
gitlabIDTokenValidator gitlabIDTokenValidator
// circleCITokenValidate allows ID tokens from CircleCI to be validated by
// the auth server. It can be overridden for the purpose of tests.
circleCITokenValidate func(ctx context.Context, organizationID, token string) (*circleci.IDTokenClaims, error)
// kubernetesTokenValidator allows tokens from Kubernetes to be validated
// by the auth server. It can be overridden for the purpose of tests.
kubernetesTokenValidator kubernetesTokenValidator
// loadAllCAs tells tsh to load the host CAs for all clusters when trying to ssh into a node.
loadAllCAs bool
// license is the Teleport Enterprise license used to start the auth server
license *liblicense.License
// headlessAuthenticationWatcher is a headless authentication watcher,
// used to catch and propagate headless authentication request changes.
headlessAuthenticationWatcher *local.HeadlessAuthenticationWatcher
loginHooksMu sync.RWMutex
// loginHooks are a list of hooks that will be called on login.
loginHooks []LoginHook
// httpClientForAWSSTS overwrites the default HTTP client used for making
// STS requests.
httpClientForAWSSTS utils.HTTPDoClient
}
// SetSAMLService registers svc as the SAMLService that provides the SAML
// connector implementation. If a SAMLService has already been registered, this
// will override the previous registration.
func (a *Server) SetSAMLService(svc SAMLService) {
a.samlAuthService = svc
}
// SetOIDCService registers svc as the OIDCService that provides the OIDC
// connector implementation. If a OIDCService has already been registered, this
// will override the previous registration.
func (a *Server) SetOIDCService(svc OIDCService) {
a.oidcAuthService = svc
}
// SetLicense sets the license
func (a *Server) SetLicense(license *liblicense.License) {
a.license = license
}
// SetReleaseService sets the release service
func (a *Server) SetReleaseService(svc release.Client) {
a.releaseService = svc
}
// SetUpgradeWindowStartHourGetter sets the getter used to sync the ClusterMaintenanceConfig resource
// with the cloud UpgradeWindowStartHour value.
func (a *Server) SetUpgradeWindowStartHourGetter(fn func(context.Context) (int64, error)) {
a.lock.Lock()
defer a.lock.Unlock()
a.upgradeWindowStartHourGetter = fn
}
func (a *Server) getUpgradeWindowStartHourGetter() func(context.Context) (int64, error) {
a.lock.Lock()
defer a.lock.Unlock()
return a.upgradeWindowStartHourGetter
}
// SetLoginRuleEvaluator sets the login rule evaluator.
func (a *Server) SetLoginRuleEvaluator(l loginrule.Evaluator) {
a.loginRuleEvaluator = l
}
// GetLoginRuleEvaluator returns the login rule evaluator. It is guaranteed not
// to return nil, if no evaluator has been installed it will return
// [loginrule.NullEvaluator].
func (a *Server) GetLoginRuleEvaluator() loginrule.Evaluator {
if a.loginRuleEvaluator == nil {
return loginrule.NullEvaluator{}
}
return a.loginRuleEvaluator
}
// RegisterLoginHook will register a login hook with the auth server.
func (a *Server) RegisterLoginHook(hook LoginHook) {
a.loginHooksMu.Lock()
defer a.loginHooksMu.Unlock()
a.loginHooks = append(a.loginHooks, hook)
}
// CallLoginHooks will call the registered login hooks.
func (a *Server) CallLoginHooks(ctx context.Context, user types.User) error {
// Make a copy of the login hooks to operate on.
a.loginHooksMu.RLock()
loginHooks := make([]LoginHook, len(a.loginHooks))
copy(loginHooks, a.loginHooks)
a.loginHooksMu.RUnlock()
if len(loginHooks) == 0 {
return nil
}
var errs []error
for _, hook := range loginHooks {
errs = append(errs, hook(ctx, user))
}
return trace.NewAggregate(errs...)
}
// ResetLoginHooks will clear out the login hooks.
func (a *Server) ResetLoginHooks() {
a.loginHooksMu.Lock()
a.loginHooks = nil
a.loginHooksMu.Unlock()
}
// CloseContext returns the close context
func (a *Server) CloseContext() context.Context {
return a.closeCtx
}
// SetLockWatcher sets the lock watcher.
func (a *Server) SetLockWatcher(lockWatcher *services.LockWatcher) {
a.lock.Lock()
defer a.lock.Unlock()
a.lockWatcher = lockWatcher
}
func (a *Server) checkLockInForce(mode constants.LockingMode, targets []types.LockTarget) error {
a.lock.RLock()
defer a.lock.RUnlock()
if a.lockWatcher == nil {
return trace.BadParameter("lockWatcher is not set")
}
return a.lockWatcher.CheckLockInForce(mode, targets...)
}
func (a *Server) SetHeadlessAuthenticationWatcher(headlessAuthenticationWatcher *local.HeadlessAuthenticationWatcher) {
a.lock.Lock()
defer a.lock.Unlock()
a.headlessAuthenticationWatcher = headlessAuthenticationWatcher
}
// syncUpgradeWindowStartHour attempts to load the cloud UpgradeWindowStartHour value and set
// the ClusterMaintenanceConfig resource's AgentUpgrade.UTCStartHour field to match it.
func (a *Server) syncUpgradeWindowStartHour(ctx context.Context) error {
getter := a.getUpgradeWindowStartHourGetter()
if getter == nil {
return trace.Errorf("getter has not been registered")
}
startHour, err := getter(ctx)
if err != nil {
return trace.Wrap(err)
}
cmc, err := a.GetClusterMaintenanceConfig(ctx)
if err != nil {
if !trace.IsNotFound(err) {
return trace.Wrap(err)
}
// create an empty maintenance config resource on NotFound
cmc = types.NewClusterMaintenanceConfig()
}
agentWindow, _ := cmc.GetAgentUpgradeWindow()
agentWindow.UTCStartHour = uint32(startHour)
cmc.SetAgentUpgradeWindow(agentWindow)
if err := a.UpdateClusterMaintenanceConfig(ctx, cmc); err != nil {
return trace.Wrap(err)
}
return nil
}
func (a *Server) periodicSyncUpgradeWindowStartHour() {
checkInterval := interval.New(interval.Config{
Duration: time.Minute * 3,
FirstDuration: utils.FullJitter(time.Second * 30),
Jitter: retryutils.NewSeventhJitter(),
})
defer checkInterval.Stop()
for {
select {
case <-checkInterval.Next():
if err := a.syncUpgradeWindowStartHour(a.closeCtx); err != nil {
if a.closeCtx.Err() == nil {
// we run this periodic at a fairly high frequency, so errors are just
// logged but otherwise ignored.
log.Warnf("Failed to sync upgrade window start hour: %v", err)
}
}
case <-a.closeCtx.Done():
return
}
}
}
// runPeriodicOperations runs some periodic bookkeeping operations
// performed by auth server
func (a *Server) runPeriodicOperations() {
ctx := context.TODO()
// run periodic functions with a semi-random period
// to avoid contention on the database in case if there are multiple
// auth servers running - so they don't compete trying
// to update the same resources.
r := insecurerand.New(insecurerand.NewSource(a.GetClock().Now().UnixNano()))
period := defaults.HighResPollingPeriod + time.Duration(r.Intn(int(defaults.HighResPollingPeriod/time.Second)))*time.Second
log.Debugf("Ticking with period: %v.", period)
a.lock.RLock()
ticker := a.clock.NewTicker(period)
a.lock.RUnlock()
// Create a ticker with jitter
heartbeatCheckTicker := interval.New(interval.Config{
Duration: apidefaults.ServerKeepAliveTTL() * 2,
Jitter: retryutils.NewSeventhJitter(),
})
promTicker := interval.New(interval.Config{
Duration: defaults.PrometheusScrapeInterval,
Jitter: retryutils.NewSeventhJitter(),
})
missedKeepAliveCount := 0
defer ticker.Stop()
defer heartbeatCheckTicker.Stop()
defer promTicker.Stop()
firstReleaseCheck := utils.FullJitter(time.Hour * 6)
// this environment variable is "unstable" since it will be deprecated
// by an upcoming tctl command. currently exists for testing purposes only.
if os.Getenv("TELEPORT_UNSTABLE_VC_SYNC_ON_START") == "yes" {
firstReleaseCheck = utils.HalfJitter(time.Second * 10)
}
// note the use of FullJitter for the releases check interval. this lets us ensure
// that frequent restarts don't prevent checks from happening despite the infrequent
// effective check rate.
releaseCheck := interval.New(interval.Config{
Duration: time.Hour * 24,
FirstDuration: firstReleaseCheck,
Jitter: retryutils.NewFullJitter(),
})
defer releaseCheck.Stop()
// more frequent release check that just re-calculates alerts based on previously
// pulled versioning info.
localReleaseCheck := interval.New(interval.Config{
Duration: time.Minute * 10,
FirstDuration: utils.HalfJitter(time.Second * 10),
Jitter: retryutils.NewHalfJitter(),
})
defer localReleaseCheck.Stop()
// isolate the schedule of potentially long-running refreshRemoteClusters() from other tasks
go func() {
// reasonably small interval to ensure that users observe clusters as online within 1 minute of adding them.
remoteClustersRefresh := interval.New(interval.Config{
Duration: time.Second * 40,
Jitter: retryutils.NewSeventhJitter(),
})
defer remoteClustersRefresh.Stop()
for {
select {
case <-a.closeCtx.Done():
return
case <-remoteClustersRefresh.Next():
a.refreshRemoteClusters(ctx, r)
}
}
}()
// cloud auth servers need to periodically sync the upgrade window
// from the cloud db.
if modules.GetModules().Features().Cloud {
go a.periodicSyncUpgradeWindowStartHour()
}
for {
select {
case <-a.closeCtx.Done():
return
case <-ticker.Chan():
err := a.autoRotateCertAuthorities(ctx)
if err != nil {
if trace.IsCompareFailed(err) {
log.Debugf("Cert authority has been updated concurrently: %v.", err)
} else {
log.Errorf("Failed to perform cert rotation check: %v.", err)
}
}
case <-heartbeatCheckTicker.Next():
nodes, err := a.GetNodes(ctx, apidefaults.Namespace)
if err != nil {
log.Errorf("Failed to load nodes for heartbeat metric calculation: %v", err)
}
for _, node := range nodes {
if services.NodeHasMissedKeepAlives(node) {
missedKeepAliveCount++
}
}
// Update prometheus gauge
heartbeatsMissedByAuth.Set(float64(missedKeepAliveCount))
case <-promTicker.Next():
a.updateVersionMetrics()
case <-releaseCheck.Next():
a.syncReleaseAlerts(ctx, true)
case <-localReleaseCheck.Next():
a.syncReleaseAlerts(ctx, false)
}
}
}
const (
releaseAlertID = "upgrade-suggestion"
secAlertID = "security-patch-available"
verInUseLabel = "teleport.internal/ver-in-use"
)
// syncReleaseAlerts calculates alerts related to new teleport releases. When checkRemote
// is true it pulls the latest release info from github. Otherwise, it loads the versions used
// for the most recent alerts and re-syncs with latest cluster state.
func (a *Server) syncReleaseAlerts(ctx context.Context, checkRemote bool) {
log.Debug("Checking for new teleport releases via github api.")
// NOTE: essentially everything in this function is going to be
// scrapped/replaced once the inventory and version-control systems
// are a bit further along.
current := vc.NewTarget(vc.Normalize(teleport.Version))
// this environment variable is "unstable" since it will be deprecated
// by an upcoming tctl command. currently exists for testing purposes only.
if t := vc.NewTarget(os.Getenv("TELEPORT_UNSTABLE_VC_VERSION")); t.Ok() {
current = t
}
visitor := vc.Visitor{
Current: current,
}
// users cannot upgrade their own auth instances in cloud, so it isn't helpful
// to generate alerts for releases newer than the current auth server version.
if modules.GetModules().Features().Cloud {
visitor.NotNewerThan = current
}
var loadFailed bool
if checkRemote {
// scrape the github releases API with our visitor
if err := github.Visit(&visitor); err != nil {
log.Warnf("Failed to load github releases: %v (this will not impact teleport functionality)", err)
loadFailed = true
}
} else {
if err := a.visitCachedAlertVersions(ctx, &visitor); err != nil {
log.Warnf("Failed to load release alert into: %v (this will not impact teleport functionality)", err)
loadFailed = true
}
}
a.doReleaseAlertSync(ctx, current, visitor, !loadFailed)
}
// visitCachedAlertVersions updates the visitor with targets reconstructed from the metadata
// of existing alerts. This lets us "reevaluate" the alerts based on newer cluster state without
// re-pulling the releases page. Future version of teleport will cache actual full release
// descriptions, rending this unnecessary.
func (a *Server) visitCachedAlertVersions(ctx context.Context, visitor *vc.Visitor) error {
// reconstruct the target for the "latest stable" alert if it exists.
alert, err := a.getClusterAlert(ctx, releaseAlertID)
if err != nil && !trace.IsNotFound(err) {
return trace.Wrap(err)
}
if err == nil {
if t := vc.NewTarget(alert.Metadata.Labels[verInUseLabel]); t.Ok() {
visitor.Visit(t)
}
}
// reconstruct the target for the "latest sec patch" alert if it exists.
alert, err = a.getClusterAlert(ctx, secAlertID)
if err != nil && !trace.IsNotFound(err) {
return trace.Wrap(err)
}
if err == nil {
if t := vc.NewTarget(alert.Metadata.Labels[verInUseLabel], vc.SecurityPatch(true)); t.Ok() {
visitor.Visit(t)
}
}
return nil
}
func (a *Server) getClusterAlert(ctx context.Context, id string) (types.ClusterAlert, error) {
alerts, err := a.GetClusterAlerts(ctx, types.GetClusterAlertsRequest{
AlertID: id,
})
if err != nil {
return types.ClusterAlert{}, trace.Wrap(err)
}
if len(alerts) == 0 {
return types.ClusterAlert{}, trace.NotFound("cluster alert %q not found", id)
}
return alerts[0], nil
}
func (a *Server) doReleaseAlertSync(ctx context.Context, current vc.Target, visitor vc.Visitor, cleanup bool) {
const alertTTL = time.Minute * 30
// use visitor to find the oldest version among connected instances.
// TODO(fspmarshall): replace this check as soon as we have a backend inventory repr. using
// connected instances is a poor approximation and may lead to missed notifications if auth
// server is up to date, but instances not connected to this auth need update.
var instanceVisitor vc.Visitor
a.inventory.Iter(func(handle inventory.UpstreamHandle) {
v := vc.Normalize(handle.Hello().Version)
instanceVisitor.Visit(vc.NewTarget(v))
})
// build the general alert msg meant for broader consumption
msg, verInUse := makeUpgradeSuggestionMsg(visitor, current, instanceVisitor.Oldest())