-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathEksCreationEngine.py
1755 lines (1559 loc) · 77.2 KB
/
EksCreationEngine.py
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
#This file is part of Lightspin EKS Creation Engine.
#SPDX-License-Identifier: Apache-2.0
#Licensed to the Apache Software Foundation (ASF) under one
#or more contributor license agreements. See the NOTICE file
#distributed with this work for additional information
#regarding copyright ownership. The ASF licenses this file
#to you 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.
import base64
import sys
import boto3
import botocore.exceptions
import json
from datetime import datetime
import time
import subprocess
import re
from plugins.ECEDatadog import DatadogSetup
from plugins.ECEFalco import FalcoSetup
cache = list()
class ClusterManager():
def get_latest_eks_optimized_ubuntu(kubernetes_version, ami_id, ami_os, ami_architecture):
'''
This function either receives an AMI ID from main.py or receives the default value of 'SSM' which is matched against the arguments
`ami_os` and `ami_architecture` to dynamically pull the latest, stable AMI from SSM Public Parameters.
'''
ssm = boto3.client('ssm')
if ami_id == 'SSM':
# Ubuntu 20.04 LTS
if ami_os == 'ubuntu':
# AMD64
if ami_architecture == 'amd64':
# /aws/service/canonical/ubuntu/eks/20.04/1.21/stable/current/amd64/hvm/ebs-gp2/ami-id
publicParameter = str(f'/aws/service/canonical/{ami_os}/eks/20.04/{kubernetes_version}/stable/current/{ami_architecture}/hvm/ebs-gp2/ami-id')
# ARM64
else:
# /aws/service/canonical/ubuntu/eks/20.04/1.21/stable/current/arm64/hvm/ebs-gp2/ami-id
publicParameter = str(f'/aws/service/canonical/{ami_os}/eks/20.04/{kubernetes_version}/stable/current/{ami_architecture}/hvm/ebs-gp2/ami-id')
# Amazon Linux 2
# Public Params search in the console is fucky, check here: https://docs.aws.amazon.com/eks/latest/userguide/eks-optimized-ami.html
else:
# AMD64
if ami_architecture == 'amd64':
# /aws/service/eks/optimized-ami/1.21/amazon-linux-2/recommended/image_id
publicParameter = str(f'/aws/service/eks/optimized-ami/{kubernetes_version}/amazon-linux-2/recommended/image_id')
# ARM64
else:
# /aws/service/eks/optimized-ami/1.21/amazon-linux-2-arm64/recommended/image_id
publicParameter = str(f'/aws/service/eks/optimized-ami/{kubernetes_version}/amazon-linux-2-arm64/recommended/image_id')
# retrieve the AMI ID and return it
try:
amiId = ssm.get_parameter(Name=publicParameter)['Parameter']['Value']
except Exception as e:
print('Some AMIs are not stored as SSM Public Parameters despite being available from the maintainer, check the maintainer EKS documentation.')
raise e
else:
amiId = ami_id
del ami_os
del ami_architecture
del ssm
del publicParameter
print(f'Your EKS Nodegroup AMI is {amiId}')
return amiId
def create_cluster_svc_role(cluster_role_name):
'''
This function creates a Cluster Service Role for EKS, required for Cluster Creation
'''
iam = boto3.client('iam')
sts = boto3.client('sts')
acctId = sts.get_caller_identity()['Account']
# Use STS GetCallerIdentity and Datetime to generate CreatedBy and CreatedAt information for tagging
createdBy = str(sts.get_caller_identity()['Arn'])
createdAt = str(datetime.utcnow())
# Trust Policy for EKS
trustPolicy = {
'Version': '2012-10-17',
'Statement': [
{
'Effect': 'Allow',
'Principal': {
'Service': 'eks.amazonaws.com'
},
'Action': 'sts:AssumeRole'
}
]
}
try:
r = iam.create_role(
Path='/',
RoleName=cluster_role_name,
AssumeRolePolicyDocument=json.dumps(trustPolicy),
Description='Allows access to other AWS service resources that are required to operate clusters managed by EKS',
MaxSessionDuration=3600,
Tags=[
{
'Key': 'Name',
'Value': cluster_role_name
},
{
'Key': 'CreatedBy',
'Value': createdBy
},
{
'Key': 'CreatedAt',
'Value': createdAt
},
{
'Key': 'CreatedWith',
'Value': 'Lightspin ECE'
}
]
)
# Attach required Cluster Policy (AWS Managed) or get following error
# botocore.errorfactory.InvalidParameterException: An error occurred (InvalidParameterException) when calling the CreateCluster operation: The provided role doesn't have the Amazon EKS Managed Policies associated with it. Please ensure the following policies [arn:aws:iam::aws:policy/AmazonEKSClusterPolicy] are attached
waiter = iam.get_waiter('role_exists')
waiter.wait(
RoleName=cluster_role_name,
WaiterConfig={
'Delay': 3,
'MaxAttempts': 20
}
)
iam.attach_role_policy(
RoleName=cluster_role_name,
PolicyArn='arn:aws:iam::aws:policy/AmazonEKSClusterPolicy'
)
roleArn = str(r['Role']['Arn'])
except botocore.exceptions.ClientError as error:
# If we have an 'EntityAlreadyExists' error it means a Role of the same name exists, we can try to use it instead
if error.response['Error']['Code'] == 'EntityAlreadyExists':
print(f'The supplied role name of {cluster_role_name} already exists, attempting to use it')
roleArn = f'arn:aws:iam::{acctId}:role/{cluster_role_name}'
else:
print(f'Error encountered: {error}')
RollbackManager.rollback_from_cache(cache=cache)
except botocore.exceptions.WaiterError as we:
print(f'Error encountered: {we}')
RollbackManager.rollback_from_cache(cache=cache)
del iam
del sts
del acctId
del trustPolicy
print(f'Your cluster role ARN is {roleArn}')
return roleArn
def create_managed_nodegroup_s3_policy(bucket_name, nodegroup_role_name):
'''
Creates an IAM Policy that allows S3 GetObject permissions for use in the Nodegroup Role
'''
iam = boto3.client('iam')
sts = boto3.client('sts')
acctId = sts.get_caller_identity()['Account']
# Use STS GetCallerIdentity and Datetime to generate CreatedBy and CreatedAt information for tagging
createdBy = str(sts.get_caller_identity()['Arn'])
createdAt = str(datetime.utcnow())
policyName = f'{nodegroup_role_name}Policy'
iamPolicyDoc = {
'Version': '2012-10-17',
'Statement': [
{
'Sid': 'GetObjectSid',
'Effect': 'Allow',
'Action': [
's3:GetObjectAcl',
's3:GetObject',
's3:GetBucketAcl',
's3:GetBucketLocation'
],
'Resource': [
f'arn:aws:s3:::{bucket_name}/*',
f'arn:aws:s3:::{bucket_name}'
]
}
]
}
try:
r = iam.create_policy(
PolicyName=policyName,
Path='/',
PolicyDocument=json.dumps(iamPolicyDoc),
Description='Allows access to specific S3 buckets for node groups managed by EKS - Created by Lightspin ECE',
Tags=[
{
'Key': 'Name',
'Value': policyName
},
{
'Key': 'CreatedBy',
'Value': createdBy
},
{
'Key': 'CreatedAt',
'Value': createdAt
},
{
'Key': 'CreatedWith',
'Value': 'Lightspin ECE'
}
]
)
policyArn = str(r['Policy']['Arn'])
except botocore.exceptions.ClientError as error:
# If we have an 'EntityAlreadyExists' error it means a Role of the same name exists, we can try to use it instead
# we will assume it has the right permissions after all
if error.response['Error']['Code'] == 'EntityAlreadyExists':
print(f'The supplied role policy name of {policyName} already exists, attempting to use it')
policyArn = f'arn:aws:iam::{acctId}:policy/{policyName}'
else:
print(f'Error encountered: {error}')
RollbackManager.rollback_from_cache(cache=cache)
del iam
del sts
del acctId
del iamPolicyDoc
del policyName
print(f'Your node group role policy ARN is {policyArn}')
return policyArn
def create_managed_nodegroup_role(bucket_name, nodegroup_role_name, mde_on_nodes):
'''
This function creates a Nodegroup Service Role for EKS, which gives Nodes permissions to interact with AWS APIs.
This function calls the `create_managed_nodegroup_s3_policy` function and passes the S3 Bucket name specified in
main.py to allow your Nodegroup Role to communicate with the S3 bucket for bootstrapping purposes
'''
iam = boto3.client('iam')
sts = boto3.client('sts')
acctId = sts.get_caller_identity()['Account']
roleName = nodegroup_role_name
# Use STS GetCallerIdentity and Datetime to generate CreatedBy and CreatedAt information for tagging
createdBy = str(sts.get_caller_identity()['Arn'])
createdAt = str(datetime.utcnow())
# Static list of required AWS Managed Policies for EKS Managed Nodegroup Roles
# Adding SSM for SSM access as SSH Keypairs are not specified
nodegroupAwsManagedPolicies = [
'arn:aws:iam::aws:policy/AmazonEKSWorkerNodePolicy',
'arn:aws:iam::aws:policy/AmazonEC2ContainerRegistryReadOnly',
'arn:aws:iam::aws:policy/AmazonEKS_CNI_Policy',
'arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore'
]
# Grab S3 Node Group policy from other Function & add to List if MDE is enabled
if mde_on_nodes == 'True':
s3PolicyArn = ClusterManager.create_managed_nodegroup_s3_policy(bucket_name, nodegroup_role_name)
nodegroupAwsManagedPolicies.append(s3PolicyArn)
# Trust Policy for EKS NodeGroup Role trusts EC2
trustPolicy = {
'Version': '2012-10-17',
'Statement': [
{
'Effect': 'Allow',
'Principal': {
'Service': 'ec2.amazonaws.com'
},
'Action': 'sts:AssumeRole'
}
]
}
try:
r = iam.create_role(
Path='/',
RoleName=roleName,
AssumeRolePolicyDocument=json.dumps(trustPolicy),
Description='Allows access to other AWS service resources that are required to operate node groups managed by EKS',
MaxSessionDuration=3600,
Tags=[
{
'Key': 'Name',
'Value': roleName
},
{
'Key': 'CreatedBy',
'Value': createdBy
},
{
'Key': 'CreatedAt',
'Value': createdAt
},
{
'Key': 'CreatedWith',
'Value': 'Lightspin ECE'
}
]
)
roleArn = str(r['Role']['Arn'])
waiter = iam.get_waiter('role_exists')
waiter.wait(
RoleName=roleName,
WaiterConfig={
'Delay': 3,
'MaxAttempts': 20
}
)
except botocore.exceptions.ClientError as error:
# If we have an 'EntityAlreadyExists' error it means a Role of the same name exists, we can try to use it instead
# we will assume it has the right permissions after all
if error.response['Error']['Code'] == 'EntityAlreadyExists':
print(f'The supplied role name of {roleName} already exists, attempting to use it')
roleArn = f'arn:aws:iam::{acctId}:role/{roleName}'
else:
print(f'Error encountered: {error}')
RollbackManager.rollback_from_cache(cache=cache)
except botocore.exceptions.WaiterError as we:
print(f'Error encountered: {we}')
RollbackManager.rollback_from_cache(cache=cache)
# Loop through List of policies and attach Policies to Role, handle errors if already attached
try:
for policy in nodegroupAwsManagedPolicies:
iam.attach_role_policy(
RoleName=roleName,
PolicyArn=policy
)
except Exception as e:
print(f'Error encountered: {e}')
RollbackManager.rollback_from_cache(cache=cache)
del iam
del sts
del acctId
del trustPolicy
del roleName
print(f'Your node group role ARN is {roleArn}')
return roleArn
def cluster_security_group_factory(cluster_name, vpc_id, additional_ports):
'''
This function creates a minimum necessary Security Group for your EKS Cluster based on AWS reccomendations
https://docs.aws.amazon.com/eks/latest/userguide/sec-group-reqs.html this will also add permissions to ports
TCP 2801 and TCP 8765 for FalcoSidekick and Falco Security, respectively, for At-Create or later configuration
of Falco in a Cluster which provides real-time protection and event forwarding
'''
ec2 = boto3.client('ec2')
sts = boto3.client('sts')
print(f'Setting up a Security Group for VPC {vpc_id} for EKS Cluster {cluster_name}')
# Use STS GetCallerIdentity and Datetime to generate CreatedBy and CreatedAt information for tagging
createdBy = str(sts.get_caller_identity()['Arn'])
createdAt = str(datetime.utcnow())
# Generate SG Name, passed to the create_security_group() method, and used for general messaging
sgName = str(f'{cluster_name}ClusterSG')
# Load constants of ports needed reccomended by AWS and needed by Falco/Falco Sidekick
defaultPortSet = [53, 443, 2801, 8765, 10250]
# if extra ports have been provided via main.py, merge the lists and check for duplicates
if additional_ports:
for p in additional_ports:
if int(p) not in defaultPortSet:
defaultPortSet.append(int(p))
# remove the list, it's not needed anymore
del additional_ports
# Create an empty list to store all IPv4 CIDRs as VPCs may have additional IPV4 CIDRs associated
allVpcCidrs = []
# Get CIDR information on the VPC
try:
r = ec2.describe_vpcs(VpcIds=[vpc_id])['Vpcs'][0]
vpcMainCidr = str(r['CidrBlock'])
allVpcCidrs.append(vpcMainCidr)
# Loop additional CIDRs if they exist and are associated
for cidr in r['CidrBlockAssociationSet']:
if str(cidr['CidrBlockState']['State']) == 'associated':
if str(cidr['CidrBlock']) not in allVpcCidrs:
allVpcCidrs.append(str(cidr['CidrBlock']))
except KeyError as ke:
print(f'Error encountered: {ke}')
RollbackManager.rollback_from_cache(cache=cache)
except botocore.exceptions.ClientError as error:
print(f'Error encountered: {error}')
RollbackManager.rollback_from_cache(cache=cache)
# All CIDRs collected and ports consolidated, Security Group creation starts now
try:
r = ec2.create_security_group(
Description=f'Security Group for EKS Cluster {cluster_name} - Created by {createdBy} using Lightspin ECE',
GroupName=sgName,
VpcId=vpc_id,
TagSpecifications=[
{
'ResourceType': 'security-group',
'Tags': [
{
'Key': 'Name',
'Value': sgName
},
{
'Key': 'CreatedBy',
'Value': createdBy
},
{
'Key': 'CreatedAt',
'Value': createdAt
},
{
'Key': 'CreatedWith',
'Value': 'Lightspin ECE'
},
# This tag is required per AWS Docs
# One, and only one, of the security groups associated to your nodes should have the following tag applied: For more information about tagging, see Working with tags using the console. kubernetes.io/cluster/cluster-name: owned
{
'Key': f'kubernetes.io/cluster/{cluster_name}',
'Value': 'owned'
}
]
}
]
)
secGroupId = str(r['GroupId'])
sgCache = {
'ClusterSecurityGroupId': secGroupId
}
cache.append(sgCache)
print(f'Added {sgName} ID {secGroupId} to Cache')
print(f'Authorizing ingress for Ports {defaultPortSet} for CIDRS {allVpcCidrs} for {sgName}')
# Now start adding Inbound Rules per CIDR and per Port
# Add conditional logic for port 53 (DNS) to create both TCP and UDP Rules
for cidr in allVpcCidrs:
for port in defaultPortSet:
if port == 53:
ec2.authorize_security_group_ingress(
GroupId=secGroupId,
IpPermissions=[
{
'FromPort': int(port),
'ToPort': int(port),
'IpProtocol': 'tcp',
'IpRanges': [
{
'CidrIp': cidr,
'Description': f'Allow tcp {port} to {cidr}'
}
]
},
{
'FromPort': int(port),
'ToPort': int(port),
'IpProtocol': 'udp',
'IpRanges': [
{
'CidrIp': cidr,
'Description': f'Allow udp {port} to {cidr}'
}
]
}
],
TagSpecifications=[
{
'ResourceType': 'security-group-rule',
'Tags': [
{
'Key': 'Name',
'Value': f'{sgName}{cidr}{port}'
},
{
'Key': 'CreatedBy',
'Value': createdBy
},
{
'Key': 'CreatedAt',
'Value': createdAt
},
{
'Key': 'CreatedWith',
'Value': 'Lightspin ECE'
}
]
}
]
)
else:
ec2.authorize_security_group_ingress(
GroupId=secGroupId,
IpPermissions=[
{
'FromPort': int(port),
'ToPort': int(port),
'IpProtocol': 'tcp',
'IpRanges': [
{
'CidrIp': cidr,
'Description': f'Allow tcp {port} to {cidr}'
}
]
}
],
TagSpecifications=[
{
'ResourceType': 'security-group-rule',
'Tags': [
{
'Key': 'Name',
'Value': f'{sgName}{cidr}{port}'
},
{
'Key': 'CreatedBy',
'Value': createdBy
},
{
'Key': 'CreatedAt',
'Value': createdAt
},
{
'Key': 'CreatedWith',
'Value': 'Lightspin ECE'
}
]
}
]
)
# Adding inbound rules per Port for the Security Group itself (talk to self for Node-Cluster Comms)
for port in defaultPortSet:
if port == 53:
ec2.authorize_security_group_ingress(
GroupId=secGroupId,
IpPermissions=[
{
'FromPort': int(port),
'ToPort': int(port),
'IpProtocol': 'tcp',
'UserIdGroupPairs': [
{
'Description': f'Allow tcp {port} to {secGroupId}',
'GroupId': secGroupId
}
]
},
{
'FromPort': int(port),
'ToPort': int(port),
'IpProtocol': 'udp',
'UserIdGroupPairs': [
{
'Description': f'Allow udp {port} to {secGroupId}',
'GroupId': secGroupId
}
]
}
],
TagSpecifications=[
{
'ResourceType': 'security-group-rule',
'Tags': [
{
'Key': 'Name',
'Value': f'{sgName}{secGroupId}{port}'
},
{
'Key': 'CreatedBy',
'Value': createdBy
},
{
'Key': 'CreatedAt',
'Value': createdAt
},
{
'Key': 'CreatedWith',
'Value': 'Lightspin ECE'
}
]
}
]
)
else:
ec2.authorize_security_group_ingress(
GroupId=secGroupId,
IpPermissions=[
{
'FromPort': int(port),
'ToPort': int(port),
'IpProtocol': 'tcp',
'UserIdGroupPairs': [
{
'Description': f'Allow tcp {port} to {secGroupId}',
'GroupId': secGroupId
}
]
}
],
TagSpecifications=[
{
'ResourceType': 'security-group-rule',
'Tags': [
{
'Key': 'Name',
'Value': f'{sgName}{secGroupId}{port}'
},
{
'Key': 'CreatedBy',
'Value': createdBy
},
{
'Key': 'CreatedAt',
'Value': createdAt
},
{
'Key': 'CreatedWith',
'Value': 'Lightspin ECE'
}
]
}
]
)
# Adding TCP 443 (HTTPS) from the internet which is required for patching and agent communications
ec2.authorize_security_group_ingress(
GroupId=secGroupId,
IpPermissions=[
{
'FromPort': 443,
'ToPort': 443,
'IpProtocol': 'tcp',
'IpRanges': [
{
'CidrIp': '0.0.0.0/0',
'Description': f'Allow tcp 443 to Internet'
}
]
}
],
TagSpecifications=[
{
'ResourceType': 'security-group-rule',
'Tags': [
{
'Key': 'Name',
'Value': f'{sgName}Internet{port}'
},
{
'Key': 'CreatedBy',
'Value': createdBy
},
{
'Key': 'CreatedAt',
'Value': createdAt
},
{
'Key': 'CreatedWith',
'Value': 'Lightspin ECE'
}
]
}
]
)
except botocore.exceptions.ClientError as error:
print(f'Error encountered: {error}')
RollbackManager.rollback_from_cache(cache=cache)
print(f'Finished creating {sgName} and adding all required Rule Authorizations')
return secGroupId
def encryption_key_factory(cluster_name):
'''
This function is responsible for creating a KMS Key to use with EKS Secrets Envelope Encryption as well as Nodegroup (EC2) EBS Encryption
we will attach a proper Key Policy later
'''
kms = boto3.client('kms')
sts = boto3.client('sts')
# Use STS GetCallerIdentity and Datetime to generate CreatedBy and CreatedAt information for tagging
# STS is also used for the Account ID to interpolate ARNs which will be created later
createdBy = str(sts.get_caller_identity()['Arn'])
createdAt = str(datetime.utcnow())
print(f'Creating KMS CMK for encryption operations')
# The first time we create the Key we must not attach a policy as the Roles we need to give permission to do not exist yet (nodegroup & cluster IAM role)
# it will attach a default policy that allows our entire AWS Account access - this is good so we can override it later
try:
kmsKeyArn = kms.create_key(
Description=f'Used for EKS Envelope Encryption and EBS Volume Encryption for EKS Cluster {cluster_name} - Created by Lightspin ECE',
# Default values for AES-256/GCM Keys. Being verbose in case AWS ever changes the default values of these
KeyUsage='ENCRYPT_DECRYPT',
KeySpec='SYMMETRIC_DEFAULT',
Origin='AWS_KMS',
Tags=[
{
'TagKey': 'Name',
'TagValue': f'{cluster_name}-EKS-CMK'
},
{
'TagKey': 'CreatedBy',
'TagValue': createdBy
},
{
'TagKey': 'CreatedAt',
'TagValue': createdAt
},
{
'TagKey': 'CreatedWith',
'TagValue': 'Lightspin ECE'
}
]
)['KeyMetadata']['Arn']
except KeyError as ke:
print(f'Error encountered: {ke}')
RollbackManager.rollback_from_cache(cache=cache)
except botocore.exceptions.ParamValidationError as pe:
print(f'Error encountered: {pe}')
RollbackManager.rollback_from_cache(cache=cache)
except botocore.exceptions.ClientError as error:
print(f'Error encountered: {error}')
RollbackManager.rollback_from_cache(cache=cache)
return kmsKeyArn
def create_cluster(cluster_name, kubernetes_version, cluster_role_name, subnet_ids, vpc_id, additional_ports, logging_types):
'''
This function uses the EKS Boto3 Client to create a cluster, taking inputs from main.py to determing naming & Encryption
'''
eks = boto3.client('eks')
sts = boto3.client('sts')
# Use STS GetCallerIdentity and Datetime to generate CreatedBy and CreatedAt information for tagging
createdBy = str(sts.get_caller_identity()['Arn'])
createdAt = str(datetime.utcnow())
# Call `create_cluster_svc_role` to create or re-use the EKS cluster service IAM role
clusterRoleArn = ClusterManager.create_cluster_svc_role(cluster_role_name)
# Call `cluster_security_group_factory` to create or re-use an EKS cluster security group that allows minimum necessary comms intra-VPC
securityGroupId = ClusterManager.cluster_security_group_factory(cluster_name, vpc_id, additional_ports)
# Call `encryption_key_factory` to create a KMS Key ARN. Simple! (We'll add the Key Policy later)
kmsKeyArn = ClusterManager.encryption_key_factory(cluster_name)
try:
# Call to create cluster
r = eks.create_cluster(
name=cluster_name,
version=str(kubernetes_version),
roleArn=clusterRoleArn,
resourcesVpcConfig={
'subnetIds': subnet_ids,
'securityGroupIds': [securityGroupId],
'endpointPublicAccess': False,
'endpointPrivateAccess': True
},
logging={
'clusterLogging': [
{
# provide via --logging_types arg
'types': logging_types,
'enabled': True
}
]
},
encryptionConfig=[
{
'resources': [
'secrets'
],
'provider': {
'keyArn': kmsKeyArn
}
}
],
tags={
'Name': cluster_name,
'CreatedBy': createdBy,
'CreatedAt': createdAt,
'CreatedWith': 'Lightspin ECE'
}
)
# Establish provided EKS Waiter() for cluster to come up
# https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/eks.html#EKS.Waiter.ClusterActive
print(f'Waiting for your Cluster to come online')
waiter = eks.get_waiter('cluster_active')
waiter.wait(
name=cluster_name,
WaiterConfig={
'Delay': 30,
'MaxAttempts': 40
}
)
finalClusterName = str(r['cluster']['name'])
print(f'EKS Cluster {finalClusterName} is now live')
except botocore.exceptions.ClientError as error:
print(f'Error encountered: {error}')
RollbackManager.rollback_from_cache(cache=cache)
except botocore.exceptions.WaiterError as we:
print(f'Error encountered: {we}')
RollbackManager.rollback_from_cache(cache=cache)
del eks
del sts
del createdAt
del createdBy
del r
del waiter
return finalClusterName, securityGroupId, kmsKeyArn, clusterRoleArn
def generate_nodegroup_bootstrap(bucket_name, cluster_name, mde_on_nodes, ami_os):
'''
This function generates EC2 UserData (in Base64) to be passed to the `create_launch_template` Function for creating a custom
launch template that uses custom AMIs passed in main.py or defaults to the EKS-optimized AMI for Ubuntu 20.04LTS corresponding
to the K8s verson used. This function parses the S3 Bucket from main.py which stores the MDE activation scripts, if that is configured.
Additionally, required information is retrieved from the EKS Cluster to provide to the bootstrap script included by
default in EKS-optimized AMIs. In this case, we will need the CA and API Server URL
Details: https://aws.amazon.com/blogs/containers/introducing-launch-template-and-custom-ami-support-in-amazon-eks-managed-node-groups/
WTF is `set -ex`? https://askubuntu.com/questions/346900/what-does-set-e-do
'''
eks = boto3.client('eks')
print(f'Retrieving Certificate Authority and API Server URL information for bootstrap script')
# DescribeCluster and pull necessary values to set as env vars within the bootstrap
c = eks.describe_cluster(name=cluster_name)
eksApiServerUrl = str(c['cluster']['endpoint'])
eksB64ClusterCa = str(c['cluster']['certificateAuthority']['data'])
# Support for IMDSv2 Tokens for reaching metadata service
# https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instancedata-data-retrieval.html#instance-metadata-ex-7
# MDE Installation Scripts: https://docs.microsoft.com/en-us/microsoft-365/security/defender-endpoint/linux-install-manually?view=o365-worldwide
if mde_on_nodes == 'True':
# Ubuntu
if ami_os == 'ubuntu':
script = f'''#!/bin/bash
set -ex
B64_CLUSTER_CA={eksB64ClusterCa}
API_SERVER_URL={eksApiServerUrl}
/etc/eks/bootstrap.sh {cluster_name} --b64-cluster-ca $B64_CLUSTER_CA --apiserver-endpoint $API_SERVER_URL
apt update
apt upgrade -y
apt install -y curl python3 python3-pip libplist-utils gpg apt-transport-https zip unzip
curl -o microsoft.list https://packages.microsoft.com/config/ubuntu/20.04/prod.list
mv ./microsoft.list /etc/apt/sources.list.d/microsoft-prod.list
curl https://packages.microsoft.com/keys/microsoft.asc | apt-key add -
apt update
apt install -y mdatp
aws s3 cp s3://{bucket_name}/mdatp/WindowsDefenderATPOnboardingPackage.zip .
unzip WindowsDefenderATPOnboardingPackage.zip
python3 MicrosoftDefenderATPOnboardingLinuxServer.py
mdatp threat policy set --type potentially_unwanted_application --action block
mdatp config network-protection enforcement-level --value block
mdatp config real-time-protection --value enabled
TOKEN=$(curl -X PUT 'http://169.254.169.254/latest/api/token' -H 'X-aws-ec2-metadata-token-ttl-seconds: 21600')
INSTANCE_ID=$(curl -H 'X-aws-ec2-metadata-token: $TOKEN' -v http://169.254.169.254/latest/meta-data/instance-id)
mdatp edr tag set --name GROUP --value $INSTANCE_ID
'''
# Amazon Linux 2
else:
script = f'''#!/bin/bash
set -ex
B64_CLUSTER_CA={eksB64ClusterCa}
API_SERVER_URL={eksApiServerUrl}
/etc/eks/bootstrap.sh {cluster_name} --b64-cluster-ca $B64_CLUSTER_CA --apiserver-endpoint $API_SERVER_URL
yum update -y
yum-config-manager --add-repo=https://packages.microsoft.com/config/rhel/7/prod.repo
rpm --import http://packages.microsoft.com/keys/microsoft.asc
yum install mdatp -y
aws s3 cp s3://{bucket_name}/mdatp/WindowsDefenderATPOnboardingPackage.zip .
unzip WindowsDefenderATPOnboardingPackage.zip
python3 MicrosoftDefenderATPOnboardingLinuxServer.py
mdatp threat policy set --type potentially_unwanted_application --action block
mdatp config network-protection enforcement-level --value block
mdatp config real-time-protection --value enabled
TOKEN=$(curl -X PUT 'http://169.254.169.254/latest/api/token' -H 'X-aws-ec2-metadata-token-ttl-seconds: 21600')
INSTANCE_ID=$(curl -H 'X-aws-ec2-metadata-token: $TOKEN' -v http://169.254.169.254/latest/meta-data/instance-id)
mdatp edr tag set --name GROUP --value $INSTANCE_ID
'''
else:
# No need for MDE in this one, create a regular script
# Ubuntu
if ami_os == 'ubuntu':
script = f'''#!/bin/bash
set -ex
B64_CLUSTER_CA={eksB64ClusterCa}
API_SERVER_URL={eksApiServerUrl}
/etc/eks/bootstrap.sh {cluster_name} --b64-cluster-ca $B64_CLUSTER_CA --apiserver-endpoint $API_SERVER_URL
apt update
apt upgrade -y
'''
# Amazon Linux 2
else:
script = f'''#!/bin/bash
set -ex
B64_CLUSTER_CA={eksB64ClusterCa}
API_SERVER_URL={eksApiServerUrl}
/etc/eks/bootstrap.sh {cluster_name} --b64-cluster-ca $B64_CLUSTER_CA --apiserver-endpoint $API_SERVER_URL
yum update -y
'''
# Base64 encode the bootstrap script
userData = base64.b64encode(script.encode()).decode('ascii')
del eks
del c
del eksB64ClusterCa
del eksApiServerUrl
return userData
def create_launch_template(cluster_name, kubernetes_version, ami_id, bucket_name, launch_template_name, kms_key_arn, securityGroupId, ebs_volume_size, instance_type, mde_on_nodes, ami_os, ami_architecture):
'''
This function creates an EC2 Launch Template using encryption and AMI data supplied from main.py and passes it to the `builder` function
where final EKS Nodegroup creation takes place
'''
# This is for creating the Launch Template used by EKS to launch Managed Node Groups with a custom AMI & bootstrap script
ec2 = boto3.client('ec2')
sts = boto3.client('sts')
# Use STS GetCallerIdentity and Datetime to generate CreatedBy and CreatedAt information for tagging
createdBy = str(sts.get_caller_identity()['Arn'])
createdAt = str(datetime.utcnow())
# Pull latest AMI ID for EKS-optimized Ubuntu 20.04LTS for specified K8s Version in main.py
amiId = ClusterManager.get_latest_eks_optimized_ubuntu(kubernetes_version, ami_id, ami_os, ami_architecture)
# Retrieve Base64 metadata from bootstrap generation function - this will download and install MDE (MDATP) from files in the S3 bucket specified in main.py if --mde_on_nodes is true. Will use ami_os arguements to create different UserData as well
userData = ClusterManager.generate_nodegroup_bootstrap(bucket_name, cluster_name, mde_on_nodes, ami_os)
# For IMDSv2 - keeping this outside for eventual modification of hop limits?
metadataOptions = {
'HttpTokens': 'required',
'HttpPutResponseHopLimit': 2,
'HttpEndpoint': 'enabled'
}
try:
r = ec2.create_launch_template(
DryRun=False,
LaunchTemplateName=launch_template_name,
VersionDescription=f'Created by the EKS Creation Engine on {createdAt}',
LaunchTemplateData={
'EbsOptimized': False,
'BlockDeviceMappings': [
{
'DeviceName': '/dev/sda1',
'Ebs': {
'Encrypted': True,
'DeleteOnTermination': True,
'KmsKeyId': kms_key_arn,
'VolumeSize': int(ebs_volume_size),
'VolumeType': 'gp2'
}
}
],
'ImageId': amiId,
'InstanceType': instance_type,
'UserData': str(userData),
'SecurityGroupIds': [securityGroupId],
'MetadataOptions': metadataOptions,
'TagSpecifications': [
{
'ResourceType': 'instance',