Example #1
0
 private static MEMORY_BASIC_INFORMATION VirtualQueryEx(Process proc, long address)
 {
     var info = new MEMORY_BASIC_INFORMATION();
     var ptr = new IntPtr(address);
     VirtualQueryEx(proc.Handle, ptr, out info, Marshal.SizeOf(info));
     return info;
 }
Example #2
0
        /// <summary>
        /// Gets managed heap address
        /// </summary>
        private static unsafe void GetManagedHeap(IntPtr offset, out IntPtr heapsOffset, out IntPtr lastHeapByte)
        {
            var somePtr = EntityPtr.ToPointer("sample");
            var memoryBasicInformation = new MEMORY_BASIC_INFORMATION();

            heapsOffset = IntPtr.Zero;
            lastHeapByte = IntPtr.Zero;
            unsafe
            {
                while (VirtualQuery(offset, ref memoryBasicInformation, (IntPtr)Marshal.SizeOf(memoryBasicInformation)) !=
                       IntPtr.Zero)
                {
                    var isManagedHeap = (long)memoryBasicInformation.BaseAddress < (long)somePtr &&
                                        (long)somePtr <
                                        ((long)memoryBasicInformation.BaseAddress + (long)memoryBasicInformation.RegionSize);

                    if (isManagedHeap)
                    {
                        heapsOffset = offset;
                        lastHeapByte = (IntPtr)((long)offset + (long)memoryBasicInformation.RegionSize);
                    }

                    offset = (IntPtr)((long)offset + (long)memoryBasicInformation.RegionSize);
                }
            }
        }
        public static void GainMemoryAccess(IntPtr address, ulong len)
        {
            SYSTEM_INFO si = new SYSTEM_INFO();
            GetSystemInfo(out si);
            MEMORY_BASIC_INFORMATION mbi;
            ulong currentAddress = RoundUpToPageBoundary((ulong)address, si.pageSize);
            ulong endAddress = currentAddress + len;
            uint ret;
            uint oldProtect = 0;

            while (currentAddress < endAddress)
            {
                mbi = new MEMORY_BASIC_INFORMATION();
                ret = (uint)VirtualQuery((IntPtr)currentAddress, out mbi, (IntPtr)Marshal.SizeOf(mbi));
                if (ret != 0)
                {
                    if (mbi.state == MEM_COMMIT)
                    {
                        VirtualProtect(mbi.baseAddress, mbi.regionSize, PAGE_EXECUTE_READWRITE, out oldProtect);
                    }
                    if ((ulong)mbi.regionSize > 0) currentAddress += (ulong)mbi.regionSize;
                    else currentAddress += si.pageSize;
                }
                else currentAddress += si.pageSize;
            }
        }
Example #4
0
        public int readNextMemoryRegion(byte[] buffer, uint maxSize)
        {
            MEMORY_BASIC_INFORMATION mbi = new MEMORY_BASIC_INFORMATION();
            int amtRead;
            while (true)
            {
                if (nextAddr_ <= pSize_ + baseAddr_)
                {
                    if (0 == VirtualQueryEx(pHandle_, new IntPtr(nextAddr_), out mbi, (uint)Marshal.SizeOf(mbi)))
                    {
                        Console.WriteLine("VirtualQueryEx failure");
                    }
                    int rgnSize = mbi.RegionSize.ToInt32();
                    if (rgnSize > maxSize)
                    {
                        nextAddr_ += rgnSize;
                        continue;
                    }

                    ReadProcessMemory(pHandle_, new IntPtr(nextAddr_), buffer, rgnSize, out amtRead);
                    nextAddr_ += rgnSize;

                    if (0 != amtRead)
                    {
                        return amtRead;
                    }
                }
                else
                {
                    return 0;
                }
            }
        }
Example #5
0
 public static extern UIntPtr VirtualQueryEx(
     IntPtr hProcess,                    // Дескриптора процесса
     IntPtr pvAddress,                   // адрес виртуальной памяти
     out MEMORY_BASIC_INFORMATION pmbi,  // это адрес структуры MEMORY_BASIC_INFORMATION,
     // которую надо создать перед вызовом функции
     int dwLength                        // задает размер структуры MEMORY_BASIC_INFORMATION
     );
Example #6
0
        // finally...
        public static void Main()
        {
            // getting minimum & maximum address

            SYSTEM_INFO sys_info = new SYSTEM_INFO();
            GetSystemInfo(out sys_info);

            IntPtr proc_min_address = sys_info.minimumApplicationAddress;
            IntPtr proc_max_address = sys_info.maximumApplicationAddress;

            // saving the values as long ints so I won't have to do a lot of casts later
            long proc_min_address_l = (long)proc_min_address;
            long proc_max_address_l = (long)proc_max_address;

            // notepad better be runnin'
            Process process = Process.GetProcessesByName("tibia")[0];

            // opening the process with desired access level
            IntPtr processHandle = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_WM_READ, false, process.Id);

            StreamWriter sw = new StreamWriter("dump.txt");

            // this will store any information we get from VirtualQueryEx()
            MEMORY_BASIC_INFORMATION mem_basic_info = new MEMORY_BASIC_INFORMATION();

            int bytesRead = 0;  // number of bytes read with ReadProcessMemory

            while (proc_min_address_l < proc_max_address_l)
            {
                // 28 = sizeof(MEMORY_BASIC_INFORMATION)
                VirtualQueryEx(processHandle, proc_min_address, out mem_basic_info, 28);

                // if this memory chunk is accessible
                if (mem_basic_info.Protect == PAGE_READWRITE && mem_basic_info.State == MEM_COMMIT)
                {
                    byte[] buffer = new byte[mem_basic_info.RegionSize];

                    // read everything in the buffer above
                    ReadProcessMemory((int)processHandle, mem_basic_info.BaseAddress, buffer, mem_basic_info.RegionSize, ref bytesRead);

                    // then output this in the file
                    for (int i = 0; i < mem_basic_info.RegionSize; i++)
                        sw.WriteLine("0x{0} : {1}", (mem_basic_info.BaseAddress + i).ToString("X"), (char)buffer[i]);
                }

                // move to the next memory chunk
                proc_min_address_l += mem_basic_info.RegionSize;
                proc_min_address = new IntPtr(proc_min_address_l);
            }

            sw.Flush();
            sw.Close();

            Console.ReadLine();
        }
Example #7
0
 protected void MemInfo(IntPtr pHandle)
 {
     IntPtr Addy = new IntPtr();
     while (true)
     {
         MEMORY_BASIC_INFORMATION MemInfo = new MEMORY_BASIC_INFORMATION();
         int MemDump = VirtualQueryEx(pHandle, Addy, out  MemInfo, Marshal.SizeOf(MemInfo));
         if (MemDump == 0) break;
         if ((MemInfo.State & 0x1000) != 0 && (MemInfo.Protect & 0x100) == 0)
             MemoryRegion.Add(MemInfo);
         Addy = new IntPtr(MemInfo.BaseAddress.ToInt32() + (int)MemInfo.RegionSize);
     }
 }
Example #8
0
        public void ShowMemory(Process proc)
        {
            GetSystemInfo(ref system_info);
            uint address = system_info.lpMinimumApplicationAddress;
            MEMORY_BASIC_INFORMATION mbi = new MEMORY_BASIC_INFORMATION();

            while (address < system_info.lpMaximumApplicationAddress)
            {
                VirtualQueryEx(proc.Handle, address, out mbi, Marshal.SizeOf(mbi));

                Console.WriteLine("{0} {1}", ((uint)mbi.BaseAddress).ToString("X"), mbi.RegionSize.ToString("X"));
                address = (uint)mbi.BaseAddress + (uint)mbi.RegionSize;
            }
        }
Example #9
0
        public Int32 SearchSignature(Byte[] code, string szMask, int dwStartAddress, int ID)
        {
            return(0);

            uint mhProcess = (uint)GetHandle();

            int dwResult     = 0;
            int lpAddress    = dwStartAddress;
            int dwBestResult = 0;
            MEMORY_BASIC_INFORMATION lpBuffer = new MEMORY_BASIC_INFORMATION();

            Byte[] temp = Form1.temp;

            while (Win32.Kernel.VirtualQueryEx(mhProcess, (uint)lpAddress, ref lpBuffer, System.Runtime.InteropServices.Marshal.SizeOf(typeof(MEMORY_BASIC_INFORMATION))) != 0)
            {
                if (lpBuffer.Protect == 0x20 || lpBuffer.Protect == 0x80)
                {
                    readData((uint)lpBuffer.BaseAddress, (uint)lpBuffer.RegionSize, temp);
                    IntPtr vBytesAddress = Marshal.UnsafeAddrOfPinnedArrayElement(temp, 0);

                    for (int i = 0; i < lpBuffer.RegionSize - szMask.Length; i++)
                    {
                        IntPtr t    = vBytesAddress + i;
                        bool   flag = true;
                        for (int j = 0; j < szMask.Length; j++)
                        {
                            if (szMask[j] == 'x' && Marshal.ReadByte(t + j) != code[j])
                            {
                                flag = false;
                                break;
                            }
                        }
                        if (flag == true)
                        {
                            //MemRWer.closeHandle(mhProcess);
                            return(lpAddress + i);
                        }
                    }

                    if (dwResult > dwBestResult)
                    {
                        dwBestResult = dwResult;
                        break;
                    }
                    lpAddress = lpAddress + lpBuffer.RegionSize;
                }
            }
            //MemRWer.closeHandle(mhProcess);
            return(dwBestResult);
        }
Example #10
0
        public static void MemScan(string processName)
        {
            SYSTEM_INFO sys_info = new SYSTEM_INFO();

            GetSystemInfo(out sys_info);

            UIntPtr proc_min_address = sys_info.minimumApplicationAddress;
            UIntPtr proc_max_address = sys_info.maximumApplicationAddress;

            ulong proc_min_address_l = (ulong)proc_min_address;
            ulong proc_max_address_l = (ulong)proc_max_address;

            Process process = Process.GetProcessesByName(processName)[0];

            UIntPtr processHandle =
                OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_WM_READ, false, (uint)process.Id);

            MEMORY_BASIC_INFORMATION mem_basic_info = new MEMORY_BASIC_INFORMATION();

            uint bytesRead = 0;

            while (proc_min_address_l < proc_max_address_l)
            {
                VirtualQueryEx(processHandle, proc_min_address, out mem_basic_info, Marshal.SizeOf(typeof(MEMORY_BASIC_INFORMATION)));

                if (((mem_basic_info.Protect == PAGE_EXECUTE_READWRITE) || (mem_basic_info.Protect == PAGE_EXECUTE_READ)) && mem_basic_info.State == MEM_COMMIT)
                {
                    byte[] buffer = new byte[mem_basic_info.RegionSize];

                    ReadProcessMemory(processHandle,
                                      mem_basic_info.BaseAddress, buffer, mem_basic_info.RegionSize, ref bytesRead);
                    IntPtr Result = _Scan(buffer, peHeader);
                    if (Result != IntPtr.Zero)
                    {
                        Console.WriteLine("!!! Found PE binary in region: 0x{0}, Region Sz 0x{1}", (mem_basic_info.BaseAddress).ToString("X"), (mem_basic_info.RegionSize).ToString("X"));
                        Console.WriteLine("!!! Carving PE from memory...");
                        using (FileStream fileStream = new FileStream("out.exe", FileMode.Create))
                        {
                            for (uint i = (uint)Result; i < mem_basic_info.RegionSize; i++)
                            {
                                fileStream.WriteByte(buffer[i]);
                            }
                        }
                    }
                }

                proc_min_address_l += mem_basic_info.RegionSize;
                proc_min_address    = new UIntPtr(proc_min_address_l);
            }
        }
Example #11
0
    private int SignScan(byte[] bytes_scan) //searching for bytes
    {
        MEMORY_BASIC_INFORMATION zero = new MEMORY_BASIC_INFORMATION();
        int baseAddress = 0, num = 0;

        byte[] numArray;
        while (baseAddress <= Int32.MaxValue)
        {
            VirtualQueryEx(handle, (IntPtr)baseAddress, out zero, (uint)Marshal.SizeOf(typeof(MEMORY_BASIC_INFORMATION)));
            if (baseAddress != (int)zero.BaseAddress + (int)zero.RegionSize)
            {
                baseAddress = (int)zero.BaseAddress + (int)zero.RegionSize;
                try
                {
                    numArray = new byte[(int)zero.RegionSize];
                }
                catch { return(-1); }
                ReadProcessMemory(handle, zero.BaseAddress, numArray, (int)zero.RegionSize, out _);
                int x = -1;
                while (++x < (int)zero.RegionSize)
                {
                    if (numArray[x] == bytes_scan[0])
                    {
                        for (int i = 0; i < (int)bytes_scan.Length; i++)
                        {
                            if (numArray[i + x] != bytes_scan[i])
                            {
                                num = 0;
                                break;
                            }
                            else
                            {
                                num++;
                                if (num == (int)bytes_scan.Length)
                                {
                                    return((int)zero.BaseAddress + x);
                                }
                            }
                        }
                    }
                }
            }
            else
            {
                break;
            }
        }
        return(-1);
    }
Example #12
0
        public void CreateEntryPoints()
        {
            long helpMinimumAddress = (long)minimumAddress;
            int  _regionSize;
            MEMORY_BASIC_INFORMATION memoryInfo = new MEMORY_BASIC_INFORMATION();

            while (helpMinimumAddress < maximum32BitAddress)
            {
                minimumAddress = new IntPtr(helpMinimumAddress);
                VirtualQueryEx(targetHandle, minimumAddress, out memoryInfo, (uint)Marshal.SizeOf(memoryInfo));
                if (memoryInfo.RegionSize < 0) //TODO: prüfen regionsize int oder uint  |  prüfen cast auf long oder int
                {
                    break;
                }

                if (
                    //writable = not (not writeable)
                    //memoryInfo.Protect != AllocationProtectEnum.PAGE_EXECUTE_READ //not writable
                    //&& memoryInfo.Protect != AllocationProtectEnum.PAGE_READONLY //not writable
                    //&& memoryInfo.Protect != 0 //not writable
                    //&& memoryInfo.Protect != AllocationProtectEnum.PAGE_GUARDPLUSREADWRITE //not writable

                    //readonly
                    //(memoryInfo.Protect == AllocationProtectEnum.PAGE_EXECUTE_READ //not writable
                    //|| memoryInfo.Protect == AllocationProtectEnum.PAGE_READONLY) //not writable

                    //necessary
                    memoryInfo.Protect == AllocationProtectEnum.PAGE_READWRITE || //
                    memoryInfo.Protect == AllocationProtectEnum.PAGE_WRITECOMBINEPLUSREADWRITE

                    //&& memoryInfo.Protect != AllocationProtectEnum.PAGE_WRITECOPY //CopyOnWrite
                    && (memoryInfo.Type == TypeEnum.MEM_IMAGE || memoryInfo.Type == TypeEnum.MEM_PRIVATE))
                {
                    if (regionBeginning.Count != 0 && (regionBeginning.Last().Key + regionBeginning.Last().Value == memoryInfo.BaseAddress))
                    {
                        helpMinimumAddress = (uint)memoryInfo.BaseAddress - regionBeginning.Last().Value;
                        _regionSize        = regionBeginning.Last().Value + (int)memoryInfo.RegionSize;
                        regionBeginning.Remove(regionBeginning.Last().Key);
                        regionBeginning.Add(new IntPtr(helpMinimumAddress), _regionSize);
                    }
                    else
                    {
                        regionBeginning.Add(memoryInfo.BaseAddress, (int)memoryInfo.RegionSize);
                    }
                }
                helpMinimumAddress = (uint)memoryInfo.BaseAddress + memoryInfo.RegionSize;
            }
            sortedRegions = from entry in regionBeginning orderby entry.Value descending select entry;// sort region descending by region regionsize
        }
Example #13
0
        /// <summary>
        /// Opens an existing minidump file on the specified path.
        /// </summary>
        /// <param name="path">The file to open.</param>
        /// <returns></returns>
        public static MiniDumpFile OpenExisting(string path)
        {
            MemoryMappedFile           minidumpMappedFile = null;
            SafeMemoryMappedViewHandle mappedFileView     = null;

            // MemoryMappedFile will close the FileStream when it gets Disposed.
            FileStream fileStream = File.Open(path, System.IO.FileMode.Open, FileAccess.Read, FileShare.Read);

            try
            {
                minidumpMappedFile = MemoryMappedFile.CreateFromFile(fileStream, Path.GetFileName(path), 0, MemoryMappedFileAccess.Read, null, HandleInheritability.None, false);

                mappedFileView = NativeMethods.MapViewOfFile(minidumpMappedFile.SafeMemoryMappedFileHandle, NativeMethods.FILE_MAP_READ, 0, 0, IntPtr.Zero);

                if (mappedFileView.IsInvalid)
                {
                    throw new Win32Exception(Marshal.GetLastWin32Error());
                }

                MEMORY_BASIC_INFORMATION memoryInformation = default(MEMORY_BASIC_INFORMATION);

                if (NativeMethods.VirtualQuery(mappedFileView, ref memoryInformation, (IntPtr)Marshal.SizeOf(memoryInformation)) == IntPtr.Zero)
                {
                    throw new Win32Exception(Marshal.GetLastWin32Error());
                }

                mappedFileView.Initialize((ulong)memoryInformation.RegionSize);
            }
            catch
            {
                // Cleanup whatever didn't work and rethrow
                if ((minidumpMappedFile != null) && (!mappedFileView.IsInvalid))
                {
                    minidumpMappedFile.Dispose();
                }
                if ((mappedFileView != null) && (!mappedFileView.IsInvalid))
                {
                    mappedFileView.Dispose();
                }
                if (minidumpMappedFile == null)
                {
                    fileStream?.Close();
                }

                throw;
            }

            return(new MiniDumpFile(minidumpMappedFile, mappedFileView));
        }
Example #14
0
    //===================================================================================================================================
    //===================================================================================================================================
    //===================================================================================================================================
    protected bool map_process_memory(IntPtr pHandle, List <MEMORY_BASIC_INFORMATION> mapped_memory)
    {
        IntPtr address = new IntPtr();
        MEMORY_BASIC_INFORMATION MBI = new MEMORY_BASIC_INFORMATION();

        while (VirtualQueryEx(pHandle, address, out MBI, (uint)Marshal.SizeOf(MBI)) != 0)
        {
            if ((MBI.State & (uint)StateEnum.MEM_COMMIT) != 0 && (MBI.Protect & (uint)AllocationProtectEnum.PAGE_GUARD) != (uint)AllocationProtectEnum.PAGE_GUARD)
            {
                mapped_memory.Add(MBI);
            }
            address = new IntPtr(MBI.BaseAddress.ToInt64() + MBI.RegionSize);
        }
        return(mapped_memory.Count() > 0);
    }
Example #15
0
        /*
         *  -----------------------
         *  Memory Buffer Factories
         *  -----------------------
         */

        /// <summary>
        /// Finds an appropriate location where a <see cref="MemoryBuffer"/>;
        /// or other memory allocation could be performed.
        /// </summary>
        /// <param name = "size" > The space in bytes that the specific <see cref="MemoryBuffer"/> would require to accomodate.</param>
        /// <param name="minimumAddress">The minimum absolute address to find a buffer in.</param>
        /// <param name="maximumAddress">The maximum absolute address to find a buffer in.</param>
        /// <param name="isPrivateBuffer">Defines whether the buffer type created is a shared or private buffer.</param>
        public BufferAllocationProperties FindBufferLocation(int size, long minimumAddress, long maximumAddress, bool isPrivateBuffer = false)
        {
            if (minimumAddress <= 0)
            {
                throw new ArgumentException("Please do not set the minimum address to 0 or negative. It collides with the return values of Windows API functions" +
                                            "where e.g. 0 is returned on failure but you can also allocate successfully on 0.");
            }

            int bufferSize = GetBufferSize(size, isPrivateBuffer);

            // Search through the buffer cache first.
            if (_pageCache != null)
            {
                for (int x = 0; x < _pageCache.Length; x++)
                {
                    var pointer = GetBufferPointerInPageRange(ref _pageCache[x], bufferSize, (IntPtr)minimumAddress, (IntPtr)maximumAddress);
                    if (pointer != IntPtr.Zero)
                    {
                        // Page cache contains a page that can "work". Check if this page is still valid by running VirtualQuery on it
                        // and rechecking the new page.
                        var memoryBasicInformation = new MEMORY_BASIC_INFORMATION();
                        _virtualQueryFunction(Process.Handle, pointer, ref memoryBasicInformation);

                        var newPointer = GetBufferPointerInPageRange(ref memoryBasicInformation, bufferSize, (IntPtr)minimumAddress, (IntPtr)maximumAddress);
                        if (newPointer != IntPtr.Zero)
                        {
                            return(new BufferAllocationProperties(newPointer, bufferSize));
                        }
                    }
                }
            }

            // Not found in cache, get all real pages and try find appropriate spot.
            var memoryPages = MemoryPages.GetPages(Process).ToArray();

            _pageCache = memoryPages;

            for (int x = 0; x < memoryPages.Length; x++)
            {
                var pointer = GetBufferPointerInPageRange(ref memoryPages[x], bufferSize, (IntPtr)minimumAddress, (IntPtr)maximumAddress);
                if (pointer != IntPtr.Zero)
                {
                    return(new BufferAllocationProperties(pointer, bufferSize));
                }
            }

            throw new Exception($"Unable to find memory location to fit MemoryBuffer of size {size} ({bufferSize}) between {minimumAddress.ToString("X")} and {maximumAddress.ToString("X")}.");
        }
Example #16
0
        private void findUnlistedImageSectorsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MEMORY_BASIC_INFORMATION memInfo = new MEMORY_BASIC_INFORMATION();
            int  mem_size       = Marshal.SizeOf(memInfo);
            uint currentAddress = 0;

            IntPtr hProc = PELoader.OpenProcessHandle(ProcessID);

            while (NativeMethods.VirtualQueryEx(hProc, currentAddress, out memInfo, mem_size) != 0)
            {
                if (FoundModules.Contains(memInfo.AllocationBase))
                {
                    currentAddress += memInfo.RegionSize;
                    continue;
                }

                if (memInfo.Protect == 0x1)//memInfo.Type != 0x1000000
                {
                    currentAddress += memInfo.RegionSize;
                    continue;
                }

                IMAGE_DOS_HEADER header = PELoader.StructFromMemory <IMAGE_DOS_HEADER>(hProc, memInfo.AllocationBase);

                if (!FoundModules.Contains(memInfo.BaseAddress))
                {
                    byte[] buffer = new byte[memInfo.RegionSize];
                    NativeMethods.ReadProcessMemory(hProc, memInfo.BaseAddress, buffer, buffer.Length, 0);
                    for (int i = 0; i < buffer.Length - 1; i++)
                    {
                        if (buffer[i] == 'M' && buffer[i + 1] == 'Z')
                        {
                            lvModules.Items.Add(new ModuleListViewItem(ProcessID, memInfo.BaseAddress + i));
                        }
                    }
                    FoundModules.Add(memInfo.BaseAddress);
                }

                /*
                 * if(header.e_magic[0] == 'M' && header.e_magic[1] == 'Z')
                 *  lvModules.Items.Add(new ModuleListViewItem(ProcessID, memInfo.AllocationBase));
                 * FoundModules.Add(memInfo.AllocationBase);
                 */
                currentAddress += memInfo.RegionSize;//0x1000000
            }

            PELoader.CloseProcessHandle(hProc);
        }
Example #17
0
        public static List <IntPtr> ScanSignature(Int32 pid, Int32 BaseAddress, byte[] signature, bool single = false,
                                                  String mask = "")
        {
            List <IntPtr>            result = new List <IntPtr>();
            MEMORY_BASIC_INFORMATION mbi    = new MEMORY_BASIC_INFORMATION();
            Int32  offset   = 0;
            Int32  scanSize = 0;
            IntPtr byteread = IntPtr.Zero;

            IntPtr hProcess = OpenProcess(ProcessAccessFlags.All, false, pid);

            if (hProcess == IntPtr.Zero)
            {
                return(result);
            }
            scanSize = 0x7FFFFFFF;

            while (offset < scanSize)
            {
                int count = VirtualQueryEx(hProcess, (IntPtr)BaseAddress + offset, out mbi, (uint)Marshal.SizeOf(mbi));
                if (count == 0)
                {
                    break;
                }
                if (mbi.State != 0x10000) // MEM_FREE
                {
                    byte[] buffer = new byte[(int)mbi.RegionSize];
                    ReadProcessMemory(hProcess, mbi.BaseAddress, buffer, (uint)mbi.RegionSize, out byteread);

                    for (int i = 0; i < buffer.Length - signature.Length; i++)
                    {
                        if (CheckSignature(buffer, (uint)i, signature, mask))
                        {
                            result.Add((IntPtr)((uint)mbi.BaseAddress + i));
                            if (single)
                            {
                                CloseHandle(hProcess);
                                return(result);
                            }
                        }
                    }
                }
                offset += (int)mbi.RegionSize;
            }

            CloseHandle(hProcess);
            return(result);
        }
Example #18
0
        public MEMORY_BASIC_INFORMATION[] GetMemoryInfos(Process proc)
        {
            GetSystemInfo(ref system_info);
            uint address = system_info.lpMinimumApplicationAddress;
            MEMORY_BASIC_INFORMATION        mbi   = new MEMORY_BASIC_INFORMATION();
            List <MEMORY_BASIC_INFORMATION> mList = new List <MEMORY_BASIC_INFORMATION>();

            while (address < system_info.lpMaximumApplicationAddress)
            {
                VirtualQueryEx(proc.Handle, address, out mbi, Marshal.SizeOf(mbi));

                mList.Add(mbi);
                address = (uint)mbi.BaseAddress + (uint)mbi.RegionSize;
            }
            return(mList.ToArray());
        }
Example #19
0
        private List <MEMORY_BASIC_INFORMATION> getScannableChunks(long procStart, long procMaxAddressL)
        {
            List <MEMORY_BASIC_INFORMATION> result = new List <MEMORY_BASIC_INFORMATION>();

            while (procStart < procMaxAddressL)
            {
                MEMORY_BASIC_INFORMATION temp = new MEMORY_BASIC_INFORMATION();
                VirtualQueryEx((IntPtr)hProcess, (IntPtr)procStart, out temp, 28);
                if (temp.Protect == PAGE_READWRITE && temp.State == MEM_COMMIT)
                {
                    result.Add(temp);
                }
                procStart += temp.RegionSize;
            }
            return(result);
        }
Example #20
0
        /// <summary>
        /// Returns a list of pages that exist within a set process' memory.
        /// </summary>
        /// <returns></returns>
        public static List <MEMORY_BASIC_INFORMATION> GetPages(Process process)
        {
            // Is this Windows on Windows 64? (x86 app running on x64 Windows)
            IsWow64Process(process.Handle, out bool isWow64);
            GetSystemInfo(out SYSTEM_INFO systemInfo);

            // This should work.
            nuint currentAddress = 0;
            nuint maxAddress     = 0x7FFFFFFF; // 32bit (with Address Range Extension)

            // Check if 64bit.
            if (systemInfo.wProcessorArchitecture == ProcessorArchitecture.PROCESSOR_ARCHITECTURE_AMD64 && !isWow64)
            {
                maxAddress = systemInfo.lpMaximumApplicationAddress;
            }

            // Support Large Address Aware
            if (IntPtr.Size == 4 && (nuint)systemInfo.lpMaximumApplicationAddress > maxAddress)
            {
                maxAddress = (nuint)systemInfo.lpMaximumApplicationAddress;
            }

            // Get the VirtualQuery function implementation to use.
            // Local is faster and works for current process; Remote is for another process.
            VirtualQueryUtility.VirtualQueryFunction virtualQueryFunction = VirtualQueryUtility.GetVirtualQueryFunction(process);

            // Shorthand for convenience.
            List <MEMORY_BASIC_INFORMATION> memoryPages = new List <MEMORY_BASIC_INFORMATION>(8192);

            // Until we get all of the pages.
            while (currentAddress <= maxAddress)
            {
                // Get our info from VirtualQueryEx.
                var memoryInformation = new MEMORY_BASIC_INFORMATION();
                var result            = virtualQueryFunction(process.Handle, (nuint)currentAddress, ref memoryInformation);
                if (result == (UIntPtr)0)
                {
                    break;
                }

                // Add the page and increment address iterator to go to next page.
                memoryPages.Add(memoryInformation);
                currentAddress += memoryInformation.RegionSize;
            }

            return(memoryPages);
        }
Example #21
0
        public Vulturnus(Process target, PaddingByte padding = PaddingByte.NOP)
        {
            TargetProcess = target;
            Padding       = padding;
            MemoryPatches = new Dictionary <ulong, byte[]>();

            PageExecuteReadWrite = (address, size, function) =>
            {
                Func <ulong, bool> PageHasExecuteReadWriteAccess = (queryAddress) =>
                {
                    MEMORY_BASIC_INFORMATION information = new MEMORY_BASIC_INFORMATION();

                    if (VirtualQueryEx(TargetProcess.Handle, (IntPtr)queryAddress, out information, (uint)Marshal.SizeOf(typeof(MEMORY_BASIC_INFORMATION))) != (uint)Marshal.SizeOf(typeof(MEMORY_BASIC_INFORMATION)))
                    {
                        return(false);
                    }

                    if (information.Protect == 0 || ((information.Protect & Protection.PAGE_GUARD) != 0))
                    {
                        return(false);
                    }

                    if ((information.Protect & Protection.PAGE_EXECUTE_READWRITE) == 0)
                    {
                        return(false);
                    }

                    return(true);
                };

                uint protect = 0;

                if (!PageHasExecuteReadWriteAccess(address))
                {
                    protect = VirtualProtectEx(TargetProcess.Handle, (IntPtr)address, size, (uint)Protection.PAGE_EXECUTE_READWRITE, out protect) ? protect : 0;
                }

                function();

                if (protect != 0)
                {
                    return(VirtualProtectEx(TargetProcess.Handle, (IntPtr)address, size, protect, out protect));
                }

                return(true);
            };
        }
Example #22
0
        public bool ScanAllModules(String pattern, String mask, out uint ptr)
        {
            IntPtr oldBase = _baseModule;
            int    oldSize = _moduleSize;

            ptr = 0;

            SYSTEM_INFO sys_info = new SYSTEM_INFO();

            GetSystemInfo(out sys_info);

            IntPtr proc_min_address   = sys_info.minimumApplicationAddress;
            IntPtr proc_max_address   = sys_info.maximumApplicationAddress;
            long   proc_min_address_l = (long)proc_min_address;
            long   proc_max_address_l = (long)proc_max_address;
            // this will store any information we get from VirtualQueryEx()
            MEMORY_BASIC_INFORMATION mem_basic_info = new MEMORY_BASIC_INFORMATION();

            int bytesRead = 0;  // number of bytes read with ReadProcessMemory

            bool result = false;

            while (proc_min_address_l < proc_max_address_l)
            {
                // 28 = sizeof(MEMORY_BASIC_INFORMATION)
                VirtualQueryEx(_processHandle, proc_min_address, out mem_basic_info, 28);

                // if this memory chunk is accessible
                if (mem_basic_info.Protect == PAGE_READWRITE && mem_basic_info.State == MEM_COMMIT)
                {
                    _baseModule = (IntPtr)mem_basic_info.BaseAddress;
                    _moduleSize = mem_basic_info.RegionSize;
                    result      = FindPattern(pattern, mask, out ptr);
                    if (result)
                    {
                        break;
                    }
                }

                // move to the next memory chunk
                proc_min_address_l += mem_basic_info.RegionSize;
                proc_min_address    = new IntPtr(proc_min_address_l);
            }
            _baseModule = oldBase;
            _moduleSize = oldSize;
            return(result);
        }
Example #23
0
        private void ContiniousScan(Process process)
        {
            Dictionary <string, byte> MemoryDictionary = new Dictionary <string, byte>();
            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Restart();
            SYSTEM_INFO msi = new SYSTEM_INFO();

            Kernel32.GetSystemInfo(ref msi);
            MEMORY_BASIC_INFORMATION mbi = new MEMORY_BASIC_INFORMATION();
            IntPtr maxApplicationAddress = msi.lpMaximumApplicationAddress;
            IntPtr minApplicationAddress = msi.lpMinimumApplicationAddress;
            IntPtr ProcHandle            = process.Handle;
            int    bytesRead             = 0;

            bool LoopScanning = true;
            Dictionary <string, byte> oldDictionary = new Dictionary <string, byte>();

            while (LoopScanning)
            {
                MemoryDictionary.Clear();
                minApplicationAddress = msi.lpMinimumApplicationAddress;
                while ((long)minApplicationAddress < (long)maxApplicationAddress)
                {
                    Kernel32.VirtualQueryEx(ProcHandle, minApplicationAddress, out mbi, (uint)Marshal.SizeOf(typeof(MEMORY_BASIC_INFORMATION)));
                    if (mbi.Protect == Kernel32.PAGE_READWRITE && mbi.State == Kernel32.MEM_COMMIT)
                    {
                        byte[] buffer = new byte[mbi.RegionSize];
                        Kernel32.ReadProcessMemory((int)ProcHandle, mbi.BaseAddress, buffer, mbi.RegionSize, ref bytesRead);
                        for (int x = 0; x < mbi.RegionSize; x++)
                        {
                            MemoryDictionary.Add(string.Format("0x{0}", (mbi.BaseAddress + x).ToString("X16")), buffer[x]);
                        }
                    }
                    minApplicationAddress = new IntPtr(((long)minApplicationAddress + mbi.RegionSize));
                }
                if (oldDictionary.Count != 0)
                {
                    List <MemorryValue> memvals = CheckDictionaries(oldDictionary, MemoryDictionary);
                    if (memvals.Count > 0)
                    {
                        MemoryChanged.Invoke(memvals);
                    }
                }
                oldDictionary = new Dictionary <string, byte>(MemoryDictionary);
            }
        }
Example #24
0
        public static bool scanJava(Process p)
        {
            p.Refresh();
            try
            {
                if (p.HasExited)
                {
                    return false;
                }
            }
            catch (Exception)
            {
                return false;
            }
            //Console.WriteLine("Scanning " + p.ProcessName);
            IntPtr Addy = new IntPtr();
            List<MEMORY_BASIC_INFORMATION> MemReg = new List<MEMORY_BASIC_INFORMATION>();
            while (true)
            {
                MEMORY_BASIC_INFORMATION MemInfo = new MEMORY_BASIC_INFORMATION();
                int MemDump = VirtualQueryEx(p.Handle, Addy, out  MemInfo, Marshal.SizeOf(MemInfo));
                if (MemDump == 0) break;
                if (0 != (MemInfo.State & MEM_COMMIT) && 0 != (MemInfo.Protect & WRITABLE) && 0 == (MemInfo.Protect & PAGE_GUARD))
                {
                    MemReg.Add(MemInfo);
                }
                Addy = new IntPtr(MemInfo.BaseAddress.ToInt64() + MemInfo.RegionSize.ToInt64());
            }

            for (int i = 0; i < MemReg.Count; i++)
            {
                byte[] buff = new byte[MemReg[i].RegionSize.ToInt32()];
                ReadProcessMemory(p.Handle, MemReg[i].BaseAddress, buff, MemReg[i].RegionSize.ToInt32(), IntPtr.Zero);

                long Result = IndexOf(buff, javameter);
                if (Result > 0)
                {
                    buff = null;
                    GC.Collect();
                    return true;
                }
                buff = null;
            }
            GC.Collect();
            return false;
        }
Example #25
0
        public static byte[] ReadProcessMemory(uint hProcess, ulong address, int dwSize)
        {
            ulong minAddress = address;
            ulong maxAddress = address + (ulong)dwSize;
            MEMORY_BASIC_INFORMATION memBasicInfo;
            var    bytes      = new byte[0];
            IntPtr regionSize = IntPtr.Zero;

            memBasicInfo = new MEMORY_BASIC_INFORMATION();

            while (minAddress < maxAddress)
            {
                var infoSize = VirtualQueryEx(hProcess, new IntPtr((long)minAddress), out memBasicInfo, (uint)memBasicInfo.SizeOf());

                regionSize = memBasicInfo.RegionSize;

                if (memBasicInfo.Protect == AllocationProtectEnum.Readonly | memBasicInfo.Protect == AllocationProtectEnum.ReadWrite | memBasicInfo.Protect == AllocationProtectEnum.ExecuteRead | memBasicInfo.Protect == AllocationProtectEnum.ExecuteReadWrite)
                {
                    int bytesRead = 0;
                    var buffer    = new byte[(int)regionSize];

                    ReadProcessMemory(hProcess, memBasicInfo.BaseAddress, buffer, (int)regionSize, ref bytesRead);

                    if (bytesRead.As <int>() > 0)
                    {
                        if (bytesRead == (int)regionSize)
                        {
                            bytes = bytes.Append(buffer);
                        }
                        else
                        {
                            bytes = bytes.Append(buffer.PadRight((int)regionSize));
                        }
                    }
                }
                else
                {
                    bytes = bytes.Append(new byte[(int)regionSize]);
                }

                minAddress += (ulong)regionSize;
            }

            return(bytes);
        }
        private void Given_Image(uint addr, params byte[] bytes)
        {
            mem      = new MemoryArea(Address.Ptr32(addr), bytes);
            imageMap = new SegmentMap(
                mem.BaseAddress,
                new ImageSegment(".text", mem, AccessMode.ReadExecute));
            host.Setup(h => h.SegmentMap).Returns(imageMap);
            var meminfo = new MEMORY_BASIC_INFORMATION
            {
                BaseAddress    = mem.BaseAddress,
                RegionSize     = (uint)mem.Length,
                AllocationBase = mem.BaseAddress.ToLinear()
            };

            host.Setup(h => h.TE_GetMemoryInfo(
                           It.IsAny <Address>(),
                           out meminfo)).Returns(true);
        }
Example #27
0
        protected void MemInfo(IntPtr pHandle)
        {
            IntPtr intPtr = (IntPtr)((long)this.InicioScan);

            while ((long)intPtr <= (long)this.FimScan)
            {
                MEMORY_BASIC_INFORMATION memory_BASIC_INFORMATION = default(MEMORY_BASIC_INFORMATION);
                if (Kernel__.VirtualQueryEx(pHandle, intPtr, out memory_BASIC_INFORMATION, Marshal.SizeOf(memory_BASIC_INFORMATION)) == 0)
                {
                    break;
                }
                if ((memory_BASIC_INFORMATION.State & 4096u) != 0u && (memory_BASIC_INFORMATION.Protect & 256u) != 256u)
                {
                    this.MappedMemory.Add(memory_BASIC_INFORMATION);
                }
                intPtr = new IntPtr(memory_BASIC_INFORMATION.BaseAddress.ToInt32() + (int)memory_BASIC_INFORMATION.RegionSize);
            }
        }
Example #28
0
        // ReSharper restore SuggestBaseTypeForParameter

        /// <summary>
        /// Utilizes WIN32 RPM and VQEx to find given pattern in the given process context.
        /// </summary>
        /// <example>
        /// A sample usage of the <see cref="MatchPattern"/> method:
        /// <code>
        /// using static NFSScript.Core.PatternScan;
        ///
        /// class MyClass
        /// {
        ///     static int Main()
        ///     {
        ///         IntPtr addr1 = matchPattern("nfsw.exe", new Byte[] { 0x55, 0xF0, 0x0, 0xAB });
        ///         IntPtr addr2 = matchPattern("gameplay.dll", new Byte[] { 0x78, 0xA, 0xBC, 0xEB });
        ///     }
        /// }
        /// </code>
        /// </example>
        /// <remarks>Doesn't support 'ghost' patterns, a.k.a. unknown byte patterns; e.g., xx??x.</remarks>
        /// <param name="processName">The process context, has to be identifiable  in WIN32 memory; e.g., myExe.exe, myLib.dll.</param>
        /// <param name="pattern">Byte array that contains  the pattern in big-endian order (MSB->LSB).</param>
        /// <returns>The dynamic memory address if found, else IntPtr.Zero.</returns>
        public static IntPtr MatchPattern(string processName, byte[] pattern)
        {
            // Consistency
            var context = Process.GetProcessesByName(processName);

            if (context.Length < 1)
            {
                return(IntPtr.Zero);
            }

            // Init
            var handle         = context[0].Handle;
            var memoryRegistry = new List <MEMORY_BASIC_INFORMATION>();

            // Fill in registry
            var iAddress = new IntPtr();
            int memoryDump;

            do
            {
                var memoryInfo = new MEMORY_BASIC_INFORMATION();
                memoryDump = VirtualQueryEx(handle, iAddress, out memoryInfo, Marshal.SizeOf(memoryInfo));
                if ((memoryInfo.State & MEM_COMMIT) != 0 && (memoryInfo.Protect & PAGE_GUARD) == 0)
                {
                    memoryRegistry.Add(memoryInfo);
                }

                iAddress = new IntPtr(memoryInfo.BaseAddress.ToInt32() + (int)memoryInfo.RegionSize);
            } while (memoryDump > 0);

            // Scan
            foreach (var cur in memoryRegistry)
            {
                var buffer = new byte[cur.RegionSize];
                ReadProcessMemory(handle, cur.BaseAddress, buffer, cur.RegionSize, 0);

                var result = Match(buffer, pattern);
                if (result != IntPtr.Zero)
                {
                    return(new IntPtr(cur.BaseAddress.ToInt32() + result.ToInt32()));
                }
            }
            return(IntPtr.Zero);
        }
Example #29
0
        public unsafe static bool HasSufficientStack(long bytes)
        {
            var stackInfo = new MEMORY_BASIC_INFORMATION();

            // We subtract one page for our request. VirtualQuery rounds UP to the next page.
            // Unfortunately, the stack grows down. If we're on the first page (last page in the
            // VirtualAlloc), we'll be moved to the next page, which is off the stack! Note this
            // doesn't work right for IA64 due to bigger pages.
            IntPtr currentAddr = new IntPtr((uint)&stackInfo - 4096);

            // Query for the current stack allocation information.
            VirtualQuery(currentAddr, ref stackInfo, sizeof(MEMORY_BASIC_INFORMATION));

            // If the current address minus the base (remember: the stack grows downward in the
            // address space) is greater than the number of bytes requested plus the reserved
            // space at the end, the request has succeeded.
            return(((uint)currentAddr.ToInt64() - stackInfo.AllocationBase) >
                   (bytes + STACK_RESERVED_SPACE));
        }
Example #30
0
    public long SearchForBytePattern(byte[] pattern, bool wildcard = false)
    {
        MEMORY_BASIC_INFORMATION mem_info = new MEMORY_BASIC_INFORMATION();

        long min_address = 0;
        long max_address = 0x7FFFFFFF;

        byte[]        buffer        = new byte[81920];
        PatternSearch patternSearch = new PatternSearch(buffer, pattern, wildcard);

        //scan process memory regions
        while (min_address < max_address &&
               VirtualQueryEx(processHandle, (IntPtr)min_address, out mem_info, (uint)Marshal.SizeOf(typeof(MEMORY_BASIC_INFORMATION))) > 0)
        {
            //check if memory region is accessible
            //skip regions smaller than 16M (default DOSBOX memory size)
            if (mem_info.Protect == PAGE_READWRITE && mem_info.State == MEM_COMMIT && (mem_info.Type & MEM_PRIVATE) == MEM_PRIVATE &&
                (int)mem_info.RegionSize >= 1024 * 1024 * 16)
            {
                long readPosition = (long)mem_info.BaseAddress;
                int  bytesToRead  = Math.Min((int)mem_info.RegionSize, 1024 * 640);               //scan first 640K only

                long bytesRead;
                while (bytesToRead > 0 && (bytesRead = Read(buffer, readPosition, Math.Min(buffer.Length, bytesToRead))) > 0)
                {
                    //search bytes pattern
                    int index = patternSearch.IndexOf((int)bytesRead);
                    if (index != -1)
                    {
                        return(readPosition + index);
                    }

                    readPosition += bytesRead;
                    bytesToRead  -= (int)bytesRead;
                }
            }

            // move to next memory region
            min_address = (long)mem_info.BaseAddress + (long)mem_info.RegionSize;
        }

        return(-1);
    }
Example #31
0
        /// <summary>
        /// Dump memory page by page to a dump.dmp file. Can be used with Cheat Engine.
        /// </summary>
        public bool DumpMemory(string file = "dump.dmp")
        {
            Debug.Write("[DEBUG] memory dump starting... (" + DateTime.Now.ToString("h:mm:ss tt") + ")" + Environment.NewLine);
            SYSTEM_INFO sys_info = new SYSTEM_INFO();

            GetSystemInfo(out sys_info);

            UIntPtr proc_min_address = sys_info.minimumApplicationAddress;
            UIntPtr proc_max_address = sys_info.maximumApplicationAddress;

            // saving the values as long ints so I won't have to do a lot of casts later
            Int64 proc_min_address_l = (Int64)proc_min_address; //(Int64)procs.MainModule.BaseAddress;
            Int64 proc_max_address_l = (Int64)mProc.Process.VirtualMemorySize64 + proc_min_address_l;

            //int arrLength = 0;
            if (File.Exists(file))
            {
                File.Delete(file);
            }


            MEMORY_BASIC_INFORMATION memInfo = new MEMORY_BASIC_INFORMATION();

            while (proc_min_address_l < proc_max_address_l)
            {
                VirtualQueryEx(mProc.Handle, proc_min_address, out memInfo);
                byte[]  buffer = new byte[(Int64)memInfo.RegionSize];
                UIntPtr test   = (UIntPtr)((Int64)memInfo.RegionSize);
                UIntPtr test2  = (UIntPtr)((Int64)memInfo.BaseAddress);

                ReadProcessMemory(mProc.Handle, test2, buffer, test, IntPtr.Zero);

                AppendAllBytes(file, buffer); //due to memory limits, we have to dump it then store it in an array.
                //arrLength += buffer.Length;

                proc_min_address_l += (Int64)memInfo.RegionSize;
                proc_min_address    = new UIntPtr((ulong)proc_min_address_l);
            }


            Debug.Write("[DEBUG] memory dump completed. Saving dump file to " + file + ". (" + DateTime.Now.ToString("h:mm:ss tt") + ")" + Environment.NewLine);
            return(true);
        }
Example #32
0
        unsafe int MySend(int TSocket, object Buf, int len, int flags)
        {
            int ret = 0;

            IntPtr dwOldProtect          = IntPtr.Zero;
            MEMORY_BASIC_INFORMATION mbi = new MEMORY_BASIC_INFORMATION();

            VirtualQuery(pfnMsgBox, out mbi, sizeof(long));
            VirtualProtect(pfnMsgBox, 8, PAGE_READWRITE, dwOldProtect);

            // 写入原来的执行代码
            WriteProcessMemory((IntPtr)GetCurrentProcess(),
                               pfnMsgBox,
                               add_old,
                               sizeof(int) * 2, IntPtr.Zero);
            VirtualProtect(pfnMsgBox, 8, mbi.Protect, IntPtr.Zero);

            return(ret);
        }
Example #33
0
        public static unsafe bool HasSufficientStack(long bytes)
        {
            var stackInfo = new MEMORY_BASIC_INFORMATION();

            // We subtract one page for our request. VirtualQuery rounds UP to the next page.
            // Unfortunately, the stack grows down. If we're on the first page (last page in the
            // VirtualAlloc), we'll be moved to the next page, which is off the stack! Note this
            // doesn't work right for IA64 due to bigger pages.
            IntPtr currentAddr = new IntPtr((uint)&stackInfo - 4096);

            // Query for the current stack allocation information.
            VirtualQuery(currentAddr, ref stackInfo, sizeof(MEMORY_BASIC_INFORMATION));

            // If the current address minus the base (remember: the stack grows downward in the
            // address space) is greater than the number of bytes requested plus the reserved
            // space at the end, the request has succeeded.
            return ((uint)currentAddr.ToInt64() - stackInfo.AllocationBase) >
                   (bytes + STACK_RESERVED_SPACE);
        }
Example #34
0
        public static long findaddress(IntPtr Handle, byte[] DataToFind)
        {
            SYSTEM_INFO sys_info = new SYSTEM_INFO();

            GetSystemInfo(out sys_info);

            long proc_min_address = (long)sys_info.minimumApplicationAddress;
            long proc_max_address = (long)sys_info.maximumApplicationAddress;

            // saving the values as long ints so I won't have to do a lot of casts later



            // this will store any information we get from VirtualQueryEx()
            MEMORY_BASIC_INFORMATION mem_basic_info = new MEMORY_BASIC_INFORMATION();
            int bytesRead = 0;

            while (proc_min_address < proc_max_address)
            {
                // 28 = sizeof(MEMORY_BASIC_INFORMATION)
                VirtualQueryEx(Handle, (IntPtr)proc_min_address, out mem_basic_info, (uint)Marshal.SizeOf(typeof(MEMORY_BASIC_INFORMATION)));

                // if this memory chunk is accessible
                if (mem_basic_info.Protect == PAGE_READWRITE && mem_basic_info.State == MEM_COMMIT)
                {
                    byte[] buffer = new byte[(long)mem_basic_info.RegionSize];

                    // read everything in the buffer above
                    ReadProcessMemory((int)Handle, (long)mem_basic_info.BaseAddress, buffer, (long)mem_basic_info.RegionSize, ref bytesRead);


                    long Index = SimpleBoyerMooreSearch(buffer, DataToFind);
                    if (Index != -1)
                    {
                        return(Index + proc_min_address);
                    }
                }

                // move to the next memory chunk
                proc_min_address += (long)mem_basic_info.RegionSize;
            }
            return(-1);
        }
Example #35
0
        protected void MemInfo(IntPtr pHandle)
        {
            IntPtr Addy = new IntPtr();

            while (true)
            {
                MEMORY_BASIC_INFORMATION MemInfo = new MEMORY_BASIC_INFORMATION();
                int MemDump = VirtualQueryEx(pHandle, Addy, out MemInfo, Marshal.SizeOf(MemInfo));
                if (MemDump == 0)
                {
                    break;
                }
                if ((MemInfo.State & 0x1000) != 0 && (MemInfo.Protect & 0x100) == 0)
                {
                    MemoryRegion.Add(MemInfo);
                }
                Addy = new IntPtr(MemInfo.BaseAddress.ToInt32() + (int)MemInfo.RegionSize);
            }
        }
Example #36
0
        public static List <IntPtr> ScanInt32Value(Int32 pid, Int32 baseAddress, Int32 value)
        {
            List <IntPtr>            result = new List <IntPtr>();
            MEMORY_BASIC_INFORMATION mbi    = new MEMORY_BASIC_INFORMATION();
            Int32  offset   = 0;
            Int32  scanSize = 0;
            IntPtr byteread = IntPtr.Zero;

            IntPtr hProcess = OpenProcess(ProcessAccessFlags.All, false, pid);

            if (hProcess == IntPtr.Zero)
            {
                return(result);
            }
            scanSize = 0x7FFFFFFF;

            while (offset < scanSize)
            {
                int count = VirtualQueryEx(hProcess, (IntPtr)baseAddress + offset, out mbi, (uint)Marshal.SizeOf(mbi));
                if (count == 0)
                {
                    break;
                }
                if (mbi.State != 0x10000) // MEM_FREE
                {
                    byte[] buffer = new byte[(int)mbi.RegionSize];
                    ReadProcessMemory(hProcess, mbi.BaseAddress, buffer, (uint)mbi.RegionSize, out byteread);

                    for (int i = 0; i < buffer.Length; i += sizeof(Int32))
                    {
                        if (value == BitConverter.ToInt32(buffer, i))
                        {
                            result.Add((IntPtr)(uint)mbi.BaseAddress + i);
                        }
                    }
                }
                offset += (int)mbi.RegionSize;
            }

            CloseHandle(hProcess);
            return(result);
        }
        private void InitializeScanMemory()
        {
            var sysInfo = new SYSTEM_INFO();

            GetSystemInfo(out sysInfo);
            var    mbi        = new MEMORY_BASIC_INFORMATION();
            IntPtr procHandle = OpenProcess(0x10 | 0x20 | 0x400, false, process.Id);

            uint mbiSize = (uint)Marshal.SizeOf(mbi);

            uint minAddr = 0;
            uint maxAddr = (uint)sysInfo.MaxAddress;

            bool isDone      = false;
            long findAddress = 0;

            do
            {
                VirtualQueryEx(procHandle, sysInfo.MinAddress, out mbi, mbiSize);
                byte[] buffer    = new byte[(int)mbi.RegionSize];
                int    readBytes = 0;
                if (mbi.RegionSize.ToInt32() > 0)
                {
                    ReadProcessMemory(procHandle, (IntPtr)minAddr, buffer, buffer.Length, out readBytes);
                    if (readBytes > 0)
                    {
                        var searchEngine = new BoyerMoore(AstConstants.SCAN_PATTERN);
                        int resultOffset = searchEngine.Search(buffer);
                        if (resultOffset > 0)
                        {
                            findAddress = minAddr + resultOffset;
                            isDone      = true;
                        }
                    }
                }

                minAddr += (uint)mbi.RegionSize;
            } while (minAddr < maxAddr && !isDone);

            baseAddress = IntPtr.Add((IntPtr)findAddress, -0x4006);
            Memory.WriteInt32(baseAddress, 142857);
        }
Example #38
0
        public void PointerStart()
        {
            DumpMemorySynchronously();
            PointerHistory.Add(new List <PointerStructure>());


            IntPtr _currentAddress           = new IntPtr(BitConverter.ToInt32(CurrentAddress, 0));
            MEMORY_BASIC_INFORMATION memInfo = new MEMORY_BASIC_INFORMATION();

            VirtualQueryEx(targetHandle, _currentAddress, out memInfo, (uint)Marshal.SizeOf(memInfo));
            PointerStructure pointer = new PointerStructure((uint)_currentAddress, new RegionStructure(memInfo.BaseAddress, (int)memInfo.RegionSize));

            ZweiundVierzig(pointer);
            //MultiPointerSearch(pointer);


            int egal = 0;

            PointerOutput = MemoryConverter.CreateDataGridForPointer(PointerHistory);
        }
Example #39
0
        public static int WriteProcessMemoryFloat(int processHandle, int address, float value, bool forceProtection = false)
        {
            if (forceProtection)
            {
                MEMORY_BASIC_INFORMATION info = new MEMORY_BASIC_INFORMATION();
                int query = VirtualQueryEx((IntPtr)processHandle, (IntPtr)address, out info, (uint)Marshal.SizeOf(typeof(MEMORY_BASIC_INFORMATION)));

                if (info.Protect == 2)
                {
                    uint oldProtect      = 0;
                    bool protectExecuted = VirtualProtectEx((IntPtr)processHandle, (IntPtr)info.BaseAddress, (UIntPtr)(int)info.RegionSize, (uint)Protection.PAGE_READWRITE, out oldProtect);
                }
            }
            int bytesReadOrWritten = 0;

            byte[] buffer  = BitConverter.GetBytes(value);
            bool   success = Memory.WriteProcessMemory((int)processHandle, address, buffer, buffer.Length, ref bytesReadOrWritten);

            return(bytesReadOrWritten);
        }
Example #40
0
        /// <summary>
        /// Gets managed heap address
        /// </summary>
        private static unsafe void GetManagedHeap(IntPtr offset, out IntPtr heapsOffset, out IntPtr lastHeapByte, bool heaponly)
        {
            var somePtr = EntityPtr.ToPointer("sample");
            var memoryBasicInformation = new MEMORY_BASIC_INFORMATION();

            heapsOffset = IntPtr.Zero;
            lastHeapByte = IntPtr.Zero;
            unsafe
            {
                while (VirtualQuery(offset, ref memoryBasicInformation, (IntPtr) Marshal.SizeOf(memoryBasicInformation)) !=
                       IntPtr.Zero)
                {
                    var isManagedHeap = (long) memoryBasicInformation.BaseAddress < (long) somePtr &&
                                        (long) somePtr <
                                        ((long) memoryBasicInformation.BaseAddress + (long) memoryBasicInformation.RegionSize);

                    if (isManagedHeap || !heaponly)
                    {
                        Console.WriteLine(
                            "{7} base addr: 0x{0:X8} size: 0x{1:x8} type: {2:x8} alloc base: {3:x8} state: {4:x8} prot: {5:x2} alloc prot: {6:x8}",
                            (int) memoryBasicInformation.BaseAddress,
                            memoryBasicInformation.RegionSize,
                            memoryBasicInformation.Type,
                            (int) memoryBasicInformation.AllocationBase,
                            memoryBasicInformation.State,
                            memoryBasicInformation.Protect,
                            memoryBasicInformation.AllocationProtect,
                            isManagedHeap ? " ** " : "    ");
                    }

                    if (isManagedHeap)
                    {
                        heapsOffset = offset;
                        lastHeapByte = (IntPtr) ((long) offset + (long) memoryBasicInformation.RegionSize);
                    }

                    offset = (IntPtr) ((long) offset + (long) memoryBasicInformation.RegionSize);
                }
            }
        }
Example #41
0
		public MEMORY_BASIC_INFORMATION VirtualQuery(Int32 address)
		{
			var info = new MEMORY_BASIC_INFORMATION();
			var ret = VirtualQueryEx(Handle, address, ref info, Marshal.SizeOf(typeof(MEMORY_BASIC_INFORMATION)));
			if (ret == 0)
				throw new Win32Exception();
			return info;
		}
Example #42
0
		static extern Int32 VirtualQueryEx(IntPtr handle, Int32 address, ref MEMORY_BASIC_INFORMATION buffer, Int32 sizeOfBuffer);
Example #43
0
        /// <summary>
        /// Maps the view.
        /// </summary>
        private void MapView()
        {
            IntPtr ptr = MapViewOfFile(_sharedMemoryHandle.GetHandle(),
                                    FileMapAccess.FileMapRead | FileMapAccess.FileMapWrite,
                                    (uint)0,
                                    0,
                                    Size);
            if (ptr == IntPtr.Zero)
            {
                throw new InvalidOperationException("Invalid Handle. Filed to map view");
            }
            if (Size == 0)
            {
                MEMORY_BASIC_INFORMATION info = new MEMORY_BASIC_INFORMATION();

                VirtualQuery(ref ptr, ref info, (int)System.Runtime.InteropServices.Marshal.SizeOf(info));
                Size = info.RegionSize;
            }

            _stream = new SharedMemoryStream(ptr, Size);
        }
Example #44
0
 internal static extern int VirtualQuery(ref IntPtr lpAddress,
     ref MEMORY_BASIC_INFORMATION lpBuffer,
     int dwLength
     );
Example #45
0
 internal static unsafe extern IntPtr VirtualQuery(
     IntPtr address,
     ref MEMORY_BASIC_INFORMATION buffer,
     IntPtr sizeOfBuffer
 );
Example #46
0
 internal static extern UIntPtr VirtualQuery(UIntPtr lpAddress, ref MEMORY_BASIC_INFORMATION lpBuffer, UIntPtr dwLength);
Example #47
0
 unsafe internal static extern UIntPtr VirtualQuery(void* address, ref MEMORY_BASIC_INFORMATION buffer, UIntPtr sizeOfBuffer);
        public static extern int VirtualQuery(
			byte* lpAddress,
			MEMORY_BASIC_INFORMATION* lpBuffer,
			IntPtr dwLength
		);
 public static extern IntPtr VirtualQueryEx(IntPtr hProcess, IntPtr lpAddress, ref MEMORY_BASIC_INFORMATION lpBuffer, IntPtr dwLength);
 internal static extern IntPtr VirtualQuery(SafeMemoryMappedViewHandle address, ref MEMORY_BASIC_INFORMATION buffer, IntPtr sizeOfBuffer);
Example #51
0
        /// <summary>
        /// Scan the memory for any chunks that are missing from the whitelist table
        /// </summary>
        public static void ScanMissingChunks()
        {
            SYSTEM_INFO sys_info;
            GetSystemInfo(out sys_info);

            IntPtr proc_min_address = sys_info.minimumApplicationAddress;
            IntPtr proc_max_address = sys_info.maximumApplicationAddress;

            long proc_min_address_l = (long)proc_min_address;
            long proc_max_address_l = (long)proc_max_address;

            long sys_min_address_l = (long)proc_min_address;

            Process[] processes = ProcessManager.GetTibiaProcesses();
            if (processes == null || processes.Length == 0) {
                // Tibia process could not be found, wait for a bit and return
                Thread.Sleep(250);
                return;
            }
            flashClient = ProcessManager.IsFlashClient();
            foreach (Process process in processes) {
                if (!whitelistedAddresses.ContainsKey(process.Id)) whitelistedAddresses.Add(process.Id, new List<long>());
                List<long> whitelist = whitelistedAddresses[process.Id];

                proc_min_address_l = sys_min_address_l;

                IntPtr processHandle = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_WM_READ, false, process.Id);
                MEMORY_BASIC_INFORMATION mem_basic_info = new MEMORY_BASIC_INFORMATION();
                int bytesRead = 0;  // number of bytes read with ReadProcessMemory
                int scanSpeed = SettingsManager.getSettingInt("ScanSpeed");
                try {
                    while (proc_min_address_l < proc_max_address_l) {
                        proc_min_address = new IntPtr(proc_min_address_l);
                        // 28 = sizeof(MEMORY_BASIC_INFORMATION)
                        VirtualQueryEx(processHandle, proc_min_address, out mem_basic_info, 28);

                        long addr = (long)proc_min_address;
                        // check if this memory chunk is accessible
                        if (mem_basic_info.Protect == PAGE_READWRITE && mem_basic_info.State == MEM_COMMIT) {
                            if (!whitelist.Contains(addr)) {
                                if (missingChunksBuffer == null || missingChunksBuffer.Length < mem_basic_info.RegionSize) {
                                    missingChunksBuffer = new byte[mem_basic_info.RegionSize];
                                }

                                // read everything in the buffer above
                                ReadProcessMemory((int)processHandle, mem_basic_info.BaseAddress, missingChunksBuffer, mem_basic_info.RegionSize, ref bytesRead);
                                // scan the memory for strings that start with timestamps and end with the null terminator ('\0')
                                IEnumerable<string> timestampLines;
                                if (!flashClient) {
                                    timestampLines = Parser.FindTimestamps(missingChunksBuffer, bytesRead);
                                } else {
                                    timestampLines = Parser.FindTimestampsFlash(missingChunksBuffer, bytesRead);
                                }

                                // if there are any timestamps found, add the address to the list of whitelisted addresses
                                foreach (string str in timestampLines) {
                                    whitelist.Add(addr);
                                    break;
                                }

                                // performance throttling sleep after every scan (depending on scanSpeed setting)
                                if (!initialScan) {
                                    Thread.Sleep(10 + scanSpeed);
                                } else if (scanSpeed > 50) {
                                    Thread.Sleep(scanSpeed - 50);
                                }
                            }
                        }
                        // move to the next memory chunk
                        proc_min_address_l += mem_basic_info.RegionSize;
                    }
                } catch(Exception ex) {
                    Console.WriteLine(ex.Message);
                    return;
                }
            }
            initialScan = false;
        }
Example #52
0
        // string search run mode
        public static void memScanString(CliArgs myargs)
        {
            IPAddress ipAddress;
            IPEndPoint remoteIP;
            Socket sender = null;
            System.IO.StreamWriter file = null;

            // writing output to socket
            if (myargs.mode.Equals("socket"))
            {
                try
                {
                    ipAddress = IPAddress.Parse(myargs.ipaddr);
                    remoteIP = new IPEndPoint(ipAddress, myargs.portnum);
                    sender = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    sender.Connect(remoteIP);
                    Console.WriteLine("Socket connected to {0}", sender.RemoteEndPoint.ToString());
                }
                catch (SocketException se)
                {
                    Console.WriteLine("SocketException : {0}", se.ToString());
                }
            }

            // writing output to file
            if (myargs.mode.Equals("file"))
            {
                file = new System.IO.StreamWriter(myargs.filename);
                file.AutoFlush = true;
            }

            // to infinity, and beyond!
            while (true)
            {
                // getting minimum & maximum address
                SYSTEM_INFO sys_info = new SYSTEM_INFO();
                GetSystemInfo(out sys_info);

                IntPtr proc_min_address = sys_info.minimumApplicationAddress;
                IntPtr proc_max_address = sys_info.maximumApplicationAddress;

                // saving the values as long ints to avoid  lot of casts later
                long proc_min_address_l = (long)proc_min_address;
                long proc_max_address_l = (long)proc_max_address;

                String toSend = "";

                // opening the process with desired access level
                IntPtr processHandle = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_WM_READ, false, process.Id);

                // this will store any information we get from VirtualQueryEx()
                MEMORY_BASIC_INFORMATION mem_basic_info = new MEMORY_BASIC_INFORMATION();

                // number of bytes read with ReadProcessMemory
                int bytesRead = 0;

                // for some efficiencies, pre-compute prepostfix values
                int postfix = myargs.searchterm.Length + (myargs.prepostfix * 2);

                while (proc_min_address_l < proc_max_address_l)
                {
                    // 28 = sizeof(MEMORY_BASIC_INFORMATION)
                    VirtualQueryEx(processHandle, proc_min_address, out mem_basic_info, 28);

                    // if this memory chunk is accessible
                    if (mem_basic_info.Protect == PAGE_READWRITE && mem_basic_info.State == MEM_COMMIT)
                    {
                        byte[] buffer = new byte[mem_basic_info.RegionSize];

                        // read everything in the buffer above
                        ReadProcessMemory((int)processHandle, mem_basic_info.BaseAddress, buffer, mem_basic_info.RegionSize, ref bytesRead);

                        String memStringASCII = Encoding.ASCII.GetString(buffer);
                        String memStringUNICODE = Encoding.Unicode.GetString(buffer);

                        // does the search terms exist in this chunk in ASCII form?
                        if (memStringASCII.Contains(myargs.searchterm))
                        {
                            int idex = 0;
                            while ((idex = memStringASCII.IndexOf(myargs.searchterm, idex)) != -1)
                            {
                                toSend += "0x" + (mem_basic_info.BaseAddress + idex).ToString() + ":A:" + memStringASCII.Substring(idex - myargs.prepostfix, postfix) + "\n";

                                if (myargs.mode.Equals("socket"))
                                {
                                    byte[] msg = Encoding.ASCII.GetBytes(toSend);
                                    int bytesSent = sender.Send(msg);
                                }
                                if (myargs.mode.Equals("file"))
                                {
                                    file.WriteLine(toSend);
                                }
                                if (myargs.mode.Equals("stdio"))
                                {
                                    Console.WriteLine(toSend);
                                }
                                // enter sandman
                                System.Threading.Thread.Sleep(myargs.delay);
                                toSend = "";
                                idex++;
                            }
                        }

                        // does the search terms exist in this chunk in UNICODE form?
                        if (memStringUNICODE.Contains(myargs.searchterm))
                        {

                            int idex = 0;
                            while ((idex = memStringUNICODE.IndexOf(myargs.searchterm, idex)) != -1)
                            {
                                toSend += "0x" + (mem_basic_info.BaseAddress + idex).ToString() + ":U:" + memStringUNICODE.Substring(idex - myargs.prepostfix, postfix) + "\n";

                                if (myargs.mode.Equals("socket"))
                                {
                                    byte[] msg = Encoding.ASCII.GetBytes(toSend);
                                    int bytesSent = sender.Send(msg);
                                }
                                if (myargs.mode.Equals("file"))
                                {
                                    file.WriteLine(toSend);
                                }
                                if (myargs.mode.Equals("stdio"))
                                {
                                    Console.WriteLine(toSend);
                                }
                                // enter sandman
                                System.Threading.Thread.Sleep(myargs.delay);
                                toSend = "";
                                idex++;
                            }
                        }
                    }

                    // truffle shuffle - moving on chunk
                    proc_min_address_l += mem_basic_info.RegionSize;
                    proc_min_address = new IntPtr(proc_min_address_l);
                }
            }
            // ask Turing if we'll ever get here...
            sender.Shutdown(SocketShutdown.Both);
            sender.Close();
            if (myargs.mode.Equals("file"))
            {
                file.Close();
            }
        }
Example #53
0
 static extern int VirtualQueryEx(IntPtr hProcess, 
     IntPtr lpAddress, 
     out MEMORY_BASIC_INFORMATION lpBuffer, 
     uint dwLength);
        private ReadMemoryResults ReadMemory()
        {
            ReadMemoryResults results = null;
            SYSTEM_INFO sys_info = new SYSTEM_INFO();
            GetSystemInfo(out sys_info);

            IntPtr proc_min_address = sys_info.minimumApplicationAddress;
            IntPtr proc_max_address = sys_info.maximumApplicationAddress;

            long proc_min_address_l = (long)proc_min_address;
            long proc_max_address_l = (long)proc_max_address;
            Process process = GetTibiaProcess();
            if (process == null) {
                // Tibia process could not be found, wait for a bit and return
                Thread.Sleep(250);
                return null;
            }
            flashClient = TibiaClientName.ToLower().Contains("flash") || TibiaClientName.ToLower().Contains("chrome");
            IntPtr processHandle = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_WM_READ, false, process.Id);
            MEMORY_BASIC_INFORMATION mem_basic_info = new MEMORY_BASIC_INFORMATION();
            int bytesRead = 0;  // number of bytes read with ReadProcessMemory
            int scanSpeed = SettingsManager.getSettingInt("ScanSpeed");
            try {
                results = new ReadMemoryResults();
                while (proc_min_address_l < proc_max_address_l) {
                    proc_min_address = new IntPtr(proc_min_address_l);
                    // 28 = sizeof(MEMORY_BASIC_INFORMATION)
                    VirtualQueryEx(processHandle, proc_min_address, out mem_basic_info, 28);

                    // check if this memory chunk is accessible
                    if (mem_basic_info.Protect == PAGE_READWRITE && mem_basic_info.State == MEM_COMMIT) {
                        if (!memorySegments.Contains(mem_basic_info.BaseAddress)) {
                            byte[] buffer = new byte[mem_basic_info.RegionSize];

                            // read everything in the buffer above
                            ReadProcessMemory((int)processHandle, mem_basic_info.BaseAddress, buffer, mem_basic_info.RegionSize, ref bytesRead);
                            // scan the memory for strings that start with timestamps and end with the null terminator ('\0')
                            List<string> strings;
                            if (!flashClient) {
                                strings = FindTimestamps(buffer);
                            } else {
                                strings = FindTimestampsFlash(buffer);
                            }
                            if (strings.Count > 0) {
                                // if any timestamp strings were found, scan the chunk for any messages
                                SearchChunk(strings, results);
                            } else {
                                memorySegments.Add(mem_basic_info.BaseAddress);
                            }
                            // performance throttling sleep after every scan (depending on scanSpeed setting)
                            if (scanSpeed > 0) {
                                Thread.Sleep(scanSpeed);
                            }
                        }
                    }

                    // move to the next memory chunk
                    proc_min_address_l += mem_basic_info.RegionSize;
                }
            } catch {
                return null;
            }
            if (memorySegments.Count > 10) {
                memorySegments.RemoveRange(0, 10);
            } else {
                memorySegments.Clear();
            }
            process.Dispose();
            FinalCleanup(results);
            return results;
        }
Example #55
0
 internal extern static UIntPtr VirtualQuery(SafeMemoryMappedViewHandle lpAddress, ref MEMORY_BASIC_INFORMATION lpBuffer, UIntPtr dwLength);
        public IEnumerable<MEMORY_BASIC_INFORMATION> MemoryRegions()
        {
            // getting minimum & maximum address

            SYSTEM_INFO sys_info = new SYSTEM_INFO();
            GetSystemInfo(out sys_info);

            IntPtr proc_min_address = sys_info.minimumApplicationAddress;
            IntPtr proc_max_address = sys_info.maximumApplicationAddress;

            // saving the values as long ints so I won't have to do a lot of casts later
            long proc_min_address_l = (long)proc_min_address;
            long proc_max_address_l = (long)proc_max_address;

            MEMORY_BASIC_INFORMATION mem_basic_info = new MEMORY_BASIC_INFORMATION();

            long current = proc_min_address_l;
            while (current < proc_max_address_l)
            {
                var informationSize = VirtualQueryEx(processHandle, (IntPtr)current, out mem_basic_info, (uint)Marshal.SizeOf(mem_basic_info));
                if (informationSize == 0)
                    throw new Win32Exception();

                yield return mem_basic_info;

                // move to the next memory chunk
                current += mem_basic_info.RegionSize;
            }
        }
Example #57
0
 internal extern static UIntPtr VirtualQuery(IntPtr lpAddress, out MEMORY_BASIC_INFORMATION lpBuffer, UIntPtr dwLength);
Example #58
0
 public static extern IntPtr VirtualQuery(IntPtr lpAddress, out MEMORY_BASIC_INFORMATION lpBuffer, IntPtr dwLength);
Example #59
0
 public static extern IntPtr VirtualQuery(void* address, ref MEMORY_BASIC_INFORMATION buffer, IntPtr length);
Example #60
0
        public bool VirtualQuery(ulong addr, out VirtualQueryData vq)
        {
            vq = new VirtualQueryData();

            MEMORY_BASIC_INFORMATION mem = new MEMORY_BASIC_INFORMATION();
            IntPtr ptr = new IntPtr((long)addr);

            int res = VirtualQueryEx(_process, ptr, ref mem, new IntPtr(Marshal.SizeOf(mem)));
            if (res == 0)
                return false;

            vq.BaseAddress = mem.BaseAddress;
            vq.Size = mem.Size;
            return true;
        }