-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
auth_with_roles.go
7035 lines (6140 loc) · 266 KB
/
auth_with_roles.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright 2015-2021 Gravitational, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package auth
import (
"context"
"fmt"
"net/url"
"strings"
"time"
"github.com/coreos/go-semver/semver"
"github.com/google/uuid"
"github.com/gravitational/roundtrip"
"github.com/gravitational/trace"
"github.com/sirupsen/logrus"
collectortracev1 "go.opentelemetry.io/proto/otlp/collector/trace/v1"
otlpcommonv1 "go.opentelemetry.io/proto/otlp/common/v1"
"golang.org/x/exp/slices"
"github.com/gravitational/teleport"
"github.com/gravitational/teleport/api"
"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/gen/proto/go/assist/v1"
integrationpb "github.com/gravitational/teleport/api/gen/proto/go/teleport/integration/v1"
trustpb "github.com/gravitational/teleport/api/gen/proto/go/teleport/trust/v1"
userpreferencespb "github.com/gravitational/teleport/api/gen/proto/go/userpreferences/v1"
"github.com/gravitational/teleport/api/internalutils/stream"
"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/lib/auth/integration/integrationv1"
"github.com/gravitational/teleport/lib/auth/trust/trustv1"
"github.com/gravitational/teleport/lib/authz"
"github.com/gravitational/teleport/lib/backend"
"github.com/gravitational/teleport/lib/defaults"
dtauthz "github.com/gravitational/teleport/lib/devicetrust/authz"
dtconfig "github.com/gravitational/teleport/lib/devicetrust/config"
"github.com/gravitational/teleport/lib/events"
"github.com/gravitational/teleport/lib/internal/context121"
"github.com/gravitational/teleport/lib/modules"
"github.com/gravitational/teleport/lib/services"
"github.com/gravitational/teleport/lib/services/local"
"github.com/gravitational/teleport/lib/session"
"github.com/gravitational/teleport/lib/tlsca"
"github.com/gravitational/teleport/lib/utils"
)
// ServerWithRoles is a wrapper around auth service
// methods that focuses on authorizing every request
type ServerWithRoles struct {
authServer *Server
alog events.AuditLogSessionStreamer
// context holds authorization context
context authz.Context
}
// CloseContext is closed when the auth server shuts down
func (a *ServerWithRoles) CloseContext() context.Context {
return a.authServer.closeCtx
}
func (a *ServerWithRoles) actionWithContext(ctx *services.Context, namespace, resource string, verbs ...string) error {
if len(verbs) == 0 {
return trace.BadParameter("no verbs provided for authorization check on resource %q", resource)
}
var errs []error
for _, verb := range verbs {
errs = append(errs, a.context.Checker.CheckAccessToRule(ctx, namespace, resource, verb, false))
}
if err := trace.NewAggregate(errs...); err != nil {
return err
}
return nil
}
type actionConfig struct {
quiet bool
context authz.Context
}
type actionOption func(*actionConfig)
func quietAction(quiet bool) actionOption {
return func(cfg *actionConfig) {
cfg.quiet = quiet
}
}
func (a *ServerWithRoles) withOptions(opts ...actionOption) actionConfig {
cfg := actionConfig{context: a.context}
for _, opt := range opts {
opt(&cfg)
}
return cfg
}
func (c actionConfig) action(namespace, resource string, verbs ...string) error {
if len(verbs) == 0 {
return trace.BadParameter("no verbs provided for authorization check on resource %q", resource)
}
var errs []error
for _, verb := range verbs {
errs = append(errs, c.context.Checker.CheckAccessToRule(&services.Context{User: c.context.User}, namespace, resource, verb, c.quiet))
}
if err := trace.NewAggregate(errs...); err != nil {
return err
}
return nil
}
func (a *ServerWithRoles) action(namespace, resource string, verbs ...string) error {
return a.withOptions().action(namespace, resource, verbs...)
}
// currentUserAction is a special checker that allows certain actions for users
// even if they are not admins, e.g. update their own passwords,
// or generate certificates, otherwise it will require admin privileges
func (a *ServerWithRoles) currentUserAction(username string) error {
if hasLocalUserRole(a.context) && username == a.context.User.GetName() {
return nil
}
return a.context.Checker.CheckAccessToRule(&services.Context{User: a.context.User},
apidefaults.Namespace, types.KindUser, types.VerbCreate, true)
}
// authConnectorAction is a special checker that grants access to auth
// connectors. It first checks if you have access to the specific connector.
// If not, it checks if the requester has the meta KindAuthConnector access
// (which grants access to all connectors).
func (a *ServerWithRoles) authConnectorAction(namespace string, resource string, verb string) error {
if err := a.context.Checker.CheckAccessToRule(&services.Context{User: a.context.User}, namespace, resource, verb, true); err != nil {
if err := a.context.Checker.CheckAccessToRule(&services.Context{User: a.context.User}, namespace, types.KindAuthConnector, verb, false); err != nil {
return trace.Wrap(err)
}
}
return nil
}
// actionForListWithCondition extracts a restrictive filter condition to be
// added to a list query after a simple resource check fails.
func (a *ServerWithRoles) actionForListWithCondition(namespace, resource, identifier string) (*types.WhereExpr, error) {
origErr := a.withOptions(quietAction(true)).action(namespace, resource, types.VerbList)
if origErr == nil || !trace.IsAccessDenied(origErr) {
return nil, trace.Wrap(origErr)
}
cond, err := a.context.Checker.ExtractConditionForIdentifier(&services.Context{User: a.context.User}, namespace, resource, types.VerbList, identifier)
if trace.IsAccessDenied(err) {
log.WithError(err).Infof("Access to %v %v in namespace %v denied to %v.", types.VerbList, resource, namespace, a.context.Checker)
// Return the original AccessDenied to avoid leaking information.
return nil, trace.Wrap(origErr)
}
return cond, trace.Wrap(err)
}
// actionWithExtendedContext performs an additional RBAC check with extended
// rule context after a simple resource check fails.
func (a *ServerWithRoles) actionWithExtendedContext(namespace, kind, verb string, extendContext func(*services.Context) error) error {
ruleCtx := &services.Context{User: a.context.User}
origErr := a.context.Checker.CheckAccessToRule(ruleCtx, namespace, kind, verb, true)
if origErr == nil || !trace.IsAccessDenied(origErr) {
return trace.Wrap(origErr)
}
if err := extendContext(ruleCtx); err != nil {
log.WithError(err).Warning("Failed to extend context for second RBAC check.")
// Return the original AccessDenied to avoid leaking information.
return trace.Wrap(origErr)
}
return trace.Wrap(a.context.Checker.CheckAccessToRule(ruleCtx, namespace, kind, verb, false))
}
// actionForKindSession is a special checker that grants access to session
// recordings. It can allow access to a specific recording based on the
// `where` section of the user's access rule for kind `session`.
func (a *ServerWithRoles) actionForKindSession(namespace string, sid session.ID) error {
extendContext := func(ctx *services.Context) error {
sessionEnd, err := a.findSessionEndEvent(namespace, sid)
ctx.Session = sessionEnd
return trace.Wrap(err)
}
return trace.Wrap(a.actionWithExtendedContext(namespace, types.KindSession, types.VerbRead, extendContext))
}
// localServerAction returns an access denied error if the role is not one of the builtin server roles.
func (a *ServerWithRoles) localServerAction() error {
role, ok := a.context.Identity.(authz.BuiltinRole)
if !ok || !role.IsServer() {
return trace.AccessDenied("this request can be only executed by a teleport built-in server")
}
return nil
}
// remoteServerAction returns an access denied error if the role is not one of the remote builtin server roles.
func (a *ServerWithRoles) remoteServerAction() error {
role, ok := a.context.UnmappedIdentity.(authz.RemoteBuiltinRole)
if !ok || !role.IsRemoteServer() {
return trace.AccessDenied("this request can be only executed by a teleport remote server")
}
return nil
}
// isLocalOrRemoteServerAction returns true if the role is one of the builtin server roles (local or remote).
func (a *ServerWithRoles) isLocalOrRemoteServerAction() bool {
errLocal := a.localServerAction()
errRemote := a.remoteServerAction()
return errLocal == nil || errRemote == nil
}
// hasBuiltinRole checks that the attached identity is a builtin role and
// whether any of the given roles match the role set.
func (a *ServerWithRoles) hasBuiltinRole(roles ...types.SystemRole) bool {
for _, role := range roles {
if authz.HasBuiltinRole(a.context, string(role)) {
return true
}
}
return false
}
// HasBuiltinRole checks if the identity is a builtin role with the matching
// name.
// Deprecated: use authz.HasBuiltinRole instead.
func HasBuiltinRole(authContext authz.Context, name string) bool {
// TODO(jakule): This function can be removed once teleport.e is updated
// to use authz.HasBuiltinRole.
return authz.HasBuiltinRole(authContext, name)
}
// HasRemoteBuiltinRole checks if the identity is a remote builtin role with the
// matching name.
func HasRemoteBuiltinRole(authContext authz.Context, name string) bool {
if _, ok := authContext.UnmappedIdentity.(authz.RemoteBuiltinRole); !ok {
return false
}
if !authContext.Checker.HasRole(name) {
return false
}
return true
}
// hasRemoteBuiltinRole checks if the identity is a remote builtin role and the
// name matches.
func (a *ServerWithRoles) hasRemoteBuiltinRole(name string) bool {
return HasRemoteBuiltinRole(a.context, name)
}
// hasRemoteUserRole checks if the identity is a remote user or not.
func hasRemoteUserRole(authContext authz.Context) bool {
_, ok := authContext.UnmappedIdentity.(authz.RemoteUser)
return ok
}
// hasLocalUserRole checks if the identity is a local user or not.
func hasLocalUserRole(authContext authz.Context) bool {
_, ok := authContext.UnmappedIdentity.(authz.LocalUser)
return ok
}
// integrationsService returns an Integrations Service.
func (a *ServerWithRoles) integrationsService() (*integrationv1.Service, error) {
igSvc, err := integrationv1.NewService(&integrationv1.ServiceConfig{
Authorizer: authz.AuthorizerFunc(func(context.Context) (*authz.Context, error) {
return &a.context, nil
}),
Cache: a.authServer.Cache,
Backend: a.authServer.Services,
})
if err != nil {
return nil, trace.Wrap(err)
}
return igSvc, nil
}
// CreateIntegration creates an Integration.
func (a *ServerWithRoles) CreateIntegration(ctx context.Context, ig types.Integration) (types.Integration, error) {
igSvc, err := a.integrationsService()
if err != nil {
return nil, trace.Wrap(err)
}
igv1, ok := ig.(*types.IntegrationV1)
if !ok {
return nil, trace.BadParameter("unexpected integration type %T", ig)
}
ig, err = igSvc.CreateIntegration(ctx, &integrationpb.CreateIntegrationRequest{Integration: igv1})
if err != nil {
return nil, trace.Wrap(err)
}
return ig, nil
}
// GetIntegration returns an Integration by its name.
func (a *ServerWithRoles) GetIntegration(ctx context.Context, name string) (types.Integration, error) {
igSvc, err := a.integrationsService()
if err != nil {
return nil, trace.Wrap(err)
}
ig, err := igSvc.GetIntegration(ctx, &integrationpb.GetIntegrationRequest{Name: name})
if err != nil {
return nil, trace.Wrap(err)
}
return ig, nil
}
// ListIntegrations returns a list of Integrations.
// A next page can be retreived by calling ListIntegrations again and passing the nextKey from the previous response.
func (a *ServerWithRoles) ListIntegrations(ctx context.Context, pageSize int, nextKey string) ([]types.Integration, string, error) {
igSvc, err := a.integrationsService()
if err != nil {
return nil, "", trace.Wrap(err)
}
resp, err := igSvc.ListIntegrations(ctx, &integrationpb.ListIntegrationsRequest{
Limit: int32(pageSize),
NextKey: nextKey,
})
if err != nil {
return nil, "", trace.Wrap(err)
}
integrations := make([]types.Integration, 0, len(resp.GetIntegrations()))
for _, ig := range resp.GetIntegrations() {
integrations = append(integrations, ig)
}
return integrations, resp.GetNextKey(), nil
}
// UpdateIntegration updates an Integration.
func (a *ServerWithRoles) UpdateIntegration(ctx context.Context, ig types.Integration) (types.Integration, error) {
igSvc, err := a.integrationsService()
if err != nil {
return nil, trace.Wrap(err)
}
igv1, ok := ig.(*types.IntegrationV1)
if !ok {
return nil, trace.BadParameter("unexpected integration type %T", ig)
}
ig, err = igSvc.UpdateIntegration(ctx, &integrationpb.UpdateIntegrationRequest{Integration: igv1})
if err != nil {
return nil, trace.Wrap(err)
}
return ig, nil
}
// DeleteAllIntegrations deletes all integrations.
func (a *ServerWithRoles) DeleteAllIntegrations(ctx context.Context) error {
igSvc, err := a.integrationsService()
if err != nil {
return trace.Wrap(err)
}
_, err = igSvc.DeleteAllIntegrations(ctx, &integrationpb.DeleteAllIntegrationsRequest{})
return trace.Wrap(err)
}
// DeleteIntegration deletes an integration integrations.
func (a *ServerWithRoles) DeleteIntegration(ctx context.Context, name string) error {
igSvc, err := a.integrationsService()
if err != nil {
return trace.Wrap(err)
}
_, err = igSvc.DeleteIntegration(ctx, &integrationpb.DeleteIntegrationRequest{Name: name})
return trace.Wrap(err)
}
// GenerateAWSOIDCToken generates a token to be used when executing an AWS OIDC Integration action.
func (a *ServerWithRoles) GenerateAWSOIDCToken(ctx context.Context, req types.GenerateAWSOIDCTokenRequest) (string, error) {
igSvc, err := a.integrationsService()
if err != nil {
return "", trace.Wrap(err)
}
if err := req.CheckAndSetDefaults(); err != nil {
return "", trace.Wrap(err)
}
resp, err := igSvc.GenerateAWSOIDCToken(ctx, &integrationpb.GenerateAWSOIDCTokenRequest{
Issuer: req.Issuer,
})
if err != nil {
return "", trace.Wrap(err)
}
return resp.Token, nil
}
// CreateSessionTracker creates a tracker resource for an active session.
func (a *ServerWithRoles) CreateSessionTracker(ctx context.Context, tracker types.SessionTracker) (types.SessionTracker, error) {
if err := a.localServerAction(); err != nil {
return nil, trace.Wrap(err)
}
tracker, err := a.authServer.CreateSessionTracker(ctx, tracker)
if err != nil {
return nil, trace.Wrap(err)
}
return tracker, nil
}
func (a *ServerWithRoles) filterSessionTracker(ctx context.Context, joinerRoles []types.Role, tracker types.SessionTracker, verb string) bool {
// Apply RFD 45 RBAC rules to the session if it's SSH.
// This is a bit of a hack. It converts to the old legacy format
// which we don't have all data for, luckily the fields we don't have aren't made available
// to the RBAC filter anyway.
if tracker.GetKind() == types.KindSSHSession {
ruleCtx := &services.Context{User: a.context.User}
ruleCtx.SSHSession = &session.Session{
Kind: tracker.GetSessionKind(),
ID: session.ID(tracker.GetSessionID()),
Namespace: apidefaults.Namespace,
Login: tracker.GetLogin(),
Created: tracker.GetCreated(),
LastActive: a.authServer.GetClock().Now(),
ServerID: tracker.GetAddress(),
ServerAddr: tracker.GetAddress(),
ServerHostname: tracker.GetHostname(),
ClusterName: tracker.GetClusterName(),
}
for _, participant := range tracker.GetParticipants() {
// We only need to fill in User here since other fields get discarded anyway.
ruleCtx.SSHSession.Parties = append(ruleCtx.SSHSession.Parties, session.Party{
User: participant.User,
})
}
// Skip past it if there's a deny rule in place blocking access.
if err := a.context.Checker.CheckAccessToRule(ruleCtx, apidefaults.Namespace, types.KindSSHSession, verb, true /* silent */); err != nil {
return false
}
}
ruleCtx := &services.Context{User: a.context.User, SessionTracker: tracker}
if a.context.Checker.CheckAccessToRule(ruleCtx, apidefaults.Namespace, types.KindSessionTracker, types.VerbList, true /* silent */) == nil {
return true
}
evaluator := NewSessionAccessEvaluator(tracker.GetHostPolicySets(), tracker.GetSessionKind(), tracker.GetHostUser())
modes := evaluator.CanJoin(SessionAccessContext{Username: a.context.User.GetName(), Roles: joinerRoles})
return len(modes) != 0
}
const (
forwardedTag = "teleport.forwarded.for"
)
// Export forwards OTLP traces to the upstream collector configured in the tracing service. This allows for
// tsh, tctl, etc to be able to export traces without having to know how to connect to the upstream collector
// for the cluster.
//
// All spans received will have a `teleport.forwarded.for` attribute added to them with the value being one of
// two things depending on the role of the forwarder:
// 1. User forwarded: `teleport.forwarded.for: alice`
// 2. Instance forwarded: `teleport.forwarded.for: Proxy.clustername:Proxy,Node,Instance`
//
// This allows upstream consumers of the spans to be able to identify forwarded spans and act on them accordingly.
func (a *ServerWithRoles) Export(ctx context.Context, req *collectortracev1.ExportTraceServiceRequest) (*collectortracev1.ExportTraceServiceResponse, error) {
var sb strings.Builder
sb.WriteString(a.context.User.GetName())
// if forwarded on behalf of a Teleport service add its system roles
if role, ok := a.context.Identity.(authz.BuiltinRole); ok {
sb.WriteRune(':')
sb.WriteString(role.Role.String())
if len(role.AdditionalSystemRoles) > 0 {
sb.WriteRune(',')
sb.WriteString(role.AdditionalSystemRoles.String())
}
}
// the forwarded attribute to add
value := &otlpcommonv1.KeyValue{
Key: forwardedTag,
Value: &otlpcommonv1.AnyValue{
Value: &otlpcommonv1.AnyValue_StringValue{
StringValue: sb.String(),
},
},
}
// returns the index at which the attribute with
// the forwardedTag key exists, -1 if not found
tagIndex := func(attrs []*otlpcommonv1.KeyValue) int {
for i, attr := range attrs {
if attr.Key == forwardedTag {
return i
}
}
return -1
}
for _, resourceSpans := range req.ResourceSpans {
// if there is a resource, tag it with the
// forwarded attribute instead of each of tagging
// each span
if resourceSpans.Resource != nil {
if index := tagIndex(resourceSpans.Resource.Attributes); index != -1 {
resourceSpans.Resource.Attributes[index] = value
} else {
resourceSpans.Resource.Attributes = append(resourceSpans.Resource.Attributes, value)
}
// override any span attributes with a forwarded tag,
// but we don't need to add one if the span isn't already
// tagged since we just tagged the resource
for _, scopeSpans := range resourceSpans.ScopeSpans {
for _, span := range scopeSpans.Spans {
if index := tagIndex(span.Attributes); index != -1 {
span.Attributes[index] = value
}
}
}
continue
}
// there was no resource, so we must now tag all the
// individual spans with the forwarded tag
for _, scopeSpans := range resourceSpans.ScopeSpans {
for _, span := range scopeSpans.Spans {
if index := tagIndex(span.Attributes); index != -1 {
span.Attributes[index] = value
} else {
span.Attributes = append(span.Attributes, value)
}
}
}
}
if err := a.authServer.traceClient.UploadTraces(ctx, req.ResourceSpans); err != nil {
return &collectortracev1.ExportTraceServiceResponse{}, trace.Wrap(err)
}
return &collectortracev1.ExportTraceServiceResponse{}, nil
}
// GetSessionTracker returns the current state of a session tracker for an active session.
func (a *ServerWithRoles) GetSessionTracker(ctx context.Context, sessionID string) (types.SessionTracker, error) {
tracker, err := a.authServer.GetSessionTracker(ctx, sessionID)
if err != nil {
return nil, trace.Wrap(err)
}
if err := a.localServerAction(); err == nil {
return tracker, nil
}
user := a.context.User
joinerRoles, err := services.FetchRoles(user.GetRoles(), a.authServer, user.GetTraits())
if err != nil {
return nil, trace.Wrap(err)
}
ok := a.filterSessionTracker(ctx, joinerRoles, tracker, types.VerbRead)
if !ok {
return nil, trace.NotFound("session %v not found", sessionID)
}
return tracker, nil
}
// GetActiveSessionTrackers returns a list of active session trackers.
func (a *ServerWithRoles) GetActiveSessionTrackers(ctx context.Context) ([]types.SessionTracker, error) {
sessions, err := a.authServer.GetActiveSessionTrackers(ctx)
if err != nil {
return nil, trace.Wrap(err)
}
if err := a.localServerAction(); err == nil {
return sessions, nil
}
var filteredSessions []types.SessionTracker
user := a.context.User
joinerRoles, err := services.FetchRoles(user.GetRoles(), a.authServer, user.GetTraits())
if err != nil {
return nil, trace.Wrap(err)
}
for _, sess := range sessions {
ok := a.filterSessionTracker(ctx, joinerRoles, sess, types.VerbList)
if ok {
filteredSessions = append(filteredSessions, sess)
}
}
return filteredSessions, nil
}
// GetActiveSessionTrackersWithFilter returns a list of active sessions filtered by a filter.
func (a *ServerWithRoles) GetActiveSessionTrackersWithFilter(ctx context.Context, filter *types.SessionTrackerFilter) ([]types.SessionTracker, error) {
sessions, err := a.authServer.GetActiveSessionTrackersWithFilter(ctx, filter)
if err != nil {
return nil, trace.Wrap(err)
}
if err := a.localServerAction(); err == nil {
return sessions, nil
}
var filteredSessions []types.SessionTracker
user := a.context.User
joinerRoles, err := services.FetchRoles(user.GetRoles(), a.authServer, user.GetTraits())
if err != nil {
return nil, trace.Wrap(err)
}
for _, sess := range sessions {
ok := a.filterSessionTracker(ctx, joinerRoles, sess, types.VerbList)
if ok {
filteredSessions = append(filteredSessions, sess)
}
}
return filteredSessions, nil
}
// RemoveSessionTracker removes a tracker resource for an active session.
func (a *ServerWithRoles) RemoveSessionTracker(ctx context.Context, sessionID string) error {
if err := a.localServerAction(); err != nil {
return trace.Wrap(err)
}
return a.authServer.RemoveSessionTracker(ctx, sessionID)
}
// UpdateSessionTracker updates a tracker resource for an active session.
func (a *ServerWithRoles) UpdateSessionTracker(ctx context.Context, req *proto.UpdateSessionTrackerRequest) error {
if err := a.localServerAction(); err != nil {
return trace.Wrap(err)
}
return a.authServer.UpdateSessionTracker(ctx, req)
}
// AuthenticateWebUser authenticates web user, creates and returns a web session
// in case authentication is successful
func (a *ServerWithRoles) AuthenticateWebUser(ctx context.Context, req AuthenticateUserRequest) (types.WebSession, error) {
// authentication request has it's own authentication, however this limits the requests
// types to proxies to make it harder to break
if !a.hasBuiltinRole(types.RoleProxy) {
return nil, trace.AccessDenied("this request can be only executed by a proxy")
}
return a.authServer.AuthenticateWebUser(ctx, req)
}
// AuthenticateSSHUser authenticates SSH console user, creates and returns a pair of signed TLS and SSH
// short lived certificates as a result
func (a *ServerWithRoles) AuthenticateSSHUser(ctx context.Context, req AuthenticateSSHRequest) (*SSHLoginResponse, error) {
// authentication request has it's own authentication, however this limits the requests
// types to proxies to make it harder to break
if !a.hasBuiltinRole(types.RoleProxy) {
return nil, trace.AccessDenied("this request can be only executed by a proxy")
}
return a.authServer.AuthenticateSSHUser(ctx, req)
}
// GenerateOpenSSHCert signs a SSH certificate that can be used
// to connect to Agentless nodes.
func (a *ServerWithRoles) GenerateOpenSSHCert(ctx context.Context, req *proto.OpenSSHCertRequest) (*proto.OpenSSHCert, error) {
// this limits the requests types to proxies to make it harder to break
if !a.hasBuiltinRole(types.RoleProxy) && !a.hasRemoteBuiltinRole(string(types.RoleRemoteProxy)) {
return nil, trace.AccessDenied("this request can be only executed by a proxy")
}
return a.authServer.GenerateOpenSSHCert(ctx, req)
}
// CreateCertAuthority not implemented: can only be called locally.
func (a *ServerWithRoles) CreateCertAuthority(ctx context.Context, ca types.CertAuthority) error {
return trace.NotImplemented(notImplementedMessage)
}
// RotateCertAuthority starts or restarts certificate authority rotation process.
func (a *ServerWithRoles) RotateCertAuthority(ctx context.Context, req RotateRequest) error {
if err := req.CheckAndSetDefaults(a.authServer.clock); err != nil {
return trace.Wrap(err)
}
if err := a.action(apidefaults.Namespace, types.KindCertAuthority, types.VerbCreate, types.VerbUpdate); err != nil {
return trace.Wrap(err)
}
return a.authServer.RotateCertAuthority(ctx, req)
}
// RotateExternalCertAuthority rotates external certificate authority,
// this method is called by a remote trusted cluster and is used to update
// only public keys and certificates of the certificate authority.
func (a *ServerWithRoles) RotateExternalCertAuthority(ctx context.Context, ca types.CertAuthority) error {
if ca == nil {
return trace.BadParameter("missing certificate authority")
}
sctx := &services.Context{User: a.context.User, Resource: ca}
if err := a.actionWithContext(sctx, apidefaults.Namespace, types.KindCertAuthority, types.VerbRotate); err != nil {
return trace.Wrap(err)
}
return a.authServer.RotateExternalCertAuthority(ctx, ca)
}
// UpsertCertAuthority updates existing cert authority or updates the existing one.
func (a *ServerWithRoles) UpsertCertAuthority(ctx context.Context, ca types.CertAuthority) error {
trust, err := trustv1.NewService(&trustv1.ServiceConfig{
Authorizer: authz.AuthorizerFunc(func(context.Context) (*authz.Context, error) {
return &a.context, nil
}),
Cache: a.authServer.Cache,
Backend: a.authServer.Services,
})
if err != nil {
return trace.Wrap(err)
}
cav2, ok := ca.(*types.CertAuthorityV2)
if !ok {
return trace.BadParameter("unexpected ca type %T", ca)
}
_, err = trust.UpsertCertAuthority(ctx, &trustpb.UpsertCertAuthorityRequest{CertAuthority: cav2})
return trace.Wrap(err)
}
// CompareAndSwapCertAuthority updates existing cert authority if the existing cert authority
// value matches the value stored in the backend.
func (a *ServerWithRoles) CompareAndSwapCertAuthority(new, existing types.CertAuthority) error {
if err := a.action(apidefaults.Namespace, types.KindCertAuthority, types.VerbCreate, types.VerbUpdate); err != nil {
return trace.Wrap(err)
}
return a.authServer.CompareAndSwapCertAuthority(new, existing)
}
func (a *ServerWithRoles) GetCertAuthorities(ctx context.Context, caType types.CertAuthType, loadKeys bool) ([]types.CertAuthority, error) {
trust, err := trustv1.NewService(&trustv1.ServiceConfig{
Authorizer: authz.AuthorizerFunc(func(context.Context) (*authz.Context, error) {
return &a.context, nil
}),
Cache: a.authServer.Cache,
Backend: a.authServer.Services,
})
if err != nil {
return nil, trace.Wrap(err)
}
resp, err := trust.GetCertAuthorities(ctx, &trustpb.GetCertAuthoritiesRequest{Type: string(caType), IncludeKey: loadKeys})
if err != nil {
return nil, trace.Wrap(err)
}
cas := make([]types.CertAuthority, 0, len(resp.CertAuthoritiesV2))
for _, ca := range resp.CertAuthoritiesV2 {
cas = append(cas, ca)
}
return cas, trace.Wrap(err)
}
func (a *ServerWithRoles) GetCertAuthority(ctx context.Context, id types.CertAuthID, loadKeys bool) (types.CertAuthority, error) {
trust, err := trustv1.NewService(&trustv1.ServiceConfig{
Authorizer: authz.AuthorizerFunc(func(context.Context) (*authz.Context, error) {
return &a.context, nil
}),
Cache: a.authServer.Cache,
Backend: a.authServer.Services,
})
if err != nil {
return nil, trace.Wrap(err)
}
resp, err := trust.GetCertAuthority(ctx, &trustpb.GetCertAuthorityRequest{
Domain: id.DomainName,
Type: string(id.Type),
IncludeKey: loadKeys,
})
if err != nil {
return nil, trace.Wrap(err)
}
return resp, trace.Wrap(err)
}
func (a *ServerWithRoles) GetDomainName(ctx context.Context) (string, error) {
// anyone can read it, no harm in that
return a.authServer.GetDomainName()
}
// getClusterCACert returns the PEM-encoded TLS certs for the local cluster
// without signing keys. If the cluster has multiple TLS certs, they will all
// be concatenated.
func (a *ServerWithRoles) GetClusterCACert(
ctx context.Context,
) (*proto.GetClusterCACertResponse, error) {
// Allow all roles to get the CA certs.
return a.authServer.GetClusterCACert(ctx)
}
func (a *ServerWithRoles) DeleteCertAuthority(ctx context.Context, id types.CertAuthID) error {
trust, err := trustv1.NewService(&trustv1.ServiceConfig{
Authorizer: authz.AuthorizerFunc(func(context.Context) (*authz.Context, error) {
return &a.context, nil
}),
Cache: a.authServer.Cache,
Backend: a.authServer.Services,
})
if err != nil {
return trace.Wrap(err)
}
if _, err := trust.DeleteCertAuthority(ctx, &trustpb.DeleteCertAuthorityRequest{Domain: id.DomainName, Type: string(id.Type)}); err != nil {
return trace.Wrap(err)
}
return nil
}
// ActivateCertAuthority not implemented: can only be called locally.
func (a *ServerWithRoles) ActivateCertAuthority(id types.CertAuthID) error {
return trace.NotImplemented(notImplementedMessage)
}
// DeactivateCertAuthority not implemented: can only be called locally.
func (a *ServerWithRoles) DeactivateCertAuthority(id types.CertAuthID) error {
return trace.NotImplemented(notImplementedMessage)
}
// UpdateUserCARoleMap not implemented: can only be called locally.
func (a *ServerWithRoles) UpdateUserCARoleMap(ctx context.Context, name string, roleMap types.RoleMap, activated bool) error {
return trace.NotImplemented(notImplementedMessage)
}
func (a *ServerWithRoles) RegisterUsingToken(ctx context.Context, req *types.RegisterUsingTokenRequest) (*proto.Certs, error) {
// We do not trust remote addr in the request unless it's coming from the Proxy.
if !a.hasBuiltinRole(types.RoleProxy) || req.RemoteAddr == "" {
if err := setRemoteAddrFromContext(ctx, req); err != nil {
return nil, trace.Wrap(err)
}
}
// tokens have authz mechanism on their own, no need to check
return a.authServer.RegisterUsingToken(ctx, req)
}
// RegisterUsingIAMMethod registers the caller using the IAM join method and
// returns signed certs to join the cluster.
//
// See (*Server).RegisterUsingIAMMethod for further documentation.
//
// This wrapper does not do any extra authz checks, as the register method has
// its own authz mechanism.
func (a *ServerWithRoles) RegisterUsingIAMMethod(ctx context.Context, challengeResponse client.RegisterIAMChallengeResponseFunc) (*proto.Certs, error) {
certs, err := a.authServer.RegisterUsingIAMMethod(ctx, challengeResponse)
return certs, trace.Wrap(err)
}
// RegisterUsingAzureMethod registers the caller using the Azure join method and
// returns signed certs to join the cluster.
//
// See (*Server).RegisterUsingAzureMethod for further documentation.
//
// This wrapper does not do any extra authz checks, as the register method has
// its own authz mechanism.
func (a *ServerWithRoles) RegisterUsingAzureMethod(ctx context.Context, challengeResponse client.RegisterAzureChallengeResponseFunc) (*proto.Certs, error) {
certs, err := a.authServer.RegisterUsingAzureMethod(ctx, challengeResponse)
return certs, trace.Wrap(err)
}
// GenerateHostCerts generates new host certificates (signed
// by the host certificate authority) for a node.
func (a *ServerWithRoles) GenerateHostCerts(ctx context.Context, req *proto.HostCertsRequest) (*proto.Certs, error) {
clusterName, err := a.authServer.GetDomainName()
if err != nil {
return nil, trace.Wrap(err)
}
// username is hostID + cluster name, so make sure server requests new keys for itself
if a.context.User.GetName() != HostFQDN(req.HostID, clusterName) {
return nil, trace.AccessDenied("username mismatch %q and %q", a.context.User.GetName(), HostFQDN(req.HostID, clusterName))
}
if req.Role == types.RoleInstance {
if err := a.checkAdditionalSystemRoles(ctx, req); err != nil {
return nil, trace.Wrap(err)
}
} else {
if len(req.SystemRoles) != 0 {
return nil, trace.AccessDenied("additional system role encoding not supported for certs of type %q", req.Role)
}
}
existingRoles, err := types.NewTeleportRoles(a.context.User.GetRoles())
if err != nil {
return nil, trace.Wrap(err)
}
// prohibit privilege escalations through role changes (except the instance cert exception, handled above).
if !a.hasBuiltinRole(req.Role) && req.Role != types.RoleInstance {
return nil, trace.AccessDenied("roles do not match: %v and %v", existingRoles, req.Role)
}
return a.authServer.GenerateHostCerts(ctx, req)
}
// checkAdditionalSystemRoles verifies additional system roles in host cert request.
func (a *ServerWithRoles) checkAdditionalSystemRoles(ctx context.Context, req *proto.HostCertsRequest) error {
// ensure requesting cert's primary role is a server role.
role, ok := a.context.Identity.(authz.BuiltinRole)
if !ok || !role.IsServer() {
return trace.AccessDenied("additional system roles can only be claimed by a teleport built-in server")
}
// check that additional system roles are theoretically valid (distinct from permissibility, which
// is checked in the following loop).
for _, r := range req.SystemRoles {
if r.Check() != nil {
return trace.AccessDenied("additional system role %q cannot be applied (not a valid system role)", r)
}
if !r.IsLocalService() {
return trace.AccessDenied("additional system role %q cannot be applied (not a builtin service role)", r)
}
}
// check if additional system roles are permissible
for _, requestedRole := range req.SystemRoles {
if a.hasBuiltinRole(requestedRole) {
// instance is already known to hold this role
continue
}
return trace.AccessDenied("additional system role %q cannot be applied (not authorized)", requestedRole)
}
return nil
}
// RegisterInventoryControlStream handles the upstream half of the control stream handshake, then passes the control stream to
// the auth server's main control logic. We also return the post-auth hello message back up to the grpcserver layer in order to
// use it for metrics purposes.
func (a *ServerWithRoles) RegisterInventoryControlStream(ics client.UpstreamInventoryControlStream) (proto.UpstreamInventoryHello, error) {
// this value gets set further down
var hello proto.UpstreamInventoryHello
// Ensure that caller is a teleport server
role, ok := a.context.Identity.(authz.BuiltinRole)
if !ok || !role.IsServer() {
return hello, trace.AccessDenied("inventory control streams can only be created by a teleport built-in server")
}
// wait for upstream hello
select {
case msg := <-ics.Recv():
switch m := msg.(type) {
case proto.UpstreamInventoryHello:
hello = m
default:
return hello, trace.BadParameter("expected upstream hello, got: %T", m)
}
case <-ics.Done():
return hello, trace.Wrap(ics.Error())
case <-a.CloseContext().Done():
return hello, trace.Errorf("auth server shutdown")
}
// verify that server is creating stream on behalf of itself.
if hello.ServerID != role.GetServerID() {
return hello, trace.AccessDenied("control streams do not support impersonation (%q -> %q)", role.GetServerID(), hello.ServerID)
}
// in order to reduce sensitivity to downgrades/misconfigurations, we simply filter out
// services that are unrecognized or unauthorized, rather than rejecting hellos that claim them.
var filteredServices []types.SystemRole
for _, service := range hello.Services {
if !a.hasBuiltinRole(service) {
log.Warnf("Omitting service %q for control stream of instance %q (unknown or unauthorized).", service, role.GetServerID())
continue
}
filteredServices = append(filteredServices, service)
}