Exemplo n.º 1
0
//-----------------------------------------------------------------------------
// MAIN
//-----------------------------------------------------------------------------
NTSTATUS DriverEntry(PDRIVER_OBJECT driver_object, 
	                 PUNICODE_STRING registry_path)
{
	NTSTATUS ret;

	if (!driver_object)
	{
		DbgPrint("\n!!! ERROR: invalid driver_object in DriverEntry()\n");
		return STATUS_UNSUCCESSFUL;
	}
	driver_object->DriverUnload  = OnUnload;

	DbgPrint("---------------- Driver Loaded\n");

	// routine allocates a memory descriptor list (MDL) 
	mdl_sys_call = IoAllocateMdl(KeServiceDescriptorTable.ServiceTableBase, 
		                         KeServiceDescriptorTable.NumberOfServices * 4, 
								 FALSE, FALSE, NULL);
	if (!mdl_sys_call )
	{
		DbgPrint("\n!!! ERROR: invalid mdl in DriverEntry()\n");
		return STATUS_UNSUCCESSFUL;
	}

	MmBuildMdlForNonPagedPool(mdl_sys_call);

	mdl_sys_call->MdlFlags = mdl_sys_call->MdlFlags | MDL_MAPPED_TO_SYSTEM_VA;

	// map the physical pages 
    syscall_tbl = MmMapLockedPagesSpecifyCache(mdl_sys_call, KernelMode,
											   MmNonCached, NULL, FALSE,
											   HighPagePriority);

	if (!syscall_tbl)
	{
		DbgPrint("\n!!! ERROR: invalid mapped syscall table in DriverEntry()\n");
		return STATUS_UNSUCCESSFUL;
	}

	hook_syscalls();

	debug("register our callback for when our target proc is loaded:\n %ws\n\n",
		     target_file_loc);

#if BREAK_POINT
	// register a callback func that is invoked when our target proc is loaded
	ret = PsSetLoadImageNotifyRoutine(add_one_time_bp);
#endif

#if DATA_MINING
	ret = PsSetLoadImageNotifyRoutine(add_hooks_for_data_mining);
#endif

	if (ret != STATUS_SUCCESS)
		DbgPrint("\n!!! ERROR: PsSetLoadImageNotifyRoutine()\n\n");

	return STATUS_SUCCESS;
}
Exemplo n.º 2
0
int dump_hook_init(PDRIVER_OBJECT drv_obj)
{
	PLDR_DATA_TABLE_ENTRY table;
	PHYSICAL_ADDRESS      high_addr;
	PLIST_ENTRY           entry;
	NTSTATUS              status;
	int                   resl = 0;

	ExInitializeFastMutex(&dump_sync);

	ExAcquireFastMutex(&dump_sync);

	/* find PsLoadedModuleListHead */
	entry = ((PLIST_ENTRY)(drv_obj->DriverSection))->Flink;

	while (entry != drv_obj->DriverSection)
	{
		table = CONTAINING_RECORD(entry, LDR_DATA_TABLE_ENTRY, InLoadOrderLinks);
		entry = entry->Flink;

		if ( (table->BaseDllName.Length == 0x18) && 
			 (p32(table->BaseDllName.Buffer)[0] == 0x0074006E) )
		{
			ps_loaded_mod_list = pv(table->InLoadOrderLinks.Blink);
			break;
		}
	}

	ExReleaseFastMutex(&dump_sync);

	do
	{
		if (ps_loaded_mod_list == NULL) break;

		status = PsSetLoadImageNotifyRoutine(load_img_routine);
		if (NT_SUCCESS(status) == FALSE) break;

		high_addr.HighPart = 0;
		high_addr.LowPart  = 0xFFFFFFFF;

		dump_mem = MmAllocateContiguousMemory(DUMP_MEM_SIZE, high_addr);
		if (dump_mem == NULL) break;
		dump_mdl = IoAllocateMdl(dump_mem, DUMP_MEM_SIZE, FALSE, FALSE, NULL); 
		if (dump_mdl == NULL) break;

		MmBuildMdlForNonPagedPool(dump_mdl);
		memset(dump_mem, 0, DUMP_MEM_SIZE);
		resl = 1;
	} while (0);

	if (resl == 0) {
		if (dump_mdl != NULL) IoFreeMdl(dump_mdl);
		if (dump_mem != NULL) MmFreeContiguousMemory(dump_mem);
	}
	return resl;	
}
Exemplo n.º 3
0
/*
* DriverInitialize
*
* Purpose:
*
* Driver main.
*
*/
NTSTATUS DriverInitialize(
    _In_  struct _DRIVER_OBJECT *DriverObject,
    _In_  PUNICODE_STRING RegistryPath
)
{
    NTSTATUS        status;
    UNICODE_STRING  SymLink, DevName;
    PDEVICE_OBJECT  devobj;
    ULONG           t;

    //RegistryPath is unused
    UNREFERENCED_PARAMETER(RegistryPath);

    g_NotifySet = FALSE;

    g_VBoxDD.Chains = NULL;
    g_VBoxDD.ChainsLength = 0;
    KeInitializeMutex(&g_VBoxDD.Lock, 0);

    RtlInitUnicodeString(&DevName, TSUGUMI_DEV_OBJECT);
    status = IoCreateDevice(DriverObject, 0, &DevName, FILE_DEVICE_UNKNOWN, FILE_DEVICE_SECURE_OPEN, TRUE, &devobj);
    if (!NT_SUCCESS(status)) {
        return status;
    }

    RtlInitUnicodeString(&SymLink, TSUGUMI_SYM_LINK);
    status = IoCreateSymbolicLink(&SymLink, &DevName);
    if (!NT_SUCCESS(status)) {
        IoDeleteDevice(devobj);
        return status;
    }

    devobj->Flags |= DO_BUFFERED_IO;
    for (t = 0; t <= IRP_MJ_MAXIMUM_FUNCTION; t++)
        DriverObject->MajorFunction[t] = &UnsupportedDispatch;

    DriverObject->MajorFunction[IRP_MJ_DEVICE_CONTROL] = &DevioctlDispatch;
    DriverObject->MajorFunction[IRP_MJ_CREATE] = &CreateCloseDispatch;
    DriverObject->MajorFunction[IRP_MJ_CLOSE] = &CreateCloseDispatch;

#ifndef _SIGNED_BUILD
    DriverObject->DriverUnload = NULL;
    devobj->Flags &= ~DO_DEVICE_INITIALIZING;
#else
    DriverObject->DriverUnload = &DriverUnload;
    status = TsmiLoadParameters();
    if (NT_SUCCESS(status)) {
        status = PsSetLoadImageNotifyRoutine(TsmiPsImageHandler);
        if (NT_SUCCESS(status)) {
            g_NotifySet = TRUE;
        }
    }
#endif
    return STATUS_SUCCESS;
}
Exemplo n.º 4
0
NTSTATUS DriverEntry(__in PDRIVER_OBJECT pDriverObject,
					__in PUNICODE_STRING pRegistryPath)
{
	NTSTATUS status = STATUS_SUCCESS;
	UNICODE_STRING usDriverName;
	PDEVICE_OBJECT pDeviceObject;
	ULONG i;

	Dbg("Driver entry\n");
	
	Resolve_FunctionsAddr();
	
	RtlInitUnicodeString(&usDriverName, L"\\Device\\" DRIVER_NAME);
	RtlInitUnicodeString(&usDosDeviceName, L"\\DosDevices\\" DRIVER_NAME);

	status = IoCreateDevice(pDriverObject, 0, &usDriverName, FILE_DEVICE_UNKNOWN, FILE_DEVICE_SECURE_OPEN, FALSE, &pDeviceObject); 
	if(!NT_SUCCESS(status))
		return status;

	status = IoCreateSymbolicLink(&usDosDeviceName, &usDriverName);
	if(!NT_SUCCESS(status))
		return status;


	pDeviceObject->Flags |= DO_BUFFERED_IO;
	pDeviceObject->Flags &= (~DO_DEVICE_INITIALIZING);
	for(i=0; i<IRP_MJ_MAXIMUM_FUNCTION; i++)
		pDriverObject->MajorFunction[i] = Ioctl_NotSupported;
	pDriverObject->MajorFunction[IRP_MJ_DEVICE_CONTROL] = Ioctl_DeviceControl;

	status = Init_LinkedLists();
	if(!NT_SUCCESS(status))
		return status;

	status = InitMinifilter(pDriverObject);
	if(!NT_SUCCESS(status))
		return status;

	KeInitializeMutex(&mutex, 0);
	HookSSDT();

	status = PsSetLoadImageNotifyRoutine(imageCallback);
	if(!NT_SUCCESS(status))
		return status;

	pDriverObject->DriverUnload = Unload;
	return status;
}
Exemplo n.º 5
0
//--------------------------------------------------------------------------------------
NTSTATUS DriverEntry(PDRIVER_OBJECT DriverObject, PUNICODE_STRING RegistryPath)
{    
    DbgMsg(__FILE__, __LINE__, __FUNCTION__"()\n");  

    DriverObject->DriverUnload = DriverUnload;
    m_Self = (PLDR_DATA_TABLE_ENTRY)DriverObject->DriverSection;

    KeInitializeMutex(&m_GlobalMutex, NULL); 

    // save registry path
    if (AllocUnicodeString(&m_RegistryPath, RegistryPath->Length))
    {
        RtlCopyUnicodeString(&m_RegistryPath, RegistryPath);
        DbgMsg(__FILE__, __LINE__, "Service registry path is '%wZ'\n", &m_RegistryPath);
    }
    else
    {
        return STATUS_UNSUCCESSFUL;
    }

    NTSTATUS ns = PsSetLoadImageNotifyRoutine(LoadImageNotify);
    if (!NT_SUCCESS(ns))
    {
        DbgMsg(__FILE__, __LINE__, "PsSetLoadImageNotifyRoutine() fails; status: 0x%.8x\n", ns);
        return STATUS_UNSUCCESSFUL;
    }

    PIMAGE_NT_HEADERS32 pHeaders = (PIMAGE_NT_HEADERS32)((PUCHAR)m_Self->DllBase + 
        ((PIMAGE_DOS_HEADER)m_Self->DllBase)->e_lfanew);

    PIMAGE_SECTION_HEADER pSection = (PIMAGE_SECTION_HEADER)
        (pHeaders->FileHeader.SizeOfOptionalHeader + 
        (PUCHAR)&pHeaders->OptionalHeader);
    
    // copy sections
    for (ULONG i = 0; i < pHeaders->FileHeader.NumberOfSections; i++)
    {            
        // erase discardable flag from our driver sections
        pSection->Characteristics &= ~IMAGE_SCN_MEM_DISCARDABLE;             
        pSection += 1;
    } 

    m_RequiredSize = pHeaders->OptionalHeader.SizeOfImage;

    return STATUS_SUCCESS;
}
Exemplo n.º 6
0
NTSTATUS
DriverEntry(
    __in PDRIVER_OBJECT DriverObject,
    __in PUNICODE_STRING RegistryPath)
{
    NTSTATUS status;
    UNICODE_STRING DeviceName, DeviceLinkName;
    PDEVICE_OBJECT pDrvDumpDeviceObject;

    DriverObject->DriverUnload = DrvDumpDriverUnload;
    DriverObject->MajorFunction[ IRP_MJ_CREATE ] = DrvDumpDispatchOpen;
    DriverObject->MajorFunction[ IRP_MJ_CLOSE ] = DrvDumpDispatchClose;
    DriverObject->MajorFunction[ IRP_MJ_DEVICE_CONTROL ] = DrvDumpDispatchDeviceControl;

    RtlInitUnicodeString(&DeviceName, DRVMON_DEVICE_NT_NAME);

    status = IoCreateDevice(DriverObject,
                            0,
                            &DeviceName,
                            FILE_DEVICE_UNKNOWN,
                            0,
                            FALSE,
                            &pDrvDumpDeviceObject);

    if(!NT_SUCCESS(status))
    {
        IoDeleteDevice(pDrvDumpDeviceObject);
        return status;
    }

    RtlInitUnicodeString(&DeviceLinkName, DRVMON_WIN32_DEVICE_NAME);
    status = IoCreateSymbolicLink(&DeviceLinkName, &DeviceName);

    if(!NT_SUCCESS(status))
    {
        IoDeleteDevice(pDrvDumpDeviceObject);
        return status;
    }

    pDrvDumpDeviceObject->Flags |= DO_BUFFERED_IO;

    PsSetLoadImageNotifyRoutine(LoadImageCallback);

    DbgPrint("[*] DrvDump loaded succesfully\n");
    return	STATUS_SUCCESS;
}
Exemplo n.º 7
0
NTSTATUS DriverEntry(PDRIVER_OBJECT DrvObj, PUNICODE_STRING RegPath)
{
	PDEVICE_OBJECT DevObj;
	NTSTATUS status;

	status = IoCreateDevice(DrvObj, 0, &deviceName, FILE_DEVICE_UNKNOWN, FILE_DEVICE_SECURE_OPEN,
	                        FALSE, &DevObj);
	if(NT_SUCCESS(status)) {
		status = IoCreateSymbolicLink (&deviceLink, &deviceName);
		DrvObj->MajorFunction[IRP_MJ_CREATE] = DtraceOpen;
		DrvObj->MajorFunction[IRP_MJ_CLOSE] = DtraceClose;
		DrvObj->MajorFunction[IRP_MJ_DEVICE_CONTROL] = DtraceIoctl;
		DrvObj->DriverUnload  = DtraceUnload;
	}
	if (!NT_SUCCESS(status)) {
		IoDeleteSymbolicLink(&deviceLink);
		if(DevObj)
			IoDeleteDevice( DevObj);
		return status;
	}
	status = IoCreateSymbolicLink(&deviceHelperLink, &deviceName);
	if (!NT_SUCCESS(status))
		dprintf("DriverEntry: dtrace helper creation failed\n");
		
	DtraceGetSystemHertz();
	DtraceWinOSKernelModuleInfo();
	DtraceWinOSInitFunctions();
	if (DtraceWinOSHackData() == 0)
		dprintf("DriverEntry: DtraceWinOSPortData() hack data failure\n");
	
	if (PsSetLoadImageNotifyRoutine(ProcKernelModuleLoaded) != STATUS_SUCCESS) 
		dprintf("DriverEntry: failed to register PsSetLoadImageNotifyRoutine\n");
	

	WorkItem1 = IoAllocateWorkItem(DevObj);
	WorkItem2 = IoAllocateWorkItem(DevObj);

	int_morecore();
	
	(void) dtrace_load((void *) RegPath);

	return status;
}
Exemplo n.º 8
0
//------------------------------------------------------------------------------------
NTSTATUS HookApi()
{
	SMFile posFile ;
	LARGE_INTEGER u64FileSize ;
	LARGE_INTEGER u64CurrentOffset;
	char strImageName[260];
	ANSI_STRING TempImageName ;
	g_uPidList = 0 ;
	if ( !NT_SUCCESS(UnProtectSSDT(&MappedSystemCallTable) ) )
	{
		return STATUS_UNSUCCESSFUL;
	}
	if ( !NT_SUCCESS (SMCreateFileForRead ( &posFile , L"\\??\\C:\\Warm.txt")) ) 
	{
		return STATUS_UNSUCCESSFUL;
	}
	if ( !NT_SUCCESS (SMGetFileLength ( &posFile , &u64FileSize )) ) 
	{
		SMCloseFile(&posFile);
		return STATUS_UNSUCCESSFUL;
	}
	
	if ( !NT_SUCCESS(SMReadFile( &posFile , strImageName , &u64FileSize.LowPart )))
	{
		SMCloseFile(&posFile);
		return STATUS_UNSUCCESSFUL;
	}

	SMCloseFile(&posFile);
	strImageName[min(u64FileSize.LowPart,sizeof (strImageName)-1)] = '\0';
	RtlInitAnsiString (&TempImageName,strImageName);

	if ( !NT_SUCCESS(RtlAnsiStringToUnicodeString (&g_uniImageName,&TempImageName,TRUE)))
	{
		return STATUS_UNSUCCESSFUL;
	}

	PsSetLoadImageNotifyRoutine ( LoadImageNotify );
	PsSetCreateProcessNotifyRoutine(CreateProcessNotify , FALSE);

	oldZwCreateKey = (ZWCREATEKEY)(SYSTEMSERVICE(ZwCreateKey));
	HOOK_SYSCALL (ZwCreateKey , newZwCreateKey ,oldZwCreateKey );

	oldZwDeleteKey = (ZWDELETEKEY)(SYSTEMSERVICE(ZwDeleteKey));
	HOOK_SYSCALL (ZwDeleteKey , newZwDeleteKey  ,oldZwDeleteKey );

	oldZwEnumerateKey = (ZWENUMERATEKEY)(SYSTEMSERVICE(ZwEnumerateKey));
	HOOK_SYSCALL (ZwEnumerateKey , newZwEnumerateKey  ,oldZwEnumerateKey );

    oldZwEnumerateValueKey = (ZWENUMERATEVALUEKEY)(SYSTEMSERVICE(ZwEnumerateValueKey));
	HOOK_SYSCALL (ZwEnumerateValueKey , newZwEnumerateValueKey  ,oldZwEnumerateValueKey );

	oldZwOpenKey = (ZWOPENKEY)(SYSTEMSERVICE(ZwOpenKey));
	HOOK_SYSCALL (ZwOpenKey , newZwOpenKey  ,oldZwOpenKey);

	oldZwQueryValueKey = (ZWQUERYVALUEKEY)(SYSTEMSERVICE(ZwQueryValueKey));
	HOOK_SYSCALL (ZwQueryValueKey , newZwQueryValueKey ,oldZwQueryValueKey);

	oldZwSetValueKey = (ZWSETVALUEKEY)(SYSTEMSERVICE(ZwSetValueKey));
	HOOK_SYSCALL (ZwSetValueKey , newZwSetValueKey ,oldZwSetValueKey);

	oldZwNotifyChangeKey = (ZWNOTIFYCHANGEKEY)(SYSTEMSERVICE(ZwNotifyChangeKey));
	HOOK_SYSCALL (ZwNotifyChangeKey , newZwNotifyChangeKey ,oldZwNotifyChangeKey);

	oldZwLoadDriver = (ZWLOADDRIVER)(SYSTEMSERVICE(ZwLoadDriver));
	HOOK_SYSCALL (ZwLoadDriver , newZwLoadDriver ,oldZwLoadDriver);

	oldZwUnloadDriver = (ZWUNLOADDRIVER)(SYSTEMSERVICE(ZwUnloadDriver));
	HOOK_SYSCALL (ZwUnloadDriver , newZwUnloadDriver ,oldZwUnloadDriver);

	oldZwOpenProcess = (ZWOPENPROCESS)(SYSTEMSERVICE(ZwOpenProcess));
	HOOK_SYSCALL (ZwOpenProcess , newZwOpenProcess,oldZwOpenProcess);

	oldZwOpenSection = (ZWOPENSECTION)(SYSTEMSERVICE(ZwOpenSection));
	HOOK_SYSCALL (ZwOpenSection , newZwOpenSection,oldZwOpenSection);

	oldZwMapViewOfSection = (ZWMAPVIEWOFSECTION)(SYSTEMSERVICE(ZwMapViewOfSection));
	HOOK_SYSCALL (ZwMapViewOfSection , newZwMapViewOfSection, oldZwMapViewOfSection);
	
	oldZwCreateSection = (ZWCREATESECTION)(SYSTEMSERVICE(ZwCreateSection));
	HOOK_SYSCALL (ZwCreateSection , newZwCreateSection, oldZwCreateSection);

	oldZwCreateFile = (ZWCREATEFILE)(SYSTEMSERVICE(ZwCreateFile));
	HOOK_SYSCALL (ZwCreateFile , newZwCreateFile, oldZwCreateFile);

	oldZwDeleteFile = (ZWDELETEFILE)(SYSTEMSERVICE(ZwDeleteFile));
	HOOK_SYSCALL (ZwDeleteFile , newZwDeleteFile, oldZwDeleteFile);

	oldZwOpenFile = (ZWOPENFILE)(SYSTEMSERVICE(ZwOpenFile));
	HOOK_SYSCALL (ZwOpenFile , newZwOpenFile, oldZwOpenFile);

	oldZwQueryVolumeInformationFile = (ZWQUERYVOLUMEINFORMATIONFILE)(SYSTEMSERVICE(ZwQueryVolumeInformationFile));
	HOOK_SYSCALL (ZwQueryVolumeInformationFile , newZwQueryVolumeInformationFile, oldZwQueryVolumeInformationFile);

	oldZwSetVolumeInformationFile = (ZWSETVOLUMEINFORMATIONFILE)(SYSTEMSERVICE(ZwSetVolumeInformationFile));
	HOOK_SYSCALL (ZwSetVolumeInformationFile , newZwSetVolumeInformationFile, oldZwSetVolumeInformationFile);

	oldZwQueryDirectoryFile = (ZWQUERYDIRECTORYFILE)(SYSTEMSERVICE(ZwQueryDirectoryFile));
	HOOK_SYSCALL (ZwQueryDirectoryFile , newZwQueryDirectoryFile, oldZwQueryDirectoryFile);

	oldZwFsControlFile = (ZWFSCONTROLFILE)(SYSTEMSERVICE(ZwFsControlFile));
	HOOK_SYSCALL (ZwFsControlFile , newZwFsControlFile, oldZwFsControlFile);

	oldZwDeviceIoControlFile = (ZWDEVICEIOCONTROLFILE)(SYSTEMSERVICE(ZwDeviceIoControlFile));
	HOOK_SYSCALL (ZwDeviceIoControlFile , newZwDeviceIoControlFile,  oldZwDeviceIoControlFile);


	oldZwReadFile = (ZWREADFILE)(SYSTEMSERVICE(ZwReadFile));
	HOOK_SYSCALL (ZwReadFile , newZwReadFile,  oldZwReadFile);


	return STATUS_SUCCESS;

}
Exemplo n.º 9
0
/**
 *	DriverEntry
 */
NTSTATUS DriverEntry( IN PDRIVER_OBJECT pstDriverObject, IN PUNICODE_STRING pusRegistryPath )
{
	NTSTATUS ntStatus;
	UNICODE_STRING usdeviceName;
	UNICODE_STRING usDeviceLink;
	
	dprintf( "VwFirewallDrv.sys: Loading Driver....\n" );
	
	
	//
	//	保存全局数据
	//
	g_pstDriverObject = pstDriverObject;
	
	
	//
	//	Create the device
	//
	RtlInitUnicodeString( &usdeviceName, NT_DEVICE_NAME );
	
	ntStatus = IoCreateDevice( pstDriverObject, 0, &usdeviceName, VWFIREWALLDRV_FILE_DEVICE, 0, FALSE, &g_pstControlDeviceObject );
	if ( NT_SUCCESS( ntStatus ) )
	{
		//
		//	设置 IOCTL 读写方式
		//
		g_pstControlDeviceObject->Flags |= DO_BUFFERED_IO;
		
		//	Create symbolic link
		RtlInitUnicodeString( &usDeviceLink, DOS_DEVICE_NAME );
		
		ntStatus = IoCreateSymbolicLink( &usDeviceLink, &usdeviceName );
		if ( NT_SUCCESS( ntStatus ) )
		{
			//
			//	初始化驱动数据
			//
			DrvDataInit( pstDriverObject );
		}
		else
		{
			dprintf( "VwFirewallDrv.sys: Error in IoCreateSymbolicLink.\n" );
			IoDeleteDevice( pstDriverObject->DeviceObject );
		}

		//
		//	Define driver's control functions
		//
		pstDriverObject->MajorFunction[ IRP_MJ_CREATE ]		= DrvDispatch;
		pstDriverObject->MajorFunction[ IRP_MJ_CLOSE ]		= DrvDispatch;
		pstDriverObject->MajorFunction[ IRP_MJ_DEVICE_CONTROL ]	= DrvDispatch;
		pstDriverObject->DriverUnload				= DrvUnload;


		//
		//	how-to-find-process-full-image-name
		//	http://84.45.57.224/how-to-find-process-full-image-name_topic9419_post40525.html
		//
		//	retrieving full process image path name in kernel mode
		//	http://rootkit.com/board.php?thread=5660&did=proj5&disp=5660&closed=1
		//	
		//	PsSetLoadImageNotifyRoutine
		//	http://msdn.microsoft.com/en-us/library/ff559957(VS.85).aspx
		//	http://hi.baidu.com/%B7%FA%CD%DE/blog/item/f223b18951054dbb0e24442f.html
		//
		//	PsSetCreateProcessNotifyRoutine
		//	http://msdn.microsoft.com/en-us/library/ff559951(v=VS.85).aspx
		//
		PsSetCreateProcessNotifyRoutine( procprocess_CreateProcessNotifyRoutine, FALSE );
		PsSetLoadImageNotifyRoutine( procprocess_LoadImageNotifyRoutine );
	}
	
	if ( ! NT_SUCCESS( ntStatus ) )
	{
		dprintf( "Error Intitializing. Unloading driver..." );
		DrvUnload( pstDriverObject );
	}
	
	return ntStatus;
}
Exemplo n.º 10
0
/******************************************************************************
 ***  ==  ==  ==  ==  ==  => The driver entry point <=  ==  ==  ==  ==  ==  ***
 ******************************************************************************/
NTSTATUS DDKAPI
DriverEntry(PDRIVER_OBJECT DriverObject, PUNICODE_STRING RegistryPath)
{
  NTSTATUS status;
  PDEVICE_OBJECT DeviceObject;
  UNICODE_STRING DeviceNameW;
  UNICODE_STRING SymbolicLinkNameW;
  ANSI_STRING DeviceNameA;
  ANSI_STRING SymbolicLinkNameA;

  DbgPrint("DriverEntry called\r\n");

  // support for service stopping
  DriverObject->DriverUnload = my_unload;
  // create support
  DriverObject->MajorFunction[IRP_MJ_CREATE] = my_dispatch_create;
  // IOCTL support
  DriverObject->MajorFunction[IRP_MJ_DEVICE_CONTROL] =
    my_dispatch_device_control;

  KeInitializeMutex(&mutex, 0);
  //KeReleaseMutex(&mutex, FALSE);

  for (DWORD i = 0; i < ENT_CNT; ++i) {
    g_proc_table[i].pid = 0;
    g_proc_table[i].sl_pid = 0;
  }

  /* initialize counted unicode strings
   * If I want to use normal string combining logic in my_names.h,
   * need to mess with ANSI vs. Unicode */
  RtlInitString(&DeviceNameA, MY_DEVICE_NAME);
  RtlAnsiStringToUnicodeString(&DeviceNameW, &DeviceNameA, TRUE);
  RtlInitString(&SymbolicLinkNameA, MY_DOSDEVICE_NAME);
  RtlAnsiStringToUnicodeString(&SymbolicLinkNameW, &SymbolicLinkNameA, TRUE);

  // create device object
  status = IoCreateDevice(DriverObject, 0, &DeviceNameW, FILE_DEVICE_UNKNOWN,
                          0, FALSE, &DeviceObject);

  if (NT_SUCCESS(status)) {
    /* Clear a flag, set by IoCreateDevice.
     * This is not mandatory within DriverEntry,
     * but it *is* mandatory if used anywhere else. */
    DeviceObject->Flags &= ~DO_DEVICE_INITIALIZING;

    // create user-visible name for the device
    status = IoCreateSymbolicLink(&SymbolicLinkNameW, &DeviceNameW);
  }

  // Initializing process creation/load handlers
  if (NT_SUCCESS(status))
    status = PsSetCreateProcessNotifyRoutine(create_process_watcher, FALSE);
  if (NT_SUCCESS(status))
    status = PsSetLoadImageNotifyRoutine(load_image_watcher);

  if (!NT_SUCCESS(status))
    return status;

  return STATUS_SUCCESS;
}
Exemplo n.º 11
0
/*
* DevioctlDispatch
*
* Purpose:
*
* IRP_MJ_DEVICE_CONTROL dispatch.
*
*/
NTSTATUS DevioctlDispatch(
    _In_ struct _DEVICE_OBJECT *DeviceObject,
    _Inout_ struct _IRP *Irp
)
{
    NTSTATUS                status = STATUS_SUCCESS;
    PIO_STACK_LOCATION      stack;
    ULONG_PTR               bytesIO = 0;

    UNREFERENCED_PARAMETER(DeviceObject);

    stack = IoGetCurrentIrpStackLocation(Irp);

    if (stack != NULL) {
        switch (stack->Parameters.DeviceIoControl.IoControlCode) {
        case TSUGUMI_IOCTL_REFRESH_LIST:

            status = TsmiLoadParameters();
            if (g_NotifySet == FALSE) {
                if (NT_SUCCESS(status)) {
                    status = PsSetLoadImageNotifyRoutine(TsmiPsImageHandler);
                    if (NT_SUCCESS(status)) {
                        g_NotifySet = TRUE;

#ifdef _DEBUGMSG
                        DbgPrint("[TSMI] DevioctlDispatch:NotifySet=%lx\n", g_NotifySet);
#endif
                    }
                }
            }
#ifdef _DEBUGMSG
            else {
                DbgPrint("[TSMI] DevioctlDispatch:Notify already installed\n");
            }
#endif
            bytesIO = g_NotifySet;
            break;

        case TSUGUMI_IOCTL_MONITOR_STOP:

            bytesIO = 0;

            if (g_NotifySet) {
                status = PsRemoveLoadImageNotifyRoutine(TsmiPsImageHandler);
                if (NT_SUCCESS(status)) {
                    g_NotifySet = FALSE;
                    bytesIO = 1;
                }
            }
            break;

        default:
            status = STATUS_INVALID_PARAMETER;
        };
    }
    else {
        status = STATUS_INTERNAL_ERROR;
    }

    Irp->IoStatus.Status = status;
    Irp->IoStatus.Information = bytesIO;
    IoCompleteRequest(Irp, IO_NO_INCREMENT);
    return status;
}
Exemplo n.º 12
0
VOID IsKernelBooting(IN PVOID Context)
{
	NTSTATUS status;
	PUCHAR KiFastCallEntry;
	ULONG EProcess;
	int i=0;
	ULONG ImageBase;

	if (PsGetProcessCount() <= 2)
		bKernelBooting = TRUE;
	else 
		goto _InitThread;  //系统没有刚刚启动,则跳过

	while (1)
	{
		//系统刚刚启动
		if (bKernelBooting){

			//等待初始化成功
			//初始化成功分为几个条件:
			//1:注册表初始化好了,可以访问、写入
			//2:文件系统初始化好了,可以访问文件、写入文件
			//3:用户空间进程环境已经初始化好了      <== 上面这两个判断有bug,这里判断才是比较准确的

			if (PsGetProcessCount() >= 3){
				break;
			}
		}
		WaitMicroSecond(88);
	}
	/*
		系统刚刚启动,执行到这里,足以说明是深度扫描。就开始检查
		如果是深度扫描,就开启蓝屏检测
		原理:写入KeBugCkeck值,ring3启动的时候删除这个键值,代表启动成功不蓝屏
		如果下次启动的时候发现KeBugCkeck存在,就说明启动不成功,就直接返回,不做任何操作
		如果发现这个键值,说明启动不成功,直接返回,不做任何hook
	*/
	if (IsRegKeyInSystem(L"\\Registry\\Machine\\SYSTEM\\CurrentControlSet\\Control\\KeBugCheck")){
		/*

			驱动自启动不能调用PsTerminateSystemThread结束线程
			应该让线程自己返回

		*/
		return;
	}
	//写入一个值,在界面运行之后,删除,代表启动成功!
	//如果执行到这里,说明稳定运行不蓝屏!
	KeBugCheckCreateValueKey(L"\\Registry\\Machine\\SYSTEM\\CurrentControlSet\\Control\\KeBugCheck");

_InitThread:
	_asm
	{
		pushad;
		mov ecx, 0x176;
		rdmsr;
		mov KiFastCallEntry, eax;
		popad;
	}
	/*
	  
	  防止重复加载
	  备注:如果注册开机启动,插入U盘就会第二次加载
	*/
	if (*KiFastCallEntry == 0xe9)
	{
		KdPrint(("Terminate System Thread"));

		/*

			驱动自启动不能调用PsTerminateSystemThread结束线程
			应该让线程自己返回

		*/
		return;
	}
	if (ReLoadNtos(PDriverObject,RetAddress) == STATUS_SUCCESS)
	{
		//添加驱动加载的被动防御,和驱动深度扫描
		PsSetLoadImageNotifyRoutine(ImageNotify);
		//*******************************************************************
		//test
		//*******************************************************************
		//ImageBase = 0xF83E2000;
		//IatHookCheck(&ImageBase);
		//MsGetMsgHookInfo();
		//*******************************************************************
		//---------------------------------------
		//demo,深度服务扫描隐藏
		//---------------------------------------
		if (bKernelBooting)
		{
			DepthServicesRegistry = (PSERVICESREGISTRY)ExAllocatePool(NonPagedPool,sizeof(SERVICESREGISTRY)*1024);
			if (DepthServicesRegistry)
			{
				memset(DepthServicesRegistry,0,sizeof(SERVICESREGISTRY)*1024);
				status = QueryServicesRegistry(DepthServicesRegistry);
				if (status == STATUS_SUCCESS)
				{
// 					Safe_CreateValueKey(
// 						L"\\Registry\\Machine\\SYSTEM\\CurrentControlSet\\Control\\A-Protect",
// 						REG_SZ,
// 						L"QueryServicesRegistry",
// 						L"success");
				}
			}
		}
	}
	bKernelBooting = FALSE;
}
//--------------------------------------------------------------------------------------
NTSTATUS 
NTAPI
DriverEntry(
    PDRIVER_OBJECT  DriverObject,
    PUNICODE_STRING RegistryPath)
{
    if (!RuntimeInitialize(DriverObject, RegistryPath))
    {
        return STATUS_UNSUCCESSFUL;
    }

    DbgMsg(__FUNCTION__"(): Loaded at "IFMT"\n", m_DriverBase);

    // initialize NDIS structures offsets
    NdisHookInitialize(NULL);

#ifdef USE_STEALTH_IMAGE

    if (m_DriverBase == NULL)
    {
        return STATUS_UNSUCCESSFUL;
    }

    PIMAGE_NT_HEADERS32 pHeaders = (PIMAGE_NT_HEADERS32)((PUCHAR)m_DriverBase + 
        ((PIMAGE_DOS_HEADER)m_DriverBase)->e_lfanew);

    PIMAGE_SECTION_HEADER pSection = (PIMAGE_SECTION_HEADER)
        (pHeaders->FileHeader.SizeOfOptionalHeader + 
        (PUCHAR)&pHeaders->OptionalHeader);

    // calculate size, that require for rootkit code
    for (ULONG i = 0; i < pHeaders->FileHeader.NumberOfSections; i++)
    {            
        if (m_RkOffset == 0)
        {
            m_RkOffset = pSection->VirtualAddress;
        }

        if (pSection->Characteristics & IMAGE_SCN_MEM_DISCARDABLE)
        {
            // erase discardable flag from our driver sections
            pSection->Characteristics &= ~IMAGE_SCN_MEM_DISCARDABLE;
        }
        else
        {
            m_RkSize += MY_ALIGN_UP(
                pSection->Misc.VirtualSize, 
                pHeaders->OptionalHeader.SectionAlignment
            );
        }
        
        pSection += 1;
    }

    DbgMsg("Rootkit code: 0x%x bytes from 0x%.8x\n", m_RkSize, m_RkOffset);

    // to deal with ProcessRelocs()
    pHeaders->OptionalHeader.ImageBase = (ULONG)m_DriverBase;
    m_DriverSize = pHeaders->OptionalHeader.SizeOfImage;

    NTSTATUS ns = PsSetLoadImageNotifyRoutine(LoadImageNotify);
    if (!NT_SUCCESS(ns))
    {
        DbgMsg("PsSetLoadImageNotifyRoutine() fails: 0x%.8x\n", ns);
    }

#else // USE_STEALTH_IMAGE

    DriverEntryInitializePayload(NULL);   

    HANDLE hThread = NULL;
    NTSTATUS ns = PsCreateSystemThread(
        &hThread, 
        THREAD_ALL_ACCESS, 
        NULL, NULL, NULL, 
        DriverEntryContinueThread, 
        NULL
    );
    if (NT_SUCCESS(ns))
    {
        ZwClose(hThread);
    }
    else
    {
        DbgMsg("PsCreateSystemThread() fails: 0x%.8x\n", ns);
    }

#endif // USE_STEALTH_IMAGE

    return STATUS_SUCCESS;
}
Exemplo n.º 14
0
/**************************************************************

Description:

Initializes the driver and also loads the system specific PatchGuard
information.
*/
NTSTATUS DriverEntry(
    IN PDRIVER_OBJECT		InDriverObject,
    IN PUNICODE_STRING		InRegistryPath)
{
    NTSTATUS						Status;
    UNICODE_STRING					NtDeviceName;
    UNICODE_STRING					DosDeviceName;
    PEASYHOOK_DEVICE_EXTENSION		DeviceExtension;
    PDEVICE_OBJECT					DeviceObject = NULL;
    BOOLEAN							SymbolicLink = FALSE;

    /*
    Create device...
    */
    RtlInitUnicodeString(&NtDeviceName, EASYHOOK_DEVICE_NAME);

    Status = IoCreateDevice(
        InDriverObject,
        sizeof(EASYHOOK_DEVICE_EXTENSION),		// DeviceExtensionSize
        &NtDeviceName,					// DeviceName
        FILE_DEVICE_EASYHOOK,			// DeviceType
        0,								// DeviceCharacteristics
        TRUE,							// Exclusive
        &DeviceObject					// [OUT]
        );

    if (!NT_SUCCESS(Status))
        goto ERROR_ABORT;

    /*
    Expose interfaces...
    */
    DeviceExtension = (PEASYHOOK_DEVICE_EXTENSION)DeviceObject->DeviceExtension;
    DeviceExtension->MaxVersion = EASYHOOK_INTERFACE_v_1;

// Disable warning C4276: no prototype provided; assumed no parameters
#pragma warning(disable: 4276)
    DeviceExtension->API_v_1.RtlGetLastError = RtlGetLastError;
    DeviceExtension->API_v_1.RtlGetLastErrorString = RtlGetLastErrorString;
    DeviceExtension->API_v_1.LhInstallHook = LhInstallHook;
    DeviceExtension->API_v_1.LhUninstallHook = LhUninstallHook;
    DeviceExtension->API_v_1.LhWaitForPendingRemovals = LhWaitForPendingRemovals;
    DeviceExtension->API_v_1.LhBarrierGetCallback = LhBarrierGetCallback;
    DeviceExtension->API_v_1.LhBarrierGetReturnAddress = LhBarrierGetReturnAddress;
    DeviceExtension->API_v_1.LhBarrierGetAddressOfReturnAddress = LhBarrierGetAddressOfReturnAddress;
    DeviceExtension->API_v_1.LhBarrierBeginStackTrace = LhBarrierBeginStackTrace;
    DeviceExtension->API_v_1.LhBarrierEndStackTrace = LhBarrierEndStackTrace;
    DeviceExtension->API_v_1.LhBarrierPointerToModule = LhBarrierPointerToModule;
    DeviceExtension->API_v_1.LhBarrierGetCallingModule = LhBarrierGetCallingModule;
    DeviceExtension->API_v_1.LhBarrierCallStackTrace = LhBarrierCallStackTrace;
    DeviceExtension->API_v_1.LhSetGlobalExclusiveACL = LhSetGlobalExclusiveACL;
    DeviceExtension->API_v_1.LhSetGlobalInclusiveACL = LhSetGlobalInclusiveACL;
    DeviceExtension->API_v_1.LhSetExclusiveACL = LhSetExclusiveACL;
    DeviceExtension->API_v_1.LhSetInclusiveACL = LhSetInclusiveACL;
    DeviceExtension->API_v_1.LhIsProcessIntercepted = LhIsProcessIntercepted;

    /*
    Register for user-mode accessibility and set major functions...
    */
    RtlInitUnicodeString(&DosDeviceName, EASYHOOK_DOS_DEVICE_NAME);

    if (!NT_SUCCESS(Status = IoCreateSymbolicLink(&DosDeviceName, &NtDeviceName)))
        goto ERROR_ABORT;

    SymbolicLink = TRUE;

    InDriverObject->MajorFunction[IRP_MJ_CREATE] = EasyHookDispatchCreate;
    InDriverObject->MajorFunction[IRP_MJ_CLOSE] = EasyHookDispatchClose;
    InDriverObject->MajorFunction[IRP_MJ_DEVICE_CONTROL] = EasyHookDispatchDeviceControl;
    InDriverObject->DriverUnload = EasyHookUnload;

    // initialize EasyHook
    if (!NT_SUCCESS(Status = LhBarrierProcessAttach()))
        goto ERROR_ABORT;

    PsSetLoadImageNotifyRoutine(OnImageLoadNotification);

    LhCriticalInitialize();

    return LhUpdateModuleInformation();

ERROR_ABORT:

    /*
    Rollback in case of errors...
    */
    if (SymbolicLink)
        IoDeleteSymbolicLink(&DosDeviceName);

    if (DeviceObject != NULL)
        IoDeleteDevice(DeviceObject);

    return Status;
}
Exemplo n.º 15
0
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//	Description : initializes the driver and the filter port, registers driver and registry callbacks.
//
//	Parameters : 
//		_in_ PDRIVER_OBJECT pDriverObject :	Data structure used to represent the driver.
//		_in_ PUNICODE_STRING pRegistryPath :	Registry location where the information for the driver
//							was stored.
//	Return value :
//		NTSTATUS : STATUS_SUCCESS if the driver initialization has been well completed
//	Process :
//		Defines hidden / blocked processes names.
//		Creates the device driver and its symbolic link.
//		Sets IRP callbacks.
//		Creates filter communication port to send logs from the driver to the userland process.
//		Creates logs mutex.
//		Register image load and registry callbacks.
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
NTSTATUS DriverEntry(PDRIVER_OBJECT pDriverObject, PUNICODE_STRING pRegistryPath)
{
	PVOID adrFunc;
	PDEVICE_OBJECT pDeviceObject;
	UNICODE_STRING usDriverName;
	UNICODE_STRING filterPortName;
	UNICODE_STRING function;
	OBJECT_ATTRIBUTES objAttr;
	RTL_OSVERSIONINFOW osInfo;
	PSECURITY_DESCRIPTOR securityDescriptor;
	NTSTATUS status;
	ULONG i;

	// import some functions we will need
	RtlInitUnicodeString(&function, L"ZwQueryInformationThread");
	ZwQueryInformationThread = MmGetSystemRoutineAddress(&function);
	RtlInitUnicodeString(&function, L"ZwQueryInformationProcess");
	ZwQueryInformationProcess = MmGetSystemRoutineAddress(&function);
	RtlInitUnicodeString(&function, L"ZwQuerySystemInformation");
	ZwQuerySystemInformation = MmGetSystemRoutineAddress(&function);
	
	RtlInitUnicodeString(&usDriverName, L"\\Device\\DriverSSDT");
	RtlInitUnicodeString(&usDosDeviceName, L"\\DosDevices\\DriverSSDT"); 
	status = IoCreateDevice(pDriverObject, 0, &usDriverName, FILE_DEVICE_UNKNOWN, 0, FALSE, &pDeviceObject);
	if(!NT_SUCCESS(status))
		return status;
	
	status = IoCreateSymbolicLink(&usDosDeviceName, &usDriverName);
	if(!NT_SUCCESS(status))
		return status;
	
	pDeviceObject->Flags |= DO_BUFFERED_IO;
	pDeviceObject->Flags &= (~DO_DEVICE_INITIALIZING);
	for(i=0; i<IRP_MJ_MAXIMUM_FUNCTION; i++)
		pDriverObject->MajorFunction[i] = ioctl_NotSupported;
	pDriverObject->MajorFunction[IRP_MJ_DEVICE_CONTROL] = ioctl_DeviceControl;
	
	monitored_process_list = NULL;
	hidden_process_list = NULL;
	monitored_handle_list = NULL;
	
	// initialize every function pointers to null
	oldNtMapViewOfSection = NULL;
	oldNtSetContextThread = NULL;
	oldNtCreateThread = NULL;
	oldNtQueueApcThread = NULL;
	oldNtCreateProcess = NULL;
	oldNtSystemDebugControl = NULL;
	oldNtCreateProcessEx = NULL;
	oldNtWriteVirtualMemory = NULL;
	oldNtDebugActiveProcess = NULL;
	oldNtOpenProcess = NULL;
	oldNtOpenThread = NULL;
	oldNtQuerySystemInformation = NULL;
	oldNtCreateFile = NULL;
	oldNtReadFile = NULL;
	oldNtWriteFile = NULL;
	oldNtDeleteFile = NULL;
	oldNtSetInformationFile = NULL;
	oldNtQueryInformationFile = NULL;
	oldNtCreateMutant = NULL;
	oldNtDeviceIoControlFile = NULL;
	oldNtTerminateProcess = NULL;
	oldNtDelayExecution = NULL;
	oldNtQueryValueKey = NULL;
	oldNtQueryAttributesFile = NULL;
	oldNtReadVirtualMemory = NULL;
	oldNtResumeThread = NULL;
	oldNtCreateSection = NULL;
	oldNtUserCallOneParam = NULL;
	oldNtUserCallNoParam = NULL;
	oldNtClose = NULL;
	oldNtOpenFile = NULL;
	
	#ifdef DEBUG
	DbgPrint("IOCTL_CUCKOO_PATH : 0x%08x\n", IOCTL_CUCKOO_PATH);
	#endif
	
	// get os version
	if(!NT_SUCCESS(RtlGetVersion(&osInfo)))
		return status;

	// check os version	
	if(osInfo.dwMajorVersion == 5 && osInfo.dwMinorVersion == 1) // xp 32 bits
	{
		is_xp = 1;
		#ifdef DEBUG
		DbgPrint("windows xp !\n");
		#endif
	}
	else if(osInfo.dwMajorVersion == 6 && osInfo.dwMinorVersion == 1) // win 7
	{
		is_xp = 0;
		#ifdef DEBUG
		DbgPrint("windows 7!\n");
		#endif
	}
	else
	{
		#ifdef DEBUG
		DbgPrint("error : not supported os\n");
		#endif
		return -1;
	}
	
   	status = FltRegisterFilter(pDriverObject,&registration,&filter);
	if(!NT_SUCCESS(status))
		return status;
	
	RtlInitUnicodeString(&filterPortName, L"\\FilterPort");
	status = FltBuildDefaultSecurityDescriptor(&securityDescriptor, FLT_PORT_ALL_ACCESS);
	if(!NT_SUCCESS(status))
		return status;
	
	InitializeObjectAttributes(&objAttr, &filterPortName, OBJ_KERNEL_HANDLE | OBJ_CASE_INSENSITIVE, NULL, securityDescriptor); 
	
	status = FltCreateCommunicationPort(filter, &serverPort, &objAttr, NULL, ConnectCallback, DisconnectCallback, NULL, 1);
	FltFreeSecurityDescriptor(securityDescriptor);
	if(!NT_SUCCESS(status))
		return status;
	
	KeInitializeMutex(&mutex, 0);
	
	status = CmRegisterCallback(regCallback, NULL, &cookie);
	if(!NT_SUCCESS(status))
		return status;
	
	status = PsSetLoadImageNotifyRoutine(imageCallback);
	if(!NT_SUCCESS(status))
		return status;
	
	KeServiceDescriptorTableShadow = getShadowTableAddress();
	
	if(!KeServiceDescriptorTableShadow)
	{
		#ifdef DEBUG
		DbgPrint("error : couldn't retrieve Shadow SSDT\n");
		#endif
		return STATUS_UNSUCCESSFUL;
	}

	
	pDriverObject->DriverUnload = Unload;
	return STATUS_SUCCESS;
}
Exemplo n.º 16
0
///////////////////////////////////////////////////////////////////////////////////////////////////
//  DriverEntry 
//      Installable driver initialization entry point.
//      This entry point is called directly by the I/O system.
//
//  Arguments:
//      IN  DriverObject
//              pointer to the driver object
//
//      IN  RegistryPath
//              pointer to a unicode string representing the path,
//              to driver-specific key in the registry.
//
//  Return Value:
//      Status
//
NTSTATUS DriverEntry(
    IN  PDRIVER_OBJECT  DriverObject,
    IN  PUNICODE_STRING RegistryPath
    )
{
    NTSTATUS                            status;
    PDEVICE_OBJECT                      deviceObject;
    PTESTDRV_DEVICE_EXTENSION   deviceExtension;
    UNICODE_STRING                      ntName;
    UNICODE_STRING                      win32Name;

    testdrvDebugPrint(DBG_INIT, DBG_TRACE, __FUNCTION__"++");
    testdrvDebugPrint(DBG_INIT, DBG_INFO, "Compiled at %s on %s", __TIME__, __DATE__);

#ifdef DBG
//    DbgBreakPoint();
#endif

#ifdef TESTDRV_WMI_TRACE 
    WPP_INIT_TRACING(DriverObject, RegistryPath);
#endif

    RtlZeroMemory(&g_Data, sizeof(TESTDRV_DATA));

    // save registry path
    g_Data.RegistryPath.Length = RegistryPath->Length;
    g_Data.RegistryPath.MaximumLength = RegistryPath->Length + sizeof(UNICODE_NULL);
    g_Data.RegistryPath.Buffer = (PWCHAR)ExAllocatePoolWithTag(
                                            PagedPool,
                                            g_Data.RegistryPath.MaximumLength,
                                            TESTDRV_POOL_TAG
                                            );

    if (g_Data.RegistryPath.Buffer == NULL)
    {
        status = STATUS_INSUFFICIENT_RESOURCES;

        testdrvDebugPrint(DBG_INIT, DBG_ERR, __FUNCTION__": Failed to allocate memory for RegistryPath");

        return status;
    }

    RtlCopyUnicodeString(&g_Data.RegistryPath, RegistryPath);

    // setup our dispatch function table in the driver object
    DriverObject->MajorFunction[IRP_MJ_CREATE] = testdrvCreateDispatch;
    DriverObject->MajorFunction[IRP_MJ_CLOSE] = testdrvCloseDispatch;
    DriverObject->MajorFunction[IRP_MJ_DEVICE_CONTROL] = testdrvDeviceIoControlDispatch;
    DriverObject->MajorFunction[IRP_MJ_READ] = testdrvReadDispatch;
    DriverObject->MajorFunction[IRP_MJ_WRITE] = testdrvWriteDispatch;
    DriverObject->MajorFunction[IRP_MJ_CLEANUP] = testdrvCleanupDispatch;
    DriverObject->MajorFunction[IRP_MJ_SHUTDOWN] = testdrvShutdownDispatch;
    DriverObject->DriverUnload = testdrvUnload;

    // initialize device name
    RtlInitUnicodeString(&ntName, L"\\Device\\testdrvDevice");

	ExInitializeFastMutex(&qemu_output_lock);

	// Create our function device object.
    status = IoCreateDevice(
                DriverObject,
                sizeof (TESTDRV_DEVICE_EXTENSION),
                &ntName,
                FILE_DEVICE_UNKNOWN,
                0,
                FALSE,
                &deviceObject
                );

    if (!NT_SUCCESS (status)) 
    {
        ExFreePool(g_Data.RegistryPath.Buffer);
        g_Data.RegistryPath.Buffer = NULL;

        testdrvDebugPrint(DBG_INIT, DBG_ERR, __FUNCTION__"--. STATUS %x", status);

        return status;
    }

    // Initialize the device extension.
    deviceExtension = (PTESTDRV_DEVICE_EXTENSION)deviceObject->DeviceExtension;

    // Zero the memory
    RtlZeroMemory(deviceExtension, sizeof(TESTDRV_DEVICE_EXTENSION));

    // save our device object pointer
    deviceExtension->DeviceObject = deviceObject;

    // This flag sets the buffering method for reads and writes
    // to METHOD_DIRECT.  IOCTLs are handled by IO control codes
    // independent of the value of this flag.
    deviceObject->Flags |= DO_DIRECT_IO;

    RtlInitUnicodeString(&win32Name, L"\\??\\testdrvDevice");
    status = IoCreateSymbolicLink(&win32Name, &ntName);
    if (!NT_SUCCESS(status))
    {
        IoDeleteDevice(deviceObject);

        ExFreePool(g_Data.RegistryPath.Buffer);
        g_Data.RegistryPath.Buffer = NULL;

        return status;
    }

    IoRegisterShutdownNotification(deviceObject);

	InitializeListHead(&ModuleListHead);


	g_WorkItem = IoAllocateWorkItem(deviceObject);
	if(!g_WorkItem)
		return STATUS_INSUFFICIENT_RESOURCES;

	IoQueueWorkItem(g_WorkItem, GetSysModInfo, DelayedWorkQueue, g_WorkItem);
	//UpdateSysModuleList();


	PsSetLoadImageNotifyRoutine(LoadImageNotifyRoutine);
	PsSetCreateProcessNotifyRoutine(CreateProcessNotifyRoutine, FALSE);


    testdrvDebugPrint(DBG_INIT, DBG_TRACE, __FUNCTION__"--. STATUS %x", status);

    return status;
}
Exemplo n.º 17
0
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//	Description : initializes the driver and the filter port, registers driver and registry callbacks.
//
//	Parameters : 
//		_in_ PDRIVER_OBJECT pDriverObject :	Data structure used to represent the driver.
//		_in_ PUNICODE_STRING pRegistryPath :	Registry location where the information for the driver
//							was stored.
//	Return value :
//		NTSTATUS : STATUS_SUCCESS if the driver initialization has been well completed
//	Process :
//		Defines hidden / blocked processes names.
//		Creates the device driver and its symbolic link.
//		Sets IRP callbacks.
//		Creates filter communication port to send logs from the driver to the userland process.
//		Creates logs mutex.
//		Hooks SSDT.
//		Register image load and registry callbacks.
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
NTSTATUS DriverEntry(PDRIVER_OBJECT pDriverObject, PUNICODE_STRING pRegistryPath)
{
	PVOID adrFunc;
	PDEVICE_OBJECT pDeviceObject;
	UNICODE_STRING usDriverName;
	UNICODE_STRING filterPortName;
	UNICODE_STRING function;
	OBJECT_ATTRIBUTES objAttr;
	PSECURITY_DESCRIPTOR securityDescriptor;
	NTSTATUS status;
	ULONG i;
	 
	// import some functions we will need
	RtlInitUnicodeString(&function, L"ZwQueryInformationThread");
	ZwQueryInformationThread = MmGetSystemRoutineAddress(&function);
	RtlInitUnicodeString(&function, L"ZwQueryInformationProcess");
	ZwQueryInformationProcess = MmGetSystemRoutineAddress(&function);
	
	RtlInitUnicodeString(&usDriverName, L"\\Device\\DriverSSDT");
	RtlInitUnicodeString(&usDosDeviceName, L"\\DosDevices\\DriverSSDT"); 
	status = IoCreateDevice(pDriverObject, 0, &usDriverName, FILE_DEVICE_UNKNOWN, 0, FALSE, &pDeviceObject);
	if(!NT_SUCCESS(status))
		return status;
	
	status = IoCreateSymbolicLink(&usDosDeviceName, &usDriverName);
	if(!NT_SUCCESS(status))
		return status;
	
	pDeviceObject->Flags |= DO_BUFFERED_IO;
	pDeviceObject->Flags &= (~DO_DEVICE_INITIALIZING);
	for(i=0; i<IRP_MJ_MAXIMUM_FUNCTION; i++)
		pDriverObject->MajorFunction[i] = ioctl_NotSupported;
	pDriverObject->MajorFunction[IRP_MJ_DEVICE_CONTROL] = ioctl_DeviceControl;
	
	monitored_process_list = NULL;
	hidden_process_list = NULL;
	
	// initialize every function pointers to null
	oldZwMapViewOfSection = NULL;
	oldZwSetContextThread = NULL;
	oldZwCreateThread = NULL;
	oldZwQueueApcThread = NULL;
	oldZwCreateProcess = NULL;
	oldZwSystemDebugControl = NULL;
	oldZwCreateProcessEx = NULL;
	oldZwWriteVirtualMemory = NULL;
	oldZwDebugActiveProcess = NULL;
	oldZwOpenProcess = NULL;
	oldZwOpenThread = NULL;
	oldZwQuerySystemInformation = NULL;
	oldZwCreateFile = NULL;
	oldZwReadFile = NULL;
	oldZwWriteFile = NULL;
	oldZwDeleteFile = NULL;
	oldZwSetInformationFile = NULL;
	oldZwQueryInformationFile = NULL;
	oldZwCreateMutant = NULL;
	
   	status = FltRegisterFilter(pDriverObject,&registration,&filter);
	if(!NT_SUCCESS(status))
		return status;
	
	
	RtlInitUnicodeString(&filterPortName, L"\\FilterPort");
	status = FltBuildDefaultSecurityDescriptor(&securityDescriptor, FLT_PORT_ALL_ACCESS);
	if(!NT_SUCCESS(status))
		return status;
	
	InitializeObjectAttributes(&objAttr, &filterPortName, OBJ_KERNEL_HANDLE | OBJ_CASE_INSENSITIVE, NULL, securityDescriptor); 
	
	status = FltCreateCommunicationPort(filter, &serverPort, &objAttr, NULL, ConnectCallback, DisconnectCallback, NULL, 1);
	FltFreeSecurityDescriptor(securityDescriptor);
	if(!NT_SUCCESS(status))
		return status;
	
	KeInitializeMutex(&mutex, 0);
	
	status = CmRegisterCallback(regCallback, NULL, &cookie);
	if(!NT_SUCCESS(status))
		return status;
	
	status = PsSetLoadImageNotifyRoutine(imageCallback);
	if(!NT_SUCCESS(status))
		return status;
	
	hook_ssdt_entries();
	pDriverObject->DriverUnload = Unload;
	
	return STATUS_SUCCESS;
}