首页
社区
课程
招聘
[原创]Delphi编写Ring3下的SSDT查看器
发表于: 2010-4-19 10:08 11101

[原创]Delphi编写Ring3下的SSDT查看器

2010-4-19 10:08
11101

网上有一篇很精彩的文章《ring3下用ZwSystemDebugControl获取和恢复SSDT》,恢复的方法是利用ZwSystemDebugControl函数从用户空间拷贝到内核空间。可惜现在从Ring3进入Ring0的方法基本上被杀毒软件给堵住。360 HookK iFastCallEntry函数,也就是从ring3进入ring0的哪个重要函数,所以再利用ntdll.dll的函数ZwSystemDebugContro就无用。但是该代码对PE文件格式的学习很有帮助,所以用DELPHI防照这篇用C写的重新实现,相似度99%。本人也重新对delphi的指针学习得到更深的理解。相信对学习Delphi的同学会有所帮助。l在这里还要感谢木桩等同学。编译好的程序执行如下:
[ ATTACH ] ssdt.JPG  [ /ATTACH ]

源代码如下:
unit SSDT;

interface

uses SysUtils,windows,Graphics;

const
STATUS_INFO_LENGTH_MISMATCH=$C0000004;
SysDbgReadVirtualMemory = 8;
SysDbgWriteVirtualMemory = 9;

//一些常用的内型
type
NTSTATUS=ULONG;
PVOID =Pointer;

PImageBaseRelocation=^TImageBaseRelocation;
  TImageBaseRelocation=Packed Record
     VirtualAddress: DWORD;
     SizeOfBlock: DWORD;
     //TypeOffset: array[0..1] of Word;
end;

PModuleInformation=^TModuleInformation;
TModuleInformation=packed record
    Reserved:array[0..1] of ULONG ;
    Base:Longint;
    Size:Longint;
    Flags: Longint;
    Index:Smallint;
    Unknown : Smallint;
    Loadcount: Smallint;
    ModuleNameOffset:Smallint;
    ImageName:array[0..255] of  CHAR;
end;

PMEMORY_CHUNKS=^TMEMORY_CHUNKS;
TMEMORY_CHUNKS=  packed record
    Address:ULONG;
    Data:PVOID;
    Length:ULONG;
end;

TSSDT_LIST_ENTRY=packed record
fname:sTRING;
address1:ULONG; //原始地址
address2:ULONG; //目前内存地址
end;

TSSDT_LIST_ARRAY=array of TSSDT_LIST_ENTRY;

type
PArray=^TArray;
TArray=array[0..4196] of DWORD;

function  ZwQuerySystemInformation(SystemInformationClass: ULONG; SystemInformation: PVOID; SystemInformationLength: ULONG; lpReturnLength: PULONG): NTSTATUS; stdcall; external 'ntdll.dll' name 'ZwQuerySystemInformation';
function  ZwSystemDebugControl(ControlCode:integer;InputBuffer:PVOID;InputBufferLength:ulong;OutputBuffer:PVOID;OutputBufferLength:ulong;ReturnLength:PULONG): NTSTATUS; stdcall; external 'ntdll.dll' name 'ZwSystemDebugControl';

function LocateNtdllEntry():BOOL;
function GetHeaders(ibase:PCHAR;var pfh:PImageFileHeader;var poh:PImageOptionalHeader;var psh:PImageSectionHeader):DWORD;
procedure FindExport();
function FindKiServiceTable(hModule:HMODULE ;dwKSDT:DWORD):DWORD;
function DebugPrivilege(PName:PCHAR;bEnable:BOOL):BOOL;
procedure GetSSDT();

var
ssdt_list:TSSDT_LIST_ARRAY;
dwKSDT:DWORD;                // rva of KeServiceDescriptorTable
dwKiServiceTable:DWORD;    // rva of KiServiceTable
dwKernelBase,dwServices:DWORD;

implementation
  uses unit1;

function LocateNtdllEntry():BOOL;
var
ntdll:THandle;
PFunc:TFarProc;
begin
ntdll:=GetModuleHandle('ntdll.dll');
if ntdll=0 then
result:=False;
pFunc:=GetProcAddress(ntdll,'ZwQuerySystemInformation');
if pFunc=nil then
result:=False;
end;

function GetHeaders(ibase:PCHAR;var pfh:PImageFileHeader;var poh:PImageOptionalHeader;var psh:PImageSectionHeader):DWORD;
var
mzhead: PImageDosHeader;
nthead: PImageNtHeaders;
begin
mzhead:=PImageDosHeader(ibase);
if (mzhead^.e_magic<>IMAGE_DOS_SIGNATURE)  then
begin
result:=0;
exit;
end;

nthead:=PImageNtHeaders(ibase+DWORD(mzhead^._lfanew));
if  nthead^.Signature<> IMAGE_NT_SIGNATURE  then
begin
result:=0;
exit;
end;

pfh:=PImageFileHeader(ibase + DWORD(mzhead^._lfanew) + Sizeof(DWORD));

poh:=PImageOptionalHeader(ibase + DWORD(mzhead^._lfanew) + Sizeof(DWORD)+ sizeof(IMAGE_FILE_HEADER) );
if poh^.Magic<> $10b then
begin
result:=0;
exit;
end;

psh:=PImageSectionHeader( ibase + DWORD(mzhead^._lfanew) + Sizeof(DWORD) + sizeof(IMAGE_FILE_HEADER) + Sizeof(IMAGE_OPTIONAL_HEADER) ) ;
result:=1;
end;

//搜索函数名称
procedure FindExport();
var
pfh:PImageFileHeader;
poh:PImageOptionalHeader;
psh:PImageSectionHeader;
ped:PImageExportDirectory;
arrayOfFunctionNames:PArray;
arrayOfFunctionAddresses:PArray;
arrayOfFunctionOrdinals: PWordArray;
functionOrdinal,functionAddress:DWORD;
hNtdll:THandle;
i:integer;
funcName: PChar;
number:Word;
begin
hNtdll:=GetModuleHandle('ntdll.dll');
GetHeaders(PCHAR(hNtdll),pfh,poh,psh);

if(poh^.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress<>0) then
begin
  ped:= PImageExportDirectory( poh^.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress + pchar(hNtdll) );
  arrayOfFunctionNames:= PArray( hNtdll+ DWORD(ped^.AddressOfNames));
  arrayOfFunctionAddresses:= PArray(hNtdll+ DWORD(ped^.AddressOfFunctions));
  arrayOfFunctionOrdinals:=   PWordArray(hNtdll+ WORD(ped^.AddressOfNameOrdinals));

end;

SetLength(ssdt_list,ped^.NumberOfNames);
for i:= 0 to ped^.NumberOfNames -1 do
begin
  funcName:=PCHAR(hNtdll+ arrayOfFunctionNames[i]);
  functionOrdinal :=  arrayOfFunctionOrdinals[i] + ped^.Base - 1;
  functionAddress:= DWORD( hNtdll + arrayOfFunctionAddresses[functionOrdinal]);

  if (Copy(funcName,1,2)='Nt') then
  begin
    number:=(PWORD(functionAddress+1))^;
    if (number>ped^.NumberOfNames) then continue;
     ssdt_list[number].fname:=StrPas(funcName);
    //messagebox(0,pchar(inttostr(number)+'  '+StrPas(funcName)),'sad',0);
  end;
end;

end;

// 根据 KeServiceDescriptorTable 的RVA查找 KiServiceTable
function FindKiServiceTable(hModule:HMODULE ;dwKSDT:DWORD):DWORD;
var
pfh:PImageFileHeader;
poh:PImageOptionalHeader;
psh:PImageSectionHeader;
pbr:PImageBaseRelocation;
pfe:PWORD;
i,dwPointerRva,dwPointsToRva,dwKiServiceTable:DWORD;
bFirstChunk:BOOL;
begin
  GetHeaders(PCHAR(hModule),pfh,poh,psh);
if (poh^.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC].VirtualAddress<>0) then
begin
    pbr:=PImageBaseRelocation(POINTER(DWORD(hModule)+DWORD(poh^.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC].VirtualAddress)));
    bFirstChunk:=TRUE;
    while(bFirstChunk or (pbr^.VirtualAddress<>0)) do
    begin
      bFirstChunk:=FALSE;
      pfe:=PWORD(DWORD(pbr)+sizeof(TImageBaseRelocation)) ;
      for i:=0 to ((pbr^.SizeOfBlock-sizeof(TImageBaseRelocation)) shr 1)-1 do
      begin
        if(( (pfe^ and $F000) shr 12 ) = 3 ) then
        begin
         dwPointerRva:=pbr^.VirtualAddress + (pfe^ and $0FFF);
         dwPointsToRva:=(PDWORD(DWORD(hModule)+dwPointerRva))^ - DWORD(poh^.ImageBase);
         if (dwPointsToRva=dwKSDT)  then
         begin
          //这里要具体分析一下
          if((PWORD(DWORD(hModule)+dwPointerRva-2))^=$05c7)  then
          begin
          dwKiServiceTable:=(PDWORD(DWORD(hModule) + dwPointerRva +4))^ - poh^.ImageBase;
          Result:= dwKiServiceTable;
          EXIT;
          end;
         end;
        end;
       pfe:=PWORD(DWORD(pfe)+sizeof(WORD));
      end;
      (PDWORD(@pbr))^ := (PDWORD(@pbr))^ + pbr^.SizeOfBlock;
    end;
end;
  result:=0;
end;

procedure GetSSDT();
var
hKernel: HMODULE    ;
pKernelName: PCHAR ;
pService:PDWORD ;
pfh:PImageFileHeader;
poh:PImageOptionalHeader;
psh:PImageSectionHeader;
n:ULONG;
P:PULONG;
module,s:PModuleInformation;
nowaddress:PDWORD;
QueryBuff: TMEMORY_CHUNKS;
ReturnLength:DWORD;
i,j:integer;
begin
  ZwQuerySystemInformation(11,0,0,@n); //查询长度
  GetMem(p,sizeof(ULONG)*n); //分配空间
  ZwQuerySystemInformation(11,p,n*sizeof(ULONG),nil);   //通过长度查询内容
  module:= PModuleInformation(PULONG(Ulong(p)+sizeof(ULONG)));
  dwKernelBase:=DWORD(module^.Base);
  pKernelName:=pchar(module^.ImageName+module^.ModuleNameOffset);
  hKernel:=LoadLibraryEx(pKernelName,0,DONT_RESOLVE_DLL_REFERENCES);
   // map ntoskrnl - hopefully it has relocs
  if  hKernel=0 then
  begin
  exit;
  end;
  dwKSDT:=DWORD(GetProcAddress(hKernel,'KeServiceDescriptorTable'));
  if  dwKSDT=0 then
  begin
  exit;
  end;

  //得到KeServiceDescriptorTable的相对偏移
  dwKSDT:=dwKSDT-DWORD(hKernel);
  dwKiServiceTable:=FindKiServiceTable(hKernel,dwKSDT);

  GetHeaders(PCHAR(hKernel),pfh,poh,psh);
  dwServices:=0;
  pService:=PDWORD((DWORD(hKernel)+dwKiServiceTable));
  while ( (pService^- poh^.ImageBase)<poh^.SizeOfImage ) do
  begin
  ssdt_list[dwServices].address1:=pService^ - poh^.ImageBase + dwKernelBase;//dwKernelBase查询的模块地址
  pService:=PDWORD(DWORD(pService)+sizeof(DWORD));
  inc(dwServices);
  end;
  FreeLibrary(hKernel);

   GetMem(nowaddress,sizeof(DWORD)* dwServices);

   QueryBuff.Address:=  dwKernelBase+dwKiServiceTable;
   QueryBuff.Data:= nowaddress;
   QueryBuff.Length:=sizeof(DWORD)* dwServices;

  ZwSystemDebugControl(SysDbgReadVirtualMemory,
                       @QueryBuff,
                       sizeof(QueryBuff),
                       nil,
                       0,
                       @ReturnLength);

   // messagebox(0,pchar(inttohex(Ulong(QueryBuff),4)),'lk',0);
//把结果输出来
form1.ListView1.Clear;
i:=0;
while(i<dwServices) do
begin
  form1.ListView1.Items.Add;
  form1.ListView1.Items.Item[i].Caption:='0x'+inttohex(i,2);
  form1.ListView1.Items.Item[i].SubItems.add( ssdt_list[i].fname);
  form1.ListView1.Items.Item[i].SubItems.add('0x'+inttohex(ssdt_list[i].address1,4));
  ssdt_list[i].address2:= nowaddress^;
  form1.ListView1.Items.Item[i].SubItems.add('0x'+inttohex(ssdt_list[i].address2,4));
  nowaddress:=PDWORD(DWORD(nowaddress)+sizeof(DWORD));
  s:=module;
   //搜索模块
   for j:=0 to p^-1 do
   begin
    if(ssdt_list[i].address2>DWORD(s^.Base)) and (ssdt_list[i].address2<DWORD(s^.Base+ s^.Size) )  then
     begin
       form1.Listview1.Items.Item[i].SubItems.add(s^.ImageName);
       break;
    end;
    s:=PModuleInformation(DWORD(module)+sizeof(TModuleInformation)*J);
  end;

  inc(i);
end;

    FreeMem(p);
end;

//使用 ZwSystemDebugControl前必须提权
function DebugPrivilege(PName:PCHAR;bEnable:BOOL):BOOL;
var
Ok:BOOL;
hToken:THANDLE;
tp,tkpo:        TTokenPrivileges;
lBufferNeeded:DWORD;
begin
if (OpenProcessToken(GetCurrentProcess,TOKEN_QUERY or TOKEN_ADJUST_PRIVILEGES,hToken)) then
begin
  tp.PrivilegeCount:=1;
  if  bEnable then
  tp.Privileges[0].Attributes:=SE_PRIVILEGE_ENABLED;
  LookupPrivilegeValue(nil,PName,tp.Privileges[0].Luid);
  AdjustTokenPrivileges(hToken, False, tp, Sizeof(TOKEN_PRIVILEGES), TKPO, lBufferNeeded);
  if  GetLastError()=ERROR_SUCCESS then
  begin
      ok:=false;
      Exit;
  end ;
  CloseHandle(hToken);
  result:=ok;
end;
end;

end.


[培训]内核驱动高级班,冲击BAT一流互联网大厂工作,每周日13:00-18:00直播授课

上传的附件:
收藏
免费 7
支持
分享
最新回复 (6)
雪    币: 4902
活跃值: (130)
能力值: ( LV2,RANK:10 )
在线值:
发帖
回帖
粉丝
2
收藏了
学D的时候看例程
2010-4-19 11:14
0
雪    币: 1312
活跃值: (5164)
能力值: ( LV3,RANK:20 )
在线值:
发帖
回帖
粉丝
3
收藏了!!!!!!!!!!!!!!
2010-4-19 18:36
0
雪    币: 1312
活跃值: (5164)
能力值: ( LV3,RANK:20 )
在线值:
发帖
回帖
粉丝
4
出错了, 不能通过, 放个源代码的工程出来吧.......
2010-4-19 18:54
0
雪    币: 206
活跃值: (10)
能力值: ( LV2,RANK:10 )
在线值:
发帖
回帖
粉丝
5
强烈建议打包~~
2010-4-20 23:17
0
雪    币: 198
活跃值: (1585)
能力值: ( LV2,RANK:10 )
在线值:
发帖
回帖
粉丝
6
期待楼主放完整工程代码。谢谢。
2010-4-21 19:46
0
雪    币: 197
活跃值: (13)
能力值: ( LV2,RANK:10 )
在线值:
发帖
回帖
粉丝
7
自己慢慢研究一下
2010-5-5 16:49
0
游客
登录 | 注册 方可回帖
返回
//