Exemplo n.º 1
0
        void EnumModules()
        {
            this.Text = "Modules from " + ProcessName + " whit PID=" + procid.ToString();
            modules   = ProcModule.GetModuleInfos(procid);

            if (modules != null && modules.Length > 0)
            {
                for (int i = 0; i < modules.Length; i++)
                {
                    Graphics g          = lvmodules.CreateGraphics();
                    Font     objFont    = new Font("Microsoft Sans Serif", 8);
                    SizeF    stringSize = new SizeF();
                    stringSize = g.MeasureString(modules[i].baseName, objFont);
                    int processlenght = (int)(stringSize.Width + lvmodules.Margin.Horizontal * 2);

                    if (processlenght > modulename.Width)
                    {
                        modulename.Width = processlenght;
                    }

                    string[] prcdetails = new string[] { modules[i].baseName, modules[i].baseOfDll.ToString("X8"),
                                                         modules[i].sizeOfImage.ToString("X8"), modules[i].entryPoint.ToString("X8") };
                    ListViewItem proc = new ListViewItem(prcdetails);
                    lvmodules.Items.Add(proc);
                }
            }
        }
Exemplo n.º 2
0
        public static bool IsValid(this IntPtr ptr, ProcModule module = null)
        {
            if (MiniMem.AttachedProcess.ProcessHandle == IntPtr.Zero)
            {
                throw new Exception("Please attach to the game first!");
            }

            if (ptr == IntPtr.Zero)
            {
                return(false);
            }

            if (module != null)
            {
                return(ptr.ToInt32() >= module.BaseAddress.ToInt32() &&
                       ptr.ToInt32() <= module.EndAddress.ToInt32());
            }

            ProcModule pm = MiniMem.FindProcessModule(MiniMem.AttachedProcess.ProcessObject.ProcessName);             // Get "main" module

            if (pm != null)
            {
                return(ptr.ToInt32() >= pm.BaseAddress.ToInt32() &&
                       ptr.ToInt32() <= pm.EndAddress.ToInt32());
            }

            return(ptr != IntPtr.Zero);
        }
Exemplo n.º 3
0
        static void WriteUnicodeString(IntPtr Address, string istring)
        {
            UnicodeEncoding Unicode = new UnicodeEncoding();

            byte[] ubytes    = Unicode.GetBytes(istring);
            uint   BytesRead = 0;

            ProcModule.WriteProcessMemory(hprocess, Address, ubytes, (uint)ubytes.Length, out BytesRead);
        }
Exemplo n.º 4
0
        void Button4Click(object sender, EventArgs e)
        {
            OpenFileDialog fdlg = new OpenFileDialog();

            fdlg.Title            = "Browse for target dll:";
            fdlg.InitialDirectory = @"c:\";
            if (DirectoryName != "")
            {
                fdlg.InitialDirectory = DirectoryName;
            }
            fdlg.Filter           = "All files (*.dll)|*.dll";
            fdlg.FilterIndex      = 2;
            fdlg.RestoreDirectory = true;
            fdlg.Multiselect      = false;
            if (fdlg.ShowDialog() == DialogResult.OK)
            {
                string FileName  = fdlg.FileName;
                int    lastslash = FileName.LastIndexOf("\\");
                if (lastslash != -1)
                {
                    DirectoryName = FileName.Remove(lastslash, FileName.Length - lastslash);
                }
                if (DirectoryName.Length == 2)
                {
                    DirectoryName = DirectoryName + "\\";
                }

                string error      = "";
                string libname    = fdlg.FileName;
                IntPtr retaddress = ProcModule.InjectLibraryInternal((uint)procid, libname, out error);
                if (retaddress == IntPtr.Zero)
                {
                    label2.ForeColor = Color.Red;
                    label2.Text      = "Error: " + error;
                }
                else
                {
                    label2.ForeColor = Color.Blue;
                    label2.Text      = "Dll injected at address: " + retaddress.ToString("X8");
                    lvmodules.Items.Clear();
                    EnumModules();
                }
            }
        }
Exemplo n.º 5
0
 void FreeModuleToolStripMenuItemClick(object sender, EventArgs e)
 {
     if (lvmodules.SelectedIndices.Count > 0)
     {
         string libaddress    = lvmodules.Items[lvmodules.SelectedIndices[0]].SubItems[1].Text;
         IntPtr libaddressptr = (IntPtr)System.Convert.ToInt32(libaddress, 16);
         string error         = "";
         if (!ProcModule.FreeLibraryInternal((uint)procid, libaddressptr, out error))
         {
             label2.ForeColor = Color.Red;
             label2.Text      = "Error: " + error;
         }
         else
         {
             label2.ForeColor = Color.Blue;
             label2.Text      = "Dll free succesfully!";
             lvmodules.Items.Clear();
             EnumModules();
         }
     }
 }
Exemplo n.º 6
0
        public static bool WriteDump(uint processId, string fileName, DType dumpTyp)
        {
            IntPtr hProcess = OpenProcess(PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION | PROCESS_VM_OPERATION | PROCESS_VM_WRITE | PROCESS_VM_READ | PROCESS_TERMINATE, 0, (uint)processId);

            if (hProcess == IntPtr.Zero)
            {
                IntPtr pDACL, pSecDesc;

                GetSecurityInfo((int)Process.GetCurrentProcess().Handle, /*SE_KERNEL_OBJECT*/ 6, /*DACL_SECURITY_INFORMATION*/ 4, 0, 0, out pDACL, IntPtr.Zero, out pSecDesc);
                hProcess = OpenProcess(0x40000, 0, processId);
                SetSecurityInfo((int)hProcess, /*SE_KERNEL_OBJECT*/ 6, /*DACL_SECURITY_INFORMATION*/ 4 | /*UNPROTECTED_DACL_SECURITY_INFORMATION*/ 0x20000000, 0, 0, pDACL, IntPtr.Zero);
                ProcModule.CloseHandle(hProcess);
                hProcess = OpenProcess(PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION | PROCESS_VM_OPERATION | PROCESS_VM_WRITE | PROCESS_VM_READ | PROCESS_TERMINATE, 0, processId);
            }

            if (hProcess == IntPtr.Zero)
            {
                return(false);
            }
            else
            {
                using (var fs = new System.IO.FileStream(fileName, System.IO.FileMode.Create, System.IO.FileAccess.Write, System.IO.FileShare.None))
                {
                    MiniDumpExceptionInformation exp;
                    exp.ThreadId           = GetCurrentThreadId();
                    exp.ClientPointers     = false;
                    exp.ExceptioonPointers = System.Runtime.InteropServices.Marshal.GetExceptionPointers();

                    bool bRet = MiniDumpWriteDump(
                        GetCurrentProcess(),
                        GetCurrentProcessId(),
                        fs.SafeFileHandle.DangerousGetHandle(),
                        (uint)dumpTyp,
                        ref exp,
                        IntPtr.Zero,
                        IntPtr.Zero);
                    return(bRet);
                }
            }
        }
Exemplo n.º 7
0
        static IntPtr CorBindToRuntimeExAddress()
        {
            ProcModule.ModuleInfo   targetmscoree = null;
            ProcModule.ModuleInfo[] modules       = ProcModule.GetModuleInfos((int)processid);

            if (modules != null && modules.Length > 0)
            {
                for (int i = 0; i < modules.Length; i++)
                {
                    if (modules[i].baseName.ToLower().Contains("mscoree.dll"))
                    {
                        targetmscoree = modules[i];
                        break;
                    }
                }
            }


            if (targetmscoree == null || targetmscoree.baseOfDll == IntPtr.Zero)
            {
                return(IntPtr.Zero);
            }

            IntPtr CLRCreateInstanceAddress = IntPtr.Zero;

            if (hprocess != IntPtr.Zero)
            {
                int CLRCreateInstancerva = ExportTable.ProcGetExpAddress
                                               (hprocess, targetmscoree.baseOfDll, "CorBindToRuntimeEx");
                if (CLRCreateInstancerva == 0)
                {
                    return(IntPtr.Zero);
                }

                return((IntPtr)((long)targetmscoree.baseOfDll + (long)CLRCreateInstancerva));
            }
            return(IntPtr.Zero);
        }
Exemplo n.º 8
0
        void HoockDetect()
        {
            textBox1.Text = "Detecting hooks for process whit the name " + ProcessName + " and PID=" + procid.ToString() + "\r\n";

            byte[] Forread        = new byte[0x500];
            uint   BytesRead      = 0;
            int    CompileAddress = 0;
            IntPtr processHandle  = IntPtr.Zero;

            try
            {
                processHandle = OpenProcess(ProcessAccess.QueryInformation | ProcessAccess.VMRead, false, (uint)procid);
            }
            catch
            {
            }
            if (processHandle != IntPtr.Zero)
            {
                ProcModule.ModuleInfo   targetmscorjit = null;
                ProcModule.ModuleInfo[] modules        = ProcModule.GetModuleInfos(procid);

                if (modules != null && modules.Length > 0)
                {
                    for (int i = 0; i < modules.Length; i++)
                    {
                        if (modules[i].baseName.ToLower().Contains("mscorjit"))
                        {
                            targetmscorjit = modules[i];
                            break;
                        }
                    }
                }

                if (targetmscorjit == null)
                {
                    textBox1.Text = textBox1.Text + "Seems that the target process is not a .NET process!" + "\r\n";
                }
                else
                {
                    int  getJitrva = ExportTable.ProcGetExpAddress(processHandle, targetmscorjit.baseOfDll, "getJit");
                    bool isok      = false;
                    isok = ReadProcessMemory(processHandle,
                                             (IntPtr)((long)targetmscorjit.baseOfDll + (long)getJitrva), Forread, (uint)Forread.Length, ref BytesRead);
                    if (isok)
                    {
                        int count = 0;
                        while (Forread[count] != 0x0C3)
                        {
                            count++;
                        }

                        long cmpointer = (long)targetmscorjit.baseOfDll + getJitrva + count + 1;
                        textBox1.Text = textBox1.Text + "Pointer of compile method : " + cmpointer.ToString("X8") + "\r\n";

                        CompileAddress = BitConverter.ToInt32(Forread, count + 1);
                        textBox1.Text  = textBox1.Text + "Address of compile method is : " + CompileAddress.ToString("X8") + "\r\n";

                        if ((CompileAddress < (int)targetmscorjit.baseOfDll) || (CompileAddress > (int)targetmscorjit.baseOfDll + targetmscorjit.sizeOfImage))
                        {
                            textBox1.Text = textBox1.Text + "Address of compile method changed!!!" + "\r\n";
                        }
                        else
                        {
                            textBox1.Text = textBox1.Text +
                                            "Address of compile method seems to be the original one!" + "\r\n";
                        }
                    }
                    else
                    {
                        textBox1.Text = textBox1.Text + "Failed to read from selected process!" + "\r\n";
                    }
                    ProcModule.CloseHandle(processHandle);
                } // end if is not .NET
            }
            else
            {
                textBox1.Text = textBox1.Text + "Failed to open selected process!" + "\r\n";
            }
        }
Exemplo n.º 9
0
        /// <summary>
        /// 检测登录二维码是否已经扫描
        /// </summary>
        /// <param name="qqActionListener"></param>
        public void CheckQRCode(QQActionEventHandler qqActionListener)
        {
            ProcModule module = GetModule <ProcModule>(QQModuleType.PROC);

            module.CheckQRCode(qqActionListener);
        }
Exemplo n.º 10
0
        public static void HostCLR_RunMethod(String AssemblyPath, String TypeName, String MethodName, String Args, String Version)
        {
            hprocess = ProcModule.OpenProcess(ProcModule.PROCESS_QUERY_INFORMATION | ProcModule.PROCESS_VM_OPERATION | ProcModule.PROCESS_VM_WRITE | ProcModule.PROCESS_VM_READ | ProcModule.PROCESS_CREATE_THREAD, 0, (uint)processid);
            IntPtr CorBindToRuntimeExPtr = CorBindToRuntimeExAddress();
            uint   BytesRead             = 0;

            IntPtr codeCave_Code           = ProcModule.VirtualAllocEx(hprocess, IntPtr.Zero, 500, ProcModule.AllocationType.Commit, ProcModule.MemoryProtection.ExecuteReadWrite);
            IntPtr CLSID_CLRRuntimeHostPtr = ProcModule.VirtualAllocEx(hprocess, IntPtr.Zero, (uint)CLSID_CLRRuntimeHost.Length * 4, ProcModule.AllocationType.Commit, ProcModule.MemoryProtection.ReadWrite);
            IntPtr IID_ICLRRuntimeHostPtr  = ProcModule.VirtualAllocEx(hprocess, IntPtr.Zero, (uint)IID_ICLRRuntimeHost.Length, ProcModule.AllocationType.Commit, ProcModule.MemoryProtection.ReadWrite);
            IntPtr ClrHostPtr = ProcModule.VirtualAllocEx(hprocess, IntPtr.Zero, 04, ProcModule.AllocationType.Commit, ProcModule.MemoryProtection.ReadWrite);
            IntPtr dwRetPtr   = ProcModule.VirtualAllocEx(hprocess, IntPtr.Zero, 0x4, ProcModule.AllocationType.Commit, ProcModule.MemoryProtection.ReadWrite);

            IntPtr AssemblyPathPtr = ProcModule.VirtualAllocEx(hprocess, IntPtr.Zero, (uint)(AssemblyPath.Length * 2 + 2), ProcModule.AllocationType.Commit, ProcModule.MemoryProtection.ReadWrite);
            IntPtr TypeNamePtr     = ProcModule.VirtualAllocEx(hprocess, IntPtr.Zero, (uint)(TypeName.Length * 2 + 2), ProcModule.AllocationType.Commit, ProcModule.MemoryProtection.ReadWrite);
            IntPtr MethodNamePtr   = ProcModule.VirtualAllocEx(hprocess, IntPtr.Zero, (uint)(MethodName.Length * 2 + 2), ProcModule.AllocationType.Commit, ProcModule.MemoryProtection.ReadWrite);
            IntPtr ArgsPtr         = ProcModule.VirtualAllocEx(hprocess, IntPtr.Zero, (uint)(Args.Length * 2 + 2), ProcModule.AllocationType.Commit, ProcModule.MemoryProtection.ReadWrite);

            IntPtr BuildFlavorPtr = ProcModule.VirtualAllocEx(hprocess, IntPtr.Zero, 0x10, ProcModule.AllocationType.Commit, ProcModule.MemoryProtection.ReadWrite);

            ProcModule.WriteProcessMemory(hprocess, CLSID_CLRRuntimeHostPtr, CLSID_CLRRuntimeHost, (uint)CLSID_CLRRuntimeHost.Length, out BytesRead);
            ProcModule.WriteProcessMemory(hprocess, IID_ICLRRuntimeHostPtr, IID_ICLRRuntimeHost, (uint)IID_ICLRRuntimeHost.Length, out BytesRead);
            WriteUnicodeString(BuildFlavorPtr, "wks");
            WriteUnicodeString(AssemblyPathPtr, AssemblyPath);
            WriteUnicodeString(TypeNamePtr, TypeName);
            WriteUnicodeString(MethodNamePtr, MethodName);
            WriteUnicodeString(ArgsPtr, Args);

            InlineASM inline = new InlineASM();

            inline.PushOffset(ClrHostPtr);
            inline.PushOffset(IID_ICLRRuntimeHostPtr);
            inline.PushOffset(CLSID_CLRRuntimeHostPtr);
            inline.PushByte(0);
            inline.PushOffset(BuildFlavorPtr);
            inline.PushByte(0);
            inline.MovEaxValue(CorBindToRuntimeExPtr);
            inline.CallEax(); // call CorBindToRuntimeEx

            inline.MovEaxDwordPtr(ClrHostPtr);
            inline.MovEcxDwordPtrEax();
            inline.MovEdxDwordPtrEcxOffset(0x0C);
            inline.PushEax();
            inline.CallEdx(); // pClrHost->Start();

            inline.PushOffset(dwRetPtr);
            inline.PushOffset(ArgsPtr);
            inline.PushOffset(MethodNamePtr);
            inline.PushOffset(TypeNamePtr);
            inline.PushOffset(AssemblyPathPtr);
            inline.MovEaxDwordPtr(ClrHostPtr);
            inline.MovEcxDwordPtrEax();
            inline.PushEax();
            inline.MovEaxDwordPtrEcxOffset(0x2C);
            inline.CallEax(); // pClrHost->ExecuteInDefaultAppDomain

            inline.Retn();
            ProcModule.WriteProcessMemory(hprocess, codeCave_Code, inline.asm, (uint)inline.asm.Length, out BytesRead);

            IntPtr hThread = ProcModule.CreateRemoteThread(hprocess, IntPtr.Zero, 0,
                                                           codeCave_Code, IntPtr.Zero, 0, IntPtr.Zero);

/*
 * if (ProcModule.WaitForSingleObject(hThread,uint.MaxValue)!=0)
 * {
 * return;
 * }
 */

            IntPtr retcode = IntPtr.Zero;

            if (!ProcModule.GetExitCodeThread(hThread, out retcode))
            {
                return;
            }

            ProcModule.CloseHandle(hprocess);
        }
Exemplo n.º 11
0
        void DumpModule()
        {
            IntPtr hProcess = OpenProcess(PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION | PROCESS_VM_OPERATION | PROCESS_VM_WRITE | PROCESS_VM_READ | PROCESS_TERMINATE, 0, (uint)procid);

            if (hProcess == IntPtr.Zero)
            {
                IntPtr pDACL, pSecDesc;

                GetSecurityInfo((int)Process.GetCurrentProcess().Handle, /*SE_KERNEL_OBJECT*/ 6, /*DACL_SECURITY_INFORMATION*/ 4, 0, 0, out pDACL, IntPtr.Zero, out pSecDesc);
                hProcess = OpenProcess(0x40000, 0, (uint)procid);
                SetSecurityInfo((int)hProcess, /*SE_KERNEL_OBJECT*/ 6, /*DACL_SECURITY_INFORMATION*/ 4 | /*UNPROTECTED_DACL_SECURITY_INFORMATION*/ 0x20000000, 0, 0, pDACL, IntPtr.Zero);
                ProcModule.CloseHandle(hProcess);
                hProcess = OpenProcess(PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION | PROCESS_VM_OPERATION | PROCESS_VM_WRITE | PROCESS_VM_READ | PROCESS_TERMINATE, 0, (uint)procid);
            }

            if (hProcess != IntPtr.Zero)
            {
                string newdirname = DirName;
                if (DirName.Length < 2 || !Directory.Exists(DirName))
                {
                    newdirname = "C:\\";
                }

                newdirname = Path.Combine(DirName, "Dumps");
                System.IO.Directory.CreateDirectory(newdirname);
                int    ImageBase  = System.Convert.ToInt32(lvmodules.Items[lvmodules.SelectedIndices[0]].SubItems[1].Text, 16);
                string moduleName = lvmodules.Items[lvmodules.SelectedIndices[0]].SubItems[0].Text;

                bool isok;
                uint speed = 0x1000;

                try
                {
                    SYSTEM_INFO pSI = new SYSTEM_INFO();
                    GetSystemInfo(ref pSI);
                    speed = pSI.dwPageSize;
                }
                catch
                {
                }

                byte[] bigMem    = new byte[speed];
                byte[] InfoKeep  = new byte[8];
                uint   BytesRead = 0;

                int    nrofsection   = 0;
                byte[] Dump          = null;
                byte[] Partkeep      = null;
                int    filealignment = 0;
                int    rawaddress;
                int    address          = 0;
                int    offset           = 0;
                bool   ShouldFixrawsize = false;

                isok = ReadProcessMemory(hProcess, (uint)(ImageBase + 0x03C), InfoKeep, 4, ref BytesRead);
                int PEOffset = BitConverter.ToInt32(InfoKeep, 0);

                try
                {
                    isok = ReadProcessMemory(hProcess, (uint)(ImageBase + PEOffset + 0x0F8 + 20), InfoKeep, 4, ref BytesRead);
                    byte[] PeHeader = new byte[speed];

                    rawaddress = BitConverter.ToInt32(InfoKeep, 0);
                    int sizetocopy = rawaddress;
                    if (sizetocopy > speed)
                    {
                        sizetocopy = (int)speed;
                    }
                    isok   = ReadProcessMemory(hProcess, (uint)(ImageBase), PeHeader, (uint)sizetocopy, ref BytesRead);
                    offset = offset + rawaddress;

                    nrofsection = (int)BitConverter.ToInt16(PeHeader, PEOffset + 0x06);
                    int sectionalignment = BitConverter.ToInt32(PeHeader, PEOffset + 0x038);
                    filealignment = BitConverter.ToInt32(PeHeader, PEOffset + 0x03C);

                    int sizeofimage = BitConverter.ToInt32(PeHeader, PEOffset + 0x050);

                    int calculatedimagesize = BitConverter.ToInt32(PeHeader, PEOffset + 0x0F8 + 012);

                    for (int i = 0; i < nrofsection; i++)
                    {
                        int virtualsize = BitConverter.ToInt32(PeHeader, PEOffset + 0x0F8 + 0x28 * i + 08);
                        int toadd       = (virtualsize % sectionalignment);
                        if (toadd != 0)
                        {
                            toadd = sectionalignment - toadd;
                        }
                        calculatedimagesize = calculatedimagesize + virtualsize + toadd;
                    }

                    if (calculatedimagesize > sizeofimage)
                    {
                        sizeofimage = calculatedimagesize;
                    }
                    Dump = new byte[sizeofimage];
                    Array.Copy(PeHeader, Dump, sizetocopy);
                    Partkeep = new byte[sizeofimage];
                }
                catch
                {
                }


                int calcrawsize = 0;
                for (int i = 0; i < nrofsection; i++)
                {
                    int rawsize, virtualsize, virtualAddress;
                    for (int l = 0; l < nrofsection; l++)
                    {
                        rawsize        = BitConverter.ToInt32(Dump, PEOffset + 0x0F8 + 0x28 * l + 16);
                        virtualsize    = BitConverter.ToInt32(Dump, PEOffset + 0x0F8 + 0x28 * l + 08);
                        virtualAddress = BitConverter.ToInt32(Dump, PEOffset + 0x0F8 + 0x28 * l + 012);

                        // RawSize = Virtual Size rounded on FileAlligment
                        calcrawsize = 0;
                        calcrawsize = virtualsize % filealignment;
                        if (calcrawsize != 0)
                        {
                            calcrawsize = filealignment - calcrawsize;
                        }
                        calcrawsize = virtualsize + calcrawsize;

                        if (calcrawsize != 0 && rawsize != calcrawsize && rawsize != virtualsize)
                        {
                            ShouldFixrawsize = true;
                            break;
                        }
                    }

                    rawsize     = BitConverter.ToInt32(Dump, PEOffset + 0x0F8 + 0x28 * i + 16);
                    virtualsize = BitConverter.ToInt32(Dump, PEOffset + 0x0F8 + 0x28 * i + 08);
                    // RawSize = Virtual Size rounded on FileAlligment
                    virtualAddress = BitConverter.ToInt32(Dump, PEOffset + 0x0F8 + 0x28 * i + 012);


                    if (ShouldFixrawsize)
                    {
                        rawsize = virtualsize;
                        BinaryWriter writer = new BinaryWriter(new MemoryStream(Dump));
                        writer.BaseStream.Position = PEOffset + 0x0F8 + 0x28 * i + 16;
                        writer.Write(virtualsize);
                        writer.BaseStream.Position = PEOffset + 0x0F8 + 0x28 * i + 20;
                        writer.Write(virtualAddress);
                        writer.Close();
                    }



                    address = BitConverter.ToInt32(Dump, PEOffset + 0x0F8 + 0x28 * i + 12);

                    isok = ReadProcessMemory(hProcess, (uint)(ImageBase + address), Partkeep, (uint)rawsize, ref BytesRead);
                    if (!isok)
                    {
                        byte[] onepage = new byte[512];
                        for (int c = 0; c < virtualsize; c = c + 512)
                        {
                            isok = ReadProcessMemory(hProcess, (uint)(ImageBase + virtualAddress + c), onepage, (uint)512, ref BytesRead);
                            Array.Copy(onepage, 0, Partkeep, c, 512);
                        }
                    }


                    if (ShouldFixrawsize)
                    {
                        Array.Copy(Partkeep, 0, Dump, virtualAddress, rawsize);
                        offset = virtualAddress + rawsize;
                    }
                    else
                    {
                        Array.Copy(Partkeep, 0, Dump, offset, rawsize);
                        offset = offset + rawsize;
                    }
                }



                if (Dump != null && Dump.Length > 0 && Dump.Length >= offset)
                {
                    int ImportDirectoryRva = BitConverter.ToInt32(Dump, PEOffset + 0x080);
                    if (ImportDirectoryRva > 0 && ImportDirectoryRva < offset)
                    {
                        int current    = 0;
                        int ThunkToFix = 0;
                        int ThunkData  = 0;
                        isok = ReadProcessMemory(hProcess, (uint)(ImageBase + ImportDirectoryRva + current + 12), Partkeep, 4, ref BytesRead);
                        int NameOffset = BitConverter.ToInt32(Partkeep, 0);
                        while (isok && NameOffset != 0)
                        {
                            byte[] mscoreeAscii = { 0x6D, 0x73, 0x63, 0x6F, 0x72, 0x65, 0x65, 0x2E, 0x64, 0x6C, 0x6C, 0x00 };
                            byte[] NameKeeper   = new byte[mscoreeAscii.Length];
                            isok = ReadProcessMemory(hProcess, (uint)(ImageBase + NameOffset), NameKeeper, (uint)mscoreeAscii.Length, ref BytesRead);
                            if (isok && BytesEqual(NameKeeper, mscoreeAscii))
                            {
                                isok = ReadProcessMemory(hProcess, (uint)(ImageBase + ImportDirectoryRva + current), Partkeep, 4, ref BytesRead);
                                int OriginalFirstThunk = BitConverter.ToInt32(Partkeep, 0); // OriginalFirstThunk;
                                if (OriginalFirstThunk > 0 && OriginalFirstThunk < offset)
                                {
                                    isok      = ReadProcessMemory(hProcess, (uint)(ImageBase + OriginalFirstThunk), Partkeep, 4, ref BytesRead);
                                    ThunkData = BitConverter.ToInt32(Partkeep, 0);
                                    if (ThunkData > 0 && ThunkData < offset)
                                    {
                                        byte[] CorExeMain = { 0x5F, 0x43, 0x6F, 0x72, 0x45, 0x78, 0x65, 0x4D, 0x61, 0x69, 0x6E, 0x00 };
                                        byte[] CorDllMain = { 0x5F, 0x43, 0x6F, 0x72, 0x44, 0x6C, 0x6C, 0x4D, 0x61, 0x69, 0x6E, 0x00 };
                                        NameKeeper = new byte[CorExeMain.Length];
                                        isok       = ReadProcessMemory(hProcess, (uint)(ImageBase + ThunkData + 2), NameKeeper,
                                                                       (uint)CorExeMain.Length, ref BytesRead);
                                        if (isok && (BytesEqual(NameKeeper, CorExeMain) || BytesEqual(NameKeeper, CorDllMain)))
                                        {
                                            isok       = ReadProcessMemory(hProcess, (uint)(ImageBase + ImportDirectoryRva + current + 16), Partkeep, 4, ref BytesRead);
                                            ThunkToFix = BitConverter.ToInt32(Partkeep, 0); // FirstThunk;
                                            break;
                                        }
                                    }
                                }
                            }

                            current    = current + 20; // 20 size of IMAGE_IMPORT_DESCRIPTOR
                            isok       = ReadProcessMemory(hProcess, (uint)(ImageBase + ImportDirectoryRva + current + 12), Partkeep, 4, ref BytesRead);
                            NameOffset = BitConverter.ToInt32(Partkeep, 0);
                        }

                        if (ThunkToFix > 0 && ThunkToFix < offset)
                        {
                            BinaryWriter writer = new BinaryWriter(new MemoryStream(Dump));
                            isok = ReadProcessMemory(hProcess, (uint)(ImageBase + ThunkToFix), Partkeep, 4, ref BytesRead);
                            int ThunkValue = BitConverter.ToInt32(Partkeep, 0);
                            if (isok && (ThunkValue < 0 || ThunkValue > offset))
                            {
                                int fvirtualsize    = BitConverter.ToInt32(Dump, PEOffset + 0x0F8 + 08);
                                int fvirtualAddress = BitConverter.ToInt32(Dump, PEOffset + 0x0F8 + 012);
                                int frawAddress     = BitConverter.ToInt32(Dump, PEOffset + 0x0F8 + 20);
                                writer.BaseStream.Position = ThunkToFix - fvirtualAddress + frawAddress;
                                writer.Write(ThunkData);
                            }

                            int EntryPoint = BitConverter.ToInt32(Dump, PEOffset + 0x028);
                            if (EntryPoint <= 0 || EntryPoint > offset)
                            {
                                int ca = 0;
                                do
                                {
                                    isok = ReadProcessMemory(hProcess, (uint)(ImageBase + ThunkData + ca), Partkeep, 1, ref BytesRead);
                                    if (isok && Partkeep[0] == 0x0FF)
                                    {
                                        isok = ReadProcessMemory(hProcess, (uint)(ImageBase + ThunkData + ca + 1), Partkeep, 1, ref BytesRead);
                                        if (isok && Partkeep[0] == 0x025)
                                        {
                                            isok = ReadProcessMemory(hProcess, (uint)(ImageBase + ThunkData + ca + 2), Partkeep, 4, ref BytesRead);
                                            if (isok)
                                            {
                                                int RealEntryPoint = ThunkData + ca;
                                                writer.BaseStream.Position = PEOffset + 0x028;
                                                writer.Write(RealEntryPoint);
                                            }
                                        }
                                    }
                                    ca++;
                                }while (isok);
                            }
                            writer.Close();
                        }
                    }
                }

                if (Dump != null && Dump.Length > 0 && Dump.Length >= offset)
                {
                    FileStream fout;
                    string     filename = newdirname + "\\" + moduleName;
                    fout = new FileStream(filename, FileMode.Create);
                    fout.Write(Dump, 0, offset);
                    fout.Close();

                    label2.ForeColor = Color.Blue;
                    label2.Text      = "Module saved in " + filename;
                }
                else
                {
                    label2.ForeColor = Color.Red;
                    label2.Text      = "Failed to dump module!";
                }
            }
            else
            {
                label2.ForeColor = Color.Red;
                label2.Text      = "Failed to open process!";
            }
        }
Exemplo n.º 12
0
        void Button2Click(object sender, EventArgs e)
        {
            string filename    = textBox1.Text;
            string enviroments = textBox2.Text;

            if (filename != "" && File.Exists(filename))
            {
                int    processflags = processflags = 0 | (int)ProcessCreationFlags.CREATE_SUSPENDED;
                IntPtr memptr       = IntPtr.Zero;
                button2.Enabled = false;
                textBox3.Text   = "";
                GCHandle gchenv = new GCHandle();

                if (enviroments.Length != 0)
                {
                    if (enviroments.Length >= 3 && enviroments.Contains("="))
                    {
                        textBox3.AppendText("Setting Environment Variables...");

                        try
                        {
                            char[]   separator  = "\r\n".ToCharArray();
                            string[] realvalues = enviroments.Split(separator);
                            IntPtr   newptr     = memptr;
                            bool     unicode    = false;
                            if (Environment.OSVersion.Platform == PlatformID.Win32NT)
                            {
                                processflags = processflags | (int)ProcessCreationFlags.CREATE_UNICODE_ENVIRONMENT;
                                unicode      = true;
                            }
                            StringDictionary environmentVariables = new StringDictionary();

// add Environments of the parent to the child!
                            foreach (System.Collections.DictionaryEntry entry in Environment.GetEnvironmentVariables())
                            {
                                environmentVariables.Add((string)entry.Key, (string)entry.Value);
                            }

                            for (int i = 0; i < realvalues.Length; i++)
                            {
                                if (realvalues[i] != "" && realvalues[i].Contains("="))
                                {
                                    separator = "=".ToCharArray();
                                    string[] currentvalue = realvalues[i].Split(separator);
                                    if (currentvalue[0] != "")
                                    {
                                        if (environmentVariables.ContainsKey(currentvalue[0]))
                                        {
                                            textBox3.AppendText("\r\n" + "The key whit the name " +
                                                                currentvalue[0] + " is already on dictinonary!");
                                        }
                                        else
                                        {
                                            environmentVariables.Add(currentvalue[0], currentvalue[1]);
                                        }
                                    }
                                }
                            }


                            gchenv = GCHandle.Alloc(ToByteArray(environmentVariables, unicode), GCHandleType.Pinned);
                            memptr = gchenv.AddrOfPinnedObject();

                            textBox3.AppendText("\r\n" + "Environment Variables setted!");
                        }
                        catch (Exception exc)
                        {
                            textBox3.AppendText("\r\n" + exc.Message + "\r\n");
                        }
                    }
                    else
                    {
                        textBox3.AppendText("Invalid Environment Variables!" + "\r\n");
                    }
                }

                STARTUPINFO         structure           = new STARTUPINFO();
                PROCESS_INFORMATION process_information = new PROCESS_INFORMATION();
                IntPtr lpApplicationName = Marshal.StringToHGlobalUni(filename);
                try
                {
                    CreateProcess(lpApplicationName, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, 0, processflags, memptr, IntPtr.Zero, ref structure, ref process_information);
                    hprocess   = process_information.hProcess;
                    hcthread   = process_information.hThread;
                    cprocessid = process_information.dwProcessId;
                    if (gchenv.IsAllocated)
                    {
                        gchenv.Free();
                    }

                    textBox3.AppendText("\r\n" + "Process created");
                    if (checkBox1.Checked)
                    {
                        textBox3.AppendText(" on suspended mode");
                        button3.Enabled = true;
                    }
                    textBox3.AppendText("!" + "\r\n");
                }
                catch (Exception ex3)
                {
                    textBox3.AppendText("\r\n" + "Failed to start process whit the message" +
                                        ex3.Message + "\r\n");
                    return;
                }

                checktimer          = new System.Windows.Forms.Timer();
                checktimer.Interval = 30;
                checktimer.Enabled  = true;
                checktimer.Tick    += new System.EventHandler(CheckStatut);

                if (checkBox2.Checked)
                {
                    ProcModule.ModuleInfo[] modules = null;

                    for (int k = 0; k < 500; k++) // try it 500 times!
                    {
                        LoopWhileModulesAreLoadedNt(process_information.dwProcessId, process_information.hThread);
                        modules = ProcModule.GetModuleInfos((int)process_information.dwProcessId);
                        if (modules != null && modules.Length > 0)
                        {
                            for (int i = 0; i < modules.Length; i++)
                            {
                                if (modules[i].baseName.ToLower().Contains("kernel32"))
                                {
                                    targetkernel32 = modules[i];
                                    break;
                                }
                            }
                        }
                        if (targetkernel32 != null)
                        {
                            break;
                        }
                    }

                    if (targetkernel32 != null && targetkernel32.baseOfDll != IntPtr.Zero)
                    {
                        HookCreateProcess(targetkernel32.baseOfDll);
                    }
                }


                if (checkBox3.Checked)
                {
                    ProcModule.ModuleInfo[] modules = null;

                    for (int k = 0; k < 50; k++) // try it 50 times!
                    {
                        LoopWhileModulesAreLoadedNt(process_information.dwProcessId, process_information.hThread);
                        modules = ProcModule.GetModuleInfos((int)process_information.dwProcessId);
                        if (modules != null && modules.Length > 0)
                        {
                            for (int i = 0; i < modules.Length; i++)
                            {
                                if (modules[i].baseName.Length > 10 && modules[i].baseName.ToLower().StartsWith("msvcr"))
                                {
                                    targetMSVCR80 = modules[i];
                                    break;
                                }
                            }
                        }
                        if (targetMSVCR80 != null)
                        {
                            break;
                        }
                    }

                    if (targetMSVCR80 != null && targetMSVCR80.baseOfDll != IntPtr.Zero)
                    {
                        LogmemcpyInit(targetMSVCR80.baseOfDll);
                    }
                }


                if (!checkBox1.Checked)
                {
                    ResumeThread(process_information.hThread);
                }
            }
            else
            {
                textBox3.Text = "Please select a valid file!" + "\r\n";
            }
        }