-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
integrations_awsoidc.go
976 lines (830 loc) · 31.4 KB
/
integrations_awsoidc.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
/*
* Teleport
* Copyright (C) 2023 Gravitational, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package web
import (
"context"
"encoding/base64"
"encoding/json"
"fmt"
"net/http"
"net/url"
"slices"
"strings"
"github.com/gravitational/trace"
"github.com/julienschmidt/httprouter"
"github.com/gravitational/teleport"
"github.com/gravitational/teleport/api/client"
"github.com/gravitational/teleport/api/client/proto"
integrationv1 "github.com/gravitational/teleport/api/gen/proto/go/teleport/integration/v1"
"github.com/gravitational/teleport/api/types"
"github.com/gravitational/teleport/api/utils"
"github.com/gravitational/teleport/api/utils/aws"
"github.com/gravitational/teleport/lib/auth"
"github.com/gravitational/teleport/lib/defaults"
"github.com/gravitational/teleport/lib/httplib"
"github.com/gravitational/teleport/lib/integrations/awsoidc"
"github.com/gravitational/teleport/lib/integrations/awsoidc/deployserviceconfig"
"github.com/gravitational/teleport/lib/reversetunnelclient"
"github.com/gravitational/teleport/lib/services"
libutils "github.com/gravitational/teleport/lib/utils"
"github.com/gravitational/teleport/lib/web/scripts/oneoff"
"github.com/gravitational/teleport/lib/web/ui"
)
// awsOIDCListDatabases returns a list of databases using the ListDatabases action of the AWS OIDC Integration.
func (h *Handler) awsOIDCListDatabases(w http.ResponseWriter, r *http.Request, p httprouter.Params, sctx *SessionContext, site reversetunnelclient.RemoteSite) (any, error) {
ctx := r.Context()
var req ui.AWSOIDCListDatabasesRequest
if err := httplib.ReadJSON(r, &req); err != nil {
return nil, trace.Wrap(err)
}
integrationName := p.ByName("name")
if integrationName == "" {
return nil, trace.BadParameter("an integration name is required")
}
clt, err := sctx.GetUserClient(ctx, site)
if err != nil {
return nil, trace.Wrap(err)
}
listDatabasesResp, err := clt.IntegrationAWSOIDCClient().ListDatabases(ctx, &integrationv1.ListDatabasesRequest{
Integration: integrationName,
Region: req.Region,
RdsType: req.RDSType,
Engines: req.Engines,
NextToken: req.NextToken,
})
if err != nil {
return nil, trace.Wrap(err)
}
return ui.AWSOIDCListDatabasesResponse{
NextToken: listDatabasesResp.NextToken,
Databases: ui.MakeDatabases(listDatabasesResp.Databases, nil, nil),
}, nil
}
// awsOIDCDeployService deploys a Discovery Service and a Database Service in Amazon ECS.
func (h *Handler) awsOIDCDeployService(w http.ResponseWriter, r *http.Request, p httprouter.Params, sctx *SessionContext, site reversetunnelclient.RemoteSite) (any, error) {
ctx := r.Context()
var req ui.AWSOIDCDeployServiceRequest
if err := httplib.ReadJSON(r, &req); err != nil {
return nil, trace.Wrap(err)
}
integrationName := p.ByName("name")
if integrationName == "" {
return nil, trace.BadParameter("an integration name is required")
}
clt, err := sctx.GetUserClient(ctx, site)
if err != nil {
return nil, trace.Wrap(err)
}
databaseAgentMatcherLabels := make(types.Labels, len(req.DatabaseAgentMatcherLabels))
for _, label := range req.DatabaseAgentMatcherLabels {
databaseAgentMatcherLabels[label.Name] = utils.Strings{label.Value}
}
iamTokenName := deployserviceconfig.DefaultTeleportIAMTokenName
teleportConfigString, err := deployserviceconfig.GenerateTeleportConfigString(
h.PublicProxyAddr(),
iamTokenName,
databaseAgentMatcherLabels,
)
if err != nil {
return nil, trace.Wrap(err)
}
teleportVersionTag := teleport.Version
if automaticUpgrades(h.ClusterFeatures) {
cloudStableVersion, err := h.cfg.AutomaticUpgradesChannels.DefaultVersion(ctx)
if err != nil {
return "", trace.Wrap(err)
}
// cloudStableVersion has vX.Y.Z format, however the container image tag does not include the `v`.
teleportVersionTag = strings.TrimPrefix(cloudStableVersion, "v")
}
deployServiceResp, err := clt.IntegrationAWSOIDCClient().DeployService(ctx, &integrationv1.DeployServiceRequest{
DeploymentJoinTokenName: iamTokenName,
DeploymentMode: req.DeploymentMode,
TeleportConfigString: teleportConfigString,
Integration: integrationName,
Region: req.Region,
SecurityGroups: req.SecurityGroups,
SubnetIds: req.SubnetIDs,
TaskRoleArn: req.TaskRoleARN,
TeleportVersion: teleportVersionTag,
})
if err != nil {
return nil, trace.Wrap(err)
}
return ui.AWSOIDCDeployServiceResponse{
ClusterARN: deployServiceResp.ClusterArn,
ServiceARN: deployServiceResp.ServiceArn,
TaskDefinitionARN: deployServiceResp.TaskDefinitionArn,
ServiceDashboardURL: deployServiceResp.ServiceDashboardUrl,
}, nil
}
// awsOIDCDeployDatabaseService deploys a Database Service in Amazon ECS.
func (h *Handler) awsOIDCDeployDatabaseServices(w http.ResponseWriter, r *http.Request, p httprouter.Params, sctx *SessionContext, site reversetunnelclient.RemoteSite) (any, error) {
ctx := r.Context()
var req ui.AWSOIDCDeployDatabaseServiceRequest
if err := httplib.ReadJSON(r, &req); err != nil {
return nil, trace.Wrap(err)
}
integrationName := p.ByName("name")
if integrationName == "" {
return nil, trace.BadParameter("an integration name is required")
}
clt, err := sctx.GetUserClient(ctx, site)
if err != nil {
return nil, trace.Wrap(err)
}
teleportVersionTag := teleport.Version
if automaticUpgrades(h.ClusterFeatures) {
cloudStableVersion, err := h.cfg.AutomaticUpgradesChannels.DefaultVersion(ctx)
if err != nil {
return "", trace.Wrap(err)
}
// cloudStableVersion has vX.Y.Z format, however the container image tag does not include the `v`.
teleportVersionTag = strings.TrimPrefix(cloudStableVersion, "v")
}
iamTokenName := deployserviceconfig.DefaultTeleportIAMTokenName
deployments := make([]*integrationv1.DeployDatabaseServiceDeployment, 0, len(req.Deployments))
for _, d := range req.Deployments {
teleportConfigString, err := deployserviceconfig.GenerateTeleportConfigString(
h.PublicProxyAddr(),
iamTokenName,
types.Labels{
types.DiscoveryLabelVPCID: []string{d.VPCID},
types.DiscoveryLabelRegion: []string{req.Region},
},
)
if err != nil {
return nil, trace.Wrap(err)
}
deployments = append(deployments, &integrationv1.DeployDatabaseServiceDeployment{
VpcId: d.VPCID,
SubnetIds: d.SubnetIDs,
SecurityGroups: d.SecurityGroups,
TeleportConfigString: teleportConfigString,
})
}
deployServiceResp, err := clt.IntegrationAWSOIDCClient().DeployDatabaseService(ctx, &integrationv1.DeployDatabaseServiceRequest{
Integration: integrationName,
Region: req.Region,
TaskRoleArn: req.TaskRoleARN,
Deployments: deployments,
TeleportVersion: teleportVersionTag,
DeploymentJoinTokenName: deployserviceconfig.DefaultTeleportIAMTokenName,
})
if err != nil {
return nil, trace.Wrap(err)
}
return ui.AWSOIDCDeployDatabaseServiceResponse{
ClusterARN: deployServiceResp.ClusterArn,
ClusterDashboardURL: deployServiceResp.ClusterDashboardUrl,
}, nil
}
// awsOIDCConfigureDeployServiceIAM returns a script that configures the required IAM permissions to enable the usage of DeployService action.
func (h *Handler) awsOIDCConfigureDeployServiceIAM(w http.ResponseWriter, r *http.Request, p httprouter.Params) (any, error) {
ctx := r.Context()
queryParams := r.URL.Query()
clusterName, err := h.GetProxyClient().GetDomainName(ctx)
if err != nil {
return nil, trace.Wrap(err)
}
integrationName := queryParams.Get("integrationName")
if len(integrationName) == 0 {
return nil, trace.BadParameter("missing integrationName param")
}
// Ensure the IntegrationName is valid.
_, err = h.GetProxyClient().GetIntegration(ctx, integrationName)
// NotFound error is ignored to prevent disclosure of whether the integration exists in a public/no-auth endpoint.
if err != nil && !trace.IsNotFound(err) {
return nil, trace.Wrap(err)
}
awsRegion := queryParams.Get("awsRegion")
if err := aws.IsValidRegion(awsRegion); err != nil {
return nil, trace.BadParameter("invalid awsRegion")
}
role := queryParams.Get("role")
if err := aws.IsValidIAMRoleName(role); err != nil {
return nil, trace.BadParameter("invalid role %q", role)
}
taskRole := queryParams.Get("taskRole")
if err := aws.IsValidIAMRoleName(taskRole); err != nil {
return nil, trace.BadParameter("invalid taskRole")
}
// The script must execute the following command:
// teleport integration configure deployservice-iam
argsList := []string{
"integration", "configure", "deployservice-iam",
fmt.Sprintf("--cluster=%s", libutils.UnixShellQuote(clusterName)),
fmt.Sprintf("--name=%s", libutils.UnixShellQuote(integrationName)),
fmt.Sprintf("--aws-region=%s", libutils.UnixShellQuote(awsRegion)),
fmt.Sprintf("--role=%s", libutils.UnixShellQuote(role)),
fmt.Sprintf("--task-role=%s", libutils.UnixShellQuote(taskRole)),
}
script, err := oneoff.BuildScript(oneoff.OneOffScriptParams{
TeleportArgs: strings.Join(argsList, " "),
SuccessMessage: "Success! You can now go back to the browser to complete the database enrollment.",
})
if err != nil {
return nil, trace.Wrap(err)
}
httplib.SetScriptHeaders(w.Header())
_, err = fmt.Fprint(w, script)
return nil, trace.Wrap(err)
}
// awsOIDCConfigureEICEIAM returns a script that configures the required IAM permissions to enable the usage of EC2 Instance Connect Endpoint
// to access EC2 instances.
func (h *Handler) awsOIDCConfigureEICEIAM(w http.ResponseWriter, r *http.Request, p httprouter.Params) (any, error) {
queryParams := r.URL.Query()
awsRegion := queryParams.Get("awsRegion")
if err := aws.IsValidRegion(awsRegion); err != nil {
return nil, trace.BadParameter("invalid awsRegion")
}
role := queryParams.Get("role")
if err := aws.IsValidIAMRoleName(role); err != nil {
return nil, trace.BadParameter("invalid role %q", role)
}
// The script must execute the following command:
// teleport integration configure eice-iam
argsList := []string{
"integration", "configure", "eice-iam",
fmt.Sprintf("--aws-region=%s", libutils.UnixShellQuote(awsRegion)),
fmt.Sprintf("--role=%s", libutils.UnixShellQuote(role)),
}
script, err := oneoff.BuildScript(oneoff.OneOffScriptParams{
TeleportArgs: strings.Join(argsList, " "),
SuccessMessage: "Success! You can now go back to the browser to complete the EC2 enrollment.",
})
if err != nil {
return nil, trace.Wrap(err)
}
httplib.SetScriptHeaders(w.Header())
_, err = fmt.Fprint(w, script)
return nil, trace.Wrap(err)
}
// awsOIDCConfigureEKSIAM returns a script that configures the required IAM permissions to enroll EKS clusters into Teleport.
func (h *Handler) awsOIDCConfigureEKSIAM(w http.ResponseWriter, r *http.Request, p httprouter.Params) (any, error) {
queryParams := r.URL.Query()
awsRegion := queryParams.Get("awsRegion")
if err := aws.IsValidRegion(awsRegion); err != nil {
return nil, trace.BadParameter("invalid aws region")
}
role := queryParams.Get("role")
if err := aws.IsValidIAMRoleName(role); err != nil {
return nil, trace.BadParameter("invalid role %q", role)
}
// The script must execute the following command:
// "teleport integration configure eks-iam"
argsList := []string{
"integration", "configure", "eks-iam",
fmt.Sprintf("--aws-region=%s", libutils.UnixShellQuote(awsRegion)),
fmt.Sprintf("--role=%s", libutils.UnixShellQuote(role)),
}
script, err := oneoff.BuildScript(oneoff.OneOffScriptParams{
TeleportArgs: strings.Join(argsList, " "),
SuccessMessage: "Success! You can now go back to the browser to complete the EKS enrollment.",
})
if err != nil {
return nil, trace.Wrap(err)
}
httplib.SetScriptHeaders(w.Header())
_, err = fmt.Fprint(w, script)
return nil, trace.Wrap(err)
}
// awsOIDCEnrollEKSClusters enroll EKS clusters by installing teleport-kube-agent Helm chart on them.
func (h *Handler) awsOIDCEnrollEKSClusters(w http.ResponseWriter, r *http.Request, p httprouter.Params, sctx *SessionContext, site reversetunnelclient.RemoteSite) (any, error) {
ctx := r.Context()
var req ui.AWSOIDCEnrollEKSClustersRequest
if err := httplib.ReadJSON(r, &req); err != nil {
return nil, trace.Wrap(err)
}
clt, err := sctx.GetUserClient(ctx, site)
if err != nil {
return nil, trace.Wrap(err)
}
integrationName := p.ByName("name")
if integrationName == "" {
return nil, trace.BadParameter("an integration name is required")
}
// todo(anton): get auth server version and use it instead of this proxy teleport.version.
agentVersion := teleport.Version
if h.ClusterFeatures.GetAutomaticUpgrades() {
upgradesVersion, err := h.cfg.AutomaticUpgradesChannels.DefaultVersion(ctx)
if err != nil {
return "", trace.Wrap(err)
}
agentVersion = strings.TrimPrefix(upgradesVersion, "v")
}
response, err := clt.IntegrationAWSOIDCClient().EnrollEKSClusters(ctx, &integrationv1.EnrollEKSClustersRequest{
Integration: integrationName,
Region: req.Region,
EksClusterNames: req.ClusterNames,
EnableAppDiscovery: req.EnableAppDiscovery,
AgentVersion: agentVersion,
})
if err != nil {
return nil, trace.Wrap(err)
}
var data []ui.EKSClusterEnrollmentResult
for _, result := range response.Results {
data = append(data, ui.EKSClusterEnrollmentResult{
ClusterName: result.EksClusterName,
Error: result.Error,
ResourceId: result.ResourceId,
},
)
}
return ui.AWSOIDCEnrollEKSClustersResponse{
Results: data,
}, nil
}
// awsOIDCListEKSClusters returns a list of EKS clusters using the ListEKSClusters action of the AWS OIDC integration.
func (h *Handler) awsOIDCListEKSClusters(w http.ResponseWriter, r *http.Request, p httprouter.Params, sctx *SessionContext, site reversetunnelclient.RemoteSite) (any, error) {
ctx := r.Context()
var req ui.AWSOIDCListEKSClustersRequest
if err := httplib.ReadJSON(r, &req); err != nil {
return nil, trace.Wrap(err)
}
integrationName := p.ByName("name")
if integrationName == "" {
return nil, trace.BadParameter("an integration name is required")
}
clt, err := sctx.GetUserClient(ctx, site)
if err != nil {
return nil, trace.Wrap(err)
}
listResp, err := clt.IntegrationAWSOIDCClient().ListEKSClusters(ctx, &integrationv1.ListEKSClustersRequest{
Integration: integrationName,
Region: req.Region,
NextToken: req.NextToken,
})
if err != nil {
return nil, trace.Wrap(err)
}
return ui.AWSOIDCListEKSClustersResponse{
NextToken: listResp.NextToken,
Clusters: ui.MakeEKSClusters(listResp.Clusters),
}, nil
}
// awsOIDCListEC2 returns a list of EC2 Instances using the ListEC2 action of the AWS OIDC Integration.
func (h *Handler) awsOIDCListEC2(w http.ResponseWriter, r *http.Request, p httprouter.Params, sctx *SessionContext, site reversetunnelclient.RemoteSite) (any, error) {
ctx := r.Context()
var req ui.AWSOIDCListEC2Request
if err := httplib.ReadJSON(r, &req); err != nil {
return nil, trace.Wrap(err)
}
integrationName := p.ByName("name")
if integrationName == "" {
return nil, trace.BadParameter("an integration name is required")
}
clt, err := sctx.GetUserClient(ctx, site)
if err != nil {
return nil, trace.Wrap(err)
}
listResp, err := clt.IntegrationAWSOIDCClient().ListEC2(ctx, &integrationv1.ListEC2Request{
Integration: integrationName,
Region: req.Region,
NextToken: req.NextToken,
})
if err != nil {
return nil, trace.Wrap(err)
}
accessChecker, err := sctx.GetUserAccessChecker()
if err != nil {
return nil, trace.Wrap(err)
}
servers := make([]ui.Server, 0, len(listResp.Servers))
for _, s := range listResp.Servers {
serverUI, err := ui.MakeServer(h.auth.clusterName, s, accessChecker)
if err != nil {
return nil, trace.Wrap(err)
}
servers = append(servers, serverUI)
}
return ui.AWSOIDCListEC2Response{
NextToken: listResp.NextToken,
Servers: servers,
}, nil
}
// awsOIDCListSecurityGroups returns a list of VPC Security Groups using the ListSecurityGroups action of the AWS OIDC Integration.
func (h *Handler) awsOIDCListSecurityGroups(w http.ResponseWriter, r *http.Request, p httprouter.Params, sctx *SessionContext, site reversetunnelclient.RemoteSite) (any, error) {
ctx := r.Context()
var req ui.AWSOIDCListSecurityGroupsRequest
if err := httplib.ReadJSON(r, &req); err != nil {
return nil, trace.Wrap(err)
}
integrationName := p.ByName("name")
if integrationName == "" {
return nil, trace.BadParameter("an integration name is required")
}
clt, err := sctx.GetUserClient(ctx, site)
if err != nil {
return nil, trace.Wrap(err)
}
listResp, err := clt.IntegrationAWSOIDCClient().ListSecurityGroups(ctx, &integrationv1.ListSecurityGroupsRequest{
Integration: integrationName,
Region: req.Region,
VpcId: req.VPCID,
NextToken: req.NextToken,
})
if err != nil {
return nil, trace.Wrap(err)
}
sgs := make([]awsoidc.SecurityGroup, 0, len(listResp.SecurityGroups))
for _, sg := range listResp.SecurityGroups {
sgs = append(sgs, awsoidc.SecurityGroup{
Name: sg.Name,
ID: sg.Id,
Description: sg.Description,
InboundRules: awsOIDCSecurityGroupsRulesConverter(sg.InboundRules),
OutboundRules: awsOIDCSecurityGroupsRulesConverter(sg.OutboundRules),
})
}
return ui.AWSOIDCListSecurityGroupsResponse{
NextToken: listResp.NextToken,
SecurityGroups: sgs,
}, nil
}
func awsOIDCSecurityGroupsRulesConverter(inRules []*integrationv1.SecurityGroupRule) []awsoidc.SecurityGroupRule {
out := make([]awsoidc.SecurityGroupRule, 0, len(inRules))
for _, r := range inRules {
cidrs := make([]awsoidc.CIDR, 0, len(r.Cidrs))
for _, cidr := range r.Cidrs {
cidrs = append(cidrs, awsoidc.CIDR{
CIDR: cidr.Cidr,
Description: cidr.Description,
})
}
out = append(out, awsoidc.SecurityGroupRule{
IPProtocol: r.IpProtocol,
FromPort: int(r.FromPort),
ToPort: int(r.ToPort),
CIDRs: cidrs,
})
}
return out
}
// awsOIDCRequiredDatabasesVPCS returns a map of required VPC's and its subnets.
// This is required during the web UI discover flow (where users opt for auto
// discovery) to determine if user can skip the auto deployment screen (where we deploy
// database agents).
//
// This api will return empty if we already have agents that can proxy the discovered databases.
// Otherwise it will return with a map of VPC and its subnets where it's values are later used
// to configure and deploy an agent (deploy an agent per unique VPC).
func (h *Handler) awsOIDCRequiredDatabasesVPCS(w http.ResponseWriter, r *http.Request, p httprouter.Params, sctx *SessionContext, site reversetunnelclient.RemoteSite) (any, error) {
ctx := r.Context()
var req ui.AWSOIDCRequiredVPCSRequest
if err := httplib.ReadJSON(r, &req); err != nil {
return nil, trace.Wrap(err)
}
integrationName := p.ByName("name")
if integrationName == "" {
return nil, trace.BadParameter("an integration name is required")
}
clt, err := sctx.GetUserClient(ctx, site)
if err != nil {
return nil, trace.Wrap(err)
}
respAllDatabases, err := awsOIDCListAllDatabases(ctx, clt, integrationName, req.Region)
if err != nil {
return nil, trace.Wrap(err)
}
if len(respAllDatabases) == 0 {
return nil, trace.BadParameter("there are no available RDS instances or clusters found in region %q", req.Region)
}
resp, err := awsOIDCRequiredVPCSHelper(ctx, clt, req, respAllDatabases)
if err != nil {
return nil, trace.Wrap(err)
}
return resp, nil
}
func awsOIDCListAllDatabases(ctx context.Context, clt auth.ClientI, integration, region string) ([]*types.DatabaseV3, error) {
nextToken := ""
var fetchedRDSs []*types.DatabaseV3
// Get all rds instances.
for {
resp, err := clt.IntegrationAWSOIDCClient().ListDatabases(ctx, &integrationv1.ListDatabasesRequest{
Integration: integration,
Region: region,
RdsType: services.RDSDescribeTypeInstance,
Engines: []string{services.RDSEngineMySQL, services.RDSEngineMariaDB, services.RDSEnginePostgres},
NextToken: nextToken,
})
if err != nil {
return nil, trace.Wrap(err)
}
fetchedRDSs = append(fetchedRDSs, resp.Databases...)
nextToken = resp.NextToken
if len(nextToken) == 0 {
break
}
}
// Get all rds clusters.
nextToken = ""
for {
resp, err := clt.IntegrationAWSOIDCClient().ListDatabases(ctx, &integrationv1.ListDatabasesRequest{
Integration: integration,
Region: region,
RdsType: services.RDSDescribeTypeCluster,
Engines: []string{services.RDSEngineAuroraMySQL, services.RDSEngineAuroraPostgres},
NextToken: nextToken,
})
if err != nil {
return nil, trace.Wrap(err)
}
fetchedRDSs = append(fetchedRDSs, resp.Databases...)
nextToken = resp.NextToken
if len(nextToken) == 0 {
break
}
}
return fetchedRDSs, nil
}
func awsOIDCRequiredVPCSHelper(ctx context.Context, clt auth.ClientI, req ui.AWSOIDCRequiredVPCSRequest, fetchedRDSs []*types.DatabaseV3) (*ui.AWSOIDCRequiredVPCSResponse, error) {
// Get all database services with ecs/fargate metadata label.
nextToken := ""
fetchedDbSvcs := []types.DatabaseService{}
for {
page, err := client.GetResourcePage[types.DatabaseService](ctx, clt, &proto.ListResourcesRequest{
ResourceType: types.KindDatabaseService,
Limit: defaults.MaxIterationLimit,
StartKey: nextToken,
Labels: map[string]string{types.AWSOIDCAgentLabel: types.True},
})
if err != nil {
return nil, trace.Wrap(err)
}
fetchedDbSvcs = append(fetchedDbSvcs, page.Resources...)
nextToken = page.NextKey
if len(nextToken) == 0 {
break
}
}
// Construct map of VPCs and its subnets.
vpcLookup := map[string][]string{}
for _, db := range fetchedRDSs {
rds := db.GetAWS().RDS
vpcId := rds.VPCID
if _, found := vpcLookup[vpcId]; !found {
vpcLookup[vpcId] = rds.Subnets
continue
}
combinedSubnets := append(vpcLookup[vpcId], rds.Subnets...)
vpcLookup[vpcId] = utils.Deduplicate(combinedSubnets)
}
for _, svc := range fetchedDbSvcs {
if len(svc.GetResourceMatchers()) != 1 || svc.GetResourceMatchers()[0].Labels == nil {
continue
}
// Database services deployed by Teleport have known configurations where
// we will only define a single resource matcher.
labelMatcher := *svc.GetResourceMatchers()[0].Labels
// We check for length 3, because we are only
// wanting/checking for 3 discovery labels.
if len(labelMatcher) != 3 {
continue
}
if slices.Compare(labelMatcher[types.DiscoveryLabelAccountID], []string{req.AccountID}) != 0 {
continue
}
if slices.Compare(labelMatcher[types.DiscoveryLabelRegion], []string{req.Region}) != 0 {
continue
}
if len(labelMatcher[types.DiscoveryLabelVPCID]) != 1 {
continue
}
delete(vpcLookup, labelMatcher[types.DiscoveryLabelVPCID][0])
}
return &ui.AWSOIDCRequiredVPCSResponse{
VPCMapOfSubnets: vpcLookup,
}, nil
}
// awsOIDCListEC2ICE returns a list of EC2 Instance Connect Endpoints using the ListEC2ICE action of the AWS OIDC Integration.
func (h *Handler) awsOIDCListEC2ICE(w http.ResponseWriter, r *http.Request, p httprouter.Params, sctx *SessionContext, site reversetunnelclient.RemoteSite) (any, error) {
ctx := r.Context()
var req ui.AWSOIDCListEC2ICERequest
if err := httplib.ReadJSON(r, &req); err != nil {
return nil, trace.Wrap(err)
}
integrationName := p.ByName("name")
if integrationName == "" {
return nil, trace.BadParameter("an integration name is required")
}
clt, err := sctx.GetUserClient(ctx, site)
if err != nil {
return nil, trace.Wrap(err)
}
vpcIds := req.VPCIDs
if len(vpcIds) == 0 {
vpcIds = []string{req.VPCID}
}
resp, err := clt.IntegrationAWSOIDCClient().ListEICE(ctx, &integrationv1.ListEICERequest{
Integration: integrationName,
Region: req.Region,
VpcIds: vpcIds,
NextToken: req.NextToken,
})
if err != nil {
return nil, trace.Wrap(err)
}
endpoints := make([]awsoidc.EC2InstanceConnectEndpoint, 0, len(resp.Ec2Ices))
for _, e := range resp.Ec2Ices {
endpoints = append(endpoints, awsoidc.EC2InstanceConnectEndpoint{
Name: e.Name,
State: e.State,
StateMessage: e.StateMessage,
DashboardLink: e.DashboardLink,
SubnetID: e.SubnetId,
VPCID: e.VpcId,
})
}
return ui.AWSOIDCListEC2ICEResponse{
NextToken: resp.NextToken,
DashboardLink: resp.DashboardLink,
EC2ICEs: endpoints,
}, nil
}
// awsOIDCDeployC2ICE creates an EC2 Instance Connect Endpoint.
func (h *Handler) awsOIDCDeployEC2ICE(w http.ResponseWriter, r *http.Request, p httprouter.Params, sctx *SessionContext, site reversetunnelclient.RemoteSite) (any, error) {
ctx := r.Context()
var req ui.AWSOIDCDeployEC2ICERequest
if err := httplib.ReadJSON(r, &req); err != nil {
return nil, trace.Wrap(err)
}
integrationName := p.ByName("name")
if integrationName == "" {
return nil, trace.BadParameter("an integration name is required")
}
clt, err := sctx.GetUserClient(ctx, site)
if err != nil {
return nil, trace.Wrap(err)
}
endpoints := make([]*integrationv1.EC2ICEndpoint, 0, len(req.Endpoints))
for _, endpoint := range req.Endpoints {
endpoints = append(endpoints, &integrationv1.EC2ICEndpoint{
SubnetId: endpoint.SubnetID,
SecurityGroupIds: endpoint.SecurityGroupIDs,
})
}
// Backwards compatible: get the endpoint from the deprecated fields.
if len(endpoints) == 0 {
endpoints = append(endpoints, &integrationv1.EC2ICEndpoint{
SubnetId: req.SubnetID,
SecurityGroupIds: req.SecurityGroupIDs,
})
}
createResp, err := clt.IntegrationAWSOIDCClient().CreateEICE(ctx, &integrationv1.CreateEICERequest{
Integration: integrationName,
Region: req.Region,
Endpoints: endpoints,
})
if err != nil {
return nil, trace.Wrap(err)
}
respEndpoints := make([]ui.AWSOIDCDeployEC2ICEResponseEndpoint, 0, len(createResp.CreatedEndpoints))
for _, endpoint := range createResp.CreatedEndpoints {
respEndpoints = append(respEndpoints, ui.AWSOIDCDeployEC2ICEResponseEndpoint{
Name: endpoint.Name,
SubnetID: endpoint.SubnetId,
})
}
return ui.AWSOIDCDeployEC2ICEResponse{
Name: createResp.Name,
Endpoints: respEndpoints,
}, nil
}
// awsOIDCConfigureIdP returns a script that configures AWS OIDC Integration
// by creating an OIDC Identity Provider that trusts Teleport instance.
func (h *Handler) awsOIDCConfigureIdP(w http.ResponseWriter, r *http.Request, p httprouter.Params) (any, error) {
ctx := r.Context()
queryParams := r.URL.Query()
clusterName, err := h.GetProxyClient().GetDomainName(ctx)
if err != nil {
return nil, trace.Wrap(err)
}
integrationName := queryParams.Get("integrationName")
if len(integrationName) == 0 {
return nil, trace.BadParameter("missing integrationName param")
}
// Ensure the IntegrationName is valid.
_, err = h.GetProxyClient().GetIntegration(ctx, integrationName)
// NotFound error is ignored to prevent disclosure of whether the integration exists in a public/no-auth endpoint.
if err != nil && !trace.IsNotFound(err) {
return nil, trace.Wrap(err)
}
role := queryParams.Get("role")
if err := aws.IsValidIAMRoleName(role); err != nil {
return nil, trace.BadParameter("invalid role %q", role)
}
s3Bucket := queryParams.Get("s3Bucket")
s3Prefix := queryParams.Get("s3Prefix")
if s3Bucket == "" || s3Prefix == "" {
return nil, trace.BadParameter("s3Bucket and s3Prefix query params are required")
}
s3URI := url.URL{Scheme: "s3", Host: s3Bucket, Path: s3Prefix}
jwksContents, err := h.jwks(r.Context(), types.OIDCIdPCA)
if err != nil {
return nil, trace.Wrap(err)
}
jwksJSON, err := json.Marshal(jwksContents)
if err != nil {
return nil, trace.Wrap(err)
}
// The script must execute the following command:
// teleport integration configure awsoidc-idp
argsList := []string{
"integration", "configure", "awsoidc-idp",
fmt.Sprintf("--cluster=%s", libutils.UnixShellQuote(clusterName)),
fmt.Sprintf("--name=%s", libutils.UnixShellQuote(integrationName)),
fmt.Sprintf("--role=%s", libutils.UnixShellQuote(role)),
fmt.Sprintf("--s3-bucket-uri=%s", libutils.UnixShellQuote(s3URI.String())),
fmt.Sprintf("--s3-jwks-base64=%s", base64.StdEncoding.EncodeToString(jwksJSON)),
}
script, err := oneoff.BuildScript(oneoff.OneOffScriptParams{
TeleportArgs: strings.Join(argsList, " "),
SuccessMessage: "Success! You can now go back to the browser to use the integration with AWS.",
})
if err != nil {
return nil, trace.Wrap(err)
}
httplib.SetScriptHeaders(w.Header())
_, err = fmt.Fprint(w, script)
return nil, trace.Wrap(err)
}
// awsOIDCConfigureListDatabasesIAM returns a script that configures the required IAM permissions to allow Listing RDS DB Clusters and Instances.
func (h *Handler) awsOIDCConfigureListDatabasesIAM(w http.ResponseWriter, r *http.Request, p httprouter.Params) (any, error) {
queryParams := r.URL.Query()
awsRegion := queryParams.Get("awsRegion")
if err := aws.IsValidRegion(awsRegion); err != nil {
return nil, trace.BadParameter("invalid awsRegion")
}
role := queryParams.Get("role")
if err := aws.IsValidIAMRoleName(role); err != nil {
return nil, trace.BadParameter("invalid role %q", role)
}
// The script must execute the following command:
// teleport integration configure listdatabases-iam
argsList := []string{
"integration", "configure", "listdatabases-iam",
fmt.Sprintf("--aws-region=%s", libutils.UnixShellQuote(awsRegion)),
fmt.Sprintf("--role=%s", libutils.UnixShellQuote(role)),
}
script, err := oneoff.BuildScript(oneoff.OneOffScriptParams{
TeleportArgs: strings.Join(argsList, " "),
SuccessMessage: "Success! You can now go back to the browser to complete the Database enrollment.",
})
if err != nil {
return nil, trace.Wrap(err)
}
httplib.SetScriptHeaders(w.Header())
_, err = fmt.Fprint(w, script)
return nil, trace.Wrap(err)
}
// accessGraphCloudSyncOIDC returns a script that configures the required IAM permissions to sync
// Cloud resources with Teleport Access Graph.
func (h *Handler) accessGraphCloudSyncOIDC(w http.ResponseWriter, r *http.Request, p httprouter.Params) (any, error) {
queryParams := r.URL.Query()
switch kind := queryParams.Get("kind"); kind {
case "aws-iam":
return h.awsAccessGraphOIDCSync(w, r, p)
default:
return nil, trace.BadParameter("unsupported kind provided %q", kind)
}
}
func (h *Handler) awsAccessGraphOIDCSync(w http.ResponseWriter, r *http.Request, p httprouter.Params) (any, error) {
queryParams := r.URL.Query()
role := queryParams.Get("role")
if err := aws.IsValidIAMRoleName(role); err != nil {
return nil, trace.BadParameter("invalid role %q", role)
}
// The script must execute the following command:
// "teleport integration configure access-graph aws-iam"
argsList := []string{
"integration", "configure", "access-graph", "aws-iam",
fmt.Sprintf("--role=%s", libutils.UnixShellQuote(role)),
}
script, err := oneoff.BuildScript(oneoff.OneOffScriptParams{
TeleportArgs: strings.Join(argsList, " "),
SuccessMessage: "Success! You can now go back to the browser to complete the Access Graph AWS Sync enrollment.",
})
if err != nil {
return nil, trace.Wrap(err)
}
httplib.SetScriptHeaders(w.Header())
_, err = fmt.Fprint(w, script)
return nil, trace.Wrap(err)
}