-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
aws.go
1413 lines (1274 loc) · 47.6 KB
/
aws.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 2022 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 aws
import (
"context"
"errors"
"fmt"
"strings"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/arn"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/endpoints"
awssession "github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/iam"
"github.com/aws/aws-sdk-go/service/iam/iamiface"
"github.com/aws/aws-sdk-go/service/kms"
"github.com/aws/aws-sdk-go/service/secretsmanager"
"github.com/aws/aws-sdk-go/service/ssm"
"github.com/aws/aws-sdk-go/service/ssm/ssmiface"
"github.com/aws/aws-sdk-go/service/sts"
"github.com/aws/aws-sdk-go/service/sts/stsiface"
"github.com/gravitational/trace"
"golang.org/x/exp/slices"
"github.com/gravitational/teleport/api/types"
apiutils "github.com/gravitational/teleport/api/utils"
apiawsutils "github.com/gravitational/teleport/api/utils/aws"
awslib "github.com/gravitational/teleport/lib/cloud/aws"
"github.com/gravitational/teleport/lib/configurators"
"github.com/gravitational/teleport/lib/defaults"
"github.com/gravitational/teleport/lib/modules"
"github.com/gravitational/teleport/lib/service/servicecfg"
"github.com/gravitational/teleport/lib/services"
"github.com/gravitational/teleport/lib/srv/db/secrets"
"github.com/gravitational/teleport/lib/utils"
awsutils "github.com/gravitational/teleport/lib/utils/aws"
)
const (
// DatabaseAccessPolicyName is the policy name for database access.
DatabaseAccessPolicyName = "DatabaseAccess"
// databasePolicyDescription description used on the policy created.
databasePolicyDescription = "Used by Teleport database agents for accessing AWS-hosted databases."
// discoveryServicePolicyDescription description used on the policy created.
discoveryServicePolicyDescription = "Used by Teleport the discovery service to discover AWS-hosted services."
// boundarySuffix boundary policies will have this suffix.
boundarySuffix = "Boundary"
// policyTeleportTagKey key of the tag added to the policies created.
policyTeleportTagKey = "teleport"
// policyTeleportTagValue value of the tag added to the policies created.
policyTeleportTagValue = ""
// defaultAttachUser default user that the policy will be attached to.
defaultAttachUser = "username"
// targetIdentityARNSectionPlaceholder is the placeholder to use in a target
// AWS IAM identity ARN when the full ARN is not given by the user and the
// configurator is running in --manual mode.
// e.g. arn:*:iam::*:user/username (placeholder for partition and account).
targetIdentityARNSectionPlaceholder = "*"
)
type databaseActions struct {
// discovery is a list of actions used for database discovery.
discovery []string
// iamAuth is a list of actions used for enabling IAM auth.
iamAuth []string
// metadata is a list of actions used for fetching database metadata
metadata []string
// managedUsers is a list of actions used for managing database users.
managedUsers []string
// authBoundary is a list of actions for authorization that need to added
// to boundary policies.
authBoundary []string
requireIAMEdit bool
requireSecretsManager bool
}
func (a databaseActions) buildStatement(opt databaseActionsBuildOption) *awslib.Statement {
var actions []string
if opt.withDiscovery {
actions = append(actions, a.discovery...)
}
if opt.withMetadata {
actions = append(actions, a.metadata...)
}
if opt.withAuth {
actions = append(actions, a.iamAuth...)
actions = append(actions, a.managedUsers...)
}
if opt.withAuthBoundary {
actions = append(actions, a.authBoundary...)
}
return &awslib.Statement{
Effect: awslib.EffectAllow,
Actions: apiutils.Deduplicate(actions),
Resources: []string{"*"},
}
}
type databaseActionsBuildOption struct {
withDiscovery bool
withMetadata bool
withAuth bool
withAuthBoundary bool
}
func makeDatabaseActionsBuildOption(flags configurators.BootstrapFlags, targetCfg targetConfig, boundary bool) databaseActionsBuildOption {
switch flags.Service {
case configurators.DiscoveryService:
return databaseActionsBuildOption{
withDiscovery: true,
}
case configurators.DatabaseServiceByDiscoveryServiceConfig:
return databaseActionsBuildOption{
withDiscovery: false,
withAuth: true,
withAuthBoundary: boundary,
// Discovered databases should be checked by URL validator which
// requires same permissions as the metadata service.
withMetadata: true,
}
case configurators.DatabaseService:
return databaseActionsBuildOption{
withDiscovery: true,
withMetadata: true,
withAuth: true,
withAuthBoundary: boundary,
}
default:
return databaseActionsBuildOption{}
}
}
var (
// defaultPolicyTags default list of tags present at the managed policies.
defaultPolicyTags = map[string]string{policyTeleportTagKey: policyTeleportTagValue}
// secretsManagerActions is a list of actions used for SecretsManager.
secretsManagerActions = []string{
"secretsmanager:DescribeSecret",
"secretsmanager:CreateSecret",
"secretsmanager:UpdateSecret",
"secretsmanager:DeleteSecret",
"secretsmanager:GetSecretValue",
"secretsmanager:PutSecretValue",
"secretsmanager:TagResource",
}
// kmsActions is a list of actions used for custom KMS keys.
kmsActions = []string{
"kms:GenerateDataKey",
"kms:Decrypt",
}
// ec2Actions is a list of actions used for EC2 auto-discovery
ec2Actions = []string{
"ec2:DescribeInstances",
"ssm:GetCommandInvocation",
"ssm:SendCommand",
}
// stsActions is a list of actions used for assuming an AWS role.
stsActions = []string{
"sts:AssumeRole",
}
// rdsActions contains IAM actions for types.AWSMatcherRDS (RDS
// instances and Aurora clusters).
rdsActions = databaseActions{
discovery: []string{"rds:DescribeDBInstances", "rds:DescribeDBClusters"},
metadata: []string{"rds:DescribeDBInstances", "rds:DescribeDBClusters"},
iamAuth: []string{"rds:ModifyDBInstance", "rds:ModifyDBCluster"},
authBoundary: []string{"rds-db:connect"},
requireIAMEdit: true,
}
// rdsProxyActions contains IAM actions for types.AWSMatcherRDSProxy.
rdsProxyActions = databaseActions{
discovery: []string{
"rds:DescribeDBProxies",
"rds:DescribeDBProxyEndpoints",
"rds:DescribeDBProxyTargets",
"rds:ListTagsForResource",
},
metadata: []string{
"rds:DescribeDBProxies",
"rds:DescribeDBProxyEndpoints",
},
authBoundary: []string{"rds-db:connect"},
requireIAMEdit: true,
}
// redshiftActions contains IAM actions for types.AWSMatcherRedshift.
redshiftActions = databaseActions{
discovery: []string{"redshift:DescribeClusters"},
metadata: []string{"redshift:DescribeClusters"},
authBoundary: []string{"redshift:GetClusterCredentials"},
requireIAMEdit: true,
}
// redshiftServerlessActions contains IAM actions for types.AWSMatcherRedshiftServerless.
redshiftServerlessActions = databaseActions{
discovery: []string{
"redshift-serverless:ListWorkgroups",
"redshift-serverless:ListEndpointAccess",
"redshift-serverless:ListTagsForResource",
},
metadata: []string{
"redshift-serverless:GetEndpointAccess",
"redshift-serverless:GetWorkgroup",
},
authBoundary: stsActions,
}
// elastiCacheActions contains IAM actions for types.AWSMatcherElastiCache.
elastiCacheActions = databaseActions{
discovery: []string{
"elasticache:ListTagsForResource",
"elasticache:DescribeReplicationGroups",
"elasticache:DescribeCacheClusters",
"elasticache:DescribeCacheSubnetGroups",
},
metadata: []string{
"elasticache:DescribeReplicationGroups",
},
managedUsers: []string{
"elasticache:DescribeUsers",
"elasticache:ModifyUser",
},
requireSecretsManager: true,
authBoundary: []string{"elasticache:Connect"},
requireIAMEdit: true,
}
// memoryDBActions contains IAM actions for types.AWSMatcherMemoryDB.
memoryDBActions = databaseActions{
discovery: []string{
"memorydb:ListTags",
"memorydb:DescribeClusters",
"memorydb:DescribeSubnetGroups",
},
metadata: []string{
"memorydb:DescribeClusters",
},
managedUsers: []string{
"memorydb:DescribeUsers",
"memorydb:UpdateUser",
},
requireSecretsManager: true,
authBoundary: []string{"memorydb:Connect"},
requireIAMEdit: true,
}
// awsKeyspacesActions contains IAM actions for static AWS Keyspaces databases.
awsKeyspacesActions = databaseActions{
authBoundary: stsActions,
}
// dynamodbActions contains IAM actions for static AWS DynamoDB databases.
dynamodbActions = databaseActions{
authBoundary: stsActions,
}
// opensearchActions contains IAM actions for types.AWSMatcherOpenSearch
opensearchActions = databaseActions{
discovery: []string{
"es:ListDomainNames",
"es:DescribeDomains",
"es:ListTags",
},
metadata: []string{
// Used for url validation.
"es:DescribeDomains",
},
authBoundary: stsActions,
}
)
// awsConfigurator defines the AWS database configurator.
type awsConfigurator struct {
// config AWS configurator list of configs.
config ConfiguratorConfig
// actions list of the configurator actions, those are populated on the
// `build` function.
actions []configurators.ConfiguratorAction
}
type ConfiguratorConfig struct {
// Flags user-provided flags to configure/execute the configurator.
Flags configurators.BootstrapFlags
// ServiceConfig Teleport database service config.
ServiceConfig *servicecfg.Config
// AWSSession current AWS session.
AWSSession *awssession.Session
// AWSSTSClient AWS STS client.
AWSSTSClient stsiface.STSAPI
// AWSIAMClient AWS IAM client.
AWSIAMClient iamiface.IAMAPI
// AWSSSMClient is a mapping of region -> ssm client
AWSSSMClients map[string]ssmiface.SSMAPI
// Policies instance of the `Policies` that the actions use.
Policies awslib.Policies
// Identity is the current AWS credentials chain identity.
Identity awslib.Identity
}
// CheckAndSetDefaults checks and set configuration default values.
func (c *ConfiguratorConfig) CheckAndSetDefaults() error {
if c.ServiceConfig == nil {
return trace.BadParameter("config file is required")
}
useFIPSEndpoint := endpoints.FIPSEndpointStateUnset
if modules.GetModules().IsBoringBinary() {
useFIPSEndpoint = endpoints.FIPSEndpointStateEnabled
}
// When running the command in manual mode, we want to have zero dependency
// with AWS configurations (like awscli or environment variables), so that
// the user can run this command and generate the instructions without any
// pre-requisite.
if !c.Flags.Manual {
var err error
if c.AWSSession == nil {
c.AWSSession, err = awssession.NewSessionWithOptions(awssession.Options{
SharedConfigState: awssession.SharedConfigEnable,
Config: aws.Config{
EC2MetadataEnableFallback: aws.Bool(false),
UseFIPSEndpoint: useFIPSEndpoint,
},
})
if err != nil {
return trace.Wrap(err)
}
}
if c.AWSSTSClient == nil {
c.AWSSTSClient = sts.New(c.AWSSession)
}
if c.AWSIAMClient == nil {
c.AWSIAMClient = iam.New(c.AWSSession)
}
if c.Identity == nil {
c.Identity, err = awslib.GetIdentityWithClient(context.Background(), c.AWSSTSClient)
if err != nil {
return trace.Wrap(err)
}
}
if c.AWSSSMClients == nil {
c.AWSSSMClients = make(map[string]ssmiface.SSMAPI)
for _, matcher := range c.ServiceConfig.Discovery.AWSMatchers {
if !slices.Contains(matcher.Types, types.AWSMatcherEC2) {
continue
}
for _, region := range matcher.Regions {
if _, ok := c.AWSSSMClients[region]; ok {
continue
}
session, err := awssession.NewSessionWithOptions(awssession.Options{
Config: aws.Config{
Region: ®ion,
EC2MetadataEnableFallback: aws.Bool(false),
UseFIPSEndpoint: useFIPSEndpoint,
},
SharedConfigState: awssession.SharedConfigEnable,
})
if err != nil {
return trace.Wrap(err)
}
c.AWSSSMClients[region] = ssm.New(session)
}
}
}
if c.Policies == nil {
c.Policies = awslib.NewPolicies(c.Identity.GetPartition(), c.Identity.GetAccountID(), iam.New(c.AWSSession))
}
}
return nil
}
// NewAWSConfigurator creates an instance of awsConfigurator and builds its
// actions.
func NewAWSConfigurator(config ConfiguratorConfig) (configurators.Configurator, error) {
err := config.CheckAndSetDefaults()
if err != nil {
return nil, trace.Wrap(err)
}
actions, err := buildActions(config)
if err != nil {
return nil, trace.Wrap(err)
}
return &awsConfigurator{config, actions}, nil
}
// IsEmpty checks if the configurator has no actions.
func (a *awsConfigurator) IsEmpty() bool {
return len(a.actions) == 0
}
// Name returns human-readable configurator name.
func (a *awsConfigurator) Name() string {
return "AWS"
}
// Description returns a brief description of the configurator.
func (a *awsConfigurator) Description() string {
return "Configure AWS for " + a.config.Flags.Service.Name()
}
// Actions list of configurator actions.
func (a *awsConfigurator) Actions() []configurators.ConfiguratorAction {
return a.actions
}
// awsPolicyCreator creates a `PolicyDocument` on AWS, it also stores the policy
// ARN in the context.
type awsPolicyCreator struct {
// policies `Policies` used to upsert the policy document.
policies awslib.Policies
// isBoundary indicates if the policy created is a boundary or not.
isBoundary bool
// policy document that will be created on AWS.
policy *awslib.Policy
// formattedPolicy human-readable representation of the policy document.
formattedPolicy string
}
// Description returns what the action will perform.
func (a *awsPolicyCreator) Description() string {
return fmt.Sprintf("Create IAM Policy %q", a.policy.Name)
}
// Details returns the policy document that will be created.
func (a *awsPolicyCreator) Details() string {
return a.formattedPolicy
}
// Execute upserts the policy and store its ARN in the action context.
func (a *awsPolicyCreator) Execute(ctx context.Context, actionCtx *configurators.ConfiguratorActionContext) error {
if a.policies == nil {
return trace.BadParameter("policy helper not initialized")
}
arn, err := a.policies.Upsert(ctx, a.policy)
if err != nil {
return trace.Wrap(err)
}
if a.isBoundary {
actionCtx.AWSPolicyBoundaryArn = arn
} else {
actionCtx.AWSPolicyArn = arn
}
return nil
}
// awsPoliciesAttacher attach policy and policy boundary to a target. Both
// policies ARN are retrieved from the `Execute` `context.Context`.
type awsPoliciesAttacher struct {
// policies `Policies` used to attach policy and policy boundary.
policies awslib.Policies
// target identity where the policy will be attached to.
target awslib.Identity
}
// Description returns what the action will perform.
func (a *awsPoliciesAttacher) Description() string {
return fmt.Sprintf("Attach IAM policies to %q", a.target.GetName())
}
// Details attacher doesn't have any extra detail, this function returns an
// empty string.
func (a *awsPoliciesAttacher) Details() string {
return ""
}
// Execute retrieves policy and policy boundary ARNs from
// `ConfiguratorActionContext` and attach them to the `target`.
func (a *awsPoliciesAttacher) Execute(ctx context.Context, actionCtx *configurators.ConfiguratorActionContext) error {
if a.policies == nil {
return trace.BadParameter("policy helper not initialized")
}
if actionCtx.AWSPolicyArn == "" {
return trace.BadParameter("policy ARN not present")
}
if actionCtx.AWSPolicyBoundaryArn == "" {
return trace.BadParameter("policy boundary ARN not present")
}
err := a.policies.Attach(ctx, actionCtx.AWSPolicyArn, a.target)
if err != nil {
return trace.Wrap(err)
}
err = a.policies.AttachBoundary(ctx, actionCtx.AWSPolicyBoundaryArn, a.target)
if err != nil {
return trace.Wrap(err)
}
return nil
}
func buildDiscoveryActions(config ConfiguratorConfig, targetCfg targetConfig) ([]configurators.ConfiguratorAction, error) {
actions, err := buildCommonActions(config, targetCfg)
if err != nil {
return nil, trace.Wrap(err)
}
proxyAddr, err := getProxyAddrFromConfig(config.ServiceConfig, config.Flags)
if err != nil {
return nil, err
}
actions = append(actions, buildSSMDocumentCreators(config.AWSSSMClients, targetCfg, proxyAddr)...)
return actions, nil
}
func buildCommonActions(config ConfiguratorConfig, targetCfg targetConfig) ([]configurators.ConfiguratorAction, error) {
// Generate policies.
policy, err := buildPolicyDocument(config.Flags, targetCfg, false)
if err != nil {
return nil, trace.Wrap(err)
}
policyBoundary, err := buildPolicyDocument(config.Flags, targetCfg, true)
if err != nil {
return nil, trace.Wrap(err)
}
// If the policy has no statements means that the agent doesn't require
// any IAM permission. In this case, return without errors and with empty
// actions.
if len(policy.Document.Statements) == 0 {
return []configurators.ConfiguratorAction{}, nil
}
formattedPolicy, err := policy.Document.Marshal()
if err != nil {
return nil, trace.Wrap(err)
}
var actions []configurators.ConfiguratorAction
// Create IAM Policy.
actions = append(actions, &awsPolicyCreator{
policies: config.Policies,
policy: policy,
formattedPolicy: formattedPolicy,
})
formattedPolicyBoundary, err := policyBoundary.Document.Marshal()
if err != nil {
return nil, trace.Wrap(err)
}
// Create IAM Policy boundary.
actions = append(actions, &awsPolicyCreator{
policies: config.Policies,
policy: policyBoundary,
formattedPolicy: formattedPolicyBoundary,
isBoundary: true,
})
// Attach both policies to the target.
actions = append(actions, &awsPoliciesAttacher{policies: config.Policies, target: targetCfg.identity})
return actions, nil
}
// buildActions generates the policy documents and configurator actions.
func buildActions(config ConfiguratorConfig) ([]configurators.ConfiguratorAction, error) {
// Identity is going to be empty (`nil`) when running the command on
// `Manual` mode, place a wildcard to keep the generated policies valid.
accountID := targetIdentityARNSectionPlaceholder
partitionID := targetIdentityARNSectionPlaceholder
if config.Identity != nil {
accountID = config.Identity.GetAccountID()
partitionID = config.Identity.GetPartition()
}
// Define the target and target type.
target, err := policiesTarget(config.Flags, accountID, partitionID, config.Identity, config.AWSIAMClient)
if err != nil {
return nil, trace.Wrap(err)
}
targetCfg, err := getTargetConfig(config.Flags, config.ServiceConfig, target)
if err != nil {
return nil, trace.Wrap(err)
}
if config.Flags.Service.IsDiscovery() {
return buildDiscoveryActions(config, targetCfg)
}
return buildCommonActions(config, targetCfg)
}
// policiesTarget defines which target and its type the policies will be
// attached to.
func policiesTarget(flags configurators.BootstrapFlags, accountID string, partitionID string, identity awslib.Identity, iamClient iamiface.IAMAPI) (awslib.Identity, error) {
if flags.AttachToUser != "" {
userArn := flags.AttachToUser
if !arn.IsARN(flags.AttachToUser) {
userArn = buildIAMARN(partitionID, accountID, "user", flags.AttachToUser)
}
return awslib.IdentityFromArn(userArn)
}
if flags.AttachToRole != "" {
roleArn := flags.AttachToRole
if !arn.IsARN(flags.AttachToRole) {
roleArn = buildIAMARN(partitionID, accountID, "role", flags.AttachToRole)
}
return awslib.IdentityFromArn(roleArn)
}
if identity == nil {
return awslib.IdentityFromArn(buildIAMARN(partitionID, accountID, "user", defaultAttachUser))
}
if identity.GetType() == awslib.ResourceTypeAssumedRole {
roleIdentity, err := getRoleARNForAssumedRole(iamClient, identity)
if err != nil {
return nil, trace.Wrap(err)
}
return roleIdentity, nil
}
return identity, nil
}
// buildIAMARN constructs an AWS IAM ARN string from the given partition,
// account, resource type, and resource.
// If the resource starts with the "/" prefix, this function takes care not to
// add an additional "/" prefix to the constructed ARN.
// This handles resource names that include a path correctly. Example:
// resource input: "/some/path/to/rolename"
// arn output: "arn:aws:iam::123456789012:role/some/path/to/rolename"
func buildIAMARN(partitionID, accountID, resourceType, resource string) string {
if strings.HasPrefix(resource, "/") {
return fmt.Sprintf("arn:%s:iam::%s:%s%s", partitionID, accountID, resourceType, resource)
} else {
return fmt.Sprintf("arn:%s:iam::%s:%s/%s", partitionID, accountID, resourceType, resource)
}
}
// failedToResolveAssumeRoleARN is an error message returned when an
// assumed-role identity cannot be resolved to the role ARN that it assumes,
// which is necessary to attach policies to the identity.
// Rather than returning errors about why it failed, this message suggests a
// simple fix for the user to specify a role or user to attach policies to.
const failedToResolveAssumeRoleARN = "Running with assumed-role credentials. Policies cannot be attached to an assumed-role. Provide the name or ARN of the IAM user or role to attach policies to."
// getRoleARNForAssumedRole attempts to resolve assumed-role credentials to
// the underlying role ARN using IAM API.
// This is necessary since the assumed-role ARN does not include the role path,
// so we cannot reliably reconstruct the role ARN from the assumed-role ARN.
func getRoleARNForAssumedRole(iamClient iamiface.IAMAPI, identity awslib.Identity) (awslib.Identity, error) {
roleOutput, err := iamClient.GetRole(&iam.GetRoleInput{RoleName: aws.String(identity.GetName())})
if err != nil || roleOutput == nil || roleOutput.Role == nil || roleOutput.Role.Arn == nil {
return nil, trace.BadParameter(failedToResolveAssumeRoleARN)
}
roleIdentity, err := awslib.IdentityFromArn(*roleOutput.Role.Arn)
if err != nil {
return nil, trace.BadParameter(failedToResolveAssumeRoleARN)
}
return roleIdentity, nil
}
// buildPolicyDocument builds the policy document.
func buildPolicyDocument(flags configurators.BootstrapFlags, targetCfg targetConfig, boundary bool) (*awslib.Policy, error) {
policyDoc := awslib.NewPolicyDocument()
policyDescription := databasePolicyDescription
policyName := flags.PolicyName
if boundary {
policyName += boundarySuffix
}
if flags.Service.IsDiscovery() {
policyDescription = discoveryServicePolicyDescription
if isEC2AutoDiscoveryEnabled(flags, targetCfg.awsMatchers) {
policyDoc.EnsureStatements(buildEC2AutoDiscoveryStatements()...)
}
}
// Build statements for databases.
// TODO(greedy52) remove discovery permissions for static databases.
var requireSecretsManager, requireIAMEdit bool
var allActions []databaseActions
if hasRDSDatabases(flags, targetCfg) {
allActions = append(allActions, rdsActions)
}
if hasRDSProxyDatabases(flags, targetCfg) {
allActions = append(allActions, rdsProxyActions)
}
if hasRedshiftDatabases(flags, targetCfg) {
allActions = append(allActions, redshiftActions)
}
if hasRedshiftServerlessDatabases(flags, targetCfg) {
allActions = append(allActions, redshiftServerlessActions)
}
if hasElastiCacheDatabases(flags, targetCfg) {
allActions = append(allActions, elastiCacheActions)
}
if hasMemoryDBDatabases(flags, targetCfg) {
allActions = append(allActions, memoryDBActions)
}
if hasAWSKeyspacesDatabases(flags, targetCfg) {
allActions = append(allActions, awsKeyspacesActions)
}
if hasDynamoDBDatabases(flags, targetCfg) {
allActions = append(allActions, dynamodbActions)
}
if hasOpenSearchDatabases(flags, targetCfg) {
allActions = append(allActions, opensearchActions)
}
dbOption := makeDatabaseActionsBuildOption(flags, targetCfg, boundary)
for _, dbActions := range allActions {
policyDoc.EnsureStatements(dbActions.buildStatement(dbOption))
if dbOption.withAuth {
requireSecretsManager = requireSecretsManager || dbActions.requireSecretsManager
requireIAMEdit = requireIAMEdit || dbActions.requireIAMEdit
}
}
stsAssumeRoleStatements, err := buildSTSAssumeRoleStatements(flags, targetCfg, boundary)
if err != nil {
return nil, trace.Wrap(err)
}
policyDoc.EnsureStatements(stsAssumeRoleStatements...)
// For databases that need to access SecretsManager (and KMS).
if requireSecretsManager {
policyDoc.EnsureStatements(buildSecretsManagerStatements(targetCfg.databases, targetCfg.identity)...)
}
// For databases that need to edit IAM user/role policy.
if requireIAMEdit {
targetStatements, err := buildIAMEditStatements(targetCfg.identity)
if err != nil {
return nil, trace.Wrap(err)
}
policyDoc.EnsureStatements(targetStatements...)
}
return awslib.NewPolicy(
policyName,
policyDescription,
defaultPolicyTags,
policyDoc,
), nil
}
func getProxyAddrFromConfig(cfg *servicecfg.Config, flags configurators.BootstrapFlags) (string, error) {
if flags.Proxy != "" {
addr, err := utils.ParseHostPortAddr(flags.Proxy, defaults.HTTPListenPort)
if err != nil {
return "", trace.Wrap(err)
}
return fmt.Sprintf("https://%s", addr.String()), nil
}
if len(cfg.Proxy.PublicAddrs) != 0 {
return fmt.Sprintf("https://%s", cfg.Proxy.PublicAddrs[0].String()), nil
}
if !cfg.ProxyServer.IsEmpty() {
return fmt.Sprintf("https://%s", cfg.ProxyServer.String()), nil
}
return "", trace.NotFound("proxy address not found, please provide --proxy, or set either teleport.proxy_server or proxy_service.public_addr in the teleport config")
}
func buildSSMDocumentCreators(ssm map[string]ssmiface.SSMAPI, targetCfg targetConfig, proxyAddr string) []configurators.ConfiguratorAction {
var creators []configurators.ConfiguratorAction
for _, matcher := range targetCfg.awsMatchers {
if !slices.Contains(matcher.Types, types.AWSMatcherEC2) {
continue
}
for _, region := range matcher.Regions {
ssmCreator := awsSSMDocumentCreator{
ssm: ssm[region],
Name: matcher.SSM.DocumentName,
Contents: EC2DiscoverySSMDocument(proxyAddr),
}
creators = append(creators, &ssmCreator)
}
}
return creators
}
func isEC2AutoDiscoveryEnabled(flags configurators.BootstrapFlags, matchers []types.AWSMatcher) bool {
if flags.ForceEC2Permissions {
return true
}
return isAutoDiscoveryEnabledForMatcher(types.AWSMatcherEC2, matchers)
}
// hasRDSDatabases checks if the agent needs permission for
// RDS/Aurora databases.
func hasRDSDatabases(flags configurators.BootstrapFlags, targetCfg targetConfig) bool {
if flags.ForceRDSPermissions {
return true
}
return isAutoDiscoveryEnabledForMatcher(types.AWSMatcherRDS, targetCfg.awsMatchers) ||
findEndpointIs(targetCfg.databases, isRDSEndpoint)
}
// hasRDSProxyDatabases checks if the agent needs permission for
// RDS Proxy databases.
func hasRDSProxyDatabases(flags configurators.BootstrapFlags, targetCfg targetConfig) bool {
if flags.ForceRDSProxyPermissions {
return true
}
return isAutoDiscoveryEnabledForMatcher(types.AWSMatcherRDSProxy, targetCfg.awsMatchers) ||
findEndpointIs(targetCfg.databases, isRDSProxyEndpoint)
}
// hasRedshiftDatabases checks if the agent needs permission for
// Redshift databases.
func hasRedshiftDatabases(flags configurators.BootstrapFlags, targetCfg targetConfig) bool {
if flags.ForceRedshiftPermissions {
return true
}
return isAutoDiscoveryEnabledForMatcher(types.AWSMatcherRedshift, targetCfg.awsMatchers) ||
findEndpointIs(targetCfg.databases, apiawsutils.IsRedshiftEndpoint)
}
// hasRedshiftServerlessDatabases checks if the agent needs permission for
// Redshift Serverless databases.
func hasRedshiftServerlessDatabases(flags configurators.BootstrapFlags, targetCfg targetConfig) bool {
if flags.ForceRedshiftServerlessPermissions {
return true
}
return isAutoDiscoveryEnabledForMatcher(types.AWSMatcherRedshiftServerless, targetCfg.awsMatchers) ||
findEndpointIs(targetCfg.databases, apiawsutils.IsRedshiftServerlessEndpoint)
}
// hasElastiCacheDatabases checks if the agent needs permission for
// ElastiCache databases.
func hasElastiCacheDatabases(flags configurators.BootstrapFlags, targetCfg targetConfig) bool {
if flags.ForceElastiCachePermissions {
return true
}
return isAutoDiscoveryEnabledForMatcher(types.AWSMatcherElastiCache, targetCfg.awsMatchers) ||
findEndpointIs(targetCfg.databases, apiawsutils.IsElastiCacheEndpoint)
}
// hasMemoryDBDatabases checks if the agent needs permission for
// ElastiCache databases.
func hasMemoryDBDatabases(flags configurators.BootstrapFlags, targetCfg targetConfig) bool {
if flags.ForceMemoryDBPermissions {
return true
}
return isAutoDiscoveryEnabledForMatcher(types.AWSMatcherMemoryDB, targetCfg.awsMatchers) ||
findEndpointIs(targetCfg.databases, apiawsutils.IsMemoryDBEndpoint)
}
// hasOpenSearchDatabases checks if the agent needs permission for OpenSearch
// databases.
func hasOpenSearchDatabases(flags configurators.BootstrapFlags, targetCfg targetConfig) bool {
if flags.ForceOpenSearchPermissions {
return true
}
return isAutoDiscoveryEnabledForMatcher(types.AWSMatcherOpenSearch, targetCfg.awsMatchers) ||
findDatabaseIs(targetCfg.databases, func(db *servicecfg.Database) bool {
return db.Protocol == defaults.ProtocolOpenSearch
})
}
// hasAWSKeyspacesDatabases checks if the agent needs permission for AWS Keyspaces.
func hasAWSKeyspacesDatabases(flags configurators.BootstrapFlags, targetCfg targetConfig) bool {
if flags.ForceAWSKeyspacesPermissions {
return true
}
// There is no auto discovery for AWS Keyspaces.
if flags.Service.IsDiscovery() {
return false
}
return findDatabaseIs(targetCfg.databases, func(database *servicecfg.Database) bool {
return database.Protocol == defaults.ProtocolCassandra && database.AWS.AccountID != ""
})
}
// hasDynamoDBDatabases checks if the agent needs permission for AWS DynamoDB.
func hasDynamoDBDatabases(flags configurators.BootstrapFlags, targetCfg targetConfig) bool {
if flags.ForceDynamoDBPermissions {
return true
}
// There is no auto discovery for AWS DynamoDB.
if flags.Service.IsDiscovery() {
return false
}
return findDatabaseIs(targetCfg.databases, func(database *servicecfg.Database) bool {
return database.Protocol == defaults.ProtocolDynamoDB
})
}
// isAutoDiscoveryEnabledForMatcher returns true if provided AWS matcher type
// is found.
func isAutoDiscoveryEnabledForMatcher(matcherType string, matchers []types.AWSMatcher) bool {
return findAWSMatcherIs(matchers, func(matcher *types.AWSMatcher) bool {
for _, databaseType := range matcher.Types {
if databaseType == matcherType {
return true
}
}
return false
})
}
// findEndpointIs returns true if provided check returns true for any static
// endpoint.
func findEndpointIs(databases []*servicecfg.Database, endpointIs func(string) bool) bool {
return findDatabaseIs(databases, func(database *servicecfg.Database) bool {
return endpointIs(database.URI)
})
}
// findDatabaseIs returns true if provided check returns true for any static
// database config.
func findDatabaseIs(databases []*servicecfg.Database, is func(*servicecfg.Database) bool) bool {
for _, database := range databases {
if is(database) {
return true
}
}
return false
}
// findAWSMatcherIs returns true if the provided check returns true for any
// AWS matcher.
func findAWSMatcherIs(matchers []types.AWSMatcher, is func(*types.AWSMatcher) bool) bool {
for i := range matchers {
if is(&matchers[i]) {
return true
}
}
return false
}
// supportsAWSAssumeRole returns true if the given matcher supports assuming
// AWS roles. Currently limited to just the AWS database matchers.
func supportsAWSAssumeRole(matcher types.AWSMatcher) bool {
for _, matcherType := range matcher.Types {
if slices.Contains(types.SupportedAWSDatabaseMatchers, matcherType) {
return true
}
}
return false
}
// isRDSEndpoint returns true if the endpoint is an endpoint for RDS instance or Aurora cluster.
func isRDSEndpoint(uri string) bool {
details, err := apiawsutils.ParseRDSEndpoint(uri)
if err != nil {
return false
}
return !details.IsProxy()
}
// isRDSProxyEndpoint returns true if the endpoint is an endpoint for RDS Proxy.
func isRDSProxyEndpoint(uri string) bool {
details, err := apiawsutils.ParseRDSEndpoint(uri)
if err != nil {
return false
}
return details.IsProxy()
}
// buildIAMEditStatements returns IAM statements necessary for the Teleport
// agent to edit user/role permissions.
func buildIAMEditStatements(target awslib.Identity) ([]*awslib.Statement, error) {
switch target.(type) {
case awslib.User, *awslib.User:
return []*awslib.Statement{
awslib.StatementForIAMEditUserPolicy(target.String()),
}, nil
case awslib.Role, *awslib.Role:
return []*awslib.Statement{
awslib.StatementForIAMEditRolePolicy(target.String()),
}, nil
default:
return nil, trace.BadParameter("policies target must be an user or role, received %T", target)