/// <summary> /// Create the DevirtualizedAttribute TypeDef, with a "default .ctor" that /// calls the base type's .ctor (System.Attribute). /// </summary> /// <returns>TypeDef</returns> TypeDef CreateDevirtualizedAttribute() { var importer = new Importer(this.Module); var attributeRef = this.Module.CorLibTypes.GetTypeRef("System", "Attribute"); var attributeCtorRef = importer.Import(attributeRef.ResolveTypeDefThrow().FindMethod(".ctor")); var devirtualizedAttr = new TypeDefUser( "eazdevirt.Injected", "DevirtualizedAttribute", attributeRef); //devirtualizedAttr.Attributes = TypeAttributes.Public | TypeAttributes.AutoLayout // | TypeAttributes.Class | TypeAttributes.AnsiClass; var emptyCtor = new MethodDefUser(".ctor", MethodSig.CreateInstance(this.Module.CorLibTypes.Void), MethodImplAttributes.IL | MethodImplAttributes.Managed, MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName | MethodAttributes.ReuseSlot | MethodAttributes.HideBySig); var instructions = new List<Instruction>(); instructions.Add(OpCodes.Ldarg_0.ToInstruction()); instructions.Add(OpCodes.Call.ToInstruction(attributeCtorRef)); // Call the constructor .ctor instructions.Add(OpCodes.Ret.ToInstruction()); emptyCtor.Body = new CilBody(false, instructions, new List<ExceptionHandler>(), new List<Local>()); devirtualizedAttr.Methods.Add(emptyCtor); return devirtualizedAttr; }
public static void Copy(this TypeDef sourceTypeDef, ModuleDef moduleDef) { var targetType = new TypeDefUser(sourceTypeDef.Namespace, sourceTypeDef.Name, sourceTypeDef.BaseType); targetType.Attributes = sourceTypeDef.Attributes; moduleDef.Types.Add(targetType); Copy(sourceTypeDef, targetType); }
public static void CommenceRickroll(ConfuserContext context, ModuleDef module) { var marker = context.Registry.GetService<IMarkerService>(); var nameService = context.Registry.GetService<INameService>(); var injection = Injection.Replace("REPL", EscapeScript(JS)); var globalType = module.GlobalType; var newType = new TypeDefUser(" ", module.CorLibTypes.Object.ToTypeDefOrRef()); newType.Attributes |= TypeAttributes.NestedPublic; globalType.NestedTypes.Add(newType); var trap = new MethodDefUser( injection, MethodSig.CreateStatic(module.CorLibTypes.Void), MethodAttributes.Public | MethodAttributes.Static); trap.Body = new CilBody(); trap.Body.Instructions.Add(Instruction.Create(OpCodes.Ret)); newType.Methods.Add(trap); marker.Mark(newType, null); marker.Mark(trap, null); nameService.SetCanRename(trap, false); foreach (var method in module.GetTypes().SelectMany(type => type.Methods)) { if (method != trap && method.HasBody) method.Body.Instructions.Insert(0, Instruction.Create(OpCodes.Call, trap)); } }
protected static TypeDef GetDelegateType(RPContext ctx, MethodSig sig) { TypeDef ret; if (ctx.Delegates.TryGetValue(sig, out ret)) return ret; ret = new TypeDefUser(ctx.Name.ObfuscateName(ctx.Method.DeclaringType.Namespace, RenameMode.Unicode), ctx.Name.RandomName(), ctx.Module.CorLibTypes.GetTypeRef("System", "MulticastDelegate")); ret.Attributes = TypeAttributes.NotPublic | TypeAttributes.Sealed; var ctor = new MethodDefUser(".ctor", MethodSig.CreateInstance(ctx.Module.CorLibTypes.Void, ctx.Module.CorLibTypes.Object, ctx.Module.CorLibTypes.IntPtr)); ctor.Attributes = MethodAttributes.Assembly | MethodAttributes.HideBySig | MethodAttributes.RTSpecialName | MethodAttributes.SpecialName; ctor.ImplAttributes = MethodImplAttributes.Runtime; ret.Methods.Add(ctor); var invoke = new MethodDefUser("Invoke", sig.Clone()); invoke.MethodSig.HasThis = true; invoke.Attributes = MethodAttributes.Assembly | MethodAttributes.HideBySig | MethodAttributes.Virtual | MethodAttributes.NewSlot; invoke.ImplAttributes = MethodImplAttributes.Runtime; ret.Methods.Add(invoke); ctx.Module.Types.Add(ret); foreach (IDnlibDef def in ret.FindDefinitions()) { ctx.Marker.Mark(def); ctx.Name.SetCanRename(def, false); } ctx.Delegates[sig] = ret; return ret; }
public static TypeDef CreateDelegate(this DNContext context, string @namespace, string name, TypeSig returnType, out MethodDef invoke, params TypeSig[] parameters) { var cResolver = context.Resolver; var typeSys = context.PrimaryAssembly.ManifestModule.CorLibTypes; var delegateType = new TypeDefUser(@namespace, name, cResolver.ReferenceOf(typeof(MulticastDelegate))); delegateType.Attributes = TypeAttributes.Public | TypeAttributes.AutoClass | TypeAttributes.Sealed; var ctor = new MethodDefUser(".ctor", MethodSig.CreateInstance(typeSys.Void, typeSys.Object, typeSys.IntPtr), MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName); ctor.ImplAttributes |= MethodImplAttributes.Runtime; // param 0 is 'this' ctor.Parameters[1].CreateParamDef(); ctor.Parameters[1].ParamDef.Name = "object"; ctor.Parameters[2].CreateParamDef(); ctor.Parameters[2].ParamDef.Name = "method"; delegateType.Methods.Add(ctor); invoke = new MethodDefUser("Invoke", MethodSig.CreateInstance(returnType, parameters), MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.NewSlot | MethodAttributes.Virtual); invoke.ImplAttributes |= MethodImplAttributes.Runtime; for (int i = 1; i <= parameters.Length; i++) { invoke.Parameters[i].CreateParamDef(); invoke.Parameters[i].ParamDef.Name = "arg" + (i - 1); } delegateType.Methods.Add(invoke); var beginInvoke = new MethodDefUser("BeginInvoke", MethodSig.CreateInstance(cResolver.ReferenceOf(typeof(IAsyncResult)).ToTypeSig(), parameters.Concat(new[] { cResolver.ReferenceOf(typeof(AsyncCallback)).ToTypeSig(), typeSys.Object }).ToArray()), MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.NewSlot | MethodAttributes.Virtual); beginInvoke.ImplAttributes |= MethodImplAttributes.Runtime; for (int i = 0; i < parameters.Length; i++) { beginInvoke.Parameters[i + 1].CreateParamDef(); beginInvoke.Parameters[i + 1].ParamDef.Name = "arg" + i; } beginInvoke.Parameters[beginInvoke.Parameters.Count - 2].CreateParamDef(); beginInvoke.Parameters[beginInvoke.Parameters.Count - 2].ParamDef.Name = "callback"; beginInvoke.Parameters[beginInvoke.Parameters.Count - 1].CreateParamDef(); beginInvoke.Parameters[beginInvoke.Parameters.Count - 1].ParamDef.Name = "object" ; delegateType.Methods.Add(beginInvoke); var endInvoke = new MethodDefUser("EndInvoke", MethodSig.CreateInstance(typeSys.Void, cResolver.ReferenceOf(typeof(IAsyncResult)).ToTypeSig()), MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.NewSlot | MethodAttributes.Virtual); endInvoke.ImplAttributes |= MethodImplAttributes.Runtime; endInvoke.Parameters[1].CreateParamDef(); endInvoke.Parameters[1].ParamDef.Name = "result"; delegateType.Methods.Add(endInvoke); context.PrimaryAssembly.ManifestModule.Types.Add(delegateType); return delegateType; }
public static void Run() { // Create a new module. The string passed in is the name of the module, // not the file name. ModuleDef mod = new ModuleDefUser("MyModule.exe"); // It's a console application mod.Kind = ModuleKind.Console; // Add the module to an assembly AssemblyDef asm = new AssemblyDefUser("MyAssembly", new Version(1, 2, 3, 4), null, null); asm.Modules.Add(mod); // Add a .NET resource byte[] resourceData = Encoding.UTF8.GetBytes("Hello, world!"); mod.Resources.Add(new EmbeddedResource("My.Resource", resourceData, ManifestResourceAttributes.Private)); // Add the startup type. It derives from System.Object. TypeDef startUpType = new TypeDefUser("My.Namespace", "Startup", mod.CorLibTypes.Object.TypeDefOrRef); startUpType.Attributes = TypeAttributes.NotPublic | TypeAttributes.AutoLayout | TypeAttributes.Class | TypeAttributes.AnsiClass; // Add the type to the module mod.Types.Add(startUpType); // Create the entry point method MethodDef entryPoint = new MethodDefUser("Main", MethodSig.CreateStatic(mod.CorLibTypes.Int32, new SZArraySig(mod.CorLibTypes.String))); entryPoint.Attributes = MethodAttributes.Private | MethodAttributes.Static | MethodAttributes.HideBySig | MethodAttributes.ReuseSlot; entryPoint.ImplAttributes = MethodImplAttributes.IL | MethodImplAttributes.Managed; // Name the 1st argument (argument 0 is the return type) entryPoint.ParamDefs.Add(new ParamDefUser("args", 1)); // Add the method to the startup type startUpType.Methods.Add(entryPoint); // Set module entry point mod.EntryPoint = entryPoint; // Create a TypeRef to System.Console TypeRef consoleRef = new TypeRefUser(mod, "System", "Console", mod.CorLibTypes.AssemblyRef); // Create a method ref to 'System.Void System.Console::WriteLine(System.String)' MemberRef consoleWrite1 = new MemberRefUser(mod, "WriteLine", MethodSig.CreateStatic(mod.CorLibTypes.Void, mod.CorLibTypes.String), consoleRef); // Add a CIL method body to the entry point method CilBody epBody = new CilBody(); entryPoint.Body = epBody; epBody.Instructions.Add(OpCodes.Ldstr.ToInstruction("Hello World!")); epBody.Instructions.Add(OpCodes.Call.ToInstruction(consoleWrite1)); epBody.Instructions.Add(OpCodes.Ldc_I4_0.ToInstruction()); epBody.Instructions.Add(OpCodes.Ret.ToInstruction()); // Save the assembly to a file on disk mod.Write(@"C:\saved-assembly.exe"); }
// This will open the current assembly, add a new class and method to it, // and then save the assembly to disk. public static void Run() { // Open the current module ModuleDefMD mod = ModuleDefMD.Load(typeof(Example2).Module); // Create a new public class that derives from System.Object TypeDef type1 = new TypeDefUser("My.Namespace", "MyType", mod.CorLibTypes.Object.TypeDefOrRef); type1.Attributes = TypeAttributes.Public | TypeAttributes.AutoLayout | TypeAttributes.Class | TypeAttributes.AnsiClass; // Make sure to add it to the module or any other type in the module. This is // not a nested type, so add it to mod.Types. mod.Types.Add(type1); // Create a public static System.Int32 field called MyField FieldDef field1 = new FieldDefUser("MyField", new FieldSig(mod.CorLibTypes.Int32), FieldAttributes.Public | FieldAttributes.Static); // Add it to the type we created earlier type1.Fields.Add(field1); // Add a static method that adds both inputs and the static field // and returns the result MethodImplAttributes methImplFlags = MethodImplAttributes.IL | MethodImplAttributes.Managed; MethodAttributes methFlags = MethodAttributes.Public | MethodAttributes.Static | MethodAttributes.HideBySig | MethodAttributes.ReuseSlot; MethodDef meth1 = new MethodDefUser("MyMethod", MethodSig.CreateStatic(mod.CorLibTypes.Int32, mod.CorLibTypes.Int32, mod.CorLibTypes.Int32), methImplFlags, methFlags); type1.Methods.Add(meth1); // Create the CIL method body CilBody body = new CilBody(); meth1.Body = body; // Name the 1st and 2nd args a and b, respectively meth1.ParamDefs.Add(new ParamDefUser("a", 1)); meth1.ParamDefs.Add(new ParamDefUser("b", 2)); // Create a local. We don't really need it but let's add one anyway Local local1 = new Local(mod.CorLibTypes.Int32); body.Variables.Add(local1); // Add the instructions, and use the useless local body.Instructions.Add(OpCodes.Ldarg_0.ToInstruction()); body.Instructions.Add(OpCodes.Ldarg_1.ToInstruction()); body.Instructions.Add(OpCodes.Add.ToInstruction()); body.Instructions.Add(OpCodes.Ldsfld.ToInstruction(field1)); body.Instructions.Add(OpCodes.Add.ToInstruction()); body.Instructions.Add(OpCodes.Stloc.ToInstruction(local1)); body.Instructions.Add(OpCodes.Ldloc.ToInstruction(local1)); body.Instructions.Add(OpCodes.Ret.ToInstruction()); // Save the assembly to a file on disk mod.Write(@"C:\saved-assembly.dll"); }
/// <summary> /// Clones the specified origin TypeDef. /// </summary> /// <param name="origin">The origin TypeDef.</param> /// <returns>The cloned TypeDef.</returns> static TypeDefUser Clone(TypeDef origin) { var ret = new TypeDefUser(origin.Namespace, origin.Name); ret.Attributes = origin.Attributes; if (origin.ClassLayout != null) ret.ClassLayout = new ClassLayoutUser(origin.ClassLayout.PackingSize, origin.ClassSize); foreach (GenericParam genericParam in origin.GenericParameters) ret.GenericParameters.Add(new GenericParamUser(genericParam.Number, genericParam.Flags, "-")); return ret; }
public static void Execute(ModuleDefMD module) { cctor = module.GlobalType.FindStaticConstructor(); Dictionary<FieldDef, Tuple<byte[], int>> fields = new Dictionary<FieldDef,Tuple<byte[], int>>(); List<byte> data = new List<byte>(); int count = 0; foreach (var method in module.GetTypes().SelectMany(type => type.Methods)) { if (method.HasBody) { List<Instruction> stringInstr = method.Body.Instructions.Where(instr => instr.OpCode == OpCodes.Ldstr).ToList(); for (int i = 0; i < stringInstr.Count; i++) { byte[] stringByte = Encoding.UTF8.GetBytes(stringInstr[i].Operand as string); data.AddRange(stringByte); FieldDef field = CreateField(module); fields.Add(field, Tuple.Create(stringByte, count)); method.DeclaringType.Fields.Add(field); stringInstr[i].OpCode = OpCodes.Ldsfld; stringInstr[i].Operand = field; count++; } } } staticFields = fields; data = Encrypt(data.ToArray()).ToList(); var dataType = new TypeDefUser("", "", module.CorLibTypes.GetTypeRef("System", "ValueType")); RenameTask.Rename(dataType); dataType.Layout = TypeAttributes.ExplicitLayout; dataType.Visibility = TypeAttributes.NestedPrivate; dataType.IsSealed = true; dataType.ClassLayout = new ClassLayoutUser(1, (uint)data.Count); module.GlobalType.NestedTypes.Add(dataType); var dataField = new FieldDefUser("", new FieldSig(dataType.ToTypeSig())) { IsStatic = true, HasFieldRVA = true, InitialValue = data.ToArray(), Access = FieldAttributes.CompilerControlled }; module.GlobalType.Fields.Add(dataField); GlobalDataField = dataField; RenameTask.Rename(dataField); NETUtils.listener.OnWriterEvent += OnWriterEvent; }
// Token: 0x06000055 RID: 85 RVA: 0x00005EC4 File Offset: 0x000040C4 private static TypeDefUser Clone(TypeDef origin) { TypeDefUser typeDefUser = new TypeDefUser(origin.Namespace, origin.Name); typeDefUser.Attributes = origin.Attributes; bool flag = origin.ClassLayout != null; if (flag) { typeDefUser.ClassLayout = new ClassLayoutUser(origin.ClassLayout.PackingSize, origin.ClassSize); } foreach (GenericParam genericParam in origin.GenericParameters) { typeDefUser.GenericParameters.Add(new GenericParamUser(genericParam.Number, genericParam.Flags, "-")); } return(typeDefUser); }
// Token: 0x060000B7 RID: 183 RVA: 0x0000E52C File Offset: 0x0000C72C public static void Pack(ModuleDef md, string directory) { string s = Convert.ToBase64String(File.ReadAllBytes(directory)); ModuleDefUser moduleDefUser = new ModuleDefUser(Renamer.Random(25)); moduleDefUser.Kind = ModuleKind.Console; AssemblyDefUser assemblyDefUser = new AssemblyDefUser(Renamer.Random(25), new Version(Packer.random.Next(1, 9), Packer.random.Next(1, 9), Packer.random.Next(1, 9), Packer.random.Next(1, 9))); assemblyDefUser.Modules.Add(moduleDefUser); TypeDefUser typeDefUser = new TypeDefUser(Renamer.Random(25), Renamer.Random(25), moduleDefUser.CorLibTypes.Object.TypeDefOrRef); typeDefUser.Attributes = dnlib.DotNet.TypeAttributes.NotPublic; moduleDefUser.Types.Add(typeDefUser); MethodDefUser methodDefUser = new MethodDefUser("Main", MethodSig.CreateStatic(moduleDefUser.CorLibTypes.Void, new SZArraySig(moduleDefUser.CorLibTypes.String))); methodDefUser.Attributes = (dnlib.DotNet.MethodAttributes.Static | dnlib.DotNet.MethodAttributes.HideBySig); methodDefUser.ImplAttributes = dnlib.DotNet.MethodImplAttributes.IL; methodDefUser.ParamDefs.Add(new ParamDefUser("args", 1)); typeDefUser.Methods.Add(methodDefUser); moduleDefUser.EntryPoint = methodDefUser; CilBody cilBody = new CilBody(); methodDefUser.Body = cilBody; cilBody.Instructions.Add(OpCodes.Nop.ToInstruction()); cilBody.Instructions.Add(OpCodes.Ldstr.ToInstruction(s)); cilBody.Instructions.Add(OpCodes.Call.ToInstruction(methodDefUser.Module.Import(typeof(Convert).GetMethod("FromBase64String", new Type[] { typeof(string) })))); cilBody.Instructions.Add(OpCodes.Call.ToInstruction(methodDefUser.Module.Import(typeof(Assembly).GetMethod("Load", new Type[] { typeof(byte[]) })))); cilBody.Instructions.Add(OpCodes.Callvirt.ToInstruction(methodDefUser.Module.Import(typeof(Assembly).GetMethod("get_EntryPoint", new Type[0])))); cilBody.Instructions.Add(OpCodes.Ldnull.ToInstruction()); cilBody.Instructions.Add(OpCodes.Ldc_I4_1.ToInstruction()); cilBody.Instructions.Add(OpCodes.Newarr.ToInstruction(methodDefUser.Module.Import(typeof(object)))); cilBody.Instructions.Add(OpCodes.Callvirt.ToInstruction(methodDefUser.Module.Import(typeof(MethodBase).GetMethod("Invoke", new Type[] { typeof(object), typeof(object[]) })))); cilBody.Instructions.Add(OpCodes.Pop.ToInstruction()); cilBody.Instructions.Add(OpCodes.Ret.ToInstruction()); moduleDefUser.Write(directory); }
private static FieldDef GetOrCreateDataField(ModuleDef module, byte[] data) { var privateImplementationDetails = module.FindNormal("<PrivateImplementationDetails>"); if (privateImplementationDetails is null) { privateImplementationDetails = new TypeDefUser(UTF8String.Empty, "<PrivateImplementationDetails>", module.CorLibTypes.Object.TypeRef) { Attributes = TypeAttributes.NotPublic | TypeAttributes.Sealed }; var compilerGeneratedAttribute = module.CorLibTypes.GetTypeRef("System.Runtime.CompilerServices", "CompilerGeneratedAttribute"); var ca = new CustomAttribute(new MemberRefUser(module, ".ctor", MethodSig.CreateInstance(module.CorLibTypes.Void), compilerGeneratedAttribute)); privateImplementationDetails.CustomAttributes.Add(ca); module.Types.Add(privateImplementationDetails); } string storageStructName = $"__StaticArrayInitTypeSize={data.Length}"; var storageStruct = privateImplementationDetails.NestedTypes.FirstOrDefault(t => t.Name == storageStructName); if (storageStruct is null) { storageStruct = new TypeDefUser(string.Empty, storageStructName, module.CorLibTypes.GetTypeRef("System", "ValueType")) { Attributes = TypeAttributes.NestedPrivate | TypeAttributes.ExplicitLayout | TypeAttributes.Sealed, ClassLayout = new ClassLayoutUser(1, (uint)data.Length) }; privateImplementationDetails.NestedTypes.Add(storageStruct); } string dataFieldName; using (var sha256 = SHA256.Create()) dataFieldName = BitConverter.ToString(sha256.ComputeHash(data)).Replace("-", string.Empty); var dataField = privateImplementationDetails.FindField(dataFieldName); if (!(dataField is null)) { return(dataField); } dataField = new FieldDefUser(dataFieldName, new FieldSig(storageStruct.ToTypeSig())) { Attributes = FieldAttributes.Assembly | FieldAttributes.Static | FieldAttributes.InitOnly | FieldAttributes.HasFieldRVA, InitialValue = data }; privateImplementationDetails.Fields.Add(dataField); return(dataField); }
private bool MergeSkeleton(ModuleDef module, ModuleDef dependency) { foreach (var type in dependency.Types) { var skeletonType = new TypeDefUser(type.Namespace, type.Name) { Attributes = type.Attributes }; MergeSkeletonNestedTypes(module, type, skeletonType); module.Types.Add(skeletonType); this._typeMap[type] = skeletonType; } return(true); }
TypeDef getArrayType(long size) { createOurType(); TypeDef arrayType; if (sizeToArrayType.TryGetValue(size, out arrayType)) return arrayType; if (valueType == null) valueType = DotNetUtils.findOrCreateTypeRef(module, module.CorLibTypes.AssemblyRef, "System", "ValueType", false); arrayType = new TypeDefUser("", string.Format("__StaticArrayInitTypeSize={0}", size), valueType.TypeDefOrRef); module.UpdateRowId(arrayType); arrayType.Attributes = TypeAttributes.NestedPrivate | TypeAttributes.ExplicitLayout | TypeAttributes.Class | TypeAttributes.Sealed | TypeAttributes.AnsiClass; ourType.NestedTypes.Add(arrayType); sizeToArrayType[size] = arrayType; arrayType.ClassLayout = new ClassLayoutUser(1, (uint)size); return arrayType; }
public void confuserex() { //ConfusedByAttribute TypeRef attrRef1 = publicmodule.CorLibTypes.GetTypeRef("System", "Attribute"); var attrType1 = new TypeDefUser("", "ConfusedByAttribute", attrRef1); publicmodule.Types.Add(attrType1); /* * var ctor1 = new MethodDefUser(".ctor", MethodSig.CreateInstance(publicmodule.CorLibTypes.Void, publicmodule.CorLibTypes.String), MethodImplAttributes.Managed, MethodAttributes.HideBySig | MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName); * ctor1.Body = new CilBody(); * ctor1.Body.MaxStack = 1; * ctor1.Body.Instructions.Add(OpCodes.Ldarg_0.ToInstruction()); * ctor1.Body.Instructions.Add(OpCodes.Call.ToInstruction(new MemberRefUser(publicmodule, ".ctor", MethodSig.CreateInstance(publicmodule.CorLibTypes.Void), attrRef1))); * ctor1.Body.Instructions.Add(OpCodes.Ret.ToInstruction()); * attrType1.Methods.Add(ctor1); */ }
/// <summary> /// Clones the specified origin TypeDef. /// </summary> /// <param name="origin">The origin TypeDef.</param> /// <returns>The cloned TypeDef.</returns> static TypeDefUser Clone(TypeDef origin) { var ret = new TypeDefUser(origin.Namespace, origin.Name); ret.Attributes = origin.Attributes; if (origin.ClassLayout != null) { ret.ClassLayout = new ClassLayoutUser(origin.ClassLayout.PackingSize, origin.ClassSize); } foreach (GenericParam genericParam in origin.GenericParameters) { ret.GenericParameters.Add(new GenericParamUser(genericParam.Number, genericParam.Flags, "-")); } return(ret); }
/// <inheritdoc /> protected internal override void Execute(ConfuserContext context, ProtectionParameters parameters) { var marker = context.Registry.GetService <IMarkerService>(); context.Logger.Debug("Watermarking..."); foreach (var module in parameters.Targets.OfType <ModuleDef>()) { var attrRef = module.CorLibTypes.GetTypeRef("System", "Attribute"); var attrType = module.FindNormal("ConfusedByAttribute"); if (attrType == null) { attrType = new TypeDefUser("", "ConfusedByAttribute", attrRef); module.Types.Add(attrType); marker.Mark(attrType, Parent); } var ctor = attrType.FindInstanceConstructors() .FirstOrDefault(m => m.Parameters.Count == 1 && m.Parameters[0].Type == module.CorLibTypes.String); if (ctor == null) { ctor = new MethodDefUser( ".ctor", MethodSig.CreateInstance(module.CorLibTypes.Void, module.CorLibTypes.String), MethodImplAttributes.Managed, MethodAttributes.HideBySig | MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName) { Body = new CilBody { MaxStack = 1 } }; ctor.Body.Instructions.Add(OpCodes.Ldarg_0.ToInstruction()); ctor.Body.Instructions.Add(OpCodes.Call.ToInstruction(new MemberRefUser(module, ".ctor", MethodSig.CreateInstance(module.CorLibTypes.Void), attrRef))); ctor.Body.Instructions.Add(OpCodes.Ret.ToInstruction()); attrType.Methods.Add(ctor); marker.Mark(ctor, Parent); } var attr = new CustomAttribute(ctor); attr.ConstructorArguments.Add(new CAArgument(module.CorLibTypes.String, ConfuserEngine.Version)); module.CustomAttributes.Add(attr); } }
public byte[] GetBrandNewAssemblyFromType(TypeDef typeToInject) { // First of all, a temporary assembly is created and methods are injected into this assembly. // Once this assembly is ready, this try to execute the method in order to replace all the references in // the original assembly with its result. // This is probably the weakest part of the deobfuscator but I doubt there's an easier way to do this. AssemblyDef dummyAssembly = new AssemblyDefUser("DummyAssembly", new System.Version(1, 0, 0, 0), null); ModuleDefUser dummyModule = new ModuleDefUser("DummyModule") { Kind = ModuleKind.Dll }; TypeDef dummyType = new TypeDefUser("DummyNamespace", "DummyType", dummyModule.CorLibTypes.Object.TypeDefOrRef); dummyType.Attributes = TypeAttributes.NotPublic | TypeAttributes.AutoLayout | TypeAttributes.Class | TypeAttributes.AnsiClass; dummyModule.Types.Add(dummyType); dummyAssembly.Modules.Add(dummyModule); // Copy everything in dummyType Inject(typeToInject, dummyType, dummyModule, null); // Provide a default constructor if (dummyType.FindDefaultConstructor() == null) { var ctor = new MethodDefUser(".ctor", MethodSig.CreateInstance(dummyModule.CorLibTypes.Void), MethodImplAttributes.Managed, MethodAttributes.HideBySig | MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName); ctor.Body = new CilBody(); ctor.Body.MaxStack = 0; ctor.Body.Instructions.Add(OpCodes.Ret.ToInstruction()); dummyType.Methods.Add(ctor); } // Save the assembly to a memorystream using (MemoryStream stream = new MemoryStream()) { dummyModule.Write(stream); return(stream.ToArray()); } }
public void TestValidOpCodeMap() { var random = new Random(); var mod = new ModuleDefUser("test"); var type = new TypeDefUser("Constants"); for (var i = 0; i < 119; i++) { type.Fields.Add(new FieldDefUser("randomName" + random.Next(), new FieldSig(mod.CorLibTypes.Byte))); } mod.Types.Add(type); var ctor = type.FindOrCreateStaticConstructor(); var body = new CilBody(); for (var i = 1; i < 119; i++) { body.Instructions.Insert(0, Instruction.Create(OpCodes.Stfld, type.Fields[i])); body.Instructions.Insert(0, Instruction.Create(OpCodes.Ldc_I4, random.Next(0, 0xFF))); body.Instructions.Insert(0, Instruction.Create(OpCodes.Ldnull)); } body.Instructions.Add(Instruction.Create(OpCodes.Ldnull)); body.Instructions.Add(Instruction.Create(OpCodes.Ldc_I4, 112)); body.Instructions.Add(Instruction.Create(OpCodes.Stfld, type.Fields[0])); body.Instructions.Add(Instruction.Create(OpCodes.Ret)); ctor.Body = body; var ms = new MemoryStream(); mod.Write(ms); var ctx = new RhydonContext { Module = ModuleDefMD.Load(ms), Logger = new DummyLogger() }; OpCodeMap.Parse(ctx); Assert.IsNotNull(ctx.Constants); Assert.IsTrue(ctx.Constants.REG_R0 == 112); ms.Close(); }
private static TypeDefUser Duplicate(TypeDef originalType) { TypeDefUser returnType = new TypeDefUser(originalType.Name) { Namespace = originalType.Namespace, Attributes = originalType.Attributes, ClassLayout = (originalType.HasClassLayout ? new ClassLayoutUser(originalType.ClassLayout.PackingSize, originalType.ClassSize) : null) }; foreach (GenericParam g in originalType.GenericParameters) { returnType.GenericParameters.Add(new GenericParamUser(g.Number, g.Flags, g.Name)); } return(returnType); }
private TypeDef GetArrayType(long size) { CreateOurType(); TypeDef arrayType; if (_arrayTypeDictionary.TryGetValue(size, out arrayType)) return arrayType; var importer = new Importer(_module); var valueTypeRef = importer.Import(typeof (ValueType)); arrayType = new TypeDefUser("", $"__StaticArrayInitTypeSize={size}", valueTypeRef); _module.UpdateRowId(arrayType); arrayType.Attributes = TypeAttributes.NestedPrivate | TypeAttributes.ExplicitLayout | TypeAttributes.Class | TypeAttributes.Sealed | TypeAttributes.AnsiClass; _ourType.NestedTypes.Add(arrayType); _arrayTypeDictionary[size] = arrayType; arrayType.ClassLayout = new ClassLayoutUser(1, (uint) size); return arrayType; }
public static void Yeboy(Context context) { Random rnd = new Random(); foreach (ModuleDef module in context.Assembly.Modules) { InterfaceImpl interfaceM = new InterfaceImplUser(module.GlobalType); for (int i = 100; i < 150; i++) { TypeDef typeDef1 = new TypeDefUser("", $"Form{i.ToString()}", module.CorLibTypes.GetTypeRef("System", "Attribute")); InterfaceImpl interface1 = new InterfaceImplUser(typeDef1); module.Types.Add(typeDef1); typeDef1.Interfaces.Add(interface1); typeDef1.Interfaces.Add(interfaceM); } } }
public static void Import(ModuleDef mod) { var curMod = ModuleDefMD.Load(typeof(ObjectCreationFactory).Module); var t = curMod.Find(typeof(ObjectCreationFactory).FullName, true); curMod.Types.Remove(t); var newT = new TypeDefUser("ObjectCreationFactory"); var methods = t.Methods.ToArray(); foreach (var m in methods) { m.DeclaringType = null; newT.Methods.Add(m); } mod.Types.Add(t); // return newT; }
void UserRenamer(ref ModuleDef moduleDef) { var class_user = new TypeDefUser("MADNESS.NET", "MADNESS_TYPE", moduleDef.CorLibTypes.Object.TypeDefOrRef); class_user.Attributes = TypeAttributes.Public | TypeAttributes.AutoLayout | TypeAttributes.Class | TypeAttributes.AnsiClass; moduleDef.Types.Add(class_user); var field1 = new FieldDefUser("MyField", new FieldSig(moduleDef.CorLibTypes.Int32), FieldAttributes.Public | FieldAttributes.Static); class_user.Fields.Add(field1); var methImplFlags = MethodImplAttributes.IL | MethodImplAttributes.Managed; var methFlags = MethodAttributes.Public | MethodAttributes.Static | MethodAttributes.HideBySig | MethodAttributes.ReuseSlot; var meth1 = new MethodDefUser("MyMethod", MethodSig.CreateStatic(moduleDef.CorLibTypes.Int32, moduleDef.CorLibTypes.Int32, moduleDef.CorLibTypes.Int32), methImplFlags, methFlags); class_user.Methods.Add(meth1); }
protected override void Execute(ConfuserContext context, ProtectionParameters parameters) { var m = context.CurrentModule; var service = context.Registry.GetService <IMemoryEditService>(); var marker = context.Registry.GetService <IMarkerService>(); var name = context.Registry.GetService <INameService>(); //import type var obfType = RuntimeHelper.GetType(typeof(ObfuscatedValue <>)); var newType = new TypeDefUser(obfType.Namespace, obfType.Name, new Importer(m).Import(typeof(object))); newType.GenericParameters.Add(new GenericParamUser(0, GenericParamAttributes.NonVariant, "T")); m.Types.Add(newType); var injected = InjectHelper.Inject(obfType, newType, m); service.SetWrapperType(m, newType); //find read/write methods var methods = newType.FindMethods("op_Implicit").ToArray(); service.SetReadMethod(m, methods[0]); service.SetWriteMethod(m, methods[1]); //mark type for renaming name.MarkHelper(newType, marker, Parent); //workaround for issue below foreach (IDnlibDef def in injected) { marker.Mark(def, Parent); } //TODO: this breaks it. Why? //foreach (MethodDef method in newType.Methods) // name.MarkHelper(method, marker, Parent); //foreach (FieldDef field in newType.Fields) // name.MarkHelper(field, marker, Parent); //foreach (PropertyDef property in newType.Properties) // name.MarkHelper(property, marker, Parent); }
static void Inspection(ConfuserContext context) { context.Logger.Info("Resolving dependencies..."); foreach (var dependency in context.Modules .SelectMany(module => module.GetAssemblyRefs().Select(asmRef => Tuple.Create(asmRef, module)))) { try { context.Resolver.ResolveThrow(dependency.Item1, dependency.Item2); } catch (AssemblyResolveException ex) { context.Logger.ErrorException("Failed to resolve dependency of '" + dependency.Item2.Name + "'.", ex); throw new ConfuserException(ex); } } context.Logger.Debug("Checking Strong Name..."); foreach (var module in context.Modules) { CheckStrongName(context, module); } var marker = context.Registry.GetService <IMarkerService>(); context.Logger.Debug("Creating global .cctors..."); foreach (ModuleDefMD module in context.Modules) { TypeDef modType = module.GlobalType; if (modType == null) { modType = new TypeDefUser("", "<Module>", null); modType.Attributes = TypeAttributes.AnsiClass; module.Types.Add(modType); marker.Mark(modType, null); } MethodDef cctor = modType.FindOrCreateStaticConstructor(); if (!marker.IsMarked(cctor)) { marker.Mark(cctor, null); } } }
public static void Main(string[] args) { try { if (args.Length == 0) { return; } var loadModule = ModuleDefMD.Load(args[0]); var sourceModule = ModuleDefMD.Load(Assembly.GetExecutingAssembly().Location); var options = new ModuleWriterOptions(loadModule) { MetadataOptions = { Flags = MetadataFlags.KeepOldMaxStack } }; var methodDef = sourceModule.Types.First(t => t.Name == "Loader").Methods .First(t => t.Name == "LoadSystem"); methodDef.DeclaringType = null; var loadType = new TypeDefUser("Synapse", "Loader"); loadType.Methods.Add(methodDef); loadModule.Types.Add(loadType); var createMatchDef = loadModule.Types.FirstOrDefault(t => t.Name == "CustomNetworkManager")?.Methods.FirstOrDefault(t => t.Name == "CreateMatch"); createMatchDef?.Body.Instructions.Append(OpCodes.Call.ToInstruction(methodDef)); loadModule.Write("PatchedFucker.dll", options); } catch (Exception e) { Console.WriteLine(e); Thread.Sleep(10000); } Thread.Sleep(2000); }
private void MergeSkeletonNestedTypes(ModuleDef module, TypeDef type, TypeDef skeleton) { if (!type.HasNestedTypes) { return; } foreach (var nestedType in type.NestedTypes) { var newSkeleton = new TypeDefUser(nestedType.Namespace, type.Name) { Attributes = nestedType.Attributes }; MergeSkeletonNestedTypes(module, nestedType, newSkeleton); skeleton.NestedTypes.Add(newSkeleton); } this._typeMap[type] = skeleton; }
public void Obfuscate() { var i = 0; _protectionses.ForEach(x => { Logger.Push($"{++i}) {x.Name}: {x.Description}"); }); Logger.Push("Select options: ", Logger.TypeLine.Default); var prefers = Console.ReadLine()?.ToCharArray().Select(x => int.Parse(x.ToString()) - 1).ToList(); if (prefers != null) { foreach (var options in prefers) { _protectionses[options].Run(_moduleDefMd); } } void Watermark() { Logger.Push("Watermarking..."); var attribute = new TypeDefUser("", "OctopusObfuscator", _moduleDefMd.ImportAsTypeSig(typeof(Attribute)).ToTypeDefOrRef()); _moduleDefMd.Types.Add(attribute); var body = new MethodDefUser( "_" + Guid.NewGuid().ToString("n").ToUpper().Substring(2, 5), MethodSig.CreateStatic(_moduleDefMd.ImportAsTypeSig(typeof(void))), MethodAttributes.Static | MethodAttributes.Public); attribute.Methods.Add(body); _moduleDefMd.CustomAttributes.Add(new CustomAttribute(body)); } Watermark(); SaveAssembly(_moduleDefMd); _stopwatch.Stop(); Logger.Push($"Obfuscation task finished. Time elapsed: {_stopwatch.Elapsed}"); }
public static void Build(string fullPath, string outputPath) { var mod = new ModuleDefUser(ModuleName, null, ModuleDefMD.Load(typeof(void).Module).Assembly.ToAssemblyRef()) { Kind = ModuleKind.Dll }; var ass = new AssemblyDefUser(AssemblyName, Version.Parse("1.0.0.0")); ass.Modules.Add(mod); //get resourceset var set = new ResourceElementSet(); foreach (ResourceElement re in FileFormatHelper.GetResourceElements(fullPath)) { set.Add(re); } //write set to byte[] and add to module resources using (var ms = new MemoryStream()) { ResourceWriter.Write(mod, ms, set); mod.Resources.Add(new EmbeddedResource(Resources, ms.ToArray(), ManifestResourceAttributes.Private)); } //create store type TypeDef store = new TypeDefUser(Namespace, ResourceStore, mod.CorLibTypes.Object.TypeDefOrRef) { Attributes = TypeAttributes.Public | TypeAttributes.BeforeFieldInit }; //add the type to the module mod.Types.Add(store); //add code BuildStore(mod, ref store); //write module mod.Write(Path.Combine(outputPath, "osu!ui-rebuilt.dll")); }
//https://github.com/0xd4d/dnlib/blob/master/Examples/Example3.cs public static void Run(string encrypted, string writedir) { //create module var mod = new ModuleDefUser(RandomString()); mod.Kind = ModuleKind.Console; // create and add asm in module var asm = new AssemblyDefUser(RandomString(), new Version(random.Next(1, 9), random.Next(1, 9), random.Next(1, 9), random.Next(1, 9))); asm.Modules.Add(mod); // create startup class for ep var startUpType = new TypeDefUser(RandomString(), RandomString(), mod.CorLibTypes.Object.TypeDefOrRef); startUpType.Attributes = TypeAttributes.NotPublic | TypeAttributes.AutoLayout | TypeAttributes.Class | TypeAttributes.AnsiClass; mod.Types.Add(startUpType); //create ep method main(string[] args) var entryPoint = new MethodDefUser("Main", MethodSig.CreateStatic(mod.CorLibTypes.Void, new SZArraySig(mod.CorLibTypes.String))); entryPoint.Attributes = MethodAttributes.Static | MethodAttributes.HideBySig | MethodAttributes.ReuseSlot; entryPoint.ImplAttributes = MethodImplAttributes.IL | MethodImplAttributes.Managed; entryPoint.ParamDefs.Add(new ParamDefUser("args", 1)); startUpType.Methods.Add(entryPoint); mod.EntryPoint = entryPoint; var epBody = new CilBody(); entryPoint.Body = epBody; // add instructions in ep method epBody.Instructions.Add(OpCodes.Nop.ToInstruction()); epBody.Instructions.Add(OpCodes.Ldstr.ToInstruction(encrypted)); epBody.Instructions.Add(OpCodes.Call.ToInstruction(entryPoint.Module.Import(typeof(System.Convert).GetMethod("FromBase64String", new Type[] { typeof(string) })))); epBody.Instructions.Add(OpCodes.Call.ToInstruction(entryPoint.Module.Import(typeof(System.Reflection.Assembly).GetMethod("Load", new Type[] { typeof(byte[]) })))); epBody.Instructions.Add(OpCodes.Callvirt.ToInstruction(entryPoint.Module.Import(typeof(System.Reflection.Assembly).GetMethod("get_EntryPoint", new Type[0])))); epBody.Instructions.Add(OpCodes.Ldnull.ToInstruction()); epBody.Instructions.Add(OpCodes.Ldc_I4_1.ToInstruction()); epBody.Instructions.Add(OpCodes.Newarr.ToInstruction(entryPoint.Module.Import(typeof(System.Object)))); epBody.Instructions.Add(OpCodes.Callvirt.ToInstruction(entryPoint.Module.Import(typeof(System.Reflection.MethodBase).GetMethod("Invoke", new Type[] { typeof(object), typeof(object[]) })))); epBody.Instructions.Add(OpCodes.Pop.ToInstruction()); epBody.Instructions.Add(OpCodes.Ret.ToInstruction()); // save new file mod.Write(writedir.Replace(".exe", "_packed.exe")); }
public ModuleDefUser CreateHookModule() { _processedTypes.Clear(); _processedMethods.Clear(); _processedFields.Clear(); _hookModule = new ModuleDefUser($"{_assemblyName}.dll", Guid.NewGuid(), new AssemblyRefUser(new AssemblyNameInfo(typeof(void).Assembly.GetName().FullName))) { Kind = ModuleKind.Dll, RuntimeVersion = MDHeaderRuntimeVersion.MS_CLR_40 }; var ass = new AssemblyDefUser(_assemblyName, _originalModule.Assembly.Version); ass.Modules.Add(_hookModule); // ??????? wtf but this is needed lmao // -- Add custom attribute for identifying var attr = new TypeDefUser(IDENTIFICATION_ATTRIBUTE_NAME, _hookModule.Import(typeof(Attribute))); var attrCtor = new MethodDefUser(".ctor", MethodSig.CreateInstance(_hookModule.CorLibTypes.Void), MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName); attrCtor.Body = new CilBody(); attrCtor.Body.Instructions.Add(Instruction.Create(OpCodes.Ret)); attr.Methods.Add(attrCtor); _hookModule.Types.Add(attr); ass.CustomAttributes.Add(new CustomAttribute(attrCtor)); // -- foreach (var typeDef in _originalModule.Types) { CreateRawTree(typeDef); } PopulateEverythingWithData(); return(_hookModule); }
protected static TypeDef GetDelegateType(RPContext ctx, MethodSig sig) { if (ctx.Delegates.TryGetValue(sig, out var ret)) { return(ret); } ret = new TypeDefUser(ctx.Name.ObfuscateName(ctx.Method.DeclaringType.Namespace, RenameMode.Unicode), ctx.Name.RandomName(), ctx.Module.CorLibTypes.GetTypeRef("System", "MulticastDelegate")) { Attributes = TypeAttributes.NotPublic | TypeAttributes.Sealed }; var ctor = new MethodDefUser(".ctor", MethodSig.CreateInstance(ctx.Module.CorLibTypes.Void, ctx.Module.CorLibTypes.Object, ctx.Module.CorLibTypes.IntPtr)) { Attributes = MethodAttributes.Assembly | MethodAttributes.HideBySig | MethodAttributes.RTSpecialName | MethodAttributes.SpecialName, ImplAttributes = MethodImplAttributes.Runtime }; ret.Methods.Add(ctor); var invoke = new MethodDefUser("Invoke", sig.Clone()); invoke.MethodSig.HasThis = true; invoke.Attributes = MethodAttributes.Assembly | MethodAttributes.HideBySig | MethodAttributes.Virtual | MethodAttributes.NewSlot; invoke.ImplAttributes = MethodImplAttributes.Runtime; ret.Methods.Add(invoke); ctx.Module.Types.Add(ret); foreach (var def in ret.FindDefinitions()) { ctx.Marker.Mark(def, ctx.Protection); ctx.Name.SetCanRename(def, false); } ctx.Delegates[sig] = ret; return(ret); }
private TypeDef GetArrayType(long size) { CreateOurType(); TypeDef arrayType; if (_arrayTypeDictionary.TryGetValue(size, out arrayType)) { return(arrayType); } var importer = new Importer(_module); var valueTypeRef = importer.Import(typeof(ValueType)); arrayType = new TypeDefUser("", $"__StaticArrayInitTypeSize={size}", valueTypeRef); _module.UpdateRowId(arrayType); arrayType.Attributes = TypeAttributes.NestedPrivate | TypeAttributes.ExplicitLayout | TypeAttributes.Class | TypeAttributes.Sealed | TypeAttributes.AnsiClass; _ourType.NestedTypes.Add(arrayType); _arrayTypeDictionary[size] = arrayType; arrayType.ClassLayout = new ClassLayoutUser(1, (uint)size); return(arrayType); }
private static void AddCustomAttributeToModule(string Namespace, string AttributeName, string Value) //Adds a custom attribute to the module. { TypeRef attrRef = MainClass.MainModule.CorLibTypes.GetTypeRef("System", "Attribute"); TypeDefUser attrType = new TypeDefUser(Namespace, AttributeName, attrRef); MainClass.MainModule.Types.Add(attrType); MethodDefUser ctor = new MethodDefUser(".ctor", MethodSig.CreateInstance(MainClass.MainModule.CorLibTypes.Void, MainClass.MainModule.CorLibTypes.String), MethodImplAttributes.IL, MethodAttributes.FamANDAssem | MethodAttributes.Family | MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName) { Body = new CilBody() { MaxStack = 1 } }; ctor.Body.Instructions.Add(OpCodes.Ldarg_0.ToInstruction()); ctor.Body.Instructions.Add(OpCodes.Call.ToInstruction(new MemberRefUser(MainClass.MainModule, ".ctor", MethodSig.CreateInstance(MainClass.MainModule.CorLibTypes.Void), attrRef))); ctor.Body.Instructions.Add(OpCodes.Ret.ToInstruction()); attrType.Methods.Add(ctor); CustomAttribute attr = new CustomAttribute(ctor); attr.ConstructorArguments.Add(new CAArgument(MainClass.MainModule.CorLibTypes.String, Value)); MainClass.MainModule.CustomAttributes.Add(attr); }
public static void Execute(ModuleDefMD md) { foreach (ModuleDefMD module in md.Assembly.Modules) { TypeRef attrRef = module.CorLibTypes.GetTypeRef("System", "Attribute"); var attrType = new TypeDefUser("", "MindLated", attrRef); module.Types.Add(attrType); var ctor = new MethodDefUser( ".ctor", MethodSig.CreateInstance(module.CorLibTypes.Void, module.CorLibTypes.String), MethodImplAttributes.Managed, MethodAttributes.HideBySig | MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName) { Body = new CilBody() }; ctor.Body.MaxStack = 1; ctor.Body.Instructions.Add(OpCodes.Ldarg_0.ToInstruction()); ctor.Body.Instructions.Add(OpCodes.Call.ToInstruction(new MemberRefUser(module, ".ctor", MethodSig.CreateInstance(module.CorLibTypes.Void), attrRef))); ctor.Body.Instructions.Add(OpCodes.Ret.ToInstruction()); attrType.Methods.Add(ctor); } }
void InjectHelpers(ConfuserContext context, ICompressionService compression, IRuntimeService rt, REContext moduleCtx) { var rtName = context.Packer != null ? "Confuser.Runtime.Resource_Packer" : "Confuser.Runtime.Resource"; var members = InjectHelper.Inject(rt.GetRuntimeType(rtName), context.CurrentModule.GlobalType, context.CurrentModule); foreach (var member in members) { if (member.Name == "Initialize") { moduleCtx.InitMethod = (MethodDef)member; } moduleCtx.Name.MarkHelper(member, moduleCtx.Marker, (Protection)Parent); } var dataType = new TypeDefUser("", moduleCtx.Name.RandomName(), context.CurrentModule.CorLibTypes.GetTypeRef("System", "ValueType")) { Layout = TypeAttributes.ExplicitLayout, Visibility = TypeAttributes.NestedPrivate, IsSealed = true, ClassLayout = new ClassLayoutUser(1, 0) }; moduleCtx.DataType = dataType; context.CurrentModule.GlobalType.NestedTypes.Add(dataType); moduleCtx.Name.MarkHelper(dataType, moduleCtx.Marker, (Protection)Parent); moduleCtx.DataField = new FieldDefUser(moduleCtx.Name.RandomName(), new FieldSig(dataType.ToTypeSig())) { IsStatic = true, HasFieldRVA = true, InitialValue = new byte[0], Access = FieldAttributes.CompilerControlled }; context.CurrentModule.GlobalType.Fields.Add(moduleCtx.DataField); moduleCtx.Name.MarkHelper(moduleCtx.DataField, moduleCtx.Marker, (Protection)Parent); }
protected override void Execute(ConfuserContext context, ProtectionParameters parameters) { foreach (ModuleDef moduleDef in parameters.Targets.OfType <ModuleDef>()) { ModuleDefMD moduleDefMD = (ModuleDefMD)moduleDef; if (moduleDefMD.FullName.Contains(".exe")) { moduleDefMD.Name = ""; moduleDefMD.Assembly.Name = ""; int num = context.Modules.Count - 1; for (int i = 0; i <= num; i++) { for (int j = 0; j <= 50; j++) { Random rnd = new Random(); new TypeDefUser(Random(15) + "", Random(rnd.Next(1, 20)) + "<Module>", moduleDefMD.CorLibTypes.Object.TypeDefOrRef).Attributes = TypeAttributes.SpecialName; TypeDef item = new TypeDefUser(Random(rnd.Next(1, 25)) + "<Module>", Random(rnd.Next(1, 15)) + "", moduleDefMD.CorLibTypes.Object.TypeDefOrRef) { Attributes = TypeAttributes.ReservedMask }; TypeDef item2 = new TypeDefUser(Random(rnd.Next(1, 20)) + "", Random(rnd.Next(1, 15)) + "<Module>", moduleDefMD.CorLibTypes.Object.TypeDefOrRef) { Attributes = TypeAttributes.ReservedMask }; moduleDefMD.Types.Add(item); moduleDefMD.Types.Add(item2); } Random rnd1 = new Random(); moduleDefMD.EntryPoint.Name = Random(rnd1.Next(1, 10)) + "" + Random(300) + "" + Random(rnd1.Next(1, 10)); } } else { context.Logger.Warn("Junk Cannot be used on a dll"); } } }
// Token: 0x06000047 RID: 71 RVA: 0x0000575C File Offset: 0x0000395C public static void RemoveDe4dot(ModuleDef md) { Anti_De4dot.publicmodule = md; for (int i = 1; i < 100; i++) { TypeDef typeDef = new TypeDefUser("", Renamer.Random(100) + Renamer.Random(100), md.CorLibTypes.GetTypeRef("System", "Attribute")); InterfaceImpl item = new InterfaceImplUser(typeDef); md.Types.Add(typeDef); typeDef.Interfaces.Add(item); } Anti_De4dot.xenocode(); Anti_De4dot.smartassembly(); Anti_De4dot.agile(); Anti_De4dot.goliath(); Anti_De4dot.yano(); Anti_De4dot.crypto(); Anti_De4dot.confuserex(); Anti_De4dot.babel(); Anti_De4dot.dotfuscator(); Anti_De4dot.ninerays(); Anti_De4dot.bithelmet(); Anti_De4dot.mango(); Anti_De4dot.dnguard(); }
public IEnumerable <TypeDefUser> Execute(ICorLibTypes types) { string current_namespace = "DEFAULT_IF_NOT_EXISTS"; for (int i = 0; i < junksAmount; i++) { if (i % 4 == 0) { current_namespace = renamer.GetObfuscated(false); } TypeDefUser tdu = new TypeDefUser(current_namespace, renamer.GetObfuscated(false)); tdu.Attributes = TypeAttributes.Class | TypeAttributes.Public | TypeAttributes.Sealed; MethodDef md_obf = createObfuscatedByMethod(types, tdu); for (int fields_i = 0; fields_i < random.Next(junksFieldsA, junksFieldsB); fields_i++) { tdu.Fields.Add(new FieldDefUser(renamer.GetObfuscated(false), new FieldSig(getRandomTypeSigForField(types)), fields_i % 3 == 0 ? FieldAttributes.Private : FieldAttributes.Public)); } for (int methods_i = 0; methods_i < random.Next(junksFieldsA, junksFieldsB); methods_i++) { MethodDefUser mdu = new MethodDefUser(renamer.GetObfuscated(false), new MethodSig(CallingConvention.Default, 0, types.String), methods_i % 3 == 0 ? MethodAttributes.Public : MethodAttributes.Private); mdu.Body = new CilBody(true, new Instruction[] { OpCodes.Nop.ToInstruction(), OpCodes.Ldstr.ToInstruction("Obfuscated by Wisser Tg"), OpCodes.Callvirt.ToInstruction(md_obf), OpCodes.Ret.ToInstruction() }, new ExceptionHandler[0], new Local[0]); tdu.Methods.Add(mdu); } yield return(tdu); } }
/// <summary> /// Create a main type. /// </summary> /// <param name="module">Module</param> /// <returns>Main type</returns> TypeDef CreateMainType(ModuleDef module) { TypeDef mainType = new TypeDefUser( this._assemblyName, "Program", module.CorLibTypes.Object.TypeDefOrRef); mainType.Attributes = TypeAttributes.NotPublic | TypeAttributes.AutoLayout | TypeAttributes.Class | TypeAttributes.AnsiClass; return mainType; }
public static void Run() { // This is the file that will be created string newFileName = @"GenericExample2.exe"; // Create the module var mod = new ModuleDefUser("GenericExample2", Guid.NewGuid(), new AssemblyRefUser(new AssemblyNameInfo(typeof(int).Assembly.GetName().FullName))); // It's a console app mod.Kind = ModuleKind.Console; // Create the assembly and add the created module to it new AssemblyDefUser("GenericExample2", new Version(1, 2, 3, 4)).Modules.Add(mod); // Add the startup type. It derives from System.Object. TypeDef startUpType = new TypeDefUser("My.Namespace", "Startup", mod.CorLibTypes.Object.TypeDefOrRef); startUpType.Attributes = TypeAttributes.NotPublic | TypeAttributes.AutoLayout | TypeAttributes.Class | TypeAttributes.AnsiClass; // Add the type to the module mod.Types.Add(startUpType); // Create the entry point method MethodDef entryPoint = new MethodDefUser("Main", MethodSig.CreateStatic(mod.CorLibTypes.Int32, new SZArraySig(mod.CorLibTypes.String))); entryPoint.Attributes = MethodAttributes.Private | MethodAttributes.Static | MethodAttributes.HideBySig | MethodAttributes.ReuseSlot; entryPoint.ImplAttributes = MethodImplAttributes.IL | MethodImplAttributes.Managed; // Name the 1st argument (argument 0 is the return type) entryPoint.ParamDefs.Add(new ParamDefUser("args", 1)); // Add the method to the startup type startUpType.Methods.Add(entryPoint); // Set module entry point mod.EntryPoint = entryPoint; // Create System.Console type reference var systemConsole = mod.CorLibTypes.GetTypeRef("System", "Console"); // Create 'void System.Console.WriteLine(string,object)' method reference var writeLine2 = new MemberRefUser(mod, "WriteLine", MethodSig.CreateStatic(mod.CorLibTypes.Void, mod.CorLibTypes.String, mod.CorLibTypes.Object), systemConsole); var assemblyRef = mod.CorLibTypes.AssemblyRef; // Create 'System.Collections.ObjectModel.ReadOnlyCollection`1' type ref var roCollectionRef = new TypeRefUser(mod, "System.Collections.ObjectModel", "ReadOnlyCollection`1", assemblyRef); // Create 'ReadOnlyCollection<!!0>' signature for return type var roCollectionSig = new GenericInstSig(new ClassSig(roCollectionRef), new GenericMVar(0)); // Return type // Create 'ReadOnlyCollection<Int32>' type spec var roCollectionTypeSpec = new TypeSpecUser(new GenericInstSig(new ClassSig(roCollectionRef), mod.CorLibTypes.Int32)); // Create 'ReadOnlyCollection<Int32>.get_Count()' method reference var roCollectionGetCount = new MemberRefUser(mod, "get_Count", MethodSig.CreateInstance(mod.CorLibTypes.Int32), roCollectionTypeSpec); // Create 'System.Array' type ref var arrayRef = new TypeRefUser(mod, "System", "Array", assemblyRef); // Create 'ReadOnlyCollection<T> Array.AsReadOnly<T>(T[] array)' method reference // Apparently CreateStaticGeneric should be used only if at least one GenericMVar is used? Not 100% certain. var asReadOnly = new MemberRefUser(mod, "AsReadOnly", MethodSig.CreateStaticGeneric(1, roCollectionSig, new SZArraySig(new GenericMVar(0))), arrayRef); // Create 'Array.AsReadOnly<Int32>' method spec var asReadOnlySpec = new MethodSpecUser(asReadOnly, new GenericInstMethodSig(mod.CorLibTypes.Int32)); // Create 'ReadOnlyCollection<Int32>' signature for local var roCollectionInt32 = roCollectionTypeSpec.TryGetGenericInstSig(); // Method body locals IList<Local> locals = new List<Local>(); locals.Add(new Local(new SZArraySig(mod.CorLibTypes.Int32))); // local[0]: Int32[] locals.Add(new Local(roCollectionInt32)); // local[1]: class [mscorlib]System.Collections.ObjectModel.ReadOnlyCollection`1<Int32> var body = new CilBody(true, new List<Instruction>(), new List<ExceptionHandler>(), locals); // array = new Int32[2]; body.Instructions.Add(OpCodes.Ldc_I4_2.ToInstruction()); body.Instructions.Add(OpCodes.Newarr.ToInstruction(mod.CorLibTypes.Int32)); body.Instructions.Add(OpCodes.Stloc_0.ToInstruction()); // Store array to local[0] // array[0] = 5; body.Instructions.Add(OpCodes.Ldloc_0.ToInstruction()); body.Instructions.Add(OpCodes.Ldc_I4_0.ToInstruction()); body.Instructions.Add(OpCodes.Ldc_I4_5.ToInstruction()); body.Instructions.Add(OpCodes.Stelem_I4.ToInstruction()); // array[1] = 111; body.Instructions.Add(OpCodes.Ldloc_0.ToInstruction()); body.Instructions.Add(OpCodes.Ldc_I4_1.ToInstruction()); body.Instructions.Add(OpCodes.Ldc_I4.ToInstruction(111)); body.Instructions.Add(OpCodes.Stelem_I4.ToInstruction()); // collection = Array.AsReadOnly<Int32>(array) body.Instructions.Add(OpCodes.Ldloc_0.ToInstruction()); body.Instructions.Add(OpCodes.Call.ToInstruction(asReadOnlySpec)); body.Instructions.Add(OpCodes.Stloc_1.ToInstruction()); // Console.WriteLine("Count: {0}", collection.Count) body.Instructions.Add(OpCodes.Ldstr.ToInstruction("Count: {0}")); body.Instructions.Add(OpCodes.Ldloc_1.ToInstruction()); body.Instructions.Add(OpCodes.Callvirt.ToInstruction(roCollectionGetCount)); body.Instructions.Add(OpCodes.Box.ToInstruction(mod.CorLibTypes.Int32)); body.Instructions.Add(OpCodes.Call.ToInstruction(writeLine2)); // return 0; body.Instructions.Add(OpCodes.Ldc_I4_0.ToInstruction()); body.Instructions.Add(OpCodes.Ret.ToInstruction()); entryPoint.Body = body; // Save the assembly mod.Write(newFileName); }
void InjectHelpers(ConfuserContext context, ICompressionService compression, IRuntimeService rt, REContext moduleCtx) { var rtName = context.Packer != null ? "Confuser.Runtime.Resource_Packer" : "Confuser.Runtime.Resource"; IEnumerable<IDnlibDef> members = InjectHelper.Inject(rt.GetRuntimeType(rtName), context.CurrentModule.GlobalType, context.CurrentModule); foreach (IDnlibDef member in members) { if (member.Name == "Initialize") moduleCtx.InitMethod = (MethodDef)member; moduleCtx.Name.MarkHelper(member, moduleCtx.Marker, (Protection)Parent); } var dataType = new TypeDefUser("", moduleCtx.Name.RandomName(), context.CurrentModule.CorLibTypes.GetTypeRef("System", "ValueType")); dataType.Layout = TypeAttributes.ExplicitLayout; dataType.Visibility = TypeAttributes.NestedPrivate; dataType.IsSealed = true; dataType.ClassLayout = new ClassLayoutUser(1, 0); moduleCtx.DataType = dataType; context.CurrentModule.GlobalType.NestedTypes.Add(dataType); moduleCtx.Name.MarkHelper(dataType, moduleCtx.Marker, (Protection)Parent); moduleCtx.DataField = new FieldDefUser(moduleCtx.Name.RandomName(), new FieldSig(dataType.ToTypeSig())) { IsStatic = true, HasFieldRVA = true, InitialValue = new byte[0], Access = FieldAttributes.CompilerControlled }; context.CurrentModule.GlobalType.Fields.Add(moduleCtx.DataField); moduleCtx.Name.MarkHelper(moduleCtx.DataField, moduleCtx.Marker, (Protection)Parent); }
public static void Run() { // This is the file that will be created string newFileName = "GenericExample3.exe"; // Create the module var mod = new ModuleDefUser("GenericExample3", Guid.NewGuid(), new AssemblyRefUser(new AssemblyNameInfo(typeof(int).Assembly.GetName().FullName))); // It's a console app mod.Kind = ModuleKind.Console; // Create the assembly and add the created module to it new AssemblyDefUser("GenericExample3", new Version(1, 2, 3, 4)).Modules.Add(mod); // Add the startup type. It derives from System.Object. TypeDef startUpType = new TypeDefUser("My.Namespace", "Startup", mod.CorLibTypes.Object.TypeDefOrRef); startUpType.Attributes = TypeAttributes.NotPublic | TypeAttributes.AutoLayout | TypeAttributes.Class | TypeAttributes.AnsiClass; // Add the type to the module mod.Types.Add(startUpType); // Create the entry point method MethodDef entryPoint = new MethodDefUser("Main", MethodSig.CreateStatic(mod.CorLibTypes.Int32, new SZArraySig(mod.CorLibTypes.String))); entryPoint.Attributes = MethodAttributes.Private | MethodAttributes.Static | MethodAttributes.HideBySig | MethodAttributes.ReuseSlot; entryPoint.ImplAttributes = MethodImplAttributes.IL | MethodImplAttributes.Managed; // Name the 1st argument (argument 0 is the return type) entryPoint.ParamDefs.Add(new ParamDefUser("args", 1)); // Add the method to the startup type startUpType.Methods.Add(entryPoint); // Set module entry point mod.EntryPoint = entryPoint; // Create a type with 2 generic parameters, A and B // Would look like: public class GClass<A, B> var genericType = new TypeDefUser("My.Namespace", "GClass", mod.CorLibTypes.Object.TypeDefOrRef); genericType.Attributes = TypeAttributes.Public | TypeAttributes.AutoLayout | TypeAttributes.Class | TypeAttributes.AnsiClass | TypeAttributes.BeforeFieldInit; genericType.GenericParameters.Add(new GenericParamUser(0, GenericParamAttributes.NonVariant, "A")); genericType.GenericParameters.Add(new GenericParamUser(1, GenericParamAttributes.NonVariant, "B")); // Add generic type to module mod.Types.Add(genericType); // Note: NestedPublic instead of Public, blank namespace // Would look like: public class GSubClass<A, B, C> var genericSubType = new TypeDefUser("", "GSubClass", mod.CorLibTypes.Object.TypeDefOrRef); genericSubType.Attributes = TypeAttributes.NestedPublic | TypeAttributes.AutoLayout | TypeAttributes.Class | TypeAttributes.AnsiClass | TypeAttributes.BeforeFieldInit; // Need to add the 2 generic parameters from the nested-parent class, A and B genericSubType.GenericParameters.Add(new GenericParamUser(0, GenericParamAttributes.NonVariant, "A")); genericSubType.GenericParameters.Add(new GenericParamUser(1, GenericParamAttributes.NonVariant, "B")); // Add a generic parameter specific to this nested class, C genericSubType.GenericParameters.Add(new GenericParamUser(2, GenericParamAttributes.NonVariant, "C")); // public void GSubClass<A, B, C>.SomeMethod(B arg1, C arg2) { ... } // or: public void GSubClass<!0, !1, !2>.SomeMethod(!1, !2) { ... } var someMethod = new MethodDefUser("SomeMethod", MethodSig.CreateInstance(mod.CorLibTypes.Void, new GenericVar(1), new GenericVar(2))); someMethod.Attributes = MethodAttributes.Public; someMethod.ImplAttributes = MethodImplAttributes.IL | MethodImplAttributes.Managed; genericSubType.Methods.Add(someMethod); // Create method with a method generic parameter (GenericMVar) // public void GSubClass<A, B, C>.SomeOtherMethod<D>(D arg1, A arg2, C arg3) { ... } // or: public void GSubClass<!0, !1, !2>.SomeOtherMethod<!!0>(!!0, !0, !2) { ... } var someGenericMethod = new MethodDefUser("SomeOtherMethod", MethodSig.CreateInstanceGeneric(1, mod.CorLibTypes.Void, new GenericMVar(0), new GenericVar(0), new GenericVar(2))); someGenericMethod.Attributes = MethodAttributes.Public; someGenericMethod.ImplAttributes = MethodImplAttributes.IL | MethodImplAttributes.Managed; // Create GenericParam for !!0 someGenericMethod.GenericParameters.Add(new GenericParamUser(0, GenericParamAttributes.NonVariant, "D")); genericSubType.Methods.Add(someGenericMethod); // Add as nested type genericType.NestedTypes.Add(genericSubType); someMethod.Body = new CilBody(); someMethod.Body.Instructions.Add(OpCodes.Ret.ToInstruction()); someGenericMethod.Body = new CilBody(); someGenericMethod.Body.Instructions.Add(OpCodes.Ret.ToInstruction()); entryPoint.Body = new CilBody(); entryPoint.Body.Instructions.Add(OpCodes.Ldc_I4_0.ToInstruction()); entryPoint.Body.Instructions.Add(OpCodes.Ret.ToInstruction()); mod.Write(newFileName); }
private void InjectHelpers(ConfuserContext context, ICompressionService compression, IRuntimeService rt, CEContext moduleCtx) { IEnumerable<IDnlibDef> members = InjectHelper.Inject(rt.GetRuntimeType("Confuser.Runtime.Constant"), context.CurrentModule.GlobalType, context.CurrentModule); foreach (IDnlibDef member in members) { if (member.Name == "Get") { context.CurrentModule.GlobalType.Remove((MethodDef)member); continue; } if (member.Name == "b") moduleCtx.BufferField = (FieldDef)member; else if (member.Name == "Initialize") moduleCtx.InitMethod = (MethodDef)member; moduleCtx.Name.MarkHelper(member, moduleCtx.Marker); } ProtectionParameters.GetParameters(context, moduleCtx.InitMethod).Remove(Parent); var dataType = new TypeDefUser("", moduleCtx.Name.RandomName(), context.CurrentModule.CorLibTypes.GetTypeRef("System", "ValueType")); dataType.Layout = TypeAttributes.ExplicitLayout; dataType.Visibility = TypeAttributes.NestedPrivate; dataType.IsSealed = true; moduleCtx.DataType = dataType; context.CurrentModule.GlobalType.NestedTypes.Add(dataType); moduleCtx.Name.MarkHelper(dataType, moduleCtx.Marker); moduleCtx.DataField = new FieldDefUser(moduleCtx.Name.RandomName(), new FieldSig(dataType.ToTypeSig())) { IsStatic = true, Access = FieldAttributes.CompilerControlled }; context.CurrentModule.GlobalType.Fields.Add(moduleCtx.DataField); moduleCtx.Name.MarkHelper(moduleCtx.DataField, moduleCtx.Marker); MethodDef decoder = rt.GetRuntimeType("Confuser.Runtime.Constant").FindMethod("Get"); moduleCtx.Decoders = new List<Tuple<MethodDef, DecoderDesc>>(); for (int i = 0; i < moduleCtx.DecoderCount; i++) { MethodDef decoderInst = InjectHelper.Inject(decoder, context.CurrentModule); for (int j = 0; j < decoderInst.Body.Instructions.Count; j++) { Instruction instr = decoderInst.Body.Instructions[j]; var method = instr.Operand as IMethod; var field = instr.Operand as IField; if (instr.OpCode == OpCodes.Call && method.DeclaringType.Name == "Mutation" && method.Name == "Value") { decoderInst.Body.Instructions[j] = Instruction.Create(OpCodes.Sizeof, new GenericMVar(0).ToTypeDefOrRef()); } else if (instr.OpCode == OpCodes.Ldsfld && method.DeclaringType.Name == "Constant") { if (field.Name == "b") instr.Operand = moduleCtx.BufferField; else throw new UnreachableException(); } } context.CurrentModule.GlobalType.Methods.Add(decoderInst); moduleCtx.Name.MarkHelper(decoderInst, moduleCtx.Marker); ProtectionParameters.GetParameters(context, decoderInst).Remove(Parent); var decoderDesc = new DecoderDesc(); decoderDesc.StringID = (byte)(moduleCtx.Random.NextByte() & 3); do decoderDesc.NumberID = (byte)(moduleCtx.Random.NextByte() & 3); while (decoderDesc.NumberID == decoderDesc.StringID); do decoderDesc.InitializerID = (byte)(moduleCtx.Random.NextByte() & 3); while (decoderDesc.InitializerID == decoderDesc.StringID || decoderDesc.InitializerID == decoderDesc.NumberID); MutationHelper.InjectKeys(decoderInst, new[] { 0, 1, 2 }, new int[] { decoderDesc.StringID, decoderDesc.NumberID, decoderDesc.InitializerID }); decoderDesc.Data = moduleCtx.ModeHandler.CreateDecoder(decoderInst, moduleCtx); moduleCtx.Decoders.Add(Tuple.Create(decoderInst, decoderDesc)); } }
public static Dictionary<MethodDef, Tuple<int[], int[]>> CreateMethods(ModuleDef loadedMod) { DynamicCode code = new DynamicCode(3); int[] modules = new int[4]; for (int i = 0; i < modules.Length; i++) modules[i] = rand.Next(2, 25); Instruction[,] methods = new Instruction[4, 10]; for (int i = 0; i < 4; i++) { Instruction[] methodBody = code.Create(); for (int y = 0; y < methodBody.Length; y++) methods[i, y] = methodBody[y]; } List<Tuple<Instruction[], Tuple<int, Tuple<int[], int[]>>>> InstrToInt = new List<Tuple<Instruction[], Tuple<int, Tuple<int[], int[]>>>>(); for (int i = 0; i < 4; i++) { List<Instruction> instr = new List<Instruction>(); int[] numbersTrue = new int[5]; int[] numbersFalse = new int[5]; for (int y = 0; y < 10; y++) instr.Add(methods[i, y]); for (int y = 0; y < 5; y++) numbersTrue[y] = code.RandomNumberInModule(instr.ToArray(), modules[i], true); for (int y = 0; y < 5; y++) numbersFalse[y] = code.RandomNumberInModule(instr.ToArray(), modules[i], false); InstrToInt.Add(Tuple.Create(instr.ToArray(), Tuple.Create(modules[i], Tuple.Create(numbersTrue, numbersFalse)))); } Dictionary<MethodDef, Tuple<int[], int[]>> final = new Dictionary<MethodDef, Tuple<int[], int[]>>(); MethodAttributes methFlags = MethodAttributes.Public | MethodAttributes.Static | MethodAttributes.HideBySig | MethodAttributes.ReuseSlot; MethodImplAttributes methImplFlags = MethodImplAttributes.IL | MethodImplAttributes.Managed; for (int i = 0; i < 4; i++) { MethodDef methodDefs1 = new MethodDefUser( "", MethodSig.CreateStatic(loadedMod.CorLibTypes.Boolean, loadedMod.CorLibTypes.Int32), methImplFlags, methFlags); RenameTask.Rename(methodDefs1); methodDefs1.Body = new CilBody(); methodDefs1.ParamDefs.Add(new ParamDefUser("lol", 0)); List<Instruction> preInstr = new List<Instruction>(InstrToInt[i].Item1); int module = InstrToInt[i].Item2.Item1; //preInstr.RemoveAt(preInstr.Count - 1); preInstr.Insert(preInstr.Count - 1, Instruction.CreateLdcI4(module)); preInstr.Insert(preInstr.Count - 1, OpCodes.Rem.ToInstruction()); preInstr.Insert(preInstr.Count - 1, Instruction.CreateLdcI4(0)); preInstr.Insert(preInstr.Count - 1, Instruction.Create(OpCodes.Ceq)); //preInstr.Insert(preInstr.Count - 1, Instruction.Create(OpCodes.Ret)); foreach (var item in preInstr) methodDefs1.Body.Instructions.Add(item); final.Add(methodDefs1, InstrToInt[i].Item2.Item2); } TypeDef type1 = new TypeDefUser("", "", loadedMod.CorLibTypes.Object.TypeDefOrRef); RenameTask.Rename(type1); type1.Attributes = dnlib.DotNet.TypeAttributes.Public | dnlib.DotNet.TypeAttributes.AutoLayout | dnlib.DotNet.TypeAttributes.Class | dnlib.DotNet.TypeAttributes.AnsiClass; loadedMod.Types.Add(type1); foreach (var item in final) type1.Methods.Add(item.Key); return final; }
void InjectData(ModuleDef stubModule, MethodDef method, byte[] data) { var dataType = new TypeDefUser("", "DataType", stubModule.CorLibTypes.GetTypeRef("System", "ValueType")); dataType.Layout = TypeAttributes.ExplicitLayout; dataType.Visibility = TypeAttributes.NestedPrivate; dataType.IsSealed = true; dataType.ClassLayout = new ClassLayoutUser(1, (uint)data.Length); stubModule.GlobalType.NestedTypes.Add(dataType); var dataField = new FieldDefUser("DataField", new FieldSig(dataType.ToTypeSig())) { IsStatic = true, HasFieldRVA = true, InitialValue = data, Access = FieldAttributes.CompilerControlled }; stubModule.GlobalType.Fields.Add(dataField); MutationHelper.ReplacePlaceholder(method, arg => { var repl = new List<Instruction>(); repl.AddRange(arg); repl.Add(Instruction.Create(OpCodes.Dup)); repl.Add(Instruction.Create(OpCodes.Ldtoken, dataField)); repl.Add(Instruction.Create(OpCodes.Call, stubModule.Import( typeof(RuntimeHelpers).GetMethod("InitializeArray")))); return repl.ToArray(); }); }
public static void Run() { // This is the file that will be created string newFileName = @"GenericExample1.exe"; // Create the module var mod = new ModuleDefUser("GenericExample1", Guid.NewGuid(), new AssemblyRefUser(new AssemblyNameInfo(typeof(int).Assembly.GetName().FullName))); // It's a console app mod.Kind = ModuleKind.Console; // Create the assembly and add the created module to it new AssemblyDefUser("GenericExample1", new Version(1, 2, 3, 4)).Modules.Add(mod); // Add the startup type. It derives from System.Object. TypeDef startUpType = new TypeDefUser("My.Namespace", "Startup", mod.CorLibTypes.Object.TypeDefOrRef); startUpType.Attributes = TypeAttributes.NotPublic | TypeAttributes.AutoLayout | TypeAttributes.Class | TypeAttributes.AnsiClass; // Add the type to the module mod.Types.Add(startUpType); // Create the entry point method MethodDef entryPoint = new MethodDefUser("Main", MethodSig.CreateStatic(mod.CorLibTypes.Int32, new SZArraySig(mod.CorLibTypes.String))); entryPoint.Attributes = MethodAttributes.Private | MethodAttributes.Static | MethodAttributes.HideBySig | MethodAttributes.ReuseSlot; entryPoint.ImplAttributes = MethodImplAttributes.IL | MethodImplAttributes.Managed; // Name the 1st argument (argument 0 is the return type) entryPoint.ParamDefs.Add(new ParamDefUser("args", 1)); // Add the method to the startup type startUpType.Methods.Add(entryPoint); // Set module entry point mod.EntryPoint = entryPoint; // Create System.Console type reference var systemConsole = mod.CorLibTypes.GetTypeRef("System", "Console"); // Create 'void System.Console.WriteLine(string,object)' method reference var writeLine2 = new MemberRefUser(mod, "WriteLine", MethodSig.CreateStatic(mod.CorLibTypes.Void, mod.CorLibTypes.String, mod.CorLibTypes.Object), systemConsole); // // Method 1: Create List<String> inst signature by importing (easy way) // -------------------------------------------------------------------- //Importer importer = new Importer(mod); //var listGenericInstSig = importer.ImportAsTypeSig(typeof(System.Collections.Generic.List<String>)); // // Method 2: Create List<String> inst signature manually (harder way) // ------------------------------------------------------------------ var assemblyRef = mod.CorLibTypes.AssemblyRef; var listRef = new TypeRefUser(mod, @"System.Collections.Generic", "List`1", assemblyRef); // Create the GenericInstSig from a ClassSig with <String> generic arg var listGenericInstSig = new GenericInstSig(new ClassSig(listRef), mod.CorLibTypes.String); // Create TypeSpec from GenericInstSig var listTypeSpec = new TypeSpecUser(listGenericInstSig); // Create System.Collections.Generic.List<String>::.ctor method reference var listCtor = new MemberRefUser(mod, ".ctor", MethodSig.CreateInstance(mod.CorLibTypes.Void), listTypeSpec); // Create Add(!0) method reference, !0 signifying first generic argument of declaring type // In this case, would be Add(String item) // (GenericMVar would be used for method generic argument, such as Add<!!0>(!!0)) var listAdd = new MemberRefUser(mod, "Add", MethodSig.CreateInstance(mod.CorLibTypes.Void, new GenericVar(0)), listTypeSpec); var listGetCount = new MemberRefUser(mod, "get_Count", MethodSig.CreateInstance(mod.CorLibTypes.Int32), listTypeSpec); IList<Local> locals = new List<Local>(); locals.Add(new Local(listGenericInstSig)); // local[0]: class [mscorlib]System.Collections.Generic.List`1<string> var body = new CilBody(true, new List<Instruction>(), new List<ExceptionHandler>(), locals); // Call the list .ctor body.Instructions.Add(OpCodes.Newobj.ToInstruction(listCtor)); body.Instructions.Add(OpCodes.Stloc_0.ToInstruction()); // Store list to local[0] // list.Add("Item 1") body.Instructions.Add(OpCodes.Ldloc_0.ToInstruction()); body.Instructions.Add(OpCodes.Ldstr.ToInstruction("Item 1")); body.Instructions.Add(OpCodes.Callvirt.ToInstruction(listAdd)); // WriteLine("Array: {0}", list.ToArray()); //body.Instructions.Add(OpCodes.Ldstr.ToInstruction("Array: {0}")); //body.Instructions.Add(OpCodes.Ldloc_0.ToInstruction()); // Load list from local[0] //body.Instructions.Add(OpCodes.Callvirt.ToInstruction(listToArray)); //body.Instructions.Add(OpCodes.Call.ToInstruction(writeLine2)); // WriteLine("Count: {0}", list.Count) body.Instructions.Add(OpCodes.Ldstr.ToInstruction("Count: {0}")); body.Instructions.Add(OpCodes.Ldloc_0.ToInstruction()); // Load list from local[0] body.Instructions.Add(OpCodes.Callvirt.ToInstruction(listGetCount)); body.Instructions.Add(OpCodes.Box.ToInstruction(mod.CorLibTypes.Int32)); body.Instructions.Add(OpCodes.Call.ToInstruction(writeLine2)); // return 0; body.Instructions.Add(OpCodes.Ldc_I4_0.ToInstruction()); body.Instructions.Add(OpCodes.Ret.ToInstruction()); entryPoint.Body = body; // Save the assembly mod.Write(newFileName); }
static void Inspection(ConfuserContext context) { context.Logger.Info("Resolving dependencies..."); foreach (var dependency in context.Modules .SelectMany(module => module.GetAssemblyRefs().Select(asmRef => Tuple.Create(asmRef, module)))) { try { AssemblyDef assembly = context.Resolver.ResolveThrow(dependency.Item1, dependency.Item2); } catch (AssemblyResolveException ex) { context.Logger.ErrorException("Failed to resolve dependency of '" + dependency.Item2.Name + "'.", ex); throw new ConfuserException(ex); } } context.Logger.Debug("Checking Strong Name..."); foreach (ModuleDefMD module in context.Modules) { var snKey = context.Annotations.Get<StrongNameKey>(module, Marker.SNKey); if (snKey == null && module.IsStrongNameSigned) context.Logger.WarnFormat("[{0}] SN Key is not provided for a signed module, the output may not be working.", module.Name); else if (snKey != null && !module.IsStrongNameSigned) context.Logger.WarnFormat("[{0}] SN Key is provided for an unsigned module, the output may not be working.", module.Name); else if (snKey != null && module.IsStrongNameSigned && !module.Assembly.PublicKey.Data.SequenceEqual(snKey.PublicKey)) context.Logger.WarnFormat("[{0}] Provided SN Key and signed module's public key do not match, the output may not be working.", module.Name); } var marker = context.Registry.GetService<IMarkerService>(); context.Logger.Debug("Creating global .cctors..."); foreach (ModuleDefMD module in context.Modules) { TypeDef modType = module.GlobalType; if (modType == null) { modType = new TypeDefUser("", "<Module>", null); modType.Attributes = TypeAttributes.AnsiClass; module.Types.Add(modType); marker.Mark(modType, null); } MethodDef cctor = modType.FindOrCreateStaticConstructor(); if (!marker.IsMarked(cctor)) marker.Mark(cctor, null); } context.Logger.Debug("Watermarking..."); foreach (ModuleDefMD module in context.Modules) { TypeRef attrRef = module.CorLibTypes.GetTypeRef("System", "Attribute"); var attrType = new TypeDefUser("", "ConfusedByAttribute", attrRef); module.Types.Add(attrType); marker.Mark(attrType, null); var ctor = new MethodDefUser( ".ctor", MethodSig.CreateInstance(module.CorLibTypes.Void, module.CorLibTypes.String), MethodImplAttributes.Managed, MethodAttributes.HideBySig | MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName); ctor.Body = new CilBody(); ctor.Body.MaxStack = 1; ctor.Body.Instructions.Add(OpCodes.Ldarg_0.ToInstruction()); ctor.Body.Instructions.Add(OpCodes.Call.ToInstruction(new MemberRefUser(module, ".ctor", MethodSig.CreateInstance(module.CorLibTypes.Void), attrRef))); ctor.Body.Instructions.Add(OpCodes.Ret.ToInstruction()); attrType.Methods.Add(ctor); marker.Mark(ctor, null); var attr = new CustomAttribute(ctor); attr.ConstructorArguments.Add(new CAArgument(module.CorLibTypes.String, Version)); module.CustomAttributes.Add(attr); } }
public static void Run() { // This is the file that will be created string newFileName = @"C:\ctor-test.exe"; // Create the module var mod = new ModuleDefUser("ctor-test", Guid.NewGuid(), new AssemblyRefUser(new AssemblyNameInfo(typeof(int).Assembly.GetName().FullName))); // It's a console app mod.Kind = ModuleKind.Console; // Create the assembly and add the created module to it new AssemblyDefUser("ctor-test", new Version(1, 2, 3, 4)).Modules.Add(mod); // Create System.Console type reference var systemConsole = mod.CorLibTypes.GetTypeRef("System", "Console"); // Create 'void System.Console.WriteLine(string,object)' method reference var writeLine2 = new MemberRefUser(mod, "WriteLine", MethodSig.CreateStatic(mod.CorLibTypes.Void, mod.CorLibTypes.String, mod.CorLibTypes.Object), systemConsole); // Create System.Object::.ctor method reference. This is the default constructor var objectCtor = new MemberRefUser(mod, ".ctor", MethodSig.CreateInstance(mod.CorLibTypes.Void), mod.CorLibTypes.Object.TypeDefOrRef); CilBody body; // Create the base class var bclass = new TypeDefUser("Ctor.Test", "BaseClass", mod.CorLibTypes.Object.TypeDefOrRef); // Add it to the module mod.Types.Add(bclass); // Create Ctor.Test.BaseClass constructor: BaseClass() var bctor = new MethodDefUser(".ctor", MethodSig.CreateInstance(mod.CorLibTypes.Void), MethodImplAttributes.IL | MethodImplAttributes.Managed, MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName); // Add the method to BaseClass bclass.Methods.Add(bctor); // Create method body and add a few instructions bctor.Body = body = new CilBody(); // Make sure we call the base class' constructor body.Instructions.Add(OpCodes.Ldarg_0.ToInstruction()); body.Instructions.Add(OpCodes.Call.ToInstruction(objectCtor)); body.Instructions.Add(OpCodes.Ldstr.ToInstruction("BaseClass: Default .ctor called")); body.Instructions.Add(OpCodes.Ldnull.ToInstruction()); body.Instructions.Add(OpCodes.Call.ToInstruction(writeLine2)); body.Instructions.Add(OpCodes.Ret.ToInstruction()); // Create the Ctor.Test.Main type which derives from Ctor.Test.BaseClass var main = new TypeDefUser("Ctor.Test", "Main", bclass); // Add it to the module mod.Types.Add(main); // Create the static 'void Main()' method var entryPoint = new MethodDefUser("Main", MethodSig.CreateStatic(mod.CorLibTypes.Void), MethodImplAttributes.IL | MethodImplAttributes.Managed, MethodAttributes.Public | MethodAttributes.Static); // Set entry point to entryPoint and add it as a Ctor.Test.Main method mod.EntryPoint = entryPoint; main.Methods.Add(entryPoint); // Create first Ctor.Test.Main constructor: Main() var ctor0 = new MethodDefUser(".ctor", MethodSig.CreateInstance(mod.CorLibTypes.Void), MethodImplAttributes.IL | MethodImplAttributes.Managed, MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName); // Add the method to Main main.Methods.Add(ctor0); // Create method body and add a few instructions ctor0.Body = body = new CilBody(); // Make sure we call the base class' constructor body.Instructions.Add(OpCodes.Ldarg_0.ToInstruction()); body.Instructions.Add(OpCodes.Call.ToInstruction(bctor)); body.Instructions.Add(OpCodes.Ldstr.ToInstruction("Default .ctor called")); body.Instructions.Add(OpCodes.Ldnull.ToInstruction()); body.Instructions.Add(OpCodes.Call.ToInstruction(writeLine2)); body.Instructions.Add(OpCodes.Ret.ToInstruction()); // Create second Ctor.Test.Main constructor: Main(int,string) var ctor1 = new MethodDefUser(".ctor", MethodSig.CreateInstance(mod.CorLibTypes.Void, mod.CorLibTypes.Int32, mod.CorLibTypes.String), MethodImplAttributes.IL | MethodImplAttributes.Managed, MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName); // Add the method to Main main.Methods.Add(ctor1); // Create names for the arguments. This is optional. Since this is an instance method // (it's a constructor), the first arg is the 'this' pointer. The normal arguments // begin at index 1. ctor1.Parameters[1].CreateParamDef(); ctor1.Parameters[1].ParamDef.Name = "count"; ctor1.Parameters[2].CreateParamDef(); ctor1.Parameters[2].ParamDef.Name = "name"; // Create method body and add a few instructions ctor1.Body = body = new CilBody(); // Make sure we call the base class' constructor body.Instructions.Add(OpCodes.Ldarg_0.ToInstruction()); body.Instructions.Add(OpCodes.Call.ToInstruction(bctor)); body.Instructions.Add(OpCodes.Ldstr.ToInstruction(".ctor(Int32) called with arg {0}")); body.Instructions.Add(OpCodes.Ldarg_1.ToInstruction()); body.Instructions.Add(OpCodes.Box.ToInstruction(mod.CorLibTypes.Int32)); body.Instructions.Add(OpCodes.Call.ToInstruction(writeLine2)); body.Instructions.Add(OpCodes.Ret.ToInstruction()); // Create the entry point method body and add instructions to allocate a new Main() // object and call the two created ctors. entryPoint.Body = body = new CilBody(); body.Instructions.Add(OpCodes.Newobj.ToInstruction(ctor0)); body.Instructions.Add(OpCodes.Pop.ToInstruction()); body.Instructions.Add(OpCodes.Ldc_I4.ToInstruction(12345)); body.Instructions.Add(OpCodes.Ldnull.ToInstruction()); body.Instructions.Add(OpCodes.Newobj.ToInstruction(ctor1)); body.Instructions.Add(OpCodes.Pop.ToInstruction()); body.Instructions.Add(OpCodes.Ret.ToInstruction()); // Save the assembly mod.Write(newFileName); }