Skip to content

Commit

Permalink
api: don't auto-elevate
Browse files Browse the repository at this point in the history
There's no longer a need to do this for every API call. This only exists
now for the pnp guid reuse workaround hack.

Signed-off-by: Jason A. Donenfeld <[email protected]>
  • Loading branch information
zx2c4 committed Jun 24, 2021
1 parent 6ce07c7 commit b157989
Show file tree
Hide file tree
Showing 8 changed files with 69 additions and 161 deletions.
57 changes: 13 additions & 44 deletions api/adapter.c
Original file line number Diff line number Diff line change
Expand Up @@ -668,18 +668,13 @@ WintunFreeAdapter(_In_ WINTUN_ADAPTER *Adapter)
_Return_type_success_(return != NULL) WINTUN_ADAPTER *WINAPI
WintunOpenAdapter(_In_z_ const WCHAR *Pool, _In_z_ const WCHAR *Name)
{
if (!ElevateToSystem())
{
LOG(WINTUN_LOG_ERR, L"Failed to impersonate SYSTEM user");
return NULL;
}
DWORD LastError;
WINTUN_ADAPTER *Adapter = NULL;
HANDLE Mutex = NamespaceTakePoolMutex(Pool);
if (!Mutex)
{
LastError = LOG(WINTUN_LOG_ERR, L"Failed to take %s pool mutex", Pool);
goto cleanupToken;
goto cleanup;
}

HDEVINFO DevInfo = SetupDiGetClassDevsExW(&GUID_DEVCLASS_NET, NULL, NULL, DIGCF_PRESENT, NULL, NULL, NULL);
Expand Down Expand Up @@ -759,8 +754,7 @@ _Return_type_success_(return != NULL) WINTUN_ADAPTER *WINAPI
SetupDiDestroyDeviceInfoList(DevInfo);
cleanupMutex:
NamespaceReleaseMutex(Mutex);
cleanupToken:
RevertToSelf();
cleanup:
SetLastError(LastError);
return Adapter;
}
Expand Down Expand Up @@ -1840,11 +1834,6 @@ _Return_type_success_(return != NULL) WINTUN_ADAPTER *WINAPI WintunCreateAdapter
_In_opt_ const GUID *RequestedGUID,
_Out_opt_ BOOL *RebootRequired)
{
if (!ElevateToSystem())
{
LOG(WINTUN_LOG_ERR, L"Failed to impersonate SYSTEM user");
return NULL;
}
BOOL DummyRebootRequired;
if (!RebootRequired)
RebootRequired = &DummyRebootRequired;
Expand All @@ -1855,12 +1844,11 @@ _Return_type_success_(return != NULL) WINTUN_ADAPTER *WINAPI WintunCreateAdapter
{
Adapter = CreateAdapterViaRundll32(Pool, Name, RequestedGUID, RebootRequired);
LastError = Adapter ? ERROR_SUCCESS : GetLastError();
goto cleanupToken;
goto cleanup;
}
Adapter = CreateAdapter(Pool, Name, RequestedGUID, RebootRequired);
LastError = Adapter ? ERROR_SUCCESS : GetLastError();
cleanupToken:
RevertToSelf();
cleanup:
return RET_ERROR(Adapter, LastError);
}

Expand All @@ -1869,11 +1857,6 @@ _Return_type_success_(return != FALSE) BOOL WINAPI WintunDeleteAdapter(
_In_ BOOL ForceCloseSessions,
_Out_opt_ BOOL *RebootRequired)
{
if (!ElevateToSystem())
{
LOG(WINTUN_LOG_ERR, L"Failed to impersonate SYSTEM user");
return FALSE;
}
BOOL DummyRebootRequired;
if (!RebootRequired)
RebootRequired = &DummyRebootRequired;
Expand All @@ -1883,14 +1866,14 @@ _Return_type_success_(return != FALSE) BOOL WINAPI WintunDeleteAdapter(
{
LastError =
DeleteAdapterViaRundll32(Adapter, ForceCloseSessions, RebootRequired) ? ERROR_SUCCESS : GetLastError();
goto cleanupToken;
goto cleanup;
}

HANDLE Mutex = NamespaceTakePoolMutex(Adapter->Pool);
if (!Mutex)
{
LastError = LOG(WINTUN_LOG_ERR, L"Failed to take %s pool mutex", Adapter->Pool);
goto cleanupToken;
goto cleanup;
}

HDEVINFO DevInfo;
Expand Down Expand Up @@ -1930,8 +1913,7 @@ _Return_type_success_(return != FALSE) BOOL WINAPI WintunDeleteAdapter(
SetupDiDestroyDeviceInfoList(DevInfo);
cleanupMutex:
NamespaceReleaseMutex(Mutex);
cleanupToken:
RevertToSelf();
cleanup:
return RET_ERROR(TRUE, LastError);
}

Expand Down Expand Up @@ -1990,12 +1972,6 @@ static _Return_type_success_(return != FALSE) BOOL
_Return_type_success_(return != FALSE) BOOL WINAPI
WintunDeletePoolDriver(_In_z_ const WCHAR *Pool, _Out_opt_ BOOL *RebootRequired)
{
if (!ElevateToSystem())
{
LOG(WINTUN_LOG_ERR, L"Failed to impersonate SYSTEM user");
return FALSE;
}

BOOL DummyRebootRequired;
if (!RebootRequired)
RebootRequired = &DummyRebootRequired;
Expand All @@ -2005,20 +1981,20 @@ _Return_type_success_(return != FALSE) BOOL WINAPI
if (MAYBE_WOW64 && NativeMachine != IMAGE_FILE_PROCESS)
{
LastError = DeletePoolDriverViaRundll32(Pool, RebootRequired) ? ERROR_SUCCESS : GetLastError();
goto cleanupToken;
goto cleanup;
}

if (!DeleteAllOurAdapters(Pool, RebootRequired))
{
LastError = GetLastError();
goto cleanupToken;
goto cleanup;
}

HANDLE DriverInstallationLock = NamespaceTakeDriverInstallationMutex();
if (!DriverInstallationLock)
{
LastError = LOG(WINTUN_LOG_ERR, L"Failed to take driver installation mutex");
goto cleanupToken;
goto cleanup;
}
HDEVINFO DeviceInfoSet = SetupDiGetClassDevsW(&GUID_DEVCLASS_NET, NULL, NULL, 0);
if (!DeviceInfoSet)
Expand Down Expand Up @@ -2060,25 +2036,19 @@ _Return_type_success_(return != FALSE) BOOL WINAPI
SetupDiDestroyDeviceInfoList(DeviceInfoSet);
cleanupDriverInstallationLock:
NamespaceReleaseMutex(DriverInstallationLock);
cleanupToken:
RevertToSelf();
cleanup:
return RET_ERROR(TRUE, LastError);
}

_Return_type_success_(return != FALSE) BOOL WINAPI
WintunEnumAdapters(_In_z_ const WCHAR *Pool, _In_ WINTUN_ENUM_CALLBACK Func, _In_ LPARAM Param)
{
if (!ElevateToSystem())
{
LOG(WINTUN_LOG_ERR, L"Failed to impersonate SYSTEM user");
return FALSE;
}
DWORD LastError = ERROR_SUCCESS;
HANDLE Mutex = NamespaceTakePoolMutex(Pool);
if (!Mutex)
{
LastError = LOG(WINTUN_LOG_ERR, L"Failed to take %s pool mutex", Pool);
goto cleanupToken;
goto cleanup;
}
HDEVINFO DevInfo = SetupDiGetClassDevsExW(&GUID_DEVCLASS_NET, NULL, NULL, DIGCF_PRESENT, NULL, NULL, NULL);
if (DevInfo == INVALID_HANDLE_VALUE)
Expand Down Expand Up @@ -2112,7 +2082,6 @@ _Return_type_success_(return != FALSE) BOOL WINAPI
SetupDiDestroyDeviceInfoList(DevInfo);
cleanupMutex:
NamespaceReleaseMutex(Mutex);
cleanupToken:
RevertToSelf();
cleanup:
return RET_ERROR(TRUE, LastError);
}
95 changes: 7 additions & 88 deletions api/elevate.c
Original file line number Diff line number Diff line change
Expand Up @@ -9,19 +9,19 @@
#include <Windows.h>
#include <TlHelp32.h>

_Return_type_success_(return != FALSE) BOOL ElevateToSystem(void)
static _Return_type_success_(return != FALSE) BOOL ElevateToSystem(void)
{
HANDLE CurrentProcessToken, ThreadToken, ProcessSnapshot, WinlogonProcess, WinlogonToken, DuplicatedToken;
PROCESSENTRY32W ProcessEntry = { .dwSize = sizeof(PROCESSENTRY32W) };
BOOL Ret;
DWORD LastError = ERROR_SUCCESS;
TOKEN_PRIVILEGES Privileges = { .PrivilegeCount = 1, .Privileges = { { .Attributes = SE_PRIVILEGE_ENABLED } } };
CHAR LocalSystemSid[0x400];
CHAR LocalSystemSid[MAX_SID_SIZE];
DWORD RequiredBytes = sizeof(LocalSystemSid);
struct
{
TOKEN_USER MaybeLocalSystem;
CHAR LargeEnoughForLocalSystem[0x400];
CHAR LargeEnoughForLocalSystem[MAX_SID_SIZE];
} TokenUserBuffer;

Ret = CreateWellKnownSid(WinLocalSystemSid, NULL, &LocalSystemSid, &RequiredBytes);
Expand All @@ -46,7 +46,7 @@ _Return_type_success_(return != FALSE) BOOL ElevateToSystem(void)
goto cleanup;
}
if (EqualSid(TokenUserBuffer.MaybeLocalSystem.User.Sid, LocalSystemSid))
return TRUE;
return ImpersonateSelf(SecurityImpersonation);
Ret = LookupPrivilegeValueW(NULL, SE_DEBUG_NAME, &Privileges.Privileges[0].Luid);
if (!Ret)
{
Expand Down Expand Up @@ -122,81 +122,6 @@ _Return_type_success_(return != FALSE) BOOL ElevateToSystem(void)
return FALSE;
}

_Return_type_success_(return != NULL) HANDLE GetPrimarySystemTokenFromThread(void)
{
HANDLE CurrentToken, DuplicatedToken;
BOOL Ret;
DWORD LastError;
TOKEN_PRIVILEGES Privileges = { .PrivilegeCount = 1, .Privileges = { { .Attributes = SE_PRIVILEGE_ENABLED } } };
CHAR LocalSystemSid[0x400];
DWORD RequiredBytes = sizeof(LocalSystemSid);
struct
{
TOKEN_USER MaybeLocalSystem;
CHAR LargeEnoughForLocalSystem[0x400];
} TokenUserBuffer;

Ret = CreateWellKnownSid(WinLocalSystemSid, NULL, &LocalSystemSid, &RequiredBytes);
if (!Ret)
{
LastError = LOG_LAST_ERROR(L"Failed to create SID");
return NULL;
}
Ret = OpenThreadToken(
GetCurrentThread(), TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES | TOKEN_DUPLICATE, FALSE, &CurrentToken);
if (!Ret && GetLastError() == ERROR_NO_TOKEN)
Ret = OpenProcessToken(
GetCurrentProcess(), TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES | TOKEN_DUPLICATE, &CurrentToken);
if (!Ret)
{
LastError = LOG_LAST_ERROR(L"Failed to open token");
return NULL;
}
Ret = GetTokenInformation(CurrentToken, TokenUser, &TokenUserBuffer, sizeof(TokenUserBuffer), &RequiredBytes);
if (!Ret)
{
LastError = LOG_LAST_ERROR(L"Failed to get token information");
goto cleanup;
}
if (!EqualSid(TokenUserBuffer.MaybeLocalSystem.User.Sid, LocalSystemSid))
{
LOG(WINTUN_LOG_ERR, L"Not SYSTEM");
LastError = ERROR_ACCESS_DENIED;
goto cleanup;
}
Ret = LookupPrivilegeValueW(NULL, SE_ASSIGNPRIMARYTOKEN_NAME, &Privileges.Privileges[0].Luid);
if (!Ret)
{
LastError = LOG_LAST_ERROR(L"Failed to lookup privilege value");
goto cleanup;
}
Ret = AdjustTokenPrivileges(CurrentToken, FALSE, &Privileges, 0, NULL, NULL);
if (!Ret)
{
LastError = LOG_LAST_ERROR(L"Failed to adjust token privileges");
goto cleanup;
}
Ret = DuplicateTokenEx(
CurrentToken,
TOKEN_QUERY | TOKEN_DUPLICATE | TOKEN_ASSIGN_PRIMARY,
NULL,
SecurityImpersonation,
TokenPrimary,
&DuplicatedToken);
if (!Ret)
{
LastError = LOG_LAST_ERROR(L"Failed to duplicate token");
goto cleanup;
}
CloseHandle(CurrentToken);
return DuplicatedToken;

cleanup:
CloseHandle(CurrentToken);
SetLastError(LastError);
return NULL;
}

_Return_type_success_(return != FALSE) BOOL ImpersonateService(_In_z_ WCHAR *ServiceName, _In_ HANDLE *OriginalToken)
{
HANDLE ThreadToken, ServiceProcess, ServiceToken, DuplicatedToken;
Expand All @@ -212,20 +137,14 @@ _Return_type_success_(return != FALSE) BOOL ImpersonateService(_In_z_ WCHAR *Ser
GetLastError() != ERROR_NO_TOKEN)
return FALSE;

if (!ElevateToSystem())
goto cleanup;

if (!LookupPrivilegeValueW(NULL, SE_DEBUG_NAME, &Privileges.Privileges[0].Luid))
{
LastError = LOG_LAST_ERROR(L"Failed to lookup privilege value");
goto cleanup;
}
if (!*OriginalToken)
{
RevertToSelf();
if (!ImpersonateSelf(SecurityImpersonation))
{
LastError = LOG_LAST_ERROR(L"Failed to impersonate self");
goto cleanup;
}
}
if (!OpenThreadToken(GetCurrentThread(), TOKEN_ADJUST_PRIVILEGES, FALSE, &ThreadToken))
{
LastError = LOG_LAST_ERROR(L"Failed to open thread token");
Expand Down
4 changes: 0 additions & 4 deletions api/elevate.h
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,6 @@

#include <Windows.h>

_Return_type_success_(return != FALSE) BOOL ElevateToSystem(void);

_Return_type_success_(return != NULL) HANDLE GetPrimarySystemTokenFromThread(void);

_Return_type_success_(return != FALSE) BOOL ImpersonateService(_In_z_ WCHAR *ServiceName, _In_ HANDLE *OriginalToken);

_Return_type_success_(return != FALSE) BOOL RestoreToken(_In_ HANDLE OriginalToken);
43 changes: 41 additions & 2 deletions api/entry.c
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
HINSTANCE ResourceModule;
HANDLE ModuleHeap;
SECURITY_ATTRIBUTES SecurityAttributes = { .nLength = sizeof(SECURITY_ATTRIBUTES) };
BOOL IsLocalSystem;

static FARPROC WINAPI
DelayedLoadLibraryHook(unsigned dliNotify, PDelayLoadInfo pdli)
Expand All @@ -35,6 +36,41 @@ DelayedLoadLibraryHook(unsigned dliNotify, PDelayLoadInfo pdli)

const PfnDliHook __pfnDliNotifyHook2 = DelayedLoadLibraryHook;

static BOOL
InitializeSecurityObjects(void)
{
BYTE LocalSystemSid[MAX_SID_SIZE];
DWORD RequiredBytes = sizeof(LocalSystemSid);
HANDLE CurrentProcessToken;
struct
{
TOKEN_USER MaybeLocalSystem;
CHAR LargeEnoughForLocalSystem[MAX_SID_SIZE];
} TokenUserBuffer;
BOOL Ret = FALSE;

if (!CreateWellKnownSid(WinLocalSystemSid, NULL, LocalSystemSid, &RequiredBytes))
return FALSE;

if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &CurrentProcessToken))
return FALSE;

if (!GetTokenInformation(CurrentProcessToken, TokenUser, &TokenUserBuffer, sizeof(TokenUserBuffer), &RequiredBytes))
goto cleanupProcessToken;

IsLocalSystem = EqualSid(TokenUserBuffer.MaybeLocalSystem.User.Sid, LocalSystemSid);
Ret = ConvertStringSecurityDescriptorToSecurityDescriptorW(
IsLocalSystem ? L"O:SYD:P(A;;GA;;;SY)(A;;GA;;;BA)S:(ML;;NWNRNX;;;HI)"
: L"O:BAD:P(A;;GA;;;SY)(A;;GA;;;BA)S:(ML;;NWNRNX;;;HI)",
SDDL_REVISION_1,
&SecurityAttributes.lpSecurityDescriptor,
NULL);

cleanupProcessToken:
CloseHandle(CurrentProcessToken);
return Ret;
}

BOOL APIENTRY
DllMain(_In_ HINSTANCE hinstDLL, _In_ DWORD fdwReason, _In_ LPVOID lpvReserved)
{
Expand All @@ -47,8 +83,11 @@ DllMain(_In_ HINSTANCE hinstDLL, _In_ DWORD fdwReason, _In_ LPVOID lpvReserved)
ModuleHeap = HeapCreate(0, 0, 0);
if (!ModuleHeap)
return FALSE;
ConvertStringSecurityDescriptorToSecurityDescriptorW(
L"O:SYD:P(A;;GA;;;SY)", SDDL_REVISION_1, &SecurityAttributes.lpSecurityDescriptor, NULL);
if (!InitializeSecurityObjects())
{
HeapDestroy(ModuleHeap);
return FALSE;
}
AdapterInit();
NamespaceInit();
break;
Expand Down
1 change: 1 addition & 0 deletions api/entry.h
Original file line number Diff line number Diff line change
Expand Up @@ -29,3 +29,4 @@
extern HINSTANCE ResourceModule;
extern HANDLE ModuleHeap;
extern SECURITY_ATTRIBUTES SecurityAttributes;
extern BOOL IsLocalSystem;
4 changes: 2 additions & 2 deletions api/namespace.c
Original file line number Diff line number Diff line change
Expand Up @@ -59,8 +59,8 @@ static _Return_type_success_(return != FALSE) BOOL NamespaceRuntimeInit(void)
}

BYTE Sid[MAX_SID_SIZE];
DWORD SidSize = MAX_SID_SIZE;
if (!CreateWellKnownSid(WinLocalSystemSid, NULL, Sid, &SidSize))
DWORD SidSize = sizeof(Sid);
if (!CreateWellKnownSid(IsLocalSystem ? WinLocalSystemSid : WinBuiltinAdministratorsSid, NULL, Sid, &SidSize))
{
LastError = LOG_LAST_ERROR(L"Failed to create SID");
goto cleanupBCryptCloseAlgorithmProvider;
Expand Down
Loading

0 comments on commit b157989

Please sign in to comment.