public Configuration Cross(Mutator mutator, Configuration other, int count) { Configuration configuration = new Configuration(_knapsack); mutator.Mutate(configuration._presence, count); for (int i = 0; i < _presence.Length; i++) { configuration._presence[i] = configuration._presence[i] ? other._presence[i] : _presence[i]; } return configuration; }
public void WhenMutationIsRequested_Double_FullRandomMethod_AllValuesChanged() { Population <double> population = new Population <double> (); population.Initialise(1, 100000); double[] beforeMutation = population[0].Code.Select(i => i).ToArray(); Mutator <double> mutator = MutationProvider.GetMutator <double> (); ConfigurationProvider.Mutation.ChanceOfMutation = 1; mutator.Mutate(population); population[0].Code.For((item, i) => { Assert.AreNotEqual(beforeMutation[i], item); }); }
public void WhenMutationIsRequested_Int_Chance100pc_AllValuesChanged() { Population <int> population = new Population <int> (); population.Initialise(1, 1000); int[] beforeMutation = population[0].Code.Select(i => i).ToArray(); Mutator <int> mutator = MutationProvider.GetMutator <int> (); ConfigurationProvider.Mutation.ChanceOfMutation = 1; mutator.Mutate(population); population[0].Code.For((item, i) => { Assert.AreNotEqual(beforeMutation[i], item); }); }
public void WhenMutationIsRequested_Byte_Chance0pc_NoValuesChanged() { Population <byte> population = new Population <byte> (); population.Initialise(1, 1000); byte[] beforeMutation = population [0].Code.Select(i => i).ToArray(); Mutator <byte> mutator = MutationProvider.GetMutator <byte> (); ConfigurationProvider.Mutation.ChanceOfMutation = 0; mutator.Mutate(population); population[0].Code.For((item, i) => { Assert.AreEqual(beforeMutation[i], item); }); }
protected override TypeSpec[] ResolveBaseTypes(out FullNamedExpression base_class) { var mtype = Iterator.OriginalIteratorType; if (Mutator != null) { mtype = Mutator.Mutate(mtype); } iterator_type_expr = new TypeExpression(mtype, Location); generic_args = new TypeArguments(iterator_type_expr); var list = new List <FullNamedExpression> (); if (Iterator.IsEnumerable) { enumerable_type = new TypeExpression(Compiler.BuiltinTypes.IEnumerable, Location); list.Add(enumerable_type); if (Module.PredefinedTypes.IEnumerableGeneric.Define()) { generic_enumerable_type = new GenericTypeExpr(Module.PredefinedTypes.IEnumerableGeneric.TypeSpec, generic_args, Location); list.Add(generic_enumerable_type); } } enumerator_type = new TypeExpression(Compiler.BuiltinTypes.IEnumerator, Location); list.Add(enumerator_type); list.Add(new TypeExpression(Compiler.BuiltinTypes.IDisposable, Location)); var ienumerator_generic = Module.PredefinedTypes.IEnumeratorGeneric; if (ienumerator_generic.Define()) { generic_enumerator_type = new GenericTypeExpr(ienumerator_generic.TypeSpec, generic_args, Location); list.Add(generic_enumerator_type); } type_bases = list; return(base.ResolveBaseTypes(out base_class)); }
public void WhenMutationIsRequested_Int_ContextMethod_AllValuesChangedWithinVariance() { Population <int> population = new Population <int> (); (InitialiserContextProvider.GetContext <int>() as IntBasedGenomeInitialiserContext).Min = 100; (InitialiserContextProvider.GetContext <int>() as IntBasedGenomeInitialiserContext).Max = 200; population.Initialise(1, 10000); ConfigurationProvider.Mutation.ChanceOfMutation = 1; ConfigurationProvider.Mutation.MutationMethod = MutationConfiguration.MutationStyle.Variance; ConfigurationProvider.Mutation.ContextMutationVariance = .25; Mutator <int> mutator = MutationProvider.GetMutator <int> (); population[0].Code.For((item, i) => { int mod5 = i % 5; population[0].Code [i] = 10 + ((mod5 % 5) * 10) + (InitialiserContextProvider.GetContext <int>() as IntBasedGenomeInitialiserContext).Min; }); mutator.Mutate(population); int variance = 25; population[0].Code.For((item, i) => { int mod5 = i % 5; int original = 10 + ((mod5 % 5) * 10) + (InitialiserContextProvider.GetContext <int>() as IntBasedGenomeInitialiserContext).Min; int min = original - variance; int max = original + variance; Assert.GreaterOrEqual(item, min); Assert.LessOrEqual(item, max); }); }
protected override TypeSpec[] ResolveBaseTypes(out FullNamedExpression base_class) { var mtype = Iterator.OriginalIteratorType; if (Mutator != null) { mtype = Mutator.Mutate(mtype); } iterator_type_expr = new TypeExpression(mtype, Location); var ifaces = new List <TypeSpec> (5); if (Iterator.IsEnumerable) { ifaces.Add(Compiler.BuiltinTypes.IEnumerable); if (Module.PredefinedTypes.IEnumerableGeneric.Define()) { generic_enumerable_type = Module.PredefinedTypes.IEnumerableGeneric.TypeSpec.MakeGenericType(Module, new[] { mtype }); ifaces.Add(generic_enumerable_type); } } ifaces.Add(Compiler.BuiltinTypes.IEnumerator); ifaces.Add(Compiler.BuiltinTypes.IDisposable); var ienumerator_generic = Module.PredefinedTypes.IEnumeratorGeneric; if (ienumerator_generic.Define()) { generic_enumerator_type = ienumerator_generic.TypeSpec.MakeGenericType(Module, new [] { mtype }); ifaces.Add(generic_enumerator_type); } base_class = null; base_type = Compiler.BuiltinTypes.Object; return(ifaces.ToArray()); }
public void WhenMutationIsRequested_Double_ContextMethod_VarianceIsApprox50pcNegativeVariance() { var population = new Population <double> (); (InitialiserContextProvider.GetContext <double> () as DoubleBasedGenomeInitialiserContext).Min = 100d; (InitialiserContextProvider.GetContext <double> () as DoubleBasedGenomeInitialiserContext).Max = 200d; var genomeCount = 10000; population.Initialise(1, genomeCount); ConfigurationProvider.Mutation.ChanceOfMutation = 1; ConfigurationProvider.Mutation.MutationMethod = MutationConfiguration.MutationStyle.Variance; ConfigurationProvider.Mutation.ContextMutationVariance = .25; Mutator <double> mutator = MutationProvider.GetMutator <double> (); population [0].Code.For((item, i) => { population [0].Code [i] = 150; }); mutator.Mutate(population); int negativeVarianceCount = 0; population [0].Code.For((item, i) => { if (item < 150) { negativeVarianceCount += 1; } }); //assume between 45% and 55% double acceptableMin = (double)genomeCount * ((double)4.5 / 10); double acceptableMax = (double)genomeCount * ((double)5.5 / 10); Assert.GreaterOrEqual(negativeVarianceCount, acceptableMin); Assert.LessOrEqual(negativeVarianceCount, acceptableMax); }
public void MutatorTest4() { Organism organism = new Organism(); organism.Chromosomes.Add(new Chromosome(1, "10")); int runCount = 100000; double mutationProbability = 0; MutationCounter mutator = new MutationCounter(); IRandom rand = new Rand(); Mutator mutationManager = new Mutator(rand, mutationProbability); mutationManager.AddMutator(mutator); for (int i = 0; i <= runCount - 1; i++) { mutationManager.Mutate(organism); } Assert.AreEqual(0, mutator.MutationCount); Assert.AreEqual("10", organism.Chromosomes[0].ToString()); }
public void WhenMutationIsSetToVariance_Double_CheckedOverflow_MutationLessThanMinFloorAtMin() { var population = new Population <double> (); (InitialiserContextProvider.GetContext <double> () as DoubleBasedGenomeInitialiserContext).Min = 10d; (InitialiserContextProvider.GetContext <double> () as DoubleBasedGenomeInitialiserContext).Max = 110d; DoubleBasedSingleInitialiser initialiser = new DoubleBasedSingleInitialiser( (InitialiserContextProvider.GetContext <double> () as DoubleBasedGenomeInitialiserContext).Min); InitialiserProvider.AddInitialiser(initialiser); var genomeLength = 100000; population.Initialise(1, genomeLength); ConfigurationProvider.Mutation.AllowUncheckedVariance = false; ConfigurationProvider.Mutation.ChanceOfMutation = 1; ConfigurationProvider.Mutation.ContextMutationVariance = .1; ConfigurationProvider.Mutation.MutationMethod = MutationConfiguration.MutationStyle.Variance; Mutator <double> mutator = MutationProvider.GetMutator <double> (); mutator.Mutate(population); int underflowCount = 0; population [0].Code.ForEach(i => { underflowCount += i == (InitialiserContextProvider.GetContext <double> () as DoubleBasedGenomeInitialiserContext).Min ? 1 : 0; }); double acceptableMin = (double)genomeLength * ((double)4.5d / 10); double acceptableMax = (double)genomeLength * ((double)5.5d / 10); Assert.LessOrEqual(underflowCount, acceptableMax); Assert.GreaterOrEqual(underflowCount, acceptableMin); }
public void WhenMutationIsSetToVariance_Byte_UncheckedOverflow_MutationLessThanMinUnderflowToMax() { Population <byte> population = new Population <byte> (); (InitialiserContextProvider.GetContext <byte> () as ByteBasedGenomeInitialiserContext).Min = 0; (InitialiserContextProvider.GetContext <byte> () as ByteBasedGenomeInitialiserContext).Max = 100; ByteBasedSingleInitialiser initialiser = new ByteBasedSingleInitialiser( (InitialiserContextProvider.GetContext <byte> () as ByteBasedGenomeInitialiserContext).Min); InitialiserProvider.AddInitialiser(initialiser); var genomeLength = 1000; population.Initialise(1, genomeLength); ConfigurationProvider.Mutation.AllowUncheckedVariance = true; ConfigurationProvider.Mutation.ChanceOfMutation = 1; ConfigurationProvider.Mutation.ContextMutationVariance = .1; ConfigurationProvider.Mutation.MutationMethod = MutationConfiguration.MutationStyle.Variance; Mutator <byte> mutator = MutationProvider.GetMutator <byte> (); mutator.Mutate(population); int overflowCount = 0; population [0].Code.ForEach(i => { overflowCount += i >= 90 ? 1 : 0; }); double acceptableMin = (double)genomeLength * ((double)4.5d / 10); double acceptableMax = (double)genomeLength * ((double)5.5d / 10); Assert.LessOrEqual(overflowCount, acceptableMax); Assert.GreaterOrEqual(overflowCount, acceptableMin); }
public void Phase1(ModuleDefinition mod) { AssemblyDefinition i = AssemblyDefinition.ReadAssembly(typeof(Iid).Assembly.Location); i.MainModule.ReadSymbols(); root = CecilHelper.Inject(mod, i.MainModule.GetType("AntiTamperMem")); mod.Types.Add(root); MethodDefinition cctor = mod.GetType("<Module>").GetStaticConstructor(); cctor.Body.GetILProcessor().InsertBefore(0, Instruction.Create(OpCodes.Call, root.Methods.FirstOrDefault(mtd => mtd.Name == "Initalize"))); Mutator mutator = new Mutator(); mutator.IntKeys = new int[] { key0, (int)sectName.ToCharArray().Sum(_ => (int)_), key2, key3, key4, key5, key6 }; mutator.LongKeys = new long[] { key1 }; mutator.Mutate(Confuser.Random, root, mod); root.Name = Confuser.ObfuscationHelper.GetRandomName(); root.Namespace = ""; AddHelper(root, HelperAttribute.NoInjection); foreach (MethodDefinition mtdDef in root.Methods) { mtdDef.Name = Confuser.ObfuscationHelper.GetRandomName(); AddHelper(mtdDef, HelperAttribute.NoInjection); } Confuser.Database.AddEntry("AntiTamper", "Helper", root.FullName); }
/// <summary> /// Main running method for the application. /// </summary> /// <param name="args">Commandline arguments to the application.</param> /// <returns>Returns the application error code.</returns> private int Run(string[] args) { Decompiler decompiler = null; Mutator mutator = null; Unbinder unbinder = null; try { // parse the command line this.ParseCommandLine(args); // exit if there was an error parsing the command line (otherwise the logo appears after error messages) if (this.messageHandler.EncounteredError) { return(this.messageHandler.LastErrorNumber); } if (null == this.inputFile || null == this.outputFile) { this.showHelp = true; } if (this.showLogo) { Assembly darkAssembly = Assembly.GetExecutingAssembly(); Console.WriteLine("Microsoft (R) Windows Installer Xml Decompiler Version {0}", darkAssembly.GetName().Version.ToString()); Console.WriteLine("Copyright (C) Microsoft Corporation 2003. All rights reserved.\n"); Console.WriteLine(); } if (this.showHelp) { Console.WriteLine(" usage: dark.exe [-?] [-nologo] database.msi source.wxs"); Console.WriteLine(); Console.WriteLine(" -ext extension assembly or \"class, assembly\""); Console.WriteLine(" -nologo skip printing dark logo information"); Console.WriteLine(" -notidy do not delete temporary files (useful for debugging)"); Console.WriteLine(" -sdet suppress dropping empty tables (adds EnsureTable as appropriate)"); Console.WriteLine(" -sras suppress relative action sequencing (use explicit sequence numbers)"); Console.WriteLine(" -sui suppress decompiling UI-related tables"); Console.WriteLine(" -sw<N> suppress warning with specific message ID"); Console.WriteLine(" -v verbose output"); Console.WriteLine(" -wx treat warnings as errors"); Console.WriteLine(" -x <path> export binaries from cabinets and embedded binaries to the provided path"); Console.WriteLine(" -xo output xml instead of WiX source code (mandatory for transforms and patches)"); Console.WriteLine(" -? this help information"); Console.WriteLine(); Console.WriteLine("Environment variables:"); Console.WriteLine(" WIX_TEMP overrides the temporary directory used for cab extraction, binary extraction, ..."); Console.WriteLine(); Console.WriteLine("Common extensions:"); Console.WriteLine(" .wxi - Windows installer Xml Include file"); Console.WriteLine(" .wxl - Windows installer Xml Localization file"); Console.WriteLine(" .wxs - Windows installer Xml Source file"); Console.WriteLine(" .wixlib - Windows installer Xml Library file (in XML format)"); Console.WriteLine(" .wixobj - Windows installer Xml Object file (in XML format)"); Console.WriteLine(" .wixout - Windows installer Xml Output file (in XML format)"); Console.WriteLine(); Console.WriteLine(" .msi - Windows installer Product Database"); Console.WriteLine(" .msm - Windows installer Merge Module"); Console.WriteLine(" .msp - Windows installer Patch"); Console.WriteLine(" .mst - Windows installer Transform"); Console.WriteLine(" .pcp - Windows installer Patch Creation Package"); Console.WriteLine(); Console.WriteLine("For more information see: http://wix.sourceforge.net"); return(this.messageHandler.LastErrorNumber); } // create the decompiler and mutator decompiler = new Decompiler(); mutator = new Mutator(); unbinder = new Unbinder(); // read the configuration file (dark.exe.config) AppCommon.ReadConfiguration(this.extensionList); // load any extensions foreach (string extension in this.extensionList) { WixExtension wixExtension = WixExtension.Load(extension); decompiler.AddExtension(wixExtension); unbinder.AddExtension(wixExtension); } // set options decompiler.SuppressDroppingEmptyTables = this.suppressDroppingEmptyTables; decompiler.SuppressRelativeActionSequencing = this.suppressRelativeActionSequencing; decompiler.SuppressUI = this.suppressUI; decompiler.TempFilesLocation = Environment.GetEnvironmentVariable("WIX_TEMP"); unbinder.TempFilesLocation = Environment.GetEnvironmentVariable("WIX_TEMP"); decompiler.Message += new MessageEventHandler(this.messageHandler.Display); mutator.Message += new MessageEventHandler(this.messageHandler.Display); unbinder.Message += new MessageEventHandler(this.messageHandler.Display); // print friendly message saying what file is being decompiled Console.WriteLine(Path.GetFileName(this.inputFile)); // unbind Output output = unbinder.Unbind(this.inputFile, this.outputType, this.exportBasePath); if (null != output) { if (OutputType.Patch == this.outputType || OutputType.Transform == this.outputType || this.outputXml) { output.Save(this.outputFile, null, new WixVariableResolver(), null); } else // decompile { Wix.Wix wix = decompiler.Decompile(output); // output if (null != wix) { XmlTextWriter writer = null; // mutate the Wix document if (!mutator.Mutate(wix)) { return(this.messageHandler.LastErrorNumber); } try { writer = new XmlTextWriter(this.outputFile, System.Text.Encoding.UTF8); writer.Indentation = 4; writer.IndentChar = ' '; writer.QuoteChar = '"'; writer.Formatting = Formatting.Indented; writer.WriteStartDocument(); wix.OutputXml(writer); writer.WriteEndDocument(); } finally { if (null != writer) { writer.Close(); } } } } } } catch (WixException we) { this.messageHandler.Display(this, we.Error); } catch (Exception e) { this.messageHandler.Display(this, WixErrors.UnexpectedException(e.Message, e.GetType().ToString(), e.StackTrace)); if (e is NullReferenceException || e is SEHException) { throw; } } finally { if (null != decompiler) { if (this.tidy) { if (!decompiler.DeleteTempFiles()) { Console.WriteLine("Warning, failed to delete temporary directory: {0}", decompiler.TempFilesLocation); } } else { Console.WriteLine("Temporary directory located at '{0}'.", decompiler.TempFilesLocation); } } if (null != unbinder) { if (this.tidy) { if (!unbinder.DeleteTempFiles()) { Console.WriteLine("Warning, failed to delete temporary directory: {0}", unbinder.TempFilesLocation); } } else { Console.WriteLine("Temporary directory located at '{0}'.", unbinder.TempFilesLocation); } } } return(this.messageHandler.LastErrorNumber); }
/// <summary> /// Main running method for the application. /// </summary> /// <param name="args">Commandline arguments to the application.</param> /// <returns>Returns the application error code.</returns> private int Run(string[] args) { Decompiler decompiler = null; Mutator mutator = null; Unbinder unbinder = null; try { // parse the command line this.ParseCommandLine(args); // exit if there was an error parsing the command line (otherwise the logo appears after error messages) if (this.messageHandler.EncounteredError) { return(this.messageHandler.LastErrorNumber); } if (null == this.inputFile) { this.showHelp = true; } else if (null == this.outputFile) { if (null == this.outputDirectory) { this.outputFile = Path.ChangeExtension(Path.GetFileName(this.inputFile), ".wxs"); } else { this.outputFile = Path.Combine(this.outputDirectory, Path.ChangeExtension(Path.GetFileName(this.inputFile), ".wxs")); } } if (this.showLogo) { AppCommon.DisplayToolHeader(); } if (this.showHelp) { Console.WriteLine(DarkStrings.HelpMessage); AppCommon.DisplayToolFooter(); return(this.messageHandler.LastErrorNumber); } foreach (string parameter in this.invalidArgs) { this.messageHandler.Display(this, WixWarnings.UnsupportedCommandLineArgument(parameter)); } this.invalidArgs = null; // create the decompiler and mutator decompiler = new Decompiler(); mutator = new Mutator(); mutator.Core = new HarvesterCore(new MessageEventHandler(this.messageHandler.Display)); unbinder = new Unbinder(); // read the configuration file (dark.exe.config) AppCommon.ReadConfiguration(this.extensionList); // load any extensions foreach (string extension in this.extensionList) { WixExtension wixExtension = WixExtension.Load(extension); decompiler.AddExtension(wixExtension); unbinder.AddExtension(wixExtension); } // set options decompiler.SuppressCustomTables = this.suppressCustomTables; decompiler.SuppressDroppingEmptyTables = this.suppressDroppingEmptyTables; decompiler.SuppressRelativeActionSequencing = this.suppressRelativeActionSequencing; decompiler.SuppressUI = this.suppressUI; decompiler.TempFilesLocation = Environment.GetEnvironmentVariable("WIX_TEMP"); if (!String.IsNullOrEmpty(this.exportBasePath)) { decompiler.ExportFilePath = this.exportBasePath; } unbinder.TempFilesLocation = Environment.GetEnvironmentVariable("WIX_TEMP"); decompiler.Message += new MessageEventHandler(this.messageHandler.Display); unbinder.Message += new MessageEventHandler(this.messageHandler.Display); // print friendly message saying what file is being decompiled Console.WriteLine(Path.GetFileName(this.inputFile)); // unbind // TODO: passing a bundle to the decompiler without the /x parameter specified stumbles here // as the exportBasePath will be null. Need a design decision whether to throw an // message below or throw a message here Output output = unbinder.Unbind(this.inputFile, this.outputType, this.exportBasePath); if (null != output) { if (OutputType.Patch == this.outputType || OutputType.Transform == this.outputType || this.outputXml) { output.Save(this.outputFile, null, new WixVariableResolver(), null); } else // decompile { Wix.Wix wix = decompiler.Decompile(output); // output if (null != wix) { XmlTextWriter writer = null; // mutate the Wix document if (!mutator.Mutate(wix)) { return(this.messageHandler.LastErrorNumber); } try { Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(this.outputFile))); writer = new XmlTextWriter(this.outputFile, System.Text.Encoding.UTF8); writer.Indentation = 4; writer.IndentChar = ' '; writer.QuoteChar = '"'; writer.Formatting = Formatting.Indented; writer.WriteStartDocument(); wix.OutputXml(writer); writer.WriteEndDocument(); } catch (Exception e) { this.messageHandler.Display(this, WixErrors.FileWriteError(this.outputFile, e.Message)); return(this.messageHandler.LastErrorNumber); } finally { if (null != writer) { writer.Close(); } } } } } } catch (WixException we) { this.messageHandler.Display(this, we.Error); } catch (Exception e) { this.messageHandler.Display(this, WixErrors.UnexpectedException(e.Message, e.GetType().ToString(), e.StackTrace)); if (e is NullReferenceException || e is SEHException) { throw; } } finally { if (null != decompiler) { if (this.tidy) { if (!decompiler.DeleteTempFiles()) { Console.WriteLine(DarkStrings.WAR_FailedToDeleteTempDir, decompiler.TempFilesLocation); } } else { Console.WriteLine(DarkStrings.INF_TempDirLocatedAt, decompiler.TempFilesLocation); } } if (null != unbinder) { if (this.tidy) { if (!unbinder.DeleteTempFiles()) { Console.WriteLine(DarkStrings.WAR_FailedToDeleteTempDir, unbinder.TempFilesLocation); } } else { Console.WriteLine(DarkStrings.INF_TempDirLocatedAt, unbinder.TempFilesLocation); } } } return(this.messageHandler.LastErrorNumber); }
public override void Process(ConfusionParameter parameter) { _Context txt = rc.txts[mod]; txt.dats = new List<KeyValuePair<string, byte[]>>(); TypeDefinition modType = mod.GetType("<Module>"); AssemblyDefinition i = AssemblyDefinition.ReadAssembly(typeof(Iid).Assembly.Location); i.MainModule.ReadSymbols(); txt.reso = i.MainModule.GetType("Encryptions").Methods.FirstOrDefault(mtd => mtd.Name == "Resources"); txt.reso = CecilHelper.Inject(mod, txt.reso); modType.Methods.Add(txt.reso); txt.reso.Name = ObfuscationHelper.GetRandomName(); txt.reso.IsAssembly = true; AddHelper(txt.reso, HelperAttribute.NoInjection); Database.AddEntry("ResEncrypt", "Resolver", txt.reso.FullName); TypeDefinition lzma = mod.GetType("Lzma" + mod.GetHashCode()); if (lzma == null) { lzma = CecilHelper.Inject(mod, i.MainModule.GetType("Lzma")); lzma.IsNotPublic = true; lzma.Name = "Lzma" + mod.GetHashCode(); mod.Types.Add(lzma); } FieldDefinition datAsm = new FieldDefinition( ObfuscationHelper.GetRandomName(), FieldAttributes.Static | FieldAttributes.CompilerControlled, mod.Import(typeof(System.Reflection.Assembly))); modType.Fields.Add(datAsm); AddHelper(datAsm, HelperAttribute.NoInjection); Database.AddEntry("ResEncrypt", "Store", datAsm.FullName); txt.key0 = (byte)Random.Next(0, 0x100); do { txt.key1 = (byte)Random.Next(1, 0x100); } while (txt.key1 == txt.key0); Database.AddEntry("ResEncrypt", "Key0", txt.key0); Database.AddEntry("ResEncrypt", "Key1", txt.key1); txt.resId = ObfuscationHelper.GetRandomName(); Database.AddEntry("ResEncrypt", "ResID", txt.resId); Mutator mutator = new Mutator(); mutator.StringKeys = new string[] { txt.resId }; mutator.IntKeys = new int[] { txt.key0, txt.key1 }; mutator.Mutate(Random, txt.reso.Body); foreach (Instruction inst in txt.reso.Body.Instructions) { if (inst.Operand is FieldReference && (inst.Operand as FieldReference).Name == "datAsm") inst.Operand = datAsm; else if (inst.Operand is TypeReference && (inst.Operand as TypeReference).FullName == "System.Exception") inst.Operand = modType; else if (inst.Operand is MethodReference && (inst.Operand as MethodReference).DeclaringType.Name == "LzmaDecoder") inst.Operand = lzma.NestedTypes .Single(_ => _.Name == "LzmaDecoder").Methods .Single(_ => _.Name == (inst.Operand as MethodReference).Name); } foreach (var x in txt.reso.Body.Variables) if (x.VariableType.Name == "LzmaDecoder") x.VariableType = lzma.NestedTypes.Single(_ => _.Name == "LzmaDecoder"); MethodDefinition cctor = mod.GetType("<Module>").GetStaticConstructor(); MethodBody bdy = cctor.Body as MethodBody; ILProcessor psr = bdy.GetILProcessor(); //Reverse order psr.InsertBefore(0, Instruction.Create(OpCodes.Callvirt, mod.Import(typeof(AppDomain).GetEvent("ResourceResolve").GetAddMethod()))); psr.InsertBefore(0, Instruction.Create(OpCodes.Newobj, mod.Import(typeof(ResolveEventHandler).GetConstructor(new Type[] { typeof(object), typeof(IntPtr) })))); psr.InsertBefore(0, Instruction.Create(OpCodes.Ldftn, txt.reso)); psr.InsertBefore(0, Instruction.Create(OpCodes.Ldnull)); psr.InsertBefore(0, Instruction.Create(OpCodes.Call, mod.Import(typeof(AppDomain).GetProperty("CurrentDomain").GetGetMethod()))); }
public void Phase1(ModuleDefinition mod) { AssemblyDefinition i = AssemblyDefinition.ReadAssembly(typeof(Iid).Assembly.Location); i.MainModule.ReadSymbols(); root = CecilHelper.Inject(mod, i.MainModule.GetType("AntiTamperMem")); mod.Types.Add(root); MethodDefinition cctor = mod.GetType("<Module>").GetStaticConstructor(); cctor.Body.GetILProcessor().InsertBefore(0, Instruction.Create(OpCodes.Call, root.Methods.FirstOrDefault(mtd => mtd.Name == "Initalize"))); Mutator mutator = new Mutator(); mutator.IntKeys = new int[] { key0, (int)sectName.ToCharArray().Sum(_ => (int)_), key2, key3, key4, key5, key6 }; mutator.LongKeys = new long[] { key1 }; mutator.Mutate(Confuser.Random, root); root.Name = Confuser.ObfuscationHelper.GetRandomName(); root.Namespace = ""; AddHelper(root, HelperAttribute.NoInjection); foreach (MethodDefinition mtdDef in root.Methods) { mtdDef.Name = Confuser.ObfuscationHelper.GetRandomName(); AddHelper(mtdDef, HelperAttribute.NoInjection); } Confuser.Database.AddEntry("AntiTamper", "Helper", root.FullName); }
public void Mutate(Mutator mutator, int count) { Debug.Assert(count <= _presence.Length); mutator.Mutate(_presence, count); }
public static void MutateValueSucceedsIfContextIsNullWhenNotRequired() { Mutator.Mutate <int>(null, new[] { new ToDefaultValueAttribute() }); Mutator.Mutate(null, new[] { new ToDefaultValueAttribute() }, 0); }
/// <summary> /// Main running method for the application. /// </summary> /// <param name="args">Commandline arguments to the application.</param> /// <returns>Returns the application error code.</returns> private int Run(string[] args) { Decompiler decompiler = null; Mutator mutator = null; Unbinder unbinder = null; try { // parse the command line this.ParseCommandLine(args); // exit if there was an error parsing the command line (otherwise the logo appears after error messages) if (this.messageHandler.EncounteredError) { return this.messageHandler.LastErrorNumber; } if (null == this.inputFile) { this.showHelp = true; } else if (null == this.outputFile) { if (null == this.outputDirectory) { this.outputFile = Path.ChangeExtension(Path.GetFileName(this.inputFile), ".wxs"); } else { this.outputFile = Path.Combine(this.outputDirectory, Path.ChangeExtension(Path.GetFileName(this.inputFile), ".wxs")); } } if (this.showLogo) { AppCommon.DisplayToolHeader(); } if (this.showHelp) { Console.WriteLine(DarkStrings.HelpMessage); AppCommon.DisplayToolFooter(); return this.messageHandler.LastErrorNumber; } foreach (string parameter in this.invalidArgs) { this.messageHandler.Display(this, WixWarnings.UnsupportedCommandLineArgument(parameter)); } this.invalidArgs = null; // create the decompiler and mutator decompiler = new Decompiler(); mutator = new Mutator(); mutator.Core = new HarvesterCore(new MessageEventHandler(this.messageHandler.Display)); unbinder = new Unbinder(); // read the configuration file (dark.exe.config) AppCommon.ReadConfiguration(this.extensionList); // load any extensions foreach (string extension in this.extensionList) { WixExtension wixExtension = WixExtension.Load(extension); decompiler.AddExtension(wixExtension); unbinder.AddExtension(wixExtension); } // set options decompiler.SuppressCustomTables = this.suppressCustomTables; decompiler.SuppressDroppingEmptyTables = this.suppressDroppingEmptyTables; decompiler.SuppressRelativeActionSequencing = this.suppressRelativeActionSequencing; decompiler.SuppressUI = this.suppressUI; decompiler.TempFilesLocation = Environment.GetEnvironmentVariable("WIX_TEMP"); if (!String.IsNullOrEmpty(this.exportBasePath)) { decompiler.ExportFilePath = this.exportBasePath; } unbinder.TempFilesLocation = Environment.GetEnvironmentVariable("WIX_TEMP"); decompiler.Message += new MessageEventHandler(this.messageHandler.Display); unbinder.Message += new MessageEventHandler(this.messageHandler.Display); // print friendly message saying what file is being decompiled Console.WriteLine(Path.GetFileName(this.inputFile)); // unbind // TODO: passing a bundle to the decompiler without the /x parameter specified stumbles here // as the exportBasePath will be null. Need a design decision whether to throw an // message below or throw a message here Output output = unbinder.Unbind(this.inputFile, this.outputType, this.exportBasePath); if (null != output) { if (OutputType.Patch == this.outputType || OutputType.Transform == this.outputType || this.outputXml) { output.Save(this.outputFile, null, new WixVariableResolver(), null); } else // decompile { Wix.Wix wix = decompiler.Decompile(output); // output if (null != wix) { XmlTextWriter writer = null; // mutate the Wix document if (!mutator.Mutate(wix)) { return this.messageHandler.LastErrorNumber; } try { Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(this.outputFile))); writer = new XmlTextWriter(this.outputFile, System.Text.Encoding.UTF8); writer.Indentation = 4; writer.IndentChar = ' '; writer.QuoteChar = '"'; writer.Formatting = Formatting.Indented; writer.WriteStartDocument(); wix.OutputXml(writer); writer.WriteEndDocument(); } catch (Exception e) { this.messageHandler.Display(this, WixErrors.FileWriteError(this.outputFile, e.Message)); return this.messageHandler.LastErrorNumber; } finally { if (null != writer) { writer.Close(); } } } } } } catch (WixException we) { this.messageHandler.Display(this, we.Error); } catch (Exception e) { this.messageHandler.Display(this, WixErrors.UnexpectedException(e.Message, e.GetType().ToString(), e.StackTrace)); if (e is NullReferenceException || e is SEHException) { throw; } } finally { if (null != decompiler) { if (this.tidy) { if (!decompiler.DeleteTempFiles()) { Console.WriteLine(DarkStrings.WAR_FailedToDeleteTempDir, decompiler.TempFilesLocation); } } else { Console.WriteLine(DarkStrings.INF_TempDirLocatedAt, decompiler.TempFilesLocation); } } if (null != unbinder) { if (this.tidy) { if (!unbinder.DeleteTempFiles()) { Console.WriteLine(DarkStrings.WAR_FailedToDeleteTempDir, unbinder.TempFilesLocation); } } else { Console.WriteLine(DarkStrings.INF_TempDirLocatedAt, unbinder.TempFilesLocation); } } } return this.messageHandler.LastErrorNumber; }
public override void DeInitialize() { _Context txt = cc.txts[mod]; TypeDefinition modType = mod.GetType("<Module>"); AssemblyDefinition i = AssemblyDefinition.ReadAssembly(typeof(Iid).Assembly.Location); i.MainModule.ReadSymbols(); txt.proxy = i.MainModule.GetType("Proxies").Methods.FirstOrDefault(mtd => mtd.Name == "CtorProxy"); txt.proxy = CecilHelper.Inject(mod, txt.proxy); modType.Methods.Add(txt.proxy); txt.proxy.IsAssembly = true; txt.proxy.Name = ObfuscationHelper.GetRandomName(); AddHelper(txt.proxy, 0); Database.AddEntry("CtorProxy", "Proxy", txt.proxy.FullName); Instruction placeholder = null; txt.key = (uint)Random.Next(); Database.AddEntry("CtorProxy", "Key", txt.key); Mutator mutator = new Mutator(); mutator.Mutate(Random, txt.proxy.Body); placeholder = mutator.Placeholder; if (txt.isNative) { txt.nativeDecr = new MethodDefinition( ObfuscationHelper.GetRandomName(), MethodAttributes.Abstract | MethodAttributes.CompilerControlled | MethodAttributes.ReuseSlot | MethodAttributes.Static, mod.TypeSystem.Int32); txt.nativeDecr.ImplAttributes = MethodImplAttributes.Native; txt.nativeDecr.Parameters.Add(new ParameterDefinition(mod.TypeSystem.Int32)); modType.Methods.Add(txt.nativeDecr); Database.AddEntry("CtorProxy", "NativeDecr", txt.nativeDecr.FullName); do { txt.exp = new ExpressionGenerator(Random.Next()).Generate(6); txt.invExp = ExpressionInverser.InverseExpression(txt.exp); } while ((txt.visitor = new x86Visitor(txt.invExp, null)).RegisterOverflowed); Database.AddEntry("CtorProxy", "Exp", txt.exp); Database.AddEntry("CtorProxy", "InvExp", txt.invExp); CecilHelper.Replace(txt.proxy.Body, placeholder, new Instruction[] { Instruction.Create(OpCodes.Call, txt.nativeDecr) }); } else CecilHelper.Replace(txt.proxy.Body, placeholder, new Instruction[] { Instruction.Create(OpCodes.Ldc_I4, (int)txt.key), Instruction.Create(OpCodes.Xor) }); }
public void Phase1(ModuleDefinition mod) { AssemblyDefinition i = AssemblyDefinition.ReadAssembly(typeof(Iid).Assembly.Location); i.MainModule.ReadSymbols(); root = CecilHelper.Inject(mod, i.MainModule.GetType("AntiTamperJIT")); mod.Types.Add(root); MethodDefinition cctor = mod.GetType("<Module>").GetStaticConstructor(); cctor.Body.GetILProcessor().InsertBefore(0, Instruction.Create(OpCodes.Call, root.Methods.FirstOrDefault(mtd => mtd.Name == "Initialize"))); Mutator mutator = new Mutator(); mutator.IntKeys = new int[] { key0, (int)sectName.ToCharArray().Sum(_ => (int)_), key2, key3, key4, key5, key6 }; mutator.LongKeys = new long[] { key1 }; mutator.Mutate(Confuser.Random, root); root.Name = Confuser.ObfuscationHelper.GetRandomName(); root.Namespace = ""; AddHelper(root, HelperAttribute.NoInjection); foreach (MethodDefinition mtdDef in root.Methods) { if (mtdDef.IsConstructor) { continue; } mtdDef.Name = Confuser.ObfuscationHelper.GetRandomName(); AddHelper(mtdDef, HelperAttribute.NoInjection); } foreach (FieldDefinition fldDef in root.Fields) { fldDef.Name = Confuser.ObfuscationHelper.GetRandomName(); AddHelper(fldDef, HelperAttribute.NoInjection); } foreach (TypeDefinition nested in root.NestedTypes) { if (nested.Name == "MethodData") { FieldDefinition[] fields = nested.Fields.ToArray(); byte[] layout = fieldLayout.Clone() as byte[]; Array.Sort(layout, fields); for (byte j = 1; j <= 5; j++) { layout[j - 1] = j; } Array.Sort(fieldLayout, layout); fieldLayout = layout; nested.Fields.Clear(); foreach (var f in fields) { nested.Fields.Add(f); } } nested.Name = Confuser.ObfuscationHelper.GetRandomName(); AddHelper(nested, HelperAttribute.NoInjection); foreach (MethodDefinition mtdDef in nested.Methods) { if (mtdDef.IsConstructor || mtdDef.IsRuntime) { continue; } if (mtdDef.Name == "Obj2Ptr") { mtdDef.Body.Instructions.Clear(); mtdDef.Body.Instructions.Add(Instruction.Create(OpCodes.Ldarg_0)); mtdDef.Body.Instructions.Add(Instruction.Create(OpCodes.Ret)); } mtdDef.Name = Confuser.ObfuscationHelper.GetRandomName(); AddHelper(mtdDef, HelperAttribute.NoInjection); } foreach (FieldDefinition fldDef in nested.Fields) { if (fldDef.IsRuntimeSpecialName) { continue; } fldDef.Name = Confuser.ObfuscationHelper.GetRandomName(); AddHelper(fldDef, HelperAttribute.NoInjection); } } Confuser.Database.AddEntry("AntiTamper", "Helper", root.Name); }
public void Phase1(ModuleDefinition mod) { AssemblyDefinition i = AssemblyDefinition.ReadAssembly(typeof(Iid).Assembly.Location); i.MainModule.ReadSymbols(); root = CecilHelper.Inject(mod, i.MainModule.GetType("AntiTamperJIT")); mod.Types.Add(root); MethodDefinition cctor = mod.GetType("<Module>").GetStaticConstructor(); cctor.Body.GetILProcessor().InsertBefore(0, Instruction.Create(OpCodes.Call, root.Methods.FirstOrDefault(mtd => mtd.Name == "Initialize"))); Mutator mutator = new Mutator(); mutator.IntKeys = new int[] { key0, (int)sectName.ToCharArray().Sum(_ => (int)_), key2, key3, key4, key5, key6 }; mutator.LongKeys = new long[] { key1 }; mutator.Mutate(Confuser.Random, root); root.Name = Confuser.ObfuscationHelper.GetRandomName(); root.Namespace = ""; AddHelper(root, HelperAttribute.NoInjection); foreach (MethodDefinition mtdDef in root.Methods) { if (mtdDef.IsConstructor) continue; mtdDef.Name = Confuser.ObfuscationHelper.GetRandomName(); AddHelper(mtdDef, HelperAttribute.NoInjection); } foreach (FieldDefinition fldDef in root.Fields) { fldDef.Name = Confuser.ObfuscationHelper.GetRandomName(); AddHelper(fldDef, HelperAttribute.NoInjection); } foreach (TypeDefinition nested in root.NestedTypes) { if (nested.Name == "MethodData") { FieldDefinition[] fields = nested.Fields.ToArray(); byte[] layout = fieldLayout.Clone() as byte[]; Array.Sort(layout, fields); for (byte j = 1; j <= 5; j++) layout[j - 1] = j; Array.Sort(fieldLayout, layout); fieldLayout = layout; nested.Fields.Clear(); foreach (var f in fields) nested.Fields.Add(f); } nested.Name = Confuser.ObfuscationHelper.GetRandomName(); AddHelper(nested, HelperAttribute.NoInjection); foreach (MethodDefinition mtdDef in nested.Methods) { if (mtdDef.IsConstructor || mtdDef.IsRuntime) continue; if (mtdDef.Name == "Obj2Ptr") { mtdDef.Body.Instructions.Clear(); mtdDef.Body.Instructions.Add(Instruction.Create(OpCodes.Ldarg_0)); mtdDef.Body.Instructions.Add(Instruction.Create(OpCodes.Ret)); } mtdDef.Name = Confuser.ObfuscationHelper.GetRandomName(); AddHelper(mtdDef, HelperAttribute.NoInjection); } foreach (FieldDefinition fldDef in nested.Fields) { if (fldDef.IsRuntimeSpecialName) continue; fldDef.Name = Confuser.ObfuscationHelper.GetRandomName(); AddHelper(fldDef, HelperAttribute.NoInjection); } } Confuser.Database.AddEntry("AntiTamper", "Helper", root.Name); }
public override void DeInitialize() { _Context txt = mc.txts[mod]; TypeDefinition modType = mod.GetType("<Module>"); AssemblyDefinition i = AssemblyDefinition.ReadAssembly(typeof(Iid).Assembly.Location); i.MainModule.ReadSymbols(); txt.proxy = i.MainModule.GetType("Proxies").Methods.FirstOrDefault(mtd => mtd.Name == "MtdProxy"); txt.proxy = CecilHelper.Inject(mod, txt.proxy); modType.Methods.Add(txt.proxy); txt.proxy.IsAssembly = true; txt.proxy.Name = ObfuscationHelper.GetRandomName(); AddHelper(txt.proxy, 0); Database.AddEntry("MtdProxy", "Proxy", txt.proxy.FullName); Instruction placeholder = null; txt.key = (uint)Random.Next(); txt.keyChar1 = (char)Random.Next(1, 32); do { txt.keyChar2 = (char)Random.Next(1, 32); } while (txt.keyChar2 == txt.keyChar1); Database.AddEntry("MtdProxy", "Key", txt.key); Database.AddEntry("MtdProxy", "KeyChar1", (int)txt.keyChar1); Database.AddEntry("MtdProxy", "KeyChar2", (int)txt.keyChar2); Mutator mutator = new Mutator(); mutator.IntKeys = new int[] { txt.keyChar1 }; mutator.Mutate(Random, txt.proxy.Body); placeholder = mutator.Placeholder; if (txt.isNative) { txt.nativeDecr = new MethodDefinition( ObfuscationHelper.GetRandomName(), MethodAttributes.Abstract | MethodAttributes.CompilerControlled | MethodAttributes.ReuseSlot | MethodAttributes.Static, mod.TypeSystem.Int32); txt.nativeDecr.ImplAttributes = MethodImplAttributes.Native; txt.nativeDecr.Parameters.Add(new ParameterDefinition(mod.TypeSystem.Int32)); modType.Methods.Add(txt.nativeDecr); Database.AddEntry("MtdProxy", "NativeDecr", txt.nativeDecr.FullName); do { txt.exp = new ExpressionGenerator(Random.Next()).Generate(6); txt.invExp = ExpressionInverser.InverseExpression(txt.exp); } while ((txt.visitor = new x86Visitor(txt.invExp, null)).RegisterOverflowed); Database.AddEntry("MtdProxy", "Exp", txt.exp); Database.AddEntry("MtdProxy", "InvExp", txt.invExp); CecilHelper.Replace(txt.proxy.Body, placeholder, new Instruction[] { Instruction.Create(OpCodes.Call, txt.nativeDecr) }); } else { CecilHelper.Replace(txt.proxy.Body, placeholder, new Instruction[] { Instruction.Create(OpCodes.Ldc_I4, (int)txt.key), Instruction.Create(OpCodes.Xor) }); } }
Conster[] CreateConsters(_Context txt, Random rand, string injectName, FieldDefinition constTbl, FieldDefinition constBuffer) { AssemblyDefinition injection = AssemblyDefinition.ReadAssembly(typeof(Iid).Assembly.Location); injection.MainModule.ReadSymbols(); MethodDefinition method = injection.MainModule.GetType("Encryptions").Methods.FirstOrDefault(mtd => mtd.Name == "Constants"); List <Conster> ret = new List <Conster>(); TypeDefinition lzma = mod.GetType("Lzma" + mod.GetHashCode()); if (lzma == null) { lzma = CecilHelper.Inject(mod, injection.MainModule.GetType("Lzma")); lzma.IsNotPublic = true; lzma.Name = "Lzma" + mod.GetHashCode(); mod.Types.Add(lzma); } rand.NextBytes(txt.keyBuff); for (int i = 0; i < txt.keyBuff.Length; i++) { txt.keyBuff[i] &= 0x7f; } txt.keyBuff[0] = 7; txt.keyBuff[1] = 0; txt.resKey = (rand.Next(0x20, 0x80) << 24) | (rand.Next(0x20, 0x80) << 32) | (rand.Next(0x20, 0x80) << 16) | (rand.Next(0x20, 0x80) << 0); txt.resId = Encoding.UTF8.GetString(BitConverter.GetBytes(txt.resKey)); txt.key = (uint)rand.Next(); Database.AddEntry("Const", "KeyBuff", txt.keyBuff); Database.AddEntry("Const", "ResKey", txt.resKey); Database.AddEntry("Const", "ResId", txt.resId); Database.AddEntry("Const", "Key", txt.key); Mutator mutator = new Mutator(); MethodDefinition init = injection.MainModule.GetType("Encryptions").Methods.FirstOrDefault(mtd => mtd.Name == injectName); { MethodDefinition cctor = mod.GetType("<Module>").GetStaticConstructor(); MethodDefinition m = CecilHelper.Inject(mod, init); Instruction placeholder = null; mutator.IntKeys = new int[] { txt.resKey }; mutator.Mutate(Random, m.Body); txt.keyInst = mutator.Delayed0; placeholder = mutator.Placeholder; foreach (Instruction inst in m.Body.Instructions) { if (inst.Operand is FieldReference) { if ((inst.Operand as FieldReference).Name == "constTbl") { inst.Operand = constTbl; } else if ((inst.Operand as FieldReference).Name == "constBuffer") { inst.Operand = constBuffer; } } else if (inst.Operand is MethodReference && (inst.Operand as MethodReference).DeclaringType.Name == "LzmaDecoder") { inst.Operand = lzma.NestedTypes .Single(_ => _.Name == "LzmaDecoder").Methods .Single(_ => _.Name == (inst.Operand as MethodReference).Name); } } foreach (var i in m.Body.Variables) { if (i.VariableType.Name == "LzmaDecoder") { i.VariableType = lzma.NestedTypes.Single(_ => _.Name == "LzmaDecoder"); } } if (txt.isNative) { CecilHelper.Replace(m.Body, placeholder, new Instruction[] { Instruction.Create(OpCodes.Call, txt.nativeDecr) }); } else if (txt.isDyn) { Instruction ldloc = placeholder.Previous; m.Body.Instructions.Remove(placeholder.Previous); //ldloc CecilHelper.Replace(m.Body, placeholder, new CecilVisitor(txt.invExp, new Instruction[] { ldloc }).GetInstructions()); } ILProcessor psr = cctor.Body.GetILProcessor(); Instruction begin = cctor.Body.Instructions[0]; for (int i = m.Body.Instructions.Count - 1; i >= 0; i--) { if (m.Body.Instructions[i].OpCode != OpCodes.Ret) { psr.InsertBefore(0, m.Body.Instructions[i]); } } cctor.Body.InitLocals = true; foreach (var i in m.Body.Variables) { cctor.Body.Variables.Add(i); } } byte[] n = new byte[0x10]; int typeDefCount = rand.Next(1, 10); for (int i = 0; i < typeDefCount; i++) { TypeDefinition typeDef = new TypeDefinition( "", ObfuscationHelper.GetRandomName(), TypeAttributes.Class | TypeAttributes.Abstract | TypeAttributes.NotPublic | TypeAttributes.Sealed, mod.TypeSystem.Object); mod.Types.Add(typeDef); int methodCount = rand.Next(1, 5); Database.AddEntry("Const", "ConsterTypes", typeDef.FullName); for (int j = 0; j < methodCount; j++) { MethodDefinition mtd = CecilHelper.Inject(mod, method); mtd.Name = ObfuscationHelper.GetRandomName(); mtd.IsCompilerControlled = true; AddHelper(mtd, HelperAttribute.NoInjection); typeDef.Methods.Add(mtd); Database.AddEntry("Const", "ConsterMethods", mtd.FullName); Conster conster = new Conster(); conster.key0 = (long)rand.Next() * rand.Next(); conster.key1 = (long)rand.Next() * rand.Next(); conster.key2 = (long)rand.Next() * rand.Next(); conster.key3 = rand.Next(); conster.conster = mtd; Database.AddEntry("Const", mtd.FullName, string.Format("{0:X}, {1:X}, {2:X}, {3:X}", conster.key0, conster.key1, conster.key2, conster.key3)); mutator = new Mutator(); mutator.LongKeys = new long[] { conster.key0, conster.key1, conster.key2 }; mutator.IntKeys = new int[] { conster.key3 }; mutator.Mutate(Random, mtd.Body); foreach (Instruction inst in mtd.Body.Instructions) { if (inst.Operand is FieldReference) { if ((inst.Operand as FieldReference).Name == "constTbl") { inst.Operand = constTbl; } else if ((inst.Operand as FieldReference).Name == "constBuffer") { inst.Operand = constBuffer; } } } conster.keyInst = mutator.Delayed0; ret.Add(conster); } } return(ret.ToArray()); }
private Population <T> Mutate(Population <T> population) { return(Mutator.Mutate(population, _options)); }
public override void Process(ConfusionParameter parameter) { _Context txt = rc.txts[mod]; txt.dats = new List <KeyValuePair <string, byte[]> >(); TypeDefinition modType = mod.GetType("<Module>"); AssemblyDefinition i = AssemblyDefinition.ReadAssembly(typeof(Iid).Assembly.Location); i.MainModule.ReadSymbols(); txt.reso = i.MainModule.GetType("Encryptions").Methods.FirstOrDefault(mtd => mtd.Name == "Resources"); txt.reso = CecilHelper.Inject(mod, txt.reso); modType.Methods.Add(txt.reso); txt.reso.Name = ObfuscationHelper.GetRandomName(); txt.reso.IsAssembly = true; AddHelper(txt.reso, HelperAttribute.NoInjection); Database.AddEntry("ResEncrypt", "Resolver", txt.reso.FullName); TypeDefinition lzma = mod.GetType("Lzma" + mod.GetHashCode()); if (lzma == null) { lzma = CecilHelper.Inject(mod, i.MainModule.GetType("Lzma")); lzma.IsNotPublic = true; lzma.Name = "Lzma" + mod.GetHashCode(); mod.Types.Add(lzma); } FieldDefinition datAsm = new FieldDefinition( ObfuscationHelper.GetRandomName(), FieldAttributes.Static | FieldAttributes.CompilerControlled, mod.Import(typeof(System.Reflection.Assembly))); modType.Fields.Add(datAsm); AddHelper(datAsm, HelperAttribute.NoInjection); Database.AddEntry("ResEncrypt", "Store", datAsm.FullName); txt.key0 = (byte)Random.Next(0, 0x100); do { txt.key1 = (byte)Random.Next(1, 0x100); } while (txt.key1 == txt.key0); Database.AddEntry("ResEncrypt", "Key0", txt.key0); Database.AddEntry("ResEncrypt", "Key1", txt.key1); txt.resId = ObfuscationHelper.GetRandomName(); Database.AddEntry("ResEncrypt", "ResID", txt.resId); Mutator mutator = new Mutator(); mutator.StringKeys = new string[] { txt.resId }; mutator.IntKeys = new int[] { txt.key0, txt.key1 }; mutator.Mutate(Random, txt.reso.Body, mod); foreach (Instruction inst in txt.reso.Body.Instructions) { if (inst.Operand is FieldReference && (inst.Operand as FieldReference).Name == "datAsm") { inst.Operand = datAsm; } else if (inst.Operand is TypeReference && (inst.Operand as TypeReference).FullName == "System.Exception") { inst.Operand = modType; } else if (inst.Operand is MethodReference && (inst.Operand as MethodReference).DeclaringType.Name == "LzmaDecoder") { inst.Operand = lzma.NestedTypes .Single(_ => _.Name == "LzmaDecoder").Methods .Single(_ => _.Name == (inst.Operand as MethodReference).Name); } } foreach (var x in txt.reso.Body.Variables) { if (x.VariableType.Name == "LzmaDecoder") { x.VariableType = lzma.NestedTypes.Single(_ => _.Name == "LzmaDecoder"); } } MethodDefinition cctor = mod.GetType("<Module>").GetStaticConstructor(); MethodBody bdy = cctor.Body as MethodBody; ILProcessor psr = bdy.GetILProcessor(); //Reverse order psr.InsertBefore(0, Instruction.Create(OpCodes.Callvirt, mod.Import(typeof(AppDomain).GetEvent("ResourceResolve").GetAddMethod()))); psr.InsertBefore(0, Instruction.Create(OpCodes.Newobj, mod.Import(typeof(ResolveEventHandler).GetConstructor(new Type[] { typeof(object), typeof(IntPtr) })))); psr.InsertBefore(0, Instruction.Create(OpCodes.Ldftn, txt.reso)); psr.InsertBefore(0, Instruction.Create(OpCodes.Ldnull)); psr.InsertBefore(0, Instruction.Create(OpCodes.Call, mod.Import(typeof(AppDomain).GetProperty("CurrentDomain").GetGetMethod()))); }
Conster[] CreateConsters(_Context txt, Random rand, string injectName, FieldDefinition constTbl, FieldDefinition constBuffer) { AssemblyDefinition injection = AssemblyDefinition.ReadAssembly(typeof(Iid).Assembly.Location); injection.MainModule.ReadSymbols(); MethodDefinition method = injection.MainModule.GetType("Encryptions").Methods.FirstOrDefault(mtd => mtd.Name == "Constants"); List<Conster> ret = new List<Conster>(); TypeDefinition lzma = mod.GetType("Lzma" + mod.GetHashCode()); if (lzma == null) { lzma = CecilHelper.Inject(mod, injection.MainModule.GetType("Lzma")); lzma.IsNotPublic = true; lzma.Name = "Lzma" + mod.GetHashCode(); mod.Types.Add(lzma); } rand.NextBytes(txt.keyBuff); for (int i = 0; i < txt.keyBuff.Length; i++) txt.keyBuff[i] &= 0x7f; txt.keyBuff[0] = 7; txt.keyBuff[1] = 0; txt.resKey = (rand.Next(0x20, 0x80) << 24) | (rand.Next(0x20, 0x80) << 32) | (rand.Next(0x20, 0x80) << 16) | (rand.Next(0x20, 0x80) << 0 ); txt.resId = Encoding.UTF8.GetString(BitConverter.GetBytes(txt.resKey)); txt.key = (uint)rand.Next(); Database.AddEntry("Const", "KeyBuff", txt.keyBuff); Database.AddEntry("Const", "ResKey", txt.resKey); Database.AddEntry("Const", "ResId", txt.resId); Database.AddEntry("Const", "Key", txt.key); Mutator mutator = new Mutator(); MethodDefinition init = injection.MainModule.GetType("Encryptions").Methods.FirstOrDefault(mtd => mtd.Name == injectName); { MethodDefinition cctor = mod.GetType("<Module>").GetStaticConstructor(); MethodDefinition m = CecilHelper.Inject(mod, init); Instruction placeholder = null; mutator.IntKeys = new int[] { txt.resKey }; mutator.Mutate(Random, m.Body); txt.keyInst = mutator.Delayed0; placeholder = mutator.Placeholder; foreach (Instruction inst in m.Body.Instructions) { if (inst.Operand is FieldReference) { if ((inst.Operand as FieldReference).Name == "constTbl") inst.Operand = constTbl; else if ((inst.Operand as FieldReference).Name == "constBuffer") inst.Operand = constBuffer; } else if (inst.Operand is MethodReference && (inst.Operand as MethodReference).DeclaringType.Name == "LzmaDecoder") inst.Operand = lzma.NestedTypes .Single(_ => _.Name == "LzmaDecoder").Methods .Single(_ => _.Name == (inst.Operand as MethodReference).Name); } foreach (var i in m.Body.Variables) if (i.VariableType.Name == "LzmaDecoder") i.VariableType = lzma.NestedTypes.Single(_ => _.Name == "LzmaDecoder"); if (txt.isNative) CecilHelper.Replace(m.Body, placeholder, new Instruction[] { Instruction.Create(OpCodes.Call, txt.nativeDecr) }); else if (txt.isDyn) { Instruction ldloc = placeholder.Previous; m.Body.Instructions.Remove(placeholder.Previous); //ldloc CecilHelper.Replace(m.Body, placeholder, new CecilVisitor(txt.invExp, new Instruction[] { ldloc }).GetInstructions()); } ILProcessor psr = cctor.Body.GetILProcessor(); Instruction begin = cctor.Body.Instructions[0]; for (int i = m.Body.Instructions.Count - 1; i >= 0; i--) { if (m.Body.Instructions[i].OpCode != OpCodes.Ret) psr.InsertBefore(0, m.Body.Instructions[i]); } cctor.Body.InitLocals = true; foreach (var i in m.Body.Variables) cctor.Body.Variables.Add(i); } byte[] n = new byte[0x10]; int typeDefCount = rand.Next(1, 10); for (int i = 0; i < typeDefCount; i++) { TypeDefinition typeDef = new TypeDefinition( "", ObfuscationHelper.GetRandomName(), TypeAttributes.Class | TypeAttributes.Abstract | TypeAttributes.NotPublic | TypeAttributes.Sealed, mod.TypeSystem.Object); mod.Types.Add(typeDef); int methodCount = rand.Next(1, 5); Database.AddEntry("Const", "ConsterTypes", typeDef.FullName); for (int j = 0; j < methodCount; j++) { MethodDefinition mtd = CecilHelper.Inject(mod, method); mtd.Name = ObfuscationHelper.GetRandomName(); mtd.IsCompilerControlled = true; AddHelper(mtd, HelperAttribute.NoInjection); typeDef.Methods.Add(mtd); Database.AddEntry("Const", "ConsterMethods", mtd.FullName); Conster conster = new Conster(); conster.key0 = (long)rand.Next() * rand.Next(); conster.key1 = (long)rand.Next() * rand.Next(); conster.key2 = (long)rand.Next() * rand.Next(); conster.key3 = rand.Next(); conster.conster = mtd; Database.AddEntry("Const", mtd.FullName, string.Format("{0:X}, {1:X}, {2:X}, {3:X}", conster.key0, conster.key1, conster.key2, conster.key3)); mutator = new Mutator(); mutator.LongKeys = new long[] { conster.key0, conster.key1, conster.key2 }; mutator.IntKeys = new int[] { conster.key3 }; mutator.Mutate(Random, mtd.Body); foreach (Instruction inst in mtd.Body.Instructions) if (inst.Operand is FieldReference) { if ((inst.Operand as FieldReference).Name == "constTbl") inst.Operand = constTbl; else if ((inst.Operand as FieldReference).Name == "constBuffer") inst.Operand = constBuffer; } conster.keyInst = mutator.Delayed0; ret.Add(conster); } } return ret.ToArray(); }