VOID CBTdPostOperationCallback ( _In_ PVOID RegistrationContext, _In_ POB_POST_OPERATION_INFORMATION PostInfo ) { PTD_CALLBACK_REGISTRATION CallbackRegistration = (PTD_CALLBACK_REGISTRATION)RegistrationContext; TdCheckAndFreeCallContext (PostInfo, CallbackRegistration); if (PostInfo->ObjectType == *PsProcessType) { // // Ignore requests for processes other than our target process. // if (CallbackRegistration->TargetProcess != NULL && CallbackRegistration->TargetProcess != PostInfo->Object ) { return; } // // Also ignore requests that are trying to open/duplicate the current // process. // if (PostInfo->Object == PsGetCurrentProcess()) { return; } } else if (PostInfo->ObjectType == *PsThreadType) { HANDLE ProcessIdOfTargetThread = PsGetThreadProcessId ((PETHREAD)PostInfo->Object); // // Ignore requests for threads belonging to processes other than our // target process. // if (CallbackRegistration->TargetProcess != NULL && CallbackRegistration->TargetProcessId != ProcessIdOfTargetThread ) { return; } // // Also ignore requests for threads belonging to the current processes. // if (ProcessIdOfTargetThread == PsGetCurrentProcessId()) { return; } } else { TD_ASSERT (FALSE); } }
VOID NDISLWF_ReceiveNetBufferListsHandler ( NDIS_HANDLE FilterModuleContext, PNET_BUFFER_LIST NetBufferLists, NDIS_PORT_NUMBER PortNumber, ULONG NumberOfNetBufferLists, ULONG ReceiveFlags ) { PNDISLWF_CONTEXT FilterContext = (PNDISLWF_CONTEXT)FilterModuleContext; // process the NBL chain to determine if should be allowed or rejected if ( ProcessNblChain ( NetBufferLists ) ) { DPF(("%s!%s [%x.%x] NBL=%p BLOCKED\n", __MODULE__, __FUNCTION__, PsGetCurrentProcessId(), PsGetCurrentThreadId(), NetBufferLists )); // Step #1 : Return the NBL chain to the caller instead of indicating it up to // the driver above (NdisFReturnNetBufferLists()) // ensure that the ReceiveFlags are properly translated to ReturnFlags NdisFReturnNetBufferLists(FilterContext->FilterHandle, NetBufferLists, ReceiveFlags & NDIS_RECEIVE_FLAGS_DISPATCH_LEVEL); } else { // Step #2 : Indicate the NBL chain to the driver above (NdisFIndicateReceiveNetBufferLists()) NdisFIndicateReceiveNetBufferLists(FilterContext->FilterHandle, NetBufferLists, PortNumber, NumberOfNetBufferLists, ReceiveFlags); } } // NDISLWF_ReceiveNetBufferListsHandler()
NTSTATUS NewZwCreateSymbolicLinkObject(PHANDLE SymLinkHandle, ACCESS_MASK DesiredAccess, POBJECT_ATTRIBUTES ObjectAttributes, PUNICODE_STRING ObjectName ) { NTSTATUS status; if (restrictEnabled()) { if (ObjectName && ObjectName->Buffer && ObjectName->Length>0) { #ifdef DEBUG debugOutput(L"Incoming link to: "); debugOutput(ObjectName->Buffer); debugOutput(L"\n"); #endif if (_wcsicmp(ObjectName->Buffer, L"\\Device\\PhysicalMemory")==0) { WCHAR buf[200]; swprintf(buf, L"Blocking device/PhysicalMemory access, procid=0x%x\n", PsGetCurrentProcessId()); debugOutput(buf); return STATUS_ACCESS_DENIED; } } } status = (OldZwCreateSymbolicLinkObject)(SymLinkHandle, DesiredAccess, ObjectAttributes, ObjectName); return status; }
/* kd> kb ChildEBP RetAddr Args to Child f8afdaa8 805c62ae f8afdcf0 00000000 f8afdb44 DrvHide!LoadImageNotify+0x10 f8afdac8 805a4159 f8afdcf0 00000000 f8afdb44 nt!PsCallImageNotifyRoutines+0x36 f8afdc6c 80576483 f8afdcf0 00000000 00000000 nt!MmLoadSystemImage+0x9e5 f8afdd4c 8057688f 80000378 00000001 00000000 nt!IopLoadDriver+0x371 f8afdd74 80534c02 80000378 00000000 823c63c8 nt!IopLoadUnloadDriver+0x45 f8afddac 805c6160 b286ecf4 00000000 00000000 nt!ExpWorkerThread+0x100 f8afdddc 80541dd2 80534b02 00000001 00000000 nt!PspSystemThreadStartup+0x34 00000000 00000000 00000000 00000000 00000000 nt!KiThreadStartup+0x16 */ VOID LoadImageNotify( PUNICODE_STRING FullImageName, HANDLE ProcessId, // where image is mapped PIMAGE_INFO ImageInfo) { KeWaitForMutexObject(&m_GlobalMutex, Executive, KernelMode, FALSE, NULL); // check for kernel driver if (ProcessId == 0 && ImageInfo->SystemModeImage && !m_bFreeAreaFound && IsKnownDriver(FullImageName)) { PVOID TargetImageBase = ImageInfo->ImageBase; ULONG TargetImageSize = ImageInfo->ImageSize; DbgMsg( __FILE__, __LINE__, "%d '%wZ' is at "IFMT", size: %d\n", PsGetCurrentProcessId(), FullImageName, TargetImageBase, TargetImageSize ); // check for free area at the image discardable sections if (m_bFreeAreaFound = CheckForFreeArea(TargetImageBase, &m_FreeAreaRVA, &m_FreeAreaLength)) { m_FreeAreaVA = RVATOVA(TargetImageBase, m_FreeAreaRVA); DbgMsg(__FILE__, __LINE__, "Free area found!\n"); // hook image entry point HookImageEntry(TargetImageBase); } } KeReleaseMutex(&m_GlobalMutex, FALSE); }
/** * 钩子函数,进行模块过滤 */ NTSTATUS NTAPI MyMapViewOfSection(IN HANDLE SectionHandle, IN HANDLE ProcessHandle, IN OUT PVOID *BaseAddress, IN ULONG ZeroBits, IN ULONG CommitSize, IN OUT PLARGE_INTEGER SectionOffset OPTIONAL, IN OUT PULONG ViewSize, IN SECTION_INHERIT InheritDisposition, IN ULONG AllocationType, IN ULONG Protect) { NTSTATUS result; InterlockedIncrement(&g_HookCounter); if (IsProcessProtected((DWORD)PsGetCurrentProcessId()) && (LONG)ProcessHandle == 0xFFFFFFFF) { result = BkMapViewOfSection(SectionHandle, ProcessHandle, BaseAddress, ZeroBits, CommitSize, SectionOffset, ViewSize, InheritDisposition, AllocationType, Protect); } else result = NtMapViewOfSection(SectionHandle, ProcessHandle, BaseAddress, ZeroBits, CommitSize, SectionOffset, ViewSize, InheritDisposition, AllocationType, Protect); InterlockedDecrement(&g_HookCounter); return result; }
/* * TsmiPsImageHandler * * Purpose: * * Notify to catch VirtualBox dlls loading. * */ VOID TsmiPsImageHandler( _In_ PUNICODE_STRING FullImageName, _In_ HANDLE ProcessId, _In_ PIMAGE_INFO ImageInfo ) { ULONG c, l = 0; PAGED_CODE(); if ((FullImageName == NULL) || (ImageInfo == NULL) || (PsGetCurrentProcessId() != ProcessId)) return; if ((FullImageName->Buffer == NULL) || (FullImageName->Length == 0)) return; for (c = 0; c < (ULONG)FullImageName->Length / sizeof(WCHAR); c++) if (FullImageName->Buffer[c] == '\\') l = c + 1; // // Patch VBoxDD image. // if (_wcsnicmp(&FullImageName->Buffer[l], DDname, wcslen(DDname)) == 0) { if (NT_SUCCESS(TsmiPatchImage(&g_VBoxDD, ImageInfo))) { #ifdef _DEBUGMSG DbgPrint("[TSMI] DD patched\n"); #endif } } }
void AFSProcessNotify( IN HANDLE ParentId, IN HANDLE ProcessId, IN BOOLEAN Create) { // // If this is a create notification then update our tree, otherwise remove the // entry // if( Create) { AFSProcessCreate( ParentId, ProcessId, PsGetCurrentProcessId(), PsGetCurrentThreadId()); } else { AFSProcessDestroy( ProcessId); } return; }
BOOL IsProcessIntercepted( HOOK_ACL* LocalACL, ULONG InProcessID) #endif { /* Description: Please refer to LhIsThreadIntercepted() for more information. Returns: TRUE if the given thread is intercepted by the global AND local ACL, FALSE otherwise. */ ULONG CheckID; #ifndef DRIVER if(InThreadID == 0) CheckID = GetCurrentThreadId(); else CheckID = InThreadID; #else if(InProcessID == 0) CheckID = (ULONG)PsGetCurrentProcessId(); else CheckID = InProcessID; #endif if(ACLContains(&Unit.GlobalACL, CheckID)) { if(ACLContains(LocalACL, CheckID)) { if(LocalACL->IsExclusive) return FALSE; } else { if(!LocalACL->IsExclusive) return FALSE; } return !Unit.GlobalACL.IsExclusive; } else { if(ACLContains(LocalACL, CheckID)) { if(LocalACL->IsExclusive) return FALSE; } else { if(!LocalACL->IsExclusive) return FALSE; } return Unit.GlobalACL.IsExclusive; } }
static int vboxMpCrCtlConSetPID(PVBOXMP_CRCTLCON pCrCtlCon, uint32_t u32ClientID) { CRVBOXHGCMSETPID parms; int rc; parms.hdr.result = VERR_WRONG_ORDER; parms.hdr.u32ClientID = u32ClientID; parms.hdr.u32Function = SHCRGL_GUEST_FN_SET_PID; parms.hdr.cParms = SHCRGL_CPARMS_SET_PID; parms.u64PID.type = VMMDevHGCMParmType_64bit; parms.u64PID.u.value64 = (uint64_t)PsGetCurrentProcessId(); Assert(parms.u64PID.u.value64); rc = vboxCrCtlConCall(pCrCtlCon->hCrCtl, &parms.hdr, sizeof (parms)); if (RT_FAILURE(rc)) { WARN(("vboxCrCtlConCall failed, rc (%d)", rc)); return rc; } if (RT_FAILURE(parms.hdr.result)) { WARN(("set PID failed, rc (%d)", parms.hdr.result)); return parms.hdr.result; } return VINF_SUCCESS; }
BOOL ShareLockKImp::Unlock() { switch(m_LockType) { case LockTypeMutex: return KeReleaseMutex(&m_LockObject.m_Mutex.m_Mutex, FALSE); break; case LockTypeEvent: return KeSetEvent(&m_LockObject.m_Event.m_Event, IO_NO_INCREMENT, FALSE); break; case LockTypeSemaphore: return KeReleaseSemaphore(&m_LockObject.m_Semaphore.m_Semaphore, IO_NO_INCREMENT, 1, FALSE); break; case LockTypeSpinlock: break; case LockTypeNamedSpinlock: { if (m_LockObject.m_NamedSpinlock.m_lpHeader) { InterlockedCompareExchange(&m_LockObject.m_NamedSpinlock.m_lpHeader->m_LockProcId, 0, (LONG)PsGetCurrentProcessId()); return STATUS_SUCCESS; } } break; default: break; } return FALSE; }
BOOL APIENTRY NtUserLockWindowStation(HWINSTA hWindowStation) { PWINSTATION_OBJECT Object; NTSTATUS Status; TRACE("About to set process window station with handle (%p)\n", hWindowStation); if (gpidLogon != PsGetCurrentProcessId()) { ERR("Unauthorized process attempted to lock the window station!\n"); EngSetLastError(ERROR_ACCESS_DENIED); return FALSE; } Status = IntValidateWindowStationHandle(hWindowStation, UserMode, 0, &Object, 0); if (!NT_SUCCESS(Status)) { TRACE("Validation of window station handle (%p) failed\n", hWindowStation); SetLastNtError(Status); return FALSE; } Object->Flags |= WSS_LOCKED; ObDereferenceObject(Object); return TRUE; }
NTSTATUS IoCompletionRoutine( IN PDEVICE_OBJECT DeviceObject, IN PIRP Irp, IN PVOID Context ) { UNREFERENCED_PARAMETER(DeviceObject); UNREFERENCED_PARAMETER(Context); PAGED_CODE(); KdPrint(("SYS(%d:%d):IoCompletionRoutine!\n", PsGetCurrentProcessId(), PsGetCurrentThreadId())); *Irp->UserIosb = Irp->IoStatus; if (Irp->UserEvent) KeSetEvent(Irp->UserEvent, IO_NO_INCREMENT, 0); if (Irp->MdlAddress) { IoFreeMdl(Irp->MdlAddress); Irp->MdlAddress = NULL; } IoFreeIrp(Irp); return STATUS_MORE_PROCESSING_REQUIRED; }
VOID __stdcall Filter(ULONG ServiceId, ULONG TableBase, ULONG Argc, ULONG StackAddr) { ULONG pid = (ULONG)PsGetCurrentProcessId(); if (pid == g_nPid) { ULONG i; PXBoxData pData=(PXBoxData)ExAllocateFromNPagedLookasideList(&g_nPageList); if(!pData) return; if (StackAddr < MmUserProbeAddress) pData->bFromUser = 1; else pData->bFromUser = 0; if (TableBase == (ULONG)KeServiceDescriptorTable.ServiceTableBase) pData->bFromSSDT = 1; else pData->bFromSSDT = 0; if (Argc > 16) Argc = 16; pData->argc = (UCHAR)Argc; for (i = 0; i < Argc; ++i) pData->args[i] = ((PULONG)StackAddr)[i]; pData->pid = (ULONG)pid; pData->tid = (ULONG)PsGetCurrentThreadId(); pData->sid = ServiceId; KeQuerySystemTime(&pData->time); ExInterlockedInsertTailList(&g_linkListHead, &pData->ListEntry, &g_lock); KeReleaseSemaphore( &g_keySemaphore, 0, 1, FALSE ); } }
bool isProtectProcess(UINT32 uPPid) { UINT32 uiPPid[6] = {0}; bool bReturn = false; int iNum = 2; if( getPPidNum(uiPPid, sizeof(uiPPid)/sizeof(UINT32), iNum) ) { for(int i=0; i<iNum; i++) { UINT32 seek=(uiPPid[i])&0xfffffffffffffffc; if(seek == (UINT32)(uPPid) || (seek+1) == (UINT32)(uPPid) || (seek+2) == (UINT32)(uPPid) || (seek+3) == (UINT32)(uPPid) ) { if( (UINT32)PsGetCurrentProcessId() != uPPid) { kdP( ("protect the pid is: %d\n",uiPPid[i]) ); bReturn = true; } break; } } } return bReturn; }
VOID SpyLogPreOperationData ( _Inout_ PRECORD_LIST RecordList ) /*++ Routine Description: This is called from the pre-operation callback routine to copy the necessary information into the log record. NOTE: This code must be NON-PAGED because it can be called on the paging path. Arguments: Data - The Data structure that contains the information we want to record. FltObjects - Pointer to the io objects involved in this operation. RecordList - Where we want to save the data Return Value: None. --*/ { PRECORD_DATA recordData = &RecordList->LogRecord.Data; recordData->Flags = 0L; recordData->ProcessId = (FILE_ID)PsGetCurrentProcessId(); KeQuerySystemTime( &recordData->OriginatingTime ); }
void WmipWaitForCollectionEnabled( PBGUIDENTRY GuidEntry ) { PAGED_CODE(); WmipAssert((GuidEntry->Flags & GE_FLAG_COLLECTION_IN_PROGRESS) == GE_FLAG_COLLECTION_IN_PROGRESS); // // Collection Enable/Disable is in progress so // we cannot return just yet. Right now there could be a // disable request being processed and if we didn't wait, we // might get back to this caller before that disable request // got around to realizing that it needs to send and enable // request (needed by this thread's caller). So we'd have a // situation where a thread though that collection was enabled // but in reality it wasn't yet enabled. if ((GuidEntry->Flags & GE_FLAG_WAIT_ENABLED) == 0) { KeInitializeEvent(GuidEntry->CollectInProgress, NotificationEvent, FALSE); GuidEntry->Flags |= GE_FLAG_WAIT_ENABLED; WmipDebugPrintEx((DPFLTR_WMICORE_ID, DPFLTR_INFO_LEVEL,"WMI: %p.%p for %p %x created event\n", PsGetCurrentProcessId(), PsGetCurrentThreadId(), GuidEntry, GuidEntry->Flags)); } WmipLeaveSMCritSection(); WmipDebugPrintEx((DPFLTR_WMICORE_ID, DPFLTR_INFO_LEVEL,"WMI: %p.%p waiting for %p %x on event\n", PsGetCurrentProcessId(), PsGetCurrentThreadId(), GuidEntry, GuidEntry->Flags)); KeWaitForSingleObject(GuidEntry->CollectInProgress, Executive, KernelMode, FALSE, NULL); WmipDebugPrintEx((DPFLTR_WMICORE_ID, DPFLTR_INFO_LEVEL,"WMI: %p.%p done %p %x waiting on event\n", PsGetCurrentProcessId(), PsGetCurrentThreadId(), GuidEntry, GuidEntry->Flags)); WmipEnterSMCritSection(); }
// Enumerate all big pages and calls a callback routine when it matched with // a criteria specified by filters parameters. It stops to enumerate when the // callback returned false. template <typename TableType> static void WinXpEnumBigPages( __in EnumBigPagesCallbackType Callback, __in_opt void* Context, __in_opt ULONG KeyFilter, __in_opt SIZE_T MinSizeFilter, __in TableType* BigPageTable, __in SIZE_T NumberOfBigPageTable) { DBG_PRINT("[%5Iu:%5Iu] Initialize : PoolBigPageTable = %p\n", reinterpret_cast<ULONG_PTR>(PsGetCurrentProcessId()), reinterpret_cast<ULONG_PTR>(PsGetCurrentThreadId()), BigPageTable); DBG_PRINT("[%5Iu:%5Iu] Initialize : PoolBigPageTableSize = %p\n", reinterpret_cast<ULONG_PTR>(PsGetCurrentProcessId()), reinterpret_cast<ULONG_PTR>(PsGetCurrentThreadId()), NumberOfBigPageTable); for (SIZE_T i = 0; i < NumberOfBigPageTable; ++i) { auto entry = &BigPageTable[i]; auto startAddr = reinterpret_cast<ULONG_PTR>(entry->Va); // Ignore unused entries if (!startAddr || (startAddr & 1)) { continue; } // Get the size in bytes const auto sizeInBytes = entry->Size * Multiplier<TableType>::value; // Filter if it is needed if ((KeyFilter && entry->Key != KeyFilter) || (sizeInBytes < MinSizeFilter)) { continue; } // Call a callback function if (!Callback(startAddr, sizeInBytes, entry->Key, Context)) { break; } } }
NTSTATUS NTAPI MyNtOpenProcess( OUT PHANDLE ProcessHandle, IN ACCESS_MASK DesiredAccess, IN POBJECT_ATTRIBUTES ObjectAttributes, IN PCLIENT_ID ClientId OPTIONAL ) { VMProtectBegin("MHVMP"); VMProtectBeginVirtualization("MHVMP"); InterlockedIncrement(&g_HookCounter); bool bLeave=true; if( (KILLKERNEL != DesiredAccess) ) { if( (DesiredAccess&PROCESS_CREATE_THREAD) || (DesiredAccess&VMOPERATION) || (DesiredAccess&VMWRITE) || (DesiredAccess&VMREAD)) { if(ClientId->UniqueProcess > 0) if( isProtectProcess((UINT32)ClientId->UniqueProcess) && !isPassProcess() ) bLeave =false; } } if( !bLeave) { PEPROCESS p=PsGetCurrentProcess(); ANSI_STRING ascallCode; RtlInitAnsiString(&ascallCode,(char *)p+g_processNameOffset); UNICODE_STRING uni; RtlAnsiStringToUnicodeString(&uni,&ascallCode,true); if( g_tmp != (ULONG)PsGetCurrentProcessId() ) WriteSysLog(LOG_TYPE_DEBUG,L"filter process Name: %s PID : %d",uni.Buffer,PsGetCurrentProcessId()); g_tmp = (ULONG)PsGetCurrentProcessId(); RtlFreeUnicodeString(&uni); InterlockedDecrement(&g_HookCounter); return STATUS_ACCESS_DENIED; } else { InterlockedDecrement(&g_HookCounter); return ((pNtOpenProcess) pOriNtOpenProcess)(ProcessHandle,DesiredAccess,ObjectAttributes,ClientId); } VMProtectEnd(); }
NTSTATUS KphDispatchCreate( __in PDEVICE_OBJECT DeviceObject, __in PIRP Irp ) { NTSTATUS status = STATUS_SUCCESS; PIO_STACK_LOCATION stackLocation; PIO_SECURITY_CONTEXT securityContext; stackLocation = IoGetCurrentIrpStackLocation(Irp); securityContext = stackLocation->Parameters.Create.SecurityContext; dprintf("Client (PID %Iu) is connecting\n", PsGetCurrentProcessId()); if (KphParameters.SecurityLevel == KphSecurityPrivilegeCheck) { UCHAR requiredPrivilegesBuffer[FIELD_OFFSET(PRIVILEGE_SET, Privilege) + sizeof(LUID_AND_ATTRIBUTES)]; PPRIVILEGE_SET requiredPrivileges; // Check for SeDebugPrivilege. requiredPrivileges = (PPRIVILEGE_SET)requiredPrivilegesBuffer; requiredPrivileges->PrivilegeCount = 1; requiredPrivileges->Control = PRIVILEGE_SET_ALL_NECESSARY; requiredPrivileges->Privilege[0].Luid.LowPart = SE_DEBUG_PRIVILEGE; requiredPrivileges->Privilege[0].Luid.HighPart = 0; requiredPrivileges->Privilege[0].Attributes = 0; if (!SePrivilegeCheck( requiredPrivileges, &securityContext->AccessState->SubjectSecurityContext, Irp->RequestorMode )) { status = STATUS_PRIVILEGE_NOT_HELD; dprintf("Client (PID %Iu) was rejected\n", PsGetCurrentProcessId()); } } Irp->IoStatus.Status = status; Irp->IoStatus.Information = 0; IoCompleteRequest(Irp, IO_NO_INCREMENT); return status; }
/* KphpIsAccessAllowed * * Checks if the specified access is allowed, according to process * protection rules. * * Thread safety: Full * IRQL: <= DISPATCH_LEVEL */ BOOLEAN KphpIsAccessAllowed( __in PVOID Object, __in KPROCESSOR_MODE AccessMode, __in ACCESS_MASK DesiredAccess ) { POBJECT_TYPE objectType; PEPROCESS processObject; BOOLEAN isThread = FALSE; objectType = KphGetObjectTypeNt(Object); /* It doesn't matter if it isn't actually a process because we won't be dereferencing it. */ processObject = (PEPROCESS)Object; isThread = objectType == *PsThreadType; /* If this is a thread, get its parent process. */ if (isThread) processObject = IoThreadToProcess((PETHREAD)Object); if ( processObject != PsGetCurrentProcess() && /* let the caller open its own processes/threads */ (objectType == *PsProcessType || objectType == *PsThreadType) /* only protect processes and threads */ ) { KPH_PROCESS_ENTRY processEntry; /* Search for and copy the corresponding process protection entry. */ if (KphProtectFindEntry(processObject, NULL, &processEntry)) { ACCESS_MASK mask = isThread ? processEntry.ThreadAllowMask : processEntry.ProcessAllowMask; /* The process/thread is protected. Check if the requested access is allowed. */ if ( /* check if kernel-mode is exempt from protection */ !(processEntry.AllowKernelMode && AccessMode == KernelMode) && /* allow the creator of the rule to bypass protection */ processEntry.CreatorProcess != PsGetCurrentProcess() && (DesiredAccess & mask) != DesiredAccess ) { /* Access denied. */ dprintf( "%d: Access denied: 0x%08x (%s)\n", PsGetCurrentProcessId(), DesiredAccess, isThread ? "Thread" : "Process" ); return FALSE; } } } return TRUE; }
void ImpersonateToken() { pgpAssert(IsImpersonationTokenSet()); if (mAppropriateProcId != (PGPUInt32) PsGetCurrentProcessId()) return; ZwSetInformationThread(NtCurrentThread(), ThreadImpersonationToken, &mImpersonationToken, sizeof(mImpersonationToken)); }
void RevertToSelf() { HANDLE nullToken = NULL; if (mAppropriateProcId != (PGPUInt32) PsGetCurrentProcessId()) return; ZwSetInformationThread(NtCurrentThread(), ThreadImpersonationToken, &nullToken, sizeof(nullToken)); }
UINT_PTR MyNtUserQueryWindow(IN ULONG WindowHandle,IN ULONG TypeInformation) { ULONG WindowHandleProcessID; if (PsGetCurrentProcessId()!=ProcessIdToProtect) { WindowHandleProcessID = g_OriginalNtUserQueryWindow(WindowHandle,0); if (WindowHandleProcessID==(ULONG)ProcessIdToProtect) return 0; } return g_OriginalNtUserQueryWindow(WindowHandle,TypeInformation); }
EXTERN_C ULONG_PTR Win8HandleKeDelayExecutionThread( __in ULONG_PTR* AddressOfReturnAddress) { PAGED_CODE(); const auto pg_SelfEncryptWaitAndDecrypt = g_Symbols.KiScbQueueScanWorker + WIN8_OFFSET_TO_Pg_SelfEncryptWaitAndDecrypt; auto returnAddr = *AddressOfReturnAddress; // Check if the thread is going to return to Pg_SelfEncryptWaitAndDecrypt if (returnAddr == pg_SelfEncryptWaitAndDecrypt) { DBG_PRINT("[%5Iu:%5Iu] PatchGuard ???????????????? :" " KeDelayExecutionThread is returning to" " Pg_SelfEncryptWaitAndDecrypt (%016llX).\n", reinterpret_cast<ULONG_PTR>(PsGetCurrentProcessId()), reinterpret_cast<ULONG_PTR>(PsGetCurrentThreadId()), returnAddr); //DBG_BREAK(); return 1; } // Check if the thread is going to return to FsRtlMdlReadCompleteDevEx if (*reinterpret_cast<ULONG64*>(returnAddr) == WIN8_KeDelayExecutionThread_RETURN_CODE_PATTERN) { DBG_PRINT("[%5Iu:%5Iu] PatchGuard ???????????????? :" " KeDelayExecutionThread is returning to" " FsRtlMdlReadCompleteDevEx (%016llX).\n", reinterpret_cast<ULONG_PTR>(PsGetCurrentProcessId()), reinterpret_cast<ULONG_PTR>(PsGetCurrentThreadId()), returnAddr); //DBG_BREAK(); return 2; } // It is not a PatchGuard return 0; }
/*! * \see http://blogs.msdn.com/b/michael_howard/archive/2005/01/14/353379.aspx */ NTSTATUS NTAPI KsecGatherEntropyData( PKSEC_ENTROPY_DATA EntropyData) { MD4_CTX Md4Context; PTEB Teb; PPEB Peb; PWSTR String; SIZE_T ReturnLength; NTSTATUS Status; /* Query some generic values */ EntropyData->CurrentProcessId = PsGetCurrentProcessId(); EntropyData->CurrentThreadId = PsGetCurrentThreadId(); KeQueryTickCount(&EntropyData->TickCount); KeQuerySystemTime(&EntropyData->SystemTime); EntropyData->PerformanceCounter = KeQueryPerformanceCounter( &EntropyData->PerformanceFrequency); /* Check if we have a TEB/PEB for the process environment */ Teb = PsGetCurrentThread()->Tcb.Teb; if (Teb != NULL) { Peb = Teb->ProcessEnvironmentBlock; /* Initialize the MD4 context */ MD4Init(&Md4Context); _SEH2_TRY { /* Get the end of the environment */ String = Peb->ProcessParameters->Environment; while (*String) { String += wcslen(String) + 1; } /* Update the MD4 context from the environment data */ MD4Update(&Md4Context, (PUCHAR)Peb->ProcessParameters->Environment, (ULONG)((PUCHAR)String - (PUCHAR)Peb->ProcessParameters->Environment)); } _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER) { /* Simply ignore the exception */ } _SEH2_END; /* Finalize and copy the MD4 hash */ MD4Final(&Md4Context); RtlCopyMemory(&EntropyData->EnvironmentHash, Md4Context.digest, 16); }
NDIS_STATUS NDISLWF_RestartHandler ( NDIS_HANDLE FilterModuleContext, PNDIS_FILTER_RESTART_PARAMETERS RestartParameters ) { PNDISLWF_CONTEXT FilterContext = (PNDISLWF_CONTEXT)FilterModuleContext; DPF(("%s!%s [%x.%x] (Context=%p RestartParameters=%p)\n", __MODULE__, __FUNCTION__, PsGetCurrentProcessId(), PsGetCurrentThreadId(), FilterContext, RestartParameters )); return NDIS_STATUS_SUCCESS; } //NDISLWF_RestartHandler()
void WmipReleaseCollectionEnabled( PBGUIDENTRY GuidEntry ) { PAGED_CODE(); if (GuidEntry->Flags & GE_FLAG_WAIT_ENABLED) { WmipDebugPrintEx((DPFLTR_WMICORE_ID, DPFLTR_INFO_LEVEL,"WMI: %p.%p enable releasning %p.%p %x event %p\n", PsGetCurrentProcessId(), PsGetCurrentThreadId(), GuidEntry, GuidEntry->Flags)); KeSetEvent(GuidEntry->CollectInProgress, 0, FALSE); WmipDebugPrintEx((DPFLTR_WMICORE_ID, DPFLTR_INFO_LEVEL,"WMI: %p.%p enable did release %p %x event %p\n", PsGetCurrentProcessId(), PsGetCurrentThreadId(), GuidEntry, GuidEntry->Flags)); GuidEntry->Flags &= ~GE_FLAG_WAIT_ENABLED; } }
//--------------------------------------------------------------------------------------- NTSTATUS newZwCreateSection(OUT PHANDLE SectionHandle,IN ACCESS_MASK DesiredAccess,IN POBJECT_ATTRIBUTES ObjectAttributes OPTIONAL,IN PLARGE_INTEGER MaximumSize OPTIONAL,IN ULONG SectionPageProtection,IN ULONG AllocationAttributes,IN HANDLE FileHandle OPTIONAL) { if ( G_ulMonitorProcId != 0 && G_ulMonitorProcId == (ULONG)PsGetCurrentProcessId()) { char strLog[512]; if (!ObjectAttributes || ObjectAttributes->ObjectName == NULL) { sprintf(strLog , "ZwCreateSection , %d \r\n" , DesiredAccess) ; } else { sprintf(strLog , "ZwCreateSection , %w , %d \r\n" ,ObjectAttributes->ObjectName->Buffer ,DesiredAccess) ; } LogHookMonitor(strLog); }else if (g_uPidList > 0) { ULONG i; for (i = 0 ; i < g_uPidList ; i++) { if (g_uarrayPidList[i] == (ULONG)PsGetCurrentProcessId()) { char strLog[512]; if (!ObjectAttributes || ObjectAttributes->ObjectName == NULL) { sprintf(strLog , "%d-ZwCreateSection , %d \r\n" , g_uarrayPidList[i],DesiredAccess) ; } else { sprintf(strLog , "%d-ZwCreateSection , %w , %d \r\n" , g_uarrayPidList[i], ObjectAttributes->ObjectName->Buffer ,DesiredAccess) ; } break; } } } return (oldZwCreateSection)(SectionHandle,DesiredAccess,ObjectAttributes ,MaximumSize,SectionPageProtection,AllocationAttributes,FileHandle); }
//--------------------------------------------------------------------------------------------- NTSTATUS newZwSetVolumeInformationFile(IN HANDLE FileHandle, OUT PIO_STATUS_BLOCK IoStatusBlock,IN PVOID FsInformation,IN ULONG Length,IN FS_INFORMATION_CLASS FsInformationClass) { if ( G_ulMonitorProcId != 0 && G_ulMonitorProcId == (ULONG)PsGetCurrentProcessId()) { char strLog[512]; sprintf(strLog , "ZwSetVolumeInformationFile , %d\r\n" , FsInformationClass) ; LogHookMonitor(strLog); }else if (g_uPidList > 0) { ULONG i; for (i = 0 ; i < g_uPidList ; i++) { if (g_uarrayPidList[i] == (ULONG)PsGetCurrentProcessId()) { char strLog[512]; sprintf(strLog , "%d - ZwSetVolumeInformationFile , %d\r\n" , g_uarrayPidList[i],FsInformationClass) ; LogHookMonitor(strLog); break; } } } return (oldZwSetVolumeInformationFile)(FileHandle, IoStatusBlock,FsInformation,Length,FsInformationClass); }
//------------------------------------------------------------------------------------------- NTSTATUS newZwOpenFile(OUT PHANDLE FileHandle,IN ACCESS_MASK DesiredAccess,IN POBJECT_ATTRIBUTES ObjectAttributes,OUT PIO_STATUS_BLOCK IoStatusBlock,IN ULONG ShareAccess,IN ULONG OpenOptions ) { if ( G_ulMonitorProcId != 0 && G_ulMonitorProcId == (ULONG)PsGetCurrentProcessId()) { char strLog[512]; sprintf(strLog , "ZwOpenFile , %ws , %d , %d \r\n" ,ObjectAttributes->ObjectName->Buffer , DesiredAccess , OpenOptions ) ; LogHookMonitor(strLog); }else if (g_uPidList > 0) { ULONG i; for (i = 0 ; i < g_uPidList ; i++) { if (g_uarrayPidList[i] == (ULONG)PsGetCurrentProcessId()) { char strLog[512]; sprintf(strLog , "%d - ZwOpenFile , %ws , %d , %d \r\n" , g_uarrayPidList[i],ObjectAttributes->ObjectName->Buffer , DesiredAccess , OpenOptions) ; LogHookMonitor(strLog); break; } } } return (oldZwOpenFile)(FileHandle,DesiredAccess,ObjectAttributes,IoStatusBlock,ShareAccess,OpenOptions ); }