-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhandler.py
246 lines (155 loc) · 6.36 KB
/
handler.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
#!/usr/bin/env python3
import json
import zipfile
# import tarfile
# import gzip
import time
import rarfile
import os
import urllib3
import urllib.request
import urllib.parse
from bs4 import BeautifulSoup
import random
import logging
import boto3
logger = logging.getLogger()
logger.setLevel(logging.INFO)
def emptyDir(dirPath):
# Empty /tmp folder for first time use
for fileName in os.listdir(dirPath):
os.remove(dirPath + fileName)
def zipDir(fileNames, dirPath, filePath):
# Write a new zipfile without password
with zipfile.ZipFile(filePath, 'w') as zipFile:
for fileName in fileNames:
zipFile.write(dirPath + "/" + fileName)
zipFile.close()
print("Zip successful")
def deleteFileWithFilePath(filePath):
print("Deleting", filePath, "...")
# Delete password protected zipfile
os.remove(filePath)
def randomChoiceDict(srcDict):
return random.choice(list(srcDict.items()))
def randomChoiceList(srcList):
return random.choice(srcList)
def getfile(http):
files_url = "http://www.tekdefense.com/downloads/malware-samples/"
download_base_url = "http://www.tekdefense.com"
r = http.request('GET', files_url)
parsed_html = BeautifulSoup(r.data, 'html.parser')
tempList = parsed_html.body.find_all('h3', attrs={'class': 'title'})
linksDict = {}
for link in tempList:
linksDict.update({link.text: download_base_url + urllib.parse.quote(link.find('a').get("href"))})
tempDict = {}
for link in linksDict.keys():
if ".exe.zip" not in link:
tempDict.update({link: linksDict[link]})
return randomChoiceDict(tempDict)
def zipRepack(zipPassword, dirPath, fileName, filePath):
with zipfile.ZipFile(filePath) as zipFile:
zipFile.extractall(pwd=bytes(zipPassword, 'utf-8'), path=dirPath)
deleteFileWithFilePath(filePath=filePath)
# fileNames = os.listdir(dirPath)
# print("Directory - " + str(fileNames))
# # if fileName in fileNames:
# # fileNames.remove(fileName)
# zipDir(fileNames, dirPath, filePath)
# def tarRepack(dirPath, fileName):
# tar = tarfile.open(dirPath + fileName)
# names = tar.getnames()
# temp_file_path = ''
# if os.path.isdir(dirPath + fileName + "_files"):
# print('file already exist')
# temp_file_path = os.path.isdir(dirPath + fileName + "_files")
# else:
# temp_file_path = os.mkdir(dirPath + fileName + "_files")
# print('Create a new filename')
# # Because there are many files after decompression, a directory with the same name should be established in advance
# for name in names:
# tar.extract(name, dirPath + fileName + "_files/")
# tar.close()
# return temp_file_path
# def gzipRepack(fileName):
# f_name = fileName.replace(".gz", "")
# # Get the name of the file, remove
# g_file = gzip.GzipFile(fileName)
# # Create gzip object
# f = open(f_name, "w+").write(g_file.read())
# # After the gzip object is opened with read(), it is written into the file created by open().
# g_file.close()
def rarRepack(zipPassword, dirPath, fileName, filePath):
with rarfile.Rarfile(dirPath + fileName) as file:
file.extractall(pwd=zipPassword)
file.close()
deleteFileWithFilePath(filePath=filePath)
# fileNames = os.listdir(dirPath)
# zipDir(fileNames, dirPath, filePath)
def repackWithoutPassword(fileExtension, zipPassword, dirPath, fileName, filePath):
if "zip" in fileExtension:
zipRepack(zipPassword, dirPath, fileName, filePath)
elif "tar" in fileExtension:
rarRepack(zipPassword, dirPath, fileName, filePath)
elif "gz" in fileExtension:
rarRepack(zipPassword, dirPath, fileName, filePath)
elif "rar" in fileExtension:
rarRepack(zipPassword, dirPath, fileName, filePath)
else:
raise Exception("Unrecognized file extension: The file is not a zip, tar, tar.gz, rar.")
def s3WriteToFile(regionName, s3BucketName, dirPath, fileName):
s3Client = boto3.client('s3', region_name=regionName)
s3PutObjectResponse = s3Client.put_object(
Bucket=s3BucketName,
Key=fileName,
Body=open(dirPath + "/" + fileName, 'rb'),
ServerSideEncryption='AES256',
StorageClass='REDUCED_REDUNDANCY'
)
print("\ns3PutObjectResponse - " + str(s3PutObjectResponse))
# time.sleep(3)
waiter = s3Client.get_waiter('object_exists')
waiter.wait(
Bucket=s3BucketName,
Key=fileName
)
print("\nS3 ObjectExists!")
return s3PutObjectResponse
def antimalwaretest(regionName, s3IngestBucketName):
userAgent = {'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.2 Safari/605.1.15'}
http = urllib3.PoolManager(5, headers=userAgent)
file = getfile(http)
fileName = file[0]
fileUrl = file[1]
zipPassword = 'infected'
# Attempt to download the various eicar test files
print("---Running Anti-Malware Test---")
print("Downloading Malware -", fileUrl)
# Building a new filePath
dirPath = "/tmp/"
filePath = dirPath + fileName
# Empty /tmp folder for first time use
emptyDir(dirPath)
# Download file to custom filePath
urllib.request.urlretrieve(fileUrl, filePath)
fileExtension = fileName.split(".")[-1].lower()
repackWithoutPassword(fileExtension, zipPassword, dirPath, fileName, filePath)
for fileName in os.listdir(dirPath):
s3WriteToFile(regionName, s3IngestBucketName, dirPath, fileName)
print("Remove all Malware Files")
emptyDir(dirPath)
def main(event, context):
regionName = str(os.environ.get("awsRegion"))
s3IngestBucketName = str(os.environ.get("s3IngestBucketName"))
if s3IngestBucketName[-1] == ",":
s3IngestBucketName = s3IngestBucketName[:-1].replace(" ", "").split(",")
else:
s3IngestBucketName = s3IngestBucketName.replace(" ", "").split(",")
print("Target S3 Bucket:", str(randomChoiceList(s3IngestBucketName)))
antimalwaretest(regionName, randomChoiceList(s3IngestBucketName))
body = {
"message": "Go FSS-MalwareTest! Your function executed successfully!",
"input": event
}
return {"statusCode": 200, "body": json.dumps(body)}