forked from de4dot/de4dot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFilesDeobfuscator.cs
393 lines (350 loc) · 12.8 KB
/
FilesDeobfuscator.cs
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
/*
Copyright (C) 2011-2015 [email protected]
This file is part of de4dot.
de4dot is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
de4dot is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with de4dot. If not, see <http://www.gnu.org/licenses/>.
*/
using System;
using System.IO;
using System.Collections.Generic;
using dnlib.DotNet;
using dnlib.DotNet.Writer;
using de4dot.code;
using de4dot.code.renamer;
using de4dot.code.deobfuscators;
using de4dot.code.AssemblyClient;
namespace de4dot.cui {
class FilesDeobfuscator {
Options options;
IDeobfuscatorContext deobfuscatorContext = new DeobfuscatorContext();
public class Options {
public ModuleContext ModuleContext { get; set; }
public IList<IDeobfuscatorInfo> DeobfuscatorInfos { get; set; }
public IList<IObfuscatedFile> Files { get; set; }
public IList<SearchDir> SearchDirs { get; set; }
public MetadataFlags MetadataFlags { get; set; }
public bool DetectObfuscators { get; set; }
public RenamerFlags RenamerFlags { get; set; }
public bool RenameSymbols { get; set; }
public bool ControlFlowDeobfuscation { get; set; }
public bool KeepObfuscatorTypes { get; set; }
public bool OneFileAtATime { get; set; }
public DecrypterType? DefaultStringDecrypterType { get; set; }
public List<string> DefaultStringDecrypterMethods { get; private set; }
public IAssemblyClientFactory AssemblyClientFactory { get; set; }
public Options() {
ModuleContext = new ModuleContext(TheAssemblyResolver.Instance);
DeobfuscatorInfos = new List<IDeobfuscatorInfo>();
Files = new List<IObfuscatedFile>();
SearchDirs = new List<SearchDir>();
DefaultStringDecrypterMethods = new List<string>();
RenamerFlags = RenamerFlags.RenameNamespaces |
RenamerFlags.RenameTypes |
RenamerFlags.RenameProperties |
RenamerFlags.RenameEvents |
RenamerFlags.RenameFields |
RenamerFlags.RenameMethods |
RenamerFlags.RenameMethodArgs |
RenamerFlags.RenameGenericParams |
RenamerFlags.RestorePropertiesFromNames |
RenamerFlags.RestoreEventsFromNames |
RenamerFlags.RestoreProperties |
RenamerFlags.RestoreEvents;
RenameSymbols = true;
ControlFlowDeobfuscation = true;
}
}
public class SearchDir {
public string InputDirectory { get; set; }
public string OutputDirectory { get; set; }
public bool SkipUnknownObfuscators { get; set; }
}
public FilesDeobfuscator(Options options) => this.options = options;
public void DoIt() {
if (options.DetectObfuscators)
DetectObfuscators();
else if (options.OneFileAtATime)
DeobfuscateOneAtATime();
else
DeobfuscateAll();
}
static void RemoveModule(ModuleDef module) => TheAssemblyResolver.Instance.Remove(module);
void DetectObfuscators() {
foreach (var file in LoadAllFiles(true)) {
RemoveModule(file.ModuleDefMD);
file.Dispose();
deobfuscatorContext.Clear();
}
}
void DeobfuscateOneAtATime() {
foreach (var file in LoadAllFiles()) {
int oldIndentLevel = Logger.Instance.IndentLevel;
try {
file.DeobfuscateBegin();
file.Deobfuscate();
file.DeobfuscateEnd();
Rename(new List<IObfuscatedFile> { file });
file.Save();
RemoveModule(file.ModuleDefMD);
TheAssemblyResolver.Instance.ClearAll();
deobfuscatorContext.Clear();
}
catch (Exception ex) {
Logger.Instance.Log(false, null, LoggerEvent.Warning, "Could not deobfuscate {0}. Use -v to see stack trace", file.Filename);
Program.PrintStackTrace(ex, LoggerEvent.Verbose);
}
finally {
file.Dispose();
Logger.Instance.IndentLevel = oldIndentLevel;
}
}
}
void DeobfuscateAll() {
var allFiles = new List<IObfuscatedFile>(LoadAllFiles());
try {
DeobfuscateAllFiles(allFiles);
Rename(allFiles);
SaveAllFiles(allFiles);
}
finally {
foreach (var file in allFiles) {
if (file != null)
file.Dispose();
}
}
}
IEnumerable<IObfuscatedFile> LoadAllFiles() => LoadAllFiles(false);
IEnumerable<IObfuscatedFile> LoadAllFiles(bool onlyScan) {
var loader = new DotNetFileLoader(new DotNetFileLoader.Options {
ModuleContext = options.ModuleContext,
PossibleFiles = options.Files,
SearchDirs = options.SearchDirs,
CreateDeobfuscators = () => CreateDeobfuscators(),
DefaultStringDecrypterType = options.DefaultStringDecrypterType,
DefaultStringDecrypterMethods = options.DefaultStringDecrypterMethods,
AssemblyClientFactory = options.AssemblyClientFactory,
DeobfuscatorContext = deobfuscatorContext,
ControlFlowDeobfuscation = options.ControlFlowDeobfuscation,
KeepObfuscatorTypes = options.KeepObfuscatorTypes,
MetadataFlags = options.MetadataFlags,
RenamerFlags = options.RenamerFlags,
CreateDestinationDir = !onlyScan,
});
foreach (var file in loader.Load())
yield return file;
}
class DotNetFileLoader {
Options options;
Dictionary<string, bool> allFiles = new Dictionary<string, bool>(StringComparer.OrdinalIgnoreCase);
Dictionary<string, bool> visitedDirectory = new Dictionary<string, bool>(StringComparer.OrdinalIgnoreCase);
public class Options {
public ModuleContext ModuleContext { get; set; }
public IEnumerable<IObfuscatedFile> PossibleFiles { get; set; }
public IEnumerable<SearchDir> SearchDirs { get; set; }
public Func<IList<IDeobfuscator>> CreateDeobfuscators { get; set; }
public DecrypterType? DefaultStringDecrypterType { get; set; }
public List<string> DefaultStringDecrypterMethods { get; set; }
public IAssemblyClientFactory AssemblyClientFactory { get; set; }
public IDeobfuscatorContext DeobfuscatorContext { get; set; }
public bool ControlFlowDeobfuscation { get; set; }
public bool KeepObfuscatorTypes { get; set; }
public MetadataFlags MetadataFlags { get; set; }
public RenamerFlags RenamerFlags { get; set; }
public bool CreateDestinationDir { get; set; }
}
public DotNetFileLoader(Options options) => this.options = options;
public IEnumerable<IObfuscatedFile> Load() {
foreach (var file in options.PossibleFiles) {
if (Add(file, false, true))
yield return file;
}
foreach (var searchDir in options.SearchDirs) {
foreach (var file in LoadFiles(searchDir))
yield return file;
}
}
bool Add(IObfuscatedFile file, bool skipUnknownObfuscator, bool isFromPossibleFiles) {
var key = Utils.GetFullPath(file.Filename);
if (allFiles.ContainsKey(key)) {
Logger.Instance.Log(false, null, LoggerEvent.Warning, "Ingoring duplicate file: {0}", file.Filename);
return false;
}
allFiles[key] = true;
int oldIndentLevel = Logger.Instance.IndentLevel;
try {
file.DeobfuscatorContext = options.DeobfuscatorContext;
file.Load(options.CreateDeobfuscators());
}
catch (NotSupportedException) {
return false; // Eg. unsupported architecture
}
catch (BadImageFormatException) {
if (isFromPossibleFiles)
Logger.Instance.Log(false, null, LoggerEvent.Warning, "The file isn't a .NET PE file: {0}", file.Filename);
return false; // Not a .NET file
}
catch (EndOfStreamException) {
return false;
}
catch (IOException) {
if (isFromPossibleFiles)
Logger.Instance.Log(false, null, LoggerEvent.Warning, "The file isn't a .NET PE file: {0}", file.Filename);
return false; // Not a .NET file
}
catch (Exception ex) {
Logger.Instance.Log(false, null, LoggerEvent.Warning, "Could not load file ({0}): {1}", ex.GetType(), file.Filename);
return false;
}
finally {
Logger.Instance.IndentLevel = oldIndentLevel;
}
var deob = file.Deobfuscator;
if (skipUnknownObfuscator && deob.Type == "un") {
Logger.v("Skipping unknown obfuscator: {0}", file.Filename);
RemoveModule(file.ModuleDefMD);
return false;
}
else {
Logger.n("Detected {0} ({1})", deob.Name, file.Filename);
if (options.CreateDestinationDir)
CreateDirectories(Path.GetDirectoryName(file.NewFilename));
return true;
}
}
IEnumerable<IObfuscatedFile> LoadFiles(SearchDir searchDir) {
DirectoryInfo di = null;
bool ok = false;
try {
di = new DirectoryInfo(searchDir.InputDirectory);
if (di.Exists)
ok = true;
}
catch (System.Security.SecurityException) {
}
catch (ArgumentException) {
}
if (ok) {
foreach (var filename in DoDirectoryInfo(searchDir, di)) {
var obfuscatedFile = CreateObfuscatedFile(searchDir, filename);
if (obfuscatedFile != null)
yield return obfuscatedFile;
}
}
}
IEnumerable<string> RecursiveAdd(SearchDir searchDir, IEnumerable<FileSystemInfo> fileSystemInfos) {
foreach (var fsi in fileSystemInfos) {
if ((int)(fsi.Attributes & System.IO.FileAttributes.Directory) != 0) {
foreach (var filename in DoDirectoryInfo(searchDir, (DirectoryInfo)fsi))
yield return filename;
}
else {
var fi = (FileInfo)fsi;
if (fi.Exists)
yield return fi.FullName;
}
}
}
IEnumerable<string> DoDirectoryInfo(SearchDir searchDir, DirectoryInfo di) {
if (!di.Exists)
return new List<string>();
if (visitedDirectory.ContainsKey(di.FullName))
return new List<string>();
visitedDirectory[di.FullName] = true;
FileSystemInfo[] fsinfos;
try {
fsinfos = di.GetFileSystemInfos();
}
catch (UnauthorizedAccessException) {
return new List<string>();
}
catch (IOException) {
return new List<string>();
}
catch (System.Security.SecurityException) {
return new List<string>();
}
return RecursiveAdd(searchDir, fsinfos);
}
IObfuscatedFile CreateObfuscatedFile(SearchDir searchDir, string filename) {
var fileOptions = new ObfuscatedFile.Options {
Filename = Utils.GetFullPath(filename),
ControlFlowDeobfuscation = options.ControlFlowDeobfuscation,
KeepObfuscatorTypes = options.KeepObfuscatorTypes,
MetadataFlags = options.MetadataFlags,
RenamerFlags = options.RenamerFlags,
};
if (options.DefaultStringDecrypterType != null)
fileOptions.StringDecrypterType = options.DefaultStringDecrypterType.Value;
fileOptions.StringDecrypterMethods.AddRange(options.DefaultStringDecrypterMethods);
if (!string.IsNullOrEmpty(searchDir.OutputDirectory)) {
var inDir = Utils.GetFullPath(searchDir.InputDirectory);
var outDir = Utils.GetFullPath(searchDir.OutputDirectory);
if (!Utils.StartsWith(fileOptions.Filename, inDir, StringComparison.OrdinalIgnoreCase))
throw new UserException($"Filename {fileOptions.Filename} does not start with inDir {inDir}");
var subDirs = fileOptions.Filename.Substring(inDir.Length);
if (subDirs.Length > 0 && subDirs[0] == Path.DirectorySeparatorChar)
subDirs = subDirs.Substring(1);
fileOptions.NewFilename = Utils.GetFullPath(Path.Combine(outDir, subDirs));
if (fileOptions.Filename.Equals(fileOptions.NewFilename, StringComparison.OrdinalIgnoreCase))
throw new UserException($"Input and output filename is the same: {fileOptions.Filename}");
}
var obfuscatedFile = new ObfuscatedFile(fileOptions, options.ModuleContext, options.AssemblyClientFactory);
if (Add(obfuscatedFile, searchDir.SkipUnknownObfuscators, false))
return obfuscatedFile;
obfuscatedFile.Dispose();
return null;
}
void CreateDirectories(string path) {
if (string.IsNullOrEmpty(path))
return;
try {
var di = new DirectoryInfo(path);
if (!di.Exists)
di.Create();
}
catch (System.Security.SecurityException) {
}
catch (ArgumentException) {
}
}
}
void DeobfuscateAllFiles(IEnumerable<IObfuscatedFile> allFiles) {
try {
foreach (var file in allFiles)
file.DeobfuscateBegin();
foreach (var file in allFiles) {
file.Deobfuscate();
file.DeobfuscateEnd();
}
}
finally {
foreach (var file in allFiles)
file.DeobfuscateCleanUp();
}
}
void SaveAllFiles(IEnumerable<IObfuscatedFile> allFiles) {
foreach (var file in allFiles)
file.Save();
}
IList<IDeobfuscator> CreateDeobfuscators() {
var list = new List<IDeobfuscator>(options.DeobfuscatorInfos.Count);
foreach (var info in options.DeobfuscatorInfos)
list.Add(info.CreateDeobfuscator());
return list;
}
void Rename(IEnumerable<IObfuscatedFile> theFiles) {
if (!options.RenameSymbols)
return;
var renamer = new Renamer(deobfuscatorContext, theFiles, options.RenamerFlags);
renamer.Rename();
}
}
}