Document native Windows EEInfo probe and preserved closed gates
Rust development slice / linux (push) Failing after 6s

This commit is contained in:
2026-11-14 17:36:50 +01:00
parent 19f0b1e7f6
commit 29e35c4fb6
6 changed files with 1080 additions and 0 deletions
+138
View File
@@ -0,0 +1,138 @@
#!/usr/bin/env python3
"""Local-only SYSTEM trace diagnostic build; no VM and no product source edits."""
import base64
import difflib
import hashlib
import importlib.util
import json
import os
from pathlib import Path
import re
import shutil
import subprocess
import uuid
ROOT = Path(__file__).resolve().parents[3]
HERE = Path(__file__).resolve().parent
STATE = ROOT / 'devstate/windows-clock-eeinfo-trace'
IMAGE = 'sha256:1b2fd985d2c1fcc3545ace602405dc68fa899201bd8a73fa319ff96377203fa9'
BASELINE = ROOT / 'devstate/windows-clock-midl/diagnostic-builds/181c3a1c-8324-41fd-9b7c-aa8010262912/qualification.json'
BASELINE_SHA = '2e0de3acf72ab5c3a8e0baa54e8643d086ea7c03d1b38fd89b6bfc00e45f8cbb'
NATIVE = ROOT / 'devstate/windows-clock-midl/native-cases/149bafe2-3469-4580-b133-988812bcc3db'
READBACK = NATIVE / 'readback-059c15ef-0f31-41aa-ad1d-ea6b774280d7.json'
READBACK_SHA = '0dc2373825f7f8f224cda04ecd5c521dd3c37a6e712bc3ed83bc4fa6d0d89c8c'
def require(value, message):
if not value: raise RuntimeError(message)
def sha(path):
return hashlib.sha256(Path(path).read_bytes()).hexdigest()
def write(path, raw):
path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
fd = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY | os.O_NOFOLLOW, 0o600)
with os.fdopen(fd, 'wb') as output:
output.write(raw); output.flush(); os.fsync(output.fileno())
def save(path, value):
write(path, (json.dumps(value, indent=2) + '\n').encode())
def original_sources():
require(sha(BASELINE) == BASELINE_SHA, 'original b1d3 qualification')
value = json.loads(BASELINE.read_bytes())
require(len(value['source_files']) == 131 and value['artifact']['sha256'] == 'b1d3da4f393ddf20bc8e48a9894ee314666f2ac3613ef97f5c228e3d089ca560', 'unchanged complete original131 source set')
for name, digest in value['source_files'].items():
path = ROOT / name
require(not path.is_symlink() and path.is_file() and sha(path) == digest, 'original131 input changed')
return value
def own_sources():
return {str((HERE / name).relative_to(ROOT)):sha(HERE / name) for name in ('clock_rpc_eeinfo.c','system_trace_eeinfo.c','build.py','native.py')}
def main():
os.umask(0o077)
baseline = original_sources(); before = own_sources()
require(sha(READBACK) == READBACK_SHA, 'actual Microsoft codegen readback')
receipt = json.loads(READBACK.read_bytes())
require(receipt['readback_only'] is True and receipt['result']['complete'] is True
and receipt['result']['run']['exit_code'] == 0 and receipt['result']['no_rpc'] is True,
'actual completed MIDL codegen')
folder = STATE / ('build-' + str(uuid.uuid4())); folder.mkdir(mode=0o700, parents=True)
source = folder / 'source'; source.mkdir(mode=0o700)
generated = {}
for name, digest in baseline['generated_inputs'].items():
path = NATIVE / ('native-' + name); raw = path.read_bytes()
item = next(item for item in receipt['files'] if item['name'] == name)
require(sha(path) == item['sha256'] == digest and len(raw) == item['bytes']
and base64.b64decode(item['base64'], validate=True) == raw, 'same actual unchanged Microsoft output')
write(source / name, raw); generated[name] = digest
baseline_wrapper = ROOT / 'crates/agent-windows/native/clock_rpc.c'
require(sha(baseline_wrapper) == '74aceb6e2b70c5dd628fae069a842c356c20300b8c8ab12754258c78eaf295c8','same original C/Auth wrapper')
wrapper = HERE / 'clock_rpc_eeinfo.c'
write(source / 'clock_rpc.c', wrapper.read_bytes()); write(source / 'system_trace.c', (HERE / 'system_trace_eeinfo.c').read_bytes())
delta = ''.join(difflib.unified_diff(baseline_wrapper.read_text().splitlines(True),wrapper.read_text().splitlines(True),fromfile='original-clock_rpc.c',tofile='diagnostic-clock_rpc_eeinfo.c'))
write(folder / 'wrapper-source.diff',delta.encode())
save(folder / 'intent.json', dict(image=IMAGE, original131=baseline['source_files'], baseline_sha256=BASELINE_SHA,
actual_codegen_readback_sha256=READBACK_SHA, generated=generated, own_sources=before,
wrapper_sha256=sha(wrapper), original_wrapper_sha256=sha(baseline_wrapper), wrapper_diff_sha256=sha(folder / 'wrapper-source.diff'), own_system_token_only=True, exactly_one_trace_call=True, no_vm=True))
output = folder / 'output'; output.mkdir(mode=0o700)
checks = {}
def run(name, args):
command = ['docker','run','--rm','--network','none','--read-only','--tmpfs','/tmp:rw,size=128m',
'-v',str(source)+':/src:ro','-v',str(output)+':/out','--entrypoint',args[0],IMAGE,*args[1:]]
done = subprocess.run(command,capture_output=True,timeout=120)
write(folder / (name+'.stdout'),done.stdout); write(folder / (name+'.stderr'),done.stderr)
checks[name] = dict(exit_code=done.returncode,command=command,stdout_sha256=sha(folder / (name+'.stdout')),stderr_sha256=sha(folder / (name+'.stderr')))
save(folder / (name+'.json'),checks[name]); require(done.returncode == 0,'local diagnostic compile/check failure: '+name)
return done.stdout
flags = ['--target=x86_64-w64-windows-gnu','-fms-extensions','-Wall','-Wextra','-Werror','-D_M_AMD64=100','-I/src','-O2']
run('main',['clang',*flags,'-c','/src/system_trace.c','-o','/out/system_trace.o'])
run('wrapper',['clang',*flags,'-c','/src/clock_rpc.c','-o','/out/clock_rpc.o'])
run('actual-midl',['clang',*flags,'-Wno-error=missing-braces','-Wno-error=unused-const-variable','-c','/src/w32time_c.c','-o','/out/w32time_c.o'])
run('link',['x86_64-w64-mingw32-gcc','-static-libgcc','-municode','/out/system_trace.o','/out/clock_rpc.o','/out/w32time_c.o',
'-lrpcrt4','-ladvapi32','-lkernel32','-lmincore','-o','/out/ClockSystemEeInfoTrace.linked.exe'])
raw_linked = output / 'ClockSystemEeInfoTrace.linked.exe'
linked = output / 'ClockSystemEeInfoTrace.original.exe'; delivery = output / 'ClockSystemEeInfoTrace.exe'
# Retain a caller-owned private exact copy; Docker's root-owned raw link is
# kept too. No chmod/chown of unrelated objects or source mutation.
shutil.copyfile(raw_linked,linked); linked.chmod(0o600)
shutil.copyfile(linked,delivery); delivery.chmod(0o600)
run('strip',['x86_64-w64-mingw32-strip','--strip-debug','/out/ClockSystemEeInfoTrace.exe'])
imports = sorted(set(re.findall(r'DLL Name:\s+(\S+)',run('imports',['x86_64-w64-mingw32-objdump','-p','/out/ClockSystemEeInfoTrace.exe']).decode())))
require(imports and {name.lower() for name in imports}.issubset({'kernel32.dll','msvcrt.dll','advapi32.dll','rpcrt4.dll','api-ms-win-core-realtime-l1-1-2.dll'}),'reviewed system DLL imports only')
data = delivery.read_bytes(); offset = int.from_bytes(data[60:64],'little')
require(data[:2] == b'MZ' and data[offset:offset+6] == b'PE\0\0\x64\x86' and len(data) < 1048576,'bounded standalone C x64 PE')
spec = importlib.util.spec_from_file_location('system_trace_native',HERE / 'native.py'); native = importlib.util.module_from_spec(spec); spec.loader.exec_module(native)
script = folder / 'native.ps1'; write(script,native.SCRIPT.encode())
parser = "$e=$null;$t=$null;[System.Management.Automation.Language.Parser]::ParseFile($args[0],[ref]$t,[ref]$e)|Out-Null;if($e.Count){$e|ForEach-Object{$_.Message};exit 1};'AST_PASS'"
parser_path = folder / 'parse-native.ps1'; write(parser_path,parser.encode())
parsed = subprocess.run(['/tmp/rmm-powershell-parser/pwsh','-NoLogo','-NoProfile','-NonInteractive','-File',str(parser_path),str(script)],capture_output=True,timeout=15)
write(folder / 'powershell-parser.stdout',parsed.stdout); write(folder / 'powershell-parser.stderr',parsed.stderr)
require(parsed.returncode == 0 and b'AST_PASS' in parsed.stdout and not parsed.stderr,'actual PowerShell AST')
command_chars = len(native.encoded_command())
require(command_chars < 32767,'Windows encoded command length')
require(original_sources()['source_files'] == baseline['source_files'] and own_sources() == before,'all original131 and new sources unchanged')
manifest = dict(schema_version=1,profile='clock-system-eeinfo-v1',image=IMAGE,baseline_sha256=BASELINE_SHA,
original131=baseline['source_files'],own_sources=before,wrapper_sha256=sha(wrapper),original_wrapper_sha256=sha(baseline_wrapper),wrapper_diff_sha256=sha(folder / 'wrapper-source.diff'),generated=generated,
actual_codegen_readback_sha256=READBACK_SHA,checks=checks,script_sha256=hashlib.sha256(native.SCRIPT.encode()).hexdigest(),
powershell_ast_passed=True,encoded_command_characters=command_chars,
artifact=dict(path=str(delivery),sha256=sha(delivery),bytes=len(data),imports=imports),
linked=dict(path=str(linked),sha256=sha(linked)),raw_linked_sha256=sha(raw_linked),native_executed=False,clock_qualified=False,
adapter_qualified=False,product_gate_open=False,no_vm=True,no_rmm_jobs=True)
save(folder / 'manifest.json',manifest)
print(json.dumps(dict(manifest=str(folder / 'manifest.json'),manifest_sha256=sha(folder / 'manifest.json'),artifact=manifest['artifact'],
original131_unchanged=True,powershell_ast=True,command_characters=command_chars,native_executed=False)))
if __name__ == '__main__':
try: main()
except Exception as error:
print(json.dumps(dict(error='CLOCK_SYSTEM_TRACE_LOCAL_INCOMPLETE',error_class=type(error).__name__,details_suppressed=True)))
raise SystemExit(2) from None
@@ -0,0 +1,291 @@
/* Only the authenticated local MS-W32T status operation is reachable here.
* NDR code is generated by WIDL; SEH must terminate inside C, never in Rust.
*/
#define _WIN32_WINNT 0x0a00
#include <windows.h>
#include <rpc.h>
#include <rpcasync.h>
#include <stdint.h>
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#include "w32time.h"
/* Documented public SDK API; older MinGW headers omit its declaration. */
int RPC_ENTRY RpcExceptionFilter(unsigned long exception_code);
/* Older MinGW headers stop at V3. This is the documented x64 V5 SDK layout,
* not a fallback to an older authentication contract. MSVC also checks it
* directly against its native SDK declaration. Windows x64 is the only target.
* https://learn.microsoft.com/windows/win32/api/rpcdce/ns-rpcdce-rpc_security_qos_v5_w
*/
typedef struct {
unsigned long Version, Capabilities, IdentityTracking, ImpersonationType;
unsigned long AdditionalSecurityInfoType;
union { RPC_HTTP_TRANSPORT_CREDENTIALS_W *HttpCredentials; } u;
void *Sid;
unsigned int EffectiveOnly;
void *ServerSecurityDescriptor;
} RmmRpcQosV5;
_Static_assert(sizeof(RmmRpcQosV5) == 56, "x64 RPC QOS V5 ABI");
_Static_assert(offsetof(RmmRpcQosV5, Sid) == offsetof(RPC_SECURITY_QOS_V3_W, Sid), "SDK QOS prefix ABI");
_Static_assert(offsetof(RmmRpcQosV5, ServerSecurityDescriptor) == 48, "x64 server descriptor ABI");
#ifdef _MSC_VER
_Static_assert(sizeof(RmmRpcQosV5) == sizeof(RPC_SECURITY_QOS_V5_W), "native SDK QOS V5 ABI");
_Static_assert(offsetof(RmmRpcQosV5, ServerSecurityDescriptor) == offsetof(RPC_SECURITY_QOS_V5_W, ServerSecurityDescriptor), "native SDK descriptor ABI");
#endif
typedef struct Allocation { struct Allocation *next; size_t size; } Allocation;
typedef struct { Allocation *head; size_t total; } Arena;
/* Explicit Windows TLS also works on threads created by SCM. Clang static TLS
* in the mixed Rust/MinGW PE did not initialize such a thread's storage. */
static INIT_ONCE arena_once = INIT_ONCE_STATIC_INIT;
static DWORD arena_index = TLS_OUT_OF_INDEXES;
static BOOL CALLBACK initialize_arena(PINIT_ONCE once, PVOID parameter, PVOID *context) {
(void)once; (void)parameter; (void)context;
arena_index = TlsAlloc();
return arena_index != TLS_OUT_OF_INDEXES;
}
void *__RPC_USER MIDL_user_allocate(size_t size) {
Arena *arena = TlsGetValue(arena_index);
if (!arena || size > 65536 || arena->total > 65536 - size) return NULL;
Allocation *p = calloc(1, sizeof(*p) + size);
if (!p) return NULL;
p->size = size; p->next = arena->head; arena->head = p; arena->total += size;
return p + 1;
}
void __RPC_USER MIDL_user_free(void *memory) {
Arena *arena = TlsGetValue(arena_index);
if (!memory || !arena) return;
Allocation **link = &arena->head;
while (*link && (*link + 1) != memory) link = &(*link)->next;
if (*link) { Allocation *p = *link; *link = p->next; arena->total -= p->size; free(p); }
}
static void release_allocations(Arena *arena) {
while (arena->head) MIDL_user_free(arena->head + 1);
}
/* Stable numeric ABI, no returned peer/source strings or remotely sized data. */
typedef struct {
uint32_t leap, stratum, state, flags, last_result, size;
uint64_t last_sync, sync_age;
int64_t root_delay;
uint64_t root_dispersion;
int64_t phase;
} RmmClockStatus;
_Static_assert(sizeof(RmmClockStatus) == 64, "Rust numeric clock ABI");
_Static_assert(sizeof(RMM_W32TIME_STATUS) == 120, "MS-W32T x64 structure ABI");
/* Diagnostic-only numeric ABI. No strings, names, pointers or remote arrays
* leave C. A zero native return is meaningful only when return_present is1.
* Stages:10 compose,20 binding,30 auth,40 call-timeout,50 arena,
* 60 invoking,61 returned,62 raw numeric status,70 local guard,80 mapped,
* 90 contained RPC/SEH exception. Never used by the clock trust evaluator.
*/
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, "Rust numeric diagnostic ABI");
/* Diagnostic source variant only. No strings/parameters leave this function. */
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(RmmClockEeRecord) == 20, "numeric EEInfo record ABI");
_Static_assert(sizeof(RmmClockEeInfo) == 104, "bounded four-record EEInfo ABI");
static void capture_eeinfo(RmmClockEeInfo *out) {
RPC_ERROR_ENUM_HANDLE enumeration = {0};
out->capture_attempted = 1;
out->start_status = RpcErrorStartEnumeration(&enumeration);
if (out->start_status != RPC_S_OK) return;
for (unsigned i = 0; i < 4; ++i) {
RPC_EXTENDED_ERROR_INFO info = {0};
info.Version = RPC_EEINFO_VERSION;
info.Flags = 0;
info.NumberOfParameters = MaxNumberOfEEInfoParams;
out->next_status = RpcErrorGetNextRecord(&enumeration, FALSE, &info);
if (out->next_status != RPC_S_OK) break;
RmmClockEeRecord *record = &out->records[out->count++];
record->generating_component = info.GeneratingComponent;
record->status = info.Status;
record->detection_location = info.DetectionLocation;
record->flags = info.Flags;
record->number_of_parameters = info.NumberOfParameters;
/* ComputerName and Parameters are neither copied nor dereferenced.
* CopyStrings=FALSE: RPC owns all borrowed fields until EndEnumeration. */
}
out->limit_reached = out->count == 4;
out->end_status = RpcErrorEndEnumeration(&enumeration);
}
static uint32_t invoke_status(RPC_BINDING_HANDLE binding, RmmClockStatus *out, RmmClockTrace *trace, RmmClockEeInfo *eeinfo) {
RMM_W32TIME_STATUS *status = NULL;
unsigned long result = 0;
Arena arena = {0};
if (trace) trace->stage = 50;
if (!result && !InitOnceExecuteOnce(&arena_once, initialize_arena, NULL, NULL)) result = ERROR_NOT_ENOUGH_MEMORY;
if (!result && TlsGetValue(arena_index)) result = ERROR_BUSY;
if (!result && !TlsSetValue(arena_index, &arena)) result = GetLastError();
if (!result) {
RpcTryExcept {
if (trace) trace->stage = 60;
result = RmmW32TimeQueryStatus(binding, &status);
if (trace) {
trace->stage = 61; trace->native_rpc_return_present = 1;
trace->native_rpc_return = result;
}
if (!result) {
if (trace) {
trace->stage = 62; trace->status_present = status != NULL;
if (status) {
trace->ul_size = status->ulSize; trace->c_entries = status->cEntries;
trace->p_entries_present = status->pEntries != NULL;
}
}
if (!status || status->ulSize != sizeof(*status) || status->cEntries || status->pEntries) {
if (trace) trace->stage = 70;
result = RPC_X_BAD_STUB_DATA;
}
else {
if (trace) trace->stage = 80;
out->leap = status->eLeapIndicator; out->stratum = status->nStratum;
out->state = status->ulLcState; out->flags = status->ulTSFlags;
out->last_result = status->eLastSyncResult; out->size = status->ulSize;
out->last_sync = status->qwLastSyncTicks; out->sync_age = status->tpTimeLastGoodSync;
out->root_delay = status->toRootDelay; out->root_dispersion = status->tpRootDispersion;
out->phase = status->toSysPhaseOffset;
}
}
} RpcExcept(RpcExceptionFilter(RpcExceptionCode())) {
result = RpcExceptionCode();
if (eeinfo) capture_eeinfo(eeinfo); /* before any further RPC call */
if (trace) {trace->stage = 90; trace->rpc_exception = result;}
} RpcEndExcept
release_allocations(&arena);
TlsSetValue(arena_index, NULL);
}
return result;
}
static uint32_t pipe_query(RmmClockStatus *out, RmmClockTrace *trace, RmmClockEeInfo *eeinfo) {
RPC_WSTR text = NULL;
RPC_BINDING_HANDLE binding = NULL;
RPC_SECURITY_QOS qos = {0};
unsigned long result;
memset(out, 0, sizeof(*out));
if (trace) trace->stage = 10;
result = RpcStringBindingComposeW(NULL, (RPC_WSTR)L"ncacn_np", NULL,
(RPC_WSTR)L"\\pipe\\W32TIME_ALT", NULL, &text);
if (result) return result;
if (trace) trace->stage = 20;
result = RpcBindingFromStringBindingW(text, &binding);
RpcStringFreeW(&text);
if (result) return result;
qos.Version = RPC_C_SECURITY_QOS_VERSION;
qos.Capabilities = RPC_C_QOS_CAPABILITIES_DEFAULT;
qos.IdentityTracking = RPC_C_QOS_IDENTITY_STATIC;
qos.ImpersonationType = RPC_C_IMP_LEVEL_IDENTIFY;
if (trace) trace->stage = 30;
result = RpcBindingSetAuthInfoExW(binding, NULL, RPC_C_AUTHN_LEVEL_PKT_PRIVACY,
RPC_C_AUTHN_WINNT, NULL, RPC_C_AUTHZ_NONE, &qos);
if (!result) {
if (trace) trace->stage = 40;
result = RpcBindingSetOption(binding, RPC_C_OPT_CALL_TIMEOUT, 1500);
}
if (!result) result = invoke_status(binding, out, trace, eeinfo);
RpcBindingFree(&binding);
return result;
}
uint32_t rmm_clock_query(RmmClockStatus *out) { return pipe_query(out, NULL, NULL); }
uint32_t rmm_clock_query_trace(RmmClockTrace *trace) {
RmmClockStatus ignored = {0};
memset(trace, 0, sizeof(*trace));
return pipe_query(&ignored, trace, NULL);
}
/* Kernel-authenticated ALPC only. No automatic fallback to named pipes.
* The expected SID is fixed locally, never adopted from endpoint metadata.
*/
static uint32_t alpc_query(RmmClockStatus *out, unsigned control) {
RPC_IF_ID id = {0};
RPC_EP_INQ_HANDLE inquiry = NULL;
RPC_STATUS result;
memset(out, 0, sizeof(*out));
result = UuidFromStringW((RPC_WSTR)L"8fb6d884-2388-11d0-8c35-00c04fda2795", &id.Uuid);
if (result) return result;
id.VersMajor = 4; id.VersMinor = 1;
result = RpcMgmtEpEltInqBegin(NULL, RPC_C_EP_MATCH_BY_IF, &id, RPC_C_VERS_EXACT, NULL, &inquiry);
if (result) return result;
for (unsigned i=0; i<16; ++i) {
RPC_IF_ID actual = {0};
RPC_BINDING_HANDLE binding = NULL;
UUID object = {0};
RPC_WSTR annotation = NULL, text = NULL, protocol = NULL;
result = RpcMgmtEpEltInqNextW(inquiry, &actual, &binding, &object, &annotation);
if (annotation) RpcStringFreeW(&annotation);
if (result) break;
result = RpcBindingToStringBindingW(binding, &text);
if (!result) result = RpcStringBindingParseW(text, NULL, &protocol, NULL, NULL, NULL);
int local = !result && !wcscmp((wchar_t *)protocol, L"ncalrpc");
if (protocol) RpcStringFreeW(&protocol);
if (text) RpcStringFreeW(&text);
if (result) {RpcBindingFree(&binding);break;}
if (local) {
_Alignas(8) BYTE expected_sid[SECURITY_MAX_SID_SIZE];
_Alignas(8) BYTE service_sid[SECURITY_MAX_SID_SIZE];
_Alignas(8) BYTE acl_buffer[sizeof(ACL) + sizeof(ACCESS_ALLOWED_ACE) + SECURITY_MAX_SID_SIZE];
SECURITY_DESCRIPTOR descriptor;
WCHAR domain[64];
DWORD domain_size = sizeof(domain) / sizeof(domain[0]);
DWORD service_sid_size = sizeof(service_sid);
SID_NAME_USE sid_type;
DWORD sid_size = sizeof(expected_sid);
RmmRpcQosV5 qos = {0};
/* An account-only SID19 binding also accepts other LocalService
* processes, including our network agent. The client-owned V5
* descriptor therefore requires the separate W32Time service SID.
* No descriptor/identity is obtained from endpoint metadata.
* Controls are fixed read-only diagnostics, never production modes.
*/
if (!CreateWellKnownSid(control == 1 ? WinLocalSystemSid : WinLocalServiceSid,
NULL, expected_sid, &sid_size)) result = GetLastError();
if (!result && !LookupAccountNameW(NULL,
control == 2 ? L"NT SERVICE\\RmmDiscoveryWindows" : L"NT SERVICE\\W32Time",
service_sid, &service_sid_size, domain, &domain_size, &sid_type)) result = GetLastError();
if (!result && (!IsValidSid(service_sid) || service_sid_size > sizeof(service_sid))) result = ERROR_INVALID_SID;
if (!result && !InitializeAcl((PACL)acl_buffer, sizeof(acl_buffer), ACL_REVISION)) result = GetLastError();
if (!result && !AddAccessAllowedAce((PACL)acl_buffer, ACL_REVISION, GENERIC_ALL, service_sid)) result = GetLastError();
if (!result && !InitializeSecurityDescriptor(&descriptor, SECURITY_DESCRIPTOR_REVISION)) result = GetLastError();
if (!result && !SetSecurityDescriptorDacl(&descriptor, TRUE, (PACL)acl_buffer, FALSE)) result = GetLastError();
if (!result) {
qos.Version = 5; /* RPC_C_SECURITY_QOS_VERSION_5 */
qos.Capabilities = RPC_C_QOS_CAPABILITIES_MUTUAL_AUTH;
qos.IdentityTracking = RPC_C_QOS_IDENTITY_STATIC;
qos.ImpersonationType = RPC_C_IMP_LEVEL_IDENTIFY;
qos.Sid = expected_sid;
qos.EffectiveOnly = TRUE;
qos.ServerSecurityDescriptor = &descriptor;
result = RpcBindingSetAuthInfoExW(binding, NULL, RPC_C_AUTHN_LEVEL_PKT_PRIVACY,
RPC_C_AUTHN_WINNT, NULL, RPC_C_AUTHZ_NONE, (RPC_SECURITY_QOS *)&qos);
if (!result) result = invoke_status(binding, out, NULL, NULL);
}
RpcBindingFree(&binding);
break; /* no retry, alternate identity, endpoint or weaker transport */
}
RpcBindingFree(&binding);
result = EPT_S_NOT_REGISTERED;
}
RpcMgmtEpEltInqDone(&inquiry);
return result == RPC_X_NO_MORE_ENTRIES ? EPT_S_NOT_REGISTERED : result;
}
uint32_t rmm_clock_alpc_query(RmmClockStatus *out) { return alpc_query(out, 0); }
uint32_t rmm_clock_wrong_account(RmmClockStatus *out) { return alpc_query(out, 1); }
uint32_t rmm_clock_wrong_service(RmmClockStatus *out) { return alpc_query(out, 2); }
/* Exactly one original authenticated pipe query; EEInfo is observation only. */
uint32_t rmm_clock_query_trace_eeinfo(RmmClockTrace *trace, RmmClockEeInfo *eeinfo) {
RmmClockStatus ignored = {0};
memset(trace, 0, sizeof(*trace));
memset(eeinfo, 0, sizeof(*eeinfo));
return pipe_query(&ignored, trace, eeinfo);
}
+234
View File
@@ -0,0 +1,234 @@
#!/usr/bin/env python3
"""Parent-only native SYSTEM trace bootstrap: prepare, once start, read, cleanup.
Readback is strictly read-only. Cleanup is a separate explicit phase and may
remove only this exact stopped diagnostic service. Never changes W32Time/RMM.
"""
import argparse
import base64
import datetime as dt
import hashlib
import json
import os
from pathlib import Path
import re
import shlex
import stat
import subprocess
import sys
import uuid
ROOT = Path(__file__).resolve().parents[3]
HERE = Path(__file__).resolve().parent
STATE = ROOT / 'devstate/windows-clock-eeinfo-trace'
ACCESS_ROOT = Path('/home/kevin/Schreibtisch/Coding/rust-discovery')
def require(value,message):
if not value: raise RuntimeError(message)
def sha(path):
return hashlib.sha256(Path(path).read_bytes()).hexdigest()
def pairs(items):
result = {}
for name,value in items:
require(name not in result,'duplicate JSON key'); result[name] = value
return result
def private(path,directory=False):
item = Path(path).lstat()
require(item.st_uid == os.getuid() and stat.S_IMODE(item.st_mode) == (0o700 if directory else 0o600)
and (stat.S_ISDIR(item.st_mode) if directory else stat.S_ISREG(item.st_mode) and item.st_nlink == 1),'private owned path')
def load(path):
private(path); require(Path(path).stat().st_size <= 2*1024*1024,'bounded private JSON')
return json.loads(Path(path).read_bytes(),object_pairs_hook=pairs)
def save(path,value):
private(path.parent,True)
fd = os.open(path,os.O_CREAT|os.O_EXCL|os.O_WRONLY|os.O_NOFOLLOW,0o600)
with os.fdopen(fd,'w') as output:
json.dump(value,output,indent=2); output.flush(); os.fsync(output.fileno())
SCRIPT = r'''
$ErrorActionPreference='Stop';$p=([Console]::In.ReadLine()|ConvertFrom-Json)
$id=[guid]::ParseExact($p.id,'D').ToString()
if($id-cne$p.id-or$p.profile-cne'clock-system-eeinfo-v1'-or$p.action-notin@('prepare','start','readback','cleanup')-or$p.binary_sha256-notmatch'^[a-f0-9]{64}$'-or$p.manifest_sha256-notmatch'^[a-f0-9]{64}$'-or$p.script_sha256-notmatch'^[a-f0-9]{64}$'){throw 'Fixed SYSTEM diagnostic request'}
$root='C:\ProgramData\RustDiscoveryBootstrap';$name='RmmClockSystemEeInfoDiagnostic';$case=Join-Path $root ('clock-eeinfo-trace-'+$id);$exe=Join-Path $case 'ClockSystemEeInfoTrace.exe';$command='"'+$exe+'" --service '+$id
function Test-RmmTracePrivate($path,$dir){$i=Get-Item -LiteralPath $path -Force;if($i.PSIsContainer-ne$dir-or($i.Attributes-band[IO.FileAttributes]::ReparsePoint)){throw 'Private object type'};$a=Get-Acl -LiteralPath $path;if($a.GetOwner([Security.Principal.SecurityIdentifier]).Value-notin@('S-1-5-18','S-1-5-32-544')){throw 'Private object owner'};$rules=@($a.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier]));if(!$rules.Count){throw 'Empty private ACL'};foreach($e in $rules){if($e.AccessControlType-ne'Allow'-or$e.IdentityReference.Value-notin@('S-1-5-18','S-1-5-32-544')-or($e.PropagationFlags-band[Security.AccessControl.PropagationFlags]::InheritOnly)){throw 'Broad private ACL'}}}
function Write-RmmTraceNew($path,$value){$f=[IO.File]::Open($path,[IO.FileMode]::CreateNew,[IO.FileAccess]::Write,[IO.FileShare]::Read);try{$b=[Text.Encoding]::UTF8.GetBytes(($value|ConvertTo-Json -Depth 12 -Compress));$f.Write($b,0,$b.Length);$f.Flush($true)}finally{$f.Dispose()}}
function Get-RmmTraceJson($path){Test-RmmTracePrivate $path $false;if((Get-Item -LiteralPath $path).Length-gt16384){throw 'Small diagnostic receipt'};return(Get-Content -LiteralPath $path -Raw|ConvertFrom-Json)}
function Get-RmmTraceService{return(Get-CimInstance Win32_Service -Filter "Name='RmmClockSystemEeInfoDiagnostic'" -OperationTimeoutSec 5)}
function Test-RmmTraceService($s){if($s-and($s.PathName-cne$command-or$s.StartName-cne'LocalSystem'-or$s.StartMode-cne'Manual')){throw 'Only own exact temporary service'}}
if($p.action-eq'readback'-and!(Test-Path -LiteralPath $case)){@{id=$id;status='remote_case_absent';read_only=$true}|ConvertTo-Json -Compress;exit 0}
Test-RmmTracePrivate $root $true
if($p.action-eq'prepare'){if((Test-Path -LiteralPath $case)-or(Get-RmmTraceService)){throw 'Existing case/service retained'};New-Item -ItemType Directory -Path $case|Out-Null;Test-RmmTracePrivate $case $true;Write-RmmTraceNew (Join-Path $case 'intent.json') $p;@{id=$id;prepared=$true}|ConvertTo-Json -Compress;exit 0}
Test-RmmTracePrivate $case $true;$old=Get-RmmTraceJson (Join-Path $case 'intent.json')
foreach($field in @('id','profile','binary_sha256','manifest_sha256','script_sha256','binary_bytes')){if($old.$field-cne$p.$field){throw 'Original exact diagnostic intent'}}
Test-RmmTracePrivate $exe $false;if((Get-Item -LiteralPath $exe).Length-ne$p.binary_bytes-or(Get-FileHash -LiteralPath $exe -Algorithm SHA256).Hash.ToLowerInvariant()-cne$p.binary_sha256){throw 'Exact diagnostic executable'}
$s=Get-RmmTraceService;Test-RmmTraceService $s
if($p.action-eq'start'){
if($s-or(Test-Path -LiteralPath (Join-Path $case 'start-intent.json'))){throw 'No repeated start; original readback only'}
Write-RmmTraceNew (Join-Path $case 'start-intent.json') @{id=$id;command=$command;binary_sha256=$p.binary_sha256;create_once=$true}
New-Service -Name $name -BinaryPathName $command -StartupType Manual|Out-Null
$s=Get-RmmTraceService;Test-RmmTraceService $s;if(!$s){throw 'Own service creation missing'}
Write-RmmTraceNew (Join-Path $case 'service-created.json') @{id=$id;command=$command;start_name=$s.StartName}
Write-RmmTraceNew (Join-Path $case 'service-start-intent.json') @{start_once=$true}
Start-Service -Name $name
$deadline=[DateTime]::UtcNow.AddSeconds(20)
do{$s=Get-RmmTraceService;Test-RmmTraceService $s;if(!$s-or$s.State-eq'Stopped'){break};Start-Sleep -Milliseconds 100}while([DateTime]::UtcNow-lt$deadline)
}
if($p.action-eq'cleanup'){
if(!$s){if(!(Test-Path -LiteralPath (Join-Path $case 'cleanup-intent.json'))){throw 'Missing service without bound cleanup'};@{id=$id;cleanup_verified=$true;already_absent=$true;read_only=$true}|ConvertTo-Json -Compress;exit 0}
if($s.State-cne'Stopped'){throw 'Cleanup only own bound stopped service'}
$created=Get-RmmTraceJson (Join-Path $case 'service-created.json');if($created.id-cne$id-or$created.command-cne$command-or$created.start_name-cne'LocalSystem'){throw 'Original service creation binding'}
if(Test-Path -LiteralPath (Join-Path $case 'cleanup-intent.json')){throw 'Cleanup already attempted; readback only'}
Write-RmmTraceNew (Join-Path $case 'cleanup-intent.json') @{id=$id;command=$command;delete_once=$true}
& "$env:WINDIR\System32\sc.exe" delete $name|Out-Null;if($LASTEXITCODE-ne0){throw 'Own stopped service deletion incomplete'}
if(Get-RmmTraceService){throw 'Own service still registered; readback only'}
Write-RmmTraceNew (Join-Path $case 'cleanup-completed.json') @{id=$id;service_absent=$true}
@{id=$id;cleanup_verified=$true;already_absent=$false;read_only=$false}|ConvertTo-Json -Compress;exit 0
}
$report=$null;$result=Join-Path $case 'result.json';if(Test-Path -LiteralPath $result){$report=Get-RmmTraceJson $result}
$cleaned=$false;$cleanupReceipt=Join-Path $case 'cleanup-completed.json';if(Test-Path -LiteralPath $cleanupReceipt){$c=Get-RmmTraceJson $cleanupReceipt;if($c.id-cne$id-or$c.service_absent-ne$true){throw 'Bound cleanup receipt'};$cleaned=$true}
@{id=$id;service_present=[bool]$s;service_state=$(if($s){$s.State}else{$null});service_exit_code=$(if($s){$s.ExitCode}else{$null});start_intent_present=(Test-Path -LiteralPath (Join-Path $case 'service-start-intent.json'));cleanup_intent_present=(Test-Path -LiteralPath (Join-Path $case 'cleanup-intent.json'));cleanup_completed=$cleaned;report=$report;read_only=($p.action-eq'readback');no_rmm_jobs=$true;no_w32time_change=$true;no_agent_change=$true}|ConvertTo-Json -Depth 12 -Compress
'''
def encoded_command():
script = 'try {\n'+SCRIPT+'\n} catch {[pscustomobject]@{bootstrap_error=$true;error_id=$_.FullyQualifiedErrorId;line=$_.InvocationInfo.ScriptLineNumber}|ConvertTo-Json -Compress;exit 1}'
return 'powershell.exe -NoLogo -NoProfile -NonInteractive -EncodedCommand '+base64.b64encode(script.encode('utf-16le')).decode()
def manifest(path):
path = path.absolute(); private(path.parent,True)
require(path.name == 'manifest.json' and path.parent.parent == STATE and re.fullmatch(r'build-[0-9a-f-]{36}',path.parent.name),'fixed local build manifest')
value = load(path)
require(value['profile'] == 'clock-system-eeinfo-v1' and value['schema_version'] == 1
and value['native_executed'] is False and value['clock_qualified'] is False and value['product_gate_open'] is False
and value['powershell_ast_passed'] is True and value['encoded_command_characters'] == len(encoded_command()) < 32767
and value['script_sha256'] == hashlib.sha256(SCRIPT.encode()).hexdigest(),'same reviewed nonqualifying diagnostic source')
require(value['original_wrapper_sha256'] == '74aceb6e2b70c5dd628fae069a842c356c20300b8c8ab12754258c78eaf295c8'
and sha(path.parent / 'wrapper-source.diff') == value['wrapper_diff_sha256'],'same exact observational source delta')
for name,digest in value['own_sources'].items():require(sha(ROOT / name) == digest,'same original local driver source')
for name in ('artifact','linked'):
item=value[name];p=Path(item['path']);require(p.parent == path.parent / 'output','fixed retained PE path');private(p);require(sha(p) == item['sha256'],'retained exact diagnostic PE')
require(Path(value['artifact']['path']).stat().st_size == value['artifact']['bytes'],'exact PE size')
return value
def access(root):
require(root == ACCESS_ROOT and root.resolve() == root,'existing Main access root only')
sys.path.insert(0,str(ROOT / 'deploy'))
import vm_access_check
config = vm_access_check.load_config(root / 'credentials/server.conf')
require(config['address'] == '88.99.80.202' and config['username'] == 'root' and config.get('port','22') == '22','fixed existing cloud reverse jump')
record=load(root / 'credentials/windows-dev-access.json');expiry=dt.datetime.fromisoformat(record['expires_at'])
require(expiry.utcoffset() is not None and dt.datetime.now(dt.timezone.utc) < expiry,'current existing access only')
private(root / 'credentials',True);private(root / 'credentials/windows-dev.known_hosts')
key=str(Path(config['ssh_key_path']).expanduser())
jump=['ssh','-F','/dev/null','-T','-p','22','-i',key,'-o','StrictHostKeyChecking=yes','-o','BatchMode=yes','-o','ForwardAgent=no','-o','IdentitiesOnly=yes','-W','127.0.0.1:22240','root@88.99.80.202']
prefix=['ssh','-F','/dev/null','-T','-i',key,'-o','ProxyCommand='+shlex.join(jump),'-o','HostKeyAlias=rmm-windows-dev','-o','UserKnownHostsFile='+str(root / 'credentials/windows-dev.known_hosts'),'-o','GlobalKnownHostsFile=/dev/null','-o','StrictHostKeyChecking=yes','-o','BatchMode=yes','-o','IdentitiesOnly=yes','-o','ForwardAgent=no','-o','ConnectTimeout=10','rmm-dev@127.0.0.1']
require(record['ssh_prefix'] == prefix,'original pinned transport only')
return prefix
def run_transport(args,data,folder):
try:
done=subprocess.run(args,input=data,capture_output=True,timeout=50)
save(folder / ('transport-'+str(uuid.uuid4())+'.json'),dict(returncode=done.returncode,stdout_b64=base64.b64encode(done.stdout).decode(),stderr_b64=base64.b64encode(done.stderr).decode()))
require(done.returncode == 0,'transport incomplete; original readback only')
return done.stdout
except subprocess.TimeoutExpired as error:
save(folder / ('transport-timeout-'+str(uuid.uuid4())+'.json'),dict(timed_out=True,stdout_b64=base64.b64encode(error.stdout or b'').decode(),stderr_b64=base64.b64encode(error.stderr or b'').decode()))
raise RuntimeError('lost reply; no repeated operation') from None
def rpc(prefix,payload,folder):
value=json.loads(run_transport(prefix+[encoded_command()],(json.dumps(payload)+'\n').encode(),folder).decode('utf-8-sig'),object_pairs_hook=pairs)
require(isinstance(value,dict) and 'bootstrap_error' not in value,'remote diagnostic incomplete')
return value
def check_report(value,ident):
require(value['id'] == ident and value['no_rmm_jobs'] is True and value['no_w32time_change'] is True and value['no_agent_change'] is True,'exact nonproduct diagnostic case')
report=value.get('report')
if report is None:return False
require(report['schema_version'] == 1 and report['profile'] == 'clock-system-eeinfo-v1' and report['case_id'] == ident
and report['token_system'] is True and report['read_only'] is True and report['diagnostic_only'] is True
and report['query_invocations'] == 1 and report['clock_qualified'] is False and report['adapter_qualified'] is False
and report['product_gate_open'] is False,'actual SYSTEM token and single nonqualifying trace')
fields={'stage','native_rpc_return','native_rpc_return_present','rpc_exception','status_present','ul_size','c_entries','p_entries_present'}
require(set(report['trace']) == fields and type(report['rpc_code']) is int and 0 <= report['rpc_code'] < 2**32
and all(type(n) is int and 0 <= n < 2**32 for n in report['trace'].values()),'bounded numeric trace only')
ee=report['eeinfo']
require(set(ee) == {'capture_attempted','start_status','next_status','end_status','count','limit_reached','records'}
and all(type(ee[k]) is int and 0 <= ee[k] < 2**32 for k in ('capture_attempted','start_status','next_status','end_status','count','limit_reached'))
and ee['capture_attempted'] in (0,1) and 0 <= ee['count'] <= 4 and len(ee['records']) == ee['count']
and ee['limit_reached'] == int(ee['count'] == 4),'four-record numeric EEInfo budget')
record_fields={'generating_component','status','detection_location','flags','number_of_parameters'}
for record in ee['records']:
require(set(record) == record_fields and all(type(n) is int and 0 <= n < 2**32 for n in record.values())
and record['number_of_parameters'] <= 4,'numeric EEInfo fields only; no parameter contents')
if report['trace']['stage'] == 90:require(ee['capture_attempted'] == 1 and report['rpc_code'] == report['trace']['rpc_exception'],'original exception code preserved before immediate capture')
return (value['service_state'] == 'Stopped' and value['service_exit_code'] == 0) or (value['service_present'] is False and value['cleanup_completed'] is True)
def execute(action,path,root,ident):
os.umask(0o077);STATE.mkdir(mode=0o700,exist_ok=True);private(STATE,True)
value=manifest(path);prefix=access(root)
if action == 'prepare':
require(not ident,'new diagnostic case only');ident=str(uuid.uuid4());folder=STATE / ident;folder.mkdir(mode=0o700)
payload=dict(id=ident,profile='clock-system-eeinfo-v1',manifest_sha256=sha(path),binary_sha256=value['artifact']['sha256'],binary_bytes=value['artifact']['bytes'],script_sha256=value['script_sha256'])
save(folder / 'intent.json',dict(payload=payload,manifest_path=str(path.absolute()),access_root=str(root)))
print(json.dumps(dict(case_id=ident,prepare_once=True)),flush=True)
prepared=rpc(prefix,dict(payload,action='prepare'),folder);save(folder / 'prepared-remote.json',prepared);require(prepared == dict(id=ident,prepared=True),'new private remote case')
save(folder / 'upload-intent.json',dict(binary_sha256=payload['binary_sha256'],upload_once=True))
args=['sftp']+[p for p in prefix[1:-1] if p != '-T']+['-b','-',prefix[-1]]
destination='/C:/ProgramData/RustDiscoveryBootstrap/clock-eeinfo-trace-'+ident+'/ClockSystemEeInfoTrace.exe'
run_transport(args,('put '+json.dumps(value['artifact']['path'])+' '+json.dumps(destination)+'\n').encode(),folder)
save(folder / 'upload-completed.json',dict(uploaded=True));print(json.dumps(dict(case_id=ident,prepared=True,service_started=False)));return
require(str(uuid.UUID(ident)) == ident,'canonical original case')
folder=STATE / ident;private(folder,True);original=load(folder / 'intent.json');payload=original['payload']
require(original['manifest_path'] == str(path.absolute()) and original['access_root'] == str(root)
and payload['manifest_sha256'] == sha(path) and payload['script_sha256'] == value['script_sha256'],'original same-case input tuple')
if action in ('start','cleanup'):
if action == 'start':require(load(folder / 'upload-completed.json')['uploaded'] is True,'completed original upload')
save(folder / (action+'-intent.json'),dict(action=action,once=True))
result=rpc(prefix,dict(payload,action=action),folder);save(folder / ('readback-'+str(uuid.uuid4())+'.json'),result)
if action == 'cleanup':
require(result.get('id') == ident and result.get('cleanup_verified') is True,'own stopped service cleanup only')
print(json.dumps(dict(case_id=ident,cleanup_verified=True)));return
if result.get('status'):
require(action == 'readback' and result['status'] == 'remote_case_absent','read-only original partial status')
print(json.dumps(dict(case_id=ident,complete=False,retry_allowed=False)));return
complete=check_report(result,ident)
if complete:
destination=folder / 'diagnostic-result.json'
receipt=dict(complete=True,manifest_sha256=sha(path),actual=result,clock_qualified=False,product_gate_open=False)
if destination.exists():require(load(destination)['actual']['report'] == result['report'],'preserve original numeric report')
else:save(destination,receipt)
print(json.dumps(dict(case_id=ident,diagnostic_complete=complete,rpc_code=result['report']['rpc_code'] if complete else None,
stage=result['report']['trace']['stage'] if complete else None,eeinfo_count=result['report']['eeinfo']['count'] if complete else None,clock_qualified=False,cleanup_separate=True)))
def main():
parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('action',choices=('prepare','start','readback','cleanup'))
parser.add_argument('--manifest',type=Path,required=True);parser.add_argument('--access-root',type=Path,required=True);parser.add_argument('--id')
parser.add_argument('--execute-native',action='store_true');args=parser.parse_args()
require((args.action == 'readback' and not args.execute_native) or (args.action != 'readback' and args.execute_native),'explicit native effect phase; readback only reads')
execute(args.action,args.manifest,args.access_root,args.id)
if __name__ == '__main__':
try:main()
except Exception as error:
print(json.dumps(dict(error='CLOCK_SYSTEM_TRACE_NATIVE_INCOMPLETE',error_class=type(error).__name__,details_suppressed=True)))
raise SystemExit(2) from None
@@ -0,0 +1,135 @@
/* Standalone diagnostic only. The original C/Auth/MIDL inputs are linked
* unchanged. Exactly one trace query, only under this process's SYSTEM token.
* No clock setter, token impersonation, NTP/ACL/provider or product gate. */
#define _WIN32_WINNT 0x0a00
#include <windows.h>
#include <stdint.h>
#include <stdio.h>
#include <wchar.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");
uint32_t rmm_clock_query_trace_eeinfo(RmmClockTrace *trace, RmmClockEeInfo *eeinfo);
static WCHAR service_name[] = L"RmmClockSystemEeInfoDiagnostic";
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(void) {
HANDLE token = NULL;
DWORD needed = 0, result = ERROR_SUCCESS;
_Alignas(8) BYTE storage[4096];
if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &token)) return GetLastError();
if (!GetTokenInformation(token, TokenUser, storage, sizeof(storage), &needed)) result = GetLastError();
else if (needed > sizeof(storage) || !IsWellKnownSid(((TOKEN_USER *)storage)->User.Sid, WinLocalSystemSid)) result = ERROR_ACCESS_DENIED;
CloseHandle(token);
return result;
}
static DWORD write_result(uint32_t rpc, const RmmClockTrace *trace, const RmmClockEeInfo *eeinfo) {
WCHAR path[256];
char id[37], report[4096];
DWORD written = 0, result = ERROR_SUCCESS;
for (unsigned i = 0; i < 37; ++i) id[i] = (char)case_id[i];
int count = swprintf(path, sizeof(path) / sizeof(path[0]),
L"C:\\ProgramData\\RustDiscoveryBootstrap\\clock-eeinfo-trace-%ls\\result.json", case_id);
if (count <= 0 || count >= (int)(sizeof(path) / sizeof(path[0]))) return ERROR_INVALID_PARAMETER;
count = snprintf(report, sizeof(report),
"{\"schema_version\":1,\"profile\":\"clock-system-eeinfo-v1\",\"case_id\":\"%s\","
"\"token_system\":true,\"read_only\":true,\"diagnostic_only\":true,\"query_invocations\":1,"
"\"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, (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, "]}}\n");
if (appended <= 0 || (size_t)appended >= sizeof(report) - used) return ERROR_BUFFER_OVERFLOW;
used += (size_t)appended;
count = (int)used;
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, report, (DWORD)count, &written, NULL) || written != (DWORD)count) result = ERROR_WRITE_FAULT;
else if (!FlushFileBuffers(file)) result = GetLastError();
CloseHandle(file);
return result;
}
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;
DWORD result = own_system_token();
if (!result) {
RmmClockTrace trace = {0};
RmmClockEeInfo eeinfo = {0};
uint32_t rpc = rmm_clock_query_trace_eeinfo(&trace, &eeinfo); /* exactly one fixed call */
result = write_result(rpc, &trace, &eeinfo);
}
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;
}