Prove native Windows time RPC with explicit local impersonation level
Rust development slice / linux (push) Failing after 6s
Rust development slice / linux (push) Failing after 6s
This commit is contained in:
@@ -0,0 +1,176 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Local-only isolated process privilege comparison; never starts a target."""
|
||||
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-spnego-impersonate-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'
|
||||
PARENT_MANIFEST = ROOT / 'devstate/windows-clock-spnego-privilege-trace/build-b56e3f3d-8904-4fd8-9c34-0e55e57c8f07/manifest.json'
|
||||
PARENT_SHA = '6c97658307ec66e6605574dca27cdbc79efefa9cd7f386e6e2cb3f73d9b5c6d3'
|
||||
PARENT_RESULT = ROOT / 'devstate/windows-clock-spnego-privilege-trace/6de04277-6bec-477d-b1c9-bfca88a9cd78/diagnostic-result.json'
|
||||
PARENT_RESULT_SHA = 'c7556589a015fc5ab53feffe3caf74a3904b7f5a65b70066f256cc0693ff8152'
|
||||
UNCHANGED_DIAGNOSTICS = {
|
||||
'deploy/windows/clock-spnego-privilege-trace/clock_rpc_spnego_privilege.c': '0cdffb2a881caf770b73ba32310305f2a4bfd1bdf8fc9e4a4544448bf0c7b7ac',
|
||||
'deploy/windows/clock-spnego-privilege-trace/system_trace_spnego_privilege.c': '392f7b9f8d8eec78d6d2645d5a47db1a5e8e739259e4205c01399c176b94a19e',
|
||||
'deploy/windows/clock-spnego-privilege-trace/build.py': '7977e67a3a4ae550a5ddc3e2435bef9506a97424719c5825364a35d558dfda48',
|
||||
'deploy/windows/clock-spnego-privilege-trace/native.py': '74d1740b921d7f1f20b0c78dfaa3cd5b8d9eb19eacb6bc31403d7b1dd4018ab1',
|
||||
'deploy/windows/clock-spnego-empty-trace/clock_rpc_spnego_empty.c': '9d9b5d247e9fc1570a72ced2f02373582c1aed7896e2f4bf8e7e85709a287dc5',
|
||||
'deploy/windows/clock-spnego-empty-trace/system_trace_spnego_empty.c': 'b8ce7b360e264e35781831e58a4a3278f7b35e44f07600e832d5d4ba82e8b986',
|
||||
'deploy/windows/clock-spnego-empty-trace/build.py': 'f72b50ad6977f491b32723ef9249569e6179e3072445392689a7a0bdf29c7f64',
|
||||
'deploy/windows/clock-spnego-empty-trace/native.py': '557cf3900ed16236376a26d24e863972e38d0ac7b34d3feb4329bc7d5bc7bc01',
|
||||
'deploy/windows/clock-system-trace/system_trace.c': '5be92130fda4dbb2a0078861f2b4ebd70bc3b7ecc3a65af0b426702cb69b772a',
|
||||
'deploy/windows/clock-system-trace/build.py': 'e66ef17ba8a442f594114e3fa8eec62c256f0a9b1d9ca0d4e5c821675e00f05f',
|
||||
'deploy/windows/clock-system-trace/native.py': 'fd46fc5167ac85808a4483f76e774e5e05e0d79f4a01def611a0c0b91414714e',
|
||||
'deploy/windows/clock-eeinfo-trace/clock_rpc_eeinfo.c': '2bf009c3118af34ae7945c7d67b4647f0b24a9db34fbeeb4b44299e69f7e9a68',
|
||||
'deploy/windows/clock-eeinfo-trace/system_trace_eeinfo.c': '09628d345592c767ebe136e40108e283e96bc37f749c5db93e62e327cb890301',
|
||||
'deploy/windows/clock-eeinfo-trace/build.py': '59a0c3f881b824d921d165ace4da1e5992b85ddbf9d1d5132404b588dd50f36c',
|
||||
'deploy/windows/clock-eeinfo-trace/native.py': 'cc71c230d4e6e30831eefd20de3d80848732e74d0ce077d79db29c3a1db33e8f',
|
||||
'deploy/windows/clock-spnego-trace/clock_rpc_spnego.c': '10882bb39d7f27cc7e42123f2d2d4b2dbfb7a4cf86ed5bc80767c5fba1a33147',
|
||||
'deploy/windows/clock-spnego-trace/system_trace_spnego.c': '74f96e1e3d55799c3b599abf81ad5e66e436b9fcbd3b7125d87fe102d303812c',
|
||||
'deploy/windows/clock-spnego-trace/build.py': 'b10cdc0ba340d9b209e40a22391606f763aed01669e0356322f817eca6f08e0c',
|
||||
'deploy/windows/clock-spnego-trace/native.py': 'b85773f8c65d99aa59ec7318a2edca38d205ad3da394f645220f63ba1914bfd0',
|
||||
}
|
||||
|
||||
|
||||
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(ROOT/'devstate/windows-clock-spnego-trace/build-2ebcfe9c-1e2b-4a50-99c5-3370640aeb77/manifest.json')=='f6b5cd23b1599c2db4fc803fd7232dfd3522dead840e492f659e4efd7a6be001', 'original F6 manifest retained')
|
||||
require(sha(ROOT/'devstate/windows-clock-spnego-trace/0f512772-3599-4c83-b877-41c74fe50fb0/diagnostic-result.json')=='4c99b34b8c64f877dbbf0fe860d59499f1c054de7d036016e80b84581448cfc9', 'original F6 result retained')
|
||||
require(sha(PARENT_MANIFEST) == PARENT_SHA and sha(PARENT_RESULT) == PARENT_RESULT_SHA, 'original enabled-privilege RPC5 case retained')
|
||||
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')
|
||||
require(all(sha(ROOT/name)==digest for name,digest in UNCHANGED_DIAGNOSTICS.items()),'existing SYSTEM/WINNT/EEInfo diagnostic sources unchanged')
|
||||
return value
|
||||
|
||||
|
||||
def own_sources():
|
||||
return {str((HERE / name).relative_to(ROOT)):sha(HERE / name) for name in ('clock_rpc_spnego_impersonate.c','system_trace_spnego_impersonate.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_spnego_impersonate.c'
|
||||
write(source / 'clock_rpc.c', wrapper.read_bytes()); write(source / 'system_trace.c', (HERE / 'system_trace_spnego_impersonate.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_spnego_impersonate.c'))
|
||||
write(folder / 'wrapper-source.diff',delta.encode())
|
||||
parent_wrapper = ROOT / 'deploy/windows/clock-spnego-privilege-trace/clock_rpc_spnego_privilege.c'
|
||||
parent_delta = ''.join(difflib.unified_diff(parent_wrapper.read_text().splitlines(True), wrapper.read_text().splitlines(True),
|
||||
fromfile='unchanged-parent-spnego.c', tofile='new-spnego-impersonate.c'))
|
||||
write(folder / 'parent-wrapper-source.diff', parent_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'), unchanged_diagnostics=UNCHANGED_DIAGNOSTICS,
|
||||
parent_manifest_sha256=PARENT_SHA,parent_result_sha256=PARENT_RESULT_SHA,parent_wrapper_diff_sha256=sha(folder / 'parent-wrapper-source.diff'),
|
||||
own_system_token_only=True,token_query_only=False,own_token_privilege_adjustment=True,peer_token_query_only=True,max_enables=1,max_restores=1,max_principal_discoveries=1,max_status_queries=1,principal_identity_proven=False,returned_empty_principal_allowed=True,null_principal_allowed=False,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/ClockSpnegoImpersonateTrace.linked.exe'])
|
||||
raw_linked = output / 'ClockSpnegoImpersonateTrace.linked.exe'
|
||||
linked = output / 'ClockSpnegoImpersonateTrace.original.exe'; delivery = output / 'ClockSpnegoImpersonateTrace.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/ClockSpnegoImpersonateTrace.exe'])
|
||||
imports = sorted(set(re.findall(r'DLL Name:\s+(\S+)',run('imports',['x86_64-w64-mingw32-objdump','-p','/out/ClockSpnegoImpersonateTrace.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')
|
||||
require(imports == json.loads(PARENT_MANIFEST.read_bytes())['artifact']['imports'], 'same DLL imports as exact Empty comparison')
|
||||
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-spnego-impersonate-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,unchanged_diagnostics=UNCHANGED_DIAGNOSTICS,token_query_only=False,own_token_privilege_adjustment=True,peer_token_query_only=True,max_enables=1,max_restores=1,max_principal_discoveries=1,max_status_queries=1,principal_identity_proven=False,
|
||||
parent_manifest_sha256=PARENT_SHA,parent_result_sha256=PARENT_RESULT_SHA,parent_wrapper_diff_sha256=sha(folder / 'parent-wrapper-source.diff'),returned_empty_principal_allowed=True,null_principal_allowed=False,
|
||||
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,259 @@
|
||||
/* Isolated diagnostic variant: discover SPNEGO principal on the fixed local
|
||||
* authenticated endpoint, then at most one MS-W32T Opnum6. No fallback/trust.
|
||||
* Actual Microsoft-generated MIDL is reused. SEH stays entirely inside C.
|
||||
*/
|
||||
#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);
|
||||
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);
|
||||
}
|
||||
|
||||
/* Numeric protocol-path observations, never a server-identity assertion. */
|
||||
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, "numeric SPNEGO path ABI");
|
||||
|
||||
static uint32_t check_principal(RPC_WSTR value, RmmClockAuthTrace *auth) {
|
||||
if (!value) return ERROR_INVALID_DATA;
|
||||
auth->principal_present = 1;
|
||||
int high = 0;
|
||||
for (unsigned i = 0; i <= 512; ++i) {
|
||||
unsigned unit = value[i];
|
||||
if (!unit) {
|
||||
auth->principal_units = i;
|
||||
/* Preserve a returned non-NULL empty string; the SSP decides its meaning. */
|
||||
if (high) return ERROR_INVALID_NAME;
|
||||
auth->principal_validated = 1;
|
||||
return ERROR_SUCCESS;
|
||||
}
|
||||
if (i == 512 || unit < 0x20 || (unit >= 0x7f && unit <= 0x9f)) return ERROR_INVALID_NAME;
|
||||
if (high) {
|
||||
if (unit < 0xdc00 || unit > 0xdfff) return ERROR_INVALID_NAME;
|
||||
high = 0;
|
||||
} else if (unit >= 0xd800 && unit <= 0xdbff) high = 1;
|
||||
else if (unit >= 0xdc00 && unit <= 0xdfff) return ERROR_INVALID_NAME;
|
||||
}
|
||||
return ERROR_INVALID_NAME;
|
||||
}
|
||||
|
||||
static uint32_t invoke_status(RPC_BINDING_HANDLE binding, RmmClockStatus *out, RmmClockTrace *trace, RmmClockEeInfo *eeinfo, RmmClockAuthTrace *auth) {
|
||||
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;
|
||||
auth->status_query_invocations = 1;
|
||||
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, RmmClockAuthTrace *auth) {
|
||||
RPC_WSTR text = NULL;
|
||||
RPC_BINDING_HANDLE binding = NULL;
|
||||
RPC_WSTR principal = NULL;
|
||||
RPC_SECURITY_QOS qos = {0};
|
||||
unsigned long result;
|
||||
memset(out, 0, sizeof(*out));
|
||||
memset(auth, 0, sizeof(*auth));
|
||||
auth->authn_service = RPC_C_AUTHN_GSS_NEGOTIATE;
|
||||
auth->authn_level = RPC_C_AUTHN_LEVEL_PKT_PRIVACY;
|
||||
auth->impersonation_type = RPC_C_IMP_LEVEL_IMPERSONATE;
|
||||
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;
|
||||
/* Bound the management discovery as well as Opnum6. RpcMgmt allocates its
|
||||
* returned string internally: the 512-unit check bounds inspection/use,
|
||||
* not RPC runtime allocations made before the API returns. */
|
||||
if (trace) trace->stage = 40;
|
||||
result = RpcBindingSetOption(binding, RPC_C_OPT_CALL_TIMEOUT, 1500);
|
||||
if (!result) {
|
||||
if (trace) trace->stage = 25;
|
||||
RpcTryExcept {
|
||||
auth->discovery_invocations = 1;
|
||||
result = RpcMgmtInqServerPrincNameW(binding, RPC_C_AUTHN_GSS_NEGOTIATE, &principal);
|
||||
auth->discovery_return_present = 1;
|
||||
auth->discovery_status = result;
|
||||
if (result && eeinfo) {auth->eeinfo_origin = 1; capture_eeinfo(eeinfo);}
|
||||
} RpcExcept(RpcExceptionFilter(RpcExceptionCode())) {
|
||||
result = RpcExceptionCode();
|
||||
auth->discovery_status = result;
|
||||
if (eeinfo) {auth->eeinfo_origin = 1; capture_eeinfo(eeinfo);}
|
||||
if (trace) {trace->stage = 91; trace->rpc_exception = result;}
|
||||
} RpcEndExcept
|
||||
}
|
||||
if (!result) {
|
||||
if (trace) trace->stage = 26;
|
||||
result = check_principal(principal, auth);
|
||||
}
|
||||
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_IMPERSONATE;
|
||||
if (!result) {
|
||||
if (trace) trace->stage = 30;
|
||||
/* The returned principal is ONLY a diagnostic authentication input,
|
||||
* never an independently trusted service/account/SID assertion. */
|
||||
result = RpcBindingSetAuthInfoExW(binding, principal, RPC_C_AUTHN_LEVEL_PKT_PRIVACY,
|
||||
RPC_C_AUTHN_GSS_NEGOTIATE, NULL, RPC_C_AUTHZ_NONE, &qos);
|
||||
if (result && eeinfo) {auth->eeinfo_origin = 3; capture_eeinfo(eeinfo);}
|
||||
}
|
||||
if (!result) {
|
||||
result = invoke_status(binding, out, trace, eeinfo, auth);
|
||||
if (eeinfo && eeinfo->capture_attempted) auth->eeinfo_origin = 2;
|
||||
}
|
||||
/* Preserve the original discovery/auth/query result before cleanup RPC. */
|
||||
if (principal) {
|
||||
auth->principal_free_attempted = 1;
|
||||
auth->principal_free_status = RpcStringFreeW(&principal);
|
||||
}
|
||||
auth->binding_free_attempted = 1;
|
||||
auth->binding_free_status = RpcBindingFree(&binding);
|
||||
return result;
|
||||
}
|
||||
/* At most one authenticated status query after exactly one discovery. */
|
||||
uint32_t rmm_clock_query_trace_spnego_impersonate(RmmClockTrace *trace, RmmClockEeInfo *eeinfo, RmmClockAuthTrace *auth) {
|
||||
RmmClockStatus ignored = {0};
|
||||
memset(trace, 0, sizeof(*trace));
|
||||
memset(eeinfo, 0, sizeof(*eeinfo));
|
||||
return pipe_query(&ignored, trace, eeinfo, auth);
|
||||
}
|
||||
@@ -0,0 +1,345 @@
|
||||
#!/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-spnego-impersonate-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-spnego-impersonate-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='RmmClockSpnegoImpersonateDiagnostic';$case=Join-Path $root ('clock-spnego-impersonate-trace-'+$id);$exe=Join-Path $case 'ClockSpnegoImpersonateTrace.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-gt262144){throw 'Small diagnostic receipt'};return(Get-Content -LiteralPath $path -Raw|ConvertFrom-Json)}
|
||||
function Get-RmmTraceService{return(Get-CimInstance Win32_Service -Filter "Name='RmmClockSpnegoImpersonateDiagnostic'" -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;service_exit_code=$s.ExitCode}
|
||||
@{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}
|
||||
$token=$null;$tokenFile=Join-Path $case 'token.json';if(Test-Path -LiteralPath $tokenFile){$token=Get-RmmTraceJson $tokenFile}
|
||||
$before=$null;$beforeFile=Join-Path $case 'privilege-before.json';if(Test-Path -LiteralPath $beforeFile){$before=Get-RmmTraceJson $beforeFile}
|
||||
$adjust=$null;$adjustFile=Join-Path $case 'privilege-adjustment.json';if(Test-Path -LiteralPath $adjustFile){$adjust=Get-RmmTraceJson $adjustFile}
|
||||
$cleaned=$false;$cleanedExit=$null;$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-or$null-eq$c.service_exit_code-or$c.service_exit_code-lt0-or$c.service_exit_code-gt4294967295){throw 'Bound cleanup receipt'};$cleaned=$true;$cleanedExit=$c.service_exit_code}
|
||||
@{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;cleaned_service_exit_code=$cleanedExit;report=$report;token_before_rpc=$token;privilege_before=$before;privilege_adjustment=$adjust;read_only=($p.action-eq'readback');no_rmm_jobs=$true;no_w32time_change=$true;no_agent_change=$true;own_privilege_adjustment=$true;foreign_token_query_only=$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-spnego-impersonate-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')
|
||||
require(value['token_query_only'] is False and value['own_token_privilege_adjustment'] is True and value['peer_token_query_only'] is True and value['max_enables']==value['max_restores']==1 and value['max_principal_discoveries']==value['max_status_queries']==1
|
||||
and value['principal_identity_proven'] is False,'one own-token privilege adjustment/restore, peer QUERY only, no fallback/identity claim')
|
||||
require(value['parent_manifest_sha256']=='6c97658307ec66e6605574dca27cdbc79efefa9cd7f386e6e2cb3f73d9b5c6d3'
|
||||
and value['parent_result_sha256']=='c7556589a015fc5ab53feffe3caf74a3904b7f5a65b70066f256cc0693ff8152'
|
||||
and value['returned_empty_principal_allowed'] is True and value['null_principal_allowed'] is False
|
||||
and sha(path.parent/'parent-wrapper-source.diff')==value['parent_wrapper_diff_sha256'],
|
||||
'exact enabled-privilege parent; one explicit local impersonation-level comparison, no fallback')
|
||||
for name,digest in value['unchanged_diagnostics'].items():require(sha(ROOT/name)==digest,'original SYSTEM/WINNT/EEInfo inputs retained')
|
||||
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_rpc_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 and value['own_privilege_adjustment'] is True and value['foreign_token_query_only'] 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-spnego-impersonate-v1' and report['case_id'] == ident
|
||||
and report['token_system'] is True and report['read_only'] is False and report['diagnostic_only'] is True
|
||||
and type(report['query_invocations']) is int and report['query_invocations'] in (0,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')
|
||||
token=report['token']
|
||||
require(set(token)=={'query_status','system_user','token_type','thread_query_status','thread_present','lookup_status','privileges_status','privilege_present','privilege_attributes','privilege_enabled','privilege_default','privilege_removed'}
|
||||
and all(type(v) is int and 0<=v<2**32 for v in token.values())
|
||||
and token==value['token_before_rpc'] and token['query_status']==token['lookup_status']==token['privileges_status']==0
|
||||
and token['system_user']==1 and token['token_type']==1 and token['thread_present']==0 and token['thread_query_status']==1008,
|
||||
'durable own SYSTEM primary token/privileges observed before RPC without impersonation')
|
||||
require(all(token[k] in (0,1) for k in ('privilege_present','privilege_enabled','privilege_default','privilege_removed'))
|
||||
and token['privilege_enabled']==int(bool(token['privilege_attributes']&2))
|
||||
and token['privilege_default']==int(bool(token['privilege_attributes']&1))
|
||||
and token['privilege_removed']==int(bool(token['privilege_attributes']&4))
|
||||
and (token['privilege_present'] or token['privilege_attributes']==0),'present/enabled privilege attributes remain observations only')
|
||||
auth=report['auth']
|
||||
require(set(auth)=={'discovery_invocations','discovery_status','discovery_return_present','principal_present','principal_units','principal_validated','status_query_invocations','authn_service','authn_level','impersonation_type','principal_free_attempted','principal_free_status','binding_free_attempted','binding_free_status','eeinfo_origin'}
|
||||
and all(type(v) is int and 0<=v<2**32 for v in auth.values())
|
||||
and auth['authn_service']==9 and auth['authn_level']==6 and auth['impersonation_type']==3
|
||||
and all(auth[k] in (0,1) for k in ('discovery_invocations','discovery_return_present','principal_present','principal_validated','status_query_invocations','principal_free_attempted','binding_free_attempted'))
|
||||
and auth['status_query_invocations']==report['query_invocations'] and auth['eeinfo_origin'] in (0,1,2,3)
|
||||
and auth['discovery_return_present']<=auth['discovery_invocations']
|
||||
and auth['principal_units']<=512,'bounded one-discovery/at-most-one-status SPNEGO Privacy Identify path')
|
||||
if auth['principal_validated']:
|
||||
require(auth['principal_present']==1 and 0<=auth['principal_units']<=512,'checked non-NULL bounded UTF16 principal, possibly empty')
|
||||
if auth['principal_present']:
|
||||
require(auth['principal_free_attempted']==1,'owned principal cleanup attempted')
|
||||
if auth['status_query_invocations']:
|
||||
require(auth['discovery_invocations']==auth['discovery_return_present']==auth['principal_present']==auth['principal_validated']==1
|
||||
and auth['discovery_status']==0 and 0<=auth['principal_units']<=512,'no status query without successful checked principal discovery')
|
||||
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')
|
||||
require(ee['capture_attempted']==int(auth['eeinfo_origin']!=0),'numeric EEInfo origin matches capture')
|
||||
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'] in (90,91):
|
||||
require(ee['capture_attempted']==1 and report['rpc_code']==report['trace']['rpc_exception']
|
||||
and auth['eeinfo_origin']==(2 if report['trace']['stage']==90 else 1),'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 and value.get('cleaned_service_exit_code')==0)
|
||||
|
||||
|
||||
def numeric(value):
|
||||
return type(value) is int and 0<=value<2**32
|
||||
|
||||
|
||||
def validate_snapshot(value):
|
||||
fields={'present','query_status','token_id','authentication_id','modified_id','expiration_time','token_type','impersonation_level','dynamic_charged','dynamic_available','group_count','privilege_count','privileges'}
|
||||
require(isinstance(value,dict) and set(value)==fields,'exact numeric token snapshot')
|
||||
for k in fields-{'token_id','authentication_id','modified_id','expiration_time','privileges'}:
|
||||
require(numeric(value[k]),'numeric token statistic')
|
||||
for k in ('token_id','authentication_id','modified_id','expiration_time'):
|
||||
require(isinstance(value[k],list) and len(value[k])==2 and all(numeric(v) for v in value[k]),'numeric LUID/time pair')
|
||||
require(value['present']==1 and value['query_status']==0 and value['token_type']==1,'queried primary token')
|
||||
privileges=value['privileges']
|
||||
require(isinstance(privileges,list) and len(privileges)==value['privilege_count']<=256
|
||||
and all(isinstance(p,list) and len(p)==3 and all(numeric(n) for n in p) for p in privileges),'bounded complete privilege list')
|
||||
keys=[(p[1],p[0]) for p in privileges]
|
||||
require(keys==sorted(set(keys)),'sorted unique privilege LUIDs')
|
||||
|
||||
|
||||
def same_identity(before,after):
|
||||
return all(before[k]==after[k] for k in ('token_id','authentication_id','token_type'))
|
||||
|
||||
|
||||
def check_privilege_evidence(value):
|
||||
before=value.get('privilege_before');change=value.get('privilege_adjustment')
|
||||
if before is None or change is None:return False
|
||||
require(set(before)=={'schema_version','own_pid','own_creation','own','peers'} and before['schema_version']==1
|
||||
and numeric(before['own_pid']) and before['own_pid']>0 and isinstance(before['own_creation'],list) and len(before['own_creation'])==2 and all(numeric(v) for v in before['own_creation']),'bound pre-enable numeric witness')
|
||||
validate_snapshot(before['own'])
|
||||
require(isinstance(before['peers'],list) and len(before['peers'])==4,'four named peer witnesses')
|
||||
for i,peer in enumerate(before['peers']):
|
||||
require(set(peer)=={'role','pid','creation','token'} and peer['role']==i and numeric(peer['pid']) and peer['pid']>0 and peer['pid']!=before['own_pid']
|
||||
and isinstance(peer['creation'],list) and len(peer['creation'])==2 and all(numeric(v) for v in peer['creation']),'held peer PID/start binding')
|
||||
validate_snapshot(peer['token'])
|
||||
require(peer['token']['token_id']!=before['own']['token_id'],'different actual peer token object')
|
||||
fields={'schema_version','preflight_status','enable_attempted','enable_return','enable_error','previous_count','previous_bytes','previous_luid','previous_attributes','active_status','rpc_attempted','restore_attempted','restore_return','restore_error','restore_input_from_previous','restored_status','peer_after_status','restoration_verified','flow_status','target_luid','active','restored','peers_after'}
|
||||
require(set(change)==fields and all(numeric(change[k]) for k in fields-{'previous_luid','target_luid','active','restored','peers_after'}),'exact bounded adjustment witness')
|
||||
for k in ('previous_luid','target_luid'):
|
||||
require(isinstance(change[k],list) and len(change[k])==2 and all(numeric(n) for n in change[k]),'exact privilege LUID')
|
||||
target=change['target_luid']
|
||||
expected=[p.copy() for p in before['own']['privileges']]
|
||||
targets=[p for p in expected if p[:2]==target]
|
||||
require(len(targets)==1 and targets[0][2]==0,'exact one present originally disabled privilege')
|
||||
require(change['schema_version']==1 and change['preflight_status']==0
|
||||
and all(change[k] in (0,1) for k in ('enable_attempted','enable_return','rpc_attempted','restore_attempted','restore_return','restore_input_from_previous','restoration_verified')),'one bounded activation/restore flow')
|
||||
# Failure reports remain available raw. Never call them preserved/complete.
|
||||
if change['flow_status']!=0 or change['restoration_verified']!=1:return False
|
||||
require(change['enable_attempted']==change['enable_return']==change['restore_attempted']==change['restore_return']==change['restore_input_from_previous']==1
|
||||
and change['enable_error']==change['restore_error']==change['active_status']==change['restored_status']==change['peer_after_status']==0
|
||||
and change['previous_count']==1 and change['previous_bytes']==16 and change['previous_luid']==target and change['previous_attributes']==0,
|
||||
'one successful exact enable and PreviousState restore, not TRUE/NOT_ALL_ASSIGNED')
|
||||
validate_snapshot(change['active']);validate_snapshot(change['restored'])
|
||||
targets[0][2]=2
|
||||
require(same_identity(before['own'],change['active']) and same_identity(before['own'],change['restored'])
|
||||
and change['active']['privileges']==expected and change['restored']['privileges']==before['own']['privileges'],
|
||||
'same own token only target enable bit changes and exact original attributes restored')
|
||||
require(isinstance(change['peers_after'],list) and len(change['peers_after'])==4,'four post-restore peer snapshots')
|
||||
for peer,after in zip(before['peers'],change['peers_after']):
|
||||
validate_snapshot(after)
|
||||
require(same_identity(peer['token'],after) and peer['token']['modified_id']==after['modified_id']
|
||||
and peer['token']['privileges']==after['privileges'],'observed peer token and privilege state preserved')
|
||||
require(change['rpc_attempted']==1 and value['report']['query_invocations']<=1,'at most one RPC function after verified enable')
|
||||
return True
|
||||
|
||||
|
||||
def check_report(value,ident):
|
||||
rpc_complete=check_rpc_report(value,ident)
|
||||
privilege_complete=check_privilege_evidence(value)
|
||||
return rpc_complete and privilege_complete
|
||||
|
||||
|
||||
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-spnego-impersonate-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-spnego-impersonate-trace-'+ident+'/ClockSpnegoImpersonateTrace.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,495 @@
|
||||
/* 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_impersonate(RmmClockTrace *trace, RmmClockEeInfo *eeinfo, RmmClockAuthTrace *auth);
|
||||
|
||||
static WCHAR service_name[] = L"RmmClockSpnegoImpersonateDiagnostic";
|
||||
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-impersonate-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-impersonate-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=3;
|
||||
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_impersonate(&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;
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
# Nativer RPC-Vergleich: Impersonate statt Identify
|
||||
|
||||
2026-11-14. Der getrennte Diagnosefall
|
||||
`daf8205c-a110-4fb7-9ae0-f27ca1532d8f` liefert erstmals einen normalen
|
||||
erfolgreichen W32Time-Statusreturn. **Keine Produktclockfreigabe:** Dienstidentität,
|
||||
LocalService-Pfad und tatsächliche Zeitqualität sind weiterhin separat nachzuweisen.
|
||||
|
||||
## Konkreter Anlass und geprüfter Unterschied
|
||||
|
||||
Die [vorherige Diagnose](windows-clock-process-privilege-result.md) hatte trotz
|
||||
nachgewiesen aktivem vorhandenem Prozessprivileg weiterhin RPC5/Stage90 ergeben.
|
||||
Der Windows-eigene `w32tm /query /status /verbose` dagegen lieferte als
|
||||
bestehender Admintransport Exit0. Seine Ausgabe war selbst Leap3/Stratum0,
|
||||
nicht synchronisiert; damit bestehen unabhängige Transport- und Zeitqualitätsgates.
|
||||
|
||||
Root las ausschließlich die vorhandenen Microsoft-Systemdateien `w32tm.exe`
|
||||
und `w32time.dll`, prüfte SignaturstatusValid und identische SHA/Länge vor und
|
||||
nach der privaten Kopie. Keine Installation oder DLL-/Produktänderung:
|
||||
|
||||
| Datei | Bytes | SHA256 |
|
||||
| --- | ---: | --- |
|
||||
| w32tm.exe | 274432 | `e81bcc55d0ed5d744b2f23417e9b2706e17a1c02a340503887679f54005570e5` |
|
||||
| w32time.dll | 745472 | `38c2efef83c2becb913d820b02fb16e987eccebf06ae4072093632b4c3bcc2ab` |
|
||||
|
||||
Lokale PE-Analyse dieser konkreten DLL: Der Export `W32TimeQueryStatus`
|
||||
(RVA280d0) ruft Discovery mit GSS9 und anschließend
|
||||
`RpcBindingSetAuthInfoW` mit Privacy6 auf. Der gefundene serverseitige
|
||||
Callback ruft nach `RpcImpersonateClient(NULL)`
|
||||
`OpenThreadToken` mit TOKEN_QUERY und OpenAsSelfFALSE auf. Das ist ein
|
||||
versionsgebundener Binärbefund, kein allgemeiner Vertrag jeder Windowsversion.
|
||||
Microsoft dokumentiert, dass das Öffnen des Tokens auf Identification-Stufe
|
||||
OpenAsSelfTRUE benötigt, da diese Stufe keine Executiveobjekte öffnen darf.
|
||||
[OpenThreadToken-Vertrag](https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-openthreadtoken).
|
||||
Die RPC-Standardstufe ist Impersonate, wenn die höhere Ebene nichts anderes
|
||||
vorgibt. [MS-RPCE](https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-rpce/fd5d5c6e-80f4-49b5-887f-4ce844cc62c4).
|
||||
|
||||
Deshalb wurde ein neuer, ausdrücklich getrennter Diagnosekandidat erstellt:
|
||||
die RPC-Stufe wechselt von Identify2 auf Impersonate3. Das erlaubt dem lokalen
|
||||
RPC-Server die lokale Impersonation des Diagnoseprozesses; es ist keine
|
||||
Delegatestufe und keine stille Produktlockerung. Namen/Fallprofil/Elternbezüge
|
||||
sind getrennt. GSS9, Privacy6, tatsächlicher zurückgegebener nicht-NULL
|
||||
Principal einschließlich Emptystring, eine Discovery und höchstens eine
|
||||
Opnum6 bleiben unverändert. Kein Authfallback oder Setter. Der gleiche
|
||||
SYSTEM-Own-Token-Enable-/PreviousState-Restoreablauf und die vier gehaltenen
|
||||
Peerprozesse mit ausschließlich TokenQUERY bleiben erhalten.
|
||||
|
||||
## Tatsächliche lokale und native Ergebnisse
|
||||
|
||||
Die vier neuen Quellen unter `deploy/windows/clock-spnego-impersonate-trace/`
|
||||
wurden unabhängig geprüft. Manifest
|
||||
`5644a50aee329144cb32c5bf0ebf4992ec068c59ca024416b66e8201366fd702`,
|
||||
PE114089Byte/SHA256
|
||||
`885a6f28df76ebc06e1457628cb4387bc9c0fa822b750fd29ce29d50aaf08fa5`.
|
||||
Tatsächlich bestanden: C-Compile mit Warnungen als Fehler, unveränderte
|
||||
Microsoft-MIDL-Ausgaben, Link, DLL-Importgrenze, PowerShell-AST sowie lokaler
|
||||
Manifestreader. Original131 Produktinputs,19 vorherige Diagnoseinputs,
|
||||
Elternmanifest6c976583 und ursprünglicher Fehlerbelegc7556589 bleiben bytegleich.
|
||||
|
||||
Root bereitete den separaten Fall vor, übertrug dessen feste EXE und startete
|
||||
genau einmal den eigenen temporären SYSTEM-Dienst. Tatsächlich:
|
||||
|
||||
- DienstStopped/Exit0; vollständiger normaler Return, RPC0, Stage80;
|
||||
- native Rückgabe0, Status vorhanden, ulSize120, cEntries0, pEntriesNULL;
|
||||
- genau eine erfolgreiche Principaldiscovery, tatsächlich nicht-NULL/leer,
|
||||
genau eine Opnum6 mit GSS9/Privacy6/Impersonate3;
|
||||
- keine RPC-Ausnahme und kein EEInfo-Record;
|
||||
- genau ein erfolgreiches Aktivieren des vorher vorhandenen Privilegs und
|
||||
nachgelesene vollständige Rücksetzung; alle beobachteten Peertoken unverändert.
|
||||
|
||||
Ein separater rein lesender Same-case-Aufruf bestätigte das Originalergebnis;
|
||||
anschließend wurde ausschließlich der eigene gestoppte Dienst entfernt.
|
||||
Endbeleg `diagnostic-result.json`, SHA256
|
||||
`26a06f8f46a7b5fa173c5ee81cd97a4542571a7b97b15fd5e0e8a41315680c4e`.
|
||||
Zusätzliche native Erhaltungsnachlese bestanden: sechs bestehende RMM-Bereiche
|
||||
und vollständiger Servergate gleich; Windows0/0/0/0, Linux31/31/27/0,
|
||||
Rootpolicycf15 geschlossen. Before-SHA256
|
||||
`d0f45d6d25936de2d4d66ef79b9bd3a1bb9bd5013cbbcd7ef3d145703e6c96cd`,
|
||||
After-SHA256 `792e164fcdc567c3ac620d89a7d8907ab6d80b9485e135c6744c92191eae31fe`.
|
||||
|
||||
Im kontrollierten Vergleich ändert der explizite RPC-Stufenwechsel das Ergebnis
|
||||
von5/Stage90 auf0/Stage80. Das stützt die konkrete Identify-/Callbackursache;
|
||||
ein interner Fehlerort des früheren fehlgeschlagenen Aufrufs wurde nicht
|
||||
serverseitig instrumentiert. Eine Discovery oder der zurückgegebene SPN,
|
||||
insbesondere unter NTLM, ist weiterhin kein unabhängiger Dienstidentitätsbeweis.
|
||||
Der Diagnosepfad enthält keine Produktionsfreigabe oder RMM-Jobausführung.
|
||||
|
||||
## Weiter offen
|
||||
|
||||
Die Produktclock braucht einen nachgewiesenen Account-/W32Time-Servicebezug
|
||||
mit passenden tatsächlichen negativen Identitätskontrollen; außerdem einen
|
||||
nativen LocalService- und Unsicherheits-/Kontinuitätsnachweis. Die vorhandene
|
||||
VM-Uhr ist laut Builtinstatus unsynchronisiert. Zwei rein lesende NTP-
|
||||
Stripchartproben zum bereits konfigurierten Peer antworteten; privater Beleg
|
||||
`156f5df32f54f3886b9712eecee6f73d7f08b3ddb3b216e9219137c89dc15785`.
|
||||
Dies prüft den Stripchartpfad und beweist nicht die erfolgreiche
|
||||
W32Time-Synchronisierung über dessen eigenen Quellport. Ein einmaliger
|
||||
`w32tm /resync` wurde dem Benutzer konkret zur Freigabe vorgelegt und hier
|
||||
noch nicht ausgeführt. NTPserver/Peers, Startart, ACLs, Rechtezuweisung,
|
||||
Produktdateien, Clockgate und Windows-RMM-Verbrauch blieben unverändert.
|
||||
|
||||
Private Belege einschließlich PE-Kopien/Disassembly bleiben gitignoriert;
|
||||
Microsoft-Binärdateien oder deren vollständige Disassembly werden nicht publiziert.
|
||||
Reference in New Issue
Block a user