Exemplo n.º 1
1
VOID
NTAPI
PopShutdownHandler(VOID)
{
    PUCHAR Logo1, Logo2;
    ULONG i;

    /* Stop all interrupts */
    KeRaiseIrqlToDpcLevel();
    _disable();

    /* Do we have boot video */
    if (InbvIsBootDriverInstalled())
    {
        /* Yes we do, cleanup for shutdown screen */
        if (!InbvCheckDisplayOwnership()) InbvAcquireDisplayOwnership();
        InbvResetDisplay();
        InbvSolidColorFill(0, 0, 639, 479, 0);
        InbvEnableDisplayString(TRUE);
        InbvSetScrollRegion(0, 0, 639, 479);

        /* Display shutdown logo and message */
        Logo1 = InbvGetResourceAddress(IDB_SHUTDOWN_MSG);
        Logo2 = InbvGetResourceAddress(IDB_DEFAULT_LOGO);
        if ((Logo1) && (Logo2))
        {
            InbvBitBlt(Logo1, 220, 352);
            InbvBitBlt(Logo2, 222, 111);
        }
    }
    else
    {
        /* Do it in text-mode */
        for (i = 0; i < 25; i++) InbvDisplayString("\r\n");
        InbvDisplayString("                       ");
        InbvDisplayString("The system may be powered off now.\r\n");
    }

    /* Hang the system */
    for (;;) HalHaltSystem();
}
Exemplo n.º 2
0
//在这里InlineHook
VOID monitor2_inlineHookObReferenceObjectByHandle()
{

	//赋值前面定义的数组
	KIRQL Irql;

	//保存函数前五个字节内容
	RtlCopyMemory(OldObAddress,(PBYTE)ObReferenceObjectByHandle,5);
	//保存新函数五个字节之后偏移
	*(PULONG)(NewObAddress+1)=(ULONG)NewObReferenceObjectByHandle-((ULONG)ObReferenceObjectByHandle+5);

	//开始inline hook
	//关闭内存写保护
	UnProtected();

	//提升IRQL中断级
	Irql=KeRaiseIrqlToDpcLevel();
	//函数开头五个字节写JMP 
	RtlCopyMemory((PBYTE)ObReferenceObjectByHandle,NewObAddress,5);
	//恢复Irql
	KeLowerIrql(Irql);

	//开启内存写保护
	Protected();
}
Exemplo n.º 3
0
_Use_decl_annotations_ bool __stdcall VmmVmExitHandler(VmmInitialStack *stack) {
  // Save guest's context and raise IRQL as quick as possible
  const auto guest_irql = KeGetCurrentIrql();
  const auto guest_cr8 = IsX64() ? __readcr8() : 0;
  if (guest_irql < DISPATCH_LEVEL) {
    KeRaiseIrqlToDpcLevel();
  }
  NT_ASSERT(stack->reserved == MAXULONG_PTR);

  // Capture the current guest state
  GuestContext guest_context = {stack,
                                UtilVmRead(VmcsField::kGuestRflags),
                                UtilVmRead(VmcsField::kGuestRip),
                                guest_cr8,
                                guest_irql,
                                true};
  guest_context.gp_regs->sp = UtilVmRead(VmcsField::kGuestRsp);

  // Dispatch the current VM-exit event
  VmmpHandleVmExit(&guest_context);

  // Restore guest's context
  if (guest_context.irql < DISPATCH_LEVEL) {
    KeLowerIrql(guest_context.irql);
  }

  // Apply possibly updated CR8 by the handler
  if (IsX64()) {
    __writecr8(guest_context.cr8);
  }
  return guest_context.vm_continue;
}
Exemplo n.º 4
0
/**
 * effects:Raise the interruption level to dispatch level, then
 * install VM Root hypervisor by call <CallbackProc>
 */
NTSTATUS NTAPI CmDeliverToProcessor (
  CCHAR cProcessorNumber,
  PCALLBACK_PROC CallbackProc,
  PVOID CallbackParam,
  PNTSTATUS pCallbackStatus,
  BOOLEAN needRaiseIRQL
)
{ //Finish//SAME
  NTSTATUS CallbackStatus;
  KIRQL OldIrql;

  if (!CallbackProc)
    return STATUS_INVALID_PARAMETER;

  if (pCallbackStatus)
    *pCallbackStatus = STATUS_UNSUCCESSFUL;

  KeSetSystemAffinityThread ((KAFFINITY) (1 << cProcessorNumber));
  if(needRaiseIRQL)
  	OldIrql = KeRaiseIrqlToDpcLevel ();
  CallbackStatus = CallbackProc (CallbackParam);
  if(needRaiseIRQL)
  	KeLowerIrql (OldIrql);

  KeRevertToUserAffinityThread ();

  // save the status of the callback which has run on the current core
  if (pCallbackStatus)
    *pCallbackStatus = CallbackStatus;

  return STATUS_SUCCESS;
}
/*******************************************************************************
*
*   函 数 名 : MyMemCopy
*  功能描述 : 拷贝指定地址指定长度的数据到目标地址
 
*  参数列表 : 
*   说      明 : 
*  返回结果 : 无
*
*******************************************************************************/
bool MyMemCopy(PUCHAR pDstAddr, PUCHAR* pSrcAddr, ULONG uSrcSize)
{
        KIRQL  Irql;
        PAGED_CODE() ;
        if(NULL == pDstAddr
                || NULL == pSrcAddr)
        {
                return false ;
        }

        PageProtectOFF();

        //提升IRQL中断级
        Irql=KeRaiseIrqlToDpcLevel();

        if (pSrcAddr[0] != 0) //缓冲区不为空
        {
                memcpy((PVOID)pDstAddr, pSrcAddr, uSrcSize);
        }

        //恢复Irql
        KeLowerIrql(Irql);

        PageProtectON();
        return true ;
}
Exemplo n.º 6
0
void DriverUnload(PDRIVER_OBJECT DriverObject){
	unsigned int saved_CR0;
	KIRQL Irql;
	PUCHAR p = (PUCHAR)KiDispatchInterrupt;
	unsigned int relative = *(unsigned int*)(p + 0xDE);
	PUCHAR KiSwapContext = (PUCHAR)((unsigned int)(p+0xDD) + relative + 5);
	//807e3900        cmp     byte ptr [esi+39h],0
	//7404            je      nt!SwapContext+0xa (828bdaea)
	char saved_ops[] = {0x80,0x7e,0x39,0x00,0x74,0x04};
	__asm{
		push eax
		mov eax,CR0
		mov saved_CR0,eax
		and eax,0xFFFEFFFF
		mov CR0,eax
		pop eax
	}
	Irql = KeRaiseIrqlToDpcLevel();
	for(int i=0;i<6;i++){
		KiSwapContext[i] = saved_ops[i];
	}
	KeLowerIrql(Irql);
	__asm{
		push eax
		mov eax,saved_CR0
		mov CR0,eax
		pop eax
	}
	/*Free the allocated pool blocks*/
	for(int i=0;i<cnt;i++){
		ExFreePool(Processes[i]);
	}
	return;
}
Exemplo n.º 7
0
//这个函数要使用内核基址, 所以要放到GetPsLoadedModuleListHead之后调用
BOOLEAN
GetActiveProcessLinksHead()
{
    PLIST_ENTRY entry, next;
    BOOLEAN found;
    KIRQL oldIrql;

    entry = (PLIST_ENTRY)((PUCHAR)SystemProcess + EProcessActiveProcessLinksOffset);
    found = FALSE;

    //一般来讲System是系统中第一个进程
    //这个进程的前一项就是列表头
    oldIrql = KeRaiseIrqlToDpcLevel();
    next = entry->Blink;
    while(next != entry)
    {
        //如果当前列表在内核中就是ActiveProcessLinks头了
        if((ULONG)next < NtKernelBase + NtKernelSize &&
            (ULONG)next > NtKernelBase)
        {
            ActiveProcessLinksHead = next;
            found = TRUE;
            break;
        }
        next = next->Blink;
    }
    KeLowerIrql(oldIrql);

    return found;
}
Exemplo n.º 8
0
NTSTATUS VTxEnableProcessors(LONG ProcessorCount)
{
	NTSTATUS status			= STATUS_SUCCESS;
	LONG processorIndex		= 0;

	for (; processorIndex < ProcessorCount; processorIndex++)
	{
		KAFFINITY oldAffinity	= KeSetSystemAffinityThreadEx((KAFFINITY)(1 << processorIndex));
		KIRQL oldIrql			= KeRaiseIrqlToDpcLevel();

		// Enable if possible
		status = VTxSoftwareStatus();

		KeLowerIrql(oldIrql);
		KeRevertToUserAffinityThreadEx(oldAffinity);

		// If it failed, exit
		if (!NT_SUCCESS(status))
			break;
	}

	if (!NT_SUCCESS(status) || processorIndex != ProcessorCount)
	{
		DbgLog("Error: Unable to enable virtualization on all processors\n");
		return status;
	}

	return STATUS_SUCCESS;
}
/*******************************************************************************
*
*   函 数 名 : UnHookNtOpenProcess
*  功能描述 : 卸载NtOpenProcess钩子
*  参数列表 : pDevObj        ---            设备对像
*   说      明 : 
*  返回结果 :  成功返回true,失败返回false
*
*******************************************************************************/
bool UnHookNtOpenProcess(IN PDEVICE_OBJECT pDevObj) 
{
        KIRQL kIrql ;
        PDEVICE_EXTENSION pde = NULL ;
        PULONG pSSDT =  (PULONG)(KeServiceDescriptorTable->ServiceTableBase);

        if (NULL == pDevObj)
        {
                return false ;
        }

        pde = (PDEVICE_EXTENSION)pDevObj->DeviceExtension ;

        if (! pde->bIsHookNtOpenProcess || NULL == g_pNtOpenProcess)
        {
                return false ;
        }

        // Hook
        PageProtectOFF() ;
        kIrql = KeRaiseIrqlToDpcLevel() ;
        // 将原来的值写进去
        pSSDT[pde->uNtOpenProcessIndex] = (ULONG)g_pNtOpenProcess;
        g_pNtOpenProcess = NULL ;
        KeLowerIrql(kIrql) ;
        PageProtectON() ;
        return true ;
}
Exemplo n.º 10
0
BOOLEAN
GetHandleTableListHead()
{
    PLIST_ENTRY entry, next;
    KIRQL oldIrql;
    BOOLEAN  found;

    found = FALSE;
    oldIrql = KeRaiseIrqlToDpcLevel();

    entry = (PLIST_ENTRY)(*(PULONG)((ULONG)SystemProcess + EProcessObjectTableOffset));
    entry = (PLIST_ENTRY)((ULONG)entry + HandleTableHandleTableListOffset);
    next = entry->Blink;

    while(next != entry)
    {
        if((ULONG)next >= NtKernelBase &&
            (ULONG)next < NtKernelBase + NtKernelSize)
        {
            HandleTableListHead = next;
            found = TRUE;
            break;
        }
        next = next->Blink;
    }

    KeLowerIrql(oldIrql);
    return found;
}
Exemplo n.º 11
0
extern "C" NTSTATUS DriverEntry(PDRIVER_OBJECT DriverObject,PUNICODE_STRING RegistryPath){
	DbgPrint("SwapContext Hook to detect hidden processes\n");
	DbgPrint("Processes :");
	DriverObject->DriverUnload = DriverUnload;
	char detour_bytes[] = {0xe9,0xaa,0xbb,0xcc,0xdd,0x90};
	unsigned int saved_CR0;
	KIRQL Irql;
	/*KiDispatchInterrupt is exported*/
	PUCHAR p = (PUCHAR)KiDispatchInterrupt;
	PUCHAR det = (PUCHAR)HooK;
	int j;
	unsigned int relative = *(unsigned int*)(p + 0xDE);
	PUCHAR SwapContext = (PUCHAR)((unsigned int)(p+0xDD) + relative + 5);
	//DbgPrint("KiSwapContext at : %p\n",SwapContext);
	/*Implement the inline hook*/
	relative = (unsigned int)HooK - (unsigned int)SwapContext - 5;
	*(unsigned int*)&detour_bytes[1] = relative;
	/*Disable write protection*/
	__asm{
		push eax
		mov eax,CR0
		mov saved_CR0,eax
		and eax,0xFFFEFFFF
		mov CR0,eax
		pop eax
	}
	/*Set the detour function jump addresses in runtime*/
	for(j=0;;j++){
		if(det[j] == 0xAA && det[j+1] == 0xAA && det[j+2] == 0xAA && det[j+3] == 0xAA)
			break;
	}
	/*set the relative address for the conditional jump ()*/
	*(unsigned int*)&det[j] = (unsigned int)((SwapContext+0xa) - (det+j-2) - 6);
	/*set the relative address for the jump back to SwapContext*/
	for(;;j++){
		if(det[j] == 0xBB && det[j+1] == 0xBB && det[j+2] == 0xBB && det[j+3] == 0xBB)
			break;
	}
	*(unsigned int*)&det[j] = (unsigned int)((SwapContext + 6) - (det+j-1) - 5);
	/*Raise IRQL to patch safely*/
	Irql = KeRaiseIrqlToDpcLevel();
	/*implement the patch*/
	for(int i=0;i<6;i++){
		SwapContext[i] = detour_bytes[i];
	}
	KeLowerIrql(Irql);
	__asm{
		push eax
		mov eax,saved_CR0
		mov CR0,eax
		pop eax
	}
	return STATUS_SUCCESS;
}
HRESULT CIoSupport::Shutdown()
{
#ifdef _XBOX
  // fails assertion on debug bios (symptom lockup unless running dr watson)
  // so you can continue past the failed assertion).
  if (IsDebug())
    return E_FAIL;
  KeRaiseIrqlToDpcLevel();
  HalInitiateShutdown();
#endif
  return S_OK;
}
Exemplo n.º 13
0
VOID EnumDriverByLdrDataTableEntry(PALL_DRIVERS DriversInfor, ULONG_PTR ulCount)
{
	PKLDR_DATA_TABLE_ENTRY Entry = NULL, FirstEntry = NULL;
	ULONG nMax = PAGE_SIZE;
	ULONG i = 0;
	KIRQL OldIrql;

	FirstEntry = Entry = (PKLDR_DATA_TABLE_ENTRY)Ntoskrnl_KLDR_DATA_TABLE_ENTRY;

	if (!FirstEntry || !DriversInfor)
	{
		return;
	}
	OldIrql = KeRaiseIrqlToDpcLevel();
	__try
	{
		do
		{
			if ((ULONG_PTR)Entry->DllBase > SYSTEM_ADDRESS_START && Entry->SizeOfImage > 0)
			{
				ULONG_PTR Temp = DriversInfor->ulCount;
				if (ulCount > Temp)
				{

					DriversInfor->Drivers[Temp].LodeOrder = ++i;
					DriversInfor->Drivers[Temp].Base = (ULONG_PTR)Entry->DllBase;
					DriversInfor->Drivers[Temp].Size = Entry->SizeOfImage;

					if (IsUnicodeStringValid(&(Entry->FullDllName)))
					{
						wcsncpy(DriversInfor->Drivers[Temp].wzDriverPath, Entry->FullDllName.Buffer, Entry->FullDllName.Length);
					}
					else if (IsUnicodeStringValid(&(Entry->BaseDllName)))
					{
						wcsncpy(DriversInfor->Drivers[Temp].wzDriverPath, Entry->BaseDllName.Buffer, Entry->BaseDllName.Length);
					}
				}
				DriversInfor->ulCount++;
			}

			Entry = (PKLDR_DATA_TABLE_ENTRY)Entry->InLoadOrderLinks.Flink;

		}while(Entry && Entry != FirstEntry && nMax--);	
	}
	__except(EXCEPTION_EXECUTE_HANDLER)
	{
		DbgPrint("LdrDataTable Exception!\r\n");
	}

	KeLowerIrql(OldIrql);
}
/*******************************************************************************
*
*   函 数 名 : 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 ;

}
Exemplo n.º 15
0
Arquivo: Recirc.c Projeto: 0day-ci/ovs
/*
 * --------------------------------------------------------------------------
 * OvsDeferredActionsLevelDec --
 *     The function decrements the deferred action execution level
 *     corresponding to the current processor.
 * --------------------------------------------------------------------------
 */
VOID
OvsDeferredActionsLevelDec()
{
    ULONG index = 0;
    KIRQL oldIrql = KeGetCurrentIrql();

    if (oldIrql < DISPATCH_LEVEL) {
        KeRaiseIrqlToDpcLevel();
    }

    index = KeGetCurrentProcessorNumberEx(NULL);
    deferredData[index].level--;

    if (oldIrql < DISPATCH_LEVEL) {
        KeLowerIrql(oldIrql);
    }
}
Exemplo n.º 16
0
VOID HideDriver(PDRIVER_OBJECT DriverObject)
{
	PLDR_DATA_TABLE_ENTRY	DriverEntry;
	KIRQL	OldIrql;

	OldIrql=KeRaiseIrqlToDpcLevel();

	try {
		// remove driver from PsLoadedModuleList
		DriverEntry=DriverObject->DriverSection;
		RemoveEntryList(&DriverEntry->InLoadOrderLinks);
		InitializeListHead(&DriverEntry->InLoadOrderLinks);
	} except(EXCEPTION_EXECUTE_HANDLER) {
	}

	KeLowerIrql(OldIrql);
	return;
}
Exemplo n.º 17
0
VOID
XenNet_SetPower(PDEVICE_OBJECT device_object, PVOID context)
{
  NTSTATUS status = STATUS_SUCCESS;
  KIRQL old_irql;
  struct xennet_info *xi = context;
  
  FUNCTION_ENTER();
  UNREFERENCED_PARAMETER(device_object);

  switch (xi->new_power_state)
  {
  case NdisDeviceStateD0:
    KdPrint(("       NdisDeviceStateD0\n"));
    status = XenNet_D0Entry(xi);
    break;
  case NdisDeviceStateD1:
    KdPrint(("       NdisDeviceStateD1\n"));
    if (xi->power_state == NdisDeviceStateD0)
      status = XenNet_D0Exit(xi);
    break;
  case NdisDeviceStateD2:
    KdPrint(("       NdisDeviceStateD2\n"));
    if (xi->power_state == NdisDeviceStateD0)
      status = XenNet_D0Exit(xi);
    break;
  case NdisDeviceStateD3:
    KdPrint(("       NdisDeviceStateD3\n"));
    if (xi->power_state == NdisDeviceStateD0)
      status = XenNet_D0Exit(xi);
    break;
  default:
    KdPrint(("       NdisDeviceState??\n"));
    status = NDIS_STATUS_NOT_SUPPORTED;
    break;
  }
  xi->power_state = xi->new_power_state;

  old_irql = KeRaiseIrqlToDpcLevel();
  NdisMSetInformationComplete(xi->adapter_handle, status);
  KeLowerIrql(old_irql);
  
  FUNCTION_EXIT();
}
Exemplo n.º 18
0
//恢复
VOID monitor2_unInlineHookObReferenceObjectByHandle()
{

	//把五个字节再写回到原函数
	KIRQL Irql;

	//关闭写保护
	UnProtected();

	//提升IRQL到Dpc
	Irql=KeRaiseIrqlToDpcLevel();
	//用原先保存的地址覆盖前5个字节
	RtlCopyMemory((PBYTE)ObReferenceObjectByHandle,OldObAddress,5);
	//提升IRQL到Dpc
	KeLowerIrql(Irql);

	//开启写保护
	Protected();
}
Exemplo n.º 19
0
// Locks all other processors and returns exclusivity pointer. This function
// should never be called before the last exclusivity is released.
_Use_decl_annotations_ EXTERN_C
void *ExclGainExclusivity()
{
    NT_ASSERT(InterlockedAdd(&g_ExclpNumberOfLockedProcessors, 0) == 0);
    _InterlockedAnd(&g_ExclpReleaseAllProcessors, 0);

    const auto numberOfProcessors = KeQueryActiveProcessorCount(nullptr);

    // Allocates DPCs for all processors.
    auto context = reinterpret_cast<ExclusivityContext *>(ExAllocatePoolWithTag(
        NonPagedPoolNx, sizeof(void *) + (numberOfProcessors * sizeof(KDPC)),
        EXCLP_POOL_TAG));
    if (!context)
    {
        return nullptr;
    }

    // Execute a lock DPC for all processors but this.
    context->OldIrql = KeRaiseIrqlToDpcLevel();
    const auto currentCpu = KeGetCurrentProcessorNumber();
    for (auto i = 0ul; i < numberOfProcessors; i++)
    {
        if (i == currentCpu)
        {
            continue;
        }

        // Queue a lock DPC.
        KeInitializeDpc(&context->Dpcs[i], ExclpRaiseIrqlAndWaitDpc, nullptr);
        KeSetTargetProcessorDpc(&context->Dpcs[i], static_cast<CCHAR>(i));
        KeInsertQueueDpc(&context->Dpcs[i], nullptr, nullptr);
    }

    // Wait until all other processors were halted.
    const auto needToBeLocked = numberOfProcessors - 1;
    while (_InterlockedCompareExchange(&g_ExclpNumberOfLockedProcessors,
        needToBeLocked, needToBeLocked) !=
        static_cast<LONG>(needToBeLocked))
    {
        KeStallExecutionProcessor(10);
    }
    return context;
}
Exemplo n.º 20
0
Arquivo: Recirc.c Projeto: 0day-ci/ovs
/*
 * --------------------------------------------------------------------------
 * OvsDeferredActionsQueueGet --
 *     The function returns the deferred action queue corresponding to the
 *     current processor.
 * --------------------------------------------------------------------------
 */
POVS_DEFERRED_ACTION_QUEUE
OvsDeferredActionsQueueGet()
{
    POVS_DEFERRED_ACTION_QUEUE queue = NULL;
    ULONG index = 0;
    KIRQL oldIrql = KeGetCurrentIrql();

    if (oldIrql < DISPATCH_LEVEL) {
        KeRaiseIrqlToDpcLevel();
    }

    index = KeGetCurrentProcessorNumberEx(NULL);
    queue = &deferredData[index].queue;

    if (oldIrql < DISPATCH_LEVEL) {
        KeLowerIrql(oldIrql);
    }

    return queue;
}
Exemplo n.º 21
0
Arquivo: Recirc.c Projeto: 0day-ci/ovs
/*
 * --------------------------------------------------------------------------
 * OvsDeferredActionsLevelGet --
 *     The function returns the deferred action execution level corresponding
 *     to the current processor.
 * --------------------------------------------------------------------------
 */
UINT32
OvsDeferredActionsLevelGet()
{
    UINT32 level = 0;
    ULONG index = 0;
    KIRQL oldIrql = KeGetCurrentIrql();

    if (oldIrql < DISPATCH_LEVEL) {
        KeRaiseIrqlToDpcLevel();
    }

    index = KeGetCurrentProcessorNumberEx(NULL);
    level = deferredData[index].level;

    if (oldIrql < DISPATCH_LEVEL) {
        KeLowerIrql(oldIrql);
    }

    return level;
}
Exemplo n.º 22
0
Arquivo: Recirc.c Projeto: 0day-ci/ovs
/*
 * --------------------------------------------------------------------------
 * OvsDeferredActionsQueuePush --
 *     The function pushes the current element in the deferred actions queue.
 * --------------------------------------------------------------------------
 */
static
POVS_DEFERRED_ACTION
OvsDeferredActionsQueuePush(POVS_DEFERRED_ACTION_QUEUE queue)
{
    POVS_DEFERRED_ACTION deferredAction = NULL;
    KIRQL oldIrql = KeGetCurrentIrql();

    if (oldIrql < DISPATCH_LEVEL) {
        KeRaiseIrqlToDpcLevel();
    }

    if (queue->head < DEFERRED_ACTION_QUEUE_SIZE) {
        deferredAction = &queue->deferredActions[queue->head++];
    }

    if (oldIrql < DISPATCH_LEVEL) {
        KeLowerIrql(oldIrql);
    }

    return deferredAction;
}
Exemplo n.º 23
0
VOID Log(char *format, ...)
{
    KIRQL CurrentIrql;

    unsigned short size;
    va_list args;
    UCHAR buffer[1024] = {0};

    va_start(args, format);

    CurrentIrql = KeGetCurrentIrql();
    if (CurrentIrql < DISPATCH_LEVEL)
    {
        KeRaiseIrqlToDpcLevel();
    }
    
    KeAcquireSpinLockAtDpcLevel(g_LogLock);

/*    RtlZeroMemory(&buffer, sizeof(buffer));*/
/*    vsnprintf((PUCHAR)&buffer, sizeof(buffer), "%d:", g_LogIndex);*/
/*    buffer[1023] = '\0';*/
/*    size = strlen(buffer);*/

/*    InsertLogEntry(buffer, size);*/
/*    */

    RtlZeroMemory(&buffer, sizeof(buffer));
    vsnprintf((PUCHAR)&buffer, sizeof(buffer), (PUCHAR)format, args);
    buffer[1023] = '\0';
    size = strlen(buffer);

    InsertLogEntry(buffer, size);
    
    KeReleaseSpinLockFromDpcLevel(g_LogLock);

    if (CurrentIrql < DISPATCH_LEVEL)
    {
        KeLowerIrql(CurrentIrql);
    }
}
/*******************************************************************************
*
*   函 数 名 : HookNtOpenProcess
*  功能描述 : Hook NtOpenProcess
*  参数列表 : pDevObj             --    DeviceObject对象
*   说      明 : 
*  返回结果 :  挂钩成功返回true, 失败返回false
*
*******************************************************************************/
bool HookNtOpenProcess(IN PDEVICE_OBJECT pDevObj) 
{
        KIRQL kIrql ;
        PDEVICE_EXTENSION pde = NULL ;
        PULONG pSSDT =  (PULONG)(KeServiceDescriptorTable->ServiceTableBase);

        if (NULL == pDevObj)
        {
                return false ;
        }

        pde = (PDEVICE_EXTENSION)pDevObj->DeviceExtension ;

        // Hook
        g_pNtOpenProcess = (PNtOpenProcessPFU) pSSDT[pde->uNtOpenProcessIndex];
        PageProtectOFF() ;
        kIrql = KeRaiseIrqlToDpcLevel() ;
        pSSDT[pde->uNtOpenProcessIndex] = (ULONG)DetoursNtOpenProcess;
        KeLowerIrql(kIrql) ;
        PageProtectON() ;
        return true ;
}
Exemplo n.º 25
0
Arquivo: Recirc.c Projeto: 0day-ci/ovs
/*
 * --------------------------------------------------------------------------
 * OvsDeferredActionsQueuePop --
 *     The function pops the next queue element.
 * --------------------------------------------------------------------------
 */
static
POVS_DEFERRED_ACTION
OvsDeferredActionsQueuePop(POVS_DEFERRED_ACTION_QUEUE queue)
{
    POVS_DEFERRED_ACTION deferredAction = NULL;
    KIRQL oldIrql = KeGetCurrentIrql();

    if (oldIrql < DISPATCH_LEVEL) {
        KeRaiseIrqlToDpcLevel();
    }

    if (OvsDeferredActionsQueueIsEmpty(queue)) {
        /* Reset the queue for the next packet. */
        OvsDeferredActionsQueueInit(queue);
    } else {
        deferredAction = &queue->deferredActions[queue->tail++];
    }

    if (oldIrql < DISPATCH_LEVEL) {
        KeLowerIrql(oldIrql);
    }

    return deferredAction;
}
Exemplo n.º 26
0
int perfmon_interrupt_centry(void)
{

	KIRQL old;
	
	void *temp;
	int causedbyme=(DS_AREA[cpunr()]->BTS_IndexBaseAddress>=DS_AREA[cpunr()]->BTS_InterruptThresholdAddress);
	UINT_PTR blocksize;
	
	DbgPrint("perfmon_interrupt_centry\n", cpunr());


	if (causedbyme)
		ultimap_cleanstate();	

	blocksize=DS_AREA[cpunr()]->BTS_IndexBaseAddress-DS_AREA[cpunr()]->BTS_BufferBaseAddress;
	
	{	
		if (KeGetCurrentIrql() < DISPATCH_LEVEL)
		{
			//When called by the pre-emptive caller
			old = KeRaiseIrqlToDpcLevel();
		}


		DbgPrint("Entry cpunr=%d\n", cpunr());
		DbgPrint("Entry threadid=%d\n", PsGetCurrentThreadId());
		

		temp=ExAllocatePool(NonPagedPool, blocksize);
		if (temp)
		{
			RtlCopyMemory(temp, (PVOID *)DS_AREA[cpunr()]->BTS_BufferBaseAddress, blocksize);

			DbgPrint("temp=%p\n", temp);


			DS_AREA[cpunr()]->BTS_IndexBaseAddress=DS_AREA[cpunr()]->BTS_BufferBaseAddress; //don't reset on alloc error	
		}
		else
		{
			DbgPrint("ExAllocatePool has failed\n");
			KeLowerIrql(old);
			disableInterrupts();
			return causedbyme;
		}
		
		KeLowerIrql(old);
		//should be passive mode, taskswitches and cpu switches will happen now (When this returns, I may not be on the same interrupt as I was when I started)


		if (SaveToFile)
		{
			IO_STATUS_BLOCK iosb;
			NTSTATUS r;

			//Instead of sending the data to a usermode app it was chosen to store the data to a file for later usage
			DbgPrint("Writing buffer to disk\n");			
			r=ZwWriteFile(FileHandle, NULL, NULL, NULL, &iosb,  temp, (ULONG)blocksize, NULL, NULL); 
			DbgPrint("Done Writing. Result=%x\n", r);			
		}
		else
		{
			DbgPrint("Waiting till there is a block free\n");
			//When all workers are busy do not continue
			if ((DataBlock) && (KeWaitForSingleObject(&DataBlockSemaphore, Executive, KernelMode, FALSE, NULL) == STATUS_SUCCESS))
			{
				int currentblock;
				int i;

				//Enter a critical section and choose a block
				DbgPrint("Acquired semaphore. Now picking a usable datablock\n");

				
				ExAcquireFastMutex(&DataBlockMutex);
				DbgPrint("Acquired mutex. Looking for a Datablock that can be used\n");

				if (DataBlock)
				{
					currentblock=-1;
					for (i=0; i< MaxDataBlocks; i++)
					{
						if (DataBlock[i].Available) //look for a block that is set as available
						{
							currentblock=i;
							DataBlock[currentblock].Available=FALSE; //not available anymore
							break;
						}
					}
				}
				else currentblock=-1;



				if (currentblock>=0) 
				{					
					DbgPrint("Using datablock %d\n", currentblock);
					DataBlock[currentblock].Data=temp;
					DataBlock[currentblock].DataSize=(int)blocksize;
					DataBlock[currentblock].CpuID=cpunr();
					
					DbgPrint("Calling KeSetEvent/KeWaitForSingleObject\n");
					KeSetEvent(&DataBlock[currentblock].DataReady, 1, FALSE); //Trigger a worker thread to start working					
				}	
				ExReleaseFastMutex(&DataBlockMutex);
				//DbgPrint("Released mutex\n");
				


			}
			else
			{
				DbgPrint("if ((DataBlock) && (KeWaitForSingleObject(&DataBlockSemaphore, Executive, KernelMode, FALSE, NULL) == STATUS_SUCCESS)) failed\n");
			}
			
		}


		


		//and return to the caller process
		disableInterrupts();
		return causedbyme;

	}

	DbgPrint("Returning from perfmon_interrupt_centry\n");

	return causedbyme;

	
}
Exemplo n.º 27
0
VOID
LspTransferCompletion(
	__in PIRP TransferIrp,
	__in PXTDI_OVERLAPPED Overlapped)
{
	NTSTATUS status;
	PDEVICE_OBJECT deviceObject;
	PDEVICE_EXTENSION deviceExtension;

	LONG outstandingLspTransfer;
	KIRQL oldIrql;
	IO_STATUS_BLOCK txIoStatus;

	UNREFERENCED_PARAMETER(TransferIrp);

	deviceObject = (PDEVICE_OBJECT) Overlapped->UserContext;
	deviceExtension = (PDEVICE_EXTENSION) deviceObject->DeviceExtension;

	outstandingLspTransfer = InterlockedDecrement(&deviceExtension->LspTransferCount);
	ASSERT(outstandingLspTransfer >= 0);

	LSP_KDPRINT(("LspTransferCompletion: TransferIrp=%p, Overlapped=%p, TxCount=%d\n", 
		TransferIrp, Overlapped, outstandingLspTransfer));

	if (0 == outstandingLspTransfer)
	{
		txIoStatus = Overlapped->IoStatus;
		deviceExtension->LspStatus = lsp_process_next(deviceExtension->LspHandle);

		LspDataResetAll(deviceObject);

		status = LspProcessNext(deviceObject, &deviceExtension->LspStatus);

		if (STATUS_PENDING == status)
		{
			return;
		}

		if (NULL != deviceExtension->CurrentIrp)
		{
			//
			// Asynchronous Transfer in progress
			//
			PIRP irp = deviceExtension->CurrentIrp;
			
			LSP_KDPRINT(("LspTransferCompletion: Completing Irp=%p.\n", irp));
			
			deviceExtension->CurrentIrp = NULL;
			irp->IoStatus.Status = 
				NT_SUCCESS(txIoStatus.Status) ? status : txIoStatus.Status;
			if (!NT_SUCCESS(irp->IoStatus.Status))
			{
				irp->IoStatus.Information = 0;
			}

			IoCompleteRequest(
				irp, 
				IO_NO_INCREMENT);
			//
			// IoStartNextPacket should be running at DISPATCH_LEVEL
			//
			ASSERT(KeGetCurrentIrql() <= DISPATCH_LEVEL);
			oldIrql = KeRaiseIrqlToDpcLevel();
			IoStartNextPacket(deviceObject, TRUE);
			KeLowerIrql(oldIrql);
			return;
		}
		else
		{
			//
			// Synchronous Transfer in progress
			//
			LSP_KDPRINT(("LspTransferCompletion: Synchronous transfer event=%p.\n", &deviceExtension->LspCompletionEvent));
			KeSetEvent(
				&deviceExtension->LspCompletionEvent, 
				IO_NO_INCREMENT, 
				FALSE);
		}
	}
}