Skip to content

Instantly share code, notes, and snippets.

@diversenok
Last active August 3, 2023 13:48
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save diversenok/4243d878531d0816370d7589ffa77813 to your computer and use it in GitHub Desktop.
Save diversenok/4243d878531d0816370d7589ffa77813 to your computer and use it in GitHub Desktop.
Assign current token to another process.

A simple program that assigns current token to another process.

To succeed the target's process token should not be locked, so use it on newly created suspended processes. The program does not require any additional privileges.

The source code depends on phnt headers.

Binaries: AssignToken.zip

#include <phnt_windows.h>
#include <phnt.h>
#include <stdio.h>
#define PHNT_VERSION PHNT_WIN7
BOOL IsSuccess(NTSTATUS Status, LPCWSTR Where)
{
if (!NT_SUCCESS(Status))
wprintf_s(L"%s faild with 0x%0.8x", Where, Status);
return NT_SUCCESS(Status);
}
int main() {
NTSTATUS status;
HANDLE hToken = 0;
HANDLE hProcess = 0;
PROCESS_ACCESS_TOKEN accessToken = { 0 };
OBJECT_ATTRIBUTES objectAttributes = { 0 };
CLIENT_ID clientID = { 0 };
DWORD pid;
objectAttributes.Length = sizeof(OBJECT_ATTRIBUTES);
status = NtOpenProcessToken(NtCurrentProcess(), TOKEN_DUPLICATE, &hToken);
if (!IsSuccess(status, L"Open current token"))
return 0;
status = NtDuplicateToken(
hToken,
TOKEN_ASSIGN_PRIMARY,
&objectAttributes,
0,
TokenPrimary,
&accessToken.Token
);
NtClose(hToken);
if (!IsSuccess(status, L"Duplicate token"))
return 0;
wprintf_s(L"Target PID = ");
wscanf_s(L"%d", &pid);
clientID.UniqueProcess = (HANDLE)pid;
status = NtOpenProcess(
&hProcess,
PROCESS_QUERY_INFORMATION | PROCESS_SET_INFORMATION,
&objectAttributes,
&clientID
);
if (IsSuccess(status, L"Open target process"))
{
status = NtGetNextThread(
hProcess,
NULL,
THREAD_QUERY_INFORMATION,
0,
0,
&accessToken.Thread
);
if (IsSuccess(status, L"Open target thread"))
{
status = NtSetInformationProcess(
hProcess,
ProcessAccessToken,
&accessToken,
sizeof(PROCESS_ACCESS_TOKEN)
);
if (IsSuccess(status, L"Assign token to the process"))
wprintf_s(L"Done.");
}
}
if (hProcess)
NtClose(hProcess);
if (accessToken.Thread)
NtClose(accessToken.Thread);
if (accessToken.Token)
NtClose(accessToken.Token);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment