Exemplo n.º 1
0
        private static void CreateAssembly(string assembly, Bitness bitness, Action <ModuleDefMD> modifyAction = null)
        {
            var creationOptions = new ModuleCreationOptions
            {
                Context = ModuleDef.CreateModuleContext(),
                TryToLoadPdbFromDisk = true
            };

            using var module = ModuleDefMD.Load(assembly, creationOptions);

            ChangeBitness(module, bitness);

            modifyAction?.Invoke(module);

            DisableEditAndContinueForModule(module);

            var path         = Path.GetDirectoryName(module.Location);
            var filename     = Path.GetFileNameWithoutExtension(module.Location);
            var extension    = Path.GetExtension(module.Location);
            var saveFilename = $"{filename}.{bitness}{extension}";

            module.Name = saveFilename;

            var moduleWriterOptions = new ModuleWriterOptions(module)
            {
                AddCheckSum = true,
                WritePdb    = true
            };
            var moduleWriter = new ModuleWriter(module, moduleWriterOptions);

            ReplaceMSCOREEReferenceWithIJWHostForNetCoreApp(module, moduleWriter);

            moduleWriter.Write(Path.Combine(path, saveFilename));
        }
Exemplo n.º 2
0
        public static AssemblyPublicInterface Load(byte[] assemblyBytes)
        {
            var modCtx = ModuleDef.CreateModuleContext();
            var module = ModuleDefMD.Load(assemblyBytes, modCtx);

            return(BuildAssemblyPublicInterface(module));
        }
Exemplo n.º 3
0
        public static void main_poly(string username, int tn)
        {
            ModuleContext mod_ctx = ModuleDef.CreateModuleContext();
            ModuleDefMD   module  = ModuleDefMD.Load(@"ldr_base.exe", mod_ctx);

            if (module == null)
            {
                Console.WriteLine("module is null (HOW??)");
                return;
            }

            Console.WriteLine("tn[{1}] - got module for username {0}", username, tn);

            /*
             * big credits to: https://blog.syscall.party/post/writing-a-simple-net-deobfuscator/
             * idea and some functions from ^
             */

            polymorphic.set_username(username);

            foreach (var type in module.GetTypes())
            {
                //this gives us classes, functions, functions body, etc
                polymorphic.modify_strings(type);
            }
            polymorphic.finish_write(module, username, tn);
        }
Exemplo n.º 4
0
        /// <summary>
        /// Strips the IL from the given assembly, leaving only a reference assembly with no executable code.
        /// </summary>
        private static void StripAssembly(string filePath)
        {
            Console.WriteLine($"Stripping Assembly: {Path.GetFileName(filePath)}");

            ModuleContext context = ModuleDef.CreateModuleContext();
            ModuleDefMD   module  = ModuleDefMD.Load(filePath, context);

            foreach (TypeDef type in module.Types)
            {
                StripType(type);
            }

            // HACK: What if we need to reference embedded resources like localized strings?  Can we empty just the resource CONTENTS?
            module.Resources?.Clear();

            string outPath = Path.Combine(Path.GetDirectoryName(filePath), "Stripped", Path.GetFileName(filePath));

            Directory.CreateDirectory(Path.GetDirectoryName(outPath));

            if (module.IsILOnly)
            {
                module.Write(outPath, new ModuleWriterOptions(module)
                {
                    ShareMethodBodies = true
                });
            }
            else
            {
                // Mixed Mode Assembly
                module.NativeWrite(outPath, new NativeModuleWriterOptions(module, optimizeImageSize: true)
                {
                    ShareMethodBodies = true
                });
            }
        }
Exemplo n.º 5
0
        public void Compile(string inputFilePath, string outputFilePath)
        {
            ModuleContext modCtx = ModuleDef.CreateModuleContext();

            var corlibFilePath = _configuration.CorelibPath;

            if (string.IsNullOrEmpty(corlibFilePath))
            {
                var inputDirectoryName = Path.GetDirectoryName(inputFilePath);
                if (inputDirectoryName != null)
                {
                    corlibFilePath = Path.Combine(inputDirectoryName, "System.Private.CoreLib.dll");
                }
            }
            ModuleDefMD corlibModule      = ModuleDefMD.Load(corlibFilePath, modCtx);
            var         corlibAssemblyRef = corlibModule.Assembly.ToAssemblyRef();

            var options = new ModuleCreationOptions(modCtx)
            {
                CorLibAssemblyRef = corlibAssemblyRef
            };

            ModuleDefMD module = ModuleDefMD.Load(inputFilePath, options);

            var typesToCompile = new List <TypeDef>();

            typesToCompile.AddRange(corlibModule.Types);
            typesToCompile.AddRange(module.Types);

            var rootNode = _typeDependencyAnalyser.AnalyseDependencies(typesToCompile, module.EntryPoint);

            CompileNode(rootNode);

            _z80Writer.OutputCode(rootNode, inputFilePath, outputFilePath);
        }
Exemplo n.º 6
0
        static void Main(string[] args)
        {
            while (true)
            {
                Console.Clear();

                string modulePath = "";
                int    proxyDepth = 0;

                try
                {
                    modulePath = args[0];
                }
                catch (IndexOutOfRangeException)
                {
                    Console.WriteLine("Error : no module selected... press ENTER to exit.");
                    Console.ReadLine();
                    Environment.Exit(0);
                }

                Console.Write("Proxy depth : ");
                int.TryParse(Console.ReadLine(), out proxyDepth);

                if (proxyDepth < 1)
                {
                    Console.WriteLine("Invalid proxy depth (should be greater than 1)");
                    Thread.Sleep(700);
                    continue;
                }

                Console.Clear();

                ModuleContext modCtx = ModuleDef.CreateModuleContext();
                ModuleDefMD   module = ModuleDefMD.Load(modulePath, modCtx);

                var myProxyRemover = new ProxyRemover(module, modulePath);
                int removedProxies = myProxyRemover.RemoveProxiesFromTypes(module.Types, proxyDepth);

                if (removedProxies > 0)
                {
                    Console.WriteLine();
                }
                Console.WriteLine(removedProxies + " proxies removed");
                Console.WriteLine();

                if (removedProxies > 0)
                {
                    Console.WriteLine("Saving module...");
                    myProxyRemover.SaveModule();
                }


                Console.WriteLine("Done.");
                Console.ReadLine();
                break;
            }
        }
        static TypeExtensions()
        {
            var module    = typeof(TypeExtensions).Module;
            var context   = ModuleDef.CreateModuleContext();
            var moduleDef = ModuleDefMD.Load(module, context);

            _types = moduleDef.Types.ToList();
            var nestedTypes = _types.SelectMany(t => t.NestedTypes ?? Enumerable.Empty <TypeDef>()).ToList();

            _types.AddRange(nestedTypes);
        }
Exemplo n.º 8
0
        public void Run()
        {
            ModuleContext context = ModuleDef.CreateModuleContext();
            ModuleDefMD   module  = ModuleDefMD.Load(opts.InputAssemblyPath, context);

            foreach (IDeobfuscationPass pass in passes)
            {
                pass.Run(module, opts);
            }

            module.Write(opts.OutputAssemblyPath);
        }
Exemplo n.º 9
0
        public static MonoDecompiler FromFile(string path)
        {
            if (!File.Exists(path))
            {
                return(null);
            }

            ModuleContext modCtx = ModuleDef.CreateModuleContext();
            ModuleDefMD   module = ModuleDefMD.Load(path, modCtx);

            return(new MonoDecompiler(module));
        }
Exemplo n.º 10
0
        private void LoadModuleCatalog()
        {
            if (!ModulesDirectory.Exists)
            {
                throw new InvalidOperationException($"Directory {ModulesDirectory} could not be found.");
            }

            var loadedAssemblies = GetLoadedAssemblies();
            Log.Debug($"Loaded assembly list:\n\t{loadedAssemblies.Select(x => new {x.FullName, x.Location}).DumpToTable()}");

            var existingModules = moduleCatalog.Modules.ToArray();
            Log.Debug(
                $"Default Modules list:\n\t{existingModules.Select(x => new {x.ModuleName, x.ModuleType, x.Ref, x.State, x.InitializationMode, x.DependsOn}).DumpToTable()}");

            var potentialModules = (
                from dllFile in ModulesDirectory.GetFiles("*.dll")
                let loadedModules = loadedAssemblies.Where(x => !string.IsNullOrEmpty(x.Location))
                    .Select(x => new FileInfo(x.Location))
                    .Where(x => x.Exists)
                    .ToArray()
                where !loadedModules.Contains(dllFile)
                let moduleContext = ModuleDef.CreateModuleContext()
                let dllFileData = File.ReadAllBytes(dllFile.FullName)
                let module = LoadModuleSafe(dllFileData, moduleContext, dllFile.FullName)
                where module != null
                select new {module, dllFile}).ToArray();

            var discoveredModules = (
                from item in potentialModules
                from prismBootstrapper in GetPrismBootstrapperTypes(item.module)
                select new {item.dllFile, item.module, prismBootstrapper}).ToArray();

            Log.Debug(
                $"Discovered {discoveredModules.Length} modules:\n\t{discoveredModules.Select(x => new {x.dllFile.FullName, x.module.Metadata.VersionString, x.prismBootstrapper.AssemblyQualifiedName}).DumpToTable()}");
            
            foreach (var module in discoveredModules)
            {
                Log.Debug($"Loading modules from file {module.dllFile}");
                if (AppArguments.Instance.IsLazyMode)
                {
                    var moduleInfo = PrepareLocalModuleInfo(module.prismBootstrapper, module.dllFile);
                    Log.Debug($"LazyMode is enabled, adding ModuleInfo: {moduleInfo}");
                    moduleCatalog.AddModule(moduleInfo);
                }
                else
                {
                    var assemblyBytes = File.ReadAllBytes(module.dllFile.FullName);
                    LoadModulesFromBytes(assemblyBytes);
                }
            }
        }
Exemplo n.º 11
0
        static void ParseModule(string moduleFile)
        {
            ModuleContext modCtx = ModuleDef.CreateModuleContext();

            currentModule = ModuleDefMD.Load(moduleFile, modCtx);

            string moduleOutput = OUTPUT_DIR + "\\" + currentModule.Name;

            if (!Directory.Exists(moduleOutput))
            {
                Directory.CreateDirectory(moduleOutput);
            }

            ParseClasses();
        }
Exemplo n.º 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);
     }
     catch
     {
         Write("Error for Loade Module", TypeMessage.Error);
     }
 }
Exemplo n.º 13
0
 // Token: 0x06000067 RID: 103 RVA: 0x00006AB0 File Offset: 0x00004CB0
 public static void LoadModule(string filename)
 {
     try
     {
         context.FileName = filename;
         byte[]        data    = File.ReadAllBytes(filename);
         ModuleContext context = ModuleDef.CreateModuleContext();
         context.module = ModuleDefMD.Load(data, context);
         foreach (AssemblyRef assemblyRef in context.module.GetAssemblyRefs())
         {
         }
     }
     catch
     {
     }
 }
Exemplo n.º 14
0
        public static void Main(string[] args)
        {
            var ctx = ModuleDef.CreateModuleContext();
            //var module = ModuleDefMD.Load("/Users/mustafa/Work/digitoygames/digiplay-net/OkeyExtra/iOS/bin/iPhone/Debug/OkeyExtra.exe", ctx);
            //var module = ModuleDefMD.Load("/Users/mustafa/Projects/csharp/bin/Debug/csharp.exe", ctx);
            var         module      = ModuleDefMD.Load("/Users/mustafa/Work/digitoygames/digiplay-net/GinRummyExtra/Android/bin/Debug/GinRummyExtra.dll", ctx);
            CorLibTypes corLibTypes = new CorLibTypes(module);

            CPP(module);
            return;

            var buffer = new StringBuilder();

            foreach (var type in module.GetTypes())
            {
                //if (!type.FullName.StartsWith("Test")) continue;

                buffer.Append("Type=" + type.FullName);
                if (type.GenericParameters != null)
                {
                    foreach (var g in type.GenericParameters)
                    {
                        buffer.Append(" Gen=" + g.FullName);
                    }
                }
                buffer.Append("\n");
                foreach (var f in type.Fields)
                {
                    buffer.Append("  field:" + f.Name + " " + f.FieldType + "\n");
                }
                Test(module, type, corLibTypes, buffer);

                if (type.NestedTypes != null)
                {
                    foreach (var nt in type.NestedTypes)
                    {
                        buffer.Append("Type=" + nt.FullName + "\n");
                        foreach (var f in nt.Fields)
                        {
                            buffer.Append("  field:" + f.Name + " " + f.FieldType + "\n");
                        }
                        Test(module, nt, corLibTypes, buffer);
                    }
                }
            }
            System.IO.File.WriteAllText("il.txt", buffer.ToString());
        }
Exemplo n.º 15
0
        /// <summary>
        /// Hotloads an assembly. Redirects to <see cref="Assembly.Load(byte[])"/> if <see cref="Enabled"/> is set to false.
        /// </summary>
        /// <param name="assemblyData">The assembly to hotload.</param>
        /// <returns>The loaded assembly.</returns>
        public static Assembly LoadAssembly(byte[] assemblyData)
        {
            if (!Enabled)
            {
                return(Assembly.Load(assemblyData));
            }

            using var input  = new MemoryStream(assemblyData, writable: false);
            using var output = new MemoryStream();

            var modCtx = ModuleDef.CreateModuleContext();
            var module = ModuleDefMD.Load(input, modCtx);

            var isMono        = Type.GetType("Mono.Runtime") != null;
            var isStrongNamed = module.Assembly.PublicKey != null;

            if (!isMono && isStrongNamed)
            {
                // Don't hotload strong-named assemblies unless mono
                // Will cause FileLoadException's if not mono
                return(Assembly.Load(assemblyData));
            }

            var realFullname = module.Assembly.FullName;

            if (s_Assemblies.ContainsKey(realFullname))
            {
                s_Assemblies.Remove(realFullname);
            }

            var guid = Guid.NewGuid().ToString().Replace("-", "").Substring(0, 6);
            var name = $"{module.Assembly.Name}-{guid}";

            module.Assembly.Name         = name;
            module.Assembly.PublicKey    = null;
            module.Assembly.HasPublicKey = false;

            module.Write(output);
            output.Seek(offset: 0, SeekOrigin.Begin);

            var newAssemblyData = output.ToArray();
            var assembly        = Assembly.Load(newAssemblyData);

            s_Assemblies.Add(realFullname, assembly);
            return(assembly);
        }
Exemplo n.º 16
0
        static void ParseModule(string moduleFile)
        {
            Console.WriteLine("Generating SDK for {0}...", Path.GetFileName(moduleFile));

            ModuleContext modCtx = ModuleDef.CreateModuleContext();

            currentModule = ModuleDefMD.Load(moduleFile, modCtx);

            string moduleOutput = OUTPUT_DIR + "\\" + currentModule.Name;

            if (!Directory.Exists(moduleOutput))
            {
                Directory.CreateDirectory(moduleOutput);
            }

            ParseClasses();
        }
Exemplo n.º 17
0
        private static void Main(string[] args)
        {
            // Parse commands
            Parser.Default.ParseArguments <Options>(args).WithParsed(_opts => Arguments = _opts);
            if (Arguments == null)
            {
                Console.ReadKey();
                return;
            }
            if (!Directory.Exists(Arguments.Il2cppDumpFiles) || File.Exists(Arguments.Il2cppDumpFiles + "/il2cpp.h"))
            {
                Parser.Default.ParseArguments <Options>(Array.Empty <string>()).WithParsed(_opts => Arguments = _opts);
                Console.ReadKey();
                return;
            }
            string[]      a           = Directory.GetFiles(Arguments.Il2cppDumpFiles);
            ModuleContext modCtx      = ModuleDef.CreateModuleContext();
            var           asmResolver = (AssemblyResolver)modCtx.AssemblyResolver;

            ModuleDefMD[] modules = a.Select(p => ModuleDefMD.Load(p, modCtx)).ToArray();
            //modules = modules.OrderByDescending(x => x.Assembly.Name == "System");
            foreach (var dll in modules)
            {
                asmResolver.AddToCache(dll);
            }
            var typeRefs = new Dictionary <string, List <TypeRef> >();

            foreach (var module in modules)
            {
                foreach (var typeRef in module.GetTypeRefs())
                {
                    var tf = typeRef.ResolveTypeDef();
                    if (tf != null)
                    {
                        if (!typeRefs.TryGetValue($"{typeRef.DefinitionAssembly.Name}_{tf.FullName}", out var l))
                        {
                            l = new List <TypeRef>();
                            typeRefs.Add($"{typeRef.DefinitionAssembly.Name}_{tf.FullName}", l);
                        }
                        l.Add(typeRef);
                    }
                }
            }
            foreach (var module in modules)
            {
        protected void PerformFieldCheck <TRef, TLocal>(params string[] expectedMessages)
        {
            var data   = File.ReadAllBytes(typeof(TRef).Assembly.Location);
            var modCtx = ModuleDef.CreateModuleContext();
            var module = ModuleDefMD.Load(data, modCtx);

            var refDef   = module.GetTypes().Single(td => td.AssemblyQualifiedName == typeof(TRef).AssemblyQualifiedName);
            var localDef = module.GetTypes().Single(td => td.AssemblyQualifiedName == typeof(TLocal).AssemblyQualifiedName);

            var actualMessages = new List <string>();

            foreach (IVersionRuleRunner runner in _integrationFixture.RuleRunners)
            {
                actualMessages.AddRange(runner.Analyze(refDef, localDef).Select(c => c.Message));
            }

            AssertContentEqual(expectedMessages, actualMessages);
        }
Exemplo n.º 19
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);
     }
 }
Exemplo n.º 20
0
        public DnSpyDecompiler()
        {
            this.files                = new List <string>();
            this.asmPaths             = new List <string>();
            this.userGacPaths         = new List <string>();
            this.gacFiles             = new List <string>();
            this.decompilationContext = new DecompilationContext();
            this.moduleContext        = ModuleDef.CreateModuleContext(true);
            this.assemblyResolver     = (AssemblyResolver)moduleContext.AssemblyResolver;
            this.assemblyResolver.EnableTypeDefCache = true;
            this.bamlDecompiler  = TryLoadBamlDecompiler();
            this.decompileBaml   = bamlDecompiler != null;
            this.reservedOptions = GetReservedOptions();

            var langs = new List <ILanguage>();

            langs.AddRange(GetAllLanguages());
            langs.Sort((a, b) => a.OrderUI.CompareTo(b.OrderUI));
            this.allLanguages = langs.ToArray();
        }
Exemplo n.º 21
0
        public void CreateMod()
        {
            ModuleContext modCtx         = ModuleDef.CreateModuleContext();
            ModuleDefMD   moddedModule   = ModuleDefMD.Load(moddedAssembly, modCtx);
            ModuleDefMD   originalModule = ModuleDefMD.Load(originalAssembly, modCtx);

            #region QuickAndDirtyRemoveLater

            var changedMethods = GetChangedMethods(moddedModule, originalModule);

            var output = "";

            foreach (var method in changedMethods)
            {
                output += method.FullName + "\n";
            }

            var addedTypesAndMethods = GetAddedTypesAndMethods(moddedModule, originalModule);

            output += "\n\nADDED TYPES: \n\n";

            foreach (var addedType in addedTypesAndMethods.Item1)
            {
                output += addedType.FullName + "\n";
            }

            output += "\n\nADDED METHODS: \n\n";

            foreach (var addedMethod in addedTypesAndMethods.Item2)
            {
                output += addedMethod.FullName + "\n";
            }

            File.WriteAllText(outFile, output);

            #endregion

            var save = CreateSave(moddedModule, originalModule);
            var json = JsonConvert.SerializeObject(save, Formatting.Indented);
            File.WriteAllText(outFile, json);
        }
Exemplo n.º 22
0
        IEnumerable <TypeDef> GetInjectedTypes()
        {
            var ev   = new NetfuserEvent.InjectTypes(this);
            var mods = new ConcurrentDictionary <Assembly, ModuleDef>();

            Fire(ev);
            if (ev.Types.Count == 0 && ev.TypeDefs.Count == 0)
            {
                return(Empty.Array <TypeDef>());
            }
            var ctx = ModuleDef.CreateModuleContext();

            foreach (var t in ev.Types)
            {
                var mod = mods.GetOrAdd(t.Assembly, a => ModuleDefMD.Load(a.Location, ctx));
                var imp = new Importer(mod, ImporterOptions.TryToUseDefs);
                var tr  = imp.Import(t);
                ev.TypeDefs.Add(tr.ResolveTypeDefThrow());
            }

            return(ev.TypeDefs);
        }
Exemplo n.º 23
0
        static void Main(string[] args)
        {
            #region Read a .NET module from a file:
            // 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();
            ModuleDefMD   module = ModuleDefMD.Load(MYEXE, modCtx);
            #endregion


            //#region Write PDB files
            //// Create a default assembly resolver and type resolver
            ////ModuleContext modCtx = ModuleDef.CreateModuleContext();
            //var mod = ModuleDefMD.Load(MYEXE, modCtx);
            //// ...
            //var wopts = new dnlib.DotNet.Writer.ModuleWriterOptions(mod);
            //wopts.WritePdb = true;
            //wopts.PdbFileName = @"out.pdb";	// Set other file name
            //mod.Write(@"out.dll", wopts);
            //#endregion
        }
Exemplo n.º 24
0
        public void LoadMods(List <Mod> mods)
        {
            ModuleContext modCtx         = ModuleDef.CreateModuleContext();
            ModuleDefMD   originalModule = ModuleDefMD.Load(originalAssembly, modCtx);

            // Restore Original
            originalModule.Write(output);

            mods.ForEach(mod =>
            {
                if (mod.Active)
                {
                    var jsonString = File.ReadAllText(mod.Path);
                    Save save      = JsonConvert.DeserializeObject <Save>(jsonString);

                    InjectNewClasses(save, originalModule);

                    InjectModdedMethods(save, originalModule);

                    originalModule.Write(output);
                }
            });
        }
Exemplo n.º 25
0
        public static Assembly LoadAssembly(byte[] assemblyData)
        {
            if (!Enabled)
            {
                return(Assembly.Load(assemblyData));
            }

            using var input  = new MemoryStream(assemblyData, writable: false);
            using var output = new MemoryStream();

            var modCtx = ModuleDef.CreateModuleContext();
            var module = ModuleDefMD.Load(input, modCtx);

            var realFullname = module.Assembly.FullName;

            if (s_Assemblies.ContainsKey(realFullname))
            {
                s_Assemblies.Remove(realFullname);
            }

            var guid = Guid.NewGuid().ToString().Replace("-", "").Substring(0, 6);
            var name = $"{module.Assembly.Name}-{guid}";

            module.Assembly.Name         = name;
            module.Assembly.PublicKey    = null;
            module.Assembly.HasPublicKey = false;

            module.Write(output);
            output.Seek(offset: 0, SeekOrigin.Begin);

            var newAssemblyData = output.ToArray();
            var assembly        = Assembly.Load(newAssemblyData);

            s_Assemblies.Add(realFullname, assembly);
            return(assembly);
        }
Exemplo n.º 26
0
        private static void Main(string[] args)
        {
            try
            {
                string path;

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

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

                ModuleDefMD module = ModuleDefMD.Load(path);

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

                Console.WriteLine($"Loaded {module.Name}");

                Console.WriteLine("Resolving References...");

                module.Context = ModuleDef.CreateModuleContext();

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

                Console.WriteLine("Injecting the Bootstrap Class.");

                ModuleDefMD bootstrap = ModuleDefMD.Load(Path.Combine(Directory.GetCurrentDirectory(), "Exiled.Bootstrap.dll"));

                Console.WriteLine("Loaded " + bootstrap.Name);

                TypeDef modClass = bootstrap.Types[0];

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

                var modRefType = modClass;

                bootstrap.Types.Remove(modClass);

                modRefType.DeclaringType = null;

                module.Types.Add(modRefType);

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

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

                Console.WriteLine("Injected!");
                Console.WriteLine("Injection completed!");
                Console.WriteLine("Patching code...");

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

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

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

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

                module.Write(Path.Combine(Path.GetDirectoryName(Path.GetFullPath(path)), "Assembly-CSharp-Exiled.dll"));

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

            Console.Read();
        }
Exemplo n.º 27
0
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            var           time   = DateTime.Now.ToString("hh:mm:ss");
            ModuleContext modCtx = ModuleDef.CreateModuleContext();
            var           module = ModuleDefMD.Load(Program.Text, modCtx);

            ConsoleLog.Foreground = Brushes.Black;
            ConsoleLog.AppendText($"{time} Starting obfuscation{Environment.NewLine}");

            if (String_Encryption.IsChecked == true)
            {
                StringEncPhase.Execute(module);
                ConsoleLog.AppendText($"{time} Processing string encryption{Environment.NewLine}");
            }

            if (Online_Decryption.IsChecked == true)
            {
                OnlinePhase.Execute(module);
                ConsoleLog.AppendText($"{time} Processing online decryption{Environment.NewLine}");
            }

            if (Cflow.IsChecked == true)
            {
                ControlFlowObfuscation.Execute(module);
                ConsoleLog.AppendText($"{time} Processing control flow{Environment.NewLine}");
            }

            if (IntConf.IsChecked == true)
            {
                AddIntPhase.Execute2(module);
                ConsoleLog.AppendText($"{time} Processing integer confusion{Environment.NewLine}");
            }

            if (SUC.IsChecked == true)
            {
                StackUnfConfusion.Execute(module);
                ConsoleLog.AppendText($"{time} Processing stack confusion{Environment.NewLine}");
            }

            if (Ahri.IsChecked == true)
            {
                Arithmetic.Execute(module);
                ConsoleLog.AppendText($"{time} Processing math calculations{Environment.NewLine}");
            }

            if (LF.IsChecked == true)
            {
                L2F.Execute(module);
                ConsoleLog.AppendText($"{time} Processing constant fields{Environment.NewLine}");
            }

            if (LFV2.IsChecked == true)
            {
                L2FV2.Execute(module);
                ConsoleLog.AppendText($"{time} Processing local fields{Environment.NewLine}");
            }

            if (Calli_.IsChecked == true)
            {
                Calli.Execute(module);
                ConsoleLog.AppendText($"{time} Processing calli conversion{Environment.NewLine}");
            }

            if (Proxy_String.IsChecked == true)
            {
                ProxyString.Execute(module);
                ConsoleLog.AppendText($"{time} Processing proxy strings{Environment.NewLine}");
            }

            if (ProxyConstants.IsChecked == true)
            {
                ProxyINT.Execute(module);
                ConsoleLog.AppendText($"{time} Processing proxy constants{Environment.NewLine}");
            }

            if (Proxy_Meth.IsChecked == true)
            {
                ProxyMeth.Execute(module);
                ConsoleLog.AppendText($"{time} Processing proxy methods{Environment.NewLine}");
            }

            if (Anti_De4dot.IsChecked == true)
            {
                AntiDecompile.Execute(module.Assembly);
                ConsoleLog.AppendText($"{time} Processing anti-decompile{Environment.NewLine}");
            }

            if (JumpCflow.IsChecked == true)
            {
                JumpCFlow.Execute(module);
                ConsoleLog.AppendText($"{time} Processing flow conversion{Environment.NewLine}");
            }

            if (AntiDebug.IsChecked == true)
            {
                Anti_Debug.Execute(module);
                ConsoleLog.AppendText($"{time} Processing anti-debug{Environment.NewLine}");
            }

            if (Anti_Dump.IsChecked == true)
            {
                AntiDump.Execute(module);
                ConsoleLog.AppendText($"{time} Processing anti-dump{Environment.NewLine}");
            }

            if (AntiTamper.IsChecked == true)
            {
                Protection.Software.AntiTamper.Execute(module);
                ConsoleLog.AppendText($"{time} Processing anti-tamper{Environment.NewLine}");
            }

            if (InvalidMD.IsChecked == true)
            {
                InvalidMDPhase.Execute(module.Assembly);
                ConsoleLog.AppendText($"{time} Processing invalid metadata{Environment.NewLine}");
            }

            var text2 = Path.GetDirectoryName(Program.Text);

            if (text2 != null && !text2.EndsWith("\\"))
            {
                text2 += "\\";
            }

            var path = $"{text2}{Path.GetFileNameWithoutExtension(Program.Text)}_protected{Path.GetExtension(Program.Text)}";

            module.Write(path,
                         new ModuleWriterOptions(module)
            {
                PEHeadersOptions = { NumberOfRvaAndSizes = 13 }, Logger = DummyLogger.NoThrowInstance
            });

            ConsoleLog.AppendText($"{time} File: {path}{Environment.NewLine}{Environment.NewLine}");

            if (AntiTamper.IsChecked == true)
            {
                Protection.Software.AntiTamper.Sha256(path);
            }
        }
Exemplo n.º 28
0
        public static int Main(string[] args)
        {
            if (args.Length < 2)
            {
                return(XConsole.WriteLine("NameMapper.CLI - map names from assembly with deobfuscated names to assembly with obfuscated names\n" +
                                          "by exys, 2019\n" +
                                          "\n" +
                                          "Usage:\n" +
                                          "NameMapper.CLI [clean module] [obfuscated module]"));
            }

            if (!File.Exists(_cleanModulePath = Path.GetFullPath(args[0])))
            {
                return(XConsole.PrintError("Specified clean module path does not exist"));
            }

            if (!File.Exists(_obfModulePath = Path.GetFullPath(args[1])))
            {
                return(XConsole.PrintError("Specified obfuscated module path does not exist"));
            }

            try
            {
                _cleanModule = ModuleDefMD.Load(_cleanModulePath, ModuleDef.CreateModuleContext());
                _obfModule   = ModuleDefMD.Load(_obfModulePath, ModuleDef.CreateModuleContext());
            }
            catch (Exception e) { return(XConsole.PrintError("An error occurred while trying to load and process modules! Details:\n" + e)); }

            XConsole.PrintInfo($"Loaded modules: {_cleanModule.Assembly.FullName} (clean); {_obfModule.Assembly.FullName} (obfuscated).");

            var fancyOut = new ConcurrentQueue <string>();

            // ReSharper disable once FunctionNeverReturns
            ThreadPool.QueueUserWorkItem(state =>
            {
                while (true)
                {
                    if (!fancyOut.IsEmpty && fancyOut.TryDequeue(out string msg))
                    {
                        XConsole.Write(msg);
                    }

                    Thread.Sleep(1);
                }
            });

            NameMapper nameMapper = new NameMapper(_cleanModule, _obfModule, fancyOut);

            nameMapper.BeginProcessing();

            string filename = Path.GetFileNameWithoutExtension(_obfModulePath) + "-nmapped" + Path.GetExtension(_obfModulePath);

            XConsole.PrintInfo("Finally writing module back (with \"-nmapped\" tag)!");

            _obfModule.Write(
                Path.Combine(
                    Path.GetDirectoryName(_obfModulePath) ?? throw new NameMapperCliException("Path to write module to is null unexpectedly"), filename),
                new ModuleWriterOptions(_obfModule)
            {
                MetadataOptions = { Flags = DEFAULT_METADATA_FLAGS }
            });

            Console.ReadKey(true);

            return(0);
        }
Exemplo n.º 29
0
        /// <summary>
        /// This Program is used to compile the Assembly-CSharp.
        ///
        /// For Instruction on how to use this Program please check the readme of this Project.
        /// </summary>
        public static void Main(string[] args)
        {
            if (args.Length != 1)
            {
                Console.WriteLine("Missing File Argument");
                return;
            }

            var module = ModuleDefMD.Load(args[0]);

            if (module == null)
            {
                Console.WriteLine("File Not Found");
                return;
            }

            module.IsILOnly              = true;
            module.VTableFixups          = null;
            module.Assembly.PublicKey    = null;
            module.Assembly.HasPublicKey = false;

            var opts = new ModuleWriterOptions(module);

            Console.WriteLine($"Synapse: Loaded {module.Name}");
            Console.WriteLine("Synapse-Assemble: Resolving Ref..");

            var modCtx      = ModuleDef.CreateModuleContext();
            var asmResolver = (AssemblyResolver)modCtx.AssemblyResolver;

            module.Context = modCtx;

            ((AssemblyResolver)module.Context.AssemblyResolver).AddToCache(module);
            Console.WriteLine("Synapse-Injection: Injection of ModLoader");

            var modLoader = ModuleDefMD.Load("SynapseModLoader.dll");

            Console.WriteLine($"Synapse-Inject: Loaded {modLoader.Name}");

            var modClass = modLoader.Types[0];

            foreach (var type in modLoader.Types)
            {
                if (type.Name != "ModLoader")
                {
                    continue;
                }
                modClass = type;
                Console.WriteLine($"Synapse-Inject: Hooked to: {type.Namespace}.{type.Name}");
            }

            var modRefType = modClass;

            modLoader.Types.Remove(modClass);
            modRefType.DeclaringType = null;
            module.Types.Add(modRefType);

            var call = FindMethod(modRefType, "LoadModSystem");

            if (call == null)
            {
                Console.WriteLine("Failed to get 'LoadModSystem'. Perm Err?");
                return;
            }

            Console.WriteLine("Synapse-Inject: Injected!");
            Console.WriteLine("Synapse: Patching...");

            var def = FindType(module.Assembly, "ServerConsoleSender");

            // ReSharper disable once IdentifierTypo
            MethodDef bctor = new MethodDefUser(".ctor", MethodSig.CreateInstance(module.CorLibTypes.Void),
                                                MethodImplAttributes.IL | MethodImplAttributes.Managed,
                                                MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName);

            if (FindMethod(def, ".ctor") != null)
            {
                bctor = FindMethod(def, ".ctor");
                Console.WriteLine("Synapse: Re-using constructor.");
            }
            else
            {
                def.Methods.Add(bctor);
            }

            CilBody body;

            bctor.Body = body = new CilBody();

            body.Instructions.Add(OpCodes.Call.ToInstruction(call));
            body.Instructions.Add(OpCodes.Ret.ToInstruction());

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

            Console.WriteLine("Synapse: Patch Complete!");

            var publicModule = ModuleDefMD.Load("Assembly-CSharp-Synapse.dll");

            Console.WriteLine("Synapse-Public: Creating Publicized DLL");

            var allTypes   = GetAllTypes(publicModule.Assembly.ManifestModule);
            var typeDefs   = allTypes.ToList();
            var allMethods = typeDefs.SelectMany(t => t.Methods);
            var allFields  = typeDefs.SelectMany(t => t.Fields);

            #region Publiczing

            foreach (var type in typeDefs.Where(type => !type?.IsPublic ?? false))
            {
                type.Attributes = type.IsNested ? TypeAttributes.NestedPublic : TypeAttributes.Public;
            }

            foreach (var method in allMethods)
            {
                if (!method?.IsPublic ?? false)
                {
                    method.Access = MethodAttributes.Public;
                }
            }


            foreach (var field in allFields)
            {
                if (!field?.IsPublic ?? false)
                {
                    field.Access = FieldAttributes.Public;
                }
            }

            #endregion

            publicModule.Write("Assembly-CSharp-Synapse_publicised.dll");

            Console.WriteLine("Synapse-Public: Created Publicised DLL");

            Thread.Sleep(1000000000);
        }
Exemplo n.º 30
0
        public static void Publicize(string input, string output = null)
        {
            output ??= DefaultOutputDir + Path.DirectorySeparatorChar;
            if (string.IsNullOrEmpty(Path.GetFileName(output)))
            {
                output = Path.Combine(output, Path.GetFileNameWithoutExtension(input) + Suffix + Path.GetExtension(input));
            }

            if (!File.Exists(input))
            {
                Console.WriteLine();
                Console.WriteLine("ERROR! File doesn't exist or you don't have sufficient permissions.");
                Environment.Exit(30);
            }

            ModuleDefMD module = null;

            try
            {
                module = ModuleDefMD.Load(input, ModuleDef.CreateModuleContext());
            }
            catch (Exception e)
            {
                Console.WriteLine();
                Console.WriteLine("ERROR! Cannot read the assembly. Please check your permissions.");
                Console.WriteLine(e);
                Environment.Exit(40);
            }

            var runtimeVisibilityAttribute = new TypeDefUser("RuntimeVisibilityAttribute", module.Import(typeof(Attribute)))
            {
                Attributes = TypeAttributes.Class & TypeAttributes.Public
            };

            module.Types.Add(runtimeVisibilityAttribute);

            runtimeVisibilityAttribute.Methods.Add(new MethodDefUser(
                                                       ".ctor",
                                                       MethodSig.CreateInstance(module.CorLibTypes.Void, module.CorLibTypes.String),
                                                       MethodImplAttributes.Managed & MethodImplAttributes.IL,
                                                       MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName)
            {
                ParamDefs = { new ParamDefUser("visibility") }
            }
                                                   );

            var allTypes = module.GetTypes().ToList();

            var types   = 0;
            var methods = 0;
            var fields  = 0;

            foreach (var type in allTypes)
            {
                foreach (var method in type.Methods)
                {
                    if (method.IsPublic)
                    {
                        continue;
                    }

                    methods++;
                    method.CustomAttributes.Add(
                        new CustomAttribute(runtimeVisibilityAttribute.FindConstructors().Single(),
                                            new[]
                    {
                        new CAArgument(module.CorLibTypes.String, method.Access.ToString())
                    })
                        );
                    method.Access = MethodAttributes.Public;
                }

                foreach (var field in type.Fields)
                {
                    if (field.IsPublic)
                    {
                        continue;
                    }

                    fields++;
                    field.CustomAttributes.Add(
                        new CustomAttribute(runtimeVisibilityAttribute.FindConstructors().Single(),
                                            new[]
                    {
                        new CAArgument(module.CorLibTypes.String, field.Access.ToString())
                    })
                        );
                    field.Access = FieldAttributes.Public;
                }

                if (type.IsNested ? type.IsNestedPublic : type.IsPublic)
                {
                    continue;
                }

                types++;
                type.CustomAttributes.Add(
                    new CustomAttribute(runtimeVisibilityAttribute.FindConstructors().Single(),
                                        new[]
                {
                    new CAArgument(module.CorLibTypes.String, type.Visibility.ToString())
                })
                    );
                type.Visibility = type.IsNested ? TypeAttributes.NestedPublic : TypeAttributes.Public;
            }

            const string reportString = "Changed {0} {1} to public.";

            Console.WriteLine(reportString, types, "types");
            Console.WriteLine(reportString, methods, "methods (including getters and setters)");
            Console.WriteLine(reportString, fields, "fields");

            Console.WriteLine();

            Console.WriteLine("Saving a copy of the modified assembly ...");

            try
            {
                var directory = Path.GetDirectoryName(output);
                if (!string.IsNullOrEmpty(directory))
                {
                    Directory.CreateDirectory(directory);
                }

                module.Write(output);
            }
            catch (Exception e)
            {
                Console.WriteLine();
                Console.WriteLine("ERROR! Cannot create/overwrite the new assembly. ");
                Console.WriteLine("Please check the path and its permissions " +
                                  "and in case of overwriting an existing file ensure that it isn't currently used.");
                Console.WriteLine(e);
                Environment.Exit(50);
            }

            Console.WriteLine("Completed.");
        }