コード例 #1
0
        public virtual MarkerSetting MarkAssemblies(Confuser cr, Logger logger)
        {
            this.cr   = cr;
            this.proj = cr.param.Project;
            MarkerSetting ret = new MarkerSetting();

            ret.Assemblies = new AssemblySetting[proj.Count];

            InitRules();

            Marking setting = new Marking();

            using (setting.Level())
            {
                for (int i = 0; i < proj.Count; i++)
                {
                    using (setting.Level())
                        ret.Assemblies[i] = _MarkAssembly(proj[i], setting);
                    logger._Progress(i + 1, proj.Count);
                }
                if (proj.Packer != null)
                {
                    ret.Packer           = Packers[proj.Packer.Id];
                    ret.PackerParameters = Clone(proj.Packer);
                }
            }

            return(ret);
        }
コード例 #2
0
ファイル: ObfAttrMarker.cs プロジェクト: ylm3721/ConfuserEx
        protected override MarkerResult MarkProject(ConfuserProject proj, ConfuserContext context)
        {
            crossModuleAttrs = new Dictionary <string, Dictionary <Regex, List <ObfuscationAttributeInfo> > >();
            this.context     = context;
            project          = proj;
            extModules       = new List <byte[]>();

            var modules = new List <Tuple <ProjectModule, ModuleDefMD> >();

            foreach (ProjectModule module in proj)
            {
                ModuleDefMD modDef = module.Resolve(proj.BaseDirectory, context.Resolver.DefaultModuleContext);
                context.CheckCancellation();

                context.Resolver.AddToCache(modDef);
                modules.Add(Tuple.Create(module, modDef));
            }
            foreach (var module in modules)
            {
                context.Logger.InfoFormat("Loading '{0}'...", module.Item1.Path);

                MarkModule(module.Item2, module == modules[0]);

                // Packer parameters are stored in modules
                if (packer != null)
                {
                    ProtectionParameters.GetParameters(context, module.Item2)[packer] = packerParams;
                }
            }
            return(new MarkerResult(modules.Select(module => module.Item2).ToList(), packer, extModules));
        }
コード例 #3
0
        private static ProjectModule GetOrCreateProjectModule(ConfuserProject project, string assemblyPath, bool isExternal = false)
        {
            var assemblyFileName = Path.GetFileName(assemblyPath);
            var assemblyName     = Path.GetFileNameWithoutExtension(assemblyPath);

            foreach (var module in project)
            {
                if (string.Equals(module.Path, assemblyFileName) || string.Equals(module.Path, assemblyName))
                {
                    return(module);
                }
            }

            if (assemblyPath.StartsWith(project.BaseDirectory))
            {
                assemblyPath = assemblyPath.Substring(project.BaseDirectory.Length).TrimStart(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
            }

            var result = new ProjectModule {
                Path       = assemblyPath,
                IsExternal = isExternal
            };

            project.Add(result);
            return(result);
        }
コード例 #4
0
ファイル: MainWindow.xaml.cs プロジェクト: Elliesaur/Confuser
 private void Save_Click(object sender, RoutedEventArgs e)
 {
     if (Project.FileName == null)
     {
         SaveFileDialog sfd = new SaveFileDialog();
         sfd.Filter = "Confuser Project (*.crproj)|*.crproj|All Files (*.*)|*.*";
         if (sfd.ShowDialog() ?? false)
         {
             ConfuserProject   proj        = Project.ToCrProj();
             XmlWriterSettings wtrSettings = new XmlWriterSettings();
             wtrSettings.Indent = true;
             XmlWriter writer = XmlWriter.Create(sfd.FileName, wtrSettings);
             proj.Save().Save(writer);
             Project.IsModified = false;
             Project.FileName   = sfd.FileName;
             ProjectChanged(proj, new PropertyChangedEventArgs(""));
         }
     }
     else
     {
         ConfuserProject proj = Project.ToCrProj();
         proj.Save().Save(Project.FileName);
         Project.IsModified = false;
         ProjectChanged(proj, new PropertyChangedEventArgs(""));
     }
 }
コード例 #5
0
 public void FromConfuserProject(ConfuserProject prj)
 {
     output = prj.OutputPath;
     snKey  = prj.SNKeyPath;
     seed   = prj.Seed;
     dbg    = prj.Debug;
     foreach (var i in prj.Plugins)
     {
         LoadAssembly(Assembly.LoadFrom(i), false);
     }
     if (prj.Packer != null)
     {
         this.packer = new PrjConfig <Packer>(Packers.Single(_ => _.ID == prj.Packer.Id), this);
         foreach (var j in prj.Packer.AllKeys)
         {
             this.packer.Add(new PrjArgument(this)
             {
                 Name = j, Value = prj.Packer[j]
             });
         }
     }
     foreach (var i in prj)
     {
         PrjAssembly asm = new PrjAssembly(this);
         asm.FromCrAssembly(this, i);
         Assemblies.Add(asm);
     }
     foreach (var i in prj.Rules)
     {
         PrjRule rule = new PrjRule(this);
         rule.FromCrRule(this, i);
         Rules.Add(rule);
     }
 }
コード例 #6
0
        protected override MarkerResult MarkProject(ConfuserProject proj, ConfuserContext context)
        {
            crossModuleAttrs = new Dictionary<string, Dictionary<Regex, List<ObfuscationAttributeInfo>>>();
            this.context = context;
            project = proj;
            extModules = new List<byte[]>();

            var modules = new List<Tuple<ProjectModule, ModuleDefMD>>();
            foreach (ProjectModule module in proj) {
                ModuleDefMD modDef = module.Resolve(proj.BaseDirectory, context.Resolver.DefaultModuleContext);
                context.CheckCancellation();

                context.Resolver.AddToCache(modDef);
                modules.Add(Tuple.Create(module, modDef));
            }
            foreach (var module in modules) {
                context.Logger.InfoFormat("Loading '{0}'...", module.Item1.Path);

                MarkModule(module.Item2, module == modules[0]);

                // Packer parameters are stored in modules
                if (packer != null)
                    ProtectionParameters.GetParameters(context, module.Item2)[packer] = packerParams;
            }
            return new MarkerResult(modules.Select(module => module.Item2).ToList(), packer, extModules);
        }
コード例 #7
0
        private static byte[] ConfuseAssembly(byte[] ILBytes)
        {
            Console.WriteLine("[*]Confusing assembly..");
            string          temp     = Guid.NewGuid().ToString("n").Substring(0, 8);
            string          path     = Path.DirectorySeparatorChar + "tmp" + Path.DirectorySeparatorChar;
            string          tempPath = path + temp;
            ConfuserProject project  = new ConfuserProject();

            System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
            File.WriteAllBytes(tempPath, ILBytes);
            string ProjectFile = String.Format(
                ConfuserExOptions,
                path,
                path,
                temp
                );

            doc.Load(new StringReader(ProjectFile));
            project.Load(doc);
            project.ProbePaths.Add(Common.Net35Directory);
            project.ProbePaths.Add(Common.Net40Directory);

            ConfuserParameters parameters = new ConfuserParameters();

            parameters.Project = project;
            parameters.Logger  = new ConfuserConsoleLogger();
            Directory.SetCurrentDirectory(Common.CompilerRefsDirectory);
            ConfuserEngine.Run(parameters).Wait();
            byte[] ConfusedBytes = File.ReadAllBytes(tempPath);
            File.Delete(tempPath);
            return(ConfusedBytes);
        }
コード例 #8
0
ファイル: Marker.cs プロジェクト: vebin/ConfuserEx
        /// <summary>
        ///     Parses the rules' patterns.
        /// </summary>
        /// <param name="proj">The project.</param>
        /// <param name="module">The module description.</param>
        /// <param name="context">The working context.</param>
        /// <returns>Parsed rule patterns.</returns>
        /// <exception cref="System.ArgumentException">
        ///     One of the rules has invalid pattern.
        /// </exception>
        protected Rules ParseRules(ConfuserProject proj, ProjectModule module, ConfuserContext context)
        {
            var ret    = new Rules();
            var parser = new PatternParser();

            foreach (Rule rule in proj.Rules.Concat(module.Rules))
            {
                try {
                    ret.Add(rule, parser.Parse(rule.Pattern));
                }
                catch (InvalidPatternException ex) {
                    context.Logger.ErrorFormat("Invalid rule pattern: " + rule.Pattern + ".", ex);
                    throw new ConfuserException(ex);
                }
                foreach (var setting in rule)
                {
                    if (!protections.ContainsKey(setting.Id))
                    {
                        context.Logger.ErrorFormat("Cannot find protection with ID '{0}'.", setting.Id);
                        throw new ConfuserException(null);
                    }
                }
            }
            return(ret);
        }
コード例 #9
0
        /// <summary>
        ///     Parses the rules' patterns.
        /// </summary>
        /// <param name="proj">The project.</param>
        /// <param name="module">The module description.</param>
        /// <param name="context">The working context.</param>
        /// <returns>Parsed rule patterns.</returns>
        /// <exception cref="T:System.ArgumentException">
        ///     One of the rules has invalid pattern.
        /// </exception>
        // Token: 0x06000195 RID: 405 RVA: 0x0000D320 File Offset: 0x0000B520
        protected Dictionary <Rule, PatternExpression> ParseRules(ConfuserProject proj, ProjectModule module, ConfuserContext context)
        {
            Dictionary <Rule, PatternExpression> ret = new Dictionary <Rule, PatternExpression>();
            PatternParser parser = new PatternParser();

            foreach (Rule rule in proj.Rules.Concat(module.Rules))
            {
                try
                {
                    ret.Add(rule, parser.Parse(rule.Pattern));
                }
                catch (InvalidPatternException ex)
                {
                    context.Logger.ErrorFormat("Invalid rule pattern: " + rule.Pattern + ".", new object[]
                    {
                        ex
                    });
                    throw new ConfuserException(ex);
                }
                foreach (SettingItem <Protection> setting in rule)
                {
                    if (!this.protections.ContainsKey(setting.Id))
                    {
                        context.Logger.ErrorFormat("Cannot find protection with ID '{0}'.", new object[]
                        {
                            setting.Id
                        });
                        throw new ConfuserException(null);
                    }
                }
            }
            return(ret);
        }
コード例 #10
0
ファイル: AppVM.cs プロジェクト: l1101100/ConfuserEx
        void OpenProj()
        {
            if (!PromptSave())
            {
                return;
            }

            var ofd = new VistaOpenFileDialog();

            ofd.Filter = "ConfuserEx Projects (*.crproj)|*.crproj|All Files (*.*)|*.*";
            if ((ofd.ShowDialog(Application.Current.MainWindow) ?? false) && ofd.FileName != null)
            {
                string fileName = ofd.FileName;
                try {
                    var xmlDoc = new XmlDocument();
                    xmlDoc.Load(fileName);
                    var proj = new ConfuserProject();
                    proj.Load(xmlDoc);
                    Project  = new ProjectVM(proj);
                    FileName = fileName;
                }
                catch {
                    MessageBox.Show("Invalid project!", "ConfuserEx", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
        }
コード例 #11
0
        void LoadProj(AppVM app)
        {
            var args = Environment.GetCommandLineArgs();

            if (args.Length != 2 || !File.Exists(args[1]))
            {
                return;
            }

            string fileName = Path.GetFullPath(args[1]);

            try
            {
                var xmlDoc = new XmlDocument();
                xmlDoc.Load(fileName);
                var proj = new ConfuserProject();
                proj.Load(xmlDoc);
                app.Project  = new ProjectVM(proj, fileName);
                app.FileName = fileName;
            }
            catch
            {
                MessageBox.Show("无效的项目!", "ConfuserEx", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
コード例 #12
0
        public ConfuserProject ToCrProj()
        {
            ConfuserProject ret = new ConfuserProject();

            ret.OutputPath = output;
            ret.SNKeyPath  = snKey;
            ret.Seed       = seed;
            ret.Debug      = dbg;
            ret.BasePath   = GetBasePath();

            if (packer != null)
            {
                ret.Packer = packer.ToCrConfig();
            }
            foreach (string i in Plugins)
            {
                ret.Plugins.Add(i);
            }

            foreach (var i in Assemblies)
            {
                ret.Add(i.ToCrAssembly());
            }
            foreach (var i in Rules)
            {
                ret.Rules.Add(i.ToCrRule());
            }
            return(ret);
        }
コード例 #13
0
ファイル: Compiler.cs プロジェクト: mlynchcogent/Covenant
        private static byte[] Confuse(byte[] ILBytes)
        {
            ConfuserProject project = new ConfuserProject();

            System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
            File.WriteAllBytes(Common.CovenantTempDirectory + "confused", ILBytes);
            string ProjectFile = String.Format(
                ConfuserExOptions,
                Common.CovenantTempDirectory,
                Common.CovenantTempDirectory,
                "confused"
                );

            doc.Load(new StringReader(ProjectFile));
            project.Load(doc);
            project.ProbePaths.Add(Common.CovenantAssemblyReferenceNet35Directory);
            project.ProbePaths.Add(Common.CovenantAssemblyReferenceNet40Directory);

            ConfuserParameters parameters = new ConfuserParameters();

            parameters.Project = project;
            parameters.Logger  = default;
            ConfuserEngine.Run(parameters).Wait();
            return(File.ReadAllBytes(Common.CovenantTempDirectory + "confused"));
        }
コード例 #14
0
ファイル: Packer.cs プロジェクト: EmilZhou/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);

			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),
					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 };
		}
コード例 #15
0
        private void Pack()
        {
            logger.Info("Obfuscating...");

            var proj = new ConfuserProject();

            foreach (var file in Directory.GetFiles(privPath).OrderByDescending(x => x).Where(x => x.EndsWith(".exe") || x.EndsWith(".dll")))
            {
                proj.Add(new ProjectModule {
                    Path = file
                });
            }
#if DEBUG || __TRACE
            proj.OutputDirectory = Path.Combine(privPath.Trim('\\'), "Confused");
#else
            proj.OutputDirectory = privPath;
#endif
            proj.Debug         = true;
            proj.BaseDirectory = privPath;
            proj.ProbePaths.Add(binPath);
            proj.PluginPaths.Add(Path.Combine(binPath, "KoiVM.Confuser.exe"));

            var parameters = new Cr.ConfuserParameters();
            parameters.Project = proj;
            parameters.Logger  = logger;
            Cr.ConfuserEngine.Run(parameters).Wait();

            logger.Info("Packing...");
            using (var stream = new MemoryStream())
            {
                var rc4 = new RC4(Convert.FromBase64String("S29pVk0gaXMgYfD4Da3V0ZSEhIQ=="));//S29pVk0gaXMgY3V0ZSEhIQ==
                using (var deflate = new DeflateStream(stream, CompressionMode.Compress))
                    using (var writer = new BinaryWriter(deflate))
                    {
#if DEBUG || __TRACE
                        var fileList = Directory.GetFiles(@"C:\Users\Nybher\Desktop\koiVM\Debug\bin\pub\ann\");
#else
                        var fileList = Directory.GetFiles(privPath, "*.dll");
#endif

                        writer.Write(fileList.Length);
                        foreach (var file in fileList)
                        {
                            var fileBuf = File.ReadAllBytes(file);
                            writer.Write(fileBuf.Length);
                            writer.Write(fileBuf);
#if !DEBUG && !__TRACE
                            File.Delete(file);
#endif
                        }
                    }
                var buf = stream.ToArray();
                rc4.Crypt(buf, 0, buf.Length);
                File.WriteAllBytes(Path.Combine(privPath, "koi.pack"), buf);

                WriteVersion(version);
            }
        }
コード例 #16
0
        /// <inheritdoc />
        protected internal override MarkerResult MarkProject(ConfuserProject proj, ConfuserContext context)
        {
            crossModuleAttrs = new Dictionary <string, Dictionary <Regex, List <ObfuscationAttributeInfo> > >();
            this.context     = context;
            project          = proj;
            extModules       = new List <byte[]>();

            if (proj.Packer != null)
            {
                if (!packers.ContainsKey(proj.Packer.Id))
                {
                    context.Logger.ErrorFormat("Cannot find packer with ID '{0}'.", proj.Packer.Id);
                    throw new ConfuserException(null);
                }

                packer       = packers[proj.Packer.Id];
                packerParams = new Dictionary <string, string>(proj.Packer, StringComparer.OrdinalIgnoreCase);
            }

            var modules = new List <Tuple <ProjectModule, ModuleDefMD> >();

            foreach (ProjectModule module in proj)
            {
                if (module.IsExternal)
                {
                    extModules.Add(module.LoadRaw(proj.BaseDirectory));
                    continue;
                }

                ModuleDefMD modDef = module.Resolve(proj.BaseDirectory, context.Resolver.DefaultModuleContext);
                context.CheckCancellation();

                context.Resolver.AddToCache(modDef);
                modules.Add(Tuple.Create(module, modDef));
            }
            foreach (var module in modules)
            {
                context.Logger.InfoFormat("Loading '{0}'...", module.Item1.Path);

                Rules rules = ParseRules(proj, module.Item1, context);
                MarkModule(module.Item1, module.Item2, rules, module == modules[0]);

                context.Annotations.Set(module.Item2, RulesKey, rules);

                // Packer parameters are stored in modules
                if (packer != null)
                {
                    ProtectionParameters.GetParameters(context, module.Item2)[packer] = packerParams;
                }
            }

            if (proj.Debug && proj.Packer != null)
            {
                context.Logger.Warn("Generated Debug symbols might not be usable with packers!");
            }

            return(new MarkerResult(modules.Select(module => module.Item2).ToList(), packer, extModules));
        }
コード例 #17
0
        /// <summary>
        ///     Loads the assembly and marks the project.
        /// </summary>
        /// <param name="proj">The project.</param>
        /// <param name="context">The working context.</param>
        /// <returns><see cref="MarkerResult" /> storing the marked modules and packer information.</returns>
        protected internal virtual MarkerResult MarkProject(ConfuserProject proj, ConfuserContext context)
        {
            Packer packer = null;
            Dictionary <string, string> packerParams = null;

            if (proj.Packer != null)
            {
                if (!packers.ContainsKey(proj.Packer.Id))
                {
                    context.Logger.ErrorFormat("Cannot find packer with ID '{0}'.", proj.Packer.Id);
                    throw new ConfuserException(null);
                }
                if (proj.Debug)
                {
                    context.Logger.Warn("Generated Debug symbols might not be usable with packers!");
                }

                packer       = packers[proj.Packer.Id];
                packerParams = new Dictionary <string, string>(proj.Packer, StringComparer.OrdinalIgnoreCase);
            }

            var modules = new List <ModuleDefMD>();

            foreach (ProjectModule module in proj)
            {
                context.Logger.InfoFormat("Loading '{0}'...", module.Path);

                ModuleDefMD modDef = module.Resolve(proj.BaseDirectory, context.Resolver.DefaultModuleContext);
                context.CheckCancellation();

                if (proj.Debug)
                {
                    modDef.LoadPdb();
                }

                Rules rules = ParseRules(proj, module, context);

                context.Annotations.Set(modDef, SNKey, LoadSNKey(context, module.SNKeyPath == null ? null : Path.Combine(proj.BaseDirectory, module.SNKeyPath), module.SNKeyPassword));
                context.Annotations.Set(modDef, RulesKey, rules);

                foreach (IDnlibDef def in modDef.FindDefinitions())
                {
                    ApplyRules(context, def, rules);
                    context.CheckCancellation();
                }

                // Packer parameters are stored in modules
                if (packerParams != null)
                {
                    ProtectionParameters.GetParameters(context, modDef)[packer] = packerParams;
                }

                modules.Add(modDef);
            }
            return(new MarkerResult(modules, packer));
        }
コード例 #18
0
        /// <inheritdoc />
        // Token: 0x060001B6 RID: 438 RVA: 0x0000E14C File Offset: 0x0000C34C
        protected internal override MarkerResult MarkProject(ConfuserProject proj, ConfuserContext context)
        {
            this.crossModuleAttrs = new Dictionary <string, Dictionary <Regex, List <ObfAttrMarker.ObfuscationAttributeInfo> > >();
            this.context          = context;
            this.project          = proj;
            this.extModules       = new List <byte[]>();
            if (proj.Packer != null)
            {
                if (!this.packers.ContainsKey(proj.Packer.Id))
                {
                    context.Logger.ErrorFormat("Cannot find packer with ID '{0}'.", new object[]
                    {
                        proj.Packer.Id
                    });
                    throw new ConfuserException(null);
                }
                this.packer       = this.packers[proj.Packer.Id];
                this.packerParams = new Dictionary <string, string>(proj.Packer, StringComparer.OrdinalIgnoreCase);
            }
            List <Tuple <ProjectModule, ModuleDefMD> > modules = new List <Tuple <ProjectModule, ModuleDefMD> >();

            foreach (ProjectModule module3 in proj)
            {
                if (module3.IsExternal)
                {
                    this.extModules.Add(module3.LoadRaw(proj.BaseDirectory));
                }
                else
                {
                    ModuleDefMD modDef = module3.Resolve(proj.BaseDirectory, context.Resolver.DefaultModuleContext);
                    context.CheckCancellation();
                    context.Resolver.AddToCache(modDef);
                    modules.Add(Tuple.Create <ProjectModule, ModuleDefMD>(module3, modDef));
                }
            }
            foreach (Tuple <ProjectModule, ModuleDefMD> module2 in modules)
            {
                context.Logger.InfoFormat("Loading '{0}'...", new object[]
                {
                    module2.Item1.Path
                });
                Dictionary <Rule, PatternExpression> rules = base.ParseRules(proj, module2.Item1, context);
                this.MarkModule(module2.Item1, module2.Item2, rules, module2 == modules[0]);
                context.Annotations.Set <Dictionary <Rule, PatternExpression> >(module2.Item2, Marker.RulesKey, rules);
                if (this.packer != null)
                {
                    ProtectionParameters.GetParameters(context, module2.Item2)[this.packer] = this.packerParams;
                }
            }
            if (proj.Debug && proj.Packer != null)
            {
                context.Logger.Warn("Generated Debug symbols might not be usable with packers!");
            }
            return(new MarkerResult((from module in modules
                                     select module.Item2).ToList <ModuleDefMD>(), this.packer, this.extModules));
        }
コード例 #19
0
ファイル: MainWindow.xaml.cs プロジェクト: Elliesaur/Confuser
        private void Open_Click(object sender, RoutedEventArgs e)
        {
            if (Project.IsModified)
            {
                switch (MessageBox.Show(
                            "You have unsaved changes in this project!\r\nDo you want to save them?",
                            "Confuser", MessageBoxButton.YesNoCancel, MessageBoxImage.Question))
                {
                case MessageBoxResult.Yes:
                    Save_Click(this, new RoutedEventArgs());
                    break;

                case MessageBoxResult.No:
                    break;

                case MessageBoxResult.Cancel:
                    return;
                }
            }

            OpenFileDialog sfd = new OpenFileDialog();

            sfd.Filter = "Confuser Project (*.crproj)|*.crproj|All Files (*.*)|*.*";
            if (sfd.ShowDialog() ?? false)
            {
                try
                {
                    XmlDocument xmlDoc = new XmlDocument();
                    xmlDoc.Load(sfd.FileName);

                    ConfuserProject proj = new ConfuserProject();
                    proj.Load(xmlDoc);

                    Prj prj = new Prj();
                    prj.FromConfuserProject(proj);
                    prj.FileName = sfd.FileName;

                    Project = prj;
                    foreach (ConfuserTab i in Tab.Items)
                    {
                        i.InitProj();
                    }
                    prj.PropertyChanged += new PropertyChangedEventHandler(ProjectChanged);
                    prj.IsModified       = false;
                    ProjectChanged(Project, new PropertyChangedEventArgs(""));
                    Tab.SelectedIndex = 0;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(string.Format(
                                        @"Invalid project file!
Message : {0}
Stack Trace : {1}", ex.Message, ex.StackTrace), "Confuser", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
        }
コード例 #20
0
        // Token: 0x060001F9 RID: 505 RVA: 0x0000FC54 File Offset: 0x0000DE54
        protected internal override MarkerResult MarkProject(ConfuserProject proj, ConfuserContext context)
        {
            MarkerResult result = base.MarkProject(proj, context);

            foreach (ModuleDefMD module in result.Modules)
            {
                context.Annotations.Set <StrongNameKey>(module, Marker.SNKey, this.snKey);
            }
            return(result);
        }
コード例 #21
0
            protected override MarkerResult MarkProject(ConfuserProject proj, ConfuserContext context)
            {
                MarkerResult result = base.MarkProject(proj, context);

                foreach (ModuleDefMD module in result.Modules)
                {
                    context.Annotations.Set(module, SNKey, snKey);
                }
                return(result);
            }
コード例 #22
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 };
        }
コード例 #23
0
ファイル: Program.cs プロジェクト: yuske/ConfuserEx
        private static int Main(string[] args)
        {
            ConsoleColor original = Console.ForegroundColor;

            Console.ForegroundColor = ConsoleColor.White;
            string originalTitle = Console.Title;

            Console.Title = "ConfuserEx";

            try {
                if (args.Length < 1)
                {
                    PrintUsage();
                    return(0);
                }

                var proj = new ConfuserProject();
                try {
                    var xmlDoc = new XmlDocument();
                    xmlDoc.Load(args[0]);
                    proj.Load(xmlDoc);
                    proj.BaseDirectory = Path.Combine(Path.GetDirectoryName(args[0]), proj.BaseDirectory);
                }
                catch (Exception ex) {
                    WriteLineWithColor(ConsoleColor.Red, "Failed to load project:");
                    WriteLineWithColor(ConsoleColor.Red, ex.ToString());
                    return(-1);
                }

                var parameters = new ConfuserParameters();
                parameters.Project = proj;
                var logger = new ConsoleLogger();
                parameters.Logger = new ConsoleLogger();

                Console.Title = "ConfuserEx - Running...";
                ConfuserEngine.Run(parameters).Wait();

                bool noPause = args.Length > 1 && args[1].ToUpperInvariant() == "NOPAUSE";
                if (NeedPause() && !noPause)
                {
                    Console.WriteLine("Press any key to continue...");
                    Console.ReadKey(true);
                }

                return(logger.ReturnValue);
            }
            finally {
                Console.ForegroundColor = original;
                Console.Title           = originalTitle;
            }
        }
コード例 #24
0
        protected internal override MarkerResult MarkProject(ConfuserProject proj, ConfuserContext context)
        {
            MarkerResult result = base.MarkProject(proj, context);

            foreach (ModuleDefMD module in result.Modules)
            {
                context.Annotations.Set(module, SNKey, snKey);
                context.Annotations.Set(module, SNPubKey, snPubKey);
                context.Annotations.Set(module, SNDelaySig, snDelaySig);
                context.Annotations.Set(module, SNSigKey, snSigKey);
                context.Annotations.Set(module, SNSigPubKey, snPubSigKey);
            }
            return(result);
        }
コード例 #25
0
ファイル: MainWindow.xaml.cs プロジェクト: Elliesaur/Confuser
        public void LoadPrj(string path)
        {
            if (Project.IsModified)
            {
                switch (MessageBox.Show(
                            "You have unsaved changes in this project!\r\nDo you want to save them?",
                            "Confuser", MessageBoxButton.YesNoCancel, MessageBoxImage.Question))
                {
                case MessageBoxResult.Yes:
                    Save_Click(this, new RoutedEventArgs());
                    break;

                case MessageBoxResult.No:
                    break;

                case MessageBoxResult.Cancel:
                    return;
                }
            }

            try
            {
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load(path);

                ConfuserProject proj = new ConfuserProject();
                proj.Load(xmlDoc);

                Prj prj = new Prj();
                prj.FileName = path;
                prj.FromConfuserProject(proj);

                Project = prj;
                foreach (ConfuserTab i in Tab.Items)
                {
                    i.InitProj();
                }
                prj.PropertyChanged += new PropertyChangedEventHandler(ProjectChanged);
                prj.IsModified       = false;
                ProjectChanged(Project, new PropertyChangedEventArgs(""));
                Tab.SelectedIndex = 0;
            }
            catch (Exception ex)
            {
                MessageBox.Show(string.Format(
                                    @"Invalid project file!
Message : {0}
Stack Trace : {1}", ex.Message, ex.StackTrace), "Confuser", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
コード例 #26
0
        public Form1()
        {
            InitializeComponent();
            string version = "Could no connect to server";

            try
            {
                version = new WebClient().DownloadString("https://pastebin.com/raw/rQUCwMmL");
            }
            catch
            {
            }
            thirteenForm1.Text += version;
            proj = new ConfuserProject();
        }
コード例 #27
0
        /// <inheritdoc />
        protected internal override MarkerResult MarkProject(ConfuserProject proj, ConfuserContext context)
        {
            crossModuleAttrs = new Dictionary<string, Dictionary<Regex, List<ObfuscationAttributeInfo>>>();
            this.context = context;
            project = proj;
            extModules = new List<byte[]>();

            if (proj.Packer != null) {
                if (!packers.ContainsKey(proj.Packer.Id)) {
                    context.Logger.ErrorFormat("Cannot find packer with ID '{0}'.", proj.Packer.Id);
                    throw new ConfuserException(null);
                }

                packer = packers[proj.Packer.Id];
                packerParams = new Dictionary<string, string>(proj.Packer, StringComparer.OrdinalIgnoreCase);
            }

            var modules = new List<Tuple<ProjectModule, ModuleDefMD>>();
            foreach (ProjectModule module in proj) {
                if (module.IsExternal) {
                    extModules.Add(module.LoadRaw(proj.BaseDirectory));
                    continue;
                }

                ModuleDefMD modDef = module.Resolve(proj.BaseDirectory, context.Resolver.DefaultModuleContext);
                context.CheckCancellation();

                context.Resolver.AddToCache(modDef);
                modules.Add(Tuple.Create(module, modDef));
            }
            foreach (var module in modules) {
                context.Logger.InfoFormat("Loading '{0}'...", module.Item1.Path);

                Rules rules = ParseRules(proj, module.Item1, context);
                MarkModule(module.Item1, module.Item2, rules, module == modules[0]);

                context.Annotations.Set(module.Item2, RulesKey, rules);

                // Packer parameters are stored in modules
                if (packer != null)
                    ProtectionParameters.GetParameters(context, module.Item2)[packer] = packerParams;
            }

            if (proj.Debug && proj.Packer != null)
                context.Logger.Warn("Generated Debug symbols might not be usable with packers!");

            return new MarkerResult(modules.Select(module => module.Item2).ToList(), packer, extModules);
        }
コード例 #28
0
        public override bool Execute()
        {
            var project = new ConfuserProject();

            if (!string.IsNullOrWhiteSpace(SourceProject?.ItemSpec))
            {
                var xmlDoc = new XmlDocument();
                xmlDoc.Load(SourceProject.ItemSpec);
                project.Load(xmlDoc);

                // Probe Paths are not required, because all dependent assemblies are added as external modules.
                project.ProbePaths.Clear();
            }

            project.BaseDirectory = Path.GetDirectoryName(AssemblyPath.ItemSpec);
            var mainModule = GetOrCreateProjectModule(project, AssemblyPath.ItemSpec);

            if (!string.IsNullOrWhiteSpace(KeyFilePath?.ItemSpec))
            {
                mainModule.SNKeyPath = KeyFilePath.ItemSpec;
            }

            if (SatelliteAssemblyPaths != null)
            {
                foreach (var satelliteAssembly in SatelliteAssemblyPaths)
                {
                    if (!string.IsNullOrWhiteSpace(satelliteAssembly?.ItemSpec))
                    {
                        var satelliteModule = GetOrCreateProjectModule(project, satelliteAssembly.ItemSpec);
                        if (!string.IsNullOrWhiteSpace(KeyFilePath?.ItemSpec))
                        {
                            satelliteModule.SNKeyPath = KeyFilePath.ItemSpec;
                        }
                    }
                }
            }

            foreach (var probePath in References.Select(r => Path.GetDirectoryName(r.ItemSpec)).Distinct())
            {
                project.ProbePaths.Add(probePath);
            }

            project.Save().Save(ResultProject.ItemSpec);

            return(true);
        }
コード例 #29
0
ファイル: Program.cs プロジェクト: GavinHwa/ConfuserEx
        private static int Main(string[] args)
        {
            ConsoleColor original = Console.ForegroundColor;
            Console.ForegroundColor = ConsoleColor.White;
            string originalTitle = Console.Title;
            Console.Title = "ConfuserEx";

            try {
                if (args.Length < 1) {
                    PrintUsage();
                    return 0;
                }

                var proj = new ConfuserProject();
                try {
                    var xmlDoc = new XmlDocument();
                    xmlDoc.Load(args[0]);
                    proj.Load(xmlDoc);
                    proj.BaseDirectory = Path.Combine(Path.GetDirectoryName(args[0]), proj.BaseDirectory);
                }
                catch (Exception ex) {
                    WriteLineWithColor(ConsoleColor.Red, "Failed to load project:");
                    WriteLineWithColor(ConsoleColor.Red, ex.ToString());
                    return -1;
                }

                var parameters = new ConfuserParameters();
                parameters.Project = proj;
                var logger = new ConsoleLogger();
                parameters.Logger = new ConsoleLogger();

                Console.Title = "ConfuserEx - Running...";
                ConfuserEngine.Run(parameters).Wait();

                if (NeedPause()) {
                    Console.WriteLine("Press any key to continue...");
                    Console.ReadKey(true);
                }

                return logger.ReturnValue;
            }
            finally {
                Console.ForegroundColor = original;
                Console.Title = originalTitle;
            }
        }
コード例 #30
0
		void LoadProj(AppVM app) {
			var args = Environment.GetCommandLineArgs();
			if (args.Length != 2 || !File.Exists(args[1]))
				return;

			string fileName = Path.GetFullPath(args[1]);
			try {
				var xmlDoc = new XmlDocument();
				xmlDoc.Load(fileName);
				var proj = new ConfuserProject();
				proj.Load(xmlDoc);
				app.Project = new ProjectVM(proj, fileName);
				app.FileName = fileName;
			}
			catch {
				MessageBox.Show("Invalid project!", "ConfuserEx", MessageBoxButton.OK, MessageBoxImage.Error);
			}
		}
コード例 #31
0
        public override bool Execute()
        {
            var project = new ConfuserProject();
            var xmlDoc  = new XmlDocument();

            xmlDoc.Load(Project.ItemSpec);
            project.Load(xmlDoc);
            project.OutputDirectory = Path.GetDirectoryName(OutputAssembly.ItemSpec);

            var logger     = new MSBuildLogger(Log);
            var parameters = new ConfuserParameters {
                Project = project,
                Logger  = logger
            };

            ConfuserEngine.Run(parameters).Wait();
            return(!logger.HasError);
        }
コード例 #32
0
ファイル: AppVM.cs プロジェクト: l1101100/ConfuserEx
        bool SaveProj()
        {
            if (!firstSaved || !File.Exists(FileName))
            {
                var sfd = new VistaSaveFileDialog();
                sfd.FileName = FileName;
                sfd.Filter   = "ConfuserEx Projects (*.crproj)|*.crproj|All Files (*.*)|*.*";
                if (!(sfd.ShowDialog(Application.Current.MainWindow) ?? false) || sfd.FileName == null)
                {
                    return(false);
                }
                FileName = sfd.FileName;
            }
            ConfuserProject proj = ((IViewModel <ConfuserProject>)Project).Model;

            proj.Save().Save(FileName);
            Project.IsModified = false;
            firstSaved         = true;
            return(true);
        }
コード例 #33
0
        private void RunConfuser(ConfuserProject proj)
        {
            var parameters = new ConfuserParameters();

            parameters.Project = proj;
            if (File.Exists(Application.ExecutablePath))
            {
                Environment.CurrentDirectory = Path.GetDirectoryName(Application.ExecutablePath);
            }
            parameters.Logger = this;

            richTextBox1.Text = "";

            cancelSrc = new CancellationTokenSource();
            begin     = DateTime.Now;

            ConfuserEngine.Run(parameters, cancelSrc.Token)
            .ContinueWith(_ => {
                thirteenButton6.Text = "Protect";
            });
        }
コード例 #34
0
        public override bool Execute()
        {
            var project = new ConfuserProject();
            var xmlDoc  = new XmlDocument();

            xmlDoc.Load(Project.ItemSpec);
            project.Load(xmlDoc);
            project.OutputDirectory = Path.GetDirectoryName(Path.GetFullPath(OutputAssembly.ItemSpec));

            var logger     = new MSBuildLogger(Log);
            var parameters = new ConfuserParameters {
                Project = project,
                Logger  = logger
            };

            ConfuserEngine.Run(parameters).Wait();

            ConfusedFiles = project.Select(m => new TaskItem(Path.Combine(project.OutputDirectory, m.Path))).Cast <ITaskItem>().ToArray();

            return(!logger.HasError);
        }
コード例 #35
0
        static void LoadTemplateProject(string templatePath, ConfuserProject proj, List <ProjectModule> templateModules)
        {
            var templateProj = new ConfuserProject();
            var xmlDoc       = new XmlDocument();

            xmlDoc.Load(templatePath);
            templateProj.Load(xmlDoc);

            foreach (var rule in templateProj.Rules)
            {
                proj.Rules.Add(rule);
            }

            proj.Packer = templateProj.Packer;

            foreach (string pluginPath in templateProj.PluginPaths)
            {
                proj.PluginPaths.Add(pluginPath);
            }

            foreach (string probePath in templateProj.ProbePaths)
            {
                proj.ProbePaths.Add(probePath);
            }

            foreach (var templateModule in templateProj)
            {
                if (templateModule.IsExternal)
                {
                    proj.Add(templateModule);
                }
                else
                {
                    templateModules.Add(templateModule);
                }
            }
        }
コード例 #36
0
ファイル: MSBuildTask.cs プロジェクト: n017/Confuser
        public override bool Execute()
        {
            Log.LogMessage(MessageImportance.Low, "Confuser Version v{0}\n", typeof(Core.Confuser).Assembly.GetName().Version);

            string crproj = Path.Combine(
                Path.GetDirectoryName(BuildEngine.ProjectFileOfTaskNode),
                CrProj);

            if (!File.Exists(crproj))
            {
                Log.LogError("Confuser", "CR001", "Project", "",
                    0, 0, 0, 0,
                    string.Format("Error: Crproj file '{0}' not exist!", crproj));
                return false;
            }

            XmlDocument xmlDoc = new XmlDocument();
            ConfuserProject proj = new ConfuserProject();
            bool err = false;
            try
            {
                XmlReaderSettings settings = new XmlReaderSettings();
                settings.Schemas.Add(ConfuserProject.Schema);
                settings.ValidationType = ValidationType.Schema;
                settings.ValidationEventHandler += (sender, e) =>
                {
                    Log.LogError("Confuser", "CR002", "Project", crproj,
                        e.Exception.LineNumber, e.Exception.LinePosition,
                        e.Exception.LineNumber, e.Exception.LinePosition,
                        e.Message);
                    err = true;
                };
                var rdr = XmlReader.Create(crproj, settings);
                xmlDoc.Load(rdr);
                rdr.Close();
                if (err)
                    return false;
                proj.Load(xmlDoc);
            }
            catch (Exception ex)
            {
                Log.LogError("Confuser", "CR002", "Project", crproj,
                    0, 0, 0, 0,
                    ex.Message);
                return false;
            }
            proj.BasePath = BasePath;

            Core.Confuser cr = new Core.Confuser();
            ConfuserParameter param = new ConfuserParameter();
            param.Project = proj;

            var logger = new MSBuildLogger(Log);
            logger.Initalize(param.Logger);

            Log.LogMessage(MessageImportance.Low, "Start working.");
            Log.LogMessage(MessageImportance.Low, "***************");
            cr.Confuse(param);

            return logger.ReturnValue;
        }
コード例 #37
0
ファイル: Packer.cs プロジェクト: n017/Confuser
        protected string[] ProtectStub(AssemblyDefinition asm)
        {
            string tmp = Path.GetTempPath() + "\\" + Path.GetRandomFileName() + "\\";
            Directory.CreateDirectory(tmp);
            ModuleDefinition modDef = this.cr.settings.Single(_ => _.IsMain).Assembly.MainModule;
            asm.MainModule.TimeStamp = modDef.TimeStamp;
            byte[] mvid = new byte[0x10];
            Random.NextBytes(mvid);
            asm.MainModule.Mvid = new Guid(mvid);
            MetadataProcessor psr = new MetadataProcessor();
            Section oldRsrc = null;
            foreach (Section s in modDef.GetSections())
                if (s.Name == ".rsrc") { oldRsrc = s; break; }
            if (oldRsrc != null)
            {
                psr.ProcessImage += accessor =>
                {
                    Section sect = null;
                    foreach (Section s in accessor.Sections)
                        if (s.Name == ".rsrc") { sect = s; break; }
                    if (sect == null)
                    {
                        sect = new Section()
                        {
                            Name = ".rsrc",
                            Characteristics = 0x40000040
                        };
                        foreach (Section s in accessor.Sections)
                            if (s.Name == ".text") { accessor.Sections.Insert(accessor.Sections.IndexOf(s) + 1, sect); break; }
                    }
                    sect.VirtualSize = oldRsrc.VirtualSize;
                    sect.SizeOfRawData = oldRsrc.SizeOfRawData;
                    int idx = accessor.Sections.IndexOf(sect);
                    sect.VirtualAddress = accessor.Sections[idx - 1].VirtualAddress + ((accessor.Sections[idx - 1].VirtualSize + 0x2000U - 1) & ~(0x2000U - 1));
                    sect.PointerToRawData = accessor.Sections[idx - 1].PointerToRawData + accessor.Sections[idx - 1].SizeOfRawData;
                    for (int i = idx + 1; i < accessor.Sections.Count; i++)
                    {
                        accessor.Sections[i].VirtualAddress = accessor.Sections[i - 1].VirtualAddress + ((accessor.Sections[i - 1].VirtualSize + 0x2000U - 1) & ~(0x2000U - 1));
                        accessor.Sections[i].PointerToRawData = accessor.Sections[i - 1].PointerToRawData + accessor.Sections[i - 1].SizeOfRawData;
                    }
                    ByteBuffer buff = new ByteBuffer(oldRsrc.Data);
                    PatchResourceDirectoryTable(buff, oldRsrc, sect);
                    sect.Data = buff.GetBuffer();
                };
            }
            psr.Process(asm.MainModule, tmp + Path.GetFileName(modDef.FullyQualifiedName), new WriterParameters()
            {
                StrongNameKeyPair = this.cr.sn,
                WriteSymbols = this.cr.param.Project.Debug
            });

            Confuser cr = new Confuser();

            ConfuserProject proj = new ConfuserProject();
            proj.Seed = Random.Next().ToString();
            proj.Debug = this.cr.param.Project.Debug;
            foreach (var i in this.cr.param.Project.Rules)
                proj.Rules.Add(i);
            proj.Add(new ProjectAssembly()
            {
                Path = tmp + Path.GetFileName(modDef.FullyQualifiedName)
            });
            proj.OutputPath = tmp;
            foreach (var i in this.cr.param.Project.Plugins) proj.Plugins.Add(i);
            proj.SNKeyPath = this.cr.param.Project.SNKeyPath;

            ConfuserParameter par = new ConfuserParameter();
            par.Project = proj;
            par.ProcessMetadata = PostProcessMetadata;
            par.ProcessImage = PostProcessImage;
            cr.Confuse(par);

            return Directory.GetFiles(tmp);
        }
コード例 #38
0
ファイル: Program.cs プロジェクト: MetSystem/ConfuserEx
        static int Main(string[] args)
        {
            ConsoleColor original = Console.ForegroundColor;
            Console.ForegroundColor = ConsoleColor.White;
            string originalTitle = Console.Title;
            Console.Title = "ConfuserEx";

            bool noPause = false;
            string outDir = null;
            var p = new OptionSet {
                {
                    "n|nopause", "no pause after finishing protection.",
                    value => { noPause = (value != null); }
                }, {
                    "o|out=", "specifies output directory.",
                    value => { outDir = value; }
                }
            };

            List<string> files;
            try {
                files = p.Parse(args);
                if (files.Count == 0)
                    throw new ArgumentException("No input files specified.");
            }
            catch (Exception ex) {
                Console.Write("ConfuserEx.CLI: ");
                Console.WriteLine(ex.Message);
                PrintUsage();
                return -1;
            }

            try {
                var parameters = new ConfuserParameters();

                if (files.Count == 1 && Path.GetExtension(files[0]) == ".crproj") {
                    var proj = new ConfuserProject();
                    try {
                        var xmlDoc = new XmlDocument();
                        xmlDoc.Load(files[0]);
                        proj.Load(xmlDoc);
                        proj.BaseDirectory = Path.Combine(Path.GetDirectoryName(files[0]), proj.BaseDirectory);
                    }
                    catch (Exception ex) {
                        WriteLineWithColor(ConsoleColor.Red, "Failed to load project:");
                        WriteLineWithColor(ConsoleColor.Red, ex.ToString());
                        return -1;
                    }

                    parameters.Project = proj;
                }
                else {
                    // Generate a ConfuserProject for input modules
                    // Assuming first file = main module
                    var proj = new ConfuserProject();
                    foreach (var input in files)
                        proj.Add(new ProjectModule { Path = input });
                    proj.BaseDirectory = Path.GetDirectoryName(files[0]);
                    proj.OutputDirectory = outDir;
                    parameters.Project = proj;
                    parameters.Marker = new ObfAttrMarker();
                }

                int retVal = RunProject(parameters);

                if (NeedPause() && !noPause) {
                    Console.WriteLine("Press any key to continue...");
                    Console.ReadKey(true);
                }

                return retVal;
            }
            finally {
                Console.ForegroundColor = original;
                Console.Title = originalTitle;
            }
        }
コード例 #39
0
ファイル: Program.cs プロジェクト: n017/Confuser
        static int ParseCommandLine(string[] args, out ConfuserProject proj)
        {
            proj = new ConfuserProject();

            if (args.Length == 1 && !args[0].StartsWith("-"))   //shortcut for -project
            {
                if (!File.Exists(args[0]))
                {
                    WriteLineWithColor(ConsoleColor.Red, string.Format("Error: File '{0}' not exist!", args[0]));
                    return 2;
                }
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load(args[0]);
                try
                {
                    proj.Load(xmlDoc);
                }
                catch (Exception e)
                {
                    WriteLineWithColor(ConsoleColor.Red, string.Format("Error: Invalid project format! Message : {0}", e.Message));
                    return 4;
                }
                return 0;
            }

            bool? state = null;
            for (int i = 0; i < args.Length; i++)
            {
                string action = args[i].ToLower();
                if (!action.StartsWith("-") || i + 1 >= args.Length)
                {
                    WriteLineWithColor(ConsoleColor.Red, string.Format("Error: Invalid argument {0}!", action));
                    return 3;
                }
                action = action.Substring(1).ToLower();
                switch (action)
                {
                    case "project":
                        {
                            if (state == true)
                            {
                                WriteLineWithColor(ConsoleColor.Red, string.Format("Error: Invalid combination!"));
                                return 3;
                            }
                            if (!File.Exists(args[i + 1]))
                            {
                                WriteLineWithColor(ConsoleColor.Red, string.Format("Error: File '{0}' not exist!", args[i + 1]));
                                return 2;
                            }
                            try
                            {
                                XmlDocument xmlDoc = new XmlDocument();
                                xmlDoc.Load(args[i + 1]);
                                proj.Load(xmlDoc);
                                proj.BasePath = Path.GetDirectoryName(args[i + 1]);
                            }
                            catch (Exception e)
                            {
                                WriteLineWithColor(ConsoleColor.Red, string.Format("Error: Invalid project format! Message : {0}", e.Message));
                                return 4;
                            }
                            state = false;
                            i += 1;
                        } break;
                    case "preset":
                        {
                            if (state == false)
                            {
                                WriteLineWithColor(ConsoleColor.Red, string.Format("Error: Invalid combination!"));
                                return 3;
                            }
                            try
                            {
                                Rule rule = new Rule();
                                rule.Preset = (Preset)Enum.Parse(typeof(Preset), args[i + 1], true);
                                rule.Pattern = ".*";
                                proj.Rules.Add(rule);
                                i += 1;
                                state = true;
                            }
                            catch
                            {
                                WriteLineWithColor(ConsoleColor.Red, string.Format("Error: Invalid preset '{0}'!", args[i + 1]));
                                return 3;
                            }
                        } break;
                    case "input":
                        {
                            if (state == false)
                            {
                                WriteLineWithColor(ConsoleColor.Red, string.Format("Error: Invalid combination!"));
                                return 3;
                            }
                            int parameterCounter = i + 1;

                            for (int j = i + 1; j < args.Length && !args[j].StartsWith("-"); j++)
                            {
                                parameterCounter = j;
                                string inputParameter = args[j];

                                int lastBackslashPosition = inputParameter.LastIndexOf('\\') + 1;
                                string filename = inputParameter.Substring(lastBackslashPosition, inputParameter.Length - lastBackslashPosition);
                                string path = inputParameter.Substring(0, lastBackslashPosition);

                                try
                                {
                                    string[] fileList = Directory.GetFiles(path, filename);
                                    if (fileList.Length == 0)
                                    {
                                        WriteLineWithColor(ConsoleColor.Red, string.Format("Error: No files matching '{0}' in directory '{1}'!", filename));
                                        return 2;
                                    }
                                    else if (fileList.Length == 1)
                                    {
                                        proj.Add(new ProjectAssembly()
                                        {
                                            Path = fileList[0],
                                            IsMain = j == i + 1 && filename.Contains('?') == false && filename.Contains('*') == false
                                        });
                                    }
                                    else
                                    {
                                        foreach (string expandedFilename in fileList)
                                        {
                                            proj.Add(new ProjectAssembly() { Path = expandedFilename, IsMain = false });
                                        }
                                    }
                                }
                                catch (DirectoryNotFoundException)
                                {
                                    WriteLineWithColor(ConsoleColor.Red, string.Format("Error: Directory '{0}' does not exist!", path));
                                    return 2;
                                }
                            }
                            state = true;
                            i = parameterCounter;
                        } break;
                    case "output":
                        {
                            if (state == false)
                            {
                                WriteLineWithColor(ConsoleColor.Red, string.Format("Error: Invalid combination!"));
                                return 3;
                            }
                            if (!Directory.Exists(args[i + 1]))
                            {
                                WriteLineWithColor(ConsoleColor.Red, string.Format("Error: Directory '{0}' not exist!", args[i + 1]));
                                return 2;
                            }
                            proj.OutputPath = args[i + 1];
                            state = true;
                            i += 1;
                        } break;
                    case "snkey":
                        {
                            if (!File.Exists(args[i + 1]))
                            {
                                WriteLineWithColor(ConsoleColor.Red, string.Format("Error: File '{0}' not exist!", args[i + 1]));
                                return 2;
                            }
                            proj.SNKeyPath = args[i + 1];
                            state = true;
                            i += 1;
                        } break;
                }
            }

            if (proj.Count == 0 || string.IsNullOrEmpty(proj.OutputPath))
            {
                WriteLineWithColor(ConsoleColor.Red, "Error: Missing required arguments!");
                return 4;
            }

            return 0;
        }
コード例 #40
0
ファイル: Marker.cs プロジェクト: EmilZhou/ConfuserEx
		/// <summary>
		///     Parses the rules' patterns.
		/// </summary>
		/// <param name="proj">The project.</param>
		/// <param name="module">The module description.</param>
		/// <param name="context">The working context.</param>
		/// <returns>Parsed rule patterns.</returns>
		/// <exception cref="System.ArgumentException">
		///     One of the rules has invalid pattern.
		/// </exception>
		protected Rules ParseRules(ConfuserProject proj, ProjectModule module, ConfuserContext context) {
			var ret = new Rules();
			var parser = new PatternParser();
			foreach (Rule rule in proj.Rules.Concat(module.Rules)) {
				try {
					ret.Add(rule, parser.Parse(rule.Pattern));
				}
				catch (InvalidPatternException ex) {
					context.Logger.ErrorFormat("Invalid rule pattern: " + rule.Pattern + ".", ex);
					throw new ConfuserException(ex);
				}
				foreach (var setting in rule) {
					if (!protections.ContainsKey(setting.Id)) {
						context.Logger.ErrorFormat("Cannot find protection with ID '{0}'.", setting.Id);
						throw new ConfuserException(null);
					}
				}
			}
			return ret;
		}
コード例 #41
0
ファイル: Marker.cs プロジェクト: EmilZhou/ConfuserEx
		/// <summary>
		///     Loads the assembly and marks the project.
		/// </summary>
		/// <param name="proj">The project.</param>
		/// <param name="context">The working context.</param>
		/// <returns><see cref="MarkerResult" /> storing the marked modules and packer information.</returns>
		protected internal virtual MarkerResult MarkProject(ConfuserProject proj, ConfuserContext context) {
			Packer packer = null;
			Dictionary<string, string> packerParams = null;

			if (proj.Packer != null) {
				if (!packers.ContainsKey(proj.Packer.Id)) {
					context.Logger.ErrorFormat("Cannot find packer with ID '{0}'.", proj.Packer.Id);
					throw new ConfuserException(null);
				}
				if (proj.Debug)
					context.Logger.Warn("Generated Debug symbols might not be usable with packers!");

				packer = packers[proj.Packer.Id];
				packerParams = new Dictionary<string, string>(proj.Packer, StringComparer.OrdinalIgnoreCase);
			}

			var modules = new List<Tuple<ProjectModule, ModuleDefMD>>();
			var extModules = new List<byte[]>();
			foreach (ProjectModule module in proj) {
				if (module.IsExternal) {
					extModules.Add(module.LoadRaw(proj.BaseDirectory));
					continue;
				}

				ModuleDefMD modDef = module.Resolve(proj.BaseDirectory, context.Resolver.DefaultModuleContext);
				context.CheckCancellation();

				if (proj.Debug)
					modDef.LoadPdb();

				context.Resolver.AddToCache(modDef);
				modules.Add(Tuple.Create(module, modDef));
			}

			foreach (var module in modules) {
				context.Logger.InfoFormat("Loading '{0}'...", module.Item1.Path);
				Rules rules = ParseRules(proj, module.Item1, context);

				context.Annotations.Set(module.Item2, SNKey, LoadSNKey(context, module.Item1.SNKeyPath == null ? null : Path.Combine(proj.BaseDirectory, module.Item1.SNKeyPath), module.Item1.SNKeyPassword));
				context.Annotations.Set(module.Item2, RulesKey, rules);

				foreach (IDnlibDef def in module.Item2.FindDefinitions()) {
					ApplyRules(context, def, rules);
					context.CheckCancellation();
				}

				// Packer parameters are stored in modules
				if (packerParams != null)
					ProtectionParameters.GetParameters(context, module.Item2)[packer] = packerParams;
			}
			return new MarkerResult(modules.Select(module => module.Item2).ToList(), packer, extModules);
		}
コード例 #42
0
ファイル: Program.cs プロジェクト: EmilZhou/ConfuserEx
		static int Main(string[] args) {
			ConsoleColor original = Console.ForegroundColor;
			Console.ForegroundColor = ConsoleColor.White;
			string originalTitle = Console.Title;
			Console.Title = "ConfuserEx";
			try {
				bool noPause = false;
				bool debug = false;
				string outDir = null;
				List<string> probePaths = new List<string>();
				List<string> plugins = new List<string>();
				var p = new OptionSet {
					{
						"n|nopause", "no pause after finishing protection.",
						value => { noPause = (value != null); }
					}, {
						"o|out=", "specifies output directory.",
						value => { outDir = value; }
					}, {
						"probe=", "specifies probe directory.",
						value => { probePaths.Add(value); }
					}, {
						"plugin=", "specifies plugin path.",
						value => { plugins.Add(value); }
					}, {
						"debug", "specifies debug symbol generation.",
						value => { debug = (value != null); }
					}
				};

				List<string> files;
				try {
					files = p.Parse(args);
					if (files.Count == 0)
						throw new ArgumentException("No input files specified.");
				}
				catch (Exception ex) {
					Console.Write("ConfuserEx.CLI: ");
					Console.WriteLine(ex.Message);
					PrintUsage();
					return -1;
				}

				var parameters = new ConfuserParameters();

				if (files.Count == 1 && Path.GetExtension(files[0]) == ".crproj") {
					var proj = new ConfuserProject();
					try {
						var xmlDoc = new XmlDocument();
						xmlDoc.Load(files[0]);
						proj.Load(xmlDoc);
						proj.BaseDirectory = Path.Combine(Path.GetDirectoryName(files[0]), proj.BaseDirectory);
					}
					catch (Exception ex) {
						WriteLineWithColor(ConsoleColor.Red, "Failed to load project:");
						WriteLineWithColor(ConsoleColor.Red, ex.ToString());
						return -1;
					}

					parameters.Project = proj;
				}
				else {
					if (string.IsNullOrEmpty(outDir)) {
						Console.WriteLine("ConfuserEx.CLI: No output directory specified.");
						PrintUsage();
						return -1;
					}

					var proj = new ConfuserProject();

					if (Path.GetExtension(files[files.Count - 1]) == ".crproj") {
						var templateProj = new ConfuserProject();
						var xmlDoc = new XmlDocument();
						xmlDoc.Load(files[files.Count - 1]);
						templateProj.Load(xmlDoc);
						files.RemoveAt(files.Count - 1);

						foreach (var rule in templateProj.Rules)
							proj.Rules.Add(rule);
					}

					// Generate a ConfuserProject for input modules
					// Assuming first file = main module
					foreach (var input in files)
						proj.Add(new ProjectModule { Path = input });

					proj.BaseDirectory = Path.GetDirectoryName(files[0]);
					proj.OutputDirectory = outDir;
					foreach (var path in probePaths)
						proj.ProbePaths.Add(path);
					foreach (var path in plugins)
						proj.PluginPaths.Add(path);
					proj.Debug = debug;
					parameters.Project = proj;
				}

				int retVal = RunProject(parameters);

				if (NeedPause() && !noPause) {
					Console.WriteLine("Press any key to continue...");
					Console.ReadKey(true);
				}

				return retVal;
			}
			finally {
				Console.ForegroundColor = original;
				Console.Title = originalTitle;
			}
		}
コード例 #43
0
ファイル: AppVM.cs プロジェクト: EmilZhou/ConfuserEx
		void OpenProj() {
			if (!PromptSave())
				return;

			var ofd = new VistaOpenFileDialog();
			ofd.Filter = "ConfuserEx Projects (*.crproj)|*.crproj|All Files (*.*)|*.*";
			if ((ofd.ShowDialog(Application.Current.MainWindow) ?? false) && ofd.FileName != null) {
				string fileName = ofd.FileName;
				try {
					var xmlDoc = new XmlDocument();
					xmlDoc.Load(fileName);
					var proj = new ConfuserProject();
					proj.Load(xmlDoc);
					Project = new ProjectVM(proj, fileName);
					FileName = fileName;
				}
				catch {
					MessageBox.Show("Invalid project!", "ConfuserEx", MessageBoxButton.OK, MessageBoxImage.Error);
				}
			}
		}
コード例 #44
0
ファイル: MainWindow.xaml.cs プロジェクト: n017/Confuser
        private void Open_Click(object sender, RoutedEventArgs e)
        {
            if (Project.IsModified)
            {
                switch (MessageBox.Show(
                    "You have unsaved changes in this project!\r\nDo you want to save them?",
                    "Confuser", MessageBoxButton.YesNoCancel, MessageBoxImage.Question))
                {
                    case MessageBoxResult.Yes:
                        Save_Click(this, new RoutedEventArgs());
                        break;
                    case MessageBoxResult.No:
                        break;
                    case MessageBoxResult.Cancel:
                        return;
                }
            }

            OpenFileDialog sfd = new OpenFileDialog();
            sfd.Filter = "Confuser Project (*.crproj)|*.crproj|All Files (*.*)|*.*";
            if (sfd.ShowDialog() ?? false)
            {
                try
                {
                    XmlDocument xmlDoc = new XmlDocument();
                    xmlDoc.Load(sfd.FileName);

                    ConfuserProject proj = new ConfuserProject();
                    proj.Load(xmlDoc);

                    Prj prj = new Prj();
                    prj.FromConfuserProject(proj);
                    prj.FileName = sfd.FileName;

                    Project = prj;
                    foreach (ConfuserTab i in Tab.Items)
                        i.InitProj();
                    prj.PropertyChanged += new PropertyChangedEventHandler(ProjectChanged);
                    prj.IsModified = false;
                    ProjectChanged(Project, new PropertyChangedEventArgs(""));
                    Tab.SelectedIndex = 0;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(string.Format(
            @"Invalid project file!
            Message : {0}
            Stack Trace : {1}", ex.Message, ex.StackTrace), "Confuser", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
        }
コード例 #45
0
ファイル: MainWindow.xaml.cs プロジェクト: n017/Confuser
        public void LoadPrj(string path)
        {
            if (Project.IsModified)
            {
                switch (MessageBox.Show(
                    "You have unsaved changes in this project!\r\nDo you want to save them?",
                    "Confuser", MessageBoxButton.YesNoCancel, MessageBoxImage.Question))
                {
                    case MessageBoxResult.Yes:
                        Save_Click(this, new RoutedEventArgs());
                        break;
                    case MessageBoxResult.No:
                        break;
                    case MessageBoxResult.Cancel:
                        return;
                }
            }

            try
            {
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load(path);

                ConfuserProject proj = new ConfuserProject();
                proj.Load(xmlDoc);

                Prj prj = new Prj();
                prj.FileName = path;
                prj.FromConfuserProject(proj);

                Project = prj;
                foreach (ConfuserTab i in Tab.Items)
                    i.InitProj();
                prj.PropertyChanged += new PropertyChangedEventHandler(ProjectChanged);
                prj.IsModified = false;
                ProjectChanged(Project, new PropertyChangedEventArgs(""));
                Tab.SelectedIndex = 0;
            }
            catch (Exception ex)
            {
                MessageBox.Show(string.Format(
            @"Invalid project file!
            Message : {0}
            Stack Trace : {1}", ex.Message, ex.StackTrace), "Confuser", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
コード例 #46
0
ファイル: Packer.cs プロジェクト: cybercircuits/ConfuserEx
 protected internal override MarkerResult MarkProject(ConfuserProject proj, ConfuserContext context)
 {
     MarkerResult result = base.MarkProject(proj, context);
     foreach (ModuleDefMD module in result.Modules)
         context.Annotations.Set(module, SNKey, snKey);
     return result;
 }