示例#1
0
        private static SortedSet <string> Instrument(ModuleDefMD src, Stream dst, Func <string, bool> matcher, TypeDef traceType)
        {
            var sharedMemDef    = traceType.Fields.Single(f => f.Name == nameof(Common.Trace.SharedMem));
            var prevLocationDef = traceType.Fields.Single(f => f.Name == nameof(Common.Trace.PrevLocation));

            var sharedMemRef    = src.Import(sharedMemDef);
            var prevLocationRef = src.Import(prevLocationDef);

            var types = new SortedSet <string>();

            foreach (var type in src.GetTypes())
            {
                if (type.HasMethods && matcher(type.FullName))
                {
                    bool instrumented = false;

                    foreach (var method in type.Methods)
                    {
                        if (method.HasBody)
                        {
                            Method.Instrument(sharedMemRef, prevLocationRef, method);

                            if (!instrumented)
                            {
                                types.Add(type.FullName);
                                instrumented = true;
                            }
                        }
                    }
                }
            }

            src.Write(dst);
            return(types);
        }
示例#2
0
 public void Initialize()
 {
     MethodDefs.Add(_moduleDefMd.Import(typeof(StackTrace).GetConstructor(new Type[0])));
     MethodDefs.Add(_moduleDefMd.Import(typeof(StackTrace).GetMethod("GetFrame", new Type[] { typeof(int) })));
     MethodDefs.Add(_moduleDefMd.Import(typeof(StackFrame).GetMethod("GetMethod")));
     MethodDefs.Add(_moduleDefMd.Import(typeof(MethodBase).GetMethod("GetMethodBody")));
     MethodDefs.Add(_moduleDefMd.Import(typeof(MethodBody).GetMethod("GetILAsByteArray")));
 }
示例#3
0
        public void Apply()
        {
            string assemblyCSharp         = Path.Combine(subnauticaManagedPath, GAME_ASSEMBLY_NAME);
            string nitroxPatcherPath      = Path.Combine(subnauticaManagedPath, NITROX_ASSEMBLY_NAME);
            string modifiedAssemblyCSharp = Path.Combine(subnauticaManagedPath, GAME_ASSEMBLY_MODIFIED_NAME);

            if (File.Exists(modifiedAssemblyCSharp))
            {
                File.Delete(modifiedAssemblyCSharp);
            }

            using (ModuleDefMD module = ModuleDefMD.Load(assemblyCSharp))
                using (ModuleDefMD nitroxPatcherAssembly = ModuleDefMD.Load(nitroxPatcherPath))
                {
                    TypeDef   nitroxMainDefinition    = nitroxPatcherAssembly.GetTypes().FirstOrDefault(x => x.Name == NITROX_ENTRY_TYPE_NAME);
                    MethodDef executeMethodDefinition = nitroxMainDefinition.Methods.FirstOrDefault(x => x.Name == NITROX_ENTRY_METHOD_NAME);

                    MemberRef executeMethodReference = module.Import(executeMethodDefinition);

                    TypeDef   gameInputType = module.GetTypes().First(x => x.FullName == GAME_INPUT_TYPE_NAME);
                    MethodDef awakeMethod   = gameInputType.Methods.First(x => x.Name == GAME_INPUT_METHOD_NAME);

                    Instruction callNitroxExecuteInstruction = OpCodes.Call.ToInstruction(executeMethodReference);

                    awakeMethod.Body.Instructions.Insert(0, callNitroxExecuteInstruction);
                    module.Write(modifiedAssemblyCSharp);
                }

            File.SetAttributes(assemblyCSharp, System.IO.FileAttributes.Normal);
            File.Delete(assemblyCSharp);
            File.Move(modifiedAssemblyCSharp, assemblyCSharp);
        }
示例#4
0
        public bool Inject(ModuleDefMD _Module, string _Path)
        {
            Module = _Module;
            path   = _Path;
            bool injected = false;

            TypeDef[] array = Module.Types.ToArray <TypeDef>();
            for (int i = 0; i < array.Length; i++)
            {
                foreach (MethodDef method in array[i].Methods.ToArray <MethodDef>())
                {
                    bool flag = method.HasBody && method.Body.HasInstructions && method.Body.Instructions.Count() >= 15 && !method.FullName.Contains("My.") && !method.FullName.Contains(".My") && !method.IsConstructor && !method.DeclaringType.IsGlobalModuleType;
                    if (flag)
                    {
                        for (int j = 0; j < method.Body.Instructions.Count - 1; j++)
                        {
                            if (method.Body.Instructions[j].OpCode == OpCodes.Callvirt)
                            {
                                string operand = method.Body.Instructions[j].Operand.ToString();
                                if (operand.Contains("System.Object System.Reflection.MethodBase::Invoke(System.Object,System.Object[])") && method.Body.Instructions[j - 1].IsLdarg() && method.Body.Instructions[j - 2].IsLdarg() && method.Body.Instructions[j - 3].IsLdarg())
                                {
                                    Importer importer = new Importer(Module);
                                    IMethod  myMethod;
                                    myMethod = importer.Import(typeof(Venturi77CallHijacker.Handler).GetMethod("HandleInvoke"));
                                    method.Body.Instructions[j].Operand = Module.Import(myMethod);
                                    method.Body.Instructions[j].OpCode  = OpCodes.Call;
                                    injected = true;
                                }
                            }
                        }
                    }
                }
            }
            return(injected);
        }
示例#5
0
        static void AddServerVariables(string path, string runtimepath)
        {
            if (!File.Exists(path))
            {
                Error("Couldn't find server variables file at " + path);
            }

            var dict = JsonConvert.DeserializeObject <Dictionary <string, string> >(File.ReadAllText(path));
            var mod  = ModuleDefMD.Load(runtimepath);

            var seal = mod.Types.Single(t => t.Name == "Seal");
            var vars = seal.Fields.Single(f => f.Name == "_vars");
            var body = seal.FindOrCreateStaticConstructor().Body;

            foreach (var pair in dict)
            {
                body.Instructions.Insert(2, new Instruction(OpCodes.Ldsfld, vars));
                body.Instructions.Insert(3, new Instruction(OpCodes.Ldstr, pair.Key));
                body.Instructions.Insert(4, new Instruction(OpCodes.Ldstr, pair.Value));
                body.Instructions.Insert(5, new Instruction(OpCodes.Callvirt, _mod.Import(typeof(Dictionary <string, string>).GetMethod("set_Item", (BindingFlags)(-1)))));
            }

            using (var ms = new MemoryStream()) {
                mod.Write(ms);
                mod.Dispose();
                File.WriteAllBytes(runtimepath, ms.ToArray());
            }
        }
示例#6
0
        public void Apply()
        {
            string gameInputPath        = subnauticaBasePath + GAME_ASSEMBLY_NAME;
            string nitroxPatcherPath    = subnauticaBasePath + NITROX_ASSEMBLY_NAME;
            string modifiedAssemblyPath = subnauticaBasePath + GAME_ASSEMBLY_MODIFIED_NAME;

            using (ModuleDefMD module = ModuleDefMD.Load(gameInputPath))
                using (ModuleDefMD nitroxPatcherAssembly = ModuleDefMD.Load(nitroxPatcherPath))
                {
                    TypeDef   nitroxMainDefinition    = nitroxPatcherAssembly.GetTypes().FirstOrDefault(x => x.Name == NITROX_ENTRY_TYPE_NAME);
                    MethodDef executeMethodDefinition = nitroxMainDefinition.Methods.FirstOrDefault(x => x.Name == NITROX_ENTRY_METHOD_NAME);

                    MemberRef executeMethodReference = module.Import(executeMethodDefinition);

                    TypeDef   gameInputType = module.GetTypes().First(x => x.FullName == GAME_INPUT_TYPE_NAME);
                    MethodDef awakeMethod   = gameInputType.Methods.First(x => x.Name == GAME_INPUT_METHOD_NAME);

                    Instruction callNitroxExecuteInstruction = OpCodes.Call.ToInstruction(executeMethodReference);

                    awakeMethod.Body.Instructions.Insert(0, callNitroxExecuteInstruction);
                    module.Write(modifiedAssemblyPath);
                }

            string backuupAssemblyPath = subnauticaBasePath + GAME_ASSEMBLY_BACKUP_NAME;

            File.Replace(modifiedAssemblyPath, gameInputPath, backuupAssemblyPath);
        }
        public override void Deobfuscate()
        {
            //          Console.WriteLine("[!] Cleaning Callis");
            List <CallInfo> calls = FindPointers();

            if (calls == null)
            {
                return;
            }
            if (calls.Count == 0)
            {
                //Console.WriteLine("[!] No calls found!");
                //		Console.ReadLine();
                return;
            }

            //   Console.WriteLine("[!] Calli Total Calls: {0}", calls.Count);

            foreach (CallInfo call in calls)
            {
                call.References.AddRange(FindReferences(call));
            }

            int replaced = 0;

            foreach (CallInfo call in calls)
            {
                foreach (CallRef reference in call.References)
                {
                    if (reference.ParentMethod.MDToken.ToInt32() == 0x06000260)
                    {
                    }
                    int instIndex = reference.ParentMethod.Body.Instructions.IndexOf(reference.CalliInst);
                    if (instIndex == -1)
                    {
                        continue;
                    }

                    // Nop the above 3 insts
                    var fieldCalli = reference.ParentMethod.Body.Instructions[instIndex - 3].Operand as FieldDef;
                    if (fieldCalli != fieldDef)
                    {
                        continue;
                    }
                    for (int i = 1; i <= 3; i++)
                    {
                        reference.ParentMethod.Body.Instructions[instIndex - i].OpCode  = OpCodes.Nop;
                        reference.ParentMethod.Body.Instructions[instIndex - i].Operand = null;
                    }
                    reference.ParentMethod.Body.Instructions[instIndex].OpCode  = OpCodes.Call;
                    reference.ParentMethod.Body.Instructions[instIndex].Operand = ModuleDefMD.Import(call.TargetMethod);
                    replaced++;
                }
            }

            //   Console.WriteLine("[!] Calli Total Replaced: {0}", replaced);
            return;
        }
示例#8
0
        public static bool InjectEazVM(ModuleDefMD Module, string Pathh)
        {
            bool injected = false;

            TypeDef[] array = Module.Types.ToArray <TypeDef>();
            for (int i = 0; i < array.Length; i++)
            {
                foreach (MethodDef method in array[i].Methods.ToArray <MethodDef>())
                {
                    bool flag = method.HasBody && method.Body.HasInstructions && method.Body.Instructions.Count() >= 15 && !method.FullName.Contains("My.") && !method.FullName.Contains(".My") && !method.IsConstructor && !method.DeclaringType.IsGlobalModuleType;
                    if (flag)
                    {
                        for (int j = 0; j < method.Body.Instructions.Count - 1; j++)
                        {
                            if (method.Body.Instructions[j].OpCode == OpCodes.Callvirt)
                            {
                                if (j <= 4)
                                {
                                    continue;
                                }
                                if (method.Body.Instructions[j - 1].OpCode == OpCodes.Ldarg_3 || method.Body.Instructions[j - 1].OpCode == OpCodes.Ldarg_2)
                                {
                                    if (method.Body.Instructions[j - 2].OpCode == OpCodes.Ldarg_2 || method.Body.Instructions[j - 2].OpCode == OpCodes.Ldarg_1)
                                    {
                                        if (method.Body.Instructions[j - 3].OpCode == OpCodes.Ldarg_1 || method.Body.Instructions[j - 3].OpCode == OpCodes.Ldarg_0)
                                        {
                                            Importer importer = new Importer(Module);
                                            IMethod  Method;
                                            Method = importer.Import(typeof(Venturi77CallHijacker.Handler).GetMethod("HandleInvoke"));
                                            method.Body.Instructions[j].Operand = Module.Import(Method);
                                            method.Body.Instructions[j].OpCode  = OpCodes.Call;
                                            injected = true;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            if (!injected)
            {
                return(injected);
            }
            ModuleWriterOptions moduleWriterOptions = new ModuleWriterOptions(Module);

            moduleWriterOptions.MetadataOptions.Flags = MetadataFlags.KeepOldMaxStack;
            moduleWriterOptions.Logger = DummyLogger.NoThrowInstance;
            moduleWriterOptions.MetadataOptions.Flags = MetadataFlags.PreserveAll;
            moduleWriterOptions.MetadataOptions.PreserveHeapOrder(Module, true);
            moduleWriterOptions.Cor20HeaderOptions.Flags = new ComImageFlags?(ComImageFlags.ILOnly | ComImageFlags.Bit32Required);
            Module.Write(Pathh + "_Injected.exe", moduleWriterOptions);
            File.Copy("Venturi77CallHijacker.dll", Path.GetDirectoryName(Pathh) + "\\Venturi77CallHijacker.dll");
            File.Copy("Newtonsoft.Json.dll", Path.GetDirectoryName(Pathh) + "\\Newtonsoft.Json.dll");
            return(injected);
        }
示例#9
0
        public void Inject(ModuleDefMD module)
        {
            MethodDefUser decode = new MethodDefUser("Decode", MethodSig.CreateStatic(module.CorLibTypes.String, module.CorLibTypes.String), MethodImplAttributes.IL | MethodImplAttributes.Managed, MethodAttributes.Public | MethodAttributes.Static | MethodAttributes.HideBySig | MethodAttributes.ReuseSlot);

            module.GlobalType.Methods.Add(decode);
            CilBody body = new CilBody();

            decode.Body = body;

            body.Instructions.Add(OpCodes.Nop.ToInstruction());
            body.Instructions.Add(OpCodes.Call.ToInstruction(module.Import(typeof(System.Text.Encoding).GetMethod("get_UTF8", new Type[] { }))));
            body.Instructions.Add(OpCodes.Ldarg_0.ToInstruction());
            body.Instructions.Add(OpCodes.Call.ToInstruction(module.Import(typeof(System.Convert).GetMethod("FromBase64String", new Type[] { typeof(string) }))));
            body.Instructions.Add(OpCodes.Callvirt.ToInstruction(module.Import(typeof(System.Text.Encoding).GetMethod("GetString", new Type[] { typeof(byte[]) }))));
            body.Instructions.Add(OpCodes.Ret.ToInstruction());

            foreach (TypeDef type in module.Types)
            {
                if (type.Name != "Resources" || type.Name != "Settings")
                {
                    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)
                            {
                                method.Body.Instructions[i].Operand = Convert.ToBase64String(UTF8Encoding.UTF8.GetBytes(method.Body.Instructions[i].Operand.ToString()));
                                method.Body.Instructions.Insert(i + 1, new Instruction(OpCodes.Call, decode));
                                i += 1;
                            }
                        }
                        method.Body.SimplifyBranches();
                        method.Body.OptimizeBranches();
                    }
                }
            }
        }
示例#10
0
        internal IMethod FindMethod(string fullName)
        {
            foreach (var module in Module.Assembly.Modules)
            {
                foreach (var type in module.GetTypes())
                {
                    foreach (var method in type.Methods)
                    {
                        if (string.Equals(method.FullName, fullName, StringComparison.InvariantCultureIgnoreCase))
                        {
                            return(method);
                        }
                    }
                }
            }

            LoadCustomModule(ref fullName, out ModuleDefMD customModule);

            foreach (var module in customModule.Assembly.Modules)
            {
                foreach (var type in module.GetTypes())
                {
                    foreach (var method in type.Methods)
                    {
                        if (string.Equals(method.FullName, fullName, StringComparison.InvariantCultureIgnoreCase))
                        {
                            return(Module.Import(method));
                        }
                    }
                }
            }

            throw new PatcherException("Method not found", fullName);
        }
示例#11
0
        public static bool FindField(ModuleDefMD module)
        {
            TypeDef type = module.GlobalType;

            foreach (FieldDef fld in type.Fields)
            {
                if (fld.FieldType.ReflectionFullName == module.Import(typeof(Assembly)).ToTypeSig().ReflectionFullName)
                {
                    return(true);
                }
            }
            return(false);
        }
示例#12
0
        public static Instruction CallHelperMethodInstruction(ModuleDefMD mod, TypeDef helperClass, string methodName)
        {
            MemberRef methodRef = new MemberRefUser(
                mod,
                methodName,
                MethodSig.CreateStatic(mod.CorLibTypes.Void),
                helperClass
                );

            IMethod importedMethodRef = mod.Import(methodRef);

            return(OpCodes.Call.ToInstruction(importedMethodRef));
        }
示例#13
0
        //Try to find a Proxy meth of Anti-Debug. Can't work if RefProxy is not enabled....
        public static bool TryFindAntiDebug(ModuleDefMD module)
        {
            TypeDef type = module.GlobalType;

            foreach (MethodDef method in type.Methods)
            {
                if (method.ReturnType.ReflectionFullName == module.Import(typeof(System.Threading.Thread)).ToTypeSig().ReflectionFullName)
                {
                    if (method.MethodSig.Params.Count == 1 && method.MethodSig.Params[0].ToString().Contains("ParameterizedThreadStart"))
                    {
                        return(true);
                    }
                }
            }
            return(false);
        }
示例#14
0
        //Try to find a Proxy meth of Anti-Dump. Can't work if RefProxy is not enabled....
        public static bool TryFindAntiDump(ModuleDefMD module)
        {
            TypeDef type = module.GlobalType;

            foreach (MethodDef method in type.Methods)
            {
                if (method.ReturnType.ReflectionFullName == module.Import(typeof(Type)).ToTypeSig().ReflectionFullName)
                {
                    if (method.MethodSig.Params.Count == 1 && method.MethodSig.Params[0].ToString().Contains("RuntimeTypeHandle"))
                    {
                        return(true);
                    }
                }
            }
            return(false);
        }
示例#15
0
        //Try to find a Proxy meth of Resources decryption. Works even without proxy
        public static bool TryGetResource(ModuleDefMD module)
        {
            TypeDef type = module.GlobalType;

            foreach (MethodDef method in type.Methods)
            {
                if (method.ReturnType.ReflectionFullName == module.Import(typeof(Assembly)).ToTypeSig().ReflectionFullName)
                {
                    if (method.MethodSig.Params.Count == 2 && method.MethodSig.Params[0].ToString().Contains("Object") && method.MethodSig.Params[1].ToString().Contains("ResolveEventArgs"))
                    {
                        //Extra check to strengthen result
                        return(FindField(module));
                    }
                }
            }
            return(false);
        }
示例#16
0
        public void Apply()
        {
            string assemblyCSharp         = Path.Combine(subnauticaManagedPath, GAME_ASSEMBLY_NAME);
            string nitroxPatcherPath      = Path.Combine(subnauticaManagedPath, NITROX_ASSEMBLY_NAME);
            string modifiedAssemblyCSharp = Path.Combine(subnauticaManagedPath, GAME_ASSEMBLY_MODIFIED_NAME);

            if (File.Exists(modifiedAssemblyCSharp))
            {
                File.Delete(modifiedAssemblyCSharp);
            }

            using (ModuleDefMD module = ModuleDefMD.Load(assemblyCSharp))
                using (ModuleDefMD nitroxPatcherAssembly = ModuleDefMD.Load(nitroxPatcherPath))
                {
                    TypeDef   nitroxMainDefinition    = nitroxPatcherAssembly.GetTypes().FirstOrDefault(x => x.Name == NITROX_ENTRY_TYPE_NAME);
                    MethodDef executeMethodDefinition = nitroxMainDefinition.Methods.FirstOrDefault(x => x.Name == NITROX_ENTRY_METHOD_NAME);

                    MemberRef executeMethodReference = module.Import(executeMethodDefinition);

                    TypeDef   gameInputType = module.GetTypes().First(x => x.FullName == GAME_INPUT_TYPE_NAME);
                    MethodDef awakeMethod   = gameInputType.Methods.First(x => x.Name == GAME_INPUT_METHOD_NAME);

                    Instruction callNitroxExecuteInstruction = OpCodes.Call.ToInstruction(executeMethodReference);

                    awakeMethod.Body.Instructions.Insert(0, callNitroxExecuteInstruction);
                    module.Write(modifiedAssemblyCSharp);
                }

            // The assembly might be used by other code or some other program might work in it. Retry to be on the safe side.
            Exception error = RetryWait(() => File.Delete(assemblyCSharp), 100, 5);

            if (error != null)
            {
                throw error;
            }
            File.Move(modifiedAssemblyCSharp, assemblyCSharp);
        }
示例#17
0
 public string FindModePacker(ModuleDefMD module)
 {
     foreach (TypeDef type in module.Types)
     {
         foreach (MethodDef method in type.Methods.Where(m => m.HasBody && m.Body.HasInstructions))
         {
             if (method.MethodSig.RetType.ReflectionFullName == module.Import(typeof(GCHandle)).ToTypeSig().ReflectionFullName)
             {
                 if (method.MethodSig.Params.Count == 2 && method.MethodSig.Params[0].ToString().Contains("UInt32[]") && method.MethodSig.Params[1].ToString().Contains("UInt32"))
                 {
                     if (method.Body.Variables.Count >= 14)
                     {
                         return("Dynamic");
                     }
                     else
                     {
                         return("Normal");
                     }
                 }
             }
         }
     }
     return("Not Found");
 }
示例#18
0
        void AntiDebug(ref ModuleDefMD moduleDef, string folderPathFile)
        {
            int skipFirstInvoke = 0;

            foreach (var type in moduleDef.Types)
            {
                foreach (var method in type.Methods)
                {
                    if (method.Parameters.Count == 3 && method.Parameters[1].Type.TypeName == "MethodBase" && method.Parameters[2].Type.TypeName == "Boolean")
                    {
                        for (int i = 0; i < method.Body.Instructions.Count; i++)
                        {
                            if (method.Body.Instructions[i].Operand?.ToString().Contains("Invoke") ?? false)
                            {
                                if (skipFirstInvoke++ == 1)
                                {
                                    var indexInvoke     = method.Body.Instructions.IndexOf(method.Body.Instructions[i]);
                                    var lastInstruction = method.Body.Instructions[indexInvoke + 2]; // stub, will be reinitialized later

                                    Local getLocal;

                                    if (method.Body.Instructions[indexInvoke + 1].IsStloc())
                                    {
                                        if (method.Body.Instructions[indexInvoke + 1].OpCode == OpCodes.Stloc_0)
                                        {
                                            getLocal = method.Body.Variables.Locals[0];
                                        }
                                        else if (method.Body.Instructions[indexInvoke + 1].OpCode == OpCodes.Stloc_1)
                                        {
                                            getLocal = method.Body.Variables.Locals[1];
                                        }
                                        else if (method.Body.Instructions[indexInvoke + 1].OpCode == OpCodes.Stloc_2)
                                        {
                                            getLocal = method.Body.Variables.Locals[2];
                                        }
                                        else if (method.Body.Instructions[indexInvoke + 1].OpCode == OpCodes.Stloc_3)
                                        {
                                            getLocal = method.Body.Variables.Locals[3];
                                        }
                                        else
                                        {
                                            getLocal = method.Body.Instructions[indexInvoke + 1].GetLocal(null);
                                        }
                                    }
                                    else if (method.Body.Instructions[indexInvoke + 3].OpCode == OpCodes.Stloc_S)
                                    {
                                        getLocal     = method.Body.Instructions[indexInvoke + 3].GetLocal(null);
                                        indexInvoke += 2;
                                    }
                                    else
                                    {
                                        getLocal     = method.Body.Instructions[indexInvoke + 5].GetLocal(null); // skip VMP-mutations
                                        indexInvoke += 4;
                                    }

                                    // ### CRC-Check ###
                                    Console.WriteLine("CRC-check bypassing...");
                                    int     indexPreInvoke = indexInvoke;
                                    Local   getLocalObjectInvokeArgs;
                                    dynamic opcodeLdlocS;
                                    while (true)
                                    {
                                        if (method.Body.Instructions[indexPreInvoke].IsLdloc())
                                        {
                                            opcodeLdlocS = method.Body.Instructions[indexPreInvoke].Operand;
                                            if (opcodeLdlocS.Type?.FullName == "System.Object[]")
                                            {
                                                getLocalObjectInvokeArgs = method.Body.Variables[opcodeLdlocS.Index];
                                                break;
                                            }
                                        }
                                        indexPreInvoke--;
                                    }
                                    while (true)
                                    {
                                        if (method.Body.Instructions[indexPreInvoke].IsLdarg())
                                        {
                                            method.Body.Instructions.Insert(indexPreInvoke + 1, Instruction.Create(OpCodes.Callvirt, moduleDef.Import(typeof(System.Reflection.MemberInfo).GetMethod("get_Name", new Type[] { }))));
                                            method.Body.Instructions.Insert(indexPreInvoke + 2, Instruction.Create(OpCodes.Ldstr, "CreateFile"));
                                            method.Body.Instructions.Insert(indexPreInvoke + 3, Instruction.Create(OpCodes.Call, moduleDef.Import(typeof(System.String).GetMethod("op_Equality", new Type[] { typeof(string), typeof(string) }))));
                                            method.Body.Instructions.Insert(indexPreInvoke + 4, Instruction.Create(OpCodes.Brfalse_S, lastInstruction));
                                            method.Body.Instructions.Insert(indexPreInvoke + 5, Instruction.Create(OpCodes.Ldloc_S, getLocalObjectInvokeArgs));
                                            method.Body.Instructions.Insert(indexPreInvoke + 6, Instruction.Create(OpCodes.Ldc_I4_0));
                                            method.Body.Instructions.Insert(indexPreInvoke + 7, Instruction.Create(OpCodes.Ldstr, folderPathFile));
                                            method.Body.Instructions.Insert(indexPreInvoke + 8, Instruction.Create(OpCodes.Stelem_Ref));
                                            method.Body.Instructions.Insert(indexPreInvoke + 9, Instruction.Create(OpCodes.Ldarg_1));
                                            indexInvoke += 9;
                                            break;
                                        }
                                        indexPreInvoke--;
                                    }


                                    Console.WriteLine("Anti-debug bypassing...");
                                    // ### NtQueryInformationProcess ###
                                    method.Body.Instructions.Insert(indexInvoke + 2, Instruction.Create(OpCodes.Ldarg_1));
                                    method.Body.Instructions.Insert(indexInvoke + 3, Instruction.Create(OpCodes.Callvirt, moduleDef.Import(typeof(System.Reflection.MemberInfo).GetMethod("get_Name", new Type[] { }))));
                                    method.Body.Instructions.Insert(indexInvoke + 4, Instruction.Create(OpCodes.Ldstr, "NtQueryInformationProcess"));
                                    method.Body.Instructions.Insert(indexInvoke + 5, Instruction.Create(OpCodes.Call, moduleDef.Import(typeof(System.String).GetMethod("op_Equality", new Type[] { typeof(string), typeof(string) }))));
                                    method.Body.Instructions.Insert(indexInvoke + 6, Instruction.Create(OpCodes.Brfalse_S, lastInstruction));
                                    method.Body.Instructions.Insert(indexInvoke + 7, Instruction.Create(OpCodes.Ldc_I4_1));
                                    method.Body.Instructions.Insert(indexInvoke + 8, Instruction.Create(OpCodes.Box, moduleDef.Import(typeof(System.Int32))));
                                    method.Body.Instructions.Insert(indexInvoke + 9, Instruction.Create(OpCodes.Stloc_S, getLocal));

                                    // ### is_Attached ###
                                    method.Body.Instructions.Insert(indexInvoke + 10, Instruction.Create(OpCodes.Ldarg_1));
                                    method.Body.Instructions.Insert(indexInvoke + 11, Instruction.Create(OpCodes.Callvirt, moduleDef.Import(typeof(System.Reflection.MemberInfo).GetMethod("get_Name", new Type[] { }))));
                                    method.Body.Instructions.Insert(indexInvoke + 12, Instruction.Create(OpCodes.Ldstr, "get_IsAttached"));
                                    method.Body.Instructions.Insert(indexInvoke + 13, Instruction.Create(OpCodes.Call, moduleDef.Import(typeof(System.String).GetMethod("op_Equality", new Type[] { typeof(string), typeof(string) }))));
                                    method.Body.Instructions.Insert(indexInvoke + 14, Instruction.Create(OpCodes.Brfalse_S, lastInstruction));
                                    method.Body.Instructions.Insert(indexInvoke + 15, Instruction.Create(OpCodes.Ldc_I4_0));
                                    method.Body.Instructions.Insert(indexInvoke + 16, Instruction.Create(OpCodes.Box, moduleDef.Import(typeof(System.Boolean))));
                                    method.Body.Instructions.Insert(indexInvoke + 17, Instruction.Create(OpCodes.Stloc_S, getLocal));

                                    // ### IsLogging ###
                                    method.Body.Instructions.Insert(indexInvoke + 18, Instruction.Create(OpCodes.Ldarg_1));
                                    method.Body.Instructions.Insert(indexInvoke + 19, Instruction.Create(OpCodes.Callvirt, moduleDef.Import(typeof(System.Reflection.MemberInfo).GetMethod("get_Name", new Type[] { }))));
                                    method.Body.Instructions.Insert(indexInvoke + 20, Instruction.Create(OpCodes.Ldstr, "IsLogging"));
                                    method.Body.Instructions.Insert(indexInvoke + 21, Instruction.Create(OpCodes.Call, moduleDef.Import(typeof(System.String).GetMethod("op_Equality", new Type[] { typeof(string), typeof(string) }))));
                                    method.Body.Instructions.Insert(indexInvoke + 22, Instruction.Create(OpCodes.Brfalse_S, lastInstruction));
                                    method.Body.Instructions.Insert(indexInvoke + 23, Instruction.Create(OpCodes.Ldc_I4_0));
                                    method.Body.Instructions.Insert(indexInvoke + 24, Instruction.Create(OpCodes.Box, moduleDef.Import(typeof(System.Boolean))));
                                    method.Body.Instructions.Insert(indexInvoke + 25, Instruction.Create(OpCodes.Stloc_S, getLocal));
                                    // ### IsDebuggerPresent ###
                                    method.Body.Instructions.Insert(indexInvoke + 26, Instruction.Create(OpCodes.Ldarg_1));
                                    method.Body.Instructions.Insert(indexInvoke + 27, Instruction.Create(OpCodes.Callvirt, moduleDef.Import(typeof(System.Reflection.MemberInfo).GetMethod("get_Name", new Type[] { }))));
                                    method.Body.Instructions.Insert(indexInvoke + 28, Instruction.Create(OpCodes.Ldstr, "IsDebuggerPresent"));
                                    method.Body.Instructions.Insert(indexInvoke + 29, Instruction.Create(OpCodes.Call, moduleDef.Import(typeof(System.String).GetMethod("op_Equality", new Type[] { typeof(string), typeof(string) }))));
                                    method.Body.Instructions.Insert(indexInvoke + 30, Instruction.Create(OpCodes.Brfalse_S, lastInstruction));
                                    method.Body.Instructions.Insert(indexInvoke + 31, Instruction.Create(OpCodes.Ldc_I4_0));
                                    method.Body.Instructions.Insert(indexInvoke + 32, Instruction.Create(OpCodes.Box, moduleDef.Import(typeof(System.Boolean))));
                                    method.Body.Instructions.Insert(indexInvoke + 33, Instruction.Create(OpCodes.Stloc_S, getLocal));

                                    // ### CheckRemoteDebuggerPresent ###
                                    method.Body.Instructions.Insert(indexInvoke + 34, Instruction.Create(OpCodes.Ldarg_1));
                                    method.Body.Instructions.Insert(indexInvoke + 35, Instruction.Create(OpCodes.Callvirt, moduleDef.Import(typeof(System.Reflection.MemberInfo).GetMethod("get_Name", new Type[] { }))));
                                    method.Body.Instructions.Insert(indexInvoke + 36, Instruction.Create(OpCodes.Ldstr, "CheckRemoteDebuggerPresent"));
                                    method.Body.Instructions.Insert(indexInvoke + 37, Instruction.Create(OpCodes.Call, moduleDef.Import(typeof(System.String).GetMethod("op_Equality", new Type[] { typeof(string), typeof(string) }))));
                                    method.Body.Instructions.Insert(indexInvoke + 38, Instruction.Create(OpCodes.Brfalse_S, lastInstruction));
                                    method.Body.Instructions.Insert(indexInvoke + 39, Instruction.Create(OpCodes.Ldc_I4_0));
                                    method.Body.Instructions.Insert(indexInvoke + 40, Instruction.Create(OpCodes.Box, moduleDef.Import(typeof(System.Boolean))));
                                    method.Body.Instructions.Insert(indexInvoke + 41, Instruction.Create(OpCodes.Stloc_S, getLocal));


                                    var invoke = (MemberRef)method.Body.Instructions[indexInvoke].Operand;

                                    method.Body.UpdateInstructionOffsets(); // update offsets

                                    if (invoke.GetParamCount() == 5)        // new version VMP (build 1261)
                                    {
                                        // lastInstruction = this pointer, when need jump
                                        lastInstruction = method.Body.Instructions[indexInvoke - 6];                                         // On Ldarg.1
                                        method.Body.Instructions[indexInvoke - 11] = Instruction.Create(OpCodes.Brfalse_S, lastInstruction); // create Instruction
                                    }
                                    else // old version VMP (build 1213)
                                    {
                                        // lastInstruction = this pointer, when need jump
                                        lastInstruction = method.Body.Instructions[indexInvoke - 3];                                        // On Ldarg.1
                                        method.Body.Instructions[indexInvoke - 8] = Instruction.Create(OpCodes.Brfalse_S, lastInstruction); // create Instruction
                                    }

                                    lastInstruction = method.Body.Instructions[indexInvoke + 10];
                                    method.Body.Instructions[indexInvoke + 6] = Instruction.Create(OpCodes.Brfalse_S, lastInstruction);

                                    lastInstruction = method.Body.Instructions[indexInvoke + 18];
                                    method.Body.Instructions[indexInvoke + 14] = Instruction.Create(OpCodes.Brfalse_S, lastInstruction);

                                    lastInstruction = method.Body.Instructions[indexInvoke + 26];
                                    method.Body.Instructions[indexInvoke + 22] = Instruction.Create(OpCodes.Brfalse_S, lastInstruction);

                                    lastInstruction = method.Body.Instructions[indexInvoke + 34];
                                    method.Body.Instructions[indexInvoke + 30] = Instruction.Create(OpCodes.Brfalse_S, lastInstruction);

                                    lastInstruction = method.Body.Instructions[indexInvoke + 42];
                                    method.Body.Instructions[indexInvoke + 38] = Instruction.Create(OpCodes.Brfalse_S, lastInstruction);


                                    i += 20;
                                }
                            }
                        }
                    }
                }
            }
        }
示例#19
0
        public static bool InjectKoiVM(ModuleDefMD Module, string Pathh)
        {
            bool injected = false;

            TypeDef[] array = Module.Types.ToArray <TypeDef>();
            for (int i = 0; i < array.Length; i++)
            {
                foreach (MethodDef method in array[i].Methods.ToArray <MethodDef>())
                {
                    bool flag = method.HasBody && method.Body.HasInstructions && !method.FullName.Contains("My.") && !method.FullName.Contains(".My") && !method.IsConstructor && !method.DeclaringType.IsGlobalModuleType;
                    if (flag)
                    {
                        for (int j = 0; j < method.Body.Instructions.Count - 1; j++)
                        {
                            if (method.Body.Instructions[j].OpCode == OpCodes.Ldarg_2)
                            {
                                if (method.Body.Instructions[j + 1].OpCode == OpCodes.Ldloc_2)
                                {
                                    if (method.Body.Instructions[j + 2].OpCode == OpCodes.Ldloc_3)
                                    {
                                        if (method.Body.Instructions[j + 3].OpCode == OpCodes.Callvirt)
                                        {
                                            if (method.Body.Instructions[j + 4].OpCode == OpCodes.Stloc_S)
                                            {
                                                method.Body.Instructions[j + 3].OpCode = OpCodes.Call;
                                                Importer importer = new Importer(Module);
                                                IMethod  Method;
                                                Method = importer.Import(typeof(Venturi77CallHijacker.Handler).GetMethod("HandleInvoke"));
                                                method.Body.Instructions[j + 3].Operand = Module.Import(Method);
                                                injected = true;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            if (!injected)
            {
                return(injected);
            }
            ModuleWriterOptions nativeModuleWriterOptions = new ModuleWriterOptions(Module);

            nativeModuleWriterOptions.MetadataOptions.Flags = MetadataFlags.KeepOldMaxStack;
            nativeModuleWriterOptions.Logger = DummyLogger.NoThrowInstance;
            nativeModuleWriterOptions.MetadataOptions.Flags    = MetadataFlags.PreserveAll;
            nativeModuleWriterOptions.Cor20HeaderOptions.Flags = new ComImageFlags?(ComImageFlags.ILOnly);
            var otherstrteams = Module.Metadata.AllStreams.Where(a => a.GetType() == typeof(DotNetStream));

            nativeModuleWriterOptions.MetadataOptions.PreserveHeapOrder(Module, addCustomHeaps: true);
            Module.Write(Path.Combine(Path.GetDirectoryName(Pathh), Path.GetFileNameWithoutExtension(Pathh) + "_Injected" + ".exe"), nativeModuleWriterOptions);
            File.Copy("Venturi77CallHijacker.dll", Path.GetDirectoryName(Pathh) + "\\Venturi77CallHijacker.dll");
            File.Copy("Newtonsoft.Json.dll", Path.GetDirectoryName(Pathh) + "\\Newtonsoft.Json.dll");
            return(injected);
        }
        public static void InjectForlaxerEaz(string path, int pick)
        {
            ModuleDefMD md = ModuleDefMD.Load(path);

            foreach (TypeDef type in md.Types)
            {
                foreach (MethodDef method in type.Methods)
                {
                    if (method.HasBody && method.Body.HasInstructions && method.Body.Instructions.Count() < 200)
                    {
                        for (int i = 0; i < method.Body.Instructions.Count(); i++)
                        {
                            if (method.Body.Instructions[i].OpCode == OpCodes.Callvirt)
                            {
                                string operand = method.Body.Instructions[i].Operand.ToString();
                                if (operand.Contains("System.Object System.Reflection.MethodBase::Invoke(System.Object,System.Object[])") && method.Body.Instructions[i - 1].IsLdarg() && method.Body.Instructions[i - 2].IsLdarg() && method.Body.Instructions[i - 3].IsLdarg())
                                {
                                    MDToken var = method.MDToken;
                                    Colorful.Console.Write("[INFO]     ", Color.Purple);
                                    Colorful.Console.Write("Invoke MDToken: " + var.Raw.ToString());
                                    method.Body.Instructions[i].OpCode = OpCodes.Nop;
                                    Importer importer = new Importer(md);
                                    IMethod  myMethod;
                                    if (pick == 1)
                                    {
                                        myMethod = importer.Import(typeof(Forlaxer.Forlaxer).GetMethod("dbgInvokeHandler"));
                                    }
                                    else
                                    {
                                        myMethod = importer.Import(typeof(Forlaxer.Forlaxer).GetMethod("InvokeHandler"));
                                    }
                                    method.Body.Instructions.Insert(i + 1, new Instruction(OpCodes.Call, md.Import(myMethod)));
                                    i += 1;
                                    success("Forlaxer Hooked Succesfully!");
                                }
                            }
                        }
                    }
                }
            }
            BLOCK1:
            ModuleWriterOptions moduleWriterOptions = new ModuleWriterOptions(md);

            moduleWriterOptions.MetadataOptions.Flags = MetadataFlags.KeepOldMaxStack;
            moduleWriterOptions.Logger = DummyLogger.NoThrowInstance;
            moduleWriterOptions.MetadataOptions.Flags = MetadataFlags.PreserveAll;
            moduleWriterOptions.MetadataOptions.PreserveHeapOrder(md, true);
            moduleWriterOptions.Cor20HeaderOptions.Flags = new ComImageFlags?(ComImageFlags.ILOnly | ComImageFlags.Bit32Required);
            md.Write(path + "_Hooked_.exe", moduleWriterOptions);
        }
示例#21
0
        private void AntiVMInit(ref ModuleDefMD moduleDefMD)
        {
            foreach (var type in moduleDefMD.Types)
            {
                // Bypass EnumSystemFirmwareTables()
                if (type.Methods.Count == 1 || type.Fields.Count == 5)
                {
                    foreach (var method in type.Methods)
                    {
                        if (method.HasBody)
                        {
                            var countLdcI4_1 = 0;
                            foreach (var instruction in method.Body.Instructions)
                            {
                                // Bypass EnumSystemFirmwareTables()
                                if (instruction.OpCode.Code == Code.Ldc_I4_1) // check signature (count Ldc_I4_1 == 13)
                                {
                                    countLdcI4_1++;
                                }
                                else if (instruction.IsLdcI4() && instruction.GetLdcI4Value() == 1)
                                {
                                    countLdcI4_1++;
                                }
                            }

                            if (countLdcI4_1 == 13)
                            {
                                Console.WriteLine("Bypass Anti-Virtual-Machine bypassing(EnumSystemFirmwareTables)");
                                for (var indexInstructions = 0;
                                     indexInstructions < method.Body.Instructions.Count - 2;
                                     indexInstructions++)
                                {
                                    method.Body.Instructions[indexInstructions] = Instruction.Create(OpCodes.Nop);
                                }

                                method.Body.Instructions[method.Body.Instructions.Count - 2] =
                                    Instruction.Create(OpCodes.Ldc_I4, 0);
                            }
                        }
                    }
                }
                // Bypass CPUID 0x40000000 && 0x40000010
                if (type.Fields.Count == 2 && type.Methods.Count == 2)
                {
                    foreach (var method in type.Methods)
                    {
                        if (method.HasBody)
                        {
                            for (int indexInstructions = 0; indexInstructions < method.Body.Instructions.Count; indexInstructions++)
                            {
                                if (method.Body.Instructions[indexInstructions].OpCode == OpCodes.Ldtoken &&
                                    method.Body.Instructions[indexInstructions + 3].OpCode == OpCodes.Castclass &&
                                    method.Body.Instructions[indexInstructions + 6].OpCode == OpCodes.Initobj)
                                {
                                    Console.WriteLine("Bypass CPUID 0x40000000 && 0x40000010");
                                    method.Body.Instructions[0]  = new Instruction(OpCodes.Ldc_I4_4);
                                    method.Body.Instructions[1]  = new Instruction(OpCodes.Newarr, moduleDefMD.Import(typeof(System.Int32)));
                                    method.Body.Instructions[2]  = new Instruction(OpCodes.Dup);
                                    method.Body.Instructions[3]  = new Instruction(OpCodes.Ldc_I4_0);
                                    method.Body.Instructions[4]  = new Instruction(OpCodes.Ldc_I4, 0x206A7);
                                    method.Body.Instructions[5]  = new Instruction(OpCodes.Stelem_I4);
                                    method.Body.Instructions[6]  = new Instruction(OpCodes.Dup);
                                    method.Body.Instructions[7]  = new Instruction(OpCodes.Ldc_I4_1);
                                    method.Body.Instructions[8]  = new Instruction(OpCodes.Ldc_I4, 0x3100800);
                                    method.Body.Instructions[9]  = new Instruction(OpCodes.Stelem_I4);
                                    method.Body.Instructions[10] = new Instruction(OpCodes.Dup);
                                    method.Body.Instructions[11] = new Instruction(OpCodes.Ldc_I4_2);
                                    method.Body.Instructions[12] = new Instruction(OpCodes.Ldc_I4, 0x1F9AE3BF);
                                    method.Body.Instructions[13] = new Instruction(OpCodes.Stelem_I4);
                                    method.Body.Instructions[14] = new Instruction(OpCodes.Dup);
                                    method.Body.Instructions[15] = new Instruction(OpCodes.Ldc_I4_3);
                                    method.Body.Instructions[16] = new Instruction(OpCodes.Ldc_I4, -0x40140401);
                                    method.Body.Instructions[17] = new Instruction(OpCodes.Stelem_I4);
                                    method.Body.Instructions[18] = new Instruction(OpCodes.Ret);
                                    for (int indexCleaningInstruction = 19; indexCleaningInstruction < method.Body.Instructions.Count;)
                                    {
                                        if (method.Body.Instructions[indexCleaningInstruction] != null)
                                        {
                                            method.Body.Instructions.RemoveAt(indexCleaningInstruction);
                                        }
                                    }

                                    for (int exceptionIterator = method.Body.ExceptionHandlers.Count - 1;
                                         exceptionIterator >= 0;
                                         exceptionIterator--)
                                    {
                                        method.Body.ExceptionHandlers.RemoveAt(exceptionIterator);
                                    }
                                    method.Body.OptimizeBranches();
                                    method.Body.UpdateInstructionOffsets();
                                    break;
                                }
                            }
                        }
                    }
                }
            }
        }
        public static void Publicize(string input, string output = null)
        {
            output ??= DefaultOutputDir + Path.DirectorySeparatorChar;
            if (string.IsNullOrEmpty(Path.GetFileName(output)))
            {
                output = Path.Combine(output, Path.GetFileNameWithoutExtension(input) + Suffix + Path.GetExtension(input));
            }

            if (!File.Exists(input))
            {
                Console.WriteLine();
                Console.WriteLine("ERROR! File doesn't exist or you don't have sufficient permissions.");
                Environment.Exit(30);
            }

            ModuleDefMD module = null;

            try
            {
                module = ModuleDefMD.Load(input, ModuleDef.CreateModuleContext());
            }
            catch (Exception e)
            {
                Console.WriteLine();
                Console.WriteLine("ERROR! Cannot read the assembly. Please check your permissions.");
                Console.WriteLine(e);
                Environment.Exit(40);
            }

            var runtimeVisibilityAttribute = new TypeDefUser("RuntimeVisibilityAttribute", module.Import(typeof(Attribute)))
            {
                Attributes = TypeAttributes.Class & TypeAttributes.Public
            };

            module.Types.Add(runtimeVisibilityAttribute);

            runtimeVisibilityAttribute.Methods.Add(new MethodDefUser(
                                                       ".ctor",
                                                       MethodSig.CreateInstance(module.CorLibTypes.Void, module.CorLibTypes.String),
                                                       MethodImplAttributes.Managed & MethodImplAttributes.IL,
                                                       MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName)
            {
                ParamDefs = { new ParamDefUser("visibility") }
            }
                                                   );

            var allTypes = module.GetTypes().ToList();

            var types   = 0;
            var methods = 0;
            var fields  = 0;

            foreach (var type in allTypes)
            {
                foreach (var method in type.Methods)
                {
                    if (method.IsPublic)
                    {
                        continue;
                    }

                    methods++;
                    method.CustomAttributes.Add(
                        new CustomAttribute(runtimeVisibilityAttribute.FindConstructors().Single(),
                                            new[]
                    {
                        new CAArgument(module.CorLibTypes.String, method.Access.ToString())
                    })
                        );
                    method.Access = MethodAttributes.Public;
                }

                foreach (var field in type.Fields)
                {
                    if (field.IsPublic)
                    {
                        continue;
                    }

                    fields++;
                    field.CustomAttributes.Add(
                        new CustomAttribute(runtimeVisibilityAttribute.FindConstructors().Single(),
                                            new[]
                    {
                        new CAArgument(module.CorLibTypes.String, field.Access.ToString())
                    })
                        );
                    field.Access = FieldAttributes.Public;
                }

                if (type.IsNested ? type.IsNestedPublic : type.IsPublic)
                {
                    continue;
                }

                types++;
                type.CustomAttributes.Add(
                    new CustomAttribute(runtimeVisibilityAttribute.FindConstructors().Single(),
                                        new[]
                {
                    new CAArgument(module.CorLibTypes.String, type.Visibility.ToString())
                })
                    );
                type.Visibility = type.IsNested ? TypeAttributes.NestedPublic : TypeAttributes.Public;
            }

            const string reportString = "Changed {0} {1} to public.";

            Console.WriteLine(reportString, types, "types");
            Console.WriteLine(reportString, methods, "methods (including getters and setters)");
            Console.WriteLine(reportString, fields, "fields");

            Console.WriteLine();

            Console.WriteLine("Saving a copy of the modified assembly ...");

            try
            {
                var directory = Path.GetDirectoryName(output);
                if (!string.IsNullOrEmpty(directory))
                {
                    Directory.CreateDirectory(directory);
                }

                module.Write(output);
            }
            catch (Exception e)
            {
                Console.WriteLine();
                Console.WriteLine("ERROR! Cannot create/overwrite the new assembly. ");
                Console.WriteLine("Please check the path and its permissions " +
                                  "and in case of overwriting an existing file ensure that it isn't currently used.");
                Console.WriteLine(e);
                Environment.Exit(50);
            }

            Console.WriteLine("Completed.");
        }
示例#23
0
 public static void Execute(ModuleDefMD asm)
 {
     asm.Mvid = null;
     asm.Name = RandomString(Random.Next(90, 120), Ascii);
     asm.Import(new FieldDefUser(RandomString(Random.Next(90, 120), Ascii)));
     foreach (TypeDef typeDef in asm.Types)
     {
         foreach (MethodDef methodDef in typeDef.Methods)
         {
             bool flag = methodDef.Body == null;
             if (!flag)
             {
                 methodDef.Body.SimplifyBranches();
                 bool flag2 = methodDef.ReturnType.FullName != "System.Void" || !methodDef.HasBody || methodDef.Body.Instructions.Count == 0;
                 if (!flag2)
                 {
                     TypeSig typeSig  = asm.Import(typeof(int)).ToTypeSig();
                     Local   local    = new Local(typeSig);
                     TypeSig typeSig2 = asm.Import(typeof(bool)).ToTypeSig();
                     Local   local2   = new Local(typeSig2);
                     methodDef.Body.Variables.Add(local);
                     methodDef.Body.Variables.Add(local2);
                     Instruction operand     = methodDef.Body.Instructions[methodDef.Body.Instructions.Count - 1];
                     Instruction item        = new Instruction(OpCodes.Ret);
                     Instruction instruction = new Instruction(OpCodes.Ldc_I4_1);
                     methodDef.Body.Instructions.Insert(0, new Instruction(OpCodes.Ldc_I4_0));
                     methodDef.Body.Instructions.Insert(1, new Instruction(OpCodes.Stloc, local));
                     methodDef.Body.Instructions.Insert(2, new Instruction(OpCodes.Br, instruction));
                     Instruction instruction2 = new Instruction(OpCodes.Ldloc, local);
                     methodDef.Body.Instructions.Insert(3, instruction2);
                     methodDef.Body.Instructions.Insert(4, new Instruction(OpCodes.Ldc_I4_0));
                     methodDef.Body.Instructions.Insert(5, new Instruction(OpCodes.Ceq));
                     methodDef.Body.Instructions.Insert(6, new Instruction(OpCodes.Ldc_I4_1));
                     methodDef.Body.Instructions.Insert(7, new Instruction(OpCodes.Ceq));
                     methodDef.Body.Instructions.Insert(8, new Instruction(OpCodes.Stloc, local2));
                     methodDef.Body.Instructions.Insert(9, new Instruction(OpCodes.Ldloc, local2));
                     methodDef.Body.Instructions.Insert(10, new Instruction(OpCodes.Brtrue, methodDef.Body.Instructions[10]));
                     methodDef.Body.Instructions.Insert(11, new Instruction(OpCodes.Ret));
                     methodDef.Body.Instructions.Insert(12, new Instruction(OpCodes.Ldstr, "Scold"));
                     methodDef.Body.Instructions.Insert(13, new Instruction(OpCodes.Unbox_Any));
                     methodDef.Body.Instructions.Insert(14, new Instruction(OpCodes.Call));
                     methodDef.Body.Instructions.Insert(15, new Instruction(OpCodes.Calli));
                     methodDef.Body.Instructions.Insert(16, new Instruction(OpCodes.Callvirt));
                     methodDef.Body.Instructions.Insert(17, new Instruction(OpCodes.Sizeof));
                     methodDef.Body.Instructions.Insert(18, new Instruction(OpCodes.Unaligned, operand));
                     methodDef.Body.Instructions.Insert(methodDef.Body.Instructions.Count, instruction);
                     methodDef.Body.Instructions.Insert(methodDef.Body.Instructions.Count, new Instruction(OpCodes.Stloc, local2));
                     methodDef.Body.Instructions.Insert(methodDef.Body.Instructions.Count, new Instruction(OpCodes.Br, instruction2));
                     methodDef.Body.Instructions.Insert(methodDef.Body.Instructions.Count, item);
                     ExceptionHandler item2 = new ExceptionHandler(ExceptionHandlerType.Finally)
                     {
                         HandlerStart = methodDef.Body.Instructions[10],
                         HandlerEnd   = methodDef.Body.Instructions[11],
                         TryEnd       = methodDef.Body.Instructions[14],
                         TryStart     = methodDef.Body.Instructions[12]
                     };
                     bool flag3 = !methodDef.Body.HasExceptionHandlers;
                     if (flag3)
                     {
                         methodDef.Body.ExceptionHandlers.Add(item2);
                     }
                     methodDef.Body.OptimizeBranches();
                     methodDef.Body.OptimizeMacros();
                 }
             }
         }
     }
 }
示例#24
0
        /// <summary>
        /// Weaves the interface.
        /// What we do here is:
        /// - creating a class (which is named after the interface name)
        /// - this class implements all interface members
        /// - all members invoke Invocation.ProcessInterfaceMethod
        /// </summary>
        /// <param name="moduleDefinition">The module definition.</param>
        /// <param name="interfaceType">Type of the interface.</param>
        /// <param name="context">The context.</param>
        private void WeaveInterface(ModuleDefMD moduleDefinition, TypeDef interfaceType, WeavingContext context)
        {
            var importedInterfaceType = moduleDefinition.Import(interfaceType);

            Logging.WriteDebug("Weaving interface '{0}'", interfaceType.FullName);
            TypeDef implementationType;
            TypeDef advisedInterfaceType;

            lock (moduleDefinition)
            {
                // ensure we're creating the interface only once
                var implementationTypeName      = GetImplementationTypeName(interfaceType.Name);
                var implementationTypeNamespace = interfaceType.Namespace;
                if (moduleDefinition.GetTypes().Any(t => t.Namespace == implementationTypeNamespace && t.Name == implementationTypeName))
                {
                    return;
                }

                // now, create the implementation type
                var typeAttributes = (InjectAsPrivate ? TypeAttributes.NotPublic : TypeAttributes.Public) | TypeAttributes.Class |
                                     TypeAttributes.BeforeFieldInit;
                advisedInterfaceType = TypeResolver.Resolve(moduleDefinition, typeof(AdvisedInterface));
                // TODO: this should work using TypeImporter.Import
                var advisedInterfaceTypeReference = moduleDefinition.Import(advisedInterfaceType);
                implementationType = new TypeDefUser(implementationTypeNamespace, implementationTypeName, advisedInterfaceTypeReference)
                {
                    Attributes = typeAttributes
                };
                implementationType.Interfaces.Add(new InterfaceImplUser(importedInterfaceType));

                lock (moduleDefinition)
                    moduleDefinition.Types.Add(implementationType);
            }

            // create empty .ctor. This .NET mofo wants it!
            var baseEmptyConstructor = moduleDefinition.SafeImport(advisedInterfaceType.FindConstructors().Single());
            const MethodAttributes ctorAttributes = MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.SpecialName |
                                                    MethodAttributes.RTSpecialName;
            var method = new MethodDefUser(".ctor", baseEmptyConstructor.MethodSig, ctorAttributes);

            method.Body = new CilBody();
            method.Body.Instructions.Add(Instruction.Create(OpCodes.Ldarg_0));
            method.Body.Instructions.Add(Instruction.Create(OpCodes.Call, baseEmptyConstructor));
            method.Body.Instructions.Add(Instruction.Create(OpCodes.Ret));
            implementationType.Methods.Add(method);

            // create implementation methods
            foreach (var currentInterfaceType in interfaceType.GetAllInterfaces(TypeResolver))
            {
                foreach (var interfaceMethod in currentInterfaceType.Methods.Where(m => !m.IsSpecialName))
                {
                    WeaveInterfaceMethod(interfaceMethod, implementationType, true, context);
                }

                // create implementation properties
                foreach (var interfaceProperty in currentInterfaceType.Properties)
                {
                    var implementationProperty = new PropertyDefUser(interfaceProperty.Name, interfaceProperty.PropertySig);
                    implementationType.Properties.Add(implementationProperty);
                    if (interfaceProperty.GetMethod != null)
                    {
                        implementationProperty.GetMethod = WeaveInterfaceMethod(interfaceProperty.GetMethod, implementationType, InjectAsPrivate, context);
                    }
                    if (interfaceProperty.SetMethod != null)
                    {
                        implementationProperty.SetMethod = WeaveInterfaceMethod(interfaceProperty.SetMethod, implementationType, InjectAsPrivate, context);
                    }
                }

                // create implementation events
                foreach (var interfaceEvent in currentInterfaceType.Events)
                {
                    var implementationEvent = new EventDefUser(interfaceEvent.Name, interfaceEvent.EventType);
                    implementationType.Events.Add(implementationEvent);
                    if (interfaceEvent.AddMethod != null)
                    {
                        implementationEvent.AddMethod = WeaveInterfaceMethod(interfaceEvent.AddMethod, implementationType, InjectAsPrivate, context);
                    }
                    if (interfaceEvent.RemoveMethod != null)
                    {
                        implementationEvent.RemoveMethod = WeaveInterfaceMethod(interfaceEvent.RemoveMethod, implementationType, InjectAsPrivate, context);
                    }
                }
            }
        }
        public static void InjectForlaxerKoi(string path, byte[] koi, int pick)
        {
            ModuleDefMD md = ModuleDefMD.Load(path);

            foreach (TypeDef type in md.Types)
            {
                foreach (MethodDef method in type.Methods)
                {
                    if (method.HasBody && method.Body.HasInstructions && method.Body.Instructions.Count() > 150)
                    {
                        for (int i = 0; i < method.Body.Instructions.Count(); i++)
                        {
                            if (method.Body.Instructions[i].OpCode == OpCodes.Callvirt)
                            {
                                string operand = method.Body.Instructions[i].Operand.ToString();
                                if (operand.Contains("System.Object System.Reflection.MethodBase::Invoke(System.Object,System.Object[])") && method.Body.Instructions[i + 1].IsStloc() && method.Body.Instructions[i - 2].IsLdloc())
                                {
                                    MDToken var = method.MDToken;
                                    Colorful.Console.Write("[INFO]     ", Color.Purple);
                                    Colorful.Console.Write("Invoke MDToken: " + var.Raw.ToString());
                                    method.Body.Instructions[i].OpCode = OpCodes.Nop;
                                    Importer importer = new Importer(md);
                                    IMethod  myMethod;
                                    if (pick == 1)
                                    {
                                        myMethod = importer.Import(typeof(Forlaxer.Forlaxer).GetMethod("dbgInvokeHandler"));
                                    }
                                    else
                                    {
                                        myMethod = importer.Import(typeof(Forlaxer.Forlaxer).GetMethod("InvokeHandler"));
                                    }
                                    method.Body.Instructions.Insert(i + 1, new Instruction(OpCodes.Call, md.Import(myMethod)));
                                    i += 1;
                                    success("Forlaxer Hooked Succesfully!");
                                }
                            }
                        }
                    }
                }
            }
            BLOCK1:
            dbg("Preparing to move KoiVM Data...");
            MethodDef methodDef  = stuffs.GetMethod(md);
            MethodDef methodDef2 = stuffs.GetMethod2(md);

            try
            {
                methodDef.Body.Instructions.Clear();
            }
            catch { }

            ModuleDefMD mod        = ModuleDefMD.Load("ForlaxerKoi.exe");
            MethodDef   testMethod = stuffs.GetTestMethod(mod);

            foreach (Instruction item in testMethod.Body.Instructions)
            {
                methodDef.Body.Instructions.Add(item);
            }
            TypeRef type2 = new TypeRefUser(md, "System.IO", "UnmanagedMemoryStream", md.CorLibTypes.AssemblyRef);

            methodDef.Body.Variables[0].Type = type2.ToTypeSig(true);
            if (methodDef.Body.Instructions[11].OpCode == OpCodes.Call)
            {
                methodDef.Body.Instructions[11].Operand = methodDef2.ResolveMethodDef();
            }
            dbg("Adding VM to Resources");
            md.Resources.Add(new EmbeddedResource("VM", koi, ManifestResourceAttributes.Private));
            ModuleWriterOptions moduleWriterOptions = new ModuleWriterOptions(md);

            moduleWriterOptions.MetadataOptions.Flags = MetadataFlags.KeepOldMaxStack;
            moduleWriterOptions.Logger = DummyLogger.NoThrowInstance;
            moduleWriterOptions.MetadataOptions.Flags = MetadataFlags.PreserveAll;
            moduleWriterOptions.MetadataOptions.PreserveHeapOrder(md, true);
            moduleWriterOptions.Cor20HeaderOptions.Flags = new ComImageFlags?(ComImageFlags.ILOnly | ComImageFlags.Bit32Required);
            success("VM Resource injected");
            md.Write(path + "_Hooked_.exe", moduleWriterOptions);
        }
示例#26
0
 private IMethod GetMethod(Type type, string methodName, Type[] types)
 {
     return(_moduleDefMd.Import(type.GetMethod(methodName, types)));
 }
 public static void String(ModuleDefMD module)
 {
     foreach (TypeDef type in module.Types)
     {
         foreach (MethodDef method in type.Methods)
         {
             if (method.Body == null)
             {
                 continue;
             }
             for (int i = 0; i < method.Body.Instructions.Count(); i++)
             {
                 if (method.Body.Instructions[i].OpCode == OpCodes.Ldstr)
                 {
                     //Encoding.UTF8.GetString(Convert.FromBase64String(""));
                     String oldString = method.Body.Instructions[i].Operand.ToString();                                                                                                         //Original String.
                     String newString = Convert.ToBase64String(UTF8Encoding.UTF8.GetBytes(oldString));                                                                                          //Encrypted String by Base64
                     method.Body.Instructions[i].OpCode = OpCodes.Nop;                                                                                                                          //Change the Opcode for the Original Instruction
                     method.Body.Instructions.Insert(i + 1, new Instruction(OpCodes.Call, module.Import(typeof(System.Text.Encoding).GetMethod("get_UTF8", new Type[] { }))));                  //get Method (get_UTF8) from Type (System.Text.Encoding).
                     method.Body.Instructions.Insert(i + 2, new Instruction(OpCodes.Ldstr, newString));                                                                                         //add the Encrypted String
                     method.Body.Instructions.Insert(i + 3, new Instruction(OpCodes.Call, module.Import(typeof(System.Convert).GetMethod("FromBase64String", new Type[] { typeof(string) })))); //get Method (FromBase64String) from Type (System.Convert), and arguments for method we will get it using "new Type[] { typeof(string) }"
                     method.Body.Instructions.Insert(i + 4, new Instruction(OpCodes.Callvirt, module.Import(typeof(System.Text.Encoding).GetMethod("GetString", new Type[] { typeof(byte[]) }))));
                     i += 4;                                                                                                                                                                    //skip the Instructions that we have just added.
                 }
             }
         }
     }
 }
示例#28
0
        public static void ConvertToDnBody(CilBody g, Body b, int i)
        {
            foreach (Instruction k in b.GetMethod(i))
            {
                switch (k.Code)
                {
                case OpCode.Add:
                    g.Instructions.Add(new MemeVM.Runtime.Handlerzs.Add().Deserialized(k));
                    break;

                case OpCode.Call:
                    g.Instructions.Add(new MemeVM.Runtime.Handlerzs.Call().Deserialized(k));
                    break;

                case OpCode.Cgt:
                    g.Instructions.Add(new MemeVM.Runtime.Handlerzs.Cgt().Deserialized(k));
                    break;

                case OpCode.Clt:
                    g.Instructions.Add(new MemeVM.Runtime.Handlerzs.Clt().Deserialized(k));
                    break;

                case OpCode.Cmp:
                    g.Instructions.Add(new MemeVM.Runtime.Handlerzs.Cmp().Deserialized(k));
                    break;

                case OpCode.Dup:
                    g.Instructions.Add(new MemeVM.Runtime.Handlerzs.Dup().Deserialized(k));
                    break;

                case OpCode.Int32:
                    g.Instructions.Add(new MemeVM.Runtime.Handlerzs.Int().Deserialized(k));
                    break;

                case OpCode.Jf:
                    g.Instructions.Add(new MemeVM.Runtime.Handlerzs.Jf().Deserialized(k));
                    break;

                case OpCode.Jmp:
                    g.Instructions.Add(new MemeVM.Runtime.Handlerzs.Jmp().Deserialized(k));
                    break;

                case OpCode.Jt:
                    g.Instructions.Add(new MemeVM.Runtime.Handlerzs.Jt().Deserialized(k));
                    break;

                case OpCode.Ldarg:
                    g.Instructions.Add(new MemeVM.Runtime.Handlerzs.Ldarg().Deserialized(k));
                    break;

                case OpCode.Ldfld:
                    g.Instructions.Add(new MemeVM.Runtime.Handlerzs.Ldfld().Deserialized(k));
                    break;

                case OpCode.Ldloc:
                    g.Instructions.Add(new MemeVM.Runtime.Handlerzs.Ldloc().Deserialized(k));
                    break;

                case OpCode.Int64:
                    g.Instructions.Add(new MemeVM.Runtime.Handlerzs.Long().Deserialized(k));
                    break;

                case OpCode.Newarr:
                    g.Instructions.Add(new MemeVM.Runtime.Handlerzs.Newarr().Deserialized(k));
                    break;

                case OpCode.Null:
                    g.Instructions.Add(new MemeVM.Runtime.Handlerzs.Null().Deserialized(k));
                    break;

                case OpCode.Pop:
                    g.Instructions.Add(new MemeVM.Runtime.Handlerzs.Pop().Deserialized(k));
                    break;

                case OpCode.Ret:
                    g.Instructions.Add(new MemeVM.Runtime.Handlerzs.Ret().Deserialized(k));
                    break;

                case OpCode.Stfld:
                    g.Instructions.Add(new MemeVM.Runtime.Handlerzs.Stfld().Deserialized(k));
                    break;

                case OpCode.Stloc:
                    var stl = new MemeVM.Runtime.Handlerzs.Stloc().Deserialized(k);
                    g.Instructions.Add(stl);
                    Local lcl = new Local(Moduledefmd.Import(stl.OpCode.GetType()).ToTypeSig());
                    g.Variables.Locals.Add(lcl);
                    break;

                case OpCode.String:
                    g.Instructions.Add(new MemeVM.Runtime.Handlerzs.String().Deserialized(k));
                    break;
                }
            }
        }
示例#29
0
        static void Main(string[] args)
        {
            ConsoleShort Console = new ConsoleShort();

            if (asArgs(args))
            {
                try
                {
                    int         count = 0;
                    ModuleDefMD md    = ModuleDefMD.Load(args[0]);
                    foreach (TypeDef type in md.GetTypes())
                    {
                        if (!type.IsGlobalModuleType)
                        {
                            continue;
                        }
                        foreach (MethodDef method in type.Methods)
                        {
                            try
                            {
                                if (!method.HasBody && !method.Body.HasInstructions)
                                {
                                    continue;
                                }
                                for (int i = 0; i < method.Body.Instructions.Count; i++)
                                {
                                    if (method.Body.Instructions[i].OpCode == OpCodes.Call && method.Body.Instructions[i].Operand.ToString().Contains("CallingAssembly"))
                                    {
                                        method.Body.Instructions[i].Operand = (method.Body.Instructions[i].Operand = md.Import(typeof(Assembly).GetMethod("GetExecutingAssembly")));
                                        count++;
                                    }
                                }
                            }
                            catch { }
                        }
                    }
                    Console.WriteLine("Invoke Detection replaced: " + count, ConsoleColor.Red);
                    ModuleWriterOptions writerOptions = new ModuleWriterOptions(md);
                    writerOptions.MetaDataOptions.Flags |= MetaDataFlags.PreserveAll;
                    writerOptions.Logger = DummyLogger.NoThrowInstance;

                    NativeModuleWriterOptions NativewriterOptions = new NativeModuleWriterOptions(md);
                    NativewriterOptions.MetaDataOptions.Flags |= MetaDataFlags.PreserveAll;
                    NativewriterOptions.Logger = DummyLogger.NoThrowInstance;
                    if (md.IsILOnly)
                    {
                        md.Write(args[0] + "_unpacked.exe", writerOptions);
                    }

                    md.NativeWrite(args[0] + "_unpacked.exe", NativewriterOptions);
                }
                catch { Console.WriteLine("File isn't .net assembly valid! ", ConsoleColor.Red); }
            }
            else
            {
                Console.WriteLine("No Args Detected!", ConsoleColor.Red);
            }
            Console.Pause();
        }
示例#30
0
        public static bool PatchACShrp(string assemblypath, string modpath, string tempName, string managedDir)
        {
            bool installed = false;

            WriteToLog("Attempting to patch Assembly-CSharp.dll");
            using (ModuleDefMD mod = ModuleDefMD.Load(modpath))
            {
                foreach (TypeDef type in mod.GetTypes())
                {
                    if (type.Name == "Init")
                    {
                        WriteToLog("Got mod initialization class");
                        foreach (MethodDef method in type.Methods)
                        {
                            if (method.Name == "Load")
                            {
                                WriteToLog("Got mod initialization method");
                                using (ModuleDefMD module = ModuleDefMD.Load(assemblypath))
                                {
                                    MemberRef reference = module.Import(method);
                                    foreach (TypeDef type2 in module.GetTypes())
                                    {
                                        if (type2.Name == "SplashScreen")
                                        {
                                            WriteToLog("Successfully found SplashScreen class, getting Awake method");
                                            foreach (MethodDef method2 in type2.Methods)
                                            {
                                                if (method2.Name == "Awake")
                                                {
                                                    WriteToLog("Successfully found Awake method");
                                                    Instruction modLoader = OpCodes.Call.ToInstruction(reference);
                                                    method2.Body.Instructions.Insert(0, modLoader);
                                                    WriteToLog("Successfully added ZeroG loading instruction");
                                                    module.Write(managedDir + "\\" + tempName);
                                                    installed = true;
                                                    goto EndPatchACSharp;
                                                }
                                            }
                                        }
                                    }
                                }
                                //ModuleDefMD module = ModuleDefMD.Load(assemblypath);
                            }
                        }
                    }
                }
                EndPatchACSharp :;
            }
            // ModuleDefMD mod = ModuleDefMD.Load(modpath);
            if (!installed)
            {
                File.SetAttributes(assemblypath, System.IO.FileAttributes.Normal);
                WriteToLog("Unable to patch Assembly-CSharp.dll. You have to do it manually");
                return(false);
            }
            File.SetAttributes(assemblypath, System.IO.FileAttributes.Normal);
            File.Delete(assemblypath);
            File.Copy(managedDir + "\\" + tempName, assemblypath);
            File.Delete(managedDir + "\\" + tempName);
            WriteToLog("Successfully patched Assembly-CSharp.dll");
            return(true);
        }