Hide a process from Task Manager - windows

I'm trying to hide a process from the taskmanager but it doesn't work .
I dont understand why ...
Thank you for your help in advance... !
This is my function who inject the hider_dll.dll :
int Inject(char* dll)
{
int pid = getpid();
HANDLE hProc=OpenProcess(PROCESS_ALL_ACCESS,false,pid);
if(hProc)
{
cout<<"OpenProcess success"<<endl;
}
else
{
cout<<"OpenProcess failed..."<<endl;
return 0;
}
LPVOID Vmem=VirtualAllocEx(hProc,0,strlen(dll)+1,MEM_COMMIT|MEM_RESERVE,PAGE_READWRITE);
DWORD wrt;
WriteProcessMemory(hProc,Vmem,dll,strlen(dll),(SIZE_T*)&wrt);
stringstream sstr;
sstr << wrt;
string str = sstr.str();
cout<<"Writed "+str+" bytes"<<endl;
FARPROC LoadLib=GetProcAddress(LoadLibrary(L"kernel32.dll"),"LoadLibraryA");
HANDLE h=CreateRemoteThread(hProc,0,0,(LPTHREAD_START_ROUTINE)LoadLib,Vmem,0,0);
if(h)
{
cout<<"CreateRemoteThread success"<<endl;
}
else
{
cout<<"CreateRemoteThread failed\r\nError:"<<GetLastError()<<endl;
return 0;
}
WaitForSingleObject(h,INFINITE);
DWORD exit;
GetExitCodeThread(h,&exit);
cout<<"Dll loaded to "<<exit<<endl;
return 1;
}

Here is a proper injector:
#include <iostream>
#include <Windows.h>
#include <TlHelp32.h>
DWORD GetProcId(const char* procName)
{
DWORD procId = 0;
HANDLE hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (hSnap != INVALID_HANDLE_VALUE)
{
PROCESSENTRY32 procEntry;
procEntry.dwSize = sizeof(procEntry);
if (Process32First(hSnap, &procEntry))
{
do
{
if (!_stricmp(procEntry.szExeFile, procName))
{
procId = procEntry.th32ProcessID;
break;
}
} while (Process32Next(hSnap, &procEntry));
}
}
CloseHandle(hSnap);
return procId;
}
int main()
{
const char* dllPath = "C:\\Users\\'%USERNAME%'\\Desktop\\dll.dll"; //
const char* procName = "processname.exe"; //
DWORD procId = 0;
while (!procId)
{
procId = GetProcId(procName);
Sleep(30);
}
HANDLE hProc = OpenProcess(PROCESS_ALL_ACCESS, 0, procId);
if (hProc && hProc != INVALID_HANDLE_VALUE)
{
void* loc = VirtualAllocEx(hProc, 0, MAX_PATH, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
WriteProcessMemory(hProc, loc, dllPath, strlen(dllPath) + 1, 0);
HANDLE hThread = CreateRemoteThread(hProc, 0, 0, (LPTHREAD_START_ROUTINE)LoadLibraryA, loc, 0, 0);
if (hThread)
{
CloseHandle(hThread);
}
}
if (hProc)
{
CloseHandle(hProc);
}
return 0;
}
To hide processes from Task Manager you need to hook NtQuerySystemInformation() and if the argument SYSTEM_PROCESS_INFORMATION is used, you need to remove your process from the linked list of processes.
This is what your hook would look like:
// Hooked function
NTSTATUS WINAPI HookedNtQuerySystemInformation(
__in SYSTEM_INFORMATION_CLASS SystemInformationClass,
__inout PVOID SystemInformation,
__in ULONG SystemInformationLength,
__out_opt PULONG ReturnLength
)
{
NTSTATUS status = OriginalNtQuerySystemInformation(SystemInformationClass,
SystemInformation,
SystemInformationLength,
ReturnLength);
if (SystemProcessInformation == SystemInformationClass && STATUS_SUCCESS == status)
{
// Loop through the list of processes
PMY_SYSTEM_PROCESS_INFORMATION pCurrent = NULL;
PMY_SYSTEM_PROCESS_INFORMATION pNext = (PMY_SYSTEM_PROCESS_INFORMATION)
SystemInformation;
do
{
pCurrent = pNext;
pNext = (PMY_SYSTEM_PROCESS_INFORMATION)((PUCHAR)pCurrent + pCurrent->
NextEntryOffset);
if (!wcsncmp(pNext->ImageName.Buffer, L"notepad.exe", pNext->ImageName.Length))
{
if (!pNext->NextEntryOffset)
{
pCurrent->NextEntryOffset = 0;
}
else
{
pCurrent->NextEntryOffset += pNext->NextEntryOffset;
}
pNext = pCurrent;
}
} while (pCurrent->NextEntryOffset != 0);
}
return status;
}

Related

Error creating a screenshot in the winapi service

I have a client application written in C++, and a server written in Python. This application has several functions, including getting a screenshot of the client's desktop and getting this file on the server.
When I run these programs without any add-ons, everything works. I need to upload my client to the service, and I do it through CreateProcess[client file] inside of my service. All other functions besides the screenshot work with this approach.
Server code, getting a screenshot:
if (cState == State.GETTING_SCREENSHOT):
message = "SCREENSHOT".encode('utf-8')
MySend(client_sock , message)
curr_number = 0
with open("settings.txt" , 'r') as settings:
curr_number_str = settings.readline()
curr_number = int(curr_number_str)
with open("settings.txt" , 'w') as settings:
settings.write(str(curr_number + 1))
screenshot_file = str(curr_number) + ".png"
with open(screenshot_file , 'wb') as file:
while True:
data = MyRecv(client_sock , 40000)
data_arr = bytearray(data)
if (data_arr[:10] == b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'):
continue
if (b'ENDOFF' in data):
break
file.write(data)
cState = State.INPUT_COMMAND
Client code:
case SENDING_SCREENSHOT_IN_PROGRESS:
{
wchar_t PathToLocalAppDataFolder[MAX_PATH];
if (FAILED(SHGetFolderPathW(NULL, CSIDL_LOCAL_APPDATA, NULL, 0, PathToLocalAppDataFolder))) {
LoadMessage("Error in ShGetFolderPathW");
break;
}
std::wstring PathToScreenshot = std::wstring(PathToLocalAppDataFolder) + L"\\1.png";
if (!SaveScreen(PathToScreenshot.c_str())) {
LoadMessage("SaveScreen api-func failed");
break;
}
HANDLE hFile = CreateFile(PathToScreenshot.c_str(), GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE) {
LoadMessage("Can not open screenshot file");
break;
}
DWORD dwRead = 1;
BYTE buffSend[BIG_BUFFLEN];
while (dwRead) {
ZeroMemory(buffSend, BIG_BUFFLEN);
dwRead = 0;
ReadFile(hFile, buffSend, BIG_BUFFLEN, &dwRead, NULL);
MySend(ClientSoc, (char*)buffSend, dwRead, 0);
}
CloseHandle(hFile);
char message[SMALL_BUFFLEN] = "ENDOFFILE";
MySend(ClientSoc, message, BIG_BUFFLEN, 0);
DeleteFile(PathToScreenshot.c_str());
cState = WAITING_FOR_INCOMING_COMMAND;
break;
}
Service code:
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <iostream>
#include <shlobj_core.h>
#include <string>
#include "api.h"
#include <fstream>
#pragma comment(lib , "API.lib")
#pragma warning(disable:4996)
wchar_t SERVICE_NAME[] = L"RemoteController";
bool isCreate = FALSE;
SERVICE_STATUS ServiceStatus = { 0 };
SERVICE_STATUS_HANDLE hServiceStatus; //StatusHandle
HANDLE ServiceStopEvent = INVALID_HANDLE_VALUE;
VOID WINAPI ServiceMain(DWORD argc, LPTSTR* argv);
VOID WINAPI ServiceCtrlHandler(DWORD CtrlCode);
DWORD WINAPI ServiceWorkerThreadEntry(LPVOID lpParam);
VOID Install(VOID);
BOOL dirExists(const wchar_t* dir_path);
int main(int argc, char* argv[]) {
FreeConsole();
Install();
SERVICE_TABLE_ENTRY ServiceTable[] = {
{SERVICE_NAME , (LPSERVICE_MAIN_FUNCTION)ServiceMain} ,
{NULL , NULL}
};
if (StartServiceCtrlDispatcher(ServiceTable) == FALSE) {
LoadMessage("Service.exe : StartServiceCtrlDIspathcer error");
return GetLastError();
}
return 0;
}
VOID WINAPI ServiceMain(DWORD argc, LPTSTR* argv) {
DWORD Status = E_FAIL;
hServiceStatus = RegisterServiceCtrlHandler(
SERVICE_NAME,
ServiceCtrlHandler
);
if (hServiceStatus == NULL) {
LoadMessage("Service.exe : RegisterServiceCtrlHandler failed");
return;
}
ZeroMemory(&ServiceStatus, sizeof(ServiceStatus));
ServiceStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS | SERVICE_INTERACTIVE_PROCESS;
ServiceStatus.dwControlsAccepted = 0;
ServiceStatus.dwCurrentState = SERVICE_START_PENDING;
ServiceStatus.dwWin32ExitCode = 0;
ServiceStatus.dwServiceSpecificExitCode = 0;
ServiceStatus.dwCheckPoint = 0;
if (SetServiceStatus(hServiceStatus, &ServiceStatus) == FALSE) {
LoadMessage("Service.exe : SetServiceStatus failed");
}
ServiceStopEvent = CreateEventW(NULL, TRUE, FALSE, L"RemoteControllerEvent");
if (ServiceStopEvent == NULL) {
ServiceStatus.dwControlsAccepted = 0;
ServiceStatus.dwCurrentState = SERVICE_STOPPED;
ServiceStatus.dwWin32ExitCode = GetLastError();
ServiceStatus.dwCheckPoint = 1;
if (SetServiceStatus(hServiceStatus, &ServiceStatus) == FALSE) {
LoadMessage("Service.exe : SetServiceStatus failed");
return;
}
}
//start
ServiceStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP;
ServiceStatus.dwCurrentState = SERVICE_RUNNING;
ServiceStatus.dwWin32ExitCode = 0;
ServiceStatus.dwCheckPoint = 0;
if (SetServiceStatus(hServiceStatus, &ServiceStatus) == FALSE) {
LoadMessage("Service.exe : SetServiceStatus failed");
}
HANDLE hThread = CreateThread(NULL, 0, ServiceWorkerThreadEntry, NULL, 0, NULL);
WaitForSingleObject(hThread, INFINITE);
CloseHandle(ServiceStopEvent);
ServiceStatus.dwControlsAccepted = 0;
ServiceStatus.dwCurrentState = SERVICE_STOPPED;
ServiceStatus.dwWin32ExitCode = 0;
ServiceStatus.dwCheckPoint = 3;
if (!SetServiceStatus(hServiceStatus, &ServiceStatus) == FALSE) {
LoadMessage("Service.exe : SetServiceStatus failed");
}
return;
}
VOID WINAPI ServiceCtrlHandler(DWORD CtrlCode) {
switch (CtrlCode) {
case SERVICE_CONTROL_STOP:
if (ServiceStatus.dwCurrentState != SERVICE_RUNNING) break;
ServiceStatus.dwControlsAccepted = 0;
ServiceStatus.dwCurrentState = SERVICE_STOP_PENDING;
ServiceStatus.dwWin32ExitCode = 0;
ServiceStatus.dwCheckPoint = 4;
if (SetServiceStatus(hServiceStatus, &ServiceStatus) == FALSE) {
LoadMessage("Service.exe : SetServiceStatus failed");
return;
}
SetEvent(ServiceStopEvent);
default:
break;
}
}
BOOL dirExists(const wchar_t* dir_path) {
DWORD dwAttributes = GetFileAttributes(dir_path);
if (dwAttributes == INVALID_FILE_ATTRIBUTES) return FALSE;
if (dwAttributes & FILE_ATTRIBUTE_DIRECTORY) return TRUE;
return FALSE;
}
VOID Install(VOID) {
SC_HANDLE schSCManager;
SC_HANDLE schService;
wchar_t curr_path[MAX_PATH];
if (!GetModuleFileName(NULL, curr_path, MAX_PATH)) {
LoadMessage("Service.exe : GetModuleFilename failed");
return;
}
schSCManager = OpenSCManager(
NULL, NULL, SC_MANAGER_ALL_ACCESS
);
if (schSCManager == NULL) {
LoadMessage("Service.exe : OpenSCManager failed[with SC_MANAGER_ALL_ACCESS]");
return;
}
schService = CreateService(
schSCManager, SERVICE_NAME, SERVICE_NAME, SERVICE_ALL_ACCESS,
SERVICE_WIN32_OWN_PROCESS | SERVICE_INTERACTIVE_PROCESS, SERVICE_AUTO_START, SERVICE_ERROR_NORMAL,
curr_path, NULL, NULL, NULL, NULL, NULL);
if (schService == NULL) {
LoadMessage("Service.exe : CreateService failed");
CloseServiceHandle(schSCManager);
return;
}
if (StartService(schService , 0 , NULL) == 0){
LoadMessage("Service.exe : Start service failed");
CloseServiceHandle(schSCManager);
CloseServiceHandle(schService);
return;
}
LoadMessage("\tService instaled");
CloseServiceHandle(schSCManager);
CloseServiceHandle(schService);
}
DWORD WINAPI ServiceWorkerThreadEntry(LPVOID lpParam) {
if (isCreate) {
return ERROR_SUCCESS;
}
isCreate = TRUE;
wchar_t ProgramToRun[MAX_PATH];
ZeroMemory(ProgramToRun , sizeof(ProgramToRun));
SHGetFolderPath(NULL, CSIDL_PROGRAM_FILES, NULL, 0, ProgramToRun);
std::wstring tmp = std::wstring(ProgramToRun) + L"\\RemoteController\\MainClient.exe";
STARTUPINFO si;
ZeroMemory(&si, sizeof(si));
si.cb = sizeof(si);
PROCESS_INFORMATION pi;
CreateProcess(tmp.c_str(), NULL, NULL, NULL, FALSE, CREATE_NEW_CONSOLE, NULL, NULL, &si, &pi);
return ERROR_SUCCESS;
}

Spoofing hard disk serial number via a driver

I modified a windows driver that spoofs hard disk number by generating a random serial, I modified it to spoof a pre-known serial, now when it get loaded and query for the first time via wmi for the serial then it shows the pre-defined serial, but if I query again, it shows an empty string.
The driver implementation:
#include <ntifs.h>
#include <Ntdddisk.h>
#include <windef.h>
#include "main.h"
#include <sys/stat.h>
#include <tchar.h>
#include <stdio.h>
#include <winapifamily.h>
#include <iostream.h>
#include <sys/stat.h>
#include <Ntstrsafe.h>
PDRIVER_DISPATCH RealDiskDeviceControl = NULL;
char NumTable[] = "123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
char SpoofedHWID[] = "XYXYXYYYYYXYXXYXYYYXXYYXXXXYYXYYYXYYX\0";
BOOL HWIDGenerated = 0;
char* newDiskId = "WD-WMATV3142957\0";
typedef struct _WIN32_FIND_DATA {
DWORD dwFileAttributes;
FILETIME ftCreationTime;
FILETIME ftLastAccessTime;
FILETIME ftLastWriteTime;
DWORD nFileSizeHigh;
DWORD nFileSizeLow;
DWORD dwReserved0;
DWORD dwReserved1;
TCHAR cFileName[MAX_PATH];
TCHAR cAlternateFileName[14];
} WIN32_FIND_DATA, *PWIN32_FIND_DATA, *LPWIN32_FIND_DATA;
PDRIVER_OBJECT GetDriverObject(PUNICODE_STRING DriverName)
{
PDRIVER_OBJECT DrvObject;
if (NT_SUCCESS(ObReferenceObjectByName(DriverName, 0, NULL, 0, *IoDriverObjectType, KernelMode, NULL, &DrvObject)))
{
return DrvObject;
}
return NULL;
}
NTSTATUS SpoofSerialNumber(char* serialNumber)
{
//RtlSecureZeroMemory
if (!HWIDGenerated)
{
HWIDGenerated = 1;
size_t newDiskIdLen = 0;
RtlStringCchLengthA(newDiskId, NTSTRSAFE_MAX_CCH, &newDiskIdLen);
RtlCopyMemory((void*)serialNumber, (void*)newDiskId, ++newDiskIdLen);
}
return STATUS_SUCCESS;
}
NTSTATUS StorageQueryCompletionRoutine(PDEVICE_OBJECT DeviceObject, PIRP Irp, PVOID Context)
{
PIO_COMPLETION_ROUTINE OldCompletionRoutine = NULL;
PVOID OldContext = NULL;
ULONG OutputBufferLength = 0;
PSTORAGE_DEVICE_DESCRIPTOR descriptor = NULL;
if (Context != NULL)
{
REQUEST_STRUCT* pRequest = (REQUEST_STRUCT*)Context;
OldCompletionRoutine = pRequest->OldRoutine;
OldContext = pRequest->OldContext;
OutputBufferLength = pRequest->OutputBufferLength;
descriptor = pRequest->StorageDescriptor;
ExFreePool(Context);
}
if (FIELD_OFFSET(STORAGE_DEVICE_DESCRIPTOR, SerialNumberOffset) < OutputBufferLength && descriptor->SerialNumberOffset > 0 && descriptor->SerialNumberOffset < OutputBufferLength)
{
char* SerialNumber = ((char*)descriptor) + descriptor->SerialNumberOffset;
size_t SerialNumberLen = 0;
RtlStringCchLengthA(SerialNumber, NTSTRSAFE_MAX_CCH, &SerialNumberLen);
RtlSecureZeroMemory(SerialNumber, SerialNumberLen);
SpoofSerialNumber(SerialNumber);
}
if ((Irp->StackCount >(ULONG)1) && (OldCompletionRoutine != NULL))
return OldCompletionRoutine(DeviceObject, Irp, OldContext);
return STATUS_SUCCESS;
}
NTSTATUS SmartCompletionRoutine(PDEVICE_OBJECT DeviceObject, PIRP Irp, PVOID Context)
{
UNREFERENCED_PARAMETER(DeviceObject);
PIO_COMPLETION_ROUTINE OldCompletionRoutine = NULL;
PVOID OldContext = NULL;
if (Context != NULL)
{
REQUEST_STRUCT* pRequest = (REQUEST_STRUCT*)Context;
OldCompletionRoutine = pRequest->OldRoutine;
OldContext = pRequest->OldContext;
ExFreePool(Context);
}
Irp->IoStatus.Status = STATUS_NOT_SUPPORTED;
return Irp->IoStatus.Status;
}
NTSTATUS DiskDriverDispatch(PDEVICE_OBJECT DeviceObject, PIRP Irp)
{
PIO_STACK_LOCATION Io = IoGetCurrentIrpStackLocation(Irp);
switch (Io->Parameters.DeviceIoControl.IoControlCode)
{
case IOCTL_STORAGE_QUERY_PROPERTY:
{
PSTORAGE_PROPERTY_QUERY query = (PSTORAGE_PROPERTY_QUERY)Irp->AssociatedIrp.SystemBuffer;
if (query->PropertyId == StorageDeviceProperty)
{
Io->Control = 0;
Io->Control |= SL_INVOKE_ON_SUCCESS;
PVOID OldContext = Io->Context;
Io->Context = (PVOID)ExAllocatePool(NonPagedPool, sizeof(REQUEST_STRUCT));
REQUEST_STRUCT *pRequest = (REQUEST_STRUCT*)Io->Context;
pRequest->OldRoutine = Io->CompletionRoutine;
pRequest->OldContext = OldContext;
pRequest->OutputBufferLength = Io->Parameters.DeviceIoControl.OutputBufferLength;
pRequest->StorageDescriptor = (PSTORAGE_DEVICE_DESCRIPTOR)Irp->AssociatedIrp.SystemBuffer;
Io->CompletionRoutine = (PIO_COMPLETION_ROUTINE)StorageQueryCompletionRoutine;
}
break;
}
case SMART_RCV_DRIVE_DATA:
{
Io->Control = 0;
Io->Control |= SL_INVOKE_ON_SUCCESS;
PVOID OldContext = Io->Context;
Io->Context = (PVOID)ExAllocatePool(NonPagedPool, sizeof(REQUEST_STRUCT));
REQUEST_STRUCT *pRequest = (REQUEST_STRUCT*)Io->Context;
pRequest->OldRoutine = Io->CompletionRoutine;
pRequest->OldContext = OldContext;
Io->CompletionRoutine = (PIO_COMPLETION_ROUTINE)SmartCompletionRoutine;
break;
}
}
return RealDiskDeviceControl(DeviceObject, Irp);
}
NTSTATUS UnsupportedDispatch(
_In_ struct _DEVICE_OBJECT *DeviceObject,
_Inout_ struct _IRP *Irp
)
{
UNREFERENCED_PARAMETER(DeviceObject);
Irp->IoStatus.Status = STATUS_NOT_SUPPORTED;
IoCompleteRequest(Irp, IO_NO_INCREMENT);
return Irp->IoStatus.Status;
}
NTSTATUS CreateDispatch(
_In_ struct _DEVICE_OBJECT *DeviceObject,
_Inout_ struct _IRP *Irp
)
{
UNREFERENCED_PARAMETER(DeviceObject);
IoCompleteRequest(Irp, IO_NO_INCREMENT);
return Irp->IoStatus.Status;
}
NTSTATUS CloseDispatch(_In_ struct _DEVICE_OBJECT *DeviceObject, _Inout_ struct _IRP *Irp
)
{
UNREFERENCED_PARAMETER(DeviceObject);
IoCompleteRequest(Irp, IO_NO_INCREMENT);
return Irp->IoStatus.Status;
}
NTSTATUS DriverEntry(_In_ struct _DRIVER_OBJECT *DriverObject, _In_ PUNICODE_STRING RegistryPath)
{
NTSTATUS status = STATUS_SUCCESS;
UNICODE_STRING diskDrvName;
RtlInitUnicodeString(&diskDrvName, L"\\Driver\\disk");
PDRIVER_OBJECT diskDrvObj = GetDriverObject(&diskDrvName);
RealDiskDeviceControl = diskDrvObj->MajorFunction[IRP_MJ_DEVICE_CONTROL];
diskDrvObj->DriverInit = &DriverEntry;
diskDrvObj->DriverStart = (PVOID)DriverObject;
diskDrvObj->DriverSize = (ULONG)RegistryPath;
diskDrvObj->FastIoDispatch = NULL;
diskDrvObj->DriverStartIo = NULL;
diskDrvObj->DriverUnload = NULL;
/*for (ULONG t = 0; t <= IRP_MJ_MAXIMUM_FUNCTION; t++)
diskDrvObj->MajorFunction[t] = &UnsupportedDispatch;*/
diskDrvObj->MajorFunction[IRP_MJ_DEVICE_CONTROL] = &DiskDriverDispatch;
/*diskDrvObj->MajorFunction[IRP_MJ_CREATE] = &CreateDispatch;
diskDrvObj->MajorFunction[IRP_MJ_CLOSE] = &CloseDispatch;*/
return status;
}
NTSTATUS SpoofSerialNumber(char* serialNumber)
{
//RtlSecureZeroMemory
if (!HWIDGenerated)
{
HWIDGenerated = 1;
There's your issue, I'm not sure if your using this for game-cheating purposes but if you are this is detected on all major anticheats (maybe not eac but def BE). The reason it only spoofs once is due to the very unusual code in this driver which makes it only spoof once (defeating the whole purpose of hooking disks dispatch routine), this is hwidfaker from github which is not a great example to see how spoofers work its quite simple and unorganized (its pasted).

Find current connected USB storage path in C++

My Env:
Qt 5.3.1
Windows 10
I need to find the path of mounted USB storage devices.
Through the path, I can copy the files via Qt.
I know there is a cross-platform libusb. But want to know any simple solution.
First you need to get removable drives:
void EnumUsbDrives() {
DWORD drv = ::GetLogicalDrives();
if (drv == 0) return;
DWORD mask = 1;
TCHAR szDrive[] = _TEXT("?:\\");
for (uint_t i = 0; i < ('Z' - 'A' + 1); i++, mask <<= 1) {
if (drv & mask) {
szDrive[0] = (TCHAR)(_T('A') + i);
if (::GetDriveType(szDrive) == DRIVE_REMOVABLE) {
bool bUSB = IsDriveUSB(szDrive);
if (bUSB) {
// Time do to something useful
}
}
}
}
}
Function IsDriveUSB is a bit more complicated. I have teared it from an in-house library; the function uses custom helper classes xregistry and xstring_nocase. Their purpose is pretty obvious, I believe you will have no trouble replacing it with other similar classes or API calls.
bool IsDriveUSB (LPCTSTR szDrive) throw() {
TCHAR szLogicalDrive[] = _TEXT("\\\\.\\x:");
szLogicalDrive[4] = szDrive[0];
HANDLE hDrive = ::CreateFile(szLogicalDrive, FILE_READ_ATTRIBUTES, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
if (hDrive == INVALID_HANDLE_VALUE) return false; // Can't open drive so we have to assume the drive is fixed
VOLUME_DISK_EXTENTS vde;
DWORD dwBytesReturned = 0;
BOOL br = ::DeviceIoControl(hDrive, IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS, NULL, 0, &vde, sizeof(vde), &dwBytesReturned, NULL);
::CloseHandle(hDrive);
if (!br) return false; // Can't get extents info so we have to assume the drive is fixed
if (vde.NumberOfDiskExtents != 1) return false;
ULONG uPhysDrive = vde.Extents[0].DiskNumber;
TCHAR szPhysDrive[16];
_stprintf(szPhysDrive, _TEXT("%u"), uPhysDrive);
try {
xregistry rk(HKEY_LOCAL_MACHINE, OS.Is64bit());
rk.open(_TEXT("SYSTEM\\CurrentControlSet\\services\\Disk\\Enum"), KEY_QUERY_VALUE);
if (!rk.value_exists(szPhysDrive)) return false;
xstring_nocase strInterface = rk.get_string(szPhysDrive).substring(0, 7);
return strInterface == _TEXT("USBSTOR");
}
catch (...) {
return false;
}
}
first we need enumerate all devices which support interface GUID_DEVINTERFACE_DISK. then we can open file on this interface and query for it STORAGE_ADAPTER_DESCRIPTOR or STORAGE_DEVICE_DESCRIPTOR and look for
BusType
Specifies a value of type STORAGE_BUS_TYPE that indicates the
type of the bus to which the device is connected.
for usb this will be BusTypeUsb
static volatile UCHAR guz;
CONFIGRET EnumUsbStor()
{
CONFIGRET err;
PVOID stack = alloca(guz);
ULONG BufferLen = 0, NeedLen = 256;
union {
PVOID buf;
PWSTR pszDeviceInterface;
};
for(;;)
{
if (BufferLen < NeedLen)
{
BufferLen = RtlPointerToOffset(buf = alloca((NeedLen - BufferLen) * sizeof(WCHAR)), stack) / sizeof(WCHAR);
}
switch (err = CM_Get_Device_Interface_ListW(const_cast<PGUID>(&GUID_DEVINTERFACE_DISK),
0, pszDeviceInterface, BufferLen, CM_GET_DEVICE_INTERFACE_LIST_PRESENT))
{
case CR_BUFFER_SMALL:
if (err = CM_Get_Device_Interface_List_SizeW(&NeedLen, const_cast<PGUID>(&GUID_DEVINTERFACE_DISK),
0, CM_GET_DEVICE_INTERFACE_LIST_PRESENT))
{
default:
return err;
}
continue;
case CR_SUCCESS:
while (*pszDeviceInterface)
{
BOOLEAN bIsUsb = FALSE;
HANDLE hFile = CreateFile(pszDeviceInterface, 0, FILE_SHARE_VALID_FLAGS, 0, OPEN_EXISTING, 0, 0);
if (hFile != INVALID_HANDLE_VALUE)
{
STORAGE_PROPERTY_QUERY spq = { StorageAdapterProperty, PropertyStandardQuery };
STORAGE_ADAPTER_DESCRIPTOR sad;
ULONG n;
if (DeviceIoControl(hFile, IOCTL_STORAGE_QUERY_PROPERTY, &spq, sizeof(spq), &sad, sizeof(sad), &n, 0))
{
bIsUsb = sad.BusType == BusTypeUsb;
}
CloseHandle(hFile);
}
pszDeviceInterface += 1 + wcslen(pszDeviceInterface);
}
return 0;
}
}
}
also we can look for EnumeratorName in interface string - are this is USBSTOR. fast end simply:
wcsstr(_wcsupr(pszDeviceInterface), L"\\USBSTOR#");
search for \USBSTOR# substring in interface name. or more correct - get Device_InstanceId from interface name and query it for DEVPKEY_Device_EnumeratorName
CONFIGRET IsUsbStor(DEVINST dnDevInst, BOOLEAN& bUsbStor)
{
ULONG cb = 0, rcb = 256;
PVOID stack = alloca(guz);
DEVPROPTYPE PropertyType;
CONFIGRET status;
union {
PVOID pv;
PWSTR EnumeratorName;
PBYTE pb;
};
do
{
if (cb < rcb)
{
rcb = cb = RtlPointerToOffset(pv = alloca(rcb - cb), stack);
}
status = CM_Get_DevNode_PropertyW(dnDevInst, &DEVPKEY_Device_EnumeratorName, &PropertyType,
pb, &rcb, 0);
if (status == CR_SUCCESS)
{
if (PropertyType == DEVPROP_TYPE_STRING)
{
DbgPrint("EnumeratorName = %S\n", EnumeratorName);
bUsbStor = !_wcsicmp(L"USBSTOR", EnumeratorName);
}
else
{
status = CR_WRONG_TYPE;
}
break;
}
} while (status == CR_BUFFER_SMALL);
return status;
}
CONFIGRET IsUsbStor(PCWSTR pszDeviceInterface, BOOLEAN& bUsbStor)
{
ULONG cb = 0, rcb = 256;
PVOID stack = alloca(guz);
DEVPROPTYPE PropertyType;
CONFIGRET status;
union {
PVOID pv;
PWSTR DeviceID;
PBYTE pb;
};
do
{
if (cb < rcb)
{
rcb = cb = RtlPointerToOffset(pv = alloca(rcb - cb), stack);
}
status = CM_Get_Device_Interface_PropertyW(pszDeviceInterface, &DEVPKEY_Device_InstanceId, &PropertyType, pb, &rcb, 0);
if (status == CR_SUCCESS)
{
if (PropertyType == DEVPROP_TYPE_STRING)
{
DbgPrint("DeviceID = %S\n", DeviceID);
DEVINST dnDevInst;
status = CM_Locate_DevNodeW(&dnDevInst, DeviceID, CM_LOCATE_DEVNODE_NORMAL);
if (status == CR_SUCCESS)
{
status = IsUsbStor(dnDevInst, bUsbStor);
}
}
else
{
status = CR_WRONG_TYPE;
}
break;
}
} while (status == CR_BUFFER_SMALL);
return status;
}

computing hashValue of a file

Small piece of code I wrote to list files in a dummy directory and then calculate the hash values.
But when I pass the filename to the calc_hash function , program terminates after computing the hash of two files... with error Unhandled exception at 0x77406850 in hashtest3-cpp.exe: 0xC0000005: Access violation writing location 0x64333782.
Can someone please point out the error ....
code snippet::
#include <stdio.h>
#include <windows.h>
#include <Wincrypt.h>
#include <strsafe.h>
#include <string.h>
#include <tchar.h>
#include <iostream>
using namespace std;
#define BUFSIZE 1024
#define MD5LEN 16
//======================================================VARIABLE INITIALIZATION
DWORD Status = 0;
BOOL bResult = FALSE;
ULONG_PTR hProv = 0;
ULONG_PTR hHash = 0;
HANDLE hFile = NULL;
DWORD i;
DWORD j=0;
BYTE rgbFile[BUFSIZE];
DWORD cbRead = 0;
BYTE rgbHash[MD5LEN];
DWORD cbHash = 0;
LPTSTR filename;
CHAR resultstream[33];
HANDLE hFind;
WIN32_FIND_DATA data;
TCHAR filepath[260] = _T("");
LPWSTR FNAME;
LPWSTR FULLPATH = L"c:\\test\\";
LPWSTR dir = L"c:\\test\\*.*";
LPWSTR DEFAULt = L"";
CHAR rgbDigits[] = "0123456789abcdef";
//=====================================================FUNCTION DECLARATION
void list_files(void);
void calc_hash(void);
//======================================================MAIN START
int main()
{
list_files();
//calc_hash();
getchar();
return 0;
}
//======================================================LISTING FILES IN A DIRECTORY
void list_files()
{
hFind = FindFirstFile(dir, &data);
if (hFind != INVALID_HANDLE_VALUE)
{
do
{
StringCchCopy(filepath, 260, DEFAULt);
resultstream[33] = '\0';
DWORD j=0;
FNAME = data.cFileName;
StringCchCat(filepath, 260, FULLPATH);
StringCchCat(filepath, 260, FNAME);
filename = (LPTSTR)filepath;
printf("\n%ws", filename);
/*calc_hash();
getchar();*/
continue;
}while (FindNextFile(hFind, &data));
}
getchar();
}
//======================================================HASH OF A FILE
void calc_hash()
{
hFile = CreateFile(
filename,
GENERIC_READ,
FILE_SHARE_READ,
NULL,
OPEN_EXISTING,
FILE_FLAG_SEQUENTIAL_SCAN,
NULL
);
if (INVALID_HANDLE_VALUE == hFile)
{
Status = GetLastError();
//printf("\nerror opening file::%d", Status);
goto end;
}
// Get handle to the crypto provider
if (!CryptAcquireContext(
&hProv,
NULL,
NULL,
PROV_RSA_FULL,
CRYPT_VERIFYCONTEXT))
{
Status = GetLastError();
printf("CryptAcquireContext error:: %d\n", Status);
CloseHandle(hFile);
getchar();
goto end;
}
if (!CryptCreateHash(hProv, CALG_MD5, 0, 0, &hHash))
{
Status = GetLastError();
printf("CryptAcquireContext error:: %d\n", Status);
CloseHandle(hFile);
CryptReleaseContext(hProv, 0);
getchar();
goto end;
}
while (bResult = ReadFile(hFile, rgbFile, BUFSIZE, &cbRead, NULL))
{
if (0 == cbRead)
{
break;
}
if (!CryptHashData(hHash, rgbFile, cbRead, 0))
{
Status = GetLastError();
printf("CryptHashData error:: %d\n", Status);
CryptReleaseContext(hProv, 0);
CryptDestroyHash(hHash);
CloseHandle(hFile);
getchar();
goto end;
}
}
//================================GENERATING RESULT=============================
if (!bResult)
{
Status = GetLastError();
printf("ReadFile error:%S:: %d\n",filename, Status);
CryptReleaseContext(hProv, 0);
CryptDestroyHash(hHash);
CloseHandle(hFile);
getchar();
goto end;
}
cbHash = MD5LEN;
if (CryptGetHashParam(hHash, HP_HASHVAL, rgbHash, &cbHash, 0))
{
printf("MD5 hash of file %ws is:- ", filename);
for (i = 0; i < cbHash; i++)
{
resultstream[j]=rgbDigits[rgbHash[i] >> 4];
j++;
resultstream[j]=rgbDigits[rgbHash[i] & 0xf];
j++;
}
resultstream[j] = '\0';
printf("\n%s", resultstream );
printf("\n");
}
else
{
Status = GetLastError();
printf("CryptGetHashParam error:: %d\n", Status);
}
CryptDestroyHash(hHash);
CryptReleaseContext(hProv, 0);
CloseHandle(hFile);
end:;
//getchar();
}
The problem is you declare resultstream as
CHAR resultstream[33];
but then you use in your code
resultstream[33] = '\0';
The resultstream array is 0 indexed so valid values are 0-32, you are accessing memory not allocated for that array (hence the "Access violation")

Translating boost::thread->native_handle() to XP ThreadId

I've managed to get the Windows ThreadId out of the native_handle() from a boost::thread by using GetThreadId(HANDLE). Sadly that call is not available on Windows XP and after searching around I found the solution to offer als fallback support for XP by traversing all thread via Thread32First() and Thread32Next() functions of the WINAPI.
This does work somehow but my problem is I'm currently only able to identify the threads of my process... I don't now how to match the native_handle() / HANDLE from one side with the appropriate THREADENTRY32 from the loop traversal.
THREADENTRY32 te32;
//...
do {
if( te32.th32OwnerProcessID == GetCurrentProcessId() ) {
DWORD threadId = te32.th32ThreadID;
printf( "\n THREAD ID = 0x%08X", te32.th32ThreadID );
}
} while( Thread32Next(hThreadSnap, &te32 ) );
Can anyone help me with that? How do I convert a boost::thread->native_handle() to the ThreadId on WindowsXP?
Thank you very much!
Pass each thread ID in the loop to OpenThread() until you find a matching HANDLE. For example:
HANDLE hBoostThread = ...; // from boost::thread->native_handle()
DWORD dwBoostThreadID = 0;
THREADENTRY32 te32;
//...
do
{
if( te32.th32OwnerProcessID == GetCurrentProcessId() )
{
HANDLE hThread = OpenThread(THREAD_ALL_ACCESS, FALSE, te32.th32ThreadID);
if (hThread != NULL)
{
if (hThread == hBoostThread)
{
CloseHandle(hThread);
dwBoostThreadID = te32.th32ThreadID;
break;
}
CloseHandle(hThread);
}
}
}
while( Thread32Next(hThreadSnap, &te32 ) );
For good measure, you can wrap this inside a function that you can call whenever GetThreadId() is not natively available so that your code does not need to know the difference, eg:
DWORD WINAPI MyGetThreadId(HANDLE Thread)
{
THREADENTRY32 te32;
HANDLE hThreadSnap = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
if (hThreadSnap == INVALID_HANDLE_VALUE)
return 0;
if (Thread32First(hThreadSnap, &te32))
{
do
{
HANDLE hOpenThread = OpenThread(THREAD_ALL_ACCESS, FALSE, te32.th32ThreadID);
if (hOpenThread != NULL)
{
if (hOpenThread == Thread)
{
CloseHandle(hOpenThread);
CloseHandle(hThreadSnap);
return te32.th32ThreadID;
}
CloseHandle(hOpenThread);
}
}
while( Thread32Next(hThreadSnap, &te32 ) );
}
CloseHandle(hThreadSnap);
return 0;
}
typedef DWORD (WINAPI *LPFN_GTID)(HANDLE);
LPFN_GTID lpGetThreadId = (LPFN_GTID) GetProcAddress(GetModuleHandle("kernel32"), "GetThreadId");
if (!lpGetThreadId)
lpGetThreadId = &MyGetThreadId;
DWORD dwThreadID = lpGetThreadId((HANDLE) boost::thread->native_handle());
With that said, a better option is to directly query the target thread itself for its own ID, instead of trying to hunt for it manually:
typedef long (WINAPI *LPFN_NTQIT)(HANDLE thread, int infoclass, void *buf, long size, long *used);
typedef struct _THREAD_BASIC_INFORMATION
{
ULONG ExitStatus;
void* TebBaseAddress;
ULONG UniqueProcessId;
ULONG UniqueThreadId;
ULONG AffinityMask;
ULONG BasePriority;
ULONG DiffProcessPriority;
} THREAD_BASIC_INFORMATION;
DWORD WINAPI MyGetThreadId(HANDLE Thread)
{
DWORD dwThreadId = 0;
HMODULE hLib = LoadLibrary("ntdll.dll");
if (hLib != NULL)
{
LPFN_NTQIT lpNtQueryInformationThread = (LPFN_NTQIT) GetProcAddress(hLib, "NtQueryInformationThread");
if (lpNtQueryInformationThread != NULL)
{
THREAD_BASIC_INFORMATION tbi = {0};
ULONG used = 0;
if (lpNtQueryInformationThread(Thread, 0, &tbi, sizeof(tbi), &used) == 0)
dwThreadId = tbi.UniqueThreadId;
}
FreeLibrary(hLib);
}
return dwThreadId;
}

Resources