Skip to content

Instantly share code, notes, and snippets.

@tingtho
Forked from diversenok/AssignToken.c
Created August 3, 2023 13:48
Show Gist options
  • Select an option

  • Save tingtho/8e149a5e81fe6befcd0e514234087b64 to your computer and use it in GitHub Desktop.

Select an option

Save tingtho/8e149a5e81fe6befcd0e514234087b64 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