forked from widdix/aws-s3-virusscan
-
Notifications
You must be signed in to change notification settings - Fork 0
/
template.yaml
963 lines (951 loc) · 35 KB
/
template.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
---
# Copyright 2018 widdix GmbH
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
AWSTemplateFormatVersion: '2010-09-09'
Description: 'Security: S3 VirusScan, a cloudonaut.io template'
Metadata:
'AWS::CloudFormation::Interface':
ParameterGroups:
- Label:
default: 'Parent Stacks'
Parameters:
- ParentVPCStack
- ParentSSHBastionStack
- Label:
default: 'Scan Parameters'
Parameters:
- DeleteInfectedFiles
- ReportCleanFiles
- TagFiles
- TagKey
- S3BucketRestriction
- S3ObjectRestriction
- Label:
default: 'Auto Scaling Group Parameters'
Parameters:
- AutoScalingMinSize
- AutoScalingMaxSize
- Label:
default: 'EC2 Parameters'
Parameters:
- KeyName
- IAMUserSSHAccess
- SystemsManagerAccess
- InstanceType
- SpotPrice
- LogsRetentionInDays
- VolumeSize
Parameters:
ParentVPCStack:
Description: 'Stack name of parent VPC stack based on vpc/vpc-*azs.yaml template.'
Type: String
ParentSSHBastionStack:
Description: 'Optional stack name of parent SSH bastion host/instance stack based on vpc/vpc-ssh-bastion.yaml template.'
Type: String
Default: ''
S3BucketRestriction:
Description: 'Restrict access to specific S3 buckets (e.g. arn:aws:s3:::s3-virusscan-a,arn:aws:s3:::s3-virusscan-b or * to allow access to all S3 buckets).'
Type: CommaDelimitedList
Default: '*'
S3ObjectRestriction:
Description: 'Restrict access to specific S3 objects (e.g. arn:aws:s3:::s3-virusscan-a/*,arn:aws:s3:::s3-virusscan-b/* or * to allow access to all S3 objects).'
Type: CommaDelimitedList
Default: '*'
DeleteInfectedFiles:
Description: 'Automatically delete infected files'
Type: String
Default: true
AllowedValues:
- true
- false
ReportCleanFiles:
Description: 'Report successful scan of clean, as well as infected files to the SNS topic'
Type: String
Default: false
AllowedValues:
- true
- false
TagFiles:
Description: 'Tag S3 object upon successful scan accordingly with values of "clean" or "infected" (only if DeleteInfectedFiles != false) using key specified by TagKey.'
Type: String
Default: false
AllowedValues:
- true
- false
TagKey:
Description: 'S3 object tag key used to specify values of "clean" or "infected".'
Type: String
Default: 'clamav-status'
AutoScalingMinSize:
Description: 'Min Size for Auto Scaling'
Type: Number
Default: 1
ConstraintDescription: 'Must be >= 0'
MinValue: 0
AutoScalingMaxSize:
Description: 'Max Size for Auto Scaling'
Type: Number
Default: 1
ConstraintDescription: 'Must be >= 1'
MinValue: 1
KeyName:
Description: 'Optional provide an EC2 key pair if you want to login via SSH'
Type: String
Default: ''
IAMUserSSHAccess:
Description: 'Synchronize public keys of IAM users to enable personalized SSH access (Doc: https://cloudonaut.io/manage-aws-ec2-ssh-access-with-iam/).'
Type: String
Default: false
AllowedValues:
- true
- false
SystemsManagerAccess:
Description: 'Enable AWS Systems Manager agent and authorization.'
Type: String
Default: true
AllowedValues:
- true
- false
InstanceType:
Description: 'Specifies the instance type of the EC2 instance'
Type: String
Default: 't2.small'
SpotPrice:
Description: 'Optional spot price (leave empty to start on-demand instances).'
Type: String
AllowedPattern: '[0-9\.]*'
ConstraintDescription: 'Must be a positive number'
Default: ''
LogsRetentionInDays:
Description: 'Specifies the number of days you want to retain log events.'
Type: Number
Default: 14
AllowedValues: [1, 3, 5, 7, 14, 30, 60, 90, 120, 150, 180, 365, 400, 545, 731, 1827, 3653]
VolumeSize:
Description: The size of the volume, in gibibytes (GiBs).
Type: Number
Default: 8
ConstraintDescription: 'Must be in the range [8-1024]'
MinValue: 8
MaxValue: 1024
Conditions:
HasKeyName: !Not [!Equals [!Ref KeyName, '']]
HasIAMUserSSHAccess: !Equals [!Ref IAMUserSSHAccess, 'true']
HasSystemsManagerAccess: !Equals [!Ref SystemsManagerAccess, 'true']
HasSSHBastionSecurityGroup: !Not [!Equals [!Ref ParentSSHBastionStack, '']]
HasNotSSHBastionSecurityGroup: !Equals [!Ref ParentSSHBastionStack, '']
HasDeleteInfectedFiles: !Equals [!Ref DeleteInfectedFiles, 'true']
HasTagFiles: !Equals [!Ref TagFiles, 'true']
HasSpotPrice: !Not [!Equals [!Ref SpotPrice, '']]
Mappings:
RegionMap:
'ap-south-1':
AMI: 'ami-06bcd1131b2f55803'
'eu-west-3':
AMI: 'ami-051707cdba246187b'
'eu-north-1':
AMI: 'ami-07ec6279'
'eu-west-2':
AMI: 'ami-0274e11dced17bb5b'
'eu-west-1':
AMI: 'ami-09693313102a30b2c'
'ap-northeast-2':
AMI: 'ami-0b4fdb56a00adb616'
'ap-northeast-1':
AMI: 'ami-0a2de1c3b415889d2'
'sa-east-1':
AMI: 'ami-0112d42866980b373'
'ca-central-1':
AMI: 'ami-076b4adb3f90cd384'
'ap-southeast-1':
AMI: 'ami-0b84d2c53ad5250c2'
'ap-southeast-2':
AMI: 'ami-08589eca6dcc9b39c'
'eu-central-1':
AMI: 'ami-034fffcc6a0063961'
'us-east-1':
AMI: 'ami-009d6802948d06e52'
'us-east-2':
AMI: 'ami-02e680c4540db351e'
'us-west-1':
AMI: 'ami-011b6930a81cd6aaf'
'us-west-2':
AMI: 'ami-01bbe152bf19d0289'
Resources:
FindingsTopic:
Type: 'AWS::SNS::Topic'
Properties: {}
ScanQueue:
Type: 'AWS::SQS::Queue'
Properties:
VisibilityTimeout: 300
RedrivePolicy:
deadLetterTargetArn: !GetAtt 'ScanQueueDLQ.Arn'
maxReceiveCount: 3
ScanQueueFullAlarm:
Type: 'AWS::CloudWatch::Alarm'
Properties:
AlarmActions:
- !Ref ScanScaleUp
ComparisonOperator: GreaterThanThreshold
Dimensions:
- Name: QueueName
Value: !GetAtt 'ScanQueue.QueueName'
EvaluationPeriods: 1
MetricName: ApproximateNumberOfMessagesVisible
Namespace: 'AWS/SQS'
Period: 300
Statistic: Maximum
Threshold: 0
ScanQueueEmptyAlarm:
Type: 'AWS::CloudWatch::Alarm'
Properties:
AlarmActions:
- !Ref ScanScaleDown
ComparisonOperator: LessThanOrEqualToThreshold
Dimensions:
- Name: QueueName
Value: !GetAtt 'ScanQueue.QueueName'
EvaluationPeriods: 1
MetricName: ApproximateNumberOfMessagesVisible
Namespace: 'AWS/SQS'
Period: 300
Statistic: Maximum
Threshold: 0
ScanQueuePolicy:
Type: 'AWS::SQS::QueuePolicy'
Properties:
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal:
AWS: '*'
Action: 'SQS:SendMessage'
Resource: !GetAtt 'ScanQueue.Arn'
Queues:
- !Ref ScanQueue
ScanQueueDLQ:
Type: 'AWS::SQS::Queue'
Properties:
MessageRetentionPeriod: 1209600
ScanQueueDLQAlarm:
Type: 'AWS::CloudWatch::Alarm'
Properties:
AlarmDescription: 'Alarm if dead letter queue has messages'
Namespace: 'AWS/SQS'
MetricName: ApproximateNumberOfMessagesVisible
Dimensions:
- Name: QueueName
Value: !GetAtt 'ScanQueueDLQ.QueueName'
Statistic: Sum
Period: 60
EvaluationPeriods: 1
Threshold: 1
ComparisonOperator: GreaterThanOrEqualToThreshold
AlarmActions:
- !Ref FindingsTopic
ScanQueueOldMessagesAlarm:
Type: 'AWS::CloudWatch::Alarm'
Properties:
AlarmDescription: 'Alarm if scan queue contains a message older than 1 hour'
Namespace: 'AWS/SQS'
MetricName: ApproximateAgeOfOldestMessage
Dimensions:
- Name: QueueName
Value: !GetAtt 'ScanQueue.QueueName'
Statistic: Maximum
Period: 60
EvaluationPeriods: 1
Threshold: 3600 # 1 hour
ComparisonOperator: GreaterThanOrEqualToThreshold
AlarmActions:
- !Ref FindingsTopic
ScanAutoScalingGroup:
Type: 'AWS::AutoScaling::AutoScalingGroup'
Properties:
LaunchConfigurationName: !Ref ScanLaunchConfiguration
MaxSize: !Ref AutoScalingMaxSize
MinSize: !Ref AutoScalingMinSize
VPCZoneIdentifier: !Split [',', {'Fn::ImportValue': !Sub '${ParentVPCStack}-SubnetsPublic'}]
Tags:
- Key: Name
Value: !Ref 'AWS::StackName'
PropagateAtLaunch: true
CreationPolicy:
ResourceSignal:
Timeout: PT10M
UpdatePolicy:
AutoScalingRollingUpdate:
PauseTime: PT10M
WaitOnResourceSignals: true
ScanScaleUp:
Type: 'AWS::AutoScaling::ScalingPolicy'
Properties:
AdjustmentType: ChangeInCapacity
AutoScalingGroupName: !Ref ScanAutoScalingGroup
EstimatedInstanceWarmup: 300
MetricAggregationType: Maximum
PolicyType: StepScaling
StepAdjustments:
- MetricIntervalLowerBound: 0
MetricIntervalUpperBound: 25
ScalingAdjustment: 1
- MetricIntervalLowerBound: 25
MetricIntervalUpperBound: 100
ScalingAdjustment: 2
- MetricIntervalLowerBound: 100
MetricIntervalUpperBound: 400
ScalingAdjustment: 4
- MetricIntervalLowerBound: 400
MetricIntervalUpperBound: 1600
ScalingAdjustment: 8
- MetricIntervalLowerBound: 1600
MetricIntervalUpperBound: 6400
ScalingAdjustment: 16
- MetricIntervalLowerBound: 6400
MetricIntervalUpperBound: 25600
ScalingAdjustment: 32
- MetricIntervalLowerBound: 25600
ScalingAdjustment: 64
ScanScaleDown:
Type: 'AWS::AutoScaling::ScalingPolicy'
Properties:
AdjustmentType: PercentChangeInCapacity
AutoScalingGroupName: !Ref ScanAutoScalingGroup
Cooldown: '300'
MinAdjustmentMagnitude: 1
PolicyType: SimpleScaling
ScalingAdjustment: -25
ScanInstanceProfile:
Type: 'AWS::IAM::InstanceProfile'
Properties:
Roles:
- !Ref ScanIAMRole
ScanIAMRole:
Type: 'AWS::IAM::Role'
Properties:
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal:
Service: 'ec2.amazonaws.com'
Action: sts:AssumeRole
ManagedPolicyArns: !If [HasSystemsManagerAccess, ['arn:aws:iam::aws:policy/service-role/AmazonEC2RoleforSSM'], []]
Path: /
Policies:
- PolicyName: s3read
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action:
- 's3:GetObject*'
Resource: !Ref S3ObjectRestriction
- Effect: Allow
Action:
- 's3:ListBucket*'
Resource: !Ref S3BucketRestriction
- PolicyName: sqs
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action:
- 'sqs:DeleteMessage'
- 'sqs:ReceiveMessage'
Resource: !GetAtt 'ScanQueue.Arn'
- PolicyName: sns
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action: 'sns:Publish'
Resource: !Ref FindingsTopic
- PolicyName: logs
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action:
- 'logs:CreateLogGroup'
- 'logs:CreateLogStream'
- 'logs:PutLogEvents'
- 'logs:DescribeLogStreams'
Resource: 'arn:aws:logs:*:*:*'
DeletePolicy:
Type: 'AWS::IAM::Policy'
Condition: HasDeleteInfectedFiles
Properties:
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action:
- 's3:DeleteObject*'
Resource: !Ref S3ObjectRestriction
PolicyName: s3delete
Roles:
- !Ref ScanIAMRole
TagObjectPolicy:
Type: 'AWS::IAM::Policy'
Condition: HasTagFiles
Properties:
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action: 's3:PutObjectTagging'
Resource: !Ref S3ObjectRestriction
Condition:
'ForAllValues:StringLike':
's3:RequestObjectTagKeys': !Ref TagKey
PolicyName: s3objecttag
Roles:
- !Ref ScanIAMRole
ScanIAMPolicySSHAccess:
Type: 'AWS::IAM::Policy'
Condition: HasIAMUserSSHAccess
Properties:
Roles:
- !Ref ScanIAMRole
PolicyName: iam
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action:
- 'iam:ListUsers'
Resource:
- '*'
- Effect: Allow
Action:
- 'iam:ListSSHPublicKeys'
- 'iam:GetSSHPublicKey'
Resource:
- !Sub 'arn:aws:iam::${AWS::AccountId}:user/*'
Logs:
Type: 'AWS::Logs::LogGroup'
Properties:
RetentionInDays: !Ref LogsRetentionInDays
ScanLaunchConfiguration:
Type: 'AWS::AutoScaling::LaunchConfiguration'
Metadata:
'AWS::CloudFormation::Init':
configSets:
default: !If [HasIAMUserSSHAccess, [awslogs, ssh-access, extras1, extras2, config], [awslogs, extras1, extras2, config]]
awslogs:
packages:
yum:
awslogs: []
files:
'/etc/awslogs/awscli.conf':
content: !Sub |
[default]
region = ${AWS::Region}
[plugins]
cwlogs = cwlogs
mode: '000644'
owner: root
group: root
'/etc/awslogs/awslogs.conf':
content: !Sub |
[general]
state_file = /var/lib/awslogs/agent-state
[/var/log/amazon/ssm/amazon-ssm-agent.log]
datetime_format = %Y-%m-%d %H:%M:%S
file = /var/log/amazon/ssm/amazon-ssm-agent.log
log_stream_name = {instance_id}/var/log/amazon/ssm/amazon-ssm-agent.log
log_group_name = ${Logs}
[/var/log/amazon/ssm/errors.log]
datetime_format = %Y-%m-%d %H:%M:%S
file = /var/log/amazon/ssm/errors.log
log_stream_name = {instance_id}/var/log/amazon/ssm/errors.log
log_group_name = ${Logs}
[/var/log/audit/audit.log]
file = /var/log/audit/audit.log
log_stream_name = {instance_id}/var/log/audit/audit.log
log_group_name = ${Logs}
[/var/log/awslogs.log]
datetime_format = %Y-%m-%d %H:%M:%S
file = /var/log/awslogs.log
log_stream_name = {instance_id}/var/log/awslogs.log
log_group_name = ${Logs}
[/var/log/boot.log]
file = /var/log/boot.log
log_stream_name = {instance_id}/var/log/boot.log
log_group_name = ${Logs}
[/var/log/cfn-hup.log]
datetime_format = %Y-%m-%d %H:%M:%S
file = /var/log/cfn-hup.log
log_stream_name = {instance_id}/var/log/cfn-hup.log
log_group_name = ${Logs}
[/var/log/cfn-init-cmd.log]
datetime_format = %Y-%m-%d %H:%M:%S
file = /var/log/cfn-init-cmd.log
log_stream_name = {instance_id}/var/log/cfn-init-cmd.log
log_group_name = ${Logs}
[/var/log/cfn-init.log]
datetime_format = %Y-%m-%d %H:%M:%S
file = /var/log/cfn-init.log
log_stream_name = {instance_id}/var/log/cfn-init.log
log_group_name = ${Logs}
[/var/log/cfn-wire.log]
datetime_format = %Y-%m-%d %H:%M:%S
file = /var/log/cfn-wire.log
log_stream_name = {instance_id}/var/log/cfn-wire.log
log_group_name = ${Logs}
[/var/log/cloud-init-output.log]
file = /var/log/cloud-init-output.log
log_stream_name = {instance_id}/var/log/cloud-init-output.log
log_group_name = ${Logs}
[/var/log/cloud-init.log]
datetime_format = %b %d %H:%M:%S
file = /var/log/cloud-init.log
log_stream_name = {instance_id}/var/log/cloud-init.log
log_group_name = ${Logs}
[/var/log/cron]
datetime_format = %b %d %H:%M:%S
file = /var/log/cron
log_stream_name = {instance_id}/var/log/cron
log_group_name = ${Logs}
[/var/log/dmesg]
file = /var/log/dmesg
log_stream_name = {instance_id}/var/log/dmesg
log_group_name = ${Logs}
[/var/log/grubby_prune_debug]
file = /var/log/grubby_prune_debug
log_stream_name = {instance_id}/var/log/grubby_prune_debug
log_group_name = ${Logs}
[/var/log/maillog]
datetime_format = %b %d %H:%M:%S
file = /var/log/maillog
log_stream_name = {instance_id}/var/log/maillog
log_group_name = ${Logs}
[/var/log/messages]
datetime_format = %b %d %H:%M:%S
file = /var/log/messages
log_stream_name = {instance_id}/var/log/messages
log_group_name = ${Logs}
[/var/log/secure]
datetime_format = %b %d %H:%M:%S
file = /var/log/secure
log_stream_name = {instance_id}/var/log/secure
log_group_name = ${Logs}
[/var/log/yum.log]
datetime_format = %b %d %H:%M:%S
file = /var/log/yum.log
log_stream_name = {instance_id}/var/log/yum.log
log_group_name = ${Logs}
mode: '000644'
owner: root
group: root
services:
sysvinit:
awslogsd:
enabled: true
ensureRunning: true
packages:
yum:
- awslogs
files:
- '/etc/awslogs/awslogs.conf'
- '/etc/awslogs/awscli.conf'
ssh-access:
files:
'/opt/authorized_keys_command.sh':
content: |
#!/bin/bash -e
if [ -z "$1" ]; then
exit 1
fi
UnsaveUserName="$1"
UnsaveUserName=${UnsaveUserName//".plus."/"+"}
UnsaveUserName=${UnsaveUserName//".equal."/"="}
UnsaveUserName=${UnsaveUserName//".comma."/","}
UnsaveUserName=${UnsaveUserName//".at."/"@"}
aws iam list-ssh-public-keys --user-name "$UnsaveUserName" --query "SSHPublicKeys[?Status == 'Active'].[SSHPublicKeyId]" --output text | while read -r KeyId; do
aws iam get-ssh-public-key --user-name "$UnsaveUserName" --ssh-public-key-id "$KeyId" --encoding SSH --query "SSHPublicKey.SSHPublicKeyBody" --output text
done
mode: '000755'
owner: root
group: root
'/opt/import_users.sh':
content: |
#!/bin/bash -e
aws iam list-users --query "Users[].[UserName]" --output text | while read User; do
SaveUserName="$User"
SaveUserName=${SaveUserName//"+"/".plus."}
SaveUserName=${SaveUserName//"="/".equal."}
SaveUserName=${SaveUserName//","/".comma."}
SaveUserName=${SaveUserName//"@"/".at."}
if [ "${#SaveUserName}" -le "32" ]; then
if ! id -u "$SaveUserName" >/dev/null 2>&1; then
#sudo will read each file in /etc/sudoers.d, skipping file names that end in ‘~’ or contain a ‘.’ character to avoid causing problems with package manager or editor temporary/backup files.
SaveUserFileName=$(echo "$SaveUserName" | tr "." " ")
/usr/sbin/useradd "$SaveUserName"
echo "$SaveUserName ALL=(ALL) NOPASSWD:ALL" > "/etc/sudoers.d/$SaveUserFileName"
fi
else
echo "Can not import IAM user ${SaveUserName}. User name is longer than 32 characters."
fi
done
mode: '000755'
owner: root
group: root
'/etc/cron.d/import_users':
content: |
*/10 * * * * root /opt/import_users.sh
mode: '000644'
owner: root
group: root
commands:
'a_configure_sshd_command':
command: 'sed -e ''/AuthorizedKeysCommand / s/^#*/#/'' -i /etc/ssh/sshd_config; echo -e ''\nAuthorizedKeysCommand /opt/authorized_keys_command.sh'' >> /etc/ssh/sshd_config'
test: '! grep -q ''^AuthorizedKeysCommand /opt/authorized_keys_command.sh'' /etc/ssh/sshd_config'
'b_configure_sshd_commanduser':
command: 'sed -e ''/AuthorizedKeysCommandUser / s/^#*/#/'' -i /etc/ssh/sshd_config; echo -e ''\nAuthorizedKeysCommandUser nobody'' >> /etc/ssh/sshd_config'
test: '! grep -q ''^AuthorizedKeysCommandUser nobody'' /etc/ssh/sshd_config'
'c_import_users':
command: './import_users.sh'
cwd: '/opt'
services:
sysvinit:
sshd:
enabled: true
ensureRunning: true
commands:
- 'a_configure_sshd_command'
- 'b_configure_sshd_commanduser'
extras1:
commands:
a_enable_epel:
command: 'amazon-linux-extras enable epel=7.11'
test: "! grep -Fxq '[amzn2extra-epel]' /etc/yum.repos.d/amzn2-extras.repo"
extras2:
packages:
yum:
epel-release: []
config:
packages:
yum:
clamd: []
clamav: []
clamav-update: []
ruby: []
rubygems:
'aws-sdk-sqs': ['1.10.0']
'aws-sdk-sns': ['1.9.0']
'aws-sdk-s3': ['1.30.1']
daemons: ['1.2.6']
'rubysl-securerandom': ['2.0.0']
files:
'/opt/aws-s3-virusscan/daemon.rb':
content: |
#!/usr/bin/env ruby
require 'daemons'
Daemons.run(__dir__ + '/worker.rb', {:monitor => true, :log_output_syslog => true})
mode: '000744'
owner: root
group: root
'/opt/aws-s3-virusscan/worker.rb':
content: |
#!/usr/bin/env ruby
require 'aws-sdk-sqs'
require 'aws-sdk-sns'
require 'aws-sdk-s3'
require 'json'
require 'uri'
require 'yaml'
require 'syslog/logger'
require 'securerandom'
class ClamScanWorker
attr_reader :log, :conf, :sns, :tag_key, :clean_tag_set, :infected_tag_set
CLEAN_STATUS = 'clean'
INFECTED_STATUS = 'infected'
def initialize
@log = Syslog::Logger.new 's3-virusscan'
@conf = YAML::load_file(__dir__ + '/s3-virusscan.conf')
Aws.config.update(region: conf['region'])
@tag_key = conf['tag_key']
@clean_tag_set = {tag_set: [{key: tag_key, value: CLEAN_STATUS}]}
@infected_tag_set = {tag_set: [{key: tag_key, value: INFECTED_STATUS}]}
@sns = Aws::SNS::Client.new()
end
def perform
log.info "s3-virusscan started"
s3 = Aws::S3::Client.new()
poller = Aws::SQS::QueuePoller.new(conf['queue'])
poller.poll do |msg|
begin
body = JSON.parse(msg.body)
if body.key?('Records')
body['Records'].each do |record|
bucket = record['s3']['bucket']['name']
key = URI.decode(record['s3']['object']['key']).gsub('+', ' ')
fileName = "/tmp/#{SecureRandom.uuid}"
log.debug "scanning s3://#{bucket}/#{key}..."
begin
s3.get_object(
response_target: fileName,
bucket: bucket,
key: key
)
rescue Aws::S3::Errors::NoSuchKey
log.debug "s3://#{bucket}/#{key} does no longer exist"
next
end
begin
system("clamdscan #{fileName}")
exitstatus = $?.exitstatus
if exitstatus == 0 # No virus found.
if conf['report_clean']
publish_notification(bucket, key, CLEAN_STATUS);
else
log.debug "s3://#{bucket}/#{key} is clean"
end
if conf['tag_files']
s3.put_object_tagging({
bucket: bucket,
key: key,
tagging: clean_tag_set
})
end
elsif exitstatus == 1 # Virus(es) found.
publish_notification(bucket, key, INFECTED_STATUS);
if conf['delete']
s3.delete_object(
bucket: bucket,
key: key
)
log.debug "s3://#{bucket}/#{key} was deleted"
elsif conf['tag_files']
s3.put_object_tagging({
bucket: bucket,
key: key,
tagging: infected_tag_set
})
end
else # An error occured.
raise "s3://#{bucket}/#{key} could not be scanned, clamdscan exit status was #{exitstatus}, retry"
end
ensure
system("rm #{fileName}")
end
end
end
rescue Exception => e
log.error "message failed: #{e.inspect} #{msg.inspect}"
raise e
end
end
end
private
def publish_notification(bucket, key, status)
msg = "s3://#{bucket}/#{key} is #{status}"
if status == INFECTED_STATUS and conf['delete']
msg << ", deleting..."
end
log.debug msg
sns.publish(
topic_arn: conf['topic'],
message: msg,
subject: "s3-virusscan s3://#{bucket}",
message_attributes: {
"key" => {
data_type: "String",
string_value: key
},
"status" => {
data_type: "String",
string_value: status
}
}
)
end
end
# do some work
ClamScanWorker.new.perform
mode: '000744'
owner: root
group: root
'/opt/aws-s3-virusscan/s3-virusscan.conf':
content: !Sub |
delete: ${DeleteInfectedFiles}
report_clean: ${ReportCleanFiles}
tag_files: ${TagFiles}
tag_key: ${TagKey}
region: ${AWS::Region}
queue: ${ScanQueue}
topic: ${FindingsTopic}
mode: '000644'
owner: root
group: root
'/etc/init.d/s3-virusscan':
content: |
#!/usr/bin/env ruby
# chkconfig: - 80 20
APP_NAME = 's3-virusscan'
APP_PATH = '/opt/aws-s3-virusscan/daemon.rb'
case ARGV.first
when 'start'
puts "Starting #{APP_NAME}..."
system(APP_PATH, 'start')
exit($?.exitstatus)
when 'stop'
system(APP_PATH, 'stop')
exit($?.exitstatus)
when 'restart'
system(APP_PATH, 'restart')
exit($?.exitstatus)
when 'status'
system(APP_PATH, 'status')
exit($?.exitstatus)
end
unless %w{start stop restart status}.include? ARGV.first
puts "Usage: #{APP_NAME} {start|stop|restart|status}"
exit(1)
end
mode: '000755'
owner: root
group: root
'/etc/cfn/cfn-hup.conf':
content: !Sub |
[main]
stack=${AWS::StackId}
region=${AWS::Region}
interval=1
mode: '000400'
owner: root
group: root
'/etc/cfn/hooks.d/cfn-auto-reloader.conf':
content: !Sub |
[cfn-auto-reloader-hook]
triggers=post.update
path=Resources.ScanLaunchConfiguration.Metadata.AWS::CloudFormation::Init
action=/opt/aws/bin/cfn-init -v --stack ${AWS::StackName} --resource ScanLaunchConfiguration --region ${AWS::Region}
runas=root
commands:
a_enable_freshclam_cron:
command: 'sed -i "s/^FRESHCLAM_DELAY/#FRESHCLAM_DELAY/g" /etc/sysconfig/freshclam'
b_enable_freshclam:
command: 'sed -i "s/^Example/#Example/g" /etc/freshclam.conf'
c_prepare_local_sopcket:
command: 'mkdir /var/run/clamd.scan && chown clamscan:clamscan /var/run/clamd.scan'
test: '[ ! -d /var/run/clamd.scan ]'
d_enable_clamd_scan:
command: 'sed -i "s/^Example/#Example/g;s/^#LocalSocket /LocalSocket /g" /etc/clamd.d/scan.conf'
e_add_clamdscan_config:
command: 'ln -s /etc/clamd.d/scan.conf /etc/clamd.conf'
test: '[ ! -f /etc/clamd.conf ]'
f_update_clamav_db:
command: freshclam
services:
sysvinit:
's3-virusscan':
enabled: true
ensureRunning: true
files:
- '/opt/aws-s3-virusscan/daemon.rb'
- '/opt/aws-s3-virusscan/worker.rb'
- '/opt/aws-s3-virusscan/s3-virusscan.conf'
- '/etc/init.d/s3-virusscan'
'clamd@scan':
enabled: true
ensureRunning: true
packages:
yum:
- clamd
files:
- '/etc/clamd.conf'
amazon-ssm-agent:
enabled: !If [HasSystemsManagerAccess, true, false]
ensureRunning: !If [HasSystemsManagerAccess, true, false]
'cfn-hup':
enabled: true
ensureRunning: true
files:
- '/etc/cfn/cfn-hup.conf'
- '/etc/cfn/hooks.d/cfn-auto-reloader.conf'
Properties:
KeyName: !If [HasKeyName, !Ref KeyName, !Ref 'AWS::NoValue']
AssociatePublicIpAddress: true
EbsOptimized: false
BlockDeviceMappings:
- DeviceName: '/dev/xvda'
Ebs:
VolumeSize: !Ref VolumeSize
VolumeType: gp2
IamInstanceProfile: !Ref ScanInstanceProfile
ImageId: !FindInMap [RegionMap, !Ref 'AWS::Region', AMI]
InstanceType: !Ref InstanceType
SpotPrice: !If [HasSpotPrice, !Ref SpotPrice, !Ref 'AWS::NoValue']
SecurityGroups:
- !Ref ScanSecurityGroup
UserData:
'Fn::Base64': !Sub |
#!/bin/bash -ex
trap '/opt/aws/bin/cfn-signal -e 1 --stack ${AWS::StackName} --resource ScanAutoScalingGroup --region ${AWS::Region}' ERR
/opt/aws/bin/cfn-init -v --stack ${AWS::StackName} --resource ScanLaunchConfiguration --region ${AWS::Region}
/opt/aws/bin/cfn-signal -e 0 --stack ${AWS::StackName} --resource ScanAutoScalingGroup --region ${AWS::Region}
ScanSecurityGroup:
Type: 'AWS::EC2::SecurityGroup'
Properties:
GroupDescription: 'S3 VirusScan'
VpcId: {'Fn::ImportValue': !Sub '${ParentVPCStack}-VPC'}
ScanSecurityGroupInSSHBastion:
Type: 'AWS::EC2::SecurityGroupIngress'
Condition: HasSSHBastionSecurityGroup
Properties:
GroupId: !Ref ScanSecurityGroup
IpProtocol: tcp
FromPort: 22
ToPort: 22
SourceSecurityGroupId: {'Fn::ImportValue': !Sub '${ParentSSHBastionStack}-SecurityGroup'}
ScanSecurityGroupInAll:
Type: 'AWS::EC2::SecurityGroupIngress'
Condition: HasNotSSHBastionSecurityGroup
Properties:
GroupId: !Ref ScanSecurityGroup
IpProtocol: tcp
FromPort: 22
ToPort: 22
CidrIp: '0.0.0.0/0'
Outputs:
ScanQueueArn:
Description: 'The ARN of the Scan Queue.'
Value: !GetAtt 'ScanQueue.Arn'
Export:
Name: !Sub '${AWS::StackName}-ScanQueueArn'
ScanQueueName:
Description: 'The name of the Scan Queue.'
Value: !GetAtt 'ScanQueue.QueueName'
Export:
Name: !Sub '${AWS::StackName}-ScanQueueName'
ScanQueueUrl:
Description: 'The URL of the Scan Queue.'
Value: !Ref ScanQueue
Export:
Name: !Sub '${AWS::StackName}-ScanQueueUrl'
FindingsTopicArn:
Description: 'The ARN of the Findings Topic.'
Value: !Ref FindingsTopic
Export:
Name: !Sub '${AWS::StackName}-FindingsTopicArn'
FindingsTopicName:
Description: 'The name of the Findings Topic.'
Value: !GetAtt 'FindingsTopic.TopicName'
Export:
Name: !Sub '${AWS::StackName}-FindingsTopicName'