const CHAR * AdvancedPhoto_Text( ULONGLONG Flags ) { PAGED_CODE(); switch( Flags ) { case KSCAMERA_EXTENDEDPROP_ADVANCEDPHOTO_OFF: return "Off"; case KSCAMERA_EXTENDEDPROP_ADVANCEDPHOTO_AUTO: return "Auto"; case KSCAMERA_EXTENDEDPROP_ADVANCEDPHOTO_HDR: return "HDR"; case KSCAMERA_EXTENDEDPROP_ADVANCEDPHOTO_FNF: return "FNF"; case KSCAMERA_EXTENDEDPROP_ADVANCEDPHOTO_ULTRALOWLIGHT: return "UltraLL"; case KSCAMERA_EXTENDEDPROP_ADVANCEDPHOTO_AUTO | KSCAMERA_EXTENDEDPROP_ADVANCEDPHOTO_HDR: return "Auto|HDR"; case KSCAMERA_EXTENDEDPROP_ADVANCEDPHOTO_AUTO | KSCAMERA_EXTENDEDPROP_ADVANCEDPHOTO_FNF: return "Auto|FNF"; case KSCAMERA_EXTENDEDPROP_ADVANCEDPHOTO_AUTO | KSCAMERA_EXTENDEDPROP_ADVANCEDPHOTO_ULTRALOWLIGHT: return "Auto|UltraLL"; default: { static CHAR buffer[32]; RtlStringCbPrintfA(buffer, sizeof(buffer), "Unknown [0x%016llX]", Flags); return (const CHAR *) buffer; } } }
////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Description : // Generates a message using "pid", "message" and "parameter" and sends it back to userland throught // a filter communication port. // Parameters : // _in_opt_ ULONG pid : Process ID from which the logs are produced. // _in_opt_ PWCHAR message : Message (function name most of the time). // _in_opt_ PWCHAR parameter : Function args. // Return value : // NTSTATUS : FltSendMessage return value. // Process : // - Retrieves the process name from the pid and saves the whole data into an ANSI string. // - Generates an ANSI string with the message, with the process name, pid, and function name, and the // - generic "parameter" parameter. The resulting output will basically follow this scheme: // "pid","proces_name","function_name","FAILED/SUCCESS(0/1)","return_value","number_of_arguments","argument1->value","argument2->value"... // - Uses the "mutex" mutex to avoid concurrency when using the FltSendMessage() function. ////////////////////////////////////////////////////////////////////////////////////////////////////////////// NTSTATUS sendLogs(ULONG pid, PWCHAR message, PWCHAR parameter) { NTSTATUS status = STATUS_SUCCESS; CHAR buf[MAXSIZE]; UNICODE_STRING processName; ULONG sizeBuf; LARGE_INTEGER timeout; timeout.QuadPart = -((LONGLONG)0.5*10*1000*1000); if(message == NULL) return STATUS_INVALID_PARAMETER; #ifdef DEBUG DbgPrint("SendLogs\n"); #endif processName.Length = 0; processName.MaximumLength = NTSTRSAFE_UNICODE_STRING_MAX_CCH * sizeof(WCHAR); processName.Buffer = ExAllocatePoolWithTag(NonPagedPool, processName.MaximumLength, PROCNAME_TAG); if(!processName.Buffer) { KeWaitForMutexObject(&mutex, Executive, KernelMode, FALSE, NULL); status = FltSendMessage(filter, &clientPort, "0,error,error,error\n", 20, NULL, 0, &timeout); KeReleaseMutex(&mutex, FALSE); return STATUS_NO_MEMORY; } status = getProcNameByPID(pid, &processName); if(!NT_SUCCESS(status)) { KeWaitForMutexObject(&mutex, Executive, KernelMode, FALSE, NULL); status = FltSendMessage(filter, &clientPort, "0,error,error,error\n", 20, NULL, 0, &timeout); KeReleaseMutex(&mutex, FALSE); ExFreePool(processName.Buffer); return status; } status = RtlStringCbPrintfA(buf, MAXSIZE, "%d,%wZ,%ws,%ws\n", pid, &processName, message, parameter); if(!NT_SUCCESS(status) || status == STATUS_BUFFER_OVERFLOW) { KeWaitForMutexObject(&mutex, Executive, KernelMode, FALSE, NULL); status = FltSendMessage(filter, &clientPort, "0,error,error,error\n", 20, NULL, 0, &timeout); KeReleaseMutex(&mutex, FALSE); ExFreePool(processName.Buffer); return status; } status = RtlStringCbLengthA(buf, MAXSIZE, &sizeBuf); if(!NT_SUCCESS(status)) { KeWaitForMutexObject(&mutex, Executive, KernelMode, FALSE, NULL); status = FltSendMessage(filter, &clientPort, "0,error,error,error\n", 20, NULL, 0, &timeout); KeReleaseMutex(&mutex, FALSE); ExFreePool(processName.Buffer); return status; } KeWaitForMutexObject(&mutex, Executive, KernelMode, FALSE, NULL); #ifdef DEBUG DbgPrint("\tmsg : %s\n", buf); #endif status = FltSendMessage(filter, &clientPort, buf, sizeBuf, NULL, 0, NULL); if(status == STATUS_TIMEOUT) DbgPrint("STATUS_TIMEOUT !!\n"); KeReleaseMutex(&mutex, FALSE); ExFreePool(processName.Buffer); #ifdef DEBUG if(!NT_SUCCESS(status)) DbgPrint("return : 0x%08x\n", status); #endif DEBUG return status; }
VOID findSSDTHooks(PCHAR report, ULONG size, ULONG kernelBase, ULONG kernelEnd) { PULONG pulModuleList = NULL; CHAR temp[256]; ULONG nbEntries = 0; ULONG cpt = 0; // DbgPrint("findSSDTHooks\n"); pulModuleList = modulesInMemory; //récupération de l'@ de la SSDT nbEntries=KeServiceDescriptorTable.NumberOfServices; //pour chaque entrée de la SSDT for(cpt=0; cpt<nbEntries; cpt++) { //si hors limites if(KeServiceDescriptorTable.ServiceTableBase[cpt] < kernelBase || KeServiceDescriptorTable.ServiceTableBase[cpt] > kernelEnd) { if(RtlStringCbPrintfA(temp, 256*sizeof(char), "210|r0|||#%x syscall|%s.0x%x\n", cpt, whosThisAddr(KeServiceDescriptorTable.ServiceTableBase[cpt]), KeServiceDescriptorTable.ServiceTableBase[cpt])==STATUS_SUCCESS) { //DbgPrint("HOOK : #0x%x -> 0x%x\n", cpt, KeServiceDescriptorTable.ServiceTableBase[cpt]); if(RtlStringCchCatA(report, size, temp) != STATUS_SUCCESS) { DbgPrint("Error : RtlStringCchCat\n"); return ; } } else { DbgPrint("Error : RtlStringCbVPrintf\n"); return ; } } } }
NTSTATUS XenPciPdo_EvtDeviceD0Exit(WDFDEVICE device, WDF_POWER_DEVICE_STATE target_state) { NTSTATUS status = STATUS_SUCCESS; PXENPCI_PDO_DEVICE_DATA xppdd = GetXppdd(device); PXENPCI_DEVICE_DATA xpdd = GetXpdd(xppdd->wdf_device_bus_fdo); char path[128]; UNREFERENCED_PARAMETER(device); UNREFERENCED_PARAMETER(target_state); FUNCTION_ENTER(); FUNCTION_MSG("path = %s\n", xppdd->path); switch (target_state) { case WdfPowerDeviceD0: FUNCTION_MSG("WdfPowerDeviceD1\n"); break; case WdfPowerDeviceD1: FUNCTION_MSG("WdfPowerDeviceD1\n"); break; case WdfPowerDeviceD2: FUNCTION_MSG("WdfPowerDeviceD2\n"); break; case WdfPowerDeviceD3: FUNCTION_MSG("WdfPowerDeviceD3\n"); if (xppdd->hiber_usage_kludge) { FUNCTION_MSG("(but really WdfPowerDevicePrepareForHibernation)\n"); target_state = WdfPowerDevicePrepareForHibernation; } break; case WdfPowerDeviceD3Final: FUNCTION_MSG("WdfPowerDeviceD3Final\n"); break; case WdfPowerDevicePrepareForHibernation: FUNCTION_MSG("WdfPowerDevicePrepareForHibernation\n"); break; default: FUNCTION_MSG("Unknown WdfPowerDevice state %d\n", target_state); break; } if (target_state == WdfPowerDevicePrepareForHibernation) { FUNCTION_MSG("not powering down as we are hibernating\n"); // should we set the backend state here so it's correct on resume??? } /* Remove watch on backend state */ /* even if hibernate */ if (xppdd->device_callback) { FUNCTION_MSG("Removing watch %s\n", xppdd->device); RtlStringCbPrintfA(path, ARRAY_SIZE(path), "%s/state", xppdd->backend_path); XenBus_RemWatch(xpdd, XBT_NIL, path, XenPci_BackendStateCallback, xppdd); } FUNCTION_EXIT(); return status; }
//---------------------------------------------------------------------------- void FormatTimestamp(__in char *buffer, __in const size_t size) { LARGE_INTEGER localTime; LARGE_INTEGER systemTime; TIME_FIELDS timeFields; KeQuerySystemTime(&systemTime); ExSystemTimeToLocalTime(&systemTime, &localTime); RtlTimeToTimeFields(&localTime, &timeFields); RtlStringCbPrintfA(buffer, size, "%04d-%02d-%02d %02d:%02d:%02d.%03d", timeFields.Year, timeFields.Month, timeFields.Day, timeFields.Hour, timeFields.Minute, timeFields.Second, timeFields.Milliseconds); }
static NTSTATUS XenPci_GetBackendDetails(WDFDEVICE device) { PXENPCI_PDO_DEVICE_DATA xppdd = GetXppdd(device); PXENPCI_DEVICE_DATA xpdd = GetXpdd(xppdd->wdf_device_bus_fdo); char path[128]; PCHAR res; PCHAR value; FUNCTION_ENTER(); /* Get backend path */ RtlStringCbPrintfA(path, ARRAY_SIZE(path), "%s/backend", xppdd->path); res = XenBus_Read(xpdd, XBT_NIL, path, &value); if (res) { FUNCTION_MSG("Failed to read backend path\n"); XenPci_FreeMem(res); return STATUS_UNSUCCESSFUL; } RtlStringCbCopyA(xppdd->backend_path, ARRAY_SIZE(xppdd->backend_path), value); XenPci_FreeMem(value); /* Get backend id */ RtlStringCbPrintfA(path, ARRAY_SIZE(path), "%s/backend-id", xppdd->path); res = XenBus_Read(xpdd, XBT_NIL, path, &value); if (res) { FUNCTION_MSG("Failed to read backend id\n"); XenPci_FreeMem(res); return STATUS_UNSUCCESSFUL; } xppdd->backend_id = (domid_t)atoi(value); XenPci_FreeMem(value); FUNCTION_EXIT(); return STATUS_SUCCESS; }
static FORCEINLINE VOID __PdoSetName( IN PXENFILT_PDO Pdo ) { PXENFILT_DX Dx = Pdo->Dx; const CHAR *Text; NTSTATUS status; Text = EmulatedGetObjectText(Pdo->EmulatedObject); status = RtlStringCbPrintfA(Dx->Name, MAX_DEVICE_ID_LEN, "%s", Text); ASSERT(NT_SUCCESS(status)); }
NTSTATUS XenPci_SuspendPdo(WDFDEVICE device) { PXENPCI_PDO_DEVICE_DATA xppdd = GetXppdd(device); PXENPCI_DEVICE_DATA xpdd = xppdd->xpdd; PCHAR response; CHAR path[128]; if (xppdd->device_callback) { FUNCTION_MSG("Suspending %s\n", xppdd->device); xppdd->device_callback(xppdd->device_callback_context, XN_DEVICE_CALLBACK_SUSPEND, NULL); RtlStringCbPrintfA(path, ARRAY_SIZE(path), "%s/state", xppdd->backend_path); response = XenBus_RemWatch(xpdd, XBT_NIL, path, XenPci_BackendStateCallback, xppdd); if (response) { FUNCTION_MSG("XnRemWatch - %s = %s\n", path, response); XenPci_FreeMem(response); } } return STATUS_SUCCESS; }
/* Called at PASSIVE_LEVEL(?) Called during restore */ static ULONG XenPci_ReadBackendState(PXENPCI_PDO_DEVICE_DATA xppdd) { PXENPCI_DEVICE_DATA xpdd = GetXpdd(xppdd->wdf_device_bus_fdo); char path[128]; char *value; char *err; ULONG backend_state; RtlStringCbPrintfA(path, ARRAY_SIZE(path), "%s/state", xppdd->backend_path); err = XenBus_Read(xpdd, XBT_NIL, path, &value); if (err) { XenPci_FreeMem(err); return XenbusStateUnknown; } else { backend_state = atoi(value); XenPci_FreeMem(value); return backend_state; } }
NTSTATUS XenPci_ResumePdo(WDFDEVICE device) { PXENPCI_PDO_DEVICE_DATA xppdd = GetXppdd(device); PXENPCI_DEVICE_DATA xpdd = xppdd->xpdd; PCHAR response; CHAR path[128]; XenPci_GetBackendDetails(device); if (xppdd->device_callback) { FUNCTION_MSG("Resuming %s\n", xppdd->device); RtlStringCbPrintfA(path, ARRAY_SIZE(path), "%s/state", xppdd->backend_path); response = XenBus_AddWatch(xpdd, XBT_NIL, path, XenPci_BackendStateCallback, xppdd); if (response) { FUNCTION_MSG("XnAddWatch - %s = %s\n", path, response); XenPci_FreeMem(response); xppdd->device_callback = NULL; xppdd->device_callback_context = NULL; FUNCTION_EXIT(); return STATUS_UNSUCCESSFUL; } xppdd->device_callback(xppdd->device_callback_context, XN_DEVICE_CALLBACK_RESUME, NULL); } return STATUS_SUCCESS; }
void natvLogSession( IN const char * prefixStr, IN TRACED_CONNECTION* pItem, IN ULONG prevState, IN const char * sufixStr ) { TIME_FIELDS TimeFields; char timeStr[30]; LARGE_INTEGER time; char dstIpAddrStr[30]; char srcIpAddrStr[30]; KeQuerySystemTime(&time); ExSystemTimeToLocalTime(&time, &time); RtlTimeToTimeFields(&time, &TimeFields); RtlStringCbPrintfA(timeStr, sizeof(timeStr), "%02d:%02d:%02d.%03d ", TimeFields.Hour, TimeFields.Minute, TimeFields.Second, TimeFields.Milliseconds); PRINT_IP(dstIpAddrStr, &pItem->dstIpAddrOrg); PRINT_IP(srcIpAddrStr, &pItem->srcIpAddrOrg); DbgPrint("%s %s session %s %s: %s:%u->%s:%u. State %s->%s\n", timeStr, prefixStr, pItem->out ? "OUT" : "IN ", sufixStr, srcIpAddrStr, RtlUshortByteSwap(pItem->srcPortOrg), dstIpAddrStr, RtlUshortByteSwap(pItem->dstPortOrg), natsState2Name(prevState), natsState2Name(pItem->state) ); }
void CHardwareSimulation:: FakeHardware ( ) /*++ Routine Description: Simulate an interrupt and what the hardware would have done in the time since the previous interrupt. Arguments: None Return Value: None --*/ { PAGED_CODE(); KScopedMutex Lock( m_ListLock ); m_InterruptTime++; // // The hardware can be in a pause state in which case, it issues interrupts // but does not complete mappings. In this case, don't bother synthesizing // a frame and doing the work of looking through the mappings table. // if (m_PinState == PinRunning) { // // Generate a "time stamp" just to overlay it onto the capture image. // It makes it more exciting than bars that do nothing. // ULONGLONG time = ConvertQPCtoTimeStamp(NULL); DBG_TRACE("QPC=0x%016llX", time); m_Synthesizer->SetFrameNumber( m_InterruptTime ); m_Synthesizer->SetRelativePts( (m_InterruptTime + 1) * m_TimePerFrame ); m_Synthesizer->SetQpcTime( time ); m_Synthesizer->DoSynthesize(); CHAR Text[64]; CExtendedProperty Control; m_Sensor->GetVideoStabilization( &Control ); RtlStringCbPrintfA(Text, sizeof(Text), "DVS: %s", DVS_Text(Control.Flags)); m_Synthesizer->OverlayText( 0, m_Height-38, 1, Text, BLACK, WHITE ); m_Sensor->GetOpticalImageStabilization( &Control ); RtlStringCbPrintfA(Text, sizeof(Text), "OIS: %s", OIS_Text(Control.Flags)); m_Synthesizer->OverlayText( 0, m_Height-48, 1, Text, BLACK, WHITE ); // // Fill scatter gather buffers // if (!NT_SUCCESS (FillScatterGatherBuffers ())) { InterlockedIncrement (PLONG (&m_NumFramesSkipped)); } } // // Issue an interrupt to our hardware sink. This is a "fake" interrupt. // It will occur at DISPATCH_LEVEL. // m_Sensor -> Interrupt (m_PinID); // // Schedule the timer for the next interrupt time, if the pin is still running. // if( m_PinState == PinRunning ) { LARGE_INTEGER NextTime; NextTime.QuadPart = m_StartTime.QuadPart + (m_TimePerFrame * (m_InterruptTime + 1)); #ifdef ENABLE_TRACING // To keep us from a tight spin when trying to debug this code... LARGE_INTEGER Now; KeQuerySystemTime(&Now); if( Now.QuadPart >= NextTime.QuadPart ) { NextTime.QuadPart = 0LL - m_TimePerFrame ; } #endif m_IsrTimer.Set( NextTime ); } }
VOID MyThreadStart(__in PVOID StartContext){ HANDLE handle;//Create File handle NTSTATUS ntstatus; NTSTATUS timerStatus; //IO_STATUS_BLOCK ioStatusBlock; //OBJECT_ATTRIBUTES ObjAttr; //UNICODE_STRING path; LARGE_INTEGER timeout; //#define BUFFER_SIZE 30 // CHAR buffer[BUFFER_SIZE]; //size_t cb; NTSTATUS Status; HANDLE hEvent; //OBJECT_ATTRIBUTES oa; //UNICODE_STRING us; int counter=20; SIZE_T BytesNUM; char* dataPtr; __debugbreak(); dataPtr="123"; BytesNUM=strlen(dataPtr)*sizeof(char); WriteToRingBuffer(&dataPtr, BytesNUM); FlushRingBuffre(); RtlInitUnicodeString( &path, L"\\DosDevices\\C:\\MyLogger.txt"); InitializeObjectAttributes( &ObjAttr, &path, //ObjectName OBJ_CASE_INSENSITIVE, //Attributes NULL, //RootDirectory NULL); //SecurityDescriptor // Do not try to perform any file operations at higher IRQL levels. // Instead, you may use a work item or a system worker thread to perform file operations. if(KeGetCurrentIrql() != PASSIVE_LEVEL) // return STATUS_INVALID_DEVICE_STATE; DbgPrint("STATUS_INVALID_DEVICE_STATE\n"); ntstatus = ZwCreateFile(&handle, GENERIC_WRITE, &ObjAttr, &ioStatusBlock, NULL, FILE_ATTRIBUTE_NORMAL, 0, FILE_OVERWRITE_IF, FILE_SYNCHRONOUS_IO_NONALERT, NULL, 0); timeout.QuadPart = -5 * 1000000; RtlInitUnicodeString( &us, L"\\BaseNamedObjects\\TestEvent"); InitializeObjectAttributes( &oa, &us, //ObjectName OBJ_CASE_INSENSITIVE, //Attributes NULL, //RootDirectory NULL); //SecurityDescriptor Status = ZwCreateEvent(&hEvent, EVENT_ALL_ACCESS, &oa, NotificationEvent, FALSE); if(NT_SUCCESS(Status)){ DbgPrint("Event created"); } else { DbgPrint("Event Not created"); } Status = ObReferenceObjectByHandle( hEvent, //Handle EVENT_ALL_ACCESS, //DesiredAccess NULL, //ObjectType KernelMode, //AccessMode &pEvent, //Object NULL); //HandleInformation if (!NT_SUCCESS(Status)) { ZwClose(hEvent); DbgPrint("Failed to reference event \n"); //return Status; }; while(counter!=0){ timerStatus = KeWaitForSingleObject( pEvent, Executive, KernelMode, FALSE, &timeout ); if(timerStatus == STATUS_TIMEOUT){ if(NT_SUCCESS(ntstatus)) { ntstatus = RtlStringCbPrintfA(buffer, sizeof(buffer), "This is %d test\r\n", counter); if(NT_SUCCESS(ntstatus)) { ntstatus = RtlStringCbLengthA(buffer, sizeof(buffer), &cb); if(NT_SUCCESS(ntstatus)) { ntstatus = ZwWriteFile(handle, NULL, NULL, NULL, &ioStatusBlock, buffer, cb, NULL, NULL); } } //ZwClose(handle); } } counter--; } ZwClose(handle); }
// // Read the MSR register to identify hooks and reads first bytes to find inline // hooks. // VOID findSYSENTERHook(PCHAR report, ULONG size, ULONG kernelBase, ULONG kernelEnd) { ULONG ulFastCallLoc = 0; CHAR temp[256]; UCHAR firstByte=0; ULONG cpt = 0; ULONG zwaddr = 0; ULONG kisysservreladdr = 0; ULONG kisysservaddr = 0; // read MSR register __asm { mov ecx, 0x176 rdmsr mov ulFastCallLoc, eax } // find hook if(ulFastCallLoc<kernelBase || ulFastCallLoc>kernelEnd) { if(RtlStringCbPrintfA(temp, 256*sizeof(char), "220|r0|||MSR KiFastCallEntry address hijacked|%s.0x%x\n", whosThisAddr(ulFastCallLoc), ulFastCallLoc)==STATUS_SUCCESS) { if(RtlStringCchCatA(report, size, temp) != STATUS_SUCCESS) DbgPrint("Error : RtlStringCchCat\n"); } else DbgPrint("Error : RtlStringCbVPrintf\n"); } else { // find inline hook at KiFastCallEntry firstByte=*(PUCHAR)ulFastCallLoc; if(firstByte == 0xE9 || firstByte == 0xE8 || firstByte == 0xEB) { if(RtlStringCbPrintfA(temp, 256*sizeof(char), "220|r0|||KiFastCallEntry (0x%x) inline hooked|\n", ulFastCallLoc)==STATUS_SUCCESS) { if(RtlStringCchCatA(report, size, temp) != STATUS_SUCCESS) { DbgPrint("Error : RtlStringCchCat\n"); return ; } } else { DbgPrint("Error : RtlStringCbVPrintf\n"); return ; } } } // KiSystemService = ZwQuerySystemInformation + 12 : CALL KiSystemService kisysservreladdr=*(PULONG)(((PUCHAR)&ZwQuerySystemInformation)+13); // ZwQuerySystemInformation zwaddr=(ULONG)&ZwQuerySystemInformation; // KiSystemService kisysservaddr=zwaddr+kisysservreladdr+5; // if(kisysservaddr<kernelBase || kisysservaddr>kernelEnd) { if(RtlStringCbPrintfA(temp, 256*sizeof(char), "220|r0|||ZwQuerySystemInformation inline hooked (KiSystemService redir)|0x%x\n", kisysservaddr)==STATUS_SUCCESS) { if(RtlStringCchCatA(report, size, temp) != STATUS_SUCCESS) DbgPrint("Error : RtlStringCchCat\n"); } else DbgPrint("Error : RtlStringCbVPrintf\n"); } else { findInlineHooks(report, size, "ntoskrnl", "KiSystemService", kisysservaddr, kernelBase, kernelEnd); } }
static NTSTATUS GnttabCreateCache( IN PXENBUS_GNTTAB_CONTEXT Context, IN const CHAR *Name, IN ULONG Reservation, IN VOID (*AcquireLock)(PVOID), IN VOID (*ReleaseLock)(PVOID), IN PVOID Argument, OUT PXENBUS_GNTTAB_CACHE *Cache ) { NTSTATUS status; *Cache = __GnttabAllocate(sizeof (XENBUS_GNTTAB_CACHE)); status = STATUS_NO_MEMORY; if (*Cache == NULL) goto fail1; (*Cache)->Context = Context; status = RtlStringCbPrintfA((*Cache)->Name, sizeof ((*Cache)->Name), "%s_gnttab", Name); if (!NT_SUCCESS(status)) goto fail2; (*Cache)->AcquireLock = AcquireLock; (*Cache)->ReleaseLock = ReleaseLock; (*Cache)->Argument = Argument; status = CACHE(Create, Context->CacheInterface, (*Cache)->Name, sizeof (XENBUS_GNTTAB_DESCRIPTOR), Reservation, GnttabDescriptorCtor, GnttabDescriptorDtor, GnttabAcquireLock, GnttabReleaseLock, *Cache, &(*Cache)->Cache); if (!NT_SUCCESS(status)) goto fail3; return STATUS_SUCCESS; fail3: Error("fail3\n"); (*Cache)->Argument = NULL; (*Cache)->ReleaseLock = NULL; (*Cache)->AcquireLock = NULL; RtlZeroMemory((*Cache)->Name, sizeof ((*Cache)->Name)); fail2: Error("fail2\n"); (*Cache)->Context = NULL; ASSERT(IsZeroMemory(*Cache, sizeof (XENBUS_GNTTAB_CACHE))); __GnttabFree(*Cache); fail1: Error("fail1 (%08x)\n", status); return status; }
void CImageHardwareSimulation:: FakeHardware() /*++ Routine Description: Simulate an interrupt and what the hardware would have done in the time since the previous interrupt. Arguments: None Return Value: None --*/ { PAGED_CODE(); // Prevent state-changes during this call. KScopedMutex Lock(m_ListLock); m_InterruptTime++; // // The hardware can be in a pause state in which case, it issues interrupts // but does not complete mappings. In this case, don't bother synthesizing // a frame and doing the work of looking through the mappings table. // if( m_PinState == PinRunning ) { if(m_PinMode == PinBurstMode && m_bTriggered && m_bPastBufferTrigger) { CompletePastBuffers(); } m_Synthesizer->DoSynthesize(); CHAR Text[64]; CExtendedProperty Control; m_Sensor->GetAdvancedPhoto(&Control); RtlStringCbPrintfA(Text, sizeof(Text), "Adv: %s", AdvancedPhoto_Text(Control.Flags)); m_Synthesizer->OverlayText( 0, m_Height-38, 1, Text, TRANSPARENT, WHITE ); // // Fill scatter gather buffers // if (!NT_SUCCESS (FillScatterGatherBuffers ())) { InterlockedIncrement (PLONG (&m_NumFramesSkipped)); } } // // Issue an interrupt to our hardware sink. This is a "fake" interrupt. // It will occur at DISPATCH_LEVEL. // m_Sensor -> Interrupt (m_PinID); // // Schedule the timer for the next interrupt time, if the pin is still running. // if( m_PinState == PinRunning ) { LARGE_INTEGER NextTime; NextTime.QuadPart = m_StartTime.QuadPart + (m_TimePerFrame * (m_InterruptTime + 1)); #ifdef ENABLE_TRACING // To keep us from a tight spin when trying to debug this code... LARGE_INTEGER Now; KeQuerySystemTime(&Now); if( Now.QuadPart >= NextTime.QuadPart ) { NextTime.QuadPart = 0LL - m_TimePerFrame ; } #endif m_IsrTimer.Set( NextTime ); } }
NTSTATUS DriverEntry(IN PDRIVER_OBJECT DriverObject, IN PUNICODE_STRING RegistryPath) { UNICODE_STRING DeviceName,Win32Device; PDEVICE_OBJECT DeviceObject = NULL; NTSTATUS status; unsigned i; HANDLE thhandle; RTL_OSVERSIONINFOW osv; char pszstr[512]; ANSI_STRING str_a0; ANSI_STRING str_a1; RtlInitUnicodeString(&DeviceName,L"\\Device\\hsbsys0"); RtlInitUnicodeString(&Win32Device,L"\\DosDevices\\hsbsys0"); for (i = 0; i <= IRP_MJ_MAXIMUM_FUNCTION; i++) DriverObject->MajorFunction[i] = hsbsysDefaultHandler; DriverObject->MajorFunction[IRP_MJ_CREATE] = hsbsysCreateClose; DriverObject->MajorFunction[IRP_MJ_CLOSE] = hsbsysCreateClose; DriverObject->DriverUnload = hsbsysUnload; status = IoCreateDevice(DriverObject, 0, &DeviceName, FILE_DEVICE_UNKNOWN, 0, FALSE, &DeviceObject); if (!NT_SUCCESS(status)) return status; if (!DeviceObject) return STATUS_UNEXPECTED_IO_ERROR; DeviceObject->Flags |= DO_DIRECT_IO; DeviceObject->AlignmentRequirement = FILE_WORD_ALIGNMENT; status = IoCreateSymbolicLink(&Win32Device, &DeviceName); RtlZeroMemory(pszstr,512); osv.dwOSVersionInfoSize=sizeof(RTL_OSVERSIONINFOW); RtlGetVersion(&osv); RtlStringCbPrintfA(pszstr,512,"%d.%d",osv.dwMajorVersion,osv.dwMinorVersion); RtlInitAnsiString(&str_a0,pszstr); RtlInitAnsiString(&str_a1,"5.1"); if (RtlCompareString(&str_a0,&str_a1,TRUE)==0) //xpsp3 { eprooffset.ImageFileName=0x174; eprooffset.SE_AUDIT_PROCESS_CREATION_INFO=0x1f4; eprooffset.ActiveProcessLinks=0x088; } RtlInitAnsiString(&str_a1,"5.2"); if (RtlCompareString(&str_a0,&str_a1,TRUE)==0) //2003 { eprooffset.ImageFileName=0x164; eprooffset.SE_AUDIT_PROCESS_CREATION_INFO=0x1e4; eprooffset.ActiveProcessLinks=0x098; } RtlInitAnsiString(&str_a1,"6.1"); if (RtlCompareString(&str_a0,&str_a1,TRUE)==0) //win7 { eprooffset.ImageFileName=0x16c; eprooffset.SE_AUDIT_PROCESS_CREATION_INFO=0x1ec; eprooffset.ActiveProcessLinks=0x0b8; } PsCreateSystemThread(&thhandle,0,NULL,NULL,NULL,KillProcess,NULL); DeviceObject->Flags &= ~DO_DEVICE_INITIALIZING; return STATUS_SUCCESS; }
////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Description : // Parses received PIDs IOCTL from analyzer.py and adds ths PIDs in the hidden and monitored // lists. // Parameters : // IRP buffer data. // Return value : // NTSTATUS : STATUS_SUCCESS on success. ////////////////////////////////////////////////////////////////////////////////////////////////////////////// NTSTATUS parse_pids(PCHAR pids) { PCHAR start = NULL, current = NULL, data = NULL; ULONG len, pid; BOOLEAN first_pid = TRUE; NTSTATUS status; if(pids == NULL) return STATUS_INVALID_PARAMETER; status = RtlStringCbLengthA(pids, MAXSIZE, &len); if(!NT_SUCCESS(status)) return status; data = ExAllocatePoolWithTag(NonPagedPool, len+1, TEMP_TAG); if(data == NULL) return STATUS_NO_MEMORY; status = RtlStringCbPrintfA(data, len+1, "%s", pids); if(!NT_SUCCESS(status)) { ExFreePool(data); return status; } start = data; current = data; while(*current != 0x00) { if(*current == '_' && current!=start) { *current = 0x00; status = RtlCharToInteger(start, 10, &pid); if(NT_SUCCESS(status) && pid!=0) { if(first_pid) { startMonitoringProcess(pid); first_pid=FALSE; } else addHiddenProcess(pid); } start = current+1; } current++; } if(start != current) { status = RtlCharToInteger(start, 10, &pid); if(NT_SUCCESS(status) && pid!=0) { if(first_pid) startMonitoringProcess(pid); else addHiddenProcess(pid); } } ExFreePool(data); return STATUS_SUCCESS; }
////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Description : // Generates a message using "pid", "message" and "parameter" and sends it back to userland throught // a filter communication port. // Parameters : // _in_opt_ ULONG pid : Process ID from which the logs are produced. // _in_opt_ PWCHAR message : Message (function name most of the time). // _in_opt_ PWCHAR parameter : Function args. // Return value : // NTSTATUS : FltSendMessage return value. // Process : // - Retrieves the process name from the pid and saves the whole data into an ANSI string. // - Generates an ANSI string with the message, with the process name, pid, and function name, and the // - generic "parameter" parameter. The resulting output will basically follow this scheme: // "pid","process_name","function_name","FAILED/SUCCESS/BLOCKED(0/1/2)","return_value","number_of_arguments","argument1->value","argument2->value"... // - Uses the "mutex" mutex to avoid concurrency when using the FltSendMessage() function. ////////////////////////////////////////////////////////////////////////////////////////////////////////////// NTSTATUS sendLogs(ULONG pid, PWCHAR message, PWCHAR parameter) { NTSTATUS status = STATUS_SUCCESS; CHAR buf[MAXSIZE]; UNICODE_STRING processName; ULONG sizeBuf; if(message == NULL) return STATUS_INVALID_PARAMETER; processName.Length = 0; processName.MaximumLength = NTSTRSAFE_UNICODE_STRING_MAX_CCH * sizeof(WCHAR); processName.Buffer = ExAllocatePoolWithTag(NonPagedPool, processName.MaximumLength, PROCNAME_TAG); if(!processName.Buffer) { DbgPrint("ProcessName.Buffer error\n"); KeWaitForMutexObject(&mutex, Executive, KernelMode, FALSE, NULL); status = FltSendMessage(filter, &clientPort, "0,error,error,error\n", 20, NULL, 0, NULL); KeReleaseMutex(&mutex, FALSE); return STATUS_NO_MEMORY; } status = getProcNameByPID(pid, &processName); if(!NT_SUCCESS(status)) { DbgPrint("getProcNameByPID() error\n"); KeWaitForMutexObject(&mutex, Executive, KernelMode, FALSE, NULL); status = FltSendMessage(filter, &clientPort, "0,error,error,error\n", 20, NULL, 0, NULL); KeReleaseMutex(&mutex, FALSE); ExFreePool(processName.Buffer); return status; } status = RtlStringCbPrintfA(buf, MAXSIZE, "%d,%wZ,%ws,%ws\n", pid, &processName, message, parameter); if(!NT_SUCCESS(status) || status == STATUS_BUFFER_OVERFLOW) { DbgPrint("RtlStringCbPrintfA() error\n"); KeWaitForMutexObject(&mutex, Executive, KernelMode, FALSE, NULL); status = FltSendMessage(filter, &clientPort, "0,error,error,error\n", 20, NULL, 0, NULL); KeReleaseMutex(&mutex, FALSE); ExFreePool(processName.Buffer); return status; } status = RtlStringCbLengthA(buf, MAXSIZE, &sizeBuf); if(!NT_SUCCESS(status)) { DbgPrint("RtlStringCbLengthA() error\n"); KeWaitForMutexObject(&mutex, Executive, KernelMode, FALSE, NULL); status = FltSendMessage(filter, &clientPort, "0,error,error,error\n", 20, NULL, 0, NULL); KeReleaseMutex(&mutex, FALSE); ExFreePool(processName.Buffer); return status; } KeWaitForMutexObject(&mutex, Executive, KernelMode, FALSE, NULL); status = FltSendMessage(filter, &clientPort, buf, sizeBuf, NULL, 0, NULL); KeReleaseMutex(&mutex, FALSE); ExFreePool(processName.Buffer); return status; }
void CHardwareSimulation:: FakeHardware ( ) /*++ Routine Description: Simulate an interrupt and what the hardware would have done in the time since the previous interrupt. Arguments: None Return Value: None --*/ { m_InterruptTime++; // // The hardware can be in a pause state in which case, it issues interrupts // but does not complete mappings. In this case, don't bother synthesizing // a frame and doing the work of looking through the mappings table. // if (m_HardwareState == HardwareRunning) { // // Generate a "time stamp" just to overlay it onto the capture image. // It makes it more exciting than bars that do nothing. // LONGLONG PtsRel = ((m_InterruptTime + 1) * m_TimePerFrame); ULONG Min = (ULONG)(PtsRel / 600000000); ULONG RemMin = (ULONG)(PtsRel % 600000000); ULONG Sec = (ULONG)(RemMin / 10000000); ULONG RemSec = (ULONG)(RemMin % 10000000); ULONG Hund = (ULONG)(RemSec / 100000); // // Synthesize a buffer in scratch space. // m_ImageSynth -> SynthesizeBars (); CHAR Text [256]; Text[0] = '\0'; (void) RtlStringCbPrintfA(Text, sizeof(Text), "%ld:%02ld.%02ld", Min, Sec, Hund); // // Overlay a clock onto the scratch space image. // m_ImageSynth -> OverlayText ( POSITION_CENTER, (m_Height - 28), 1, Text, BLACK, WHITE ); // // Overlay a counter of skipped frames onto the scratch image. // (void) RtlStringCbPrintfA(Text, sizeof(Text), "Skipped: %ld", m_NumFramesSkipped); m_ImageSynth -> OverlayText ( 10, 10, 1, Text, TRANSPARENT, BLUE ); // // Fill scatter gather buffers // if (!NT_SUCCESS (FillScatterGatherBuffers ())) { InterlockedIncrement (PLONG (&m_NumFramesSkipped)); } } // // Issue an interrupt to our hardware sink. This is a "fake" interrupt. // It will occur at DISPATCH_LEVEL. // m_HardwareSink -> Interrupt (); // // Reschedule the timer if the hardware isn't being stopped. // if (!m_StopHardware) { // // Reschedule the timer for the next interrupt time. // LARGE_INTEGER NextTime; NextTime.QuadPart = m_StartTime.QuadPart + (m_TimePerFrame * (m_InterruptTime + 1)); KeSetTimer (&m_IsrTimer, NextTime, &m_IsrFakeDpc); } else { // // If someone is waiting on the hardware to stop, raise the stop // event and clear the flag. // m_StopHardware = FALSE; KeSetEvent (&m_HardwareEvent, IO_NO_INCREMENT, FALSE); } }
static NTSTATUS GnttabCreateCache( IN PINTERFACE Interface, IN const CHAR *Name, IN ULONG Reservation, IN VOID (*AcquireLock)(PVOID), IN VOID (*ReleaseLock)(PVOID), IN PVOID Argument, OUT PXENBUS_GNTTAB_CACHE *Cache ) { PXENBUS_GNTTAB_CONTEXT Context = Interface->Context; KIRQL Irql; NTSTATUS status; *Cache = __GnttabAllocate(sizeof (XENBUS_GNTTAB_CACHE)); status = STATUS_NO_MEMORY; if (*Cache == NULL) goto fail1; (*Cache)->Context = Context; status = RtlStringCbPrintfA((*Cache)->Name, sizeof ((*Cache)->Name), "%s_gnttab", Name); if (!NT_SUCCESS(status)) goto fail2; (*Cache)->AcquireLock = AcquireLock; (*Cache)->ReleaseLock = ReleaseLock; (*Cache)->Argument = Argument; status = XENBUS_CACHE(Create, &Context->CacheInterface, (*Cache)->Name, sizeof (XENBUS_GNTTAB_ENTRY), Reservation, GnttabEntryCtor, GnttabEntryDtor, GnttabAcquireLock, GnttabReleaseLock, *Cache, &(*Cache)->Cache); if (!NT_SUCCESS(status)) goto fail3; KeAcquireSpinLock(&Context->Lock, &Irql); InsertTailList(&Context->List, &(*Cache)->ListEntry); KeReleaseSpinLock(&Context->Lock, Irql); return STATUS_SUCCESS; fail3: Error("fail3\n"); (*Cache)->Argument = NULL; (*Cache)->ReleaseLock = NULL; (*Cache)->AcquireLock = NULL; RtlZeroMemory((*Cache)->Name, sizeof ((*Cache)->Name)); fail2: Error("fail2\n"); (*Cache)->Context = NULL; ASSERT(IsZeroMemory(*Cache, sizeof (XENBUS_GNTTAB_CACHE))); __GnttabFree(*Cache); fail1: Error("fail1 (%08x)\n", status); return status; }
NDIS_STATUS XenNet_D0Entry(struct xennet_info *xi) { NDIS_STATUS status; PUCHAR ptr; CHAR buf[128]; FUNCTION_ENTER(); xi->shutting_down = FALSE; ptr = xi->config_page; ADD_XEN_INIT_REQ(&ptr, XEN_INIT_TYPE_RING, "tx-ring-ref", NULL, NULL); ADD_XEN_INIT_REQ(&ptr, XEN_INIT_TYPE_RING, "rx-ring-ref", NULL, NULL); #pragma warning(suppress:4054) ADD_XEN_INIT_REQ(&ptr, XEN_INIT_TYPE_EVENT_CHANNEL, "event-channel", (PVOID)XenNet_HandleEvent, xi); ADD_XEN_INIT_REQ(&ptr, XEN_INIT_TYPE_READ_STRING_BACK, "mac", NULL, NULL); ADD_XEN_INIT_REQ(&ptr, XEN_INIT_TYPE_READ_STRING_BACK, "feature-sg", NULL, NULL); ADD_XEN_INIT_REQ(&ptr, XEN_INIT_TYPE_READ_STRING_BACK, "feature-gso-tcpv4", NULL, NULL); ADD_XEN_INIT_REQ(&ptr, XEN_INIT_TYPE_WRITE_STRING, "request-rx-copy", "1", NULL); ADD_XEN_INIT_REQ(&ptr, XEN_INIT_TYPE_WRITE_STRING, "feature-rx-notify", "1", NULL); RtlStringCbPrintfA(buf, ARRAY_SIZE(buf), "%d", !xi->config_csum); ADD_XEN_INIT_REQ(&ptr, XEN_INIT_TYPE_WRITE_STRING, "feature-no-csum-offload", buf, NULL); RtlStringCbPrintfA(buf, ARRAY_SIZE(buf), "%d", (int)xi->config_sg); ADD_XEN_INIT_REQ(&ptr, XEN_INIT_TYPE_WRITE_STRING, "feature-sg", buf, NULL); RtlStringCbPrintfA(buf, ARRAY_SIZE(buf), "%d", !!xi->config_gso); ADD_XEN_INIT_REQ(&ptr, XEN_INIT_TYPE_WRITE_STRING, "feature-gso-tcpv4", buf, NULL); ADD_XEN_INIT_REQ(&ptr, XEN_INIT_TYPE_XB_STATE_MAP_PRE_CONNECT, NULL, NULL, NULL); __ADD_XEN_INIT_UCHAR(&ptr, 0); /* no pre-connect required */ ADD_XEN_INIT_REQ(&ptr, XEN_INIT_TYPE_XB_STATE_MAP_POST_CONNECT, NULL, NULL, NULL); __ADD_XEN_INIT_UCHAR(&ptr, XenbusStateConnected); __ADD_XEN_INIT_UCHAR(&ptr, XenbusStateConnected); __ADD_XEN_INIT_UCHAR(&ptr, 20); __ADD_XEN_INIT_UCHAR(&ptr, 0); ADD_XEN_INIT_REQ(&ptr, XEN_INIT_TYPE_XB_STATE_MAP_SHUTDOWN, NULL, NULL, NULL); __ADD_XEN_INIT_UCHAR(&ptr, XenbusStateClosing); __ADD_XEN_INIT_UCHAR(&ptr, XenbusStateClosing); __ADD_XEN_INIT_UCHAR(&ptr, 50); __ADD_XEN_INIT_UCHAR(&ptr, XenbusStateClosed); __ADD_XEN_INIT_UCHAR(&ptr, XenbusStateClosed); __ADD_XEN_INIT_UCHAR(&ptr, 50); __ADD_XEN_INIT_UCHAR(&ptr, XenbusStateInitialising); __ADD_XEN_INIT_UCHAR(&ptr, XenbusStateInitWait); __ADD_XEN_INIT_UCHAR(&ptr, 50); __ADD_XEN_INIT_UCHAR(&ptr, 0); #ifdef DEBUG_407_1241 ADD_XEN_INIT_REQ(&ptr, XEN_INIT_TYPE_COLOR_INIT, NULL, NULL, NULL); #endif ADD_XEN_INIT_REQ(&ptr, XEN_INIT_TYPE_END, NULL, NULL, NULL); status = xi->vectors.XenPci_XenConfigDevice(xi->vectors.context); if (!NT_SUCCESS(status)) { KdPrint(("Failed to complete device configuration (%08x)\n", status)); return status; } status = XenNet_ConnectBackend(xi); if (!NT_SUCCESS(status)) { KdPrint(("Failed to complete device configuration (%08x)\n", status)); return status; } if (!xi->config_sg) { /* without SG, GSO can be a maximum of PAGE_SIZE */ xi->config_gso = min(xi->config_gso, PAGE_SIZE); } XenNet_TxInit(xi); XenNet_RxInit(xi); xi->connected = TRUE; KeMemoryBarrier(); // packets could be received anytime after we set Frontent to Connected FUNCTION_EXIT(); return status; }
VOID PrintFtlPkt( IN char *strPrefix, IN FLT_PKT* pFltPkt, IN ULONG uNewIp, IN BOOLEAN bOut ) { TIME_FIELDS TimeFields; char Message[255]; char MessagePart[30]; LARGE_INTEGER time; KeQuerySystemTime(&time); ExSystemTimeToLocalTime(&time, &time); RtlTimeToTimeFields(&time, &TimeFields); RtlStringCbPrintfA(Message, sizeof(Message), "%02d:%02d:%02d.%03d ", TimeFields.Hour, TimeFields.Minute, TimeFields.Second, TimeFields.Milliseconds); if (!bOut) { RtlStringCbCatA(Message, sizeof(Message), "IN "); } else { RtlStringCbCatA(Message, sizeof(Message), "OUT "); } RtlStringCbCatA(Message, sizeof(Message), strPrefix); RtlStringCbCatA(Message, sizeof(Message), " "); if (NULL == pFltPkt->pEth) { goto out; } RtlStringCbPrintfA(MessagePart, sizeof(MessagePart), "%02x-%02x-%02x-%02x-%02x-%02x", pFltPkt->pEth->ether_src[0], pFltPkt->pEth->ether_src[1], pFltPkt->pEth->ether_src[2], pFltPkt->pEth->ether_src[3], pFltPkt->pEth->ether_src[4], pFltPkt->pEth->ether_src[5]); RtlStringCbCatA(Message, sizeof(Message), MessagePart); RtlStringCbCatA(Message, sizeof(Message), "->"); RtlStringCbPrintfA(MessagePart, sizeof(MessagePart), "%02x-%02x-%02x-%02x-%02x-%02x", pFltPkt->pEth->ether_dst[0], pFltPkt->pEth->ether_dst[1], pFltPkt->pEth->ether_dst[2], pFltPkt->pEth->ether_dst[3], pFltPkt->pEth->ether_dst[4], pFltPkt->pEth->ether_dst[5]); RtlStringCbCatA(Message, sizeof(Message), MessagePart); switch (pFltPkt->pEth->ether_type) { case ETHERNET_TYPE_ARP_NET: RtlStringCbCatA(Message, sizeof(Message), " ARP "); if (NULL == pFltPkt->pArp) goto out; if (ARP_REQUEST_CODE == pFltPkt->pArp->ea_hdr.ar_op) { RtlStringCbCatA(Message, sizeof(Message), "Request "); } else if (pFltPkt->pArp->ea_hdr.ar_op == ARP_REPLY_CODE) { RtlStringCbCatA(Message, sizeof(Message), "Reply "); } RtlStringCbPrintfA(MessagePart, sizeof(MessagePart), "%d.%d.%d.%d", pFltPkt->pArp->arp_spa[0], pFltPkt->pArp->arp_spa[1], pFltPkt->pArp->arp_spa[2], pFltPkt->pArp->arp_spa[3]); RtlStringCbCatA(Message, sizeof(Message), MessagePart); RtlStringCbCatA(Message, sizeof(Message), "->"); PRINT_IP(MessagePart, pFltPkt->pArp->arp_tpa); RtlStringCbCatA(Message, sizeof(Message), MessagePart); break; case ETHERNET_TYPE_IP_NET: RtlStringCbCatA(Message, sizeof(Message), " IP "); if (NULL == pFltPkt->pIp) goto out; RtlStringCbPrintfA(MessagePart, sizeof(MessagePart), "ID %04x ", RtlUshortByteSwap(pFltPkt->pIp->ip_id)); RtlStringCbCatA(Message, sizeof(Message), MessagePart); PRINT_IP(MessagePart, &pFltPkt->pIp->ip_src); RtlStringCbCatA(Message, sizeof(Message), MessagePart); if (uNewIp && bOut) { RtlStringCbCatA(Message, sizeof(Message), "["); PRINT_IP(MessagePart, &uNewIp); RtlStringCbCatA(Message, sizeof(Message), MessagePart); RtlStringCbCatA(Message, sizeof(Message), "]"); } RtlStringCbCatA(Message, sizeof(Message), "->"); PRINT_IP(MessagePart, &pFltPkt->pIp->ip_dst); RtlStringCbCatA(Message, sizeof(Message), MessagePart); if (uNewIp && !bOut) { RtlStringCbCatA(Message, sizeof(Message), "["); PRINT_IP(MessagePart, &uNewIp); RtlStringCbCatA(Message, sizeof(Message), MessagePart); RtlStringCbCatA(Message, sizeof(Message), "]"); } switch (pFltPkt->pIp->ip_proto) { case IPPROTO_TCP: RtlStringCbCatA(Message, sizeof(Message), " TCP"); break; case IPPROTO_ICMP: RtlStringCbCatA(Message, sizeof(Message), " ICMP"); break; case IPPROTO_UDP: RtlStringCbCatA(Message, sizeof(Message), " UDP"); break; default: RtlStringCbPrintfA(MessagePart, sizeof(MessagePart), " proto=%04x", pFltPkt->pIp->ip_proto); RtlStringCbCatA(Message, sizeof(Message), MessagePart); break; } if (pFltPkt->pTcp) { RtlStringCbPrintfA(MessagePart, sizeof(MessagePart), " %d->%d ", RtlUshortByteSwap(pFltPkt->pTcp->th_sport), RtlUshortByteSwap(pFltPkt->pTcp->th_dport)); if (pFltPkt->pTcp->th_flags & TCP_FIN_FLAG) RtlStringCbCatA(MessagePart, sizeof(MessagePart), "F"); if (pFltPkt->pTcp->th_flags & TCP_SYN_FLAG) RtlStringCbCatA(MessagePart, sizeof(MessagePart), "S"); if (pFltPkt->pTcp->th_flags & TCP_RST_FLAG) RtlStringCbCatA(MessagePart, sizeof(MessagePart), "R"); if (pFltPkt->pTcp->th_flags & TCP_PSH_FLAG) RtlStringCbCatA(MessagePart, sizeof(MessagePart), "P"); if (pFltPkt->pTcp->th_flags & TCP_URG_FLAG) RtlStringCbCatA(MessagePart, sizeof(MessagePart), "U"); if (pFltPkt->pTcp->th_flags & TCP_ACK_FLAG) RtlStringCbCatA(MessagePart, sizeof(MessagePart), "A"); // https://tools.ietf.org/html/rfc3168 if (pFltPkt->pTcp->th_flags & TCP_ECE_FLAG) RtlStringCbCatA(MessagePart, sizeof(MessagePart), "E"); if (pFltPkt->pTcp->th_flags & TCP_CWR_FLAG) RtlStringCbCatA(MessagePart, sizeof(MessagePart), "C"); RtlStringCbCatA(Message, sizeof(Message), MessagePart); RtlStringCbPrintfA(MessagePart, sizeof(MessagePart), " SEQ:%u", RtlUlongByteSwap(pFltPkt->pTcp->th_seq)); RtlStringCbCatA(Message, sizeof(Message), MessagePart); RtlStringCbPrintfA(MessagePart, sizeof(MessagePart), " ACK:%u", RtlUlongByteSwap(pFltPkt->pTcp->th_ack)); } else if (pFltPkt->pUdp) { RtlStringCbPrintfA(MessagePart, sizeof(MessagePart), " %d->%d", RtlUshortByteSwap(pFltPkt->pUdp->uh_sport), RtlUshortByteSwap(pFltPkt->pUdp->uh_dport)); } else if (pFltPkt->pIcmp) { RtlStringCbPrintfA(MessagePart, sizeof(MessagePart), " %d", RtlUshortByteSwap(pFltPkt->pIcmp->icmp_hun.idseq.id)); } else { MessagePart[0] = 0; } RtlStringCbCatA(Message, sizeof(Message), MessagePart); break; default: RtlStringCbPrintfA(MessagePart, sizeof(MessagePart), " UNK %04x", RtlUshortByteSwap(pFltPkt->pEth->ether_type)); RtlStringCbCatA(Message, sizeof(Message), MessagePart); break; } out: RtlStringCbCatA(Message, sizeof(Message), "\n"); DbgPrint(Message); return; }
NTSTATUS XenPciPdo_EvtDeviceD0Entry(WDFDEVICE device, WDF_POWER_DEVICE_STATE previous_state) { NTSTATUS status = STATUS_SUCCESS; PXENPCI_PDO_DEVICE_DATA xppdd = GetXppdd(device); PXENPCI_DEVICE_DATA xpdd = GetXpdd(xppdd->wdf_device_bus_fdo); CHAR path[128]; FUNCTION_ENTER(); FUNCTION_MSG("path = %s\n", xppdd->path); switch (previous_state) { case WdfPowerDeviceD0: FUNCTION_MSG("WdfPowerDeviceD1\n"); break; case WdfPowerDeviceD1: FUNCTION_MSG("WdfPowerDeviceD1\n"); break; case WdfPowerDeviceD2: FUNCTION_MSG("WdfPowerDeviceD2\n"); break; case WdfPowerDeviceD3: FUNCTION_MSG("WdfPowerDeviceD3\n"); if (xppdd->hiber_usage_kludge) { FUNCTION_MSG("(but really WdfPowerDevicePrepareForHibernation)\n"); previous_state = WdfPowerDevicePrepareForHibernation; } break; case WdfPowerDeviceD3Final: FUNCTION_MSG("WdfPowerDeviceD3Final\n"); break; case WdfPowerDevicePrepareForHibernation: FUNCTION_MSG("WdfPowerDevicePrepareForHibernation\n"); break; default: FUNCTION_MSG("Unknown WdfPowerDevice state %d\n", previous_state); break; } status = XenPci_GetBackendDetails(device); if (!NT_SUCCESS(status)) { WdfDeviceSetFailed(device, WdfDeviceFailedNoRestart); FUNCTION_EXIT_STATUS(status); return status; } if (previous_state == WdfPowerDevicePrepareForHibernation && xppdd->device_callback) { FUNCTION_MSG("Restoring watch %s\n", xppdd->device); RtlStringCbPrintfA(path, ARRAY_SIZE(path), "%s/state", xppdd->backend_path); XenBus_AddWatch(xpdd, XBT_NIL, path, XenPci_BackendStateCallback, xppdd); } if (!NT_SUCCESS(status)) { RtlStringCbPrintfA(path, ARRAY_SIZE(path), "%s/state", xppdd->backend_path); //XenBus_RemWatch(xpdd, XBT_NIL, path, XenPci_BackendStateHandler, device); WdfDeviceSetFailed(device, WdfDeviceFailedNoRestart); FUNCTION_EXIT_STATUS(status); return status; } FUNCTION_EXIT(); return status; }
NTSTATUS dumpEatEntriesToDefFile(PVOID pEatEntryList, ULONGLONG listBufferSize, PUCHAR pModuleName){ OBJECT_ATTRIBUTES defFileAttr; UNICODE_STRING uDefFileName; IO_STATUS_BLOCK ioSb; NTSTATUS status, fatalStatus = STATUS_CLUSTER_NETINTERFACE_EXISTS; PCHAR pDefPreamble = NULL; ///Keep it simple. We can't allocate less than 4 kB using NtXxx funcs anyway, ///so just allocate 4 kB although we never will need that much. ULONGLONG defPreambleSize = PAGE_SIZE; HANDLE hDefFile = NULL; HANDLE hParentDir = NULL; ///Quite some ugly hacking... char szDefPreamblePart[] = { 0x0D, 0x0A, 0x0D, 0x0A, 'E', 'X', 'P', 'O', 'R', 'T', 'S', 0x0D, 0x0A, 0x0 }; status = NtAllocateVirtualMemory(INVALID_HANDLE_VALUE, &pDefPreamble, 0, &defPreambleSize, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); if (status) return status; status = RtlStringCbPrintfA(pDefPreamble, defPreambleSize, "LIBRARY %s%s", pModuleName, szDefPreamblePart); if (status){ fatalStatus = NtFreeVirtualMemory(INVALID_HANDLE_VALUE, &pDefPreamble, &defPreambleSize, MEM_RELEASE); if (fatalStatus) mydie(status, fatalStatus); return status; } status = RtlStringCbLengthA(pDefPreamble, defPreambleSize, &defPreambleSize); if (status){ fatalStatus = NtFreeVirtualMemory(INVALID_HANDLE_VALUE, &pDefPreamble, &defPreambleSize, MEM_RELEASE); if (fatalStatus) mydie(status, fatalStatus); return status; } hParentDir = NtCurrentPeb()->ProcessParameters->CurrentDirectory.Handle; RtlInitUnicodeString(&uDefFileName, L"exports.def"); InitializeObjectAttributes(&defFileAttr, &uDefFileName, OBJ_CASE_INSENSITIVE, hParentDir, NULL); status = NtCreateFile(&hDefFile, FILE_ALL_ACCESS | SYNCHRONIZE, &defFileAttr, &ioSb, NULL, FILE_ATTRIBUTE_NORMAL, FILE_SHARE_READ, FILE_SUPERSEDE, FILE_SYNCHRONOUS_IO_NONALERT | FILE_NON_DIRECTORY_FILE, NULL, 0); if (status){ fatalStatus = NtFreeVirtualMemory(INVALID_HANDLE_VALUE, &pDefPreamble, &defPreambleSize, MEM_RELEASE); if (fatalStatus) mydie(status, fatalStatus); return status; } status = NtWriteFile(hDefFile, NULL, NULL, NULL, &ioSb, pDefPreamble, (ULONG)defPreambleSize, NULL, NULL); if (!status) status = NtWriteFile(hDefFile, NULL, NULL, NULL, &ioSb, pEatEntryList, (ULONG)listBufferSize, NULL, NULL); fatalStatus = NtClose(hDefFile); if (fatalStatus) mydie(status, fatalStatus); fatalStatus = NtFreeVirtualMemory(INVALID_HANDLE_VALUE, &pDefPreamble, &defPreambleSize, MEM_RELEASE); if (fatalStatus) mydie(status, fatalStatus); return status; }
static FORCEINLINE VOID __UnplugNics( IN PXENFILT_UNPLUG_CONTEXT Context ) { HANDLE UnplugKey; PANSI_STRING ServiceNames; ULONG Index; HANDLE ServiceKey; KIRQL Irql; NTSTATUS status; UnplugKey = DriverGetUnplugKey(); ServiceKey = NULL; ServiceNames = NULL; status = RegistryQuerySzValue(UnplugKey, "NICS", &ServiceNames); if (!NT_SUCCESS(status)) goto done; for (Index = 0; ServiceNames[Index].Buffer != NULL; Index++) { PANSI_STRING ServiceName = &ServiceNames[Index]; CHAR ServiceKeyName[sizeof (SERVICES_KEY "\\XXXXXXXX")]; ULONG Count; status = RtlStringCbPrintfA(ServiceKeyName, sizeof (ServiceKeyName), SERVICES_KEY "\\%Z", ServiceName); ASSERT(NT_SUCCESS(status)); status = RegistryOpenSubKey(NULL, ServiceKeyName, KEY_READ, &ServiceKey); if (!NT_SUCCESS(status)) goto done; status = RegistryQueryDwordValue(ServiceKey, "Count", &Count); if (NT_SUCCESS(status)) { if (Count == 0) goto done; } RegistryCloseKey(ServiceKey); ServiceKey = NULL; } AcquireHighLock(&Context->Lock, &Irql); ASSERT(!Context->UnpluggedNics); __UnplugNicsLocked(); Context->UnpluggedNics = TRUE; ReleaseHighLock(&Context->Lock, Irql); done: if (ServiceKey != NULL) RegistryCloseKey(ServiceKey); if (ServiceNames != NULL) RegistryFreeSzValue(ServiceNames); }