/// <summary> /// /// </summary> /// <param name="module">The .NET protected ModuleDefMD</param> /// <param name="Methoddecryption">The method which decrypt the strings</param> public static void DecryptStringsInMethod(ModuleDefMD module, MethodDef Methoddecryption) { foreach (TypeDef type in module.Types) { foreach (MethodDef method in type.Methods) { if (!method.HasBody) break; for (int i = 0; i < method.Body.Instructions.Count; i++) { if (method.Body.Instructions[i].OpCode == OpCodes.Call) { if (method.Body.Instructions[i].Operand.ToString().ToLower().Contains(Typedecryption.Name.ToLower())) { Type2Remove.Add(Typedecryption); var CalledDecMethod = (MethodDef)method.Body.Instructions[i].Operand; var decryptedstring = ExtractStringFromMethod(CalledDecMethod); if (decryptedstring == "[DEObfuscar] Error") { // } else { CilBody body = method.Body; body.Instructions[i].OpCode = OpCodes.Ldstr; body.Instructions[i].Operand = decryptedstring; DeobedStringNumber = DeobedStringNumber + 1; } } } } } } }
public static MethodDef GetDecryptType(ModuleDefMD asmodule) { // var module_types = asmodule.Types; asm = asmodule; // foreach (TypeDef type in module_types) { if (type.Name == "<Module>") continue; foreach (MethodDef method in type.Methods) { if (!method.HasBody) continue; if (!method.IsConstructor) continue; var instrsdec = method.Body.Instructions; if (instrsdec.Count < 5) continue; for (int i = 0; i < instrsdec.Count; i++) { if (method.Body.Instructions[0].OpCode == OpCodes.Ldstr && method.Body.Instructions[1].OpCode == OpCodes.Call && method.Body.Instructions[2].OpCode == OpCodes.Stsfld) { return method; } } } } return null; }
public AssemblyResolver(ModuleDefMD module, DecrypterType decrypterType) { this.module = module; this.frameworkType = DotNetUtils.getFrameworkType(module); this.decrypterType = decrypterType; this.codeCompilerMethodCallRestorer = new CodeCompilerMethodCallRestorer(module); }
ResourceWriter(ModuleDefMD module, Stream stream, ResourceElementSet resources) { this.module = module; this.typeCreator = new ResourceDataCreator(module); this.writer = new BinaryWriter(stream); this.resources = resources; }
private static FieldDef CreateField(ModuleDefMD module) { FieldAttributes attrb = FieldAttributes.Public | FieldAttributes.Static | FieldAttributes.HasFieldRVA | FieldAttributes.CompilerControlled; FieldDef field = new FieldDefUser("", new FieldSig(module.CorLibTypes.String), attrb); RenameTask.Rename(field); return field; }
public static EmbeddedAssemblyInfo create(ModuleDefMD module, string encName, string rsrcName) { var info = new EmbeddedAssemblyInfo(); try { if (encName == "" || Convert.ToBase64String(Convert.FromBase64String(encName)) != encName) return null; } catch (FormatException) { return null; } if (rsrcName.Length > 0 && rsrcName[0] == '[') { int i = rsrcName.IndexOf(']'); if (i < 0) return null; info.flags = rsrcName.Substring(1, i - 1); info.isTempFile = info.flags.IndexOf('t') >= 0; info.isCompressed = info.flags.IndexOf('z') >= 0; rsrcName = rsrcName.Substring(i + 1); } if (rsrcName == "") return null; info.assemblyName = Encoding.UTF8.GetString(Convert.FromBase64String(encName)); info.resourceName = rsrcName; info.resource = DotNetUtils.getResource(module, rsrcName) as EmbeddedResource; info.simpleName = Utils.getAssemblySimpleName(info.assemblyName); return info; }
public static EmbeddedResource findEmbeddedResource(ModuleDefMD module, TypeDef decrypterType, ISimpleDeobfuscator simpleDeobfuscator, IDeobfuscator deob) { return findEmbeddedResource(module, decrypterType, (method) => { simpleDeobfuscator.deobfuscate(method); simpleDeobfuscator.decryptStrings(method, deob); }); }
public ReferenceFolderTreeNode(ModuleDefMD module, AssemblyTreeNode parentAssembly, AssemblyListTreeNode assemblyListTreeNode) { this.module = module; this.parentAssembly = parentAssembly; this.assemblyListTreeNode = assemblyListTreeNode; this.LazyLoading = true; }
public ResolverBase(ModuleDefMD module, ISimpleDeobfuscator simpleDeobfuscator, IDeobfuscator deob) { this.module = module; this.frameworkType = DotNetUtils.getFrameworkType(module); this.simpleDeobfuscator = simpleDeobfuscator; this.deob = deob; }
ModuleDefMD SetModule(ModuleDefMD newModule) { module = newModule; TheAssemblyResolver.Instance.AddModule(module); module.EnableTypeDefFindCache = true; module.Location = filename; return module; }
public BamlDocument Analyze(ModuleDefMD module, string bamlName, byte[] data) { this.module = module; this.bamlName = bamlName; if (module.IsClr40) { things = thingsv4 ?? (thingsv4 = new KnownThingsv4(context, module)); } else { things = thingsv3 ?? (thingsv3 = new KnownThingsv3(context, module)); } Debug.Assert(BitConverter.ToInt32(data, 0) == data.Length - 4); BamlDocument document = BamlReader.ReadDocument(new MemoryStream(data, 4, data.Length - 4)); // Remove debug infos document.RemoveWhere(rec => rec is LineNumberAndPositionRecord || rec is LinePositionRecord); // Populate references PopulateReferences(document); // Process elements BamlElement rootElem = BamlElement.Read(document); BamlElement trueRoot = rootElem.Children.Single(); var stack = new Stack<BamlElement>(); stack.Push(rootElem); while (stack.Count > 0) { BamlElement elem = stack.Pop(); ProcessBAMLElement(trueRoot, elem); foreach (BamlElement child in elem.Children) stack.Push(child); } return document; }
public ImageReader(IDeobfuscatorContext deobfuscatorContext, ModuleDefMD module, byte[] data) { this.deobfuscatorContext = deobfuscatorContext; this.module = module; this.reader = MemoryImageStream.Create(data); this.memberRefConverter = new MemberRefConverter(module); }
public MethodsDecrypter(ModuleDefMD module, MethodsDecrypter oldOne) { this.module = module; this.encryptedResource = new EncryptedResource(module, oldOne.encryptedResource); this.tokenToNativeMethod = oldOne.tokenToNativeMethod; this.totalEncryptedNativeMethods = oldOne.totalEncryptedNativeMethods; this.xorKey = oldOne.xorKey; }
static EmbeddedResource FindEmbeddedResource1(ModuleDefMD module, MethodDef method) { foreach (var s in DotNetUtils.GetCodeStrings(method)) { var resource = DotNetUtils.GetResource(module, s) as EmbeddedResource; if (resource != null) return resource; } return null; }
public Csvm(IDeobfuscatorContext deobfuscatorContext, ModuleDefMD module, Csvm oldOne) { this.deobfuscatorContext = deobfuscatorContext; this.module = module; if (oldOne.resource != null) this.resource = (EmbeddedResource)module.Resources[oldOne.module.Resources.IndexOf(oldOne.resource)]; if (oldOne.vmAssemblyRef != null) this.vmAssemblyRef = module.ResolveAssemblyRef(oldOne.vmAssemblyRef.Rid); }
private static List<MethodDef> GetInstrumentationMethods(ModuleDefMD instrumentationAssembly, TypeDef instrumentedAttribute, ModuleDefMD sourceAssembly) { return instrumentationAssembly.Types .Where(x => x.FullName != instrumentedAttribute.FullName) .Where(x => FindSourceType(x.ToTypeSig(), sourceAssembly) != null) .SelectMany(x => x.Methods) .Where(y => y.CustomAttributes.Any(x => x.AttributeType == instrumentedAttribute)).ToList(); }
// Following codes are auto-generated, do not modify. void InitAssemblies(ModuleDefMD initMod) { assemblies[0] = context.Resolver.ResolveThrow("PresentationFramework, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35", initMod); assemblies[1] = context.Resolver.ResolveThrow("PresentationCore, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35", initMod); assemblies[2] = context.Resolver.ResolveThrow("mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", initMod); assemblies[3] = context.Resolver.ResolveThrow("System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", initMod); assemblies[4] = context.Resolver.ResolveThrow("WindowsBase, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35", initMod); assemblies[5] = context.Resolver.ResolveThrow("System.Xml, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", initMod); }
CustomAttributeReader(ModuleDefMD readerModule, uint offset) { this.module = readerModule; this.reader = readerModule.BlobStream.CreateStream(offset); this.ownReader = true; this.genericArguments = null; this.recursionCounter = new RecursionCounter(); this.verifyReadAllBytes = false; }
public ProxyCallFixer(ModuleDefMD module, byte[] fileData) : base(module) { this.fileData = fileData; if (module.Assembly == null) ourAsm = " -1-1-1-1-1- , Version=1.2.3.4, Culture=neutral, PublicKeyToken=null"; else ourAsm = module.Assembly.FullName; }
public MyDeobfuscator(ModuleDefMD module) { cliSecureRtType = new CliSecureRtType(module); cliSecureRtType.Find(null); stringDecrypter = new StringDecrypter(module, cliSecureRtType.StringDecrypterMethod); stringDecrypter.Find(); cliSecureRtType.FindStringDecrypterMethod(); stringDecrypter.Method = cliSecureRtType.StringDecrypterMethod; staticStringInliner.Add(stringDecrypter.Method, (method, gim, args) => stringDecrypter.Decrypt((string)args[0])); }
public ProxyCallFixer(ModuleDefMD module, MainType mainType, ProxyCallFixer oldOne) : base(module, oldOne) { this.mainType = mainType; info.proxyType = Lookup(oldOne.info.proxyType, "Could not find proxyType"); info.initMethod = Lookup(oldOne.info.initMethod, "Could not find initMethod"); info.dataField = Lookup(oldOne.info.dataField, "Could not find dataField"); info.ilgeneratorType = Lookup(oldOne.info.ilgeneratorType, "Could not find ilgeneratorType"); info.fieldInfoType = Lookup(oldOne.info.fieldInfoType, "Could not find fieldInfoType"); info.methodInfoType = Lookup(oldOne.info.methodInfoType, "Could not find methodInfoType"); }
public static List<MethodDef> FindAll(ModuleDefMD module) { var list = new List<MethodDef>(); foreach (var type in module.GetTypes()) { foreach (var method in type.Methods) { if (IsInvalidMethod(method)) list.Add(method); } } return list; }
public KnownThingsv3(ConfuserContext context, ModuleDefMD initMod) { this.context = context; assemblies = new Dictionary<int, AssemblyDef>(); types = new Dictionary<KnownTypes, TypeDef>(); properties = new Dictionary<KnownProperties, Tuple<KnownTypes, PropertyDef, TypeDef>>(); InitAssemblies(initMod); InitTypes(); InitProperties(); }
private static string FetchBlobSignature(ModuleDefMD mod) { var blobStream = mod.BlobStream.ImageStream; var rawBuff = new byte[blobStream.Length]; var exp = new Regex("Confuser v[0-9].[0-9].[0-9].[0-9]"); blobStream.Read(rawBuff, 0, rawBuff.Length); var match = exp.Match(Encoding.UTF8.GetString(rawBuff)); return match.Success ? match.Groups[0].Value : null; }
public MyDeobfuscator(ModuleDefMD module) { cliSecureRtType = new CliSecureRtType(module); cliSecureRtType.Find(null); stringDecrypter = new StringDecrypter(module, cliSecureRtType.StringDecrypterInfos); stringDecrypter.Find(); cliSecureRtType.FindStringDecrypterMethod(); stringDecrypter.AddDecrypterInfos(cliSecureRtType.StringDecrypterInfos); stringDecrypter.Initialize(); foreach (var info in stringDecrypter.StringDecrypterInfos) staticStringInliner.Add(info.Method, (method, gim, args) => stringDecrypter.Decrypt((string)args[0])); }
public static bool IsSimpleZipDecryptMethod_QuickCheck(ModuleDefMD module, IMethod method, out MethodDef simpleZipTypeMethod) { simpleZipTypeMethod = null; if (!DotNetUtils.IsMethod(method, "System.Byte[]", "(System.Byte[])")) return false; var methodDef = DotNetUtils.GetMethod(DotNetUtils.GetType(module, method.DeclaringType), method); if (methodDef == null) return false; simpleZipTypeMethod = methodDef; return true; }
public static EmbeddedResource FindEmbeddedResource(ModuleDefMD module, TypeDef decrypterType, Action<MethodDef> fixMethod) { foreach (var method in decrypterType.Methods) { if (!DotNetUtils.IsMethod(method, "System.String", "()")) continue; if (!method.IsStatic) continue; fixMethod(method); var resource = FindEmbeddedResource1(module, method) ?? FindEmbeddedResource2(module, method); if (resource != null) return resource; } return null; }
private static TypeDef FindInstrumentedAttribute(ModuleDefMD instrumentationAssembly) { const string attributeName = "InstrumentedAttribute"; List<TypeDef> types = instrumentationAssembly.Types.Where(x => x.Name == attributeName).ToList(); if (types.Count > 1) { throw new ApplicationException($"There is more than one {attributeName} in instrumenataion assembly"); } if (types.Count == 0) { throw new ApplicationException($"There is no {attributeName} in instrumenataion assembly"); } return types[0]; }
public static string DecryptResourceName(ModuleDefMD module, MethodDef method) { string resourceName = ""; MethodDef cctor = method, orginalResMethod = null; // retrive key and encrypted resource name int key = 0; var instrs = cctor.Body.Instructions; for (int i = 0; i < instrs.Count - 2; i++) { if (instrs[i].OpCode != OpCodes.Ldstr) continue; if (!instrs[i + 1].IsLdcI4()) break; key = instrs[i + 1].GetLdcI4Value(); resourceName = instrs[i].Operand as String; cctor = instrs[i + 2].Operand as MethodDef; break; } // Find the method that contains resource name while (orginalResMethod == null) { foreach (var instr in cctor.Body.Instructions) { if (instr.OpCode == OpCodes.Ldftn) { MethodDef tempMethod = instr.Operand as MethodDef; if (tempMethod.ReturnType.FullName != "System.String") continue; orginalResMethod = tempMethod; break; } else if (instr.OpCode == OpCodes.Callvirt) { cctor = instr.Operand as MethodDef; cctor = cctor.DeclaringType.FindStaticConstructor(); break; } } } // Get encrypted Resource name string encResourcename = DotNetUtils.GetCodeStrings(orginalResMethod)[0]; // get Decryption key int xorKey = 0; for (int i = 0; i < orginalResMethod.Body.Instructions.Count; i++) { if (orginalResMethod.Body.Instructions[i].OpCode == OpCodes.Xor) xorKey = orginalResMethod.Body.Instructions[i - 1].GetLdcI4Value(); } encResourcename = XorCipher(encResourcename, xorKey); var firstResource = GetResource(module, new string[] { encResourcename }); resourceName = DecryptResourceName(resourceName, key, firstResource.GetResourceData()); return resourceName; }
public static EmbeddedResource GetResource(ModuleDefMD module, IEnumerable<string> names) { foreach (var name in names) { var resource = DotNetUtils.GetResource(module, name) as EmbeddedResource; if (resource != null) return resource; try { resource = DotNetUtils.GetResource(module, Encoding.UTF8.GetString(Convert.FromBase64String(name))) as EmbeddedResource; if (resource != null) return resource; } catch { } } return null; }
private WeavingContext CreateWeavingContext(ModuleDefMD moduleDefinition) { var context = new WeavingContext { CompilerGeneratedAttributeType = moduleDefinition.Import(typeof(CompilerGeneratedAttribute)), PriorityAttributeType = TypeResolver.Resolve(moduleDefinition, typeof(PriorityAttribute)), AbstractTargetAttributeType = TypeResolver.Resolve(moduleDefinition, typeof(AbstractTargetAttribute)), AdviceInterfaceType = TypeResolver.Resolve(moduleDefinition, typeof(IAdvice)), WeavingAdviceInterfaceType = TypeResolver.Resolve(moduleDefinition, typeof(IWeavingAdvice)), ExecutionPointAttributeDefaultCtor = moduleDefinition.Import(TypeResolver.Resolve(moduleDefinition, typeof(ExecutionPointAttribute)).FindDefaultConstructor()), ExcludePointcutAttributeType = TypeResolver.Resolve(moduleDefinition, typeof(ExcludePointcutAttribute)), IncludePointcutAttributeType = TypeResolver.Resolve(moduleDefinition, typeof(IncludePointcutAttribute)), ExcludeAdviceAttributeType = TypeResolver.Resolve(moduleDefinition, typeof(ExcludeAdvicesAttribute)), }; return(context); }
/// <summary> /// Weaves the specified module definition. /// </summary> /// <param name="moduleDefinition">The module definition.</param> public bool Weave(ModuleDefMD moduleDefinition) { var auditTimer = new AuditTimer(); try { // sanity check auditTimer.NewZone("Types import"); // context var context = CreateWeavingContext(moduleDefinition); if (context.AdviceInterfaceType == null) { Logging.WriteWarning("IAdvice interface not found here (not referenced means not used), exiting"); return(false); } // runtime check auditTimer.NewZone("Runtime check"); var targetFramework = GetTargetFramework(moduleDefinition); InjectAsPrivate = targetFramework.Silverlight == null && targetFramework.WindowsPhone == null; // weave methods (they can be property-related, too) auditTimer.NewZone("Weavable methods detection"); Func <MarkedNode, bool> isWeavable = n => IsWeavable(n) && !IsFromComputerGeneratedType(n); var weavingAdvicesMethods = GetMarkedMethods(moduleDefinition, context.WeavingAdviceInterfaceType, context).Where(isWeavable).ToArray(); var weavableMethods = GetMarkedMethods(moduleDefinition, context.AdviceInterfaceType, context).Where(isWeavable).ToArray(); auditTimer.NewZone("Abstract targets"); var generatedFieldsToBeRemoved = new List <FieldDef>(); var methodsWithAbstractTarget = weavableMethods.Where(m => m.AbstractTarget).ToArray(); if (methodsWithAbstractTarget.Length > 0) { generatedFieldsToBeRemoved.AddRange(GetRemovableFields(methodsWithAbstractTarget, context)); foreach (var fieldReference in generatedFieldsToBeRemoved) { Logging.WriteDebug("Field {0} to be removed", fieldReference.FullName); } } auditTimer.NewZone("Methods weaving advice"); weavingAdvicesMethods.ForAll(i => RunWeavingAdvices(i, context)); auditTimer.NewZone("Methods weaving"); weavableMethods.ForAll(m => WeaveMethod(moduleDefinition, m, context)); auditTimer.NewZone("Weavable interfaces detection"); var weavableInterfaces = GetAdviceHandledInterfaces(moduleDefinition).Union(GetDynamicHandledInterfaces(moduleDefinition)).ToArray(); auditTimer.NewZone("Interface methods weaving"); weavableInterfaces.ForAll(i => WeaveInterface(moduleDefinition, i, context)); // and then, the info advices auditTimer.NewZone("Info advices weaving"); var infoAdviceInterface = TypeResolver.Resolve(moduleDefinition, typeof(IInfoAdvice)); moduleDefinition.GetTypes().ForAll(t => WeaveInfoAdvices(moduleDefinition, t, infoAdviceInterface, context)); auditTimer.NewZone("Abstract targets cleanup"); foreach (var generatedFieldToBeRemoved in generatedFieldsToBeRemoved) { generatedFieldToBeRemoved.DeclaringType.Fields.Remove(generatedFieldToBeRemoved); } auditTimer.LastZone(); var report = auditTimer.GetReport(); var maxLength = report.Keys.Max(k => k.Length); Logging.WriteDebug("--- Timings --------------------------"); foreach (var reportPart in report) { Logging.WriteDebug("{0} : {1}ms", reportPart.Key.PadRight(maxLength), (int)reportPart.Value.TotalMilliseconds); } Logging.WriteDebug("--------------------------------------"); Logging.Write("MrAdvice {3} weaved module '{0}' (targeting framework {2}) in {1}ms", moduleDefinition.Assembly.FullName, (int)report.Sum(r => r.Value.TotalMilliseconds), targetFramework.ToString(), Product.Version); return(true); } catch (Exception e) { Logging.WriteError("Internal error during {0}: {1}", auditTimer.CurrentZoneName, e); Logging.WriteError("Please complain, whine, cry, yell at https://github.com/ArxOne/MrAdvice/issues/new"); return(false); } }