static byte[] Encrypt(ObfuscationHelper helper, byte[] buff, byte[] dat, out byte[] iv, byte key) { key += Convert.ToByte(Math.Max(Math.Pow(2d, 2), Math.Pow(35d, 1d))); dat = (byte[])dat.Clone(); SHA512 sha = SHA512.Create(); byte[] c = sha.ComputeHash(buff); for (int i = 0; i < dat.Length; i += 64) { byte[] o = new byte[64]; int len = dat.Length <= i + 64 ? dat.Length : i + 64; Buffer.BlockCopy(dat, i, o, 0, len - i); for (int j = i; j < len; j++) { dat[j] ^= (byte)(c[j - i] ^ key); //CHANGED DATA } c = sha.ComputeHash(o); } RijndaelManaged ri = helper.CreateRijndael(); iv = ri.IV; MemoryStream ret = new MemoryStream(); using (CryptoStream cStr = new CryptoStream(ret, ri.CreateEncryptor(SHA256.Create().ComputeHash(buff), iv), CryptoStreamMode.Write)) cStr.Write(dat, 0, dat.Length); return(ret.ToArray()); }
private void ProcessSafe(ConfusionParameter parameter) { _Context txt = cc.txts[mod]; TypeDefinition modType = mod.GetType("<Module>"); FieldDefinition constTbl = new FieldDefinition( ObfuscationHelper.GetRandomName(), FieldAttributes.Static | FieldAttributes.CompilerControlled, mod.Import(typeof(Dictionary <uint, object>))); modType.Fields.Add(constTbl); AddHelper(constTbl, HelperAttribute.NoInjection); Database.AddEntry("Const", "ConstTbl", constTbl.FullName); FieldDefinition constBuffer = new FieldDefinition( ObfuscationHelper.GetRandomName(), FieldAttributes.Static | FieldAttributes.CompilerControlled, mod.Import(typeof(byte[]))); modType.Fields.Add(constBuffer); AddHelper(constBuffer, HelperAttribute.NoInjection); Database.AddEntry("Const", "ConstBuffer", constBuffer.FullName); txt.consters = CreateConsters(txt, Random, "InitializeSafe", constTbl, constBuffer); }
void PerformMethod(MethodDefinition mtd, NameMode mode) { if (GetRenOk(mtd)) { mtd.Name = ObfuscationHelper.GetNewName(mtd.Name, mode); Identifier id = (Identifier)(mtd as IAnnotationProvider).Annotations[NameAnalyzer.RenId]; Identifier n = id; n.scope = mtd.DeclaringType.FullName; n.name = mtd.Name; foreach (IReference refer in (mtd as IAnnotationProvider).Annotations[NameAnalyzer.RenRef] as List <IReference> ) { refer.UpdateReference(id, n); } foreach (ParameterDefinition para in mtd.Parameters) { para.Name = ObfuscationHelper.GetNewName(para.Name, mode); } } //Variable names are stored in pdb, so no need to rename //if (mtd.HasBody) //{ // foreach (VariableDefinition var in mtd.Body.Variables) // { // var.Name = ObfuscationHelper.GetNewName(var.Name, mode); // } //} }
void PerformMethod(MethodDefinition mtd) { if ((bool)(mtd as IAnnotationProvider).Annotations["RenOk"]) { mtd.Name = ObfuscationHelper.GetNewName(mtd.Name); Identifier id = (Identifier)(mtd as IAnnotationProvider).Annotations["RenId"]; Identifier n = id; n.scope = mtd.DeclaringType.FullName; n.name = mtd.Name; foreach (IReference refer in (mtd as IAnnotationProvider).Annotations["RenRef"] as List <IReference> ) { refer.UpdateReference(id, n); } } foreach (ParameterDefinition para in mtd.Parameters) { para.Name = ObfuscationHelper.GetNewName(para.Name); } if (mtd.HasBody) { foreach (VariableDefinition var in mtd.Body.Variables) { var.Name = ObfuscationHelper.GetNewName(var.Name); } } }
public override void Process(ConfusionParameter parameter) { IMemberDefinition mem = parameter.Target as IMemberDefinition; if (GetCancel(mem)) { return; } if (mem is TypeDefinition) { TypeDefinition type = mem as TypeDefinition; if (GetRenOk(type)) { string originalName = type.Name; string originalFName = TypeParser.ToParseable(type); var mode = (NameMode)(mem.Module as IAnnotationProvider).Annotations[NameAnalyzer.RenMode]; type.Name = ObfuscationHelper.GetNewName(originalFName, mode); switch (mode) { case NameMode.Unreadable: type.Namespace = ""; break; case NameMode.ASCII: type.Namespace = " "; break; case NameMode.Letters: type.Namespace = "BANANA"; break; } Identifier id = (Identifier)(type as IAnnotationProvider).Annotations[NameAnalyzer.RenId]; Identifier n = id; n.name = CecilHelper.GetName(type); n.scope = CecilHelper.GetNamespace(type); foreach (IReference refer in (type as IAnnotationProvider).Annotations[NameAnalyzer.RenRef] as List <IReference> ) { refer.UpdateReference(id, n); } Database.AddEntry("Rename", originalName, type.Name); } } else if (mem is MethodDefinition) { MethodDefinition mtd = mem as MethodDefinition; PerformMethod(mtd); } else if (GetRenOk(mem as IAnnotationProvider)) { mem.Name = ObfuscationHelper.GetNewName(mem.Name, (NameMode)(mem.Module as IAnnotationProvider).Annotations[NameAnalyzer.RenMode]); Identifier id = (Identifier)(mem as IAnnotationProvider).Annotations[NameAnalyzer.RenId]; Identifier n = id; n.scope = mem.DeclaringType.FullName; n.name = mem.Name; foreach (IReference refer in (mem as IAnnotationProvider).Annotations[NameAnalyzer.RenRef] as List <IReference> ) { refer.UpdateReference(id, n); } } }
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) { AssemblyDefinition i = AssemblyDefinition.ReadAssembly(typeof(Iid).Assembly.Location); cion.root = CecilHelper.Inject(mod, i.MainModule.GetType("AntiTamper")); mod.Types.Add(cion.root); MethodDefinition cctor = mod.GetType("<Module>").GetStaticConstructor(); cctor.Body.GetILProcessor().InsertBefore(0, Instruction.Create(OpCodes.Call, cion.root.Methods.FirstOrDefault(mtd => mtd.Name == "Initalize"))); MethodDefinition init = cion.root.Methods.FirstOrDefault(mtd => mtd.Name == "Initalize"); foreach (Instruction inst in init.Body.Instructions) { if (inst.Operand is int) { switch ((int)inst.Operand) { case 0x11111111: inst.Operand = cion.key0; break; case 0x33333333: inst.Operand = cion.key2; break; case 0x44444444: inst.Operand = cion.key3; break; case 0x55555555: inst.Operand = cion.key4; break; } } else if (inst.Operand is long && (long)inst.Operand == 0x2222222222222222) { inst.Operand = cion.key1; } } MethodDefinition dec = cion.root.Methods.FirstOrDefault(mtd => mtd.Name == "Decrypt"); foreach (Instruction inst in dec.Body.Instructions) { if (inst.Operand is int && (int)inst.Operand == 0x11111111) { inst.Operand = (int)cion.key5; } } cion.root.Name = ObfuscationHelper.GetNewName("AntiTamperModule" + Guid.NewGuid().ToString()); cion.root.Namespace = ""; AddHelper(cion.root, HelperAttribute.NoInjection); foreach (MethodDefinition mtdDef in cion.root.Methods) { mtdDef.Name = ObfuscationHelper.GetNewName(mtdDef.Name + Guid.NewGuid().ToString()); AddHelper(mtdDef, HelperAttribute.NoInjection); } }
public override void Process(ConfusionParameter parameter) { AssemblyDefinition self = AssemblyDefinition.ReadAssembly(typeof(Iid).Assembly.Location); Database.AddEntry("AntiDebug", "Win32", Array.IndexOf(parameter.GlobalParameters.AllKeys, "win32") != -1); if (Array.IndexOf(parameter.GlobalParameters.AllKeys, "win32") != -1) { TypeDefinition type = CecilHelper.Inject(mod, self.MainModule.GetType("AntiDebugger")); type.Methods.Remove(type.Methods.FirstOrDefault(mtd => mtd.Name == "AntiDebugSafe")); type.Methods.Remove(type.Methods.FirstOrDefault(mtd => mtd.Name == "InitializeSafe")); mod.Types.Add(type); TypeDefinition modType = mod.GetType("<Module>"); ILProcessor psr = modType.GetStaticConstructor().Body.GetILProcessor(); psr.InsertBefore(psr.Body.Instructions.Count - 1, Instruction.Create(OpCodes.Call, type.Methods.FirstOrDefault(mtd => mtd.Name == "Initialize"))); type.Name = ObfuscationHelper.GetRandomName(); type.Namespace = ""; AddHelper(type, HelperAttribute.NoInjection); foreach (MethodDefinition mtdDef in type.Methods) { mtdDef.Name = ObfuscationHelper.GetRandomName(); AddHelper(mtdDef, HelperAttribute.NoInjection); } Database.AddEntry("AntiDebug", "Helper", type.FullName); } else { TypeDefinition type = CecilHelper.Inject(mod, self.MainModule.GetType("AntiDebugger")); type.Methods.Remove(type.Methods.FirstOrDefault(mtd => mtd.Name == "AntiDebug")); type.Methods.Remove(type.Methods.FirstOrDefault(mtd => mtd.Name == "Initialize")); mod.Types.Add(type); TypeDefinition modType = mod.GetType("<Module>"); ILProcessor psr = modType.GetStaticConstructor().Body.GetILProcessor(); psr.InsertBefore(psr.Body.Instructions.Count - 1, Instruction.Create(OpCodes.Call, type.Methods.FirstOrDefault(mtd => mtd.Name == "InitializeSafe"))); type.Name = ObfuscationHelper.GetRandomName(); type.Namespace = ""; AddHelper(type, HelperAttribute.NoInjection); foreach (MethodDefinition mtdDef in type.Methods) { mtdDef.Name = ObfuscationHelper.GetRandomName(); AddHelper(mtdDef, HelperAttribute.NoInjection); } Database.AddEntry("AntiDebug", "Helper", type.FullName); } }
public override void Process(ConfusionParameter parameter) { AssemblyDefinition self = AssemblyDefinition.ReadAssembly(typeof(Iid).Assembly.Location); TypeDefinition type = CecilHelper.Inject(mod, self.MainModule.GetType("AntiDumping")); mod.Types.Add(type); TypeDefinition modType = mod.GetType("<Module>"); ILProcessor psr = modType.GetStaticConstructor().Body.GetILProcessor(); psr.InsertBefore(psr.Body.Instructions.Count - 1, Instruction.Create(OpCodes.Call, type.Methods.FirstOrDefault(mtd => mtd.Name == "Initalize"))); type.Name = ObfuscationHelper.GetNewName("AntiDumping" + Guid.NewGuid().ToString()); type.Namespace = ""; AddHelper(type, HelperAttribute.NoInjection); foreach (MethodDefinition mtdDef in type.Methods) { mtdDef.Name = ObfuscationHelper.GetNewName(mtdDef.Name + Guid.NewGuid().ToString()); AddHelper(mtdDef, HelperAttribute.NoInjection); } }
public override void DeInitialize() { TypeDefinition modType = mod.GetType("<Module>"); AssemblyDefinition i = AssemblyDefinition.ReadAssembly(typeof(Iid).Assembly.Location); mc.proxy = i.MainModule.GetType("Proxies").Methods.FirstOrDefault(mtd => mtd.Name == "MtdProxy"); mc.proxy = CecilHelper.Inject(mod, mc.proxy); modType.Methods.Add(mc.proxy); mc.proxy.IsAssembly = true; mc.proxy.Name = ObfuscationHelper.GetNewName("Proxy" + Guid.NewGuid().ToString()); AddHelper(mc.proxy, 0); mc.key = new Random().Next(); foreach (Instruction inst in mc.proxy.Body.Instructions) { if (inst.Operand is int && (int)inst.Operand == 0x12345678) { inst.Operand = mc.key; break; } } }
public override void Process(ConfusionParameter parameter) { IMemberDefinition mem = parameter.Target as IMemberDefinition; if (mem is TypeDefinition) { TypeDefinition type = mem as TypeDefinition; if ((bool)(type as IAnnotationProvider).Annotations["RenOk"]) { type.Name = ObfuscationHelper.GetNewName(type.FullName); type.Namespace = ""; Identifier id = (Identifier)(type as IAnnotationProvider).Annotations["RenId"]; Identifier n = id; n.name = type.Name; n.scope = type.Namespace; foreach (IReference refer in (type as IAnnotationProvider).Annotations["RenRef"] as List <IReference> ) { refer.UpdateReference(id, n); } } } else if (mem is MethodDefinition) { MethodDefinition mtd = mem as MethodDefinition; PerformMethod(mtd); } else if ((bool)(mem as IAnnotationProvider).Annotations["RenOk"]) { mem.Name = ObfuscationHelper.GetNewName(mem.Name); Identifier id = (Identifier)(mem as IAnnotationProvider).Annotations["RenId"]; Identifier n = id; n.scope = mem.DeclaringType.FullName; n.name = mem.Name; foreach (IReference refer in (mem as IAnnotationProvider).Annotations["RenRef"] as List <IReference> ) { refer.UpdateReference(id, n); } } }
public override void Initialize(ModuleDefinition mod) { foreach (var di in ObfuscationHelper.StringGen.DynGen.Dynamics) { foreach (var mtd in di.Wrapper.Methods) { if (mtd.IsRuntimeSpecialName || mtd.IsConstructor || mtd.IsSpecialName) { continue; } mtd.Name = ObfuscationHelper.GetRandomName(); } foreach (var fd in di.Wrapper.Fields) { fd.Name = ObfuscationHelper.GetRandomName(); } //if (di.Wrapper.Methods.FirstOrDefault(x => x.Name.StartsWith("DYN__")) != null) //{ // mod.Types.Remove(di.Wrapper); //} } }
static byte[] Encrypt(ObfuscationHelper helper, byte[] buff, byte[] dat, out byte[] iv, byte key) { dat = (byte[])dat.Clone(); SHA512 sha = SHA512.Create(); byte[] c = sha.ComputeHash(buff); for (int i = 0; i < dat.Length; i += 64) { byte[] o = new byte[64]; int len = dat.Length <= i + 64 ? dat.Length : i + 64; Buffer.BlockCopy(dat, i, o, 0, len - i); for (int j = i; j < len; j++) dat[j] ^= (byte)(c[j - i] ^ key); c = sha.ComputeHash(o); } RijndaelManaged ri = helper.CreateRijndael(); iv = ri.IV; MemoryStream ret = new MemoryStream(); using (CryptoStream cStr = new CryptoStream(ret, ri.CreateEncryptor(SHA256.Create().ComputeHash(buff), iv), CryptoStreamMode.Write)) cStr.Write(dat, 0, dat.Length); return ret.ToArray(); }
byte[] GetAsm() { AssemblyDefinition asm = AssemblyDefinition.CreateAssembly(new AssemblyNameDefinition(ObfuscationHelper.GetNewName(Guid.NewGuid().ToString()), new Version()), ObfuscationHelper.GetNewName(Guid.NewGuid().ToString()), ModuleKind.Dll); foreach (KeyValuePair <string, byte[]> i in rc.dats) { asm.MainModule.Resources.Add(new EmbeddedResource(i.Key, ManifestResourceAttributes.Public, i.Value)); } MemoryStream ms = new MemoryStream(); asm.Write(ms); return(ms.ToArray()); }
string GetNameO(MethodReference mbr) { return(ObfuscationHelper.GetNewName(mbr.ToString())); }
string GetSignatureO(MethodReference mbr) { return(ObfuscationHelper.GetNewName(GetSignature(mbr))); }
public override void Process(NameValueCollection parameters, MetadataProcessor.MetadataAccessor accessor) { _Context _txt = mc.txts[accessor.Module]; for (int i = 0; i < _txt.txts.Count; i++) { int j = Random.Next(0, _txt.txts.Count); var tmp = _txt.txts[i]; _txt.txts[i] = _txt.txts[j]; _txt.txts[j] = tmp; } TypeDefinition typeDef = new TypeDefinition("", "", 0); foreach (Context txt in _txt.txts) { txt.token = accessor.LookupToken(txt.mtdRef); if (txt.fld.Name[0] != '\0') { continue; } txt.fld.Name = (txt.isVirt ? _txt.keyChar1 : _txt.keyChar2) + "\n" + ObfuscationHelper.GetRandomName(); //Hack into cecil to generate diff sig for diff field -_- int pos = txt.fld.DeclaringType.Fields.IndexOf(txt.fld) + 1; while (typeDef.GenericParameters.Count < pos) { typeDef.GenericParameters.Add(new GenericParameter(typeDef)); } txt.fld.FieldType = new GenericInstanceType(txt.fld.FieldType) { GenericArguments = { accessor.Module.TypeSystem.Object, accessor.Module.TypeSystem.Object, accessor.Module.TypeSystem.Object, accessor.Module.TypeSystem.Object, accessor.Module.TypeSystem.Object, typeDef.GenericParameters[pos - 1] } }; Database.AddEntry("MtdProxy", (txt.isVirt ? "callvirt " : "call ") + txt.mtdRef.FullName, txt.fld.Name); Database.AddEntry("MtdProxy", txt.fld.Name, txt.inst.Operand.ToString()); } if (!_txt.isNative) { return; } _txt.nativeRange = new Range(accessor.Codebase + (uint)accessor.Codes.Position, 0); MemoryStream ms = new MemoryStream(); using (BinaryWriter wtr = new BinaryWriter(ms)) { wtr.Write(new byte[] { 0x89, 0xe0 }); // mov eax, esp wtr.Write(new byte[] { 0x53 }); // push ebx wtr.Write(new byte[] { 0x57 }); // push edi wtr.Write(new byte[] { 0x56 }); // push esi wtr.Write(new byte[] { 0x29, 0xe0 }); // sub eax, esp wtr.Write(new byte[] { 0x83, 0xf8, 0x18 }); // cmp eax, 24 wtr.Write(new byte[] { 0x74, 0x07 }); // je n wtr.Write(new byte[] { 0x8b, 0x44, 0x24, 0x10 }); // mov eax, [esp + 4] wtr.Write(new byte[] { 0x50 }); // push eax wtr.Write(new byte[] { 0xeb, 0x01 }); // jmp z wtr.Write(new byte[] { 0x51 }); //n: push ecx x86Register ret; //z: var insts = _txt.visitor.GetInstructions(out ret); foreach (var i in insts) { wtr.Write(i.Assemble()); } if (ret != x86Register.EAX) { wtr.Write( new x86Instruction() { OpCode = x86OpCode.MOV, Operands = new Ix86Operand[] { new x86RegisterOperand() { Register = x86Register.EAX }, new x86RegisterOperand() { Register = ret } } }.Assemble()); } wtr.Write(new byte[] { 0x5e }); //pop esi wtr.Write(new byte[] { 0x5f }); //pop edi wtr.Write(new byte[] { 0x5b }); //pop ebx wtr.Write(new byte[] { 0xc3 }); //ret wtr.Write(new byte[((ms.Length + 3) & ~3) - ms.Length]); } byte[] codes = ms.ToArray(); Database.AddEntry("MtdProxy", "Native", codes); accessor.Codes.WriteBytes(codes); accessor.SetCodePosition(accessor.Codebase + (uint)accessor.Codes.Position); _txt.nativeRange.Length = (uint)codes.Length; }
string GetNameO(bool isVirt, MethodReference mbr) { return(ObfuscationHelper.GetNewName((isVirt ? "V>." : "") + mbr.ToString())); }
string GetNameO(ParameterDefinition arg) { return(ObfuscationHelper.GetNewName(arg.Name)); }
public override void Process(NameValueCollection parameters, MetadataProcessor.MetadataAccessor accessor) { accessor.TableHeap.GetTable <TypeDefTable>(Table.TypeDef)[0].Col2 = 0xffff; uint mtdLen = (uint)accessor.TableHeap.GetTable <MethodTable>(Table.Method).Length + 1; uint fldLen = (uint)accessor.TableHeap.GetTable <FieldTable>(Table.Field).Length + 1; Database.AddEntry("InvalidMd", "HasReflection", Array.IndexOf(parameters.AllKeys, "hasreflection") != -1); Database.AddEntry("InvalidMd", "Runtime", accessor.Module.Runtime); if (Array.IndexOf(parameters.AllKeys, "hasreflection") == -1) { if (accessor.Module.Runtime != TargetRuntime.Net_4_0) { List <uint> nss = new List <uint>(); foreach (Row <TypeAttributes, uint, uint, uint, uint, uint> i in accessor.TableHeap.GetTable <TypeDefTable>(Table.TypeDef)) { if (i == null) { break; } else if (!nss.Contains(i.Col3)) { nss.Add(i.Col3); } } uint nested = (uint)accessor.TableHeap.GetTable <TypeDefTable>(Table.TypeDef).AddRow(new Row <TypeAttributes, uint, uint, uint, uint, uint>(0, 0x7fffffff, 0, 0x3FFFD, fldLen, mtdLen)); accessor.TableHeap.GetTable <NestedClassTable>(Table.NestedClass).AddRow(new Row <uint, uint>(nested, nested)); foreach (uint i in nss) { uint type = (uint)accessor.TableHeap.GetTable <TypeDefTable>(Table.TypeDef).AddRow(new Row <TypeAttributes, uint, uint, uint, uint, uint>(0, 0x7fffffff, i, 0x3FFFD, fldLen, mtdLen)); accessor.TableHeap.GetTable <NestedClassTable>(Table.NestedClass).AddRow(new Row <uint, uint>(nested, type)); } foreach (Row <ParameterAttributes, ushort, uint> r in accessor.TableHeap.GetTable <ParamTable>(Table.Param)) { if (r != null) { r.Col3 = 0x7fffffff; } } } } accessor.TableHeap.GetTable <ModuleTable>(Table.Module).AddRow(accessor.StringHeap.GetStringIndex(ObfuscationHelper.GetRandomName())); accessor.TableHeap.GetTable <AssemblyTable>(Table.Assembly).AddRow(new Row <AssemblyHashAlgorithm, ushort, ushort, ushort, ushort, AssemblyAttributes, uint, uint, uint>( AssemblyHashAlgorithm.None, 0, 0, 0, 0, AssemblyAttributes.SideBySideCompatible, 0, accessor.StringHeap.GetStringIndex(ObfuscationHelper.GetRandomName()), 0)); for (int i = 0; i < 10; i++) { accessor.TableHeap.GetTable <ENCLogTable>(Table.EncLog).AddRow(new Row <uint, uint>((uint)Random.Next(), (uint)Random.Next())); } for (int i = 0; i < 10; i++) { accessor.TableHeap.GetTable <ENCMapTable>(Table.EncMap).AddRow((uint)Random.Next()); } accessor.TableHeap.GetTable <AssemblyRefTable>(Table.AssemblyRef).AddRow(new Row <ushort, ushort, ushort, ushort, AssemblyAttributes, uint, uint, uint, uint>( 0, 0, 0, 0, AssemblyAttributes.SideBySideCompatible, 0, 0xffff, 0, 0xffff)); Randomize(accessor.TableHeap.GetTable <NestedClassTable>(Table.NestedClass)); Randomize(accessor.TableHeap.GetTable <ManifestResourceTable>(Table.ManifestResource)); Randomize(accessor.TableHeap.GetTable <GenericParamConstraintTable>(Table.GenericParamConstraint)); }
public DynamicInfo CreateDynamic(Expression exP, Expression exR, int input, int output, bool useMath) { TypeDefinition injType = CecilHelper.Inject(Module, injection.MainModule.GetType("PolyInjection")); injType.Name = ObfuscationHelper.Instance.GetRandomName(); FieldDefinition dmInstance = injType.Fields.FirstOrDefault(x => x.Name == "dm"); FieldDefinition delInstance = injType.Fields.FirstOrDefault(x => x.Name == "Invoke"); MethodDefinition initMd = injType.Methods.FirstOrDefault(x => x.Name == "Initialize"); initMd.Name = "DYN___" + initMd.Name; ILProcessor ilp = initMd.Body.GetILProcessor(); for (int i = 0; i < initMd.Body.Instructions.Count; i++) { Instruction inst = initMd.Body.Instructions[i]; if (inst.Operand is FieldReference) { if ((inst.Operand as FieldReference).Name == "dm") { inst.Operand = dmInstance; } else if ((inst.Operand as FieldReference).Name == "Invoke") { inst.Operand = delInstance; } if ((inst.Operand as FieldReference).Name == "MethodName") { inst.OpCode = OpCodes.Ldstr; inst.Operand = ObfuscationHelper.GetRandomString(rand.Next(1, 5)); } } } // Ldarg_0 is evald CecilVisitor cv = new Visitors.CecilVisitor(exR, new Instruction[] { Instruction.Create(OpCodes.Ldarg_0) }); List <Instruction> cvInsts = cv.GetInstructions().ToList(); for (int i = 0; i < cvInsts.Count; i++) { Instruction cvInst = cvInsts[i]; if (cvInst.OpCode == OpCodes.Ldarg_0) { cvInsts.Insert(i + 1, Instruction.Create(OpCodes.Conv_I4)); i += 1; } } for (int i = 0; i < initMd.Body.Instructions.Count; i++) { Instruction inst = initMd.Body.Instructions[i]; if (inst.OpCode == OpCodes.Ldsfld && (inst.Operand as FieldReference).Name == "Conv_R8") { // Go back two, start inserting i -= 2; Instruction real = initMd.Body.Instructions[i]; List <Instruction> ei = ConvertToEmit(initMd, cvInsts, useMath);//new List<Instruction>(); ei.Reverse(); foreach (Instruction a in ei) { initMd.Body.Instructions.Insert(i + 1, a); } initMd.Body.ComputeHeader(); initMd.Body.ComputeOffsets(); initMd.Body.OptimizeMacros(); break; } } Module.Types.Add(injType); DynamicInfo di = new DynamicInfo(); di.DelegateInstance = delInstance; di.DelegateType = injType.NestedTypes[0]; di.Wrapper = injType; di.Input = input; di.Output = output; di.Exp = exP; Dynamics.Add(di); return(di); }
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()); }
byte[] GetAsm(uint timestamp, List <KeyValuePair <string, byte[]> > dats) { AssemblyDefinition asm = AssemblyDefinition.CreateAssembly(new AssemblyNameDefinition(ObfuscationHelper.GetRandomName(), new Version()), ObfuscationHelper.GetRandomName(), ModuleKind.Dll); foreach (KeyValuePair <string, byte[]> i in dats) { asm.MainModule.Resources.Add(new EmbeddedResource(i.Key, ManifestResourceAttributes.Public, i.Value)); } asm.MainModule.TimeStamp = timestamp; byte[] mvid = new byte[0x10]; Random.NextBytes(mvid); asm.MainModule.Mvid = new Guid(mvid); MemoryStream ms = new MemoryStream(); asm.Write(ms); return(ms.ToArray()); }
public override void Process(ConfusionParameter parameter) { Database.AddEntry("Const", "Type", parameter.GlobalParameters["type"] ?? "normal"); if (parameter.GlobalParameters["type"] != "dynamic" && parameter.GlobalParameters["type"] != "native") { ProcessSafe(parameter); return; } _Context txt = cc.txts[mod]; txt.isNative = parameter.GlobalParameters["type"] == "native"; txt.isDyn = parameter.GlobalParameters["type"] == "dynamic"; TypeDefinition modType = mod.GetType("<Module>"); FieldDefinition constTbl = new FieldDefinition( ObfuscationHelper.GetRandomName(), FieldAttributes.Static | FieldAttributes.CompilerControlled, mod.Import(typeof(Dictionary <uint, object>))); modType.Fields.Add(constTbl); AddHelper(constTbl, HelperAttribute.NoInjection); Database.AddEntry("Const", "ConstTbl", constTbl.FullName); FieldDefinition constBuffer = new FieldDefinition( ObfuscationHelper.GetRandomName(), FieldAttributes.Static | FieldAttributes.CompilerControlled, mod.Import(typeof(byte[]))); modType.Fields.Add(constBuffer); AddHelper(constBuffer, HelperAttribute.NoInjection); Database.AddEntry("Const", "ConstBuffer", constBuffer.FullName); 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("Const", "NativeDecr", txt.nativeDecr.FullName); } var expGen = new ExpressionGenerator(Random.Next()); int seed = expGen.Seed; if (txt.isNative) { do { txt.exp = new ExpressionGenerator(Random.Next()).Generate(6); txt.invExp = ExpressionInverser.InverseExpression(txt.exp); } while ((txt.visitor = new x86Visitor(txt.invExp, null)).RegisterOverflowed); } else { txt.exp = expGen.Generate(10); txt.invExp = ExpressionInverser.InverseExpression(txt.exp); } Database.AddEntry("Const", "Exp", txt.exp); Database.AddEntry("Const", "InvExp", txt.invExp); txt.consters = CreateConsters(txt, Confuser.Random, "Initialize", constTbl, constBuffer); }
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()))); }
public List <Instruction> Generate(MethodDefinition CurrentMethod, int target, int maxLength = 20, bool unsigned = false) { List <Instruction> builder = new List <Instruction>(); DynamicGenerator.DynamicInfo dCall; if (target < 0) { return(new List <Instruction>() { Instruction.Create(OpCodes.Ldc_I4, target) }); } if (target <= maxLength) { // Make one string and use the length of int in the place of the target. Instruction strInst = Instruction.Create(OpCodes.Ldstr, ObfuscationHelper.GetRandomString(target)); if (target == 0 && rand.Next(0, 100) % 2 == 0) { strInst = StringEmpty; } builder.Add(strInst); builder.Add(LengthCall); } else { // Make one string (random length) and use the length of it, + rest (perhaps expression gen for that?). int take = rand.Next(0, 20); Instruction strInst = Instruction.Create(OpCodes.Ldstr, ObfuscationHelper.GetRandomString(take)); if (take == 0 && rand.Next(0, 100) % 2 == 0) { strInst = StringEmpty; } int remainder = target - take; bool hasAdded = false; if (rand.Next(0, 100) % 2 == 0) { builder.Add(strInst); builder.Add(LengthCall); hasAdded = true; } if (rand.Next(0, 100) % 2 == 0) { Expression ex = ExpGen.Generate(5); int evald = ExpressionEvaluator.Evaluate(ex, remainder); Expression exR = ExpressionInverser.InverseExpression(ex); CecilVisitor cv = new Visitors.CecilVisitor(exR, new Instruction[] { Instruction.Create(OpCodes.Ldc_I4, evald) }); builder.AddRange(cv.GetInstructions()); } else if (rand.Next(0, 100) % 2 == 0) { builder.AddRange(MathGen.GenerateLevels(remainder, !unsigned ? OpCodes.Ldc_I4 : OpCodes.Ldc_I4_0, rand.Next(0, 3))); } else if (!CurrentMethod.Name.StartsWith("DYN___")) { builder.AddRange(DynGen.Generate(CurrentMethod, remainder, !unsigned ? OpCodes.Ldc_I4 : OpCodes.Ldc_I4_0, out dCall)); } else { /*Expression ex = ExpGen.Generate(5); * * int evald = ExpressionEvaluator.Evaluate(ex, remainder); * * Expression exR = ExpressionInverser.InverseExpression(ex); * * CecilVisitor cv = new Visitors.CecilVisitor(exR, new Instruction[] { Instruction.Create(OpCodes.Ldc_I4, evald) }); * * builder.AddRange(cv.GetInstructions());*/ builder.AddRange(MathGen.GenerateLevels(remainder, !unsigned ? OpCodes.Ldc_I4 : OpCodes.Ldc_I4_0, rand.Next(0, 4))); } if (!hasAdded) { builder.Add(strInst); builder.Add(LengthCall); } builder.Add(Instruction.Create(OpCodes.Add)); if (unsigned) { builder.Add(Instruction.Create(OpCodes.Conv_U4)); } } return(builder); }