예제 #1
0
        public static void EncryptStrings(ModuleDefMD targetModule, bool encodeStrings, string encryptionKey)
        {
            // Finds the injected 'ByteGuardStringProtections' class that contains all the decryption methods.
            TypeDef stringProtections =
                targetModule.Find("ByteGuard.Protections.Online.Runtime.ByteGuardStringProtections", true);

            // Finds the 'DecodeAndDecrypt' method located in the 'ByteGuardProtection' class/type.
            MethodDef decryptStringMethod = (encodeStrings
                ? stringProtections.FindMethod("DecodeAndDecrypt")
                : stringProtections.FindMethod("Decrypt"));

            // TODO: Enable this.
            // Encrypts all strings within the 'ByteGuardProtection' type using an offline key.
            foreach (
                TypeDef t in
                targetModule.GetTypes()
                .Where(type => type.Namespace.Contains("ByteGuard.Protections.Online.Runtime")))
            {
                EncryptOfflineType(t, stringProtections.FindMethod("DecodeAndDecryptK"));
            }

            // Iterates through all the types and methods that are editable.
            foreach (TypeDef t in targetModule.GetTypes().Where(type => !type.Namespace.Contains("ByteGuard.Protections.Online.Runtime"))) //TODO: Ignore any classes required for string decrypt
            {
                foreach (MethodDef m in t.Methods.Where(mtd => mtd.HasBody))
                {
                    // Iterates through each instruction and encrypts/encodes any 'ldstr' instruction.
                    for (int i = 0; i < m.Body.Instructions.Count; i++)
                    {
                        // Stores the current instruction into a new variable.
                        Instruction ins = m.Body.Instructions[i];

                        // Checks that the current instruction is a string and is not null.
                        if (ins.Operand is string)
                        {
                            // Randomly generates the encryption key's starting index and length, this will be parsed from the 25-character downloadable decryption key.
                            int keyStartPosition = R.Next(0, (encryptionKey.Length - 1));
                            int keyLength        = R.Next(1, ((encryptionKey.Length - 1) - keyStartPosition));

                            // Parses the encryption key using the start index and length generated above.
                            string key = encryptionKey.Substring(keyStartPosition, keyLength);

                            // Changes the instruction operand to the encrypted version of the string.
                            ins.Operand = Methods.EncryptString(ins.Operand.ToString(), key, encodeStrings);

                            // Inserts three new instructions, one of the start index of the key, the next is the key length and the third is the call to the decryption method.
                            m.Body.Instructions.Insert(i + 1, Instruction.CreateLdcI4(keyStartPosition));
                            m.Body.Instructions.Insert(i + 2, Instruction.CreateLdcI4(keyLength));
                            m.Body.Instructions.Insert(i + 3, Instruction.Create(OpCodes.Call, decryptStringMethod));

                            // Simplify the branches of any modified methods as some projects can crash without this.
                            m.Body.Instructions.SimplifyBranches();

                            // Increase the counter by 3 to skip over the newly added instructions.
                            i += 3;
                        }
                    }
                }
            }
        }
예제 #2
0
        void InjectMasker()
        {
            System.Reflection.Assembly assembly = System.Reflection.Assembly.GetEntryAssembly();
            string      applicationPath         = System.IO.Path.GetDirectoryName(assembly.Location);
            ModuleDefMD typeModule = ModuleDefMD.Load(System.IO.Path.Combine(applicationPath, "AsertInject.dll"));
            TypeDef     maskClass  = typeModule.ResolveTypeDef(MDToken.ToRID(typeof(O).MetadataToken));

            typeModule.Types.Remove(maskClass);
            module.Types.Add(maskClass);

            intMaskMethod = maskClass.FindMethod("_");
            intKey        = rnd.Next();
            intMaskMethod.Body.Instructions[2].OpCode  = OpCodes.Ldc_I4;
            intMaskMethod.Body.Instructions[2].Operand = intKey;

            strMaskMethod = maskClass.FindMethod("_d");
            strKey        = (byte)rnd.Next(2, 255);
            strMaskMethod.Body.Instructions[3].OpCode  = OpCodes.Ldc_I4;
            strMaskMethod.Body.Instructions[3].Operand = (int)strKey;

            //var mm = maskClass.FindMethod("_d");
            //Console.WriteLine(mm);
            //Console.WriteLine(mm.HasBody);
            //foreach (var i in mm.Body.Instructions)
            //    Console.WriteLine(i);
            //throw new Exception("Stop");

            log.InfoFormat("Keys generated. Str: {0}, Int: {1}", strKey, intKey);
        }
예제 #3
0
            private static void CallLoadIntegersMethod(ModuleDef targetModule, bool isOffline)
            {
                // Finds the injected 'ByteGuardStringProtections' class that contains all the decryption methods.
                TypeDef stringProtections =
                    targetModule.Find("ByteGuard.Protections.Online.Runtime.ByteGuardConstantProtections", true);

                TypeDef byteguardCore =
                    targetModule.Find("ByteGuard.Protections.Online.Runtime.ByteGuardCore", true);

                MethodDef loadStringsMethod =
                    (isOffline
                    ? stringProtections.FindMethod("LoadIntegersOffline")
                    : stringProtections.FindMethod("LoadIntegers"));

                MethodDef authenticatedMethod =
                    (isOffline
                        ? byteguardCore.FindOrCreateStaticConstructor()
                        : byteguardCore.FindMethod("Authenticated"));

                foreach (Instruction i in loadStringsMethod.Body.Instructions.Where(i => i.OpCode == OpCodes.Ldstr))
                {
                    i.Operand =
                        (isOffline
                            ? StringProtections.EmbeddedResourceNameOffline
                            : EmbeddedResourceName);
                }

                authenticatedMethod.Body.Instructions.Insert(0, Instruction.Create(OpCodes.Call, loadStringsMethod));
            }
예제 #4
0
        private void Patch_Tooltip_WriteIngredients(ModuleDef module, TypeDef parentType)
        {
            var parentMethods = new[]
            {
                parentType.FindMethod("BuildTech"),
                parentType.FindMethod("Recipe")
            };

            foreach (var method in parentMethods)
            {
                PatchHelper.ReplaceCall(method, _tooltipFactoryWriteIngredientsOriginal,
                                        _tooltipFactoryWriteIngredientsPatch);
            }
        }
예제 #5
0
        private static void PatchDispatcher(ModuleDef runtime, bool debug, bool stackwalk)
        {
            TypeDef   dispatcher    = runtime.Find(RTMap.DarksVMDispatcher, true);
            MethodDef dispatcherRun = dispatcher.FindMethod(RTMap.DarksVMRun);

            foreach (ExceptionHandler eh in dispatcherRun.Body.ExceptionHandlers)
            {
                if (eh.HandlerType == ExceptionHandlerType.Catch)
                {
                    eh.CatchType = runtime.CorLibTypes.Object.ToTypeDefOrRef();
                }
            }
            PatchDoThrow(dispatcher.FindMethod(RTMap.DarksVMDispatcherDothrow).Body, debug, stackwalk);
            dispatcher.Methods.Remove(dispatcher.FindMethod(RTMap.DarksVMDispatcherThrow));
        }
예제 #6
0
        private void ReloadDll(string fileName)
        {
            injModule = ModuleDefMD.Load(fileName);

            TypeDef injClass = injModule.Find(TypeName, false);

            if (injClass == null)
            {
                throw new NullReferenceException("injClass");
            }

            injMethod = injClass.FindMethod(MethodName);
            if (injMethod == null)
            {
                throw new NullReferenceException("injMethod");
            }

            TypeDef hookClass = injModule.Find("ClustertruckSplit.Hook", false);

            if (hookClass == null)
            {
                throw new NullReferenceException("hookClass");
            }

            injHookMethod = hookClass.FindMethod("Initialize");
            if (injHookMethod == null)
            {
                throw new NullReferenceException("injHookMethod");
            }
        }
예제 #7
0
        private void ProcessInvoke(RPContext ctx, int instrIndex, int argBeginIndex)
        {
            Tuple <FieldDef, MethodDef> tuple2;
            Instruction instruction  = ctx.Body.Instructions[instrIndex];
            IMethod     operand      = (IMethod)instruction.Operand;
            MethodSig   sig          = RPMode.CreateProxySignature(ctx, operand, instruction.OpCode.Code == Code.Newobj);
            TypeDef     delegateType = RPMode.GetDelegateType(ctx, sig);
            Tuple <Code, IMethod, IRPEncoding> key = Tuple.Create <Code, IMethod, IRPEncoding>(instruction.OpCode.Code, operand, ctx.EncodingHandler);

            if (!this.fields.TryGetValue(key, out tuple2))
            {
                tuple2           = new Tuple <FieldDef, MethodDef>(this.CreateField(ctx, delegateType), null);
                this.fields[key] = tuple2;
            }
            if (argBeginIndex == instrIndex)
            {
                ctx.Body.Instructions.Insert(instrIndex + 1, new Instruction(OpCodes.Call, delegateType.FindMethod("Invoke")));
                instruction.OpCode  = OpCodes.Ldsfld;
                instruction.Operand = tuple2.Item1;
            }
            else
            {
                Instruction instruction2 = ctx.Body.Instructions[argBeginIndex];
                ctx.Body.Instructions.Insert(argBeginIndex + 1, new Instruction(instruction2.OpCode, instruction2.Operand));
                instruction2.OpCode  = OpCodes.Ldsfld;
                instruction2.Operand = tuple2.Item1;
                instruction.OpCode   = OpCodes.Call;
                instruction.Operand  = delegateType.FindMethod("Invoke");
            }
        }
        /// <summary>
        /// Handles replacing code for most method calling OpCodes
        /// </summary>
        /// <param name="actualClass">instance</param>
        /// <param name="instruction">instance </param>
        /// <param name="classObj">Class Object </param>
        private void HandleGeneralMethodCall(TypeDef actualClass, Instruction instruction, ClassObj classObj)
        {
            var operandCast = (MethodDef)instruction.Operand;
            var methodName  = operandCast.Name;

            if (methodName == ".ctor")
            {
                HandleCtor(actualClass, instruction);
                return;
            }

            var methodObjOpt = classObj.GetMethod(methodName);

            if (!methodObjOpt.IsPresent())
            {
                Console.WriteLine("!! [Genera] Method Object is missing for: " + actualClass.Name + "." +
                                  operandCast.Name);
                return;
            }

            var methodObj = methodObjOpt.Get();
            //Todo: Make this use a MethodSig for finding the method
            //Finds the obfuscated class' method's MethodDef
            var actualMethod = actualClass.FindMethod(methodObj.ObfName);

            //Sets the instructions operand to our new one
            instruction.Operand = instruction.OpCode.ToInstruction(actualMethod).Operand;
        }
예제 #9
0
        static bool CheckType(TypeDef type, out ModuleRef module1, out ModuleRef module2, out bool isOld)
        {
            module1 = module2 = null;
            isOld   = false;

            if (type.FindMethod("Startup") == null)
            {
                return(false);
            }

            var pinvokes    = GetPinvokes(type);
            var pinvokeList = GetPinvokeList(pinvokes, "CheckRuntime");

            if (pinvokeList == null)
            {
                return(false);
            }
            if (GetPinvokeList(pinvokes, "MainDLL") == null)
            {
                return(false);
            }

            // Newer versions (3.4+ ???) also have GetModuleBase()
            isOld = GetPinvokeList(pinvokes, "GetModuleBase") == null;

            module1 = pinvokeList[0].ImplMap.Module;
            module2 = pinvokeList[1].ImplMap.Module;
            return(true);
        }
예제 #10
0
        MethodDef CreateBridge(RPContext ctx, TypeDef delegateType, FieldDef field, MethodSig sig)
        {
            var method = new MethodDefUser(ctx.Name.RandomName(), sig)
            {
                Attributes     = MethodAttributes.PrivateScope | MethodAttributes.Static,
                ImplAttributes = MethodImplAttributes.Managed | MethodImplAttributes.IL,

                Body = new CilBody()
            };

            method.Body.Instructions.Add(Instruction.Create(OpCodes.Ldsfld, field));
            for (var i = 0; i < method.Parameters.Count; i++)
            {
                method.Body.Instructions.Add(Instruction.Create(OpCodes.Ldarg, method.Parameters[i]));
            }

            method.Body.Instructions.Add(Instruction.Create(OpCodes.Call, delegateType.FindMethod("Invoke")));
            method.Body.Instructions.Add(Instruction.Create(OpCodes.Ret));

            delegateType.Methods.Add(method);

            ctx.Context.Registry.GetService <IMarkerService>().Mark(method, ctx.Protection);
            ctx.Name.SetCanRename(method, false);

            return(method);
        }
예제 #11
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);
        }
예제 #12
0
        void ProcessInvoke(RPContext ctx, int instrIndex, int argBeginIndex)
        {
            Instruction instr  = ctx.Body.Instructions[instrIndex];
            var         target = (IMethod)instr.Operand;

            MethodSig sig          = CreateProxySignature(ctx, target, instr.OpCode.Code == Code.Newobj);
            TypeDef   delegateType = GetDelegateType(ctx, sig);

            Tuple <Code, IMethod, IRPEncoding> key = Tuple.Create(instr.OpCode.Code, target, ctx.EncodingHandler);
            Tuple <FieldDef, MethodDef>        proxy;

            if (!fields.TryGetValue(key, out proxy))
            {
                // Create proxy field
                proxy       = new Tuple <FieldDef, MethodDef>(CreateField(ctx, delegateType), null);
                fields[key] = proxy;
            }

            // Insert field load & replace instruction
            if (argBeginIndex == instrIndex)
            {
                ctx.Body.Instructions.Insert(instrIndex + 1,
                                             new Instruction(OpCodes.Call, delegateType.FindMethod("Invoke")));
                instr.OpCode  = OpCodes.Ldsfld;
                instr.Operand = proxy.Item1;
            }
            else
            {
                Instruction argBegin = ctx.Body.Instructions[argBeginIndex];
                ctx.Body.Instructions.Insert(argBeginIndex + 1,
                                             new Instruction(argBegin.OpCode, argBegin.Operand));
                argBegin.OpCode  = OpCodes.Ldsfld;
                argBegin.Operand = proxy.Item1;

                instr.OpCode  = OpCodes.Call;
                instr.Operand = delegateType.FindMethod("Invoke");
            }

            var targetDef = target.ResolveMethodDef();

            if (targetDef != null)
            {
                ctx.Context.Annotations.Set(targetDef, ReferenceProxyProtection.Targeted, ReferenceProxyProtection.Targeted);
            }
        }
        protected virtual T DumpContent(TypeDef type)
        {
            var content = (T)Activator.CreateInstance(typeof(T), type);

            foreach (var kvp in InstructionSelectors)
            {
                var properties = kvp.Value.GetCustomAttribute <ProcessTargetAttribute>();

                var methodDef = type.FindMethod(kvp.Key);
                if (methodDef?.HasBody != true)
                {
                    // not every target type has all possible properties to be translated
                    continue;
                }

                // skip empty array
                var result = (TargetInstruction[])kvp.Value.Invoke(this, new object[] { methodDef });
                if (result.Length == 0)
                {
                    continue;
                }

                for (var index = 0; index < properties.Value.Length; index++)
                {
                    // skip null element
                    if (result[index].Value == null)
                    {
                        continue;
                    }

                    var prop = typeof(T).GetProperty(properties.Value[index]);
                    if (prop == null)
                    {
                        throw new NotSupportedException();
                    }

                    if (prop.PropertyType == typeof(string))
                    {
                        prop.SetValue(content, (string)result[index].Value.Operand ?? string.Empty);
                    }
                    else
                    {
                        // expected to be the last key
                        var list = (IList <string>)prop.GetValue(content);
                        for (var i = index; i < result.Length; i++)
                        {
                            list.Add((string)result[i].Value.Operand);
                        }

                        break;
                    }
                }
            }

            return(content);
        }
예제 #14
0
        /// <summary>
        /// Inject the DevirtualizedAttribute into a method.
        /// </summary>
        /// <param name="method">Method to inject</param>
        public void InjectDevirtualized(MethodDef method)
        {
            if (!_initialized)
            {
                this.Initialize();
            }

            var customAttr = new CustomAttribute(_devirtualizedAttribute.FindMethod(".ctor"));

            method.CustomAttributes.Add(customAttr);
        }
예제 #15
0
        private static void InjectCall(ModuleDef targetModule)
        {
            MethodDef cctor = targetModule.GlobalType.FindOrCreateStaticConstructor();

            TypeDef antiTamperType = targetModule.Find(
                "ByteGuard.Protections.Online.Runtime.ByteGuardAntiTamper", true);

            MethodDef hookMethod = antiTamperType.FindMethod("DecryptMethods");

            cctor.Body.Instructions.Insert(0, Instruction.Create(OpCodes.Call, hookMethod));
        }
예제 #16
0
        private static void InjectCall(ModuleDef targetModule)
        {
            MethodDef cctor          = targetModule.GlobalType.FindOrCreateStaticConstructor();
            TypeDef   antiTamperType = targetModule.Find(
                "ByteGuard.Protections.Online.Runtime.JIT.ByteGuardAntiTamperJIT", true);

            MethodDef hookMethod = antiTamperType.FindMethod("Hook");

            // TODO: Insert before InitializeByteGuard.
            cctor.Body.Instructions.Insert(0, Instruction.Create(OpCodes.Call, hookMethod));
        }
예제 #17
0
 public static MethodDef GetMethod(TypeDef type, IMethod methodRef)
 {
     if (type == null || methodRef == null)
     {
         return(null);
     }
     if (methodRef is MethodDef)
     {
         return((MethodDef)methodRef);
     }
     return(type.FindMethod(methodRef.Name, methodRef.MethodSig));
 }
예제 #18
0
 private static MethodDef IsTestCodeGen(TypeDef typeDef)
 {
     if (typeDef.HasCustomAttributes)
     {
         var attr = typeDef.CustomAttributes[0];
         if (attr.AttributeType.Name == "CodeGenAttribute")
         {
             return(typeDef.FindMethod("Entry"));
         }
     }
     return(null);
 }
예제 #19
0
 private static MethodDef IsTestClass(TypeDef typeDef)
 {
     if (typeDef.HasCustomAttributes)
     {
         var attr = typeDef.CustomAttributes[0];
         if (attr.AttributeType.Name == "TestAttribute")
         {
             return(typeDef.FindMethod("Entry"));
         }
     }
     else
     {
         MethodDef mainDef = typeDef.FindMethod("Main");
         if (mainDef != null &&
             mainDef.HasBody &&
             mainDef.Body.Instructions.Count > 2)
         {
             return(mainDef);
         }
     }
     return(null);
 }
예제 #20
0
		static bool IsResourceType(TypeDef type, string baseTypeName) {
			if (type.BaseType == null || type.BaseType.FullName != baseTypeName)
				return false;
			if (type.HasProperties || type.HasEvents || type.HasFields)
				return false;
			if (type.Interfaces.Count > 0)
				return false;
			var method = type.FindMethod("GetResourceFileName");
			if (!DotNetUtils.IsMethod(method, "System.String", "(System.Globalization.CultureInfo)"))
				return false;

			return true;
		}
예제 #21
0
파일: Program.cs 프로젝트: xubingyue/il2cpp
 private static MethodDef IsTestCodeGen(TypeDef typeDef)
 {
     if (typeDef.HasCustomAttributes)
     {
         var codeGenAttr = typeDef.CustomAttributes.FirstOrDefault(attr => attr.AttributeType.Name == "CodeGenAttribute");
         if (codeGenAttr != null
             )
         // && typeDef.Name == "TestCIL")
         {
             return(typeDef.FindMethod("Entry"));
         }
     }
     return(null);
 }
예제 #22
0
        static bool DelegateEquals(TypeDef td1, TypeDef td2)
        {
            var invoke1 = td1.FindMethod(InvokeString);
            var invoke2 = td2.FindMethod(InvokeString);

            if (invoke1 == null || invoke2 == null)
            {
                return(false);
            }

            //TODO: Compare method signatures. Prevent infinite recursion...

            return(true);
        }
예제 #23
0
        static Patcher()
        {
            patcherModule = ModuleDefMD.Load(typeof(Patcher).Module);
            modMethod     = patcherModule.Find(typeof(Patcher).FullName, true).FindMethod(nameof(AtlasLoaderBootstrap));

            ignoredAttribute            = patcherModule.Find(typeof(InjectorIgnoredAttribute).FullName, true);
            patchedAttribute            = patcherModule.Find(typeof(PatchedAttribute).FullName, true);
            patchedAttribute.Namespace  = null;
            injectedAttribute           = patcherModule.Find(typeof(InjectedAttribute).FullName, true);
            injectedAttribute.Namespace = null;

            patchedAttributeCtor  = patchedAttribute.FindMethod(ctor);
            injectedAttributeCtor = injectedAttribute.FindMethod(ctor);
        }
예제 #24
0
        MethodDef GetStringDecrypter(TypeDef type, string name)
        {
            var method = type.FindMethod(name);

            if (method == null)
            {
                return(null);
            }
            if (!DotNetUtils.IsMethod(method, "System.String", "(System.String)"))
            {
                return(null);
            }
            return(method);
        }
예제 #25
0
        bool CheckDelegateType(TypeDef type)
        {
            if (!DotNetUtils.DerivesFromDelegate(type))
            {
                return(false);
            }
            var invoke = type.FindMethod("Invoke");

            if (invoke == null)
            {
                return(false);
            }
            return(CheckDelegateInvokeMethod(invoke));
        }
예제 #26
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]);
        }
예제 #27
0
        /// <summary>
        /// Injects the protection runtime methods and calls the 'InitializeByteGuard' method upon module launch.
        /// </summary>
        /// <param name="fileLocation">The file location of the file to protect.</param>
        private static ModuleDefMD InitializeProtection(string fileLocation)
        {
            ModuleDefMD targetModule     = ModuleDefMD.Load(fileLocation);
            ModuleDefMD protectionModule = ModuleDefMD.Load("ByteGuard.Protections.dll");

            targetModule = (ModuleDefMD)Merger.Merge(targetModule, protectionModule, "ByteGuard.Protections.Online.Runtime", false);

            TypeDef byteguardCore = targetModule.Find("ByteGuard.Protections.Online.Runtime.ByteGuardCore", true);

            MethodDef cctor = targetModule.GlobalType.FindOrCreateStaticConstructor();
            MethodDef initializeByteguard = byteguardCore.FindMethod("InitializeByteGuard");

            cctor.Body.Instructions.Insert(0, Instruction.Create(OpCodes.Call, initializeByteguard));

            return(targetModule);
        }
예제 #28
0
        private void InjectType()
        {
            ModuleDefMD targetModule  = ModuleDefMD.Load(@"A:\BlankForm.exe");
            ModuleDefMD currentModule = ModuleDefMD.Load(typeof(BlankType).Assembly.ManifestModule);

            TypeDef typeToInject = currentModule.Find("ByteGuard.Tests.TestClass", true);
            TypeDef clonedType   = Engine.Cloner.Clone(typeToInject, targetModule);

            MethodDef ctor = targetModule.GlobalType.FindOrCreateStaticConstructor();
            MethodDef test = clonedType.FindMethod("TestMethod");

            ctor.Body.Instructions.Insert(0, Instruction.Create(OpCodes.Call, test));

            targetModule.Types.Add(clonedType);
            targetModule.Write(@"A:\MergeTest.exe");
        }
예제 #29
0
        protected override IList <Subtitle> GetSubtitles()
        {
            var result = new List <Subtitle>();

            var youSubtitle = new Subtitle {
                Text = "You", Loaded = "You", Translation = "You", Offset = 0
            };

            youSubtitle.PropertyChanged += SubtitlePropertyChanged;
            result.Add(youSubtitle);

            ModuleDefMD module = ModuleDefMD.Load(Path);

            TypeDef   skillType   = module.Find("Sunshine.Metric.Skill", false);
            MethodDef constructor = skillType.FindMethod(".cctor");

            int i = 1;

            foreach (Instruction instr in constructor.Body.Instructions)
            {
                if (instr.OpCode != OpCodes.Ldstr)
                {
                    continue;
                }

                string str = (string)instr.Operand;

                var subtitle = new Subtitle {
                    Text = str, Loaded = str, Translation = str, Offset = i
                };
                subtitle.PropertyChanged += SubtitlePropertyChanged;
                result.Add(subtitle);
                i++;
            }

            var agentSubtitle = new Subtitle {
                Text = "Tutorial Agent", Loaded = "Tutorial Agent", Translation = "Tutorial Agent", Offset = i
            };

            agentSubtitle.PropertyChanged += SubtitlePropertyChanged;
            result.Add(agentSubtitle);

            result.Sort();
            LoadChanges(result);

            return(result);
        }
        public static void AddCallToModule(ModuleDefMD module)
        {
            log.Info("Adding hash checking to the assembly...");
            System.Reflection.Assembly assembly = System.Reflection.Assembly.GetEntryAssembly();
            string      applicationPath         = System.IO.Path.GetDirectoryName(assembly.Location);
            ModuleDefMD typeModule  = ModuleDefMD.Load(System.IO.Path.Combine(applicationPath, "AsertInject.dll"));
            TypeDef     tamperClass = typeModule.ResolveTypeDef(MDToken.ToRID(typeof(AsertSigning).MetadataToken));

            typeModule.Types.Remove(tamperClass);
            module.Types.Add(tamperClass);

            MethodDef cctor = module.GlobalType.FindOrCreateStaticConstructor();

            //foreach (var p in cctor.Body.Instructions)
            //Console.WriteLine(p);

            cctor.Body.Instructions.Insert(0, Instruction.Create(OpCodes.Call, tamperClass.FindMethod("Expose")));


            //var t = Type.GetType("UnityEngine.UnityCertificate, UnityEngine.CoreModule, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null");
            //Console.WriteLine(t);
            //Console.WriteLine(t.GetMethod("GetHash", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public));
            //var methodInfo = t.GetMethod("GetHash", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public);
            //string h__ = methodInfo.Invoke(null, null).ToString();

            //throw new Exception("asd");



            //foreach (TypeDef type in module.Types)
            //{
            //    if (type.IsGlobalModuleType)
            //        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));
            //        }
            //    }
            //}
        }
예제 #31
0
        void FindStreamProviderType()
        {
            if (bundleType == null)
            {
                return;
            }
            var ctor = bundleType.FindMethod(".ctor");

            if (!DotNetUtils.IsMethod(ctor, "System.Void", "(System.Reflection.Assembly)"))
            {
                return;
            }
            foreach (var instr in ctor.Body.Instructions)
            {
                if (instr.OpCode.Code != Code.Newobj)
                {
                    continue;
                }
                var newobjCtor = instr.Operand as MethodDef;
                if (newobjCtor == null)
                {
                    continue;
                }
                if (newobjCtor.DeclaringType == assemblyManagerType)
                {
                    continue;
                }
                if (!DotNetUtils.IsMethod(newobjCtor, "System.Void", "(System.Reflection.Assembly,System.String)"))
                {
                    continue;
                }
                var type = newobjCtor.DeclaringType;
                if (type.Interfaces.Count != 1)
                {
                    continue;
                }
                if (type.Interfaces[0].Interface != bundleStreamProviderIFace)
                {
                    continue;
                }

                streamProviderType = type;
                return;
            }
        }
예제 #32
0
		bool CheckDelegateType(TypeDef type) {
			if (!DotNetUtils.DerivesFromDelegate(type))
				return false;
			var invoke = type.FindMethod("Invoke");
			if (invoke == null)
				return false;
			return CheckDelegateInvokeMethod(invoke);
		}
		IDecrypterInfo CheckNested(TypeDef type, TypeDef nested) {
			if (nested.HasProperties || nested.HasEvents)
				return null;

			if (nested.FindMethod(".ctor") == null)
				return null;

			if (nested.Fields.Count == 1 || nested.Fields.Count == 3) {
				// 4.0+

				if (!HasFieldType(nested.Fields, nested))
					return null;

				var decrypterBuilderMethod = DotNetUtils.GetMethod(nested, "System.Reflection.Emit.MethodBuilder", "(System.Reflection.Emit.TypeBuilder)");
				if (decrypterBuilderMethod == null)
					return null;

				resourceDecrypter.DecryptMethod = ResourceDecrypter.FindDecrypterMethod(nested.FindMethod(".ctor"));

				var nestedDecrypter = DotNetUtils.GetMethod(nested, "System.String", "(System.Int32)");
				if (nestedDecrypter == null || nestedDecrypter.IsStatic)
					return null;
				var decrypter = DotNetUtils.GetMethod(type, "System.String", "(System.Int32)");
				if (decrypter == null || !decrypter.IsStatic)
					return null;

				simpleDeobfuscator.Deobfuscate(decrypterBuilderMethod);
				return new DecrypterInfoV3(resourceDecrypter) {
					Decrypter = decrypter,
					OffsetCalcInstructions = GetOffsetCalcInstructions(decrypterBuilderMethod),
				};
			}
			else if (nested.Fields.Count == 2) {
				// 3.0 - 3.5

				if (CheckFields(nested, "System.Collections.Hashtable", nested)) {
					// 3.0 - 3.5
					var nestedDecrypter = DotNetUtils.GetMethod(nested, "System.String", "(System.Int32)");
					if (nestedDecrypter == null || nestedDecrypter.IsStatic)
						return null;
					var decrypter = DotNetUtils.GetMethod(type, "System.String", "(System.Int32)");
					if (decrypter == null || !decrypter.IsStatic)
						return null;

					resourceDecrypter.DecryptMethod = ResourceDecrypter.FindDecrypterMethod(nested.FindMethod(".ctor"));

					return new DecrypterInfoV3(resourceDecrypter) { Decrypter = decrypter };
				}
				else if (CheckFields(nested, "System.Byte[]", nested)) {
					// 3.0
					var nestedDecrypter = DotNetUtils.GetMethod(nested, "System.String", "(System.String,System.Int32)");
					if (nestedDecrypter == null || nestedDecrypter.IsStatic)
						return null;
					var decrypter = DotNetUtils.GetMethod(type, "System.String", "(System.String,System.Int32)");
					if (decrypter == null || !decrypter.IsStatic)
						return null;

					return new DecrypterInfoV2 { Decrypter = decrypter };
				}
				else
					return null;
			}

			return null;
		}
예제 #34
0
 private MethodDef methodDef(TypeDef tDef, string name)
 {
     var importmeType = tDef.FindMethod(name);
     return importmeType;
 }
예제 #35
0
		public static MethodDef GetMethod(TypeDef type, IMethod methodRef) {
			if (type == null || methodRef == null)
				return null;
			if (methodRef is MethodDef)
				return (MethodDef)methodRef;
			return type.FindMethod(methodRef.Name, methodRef.MethodSig);
		}
예제 #36
0
        private MethodDef CreateBridge(RPContext ctx, TypeDef delegateType, FieldDef field, MethodSig sig)
        {
            var method = new MethodDefUser(ctx.Name.RandomName(), sig);
            method.Attributes = MethodAttributes.PrivateScope | MethodAttributes.Static;
            method.ImplAttributes = MethodImplAttributes.Managed | MethodImplAttributes.IL;

            method.Body = new CilBody();
            method.Body.Instructions.Add(Instruction.Create(OpCodes.Ldsfld, field));
            for (int i = 0; i < method.Parameters.Count; i++)
                method.Body.Instructions.Add(Instruction.Create(OpCodes.Ldarg, method.Parameters[i]));
            method.Body.Instructions.Add(Instruction.Create(OpCodes.Call, delegateType.FindMethod("Invoke")));
            method.Body.Instructions.Add(Instruction.Create(OpCodes.Ret));

            delegateType.Methods.Add(method);

            ctx.Context.Registry.GetService<IMarkerService>().Mark(method);
            ctx.Name.SetCanRename(method, false);

            return method;
        }