Beispiel #1
0
        static void packer()
        {
            try
            {
                if (Protections.Packer.IsPacked(module))
                {
                    Console.WriteLine("[!] Compressor Detected");
                    try
                    {
                        Protections.Packer.findLocal();
                        Console.WriteLine("[!] Compressor Removed Successfully");
                        Console.WriteLine("[!] Now Cleaning The koi Module");
                    }
                    catch
                    {
                        Console.WriteLine("[!] Compressor Failed To Remove");
                    }

                    antitamper();
                    module.EntryPoint = module.ResolveToken(Protections.StaticPacker.epToken) as MethodDef;
                }
            }
            catch
            {
                Console.WriteLine("An error in dynamic packer remover happened");
            }
        }
		void Initialize(ModuleDefMD module) {
			var info = module.MetaData.ImageCor20Header.VTableFixups;
			if (info.VirtualAddress == 0 || info.Size == 0) {
				this.vtables = ThreadSafeListCreator.Create<VTable>();
				return;
			}
			this.rva = info.VirtualAddress;
			this.vtables = ThreadSafeListCreator.Create<VTable>((int)info.Size / 8);

			var peImage = module.MetaData.PEImage;
			using (var reader = peImage.CreateFullStream()) {
				reader.Position = (long)peImage.ToFileOffset(info.VirtualAddress);
				long endPos = reader.Position + info.Size;
				while (reader.Position + 8 <= endPos && reader.CanRead(8)) {
					RVA tableRva = (RVA)reader.ReadUInt32();
					int numSlots = reader.ReadUInt16();
					var flags = (VTableFlags)reader.ReadUInt16();
					var vtable = new VTable(tableRva, flags, numSlots);
					vtables.Add(vtable);

					var pos = reader.Position;
					reader.Position = (long)peImage.ToFileOffset(tableRva);
					int slotSize = vtable.Is64Bit ? 8 : 4;
					while (numSlots-- > 0 && reader.CanRead(slotSize)) {
						vtable.Methods.Add(module.ResolveToken(reader.ReadUInt32()) as IMethod);
						if (slotSize == 8)
							reader.ReadUInt32();
					}
					reader.Position = pos;
				}
			}
		}
Beispiel #3
0
        public PdbConstant[] GetConstants(ModuleDefMD module, GenericParamContext gpContext)
        {
            if (constants == null)
            {
                return(emptySymbolConstants);
            }
            var res = new PdbConstant[constants.Count];

            for (int i = 0; i < res.Length; i++)
            {
                var     info = constants[i];
                TypeSig signature;
                var     saSig    = module.ResolveToken(info.SignatureToken) as StandAloneSig;
                var     fieldSig = saSig == null ? null : saSig.Signature as FieldSig;
                if (fieldSig == null)
                {
                    Debug.Fail("Constant without a signature");
                    signature = null;
                }
                else
                {
                    signature = fieldSig.Type;
                }
                res[i] = new PdbConstant(info.Name, signature, info.Value);
            }
            return(res);
        }
Beispiel #4
0
        void Restore2()
        {
            Logger.n("Restoring CSVM methods");
            Logger.Instance.Indent();

            var opcodeDetector = GetVmOpCodeHandlerDetector();
            var csvmMethods    = new CsvmDataReader(resource.Data).Read();

            var converter     = new CsvmToCilMethodConverter(deobfuscatorContext, module, opcodeDetector);
            var methodPrinter = new MethodPrinter();

            foreach (var csvmMethod in csvmMethods)
            {
                var cilMethod = module.ResolveToken(csvmMethod.Token) as MethodDef;
                if (cilMethod == null)
                {
                    throw new ApplicationException(string.Format("Could not find method {0:X8}", csvmMethod.Token));
                }
                converter.Convert(cilMethod, csvmMethod);
                Logger.v("Restored method {0:X8}", cilMethod.MDToken.ToInt32());
                PrintMethod(methodPrinter, cilMethod);
            }
            Logger.Instance.DeIndent();
            Logger.n("Restored {0} CSVM methods", csvmMethods.Count);
        }
Beispiel #5
0
 IMethod ReResolve(IMethod method, GenericParamContext gpContext)
 {
     if (method.IsMethodSpec || method.IsMemberRef)
     {
         method = module.ResolveToken(method.MDToken.Raw, gpContext) as IMethod ?? method;
     }
     return(method);
 }
        void Decrypt(IBinaryReader reader, int delegateTypeToken, ISimpleDeobfuscator simpleDeobfuscator)
        {
            var delegateType = module.ResolveToken(delegateTypeToken) as TypeDef;

            if (delegateType == null)
            {
                throw new ApplicationException("Couldn't find delegate type");
            }

            int delToken, encMethToken, encDeclToken;

            if (!GetTokens(delegateType, out delToken, out encMethToken, out encDeclToken))
            {
                throw new ApplicationException("Could not find encrypted method tokens");
            }
            if (delToken != delegateTypeToken)
            {
                throw new ApplicationException("Invalid delegate type token");
            }
            var encType = module.ResolveToken(encDeclToken) as ITypeDefOrRef;

            if (encType == null)
            {
                throw new ApplicationException("Invalid declaring type token");
            }
            var encMethod = module.ResolveToken(encMethToken) as MethodDef;

            if (encMethod == null)
            {
                throw new ApplicationException("Invalid encrypted method token");
            }

            var bodyReader = new MethodBodyReader(module, reader);

            bodyReader.Read(encMethod);
            bodyReader.RestoreMethod(encMethod);
            Logger.v("Restored method {0} ({1:X8}). Instrs:{2}, Locals:{3}, Exceptions:{4}",
                     Utils.RemoveNewlines(encMethod.FullName),
                     encMethod.MDToken.ToInt32(),
                     encMethod.Body.Instructions.Count,
                     encMethod.Body.Variables.Count,
                     encMethod.Body.ExceptionHandlers.Count);
            delegateTypes.Add(delegateType);
            simpleDeobfuscator.MethodModified(encMethod);
        }
Beispiel #7
0
        static void packer()
        {
            if (Protections.Packer.IsPacked(module))
            {
                Console.WriteLine("[!] Compressor Dynamico Detectado");
                try
                {
                    Protections.Packer.findLocal();
                    Console.WriteLine("[!] Compressor Removido");
                }
                catch
                {
                    Console.WriteLine("[!] Compressor Erro ao Remover");
                }

                antitamper();
                module.EntryPoint = module.ResolveToken(Protections.StaticPacker.epToken) as MethodDef;
            }
        }
Beispiel #8
0
		public void reloaded() {
			foreach (var pair in tokenToNativeMethod) {
				int token = (int)pair.Key;
				var method = module.ResolveToken(token) as MethodDef;
				if (method == null)
					throw new ApplicationException(string.Format("Could not find method {0:X8}", token));
				methodToNativeMethod[method] = pair.Value;
			}
			tokenToNativeMethod = null;
		}
        private static string DecryptSting(MethodSpec decryptionMethod, uint uintVal, object arrayVal)
        {
            Base.methodsToRemove.Add(decryptionMethod);
            MethodDef resolvedDef = decryptionMethod.ResolveMethodDef();

            CawkEmulatorV4.Emulation emulationD = new CawkEmulatorV4.Emulation(resolvedDef);
            emulationD.ValueStack.Fields[ModuleDefMD.ResolveToken(Strings.Initalise.DecryptInitialByteArray.fields.MDToken.ToInt32()) as FieldDef] = Strings.Initalise.DecryptInitialByteArray.byte_0;
            File.WriteAllBytes("Method.bin", methodBytes);
            if (FieldValueGrabber.value != null)
            {
                emulationD.ValueStack.Fields[
                    ModuleDefMD.ResolveToken(FieldValueGrabber.value.Item1.MDToken.ToInt32()) as
                    FieldDef] = (int)
                                FieldValueGrabber.value.Item2;
            }

            emulationD.ValueStack.Parameters[resolvedDef.Parameters[0]] = uintVal;
            emulationD.ValueStack.Parameters[resolvedDef.Parameters[1]] = arrayVal;
            emulationD.OnCallPrepared         = (sender, e) => { HandleCall(sender, e); };
            emulationD.OnInstructionPrepared += (emulation, args) =>
            {
                if (args.Instruction.OpCode == OpCodes.Isinst)
                {
                    dynamic value     = emulation.ValueStack.CallStack.Pop();
                    TypeRef instrType = args.Instruction.Operand as TypeRef;
                    dynamic name      = value.GetType().Name;
                    if (instrType.FullName.Contains(name))
                    {
                        emulation.ValueStack.CallStack.Push(1);
                    }
                    else
                    {
                        emulation.ValueStack.CallStack.Push(null);
                    }
                    args.Cancel = true;
                }
                else if (args.Instruction.OpCode == OpCodes.Castclass)
                {
                    dynamic abc = emulation.ValueStack.CallStack.Pop();
                    if (abc is int[])
                    {
                        emulation.ValueStack.CallStack.Push((int[])abc);
                        args.Cancel = true;
                    }

                    if (args.Instruction.Operand.ToString().Contains("Assembly"))
                    {
                        emulation.ValueStack.CallStack.Push(null);
                        args.Cancel = true;
                    }
                }
            };
            emulationD.Emulate();
            return((string)emulationD.ValueStack.CallStack.Pop());
        }
Beispiel #10
0
 static void AddToken(this IList <short> instrs, ModuleDefMD module, uint token)
 {
     if (module == null || module.ResolveToken(token) == null)
     {
         instrs.AddUnknownInt32();
     }
     else
     {
         instrs.AddInt32(unchecked ((int)token));
     }
 }
Beispiel #11
0
        public override IDeobfuscator ModuleReloaded(ModuleDefMD module)
        {
            if (module.Assembly != null)
            {
                realAssemblyInfo = null;
            }
            if (realAssemblyInfo != null)
            {
                realAssemblyInfo.realAssembly.Modules.Insert(0, module);
                if (realAssemblyInfo.entryPointToken != 0)
                {
                    module.EntryPoint = module.ResolveToken((int)realAssemblyInfo.entryPointToken) as MethodDef;
                }
                module.Kind = realAssemblyInfo.kind;
                module.Name = new UTF8String(realAssemblyInfo.moduleName);
            }

            var newOne = new Deobfuscator(options);

            DeobfuscatedFile.SetDeobfuscator(newOne);
            newOne.realAssemblyInfo = realAssemblyInfo;
            newOne.decryptState     = decryptState;
            newOne.DeobfuscatedFile = DeobfuscatedFile;
            newOne.ModuleBytes      = ModuleBytes;
            newOne.embeddedAssemblyInfos.AddRange(embeddedAssemblyInfos);
            newOne.SetModule(module);
            newOne.RemoveObfuscatorAttribute();
            newOne.jitMethodsDecrypter = hasUnpacked ? new JitMethodsDecrypter(module, DeobfuscatedFile) :
                                         new JitMethodsDecrypter(module, DeobfuscatedFile, jitMethodsDecrypter);
            if ((newOne.decryptState & DecryptState.CanDecryptMethods) != 0)
            {
                try {
                    newOne.jitMethodsDecrypter.Find();
                }
                catch {
                }
                if (newOne.jitMethodsDecrypter.Detected)
                {
                    return(newOne);
                }
            }
            newOne.memoryMethodsDecrypter = hasUnpacked ? new MemoryMethodsDecrypter(module, DeobfuscatedFile) :
                                            new MemoryMethodsDecrypter(module, DeobfuscatedFile, memoryMethodsDecrypter);
            if ((newOne.decryptState & DecryptState.CanDecryptMethods) != 0)
            {
                newOne.memoryMethodsDecrypter.Find();
                if (newOne.memoryMethodsDecrypter.Detected)
                {
                    return(newOne);
                }
            }
            newOne.InitializeTheRest(this);
            return(newOne);
        }
Beispiel #12
0
		/// <summary>
		/// Constructor
		/// </summary>
		/// <param name="reader">A <see cref="ISymbolReader"/> instance</param>
		/// <param name="module">Owner module</param>
		public PdbState(ISymbolReader reader, ModuleDefMD module) {
			if (reader == null)
				throw new ArgumentNullException("reader");
			if (module == null)
				throw new ArgumentNullException("module");
			this.reader = reader;

			this.userEntryPoint = module.ResolveToken(reader.UserEntryPoint.GetToken()) as MethodDef;

			foreach (var doc in reader.GetDocuments())
				Add_NoLock(new PdbDocument(doc));
		}
Beispiel #13
0
        public static T Lookup <T>(ModuleDefMD module, T def, string errorMessage) where T : class, ICodedToken
        {
            if (def == null)
            {
                return(null);
            }
            var newDef = module.ResolveToken(def.MDToken.Raw) as T;

            if (newDef == null)
            {
                throw new ApplicationException(errorMessage);
            }
            return(newDef);
        }
 public void Reloaded()
 {
     foreach (var pair in tokenToNativeMethod)
     {
         int token  = (int)pair.Key;
         var method = module.ResolveToken(token) as MethodDef;
         if (method == null)
         {
             throw new ApplicationException($"Could not find method {token:X8}");
         }
         methodToNativeMethod[method] = pair.Value;
     }
     tokenToNativeMethod = null;
 }
Beispiel #15
0
        public void Deobfuscate(Blocks blocks)
        {
            if (type == null)
            {
                return;
            }

            var gpContext = GenericParamContext.Create(blocks.Method);

            foreach (var block in blocks.MethodBlocks.GetAllBlocks())
            {
                var instrs = block.Instructions;
                for (int i = 0; i < instrs.Count - 1; i++)
                {
                    var instr = instrs[i];
                    if (instr.OpCode.Code != Code.Ldc_I4)
                    {
                        continue;
                    }
                    var call = instrs[i + 1];
                    if (call.OpCode.Code != Code.Call)
                    {
                        continue;
                    }
                    var method = call.Operand as IMethod;
                    if (method == null)
                    {
                        continue;
                    }
                    if (!new SigComparer().Equals(type, method.DeclaringType))
                    {
                        continue;
                    }
                    var methodDef = DotNetUtils.GetMethod(module, method);
                    if (methodDef == null)
                    {
                        continue;
                    }
                    if (methodDef != typeMethod && methodDef != fieldMethod)
                    {
                        continue;
                    }

                    uint token = (uint)(int)instrs[i].Operand;
                    instrs[i]     = new Instr(OpCodes.Nop.ToInstruction());
                    instrs[i + 1] = new Instr(new Instruction(OpCodes.Ldtoken, module.ResolveToken(token, gpContext) as ITokenOperand));
                }
            }
        }
Beispiel #16
0
        private void PatchCallingAssemblyCheck(ModuleDefMD module, uint mdToken)
        {
            MethodDef method = (MethodDef)module.ResolveToken(mdToken);

            for (int i = 0; i < method.Body.Instructions.Count - 1; i++)
            {
                if (method.Body.Instructions[i].OpCode.Code == Code.Call &&
                    method.Body.Instructions[i + 1].OpCode.Code == Code.Call &&
                    ((MemberRef)method.Body.Instructions[i].Operand).Name == "GetExecutingAssembly")
                {
                    method.Body.Instructions[i + 1].Operand = method.Body.Instructions[i].Operand;
                    break;
                }
            }
        }
Beispiel #17
0
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="reader">A <see cref="ISymbolReader"/> instance</param>
        /// <param name="module">Owner module</param>
        public PdbState(ISymbolReader reader, ModuleDefMD module)
        {
            if (reader == null)
            {
                throw new ArgumentNullException("reader");
            }
            if (module == null)
            {
                throw new ArgumentNullException("module");
            }
            this.reader = reader;

            this.userEntryPoint = module.ResolveToken(reader.UserEntryPoint.GetToken()) as MethodDef;

            foreach (var doc in reader.GetDocuments())
            {
                Add_NoLock(new PdbDocument(doc));
            }
        }
        public static byte[] tester(MethodDef methodDef, ModuleDefMD updated)
        {
            var streamFull = updated.Metadata.PEImage.CreateReader();
            var upated     = (updated.ResolveToken(methodDef.MDToken.ToInt32()) as MethodDef);
            var offset     = updated.Metadata.PEImage.ToFileOffset(upated.RVA);

            streamFull.Position = (uint)offset;
            byte b = streamFull.ReadByte();

            ushort flags;
            byte   headerSize;
            ushort maxStack;
            uint   codeSize = 0;

            switch (b & 7)
            {
            case 2:
            case 6:
                flags      = 2;
                maxStack   = 8;
                codeSize   = (uint)(b >> 2);
                headerSize = 1;
                break;

            case 3:
                flags      = (ushort)((streamFull.ReadByte() << 8) | b);
                headerSize = (byte)(flags >> 12);
                maxStack   = streamFull.ReadUInt16();
                codeSize   = streamFull.ReadUInt32();
                break;
            }
            if (codeSize != 0)
            {
                byte[] il_byte = new byte[codeSize];
                streamFull.Position = (uint)offset + upated.Body.HeaderSize;
                streamFull.ReadBytes(il_byte, 0, il_byte.Length);
                return(il_byte);
            }
            return(null);
        }
Beispiel #19
0
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="reader">A <see cref="SymbolReader"/> instance</param>
        /// <param name="module">Owner module</param>
        public PdbState(SymbolReader reader, ModuleDefMD module)
        {
            if (reader == null)
            {
                throw new ArgumentNullException("reader");
            }
            if (module == null)
            {
                throw new ArgumentNullException("module");
            }
            this.reader = reader;
            reader.Initialize(module);
            PdbFileKind   = reader.PdbFileKind;
            this.compiler = CalculateCompiler(module);

            this.userEntryPoint = module.ResolveToken(reader.UserEntryPoint) as MethodDef;

            foreach (var doc in reader.Documents)
            {
                Add_NoLock(new PdbDocument(doc));
            }
        }
        public override void Deobfuscate()
        {
            //    Console.WriteLine("[!] Setting Up String Decryption Finding Init Method");
            GetMethod = firstStep(ModuleDefMD);
            Base.methodsToRemove.Add(GetMethod);
            if (GetMethod == null)
            {
                //      Console.WriteLine("[!!] Method Not Found Fix This");
                return;
            }
            //     Console.WriteLine("[!] Found String Init Method {0}. Emulating", GetMethod.Name);
            var insemu = new Emulation(GetMethod);

            insemu.OnInstructionPrepared = (sender, e) =>
            {
                if (e.Instruction.OpCode == OpCodes.Castclass)
                {
                    e.Cancel = true;
                }
            };
            insemu.OnCallPrepared = (sender, e) =>
            {
                if (e.Instruction.Operand.ToString()
                    .Contains(
                        "System.Void System.Runtime.CompilerServices.RuntimeHelpers::InitializeArray(System.Array,System.RuntimeFieldHandle")
                    )
                {
                    var stack2 = sender.ValueStack.CallStack.Pop();
                    var stack1 = sender.ValueStack.CallStack.Pop();
                    sender.ValueStack.CallStack.Pop();
                    var fielddef = ModuleDefMD.ResolveToken(stack2) as FieldDef;
                    var test     = fielddef.InitialValue;
                    var decoded  = new uint[test.Length / 4];
                    Buffer.BlockCopy(test, 0, decoded, 0, test.Length);
                    stack1 = decoded;
                    sender.ValueStack.CallStack.Push(stack1);
                    e.bypassCall = true;
                }
                else if (e.Instruction.Operand is MethodDef &&
                         e.Instruction.Operand.ToString().Contains("(System.Byte[])"))
                {
                    e.endMethod = true;
                }
                else
                {
                    e.AllowCall = false;
                }
            };

            GC.Collect();
            Thread.Sleep(1000);
            GC.Collect();
            insemu.Emulate();
            if (GetMethod.Body.Instructions[GetMethod.Body.Instructions.Count - 2].OpCode == OpCodes.Stsfld)
            {
                fields = (FieldDef)GetMethod.Body.Instructions[GetMethod.Body.Instructions.Count - 2].Operand;
            }
            var aaa = GetMethod.Body.Variables.Where(i => i.Type.FullName.Contains("System.Byte[]")).ToArray();


            var byteStackLocal = insemu.ValueStack.Locals[aaa[0].Index];

            //Console.WriteLine("[!] Emulation Success Got Array");

            if (Protections.Base.NativePacker)
            {
                byteStackLocal = P1(byteStackLocal, byteStackLocal.Length);
            }
            byte_0 = (byte[])byteStackLocal;

            return;
        }
Beispiel #21
0
 T Resolve <T>(int token)
 {
     return((T)module.ResolveToken(token));
 }
Beispiel #22
0
 T Resolve <T>(int token)
 {
     return((T)module.ResolveToken(token, gpContext));
 }
Beispiel #23
0
        private bool checkBlocks()
        {
            bool   isError         = false;
            string logInfo         = "";
            var    blocksToFind    = new List <List <string> >();
            var    blocksToReplace = new List <List <string> >();

            foreach (var block in Regex.Split(inputFindText, @"^={3,}", RegexOptions.Multiline))
            {
                var instrs = block.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries).ToList();
                blocksToFind.Add(instrs);
            }

            foreach (var block in Regex.Split(inputReplaceText, @"^={3,}", RegexOptions.Multiline))
            {
                var instrs = block.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries).ToList();
                blocksToReplace.Add(instrs);
            }

            if (blocksToFind.Count != blocksToReplace.Count)
            {
                MessageBox.Show(
                    string.Format("Size of Blocks Find and Replace not Match\r\nBlocks Find: {0}\r\nBlocks Replace: {1}",
                                  blocksToFind.Count, blocksToReplace.Count),
                    "Blocks Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                isError = true;
            }

            if (!isError)
            {
                for (int i = 0; i < blocksToFind.Count; i++)
                {
                    if (blocksToFind[i].Count != blocksToReplace[i].Count)
                    {
                        logInfo += string.Format(
                            "Error, Block {0} has different size\r\nFind ({1}):\r\n{2}\r\n\r\nReplace ({3}):\r\n{4}\r\n{5}\r\n", i + 1,
                            blocksToFind[i].Count, string.Join("\r\n", blocksToFind[i].ToArray()),
                            blocksToReplace[i].Count, string.Join("\r\n", blocksToReplace[i].ToArray()),
                            "================================================");

                        isError = true;
                    }
                }
            }

            try
            {
                module = ModuleDefMD.Load(moduleName);
            }
            catch
            {
                writeStatus(string.Format("Error Loading \"{0}\" Maybe not .NET Executable", Path.GetFileName(moduleName)));
                isError = true;
            }

            if (!isError)
            {
                for (int i = 0; i < blocksToFind.Count; i++)
                {
                    var block        = blocksToFind[i];
                    var instructions = new List <Instruction>();
                    for (int j = 0; j < block.Count; j++)
                    {
                        var         line    = block[j];
                        OpCode      opCode  = null;
                        Instruction instr   = new Instruction();
                        string[]    toInstr = line.Trim().Split(new char[] { ' ', '\t' }, 2);
                        if (toInstr.Length > 0)
                        {
                            opCode = GetOpCodeFromString(toInstr[0]);
                        }
                        if (opCode != null)
                        {
                            instr.OpCode = opCode;
                            if (toInstr.Length == 2)
                            {
                                instr.Operand = toInstr[1].Trim().Trim('"');
                            }
                            instructions.Add(instr);
                        }
                        else
                        {
                            logInfo += string.Format(
                                "\"{0}\" is not valid OpCode, Block Find {1} Line {2}\r\n{3}",
                                toInstr[0], i + 1, j + 1, line);
                            isError = true;
                        }
                    }

                    BlocksFind.Add(instructions);
                }
            }

            if (!isError)
            {
                for (int i = 0; i < blocksToReplace.Count; i++)
                {
                    var block        = blocksToReplace[i];
                    var instructions = new List <Instruction>();
                    for (int j = 0; j < block.Count; j++)
                    {
                        var         line    = block[j];
                        OpCode      opCode  = null;
                        Instruction instr   = new Instruction();
                        string[]    toInstr = line.Trim().Split(new char[] { ' ', '\t' }, 2);

                        if (toInstr[0].Trim() == "=")
                        {
                            instr.Operand = "=";
                            instructions.Add(instr);
                            continue;
                        }

                        opCode = GetOpCodeFromString(toInstr[0]);

                        if (opCode != null)
                        {
                            instr.OpCode = opCode;
                            if (toInstr.Length == 2)
                            {
                                if (opCode == OpCodes.Call)
                                {
                                    string mdtoken = toInstr[1].Trim().ToUpper();
                                    if (mdtoken == "" || !Regex.IsMatch(mdtoken, @"^(0[Xx])?[A-F0-9]{8}$"))
                                    {
                                        isError = true;
                                    }
                                    else
                                    {
                                        uint rid      = uint.Parse(mdtoken.ToUpper().Replace("0X", ""), System.Globalization.NumberStyles.HexNumber);
                                        var  isMethod = module.ResolveToken(rid);
                                        if (isMethod == null)
                                        {
                                            isError = true;
                                        }
                                        instr.Operand = rid;
                                    }

                                    if (isError)
                                    {
                                        logInfo += string.Format(
                                            "\"{0}\" is invalid Operand/MDToken for \"Call\", Block Replace {1} Line {2}\r\n{3}\r\n{4}\r\n",
                                            mdtoken, i + 1, j + 1, "The value Should be Hex or MDToken like 06000001 or 0x06000001", line);
                                    }
                                }
                                else
                                {
                                    instr.Operand = toInstr[1].Trim().Trim('"');
                                }
                            }

                            instructions.Add(instr);
                        }
                        else
                        {
                            logInfo += string.Format(
                                "\"{0}\" is not valid OpCode, Block Replace {1} Line {2}\r\n{3}",
                                toInstr[0], i + 1, j + 1, line);
                            isError = true;
                        }
                    }

                    BlocksReplace.Add(instructions);
                }
            }

            if (isError)
            {
                if (logInfo != "")
                {
                    showFormLog(logInfo);
                }
                enableControl(true);
                isRunning = false;
                if (module != null)
                {
                    module.Dispose();
                }
                return(false);
            }

            return(true);
        }
Beispiel #24
0
        private void ReplaceInstructions()
        {
            string currentBlockNum = "";

            foreach (var type in module.GetTypes())
            {
                foreach (var method in type.Methods)
                {
                    bool isNewMethod = true;
                    if (!method.HasBody)
                    {
                        continue;
                    }
                    var instrs = method.Body.Instructions;
                    for (int i = 0; i < instrs.Count; i++)
                    {
                        // start replace
                        for (int B = 0; B < BlocksFind.Count; B++)
                        {
                            bool isMatched = false;
                            int  j         = i;
                            var  blockFind = BlocksFind[B];

                            // check
                            for (int k = 0; k < blockFind.Count; k++)
                            {
                                if (instrs[j].OpCode == blockFind[k].OpCode)
                                {
                                    if (blockFind[k].OpCode == OpCodes.Call)
                                    {
                                        if (instrs[j].Operand == null)
                                        {
                                            isMatched = false;
                                        }
                                        else
                                        {
                                            if (instrs[j].Operand.ToString().Contains(blockFind[k].Operand.ToString()))
                                            {
                                                isMatched = true;
                                            }
                                            else
                                            {
                                                isMatched = false;
                                            }
                                        }
                                    }
                                    else if (blockFind[k].Operand != null)
                                    {
                                        if (instrs[j].Operand.ToString().Contains(blockFind[k].Operand.ToString()))
                                        {
                                            isMatched = true;
                                        }
                                        else
                                        {
                                            isMatched = false;
                                        }
                                    }
                                    else
                                    {
                                        isMatched = true;
                                    }
                                }
                                else
                                {
                                    isMatched = false;
                                    break;
                                }
                                j++;
                            }

                            if (isMatched)
                            {
                                if (isNewMethod)
                                {
                                    isNewMethod = false;
                                    EditedMethodsCount++;
                                    logInfo += string.Format(
                                        "==========================================\r\nMethod: {0} || MDToken: 0x06{1:X6}\r\n",
                                        method.FullName, method.MDToken.Rid);
                                    currentBlockNum = "";
                                }
                                if (currentBlockNum != (B + 1).ToString())
                                {
                                    currentBlockNum = (B + 1).ToString();
                                    logInfo        += string.Format("\r\nBlock Find and Replace: {0}\r\n", (B + 1));
                                }

                                // Do replace
                                j = i;
                                for (int k = 0; k < blockFind.Count; k++)
                                {
                                    var newOperand = BlocksReplace[B][k].Operand;
                                    if (newOperand.ToString() == "=")
                                    {
                                        logInfo += string.Format("#{0} --> {1}  {2}  ==>  No Change\r\n",
                                                                 j, instrs[j].OpCode, instrs[j].Operand,
                                                                 BlocksReplace[B][k].OpCode, newOperand);
                                    }
                                    else
                                    {
                                        if (BlocksReplace[B][k].OpCode == OpCodes.Call)
                                        {
                                            newOperand = module.ResolveToken((uint)BlocksReplace[B][k].Operand);
                                        }

                                        logInfo += string.Format("#{0} --> {1}  {2}  ==>  {3}  {4}\r\n",
                                                                 j, instrs[j].OpCode, instrs[j].Operand,
                                                                 BlocksReplace[B][k].OpCode, newOperand);

                                        method.Body.Instructions[j].OpCode  = BlocksReplace[B][k].OpCode;
                                        method.Body.Instructions[j].Operand = newOperand;
                                    }

                                    j++;
                                }

                                ReplacedBlocks++;
                                // set method.Body.Instructions loop position
                                i = j;
                            }
                        }
                    }
                }
            }
        }
        public static void HandleCall(Emulation sender, CallEventArgs e)
        {
            object instruction = e.Instruction.Operand;

            if (instruction.ToString().Contains("System.Void System.Diagnostics.StackTrace::.ctor()"))
            {
                sender.ValueStack.CallStack.Push(1);
                e.bypassCall = true;
            }

            else if (instruction.ToString().Contains("System.Diagnostics.StackFrame System.Diagnostics.StackTrace::GetFrame(System.Int32)"))
            {
                dynamic call = sender.ValueStack.CallStack.Pop();
                dynamic ldc  = sender.ValueStack.CallStack.Pop();
                sender.ValueStack.CallStack.Push(1);
                e.bypassCall = true;
            }
            else if (e.Instruction.Operand.ToString().Contains("System.String System.String::Intern(System.String)"))
            {
                dynamic abc = sender.ValueStack.CallStack.Pop();
                sender.ValueStack.CallStack.Push(string.Intern(abc));
                e.bypassCall = true;
            }
            else if (instruction.ToString().Contains("System.Reflection.MethodBase System.Diagnostics.StackFrame::GetMethod()"))
            {
                dynamic call = sender.ValueStack.CallStack.Pop();
                sender.ValueStack.CallStack.Push(1);
                e.bypassCall = true;
            }
            else if (instruction.ToString().Contains("System.Reflection.MethodBody System.Reflection.MethodBase::GetMethodBody()"))
            {
                dynamic call = sender.ValueStack.CallStack.Pop();
                sender.ValueStack.CallStack.Push(1);
                e.bypassCall = true;
            }
            else if (instruction.ToString().Contains("System.Byte[] System.Reflection.MethodBody::GetILAsByteArray()"))
            {
                sender.ValueStack.CallStack.Pop();
                sender.ValueStack.CallStack.Push(methodBytes);
                e.bypassCall = true;
            }
            else if (instruction.ToString().Contains("System.Text.Encoding System.Text.Encoding::get_UTF8()"))
            {
                sender.ValueStack.CallStack.Push(Encoding.UTF8);
                e.bypassCall = true;
            }
            else if (e.Instruction.Operand.ToString().Contains("System.String System.Text.Encoding::GetString(System.Byte[],System.Int32,System.Int32)"))
            {
                dynamic abc = sender.ValueStack.CallStack.Pop();
                dynamic def = sender.ValueStack.CallStack.Pop();
                dynamic ghi = sender.ValueStack.CallStack.Pop();
                sender.ValueStack.CallStack.Pop();
                sender.ValueStack.CallStack.Push(Encoding.UTF8.GetString(ghi, (int)def, (int)abc));
                e.bypassCall = true;
            }
            else if (instruction.ToString().Contains("System.String System.Reflection.MemberInfo::get_Name()"))
            {
                sender.ValueStack.CallStack.Pop();
                sender.ValueStack.CallStack.Push(methodName);
                e.bypassCall = true;
            }
            else if (e.Instruction.Operand.ToString().Contains("System.Byte[] System.Text.Encoding::GetBytes(System.String)"))
            {
                dynamic abc = sender.ValueStack.CallStack.Pop();
                sender.ValueStack.CallStack.Pop();
                sender.ValueStack.CallStack.Push(Encoding.UTF8.GetBytes(abc));
                e.bypassCall = true;
            }
            else if (e.Instruction.Operand.ToString().Contains("System.Type System.Object::GetType()"))
            {
                dynamic abc = sender.ValueStack.CallStack.Pop();
                //        sender.ValueStack.CallStack.Pop();
                sender.ValueStack.CallStack.Push(abc.GetType());
                e.bypassCall = true;
            }
            else if (instruction.ToString().Contains("System.Boolean System.String::op_Equality(System.String,System.String)"))
            {
                dynamic one   = sender.ValueStack.CallStack.Pop();
                dynamic two   = sender.ValueStack.CallStack.Pop();
                dynamic boole = one == two;
                sender.ValueStack.CallStack.Push(boole);
                e.bypassCall = true;
            }
            else if (instruction.ToString().Contains("System.Boolean System.String::op_Inequality(System.String,System.String)"))
            {
                dynamic one   = sender.ValueStack.CallStack.Pop();
                dynamic two   = sender.ValueStack.CallStack.Pop();
                dynamic boole = one != two;
                sender.ValueStack.CallStack.Push(boole);
                e.bypassCall = true;
            }
            else if (instruction.ToString().Contains("System.Reflection.Assembly System.Reflection.Assembly::GetCallingAssembly()"))
            {
                sender.ValueStack.CallStack.Push(1);
                e.bypassCall = true;
            }
            else if (instruction.ToString().Contains("System.String System.Reflection.Assembly::get_FullName()"))
            {
                sender.ValueStack.CallStack.Pop();
                sender.ValueStack.CallStack.Push(ModuleDefMD.FullName);
                e.bypassCall = true;
            }
            else if (instruction.ToString().Contains("System.Reflection.Assembly System.Reflection.Assembly::GetExecutingAssembly()"))
            {
                sender.ValueStack.CallStack.Push(1);
                e.bypassCall = true;
            }
            else if (instruction.ToString()
                     .Contains("System.Type System.Type::GetTypeFromHandle(System.RuntimeTypeHandle"))
            {
                dynamic stack = sender.ValueStack.CallStack.Pop();
                sender.ValueStack.CallStack.Push(typeof(string).GetType());
                e.bypassCall = true;
            }
            else if (instruction.ToString().Contains("System.Object System.Reflection.MethodBase::Invoke"))
            {
                sender.ValueStack.CallStack.Pop();
                sender.ValueStack.CallStack.Pop();
                sender.ValueStack.CallStack.Pop();
                sender.ValueStack.CallStack.Push(1);
                e.bypassCall = true;
            }
            else if (instruction is MethodDef && ((MethodDef)instruction).IsNative)
            {
                dynamic             value     = sender.ValueStack.CallStack.Pop();
                MethodDef           methodsss = (MethodDef)instruction;
                dnlib.IO.FileOffset offset    = ModuleDefMD.Metadata.PEImage.ToFileOffset(methodsss.RVA);
                uint abc = (uint)Test(File.ReadAllBytes(Program.Path), (ulong)offset, (uint)value);
                sender.ValueStack.CallStack.Push((int)abc);
                e.bypassCall = true;
            }
            else if (e.Instruction.Operand.ToString()
                     .Contains(
                         "System.Void System.Runtime.CompilerServices.RuntimeHelpers::InitializeArray(System.Array,System.RuntimeFieldHandle")
                     )
            {
                dynamic stack2 = sender.ValueStack.CallStack.Pop();
                dynamic stack1 = sender.ValueStack.CallStack.Pop();
                sender.ValueStack.CallStack.Pop();
                FieldDef fielddef = ModuleDefMD.ResolveToken(stack2) as FieldDef;
                byte[]   test     = fielddef.InitialValue;
                uint[]   decoded  = new uint[test.Length / 4];
                Buffer.BlockCopy(test, 0, decoded, 0, test.Length);
                stack1 = decoded;
                sender.ValueStack.CallStack.Push(stack1);
                e.bypassCall = true;
            }
        }
Beispiel #26
0
        TypeSig ReadTypeRef(BinaryReader reader, GenericParamContext gpContext)
        {
            var etype = (ElementType)reader.ReadInt32();

            switch (etype)
            {
            case ElementType.Void: return(module.CorLibTypes.Void);

            case ElementType.Boolean: return(module.CorLibTypes.Boolean);

            case ElementType.Char: return(module.CorLibTypes.Char);

            case ElementType.I1: return(module.CorLibTypes.SByte);

            case ElementType.U1: return(module.CorLibTypes.Byte);

            case ElementType.I2: return(module.CorLibTypes.Int16);

            case ElementType.U2: return(module.CorLibTypes.UInt16);

            case ElementType.I4: return(module.CorLibTypes.Int32);

            case ElementType.U4: return(module.CorLibTypes.UInt32);

            case ElementType.I8: return(module.CorLibTypes.Int64);

            case ElementType.U8: return(module.CorLibTypes.UInt64);

            case ElementType.R4: return(module.CorLibTypes.Single);

            case ElementType.R8: return(module.CorLibTypes.Double);

            case ElementType.String: return(module.CorLibTypes.String);

            case ElementType.TypedByRef: return(module.CorLibTypes.TypedReference);

            case ElementType.I: return(module.CorLibTypes.IntPtr);

            case ElementType.U: return(module.CorLibTypes.UIntPtr);

            case ElementType.Object: return(module.CorLibTypes.Object);

            case ElementType.ValueType:
            case ElementType.Var:
            case ElementType.MVar:
                return((module.ResolveToken(reader.ReadUInt32(), gpContext) as ITypeDefOrRef).ToTypeSig());

            case ElementType.GenericInst:
                etype = (ElementType)reader.ReadInt32();
                if (etype == ElementType.ValueType)
                {
                    return((module.ResolveToken(reader.ReadUInt32(), gpContext) as ITypeDefOrRef).ToTypeSig());
                }
                // ElementType.Class
                return(module.CorLibTypes.Object);

            case ElementType.Ptr:
            case ElementType.Class:
            case ElementType.Array:
            case ElementType.FnPtr:
            case ElementType.SZArray:
            case ElementType.ByRef:
            case ElementType.CModReqd:
            case ElementType.CModOpt:
            case ElementType.Internal:
            case ElementType.Sentinel:
            case ElementType.Pinned:
            default:
                return(module.CorLibTypes.Object);
            }
        }
        public static dnlib.DotNet.Emit.Instruction CreateInstr(Instruction instr, MethodDef meth)
        {
            switch (instr.Code)
            {
            case OpCode.Add:
                Stack.Pop();
                Stack.Pop();
                return(dnlib.DotNet.Emit.Instruction.Create(OpCodes.Add));

            case OpCode.Call:
                Tuple <short, int, bool> tuple = (Tuple <short, int, bool>)instr.Operand;
                ModuleDefMD str = ModuleDefMD.Load(GetReference(tuple.Item1));
                IMethod     meh = (IMethod)str.ResolveToken((uint)tuple.Item2);
                module.Import(meh);
                return(dnlib.DotNet.Emit.Instruction.Create(OpCodes.Call, module.Import(meh)));

            case OpCode.Cgt:
                Stack.Pop();
                Stack.Pop();
                return(dnlib.DotNet.Emit.Instruction.Create(OpCodes.Cgt));

            case OpCode.Clt:
                Stack.Pop();
                Stack.Pop();
                return(dnlib.DotNet.Emit.Instruction.Create(OpCodes.Clt));

            //  case OpCode.Cmp:
            //    return dnlib.DotNet.Emit.Instruction.Create(OpCodes.C);
            case OpCode.Div:
                Stack.Pop();
                Stack.Pop();
                return(dnlib.DotNet.Emit.Instruction.Create(OpCodes.Div));

            case OpCode.Dup:
                object value = Stack.Pop();
                Stack.Push(value);
                Stack.Push(value);
                return(dnlib.DotNet.Emit.Instruction.Create(OpCodes.Dup));

            case OpCode.Jf:
                Stack.Pop();
                return(dnlib.DotNet.Emit.Instruction.Create(OpCodes.Ldstr, string.Format("BrFalse|{0}", meth.Body.Instructions[(int)instr.Operand])));

            case OpCode.Jmp:
                return(dnlib.DotNet.Emit.Instruction.Create(OpCodes.Ldstr, string.Format("Br|{0}", meth.Body.Instructions[(int)instr.Operand])));

            case OpCode.Jt:
                Stack.Pop();
                return(dnlib.DotNet.Emit.Instruction.Create(OpCodes.Ldstr, string.Format("BrTrue|{0}", meth.Body.Instructions[(int)instr.Operand])));

            case OpCode.Int32:
                Stack.Push((int)instr.Operand);
                return(dnlib.DotNet.Emit.Instruction.Create(OpCodes.Ldc_I4, (int)instr.Operand));

            case OpCode.Ldarg:
                //A fix
                Stack.Push(meth.Parameters[(int)((short)instr.Operand)]);
                return(dnlib.DotNet.Emit.Instruction.Create(ldarg(Convert.ToInt32(instr.Operand))));

            case OpCode.Ldfld:
                Stack.Pop();
                int      item2 = ((Tuple <short, int>)instr.Operand).Item2;
                FieldDef fld   = module.ResolveField((uint)item2);
                Stack.Push(fld.InitialValue);
                return(dnlib.DotNet.Emit.Instruction.Create(OpCodes.Ldfld, fld));

            case OpCode.Ldloc:
                //A fix
                Local l = meth.Body.Variables[(short)instr.Operand];
                Stack.Push(l);
                return(dnlib.DotNet.Emit.Instruction.Create(OpCodes.Ldloc, l));

            case OpCode.Mul:
                return(dnlib.DotNet.Emit.Instruction.Create(OpCodes.Mul));

            case OpCode.Int64:
                Stack.Push((int)instr.Operand);
                return(dnlib.DotNet.Emit.Instruction.Create(OpCodes.Ldc_I8, (long)instr.Operand));

            case OpCode.Newarr:
                Stack.Pop();
                Tuple <short, int> tuple3 = (Tuple <short, int>)instr.Operand;
                Stack.Push(module.ResolveTypeDef((uint)tuple3.Item2));
                return(dnlib.DotNet.Emit.Instruction.Create(OpCodes.Newarr, module.ResolveTypeDef((uint)tuple3.Item2)));

            case OpCode.Null:
                return(dnlib.DotNet.Emit.Instruction.Create(OpCodes.Nop));

            case OpCode.Pop:
                Stack.Pop();
                return(dnlib.DotNet.Emit.Instruction.Create(OpCodes.Pop));

            case OpCode.Ret:
                return(dnlib.DotNet.Emit.Instruction.Create(OpCodes.Ret));

            case OpCode.Stfld:
                Stack.Pop();
                int item22 = ((Tuple <short, int>)instr.Operand).Item2;
                return(dnlib.DotNet.Emit.Instruction.Create(OpCodes.Stfld, module.ResolveField((uint)item22)));

            case OpCode.Stloc:

                var   loc = Stack.Pop();
                Local ll  = meth.Body.Variables.Add(new Local(module.Import(loc.GetType()).ToTypeSig()));
                return(dnlib.DotNet.Emit.Instruction.Create(OpCodes.Stloc, ll));

            case OpCode.String:
                Stack.Push((string)instr.Operand);
                return(dnlib.DotNet.Emit.Instruction.Create(OpCodes.Ldstr, (string)instr.Operand));

            default:
                return(dnlib.DotNet.Emit.Instruction.Create(OpCodes.Nop));
            }
        }
Beispiel #28
0
 protected override IField ReadInlineField(Instruction instr)
 {
     return(module.ResolveToken(reader.ReadUInt32(), gpContext) as IField);
 }
        public static void delegateReplacer(ModuleDefMD module)
        {
            int amoiunt = 0;

            foreach (TypeDef types in module.GetTypes())
            {
                foreach (MethodDef methods in types.Methods)
                {
                    if (!methods.HasBody)
                    {
                        continue;
                    }
                    for (int i = 0; i < methods.Body.Instructions.Count; i++)
                    {
                        Instruction inst = methods.Body.Instructions[i];

                        if (inst.OpCode == OpCodes.Call && inst.Operand is MethodDef)
                        {
                            var mtd = (MethodDef)inst.Operand;

                            if (mtd.Name != "Invoke")
                            {
                                continue;
                            }

                            // Get ldsfld above
                            int x = i;
                            while (x >= 0)
                            {
                                Instruction xInst = methods.Body.Instructions[x];
                                if (xInst.OpCode == OpCodes.Ldsfld && xInst.Operand is FieldDef)
                                {
                                    FieldDef fd = (FieldDef)xInst.Operand;
                                    if (fd.FieldSig.Type.IsOptionalModifier)
                                    {
                                        break;
                                    }
                                }
                                x--;
                            }

                            if (x < 0)
                            {
                                continue;
                            }


                            FieldDef fie = (FieldDef)methods.Body.Instructions[x].Operand;

                            foreach (DelegateInfo2 delegateInfo in ListedDelegateInfo2s)
                            {
                                if (delegateInfo.fieldDef == fie)
                                {
                                    var abc = module.ResolveToken(delegateInfo.mdtoken);

                                    if (abc != null)
                                    {
                                        methods.Body.Instructions[i].OpCode  = delegateInfo.opcode;
                                        methods.Body.Instructions[i].Operand = abc;


                                        methods.Body.Instructions[x].OpCode = OpCodes.Nop;
                                        amoiunt++;
                                    }
                                    break;
                                }
                            }
                        }
                    }
                }
            }
        }