Penulis Topik: [Delphi] Get MD5 Loaded Module  (Dibaca 13588 kali)

Offline meong

  • Pro100
  • ****
  • Tulisan: 121
  • Reputation: 203
    • Lihat Profil
[Delphi] Get MD5 Loaded Module
« pada: November 21, 2011, 08:04:46 AM »
Terkadang kita butuh mengambil checksum atau hash dari module/dll yang terload dengan tujuan menggunakannya untuk berbagai keperluan, ex Anti Tampering pada game <- . Nah snippet berikut akan mengenumerasi semua module yang terload (PEB) dan mengambil md5 dari first section, semoga berguna :D.


Kode: [Pilih]
program MemMd5;

uses
  Windows,
  Sysutils,
  JwaNative,
  JwaNtStatus,
  JwaWinType,
  NcxTypes,
  NcxNtDef,
  NcxNtTeb,
  codesitelogging,
  U_UnionApi,
  U_Md5;

type
  PROCESS_BASIC_INFORMATION = record
    ExitStatus: Cardinal;
    PebBaseAddress: PVOID;
    AffinityMask: Cardinal;
    BasePriority: Cardinal;
    UniqueProcessId: Cardinal;
    InheritedFromUniqueProcessId: Cardinal;
  end;
  TProcessBasicInformation = PROCESS_BASIC_INFORMATION;
  PProcessBasicInformation = ^TProcessBasicInformation;

  TImageOptionalHeader64 = packed record
    Magic                       : WORD;
    MajorLinkerVersion          : BYTE;
    MinorLinkerVersion          : BYTE;
    SizeOfCode                  : DWORD;
    SizeOfInitializedData       : DWORD;
    SizeOfUninitializedData     : DWORD;
    AddressOfEntryPoint         : DWORD;
    BaseOfCode                  : DWORD;
    ImageBase                   : int64;
    SectionAlignment            : DWORD;
    FileAlignment               : DWORD;
    MajorOperatingSystemVersion : WORD;
    MinorOperatingSystemVersion : WORD;
    MajorImageVersion           : WORD;
    MinorImageVersion           : WORD;
    MajorSubsystemVersion       : WORD;
    MinorSubsystemVersion       : WORD;
    Win32VersionValue           : DWORD;
    SizeOfImage                 : DWORD;
    SizeOfHeaders               : DWORD;
    CheckSum                    : DWORD;
    Subsystem                   : WORD;
    DllCharacteristics          : WORD;
    SizeOfStackReserve          : int64;
    SizeOfStackCommit           : int64;
    SizeOfHeapReserve           : int64;
    SizeOfHeapCommit            : int64;
    LoaderFlags                 : DWORD;
    NumberOfRvaAndSizes         : DWORD;
    DataDirectory               : array [0..IMAGE_NUMBEROF_DIRECTORY_ENTRIES - 1] of IMAGE_DATA_DIRECTORY;
  end;
  PImageOptionalHeader64 = ^TImageOptionalHeader64;

  PImageBaseRelocation = ^TImageBaseRelocation;
  _IMAGE_BASE_RELOCATION = packed record
    VirtualAddress: DWORD;
    SizeOfBlock: DWORD;
  end;
  TImageBaseRelocation = _IMAGE_BASE_RELOCATION;
  IMAGE_BASE_RELOCATION = _IMAGE_BASE_RELOCATION;

const
  IMAGE_NT_OPTIONAL_HDR32_MAGIC = $10b;  // 32bit PE file
  IMAGE_NT_OPTIONAL_HDR64_MAGIC = $20b;  // 64bit PE file

function NtSuccess(API:AnsiString; AStatus: LongInt): Boolean; overload;
var
  error : DWord;
begin
  Result := AStatus >= 0;
  if result=false then begin
    error := RtlNtStatusToDosError(AStatus);
    SetLastError(error);
    codesite.Sendwinerror('api', error);
  end;
end;

function NtSuccess(AStatus: LongInt): Boolean; overload;
begin
  Result := AStatus >= 0;
end;

function NTApiCall(ApiName: AnsiString; Arg: Array of Const): DWORD; stdcall;
begin
  result := ApiCall32(ApiName, Arg);
  NtSuccess(ApiName, result);
end;

Function GetModuleString(Buff:PWideChar):string;
var
  temp:String;
  I: Integer;
begin
  SetString(temp, Buff, StrLen(Buff));
  I := LastDelimiter('.' + PathDelim + DriveDelim, temp);
  if (I > 0) and (temp[i] = '.') then
    result := Copy(temp, 1, I+3)
  else
    result := temp;
end;

function Align(Value, Align: Cardinal): Cardinal;
begin
  if ((Value mod Align) = 0) then
    Result := Value
  else
    Result := ((Value + Align - 1) div Align) * Align;
end;

Function SetMemProtection(ph: THandle; lpAddress: Pointer; dwSize, flNewProtect: DWORD; var OldProtect: DWORD):boolean;
var
  status: NTStatus;
begin
  Status := NTApiCall('NtProtectVirtualMemory', [
              ph,
              @lpAddress,
              @dwSize,
              flNewProtect,
              @OldProtect
            ]);

  result := NtSuccess(Status);
end;

function GetPeb32(ph : THandle; var PEB : TPeb32):Boolean;
var
  PBI           : PROCESS_BASIC_INFORMATION;
begin
  result := false;

  {Get PROCESS_BASIC_INFORMATION}
  if not NtSuccess(NTApiCall('NtQueryInformationProcess', [ph, Pointer(ProcessBasicInformation), @PBI, SizeOf(PBI), nil])) then begin
    {$IFDEF DebugMode}Codesite.SendWinError('Failed Get PROCESS BASIC INFORMATION  ', Getlasterror);{$ENDIF}
    exit;
  end;

  {Reading PEB}
  if not NtSuccess(NTApiCall('NtReadVirtualMemory', [ph, pbi.PebBaseAddress, @PEB, sizeof(PEB), nil])) then begin
    {$IFDEF DebugMode}Codesite.SendWinError('Failed Reading PEB', Getlasterror);{$ENDIF}
    exit;
  end;

  result := true;
end;

function MD5FirstSectionModule(ph: Thandle; ImageBase:Pointer): String;
var
  pImage:     Pointer;
  pSection:   Pointer;
  INH:        PImageNtHeaders;
  pISH:       PImageSectionHeader;
  Scaddr:     DWord;
  ScSize:     DWord;
  Protect:    DWORD;
begin
  result := '';
  pImage := AllocMem($1000);
  try

    { Read Image }
    if not NtSuccess(NTApiCall('NtReadVirtualMemory', [ph, ImageBase, pImage, $1000, nil])) then begin
      {$IFDEF DebugMode}Codesite.SendWinError('Failed Reading Image ', Getlasterror);{$ENDIF}
      exit;
    end;

    { Check Dos Header }
    if (PImageDosHeader(pImage)^.e_magic <> IMAGE_DOS_SIGNATURE) then exit;

    { Check PE Header }
    INH := Pointer(NativeUint(pImage) + NativeUint(PImageDosHeader(pImage)^._lfanew));
    if (INH^.Signature <> IMAGE_NT_SIGNATURE) then exit;

    { get first section }
    if INH^.OptionalHeader.Magic = IMAGE_NT_OPTIONAL_HDR64_MAGIC then
      pISH := PImageSectionHeader(NativeUint(@INH^.OptionalHeader) + sizeOf(TImageOptionalHeader64))
    else
      pISH := PImageSectionHeader(NativeUint(@INH^.OptionalHeader) + sizeOf(TImageOptionalHeader));

    { get section address }
    Scaddr := Align(pISH^.VirtualAddress, INH^.OptionalHeader.SectionAlignment);

    { get section size }
    ScSize := pISH^.Misc.VirtualSize;
    if (ScSize = 0) then ScSize := pISH^.SizeOfRawData;

    pSection := AllocMem(ScSize);
    try

      { get memory protection }
      SetMemProtection(ph, Pointer(NativeUint(ImageBase)+Scaddr), ScSize, PAGE_EXECUTE_READWRITE, Protect);

      { check if can access}
      if ((Protect and PAGE_NOACCESS) = PAGE_NOACCESS) then begin
        SetMemProtection(ph, Pointer(NativeUint(ImageBase)+Scaddr), ScSize, Protect, Protect);
      end else begin

        { read section }
        if NtSuccess(NTApiCall('NtReadVirtualMemory', [ph, Pointer(NativeUint(ImageBase)+Scaddr), pSection, ScSize, nil])) then begin

          { Get MD5}
          result := MD5DigestToString(MD5Buffer(pSection^, ScSize));
        end;

        { restore the protection }
        SetMemProtection(ph, Pointer(NativeUint(ImageBase)+Scaddr), ScSize, Protect, Protect);
      end;
    finally
      FreeMem(pSection);
    end;
  finally
    FreeMem(pImage);
  end;
end;

procedure PEB32ModuleList(ph : THandle);
var
  PEB           : TPeb32;
  LdrData       : TPebLdrData32;
  LdrModule     : TLdrDataTableEntry32;
  BaseDllName   : Pointer;
  i, dwread     : DWord;
  Head,Current  : DWord;
begin
  if not GetPeb32(ph, PEB) then exit;

  { Reading LoaderData }
  if not NtSuccess(NTApiCall('NtReadVirtualMemory', [ph, PEB.Ldr, @LdrData, sizeof(TPebLdrData32), @dwread])) then begin
    {$IFDEF DebugMode}Codesite.SendWinError('Failed Reading LoaderData ', Getlasterror);{$ENDIF}
    exit;
  end;

  { init for enum the linked list }
  i := 0;
  Head := 0;
  Current := DWord(LdrData.InLoadOrderModuleList.Flink);

  { loop for all ldr entry or module }
  repeat

    { Reading Current entry }
    if not NtSuccess(NTApiCall('NtReadVirtualMemory', [ph, Ptr(Current), @LdrModule, SizeOf(LdrModule), @dwread])) then begin
      {$IFDEF DebugMode}Codesite.SendWinError('Failed Reading Current entry ', Getlasterror);{$ENDIF}
      break;
    end;

    BaseDllName := AllocMem(LdrModule.BaseDllName.Length);
    try

      { Reading BaseDllName }
      if not NtSuccess(NTApiCall('NtReadVirtualMemory', [ph, LdrModule.BaseDllName.Buffer, BaseDllName, LdrModule.BaseDllName.Length, @dwread])) then begin
        {$IFDEF DebugMode}Codesite.SendWinError('Failed Reading BaseDllName', Getlasterror);{$ENDIF}
        break;
      end;

      codesite.send('%s | %s ',[GetModuleString(BaseDllName), MD5FirstSectionModule(ph, LdrModule.DllBase)]);
    finally
      FreeMem(BaseDllName, LdrModule.BaseDllName.Length);
    end;

    { Next Module }
    if i=0 then Head := Dword(LdrModule.InLoadOrderLinks.Blink);
    Current := Dword(LdrModule.InLoadOrderLinks.Flink);
    inc(i);
  until Current = Head;
end;


begin
  try
    PEB32ModuleList(thandle(-1));
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
end.

hmm btw untuk module enumerasi anda bisa menggunakan methode lain misalkan dengan query memory.

directlink : http://cybercoding.wordpress.com/2011/11/21/delphi-get-md5-loaded-module/

Offline suryascience

  • Pro100
  • ****
  • Tulisan: 173
  • Reputation: 189
  • Aku butuh ilmu bukan cendol
    • Lihat Profil
    • Portal pendidikan dasar ilmu-ilmu Exacta
Re: [Delphi] Get MD5 Loaded Module
« Jawab #1 pada: November 22, 2011, 12:10:59 AM »
Maaf keluar dari topik mengenai MD5  :-[ , SMADAVER, tanya dong, gimana sih buat form pake delphi biar tampilannya seperti Windows Media Player gitu  :D , atau seperti Ontrack Easy Recovery yang User Interface nya bisa running di dos mode.
Artikel Suryatekno kini dialihkan ke :
http://achil.besaba.com
Artikel terbarunya :
 http://achil.besaba.com/seo-dimata-orang-awam/

Offline deni.doank

  • Pro10
  • ***
  • Tulisan: 51
  • Reputation: 81
  • Jenis kelamin: Pria
    • Lihat Profil
Re: [Delphi] Get MD5 Loaded Module
« Jawab #2 pada: Juni 04, 2012, 10:30:28 PM »
ini pake compiler Delphi berapa?

Offline meong

  • Pro100
  • ****
  • Tulisan: 121
  • Reputation: 203
    • Lihat Profil
Re: [Delphi] Get MD5 Loaded Module
« Jawab #3 pada: Desember 11, 2012, 03:31:19 PM »
ini pake compiler Delphi berapa?

saya pake compiler delphi xe.. tapi bisa pake delphi 7 juga kok ;)

Offline HyperLinx

  • Pro200
  • *****
  • Tulisan: 230
  • Reputation: 252
    • Lihat Profil
Re: [Delphi] Get MD5 Loaded Module
« Jawab #4 pada: Juli 06, 2013, 04:28:31 PM »
ck ck ck ... yang minusin postingan diatas kayaknya otaknya minus juga nih  :puke: