Ejemplo n.º 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);
        }
Ejemplo n.º 2
0
        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"));
        }
Ejemplo n.º 3
0
        void DoProtect()
        {
            var parameters = new ConfuserParameters
            {
                Project = ((IViewModel <ConfuserProject>)App.Project).Model
            };

            if (File.Exists(App.FileName))
            {
                Environment.CurrentDirectory = Path.GetDirectoryName(App.FileName);
            }

            parameters.Logger = this;

            documentContent.Inlines.Clear();
            cancelSrc = new CancellationTokenSource();
            Result    = null;
            Progress  = null;
            begin     = DateTime.Now;
            App.NavigationDisabled = true;

            ConfuserEngine.Run(parameters, cancelSrc.Token)
            .ContinueWith(_ =>
                          Application.Current.Dispatcher.BeginInvoke(new Action(() => {
                Progress = 0;
                App.NavigationDisabled = false;
                CommandManager.InvalidateRequerySuggested();
            })));
        }
Ejemplo n.º 4
0
 // Token: 0x06000002 RID: 2 RVA: 0x00002530 File Offset: 0x00000730
 private static int RunProject(ConfuserParameters parameters)
 {
     Program.ConsoleLogger logger = new Program.ConsoleLogger();
     parameters.Logger = logger;
     Console.Title     = "DarksProtector v" + ConfuserEngine.Version + " - Running...";
     ConfuserEngine.Run(parameters, null).Wait();
     return(logger.ReturnValue);
 }
Ejemplo n.º 5
0
        static int RunProject(ConfuserParameters parameters)
        {
            var logger = new ConsoleLogger();

            parameters.Logger = logger;

            ConfuserEngine.Run(parameters).Wait();

            return(logger.ReturnValue);
        }
Ejemplo n.º 6
0
        private static int RunProject(ConfuserParameters parameters)
        {
            var logger = new ConsoleLogger();

            parameters.Logger = logger;

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

            return(logger.ReturnValue);
        }
Ejemplo n.º 7
0
        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;
            }
        }
Ejemplo n.º 8
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);
        }
Ejemplo n.º 9
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";
            });
        }
Ejemplo n.º 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(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);
        }
Ejemplo n.º 11
0
        string ProtectRT(ConfuserContext context, string fileName)
        {
            string outDir = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());

            Directory.CreateDirectory(outDir);

            var proj = new ConfuserProject();

            proj.Seed  = context.Project.Seed;
            proj.Debug = context.Project.Debug;
            //foreach (Rule rule in context.Project.Rules) {
            //    var r = rule.Clone();
            //    r.RemoveWhere(prot => prot.Id == Parent.Id);
            //    proj.Rules.Add(r);
            //}
            proj.Rules.Add(new Rule {
                new SettingItem <Protection>("anti ildasm"),
                new SettingItem <Protection>("ref proxy")
                {
                    { "mode", "mild" },
                    { "typeErasure", "true" }
                },
                new SettingItem <Protection>("rename")
                {
                    { "mode", "letters" }
                },
            });
            proj.Add(new ProjectModule {
                Path = fileName
            });
            proj.BaseDirectory   = Path.GetDirectoryName(fileName);
            proj.OutputDirectory = outDir;
            foreach (var path in context.Project.ProbePaths)
            {
                proj.ProbePaths.Add(path);
            }
            proj.ProbePaths.Add(context.Project.BaseDirectory);

            StrongNameKey snKey = null;

            foreach (var module in context.Modules)
            {
                snKey = context.Annotations.Get <StrongNameKey>(module, Marker.SNKey);
                if (snKey != null)
                {
                    break;
                }
            }

            try {
                ConfuserEngine.Run(new ConfuserParameters {
                    Logger  = new RTLogger(context.Logger),
                    Marker  = new RTMarker(snKey),
                    Project = proj,
                }, context.CancellationToken).Wait();
            }
            catch (AggregateException ex) {
                context.Logger.Error("Failed to protect Runtime.");
                throw new ConfuserException(ex);
            }

            return(Path.Combine(outDir, Path.GetFileName(fileName)));
        }
Ejemplo n.º 12
0
        internal async Task <bool> ConfuseAssembly(string targetPath, ModuleDefMD targetModule)
        {
            if (string.IsNullOrWhiteSpace(targetPath))
            {
                throw new ArgumentNullException(nameof(targetPath));
            }

            if (targetModule == null)
            {
                throw new ArgumentNullException(nameof(targetModule));
            }

            var targetFile      = Path.GetFileName(targetPath);
            var targetDirectory = Path.GetDirectoryName(targetPath);

            var project = new ConfuserProject
            {
                BaseDirectory   = targetDirectory,
                OutputDirectory = targetDirectory
            };

            // Confuser plugins are merged into the main assembly at build time. Instruct the project to load them from the running executable.
            project.PluginPaths.Add(Assembly.GetExecutingAssembly().Location);

            byte[] rawData;
            using (var ms = new MemoryStream())
            {
                targetModule.Write(ms);
                targetModule.Dispose();
                ms.Seek(0, SeekOrigin.Begin);
                rawData = ms.ToArray();
            }

            if (rawData == null || rawData.Count() == 0)
            {
                return(false);
            }

            ProjectModule projectModule = new ProjectModule
            {
                Path    = targetFile,
                RawData = rawData
            };

            projectModule.Rules.Add(new Rule
            {
                new SettingItem <Protection>("watermark", SettingItemAction.Remove),
                new SettingItem <Protection>("anti debug"),
                new SettingItem <Protection>("anti ildasm"),
                new SettingItem <Protection>("ctrl flow"),
                new SettingItem <Protection>("ref proxy"),
                new SettingItem <Protection>("harden"),
            });

            project.Add(projectModule);

            var parameters = new ConfuserParameters
            {
                Project = project,
                Logger  = this
            };

            await ConfuserEngine.Run(parameters);

            return(_successfullyProtected);
        }
        protected override void ProcessRecord()
        {
            try
            {
                var parameters = new ConfuserParameters
                {
                    Logger  = new ConfuserLogger(),
                    Project = new ConfuserProject()
                };

                parameters.Project.BaseDirectory   = Path.GetDirectoryName(AssemblyFile);
                parameters.Project.OutputDirectory = Path.GetDirectoryName(AssemblyFile);

                if (!Directory.Exists(parameters.Project.OutputDirectory))
                {
                    Directory.CreateDirectory(parameters.Project.OutputDirectory);
                }

                var module = new ProjectModule
                {
                    Path = AssemblyFile
                };

                if (!string.IsNullOrEmpty(KeyFile))
                {
                    module.SNKeyPath = KeyFile;
                }

                parameters.Project.Add(module);

                // Having no protection doesn't make any sense, so recommended settings will be used
                var rule = ((ProtectionPreset)ObfuscationLevel == ProtectionPreset.None) ?
                           new Rule
                {
                    new SettingItem <Protection>("rename", SettingItemAction.Add)
                    {
                        { "mode", "sequential" },
                        { "forceRen", "true" }
                    },

                    new SettingItem <Protection>("ctrl flow", SettingItemAction.Add)
                    {
                        { "intensity", "30" }
                    },

                    new SettingItem <Protection>("constants", SettingItemAction.Add)
                    {
                        { "decoderCount", "10" },
                        { "elements", "SNPI" }
                    }
                }
                    : new Rule(preset: (ProtectionPreset)ObfuscationLevel);

                parameters.Project.Rules.Add(rule);

                ConfuserEngine.Run(parameters).Wait();
            }
            catch (Exception ex)
            {
                WriteVerbose(ex.Message);
                WriteVerbose(ex.StackTrace);

                System.Diagnostics.Debugger.Launch();
            }
        }
Ejemplo n.º 14
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));
        }