-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
auth.go
3755 lines (3396 loc) · 120 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"
"encoding/base64"
"errors"
"fmt"
"math"
"math/big"
insecurerand "math/rand"
"net"
"net/url"
"strings"
"sync"
"time"
"github.com/coreos/go-oidc/oauth2"
"github.com/coreos/go-oidc/oidc"
"github.com/gravitational/trace"
"github.com/jonboulle/clockwork"
"github.com/pborman/uuid"
"github.com/prometheus/client_golang/prometheus"
saml2 "github.com/russellhaering/gosaml2"
"github.com/sirupsen/logrus"
"golang.org/x/crypto/ssh"
"github.com/gravitational/teleport"
"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/lib/auth/keystore"
"github.com/gravitational/teleport/lib/auth/u2f"
wanlib "github.com/gravitational/teleport/lib/auth/webauthn"
"github.com/gravitational/teleport/lib/backend"
"github.com/gravitational/teleport/lib/defaults"
"github.com/gravitational/teleport/lib/events"
kubeutils "github.com/gravitational/teleport/lib/kube/utils"
"github.com/gravitational/teleport/lib/limiter"
"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"
"github.com/gravitational/teleport/lib/utils"
"github.com/gravitational/teleport/lib/utils/interval"
)
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"
)
// ServerOption allows setting options as functional arguments to Server
type ServerOption func(*Server)
// NewServer creates and configures a new Server instance
func NewServer(cfg *InitConfig, opts ...ServerOption) (*Server, error) {
err := utils.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.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.KeyStoreConfig.RSAKeyPairSource == nil {
cfg.KeyStoreConfig.RSAKeyPairSource = cfg.Authority.GenerateKeyPair
}
if cfg.KeyStoreConfig.HostUUID == "" {
cfg.KeyStoreConfig.HostUUID = cfg.HostUUID
}
limiter, err := limiter.NewConnectionsLimiter(limiter.Config{
MaxConnections: defaults.LimiterMaxConcurrentSignatures,
})
if err != nil {
return nil, trace.Wrap(err)
}
keyStore, err := keystore.NewKeyStore(cfg.KeyStoreConfig)
if err != nil {
return nil, trace.Wrap(err)
}
closeCtx, cancelFunc := context.WithCancel(context.TODO())
as := Server{
bk: cfg.Backend,
limiter: limiter,
Authority: cfg.Authority,
AuthServiceName: cfg.AuthServiceName,
oidcClients: make(map[string]*oidcClient),
samlProviders: make(map[string]*samlProvider),
githubClients: make(map[string]*githubClient),
caSigningAlg: cfg.CASigningAlg,
cancelFunc: cancelFunc,
closeCtx: closeCtx,
emitter: cfg.Emitter,
streamer: cfg.Streamer,
Services: Services{
Trust: cfg.Trust,
Presence: cfg.Presence,
Provisioner: cfg.Provisioner,
Identity: cfg.Identity,
Access: cfg.Access,
DynamicAccessExt: cfg.DynamicAccessExt,
ClusterConfiguration: cfg.ClusterConfiguration,
Restrictions: cfg.Restrictions,
Apps: cfg.Apps,
Databases: cfg.Databases,
IAuditLog: cfg.AuditLog,
Events: cfg.Events,
WindowsDesktops: cfg.WindowsDesktops,
},
keyStore: keyStore,
}
for _, o := range opts {
o(&as)
}
if as.clock == nil {
as.clock = clockwork.NewRealClock()
}
return &as, nil
}
type Services struct {
services.Trust
services.Presence
services.Provisioner
services.Identity
services.Access
services.DynamicAccessExt
services.ClusterConfiguration
services.Restrictions
services.Apps
services.Databases
services.WindowsDesktops
types.Events
events.IAuditLog
}
// 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)
}
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 hearbeats missed by auth server",
},
)
prometheusCollectors = []prometheus.Collector{
generateRequestsCount, generateThrottledRequestsCount,
generateRequestsCurrent, generateRequestsLatencies, UserLoginCount, heartbeatsMissedByAuth,
}
)
// 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
oidcClients map[string]*oidcClient
samlProviders map[string]*samlProvider
githubClients map[string]*githubClient
clock clockwork.Clock
bk backend.Backend
closeCtx context.Context
cancelFunc context.CancelFunc
sshca.Authority
// 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
// Services encapsulate services - provisioner, trust, etc
// used by the auth server in a separate structure
Services
// 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
// caSigningAlg is an SSH signing algorithm to use when generating new CAs.
caSigningAlg *string
// cache is a fast cache that allows auth server
// to use cache for most frequent operations,
// if not set, cache uses itself
cache Cache
// 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 is an interface for interacting with private keys in CAs which
// may be backed by HSMs
keyStore keystore.KeyStore
// lockWatcher is a lock watcher, used to verify cert generation requests.
lockWatcher *services.LockWatcher
}
// SetCache sets cache used by auth server
func (a *Server) SetCache(clt Cache) {
a.lock.Lock()
defer a.lock.Unlock()
a.cache = clt
}
// GetCache returns cache used by auth server
func (a *Server) GetCache() Cache {
a.lock.RLock()
defer a.lock.RUnlock()
if a.cache == nil {
return &a.Services
}
return a.cache
}
// 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...)
}
// 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: utils.NewSeventhJitter(),
})
missedKeepAliveCount := 0
defer ticker.Stop()
defer heartbeatCheckTicker.Stop()
for {
select {
case <-a.closeCtx.Done():
return
case <-ticker.Chan():
err := a.autoRotateCertAuthorities()
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))
}
}
}
func (a *Server) Close() error {
a.cancelFunc()
if a.bk != nil {
return trace.Wrap(a.bk.Close())
}
return nil
}
func (a *Server) GetClock() clockwork.Clock {
a.lock.RLock()
defer a.lock.RUnlock()
return a.clock
}
// SetClock sets clock, used in tests
func (a *Server) SetClock(clock clockwork.Clock) {
a.lock.Lock()
defer a.lock.Unlock()
a.clock = clock
}
// SetAuditLog sets the server's audit log
func (a *Server) SetAuditLog(auditLog events.IAuditLog) {
a.IAuditLog = auditLog
}
// GetAuthPreference gets AuthPreference from the cache.
func (a *Server) GetAuthPreference(ctx context.Context) (types.AuthPreference, error) {
return a.GetCache().GetAuthPreference(ctx)
}
// GetClusterAuditConfig gets ClusterAuditConfig from the cache.
func (a *Server) GetClusterAuditConfig(ctx context.Context, opts ...services.MarshalOption) (types.ClusterAuditConfig, error) {
return a.GetCache().GetClusterAuditConfig(ctx, opts...)
}
// GetClusterNetworkingConfig gets ClusterNetworkingConfig from the cache.
func (a *Server) GetClusterNetworkingConfig(ctx context.Context, opts ...services.MarshalOption) (types.ClusterNetworkingConfig, error) {
return a.GetCache().GetClusterNetworkingConfig(ctx, opts...)
}
// GetSessionRecordingConfig gets SessionRecordingConfig from the cache.
func (a *Server) GetSessionRecordingConfig(ctx context.Context, opts ...services.MarshalOption) (types.SessionRecordingConfig, error) {
return a.GetCache().GetSessionRecordingConfig(ctx, opts...)
}
// GetClusterName returns the domain name that identifies this authority server.
// Also known as "cluster name"
func (a *Server) GetClusterName(opts ...services.MarshalOption) (types.ClusterName, error) {
return a.GetCache().GetClusterName(opts...)
}
// GetDomainName returns the domain name that identifies this authority server.
// Also known as "cluster name"
func (a *Server) GetDomainName() (string, error) {
clusterName, err := a.GetClusterName()
if err != nil {
return "", trace.Wrap(err)
}
return clusterName.GetClusterName(), nil
}
// LocalCAResponse contains the concatenated PEM-encoded TLS certs for the local
// cluster's Host CA
type LocalCAResponse struct {
// TLSCA is a PEM-encoded TLS certificate authority.
TLSCA []byte `json:"tls_ca"`
}
// GetClusterCACert returns the PEM-encoded TLS certs for the local cluster. If
// the cluster has multiple TLS certs, they will all be concatenated.
func (a *Server) GetClusterCACert() (*LocalCAResponse, error) {
clusterName, err := a.GetClusterName()
if err != nil {
return nil, trace.Wrap(err)
}
// Extract the TLS CA for this cluster.
hostCA, err := a.GetCache().GetCertAuthority(types.CertAuthID{
Type: types.HostCA,
DomainName: clusterName.GetClusterName(),
}, false)
if err != nil {
return nil, trace.Wrap(err)
}
certs := services.GetTLSCerts(hostCA)
if len(certs) < 1 {
return nil, trace.NotFound("no tls certs found in host CA")
}
allCerts := bytes.Join(certs, []byte("\n"))
return &LocalCAResponse{
TLSCA: allCerts,
}, nil
}
// GenerateHostCert uses the private key of the CA to sign the public key of the host
// (along with meta data like host ID, node name, roles, and ttl) to generate a host certificate.
func (a *Server) GenerateHostCert(hostPublicKey []byte, hostID, nodeName string, principals []string, clusterName string, role types.SystemRole, ttl time.Duration) ([]byte, error) {
domainName, err := a.GetDomainName()
if err != nil {
return nil, trace.Wrap(err)
}
// get the certificate authority that will be signing the public key of the host
ca, err := a.Trust.GetCertAuthority(types.CertAuthID{
Type: types.HostCA,
DomainName: domainName,
}, true)
if err != nil {
return nil, trace.BadParameter("failed to load host CA for %q: %v", domainName, err)
}
caSigner, err := a.keyStore.GetSSHSigner(ca)
if err != nil {
return nil, trace.Wrap(err)
}
// create and sign!
return a.generateHostCert(services.HostCertParams{
CASigner: caSigner,
CASigningAlg: sshutils.GetSigningAlgName(ca),
PublicHostKey: hostPublicKey,
HostID: hostID,
NodeName: nodeName,
Principals: principals,
ClusterName: clusterName,
Role: role,
TTL: ttl,
})
}
func (a *Server) generateHostCert(p services.HostCertParams) ([]byte, error) {
authPref, err := a.GetAuthPreference(context.TODO())
if err != nil {
return nil, trace.Wrap(err)
}
if p.Role == types.RoleNode {
if lockErr := a.checkLockInForce(authPref.GetLockingMode(),
[]types.LockTarget{{Node: p.HostID}, {Node: HostFQDN(p.HostID, p.ClusterName)}},
); lockErr != nil {
return nil, trace.Wrap(lockErr)
}
}
return a.Authority.GenerateHostCert(p)
}
// GetKeyStore returns the KeyStore used by the auth server
func (a *Server) GetKeyStore() keystore.KeyStore {
return a.keyStore
}
type certRequest struct {
// user is a user to generate certificate for
user types.User
// impersonator is a user who generates the certificate,
// is set when different from the user in the certificate
impersonator string
// checker is used to perform RBAC checks.
checker services.AccessChecker
// ttl is Duration of the certificate
ttl time.Duration
// publicKey is RSA public key in authorized_keys format
publicKey []byte
// compatibility is compatibility mode
compatibility string
// overrideRoleTTL is used for requests when the requested TTL should not be
// adjusted based off the role of the user. This is used by tctl to allow
// creating long lived user certs.
overrideRoleTTL bool
// usage is a list of acceptable usages to be encoded in X509 certificate,
// is used to limit ways the certificate can be used, for example
// the cert can be only used against kubernetes endpoint, and not auth endpoint,
// no usage means unrestricted (to keep backwards compatibility)
usage []string
// routeToCluster is an optional teleport cluster name to route the
// certificate requests to, this teleport cluster name will be used to
// route the requests to in case of kubernetes
routeToCluster string
// kubernetesCluster specifies the target kubernetes cluster for TLS
// identities. This can be empty on older Teleport clients.
kubernetesCluster string
// traits hold claim data used to populate a role at runtime.
traits wrappers.Traits
// activeRequests tracks privilege escalation requests applied
// during the construction of the certificate.
activeRequests services.RequestIDs
// appSessionID is the session ID of the application session.
appSessionID string
// appPublicAddr is the public address of the application.
appPublicAddr string
// appClusterName is the name of the cluster this application is in.
appClusterName string
// appName is the name of the application to generate cert for.
appName string
// awsRoleARN is the role ARN to generate certificate for.
awsRoleARN string
// dbService identifies the name of the database service requests will
// be routed to.
dbService string
// dbProtocol specifies the protocol of the database a certificate will
// be issued for.
dbProtocol string
// dbUser is the optional database user which, if provided, will be used
// as a default username.
dbUser string
// dbName is the optional database name which, if provided, will be used
// as a default database.
dbName string
// mfaVerified is the UUID of an MFA device when this certRequest was
// created immediately after an MFA check.
mfaVerified string
// clientIP is an IP of the client requesting the certificate.
clientIP string
}
// check verifies the cert request is valid.
func (r *certRequest) check() error {
if r.user == nil {
return trace.BadParameter("missing parameter user")
}
if r.checker == nil {
return trace.BadParameter("missing parameter checker")
}
// When generating certificate for MongoDB access, database username must
// be encoded into it. This is required to be able to tell which database
// user to authenticate the connection as.
if r.dbProtocol == defaults.ProtocolMongoDB {
if r.dbUser == "" {
return trace.BadParameter("must provide database user name to generate certificate for database %q", r.dbService)
}
}
return nil
}
type certRequestOption func(*certRequest)
func certRequestMFAVerified(mfaID string) certRequestOption {
return func(r *certRequest) { r.mfaVerified = mfaID }
}
func certRequestClientIP(ip string) certRequestOption {
return func(r *certRequest) { r.clientIP = ip }
}
// GenerateUserTestCerts is used to generate user certificate, used internally for tests
func (a *Server) GenerateUserTestCerts(key []byte, username string, ttl time.Duration, compatibility, routeToCluster string) ([]byte, []byte, error) {
user, err := a.Identity.GetUser(username, false)
if err != nil {
return nil, nil, trace.Wrap(err)
}
checker, err := services.FetchRoles(user.GetRoles(), a.Access, user.GetTraits())
if err != nil {
return nil, nil, trace.Wrap(err)
}
certs, err := a.generateUserCert(certRequest{
user: user,
ttl: ttl,
compatibility: compatibility,
publicKey: key,
routeToCluster: routeToCluster,
checker: checker,
traits: user.GetTraits(),
})
if err != nil {
return nil, nil, trace.Wrap(err)
}
return certs.SSH, certs.TLS, nil
}
// AppTestCertRequest combines parameters for generating a test app access cert.
type AppTestCertRequest struct {
// PublicKey is the public key to sign.
PublicKey []byte
// Username is the Teleport user name to sign certificate for.
Username string
// TTL is the test certificate validity period.
TTL time.Duration
// PublicAddr is the application public address. Used for routing.
PublicAddr string
// ClusterName is the name of the cluster application resides in. Used for routing.
ClusterName string
// SessionID is the optional session ID to encode. Used for routing.
SessionID string
// AWSRoleARN is optional AWS role ARN a user wants to assume to encode.
AWSRoleARN string
}
// GenerateUserAppTestCert generates an application specific certificate, used
// internally for tests.
func (a *Server) GenerateUserAppTestCert(req AppTestCertRequest) ([]byte, error) {
user, err := a.Identity.GetUser(req.Username, false)
if err != nil {
return nil, trace.Wrap(err)
}
checker, err := services.FetchRoles(user.GetRoles(), a.Access, user.GetTraits())
if err != nil {
return nil, trace.Wrap(err)
}
sessionID := req.SessionID
if sessionID == "" {
sessionID = uuid.New()
}
certs, err := a.generateUserCert(certRequest{
user: user,
publicKey: req.PublicKey,
checker: checker,
ttl: req.TTL,
// Set the login to be a random string. Application certificates are never
// used to log into servers but SSH certificate generation code requires a
// principal be in the certificate.
traits: wrappers.Traits(map[string][]string{
teleport.TraitLogins: {uuid.New()},
}),
// Only allow this certificate to be used for applications.
usage: []string{teleport.UsageAppsOnly},
// Add in the application routing information.
appSessionID: sessionID,
appPublicAddr: req.PublicAddr,
appClusterName: req.ClusterName,
awsRoleARN: req.AWSRoleARN,
})
if err != nil {
return nil, trace.Wrap(err)
}
return certs.TLS, nil
}
// DatabaseTestCertRequest combines parameters for generating test database
// access certificate.
type DatabaseTestCertRequest struct {
// PublicKey is the public key to sign.
PublicKey []byte
// Cluster is the Teleport cluster name.
Cluster string
// Username is the Teleport username.
Username string
// RouteToDatabase contains database routing information.
RouteToDatabase tlsca.RouteToDatabase
}
// GenerateDatabaseTestCert generates a database access certificate for the
// provided parameters. Used only internally in tests.
func (a *Server) GenerateDatabaseTestCert(req DatabaseTestCertRequest) ([]byte, error) {
user, err := a.Identity.GetUser(req.Username, false)
if err != nil {
return nil, trace.Wrap(err)
}
checker, err := services.FetchRoles(user.GetRoles(), a.Access, user.GetTraits())
if err != nil {
return nil, trace.Wrap(err)
}
certs, err := a.generateUserCert(certRequest{
user: user,
publicKey: req.PublicKey,
checker: checker,
ttl: time.Hour,
traits: wrappers.Traits(map[string][]string{
teleport.TraitLogins: {req.Username},
}),
routeToCluster: req.Cluster,
dbService: req.RouteToDatabase.ServiceName,
dbProtocol: req.RouteToDatabase.Protocol,
dbUser: req.RouteToDatabase.Username,
dbName: req.RouteToDatabase.Database,
})
if err != nil {
return nil, trace.Wrap(err)
}
return certs.TLS, nil
}
// generateUserCert generates user certificates
func (a *Server) generateUserCert(req certRequest) (*proto.Certs, error) {
err := req.check()
if err != nil {
return nil, trace.Wrap(err)
}
// Reject the cert request if there is a matching lock in force.
authPref, err := a.GetAuthPreference(context.TODO())
if err != nil {
return nil, trace.Wrap(err)
}
if lockErr := a.checkLockInForce(req.checker.LockingMode(authPref.GetLockingMode()), append(
services.RolesToLockTargets(req.checker.RoleNames()),
types.LockTarget{User: req.user.GetName()},
types.LockTarget{MFADevice: req.mfaVerified},
)); lockErr != nil {
return nil, trace.Wrap(lockErr)
}
// reuse the same RSA keys for SSH and TLS keys
cryptoPubKey, err := sshutils.CryptoPublicKey(req.publicKey)
if err != nil {
return nil, trace.Wrap(err)
}
// extract the passed in certificate format. if nothing was passed in, fetch
// the certificate format from the role.
certificateFormat, err := utils.CheckCertificateFormatFlag(req.compatibility)
if err != nil {
return nil, trace.Wrap(err)
}
if certificateFormat == teleport.CertificateFormatUnspecified {
certificateFormat = req.checker.CertificateFormat()
}
var sessionTTL time.Duration
var allowedLogins []string
// If the role TTL is ignored, do not restrict session TTL and allowed logins.
// The only caller setting this parameter should be "tctl auth sign".
// Otherwise set the session TTL to the smallest of all roles and
// then only grant access to allowed logins based on that.
if req.overrideRoleTTL {
// Take whatever was passed in. Pass in 0 to CheckLoginDuration so all
// logins are returned for the role set.
sessionTTL = req.ttl
allowedLogins, err = req.checker.CheckLoginDuration(0)
if err != nil {
return nil, trace.Wrap(err)
}
} else {
// Adjust session TTL to the smaller of two values: the session TTL
// requested in tsh or the session TTL for the role.
sessionTTL = req.checker.AdjustSessionTTL(req.ttl)
// Return a list of logins that meet the session TTL limit. This means if
// the requested session TTL is larger than the max session TTL for a login,
// that login will not be included in the list of allowed logins.
allowedLogins, err = req.checker.CheckLoginDuration(sessionTTL)
if err != nil {
return nil, trace.Wrap(err)
}
}
clusterName, err := a.GetDomainName()
if err != nil {
return nil, trace.Wrap(err)
}
if req.routeToCluster == "" {
req.routeToCluster = clusterName
}
if req.routeToCluster != clusterName {
// Authorize access to a remote cluster.
rc, err := a.Presence.GetRemoteCluster(req.routeToCluster)
if err != nil {
return nil, trace.Wrap(err)
}
if err := req.checker.CheckAccessToRemoteCluster(rc); err != nil {
if trace.IsAccessDenied(err) {
return nil, trace.NotFound("remote cluster %q not found", req.routeToCluster)
}
return nil, trace.Wrap(err)
}
}
ca, err := a.Trust.GetCertAuthority(types.CertAuthID{
Type: types.UserCA,
DomainName: clusterName,
}, true)
if err != nil {
return nil, trace.Wrap(err)
}
caSigner, err := a.keyStore.GetSSHSigner(ca)
if err != nil {
return nil, trace.Wrap(err)
}
params := services.UserCertParams{
CASigner: caSigner,
CASigningAlg: sshutils.GetSigningAlgName(ca),
PublicUserKey: req.publicKey,
Username: req.user.GetName(),
Impersonator: req.impersonator,
AllowedLogins: allowedLogins,
TTL: sessionTTL,
Roles: req.checker.RoleNames(),
CertificateFormat: certificateFormat,
PermitPortForwarding: req.checker.CanPortForward(),
PermitAgentForwarding: req.checker.CanForwardAgents(),
PermitX11Forwarding: req.checker.PermitX11Forwarding(),
RouteToCluster: req.routeToCluster,
Traits: req.traits,
ActiveRequests: req.activeRequests,
MFAVerified: req.mfaVerified,
ClientIP: req.clientIP,
}
sshCert, err := a.Authority.GenerateUserCert(params)
if err != nil {
return nil, trace.Wrap(err)
}
kubeGroups, kubeUsers, err := req.checker.CheckKubeGroupsAndUsers(sessionTTL, req.overrideRoleTTL)
// NotFound errors are acceptable - this user may have no k8s access
// granted and that shouldn't prevent us from issuing a TLS cert.
if err != nil && !trace.IsNotFound(err) {
return nil, trace.Wrap(err)
}
// Only validate/default kubernetes cluster name for the current teleport
// cluster. If this cert is targeting a trusted teleport cluster, leave all
// the kubernetes cluster validation up to them.
if req.routeToCluster == clusterName {
req.kubernetesCluster, err = kubeutils.CheckOrSetKubeCluster(a.closeCtx, a.Presence, req.kubernetesCluster, clusterName)
if err != nil {
if !trace.IsNotFound(err) {
return nil, trace.Wrap(err)
}
log.Debug("Failed setting default kubernetes cluster for user login (user did not provide a cluster); leaving KubernetesCluster extension in the TLS certificate empty")
}
}
// See which database names and users this user is allowed to use.
dbNames, dbUsers, err := req.checker.CheckDatabaseNamesAndUsers(sessionTTL, req.overrideRoleTTL)
if err != nil && !trace.IsNotFound(err) {
return nil, trace.Wrap(err)
}
// See which AWS role ARNs this user is allowed to assume.
roleARNs, err := req.checker.CheckAWSRoleARNs(sessionTTL, req.overrideRoleTTL)
if err != nil && !trace.IsNotFound(err) {
return nil, trace.Wrap(err)
}
// generate TLS certificate
cert, signer, err := a.keyStore.GetTLSCertAndSigner(ca)
if err != nil {
return nil, trace.Wrap(err)
}
tlsAuthority, err := tlsca.FromCertAndSigner(cert, signer)
if err != nil {
return nil, trace.Wrap(err)
}
identity := tlsca.Identity{
Username: req.user.GetName(),
Impersonator: req.impersonator,
Groups: req.checker.RoleNames(),
Principals: allowedLogins,
Usage: req.usage,
RouteToCluster: req.routeToCluster,
KubernetesCluster: req.kubernetesCluster,
Traits: req.traits,
KubernetesGroups: kubeGroups,
KubernetesUsers: kubeUsers,
RouteToApp: tlsca.RouteToApp{
SessionID: req.appSessionID,
PublicAddr: req.appPublicAddr,
ClusterName: req.appClusterName,
Name: req.appName,
AWSRoleARN: req.awsRoleARN,
},
TeleportCluster: clusterName,
RouteToDatabase: tlsca.RouteToDatabase{
ServiceName: req.dbService,
Protocol: req.dbProtocol,
Username: req.dbUser,
Database: req.dbName,
},
DatabaseNames: dbNames,
DatabaseUsers: dbUsers,
MFAVerified: req.mfaVerified,
ClientIP: req.clientIP,
AWSRoleARNs: roleARNs,
ActiveRequests: req.activeRequests.AccessRequests,
}
subject, err := identity.Subject()
if err != nil {
return nil, trace.Wrap(err)
}
certRequest := tlsca.CertificateRequest{