Skip to content

Commit eea1416

Browse files
committed
organized code, using pathlib instead of string, using pyzipper instead of pyminizip, etc.
1 parent df693dd commit eea1416

File tree

1 file changed

+100
-71
lines changed

1 file changed

+100
-71
lines changed

prep_file.py

+100-71
Original file line numberDiff line numberDiff line change
@@ -1,84 +1,113 @@
1-
#!/usr/bin/python
1+
#!/usr/bin/env python3
2+
# -*- coding: utf-8 -*-
3+
"""
4+
Name: Prep File
5+
Author: ytisf
6+
Date of Creation: Unknown
7+
Last Modified: May 26, 2019
28
3-
import os
4-
import sys
9+
Dev: K4YT3X
10+
Last Modified: August 21, 2019
11+
12+
Licensed under the GNU General Public License Version 3 (GNU GPL v3),
13+
available at: https://www.gnu.org/licenses/gpl-3.0.txt
14+
(C) 2014-2019 ytisf
15+
"""
16+
17+
# built-in imports
518
import hashlib
19+
import pathlib
20+
import sys
21+
import time
22+
import traceback
623

724
try:
8-
import pyminizip
9-
except ImportError:
10-
sys.stderr.write("Could not import 'pyminizip'. Did you install requirements?\n")
11-
sys.stderr.write("You can always just get 'pyminizip' by 'pip install --user pyminizip'.\n")
12-
sys.exit(1)
25+
import pyzipper
26+
except ImportError as e:
27+
print('Could not import "pyzipper". Did you install requirements?', file=sys.stderr)
28+
print('You can always just get "pyzipper" by "pip install --user pyzipper"', file=sys.stderr)
29+
raise e
1330

1431

15-
OUTPUT_FOLDER = "OUTPUT"
32+
COMPRESSION_PASSWORD = 'infected'
33+
OUTPUT_FOLDER = pathlib.Path('OUTPUT')
1634

1735

18-
def _help():
19-
"""
20-
hmmmm. nope.
21-
:return:
36+
def print_help():
37+
""" print help message
38+
39+
print program help message and return None
2240
"""
23-
print("Please run with '%s filename'." % sys.argv[0])
41+
print(f'usage: {__file__} [INPUT_FILE]')
2442
return
2543

2644

27-
def _Do(file_path):
28-
"""
29-
Prep file from file path for submission. Take file name, encrypt in ZIP with password 'infected', create MD5
30-
and SHA1 sums and store all of that in a directory of it's own.
31-
:param file_path: str
32-
:return: Bool
45+
def prepare_file(file_path):
46+
""" prep file from file path for submission
47+
48+
take file name, encrypt in ZIP with password 'infected', create MD5
49+
and SHA1 sums and store all of that in a directory of it's own
50+
51+
Arguments:
52+
file_path {pathlib.Path} -- path object of input file
3353
"""
34-
if not os.path.isfile(file_path):
35-
_help()
36-
sys.stderr.write("Seems like '%s' is not a file.\n" % file_path)
37-
return False
38-
39-
try:
40-
os.mkdir(OUTPUT_FOLDER)
41-
except OSError:
42-
sys.stderr.write("Folder exists. Please remove it before continuing.\n")
43-
return False
44-
45-
if "\\" in file_path:
46-
filename = file_path.split("\\")[:-1]
47-
elif "/" in file_path:
48-
filename = file_path.split("/")[:-1]
49-
else:
50-
filename = file_path
51-
52-
# Create ZIP Archive:
53-
# We used 7z because 'zipfile' did not support adding a password. Apparently 'pyminizip' works just as well.
54-
try:
55-
pyminizip.compress(file_path, OUTPUT_FOLDER, "%s.zip" % filename, "infected", 9)
56-
except Exception as e:
57-
sys.stderr.write("Unknown error occurred. Please report this to us so that we can fix this.\n")
58-
sys.stderr.write(str(e))
59-
return False
60-
61-
compressed_path = '%s/%s.zip' % (OUTPUT_FOLDER, filename)
62-
sys.stdout.write("[+]\tCreated ZIP Archive.\n")
63-
md5sum = hashlib.md5(open(compressed_path, 'rb').read()).hexdigest()
64-
sha1sum = hashlib.sha1(open(compressed_path, 'rb').read()).hexdigest()
65-
open("%s/%s.md5" % (OUTPUT_FOLDER, filename), 'w').write(md5sum)
66-
open("%s/%s.sha" % (OUTPUT_FOLDER, filename), 'w').write(sha1sum)
67-
open("%s/%s.pass" % (OUTPUT_FOLDER, filename), 'w').write("infected")
68-
return True
69-
70-
71-
if __name__ == "__main__":
72-
if len(sys.argv) != 2:
73-
_help()
74-
sys.exit(1)
75-
stt = _Do(sys.argv[1])
76-
if stt:
77-
sys.stdout.write("Please don't forget to add details to 'conf/maldb.db' "
78-
"and placing the folder in the appropriate directory.\n")
79-
sys.stdout.write("Thanks for helping us get this accessible to everyone.\n")
80-
sys.stdout.write("\n")
81-
sys.exit(0)
82-
else:
83-
sys.exit(1)
84-
54+
OUTPUT_FOLDER.mkdir(parents=True, exist_ok=True)
55+
56+
# create ZIP Archive
57+
# we are using 7z because "zipfile" did not support adding a password
58+
# Apparently "pyminizip" works just as well.
59+
print('Info: Creating encrypted ZIP archive')
60+
with pyzipper.AESZipFile(OUTPUT_FOLDER / f'{file_path.name}.zip', 'w', compression=pyzipper.ZIP_LZMA, encryption=pyzipper.WZ_AES) as zip_file:
61+
zip_file.setpassword(COMPRESSION_PASSWORD.encode())
62+
zip_file.write(file_path)
63+
print('Info: Created ZIP archive')
64+
65+
# calculating file hashes
66+
md5sum = hashlib.md5(open(OUTPUT_FOLDER / f'{file_path.name}.zip', 'rb').read()).hexdigest()
67+
sha1sum = hashlib.sha1(open(OUTPUT_FOLDER / f'{file_path.name}.zip', 'rb').read()).hexdigest()
68+
69+
# writing file hashes and password to files
70+
open(OUTPUT_FOLDER / f'{file_path.name}.md5', 'w').write(md5sum)
71+
open(OUTPUT_FOLDER / f'{file_path.name}.sha', 'w').write(sha1sum)
72+
open(OUTPUT_FOLDER / f'{file_path.name}.pass', 'w').write(COMPRESSION_PASSWORD)
73+
74+
75+
# start timer
76+
start_time = time.time()
77+
78+
# if this file is being imported
79+
if __name__ != '__main__':
80+
print('Error: This file cannot be imported', file=sys.stderr)
81+
ImportError('File not importable')
82+
83+
# check if there's a right amount of arguments provided
84+
if len(sys.argv) != 2:
85+
print_help()
86+
exit(1)
87+
88+
# convert input file path into file object
89+
try:
90+
input_file = pathlib.Path(sys.argv[1])
91+
except Exception:
92+
print('Error: input file format invalid', file=sys.stderr)
93+
94+
# input file validity check
95+
if not input_file.is_file():
96+
print_help()
97+
print(f'Seems like {str(input_file)} is not a file', file=sys.stderr)
98+
exit(1)
99+
100+
# zip file
101+
try:
102+
prepare_file(input_file)
103+
except Exception:
104+
print('Unexpected exception has been caught')
105+
print('Compression has failed')
106+
print('Please report the following error message to us so we can fix it')
107+
traceback.print_exc()
108+
exit(1)
109+
110+
print('Script finished')
111+
print(f'Time taken: {round((time.time() - start_time), 5)} seconds')
112+
print('Please don\'t forget to add details to "conf/maldb.db" and placing the folder in the appropriate directory')
113+
print('Thanks for helping us to get this accessible to everyone')

0 commit comments

Comments
 (0)