Exemple #1
0
        static void Main(string[] args)
        {
            var asmDef = AssemblyDef.Load(args[0]);
            var method = asmDef.ManifestModule.EntryPoint.DeclaringType.FindMethod("Foo");
            var asmResolver = new AssemblyResolver();
            var modCtx = new ModuleContext(asmResolver);

            var ast = new ILAST(method, modCtx);

            Console.WriteLine("-------------------------------");
            Console.WriteLine("         Standard AST");
            Console.WriteLine("-------------------------------");

            foreach (Element element in ast.Elements)
                Console.WriteLine("{0}: {1}", element.GetType().Name, element);

            ILAST.SimplifyElements(ast.Elements);
            Console.WriteLine("\n-------------------------------");
            Console.WriteLine("        Simplified AST");
            Console.WriteLine("-------------------------------");

            foreach (Element element in ast.Elements)
                Console.WriteLine("{0}: {1}", element.GetType().Name, element);

            Console.WriteLine(asmDef);
        }
 public MosaModuleLoader()
 {
     Modules = new List<ModuleDefMD>();
     Resolver = new AssemblyResolver(null, false, false);
     var typeResolver = new dnlib.DotNet.Resolver(Resolver);
     Resolver.DefaultModuleContext = new ModuleContext(Resolver, typeResolver);
     Resolver.EnableTypeDefCache = true;
 }
		AssemblyResolver GetDefaultResolver() {
			lock (sync) {
				if (defaultResolver == null)
					defaultResolver = new AssemblyResolver(new ModuleContext(this));
				foreach (var asm in new List<AssemblyDef>(defaultResolver.GetCachedAssemblies()))
					defaultResolver.Remove(asm);
				foreach (var assembly in LoadedAssemblies.Values)
					defaultResolver.AddToCache(assembly);
				return defaultResolver;
			}
		}
Exemple #4
0
        static List<AssemblyDef> LoadAssemblies(string target)
        {
            AssemblyResolver asmResolver = new AssemblyResolver();
            ModuleContext modCtx = new ModuleContext(asmResolver);
            asmResolver.DefaultModuleContext = modCtx;
            asmResolver.EnableTypeDefCache = true;

            var directory = Path.GetFullPath(Path.GetDirectoryName(target));
            asmResolver.PreSearchPaths.Add(directory);

            List<AssemblyDef> assemblies = new List<AssemblyDef>();
            
            foreach (var asm in Directory.GetFiles(directory, "*.*")
                .Where(f=>Path.GetExtension(f.ToLower()) == ".exe" || Path.GetExtension(f.ToLower())==".dll"))
            {
                try
                {
                    var def = AssemblyDef.Load(asm);
                    def.Modules[0].Context = modCtx;
                    asmResolver.AddToCache(def);
                    assemblies.Add(def);
                }
                catch
                {
                    //Ignore
                }
            }

            return assemblies;
        }
        /// <summary>
        ///     Runs the engine.
        /// </summary>
        /// <param name="parameters">The parameters.</param>
        /// <param name="token">The cancellation token.</param>
        static void RunInternal(ConfuserParameters parameters, CancellationToken token)
        {
            // 1. Setup context
            var context = new ConfuserContext();
            context.Logger = parameters.GetLogger();
            context.Project = parameters.Project;
            context.PackerInitiated = parameters.PackerInitiated;
            context.token = token;

            PrintInfo(context);

            bool ok = false;
            try {
                var asmResolver = new AssemblyResolver();
                asmResolver.EnableTypeDefCache = true;
                asmResolver.DefaultModuleContext = new ModuleContext(asmResolver);
                context.Resolver = asmResolver;
                context.BaseDirectory = Path.Combine(Environment.CurrentDirectory, parameters.Project.BaseDirectory.TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar);
                context.OutputDirectory = Path.Combine(parameters.Project.BaseDirectory, parameters.Project.OutputDirectory.TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar);
                foreach (string probePath in parameters.Project.ProbePaths)
                    asmResolver.PostSearchPaths.Insert(0, Path.Combine(context.BaseDirectory, probePath));

                context.CheckCancellation();

                Marker marker = parameters.GetMarker();

                // 2. Discover plugins
                context.Logger.Debug("Discovering plugins...");

                IList<Protection> prots;
                IList<Packer> packers;
                IList<ConfuserComponent> components;
                parameters.GetPluginDiscovery().GetPlugins(context, out prots, out packers, out components);

                context.Logger.InfoFormat("Discovered {0} protections, {1} packers.", prots.Count, packers.Count);

                context.CheckCancellation();

                // 3. Resolve dependency
                context.Logger.Debug("Resolving component dependency...");
                try {
                    var resolver = new DependencyResolver(prots);
                    prots = resolver.SortDependency();
                }
                catch (CircularDependencyException ex) {
                    context.Logger.ErrorException("", ex);
                    throw new ConfuserException(ex);
                }

                components.Insert(0, new CoreComponent(parameters, marker));
                foreach (Protection prot in prots)
                    components.Add(prot);
                foreach (Packer packer in packers)
                    components.Add(packer);

                context.CheckCancellation();

                // 4. Load modules
                context.Logger.Info("Loading input modules...");
                marker.Initalize(prots, packers);
                MarkerResult markings = marker.MarkProject(parameters.Project, context);
                context.Modules = markings.Modules.ToList().AsReadOnly();
                foreach (var module in context.Modules)
                    module.EnableTypeDefFindCache = true;
                context.OutputModules = Enumerable.Repeat<byte[]>(null, markings.Modules.Count).ToArray();
                context.OutputSymbols = Enumerable.Repeat<byte[]>(null, markings.Modules.Count).ToArray();
                context.OutputPaths = Enumerable.Repeat<string>(null, markings.Modules.Count).ToArray();
                context.Packer = markings.Packer;
                context.ExternalModules = markings.ExternalModules;

                context.CheckCancellation();

                // 5. Initialize components
                context.Logger.Info("Initializing...");
                foreach (ConfuserComponent comp in components) {
                    try {
                        comp.Initialize(context);
                    }
                    catch (Exception ex) {
                        context.Logger.ErrorException("Error occured during initialization of '" + comp.Name + "'.", ex);
                        throw new ConfuserException(ex);
                    }
                    context.CheckCancellation();
                }

                context.CheckCancellation();

                // 6. Build pipeline
                context.Logger.Debug("Building pipeline...");
                var pipeline = new ProtectionPipeline();
                context.Pipeline = pipeline;
                foreach (ConfuserComponent comp in components) {
                    comp.PopulatePipeline(pipeline);
                }

                context.CheckCancellation();

                //7. Run pipeline
                RunPipeline(pipeline, context);

                ok = true;
            }
            catch (AssemblyResolveException ex) {
                context.Logger.ErrorException("Failed to resolve an assembly, check if all dependencies are present in the correct version.", ex);
                PrintEnvironmentInfo(context);
            }
            catch (TypeResolveException ex) {
                context.Logger.ErrorException("Failed to resolve a type, check if all dependencies are present in the correct version.", ex);
                PrintEnvironmentInfo(context);
            }
            catch (MemberRefResolveException ex) {
                context.Logger.ErrorException("Failed to resolve a member, check if all dependencies are present in the correct version.", ex);
                PrintEnvironmentInfo(context);
            }
            catch (IOException ex) {
                context.Logger.ErrorException("An IO error occurred, check if all input/output locations are readable/writable.", ex);
            }
            catch (OperationCanceledException) {
                context.Logger.Error("Operation cancelled.");
            }
            catch (ConfuserException) {
                // Exception is already handled/logged, so just ignore and report failure
            }
            catch (Exception ex) {
                context.Logger.ErrorException("Unknown error occurred.", ex);
            }
            finally {
                if (context.Resolver != null)
                    context.Resolver.Clear();
                context.Logger.Finish(ok);
            }
        }
		protected override void ScanForObfuscator() {
			methodsDecrypter = new MethodsDecrypter(module);
			methodsDecrypter.Find();
			stringDecrypter = new StringDecrypter(module);
			stringDecrypter.Find(DeobfuscatedFile);
			booleanDecrypter = new BooleanDecrypter(module);
			booleanDecrypter.Find();
			assemblyResolver = new AssemblyResolver(module);
			assemblyResolver.Find(DeobfuscatedFile);
			obfuscatorName = DetectVersion();
			if (unpackedNativeFile)
				obfuscatorName += " (native)";
			resourceResolver = new ResourceResolver(module);
			resourceResolver.Find(DeobfuscatedFile);
		}
		public AssemblyResolver CreateResolver() {
			var resolver = new AssemblyResolver(new ModuleContext(this));
			foreach (var assembly in LoadedAssemblies.Values)
				resolver.AddToCache(assembly);
			return resolver;
		}
Exemple #8
0
		static Boolean TryLoadModule(String path, ILogger logger, out EazModule module)
		{
			try
			{
				ModuleDefMD moduleDef = ModuleDefMD.Load(path);
				AssemblyResolver asmResolver = new AssemblyResolver();
				ModuleContext modCtx = new ModuleContext(asmResolver);
				// All resolved assemblies will also get this same modCtx
				asmResolver.DefaultModuleContext = modCtx;
				moduleDef.Context = modCtx;

				module = new EazModule(moduleDef, logger);
			}
			catch (IOException e)
			{
				// Console.WriteLine(e.Message);
				Console.Write(e);
				module = null;
				return false;
			}

			return true;
		}