예제 #1
0
파일: Packer.cs 프로젝트: yuske/ConfuserEx
        /// <summary>
        ///     Protects the stub using original project settings replace the current output with the protected stub.
        /// </summary>
        /// <param name="context">The working context.</param>
        /// <param name="fileName">The result file name.</param>
        /// <param name="module">The stub module.</param>
        /// <param name="snKey">The strong name key.</param>
        /// <param name="prot">The packer protection that applies to the stub.</param>
        protected void ProtectStub(ConfuserContext context, string fileName, byte[] module, StrongNameKey snKey, Protection prot = null)
        {
            string tmpDir = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
            string outDir = Path.Combine(tmpDir, Path.GetRandomFileName());

            Directory.CreateDirectory(tmpDir);
            File.WriteAllBytes(Path.Combine(tmpDir, fileName), module);

            var proj = new ConfuserProject();

            proj.Seed = context.Project.Seed;
            foreach (Rule rule in context.Project.Rules)
            {
                proj.Rules.Add(rule);
            }
            proj.Add(new ProjectModule {
                Path = fileName
            });
            proj.BaseDirectory   = tmpDir;
            proj.OutputDirectory = outDir;

            PluginDiscovery discovery = null;

            if (prot != null)
            {
                var rule = new Rule {
                    Preset  = ProtectionPreset.None,
                    Inherit = true,
                    Pattern = "true"
                };
                rule.Add(new SettingItem <Protection> {
                    Id     = prot.Id,
                    Action = SettingItemAction.Add
                });
                proj.Rules.Add(rule);
                discovery = new PackerDiscovery(prot);
            }

            try {
                ConfuserEngine.Run(new ConfuserParameters {
                    Logger          = new PackerLogger(context.Logger),
                    PluginDiscovery = discovery,
                    Marker          = new PackerMarker(snKey),
                    Project         = proj,
                    PackerInitiated = true
                }, context.token).Wait();
            }
            catch (AggregateException ex) {
                context.Logger.Error("Failed to protect packer stub.");
                throw new ConfuserException(ex);
            }

            context.OutputModules = new[] { File.ReadAllBytes(Path.Combine(outDir, fileName)) };
            context.OutputPaths   = new[] { fileName };
        }
 /// <summary>
 ///     Runs the engine with the specified parameters.
 /// </summary>
 /// <param name="parameters">The parameters.</param>
 /// <param name="token">The token used for cancellation.</param>
 /// <returns>Task to run the engine.</returns>
 /// <exception cref="T:System.ArgumentNullException">
 ///     <paramref name="parameters" />.Project is <c>null</c>.
 /// </exception>
 // Token: 0x06000109 RID: 265 RVA: 0x00008830 File Offset: 0x00006A30
 public static Task Run(ConfuserParameters parameters, CancellationToken?token = null)
 {
     if (parameters.Project == null)
     {
         throw new ArgumentNullException("parameters");
     }
     if (!token.HasValue)
     {
         token = new CancellationToken?(new CancellationTokenSource().Token);
     }
     return(Task.Factory.StartNew(delegate
     {
         ConfuserEngine.RunInternal(parameters, token.Value);
     }, token.Value));
 }
 /// <summary>
 ///     Prints the environment information when error occurred.
 /// </summary>
 /// <param name="context">The working context.</param>
 // Token: 0x06000117 RID: 279 RVA: 0x0000A430 File Offset: 0x00008630
 private static void PrintEnvironmentInfo(ConfuserContext context)
 {
     if (context.PackerInitiated)
     {
         return;
     }
     context.Logger.Error("---BEGIN DEBUG INFO---");
     context.Logger.Error("Installed Framework Versions:");
     foreach (string ver in ConfuserEngine.GetFrameworkVersions())
     {
         context.Logger.ErrorFormat("    {0}", new object[]
         {
             ver.Trim()
         });
     }
     context.Logger.Error("");
     if (context.Resolver != null)
     {
         context.Logger.Error("Cached assemblies:");
         foreach (AssemblyDef asm in context.Resolver.GetCachedAssemblies())
         {
             if (string.IsNullOrEmpty(asm.ManifestModule.Location))
             {
                 context.Logger.ErrorFormat("    {0}", new object[]
                 {
                     asm.FullName
                 });
             }
             else
             {
                 context.Logger.ErrorFormat("    {0} ({1})", new object[]
                 {
                     asm.FullName,
                     asm.ManifestModule.Location
                 });
             }
             foreach (AssemblyRef reference in asm.Modules.OfType <ModuleDefMD>().SelectMany((ModuleDefMD m) => m.GetAssemblyRefs()))
             {
                 context.Logger.ErrorFormat("        {0}", new object[]
                 {
                     reference.FullName
                 });
             }
         }
     }
     context.Logger.Error("---END DEBUG INFO---");
 }
        /// <summary>
        ///     Runs the engine.
        /// </summary>
        /// <param name="parameters">The parameters.</param>
        /// <param name="token">The cancellation token.</param>
        // Token: 0x0600010A RID: 266 RVA: 0x000088B4 File Offset: 0x00006AB4
        private static void RunInternal(ConfuserParameters parameters, CancellationToken token)
        {
            ConfuserContext context = new ConfuserContext();

            context.Logger          = parameters.GetLogger();
            context.Project         = parameters.Project;
            context.PackerInitiated = parameters.PackerInitiated;
            context.token           = token;
            ConfuserEngine.PrintInfo(context);
            bool ok = false;

            try
            {
                AssemblyResolver asmResolver = new AssemblyResolver();
                asmResolver.EnableTypeDefCache   = true;
                asmResolver.DefaultModuleContext = new ModuleContext(asmResolver);
                context.Resolver      = asmResolver;
                context.BaseDirectory = Path.Combine(Environment.CurrentDirectory, parameters.Project.BaseDirectory.TrimEnd(new char[]
                {
                    Path.DirectorySeparatorChar
                }) + Path.DirectorySeparatorChar);
                context.OutputDirectory = Path.Combine(parameters.Project.BaseDirectory, parameters.Project.OutputDirectory.TrimEnd(new char[]
                {
                    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();
                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.", new object[]
                {
                    prots.Count,
                    packers.Count
                });
                context.CheckCancellation();
                context.Logger.Debug("Resolving component dependency...");
                try
                {
                    DependencyResolver 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();
                context.Logger.Info("Loading input modules...");
                marker.Initalize(prots, packers);
                MarkerResult markings = marker.MarkProject(parameters.Project, context);
                context.Modules = markings.Modules.ToList <ModuleDefMD>().AsReadOnly();
                foreach (ModuleDefMD module in context.Modules)
                {
                    module.EnableTypeDefFindCache = true;
                }
                context.OutputModules   = Enumerable.Repeat <byte[]>(null, markings.Modules.Count).ToArray <byte[]>();
                context.OutputSymbols   = Enumerable.Repeat <byte[]>(null, markings.Modules.Count).ToArray <byte[]>();
                context.OutputPaths     = Enumerable.Repeat <string>(null, markings.Modules.Count).ToArray <string>();
                context.Packer          = markings.Packer;
                context.ExternalModules = markings.ExternalModules;
                context.CheckCancellation();
                context.Logger.Info("Initializing...");
                foreach (ConfuserComponent comp in components)
                {
                    try
                    {
                        comp.Initialize(context);
                    }
                    catch (Exception ex2)
                    {
                        context.Logger.ErrorException("Error occured during initialization of '" + comp.Name + "'.", ex2);
                        throw new ConfuserException(ex2);
                    }
                    context.CheckCancellation();
                }
                context.CheckCancellation();
                context.Logger.Debug("Building pipeline...");
                ProtectionPipeline pipeline = new ProtectionPipeline();
                context.Pipeline = pipeline;
                foreach (ConfuserComponent comp2 in components)
                {
                    comp2.PopulatePipeline(pipeline);
                }
                context.CheckCancellation();
                ConfuserEngine.RunPipeline(pipeline, context);
                ok = true;
            }
            catch (AssemblyResolveException ex3)
            {
                context.Logger.ErrorException("Failed to resolve an assembly, check if all dependencies are present in the correct version.", ex3);
                ConfuserEngine.PrintEnvironmentInfo(context);
            }
            catch (TypeResolveException ex4)
            {
                context.Logger.ErrorException("Failed to resolve a type, check if all dependencies are present in the correct version.", ex4);
                ConfuserEngine.PrintEnvironmentInfo(context);
            }
            catch (MemberRefResolveException ex5)
            {
                context.Logger.ErrorException("Failed to resolve a member, check if all dependencies are present in the correct version.", ex5);
                ConfuserEngine.PrintEnvironmentInfo(context);
            }
            catch (IOException ex6)
            {
                context.Logger.ErrorException("An IO error occurred, check if all input/output locations are readable/writable.", ex6);
            }
            catch (OperationCanceledException)
            {
                context.Logger.Error("Operation cancelled.");
            }
            catch (ConfuserException)
            {
            }
            catch (Exception ex7)
            {
                context.Logger.ErrorException("Unknown error occurred.", ex7);
            }
            finally
            {
                if (context.Resolver != null)
                {
                    context.Resolver.Clear();
                }
                context.Logger.Finish(ok);
            }
        }
예제 #5
0
        /// <summary>
        ///     Protects the stub using original project settings replace the current output with the protected stub.
        /// </summary>
        /// <param name="context">The working context.</param>
        /// <param name="fileName">The result file name.</param>
        /// <param name="module">The stub module.</param>
        /// <param name="snKey">The strong name key.</param>
        /// <param name="prot">The packer protection that applies to the stub.</param>
        // Token: 0x060001E8 RID: 488 RVA: 0x0000F8AC File Offset: 0x0000DAAC
        protected void ProtectStub(ConfuserContext context, string fileName, byte[] module, StrongNameKey snKey, Protection prot = null)
        {
            string tmpDir = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
            string outDir = Path.Combine(tmpDir, Path.GetRandomFileName());

            Directory.CreateDirectory(tmpDir);
            for (int i = 0; i < context.OutputModules.Count; i++)
            {
                string path = Path.GetFullPath(Path.Combine(tmpDir, context.OutputPaths[i]));
                string dir  = Path.GetDirectoryName(path);
                if (!Directory.Exists(dir))
                {
                    Directory.CreateDirectory(dir);
                }
                File.WriteAllBytes(path, context.OutputModules[i]);
            }
            File.WriteAllBytes(Path.Combine(tmpDir, fileName), module);
            ConfuserProject proj = new ConfuserProject();

            proj.Seed = context.Project.Seed;
            foreach (Rule rule in context.Project.Rules)
            {
                proj.Rules.Add(rule);
            }
            proj.Add(new ProjectModule
            {
                Path = fileName
            });
            proj.BaseDirectory   = tmpDir;
            proj.OutputDirectory = outDir;
            foreach (string path2 in context.Project.ProbePaths)
            {
                proj.ProbePaths.Add(path2);
            }
            proj.ProbePaths.Add(context.Project.BaseDirectory);
            PluginDiscovery discovery = null;

            if (prot != null)
            {
                Rule rule2 = new Rule("true", ProtectionPreset.None, false)
                {
                    Preset  = ProtectionPreset.None,
                    Inherit = true,
                    Pattern = "true"
                };
                rule2.Add(new SettingItem <Protection>(null, SettingItemAction.Add)
                {
                    Id     = prot.Id,
                    Action = SettingItemAction.Add
                });
                proj.Rules.Add(rule2);
                discovery = new PackerDiscovery(prot);
            }
            try
            {
                ConfuserEngine.Run(new ConfuserParameters
                {
                    Logger          = new PackerLogger(context.Logger),
                    PluginDiscovery = discovery,
                    Marker          = new PackerMarker(snKey),
                    Project         = proj,
                    PackerInitiated = true
                }, new CancellationToken?(context.token)).Wait();
            }
            catch (AggregateException ex)
            {
                context.Logger.Error("Failed to protect packer stub.");
                throw new ConfuserException(ex);
            }
            context.OutputModules = new byte[][]
            {
                File.ReadAllBytes(Path.Combine(outDir, fileName))
            };
            context.OutputPaths = new string[]
            {
                fileName
            };
        }
예제 #6
0
        /// <summary>
        ///     Protects the stub using original project settings replace the current output with the protected stub.
        /// </summary>
        /// <param name="context">The working context.</param>
        /// <param name="fileName">The result file name.</param>
        /// <param name="module">The stub module.</param>
        /// <param name="snKey">The strong name key.</param>
        /// <param name="prot">The packer protection that applies to the stub.</param>
        protected void ProtectStub(ConfuserContext context, string fileName, byte[] module, StrongNameKey snKey, StrongNamePublicKey snPubKey, StrongNameKey snSigKey, StrongNamePublicKey snPubSigKey, bool snDelaySig, Protection prot = null)
        {
            string tmpDir = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());

            try {
                string outDir = Path.Combine(tmpDir, Path.GetRandomFileName());
                Directory.CreateDirectory(tmpDir);

                for (int i = 0; i < context.OutputModules.Count; i++)
                {
                    string path = Path.GetFullPath(Path.Combine(tmpDir, context.OutputPaths[i]));
                    var    dir  = Path.GetDirectoryName(path);
                    if (!Directory.Exists(dir))
                    {
                        Directory.CreateDirectory(dir);
                    }
                    File.WriteAllBytes(path, context.OutputModules[i]);
                }

                File.WriteAllBytes(Path.Combine(tmpDir, fileName), module);

                var proj = new ConfuserProject();
                proj.Seed = context.Project.Seed;
                foreach (Rule rule in context.Project.Rules)
                {
                    proj.Rules.Add(rule);
                }
                proj.Add(new ProjectModule {
                    Path = fileName
                });
                proj.BaseDirectory   = tmpDir;
                proj.OutputDirectory = outDir;
                foreach (var path in context.Project.ProbePaths)
                {
                    proj.ProbePaths.Add(path);
                }
                proj.ProbePaths.Add(context.Project.BaseDirectory);

                PluginDiscovery discovery = null;
                if (prot != null)
                {
                    var rule = new Rule {
                        Preset  = ProtectionPreset.None,
                        Inherit = true,
                        Pattern = "true"
                    };
                    rule.Add(new SettingItem <Protection> {
                        Id     = prot.Id,
                        Action = SettingItemAction.Add
                    });
                    proj.Rules.Add(rule);
                    discovery = new PackerDiscovery(prot);
                }

                try {
                    ConfuserEngine
                    .Run(
                        new ConfuserParameters {
                        Logger          = new PackerLogger(context.Logger),
                        PluginDiscovery = discovery,
                        Marker          = new PackerMarker(snKey, snPubKey, snDelaySig, snSigKey, snPubSigKey),
                        Project         = proj,
                        PackerInitiated = true
                    }, context.token).Wait();
                }
                catch (AggregateException ex) {
                    context.Logger.Error("Failed to protect packer stub.");
                    throw new ConfuserException(ex);
                }

                context.OutputModules = new[] { File.ReadAllBytes(Path.Combine(outDir, fileName)) };
                context.OutputPaths   = new[] { fileName };
            }
            finally {
                try {
                    if (Directory.Exists(tmpDir))
                    {
                        Directory.Delete(tmpDir, true);
                    }
                }
                catch (IOException ex) {
                    context.Logger.WarnException("Failed to remove temporary files of packer.", ex);
                }
            }
        }