-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
Copy pathauth.go
7574 lines (6736 loc) · 253 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
/*
* 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 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"
"cmp"
"context"
"crypto"
"crypto/rand"
"crypto/subtle"
"crypto/x509"
"encoding/pem"
"errors"
"fmt"
"io"
"log/slog"
"math/big"
insecurerand "math/rand"
"net"
"os"
"regexp"
"slices"
"sort"
"strconv"
"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"
"go.opentelemetry.io/otel/exporters/otlp/otlptrace"
"golang.org/x/crypto/bcrypt"
"golang.org/x/crypto/ssh"
"golang.org/x/exp/maps"
"golang.org/x/time/rate"
"google.golang.org/protobuf/types/known/durationpb"
"google.golang.org/protobuf/types/known/timestamppb"
"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"
devicepb "github.com/gravitational/teleport/api/gen/proto/go/teleport/devicetrust/v1"
headerv1 "github.com/gravitational/teleport/api/gen/proto/go/teleport/header/v1"
mfav1 "github.com/gravitational/teleport/api/gen/proto/go/teleport/mfa/v1"
notificationsv1 "github.com/gravitational/teleport/api/gen/proto/go/teleport/notifications/v1"
"github.com/gravitational/teleport/api/internalutils/stream"
"github.com/gravitational/teleport/api/metadata"
"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/entitlements"
"github.com/gravitational/teleport/lib/auth/authclient"
"github.com/gravitational/teleport/lib/auth/keystore"
"github.com/gravitational/teleport/lib/auth/userloginstate"
wanlib "github.com/gravitational/teleport/lib/auth/webauthn"
wantypes "github.com/gravitational/teleport/lib/auth/webauthntypes"
"github.com/gravitational/teleport/lib/authz"
"github.com/gravitational/teleport/lib/backend"
"github.com/gravitational/teleport/lib/cache"
"github.com/gravitational/teleport/lib/circleci"
"github.com/gravitational/teleport/lib/cloud"
"github.com/gravitational/teleport/lib/cryptosuites"
"github.com/gravitational/teleport/lib/defaults"
"github.com/gravitational/teleport/lib/devicetrust/assertserver"
"github.com/gravitational/teleport/lib/events"
"github.com/gravitational/teleport/lib/gcp"
"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/resourceusage"
"github.com/gravitational/teleport/lib/service/servicecfg"
"github.com/gravitational/teleport/lib/services"
"github.com/gravitational/teleport/lib/services/local"
"github.com/gravitational/teleport/lib/services/readonly"
"github.com/gravitational/teleport/lib/spacelift"
"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/terraformcloud"
"github.com/gravitational/teleport/lib/tlsca"
"github.com/gravitational/teleport/lib/tpm"
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
)
const (
OSSDesktopsCheckPeriod = 5 * time.Minute
OSSDesktopsAlertID = "oss-desktops"
OSSDesktopsAlertMessage = "Your cluster is beyond its allocation of 5 non-Active Directory Windows desktops. " +
"Reach out for unlimited desktops with Teleport Enterprise."
OSSDesktopsAlertLink = "https://goteleport.com/r/upgrade-community?utm_campaign=CTA_windows_local"
OSSDesktopsAlertLinkText = "Contact Sales"
OSSDesktopsLimit = 5
)
const (
dynamicLabelCheckPeriod = time.Hour
dynamicLabelAlertID = "dynamic-labels-in-deny-rules"
dynamicLabelAlertMessage = "One or more roles has deny rules that include dynamic/ labels. " +
"This is not recommended due to the volatility of dynamic/ labels and is not allowed for new roles. " +
"(hint: use 'tctl get roles' to find roles that need updating)"
)
const (
notificationsPageReadInterval = 5 * time.Millisecond
notificationsWriteInterval = 40 * time.Millisecond
)
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.VersionStorage == nil {
return nil, trace.BadParameter("version storage is not set")
}
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, err = local.NewIdentityServiceV2(cfg.Backend)
if err != nil {
return nil, trace.Wrap(err)
}
}
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.AutoUpdateService == nil {
cfg.AutoUpdateService, err = local.NewAutoUpdateService(cfg.Backend)
if err != nil {
return nil, trace.Wrap(err)
}
}
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.NewDiscardStreamer()
}
if cfg.WindowsDesktops == nil {
cfg.WindowsDesktops = local.NewWindowsDesktopService(cfg.Backend)
}
if cfg.DynamicWindowsDesktops == nil {
cfg.DynamicWindowsDesktops, err = local.NewDynamicWindowsDesktopService(cfg.Backend)
if err != nil {
return nil, trace.Wrap(err)
}
}
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.CrownJewels == nil {
cfg.CrownJewels, err = local.NewCrownJewelsService(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.SecReports == nil {
cfg.SecReports, err = local.NewSecReportsService(cfg.Backend, cfg.Clock)
if err != nil {
return nil, trace.Wrap(err)
}
}
if cfg.AccessLists == nil {
cfg.AccessLists, err = local.NewAccessListService(cfg.Backend, cfg.Clock)
if err != nil {
return nil, trace.Wrap(err)
}
}
if cfg.DatabaseObjectImportRules == nil {
cfg.DatabaseObjectImportRules, err = local.NewDatabaseObjectImportRuleService(cfg.Backend)
if err != nil {
return nil, trace.Wrap(err)
}
}
if cfg.DatabaseObjects == nil {
cfg.DatabaseObjects, err = local.NewDatabaseObjectService(cfg.Backend)
if err != nil {
return nil, trace.Wrap(err)
}
}
if cfg.PluginData == nil {
cfg.PluginData = local.NewPluginData(cfg.Backend, cfg.DynamicAccessExt)
}
if cfg.Integrations == nil {
cfg.Integrations, err = local.NewIntegrationsService(cfg.Backend)
if err != nil {
return nil, trace.Wrap(err)
}
}
if cfg.UserTasks == nil {
cfg.UserTasks, err = local.NewUserTasksService(cfg.Backend)
if err != nil {
return nil, trace.Wrap(err)
}
}
if cfg.DiscoveryConfigs == nil {
cfg.DiscoveryConfigs, err = local.NewDiscoveryConfigService(cfg.Backend)
if err != nil {
return nil, trace.Wrap(err)
}
}
if cfg.UserPreferences == nil {
cfg.UserPreferences = local.NewUserPreferencesService(cfg.Backend)
}
if cfg.UserLoginState == nil {
cfg.UserLoginState, err = local.NewUserLoginStateService(cfg.Backend)
if err != nil {
return nil, trace.Wrap(err)
}
}
if cfg.ProvisioningStates == nil {
cfg.ProvisioningStates, err = local.NewProvisioningStateService(cfg.Backend)
if err != nil {
return nil, trace.Wrap(err)
}
}
if cfg.IdentityCenter == nil {
svcCfg := local.IdentityCenterServiceConfig{Backend: cfg.Backend}
cfg.IdentityCenter, err = local.NewIdentityCenterService(svcCfg)
if err != nil {
return nil, trace.Wrap(err)
}
}
if cfg.CloudClients == nil {
cfg.CloudClients, err = cloud.NewClients()
if err != nil {
return nil, trace.Wrap(err)
}
}
if cfg.Notifications == nil {
cfg.Notifications, err = local.NewNotificationsService(cfg.Backend, cfg.Clock)
if err != nil {
return nil, trace.Wrap(err)
}
}
if cfg.BotInstance == nil {
cfg.BotInstance, err = local.NewBotInstanceService(cfg.Backend, cfg.Clock)
if err != nil {
return nil, trace.Wrap(err)
}
}
if cfg.SPIFFEFederations == nil {
cfg.SPIFFEFederations, err = local.NewSPIFFEFederationService(cfg.Backend)
if err != nil {
return nil, trace.Wrap(err, "creating SPIFFEFederation service")
}
}
if cfg.Logger == nil {
cfg.Logger = slog.With(teleport.ComponentKey, teleport.ComponentAuth)
}
limiter := limiter.NewConnectionsLimiter(defaults.LimiterMaxConcurrentSignatures)
keystoreOpts := &keystore.Options{
HostUUID: cfg.HostUUID,
ClusterName: cfg.ClusterName,
AuthPreferenceGetter: cfg.ClusterConfiguration,
FIPS: cfg.FIPS,
}
if cfg.KeyStoreConfig.PKCS11 != (servicecfg.PKCS11Config{}) {
if !modules.GetModules().Features().GetEntitlement(entitlements.HSM).Enabled {
return nil, fmt.Errorf("PKCS11 HSM support requires a license with the HSM feature enabled: %w", ErrRequiresEnterprise)
}
} else if cfg.KeyStoreConfig.GCPKMS != (servicecfg.GCPKMSConfig{}) {
if !modules.GetModules().Features().GetEntitlement(entitlements.HSM).Enabled {
return nil, fmt.Errorf("Google Cloud KMS support requires a license with the HSM feature enabled: %w", ErrRequiresEnterprise)
}
} else if cfg.KeyStoreConfig.AWSKMS != nil {
if !modules.GetModules().Features().GetEntitlement(entitlements.HSM).Enabled {
return nil, fmt.Errorf("AWS KMS support requires a license with the HSM feature enabled: %w", ErrRequiresEnterprise)
}
}
keyStore, err := keystore.NewManager(context.Background(), &cfg.KeyStoreConfig, keystoreOpts)
if err != nil {
return nil, trace.Wrap(err)
}
if cfg.KubeWaitingContainers == nil {
cfg.KubeWaitingContainers, err = local.NewKubeWaitingContainerService(cfg.Backend)
if err != nil {
return nil, trace.Wrap(err)
}
}
if cfg.AccessMonitoringRules == nil {
cfg.AccessMonitoringRules, err = local.NewAccessMonitoringRulesService(cfg.Backend)
if err != nil {
return nil, trace.Wrap(err)
}
}
if cfg.StaticHostUsers == nil {
cfg.StaticHostUsers, err = local.NewStaticHostUserService(cfg.Backend)
if err != nil {
return nil, trace.Wrap(err)
}
}
closeCtx, cancelFunc := context.WithCancel(context.TODO())
services := &Services{
TrustInternal: cfg.Trust,
PresenceInternal: cfg.Presence,
Provisioner: cfg.Provisioner,
Identity: cfg.Identity,
Access: cfg.Access,
DynamicAccessExt: cfg.DynamicAccessExt,
ClusterConfiguration: cfg.ClusterConfiguration,
AutoUpdateService: cfg.AutoUpdateService,
Restrictions: cfg.Restrictions,
Apps: cfg.Apps,
Kubernetes: cfg.Kubernetes,
Databases: cfg.Databases,
DatabaseServices: cfg.DatabaseServices,
AuditLogSessionStreamer: cfg.AuditLog,
Events: cfg.Events,
WindowsDesktops: cfg.WindowsDesktops,
DynamicWindowsDesktops: cfg.DynamicWindowsDesktops,
SAMLIdPServiceProviders: cfg.SAMLIdPServiceProviders,
UserGroups: cfg.UserGroups,
SessionTrackerService: cfg.SessionTrackerService,
ConnectionsDiagnostic: cfg.ConnectionsDiagnostic,
Integrations: cfg.Integrations,
UserTasks: cfg.UserTasks,
DiscoveryConfigs: cfg.DiscoveryConfigs,
Okta: cfg.Okta,
AccessLists: cfg.AccessLists,
DatabaseObjectImportRules: cfg.DatabaseObjectImportRules,
DatabaseObjects: cfg.DatabaseObjects,
SecReports: cfg.SecReports,
UserLoginStates: cfg.UserLoginState,
StatusInternal: cfg.Status,
UsageReporter: cfg.UsageReporter,
UserPreferences: cfg.UserPreferences,
PluginData: cfg.PluginData,
KubeWaitingContainer: cfg.KubeWaitingContainers,
Notifications: cfg.Notifications,
AccessMonitoringRules: cfg.AccessMonitoringRules,
CrownJewels: cfg.CrownJewels,
BotInstance: cfg.BotInstance,
SPIFFEFederations: cfg.SPIFFEFederations,
StaticHostUser: cfg.StaticHostUsers,
ProvisioningStates: cfg.ProvisioningStates,
IdentityCenter: cfg.IdentityCenter,
}
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,
accessMonitoringEnabled: cfg.AccessMonitoringEnabled,
logger: cfg.Logger,
}
as.inventory = inventory.NewController(&as, services,
inventory.WithAuthServerID(cfg.HostUUID),
inventory.WithOnConnect(func(s string) {
if g, ok := connectedResourceGauges[s]; ok {
g.Inc()
} else {
log.Warnf("missing connected resources gauge for keep alive %s (this is a bug)", s)
}
}),
inventory.WithOnDisconnect(func(s string, c int) {
if g, ok := connectedResourceGauges[s]; ok {
g.Sub(float64(c))
} else {
log.Warnf("missing connected resources gauge for keep alive %s (this is a bug)", s)
}
}),
)
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)
}
_, cacheEnabled := as.getCache()
// cluster config ttl cache *must* be set up after `opts` has been applied to the server because
// the Cache field starts off as a pointer to the local backend services and is only switched
// over to being a proper cache during option processing.
as.ReadOnlyCache, err = readonly.NewCache(readonly.CacheConfig{
Upstream: as.Cache,
Disabled: !cacheEnabled,
ReloadOnErr: true,
})
if err != nil {
return nil, trace.Wrap(err)
}
if as.ghaIDTokenValidator == nil {
as.ghaIDTokenValidator = githubactions.NewIDTokenValidator(
githubactions.IDTokenValidatorConfig{
Clock: as.clock,
},
)
}
if as.spaceliftIDTokenValidator == nil {
as.spaceliftIDTokenValidator = spacelift.NewIDTokenValidator(
spacelift.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.tpmValidator == nil {
as.tpmValidator = tpm.Validate
}
if as.k8sTokenReviewValidator == nil {
as.k8sTokenReviewValidator = &kubernetestoken.TokenReviewValidator{}
}
if as.k8sJWKSValidator == nil {
as.k8sJWKSValidator = kubernetestoken.ValidateTokenWithJWKS
}
if as.gcpIDTokenValidator == nil {
as.gcpIDTokenValidator = gcp.NewIDTokenValidator(
gcp.IDTokenValidatorConfig{
Clock: as.clock,
},
)
}
if as.terraformIDTokenValidator == nil {
as.terraformIDTokenValidator = terraformcloud.NewIDTokenValidator(terraformcloud.IDTokenValidatorConfig{
Clock: as.clock,
})
}
// Add in a login hook for generating state during user login.
as.ulsGenerator, err = userloginstate.NewGenerator(userloginstate.GeneratorConfig{
Log: log,
AccessLists: &as,
Access: &as,
UsageEvents: &as,
Clock: cfg.Clock,
})
if err != nil {
return nil, trace.Wrap(err)
}
as.RegisterLoginHook(as.ulsGenerator.LoginHook(services.UserLoginStates))
if _, ok := as.getCache(); !ok {
log.Warn("Auth server starting without cache (may have negative performance implications).")
}
return &as, nil
}
// Services is a collection of services that are used by the auth server.
// Avoid using this type as a dependency and instead depend on the actual
// methods/services you need. It should really only be necessary to directly
// reference this type on auth.Server itself and on code that manages
// the lifecycle of the auth server.
type Services struct {
services.TrustInternal
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.DynamicWindowsDesktops
services.SAMLIdPServiceProviders
services.UserGroups
services.SessionTrackerService
services.ConnectionsDiagnostic
services.StatusInternal
services.Integrations
services.IntegrationsTokenGenerator
services.UserTasks
services.DiscoveryConfigs
services.Okta
services.AccessLists
services.DatabaseObjectImportRules
services.DatabaseObjects
services.UserLoginStates
services.UserPreferences
services.PluginData
services.SCIM
services.Notifications
usagereporter.UsageReporter
types.Events
events.AuditLogSessionStreamer
services.SecReports
services.KubeWaitingContainer
services.AccessMonitoringRules
services.CrownJewels
services.BotInstance
services.AccessGraphSecretsGetter
services.DevicesGetter
services.SPIFFEFederations
services.StaticHostUser
services.AutoUpdateService
services.ProvisioningStates
services.IdentityCenter
}
// 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)
}
// GenerateAWSOIDCToken generates a token to be used to execute an AWS OIDC Integration action.
func (r *Services) GenerateAWSOIDCToken(ctx context.Context, integration string) (string, error) {
return r.IntegrationsTokenGenerator.GenerateAWSOIDCToken(ctx, integration)
}
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",
},
)
roleCount = prometheus.NewGauge(
prometheus.GaugeOpts{
Namespace: teleport.MetricNamespace,
Name: "roles_total",
Help: "Number of roles that exist in the cluster",
},
)
registeredAgents = prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Namespace: teleport.MetricNamespace,
Name: teleport.MetricRegisteredServers,
Help: "The number of Teleport services that are connected to an auth server.",
},
[]string{
teleport.TagVersion,
teleport.TagAutomaticUpdates,
},
)
registeredAgentsInstallMethod = prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Namespace: teleport.MetricNamespace,
Name: teleport.MetricRegisteredServersByInstallMethods,
Help: "The number of Teleport services that are connected to an auth server by install method.",
},
[]string{teleport.TagInstallMethods},
)
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},
)
totalInstancesMetric = prometheus.NewGauge(
prometheus.GaugeOpts{
Namespace: teleport.MetricNamespace,
Name: teleport.MetricTotalInstances,
Help: "Total teleport instances",
},
)
enrolledInUpgradesMetric = prometheus.NewGauge(
prometheus.GaugeOpts{
Namespace: teleport.MetricNamespace,
Name: teleport.MetricEnrolledInUpgrades,
Help: "Number of instances enrolled in automatic upgrades",
},
)
upgraderCountsMetric = prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Namespace: teleport.MetricNamespace,
Name: teleport.MetricUpgraderCounts,
Help: "Tracks the number of instances advertising each upgrader",
},
[]string{
teleport.TagUpgrader,
teleport.TagVersion,
},
)
accessRequestsCreatedMetric = prometheus.NewCounterVec(
prometheus.CounterOpts{
Namespace: teleport.MetricNamespace,
Name: teleport.MetricAccessRequestsCreated,
Help: "Tracks the number of created access requests",
},
[]string{teleport.TagRoles, teleport.TagResources},
)
userCertificatesGeneratedMetric = prometheus.NewCounterVec(
prometheus.CounterOpts{
Namespace: teleport.MetricNamespace,
Name: teleport.MetricUserCertificatesGenerated,
Help: "Tracks the number of user certificates generated",
},
[]string{teleport.TagPrivateKeyPolicy},
)
prometheusCollectors = []prometheus.Collector{
generateRequestsCount, generateThrottledRequestsCount,
generateRequestsCurrent, generateRequestsLatencies, UserLoginCount, heartbeatsMissedByAuth,
registeredAgents, migrations,
totalInstancesMetric, enrolledInUpgradesMetric, upgraderCountsMetric,
accessRequestsCreatedMetric,
registeredAgentsInstallMethod,
userCertificatesGeneratedMetric,
roleCount,
}
)
// 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
// CreateDeviceWebTokenFunc creates a new DeviceWebToken for the logged in user.
//
// Used during a successful Web login, after the user was verified and the
// WebSession created.
//
// May return `nil, nil` if device trust isn't supported (OSS), disabled, or if
// the user has no suitable trusted device.
type CreateDeviceWebTokenFunc func(context.Context, *devicepb.DeviceWebToken) (*devicepb.DeviceWebToken, error)
// CreateDeviceAssertionFunc creates a new device assertion ceremony to authenticate
// a trusted device.
type CreateDeviceAssertionFunc func() (assertserver.Ceremony, error)
// ReadOnlyCache is a type alias used to assist with embedding [readonly.Cache] in places
// where it would have a naming conflict with other types named Cache.
type ReadOnlyCache = readonly.Cache
// 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.
authclient.Cache
// ReadOnlyCache is a specialized cache that provides read-only shared references
// in certain performance-critical paths where deserialization/cloning may be too
// expensive at scale.
*ReadOnlyCache
// 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 an events session streamer, used to create continuous
// session related streams
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
// UnifiedResourceCache is a cache of multiple resource kinds to be presented
// in a unified manner in the web UI.
UnifiedResourceCache *services.UnifiedResourceCache
// AccessRequestCache is a cache of access requests that specifically provides
// custom sorting options not available via the standard backend.
AccessRequestCache *services.AccessRequestCache
// UserNotificationCache is a cache of user-specific notifications.
UserNotificationCache *services.UserNotificationCache
// GlobalNotificationCache is a cache of global notifications.
GlobalNotificationCache *services.GlobalNotificationCache
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
// spaceliftIDTokenValidator allows ID tokens from Spacelift to be validated
// by the auth server. It can be overridden for the purpose of tests.
spaceliftIDTokenValidator spaceliftIDTokenValidator
// 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
// tpmValidator allows TPMs to be validated by the auth server. It can be
// overridden for the purpose of tests.