void Thread::Thread_init() { PsCreateSystemThreadEx(&system_thread_handle, //Thread Handle 0, //KernelStackSize stack_size, //Stack Size 0, //TlsDataSize &Id, //Thread ID NULL, //StartContext1 NULL, //StartContext2 TRUE, //CreateSuspended FALSE, //DebugStack (PKSTART_ROUTINE)&callback); //StartRoutine ObReferenceObjectByHandle(system_thread_handle, (POBJECT_TYPE)PsThreadObjectType, &system_thread_handle); //#define LOW_PRIORITY 0 //#define LOW_REALTIME_PRIORITY 16 //#define HIGH_PRIORITY 31 //#define MAXIMUM_PRIORITY 32 KeSetBasePriorityThread((PKTHREAD)system_thread_handle, (PVOID)0); //Default the thread to low priority state = ThreadState::Unstarted; Id++; //increment Id so every thread Id is unique }
timeout_id_t timeout(void (*func)(void *), void* unused, hrtime_t nano) { struct timeout_func *to_func; OBJECT_ATTRIBUTES ObjectAttributes; NTSTATUS st; HANDLE thand; UNREFERENCED_PARAMETER(unused); InitializeObjectAttributes(&ObjectAttributes, NULL, OBJ_KERNEL_HANDLE, NULL, NULL); to_func = ExAllocatePoolWithTag(NonPagedPool, sizeof(struct timeout_func), 'Tag1'); if (to_func == NULL) return (timeout_id_t) NULL; to_func->time = nano; to_func->f = func; KeInitializeTimer(&to_func->Timer); to_func->Thread = NULL; st = PsCreateSystemThread(&thand, THREAD_ALL_ACCESS, &ObjectAttributes, NULL, NULL, FTTimeout, (PVOID) to_func); if (st == STATUS_SUCCESS) { /* To wait for the thread to terminate, you need the address of the underlying KTHREAD object instead of the handle you get back from PsCreateSystemThread */ ObReferenceObjectByHandle(thand, THREAD_ALL_ACCESS, NULL, KernelMode, (PVOID*)&to_func->Thread, NULL); /* Dont need the handle once we have the address of the KTHREAD */ ZwClose(thand); } else dprintf("fasttrap.sys: timeout() Thread creationfailed\n"); return (timeout_id_t) to_func->Thread; }
NTSTATUS FASTCALL IntValidateWindowStationHandle( HWINSTA WindowStation, KPROCESSOR_MODE AccessMode, ACCESS_MASK DesiredAccess, PWINSTATION_OBJECT *Object) { NTSTATUS Status; if (WindowStation == NULL) { ERR("Invalid window station handle\n"); EngSetLastError(ERROR_INVALID_HANDLE); return STATUS_INVALID_HANDLE; } Status = ObReferenceObjectByHandle( WindowStation, DesiredAccess, ExWindowStationObjectType, AccessMode, (PVOID*)Object, NULL); if (!NT_SUCCESS(Status)) SetLastNtError(Status); return Status; }
NTSTATUS HelloDDKRead(IN PDEVICE_OBJECT pDevObj, IN PIRP pIrp) { KdPrint(("DriverB:Enter B HelloDDKRead\n")); NTSTATUS ntStatus = STATUS_SUCCESS; UNICODE_STRING DeviceName; RtlInitUnicodeString( &DeviceName, L"\\Device\\MyDDKDeviceA" ); //初始化objectAttributes OBJECT_ATTRIBUTES objectAttributes; InitializeObjectAttributes(&objectAttributes, &DeviceName, OBJ_CASE_INSENSITIVE, NULL, NULL ); HANDLE hDevice; IO_STATUS_BLOCK status_block; //异步打开设备 ntStatus = ZwCreateFile(&hDevice, FILE_READ_ATTRIBUTES,//没有设SYNCHRONIZE &objectAttributes, &status_block, NULL,FILE_ATTRIBUTE_NORMAL,FILE_SHARE_READ, FILE_OPEN_IF,0,NULL,0); LARGE_INTEGER offset = RtlConvertLongToLargeInteger(0); if (NT_SUCCESS(ntStatus)) { ntStatus = ZwReadFile(hDevice,NULL,NULL,NULL,&status_block,NULL,0,&offset,NULL); } if (ntStatus==STATUS_PENDING) { KdPrint(("DriverB:ZwReadFile return STATUS_PENDING!\n")); PFILE_OBJECT FileObject; ntStatus = ObReferenceObjectByHandle(hDevice, EVENT_MODIFY_STATE, *ExEventObjectType, KernelMode, (PVOID*) &FileObject, NULL); if (NT_SUCCESS(ntStatus)) { KdPrint(("DriverB:Waiting...")); KeWaitForSingleObject(&FileObject->Event,Executive,KernelMode,FALSE,NULL); KdPrint(("DriverB:Driver A Read IRP completed now!\n")); ObDereferenceObject(FileObject); } } ZwClose(hDevice); ntStatus = STATUS_SUCCESS; // 完成IRP pIrp->IoStatus.Status = ntStatus; pIrp->IoStatus.Information = 0; // bytes xfered IoCompleteRequest( pIrp, IO_NO_INCREMENT ); KdPrint(("DriverB:Leave B HelloDDKRead\n")); return ntStatus; }
void Thread::SetPriority(int priority) { if((priority != 0) && (priority != 16) && (priority != 31) && (priority != 32)) return; //no valid values ObReferenceObjectByHandle(system_thread_handle, (POBJECT_TYPE)PsThreadObjectType, &system_thread_handle); KeSetBasePriorityThread((PKTHREAD)system_thread_handle, (PVOID)priority); }
NTSTATUS NTAPI Pin_fnWrite( PDEVICE_OBJECT DeviceObject, PIRP Irp) { PDISPATCH_CONTEXT Context; PIO_STACK_LOCATION IoStack; PFILE_OBJECT FileObject; NTSTATUS Status; /* Get current stack location */ IoStack = IoGetCurrentIrpStackLocation(Irp); /* The dispatch context is stored in the FsContext member */ Context = (PDISPATCH_CONTEXT)IoStack->FileObject->FsContext; /* Sanity check */ ASSERT(Context); if (Context->hMixerPin) { // FIXME // call kmixer to convert stream UNIMPLEMENTED } /* acquire real pin file object */ Status = ObReferenceObjectByHandle(Context->Handle, GENERIC_WRITE, *IoFileObjectType, KernelMode, (PVOID*)&FileObject, NULL); if (!NT_SUCCESS(Status)) { DPRINT1("failed\n"); Irp->IoStatus.Information = 0; Irp->IoStatus.Status = Status; /* Complete the irp */ IoCompleteRequest(Irp, IO_NO_INCREMENT); return Status; } /* skip current irp location */ IoSkipCurrentIrpStackLocation(Irp); /* get next stack location */ IoStack = IoGetNextIrpStackLocation(Irp); /* store file object of next device object */ IoStack->FileObject = FileObject; IoStack->MajorFunction = IRP_MJ_DEVICE_CONTROL; //ASSERT(Irp->AssociatedIrp.SystemBuffer); /* now call the driver */ Status = IoCallDriver(IoGetRelatedDeviceObject(FileObject), Irp); /* dereference file object */ ObDereferenceObject(FileObject); return Status; }
VOID TunerScanWorkItem(IN PDEVICE_OBJECT DeviceObject,IN PVOID Context) { HANDLE handle; NTSTATUS WaitStatus; UNREFERENCED_PARAMETER(DeviceObject); PEventHandlerData EventBlock= static_cast<PEventHandlerData>( Context); DbgPrint("MY-Event::TunerScanWorkItem"); OBJECT_ATTRIBUTES oa; InitializeObjectAttributes(&oa, NULL, OBJ_KERNEL_HANDLE, NULL, NULL); if (STATUS_SUCCESS != PsCreateSystemThread(&handle, THREAD_ALL_ACCESS, &oa, NULL, NULL, ScanThread, EventBlock)) { return; } ObReferenceObjectByHandle(handle, THREAD_ALL_ACCESS, NULL, KernelMode, (PVOID*) &EventBlock->thread, NULL); KeSetEvent(&(EventBlock->InitEvent), 0,FALSE); ZwClose(handle); do { WaitStatus = KeWaitForSingleObject(&(EventBlock->TuneEvent), Executive, KernelMode, FALSE, NULL); if (!NT_SUCCESS(WaitStatus)) { break; } if(EventBlock->bStopScan) { StopPollingThread(); KsGenerateEvent(EventBlock->EventEntry);//fire an Event to the app that we are stopped break; } CEncoderDevice* EncDevice = EventBlock->pDevice; EncDevice->CurrentFrequency = EventBlock->CurrentFrequency; KeClearEvent(&(EventBlock->TuneEvent)); DbgPrint( "MY-TunerScanWorkItem : Firing an event from driver to the app\n"); KsGenerateEvent(EventBlock->EventEntry); #pragma warning(push) #pragma warning(disable:4127) }while(1); #pragma warning (pop) DbgPrint( "MY-TunerScanWorkItem terminating\n"); IoFreeWorkItem(EventHandler->ThreadItem); // Release Work Item EventHandler->EventEntry = NULL; ExFreePoolWithTag(EventHandler, MS_SAMPLE_ANALOG_POOL_TAG); EventHandler = NULL; }
NTSTATUS NewZwMapViewOfSection( HANDLE SectionHandle, HANDLE ProcessHandle, PVOID *BaseAddress, ULONG ZeroBits, ULONG CommitSize, PLARGE_INTEGER SectionOffset, PSIZE_T ViewSize, SECTION_INHERIT InheritDisposition, ULONG AllocationType, ULONG Protect ) { NTSTATUS status; #ifdef DEBUG NTSTATUS rtn; PVOID Object; WCHAR buf[1024]; rtn= ObReferenceObjectByHandle(SectionHandle, 0, 0, KernelMode, &Object, NULL); if (rtn==STATUS_SUCCESS) { int bytes; rtn=ObQueryNameString(Object, (PUNICODE_STRING)buf, sizeof(buf), &bytes); ObDereferenceObject(Object); if (rtn==STATUS_SUCCESS) { WCHAR *p = ((PUNICODE_STRING)buf)->Buffer; debugOutput(L"MapViewOfSection "); debugOutput(p); if ((Protect&PAGE_READWRITE) || (Protect&PAGE_EXECUTE_READWRITE)) { swprintf(buf,L" protect: 0x%lx\n", Protect); debugOutput(buf); } debugOutput(L"\n"); } } #endif status = (OldZwMapViewOfSection)(SectionHandle, ProcessHandle, BaseAddress, ZeroBits, CommitSize, SectionOffset, ViewSize, InheritDisposition, AllocationType, Protect); return status; }
NTSTATUS OobEditInit( _Out_ STREAM_EDITOR* streamEditor ) { NTSTATUS status = STATUS_SUCCESS; HANDLE threadHandle; streamEditor->editInline = FALSE; KeInitializeSpinLock(&streamEditor->oobEditInfo.editLock); KeInitializeEvent( &streamEditor->oobEditInfo.editEvent, NotificationEvent, FALSE ); streamEditor->oobEditInfo.busyThreshold = 32 * 1024; streamEditor->oobEditInfo.editState = OOB_EDIT_IDLE; InitializeListHead(&streamEditor->oobEditInfo.outgoingDataQueue); status = PsCreateSystemThread( &threadHandle, THREAD_ALL_ACCESS, NULL, NULL, NULL, StreamOobEditWorker, &gStreamEditor ); if (!NT_SUCCESS(status)) { goto Exit; } status = ObReferenceObjectByHandle( threadHandle, 0, NULL, KernelMode, &gThreadObj, NULL ); NT_ASSERT(NT_SUCCESS(status)); ZwClose(threadHandle); Exit: return status; }
NTSTATUS NTAPI NtQueryInformationPort( IN HANDLE PortHandle OPTIONAL, IN PORT_INFORMATION_CLASS PortInformationClass, OUT PVOID PortInformation, IN ULONG Length, OUT PULONG ReturnLength OPTIONAL ) { KPROCESSOR_MODE PreviousMode; NTSTATUS Status; PLPCP_PORT_OBJECT PortObject; PAGED_CODE(); // // Get previous processor mode and probe output argument if necessary. // PreviousMode = KeGetPreviousMode(); if (PreviousMode != KernelMode) { try { ProbeForWrite( PortInformation, Length, sizeof( ULONG ) ); if (ARGUMENT_PRESENT( ReturnLength )) { ProbeForWriteUlong( ReturnLength ); } } except( EXCEPTION_EXECUTE_HANDLER ) { return( GetExceptionCode() ); } } if (ARGUMENT_PRESENT( PortHandle )) { Status = ObReferenceObjectByHandle( PortHandle, GENERIC_READ, LpcPortObjectType, PreviousMode, &PortObject, NULL ); if (!NT_SUCCESS( Status )) { return( Status ); } ObDereferenceObject( PortObject ); return STATUS_SUCCESS; } else { return STATUS_INVALID_INFO_CLASS; } }
EXTERN_C static NTSTATUS ScvnpWriteFile(_In_ PCFLT_RELATED_OBJECTS FltObjects, _In_ const wchar_t *OutPathW, _In_ void *Buffer, _In_ ULONG BufferSize, _In_ ULONG CreateDisposition) { PAGED_CODE(); UNICODE_STRING outPath = {}; RtlInitUnicodeString(&outPath, OutPathW); OBJECT_ATTRIBUTES objAttr = RTL_INIT_OBJECT_ATTRIBUTES( &outPath, OBJ_KERNEL_HANDLE | OBJ_CASE_INSENSITIVE); HANDLE fileHandle = nullptr; IO_STATUS_BLOCK ioStatus = {}; auto status = FltCreateFile( FltObjects->Filter, FltObjects->Instance, &fileHandle, GENERIC_WRITE, &objAttr, &ioStatus, nullptr, FILE_ATTRIBUTE_NORMAL, 0, CreateDisposition, FILE_SEQUENTIAL_ONLY | FILE_SYNCHRONOUS_IO_NONALERT | FILE_NON_DIRECTORY_FILE, nullptr, 0, 0); if (status == STATUS_OBJECT_NAME_COLLISION || status == STATUS_DELETE_PENDING) { return status; } if (!NT_SUCCESS(status)) { LOG_ERROR_SAFE("FltCreateFile failed (%08x) for %S", status, OutPathW); return status; } PFILE_OBJECT fileObject = nullptr; status = ObReferenceObjectByHandle(fileHandle, 0, nullptr, KernelMode, reinterpret_cast<void **>(&fileObject), nullptr); if (!NT_SUCCESS(status)) { LOG_ERROR_SAFE("ObReferenceObjectByHandle failed (%08x) for %S", status, OutPathW); goto End; } status = FltWriteFile(FltObjects->Instance, fileObject, nullptr, BufferSize, Buffer, 0, nullptr, nullptr, nullptr); if (!NT_SUCCESS(status)) { LOG_ERROR_SAFE("FltWriteFile failed (%08x) for %S", status, OutPathW); goto End; } End: if (fileObject) { ObDereferenceObject(fileObject); } if (fileHandle) { FltClose(fileHandle); } return status; }
NTSTATUS NtClearEvent ( __in HANDLE EventHandle ) /*++ Routine Description: This function sets an event object to a Not-Signaled state. Arguments: EventHandle - Supplies a handle to an event object. Return Value: NTSTATUS. --*/ { PVOID Event; NTSTATUS Status; // // Reference event object by handle. // Status = ObReferenceObjectByHandle(EventHandle, EVENT_MODIFY_STATE, ExEventObjectType, KeGetPreviousMode(), &Event, NULL); // // If the reference was successful, then set the state of the event // object to Not-Signaled and dereference event object. // if (NT_SUCCESS(Status)) { PERFINFO_DECLARE_OBJECT(Event); KeClearEvent((PKEVENT)Event); ObDereferenceObject(Event); } // // Return service status. // return Status; }
//Hook 后的新函数 NTSTATUS NewZwCreateFile( OUT PHANDLE FileHandle, IN ACCESS_MASK DesiredAccess, IN POBJECT_ATTRIBUTES ObjectAttributes, OUT PIO_STATUS_BLOCK IoStatusBlock, IN PLARGE_INTEGER AllocationSize OPTIONAL, IN ULONG FileAttributes, IN ULONG ShareAccess, IN ULONG CreateDisposition, IN ULONG CreateOptions, IN PVOID EaBuffer OPTIONAL, IN ULONG EaLength ) { NTSTATUS ntStatus = STATUS_SUCCESS; PFILE_OBJECT file; OBJECT_HANDLE_INFORMATION info; //调用原函数 ntStatus = OldZwCreateFile( FileHandle, DesiredAccess, ObjectAttributes, IoStatusBlock, AllocationSize, FileAttributes, ShareAccess, CreateDisposition, CreateOptions, EaBuffer, EaLength ); DbgPrint("SSDT: ZwCreateFile Invoked (%u) !", ulCount++); /////////////////////// 通过 Handle 得到文件名 ObReferenceObjectByHandle(ObjectAttributes->RootDirectory, 0, 0, \ KernelMode, &file, &info ); DbgPrint("SSDT: FileHandle %08X", FileHandle); if(file) { DbgPrint("SSDT: FileName = %ws%ws", \ file->FileName, ObjectAttributes->ObjectName->Buffer); ObDereferenceObject(file); //减少引用计数 } else { DbgPrint("SSDT: FileName = %ws",ObjectAttributes->ObjectName->Buffer); } return ntStatus; }
NTSTATUS NTAPI Pin_fnDeviceIoControl( PDEVICE_OBJECT DeviceObject, PIRP Irp) { PDISPATCH_CONTEXT Context; NTSTATUS Status; ULONG BytesReturned; PFILE_OBJECT FileObject = NULL; PIO_STACK_LOCATION IoStack; DPRINT("Pin_fnDeviceIoControl called DeviceObject %p Irp %p\n", DeviceObject, Irp); /* Get current stack location */ IoStack = IoGetCurrentIrpStackLocation(Irp); /* The dispatch context is stored in the FsContext member */ Context = (PDISPATCH_CONTEXT)IoStack->FileObject->FsContext; /* Sanity check */ ASSERT(Context); /* acquire real pin file object */ Status = ObReferenceObjectByHandle(Context->Handle, GENERIC_WRITE, *IoFileObjectType, KernelMode, (PVOID*)&FileObject, NULL); if (!NT_SUCCESS(Status)) { Irp->IoStatus.Information = 0; Irp->IoStatus.Status = Status; /* Complete the irp */ IoCompleteRequest(Irp, IO_NO_INCREMENT); return Status; } /* Re-dispatch the request to the real target pin */ Status = KsSynchronousIoControlDevice(FileObject, KernelMode, IoStack->Parameters.DeviceIoControl.IoControlCode, IoStack->Parameters.DeviceIoControl.Type3InputBuffer, IoStack->Parameters.DeviceIoControl.InputBufferLength, Irp->UserBuffer, IoStack->Parameters.DeviceIoControl.OutputBufferLength, &BytesReturned); /* release file object */ ObDereferenceObject(FileObject); /* Save status and information */ Irp->IoStatus.Information = BytesReturned; Irp->IoStatus.Status = Status; /* Complete the irp */ IoCompleteRequest(Irp, IO_NO_INCREMENT); /* Done */ return Status; }
BOOLEAN xixfs_NetEvtTerminate(PNETEVTCTX NetEvtCtx) { VOID *ThreadObject ; LARGE_INTEGER TimeOut ; NTSTATUS ntStatus ; PAGED_CODE(); DebugTrace(DEBUG_LEVEL_TRACE, DEBUG_TARGET_HOSTCOM, ("Exit xixfs_NetEvtTerminate \n")); ASSERT(KeGetCurrentIrql() <= PASSIVE_LEVEL) ; KeSetEvent(&NetEvtCtx->ShutdownEvent, IO_NO_INCREMENT, FALSE) ; ntStatus = ObReferenceObjectByHandle( NetEvtCtx->HThread, FILE_READ_DATA, NULL, KernelMode, &ThreadObject, NULL ) ; if(!NT_SUCCESS(ntStatus)) { DebugTrace(DEBUG_LEVEL_ERROR, DEBUG_TARGET_ALL, ( "[LFS] xixfs_NetEvtTerminate: referencing to the thread object failed\n")) ; goto out ; } TimeOut.QuadPart = - 20 * 10000 ; // 20 sec ntStatus = KeWaitForSingleObject( ThreadObject, Executive, KernelMode, FALSE, &TimeOut ) ; if(!NT_SUCCESS(ntStatus)) { DebugTrace(DEBUG_LEVEL_ERROR, DEBUG_TARGET_ALL, ( "[LFS] xixfs_NetEvtTerminate: waiting for the thread failed\n")) ; } ObDereferenceObject(ThreadObject) ; DebugTrace(DEBUG_LEVEL_INFO, DEBUG_TARGET_HOSTCOM, ( "[LFS] xixfs_NetEvtTerminate: Shut down successfully.\n")) ; out: DebugTrace(DEBUG_LEVEL_TRACE, DEBUG_TARGET_HOSTCOM, ("Exit xixfs_NetEvtTerminate \n")); return TRUE ; }
static NTSTATUS V4vCtrlInitializeFile(XENV4V_CONTEXT *ctx, V4V_INIT_VALUES *invs, PIRP irp) { NTSTATUS status = STATUS_SUCCESS; if (ctx == NULL) { TraceError(("no file context!\n")); return STATUS_INVALID_HANDLE; } if (invs->rxEvent == NULL) { TraceError(("no event handle!\n")); return STATUS_INVALID_HANDLE; } do { // Reference the event objects status = ObReferenceObjectByHandle(invs->rxEvent, EVENT_MODIFY_STATE, *ExEventObjectType, irp->RequestorMode, (void **)&ctx->kevReceive, NULL); if (!NT_SUCCESS(status)) { TraceError(("failed to get a reference to the receive event - error: 0x%x\n", status)); break; } ctx->ringLength = invs->ringLength; // Straighten out the ring if (ctx->ringLength > PAGE_SIZE) { ctx->ringLength = (ctx->ringLength + XENV4V_RING_MULT - 1) & ~(XENV4V_RING_MULT - 1); } else { ctx->ringLength = PAGE_SIZE; // minimum to guarantee page alignment } InterlockedExchange(&ctx->state, XENV4V_STATE_IDLE); } while (FALSE); if (!NT_SUCCESS(status)) { // If it failed, undo everything if (ctx->kevReceive != NULL) { ObDereferenceObject(ctx->kevReceive); ctx->kevReceive = NULL; } } return status; }
CScopedHandleObj( __in HANDLE hdnl, __in ACCESS_MASK mask = GENERIC_READ ) : m_obj(nullptr) { ObReferenceObjectByHandle( hdnl, mask, nullptr, KernelMode, reinterpret_cast<void**>(&m_obj), nullptr); }
NTSTATUS RegSetValueKey( IN HANDLE KeyHandle, IN PUNICODE_STRING ValueName, IN ULONG TitleIndex, IN ULONG Type, IN PVOID Data, IN ULONG DataSize ) { WCHAR szFullPath[MAXPATHLEN] = {0}; PVOID pKeyObj = NULL; ULONG ulRet = 0; PUNICODE_STRING fullUniName = NULL; int i; ULONG nAllowd = 1; WCHAR szValueName[256] = {0}; WCHAR szValue[512] = {0}; if(FALSE == IsGuardStart()) goto allowed; if(STATUS_SUCCESS == ObReferenceObjectByHandle(KeyHandle, 0, NULL, KernelMode, &pKeyObj, NULL)) { PINNERPACK_LIST pList; LONG nSubType = 0; fullUniName = ExAllocateFromPagedLookasideList(&gRegMonLooaside); if(NULL == fullUniName) goto allowed; fullUniName->MaximumLength = MAXPATHLEN * 2; ObQueryNameString(pKeyObj, (POBJECT_NAME_INFORMATION)fullUniName, MAXPATHLEN, &ulRet); ObDereferenceObject(pKeyObj); // 转换路径 ConvertKeyPath(szFullPath, fullUniName->Buffer, MAXPATHLEN); ExFreeToPagedLookasideList(&gRegMonLooaside, fullUniName); // 复制路径 wcsncpy(szValueName, (NULL != ValueName)?ValueName->Buffer:L"" , (NULL != ValueName)?ValueName->Length:0); // 比较路径 if(FALSE == IsRegGuardPath(szFullPath, szValueName, &nSubType)) goto allowed; if(REG_SZ == Type) { wcsncpy(szValue, Data, arrayof(szValueName)); } // 到用户求请 if(FALSE != CheckRequestIsAllowed(MAKEGUARDTYPE(MASK_GUARDLITE_REGMON, nSubType) , szFullPath, szValueName, szValue)) { goto allowed; } } return STATUS_ACCESS_DENIED; allowed: return RealRegSetValueKey(KeyHandle, ValueName, TitleIndex, Type, Data, DataSize); }
NTSTATUS NtAlertThread( IN HANDLE ThreadHandle ) /*++ Routine Description: This function alerts the target thread using the previous mode as the mode of the alert. Arguments: ThreadHandle - Supplies an open handle to the thread to be alerted Return Value: TBD --*/ { PETHREAD Thread; NTSTATUS st; KPROCESSOR_MODE Mode; PAGED_CODE(); Mode = KeGetPreviousMode(); st = ObReferenceObjectByHandle( ThreadHandle, THREAD_ALERT, PsThreadType, Mode, (PVOID *)&Thread, NULL ); if ( !NT_SUCCESS(st) ) { return st; } (VOID) KeAlertThread(&Thread->Tcb,Mode); ObDereferenceObject(Thread); return STATUS_SUCCESS; }
NTSTATUS NTAPI CompBattGetDeviceObjectPointer(IN PUNICODE_STRING DeviceName, IN ACCESS_MASK DesiredAccess, OUT PFILE_OBJECT *FileObject, OUT PDEVICE_OBJECT *DeviceObject) { NTSTATUS Status; OBJECT_ATTRIBUTES ObjectAttributes; IO_STATUS_BLOCK IoStatusBlock; PFILE_OBJECT LocalFileObject; HANDLE DeviceHandle; PAGED_CODE(); /* Open a file object handle to the device */ InitializeObjectAttributes(&ObjectAttributes, DeviceName, 0, NULL, NULL); Status = ZwCreateFile(&DeviceHandle, DesiredAccess, &ObjectAttributes, &IoStatusBlock, NULL, 0, FILE_SHARE_READ | FILE_SHARE_WRITE, FILE_OPEN, 0, NULL, 0); if (NT_SUCCESS(Status)) { /* Reference the file object */ Status = ObReferenceObjectByHandle(DeviceHandle, 0, IoFileObjectType, KernelMode, (PVOID)&LocalFileObject, NULL); if (NT_SUCCESS(Status)) { /* Return the FO and the associated DO */ *FileObject = LocalFileObject; *DeviceObject = IoGetRelatedDeviceObject(LocalFileObject); } /* Close the handle */ ZwClose(DeviceHandle); } /* Return status */ return Status; }
BOOL xxxRegisterUserHungAppHandlers( PFNW32ET pfnW32EndTask, HANDLE hEventWowExec) { BOOL bRetVal; PPROCESSINFO ppi; PWOWPROCESSINFO pwpi; // // Allocate the per wow process info stuff // ensuring the memory is Zero init. // pwpi = (PWOWPROCESSINFO) UserAllocPoolWithQuota(sizeof(WOWPROCESSINFO), TAG_WOW); if (!pwpi) return FALSE; RtlZeroMemory(pwpi, sizeof(*pwpi)); // // Reference the WowExec event for kernel access // bRetVal = NT_SUCCESS(ObReferenceObjectByHandle( hEventWowExec, EVENT_ALL_ACCESS, NULL, UserMode, &pwpi->pEventWowExec, NULL )); // // if sucess then intialize the pwpi, ppi structs // else free allocated memory // if (bRetVal) { pwpi->hEventWowExecClient = hEventWowExec; pwpi->lpfnWowExitTask = (DWORD)pfnW32EndTask; ppi = PpiCurrent(); ppi->pwpi = pwpi; // add to the list, order doesn't matter pwpi->pwpiNext = gpwpiFirstWow; gpwpiFirstWow = pwpi; } else { UserFreePool(pwpi); } return bRetVal; }
/* * TDI_ASSOCIATE_ADDRESS handler * * With help of this routine we can get address object by connection object * and get connection object by connection context and address object */ int tdi_associate_address(PIRP irp, PIO_STACK_LOCATION irps, struct completion *completion) { HANDLE addr_handle = ((TDI_REQUEST_KERNEL_ASSOCIATE *)(&irps->Parameters))->AddressHandle; PFILE_OBJECT addrobj = NULL; NTSTATUS status; struct ot_entry *ote_conn = NULL; KIRQL irql; int result = FILTER_DENY; KdPrint(("[tdi_fw] tdi_associate_address: devobj 0x%x; connobj 0x%x\n", irps->DeviceObject, irps->FileObject)); status = ObReferenceObjectByHandle(addr_handle, GENERIC_READ, NULL, KernelMode, &addrobj, NULL); if (status != STATUS_SUCCESS) { KdPrint(("[tdi_fw] tdi_associate_address: ObReferenceObjectByHandle: 0x%x\n", status)); goto done; } KdPrint(("[tdi_fw] tdi_associate_address: connobj = 0x%x ---> addrobj = 0x%x\n", irps->FileObject, addrobj)); // associate addrobj with connobj ote_conn = ot_find_fileobj(irps->FileObject, &irql); if (ote_conn == NULL) { KdPrint(("[tdi_fw] tdi_associate_address: ot_find_fileobj(0x%x)\n", irps->FileObject)); goto done; } ote_conn->associated_fileobj = addrobj; // add (conn_ctx, addrobj)->connobj status = ot_add_conn_ctx(addrobj, ote_conn->conn_ctx, irps->FileObject); if (status != STATUS_SUCCESS) { KdPrint(("[tdi_fw] tdi_associate_address: ot_add_conn_ctx: 0x%x\n", status)); goto done; } result = FILTER_ALLOW; done: if (addrobj != NULL) ObDereferenceObject(addrobj); // cleanup if (ote_conn != NULL) KeReleaseSpinLock(&g_ot_hash_guard, irql); return result; }
void DebugPrintInit(char* _DriverName) { HANDLE threadHandle; NTSTATUS status; // Copy the driver's name out of INIT code segment DriverNameLen = 1 + ANSIstrlen(_DriverName); DriverName = (char*)ExAllocatePool(NonPagedPool,DriverNameLen); if( DriverName==NULL) return; RtlCopyMemory( DriverName, _DriverName, DriverNameLen); ///////////////////////////////////////////////////////////////////////// // Prepare for thread start ExitNow = FALSE; KeInitializeEvent(&ThreadEvent, SynchronizationEvent, FALSE); KeInitializeEvent(&ThreadExiting, SynchronizationEvent, FALSE); // Initialise event list KeInitializeSpinLock(&EventListLock); InitializeListHead(&EventList); ///////////////////////////////////////////////////////////////////////// // Start system thread to write events to DebugPrint driver status = PsCreateSystemThread( &threadHandle, THREAD_ALL_ACCESS, NULL, NULL, NULL, DebugPrintSystemThread, NULL); if( !NT_SUCCESS(status)) return; ///////////////////////////////////////////////////////////////////////// // Save a pointer to thread and close handle. status = ObReferenceObjectByHandle( threadHandle, THREAD_ALL_ACCESS, NULL, KernelMode, &ThreadObjectPointer, NULL); if( NT_SUCCESS(status)) ZwClose(threadHandle); else { // Uh oh... force thread to exit ExitNow = TRUE; KeSetEvent( &ThreadEvent, 0, FALSE); return; } DebugPrintStarted = TRUE; // Send event that we've started logging DebugPrintMsg("DebugPrint logging started"); }
NTSTATUS TdiCreateAddress( PHANDLE Handle, PFILE_OBJECT *AddressObject, ULONG Type, ULONG Address, USHORT Port ) { CHAR Buffer[sizeof (FILE_FULL_EA_INFORMATION) + TDI_TRANSPORT_ADDRESS_LENGTH + sizeof(TA_IP_ADDRESS)]; NTSTATUS ntStatus; OBJECT_ATTRIBUTES Attr; IO_STATUS_BLOCK IoStatus; PTA_IP_ADDRESS Sin; PFILE_FULL_EA_INFORMATION Ea = (PFILE_FULL_EA_INFORMATION)&Buffer; switch(Type) { case SOCK_STREAM: InitializeObjectAttributes(&Attr, &g_TcpDeviceName, OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE, 0, 0); break; case SOCK_DGRAM: InitializeObjectAttributes(&Attr, &g_UdpDeviceName, OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE, 0, 0); break; default: return(STATUS_INVALID_PARAMETER); break; } Ea->NextEntryOffset = 0; Ea->Flags = 0; Ea->EaNameLength = TDI_TRANSPORT_ADDRESS_LENGTH; Ea->EaValueLength = sizeof (TA_IP_ADDRESS); RtlCopyMemory(Ea->EaName, TdiTransportAddress, Ea->EaNameLength + 1); Sin = (PTA_IP_ADDRESS)(Ea->EaName + Ea->EaNameLength + 1); Sin->TAAddressCount = 1; Sin->Address[0].AddressLength = TDI_ADDRESS_LENGTH_IP; Sin->Address[0].AddressType = TDI_ADDRESS_TYPE_IP; Sin->Address[0].Address[0].sin_port = Port; Sin->Address[0].Address[0].in_addr = Address; RtlZeroMemory(Sin->Address[0].Address[0].sin_zero, sizeof Sin->Address[0].Address[0].sin_zero); ntStatus = ZwCreateFile(Handle, 0, &Attr, &IoStatus, 0, FILE_ATTRIBUTE_NORMAL, 0, FILE_OPEN, 0, Ea, sizeof(Buffer)); if (NT_SUCCESS(ntStatus)) ntStatus = ObReferenceObjectByHandle(*Handle, GENERIC_READ | GENERIC_WRITE, 0, KernelMode, (PVOID *)AddressObject, 0); return(ntStatus); }
/*! . \param [in] \param [out] \param [in,out] \pre \post \return */ NTSTATUS FlTimerThreadCreate() { NTSTATUS status = STATUS_SUCCESS; HANDLE handle; OBJECT_ATTRIBUTES objectAttribs; TimerThreadStopExec = FALSE; InitializeObjectAttributes( &objectAttribs, NULL, OBJ_KERNEL_HANDLE, NULL, NULL); KeInitializeEvent(&ThreadSleepWakeup, SynchronizationEvent, FALSE); DriverInfoData->TimerThreadSleepWakeup = &ThreadSleepWakeup; KeInitializeTimer(&Timer); DriverInfoData->Timer = &Timer; status = PsCreateSystemThread(&handle, THREAD_ALL_ACCESS, &objectAttribs, NULL, NULL, (PKSTART_ROUTINE)TimerThreadExecRoutine, NULL); if (!NT_SUCCESS(status)) { KeCancelTimer(&Timer); DriverInfoData->Timer = NULL; DriverInfoData->TimerThreadSleepWakeup = NULL; DBGPRINT_ARG1("[flmonflt] PsCreateSystemThread failed: 0x%X\n", status); } else { ObReferenceObjectByHandle(handle, THREAD_ALL_ACCESS, NULL, KernelMode, &DriverInfoData->TimerThread, NULL); ZwClose(handle); DBGPRINT("[flmonflt] PsCreateSystemThread succeeded.\n"); } return status; }
NTSTATUS NTAPI AfdEnumEvents( PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATION IrpSp ) { PFILE_OBJECT FileObject = IrpSp->FileObject; PAFD_ENUM_NETWORK_EVENTS_INFO EnumReq = (PAFD_ENUM_NETWORK_EVENTS_INFO)LockRequest( Irp, IrpSp, TRUE, NULL ); PAFD_FCB FCB = FileObject->FsContext; PKEVENT UserEvent; NTSTATUS Status; UNREFERENCED_PARAMETER(DeviceObject); AFD_DbgPrint(MID_TRACE,("Called (FCB %p)\n", FCB)); if( !SocketAcquireStateLock( FCB ) ) { return LostSocket( Irp ); } if ( !EnumReq ) { return UnlockAndMaybeComplete( FCB, STATUS_NO_MEMORY, Irp, 0 ); } Status = ObReferenceObjectByHandle(EnumReq->Event, EVENT_ALL_ACCESS, ExEventObjectType, UserMode, (PVOID *)&UserEvent, NULL); if (!NT_SUCCESS(Status)) { AFD_DbgPrint(MIN_TRACE,("Unable to reference event %x\n", Status)); return UnlockAndMaybeComplete(FCB, Status, Irp, 0); } /* Clear the event */ KeClearEvent(UserEvent); ObDereferenceObject(UserEvent); /* Copy the poll state, masking out disabled events */ EnumReq->PollEvents = (FCB->PollState & ~FCB->EventSelectDisabled); RtlCopyMemory( EnumReq->EventStatus, FCB->PollStatus, sizeof(EnumReq->EventStatus) ); /* Disable the events that triggered the select until the reenabling function is called */ FCB->EventSelectDisabled |= (FCB->PollState & FCB->EventSelectTriggers); return UnlockAndMaybeComplete( FCB, STATUS_SUCCESS, Irp, 0 ); }
int getFullPath(PWCHAR buf, USHORT bufsize, POBJECT_ATTRIBUTES oa) { NTSTATUS rtn; PVOID Object; int curlen=0; buf[0]=L'\0'; if (!oa) return 0; if (oa->RootDirectory != NULL) { rtn= ObReferenceObjectByHandle(oa->RootDirectory, 0, 0, KernelMode, &Object, NULL); if (rtn==STATUS_SUCCESS) { int bytes; rtn=ObQueryNameString(Object, (PUNICODE_STRING)buf, bufsize, &bytes); ObDereferenceObject(Object); if (rtn==STATUS_SUCCESS) { WCHAR *p = ((PUNICODE_STRING)buf)->Buffer, *q=buf; USHORT len = (((PUNICODE_STRING)buf)->Length)/sizeof(WCHAR); if ((len+2)*sizeof(WCHAR)<bufsize) { while (len-->0 && *p!=L'\0') { *q++ = *p++; ++curlen; } *q++=OBJ_NAME_PATH_SEPARATOR; ++curlen; } *q = L'\0'; } } } if (oa->ObjectName && oa->Length+(curlen+1)*sizeof(WCHAR) < bufsize) { curlen += uwcscat(buf+curlen, oa->ObjectName); } else *buf = L'\0'; return curlen; }
NTSTATUS SendDIOC(PUNICODE_STRING uDeviceName, ULONG IoControlCode,PVOID InputBuffer,ULONG InputBufferLength,PVOID OutputBuffer,ULONG OutputBufferLength) { HANDLE hPidDrv; OBJECT_ATTRIBUTES ObjAttr; IO_STATUS_BLOCK ioStatus; PDEVICE_OBJECT DevObj; PFILE_OBJECT fileObject; NTSTATUS ntStatus; KEVENT Event; PIRP Irp; // PIO_STACK_LOCATION irpSp; // RtlInitUnicodeString(&us,L"\\Device\\"KLPID_NAME); InitializeObjectAttributes(&ObjAttr,uDeviceName,OBJ_CASE_INSENSITIVE,NULL,NULL); ntStatus=ZwCreateFile(&hPidDrv,SYNCHRONIZE|FILE_ANY_ACCESS,&ObjAttr,&ioStatus,NULL,0,FILE_SHARE_READ|FILE_SHARE_WRITE,FILE_OPEN,FILE_SYNCHRONOUS_IO_NONALERT,NULL,0); if(NT_SUCCESS(ntStatus)) { ntStatus=ObReferenceObjectByHandle(hPidDrv,FILE_READ_DATA,NULL,KernelMode,(PVOID*)&fileObject,NULL); if(NT_SUCCESS(ntStatus)) { if((DevObj=IoGetRelatedDeviceObject(fileObject))!=NULL) { KeInitializeEvent(&Event,NotificationEvent,FALSE); Irp=IoBuildDeviceIoControlRequest(IoControlCode,DevObj,InputBuffer,InputBufferLength,OutputBuffer,OutputBufferLength,FALSE,&Event,&ioStatus); if(Irp!=NULL) { // irpSp=IoGetNextIrpStackLocation(Irp); // irpSp->FileObject = fileObject; ntStatus=IoCallDriver(DevObj,Irp); if(ntStatus==STATUS_PENDING) { KeWaitForSingleObject(&Event,Executive,KernelMode,FALSE,(PLARGE_INTEGER)NULL); ntStatus = ioStatus.Status; } } else { // HOOKKdPrint(4, ("HOOK: IoBuildDeviceIoControlRequest failed\n")); ntStatus=STATUS_UNSUCCESSFUL; } } else { // HOOKKdPrint(1, ("HOOK: IoGetRelatedDeviceObject %S failed \n",us.Buffer)); ntStatus=STATUS_UNSUCCESSFUL; } ObDereferenceObject(fileObject); } else { // HOOKKdPrint(1, ("HOOK: ObReferenceObjectByHandle %S failed status=%x\n",us.Buffer,ntStatus)); } ZwClose(hPidDrv); } else { // HOOKKdPrint(1, ("HOOK: ZwCreateFile %S failed status=%x\n",us.Buffer,ntStatus)); } return ntStatus; }
NTSTATUS NTAPI hk_NtClose(HANDLE Handle) { PVOID object = NULL; NTSTATUS status = ObReferenceObjectByHandle(Handle, 0, NULL, ExGetPreviousMode(), &object, NULL); // // This will fail with an invalid handle // if (!NT_SUCCESS(status)) return STATUS_INVALID_HANDLE; // // Continue execution normally // ObDereferenceObject(object); return Nt::NtClose(Handle); }
NTSTATUS OpenDevice( IN PUNICODE_STRING DeviceName, IN PHANDLE HandleOut, IN PFILE_OBJECT * FileObjectOut) { NTSTATUS Status; HANDLE NodeHandle; PFILE_OBJECT FileObject; OBJECT_ATTRIBUTES ObjectAttributes; IO_STATUS_BLOCK IoStatusBlock; InitializeObjectAttributes(&ObjectAttributes, DeviceName, OBJ_KERNEL_HANDLE | OBJ_CASE_INSENSITIVE, NULL, NULL); Status = ZwCreateFile(&NodeHandle, GENERIC_READ | GENERIC_WRITE | SYNCHRONIZE, &ObjectAttributes, &IoStatusBlock, NULL, 0, 0, FILE_OPEN, FILE_SYNCHRONOUS_IO_NONALERT, NULL, 0); if (!NT_SUCCESS(Status)) { DPRINT("ZwCreateFile failed with %x %S\n", Status, DeviceName->Buffer); return Status; } Status = ObReferenceObjectByHandle(NodeHandle, GENERIC_READ | GENERIC_WRITE, IoFileObjectType, KernelMode, (PVOID*)&FileObject, NULL); if (!NT_SUCCESS(Status)) { ZwClose(NodeHandle); DPRINT("ObReferenceObjectByHandle failed with %x\n", Status); return Status; } *HandleOut = NodeHandle; *FileObjectOut = FileObject; return Status; }