-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathawsCodeCommitConformityTemplateScanner.py
More file actions
118 lines (104 loc) · 4.72 KB
/
awsCodeCommitConformityTemplateScanner.py
File metadata and controls
118 lines (104 loc) · 4.72 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
#!/usr/bin/env python3
import os
import json
import urllib3
import datetime
import boto3
from botocore.config import Config
config = Config(
region_name = 'us-east-2'
)
def s3PutObj(fileName, fileObj, severityResponse):
print("--- S3 Put Object starts ---")
print(str(os.environ.get('S3_BUCKET_NAME')) + " - " + str(os.environ.get('S3_OBJECT_KEY')))
s3Client = boto3.client('s3', config=config)
# s3GetObjResponse = s3Client.get_object(
# Bucket="conformitytemplatescannerpublicbucket",
# Key="cloudformation-templates/event.json"
# )
# print("\n\n"+str(s3GetObjResponse["Body"].read()))
s3PutObjResponse = s3Client.put_object(
Bucket=str(os.environ.get('S3_BUCKET_NAME')),
Key=str(os.environ.get('S3_OBJECT_KEY'))+"/"+fileName,
Body=fileObj
)
print(str(s3PutObjResponse))
tempList = []
for severity in severityResponse.keys():
tempList.append({'Key': str(severity), 'Value': str(severityResponse[severity])})
s3PutObjTaggingResponse = s3Client.put_object_tagging(
Bucket=str(os.environ.get('S3_BUCKET_NAME')),
Key=str(os.environ.get('S3_OBJECT_KEY'))+"/"+fileName,
Tagging={
'TagSet': tempList
}
)
print(str(s3PutObjTaggingResponse))
def postConformityApi(ccApiKey, fileString):
headers = {
"Content-Type": "application/vnd.api+json",
"Authorization": "ApiKey " + ccApiKey
}
data = {
"data": {
"attributes": {
"type": "cloudformation-template",
"contents": fileString
}
}
}
http = urllib3.PoolManager()
r = http.request('POST', 'https://us-west-2-api.cloudconformity.com/v1/template-scanner/scan', headers=headers, body=json.dumps(data))
responseDict = json.loads(r.data)
reportDict = {}
for data in responseDict["data"]:
if data["type"] == "checks":
if str(data["attributes"]["risk-level"]) not in reportDict:
reportDict.update({ data["attributes"]["risk-level"]: 1 })
else:
reportDict.update({ data["attributes"]["risk-level"]: reportDict[data["attributes"]["risk-level"]] + 1 })
print(str(reportDict))
return reportDict
def processJsonFile(ccApiKey, fileName, fileString):
cfJsonDict = json.loads(fileString)
if "AWSTemplateFormatVersion" in cfJsonDict:
ccResponse = postConformityApi(ccApiKey, fileString)
# print(str(ccResponse))
s3PutObj(fileName, fileString, ccResponse)
def processYamlFile(ccApiKey, fileName, fileString):
if "AWSTemplateFormatVersion" in fileString:
ccResponse = postConformityApi(ccApiKey, fileString)
# print(str(ccResponse))
s3PutObj(fileName, fileString, ccResponse)
def lambda_handler(event, context):
ccApiKey = str(os.environ.get('CC_API_KEY'))
supportedFileExtensions = ["json", "yaml", "yml"]
print("\nEvent: " + str(event))
print("\nContext: " + str(context))
codeCommitClient = boto3.client('codecommit', config=config)
for record in event["Records"]:
# print(str(type(record["Sns"]["Message"])))
print(str(record["Sns"]["Message"]))
message = json.loads(record["Sns"]["Message"])
codeCommitGetDiffResponse = codeCommitClient.get_differences(
repositoryName=message["detail"]["repositoryName"],
beforeCommitSpecifier=message["detail"]["oldCommitId"],
afterCommitSpecifier=message["detail"]["commitId"]
)
# print(str(type(codeCommitGetDiffResponse)))
print(str(codeCommitGetDiffResponse))
for diff in codeCommitGetDiffResponse["differences"]:
codeCommitGetBlobResponse = codeCommitClient.get_blob(
repositoryName=message["detail"]["repositoryName"],
blobId=diff["afterBlob"]["blobId"]
)
# print(str(type(codeCommitGetBlobResponse)))
# print((codeCommitGetBlobResponse["content"]).decode("utf-8"))
if ccApiKey != "" and diff["afterBlob"]["path"].split(".")[-1].lower() in supportedFileExtensions:
if "afterBlob" in diff:
if diff["afterBlob"]["path"].split(".")[-1].lower() == "json":
processJsonFile(ccApiKey, diff["afterBlob"]["path"], (codeCommitGetBlobResponse["content"]).decode("utf-8"))
elif diff["afterBlob"]["path"].split(".")[-1].lower() == "yaml" or diff["afterBlob"]["path"].split(".")[-1].lower() == "yml":
processYamlFile(ccApiKey, diff["afterBlob"]["path"], (codeCommitGetBlobResponse["content"]).decode("utf-8"))
else:
print("Not a supported file.")