Пример #1
0
        /// <summary>
        /// Creates a module.
        /// </summary>
        /// <returns></returns>
        public static ModuleDef CreateModule()
        {
            ModuleDef module = new ModuleDefUser(Guid.NewGuid().ToString());
            module.Kind = ModuleKind.Dll;

            // Add the module to an assembly
            AssemblyDef assembly = new AssemblyDefUser(Guid.NewGuid().ToString(), new Version(1, 0), null, CultureInfo.InvariantCulture.DisplayName);
            assembly.Modules.Add(module);

            return module;
        }
Пример #2
0
		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");
		}
Пример #3
0
        private byte[] DecryptArray(MethodDef method, byte[] encryptedArray)
        {
            ModuleDefUser tempModule = new ModuleDefUser("TempModule");

            AssemblyDef tempAssembly = new AssemblyDefUser("TempAssembly");

            tempAssembly.Modules.Add(tempModule);

            var tempType = new TypeDefUser("", "TempType", tempModule.CorLibTypes.Object.TypeDefOrRef);

            tempType.Attributes = TypeAttributes.Public | TypeAttributes.Class;
            MethodDef tempMethod = Utils.Clone(method);

            tempMethod.ReturnType = new SZArraySig(tempModule.CorLibTypes.Byte);
            tempMethod.MethodSig.Params.Add(new SZArraySig(tempModule.CorLibTypes.Byte));
            tempMethod.Attributes = MethodAttributes.Public | MethodAttributes.Static;

            for (int i = 0; i < 5; i++)
            {
                tempMethod.Body.Instructions.RemoveAt(2); // read encrypted array from argument
            }
            tempMethod.Body.Instructions.Insert(2, OpCodes.Ldarg_0.ToInstruction());

            for (int i = 0; i < 2; i++)
            {
                tempMethod.Body.Instructions.RemoveAt(tempMethod.Body.Instructions.Count -
                                                      2); // make return decrypted array
            }
            tempType.Methods.Add(tempMethod);
            tempModule.Types.Add(tempType);

            using (MemoryStream memoryStream = new MemoryStream())
            {
                ModuleWriterOptions moduleWriterOptions = new ModuleWriterOptions();
                moduleWriterOptions.MetaDataOptions = new MetaDataOptions();

                tempModule.Write(memoryStream, moduleWriterOptions);

                Assembly   patchedAssembly = Assembly.Load(memoryStream.ToArray());
                var        type            = patchedAssembly.ManifestModule.GetType("TempType");
                var        methods         = type.GetMethods();
                MethodInfo patchedMethod   = methods.First(m => m.IsPublic && m.IsStatic);
                byte[]     decryptedBytes  = (byte[])patchedMethod.Invoke(null, new object[] { encryptedArray });
                return(Lzma.Decompress(decryptedBytes));
            }
        }
Пример #4
0
        // 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);
        }
Пример #5
0
        public IntrinsicsAssemblyBuilder(string corlibAssemblyFullName)
        {
            var corlibRef = new AssemblyRefUser(new AssemblyNameInfo(corlibAssemblyFullName));

            module      = new ModuleDefUser(Guid.NewGuid().ToString(), Guid.NewGuid(), corlibRef);
            module.Kind = ModuleKind.Dll;
            var asm = new AssemblyDefUser(Guid.NewGuid().ToString());

            asm.Modules.Add(module);
            intrinsicsType            = new TypeDefUser(ExpressionCompilerConstants.IntrinsicAssemblyNamespace, ExpressionCompilerConstants.IntrinsicAssemblyTypeName, module.CorLibTypes.Object.TypeDefOrRef);
            intrinsicsType.Attributes = TypeAttributes.Public | TypeAttributes.AutoLayout | TypeAttributes.Class | TypeAttributes.AnsiClass | TypeAttributes.Abstract | TypeAttributes.Sealed;
            module.Types.Add(intrinsicsType);
            corlibTypes      = module.CorLibTypes;
            exceptionTypeSig = new ClassSig(corlibTypes.GetTypeRef(nameof(System), nameof(Exception)));
            typeTypeSig      = new ClassSig(corlibTypes.GetTypeRef(nameof(System), nameof(Type)));
            guidTypeSig      = new ValueTypeSig(corlibTypes.GetTypeRef(nameof(System), nameof(Guid)));
        }
Пример #6
0
        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());
            }
        }
Пример #7
0
		protected override void Pack(ConfuserContext context, ProtectionParameters parameters) {
			var ctx = context.Annotations.Get<CompressorContext>(context, ContextKey);
			if (ctx == null) {
				context.Logger.Error("No executable module!");
				throw new ConfuserException(null);
			}

			ModuleDefMD originModule = context.Modules[ctx.ModuleIndex];
			ctx.OriginModuleDef = originModule;

			var stubModule = new ModuleDefUser(ctx.ModuleName, originModule.Mvid, originModule.CorLibTypes.AssemblyRef);
			if (ctx.CompatMode) {
				var assembly = new AssemblyDefUser(originModule.Assembly);
				assembly.Name += ".cr";
				assembly.Modules.Add(stubModule);
			}
			else {
				ctx.Assembly.Modules.Insert(0, stubModule);
				ImportAssemblyTypeReferences(originModule, stubModule);
			}
			stubModule.Characteristics = originModule.Characteristics;
			stubModule.Cor20HeaderFlags = originModule.Cor20HeaderFlags;
			stubModule.Cor20HeaderRuntimeVersion = originModule.Cor20HeaderRuntimeVersion;
			stubModule.DllCharacteristics = originModule.DllCharacteristics;
			stubModule.EncBaseId = originModule.EncBaseId;
			stubModule.EncId = originModule.EncId;
			stubModule.Generation = originModule.Generation;
			stubModule.Kind = ctx.Kind;
			stubModule.Machine = originModule.Machine;
			stubModule.RuntimeVersion = originModule.RuntimeVersion;
			stubModule.TablesHeaderVersion = originModule.TablesHeaderVersion;
			stubModule.Win32Resources = originModule.Win32Resources;

			InjectStub(context, ctx, parameters, stubModule);

			var snKey = context.Annotations.Get<StrongNameKey>(originModule, Marker.SNKey);
			using (var ms = new MemoryStream()) {
				stubModule.Write(ms, new ModuleWriterOptions(stubModule, new KeyInjector(ctx)) {
					StrongNameKey = snKey
				});
				context.CheckCancellation();
				ProtectStub(context, context.OutputPaths[ctx.ModuleIndex], ms.ToArray(), snKey, new StubProtection(ctx, originModule));
			}
		}
Пример #8
0
        protected override void Pack(ConfuserContext context, ProtectionParameters parameters)
        {
            var ctx = context.Annotations.Get <XorCryptorContext>(context, ContextKey);

            if (ctx == null)
            {
                context.Logger.Error("No executable module!");
                throw new ConfuserException(null);
            }

            ModuleDefMD originModule = context.Modules[ctx.ModuleIndex];

            ctx.OriginModuleDef = originModule;

            var stubModule = new ModuleDefUser(ctx.ModuleName, originModule.Mvid, originModule.CorLibTypes.AssemblyRef);

            if (ctx.CompatMode)
            {
                var assembly = new AssemblyDefUser(originModule.Assembly);
                assembly.Name += ".mpx";
                assembly.Modules.Add(stubModule);
            }
            else
            {
                ctx.Assembly.Modules.Insert(0, stubModule);
                ImportAssemblyTypeReferences(originModule, stubModule);
            }
            stubModule.Characteristics           = originModule.Characteristics;
            stubModule.Cor20HeaderFlags          = originModule.Cor20HeaderFlags;
            stubModule.Cor20HeaderRuntimeVersion = originModule.Cor20HeaderRuntimeVersion;
            stubModule.DllCharacteristics        = originModule.DllCharacteristics;
            stubModule.EncBaseId           = originModule.EncBaseId;
            stubModule.EncId               = originModule.EncId;
            stubModule.Generation          = originModule.Generation;
            stubModule.Kind                = ctx.Kind;
            stubModule.Machine             = originModule.Machine;
            stubModule.RuntimeVersion      = originModule.RuntimeVersion;
            stubModule.TablesHeaderVersion = originModule.TablesHeaderVersion;
            stubModule.Win32Resources      = originModule.Win32Resources;

            byte[] executableModuleBytes = null; // TODO: LOL!
        }
Пример #9
0
        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"));
        }
Пример #10
0
        //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"));
        }
Пример #11
0
        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);
        }
        public static void ExportMethodsToDll(string filename, List <MethodDef> nativeMethods, ModuleDefMD asmModule)
        {
            ModuleDef moduleDef = (ModuleDef) new ModuleDefUser((UTF8String)filename);

            moduleDef.Kind = ModuleKind.Dll;
            AssemblyDefUser assemblyDefUser = new AssemblyDefUser(new UTF8String("TestAssembly"), new Version(1, 2, 3, 4));

            assemblyDefUser.Modules.Add(moduleDef);
            moduleDef.Types.Add((TypeDef) new TypeDefUser((UTF8String)"Startup", (UTF8String)"MyType", moduleDef.CorLibTypes.Object.TypeDefOrRef));
            TypeDef typeDef = moduleDef.Types.FirstOrDefault <TypeDef>((Func <TypeDef, bool>)(m => m.Name == "MyType"));

            for (int i = 0; i < nativeMethods.Count; i++)
            {
                MethodDef     methodDef     = asmModule.GlobalType.Methods.FirstOrDefault <MethodDef>((Func <MethodDef, bool>)(m => m.Name == (string)nativeMethods[i].Name + "_IL"));
                MethodDefUser methodDefUser = new MethodDefUser(new UTF8String(Encoding.UTF8.GetBytes((string)nativeMethods[i].Name)), methodDef.MethodSig, methodDef.Attributes);
                methodDefUser.Body          = methodDef.Body;
                methodDefUser.DeclaringType = (TypeDef)null;
                methodDefUser.Name          = (UTF8String)Convert.ToBase64String(Encoding.UTF8.GetBytes((string)nativeMethods[i].Name));
                typeDef.Methods.Add((MethodDef)methodDefUser);
            }
            ModuleWriterOptions options = new ModuleWriterOptions();

            assemblyDefUser.Write(filename, options);
        }
Пример #13
0
        public static void ExportMethodsToDll(String filename, List <MethodDef> nativeMethods, ModuleDefMD asmModule)
        {
            // Create new module
            ModuleDef mod = new ModuleDefUser(filename);

            mod.Kind = ModuleKind.Dll;
            var newAsm = new AssemblyDefUser(new UTF8String("TestAssembly"), new Version(1, 2, 3, 4));

            newAsm.Modules.Add(mod);

            // Add some type
            mod.Types.Add(new TypeDefUser("Startup", "MyType", mod.CorLibTypes.Object.TypeDefOrRef));
            var currentType = mod.Types.FirstOrDefault(m => m.Name == "MyType");


            for (int i = 0; i < nativeMethods.Count; i++)
            {
                var ilMethod = asmModule.GlobalType.Methods.FirstOrDefault(m => m.Name == nativeMethods[i].Name + "_IL");

                // We do clone the method since we have to set the DeclaringType to zero. But we don't want to mess with the reference
                var clonedILMethod = new MethodDefUser(new UTF8String(Encoding.UTF8.GetBytes(nativeMethods[i].Name)), ilMethod.MethodSig, ilMethod.Attributes);

                clonedILMethod.Body          = ilMethod.Body;
                clonedILMethod.DeclaringType = null;
                clonedILMethod.Name          = Convert.ToBase64String(Encoding.UTF8.GetBytes(nativeMethods[i].Name));

                currentType.Methods.Add(clonedILMethod);
            }

            var testAssemblyWriterOptions = new ModuleWriterOptions();

            // Do we want to suppress errors ?
            // testAssemblyWriterOptions.Logger = DummyLogger.NoThrowInstance;

            newAsm.Write(filename, testAssemblyWriterOptions);
        }
Пример #14
0
        // Token: 0x0600019A RID: 410 RVA: 0x00061B74 File Offset: 0x0005FD74
        private void OnWriterEvent(object sender, ModuleWriterListenerEventArgs e)
        {
            ModuleWriterBase moduleWriterBase = (ModuleWriterBase)sender;
            bool             flag             = e.WriterEvent == ModuleWriterEvent.MDBeginAddResources;

            if (flag)
            {
                this.ctx.Context.CheckCancellation();
                this.ctx.Context.Logger.Debug("Encrypting resources...");
                bool flag2 = this.ctx.Context.Packer != null;
                List <EmbeddedResource> list = this.ctx.Module.Resources.OfType <EmbeddedResource>().ToList <EmbeddedResource>();
                bool flag3 = !flag2;
                if (flag3)
                {
                    this.ctx.Module.Resources.RemoveWhere((Resource res) => res is EmbeddedResource);
                }
                string    text      = this.ctx.Name.RandomName(RenameMode.Letters);
                PublicKey publicKey = null;
                bool      flag4     = moduleWriterBase.TheOptions.StrongNameKey != null;
                if (flag4)
                {
                    publicKey = PublicKeyBase.CreatePublicKey(moduleWriterBase.TheOptions.StrongNameKey.PublicKey);
                }
                AssemblyDefUser assemblyDefUser = new AssemblyDefUser(text, new Version(0, 0), publicKey);
                assemblyDefUser.Modules.Add(new ModuleDefUser(text + ".dll"));
                ModuleDef manifestModule = assemblyDefUser.ManifestModule;
                assemblyDefUser.ManifestModule.Kind = ModuleKind.Dll;
                AssemblyRefUser asmRef = new AssemblyRefUser(manifestModule.Assembly);
                bool            flag5  = !flag2;
                if (flag5)
                {
                    foreach (EmbeddedResource embeddedResource in list)
                    {
                        embeddedResource.Attributes = ManifestResourceAttributes.Public;
                        manifestModule.Resources.Add(embeddedResource);
                        this.ctx.Module.Resources.Add(new AssemblyLinkedResource(embeddedResource.Name, asmRef, embeddedResource.Attributes));
                    }
                }
                byte[] array;
                using (MemoryStream memoryStream = new MemoryStream())
                {
                    manifestModule.Write(memoryStream, new ModuleWriterOptions
                    {
                        StrongNameKey = moduleWriterBase.TheOptions.StrongNameKey
                    });
                    array = memoryStream.ToArray();
                }
                array = this.ctx.Context.Registry.GetService <ICompressionService>().Compress(array, delegate(double progress)
                {
                    this.ctx.Context.Logger.Progress((int)(progress * 10000.0), 10000);
                });
                this.ctx.Context.Logger.EndProgress();
                this.ctx.Context.CheckCancellation();
                uint num = (uint)((array.Length + 3) / 4);
                num = (num + 15u & 4294967280u);
                uint[] array2 = new uint[num];
                Buffer.BlockCopy(array, 0, array2, 0, array.Length);
                Debug.Assert(num % 16u == 0u);
                uint   num2   = this.ctx.Random.NextUInt32() | 16u;
                uint[] array3 = new uint[16];
                uint   num3   = num2;
                for (int i = 0; i < 16; i++)
                {
                    num3     ^= num3 >> 13;
                    num3     ^= num3 << 25;
                    num3     ^= num3 >> 27;
                    array3[i] = num3;
                }
                byte[] array4 = new byte[array2.Length * 4];
                int    j;
                for (j = 0; j < array2.Length; j += 16)
                {
                    uint[] src = this.ctx.ModeHandler.Encrypt(array2, j, array3);
                    for (int k = 0; k < 16; k++)
                    {
                        array3[k] ^= array2[j + k];
                    }
                    Buffer.BlockCopy(src, 0, array4, j * 4, 64);
                }
                Debug.Assert(j == array2.Length);
                uint       num4       = (uint)array4.Length;
                TablesHeap tablesHeap = moduleWriterBase.MetaData.TablesHeap;
                tablesHeap.ClassLayoutTable[moduleWriterBase.MetaData.GetClassLayoutRid(this.ctx.DataType)].ClassSize = num4;
                RawFieldRow rawFieldRow = tablesHeap.FieldTable[moduleWriterBase.MetaData.GetRid(this.ctx.DataField)];
                rawFieldRow.Flags     |= 256;
                this.encryptedResource = moduleWriterBase.Constants.Add(new ByteArrayChunk(array4), 8u);
                MutationHelper.InjectKeys(this.ctx.InitMethod, new int[]
                {
                    0,
                    1
                }, new int[]
                {
                    (int)(num4 / 4u),
                    (int)num2
                });
            }
            else
            {
                bool flag6 = e.WriterEvent == ModuleWriterEvent.EndCalculateRvasAndFileOffsets;
                if (flag6)
                {
                    TablesHeap tablesHeap2 = moduleWriterBase.MetaData.TablesHeap;
                    tablesHeap2.FieldRVATable[moduleWriterBase.MetaData.GetFieldRVARid(this.ctx.DataField)].RVA = (uint)this.encryptedResource.RVA;
                }
            }
        }
Пример #15
0
        void OnWriterEvent(object sender, ModuleWriterListenerEventArgs e)
        {
            var writer = (ModuleWriterBase)sender;

            if (e.WriterEvent == ModuleWriterEvent.MDBeginAddResources)
            {
                ctx.Context.CheckCancellation();
                ctx.Context.Logger.Debug("Encrypting resources...");
                bool hasPacker = ctx.Context.Packer != null;

                List <EmbeddedResource> resources = ctx.Module.Resources.OfType <EmbeddedResource>().ToList();
                if (!hasPacker)
                {
                    ctx.Module.Resources.RemoveWhere(res => res is EmbeddedResource);
                }

                // move resources
                string    asmName = ctx.Name.RandomName(RenameMode.Letters);
                PublicKey pubKey  = null;
                if (writer.TheOptions.StrongNameKey != null)
                {
                    pubKey = PublicKeyBase.CreatePublicKey(writer.TheOptions.StrongNameKey.PublicKey);
                }
                var assembly = new AssemblyDefUser(asmName, new Version(0, 0), pubKey);
                assembly.Modules.Add(new ModuleDefUser(asmName + ".dll"));
                ModuleDef module = assembly.ManifestModule;
                assembly.ManifestModule.Kind = ModuleKind.Dll;
                var asmRef = new AssemblyRefUser(module.Assembly);
                if (!hasPacker)
                {
                    foreach (EmbeddedResource res in resources)
                    {
                        res.Attributes = ManifestResourceAttributes.Public;
                        module.Resources.Add(res);
                        ctx.Module.Resources.Add(new AssemblyLinkedResource(res.Name, asmRef, res.Attributes));
                    }
                }
                byte[] moduleBuff;
                using (var ms = new MemoryStream()) {
                    module.Write(ms, new ModuleWriterOptions {
                        StrongNameKey = writer.TheOptions.StrongNameKey
                    });
                    moduleBuff = ms.ToArray();
                }

                // compress
                moduleBuff = ctx.Context.Registry.GetService <ICompressionService>().Compress(
                    moduleBuff,
                    progress => ctx.Context.Logger.Progress((int)(progress * 10000), 10000));
                ctx.Context.Logger.EndProgress();
                ctx.Context.CheckCancellation();

                uint compressedLen = (uint)(moduleBuff.Length + 3) / 4;
                compressedLen = (compressedLen + 0xfu) & ~0xfu;
                var compressedBuff = new uint[compressedLen];
                Buffer.BlockCopy(moduleBuff, 0, compressedBuff, 0, moduleBuff.Length);
                Debug.Assert(compressedLen % 0x10 == 0);

                // encrypt
                uint keySeed = ctx.Random.NextUInt32() | 0x10;
                var  key     = new uint[0x10];
                uint state   = keySeed;
                for (int i = 0; i < 0x10; i++)
                {
                    state ^= state >> 13;
                    state ^= state << 25;
                    state ^= state >> 27;
                    key[i] = state;
                }

                var encryptedBuffer = new byte[compressedBuff.Length * 4];
                int buffIndex       = 0;
                while (buffIndex < compressedBuff.Length)
                {
                    uint[] enc = ctx.ModeHandler.Encrypt(compressedBuff, buffIndex, key);
                    for (int j = 0; j < 0x10; j++)
                    {
                        key[j] ^= compressedBuff[buffIndex + j];
                    }
                    Buffer.BlockCopy(enc, 0, encryptedBuffer, buffIndex * 4, 0x40);
                    buffIndex += 0x10;
                }
                Debug.Assert(buffIndex == compressedBuff.Length);
                var size = (uint)encryptedBuffer.Length;

                TablesHeap tblHeap = writer.MetaData.TablesHeap;
                tblHeap.ClassLayoutTable[writer.MetaData.GetClassLayoutRid(ctx.DataType)].ClassSize = size;
                tblHeap.FieldTable[writer.MetaData.GetRid(ctx.DataField)].Flags |= (ushort)FieldAttributes.HasFieldRVA;
                encryptedResource = writer.Constants.Add(new ByteArrayChunk(encryptedBuffer), 8);

                // inject key values
                MutationHelper.InjectKeys(ctx.InitMethod,
                                          new[] { 0, 1 },
                                          new[] { (int)(size / 4), (int)(keySeed) });
            }
            else if (e.WriterEvent == ModuleWriterEvent.EndCalculateRvasAndFileOffsets)
            {
                TablesHeap tblHeap = writer.MetaData.TablesHeap;
                tblHeap.FieldRVATable[writer.MetaData.GetFieldRVARid(ctx.DataField)].RVA = (uint)encryptedResource.RVA;
            }
        }
Пример #16
0
        protected override void Pack(ConfuserContext context, ProtectionParameters parameters)
        {
            var ctx = context.Annotations.Get <CompressorContext>(context, ContextKey);

            if (ctx == null)
            {
                context.Logger.Error("No executable module!");
                throw new ConfuserException(null);
            }

            ModuleDefMD originModule = context.Modules[ctx.ModuleIndex];

            ctx.OriginModuleDef = originModule;

            var stubModule = new ModuleDefUser(ctx.ModuleName, originModule.Mvid, originModule.CorLibTypes.AssemblyRef);

            if (ctx.CompatMode)
            {
                var assembly = new AssemblyDefUser(originModule.Assembly);
                assembly.Name += ".cr";
                assembly.Modules.Add(stubModule);
                var targetFramework = originModule.Assembly.CustomAttributes.FirstOrDefault(ca => ca.TypeFullName == "System.Runtime.Versioning.TargetFrameworkAttribute");
                if (targetFramework != null)
                {
                    var attrType = stubModule.CorLibTypes.GetTypeRef("System.Runtime.Versioning", "TargetFrameworkAttribute");
                    var ctorSig  = MethodSig.CreateInstance(stubModule.CorLibTypes.Void, stubModule.CorLibTypes.String);
                    assembly.CustomAttributes.Add(new CustomAttribute(
                                                      new MemberRefUser(stubModule, ".ctor", ctorSig, attrType), new CAArgument[] { new CAArgument(stubModule.CorLibTypes.String, targetFramework.ConstructorArguments[0].Value) }));
                }
            }
            else
            {
                ctx.Assembly.Modules.Insert(0, stubModule);
                ImportAssemblyTypeReferences(originModule, stubModule);
            }
            stubModule.Characteristics           = originModule.Characteristics;
            stubModule.Context                   = originModule.Context;
            stubModule.Cor20HeaderFlags          = originModule.Cor20HeaderFlags;
            stubModule.Cor20HeaderRuntimeVersion = originModule.Cor20HeaderRuntimeVersion;
            stubModule.DllCharacteristics        = originModule.DllCharacteristics;
            stubModule.EncBaseId                 = originModule.EncBaseId;
            stubModule.EncId               = originModule.EncId;
            stubModule.Generation          = originModule.Generation;
            stubModule.Kind                = ctx.Kind;
            stubModule.Machine             = originModule.Machine;
            stubModule.RuntimeVersion      = originModule.RuntimeVersion;
            stubModule.TablesHeaderVersion = originModule.TablesHeaderVersion;
            stubModule.Win32Resources      = originModule.Win32Resources;

            InjectStub(context, ctx, parameters, stubModule);

            var snKey       = context.Annotations.Get <StrongNameKey>(originModule, Marker.SNKey);
            var snPubKey    = context.Annotations.Get <StrongNamePublicKey>(originModule, Marker.SNPubKey);
            var snDelaySig  = context.Annotations.Get <bool>(originModule, Marker.SNDelaySig, false);
            var snSigKey    = context.Annotations.Get <StrongNameKey>(originModule, Marker.SNSigKey);
            var snPubSigKey = context.Annotations.Get <StrongNamePublicKey>(originModule, Marker.SNSigPubKey);

            using (var ms = new MemoryStream()) {
                var options = new ModuleWriterOptions(stubModule)
                {
                    StrongNameKey       = snKey,
                    StrongNamePublicKey = snPubKey,
                    DelaySign           = snDelaySig
                };
                var injector = new KeyInjector(ctx);
                options.WriterEvent += injector.WriterEvent;

                stubModule.Write(ms, options);
                context.CheckCancellation();
                ProtectStub(context, context.OutputPaths[ctx.ModuleIndex], ms.ToArray(), snKey, snPubKey, snSigKey, snPubKey, snDelaySig, new StubProtection(ctx, originModule));
            }
        }
Пример #17
0
        public static void Run()
        {
            // 创建一个新模块。 传入的字符串是模块的名称,而不是文件名。
            ModuleDef mod = new ModuleDefUser("MyModule.exe");

            // 这是一个控制台应用程序
            mod.Kind = ModuleKind.Console;

            //将模块添加到装配中
            AssemblyDef asm = new AssemblyDefUser("MyAssembly", new Version(1, 2, 3, 4), null, "");

            asm.Modules.Add(mod);

            //添加.NET资源
            //         byte[] resourceData = Encoding.UTF8.GetBytes("Hello, world!");
            //mod.Resources.Add(new EmbeddedResource("My.Resource", resourceData,
            //				ManifestResourceAttributes.Private));

            // 添加启动类型。 它派生自System.Object。
            TypeDef startUpType = new TypeDefUser("My.Namespace", "Startup", mod.CorLibTypes.Object.TypeDefOrRef);

            startUpType.Attributes = TypeAttributes.NotPublic | TypeAttributes.AutoLayout |
                                     TypeAttributes.Class | TypeAttributes.AnsiClass;
            // 将类型添加到模块
            mod.Types.Add(startUpType);

            // 创建入口点方法
            MethodDef entryPoint = new MethodDefUser("Main",
                                                     MethodSig.CreateStatic(mod.CorLibTypes.Void, new SZArraySig(mod.CorLibTypes.String)));

            entryPoint.Attributes = MethodAttributes.Private | MethodAttributes.Static |
                                    MethodAttributes.HideBySig | MethodAttributes.ReuseSlot;
            entryPoint.ImplAttributes = MethodImplAttributes.IL | MethodImplAttributes.Managed;
            // 命名第一个参数(参数0是返回类型)
            entryPoint.ParamDefs.Add(new ParamDefUser("args", 1));
            // 将方法添加到启动类型
            startUpType.Methods.Add(entryPoint);
            // 设置模块入口点
            mod.EntryPoint = entryPoint;

            // 创建TypeRef到System.Console
            TypeRef consoleRef = new TypeRefUser(mod, "System", "Console", mod.CorLibTypes.AssemblyRef);
            // 创建方法ref为'System.Void System.Console :: WriteLine(System.String)'
            MemberRef consoleWrite1 = new MemberRefUser(mod, "WriteLine",
                                                        MethodSig.CreateStatic(mod.CorLibTypes.Void, mod.CorLibTypes.String),
                                                        consoleRef);


            TypeRef ConsoleKeyInfo = new TypeRefUser(mod, "System", "ConsoleKeyInfo", mod.CorLibTypes.AssemblyRef);
            //TypeRef stream = new TypeRefUser(mod, "System.IO", "Stream", mod.CorLibTypes.AssemblyRef);
            ClassSig classSig = new ClassSig(ConsoleKeyInfo);

            SZArraySig    array5 = new SZArraySig(classSig);
            ITypeDefOrRef type1  = array5.ToTypeDefOrRef();
            ITypeDefOrRef type2  = classSig.ToTypeDefOrRef();
            TypeSig       type11 = type1.ToTypeSig();
            TypeSig       type22 = type2.ToTypeSig();
            // 创建方法ref为'System.ConsoleKeyInfo
            //System.Console::ReadKey()'
            MemberRef consoleReadKey = new MemberRefUser(
                mod,
                "ReadLine",
                //MethodSig.CreateStatic(mod.CorLibTypes.Void),
                MethodSig.CreateStatic(mod.CorLibTypes.String),
                consoleRef
                );

            //LocalList localList=new LocalList(new LazyList<Local>());
            Local local = new Local(mod.CorLibTypes.String);
            //localList.Add(local);
            //SZArraySig SZArraySig = new SZArraySig(local);

            // 将CIL方法体添加到入口点方法
            CilBody epBody = new CilBody();

            entryPoint.Body = epBody;
            epBody.Variables.Add(local);
            epBody.Instructions.Add(OpCodes.Nop.ToInstruction());
            epBody.Instructions.Add(OpCodes.Ldstr.ToInstruction("小宇专属"));
            epBody.Instructions.Add(OpCodes.Call.ToInstruction(consoleWrite1));
            epBody.Instructions.Add(OpCodes.Ldstr.ToInstruction("xiaoyu"));
            epBody.Instructions.Add(OpCodes.Call.ToInstruction(consoleWrite1));
            epBody.Instructions.Add(OpCodes.Nop.ToInstruction());
            epBody.Instructions.Add(OpCodes.Call.ToInstruction(consoleReadKey));
            //epBody.Instructions.Add(OpCodes.Ldc_I4_0.ToInstruction());

            epBody.Instructions.Add(OpCodes.Stloc_0.ToInstruction());
            epBody.Instructions.Add(OpCodes.Ldloc_0.ToInstruction());
            epBody.Instructions.Add(OpCodes.Call.ToInstruction(consoleWrite1));
            epBody.Instructions.Add(OpCodes.Nop.ToInstruction());
            epBody.Instructions.Add(OpCodes.Ret.ToInstruction());

            // 将程序集保存到磁盘上的文件中
            mod.Write(@"saved-assembly.exe");
        }
Пример #18
0
        static void Main(string[] args)
        {
            // Create assembly and main module
            var assembly = new AssemblyDefUser("HelloWorld");
            var module   = new ModuleDefUser("HelloWorld.dll", null, new AssemblyRefUser("System.Runtime", new Version(4, 2, 2, 0)));

            module.RuntimeVersion = dnlib.DotNet.MD.MDHeaderRuntimeVersion.MS_CLR_40;

            // Create type Program
            var type = new TypeDefUser(
                @namespace: "HelloWorld",
                name: "Program",
                baseType: module.CorLibTypes.Object.TypeDefOrRef);

            // Set class attributes
            type.Attributes = TypeAttributes.Public | TypeAttributes.Class;

            // Create method Main
            var method = new MethodDefUser(
                name: "Main",
                methodSig: MethodSig.CreateStatic(
                    retType: module.CorLibTypes.Void,
                    argType1: new SZArraySig(module.CorLibTypes.String)));

            // Name parameter
            method.ParamDefs.Add(new ParamDefUser("args", 1));
            // Set method attributes
            method.Attributes = MethodAttributes.Public | MethodAttributes.Static;
            // Set attributes for method's implementation
            method.ImplAttributes = MethodImplAttributes.IL | MethodImplAttributes.Managed;



            #region IMPLEMENTATION
            // Create reference to System.Console
            var consoleRef = new TypeRefUser(module, "System", "Console", new AssemblyRefUser("System.Console"));
            // Create reference to System.Console::WriteLine(string)
            var writeLineRef = new MemberRefUser(module, "WriteLine",
                                                 MethodSig.CreateStatic(
                                                     retType: module.CorLibTypes.Void,
                                                     argType1: module.CorLibTypes.String),
                                                 consoleRef);

            // Implement body of the Program::Main(string[]) method
            var body = new CilBody();
            body.Instructions.Add(Instruction.Create(OpCodes.Ldstr, "Hello World!"));
            body.Instructions.Add(Instruction.Create(OpCodes.Call, writeLineRef));
            body.Instructions.Add(Instruction.Create(OpCodes.Br, body.Instructions.First()));
            body.Instructions.Add(Instruction.Create(OpCodes.Ret));

            method.Body = body;
            #endregion



            #region ASSEMBLE
            // Wire-it up!
            assembly.Modules.Add(module);
            module.Types.Add(type);
            type.Methods.Add(method);

            // Set entrypoint
            module.EntryPoint = method;

            // Store assembly
            module.Write(Path.Combine("Generated", "HelloWorld.dll"), new dnlib.DotNet.Writer.ModuleWriterOptions(module));
            #endregion
        }
Пример #19
0
		void OnWriterEvent(object sender, ModuleWriterListenerEventArgs e) {
			var writer = (ModuleWriterBase)sender;
			if (e.WriterEvent == ModuleWriterEvent.MDBeginAddResources) {
				ctx.Context.CheckCancellation();
				ctx.Context.Logger.Debug("Encrypting resources...");
				bool hasPacker = ctx.Context.Packer != null;

				List<EmbeddedResource> resources = ctx.Module.Resources.OfType<EmbeddedResource>().ToList();
				if (!hasPacker)
					ctx.Module.Resources.RemoveWhere(res => res is EmbeddedResource);

				// move resources
				string asmName = ctx.Name.RandomName(RenameMode.Letters);
				PublicKey pubKey = null;
				if (writer.TheOptions.StrongNameKey != null)
					pubKey = PublicKeyBase.CreatePublicKey(writer.TheOptions.StrongNameKey.PublicKey);
				var assembly = new AssemblyDefUser(asmName, new Version(0, 0), pubKey);
				assembly.Modules.Add(new ModuleDefUser(asmName + ".dll"));
				ModuleDef module = assembly.ManifestModule;
				assembly.ManifestModule.Kind = ModuleKind.Dll;
				var asmRef = new AssemblyRefUser(module.Assembly);
				if (!hasPacker) {
					foreach (EmbeddedResource res in resources) {
						res.Attributes = ManifestResourceAttributes.Public;
						module.Resources.Add(res);
						ctx.Module.Resources.Add(new AssemblyLinkedResource(res.Name, asmRef, res.Attributes));
					}
				}
				byte[] moduleBuff;
				using (var ms = new MemoryStream()) {
					module.Write(ms, new ModuleWriterOptions { StrongNameKey = writer.TheOptions.StrongNameKey });
					moduleBuff = ms.ToArray();
				}

				// compress
				moduleBuff = ctx.Context.Registry.GetService<ICompressionService>().Compress(
					moduleBuff,
					progress => ctx.Context.Logger.Progress((int)(progress * 10000), 10000));
				ctx.Context.Logger.EndProgress();
				ctx.Context.CheckCancellation();

				uint compressedLen = (uint)(moduleBuff.Length + 3) / 4;
				compressedLen = (compressedLen + 0xfu) & ~0xfu;
				var compressedBuff = new uint[compressedLen];
				Buffer.BlockCopy(moduleBuff, 0, compressedBuff, 0, moduleBuff.Length);
				Debug.Assert(compressedLen % 0x10 == 0);

				// encrypt
				uint keySeed = ctx.Random.NextUInt32() | 0x10;
				var key = new uint[0x10];
				uint state = keySeed;
				for (int i = 0; i < 0x10; i++) {
					state ^= state >> 13;
					state ^= state << 25;
					state ^= state >> 27;
					key[i] = state;
				}

				var encryptedBuffer = new byte[compressedBuff.Length * 4];
				int buffIndex = 0;
				while (buffIndex < compressedBuff.Length) {
					uint[] enc = ctx.ModeHandler.Encrypt(compressedBuff, buffIndex, key);
					for (int j = 0; j < 0x10; j++)
						key[j] ^= compressedBuff[buffIndex + j];
					Buffer.BlockCopy(enc, 0, encryptedBuffer, buffIndex * 4, 0x40);
					buffIndex += 0x10;
				}
				Debug.Assert(buffIndex == compressedBuff.Length);
				var size = (uint)encryptedBuffer.Length;

				TablesHeap tblHeap = writer.MetaData.TablesHeap;
				tblHeap.ClassLayoutTable[writer.MetaData.GetClassLayoutRid(ctx.DataType)].ClassSize = size;
				tblHeap.FieldTable[writer.MetaData.GetRid(ctx.DataField)].Flags |= (ushort)FieldAttributes.HasFieldRVA;
				encryptedResource = writer.Constants.Add(new ByteArrayChunk(encryptedBuffer), 8);

				// inject key values
				MutationHelper.InjectKeys(ctx.InitMethod,
				                          new[] { 0, 1 },
				                          new[] { (int)(size / 4), (int)(keySeed) });
			}
			else if (e.WriterEvent == ModuleWriterEvent.EndCalculateRvasAndFileOffsets) {
				TablesHeap tblHeap = writer.MetaData.TablesHeap;
				tblHeap.FieldRVATable[writer.MetaData.GetFieldRVARid(ctx.DataField)].RVA = (uint)encryptedResource.RVA;
			}
		}
		/// <summary>
		/// Generate a test assembly.
		/// </summary>
		/// <returns>Assembly</returns>
		public AssemblyDef Generate()
		{
			var module = new ModuleDefUser(_moduleName);
			module.Kind = ModuleKind.Console;

			var assembly = new AssemblyDefUser(_assemblyName, _assemblyVersion);
			assembly.Modules.Add(module);

			var mainType = this.CreateMainType(module);
			module.Types.Add(mainType);

			var generatedMethods = new List<MethodDef>();
			foreach (var kvp in _methods)
			{
				var name = kvp.Key;
				var instructions = kvp.Value(module, mainType);
				var method = CreateVirtualizableMethod(module, name, instructions);

				mainType.Methods.Add(method);
				generatedMethods.Add(method);
			}

			var entryPoint = this.CreateEntryPoint(module, generatedMethods);
			mainType.Methods.Add(entryPoint);

			return assembly;
		}
Пример #21
0
        public static void Run()
        {
            // 创建一个新模块。 传入的字符串是模块的名称,而不是文件名。
            ModuleDef mod = new ModuleDefUser("MyModule.exe");

            // 这是一个控制台应用程序
            mod.Kind = ModuleKind.Console;

            //将模块添加到装配中
            AssemblyDef asm = new AssemblyDefUser("MyAssembly", new Version(1, 2, 3, 4), null, "");

            asm.Modules.Add(mod);

            //添加.NET资源
            //         byte[] resourceData = Encoding.UTF8.GetBytes("Hello, world!");
            //mod.Resources.Add(new EmbeddedResource("My.Resource", resourceData,
            //				ManifestResourceAttributes.Private));

            // 添加启动类型。 它派生自System.Object。
            TypeDef startUpType = new TypeDefUser("My.Namespace", "Startup", mod.CorLibTypes.Object.TypeDefOrRef);

            startUpType.Attributes = TypeAttributes.NotPublic | TypeAttributes.AutoLayout |
                                     TypeAttributes.Class | TypeAttributes.AnsiClass;
            // 将类型添加到模块
            mod.Types.Add(startUpType);

            // 创建入口点方法
            MethodDef entryPoint = new MethodDefUser("Main",
                                                     MethodSig.CreateStatic(mod.CorLibTypes.Void, new SZArraySig(mod.CorLibTypes.String)));

            entryPoint.Attributes = MethodAttributes.Private | MethodAttributes.Static |
                                    MethodAttributes.HideBySig | MethodAttributes.ReuseSlot;
            entryPoint.ImplAttributes = MethodImplAttributes.IL | MethodImplAttributes.Managed;
            // 命名第一个参数(参数0是返回类型)
            entryPoint.ParamDefs.Add(new ParamDefUser("args", 1));
            // 将方法添加到启动类型
            startUpType.Methods.Add(entryPoint);
            // 设置模块入口点
            mod.EntryPoint = entryPoint;

            // 创建TypeRef到System.Console
            TypeRef consoleRef = new TypeRefUser(mod, "System", "Console", mod.CorLibTypes.AssemblyRef);
            // 创建方法ref为'System.Void System.Console :: WriteLine(System.String)'
            MemberRef consoleWrite1 = new MemberRefUser(mod, "WriteLine",
                                                        MethodSig.CreateStatic(mod.CorLibTypes.Void, mod.CorLibTypes.String),
                                                        consoleRef);

            //System.Console::ReadKey()'
            MemberRef memberRefReadLine = new MemberRefUser(
                mod,
                "ReadLine",
                //MethodSig.CreateStatic(mod.CorLibTypes.Void),
                MethodSig.CreateStatic(mod.CorLibTypes.String),
                consoleRef
                );

            // 创建TypeRef到System.Console
            TypeRef int32Ref = new TypeRefUser(mod, "System", "Int32", mod.CorLibTypes.AssemblyRef);

            MemberRef memberRefParse = new MemberRefUser(
                mod,
                "Parse",
                MethodSig.CreateStatic(mod.CorLibTypes.Int32, mod.CorLibTypes.String),
                int32Ref
                );

            //string[mscorlib] System.String::Concat(object[])
            TypeRef stringRef = new TypeRefUser(mod, "System", "String", mod.CorLibTypes.AssemblyRef);

            MemberRef memberRefSystemStringConcat = new MemberRefUser(
                mod,
                "Concat",
                MethodSig.CreateStatic(mod.CorLibTypes.String, new SZArraySig(mod.CorLibTypes.Object)),
                stringRef
                );


            // 将CIL方法体添加到入口点方法
            CilBody epBody = new CilBody();

            entryPoint.Body = epBody;
            epBody.Variables.Add(new Local(mod.CorLibTypes.String, "s1"));
            epBody.Variables.Add(new Local(mod.CorLibTypes.Int32, "i1"));
            epBody.Variables.Add(new Local(mod.CorLibTypes.Int32, "i2"));
            epBody.Variables.Add(new Local(mod.CorLibTypes.String, "s2"));


            //: nop
            //: ldstr     "xyzs"
            //: call      void [mscorlib]System.Console::WriteLine(string)
            epBody.Instructions.Add(OpCodes.Nop.ToInstruction());
            epBody.Instructions.Add(OpCodes.Ldstr.ToInstruction("小宇专属"));
            epBody.Instructions.Add(OpCodes.Call.ToInstruction(consoleWrite1));
            //: nop
            //: call      string [mscorlib]System.Console::ReadLine()
            //: stloc.0
            //: ldloc.0
            //: call      void [mscorlib]System.Console::WriteLine(string)
            epBody.Instructions.Add(OpCodes.Nop.ToInstruction());
            epBody.Instructions.Add(OpCodes.Call.ToInstruction(memberRefReadLine));
            epBody.Instructions.Add(OpCodes.Stloc_0.ToInstruction());
            epBody.Instructions.Add(OpCodes.Ldloc_0.ToInstruction());
            epBody.Instructions.Add(OpCodes.Call.ToInstruction(consoleWrite1));
            //: nop
            epBody.Instructions.Add(OpCodes.Nop.ToInstruction());
            //: call      string [mscorlib]System.Console::ReadLine()
            epBody.Instructions.Add(OpCodes.Call.ToInstruction(memberRefReadLine));
            //: call      int32 [mscorlib]System.Int32::Parse(string)
            epBody.Instructions.Add(OpCodes.Call.ToInstruction(memberRefParse));
            //: stloc.1
            epBody.Instructions.Add(OpCodes.Stloc_1.ToInstruction());
            //: call      string [mscorlib]System.Console::ReadLine()
            epBody.Instructions.Add(OpCodes.Call.ToInstruction(memberRefReadLine));
            //: call      int32 [mscorlib]System.Int32::Parse(string)
            epBody.Instructions.Add(OpCodes.Call.ToInstruction(memberRefParse));
            //: stloc.2
            epBody.Instructions.Add(OpCodes.Stloc_2.ToInstruction());
            //: ldc.i4.5
            epBody.Instructions.Add(OpCodes.Ldc_I4_5.ToInstruction());
            //: newarr    [mscorlib]System.Object
            epBody.Instructions.Add(OpCodes.Newarr.ToInstruction(mod.CorLibTypes.Object));
            //: dup
            epBody.Instructions.Add(OpCodes.Dup.ToInstruction());
            //: ldc.i4.0
            epBody.Instructions.Add(OpCodes.Ldc_I4_0.ToInstruction());
            //: ldloc.1
            epBody.Instructions.Add(OpCodes.Ldloc_1.ToInstruction());
            //: box       [mscorlib]System.Int32
            epBody.Instructions.Add(OpCodes.Box.ToInstruction(mod.CorLibTypes.Int32));
            //: stelem.ref
            epBody.Instructions.Add(OpCodes.Stelem_Ref.ToInstruction());
            //: dup
            epBody.Instructions.Add(OpCodes.Dup.ToInstruction());
            //: ldc.i4.1
            epBody.Instructions.Add(OpCodes.Ldc_I4_1.ToInstruction());
            //: ldstr     "+"
            epBody.Instructions.Add(OpCodes.Ldstr.ToInstruction("+"));
            //: stelem.ref
            epBody.Instructions.Add(OpCodes.Stelem_Ref.ToInstruction());
            //: dup
            epBody.Instructions.Add(OpCodes.Dup.ToInstruction());
            //: ldc.i4.2
            epBody.Instructions.Add(OpCodes.Ldc_I4_2.ToInstruction());
            //: ldloc.2
            epBody.Instructions.Add(OpCodes.Ldloc_2.ToInstruction());
            //: box       [mscorlib]System.Int32
            epBody.Instructions.Add(OpCodes.Box.ToInstruction(mod.CorLibTypes.Int32));
            //: stelem.ref
            epBody.Instructions.Add(OpCodes.Stelem_Ref.ToInstruction());
            //: dup
            epBody.Instructions.Add(OpCodes.Dup.ToInstruction());
            //: ldc.i4.3
            epBody.Instructions.Add(OpCodes.Ldc_I4_3.ToInstruction());
            //: ldstr     "="
            epBody.Instructions.Add(OpCodes.Ldstr.ToInstruction("="));
            //: stelem.ref
            epBody.Instructions.Add(OpCodes.Stelem_Ref.ToInstruction());
            //: dup
            epBody.Instructions.Add(OpCodes.Dup.ToInstruction());
            //: ldc.i4.4
            epBody.Instructions.Add(OpCodes.Ldc_I4_4.ToInstruction());
            //: ldloc.1
            epBody.Instructions.Add(OpCodes.Ldloc_1.ToInstruction());
            //: ldloc.2
            epBody.Instructions.Add(OpCodes.Ldloc_2.ToInstruction());
            //: add
            epBody.Instructions.Add(OpCodes.Add.ToInstruction());
            //: box       [mscorlib]System.Int32
            epBody.Instructions.Add(OpCodes.Box.ToInstruction(mod.CorLibTypes.Int32));
            //: stelem.ref
            epBody.Instructions.Add(OpCodes.Stelem_Ref.ToInstruction());
            //: call      string [mscorlib]System.String::Concat(object[])
            epBody.Instructions.Add(OpCodes.Call.ToInstruction(memberRefSystemStringConcat));
            //: call      void [mscorlib]System.Console::WriteLine(string)
            epBody.Instructions.Add(OpCodes.Call.ToInstruction(consoleWrite1));
            //: nop
            epBody.Instructions.Add(OpCodes.Nop.ToInstruction());
            //: ldstr     "xyzs"
            epBody.Instructions.Add(OpCodes.Ldstr.ToInstruction("xyzs"));
            //: call      void [mscorlib]System.Console::WriteLine(string)
            epBody.Instructions.Add(OpCodes.Call.ToInstruction(consoleWrite1));
            //: nop
            epBody.Instructions.Add(OpCodes.Nop.ToInstruction());
            //: call      string [mscorlib]System.Console::ReadLine()
            epBody.Instructions.Add(OpCodes.Call.ToInstruction(memberRefReadLine));
            //: stloc.3
            epBody.Instructions.Add(OpCodes.Stloc_3.ToInstruction());
            //: ldloc.3
            epBody.Instructions.Add(OpCodes.Ldloc_3.ToInstruction());
            //: call      void [mscorlib]System.Console::WriteLine(string)
            epBody.Instructions.Add(OpCodes.Call.ToInstruction(consoleWrite1));
            //: nop
            epBody.Instructions.Add(OpCodes.Nop.ToInstruction());
            //: ret
            epBody.Instructions.Add(OpCodes.Ret.ToInstruction());

            // 将程序集保存到磁盘上的文件中
            mod.Write(@"saved-assembly31.exe");
        }
Пример #22
0
        protected override void Pack(ConfuserContext context, ProtectionParameters parameters)
        {
            var ctx = context.Annotations.Get <CompressorContext>(context, ContextKey);

            if (ctx == null)
            {
                context.Logger.Error("No executable module!");
                throw new ConfuserException(null);
            }

            ModuleDefMD originModule = context.Modules[ctx.ModuleIndex];

            ctx.OriginModuleDef = originModule;

            var stubModule = new ModuleDefUser(ctx.ModuleName, originModule.Mvid, originModule.CorLibTypes.AssemblyRef);

            if (ctx.CompatMode)
            {
                var assembly = new AssemblyDefUser(originModule.Assembly);
                assembly.Name += ".cr";
                assembly.Modules.Add(stubModule);
            }
            else
            {
                ctx.Assembly.Modules.Insert(0, stubModule);
                ImportAssemblyTypeReferences(originModule, stubModule);
            }
            stubModule.Characteristics           = originModule.Characteristics;
            stubModule.Cor20HeaderFlags          = originModule.Cor20HeaderFlags;
            stubModule.Cor20HeaderRuntimeVersion = originModule.Cor20HeaderRuntimeVersion;
            stubModule.DllCharacteristics        = originModule.DllCharacteristics;
            stubModule.EncBaseId           = originModule.EncBaseId;
            stubModule.EncId               = originModule.EncId;
            stubModule.Generation          = originModule.Generation;
            stubModule.Kind                = ctx.Kind;
            stubModule.Machine             = originModule.Machine;
            stubModule.RuntimeVersion      = originModule.RuntimeVersion;
            stubModule.TablesHeaderVersion = originModule.TablesHeaderVersion;
            stubModule.Win32Resources      = originModule.Win32Resources;

            InjectStub(context, ctx, parameters, stubModule);

            var snKey       = context.Annotations.Get <StrongNameKey>(originModule, Marker.SNKey);
            var snPubKey    = context.Annotations.Get <StrongNamePublicKey>(originModule, Marker.SNPubKey);
            var snDelaySig  = context.Annotations.Get <bool>(originModule, Marker.SNDelaySig, false);
            var snSigKey    = context.Annotations.Get <StrongNameKey>(originModule, Marker.SNSigKey);
            var snPubSigKey = context.Annotations.Get <StrongNamePublicKey>(originModule, Marker.SNSigPubKey);

            using (var ms = new MemoryStream()) {
                var options = new ModuleWriterOptions(stubModule)
                {
                    StrongNameKey       = snKey,
                    StrongNamePublicKey = snPubKey,
                    DelaySign           = snDelaySig
                };
                var injector = new KeyInjector(ctx);
                options.WriterEvent += injector.WriterEvent;

                stubModule.Write(ms, options);
                context.CheckCancellation();
                ProtectStub(context, context.OutputPaths[ctx.ModuleIndex], ms.ToArray(), snKey, snPubKey, snSigKey, snPubKey, snDelaySig, new StubProtection(ctx, originModule));
            }
        }