-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsecurity-monitoring-cft.yaml
More file actions
777 lines (708 loc) · 27.8 KB
/
security-monitoring-cft.yaml
File metadata and controls
777 lines (708 loc) · 27.8 KB
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
AWSTemplateFormatVersion: 2010-09-09
Description: 'Cloudformation Template for AWS Security Monitoring using CloudWatch Agent.'
Parameters:
LabVpcCidr:
Type: String
Default: 10.10.0.0/16
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])(/(1[6-9]|2[0-8]))$
LoadBalancerSubnet1Cidr:
Type: String
Default: 10.10.1.0/24
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])(/(1[6-9]|2[0-8]))$
LoadBalancerSubnet2Cidr:
Type: String
Default: 10.10.2.0/24
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])(/(1[6-9]|2[0-8]))$
WebServerSubnetCidr:
Type: String
Default: 10.10.10.0/24
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])(/(1[6-9]|2[0-8]))$
DatabaseServerSubnetCidr:
Type: String
Default: 10.10.20.0/24
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])(/(1[6-9]|2[0-8]))$
WebServerPrivateIp:
Type: String
Default: 10.10.10.10
DatabaseServerPrivateIp:
Type: String
Default: 10.10.20.20
LatestAL2AmiId: # Locate latest Amazon Linux 2 AMI from public parameter store
Type: 'AWS::SSM::Parameter::Value<AWS::EC2::Image::Id>'
Default: '/aws/service/ami-amazon-linux-latest/amzn2-ami-hvm-x86_64-gp2'
Resources:
#-----Start - Create networking resources-----#
LabVpc:
Type: AWS::EC2::VPC
Properties:
CidrBlock: !Ref LabVpcCidr
EnableDnsSupport: true
EnableDnsHostnames: true
InstanceTenancy: default
Tags:
- Key: Name
Value: Lab VPC
#-----Load Balancer subnet 1 resources-----#
LoadBalancerSubnet1:
Type: AWS::EC2::Subnet
DependsOn: AttachInternetGateway
Properties:
CidrBlock: !Ref LoadBalancerSubnet1Cidr
VpcId: !Ref LabVpc
MapPublicIpOnLaunch: true
AvailabilityZone: !Select
- '0'
- !GetAZs ''
Tags:
- Key: Name
Value: Load Balancer Subnet 1 (Public)
InternetGateway:
Type: AWS::EC2::InternetGateway
Properties:
Tags:
- Key: Name
Value: Internet Gateway
AttachInternetGateway:
Type: AWS::EC2::VPCGatewayAttachment
Properties:
VpcId: !Ref LabVpc
InternetGatewayId: !Ref InternetGateway
PublicRouteTable:
Type: AWS::EC2::RouteTable
DependsOn:
- LoadBalancerSubnet1
- LoadBalancerSubnet2
Properties:
VpcId: !Ref LabVpc
PublicRoute:
Type: AWS::EC2::Route
Properties:
RouteTableId: !Ref PublicRouteTable
DestinationCidrBlock: 0.0.0.0/0
GatewayId: !Ref InternetGateway
LoadBalancerSubnet1RouteTableAssociation:
Type: AWS::EC2::SubnetRouteTableAssociation
DependsOn: PublicRoute
Properties:
SubnetId: !Ref LoadBalancerSubnet1
RouteTableId: !Ref PublicRouteTable
#-----Load Balancer subnet 2 resources-----#
LoadBalancerSubnet2:
Type: AWS::EC2::Subnet
DependsOn: AttachInternetGateway
Properties:
CidrBlock: !Ref LoadBalancerSubnet2Cidr
VpcId: !Ref LabVpc
MapPublicIpOnLaunch: true
AvailabilityZone: !Select
- '1'
- !GetAZs ''
Tags:
- Key: Name
Value: Load Balancer Subnet 2 (Public)
LoadBalancerSubnet2RouteTableAssociation:
Type: AWS::EC2::SubnetRouteTableAssociation
DependsOn: PublicRoute
Properties:
SubnetId: !Ref LoadBalancerSubnet2
RouteTableId: !Ref PublicRouteTable
#-----Private subnet 1 resources-----#
WebServerSubnet:
Type: AWS::EC2::Subnet
DependsOn: NatGateway
Properties:
CidrBlock: !Ref WebServerSubnetCidr
VpcId: !Ref LabVpc
MapPublicIpOnLaunch: false
AvailabilityZone: !Select
- '0'
- !GetAZs ''
Tags:
- Key: Name
Value: Web Server Subnet (Private)
NatGateway:
Type: AWS::EC2::NatGateway
Properties:
AllocationId: !GetAtt ElasticIpForNatGateway.AllocationId
SubnetId: !Ref LoadBalancerSubnet1
Tags:
- Key: Name
Value: NAT Gateway
ElasticIpForNatGateway:
Type: AWS::EC2::EIP
Properties:
Domain: vpc
PrivateRouteTable:
Type: AWS::EC2::RouteTable
DependsOn:
- WebServerSubnet
- DatabaseServerSubnet
Properties:
VpcId: !Ref LabVpc
PrivateRoute:
Type: AWS::EC2::Route
DependsOn: NatGateway
Properties:
RouteTableId: !Ref PrivateRouteTable
DestinationCidrBlock: 0.0.0.0/0
NatGatewayId: !Ref NatGateway
WebServerSubnetRouteTableAssociation:
Type: AWS::EC2::SubnetRouteTableAssociation
DependsOn: PrivateRoute
Properties:
SubnetId: !Ref WebServerSubnet
RouteTableId: !Ref PrivateRouteTable
#-----Private subnet 2 resources-----#
DatabaseServerSubnet:
Type: AWS::EC2::Subnet
DependsOn: NatGateway
Properties:
CidrBlock: !Ref DatabaseServerSubnetCidr
VpcId: !Ref LabVpc
MapPublicIpOnLaunch: false
AvailabilityZone: !Select
- '0'
- !GetAZs ''
Tags:
- Key: Name
Value: Database Server Subnet (Private)
DatabaseServerSubnetRouteTableAssociation:
Type: AWS::EC2::SubnetRouteTableAssociation
DependsOn: PrivateRoute
Properties:
SubnetId: !Ref DatabaseServerSubnet
RouteTableId: !Ref PrivateRouteTable
#-----End - Create networking resources-----#
#-----Start - create EC2 instance profile to allow the WebServer instance to access required services-----#
WebServerProfile:
Type: AWS::IAM::InstanceProfile
Properties:
InstanceProfileName: WebServerProfile
Roles:
- !Ref WebServerIamRole
WebServerIamRole:
Type: AWS::IAM::Role
Properties:
RoleName: WebServerIamRole
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Action:
- sts:AssumeRole
Effect: Allow
Principal:
Service:
- ec2.amazonaws.com
ManagedPolicyArns:
- arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore # Allows SSM connections to the instance.
- arn:aws:iam::aws:policy/CloudWatchAgentServerPolicy
WebServerBuildPolicy: # Permissions required to build the environment
Type: AWS::IAM::Policy
Properties:
PolicyName: WebServerBuildPolicy
Roles:
- !Ref WebServerIamRole
PolicyDocument: # Permissions to modify the SSM connection settings and to delete this policy at the end of the build
Version: '2012-10-17'
Statement:
- Effect: Allow
Action:
- iam:DeleteRolePolicy
- s3:GetObject
- s3:List*
Resource: '*'
- Effect: Allow
Action:
- ssm:UpdateDocument*
- ssm:CreateDocument*
- ssm:DeleteDocument*
Resource: !Sub arn:aws:ssm:${AWS::Region}:${AWS::AccountId}:document/SSM-SessionManagerRunShell
#-----End - create EC2 instance profile to allow the WebServer instance to access required services-----#
#-----Start - Create security group for WebServer-----#
WebServerSecurityGroup:
Type: AWS::EC2::SecurityGroup
Properties:
GroupName: WebServerSG
GroupDescription: Network access rules for the Web Server instance
VpcId: !Ref LabVpc
Tags:
- Key: Name
Value: Web Server SG
SecurityGroupIngress:
- IpProtocol: TCP
FromPort: 443
ToPort: 443
CidrIp: 0.0.0.0/0
SecurityGroupEgress:
- IpProtocol: TCP
FromPort: 443
ToPort: 443
CidrIp: 0.0.0.0/0
- IpProtocol: TCP
FromPort: 80
ToPort: 80
CidrIp: 0.0.0.0/0
#-----Start - Create Web Server EC2 instance-----#
WebServer:
Type: AWS::EC2::Instance
DependsOn:
- WebServerSubnetRouteTableAssociation
- PasswordGeneratorLambdaFunction
Properties:
ImageId: !Ref LatestAL2AmiId
InstanceType: t3.micro
IamInstanceProfile: !Ref WebServerProfile
BlockDeviceMappings:
- DeviceName: /dev/xvda
Ebs:
VolumeSize: 8
DeleteOnTermination: true
VolumeType: gp3
NetworkInterfaces:
- AssociatePublicIpAddress: false
PrivateIpAddress: !Ref WebServerPrivateIp
DeviceIndex: '0'
GroupSet:
- !Ref WebServerSecurityGroup
SubnetId: !Ref WebServerSubnet
Tags:
- Key: Name
Value: Web Server
UserData:
Fn::Base64: !Sub |
#!/bin/bash
yum update -y aws-cfn-bootstrap
/opt/aws/bin/cfn-init -v --stack ${AWS::StackName} --resource WebServer --configsets InstallTools,InstallWebServer,EnableTls,InstallWordpress,CreateLocalUser,ConfigureSsm,RemoveBuildPolicy --region ${AWS::Region}
/opt/aws/bin/cfn-signal -e $? --stack ${AWS::StackName} --resource WebServer --region ${AWS::Region}
Metadata:
AWS::CloudFormation::Init:
configSets:
InstallTools:
- "install-tools"
InstallWebServer:
- "install-web-server"
EnableTls:
- "enable-tls"
InstallWordpress:
- "install-wordpress"
ConfigureSsm:
- "configure-ssm"
CreateLocalUser:
- "create-local-user"
RemoveBuildPolicy:
- "remove-lab-build-policy"
install-tools:
commands:
a-update-yum:
command: yum update -y
b-install-python3:
command: yum install -y python3
c-remove-aws-cli-v1:
command: rm -rf /usr/bin/aws
d-download-aws-cli-v2:
command: curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
e-unzip-package:
command: unzip awscliv2.zip
f-install-aws-cli-v2:
command: ./aws/install -b
install-web-server: # https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-lamp-amazon-linux-2.html
commands:
a-amazon-linux-extras:
command: amazon-linux-extras install -y lamp-mariadb10.2-php7.2 php7.2
b-install-apache-mariadb-php:
command: yum install -y httpd
c-start-apache:
command: systemctl start httpd
d-start-apache-at-boot:
command: systemctl enable httpd
e-add-user-to-apache-group:
command: usermod -a -G apache ec2-user
f-change-www-directory-ownership:
command: chown -R ec2-user:apache /var/www
g-add-group-write-permissions:
command: chmod 2775 /var/www && find /var/www -type d -exec sudo chmod 2775 {} \;
h-add-group-permissions-recursively:
command: find /var/www -type f -exec sudo chmod 0664 {} \;
enable-tls: # https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/SSL-on-amazon-linux-2.html#ssl_enable
commands:
a-install-mod-ssl:
command: yum install -y mod_ssl
b-generate-cert:
command: /etc/pki/tls/certs/make-dummy-cert /etc/pki/tls/certs/localhost.crt
c-modify-ssl-conf-file:
command: sed -i 's/SSLCertificateKeyFile/#SSLCertificateKeyFile/' /etc/httpd/conf.d/ssl.conf
d-restart-httpd-service:
command: systemctl restart httpd
install-wordpress: # https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/hosting-wordpress.html
commands:
a-download-wordpress:
command: wget https://wordpress.org/latest.tar.gz && tar -xzf latest.tar.gz
b-create-wp-config-file:
command: cp wordpress/wp-config-sample.php wordpress/wp-config.php
c-update-wp-config-file:
command: !Sub sed -i 's/database_name_here/wordpress_db/; s/username_here/wordpress_user/; s/password_here/${GeneratePassword.RandomString}/; s/'\''DB_HOST'\'', '\''localhost'\''/'\''DB_HOST'\'', '\''${DatabaseServerPrivateIp}'\''/' wordpress/wp-config.php
d-copy-wp-files-to-www:
command: mkdir /var/www/html/blog && cp -r wordpress/* /var/www/html/blog/
create-local-user:
commands:
a-create-webdev-account:
command: useradd -m webdev -g users
b-set-webdev-password:
command: !Sub echo -e "${GeneratePassword.RandomString}\n${GeneratePassword.RandomString}" | passwd webdev
configure-ssm: # Set Systems Manager Session Manager connection time out 60 minutes, sets the default user for connects to "ec2-user", and changes to the home directory at login.
files:
/temp/ssm-settings.yaml:
content: |
inputs:
s3BucketName: ""
s3KeyPrefix: ""
s3EncryptionEnabled: true
cloudWatchLogGroupName: ""
cloudWatchEncryptionEnabled: true
idleSessionTimeout: "60"
cloudWatchStreamingEnabled: true
kmsKeyId: ""
runAsEnabled: true
runAsDefaultUser: ec2-user
shellProfile:
linux: cd $HOME; pwd
schemaVersion: "1.0"
description: Document to modify Session Manager idle timeout and runas user.
sessionType: Standard_Stream
commands:
a-create-ssm-document:
command: aws ssm create-document --name "SSM-SessionManagerRunShell" --content "file:///temp/ssm-settings.yaml" --document-format YAML --document-type Session
ignoreErrors: true
b-configure-ssm:
command: aws ssm update-document --name "SSM-SessionManagerRunShell" --content "file:///temp/ssm-settings.yaml" --document-format YAML --document-version '$LATEST'
ignoreErrors: true
remove-lab-build-policy: # Removes the WebServerBuildPolicy IAM policy from the WebServerIamRole IAM role, as those permissions are needed at build time, but the student should not have access to them.
commands:
remove-lab-build-policy:
command: !Sub aws iam delete-role-policy --role-name ${WebServerIamRole} --policy-name WebServerBuildPolicy
CreationPolicy:
ResourceSignal:
Timeout: PT4M
#-----End - Create Web Server EC2 instance-----#
#-----Start - create EC2 instance profile to allow the DatabaseServer instance to access required services-----#
DatabaseServerProfile:
Type: AWS::IAM::InstanceProfile
Properties:
InstanceProfileName: DatabaseServerProfile
Roles:
- !Ref DatabaseServerIamRole
DatabaseServerIamRole:
Type: AWS::IAM::Role
Properties:
RoleName: DatabaseServerIamRole
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Action:
- sts:AssumeRole
Effect: Allow
Principal:
Service:
- ec2.amazonaws.com
ManagedPolicyArns:
- arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore # Allows SSM connections to the instance.
- arn:aws:iam::aws:policy/CloudWatchAgentServerPolicy
ModifySecurityGroupRulesPolicy:
Type: AWS::IAM::Policy
Properties:
PolicyName: ModifySecurityGroupRulesPolicy
Roles:
- !Ref DatabaseServerIamRole
PolicyDocument: # Permissions to remove security group rules that are no longer needed after the build process
Version: '2012-10-17'
Statement:
- Effect: Allow
Action:
- ec2:AuthorizeSecurityGroupEgress
- ec2:AuthorizeSecurityGroupIngress
- ec2:RevokeSecurityGroupEgress
- ec2:RevokeSecurityGroupIngress
Resource: '*'
S3BucketUploadPolicy:
Type: AWS::IAM::Policy
Properties:
PolicyName: S3BucketUploadPolicy
Roles:
- !Ref DatabaseServerIamRole
PolicyDocument: # Permissions to remove security group rules that are no longer needed after the build process
Version: '2012-10-17'
Statement:
- Effect: Allow
Action:
- s3:PutObject
Resource:
- !GetAtt LabNetworkTestBucket.Arn
- !Sub ${LabNetworkTestBucket.Arn}/*
#-----End - create EC2 instance profile to allow the DatabaseServer instance to access required services to build the lab-----#
#-----Start - Create security group for DatabaseServer-----#
DatabaseServerSecurityGroup:
Type: AWS::EC2::SecurityGroup
Properties:
GroupName: DatabaseServerSG
GroupDescription: Network access rules for the Database Server instance
VpcId: !Ref LabVpc
Tags:
- Key: Name
Value: Database Server SG
SecurityGroupIngress:
- IpProtocol: TCP
FromPort: 3306
ToPort: 3306
SourceSecurityGroupId: !Sub ${WebServerSecurityGroup.GroupId}
SecurityGroupEgress:
- IpProtocol: TCP
FromPort: 443
ToPort: 443
CidrIp: 0.0.0.0/0
#-----End - Create security group for DatabaseServer-----#
#-----Start - Create Database Server EC2 instance-----#
DatabaseServer:
Type: AWS::EC2::Instance
DependsOn:
- DatabaseServerSubnetRouteTableAssociation
- WebServer
- PasswordGeneratorLambdaFunction
Properties:
ImageId: !Ref LatestAL2AmiId
InstanceType: t3.micro
IamInstanceProfile: !Ref DatabaseServerProfile
BlockDeviceMappings:
- DeviceName: /dev/xvda
Ebs:
VolumeSize: 8
DeleteOnTermination: true
VolumeType: gp3
NetworkInterfaces:
- AssociatePublicIpAddress: false
PrivateIpAddress: !Ref DatabaseServerPrivateIp
DeviceIndex: '0'
GroupSet:
- !Ref DatabaseServerSecurityGroup
SubnetId: !Ref DatabaseServerSubnet
Tags:
- Key: Name
Value: Database Server
UserData:
Fn::Base64: !Sub |
#!/bin/bash
yum update -y aws-cfn-bootstrap
/opt/aws/bin/cfn-init -v --stack ${AWS::StackName} --resource DatabaseServer --configsets InstallTools,InstallConfigureDb,CreateLocalUser,ModifySgRules --region ${AWS::Region}
/opt/aws/bin/cfn-signal -e $? --stack ${AWS::StackName} --resource DatabaseServer --region ${AWS::Region}
Metadata:
AWS::CloudFormation::Init:
configSets:
InstallTools:
- "install-tools"
InstallConfigureDb:
- "install-and-configure-mariadb"
CreateLocalUser:
- "create-local-user"
# DownloadSampleData:
# - "download-sample-data"
ModifySgRules:
- "modify-security-group-rules"
install-tools:
commands:
a-update-yum:
command: yum update -y
b-install-python3:
command: yum install -y python3
c-remove-aws-cli-v1:
command: rm -rf /usr/bin/aws
d-download-aws-cli-v2:
command: curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
e-unzip-package:
command: unzip awscliv2.zip
f-install-aws-cli-v2:
command: ./aws/install -b
install-and-configure-mariadb:
commands:
a-install-mariadb:
command: amazon-linux-extras install -y mariadb10.5
b-mariadb-allow-remote-connections:
command: sed -i 's/#bind-address/bind-address/' /etc/my.cnf.d/mariadb-server.cnf
c-enable-and-start-mariadb-service:
command: systemctl enable mariadb && systemctl start mariadb
d-set-mariadb-root-password:
command: !Sub 'mysqladmin --user=root password "${GeneratePassword.RandomString}"'
e-mariadb-drop-anonymous-users1:
command: mysql -e "DROP USER IF EXISTS ''@'localhost'"
f-mariadb-drop-test-db:
command: mysql -e "DROP DATABASE IF EXISTS test"
g-mariadb-create-wp-db:
command: mysql -e "CREATE DATABASE IF NOT EXISTS wordpress_db"
h-mariadb-create-wp-user:
command: !Sub mysql -e "CREATE USER IF NOT EXISTS 'wordpress_user'@'${WebServerPrivateIp}' IDENTIFIED BY '${GeneratePassword.RandomString}'"
i-mariadb-grant-wp-user-rights:
command: !Sub mysql -e "GRANT ALL PRIVILEGES ON wordpress_db.* to 'wordpress_user'@'${WebServerPrivateIp}'"
j-mariadb-flush-privileges:
command: mysql -e "FLUSH PRIVILEGES"
create-local-user:
commands:
a-create-dbdev-account:
command: useradd -m dbdev -g users
b-set-dbdev-password:
command: !Sub echo -e "${GeneratePassword.RandomString}\\n${GeneratePassword.RandomString}" | passwd dbdev
# download-sample-data:
# commands:
# a-download-sample-data:
# command: !Sub wget https://${AWS::Region}-tcprod.s3.${AWS::Region}.amazonaws.com/courses/ILT-TF-200-SIPSBP/v1.4.2.prod-d8d79fbd/lab-3-monitoring-logging/scripts/SampleData.zip -O /home/ec2-user/SampleData.zip
# b-set-permissions:
# command: chown -R ec2-user /home/ec2-user/
modify-security-group-rules: # Remove egress rules for ports 80 and 443 from the web and database server security groups. They are needed at build time, but should not be there for the lab.
commands:
a-add-web-server-egress-http:
command: !Sub aws ec2 authorize-security-group-egress --group-id ${WebServerSecurityGroup.GroupId} --ip-permissions IpProtocol=tcp,FromPort=3306,ToPort=3306,UserIdGroupPairs=[{GroupId=${DatabaseServerSecurityGroup.GroupId}}]
CreationPolicy:
ResourceSignal:
Timeout: PT10M
#-----End - Create Database Server EC2 instance-----#
#-----Start - Create network load balancer-----#
#-----network load balancer (Elastic Load Balancer v2)-----#
NetworkLb:
Type: AWS::ElasticLoadBalancingV2::LoadBalancer
DependsOn:
- LoadBalancerSubnet1RouteTableAssociation
- LoadBalancerSubnet2RouteTableAssociation
Properties:
IpAddressType: ipv4
Name: web-lb
Scheme: internet-facing
Subnets:
- !Ref LoadBalancerSubnet1
- !Ref LoadBalancerSubnet2
Type: network
NetworkLbTargetGroup:
Type: AWS::ElasticLoadBalancingV2::TargetGroup
Properties:
Name: NetworkLb-WebServer-TargetGroup
Protocol: TCP
Port: 443
TargetType: instance
Targets:
- Id: !Ref WebServer
VpcId: !Ref LabVpc
NetworkLbListener:
Type: AWS::ElasticLoadBalancingV2::Listener
Properties:
DefaultActions:
- Type: forward
ForwardConfig:
TargetGroups:
- TargetGroupArn: !Ref NetworkLbTargetGroup
Protocol: TCP
Port: 443
LoadBalancerArn: !Ref NetworkLb
#-----End - Create application load balancer-----#
#-----Start - Lambda function to generate random number to use with bucket names-----#
LambdaNumberGeneratorRole:
Type: AWS::IAM::Role
Properties:
RoleName: LambdaNumberGeneratorRole
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal:
Service:
- lambda.amazonaws.com
Action:
- sts:AssumeRole
Policies:
- PolicyName: allowLambdaLogging
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: "Allow"
Action:
- "logs:*"
Resource: "*"
NumberGeneratorLambdaFunction:
Type: AWS::Lambda::Function
Properties:
FunctionName: NumberGenerator
Code:
ZipFile: >
const response = require("cfn-response");
const generateNumber = (length, chars) => {
var result = '';
for (var i = length; i > 0; --i) result += chars[Math.floor(Math.random() * chars.length)];
return result;
}
exports.handler = (event, context) =>{
const str = generateNumber(event['ResourceProperties']['Length'], '0123456789');
const responseData = {RandomNumber: str};
response.send(event, context, response.SUCCESS, responseData);
};
Handler: index.handler
Runtime: nodejs16.x
Role: !GetAtt LambdaNumberGeneratorRole.Arn
MemorySize: 128
Timeout: 20
GenerateNumber:
Type: AWS::CloudFormation::CustomResource
Properties:
Length: 9
ServiceToken: !GetAtt NumberGeneratorLambdaFunction.Arn
#-----End - Lambda function to generate random number to use with bucket names-----#
#-----Start - Create lab S3 buckets-----#
LabNetworkTestBucket:
Type: AWS::S3::Bucket
Properties:
BucketName: !Sub lab-network-test-${AWS::Region}-${GenerateNumber.RandomNumber}
PublicAccessBlockConfiguration: #Sets "Block all public access" to "On" for the bucket
BlockPublicAcls: true
BlockPublicPolicy: true
IgnorePublicAcls: true
RestrictPublicBuckets: true
#-----End - Create lab S3 buckets-----#
#-----Start - Lambda function to generate random password with given parameters-----#
PasswordGeneratorLambdaFunction:
Type: AWS::Lambda::Function
Properties:
FunctionName: PasswordGenerator
Code:
ZipFile: >
const response = require("cfn-response");
const generatePassword = (length, chars) => {
var result = '';
for (var i = length; i > 0; --i) result += chars[Math.floor(Math.random() * chars.length)];
return result;
}
exports.handler = (event, context) =>{
const str = generatePassword(event['ResourceProperties']['Length'], '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ');
const responseData = {RandomString: str};
response.send(event, context, response.SUCCESS, responseData);
};
Handler: index.handler
Runtime: nodejs16.x
Role: !GetAtt LambdaNumberGeneratorRole.Arn
MemorySize: 128
Timeout: 20
GeneratePassword:
Type: AWS::CloudFormation::CustomResource
Properties:
Length: 20
ServiceToken: !GetAtt PasswordGeneratorLambdaFunction.Arn
#-----End - Lambda function to generate random password with given parameters-----#
#-----Start - Add lab user to ReadOnly group-----#
Outputs:
AwsRegion:
Description: AWS Region the lab is running in.
Value: !Ref AWS::Region
DatabaseServerId:
Description: The EC2 instance ID of the Database Server instance.
Value: !Ref DatabaseServer
TestBucket:
Description: S3 bucket used to upload a file from the database server to activate an outgoing traffic alarm
Value: !Ref LabNetworkTestBucket
NatGatewayId:
Description: ID of the NAT gateway
Value: !Ref NatGateway
Password:
Value: !GetAtt GeneratePassword.RandomString