public static AssemblyDefinition Translate(ModuleDefMD manifestModule) { using (var assemblyStream = new MemoryStream()) { try { if (manifestModule.IsILOnly) { var writerOptions = new ModuleWriterOptions(manifestModule); writerOptions.Logger = DummyLogger.NoThrowInstance; MetaDataOptions metaDataOptions = new MetaDataOptions(); metaDataOptions.Flags = MetaDataFlags.PreserveAll; manifestModule.Write(assemblyStream, writerOptions); } else { var writerOptions = new NativeModuleWriterOptions(manifestModule); writerOptions.Logger = DummyLogger.NoThrowInstance; MetaDataOptions metaDataOptions = new MetaDataOptions(); metaDataOptions.Flags = MetaDataFlags.PreserveAll; manifestModule.NativeWrite(assemblyStream, writerOptions); } } catch (Exception) { if (assemblyStream.Length == 0) { return(null); } } assemblyStream.Position = 0; AssemblyDefinition newAssembly = AssemblyDefinition.ReadAssembly(assemblyStream); return(newAssembly); } }
public void Save(string newFilename, MetadataFlags mdFlags, IModuleWriterListener writerListener) { if (module.IsILOnly) { var writerOptions = new ModuleWriterOptions(module); writerOptions.WriterEvent += (s, e) => writerListener?.OnWriterEvent(e.Writer, e.Event); writerOptions.MetadataOptions.Flags |= mdFlags; writerOptions.Logger = Logger.Instance; module.Write(newFilename, writerOptions); } else { var writerOptions = new NativeModuleWriterOptions(module, optimizeImageSize: true); writerOptions.WriterEvent += (s, e) => writerListener?.OnWriterEvent(e.Writer, e.Event); writerOptions.MetadataOptions.Flags |= mdFlags; writerOptions.Logger = Logger.Instance; writerOptions.KeepExtraPEData = true; writerOptions.KeepWin32Resources = true; module.NativeWrite(newFilename, writerOptions); } }
internal void Save() { try { string text = Path.GetDirectoryName(assemblyPath); if (!text.EndsWith("\\")) { text += "\\"; } string filename = text + Path.GetFileNameWithoutExtension(assemblyPath) + "_Unpacked" + Path.GetExtension(assemblyPath); ModuleWriterOptions options = new ModuleWriterOptions(moduleDef); options.Logger = DummyLogger.NoThrowInstance; moduleDef.Write(filename, options); } catch (Exception ex) { Console.WriteLine("[!] Exception :\n" + ex.Message); } }
static void Main(string[] args) { Console.ForegroundColor = ConsoleColor.Green; optionParser(args); Console.WriteLine("Yeah confuserex unpacker so what"); if (path == null || mode == null) { Console.WriteLine("Check args make sure path and either -d or -s is included (Dynamic or static)"); Console.ReadLine(); return; } module = ModuleDefMD.Load(path); if (mode.ToLower() == "static") { staticRoute(); } else if (mode.ToLower() == "dynamic") { asm = Assembly.LoadFrom(path); dynamicRoute(); } else { Console.Write("Yeah erm you might be a bit of an idiot follow the instructions"); Console.ReadLine(); return; } ModuleWriterOptions writerOptions = new ModuleWriterOptions(module); writerOptions.MetadataOptions.Flags |= MetadataFlags.PreserveAll; writerOptions.Logger = DummyLogger.NoThrowInstance; module.Write(path + "Cleaned.exe", writerOptions); Console.ReadLine(); }
private void button2_Click(object sender, EventArgs e) { if (textBox1.Text == null || textBox1.Text == "") { MessageBox.Show("Please Select File"); } else { path = textBox1.Text; ModuleDefMD LoadedFile = ModuleDefMD.Load(textBox1.Text); if (checkBox1.Checked) { amount = StringDecryptor.InvokeDecryption(LoadedFile); } else { amount = StringDecryptor.Run(LoadedFile); } Excess_Nop_Remover.NopRemover(LoadedFile); label1.Text = "Strings Decrypted : " + amount; string filename = DirectoryName + "\\" + Path.GetFileNameWithoutExtension(textBox1.Text) + "-Decrypted" + Path.GetExtension(textBox1.Text); var opts = new ModuleWriterOptions(LoadedFile); opts.Logger = DummyLogger.NoThrowInstance; var writerOptions = new NativeModuleWriterOptions(LoadedFile); writerOptions.MetaDataOptions.Flags |= MetaDataFlags.PreserveAll; writerOptions.Logger = DummyLogger.NoThrowInstance; if (LoadedFile.IsILOnly) { LoadedFile.Write(filename, opts); } else { LoadedFile.NativeWrite(filename, writerOptions); } } }
private void button1_Click(object sender, EventArgs e) { module = ModuleDefMD.Load(textBox1.Text); FindStringDecrypterMethods(module); if (Methoddecryption == null) { FindStringDecrypterMethodsWithflow(module); x = 1; } DecryptStringsInMethod(module, Methoddecryption); string text2 = Path.GetDirectoryName(textBox1.Text); if (!text2.EndsWith("\\")) { text2 += "\\"; } string path = text2 + Path.GetFileNameWithoutExtension(textBox1.Text) + "_patched" + Path.GetExtension(textBox1.Text); module.Write(path); label2.Text = "Successfully decrypted " + DeobedStringNumber + " strings !"; }
public override void Rebuild(string outputFolder) { string outputPath = System.IO.Path.Combine(outputFolder, RelativePath); Directory.CreateDirectory(System.IO.Path.GetDirectoryName(outputPath)); IList <Subtitle> subtitles = GetSubtitles(); Dictionary <string, string> dict = subtitles.Where(subtitle => subtitle.Text != subtitle.Translation).ToDictionary(subtitle => subtitle.Text, subtitle => subtitle.Translation); ModuleDefMD module = ModuleDefMD.Load(Path); foreach (TypeDef t in module.Types) { foreach (MethodDef m in t.Methods) { if (!m.HasBody) { continue; } foreach (Instruction instr in m.Body.Instructions) { if (instr.OpCode != OpCodes.Ldstr) { continue; } string str = (string)instr.Operand; if (dict.TryGetValue(str, out string translation)) { instr.Operand = translation; } } } } module.Write(outputPath); }
static void ExportLsaEntryPoint(string assemblyPath) { byte[] data = File.ReadAllBytes(assemblyPath); ModuleDefMD module = ModuleDefMD.Load(data); //Little trick here that uses dnlib to search for all functions within our generated //assembly that has the DllExport attribute. We then mark that function as a native export //and remove the attribute so that we don't have a dependency on this assembly foreach (var type in module.GetTypes()) { foreach (var method in type.Methods) { var toRemove = new List <CustomAttribute>(); foreach (var attrib in method.CustomAttributes) { if (attrib.TypeFullName == typeof(DllExportAttribute).FullName) { method.ExportInfo = new MethodExportInfo(); var retType = method.MethodSig.RetType; method.MethodSig.RetType = new CModOptSig(module.CorLibTypes.GetTypeRef("System.Runtime.CompilerServices", "CallConvStdCall"), retType); toRemove.Add(attrib); } } toRemove.ForEach(remove => method.CustomAttributes.Remove(remove)); } } var moduleOptions = new ModuleWriterOptions(module); moduleOptions.PEHeadersOptions.Machine = IntPtr.Size == 8 ? dnlib.PE.Machine.AMD64 : dnlib.PE.Machine.I386; moduleOptions.Cor20HeaderOptions.Flags &= ~(dnlib.DotNet.MD.ComImageFlags.ILOnly); if (IntPtr.Size == 4) { moduleOptions.Cor20HeaderOptions.Flags |= dnlib.DotNet.MD.ComImageFlags.Bit32Required; moduleOptions.Cor20HeaderOptions.Flags &= ~(dnlib.DotNet.MD.ComImageFlags.Bit32Preferred); } module.Write(assemblyPath, moduleOptions); }
private void button1_Click(object sender, EventArgs e) { try { mainasm = ModuleDefMD.Load(this.textBox1.Text); resasm = ModuleDefMD.Load(this.textBox2.Text); if (resasm.HasResources && mainasm.HasResources) { if (resasm.Resources.Count == mainasm.Resources.Count) { foreach (var goodres in resasm.Resources) { mainasm.Resources.Remove(mainasm.Resources.Find(goodres.Name)); mainasm.Resources.Add(goodres); totalreplace++; } } else { MessageBox.Show("Resource counts must be equal !"); } } ModuleWriterOptions moduleWriterOptions = new ModuleWriterOptions(mainasm); if (mainasm.IsILOnly) { moduleWriterOptions.MetaDataOptions.Flags |= (MetaDataFlags.PreserveTypeRefRids | MetaDataFlags.PreserveTypeDefRids | MetaDataFlags.PreserveFieldRids | MetaDataFlags.PreserveMethodRids | MetaDataFlags.PreserveParamRids | MetaDataFlags.PreserveMemberRefRids | MetaDataFlags.PreserveStandAloneSigRids | MetaDataFlags.PreserveEventRids | MetaDataFlags.PreservePropertyRids | MetaDataFlags.PreserveTypeSpecRids | MetaDataFlags.PreserveMethodSpecRids | MetaDataFlags.PreserveUSOffsets | MetaDataFlags.PreserveBlobOffsets | MetaDataFlags.PreserveExtraSignatureData | MetaDataFlags.KeepOldMaxStack); moduleWriterOptions.Logger = DummyLogger.NoThrowInstance; } mainasm.Write(this.textBox1.Text.Replace(".exe", "_fixed.exe"), moduleWriterOptions); } catch (Exception ex) { MessageBox.Show(ex.ToString()); } MessageBox.Show("Total " + totalreplace.ToString() + " resource replaced."); }
private void Button2_Click(object sender, EventArgs e) { //打开.NET程序集/模块 ModuleDefMD module = ModuleDefMD.Load(this.textBox1.Text); RidList typeDef = module.Metadata.GetTypeDefRidList(); for (int i = 0; i < module.Types.Count; i++) { var t = module.Types[i]; if (t.Name == "TestAction") { for (int j = 0; j < t.Methods.Count; j++) { if (t.Methods[j].Name == "Check") { var method = t.Methods[j]; Instruction[] opCodes = { Instruction.Create(OpCodes.Ldc_I4_1), Instruction.Create(OpCodes.Ret) }; for (int l = 0; l < opCodes.Length; l++) { method.Body.Instructions[l] = opCodes[l]; } } } } } //保存程序集 module.Write(@"C:\Users\tchivs\source\repos\ComponentOneCrack\TestLibrary\bin\Debug\TestLibraryCrack.dll", new ModuleWriterOptions(module) { MetadataOptions = { Flags = MetadataFlags.KeepOldMaxStack } }); }
static void Main(string[] args) { Console.WriteLine("Welcome to yano string decryptor by MindSystem"); Console.WriteLine("The aim of this tool is to show how to decrypt string using the stack \n"); try { module = ModuleDefMD.Load(args[0]); } catch (Exception ex) { Console.WriteLine("Impossible to load module, exception message : {0}", ex.Message); return; } System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch(); watch.Start(); DecryptString(FindDecryptionMethod()); CFLow(); watch.Stop(); Console.WriteLine("\nDone ! Elapsed time : " + watch.Elapsed.TotalSeconds); string SavingPath = module.Kind == ModuleKind.Dll ? args[0].Replace(".dll", "-Obfuscated.dll") : args[0].Replace(".exe", "-Obfuscated.exe"); if (module.IsILOnly) { var opts = new ModuleWriterOptions(module); opts.MetadataOptions.Flags = MetadataFlags.PreserveAll; opts.Logger = DummyLogger.NoThrowInstance; module.Write(SavingPath, opts); } else { var opts = new NativeModuleWriterOptions(module, false); opts.MetadataOptions.Flags = MetadataFlags.PreserveAll; opts.Logger = DummyLogger.NoThrowInstance; module.NativeWrite(SavingPath, opts); } Console.ReadLine(); }
public static byte[] GetCurrentModule(ModuleDefMD module) { MemoryStream memorystream = new MemoryStream(); if (module.IsILOnly) { ModuleWriterOptions writer = new ModuleWriterOptions(module); writer.MetaDataOptions.Flags = MetaDataFlags.PreserveAll; writer.MetaDataLogger = DummyLogger.NoThrowInstance; module.Write(memorystream, writer); } else { NativeModuleWriterOptions writer = new NativeModuleWriterOptions(module); writer.MetaDataOptions.Flags = MetaDataFlags.PreserveAll; writer.MetaDataLogger = DummyLogger.NoThrowInstance; module.NativeWrite(memorystream, writer); } byte[] ByteArray = new byte[memorystream.Length]; memorystream.Position = 0; memorystream.Read(ByteArray, 0, (int)memorystream.Length); return(ByteArray); }
private void button2_Click(object sender, EventArgs e) { ModuleDefMD module = ModuleDefMD.Load(textBox1.Text); IntControlFlow.Execute(module); AssemblyRenaming.Execute(module.Assembly); string text2 = Path.GetDirectoryName(textBox1.Text); if (!text2.EndsWith("\\")) { text2 += "\\"; } string path = text2 + Path.GetFileNameWithoutExtension(textBox1.Text) + "_WithIntControlFlow" + Path.GetExtension(textBox1.Text); var opts = new ModuleWriterOptions(module); opts.PEHeadersOptions.NumberOfRvaAndSizes = 13; opts.MetadataOptions.TablesHeapOptions.ExtraData = 0x1337; opts.Logger = DummyLogger.NoThrowInstance; module.Write(path, opts); }
public void Apply() { string assemblyCSharp = Path.Combine(subnauticaManagedPath, GAME_ASSEMBLY_NAME); string nitroxPatcherPath = Path.Combine(subnauticaManagedPath, NITROX_ASSEMBLY_NAME); string modifiedAssemblyCSharp = Path.Combine(subnauticaManagedPath, GAME_ASSEMBLY_MODIFIED_NAME); if (File.Exists(modifiedAssemblyCSharp)) { File.Delete(modifiedAssemblyCSharp); } using (ModuleDefMD module = ModuleDefMD.Load(assemblyCSharp)) 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(modifiedAssemblyCSharp); } // The assembly might be used by other code or some other program might work in it. Retry to be on the safe side. Exception error = RetryWait(() => File.Delete(assemblyCSharp), 100, 5); if (error != null) { throw error; } File.Move(modifiedAssemblyCSharp, assemblyCSharp); }
private void btnDeobf_Click(object sender, EventArgs e) { ModuleDefMD md = ModuleDefMD.Load(tbin.Text); if (!IsObfuscator(md)) { MessageBox.Show(null, "This Assembly is not protected with Orange Heap!", NAME, MessageBoxButtons.OK, MessageBoxIcon.Error); } else { foreach (var type in md.Types) { foreach (var method in type.Methods) { if (!method.HasBody) { continue; } CilBody body = method.Body; body.KeepOldMaxStack = true; for (int i = 0; i < body.Instructions.Count; i++) { if (body.Instructions[i].OpCode == OpCodes.Ldstr && body.Instructions[i + 1].OpCode == OpCodes.Call && body.Instructions[i + 1].Operand == target) { body.Instructions[i].Operand = decryptstring(body.Instructions[i].Operand.ToString()); body.Instructions[i + 1].Operand = null; body.Instructions[i + 1].OpCode = OpCodes.Nop; } } } } md.Write(tbout.Text); MessageBox.Show(null, "Saved Assembly to: " + tbout.Text, NAME, MessageBoxButtons.OK, MessageBoxIcon.Information); } }
public void Remove() { string gameInputPath = subnauticaBasePath + GAME_ASSEMBLY_NAME; string modifiedAssemblyPath = subnauticaBasePath + GAME_ASSEMBLY_MODIFIED_NAME; using (ModuleDefMD module = ModuleDefMD.Load(gameInputPath)) { 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); methodInstructions.RemoveAt(nitroxExecuteInstructionIndex); module.Write(modifiedAssemblyPath); } if (File.Exists(gameInputPath)) { File.Delete(gameInputPath); } File.Move(modifiedAssemblyPath, gameInputPath); }
public static void Main(string[] args) { string path = "../Release/CILExamining.exe"; ModuleDefMD m = ModuleDefMD.Load(path); AssemblyResolver ar = new AssemblyResolver(); ModuleContext mc = new ModuleContext(ar); foreach (AssemblyRef assemblyRef in m.GetAssemblyRefs()) { ar.ResolveThrow(assemblyRef, m); } ar.PostSearchPaths.Add(path); m.Context = mc; Obfuscations.Utilities.RenameUtility ru = new Obfuscations.Utilities.RenameUtility(); new Obfuscations.ReferenceProxyObfuscation(ru.Random).Execute(m); //new Obfuscations.RenameObfuscation(ru).Execute(m); //new Obfuscations.JunkObfuscation(ru).Execute(m); m.Write(path + ".o"); }
public static async Task <byte[]> Save(ModuleDefMD targetModule, bool writeToFile) { var targetLocation = targetModule.Location; using (var ms = new MemoryStream()) { targetModule.Write(ms); targetModule.Dispose(); ms.Seek(0, SeekOrigin.Begin); var data = ms.ToArray(); if (writeToFile) { using (var fs = new FileStream(targetLocation, FileMode.Create)) { await fs.WriteAsync(data, 0, data.Length); fs.Flush(); } } return(data); } }
private void button2_Click(object sender, EventArgs e) { module = ModuleDefMD.Load(textBox1.Text); FindStringDecrypterMethods(module); DeobedStringNumber = 0; DecryptStringsInMethod(module, Methoddecryption); if (checkBox1.Checked) { RemoveDemo(module); } string text2 = Path.GetDirectoryName(textBox1.Text); if (!text2.EndsWith("\\")) { text2 += "\\"; } string path = text2 + Path.GetFileNameWithoutExtension(textBox1.Text) + "_patched" + Path.GetExtension(textBox1.Text); var opts = new ModuleWriterOptions(module); opts.Logger = DummyLogger.NoThrowInstance; module.Write(path, opts); label2.Text = "Successfully decrypted " + DeobedStringNumber + " strings !"; }
static void Main(string[] args) { Console.Title = "Anti Decompiler Cleaner - Prab"; ModuleDefMD module = null; try { module = ModuleDefMD.Load(args[0]); Console.WriteLine("[?] File Loaded: {0}", module); } catch (Exception ex) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("[*] Error ! {0}", ex); } CrashDnSpy(module); CrashDnSpy2(module); CrashDnSpy3(module); var Path = module.Kind == ModuleKind.Dll ? args[0].Replace(".dll", "-Cleaned.dll") : args[0].Replace(".exe", "-Cleaned.exe"); if (module.IsILOnly) { var opts = new ModuleWriterOptions(module); opts.MetadataOptions.Flags = MetadataFlags.PreserveAll; opts.Logger = DummyLogger.NoThrowInstance; module.Write(Path, opts); } else { var opts = new NativeModuleWriterOptions(module, true); opts.MetadataOptions.Flags = MetadataFlags.PreserveAll; opts.Logger = DummyLogger.NoThrowInstance; module.NativeWrite(Path, opts); } Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("[+] Finished !\n[+] File Saved at : {0}", Path); Console.ReadLine(); }
//private bool InjectConfig(Actions action, XDocument doc = null, bool write = true) //{ // var originalMachineConfigPath = $"{machineConfigPath}.original_"; // var gameConfigPath = GameInfo.filepathInGame; // var success = false; // switch (action) // { // case Actions.Install: // try // { // if (!Directory.Exists(managerPath)) // Directory.CreateDirectory(managerPath); // Utils.MakeBackup(machineConfigPath); // Utils.MakeBackup(libraryPaths); // if (!IsDirty(doc)) // { // File.Copy(machineConfigPath, originalMachineConfigPath, true); // } // MakeDirty(doc); // if (!InjectConfig(Actions.Remove, doc, false)) // { // Log.Print("Installation failed. Can't uninstall the previous version."); // goto EXIT; // } // Log.Print($"Applying patch to '{Path.GetFileName(machineConfigPath)}'..."); // foreach (var mapping in doc.Descendants("cryptoNameMapping")) // { // foreach(var cryptoClasses in mapping.Elements("cryptoClasses")) // { // if (!cryptoClasses.Elements("cryptoClass").Any(x => x.FirstAttribute.Name.LocalName == "ummRngWrapper")) // { // cryptoClasses.Add(new XElement("cryptoClass", new XAttribute("ummRngWrapper", "UnityModManagerNet.RngWrapper, UnityModManager, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"))); // } // } // if (!mapping.Elements("nameEntry").Any(x => x.LastAttribute.Value == "ummRngWrapper")) // { // //mapping.Add(new XElement("nameEntry", new XAttribute("name", "RandomNumberGenerator"), new XAttribute("class", "ummRngWrapper"))); // mapping.Add(new XElement("nameEntry", new XAttribute("name", "System.Security.Cryptography.RandomNumberGenerator"), new XAttribute("class", "ummRngWrapper"))); // } // break; // } // doc.Save(machineConfigPath); // DoactionLibraries(Actions.Install); // DoactionGameConfig(Actions.Install); // Log.Print("Installation was successful."); // success = true; // } // catch (Exception e) // { // Log.Print(e.ToString()); // Utils.RestoreBackup(machineConfigPath); // Utils.RestoreBackup(libraryPaths); // Utils.RestoreBackup(gameConfigPath); // Log.Print("Installation failed."); // } // break; // case Actions.Remove: // try // { // Utils.MakeBackup(gameConfigPath); // if (write) // { // Utils.MakeBackup(machineConfigPath); // Utils.MakeBackup(libraryPaths); // } // Log.Print("Removing patch..."); // MakeDirty(doc); // foreach (var mapping in doc.Descendants("cryptoNameMapping")) // { // foreach (var cryptoClasses in mapping.Elements("cryptoClasses")) // { // foreach (var cryptoClass in cryptoClasses.Elements("cryptoClass")) // { // if (cryptoClass.FirstAttribute.Name.LocalName == "ummRngWrapper") // { // cryptoClass.Remove(); // } // } // } // foreach (var nameEntry in mapping.Elements("nameEntry")) // { // if (nameEntry.LastAttribute.Value == "ummRngWrapper") // { // nameEntry.Remove(); // } // } // break; // } // if (write) // { // doc.Save(machineConfigPath); // DoactionLibraries(Actions.Remove); // DoactionGameConfig(Actions.Remove); // Log.Print("Removal was successful."); // } // success = true; // } // catch (Exception e) // { // Log.Print(e.ToString()); // if (write) // { // Utils.RestoreBackup(machineConfigPath); // Utils.RestoreBackup(libraryPaths); // Utils.RestoreBackup(gameConfigPath); // Log.Print("Removal failed."); // } // } // break; // } // EXIT: // if (write) // { // try // { // Utils.DeleteBackup(machineConfigPath); // Utils.DeleteBackup(libraryPaths); // Utils.DeleteBackup(gameConfigPath); // } // catch (Exception) // { // } // } // return success; //} private bool InjectAssembly(Actions action, ModuleDefMD assemblyDef, bool write = true) { var managerType = typeof(UnityModManager); var starterType = typeof(Injection.UnityModManagerStarter); var gameConfigPath = GameInfo.filepathInGame; var assemblyPath = Path.Combine(managedPath, assemblyDef.Name); var originalAssemblyPath = $"{assemblyPath}.original_"; var success = false; switch (action) { case Actions.Install: { try { Log.Print("======================================="); if (!Directory.Exists(managerPath)) { Directory.CreateDirectory(managerPath); } Utils.MakeBackup(assemblyPath); Utils.MakeBackup(libraryPaths); if (!IsDirty(assemblyDef)) { File.Copy(assemblyPath, originalAssemblyPath, true); MakeDirty(assemblyDef); } if (!InjectAssembly(Actions.Remove, injectedAssemblyDef, assemblyDef != injectedAssemblyDef)) { Log.Print("Installation failed. Can't uninstall the previous version."); goto EXIT; } Log.Print($"Applying patch to '{Path.GetFileName(assemblyPath)}'..."); if (!Utils.TryGetEntryPoint(assemblyDef, entryPoint, out var methodDef, out var insertionPlace, true)) { goto EXIT; } var starterDef = ModuleDefMD.Load(starterType.Module); var starter = starterDef.Types.First(x => x.Name == starterType.Name); starterDef.Types.Remove(starter); assemblyDef.Types.Add(starter); var instr = OpCodes.Call.ToInstruction(starter.Methods.First(x => x.Name == nameof(Injection.UnityModManagerStarter.Start))); if (insertionPlace == "before") { methodDef.Body.Instructions.Insert(0, instr); } else { methodDef.Body.Instructions.Insert(methodDef.Body.Instructions.Count - 1, instr); } assemblyDef.Write(assemblyPath); DoactionLibraries(Actions.Install); DoactionGameConfig(Actions.Install); Log.Print("Installation was successful."); success = true; } catch (Exception e) { Log.Print(e.ToString()); Utils.RestoreBackup(assemblyPath); Utils.RestoreBackup(libraryPaths); Utils.RestoreBackup(gameConfigPath); Log.Print("Installation failed."); } } break; case Actions.Remove: { try { if (write) { Log.Print("======================================="); } Utils.MakeBackup(gameConfigPath); var v0_12_Installed = assemblyDef.Types.FirstOrDefault(x => x.Name == managerType.Name); var newWayInstalled = assemblyDef.Types.FirstOrDefault(x => x.Name == starterType.Name); if (v0_12_Installed != null || newWayInstalled != null) { if (write) { Utils.MakeBackup(assemblyPath); Utils.MakeBackup(libraryPaths); } Log.Print("Removing patch..."); Instruction instr = null; if (newWayInstalled != null) { instr = OpCodes.Call.ToInstruction(newWayInstalled.Methods.First(x => x.Name == nameof(Injection.UnityModManagerStarter.Start))); } else if (v0_12_Installed != null) { instr = OpCodes.Call.ToInstruction(v0_12_Installed.Methods.First(x => x.Name == nameof(UnityModManager.Start))); } if (!string.IsNullOrEmpty(injectedEntryPoint)) { if (!Utils.TryGetEntryPoint(assemblyDef, injectedEntryPoint, out var methodDef, out _, true)) { goto EXIT; } for (int i = 0; i < methodDef.Body.Instructions.Count; i++) { if (methodDef.Body.Instructions[i].OpCode == instr.OpCode && methodDef.Body.Instructions[i].Operand == instr.Operand) { methodDef.Body.Instructions.RemoveAt(i); break; } } } if (newWayInstalled != null) { assemblyDef.Types.Remove(newWayInstalled); } else if (v0_12_Installed != null) { assemblyDef.Types.Remove(v0_12_Installed); } if (!IsDirty(assemblyDef)) { MakeDirty(assemblyDef); } if (write) { assemblyDef.Write(assemblyPath); DoactionLibraries(Actions.Remove); DoactionGameConfig(Actions.Remove); Log.Print("Removal was successful."); } } success = true; } catch (Exception e) { Log.Print(e.ToString()); if (write) { Utils.RestoreBackup(assemblyPath); Utils.RestoreBackup(libraryPaths); Utils.RestoreBackup(gameConfigPath); Log.Print("Removal failed."); } } } break; } EXIT: if (write) { try { Utils.DeleteBackup(assemblyPath); Utils.DeleteBackup(libraryPaths); Utils.DeleteBackup(gameConfigPath); } catch (Exception) { } } return(success); }
private async void BtnBuild_Click(object sender, EventArgs e) { if (!chkPastebin.Checked && listBoxIP.Items.Count == 0 || listBoxPort.Items.Count == 0) { return; } if (checkBox1.Checked) { if (string.IsNullOrWhiteSpace(textFilename.Text) || string.IsNullOrWhiteSpace(comboBoxFolder.Text)) { return; } if (!textFilename.Text.EndsWith("exe")) { textFilename.Text += ".exe"; } } if (string.IsNullOrWhiteSpace(txtMutex.Text)) { txtMutex.Text = getRandomCharacters(); } if (chkPastebin.Checked && string.IsNullOrWhiteSpace(txtPastebin.Text)) { return; } ModuleDefMD asmDef = null; try { using (asmDef = ModuleDefMD.Load(@"Stub/Stub.exe")) using (SaveFileDialog saveFileDialog1 = new SaveFileDialog()) { saveFileDialog1.Filter = ".exe (*.exe)|*.exe"; saveFileDialog1.InitialDirectory = Application.StartupPath; saveFileDialog1.OverwritePrompt = false; saveFileDialog1.FileName = "Client"; if (saveFileDialog1.ShowDialog() == DialogResult.OK) { btnBuild.Enabled = false; WriteSettings(asmDef); if (chkObfu.Checked) { //EncryptString.DoEncrypt(asmDef); await Task.Run(() => { Renaming.DoRenaming(asmDef); }); } asmDef.Write(saveFileDialog1.FileName); asmDef.Dispose(); if (btnAssembly.Checked) { WriteAssembly(saveFileDialog1.FileName); } if (chkIcon.Checked && !string.IsNullOrEmpty(txtIcon.Text)) { IconInjector.InjectIcon(saveFileDialog1.FileName, txtIcon.Text); } MessageBox.Show("Done!", "AsyncRAT | Builder", MessageBoxButtons.OK, MessageBoxIcon.Information); SaveSettings(); this.Close(); } } } catch (Exception ex) { MessageBox.Show(ex.Message, "AsyncRAT | Builder", MessageBoxButtons.OK, MessageBoxIcon.Error); asmDef?.Dispose(); btnBuild.Enabled = true; } }
private bool Inject(Actions action, ModuleDefMD assembly = null, bool save = true) { var assemblyPath = Path.Combine(currentManagedPath, selectedGame.AssemblyName); var backupAssemblyPath = $"{assemblyPath}.backup"; if (File.Exists(assemblyPath)) { if (assembly == null) { try { assembly = ModuleDefMD.Load(File.ReadAllBytes(assemblyPath)); } catch (Exception e) { Log.Print(e.Message); return(false); } } string className = null; string methodName = null; string placeType = null; var pos = selectedGame.PatchTarget.LastIndexOf('.'); if (pos != -1) { className = selectedGame.PatchTarget.Substring(0, pos); var pos2 = selectedGame.PatchTarget.LastIndexOf(':'); if (pos2 != -1) { methodName = selectedGame.PatchTarget.Substring(pos + 1, pos2 - pos - 1); placeType = selectedGame.PatchTarget.Substring(pos2 + 1).ToLower(); if (placeType != "after" && placeType != "before") { Log.Print($"Parameter '{placeType}' in '{selectedGame.PatchTarget}' is unknown."); } } else { methodName = selectedGame.PatchTarget.Substring(pos + 1); } if (methodName == "ctor") { methodName = ".ctor"; } } else { Log.Print($"Function name error '{selectedGame.PatchTarget}'."); return(false); } var targetClass = assembly.Types.FirstOrDefault(x => x.FullName == className); if (targetClass == null) { Log.Print($"Class '{className}' not found."); return(false); } var targetMethod = targetClass.Methods.FirstOrDefault(x => x.Name == methodName); if (targetMethod == null) { Log.Print($"Method '{methodName}' not found."); return(false); } var modManagerType = typeof(UnityModManager); switch (action) { case Actions.Install: try { Log.Print($"Backup for '{selectedGame.AssemblyName}'."); File.Copy(assemblyPath, backupAssemblyPath, true); CopyLibraries(); var modsPath = Path.Combine(currentGamePath, selectedGame.ModsDirectory); if (!Directory.Exists(modsPath)) { Directory.CreateDirectory(modsPath); } var typeInjectorInstalled = assembly.Types.FirstOrDefault(x => x.Name == modManagerType.Name); if (typeInjectorInstalled != null) { if (!Inject(Actions.Remove, assembly, false)) { Log.Print("Installation failed. Can't uninstall the previous version."); return(false); } } Log.Print("Applying patch..."); var modManagerDef = ModuleDefMD.Load(modManagerType.Module); var modManager = modManagerDef.Types.First(x => x.Name == modManagerType.Name); var modManagerModsDir = modManager.Fields.First(x => x.Name == nameof(UnityModManager.modsDirname)); modManagerModsDir.Constant.Value = selectedGame.ModsDirectory; var modManagerModInfo = modManager.Fields.First(x => x.Name == nameof(UnityModManager.infoFilename)); modManagerModInfo.Constant.Value = selectedGame.ModInfo; modManagerDef.Types.Remove(modManager); assembly.Types.Add(modManager); var instr = OpCodes.Call.ToInstruction(modManager.Methods.First(x => x.Name == nameof(UnityModManager.Start))); if (string.IsNullOrEmpty(placeType) || placeType == "after") { targetMethod.Body.Instructions.Insert(targetMethod.Body.Instructions.Count - 1, instr); } else if (placeType == "before") { targetMethod.Body.Instructions.Insert(0, instr); } if (save) { assembly.Write(assemblyPath); Log.Print("Installation was successful."); } installedVersion.Text = currentVersion.Text; btnInstall.Enabled = false; btnRemove.Enabled = true; return(true); } catch (Exception e) { Log.Print(e.Message); if (!File.Exists(assemblyPath)) { RestoreBackup(); } } break; case Actions.Remove: try { var modManagerInjected = assembly.Types.FirstOrDefault(x => x.Name == modManagerType.Name); if (modManagerInjected != null) { Log.Print("Removing patch..."); var instr = OpCodes.Call.ToInstruction(modManagerInjected.Methods.First(x => x.Name == nameof(UnityModManager.Start))); for (int i = 0; i < targetMethod.Body.Instructions.Count; i++) { if (targetMethod.Body.Instructions[i].OpCode == instr.OpCode && targetMethod.Body.Instructions[i].Operand == instr.Operand) { targetMethod.Body.Instructions.RemoveAt(i); break; } } assembly.Types.Remove(modManagerInjected); if (save) { assembly.Write(assemblyPath); Log.Print("Removal was successful."); } installedVersion.Text = "-"; btnInstall.Enabled = true; btnRemove.Enabled = false; } return(true); } catch (Exception e) { Log.Print(e.Message); if (!File.Exists(assemblyPath)) { RestoreBackup(); } } break; } } else { Log.Print($"'{assemblyPath}' not found."); return(false); } return(false); }
private void btnShellcode_Click(object sender, EventArgs e) { if (!chkPaste_bin.Checked && listBoxIP.Items.Count == 0 || listBoxPort.Items.Count == 0) { return; } if (checkBox1.Checked) { if (string.IsNullOrWhiteSpace(textFilename.Text) || string.IsNullOrWhiteSpace(comboBoxFolder.Text)) { return; } if (!textFilename.Text.EndsWith("exe")) { textFilename.Text += ".exe"; } } if (string.IsNullOrWhiteSpace(txtMutex.Text)) { txtMutex.Text = getRandomCharacters(); } if (chkPaste_bin.Checked && string.IsNullOrWhiteSpace(txtPaste_bin.Text)) { return; } ModuleDefMD asmDef = null; try { using (asmDef = ModuleDefMD.Load(@"Stub/Client.exe")) { string Temppath = Path.Combine(Application.StartupPath, @"Stub\tempClient.exe"); if (File.Exists(Temppath)) { File.Delete(Temppath); } File.Copy(Path.Combine(Application.StartupPath, @"Stub\Client.exe"), Temppath); btnShellcode.Enabled = false; btnBuild.Enabled = false; WriteSettings(asmDef, Temppath); asmDef.Write(Temppath); asmDef.Dispose(); if (btnAssembly.Checked) { WriteAssembly(Temppath); } if (chkIcon.Checked && !string.IsNullOrEmpty(txtIcon.Text)) { IconInjector.InjectIcon(Temppath, txtIcon.Text); } string savepath = ""; using (SaveFileDialog saveFileDialog1 = new SaveFileDialog()) { saveFileDialog1.Filter = ".bin (*.bin)|*.bin"; saveFileDialog1.InitialDirectory = Application.StartupPath; saveFileDialog1.OverwritePrompt = false; saveFileDialog1.FileName = "Client"; if (saveFileDialog1.ShowDialog() == DialogResult.OK) { savepath = saveFileDialog1.FileName; } } string Donutpath = Path.Combine(Application.StartupPath, @"Plugins\donut.exe"); if (!File.Exists(Donutpath)) { File.WriteAllBytes(Donutpath, Properties.Resources.donut); } Process Process = new Process(); Process.StartInfo.FileName = Donutpath; Process.StartInfo.CreateNoWindow = true; Process.StartInfo.Arguments = "-f " + Temppath + " -o " + savepath; Process.Start(); Process.WaitForExit(); Process.Close(); if (File.Exists(savepath)) { File.WriteAllText(savepath + "loader.cs", Properties.Resources.ShellcodeLoader.Replace("%qwqdanchun%", Convert.ToBase64String(File.ReadAllBytes(savepath)))); File.WriteAllText(savepath + ".b64", Convert.ToBase64String(File.ReadAllBytes(savepath))); } File.Delete(Temppath); File.Delete(Donutpath); MessageBox.Show("Done!", "Builder", MessageBoxButtons.OK, MessageBoxIcon.Information); SaveSettings(); this.Close(); } } catch (Exception ex) { MessageBox.Show(ex.Message, "Builder", MessageBoxButtons.OK, MessageBoxIcon.Error); asmDef?.Dispose(); btnBuild.Enabled = true; } }
static void Main(string[] args) { Console.Title = "Krawk Unpacker v2.0"; Console.ForegroundColor = ConsoleColor.Blue; Console.WriteLine(@" ============================================================================== _ __ _ _ _ _ | |/ / | | | | | | | | | ' / _ __ __ ___ _| | __ | | | |_ __ _ __ __ _ ___| | _____ _ __ | < | '__/ _` \ \ /\ / / |/ / | | | | '_ \| '_ \ / _` |/ __| |/ / _ \ '__| | . \| | | (_| |\ V V /| < | |__| | | | | |_) | (_| | (__| < __/ | |_|\_\_| \__,_| \_/\_/ |_|\_\ \____/|_| |_| .__/ \__,_|\___|_|\_\___|_| | | |_| {Release v2.0} Contact Skype: live:krawkreverser Discord: CrIsT#5619 Program Info Language: C# Framework: 4.5.2 Created Date: 10/07/2018 Bugs Fixed: 5/01/2019 Created By Krawk { Obs: Not Supported x86 Mixed Mode } ============================================================================== "); string diretorio = args[0]; try { Program.module = ModuleDefMD.Load(diretorio); Program.asm = Assembly.LoadFrom(diretorio); Program.Asmpath = diretorio; } catch (Exception) { Console.WriteLine("Not .NET Assembly..."); } string text = Path.GetDirectoryName(diretorio); bool flag = !text.EndsWith("\\"); if (flag) { text += "\\"; } Console.ForegroundColor = ConsoleColor.White; try { antitamper(); } catch { Console.WriteLine("[!] Anti-Tamper Falhou em remover"); } try { Staticpacker(); } catch { Console.WriteLine("[!] Packer Falhou em remover"); } try { packer(); } catch { Console.WriteLine("[!] Packer Falhou em remover"); } try { Console.ForegroundColor = ConsoleColor.White; Console.WriteLine("[!] Removendo AntiDebugger"); antidebugger.Run(module); Console.WriteLine("[!] Call Do AntiDebbuger Removida do Module"); } catch (Exception) { Console.WriteLine("[!] Erro ao Remover o AntiDebugger"); } try { Console.WriteLine("[!] Removendo AntiDumper"); antidumper.Run(module); Console.WriteLine("[!] Call Do AntiDumper Removida do Module"); } catch (Exception) { Console.WriteLine("[!] Erro ao Remover o AntiDumper"); } try { Console.WriteLine("[!] Limpando Cases De Control-Flow"); Protections.ControlFlowRun.cleaner(module); Console.WriteLine("[!] Sucesso ao Limpar Cases De Control-Flow"); } catch (Exception) { Console.WriteLine("[!] Erro ao Limpar Cases De Control-Flow"); } try { Console.WriteLine("[!] Fixando Proxy-Calls"); int amountProxy = Protections.ReferenceProxy.ProxyFixer(module); Console.WriteLine("[!] Proxy Calls Fixadas: " + amountProxy); } catch (Exception) { Console.WriteLine("[!] Erro ao Fixar Proxy-Calls"); } try { Console.WriteLine("[!] Resolvendo Equações Matemáticas"); MathsEquations.MathsFixer(module); Console.WriteLine("[!] Equações Matemáticas Resolvidas: " + MathsAmount); } catch (Exception) { Console.WriteLine("[!] Erro ao Resolver Equações Matemáticas"); } try { Console.WriteLine("[!] Resolvendo SizeOf's"); MathsEquations.SizeofRemove(module); Console.WriteLine("[!] SizeOf's Resolvidas: " + MathsAmount); } catch (Exception) { Console.WriteLine("[!] Erro ao Resolver SizeOf's"); } try { Console.WriteLine("[!] Resolvendo Invokes"); MathsEquations.SizeofRemove(module); Console.WriteLine("[!] Invokes Resolvidos Com Sucesso !"); } catch (Exception) { Console.WriteLine("[!] Erro em Remover Os Invokes !"); } try { Console.WriteLine("[!] Removendo Strings Staticas"); int strings = Protections.StaticStrings.Run(module); Console.WriteLine("[!] Strings Removidas: " + strings); } catch (Exception) { Console.WriteLine("[!] Erro ao Remover Strings Staticas"); } try { Console.WriteLine("[!] Removendo Strings Dynamicas"); int strings2 = Protections.Constants.constants(); Console.WriteLine("[!] Strings Removidas: " + strings2); } catch (Exception) { Console.WriteLine("[!] Erro ao Remover Strings Staticas"); } try { Console.WriteLine("[!] Decodificando Resources..."); ResourcesDeobfuscator.Deobfuscate(module); } catch (Exception) { Console.WriteLine("[!] Erro ao Decodificar Resources"); } try { Console.ForegroundColor = ConsoleColor.White; Console.WriteLine("[!] Removendo Attributes"); Console.WriteLine("[!] Attributes Removidas: " + AttributeRemover.startt(module, asm)); } catch { } string filename = string.Format("{0}{1}_Unpacked{2}", text, Path.GetFileNameWithoutExtension(diretorio), Path.GetExtension(diretorio)); ModuleWriterOptions writerOptions = new ModuleWriterOptions(module); writerOptions.MetaDataOptions.Flags |= MetaDataFlags.PreserveAll; writerOptions.Logger = DummyLogger.NoThrowInstance; NativeModuleWriterOptions NativewriterOptions = new NativeModuleWriterOptions(module); NativewriterOptions.MetaDataOptions.Flags |= MetaDataFlags.PreserveAll; NativewriterOptions.Logger = DummyLogger.NoThrowInstance; if (module.IsILOnly) { module.Write(filename, writerOptions); } else { module.NativeWrite(filename, NativewriterOptions); } Console.WriteLine(""); Console.WriteLine("Salvo Com Sucesso !"); Console.ReadLine(); }
private void prepareReplace() { MetadataFlags AllFlags = MetadataFlags.PreserveAll | MetadataFlags.KeepOldMaxStack | MetadataFlags.AlwaysCreateGuidHeap | MetadataFlags.RoslynSortInterfaceImpl; try { bool isBlockGood = checkBlocks(); if (!isBlockGood) { return; } if (!module.IsILOnly) { writeStatus("Info: The Assembly maybe contains unmanaged code"); Thread.Sleep(2000); } writeStatus("Processing: " + moduleName); ReplaceInstructions(); string newName = string.Format("{0}_ILR{1}", Path.GetFileNameWithoutExtension(moduleName), Path.GetExtension(moduleName)); if (ReplacedBlocks > 0) { if (module.IsILOnly) { var ManagedOptions = new ModuleWriterOptions(module); if (PreserveAllFlags) { ManagedOptions.MetadataOptions.Flags = AllFlags; } module.Write(Path.GetDirectoryName(moduleName) + "\\" + newName, ManagedOptions); } else { var UnmanagedOptions = new NativeModuleWriterOptions(module, true); if (PreserveAllFlags) { UnmanagedOptions.MetadataOptions.Flags = AllFlags; } module.NativeWrite(newName, UnmanagedOptions); } if (ShowLogs) { writeStatus(string.Format( "Done: Saved as {0} || Replaced {1} Blocks Instructions in {2} Methods", newName, ReplacedBlocks, EditedMethodsCount)); showFormLog(logInfo); } } else { writeStatus("Info: No Block Instructions Replaced!"); } //MessageBox.Show("File Saved as:\r\n" + newName, "Replaces Done", // MessageBoxButtons.OK, MessageBoxIcon.Information); if (module != null) { module.Dispose(); } enableControl(true); isRunning = false; } catch (Exception ex) { if (module != null) { module.Dispose(); } isRunning = false; if (ex.Message.Contains("Error calculating max stack")) { writeStatus("Error calculating max stack value..., try Check \"Preserve All Metadata\""); } else { if (ex.Message.Length > 100) { showFormLog(ex.Message); } else { writeStatus("Error: " + ex.Message.Trim()); } } enableControl(true); } }
private static void Main(string[] args) { try { string path; if (args.Length != 1) { Console.WriteLine("Provide the location of Assembly-CSharp.dll:"); path = Console.ReadLine(); } else { path = args[0]; } ModuleDefMD module = ModuleDefMD.Load(path); if (module == null) { Console.WriteLine($"File {path} not found!"); return; } Console.WriteLine($"Loaded {module.Name}"); Console.WriteLine("Resolving References..."); module.Context = ModuleDef.CreateModuleContext(); ((AssemblyResolver)module.Context.AssemblyResolver).AddToCache(module); Console.WriteLine("Injecting the Bootstrap Class."); ModuleDefMD bootstrap = ModuleDefMD.Load(Path.Combine(Directory.GetCurrentDirectory(), "Exiled.Bootstrap.dll")); Console.WriteLine("Loaded " + bootstrap.Name); TypeDef modClass = bootstrap.Types[0]; foreach (var type in bootstrap.Types) { if (type.Name == "Bootstrap") { modClass = type; Console.WriteLine($"[Injection] Hooked to: \"{type.Namespace}.{type.Name}\""); } } var modRefType = modClass; bootstrap.Types.Remove(modClass); modRefType.DeclaringType = null; module.Types.Add(modRefType); MethodDef call = FindMethod(modRefType, "Load"); if (call == null) { Console.WriteLine($"Failed to get the \"{call.Name}\" method! Maybe you don't have permission?"); return; } Console.WriteLine("Injected!"); Console.WriteLine("Injection completed!"); Console.WriteLine("Patching code..."); TypeDef typeDef = FindType(module.Assembly, "ServerConsole"); MethodDef start = FindMethod(typeDef, "Start"); if (start == null) { start = new MethodDefUser("Start", MethodSig.CreateInstance(module.CorLibTypes.Void), MethodImplAttributes.IL | MethodImplAttributes.Managed, MethodAttributes.Private | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName); typeDef.Methods.Add(start); } start.Body.Instructions.Insert(0, OpCodes.Call.ToInstruction(call)); module.Write(Path.Combine(Path.GetDirectoryName(Path.GetFullPath(path)), "Assembly-CSharp-Exiled.dll")); Console.WriteLine("Patching completed successfully!"); } catch (Exception exception) { Console.WriteLine($"An error has occurred while patching: {exception}"); } Console.Read(); }
public static void Publicize(string input, string output = null) { output ??= DefaultOutputDir + Path.DirectorySeparatorChar; if (string.IsNullOrEmpty(Path.GetFileName(output))) { output = Path.Combine(output, Path.GetFileNameWithoutExtension(input) + Suffix + Path.GetExtension(input)); } if (!File.Exists(input)) { Console.WriteLine(); Console.WriteLine("ERROR! File doesn't exist or you don't have sufficient permissions."); Environment.Exit(30); } ModuleDefMD module = null; try { module = ModuleDefMD.Load(input, ModuleDef.CreateModuleContext()); } catch (Exception e) { Console.WriteLine(); Console.WriteLine("ERROR! Cannot read the assembly. Please check your permissions."); Console.WriteLine(e); Environment.Exit(40); } var runtimeVisibilityAttribute = new TypeDefUser("RuntimeVisibilityAttribute", module.Import(typeof(Attribute))) { Attributes = TypeAttributes.Class & TypeAttributes.Public }; module.Types.Add(runtimeVisibilityAttribute); runtimeVisibilityAttribute.Methods.Add(new MethodDefUser( ".ctor", MethodSig.CreateInstance(module.CorLibTypes.Void, module.CorLibTypes.String), MethodImplAttributes.Managed & MethodImplAttributes.IL, MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName) { ParamDefs = { new ParamDefUser("visibility") } } ); var allTypes = module.GetTypes().ToList(); var types = 0; var methods = 0; var fields = 0; foreach (var type in allTypes) { foreach (var method in type.Methods) { if (method.IsPublic) { continue; } methods++; method.CustomAttributes.Add( new CustomAttribute(runtimeVisibilityAttribute.FindConstructors().Single(), new[] { new CAArgument(module.CorLibTypes.String, method.Access.ToString()) }) ); method.Access = MethodAttributes.Public; } foreach (var field in type.Fields) { if (field.IsPublic) { continue; } fields++; field.CustomAttributes.Add( new CustomAttribute(runtimeVisibilityAttribute.FindConstructors().Single(), new[] { new CAArgument(module.CorLibTypes.String, field.Access.ToString()) }) ); field.Access = FieldAttributes.Public; } if (type.IsNested ? type.IsNestedPublic : type.IsPublic) { continue; } types++; type.CustomAttributes.Add( new CustomAttribute(runtimeVisibilityAttribute.FindConstructors().Single(), new[] { new CAArgument(module.CorLibTypes.String, type.Visibility.ToString()) }) ); type.Visibility = type.IsNested ? TypeAttributes.NestedPublic : TypeAttributes.Public; } const string reportString = "Changed {0} {1} to public."; Console.WriteLine(reportString, types, "types"); Console.WriteLine(reportString, methods, "methods (including getters and setters)"); Console.WriteLine(reportString, fields, "fields"); Console.WriteLine(); Console.WriteLine("Saving a copy of the modified assembly ..."); try { var directory = Path.GetDirectoryName(output); if (!string.IsNullOrEmpty(directory)) { Directory.CreateDirectory(directory); } module.Write(output); } catch (Exception e) { Console.WriteLine(); Console.WriteLine("ERROR! Cannot create/overwrite the new assembly. "); Console.WriteLine("Please check the path and its permissions " + "and in case of overwriting an existing file ensure that it isn't currently used."); Console.WriteLine(e); Environment.Exit(50); } Console.WriteLine("Completed."); }
public void Save(string name) { module.Write(name); }
internal async Task <bool> ConfuseAssembly(string targetPath, ModuleDefMD targetModule) { if (string.IsNullOrWhiteSpace(targetPath)) { throw new ArgumentNullException(nameof(targetPath)); } if (targetModule == null) { throw new ArgumentNullException(nameof(targetModule)); } var targetFile = Path.GetFileName(targetPath); var targetDirectory = Path.GetDirectoryName(targetPath); var project = new ConfuserProject { BaseDirectory = targetDirectory, OutputDirectory = targetDirectory }; // Confuser plugins are merged into the main assembly at build time. Instruct the project to load them from the running executable. project.PluginPaths.Add(Assembly.GetExecutingAssembly().Location); byte[] rawData; using (var ms = new MemoryStream()) { targetModule.Write(ms); targetModule.Dispose(); ms.Seek(0, SeekOrigin.Begin); rawData = ms.ToArray(); } if (rawData == null || rawData.Count() == 0) { return(false); } ProjectModule projectModule = new ProjectModule { Path = targetFile, RawData = rawData }; projectModule.Rules.Add(new Rule { new SettingItem <Protection>("watermark", SettingItemAction.Remove), new SettingItem <Protection>("anti debug"), new SettingItem <Protection>("anti ildasm"), new SettingItem <Protection>("ctrl flow"), new SettingItem <Protection>("ref proxy"), new SettingItem <Protection>("harden"), }); project.Add(projectModule); var parameters = new ConfuserParameters { Project = project, Logger = this }; await ConfuserEngine.Run(parameters); return(_successfullyProtected); }