public bool IsNew(ref T originalModel, Mutator mutator = null) { if (_isNew.HasValue) { return(_isNew.Value); } var key = GetDataKey(this); if (string.IsNullOrEmpty(key)) { _isNew = true; return(_isNew.Value); } var keyExists = Info <T> .Settings.Adapter.KeyExists(key, mutator); if (!keyExists) { _isNew = true; return(_isNew.Value); } originalModel = Get(key, mutator, true); _isNew = originalModel == null; return(_isNew.Value); }
/// <summary> /// /// </summary> /// <param name="nn"></param> /// <param name="mutator"></param> /// <param name="rate"></param> public static void MutateNetwork(NeuralNetwork nn, Mutator mutator, float rate) { foreach (Layer l in nn.AllLayers) { MutateLayer(l, mutator, rate); } }
public static Mutator getDefaultMutator(MutatorSettings mutatorSettings) { Mutator mutator = SimpleMutator.Instance; mutator.Settings = mutatorSettings; return(mutator); }
public AuthorizationService() { _context = new Context(); _mutator = new Mutator <User>(); _userList = new List <UserDto>(); _proxy = new NotifyProxyService(); }
public void MutantFilter_ShouldSkipMutationsForExcludedMutatorType(Mutator excludedMutator, bool skipped) { // Arrange var mutant = new Mutant { Mutation = new Mutation { Type = Mutator.Arithmetic, } }; var sut = new ExcludeMutationMutantFilter(); // Act var filteredMutants = sut.FilterMutants( new[] { mutant }, null, new StrykerOptions(excludedMutations: new[] { excludedMutator.ToString() })); // Assert if (skipped) { filteredMutants.ShouldNotContain(mutant); } else { filteredMutants.ShouldContain(mutant); } }
public Guid AddDocument(string key, Guid?etag, JObject data, JObject metadata) { var docPos = Mutator.Documents.FindValue(key); EnsureNotLockedByAnotherTransaction(key, Guid.Empty); if (docPos == null) { var max = Mutator.DocumentsById.GetRightMost(); var current = max.Type == JTokenType.Null ? 0 : max.Value <int>(); var docId = current + 1; metadata["@docId"] = new JValue(docId); var docKeyPos = Writer.Position; BinaryWriter.Write(key); Mutator.DocumentsById.Add(docId, docKeyPos); Mutator.IncrementDocumentCount(); } else { var oldEtag = EnsureValidEtag(docPos.Value, etag); Mutator.DocumentsByEtag.Remove(oldEtag); } var newEtag = DocumentDatabase.CreateSequentialUuid(); long position = WriteDocument(key, metadata, newEtag, data); Mutator.Documents.Add(key, position); Mutator.DocumentsByEtag.Add(newEtag.ToByteArray(), position); return(newEtag); }
private IMongoCollection <BsonDocument> Collection(Mutator mutator = null) { var referenceCode = mutator?.SetCode ?? ""; lock (_collectionCache) { if (_collectionCache.ContainsKey(referenceCode)) { return(_collectionCache[referenceCode]); } _collectionCache[referenceCode] = Database.GetCollection <BsonDocument>(GetCollectionName(referenceCode)); try { var indexOptions = new CreateIndexOptions { Unique = false, Name = "fullTextSearch", Background = true }; var model = new CreateIndexModel <BsonDocument>(Builders <BsonDocument> .IndexKeys.Text("$**"), indexOptions); _collectionCache[referenceCode].Indexes.CreateOne(model); } catch (Exception e) { Current.Log.Info <T>(e.Message); } return(_collectionCache[referenceCode]); } }
/// <summary> /// /// </summary> /// <param name="l"></param> /// <param name="mutator"></param> /// <param name="rate"></param> public static void MutateLayer(Layer l, Mutator mutator, float rate) { float op(float v) => ApplyMutator(v, mutator, rate); l.Weights.Map(op); l.Biases.Map(op); }
protected override void MutationStrategy_StateMutating(State state, Mutator mutator) { WriteInfoMark(); Console.WriteLine("Fuzzing State: {0}", state.name); WriteInfoMark(); Console.WriteLine("Mutator: {0}", mutator.name); }
public void NextGeneration(Text text) { if (firstGrid == null || secondGrid == null) { text.text = "Must Select Two Grids"; } else { text.text = "Next Generation"; //copy Grids[0].Deserialize(firstGrid); Grids[1].Deserialize(secondGrid); //mutations Grids[2].Deserialize(Mutator.Mutate(firstGrid)); Grids[3].Deserialize(Mutator.Mutate(secondGrid)); //crossovers string[] crosses = Mutator.Crossover(firstGrid, secondGrid); Grids[4].Deserialize(crosses[0]); Grids[5].Deserialize(crosses[1]); //random Grids[6].Randomize(); Grids[7].Randomize(); firstGrid = secondGrid = null; } }
static void Main(string[] args) { var parser = new TextToSimModelParser(); var provider = new FromFileDataProvider(); var populationGenerator = new PopulationGenerator(); var selector = new GreedyItemSelector(); var mutator = new Mutator(); var popLogger = new FilePopulationLogger(); var evaluator = new Evaluator(selector); var crossoverSelector = new RouletteSelector(); var crossBreeder = new CrossBreeder(); var problem = provider.Get(); var model = parser.Parse(problem.ToArray()); var simulation = new Simulation(model, mutator, selector, popLogger, evaluator, crossoverSelector, crossBreeder, populationGenerator); simulation.Run(Config.Generations, Config.CrossoverProbability, Config.MutationProbability, Config.Population); Console.WriteLine("FINITO"); Console.Read(); }
public void MathMutator_ShouldMutate(Mutator expectedKind, SyntaxKind input, params SyntaxKind[] expectedOutput) { var target = new BinaryExpressionMutator(); var originalNode = SyntaxFactory.BinaryExpression(input, SyntaxFactory.LiteralExpression(SyntaxKind.NumericLiteralExpression, SyntaxFactory.Literal(1)), SyntaxFactory.LiteralExpression(SyntaxKind.NumericLiteralExpression, SyntaxFactory.Literal(8))); var result = target.ApplyMutations(originalNode).ToList(); if (expectedOutput.Count() == 1) { // there should be only one mutation result.ShouldHaveSingleItem(); } else { // there should be two mutations result.Count.ShouldBe(2, "Two mutations should have been made"); } int index = 0; foreach (var mutation in result) { mutation.ReplacementNode.IsKind(expectedOutput[index]).ShouldBeTrue(); mutation.Type.ShouldBe(expectedKind); index++; } }
public static T Remove(string Key, Mutator mutator = null) { var targetModel = Get(Key, mutator); targetModel?.Remove(mutator); return(targetModel); }
/// <summary> /// Allows mutation strategy to affect state change. /// </summary> /// <param name="state"></param> /// <returns></returns> public override State MutateChangingState(State state) { if (_context.controlIteration) { return(state); } string name = "STATE_" + state.name; foreach (var item in _mutations) { if (item.Key.ModelName != name) { continue; } Mutator mutator = Random.Choice(item.Value); OnMutating(state.name, mutator.name); logger.Debug("MutateChangingState: Fuzzing state change: " + state.name); logger.Debug("MutateChangingState: Mutator: " + mutator.name); return(mutator.changeState(state)); } return(state); }
public static T Get(string key, Mutator mutator = null, bool bypassCache = false) { ValidateState(EActionType.Read); if (key == null) { return(null); } if (Info <T> .Settings.KeyMemberName == null) { if (!Info <T> .Settings.Silent) { Current.Log.Warn <T>("Invalid operation; key not set"); } throw new MissingPrimaryKeyException("Key not set for " + typeof(T).FullName); } var fullKey = mutator?.KeyPrefix + key; if (!Info <T> .Configuration.UseCaching || bypassCache) { return(FetchModel(key, mutator)); } return(CacheFactory.FetchModel <T>(fullKey) ?? FetchModel(key, mutator)); }
public override void mutate(Mutator mutator) { sbyte value = Registers.validateRegister(mutator.NextByte); register1 = value; value = Registers.validateRegister(mutator.NextByte); register2 = value; }
private IMongoCollection <T> Collection <T>(Mutator mutator = null) { var referenceCode = mutator?.SetCode; var collectionName = GetCollectionName(referenceCode); var collection = Database.GetCollection <T>(collectionName); return(collection); }
public static long Count(Mutator mutator = null) { ValidateState(EActionType.Read); mutator = Info <T> .Settings.GetInstancedModifier().Value.BeforeCount(EActionType.Read, mutator) ?? mutator; return(Info <T> .Settings.Adapter.Count(mutator)); }
public static IEnumerable <TU> Query <TU>(Mutator mutator = null) { ValidateState(EActionType.Read); mutator = Info <T> .Settings.GetInstancedModifier().Value.BeforeQuery(EActionType.Read, mutator) ?? mutator; return(Info <T> .Settings.Adapter.Query <TU>(mutator)); }
public static IEnumerable <T> GetByLocator(IEnumerable <string> locators, Mutator mutator = null) { var model = Where(i => locators.Contains((i as IDataLocator).Locator), mutator).ToList(); model.AfterGet(); return(model); }
public void AddMutator(Mutator mutator) { _addedMutators.Add(mutator); if (Active) { GetSelector().AddMutator(UnityEngine.Object.Instantiate(mutator)); } }
public virtual void Initialize() { _storage = new IndividualStorage <TIndividual, TGeneStructure, TGene>(Algorithm); Mutator.Algorithm = Algorithm; Mutator.Initialize(); Filter.Algorithm = Algorithm; Filter.Initialize(); }
public override bool KeyExists(string key, Mutator mutator = null) { if (Get(key) != null) { return(true); } return(false); }
public override T Get(string key, Mutator mutator = null) { var statement = $"$._id = '{key}'"; var model = Collection().FindOne(statement); return(model); }
internal void RemoveMutator(Mutator mutator) { _addedMutators.RemoveAll(x => x.Identifier == mutator.Identifier); if (Active) { GetSelector().RemoveMutator(mutator.Identifier); } }
private void EnableMutator(Mutator obj) { Destroy(GetAvailableMutator(obj.Identifier).gameObject); CreateEnabledButton(obj).Assign(obj, DisableMutator); BattlefieldSettings.CurrentSettings.AddMutator(obj); LayoutRebuilder.ForceRebuildLayoutImmediate(EnabledParent as RectTransform); }
public virtual void Process <T>(EActionType type, EActionScope scope, Mutator mutator, T current, T source) where T : Data <T> { var client = new AmazonSimpleNotificationServiceClient(Region); var payload = RenderPayload(type, scope, mutator, current, source); SendMessage(client, payload).Wait(); }
public T Save(Mutator mutator = null) { if (_isDeleted) { return(null); } ValidateState(EActionType.Update); var localModel = (T)this; T storedModel = null; var isNew = IsNew(ref storedModel, mutator); var targetActionType = isNew ? EActionType.Insert : EActionType.Update; localModel = ProcBeforePipeline(targetActionType, EActionScope.Model, mutator, localModel, storedModel); if (localModel == null) { return(null); } if (isNew) { BeforeInsert(); } else { BeforeUpdate(); } BeforeSave(); var postKey = Info <T> .Settings.Adapter.Upsert(localModel).GetDataKey(); Info <T> .TryFlushCachedModel(localModel); if (isNew) { AfterInsert(postKey); } else { AfterUpdate(postKey); } AfterSave(postKey); _isNew = null; if (Info <T> .Settings?.Pipelines?.After == null) { return(localModel); } localModel = Get(postKey, mutator); ProcAfterPipeline(targetActionType, EActionScope.Model, mutator, localModel, storedModel); return(localModel); }
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 override void BulkRemove(IEnumerable <T> models, Mutator mutator = null) { var keyBuffer = models.Select(i => i.GetDataKey()).ToList(); foreach (var data in keyBuffer) { Remove(data); } }
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 Fix(Mutator mutator) { int weight = SumWeight(); while (weight > _knapsack.Capacity) { int idx = mutator.Rand(_presence.Length); int dir = mutator.Rand(2); int found = -1; if (dir == 0) { for (int i = idx; i < _presence.Length; i++) { if (_presence[idx]) { found = idx; break; } } } else { for (int i = idx; i >= 0; i--) { if (_presence[idx]) { found = idx; break; } } } if (found >= 0) { _presence[found] = false; weight -= _knapsack.ItemValues[found * 2]; } } }
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); }
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(); }
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 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); }
/// <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 void Mutate(Mutator mutator, int count) { Debug.Assert(count <= _presence.Length); mutator.Mutate(_presence, count); }
public void Randomize(Mutator mutator) { Mutate(mutator, _presence.Length); }