/// <summary>
		/// Constructor
		/// </summary>
		/// <param name="module">Module</param>
		/// <param name="listener">Module writer listener</param>
		public NativeModuleWriterOptions(ModuleDefMD module, IModuleWriterListener listener)
			: base(module, listener) {

			// C++ .NET mixed mode assemblies sometimes/often call Module.ResolveMethod(),
			// so method metadata tokens must be preserved.
			MetaDataOptions.Flags |= MetaDataFlags.PreserveAllMethodRids;
		}
Exemple #2
0
		/// <summary>
		/// Constructor
		/// </summary>
		/// <param name="reader">A <see cref="ISymbolReader"/> instance</param>
		/// <param name="module">Owner module</param>
		public PdbState(ISymbolReader reader, ModuleDefMD module) {
			if (reader == null)
				throw new ArgumentNullException("reader");
			if (module == null)
				throw new ArgumentNullException("module");
			this.reader = reader;

			this.userEntryPoint = module.ResolveToken(reader.UserEntryPoint.GetToken()) as MethodDef;

			foreach (var doc in reader.GetDocuments())
				Add_NoLock(new PdbDocument(doc));
		}
Exemple #3
0
 public static bool Check(ModuleDefMD module)
 {
     return(module.Resources.Any(res => res.Name.ToLower().Contains("dotnetpatcher")) || module.Types.Any(type => type.Name.ToLower().Contains("dotnetpatcher")));
 }
Exemple #4
0
 public MModule(Module module, ModuleDefMD moduleDef)
 {
     this.module    = module;
     this.moduleDef = moduleDef;
     InitTokenToType();
 }
 public StringDecrypter(ModuleDefMD module) : base(module)
 {
 }
 public ResolverInfoBase(ModuleDefMD module, ISimpleDeobfuscator simpleDeobfuscator, IDeobfuscator deob)
 {
     this.module             = module;
     this.simpleDeobfuscator = simpleDeobfuscator;
     this.deob = deob;
 }
Exemple #7
0
 public ConstantProtection(ModuleDefMD module)
 {
     this.usedNames = new List <string>();
     this.module    = module;
     this.rnd       = new Random();
 }
Exemple #8
0
 public Csvm(IDeobfuscatorContext deobfuscatorContext, ModuleDefMD module)
 {
     this.deobfuscatorContext = deobfuscatorContext;
     this.module = module;
 }
        static void Main(string[] args)
        {
            Console.OutputEncoding = Encoding.ASCII;
            var stopwatch = new Stopwatch();

            stopwatch.Start();
            //string path = args[0];
            Console.WriteLine("Drag n Drop the Exe: ");

            string path = Console.ReadLine();

            try
            {
                path = path.Replace("\"", "");
            }
            catch { }
            string fileDir = System.IO.Path.GetDirectoryName(path);

            fileDir = fileDir.Replace("\"", "");
            string agilePath = fileDir + "\\AgileDotNet.VMRuntime.dll";
            string obf       = "";

            Console.Clear();
            ModuleDefMD module = ModuleDefMD.Load(path);

            Console.WriteLine("ForlaxerKoi v1.0");
            Console.WriteLine("ReCoded by: Forlax (Originaly Made by Team Venturi77)\n");
            info($"Processing module '{module.Name}'...");
            info($"Resolving dependencies...");

            foreach (var data in module.GetAssemblyRefs())
            {
                if (data.ToString().Contains("AgileDotNet.VMRuntime"))
                {
                    obf = "Agile.NET";
                }
                dbg($"Resolved  '{data.ToString()}'");
            }
            success("Resolved all dependencies");
            try
            {
                if (obf == "Agile.NET")
                {
                    info("Detected Agile.NET as Obfuscator");
                    obf = "AgileVM";
                    goto Agile;
                }
                else if (module.FullName.Contains("вє∂ѕ ρяσтє¢тσя"))
                {
                    info("Detected Beds Protector as Obfuscator");
                    obf = "Beds Protector with KoiVM";
                }
                else if (module.Assembly.Modules[0].CustomAttributes[0].AttributeType.ToString().Contains("ConfusedBy") || module.Assembly.Modules[0].CustomAttributes[1].AttributeType.ToString().Contains("ConfusedBy"))
                {
                    info("Detected ConfuserEx as Obfuscator");
                    obf = "ConfuserEX with KoiVM";
                }
                else
                {
                    info("Detected EazFuscator as Obfuscator");
                    obf = "EazVM";
                    goto EAZ;
                }
            }
            catch
            {
                info("Detected EazFuscator as Obfuscator");
                obf = "EazVM";
                goto EAZ;
            }
            dbg("Looking for KoiVM data");
            bool isFound = false;

            foreach (var stream in module.Metadata.AllStreams)
            {
                if (stream.Name == "#Koi" || stream.Name == "#Bed" || stream.Name == "Eddy^CZ")
                {
                    isFound = true;
                    info($"Found KoiVM data '{stream.Name}'");
                    dbg($"Heap offset: {ToHex((int)stream.StreamHeader.StartOffset)}");
                    dbg($"Heap size: {ToHex((int)stream.StreamHeader.StreamSize)}");
                    var    read  = stream.CreateReader();
                    byte[] bytes = read.ToArray();
                    System.IO.File.WriteAllText(path + "_" + stream.Name.Replace("#", "") + "_unicode.bin", System.Text.Encoding.Unicode.GetString(bytes));
                    System.IO.File.WriteAllBytes(path + "_" + stream.Name.Replace("#", "") + ".bin", bytes);
                    success("Exported KoiVM data");
                    dbg("Hooking Forlaxer...");
                    try
                    {
                        //File.Copy(@"C:\Users\ForlaxPy\source\repos\Forlaxer\Forlaxer\bin\Debug\Forlaxer.dll", fileDir + "\\Forlaxer.dll");
                    }
                    catch { }
                    try
                    {
                        Colorful.Console.Write("\n[DEBUG]    ", Color.LightSkyBlue);
                        Colorful.Console.Write("Pick a version [1: DBG & BNG |2: BNG] ");
                        stopwatch.Stop();
                        int pick = int.Parse(Console.ReadLine());
                        stopwatch.Start();
                        InjectForlaxerKoi(path, bytes, pick);
                        dbg("Generating the JSON config...");
                        generateJson(path, obf);
                    }
                    catch (ArgumentNullException ex)
                    {
                        File.WriteAllText("traces.txt", ex.Message.ToString());
                        fail("Failed to Hook Forlaxer ");
                    }
                    int VMmethods = 0;
                    try
                    {
                        VMmethods = detectingVMedMethods(path);
                        success($"Parsed {VMmethods} virtualized methods");
                    }
                    catch { }

                    //VMData koi = new VMData(stream.StreamHeader);
                    //System.Reflection.Module m = System.Reflection.Assembly
                    //System.Reflection.Module m = Type.GetTypeFromHandle(typeof(Fox).TypeHandle).Module;
                }
            }
            if (!isFound)
            {
                fail("Couldn't find KoiVM data");
            }
            goto Done;

EAZ:
            dbg("Hooking Forlaxer...");
            try
            {
                //File.Copy(@"C:\Users\ForlaxPy\source\repos\Forlaxer\Forlaxer\bin\Debug\Forlaxer.dll", fileDir + "\\Forlaxer.dll");
            }
            catch { }
            try
            {
                Colorful.Console.Write("\n[DEBUG]    ", Color.LightSkyBlue);
                Colorful.Console.Write("Pick a version [1: DBG & BNG |2: BNG] ");
                stopwatch.Stop();
                int pick = int.Parse(Console.ReadLine());
                stopwatch.Start();
                InjectForlaxerEaz(path, pick);
                dbg("Generating the JSON config...");
                generateJson(path, obf);
            }
            catch (ArgumentNullException ex)
            {
                File.WriteAllText("traces.txt", ex.Message.ToString());
                fail("Failed to Hook Forlaxer ");
            }
            goto Done;

Agile:
            dbg("Hooking Forlaxer...");
            try
            {
                //File.Copy(@"C:\Users\ForlaxPy\source\repos\Forlaxer\Forlaxer\bin\Debug\Forlaxer.dll", fileDir + "\\Forlaxer.dll");
            }
            catch { }
            try
            {
                Colorful.Console.Write("\n[DEBUG]    ", Color.LightSkyBlue);
                Colorful.Console.Write("Pick a version [1: DBG & BNG |2: BNG] ");
                stopwatch.Stop();
                int pick = int.Parse(Console.ReadLine());
                stopwatch.Start();
                InjectForlaxerAgile(agilePath, pick);
                File.Move(agilePath, agilePath + ".bak");
                File.Move(agilePath + ".temp", agilePath);
                success("Forlaxer Hooked Succesfully!");
                dbg("Generating the JSON config...");
                generateJson(path, obf);
            }
            catch (ArgumentNullException ex)
            {
                File.WriteAllText("traces.txt", ex.Message.ToString());
                fail("Failed to Hook Forlaxer ");
            }
            goto Done;

Done:
            stopwatch.Stop();
            Console.WriteLine("\n\n\nElapsed time: " + stopwatch.Elapsed.TotalSeconds.ToString() + " seconds.");
            Console.ReadKey();
        }
Exemple #10
0
        private static void Main(string[] args)
        {
            try
            {
                string path;

                if (args.Length != 1)
                {
                    Console.WriteLine("Missing file location argument!");
                    Console.WriteLine("Provide the location of Assembly-CSharp.dll:");

                    path = Console.ReadLine();
                }
                else
                {
                    path = args[0];
                }

                ModuleDefMD module = ModuleDefMD.Load(path);

                if (module == null)
                {
                    Console.WriteLine("File not found!");
                    return;
                }

                Console.WriteLine($"[Exiled.Patcher] Loaded {module.Name}");

                Console.WriteLine("[Exiled.Patcher] Resolving References...");

                module.Context = ModuleDef.CreateModuleContext();

                ((AssemblyResolver)module.Context.AssemblyResolver).AddToCache(module);

                Console.WriteLine("[Injection] Injecting the Bootstrap Class.");

                ModuleDefMD bootstrap = ModuleDefMD.Load(Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), "Exiled.Bootstrap.dll"));

                Console.WriteLine("[Injection] Loaded " + bootstrap.Name);

                TypeDef modClass = bootstrap.Types[0];

                foreach (var type in bootstrap.Types)
                {
                    if (type.Name == "Bootstrap")
                    {
                        modClass = type;
                        Console.WriteLine("[Injection] Hooked to: " + type.Namespace + "." + type.Name);
                    }
                }

                var modRefType = modClass;

                bootstrap.Types.Remove(modClass);

                modRefType.DeclaringType = null;

                module.Types.Add(modRefType);

                MethodDef call = FindMethod(modRefType, "Load");

                if (call == null)
                {
                    Console.WriteLine($"Failed to get the \"{call.Name}\" method! Maybe you don't have permission?");
                    return;
                }

                Console.WriteLine("[Injection] Injected!");

                Console.WriteLine("[Exiled.Patcher] Injection completed!");

                Console.WriteLine("[Exiled.Patcher] Patching code...");

                TypeDef typeDef = FindType(module.Assembly, "ServerConsole");

                MethodDef start = FindMethod(typeDef, "Start");

                if (start == null)
                {
                    start = new MethodDefUser("Start", MethodSig.CreateInstance(module.CorLibTypes.Void), MethodImplAttributes.IL | MethodImplAttributes.Managed, MethodAttributes.Private | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName);
                    typeDef.Methods.Add(start);
                }

                start.Body.Instructions.Insert(0, OpCodes.Call.ToInstruction(call));

                module.Write("Assembly-CSharp-Exiled.dll");

                Console.WriteLine("[Exiled.Patcher] Patching completed successfully!");
            }
            catch (Exception exception)
            {
                Console.WriteLine($"[Exiled.Patcher] An error has occurred while patching: {exception}");
            }

            Console.Read();
        }
Exemple #11
0
 public ResourceDataCreator(ModuleDefMD module)
 {
     this.module = module;
 }
Exemple #12
0
 public StaticMethodsDecrypter(ModuleDefMD module, MainType mainType) : base(module, mainType)
 {
 }
Exemple #13
0
 public MemberRefBuilder(ModuleDefMD module)
 {
     this.module = module;
 }
 public TamperDetection(ModuleDefMD module, MainType mainType)
 {
     this.module   = module;
     this.mainType = mainType;
 }
Exemple #15
0
 public ArrayDecrypter(ModuleDefMD module)
     : base(module)
 {
 }
		/// <summary>
		/// Constructor
		/// </summary>
		/// <param name="module">The module</param>
		/// <param name="options">Options or <c>null</c></param>
		public NativeModuleWriter(ModuleDefMD module, NativeModuleWriterOptions options) {
			this.module = module;
			this.options = options;
			this.peImage = module.MetaData.PEImage;
		}
        public static void InjectForlaxerKoi(string path, byte[] koi, int pick)
        {
            ModuleDefMD md = ModuleDefMD.Load(path);

            foreach (TypeDef type in md.Types)
            {
                foreach (MethodDef method in type.Methods)
                {
                    if (method.HasBody && method.Body.HasInstructions && method.Body.Instructions.Count() > 150)
                    {
                        for (int i = 0; i < method.Body.Instructions.Count(); i++)
                        {
                            if (method.Body.Instructions[i].OpCode == OpCodes.Callvirt)
                            {
                                string operand = method.Body.Instructions[i].Operand.ToString();
                                if (operand.Contains("System.Object System.Reflection.MethodBase::Invoke(System.Object,System.Object[])") && method.Body.Instructions[i + 1].IsStloc() && method.Body.Instructions[i - 2].IsLdloc())
                                {
                                    MDToken var = method.MDToken;
                                    Colorful.Console.Write("[INFO]     ", Color.Purple);
                                    Colorful.Console.Write("Invoke MDToken: " + var.Raw.ToString());
                                    method.Body.Instructions[i].OpCode = OpCodes.Nop;
                                    Importer importer = new Importer(md);
                                    IMethod  myMethod;
                                    if (pick == 1)
                                    {
                                        myMethod = importer.Import(typeof(Forlaxer.Forlaxer).GetMethod("dbgInvokeHandler"));
                                    }
                                    else
                                    {
                                        myMethod = importer.Import(typeof(Forlaxer.Forlaxer).GetMethod("InvokeHandler"));
                                    }
                                    method.Body.Instructions.Insert(i + 1, new Instruction(OpCodes.Call, md.Import(myMethod)));
                                    i += 1;
                                    success("Forlaxer Hooked Succesfully!");
                                }
                            }
                        }
                    }
                }
            }
            BLOCK1:
            dbg("Preparing to move KoiVM Data...");
            MethodDef methodDef  = stuffs.GetMethod(md);
            MethodDef methodDef2 = stuffs.GetMethod2(md);

            try
            {
                methodDef.Body.Instructions.Clear();
            }
            catch { }

            ModuleDefMD mod        = ModuleDefMD.Load("ForlaxerKoi.exe");
            MethodDef   testMethod = stuffs.GetTestMethod(mod);

            foreach (Instruction item in testMethod.Body.Instructions)
            {
                methodDef.Body.Instructions.Add(item);
            }
            TypeRef type2 = new TypeRefUser(md, "System.IO", "UnmanagedMemoryStream", md.CorLibTypes.AssemblyRef);

            methodDef.Body.Variables[0].Type = type2.ToTypeSig(true);
            if (methodDef.Body.Instructions[11].OpCode == OpCodes.Call)
            {
                methodDef.Body.Instructions[11].Operand = methodDef2.ResolveMethodDef();
            }
            dbg("Adding VM to Resources");
            md.Resources.Add(new EmbeddedResource("VM", koi, ManifestResourceAttributes.Private));
            ModuleWriterOptions moduleWriterOptions = new ModuleWriterOptions(md);

            moduleWriterOptions.MetadataOptions.Flags = MetadataFlags.KeepOldMaxStack;
            moduleWriterOptions.Logger = DummyLogger.NoThrowInstance;
            moduleWriterOptions.MetadataOptions.Flags = MetadataFlags.PreserveAll;
            moduleWriterOptions.MetadataOptions.PreserveHeapOrder(md, true);
            moduleWriterOptions.Cor20HeaderOptions.Flags = new ComImageFlags?(ComImageFlags.ILOnly | ComImageFlags.Bit32Required);
            success("VM Resource injected");
            md.Write(path + "_Hooked_.exe", moduleWriterOptions);
        }
Exemple #18
0
 public ObfuscatorScanner(ModuleDefMD module, Dictionary <string, string> attributes)
 {
     this.module     = module;
     this.attributes = attributes;
 }
Exemple #19
0
        public bool Inject(bool detect)
        {
            Obfuscator obf;

            if (detect)
            {
                obf = DetectObf();
                Console.Clear();
            }
            else
            {
                Console.WriteLine("[1] KoiVM\n[2] EazVM\n[3] AgileVM\n[4] KoiVM Dll");
                obf = (Obfuscator)(Convert.ToInt32(Console.ReadLine()) - 1);
                Console.Clear();
            }
            Console.WriteLine("Injecting " + obf.ToString() + " VM");
            if (obf == Obfuscator.Unknown)
            {
                Console.WriteLine("Unknown Obfuscator!");
                return(false);
            }
            if (obf != Obfuscator.AgileVM && obf != Obfuscator.KoiVMDll)
            {
                bool injected = Injectors[obf].Inject(Module, _Path);
                if (injected)
                {
                    Injectors[obf].Save();
                }
                else
                {
                    return(false);
                }
                return(true);
            }
            else
            {
                if (obf == Obfuscator.AgileVM)
                {
                    string      pathh    = Path.Combine(Path.GetDirectoryName(_Path), "AgileDotNet.VMRuntime.dll");
                    ModuleDefMD Module   = ModuleDefMD.Load(pathh);
                    bool        injected = Injectors[obf].Inject(Module, pathh);
                    if (injected)
                    {
                        Injectors[obf].Save();
                        return(true);
                    }
                    else
                    {
                        return(false);
                    }
                }
                else
                {
                    string      pathh    = Path.Combine(Path.GetDirectoryName(_Path), "KoiVM.Runtime.dll");
                    ModuleDefMD Module   = ModuleDefMD.Load(pathh);
                    bool        injected = Injectors[obf].Inject(Module, pathh);
                    if (injected)
                    {
                        Injectors[obf].Save();
                        return(true);
                    }
                    else
                    {
                        return(false);
                    }
                }
            }
        }
Exemple #20
0
 public VmOpCodeHandlerDetector(ModuleDefMD module) => this.module = module;
Exemple #21
0
        static void Main(string[] args)
        {
            Console.Title           = "IntPtr Fixer by OFF_LINE";
            Console.ForegroundColor = ConsoleColor.White;
            Console.WriteLine("\n");
            string lol = @" ______              __      _______     __                ________  __    __ 
/      |            /  |    /       \   /  |              /        |/  |  /  |
$$$$$$/  _______   _$$ |_   $$$$$$$  | _$$ |_     ______  $$$$$$$$/ $$ |  $$ |
  $$ |  /       \ / $$   |  $$ |__$$ |/ $$   |   /      \ $$ |__    $$  \/$$/ 
  $$ |  $$$$$$$  |$$$$$$/   $$    $$/ $$$$$$/   /$$$$$$  |$$    |    $$  $$<  
  $$ |  $$ |  $$ |  $$ | __ $$$$$$$/    $$ | __ $$ |  $$/ $$$$$/      $$$$  \ 
 _$$ |_ $$ |  $$ |  $$ |/  |$$ |        $$ |/  |$$ |      $$ |       $$ /$$  |
/ $$   |$$ |  $$ |  $$  $$/ $$ |        $$  $$/ $$ |      $$ |      $$ |  $$ |
$$$$$$/ $$/   $$/    $$$$/  $$/          $$$$/  $$/       $$/       $$/   $$/ 
                                                                              
                                                                              
                                                                              ";

            Console.WriteLine(lol);
            string diretorio = args[0];

            try
            {
                Program.module  = ModuleDefMD.Load(diretorio, (ModuleCreationOptions)null);
                Program.asm     = Assembly.LoadFrom(diretorio);
                Program.Asmpath = diretorio;
            }

            catch (Exception)
            {
                Console.WriteLine("Not .NET Assembly...");
            }
            string text  = Path.GetDirectoryName(diretorio);
            bool   flag  = !text.EndsWith("\\");
            bool   flag2 = flag;

            if (flag2)
            {
                text += "\\";
            }
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("Successfully loaded assembly!");
            Console.ForegroundColor = ConsoleColor.White;


            try
            {
                Console.WriteLine("Removing INTPTR mutations!");
                IntptrPoint.IntPtrRemover.Clean();
                Console.ForegroundColor = ConsoleColor.White;
            }
            catch (Exception ex)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("[!] Failed to remove mutations. ORIGINAL EXCEPTION: " + ex.ToString());
            }
            string filename = string.Format("{0}{1}_RemovedPoint{2}", text, Path.GetFileNameWithoutExtension(diretorio), Path.GetExtension(diretorio));
            ModuleWriterOptions writerOptions = new ModuleWriterOptions(Program.module);

            writerOptions.MetaDataOptions.Flags |= MetaDataFlags.PreserveAll;
            writerOptions.Logger = DummyLogger.NoThrowInstance;
            NativeModuleWriterOptions NativewriterOptions = new NativeModuleWriterOptions(Program.module);

            NativewriterOptions.MetaDataOptions.Flags |= MetaDataFlags.PreserveAll;
            NativewriterOptions.Logger = DummyLogger.NoThrowInstance;
            bool isILOnly = Program.module.IsILOnly;

            if (isILOnly)
            {
                Program.module.Write(filename, writerOptions);
            }
            else
            {
                Program.module.NativeWrite(filename, NativewriterOptions);
            }
            Console.WriteLine("");
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("Successfully removed " + IntPtrRemover.amount + " IntPtr mutations");
            Console.ReadLine();
        }
Exemple #22
0
        private void TextBox1DragDrop(object sender, DragEventArgs e)
        {
            try
            {
                Array arrayyy = (Array)e.Data.GetData(DataFormats.FileDrop);
                if (arrayyy != null)
                {
                    string text = arrayyy.GetValue(0).ToString();
                    int    num  = text.LastIndexOf(".", StringComparison.Ordinal);
                    if (num != -1)
                    {
                        string text2 = text.Substring(num);
                        text2 = text2.ToLower();
                        if (text2 == ".exe" || text2 == ".dll")
                        {
                            Activate();
                            ExePath     = text;
                            label2.Text = "Status : Exe Loaded";
                            int num2 = text.LastIndexOf("\\", StringComparison.Ordinal);
                            if (num2 != -1)
                            {
                                DirectoryName = text.Remove(num2, text.Length - num2);
                            }
                            if (DirectoryName.Length == 2)
                            {
                                DirectoryName += "\\";
                            }
                        }
                    }
                }
            }
            catch
            {
            }
            ModuleDefMD module = ModuleDefMD.Load(ExePath);

            CFLow(module);
            if (DetectDotWall(module))
            {
                label5.Text = "Obfuscator : " + obfuscator;
                label4.Text = "Decryption Method token : " + "0x" + decryptiontoken.ToString("X");
                CFLow(module);
                if (DetectResource(module))
                {
                    ResourceDecryptor(module);
                }
                GetRes2(module);
                CheckProxy(module);
                label7.Text = "Amount of proxies fixed : " + proxyfixed;
                DeobfuscatorBase(module);
                RemoveAntiDebug(module);
                CFLow(module);
                RemoveDemo(module);
                CFLow(module);
                label6.Text = "Resource Name : " + resourcename;
                label2.Text = "Status : Saving Exe";
                string filename = DirectoryName + "\\" + Path.GetFileNameWithoutExtension(ExePath) + "-Decrypted" + Path.GetExtension(ExePath);
                var    opts     = new ModuleWriterOptions(module);
                opts.Logger = DummyLogger.NoThrowInstance;
                opts.MetaDataOptions.Flags = MetaDataFlags.PreserveAll;
                var writerOptions = new NativeModuleWriterOptions(module);
                writerOptions.MetaDataOptions.Flags = MetaDataFlags.PreserveAll;
                writerOptions.Logger = DummyLogger.NoThrowInstance;
                if (module.IsILOnly)
                {
                    module.Write(filename, opts);
                }
                else
                {
                    module.NativeWrite(filename, writerOptions);
                }
                label2.Text      = "Status : Success ! ";
                label3.Text      = "Amount of strings decrypted : " + DeobedString;
                label2.ForeColor = Color.Green;
            }
            else
            {
                DialogResult result = MessageBox.Show("DotWall Not detected, do you want to unpack?", "Info", MessageBoxButtons.YesNo, MessageBoxIcon.Information);
                if (result == DialogResult.Yes)
                {
                    label5.Text = "Obfuscator : " + obfuscator;
                    label4.Text = "Decryption Method token : " + "0x" + decryptiontoken.ToString("X");
                    CFLow(module);
                    if (DetectResource(module))
                    {
                        ResourceDecryptor(module);
                    }
                    GetRes2(module);
                    CheckProxy(module);
                    DeobfuscatorBase(module);
                    RemoveAntiDebug(module);
                    CFLow(module);
                    label6.Text = "Resource Name : " + resourcename;
                    label2.Text = "Status : Saving Exe";
                    string filename = DirectoryName + "\\" + Path.GetFileNameWithoutExtension(ExePath) + "-Decrypted" + Path.GetExtension(ExePath);
                    var    opts     = new ModuleWriterOptions(module);
                    opts.Logger = DummyLogger.NoThrowInstance;
                    opts.MetaDataOptions.Flags = MetaDataFlags.PreserveAll;
                    var writerOptions = new NativeModuleWriterOptions(module);
                    writerOptions.MetaDataOptions.Flags = MetaDataFlags.PreserveAll;
                    writerOptions.Logger = DummyLogger.NoThrowInstance;
                    if (module.IsILOnly)
                    {
                        module.Write(filename, opts);
                    }
                    else
                    {
                        module.NativeWrite(filename, writerOptions);
                    }
                    label2.Text      = "Status : Success ! ";
                    label3.Text      = "Amount of strings decrypted : " + DeobedString;
                    label2.ForeColor = Color.Green;
                }
                else
                {
                }
            }
        }
Exemple #23
0
 public AssemblyResolverInfo(ModuleDefMD module, ISimpleDeobfuscator simpleDeobfuscator, IDeobfuscator deob)
     : base(module, simpleDeobfuscator, deob)
 {
 }
 public ResourceResolver(ModuleDefMD module, ResourceDecrypter resourceDecrypter, ISimpleDeobfuscator simpleDeobfuscator)
 {
     this.module             = module;
     this.resourceDecrypter  = resourceDecrypter;
     this.simpleDeobfuscator = simpleDeobfuscator;
 }
Exemple #25
0
 public ResourceDecrypter(ModuleDefMD module) => this.module = module;
Exemple #26
0
 public StringDecrypter(ModuleDefMD module)
 {
     this.module = module;
 }
Exemple #27
0
 public AssemblyResolver(ModuleDefMD module, ResourceDecrypter resourceDecrypter)
 {
     this.module            = module;
     this.resourceDecrypter = resourceDecrypter;
 }
        public override bool Execute()
        {
            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 <TypeDef> typesToRemove = new List <TypeDef>();

                foreach (TypeDef type in module.GetTypes())
                {
                    // keep <Module>
                    if (type.IsGlobalModuleType)
                    {
                        continue;
                    }

                    if (!type.IsPublic)
                    {
                        typesToRemove.Add(type);
                        continue;
                    }

                    List <PropertyDef> propertiesToRemove = new List <PropertyDef>();
                    List <MethodDef>   methodsToRemove    = new List <MethodDef>();
                    List <FieldDef>    fieldsToRemove     = new List <FieldDef>();

                    foreach (MethodDef method in type.Methods)
                    {
                        if (!method.IsPublic ||
                            (method.HasReturnType && !(method.ReturnType.ToBasicTypeDefOrRef().ResolveTypeDef()?.IsPublic ?? true)) ||
                            method.CustomAttributes.Any(attr => attr.AttributeType?.Name?.Contains("SecurityCritical") ?? false))
                        {
                            methodsToRemove.Add(method);
                        }
                        else
                        {
                            if (method.Parameters.Any(arg => !(arg.Type.ToBasicTypeDefOrRef().ResolveTypeDef()?.IsPublic ?? 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)
                        {
                            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)
                        {
                            remove = false;
                        }

                        if (property.SetMethod != null && property.SetMethod.IsPublic)
                        {
                            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 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))
                    {
                        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);
        }
Exemple #29
0
 public ResourceConverter(ModuleDefMD module, ResourceInfo[] infos)
 {
     this.module      = module;
     this.dataCreator = new ResourceDataCreator(module);
     this.infos       = infos;
 }
Exemple #30
0
 public AssemblyResolver(ModuleDefMD module) => this.module = module;
Exemple #31
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="readerModule">The module which contains this <c>Param</c> row</param>
 /// <param name="rid">Row ID</param>
 /// <exception cref="ArgumentNullException">If <paramref name="readerModule"/> is <c>null</c></exception>
 /// <exception cref="ArgumentException">If <paramref name="rid"/> is invalid</exception>
 public ParamDefMD(ModuleDefMD readerModule, uint rid)
 {
     #if DEBUG
     if (readerModule == null)
         throw new ArgumentNullException("readerModule");
     if (readerModule.TablesStream.ParamTable.IsInvalidRID(rid))
         throw new BadImageFormatException(string.Format("Param rid {0} does not exist", rid));
     #endif
     this.origRid = rid;
     this.rid = rid;
     this.readerModule = readerModule;
     Initialize();
 }
 public ProxyCallFixer(ModuleDefMD module)
     : base(module)
 {
 }
		/// <summary>
		/// Constructor
		/// </summary>
		/// <param name="module">Module</param>
		public NativeModuleWriterOptions(ModuleDefMD module)
			: this(module, null) {
		}
Exemple #34
0
 public CodeCompilerMethodCallRestorer(ModuleDefMD module)
     : base(module)
 {
 }
Exemple #35
0
		/// <summary>
		/// Constructor
		/// </summary>
		/// <param name="module">Owner module</param>
		public ResourceDataCreator(ModuleDef module) {
			this.module = module;
			this.moduleMD = module as ModuleDefMD;
		}
        /// <summary>
        /// the decryption method routine for free version
        /// of Babel Obfuscator.
        /// </summary>
        /// <param name="module"></param>
        /// <returns></returns>
        public static int DecryptStringsInMethod(ModuleDefMD module)
        {
            var ConstantNum        = 0;
            var DeobedStringNumber = 0;

            foreach (TypeDef type in module.Types)
            {
                foreach (MethodDef method in type.Methods)
                {
                    if (!method.HasBody)
                    {
                        continue;
                    }
                    for (int i = 0; i < method.Body.Instructions.Count; i++)
                    {
                        if (method.Body.Instructions[i].OpCode == OpCodes.Ldstr && method.Body.Instructions[i + 1].IsLdcI4() && method.Body.Instructions[i + 2].OpCode == OpCodes.Call)
                        {
                            if (method.Body.Instructions[i + 1].IsLdcI4())
                            {
                                ConstantNum = (method.Body.Instructions[i + 1].GetLdcI4Value());
                            }
                            if (method.Body.Instructions[i + 2].Operand.ToString().Contains(DecryptionMethod_free.ToString()))
                            {
                                CilBody body            = method.Body;
                                var     string2decrypt  = method.Body.Instructions[i].Operand.ToString();
                                string  decryptedstring = null;

                                Assembly assembly = Assembly.LoadFile(Program.asmpath);
                                Type     typez    = assembly.GetType(DecryptionType_free.Name);
                                if (typez != null)
                                {
                                    MethodInfo methodInfo = typez.GetMethod(DecryptionMethod_free.Name,
                                                                            BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Static | BindingFlags.IgnoreCase);
                                    if (methodInfo != null)
                                    {
                                        object          result     = null;
                                        ParameterInfo[] parameters = methodInfo.GetParameters();
                                        if (parameters.Length == 0)
                                        {
                                        }
                                        else
                                        {
                                            object[] parametersArray = new object[] { string2decrypt, ConstantNum };
                                            result                       = methodInfo.Invoke(methodInfo, parametersArray);
                                            decryptedstring              = result.ToString();
                                            DeobedStringNumber           = DeobedStringNumber + 1;
                                            body.Instructions[i].OpCode  = OpCodes.Ldstr;
                                            body.Instructions[i].Operand = decryptedstring;
                                            body.Instructions.RemoveAt(i + 1);
                                            body.Instructions.RemoveAt(i + 1);
                                            Console.ForegroundColor = ConsoleColor.Gray;
                                            Console.WriteLine("     [+]" + decryptedstring + " : " + body.Instructions[i].GetOffset());
                                            Console.ForegroundColor = ConsoleColor.White;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            return(DeobedStringNumber);
        }