This repository was archived by the owner on Dec 9, 2025. It is now read-only.
Repository navigation
Expand file tree
/
Copy pathmalwexp
More file actions
executable file
·414 lines (315 loc) · 14.7 KB
/
Copy pathmalwexp
File metadata and controls
executable file
·414 lines (315 loc) · 14.7 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
#!/usr/local/bin/python3
from functools import reduce
from io import BytesIO
from pymongo import MongoClient
from pprint import pformat
from pyzipper import AESZipFile
import operator
import click
import json
import requests
import subprocess
from helpers import *
# mongodb database name
DB_NAME = "malwexp"
# bazaar api endpoint
url = "https://mb-api.abuse.ch/api/v1/"
# bazaar zpi encryption password
zip_pwd = b"infected"
db = MongoClient()[DB_NAME]
###############################################################################
# malwexp #
###############################################################################
@click.group(context_settings=dict(help_option_names=['-h', '--help']))
def malwexp():
"""
Interact with malwexp database.
This database stores malware metadata and experiments, for the A-team.
"""
pass
###############################################################################
# malware #
###############################################################################
@malwexp.group()
def malware():
"""
Interact with malwares inside malwexp database.
Malwares are documents in the database, with at least the following fields:
\b
- hashes, list of known hashes (md5, sha256, …) of the malware (at least one)
- date, estimated creation date of the malware, in YYYY-MM-DD format
- family, family the malware belongs to (e.g. wanacry)
- type, type of the malware (e.g. ransomware)
- platform, platform for which the malware is designed (e.g. win32)
- source, entity where the malware was found
- location, location where the malware can be retrieved for experiments
"""
pass
@malware.command()
@click.argument('files', nargs=-1, required=False, type=click.File('r'))
@click.option('-p', '--prompt', count=True, help="Prompt to create a document.")
@click.option('-f', '--force', is_flag=True, help="Skip confirmation prompt.")
@click.option('-q', '--quiet', is_flag=True, help="Hide debug ouptut text.")
def create(files, prompt, force, quiet):
"""
Create new malware documents in the database.
Parses all input FILES for one or more malwares described in JSON format.
"""
malwares = []
for file in files:
for malware in parse_file(file, validate_malware):
malwares.append(malware)
for _ in range(prompt):
malware = prompt_malware(quiet)
malwares.append(malware)
if len(malwares) == 0:
raise click.ClickException("nothing found.")
if not force:
if not quiet:
desc = f"{len(malwares)} malwares" if len(malwares) > 1 else "one malware"
click.echo(f"Adding {desc} to the database.")
click.confirm('Do you confirm?', abort=True)
db.malware.insert_many(malwares)
if not quiet:
desc = f"{len(malwares)} malwares" if len(malwares) > 1 else "one malware"
click.echo(f"Added {desc}.")
@malware.command()
@click.argument("hash")
@click.option('-o', '--output', type=click.File('w'), help="Output file to write result.")
@click.option('-q', '--quiet', is_flag=True, help="Hide debug ouptut text.")
def get(hash, output, quiet):
"""
Retrieve all malware documents corresponding to a given HASH.
"""
malwares = list(db.malware.find({"hash": hash}, {'_id': 0}))
if len(malwares) == 0:
raise click.ClickException("nothing found.")
if not quiet:
desc = f"{len(malwares)} malwares" if len(malwares) > 1 else "one malware"
click.echo(f"Found {desc}.")
string = json_str(malwares)
if output is None:
click.echo(string)
else:
output.write(string)
@malware.command()
@click.argument("hash")
@click.option('-f', '--force', is_flag=True, help="Skip confirmation prompt.")
@click.option('-q', '--quiet', is_flag=True, help="Hide debug ouptut text.")
def delete(hash, force, quiet):
"""
Delete all malware documents corresponding to a given HASH.
"""
count = db.malware.count_documents({"hash": hash})
if count == 0:
raise click.ClickException("nothing found.")
if not force:
if not quiet:
desc = f"{count} malwares" if count > 1 else "one malware"
click.echo(f"Deleting {desc} from the database.")
click.confirm('Do you confirm?', abort=True)
result = db.malware.delete_many({"hash": hash})
if not quiet:
desc = f"{result.deleted_count} malwares" if result.deleted_count > 1 else "one malware"
click.echo(f"Deleted {desc}.")
@malware.command()
@click.option('--all/--any', default=True, help="Get documents matching either all or at least one filter. Default behavior is all.")
@click.option('-f', '--filter', multiple=True, type=(str, str), help="Filter documents on a specified field. First parameter is the name of the field, and the second is the query for that field. Match all documents containing the query in their value for that field, ignoring case.")
@click.option('-c', '--creation', type=click.DateTime(['%Y-%m-%d']), help="Filter documents for a specific creation date.")
@click.option('-d', '--date', type=click.DateTime(['%Y-%m-%d']), help="Filter documents for a specific malware date.")
@click.option('-b', '--before', type=click.DateTime(['%Y-%m-%d']), help="Filter documents on the date field, matching all dates before and including this one.")
@click.option('-a', '--after', type=click.DateTime(['%Y-%m-%d']), help="Filter documents on the date field, matching all dates after and including this one.")
@click.option('-o', '--output', type=click.File('w'), help="Output file to write result.")
@click.option('-q', '--quiet', is_flag=True, help="Hide debug ouptut text.")
def search(all, filter, creation, date, before, after, output, quiet):
"""
Retrieve malware documents based on a set of filters.
"""
filters = get_filters(filter, creation, date, before, after, all)
malwares = list(db.malware.find(filters, {'_id': 0}))
if len(malwares) == 0:
raise click.ClickException("nothing found.")
if not quiet:
desc = f"{len(malwares)} malwares" if len(malwares) > 1 else "one malware"
click.echo(f"Found {desc}.")
# write as single object if only one
string = json_str(malwares if len(malwares) > 1 else malwares[0])
if output is None:
click.echo(string)
else:
output.write(string)
@malware.command()
@click.argument('hashes', nargs=-1, required=True)
@click.argument('field')
@click.argument('value')
@click.option('-q', '--quiet', is_flag=True, help="Hide debug ouptut text.")
def batch_update(hashes, field, value, quiet):
"""
Update all malwares from a list of HASHES to set FIELD to VALUE.
"""
if field in ["_id", "user", "creation", "hash", "date"]:
raise click.ClickException(f"cannot batch update {field} field.")
for hash in hashes:
malwares = list(db.malware.find({"hash": hash}, {'_id': 0}))
if len(malwares) == 0:
if not quiet:
click.echo(f"No malware found for {hash}.")
continue
db.malware.delete_many({"hash": hash})
for malware in malwares:
malware[field] = value
db.malware.insert_many(malwares)
if not quiet:
desc = f"{len(malwares)} malwares" if len(malwares) > 1 else "one malware"
click.echo(f"Updated {desc} for {hash}.")
###############################################################################
# experiment #
###############################################################################
@malwexp.group()
def experiment():
"""
Interact with experiments inside malwexp database.
Experiments are documents in the database, with at least the following fields:
\b
- authors, list of authors of the experiment
- samples, list of hashes of malwares used in the experiment
- date, date of the experiment, in YYYY-MM-DD format
- description, short description of the experiment
"""
pass
@experiment.command()
@click.argument('files', nargs=-1, required=False, type=click.File('r'))
@click.option('-p', '--prompt', count=True, help="Prompt to create a document.")
@click.option('-f', '--force', is_flag=True, help="Skip confirmation prompt.")
@click.option('-q', '--quiet', is_flag=True, help="Hide debug ouptut text.")
def create(files, prompt, force, quiet):
"""
Create new experiment documents in the database.
Parses all input FILES for one or more experiments described in JSON format.
"""
experiments = []
for file in files:
for experiment in parse_file(file, validate_experiment):
experiments.append(experiment)
for _ in range(prompt):
experiment = prompt_experiment(quiet)
experiments.append(experiment)
if len(experiments) == 0:
raise click.ClickException("nothing found.")
if not force:
if not quiet:
desc = f"{len(experiments)} experiments" if len(experiments) > 1 else "one experiment"
click.echo("Adding {desc} to the database.")
click.confirm('Do you confirm?', abort=True)
db.experiment.insert_many(experiments)
if not quiet:
desc = f"{len(experiments)} experiments" if len(experiments) > 1 else "one experiment"
click.echo(f"Added {desc}.")
@experiment.command()
@click.option('--all/--any', default=True, help="Get documents matching either all filters, or at least one filter. Default behavior is all.")
@click.option('-f', '--filter', multiple=True, type=(str, str), help="Filter documents on a specified field. First parameter is the name of the field, and the second is the query for that field. Match all documents containing the query in their value for that field, ignoring case.")
@click.option('-c', '--creation', type=click.DateTime(['%Y-%m-%d']), help="Filter documents for a specific creation date.")
@click.option('-d', '--date', type=click.DateTime(['%Y-%m-%d']), help="Filter documents for a specific experiment date.")
@click.option('-b', '--before', type=click.DateTime(['%Y-%m-%d']), help="Filter documents on the date field, matching all dates before and including this one.")
@click.option('-a', '--after', type=click.DateTime(['%Y-%m-%d']), help="Filter documents on the date field, matching all dates after and including this one.")
@click.option('-o', '--output', type=click.File('w'), help="Output file to write result.")
@click.option('-q', '--quiet', is_flag=True, help="Hide debug ouptut text.")
def search(all, filter, creation, date, before, after, output, quiet):
"""
Retrieve experiment documents based on a set of filters.
"""
filters = get_filters(filter, creation, date, before, after, all)
experiments = list(db.experiment.find(filters, {'_id': 0}))
if len(experiments) == 0:
raise click.ClickException("nothing found.")
if not quiet:
desc = f"{len(experiments)} experiments" if len(experiments) > 1 else "one experiment"
click.echo(f"Found {desc}.")
# write as single object if only one
string = json_str(experiments if len(experiments) > 1 else experiments[0])
if output is None:
click.echo(string)
else:
output.write(string)
###############################################################################
# bazaar #
###############################################################################
@malwexp.group()
def bazaar():
"""
Retrieve malware information and samples from bazaar.abuse.ch.
Information are converted to be compatible with malwexp database.
"""
pass
@bazaar.command()
@click.argument("hash")
@click.argument("output-dir", type=click.Path(exists=True, file_okay=False, writable=True))
@click.option('-q', '--quiet', is_flag=True, help="Hide debug ouptut text.")
def download(hash, output_dir, quiet):
"""
Download malware executable with a given HASH (sha256 only) from bazaar.
The retrieved file is stored in OUTPUT_DIR, with HASH as its name.
"""
form = { "query": "get_file", "sha256_hash": hash }
response = requests.post(url, data=form, timeout=(1, 10))
if response.status_code != 200:
raise click.ClickException("connection error.")
if response.headers['Content-Type'] != 'application/zip':
raise click.ClickException("nothing found.")
with AESZipFile(BytesIO(response.content)) as zipped:
zipped.extractall(output_dir, pwd=zip_pwd)
if not quiet:
click.echo(f"Download one malware executable.")
@bazaar.command()
@click.argument("hash")
@click.option('-o', '--output', type=click.File('w'), help="Output file to write result.")
@click.option('-q', '--quiet', is_flag=True, help="Hide debug ouptut text.")
def get(hash, output, quiet):
"""
Retrieve all malwares from bazaar corresponding to a given HASH.
"""
form = { "query": "get_info", "hash": hash }
response = requests.post(url, data=form).json()
if response["query_status"] != "ok":
raise click.ClickException("nothing found.")
malwares = []
for value in response["data"]:
malwares.append(bazaar_to_malwexp(value))
if not quiet:
desc = f"{len(malwares)} malwares" if len(malwares) > 1 else "one malware"
click.echo(f"Found {desc}.")
# write as single object if only one
string = json_str(malwares if len(malwares) > 1 else malwares[0])
if output is None:
click.echo(string)
else:
output.write(string)
@bazaar.command()
@click.argument("family")
@click.option('-l', '--limit', type=int, help="Number of malwares to retrieve.")
@click.option('-o', '--output', type=click.File('w'), help="Output file to write result.")
@click.option('-q', '--quiet', is_flag=True, help="Hide debug ouptut text.")
def search(family, limit, output, quiet):
"""
Retrieve recent malwares from bazaar corresponding to a given FAMILY.
"""
form = { "query": "get_siginfo", "signature": family, "limit": limit }
response = requests.post(url, data=form).json()
if response["query_status"] != "ok":
click.echo(response["query_status"])
raise click.ClickException("nothing found.")
malwares = []
for value in response["data"]:
malwares.append(bazaar_to_malwexp(value))
if not quiet:
desc = f"{len(malwares)} malwares" if len(malwares) > 1 else "one malware"
click.echo(f"Found {desc}.")
# write as single object if only one
string = json_str(malwares if len(malwares) > 1 else malwares[0])
if output is None:
click.echo(string)
else:
output.write(string)
###############################################################################
if __name__ == '__main__':
malwexp()