簡體   English   中英

讀取所有進程內存以查找字符串變量 c# 的地址

[英]Reading all process memory to find address of a string variable c#

我有 2 個用 c# 編寫的程序,第一個名為“ScanMe”的程序包含一個包含值“FINDMEEEEEEE”的字符串變量,以及一個值為 1546.22915487 的雙變量。 另一個名為“MemoryScan”的程序讀取第一個程序的所有內存。 我想獲取那個進程的字符串變量的內存地址

當我執行“MemoryScan”並讀取“ScanMe”進程的所有內存時,我嘗試在掃描的所有數據中找到字符串的字節數組,但我什么也沒得到。 如果我嘗試找到雙精度值,我會得到特定的內存地址,並且我也可以更改它的值,但是當我嘗試使用字符串變量執行此操作時,我無法獲得該字符串變量的地址。

ScanMe 和 MemoryScan 代碼:

class Program
{
    public static string FindMeString = "FINDMEEEEEEE";
    public static double FindMeDouble = 1546.22915487;
    static void Main(string[] args)
    {
        while (FindMeDouble == 1546.22915487)
        {
            System.Threading.Thread.Sleep(2000);
        }
        Console.WriteLine(FindMeDouble.ToString());
        Console.ReadLine();
    }
}

using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;

namespace MemoryScan
{
class MemoryController
{

    // REQUIRED CONSTS
    const int PROCESS_QUERY_INFORMATION = 0x0400;
    const int MEM_COMMIT = 0x00001000;
    const int PAGE_READWRITE = 0x04;
    const int PROCESS_WM_READ = 0x0010;
    readonly Dictionary<IntPtr, byte[]> Regions = new Dictionary<IntPtr, byte[]>();
    readonly List<SearchResult> _results = new List<SearchResult>();

    // REQUIRED METHODS
    [DllImport("kernel32.dll")]
    public static extern IntPtr OpenProcess(int dwDesiredAccess, bool bInheritHandle, int dwProcessId);

    [DllImport("kernel32.dll")]
    public static extern bool ReadProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, byte[] lpBuffer, uint dwSize, ref int lpNumberOfBytesRead);

    [DllImport("kernel32.dll")]
    static extern void GetSystemInfo(out SystemInfo lpSystemInfo);

    [DllImport("kernel32.dll", SetLastError = true)]
    static extern int VirtualQueryEx(IntPtr hProcess, IntPtr lpAddress, out MEMORY_BASIC_INFORMATION lpBuffer, int dwLength);

    public enum ProcessorArchitecture
    {
        X86 = 0,
        X64 = 9,
        Arm = -1,
        Itanium = 6,
        Unknown = 0xFFFF
    }

    // REQUIRED STRUCTS
    [StructLayout(LayoutKind.Sequential)]
    public struct SystemInfo
    {
        public ProcessorArchitecture ProcessorArchitecture;
        public uint PageSize;
        public IntPtr MinimumApplicationAddress;
        public IntPtr MaximumApplicationAddress;
        public IntPtr ActiveProcessorMask;
        public uint NumberOfProcessors;
        public uint ProcessorType;
        public uint AllocationGranularity;
        public ushort ProcessorLevel;
        public ushort ProcessorRevision;
    }

    [StructLayout(LayoutKind.Sequential)]
    public struct MEMORY_BASIC_INFORMATION
    {
        public IntPtr BaseAddress;
        public IntPtr AllocationBase;
        public uint AllocationProtect;
        public IntPtr RegionSize;
        public uint State;
        public uint Protect;
        public uint Type;
    }

    public void FindProcessMemory(int processId)
    {
        // getting minimum & maximum address
        SystemInfo sys_info;
        GetSystemInfo(out sys_info);

        uint max_Address = (uint)sys_info.MaximumApplicationAddress;
        // opening the process with desired access level
        IntPtr processHandle = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_WM_READ, false, processId);
        IntPtr current = IntPtr.Zero;

        int bytesRead = 0;  // number of bytes read with ReadProcessMemory
        int dwLength = Marshal.SizeOf(typeof(MEMORY_BASIC_INFORMATION));

        while ((uint)current < max_Address && VirtualQueryEx(processHandle, current, out MEMORY_BASIC_INFORMATION mem_basic_info, dwLength) != 0)
        {
            // if this memory chunk is accessible
            if (mem_basic_info.Protect == PAGE_READWRITE && mem_basic_info.State == MEM_COMMIT)
            {
                byte[] buffer = new byte[(int)mem_basic_info.RegionSize];

                // read everything in the buffer above
                if (ReadProcessMemory(processHandle, mem_basic_info.BaseAddress, buffer, (uint)mem_basic_info.RegionSize, ref bytesRead))
                {
                    Regions.Add(mem_basic_info.BaseAddress, buffer);
                }
                else
                    Console.WriteLine($"Error code: Marshal.GetLastWin32Error()");
            }

            // move to the next memory chunk
            current = IntPtr.Add(mem_basic_info.BaseAddress, mem_basic_info.RegionSize.ToInt32());
        }
        byte[] data = System.Text.Encoding.Unicode.GetBytes("FINDMEEEEEEE");
        foreach (IntPtr address in Regions.Keys)
        {
            foreach (int i in ByteSearch.AllIndexOf(Regions[address], data))
                _results.Add(new SearchResult(IntPtr.Add(address, i), data));
        }
        Console.ReadLine();
    }

}
public static class ByteSearch
{
    static int[] createTable(byte[] pattern)
    {
        int[] table = new int[256];

        for (int i = 0; i < table.Length; i++)
            table[i] = pattern.Length;

        for (int i = 0; i < pattern.Length - 1; i++)
            table[Convert.ToInt32(pattern[i])] = pattern.Length - i - 1;

        return table;
    }

    public static bool matchAtOffset(byte[] toSearch, byte[] pattern, int index)
    {
        if (index + pattern.Length > toSearch.Length)
            return false;

        for (int i = 0; i < pattern.Length; i++)
        {
            if (toSearch[i + index] != pattern[i])
                return false;
        }

        return true;
    }

    public static bool Contains(byte[] toSearch, byte[] pattern)
    {
        return FirstIndexOf(toSearch, pattern) != -1;
    }

    public static int FirstIndexOf(byte[] toSearch, byte[] pattern)
    {
        int[] table = createTable(pattern);
        int position = pattern.Length - 1;

        while (position < toSearch.Length)
        {
            int i;

            for (i = 0; i < pattern.Length; i++)
            {
                if (pattern[pattern.Length - 1 - i] != toSearch[position - i])
                    break;

                if (i == pattern.Length - 1)
                    return position - i;
            }

            position += table[Convert.ToInt32(toSearch[position - i])];
        }

        return -1;
    }

    public static int LastIndexOf(byte[] toSearch, byte[] pattern)
    {
        int ret = -1;
        int[] table = createTable(pattern);
        int position = pattern.Length - 1;

        while (position < toSearch.Length)
        {
            int i;
            bool found = false;

            for (i = 0; i < pattern.Length; i++)
            {
                if (pattern[pattern.Length - 1 - i] != toSearch[position - i])
                    break;

                if (i == pattern.Length - 1)
                {
                    ret = position - i;
                    found = true;
                }
            }

            if (found)
                position++;
            else
                position += table[Convert.ToInt32(toSearch[position - i])];
        }

        return ret;
    }

    public static int[] AllIndexOf(byte[] toSearch, byte[] pattern)
    {
        List<int> indices = new List<int>();
        int[] table = createTable(pattern);
        int position = pattern.Length - 1;

        while (position < toSearch.Length)
        {
            int i;
            bool found = false;

            for (i = 0; i < pattern.Length; i++)
            {
                if (pattern[pattern.Length - 1 - i] != toSearch[position - i])
                    break;

                if (i == pattern.Length - 1)
                {
                    indices.Add(position - i);
                    found = true;
                }
            }

            if (found)
                position++;
            else
                position += table[Convert.ToInt32(toSearch[position - i])];
        }

        return indices.ToArray();
    }
}
public class SearchResult
{
    public SearchResult(IntPtr add, byte[] value)
    {
        Address = add;
        Buffer = value;
    }

    public IntPtr Address { get; set; }

    public byte[] Buffer { get; set; }
}

}

為什么我找不到字符串,當我嘗試找到 double 時,我沒有問題地找到它,甚至我還可以使用 extern writeprocessmemory 更改它的值? 謝謝。

我不確定我是否可以重現您的確切情況,因為您沒有提供最小的可重現示例 但是,我啟動並運行了它 - 具有類似的結果。 然后我想出了以下幾點:

您沒有檢查ReadProcessMemory的返回值。 MSDN 說

如果函數失敗,則返回值為 0(零)。 要獲取擴展錯誤信息,請調用 GetLastError。

0將映射到false ,具體取決於您使用的 PInvoke 簽名。

要獲取最后一個錯誤,請使用Marshal.GetLastWin32Error() 在我的電腦上,錯誤代碼是 299, MSDN 說

ERROR_PARTIAL_COPY

299 (0x12B)

僅部分 ReadProcessMemory 或 WriteProcessMemory 請求已完成。

同時,讀取的字節數( ref bytesRead )為0,因此沒有讀取進程的內存。

請參閱有關此錯誤代碼的相關 SO 問題

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM