コード例 #1
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);
        }
コード例 #2
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);
            }
        }
コード例 #3
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"));
        }
コード例 #4
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);
                }
            }
        }
コード例 #5
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);
                }
            }
        }
コード例 #6
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;
            }
        }
コード例 #7
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);
            }
        }
コード例 #8
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;
            }
        }
コード例 #9
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);
        }
コード例 #10
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);
        }
コード例 #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("Invalid project!", "ConfuserEx", MessageBoxButton.OK, MessageBoxImage.Error);
			}
		}
コード例 #12
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);
        }
コード例 #13
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);
                }
            }
        }
コード例 #14
0
ファイル: Program.cs プロジェクト: rexyrexy/VirtualConfuserEx
        public async Task <bool> ProtectFile()
        {
            ConfuserProject    confuserProject    = new ConfuserProject();
            ConfuserParameters confuserParameters = new ConfuserParameters();

            try
            {
                XmlDocument xmlDocument = new XmlDocument();
                xmlDocument.Load("Dependencies\\VirtualConfuser.Project.dll");
                confuserProject.Load(xmlDocument);
                confuserProject.BaseDirectory   = Directory.GetCurrentDirectory();
                confuserProject.OutputDirectory = Directory.GetCurrentDirectory();
            }
            catch (Exception e)
            {
                //bazi insanlar kadar bombos
            }

            confuserParameters.Project = confuserProject;

            int num = Confuser.CLI.Program.RunProject(confuserParameters);

            return(num == 0);
        }
コード例 #15
0
ファイル: MSBuildTask.cs プロジェクト: zippy1981/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);
        }
コード例 #16
0
        private void ThirteenButton10_Click(object sender, EventArgs e)
        {
            ConfuserProject proj = new ConfuserProject();

            try
            {
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load($"{Directory.GetCurrentDirectory()}\\Projects\\{listBox1.SelectedItem}");
                proj.Load(xmlDoc);
                ProjectVM project = new ProjectVM(proj, $"{Directory.GetCurrentDirectory()}\\Projects\\{listBox1.SelectedItem}");

                foreach (ProjectRuleVM r in project.Rules)
                {
                    foreach (ProjectSettingVM <Protection> s in r.Protections)
                    {
                        UnCheckAllProt();
                        string name = s.Id;

                        if (name == "anti vm")
                        {
                            antivmcheck.Checked = true;
                        }
                        if (name == "anti ildasm")
                        {
                            antiildasmcheck.Checked = true;
                        }
                        if (name == "anti de4dot")
                        {
                            antide4dotcheck.Checked = true;
                        }
                        if (name == "anti debug")
                        {
                            antidebugcheck.Checked = true;
                        }
                        if (name == "anti tamper")
                        {
                            antitampercheck.Checked = true;
                        }
                        if (name == "anti dump")
                        {
                            antidumpcheck.Checked = true;
                        }
                        if (name == "anti watermark")
                        {
                            antiwatermarkcheck.Checked = true;
                        }
                        if (name == "memory protection")
                        {
                            antimemoryeditcheck.Checked = true;
                        }
                        if (name == "calli protection")
                        {
                            callicheck.Checked = true;
                        }
                        if (name == "constants")
                        {
                            constantscheck.Checked = true;
                        }
                        if (name == "ctrl flow")
                        {
                            ctrlflowcheck.Checked = true;
                        }
                        if (name == "Junk")
                        {
                            junkcheck.Checked = true;
                        }
                        if (name == "ref proxy")
                        {
                            refproxycheck.Checked = true;
                        }
                        if (name == "resources")
                        {
                            resourcescheck.Checked = true;
                        }
                        if (name == "rename")
                        {
                            renamercheck.Checked = true;
                        }
                        if (name == "Mutate Constants")
                        {
                            mutateconstantscheck.Checked = true;
                        }
                        if (name == "erase headers")
                        {
                            erasecheck.Checked = true;
                        }
                        if (name == "fake native")
                        {
                            fakenativecheck.Checked = true;
                        }
                        if (name == "lcltofield")
                        {
                            lcltofieldscheck.Checked = true;
                        }
                        if (name == "Rename Module")
                        {
                            modulerenamercheck.Checked = true;
                        }
                        if (name == "stack underflow")
                        {
                            stackunderflowcheck.Checked = true;
                        }
                        if (name == "force elevation")
                        {
                            admincheck.Checked = true;
                        }
                        if (name == "Hide Methods")
                        {
                            hidemethodscheck.Checked = true;
                        }
                        if (name == "invalid metadata")
                        {
                            invalidmetadatacheck.Checked = true;
                        }
                        if (name == "MD5 Hash Check")
                        {
                            md5check.Checked = true;
                        }
                        if (name == "module flood")
                        {
                            modulefloodcheck.Checked = true;
                        }
                        if (name == "fake obfuscator")
                        {
                            fakeobfuscatorcheck.Checked = true;
                        }
                        if (name == "process monitor")
                        {
                            processmonitorcheck.Checked = true;
                        }
                        if (name == "anti dnspy")
                        {
                            antidnspycheck.Checked = true;
                        }
                        if (name == "anti fiddler")
                        {
                            antifiddlercheck.Checked = true;
                        }
                        if (name == "anti http debugger")
                        {
                            antihttpcheck.Checked = true;
                        }
                    }
                }
            }
            catch { }
        }
コード例 #17
0
ファイル: Program.cs プロジェクト: petterlopes/ConfuserEx
        private 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;
            }
        }
コード例 #18
0
        static int Main(string[] args)
        {
            CommandLineApplication app = new CommandLineApplication();

            app.HelpOption("-? | -h | --help");
            app.ThrowOnUnexpectedArgument = false;

            // Required arguments
            CommandOption OutputFileOption = app.Option(
                "-f | --file <OUTPUT_FILE>",
                "The output file to write to.",
                CommandOptionType.SingleValue
                ).IsRequired();

            // Compilation-related arguments
            CommandOption <Compiler.DotNetVersion> DotNetVersionOption = app.Option <Compiler.DotNetVersion>(
                "-d | --dotnet | --dotnet-framework <DOTNET_VERSION>",
                "The Dotnet Framework version to target (net35 or net40).",
                CommandOptionType.SingleValue
                );

            DotNetVersionOption.Validators.Add(new MustBeDotNetVersionValidator());
            CommandOption OutputKindOption = app.Option(
                "-o | --output-kind <OUTPUT_KIND>",
                "The OutputKind to use (dll or console).",
                CommandOptionType.SingleValue
                );

            OutputKindOption.Validators.Add(new MustBeOutputKindValidator());
            CommandOption PlatformOption = app.Option(
                "-p | --platform <PLATFORM>",
                "The Platform to use (AnyCpy, x86, or x64).",
                CommandOptionType.SingleValue
                );

            PlatformOption.Validators.Add(new MustBePlatformValidator());
            CommandOption NoOptimizationOption = app.Option(
                "-n | --no-optimization",
                "Don't use source code optimization.",
                CommandOptionType.NoValue
                );
            CommandOption AssemblyNameOption = app.Option(
                "-a | --assembly-name <ASSEMBLY_NAME>",
                "The name of the assembly to be generated.",
                CommandOptionType.SingleValue
                );

            AssemblyNameOption.Validators.Add(new MustBeIdentifierValidator());

            // Source-related arguments
            CommandOption SourceFileOption = app.Option(
                "-s | --source-file <SOURCE_FILE>",
                "The source code to compile.",
                CommandOptionType.SingleValue
                ).Accepts(v => v.ExistingFile());
            CommandOption ClassNameOption = app.Option(
                "-c | --class-name <CLASS_NAME>",
                "The name of the class to be generated.",
                CommandOptionType.SingleValue
                );

            ClassNameOption.Validators.Add(new MustBeIdentifierValidator());

            CommandOption ConfuseOption = app.Option(
                "--confuse <CONFUSEREX_PROJECT_FILE>",
                "The ConfuserEx ProjectFile configuration.",
                CommandOptionType.SingleValue
                ).Accepts(v => v.ExistingFile());

            app.OnExecute(() =>
            {
                Compiler.CompilationRequest request = new Compiler.CompilationRequest();
                // Compilation options
                if (!SetRequestDirectories(ref request))
                {
                    SharpGenConsole.PrintFormattedErrorLine("Unable to specify CompilationRequest directories");
                    app.ShowHelp();
                    return(-1);
                }
                if (!SetRequestDotNetVersion(DotNetVersionOption, ref request))
                {
                    SharpGenConsole.PrintFormattedErrorLine("Invalid DotNetVersion specified.");
                    app.ShowHelp();
                    return(-2);
                }
                if (!SetRequestOutputKind(OutputKindOption, OutputFileOption, ref request))
                {
                    SharpGenConsole.PrintFormattedErrorLine("Invalid OutputKind specified.");
                    app.ShowHelp();
                    return(-3);
                }
                if (!SetRequestPlatform(PlatformOption, ref request))
                {
                    SharpGenConsole.PrintFormattedErrorLine("Invalid Platform specified.");
                    app.ShowHelp();
                    return(-4);
                }
                if (!SetRequestOptimization(NoOptimizationOption, ref request))
                {
                    SharpGenConsole.PrintFormattedErrorLine("Invalid NoOptimization specified.");
                    app.ShowHelp();
                    return(-5);
                }
                if (!SetRequestAssemblyName(AssemblyNameOption, ref request))
                {
                    SharpGenConsole.PrintFormattedErrorLine("Invalid AssemblyName specified.");
                    app.ShowHelp();
                    return(-6);
                }
                if (!SetRequestReferences(ref request))
                {
                    SharpGenConsole.PrintFormattedErrorLine("Unable to set CompilationRequest references.");
                    app.ShowHelp();
                    return(-7);
                }
                if (!SetRequestEmbeddedResources(ref request))
                {
                    SharpGenConsole.PrintFormattedErrorLine("Unable to set CompilationRequest resources.");
                    app.ShowHelp();
                    return(-8);
                }

                // Source options
                if (!SetRequestSource(SourceFileOption, ClassNameOption, app.RemainingArguments, ref request))
                {
                    SharpGenConsole.PrintFormattedErrorLine("Unable to create source code for request.");
                    app.ShowHelp();
                    return(-9);
                }

                // Compile
                SharpGenConsole.PrintFormattedProgressLine("Compiling source: ");
                SharpGenConsole.PrintInfoLine(request.Source);
                try
                {
                    byte[] compiled = Compiler.Compile(request);

                    // Write to file
                    string path = Path.Combine(Common.SharpGenOutputDirectory, OutputFileOption.Value());
                    File.WriteAllBytes(path, compiled);

                    if (ConfuseOption.HasValue())
                    {
                        ConfuserProject project    = new ConfuserProject();
                        System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
                        string ProjectFile         = String.Format(
                            File.ReadAllText(ConfuseOption.Value()),
                            Common.SharpGenOutputDirectory,
                            Common.SharpGenOutputDirectory,
                            OutputFileOption.Value()
                            );
                        doc.Load(new StringReader(ProjectFile));
                        project.Load(doc);
                        project.ProbePaths.Add(Common.Net35Directory);
                        project.ProbePaths.Add(Common.Net40Directory);

                        SharpGenConsole.PrintFormattedProgressLine("Confusing assembly...");
                        ConfuserParameters parameters = new ConfuserParameters();
                        parameters.Project            = project;
                        parameters.Logger             = new ConfuserConsoleLogger();
                        Directory.SetCurrentDirectory(Common.SharpGenRefsDirectory);
                        ConfuserEngine.Run(parameters).Wait();
                    }

                    SharpGenConsole.PrintFormattedHighlightLine("Compiled assembly written to: " + path);
                }
                catch (CompilerException e)
                {
                    SharpGenConsole.PrintFormattedErrorLine(e.Message);
                    return(-10);
                }
                catch (ConfuserException e)
                {
                    SharpGenConsole.PrintFormattedErrorLine("Confuser Exception: " + e.Message);
                    return(-11);
                }
                return(0);
            });
            return(app.Execute(args));
        }
コード例 #19
0
        static int Main(string[] args)
        {
            ConsoleColor original = Console.ForegroundColor;

            UriParser.Register(new GenericUriParser(GenericUriParserOptions.GenericAuthority), "pack", -1);

            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
                {
                    if (string.IsNullOrEmpty(outDir))
                    {
                        Console.WriteLine("ConfuserEx.CLI: No output directory specified.");
                        PrintUsage();
                        return(-1);
                    }

                    // 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;
            }
        }
コード例 #20
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);
				}
			}
		}
コード例 #21
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;
			}
		}
コード例 #22
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);
            }
        }
コード例 #23
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);
                }
            }
        }
コード例 #24
0
ファイル: Program.cs プロジェクト: naderr1ua/DarksProtector
        private static int Main(string[] args)
        {
            ConsoleColor original = Console.ForegroundColor;

            Console.ForegroundColor = ConsoleColor.White;
            Console.Title           = "DarksProtector v" + ConfuserEngine.Version;
            Title();
            int result;

            try
            {
                bool          noPause    = false;
                bool          debug      = false;
                string        outDir     = null;
                List <string> probePaths = new List <string>();
                List <string> plugins    = new List <string>();
                OptionSet     p          = new OptionSet
                {
                    {
                        "n|nopause",
                        "no pause after finishing protection.",
                        delegate(string value)
                        {
                            noPause = (value != null);
                        }
                    },
                    {
                        "o|out=",
                        "specifies output directory.",
                        delegate(string value)
                        {
                            outDir = value;
                        }
                    },
                    {
                        "probe=",
                        "specifies probe directory.",
                        delegate(string value)
                        {
                            probePaths.Add(value);
                        }
                    },
                    {
                        "plugin=",
                        "specifies plugin path.",
                        delegate(string value)
                        {
                            plugins.Add(value);
                        }
                    },
                    {
                        "debug",
                        "specifies debug symbol generation.",
                        delegate(string value)
                        {
                            debug = (value != null);
                        }
                    }
                };
                List <string> files;
                try
                {
                    files = p.Parse(args);
                    bool flag = files.Count == 0;
                    if (flag)
                    {
                        throw new ArgumentException("No input files specified.");
                    }
                }
                catch (Exception ex)
                {
                    Input("ERROR: " + ex.Message);
                    return(-1);
                }
                ConfuserParameters parameters = new ConfuserParameters();
                bool flag2 = files.Count == 1 && Path.GetExtension(files[0]) == ".darkpr";
                if (flag2)
                {
                    ConfuserProject proj = new ConfuserProject();
                    try
                    {
                        XmlDocument xmlDoc = new XmlDocument();
                        xmlDoc.Load(files[0]);
                        proj.Load(xmlDoc);
                        proj.BaseDirectory = Path.Combine(Path.GetDirectoryName(files[0]), proj.BaseDirectory);
                    }
                    catch (Exception ex2)
                    {
                        Program.WriteLineWithColor(ConsoleColor.Red, "Failed to load project:");
                        Program.WriteLineWithColor(ConsoleColor.Red, ex2.ToString());
                        return(-1);
                    }
                    parameters.Project = proj;
                }
                int  retVal = Program.RunProject(parameters);
                bool flag5  = Program.NeedPause() && !noPause;
                if (flag5)
                {
                    Credits();
                    Input("Press any key to close...");
                    Console.ReadKey(true);
                }
                result = retVal;
            }
            finally
            {
                Console.ForegroundColor = original;
            }
            return(result);

            /*Input("Logging in...");
             * if(!File.Exists("key.txt"))
             * {
             *  Input("ERROR: Invalid key, please fill key.txt with a valid c.to auth key!");
             *  Input("Press any key to close...");
             *  Console.ReadKey(true);
             *  Environment.Exit(-1);
             *  return -1;
             * }
             * string key = File.ReadAllText("key.txt");
             * try
             * {
             *  using (HttpRequest httpRequest = new HttpRequest())
             *  {
             *      httpRequest.IgnoreProtocolErrors = true;
             *      httpRequest.Proxy = null;
             *      httpRequest.UserAgent = Http.ChromeUserAgent();
             *      httpRequest.ConnectTimeout = 30000;
             *      string text = httpRequest.Post("https://cracked.to/auth.php", "a=auth&k=" + key + "&hwid=" + gethwid(), "application/x-www-form-urlencoded").ToString();
             *      Dictionary<string, string> response = JsonConvert.DeserializeObject<Dictionary<string, string>>(text);
             *      if (text.Contains("error"))
             *      {
             *          Input("ERROR: Invalid key, please fill key.txt with a valid c.to auth key!");
             *          Input("Press any key to close...");
             *          Console.ReadKey(true);
             *          Environment.Exit(-1);
             *          return -1;
             *      }
             *      else if (text.Contains("auth"))
             *      {
             *          int result;
             *          try
             *          {
             *              bool noPause = false;
             *              bool debug = false;
             *              string outDir = null;
             *              List<string> probePaths = new List<string>();
             *              List<string> plugins = new List<string>();
             *              OptionSet p = new OptionSet
             *              {
             *                  {
             *                      "n|nopause",
             *                      "no pause after finishing protection.",
             *                      delegate(string value)
             *                      {
             *                          noPause = (value != null);
             *                      }
             *                  },
             *                  {
             *                      "o|out=",
             *                      "specifies output directory.",
             *                      delegate(string value)
             *                      {
             *                          outDir = value;
             *                      }
             *                  },
             *                  {
             *                      "probe=",
             *                      "specifies probe directory.",
             *                      delegate(string value)
             *                      {
             *                          probePaths.Add(value);
             *                      }
             *                  },
             *                  {
             *                      "plugin=",
             *                      "specifies plugin path.",
             *                      delegate(string value)
             *                      {
             *                          plugins.Add(value);
             *                      }
             *                  },
             *                  {
             *                      "debug",
             *                      "specifies debug symbol generation.",
             *                      delegate(string value)
             *                      {
             *                          debug = (value != null);
             *                      }
             *                  }
             *              };
             *              List<string> files;
             *              try
             *              {
             *                  files = p.Parse(args);
             *                  bool flag = files.Count == 0;
             *                  if (flag)
             *                  {
             *                      throw new ArgumentException("No input files specified.");
             *                  }
             *              }
             *              catch (Exception ex)
             *              {
             *                  Input("ERROR: " + ex.Message);
             *                  return -1;
             *              }
             *              ConfuserParameters parameters = new ConfuserParameters();
             *              bool flag2 = files.Count == 1 && Path.GetExtension(files[0]) == ".darkpr";
             *              if (flag2)
             *              {
             *                  ConfuserProject proj = new ConfuserProject();
             *                  try
             *                  {
             *                      XmlDocument xmlDoc = new XmlDocument();
             *                      xmlDoc.Load(files[0]);
             *                      proj.Load(xmlDoc);
             *                      proj.BaseDirectory = Path.Combine(Path.GetDirectoryName(files[0]), proj.BaseDirectory);
             *                  }
             *                  catch (Exception ex2)
             *                  {
             *                      Program.WriteLineWithColor(ConsoleColor.Red, "Failed to load project:");
             *                      Program.WriteLineWithColor(ConsoleColor.Red, ex2.ToString());
             *                      return -1;
             *                  }
             *                  parameters.Project = proj;
             *              }
             *              int retVal = Program.RunProject(parameters);
             *              bool flag5 = Program.NeedPause() && !noPause;
             *              if (flag5)
             *              {
             *                  Credits();
             *                  Input("Press any key to close...");
             *                  Console.ReadKey(true);
             *              }
             *              result = retVal;
             *          }
             *          finally
             *          {
             *              Console.ForegroundColor = original;
             *          }
             *          return result;
             *      }
             *      else
             *      {
             *          Input("ERROR: Invalid key, please fill key.txt with a valid c.to auth key!");
             *          Environment.Exit(-1);
             *          return -1;
             *      }
             *  }
             * }
             * catch (Exception ex)
             * {
             *  Input("ERROR: " + ex.Message);
             *  Environment.Exit(-1);
             *  return -1;
             * }*/
        }
コード例 #25
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;
        }
コード例 #26
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;
            }
        }
コード例 #27
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;
        }
コード例 #28
0
        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);
        }