-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy paths3-checksum.yaml
304 lines (262 loc) · 10.9 KB
/
s3-checksum.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
AWSTemplateFormatVersion: "2010-09-09"
Description: Template to setup auto-generation of checksums for objects uploaded onto Amazon S3
Parameters:
ChecksumAlgorithm:
Type: String
Default: SHA256
AllowedValues:
- CRC32
- CRC32C
- SHA1
- SHA256
Description: Select Checksum Algorithm. Default and recommended choice is SHA256, however CRC32, CRC32C, SHA1 are also available.
S3Bucket:
Type: String
Description: Enter the Amazon S3 bucket for setting up Checksums.
Resources:
ChecksumLambdaFunction:
Type: AWS::Lambda::Function
Properties:
Code:
ZipFile: |
import boto3
import os
from typing import Any, Tuple
s3_client = boto3.client('s3')
s3_resource = s3 = boto3.resource('s3')
def handler(event, context):
print(event)
bucket = event['Records'][0]['s3']['bucket']['name']
key = event['Records'][0]['s3']['object']['key']
print(f"Object {key} was just uploaded in Bucket {bucket}.")
copy_source = {
'Bucket': bucket,
'Key': key
}
attributes = get_attributes(bucket, key)
print(attributes)
checksum_attr = attributes.get('Checksum', None)
encryption_attr = attributes.get('Encryption', None)
# Only proceed if Checksums don't already exist
if checksum_attr == None:
print(f"Copying {key} to the same place but adding Checksum ...")
try:
# If using SSE-KMS
if 'EncryptionKey' in attributes:
s3_resource.meta.client.copy(
copy_source,
Bucket=bucket,
Key=key,
ExtraArgs={
'ChecksumAlgorithm':os.environ['Checksum'],
'StorageClass': attributes['StorageClass'],
'ServerSideEncryption': attributes['Encryption'],
'SSEKMSKeyId': attributes['EncryptionKey']
}
)
# If using SSE-S3
elif encryption_attr != None:
s3_resource.meta.client.copy(
copy_source,
Bucket=bucket,
Key=key,
ExtraArgs={
'ChecksumAlgorithm':os.environ['Checksum'],
'StorageClass': attributes['StorageClass'],
'ServerSideEncryption': attributes['Encryption']
}
)
# If not using any encryption - NOT RECOMMENDED
else:
print(os.environ['Checksum'])
s3_resource.meta.client.copy(
copy_source,
Bucket=bucket,
Key=key,
ExtraArgs={
'ChecksumAlgorithm':os.environ['Checksum'],
'StorageClass': attributes['StorageClass']
}
)
print(f"SUCCESS: {key} now has a {os.environ['Checksum']} Checksum ")
except Exception as e:
print(e)
raise
else:
print(f"{key} already has a Checksum; No further action needed!")
return
def object_has_checksum(get_object_attributes_response: Any) -> Tuple[Any, bool, str]:
keys_to_check = ['ChecksumSHA256', 'ChecksumCRC32', 'ChecksumCRC32C', 'ChecksumSHA1']
checksum = get_object_attributes_response.get('Checksum', None)
if checksum is None:
return checksum, False, None
for key in keys_to_check:
if key in checksum:
print(f"{key} exists in Checksum object within get_object_attributes response.")
return checksum, True, key
def get_attributes(bucket, key):
try:
attributes = {}
response = s3_client.get_object_attributes(
Bucket=bucket,
Key=key,
ObjectAttributes=[
'ETag',
'Checksum',
'ObjectParts',
'StorageClass',
'ObjectSize'
]
)
print(response)
storage_class = response.get('StorageClass', '')
attributes['StorageClass'] = storage_class
has_checksum = object_has_checksum(response)
checksum_pair = has_checksum[0]
if (has_checksum[1]):
attributes['Checksum'] = has_checksum[2]
# Check if the Object already has Checksums
print(f"Checking whether {key} already has Checksum ...")
if 'ChecksumCRC32' in checksum_pair:
print(f"{key} already has a CRC32 Checksum!")
elif 'ChecksumCRC32C' in checksum_pair:
print(f"{key} already has a CRC32C Checksum!")
elif 'ChecksumSHA1' in checksum_pair:
print(f"{key} already has a SHA1 Checksum!")
elif 'ChecksumSHA256' in checksum_pair:
print(f"{key} already has a SHA256 Checksum!")
else:
print(f"{key} does not have a Checksum!")
print(f"Obtaining other attributes for {key} ...")
#Check Object's storage class
print(f"Checking Storage Class for {key} ...")
if 'StorageClass' not in response:
print(f"{key} is stored in S3-STANDARD.")
attributes['StorageClass'] = 'STANDARD'
# Check Object's encryption
print(f"Checking Encryption for {key} ...")
if 'ServerSideEncryption' not in response:
print(f"{key} is not encrypted.")
attributes['Encryption'] = None
else:
print(f"{key} is encrypted.")
attributes['Encryption'] = response['ServerSideEncryption']
if response['ServerSideEncryption'] == 'aws:kms':
attributes['EncryptionKey'] = response['SSEKMSKeyId']
return attributes
except Exception as e:
print(e)
raise
Description: Function to add Checksums to objects in Amazon S3
Environment:
Variables:
Checksum: !Ref ChecksumAlgorithm
Handler: index.handler
Role: !GetAtt ChecksumLambdaRole.Arn
Runtime: python3.9
Timeout: 600
ReservedConcurrentExecutions: 10
Metadata:
cfn_nag:
rules_to_suppress:
- id: W89
reason: "The function does not process any data but merely copies it, hence VPC configuration is not needed."
ChecksumLambdaRole:
Type: 'AWS::IAM::Role'
Properties:
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal:
Service: 'lambda.amazonaws.com'
Action:
- 'sts:AssumeRole'
Path: '/'
ManagedPolicyArns:
- 'arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole'
Policies:
- PolicyName: S3Permissions
PolicyDocument:
Version: 2012-10-17
Statement:
- Sid: S3ReadWrite
Effect: Allow
Action:
- s3:PutObject
- s3:PutObjectTagging
- s3:PutObjectAcl
- s3:GetObject
- s3:GetObjectVersion
- s3:GetObjectTagging
- s3:GetObjectAcl
- s3:GetObjectAttributes
- s3:GetObjectVersionAttributes
- s3:ListBucket
Resource:
- !Sub 'arn:aws:s3:::${S3Bucket}/*'
- PolicyName: KMSPermissions
PolicyDocument:
Version: 2012-10-17
Statement:
- Sid: S3ReadWrite
Effect: Allow
Action:
- kms:Decrypt
- kms:Encrypt
- kms:GenerateDataKey
Resource:
- !Sub 'arn:aws:kms:${AWS::Region}:${AWS::AccountId}:key/*'
S3InvokeLambdaPermission:
Type: AWS::Lambda::Permission
Properties:
Action: lambda:InvokeFunction
FunctionName: !Ref ChecksumLambdaFunction
Principal: s3.amazonaws.com
SourceArn: !Sub arn:aws:s3:::${S3Bucket}
SourceAccount: !Ref 'AWS::AccountId'
S3BatchRole:
Type: 'AWS::IAM::Role'
Properties:
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal:
Service: 'batchoperations.s3.amazonaws.com'
Action:
- 'sts:AssumeRole'
Path: '/'
Policies:
- PolicyName: S3Permissions
PolicyDocument:
Version: 2012-10-17
Statement:
- Sid: S3ReadWrite
Effect: Allow
Action:
- s3:PutObject
- s3:PutObjectAcl
- s3:PutObjectTagging
- s3:GetObject
- s3:GetObjectVersion
- s3:GetObjectAcl
- s3:GetObjectTagging
- s3:ListBucket
- s3:InitiateReplication
- s3:GetReplicationConfiguration
- s3:PutInventoryConfiguration
Resource:
- !Sub 'arn:aws:s3:::${S3Bucket}/*'
- PolicyName: KMSPermissions
PolicyDocument:
Version: 2012-10-17
Statement:
- Sid: S3ReadWrite
Effect: Allow
Action:
- kms:Decrypt
- kms:Encrypt
- kms:GenerateDataKey
Resource:
- !Sub 'arn:aws:kms:${AWS::Region}:${AWS::AccountId}:key/*'