Add DS obfuscator support

This commit is contained in:
de4dot 2012-01-22 19:58:31 +01:00
parent 080a11c437
commit 991a5281ab
9 changed files with 979 additions and 0 deletions

View File

@ -90,6 +90,13 @@
<Compile Include="deobfuscators\DeobfuscatorBase.cs" />
<Compile Include="deobfuscators\DeobfuscatorInfoBase.cs" />
<Compile Include="deobfuscators\DeobUtils.cs" />
<Compile Include="deobfuscators\DeepSea\AssemblyResolver.cs" />
<Compile Include="deobfuscators\DeepSea\DsInlinedMethodsFinder.cs" />
<Compile Include="deobfuscators\DeepSea\ResolverBase.cs" />
<Compile Include="deobfuscators\DeepSea\ResourceResolver.cs" />
<Compile Include="deobfuscators\DeepSea\StringDecrypter.cs" />
<Compile Include="deobfuscators\DeepSea\Deobfuscator.cs" />
<Compile Include="deobfuscators\DeepSea\MethodCallInliner.cs" />
<Compile Include="deobfuscators\Dotfuscator\Deobfuscator.cs" />
<Compile Include="deobfuscators\Dotfuscator\StringDecrypter.cs" />
<Compile Include="deobfuscators\dotNET_Reactor\v3\AntiStrongName.cs" />

View File

@ -0,0 +1,93 @@
/*
Copyright (C) 2011-2012 de4dot@gmail.com
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.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
using Mono.Cecil;
namespace de4dot.code.deobfuscators.DeepSea {
class AssemblyResolver : ResolverBase {
public class AssemblyInfo {
public byte[] data;
public string fullName;
public string simpleName;
public string extension;
public EmbeddedResource resource;
public AssemblyInfo(byte[] data, string fullName, string simpleName, string extension, EmbeddedResource resource) {
this.data = data;
this.fullName = fullName;
this.simpleName = simpleName;
this.extension = extension;
this.resource = resource;
}
}
public AssemblyResolver(ModuleDefinition module)
: base(module) {
}
static string[] handlerLocalTypes = new string[] {
"System.Byte[]",
"System.Security.Cryptography.SHA1CryptoServiceProvider",
"System.IO.Compression.DeflateStream",
"System.IO.MemoryStream",
"System.IO.Stream",
"System.Reflection.Assembly",
"System.String",
};
protected override bool checkHandlerMethodInternal(MethodDefinition handler) {
return new LocalTypes(handler).all(handlerLocalTypes);
}
public IEnumerable<AssemblyInfo> getAssemblyInfos() {
var infos = new List<AssemblyInfo>();
foreach (var tmp in module.Resources) {
var resource = tmp as EmbeddedResource;
if (resource == null)
continue;
if (!Regex.IsMatch(resource.Name, @"^[0-9A-F]{40}$"))
continue;
var info = getAssemblyInfos(resource);
if (info == null)
continue;
infos.Add(info);
}
return infos;
}
AssemblyInfo getAssemblyInfos(EmbeddedResource resource) {
try {
var decrypted = decryptResource(resource);
var asm = AssemblyDefinition.ReadAssembly(new MemoryStream(decrypted));
var fullName = asm.Name.FullName;
var simpleName = asm.Name.Name;
var extension = DeobUtils.getExtension(asm.Modules[0].Kind);
return new AssemblyInfo(decrypted, fullName, simpleName, extension, resource);
}
catch (Exception) {
return null;
}
}
}
}

View File

@ -0,0 +1,202 @@
/*
Copyright (C) 2011-2012 de4dot@gmail.com
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.Collections.Generic;
using Mono.Cecil;
using de4dot.blocks.cflow;
namespace de4dot.code.deobfuscators.DeepSea {
public class DeobfuscatorInfo : DeobfuscatorInfoBase {
public const string THE_NAME = "DeepSea";
public const string THE_TYPE = "ds";
BoolOption inlineMethods;
BoolOption removeInlinedMethods;
BoolOption decryptResources;
BoolOption dumpEmbeddedAssemblies;
public DeobfuscatorInfo()
: base() {
inlineMethods = new BoolOption(null, makeArgName("inline"), "Inline short methods", true);
removeInlinedMethods = new BoolOption(null, makeArgName("remove-inlined"), "Remove inlined methods", true);
decryptResources = new BoolOption(null, makeArgName("rsrc"), "Decrypt resources", true);
dumpEmbeddedAssemblies = new BoolOption(null, makeArgName("embedded"), "Dump embedded assemblies", true);
}
public override string Name {
get { return THE_NAME; }
}
public override string Type {
get { return THE_TYPE; }
}
public override IDeobfuscator createDeobfuscator() {
return new Deobfuscator(new Deobfuscator.Options {
ValidNameRegex = validNameRegex.get(),
InlineMethods = inlineMethods.get(),
RemoveInlinedMethods = removeInlinedMethods.get(),
DecryptResources = decryptResources.get(),
DumpEmbeddedAssemblies = dumpEmbeddedAssemblies.get(),
});
}
protected override IEnumerable<Option> getOptionsInternal() {
return new List<Option>() {
inlineMethods,
removeInlinedMethods,
decryptResources,
dumpEmbeddedAssemblies,
};
}
}
class Deobfuscator : DeobfuscatorBase {
Options options;
bool startedDeobfuscating = false;
StringDecrypter stringDecrypter;
ResourceResolver resourceResolver;
AssemblyResolver assemblyResolver;
internal class Options : OptionsBase {
public bool InlineMethods { get; set; }
public bool RemoveInlinedMethods { get; set; }
public bool DecryptResources { get; set; }
public bool DumpEmbeddedAssemblies { get; set; }
}
public override string Type {
get { return DeobfuscatorInfo.THE_TYPE; }
}
public override string TypeLong {
get { return DeobfuscatorInfo.THE_NAME; }
}
public override string Name {
get { return TypeLong; }
}
protected override bool CanInlineMethods {
get { return startedDeobfuscating ? options.InlineMethods : true; }
}
public override IMethodCallInliner MethodCallInliner {
get {
if (CanInlineMethods)
return new MethodCallInliner();
return new NoMethodInliner();
}
}
public Deobfuscator(Options options)
: base(options) {
this.options = options;
}
protected override int detectInternal() {
int val = 0;
int sum = toInt32(stringDecrypter.Detected) +
toInt32(resourceResolver.Detected) +
toInt32(assemblyResolver.Detected);
if (sum > 0)
val += 100 + 10 * (sum - 1);
return val;
}
protected override void scanForObfuscator() {
stringDecrypter = new StringDecrypter(module);
stringDecrypter.find(DeobfuscatedFile);
resourceResolver = new ResourceResolver(module);
resourceResolver.find();
assemblyResolver = new AssemblyResolver(module);
assemblyResolver.find();
}
public override void deobfuscateBegin() {
base.deobfuscateBegin();
foreach (var method in stringDecrypter.DecrypterMethods) {
staticStringInliner.add(method, (method2, args) => {
return stringDecrypter.decrypt(method2, (int)args[0]);
});
}
DeobfuscatedFile.stringDecryptersAdded();
if (options.DecryptResources) {
resourceResolver.initialize(DeobfuscatedFile, this);
decryptResources();
}
dumpEmbeddedAssemblies();
startedDeobfuscating = true;
}
void decryptResources() {
if (!options.DecryptResources)
return;
var rsrc = resourceResolver.mergeResources();
if (rsrc == null)
return;
addResourceToBeRemoved(rsrc, "Encrypted resources");
addCctorInitCallToBeRemoved(resourceResolver.InitMethod);
addCallToBeRemoved(module.EntryPoint, resourceResolver.InitMethod);
addMethodToBeRemoved(resourceResolver.InitMethod, "Resource resolver init method");
addMethodToBeRemoved(resourceResolver.HandlerMethod, "Resource resolver handler method");
}
void dumpEmbeddedAssemblies() {
if (!options.DumpEmbeddedAssemblies)
return;
foreach (var info in assemblyResolver.getAssemblyInfos()) {
DeobfuscatedFile.createAssemblyFile(info.data, info.simpleName, info.extension);
addResourceToBeRemoved(info.resource, string.Format("Embedded assembly: {0}", info.fullName));
}
addCctorInitCallToBeRemoved(assemblyResolver.InitMethod);
addCallToBeRemoved(module.EntryPoint, assemblyResolver.InitMethod);
addMethodToBeRemoved(assemblyResolver.InitMethod, "Assembly resolver init method");
addMethodToBeRemoved(assemblyResolver.HandlerMethod, "Assembly resolver handler method");
}
public override void deobfuscateEnd() {
removeInlinedMethods();
if (Operations.DecryptStrings != OpDecryptString.None)
addMethodsToBeRemoved(stringDecrypter.DecrypterMethods, "String decrypter method");
base.deobfuscateEnd();
}
void removeInlinedMethods() {
if (!options.InlineMethods || !options.RemoveInlinedMethods)
return;
removeInlinedMethods(DsInlinedMethodsFinder.find(module));
}
public override IEnumerable<string> getStringDecrypterMethods() {
var list = new List<string>();
foreach (var method in stringDecrypter.DecrypterMethods)
list.Add(method.MetadataToken.ToInt32().ToString("X8"));
return list;
}
}
}

View File

@ -0,0 +1,38 @@
/*
Copyright (C) 2011-2012 de4dot@gmail.com
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.Collections.Generic;
using Mono.Cecil;
namespace de4dot.code.deobfuscators.DeepSea {
static class DsInlinedMethodsFinder {
public static List<MethodDefinition> find(ModuleDefinition module) {
var inlinedMethods = new List<MethodDefinition>();
foreach (var type in module.GetTypes()) {
foreach (var method in type.Methods) {
if (MethodCallInliner.canInline(method))
inlinedMethods.Add(method);
}
}
return inlinedMethods;
}
}
}

View File

@ -0,0 +1,185 @@
/*
Copyright (C) 2011-2012 de4dot@gmail.com
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.Collections.Generic;
using Mono.Cecil;
using Mono.Cecil.Cil;
using de4dot.blocks;
using de4dot.blocks.cflow;
namespace de4dot.code.deobfuscators.DeepSea {
class MethodCallInliner : MethodCallInlinerBase {
InstructionEmulator instructionEmulator = new InstructionEmulator();
protected override bool deobfuscateInternal() {
bool changed = false;
var instructions = block.Instructions;
for (int i = 0; i < instructions.Count; i++) {
var instr = instructions[i].Instruction;
if (instr.OpCode.Code == Code.Call)
changed |= inlineMethod(instr, i);
}
return changed;
}
bool inlineMethod(Instruction callInstr, int instrIndex) {
var method = callInstr.Operand as MethodDefinition;
if (method == null)
return false;
if (!canInline(method))
return false;
if (instrIndex < 2)
return false;
var ldci4_1st = block.Instructions[instrIndex - 2];
var ldci4_2nd = block.Instructions[instrIndex - 1];
if (!ldci4_1st.isLdcI4() || !ldci4_2nd.isLdcI4())
return false;
if (!inlineMethod(method, instrIndex, ldci4_1st.getLdcI4Value(), ldci4_2nd.getLdcI4Value()))
return false;
return true;
}
bool inlineMethod(MethodDefinition methodToInline, int instrIndex, int const1, int const2) {
var parameters = DotNetUtils.getParameters(methodToInline);
var arg1 = parameters[parameters.Count - 2];
var arg2 = parameters[parameters.Count - 1];
instructionEmulator.init(methodToInline.HasImplicitThis, false, methodToInline.Parameters, methodToInline.Body.Variables);
instructionEmulator.setArg(arg1, new Int32Value(const1));
instructionEmulator.setArg(arg2, new Int32Value(const2));
Instruction instr;
var instrs = methodToInline.Body.Instructions;
int index = 0;
int counter = 0;
while (true) {
if (counter++ >= 50)
return false;
if (index >= instrs.Count)
return false;
instr = instrs[index];
switch (instr.OpCode.Code) {
case Code.Stloc:
case Code.Stloc_S:
case Code.Stloc_0:
case Code.Stloc_1:
case Code.Stloc_2:
case Code.Stloc_3:
case Code.Ldloc:
case Code.Ldloc_S:
case Code.Ldloc_0:
case Code.Ldloc_1:
case Code.Ldloc_2:
case Code.Ldloc_3:
case Code.Ldc_I4:
case Code.Ldc_I4_0:
case Code.Ldc_I4_1:
case Code.Ldc_I4_2:
case Code.Ldc_I4_3:
case Code.Ldc_I4_4:
case Code.Ldc_I4_5:
case Code.Ldc_I4_6:
case Code.Ldc_I4_7:
case Code.Ldc_I4_8:
case Code.Ldc_I4_M1:
case Code.Ldc_I4_S:
case Code.Add:
case Code.Sub:
case Code.Xor:
case Code.Or:
case Code.Nop:
instructionEmulator.emulate(instr);
index++;
break;
case Code.Ldarg:
case Code.Ldarg_S:
case Code.Ldarg_0:
case Code.Ldarg_1:
case Code.Ldarg_2:
case Code.Ldarg_3:
var arg = DotNetUtils.getParameter(parameters, instr);
if (arg != arg1 && arg != arg2)
goto checkInline;
instructionEmulator.emulate(instr);
index++;
break;
case Code.Call:
case Code.Callvirt:
case Code.Newobj:
goto checkInline;
case Code.Switch:
var value = instructionEmulator.pop() as Int32Value;
if (value == null || !value.allBitsValid())
return false;
var targets = (Instruction[])instr.Operand;
if (value.value >= 0 && value.value < targets.Length)
index = instrs.IndexOf(targets[value.value]);
else
index++;
break;
case Code.Br:
case Code.Br_S:
index = instrs.IndexOf((Instruction)instr.Operand);
break;
default:
return false;
}
}
checkInline:
if (!inlineOtherMethod(instrIndex, methodToInline, instr, index + 1, 2))
return false;
block.insert(instrIndex, Instruction.Create(OpCodes.Pop));
block.insert(instrIndex, Instruction.Create(OpCodes.Pop));
return true;
}
public static bool canInline(MethodDefinition method) {
if (method == null || method.Body == null)
return false;
if (method.Body.ExceptionHandlers.Count > 0)
return false;
var parameters = method.Parameters;
int paramCount = parameters.Count;
if (paramCount < 2)
return false;
if (parameters[paramCount - 1].ParameterType.FullName != "System.Int32")
return false;
if (parameters[paramCount - 2].ParameterType.FullName != "System.Int32")
return false;
if (method.Attributes != (MethodAttributes.Assembly | MethodAttributes.Static))
return false;
//TODO: Also check that it has a switch statement and an xor instruction
return true;
}
}
}

View File

@ -0,0 +1,123 @@
/*
Copyright (C) 2011-2012 de4dot@gmail.com
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 Mono.Cecil;
using Mono.Cecil.Cil;
using de4dot.blocks;
namespace de4dot.code.deobfuscators.DeepSea {
abstract class ResolverBase {
protected ModuleDefinition module;
protected MethodDefinition initMethod;
protected MethodDefinition resolveHandler;
public MethodDefinition InitMethod {
get { return initMethod; }
}
public MethodDefinition HandlerMethod {
get { return resolveHandler; }
}
public bool Detected {
get { return initMethod != null; }
}
public ResolverBase(ModuleDefinition module) {
this.module = module;
}
public void find() {
if (checkCalledMethods(DotNetUtils.getModuleTypeCctor(module)))
return;
if (checkCalledMethods(module.EntryPoint))
return;
}
bool checkCalledMethods(MethodDefinition checkMethod) {
if (checkMethod == null || checkMethod.Body == null)
return false;
foreach (var tuple in DotNetUtils.getCalledMethods(module, checkMethod)) {
var method = tuple.Item2;
if (method.Name == ".cctor" || method.Name == ".ctor")
continue;
if (!method.IsStatic || !DotNetUtils.isMethod(method, "System.Void", "()"))
continue;
if (checkResolverInitMethod(method))
return true;
}
return false;
}
bool checkResolverInitMethod(MethodDefinition resolverInitMethod) {
if (resolverInitMethod == null || resolverInitMethod.Body == null)
return false;
var resolveHandlerMethod = getLdftnMethod(resolverInitMethod);
if (resolveHandlerMethod == null)
return false;
if (!checkHandlerMethod(resolveHandlerMethod))
return false;
initMethod = resolverInitMethod;
resolveHandler = resolveHandlerMethod;
return true;
}
MethodDefinition getLdftnMethod(MethodDefinition method) {
foreach (var instr in method.Body.Instructions) {
if (instr.OpCode.Code != Code.Ldftn)
continue;
var loadedMethod = instr.Operand as MethodDefinition;
if (loadedMethod != null)
return loadedMethod;
}
return null;
}
bool checkHandlerMethod(MethodDefinition handler) {
if (handler == null || handler.Body == null)
return false;
if (!DotNetUtils.isMethod(handler, "System.Reflection.Assembly", "(System.Object,System.ResolveEventArgs)"))
return false;
return checkHandlerMethodInternal(handler);
}
protected abstract bool checkHandlerMethodInternal(MethodDefinition handler);
protected static byte[] decryptResource(EmbeddedResource resource) {
var data = resource.GetResourceData();
const int baseIndex = 1;
for (int i = baseIndex; i < data.Length; i++)
data[i] ^= (byte)((i - baseIndex) + data[0]);
if (BitConverter.ToInt16(data, baseIndex) != 0x5A4D)
return DeobUtils.inflate(data, 1, data.Length - 1, true);
var data2 = new byte[data.Length - baseIndex];
Array.Copy(data, baseIndex, data2, 0, data2.Length);
return data2;
}
}
}

View File

@ -0,0 +1,66 @@
/*
Copyright (C) 2011-2012 de4dot@gmail.com
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 Mono.Cecil;
namespace de4dot.code.deobfuscators.DeepSea {
class ResourceResolver : ResolverBase {
EmbeddedResource resource;
public ResourceResolver(ModuleDefinition module)
: base(module) {
}
static string[] handlerLocalTypes = new string[] {
"System.AppDomain",
"System.Byte[]",
"System.Collections.Generic.Dictionary`2<System.String,System.String>",
"System.IO.Compression.DeflateStream",
"System.IO.MemoryStream",
"System.IO.Stream",
"System.Reflection.Assembly",
"System.String",
"System.String[]",
};
protected override bool checkHandlerMethodInternal(MethodDefinition handler) {
return new LocalTypes(handler).all(handlerLocalTypes);
}
public void initialize(ISimpleDeobfuscator simpleDeobfuscator, IDeobfuscator deob) {
if (resolveHandler == null)
return;
simpleDeobfuscator.deobfuscate(resolveHandler);
simpleDeobfuscator.decryptStrings(resolveHandler, deob);
resource = DeobUtils.getEmbeddedResourceFromCodeStrings(module, resolveHandler);
if (resource == null) {
Log.w("Could not find resource of encrypted resources");
return;
}
}
public EmbeddedResource mergeResources() {
if (resource == null)
return null;
DeobUtils.decryptAndAddResources(module, resource.Name, () => decryptResource(resource));
return resource;
}
}
}

View File

@ -0,0 +1,264 @@
/*
Copyright (C) 2011-2012 de4dot@gmail.com
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.Collections.Generic;
using System.Text;
using Mono.Cecil;
using Mono.Cecil.Cil;
using de4dot.blocks;
namespace de4dot.code.deobfuscators.DeepSea {
class StringDecrypter {
ModuleDefinition module;
MethodDefinitionAndDeclaringTypeDict<DecrypterInfo> methodToInfo = new MethodDefinitionAndDeclaringTypeDict<DecrypterInfo>();
class DecrypterInfo {
MethodDefinition cctor;
public MethodDefinition method;
FieldDefinition cachedStringsField;
FieldDefinition keyField;
int magic;
string[] encryptedStrings;
short[] key;
public DecrypterInfo(MethodDefinition cctor, MethodDefinition method) {
this.cctor = cctor;
this.method = method;
}
public string decrypt(int magic2) {
var es = encryptedStrings[magic ^ magic2];
var sb = new StringBuilder(es.Length);
for (int i = 0; i < es.Length; i++)
sb.Append((char)(es[i] ^ key[(magic2 + i) % key.Length]));
return sb.ToString();
}
public bool initialize() {
if (!findMagic(method, out magic))
return false;
if (!findFields())
return false;
if (!findEncryptedStrings(method))
return false;
key = findKey();
if (key.Length == 0)
return false;
return true;
}
bool findFields() {
foreach (var instr in method.Body.Instructions) {
if (instr.OpCode.Code != Code.Stsfld && instr.OpCode.Code != Code.Ldsfld)
continue;
var field = instr.Operand as FieldDefinition;
if (field == null)
continue;
if (!MemberReferenceHelper.compareTypes(method.DeclaringType, field.DeclaringType))
continue;
switch (field.FieldType.FullName) {
case "System.Char[]":
if (keyField != null && keyField != field)
return false;
keyField = field;
break;
case "System.String[]":
if (cachedStringsField != null && cachedStringsField != field)
return false;
cachedStringsField = field;
break;
default:
break;
}
}
return keyField != null && cachedStringsField != null;
}
short[] findKey() {
var pkt = cctor.Module.Assembly.Name.PublicKeyToken;
if (pkt != null && pkt.Length > 0)
return getPublicKeyTokenKey(pkt);
return findKey(cctor);
}
short[] findKey(MethodDefinition initMethod) {
var instrs = initMethod.Body.Instructions;
for (int i = 0; i < instrs.Count - 1; i++) {
var ldci4 = instrs[i];
if (!DotNetUtils.isLdcI4(ldci4))
continue;
var newarr = instrs[i + 1];
if (newarr.OpCode.Code != Code.Newarr)
continue;
if (newarr.Operand.ToString() != "System.Char")
continue;
i++;
var array = ArrayFinder.getInitializedInt16Array(DotNetUtils.getLdcI4Value(ldci4), initMethod, ref i);
if (array == null)
continue;
i++;
if (i >= instrs.Count)
return null;
var stsfld = instrs[i];
if (stsfld.OpCode.Code != Code.Stsfld)
continue;
if (MemberReferenceHelper.compareFieldReferenceAndDeclaringType(keyField, stsfld.Operand as FieldReference))
return array;
}
return null;
}
static short[] getPublicKeyTokenKey(byte[] publicKeyToken) {
var key = new short[publicKeyToken.Length];
for (int i = 0; i < publicKeyToken.Length; i++) {
int b = publicKeyToken[i];
key[i] = (short)((b << 4) ^ b);
}
return key;
}
static bool findMagic(MethodDefinition method, out int magic) {
var instrs = method.Body.Instructions;
for (int i = 0; i < instrs.Count - 2; i++) {
var ldarg = instrs[i];
if (DotNetUtils.getArgIndex(ldarg) != 0)
continue;
var ldci4 = instrs[i + 1];
if (!DotNetUtils.isLdcI4(ldci4))
continue;
if (instrs[i + 2].OpCode.Code != Code.Xor)
continue;
magic = DotNetUtils.getLdcI4Value(ldci4);
return true;
}
magic = 0;
return false;
}
bool findEncryptedStrings(MethodDefinition method) {
var switchInstr = getOnlySwitchInstruction(method);
if (switchInstr == null)
return false;
var targets = (Instruction[])switchInstr.Operand;
encryptedStrings = new string[targets.Length];
for (int i = 0; i < targets.Length; i++) {
var target = targets[i];
if (target.OpCode.Code != Code.Ldstr)
return false;
encryptedStrings[i] = (string)target.Operand;
}
return true;
}
static Instruction getOnlySwitchInstruction(MethodDefinition method) {
Instruction switchInstr = null;
foreach (var instr in method.Body.Instructions) {
if (instr.OpCode.Code != Code.Switch)
continue;
if (switchInstr != null)
return null;
switchInstr = instr;
}
return switchInstr;
}
public override string ToString() {
return string.Format("M:{0:X8} N:{1}", magic, encryptedStrings.Length);
}
}
public bool Detected {
get { return methodToInfo.Count != 0; }
}
public List<MethodDefinition> DecrypterMethods {
get {
var methods = new List<MethodDefinition>(methodToInfo.Count);
foreach (var info in methodToInfo.getValues())
methods.Add(info.method);
return methods;
}
}
public StringDecrypter(ModuleDefinition module) {
this.module = module;
}
public void find(ISimpleDeobfuscator simpleDeobfuscator) {
bool hasPublicKeyToken = module.Assembly.Name.PublicKeyToken != null && module.Assembly.Name.PublicKeyToken.Length != 0;
foreach (var type in module.GetTypes()) {
if (!checkFields(type.Fields))
continue;
var cctor = DotNetUtils.getMethod(type, ".cctor");
if (cctor == null)
continue;
if (!hasPublicKeyToken)
simpleDeobfuscator.deobfuscate(cctor);
foreach (var method in DotNetUtils.findMethods(type.Methods, "System.String", new string[] { "System.Int32" }, true)) {
simpleDeobfuscator.deobfuscate(method);
var info = getInfo(cctor, method);
if (info == null)
continue;
methodToInfo.add(method, info);
}
}
}
static bool checkFields(IEnumerable<FieldDefinition> fields) {
bool foundCharAry = false, foundStringAry = false;
foreach (var field in fields) {
if (foundCharAry && foundStringAry)
break;
switch (field.FieldType.FullName) {
case "System.Char[]":
foundCharAry = true;
break;
case "System.String[]":
foundStringAry = true;
break;
}
}
return foundCharAry && foundStringAry;
}
DecrypterInfo getInfo(MethodDefinition cctor, MethodDefinition method) {
if (method == null || method.Body == null)
return null;
var info = new DecrypterInfo(cctor, method);
if (!info.initialize())
return null;
return info;
}
public string decrypt(MethodReference method, int magic2) {
var info = methodToInfo.find(method);
return info.decrypt(magic2);
}
}
}

View File

@ -33,6 +33,7 @@ namespace de4dot.cui {
new de4dot.code.deobfuscators.Babel_NET.DeobfuscatorInfo(),
new de4dot.code.deobfuscators.CliSecure.DeobfuscatorInfo(),
new de4dot.code.deobfuscators.CryptoObfuscator.DeobfuscatorInfo(),
new de4dot.code.deobfuscators.DeepSea.DeobfuscatorInfo(),
new de4dot.code.deobfuscators.Dotfuscator.DeobfuscatorInfo(),
new de4dot.code.deobfuscators.dotNET_Reactor.v3.DeobfuscatorInfo(),
new de4dot.code.deobfuscators.dotNET_Reactor.v4.DeobfuscatorInfo(),