示例#1
0
 protected override void LoadChildren()
 {
     foreach (var r in module.GetAssemblyRefs().OrderBy(r => r.Name.String))
     {
         this.Children.Add(new AssemblyReferenceTreeNode(r, parentAssembly));
     }
     foreach (var r in module.GetModuleRefs().OrderBy(r => r.Name.String))
     {
         this.Children.Add(new ModuleReferenceTreeNode(r));
     }
 }
示例#2
0
        public static Obfuscator DetectObfuscator(ModuleDefMD Module, string Path)
        {
            if (Module.GetAssemblyRefs().Where(q => q.ToString().Contains("AgileDotNet.VMRuntime")).ToArray().Count() > 0)
            {
                return(Obfuscator.AgileVM);
            }
            if (Module.Types.SingleOrDefault(t => t.HasFields && t.Fields.Count == 119) != null)
            {
                return(Obfuscator.KoiVM);
            }
            if (Module.GetAssemblyRefs().Where(q => q.ToString().Contains("KoiVM.Runtime")).ToArray().Count() > 0)
            {
                return(Obfuscator.KoiVMDll);
            }

            foreach (var type in Module.Types)
            {
                foreach (var method in type.Methods)
                {
                    if (method.HasBody && method.Body.HasInstructions && method.Body.Instructions.Count() >= 6)
                    {
                        if (method.Body.Instructions[0].IsLdarg())
                        {
                            if (method.Body.Instructions[1].IsLdarg())
                            {
                                if (method.Body.Instructions[2].IsLdarg())
                                {
                                    if (method.Body.Instructions[3].IsLdarg())
                                    {
                                        if (method.Body.Instructions[5].OpCode == OpCodes.Pop)
                                        {
                                            if (method.Body.Instructions[6].OpCode == OpCodes.Ret)
                                            {
                                                if (method.Body.Instructions[4].OpCode == OpCodes.Call)
                                                {
                                                    if (method.Body.Instructions[4].ToString().Contains("(System.IO.Stream,System.String,System.Object[])"))
                                                    {
                                                        return(Obfuscator.EazVM);
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            return(Obfuscator.Unknown);
        }
示例#3
0
        private void LoadDependencies(ModuleDefMD module)
        {
            if (seenModules.Contains(module.Location))
            {
                return;
            }

            seenModules.Add(module.Location);
            Modules.Add(module);
            Resolver.AddToCache(module);

            foreach (var assemblyRef in module.GetAssemblyRefs())
            {
                // There are cases, where the Resolver will not be able to resolve the assemblies
                // automatically, even if they are in the same directory.
                // (maybe this has todo with linux / specific mono versions?)
                // So, try to load them manually recursively first.
                var subModuleFile = Path.Combine(Path.GetDirectoryName(module.Location), assemblyRef.Name + ".dll");
                if (File.Exists(subModuleFile))
                {
                    var subModule = ModuleDefMD.Load(subModuleFile, Resolver.DefaultModuleContext);
                    if (subModule != null)
                    {
                        LoadDependencies(subModule);
                    }
                }

                var assembly = Resolver.ResolveThrow(assemblyRef, null);

                foreach (var moduleRef in assembly.Modules)
                {
                    LoadDependencies((ModuleDefMD)moduleRef);
                }
            }
        }
示例#4
0
        /// <summary>
        /// Get the AssemblyRef of the module from the assembly full name, adding
        /// our own AssemblyRef if none found.
        /// </summary>
        /// <param name="fullName">Assembly full name</param>
        /// <returns>AssemblyRef</returns>
        public AssemblyRef FindAssemblyRef(String fullName)
        {
            // fullName: ", mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
            // causes...
            // System.IO.FileLoadException: The given assembly name or codebase was invalid. (Exception from HRESULT: 0x80131047)
            //    at System.Reflection.AssemblyName.nInit(RuntimeAssembly& assembly, Boolean forIntrospection, Boolean raiseResolveEvent)
            //    at System.Reflection.AssemblyName.nInit()
            //    at eazdevirt.Util.NameResolver.FindAssemblyRef(String fullName)
            //    at eazdevirt.Util.NameResolver.FindAssemblyRef(TypeName typeName)
            //    at eazdevirt.Util.NameResolver.ResolveTypeDefOrRef(TypeName typeName)
            //    at eazdevirt.IO.Resolver.ResolveType_NoLock(Int32 position)
            //    at eazdevirt.IO.Resolver.ResolveType(Int32 position)
            //    at eazdevirt.IO.VirtualizedMethodBodyReader.SetLocalsAndParameters()
            //    at eazdevirt.IO.VirtualizedMethodBodyReader.Read()
            //    at eazdevirt.Devirtualizer.Devirtualize(DevirtualizeOptions options, Action`1 attemptCallback)

            // Try to find AssemblyRef via full name
            var assemblyRef = _module.GetAssemblyRefs().FirstOrDefault((ar) =>
            {
                return(ar.FullName.Equals(fullName));
            });

            if (assemblyRef != null)
            {
                return(assemblyRef);
            }

            // If unable to find, add our own AssemblyRef from the full name
            return(new AssemblyRefUser(new System.Reflection.AssemblyName(fullName)));
        }
示例#5
0
        private static void asmRefAdder()
        {
            var asmResolver = new AssemblyResolver {
                EnableTypeDefCache = true
            };
            var modCtx = new ModuleContext(asmResolver);

            asmResolver.DefaultModuleContext = modCtx;
            var asmRefs = module.GetAssemblyRefs().ToList();

            module.Context = modCtx;
            foreach (var asmRef in asmRefs)
            {
                try
                {
                    if (asmRef == null)
                    {
                        continue;
                    }
                    var asm = asmResolver.Resolve(asmRef.FullName, module);
                    if (asm == null)
                    {
                        continue;
                    }
                    ((AssemblyResolver)module.Context.AssemblyResolver).AddToCache(asm);
                }
                catch
                {
                }
            }
        }
示例#6
0
        public static FrameworkType GetFrameworkType(ModuleDefMD module)
        {
            foreach (var modRef in module.GetAssemblyRefs())
            {
                if (modRef.Name != "mscorlib")
                {
                    continue;
                }
                if (PublicKeyBase.IsNullOrEmpty2(modRef.PublicKeyOrToken))
                {
                    continue;
                }
                switch (BitConverter.ToString(modRef.PublicKeyOrToken.Data).Replace("-", "").ToLowerInvariant())
                {
                case "b77a5c561934e089":
                    return(FrameworkType.Desktop);

                case "7cec85d7bea7798e":
                    return(FrameworkType.Silverlight);

                case "969db8053d3322ac":
                    return(FrameworkType.CompactFramework);

                case "1c9e259686f921e0":
                    return(FrameworkType.XNA);

                case "e92a8b81eba7ceb7":
                    return(FrameworkType.Zune);
                }
            }

            return(FrameworkType.Unknown);
        }
示例#7
0
        public void LoadAssembly(ModuleDefMD manifestModule, string path, bool clear)
        {
            AnalysisHandler.Reset();
            RefNode       = null;
            CurrentModule = null;

            if (clear)
            {
                CurrentTreeView.Nodes.Clear();
            }

            TreeNode file = NewFile(manifestModule, path);

            file.AddTo(CurrentTreeView);

            ModuleDefMD module = manifestModule;

            NameSpaceList.Clear();

            TreeNode moduleNode = NewModule(module);

            moduleNode.AddTo(file);

            CurrentModule = moduleNode;

            if (module.Types.Any())
            {
                foreach (TypeDef type in module.Types.OrderBy(t => t.Name.ToLower()))
                {
                    new TypeHandler(this).HandleType(type, false);
                }
            }

            CurrentModule = moduleNode;

            if (module.GetAssemblyRefs().Any())
            {
                new ReferenceHandler(this).HandleReferences(module.GetAssemblyRefs());
            }

            var processor = new NodeDevirtualizer(RefNode, this);

            processor.ProcessNode();
            processor.WorkerFinished += processor_WorkerFinished;
            RefNode = processor.Node;
        }
 static bool ShouldPatchAssembly(ModuleDefMD mod)
 {
     foreach (var asmRef in mod.GetAssemblyRefs())
     {
         string name = asmRef.Name;
         if (name == "netstandard")
         {
             return(false);
         }
     }
     return(true);
 }
示例#9
0
 private static void _fixExternalReferenceImpl(ModuleDefMD module, AssemblyRef oldAsmRef, AssemblyRef newAsmRef)
 {
     // Credit: https://github.com/0xd4d/dnSpy/issues/173#issuecomment-242180559
     foreach (var asmRef in module.GetAssemblyRefs())
     {
         if (_isEqual(asmRef, oldAsmRef))
         {
             asmRef.PublicKeyOrToken = newAsmRef.PublicKeyOrToken;
             asmRef.Version          = newAsmRef.Version;
         }
     }
 }
示例#10
0
        //Here we replace the AssemblyRef entry for TrinitySeal with Unitas.Runtime
        //With this, we not only hijack all library calls
        //But we also bypass the hash check
        static void ProcessAssembly(string vars)
        {
            Console.WriteLine("Processing assembly...");
            var opts = new ModuleWriterOptions(_mod)
            {
                Logger = DummyLogger.NoThrowInstance
            };
            var writer = new ModuleWriter(_mod, opts);

            foreach (var asmref in _mod.GetAssemblyRefs())
            {
                if (asmref.Name != "TrinitySeal")
                {
                    continue;
                }

                Console.WriteLine("Replacing reference");
                asmref.Name = "Unitas.Runtime";
            }

            Console.WriteLine("Fixing namespaces...");
            foreach (var typeref in _mod.GetTypeRefs())
            {
                if (typeref.Namespace == "TrinitySeal" && typeref.DefinitionAssembly.Name == "Unitas.Runtime")
                {
                    typeref.Namespace = "Unitas.Runtime";
                }
            }

            //Preserve EVERYTHING
            opts.MetadataOptions.PreserveHeapOrder(_mod, true);
            opts.MetadataOptions.Flags |= MetadataFlags.PreserveRids | MetadataFlags.KeepOldMaxStack;

            var runtime = Path.Combine(Path.GetDirectoryName(_mod.Location), "Unitas.Runtime.dll");

            File.Copy(typeof(Seal).Assembly.Location, runtime, true);
            if (vars != null)
            {
                AddServerVariables(vars, runtime);
            }

            writer.Write(GetNewName());
            Console.WriteLine($"Bypassed assembly saved at: {GetNewName()}");
        }
示例#11
0
        private void LoadDependencies(ModuleDefMD module)
        {
            if (seenModules.Contains(module.Location))
            {
                return;
            }
            seenModules.Add(module.Location);
            Modules.Add(module);
            Resolver.AddToCache(module);

            foreach (var assemblyRef in module.GetAssemblyRefs())
            {
                AssemblyDef assembly = Resolver.ResolveThrow(assemblyRef, null);
                foreach (var moduleRef in assembly.Modules)
                {
                    LoadDependencies((ModuleDefMD)moduleRef);
                }
            }
        }
示例#12
0
 public static void LoadModule(string filename)
 {
     try
     {
         FileName = filename;
         byte[]        data   = File.ReadAllBytes(filename);
         ModuleContext modCtx = ModuleDef.CreateModuleContext();
         module = ModuleDefMD.Load(data, modCtx);
         Write("Module Loaded : " + module.Name, TypeMessage.Info);
         foreach (AssemblyRef dependance in module.GetAssemblyRefs())
         {
             Write($"Dependance : {dependance.Name}", TypeMessage.Info);
         }
     }
     catch
     {
         Write("Error for Loade Module", TypeMessage.Error);
     }
 }
示例#13
0
        public static List <string> GetRefs(string file)
        {
            List <string> refs = new List <string>();

            Console.WriteLine(string.Format("[+] Analyzing {0}", file));
            try {
                using (ModuleDefMD mod = ModuleDefMD.Load(file)) {
                    foreach (var reference in mod.GetAssemblyRefs())
                    {
                        refs.Add(reference.Name);
                    }
                }
            }
            catch (IOException e) {
                Console.WriteLine(string.Format("[-] Failed to analyze {0}, file not found", file));
            }
            catch (BadImageFormatException e) {
                Console.WriteLine(string.Format("[-] Failed to analyze {0}, bad image format", file));
            }

            return(refs);
        }
示例#14
0
        public static void LoadAsmRef()
        {
            var asmResolver = new AssemblyResolver();
            var modCtx      = new ModuleContext(asmResolver);

            asmResolver.DefaultModuleContext = modCtx;
            asmResolver.EnableTypeDefCache   = true;

            module.Location = filename;
            var asmRefs = module.GetAssemblyRefs().ToList();

            module.Context = modCtx;
            foreach (var asmRef in asmRefs)
            {
                if (asmRef == null)
                {
                    continue;
                }
                var asma = asmResolver.Resolve(asmRef.FullName, module);
                //	Protections.Protections.ModuleDef.Context.AssemblyResolver.AddToCache(asma);
                ((AssemblyResolver)module.Context.AssemblyResolver).AddToCache(asma);
            }
        }
示例#15
0
            private static AssemblyRef GetCallingConventionAssemblyRefForNetCore(ModuleDefMD module, string callingConventionAssemblyName)
            {
                var numAsmRefs = module.TablesStream.AssemblyRefTable.Rows;

                foreach (var assemblyRef in module.GetAssemblyRefs())
                {
                    if (assemblyRef is null)
                    {
                        continue;
                    }

                    if (assemblyRef.Name == callingConventionAssemblyName)
                    {
                        return(assemblyRef);
                    }
                }

                var compilerServicesAssembly = new AssemblyRefUser(module.Context.AssemblyResolver.ResolveThrow(new AssemblyRefUser(callingConventionAssemblyName), module));

                module.UpdateRowId(compilerServicesAssembly);

                return(compilerServicesAssembly);
            }
示例#16
0
        public static void Main(string[] args)
        {
            string path = "../Release/CILExamining.exe";

            ModuleDefMD      m  = ModuleDefMD.Load(path);
            AssemblyResolver ar = new AssemblyResolver();
            ModuleContext    mc = new ModuleContext(ar);

            foreach (AssemblyRef assemblyRef in m.GetAssemblyRefs())
            {
                ar.ResolveThrow(assemblyRef, m);
            }
            ar.PostSearchPaths.Add(path);

            m.Context = mc;

            Obfuscations.Utilities.RenameUtility ru = new Obfuscations.Utilities.RenameUtility();

            new Obfuscations.ReferenceProxyObfuscation(ru.Random).Execute(m);
            //new Obfuscations.RenameObfuscation(ru).Execute(m);
            //new Obfuscations.JunkObfuscation(ru).Execute(m);

            m.Write(path + ".o");
        }
示例#17
0
        private static void Main(string[] args)
        {
            Console.WriteLine("Name of Executable to Unpack : ");
            var path = Console.ReadLine();

            if (path == string.Empty)
            {
                return;
            }
            if (path != null && path.StartsWith("\"") && path[path.Length - 1] == '"')
            {
                path = path.Substring(1, path.Length - 2);
            }

            if (!File.Exists(path))
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("[!] File not found");
                Console.WriteLine("[!] Press key to exit...");
                Console.Read();
                return;
            }
            Console.WriteLine("Babel Unpacker running..");
            ModuleDefMD      moduleDefMD      = ModuleDefMD.Load(path);
            AssemblyResolver assemblyResolver = new AssemblyResolver();
            ModuleContext    moduleContext    = new ModuleContext(assemblyResolver);

            assemblyResolver.DefaultModuleContext = moduleContext;
            assemblyResolver.EnableTypeDefCache   = true;
            moduleDefMD.Location = path;
            List <AssemblyRef> list = moduleDefMD.GetAssemblyRefs().ToList <AssemblyRef>();

            moduleDefMD.Context = moduleContext;
            foreach (AssemblyRef assemblyRef in list)
            {
                if (assemblyRef != null)
                {
                    AssemblyDef assemblyDef = assemblyResolver.Resolve(assemblyRef.FullName, moduleDefMD);
                    moduleDefMD.Context.AssemblyResolver.AddToCache(assemblyDef);
                }
            }
            Program.asm = Assembly.LoadFrom(path);
            De4Dot.Cflow(moduleDefMD);
            VMDecryptor.run(moduleDefMD, Program.asm);
            Delegates.CleanDelegates(moduleDefMD);
            Ints.CleanInts(moduleDefMD);
            Ints.CleanFloats(moduleDefMD);
            Ints.CleanDouble(moduleDefMD);
            Strings.CleanStringMethodOne(moduleDefMD);
            Strings.CleanStringMethodTwo(moduleDefMD);
            De4Dot.Cflow(moduleDefMD);
            Ints.CleanInts(moduleDefMD);
            Ints.CleanFloats(moduleDefMD);
            Ints.CleanDouble(moduleDefMD);
            Strings.CleanStringMethodOne(moduleDefMD);
            Strings.CleanStringMethodTwo(moduleDefMD);
            De4Dot.Cflow(moduleDefMD);
            AntiTamper.AntiTamp(moduleDefMD);
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("Unpack Complete !");
            moduleDefMD.Write("cleaned_" + path, new ModuleWriterOptions(moduleDefMD));
        }
示例#18
0
        private static void Remove(ModuleDefMD md, StrongNameKey key = null, bool checkBaml = false, int floor = 0)
        {
            //if (WhiteList.Contains(md.Assembly.Name))
            //{
            //    Log($"{md.Assembly.Name} is in WhiteList! It will keep its sign.");
            //}
            bool      isResign = key != null;
            PublicKey pk       = null;

            if (isResign)
            {
                pk = new PublicKey(key.PublicKey);
            }
            string operation = isResign ? "Resigning" : "Removing";

            Log($"{"".PadLeft(floor, PaddingChar)}{operation} StrongName for assembly [{md.Name}] ...");
            md.IsStrongNameSigned = isResign;
            if (!isResign)
            {
                //if (md.Assembly.PublicKeyToken != null)
                //{
                //    md.Assembly.PublicKeyToken.Data = null;
                //}
                if (md.Assembly.PublicKey != null)
                {
                    md.Assembly.PublicKey = null;
                }
                md.Assembly.HasPublicKey = false;
            }

            HandleDic[md.Assembly.Name] = true;

            if (checkBaml)
            {
                BamlProject b = new BamlProject(md);
                b.RemoveRefKeyToken(CurrentPublicKeyToken, pk?.Token.ToString() ?? "null");
                if (b.BamlFiles.Count > 0)
                {
                    Log($"{"".PadLeft(floor, PaddingChar)}{operation} StrongName for BAMLs in [{md.Name}] ...");
                }
                b.ProcessForRef();
            }
            var attrs = md.Assembly.CustomAttributes.FindAll(InternalInvisibleAttr);

            if (attrs.Any())
            {
                Log($"{"".PadLeft(floor, PaddingChar)}{operation} StrongName for Attributes in [{md.Name}] ...");
            }
            foreach (var attr in attrs)
            {
                var s = (UTF8String)attr.ConstructorArguments[0].Value;
                if (s.Contains("PublicKey=" + CurrentPublicKey))
                {
                    var arg = attr.ConstructorArguments[0];
                    arg.Value = s.Remove(s.IndexOf(","));
                    var name = arg.Value.ToString();
                    if (isResign)
                    {
                        arg.Value += $", {pk.ToString()}";
                    }
                    attr.ConstructorArguments[0] = arg;

                    //Remove InternalVisible
                    if (HandleDic.ContainsKey(name) && HandleDic[name])
                    {
                        continue;
                    }
                    var p = Path.Combine(CurrentPath, name + ".dll");
                    if (!File.Exists(p))
                    {
                        p = Path.Combine(CurrentPath, name + ".exe");
                    }
                    if (File.Exists(p))
                    {
                        try
                        {
                            Remove(ModuleDefMD.Load(p), key, checkBaml, floor + 1);
                        }
                        catch (Exception ex)
                        {
                            Log(ex.ToString());
                        }
                    }
                }
            }
            //Remove AssemblyRef
            Log($"{"".PadLeft(floor, PaddingChar)}{operation} StrongName for AssemblyRefs in [{md.Name}] ...");
            foreach (var asmref in md.GetAssemblyRefs())
            {
                if (asmref.PublicKeyOrToken.Token.ToString() == CurrentPublicKeyToken)
                {
                    var p = Path.Combine(CurrentPath, asmref.Name + ".dll");
                    if (!File.Exists(p))
                    {
                        p = Path.Combine(CurrentPath, asmref.Name + ".exe");
                    }
                    if (File.Exists(p))
                    {
                        if (!isResign)
                        {
                            //if (asmref.PublicKeyOrToken != null)
                            //{
                            //    asmref.PublicKeyOrToken = null;
                            //}
                            asmref.HasPublicKey = false;
                        }
                        else
                        {
                            asmref.PublicKeyOrToken = pk.Token;
                            asmref.HasPublicKey     = false;
                        }

                        if (HandleDic.ContainsKey(asmref.Name) && HandleDic[asmref.Name])
                        {
                            continue;
                        }

                        try
                        {
                            Remove(ModuleDefMD.Load(p), key, checkBaml, floor + 1);
                        }
                        catch (Exception ex)
                        {
                            Log(ex.ToString());
                        }
                    }
                }
            }
            Log($"{"".PadLeft(floor, PaddingChar)}Saving [{md.Name}] ...");
            if (isResign)
            {
                if (md.IsILOnly)
                {
                    ModuleWriterOptions option = new ModuleWriterOptions(md);
                    option.InitializeStrongNameSigning(md, key);
                    option.ShareMethodBodies = false;
                    md.Write(Path.Combine(SavePath, md.Name), option);
                }
                else
                {
                    NativeModuleWriterOptions option = new NativeModuleWriterOptions(md, false);
                    option.InitializeStrongNameSigning(md, key);
                    md.NativeWrite(Path.Combine(SavePath, md.Name), option);
                }
            }
            else
            {
                if (md.IsILOnly)
                {
                    md.Write(Path.Combine(SavePath, md.Name));
                }
                else
                {
                    md.NativeWrite(Path.Combine(SavePath, md.Name));
                }
            }
        }
示例#19
0
        public void Run()
        {
            // Create a default assembly resolver and type resolver and pass it to Load().
            // If it's a .NET Core assembly, you'll need to disable GAC loading and add
            // .NET Core reference assembly search paths.
            ModuleContext modCtx = ModuleDef.CreateModuleContext();

            IAssemblyResolver resolver = new CustomAssemblyResolver(references);

            modCtx.AssemblyResolver = resolver;

            module = ModuleDefMD.Load(inputFileName, modCtx);
            Importer importer = new Importer(module);

            var instantiateComponentMethod = (from t in module.GetTypes()
                                              where t.Name == "ComponentFactory"
                                              from m in t.Methods
                                              where m.Name == "InstantiateComponent"
                                              select m).Single();

            var assembly = resolver.Resolve(module.GetAssemblyRefs().FirstOrDefault(x => x.Name == "Microsoft.Extensions.DependencyInjection.Abstractions"), module);

            var getServiceMethod = (from t in assembly.ManifestModule.GetTypes()
                                    where t.Name == "ActivatorUtilities"
                                    from m in t.Methods
                                    where m.Name == "GetServiceOrCreateInstance" &&
                                    !m.HasGenericParameters
                                    select m).Single();

            var firstCall = instantiateComponentMethod.Body.Instructions.First(x => x.OpCode == OpCodes.Call);

            instantiateComponentMethod.Body.Instructions.Insert(0, OpCodes.Ldarg_1.ToInstruction());
            firstCall.Operand = importer.Import(getServiceMethod);



            if (module.IsILOnly)
            {
                // Create writer options
                var opts = new ModuleWriterOptions(module);

                // Open or create the strong name key
                var signatureKey = new StrongNameKey(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Key.snk"));

                // This method will initialize the required properties
                opts.InitializeStrongNameSigning(module, signatureKey);

                module.Write(outputFileName, opts);
            }
            else
            {
                // Create writer options
                var opts = new NativeModuleWriterOptions(module, false);

                // Open or create the strong name key
                var signatureKey = new StrongNameKey(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Key.snk"));

                // This method will initialize the required properties
                opts.InitializeStrongNameSigning(module, signatureKey);

                module.NativeWrite(outputFileName, opts);
            }
        }
        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();
        }
        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);
        }
示例#22
0
        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();
        }