private void ProtectStrings(ModuleDefMD module) //Encodes all the strings. { foreach (TypeDef type in module.GetTypes()) { foreach (MethodDef method in type.Methods) { if (!method.HasBody) { continue; } var instr = method.Body.Instructions; for (int i = 0; i < instr.Count; i++) { if (instr[i].OpCode == OpCodes.Ldstr) { var originalStr = instr[i].Operand as string; if (Exclusion.ExcludedStrings.Contains(originalStr)) { continue; } var encodedStr = StringEncoding.EncryptString(originalStr); instr[i].Operand = encodedStr; instr.Insert(i + 1, Instruction.Create(OpCodes.Call, _injectedMethodDef)); method.Body.SimplifyBranches(); method.Body.OptimizeBranches(); } } } } }
Dictionary <FieldInfo, bool> FindFieldsToKeep() { var keep = new Dictionary <FieldInfo, bool>(); foreach (var type in module.GetTypes()) { foreach (var method in type.Methods) { if (type == DotNetUtils.GetModuleType(module) && method.Name == ".cctor") { continue; } if (method.Body == null) { continue; } foreach (var instr in method.Body.Instructions) { var field = instr.Operand as IField; if (field == null) { continue; } var fieldInfo = fieldToInfo.Find(field); if (fieldInfo == null) { continue; } keep[fieldInfo] = true; } } } return(keep); }
public void Find(ISimpleDeobfuscator simpleDeobfuscator) { foreach (var type in module.GetTypes()) { FindStringDecrypterMethods(type, simpleDeobfuscator); } }
public void find() { var additionalTypes = new string[] { "System.IntPtr", // "System.Reflection.Assembly", //TODO: Not in unknown DNR version with jitter support }; var checkedMethods = new Dictionary<IMethod, bool>(MethodEqualityComparer.CompareDeclaringTypes); var callCounter = new CallCounter(); int typesLeft = 30; foreach (var type in module.GetTypes()) { var cctor = type.FindStaticConstructor(); if (cctor == null || cctor.Body == null) continue; if (typesLeft-- <= 0) break; foreach (var method in DotNetUtils.getCalledMethods(module, cctor)) { if (!checkedMethods.ContainsKey(method)) { checkedMethods[method] = false; if (method.DeclaringType.BaseType == null || method.DeclaringType.BaseType.FullName != "System.Object") continue; if (!DotNetUtils.isMethod(method, "System.Void", "()")) continue; if (!encryptedResource.couldBeResourceDecrypter(method, additionalTypes)) continue; checkedMethods[method] = true; } else if (!checkedMethods[method]) continue; callCounter.add(method); } } encryptedResource.Method = (MethodDef)callCounter.most(); }
public void Apply(ModuleDefMD module) { foreach (var type in module.GetTypes()) { Apply(module, type); } }
/// <summary> /// The FileMethods /// </summary> /// <param name="mod">The mod<see cref="ModuleDefMD"/></param> /// <returns>The <see cref="IEnumerable{string}"/></returns> private IEnumerable <string> FileMethods(ModuleDefMD mod) { var dList = new List <string>(); string[] items = new string[] { "submit_file", "Form1_Load", "vtot" }; foreach (var td in mod.GetTypes()) //mod.GetTypes() palauttaa kaikki tyypit myös nested { foreach (var mDef in td.Methods) { //loopataan metodit // MessageBox.Show(mDef.Name); foreach (string i in items) //loopataan items lista { if (mDef.Name.Contains(i)) //jos metodi löytyy items listasta lisää toiseen listaan { dList.Add(i); } } } } if (dList.Count != 0) { var message = string.Join(Environment.NewLine, dList); MessageBox.Show(message, @"Methods", MessageBoxButtons.OK, MessageBoxIcon.Information); } return(dList); }
public ModuleDefMD Rename(ModuleDefMD module) { ModuleDefMD moduleToRename = module; foreach (TypeDef type in moduleToRename.GetTypes()) { if (type.IsGlobalModuleType) { continue; } if (type.Name == "GeneratedInternalTypeHelper") { continue; } foreach (MethodDef method in type.Methods) { if (!method.HasBody) { continue; } if (method.Name == ".ctor" || method.Name == ".cctor") { continue; } method.Name = Utils.GenerateRandomString(); } } return(moduleToRename); }
static void Main(string[] args) { if (args.Length == 0) { Console.WriteLine("Usage: AgentTeslaStringDecryptor.exe <pathToFile>"); System.Environment.Exit(1); } string filename = args[0]; Console.WriteLine("Dercypting strings from binary: {0}", filename); try { ModuleDefMD mod = ModuleDefMD.Load(filename); TypeDef typeDefMD = FindMaxTypeByFields(mod.GetTypes().ToList()); Console.WriteLine("Module name with max nuber of fields: {0}, numbers of fields: {1}", typeDefMD.Name, typeDefMD.Fields.Count); StreamWriter sw = File.CreateText("decStringsOut.txt"); for (int i = 1; i < typeDefMD.Fields.Count; i++) { if (typeDefMD.Fields.ElementAt(i).InitialValue is System.Byte[]) { sw.WriteLine("{0} {1}", i, decryptString(typeDefMD.Fields.ElementAt(i).InitialValue)); } } sw.Close(); Console.WriteLine("Done, enter key ..."); Console.ReadKey(); } catch (BadImageFormatException e) { Console.WriteLine("Load binary error: {0}", e.Message); Console.WriteLine(".Net binary is required"); } }
private static void RemoveJunkMethods(ModuleDefMD module) { int num = 0; foreach (TypeDef current in module.GetTypes()) { List <MethodDef> list = new List <MethodDef>(); foreach (MethodDef current2 in current.Methods) { bool flag = junkMethods.Contains(current2); if (flag) { list.Add(current2); } } int num2; for (int i = 0; i < list.Count; i = num2 + 1) { current.Methods.Remove(list[i]); num2 = num; num = num2 + 1; num2 = i; } list.Clear(); } junkMethods.Clear(); bool flag2 = num > 0; }
public static void Execute(ModuleDefMD module) { Write($"Fixing the Call To Calli protection..", Type.Info); Remove_Nops.Execute(module); var callsFixed = 0; foreach (var type in module.GetTypes().Where(t => t.HasMethods)) { foreach (var method in type.Methods.Where(m => m.HasBody && m.Body.HasInstructions)) { var instr = method.Body.Instructions; for (var i = 0; i < instr.Count; i++) { if (instr[i].OpCode == OpCodes.Ldftn && instr[i + 1].OpCode == OpCodes.Calli) { instr[i + 1].OpCode = OpCodes.Nop; instr[i].OpCode = OpCodes.Call; callsFixed++; Write($"Fixed the call in method: {method.Name} at offset: {instr[i].Offset}", Type.Debug); } } } } Write(callsFixed == 0 ? "No Call To Calli found !" : callsFixed == 1 ? $"Fixed {callsFixed} call !" : callsFixed > 1 ? $"Fixed {callsFixed} calls !" : "", Type.Success); }
public ModuleDefMD Rename(ModuleDefMD module) { ModuleDefMD moduleToRename = module; foreach (TypeDef type in moduleToRename.GetTypes()) { if (type.IsGlobalModuleType) { continue; } foreach (var field in type.Fields) { string nameValue; if (_names.TryGetValue(field.Name, out nameValue)) { field.Name = nameValue; } else { string newName = Utils.GenerateRandomString(); _names.Add(field.Name, newName); field.Name = newName; } } } return(ApplyChangesToResources(moduleToRename)); }
public static void Execute(ModuleDefMD module) { Write($"Fixing the Empty Types protection..", Type.Info); Remove_Nops.Execute(module); var emptyTypesFixed = 0; foreach (var type in module.GetTypes().Where(t => t.HasMethods)) { foreach (var method in type.Methods.Where(m => m.HasBody && m.Body.HasInstructions)) { var instr = method.Body.Instructions; for (var i = 0; i < instr.Count; i++) { if (instr[i].OpCode == OpCodes.Ldsfld && instr[i].Operand.ToString().Contains("System.Type::EmptyTypes") && instr[i + 1].OpCode == OpCodes.Ldlen) { instr[i + 1].OpCode = OpCodes.Nop; instr[i].OpCode = OpCodes.Ldc_I4; instr[i].Operand = 0; emptyTypesFixed++; Write($"Fixed the empty types in method: {method.Name} at offset: {instr[i].Offset}", Type.Debug); } } } } Write(emptyTypesFixed == 0 ? "No Empty Types found !" : $"Fixed {emptyTypesFixed} empty types protection !", Type.Success); }
public static void ReplaceCtorLDCI4(ModuleDefMD module, int value, FieldDef field) { foreach (TypeDef type in module.GetTypes()) { if (!type.IsGlobalModuleType) { foreach (MethodDef method in type.Methods) { if (method.HasBody && method.Body.HasInstructions) { foreach (var instr in method.Body.Instructions) { if (instr.OpCode == OpCodes.Ldsfld) { if (instr.Operand is FieldDef && instr.Operand == field) { instr.OpCode = OpCodes.Ldc_I4; instr.Operand = value; } } } } } } } }
public void Apply() { string gameInputPath = subnauticaBasePath + GAME_ASSEMBLY_NAME; string nitroxPatcherPath = subnauticaBasePath + NITROX_ASSEMBLY_NAME; string modifiedAssemblyPath = subnauticaBasePath + GAME_ASSEMBLY_MODIFIED_NAME; using (ModuleDefMD module = ModuleDefMD.Load(gameInputPath)) using (ModuleDefMD nitroxPatcherAssembly = ModuleDefMD.Load(nitroxPatcherPath)) { TypeDef nitroxMainDefinition = nitroxPatcherAssembly.GetTypes().FirstOrDefault(x => x.Name == NITROX_ENTRY_TYPE_NAME); MethodDef executeMethodDefinition = nitroxMainDefinition.Methods.FirstOrDefault(x => x.Name == NITROX_ENTRY_METHOD_NAME); MemberRef executeMethodReference = module.Import(executeMethodDefinition); TypeDef gameInputType = module.GetTypes().First(x => x.FullName == GAME_INPUT_TYPE_NAME); MethodDef awakeMethod = gameInputType.Methods.First(x => x.Name == GAME_INPUT_METHOD_NAME); Instruction callNitroxExecuteInstruction = OpCodes.Call.ToInstruction(executeMethodReference); awakeMethod.Body.Instructions.Insert(0, callNitroxExecuteInstruction); module.Write(modifiedAssemblyPath); } string backuupAssemblyPath = subnauticaBasePath + GAME_ASSEMBLY_BACKUP_NAME; File.Replace(modifiedAssemblyPath, gameInputPath, backuupAssemblyPath); }
void RestoreMethods() { if (methodInfos.Count == 0) { return; } Logger.v("Restoring {0} methods", methodInfos.Count); Logger.Instance.Indent(); foreach (var type in module.GetTypes()) { foreach (var method in type.Methods) { if (method.Body == null) { continue; } if (RestoreMethod(method)) { Logger.v("Restored method {0} ({1:X8}). Instrs:{2}, Locals:{3}, Exceptions:{4}", Utils.RemoveNewlines(method.FullName), method.MDToken.ToInt32(), method.Body.Instructions.Count, method.Body.Variables.Count, method.Body.ExceptionHandlers.Count); } } } Logger.Instance.DeIndent(); if (methodInfos.Count != 0) { Logger.w("{0} methods weren't restored", methodInfos.Count); } }
// Token: 0x060000AE RID: 174 RVA: 0x0000928C File Offset: 0x0000748C private static ModuleDefMD ApplyChangesToResources(ModuleDefMD module) { foreach (TypeDef typeDef in module.GetTypes()) { bool isGlobalModuleType = typeDef.IsGlobalModuleType; if (!isGlobalModuleType) { foreach (MethodDef methodDef in typeDef.Methods) { bool flag = methodDef.Name != "InitializeComponent"; if (!flag) { IList <Instruction> instructions = methodDef.Body.Instructions; for (int i = 0; i < instructions.Count - 3; i++) { bool flag2 = instructions[i].OpCode == OpCodes.Ldstr; if (flag2) { foreach (KeyValuePair <string, string> keyValuePair in Renamer.FieldsRenaming._names) { bool flag3 = keyValuePair.Key == instructions[i].Operand.ToString(); if (flag3) { instructions[i].Operand = keyValuePair.Value; } } } } } } } } return(module); }
/// <summary> /// The NetStrings /// </summary> /// <param name="mod">The mod<see cref="ModuleDefMD"/></param> /// <returns>The <see cref="IEnumerable{string}"/></returns> private IEnumerable <string> NetStrings(ModuleDefMD mod) { var dumpList = new List <string>(); //uusi merkkijonolista foreach (var td in mod.GetTypes()) //// mod.GetTypes() palauttaa kaikki tyypit myös nested { foreach (var mDef in td.Methods) //loopataan jokainen Metodi { if (mDef.HasBody) //Onko MethodDefinition alla mitään True : False { foreach (var instru in mDef.Body.Instructions) //loopataan käskyt { if (Equals(instru.OpCode, OpCodes.Ldstr)) //jos käskyn operaatiokoodi = ldstr lisää listaan { dumpList.Add(instru.ToString()); } } } } } var message = string.Join(Environment.NewLine, dumpList); //yhdistetään listan sisältö jotta ei tarvitse näyttää yksikerrallaan. if (checkBox1.Checked) { MessageBox.Show(message, @"Strings", MessageBoxButtons.OK, MessageBoxIcon.Information); } return(dumpList); }
// Token: 0x060000B5 RID: 181 RVA: 0x000097F4 File Offset: 0x000079F4 public ModuleDefMD Rename(ModuleDefMD module) { foreach (TypeDef typeDef in module.GetTypes()) { bool isGlobalModuleType = typeDef.IsGlobalModuleType; if (!isGlobalModuleType) { bool flag = typeDef.Name == "GeneratedInternalTypeHelper"; if (!flag) { foreach (MethodDef methodDef in typeDef.Methods) { bool flag2 = !methodDef.HasBody; if (!flag2) { bool flag3 = methodDef.Name == ".ctor" || methodDef.Name == ".cctor"; if (!flag3) { methodDef.Name = Renamer.Generator.GenerateString(); } } } } } } return(module); }
public void Find() { foreach (var type in module.GetTypes()) { Initialize(type); } }
// Token: 0x060000B7 RID: 183 RVA: 0x0000990C File Offset: 0x00007B0C public ModuleDefMD Rename(ModuleDefMD module) { foreach (TypeDef typeDef in module.GetTypes()) { bool isGlobalModuleType = typeDef.IsGlobalModuleType; if (!isGlobalModuleType) { bool flag = typeDef.Namespace == ""; if (!flag) { string s; bool flag2 = Renamer.NamespacesRenaming._names.TryGetValue(typeDef.Namespace, out s); if (flag2) { typeDef.Namespace = s; } else { string text = Renamer.Generator.GenerateString(); Renamer.NamespacesRenaming._names.Add(typeDef.Namespace, text); typeDef.Namespace = text; } } } } return(Renamer.NamespacesRenaming.ApplyChangesToResources(module)); }
public void Remove() { string assemblyCSharp = Path.Combine(subnauticaManagedPath, GAME_ASSEMBLY_NAME); string modifiedAssemblyCSharp = Path.Combine(subnauticaManagedPath, GAME_ASSEMBLY_MODIFIED_NAME); using (ModuleDefMD module = ModuleDefMD.Load(assemblyCSharp)) { TypeDef gameInputType = module.GetTypes().First(x => x.FullName == GAME_INPUT_TYPE_NAME); MethodDef awakeMethod = gameInputType.Methods.First(x => x.Name == GAME_INPUT_METHOD_NAME); IList <Instruction> methodInstructions = awakeMethod.Body.Instructions; int nitroxExecuteInstructionIndex = FindNitroxExecuteInstructionIndex(methodInstructions); if (nitroxExecuteInstructionIndex == -1) { return; } methodInstructions.RemoveAt(nitroxExecuteInstructionIndex); module.Write(modifiedAssemblyCSharp); File.SetAttributes(assemblyCSharp, FileAttributes.Normal); } FileSystem.Instance.ReplaceFile(modifiedAssemblyCSharp, assemblyCSharp); }
public static void DeobFuscateMethods(ModuleDefMD module) { int counter = 0; Type[] asm2 = InitPhase.Initializebytes.assembly.ManifestModule.GetTypes(); foreach (TypeDef type in module.GetTypes()) { foreach (MethodDef method in type.Methods) { if (!method.HasBody) { continue; } if (!method.Body.HasInstructions) { continue; } var instructions = method.Body.Instructions; for (int i = 0; i < instructions.Count; i++) { if (instructions[i].OpCode == OpCodes.Ldtoken && instructions[i + 1].IsLdcI4() && (instructions[instructions.Count - 3].OpCode == OpCodes.Call || instructions[instructions.Count - 2].OpCode == OpCodes.Call)) { TypeDef param1 = (TypeDef)instructions[i].Operand; RuntimeTypeHandle t = asm2.First(x => x.Name == param1.ReflectionName).TypeHandle; int param2 = instructions[i + 1].GetLdcI4Value(); CilBody dm = MemeVM_Devirt.InitPhase.Initializebytes.DecryptMethod(method, Type.GetTypeFromHandle(t).Assembly, param2); method.Body = dm; counter++; } } } } Console.WriteLine("Bodies Replaced: " + counter); }
public static void main_poly(string username, int tn) { ModuleContext mod_ctx = ModuleDef.CreateModuleContext(); ModuleDefMD module = ModuleDefMD.Load(@"ldr_base.exe", mod_ctx); if (module == null) { Console.WriteLine("module is null (HOW??)"); return; } Console.WriteLine("tn[{1}] - got module for username {0}", username, tn); /* * big credits to: https://blog.syscall.party/post/writing-a-simple-net-deobfuscator/ * idea and some functions from ^ */ polymorphic.set_username(username); foreach (var type in module.GetTypes()) { //this gives us classes, functions, functions body, etc polymorphic.modify_strings(type); } polymorphic.finish_write(module, username, tn); }
public static void Execute(ModuleDefMD module) { int decrypted = 0; foreach (var type in module.GetTypes()) { foreach (var method in type.Methods) { if (!method.HasBody) { continue; } var instructions = method.Body.Instructions; for (int i = 2; i < instructions.Count; i++) { if (method.Body.Instructions[i].OpCode == OpCodes.Call && method.Body.Instructions[i].Operand.ToString().Contains("Parse") && method.Body.Instructions[i + 1].OpCode == OpCodes.Conv_I4 && method.Body.Instructions[i - 1].OpCode == OpCodes.Ldstr) { Logger.Write($"Fixing {Name} in the method: {method.Name} at the line: {i}", Logger.Type.Info); string valueToPut = method.Body.Instructions[i - 1].Operand.ToString(); string secondvalue = method.Body.Instructions[i - 2].Operand.ToString(); method.Body.Instructions[i].OpCode = OpCodes.Nop; method.Body.Instructions[i - 2].OpCode = OpCodes.Ldc_I4; method.Body.Instructions[i - 2].Operand = (int)double.Parse(secondvalue) + (int)double.Parse(valueToPut); method.Body.Instructions[i - 1].OpCode = OpCodes.Nop; method.Body.Instructions[i + 2].OpCode = OpCodes.Nop; decrypted++; } } } } }
public ModuleDefMD Rename(ModuleDefMD module) { ModuleDefMD moduleToRename = module; foreach (TypeDef type in moduleToRename.GetTypes()) { if (type.IsGlobalModuleType) { continue; } if (type.Name == "GeneratedInternalTypeHelper" || type.Name == "Resources" || type.Name == "Settings") { continue; } string nameValue; if (_names.TryGetValue(type.Name, out nameValue)) { type.Name = nameValue; } else { string newName = Utils.GenerateRandomString(); _names.Add(type.Name, newName); type.Name = newName; } } return(ApplyChangesToResources(moduleToRename)); }
private static MethodDef FindStaticConstructor(ModuleDefMD moduleDef) { MethodDef cctor; cctor = moduleDef.GlobalType.FindStaticConstructor(); if (cctor != null) { return(cctor); } foreach (TypeDef typeDef in moduleDef.GetTypes()) { IList <Instruction> instructions; cctor = typeDef.FindStaticConstructor(); if (cctor == null) { continue; } instructions = cctor.Body.Instructions; if (instructions.Count == 2 && instructions[0].OpCode.Code == Code.Call && (instructions[0].Operand is MethodDef)) { // 只有一个call和ret,否则可能带有其它IL导致执行出错 break; } } return(cctor); }
public override void Deobfuscate() { MutationsBase.ModuleDefMD = Base.ModuleDefMD; MutationsBase.methods = (from type in ModuleDefMD.GetTypes() where type.HasMethods from method in type.Methods where method.HasBody && method.Body.Instructions.Count > 5 select method).ToList(); bool modified = true; while (modified) { modified = false; var ab = new Protections.CodeFlow.FieldFixers.FieldsInCtor(); ab.Deobfuscate(); foreach (MutationsBase cflow in mutationModules) { bool result = cflow.Deobfuscate(); if (result) { modified = true; } } } }
public static void Execute(ModuleDefMD module) { Write("Fixing the Empty Types protection.."); RemoveNops.Execute(module); var emptyTypesFixed = 0; foreach (TypeDef type in module.GetTypes().Where(t => t.HasMethods)) { foreach (MethodDef method in type.Methods.Where(m => m.HasBody && m.Body.HasInstructions)) { IList <Instruction> instr = method.Body.Instructions; for (var i = 1; i < instr.Count; i++) { if (instr[i].OpCode != OpCodes.Ldlen || instr[i - 1].OpCode != OpCodes.Ldsfld) { continue; } if (!(instr[i - 1].Operand is MemberRef memberRef) || memberRef.Name != "EmptyTypes") { continue; } instr[i - 1] = Instruction.Create(OpCodes.Nop); instr[i] = Instruction.Create(OpCodes.Ldc_I4_0); emptyTypesFixed++; Write($"Fixed the empty types in method: {method.Name} at offset: {instr[i].Offset}", Type.Debug); } } } Write(emptyTypesFixed == 0 ? "No Empty Types found !" : $"Fixed {emptyTypesFixed} empty types protection !", Type.Success); }
private List <TypeDef> GetAddedTypes(ModuleDefMD moddedModule, ModuleDefMD originalModule) { var addedTypes = new List <TypeDef>(); var typeFound = false; foreach (var typeDef in moddedModule.GetTypes()) { foreach (var orgTypeDef in originalModule.GetTypes()) { if (typeDef.FullName == orgTypeDef.FullName) { typeFound = true; break; } } if (typeFound == false) { addedTypes.Add(typeDef); } else { typeFound = false; } } return(addedTypes); }
public static void cleaner(ModuleDefMD module) { foreach (TypeDef types in module.GetTypes()) { foreach (MethodDef methods in types.Methods) { if (!methods.HasBody) { continue; } if (hasCflow(methods)) { if (Program.veryVerbose) { Console.ForegroundColor = ConsoleColor.Cyan; Console.Write("Cleaning Control Flow for " + methods.FullName + "\nThe case order is: "); Console.ForegroundColor = ConsoleColor.Green; } DeobfuscateCflow(methods); if (Program.veryVerbose) { Console.WriteLine(); } } } } }