-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathdecryptor.py
More file actions
223 lines (194 loc) · 9.13 KB
/
Copy pathdecryptor.py
File metadata and controls
223 lines (194 loc) · 9.13 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
def _initializer() -> None:
import argparse
parser = argparse.ArgumentParser()
target_group = parser.add_mutually_exclusive_group(required=True)
target_group.add_argument('-d', '--dir', type=str, help='Specify target directory where obfuscated files are located')
target_group.add_argument('-f', '--file', type=str, help='Specify a single obfuscated target file')
parser.add_argument('-e', '--extension', type=str, required=False, help='Use together with the --dir option to filter out target files by extension')
parser.add_argument('-o', '--output', type=str, required=False, help='Output directory for deobfuscated files')
parser.add_argument('-l', '--dnlibpath', type=str, required=True, help='Specify where precompiled dnlib dependency is located')
parser.add_argument('-s', '--powershellpath', type=str, required=False, help='Optional powershell path argument. Used instead of dnlib for reflection')
parser.add_argument('-p', '--use-powershell', action='store_true', help='A flag to toggle usage of powershell instead of dnlib for reflection')
verbosity_group = parser.add_mutually_exclusive_group(required=False)
verbosity_group.add_argument('-q', '--quiet', action='store_true', help='A flag to toggle quiet mode')
verbosity_group.add_argument('-v', '--verbose', action='store_true', help='A flag to toggle verbose mode')
global args
args = parser.parse_args()
if __name__ == '__main__':
_initializer()
import clr
clr.AddReference(args.dnlibpath)
from dnlib.DotNet import *
from dnlib.DotNet.Emit import OpCodes, Instruction
import System
import subprocess
import os
import logging
import glob
def patch_string(instructions, index, decrypted_str, *str_instructions) -> int:
if len(str_instructions) != 3:
return 0
if str_instructions[0].GetSize() != 5:
return 0
str_instructions[0].OpCode = OpCodes.Ldstr
str_instructions[0].Operand = decrypted_str
nop_instruction = Instruction.Create(OpCodes.Nop)
nop_range = str_instructions[1].GetSize() + str_instructions[2].GetSize()
for _ in range(len(str_instructions) - 1):
instructions.RemoveAt(index+1)
for _ in range(nop_range):
instructions.Insert(index+1, nop_instruction)
return nop_range
def decrypt_i4_powershell(value, mdtoken, target, powershellpath) -> str:
loadfile = f' -Command "[Reflection.Assembly]::LoadFile(\'{target}\')'
resolve_method = f'.ManifestModule.ResolveMethod({mdtoken})'
invoke_method = f'.MakeGenericMethod([string]).Invoke($null, @({value}))"'
cmd = powershellpath + loadfile + resolve_method + invoke_method
p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
result = p.communicate()
try:
decrypted_str = result[0].decode()
new_line_carriage_return = -2
return decrypted_str[:new_line_carriage_return]
except UnicodeDecodeError as e:
logging.error(f'Failed to decode a string. {e}')
def decrypt_i4(value, mdtoken, target) -> str:
global args
if args.powershellpath is not None:
return decrypt_i4_powershell(value, mdtoken, target, args.powershellpath)
elif args.use_powershell:
return decrypt_i4_powershell(value, mdtoken, target, 'powershell.exe')
assembly = System.Reflection.Assembly.LoadFile(target)
module = assembly.ManifestModule
method = module.ResolveMethod(int(mdtoken, 16))
generic_method = method.MakeGenericMethod(System.Type.GetType("System.String"))
method_args = System.Array[System.Object]([System.Int32(int(value))])
decrypted_str = generic_method.Invoke(None, method_args)
return decrypted_str
def get_mdtoken_from_method(method_name, method_to_mdtoken) -> str:
for method in method_to_mdtoken:
if method_name in method:
return method_to_mdtoken[method]
def decrypt_strings(instructions, method_to_mdtoken, target) -> None:
i = 0
while i < len(instructions)-3:
instruction1 = instructions[i]
instruction2 = instructions[i+1]
instruction3 = instructions[i+2]
instruction3_str = instruction3.ToString()
# change the signature if a bug is encountered
if instruction1.OpCode.Code == OpCodes.Ldc_I4.Code and \
instruction2.OpCode.Code == OpCodes.Br_S.Code and \
instruction3.OpCode.Code == OpCodes.Call.Code and \
'System.String <Module>::' in instruction3_str:
method_name = instruction3_str.split(':')[3].split('<')[0]
mdtoken = get_mdtoken_from_method(method_name, method_to_mdtoken)
instruction1_val_str = str(instruction1.GetLdcI4Value())
decrypted_str = decrypt_i4(instruction1_val_str, mdtoken, target)
if decrypted_str is None: break
logging.debug(f'Decrypted the "{decrypted_str}" string')
offset = patch_string(
instructions,
i,
decrypted_str,
instruction1,
instruction2,
instruction3
)
if offset == 0:
logging.error(f'Failed to patch string instructions')
i += offset
i += 1
def patch_anticall(instructions, index, *anticall_instructions) -> None:
nop_instruction = Instruction.Create(OpCodes.Nop)
nop_range = 0
for anticall_instruction in anticall_instructions:
nop_range += anticall_instruction.GetSize()
for _ in range(len(anticall_instructions)):
instructions.RemoveAt(index)
for _ in range(nop_range):
instructions.Insert(index, nop_instruction)
def remove_anticall_protection(instructions) -> None:
i = 0
while i < len(instructions)-4:
instruction1 = instructions[i]
instruction2 = instructions[i+1]
instruction3 = instructions[i+2]
instruction4 = instructions[i+3]
# change the signature if a bug is encountered
if instruction1.OpCode.Code == OpCodes.Call.Code and \
instruction2.OpCode.Code == OpCodes.Call.Code and \
instruction3.OpCode.Code == OpCodes.Callvirt.Code and \
'GetExecutingAssembly' in instruction1.ToString() and \
'GetCallingAssembly' in instruction2.ToString():
patch_anticall(
instructions,
i,
instruction1,
instruction2,
instruction3,
instruction4
)
logging.debug(f'Removed anticall protection from a protected function')
break
i += 1
def process_target_module_decrypt(target) -> str:
out_path = target + '.decrypted'
module = ModuleDefMD.Load(target)
types = module.GetTypes()
method_to_mdtoken = {}
for type_ in types:
methods = type_.Methods
for method in methods:
method_to_mdtoken[method.ToString()] = '0x' + method.MDToken.ToString()
for method in methods:
if not method.HasBody: continue
instructions = method.Body.Instructions
decrypt_strings(instructions, method_to_mdtoken, target)
logging.debug(f'Writing patched DLL with decrypted strings to {out_path}')
module.Write(out_path)
return out_path
def process_target_module_anticall(target, output) -> str:
out_path = target + '.noanticall'
if output is not None:
out_path = output
out_path += '\\' if output[-1] != '\\' else ''
out_path += os.path.basename(target) + '.noanticall'
module = ModuleDefMD.Load(target)
types = module.GetTypes()
for type_ in types:
methods = type_.Methods
for method in methods:
if not method.HasBody: continue
instructions = method.Body.Instructions
remove_anticall_protection(instructions)
logging.debug(f'Writing patched DLL with no anticall protection to {out_path}')
module.Write(out_path)
return out_path
def log_setup():
log_level = logging.INFO
if args.quite:
log_level = logging.ERROR
elif args.verbose:
log_level = logging.DEBUG
logging.basicConfig(
level=log_level,
format='[%(levelname)s] %(message)s',
)
def main() -> None:
log_setup()
files = []
if args.file is not None:
files = [args.file]
elif args.dir is not None and args.extension is not None:
files = glob.glob(f"{args.dir}\\*{args.extension}")
elif args.dir is not None:
files = glob.glob(f"{args.dir}\\*")
for target in files:
logging.info(f'Processing {target}')
noanticall_dll_path = process_target_module_anticall(target, args.output)
logging.info(f'Successfully written patched DLL with no anticall protection to {noanticall_dll_path}')
decrypted_dll_path = process_target_module_decrypt(noanticall_dll_path)
logging.info(f'Successfully written patched DLL with decrypted strings to {decrypted_dll_path}')
if __name__ == '__main__':
main()