3
votes

I'm tryin to scan an entire process memory but no success... What I'm doing is: for tests I'm using notepad, so I write there %B and this values in HEX are: 25(%) and 42(B). So the code is:

  while (VirtualQueryEx(PIDHandle, Pointer(MemStart), MemInfo, SizeOf(MemInfo)) <> 0) do
    begin
      if ((MemInfo.State = MEM_COMMIT) and (not (MemInfo.Protect = PAGE_GUARD)
        or (MemInfo.Protect = PAGE_NOACCESS)) and (MemInfo.Protect = PAGE_READWRITE)) then
          begin
            SetLength(Buff, MemInfo.RegionSize);
              if (ReadProcessMemory(PIDHandle, MemInfo.BaseAddress, Buff,
                                        MemInfo.RegionSize, ReceivedBytes)) then
                begin
                for I := 0 to SizeOf(Buff) do
                 begin
   if (IntToHex(Buff[i], 1) = '25') and (IntToHex(Buff[i+2], 1) = '42') then
                  Form1.Memo1.Lines.Append(IntToHex(Buff[i], 1));
                 end;

                end;
          end;
      MemStart:= MemStart + MemInfo.RegionSize;
    end;
  CloseHandle(PIDHandle);
  end;

The var 'Buff' is TBytes (I read about TBytes and think it's same as array of byte). So I'm converting the bytes to Hex, and searching for values: 25 and 42 respectively. The code is like:

if (IntToHex(Buff[i], 1) = '25') and (IntToHex(Buff[i+2], 1) = '42') then

Because have 00 between the hex values. So I need to add '+2'. How can I scan the entire memory for this values??

1

1 Answers

8
votes

Notepad uses Unicode so you'll need to look for UTF-16 encoded data, $0025 and $0042.

I don't understand why you feel the need to convert into hex strings before comparing. There's nothing special about hex that requires the use of strings. Hexadecimal is just a number system with base-16. So, decimal 32 is the same as hexadecimal 20, i.e. 32=$20. Do your comparison directly with integral values:

if (Buff[i]=$25) and (Buff[i+2]=$42) then

That said, taking into account the $00 bytes your test should really be something like this:

var
  Target: string;
....
Target := '%B';
if CompareMem(@Buff[i], @Target[1], Length(Target)*SizeOf(Char)) then
  ....

I don't want to get too deep into the rest of your code, but this line

for I := 0 to SizeOf(Buff) do

is wrong on many different levels.

  1. SizeOf(Buff) returns the size of a pointer since a dynamic array variable is essentially just a pointer. A useful thing to remember is that SizeOf is evaluated at compile time.
  2. If you used Length instead of SizeOf then you would be iterating over the end of the list. To loop over a dynamic array, loop from 0 to Length(...)-1.
  3. But in this case you are accessing index i+2 inside the loop, so you should loop from 0 to Length(...)-3.

But in fact you need to compare against 4 consecutive bytes to find a match. Perhaps like this:

TargetByteLength = Length(Target)*SizeOf(Char);
for i := 0 to Length(Buff)-TargetByteLength do
  if CompareMem(@Buff[i], @Target[1], TargetByteLength) then
    ....