Форум по Delphi программированию

Delphi Sources



Вернуться   Форум по Delphi программированию > Все о Delphi > Программа и интерфейс
Ник
Пароль
Регистрация <<         Правила форума         >> FAQ Пользователи Календарь Поиск Сообщения за сегодня Все разделы прочитаны

Ответ
 
Опции темы Поиск в этой теме Опции просмотра
  #1  
Старый 25.11.2010, 22:00
Аватар для v1s2222
v1s2222 v1s2222 вне форума
Продвинутый
 
Регистрация: 07.09.2010
Сообщения: 726
Репутация: 26711
По умолчанию Дебаг

Здравствуйте форумчане
Возник не большой вопрос: надо из процесса вытащить определенную переменную (возможно, строку, возможно, число).
Вообще можно сказать, что это взлом программ, но мне это надо не для взлома, а для дебага.
Объясню еще раз: надо найти в определенном процессе строку (то бишь надо найти ее адрес). После этого - в процесс по найденному адресу надо записать другой текст (мой)... но я понимаю, что если размер нового текста будет равен предыдущему, то все будет нормально, а вот если например мой текст по длине будет меньше, то надо дописывать нули, а вот как поступать, если текст мой больше, чем тот, что был... надо заменять точку входа и т.д. а вот как это сделать пока что не понимаю... Помогите очень надо!

ЗЫ но так как я читал в свое время правила форума... то:
надеюсь, что это не относиться к пункту 2.7:
"2.7. На форуме запрещено обсуждать все, что относится к взлому, незаконному использованию и распространению программного обеспечения.", т.к. мне это необходимо далеко не для взлома...
__________________
Помогаю за Спасибо
Ответить с цитированием
  #2  
Старый 25.11.2010, 23:00
Аватар для v1s2222
v1s2222 v1s2222 вне форума
Продвинутый
 
Регистрация: 07.09.2010
Сообщения: 726
Репутация: 26711
По умолчанию

Уже сам нашел почти то, что хотел
Спасибо
__________________
Помогаю за Спасибо
Ответить с цитированием
  #3  
Старый 26.11.2010, 00:22
Аватар для Bargest
Bargest Bargest вне форума
Профессионал
 
Регистрация: 19.10.2010
Адрес: Москва
Сообщения: 2,390
Версия Delphi: XE3/VS12/FASM
Репутация: 14665
По умолчанию

хмм.. интересно, как писать в чужой процесс? поделитесь пожалста))
а насчет текста больше - можно нарыть, где находится эта переменная (поискать упоминание адреса этой строки), вписать туда другой адрес, и по новому адресу прописать нужный текст. Правда это чуток замусорит оперативку.
мб так
__________________
jmp $ ; Happy End!
The Cake Is A Lie.
Ответить с цитированием
  #4  
Старый 26.11.2010, 15:58
Аватар для v1s2222
v1s2222 v1s2222 вне форума
Продвинутый
 
Регистрация: 07.09.2010
Сообщения: 726
Репутация: 26711
По умолчанию

Пожалуйста:
Код:
unit MemoryAdreses;

{
  Made By SVSD_VAL
   Site   : SVSD.MirGames.Ru
   ICq    : 223-725-915
   Mail   : ValDIm_05@mail.ru / SVSD_VAL@SibNet.ru
   Jabber : svsd_val@Jabber.Sibnet.ru
}

{$Warnings off}

interface

uses
  Windows;

type
  TMappedAddress = Record
    Address, Size: Cardinal;
  end;

  TMemoryAdres = Record
    MemoryAddress: Cardinal;
    Value: Int64;
    bType: byte;
  end;

  TAddreses = object
    Address: Array of TMemoryAdres;
    Procedure Add(Addres: Cardinal; Value, ByteType: Int64);
    Procedure Remove(id: Cardinal);
    Function  Get(id: Cardinal): TMemoryAdres;
    Procedure Clear;
  end;

  TMemorySearcher = Class
  private
    Mapped: Array of TMappedAddress; // This holds all the info about the R/W memory blocks
    MapsCount: Integer;                 // The number of R/W blocks in Mapped
    Addreses: TAddreses;               // Our addreses in memory

    H_WND,
    H_PID,
    H_PROC: LongWord;

    RW,
    Addreses_count: Cardinal;
    SeekTime: Integer;

    Procedure OpenOrCloseProcess(Open:boolean);
    Procedure MapMemory(BufferSize : Integer; ByteType : Integer);

   public
    Max, Pos: Integer;

    Procedure AssignHandle(Handle: LongWord);

    Procedure AddAddres(addres:Cardinal; value, byteType: Int64);
    Procedure RemoveAddres(id : Integer);
    Procedure Clear;

    Function  SetAddresValue(Addres, ByteType : Cardinal; NewValue:int64):Boolean;
    Function  GetAddresValue(Addres, ByteType : Cardinal; var GetValue:int64):Boolean;
    Function  GetAddres(id:Cardinal):TMemoryAdres;

    Procedure FindValue(Value:Int64;ByteType:Byte; ProcessMessages:Pointer);
    Procedure SortFoundedValue(Value:Int64; ProcessMessages:Pointer);
    Property  AddresCount :cardinal read Addreses_count;
  end;

implementation

const
  Address_begin = $400000;
  Address_end   = $80000000;
  BufferSize    = 4096;

{ --------------------------------------------------------------------------- }
{ Addreses manager ---------------------------------------------------------- }
{ --------------------------------------------------------------------------- }
procedure TAddreses.Add(addres: Cardinal; value, ByteType: Int64);
var
  i: Integer;
begin
  I := Length(Address);
  SetLength(Address, I+1);
  Address[i].MemoryAddress := AddRes;
  Address[i].Value         := Value;
  Address[i].bType         := ByteType;
end;

procedure TAddreses.Remove(id: Cardinal);
begin
  if(id > High(Address)) then Exit;

  Address[id] := Address[High(Address)];
  SetLength(Address, High(Address));
end;

function TAddreses.Get(id: Cardinal): TMemoryAdres;
begin
  if(id > High(Address)) then Exit;

  Result := Address[id];
end;

procedure TAddreses.Clear;
begin
  Address := nil;
end;

{ --------------------------------------------------------------------------- }
{ Memory Manager Our Searcher------------------------------------------------ }
{ --------------------------------------------------------------------------- }
procedure TMemorySearcher.OpenOrCloseProcess(Open: Boolean);
begin
  if(Open) then begin
    H_PROC := openprocess(process_all_access,false,H_PID);
  end
  else begin
    CloseHandle(H_Proc);
    h_proc := 0;
  end;
end;

procedure TMemorySearcher.AssignHandle(Handle: LongWord);
begin
  if(Handle = 0) then Exit;

  H_WND := Handle;
  GetWindowThreadProcessID(h_wnd, H_PID);
end;

procedure TMemorySearcher.AddAddres(addres: Cardinal; value, ByteType: Int64);
begin
  Addreses.Add(addres, value, ByteType);
end;

procedure TMemorySearcher.RemoveAddres(id: Integer);
begin
  Addreses.Remove(id);
end;

function TMemorySearcher.GetAddres(id: Cardinal): TMemoryAdres;
begin
  Result := Addreses.Get(id);
end;


procedure TMemorySearcher.Clear;
begin
  Addreses.Clear;
end;


function TMemorySearcher.GetAddresValue(Addres, ByteType: Cardinal; var GetValue: int64): Boolean;
begin
  Result := False;

  GetValue:=0;
  OpenOrCloseProcess(True);
  if(H_Proc <> 0 ) and
  ReadProcessMemory(H_Proc, Pointer(Addres), @GetValue, ByteType, rw) then
    Result := True;

  OpenOrCloseProcess(False);
end;

function TMemorySearcher.SetAddresValue(Addres, ByteType : Cardinal; NewValue: int64): Boolean;
begin
  Result := False;

  OpenOrCloseProcess(True);
  if(H_Proc <> 0 )and
  WriteProcessMemory(H_Proc, Pointer(Addres), @NewValue, ByteType, rw) then
    Result := True;

  OpenOrCloseProcess(False);
end;

procedure TMemorySearcher.FindValue(Value: Int64; ByteType: Byte; ProcessMessages: Pointer);
var
  i, i2      : Integer;
  FoundValue : Int64;
  PM         : procedure;
  Buffer     : Array of Byte;
begin
  PM := ProcessMessages;

  MapMemory(BufferSize, ByteType);
  SetLength(Buffer, BufferSize + (ByteType - 1));

  OpenOrCloseProcess(True);

  SeekTime := gettickcount;
  Max := MapsCount;

  for i := 0 to MapsCount do begin
    ReadProcessMemory(H_Proc, Pointer(Mapped[ I ].Address), @Buffer[0], Mapped[i].Size, Rw);

       // Check for a match
    for i2 := 0 to (buffersize - byteType - 1) do begin
      FoundValue := 0;
      CopyMemory(@FoundValue, @Buffer[I2], ByteType);

      if(FoundValue = Value) then
        AddAddres(Mapped[i].Address + i2, FoundValue, ByteType);
    end;

    if(i mod 100 = 0) and (@PM <> nil) then
      PM;

    POS := i;
  end;

  SetLength(Buffer, 0 );
  Addreses_count:= Length(Addreses.Address);

  OpenOrCloseProcess(False);

  SeekTime := gettickcount - SeekTime;

  if(@PM <> nil) then
    PM;
end;

procedure TMemorySearcher.SortFoundedValue(Value: Int64; ProcessMessages: Pointer);
var
  i         : Integer;
  FoundValue: Int64;
  PM        : procedure;
  Buffer    : Array of Byte;
  Founded   : TAddreses;
begin
  PM := ProcessMessages;
  OpenOrCloseProcess(True);

  SeekTime := GetTickCount;

  SetLength(Buffer, 8);
  FillChar(buffer[0], 8, 0);

  for i := 0 to Length(Addreses.Address) - 1 do
    With Addreses do begin
      FoundValue:=0;

      ReadProcessMemory(H_Proc, Pointer(Address[i].MemoryAddress), @Buffer[0], Address[i].bType, Rw);

      CopyMemory(@FoundValue, @Buffer[0], Address[i].bType);

      if(FoundValue = Value) then
        Founded.Add(Address[i].MemoryAddress, FoundValue, Address[i].bType);

      if(i mod 100 = 0) and (@PM <> nil) then
        PM;
    end; // with
  SetLength(Buffer, 0);

  Addreses.Clear;

  SetLength(Addreses.Address, Length(Founded.Address));
  Move(Founded.Address[0].MemoryAddress, Addreses.Address[0].MemoryAddress, Length(Founded.Address) * SizeOf(TMemoryAdres) );

  Addreses_count:= Length(addreses.Address);
  OpenOrCloseProcess(False);

  SeekTime := GetTickCount - SeekTime;
end;

procedure TMemorySearcher.MapMemory(BufferSize: Integer; ByteType: Integer);
var
  MBI       : MEMORY_BASIC_INFORMATION;
  dwAddress : Cardinal;
  Region    : Integer;
  Block     : Integer;
begin
  dwAddress := Address_begin;

  Finalize(Mapped);
  Mapped := nil;

  MapsCount := 0;

  H_Proc    := OpenProcess(PROCESS_QUERY_INFORMATION, False, H_PID);

  While(VirtualQueryEx(H_Proc, Pointer(dwAddress), MBI, SizeOf(MEMORY_BASIC_INFORMATION)) > 0)
  and (Integer(MBI.BaseAddress) + MBI.RegionSize < Address_end) do begin
    if(MBI.Protect = PAGE_READWRITE) and ((MBI.State = MEM_COMMIT) or (MBI.State = MEM_RESERVE)) then begin
      Region := MBI.RegionSize;
      Block  := 0;

      Repeat
        if(Block > 0) then
          MBI.BaseAddress := Pointer(Integer(MBI.BaseAddress) - (ByteType - 1));

        MapsCount := Length(Mapped);
        SetLength(Mapped, MapsCount+1);
        Mapped[MapsCount].Address := Integer(MBI.BaseAddress) + (MBI.RegionSize - Region);

        if(Region <= BufferSize) then begin
          if(Block > 0) then
            Mapped[MapsCount].Size := Region + (ByteType - 1)
          else
            Mapped[MapsCount].Size := Region;

          Region := 0;
        end
        else
        begin
          if(Block > 0) then
            Mapped[MapsCount].Size := BufferSize + (ByteType - 1)
          else
            Mapped[MapsCount].Size := BufferSize;

          inc(Block);
          Region := Region - BufferSize;
        end;
      Until Region = 0;
    end;

    Inc(dwAddress, MBI.RegionSize);
  end; // while

  CloseHandle(h_proc);
end;

end.

ЗЫ не мой модуль но в принципе понять, как работает можно.
__________________
Помогаю за Спасибо
Ответить с цитированием
  #5  
Старый 26.11.2010, 20:47
Аватар для Bargest
Bargest Bargest вне форума
Профессионал
 
Регистрация: 19.10.2010
Адрес: Москва
Сообщения: 2,390
Версия Delphi: XE3/VS12/FASM
Репутация: 14665
По умолчанию

Вау, я всегда верил в WinAPI! спасибо. Не знал, что прямо в апи есть функции такие, как например ReadProcessMemory.
__________________
jmp $ ; Happy End!
The Cake Is A Lie.
Ответить с цитированием
  #6  
Старый 26.11.2010, 21:37
Аватар для v1s2222
v1s2222 v1s2222 вне форума
Продвинутый
 
Регистрация: 07.09.2010
Сообщения: 726
Репутация: 26711
По умолчанию

Да к счастью есть
Без подобных функций не какие дебагеры бы не работали...
__________________
Помогаю за Спасибо
Ответить с цитированием
Ответ


Delphi Sources

Опции темы Поиск в этой теме
Поиск в этой теме:

Расширенный поиск
Опции просмотра

Ваши права в разделе
Вы не можете создавать темы
Вы не можете отвечать на сообщения
Вы не можете прикреплять файлы
Вы не можете редактировать сообщения

BB-коды Вкл.
Смайлы Вкл.
[IMG] код Вкл.
HTML код Выкл.
Быстрый переход


Часовой пояс GMT +3, время: 09:02.


 

Сайт

Форум

FAQ

RSS лента

Прочее

 

Copyright © Форум "Delphi Sources" by BrokenByte Software, 2004-2023

ВКонтакте   Facebook   Twitter