forked from dfir-it/unsapien
-
Notifications
You must be signed in to change notification settings - Fork 0
/
unsapien.py
504 lines (448 loc) · 17.7 KB
/
unsapien.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
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
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
#
# jj @dfir_it
#
# Extracts embedded scripts, files and configuration
# from binaries generated by SAPIEN Script Packager
# (available in PowerShell Studio or PrimalScript)
#
import os
import sys
import pefile
import argparse
import logging
from pbkdf2 import PBKDF2
from Crypto.Cipher import AES
from hashlib import sha256
from StringIO import StringIO
from zipfile import ZipFile
from hexdump import hexdump
from collections import OrderedDict
from distutils.dir_util import mkpath
from distutils.errors import DistutilsFileError
from construct import Seek, Struct, CString, Flag, Int32ul, Bytes
from construct import Adapter, this, Computed, GreedyRange, StreamError
# Key pairs found in binaries generated by SAPIEN Script Packager.
# Each binary uses a pair of keys:
# 1. Key to decrypt password embedded in configuartion (RCDATA ID 1)
# 2. Key to decrypt script, data and library files (RCDATA ID 2, 3, 4)
KEYS = [
("foobar", "hsdiafwiuera"),
("073E77D0D536421AA25BF60B16746B88", "BC373ACA27924EBEA29D2A22E348ACB4")
]
# Passwords are padded with 0s before or after encryption, depending
# on Script Packager version
class Password(Adapter):
def _decode(self, obj, context, path):
if all(ord(c) == 0 for c in obj):
return ""
else:
return obj.rstrip("\x00")
class Int2Bool(Adapter):
def _decode(self, obj, context, path):
return bool(obj)
# "Runmode" value designates which "alternate credentials" option will be used
# during runtime (if defined)
class Runmode(Adapter):
def _decode(self, obj, context, path):
return {
0: "Current user",
1: "Impersonate user",
2: "RunAs user"
}.get(obj, "Unknown value")
class Utf8(Adapter):
def _decode(self, obj, context, path):
return obj.encode("utf-8", "ignore")
# construct structures definig configuration layout.
# Majority of fields are named after corresponding variable names
# found in reversed binaries.
# Note: Not always fields present in configuration are parsed or used by
# generated executables.
CSTRUCT = {
800: Struct(
"Title" / Utf8(CString("ascii")),
Seek(128), "Initial Folder" / Utf8(CString("ascii")),
Seek(648), "Leave Data Files" / Int2Bool(Int32ul),
Seek(660), "Run CScript" / Int2Bool(Int32ul),
Seek(664), "Don't Wait For Child Process" / Int2Bool(Int32ul),
Seek(668), "Temp Location" / Int32ul,
Seek(672), "UserID" / Utf8(CString("ascii")),
Seek(736), "Password" / Password(Bytes(64))
),
1060: Struct(
"Title" / Utf8(CString("ascii")),
Seek(128), "Initial Folder" / Utf8(CString("ascii")),
Seek(648), "Script Engine" / Utf8(CString("ascii")),
Seek(908), "Leave Data Files" / Int2Bool(Int32ul),
Seek(920), "Dont Wait For Child Process" / Int2Bool(Int32ul),
Seek(924), "Temp Location" / Int32ul,
Seek(928), "UserID" / Utf8(CString("ascii")),
Seek(992), "Password" / Password(Bytes(68))
),
1064: Struct(
"Title" / Utf8(CString("ascii")),
Seek(128), "Initial Folder" / Utf8(CString("ascii")),
Seek(648), "Script Engine" / Utf8(CString("ascii")),
Seek(908), "Leave Data Files" / Int2Bool(Int32ul),
Seek(924), "Temp Location" / Int32ul,
Seek(928), "UserID" / Utf8(CString("ascii")),
Seek(992), "Password" / Password(Bytes(64)),
Seek(1056), "Alternate Credentials" / Int2Bool(Int32ul),
Seek(1060), "Trial Mode" / Int2Bool(Int32ul)
),
1340: Struct(
"Title" / Utf8(CString("ascii")),
Seek(128), "Initial Folder" / Utf8(CString("ascii")),
Seek(388), "COM Object Path" / Utf8(CString("ascii")),
Seek(648), "Script Engine" / Utf8(CString("ascii")),
Seek(908), "LeaveData Files" / Flag,
Seek(909), "Leave Script Files" / Flag,
Seek(910), "Leave COM Objects" / Flag,
Seek(911), "Run Parallel" / Flag,
Seek(912), "Folder Settings" / Int32ul,
Seek(928), "UserID" / Utf8(CString("ascii")),
Seek(992), "Password" / Password(Bytes(64)),
# "Login Method" is read from offset 1052 in analyzed binary but it
# overlaps with password field...
Seek(1056), "Login Method" / Int32ul,
Seek(1060), "Trial Mode" / Int2Bool(Int32ul),
Seek(1064), "MTA Mode" / Int2Bool(Int32ul),
Seek(1068), "Trial Mode Day" / Int32ul,
Seek(1072), "Trial Mode Month" / Int32ul,
Seek(1076), "Trial Mode Year" / Int32ul
),
2636: Struct(
"Title" / Utf8(CString("utf16")),
Seek(256), "Initial Folder" / Utf8(CString("utf16")),
Seek(776), "COM Object Path" / Utf8(CString("utf16")),
Seek(1296), "Script Engine" / Utf8(CString("utf16")),
Seek(1816), "Leave Data Files" / Flag,
Seek(1820), "Leave Script Files" / Flag,
Seek(1824), "Leave COM Objects" / Flag,
Seek(1828), "Run Parallel" / Flag,
Seek(1832), "Folder Settings" / Int32ul,
Seek(1836), "UserID" / Utf8(CString("utf16")),
Seek(1964), "Password" / Password(Bytes(64)),
Seek(2092), "Alternate Credentials" / Runmode(Int32ul),
Seek(2096), "Trial Mode" / Int2Bool(Int32ul),
Seek(2100), "MTA Mode" / Int2Bool(Int32ul),
Seek(2104), "Trial Mode Day" / Int32ul,
Seek(2108), "Trial Mode Month" / Int32ul,
Seek(2112), "Trial Mode Year" / Int32ul
),
5236: Struct(
"Title" / Utf8(CString("utf16")),
Seek(256), "Initial Folder" / Utf8(CString("utf16")),
Seek(776), "COM Object Path" / Utf8(CString("utf16")),
Seek(1296), "Script Engine" / Utf8(CString("utf16")),
Seek(1816), "Leave Data Files" / Flag,
Seek(1820), "Leave Script Files" / Flag,
Seek(1824), "Leave COM Objects" / Flag,
Seek(1828), "Run Parallel" / Flag,
Seek(1832), "Folder Settings" / Int32ul,
Seek(1836), "UserID" / Utf8(CString("utf16")),
Seek(1964), "Password" / Password(Bytes(64)),
Seek(2092), "Alternate Credentials" / Runmode(Int32ul),
Seek(2096), "Trial Mode" / Int2Bool(Int32ul),
Seek(2100), "Options" / Int32ul,
"MTA Mode" / Computed(this.Options & 1 == 1),
"Execution restrictions" / Computed(this.Options & 2 == 2),
"Allow only single instance" / Computed(this.Options & 4 == 4),
"Check EnableScriptBlockLogging" / Computed(this.Options & 8 == 8),
"Disable EnableScriptBlockLogging" / Computed(this.Options & 32 == 32),
"Disable EnableTranscripting" / Computed(this.Options & 64 == 64),
"Use AES" / Computed(this.Options & 512 == 512),
Seek(2104), "Trial Mode Day" / Int32ul,
Seek(2108), "Trial Mode Month" / Int32ul,
Seek(2112), "Trial Mode Year" / Int32ul,
Seek(2116), "Script name" / Utf8(CString("utf16")),
Seek(2636), "Allowed OS version" / Utf8(CString("utf16")),
Seek(3156), "Allowed users" / Utf8(CString("utf16")),
Seek(3676), "Allowed hostnames" / Utf8(CString("utf16")),
Seek(4196), "Allowed MAC addresses" / Utf8(CString("utf16")),
Seek(4716), "Allowed domains" / Utf8(CString("utf16")),
)
}
def parse_config(config_rcdata):
config = {}
try:
cstruct = CSTRUCT[len(config_rcdata)]
except KeyError:
print("ERROR: Configuration: Unknown structure.")
logger.info("[+] Raw configuration data:")
if args.verbose:
hexdump(config_rcdata)
try:
config = cstruct.parse(config_rcdata)
except (UnicodeDecodeError, StreamError) as e:
print("ERROR: Configuration parsing error: {0}".format(e))
logger.info("[+] Raw configuration data:")
if args.verbose:
hexdump(config_rcdata)
config = OrderedDict(config)
config.pop("_io", None)
return config
def decrypt_simple(rcdata, key):
result = ""
i = 0
while (i < len(rcdata)):
b = ord(rcdata[i])
b2 = ord(key[i % len(key)])
b = (b + 106) & 0xff
b = (b - b2) & 0xff
if (i % 5) != 0:
b = (b + 2) & 0xff
if (i % 7) != 0:
b = (b - 9) & 0xff
if (i % 3) != 0:
b = (b + 3) & 0xff
b = (~ b) & 0xff
b = (b - 27) & 0xff
result += chr(b)
i += 1
return decode(result)
# Never tested - I have yet to see a sample using "high encryption pack" (AES)
def decrypt_aes(rcdata, key):
hash1 = sha256(key).digest()
hash2 = sha256(hash1).digest()
d = PBKDF2(hash2, hash2, 1000)
key = d.read(32)
iv = d.read(16)
aes = AES.new(key, AES.MODE_CBC, iv)
script_data = aes.decrypt(rcdata)
return decode(script_data)
def unzip(data):
files = {}
data = StringIO(data)
z = ZipFile(data)
for name in z.namelist():
files[name] = z.read(name)
return files
def decode(data):
# UTF-16 BOM: U+FEFF
if data[:2] == "\xff\xfe":
return data.decode("utf-16").encode("utf-8", "ignore")
# UTF-8 BOM: 0xEF,0xBB,0xBF
elif data[:3] == "\xef\xbb\xbf":
return data.decode("utf-8-sig").encode("utf-8", "ignore")
else:
return data
def get_sha(data):
return sha256(data).hexdigest()
# Extract files from data or library resource.
# File name field size ("nsize") can designate number or characters or
# number of bytes in file name ("name"), depending on packager version.
def get_files(data):
files = {}
fstruct = GreedyRange(
Struct(
"dsize" / Int32ul,
"nsize" / Int32ul,
"name" / Bytes(256),
"fdata" / Bytes(this.dsize),
)
)
fdata = fstruct.parse(data)
for file in fdata:
if file["nsize"] > 1 and ord(file["name"][1]) == 0:
filename = CString("utf16").parse(file["name"])
else:
filename = CString("ascii").parse(file["name"])
filename = filename.encode("ascii", "ignore")
files[filename] = file["fdata"]
return files
def write_file(dir, filename, content):
path = os.path.join(os.path.abspath(dir), filename)
logger.info("[+] Saving content of {0} to: {1}".format(filename, path))
try:
with open(path, "wb") as f:
f.write(content)
except (IOError, OSError) as e:
print("ERROR: {0}".format(e))
if __name__ == "__main__":
argparser = argparse.ArgumentParser(
description="""Extracts embedded scripts, files and configuration """
"""from binaries generated by SAPIEN Script Packager """
"""(available in PowerShell Studio or PrimalScript) """
)
argparser.add_argument("file", type=str, help="Input file")
argparser.add_argument(
"-v",
"--verbose",
help="Enable verbose output",
action="store_true", default=False
)
argparser.add_argument(
"-d",
"--dump",
type=str,
metavar="directory",
help="Dump files to specified directory",
action="store",
default=False
)
args = argparser.parse_args()
if args.verbose:
logging.basicConfig(
level=logging.INFO,
stream=sys.stdout,
format="%(message)s"
)
logger = logging.getLogger(__file__)
try:
pe = pefile.PE(args.file)
except (IOError, OSError, pefile.PEFormatError) as e:
print("ERROR: {0}".format(e))
sys.exit()
logger.info("[+] Analyzing file: {0}".format(args.file))
dump_files = False
if args.dump:
try:
mkpath(args.dump)
except DistutilsFileError as e:
print("ERROR: Unable to create specified directory: {0}".format(e))
sys.exit()
dump_files = True
config_key = ""
script_key = ""
# Iterate through PE sections and try to identify known decryption keys.
# This makes sure we are dealing with a binary generated by
# one of SAPIEN tools.
for section in pe.sections:
n = section.Name.rstrip("\x00")
if n in [".text", ".rdata", ".data"]:
section_data = section.get_data()
for key_pair in KEYS:
if all(section_data.find(k) >= 0 for k in key_pair):
config_key, script_key = key_pair
logger.info(
"[+] Config key: {0} [{1}]".format(config_key, n)
)
logger.info(
"[+] Data key: {0} [{1}]".format(script_key, n)
)
if not (config_key and script_key):
print("ERROR: Could not find decryption keys in the provided file")
sys.exit()
config_rcdata = ""
library_rcdata = ""
file_rcdata = ""
script_rcdata = ""
# Iterate through RCDATA resources and try to obtain raw data containing:
# - Configuration [RCDATA ID 1]
# - Library files (WSC/COM objects) [RCDATA ID 2]
# - Data files (additional files required by script) [RCDATA ID 3]
# - Script (PowerShell, VBS, JScript, HTA, etc.) [RCDATA ID 4]
for entry in pe.DIRECTORY_ENTRY_RESOURCE.entries:
if entry.id == pefile.RESOURCE_TYPE["RT_RCDATA"]:
for e in entry.directory.entries:
rva = e.directory.entries[0].data.struct.OffsetToData
size = e.directory.entries[0].data.struct.Size
rcdata = pe.get_data(rva, size)
if e.id == 1:
config_rcdata = rcdata
logger.info(
"[+] Found RCDATA 1 (configuration) [{0}]".format(size)
)
elif e.id == 2:
library_rcdata = rcdata
logger.info(
"[+] Found RCDATA 2 (library files) [{0}]".format(size)
)
elif e.id == 3:
file_rcdata = rcdata
logger.info(
"[+] Found RCDATA 3 (data files) [{0}]".format(size)
)
elif e.id == 4:
script_rcdata = rcdata
logger.info(
"[+] Found RCDATA 4 (script) [{0}]".format(size)
)
# By default "decrypt_simple" function is used to decrypt
# embedded credentials, scripts and files
decrypt = decrypt_simple
# Parse and print configuration data
if config_rcdata:
config = parse_config(config_rcdata)
if config:
if config["Password"]:
config["Password"] = decrypt(config["Password"], config_key)
config["Password"] = config["Password"].rstrip("\x00")
print("Configuration:")
for k, v in config.items():
print("{0:33}: {1}".format(k, v))
else:
print("ERROR: Configuration resource not found or is empty.")
# Assuming configuration resource is mandatory
sys.exit()
# AES based encryption is available only in "high encryption pack"
# (https://www.sapien.com/forums/viewtopic.php?t=11191)
if "Use AES" in config and config["Use AES"]:
logger.info("[+] Using AES.")
decrypt = decrypt_aes
# Decrypt, parse and print script(s)
if script_rcdata:
scripts = {}
script_data = decrypt(script_rcdata, script_key)
if script_data[0:4] == "PK\x03\x04":
logger.info("[+] Script is compressed, unzipping...")
scripts = unzip(script_data)
elif all(ord(c) == 0 for c in script_data[-8:]):
# I found only one script packaged this way - format follows
# data/library files format but file size is totally off:
logger.info("[+] Script contains broken metadata...")
name = CString("utf16").parse(script_data[8:8+256])
script = CString("utf16").parse(script_data[8+256:-16]+"\x00\x00")
scripts[name] = script
else:
if "Script name" in config and config["Script name"]:
name = config["Script name"]
elif "Title" in config and config["Title"]:
name = config["Title"]
else:
name = "unknown"
scripts[name] = script_data
for name, content in scripts.items():
h = get_sha(content)
print("\nScript: {0} [{1}]".format(name, h))
print(content)
if dump_files:
write_file(args.dump, name, content)
else:
print("ERROR: Script resource not found or is empty.")
# Assuming script resource is mandatory
sys.exit()
# Decrypt, parse and print data file(s)
if file_rcdata:
dfiles = {}
logger.info("[+] Processing data files")
data_files = decrypt(file_rcdata, script_key)
if data_files[0:4] == "PK\x03\x04":
logger.info("[+] Data files are compressed")
dfiles = unzip(data_files)
else:
dfiles = get_files(data_files)
for name, content in dfiles.items():
h = get_sha(content)
print("\nData file: {0} [{1}]".format(name, h))
hexdump(content[:128])
if dump_files:
write_file(args.dump, name, content)
# Decrypt, parse and print library file(s)
if library_rcdata:
lfiles = {}
logger.info("[+] Processing library files")
library_files = decrypt(library_rcdata, script_key)
if library_files[0:4] == "PK\x03\x04":
logger.info("[+] Library files are compressed")
lfiles = unzip(library_files)
else:
lfiles = get_files(library_files)
for name, content in lfiles.items():
h = get_sha(content)
print("\nLibrary file: {0} [{1}]".format(name, h))
hexdump(content[:128])
if dump_files:
write_file(args.dump, name, content)