コード例 #1
0
        private MethodDef InjectClass(ModuleDef module)
        {
            //We declare our Module, here we want to load the EncryptionHelper class
            ModuleDefMD typeModule = ModuleDefMD.Load(typeof(InfectHelper).Module);
            //We declare EncryptionHelper as a TypeDef using it's Metadata token (needed)
            TypeDef typeDef = typeModule.ResolveTypeDef(MDToken.ToRID(typeof(InfectHelper).MetadataToken));
            //We use confuserEX InjectHelper class to inject EncryptionHelper class into our target, under <Module>
            IEnumerable <IDnlibDef> members = InjectHelper.Inject(typeDef, module.GlobalType, module);
            //We find the Decrypt() Method in EncryptionHelper we just injected
            MethodDef init = (MethodDef)members.Single(method => method.Name == "DoInfect");

            //we will call this method later

            //We just have to remove .ctor method because otherwise it will
            //lead to Global constructor error (e.g [MD]: Error: Global item (field,method) must be Static. [token:0x06000002] / [MD]: Error: Global constructor. [token:0x06000002] )
            foreach (MethodDef md in module.GlobalType.Methods)
            {
                if (md.Name == ".ctor")
                {
                    module.GlobalType.Remove(md);
                    //Now we go out of this mess
                    break;
                }
            }
            return(init);
        }
コード例 #2
0
        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, InjectHelper.Import(stubModule,
                                                                              typeof(RuntimeHelpers).GetMethod("InitializeArray"))));
                return(repl.ToArray());
            });
        }
コード例 #3
0
ファイル: InjectPhase.cs プロジェクト: ravselj/ConfuserEx
        private void InjectHelpers(ConfuserContext context, ICompressionService compression, IRuntimeService rt, REContext moduleCtx)
        {
            IEnumerable <IDnlibDef> members = InjectHelper.Inject(rt.GetRuntimeType("Confuser.Runtime.Resource"), context.CurrentModule.GlobalType, context.CurrentModule);

            foreach (IDnlibDef member in members)
            {
                if (member.Name == "Initialize")
                {
                    moduleCtx.InitMethod = (MethodDef)member;
                }
                moduleCtx.Name.MarkHelper(member, moduleCtx.Marker);
            }

            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);

            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);
        }
コード例 #4
0
            // Token: 0x060001EF RID: 495 RVA: 0x00011CCC File Offset: 0x0000FECC
            protected override void Execute(ConfuserContext context, ProtectionParameters parameters)
            {
                TypeDef        rtType = context.Registry.GetService <IRuntimeService>().GetRuntimeType("Confuser.Runtime.ModuleFlood");
                IMarkerService marker = context.Registry.GetService <IMarkerService>();
                INameService   name   = context.Registry.GetService <INameService>();

                foreach (ModuleDef module in parameters.Targets.OfType <ModuleDef>())
                {
                    IEnumerable <IDnlibDef> members = InjectHelper.Inject(rtType, module.GlobalType, module);
                    MethodDef cctor   = module.GlobalType.FindStaticConstructor();
                    string[]  methods = { "Initialize", "Initialize1", "Initialize2", "Initialize3", "Initialize4", "Initialize5", "Initialize6", "Initialize7", "Initialize7" };
                    int       random  = new Random().Next(50, 60);
                    int       ary     = 0;
                    for (int i = 0; i < random; i++)
                    {
                        MethodDef init = (MethodDef)members.Single((IDnlibDef method) => method.Name == methods[ary]);
                        cctor.Body.Instructions.Insert(0, Instruction.Create(OpCodes.Call, init));

                        ary++;
                        if (ary == 8)
                        {
                            ary = 0;
                        }
                    }



                    foreach (IDnlibDef member in members)
                    {
                        name.MarkHelper(member, marker, (Protection)base.Parent);
                    }
                }
            }
コード例 #5
0
        public void Protect()
        {
            TypeDef   type        = typeDef("Protect.NET.Runtime.Constants");
            ModuleDef mainModule  = Globals.asm.ManifestModule.Types[0].Module;
            MethodDef mDefEncrypt = methodDef(type, "EncryptOrDecrypt");

            mDefEncrypt.DeclaringType = Globals.asm.ManifestModule.Types[0];
            mDefEncrypt.Name          = Generator.getName();
            InjectHelper.Inject(mDefEncrypt, mainModule);


            TypeDef   type2        = typeDef("Protect.NET.Runtime.Constants");
            ModuleDef mainModule2  = Globals.asm.ManifestModule.Types[0].Module;
            MethodDef mDefEncrypt2 = methodDef(type2, "EncryptOrDecrypt");

            mDefEncrypt2.DeclaringType = mDefEncrypt.DeclaringType;
            mDefEncrypt2.Name          = Generator.getName();
            InjectHelper.Inject(mDefEncrypt2, mainModule2);

            List <string> keys = new List <string>();

            for (int mDef = 0; mDef < Globals.asm.Modules.Count; mDef++)
            {
                ModuleDef moduleDef = Globals.asm.Modules[mDef];
                for (int j = 0; j < moduleDef.Types.Count; j++)
                {
                    TypeDef td = moduleDef.Types[j];
                    for (int qq = 0; qq < td.Methods.Count; qq++)
                    {
                        MethodDef mmDef = td.Methods[qq];
                        if (!mmDef.HasBody)
                        {
                            return;
                        }
                        int instrCount = mmDef.Body.Instructions.Count;
                        for (int i = 0; i < instrCount; i++)
                        {
                            Instruction cur = mmDef.Body.Instructions[i];
                            string      key = Utils.GenerateKey(15);

                            if (cur.OpCode == OpCodes.Ldstr && !keys.Contains(cur.Operand.ToString()))
                            {
                                int rand = Utils.randomInt(0, 2);
                                Console.WriteLine(rand.ToString());
                                cur.Operand = Runtime.Constants.EncryptOrDecrypt(cur.Operand.ToString(), key);

                                mmDef.Body.Instructions.Insert(i + 1, new Instruction(OpCodes.Ldstr, key));
                                mmDef.Body.Instructions.Insert(i + 2, new Instruction(OpCodes.Call, (rand == 0) ? mDefEncrypt : mDefEncrypt2));

                                mmDef.Body.OptimizeBranches();
                                mmDef.Body.SimplifyBranches();

                                keys.Add(key);
                            }
                        }
                    }
                }
            }
        }
コード例 #6
0
        TypeDef GetKeyAttr(RPContext ctx)
        {
            if (keyAttrs == null)
            {
                keyAttrs = new Tuple <TypeDef, Func <int, int> > [0x10];
            }

            int index = ctx.Random.NextInt32(keyAttrs.Length);

            if (keyAttrs[index] == null)
            {
                TypeDef rtType       = ctx.Context.Registry.GetService <IRuntimeService>().GetRuntimeType("Confuser.Runtime.RefProxyKey");
                TypeDef injectedAttr = InjectHelper.Inject(rtType, ctx.Module);
                injectedAttr.Name      = ctx.Name.RandomName();
                injectedAttr.Namespace = string.Empty;

                Expression expression, inverse;
                var        var    = new Variable("{VAR}");
                var        result = new Variable("{RESULT}");

                ctx.DynCipher.GenerateExpressionPair(
                    ctx.Random,
                    new VariableExpression {
                    Variable = var
                }, new VariableExpression {
                    Variable = result
                },
                    ctx.Depth, out expression, out inverse);

                var expCompiled = new DMCodeGen(typeof(int), new[] { Tuple.Create("{VAR}", typeof(int)) })
                                  .GenerateCIL(expression)
                                  .Compile <Func <int, int> >();

                MethodDef ctor = injectedAttr.FindMethod(".ctor");
                MutationHelper.ReplacePlaceholder(ctor, arg =>
                {
                    var invCompiled = new List <Instruction>();
                    new CodeGen(arg, ctor, invCompiled).GenerateCIL(inverse);
                    return(invCompiled.ToArray());
                });
                keyAttrs[index] = Tuple.Create(injectedAttr, expCompiled);

                ctx.Module.AddAsNonNestedType(injectedAttr);

                foreach (IDnlibDef def in injectedAttr.FindDefinitions())
                {
                    if (def.Name == "GetHashCode")
                    {
                        ctx.Name.MarkHelper(def, ctx.Marker, ctx.Protection);
                        ((MethodDef)def).Access = MethodAttributes.Public;
                    }
                    else
                    {
                        ctx.Name.MarkHelper(def, ctx.Marker, ctx.Protection);
                    }
                }
            }
            return(keyAttrs[index].Item1);
        }
コード例 #7
0
        void IProtector.InjectPhase(Context krawk)
        {
            ModuleDefMD             typeModule = ModuleDefMD.Load(typeof(CalliRuntime).Module);
            TypeDef                 typeDef    = typeModule.ResolveTypeDef(MDToken.ToRID(typeof(CalliRuntime).MetadataToken));
            IEnumerable <IDnlibDef> members    = InjectHelper.Inject(typeDef, krawk.GlobalType, krawk.ManifestModule);

            decryptionmethod = (MethodDef)members.Single(method => method.Name == "ResolveToken");
        }
コード例 #8
0
ファイル: AntiDbg.cs プロジェクト: xHeaven/Krawk-Protector
        public void InjectPhase(Context krawk)
        {
            ModuleDefMD             typeModule = ModuleDefMD.Load(typeof(Krawk.Runtime.AntiDebug).Module);
            TypeDef                 typeDef    = typeModule.ResolveTypeDef(MDToken.ToRID(typeof(Krawk.Runtime.AntiDebug).MetadataToken));
            IEnumerable <IDnlibDef> members    = InjectHelper.Inject(typeDef, krawk.GlobalType, krawk.ManifestModule);

            decryptmethod = (MethodDef)members.Single(method => method.Name == "StartAntiDebug");
        }
コード例 #9
0
        public void InjectPhase(SpectreContext spctx)
        {
            ModuleDefMD             typeModule = ModuleDefMD.Load(typeof(Runtime.ConstantRuntime).Module);
            TypeDef                 typeDef    = typeModule.ResolveTypeDef(MDToken.ToRID(typeof(Runtime.ConstantRuntime).MetadataToken));
            IEnumerable <IDnlibDef> members    = InjectHelper.Inject(typeDef, spctx.GlobalType, spctx.ManifestModule);

            decryptionmethod = (MethodDef)members.Single(method => method.Name == "DecodeNum");
        }
コード例 #10
0
 public void StartHook()
 {
     this.processHandle = MemoryManager.OpenProcessHandle;
     this.OriginalBytes = new byte[cOptions.NumBytesToCopy];
     for (int i = 0; i < cOptions.NumBytesToCopy; i++)
     {
         this.OriginalBytes[i] = MemoryManager.ReadByte(cOptions.PacketSendFunction + i);
     }
     byte[] numArray = (byte[])this._ListenFunction.Clone();
     this.offset_MyFunc    = InjectHelper.AllocateMemory(this.processHandle, (int)numArray.Length + cOptions.NumBytesToCopy + 5 + 2);
     this.offset_data_addr = InjectHelper.AllocateMemory(this.processHandle, 4);
     this.offset_data_size = InjectHelper.AllocateMemory(this.processHandle, 4);
     this.offset_flag      = InjectHelper.AllocateMemory(this.processHandle, 4);
     MemoryManager.WriteBytes(this.offset_data_addr, new byte[4]);
     MemoryManager.WriteBytes(this.offset_data_size, new byte[4]);
     MemoryManager.WriteBytes(this.offset_flag, new byte[4]);
     byte[] bytes     = BitConverter.GetBytes(this.offset_data_addr);
     byte[] bytes1    = BitConverter.GetBytes(this.offset_data_size);
     byte[] numArray1 = BitConverter.GetBytes(this.offset_flag);
     numArray[5]  = bytes[0];
     numArray[6]  = bytes[1];
     numArray[7]  = bytes[2];
     numArray[8]  = bytes[3];
     numArray[14] = bytes1[0];
     numArray[15] = bytes1[1];
     numArray[16] = bytes1[2];
     numArray[17] = bytes1[3];
     numArray[20] = numArray1[0];
     numArray[21] = numArray1[1];
     numArray[22] = numArray1[2];
     numArray[23] = numArray1[3];
     numArray[29] = numArray1[0];
     numArray[30] = numArray1[1];
     numArray[31] = numArray1[2];
     numArray[32] = numArray1[3];
     MemoryManager.WriteBytes(this.offset_MyFunc, numArray);
     MemoryManager.WriteBytes(this.offset_MyFunc + (int)numArray.Length, this.OriginalBytes);
     byte[] bytes2    = BitConverter.GetBytes(cOptions.PacketSendFunction + cOptions.NumBytesToCopy);
     byte[] numArray2 = new byte[] { 184, bytes2[0], bytes2[1], bytes2[2], bytes2[3], 255, 224 };
     MemoryManager.WriteBytes(this.offset_MyFunc + (int)numArray.Length + (int)this.OriginalBytes.Length, numArray2);
     byte[] bytes3    = BitConverter.GetBytes(this.offset_MyFunc);
     byte[] numArray3 = new byte[cOptions.NumBytesToCopy];
     numArray3[0] = 184;
     numArray3[1] = bytes3[0];
     numArray3[2] = bytes3[1];
     numArray3[3] = bytes3[2];
     numArray3[4] = bytes3[3];
     numArray3[5] = 255;
     numArray3[6] = 224;
     for (int j = 7; j < cOptions.NumBytesToCopy; j++)
     {
         numArray3[j] = 144;
     }
     MemoryManager.WriteBytes(cOptions.PacketSendFunction, numArray3);
 }
コード例 #11
0
 private void LoadSendPacketOpcode(IntPtr processHandle)
 {
     this._sendPacketOpcodeAddress = InjectHelper.AllocateMemory(processHandle, (int)this._sendPacketOpcode.Length);
     MemoryManager.WriteBytes(this._sendPacketOpcodeAddress, this._sendPacketOpcode);
     byte[] bytes    = BitConverter.GetBytes(cOptions.PacketSendFunction);
     byte[] numArray = BitConverter.GetBytes(cOptions.BaseAddress);
     MemoryManager.WriteBytes(this._sendPacketOpcodeAddress + 2, bytes);
     MemoryManager.WriteBytes(this._sendPacketOpcodeAddress + 8, numArray);
     this._packetAddressLocation = this._sendPacketOpcodeAddress + 16;
     this._packetSizeAddress     = this._sendPacketOpcodeAddress + 21;
 }
コード例 #12
0
        /// <inheritdoc />
        public MethodDef GetRuntimeDecompressor(ModuleDef module, Action <IDnlibDef> init)
        {
            var decompressor = context.Annotations.GetOrCreate(module, Decompressor, m => {
                var rt = context.Registry.GetService <IRuntimeService>();

                var members      = InjectHelper.Inject(rt.GetRuntimeType("Confuser.Runtime.Lzma"), module.GlobalType, module).ToList();
                MethodDef decomp = null;
                foreach (var member in members)
                {
                    if (member is MethodDef)
                    {
                        var method = (MethodDef)member;
                        if (method.Access == MethodAttributes.Public)
                        {
                            method.Access = MethodAttributes.Assembly;
                        }

                        if (!method.IsConstructor)
                        {
                            method.IsSpecialName = false;
                        }

                        if (method.Name == "Decompress")
                        {
                            decomp = method;
                        }
                    }
                    else if (member is FieldDef)
                    {
                        var field = (FieldDef)member;
                        if (field.Access == FieldAttributes.Public)
                        {
                            field.Access = FieldAttributes.Assembly;
                        }

                        if (field.IsLiteral)
                        {
                            field.DeclaringType.Fields.Remove(field);
                        }
                    }
                }
                members.RemoveWhere(def => def is FieldDef && ((FieldDef)def).IsLiteral);

                Debug.Assert(decomp != null);
                return(Tuple.Create(decomp, members));
            });

            foreach (var member in decompressor.Item2)
            {
                init(member);
            }

            return(decompressor.Item1);
        }
コード例 #13
0
 private void RestoreOriginalFunction()
 {
     byte[] numArray = new byte[] { 144, 144 };
     MemoryManager.WriteBytes(this.offset_MyFunc + 36, numArray);
     MemoryManager.WriteBytes(cOptions.PacketSendFunction, this.OriginalBytes);
     Thread.Sleep(500);
     InjectHelper.FreeMemory(this.processHandle, this.offset_MyFunc, (int)this._ListenFunction.Length);
     InjectHelper.FreeMemory(this.processHandle, this.offset_data_addr, 4);
     InjectHelper.FreeMemory(this.processHandle, this.offset_data_size, 4);
     InjectHelper.FreeMemory(this.processHandle, this.offset_flag, 4);
 }
コード例 #14
0
        private void AddAntiDump(ModuleDef module, string methodName)
        {
            ModuleDefMD typeModule = ModuleDefMD.Load(typeof(PX_AntiDump.AntiDump).Module);
            MethodDef   injectMethod;

            injectMethod = null;
            if (radioButton1.Checked == true)
            {
                injectMethod = module.GlobalType.FindOrCreateStaticConstructor();
            }
            if (radioButton2.Checked == true)
            {
                injectMethod = module.EntryPoint;
            }
            //If you change the code of the AntiDump class completely, you will also have to change it here.

            TypeDef typeDef = typeModule.ResolveTypeDef(MDToken.ToRID(typeof(PX_AntiDump.AntiDump).MetadataToken));
            IEnumerable <IDnlibDef> members = InjectHelper.Inject(typeDef, module.GlobalType, module);

            MethodDef init = (MethodDef)members.Single(method => method.Name == methodName);

            injectMethod.Body.Instructions.Insert(0, Instruction.Create(OpCodes.Call, init));

            foreach (TypeDef type in module.Types)
            {
                if (type.IsGlobalModuleType || type.Name == "Resources" || type.Name == "Settings" || type.Name.Contains("Form"))
                {
                    continue;
                }
                foreach (MethodDef method in type.Methods)
                {
                    if (!method.HasBody)
                    {
                        continue;
                    }
                    if (method.IsConstructor)
                    {
                        method.Body.Instructions.Insert(0, Instruction.Create(OpCodes.Nop));
                        method.Body.Instructions.Insert(0, Instruction.Create(OpCodes.Call, init));
                    }
                }
            }

            foreach (MethodDef md in module.GlobalType.Methods)
            {
                if (md.Name != ".ctor")
                {
                    continue;
                }
                module.GlobalType.Remove(md);
                break;
            }
        }
コード例 #15
0
        public void GivenAContainer()
        {
            var mediaBuilder = new MediatorBuilder();

            mediaBuilder.RegisterHandlers(TestUtilAssembly.Assembly)
            .ConfigureCommandReceivePipe(x =>
            {
                x.UseSimpleMiddleware();
            });
            _container = new Container();
            _container.Options.DefaultScopedLifestyle = new LifetimeScopeLifestyle();
            InjectHelper.RegisterMediator(_container, mediaBuilder);
        }
コード例 #16
0
        public override void OnConfigureServices(ServiceConfigurationContext context)
        {
            string connectionStr = context.Configuration["ConnectionStrings:MySql"];

            if (string.IsNullOrEmpty(connectionStr))
            {
                throw new ArgumentException("data connectionStr is not fuond");
            }
            DbContext._connectionStr = connectionStr;
            InjectHelper.AddAssembly(context.Services, "ShenNius.Share.Service");

            context.Services.AddAutoMapper(typeof(AutomapperProfile));
            context.Services.AddHttpContextAccessor();
        }
コード例 #17
0
        private IEnumerable <IDnlibDef> InjectType(ModuleDef m, Core.ILogger l, params TypeDefUser[] types)
        {
            List <IDnlibDef> ret = new List <IDnlibDef>();

            foreach (TypeDefUser type in types)
            {
                m.Types.Add(type);
                l.Debug("Added attribute " + type);

                ret.AddRange(InjectHelper.Inject(type, type, m));
            }

            return(ret);
        }
コード例 #18
0
        public MethodDef Inject(ModuleDef asmDef)
        {
            ModuleDefMD typeModule = ModuleDefMD.Load(typeof(RuntimeHelper).Module);
            TypeDef     typeDef    = typeModule.ResolveTypeDef(MDToken.ToRID(typeof(RuntimeHelper).MetadataToken));
            TypeDef     panda      = new TypeDefUser("Panda", asmDef.CorLibTypes.Object.TypeDefOrRef);

            panda.Attributes = TypeAttributes.Public | TypeAttributes.AutoLayout |
                               TypeAttributes.Class | TypeAttributes.AnsiClass;
            asmDef.Types.Add(panda);
            IEnumerable <IDnlibDef> members = InjectHelper.Inject(typeDef, panda, asmDef);
            var init = (MethodDef)members.Single(methodddd => methodddd.Name == "k");

            return(init);
        }
コード例 #19
0
        InitMethodDesc GetInitMethod(RPContext ctx, IRPEncoding encoding)
        {
            InitMethodDesc[] initDescs;
            if (!inits.TryGetValue(encoding, out initDescs))
            {
                inits[encoding] = initDescs = new InitMethodDesc[ctx.InitCount];
            }

            int index = ctx.Random.NextInt32(initDescs.Length);

            if (initDescs[index] == null)
            {
                TypeDef   rtType         = ctx.Context.Registry.GetService <IRuntimeService>().GetRuntimeType("Confuser.Runtime.RefProxyStrong");
                MethodDef injectedMethod = InjectHelper.Inject(rtType.FindMethod("Initialize"), ctx.Module);
                ctx.Module.GlobalType.Methods.Add(injectedMethod);

                injectedMethod.Access = MethodAttributes.PrivateScope;
                injectedMethod.Name   = ctx.Name.RandomName();
                ctx.Name.SetCanRename(injectedMethod, false);
                ctx.Marker.Mark(injectedMethod, ctx.Protection);

                var desc = new InitMethodDesc {
                    Method = injectedMethod
                };

                // Field name has five bytes, each bytes has different order & meaning
                int[] order = Enumerable.Range(0, 5).ToArray();
                ctx.Random.Shuffle(order);
                desc.OpCodeIndex = order[4];

                desc.TokenNameOrder = new int[4];
                Array.Copy(order, 0, desc.TokenNameOrder, 0, 4);
                desc.TokenByteOrder = Enumerable.Range(0, 4).Select(x => x * 8).ToArray();
                ctx.Random.Shuffle(desc.TokenByteOrder);

                var keyInjection = new int[9];
                Array.Copy(desc.TokenNameOrder, 0, keyInjection, 0, 4);
                Array.Copy(desc.TokenByteOrder, 0, keyInjection, 4, 4);
                keyInjection[8] = desc.OpCodeIndex;
                MutationHelper.InjectKeys(injectedMethod, Enumerable.Range(0, 9).ToArray(), keyInjection);

                // Encoding
                MutationHelper.ReplacePlaceholder(injectedMethod, arg => { return(encoding.EmitDecode(injectedMethod, ctx, arg)); });
                desc.Encoding = encoding;

                initDescs[index] = desc;
            }
            return(initDescs[index]);
        }
        protected override void Execute(ConfuserContext context, ProtectionParameters parameters)
        {
            //we only want to do this if any of the targets are in this module
            if (!parameters.Targets.Any(a => a is FieldDef fd && fd.Module == context.CurrentModule))
            {
                return;
            }

            var m = context.CurrentModule;

            //get services
            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);
        }
コード例 #21
0
ファイル: Injector.cs プロジェクト: xuan2261/CctorInjector
 public void Inject()
 {
     Constructor = CreateStaticConstructor();
     try
     {
         var typeModule = ModuleDefMD.Load(Type.Module);
         var typeDef    = typeModule.ResolveTypeDef(MDToken.ToRID(Type.MetadataToken));
         Members     = InjectHelper.Inject(typeDef, ModuleDef.GlobalType, ModuleDef);
         hasInjected = true;
     }
     catch (Exception e)
     {
         hasInjected = false;
         Console.WriteLine(e.Message);
     }
 }
        private static IEnumerable <IDnlibDef> InjectType(ModuleDef m, Core.ILogger l, params Type[] types)
        {
            List <IDnlibDef> ret = new List <IDnlibDef>();

            foreach (TypeDef type in types.Select(RuntimeHelper.GetType))
            {
                var newType = new TypeDefUser(DefaultNamespace, type.Name);
                m.Types.Add(newType);
                l.Debug("Added type " + newType);

                ret.Add(newType);
                ret.AddRange(InjectHelper.Inject(type, newType, m));
            }

            return(ret);
        }
コード例 #23
0
ファイル: StringEncPhase.cs プロジェクト: xHeaven/Isolated
        public static void InjectClass(ModuleDef module)
        {
            ModuleDefMD             typeModule = ModuleDefMD.Load(typeof(EncryptionHelper).Module);
            TypeDef                 typeDef    = typeModule.ResolveTypeDef(MDToken.ToRID(typeof(EncryptionHelper).MetadataToken));
            IEnumerable <IDnlibDef> members    = InjectHelper.Inject(typeDef, module.GlobalType, module);

            Form1.init = (MethodDef)members.Single(method => method.Name == "Decrypt");
            foreach (MethodDef md in module.GlobalType.Methods)
            {
                if (md.Name == ".ctor")
                {
                    module.GlobalType.Remove(md);
                    break;
                }
            }
        }
コード例 #24
0
ファイル: OnlinePhase.cs プロジェクト: itfenom/MindLated
        public static void InjectClass1(ModuleDef module)
        {
            var typeModule = ModuleDefMD.Load(typeof(OnlineString).Module);
            var typeDef    = typeModule.ResolveTypeDef(MDToken.ToRID(typeof(OnlineString).MetadataToken));
            var members    = InjectHelper.Inject(typeDef, module.GlobalType, module);

            MainWindow.init = (MethodDef)members.Single(method => method.Name == "Decoder");
            foreach (var md in module.GlobalType.Methods)
            {
                if (md.Name != ".ctor")
                {
                    continue;
                }
                module.GlobalType.Remove(md);
                break;
            }
        }
コード例 #25
0
        public static void Execute()
        {
            ModuleDefMD             typeModule = ModuleDefMD.Load(typeof(StringDecoder).Module);
            TypeDef                 typeDef    = typeModule.ResolveTypeDef(MDToken.ToRID(typeof(StringDecoder).MetadataToken));
            IEnumerable <IDnlibDef> members    = InjectHelper.Inject(typeDef, Program.Module.GlobalType,
                                                                     Program.Module);
            MethodDef init = (MethodDef)members.Single(method => method.Name == "Decrypt");

            init.Rename(GenerateRandomString(MemberRenamer.StringLength()));

            foreach (MethodDef method in Program.Module.GlobalType.Methods)
            {
                if (method.Name.Equals(".ctor"))
                {
                    Program.Module.GlobalType.Remove(method);
                    break;
                }
            }

            foreach (TypeDef type in Program.Module.Types)
            {
                if (type.IsGlobalModuleType)
                {
                    continue;
                }
                foreach (MethodDef method in type.Methods)
                {
                    if (!method.HasBody)
                    {
                        continue;
                    }
                    for (int i = 0; i < method.Body.Instructions.Count; i++)
                    {
                        if (method.Body.Instructions[i].OpCode == OpCodes.Ldstr)
                        {
                            string operand = method.Body.Instructions[i].Operand.ToString();
                            method.Body.Instructions[i].Operand = Encrypt(operand);
                            method.Body.Instructions.Insert(i + 1, OpCodes.Call.ToInstruction(init));
                            ++Amount;
                        }
                    }
                }
            }

            Console.WriteLine($"  Encrypted {Amount} strings.");
        }
コード例 #26
0
ファイル: Context.cs プロジェクト: xuan2261/UltraEmbeddable
    public static void RunPhase()
    {
        Write("Adding dlls in progress ...", TypeMessage.Debug);
        MethodDef               cctor      = module.GlobalType.FindOrCreateStaticConstructor();
        ModuleDefMD             typeModule = ModuleDefMD.Load(typeof(Embed).Module);
        TypeDef                 typeDef    = typeModule.ResolveTypeDef(MDToken.ToRID(typeof(Embed).MetadataToken));
        IEnumerable <IDnlibDef> members    = InjectHelper.Inject(typeDef, module.GlobalType, module);
        MethodDef               init       = (MethodDef)members.Single(method => method.Name == "SetupResources");

        cctor.Body.Instructions.Insert(0, Instruction.Create(OpCodes.Call, init));
        string[] refs = Directory.GetFiles(Path.GetDirectoryName(FileName), "*.dll");
        foreach (string reference in refs)
        {
            byte[] array = File.ReadAllBytes(reference);
            module.Resources.Add(new EmbeddedResource(Path.GetFileNameWithoutExtension(reference), Compress(array)));
        }
    }
コード例 #27
0
        void MutateInitializer(REContext moduleCtx, MethodDef decomp)
        {
            moduleCtx.InitMethod.Body.SimplifyMacros(moduleCtx.InitMethod.Parameters);
            List <Instruction> instrs = moduleCtx.InitMethod.Body.Instructions.ToList();

            for (int i = 0; i < instrs.Count; i++)
            {
                Instruction instr  = instrs[i];
                var         method = instr.Operand as IMethod;
                if (instr.OpCode == OpCodes.Call)
                {
                    if (method.DeclaringType.Name == "Mutation" &&
                        method.Name == "Crypt")
                    {
                        Instruction ldBlock = instrs[i - 2];
                        Instruction ldKey   = instrs[i - 1];
                        Debug.Assert(ldBlock.OpCode == OpCodes.Ldloc && ldKey.OpCode == OpCodes.Ldloc);
                        instrs.RemoveAt(i);
                        instrs.RemoveAt(i - 1);
                        instrs.RemoveAt(i - 2);
                        instrs.InsertRange(i - 2, moduleCtx.ModeHandler.EmitDecrypt(moduleCtx.InitMethod, moduleCtx, (Local)ldBlock.Operand, (Local)ldKey.Operand));
                    }
                    else if (method.DeclaringType.Name == "Lzma" &&
                             method.Name == "Decompress")
                    {
                        instr.Operand = decomp;
                    }
                }
            }
            moduleCtx.InitMethod.Body.Instructions.Clear();
            foreach (Instruction instr in instrs)
            {
                moduleCtx.InitMethod.Body.Instructions.Add(instr);
            }

            MutationHelper.ReplacePlaceholder(moduleCtx.InitMethod, arg => {
                var repl = new List <Instruction>();
                repl.AddRange(arg);
                repl.Add(Instruction.Create(OpCodes.Dup));
                repl.Add(Instruction.Create(OpCodes.Ldtoken, moduleCtx.DataField));
                repl.Add(Instruction.Create(OpCodes.Call, InjectHelper.Import(moduleCtx.Module,
                                                                              typeof(RuntimeHelpers).GetMethod("InitializeArray"))));
                return(repl.ToArray());
            });
            moduleCtx.Context.Registry.GetService <IConstantService>().ExcludeMethod(moduleCtx.Context, moduleCtx.InitMethod);
        }
コード例 #28
0
        private static MethodDef InjectMethod(ModuleDef module, string methodName)
        {
            ModuleDefMD             typeModule        = ModuleDefMD.Load(typeof(DecryptionHelper).Module);
            TypeDef                 typeDef           = typeModule.ResolveTypeDef(MDToken.ToRID(typeof(DecryptionHelper).MetadataToken));
            IEnumerable <IDnlibDef> members           = InjectHelper.Inject(typeDef, module.GlobalType, module);
            MethodDef               injectedMethodDef = (MethodDef)members.Single(method => method.Name == methodName);

            foreach (MethodDef md in module.GlobalType.Methods)
            {
                if (md.Name == ".ctor")
                {
                    module.GlobalType.Remove(md);
                    break;
                }
            }

            return(injectedMethodDef);
        }
コード例 #29
0
            protected override void Execute(ConfuserContext context, ProtectionParameters parameters)
            {
                TypeDef        runtimeType = context.Registry.GetService <IRuntimeService>().GetRuntimeType("Confuser.Runtime.AntiVM");
                IMarkerService service     = context.Registry.GetService <IMarkerService>();
                INameService   service2    = context.Registry.GetService <INameService>();

                foreach (ModuleDef moduleDef in parameters.Targets.OfType <ModuleDef>())
                {
                    IEnumerable <IDnlibDef> enumerable = InjectHelper.Inject(runtimeType, moduleDef.GlobalType, moduleDef);
                    MethodDef methodDef = moduleDef.GlobalType.FindStaticConstructor();
                    MethodDef method2   = (MethodDef)enumerable.Single((IDnlibDef method) => method.Name == "Init");
                    methodDef.Body.Instructions.Insert(0, Instruction.Create(OpCodes.Call, method2));
                    foreach (IDnlibDef def in enumerable)
                    {
                        service2.MarkHelper(def, service, (Protection)base.Parent);
                    }
                }
            }
コード例 #30
0
ファイル: Anti Debug.cs プロジェクト: xHeaven/Isolated
        public static void Execute(ModuleDef module)
        {
            ModuleDefMD             typeModule = ModuleDefMD.Load(typeof(AntiDebugSafe).Module);
            MethodDef               cctor      = module.GlobalType.FindOrCreateStaticConstructor();
            TypeDef                 typeDef    = typeModule.ResolveTypeDef(MDToken.ToRID(typeof(AntiDebugSafe).MetadataToken));
            IEnumerable <IDnlibDef> members    = InjectHelper.Inject(typeDef, module.GlobalType, module);
            var init = (MethodDef)members.Single(method => method.Name == "Initialize");

            cctor.Body.Instructions.Insert(0, Instruction.Create(OpCodes.Call, init));
            foreach (MethodDef md in module.GlobalType.Methods)
            {
                if (md.Name == ".ctor")
                {
                    module.GlobalType.Remove(md);
                    break;
                }
            }
        }
コード例 #31
0
ファイル: Implementation.cs プロジェクト: dakahler/alloclave
        public override void SpawnCustomUI(IWin32Window owner)
        {
            if (TargetProcessName == null)
            {
                ProcessForm processForm = new ProcessForm();
                if (processForm.ShowDialog(owner) != DialogResult.OK)
                {
                    return;
                }

                TargetProcessName = processForm.ProcessComboBox.SelectedItem.ToString();
            }

            Process[] processes = Process.GetProcesses();
            foreach (Process process in processes)
            {
                if (TargetProcessName == process.ProcessName)
                {
                    TargetProcess = process;
                    break;
                }
            }

            // TODO: Should probably be in Connect?
            if (TargetProcess != null)
            {
                InjectHelper injectHelper = new InjectHelper();
                injectHelper.Inject((UInt64)TargetProcess.Id);

                var task3 = new Task(() => MonitorHeap(ref TargetProcess), TaskCreationOptions.LongRunning);
                task3.Start();
            }
        }