This repository has been archived by the owner on Feb 27, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cft_sidecar.yaml
1759 lines (1617 loc) · 69.6 KB
/
cft_sidecar.yaml
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
# Cyral Sidecar
AWSTemplateFormatVersion: "2010-09-09"
Metadata:
'AWS::CloudFormation::Interface':
ParameterGroups:
- Label:
default: 'Sidecar basics'
Parameters:
- SidecarId
- ControlPlane
- SidecarClientID
- SidecarClientSecret
- Label:
default: 'Networking and Security Configuration'
Parameters:
- VPC
- Subnets
- SidecarPorts
- AssociatePublicIpAddress
- LoadBalancerScheme
- LoadBalancerCertificateArn
- LoadBalancerStickyPorts
- LoadBalancerSubnets
- LoadBalancerTLSPorts
- SSHKeyName
- SSHInboundCIDR
- DBInboundCIDR
- MonitoringInboundCIDR
- DeploySecrets
- SecretsLocation
- SecretsKMSArn
- EC2EBSKMSArn
- ContainerRegistry
- ContainerRegistryUsername
- ContainerRegistryKey
- SidecarTLSCertificateSecretArn
- SidecarTLSCertificateRoleArn
- SidecarCACertificateSecretArn
- SidecarCACertificateRoleArn
- SidecarCustomHostRole
- UserPolicies
- PermissionsBoundary
- Label:
default: 'SIEM Configuration'
Parameters:
- CloudwatchLogGroupName
- CloudwatchLogsRetention
- Label:
default: 'Snowflake Configuration'
Parameters:
- IdPSSOLoginURL
- IdPCertificate
- Label:
default: 'Advanced'
Parameters:
- SidecarVersion
- NamePrefix
- SidecarDNSName
- SidecarDNSHostedZoneId
- SidecarVolumeSize
- SidecarInstanceType
- EnableLocationBasedPolicyEval
- AmiId
- HealthCheckGracePeriod
- CustomUserDataPre
- CustomUserDataPreSidecarStart
- CustomUserDataPost
- MetadataHttpTokensOption
- TLSSkipVerify
- UseSingleContainer
- Label:
default: 'High Availability'
Parameters:
- AsgMin
- AsgMax
- AsgDesired
- EnableCrossZoneLoadBalancing
Parameters:
SidecarPorts:
Description:
"List of ports allowed to connect to the sidecar through the load balancer and security group.
The maximum number of ports is limited to Network Load Balancers quotas (listeners and target
groups). See also 'LoadBalancerTLSPorts'. Avoid port `9000` as it is reserved for instance
monitoring."
Type: String
Default: 443,453,1433,1521,3306,3307,5432,5439,9996,9999,27017,27018,27019,31010
AllowedPattern: ^(\d+\,)*(\d+)$
LoadBalancerTLSPorts:
Description:
"List of ports that will have TLS terminated at load balancer level
(snowflake or S3 browser support, for example). If assigned, 'LoadBalancerCertificateArn'
must also be provided. This parameter must be a subset of 'SidecarPorts'."
Type: String
Default: ""
AllowedPattern: ^((\d+\,)*(\d+))*$
LoadBalancerStickyPorts:
Description:
"List of ports that will have session stickiness enabled.
This parameter must be a subset of 'SidecarPorts'."
Type: String
Default: ""
AllowedPattern: ^((\d+\,)*(\d+))*$
VPC:
Description: "AWS VPC ID to deploy sidecar to"
Type: AWS::EC2::VPC::Id
AllowedPattern: ".+"
LoadBalancerScheme :
Description: "EC2 network load balancer scheme ('internal' or 'internet-facing')"
Type: String
AllowedValues: ['internal', 'internet-facing']
Default: 'internal'
ConstraintDescription: must specify 'internal' or 'internet-facing'.
AssociatePublicIpAddress :
Description: "Associates a public IP to sidecar EC2 instances"
Type: String
AllowedValues: [true, false]
Default: false
ConstraintDescription: must specify 'true' or 'false'.
SidecarDNSName:
Description: "(Optional) Fully qualified domain name that will be automatically created/updated to reference the sidecar LB"
Type: String
Default: ""
SidecarDNSHostedZoneId:
Description: "(Optional) Route53 hosted zone ID for the corresponding SidecarDNSName provided"
Type: String
Default: ""
DeploySecrets:
Description: "Create the AWS Secrets Manager resource at `SecretsLocation` storing `SidecarClientID`, `SidecarClientSecret` and `ContainerRegistryKey`"
Type: String
AllowedValues: [true, false]
Default: true
ConstraintDescription: must specify 'true' or 'false'.
SecretsLocation:
Description: "(Optional) Location in AWS Secrets Manager to store `SidecarClientID`, `SidecarClientSecret` and `ContainerRegistryKey`. If unset, will assume `/cyral/sidecars/<SIDECAR_ID>/secrets`."
Type: String
Default: ""
SecretsKMSArn:
Description: "(Optional) ARN of the KMS key used to encrypt/decrypt secrets. If unset, secrets will use the default KMS key."
Type: String
Default: ""
EC2EBSKMSArn:
Description: "(Optional) ARN of the KMS key used to encrypt/decrypt EBS volumes. If unset, EBS will use the default KMS key. Make sure the KMS key allows the principal `arn:aws:iam::ACCOUNT_NUMBER:role/aws-service-role/autoscaling.amazonaws.com/AWSServiceRoleForAutoScaling`, otherwise the ASG will not be able to launch the new instances."
Type: String
Default: ""
SidecarClientID:
NoEcho: true
Description: "Sidecar client ID"
Type: String
AllowedPattern: ".+"
SidecarClientSecret:
NoEcho: true
Description: "Sidecar client secret"
Type: String
AllowedPattern: ".+"
SidecarTLSCertificateSecretArn:
Description: "(Optional) ARN of secret in AWS Secrets Manager that contains a certificate to terminate TLS connections."
Type: String
Default: ""
AllowedPattern: "^(|arn:.+)$"
SidecarTLSCertificateRoleArn:
Description: "(Optional) ARN of an AWS IAM Role to assume when reading the TLS certificate."
Type: String
Default: ""
AllowedPattern: "^(|arn:.+)$"
SidecarCACertificateSecretArn:
Description: "(Optional) ARN of secret in AWS Secrets Manager that contains a CA certificate to sign sidecar-generated certs."
Type: String
Default: ""
AllowedPattern: "^(|arn:.+)$"
SidecarCACertificateRoleArn:
Description: "(Optional) ARN of an AWS IAM Role to assume when reading the CA certificate."
Type: String
Default: ""
AllowedPattern: "^(|arn:.+)$"
SidecarCustomHostRole:
Description: "(Optional) Name of an AWS IAM Role to attach to the EC2 instance profile."
Type: String
Default: ""
LoadBalancerCertificateArn:
Type: String
Description: (Optional) ARN of SSL certificate that will be used for client connections to Snowflake or S3 Browser.
Default: ""
IdPSSOLoginURL:
Description: "(Optional) The IdP SSO URL for the IdP being used with Snowflake. Required if using SSO with Snowflake."
Type: String
Default: ""
IdPCertificate:
Description: "(Optional) The certificate used to verify SAML assertions from the IdP being used with Snowflake. Enter this value as a one-line string with literal \n characters specifying the line breaks. Required if using SSO with Snowflake."
Type: String
Default: ""
SidecarPublicIdPCertificate:
Description: "(Optional) The public certificate used to verify signatures for SAML Assertions generated by the sidecar. Required if using SSO with Snowflake."
Type: String
Default: ""
SidecarPrivateIdPKey:
Description: "(Optional) The private key used to sign SAML Assertions generated by the sidecar. Required if using SSO with Snowflake."
Type: String
Default: ""
NoEcho: true
LoadBalancerSubnets:
Description: "Subnets to add load balancer to. If not provided, the load balancer will assume the subnets specified in the `Subnets` parameter."
Type: CommaDelimitedList
Default: ""
SSHKeyName:
Type: String
Description: "Name of an existing EC2 KeyPair to enable SSH access to the EC2 instances."
Default: ""
SSHInboundCIDR:
AllowedPattern: ^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])(\/([0-9]|[1-2][0-9]|3[0-2]))$
ConstraintDescription: "CIDR block parameter must be in the form x.x.x.x/x"
Description: "Allowed CIDR block for SSH access to the sidecar."
Type: String
Default: "0.0.0.0/0"
DBInboundCIDR:
AllowedPattern: ^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])(\/([0-9]|[1-2][0-9]|3[0-2]))$
ConstraintDescription: "CIDR block parameter must be in the form x.x.x.x/x"
Description: "Allowed CIDR block for database access to the sidecar."
Type: String
Default: "0.0.0.0/0"
MonitoringInboundCIDR:
AllowedPattern: ^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])(\/([0-9]|[1-2][0-9]|3[0-2]))$
ConstraintDescription: "CIDR block parameter must be in the form x.x.x.x/x"
Description: "Allowed CIDR block for health check and metrics requests to the sidecar. If restricting the access, consider setting to the VPC CIDR or an equivalent to cover the assigned subnets as the load balancer performs health checks on the EC2 instances."
Type: String
Default: "0.0.0.0/0"
SidecarVolumeSize:
Description: "Sidecar EC2 volume size (min 15GB)"
Type: "String"
Default: "15"
AllowedPattern: "[0-9]+"
SidecarInstanceType:
AllowedValues:
[t3.small, t3.medium, t3.large, t3.xlarge, m5.large, m5.xlarge, m5n.large, m5n.xlarge, c5.large, c5.xlarge, r5.large, r5.xlarge]
Default: t3.medium
Description: "Amazon EC2 instance type for the sidecar instances"
Type: String
EnableLocationBasedPolicyEval:
Type: String
Description: "Enable/Disable location-based policy evaluation"
Default: "false"
AllowedValues:
- "true"
- "false"
Subnets:
Description: "Subnets to add sidecar to"
Type: "List<AWS::EC2::Subnet::Id>"
SidecarId:
Type: String
Description: "Sidecar identifier"
AllowedPattern: ".+"
SidecarVersion:
Type: String
Description: "(Optional) The version of the sidecar. If unset, the version will be dynamically retrieved from the Control Plane."
Default: ""
NamePrefix:
Type: String
Description: "Prefix for names of the AWS resources created. Maximum length is 24 characters."
Default: ""
ControlPlane:
Type: String
Description: Control plane URL - <tenant>.app.cyral.com
AllowedPattern: ".+"
AmiId:
Type: 'AWS::SSM::Parameter::Value<AWS::EC2::Image::Id>'
Description: "Amazon Linux 2 AMI ID for sidecar EC2 instances. The default behavior is to use the latest version.
In order to define a new image, replace 'recommended' by the desired image name (eg 'amzn2-ami-ecs-hvm-2.0.20181112-x86_64-ebs')."
Default: '/aws/service/ami-amazon-linux-latest/amzn2-ami-hvm-x86_64-gp2'
CloudwatchLogsRetention:
Type: String
Description: Cloudwatch logs retention in days
ConstraintDescription: 'Valid values are: [1, 3, 5, 7, 14, 30, 60, 90, 120, 150, 180, 365, 400, 545, 731, 1827, 3653]'
Default: "14"
AllowedPattern: "^(1|3|5|7|14|30|60|90|120|150|180|365|400|545|731|1827|3653)$"
CloudwatchLogGroupName:
Type: String
Description: Cloudwatch log group name. In order to use this log group, set the logging integration in the control plane.
Default: ""
UserPolicies:
Type: CommaDelimitedList
Description: (Optional) List of IAM policies ARNs that will be attached to the sidecar IAM role (Comma Delimited List)
Default: ""
PermissionsBoundary:
Type: String
Description: ARN of the permissions boundary to apply to all the IAM roles. Set to an empty string if no permission boundaries should be used.
Default: ""
ContainerRegistry:
Description: "Address of the container registry where Cyral images are stored."
Type: String
AllowedPattern: ".+"
Default: "public.ecr.aws/cyral"
ContainerRegistryUsername:
Description: "Username to authenticate to the container registry."
Type: String
Default: ""
ContainerRegistryKey:
NoEcho: true
Description: "Corresponding key for the user name provided to authenticate to the container registry."
Type: String
Default: ""
HealthCheckGracePeriod:
Type: String
Description: "Determines how long (in seconds) the ASG will wait before checking the health status of the EC2 instance."
Default: "600"
AllowedPattern: "[0-9]+"
RecycleHealthCheckIntervalSec:
Type: String
Description: "(Optional) The interval (in seconds) in which the sidecar instance checks whether it has been marked or recycling."
Default: "30"
AllowedPattern: "[0-9]+"
AsgMin:
Description: "The minimum number of hosts to create in the auto autoscaling group"
Type: "String"
Default: "1"
AllowedPattern: "[0-9]+"
AsgDesired:
Description: "The desired number of hosts to create in the auto scaling group"
Type: "String"
Default: "1"
AllowedPattern: "[0-9]+"
AsgMax:
Description: "The maximum number of hosts to create in the auto scaling group"
Type: "String"
Default: "2"
AllowedPattern: "[0-9]+"
EnableCrossZoneLoadBalancing:
Description: "Enable cross zone load balancing"
Type: "String"
Default: "true"
AllowedValues:
- "true"
- "false"
CustomTag:
Type: String
Description: (Optional) Custom tag to be added in the sidecar resources. Ex:"key=value".
Default: ""
AllowedPattern: "^([0-9a-zA-Z]+=[0-9a-zA-Z]+|)$"
CustomUserDataPre:
Type: String
Description: (Optional) Ancillary consumer supplied user-data script. Provide Bash script commands to be executed before the sidecar installation. Ex:"echo 'TEST'".
Default: ""
CustomUserDataPreSidecarStart:
Type: String
Description: (Optional) Ancillary consumer supplied user-data script. Provide Bash script commands to be executed before the sidecar starts. Ex:"echo 'TEST'"
Default: ""
CustomUserDataPost:
Type: String
Description: (Optional) Ancillary consumer supplied user-data script. Provide Bash script commands to be executed after the sidecar starts. Ex:"echo 'TEST'"
Default: ""
MetadataHttpTokensOption:
Type: String
Description: Instance Metadata Service token requirement
Default: "required"
AllowedValues:
- "required"
- "optional"
TLSSkipVerify:
Description: "Skip TLS verification for HTTPS communication with the control plane and during sidecar initialization"
Type: "String"
Default: "false"
AllowedValues:
- "true"
- "false"
UseSingleContainer:
Description: "Use single container for sidecar deployment"
Type: "String"
Default: "false"
AllowedValues:
- "true"
- "false"
Mappings:
Constants:
MacrosTemplate:
# When changing the macros template version here, please make sure to also
# change it accordingly inside the resources template. The values are
# hardcoded there due to CloudFormation limitations (not possible to pass
# Macros version as a parameter to that stack).
Version: 1.4
ResourcesTemplate:
Version: 1.8
Conditions:
mustDeploySecrets: !Equals [!Ref DeploySecrets, true]
mustCreateDNSRecordSet: !And [!Not [!Equals [!Ref SidecarDNSHostedZoneId, '']], !Not [!Equals [!Ref SidecarDNSName, '']]]
sidecarDNSNameNotEmpty: !Not [!Equals [!Ref SidecarDNSName, '']]
sidecarTLSCertificateSecretArnEmpty: !Equals [!Ref SidecarTLSCertificateSecretArn, '']
sidecarTLSCertificateSecretArnNotEmpty: !Not [!Condition sidecarTLSCertificateSecretArnEmpty]
sidecarTLSCertificateRoleArnEmpty: !Equals [!Ref SidecarTLSCertificateRoleArn, '']
sidecarTLSCertificateRoleArnNotEmpty: !Not [!Condition sidecarTLSCertificateRoleArnEmpty]
sidecarTLSCertificateDoNotAssumeRole: !And
- !Condition sidecarTLSCertificateSecretArnNotEmpty
- !Condition sidecarTLSCertificateRoleArnEmpty
sidecarTLSCertificateMustAssumeRole: !And
- !Condition sidecarTLSCertificateSecretArnNotEmpty
- !Condition sidecarTLSCertificateRoleArnNotEmpty
sidecarCACertificateSecretArnEmpty: !Equals [!Ref SidecarCACertificateSecretArn, '']
sidecarCACertificateSecretArnNotEmpty: !Not [!Condition sidecarCACertificateSecretArnEmpty]
sidecarCACertificateRoleArnEmpty: !Equals [!Ref SidecarCACertificateRoleArn, '']
sidecarCACertificateRoleArnNotEmpty: !Not [!Condition sidecarCACertificateRoleArnEmpty]
sidecarCACertificateDoNotAssumeRole: !And
- !Condition sidecarCACertificateSecretArnNotEmpty
- !Condition sidecarCACertificateRoleArnEmpty
sidecarCACertificateMustAssumeRole: !And
- !Condition sidecarCACertificateSecretArnNotEmpty
- !Condition sidecarCACertificateRoleArnNotEmpty
sidecarCustomHostRoleEmpty: !Equals [!Ref SidecarCustomHostRole, '']
loadBalancerSubnetsEmpty: !Equals [!Join [",", !Ref LoadBalancerSubnets] , '']
mustAttachUserPolicies: !Not [!Equals [!Join ["", !Ref UserPolicies], ""]]
useKMSSecrets: !Not [!Equals [!Ref SecretsKMSArn, '']]
useKMSEBS: !Not [!Equals [!Ref EC2EBSKMSArn, '']]
useKMSSecretsOrEBS: !Or [!Condition useKMSSecrets, !Condition useKMSEBS]
useKMS: !Or [!Condition useKMSSecrets, !Condition useKMSEBS]
usePermissionsBoundary: !Not [!Equals [!Ref PermissionsBoundary, '']]
useCustomTag: !Not [!Equals [!Ref CustomTag, '']]
shouldSkipTls: !Equals [!Ref TLSSkipVerify, true]
hasCloudwatchLogGroupName: !Not [!Equals [!Ref CloudwatchLogGroupName, '']]
hasSSHKeyName: !Not [!Equals [!Ref SSHKeyName, '']]
hasSecretsLocation: !Not [!Equals [!Ref SecretsLocation, '']]
Resources:
GetNamePrefixLambda:
Type: AWS::Lambda::Function
Properties:
Description: "Creates the default NamePrefix in case not provided by the user"
Handler: index.handler
Runtime: "python3.9"
Timeout: 30
Role: !GetAtt LambdaIngressListRole.Arn
Code:
ZipFile: |
import json
import cfnresponse
def handler(event, context):
try:
response_data = {}
currentNamePrefix = event['ResourceProperties']['CurrentNamePrefix']
sidecarId = str(event['ResourceProperties']['SidecarId']) # Convert to string
if currentNamePrefix:
response_data['NamePrefix'] = currentNamePrefix
else:
response_data['NamePrefix'] = 'cyral-' + sidecarId[-6:].lower()
cfnresponse.send(event, context, cfnresponse.SUCCESS, response_data)
except Exception as e:
print(f'error: {e}')
cfnresponse.send(event, context, cfnresponse.FAILED, {})
Tags:
- Key: "Stack"
Value: !Ref "AWS::StackName"
- Fn::If:
- useCustomTag
- Key: !Select [0, !Split ["=", !Ref CustomTag]]
Value: !Select [1, !Split ["=", !Ref CustomTag]]
- !Ref AWS::NoValue
GetNamePrefixCustomResource:
Type: AWS::CloudFormation::CustomResource
Properties:
ServiceToken: !GetAtt GetNamePrefixLambda.Arn
CurrentNamePrefix: !Ref NamePrefix
SidecarId: !Ref SidecarId
CloudwatchLogGroup:
Type: AWS::Logs::LogGroup
Properties:
LogGroupName: !If [hasCloudwatchLogGroupName, !Ref CloudwatchLogGroupName, !GetAtt GetNamePrefixCustomResource.NamePrefix]
RetentionInDays: !Ref CloudwatchLogsRetention
Tags:
- Key: "Stack"
Value: !Ref "AWS::StackName"
- Fn::If:
- useCustomTag
- Key: !Select [0, !Split ["=", !Ref CustomTag]]
Value: !Select [1, !Split ["=", !Ref CustomTag]]
- !Ref AWS::NoValue
AutoScalingGroupSidecar:
Type: "AWS::AutoScaling::AutoScalingGroup"
UpdatePolicy:
AutoScalingRollingUpdate:
MinInstancesInService: 0
MaxBatchSize: 1
PauseTime: "PT5M"
SuspendProcesses:
- HealthCheck
- ReplaceUnhealthy
- AZRebalance
- AlarmNotification
- ScheduledActions
WaitOnResourceSignals: true
Properties:
LaunchTemplate:
LaunchTemplateId: !Ref SidecarLaunchTemplate
Version: !GetAtt SidecarLaunchTemplate.LatestVersionNumber
VPCZoneIdentifier: !Ref Subnets
MinSize: !Ref AsgMin
MaxSize: !Ref AsgMax
Cooldown: "0"
DesiredCapacity: !Ref AsgDesired
HealthCheckType: EC2
HealthCheckGracePeriod: !Ref HealthCheckGracePeriod
TargetGroupARNs:
Fn::Split:
- ","
- Fn::GetAtt:
- ResourcesStack
- Outputs.TargetGroupARNs
MetricsCollection:
- Granularity: "1Minute"
Metrics:
- "GroupInServiceInstances"
- "GroupPendingInstances"
- "GroupTerminatingInstances"
- "GroupTotalInstances"
Tags:
- Key: "Name"
Value: !Join ["-", [!GetAtt GetNamePrefixCustomResource.NamePrefix, "sidecar"]]
PropagateAtLaunch: true
- Key: "SidecarVersion"
Value: !Ref SidecarVersion
PropagateAtLaunch: true
- Key: "Stack"
Value: !Ref "AWS::StackName"
PropagateAtLaunch: true
- Key: "MetricsPort"
Value: "9000"
PropagateAtLaunch: true
- Fn::If:
- useCustomTag
- Key: !Select [0, !Split ["=", !Ref CustomTag]]
Value: !Select [1, !Split ["=", !Ref CustomTag]]
PropagateAtLaunch: true
- !Ref AWS::NoValue
CreationPolicy:
ResourceSignal:
Count: 0
Timeout: PT5M
SidecarHostProfile:
DependsOn: SidecarHostPolicy
Type: "AWS::IAM::InstanceProfile"
Properties:
Roles:
- !If [sidecarCustomHostRoleEmpty, !Ref SidecarHostRole, !Ref SidecarCustomHostRole]
Path: /
SidecarHostRole:
Condition: sidecarCustomHostRoleEmpty
Type: "AWS::IAM::Role"
Properties:
PermissionsBoundary:
Fn::If:
- usePermissionsBoundary
- !Ref PermissionsBoundary
- !Ref AWS::NoValue
Path: /
AssumeRolePolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Principal:
Service:
- ec2.amazonaws.com
Action:
- "sts:AssumeRole"
ManagedPolicyArns: !If [mustAttachUserPolicies, !Ref UserPolicies, !Ref AWS::NoValue]
SidecarHostPolicy:
Type: "AWS::IAM::Policy"
Properties:
PolicyName: SidecarPolicy
PolicyDocument:
Version: 2012-10-17
Statement:
- Action:
- "ec2:DescribeTags"
- "autoscaling:CompleteLifecycleAction"
- "autoscaling:SetInstanceHealth"
Resource: "*"
Effect: Allow
- Action:
- "logs:CreateLogStream"
- "logs:PutLogEvents"
Resource: !GetAtt CloudwatchLogGroup.Arn
Effect: Allow
- Action:
- "secretsmanager:GetSecretValue"
Resource:
- !Sub 'arn:${AWS::Partition}:secretsmanager:${AWS::Region}:${AWS::AccountId}:secret:/cyral/*'
- !Sub
- 'arn:${AWS::Partition}:secretsmanager:${AWS::Region}:${AWS::AccountId}:secret:${secrets_location}*'
- secrets_location: !If [hasSecretsLocation, !Ref SecretsLocation, !Sub '/cyral/sidecars/${SidecarId}/secrets']
- !If [sidecarTLSCertificateDoNotAssumeRole, !Ref SidecarTLSCertificateSecretArn, !Ref AWS::NoValue]
- !If [sidecarCACertificateDoNotAssumeRole, !Ref SidecarCACertificateSecretArn, !Ref AWS::NoValue]
Effect: Allow
- Action:
- "ecr:GetAuthorizationToken"
Resource: "*"
Effect: Allow
- Action:
- "ecr:BatchGetImage"
- "ecr:GetDownloadUrlForLayer"
Resource: !Sub "arn:${AWS::Partition}:ecr:*:${AWS::AccountId}:repository/*"
Effect: Allow
- Fn::If:
- sidecarTLSCertificateMustAssumeRole
- Effect: Allow
Action:
- sts:AssumeRole
Resource: !Ref SidecarTLSCertificateRoleArn
- !Ref AWS::NoValue
- Fn::If:
- sidecarCACertificateMustAssumeRole
- Effect: Allow
Action:
- sts:AssumeRole
Resource: !Ref SidecarCACertificateRoleArn
- !Ref AWS::NoValue
Roles:
- !If [sidecarCustomHostRoleEmpty, !Ref SidecarHostRole, !Ref SidecarCustomHostRole]
SidecarKMSPolicy:
Type: "AWS::IAM::Policy"
Condition: useKMS
Properties:
PolicyName: SidecarKMSPolicy
PolicyDocument:
Version: 2012-10-17
Statement:
- Fn::If:
- useKMSSecretsOrEBS
- Effect: Allow
Action:
- kms:Encrypt
- kms:Decrypt
- kms:GenerateDataKey
Resource:
- !If [useKMSSecrets, !Ref SecretsKMSArn, !Ref AWS::NoValue]
- !If [useKMSEBS, !Ref EC2EBSKMSArn, !Ref AWS::NoValue]
- !Ref AWS::NoValue
Roles:
- !If [sidecarCustomHostRoleEmpty, !Ref SidecarHostRole, !Ref SidecarCustomHostRole]
SidecarLaunchTemplate:
Type: AWS::EC2::LaunchTemplate
Properties:
LaunchTemplateName: !Sub '${AWS::StackName}-LT'
LaunchTemplateData:
KeyName: !If [hasSSHKeyName, !Ref SSHKeyName, !Ref AWS::NoValue]
IamInstanceProfile:
Name: !Ref SidecarHostProfile
ImageId: !Ref AmiId
InstanceType: !Ref SidecarInstanceType
BlockDeviceMappings:
- DeviceName: /dev/xvda
Ebs:
VolumeSize: !Ref SidecarVolumeSize
VolumeType: gp2
DeleteOnTermination: true
KmsKeyId: !If [useKMSEBS, !Ref EC2EBSKMSArn, !Ref AWS::NoValue]
Encrypted: true
NetworkInterfaces:
- DeviceIndex: 0
AssociatePublicIpAddress: !Ref AssociatePublicIpAddress
Groups:
- !Ref SidecarSecurityGroup
MetadataOptions:
# This is needed because clients of AWS services run within
# containers on EC2 instance. See https://github.com/aws/aws-sdk-go/issues/2972
# for a detailed explanation.
HttpPutResponseHopLimit: 1
HttpTokens: !Ref MetadataHttpTokensOption
UserData:
Fn::Base64: !Sub
- |
#!/bin/bash -e
${functions}
${CustomUserDataPre}
${pre}
${CustomUserDataPreSidecarStart}
${post}
${CustomUserDataPost}
/opt/aws/bin/cfn-signal -e $? --stack ${AWS::StackName} --resource AutoScalingGroupSidecar --region ${AWS::Region}
- functions:
!Sub
- |
# Defining functions
function package_install(){
echo "Updating and installing packages..."
yum update -y
yum install -y aws-cfn-bootstrap wget ec2-instance-connect docker jq
}
function docker_compose_install(){
# Compose Setup
sudo mkdir -p /usr/local/lib/docker/cli-plugins/
sudo ${curl} -SsfL https://github.com/docker/compose/releases/latest/download/docker-compose-linux-x86_64 -o /usr/local/lib/docker/cli-plugins/docker-compose
sudo chmod +x /usr/local/lib/docker/cli-plugins/docker-compose
}
function docker_setup(){
echo "Configuring Docker..."
sudo usermod -a -G docker ec2-user
# Configure fd limit for ec2 instance and containers
sudo bash -c 'cat > /etc/security/limits.d/fdlimit.conf' << EOF
* soft nofile 65535
* hard nofile 65535
EOF
sudo bash -c 'cat > /etc/sysconfig/docker' << EOF
DAEMON_MAXFILES=65535
OPTIONS="--default-ulimit nofile=65535:65535"
DAEMON_PIDFILE_TIMEOUT=10
EOF
sudo systemctl enable docker
sudo systemctl restart docker
}
function retry() {
RETRIES=15
while [ $RETRIES -gt 0 ]; do
set +e
$@
RESULT=$?
set -e
if [ $RESULT -eq 0 ]; then
echo "Success"
return 0
fi
echo "Failed"
sleep 5
let RETRIES-=1
done
echo "Retries exceeded"
exit 3
}
function extract_key_from_json_input() {
# Both key and tls.key are valid JSON keys for private keys.
# Values can be PEM strings or base64-encoded PEM strings.
jq -r '
(if has("key") then .key else ."tls.key" end) as $key |
if ($key | startswith("-----BEGIN")) then $key else ($key | gsub("\\s+"; "") | @base64d) end
'
}
function extract_cert_from_json_input() {
# Both cert and tls.crt are valid JSON keys for certificates.
# Values can be PEM strings or base64-encoded PEM strings.
jq -r '
(if has("cert") then .cert else ."tls.crt" end) as $cert |
if ($cert | startswith("-----BEGIN")) then $cert else ($cert | gsub("\\s+"; "") | @base64d) end
'
}
function get_secret_value() {
secret_arn="$1"
role_arn="$2"
[ -z "$secret_arn" ] && return
(
if [ -n "$role_arn" ]; then
assume_role_result="$(aws sts assume-role --role-arn $role_arn --role-session-name cyral-sidecar)"
export AWS_ACCESS_KEY_ID=$(echo "$assume_role_result" | jq -r .Credentials.AccessKeyId)
export AWS_SECRET_ACCESS_KEY=$(echo "$assume_role_result" | jq -r .Credentials.SecretAccessKey)
export AWS_SESSION_TOKEN=$(echo "$assume_role_result" | jq -r .Credentials.SessionToken)
fi
aws --region ${AWS::Region} secretsmanager get-secret-value --secret-id $secret_arn --query SecretString --output text
)
}
function get_secret(){
echo "Fetching Secret..."
if ! secret=$(aws secretsmanager get-secret-value --secret-id "${secrets_location}" --query SecretString --output text --region "${AWS::Region}" 2>&1); then
echo "Unable to fetch secret ${secrets_location}"
echo "Error: $secret"
exit 1
fi
SIDECAR_CLIENT_ID=$(echo "$secret" | jq -r .clientId)
SIDECAR_CLIENT_SECRET=$(echo "$secret" | jq -r .clientSecret)
}
function load_certs() {
echo "Loading certificates..."
local sidecar_tls_cert_secret_value sidecar_ca_cert_secret_value
sidecar_tls_cert_secret_value=$(
get_secret_value "${sidecar_tls_certificate_secret_arn}" "${SidecarTLSCertificateRoleArn}"
)
sidecar_ca_cert_secret_value=$(
get_secret_value "${sidecar_ca_certificate_secret_arn}" "${SidecarCACertificateRoleArn}"
)
SIDECAR_TLS_KEY=$(echo "$sidecar_tls_cert_secret_value" | extract_key_from_json_input | base64 -w 0)
SIDECAR_TLS_CERT=$(echo "$sidecar_tls_cert_secret_value" | extract_cert_from_json_input | base64 -w 0)
SIDECAR_CA_KEY=$(echo "$sidecar_ca_cert_secret_value" | extract_key_from_json_input | base64 -w 0)
SIDECAR_CA_CERT=$(echo "$sidecar_ca_cert_secret_value" | extract_cert_from_json_input | base64 -w 0)
}
function load_idp_certs() {
echo "Loading IDP certificates..."
SIDECAR_IDP_PUBLIC_CERT="$(echo "$secret" | jq -r .sidecarPublicIdpCertificate)"
SIDECAR_IDP_PRIVATE_KEY="$(echo "$secret" | jq -r .sidecarPrivateIdpKey)"
}
function fetch_hostname() {
echo "Fetching public hostname..."
INSTANCE_ID=$(${curl} -sf -H "X-aws-ec2-metadata-token: $( \
${curl} -sf -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600" \
)" http://169.254.169.254/latest/meta-data/instance-id || echo "$HOSTNAME")
echo "Setting INSTANCE_ID to '$INSTANCE_ID'"
}
function update_nginx_resolver(){
export NGINX_RESOLVER=$(cat /etc/resolv.conf | grep nameserver | awk '{print $2}')
echo "Setting NGINX_RESOLVER to '$NGINX_RESOLVER'..."
}
function get_token () {
echo "Getting Control Plane Token using port $1..."
local url_token="https://${ControlPlane}:$1/v1/users/oidc/token"
token=$(${curl} --no-progress-meter --fail-with-body --request POST "$url_token" -d grant_type=client_credentials -d client_id="$SIDECAR_CLIENT_ID" -d client_secret="$SIDECAR_CLIENT_SECRET" 2>&1)
token_error=$(echo $?)
}
function get_sidecar_version () {
echo "Getting sidecar version from Control Plane..."
get_token "443"
if [[ $token_error -ne 0 ]]; then
error_443="$token"
get_token "8000"
if [[ $token_error -ne 0 ]]; then
echo "Unable to retrieve token!!"
echo "Attempt on 443: $error_443"
echo "Attempt on 8000: $token"
return 1
fi
fi
local access_token=$(echo "$token" | jq -r .access_token)
local resp=$(${curl} --no-progress-meter --fail-with-body --request GET "https://${ControlPlane}/v2/sidecars/${SidecarId}" -H "Authorization: Bearer $access_token")
if [[ $? -ne 0 ]]; then
echo "Error retrieving sidecar version from Control Plane."
return 1
fi
SIDECAR_VERSION=$(echo "$resp" | jq -r '.sidecar.version // empty')
}
function download_sidecar () {
local access_token url
echo "Downloading Sidecar Compose File..."
get_token "443"
if [[ $token_error -ne 0 ]]; then
error_443="$token"
get_token "8000"
if [[ $token_error -ne 0 ]]; then
echo "Unable to retrieve token!!"
echo "Attempt on 443: $error_443"
echo "Attempt on 8000: $token"
return 1
fi
fi
access_token=$(echo "$token" | jq -r .access_token)
url="https://${ControlPlane}/deploy/docker-compose?TemplateVersion=$SIDECAR_VERSION"
echo "Trying to download the sidecar template from: $url"
if ! ${curl} -fsS --no-progress-meter -o /home/ec2-user/sidecar.compose.yaml -L "$url" -H "Authorization: Bearer $access_token" ; then
echo "Unable to download compose file for version $SIDECAR_VERSION, please make sure all parameters are correct"
return 1
fi
return 0
}
function registry_login () {
echo "Container Registry Login..."
local key=$(echo "$secret" | jq -r 'select(.containerRegistryKey != null) | .containerRegistryKey' | base64 --decode)
if [[ ${ContainerRegistry} == *"aws"* ]]; then
echo "(login): Logging in to AWS ECR..."
eval $(aws ecr --no-include-email get-login --region ${AWS::Region})
elif [ -n "$key" ]; then
echo "(login): Logging in to GCR..."
echo "$key" | docker login -u ${ContainerRegistryUsername} --password-stdin https://gcr.io
else
echo "(login): Won't log in automatically to any image registry. Image registry set to: ${ContainerRegistry}"
fi
}
# Checks if the specified Docker container is running without restarts within 5 seconds
function containerCheck () {
CONTAINER_NAME="$1"
WAIT_TIME=0
EXPECTED_WAIT_TIME=5
until [ $WAIT_TIME -eq $EXPECTED_WAIT_TIME ] || [ "$(eval docker inspect "$CONTAINER_NAME" | jq -r -e '.[].RestartCount')" -ne 0 ]; do
printf "."
(( WAIT_TIME++ ))
sleep 1
done
echo ""
[ "$WAIT_TIME" -eq $EXPECTED_WAIT_TIME ]
}
function launch () {
echo "Starting sidecar..."
cd /home/ec2-user
if [[ ${UseSingleContainer} == "true" ]]; then
SINGLE_CONTAINER_IMAGE=${ContainerRegistry}/cyral-sidecar:$SIDECAR_VERSION
retry docker pull -q $SINGLE_CONTAINER_IMAGE
retry docker run -d --name sidecar --network=host --log-driver=local --log-opt max-size=500m --restart=unless-stopped --env-file .env $SINGLE_CONTAINER_IMAGE
if ! containerCheck "sidecar"; then
echo "--> Problem with sidecar! Inspect the logs to diagnose the issue. <--"
fi
else
retry docker compose -f sidecar.compose.yaml pull -q
retry docker compose -f sidecar.compose.yaml up -d
fi
}
- sidecar_tls_certificate_secret_arn: !If
- sidecarTLSCertificateSecretArnEmpty
- !Ref SidecarCreatedCertificateSecret
- !Ref SidecarTLSCertificateSecretArn
sidecar_ca_certificate_secret_arn: !If
- sidecarCACertificateSecretArnEmpty
- !Ref SidecarCACertificateSecret
- !Ref SidecarCACertificateSecretArn
curl:
Fn::If:
- shouldSkipTls
- "curl -k"
- "curl"
secrets_location: !If [hasSecretsLocation, !Ref SecretsLocation, !Sub '/cyral/sidecars/${SidecarId}/secrets']
pre:
!Sub
- |
mkdir -p /home/ec2-user/cyral/
package_install
get_secret
fetch_hostname
# Get the latest sidecar version from the Control Plane if necessary.
IS_DYNAMIC_VERSION="false"
SIDECAR_VERSION=${SidecarVersion}
if [ -z $SIDECAR_VERSION ]; then
echo "Sidecar version is unset - version will be dynamically managed."
IS_DYNAMIC_VERSION="true"
get_sidecar_version
if [ $? -ne 0 ]; then
echo "Error getting sidecar version from Control Plane. Dynamic version support is only enabled for Control Planes >= v4.10"