496 lines
31 KiB
C
496 lines
31 KiB
C
/* Isolated own-process privilege comparison. Original MIDL/Auth unchanged.
|
|
* One existing own privilege enabled and restored; peer tokens QUERY only.
|
|
* No clock setter, token impersonation, NTP/ACL/provider or product gate. */
|
|
#define _WIN32_WINNT 0x0a00
|
|
#define UNICODE 1
|
|
#include <windows.h>
|
|
#include <stdint.h>
|
|
#include <stddef.h>
|
|
#include <stdio.h>
|
|
#include <wchar.h>
|
|
#include <stdarg.h>
|
|
#include <tlhelp32.h>
|
|
|
|
typedef struct {
|
|
uint32_t stage, native_rpc_return, native_rpc_return_present, rpc_exception;
|
|
uint32_t status_present, ul_size, c_entries, p_entries_present;
|
|
} RmmClockTrace;
|
|
_Static_assert(sizeof(RmmClockTrace) == 32, "same diagnostic trace ABI");
|
|
typedef struct {
|
|
uint32_t generating_component, status, detection_location, flags;
|
|
int32_t number_of_parameters;
|
|
} RmmClockEeRecord;
|
|
typedef struct {
|
|
uint32_t capture_attempted, start_status, next_status, end_status, count, limit_reached;
|
|
RmmClockEeRecord records[4];
|
|
} RmmClockEeInfo;
|
|
_Static_assert(sizeof(RmmClockEeInfo) == 104, "same four-record numeric EEInfo ABI");
|
|
typedef struct {
|
|
uint32_t discovery_invocations, discovery_status, discovery_return_present;
|
|
uint32_t principal_present, principal_units, principal_validated;
|
|
uint32_t status_query_invocations, authn_service, authn_level, impersonation_type;
|
|
uint32_t principal_free_attempted, principal_free_status;
|
|
uint32_t binding_free_attempted, binding_free_status, eeinfo_origin;
|
|
} RmmClockAuthTrace;
|
|
_Static_assert(sizeof(RmmClockAuthTrace) == 60, "same numeric auth trace ABI");
|
|
typedef struct {
|
|
uint32_t query_status, system_user, token_type, thread_query_status, thread_present;
|
|
uint32_t lookup_status, privileges_status, privilege_present, privilege_attributes;
|
|
uint32_t privilege_enabled, privilege_default, privilege_removed;
|
|
} RmmTokenProbe;
|
|
uint32_t rmm_clock_query_trace_spnego_privilege(RmmClockTrace *trace, RmmClockEeInfo *eeinfo, RmmClockAuthTrace *auth);
|
|
|
|
static WCHAR service_name[] = L"RmmClockSpnegoPrivilegeDiagnostic";
|
|
static WCHAR case_id[37];
|
|
static SERVICE_STATUS_HANDLE status_handle;
|
|
static SERVICE_STATUS service_status;
|
|
|
|
static DWORD WINAPI control(DWORD event, DWORD type, void *data, void *context) {
|
|
(void)event; (void)type; (void)data; (void)context;
|
|
return ERROR_CALL_NOT_IMPLEMENTED;
|
|
}
|
|
|
|
static DWORD own_system_token(RmmTokenProbe *probe) {
|
|
HANDLE token = NULL;
|
|
HANDLE thread = NULL;
|
|
DWORD needed = 0, result = ERROR_SUCCESS;
|
|
_Alignas(8) BYTE storage[4096];
|
|
if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &token)) {
|
|
probe->query_status = GetLastError();
|
|
return probe->query_status;
|
|
}
|
|
if (!GetTokenInformation(token, TokenUser, storage, sizeof(storage), &needed)) result = GetLastError();
|
|
else if (needed < sizeof(TOKEN_USER) || needed > sizeof(storage)
|
|
|| !IsWellKnownSid(((TOKEN_USER *)storage)->User.Sid, WinLocalSystemSid)) result = ERROR_ACCESS_DENIED;
|
|
else probe->system_user = 1;
|
|
if (!result) {
|
|
TOKEN_TYPE type = 0;
|
|
if (!GetTokenInformation(token, TokenType, &type, sizeof(type), &needed)) result = GetLastError();
|
|
else {
|
|
probe->token_type = (uint32_t)type;
|
|
if (needed != sizeof(type) || type != TokenPrimary) result = ERROR_ACCESS_DENIED;
|
|
}
|
|
}
|
|
if (!result) {
|
|
if (OpenThreadToken(GetCurrentThread(), TOKEN_QUERY, TRUE, &thread)) {
|
|
probe->thread_present = 1;
|
|
CloseHandle(thread);
|
|
result = ERROR_ACCESS_DENIED; /* never impersonate/revert to continue */
|
|
} else {
|
|
probe->thread_query_status = GetLastError();
|
|
if (probe->thread_query_status != ERROR_NO_TOKEN) result = probe->thread_query_status;
|
|
}
|
|
}
|
|
if (!result) {
|
|
LUID target = {0};
|
|
if (!LookupPrivilegeValueW(NULL, SE_SYSTEMTIME_NAME, &target)) {
|
|
probe->lookup_status = GetLastError();result = probe->lookup_status;
|
|
} else {
|
|
needed = 0;
|
|
if (GetTokenInformation(token, TokenPrivileges, NULL, 0, &needed)
|
|
|| GetLastError() != ERROR_INSUFFICIENT_BUFFER || needed < sizeof(DWORD) || needed > sizeof(storage)) {
|
|
probe->privileges_status = ERROR_INVALID_DATA;result = ERROR_INVALID_DATA;
|
|
} else if (!GetTokenInformation(token, TokenPrivileges, storage, sizeof(storage), &needed)) {
|
|
probe->privileges_status = GetLastError();result = probe->privileges_status;
|
|
} else {
|
|
TOKEN_PRIVILEGES *privileges = (TOKEN_PRIVILEGES *)storage;
|
|
size_t count = privileges->PrivilegeCount;
|
|
if (count > 256 || needed > sizeof(storage)
|
|
|| offsetof(TOKEN_PRIVILEGES, Privileges) + count * sizeof(LUID_AND_ATTRIBUTES) > needed) {
|
|
probe->privileges_status = ERROR_INVALID_DATA;result = ERROR_INVALID_DATA;
|
|
} else for (size_t i = 0; i < count; ++i) {
|
|
const LUID_AND_ATTRIBUTES *p = &privileges->Privileges[i];
|
|
if (p->Luid.LowPart != target.LowPart || p->Luid.HighPart != target.HighPart) continue;
|
|
if (probe->privilege_present) {result = ERROR_INVALID_DATA;break;}
|
|
probe->privilege_present = 1;
|
|
probe->privilege_attributes = p->Attributes;
|
|
probe->privilege_enabled = !!(p->Attributes & SE_PRIVILEGE_ENABLED);
|
|
probe->privilege_default = !!(p->Attributes & SE_PRIVILEGE_ENABLED_BY_DEFAULT);
|
|
probe->privilege_removed = !!(p->Attributes & SE_PRIVILEGE_REMOVED);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
probe->query_status = result;
|
|
CloseHandle(token);
|
|
return result;
|
|
}
|
|
|
|
#define TOKEN_FIELDS "\"query_status\":%lu,\"system_user\":%lu,\"token_type\":%lu,\"thread_query_status\":%lu,\"thread_present\":%lu,\"lookup_status\":%lu,\"privileges_status\":%lu,\"privilege_present\":%lu,\"privilege_attributes\":%lu,\"privilege_enabled\":%lu,\"privilege_default\":%lu,\"privilege_removed\":%lu"
|
|
#define TOKEN_VALUES(p) (unsigned long)(p)->query_status,(unsigned long)(p)->system_user,(unsigned long)(p)->token_type,(unsigned long)(p)->thread_query_status,(unsigned long)(p)->thread_present,(unsigned long)(p)->lookup_status,(unsigned long)(p)->privileges_status,(unsigned long)(p)->privilege_present,(unsigned long)(p)->privilege_attributes,(unsigned long)(p)->privilege_enabled,(unsigned long)(p)->privilege_default,(unsigned long)(p)->privilege_removed
|
|
static DWORD write_new(const WCHAR *suffix, const char *bytes, DWORD length) {
|
|
WCHAR path[256];DWORD written = 0, result = ERROR_SUCCESS;
|
|
int count = swprintf(path, sizeof(path) / sizeof(path[0]),
|
|
L"C:\\ProgramData\\RustDiscoveryBootstrap\\clock-spnego-privilege-trace-%ls\\%ls", case_id, suffix);
|
|
if (count <= 0 || count >= (int)(sizeof(path) / sizeof(path[0]))) return ERROR_INVALID_PARAMETER;
|
|
HANDLE file = CreateFileW(path, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_NEW,
|
|
FILE_ATTRIBUTE_NORMAL | FILE_FLAG_WRITE_THROUGH, NULL);
|
|
if (file == INVALID_HANDLE_VALUE) return GetLastError();
|
|
if (!WriteFile(file, bytes, length, &written, NULL) || written != length) result = ERROR_WRITE_FAULT;
|
|
else if (!FlushFileBuffers(file)) result = GetLastError();
|
|
CloseHandle(file);return result;
|
|
}
|
|
static DWORD write_token(const RmmTokenProbe *token) {
|
|
char report[1024];
|
|
int count = snprintf(report, sizeof(report), "{" TOKEN_FIELDS "}\n", TOKEN_VALUES(token));
|
|
if (count <= 0 || count >= (int)sizeof(report)) return ERROR_BUFFER_OVERFLOW;
|
|
return write_new(L"token.json", report, (DWORD)count);
|
|
}
|
|
|
|
/* Only this held own token is ever passed to AdjustTokenPrivileges. Peer
|
|
* handles request TOKEN_QUERY only and are retained until the final readback. */
|
|
typedef struct {
|
|
DWORD present, query_status;
|
|
TOKEN_STATISTICS statistics;
|
|
DWORD count;
|
|
LUID_AND_ATTRIBUTES privileges[256];
|
|
} TokenSnapshot;
|
|
typedef struct {
|
|
HANDLE process, token;
|
|
SC_HANDLE service;
|
|
DWORD pid;
|
|
FILETIME creation;
|
|
TokenSnapshot before, after;
|
|
} Peer;
|
|
typedef struct {
|
|
HANDLE own;
|
|
SC_HANDLE manager;
|
|
FILETIME creation;
|
|
Peer peers[4]; /* SCM, W32Time, agent, helper */
|
|
TokenSnapshot before, active, restored;
|
|
LUID privilege;
|
|
DWORD preflight_status, enable_attempted, enable_return, enable_error;
|
|
DWORD previous_count, previous_bytes, previous_luid_low, previous_luid_high, previous_attributes;
|
|
DWORD active_status, rpc_attempted, restore_attempted, restore_return, restore_error;
|
|
DWORD restore_input_from_previous, restored_status, peer_after_status, restoration_verified, flow_status;
|
|
} PrivilegeContext;
|
|
|
|
static int luid_equal(LUID a, LUID b) {return a.LowPart==b.LowPart && a.HighPart==b.HighPart;}
|
|
static int luid_before(LUID a, LUID b) {
|
|
return (DWORD)a.HighPart<(DWORD)b.HighPart || (a.HighPart==b.HighPart && a.LowPart<b.LowPart);
|
|
}
|
|
static DWORD snapshot(HANDLE token, TokenSnapshot *out) {
|
|
DWORD needed=0, status=ERROR_SUCCESS;
|
|
_Alignas(8) BYTE storage[4096];
|
|
out->query_status=ERROR_INVALID_DATA;
|
|
if (!GetTokenInformation(token,TokenStatistics,&out->statistics,sizeof(out->statistics),&needed)) status=GetLastError();
|
|
else if (needed!=sizeof(out->statistics)) status=ERROR_INVALID_DATA;
|
|
if (!status) {
|
|
needed=0;
|
|
if (GetTokenInformation(token,TokenPrivileges,NULL,0,&needed)
|
|
|| GetLastError()!=ERROR_INSUFFICIENT_BUFFER || needed<sizeof(DWORD) || needed>sizeof(storage)) status=ERROR_INVALID_DATA;
|
|
else if (!GetTokenInformation(token,TokenPrivileges,storage,sizeof(storage),&needed)) status=GetLastError();
|
|
else {
|
|
TOKEN_PRIVILEGES *value=(TOKEN_PRIVILEGES *)storage;
|
|
if (value->PrivilegeCount>256 || value->PrivilegeCount!=out->statistics.PrivilegeCount || needed>sizeof(storage)
|
|
|| offsetof(TOKEN_PRIVILEGES,Privileges)+(size_t)value->PrivilegeCount*sizeof(LUID_AND_ATTRIBUTES)>needed) status=ERROR_INVALID_DATA;
|
|
else {
|
|
out->count=value->PrivilegeCount;
|
|
for (DWORD i=0;i<out->count;++i) out->privileges[i]=value->Privileges[i];
|
|
for (DWORD i=1;i<out->count;++i) {
|
|
LUID_AND_ATTRIBUTES item=out->privileges[i];DWORD j=i;
|
|
while(j && luid_before(item.Luid,out->privileges[j-1].Luid)) {out->privileges[j]=out->privileges[j-1];--j;}
|
|
out->privileges[j]=item;
|
|
}
|
|
for(DWORD i=1;i<out->count;++i)
|
|
if(luid_equal(out->privileges[i-1].Luid,out->privileges[i].Luid)) status=ERROR_INVALID_DATA;
|
|
}
|
|
}
|
|
}
|
|
out->query_status=status;out->present=!status;return status;
|
|
}
|
|
static int identity_equal(const TokenSnapshot *a,const TokenSnapshot *b) {
|
|
return a->present && b->present && luid_equal(a->statistics.TokenId,b->statistics.TokenId)
|
|
&& luid_equal(a->statistics.AuthenticationId,b->statistics.AuthenticationId)
|
|
&& a->statistics.TokenType==b->statistics.TokenType;
|
|
}
|
|
static DWORD compare_snapshots(const TokenSnapshot *a,const TokenSnapshot *b,LUID target,int enabled) {
|
|
if(!identity_equal(a,b) || a->count!=b->count) return ERROR_INVALID_DATA;
|
|
DWORD matched=0;
|
|
for(DWORD i=0;i<a->count;++i) {
|
|
if(!luid_equal(a->privileges[i].Luid,b->privileges[i].Luid)) return ERROR_INVALID_DATA;
|
|
DWORD attributes=a->privileges[i].Attributes;
|
|
if(luid_equal(target,a->privileges[i].Luid)) {++matched;if(attributes) return ERROR_INVALID_DATA;if(enabled) attributes=SE_PRIVILEGE_ENABLED;}
|
|
if(b->privileges[i].Attributes!=attributes) return ERROR_INVALID_DATA;
|
|
}
|
|
return matched==1?ERROR_SUCCESS:ERROR_PRIVILEGE_NOT_HELD;
|
|
}
|
|
static DWORD query_service_pid(SC_HANDLE service,DWORD *pid) {
|
|
SERVICE_STATUS_PROCESS state={0};DWORD needed=0;
|
|
if(!QueryServiceStatusEx(service,SC_STATUS_PROCESS_INFO,(BYTE *)&state,sizeof(state),&needed)) return GetLastError();
|
|
if(needed!=sizeof(state) || state.dwCurrentState!=SERVICE_RUNNING || !state.dwProcessId) return ERROR_INVALID_STATE;
|
|
*pid=state.dwProcessId;return ERROR_SUCCESS;
|
|
}
|
|
static DWORD scm_pid(DWORD *pid) {
|
|
HANDLE list=CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0);
|
|
if(list==INVALID_HANDLE_VALUE) return GetLastError();
|
|
PROCESSENTRY32W entry={0};entry.dwSize=sizeof(entry);DWORD found=0,status=0;
|
|
if(!Process32FirstW(list,&entry)) status=GetLastError();
|
|
else {
|
|
do {if(!_wcsicmp(entry.szExeFile,L"services.exe")){*pid=entry.th32ProcessID;++found;}}
|
|
while(Process32NextW(list,&entry));
|
|
if(GetLastError()!=ERROR_NO_MORE_FILES) status=GetLastError();
|
|
else if(found!=1) status=ERROR_INVALID_DATA;
|
|
}
|
|
CloseHandle(list);return status;
|
|
}
|
|
static DWORD thread_absent(void) {
|
|
HANDLE token=NULL;
|
|
if(OpenThreadToken(GetCurrentThread(),TOKEN_QUERY,TRUE,&token)) {CloseHandle(token);return ERROR_ACCESS_DENIED;}
|
|
DWORD error=GetLastError();return error==ERROR_NO_TOKEN?ERROR_SUCCESS:error;
|
|
}
|
|
static DWORD peer_binding(Peer *peer,DWORD index) {
|
|
DWORD pid=0,status=index?query_service_pid(peer->service,&pid):scm_pid(&pid);
|
|
if(status) return status;
|
|
if(pid!=peer->pid || GetProcessId(peer->process)!=pid || WaitForSingleObject(peer->process,0)!=WAIT_TIMEOUT) return ERROR_INVALID_DATA;
|
|
FILETIME created,ended,kernel,user;
|
|
if(!GetProcessTimes(peer->process,&created,&ended,&kernel,&user)) return GetLastError();
|
|
if(CompareFileTime(&created,&peer->creation)) return ERROR_INVALID_DATA;
|
|
HANDLE current=NULL;TokenSnapshot now={0};
|
|
if(!OpenProcessToken(peer->process,TOKEN_QUERY,¤t)) return GetLastError();
|
|
status=snapshot(current,&now);CloseHandle(current);
|
|
if(status) return status;
|
|
return identity_equal(&now,&peer->before)?ERROR_SUCCESS:ERROR_INVALID_DATA;
|
|
}
|
|
static DWORD prepare_privilege(PrivilegeContext *ctx) {
|
|
if(!OpenProcessToken(GetCurrentProcess(),TOKEN_QUERY|TOKEN_ADJUST_PRIVILEGES,&ctx->own)) return GetLastError();
|
|
_Alignas(8) BYTE user_info[4096];DWORD needed=0;FILETIME ended,kernel,user;
|
|
if(!GetTokenInformation(ctx->own,TokenUser,user_info,sizeof(user_info),&needed))return GetLastError();
|
|
if(needed<sizeof(TOKEN_USER) || needed>sizeof(user_info) || !IsWellKnownSid(((TOKEN_USER *)user_info)->User.Sid,WinLocalSystemSid))return ERROR_ACCESS_DENIED;
|
|
if(!GetProcessTimes(GetCurrentProcess(),&ctx->creation,&ended,&kernel,&user))return GetLastError();
|
|
DWORD status=snapshot(ctx->own,&ctx->before);if(status) return status;
|
|
if(ctx->before.statistics.TokenType!=TokenPrimary) return ERROR_ACCESS_DENIED;
|
|
if((status=thread_absent())) return status;
|
|
if(!LookupPrivilegeValueW(NULL,SE_SYSTEMTIME_NAME,&ctx->privilege)) return GetLastError();
|
|
if((status=compare_snapshots(&ctx->before,&ctx->before,ctx->privilege,0))) return status;
|
|
ctx->manager=OpenSCManagerW(NULL,NULL,SC_MANAGER_CONNECT);
|
|
if(!ctx->manager) return GetLastError();
|
|
const WCHAR *names[4]={NULL,L"W32Time",L"RmmDiscoveryWindows",L"RmmDiscoverySystemHelper"};
|
|
const WCHAR *binaries[4]={L"services.exe",L"svchost.exe",L"C:\\Program Files\\RustDiscovery\\rmm-agent-windows.exe",L"C:\\Program Files\\RustDiscovery\\rmm-helper-windows.exe"};
|
|
for(DWORD i=0;i<4;++i) {
|
|
Peer *peer=&ctx->peers[i];
|
|
if(i) {peer->service=OpenServiceW(ctx->manager,names[i],SERVICE_QUERY_STATUS);if(!peer->service)return GetLastError();}
|
|
status=i?query_service_pid(peer->service,&peer->pid):scm_pid(&peer->pid);if(status)return status;
|
|
if(peer->pid==GetCurrentProcessId()) return ERROR_INVALID_DATA;
|
|
peer->process=OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION|SYNCHRONIZE,FALSE,peer->pid);
|
|
if(!peer->process)return GetLastError();
|
|
WCHAR path[512],expected[512];DWORD length=512;
|
|
if(!QueryFullProcessImageNameW(peer->process,0,path,&length))return GetLastError();
|
|
if(i<2) {UINT n=GetSystemDirectoryW(expected,512);if(!n || n>480)return ERROR_INVALID_DATA;
|
|
if(swprintf(expected+n,512-n,L"\\%ls",binaries[i])<=0)return ERROR_INVALID_DATA;}
|
|
else {if(wcslen(binaries[i])>=512)return ERROR_INVALID_DATA;wcscpy(expected,binaries[i]);}
|
|
if(_wcsicmp(path,expected))return ERROR_INVALID_DATA;
|
|
FILETIME ended,kernel,user;
|
|
if(!GetProcessTimes(peer->process,&peer->creation,&ended,&kernel,&user))return GetLastError();
|
|
if(!OpenProcessToken(peer->process,TOKEN_QUERY,&peer->token))return GetLastError();
|
|
status=snapshot(peer->token,&peer->before);if(status)return status;
|
|
if(peer->before.statistics.TokenType!=TokenPrimary || luid_equal(peer->before.statistics.TokenId,ctx->before.statistics.TokenId))return ERROR_ACCESS_DENIED;
|
|
if((status=peer_binding(peer,i)))return status;
|
|
}
|
|
return ERROR_SUCCESS;
|
|
}
|
|
static DWORD own_current(PrivilegeContext *ctx) {
|
|
HANDLE token=NULL;TokenSnapshot current={0};
|
|
if(!OpenProcessToken(GetCurrentProcess(),TOKEN_QUERY,&token))return GetLastError();
|
|
DWORD status=snapshot(token,¤t);CloseHandle(token);
|
|
if(status)return status;
|
|
if(!identity_equal(&ctx->before,¤t))return ERROR_INVALID_DATA;
|
|
return thread_absent();
|
|
}
|
|
static void close_privilege(PrivilegeContext *ctx) {
|
|
for(DWORD i=0;i<4;++i){Peer *p=&ctx->peers[i];if(p->token)CloseHandle(p->token);if(p->process)CloseHandle(p->process);if(p->service)CloseServiceHandle(p->service);}
|
|
if(ctx->manager)CloseServiceHandle(ctx->manager);if(ctx->own)CloseHandle(ctx->own);
|
|
}
|
|
|
|
static char witness[262144];
|
|
static size_t witness_used;
|
|
static int append(const char *format,...) {
|
|
va_list args;va_start(args,format);
|
|
int n=vsnprintf(witness+witness_used,sizeof(witness)-witness_used,format,args);va_end(args);
|
|
if(n<=0 || (size_t)n>=sizeof(witness)-witness_used)return 0;
|
|
witness_used+=(size_t)n;return 1;
|
|
}
|
|
static int append_snapshot(const TokenSnapshot *s) {
|
|
const TOKEN_STATISTICS *v=&s->statistics;
|
|
if(!append("{\"present\":%lu,\"query_status\":%lu,\"token_id\":[%lu,%lu],\"authentication_id\":[%lu,%lu],\"modified_id\":[%lu,%lu],\"expiration_time\":[%lu,%lu],\"token_type\":%lu,\"impersonation_level\":%lu,\"dynamic_charged\":%lu,\"dynamic_available\":%lu,\"group_count\":%lu,\"privilege_count\":%lu,\"privileges\":[",
|
|
(unsigned long)s->present,(unsigned long)s->query_status,(unsigned long)v->TokenId.LowPart,(unsigned long)(DWORD)v->TokenId.HighPart,
|
|
(unsigned long)v->AuthenticationId.LowPart,(unsigned long)(DWORD)v->AuthenticationId.HighPart,(unsigned long)v->ModifiedId.LowPart,(unsigned long)(DWORD)v->ModifiedId.HighPart,
|
|
(unsigned long)v->ExpirationTime.LowPart,(unsigned long)(DWORD)v->ExpirationTime.HighPart,(unsigned long)v->TokenType,(unsigned long)v->ImpersonationLevel,
|
|
(unsigned long)v->DynamicCharged,(unsigned long)v->DynamicAvailable,(unsigned long)v->GroupCount,(unsigned long)s->count))return 0;
|
|
for(DWORD i=0;i<s->count;++i)if(!append("%s[%lu,%lu,%lu]",i?",":"",(unsigned long)s->privileges[i].Luid.LowPart,(unsigned long)(DWORD)s->privileges[i].Luid.HighPart,(unsigned long)s->privileges[i].Attributes))return 0;
|
|
return append("]}");
|
|
}
|
|
static DWORD write_before(const PrivilegeContext *ctx) {
|
|
witness_used=0;
|
|
if(!append("{\"schema_version\":1,\"own_pid\":%lu,\"own_creation\":[%lu,%lu],\"own\":",(unsigned long)GetCurrentProcessId(),(unsigned long)ctx->creation.dwLowDateTime,(unsigned long)ctx->creation.dwHighDateTime) || !append_snapshot(&ctx->before) || !append(",\"peers\":["))return ERROR_BUFFER_OVERFLOW;
|
|
for(DWORD i=0;i<4;++i){const Peer *p=&ctx->peers[i];
|
|
if(!append("%s{\"role\":%lu,\"pid\":%lu,\"creation\":[%lu,%lu],\"token\":",i?",":"",(unsigned long)i,(unsigned long)p->pid,(unsigned long)p->creation.dwLowDateTime,(unsigned long)p->creation.dwHighDateTime)
|
|
|| !append_snapshot(&p->before) || !append("}"))return ERROR_BUFFER_OVERFLOW;}
|
|
if(!append("]}\n"))return ERROR_BUFFER_OVERFLOW;
|
|
return write_new(L"privilege-before.json",witness,(DWORD)witness_used);
|
|
}
|
|
static DWORD write_adjustment(const PrivilegeContext *ctx) {
|
|
witness_used=0;
|
|
if(!append("{\"schema_version\":1,\"preflight_status\":%lu,\"enable_attempted\":%lu,\"enable_return\":%lu,\"enable_error\":%lu,\"previous_count\":%lu,\"previous_bytes\":%lu,\"previous_luid\":[%lu,%lu],\"previous_attributes\":%lu,\"active_status\":%lu,\"rpc_attempted\":%lu,\"restore_attempted\":%lu,\"restore_return\":%lu,\"restore_error\":%lu,\"restore_input_from_previous\":%lu,\"restored_status\":%lu,\"peer_after_status\":%lu,\"restoration_verified\":%lu,\"flow_status\":%lu,\"target_luid\":[%lu,%lu],\"active\":",
|
|
(unsigned long)ctx->preflight_status,(unsigned long)ctx->enable_attempted,(unsigned long)ctx->enable_return,(unsigned long)ctx->enable_error,
|
|
(unsigned long)ctx->previous_count,(unsigned long)ctx->previous_bytes,(unsigned long)ctx->previous_luid_low,(unsigned long)ctx->previous_luid_high,(unsigned long)ctx->previous_attributes,
|
|
(unsigned long)ctx->active_status,(unsigned long)ctx->rpc_attempted,(unsigned long)ctx->restore_attempted,(unsigned long)ctx->restore_return,(unsigned long)ctx->restore_error,
|
|
(unsigned long)ctx->restore_input_from_previous,(unsigned long)ctx->restored_status,(unsigned long)ctx->peer_after_status,(unsigned long)ctx->restoration_verified,(unsigned long)ctx->flow_status,
|
|
(unsigned long)ctx->privilege.LowPart,(unsigned long)(DWORD)ctx->privilege.HighPart)
|
|
|| !append_snapshot(&ctx->active) || !append(",\"restored\":") || !append_snapshot(&ctx->restored) || !append(",\"peers_after\":["))return ERROR_BUFFER_OVERFLOW;
|
|
for(DWORD i=0;i<4;++i){if(i && !append(","))return ERROR_BUFFER_OVERFLOW;if(!append_snapshot(&ctx->peers[i].after))return ERROR_BUFFER_OVERFLOW;}
|
|
if(!append("]}\n"))return ERROR_BUFFER_OVERFLOW;
|
|
return write_new(L"privilege-adjustment.json",witness,(DWORD)witness_used);
|
|
}
|
|
|
|
static DWORD write_result(uint32_t rpc, const RmmClockTrace *trace, const RmmClockEeInfo *eeinfo, const RmmClockAuthTrace *auth, const RmmTokenProbe *token) {
|
|
char id[37], report[4096];
|
|
for (unsigned i = 0; i < 37; ++i) id[i] = (char)case_id[i];
|
|
int count = snprintf(report, sizeof(report),
|
|
"{\"schema_version\":1,\"profile\":\"clock-system-spnego-privilege-v1\",\"case_id\":\"%s\","
|
|
"\"token_system\":%s,\"read_only\":false,\"diagnostic_only\":true,\"query_invocations\":%lu,"
|
|
"\"clock_qualified\":false,\"adapter_qualified\":false,\"product_gate_open\":false,\"rpc_code\":%lu,"
|
|
"\"trace\":{\"stage\":%lu,\"native_rpc_return\":%lu,\"native_rpc_return_present\":%lu,"
|
|
"\"rpc_exception\":%lu,\"status_present\":%lu,\"ul_size\":%lu,\"c_entries\":%lu,\"p_entries_present\":%lu}}\n",
|
|
id, (token->query_status==0 && token->system_user==1 && token->token_type==1 && token->thread_present==0 && token->thread_query_status==ERROR_NO_TOKEN)?"true":"false",
|
|
(unsigned long)auth->status_query_invocations, (unsigned long)rpc, (unsigned long)trace->stage,
|
|
(unsigned long)trace->native_rpc_return, (unsigned long)trace->native_rpc_return_present,
|
|
(unsigned long)trace->rpc_exception, (unsigned long)trace->status_present,
|
|
(unsigned long)trace->ul_size, (unsigned long)trace->c_entries, (unsigned long)trace->p_entries_present);
|
|
if (count <= 0 || count >= (int)sizeof(report)) return ERROR_BUFFER_OVERFLOW;
|
|
if (count < 3 || eeinfo->count > 4) return ERROR_INVALID_DATA;
|
|
/* Replace only the final root-object closure; original trace stays intact. */
|
|
size_t used = (size_t)count - 2;
|
|
int appended = snprintf(report + used, sizeof(report) - used,
|
|
",\"eeinfo\":{\"capture_attempted\":%lu,\"start_status\":%lu,\"next_status\":%lu,"
|
|
"\"end_status\":%lu,\"count\":%lu,\"limit_reached\":%lu,\"records\":[",
|
|
(unsigned long)eeinfo->capture_attempted, (unsigned long)eeinfo->start_status,
|
|
(unsigned long)eeinfo->next_status, (unsigned long)eeinfo->end_status,
|
|
(unsigned long)eeinfo->count, (unsigned long)eeinfo->limit_reached);
|
|
if (appended <= 0 || (size_t)appended >= sizeof(report) - used) return ERROR_BUFFER_OVERFLOW;
|
|
used += (size_t)appended;
|
|
for (unsigned i = 0; i < eeinfo->count; ++i) {
|
|
const RmmClockEeRecord *record = &eeinfo->records[i];
|
|
appended = snprintf(report + used, sizeof(report) - used,
|
|
"%s{\"generating_component\":%lu,\"status\":%lu,\"detection_location\":%lu,"
|
|
"\"flags\":%lu,\"number_of_parameters\":%ld}", i ? "," : "",
|
|
(unsigned long)record->generating_component, (unsigned long)record->status,
|
|
(unsigned long)record->detection_location, (unsigned long)record->flags,
|
|
(long)record->number_of_parameters);
|
|
if (appended <= 0 || (size_t)appended >= sizeof(report) - used) return ERROR_BUFFER_OVERFLOW;
|
|
used += (size_t)appended;
|
|
}
|
|
appended = snprintf(report + used, sizeof(report) - used,
|
|
"]},\"token\":{" TOKEN_FIELDS "},\"auth\":{"
|
|
"\"discovery_invocations\":%lu,\"discovery_status\":%lu,\"discovery_return_present\":%lu,"
|
|
"\"principal_present\":%lu,\"principal_units\":%lu,\"principal_validated\":%lu,"
|
|
"\"status_query_invocations\":%lu,\"authn_service\":%lu,\"authn_level\":%lu,\"impersonation_type\":%lu,"
|
|
"\"principal_free_attempted\":%lu,\"principal_free_status\":%lu,\"binding_free_attempted\":%lu,"
|
|
"\"binding_free_status\":%lu,\"eeinfo_origin\":%lu}}\n",
|
|
TOKEN_VALUES(token), (unsigned long)auth->discovery_invocations, (unsigned long)auth->discovery_status,
|
|
(unsigned long)auth->discovery_return_present, (unsigned long)auth->principal_present,
|
|
(unsigned long)auth->principal_units, (unsigned long)auth->principal_validated,
|
|
(unsigned long)auth->status_query_invocations, (unsigned long)auth->authn_service,
|
|
(unsigned long)auth->authn_level, (unsigned long)auth->impersonation_type,
|
|
(unsigned long)auth->principal_free_attempted, (unsigned long)auth->principal_free_status,
|
|
(unsigned long)auth->binding_free_attempted, (unsigned long)auth->binding_free_status,
|
|
(unsigned long)auth->eeinfo_origin);
|
|
if (appended <= 0 || (size_t)appended >= sizeof(report) - used) return ERROR_BUFFER_OVERFLOW;
|
|
used += (size_t)appended;
|
|
count = (int)used;
|
|
return write_new(L"result.json", report, (DWORD)count);
|
|
}
|
|
|
|
static void WINAPI run_service(DWORD argc, WCHAR **argv) {
|
|
(void)argc; (void)argv;
|
|
status_handle = RegisterServiceCtrlHandlerExW(service_name, control, NULL);
|
|
if (!status_handle) return;
|
|
ZeroMemory(&service_status, sizeof(service_status));
|
|
service_status.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
|
|
service_status.dwCurrentState = SERVICE_RUNNING;
|
|
service_status.dwControlsAccepted = 0;
|
|
if (!SetServiceStatus(status_handle, &service_status)) return;
|
|
RmmTokenProbe token={0};PrivilegeContext ctx={0};
|
|
RmmClockTrace trace={0};RmmClockEeInfo eeinfo={0};
|
|
RmmClockAuthTrace auth={0};auth.authn_service=9;auth.authn_level=6;auth.impersonation_type=2;
|
|
DWORD result=own_system_token(&token),rpc=0;
|
|
DWORD token_write=write_token(&token); /* durable old numeric probe */
|
|
if(!result)result=token_write;
|
|
if(!result)result=prepare_privilege(&ctx);
|
|
if(!result)result=write_before(&ctx); /* durable complete pre-enable witness */
|
|
ctx.preflight_status=result;
|
|
if(!result) {
|
|
TOKEN_PRIVILEGES enable={0},previous={0},restore={0};DWORD previous_bytes=0;
|
|
enable.PrivilegeCount=1;enable.Privileges[0].Luid=ctx.privilege;
|
|
enable.Privileges[0].Attributes=SE_PRIVILEGE_ENABLED;
|
|
restore.PrivilegeCount=1;restore.Privileges[0].Luid=ctx.privilege; /* saved original Attr0 */
|
|
ctx.enable_attempted=1; /* all paths after this call execute the one restore */
|
|
SetLastError(ERROR_SUCCESS);
|
|
ctx.enable_return=!!AdjustTokenPrivileges(ctx.own,FALSE,&enable,sizeof(previous),&previous,&previous_bytes);
|
|
ctx.enable_error=GetLastError();ctx.previous_count=previous.PrivilegeCount;ctx.previous_bytes=previous_bytes;
|
|
if(previous.PrivilegeCount==1) {
|
|
ctx.previous_luid_low=previous.Privileges[0].Luid.LowPart;
|
|
ctx.previous_luid_high=(DWORD)previous.Privileges[0].Luid.HighPart;
|
|
ctx.previous_attributes=previous.Privileges[0].Attributes;
|
|
if(previous_bytes==sizeof(previous) && luid_equal(previous.Privileges[0].Luid,ctx.privilege)
|
|
&& previous.Privileges[0].Attributes==0) {
|
|
restore=previous;ctx.restore_input_from_previous=1;
|
|
}
|
|
}
|
|
if(!ctx.enable_return || ctx.enable_error || !ctx.restore_input_from_previous)
|
|
result=ctx.enable_error?ctx.enable_error:ERROR_INVALID_DATA;
|
|
if(!result)result=snapshot(ctx.own,&ctx.active);
|
|
if(!result)result=compare_snapshots(&ctx.before,&ctx.active,ctx.privilege,1);
|
|
if(!result)result=own_current(&ctx);
|
|
for(DWORD i=0;!result && i<4;++i)result=peer_binding(&ctx.peers[i],i);
|
|
ctx.active_status=result;
|
|
if(!result) {ctx.rpc_attempted=1;rpc=rmm_clock_query_trace_spnego_privilege(&trace,&eeinfo,&auth);}
|
|
/* No report IO or early return between adjustment and this restoration. */
|
|
ctx.restore_attempted=1;SetLastError(ERROR_SUCCESS);
|
|
ctx.restore_return=!!AdjustTokenPrivileges(ctx.own,FALSE,&restore,0,NULL,NULL);
|
|
ctx.restore_error=GetLastError();
|
|
ctx.restored_status=snapshot(ctx.own,&ctx.restored);
|
|
if(!ctx.restored_status)ctx.restored_status=compare_snapshots(&ctx.before,&ctx.restored,ctx.privilege,0);
|
|
if(!ctx.restored_status)ctx.restored_status=own_current(&ctx);
|
|
ctx.restoration_verified=ctx.restore_return && !ctx.restore_error && !ctx.restored_status;
|
|
if(!ctx.restoration_verified && !result)result=ctx.restore_error?ctx.restore_error:ERROR_INVALID_DATA;
|
|
for(DWORD i=0;i<4;++i) {
|
|
Peer *peer=&ctx.peers[i];DWORD status=peer_binding(peer,i);
|
|
if(!status)status=snapshot(peer->token,&peer->after);
|
|
if(!status && (!identity_equal(&peer->before,&peer->after)
|
|
|| !luid_equal(peer->before.statistics.ModifiedId,peer->after.statistics.ModifiedId)
|
|
|| peer->before.count!=peer->after.count))status=ERROR_INVALID_DATA;
|
|
for(DWORD j=0;!status && j<peer->before.count;++j)
|
|
if(!luid_equal(peer->before.privileges[j].Luid,peer->after.privileges[j].Luid)
|
|
|| peer->before.privileges[j].Attributes!=peer->after.privileges[j].Attributes)status=ERROR_INVALID_DATA;
|
|
if(status && !ctx.peer_after_status)ctx.peer_after_status=status;
|
|
}
|
|
if(ctx.peer_after_status && !result)result=ctx.peer_after_status;
|
|
}
|
|
ctx.flow_status=result;
|
|
DWORD adjustment_write=write_adjustment(&ctx);
|
|
if(!result)result=adjustment_write;
|
|
if(!ctx.rpc_attempted){rpc=ctx.flow_status;trace.stage=200;}
|
|
DWORD result_write=write_result(rpc,&trace,&eeinfo,&auth,&token);
|
|
if(!result)result=result_write;
|
|
close_privilege(&ctx);
|
|
service_status.dwCurrentState = SERVICE_STOPPED;
|
|
service_status.dwWin32ExitCode = result;
|
|
SetServiceStatus(status_handle, &service_status);
|
|
}
|
|
|
|
int wmain(int argc, WCHAR **argv) {
|
|
if (argc != 3 || wcscmp(argv[1], L"--service") || wcslen(argv[2]) != 36) return ERROR_INVALID_PARAMETER;
|
|
for (unsigned i = 0; i < 36; ++i) {
|
|
WCHAR value = argv[2][i];
|
|
if (i == 8 || i == 13 || i == 18 || i == 23) {
|
|
if (value != L'-') return ERROR_INVALID_PARAMETER;
|
|
} else if (!((value >= L'0' && value <= L'9') || (value >= L'a' && value <= L'f'))) return ERROR_INVALID_PARAMETER;
|
|
case_id[i] = value;
|
|
}
|
|
case_id[36] = 0;
|
|
SERVICE_TABLE_ENTRYW table[] = {{service_name, run_service}, {NULL, NULL}};
|
|
if (!StartServiceCtrlDispatcherW(table)) return (int)GetLastError();
|
|
return 0;
|
|
}
|