/*
功能:显示每个CPU的GDT信息。
注释:以下结构摘自WRK。
made by correy.
made at 2015.01.11.
*/
#include <ntifs.h>
#include <windef.h>
#if defined(_AMD64_) || defined(_IA64_) //defined(_WIN64)
// Special Registers for AMD64.
typedef struct _AMD64_DESCRIPTOR {
USHORT Pad[3];
USHORT Limit;
ULONG64 Base;
} AMD64_DESCRIPTOR, *PAMD64_DESCRIPTOR;
typedef union _KGDTENTRY64 {
struct {
USHORT LimitLow;
USHORT BaseLow;
union {
struct {
UCHAR BaseMiddle;
UCHAR Flags1;
UCHAR Flags2;
UCHAR BaseHigh;
} Bytes;
struct {
ULONG BaseMiddle : 8;
ULONG Type : 5;//把S位包含进去了,也就是是否为系统段描述符的位。
ULONG Dpl : 2;
ULONG Present : 1;
ULONG LimitHigh : 4;
ULONG System : 1;//即AVL,系统软件自定义的。
ULONG LongMode : 1;
ULONG DefaultBig : 1;//即INTEL的D/B (default operation size/default stack pointer size and/or upper bound) flag。
ULONG Granularity : 1;
ULONG BaseHigh : 8;
} Bits;
};
//ULONG BaseUpper;/*经观察,64下的结构的长度是6字节,不是上面定义的16字节。*/
//ULONG MustBeZero;
};
//ULONG64 Alignment;
} KGDTENTRY64, *PKGDTENTRY64;
#else
// Special Registers for i386
typedef struct _X86_DESCRIPTOR {
USHORT Pad;
USHORT Limit;
ULONG Base;
} X86_DESCRIPTOR, *PX86_DESCRIPTOR;
typedef struct _X86_KSPECIAL_REGISTERS {
ULONG Cr0;
ULONG Cr2;
ULONG Cr3;
ULONG Cr4;
ULONG KernelDr0;
ULONG KernelDr1;
ULONG KernelDr2;
ULONG KernelDr3;
ULONG KernelDr6;
ULONG KernelDr7;
X86_DESCRIPTOR Gdtr;
X86_DESCRIPTOR Idtr;//由此可知,GDT和IDT的结构是一样的。
USHORT Tr;
USHORT Ldtr;
ULONG Reserved[6];
} X86_KSPECIAL_REGISTERS, *PX86_KSPECIAL_REGISTERS;
// GDT Entry
typedef struct _KGDTENTRY {
USHORT LimitLow;
USHORT BaseLow;
union {
struct {
UCHAR BaseMid;
UCHAR Flags1; // Declare as bytes to avoid alignment
UCHAR Flags2; // Problems.
UCHAR BaseHi;
} Bytes;
struct {
ULONG BaseMid : 8;
ULONG Type : 5;//把S位包含进去了,也就是是否为系统段描述符的位。
ULONG Dpl : 2;
ULONG Pres : 1;
ULONG LimitHi : 4;
ULONG Sys : 1;//即AVL,系统软件自定义的。
ULONG Reserved_0 : 1;//LongMode
ULONG Default_Big : 1;//即INTEL的D/B (default operation size/default stack pointer size and/or upper bound) flag。
ULONG Granularity : 1;
ULONG BaseHi : 8;
} Bits;
} HighWord;
} KGDTENTRY, *PKGDTENTRY;
#endif
/*
根据:Table 3-1. Code- and Data-Segment Types,仿照WINDBG的dg命令定义。
*/
char SegmentTypes[][256] = {
"<Reserved>",//Data Read-Only缩写是:Data RO,也可认为是: <Reserved>。如果结构(UINT64)全部为零,也可认为是Reserved。
"Data RO AC",//Data Read-Only, accessed
"Data RW",//Data Read/Write
"Data RW AC",//Data Read/Write, accessed
"Data RO ED",//Data Read-Only, expand-down
"Data RO ED AC",//Data Read-Only, expand-down, accessed
"Data RW ED",//Data Read/Write, expand-down
"Data RW ED AC",//Data Read/Write, expand-down, accessed
"Code EO",//Code Execute-Only
"Code EO AC",//Code Execute-Only, accessed
"Code RE",//Code Execute/Read 加空格以便显示的对齐。
"Code RE AC",//Code Execute/Read, accessed
"Code EO CO",//Code Execute-Only, conforming
"Code EO CO AC",//Code Execute-Only, conforming, accessed
"Code RE CO",//Code Execute/Read, conforming
"Code RE CO AC",//Code Execute/Read, conforming, accessed
"TSS32 Busy ",//这个也可显示只要识别了TSS及内容。
"TSS32 Avl" //这个在X86上出现了。
};
DRIVER_UNLOAD DriverUnload;
VOID DriverUnload(__in PDRIVER_OBJECT DriverObject)
{
}
#ifdef _X86_
__forceinline PKPCR KeGetPcr (VOID)
{
return (PKPCR)__readfsdword(FIELD_OFFSET(KPCR, SelfPcr));
}
#endif
USHORT NTAPI GetGdtLimit ();//汇编函数。
#if defined(_WIN64)
void show_gdt(int i)
/*
i的取值可以是0.
*/
{
//SIZE_T IDTR;
//X86_DESCRIPTOR gdtr = {0};//A pointer to the memory location where the IDTR is stored.
//KGDTENTRY * GDT = 0;
USHORT GdtLimit = 0;
SIZE_T r = 0;
PVOID p = 0;
int index = 0;
int maximun = 0;
PKGDTENTRY64 pkgdte;
SIZE_T ISR = 0;
KeSetSystemAffinityThread(i + 1);
pkgdte = KeGetPcr()->GdtBase;//没有__sgdt,也不用sgdt汇编指令的办法。但是这个获取的没有长度。
GdtLimit = GetGdtLimit ();//一般等于0x7f.
KeRevertToUserAffinityThread();
//p = &gdtr.Limit;
//r = * (SIZE_T *)p;
//pkgdte = (PKGDTENTRY)r;
/*
其实直接:
maximun = (idtr.Base + 1) / sizeof(KIDTENTRY);
也可以。
maximun一般等于256.
*/
//if (gdtr.Pad % sizeof(KIDTENTRY) == 0) {
// maximun = gdtr.Pad / sizeof(KIDTENTRY);
//} else {
// maximun = gdtr.Pad / sizeof(KIDTENTRY);
// maximun++;
//}
//if (GdtLimit % sizeof(KGDTENTRY64) == 0) {
// maximun = GdtLimit / sizeof(KGDTENTRY64);
//} else {
// maximun = GdtLimit / sizeof(KGDTENTRY64);
// maximun++;//一般是128.
//}
maximun = (GdtLimit + 1) / sizeof(KGDTENTRY64);
/*
显示格式:
CPU SN Sel Base Limit Type Pl Size Gran Pres Long Flags
--- -- ---- ----------------- ----------------- ---------- -- ---- ---- ---- ---- --------
注释:CPU和SN是自己添加的。SN即Segment Name,如:CS,DS,FS等.
*/
KdPrint(("Sel Base Limit Type DPl Size Gran Pres Long Flags\n"));//CPU SN
KdPrint(("---- ---------------- ---------------- ------------- --- ---- ---- ---- ---- --------\n"));//--- --
KdPrint(("\n"));
for ( ;index < maximun ;index++ )
{
PKGDTENTRY64 pkgdte_t = &pkgdte[index];
SIZE_T Base = 0;
SIZE_T Limit = 0;
ULONG Type = 0;
char * size = NULL;
char * Granularity = NULL;
char * Present = NULL;
char * LongMode = NULL;
int Flags = 0;
Base = pkgdte_t->Bits.BaseHigh;
Base = (Base << 24);
Base += (pkgdte_t->BaseLow + (pkgdte_t->Bits.BaseMiddle << 16));
Limit = pkgdte_t->LimitLow + (pkgdte_t->Bits.LimitHigh << 16);
if (pkgdte_t->Bits.DefaultBig && Base)
{
//扩充高位为1.即F.
Base += 0xffffffff00000000;
}
if (pkgdte_t->Bits.DefaultBig && pkgdte_t->Bits.Granularity)
{
//扩充高位为1.即F.
SIZE_T t = Limit;
Limit = (Limit << 12);
Limit += PAGE_SIZE - 1;
}
Type = pkgdte_t->Bits.Type;
_bittestandreset(&Type, 4);//因为这个包含了S位,所以要清除这个位标志。
if (pkgdte_t->Bits.DefaultBig)
{
size = "Bg ";//Big 加空格是为了对齐显示。
}
else
{
size = "Nb ";//Not Big 加空格是为了对齐显示。
}
if (pkgdte_t->Bits.Granularity)
{
Granularity = "Pg ";//Page 加空格是为了对齐显示。
}
else
{
Granularity = "By ";//Byte 加空格是为了对齐显示。
}
if (pkgdte_t->Bits.Present)
{
Present = "P ";//Present 加空格是为了对齐显示。
}
else
{
Present = "NP ";//NO Present 加空格是为了对齐显示。
}
if (pkgdte_t->Bits.LongMode)
{
LongMode = "Lo ";//Long 加空格是为了对齐显示。
}
else
{
LongMode = "Nl ";//NO long 加空格是为了对齐显示。
}
Flags = (pkgdte_t->Bytes.Flags2 >> 4);//去掉Segment limit的那几位。
Flags = Flags << 8;
Flags = Flags + pkgdte_t->Bytes.Flags1;
KdPrint(("%04x %p %p %13s %03x %s %s %s %s 0x%04x\n",
index * 8, //sizeof (KGDTENTRY)
Base,
Limit,
SegmentTypes[Type],
pkgdte_t->Bits.Dpl,
size,
Granularity,
Present,
LongMode,
Flags
));
//if (pkgdte_t->Bits.Present)
//{
// KdPrint(("第%d号CPU的GDT的Sel:0x%03x, Base:0x%016p, Limit:0x%016p, type:0x%02x, Dpl:0x%x, Pres:0x%x, Sys:0x%x, LongMode:0x%x, Default_Big:0x%x, Granularity:0x%x.\n",
// i, index * sizeof (KGDTENTRY64), Base, Limit,
// pkgdte_t->Bits.Type,
// pkgdte_t->Bits.Dpl,
// pkgdte_t->Bits.Present,//再打印一次吧!
// pkgdte_t->Bits.System,
// pkgdte_t->Bits.LongMode,
// pkgdte_t->Bits.DefaultBig,
// pkgdte_t->Bits.Granularity
// ));
//}
//else //<Reserved>
//{
// KdPrint(("第%d号CPU的GDT的Sel:0x%03x is Reserved!\n", i, index * sizeof (KGDTENTRY64)));
//}
////偶尔出现有一个不对,即0x38的值不对,
//Base = pkgdte_t->BaseLow + (pkgdte_t->HighWord.Bits.BaseHi << 24) + (pkgdte_t->HighWord.Bits.BaseMid << 16);//其实用位与更快 | 。
//if (pkgdte_t->HighWord.Bits.Granularity && BooleanFlagOn(pkgdte_t->HighWord.Bits.Type, 2 ) ) {//关于标志位及算法,见权威资料。
// Limit = pkgdte_t->LimitLow + (pkgdte_t->HighWord.Bits.LimitHi << 16);
// Limit *= PAGE_SIZE;
// Limit += PAGE_SIZE - 1;
//} else {
// Limit = pkgdte_t->LimitLow + (pkgdte_t->HighWord.Bits.LimitHi << 16);
//}
//KdPrint(("第%d号CPU的GDT的Sel:0x%03x, Base:0x%08x, Limit:0x%08x, type:0x%02x, Dpl:0x%x, Pres:0x%x, Sys:0x%x,Default_Big:0x%x, Granularity:0x%x.\n",
// i, index * sizeof (KGDTENTRY), Base, Limit,
// pkgdte_t->HighWord.Bits.Type,
// pkgdte_t->HighWord.Bits.Dpl,
// pkgdte_t->HighWord.Bits.Pres,
// pkgdte_t->HighWord.Bits.Sys,
// pkgdte_t->HighWord.Bits.Default_Big,
// pkgdte_t->HighWord.Bits.Granularity
// ));
/*
这里的Default_Big对应dg命令的size.
这里的Sys对应dg命令的long.
Flags的值等于变相打印了,这里就不再打印了。
*/
}
}
#else
void show_gdt(int i)
/*
i的取值可以是0.
*/
{
//SIZE_T IDTR;
//X86_DESCRIPTOR gdtr = {0};//A pointer to the memory location where the IDTR is stored.
//KGDTENTRY * GDT = 0;
USHORT GdtLimit = 0;
SIZE_T r = 0;
PVOID p = 0;
int index = 0;
int maximun = 0;
PKGDTENTRY pkgdte;
SIZE_T ISR = 0;
KeSetSystemAffinityThread(i + 1);
pkgdte = KeGetPcr()->GDT;//没有__sgdt,也不用sgdt汇编指令的办法。但是这个获取的没有长度。
GdtLimit = GetGdtLimit ();//一般等于0x3ff.
KeRevertToUserAffinityThread();
//p = &gdtr.Limit;
//r = * (SIZE_T *)p;
//pkgdte = (PKGDTENTRY)r;
/*
其实直接:
maximun = (idtr.Base + 1) / sizeof(KIDTENTRY);
也可以。
maximun一般等于256.
*/
//if (gdtr.Pad % sizeof(KIDTENTRY) == 0) {
// maximun = gdtr.Pad / sizeof(KIDTENTRY);
//} else {
// maximun = gdtr.Pad / sizeof(KIDTENTRY);
// maximun++;
//}
if (GdtLimit % sizeof(KGDTENTRY) == 0) {
maximun = GdtLimit / sizeof(KGDTENTRY);
} else {
maximun = GdtLimit / sizeof(KGDTENTRY);
maximun++;//一般是128.
}
/*
显示格式:
CPU SN Sel Base Limit Type Pl Size Gran Pres Long Flags
--- -- ---- ----------------- ----------------- ---------- -- ---- ---- ---- ---- --------
注释:CPU和SN是自己添加的。SN即Segment Name,如:CS,DS,FS等.
*/
KdPrint(("Sel Base Limit Type DPl Size Gran Pres Long Flags\n"));//CPU SN
KdPrint(("---- -------- ------------- ------------- --- ---- ---- ---- ---- --------\n"));//--- --
KdPrint(("\n"));
for ( ;index < maximun ;index++ )
{
PKGDTENTRY pkgdte_t = &pkgdte[index];
SIZE_T Base = 0;
SIZE_T Limit = 0;
ULONG Type = 0;
char * size = NULL;
char * Granularity = NULL;
char * Present = NULL;
char * LongMode = NULL;
int Flags = 0;
//注意:0x38处的值不停的变化。
USHORT BaseLow = pkgdte_t->BaseLow;
ULONG BaseMid = pkgdte_t->HighWord.Bits.BaseMid;
ULONG BaseHi = pkgdte_t->HighWord.Bits.BaseHi;
Base = (BaseHi << 24) + (BaseMid << 16) + BaseLow;//其实用位与更快 | 。
if (pkgdte_t->HighWord.Bits.Granularity && BooleanFlagOn(pkgdte_t->HighWord.Bits.Type, 2 ) ) {//关于标志位及算法,见权威资料。
Limit = pkgdte_t->LimitLow + (pkgdte_t->HighWord.Bits.LimitHi << 16);
Limit *= PAGE_SIZE;
Limit += PAGE_SIZE - 1;
} else {
Limit = pkgdte_t->LimitLow + (pkgdte_t->HighWord.Bits.LimitHi << 16);
}
//if (pkgdte_t->HighWord.Bits.Default_Big && Base)
//{
// //扩充高位为1.即F.
// Base += 0xffff0000;
//}
//if (pkgdte_t->Bits.DefaultBig && pkgdte_t->Bits.Granularity)
//{
// //扩充高位为1.即F.
// SIZE_T t = Limit;
// Limit = (Limit << 12);
// Limit += PAGE_SIZE - 1;
//}
Type = pkgdte_t->HighWord.Bits.Type;
_bittestandreset(&Type, 4);//因为这个包含了S位,所以要清除这个位标志。
if (pkgdte_t->HighWord.Bits.Default_Big)
{
size = "Bg ";//Big 加空格是为了对齐显示。
}
else
{
size = "Nb ";//Not Big 加空格是为了对齐显示。
}
if (pkgdte_t->HighWord.Bits.Granularity)
{
Granularity = "Pg ";//Page 加空格是为了对齐显示。
}
else
{
Granularity = "By ";//Byte 加空格是为了对齐显示。
}
if (pkgdte_t->HighWord.Bits.Pres)
{
Present = "P ";//Present 加空格是为了对齐显示。
}
else
{
Present = "NP ";//NO Present 加空格是为了对齐显示。
}
if (pkgdte_t->HighWord.Bits.Reserved_0)
{
LongMode = "Lo ";//Long 加空格是为了对齐显示。
}
else
{
LongMode = "Nl ";//NO long 加空格是为了对齐显示。
}
Flags = (pkgdte_t->HighWord.Bytes.Flags2 >> 4);//去掉Segment limit的那几位。
Flags = Flags << 8;
Flags = Flags + pkgdte_t->HighWord.Bytes.Flags1;
KdPrint(("%04x %p %p %13s %03x %s %s %s %s 0x%04x\n",
index * 8, //sizeof (KGDTENTRY)
Base,
Limit,
SegmentTypes[Type],
pkgdte_t->HighWord.Bits.Dpl,
size,
Granularity,
Present,
LongMode,
Flags
));
//KdPrint(("第%d号CPU的GDT的Sel:0x%03x, Base:0x%08x, Limit:0x%08x, type:0x%02x, Dpl:0x%x, Pres:0x%x, Sys:0x%x,Default_Big:0x%x, Granularity:0x%x.\n",
// i, index * sizeof (KGDTENTRY), Base, Limit,
// pkgdte_t->HighWord.Bits.Type,
// pkgdte_t->HighWord.Bits.Dpl,
// pkgdte_t->HighWord.Bits.Pres,
// pkgdte_t->HighWord.Bits.Sys,
// pkgdte_t->HighWord.Bits.Default_Big,
// pkgdte_t->HighWord.Bits.Granularity
// ));
/*
这里的Default_Big对应dg命令的size.
这里的Sys对应dg命令的long.
Flags的值等于变相打印了,这里就不再打印了。
*/
}
}
#endif
#pragma INITCODE
DRIVER_INITIALIZE DriverEntry;
NTSTATUS DriverEntry(__in struct _DRIVER_OBJECT * DriverObject, __in PUNICODE_STRING RegistryPath)
{
int i = 0;
KdBreakPoint();
DriverObject->DriverUnload = DriverUnload;
for ( ;i < KeNumberProcessors ;i++ )//KeQueryMaximumProcessorCount() KeGetCurrentProcessorNumber
{
show_gdt(i);
}
return STATUS_SUCCESS;
}
/*
0: kd> dg 0 256
P Si Gr Pr Lo
Sel Base Limit Type l ze an es ng Flags
---- -------- -------- ---------- - -- -- -- -- --------
0000 00000000 00000000 <Reserved> 0 Nb By Np Nl 00000000
0008 00000000 ffffffff Code RE Ac 0 Bg Pg P Nl 00000c9b
0010 00000000 ffffffff Data RW Ac 0 Bg Pg P Nl 00000c93
0018 00000000 ffffffff Code RE Ac 3 Bg Pg P Nl 00000cfb
0020 00000000 ffffffff Data RW Ac 3 Bg Pg P Nl 00000cf3
0028 80042000 000020ab TSS32 Busy 0 Nb By P Nl 0000008b
0030 ffdff000 00001fff Data RW Ac 0 Bg Pg P Nl 00000c93
0038 00000000 00000fff Data RW Ac 3 Bg By P Nl 000004f3
0040 00000400 0000ffff Data RW 3 Nb By P Nl 000000f2
0048 00000000 00000000 <Reserved> 0 Nb By Np Nl 00000000
0050 80552700 00000068 TSS32 Avl 0 Nb By P Nl 00000089
0058 80552768 00000068 TSS32 Avl 0 Nb By P Nl 00000089
0060 00022f40 0000ffff Data RW Ac 0 Nb By P Nl 00000093
0068 000b8000 00003fff Data RW 0 Nb By P Nl 00000092
0070 ffff7000 000003ff Data RW 0 Nb By P Nl 00000092
0078 80400000 0000ffff Code RE 0 Nb By P Nl 0000009a
0080 80400000 0000ffff Data RW 0 Nb By P Nl 00000092
0088 00000000 00000000 Data RW 0 Nb By P Nl 00000092
0090 00000000 00000000 <Reserved> 0 Nb By Np Nl 00000000
0098 00000000 00000000 <Reserved> 0 Nb By Np Nl 00000000
00A0 82181238 00000068 TSS32 Avl 0 Nb By P Nl 00000089
00A8 00000000 00000000 <Reserved> 0 Nb By Np Nl 00000000
00B0 00000000 00000000 <Reserved> 0 Nb By Np Nl 00000000
00B8 00000000 00000000 <Reserved> 0 Nb By Np Nl 00000000
00C0 00000000 00000000 <Reserved> 0 Nb By Np Nl 00000000
00C8 00000000 00000000 <Reserved> 0 Nb By Np Nl 00000000
00D0 00000000 00000000 <Reserved> 0 Nb By Np Nl 00000000
00D8 00000000 00000000 <Reserved> 0 Nb By Np Nl 00000000
00E0 f851f000 0000ffff Code RE Ac 0 Nb By P Nl 0000009f
00E8 00000000 0000ffff Data RW 0 Nb By P Nl 00000092
00F0 804fd040 000003b7 Code EO 0 Nb By P Nl 00000098
00F8 00000000 0000ffff Data RW 0 Nb By P Nl 00000092
0100 ba4bd400 0000ffff Data RW Ac 0 Bg By P Nl 00000493
0108 ba4bd400 0000ffff Data RW Ac 0 Bg By P Nl 00000493
0110 ba4bd400 0000ffff Data RW Ac 0 Bg By P Nl 00000493
0118 00008003 0000f120 <Reserved> 0 Nb By Np Nl 00000000
0120 00008003 0000f128 <Reserved> 0 Nb By Np Nl 00000000
0128 00008003 0000f130 <Reserved> 0 Nb By Np Nl 00000000
0130 00008003 0000f138 <Reserved> 0 Nb By Np Nl 00000000
0138 00008003 0000f140 <Reserved> 0 Nb By Np Nl 00000000
0140 00008003 0000f148 <Reserved> 0 Nb By Np Nl 00000000
0148 00008003 0000f150 <Reserved> 0 Nb By Np Nl 00000000
0150 00008003 0000f158 <Reserved> 0 Nb By Np Nl 00000000
0158 00008003 0000f160 <Reserved> 0 Nb By Np Nl 00000000
0160 00008003 0000f168 <Reserved> 0 Nb By Np Nl 00000000
0168 00008003 0000f170 <Reserved> 0 Nb By Np Nl 00000000
0170 00008003 0000f178 <Reserved> 0 Nb By Np Nl 00000000
0178 00008003 0000f180 <Reserved> 0 Nb By Np Nl 00000000
0180 00008003 0000f188 <Reserved> 0 Nb By Np Nl 00000000
0188 00008003 0000f190 <Reserved> 0 Nb By Np Nl 00000000
0190 00008003 0000f198 <Reserved> 0 Nb By Np Nl 00000000
0198 00008003 0000f1a0 <Reserved> 0 Nb By Np Nl 00000000
01A0 00008003 0000f1a8 <Reserved> 0 Nb By Np Nl 00000000
01A8 00008003 0000f1b0 <Reserved> 0 Nb By Np Nl 00000000
01B0 00008003 0000f1b8 <Reserved> 0 Nb By Np Nl 00000000
01B8 00008003 0000f1c0 <Reserved> 0 Nb By Np Nl 00000000
01C0 00008003 0000f1c8 <Reserved> 0 Nb By Np Nl 00000000
01C8 00008003 0000f1d0 <Reserved> 0 Nb By Np Nl 00000000
01D0 00008003 0000f1d8 <Reserved> 0 Nb By Np Nl 00000000
01D8 00008003 0000f1e0 <Reserved> 0 Nb By Np Nl 00000000
01E0 00008003 0000f1e8 <Reserved> 0 Nb By Np Nl 00000000
01E8 00008003 0000f1f0 <Reserved> 0 Nb By Np Nl 00000000
01F0 00008003 0000f1f8 <Reserved> 0 Nb By Np Nl 00000000
01F8 00008003 0000f200 <Reserved> 0 Nb By Np Nl 00000000
0200 00008003 0000f208 <Reserved> 0 Nb By Np Nl 00000000
0208 00008003 0000f210 <Reserved> 0 Nb By Np Nl 00000000
0210 00008003 0000f218 <Reserved> 0 Nb By Np Nl 00000000
0218 00008003 0000f220 <Reserved> 0 Nb By Np Nl 00000000
0220 00008003 0000f228 <Reserved> 0 Nb By Np Nl 00000000
0228 00008003 0000f230 <Reserved> 0 Nb By Np Nl 00000000
0230 00008003 0000f238 <Reserved> 0 Nb By Np Nl 00000000
0238 00008003 0000f240 <Reserved> 0 Nb By Np Nl 00000000
0240 00008003 0000f248 <Reserved> 0 Nb By Np Nl 00000000
0248 00008003 0000f250 <Reserved> 0 Nb By Np Nl 00000000
0250 00008003 0000f258 <Reserved> 0 Nb By Np Nl 00000000
0: kd> dg 0 256
P Si Gr Pr Lo
Sel Base Limit Type l ze an es ng Flags
---- ----------------- ----------------- ---------- - -- -- -- -- --------
0000 00000000`00000000 00000000`00000000 <Reserved> 0 Nb By Np Nl 00000000
0008 00000000`00000000 00000000`00000000 <Reserved> 0 Nb By Np Nl 00000000
0010 00000000`00000000 00000000`00000000 Code RE Ac 0 Nb By P Lo 0000029b
0018 00000000`00000000 00000000`ffffffff Data RW Ac 0 Bg Pg P Nl 00000c93
0020 00000000`00000000 00000000`ffffffff Code RE 3 Bg Pg P Nl 00000cfa
0028 00000000`00000000 00000000`ffffffff Data RW Ac 3 Bg Pg P Nl 00000cf3
0030 00000000`00000000 00000000`00000000 Code RE Ac 3 Nb By P Lo 000002fb
0038 00000000`00000000 00000000`00000000 <Reserved> 0 Nb By Np Nl 00000000
0040 00000000`01794080 00000000`00000067 TSS32 Busy 0 Nb By P Nl 0000008b
0048 00000000`0000ffff 00000000`0000f800 <Reserved> 0 Nb By Np Nl 00000000
0050 ffffffff`fffa0000 00000000`00003c00 Data RW Ac 3 Bg By P Nl 000004f3
0058 00000000`00000000 00000000`00000000 <Reserved> 0 Nb By Np Nl 00000000
0060 00000000`00000000 00000000`ffffffff Code RE 0 Bg Pg P Nl 00000c9a
0068 00000000`00000000 00000000`00000000 <Reserved> 0 Nb By Np Nl 00000000
0070 00000000`00000000 00000000`00000000 <Reserved> 0 Nb By Np Nl 00000000
0078 00000000`00000000 00000000`00000000 <Reserved> 0 Nb By Np Nl 00000000
0080 Unable to get descriptor
kd> r GDTR
gdtr=fffff80004289000
kd> db fffff80004289000
fffff800`04289000 00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00 ................
fffff800`04289010 00 00 00 00 00 9b 20 00-ff ff 00 00 00 93 cf 00 ...... .........
fffff800`04289020 ff ff 00 00 00 fb cf 00-ff ff 00 00 00 f3 cf 00 ................
fffff800`04289030 00 00 00 00 00 fb 20 00-00 00 00 00 00 00 00 00 ...... .........
fffff800`04289040 67 00 70 a0 28 8b 00 04-00 f8 ff ff 00 00 00 00 g.p.(...........
fffff800`04289050 00 3c 00 00 fe f3 40 ff-00 00 00 00 00 00 00 00 .<....@.........
fffff800`04289060 ff ff 00 00 00 9a cf 00-00 00 00 00 00 00 00 00 ................
fffff800`04289070 40 bf 10 00 00 8e a5 01-00 f8 ff ff 00 00 00 00 @...............
kd> r gdtl
gdtl=006f
kd> dg @cs
P Si Gr Pr Lo
Sel Base Limit Type l ze an es ng Flags
---- ----------------- ----------------- ---------- - -- -- -- -- --------
0010 00000000`00000000 00000000`00000000 Code RE Ac 0 Nb By P Lo 0000029b
kd> r cs
cs=0010
*/
----------------------------------------------------------------------------------------
;.\i386\asm.asm 的内容如下:
.686p
.model flat,StdCall
option casemap:none
.CODE
;摘自:nbp-0.32-public
GetGdtLimit PROC
LOCAL gdtr[10]:BYTE
sgdt gdtr
mov ax, WORD PTR gdtr[0]
ret
GetGdtLimit ENDP
END
----------------------------------------------------------------------------------------
:.\amd64\asm.asm的内容如下:
.CODE
;摘自:nbp-0.32-public
GetGdtLimit PROC
LOCAL gdtr[10]:BYTE
sgdt gdtr
mov ax, WORD PTR gdtr[0]
ret
GetGdtLimit ENDP
END
----------------------------------------------------------------------------------------
#source文件的内容如下:
TARGETNAME=test
TARGETTYPE=DRIVER
SOURCES=test.C
AMD64_SOURCES=.\amd64\asm.asm
I386_SOURCES=.\i386\asm.asm
TARGETPATH=obj
----------------------------------------------------------------------------------------
2015年8月8日星期六
2015年7月23日星期四
Base64加解密
#include <windows.h>
#include <stdio.h>
#include <Dbghelp.h>
#pragma comment(lib, "Dbghelp.lib")
#pragma comment(lib, "Imagehlp.lib")
#include <Wincrypt.h>
#pragma comment(lib, "Crypt32.lib")
#pragma warning(disable:4995)
#pragma warning(disable:4996)
/*
目的:主要示例Base64的转换。
实现:解密Base64。
系统的接口:
CryptStringToBinary
CryptBinaryToString
微软的编码:
http://research.microsoft.com/en-us/um/redmond/projects/invisible/src/crypto/cyphers/base64/base64.c.htm
如果真想找到微软的东西,那就在sdk 6.0 Samples里面搜索Base64吧!
其实系统也有自带的命令的,用法如下:
CertUtil -encode InFile OutFile 将文件编码为 Base64
CertUtil -decode InFile OutFile 解码 Base64 编码的文件
made by corey
made at 2015.05.14
*/
void main()
{
//DebugBreak();
//__debugbreak();
//摘自:http://zh.wikipedia.org/wiki/Base64
LPCTSTR pszString = L"Man is distinguished, not only by his reason, "
L"but by this singular passion from other animals, "
L"which is a lust of the mind, that by a perseverance of delight in "
L"the continued and indefatigable generation of knowledge, exceeds the short vehemence of any carnal pleasure.";
DWORD cchString = lstrlen(pszString) * sizeof(wchar_t);
DWORD dwFlags = CRYPT_STRING_BASE64;
BOOL B = 0;
LPTSTR pszString2 = 0;
DWORD pcchString = 0;
B = CryptBinaryToString((BYTE *)pszString, cchString, dwFlags, pszString2, &pcchString);
if (B == false)
{
return;
}
pcchString = pcchString * sizeof(wchar_t);
pszString2 = (LPTSTR) HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, pcchString);
if (pszString2 == NULL)
{
printf ("Failed to allocate on heap.\n");
return;
}
//注意单字符和宽字符的编码是不一样的。
B = CryptBinaryToString((BYTE *)pszString, cchString, dwFlags, pszString2, &pcchString);
if (B == false)
{
HeapFree(GetProcessHeap(), 0, pszString2);
return;
}
HeapFree(GetProcessHeap(), 0, pszString2);
return;
}
--------------------------------------------------------------------------------------------------------------------------------
#include <windows.h>
#include <stdio.h>
#include <Dbghelp.h>
#pragma comment(lib, "Dbghelp.lib")
#pragma comment(lib, "Imagehlp.lib")
#include <Wincrypt.h>
#pragma comment(lib, "Crypt32.lib")
#pragma warning(disable:4995)
#pragma warning(disable:4996)
/*
目的:主要示例Base64的转换。
实现:解密Base64。
CryptStringToBinary
CryptBinaryToString
made by corey
made at 2015.05.14
*/
void main()
{
//DebugBreak();
//__debugbreak();
//这个必须是相应的编码,如:Base64,否则下面的转换失败。
//摘自:http://zh.wikipedia.org/wiki/Base64
//LPCTSTR pszString = L"madebycorrey";
LPCTSTR pszString = L"TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1dCBieSB0aGlz"
L"IHNpbmd1bGFyIHBhc3Npb24gZnJvbSBvdGhlciBhbmltYWxzLCB3aGljaCBpcyBhIGx1c3Qgb2Yg"
L"dGhlIG1pbmQsIHRoYXQgYnkgYSBwZXJzZXZlcmFuY2Ugb2YgZGVsaWdodCBpbiB0aGUgY29udGlu"
L"dWVkIGFuZCBpbmRlZmF0aWdhYmxlIGdlbmVyYXRpb24gb2Yga25vd2xlZGdlLCBleGNlZWRzIHRo"
L"ZSBzaG9ydCB2ZWhlbWVuY2Ugb2YgYW55IGNhcm5hbCBwbGVhc3VyZS4=";
////////////////////////////////////////////////////////////////////////////////////////////////////////
//第一步:把这个编码(Base64)转换为加密的二进制。
DWORD cchString = lstrlen(pszString);
DWORD dwFlags = CRYPT_STRING_BASE64;
BYTE * pbBinary = NULL;
DWORD pcbBinary = 0;
DWORD pdwSkip = 0;
DWORD pdwFlags = 0;
BOOL B = CryptStringToBinary(
pszString,
//The number of characters of the formatted string to be converted, not including the terminating NULL character.
//If this parameter is zero, pszString is considered to be a null-terminated string.
cchString,
dwFlags,
pbBinary,
_Inout_ &pcbBinary,
_Out_ & pdwSkip,
_Out_ & pdwFlags
);
if (B == false)
{
int x = GetLastError();
return;
}
pcbBinary = pcbBinary * sizeof(wchar_t);
pbBinary = (BYTE *) HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, pcbBinary);
if (pbBinary == NULL)
{
printf ("Failed to allocate on heap.\n");
return;
}
B = CryptStringToBinary(pszString, cchString, dwFlags, pbBinary, &pcbBinary, &pdwSkip, &pdwFlags);
if (B == false)
{
HeapFree(GetProcessHeap(), 0, pbBinary);
return;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////
//第二步:把上一步的内容这个转换为原文。
LPTSTR pszString2 = 0;
DWORD pcchString = 0;
B = CryptBinaryToString(pbBinary, pcbBinary, dwFlags,
_Out_opt_ pszString2,
_Inout_ &pcchString
);
if (B == false)
{
HeapFree(GetProcessHeap(), 0, pbBinary);
return;
}
pcchString = pcchString * sizeof(wchar_t);
pszString2 = (LPTSTR) HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, pcchString);
if (pszString2 == NULL)
{
HeapFree(GetProcessHeap(), 0, pbBinary);
printf ("Failed to allocate on heap.\n");
return;
}
B = CryptBinaryToString(pbBinary, pcbBinary, dwFlags,
_Out_opt_ pszString2,
_Inout_ &pcchString
);//这里把空格给去掉了,多个回车换行。如果有-,后面的都截取了。总是多个回车换行。
if (B == false)
{
HeapFree(GetProcessHeap(), 0, pbBinary);
HeapFree(GetProcessHeap(), 0, pszString2);
return;
}
HeapFree(GetProcessHeap(), 0, pbBinary);
HeapFree(GetProcessHeap(), 0, pszString2);
return;
////////////////////////////////////////////////////////////////////////////////////////////////////////
}
#include <stdio.h>
#include <Dbghelp.h>
#pragma comment(lib, "Dbghelp.lib")
#pragma comment(lib, "Imagehlp.lib")
#include <Wincrypt.h>
#pragma comment(lib, "Crypt32.lib")
#pragma warning(disable:4995)
#pragma warning(disable:4996)
/*
目的:主要示例Base64的转换。
实现:解密Base64。
系统的接口:
CryptStringToBinary
CryptBinaryToString
微软的编码:
http://research.microsoft.com/en-us/um/redmond/projects/invisible/src/crypto/cyphers/base64/base64.c.htm
如果真想找到微软的东西,那就在sdk 6.0 Samples里面搜索Base64吧!
其实系统也有自带的命令的,用法如下:
CertUtil -encode InFile OutFile 将文件编码为 Base64
CertUtil -decode InFile OutFile 解码 Base64 编码的文件
made by corey
made at 2015.05.14
*/
void main()
{
//DebugBreak();
//__debugbreak();
//摘自:http://zh.wikipedia.org/wiki/Base64
LPCTSTR pszString = L"Man is distinguished, not only by his reason, "
L"but by this singular passion from other animals, "
L"which is a lust of the mind, that by a perseverance of delight in "
L"the continued and indefatigable generation of knowledge, exceeds the short vehemence of any carnal pleasure.";
DWORD cchString = lstrlen(pszString) * sizeof(wchar_t);
DWORD dwFlags = CRYPT_STRING_BASE64;
BOOL B = 0;
LPTSTR pszString2 = 0;
DWORD pcchString = 0;
B = CryptBinaryToString((BYTE *)pszString, cchString, dwFlags, pszString2, &pcchString);
if (B == false)
{
return;
}
pcchString = pcchString * sizeof(wchar_t);
pszString2 = (LPTSTR) HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, pcchString);
if (pszString2 == NULL)
{
printf ("Failed to allocate on heap.\n");
return;
}
//注意单字符和宽字符的编码是不一样的。
B = CryptBinaryToString((BYTE *)pszString, cchString, dwFlags, pszString2, &pcchString);
if (B == false)
{
HeapFree(GetProcessHeap(), 0, pszString2);
return;
}
HeapFree(GetProcessHeap(), 0, pszString2);
return;
}
--------------------------------------------------------------------------------------------------------------------------------
#include <windows.h>
#include <stdio.h>
#include <Dbghelp.h>
#pragma comment(lib, "Dbghelp.lib")
#pragma comment(lib, "Imagehlp.lib")
#include <Wincrypt.h>
#pragma comment(lib, "Crypt32.lib")
#pragma warning(disable:4995)
#pragma warning(disable:4996)
/*
目的:主要示例Base64的转换。
实现:解密Base64。
CryptStringToBinary
CryptBinaryToString
made by corey
made at 2015.05.14
*/
void main()
{
//DebugBreak();
//__debugbreak();
//这个必须是相应的编码,如:Base64,否则下面的转换失败。
//摘自:http://zh.wikipedia.org/wiki/Base64
//LPCTSTR pszString = L"madebycorrey";
LPCTSTR pszString = L"TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1dCBieSB0aGlz"
L"IHNpbmd1bGFyIHBhc3Npb24gZnJvbSBvdGhlciBhbmltYWxzLCB3aGljaCBpcyBhIGx1c3Qgb2Yg"
L"dGhlIG1pbmQsIHRoYXQgYnkgYSBwZXJzZXZlcmFuY2Ugb2YgZGVsaWdodCBpbiB0aGUgY29udGlu"
L"dWVkIGFuZCBpbmRlZmF0aWdhYmxlIGdlbmVyYXRpb24gb2Yga25vd2xlZGdlLCBleGNlZWRzIHRo"
L"ZSBzaG9ydCB2ZWhlbWVuY2Ugb2YgYW55IGNhcm5hbCBwbGVhc3VyZS4=";
////////////////////////////////////////////////////////////////////////////////////////////////////////
//第一步:把这个编码(Base64)转换为加密的二进制。
DWORD cchString = lstrlen(pszString);
DWORD dwFlags = CRYPT_STRING_BASE64;
BYTE * pbBinary = NULL;
DWORD pcbBinary = 0;
DWORD pdwSkip = 0;
DWORD pdwFlags = 0;
BOOL B = CryptStringToBinary(
pszString,
//The number of characters of the formatted string to be converted, not including the terminating NULL character.
//If this parameter is zero, pszString is considered to be a null-terminated string.
cchString,
dwFlags,
pbBinary,
_Inout_ &pcbBinary,
_Out_ & pdwSkip,
_Out_ & pdwFlags
);
if (B == false)
{
int x = GetLastError();
return;
}
pcbBinary = pcbBinary * sizeof(wchar_t);
pbBinary = (BYTE *) HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, pcbBinary);
if (pbBinary == NULL)
{
printf ("Failed to allocate on heap.\n");
return;
}
B = CryptStringToBinary(pszString, cchString, dwFlags, pbBinary, &pcbBinary, &pdwSkip, &pdwFlags);
if (B == false)
{
HeapFree(GetProcessHeap(), 0, pbBinary);
return;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////
//第二步:把上一步的内容这个转换为原文。
LPTSTR pszString2 = 0;
DWORD pcchString = 0;
B = CryptBinaryToString(pbBinary, pcbBinary, dwFlags,
_Out_opt_ pszString2,
_Inout_ &pcchString
);
if (B == false)
{
HeapFree(GetProcessHeap(), 0, pbBinary);
return;
}
pcchString = pcchString * sizeof(wchar_t);
pszString2 = (LPTSTR) HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, pcchString);
if (pszString2 == NULL)
{
HeapFree(GetProcessHeap(), 0, pbBinary);
printf ("Failed to allocate on heap.\n");
return;
}
B = CryptBinaryToString(pbBinary, pcbBinary, dwFlags,
_Out_opt_ pszString2,
_Inout_ &pcchString
);//这里把空格给去掉了,多个回车换行。如果有-,后面的都截取了。总是多个回车换行。
if (B == false)
{
HeapFree(GetProcessHeap(), 0, pbBinary);
HeapFree(GetProcessHeap(), 0, pszString2);
return;
}
HeapFree(GetProcessHeap(), 0, pbBinary);
HeapFree(GetProcessHeap(), 0, pszString2);
return;
////////////////////////////////////////////////////////////////////////////////////////////////////////
}
2015年6月24日星期三
IDA-PRO调试MBR
环境/工具:IDAPRO+VMWARE(windows XP 32环境)。
步骤:
1.VMware的.vmx文件的配置。
这个就不说了,假定你已经会了。
例如:
debugStub.listen.guest32 = "TRUE"
debugStub.hideBreakpoints= "TRUE"
还如:
debugStub.listen.guest32.remote = "TRUE"
debugStub.listen.guest64.remote = "TRUE"
monitor.debugOnStartGuest32 = "TRUE"
debugStub.hideBreakpoints = "TRUE"
bios.bootDelay = "3000"
具体的可参观官网的:Debugging Windows kernel under VMWare using IDA's GDB debugger.PDF
其中就有如下经典的两行:
debugStub.listen.guest32 = "TRUE"
debugStub.hideBreakpoints= "TRUE"
2.开启IDA->debugger->attach->remote GDB debugger.
填写好,名字是loacalhost,端口是8832.
注意此时填写好之后不要点击OK。因为虚拟机还没有启动。
3.开启VMWARE->电源->打开电源时进入固件。
之所以这样做是因为好控制,否则时机很难掌握。
此时虚拟机停止在BIOS里运行。
4.点击第二步出现OK。
也就是IDA的那个OK按钮。
弹出个提示框,我没有看,是英文,继续点击OK。
之后又出现个选择框,选择ID为0的那个,然后点击OK。
此时有弹出个提示框,提示成功了,点击OK。
此时弹出了一个界面,此时最好要等待会,可能是在分析。
其实此时也不用等待,直接点击取消按钮,即进入了调试界面。
5.在调试界面的反汇编窗口的地址上右键,然后选择jump to address,在弹出的界面中输入:MEMORY:00007C00。
然后点击OK。此时定位到这个指令。
注意:此时因为还在BIOS里运行,MBR还没有运行,所以这里的内容是空的。
不过,在这里可以先设置断点。设置断点的做法就不说了。
设置完毕之后按F9,让她继续运行。
6.切换/进入IDA,也就是在IDA中点击那个绿色的三角箭头。
此时还在BIOS里运行,所以要继续运行。
我是点击F10,然后选择保存就运行了。
7.因为刚才设置的IDA断点,此时IDA段下来了。此时VMWARE出现绿色的三角箭头并停止运行。
此时IDA的MEMORY:00007C00处也有内容了。
但是此时是32位的汇编。
此时按下alt + s,然后选16-bit segment。
此时变成了数据,然后再右键选择代码就可以了。
此时变成了16位的汇编了。
从此开始你的系统之旅吧!
MBR->BPR->直至系统加载成功。
made by correy
made at 9:29 2015/6/3.
步骤:
1.VMware的.vmx文件的配置。
这个就不说了,假定你已经会了。
例如:
debugStub.listen.guest32 = "TRUE"
debugStub.hideBreakpoints= "TRUE"
还如:
debugStub.listen.guest32.remote = "TRUE"
debugStub.listen.guest64.remote = "TRUE"
monitor.debugOnStartGuest32 = "TRUE"
debugStub.hideBreakpoints = "TRUE"
bios.bootDelay = "3000"
具体的可参观官网的:Debugging Windows kernel under VMWare using IDA's GDB debugger.PDF
其中就有如下经典的两行:
debugStub.listen.guest32 = "TRUE"
debugStub.hideBreakpoints= "TRUE"
2.开启IDA->debugger->attach->remote GDB debugger.
填写好,名字是loacalhost,端口是8832.
注意此时填写好之后不要点击OK。因为虚拟机还没有启动。
3.开启VMWARE->电源->打开电源时进入固件。
之所以这样做是因为好控制,否则时机很难掌握。
此时虚拟机停止在BIOS里运行。
4.点击第二步出现OK。
也就是IDA的那个OK按钮。
弹出个提示框,我没有看,是英文,继续点击OK。
之后又出现个选择框,选择ID为0的那个,然后点击OK。
此时有弹出个提示框,提示成功了,点击OK。
此时弹出了一个界面,此时最好要等待会,可能是在分析。
其实此时也不用等待,直接点击取消按钮,即进入了调试界面。
5.在调试界面的反汇编窗口的地址上右键,然后选择jump to address,在弹出的界面中输入:MEMORY:00007C00。
然后点击OK。此时定位到这个指令。
注意:此时因为还在BIOS里运行,MBR还没有运行,所以这里的内容是空的。
不过,在这里可以先设置断点。设置断点的做法就不说了。
设置完毕之后按F9,让她继续运行。
6.切换/进入IDA,也就是在IDA中点击那个绿色的三角箭头。
此时还在BIOS里运行,所以要继续运行。
我是点击F10,然后选择保存就运行了。
7.因为刚才设置的IDA断点,此时IDA段下来了。此时VMWARE出现绿色的三角箭头并停止运行。
此时IDA的MEMORY:00007C00处也有内容了。
但是此时是32位的汇编。
此时按下alt + s,然后选16-bit segment。
此时变成了数据,然后再右键选择代码就可以了。
此时变成了16位的汇编了。
从此开始你的系统之旅吧!
MBR->BPR->直至系统加载成功。
made by correy
made at 9:29 2015/6/3.
2015年5月29日星期五
一种minifilter驱动保护的方案
/*
通常的保护驱动的思路是在驱动入口不设置驱动对象的卸载函数的成员。
minifilter框架也类似。
开始的思路也是这样的,
可是经测试不行,因为通常minifilter不设置驱动对象的卸载函数,而是设置FLT_REGISTRATION的卸载函数。
经分析FltRegisterFilter是把自己的_FLT_REGISTRATION复制/修改到_FLT_FILTER。
最后经分析和原始的想法是一样的。
不罗嗦了,直接见要点.
具体的做法是:
1.FLT_REGISTRATION的Flags包含FLTFL_REGISTRATION_DO_NOT_SUPPORT_SERVICE_STOP。
这是通过逆向分析出的。
MSDN是这样说的:
If this flag is set, the minifilter is not unloaded in response to service stop requests, even if the FilterUnloadCallback member is not NULL.
也就是说,如果这样了即使设置了FilterUnloadCallback成员,FilterUnloadCallback成员也是无效的。
具体的键反汇编。
还有一个值是:FLTFL_REGISTRATION_SUPPORT_NPFS_MSFS,这个早就研究了。
2.驱动不能停止咋办?(不同于卸载,禁止卸载可以通过注册表回调来实现,更不是隐藏等别的功能)
此时驱动还在运行,我们可以和他通讯呀!
所以可选的思路有:
1)设置驱动对象的卸载函数为FLT_REGISTRATION的FilterUnloadCallback应该设置的函数。
2)设置驱动对象的卸载函数为fltmgr!FltpMiniFilterDriverUnload。
3)设置驱动对象的卸载函数为nt!IopInvalidDeviceRequest。
经测试:
方法三是不可行的,这个会蓝屏,蓝屏原因就不说了,你分析吧!
方法二是不可取的,因为那个函数是未公开的,函数的地址不好获取。
方法以是可行的,建议的。
made by correy
made at 2015.05.29
下面附下IDA分析的FltRegisterFilter函数:
*/
NTSTATUS __stdcall FltRegisterFilter(PDRIVER_OBJECT Driver, _FLT_REGISTRATION *Registration, _FLT_FILTER **RetFilter)
/*
略有改动,改为自己的编码风格。
里面还有一些数字的含义,请自己修改。
*/
{
NTSTATUS result; // eax@2
_FLT_REGISTRATION *P_FLT_REGISTRATION; // esi@3
int n; // eax@10
_FLT_OPERATION_REGISTRATION *OperationRegistration; // ecx@10
_FLT_FILTER *Ret_Filter; // ebx@14
_FLT_MUTEX_LIST_HEAD *ActiveOpens; // ST28_4@16
_FLT_MUTEX_LIST_HEAD *PortList; // ST20_4@16
_FLT_OPERATION_REGISTRATION *i; // eax@19
char MajorFunction; // cl@20
int temp; // ST44_4@28
unsigned int OperationRegistration_length; // [sp+30h] [bp-24h]@14
_FLT_OPERATION_REGISTRATION *P_FLT_OPERATION_REGISTRATION; // [sp+34h] [bp-20h]@16
NTSTATUS result_2; // [sp+38h] [bp-1Ch]@17
BOOL B = FALSE;
*RetFilter = 0;
if ( !(g_dword_BIT & 1) )
return 0xC01C0007; // 见ntstatus.h的定义。
P_FLT_REGISTRATION = Registration;
if ( (Registration->Version & 0xFF00) != 512 )
return 0xC000000D; // 见ntstatus.h的定义。
result = FltpRestoreFltMgrsPageableState();
if ( result < 0 )
return result;
B = (Registration->GenerateFileNameCallback || !Registration->NormalizeNameComponentCallback) && (Registration->NormalizeNameComponentCallback || !Registration->NormalizeContextCleanupCallback);
if ( !B )
{
return 0xC000000D; // 见ntstatus.h的定义。
}
n = 0;
OperationRegistration = Registration->OperationRegistration;
if ( OperationRegistration )
{
while ( 1 )
{
++n;
if ( OperationRegistration->MajorFunction == -128 )
break;
++OperationRegistration;
}
}
OperationRegistration_length = 20 * n;
Ret_Filter = (_FLT_FILTER *)ExAllocatePoolWithTag(0, 20 * n + Driver->DriverExtension->ServiceKeyName.Length + 288, 0x6C664D46u);
if ( !Ret_Filter )
{
return 0xC000009A;
}
memset(Ret_Filter, 0, 0x120u);
Ret_Filter->FilterUnload = Registration->FilterUnloadCallback;
Ret_Filter->InstanceSetup = Registration->InstanceSetupCallback;
Ret_Filter->InstanceQueryTeardown = Registration->InstanceQueryTeardownCallback;
Ret_Filter->InstanceTeardownStart = Registration->InstanceTeardownStartCallback;
Ret_Filter->InstanceTeardownComplete = Registration->InstanceTeardownCompleteCallback;
Ret_Filter->GenerateFileName = Registration->GenerateFileNameCallback;
Ret_Filter->NormalizeNameComponent = Registration->NormalizeNameComponentCallback;
Ret_Filter->NormalizeContextCleanup = Registration->NormalizeContextCleanupCallback;
P_FLT_OPERATION_REGISTRATION = (_FLT_OPERATION_REGISTRATION *)&Ret_Filter[1];
Ret_Filter->Base.Flags = 0x2000000;
Ret_Filter->Base.PointerCount = 1;
FltpExInitializeRundownProtection(&Ret_Filter->Base.RundownRef);
Ret_Filter->Base.PrimaryLink.Flink = 0;
FltObjectReference((int)Ret_Filter);
Ret_Filter->DriverObject = Driver;
Ret_Filter->InstanceList.rCount = 0;
ExInitializeResourceLite(&Ret_Filter->InstanceList.rLock);
InitializeListHead(&Ret_Filter->InstanceList.rList);
ActiveOpens = &Ret_Filter->ActiveOpens;
ActiveOpens->mCount = 0;
ActiveOpens->mLock.Count = 1;
ActiveOpens->mLock.Owner = 0;
ActiveOpens->mLock.Contention = 0;
KeInitializeEvent(&Ret_Filter->ActiveOpens.mLock.Event, SynchronizationEvent, 0);
InitializeListHead(&Ret_Filter->ActiveOpens.mList);
PortList = &Ret_Filter->PortList;
PortList->mCount = 0;
PortList->mLock.Count = 1;
PortList->mLock.Owner = 0;
PortList->mLock.Contention = 0;
KeInitializeEvent(&Ret_Filter->PortList.mLock.Event, SynchronizationEvent, 0);
InitializeListHead(&Ret_Filter->PortList.mList);
Ret_Filter->PortLock.Value = 0;
if ( !Registration->ContextRegistration || (result_2 = FltpProcessContextRegistration((int)Ret_Filter, &Registration->ContextRegistration->ContextType), result_2 >= 0) )
{
if ( Registration->OperationRegistration )//各个操作的前后操作。
{
Ret_Filter->Operations = P_FLT_OPERATION_REGISTRATION;
P_FLT_OPERATION_REGISTRATION = (_FLT_OPERATION_REGISTRATION *)((char *)P_FLT_OPERATION_REGISTRATION + OperationRegistration_length);
qmemcpy(&Ret_Filter[1], Registration->OperationRegistration, OperationRegistration_length);
for ( i = Ret_Filter->Operations; ; ++i )
{
MajorFunction = i->MajorFunction;
if ( i->MajorFunction == -128 )
break;
if ( MajorFunction == -19 )
{
Ret_Filter->PreVolumeMount = i->PreOperation;
Ret_Filter->PostVolumeMount = i->PostOperation;
}
else if ( MajorFunction != -20 && MajorFunction == 16 )//#define IRP_MJ_SHUTDOWN 0x10.关机是没有后操作的,有了,按思想是笑话。你设置了,这里也会给抹掉。
{
i->PostOperation = 0;
}
}
P_FLT_REGISTRATION = Registration;
}
Ret_Filter->Name.Buffer = (unsigned __int16 *)P_FLT_OPERATION_REGISTRATION;
Ret_Filter->Name.Length = 0;
Ret_Filter->Name.MaximumLength = Driver->DriverExtension->ServiceKeyName.Length;
temp = (int)(&P_FLT_OPERATION_REGISTRATION->MajorFunction + Driver->DriverExtension->ServiceKeyName.Length);
RtlCopyUnicodeString((PUNICODE_STRING)&Ret_Filter->Name, (PCUNICODE_STRING)&Driver->DriverExtension->ServiceKeyName);
result_2 = FltpInitializeFilterVerifier(Ret_Filter);
if ( result_2 >= 0 )
{
result_2 = FltpGetInstanceAltitude(Ret_Filter, 0, 0, (PUNICODE_STRING)&Ret_Filter->DefaultAltitude);
if ( result_2 >= 0 )
{
result_2 = FltpFindFrameForFilter(Ret_Filter, &Ret_Filter->DefaultAltitude);
if ( result_2 >= 0 )
{
result_2 = FltpLinkFilterIntoFrame(Ret_Filter);
if ( result_2 >= 0 )
{
Ret_Filter->OldDriverUnload = Driver->DriverUnload;
if ( !P_FLT_REGISTRATION->FilterUnloadCallback || P_FLT_REGISTRATION->Flags & 1 )//#define FLTFL_REGISTRATION_DO_NOT_SUPPORT_SERVICE_STOP 0x00000001
{//If this flag is set, the minifilter is not unloaded in response to service stop requests, even if the FilterUnloadCallback member is not NULL.
Driver->DriverUnload = 0;
DriverObject->DriverUnload = 0;
}
else
{
Driver->DriverUnload = (void (__stdcall *)(_DRIVER_OBJECT *))FltpMiniFilterDriverUnload;
}
if ( !(g_dword_BIT & 0x20) )
g_dword_BIT |= 0x20u;
*RetFilter = Ret_Filter;
}
}
}
}
}
if ( result_2 < 0 )
{
ExDeleteResourceLite(&Ret_Filter->InstanceList.rLock);
FltpCleanupContextRegistration(Ret_Filter);
FltpCleanupFilterVerifier(Ret_Filter);
FltpFreeUnicodeString(&Ret_Filter->DefaultAltitude);
ExFreePoolWithTag(Ret_Filter, 0);
}
result = result_2;
return result;
}
/*
3.注意:
文件微过滤驱动的卸载函数的原型是:
typedef NTSTATUS (*PFLT_FILTER_UNLOAD_CALLBACK) ( FLT_FILTER_UNLOAD_FLAGS Flags );
这个不同于常规驱动的的卸载函数。
VOID DRIVER_UNLOAD ( _In_ struct _DRIVER_OBJECT *DriverObject );
区别是返回值和参数。
这里有一个值:FLTFL_FILTER_UNLOAD_MANDATORY。
这个函数的说明是:
Minifilter drivers are not required to register a FilterUnloadCallback routine.
However, registering an unload routine is strongly recommended.
If a minifilter driver does not register a FilterUnloadCallback routine, it cannot be unloaded.
卸载函数不是必须的,但是强烈建议加上,如果没有就不能卸载。
注意:FLTFL_FILTER_UNLOAD_MANDATORY和STATUS_FLT_DO_NOT_DETACH的关系。
如果:是FLTFL_FILTER_UNLOAD_MANDATORY必须返回成功,如果返回STATUS_FLT_DO_NOT_DETACH会蓝屏。
可是用net stop每次都是FLTFL_FILTER_UNLOAD_MANDATORY,sc stop没有试验,但是fltmc unload 却不是。
所以此思路无效不可行。
*/
通常的保护驱动的思路是在驱动入口不设置驱动对象的卸载函数的成员。
minifilter框架也类似。
开始的思路也是这样的,
可是经测试不行,因为通常minifilter不设置驱动对象的卸载函数,而是设置FLT_REGISTRATION的卸载函数。
经分析FltRegisterFilter是把自己的_FLT_REGISTRATION复制/修改到_FLT_FILTER。
最后经分析和原始的想法是一样的。
不罗嗦了,直接见要点.
具体的做法是:
1.FLT_REGISTRATION的Flags包含FLTFL_REGISTRATION_DO_NOT_SUPPORT_SERVICE_STOP。
这是通过逆向分析出的。
MSDN是这样说的:
If this flag is set, the minifilter is not unloaded in response to service stop requests, even if the FilterUnloadCallback member is not NULL.
也就是说,如果这样了即使设置了FilterUnloadCallback成员,FilterUnloadCallback成员也是无效的。
具体的键反汇编。
还有一个值是:FLTFL_REGISTRATION_SUPPORT_NPFS_MSFS,这个早就研究了。
2.驱动不能停止咋办?(不同于卸载,禁止卸载可以通过注册表回调来实现,更不是隐藏等别的功能)
此时驱动还在运行,我们可以和他通讯呀!
所以可选的思路有:
1)设置驱动对象的卸载函数为FLT_REGISTRATION的FilterUnloadCallback应该设置的函数。
2)设置驱动对象的卸载函数为fltmgr!FltpMiniFilterDriverUnload。
3)设置驱动对象的卸载函数为nt!IopInvalidDeviceRequest。
经测试:
方法三是不可行的,这个会蓝屏,蓝屏原因就不说了,你分析吧!
方法二是不可取的,因为那个函数是未公开的,函数的地址不好获取。
方法以是可行的,建议的。
made by correy
made at 2015.05.29
下面附下IDA分析的FltRegisterFilter函数:
*/
NTSTATUS __stdcall FltRegisterFilter(PDRIVER_OBJECT Driver, _FLT_REGISTRATION *Registration, _FLT_FILTER **RetFilter)
/*
略有改动,改为自己的编码风格。
里面还有一些数字的含义,请自己修改。
*/
{
NTSTATUS result; // eax@2
_FLT_REGISTRATION *P_FLT_REGISTRATION; // esi@3
int n; // eax@10
_FLT_OPERATION_REGISTRATION *OperationRegistration; // ecx@10
_FLT_FILTER *Ret_Filter; // ebx@14
_FLT_MUTEX_LIST_HEAD *ActiveOpens; // ST28_4@16
_FLT_MUTEX_LIST_HEAD *PortList; // ST20_4@16
_FLT_OPERATION_REGISTRATION *i; // eax@19
char MajorFunction; // cl@20
int temp; // ST44_4@28
unsigned int OperationRegistration_length; // [sp+30h] [bp-24h]@14
_FLT_OPERATION_REGISTRATION *P_FLT_OPERATION_REGISTRATION; // [sp+34h] [bp-20h]@16
NTSTATUS result_2; // [sp+38h] [bp-1Ch]@17
BOOL B = FALSE;
*RetFilter = 0;
if ( !(g_dword_BIT & 1) )
return 0xC01C0007; // 见ntstatus.h的定义。
P_FLT_REGISTRATION = Registration;
if ( (Registration->Version & 0xFF00) != 512 )
return 0xC000000D; // 见ntstatus.h的定义。
result = FltpRestoreFltMgrsPageableState();
if ( result < 0 )
return result;
B = (Registration->GenerateFileNameCallback || !Registration->NormalizeNameComponentCallback) && (Registration->NormalizeNameComponentCallback || !Registration->NormalizeContextCleanupCallback);
if ( !B )
{
return 0xC000000D; // 见ntstatus.h的定义。
}
n = 0;
OperationRegistration = Registration->OperationRegistration;
if ( OperationRegistration )
{
while ( 1 )
{
++n;
if ( OperationRegistration->MajorFunction == -128 )
break;
++OperationRegistration;
}
}
OperationRegistration_length = 20 * n;
Ret_Filter = (_FLT_FILTER *)ExAllocatePoolWithTag(0, 20 * n + Driver->DriverExtension->ServiceKeyName.Length + 288, 0x6C664D46u);
if ( !Ret_Filter )
{
return 0xC000009A;
}
memset(Ret_Filter, 0, 0x120u);
Ret_Filter->FilterUnload = Registration->FilterUnloadCallback;
Ret_Filter->InstanceSetup = Registration->InstanceSetupCallback;
Ret_Filter->InstanceQueryTeardown = Registration->InstanceQueryTeardownCallback;
Ret_Filter->InstanceTeardownStart = Registration->InstanceTeardownStartCallback;
Ret_Filter->InstanceTeardownComplete = Registration->InstanceTeardownCompleteCallback;
Ret_Filter->GenerateFileName = Registration->GenerateFileNameCallback;
Ret_Filter->NormalizeNameComponent = Registration->NormalizeNameComponentCallback;
Ret_Filter->NormalizeContextCleanup = Registration->NormalizeContextCleanupCallback;
P_FLT_OPERATION_REGISTRATION = (_FLT_OPERATION_REGISTRATION *)&Ret_Filter[1];
Ret_Filter->Base.Flags = 0x2000000;
Ret_Filter->Base.PointerCount = 1;
FltpExInitializeRundownProtection(&Ret_Filter->Base.RundownRef);
Ret_Filter->Base.PrimaryLink.Flink = 0;
FltObjectReference((int)Ret_Filter);
Ret_Filter->DriverObject = Driver;
Ret_Filter->InstanceList.rCount = 0;
ExInitializeResourceLite(&Ret_Filter->InstanceList.rLock);
InitializeListHead(&Ret_Filter->InstanceList.rList);
ActiveOpens = &Ret_Filter->ActiveOpens;
ActiveOpens->mCount = 0;
ActiveOpens->mLock.Count = 1;
ActiveOpens->mLock.Owner = 0;
ActiveOpens->mLock.Contention = 0;
KeInitializeEvent(&Ret_Filter->ActiveOpens.mLock.Event, SynchronizationEvent, 0);
InitializeListHead(&Ret_Filter->ActiveOpens.mList);
PortList = &Ret_Filter->PortList;
PortList->mCount = 0;
PortList->mLock.Count = 1;
PortList->mLock.Owner = 0;
PortList->mLock.Contention = 0;
KeInitializeEvent(&Ret_Filter->PortList.mLock.Event, SynchronizationEvent, 0);
InitializeListHead(&Ret_Filter->PortList.mList);
Ret_Filter->PortLock.Value = 0;
if ( !Registration->ContextRegistration || (result_2 = FltpProcessContextRegistration((int)Ret_Filter, &Registration->ContextRegistration->ContextType), result_2 >= 0) )
{
if ( Registration->OperationRegistration )//各个操作的前后操作。
{
Ret_Filter->Operations = P_FLT_OPERATION_REGISTRATION;
P_FLT_OPERATION_REGISTRATION = (_FLT_OPERATION_REGISTRATION *)((char *)P_FLT_OPERATION_REGISTRATION + OperationRegistration_length);
qmemcpy(&Ret_Filter[1], Registration->OperationRegistration, OperationRegistration_length);
for ( i = Ret_Filter->Operations; ; ++i )
{
MajorFunction = i->MajorFunction;
if ( i->MajorFunction == -128 )
break;
if ( MajorFunction == -19 )
{
Ret_Filter->PreVolumeMount = i->PreOperation;
Ret_Filter->PostVolumeMount = i->PostOperation;
}
else if ( MajorFunction != -20 && MajorFunction == 16 )//#define IRP_MJ_SHUTDOWN 0x10.关机是没有后操作的,有了,按思想是笑话。你设置了,这里也会给抹掉。
{
i->PostOperation = 0;
}
}
P_FLT_REGISTRATION = Registration;
}
Ret_Filter->Name.Buffer = (unsigned __int16 *)P_FLT_OPERATION_REGISTRATION;
Ret_Filter->Name.Length = 0;
Ret_Filter->Name.MaximumLength = Driver->DriverExtension->ServiceKeyName.Length;
temp = (int)(&P_FLT_OPERATION_REGISTRATION->MajorFunction + Driver->DriverExtension->ServiceKeyName.Length);
RtlCopyUnicodeString((PUNICODE_STRING)&Ret_Filter->Name, (PCUNICODE_STRING)&Driver->DriverExtension->ServiceKeyName);
result_2 = FltpInitializeFilterVerifier(Ret_Filter);
if ( result_2 >= 0 )
{
result_2 = FltpGetInstanceAltitude(Ret_Filter, 0, 0, (PUNICODE_STRING)&Ret_Filter->DefaultAltitude);
if ( result_2 >= 0 )
{
result_2 = FltpFindFrameForFilter(Ret_Filter, &Ret_Filter->DefaultAltitude);
if ( result_2 >= 0 )
{
result_2 = FltpLinkFilterIntoFrame(Ret_Filter);
if ( result_2 >= 0 )
{
Ret_Filter->OldDriverUnload = Driver->DriverUnload;
if ( !P_FLT_REGISTRATION->FilterUnloadCallback || P_FLT_REGISTRATION->Flags & 1 )//#define FLTFL_REGISTRATION_DO_NOT_SUPPORT_SERVICE_STOP 0x00000001
{//If this flag is set, the minifilter is not unloaded in response to service stop requests, even if the FilterUnloadCallback member is not NULL.
Driver->DriverUnload = 0;
DriverObject->DriverUnload = 0;
}
else
{
Driver->DriverUnload = (void (__stdcall *)(_DRIVER_OBJECT *))FltpMiniFilterDriverUnload;
}
if ( !(g_dword_BIT & 0x20) )
g_dword_BIT |= 0x20u;
*RetFilter = Ret_Filter;
}
}
}
}
}
if ( result_2 < 0 )
{
ExDeleteResourceLite(&Ret_Filter->InstanceList.rLock);
FltpCleanupContextRegistration(Ret_Filter);
FltpCleanupFilterVerifier(Ret_Filter);
FltpFreeUnicodeString(&Ret_Filter->DefaultAltitude);
ExFreePoolWithTag(Ret_Filter, 0);
}
result = result_2;
return result;
}
/*
3.注意:
文件微过滤驱动的卸载函数的原型是:
typedef NTSTATUS (*PFLT_FILTER_UNLOAD_CALLBACK) ( FLT_FILTER_UNLOAD_FLAGS Flags );
这个不同于常规驱动的的卸载函数。
VOID DRIVER_UNLOAD ( _In_ struct _DRIVER_OBJECT *DriverObject );
区别是返回值和参数。
这里有一个值:FLTFL_FILTER_UNLOAD_MANDATORY。
这个函数的说明是:
Minifilter drivers are not required to register a FilterUnloadCallback routine.
However, registering an unload routine is strongly recommended.
If a minifilter driver does not register a FilterUnloadCallback routine, it cannot be unloaded.
卸载函数不是必须的,但是强烈建议加上,如果没有就不能卸载。
注意:FLTFL_FILTER_UNLOAD_MANDATORY和STATUS_FLT_DO_NOT_DETACH的关系。
如果:是FLTFL_FILTER_UNLOAD_MANDATORY必须返回成功,如果返回STATUS_FLT_DO_NOT_DETACH会蓝屏。
可是用net stop每次都是FLTFL_FILTER_UNLOAD_MANDATORY,sc stop没有试验,但是fltmc unload 却不是。
所以此思路无效不可行。
*/
2015年5月28日星期四
IDAPRO之结构分析
在IDA中是可以这样的:
NTSTATUS __stdcall FltRegisterFilter(PDRIVER_OBJECT Driver, _FLT_REGISTRATION *Registration, _FLT_FILTER **RetFilter)
{
NTSTATUS result; // eax@2
_FLT_REGISTRATION *v4; // esi@3
int v5; // eax@10
_FLT_OPERATION_REGISTRATION *v6; // ecx@10
_FLT_FILTER *Ret_Filter; // ebx@14
_LIST_ENTRY *InstanceList_rList; // ST2C_4@16
_FLT_MUTEX_LIST_HEAD *ActiveOpens; // ST28_4@16
_LIST_ENTRY *ActiveOpens_mList; // ST24_4@16
_FLT_MUTEX_LIST_HEAD *PortList; // ST20_4@16
_LIST_ENTRY *PortList_mList; // ST1C_4@16
_FLT_OPERATION_REGISTRATION *i; // eax@19
char MajorFunction; // cl@20
int temp; // ST44_4@28
unsigned int OperationRegistration_length; // [sp+30h] [bp-24h]@14
_FLT_OPERATION_REGISTRATION *v17; // [sp+34h] [bp-20h]@16
NTSTATUS result_2; // [sp+38h] [bp-1Ch]@17
*RetFilter = 0;
if ( !(g_dword_XXX & 1) )
return 0xC01C0007; // 见ntstatus.h的定义。
v4 = Registration;
if ( (Registration->Version & 0xFF00) != 512 )
goto LABEL_46;
result = FltpRestoreFltMgrsPageableState();
if ( result < 0 )
return result;
if ( (Registration->GenerateFileNameCallback || !Registration->NormalizeNameComponentCallback)
&& (Registration->NormalizeNameComponentCallback || !Registration->NormalizeContextCleanupCallback) )
{
v5 = 0;
v6 = Registration->OperationRegistration;
if ( v6 )
{
while ( 1 )
{
++v5;
if ( v6->MajorFunction == -128 )
break;
++v6;
}
}
OperationRegistration_length = 20 * v5;
Ret_Filter = (_FLT_FILTER *)ExAllocatePoolWithTag(
0,
20 * v5 + Driver->DriverExtension->ServiceKeyName.Length + 288,
0x6C664D46u);
if ( Ret_Filter )
{
memset(Ret_Filter, 0, 0x120u);
Ret_Filter->FilterUnload = Registration->FilterUnloadCallback;
Ret_Filter->InstanceSetup = Registration->InstanceSetupCallback;
Ret_Filter->InstanceQueryTeardown = Registration->InstanceQueryTeardownCallback;
Ret_Filter->InstanceTeardownStart = Registration->InstanceTeardownStartCallback;
Ret_Filter->InstanceTeardownComplete = Registration->InstanceTeardownCompleteCallback;
Ret_Filter->GenerateFileName = Registration->GenerateFileNameCallback;
Ret_Filter->NormalizeNameComponent = Registration->NormalizeNameComponentCallback;
Ret_Filter->NormalizeContextCleanup = Registration->NormalizeContextCleanupCallback;
v17 = (_FLT_OPERATION_REGISTRATION *)&Ret_Filter[1];
Ret_Filter->Base.Flags = 0x2000000;
Ret_Filter->Base.PointerCount = 1;
FltpExInitializeRundownProtection(&Ret_Filter->Base.RundownRef);
Ret_Filter->Base.PrimaryLink.Flink = 0;
FltObjectReference((int)Ret_Filter);
Ret_Filter->DriverObject = Driver;
Ret_Filter->InstanceList.rCount = 0;
ExInitializeResourceLite(&Ret_Filter->InstanceList.rLock);
InstanceList_rList = &Ret_Filter->InstanceList.rList;
InstanceList_rList->Blink = InstanceList_rList;
InstanceList_rList->Flink = InstanceList_rList;
ActiveOpens = &Ret_Filter->ActiveOpens;
ActiveOpens->mCount = 0;
ActiveOpens->mLock.Count = 1;
ActiveOpens->mLock.Owner = 0;
ActiveOpens->mLock.Contention = 0;
KeInitializeEvent(&Ret_Filter->ActiveOpens.mLock.Event, SynchronizationEvent, 0);
ActiveOpens_mList = &Ret_Filter->ActiveOpens.mList;
ActiveOpens_mList->Blink = ActiveOpens_mList;
ActiveOpens_mList->Flink = ActiveOpens_mList;
PortList = &Ret_Filter->PortList;
PortList->mCount = 0;
PortList->mLock.Count = 1;
PortList->mLock.Owner = 0;
PortList->mLock.Contention = 0;
KeInitializeEvent(&Ret_Filter->PortList.mLock.Event, SynchronizationEvent, 0);
PortList_mList = &Ret_Filter->PortList.mList;
PortList_mList->Blink = PortList_mList;
PortList_mList->Flink = PortList_mList;
Ret_Filter->PortLock.Value = 0;
if ( !Registration->ContextRegistration
|| (result_2 = FltpProcessContextRegistration((int)Ret_Filter, &Registration->ContextRegistration->ContextType),
result_2 >= 0) )
{
if ( Registration->OperationRegistration )
{
Ret_Filter->Operations = v17;
v17 = (_FLT_OPERATION_REGISTRATION *)((char *)v17 + OperationRegistration_length);
qmemcpy(&Ret_Filter[1], Registration->OperationRegistration, OperationRegistration_length);
for ( i = Ret_Filter->Operations; ; ++i )
{
MajorFunction = i->MajorFunction;
if ( i->MajorFunction == -128 )
break;
if ( MajorFunction == -19 )
{
Ret_Filter->PreVolumeMount = i->PreOperation;
Ret_Filter->PostVolumeMount = i->PostOperation;
}
else if ( MajorFunction != -20 && MajorFunction == 16 )
{
i->PostOperation = 0;
}
}
v4 = Registration;
}
Ret_Filter->Name.Buffer = (unsigned __int16 *)v17;
Ret_Filter->Name.Length = 0;
Ret_Filter->Name.MaximumLength = Driver->DriverExtension->ServiceKeyName.Length;
temp = (int)(&v17->MajorFunction + Driver->DriverExtension->ServiceKeyName.Length);
RtlCopyUnicodeString(
(PUNICODE_STRING)&Ret_Filter->Name,
(PCUNICODE_STRING)&Driver->DriverExtension->ServiceKeyName);
result_2 = FltpInitializeFilterVerifier(Ret_Filter);
if ( result_2 >= 0 )
{
result_2 = FltpGetInstanceAltitude(Ret_Filter, 0, 0, (PUNICODE_STRING)&Ret_Filter->DefaultAltitude);
if ( result_2 >= 0 )
{
result_2 = FltpFindFrameForFilter(Ret_Filter, &Ret_Filter->DefaultAltitude);
if ( result_2 >= 0 )
{
result_2 = FltpLinkFilterIntoFrame(Ret_Filter);
if ( result_2 >= 0 )
{
Ret_Filter->OldDriverUnload = Driver->DriverUnload;
if ( !v4->FilterUnloadCallback || v4->Flags & 1 )
{
Driver->DriverUnload = 0;
DriverObject->DriverUnload = 0;
}
else
{
Driver->DriverUnload = (void (__stdcall *)(_DRIVER_OBJECT *))FltpMiniFilterDriverUnload;
}
if ( !(g_dword_XXX & 0x20) )
g_dword_XXX |= 0x20u;
*RetFilter = Ret_Filter;
}
}
}
}
}
if ( result_2 < 0 )
{
ExDeleteResourceLite(&Ret_Filter->InstanceList.rLock);
FltpCleanupContextRegistration(Ret_Filter);
FltpCleanupFilterVerifier(Ret_Filter);
FltpFreeUnicodeString(&Ret_Filter->DefaultAltitude);
ExFreePoolWithTag(Ret_Filter, 0);
}
result = result_2;
}
else
{
result = 0xC000009A; // 见ntstatus.h的定义。
}
}
else
{
LABEL_46:
result = 0xC000000D; // 见ntstatus.h的定义。
}
return result;
}
这主要是导入/创建几个结构,修改下变量的名字和类型就可以了。
再次认识到:程序就是数据和指令的含义。
WINDBG辅助分析如下:
0: kd> dt fltmgr!_FLT_REGISTRATION
+0x000 Size : Uint2B
+0x002 Version : Uint2B
+0x004 Flags : Uint4B
+0x008 ContextRegistration : Ptr32 _FLT_CONTEXT_REGISTRATION
+0x00c OperationRegistration : Ptr32 _FLT_OPERATION_REGISTRATION
+0x010 FilterUnloadCallback : Ptr32 long
+0x014 InstanceSetupCallback : Ptr32 long
+0x018 InstanceQueryTeardownCallback : Ptr32 long
+0x01c InstanceTeardownStartCallback : Ptr32 void
+0x020 InstanceTeardownCompleteCallback : Ptr32 void
+0x024 GenerateFileNameCallback : Ptr32 long
+0x028 NormalizeNameComponentCallback : Ptr32 long
+0x02c NormalizeContextCleanupCallback : Ptr32 void
1: kd> dd gFilterHandle
ba08b558 81f84390
1: kd> dt _FLT_FILTER 81f84390
fltMgr!_FLT_FILTER
+0x000 Base : _FLT_OBJECT
+0x014 Frame : 0x81c62000 _FLTP_FRAME
+0x018 Name : _UNICODE_STRING "ahsh"
+0x020 DefaultAltitude : _UNICODE_STRING "370030"
+0x028 Flags : 0 (No matching name)
+0x02c DriverObject : 0x81d9ff38 _DRIVER_OBJECT
+0x030 InstanceList : _FLT_RESOURCE_LIST_HEAD
+0x074 VerifierExtension : 0x81f855e8 _FLT_VERIFIER_EXTENSION
+0x078 FilterUnload : 0xba08b810 long ahsh!FltUnload+0
+0x07c InstanceSetup : 0xba607790 long fltMgr!FltvInstanceSetup+0
+0x080 InstanceQueryTeardown : 0xba6077b4 long fltMgr!FltvInstanceQueryTeardown+0
+0x084 InstanceTeardownStart : (null)
+0x088 InstanceTeardownComplete : (null)
+0x08c SupportedContextsListHead : (null)
+0x090 SupportedContexts : [6] (null)
+0x0a8 PreVolumeMount : (null)
+0x0ac PostVolumeMount : (null)
+0x0b0 GenerateFileName : 0xba072800 long ahsh!GenerateFileName+0
+0x0b4 NormalizeNameComponent : 0xba072c30 long ahsh!NormalizeNameComponent+0
+0x0b8 NormalizeContextCleanup : (null)
+0x0bc Operations : 0x81f844b0 _FLT_OPERATION_REGISTRATION
+0x0c0 OldDriverUnload : (null)
+0x0c4 ActiveOpens : _FLT_MUTEX_LIST_HEAD
+0x0f0 PortList : _FLT_MUTEX_LIST_HEAD
+0x11c PortLock : _EX_PUSH_LOCK
0: kd> !drvobj \filesystem\ahsh 7
Driver object (81ff6750) is for:
\FileSystem\ahsh
Driver Extension List: (id , addr)
Device Object list:
DriverEntry: ba0c1e80 ahsh!GsDriverEntry
DriverStartIo: 00000000
DriverUnload: 00000000
AddDevice: 00000000
Dispatch routines:
[00] IRP_MJ_CREATE 804f55ce nt!IopInvalidDeviceRequest
[01] IRP_MJ_CREATE_NAMED_PIPE 804f55ce nt!IopInvalidDeviceRequest
[02] IRP_MJ_CLOSE 804f55ce nt!IopInvalidDeviceRequest
[03] IRP_MJ_READ 804f55ce nt!IopInvalidDeviceRequest
[04] IRP_MJ_WRITE 804f55ce nt!IopInvalidDeviceRequest
[05] IRP_MJ_QUERY_INFORMATION 804f55ce nt!IopInvalidDeviceRequest
[06] IRP_MJ_SET_INFORMATION 804f55ce nt!IopInvalidDeviceRequest
[07] IRP_MJ_QUERY_EA 804f55ce nt!IopInvalidDeviceRequest
[08] IRP_MJ_SET_EA 804f55ce nt!IopInvalidDeviceRequest
[09] IRP_MJ_FLUSH_BUFFERS 804f55ce nt!IopInvalidDeviceRequest
[0a] IRP_MJ_QUERY_VOLUME_INFORMATION 804f55ce nt!IopInvalidDeviceRequest
[0b] IRP_MJ_SET_VOLUME_INFORMATION 804f55ce nt!IopInvalidDeviceRequest
[0c] IRP_MJ_DIRECTORY_CONTROL 804f55ce nt!IopInvalidDeviceRequest
[0d] IRP_MJ_FILE_SYSTEM_CONTROL 804f55ce nt!IopInvalidDeviceRequest
[0e] IRP_MJ_DEVICE_CONTROL 804f55ce nt!IopInvalidDeviceRequest
[0f] IRP_MJ_INTERNAL_DEVICE_CONTROL 804f55ce nt!IopInvalidDeviceRequest
[10] IRP_MJ_SHUTDOWN 804f55ce nt!IopInvalidDeviceRequest
[11] IRP_MJ_LOCK_CONTROL 804f55ce nt!IopInvalidDeviceRequest
[12] IRP_MJ_CLEANUP 804f55ce nt!IopInvalidDeviceRequest
[13] IRP_MJ_CREATE_MAILSLOT 804f55ce nt!IopInvalidDeviceRequest
[14] IRP_MJ_QUERY_SECURITY 804f55ce nt!IopInvalidDeviceRequest
[15] IRP_MJ_SET_SECURITY 804f55ce nt!IopInvalidDeviceRequest
[16] IRP_MJ_POWER 804f55ce nt!IopInvalidDeviceRequest
[17] IRP_MJ_SYSTEM_CONTROL 804f55ce nt!IopInvalidDeviceRequest
[18] IRP_MJ_DEVICE_CHANGE 804f55ce nt!IopInvalidDeviceRequest
[19] IRP_MJ_QUERY_QUOTA 804f55ce nt!IopInvalidDeviceRequest
[1a] IRP_MJ_SET_QUOTA 804f55ce nt!IopInvalidDeviceRequest
[1b] IRP_MJ_PNP 804f55ce nt!IopInvalidDeviceRequest
0: kd> dt _FLT_FILTER 81f84390 -b
fltMgr!_FLT_FILTER
+0x000 Base : _FLT_OBJECT
+0x000 Flags : 0xb000b (No matching name)
+0x004 PointerCount : 0x200028
+0x008 RundownRef : _EX_RUNDOWN_REF
+0x000 Count : 0x200048
+0x000 Ptr : 0x00200048
+0x00c PrimaryLink : _LIST_ENTRY [ 0x10018 - 0x108 ]
+0x000 Flink : 0x00010018
+0x004 Blink : 0x00000108
+0x014 Frame : 0x00000002
+0x018 Name : _UNICODE_STRING ""
+0x000 Length : 0xb47
+0x002 MaximumLength : 0
+0x004 Buffer : (null)
+0x020 DefaultAltitude : _UNICODE_STRING ""
+0x000 Length : 0xb47
+0x002 MaximumLength : 0xc
+0x004 Buffer : (null)
+0x028 Flags : 0x79d0000 (No matching name)
+0x02c DriverObject : (null)
+0x030 InstanceList : _FLT_RESOURCE_LIST_HEAD
+0x000 rLock : _ERESOURCE
+0x000 SystemResourcesList : _LIST_ENTRY [ 0x7997a78 - 0x0 ]
+0x000 Flink : 0x07997a78
+0x004 Blink : (null)
+0x008 OwnerTable : 0x07997a78
+0x00c ActiveCount : 0n0
+0x00e Flag : 0
+0x010 SharedWaiters : 0x008d0000
+0x014 ExclusiveWaiters : (null)
+0x018 OwnerThreads :
[00] _OWNER_ENTRY
+0x000 OwnerThread : 0x79d0000
+0x004 OwnerCount : 0n0
+0x004 TableSize : 0
[01]
+0x000 OwnerThread : 0x7997a10
+0x004 OwnerCount : 0n0
+0x004 TableSize : 0
+0x028 ContentionCount : 0x7997a78
+0x02c NumberOfSharedWaiters : 0
+0x02e NumberOfExclusiveWaiters : 0
+0x030 Address : 0x008d0000
+0x030 CreatorBackTraceIndex : 0x8d0000
+0x034 SpinLock : 0
+0x038 rList : _LIST_ENTRY [ 0x7c2e8c7f - 0x67260000 ]
+0x000 Flink : 0x7c2e8c7f
+0x004 Blink : 0x67260000
+0x040 rCount : 0x7c2e8c6c
+0x074 VerifierExtension : (null)
+0x078 FilterUnload : (null)
+0x07c InstanceSetup : (null)
+0x080 InstanceQueryTeardown : 0x00000028
+0x084 InstanceTeardownStart : (null)
+0x088 InstanceTeardownComplete : 0x00000001
+0x08c SupportedContextsListHead : 0x00000018
+0x090 SupportedContexts :
[00] (null)
[01] (null)
[02] 0x0001001b
[03] 0x00000028
[04] 0x00080028
[05] 0x00000018
+0x0a8 PreVolumeMount : (null)
+0x0ac PostVolumeMount : (null)
+0x0b0 GenerateFileName : (null)
+0x0b4 NormalizeNameComponent : (null)
+0x0b8 NormalizeContextCleanup : 0x07997a78
+0x0bc Operations : (null)
+0x0c0 OldDriverUnload : 0x7c2e8c8a
+0x0c4 ActiveOpens : _FLT_MUTEX_LIST_HEAD
+0x000 mLock : _FAST_MUTEX
+0x000 Count : 0n0
+0x004 Owner : (null)
+0x008 Contention : 0
+0x00c Event : _KEVENT
+0x000 Header : _DISPATCHER_HEADER
+0x000 Type : 0 ''
+0x001 Absolute : 0 ''
+0x002 Size : 0 ''
+0x003 Inserted : 0 ''
+0x004 SignalState : 0n0
+0x008 WaitListHead : _LIST_ENTRY [ 0x68 - 0x0 ]
+0x000 Flink : 0x00000068
+0x004 Blink : (null)
+0x01c OldIrql : 1
+0x020 mList : _LIST_ENTRY [ 0x18 - 0x0 ]
+0x000 Flink : 0x00000018
+0x004 Blink : (null)
+0x028 mCount : 0
+0x028 mInvalid : 0y0
+0x0f0 PortList : _FLT_MUTEX_LIST_HEAD
+0x000 mLock : _FAST_MUTEX
+0x000 Count : 0n720907
+0x004 Owner : 0x00200028
+0x008 Contention : 0x200048
+0x00c Event : _KEVENT
+0x000 Header : _DISPATCHER_HEADER
+0x000 Type : 0x18 ''
+0x001 Absolute : 0 ''
+0x002 Size : 0x1 ''
+0x003 Inserted : 0 ''
+0x004 SignalState : 0n264
+0x008 WaitListHead : _LIST_ENTRY [ 0x2 - 0xb47 ]
+0x000 Flink : 0x00000002
+0x004 Blink : 0x00000b47
+0x01c OldIrql : 0
+0x020 mList : _LIST_ENTRY [ 0xc0b47 - 0x0 ]
+0x000 Flink : 0x000c0b47
+0x004 Blink : (null)
+0x028 mCount : 0x79d0000
+0x028 mInvalid : 0y0
+0x11c PortLock : _EX_PUSH_LOCK
+0x000 Waiting : 0y0
+0x000 Exclusive : 0y0
+0x000 Shared : 0y000000000000000000000000000000 (0)
+0x000 Value : 0
+0x000 Ptr : (null)
0: kd> dt 0x81f844b0 _FLT_OPERATION_REGISTRATION
ahsh!_FLT_OPERATION_REGISTRATION
+0x000 MajorFunction : 0x78 'x'
+0x004 Flags : 0
+0x008 PreOperation : 0x07997ae0 _FLT_PREOP_CALLBACK_STATUS +7997ae0
+0x00c PostOperation : (null)
+0x010 Reserved1 : 0x008d0000 Void
NTSTATUS __stdcall FltRegisterFilter(PDRIVER_OBJECT Driver, _FLT_REGISTRATION *Registration, _FLT_FILTER **RetFilter)
{
NTSTATUS result; // eax@2
_FLT_REGISTRATION *v4; // esi@3
int v5; // eax@10
_FLT_OPERATION_REGISTRATION *v6; // ecx@10
_FLT_FILTER *Ret_Filter; // ebx@14
_LIST_ENTRY *InstanceList_rList; // ST2C_4@16
_FLT_MUTEX_LIST_HEAD *ActiveOpens; // ST28_4@16
_LIST_ENTRY *ActiveOpens_mList; // ST24_4@16
_FLT_MUTEX_LIST_HEAD *PortList; // ST20_4@16
_LIST_ENTRY *PortList_mList; // ST1C_4@16
_FLT_OPERATION_REGISTRATION *i; // eax@19
char MajorFunction; // cl@20
int temp; // ST44_4@28
unsigned int OperationRegistration_length; // [sp+30h] [bp-24h]@14
_FLT_OPERATION_REGISTRATION *v17; // [sp+34h] [bp-20h]@16
NTSTATUS result_2; // [sp+38h] [bp-1Ch]@17
*RetFilter = 0;
if ( !(g_dword_XXX & 1) )
return 0xC01C0007; // 见ntstatus.h的定义。
v4 = Registration;
if ( (Registration->Version & 0xFF00) != 512 )
goto LABEL_46;
result = FltpRestoreFltMgrsPageableState();
if ( result < 0 )
return result;
if ( (Registration->GenerateFileNameCallback || !Registration->NormalizeNameComponentCallback)
&& (Registration->NormalizeNameComponentCallback || !Registration->NormalizeContextCleanupCallback) )
{
v5 = 0;
v6 = Registration->OperationRegistration;
if ( v6 )
{
while ( 1 )
{
++v5;
if ( v6->MajorFunction == -128 )
break;
++v6;
}
}
OperationRegistration_length = 20 * v5;
Ret_Filter = (_FLT_FILTER *)ExAllocatePoolWithTag(
0,
20 * v5 + Driver->DriverExtension->ServiceKeyName.Length + 288,
0x6C664D46u);
if ( Ret_Filter )
{
memset(Ret_Filter, 0, 0x120u);
Ret_Filter->FilterUnload = Registration->FilterUnloadCallback;
Ret_Filter->InstanceSetup = Registration->InstanceSetupCallback;
Ret_Filter->InstanceQueryTeardown = Registration->InstanceQueryTeardownCallback;
Ret_Filter->InstanceTeardownStart = Registration->InstanceTeardownStartCallback;
Ret_Filter->InstanceTeardownComplete = Registration->InstanceTeardownCompleteCallback;
Ret_Filter->GenerateFileName = Registration->GenerateFileNameCallback;
Ret_Filter->NormalizeNameComponent = Registration->NormalizeNameComponentCallback;
Ret_Filter->NormalizeContextCleanup = Registration->NormalizeContextCleanupCallback;
v17 = (_FLT_OPERATION_REGISTRATION *)&Ret_Filter[1];
Ret_Filter->Base.Flags = 0x2000000;
Ret_Filter->Base.PointerCount = 1;
FltpExInitializeRundownProtection(&Ret_Filter->Base.RundownRef);
Ret_Filter->Base.PrimaryLink.Flink = 0;
FltObjectReference((int)Ret_Filter);
Ret_Filter->DriverObject = Driver;
Ret_Filter->InstanceList.rCount = 0;
ExInitializeResourceLite(&Ret_Filter->InstanceList.rLock);
InstanceList_rList = &Ret_Filter->InstanceList.rList;
InstanceList_rList->Blink = InstanceList_rList;
InstanceList_rList->Flink = InstanceList_rList;
ActiveOpens = &Ret_Filter->ActiveOpens;
ActiveOpens->mCount = 0;
ActiveOpens->mLock.Count = 1;
ActiveOpens->mLock.Owner = 0;
ActiveOpens->mLock.Contention = 0;
KeInitializeEvent(&Ret_Filter->ActiveOpens.mLock.Event, SynchronizationEvent, 0);
ActiveOpens_mList = &Ret_Filter->ActiveOpens.mList;
ActiveOpens_mList->Blink = ActiveOpens_mList;
ActiveOpens_mList->Flink = ActiveOpens_mList;
PortList = &Ret_Filter->PortList;
PortList->mCount = 0;
PortList->mLock.Count = 1;
PortList->mLock.Owner = 0;
PortList->mLock.Contention = 0;
KeInitializeEvent(&Ret_Filter->PortList.mLock.Event, SynchronizationEvent, 0);
PortList_mList = &Ret_Filter->PortList.mList;
PortList_mList->Blink = PortList_mList;
PortList_mList->Flink = PortList_mList;
Ret_Filter->PortLock.Value = 0;
if ( !Registration->ContextRegistration
|| (result_2 = FltpProcessContextRegistration((int)Ret_Filter, &Registration->ContextRegistration->ContextType),
result_2 >= 0) )
{
if ( Registration->OperationRegistration )
{
Ret_Filter->Operations = v17;
v17 = (_FLT_OPERATION_REGISTRATION *)((char *)v17 + OperationRegistration_length);
qmemcpy(&Ret_Filter[1], Registration->OperationRegistration, OperationRegistration_length);
for ( i = Ret_Filter->Operations; ; ++i )
{
MajorFunction = i->MajorFunction;
if ( i->MajorFunction == -128 )
break;
if ( MajorFunction == -19 )
{
Ret_Filter->PreVolumeMount = i->PreOperation;
Ret_Filter->PostVolumeMount = i->PostOperation;
}
else if ( MajorFunction != -20 && MajorFunction == 16 )
{
i->PostOperation = 0;
}
}
v4 = Registration;
}
Ret_Filter->Name.Buffer = (unsigned __int16 *)v17;
Ret_Filter->Name.Length = 0;
Ret_Filter->Name.MaximumLength = Driver->DriverExtension->ServiceKeyName.Length;
temp = (int)(&v17->MajorFunction + Driver->DriverExtension->ServiceKeyName.Length);
RtlCopyUnicodeString(
(PUNICODE_STRING)&Ret_Filter->Name,
(PCUNICODE_STRING)&Driver->DriverExtension->ServiceKeyName);
result_2 = FltpInitializeFilterVerifier(Ret_Filter);
if ( result_2 >= 0 )
{
result_2 = FltpGetInstanceAltitude(Ret_Filter, 0, 0, (PUNICODE_STRING)&Ret_Filter->DefaultAltitude);
if ( result_2 >= 0 )
{
result_2 = FltpFindFrameForFilter(Ret_Filter, &Ret_Filter->DefaultAltitude);
if ( result_2 >= 0 )
{
result_2 = FltpLinkFilterIntoFrame(Ret_Filter);
if ( result_2 >= 0 )
{
Ret_Filter->OldDriverUnload = Driver->DriverUnload;
if ( !v4->FilterUnloadCallback || v4->Flags & 1 )
{
Driver->DriverUnload = 0;
DriverObject->DriverUnload = 0;
}
else
{
Driver->DriverUnload = (void (__stdcall *)(_DRIVER_OBJECT *))FltpMiniFilterDriverUnload;
}
if ( !(g_dword_XXX & 0x20) )
g_dword_XXX |= 0x20u;
*RetFilter = Ret_Filter;
}
}
}
}
}
if ( result_2 < 0 )
{
ExDeleteResourceLite(&Ret_Filter->InstanceList.rLock);
FltpCleanupContextRegistration(Ret_Filter);
FltpCleanupFilterVerifier(Ret_Filter);
FltpFreeUnicodeString(&Ret_Filter->DefaultAltitude);
ExFreePoolWithTag(Ret_Filter, 0);
}
result = result_2;
}
else
{
result = 0xC000009A; // 见ntstatus.h的定义。
}
}
else
{
LABEL_46:
result = 0xC000000D; // 见ntstatus.h的定义。
}
return result;
}
这主要是导入/创建几个结构,修改下变量的名字和类型就可以了。
再次认识到:程序就是数据和指令的含义。
WINDBG辅助分析如下:
0: kd> dt fltmgr!_FLT_REGISTRATION
+0x000 Size : Uint2B
+0x002 Version : Uint2B
+0x004 Flags : Uint4B
+0x008 ContextRegistration : Ptr32 _FLT_CONTEXT_REGISTRATION
+0x00c OperationRegistration : Ptr32 _FLT_OPERATION_REGISTRATION
+0x010 FilterUnloadCallback : Ptr32 long
+0x014 InstanceSetupCallback : Ptr32 long
+0x018 InstanceQueryTeardownCallback : Ptr32 long
+0x01c InstanceTeardownStartCallback : Ptr32 void
+0x020 InstanceTeardownCompleteCallback : Ptr32 void
+0x024 GenerateFileNameCallback : Ptr32 long
+0x028 NormalizeNameComponentCallback : Ptr32 long
+0x02c NormalizeContextCleanupCallback : Ptr32 void
1: kd> dd gFilterHandle
ba08b558 81f84390
1: kd> dt _FLT_FILTER 81f84390
fltMgr!_FLT_FILTER
+0x000 Base : _FLT_OBJECT
+0x014 Frame : 0x81c62000 _FLTP_FRAME
+0x018 Name : _UNICODE_STRING "ahsh"
+0x020 DefaultAltitude : _UNICODE_STRING "370030"
+0x028 Flags : 0 (No matching name)
+0x02c DriverObject : 0x81d9ff38 _DRIVER_OBJECT
+0x030 InstanceList : _FLT_RESOURCE_LIST_HEAD
+0x074 VerifierExtension : 0x81f855e8 _FLT_VERIFIER_EXTENSION
+0x078 FilterUnload : 0xba08b810 long ahsh!FltUnload+0
+0x07c InstanceSetup : 0xba607790 long fltMgr!FltvInstanceSetup+0
+0x080 InstanceQueryTeardown : 0xba6077b4 long fltMgr!FltvInstanceQueryTeardown+0
+0x084 InstanceTeardownStart : (null)
+0x088 InstanceTeardownComplete : (null)
+0x08c SupportedContextsListHead : (null)
+0x090 SupportedContexts : [6] (null)
+0x0a8 PreVolumeMount : (null)
+0x0ac PostVolumeMount : (null)
+0x0b0 GenerateFileName : 0xba072800 long ahsh!GenerateFileName+0
+0x0b4 NormalizeNameComponent : 0xba072c30 long ahsh!NormalizeNameComponent+0
+0x0b8 NormalizeContextCleanup : (null)
+0x0bc Operations : 0x81f844b0 _FLT_OPERATION_REGISTRATION
+0x0c0 OldDriverUnload : (null)
+0x0c4 ActiveOpens : _FLT_MUTEX_LIST_HEAD
+0x0f0 PortList : _FLT_MUTEX_LIST_HEAD
+0x11c PortLock : _EX_PUSH_LOCK
0: kd> !drvobj \filesystem\ahsh 7
Driver object (81ff6750) is for:
\FileSystem\ahsh
Driver Extension List: (id , addr)
Device Object list:
DriverEntry: ba0c1e80 ahsh!GsDriverEntry
DriverStartIo: 00000000
DriverUnload: 00000000
AddDevice: 00000000
Dispatch routines:
[00] IRP_MJ_CREATE 804f55ce nt!IopInvalidDeviceRequest
[01] IRP_MJ_CREATE_NAMED_PIPE 804f55ce nt!IopInvalidDeviceRequest
[02] IRP_MJ_CLOSE 804f55ce nt!IopInvalidDeviceRequest
[03] IRP_MJ_READ 804f55ce nt!IopInvalidDeviceRequest
[04] IRP_MJ_WRITE 804f55ce nt!IopInvalidDeviceRequest
[05] IRP_MJ_QUERY_INFORMATION 804f55ce nt!IopInvalidDeviceRequest
[06] IRP_MJ_SET_INFORMATION 804f55ce nt!IopInvalidDeviceRequest
[07] IRP_MJ_QUERY_EA 804f55ce nt!IopInvalidDeviceRequest
[08] IRP_MJ_SET_EA 804f55ce nt!IopInvalidDeviceRequest
[09] IRP_MJ_FLUSH_BUFFERS 804f55ce nt!IopInvalidDeviceRequest
[0a] IRP_MJ_QUERY_VOLUME_INFORMATION 804f55ce nt!IopInvalidDeviceRequest
[0b] IRP_MJ_SET_VOLUME_INFORMATION 804f55ce nt!IopInvalidDeviceRequest
[0c] IRP_MJ_DIRECTORY_CONTROL 804f55ce nt!IopInvalidDeviceRequest
[0d] IRP_MJ_FILE_SYSTEM_CONTROL 804f55ce nt!IopInvalidDeviceRequest
[0e] IRP_MJ_DEVICE_CONTROL 804f55ce nt!IopInvalidDeviceRequest
[0f] IRP_MJ_INTERNAL_DEVICE_CONTROL 804f55ce nt!IopInvalidDeviceRequest
[10] IRP_MJ_SHUTDOWN 804f55ce nt!IopInvalidDeviceRequest
[11] IRP_MJ_LOCK_CONTROL 804f55ce nt!IopInvalidDeviceRequest
[12] IRP_MJ_CLEANUP 804f55ce nt!IopInvalidDeviceRequest
[13] IRP_MJ_CREATE_MAILSLOT 804f55ce nt!IopInvalidDeviceRequest
[14] IRP_MJ_QUERY_SECURITY 804f55ce nt!IopInvalidDeviceRequest
[15] IRP_MJ_SET_SECURITY 804f55ce nt!IopInvalidDeviceRequest
[16] IRP_MJ_POWER 804f55ce nt!IopInvalidDeviceRequest
[17] IRP_MJ_SYSTEM_CONTROL 804f55ce nt!IopInvalidDeviceRequest
[18] IRP_MJ_DEVICE_CHANGE 804f55ce nt!IopInvalidDeviceRequest
[19] IRP_MJ_QUERY_QUOTA 804f55ce nt!IopInvalidDeviceRequest
[1a] IRP_MJ_SET_QUOTA 804f55ce nt!IopInvalidDeviceRequest
[1b] IRP_MJ_PNP 804f55ce nt!IopInvalidDeviceRequest
0: kd> dt _FLT_FILTER 81f84390 -b
fltMgr!_FLT_FILTER
+0x000 Base : _FLT_OBJECT
+0x000 Flags : 0xb000b (No matching name)
+0x004 PointerCount : 0x200028
+0x008 RundownRef : _EX_RUNDOWN_REF
+0x000 Count : 0x200048
+0x000 Ptr : 0x00200048
+0x00c PrimaryLink : _LIST_ENTRY [ 0x10018 - 0x108 ]
+0x000 Flink : 0x00010018
+0x004 Blink : 0x00000108
+0x014 Frame : 0x00000002
+0x018 Name : _UNICODE_STRING ""
+0x000 Length : 0xb47
+0x002 MaximumLength : 0
+0x004 Buffer : (null)
+0x020 DefaultAltitude : _UNICODE_STRING ""
+0x000 Length : 0xb47
+0x002 MaximumLength : 0xc
+0x004 Buffer : (null)
+0x028 Flags : 0x79d0000 (No matching name)
+0x02c DriverObject : (null)
+0x030 InstanceList : _FLT_RESOURCE_LIST_HEAD
+0x000 rLock : _ERESOURCE
+0x000 SystemResourcesList : _LIST_ENTRY [ 0x7997a78 - 0x0 ]
+0x000 Flink : 0x07997a78
+0x004 Blink : (null)
+0x008 OwnerTable : 0x07997a78
+0x00c ActiveCount : 0n0
+0x00e Flag : 0
+0x010 SharedWaiters : 0x008d0000
+0x014 ExclusiveWaiters : (null)
+0x018 OwnerThreads :
[00] _OWNER_ENTRY
+0x000 OwnerThread : 0x79d0000
+0x004 OwnerCount : 0n0
+0x004 TableSize : 0
[01]
+0x000 OwnerThread : 0x7997a10
+0x004 OwnerCount : 0n0
+0x004 TableSize : 0
+0x028 ContentionCount : 0x7997a78
+0x02c NumberOfSharedWaiters : 0
+0x02e NumberOfExclusiveWaiters : 0
+0x030 Address : 0x008d0000
+0x030 CreatorBackTraceIndex : 0x8d0000
+0x034 SpinLock : 0
+0x038 rList : _LIST_ENTRY [ 0x7c2e8c7f - 0x67260000 ]
+0x000 Flink : 0x7c2e8c7f
+0x004 Blink : 0x67260000
+0x040 rCount : 0x7c2e8c6c
+0x074 VerifierExtension : (null)
+0x078 FilterUnload : (null)
+0x07c InstanceSetup : (null)
+0x080 InstanceQueryTeardown : 0x00000028
+0x084 InstanceTeardownStart : (null)
+0x088 InstanceTeardownComplete : 0x00000001
+0x08c SupportedContextsListHead : 0x00000018
+0x090 SupportedContexts :
[00] (null)
[01] (null)
[02] 0x0001001b
[03] 0x00000028
[04] 0x00080028
[05] 0x00000018
+0x0a8 PreVolumeMount : (null)
+0x0ac PostVolumeMount : (null)
+0x0b0 GenerateFileName : (null)
+0x0b4 NormalizeNameComponent : (null)
+0x0b8 NormalizeContextCleanup : 0x07997a78
+0x0bc Operations : (null)
+0x0c0 OldDriverUnload : 0x7c2e8c8a
+0x0c4 ActiveOpens : _FLT_MUTEX_LIST_HEAD
+0x000 mLock : _FAST_MUTEX
+0x000 Count : 0n0
+0x004 Owner : (null)
+0x008 Contention : 0
+0x00c Event : _KEVENT
+0x000 Header : _DISPATCHER_HEADER
+0x000 Type : 0 ''
+0x001 Absolute : 0 ''
+0x002 Size : 0 ''
+0x003 Inserted : 0 ''
+0x004 SignalState : 0n0
+0x008 WaitListHead : _LIST_ENTRY [ 0x68 - 0x0 ]
+0x000 Flink : 0x00000068
+0x004 Blink : (null)
+0x01c OldIrql : 1
+0x020 mList : _LIST_ENTRY [ 0x18 - 0x0 ]
+0x000 Flink : 0x00000018
+0x004 Blink : (null)
+0x028 mCount : 0
+0x028 mInvalid : 0y0
+0x0f0 PortList : _FLT_MUTEX_LIST_HEAD
+0x000 mLock : _FAST_MUTEX
+0x000 Count : 0n720907
+0x004 Owner : 0x00200028
+0x008 Contention : 0x200048
+0x00c Event : _KEVENT
+0x000 Header : _DISPATCHER_HEADER
+0x000 Type : 0x18 ''
+0x001 Absolute : 0 ''
+0x002 Size : 0x1 ''
+0x003 Inserted : 0 ''
+0x004 SignalState : 0n264
+0x008 WaitListHead : _LIST_ENTRY [ 0x2 - 0xb47 ]
+0x000 Flink : 0x00000002
+0x004 Blink : 0x00000b47
+0x01c OldIrql : 0
+0x020 mList : _LIST_ENTRY [ 0xc0b47 - 0x0 ]
+0x000 Flink : 0x000c0b47
+0x004 Blink : (null)
+0x028 mCount : 0x79d0000
+0x028 mInvalid : 0y0
+0x11c PortLock : _EX_PUSH_LOCK
+0x000 Waiting : 0y0
+0x000 Exclusive : 0y0
+0x000 Shared : 0y000000000000000000000000000000 (0)
+0x000 Value : 0
+0x000 Ptr : (null)
0: kd> dt 0x81f844b0 _FLT_OPERATION_REGISTRATION
ahsh!_FLT_OPERATION_REGISTRATION
+0x000 MajorFunction : 0x78 'x'
+0x004 Flags : 0
+0x008 PreOperation : 0x07997ae0 _FLT_PREOP_CALLBACK_STATUS +7997ae0
+0x00c PostOperation : (null)
+0x010 Reserved1 : 0x008d0000 Void
解析PspCidTable获取进程列表
#include <ntifs.h>
#include <windef.h>
/*
功能:。
句柄表分一下几类:
1.进程内的句柄表。因为内核句柄是进程所有的,但是排除进程句柄,线程句柄。USER句柄和GDI句柄是全局的。
2.PspCidTable。因为进程句柄和线程句柄是全局,这些东西放置在哪里呢?就是这里。这个变量没有导出。
3.system这个进程的句柄表,及ObpKernelHandleTable。这个变量没有导出。
4.USER对象,也应该有个句柄表。
5.GDI对象,也应该有个句柄表。
一。进程的句柄表。
进程对象的某个成员指向此值。
以后具体分析。
二。PspCidTable的分析。
\WRK-v1.2\base\ntos\ps\psinit.c文件包含如下信息:
PHANDLE_TABLE PspCidTable; // nonpaged
PspCidTable = ExCreateHandleTable (NULL);这个函数在PspInitPhase0中。
等好多的函数调用需要这个变量,如句柄的创建,销毁,映射,锁等。估计这些 句柄是进程或线程。
另一个要注意的是:
KDDEBUGGER_DATA32结构中包含ULONG PspCidTable;
KDDEBUGGER_DATA64结构中包含ULONG64 PspCidTable;
所在的文件是:\WRK-v1.2\public\sdk\inc\wdbgexts.h
kd> vertarget
Windows XP Kernel Version 2600 (Service Pack 3) MP (1 procs) Free x86 compatible
Built by: 2600.xpsp_sp3_qfe.130704-0421
Machine Name:
Kernel base = 0x804d8000 PsLoadedModuleList = 0x8055e720
Debug session time: Wed May 20 11:07:41.772 2015 (UTC + 8:00)
System Uptime: 0 days 0:38:07.921
kd> x nt!PspCidTable
805649c0 nt!PspCidTable = <no type information>
kd> dt _handle_table 805649c0
ntdll!_HANDLE_TABLE
+0x000 TableCode : 0xe1001c60 一级表。
+0x004 QuotaProcess : 0x00000002 _EPROCESS
+0x008 UniqueProcessId : (null)
+0x00c HandleTableLock : [4] _EX_PUSH_LOCK
+0x01c HandleTableList : _LIST_ENTRY [ 0x0 - 0x0 ]
+0x024 HandleContentionEvent : _EX_PUSH_LOCK
+0x028 DebugInfo : (null)
+0x02c ExtraInfoPages : 0n0
+0x030 FirstFree : 0
+0x034 LastFree : 0
+0x038 NextHandleNeedingPool : 0
+0x03c HandleCount : 0n0
+0x040 Flags : 0
+0x040 StrictFIFO : 0y0
kd> dd 0xe1001c60 注意低两位清零
e1001c60 e1005000 00000000 00000000 00000000
e1001c70 00000000 00000000 00000000 e1001c7c
e1001c80 e1001c7c 00000000 00000000 00000000
e1001c90 00000734 000006b4 00000800 0000012e
e1001ca0 00000001 00000000 0c0b060a 64546553
e1001cb0 00000101 05000000 00000012 00440002
e1001cc0 00000002 00140000 10000000 00000101
e1001cd0 05000000 00000012 00180000 a0020000
kd> dq e1005000 这里的内容就是进程对象或者线程对象。
e1005000 fffffffe`00000000 00000000`8214e661
e1005010 00000000`8214e2d9 00000000`8214dd19
e1005020 00000000`8214da99 00000000`8214d819
e1005030 00000000`8214d599 00000000`8214d319
e1005040 00000000`8214c021 00000000`8214cda1
e1005050 00000000`8214cb21 00000000`8214c8a1
e1005060 00000000`8214c621 00000000`8214c3a1
e1005070 00000000`8214b021 00000000`8214bda1
kd> dt _HANDLE_TABLE_ENTRY e1005008 等于8*1 8 == sizeof(HANDLE_TABLE_ENTRY)
nt!_HANDLE_TABLE_ENTRY
+0x000 Object : 0x8214e661 Void
+0x000 ObAttributes : 0x8214e661
+0x000 InfoTable : 0x8214e661 _HANDLE_TABLE_ENTRY_INFO
+0x000 Value : 0x8214e661
+0x004 GrantedAccess : 0
+0x004 GrantedAccessIndex : 0
+0x006 CreatorBackTraceIndex : 0
+0x004 NextFreeTableEntry : 0n0
kd> !object 0x8214e660 注意低两位清零
Object: 8214e660 Type: (8214eca0) Process
ObjectHeader: 8214e648 (old version)
HandleCount: 2 PointerCount: 57
kd> !object 8214e2d8 注意低两位清零
Object: 8214e2d8 Type: (8214ead0) Thread
ObjectHeader: 8214e2c0 (old version)
HandleCount: 0 PointerCount: 2
三。ObpKernelHandleTable的分析。
ObpKernelHandleTable = PsGetCurrentProcess()->ObjectTable = ExCreateHandleTable( NULL );
这在ObInitSystem函数里,这在\WRK-v1.2\base\ntos\ob\obinit.c
made by correy
made at 2015.05.18
参考资料:
WRK
《windows内核原理与实现》的3.4.1节。
*/
#define TAG 'tset' //test
////\WRK-v1.2\base\ntos\inc\ex.h
// Define a structure to track handle usage
//
#define HANDLE_TRACE_DB_MAX_STACKS 65536
#define HANDLE_TRACE_DB_MIN_STACKS 128
#define HANDLE_TRACE_DB_DEFAULT_STACKS 4096
#define HANDLE_TRACE_DB_STACK_SIZE 16
//\WRK-v1.2\base\ntos\inc\ex.h
typedef struct _HANDLE_TRACE_DB_ENTRY {
CLIENT_ID ClientId;
HANDLE Handle;
#define HANDLE_TRACE_DB_OPEN 1
#define HANDLE_TRACE_DB_CLOSE 2
#define HANDLE_TRACE_DB_BADREF 3
ULONG Type;
PVOID StackTrace[HANDLE_TRACE_DB_STACK_SIZE];
} HANDLE_TRACE_DB_ENTRY, *PHANDLE_TRACE_DB_ENTRY;
//\WRK-v1.2\base\ntos\inc\ex.h
typedef struct _HANDLE_TRACE_DEBUG_INFO {
//
// Reference count for this structure
//
LONG RefCount;
//
// Size of the trace table in entries
//
ULONG TableSize;
//
// this flag will clean the TraceDb.
// once the TraceDb is cleaned, this flag will be reset.
// it is needed for setting the HANDLE_TRACE_DEBUG_INFO_COMPACT_CLOSE_HANDLE
// dynamically via KD
//
#define HANDLE_TRACE_DEBUG_INFO_CLEAN_DEBUG_INFO 0x1
//
// this flag will do the following: for each close
// it will look for a matching open, remove the open
// entry and compact TraceDb
// NOTE: this should not be used for HANDLE_TRACE_DB_BADREF
// because you will not have the close trace
//
#define HANDLE_TRACE_DEBUG_INFO_COMPACT_CLOSE_HANDLE 0x2
//
// setting this flag will break into debugger when the trace list
// wraps around. This way you will have a chance to loot at old entries
// before they are deleted
//
#define HANDLE_TRACE_DEBUG_INFO_BREAK_ON_WRAP_AROUND 0x4
//
// these are status flags, do not set them explicitly
//
#define HANDLE_TRACE_DEBUG_INFO_WAS_WRAPPED_AROUND 0x40000000
#define HANDLE_TRACE_DEBUG_INFO_WAS_SOMETIME_CLEANED 0x80000000
ULONG BitMaskFlags;
FAST_MUTEX CloseCompactionLock;
//
// Current index for the stack trace DB
//
ULONG CurrentStackIndex;
//
// Save traces of those who open and close handles
//
HANDLE_TRACE_DB_ENTRY TraceDb[1];
} HANDLE_TRACE_DEBUG_INFO, *PHANDLE_TRACE_DEBUG_INFO;
// \WRK-v1.2\base\ntos\inc\ex.h
// One handle table exists per process. Unless otherwise specified, via a
// call to RemoveHandleTable, all handle tables are linked together in a
// global list. This list is used by the snapshot handle tables call.
//
typedef struct _HANDLE_TABLE {
//
// A pointer to the top level handle table tree node.
//
ULONG_PTR TableCode;
//
// The process who is being charged quota for this handle table and a
// unique process id to use in our callbacks
//
struct _EPROCESS *QuotaProcess;
HANDLE UniqueProcessId;
//
// These locks are used for table expansion and preventing the A-B-A problem
// on handle allocate.
//
#define HANDLE_TABLE_LOCKS 4
EX_PUSH_LOCK HandleTableLock[HANDLE_TABLE_LOCKS];
//
// The list of global handle tables. This field is protected by a global
// lock.
//
LIST_ENTRY HandleTableList;
//
// Define a field to block on if a handle is found locked.
//
EX_PUSH_LOCK HandleContentionEvent;
//
// Debug info. Only allocated if we are debugging handles
//
PHANDLE_TRACE_DEBUG_INFO DebugInfo;
//
// The number of pages for additional info.
// This counter is used to improve the performance
// in ExGetHandleInfo
//
LONG ExtraInfoPages;
//
// This is a singly linked list of free table entries. We don't actually
// use pointers, but have each store the index of the next free entry
// in the list. The list is managed as a lifo list. We also keep track
// of the next index that we have to allocate pool to hold.
//
ULONG FirstFree;
//
// We free handles to this list when handle debugging is on or if we see
// that a thread has this handles bucket lock held. The allows us to delay reuse
// of handles to get a better chance of catching offenders
//
ULONG LastFree;
//
// This is the next handle index needing a pool allocation. Its also used as a bound
// for good handles.
//
ULONG NextHandleNeedingPool;
//
// The number of handle table entries in use.
//
LONG HandleCount;
//
// Define a flags field
//
union {
ULONG Flags;
//
// For optimization we reuse handle values quickly. This can be a problem for
// some usages of handles and makes debugging a little harder. If this
// bit is set then we always use FIFO handle allocation.
//
BOOLEAN StrictFIFO : 1;
};
} HANDLE_TABLE, *PHANDLE_TABLE;
// \WRK-v1.2\base\ntos\inc\ex.h
typedef struct _HANDLE_TABLE_ENTRY_INFO {
//
// The following field contains the audit mask for the handle if one
// exists. The purpose of the audit mask is to record all of the accesses
// that may have been audited when the handle was opened in order to
// support "per operation" based auditing. It is computed by walking the
// SACL of the object being opened and keeping a record of all of the audit
// ACEs that apply to the open operation going on. Each set bit corresponds
// to an access that would be audited. As each operation takes place, its
// corresponding access bit is removed from this mask.
//
ACCESS_MASK AuditMask;
} HANDLE_TABLE_ENTRY_INFO, *PHANDLE_TABLE_ENTRY_INFO;
// \WRK-v1.2\base\ntos\inc\ex.h
// A handle table stores multiple handle table entries, each entry is looked
// up by its exhandle. A handle table entry has really two fields.
//
// The first field contains a pointer object and is overloaded with the three
// low order bits used by ob to denote inherited, protected, and audited
// objects. The upper bit used as a handle table entry lock. Note, this
// means that all valid object pointers must be at least longword aligned and
// have their sign bit set (i.e., be negative).
//
// The next field contains the access mask (sometimes in the form of a granted
// access index, and creator callback trace) if the entry is in use or a
// pointer in the free list if the entry is free.
//
// Two things to note:
//
// 1. An entry is free if the object pointer is null, this means that the
// following field contains the FreeTableEntryList.
//
// 2. An entry is unlocked if the object pointer is positive and locked if its
// negative. The handle package through callbacks and Map Handle to
// Pointer will lock the entry (thus making the pointer valid) outside
// routines can then read and reset the attributes field and the object
// provided they don't unlock the entry. When the callbacks return the
// entry will be unlocked and the callers or MapHandleToPointer will need
// to call UnlockHandleTableEntry explicitly.
//
typedef struct _HANDLE_TABLE_ENTRY {
//
// The pointer to the object overloaded with three ob attributes bits in
// the lower order and the high bit to denote locked or unlocked entries
//
union {
PVOID Object;
ULONG ObAttributes;
PHANDLE_TABLE_ENTRY_INFO InfoTable;
ULONG_PTR Value;
};
//
// This field either contains the granted access mask for the handle or an
// ob variation that also stores the same information. Or in the case of
// a free entry the field stores the index for the next free entry in the
// free list. This is like a FAT chain, and is used instead of pointers
// to make table duplication easier, because the entries can just be
// copied without needing to modify pointers.
//
union {
union {
ACCESS_MASK GrantedAccess;
struct {
USHORT GrantedAccessIndex;
USHORT CreatorBackTraceIndex;
};
};
LONG NextFreeTableEntry;
};
} HANDLE_TABLE_ENTRY, *PHANDLE_TABLE_ENTRY;
typedef struct _SE_PROCESS_AUDIT_INFO {
PEPROCESS Process;
PEPROCESS Parent;
} SE_PROCESS_AUDIT_INFO, *PSE_PROCESS_AUDIT_INFO;
// \WRK-v1.2\base\ntos\inc\ex.h
// A function to enumerate through the handle table of a process using a
// callback.
//
typedef BOOLEAN (*EX_ENUMERATE_HANDLE_ROUTINE)(
IN PHANDLE_TABLE_ENTRY HandleTableEntry,
IN HANDLE Handle,
IN PVOID EnumParameter
);
//EX_ENUMERATE_HANDLE_ROUTINE eehr;
// \WRK-v1.2\base\ntos\inc\ex.h
NTKERNELAPI
BOOLEAN
ExEnumHandleTable (
__in PHANDLE_TABLE HandleTable,
__in EX_ENUMERATE_HANDLE_ROUTINE EnumHandleProcedure,
__in PVOID EnumParameter,
__out_opt PHANDLE Handle
);
/*++
Routine Description:
This function enumerates all the valid handles in a handle table.
For each valid handle in the handle table, the specified eumeration function is called.
If the enumeration function returns TRUE, then the enumeration is stopped,
the current handle is returned to the caller via the optional Handle parameter,
and this function returns TRUE to indicated that the enumeration stopped at a specific handle.
Arguments:
HandleTable - Supplies a pointer to a handle table.
EnumHandleProcedure - Supplies a pointer to a function to call for each valid handle in the enumerated handle table.
EnumParameter - Supplies an uninterpreted 32-bit value that is passed to the EnumHandleProcedure each time it is called.
Handle - Supplies an optional pointer a variable that receives the Handle value that the enumeration stopped at.
Contents of the variable only valid if this function returns TRUE.
Return Value:
If the enumeration stopped at a specific handle, then a value of TRUE
is returned. Otherwise, a value of FALSE is returned.
--*/
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//因为ObGetObjectType在XP上没有。
//所以用这些结构解析。
#define OBJ_PROTECT_CLOSE 0x00000001L
#define OBJ_AUDIT_OBJECT_CLOSE 0x00000004L
#define OBJ_HANDLE_ATTRIBUTES (OBJ_PROTECT_CLOSE | OBJ_INHERIT | OBJ_AUDIT_OBJECT_CLOSE)
//
// Object Directory Structure
//
#define NUMBER_HASH_BUCKETS 37
#define OBJ_INVALID_SESSION_ID 0xFFFFFFFF
typedef struct _OBJECT_DIRECTORY {
struct _OBJECT_DIRECTORY_ENTRY *HashBuckets[ NUMBER_HASH_BUCKETS ];
EX_PUSH_LOCK Lock;
struct _DEVICE_MAP *DeviceMap;
ULONG SessionId;
} OBJECT_DIRECTORY, *POBJECT_DIRECTORY;
// end_ntosp
// begin_ntosp
typedef struct _OBJECT_HEADER_NAME_INFO {
POBJECT_DIRECTORY Directory;
UNICODE_STRING Name;
ULONG QueryReferences;
#if DBG
ULONG Reserved2;
LONG DbgDereferenceCount;
#ifdef _WIN64
ULONG64 Reserved3; // Win64 requires these structures to be 16 byte aligned.
#endif
#endif
} OBJECT_HEADER_NAME_INFO, *POBJECT_HEADER_NAME_INFO;
// end_ntosp
typedef struct _OBJECT_CREATE_INFORMATION {
ULONG Attributes;
HANDLE RootDirectory;
PVOID ParseContext;
KPROCESSOR_MODE ProbeMode;
ULONG PagedPoolCharge;
ULONG NonPagedPoolCharge;
ULONG SecurityDescriptorCharge;
PSECURITY_DESCRIPTOR SecurityDescriptor;
PSECURITY_QUALITY_OF_SERVICE SecurityQos;
SECURITY_QUALITY_OF_SERVICE SecurityQualityOfService;
} OBJECT_CREATE_INFORMATION;
typedef struct _OBJECT_DUMP_CONTROL {
PVOID Stream;
ULONG Detail;
} OB_DUMP_CONTROL, *POB_DUMP_CONTROL;
typedef VOID (*OB_DUMP_METHOD)(
IN PVOID Object,
IN POB_DUMP_CONTROL Control OPTIONAL
);
typedef enum _OB_OPEN_REASON {
ObCreateHandle,
ObOpenHandle,
ObDuplicateHandle,
ObInheritHandle,
ObMaxOpenReason
} OB_OPEN_REASON;
typedef NTSTATUS (*OB_OPEN_METHOD)(
IN OB_OPEN_REASON OpenReason,
IN PEPROCESS Process OPTIONAL,
IN PVOID Object,
IN ACCESS_MASK GrantedAccess,
IN ULONG HandleCount
);
typedef BOOLEAN (*OB_OKAYTOCLOSE_METHOD)(
IN PEPROCESS Process OPTIONAL,
IN PVOID Object,
IN HANDLE Handle,
IN KPROCESSOR_MODE PreviousMode
);
typedef VOID (*OB_CLOSE_METHOD)(
IN PEPROCESS Process OPTIONAL,
IN PVOID Object,
IN ACCESS_MASK GrantedAccess,
IN ULONG_PTR ProcessHandleCount,
IN ULONG_PTR SystemHandleCount
);
typedef VOID (*OB_DELETE_METHOD)(
IN PVOID Object
);
typedef NTSTATUS (*OB_PARSE_METHOD)(
IN PVOID ParseObject,
IN PVOID ObjectType,
IN OUT PACCESS_STATE AccessState,
IN KPROCESSOR_MODE AccessMode,
IN ULONG Attributes,
IN OUT PUNICODE_STRING CompleteName,
IN OUT PUNICODE_STRING RemainingName,
IN OUT PVOID Context OPTIONAL,
IN PSECURITY_QUALITY_OF_SERVICE SecurityQos OPTIONAL,
OUT PVOID *Object
);
typedef NTSTATUS (*OB_SECURITY_METHOD)(
IN PVOID Object,
IN SECURITY_OPERATION_CODE OperationCode,
IN PSECURITY_INFORMATION SecurityInformation,
IN OUT PSECURITY_DESCRIPTOR SecurityDescriptor,
IN OUT PULONG CapturedLength,
IN OUT PSECURITY_DESCRIPTOR *ObjectsSecurityDescriptor,
IN POOL_TYPE PoolType,
IN PGENERIC_MAPPING GenericMapping
);
typedef NTSTATUS (*OB_QUERYNAME_METHOD)(
IN PVOID Object,
IN BOOLEAN HasObjectName,
OUT POBJECT_NAME_INFORMATION ObjectNameInfo,
IN ULONG Length,
OUT PULONG ReturnLength,
IN KPROCESSOR_MODE Mode
);
//
// Object Type Structure
//
typedef struct _OBJECT_TYPE_INITIALIZER {
USHORT Length;
BOOLEAN UseDefaultObject;
BOOLEAN CaseInsensitive;
ULONG InvalidAttributes;
GENERIC_MAPPING GenericMapping;
ULONG ValidAccessMask;
BOOLEAN SecurityRequired;
BOOLEAN MaintainHandleCount;
BOOLEAN MaintainTypeList;
POOL_TYPE PoolType;
ULONG DefaultPagedPoolCharge;
ULONG DefaultNonPagedPoolCharge;
OB_DUMP_METHOD DumpProcedure;
OB_OPEN_METHOD OpenProcedure;
OB_CLOSE_METHOD CloseProcedure;
OB_DELETE_METHOD DeleteProcedure;
OB_PARSE_METHOD ParseProcedure;
OB_SECURITY_METHOD SecurityProcedure;
OB_QUERYNAME_METHOD QueryNameProcedure;
OB_OKAYTOCLOSE_METHOD OkayToCloseProcedure;
} OBJECT_TYPE_INITIALIZER, *POBJECT_TYPE_INITIALIZER;
#define OBJECT_LOCK_COUNT 4
typedef struct _OBJECT_TYPE {
ERESOURCE Mutex;
LIST_ENTRY TypeList;
UNICODE_STRING Name; // Copy from object header for convenience
PVOID DefaultObject;
ULONG Index;
ULONG TotalNumberOfObjects;
ULONG TotalNumberOfHandles;
ULONG HighWaterNumberOfObjects;
ULONG HighWaterNumberOfHandles;
OBJECT_TYPE_INITIALIZER TypeInfo;
#ifdef POOL_TAGGING
ULONG Key;
#endif //POOL_TAGGING
ERESOURCE ObjectLocks[ OBJECT_LOCK_COUNT ];
} OBJECT_TYPE, *POBJECT_TYPE;
// begin_ntosp
typedef struct _OBJECT_CREATE_INFORMATION *POBJECT_CREATE_INFORMATION;;
typedef struct _OBJECT_HEADER {
LONG_PTR PointerCount;
union {
LONG_PTR HandleCount;
PVOID NextToFree;
};
POBJECT_TYPE Type;
UCHAR NameInfoOffset;
UCHAR HandleInfoOffset;
UCHAR QuotaInfoOffset;
UCHAR Flags;
union {
POBJECT_CREATE_INFORMATION ObjectCreateInfo;
PVOID QuotaBlockCharged;
};
PSECURITY_DESCRIPTOR SecurityDescriptor;
QUAD Body;
} OBJECT_HEADER, *POBJECT_HEADER;
//\WRK-v1.2\base\ntos\inc\ob.h
// begin_ntosp
#define OBJECT_TO_OBJECT_HEADER( o ) \
CONTAINING_RECORD( (o), OBJECT_HEADER, Body )
// end_ntosp
// begin_ntosp
//\WRK-v1.2\base\ntos\inc\ob.h
FORCEINLINE
POBJECT_HEADER_NAME_INFO
OBJECT_HEADER_TO_NAME_INFO_EXISTS (
IN POBJECT_HEADER ObjectHeader
)
{
ASSERT(ObjectHeader->NameInfoOffset != 0);
return (POBJECT_HEADER_NAME_INFO)((PUCHAR)ObjectHeader -
ObjectHeader->NameInfoOffset);
}
//\WRK-v1.2\base\ntos\inc\ob.h
FORCEINLINE
POBJECT_HEADER_NAME_INFO
OBJECT_HEADER_TO_NAME_INFO (
IN POBJECT_HEADER ObjectHeader
)
{
POBJECT_HEADER_NAME_INFO nameInfo;
if (ObjectHeader->NameInfoOffset != 0) {
nameInfo = OBJECT_HEADER_TO_NAME_INFO_EXISTS(ObjectHeader);
__assume(nameInfo != NULL);
} else {
nameInfo = NULL;
}
return nameInfo;
}
// end_ntosp
NTKERNELAPI
UCHAR *
PsGetProcessImageFileName(
__in PEPROCESS Process
);
#define PS_PROCESS_FLAGS_PROCESS_EXITING 0x00000004UL // PspExitProcess entered
BOOLEAN
PsGetProcessExitProcessCalled(
__in PEPROCESS Process
);
//{
// return (BOOLEAN) ((Process->Flags&PS_PROCESS_FLAGS_PROCESS_EXITING) != 0);
//}
//NTDDKK.H 已经定义。
//NTSTATUS
//PsGetProcessExitStatus(
// __in PEPROCESS Process
// );
//{
// return Process->ExitStatus;
//}
/*
从一个对象获取对象的类型的思路。
kd> !handle 4
PROCESS 8055d0c0 SessionId: none Cid: 0000 Peb: 00000000 ParentCid: 0000
DirBase: 00336000 ObjectTable: e1003e38 HandleCount: 275.
Image: Idle
Kernel handle table at e1003e38 with 275 entries in use
0004: Object: 8214e660 GrantedAccess: 001f0fff Entry: e1004008
Object: 8214e660 Type: (8214eca0) Process
ObjectHeader: 8214e648 (old version)
HandleCount: 2 PointerCount: 59
kd> dt _object_header 8214e648 对象的地址减去对象头的大小。
nt!_OBJECT_HEADER
+0x000 PointerCount : 0n59
+0x004 HandleCount : 0n2
+0x004 NextToFree : 0x00000002 Void
+0x008 Type : 0x8214eca0 _OBJECT_TYPE
+0x00c NameInfoOffset : 0 ''
+0x00d HandleInfoOffset : 0 ''
+0x00e QuotaInfoOffset : 0 ''
+0x00f Flags : 0x22 '"'
+0x010 ObjectCreateInfo : 0x80564960 _OBJECT_CREATE_INFORMATION
+0x010 QuotaBlockCharged : 0x80564960 Void
+0x014 SecurityDescriptor : 0xe1001be4 Void
+0x018 Body : _QUAD
kd> dt 0x8214eca0 _OBJECT_TYPE
nt!_OBJECT_TYPE
+0x000 Mutex : _ERESOURCE
+0x038 TypeList : _LIST_ENTRY [ 0x8214ecd8 - 0x8214ecd8 ]
+0x040 Name : _UNICODE_STRING "Process"
+0x048 DefaultObject : (null)
+0x04c Index : 5
+0x050 TotalNumberOfObjects : 0x17
+0x054 TotalNumberOfHandles : 0x62
+0x058 HighWaterNumberOfObjects : 0x17
+0x05c HighWaterNumberOfHandles : 0x69
+0x060 TypeInfo : _OBJECT_TYPE_INITIALIZER
+0x0ac Key : 0x636f7250
+0x0b0 ObjectLocks : [4] _ERESOURCE
*/
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
DRIVER_UNLOAD Unload;
VOID Unload(__in PDRIVER_OBJECT DriverObject)
{
NTSTATUS status = STATUS_SUCCESS;
}
BOOLEAN eehr0(IN PHANDLE_TABLE_ENTRY HandleTableEntry, IN HANDLE Handle, IN PVOID EnumParameter)
/*
感觉这里是系统进程的句柄信息,不只是进程和线程的句柄。
这个获取的进程和线程的数量不全。
*/
{
NTSTATUS status = STATUS_SUCCESS;
PVOID Object;
ULONG actualLen;
PUNICODE_STRING fullUniName;
status = ObReferenceObjectByHandle( Handle, FILE_READ_ACCESS, NULL, KernelMode, &Object, NULL );
if (!NT_SUCCESS( status ))
{
/*
这里是无效的句柄,
从打印的信息看,这个句柄是一个挨着一个来的,不是一个挨着一个,而是从小到大的顺序,按照结构/表里面有的,可用/显示的。
所以这里有无效,废弃,无用的句柄。
*/
//KdPrint(("ObReferenceObjectByHandle, handle:0x%x,:0x%X, in line: %d at file:%s。\n", Handle, status, __LINE__, __FILE__));
return FALSE;
}
fullUniName = ExAllocatePoolWithTag( NonPagedPool, 1024 *sizeof(WCHAR)+2*sizeof(ULONG), TAG);//用原来的fullname,会导致在释放的时候蓝屏。双重释放。
if( !fullUniName ) {
KdPrint(("ExAllocatePoolWithTag fail, in line: %d at file:%s。\n", __LINE__, __FILE__));
ObDereferenceObject( Object );
return FALSE;
}
status = ObQueryNameString( Object, (POBJECT_NAME_INFORMATION)fullUniName, 1024, &actualLen );
if(!NT_SUCCESS(status))
{
KdPrint(("ObQueryNameString:0x%X, in line: %d at file:%s。\n", status, __LINE__, __FILE__));
ObDereferenceObject( Object );
ExFreePool( fullUniName );
return FALSE;
}
if (fullUniName->Length != 0)
{
//KdPrint(("name:%wZ\n", fullUniName)); //有名字的肯定不是进程对象或者线程对象。
}
else
{
//KdPrint(("handle:%X的名字为空\n", Handle));
}
{
//POBJECT_HEADER_NAME_INFO NameInfo;
UNICODE_STRING process = RTL_CONSTANT_STRING(L"process");
UNICODE_STRING thread = RTL_CONSTANT_STRING(L"thread");
POBJECT_HEADER ObjectHeader = 0;
POBJECT_TYPE Type = 0;
//\WRK-v1.2\base\ntos\ob\obwait.c
ObjectHeader = (POBJECT_HEADER)(((ULONG_PTR)(HandleTableEntry->Object)) & ~OBJ_HANDLE_ATTRIBUTES);
ObjectHeader = (POBJECT_HEADER)OBJECT_TO_OBJECT_HEADER(Object);
Type = ObjectHeader->Type;
//NameInfo = OBJECT_HEADER_TO_NAME_INFO(OBJECT_TO_OBJECT_HEADER(Object));
//NameInfo = OBJECT_HEADER_TO_NAME_INFO(ObjectHeader);
if (Type != NULL)
{
if (RtlCompareUnicodeString(&Type->Name, &process, TRUE) == 0 || RtlCompareUnicodeString(&Type->Name, &thread, TRUE) == 0 )
{
KdPrint(("handle:%X\n", Handle));
}
}
}
ExFreePool( fullUniName );
ObDereferenceObject( Object );
return FALSE;
}
BOOLEAN eehr(IN PHANDLE_TABLE_ENTRY HandleTableEntry, IN HANDLE Handle, IN PVOID EnumParameter)
/*
感觉这里是系统进程的句柄信息,不只是进程和线程的句柄。
*/
{
NTSTATUS status = STATUS_SUCCESS;
UNICODE_STRING process = RTL_CONSTANT_STRING(L"process");
UNICODE_STRING thread = RTL_CONSTANT_STRING(L"thread");
POBJECT_HEADER ObjectHeader = 0;
POBJECT_TYPE Type = 0;
//\WRK-v1.2\base\ntos\ob\obwait.c
//ObjectHeader = (POBJECT_HEADER)(((ULONG_PTR)(HandleTableEntry->Object)) & ~OBJ_HANDLE_ATTRIBUTES);//测试不行。
ObjectHeader = (POBJECT_HEADER)OBJECT_TO_OBJECT_HEADER(HandleTableEntry->Object);
Type = ObjectHeader->Type;
//NameInfo = OBJECT_HEADER_TO_NAME_INFO(OBJECT_TO_OBJECT_HEADER(Object));//无用,不对。
//NameInfo = OBJECT_HEADER_TO_NAME_INFO(ObjectHeader);//无用,不对。
//这里列举的信息太多了,可能有过时的。
if (Type != NULL)
{
//这里是没有IDLE进程的。
if (RtlCompareUnicodeString(&Type->Name, &process, TRUE) == 0)
{
//不用PsLookupProcessByProcessId转换了。直接用(PEPROCESS)HandleTableEntry->Object
status = PsGetProcessExitStatus((PEPROCESS)HandleTableEntry->Object);
//KdPrint(("process handle:0x%X, %s, status:%0x%x\n", Handle, PsGetProcessImageFileName((PEPROCESS)HandleTableEntry->Object), status));
KdPrint(("process handle:0x%p, status:0x%p, %s\n", Handle, status, PsGetProcessImageFileName((PEPROCESS)HandleTableEntry->Object)));
}
else if (RtlCompareUnicodeString(&Type->Name, &thread, TRUE) == 0 )
{
//KdPrint(("thread handle:%X\n", Handle));
//不用PsLookupThreadByThreadId,而直接用线程对象:HandleTableEntry->Object。
}
}
return FALSE;
}
DRIVER_INITIALIZE DriverEntry;
NTSTATUS DriverEntry( __in struct _DRIVER_OBJECT * DriverObject, __in PUNICODE_STRING RegistryPath)
{
NTSTATUS status = STATUS_SUCCESS;
//kd> dd PspCidTable L1
//805649c0 e1001c60
//这个可以通过解析符号文件传递过来。
PHANDLE_TABLE PspCidTable = (PHANDLE_TABLE)0xe1001c60;
BOOLEAN B = FALSE;
//SE_PROCESS_AUDIT_INFO ProcessAuditInfo;
KdBreakPoint();
DriverObject->DriverUnload = Unload;
B = ExEnumHandleTable(PspCidTable, eehr, NULL, NULL);
return status;//STATUS_SUCCESS
}
#include <windef.h>
/*
功能:。
句柄表分一下几类:
1.进程内的句柄表。因为内核句柄是进程所有的,但是排除进程句柄,线程句柄。USER句柄和GDI句柄是全局的。
2.PspCidTable。因为进程句柄和线程句柄是全局,这些东西放置在哪里呢?就是这里。这个变量没有导出。
3.system这个进程的句柄表,及ObpKernelHandleTable。这个变量没有导出。
4.USER对象,也应该有个句柄表。
5.GDI对象,也应该有个句柄表。
一。进程的句柄表。
进程对象的某个成员指向此值。
以后具体分析。
二。PspCidTable的分析。
\WRK-v1.2\base\ntos\ps\psinit.c文件包含如下信息:
PHANDLE_TABLE PspCidTable; // nonpaged
PspCidTable = ExCreateHandleTable (NULL);这个函数在PspInitPhase0中。
等好多的函数调用需要这个变量,如句柄的创建,销毁,映射,锁等。估计这些 句柄是进程或线程。
另一个要注意的是:
KDDEBUGGER_DATA32结构中包含ULONG PspCidTable;
KDDEBUGGER_DATA64结构中包含ULONG64 PspCidTable;
所在的文件是:\WRK-v1.2\public\sdk\inc\wdbgexts.h
kd> vertarget
Windows XP Kernel Version 2600 (Service Pack 3) MP (1 procs) Free x86 compatible
Built by: 2600.xpsp_sp3_qfe.130704-0421
Machine Name:
Kernel base = 0x804d8000 PsLoadedModuleList = 0x8055e720
Debug session time: Wed May 20 11:07:41.772 2015 (UTC + 8:00)
System Uptime: 0 days 0:38:07.921
kd> x nt!PspCidTable
805649c0 nt!PspCidTable = <no type information>
kd> dt _handle_table 805649c0
ntdll!_HANDLE_TABLE
+0x000 TableCode : 0xe1001c60 一级表。
+0x004 QuotaProcess : 0x00000002 _EPROCESS
+0x008 UniqueProcessId : (null)
+0x00c HandleTableLock : [4] _EX_PUSH_LOCK
+0x01c HandleTableList : _LIST_ENTRY [ 0x0 - 0x0 ]
+0x024 HandleContentionEvent : _EX_PUSH_LOCK
+0x028 DebugInfo : (null)
+0x02c ExtraInfoPages : 0n0
+0x030 FirstFree : 0
+0x034 LastFree : 0
+0x038 NextHandleNeedingPool : 0
+0x03c HandleCount : 0n0
+0x040 Flags : 0
+0x040 StrictFIFO : 0y0
kd> dd 0xe1001c60 注意低两位清零
e1001c60 e1005000 00000000 00000000 00000000
e1001c70 00000000 00000000 00000000 e1001c7c
e1001c80 e1001c7c 00000000 00000000 00000000
e1001c90 00000734 000006b4 00000800 0000012e
e1001ca0 00000001 00000000 0c0b060a 64546553
e1001cb0 00000101 05000000 00000012 00440002
e1001cc0 00000002 00140000 10000000 00000101
e1001cd0 05000000 00000012 00180000 a0020000
kd> dq e1005000 这里的内容就是进程对象或者线程对象。
e1005000 fffffffe`00000000 00000000`8214e661
e1005010 00000000`8214e2d9 00000000`8214dd19
e1005020 00000000`8214da99 00000000`8214d819
e1005030 00000000`8214d599 00000000`8214d319
e1005040 00000000`8214c021 00000000`8214cda1
e1005050 00000000`8214cb21 00000000`8214c8a1
e1005060 00000000`8214c621 00000000`8214c3a1
e1005070 00000000`8214b021 00000000`8214bda1
kd> dt _HANDLE_TABLE_ENTRY e1005008 等于8*1 8 == sizeof(HANDLE_TABLE_ENTRY)
nt!_HANDLE_TABLE_ENTRY
+0x000 Object : 0x8214e661 Void
+0x000 ObAttributes : 0x8214e661
+0x000 InfoTable : 0x8214e661 _HANDLE_TABLE_ENTRY_INFO
+0x000 Value : 0x8214e661
+0x004 GrantedAccess : 0
+0x004 GrantedAccessIndex : 0
+0x006 CreatorBackTraceIndex : 0
+0x004 NextFreeTableEntry : 0n0
kd> !object 0x8214e660 注意低两位清零
Object: 8214e660 Type: (8214eca0) Process
ObjectHeader: 8214e648 (old version)
HandleCount: 2 PointerCount: 57
kd> !object 8214e2d8 注意低两位清零
Object: 8214e2d8 Type: (8214ead0) Thread
ObjectHeader: 8214e2c0 (old version)
HandleCount: 0 PointerCount: 2
三。ObpKernelHandleTable的分析。
ObpKernelHandleTable = PsGetCurrentProcess()->ObjectTable = ExCreateHandleTable( NULL );
这在ObInitSystem函数里,这在\WRK-v1.2\base\ntos\ob\obinit.c
made by correy
made at 2015.05.18
参考资料:
WRK
《windows内核原理与实现》的3.4.1节。
*/
#define TAG 'tset' //test
////\WRK-v1.2\base\ntos\inc\ex.h
// Define a structure to track handle usage
//
#define HANDLE_TRACE_DB_MAX_STACKS 65536
#define HANDLE_TRACE_DB_MIN_STACKS 128
#define HANDLE_TRACE_DB_DEFAULT_STACKS 4096
#define HANDLE_TRACE_DB_STACK_SIZE 16
//\WRK-v1.2\base\ntos\inc\ex.h
typedef struct _HANDLE_TRACE_DB_ENTRY {
CLIENT_ID ClientId;
HANDLE Handle;
#define HANDLE_TRACE_DB_OPEN 1
#define HANDLE_TRACE_DB_CLOSE 2
#define HANDLE_TRACE_DB_BADREF 3
ULONG Type;
PVOID StackTrace[HANDLE_TRACE_DB_STACK_SIZE];
} HANDLE_TRACE_DB_ENTRY, *PHANDLE_TRACE_DB_ENTRY;
//\WRK-v1.2\base\ntos\inc\ex.h
typedef struct _HANDLE_TRACE_DEBUG_INFO {
//
// Reference count for this structure
//
LONG RefCount;
//
// Size of the trace table in entries
//
ULONG TableSize;
//
// this flag will clean the TraceDb.
// once the TraceDb is cleaned, this flag will be reset.
// it is needed for setting the HANDLE_TRACE_DEBUG_INFO_COMPACT_CLOSE_HANDLE
// dynamically via KD
//
#define HANDLE_TRACE_DEBUG_INFO_CLEAN_DEBUG_INFO 0x1
//
// this flag will do the following: for each close
// it will look for a matching open, remove the open
// entry and compact TraceDb
// NOTE: this should not be used for HANDLE_TRACE_DB_BADREF
// because you will not have the close trace
//
#define HANDLE_TRACE_DEBUG_INFO_COMPACT_CLOSE_HANDLE 0x2
//
// setting this flag will break into debugger when the trace list
// wraps around. This way you will have a chance to loot at old entries
// before they are deleted
//
#define HANDLE_TRACE_DEBUG_INFO_BREAK_ON_WRAP_AROUND 0x4
//
// these are status flags, do not set them explicitly
//
#define HANDLE_TRACE_DEBUG_INFO_WAS_WRAPPED_AROUND 0x40000000
#define HANDLE_TRACE_DEBUG_INFO_WAS_SOMETIME_CLEANED 0x80000000
ULONG BitMaskFlags;
FAST_MUTEX CloseCompactionLock;
//
// Current index for the stack trace DB
//
ULONG CurrentStackIndex;
//
// Save traces of those who open and close handles
//
HANDLE_TRACE_DB_ENTRY TraceDb[1];
} HANDLE_TRACE_DEBUG_INFO, *PHANDLE_TRACE_DEBUG_INFO;
// \WRK-v1.2\base\ntos\inc\ex.h
// One handle table exists per process. Unless otherwise specified, via a
// call to RemoveHandleTable, all handle tables are linked together in a
// global list. This list is used by the snapshot handle tables call.
//
typedef struct _HANDLE_TABLE {
//
// A pointer to the top level handle table tree node.
//
ULONG_PTR TableCode;
//
// The process who is being charged quota for this handle table and a
// unique process id to use in our callbacks
//
struct _EPROCESS *QuotaProcess;
HANDLE UniqueProcessId;
//
// These locks are used for table expansion and preventing the A-B-A problem
// on handle allocate.
//
#define HANDLE_TABLE_LOCKS 4
EX_PUSH_LOCK HandleTableLock[HANDLE_TABLE_LOCKS];
//
// The list of global handle tables. This field is protected by a global
// lock.
//
LIST_ENTRY HandleTableList;
//
// Define a field to block on if a handle is found locked.
//
EX_PUSH_LOCK HandleContentionEvent;
//
// Debug info. Only allocated if we are debugging handles
//
PHANDLE_TRACE_DEBUG_INFO DebugInfo;
//
// The number of pages for additional info.
// This counter is used to improve the performance
// in ExGetHandleInfo
//
LONG ExtraInfoPages;
//
// This is a singly linked list of free table entries. We don't actually
// use pointers, but have each store the index of the next free entry
// in the list. The list is managed as a lifo list. We also keep track
// of the next index that we have to allocate pool to hold.
//
ULONG FirstFree;
//
// We free handles to this list when handle debugging is on or if we see
// that a thread has this handles bucket lock held. The allows us to delay reuse
// of handles to get a better chance of catching offenders
//
ULONG LastFree;
//
// This is the next handle index needing a pool allocation. Its also used as a bound
// for good handles.
//
ULONG NextHandleNeedingPool;
//
// The number of handle table entries in use.
//
LONG HandleCount;
//
// Define a flags field
//
union {
ULONG Flags;
//
// For optimization we reuse handle values quickly. This can be a problem for
// some usages of handles and makes debugging a little harder. If this
// bit is set then we always use FIFO handle allocation.
//
BOOLEAN StrictFIFO : 1;
};
} HANDLE_TABLE, *PHANDLE_TABLE;
// \WRK-v1.2\base\ntos\inc\ex.h
typedef struct _HANDLE_TABLE_ENTRY_INFO {
//
// The following field contains the audit mask for the handle if one
// exists. The purpose of the audit mask is to record all of the accesses
// that may have been audited when the handle was opened in order to
// support "per operation" based auditing. It is computed by walking the
// SACL of the object being opened and keeping a record of all of the audit
// ACEs that apply to the open operation going on. Each set bit corresponds
// to an access that would be audited. As each operation takes place, its
// corresponding access bit is removed from this mask.
//
ACCESS_MASK AuditMask;
} HANDLE_TABLE_ENTRY_INFO, *PHANDLE_TABLE_ENTRY_INFO;
// \WRK-v1.2\base\ntos\inc\ex.h
// A handle table stores multiple handle table entries, each entry is looked
// up by its exhandle. A handle table entry has really two fields.
//
// The first field contains a pointer object and is overloaded with the three
// low order bits used by ob to denote inherited, protected, and audited
// objects. The upper bit used as a handle table entry lock. Note, this
// means that all valid object pointers must be at least longword aligned and
// have their sign bit set (i.e., be negative).
//
// The next field contains the access mask (sometimes in the form of a granted
// access index, and creator callback trace) if the entry is in use or a
// pointer in the free list if the entry is free.
//
// Two things to note:
//
// 1. An entry is free if the object pointer is null, this means that the
// following field contains the FreeTableEntryList.
//
// 2. An entry is unlocked if the object pointer is positive and locked if its
// negative. The handle package through callbacks and Map Handle to
// Pointer will lock the entry (thus making the pointer valid) outside
// routines can then read and reset the attributes field and the object
// provided they don't unlock the entry. When the callbacks return the
// entry will be unlocked and the callers or MapHandleToPointer will need
// to call UnlockHandleTableEntry explicitly.
//
typedef struct _HANDLE_TABLE_ENTRY {
//
// The pointer to the object overloaded with three ob attributes bits in
// the lower order and the high bit to denote locked or unlocked entries
//
union {
PVOID Object;
ULONG ObAttributes;
PHANDLE_TABLE_ENTRY_INFO InfoTable;
ULONG_PTR Value;
};
//
// This field either contains the granted access mask for the handle or an
// ob variation that also stores the same information. Or in the case of
// a free entry the field stores the index for the next free entry in the
// free list. This is like a FAT chain, and is used instead of pointers
// to make table duplication easier, because the entries can just be
// copied without needing to modify pointers.
//
union {
union {
ACCESS_MASK GrantedAccess;
struct {
USHORT GrantedAccessIndex;
USHORT CreatorBackTraceIndex;
};
};
LONG NextFreeTableEntry;
};
} HANDLE_TABLE_ENTRY, *PHANDLE_TABLE_ENTRY;
typedef struct _SE_PROCESS_AUDIT_INFO {
PEPROCESS Process;
PEPROCESS Parent;
} SE_PROCESS_AUDIT_INFO, *PSE_PROCESS_AUDIT_INFO;
// \WRK-v1.2\base\ntos\inc\ex.h
// A function to enumerate through the handle table of a process using a
// callback.
//
typedef BOOLEAN (*EX_ENUMERATE_HANDLE_ROUTINE)(
IN PHANDLE_TABLE_ENTRY HandleTableEntry,
IN HANDLE Handle,
IN PVOID EnumParameter
);
//EX_ENUMERATE_HANDLE_ROUTINE eehr;
// \WRK-v1.2\base\ntos\inc\ex.h
NTKERNELAPI
BOOLEAN
ExEnumHandleTable (
__in PHANDLE_TABLE HandleTable,
__in EX_ENUMERATE_HANDLE_ROUTINE EnumHandleProcedure,
__in PVOID EnumParameter,
__out_opt PHANDLE Handle
);
/*++
Routine Description:
This function enumerates all the valid handles in a handle table.
For each valid handle in the handle table, the specified eumeration function is called.
If the enumeration function returns TRUE, then the enumeration is stopped,
the current handle is returned to the caller via the optional Handle parameter,
and this function returns TRUE to indicated that the enumeration stopped at a specific handle.
Arguments:
HandleTable - Supplies a pointer to a handle table.
EnumHandleProcedure - Supplies a pointer to a function to call for each valid handle in the enumerated handle table.
EnumParameter - Supplies an uninterpreted 32-bit value that is passed to the EnumHandleProcedure each time it is called.
Handle - Supplies an optional pointer a variable that receives the Handle value that the enumeration stopped at.
Contents of the variable only valid if this function returns TRUE.
Return Value:
If the enumeration stopped at a specific handle, then a value of TRUE
is returned. Otherwise, a value of FALSE is returned.
--*/
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//因为ObGetObjectType在XP上没有。
//所以用这些结构解析。
#define OBJ_PROTECT_CLOSE 0x00000001L
#define OBJ_AUDIT_OBJECT_CLOSE 0x00000004L
#define OBJ_HANDLE_ATTRIBUTES (OBJ_PROTECT_CLOSE | OBJ_INHERIT | OBJ_AUDIT_OBJECT_CLOSE)
//
// Object Directory Structure
//
#define NUMBER_HASH_BUCKETS 37
#define OBJ_INVALID_SESSION_ID 0xFFFFFFFF
typedef struct _OBJECT_DIRECTORY {
struct _OBJECT_DIRECTORY_ENTRY *HashBuckets[ NUMBER_HASH_BUCKETS ];
EX_PUSH_LOCK Lock;
struct _DEVICE_MAP *DeviceMap;
ULONG SessionId;
} OBJECT_DIRECTORY, *POBJECT_DIRECTORY;
// end_ntosp
// begin_ntosp
typedef struct _OBJECT_HEADER_NAME_INFO {
POBJECT_DIRECTORY Directory;
UNICODE_STRING Name;
ULONG QueryReferences;
#if DBG
ULONG Reserved2;
LONG DbgDereferenceCount;
#ifdef _WIN64
ULONG64 Reserved3; // Win64 requires these structures to be 16 byte aligned.
#endif
#endif
} OBJECT_HEADER_NAME_INFO, *POBJECT_HEADER_NAME_INFO;
// end_ntosp
typedef struct _OBJECT_CREATE_INFORMATION {
ULONG Attributes;
HANDLE RootDirectory;
PVOID ParseContext;
KPROCESSOR_MODE ProbeMode;
ULONG PagedPoolCharge;
ULONG NonPagedPoolCharge;
ULONG SecurityDescriptorCharge;
PSECURITY_DESCRIPTOR SecurityDescriptor;
PSECURITY_QUALITY_OF_SERVICE SecurityQos;
SECURITY_QUALITY_OF_SERVICE SecurityQualityOfService;
} OBJECT_CREATE_INFORMATION;
typedef struct _OBJECT_DUMP_CONTROL {
PVOID Stream;
ULONG Detail;
} OB_DUMP_CONTROL, *POB_DUMP_CONTROL;
typedef VOID (*OB_DUMP_METHOD)(
IN PVOID Object,
IN POB_DUMP_CONTROL Control OPTIONAL
);
typedef enum _OB_OPEN_REASON {
ObCreateHandle,
ObOpenHandle,
ObDuplicateHandle,
ObInheritHandle,
ObMaxOpenReason
} OB_OPEN_REASON;
typedef NTSTATUS (*OB_OPEN_METHOD)(
IN OB_OPEN_REASON OpenReason,
IN PEPROCESS Process OPTIONAL,
IN PVOID Object,
IN ACCESS_MASK GrantedAccess,
IN ULONG HandleCount
);
typedef BOOLEAN (*OB_OKAYTOCLOSE_METHOD)(
IN PEPROCESS Process OPTIONAL,
IN PVOID Object,
IN HANDLE Handle,
IN KPROCESSOR_MODE PreviousMode
);
typedef VOID (*OB_CLOSE_METHOD)(
IN PEPROCESS Process OPTIONAL,
IN PVOID Object,
IN ACCESS_MASK GrantedAccess,
IN ULONG_PTR ProcessHandleCount,
IN ULONG_PTR SystemHandleCount
);
typedef VOID (*OB_DELETE_METHOD)(
IN PVOID Object
);
typedef NTSTATUS (*OB_PARSE_METHOD)(
IN PVOID ParseObject,
IN PVOID ObjectType,
IN OUT PACCESS_STATE AccessState,
IN KPROCESSOR_MODE AccessMode,
IN ULONG Attributes,
IN OUT PUNICODE_STRING CompleteName,
IN OUT PUNICODE_STRING RemainingName,
IN OUT PVOID Context OPTIONAL,
IN PSECURITY_QUALITY_OF_SERVICE SecurityQos OPTIONAL,
OUT PVOID *Object
);
typedef NTSTATUS (*OB_SECURITY_METHOD)(
IN PVOID Object,
IN SECURITY_OPERATION_CODE OperationCode,
IN PSECURITY_INFORMATION SecurityInformation,
IN OUT PSECURITY_DESCRIPTOR SecurityDescriptor,
IN OUT PULONG CapturedLength,
IN OUT PSECURITY_DESCRIPTOR *ObjectsSecurityDescriptor,
IN POOL_TYPE PoolType,
IN PGENERIC_MAPPING GenericMapping
);
typedef NTSTATUS (*OB_QUERYNAME_METHOD)(
IN PVOID Object,
IN BOOLEAN HasObjectName,
OUT POBJECT_NAME_INFORMATION ObjectNameInfo,
IN ULONG Length,
OUT PULONG ReturnLength,
IN KPROCESSOR_MODE Mode
);
//
// Object Type Structure
//
typedef struct _OBJECT_TYPE_INITIALIZER {
USHORT Length;
BOOLEAN UseDefaultObject;
BOOLEAN CaseInsensitive;
ULONG InvalidAttributes;
GENERIC_MAPPING GenericMapping;
ULONG ValidAccessMask;
BOOLEAN SecurityRequired;
BOOLEAN MaintainHandleCount;
BOOLEAN MaintainTypeList;
POOL_TYPE PoolType;
ULONG DefaultPagedPoolCharge;
ULONG DefaultNonPagedPoolCharge;
OB_DUMP_METHOD DumpProcedure;
OB_OPEN_METHOD OpenProcedure;
OB_CLOSE_METHOD CloseProcedure;
OB_DELETE_METHOD DeleteProcedure;
OB_PARSE_METHOD ParseProcedure;
OB_SECURITY_METHOD SecurityProcedure;
OB_QUERYNAME_METHOD QueryNameProcedure;
OB_OKAYTOCLOSE_METHOD OkayToCloseProcedure;
} OBJECT_TYPE_INITIALIZER, *POBJECT_TYPE_INITIALIZER;
#define OBJECT_LOCK_COUNT 4
typedef struct _OBJECT_TYPE {
ERESOURCE Mutex;
LIST_ENTRY TypeList;
UNICODE_STRING Name; // Copy from object header for convenience
PVOID DefaultObject;
ULONG Index;
ULONG TotalNumberOfObjects;
ULONG TotalNumberOfHandles;
ULONG HighWaterNumberOfObjects;
ULONG HighWaterNumberOfHandles;
OBJECT_TYPE_INITIALIZER TypeInfo;
#ifdef POOL_TAGGING
ULONG Key;
#endif //POOL_TAGGING
ERESOURCE ObjectLocks[ OBJECT_LOCK_COUNT ];
} OBJECT_TYPE, *POBJECT_TYPE;
// begin_ntosp
typedef struct _OBJECT_CREATE_INFORMATION *POBJECT_CREATE_INFORMATION;;
typedef struct _OBJECT_HEADER {
LONG_PTR PointerCount;
union {
LONG_PTR HandleCount;
PVOID NextToFree;
};
POBJECT_TYPE Type;
UCHAR NameInfoOffset;
UCHAR HandleInfoOffset;
UCHAR QuotaInfoOffset;
UCHAR Flags;
union {
POBJECT_CREATE_INFORMATION ObjectCreateInfo;
PVOID QuotaBlockCharged;
};
PSECURITY_DESCRIPTOR SecurityDescriptor;
QUAD Body;
} OBJECT_HEADER, *POBJECT_HEADER;
//\WRK-v1.2\base\ntos\inc\ob.h
// begin_ntosp
#define OBJECT_TO_OBJECT_HEADER( o ) \
CONTAINING_RECORD( (o), OBJECT_HEADER, Body )
// end_ntosp
// begin_ntosp
//\WRK-v1.2\base\ntos\inc\ob.h
FORCEINLINE
POBJECT_HEADER_NAME_INFO
OBJECT_HEADER_TO_NAME_INFO_EXISTS (
IN POBJECT_HEADER ObjectHeader
)
{
ASSERT(ObjectHeader->NameInfoOffset != 0);
return (POBJECT_HEADER_NAME_INFO)((PUCHAR)ObjectHeader -
ObjectHeader->NameInfoOffset);
}
//\WRK-v1.2\base\ntos\inc\ob.h
FORCEINLINE
POBJECT_HEADER_NAME_INFO
OBJECT_HEADER_TO_NAME_INFO (
IN POBJECT_HEADER ObjectHeader
)
{
POBJECT_HEADER_NAME_INFO nameInfo;
if (ObjectHeader->NameInfoOffset != 0) {
nameInfo = OBJECT_HEADER_TO_NAME_INFO_EXISTS(ObjectHeader);
__assume(nameInfo != NULL);
} else {
nameInfo = NULL;
}
return nameInfo;
}
// end_ntosp
NTKERNELAPI
UCHAR *
PsGetProcessImageFileName(
__in PEPROCESS Process
);
#define PS_PROCESS_FLAGS_PROCESS_EXITING 0x00000004UL // PspExitProcess entered
BOOLEAN
PsGetProcessExitProcessCalled(
__in PEPROCESS Process
);
//{
// return (BOOLEAN) ((Process->Flags&PS_PROCESS_FLAGS_PROCESS_EXITING) != 0);
//}
//NTDDKK.H 已经定义。
//NTSTATUS
//PsGetProcessExitStatus(
// __in PEPROCESS Process
// );
//{
// return Process->ExitStatus;
//}
/*
从一个对象获取对象的类型的思路。
kd> !handle 4
PROCESS 8055d0c0 SessionId: none Cid: 0000 Peb: 00000000 ParentCid: 0000
DirBase: 00336000 ObjectTable: e1003e38 HandleCount: 275.
Image: Idle
Kernel handle table at e1003e38 with 275 entries in use
0004: Object: 8214e660 GrantedAccess: 001f0fff Entry: e1004008
Object: 8214e660 Type: (8214eca0) Process
ObjectHeader: 8214e648 (old version)
HandleCount: 2 PointerCount: 59
kd> dt _object_header 8214e648 对象的地址减去对象头的大小。
nt!_OBJECT_HEADER
+0x000 PointerCount : 0n59
+0x004 HandleCount : 0n2
+0x004 NextToFree : 0x00000002 Void
+0x008 Type : 0x8214eca0 _OBJECT_TYPE
+0x00c NameInfoOffset : 0 ''
+0x00d HandleInfoOffset : 0 ''
+0x00e QuotaInfoOffset : 0 ''
+0x00f Flags : 0x22 '"'
+0x010 ObjectCreateInfo : 0x80564960 _OBJECT_CREATE_INFORMATION
+0x010 QuotaBlockCharged : 0x80564960 Void
+0x014 SecurityDescriptor : 0xe1001be4 Void
+0x018 Body : _QUAD
kd> dt 0x8214eca0 _OBJECT_TYPE
nt!_OBJECT_TYPE
+0x000 Mutex : _ERESOURCE
+0x038 TypeList : _LIST_ENTRY [ 0x8214ecd8 - 0x8214ecd8 ]
+0x040 Name : _UNICODE_STRING "Process"
+0x048 DefaultObject : (null)
+0x04c Index : 5
+0x050 TotalNumberOfObjects : 0x17
+0x054 TotalNumberOfHandles : 0x62
+0x058 HighWaterNumberOfObjects : 0x17
+0x05c HighWaterNumberOfHandles : 0x69
+0x060 TypeInfo : _OBJECT_TYPE_INITIALIZER
+0x0ac Key : 0x636f7250
+0x0b0 ObjectLocks : [4] _ERESOURCE
*/
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
DRIVER_UNLOAD Unload;
VOID Unload(__in PDRIVER_OBJECT DriverObject)
{
NTSTATUS status = STATUS_SUCCESS;
}
BOOLEAN eehr0(IN PHANDLE_TABLE_ENTRY HandleTableEntry, IN HANDLE Handle, IN PVOID EnumParameter)
/*
感觉这里是系统进程的句柄信息,不只是进程和线程的句柄。
这个获取的进程和线程的数量不全。
*/
{
NTSTATUS status = STATUS_SUCCESS;
PVOID Object;
ULONG actualLen;
PUNICODE_STRING fullUniName;
status = ObReferenceObjectByHandle( Handle, FILE_READ_ACCESS, NULL, KernelMode, &Object, NULL );
if (!NT_SUCCESS( status ))
{
/*
这里是无效的句柄,
从打印的信息看,这个句柄是一个挨着一个来的,不是一个挨着一个,而是从小到大的顺序,按照结构/表里面有的,可用/显示的。
所以这里有无效,废弃,无用的句柄。
*/
//KdPrint(("ObReferenceObjectByHandle, handle:0x%x,:0x%X, in line: %d at file:%s。\n", Handle, status, __LINE__, __FILE__));
return FALSE;
}
fullUniName = ExAllocatePoolWithTag( NonPagedPool, 1024 *sizeof(WCHAR)+2*sizeof(ULONG), TAG);//用原来的fullname,会导致在释放的时候蓝屏。双重释放。
if( !fullUniName ) {
KdPrint(("ExAllocatePoolWithTag fail, in line: %d at file:%s。\n", __LINE__, __FILE__));
ObDereferenceObject( Object );
return FALSE;
}
status = ObQueryNameString( Object, (POBJECT_NAME_INFORMATION)fullUniName, 1024, &actualLen );
if(!NT_SUCCESS(status))
{
KdPrint(("ObQueryNameString:0x%X, in line: %d at file:%s。\n", status, __LINE__, __FILE__));
ObDereferenceObject( Object );
ExFreePool( fullUniName );
return FALSE;
}
if (fullUniName->Length != 0)
{
//KdPrint(("name:%wZ\n", fullUniName)); //有名字的肯定不是进程对象或者线程对象。
}
else
{
//KdPrint(("handle:%X的名字为空\n", Handle));
}
{
//POBJECT_HEADER_NAME_INFO NameInfo;
UNICODE_STRING process = RTL_CONSTANT_STRING(L"process");
UNICODE_STRING thread = RTL_CONSTANT_STRING(L"thread");
POBJECT_HEADER ObjectHeader = 0;
POBJECT_TYPE Type = 0;
//\WRK-v1.2\base\ntos\ob\obwait.c
ObjectHeader = (POBJECT_HEADER)(((ULONG_PTR)(HandleTableEntry->Object)) & ~OBJ_HANDLE_ATTRIBUTES);
ObjectHeader = (POBJECT_HEADER)OBJECT_TO_OBJECT_HEADER(Object);
Type = ObjectHeader->Type;
//NameInfo = OBJECT_HEADER_TO_NAME_INFO(OBJECT_TO_OBJECT_HEADER(Object));
//NameInfo = OBJECT_HEADER_TO_NAME_INFO(ObjectHeader);
if (Type != NULL)
{
if (RtlCompareUnicodeString(&Type->Name, &process, TRUE) == 0 || RtlCompareUnicodeString(&Type->Name, &thread, TRUE) == 0 )
{
KdPrint(("handle:%X\n", Handle));
}
}
}
ExFreePool( fullUniName );
ObDereferenceObject( Object );
return FALSE;
}
BOOLEAN eehr(IN PHANDLE_TABLE_ENTRY HandleTableEntry, IN HANDLE Handle, IN PVOID EnumParameter)
/*
感觉这里是系统进程的句柄信息,不只是进程和线程的句柄。
*/
{
NTSTATUS status = STATUS_SUCCESS;
UNICODE_STRING process = RTL_CONSTANT_STRING(L"process");
UNICODE_STRING thread = RTL_CONSTANT_STRING(L"thread");
POBJECT_HEADER ObjectHeader = 0;
POBJECT_TYPE Type = 0;
//\WRK-v1.2\base\ntos\ob\obwait.c
//ObjectHeader = (POBJECT_HEADER)(((ULONG_PTR)(HandleTableEntry->Object)) & ~OBJ_HANDLE_ATTRIBUTES);//测试不行。
ObjectHeader = (POBJECT_HEADER)OBJECT_TO_OBJECT_HEADER(HandleTableEntry->Object);
Type = ObjectHeader->Type;
//NameInfo = OBJECT_HEADER_TO_NAME_INFO(OBJECT_TO_OBJECT_HEADER(Object));//无用,不对。
//NameInfo = OBJECT_HEADER_TO_NAME_INFO(ObjectHeader);//无用,不对。
//这里列举的信息太多了,可能有过时的。
if (Type != NULL)
{
//这里是没有IDLE进程的。
if (RtlCompareUnicodeString(&Type->Name, &process, TRUE) == 0)
{
//不用PsLookupProcessByProcessId转换了。直接用(PEPROCESS)HandleTableEntry->Object
status = PsGetProcessExitStatus((PEPROCESS)HandleTableEntry->Object);
//KdPrint(("process handle:0x%X, %s, status:%0x%x\n", Handle, PsGetProcessImageFileName((PEPROCESS)HandleTableEntry->Object), status));
KdPrint(("process handle:0x%p, status:0x%p, %s\n", Handle, status, PsGetProcessImageFileName((PEPROCESS)HandleTableEntry->Object)));
}
else if (RtlCompareUnicodeString(&Type->Name, &thread, TRUE) == 0 )
{
//KdPrint(("thread handle:%X\n", Handle));
//不用PsLookupThreadByThreadId,而直接用线程对象:HandleTableEntry->Object。
}
}
return FALSE;
}
DRIVER_INITIALIZE DriverEntry;
NTSTATUS DriverEntry( __in struct _DRIVER_OBJECT * DriverObject, __in PUNICODE_STRING RegistryPath)
{
NTSTATUS status = STATUS_SUCCESS;
//kd> dd PspCidTable L1
//805649c0 e1001c60
//这个可以通过解析符号文件传递过来。
PHANDLE_TABLE PspCidTable = (PHANDLE_TABLE)0xe1001c60;
BOOLEAN B = FALSE;
//SE_PROCESS_AUDIT_INFO ProcessAuditInfo;
KdBreakPoint();
DriverObject->DriverUnload = Unload;
B = ExEnumHandleTable(PspCidTable, eehr, NULL, NULL);
return status;//STATUS_SUCCESS
}
订阅:
博文 (Atom)