de4dot-cex/de4dot.code/deobfuscators/dotNET_Reactor/v4/Deobfuscator.cs

725 lines
23 KiB
C#
Raw Normal View History

2011-10-25 01:44:49 +08:00
/*
2015-10-30 05:45:26 +08:00
Copyright (C) 2011-2015 de4dot@gmail.com
2011-10-25 01:44:49 +08:00
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;
2011-10-25 01:44:49 +08:00
using System.Collections.Generic;
using System.IO;
2011-11-10 07:47:22 +08:00
using System.Text.RegularExpressions;
using dnlib.PE;
using dnlib.DotNet;
using dnlib.DotNet.Emit;
using dnlib.DotNet.Writer;
2011-10-25 01:44:49 +08:00
using de4dot.blocks;
using de4dot.blocks.cflow;
2011-10-25 01:44:49 +08:00
namespace de4dot.code.deobfuscators.dotNET_Reactor.v4 {
public class DeobfuscatorInfo : DeobfuscatorInfoBase {
2011-11-04 03:03:32 +08:00
public const string THE_NAME = ".NET Reactor";
2011-12-21 04:47:45 +08:00
public const string THE_TYPE = "dr4";
public const string SHORT_NAME_REGEX = @"!^[A-Za-z0-9]{2,3}$";
const string DEFAULT_REGEX = DeobfuscatorBase.DEFAULT_ASIAN_VALID_NAME_REGEX;
BoolOption decryptMethods;
BoolOption decryptBools;
BoolOption restoreTypes;
BoolOption inlineMethods;
BoolOption removeInlinedMethods;
2011-11-08 17:27:18 +08:00
BoolOption dumpEmbeddedAssemblies;
2011-11-09 02:32:10 +08:00
BoolOption decryptResources;
BoolOption removeNamespaces;
BoolOption removeAntiStrongName;
BoolOption renameShort;
2011-10-25 01:44:49 +08:00
public DeobfuscatorInfo()
2011-11-04 07:35:07 +08:00
: base(DEFAULT_REGEX) {
2013-01-19 20:03:57 +08:00
decryptMethods = new BoolOption(null, MakeArgName("methods"), "Decrypt methods", true);
decryptBools = new BoolOption(null, MakeArgName("bools"), "Decrypt booleans", true);
restoreTypes = new BoolOption(null, MakeArgName("types"), "Restore types (object -> real type)", true);
inlineMethods = new BoolOption(null, MakeArgName("inline"), "Inline short methods", true);
removeInlinedMethods = new BoolOption(null, MakeArgName("remove-inlined"), "Remove inlined methods", true);
dumpEmbeddedAssemblies = new BoolOption(null, MakeArgName("embedded"), "Dump embedded assemblies", true);
decryptResources = new BoolOption(null, MakeArgName("rsrc"), "Decrypt resources", true);
removeNamespaces = new BoolOption(null, MakeArgName("ns1"), "Clear namespace if there's only one class in it", true);
removeAntiStrongName = new BoolOption(null, MakeArgName("sn"), "Remove anti strong name code", true);
renameShort = new BoolOption(null, MakeArgName("sname"), "Rename short names", false);
2011-10-25 01:44:49 +08:00
}
2011-11-04 03:03:32 +08:00
public override string Name {
get { return THE_NAME; }
2011-10-25 01:44:49 +08:00
}
public override string Type {
2011-11-12 18:31:07 +08:00
get { return THE_TYPE; }
2011-10-25 01:44:49 +08:00
}
2013-01-19 20:03:57 +08:00
public override IDeobfuscator CreateDeobfuscator() {
2011-10-25 01:44:49 +08:00
return new Deobfuscator(new Deobfuscator.Options {
2013-11-18 23:28:44 +08:00
ValidNameRegex = validNameRegex.Get(),
DecryptMethods = decryptMethods.Get(),
DecryptBools = decryptBools.Get(),
RestoreTypes = restoreTypes.Get(),
InlineMethods = inlineMethods.Get(),
RemoveInlinedMethods = removeInlinedMethods.Get(),
DumpEmbeddedAssemblies = dumpEmbeddedAssemblies.Get(),
DecryptResources = decryptResources.Get(),
RemoveNamespaces = removeNamespaces.Get(),
RemoveAntiStrongName = removeAntiStrongName.Get(),
RenameShort = renameShort.Get(),
2011-10-25 01:44:49 +08:00
});
}
2013-01-19 20:03:57 +08:00
protected override IEnumerable<Option> GetOptionsInternal() {
2011-10-25 01:44:49 +08:00
return new List<Option>() {
decryptMethods,
decryptBools,
restoreTypes,
inlineMethods,
removeInlinedMethods,
2011-11-08 17:27:18 +08:00
dumpEmbeddedAssemblies,
2011-11-09 02:32:10 +08:00
decryptResources,
removeNamespaces,
removeAntiStrongName,
renameShort,
2011-10-25 01:44:49 +08:00
};
}
}
class Deobfuscator : DeobfuscatorBase {
Options options;
2011-12-21 04:47:45 +08:00
string obfuscatorName = DeobfuscatorInfo.THE_NAME;
2011-10-25 01:44:49 +08:00
MyPEImage peImage;
2011-10-27 01:49:25 +08:00
byte[] fileData;
MethodsDecrypter methodsDecrypter;
2011-10-27 01:49:25 +08:00
StringDecrypter stringDecrypter;
2011-10-27 02:23:45 +08:00
BooleanDecrypter booleanDecrypter;
BooleanValueInliner booleanValueInliner;
MetadataTokenObfuscator metadataTokenObfuscator;
2011-11-08 17:27:18 +08:00
AssemblyResolver assemblyResolver;
2011-11-09 02:32:10 +08:00
ResourceResolver resourceResolver;
AntiStrongName antiStrongname;
2011-11-24 17:44:01 +08:00
EmptyClass emptyClass;
2012-07-07 06:58:50 +08:00
ProxyCallFixer proxyCallFixer;
bool unpackedNativeFile = false;
bool canRemoveDecrypterType = true;
bool startedDeobfuscating = false;
2011-10-25 01:44:49 +08:00
internal class Options : OptionsBase {
public bool DecryptMethods { get; set; }
public bool DecryptBools { get; set; }
public bool RestoreTypes { get; set; }
public bool InlineMethods { get; set; }
public bool RemoveInlinedMethods { get; set; }
2011-11-08 17:27:18 +08:00
public bool DumpEmbeddedAssemblies { get; set; }
2011-11-09 02:32:10 +08:00
public bool DecryptResources { get; set; }
public bool RemoveNamespaces { get; set; }
public bool RemoveAntiStrongName { get; set; }
public bool RenameShort { get; set; }
2011-10-25 01:44:49 +08:00
}
public override string Type {
2011-11-12 18:31:07 +08:00
get { return DeobfuscatorInfo.THE_TYPE; }
}
public override string TypeLong {
2011-12-21 04:47:45 +08:00
get { return DeobfuscatorInfo.THE_NAME + " 4.x"; }
2011-10-25 01:44:49 +08:00
}
public override string Name {
2011-10-30 02:28:29 +08:00
get { return obfuscatorName; }
2011-10-25 01:44:49 +08:00
}
2012-01-11 11:38:02 +08:00
protected override bool CanInlineMethods {
get { return startedDeobfuscating ? options.InlineMethods : true; }
}
public override IEnumerable<IBlocksDeobfuscator> BlocksDeobfuscators {
get {
var list = new List<IBlocksDeobfuscator>();
if (CanInlineMethods)
list.Add(new DnrMethodCallInliner());
return list;
}
}
2011-10-25 01:44:49 +08:00
public Deobfuscator(Options options)
: base(options) {
this.options = options;
if (options.RemoveNamespaces)
this.RenamingOptions |= RenamingOptions.RemoveNamespaceIfOneType;
else
this.RenamingOptions &= ~RenamingOptions.RemoveNamespaceIfOneType;
if (options.RenameShort)
options.ValidNameRegex.Regexes.Insert(0, new NameRegex(DeobfuscatorInfo.SHORT_NAME_REGEX));
2011-10-25 01:44:49 +08:00
}
2013-01-19 20:03:57 +08:00
public override byte[] UnpackNativeFile(IPEImage peImage) {
var data = new NativeImageUnpacker(peImage).Unpack();
if (data == null)
return null;
unpackedNativeFile = true;
ModuleBytes = data;
return data;
}
2013-01-19 20:03:57 +08:00
public override void Initialize(ModuleDefMD module) {
base.Initialize(module);
2011-10-25 01:44:49 +08:00
}
2011-11-24 14:57:31 +08:00
static Regex isRandomName = new Regex(@"^[A-Z]{30,40}$");
2011-11-23 12:28:57 +08:00
static Regex isRandomNameMembers = new Regex(@"^[a-zA-Z0-9]{9,11}$"); // methods, fields, props, events
2013-11-07 10:25:52 +08:00
static Regex isRandomNameTypes = new Regex(@"^[a-zA-Z0-9]{18,20}(?:`\d+)?$"); // types, namespaces
2011-11-23 12:28:57 +08:00
2013-01-19 20:03:57 +08:00
bool CheckValidName(string name, Regex regex) {
2011-11-24 14:57:31 +08:00
if (isRandomName.IsMatch(name))
return false;
2011-11-23 12:28:57 +08:00
if (regex.IsMatch(name)) {
2013-01-19 20:03:57 +08:00
if (RandomNameChecker.IsRandom(name))
2011-11-10 07:47:22 +08:00
return false;
2013-01-19 20:03:57 +08:00
if (!RandomNameChecker.IsNonRandom(name))
2011-11-10 07:47:22 +08:00
return false;
}
2013-01-19 20:03:57 +08:00
return CheckValidName(name);
2011-11-23 12:28:57 +08:00
}
2013-01-19 20:03:57 +08:00
public override bool IsValidNamespaceName(string ns) {
if (ns == null)
return false;
if (ns.Contains("."))
2013-01-19 20:03:57 +08:00
return base.IsValidNamespaceName(ns);
return CheckValidName(ns, isRandomNameTypes);
2011-11-23 12:28:57 +08:00
}
2013-01-19 20:03:57 +08:00
public override bool IsValidTypeName(string name) {
return name != null && CheckValidName(name, isRandomNameTypes);
2011-11-23 12:28:57 +08:00
}
2013-01-19 20:03:57 +08:00
public override bool IsValidMethodName(string name) {
return name != null && CheckValidName(name, isRandomNameMembers);
2011-11-23 12:28:57 +08:00
}
2013-01-19 20:03:57 +08:00
public override bool IsValidPropertyName(string name) {
return name != null && CheckValidName(name, isRandomNameMembers);
2011-11-23 12:28:57 +08:00
}
2013-01-19 20:03:57 +08:00
public override bool IsValidEventName(string name) {
return name != null && CheckValidName(name, isRandomNameMembers);
2011-11-23 12:28:57 +08:00
}
2013-01-19 20:03:57 +08:00
public override bool IsValidFieldName(string name) {
return name != null && CheckValidName(name, isRandomNameMembers);
2011-11-23 12:28:57 +08:00
}
2013-01-19 20:03:57 +08:00
public override bool IsValidGenericParamName(string name) {
return name != null && CheckValidName(name, isRandomNameMembers);
2011-11-23 12:28:57 +08:00
}
2013-01-19 20:03:57 +08:00
public override bool IsValidMethodArgName(string name) {
return name != null && CheckValidName(name, isRandomNameMembers);
2011-11-10 07:47:22 +08:00
}
2013-01-19 20:03:57 +08:00
public override bool IsValidMethodReturnArgName(string name) {
return string.IsNullOrEmpty(name) || CheckValidName(name, isRandomNameMembers);
2012-11-04 18:45:04 +08:00
}
2013-01-19 20:03:57 +08:00
public override bool IsValidResourceKeyName(string name) {
return name != null && CheckValidName(name, isRandomNameMembers);
2012-05-03 20:53:01 +08:00
}
2013-01-19 20:03:57 +08:00
protected override int DetectInternal() {
2011-10-25 01:44:49 +08:00
int val = 0;
2013-01-19 20:03:57 +08:00
int sum = ToInt32(methodsDecrypter.Detected) +
ToInt32(stringDecrypter.Detected) +
ToInt32(booleanDecrypter.Detected) +
ToInt32(assemblyResolver.Detected) +
ToInt32(resourceResolver.Detected);
2011-11-08 17:27:18 +08:00
if (sum > 0)
val += 100 + 10 * (sum - 1);
2011-11-24 14:49:50 +08:00
if (sum == 0) {
2013-01-19 20:03:57 +08:00
if (HasMetadataStream("#GUlD") && HasMetadataStream("#Blop"))
2011-11-24 14:49:50 +08:00
val += 10;
}
2011-10-25 01:44:49 +08:00
return val;
}
2013-01-19 20:03:57 +08:00
protected override void ScanForObfuscator() {
methodsDecrypter = new MethodsDecrypter(module);
2013-01-19 20:03:57 +08:00
methodsDecrypter.Find();
2011-10-27 01:49:25 +08:00
stringDecrypter = new StringDecrypter(module);
2013-01-19 20:03:57 +08:00
stringDecrypter.Find(DeobfuscatedFile);
2011-10-27 02:23:45 +08:00
booleanDecrypter = new BooleanDecrypter(module);
2013-01-19 20:03:57 +08:00
booleanDecrypter.Find();
2011-11-08 17:27:18 +08:00
assemblyResolver = new AssemblyResolver(module);
2013-01-19 20:03:57 +08:00
assemblyResolver.Find(DeobfuscatedFile);
obfuscatorName = DetectVersion();
if (unpackedNativeFile)
obfuscatorName += " (native)";
2011-11-09 02:32:10 +08:00
resourceResolver = new ResourceResolver(module);
2013-01-19 20:03:57 +08:00
resourceResolver.Find(DeobfuscatedFile);
2011-10-30 02:28:29 +08:00
}
2013-01-19 20:03:57 +08:00
string DetectVersion() {
2011-10-30 02:28:29 +08:00
/*
Methods decrypter locals (not showing its own types):
3.7.0.3:
"System.Byte[]"
"System.Int32"
"System.Int32[]"
"System.IntPtr"
"System.IO.BinaryReader"
"System.IO.MemoryStream"
"System.Object"
"System.Reflection.Assembly"
"System.Security.Cryptography.CryptoStream"
"System.Security.Cryptography.ICryptoTransform"
"System.Security.Cryptography.RijndaelManaged"
"System.String"
3.9.8.0:
- "System.Int32[]"
+ "System.Diagnostics.StackFrame"
4.0.0.0: (jitter)
2011-10-30 02:28:29 +08:00
- "System.Diagnostics.StackFrame"
- "System.Object"
+ "System.Boolean"
+ "System.Collections.IEnumerator"
+ "System.Delegate"
+ "System.Diagnostics.Process"
+ "System.Diagnostics.ProcessModule"
+ "System.Diagnostics.ProcessModuleCollection"
+ "System.IDisposable"
+ "System.Int64"
+ "System.UInt32"
+ "System.UInt64"
4.1.0.0: (jitter)
+ "System.Reflection.Assembly"
4.3.1.0: (jitter)
+ "System.Byte&"
2011-10-30 02:28:29 +08:00
*/
LocalTypes localTypes;
int minVer = -1;
foreach (var info in stringDecrypter.DecrypterInfos) {
if (info.key == null)
continue;
localTypes = new LocalTypes(info.method);
2013-01-19 20:03:57 +08:00
if (!localTypes.Exists("System.IntPtr"))
2011-12-21 04:47:45 +08:00
return DeobfuscatorInfo.THE_NAME + " <= 3.7";
2011-10-30 02:28:29 +08:00
minVer = 3800;
break;
}
if (methodsDecrypter.DecrypterTypeVersion != DnrDecrypterType.V1)
return DeobfuscatorInfo.THE_NAME;
2011-11-06 22:24:30 +08:00
if (methodsDecrypter.Method == null) {
2011-10-30 02:28:29 +08:00
if (minVer >= 3800)
2011-12-21 04:47:45 +08:00
return DeobfuscatorInfo.THE_NAME + " >= 3.8";
return DeobfuscatorInfo.THE_NAME;
2011-10-30 02:28:29 +08:00
}
2011-11-06 22:24:30 +08:00
localTypes = new LocalTypes(methodsDecrypter.Method);
2011-10-30 02:28:29 +08:00
2013-01-19 20:03:57 +08:00
if (localTypes.Exists("System.Int32[]")) {
2011-10-30 02:28:29 +08:00
if (minVer >= 3800)
2011-12-21 04:47:45 +08:00
return DeobfuscatorInfo.THE_NAME + " 3.8.4.1 - 3.9.0.1";
return DeobfuscatorInfo.THE_NAME + " <= 3.9.0.1";
2011-10-30 02:28:29 +08:00
}
2013-01-19 20:03:57 +08:00
if (!localTypes.Exists("System.Diagnostics.Process")) { // If < 4.0
if (localTypes.Exists("System.Diagnostics.StackFrame"))
2011-12-21 04:47:45 +08:00
return DeobfuscatorInfo.THE_NAME + " 3.9.8.0";
}
2013-01-19 20:03:57 +08:00
var compileMethod = MethodsDecrypter.FindDnrCompileMethod(methodsDecrypter.Method.DeclaringType);
if (compileMethod == null) {
DeobfuscatedFile.Deobfuscate(methodsDecrypter.Method);
if (!MethodsDecrypter.IsNewer45Decryption(methodsDecrypter.Method))
return DeobfuscatorInfo.THE_NAME + " < 4.0";
return DeobfuscatorInfo.THE_NAME + " 4.5+";
}
2013-01-19 20:03:57 +08:00
DeobfuscatedFile.Deobfuscate(compileMethod);
bool compileMethodHasConstant_0x70000000 = DeobUtils.HasInteger(compileMethod, 0x70000000); // 4.0-4.1
DeobfuscatedFile.Deobfuscate(methodsDecrypter.Method);
bool hasCorEnableProfilingString = FindString(methodsDecrypter.Method, "Cor_Enable_Profiling"); // 4.1-4.4
2014-03-20 22:57:49 +08:00
bool hasCatchString = FindString(methodsDecrypter.Method, "catch: "); // <= 4.7
if (compileMethodHasConstant_0x70000000) {
if (hasCorEnableProfilingString)
2011-12-21 04:47:45 +08:00
return DeobfuscatorInfo.THE_NAME + " 4.1";
return DeobfuscatorInfo.THE_NAME + " 4.0";
}
2012-12-04 09:29:41 +08:00
if (!hasCorEnableProfilingString) {
2013-01-19 20:03:57 +08:00
bool callsReverse = DotNetUtils.CallsMethod(methodsDecrypter.Method, "System.Void System.Array::Reverse(System.Array)");
2012-12-04 09:29:41 +08:00
if (!callsReverse)
return DeobfuscatorInfo.THE_NAME + " 4.0 - 4.4";
int numIntPtrSizeCompares = CountCompareSystemIntPtrSize(methodsDecrypter.Method);
2013-11-05 20:52:58 +08:00
bool hasSymmetricAlgorithm = new LocalTypes(methodsDecrypter.Method).Exists("System.Security.Cryptography.SymmetricAlgorithm");
if (module.IsClr40) {
switch (numIntPtrSizeCompares) {
2013-11-15 21:44:20 +08:00
case 7:
case 9: return DeobfuscatorInfo.THE_NAME + " 4.5";
2013-11-05 20:52:58 +08:00
case 10:
if (!hasSymmetricAlgorithm)
return DeobfuscatorInfo.THE_NAME + " 4.6";
2014-03-20 22:57:49 +08:00
if (hasCatchString)
return DeobfuscatorInfo.THE_NAME + " 4.7";
return DeobfuscatorInfo.THE_NAME + " 4.8";
}
}
else {
switch (numIntPtrSizeCompares) {
2013-11-15 21:44:20 +08:00
case 6:
case 8: return DeobfuscatorInfo.THE_NAME + " 4.5";
2013-11-05 20:52:58 +08:00
case 9:
if (!hasSymmetricAlgorithm)
return DeobfuscatorInfo.THE_NAME + " 4.6";
2014-03-20 22:57:49 +08:00
if (hasCatchString)
return DeobfuscatorInfo.THE_NAME + " 4.7";
return DeobfuscatorInfo.THE_NAME + " 4.8";
}
}
// Should never be reached unless it's a new version
return DeobfuscatorInfo.THE_NAME + " 4.5+";
2012-12-04 09:29:41 +08:00
}
// 4.2-4.4
2011-10-30 02:28:29 +08:00
2013-01-19 20:03:57 +08:00
if (!localTypes.Exists("System.Byte&"))
2011-12-21 04:47:45 +08:00
return DeobfuscatorInfo.THE_NAME + " 4.2";
localTypes = new LocalTypes(compileMethod);
2013-01-19 20:03:57 +08:00
if (localTypes.Exists("System.Object"))
2011-12-21 04:47:45 +08:00
return DeobfuscatorInfo.THE_NAME + " 4.4";
return DeobfuscatorInfo.THE_NAME + " 4.3";
}
static int CountCompareSystemIntPtrSize(MethodDef method) {
if (method == null || method.Body == null)
return 0;
int count = 0;
var instrs = method.Body.Instructions;
for (int i = 1; i < instrs.Count - 1; i++) {
var ldci4 = instrs[i];
if (!ldci4.IsLdcI4() || ldci4.GetLdcI4Value() != 4)
continue;
if (!instrs[i + 1].IsConditionalBranch())
continue;
var call = instrs[i - 1];
if (call.OpCode.Code != Code.Call)
continue;
var calledMethod = call.Operand as MemberRef;
if (calledMethod == null || calledMethod.FullName != "System.Int32 System.IntPtr::get_Size()")
continue;
count++;
}
return count;
}
2013-01-19 20:03:57 +08:00
static bool FindString(MethodDef method, string s) {
foreach (var cs in DotNetUtils.GetCodeStrings(method)) {
if (cs == s)
return true;
}
return false;
}
2013-01-19 20:03:57 +08:00
public override bool GetDecryptedModule(int count, ref byte[] newFileData, ref DumpedMethods dumpedMethods) {
if (count != 0)
return false;
2013-01-19 20:03:57 +08:00
fileData = ModuleBytes ?? DeobUtils.ReadModule(module);
peImage = new MyPEImage(fileData);
2011-10-27 01:49:25 +08:00
if (!options.DecryptMethods)
2011-10-29 08:27:34 +08:00
return false;
var tokenToNativeCode = new Dictionary<uint,byte[]>();
2013-01-19 20:03:57 +08:00
if (!methodsDecrypter.Decrypt(peImage, DeobfuscatedFile, ref dumpedMethods, tokenToNativeCode, unpackedNativeFile))
2011-10-29 08:27:34 +08:00
return false;
2011-10-27 01:49:25 +08:00
2011-10-29 08:27:34 +08:00
newFileData = fileData;
return true;
}
2013-01-19 20:03:57 +08:00
public override IDeobfuscator ModuleReloaded(ModuleDefMD module) {
FreePEImage();
var newOne = new Deobfuscator(options);
2013-01-19 20:03:57 +08:00
newOne.SetModule(module);
2011-10-27 02:23:45 +08:00
newOne.fileData = fileData;
newOne.peImage = new MyPEImage(fileData);
newOne.methodsDecrypter = new MethodsDecrypter(module, methodsDecrypter);
2011-10-27 01:49:25 +08:00
newOne.stringDecrypter = new StringDecrypter(module, stringDecrypter);
2011-10-27 02:23:45 +08:00
newOne.booleanDecrypter = new BooleanDecrypter(module, booleanDecrypter);
2011-11-08 17:27:18 +08:00
newOne.assemblyResolver = new AssemblyResolver(module, assemblyResolver);
2011-11-09 02:32:10 +08:00
newOne.resourceResolver = new ResourceResolver(module, resourceResolver);
2013-01-19 20:03:57 +08:00
newOne.methodsDecrypter.Reloaded();
return newOne;
}
2013-01-19 20:03:57 +08:00
void FreePEImage() {
if (peImage != null)
peImage.Dispose();
peImage = null;
}
2013-01-19 20:03:57 +08:00
public override void DeobfuscateBegin() {
base.DeobfuscateBegin();
2011-10-27 01:49:25 +08:00
2012-07-07 06:58:50 +08:00
proxyCallFixer = new ProxyCallFixer(module, DeobfuscatedFile);
2013-01-19 20:03:57 +08:00
proxyCallFixer.FindDelegateCreator();
proxyCallFixer.Find();
2012-07-07 06:58:50 +08:00
2013-01-19 20:03:57 +08:00
stringDecrypter.Initialize(peImage, fileData, DeobfuscatedFile);
if (!stringDecrypter.Detected)
2013-01-19 20:03:57 +08:00
FreePEImage();
booleanDecrypter.Initialize(fileData, DeobfuscatedFile);
booleanValueInliner = new BooleanValueInliner();
2011-11-24 17:44:01 +08:00
emptyClass = new EmptyClass(module);
2011-10-27 03:05:35 +08:00
if (options.DecryptBools) {
2013-01-19 20:03:57 +08:00
booleanValueInliner.Add(booleanDecrypter.Method, (method, gim, args) => {
return booleanDecrypter.Decrypt((int)args[0]);
});
}
2011-10-27 01:49:25 +08:00
foreach (var info in stringDecrypter.DecrypterInfos) {
2013-01-19 20:03:57 +08:00
staticStringInliner.Add(info.method, (method2, gim, args) => {
return stringDecrypter.Decrypt(method2, (int)args[0]);
2011-10-27 01:49:25 +08:00
});
}
if (stringDecrypter.OtherStringDecrypter != null) {
2013-01-19 20:03:57 +08:00
staticStringInliner.Add(stringDecrypter.OtherStringDecrypter, (method2, gim, args) => {
return stringDecrypter.Decrypt((string)args[0]);
});
}
2013-01-19 20:03:57 +08:00
DeobfuscatedFile.StringDecryptersAdded();
metadataTokenObfuscator = new MetadataTokenObfuscator(module);
2013-01-19 20:03:57 +08:00
antiStrongname = new AntiStrongName(GetDecrypterType());
bool removeResourceResolver = false;
2011-11-09 02:32:10 +08:00
if (options.DecryptResources) {
2013-01-19 20:03:57 +08:00
resourceResolver.Initialize(DeobfuscatedFile, this);
DecryptResources();
if (options.InlineMethods) {
2013-01-19 20:03:57 +08:00
AddTypeToBeRemoved(resourceResolver.Type, "Resource decrypter type");
removeResourceResolver = true;
}
2013-01-19 20:03:57 +08:00
AddEntryPointCallToBeRemoved(resourceResolver.InitMethod);
AddCctorInitCallToBeRemoved(resourceResolver.InitMethod);
2011-11-09 02:32:10 +08:00
}
if (resourceResolver.Detected && !removeResourceResolver && !resourceResolver.FoundResource)
canRemoveDecrypterType = false; // There may be calls to its .ctor
2011-11-09 02:32:10 +08:00
if (Operations.DecryptStrings != OpDecryptString.None)
2013-01-19 20:03:57 +08:00
AddResourceToBeRemoved(stringDecrypter.Resource, "Encrypted strings");
2011-11-04 14:21:12 +08:00
else
canRemoveDecrypterType = false;
2011-11-25 22:24:12 +08:00
if (options.DecryptMethods && !methodsDecrypter.HasNativeMethods) {
2013-01-19 20:03:57 +08:00
AddResourceToBeRemoved(methodsDecrypter.Resource, "Encrypted methods");
AddCctorInitCallToBeRemoved(methodsDecrypter.Method);
}
2011-11-04 14:21:12 +08:00
else
canRemoveDecrypterType = false;
if (options.DecryptBools)
2013-01-19 20:03:57 +08:00
AddResourceToBeRemoved(booleanDecrypter.Resource, "Encrypted booleans");
2011-11-04 14:21:12 +08:00
else
canRemoveDecrypterType = false;
if (!options.RemoveAntiStrongName)
2011-11-12 20:31:08 +08:00
canRemoveDecrypterType = false;
2011-11-04 14:21:12 +08:00
// The inlined methods may contain calls to the decrypter class
if (!options.InlineMethods)
canRemoveDecrypterType = false;
2011-11-08 17:27:18 +08:00
if (options.DumpEmbeddedAssemblies) {
if (options.InlineMethods)
2013-01-19 20:03:57 +08:00
AddTypeToBeRemoved(assemblyResolver.Type, "Assembly resolver");
AddEntryPointCallToBeRemoved(assemblyResolver.InitMethod);
AddCctorInitCallToBeRemoved(assemblyResolver.InitMethod);
DumpEmbeddedAssemblies();
2011-11-08 17:27:18 +08:00
}
2011-11-08 17:39:35 +08:00
if (options.InlineMethods)
2013-01-19 20:03:57 +08:00
AddTypeToBeRemoved(metadataTokenObfuscator.Type, "Metadata token obfuscator");
2011-11-08 17:39:35 +08:00
2013-01-19 20:03:57 +08:00
AddCctorInitCallToBeRemoved(emptyClass.Method);
AddCtorInitCallToBeRemoved(emptyClass.Method);
AddEntryPointCallToBeRemoved(emptyClass.Method);
if (options.InlineMethods)
2013-01-19 20:03:57 +08:00
AddTypeToBeRemoved(emptyClass.Type, "Empty class");
2011-11-24 17:44:01 +08:00
startedDeobfuscating = true;
2011-10-25 01:44:49 +08:00
}
2013-01-19 20:03:57 +08:00
void AddEntryPointCallToBeRemoved(MethodDef methodToBeRemoved) {
var entryPoint = module.EntryPoint;
2013-01-19 20:03:57 +08:00
AddCallToBeRemoved(entryPoint, methodToBeRemoved);
foreach (var calledMethod in DotNetUtils.GetCalledMethods(module, entryPoint))
AddCallToBeRemoved(calledMethod, methodToBeRemoved);
}
2013-01-19 20:03:57 +08:00
void DecryptResources() {
var rsrc = resourceResolver.MergeResources();
2011-11-09 02:32:10 +08:00
if (rsrc == null)
return;
2013-01-19 20:03:57 +08:00
AddResourceToBeRemoved(rsrc, "Encrypted resources");
2011-11-09 02:32:10 +08:00
}
2013-01-19 20:03:57 +08:00
void DumpEmbeddedAssemblies() {
2011-11-08 17:27:18 +08:00
if (!options.DumpEmbeddedAssemblies)
return;
2013-01-19 20:03:57 +08:00
foreach (var info in assemblyResolver.GetEmbeddedAssemblies(DeobfuscatedFile, this)) {
var simpleName = Utils.GetAssemblySimpleName(info.name);
DeobfuscatedFile.CreateAssemblyFile(info.resource.GetResourceData(), simpleName, null);
AddResourceToBeRemoved(info.resource, string.Format("Embedded assembly: {0}", info.name));
2011-11-08 17:27:18 +08:00
}
}
2013-01-19 20:03:57 +08:00
public override bool DeobfuscateOther(Blocks blocks) {
return booleanValueInliner.Decrypt(blocks) > 0;
}
2011-10-27 03:05:35 +08:00
2013-01-19 20:03:57 +08:00
public override void DeobfuscateMethodEnd(Blocks blocks) {
proxyCallFixer.Deobfuscate(blocks);
metadataTokenObfuscator.Deobfuscate(blocks);
FixTypeofDecrypterInstructions(blocks);
RemoveAntiStrongNameCode(blocks);
base.DeobfuscateMethodEnd(blocks);
2011-10-25 01:44:49 +08:00
}
2013-01-19 20:03:57 +08:00
void RemoveAntiStrongNameCode(Blocks blocks) {
if (!options.RemoveAntiStrongName)
2011-11-12 20:31:08 +08:00
return;
2013-01-19 20:03:57 +08:00
if (antiStrongname.Remove(blocks))
Logger.v("Removed anti strong name code");
2011-11-12 20:31:08 +08:00
}
2013-01-19 20:03:57 +08:00
TypeDef GetDecrypterType() {
2011-11-12 20:31:08 +08:00
return methodsDecrypter.DecrypterType ?? stringDecrypter.DecrypterType ?? booleanDecrypter.DecrypterType;
}
2013-01-19 20:03:57 +08:00
void FixTypeofDecrypterInstructions(Blocks blocks) {
var type = GetDecrypterType();
if (type == null)
return;
2013-01-19 20:03:57 +08:00
foreach (var block in blocks.MethodBlocks.GetAllBlocks()) {
var instructions = block.Instructions;
for (int i = 0; i < instructions.Count; i++) {
var instr = instructions[i];
if (instr.OpCode.Code != Code.Ldtoken)
continue;
2012-11-18 01:57:36 +08:00
if (!new SigComparer().Equals(type, instr.Operand as ITypeDefOrRef))
continue;
2012-12-16 07:03:56 +08:00
instructions[i] = new Instr(OpCodes.Ldtoken.ToInstruction(blocks.Method.DeclaringType));
}
}
}
2013-01-19 20:03:57 +08:00
public override void DeobfuscateEnd() {
FreePEImage();
RemoveProxyDelegates(proxyCallFixer);
RemoveInlinedMethods();
if (options.RestoreTypes)
2013-01-19 20:03:57 +08:00
new TypesRestorer(module).Deobfuscate();
2013-01-19 20:03:57 +08:00
var decrypterType = GetDecrypterType();
if (canRemoveDecrypterType && IsTypeCalled(decrypterType))
canRemoveDecrypterType = false;
2011-11-24 17:10:39 +08:00
if (canRemoveDecrypterType)
2013-01-19 20:03:57 +08:00
AddTypeToBeRemoved(decrypterType, "Decrypter type");
2011-11-12 20:31:08 +08:00
else
Logger.v("Could not remove decrypter type");
2013-01-19 20:03:57 +08:00
FixEntryPoint();
2013-01-19 20:03:57 +08:00
base.DeobfuscateEnd();
2011-10-25 01:44:49 +08:00
}
2013-01-19 20:03:57 +08:00
void FixEntryPoint() {
if (!module.IsClr1x)
return;
var ep = module.EntryPoint;
if (ep == null)
return;
if (ep.MethodSig.GetParamCount() <= 1)
return;
ep.MethodSig = MethodSig.CreateStatic(ep.MethodSig.RetType, new SZArraySig(module.CorLibTypes.String));
2012-12-16 07:03:56 +08:00
ep.ParamDefs.Clear();
ep.Parameters.UpdateParameterTypes();
}
2013-01-19 20:03:57 +08:00
void RemoveInlinedMethods() {
if (!options.InlineMethods || !options.RemoveInlinedMethods)
return;
2013-01-19 20:03:57 +08:00
FindAndRemoveInlinedMethods();
}
2013-01-19 20:03:57 +08:00
public override IEnumerable<int> GetStringDecrypterMethods() {
2012-02-25 13:25:40 +08:00
var list = new List<int>();
2011-10-27 01:49:25 +08:00
foreach (var info in stringDecrypter.DecrypterInfos)
list.Add(info.method.MDToken.ToInt32());
if (stringDecrypter.OtherStringDecrypter != null)
list.Add(stringDecrypter.OtherStringDecrypter.MDToken.ToInt32());
2011-10-25 01:44:49 +08:00
return list;
}
2011-11-25 22:24:12 +08:00
2012-11-18 01:57:36 +08:00
public override void OnWriterEvent(ModuleWriterBase writer, ModuleWriterEvent evt) {
if (!options.DecryptMethods || !methodsDecrypter.HasNativeMethods)
2011-11-25 22:24:12 +08:00
return;
switch (evt) {
case ModuleWriterEvent.Begin:
// The decrypter assumes RVAs are unique so don't share any method bodies
writer.TheOptions.ShareMethodBodies = false;
break;
case ModuleWriterEvent.MDBeginAddResources:
2013-01-19 20:03:57 +08:00
methodsDecrypter.PrepareEncryptNativeMethods(writer);
break;
case ModuleWriterEvent.BeginWriteChunks:
2013-01-19 20:03:57 +08:00
methodsDecrypter.EncryptNativeMethods(writer);
break;
}
2011-11-25 22:24:12 +08:00
}
protected override void Dispose(bool disposing) {
if (disposing)
2013-01-19 20:03:57 +08:00
FreePEImage();
base.Dispose(disposing);
}
2011-10-25 01:44:49 +08:00
}
}