Compare commits
19
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c3b09734e0 | ||
|
|
94a47da3fd | ||
|
|
e8cd6732f0 | ||
|
|
7c769750f8 | ||
|
|
59e9544223 | ||
|
|
98f4edfbff | ||
|
|
01f0a0476e | ||
|
|
29e35c4fb6 | ||
|
|
19f0b1e7f6 | ||
|
|
85f6ecc1c7 | ||
|
|
35600dc472 | ||
|
|
ae9b271095 | ||
|
|
a99823b85a | ||
|
|
15b3c6f28c | ||
|
|
5a1de712cf | ||
|
|
0be13da6d7 | ||
|
|
c4efe8a4b4 | ||
|
|
bbdfe59380 | ||
|
|
548996eb36 |
@@ -157,6 +157,7 @@ mod service {
|
|||||||
let clock = super::clock::NativeClock::new();
|
let clock = super::clock::NativeClock::new();
|
||||||
STAGE.store(30, Ordering::SeqCst);
|
STAGE.store(30, Ordering::SeqCst);
|
||||||
let pipe = super::clock::named_pipe_diagnostic();
|
let pipe = super::clock::named_pipe_diagnostic();
|
||||||
|
let status_rpc = super::clock::status_rpc_diagnostic();
|
||||||
let first = clock.report();
|
let first = clock.report();
|
||||||
std::thread::sleep(Duration::from_millis(750));
|
std::thread::sleep(Duration::from_millis(750));
|
||||||
STAGE.store(31, Ordering::SeqCst);
|
STAGE.store(31, Ordering::SeqCst);
|
||||||
@@ -164,7 +165,7 @@ mod service {
|
|||||||
let identity_controls = super::clock::identity_controls();
|
let identity_controls = super::clock::identity_controls();
|
||||||
STAGE.store(40, Ordering::SeqCst);
|
STAGE.store(40, Ordering::SeqCst);
|
||||||
let data = serde_json::to_vec_pretty(
|
let data = serde_json::to_vec_pretty(
|
||||||
&serde_json::json!({"schema":1,"case_id":case,"service_name":NAME,"token_sid":"S-1-5-19","elevated":token.elevation_flag!=0,"token":token,"endpoints":endpoints,"named_pipe_diagnostic":pipe,"identity_controls":identity_controls,"source":"MS-W32T:4.1:Opnum6:ncalrpc:SID19:W32Time:V5_descriptor:MUTUAL_AUTH:WINNT:PKT_PRIVACY","read_only":true,"samples":[first,second]}),
|
&serde_json::json!({"schema":1,"case_id":case,"service_name":NAME,"token_sid":"S-1-5-19","elevated":token.elevation_flag!=0,"token":token,"endpoints":endpoints,"named_pipe_diagnostic":pipe,"status_rpc_diagnostic":status_rpc,"identity_controls":identity_controls,"source":"MS-W32T:4.1:Opnum6:ncalrpc:SID19:W32Time:V5_descriptor:MUTUAL_AUTH:WINNT:PKT_PRIVACY","read_only":true,"samples":[first,second]}),
|
||||||
)?;
|
)?;
|
||||||
ensure!(data.len() < 16384, "READINESS_REPORT_SIZE");
|
ensure!(data.len() < 16384, "READINESS_REPORT_SIZE");
|
||||||
STAGE.store(41, Ordering::SeqCst);
|
STAGE.store(41, Ordering::SeqCst);
|
||||||
@@ -259,6 +260,6 @@ fn main() -> anyhow::Result<()> {
|
|||||||
fn main() {
|
fn main() {
|
||||||
println!(
|
println!(
|
||||||
"{}",
|
"{}",
|
||||||
serde_json::to_string(&serde_json::json!({"clock":clock::NativeClock::new().report(),"endpoints":clock::endpoint_report(),"named_pipe_diagnostic":clock::named_pipe_diagnostic(),"identity_controls":clock::identity_controls()})).unwrap()
|
serde_json::to_string(&serde_json::json!({"clock":clock::NativeClock::new().report(),"endpoints":clock::endpoint_report(),"named_pipe_diagnostic":clock::named_pipe_diagnostic(),"status_rpc_diagnostic":clock::status_rpc_diagnostic(),"identity_controls":clock::identity_controls()})).unwrap()
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -71,20 +71,47 @@ typedef struct {
|
|||||||
} RmmClockStatus;
|
} RmmClockStatus;
|
||||||
_Static_assert(sizeof(RmmClockStatus) == 64, "Rust numeric clock ABI");
|
_Static_assert(sizeof(RmmClockStatus) == 64, "Rust numeric clock ABI");
|
||||||
_Static_assert(sizeof(RMM_W32TIME_STATUS) == 120, "MS-W32T x64 structure ABI");
|
_Static_assert(sizeof(RMM_W32TIME_STATUS) == 120, "MS-W32T x64 structure ABI");
|
||||||
static uint32_t invoke_status(RPC_BINDING_HANDLE binding, RmmClockStatus *out) {
|
/* 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");
|
||||||
|
static uint32_t invoke_status(RPC_BINDING_HANDLE binding, RmmClockStatus *out, RmmClockTrace *trace) {
|
||||||
RMM_W32TIME_STATUS *status = NULL;
|
RMM_W32TIME_STATUS *status = NULL;
|
||||||
unsigned long result = 0;
|
unsigned long result = 0;
|
||||||
Arena arena = {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 && !InitOnceExecuteOnce(&arena_once, initialize_arena, NULL, NULL)) result = ERROR_NOT_ENOUGH_MEMORY;
|
||||||
if (!result && TlsGetValue(arena_index)) result = ERROR_BUSY;
|
if (!result && TlsGetValue(arena_index)) result = ERROR_BUSY;
|
||||||
if (!result && !TlsSetValue(arena_index, &arena)) result = GetLastError();
|
if (!result && !TlsSetValue(arena_index, &arena)) result = GetLastError();
|
||||||
if (!result) {
|
if (!result) {
|
||||||
RpcTryExcept {
|
RpcTryExcept {
|
||||||
|
if (trace) trace->stage = 60;
|
||||||
result = RmmW32TimeQueryStatus(binding, &status);
|
result = RmmW32TimeQueryStatus(binding, &status);
|
||||||
|
if (trace) {
|
||||||
|
trace->stage = 61; trace->native_rpc_return_present = 1;
|
||||||
|
trace->native_rpc_return = result;
|
||||||
|
}
|
||||||
if (!result) {
|
if (!result) {
|
||||||
if (!status || status->ulSize != sizeof(*status) || status->cEntries || status->pEntries)
|
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;
|
result = RPC_X_BAD_STUB_DATA;
|
||||||
|
}
|
||||||
else {
|
else {
|
||||||
|
if (trace) trace->stage = 80;
|
||||||
out->leap = status->eLeapIndicator; out->stratum = status->nStratum;
|
out->leap = status->eLeapIndicator; out->stratum = status->nStratum;
|
||||||
out->state = status->ulLcState; out->flags = status->ulTSFlags;
|
out->state = status->ulLcState; out->flags = status->ulTSFlags;
|
||||||
out->last_result = status->eLastSyncResult; out->size = status->ulSize;
|
out->last_result = status->eLastSyncResult; out->size = status->ulSize;
|
||||||
@@ -95,21 +122,24 @@ static uint32_t invoke_status(RPC_BINDING_HANDLE binding, RmmClockStatus *out) {
|
|||||||
}
|
}
|
||||||
} RpcExcept(RpcExceptionFilter(RpcExceptionCode())) {
|
} RpcExcept(RpcExceptionFilter(RpcExceptionCode())) {
|
||||||
result = RpcExceptionCode();
|
result = RpcExceptionCode();
|
||||||
|
if (trace) {trace->stage = 90; trace->rpc_exception = result;}
|
||||||
} RpcEndExcept
|
} RpcEndExcept
|
||||||
release_allocations(&arena);
|
release_allocations(&arena);
|
||||||
TlsSetValue(arena_index, NULL);
|
TlsSetValue(arena_index, NULL);
|
||||||
}
|
}
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
uint32_t rmm_clock_query(RmmClockStatus *out) {
|
static uint32_t pipe_query(RmmClockStatus *out, RmmClockTrace *trace) {
|
||||||
RPC_WSTR text = NULL;
|
RPC_WSTR text = NULL;
|
||||||
RPC_BINDING_HANDLE binding = NULL;
|
RPC_BINDING_HANDLE binding = NULL;
|
||||||
RPC_SECURITY_QOS qos = {0};
|
RPC_SECURITY_QOS qos = {0};
|
||||||
unsigned long result;
|
unsigned long result;
|
||||||
memset(out, 0, sizeof(*out));
|
memset(out, 0, sizeof(*out));
|
||||||
|
if (trace) trace->stage = 10;
|
||||||
result = RpcStringBindingComposeW(NULL, (RPC_WSTR)L"ncacn_np", NULL,
|
result = RpcStringBindingComposeW(NULL, (RPC_WSTR)L"ncacn_np", NULL,
|
||||||
(RPC_WSTR)L"\\pipe\\W32TIME_ALT", NULL, &text);
|
(RPC_WSTR)L"\\pipe\\W32TIME_ALT", NULL, &text);
|
||||||
if (result) return result;
|
if (result) return result;
|
||||||
|
if (trace) trace->stage = 20;
|
||||||
result = RpcBindingFromStringBindingW(text, &binding);
|
result = RpcBindingFromStringBindingW(text, &binding);
|
||||||
RpcStringFreeW(&text);
|
RpcStringFreeW(&text);
|
||||||
if (result) return result;
|
if (result) return result;
|
||||||
@@ -117,13 +147,23 @@ uint32_t rmm_clock_query(RmmClockStatus *out) {
|
|||||||
qos.Capabilities = RPC_C_QOS_CAPABILITIES_DEFAULT;
|
qos.Capabilities = RPC_C_QOS_CAPABILITIES_DEFAULT;
|
||||||
qos.IdentityTracking = RPC_C_QOS_IDENTITY_STATIC;
|
qos.IdentityTracking = RPC_C_QOS_IDENTITY_STATIC;
|
||||||
qos.ImpersonationType = RPC_C_IMP_LEVEL_IDENTIFY;
|
qos.ImpersonationType = RPC_C_IMP_LEVEL_IDENTIFY;
|
||||||
|
if (trace) trace->stage = 30;
|
||||||
result = RpcBindingSetAuthInfoExW(binding, NULL, RPC_C_AUTHN_LEVEL_PKT_PRIVACY,
|
result = RpcBindingSetAuthInfoExW(binding, NULL, RPC_C_AUTHN_LEVEL_PKT_PRIVACY,
|
||||||
RPC_C_AUTHN_WINNT, NULL, RPC_C_AUTHZ_NONE, &qos);
|
RPC_C_AUTHN_WINNT, NULL, RPC_C_AUTHZ_NONE, &qos);
|
||||||
if (!result) result = RpcBindingSetOption(binding, RPC_C_OPT_CALL_TIMEOUT, 1500);
|
if (!result) {
|
||||||
if (!result) result = invoke_status(binding, out);
|
if (trace) trace->stage = 40;
|
||||||
|
result = RpcBindingSetOption(binding, RPC_C_OPT_CALL_TIMEOUT, 1500);
|
||||||
|
}
|
||||||
|
if (!result) result = invoke_status(binding, out, trace);
|
||||||
RpcBindingFree(&binding);
|
RpcBindingFree(&binding);
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
uint32_t rmm_clock_query(RmmClockStatus *out) { return pipe_query(out, NULL); }
|
||||||
|
uint32_t rmm_clock_query_trace(RmmClockTrace *trace) {
|
||||||
|
RmmClockStatus ignored = {0};
|
||||||
|
memset(trace, 0, sizeof(*trace));
|
||||||
|
return pipe_query(&ignored, trace);
|
||||||
|
}
|
||||||
/* Kernel-authenticated ALPC only. No automatic fallback to named pipes.
|
/* Kernel-authenticated ALPC only. No automatic fallback to named pipes.
|
||||||
* The expected SID is fixed locally, never adopted from endpoint metadata.
|
* The expected SID is fixed locally, never adopted from endpoint metadata.
|
||||||
*/
|
*/
|
||||||
@@ -188,7 +228,7 @@ static uint32_t alpc_query(RmmClockStatus *out, unsigned control) {
|
|||||||
qos.ServerSecurityDescriptor = &descriptor;
|
qos.ServerSecurityDescriptor = &descriptor;
|
||||||
result = RpcBindingSetAuthInfoExW(binding, NULL, RPC_C_AUTHN_LEVEL_PKT_PRIVACY,
|
result = RpcBindingSetAuthInfoExW(binding, NULL, RPC_C_AUTHN_LEVEL_PKT_PRIVACY,
|
||||||
RPC_C_AUTHN_WINNT, NULL, RPC_C_AUTHZ_NONE, (RPC_SECURITY_QOS *)&qos);
|
RPC_C_AUTHN_WINNT, NULL, RPC_C_AUTHZ_NONE, (RPC_SECURITY_QOS *)&qos);
|
||||||
if (!result) result = invoke_status(binding, out);
|
if (!result) result = invoke_status(binding, out, NULL);
|
||||||
}
|
}
|
||||||
RpcBindingFree(&binding);
|
RpcBindingFree(&binding);
|
||||||
break; /* no retry, alternate identity, endpoint or weaker transport */
|
break; /* no retry, alternate identity, endpoint or weaker transport */
|
||||||
|
|||||||
@@ -31,6 +31,11 @@ typedef struct {
|
|||||||
unsigned long cEntries;
|
unsigned long cEntries;
|
||||||
[size_is(cEntries)] RMM_W32TIME_ENTRY *pEntries;
|
[size_is(cEntries)] RMM_W32TIME_ENTRY *pEntries;
|
||||||
} RMM_W32TIME_STATUS;
|
} RMM_W32TIME_STATUS;
|
||||||
|
/* Microsoft declares PW32TIME_STATUS_INFO separately. Keep the inner pointer
|
||||||
|
* explicitly unique; the out parameter's outer pointer defaults to ref.
|
||||||
|
* WIDL 7 propagates a parameter-level [ref] through a direct ** declaration.
|
||||||
|
*/
|
||||||
|
typedef [unique] RMM_W32TIME_STATUS *RMM_PW32TIME_STATUS;
|
||||||
[uuid(8fb6d884-2388-11d0-8c35-00c04fda2795), version(4.1), pointer_default(unique)]
|
[uuid(8fb6d884-2388-11d0-8c35-00c04fda2795), version(4.1), pointer_default(unique)]
|
||||||
interface RmmW32Time {
|
interface RmmW32Time {
|
||||||
unsigned long RmmUnusedSlot0([in] handle_t binding);
|
unsigned long RmmUnusedSlot0([in] handle_t binding);
|
||||||
@@ -39,5 +44,5 @@ interface RmmW32Time {
|
|||||||
unsigned long RmmUnusedSlot3([in] handle_t binding);
|
unsigned long RmmUnusedSlot3([in] handle_t binding);
|
||||||
unsigned long RmmUnusedSlot4([in] handle_t binding);
|
unsigned long RmmUnusedSlot4([in] handle_t binding);
|
||||||
unsigned long RmmUnusedSlot5([in] handle_t binding);
|
unsigned long RmmUnusedSlot5([in] handle_t binding);
|
||||||
unsigned long RmmW32TimeQueryStatus([in] handle_t binding, [out, ref] RMM_W32TIME_STATUS **status);
|
unsigned long RmmW32TimeQueryStatus([in] handle_t binding, [out] RMM_PW32TIME_STATUS *status);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -259,6 +259,87 @@ pub fn named_pipe_diagnostic() -> ClockReport {
|
|||||||
}
|
}
|
||||||
.report()
|
.report()
|
||||||
}
|
}
|
||||||
|
/// Diagnostic-only ABI captured before the existing C layout guard. Presence
|
||||||
|
/// flags are numeric0/1; no remote pointers, names or returned entries escape.
|
||||||
|
#[derive(Clone, Copy, Debug, Default, Serialize)]
|
||||||
|
#[repr(C)]
|
||||||
|
pub struct StatusRpcTrace {
|
||||||
|
pub stage: u32,
|
||||||
|
pub native_rpc_return: u32,
|
||||||
|
pub native_rpc_return_present: u32,
|
||||||
|
pub rpc_exception: u32,
|
||||||
|
pub status_present: u32,
|
||||||
|
pub ul_size: u32,
|
||||||
|
pub c_entries: u32,
|
||||||
|
pub p_entries_present: u32,
|
||||||
|
}
|
||||||
|
#[derive(Debug, Serialize)]
|
||||||
|
pub struct StatusRpcDiagnostic {
|
||||||
|
pub rpc_code: u32,
|
||||||
|
pub independent_call: bool,
|
||||||
|
pub trace: Option<StatusRpcTrace>,
|
||||||
|
pub diagnostic_only: bool,
|
||||||
|
pub adapter_qualified: bool,
|
||||||
|
pub trusted: bool,
|
||||||
|
}
|
||||||
|
/// The fixed authenticated named-pipe call is observed separately. It never
|
||||||
|
/// selects a production transport or supplies a trusted timestamp. One worker,
|
||||||
|
/// one outstanding call and no replacement/retry after a local timeout.
|
||||||
|
pub fn status_rpc_diagnostic() -> StatusRpcDiagnostic {
|
||||||
|
#[cfg(windows)]
|
||||||
|
let (rpc_code, trace) = {
|
||||||
|
type Reply = std::sync::mpsc::SyncSender<(u32, StatusRpcTrace)>;
|
||||||
|
type Requests = std::sync::mpsc::SyncSender<Reply>;
|
||||||
|
static WORKER: std::sync::OnceLock<Mutex<Option<Requests>>> = std::sync::OnceLock::new();
|
||||||
|
let worker = WORKER.get_or_init(|| {
|
||||||
|
let (sender, receiver) = std::sync::mpsc::sync_channel::<Reply>(1);
|
||||||
|
let created = std::thread::Builder::new()
|
||||||
|
.name("rmm-clock-status-diag".into())
|
||||||
|
.spawn(move || {
|
||||||
|
#[link(name = "rmm_clock_rpc", kind = "static")]
|
||||||
|
#[link(name = "rpcrt4")]
|
||||||
|
#[link(name = "advapi32")]
|
||||||
|
unsafe extern "C" {
|
||||||
|
fn rmm_clock_query_trace(trace: *mut StatusRpcTrace) -> u32;
|
||||||
|
}
|
||||||
|
while let Ok(reply) = receiver.recv() {
|
||||||
|
let mut trace = StatusRpcTrace::default();
|
||||||
|
// SAFETY: fixed8*u32 C ABI; SEH stays contained inside C.
|
||||||
|
let code = unsafe { rmm_clock_query_trace(&mut trace) };
|
||||||
|
let _ = reply.send((code, trace));
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.is_ok();
|
||||||
|
Mutex::new(created.then_some(sender))
|
||||||
|
});
|
||||||
|
if let Ok(mut worker) = worker.try_lock() {
|
||||||
|
let (reply, receiver) = std::sync::mpsc::sync_channel(1);
|
||||||
|
let sent = worker
|
||||||
|
.as_ref()
|
||||||
|
.is_some_and(|sender| sender.try_send(reply).is_ok());
|
||||||
|
if sent
|
||||||
|
&& let Ok((code, trace)) = receiver.recv_timeout(std::time::Duration::from_secs(2))
|
||||||
|
{
|
||||||
|
(code, Some(trace))
|
||||||
|
} else {
|
||||||
|
*worker = None;
|
||||||
|
(1818, None)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
(170, None)
|
||||||
|
}
|
||||||
|
};
|
||||||
|
#[cfg(not(windows))]
|
||||||
|
let (rpc_code, trace) = (50, None);
|
||||||
|
StatusRpcDiagnostic {
|
||||||
|
rpc_code,
|
||||||
|
independent_call: true,
|
||||||
|
trace,
|
||||||
|
diagnostic_only: true,
|
||||||
|
adapter_qualified: false,
|
||||||
|
trusted: false,
|
||||||
|
}
|
||||||
|
}
|
||||||
/// Read-only negative controls for the separate native readiness program.
|
/// Read-only negative controls for the separate native readiness program.
|
||||||
/// Neither control can produce clock authority, even if the OS accepts it.
|
/// Neither control can produce clock authority, even if the OS accepts it.
|
||||||
/// Rejection without a successful genuine status query is not identity proof.
|
/// Rejection without a successful genuine status query is not identity proof.
|
||||||
@@ -443,6 +524,7 @@ mod tests {
|
|||||||
}
|
}
|
||||||
#[test]
|
#[test]
|
||||||
fn production_clock_stays_closed_until_native_adapter_qualification() {
|
fn production_clock_stays_closed_until_native_adapter_qualification() {
|
||||||
|
assert_eq!(std::mem::size_of::<StatusRpcTrace>(), 32);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
NativeClock::new().now().unwrap_err().to_string(),
|
NativeClock::new().now().unwrap_err().to_string(),
|
||||||
"CLOCK_ADAPTER_UNQUALIFIED"
|
"CLOCK_ADAPTER_UNQUALIFIED"
|
||||||
|
|||||||
@@ -0,0 +1,138 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Local-only SYSTEM trace diagnostic build; no VM and no product source edits."""
|
||||||
|
import base64
|
||||||
|
import difflib
|
||||||
|
import hashlib
|
||||||
|
import importlib.util
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
import re
|
||||||
|
import shutil
|
||||||
|
import subprocess
|
||||||
|
import uuid
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parents[3]
|
||||||
|
HERE = Path(__file__).resolve().parent
|
||||||
|
STATE = ROOT / 'devstate/windows-clock-eeinfo-trace'
|
||||||
|
IMAGE = 'sha256:1b2fd985d2c1fcc3545ace602405dc68fa899201bd8a73fa319ff96377203fa9'
|
||||||
|
BASELINE = ROOT / 'devstate/windows-clock-midl/diagnostic-builds/181c3a1c-8324-41fd-9b7c-aa8010262912/qualification.json'
|
||||||
|
BASELINE_SHA = '2e0de3acf72ab5c3a8e0baa54e8643d086ea7c03d1b38fd89b6bfc00e45f8cbb'
|
||||||
|
NATIVE = ROOT / 'devstate/windows-clock-midl/native-cases/149bafe2-3469-4580-b133-988812bcc3db'
|
||||||
|
READBACK = NATIVE / 'readback-059c15ef-0f31-41aa-ad1d-ea6b774280d7.json'
|
||||||
|
READBACK_SHA = '0dc2373825f7f8f224cda04ecd5c521dd3c37a6e712bc3ed83bc4fa6d0d89c8c'
|
||||||
|
|
||||||
|
|
||||||
|
def require(value, message):
|
||||||
|
if not value: raise RuntimeError(message)
|
||||||
|
|
||||||
|
|
||||||
|
def sha(path):
|
||||||
|
return hashlib.sha256(Path(path).read_bytes()).hexdigest()
|
||||||
|
|
||||||
|
|
||||||
|
def write(path, raw):
|
||||||
|
path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||||
|
fd = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY | os.O_NOFOLLOW, 0o600)
|
||||||
|
with os.fdopen(fd, 'wb') as output:
|
||||||
|
output.write(raw); output.flush(); os.fsync(output.fileno())
|
||||||
|
|
||||||
|
|
||||||
|
def save(path, value):
|
||||||
|
write(path, (json.dumps(value, indent=2) + '\n').encode())
|
||||||
|
|
||||||
|
|
||||||
|
def original_sources():
|
||||||
|
require(sha(BASELINE) == BASELINE_SHA, 'original b1d3 qualification')
|
||||||
|
value = json.loads(BASELINE.read_bytes())
|
||||||
|
require(len(value['source_files']) == 131 and value['artifact']['sha256'] == 'b1d3da4f393ddf20bc8e48a9894ee314666f2ac3613ef97f5c228e3d089ca560', 'unchanged complete original131 source set')
|
||||||
|
for name, digest in value['source_files'].items():
|
||||||
|
path = ROOT / name
|
||||||
|
require(not path.is_symlink() and path.is_file() and sha(path) == digest, 'original131 input changed')
|
||||||
|
return value
|
||||||
|
|
||||||
|
|
||||||
|
def own_sources():
|
||||||
|
return {str((HERE / name).relative_to(ROOT)):sha(HERE / name) for name in ('clock_rpc_eeinfo.c','system_trace_eeinfo.c','build.py','native.py')}
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
os.umask(0o077)
|
||||||
|
baseline = original_sources(); before = own_sources()
|
||||||
|
require(sha(READBACK) == READBACK_SHA, 'actual Microsoft codegen readback')
|
||||||
|
receipt = json.loads(READBACK.read_bytes())
|
||||||
|
require(receipt['readback_only'] is True and receipt['result']['complete'] is True
|
||||||
|
and receipt['result']['run']['exit_code'] == 0 and receipt['result']['no_rpc'] is True,
|
||||||
|
'actual completed MIDL codegen')
|
||||||
|
folder = STATE / ('build-' + str(uuid.uuid4())); folder.mkdir(mode=0o700, parents=True)
|
||||||
|
source = folder / 'source'; source.mkdir(mode=0o700)
|
||||||
|
generated = {}
|
||||||
|
for name, digest in baseline['generated_inputs'].items():
|
||||||
|
path = NATIVE / ('native-' + name); raw = path.read_bytes()
|
||||||
|
item = next(item for item in receipt['files'] if item['name'] == name)
|
||||||
|
require(sha(path) == item['sha256'] == digest and len(raw) == item['bytes']
|
||||||
|
and base64.b64decode(item['base64'], validate=True) == raw, 'same actual unchanged Microsoft output')
|
||||||
|
write(source / name, raw); generated[name] = digest
|
||||||
|
baseline_wrapper = ROOT / 'crates/agent-windows/native/clock_rpc.c'
|
||||||
|
require(sha(baseline_wrapper) == '74aceb6e2b70c5dd628fae069a842c356c20300b8c8ab12754258c78eaf295c8','same original C/Auth wrapper')
|
||||||
|
wrapper = HERE / 'clock_rpc_eeinfo.c'
|
||||||
|
write(source / 'clock_rpc.c', wrapper.read_bytes()); write(source / 'system_trace.c', (HERE / 'system_trace_eeinfo.c').read_bytes())
|
||||||
|
delta = ''.join(difflib.unified_diff(baseline_wrapper.read_text().splitlines(True),wrapper.read_text().splitlines(True),fromfile='original-clock_rpc.c',tofile='diagnostic-clock_rpc_eeinfo.c'))
|
||||||
|
write(folder / 'wrapper-source.diff',delta.encode())
|
||||||
|
save(folder / 'intent.json', dict(image=IMAGE, original131=baseline['source_files'], baseline_sha256=BASELINE_SHA,
|
||||||
|
actual_codegen_readback_sha256=READBACK_SHA, generated=generated, own_sources=before,
|
||||||
|
wrapper_sha256=sha(wrapper), original_wrapper_sha256=sha(baseline_wrapper), wrapper_diff_sha256=sha(folder / 'wrapper-source.diff'), own_system_token_only=True, exactly_one_trace_call=True, no_vm=True))
|
||||||
|
output = folder / 'output'; output.mkdir(mode=0o700)
|
||||||
|
checks = {}
|
||||||
|
def run(name, args):
|
||||||
|
command = ['docker','run','--rm','--network','none','--read-only','--tmpfs','/tmp:rw,size=128m',
|
||||||
|
'-v',str(source)+':/src:ro','-v',str(output)+':/out','--entrypoint',args[0],IMAGE,*args[1:]]
|
||||||
|
done = subprocess.run(command,capture_output=True,timeout=120)
|
||||||
|
write(folder / (name+'.stdout'),done.stdout); write(folder / (name+'.stderr'),done.stderr)
|
||||||
|
checks[name] = dict(exit_code=done.returncode,command=command,stdout_sha256=sha(folder / (name+'.stdout')),stderr_sha256=sha(folder / (name+'.stderr')))
|
||||||
|
save(folder / (name+'.json'),checks[name]); require(done.returncode == 0,'local diagnostic compile/check failure: '+name)
|
||||||
|
return done.stdout
|
||||||
|
flags = ['--target=x86_64-w64-windows-gnu','-fms-extensions','-Wall','-Wextra','-Werror','-D_M_AMD64=100','-I/src','-O2']
|
||||||
|
run('main',['clang',*flags,'-c','/src/system_trace.c','-o','/out/system_trace.o'])
|
||||||
|
run('wrapper',['clang',*flags,'-c','/src/clock_rpc.c','-o','/out/clock_rpc.o'])
|
||||||
|
run('actual-midl',['clang',*flags,'-Wno-error=missing-braces','-Wno-error=unused-const-variable','-c','/src/w32time_c.c','-o','/out/w32time_c.o'])
|
||||||
|
run('link',['x86_64-w64-mingw32-gcc','-static-libgcc','-municode','/out/system_trace.o','/out/clock_rpc.o','/out/w32time_c.o',
|
||||||
|
'-lrpcrt4','-ladvapi32','-lkernel32','-lmincore','-o','/out/ClockSystemEeInfoTrace.linked.exe'])
|
||||||
|
raw_linked = output / 'ClockSystemEeInfoTrace.linked.exe'
|
||||||
|
linked = output / 'ClockSystemEeInfoTrace.original.exe'; delivery = output / 'ClockSystemEeInfoTrace.exe'
|
||||||
|
# Retain a caller-owned private exact copy; Docker's root-owned raw link is
|
||||||
|
# kept too. No chmod/chown of unrelated objects or source mutation.
|
||||||
|
shutil.copyfile(raw_linked,linked); linked.chmod(0o600)
|
||||||
|
shutil.copyfile(linked,delivery); delivery.chmod(0o600)
|
||||||
|
run('strip',['x86_64-w64-mingw32-strip','--strip-debug','/out/ClockSystemEeInfoTrace.exe'])
|
||||||
|
imports = sorted(set(re.findall(r'DLL Name:\s+(\S+)',run('imports',['x86_64-w64-mingw32-objdump','-p','/out/ClockSystemEeInfoTrace.exe']).decode())))
|
||||||
|
require(imports and {name.lower() for name in imports}.issubset({'kernel32.dll','msvcrt.dll','advapi32.dll','rpcrt4.dll','api-ms-win-core-realtime-l1-1-2.dll'}),'reviewed system DLL imports only')
|
||||||
|
data = delivery.read_bytes(); offset = int.from_bytes(data[60:64],'little')
|
||||||
|
require(data[:2] == b'MZ' and data[offset:offset+6] == b'PE\0\0\x64\x86' and len(data) < 1048576,'bounded standalone C x64 PE')
|
||||||
|
spec = importlib.util.spec_from_file_location('system_trace_native',HERE / 'native.py'); native = importlib.util.module_from_spec(spec); spec.loader.exec_module(native)
|
||||||
|
script = folder / 'native.ps1'; write(script,native.SCRIPT.encode())
|
||||||
|
parser = "$e=$null;$t=$null;[System.Management.Automation.Language.Parser]::ParseFile($args[0],[ref]$t,[ref]$e)|Out-Null;if($e.Count){$e|ForEach-Object{$_.Message};exit 1};'AST_PASS'"
|
||||||
|
parser_path = folder / 'parse-native.ps1'; write(parser_path,parser.encode())
|
||||||
|
parsed = subprocess.run(['/tmp/rmm-powershell-parser/pwsh','-NoLogo','-NoProfile','-NonInteractive','-File',str(parser_path),str(script)],capture_output=True,timeout=15)
|
||||||
|
write(folder / 'powershell-parser.stdout',parsed.stdout); write(folder / 'powershell-parser.stderr',parsed.stderr)
|
||||||
|
require(parsed.returncode == 0 and b'AST_PASS' in parsed.stdout and not parsed.stderr,'actual PowerShell AST')
|
||||||
|
command_chars = len(native.encoded_command())
|
||||||
|
require(command_chars < 32767,'Windows encoded command length')
|
||||||
|
require(original_sources()['source_files'] == baseline['source_files'] and own_sources() == before,'all original131 and new sources unchanged')
|
||||||
|
manifest = dict(schema_version=1,profile='clock-system-eeinfo-v1',image=IMAGE,baseline_sha256=BASELINE_SHA,
|
||||||
|
original131=baseline['source_files'],own_sources=before,wrapper_sha256=sha(wrapper),original_wrapper_sha256=sha(baseline_wrapper),wrapper_diff_sha256=sha(folder / 'wrapper-source.diff'),generated=generated,
|
||||||
|
actual_codegen_readback_sha256=READBACK_SHA,checks=checks,script_sha256=hashlib.sha256(native.SCRIPT.encode()).hexdigest(),
|
||||||
|
powershell_ast_passed=True,encoded_command_characters=command_chars,
|
||||||
|
artifact=dict(path=str(delivery),sha256=sha(delivery),bytes=len(data),imports=imports),
|
||||||
|
linked=dict(path=str(linked),sha256=sha(linked)),raw_linked_sha256=sha(raw_linked),native_executed=False,clock_qualified=False,
|
||||||
|
adapter_qualified=False,product_gate_open=False,no_vm=True,no_rmm_jobs=True)
|
||||||
|
save(folder / 'manifest.json',manifest)
|
||||||
|
print(json.dumps(dict(manifest=str(folder / 'manifest.json'),manifest_sha256=sha(folder / 'manifest.json'),artifact=manifest['artifact'],
|
||||||
|
original131_unchanged=True,powershell_ast=True,command_characters=command_chars,native_executed=False)))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
try: main()
|
||||||
|
except Exception as error:
|
||||||
|
print(json.dumps(dict(error='CLOCK_SYSTEM_TRACE_LOCAL_INCOMPLETE',error_class=type(error).__name__,details_suppressed=True)))
|
||||||
|
raise SystemExit(2) from None
|
||||||
@@ -0,0 +1,291 @@
|
|||||||
|
/* Only the authenticated local MS-W32T status operation is reachable here.
|
||||||
|
* NDR code is generated by WIDL; SEH must terminate inside C, never in Rust.
|
||||||
|
*/
|
||||||
|
#define _WIN32_WINNT 0x0a00
|
||||||
|
#include <windows.h>
|
||||||
|
#include <rpc.h>
|
||||||
|
#include <rpcasync.h>
|
||||||
|
#include <stdint.h>
|
||||||
|
#include <stddef.h>
|
||||||
|
#include <stdlib.h>
|
||||||
|
#include <string.h>
|
||||||
|
#include "w32time.h"
|
||||||
|
/* Documented public SDK API; older MinGW headers omit its declaration. */
|
||||||
|
int RPC_ENTRY RpcExceptionFilter(unsigned long exception_code);
|
||||||
|
/* Older MinGW headers stop at V3. This is the documented x64 V5 SDK layout,
|
||||||
|
* not a fallback to an older authentication contract. MSVC also checks it
|
||||||
|
* directly against its native SDK declaration. Windows x64 is the only target.
|
||||||
|
* https://learn.microsoft.com/windows/win32/api/rpcdce/ns-rpcdce-rpc_security_qos_v5_w
|
||||||
|
*/
|
||||||
|
typedef struct {
|
||||||
|
unsigned long Version, Capabilities, IdentityTracking, ImpersonationType;
|
||||||
|
unsigned long AdditionalSecurityInfoType;
|
||||||
|
union { RPC_HTTP_TRANSPORT_CREDENTIALS_W *HttpCredentials; } u;
|
||||||
|
void *Sid;
|
||||||
|
unsigned int EffectiveOnly;
|
||||||
|
void *ServerSecurityDescriptor;
|
||||||
|
} RmmRpcQosV5;
|
||||||
|
_Static_assert(sizeof(RmmRpcQosV5) == 56, "x64 RPC QOS V5 ABI");
|
||||||
|
_Static_assert(offsetof(RmmRpcQosV5, Sid) == offsetof(RPC_SECURITY_QOS_V3_W, Sid), "SDK QOS prefix ABI");
|
||||||
|
_Static_assert(offsetof(RmmRpcQosV5, ServerSecurityDescriptor) == 48, "x64 server descriptor ABI");
|
||||||
|
#ifdef _MSC_VER
|
||||||
|
_Static_assert(sizeof(RmmRpcQosV5) == sizeof(RPC_SECURITY_QOS_V5_W), "native SDK QOS V5 ABI");
|
||||||
|
_Static_assert(offsetof(RmmRpcQosV5, ServerSecurityDescriptor) == offsetof(RPC_SECURITY_QOS_V5_W, ServerSecurityDescriptor), "native SDK descriptor ABI");
|
||||||
|
#endif
|
||||||
|
|
||||||
|
typedef struct Allocation { struct Allocation *next; size_t size; } Allocation;
|
||||||
|
typedef struct { Allocation *head; size_t total; } Arena;
|
||||||
|
/* Explicit Windows TLS also works on threads created by SCM. Clang static TLS
|
||||||
|
* in the mixed Rust/MinGW PE did not initialize such a thread's storage. */
|
||||||
|
static INIT_ONCE arena_once = INIT_ONCE_STATIC_INIT;
|
||||||
|
static DWORD arena_index = TLS_OUT_OF_INDEXES;
|
||||||
|
static BOOL CALLBACK initialize_arena(PINIT_ONCE once, PVOID parameter, PVOID *context) {
|
||||||
|
(void)once; (void)parameter; (void)context;
|
||||||
|
arena_index = TlsAlloc();
|
||||||
|
return arena_index != TLS_OUT_OF_INDEXES;
|
||||||
|
}
|
||||||
|
void *__RPC_USER MIDL_user_allocate(size_t size) {
|
||||||
|
Arena *arena = TlsGetValue(arena_index);
|
||||||
|
if (!arena || size > 65536 || arena->total > 65536 - size) return NULL;
|
||||||
|
Allocation *p = calloc(1, sizeof(*p) + size);
|
||||||
|
if (!p) return NULL;
|
||||||
|
p->size = size; p->next = arena->head; arena->head = p; arena->total += size;
|
||||||
|
return p + 1;
|
||||||
|
}
|
||||||
|
void __RPC_USER MIDL_user_free(void *memory) {
|
||||||
|
Arena *arena = TlsGetValue(arena_index);
|
||||||
|
if (!memory || !arena) return;
|
||||||
|
Allocation **link = &arena->head;
|
||||||
|
while (*link && (*link + 1) != memory) link = &(*link)->next;
|
||||||
|
if (*link) { Allocation *p = *link; *link = p->next; arena->total -= p->size; free(p); }
|
||||||
|
}
|
||||||
|
static void release_allocations(Arena *arena) {
|
||||||
|
while (arena->head) MIDL_user_free(arena->head + 1);
|
||||||
|
}
|
||||||
|
/* Stable numeric ABI, no returned peer/source strings or remotely sized data. */
|
||||||
|
typedef struct {
|
||||||
|
uint32_t leap, stratum, state, flags, last_result, size;
|
||||||
|
uint64_t last_sync, sync_age;
|
||||||
|
int64_t root_delay;
|
||||||
|
uint64_t root_dispersion;
|
||||||
|
int64_t phase;
|
||||||
|
} RmmClockStatus;
|
||||||
|
_Static_assert(sizeof(RmmClockStatus) == 64, "Rust numeric clock ABI");
|
||||||
|
_Static_assert(sizeof(RMM_W32TIME_STATUS) == 120, "MS-W32T x64 structure ABI");
|
||||||
|
/* Diagnostic-only numeric ABI. No strings, names, pointers or remote arrays
|
||||||
|
* leave C. A zero native return is meaningful only when return_present is1.
|
||||||
|
* Stages:10 compose,20 binding,30 auth,40 call-timeout,50 arena,
|
||||||
|
* 60 invoking,61 returned,62 raw numeric status,70 local guard,80 mapped,
|
||||||
|
* 90 contained RPC/SEH exception. Never used by the clock trust evaluator.
|
||||||
|
*/
|
||||||
|
typedef struct {
|
||||||
|
uint32_t stage, native_rpc_return, native_rpc_return_present, rpc_exception;
|
||||||
|
uint32_t status_present, ul_size, c_entries, p_entries_present;
|
||||||
|
} RmmClockTrace;
|
||||||
|
_Static_assert(sizeof(RmmClockTrace) == 32, "Rust numeric diagnostic ABI");
|
||||||
|
|
||||||
|
/* Diagnostic source variant only. No strings/parameters leave this function. */
|
||||||
|
typedef struct {
|
||||||
|
uint32_t generating_component, status, detection_location, flags;
|
||||||
|
int32_t number_of_parameters;
|
||||||
|
} RmmClockEeRecord;
|
||||||
|
typedef struct {
|
||||||
|
uint32_t capture_attempted, start_status, next_status, end_status, count, limit_reached;
|
||||||
|
RmmClockEeRecord records[4];
|
||||||
|
} RmmClockEeInfo;
|
||||||
|
_Static_assert(sizeof(RmmClockEeRecord) == 20, "numeric EEInfo record ABI");
|
||||||
|
_Static_assert(sizeof(RmmClockEeInfo) == 104, "bounded four-record EEInfo ABI");
|
||||||
|
static void capture_eeinfo(RmmClockEeInfo *out) {
|
||||||
|
RPC_ERROR_ENUM_HANDLE enumeration = {0};
|
||||||
|
out->capture_attempted = 1;
|
||||||
|
out->start_status = RpcErrorStartEnumeration(&enumeration);
|
||||||
|
if (out->start_status != RPC_S_OK) return;
|
||||||
|
for (unsigned i = 0; i < 4; ++i) {
|
||||||
|
RPC_EXTENDED_ERROR_INFO info = {0};
|
||||||
|
info.Version = RPC_EEINFO_VERSION;
|
||||||
|
info.Flags = 0;
|
||||||
|
info.NumberOfParameters = MaxNumberOfEEInfoParams;
|
||||||
|
out->next_status = RpcErrorGetNextRecord(&enumeration, FALSE, &info);
|
||||||
|
if (out->next_status != RPC_S_OK) break;
|
||||||
|
RmmClockEeRecord *record = &out->records[out->count++];
|
||||||
|
record->generating_component = info.GeneratingComponent;
|
||||||
|
record->status = info.Status;
|
||||||
|
record->detection_location = info.DetectionLocation;
|
||||||
|
record->flags = info.Flags;
|
||||||
|
record->number_of_parameters = info.NumberOfParameters;
|
||||||
|
/* ComputerName and Parameters are neither copied nor dereferenced.
|
||||||
|
* CopyStrings=FALSE: RPC owns all borrowed fields until EndEnumeration. */
|
||||||
|
}
|
||||||
|
out->limit_reached = out->count == 4;
|
||||||
|
out->end_status = RpcErrorEndEnumeration(&enumeration);
|
||||||
|
}
|
||||||
|
|
||||||
|
static uint32_t invoke_status(RPC_BINDING_HANDLE binding, RmmClockStatus *out, RmmClockTrace *trace, RmmClockEeInfo *eeinfo) {
|
||||||
|
RMM_W32TIME_STATUS *status = NULL;
|
||||||
|
unsigned long result = 0;
|
||||||
|
Arena arena = {0};
|
||||||
|
if (trace) trace->stage = 50;
|
||||||
|
if (!result && !InitOnceExecuteOnce(&arena_once, initialize_arena, NULL, NULL)) result = ERROR_NOT_ENOUGH_MEMORY;
|
||||||
|
if (!result && TlsGetValue(arena_index)) result = ERROR_BUSY;
|
||||||
|
if (!result && !TlsSetValue(arena_index, &arena)) result = GetLastError();
|
||||||
|
if (!result) {
|
||||||
|
RpcTryExcept {
|
||||||
|
if (trace) trace->stage = 60;
|
||||||
|
result = RmmW32TimeQueryStatus(binding, &status);
|
||||||
|
if (trace) {
|
||||||
|
trace->stage = 61; trace->native_rpc_return_present = 1;
|
||||||
|
trace->native_rpc_return = result;
|
||||||
|
}
|
||||||
|
if (!result) {
|
||||||
|
if (trace) {
|
||||||
|
trace->stage = 62; trace->status_present = status != NULL;
|
||||||
|
if (status) {
|
||||||
|
trace->ul_size = status->ulSize; trace->c_entries = status->cEntries;
|
||||||
|
trace->p_entries_present = status->pEntries != NULL;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!status || status->ulSize != sizeof(*status) || status->cEntries || status->pEntries) {
|
||||||
|
if (trace) trace->stage = 70;
|
||||||
|
result = RPC_X_BAD_STUB_DATA;
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
if (trace) trace->stage = 80;
|
||||||
|
out->leap = status->eLeapIndicator; out->stratum = status->nStratum;
|
||||||
|
out->state = status->ulLcState; out->flags = status->ulTSFlags;
|
||||||
|
out->last_result = status->eLastSyncResult; out->size = status->ulSize;
|
||||||
|
out->last_sync = status->qwLastSyncTicks; out->sync_age = status->tpTimeLastGoodSync;
|
||||||
|
out->root_delay = status->toRootDelay; out->root_dispersion = status->tpRootDispersion;
|
||||||
|
out->phase = status->toSysPhaseOffset;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} RpcExcept(RpcExceptionFilter(RpcExceptionCode())) {
|
||||||
|
result = RpcExceptionCode();
|
||||||
|
if (eeinfo) capture_eeinfo(eeinfo); /* before any further RPC call */
|
||||||
|
if (trace) {trace->stage = 90; trace->rpc_exception = result;}
|
||||||
|
} RpcEndExcept
|
||||||
|
release_allocations(&arena);
|
||||||
|
TlsSetValue(arena_index, NULL);
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
static uint32_t pipe_query(RmmClockStatus *out, RmmClockTrace *trace, RmmClockEeInfo *eeinfo) {
|
||||||
|
RPC_WSTR text = NULL;
|
||||||
|
RPC_BINDING_HANDLE binding = NULL;
|
||||||
|
RPC_SECURITY_QOS qos = {0};
|
||||||
|
unsigned long result;
|
||||||
|
memset(out, 0, sizeof(*out));
|
||||||
|
if (trace) trace->stage = 10;
|
||||||
|
result = RpcStringBindingComposeW(NULL, (RPC_WSTR)L"ncacn_np", NULL,
|
||||||
|
(RPC_WSTR)L"\\pipe\\W32TIME_ALT", NULL, &text);
|
||||||
|
if (result) return result;
|
||||||
|
if (trace) trace->stage = 20;
|
||||||
|
result = RpcBindingFromStringBindingW(text, &binding);
|
||||||
|
RpcStringFreeW(&text);
|
||||||
|
if (result) return result;
|
||||||
|
qos.Version = RPC_C_SECURITY_QOS_VERSION;
|
||||||
|
qos.Capabilities = RPC_C_QOS_CAPABILITIES_DEFAULT;
|
||||||
|
qos.IdentityTracking = RPC_C_QOS_IDENTITY_STATIC;
|
||||||
|
qos.ImpersonationType = RPC_C_IMP_LEVEL_IDENTIFY;
|
||||||
|
if (trace) trace->stage = 30;
|
||||||
|
result = RpcBindingSetAuthInfoExW(binding, NULL, RPC_C_AUTHN_LEVEL_PKT_PRIVACY,
|
||||||
|
RPC_C_AUTHN_WINNT, NULL, RPC_C_AUTHZ_NONE, &qos);
|
||||||
|
if (!result) {
|
||||||
|
if (trace) trace->stage = 40;
|
||||||
|
result = RpcBindingSetOption(binding, RPC_C_OPT_CALL_TIMEOUT, 1500);
|
||||||
|
}
|
||||||
|
if (!result) result = invoke_status(binding, out, trace, eeinfo);
|
||||||
|
RpcBindingFree(&binding);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
uint32_t rmm_clock_query(RmmClockStatus *out) { return pipe_query(out, NULL, NULL); }
|
||||||
|
uint32_t rmm_clock_query_trace(RmmClockTrace *trace) {
|
||||||
|
RmmClockStatus ignored = {0};
|
||||||
|
memset(trace, 0, sizeof(*trace));
|
||||||
|
return pipe_query(&ignored, trace, NULL);
|
||||||
|
}
|
||||||
|
/* Kernel-authenticated ALPC only. No automatic fallback to named pipes.
|
||||||
|
* The expected SID is fixed locally, never adopted from endpoint metadata.
|
||||||
|
*/
|
||||||
|
static uint32_t alpc_query(RmmClockStatus *out, unsigned control) {
|
||||||
|
RPC_IF_ID id = {0};
|
||||||
|
RPC_EP_INQ_HANDLE inquiry = NULL;
|
||||||
|
RPC_STATUS result;
|
||||||
|
memset(out, 0, sizeof(*out));
|
||||||
|
result = UuidFromStringW((RPC_WSTR)L"8fb6d884-2388-11d0-8c35-00c04fda2795", &id.Uuid);
|
||||||
|
if (result) return result;
|
||||||
|
id.VersMajor = 4; id.VersMinor = 1;
|
||||||
|
result = RpcMgmtEpEltInqBegin(NULL, RPC_C_EP_MATCH_BY_IF, &id, RPC_C_VERS_EXACT, NULL, &inquiry);
|
||||||
|
if (result) return result;
|
||||||
|
for (unsigned i=0; i<16; ++i) {
|
||||||
|
RPC_IF_ID actual = {0};
|
||||||
|
RPC_BINDING_HANDLE binding = NULL;
|
||||||
|
UUID object = {0};
|
||||||
|
RPC_WSTR annotation = NULL, text = NULL, protocol = NULL;
|
||||||
|
result = RpcMgmtEpEltInqNextW(inquiry, &actual, &binding, &object, &annotation);
|
||||||
|
if (annotation) RpcStringFreeW(&annotation);
|
||||||
|
if (result) break;
|
||||||
|
result = RpcBindingToStringBindingW(binding, &text);
|
||||||
|
if (!result) result = RpcStringBindingParseW(text, NULL, &protocol, NULL, NULL, NULL);
|
||||||
|
int local = !result && !wcscmp((wchar_t *)protocol, L"ncalrpc");
|
||||||
|
if (protocol) RpcStringFreeW(&protocol);
|
||||||
|
if (text) RpcStringFreeW(&text);
|
||||||
|
if (result) {RpcBindingFree(&binding);break;}
|
||||||
|
if (local) {
|
||||||
|
_Alignas(8) BYTE expected_sid[SECURITY_MAX_SID_SIZE];
|
||||||
|
_Alignas(8) BYTE service_sid[SECURITY_MAX_SID_SIZE];
|
||||||
|
_Alignas(8) BYTE acl_buffer[sizeof(ACL) + sizeof(ACCESS_ALLOWED_ACE) + SECURITY_MAX_SID_SIZE];
|
||||||
|
SECURITY_DESCRIPTOR descriptor;
|
||||||
|
WCHAR domain[64];
|
||||||
|
DWORD domain_size = sizeof(domain) / sizeof(domain[0]);
|
||||||
|
DWORD service_sid_size = sizeof(service_sid);
|
||||||
|
SID_NAME_USE sid_type;
|
||||||
|
DWORD sid_size = sizeof(expected_sid);
|
||||||
|
RmmRpcQosV5 qos = {0};
|
||||||
|
/* An account-only SID19 binding also accepts other LocalService
|
||||||
|
* processes, including our network agent. The client-owned V5
|
||||||
|
* descriptor therefore requires the separate W32Time service SID.
|
||||||
|
* No descriptor/identity is obtained from endpoint metadata.
|
||||||
|
* Controls are fixed read-only diagnostics, never production modes.
|
||||||
|
*/
|
||||||
|
if (!CreateWellKnownSid(control == 1 ? WinLocalSystemSid : WinLocalServiceSid,
|
||||||
|
NULL, expected_sid, &sid_size)) result = GetLastError();
|
||||||
|
if (!result && !LookupAccountNameW(NULL,
|
||||||
|
control == 2 ? L"NT SERVICE\\RmmDiscoveryWindows" : L"NT SERVICE\\W32Time",
|
||||||
|
service_sid, &service_sid_size, domain, &domain_size, &sid_type)) result = GetLastError();
|
||||||
|
if (!result && (!IsValidSid(service_sid) || service_sid_size > sizeof(service_sid))) result = ERROR_INVALID_SID;
|
||||||
|
if (!result && !InitializeAcl((PACL)acl_buffer, sizeof(acl_buffer), ACL_REVISION)) result = GetLastError();
|
||||||
|
if (!result && !AddAccessAllowedAce((PACL)acl_buffer, ACL_REVISION, GENERIC_ALL, service_sid)) result = GetLastError();
|
||||||
|
if (!result && !InitializeSecurityDescriptor(&descriptor, SECURITY_DESCRIPTOR_REVISION)) result = GetLastError();
|
||||||
|
if (!result && !SetSecurityDescriptorDacl(&descriptor, TRUE, (PACL)acl_buffer, FALSE)) result = GetLastError();
|
||||||
|
if (!result) {
|
||||||
|
qos.Version = 5; /* RPC_C_SECURITY_QOS_VERSION_5 */
|
||||||
|
qos.Capabilities = RPC_C_QOS_CAPABILITIES_MUTUAL_AUTH;
|
||||||
|
qos.IdentityTracking = RPC_C_QOS_IDENTITY_STATIC;
|
||||||
|
qos.ImpersonationType = RPC_C_IMP_LEVEL_IDENTIFY;
|
||||||
|
qos.Sid = expected_sid;
|
||||||
|
qos.EffectiveOnly = TRUE;
|
||||||
|
qos.ServerSecurityDescriptor = &descriptor;
|
||||||
|
result = RpcBindingSetAuthInfoExW(binding, NULL, RPC_C_AUTHN_LEVEL_PKT_PRIVACY,
|
||||||
|
RPC_C_AUTHN_WINNT, NULL, RPC_C_AUTHZ_NONE, (RPC_SECURITY_QOS *)&qos);
|
||||||
|
if (!result) result = invoke_status(binding, out, NULL, NULL);
|
||||||
|
}
|
||||||
|
RpcBindingFree(&binding);
|
||||||
|
break; /* no retry, alternate identity, endpoint or weaker transport */
|
||||||
|
}
|
||||||
|
RpcBindingFree(&binding);
|
||||||
|
result = EPT_S_NOT_REGISTERED;
|
||||||
|
}
|
||||||
|
RpcMgmtEpEltInqDone(&inquiry);
|
||||||
|
return result == RPC_X_NO_MORE_ENTRIES ? EPT_S_NOT_REGISTERED : result;
|
||||||
|
}
|
||||||
|
uint32_t rmm_clock_alpc_query(RmmClockStatus *out) { return alpc_query(out, 0); }
|
||||||
|
uint32_t rmm_clock_wrong_account(RmmClockStatus *out) { return alpc_query(out, 1); }
|
||||||
|
uint32_t rmm_clock_wrong_service(RmmClockStatus *out) { return alpc_query(out, 2); }
|
||||||
|
|
||||||
|
/* Exactly one original authenticated pipe query; EEInfo is observation only. */
|
||||||
|
uint32_t rmm_clock_query_trace_eeinfo(RmmClockTrace *trace, RmmClockEeInfo *eeinfo) {
|
||||||
|
RmmClockStatus ignored = {0};
|
||||||
|
memset(trace, 0, sizeof(*trace));
|
||||||
|
memset(eeinfo, 0, sizeof(*eeinfo));
|
||||||
|
return pipe_query(&ignored, trace, eeinfo);
|
||||||
|
}
|
||||||
@@ -0,0 +1,234 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Parent-only native SYSTEM trace bootstrap: prepare, once start, read, cleanup.
|
||||||
|
|
||||||
|
Readback is strictly read-only. Cleanup is a separate explicit phase and may
|
||||||
|
remove only this exact stopped diagnostic service. Never changes W32Time/RMM.
|
||||||
|
"""
|
||||||
|
import argparse
|
||||||
|
import base64
|
||||||
|
import datetime as dt
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
import re
|
||||||
|
import shlex
|
||||||
|
import stat
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import uuid
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parents[3]
|
||||||
|
HERE = Path(__file__).resolve().parent
|
||||||
|
STATE = ROOT / 'devstate/windows-clock-eeinfo-trace'
|
||||||
|
ACCESS_ROOT = Path('/home/kevin/Schreibtisch/Coding/rust-discovery')
|
||||||
|
|
||||||
|
|
||||||
|
def require(value,message):
|
||||||
|
if not value: raise RuntimeError(message)
|
||||||
|
|
||||||
|
|
||||||
|
def sha(path):
|
||||||
|
return hashlib.sha256(Path(path).read_bytes()).hexdigest()
|
||||||
|
|
||||||
|
|
||||||
|
def pairs(items):
|
||||||
|
result = {}
|
||||||
|
for name,value in items:
|
||||||
|
require(name not in result,'duplicate JSON key'); result[name] = value
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def private(path,directory=False):
|
||||||
|
item = Path(path).lstat()
|
||||||
|
require(item.st_uid == os.getuid() and stat.S_IMODE(item.st_mode) == (0o700 if directory else 0o600)
|
||||||
|
and (stat.S_ISDIR(item.st_mode) if directory else stat.S_ISREG(item.st_mode) and item.st_nlink == 1),'private owned path')
|
||||||
|
|
||||||
|
|
||||||
|
def load(path):
|
||||||
|
private(path); require(Path(path).stat().st_size <= 2*1024*1024,'bounded private JSON')
|
||||||
|
return json.loads(Path(path).read_bytes(),object_pairs_hook=pairs)
|
||||||
|
|
||||||
|
|
||||||
|
def save(path,value):
|
||||||
|
private(path.parent,True)
|
||||||
|
fd = os.open(path,os.O_CREAT|os.O_EXCL|os.O_WRONLY|os.O_NOFOLLOW,0o600)
|
||||||
|
with os.fdopen(fd,'w') as output:
|
||||||
|
json.dump(value,output,indent=2); output.flush(); os.fsync(output.fileno())
|
||||||
|
|
||||||
|
|
||||||
|
SCRIPT = r'''
|
||||||
|
$ErrorActionPreference='Stop';$p=([Console]::In.ReadLine()|ConvertFrom-Json)
|
||||||
|
$id=[guid]::ParseExact($p.id,'D').ToString()
|
||||||
|
if($id-cne$p.id-or$p.profile-cne'clock-system-eeinfo-v1'-or$p.action-notin@('prepare','start','readback','cleanup')-or$p.binary_sha256-notmatch'^[a-f0-9]{64}$'-or$p.manifest_sha256-notmatch'^[a-f0-9]{64}$'-or$p.script_sha256-notmatch'^[a-f0-9]{64}$'){throw 'Fixed SYSTEM diagnostic request'}
|
||||||
|
$root='C:\ProgramData\RustDiscoveryBootstrap';$name='RmmClockSystemEeInfoDiagnostic';$case=Join-Path $root ('clock-eeinfo-trace-'+$id);$exe=Join-Path $case 'ClockSystemEeInfoTrace.exe';$command='"'+$exe+'" --service '+$id
|
||||||
|
function Test-RmmTracePrivate($path,$dir){$i=Get-Item -LiteralPath $path -Force;if($i.PSIsContainer-ne$dir-or($i.Attributes-band[IO.FileAttributes]::ReparsePoint)){throw 'Private object type'};$a=Get-Acl -LiteralPath $path;if($a.GetOwner([Security.Principal.SecurityIdentifier]).Value-notin@('S-1-5-18','S-1-5-32-544')){throw 'Private object owner'};$rules=@($a.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier]));if(!$rules.Count){throw 'Empty private ACL'};foreach($e in $rules){if($e.AccessControlType-ne'Allow'-or$e.IdentityReference.Value-notin@('S-1-5-18','S-1-5-32-544')-or($e.PropagationFlags-band[Security.AccessControl.PropagationFlags]::InheritOnly)){throw 'Broad private ACL'}}}
|
||||||
|
function Write-RmmTraceNew($path,$value){$f=[IO.File]::Open($path,[IO.FileMode]::CreateNew,[IO.FileAccess]::Write,[IO.FileShare]::Read);try{$b=[Text.Encoding]::UTF8.GetBytes(($value|ConvertTo-Json -Depth 12 -Compress));$f.Write($b,0,$b.Length);$f.Flush($true)}finally{$f.Dispose()}}
|
||||||
|
function Get-RmmTraceJson($path){Test-RmmTracePrivate $path $false;if((Get-Item -LiteralPath $path).Length-gt16384){throw 'Small diagnostic receipt'};return(Get-Content -LiteralPath $path -Raw|ConvertFrom-Json)}
|
||||||
|
function Get-RmmTraceService{return(Get-CimInstance Win32_Service -Filter "Name='RmmClockSystemEeInfoDiagnostic'" -OperationTimeoutSec 5)}
|
||||||
|
function Test-RmmTraceService($s){if($s-and($s.PathName-cne$command-or$s.StartName-cne'LocalSystem'-or$s.StartMode-cne'Manual')){throw 'Only own exact temporary service'}}
|
||||||
|
if($p.action-eq'readback'-and!(Test-Path -LiteralPath $case)){@{id=$id;status='remote_case_absent';read_only=$true}|ConvertTo-Json -Compress;exit 0}
|
||||||
|
Test-RmmTracePrivate $root $true
|
||||||
|
if($p.action-eq'prepare'){if((Test-Path -LiteralPath $case)-or(Get-RmmTraceService)){throw 'Existing case/service retained'};New-Item -ItemType Directory -Path $case|Out-Null;Test-RmmTracePrivate $case $true;Write-RmmTraceNew (Join-Path $case 'intent.json') $p;@{id=$id;prepared=$true}|ConvertTo-Json -Compress;exit 0}
|
||||||
|
Test-RmmTracePrivate $case $true;$old=Get-RmmTraceJson (Join-Path $case 'intent.json')
|
||||||
|
foreach($field in @('id','profile','binary_sha256','manifest_sha256','script_sha256','binary_bytes')){if($old.$field-cne$p.$field){throw 'Original exact diagnostic intent'}}
|
||||||
|
Test-RmmTracePrivate $exe $false;if((Get-Item -LiteralPath $exe).Length-ne$p.binary_bytes-or(Get-FileHash -LiteralPath $exe -Algorithm SHA256).Hash.ToLowerInvariant()-cne$p.binary_sha256){throw 'Exact diagnostic executable'}
|
||||||
|
$s=Get-RmmTraceService;Test-RmmTraceService $s
|
||||||
|
if($p.action-eq'start'){
|
||||||
|
if($s-or(Test-Path -LiteralPath (Join-Path $case 'start-intent.json'))){throw 'No repeated start; original readback only'}
|
||||||
|
Write-RmmTraceNew (Join-Path $case 'start-intent.json') @{id=$id;command=$command;binary_sha256=$p.binary_sha256;create_once=$true}
|
||||||
|
New-Service -Name $name -BinaryPathName $command -StartupType Manual|Out-Null
|
||||||
|
$s=Get-RmmTraceService;Test-RmmTraceService $s;if(!$s){throw 'Own service creation missing'}
|
||||||
|
Write-RmmTraceNew (Join-Path $case 'service-created.json') @{id=$id;command=$command;start_name=$s.StartName}
|
||||||
|
Write-RmmTraceNew (Join-Path $case 'service-start-intent.json') @{start_once=$true}
|
||||||
|
Start-Service -Name $name
|
||||||
|
$deadline=[DateTime]::UtcNow.AddSeconds(20)
|
||||||
|
do{$s=Get-RmmTraceService;Test-RmmTraceService $s;if(!$s-or$s.State-eq'Stopped'){break};Start-Sleep -Milliseconds 100}while([DateTime]::UtcNow-lt$deadline)
|
||||||
|
}
|
||||||
|
if($p.action-eq'cleanup'){
|
||||||
|
if(!$s){if(!(Test-Path -LiteralPath (Join-Path $case 'cleanup-intent.json'))){throw 'Missing service without bound cleanup'};@{id=$id;cleanup_verified=$true;already_absent=$true;read_only=$true}|ConvertTo-Json -Compress;exit 0}
|
||||||
|
if($s.State-cne'Stopped'){throw 'Cleanup only own bound stopped service'}
|
||||||
|
$created=Get-RmmTraceJson (Join-Path $case 'service-created.json');if($created.id-cne$id-or$created.command-cne$command-or$created.start_name-cne'LocalSystem'){throw 'Original service creation binding'}
|
||||||
|
if(Test-Path -LiteralPath (Join-Path $case 'cleanup-intent.json')){throw 'Cleanup already attempted; readback only'}
|
||||||
|
Write-RmmTraceNew (Join-Path $case 'cleanup-intent.json') @{id=$id;command=$command;delete_once=$true}
|
||||||
|
& "$env:WINDIR\System32\sc.exe" delete $name|Out-Null;if($LASTEXITCODE-ne0){throw 'Own stopped service deletion incomplete'}
|
||||||
|
if(Get-RmmTraceService){throw 'Own service still registered; readback only'}
|
||||||
|
Write-RmmTraceNew (Join-Path $case 'cleanup-completed.json') @{id=$id;service_absent=$true}
|
||||||
|
@{id=$id;cleanup_verified=$true;already_absent=$false;read_only=$false}|ConvertTo-Json -Compress;exit 0
|
||||||
|
}
|
||||||
|
$report=$null;$result=Join-Path $case 'result.json';if(Test-Path -LiteralPath $result){$report=Get-RmmTraceJson $result}
|
||||||
|
$cleaned=$false;$cleanupReceipt=Join-Path $case 'cleanup-completed.json';if(Test-Path -LiteralPath $cleanupReceipt){$c=Get-RmmTraceJson $cleanupReceipt;if($c.id-cne$id-or$c.service_absent-ne$true){throw 'Bound cleanup receipt'};$cleaned=$true}
|
||||||
|
@{id=$id;service_present=[bool]$s;service_state=$(if($s){$s.State}else{$null});service_exit_code=$(if($s){$s.ExitCode}else{$null});start_intent_present=(Test-Path -LiteralPath (Join-Path $case 'service-start-intent.json'));cleanup_intent_present=(Test-Path -LiteralPath (Join-Path $case 'cleanup-intent.json'));cleanup_completed=$cleaned;report=$report;read_only=($p.action-eq'readback');no_rmm_jobs=$true;no_w32time_change=$true;no_agent_change=$true}|ConvertTo-Json -Depth 12 -Compress
|
||||||
|
'''
|
||||||
|
|
||||||
|
|
||||||
|
def encoded_command():
|
||||||
|
script = 'try {\n'+SCRIPT+'\n} catch {[pscustomobject]@{bootstrap_error=$true;error_id=$_.FullyQualifiedErrorId;line=$_.InvocationInfo.ScriptLineNumber}|ConvertTo-Json -Compress;exit 1}'
|
||||||
|
return 'powershell.exe -NoLogo -NoProfile -NonInteractive -EncodedCommand '+base64.b64encode(script.encode('utf-16le')).decode()
|
||||||
|
|
||||||
|
|
||||||
|
def manifest(path):
|
||||||
|
path = path.absolute(); private(path.parent,True)
|
||||||
|
require(path.name == 'manifest.json' and path.parent.parent == STATE and re.fullmatch(r'build-[0-9a-f-]{36}',path.parent.name),'fixed local build manifest')
|
||||||
|
value = load(path)
|
||||||
|
require(value['profile'] == 'clock-system-eeinfo-v1' and value['schema_version'] == 1
|
||||||
|
and value['native_executed'] is False and value['clock_qualified'] is False and value['product_gate_open'] is False
|
||||||
|
and value['powershell_ast_passed'] is True and value['encoded_command_characters'] == len(encoded_command()) < 32767
|
||||||
|
and value['script_sha256'] == hashlib.sha256(SCRIPT.encode()).hexdigest(),'same reviewed nonqualifying diagnostic source')
|
||||||
|
require(value['original_wrapper_sha256'] == '74aceb6e2b70c5dd628fae069a842c356c20300b8c8ab12754258c78eaf295c8'
|
||||||
|
and sha(path.parent / 'wrapper-source.diff') == value['wrapper_diff_sha256'],'same exact observational source delta')
|
||||||
|
for name,digest in value['own_sources'].items():require(sha(ROOT / name) == digest,'same original local driver source')
|
||||||
|
for name in ('artifact','linked'):
|
||||||
|
item=value[name];p=Path(item['path']);require(p.parent == path.parent / 'output','fixed retained PE path');private(p);require(sha(p) == item['sha256'],'retained exact diagnostic PE')
|
||||||
|
require(Path(value['artifact']['path']).stat().st_size == value['artifact']['bytes'],'exact PE size')
|
||||||
|
return value
|
||||||
|
|
||||||
|
|
||||||
|
def access(root):
|
||||||
|
require(root == ACCESS_ROOT and root.resolve() == root,'existing Main access root only')
|
||||||
|
sys.path.insert(0,str(ROOT / 'deploy'))
|
||||||
|
import vm_access_check
|
||||||
|
config = vm_access_check.load_config(root / 'credentials/server.conf')
|
||||||
|
require(config['address'] == '88.99.80.202' and config['username'] == 'root' and config.get('port','22') == '22','fixed existing cloud reverse jump')
|
||||||
|
record=load(root / 'credentials/windows-dev-access.json');expiry=dt.datetime.fromisoformat(record['expires_at'])
|
||||||
|
require(expiry.utcoffset() is not None and dt.datetime.now(dt.timezone.utc) < expiry,'current existing access only')
|
||||||
|
private(root / 'credentials',True);private(root / 'credentials/windows-dev.known_hosts')
|
||||||
|
key=str(Path(config['ssh_key_path']).expanduser())
|
||||||
|
jump=['ssh','-F','/dev/null','-T','-p','22','-i',key,'-o','StrictHostKeyChecking=yes','-o','BatchMode=yes','-o','ForwardAgent=no','-o','IdentitiesOnly=yes','-W','127.0.0.1:22240','root@88.99.80.202']
|
||||||
|
prefix=['ssh','-F','/dev/null','-T','-i',key,'-o','ProxyCommand='+shlex.join(jump),'-o','HostKeyAlias=rmm-windows-dev','-o','UserKnownHostsFile='+str(root / 'credentials/windows-dev.known_hosts'),'-o','GlobalKnownHostsFile=/dev/null','-o','StrictHostKeyChecking=yes','-o','BatchMode=yes','-o','IdentitiesOnly=yes','-o','ForwardAgent=no','-o','ConnectTimeout=10','rmm-dev@127.0.0.1']
|
||||||
|
require(record['ssh_prefix'] == prefix,'original pinned transport only')
|
||||||
|
return prefix
|
||||||
|
|
||||||
|
|
||||||
|
def run_transport(args,data,folder):
|
||||||
|
try:
|
||||||
|
done=subprocess.run(args,input=data,capture_output=True,timeout=50)
|
||||||
|
save(folder / ('transport-'+str(uuid.uuid4())+'.json'),dict(returncode=done.returncode,stdout_b64=base64.b64encode(done.stdout).decode(),stderr_b64=base64.b64encode(done.stderr).decode()))
|
||||||
|
require(done.returncode == 0,'transport incomplete; original readback only')
|
||||||
|
return done.stdout
|
||||||
|
except subprocess.TimeoutExpired as error:
|
||||||
|
save(folder / ('transport-timeout-'+str(uuid.uuid4())+'.json'),dict(timed_out=True,stdout_b64=base64.b64encode(error.stdout or b'').decode(),stderr_b64=base64.b64encode(error.stderr or b'').decode()))
|
||||||
|
raise RuntimeError('lost reply; no repeated operation') from None
|
||||||
|
|
||||||
|
|
||||||
|
def rpc(prefix,payload,folder):
|
||||||
|
value=json.loads(run_transport(prefix+[encoded_command()],(json.dumps(payload)+'\n').encode(),folder).decode('utf-8-sig'),object_pairs_hook=pairs)
|
||||||
|
require(isinstance(value,dict) and 'bootstrap_error' not in value,'remote diagnostic incomplete')
|
||||||
|
return value
|
||||||
|
|
||||||
|
|
||||||
|
def check_report(value,ident):
|
||||||
|
require(value['id'] == ident and value['no_rmm_jobs'] is True and value['no_w32time_change'] is True and value['no_agent_change'] is True,'exact nonproduct diagnostic case')
|
||||||
|
report=value.get('report')
|
||||||
|
if report is None:return False
|
||||||
|
require(report['schema_version'] == 1 and report['profile'] == 'clock-system-eeinfo-v1' and report['case_id'] == ident
|
||||||
|
and report['token_system'] is True and report['read_only'] is True and report['diagnostic_only'] is True
|
||||||
|
and report['query_invocations'] == 1 and report['clock_qualified'] is False and report['adapter_qualified'] is False
|
||||||
|
and report['product_gate_open'] is False,'actual SYSTEM token and single nonqualifying trace')
|
||||||
|
fields={'stage','native_rpc_return','native_rpc_return_present','rpc_exception','status_present','ul_size','c_entries','p_entries_present'}
|
||||||
|
require(set(report['trace']) == fields and type(report['rpc_code']) is int and 0 <= report['rpc_code'] < 2**32
|
||||||
|
and all(type(n) is int and 0 <= n < 2**32 for n in report['trace'].values()),'bounded numeric trace only')
|
||||||
|
ee=report['eeinfo']
|
||||||
|
require(set(ee) == {'capture_attempted','start_status','next_status','end_status','count','limit_reached','records'}
|
||||||
|
and all(type(ee[k]) is int and 0 <= ee[k] < 2**32 for k in ('capture_attempted','start_status','next_status','end_status','count','limit_reached'))
|
||||||
|
and ee['capture_attempted'] in (0,1) and 0 <= ee['count'] <= 4 and len(ee['records']) == ee['count']
|
||||||
|
and ee['limit_reached'] == int(ee['count'] == 4),'four-record numeric EEInfo budget')
|
||||||
|
record_fields={'generating_component','status','detection_location','flags','number_of_parameters'}
|
||||||
|
for record in ee['records']:
|
||||||
|
require(set(record) == record_fields and all(type(n) is int and 0 <= n < 2**32 for n in record.values())
|
||||||
|
and record['number_of_parameters'] <= 4,'numeric EEInfo fields only; no parameter contents')
|
||||||
|
if report['trace']['stage'] == 90:require(ee['capture_attempted'] == 1 and report['rpc_code'] == report['trace']['rpc_exception'],'original exception code preserved before immediate capture')
|
||||||
|
return (value['service_state'] == 'Stopped' and value['service_exit_code'] == 0) or (value['service_present'] is False and value['cleanup_completed'] is True)
|
||||||
|
|
||||||
|
|
||||||
|
def execute(action,path,root,ident):
|
||||||
|
os.umask(0o077);STATE.mkdir(mode=0o700,exist_ok=True);private(STATE,True)
|
||||||
|
value=manifest(path);prefix=access(root)
|
||||||
|
if action == 'prepare':
|
||||||
|
require(not ident,'new diagnostic case only');ident=str(uuid.uuid4());folder=STATE / ident;folder.mkdir(mode=0o700)
|
||||||
|
payload=dict(id=ident,profile='clock-system-eeinfo-v1',manifest_sha256=sha(path),binary_sha256=value['artifact']['sha256'],binary_bytes=value['artifact']['bytes'],script_sha256=value['script_sha256'])
|
||||||
|
save(folder / 'intent.json',dict(payload=payload,manifest_path=str(path.absolute()),access_root=str(root)))
|
||||||
|
print(json.dumps(dict(case_id=ident,prepare_once=True)),flush=True)
|
||||||
|
prepared=rpc(prefix,dict(payload,action='prepare'),folder);save(folder / 'prepared-remote.json',prepared);require(prepared == dict(id=ident,prepared=True),'new private remote case')
|
||||||
|
save(folder / 'upload-intent.json',dict(binary_sha256=payload['binary_sha256'],upload_once=True))
|
||||||
|
args=['sftp']+[p for p in prefix[1:-1] if p != '-T']+['-b','-',prefix[-1]]
|
||||||
|
destination='/C:/ProgramData/RustDiscoveryBootstrap/clock-eeinfo-trace-'+ident+'/ClockSystemEeInfoTrace.exe'
|
||||||
|
run_transport(args,('put '+json.dumps(value['artifact']['path'])+' '+json.dumps(destination)+'\n').encode(),folder)
|
||||||
|
save(folder / 'upload-completed.json',dict(uploaded=True));print(json.dumps(dict(case_id=ident,prepared=True,service_started=False)));return
|
||||||
|
require(str(uuid.UUID(ident)) == ident,'canonical original case')
|
||||||
|
folder=STATE / ident;private(folder,True);original=load(folder / 'intent.json');payload=original['payload']
|
||||||
|
require(original['manifest_path'] == str(path.absolute()) and original['access_root'] == str(root)
|
||||||
|
and payload['manifest_sha256'] == sha(path) and payload['script_sha256'] == value['script_sha256'],'original same-case input tuple')
|
||||||
|
if action in ('start','cleanup'):
|
||||||
|
if action == 'start':require(load(folder / 'upload-completed.json')['uploaded'] is True,'completed original upload')
|
||||||
|
save(folder / (action+'-intent.json'),dict(action=action,once=True))
|
||||||
|
result=rpc(prefix,dict(payload,action=action),folder);save(folder / ('readback-'+str(uuid.uuid4())+'.json'),result)
|
||||||
|
if action == 'cleanup':
|
||||||
|
require(result.get('id') == ident and result.get('cleanup_verified') is True,'own stopped service cleanup only')
|
||||||
|
print(json.dumps(dict(case_id=ident,cleanup_verified=True)));return
|
||||||
|
if result.get('status'):
|
||||||
|
require(action == 'readback' and result['status'] == 'remote_case_absent','read-only original partial status')
|
||||||
|
print(json.dumps(dict(case_id=ident,complete=False,retry_allowed=False)));return
|
||||||
|
complete=check_report(result,ident)
|
||||||
|
if complete:
|
||||||
|
destination=folder / 'diagnostic-result.json'
|
||||||
|
receipt=dict(complete=True,manifest_sha256=sha(path),actual=result,clock_qualified=False,product_gate_open=False)
|
||||||
|
if destination.exists():require(load(destination)['actual']['report'] == result['report'],'preserve original numeric report')
|
||||||
|
else:save(destination,receipt)
|
||||||
|
print(json.dumps(dict(case_id=ident,diagnostic_complete=complete,rpc_code=result['report']['rpc_code'] if complete else None,
|
||||||
|
stage=result['report']['trace']['stage'] if complete else None,eeinfo_count=result['report']['eeinfo']['count'] if complete else None,clock_qualified=False,cleanup_separate=True)))
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('action',choices=('prepare','start','readback','cleanup'))
|
||||||
|
parser.add_argument('--manifest',type=Path,required=True);parser.add_argument('--access-root',type=Path,required=True);parser.add_argument('--id')
|
||||||
|
parser.add_argument('--execute-native',action='store_true');args=parser.parse_args()
|
||||||
|
require((args.action == 'readback' and not args.execute_native) or (args.action != 'readback' and args.execute_native),'explicit native effect phase; readback only reads')
|
||||||
|
execute(args.action,args.manifest,args.access_root,args.id)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
try:main()
|
||||||
|
except Exception as error:
|
||||||
|
print(json.dumps(dict(error='CLOCK_SYSTEM_TRACE_NATIVE_INCOMPLETE',error_class=type(error).__name__,details_suppressed=True)))
|
||||||
|
raise SystemExit(2) from None
|
||||||
@@ -0,0 +1,135 @@
|
|||||||
|
/* Standalone diagnostic only. The original C/Auth/MIDL inputs are linked
|
||||||
|
* unchanged. Exactly one trace query, only under this process's SYSTEM token.
|
||||||
|
* No clock setter, token impersonation, NTP/ACL/provider or product gate. */
|
||||||
|
#define _WIN32_WINNT 0x0a00
|
||||||
|
#include <windows.h>
|
||||||
|
#include <stdint.h>
|
||||||
|
#include <stdio.h>
|
||||||
|
#include <wchar.h>
|
||||||
|
|
||||||
|
typedef struct {
|
||||||
|
uint32_t stage, native_rpc_return, native_rpc_return_present, rpc_exception;
|
||||||
|
uint32_t status_present, ul_size, c_entries, p_entries_present;
|
||||||
|
} RmmClockTrace;
|
||||||
|
_Static_assert(sizeof(RmmClockTrace) == 32, "same diagnostic trace ABI");
|
||||||
|
typedef struct {
|
||||||
|
uint32_t generating_component, status, detection_location, flags;
|
||||||
|
int32_t number_of_parameters;
|
||||||
|
} RmmClockEeRecord;
|
||||||
|
typedef struct {
|
||||||
|
uint32_t capture_attempted, start_status, next_status, end_status, count, limit_reached;
|
||||||
|
RmmClockEeRecord records[4];
|
||||||
|
} RmmClockEeInfo;
|
||||||
|
_Static_assert(sizeof(RmmClockEeInfo) == 104, "same four-record numeric EEInfo ABI");
|
||||||
|
uint32_t rmm_clock_query_trace_eeinfo(RmmClockTrace *trace, RmmClockEeInfo *eeinfo);
|
||||||
|
|
||||||
|
static WCHAR service_name[] = L"RmmClockSystemEeInfoDiagnostic";
|
||||||
|
static WCHAR case_id[37];
|
||||||
|
static SERVICE_STATUS_HANDLE status_handle;
|
||||||
|
static SERVICE_STATUS service_status;
|
||||||
|
|
||||||
|
static DWORD WINAPI control(DWORD event, DWORD type, void *data, void *context) {
|
||||||
|
(void)event; (void)type; (void)data; (void)context;
|
||||||
|
return ERROR_CALL_NOT_IMPLEMENTED;
|
||||||
|
}
|
||||||
|
|
||||||
|
static DWORD own_system_token(void) {
|
||||||
|
HANDLE token = NULL;
|
||||||
|
DWORD needed = 0, result = ERROR_SUCCESS;
|
||||||
|
_Alignas(8) BYTE storage[4096];
|
||||||
|
if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &token)) return GetLastError();
|
||||||
|
if (!GetTokenInformation(token, TokenUser, storage, sizeof(storage), &needed)) result = GetLastError();
|
||||||
|
else if (needed > sizeof(storage) || !IsWellKnownSid(((TOKEN_USER *)storage)->User.Sid, WinLocalSystemSid)) result = ERROR_ACCESS_DENIED;
|
||||||
|
CloseHandle(token);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
static DWORD write_result(uint32_t rpc, const RmmClockTrace *trace, const RmmClockEeInfo *eeinfo) {
|
||||||
|
WCHAR path[256];
|
||||||
|
char id[37], report[4096];
|
||||||
|
DWORD written = 0, result = ERROR_SUCCESS;
|
||||||
|
for (unsigned i = 0; i < 37; ++i) id[i] = (char)case_id[i];
|
||||||
|
int count = swprintf(path, sizeof(path) / sizeof(path[0]),
|
||||||
|
L"C:\\ProgramData\\RustDiscoveryBootstrap\\clock-eeinfo-trace-%ls\\result.json", case_id);
|
||||||
|
if (count <= 0 || count >= (int)(sizeof(path) / sizeof(path[0]))) return ERROR_INVALID_PARAMETER;
|
||||||
|
count = snprintf(report, sizeof(report),
|
||||||
|
"{\"schema_version\":1,\"profile\":\"clock-system-eeinfo-v1\",\"case_id\":\"%s\","
|
||||||
|
"\"token_system\":true,\"read_only\":true,\"diagnostic_only\":true,\"query_invocations\":1,"
|
||||||
|
"\"clock_qualified\":false,\"adapter_qualified\":false,\"product_gate_open\":false,\"rpc_code\":%lu,"
|
||||||
|
"\"trace\":{\"stage\":%lu,\"native_rpc_return\":%lu,\"native_rpc_return_present\":%lu,"
|
||||||
|
"\"rpc_exception\":%lu,\"status_present\":%lu,\"ul_size\":%lu,\"c_entries\":%lu,\"p_entries_present\":%lu}}\n",
|
||||||
|
id, (unsigned long)rpc, (unsigned long)trace->stage,
|
||||||
|
(unsigned long)trace->native_rpc_return, (unsigned long)trace->native_rpc_return_present,
|
||||||
|
(unsigned long)trace->rpc_exception, (unsigned long)trace->status_present,
|
||||||
|
(unsigned long)trace->ul_size, (unsigned long)trace->c_entries, (unsigned long)trace->p_entries_present);
|
||||||
|
if (count <= 0 || count >= (int)sizeof(report)) return ERROR_BUFFER_OVERFLOW;
|
||||||
|
if (count < 3 || eeinfo->count > 4) return ERROR_INVALID_DATA;
|
||||||
|
/* Replace only the final root-object closure; original trace stays intact. */
|
||||||
|
size_t used = (size_t)count - 2;
|
||||||
|
int appended = snprintf(report + used, sizeof(report) - used,
|
||||||
|
",\"eeinfo\":{\"capture_attempted\":%lu,\"start_status\":%lu,\"next_status\":%lu,"
|
||||||
|
"\"end_status\":%lu,\"count\":%lu,\"limit_reached\":%lu,\"records\":[",
|
||||||
|
(unsigned long)eeinfo->capture_attempted, (unsigned long)eeinfo->start_status,
|
||||||
|
(unsigned long)eeinfo->next_status, (unsigned long)eeinfo->end_status,
|
||||||
|
(unsigned long)eeinfo->count, (unsigned long)eeinfo->limit_reached);
|
||||||
|
if (appended <= 0 || (size_t)appended >= sizeof(report) - used) return ERROR_BUFFER_OVERFLOW;
|
||||||
|
used += (size_t)appended;
|
||||||
|
for (unsigned i = 0; i < eeinfo->count; ++i) {
|
||||||
|
const RmmClockEeRecord *record = &eeinfo->records[i];
|
||||||
|
appended = snprintf(report + used, sizeof(report) - used,
|
||||||
|
"%s{\"generating_component\":%lu,\"status\":%lu,\"detection_location\":%lu,"
|
||||||
|
"\"flags\":%lu,\"number_of_parameters\":%ld}", i ? "," : "",
|
||||||
|
(unsigned long)record->generating_component, (unsigned long)record->status,
|
||||||
|
(unsigned long)record->detection_location, (unsigned long)record->flags,
|
||||||
|
(long)record->number_of_parameters);
|
||||||
|
if (appended <= 0 || (size_t)appended >= sizeof(report) - used) return ERROR_BUFFER_OVERFLOW;
|
||||||
|
used += (size_t)appended;
|
||||||
|
}
|
||||||
|
appended = snprintf(report + used, sizeof(report) - used, "]}}\n");
|
||||||
|
if (appended <= 0 || (size_t)appended >= sizeof(report) - used) return ERROR_BUFFER_OVERFLOW;
|
||||||
|
used += (size_t)appended;
|
||||||
|
count = (int)used;
|
||||||
|
HANDLE file = CreateFileW(path, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_NEW,
|
||||||
|
FILE_ATTRIBUTE_NORMAL | FILE_FLAG_WRITE_THROUGH, NULL);
|
||||||
|
if (file == INVALID_HANDLE_VALUE) return GetLastError();
|
||||||
|
if (!WriteFile(file, report, (DWORD)count, &written, NULL) || written != (DWORD)count) result = ERROR_WRITE_FAULT;
|
||||||
|
else if (!FlushFileBuffers(file)) result = GetLastError();
|
||||||
|
CloseHandle(file);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
static void WINAPI run_service(DWORD argc, WCHAR **argv) {
|
||||||
|
(void)argc; (void)argv;
|
||||||
|
status_handle = RegisterServiceCtrlHandlerExW(service_name, control, NULL);
|
||||||
|
if (!status_handle) return;
|
||||||
|
ZeroMemory(&service_status, sizeof(service_status));
|
||||||
|
service_status.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
|
||||||
|
service_status.dwCurrentState = SERVICE_RUNNING;
|
||||||
|
service_status.dwControlsAccepted = 0;
|
||||||
|
if (!SetServiceStatus(status_handle, &service_status)) return;
|
||||||
|
DWORD result = own_system_token();
|
||||||
|
if (!result) {
|
||||||
|
RmmClockTrace trace = {0};
|
||||||
|
RmmClockEeInfo eeinfo = {0};
|
||||||
|
uint32_t rpc = rmm_clock_query_trace_eeinfo(&trace, &eeinfo); /* exactly one fixed call */
|
||||||
|
result = write_result(rpc, &trace, &eeinfo);
|
||||||
|
}
|
||||||
|
service_status.dwCurrentState = SERVICE_STOPPED;
|
||||||
|
service_status.dwWin32ExitCode = result;
|
||||||
|
SetServiceStatus(status_handle, &service_status);
|
||||||
|
}
|
||||||
|
|
||||||
|
int wmain(int argc, WCHAR **argv) {
|
||||||
|
if (argc != 3 || wcscmp(argv[1], L"--service") || wcslen(argv[2]) != 36) return ERROR_INVALID_PARAMETER;
|
||||||
|
for (unsigned i = 0; i < 36; ++i) {
|
||||||
|
WCHAR value = argv[2][i];
|
||||||
|
if (i == 8 || i == 13 || i == 18 || i == 23) {
|
||||||
|
if (value != L'-') return ERROR_INVALID_PARAMETER;
|
||||||
|
} else if (!((value >= L'0' && value <= L'9') || (value >= L'a' && value <= L'f'))) return ERROR_INVALID_PARAMETER;
|
||||||
|
case_id[i] = value;
|
||||||
|
}
|
||||||
|
case_id[36] = 0;
|
||||||
|
SERVICE_TABLE_ENTRYW table[] = {{service_name, run_service}, {NULL, NULL}};
|
||||||
|
if (!StartServiceCtrlDispatcherW(table)) return (int)GetLastError();
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
[workspace]
|
||||||
|
|
||||||
|
[package]
|
||||||
|
name = "rmm-clock-midl-diagnostic"
|
||||||
|
version = "0.1.0"
|
||||||
|
edition = "2024"
|
||||||
|
license = "AGPL-3.0-only"
|
||||||
|
autobins = false
|
||||||
|
|
||||||
|
[[bin]]
|
||||||
|
name = "clock-midl-readiness"
|
||||||
|
path = "../../../crates/agent-windows/examples/clock_readiness.rs"
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
anyhow = "1.0.100"
|
||||||
|
chrono = { version = "0.4.42", features = ["serde"] }
|
||||||
|
serde = { version = "1.0.228", features = ["derive"] }
|
||||||
|
serde_json = "1.0.145"
|
||||||
|
uuid = { version = "1.18.1", features = ["v4", "serde"] }
|
||||||
|
rmm-agent-core = { path = "../../../crates/agent-core" }
|
||||||
|
|
||||||
|
[build-dependencies]
|
||||||
|
cc = "=1.11.1"
|
||||||
|
sha2 = "0.10.9"
|
||||||
|
|
||||||
|
[target.'cfg(windows)'.dependencies]
|
||||||
|
windows-sys = { version = "0.61.2", features = ["Win32_Foundation", "Win32_Security", "Win32_Security_Authorization", "Win32_Storage_FileSystem", "Win32_System_IO", "Win32_System_JobObjects", "Win32_System_Pipes", "Win32_System_SystemInformation", "Win32_System_Registry", "Win32_System_Memory", "Win32_System_Services", "Win32_System_Threading"] }
|
||||||
@@ -0,0 +1,93 @@
|
|||||||
|
//! Separate diagnostic only: actual Microsoft outputs from native case 149bafe2.
|
||||||
|
//! No generator execution/fallback, NDR edits, header-version overrides or
|
||||||
|
//! modification of the product crate's build script/output directory.
|
||||||
|
use sha2::{Digest, Sha256};
|
||||||
|
use std::{env, fs, path::Path};
|
||||||
|
|
||||||
|
fn pinned(path: &Path, expected: &str) {
|
||||||
|
let bytes = fs::read(path).expect("missing pinned diagnostic input");
|
||||||
|
assert_eq!(
|
||||||
|
format!("{:x}", Sha256::digest(bytes)),
|
||||||
|
expected,
|
||||||
|
"diagnostic input changed: {}",
|
||||||
|
path.display()
|
||||||
|
);
|
||||||
|
println!("cargo:rerun-if-changed={}", path.display());
|
||||||
|
}
|
||||||
|
|
||||||
|
fn main() {
|
||||||
|
let here = env::current_dir().unwrap();
|
||||||
|
let root = here.join("../../..");
|
||||||
|
for (name, digest) in [
|
||||||
|
(
|
||||||
|
"examples/clock_readiness.rs",
|
||||||
|
"77433fafc9891ada53571bc070e33b9c9998379b7dadf48c1e19dc3851e44fe7",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"src/clock.rs",
|
||||||
|
"08b983095015cc7ba08ce08e9436d1519bf720c5501dd7af8b8b3dbae56b356f",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"native/clock_rpc.c",
|
||||||
|
"74aceb6e2b70c5dd628fae069a842c356c20300b8c8ab12754258c78eaf295c8",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"native/clock_endpoints.c",
|
||||||
|
"85c563bc8824bc30f7e80ef36e3dae5548c1f7a94faf5e882e98f275ab9a55e7",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"native/w32time.idl",
|
||||||
|
"37da4acb622daf9acf1aa6f1218ff9f52e5a2def14e58d8d9dd8da65078b3c6c",
|
||||||
|
),
|
||||||
|
] {
|
||||||
|
pinned(&root.join("crates/agent-windows").join(name), digest);
|
||||||
|
}
|
||||||
|
let generated = here.join("generated");
|
||||||
|
pinned(
|
||||||
|
&generated.join("w32time.h"),
|
||||||
|
"db5dbe5b335eaa58a6512d4abfda44e7273f3aa8a43077dcb0719e4b97ee2bde",
|
||||||
|
);
|
||||||
|
pinned(
|
||||||
|
&generated.join("w32time_c.c"),
|
||||||
|
"d806adb431f16724c8afdea0c0751588a4bc6f82b6f0b8391d4d189d6a6f4a38",
|
||||||
|
);
|
||||||
|
if env::var("CARGO_CFG_TARGET_OS").as_deref() != Ok("windows") {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
assert_eq!(env::var("TARGET").as_deref(), Ok("x86_64-pc-windows-gnu"));
|
||||||
|
// Microsoft guards its AMD64 stub using this architecture macro. Clang's
|
||||||
|
// GNU target does not predefine it. This declares the actual selected x64
|
||||||
|
// architecture; no SDK/RPCNDR version or _MSC_VER is fabricated.
|
||||||
|
cc::Build::new()
|
||||||
|
.compiler("clang")
|
||||||
|
.flag("--target=x86_64-w64-windows-gnu")
|
||||||
|
.flag("-fms-extensions")
|
||||||
|
.flag("-Werror")
|
||||||
|
.define("_M_AMD64", Some("100"))
|
||||||
|
.include(&generated)
|
||||||
|
.file(root.join("crates/agent-windows/native/clock_rpc.c"))
|
||||||
|
.file(root.join("crates/agent-windows/native/clock_endpoints.c"))
|
||||||
|
.compile("rmm_clock_rpc");
|
||||||
|
// MIDL's unchanged descriptor initializer uses legal C brace elision for
|
||||||
|
// MinGW's union field and emits two unused const tables. Keep these style
|
||||||
|
// warnings visible only for this pinned generated unit; do not edit NDR
|
||||||
|
// data, suppress type/security errors, or weaken wrapper diagnostics.
|
||||||
|
cc::Build::new()
|
||||||
|
.compiler("clang")
|
||||||
|
.flag("--target=x86_64-w64-windows-gnu")
|
||||||
|
.flag("-fms-extensions")
|
||||||
|
.flag("-Werror")
|
||||||
|
.flag("-Wno-error=missing-braces")
|
||||||
|
.flag("-Wno-error=unused-const-variable")
|
||||||
|
.define("_M_AMD64", Some("100"))
|
||||||
|
.include(&generated)
|
||||||
|
.file(generated.join("w32time_c.c"))
|
||||||
|
.compile("rmm_clock_midl_stub");
|
||||||
|
println!("cargo:rustc-link-lib=rpcrt4");
|
||||||
|
println!("cargo:rustc-link-lib=advapi32");
|
||||||
|
// The existing GNU readiness artifact imports both precise interrupt-time
|
||||||
|
// getters through the Windows realtime API set. This SDK's kernel32 import
|
||||||
|
// archive omits them; its mincore archive supplies those same OS imports.
|
||||||
|
// No clock implementation, API fallback or generated code is substituted.
|
||||||
|
println!("cargo:rustc-link-lib=mincore");
|
||||||
|
}
|
||||||
@@ -0,0 +1,186 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Local-only isolated process privilege comparison; never starts a target."""
|
||||||
|
import base64
|
||||||
|
import argparse
|
||||||
|
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-descriptor-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-identity-trace/build-3800fdd9-d959-4746-953b-4a110114214d/manifest.json'
|
||||||
|
PARENT_SHA = 'd3a6222da8aed64e4e5ad5c07993177a11f56af229d4754ea04f248ee79385bc'
|
||||||
|
PARENT_RESULT = ROOT / 'devstate/windows-clock-spnego-identity-trace/bcda2ede-d3e0-41bf-94e9-9f44ea785c54/diagnostic-result.json'
|
||||||
|
PARENT_RESULT_SHA = 'ce4004b1fd833b9590f23d31a918daefccf8870e6630be6beb28869fad1f8b5c'
|
||||||
|
UNCHANGED_DIAGNOSTICS = {
|
||||||
|
'deploy/windows/clock-spnego-identity-trace/clock_rpc_spnego_identity.c': '43654029550c0c99904d35c381f4abfbc7b4830f28db8b92ce19acdf6971a4cf',
|
||||||
|
'deploy/windows/clock-spnego-identity-trace/system_trace_spnego_identity.c': '39539b3994b134ec3bd2c1b0b4b7dbb548f397cfd49241f450744f94dc427784',
|
||||||
|
'deploy/windows/clock-spnego-identity-trace/build.py': 'cd0cf6710005f3be20e4e5a907c83164979c8bfc9c72a13f9a5e1674b4301f1e',
|
||||||
|
'deploy/windows/clock-spnego-identity-trace/native.py': '4d1362bec09d2c1c670b73364aa31fff613c29a125596e3e1ce30180b24ad332',
|
||||||
|
'deploy/windows/clock-spnego-impersonate-trace/clock_rpc_spnego_impersonate.c': '92c7a9a6e57bc199e7ae886a87398a6af98901a5affb888cd78ab5c5b3f7a59c',
|
||||||
|
'deploy/windows/clock-spnego-impersonate-trace/system_trace_spnego_impersonate.c': 'f855fe7d0a7e5bcec0138131d78bbad7b2098c9031b1a857bc8b68ef8f57cd94',
|
||||||
|
'deploy/windows/clock-spnego-impersonate-trace/build.py': 'b8de6616d7d7caa3c2c1307f6e216594ebb9455ceabe69e99c548ac927d2cb67',
|
||||||
|
'deploy/windows/clock-spnego-impersonate-trace/native.py': 'eeec0a83b7ee9cfed874df8ce4b44da05b5eec85a4cb2c8a775d2a032e6855a5',
|
||||||
|
'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_descriptor.c','system_trace_spnego_descriptor.c','build.py','native.py')}
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
parser=argparse.ArgumentParser();parser.add_argument("--control",type=int,choices=(0,1,2),required=True);args=parser.parse_args()
|
||||||
|
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_descriptor.c'
|
||||||
|
write(source / 'clock_rpc.c', wrapper.read_bytes()); write(source / 'system_trace.c', (HERE / 'system_trace_spnego_descriptor.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_descriptor.c'))
|
||||||
|
write(folder / 'wrapper-source.diff',delta.encode())
|
||||||
|
parent_wrapper = ROOT / 'deploy/windows/clock-spnego-identity-trace/clock_rpc_spnego_identity.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-descriptor.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_discovery_principal_allowed=True,null_discovery_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','-DRMM_CLOCK_IDENTITY_CONTROL='+str(args.control),'-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/ClockSpnegoDescriptorTrace.linked.exe'])
|
||||||
|
raw_linked = output / 'ClockSpnegoDescriptorTrace.linked.exe'
|
||||||
|
linked = output / 'ClockSpnegoDescriptorTrace.original.exe'; delivery = output / 'ClockSpnegoDescriptorTrace.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/ClockSpnegoDescriptorTrace.exe'])
|
||||||
|
imports = sorted(set(re.findall(r'DLL Name:\s+(\S+)',run('imports',['x86_64-w64-mingw32-objdump','-p','/out/ClockSpnegoDescriptorTrace.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-descriptor-v1',identity_control=args.control,qos_version=5,auth_principal_from_fixed_sid=False,auth_principal_from_discovery=True,client_server_descriptor=True,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_discovery_principal_allowed=True,null_discovery_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,300 @@
|
|||||||
|
/* 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>
|
||||||
|
#ifndef RMM_CLOCK_IDENTITY_CONTROL
|
||||||
|
#error fixed diagnostic identity control required
|
||||||
|
#endif
|
||||||
|
_Static_assert(RMM_CLOCK_IDENTITY_CONTROL >= 0 && RMM_CLOCK_IDENTITY_CONTROL <= 2, "closed identity controls");
|
||||||
|
|
||||||
|
#include <rpc.h>
|
||||||
|
#include <rpcasync.h>
|
||||||
|
#include <stdint.h>
|
||||||
|
#include <stddef.h>
|
||||||
|
#include <stdlib.h>
|
||||||
|
#include <string.h>
|
||||||
|
#include "w32time.h"
|
||||||
|
/* Older MinGW headers stop at V3. This is the documented x64 V5 SDK layout,
|
||||||
|
* not a fallback to an older authentication contract. MSVC also checks it
|
||||||
|
* directly against its native SDK declaration. Windows x64 is the only target.
|
||||||
|
* https://learn.microsoft.com/windows/win32/api/rpcdce/ns-rpcdce-rpc_security_qos_v5_w
|
||||||
|
*/
|
||||||
|
typedef struct {
|
||||||
|
unsigned long Version, Capabilities, IdentityTracking, ImpersonationType;
|
||||||
|
unsigned long AdditionalSecurityInfoType;
|
||||||
|
union { RPC_HTTP_TRANSPORT_CREDENTIALS_W *HttpCredentials; } u;
|
||||||
|
void *Sid;
|
||||||
|
unsigned int EffectiveOnly;
|
||||||
|
void *ServerSecurityDescriptor;
|
||||||
|
} RmmRpcQosV5;
|
||||||
|
_Static_assert(sizeof(RmmRpcQosV5) == 56, "x64 RPC QOS V5 ABI");
|
||||||
|
_Static_assert(offsetof(RmmRpcQosV5, Sid) == offsetof(RPC_SECURITY_QOS_V3_W, Sid), "SDK QOS prefix ABI");
|
||||||
|
_Static_assert(offsetof(RmmRpcQosV5, ServerSecurityDescriptor) == 48, "x64 server descriptor ABI");
|
||||||
|
#ifdef _MSC_VER
|
||||||
|
_Static_assert(sizeof(RmmRpcQosV5) == sizeof(RPC_SECURITY_QOS_V5_W), "native SDK QOS V5 ABI");
|
||||||
|
_Static_assert(offsetof(RmmRpcQosV5, ServerSecurityDescriptor) == offsetof(RPC_SECURITY_QOS_V5_W, ServerSecurityDescriptor), "native SDK descriptor ABI");
|
||||||
|
#endif
|
||||||
|
/* 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;
|
||||||
|
uint32_t qos_version, identity_control, server_descriptor_present;
|
||||||
|
} RmmClockAuthTrace;
|
||||||
|
_Static_assert(sizeof(RmmClockAuthTrace) == 72, "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;
|
||||||
|
RmmRpcQosV5 qos = {0};
|
||||||
|
_Alignas(8) BYTE account_sid[SECURITY_MAX_SID_SIZE], service_sid[SECURITY_MAX_SID_SIZE];
|
||||||
|
_Alignas(8) BYTE acl_buffer[sizeof(ACL)+sizeof(ACCESS_ALLOWED_ACE)+SECURITY_MAX_SID_SIZE];
|
||||||
|
SECURITY_DESCRIPTOR descriptor;
|
||||||
|
DWORD account_bytes=sizeof(account_sid),service_bytes=sizeof(service_sid),domain_bytes=64;
|
||||||
|
WCHAR domain[64];SID_NAME_USE sid_type;
|
||||||
|
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;
|
||||||
|
auth->qos_version=5;auth->identity_control=RMM_CLOCK_IDENTITY_CONTROL;
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
if(!result && !CreateWellKnownSid(RMM_CLOCK_IDENTITY_CONTROL==1?WinLocalSystemSid:WinLocalServiceSid,NULL,account_sid,&account_bytes))result=GetLastError();
|
||||||
|
if(!result && !LookupAccountNameW(NULL,RMM_CLOCK_IDENTITY_CONTROL==2?L"NT SERVICE\\RmmDiscoveryWindows":L"NT SERVICE\\W32Time",service_sid,&service_bytes,domain,&domain_bytes,&sid_type))result=GetLastError();
|
||||||
|
if(!result && (!IsValidSid(account_sid)||!IsValidSid(service_sid)||service_bytes>sizeof(service_sid)))result=ERROR_INVALID_SID;
|
||||||
|
if(!result && !InitializeAcl((PACL)acl_buffer,sizeof(acl_buffer),ACL_REVISION))result=GetLastError();
|
||||||
|
if(!result && !AddAccessAllowedAce((PACL)acl_buffer,ACL_REVISION,GENERIC_ALL,RMM_CLOCK_IDENTITY_CONTROL==1?account_sid:service_sid))result=GetLastError();
|
||||||
|
if(!result && !InitializeSecurityDescriptor(&descriptor,SECURITY_DESCRIPTOR_REVISION))result=GetLastError();
|
||||||
|
if(!result && !SetSecurityDescriptorDacl(&descriptor,TRUE,(PACL)acl_buffer,FALSE))result=GetLastError();
|
||||||
|
if(!result)auth->server_descriptor_present=1;
|
||||||
|
qos.Version = 5;
|
||||||
|
qos.Capabilities = RPC_C_QOS_CAPABILITIES_MUTUAL_AUTH;
|
||||||
|
qos.IdentityTracking = RPC_C_QOS_IDENTITY_STATIC;
|
||||||
|
qos.ImpersonationType = RPC_C_IMP_LEVEL_IMPERSONATE;
|
||||||
|
qos.Sid=NULL;qos.EffectiveOnly=TRUE;qos.ServerSecurityDescriptor=&descriptor;
|
||||||
|
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, (RPC_SECURITY_QOS *)&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_descriptor(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,348 @@
|
|||||||
|
#!/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-descriptor-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-descriptor-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='RmmClockSpnegoDescriptorDiagnostic';$case=Join-Path $root ('clock-spnego-descriptor-trace-'+$id);$exe=Join-Path $case 'ClockSpnegoDescriptorTrace.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='RmmClockSpnegoDescriptorDiagnostic'" -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-descriptor-v1' and value['schema_version'] == 1
|
||||||
|
and type(value['identity_control']) is int and value['identity_control'] in (0,1,2) and value['qos_version']==5 and value['auth_principal_from_fixed_sid'] is False and value['auth_principal_from_discovery'] is True and value['client_server_descriptor'] is True
|
||||||
|
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']=='d3a6222da8aed64e4e5ad5c07993177a11f56af229d4754ea04f248ee79385bc'
|
||||||
|
and value['parent_result_sha256']=='ce4004b1fd833b9590f23d31a918daefccf8870e6630be6beb28869fad1f8b5c'
|
||||||
|
and value['returned_empty_discovery_principal_allowed'] is True and value['null_discovery_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-descriptor-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','qos_version','identity_control','server_descriptor_present'}
|
||||||
|
and all(type(v) is int and 0<=v<2**32 for v in auth.values())
|
||||||
|
and auth['qos_version']==5 and auth['identity_control'] in (0,1,2) and auth['server_descriptor_present'] in (0,1)
|
||||||
|
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['server_descriptor_present']==1 and 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-descriptor-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-descriptor-trace-'+ident+'/ClockSpnegoDescriptorTrace.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 result.get("report") is not None:require(result["report"]["auth"]["identity_control"]==value["identity_control"],"actual compiled identity control matches original manifest")
|
||||||
|
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,501 @@
|
|||||||
|
/* 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>
|
||||||
|
#ifndef RMM_CLOCK_IDENTITY_CONTROL
|
||||||
|
#error fixed diagnostic identity control required
|
||||||
|
#endif
|
||||||
|
_Static_assert(RMM_CLOCK_IDENTITY_CONTROL >= 0 && RMM_CLOCK_IDENTITY_CONTROL <= 2, "closed identity controls");
|
||||||
|
|
||||||
|
#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;
|
||||||
|
uint32_t qos_version, identity_control, server_descriptor_present;
|
||||||
|
} RmmClockAuthTrace;
|
||||||
|
_Static_assert(sizeof(RmmClockAuthTrace) == 72, "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_descriptor(RmmClockTrace *trace, RmmClockEeInfo *eeinfo, RmmClockAuthTrace *auth);
|
||||||
|
|
||||||
|
static WCHAR service_name[] = L"RmmClockSpnegoDescriptorDiagnostic";
|
||||||
|
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-descriptor-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-descriptor-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,\"qos_version\":%lu,\"identity_control\":%lu,\"server_descriptor_present\":%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,(unsigned long)auth->qos_version,(unsigned long)auth->identity_control,(unsigned long)auth->server_descriptor_present);
|
||||||
|
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;auth.qos_version=5;auth.identity_control=RMM_CLOCK_IDENTITY_CONTROL;
|
||||||
|
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_descriptor(&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,166 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Local-only SPNEGO comparison: retain the returned non-NULL empty principal."""
|
||||||
|
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-empty-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-trace/build-2ebcfe9c-1e2b-4a50-99c5-3370640aeb77/manifest.json'
|
||||||
|
PARENT_SHA = 'f6b5cd23b1599c2db4fc803fd7232dfd3522dead840e492f659e4efd7a6be001'
|
||||||
|
PARENT_RESULT = ROOT / 'devstate/windows-clock-spnego-trace/0f512772-3599-4c83-b877-41c74fe50fb0/diagnostic-result.json'
|
||||||
|
PARENT_RESULT_SHA = '4c99b34b8c64f877dbbf0fe860d59499f1c054de7d036016e80b84581448cfc9'
|
||||||
|
UNCHANGED_DIAGNOSTICS = {
|
||||||
|
'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(PARENT_MANIFEST) == PARENT_SHA and sha(PARENT_RESULT) == PARENT_RESULT_SHA, 'original F6 and empty-principal 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_empty.c','system_trace_spnego_empty.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_empty.c'
|
||||||
|
write(source / 'clock_rpc.c', wrapper.read_bytes()); write(source / 'system_trace.c', (HERE / 'system_trace_spnego_empty.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_empty.c'))
|
||||||
|
write(folder / 'wrapper-source.diff',delta.encode())
|
||||||
|
parent_wrapper = ROOT / 'deploy/windows/clock-spnego-trace/clock_rpc_spnego.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-empty.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=True,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/ClockSpnegoEmptyTrace.linked.exe'])
|
||||||
|
raw_linked = output / 'ClockSpnegoEmptyTrace.linked.exe'
|
||||||
|
linked = output / 'ClockSpnegoEmptyTrace.original.exe'; delivery = output / 'ClockSpnegoEmptyTrace.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/ClockSpnegoEmptyTrace.exe'])
|
||||||
|
imports = sorted(set(re.findall(r'DLL Name:\s+(\S+)',run('imports',['x86_64-w64-mingw32-objdump','-p','/out/ClockSpnegoEmptyTrace.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 F6 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-empty-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=True,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_IDENTIFY;
|
||||||
|
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_IDENTIFY;
|
||||||
|
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_empty(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,272 @@
|
|||||||
|
#!/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-empty-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-empty-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='RmmClockSpnegoEmptyDiagnostic';$case=Join-Path $root ('clock-spnego-empty-trace-'+$id);$exe=Join-Path $case 'ClockSpnegoEmptyTrace.exe';$command='"'+$exe+'" --service '+$id
|
||||||
|
function Test-RmmTracePrivate($path,$dir){$i=Get-Item -LiteralPath $path -Force;if($i.PSIsContainer-ne$dir-or($i.Attributes-band[IO.FileAttributes]::ReparsePoint)){throw 'Private object type'};$a=Get-Acl -LiteralPath $path;if($a.GetOwner([Security.Principal.SecurityIdentifier]).Value-notin@('S-1-5-18','S-1-5-32-544')){throw 'Private object owner'};$rules=@($a.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier]));if(!$rules.Count){throw 'Empty private ACL'};foreach($e in $rules){if($e.AccessControlType-ne'Allow'-or$e.IdentityReference.Value-notin@('S-1-5-18','S-1-5-32-544')-or($e.PropagationFlags-band[Security.AccessControl.PropagationFlags]::InheritOnly)){throw 'Broad private ACL'}}}
|
||||||
|
function Write-RmmTraceNew($path,$value){$f=[IO.File]::Open($path,[IO.FileMode]::CreateNew,[IO.FileAccess]::Write,[IO.FileShare]::Read);try{$b=[Text.Encoding]::UTF8.GetBytes(($value|ConvertTo-Json -Depth 12 -Compress));$f.Write($b,0,$b.Length);$f.Flush($true)}finally{$f.Dispose()}}
|
||||||
|
function Get-RmmTraceJson($path){Test-RmmTracePrivate $path $false;if((Get-Item -LiteralPath $path).Length-gt16384){throw 'Small diagnostic receipt'};return(Get-Content -LiteralPath $path -Raw|ConvertFrom-Json)}
|
||||||
|
function Get-RmmTraceService{return(Get-CimInstance Win32_Service -Filter "Name='RmmClockSpnegoEmptyDiagnostic'" -OperationTimeoutSec 5)}
|
||||||
|
function Test-RmmTraceService($s){if($s-and($s.PathName-cne$command-or$s.StartName-cne'LocalSystem'-or$s.StartMode-cne'Manual')){throw 'Only own exact temporary service'}}
|
||||||
|
if($p.action-eq'readback'-and!(Test-Path -LiteralPath $case)){@{id=$id;status='remote_case_absent';read_only=$true}|ConvertTo-Json -Compress;exit 0}
|
||||||
|
Test-RmmTracePrivate $root $true
|
||||||
|
if($p.action-eq'prepare'){if((Test-Path -LiteralPath $case)-or(Get-RmmTraceService)){throw 'Existing case/service retained'};New-Item -ItemType Directory -Path $case|Out-Null;Test-RmmTracePrivate $case $true;Write-RmmTraceNew (Join-Path $case 'intent.json') $p;@{id=$id;prepared=$true}|ConvertTo-Json -Compress;exit 0}
|
||||||
|
Test-RmmTracePrivate $case $true;$old=Get-RmmTraceJson (Join-Path $case 'intent.json')
|
||||||
|
foreach($field in @('id','profile','binary_sha256','manifest_sha256','script_sha256','binary_bytes')){if($old.$field-cne$p.$field){throw 'Original exact diagnostic intent'}}
|
||||||
|
Test-RmmTracePrivate $exe $false;if((Get-Item -LiteralPath $exe).Length-ne$p.binary_bytes-or(Get-FileHash -LiteralPath $exe -Algorithm SHA256).Hash.ToLowerInvariant()-cne$p.binary_sha256){throw 'Exact diagnostic executable'}
|
||||||
|
$s=Get-RmmTraceService;Test-RmmTraceService $s
|
||||||
|
if($p.action-eq'start'){
|
||||||
|
if($s-or(Test-Path -LiteralPath (Join-Path $case 'start-intent.json'))){throw 'No repeated start; original readback only'}
|
||||||
|
Write-RmmTraceNew (Join-Path $case 'start-intent.json') @{id=$id;command=$command;binary_sha256=$p.binary_sha256;create_once=$true}
|
||||||
|
New-Service -Name $name -BinaryPathName $command -StartupType Manual|Out-Null
|
||||||
|
$s=Get-RmmTraceService;Test-RmmTraceService $s;if(!$s){throw 'Own service creation missing'}
|
||||||
|
Write-RmmTraceNew (Join-Path $case 'service-created.json') @{id=$id;command=$command;start_name=$s.StartName}
|
||||||
|
Write-RmmTraceNew (Join-Path $case 'service-start-intent.json') @{start_once=$true}
|
||||||
|
Start-Service -Name $name
|
||||||
|
$deadline=[DateTime]::UtcNow.AddSeconds(20)
|
||||||
|
do{$s=Get-RmmTraceService;Test-RmmTraceService $s;if(!$s-or$s.State-eq'Stopped'){break};Start-Sleep -Milliseconds 100}while([DateTime]::UtcNow-lt$deadline)
|
||||||
|
}
|
||||||
|
if($p.action-eq'cleanup'){
|
||||||
|
if(!$s){if(!(Test-Path -LiteralPath (Join-Path $case 'cleanup-intent.json'))){throw 'Missing service without bound cleanup'};@{id=$id;cleanup_verified=$true;already_absent=$true;read_only=$true}|ConvertTo-Json -Compress;exit 0}
|
||||||
|
if($s.State-cne'Stopped'){throw 'Cleanup only own bound stopped service'}
|
||||||
|
$created=Get-RmmTraceJson (Join-Path $case 'service-created.json');if($created.id-cne$id-or$created.command-cne$command-or$created.start_name-cne'LocalSystem'){throw 'Original service creation binding'}
|
||||||
|
if(Test-Path -LiteralPath (Join-Path $case 'cleanup-intent.json')){throw 'Cleanup already attempted; readback only'}
|
||||||
|
Write-RmmTraceNew (Join-Path $case 'cleanup-intent.json') @{id=$id;command=$command;delete_once=$true}
|
||||||
|
& "$env:WINDIR\System32\sc.exe" delete $name|Out-Null;if($LASTEXITCODE-ne0){throw 'Own stopped service deletion incomplete'}
|
||||||
|
if(Get-RmmTraceService){throw 'Own service still registered; readback only'}
|
||||||
|
Write-RmmTraceNew (Join-Path $case 'cleanup-completed.json') @{id=$id;service_absent=$true}
|
||||||
|
@{id=$id;cleanup_verified=$true;already_absent=$false;read_only=$false}|ConvertTo-Json -Compress;exit 0
|
||||||
|
}
|
||||||
|
$report=$null;$result=Join-Path $case 'result.json';if(Test-Path -LiteralPath $result){$report=Get-RmmTraceJson $result}
|
||||||
|
$token=$null;$tokenFile=Join-Path $case 'token.json';if(Test-Path -LiteralPath $tokenFile){$token=Get-RmmTraceJson $tokenFile}
|
||||||
|
$cleaned=$false;$cleanupReceipt=Join-Path $case 'cleanup-completed.json';if(Test-Path -LiteralPath $cleanupReceipt){$c=Get-RmmTraceJson $cleanupReceipt;if($c.id-cne$id-or$c.service_absent-ne$true){throw 'Bound cleanup receipt'};$cleaned=$true}
|
||||||
|
@{id=$id;service_present=[bool]$s;service_state=$(if($s){$s.State}else{$null});service_exit_code=$(if($s){$s.ExitCode}else{$null});start_intent_present=(Test-Path -LiteralPath (Join-Path $case 'service-start-intent.json'));cleanup_intent_present=(Test-Path -LiteralPath (Join-Path $case 'cleanup-intent.json'));cleanup_completed=$cleaned;report=$report;token_before_rpc=$token;read_only=($p.action-eq'readback');no_rmm_jobs=$true;no_w32time_change=$true;no_agent_change=$true}|ConvertTo-Json -Depth 12 -Compress
|
||||||
|
'''
|
||||||
|
|
||||||
|
|
||||||
|
def encoded_command():
|
||||||
|
script = 'try {\n'+SCRIPT+'\n} catch {[pscustomobject]@{bootstrap_error=$true;error_id=$_.FullyQualifiedErrorId;line=$_.InvocationInfo.ScriptLineNumber}|ConvertTo-Json -Compress;exit 1}'
|
||||||
|
return 'powershell.exe -NoLogo -NoProfile -NonInteractive -EncodedCommand '+base64.b64encode(script.encode('utf-16le')).decode()
|
||||||
|
|
||||||
|
|
||||||
|
def manifest(path):
|
||||||
|
path = path.absolute(); private(path.parent,True)
|
||||||
|
require(path.name == 'manifest.json' and path.parent.parent == STATE and re.fullmatch(r'build-[0-9a-f-]{36}',path.parent.name),'fixed local build manifest')
|
||||||
|
value = load(path)
|
||||||
|
require(value['profile'] == 'clock-system-spnego-empty-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 True and value['max_principal_discoveries']==value['max_status_queries']==1
|
||||||
|
and value['principal_identity_proven'] is False,'no privilege mutation/fallback or principal-as-identity claim')
|
||||||
|
require(value['parent_manifest_sha256']=='f6b5cd23b1599c2db4fc803fd7232dfd3522dead840e492f659e4efd7a6be001'
|
||||||
|
and value['parent_result_sha256']=='4c99b34b8c64f877dbbf0fe860d59499f1c054de7d036016e80b84581448cfc9'
|
||||||
|
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 F6 comparison, returned non-NULL string only; no fabricated target or 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_report(value,ident):
|
||||||
|
require(value['id'] == ident and value['no_rmm_jobs'] is True and value['no_w32time_change'] is True and value['no_agent_change'] is True,'exact nonproduct diagnostic case')
|
||||||
|
report=value.get('report')
|
||||||
|
if report is None:return False
|
||||||
|
require(report['schema_version'] == 1 and report['profile'] == 'clock-system-spnego-empty-v1' and report['case_id'] == ident
|
||||||
|
and report['token_system'] is True and report['read_only'] is True and report['diagnostic_only'] is True
|
||||||
|
and 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']==2
|
||||||
|
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)
|
||||||
|
|
||||||
|
|
||||||
|
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-empty-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-empty-trace-'+ident+'/ClockSpnegoEmptyTrace.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,233 @@
|
|||||||
|
/* Isolated SPNEGO diagnostic. Original MIDL remains unchanged. Read the own
|
||||||
|
* SYSTEM token first; one management discovery, then at most one status query.
|
||||||
|
* 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>
|
||||||
|
|
||||||
|
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_empty(RmmClockTrace *trace, RmmClockEeInfo *eeinfo, RmmClockAuthTrace *auth);
|
||||||
|
|
||||||
|
static WCHAR service_name[] = L"RmmClockSpnegoEmptyDiagnostic";
|
||||||
|
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-empty-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);
|
||||||
|
}
|
||||||
|
|
||||||
|
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-empty-v1\",\"case_id\":\"%s\","
|
||||||
|
"\"token_system\":true,\"read_only\":true,\"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, (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};
|
||||||
|
DWORD result = own_system_token(&token);
|
||||||
|
DWORD token_write = write_token(&token); /* durable numeric witness before RPC */
|
||||||
|
if (!result) result = token_write;
|
||||||
|
if (!result) {
|
||||||
|
RmmClockTrace trace = {0};
|
||||||
|
RmmClockEeInfo eeinfo = {0};
|
||||||
|
RmmClockAuthTrace auth = {0};
|
||||||
|
uint32_t rpc = rmm_clock_query_trace_spnego_empty(&trace, &eeinfo, &auth);
|
||||||
|
result = write_result(rpc, &trace, &eeinfo, &auth, &token);
|
||||||
|
}
|
||||||
|
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,182 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Local-only isolated process privilege comparison; never starts a target."""
|
||||||
|
import base64
|
||||||
|
import argparse
|
||||||
|
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-identity-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-impersonate-trace/build-5e18bc39-0fca-4420-87e9-c94451f7775d/manifest.json'
|
||||||
|
PARENT_SHA = '5644a50aee329144cb32c5bf0ebf4992ec068c59ca024416b66e8201366fd702'
|
||||||
|
PARENT_RESULT = ROOT / 'devstate/windows-clock-spnego-impersonate-trace/daf8205c-a110-4fb7-9ae0-f27ca1532d8f/diagnostic-result.json'
|
||||||
|
PARENT_RESULT_SHA = '26a06f8f46a7b5fa173c5ee81cd97a4542571a7b97b15fd5e0e8a41315680c4e'
|
||||||
|
UNCHANGED_DIAGNOSTICS = {
|
||||||
|
'deploy/windows/clock-spnego-impersonate-trace/clock_rpc_spnego_impersonate.c': '92c7a9a6e57bc199e7ae886a87398a6af98901a5affb888cd78ab5c5b3f7a59c',
|
||||||
|
'deploy/windows/clock-spnego-impersonate-trace/system_trace_spnego_impersonate.c': 'f855fe7d0a7e5bcec0138131d78bbad7b2098c9031b1a857bc8b68ef8f57cd94',
|
||||||
|
'deploy/windows/clock-spnego-impersonate-trace/build.py': 'b8de6616d7d7caa3c2c1307f6e216594ebb9455ceabe69e99c548ac927d2cb67',
|
||||||
|
'deploy/windows/clock-spnego-impersonate-trace/native.py': 'eeec0a83b7ee9cfed874df8ce4b44da05b5eec85a4cb2c8a775d2a032e6855a5',
|
||||||
|
'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_identity.c','system_trace_spnego_identity.c','build.py','native.py')}
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
parser=argparse.ArgumentParser();parser.add_argument("--control",type=int,choices=(0,1,2),required=True);args=parser.parse_args()
|
||||||
|
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_identity.c'
|
||||||
|
write(source / 'clock_rpc.c', wrapper.read_bytes()); write(source / 'system_trace.c', (HERE / 'system_trace_spnego_identity.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_identity.c'))
|
||||||
|
write(folder / 'wrapper-source.diff',delta.encode())
|
||||||
|
parent_wrapper = ROOT / 'deploy/windows/clock-spnego-impersonate-trace/clock_rpc_spnego_impersonate.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-identity.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_discovery_principal_allowed=True,null_discovery_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','-DRMM_CLOCK_IDENTITY_CONTROL='+str(args.control),'-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/ClockSpnegoIdentityTrace.linked.exe'])
|
||||||
|
raw_linked = output / 'ClockSpnegoIdentityTrace.linked.exe'
|
||||||
|
linked = output / 'ClockSpnegoIdentityTrace.original.exe'; delivery = output / 'ClockSpnegoIdentityTrace.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/ClockSpnegoIdentityTrace.exe'])
|
||||||
|
imports = sorted(set(re.findall(r'DLL Name:\s+(\S+)',run('imports',['x86_64-w64-mingw32-objdump','-p','/out/ClockSpnegoIdentityTrace.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-identity-v1',identity_control=args.control,qos_version=5,auth_principal_from_fixed_sid=True,client_server_descriptor=True,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_discovery_principal_allowed=True,null_discovery_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,300 @@
|
|||||||
|
/* 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>
|
||||||
|
#ifndef RMM_CLOCK_IDENTITY_CONTROL
|
||||||
|
#error fixed diagnostic identity control required
|
||||||
|
#endif
|
||||||
|
_Static_assert(RMM_CLOCK_IDENTITY_CONTROL >= 0 && RMM_CLOCK_IDENTITY_CONTROL <= 2, "closed identity controls");
|
||||||
|
|
||||||
|
#include <rpc.h>
|
||||||
|
#include <rpcasync.h>
|
||||||
|
#include <stdint.h>
|
||||||
|
#include <stddef.h>
|
||||||
|
#include <stdlib.h>
|
||||||
|
#include <string.h>
|
||||||
|
#include "w32time.h"
|
||||||
|
/* Older MinGW headers stop at V3. This is the documented x64 V5 SDK layout,
|
||||||
|
* not a fallback to an older authentication contract. MSVC also checks it
|
||||||
|
* directly against its native SDK declaration. Windows x64 is the only target.
|
||||||
|
* https://learn.microsoft.com/windows/win32/api/rpcdce/ns-rpcdce-rpc_security_qos_v5_w
|
||||||
|
*/
|
||||||
|
typedef struct {
|
||||||
|
unsigned long Version, Capabilities, IdentityTracking, ImpersonationType;
|
||||||
|
unsigned long AdditionalSecurityInfoType;
|
||||||
|
union { RPC_HTTP_TRANSPORT_CREDENTIALS_W *HttpCredentials; } u;
|
||||||
|
void *Sid;
|
||||||
|
unsigned int EffectiveOnly;
|
||||||
|
void *ServerSecurityDescriptor;
|
||||||
|
} RmmRpcQosV5;
|
||||||
|
_Static_assert(sizeof(RmmRpcQosV5) == 56, "x64 RPC QOS V5 ABI");
|
||||||
|
_Static_assert(offsetof(RmmRpcQosV5, Sid) == offsetof(RPC_SECURITY_QOS_V3_W, Sid), "SDK QOS prefix ABI");
|
||||||
|
_Static_assert(offsetof(RmmRpcQosV5, ServerSecurityDescriptor) == 48, "x64 server descriptor ABI");
|
||||||
|
#ifdef _MSC_VER
|
||||||
|
_Static_assert(sizeof(RmmRpcQosV5) == sizeof(RPC_SECURITY_QOS_V5_W), "native SDK QOS V5 ABI");
|
||||||
|
_Static_assert(offsetof(RmmRpcQosV5, ServerSecurityDescriptor) == offsetof(RPC_SECURITY_QOS_V5_W, ServerSecurityDescriptor), "native SDK descriptor ABI");
|
||||||
|
#endif
|
||||||
|
/* 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;
|
||||||
|
uint32_t qos_version, identity_control, server_descriptor_present;
|
||||||
|
} RmmClockAuthTrace;
|
||||||
|
_Static_assert(sizeof(RmmClockAuthTrace) == 72, "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;
|
||||||
|
RmmRpcQosV5 qos = {0};
|
||||||
|
_Alignas(8) BYTE account_sid[SECURITY_MAX_SID_SIZE], service_sid[SECURITY_MAX_SID_SIZE];
|
||||||
|
_Alignas(8) BYTE acl_buffer[sizeof(ACL)+sizeof(ACCESS_ALLOWED_ACE)+SECURITY_MAX_SID_SIZE];
|
||||||
|
SECURITY_DESCRIPTOR descriptor;
|
||||||
|
DWORD account_bytes=sizeof(account_sid),service_bytes=sizeof(service_sid),domain_bytes=64;
|
||||||
|
WCHAR domain[64];SID_NAME_USE sid_type;
|
||||||
|
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;
|
||||||
|
auth->qos_version=5;auth->identity_control=RMM_CLOCK_IDENTITY_CONTROL;
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
if(!result && !CreateWellKnownSid(RMM_CLOCK_IDENTITY_CONTROL==1?WinLocalSystemSid:WinLocalServiceSid,NULL,account_sid,&account_bytes))result=GetLastError();
|
||||||
|
if(!result && !LookupAccountNameW(NULL,RMM_CLOCK_IDENTITY_CONTROL==2?L"NT SERVICE\\RmmDiscoveryWindows":L"NT SERVICE\\W32Time",service_sid,&service_bytes,domain,&domain_bytes,&sid_type))result=GetLastError();
|
||||||
|
if(!result && (!IsValidSid(account_sid)||!IsValidSid(service_sid)||service_bytes>sizeof(service_sid)))result=ERROR_INVALID_SID;
|
||||||
|
if(!result && !InitializeAcl((PACL)acl_buffer,sizeof(acl_buffer),ACL_REVISION))result=GetLastError();
|
||||||
|
if(!result && !AddAccessAllowedAce((PACL)acl_buffer,ACL_REVISION,GENERIC_ALL,service_sid))result=GetLastError();
|
||||||
|
if(!result && !InitializeSecurityDescriptor(&descriptor,SECURITY_DESCRIPTOR_REVISION))result=GetLastError();
|
||||||
|
if(!result && !SetSecurityDescriptorDacl(&descriptor,TRUE,(PACL)acl_buffer,FALSE))result=GetLastError();
|
||||||
|
if(!result)auth->server_descriptor_present=1;
|
||||||
|
qos.Version = 5;
|
||||||
|
qos.Capabilities = RPC_C_QOS_CAPABILITIES_MUTUAL_AUTH;
|
||||||
|
qos.IdentityTracking = RPC_C_QOS_IDENTITY_STATIC;
|
||||||
|
qos.ImpersonationType = RPC_C_IMP_LEVEL_IMPERSONATE;
|
||||||
|
qos.Sid=account_sid;qos.EffectiveOnly=TRUE;qos.ServerSecurityDescriptor=&descriptor;
|
||||||
|
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, NULL, RPC_C_AUTHN_LEVEL_PKT_PRIVACY,
|
||||||
|
RPC_C_AUTHN_GSS_NEGOTIATE, NULL, RPC_C_AUTHZ_NONE, (RPC_SECURITY_QOS *)&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_identity(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,348 @@
|
|||||||
|
#!/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-identity-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-identity-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='RmmClockSpnegoIdentityDiagnostic';$case=Join-Path $root ('clock-spnego-identity-trace-'+$id);$exe=Join-Path $case 'ClockSpnegoIdentityTrace.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='RmmClockSpnegoIdentityDiagnostic'" -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-identity-v1' and value['schema_version'] == 1
|
||||||
|
and type(value['identity_control']) is int and value['identity_control'] in (0,1,2) and value['qos_version']==5 and value['auth_principal_from_fixed_sid'] is True and value['client_server_descriptor'] is True
|
||||||
|
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']=='5644a50aee329144cb32c5bf0ebf4992ec068c59ca024416b66e8201366fd702'
|
||||||
|
and value['parent_result_sha256']=='26a06f8f46a7b5fa173c5ee81cd97a4542571a7b97b15fd5e0e8a41315680c4e'
|
||||||
|
and value['returned_empty_discovery_principal_allowed'] is True and value['null_discovery_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-identity-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','qos_version','identity_control','server_descriptor_present'}
|
||||||
|
and all(type(v) is int and 0<=v<2**32 for v in auth.values())
|
||||||
|
and auth['qos_version']==5 and auth['identity_control'] in (0,1,2) and auth['server_descriptor_present'] in (0,1)
|
||||||
|
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['server_descriptor_present']==1 and 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-identity-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-identity-trace-'+ident+'/ClockSpnegoIdentityTrace.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 result.get("report") is not None:require(result["report"]["auth"]["identity_control"]==value["identity_control"],"actual compiled identity control matches original manifest")
|
||||||
|
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,501 @@
|
|||||||
|
/* 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>
|
||||||
|
#ifndef RMM_CLOCK_IDENTITY_CONTROL
|
||||||
|
#error fixed diagnostic identity control required
|
||||||
|
#endif
|
||||||
|
_Static_assert(RMM_CLOCK_IDENTITY_CONTROL >= 0 && RMM_CLOCK_IDENTITY_CONTROL <= 2, "closed identity controls");
|
||||||
|
|
||||||
|
#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;
|
||||||
|
uint32_t qos_version, identity_control, server_descriptor_present;
|
||||||
|
} RmmClockAuthTrace;
|
||||||
|
_Static_assert(sizeof(RmmClockAuthTrace) == 72, "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_identity(RmmClockTrace *trace, RmmClockEeInfo *eeinfo, RmmClockAuthTrace *auth);
|
||||||
|
|
||||||
|
static WCHAR service_name[] = L"RmmClockSpnegoIdentityDiagnostic";
|
||||||
|
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-identity-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-identity-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,\"qos_version\":%lu,\"identity_control\":%lu,\"server_descriptor_present\":%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,(unsigned long)auth->qos_version,(unsigned long)auth->identity_control,(unsigned long)auth->server_descriptor_present);
|
||||||
|
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;auth.qos_version=5;auth.identity_control=RMM_CLOCK_IDENTITY_CONTROL;
|
||||||
|
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_identity(&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,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,172 @@
|
|||||||
|
#!/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-privilege-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-empty-trace/build-9daffc05-64d1-45c2-954a-4ec642c5ef70/manifest.json'
|
||||||
|
PARENT_SHA = '768293c37702e40876a83bbab4a24186a3b4e284cf9a193c40550dd72ef32548'
|
||||||
|
PARENT_RESULT = ROOT / 'devstate/windows-clock-spnego-empty-trace/5e0e8ce9-b9a3-4c4a-b739-3f84d714dc94/diagnostic-result.json'
|
||||||
|
PARENT_RESULT_SHA = 'c53378d5b6e1099a781bb007e2480609e4105b94498ce443df937a0a591ff307'
|
||||||
|
UNCHANGED_DIAGNOSTICS = {
|
||||||
|
'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 Empty and 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_privilege.c','system_trace_spnego_privilege.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_privilege.c'
|
||||||
|
write(source / 'clock_rpc.c', wrapper.read_bytes()); write(source / 'system_trace.c', (HERE / 'system_trace_spnego_privilege.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_privilege.c'))
|
||||||
|
write(folder / 'wrapper-source.diff',delta.encode())
|
||||||
|
parent_wrapper = ROOT / 'deploy/windows/clock-spnego-empty-trace/clock_rpc_spnego_empty.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-privilege.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/ClockSpnegoPrivilegeTrace.linked.exe'])
|
||||||
|
raw_linked = output / 'ClockSpnegoPrivilegeTrace.linked.exe'
|
||||||
|
linked = output / 'ClockSpnegoPrivilegeTrace.original.exe'; delivery = output / 'ClockSpnegoPrivilegeTrace.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/ClockSpnegoPrivilegeTrace.exe'])
|
||||||
|
imports = sorted(set(re.findall(r'DLL Name:\s+(\S+)',run('imports',['x86_64-w64-mingw32-objdump','-p','/out/ClockSpnegoPrivilegeTrace.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-privilege-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_IDENTIFY;
|
||||||
|
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_IDENTIFY;
|
||||||
|
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_privilege(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-privilege-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-privilege-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='RmmClockSpnegoPrivilegeDiagnostic';$case=Join-Path $root ('clock-spnego-privilege-trace-'+$id);$exe=Join-Path $case 'ClockSpnegoPrivilegeTrace.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='RmmClockSpnegoPrivilegeDiagnostic'" -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-privilege-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']=='768293c37702e40876a83bbab4a24186a3b4e284cf9a193c40550dd72ef32548'
|
||||||
|
and value['parent_result_sha256']=='c53378d5b6e1099a781bb007e2480609e4105b94498ce443df937a0a591ff307'
|
||||||
|
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 Empty comparison, own process privilege only; no fabricated target or 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-privilege-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']==2
|
||||||
|
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-privilege-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-privilege-trace-'+ident+'/ClockSpnegoPrivilegeTrace.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_privilege(RmmClockTrace *trace, RmmClockEeInfo *eeinfo, RmmClockAuthTrace *auth);
|
||||||
|
|
||||||
|
static WCHAR service_name[] = L"RmmClockSpnegoPrivilegeDiagnostic";
|
||||||
|
static WCHAR case_id[37];
|
||||||
|
static SERVICE_STATUS_HANDLE status_handle;
|
||||||
|
static SERVICE_STATUS service_status;
|
||||||
|
|
||||||
|
static DWORD WINAPI control(DWORD event, DWORD type, void *data, void *context) {
|
||||||
|
(void)event; (void)type; (void)data; (void)context;
|
||||||
|
return ERROR_CALL_NOT_IMPLEMENTED;
|
||||||
|
}
|
||||||
|
|
||||||
|
static DWORD own_system_token(RmmTokenProbe *probe) {
|
||||||
|
HANDLE token = NULL;
|
||||||
|
HANDLE thread = NULL;
|
||||||
|
DWORD needed = 0, result = ERROR_SUCCESS;
|
||||||
|
_Alignas(8) BYTE storage[4096];
|
||||||
|
if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &token)) {
|
||||||
|
probe->query_status = GetLastError();
|
||||||
|
return probe->query_status;
|
||||||
|
}
|
||||||
|
if (!GetTokenInformation(token, TokenUser, storage, sizeof(storage), &needed)) result = GetLastError();
|
||||||
|
else if (needed < sizeof(TOKEN_USER) || needed > sizeof(storage)
|
||||||
|
|| !IsWellKnownSid(((TOKEN_USER *)storage)->User.Sid, WinLocalSystemSid)) result = ERROR_ACCESS_DENIED;
|
||||||
|
else probe->system_user = 1;
|
||||||
|
if (!result) {
|
||||||
|
TOKEN_TYPE type = 0;
|
||||||
|
if (!GetTokenInformation(token, TokenType, &type, sizeof(type), &needed)) result = GetLastError();
|
||||||
|
else {
|
||||||
|
probe->token_type = (uint32_t)type;
|
||||||
|
if (needed != sizeof(type) || type != TokenPrimary) result = ERROR_ACCESS_DENIED;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!result) {
|
||||||
|
if (OpenThreadToken(GetCurrentThread(), TOKEN_QUERY, TRUE, &thread)) {
|
||||||
|
probe->thread_present = 1;
|
||||||
|
CloseHandle(thread);
|
||||||
|
result = ERROR_ACCESS_DENIED; /* never impersonate/revert to continue */
|
||||||
|
} else {
|
||||||
|
probe->thread_query_status = GetLastError();
|
||||||
|
if (probe->thread_query_status != ERROR_NO_TOKEN) result = probe->thread_query_status;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!result) {
|
||||||
|
LUID target = {0};
|
||||||
|
if (!LookupPrivilegeValueW(NULL, SE_SYSTEMTIME_NAME, &target)) {
|
||||||
|
probe->lookup_status = GetLastError();result = probe->lookup_status;
|
||||||
|
} else {
|
||||||
|
needed = 0;
|
||||||
|
if (GetTokenInformation(token, TokenPrivileges, NULL, 0, &needed)
|
||||||
|
|| GetLastError() != ERROR_INSUFFICIENT_BUFFER || needed < sizeof(DWORD) || needed > sizeof(storage)) {
|
||||||
|
probe->privileges_status = ERROR_INVALID_DATA;result = ERROR_INVALID_DATA;
|
||||||
|
} else if (!GetTokenInformation(token, TokenPrivileges, storage, sizeof(storage), &needed)) {
|
||||||
|
probe->privileges_status = GetLastError();result = probe->privileges_status;
|
||||||
|
} else {
|
||||||
|
TOKEN_PRIVILEGES *privileges = (TOKEN_PRIVILEGES *)storage;
|
||||||
|
size_t count = privileges->PrivilegeCount;
|
||||||
|
if (count > 256 || needed > sizeof(storage)
|
||||||
|
|| offsetof(TOKEN_PRIVILEGES, Privileges) + count * sizeof(LUID_AND_ATTRIBUTES) > needed) {
|
||||||
|
probe->privileges_status = ERROR_INVALID_DATA;result = ERROR_INVALID_DATA;
|
||||||
|
} else for (size_t i = 0; i < count; ++i) {
|
||||||
|
const LUID_AND_ATTRIBUTES *p = &privileges->Privileges[i];
|
||||||
|
if (p->Luid.LowPart != target.LowPart || p->Luid.HighPart != target.HighPart) continue;
|
||||||
|
if (probe->privilege_present) {result = ERROR_INVALID_DATA;break;}
|
||||||
|
probe->privilege_present = 1;
|
||||||
|
probe->privilege_attributes = p->Attributes;
|
||||||
|
probe->privilege_enabled = !!(p->Attributes & SE_PRIVILEGE_ENABLED);
|
||||||
|
probe->privilege_default = !!(p->Attributes & SE_PRIVILEGE_ENABLED_BY_DEFAULT);
|
||||||
|
probe->privilege_removed = !!(p->Attributes & SE_PRIVILEGE_REMOVED);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
probe->query_status = result;
|
||||||
|
CloseHandle(token);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
#define TOKEN_FIELDS "\"query_status\":%lu,\"system_user\":%lu,\"token_type\":%lu,\"thread_query_status\":%lu,\"thread_present\":%lu,\"lookup_status\":%lu,\"privileges_status\":%lu,\"privilege_present\":%lu,\"privilege_attributes\":%lu,\"privilege_enabled\":%lu,\"privilege_default\":%lu,\"privilege_removed\":%lu"
|
||||||
|
#define TOKEN_VALUES(p) (unsigned long)(p)->query_status,(unsigned long)(p)->system_user,(unsigned long)(p)->token_type,(unsigned long)(p)->thread_query_status,(unsigned long)(p)->thread_present,(unsigned long)(p)->lookup_status,(unsigned long)(p)->privileges_status,(unsigned long)(p)->privilege_present,(unsigned long)(p)->privilege_attributes,(unsigned long)(p)->privilege_enabled,(unsigned long)(p)->privilege_default,(unsigned long)(p)->privilege_removed
|
||||||
|
static DWORD write_new(const WCHAR *suffix, const char *bytes, DWORD length) {
|
||||||
|
WCHAR path[256];DWORD written = 0, result = ERROR_SUCCESS;
|
||||||
|
int count = swprintf(path, sizeof(path) / sizeof(path[0]),
|
||||||
|
L"C:\\ProgramData\\RustDiscoveryBootstrap\\clock-spnego-privilege-trace-%ls\\%ls", case_id, suffix);
|
||||||
|
if (count <= 0 || count >= (int)(sizeof(path) / sizeof(path[0]))) return ERROR_INVALID_PARAMETER;
|
||||||
|
HANDLE file = CreateFileW(path, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_NEW,
|
||||||
|
FILE_ATTRIBUTE_NORMAL | FILE_FLAG_WRITE_THROUGH, NULL);
|
||||||
|
if (file == INVALID_HANDLE_VALUE) return GetLastError();
|
||||||
|
if (!WriteFile(file, bytes, length, &written, NULL) || written != length) result = ERROR_WRITE_FAULT;
|
||||||
|
else if (!FlushFileBuffers(file)) result = GetLastError();
|
||||||
|
CloseHandle(file);return result;
|
||||||
|
}
|
||||||
|
static DWORD write_token(const RmmTokenProbe *token) {
|
||||||
|
char report[1024];
|
||||||
|
int count = snprintf(report, sizeof(report), "{" TOKEN_FIELDS "}\n", TOKEN_VALUES(token));
|
||||||
|
if (count <= 0 || count >= (int)sizeof(report)) return ERROR_BUFFER_OVERFLOW;
|
||||||
|
return write_new(L"token.json", report, (DWORD)count);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Only this held own token is ever passed to AdjustTokenPrivileges. Peer
|
||||||
|
* handles request TOKEN_QUERY only and are retained until the final readback. */
|
||||||
|
typedef struct {
|
||||||
|
DWORD present, query_status;
|
||||||
|
TOKEN_STATISTICS statistics;
|
||||||
|
DWORD count;
|
||||||
|
LUID_AND_ATTRIBUTES privileges[256];
|
||||||
|
} TokenSnapshot;
|
||||||
|
typedef struct {
|
||||||
|
HANDLE process, token;
|
||||||
|
SC_HANDLE service;
|
||||||
|
DWORD pid;
|
||||||
|
FILETIME creation;
|
||||||
|
TokenSnapshot before, after;
|
||||||
|
} Peer;
|
||||||
|
typedef struct {
|
||||||
|
HANDLE own;
|
||||||
|
SC_HANDLE manager;
|
||||||
|
FILETIME creation;
|
||||||
|
Peer peers[4]; /* SCM, W32Time, agent, helper */
|
||||||
|
TokenSnapshot before, active, restored;
|
||||||
|
LUID privilege;
|
||||||
|
DWORD preflight_status, enable_attempted, enable_return, enable_error;
|
||||||
|
DWORD previous_count, previous_bytes, previous_luid_low, previous_luid_high, previous_attributes;
|
||||||
|
DWORD active_status, rpc_attempted, restore_attempted, restore_return, restore_error;
|
||||||
|
DWORD restore_input_from_previous, restored_status, peer_after_status, restoration_verified, flow_status;
|
||||||
|
} PrivilegeContext;
|
||||||
|
|
||||||
|
static int luid_equal(LUID a, LUID b) {return a.LowPart==b.LowPart && a.HighPart==b.HighPart;}
|
||||||
|
static int luid_before(LUID a, LUID b) {
|
||||||
|
return (DWORD)a.HighPart<(DWORD)b.HighPart || (a.HighPart==b.HighPart && a.LowPart<b.LowPart);
|
||||||
|
}
|
||||||
|
static DWORD snapshot(HANDLE token, TokenSnapshot *out) {
|
||||||
|
DWORD needed=0, status=ERROR_SUCCESS;
|
||||||
|
_Alignas(8) BYTE storage[4096];
|
||||||
|
out->query_status=ERROR_INVALID_DATA;
|
||||||
|
if (!GetTokenInformation(token,TokenStatistics,&out->statistics,sizeof(out->statistics),&needed)) status=GetLastError();
|
||||||
|
else if (needed!=sizeof(out->statistics)) status=ERROR_INVALID_DATA;
|
||||||
|
if (!status) {
|
||||||
|
needed=0;
|
||||||
|
if (GetTokenInformation(token,TokenPrivileges,NULL,0,&needed)
|
||||||
|
|| GetLastError()!=ERROR_INSUFFICIENT_BUFFER || needed<sizeof(DWORD) || needed>sizeof(storage)) status=ERROR_INVALID_DATA;
|
||||||
|
else if (!GetTokenInformation(token,TokenPrivileges,storage,sizeof(storage),&needed)) status=GetLastError();
|
||||||
|
else {
|
||||||
|
TOKEN_PRIVILEGES *value=(TOKEN_PRIVILEGES *)storage;
|
||||||
|
if (value->PrivilegeCount>256 || value->PrivilegeCount!=out->statistics.PrivilegeCount || needed>sizeof(storage)
|
||||||
|
|| offsetof(TOKEN_PRIVILEGES,Privileges)+(size_t)value->PrivilegeCount*sizeof(LUID_AND_ATTRIBUTES)>needed) status=ERROR_INVALID_DATA;
|
||||||
|
else {
|
||||||
|
out->count=value->PrivilegeCount;
|
||||||
|
for (DWORD i=0;i<out->count;++i) out->privileges[i]=value->Privileges[i];
|
||||||
|
for (DWORD i=1;i<out->count;++i) {
|
||||||
|
LUID_AND_ATTRIBUTES item=out->privileges[i];DWORD j=i;
|
||||||
|
while(j && luid_before(item.Luid,out->privileges[j-1].Luid)) {out->privileges[j]=out->privileges[j-1];--j;}
|
||||||
|
out->privileges[j]=item;
|
||||||
|
}
|
||||||
|
for(DWORD i=1;i<out->count;++i)
|
||||||
|
if(luid_equal(out->privileges[i-1].Luid,out->privileges[i].Luid)) status=ERROR_INVALID_DATA;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out->query_status=status;out->present=!status;return status;
|
||||||
|
}
|
||||||
|
static int identity_equal(const TokenSnapshot *a,const TokenSnapshot *b) {
|
||||||
|
return a->present && b->present && luid_equal(a->statistics.TokenId,b->statistics.TokenId)
|
||||||
|
&& luid_equal(a->statistics.AuthenticationId,b->statistics.AuthenticationId)
|
||||||
|
&& a->statistics.TokenType==b->statistics.TokenType;
|
||||||
|
}
|
||||||
|
static DWORD compare_snapshots(const TokenSnapshot *a,const TokenSnapshot *b,LUID target,int enabled) {
|
||||||
|
if(!identity_equal(a,b) || a->count!=b->count) return ERROR_INVALID_DATA;
|
||||||
|
DWORD matched=0;
|
||||||
|
for(DWORD i=0;i<a->count;++i) {
|
||||||
|
if(!luid_equal(a->privileges[i].Luid,b->privileges[i].Luid)) return ERROR_INVALID_DATA;
|
||||||
|
DWORD attributes=a->privileges[i].Attributes;
|
||||||
|
if(luid_equal(target,a->privileges[i].Luid)) {++matched;if(attributes) return ERROR_INVALID_DATA;if(enabled) attributes=SE_PRIVILEGE_ENABLED;}
|
||||||
|
if(b->privileges[i].Attributes!=attributes) return ERROR_INVALID_DATA;
|
||||||
|
}
|
||||||
|
return matched==1?ERROR_SUCCESS:ERROR_PRIVILEGE_NOT_HELD;
|
||||||
|
}
|
||||||
|
static DWORD query_service_pid(SC_HANDLE service,DWORD *pid) {
|
||||||
|
SERVICE_STATUS_PROCESS state={0};DWORD needed=0;
|
||||||
|
if(!QueryServiceStatusEx(service,SC_STATUS_PROCESS_INFO,(BYTE *)&state,sizeof(state),&needed)) return GetLastError();
|
||||||
|
if(needed!=sizeof(state) || state.dwCurrentState!=SERVICE_RUNNING || !state.dwProcessId) return ERROR_INVALID_STATE;
|
||||||
|
*pid=state.dwProcessId;return ERROR_SUCCESS;
|
||||||
|
}
|
||||||
|
static DWORD scm_pid(DWORD *pid) {
|
||||||
|
HANDLE list=CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0);
|
||||||
|
if(list==INVALID_HANDLE_VALUE) return GetLastError();
|
||||||
|
PROCESSENTRY32W entry={0};entry.dwSize=sizeof(entry);DWORD found=0,status=0;
|
||||||
|
if(!Process32FirstW(list,&entry)) status=GetLastError();
|
||||||
|
else {
|
||||||
|
do {if(!_wcsicmp(entry.szExeFile,L"services.exe")){*pid=entry.th32ProcessID;++found;}}
|
||||||
|
while(Process32NextW(list,&entry));
|
||||||
|
if(GetLastError()!=ERROR_NO_MORE_FILES) status=GetLastError();
|
||||||
|
else if(found!=1) status=ERROR_INVALID_DATA;
|
||||||
|
}
|
||||||
|
CloseHandle(list);return status;
|
||||||
|
}
|
||||||
|
static DWORD thread_absent(void) {
|
||||||
|
HANDLE token=NULL;
|
||||||
|
if(OpenThreadToken(GetCurrentThread(),TOKEN_QUERY,TRUE,&token)) {CloseHandle(token);return ERROR_ACCESS_DENIED;}
|
||||||
|
DWORD error=GetLastError();return error==ERROR_NO_TOKEN?ERROR_SUCCESS:error;
|
||||||
|
}
|
||||||
|
static DWORD peer_binding(Peer *peer,DWORD index) {
|
||||||
|
DWORD pid=0,status=index?query_service_pid(peer->service,&pid):scm_pid(&pid);
|
||||||
|
if(status) return status;
|
||||||
|
if(pid!=peer->pid || GetProcessId(peer->process)!=pid || WaitForSingleObject(peer->process,0)!=WAIT_TIMEOUT) return ERROR_INVALID_DATA;
|
||||||
|
FILETIME created,ended,kernel,user;
|
||||||
|
if(!GetProcessTimes(peer->process,&created,&ended,&kernel,&user)) return GetLastError();
|
||||||
|
if(CompareFileTime(&created,&peer->creation)) return ERROR_INVALID_DATA;
|
||||||
|
HANDLE current=NULL;TokenSnapshot now={0};
|
||||||
|
if(!OpenProcessToken(peer->process,TOKEN_QUERY,¤t)) return GetLastError();
|
||||||
|
status=snapshot(current,&now);CloseHandle(current);
|
||||||
|
if(status) return status;
|
||||||
|
return identity_equal(&now,&peer->before)?ERROR_SUCCESS:ERROR_INVALID_DATA;
|
||||||
|
}
|
||||||
|
static DWORD prepare_privilege(PrivilegeContext *ctx) {
|
||||||
|
if(!OpenProcessToken(GetCurrentProcess(),TOKEN_QUERY|TOKEN_ADJUST_PRIVILEGES,&ctx->own)) return GetLastError();
|
||||||
|
_Alignas(8) BYTE user_info[4096];DWORD needed=0;FILETIME ended,kernel,user;
|
||||||
|
if(!GetTokenInformation(ctx->own,TokenUser,user_info,sizeof(user_info),&needed))return GetLastError();
|
||||||
|
if(needed<sizeof(TOKEN_USER) || needed>sizeof(user_info) || !IsWellKnownSid(((TOKEN_USER *)user_info)->User.Sid,WinLocalSystemSid))return ERROR_ACCESS_DENIED;
|
||||||
|
if(!GetProcessTimes(GetCurrentProcess(),&ctx->creation,&ended,&kernel,&user))return GetLastError();
|
||||||
|
DWORD status=snapshot(ctx->own,&ctx->before);if(status) return status;
|
||||||
|
if(ctx->before.statistics.TokenType!=TokenPrimary) return ERROR_ACCESS_DENIED;
|
||||||
|
if((status=thread_absent())) return status;
|
||||||
|
if(!LookupPrivilegeValueW(NULL,SE_SYSTEMTIME_NAME,&ctx->privilege)) return GetLastError();
|
||||||
|
if((status=compare_snapshots(&ctx->before,&ctx->before,ctx->privilege,0))) return status;
|
||||||
|
ctx->manager=OpenSCManagerW(NULL,NULL,SC_MANAGER_CONNECT);
|
||||||
|
if(!ctx->manager) return GetLastError();
|
||||||
|
const WCHAR *names[4]={NULL,L"W32Time",L"RmmDiscoveryWindows",L"RmmDiscoverySystemHelper"};
|
||||||
|
const WCHAR *binaries[4]={L"services.exe",L"svchost.exe",L"C:\\Program Files\\RustDiscovery\\rmm-agent-windows.exe",L"C:\\Program Files\\RustDiscovery\\rmm-helper-windows.exe"};
|
||||||
|
for(DWORD i=0;i<4;++i) {
|
||||||
|
Peer *peer=&ctx->peers[i];
|
||||||
|
if(i) {peer->service=OpenServiceW(ctx->manager,names[i],SERVICE_QUERY_STATUS);if(!peer->service)return GetLastError();}
|
||||||
|
status=i?query_service_pid(peer->service,&peer->pid):scm_pid(&peer->pid);if(status)return status;
|
||||||
|
if(peer->pid==GetCurrentProcessId()) return ERROR_INVALID_DATA;
|
||||||
|
peer->process=OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION|SYNCHRONIZE,FALSE,peer->pid);
|
||||||
|
if(!peer->process)return GetLastError();
|
||||||
|
WCHAR path[512],expected[512];DWORD length=512;
|
||||||
|
if(!QueryFullProcessImageNameW(peer->process,0,path,&length))return GetLastError();
|
||||||
|
if(i<2) {UINT n=GetSystemDirectoryW(expected,512);if(!n || n>480)return ERROR_INVALID_DATA;
|
||||||
|
if(swprintf(expected+n,512-n,L"\\%ls",binaries[i])<=0)return ERROR_INVALID_DATA;}
|
||||||
|
else {if(wcslen(binaries[i])>=512)return ERROR_INVALID_DATA;wcscpy(expected,binaries[i]);}
|
||||||
|
if(_wcsicmp(path,expected))return ERROR_INVALID_DATA;
|
||||||
|
FILETIME ended,kernel,user;
|
||||||
|
if(!GetProcessTimes(peer->process,&peer->creation,&ended,&kernel,&user))return GetLastError();
|
||||||
|
if(!OpenProcessToken(peer->process,TOKEN_QUERY,&peer->token))return GetLastError();
|
||||||
|
status=snapshot(peer->token,&peer->before);if(status)return status;
|
||||||
|
if(peer->before.statistics.TokenType!=TokenPrimary || luid_equal(peer->before.statistics.TokenId,ctx->before.statistics.TokenId))return ERROR_ACCESS_DENIED;
|
||||||
|
if((status=peer_binding(peer,i)))return status;
|
||||||
|
}
|
||||||
|
return ERROR_SUCCESS;
|
||||||
|
}
|
||||||
|
static DWORD own_current(PrivilegeContext *ctx) {
|
||||||
|
HANDLE token=NULL;TokenSnapshot current={0};
|
||||||
|
if(!OpenProcessToken(GetCurrentProcess(),TOKEN_QUERY,&token))return GetLastError();
|
||||||
|
DWORD status=snapshot(token,¤t);CloseHandle(token);
|
||||||
|
if(status)return status;
|
||||||
|
if(!identity_equal(&ctx->before,¤t))return ERROR_INVALID_DATA;
|
||||||
|
return thread_absent();
|
||||||
|
}
|
||||||
|
static void close_privilege(PrivilegeContext *ctx) {
|
||||||
|
for(DWORD i=0;i<4;++i){Peer *p=&ctx->peers[i];if(p->token)CloseHandle(p->token);if(p->process)CloseHandle(p->process);if(p->service)CloseServiceHandle(p->service);}
|
||||||
|
if(ctx->manager)CloseServiceHandle(ctx->manager);if(ctx->own)CloseHandle(ctx->own);
|
||||||
|
}
|
||||||
|
|
||||||
|
static char witness[262144];
|
||||||
|
static size_t witness_used;
|
||||||
|
static int append(const char *format,...) {
|
||||||
|
va_list args;va_start(args,format);
|
||||||
|
int n=vsnprintf(witness+witness_used,sizeof(witness)-witness_used,format,args);va_end(args);
|
||||||
|
if(n<=0 || (size_t)n>=sizeof(witness)-witness_used)return 0;
|
||||||
|
witness_used+=(size_t)n;return 1;
|
||||||
|
}
|
||||||
|
static int append_snapshot(const TokenSnapshot *s) {
|
||||||
|
const TOKEN_STATISTICS *v=&s->statistics;
|
||||||
|
if(!append("{\"present\":%lu,\"query_status\":%lu,\"token_id\":[%lu,%lu],\"authentication_id\":[%lu,%lu],\"modified_id\":[%lu,%lu],\"expiration_time\":[%lu,%lu],\"token_type\":%lu,\"impersonation_level\":%lu,\"dynamic_charged\":%lu,\"dynamic_available\":%lu,\"group_count\":%lu,\"privilege_count\":%lu,\"privileges\":[",
|
||||||
|
(unsigned long)s->present,(unsigned long)s->query_status,(unsigned long)v->TokenId.LowPart,(unsigned long)(DWORD)v->TokenId.HighPart,
|
||||||
|
(unsigned long)v->AuthenticationId.LowPart,(unsigned long)(DWORD)v->AuthenticationId.HighPart,(unsigned long)v->ModifiedId.LowPart,(unsigned long)(DWORD)v->ModifiedId.HighPart,
|
||||||
|
(unsigned long)v->ExpirationTime.LowPart,(unsigned long)(DWORD)v->ExpirationTime.HighPart,(unsigned long)v->TokenType,(unsigned long)v->ImpersonationLevel,
|
||||||
|
(unsigned long)v->DynamicCharged,(unsigned long)v->DynamicAvailable,(unsigned long)v->GroupCount,(unsigned long)s->count))return 0;
|
||||||
|
for(DWORD i=0;i<s->count;++i)if(!append("%s[%lu,%lu,%lu]",i?",":"",(unsigned long)s->privileges[i].Luid.LowPart,(unsigned long)(DWORD)s->privileges[i].Luid.HighPart,(unsigned long)s->privileges[i].Attributes))return 0;
|
||||||
|
return append("]}");
|
||||||
|
}
|
||||||
|
static DWORD write_before(const PrivilegeContext *ctx) {
|
||||||
|
witness_used=0;
|
||||||
|
if(!append("{\"schema_version\":1,\"own_pid\":%lu,\"own_creation\":[%lu,%lu],\"own\":",(unsigned long)GetCurrentProcessId(),(unsigned long)ctx->creation.dwLowDateTime,(unsigned long)ctx->creation.dwHighDateTime) || !append_snapshot(&ctx->before) || !append(",\"peers\":["))return ERROR_BUFFER_OVERFLOW;
|
||||||
|
for(DWORD i=0;i<4;++i){const Peer *p=&ctx->peers[i];
|
||||||
|
if(!append("%s{\"role\":%lu,\"pid\":%lu,\"creation\":[%lu,%lu],\"token\":",i?",":"",(unsigned long)i,(unsigned long)p->pid,(unsigned long)p->creation.dwLowDateTime,(unsigned long)p->creation.dwHighDateTime)
|
||||||
|
|| !append_snapshot(&p->before) || !append("}"))return ERROR_BUFFER_OVERFLOW;}
|
||||||
|
if(!append("]}\n"))return ERROR_BUFFER_OVERFLOW;
|
||||||
|
return write_new(L"privilege-before.json",witness,(DWORD)witness_used);
|
||||||
|
}
|
||||||
|
static DWORD write_adjustment(const PrivilegeContext *ctx) {
|
||||||
|
witness_used=0;
|
||||||
|
if(!append("{\"schema_version\":1,\"preflight_status\":%lu,\"enable_attempted\":%lu,\"enable_return\":%lu,\"enable_error\":%lu,\"previous_count\":%lu,\"previous_bytes\":%lu,\"previous_luid\":[%lu,%lu],\"previous_attributes\":%lu,\"active_status\":%lu,\"rpc_attempted\":%lu,\"restore_attempted\":%lu,\"restore_return\":%lu,\"restore_error\":%lu,\"restore_input_from_previous\":%lu,\"restored_status\":%lu,\"peer_after_status\":%lu,\"restoration_verified\":%lu,\"flow_status\":%lu,\"target_luid\":[%lu,%lu],\"active\":",
|
||||||
|
(unsigned long)ctx->preflight_status,(unsigned long)ctx->enable_attempted,(unsigned long)ctx->enable_return,(unsigned long)ctx->enable_error,
|
||||||
|
(unsigned long)ctx->previous_count,(unsigned long)ctx->previous_bytes,(unsigned long)ctx->previous_luid_low,(unsigned long)ctx->previous_luid_high,(unsigned long)ctx->previous_attributes,
|
||||||
|
(unsigned long)ctx->active_status,(unsigned long)ctx->rpc_attempted,(unsigned long)ctx->restore_attempted,(unsigned long)ctx->restore_return,(unsigned long)ctx->restore_error,
|
||||||
|
(unsigned long)ctx->restore_input_from_previous,(unsigned long)ctx->restored_status,(unsigned long)ctx->peer_after_status,(unsigned long)ctx->restoration_verified,(unsigned long)ctx->flow_status,
|
||||||
|
(unsigned long)ctx->privilege.LowPart,(unsigned long)(DWORD)ctx->privilege.HighPart)
|
||||||
|
|| !append_snapshot(&ctx->active) || !append(",\"restored\":") || !append_snapshot(&ctx->restored) || !append(",\"peers_after\":["))return ERROR_BUFFER_OVERFLOW;
|
||||||
|
for(DWORD i=0;i<4;++i){if(i && !append(","))return ERROR_BUFFER_OVERFLOW;if(!append_snapshot(&ctx->peers[i].after))return ERROR_BUFFER_OVERFLOW;}
|
||||||
|
if(!append("]}\n"))return ERROR_BUFFER_OVERFLOW;
|
||||||
|
return write_new(L"privilege-adjustment.json",witness,(DWORD)witness_used);
|
||||||
|
}
|
||||||
|
|
||||||
|
static DWORD write_result(uint32_t rpc, const RmmClockTrace *trace, const RmmClockEeInfo *eeinfo, const RmmClockAuthTrace *auth, const RmmTokenProbe *token) {
|
||||||
|
char id[37], report[4096];
|
||||||
|
for (unsigned i = 0; i < 37; ++i) id[i] = (char)case_id[i];
|
||||||
|
int count = snprintf(report, sizeof(report),
|
||||||
|
"{\"schema_version\":1,\"profile\":\"clock-system-spnego-privilege-v1\",\"case_id\":\"%s\","
|
||||||
|
"\"token_system\":%s,\"read_only\":false,\"diagnostic_only\":true,\"query_invocations\":%lu,"
|
||||||
|
"\"clock_qualified\":false,\"adapter_qualified\":false,\"product_gate_open\":false,\"rpc_code\":%lu,"
|
||||||
|
"\"trace\":{\"stage\":%lu,\"native_rpc_return\":%lu,\"native_rpc_return_present\":%lu,"
|
||||||
|
"\"rpc_exception\":%lu,\"status_present\":%lu,\"ul_size\":%lu,\"c_entries\":%lu,\"p_entries_present\":%lu}}\n",
|
||||||
|
id, (token->query_status==0 && token->system_user==1 && token->token_type==1 && token->thread_present==0 && token->thread_query_status==ERROR_NO_TOKEN)?"true":"false",
|
||||||
|
(unsigned long)auth->status_query_invocations, (unsigned long)rpc, (unsigned long)trace->stage,
|
||||||
|
(unsigned long)trace->native_rpc_return, (unsigned long)trace->native_rpc_return_present,
|
||||||
|
(unsigned long)trace->rpc_exception, (unsigned long)trace->status_present,
|
||||||
|
(unsigned long)trace->ul_size, (unsigned long)trace->c_entries, (unsigned long)trace->p_entries_present);
|
||||||
|
if (count <= 0 || count >= (int)sizeof(report)) return ERROR_BUFFER_OVERFLOW;
|
||||||
|
if (count < 3 || eeinfo->count > 4) return ERROR_INVALID_DATA;
|
||||||
|
/* Replace only the final root-object closure; original trace stays intact. */
|
||||||
|
size_t used = (size_t)count - 2;
|
||||||
|
int appended = snprintf(report + used, sizeof(report) - used,
|
||||||
|
",\"eeinfo\":{\"capture_attempted\":%lu,\"start_status\":%lu,\"next_status\":%lu,"
|
||||||
|
"\"end_status\":%lu,\"count\":%lu,\"limit_reached\":%lu,\"records\":[",
|
||||||
|
(unsigned long)eeinfo->capture_attempted, (unsigned long)eeinfo->start_status,
|
||||||
|
(unsigned long)eeinfo->next_status, (unsigned long)eeinfo->end_status,
|
||||||
|
(unsigned long)eeinfo->count, (unsigned long)eeinfo->limit_reached);
|
||||||
|
if (appended <= 0 || (size_t)appended >= sizeof(report) - used) return ERROR_BUFFER_OVERFLOW;
|
||||||
|
used += (size_t)appended;
|
||||||
|
for (unsigned i = 0; i < eeinfo->count; ++i) {
|
||||||
|
const RmmClockEeRecord *record = &eeinfo->records[i];
|
||||||
|
appended = snprintf(report + used, sizeof(report) - used,
|
||||||
|
"%s{\"generating_component\":%lu,\"status\":%lu,\"detection_location\":%lu,"
|
||||||
|
"\"flags\":%lu,\"number_of_parameters\":%ld}", i ? "," : "",
|
||||||
|
(unsigned long)record->generating_component, (unsigned long)record->status,
|
||||||
|
(unsigned long)record->detection_location, (unsigned long)record->flags,
|
||||||
|
(long)record->number_of_parameters);
|
||||||
|
if (appended <= 0 || (size_t)appended >= sizeof(report) - used) return ERROR_BUFFER_OVERFLOW;
|
||||||
|
used += (size_t)appended;
|
||||||
|
}
|
||||||
|
appended = snprintf(report + used, sizeof(report) - used,
|
||||||
|
"]},\"token\":{" TOKEN_FIELDS "},\"auth\":{"
|
||||||
|
"\"discovery_invocations\":%lu,\"discovery_status\":%lu,\"discovery_return_present\":%lu,"
|
||||||
|
"\"principal_present\":%lu,\"principal_units\":%lu,\"principal_validated\":%lu,"
|
||||||
|
"\"status_query_invocations\":%lu,\"authn_service\":%lu,\"authn_level\":%lu,\"impersonation_type\":%lu,"
|
||||||
|
"\"principal_free_attempted\":%lu,\"principal_free_status\":%lu,\"binding_free_attempted\":%lu,"
|
||||||
|
"\"binding_free_status\":%lu,\"eeinfo_origin\":%lu}}\n",
|
||||||
|
TOKEN_VALUES(token), (unsigned long)auth->discovery_invocations, (unsigned long)auth->discovery_status,
|
||||||
|
(unsigned long)auth->discovery_return_present, (unsigned long)auth->principal_present,
|
||||||
|
(unsigned long)auth->principal_units, (unsigned long)auth->principal_validated,
|
||||||
|
(unsigned long)auth->status_query_invocations, (unsigned long)auth->authn_service,
|
||||||
|
(unsigned long)auth->authn_level, (unsigned long)auth->impersonation_type,
|
||||||
|
(unsigned long)auth->principal_free_attempted, (unsigned long)auth->principal_free_status,
|
||||||
|
(unsigned long)auth->binding_free_attempted, (unsigned long)auth->binding_free_status,
|
||||||
|
(unsigned long)auth->eeinfo_origin);
|
||||||
|
if (appended <= 0 || (size_t)appended >= sizeof(report) - used) return ERROR_BUFFER_OVERFLOW;
|
||||||
|
used += (size_t)appended;
|
||||||
|
count = (int)used;
|
||||||
|
return write_new(L"result.json", report, (DWORD)count);
|
||||||
|
}
|
||||||
|
|
||||||
|
static void WINAPI run_service(DWORD argc, WCHAR **argv) {
|
||||||
|
(void)argc; (void)argv;
|
||||||
|
status_handle = RegisterServiceCtrlHandlerExW(service_name, control, NULL);
|
||||||
|
if (!status_handle) return;
|
||||||
|
ZeroMemory(&service_status, sizeof(service_status));
|
||||||
|
service_status.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
|
||||||
|
service_status.dwCurrentState = SERVICE_RUNNING;
|
||||||
|
service_status.dwControlsAccepted = 0;
|
||||||
|
if (!SetServiceStatus(status_handle, &service_status)) return;
|
||||||
|
RmmTokenProbe token={0};PrivilegeContext ctx={0};
|
||||||
|
RmmClockTrace trace={0};RmmClockEeInfo eeinfo={0};
|
||||||
|
RmmClockAuthTrace auth={0};auth.authn_service=9;auth.authn_level=6;auth.impersonation_type=2;
|
||||||
|
DWORD result=own_system_token(&token),rpc=0;
|
||||||
|
DWORD token_write=write_token(&token); /* durable old numeric probe */
|
||||||
|
if(!result)result=token_write;
|
||||||
|
if(!result)result=prepare_privilege(&ctx);
|
||||||
|
if(!result)result=write_before(&ctx); /* durable complete pre-enable witness */
|
||||||
|
ctx.preflight_status=result;
|
||||||
|
if(!result) {
|
||||||
|
TOKEN_PRIVILEGES enable={0},previous={0},restore={0};DWORD previous_bytes=0;
|
||||||
|
enable.PrivilegeCount=1;enable.Privileges[0].Luid=ctx.privilege;
|
||||||
|
enable.Privileges[0].Attributes=SE_PRIVILEGE_ENABLED;
|
||||||
|
restore.PrivilegeCount=1;restore.Privileges[0].Luid=ctx.privilege; /* saved original Attr0 */
|
||||||
|
ctx.enable_attempted=1; /* all paths after this call execute the one restore */
|
||||||
|
SetLastError(ERROR_SUCCESS);
|
||||||
|
ctx.enable_return=!!AdjustTokenPrivileges(ctx.own,FALSE,&enable,sizeof(previous),&previous,&previous_bytes);
|
||||||
|
ctx.enable_error=GetLastError();ctx.previous_count=previous.PrivilegeCount;ctx.previous_bytes=previous_bytes;
|
||||||
|
if(previous.PrivilegeCount==1) {
|
||||||
|
ctx.previous_luid_low=previous.Privileges[0].Luid.LowPart;
|
||||||
|
ctx.previous_luid_high=(DWORD)previous.Privileges[0].Luid.HighPart;
|
||||||
|
ctx.previous_attributes=previous.Privileges[0].Attributes;
|
||||||
|
if(previous_bytes==sizeof(previous) && luid_equal(previous.Privileges[0].Luid,ctx.privilege)
|
||||||
|
&& previous.Privileges[0].Attributes==0) {
|
||||||
|
restore=previous;ctx.restore_input_from_previous=1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if(!ctx.enable_return || ctx.enable_error || !ctx.restore_input_from_previous)
|
||||||
|
result=ctx.enable_error?ctx.enable_error:ERROR_INVALID_DATA;
|
||||||
|
if(!result)result=snapshot(ctx.own,&ctx.active);
|
||||||
|
if(!result)result=compare_snapshots(&ctx.before,&ctx.active,ctx.privilege,1);
|
||||||
|
if(!result)result=own_current(&ctx);
|
||||||
|
for(DWORD i=0;!result && i<4;++i)result=peer_binding(&ctx.peers[i],i);
|
||||||
|
ctx.active_status=result;
|
||||||
|
if(!result) {ctx.rpc_attempted=1;rpc=rmm_clock_query_trace_spnego_privilege(&trace,&eeinfo,&auth);}
|
||||||
|
/* No report IO or early return between adjustment and this restoration. */
|
||||||
|
ctx.restore_attempted=1;SetLastError(ERROR_SUCCESS);
|
||||||
|
ctx.restore_return=!!AdjustTokenPrivileges(ctx.own,FALSE,&restore,0,NULL,NULL);
|
||||||
|
ctx.restore_error=GetLastError();
|
||||||
|
ctx.restored_status=snapshot(ctx.own,&ctx.restored);
|
||||||
|
if(!ctx.restored_status)ctx.restored_status=compare_snapshots(&ctx.before,&ctx.restored,ctx.privilege,0);
|
||||||
|
if(!ctx.restored_status)ctx.restored_status=own_current(&ctx);
|
||||||
|
ctx.restoration_verified=ctx.restore_return && !ctx.restore_error && !ctx.restored_status;
|
||||||
|
if(!ctx.restoration_verified && !result)result=ctx.restore_error?ctx.restore_error:ERROR_INVALID_DATA;
|
||||||
|
for(DWORD i=0;i<4;++i) {
|
||||||
|
Peer *peer=&ctx.peers[i];DWORD status=peer_binding(peer,i);
|
||||||
|
if(!status)status=snapshot(peer->token,&peer->after);
|
||||||
|
if(!status && (!identity_equal(&peer->before,&peer->after)
|
||||||
|
|| !luid_equal(peer->before.statistics.ModifiedId,peer->after.statistics.ModifiedId)
|
||||||
|
|| peer->before.count!=peer->after.count))status=ERROR_INVALID_DATA;
|
||||||
|
for(DWORD j=0;!status && j<peer->before.count;++j)
|
||||||
|
if(!luid_equal(peer->before.privileges[j].Luid,peer->after.privileges[j].Luid)
|
||||||
|
|| peer->before.privileges[j].Attributes!=peer->after.privileges[j].Attributes)status=ERROR_INVALID_DATA;
|
||||||
|
if(status && !ctx.peer_after_status)ctx.peer_after_status=status;
|
||||||
|
}
|
||||||
|
if(ctx.peer_after_status && !result)result=ctx.peer_after_status;
|
||||||
|
}
|
||||||
|
ctx.flow_status=result;
|
||||||
|
DWORD adjustment_write=write_adjustment(&ctx);
|
||||||
|
if(!result)result=adjustment_write;
|
||||||
|
if(!ctx.rpc_attempted){rpc=ctx.flow_status;trace.stage=200;}
|
||||||
|
DWORD result_write=write_result(rpc,&trace,&eeinfo,&auth,&token);
|
||||||
|
if(!result)result=result_write;
|
||||||
|
close_privilege(&ctx);
|
||||||
|
service_status.dwCurrentState = SERVICE_STOPPED;
|
||||||
|
service_status.dwWin32ExitCode = result;
|
||||||
|
SetServiceStatus(status_handle, &service_status);
|
||||||
|
}
|
||||||
|
|
||||||
|
int wmain(int argc, WCHAR **argv) {
|
||||||
|
if (argc != 3 || wcscmp(argv[1], L"--service") || wcslen(argv[2]) != 36) return ERROR_INVALID_PARAMETER;
|
||||||
|
for (unsigned i = 0; i < 36; ++i) {
|
||||||
|
WCHAR value = argv[2][i];
|
||||||
|
if (i == 8 || i == 13 || i == 18 || i == 23) {
|
||||||
|
if (value != L'-') return ERROR_INVALID_PARAMETER;
|
||||||
|
} else if (!((value >= L'0' && value <= L'9') || (value >= L'a' && value <= L'f'))) return ERROR_INVALID_PARAMETER;
|
||||||
|
case_id[i] = value;
|
||||||
|
}
|
||||||
|
case_id[36] = 0;
|
||||||
|
SERVICE_TABLE_ENTRYW table[] = {{service_name, run_service}, {NULL, NULL}};
|
||||||
|
if (!StartServiceCtrlDispatcherW(table)) return (int)GetLastError();
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
@@ -0,0 +1,150 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Local-only bounded SYSTEM SPNEGO diagnostic; no VM or product source edits."""
|
||||||
|
import base64
|
||||||
|
import difflib
|
||||||
|
import hashlib
|
||||||
|
import importlib.util
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
import re
|
||||||
|
import shutil
|
||||||
|
import subprocess
|
||||||
|
import uuid
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parents[3]
|
||||||
|
HERE = Path(__file__).resolve().parent
|
||||||
|
STATE = ROOT / 'devstate/windows-clock-spnego-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'
|
||||||
|
UNCHANGED_DIAGNOSTICS = {
|
||||||
|
'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',
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def require(value, message):
|
||||||
|
if not value: raise RuntimeError(message)
|
||||||
|
|
||||||
|
|
||||||
|
def sha(path):
|
||||||
|
return hashlib.sha256(Path(path).read_bytes()).hexdigest()
|
||||||
|
|
||||||
|
|
||||||
|
def write(path, raw):
|
||||||
|
path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||||
|
fd = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY | os.O_NOFOLLOW, 0o600)
|
||||||
|
with os.fdopen(fd, 'wb') as output:
|
||||||
|
output.write(raw); output.flush(); os.fsync(output.fileno())
|
||||||
|
|
||||||
|
|
||||||
|
def save(path, value):
|
||||||
|
write(path, (json.dumps(value, indent=2) + '\n').encode())
|
||||||
|
|
||||||
|
|
||||||
|
def original_sources():
|
||||||
|
require(sha(BASELINE) == BASELINE_SHA, 'original b1d3 qualification')
|
||||||
|
value = json.loads(BASELINE.read_bytes())
|
||||||
|
require(len(value['source_files']) == 131 and value['artifact']['sha256'] == 'b1d3da4f393ddf20bc8e48a9894ee314666f2ac3613ef97f5c228e3d089ca560', 'unchanged complete original131 source set')
|
||||||
|
for name, digest in value['source_files'].items():
|
||||||
|
path = ROOT / name
|
||||||
|
require(not path.is_symlink() and path.is_file() and sha(path) == digest, 'original131 input changed')
|
||||||
|
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.c','system_trace_spnego.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.c'
|
||||||
|
write(source / 'clock_rpc.c', wrapper.read_bytes()); write(source / 'system_trace.c', (HERE / 'system_trace_spnego.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.c'))
|
||||||
|
write(folder / 'wrapper-source.diff',delta.encode())
|
||||||
|
save(folder / 'intent.json', dict(image=IMAGE, original131=baseline['source_files'], baseline_sha256=BASELINE_SHA,
|
||||||
|
actual_codegen_readback_sha256=READBACK_SHA, generated=generated, own_sources=before,
|
||||||
|
wrapper_sha256=sha(wrapper), original_wrapper_sha256=sha(baseline_wrapper), wrapper_diff_sha256=sha(folder / 'wrapper-source.diff'), unchanged_diagnostics=UNCHANGED_DIAGNOSTICS,
|
||||||
|
own_system_token_only=True,token_query_only=True,max_principal_discoveries=1,max_status_queries=1,principal_identity_proven=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/ClockSystemSpnegoTrace.linked.exe'])
|
||||||
|
raw_linked = output / 'ClockSystemSpnegoTrace.linked.exe'
|
||||||
|
linked = output / 'ClockSystemSpnegoTrace.original.exe'; delivery = output / 'ClockSystemSpnegoTrace.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/ClockSystemSpnegoTrace.exe'])
|
||||||
|
imports = sorted(set(re.findall(r'DLL Name:\s+(\S+)',run('imports',['x86_64-w64-mingw32-objdump','-p','/out/ClockSystemSpnegoTrace.exe']).decode())))
|
||||||
|
require(imports and {name.lower() for name in imports}.issubset({'kernel32.dll','msvcrt.dll','advapi32.dll','rpcrt4.dll','api-ms-win-core-realtime-l1-1-2.dll'}),'reviewed system DLL imports only')
|
||||||
|
data = delivery.read_bytes(); offset = int.from_bytes(data[60:64],'little')
|
||||||
|
require(data[:2] == b'MZ' and data[offset:offset+6] == b'PE\0\0\x64\x86' and len(data) < 1048576,'bounded standalone C x64 PE')
|
||||||
|
spec = importlib.util.spec_from_file_location('system_trace_native',HERE / 'native.py'); native = importlib.util.module_from_spec(spec); spec.loader.exec_module(native)
|
||||||
|
script = folder / 'native.ps1'; write(script,native.SCRIPT.encode())
|
||||||
|
parser = "$e=$null;$t=$null;[System.Management.Automation.Language.Parser]::ParseFile($args[0],[ref]$t,[ref]$e)|Out-Null;if($e.Count){$e|ForEach-Object{$_.Message};exit 1};'AST_PASS'"
|
||||||
|
parser_path = folder / 'parse-native.ps1'; write(parser_path,parser.encode())
|
||||||
|
parsed = subprocess.run(['/tmp/rmm-powershell-parser/pwsh','-NoLogo','-NoProfile','-NonInteractive','-File',str(parser_path),str(script)],capture_output=True,timeout=15)
|
||||||
|
write(folder / 'powershell-parser.stdout',parsed.stdout); write(folder / 'powershell-parser.stderr',parsed.stderr)
|
||||||
|
require(parsed.returncode == 0 and b'AST_PASS' in parsed.stdout and not parsed.stderr,'actual PowerShell AST')
|
||||||
|
command_chars = len(native.encoded_command())
|
||||||
|
require(command_chars < 32767,'Windows encoded command length')
|
||||||
|
require(original_sources()['source_files'] == baseline['source_files'] and own_sources() == before,'all original131 and new sources unchanged')
|
||||||
|
manifest = dict(schema_version=1,profile='clock-system-spnego-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=True,max_principal_discoveries=1,max_status_queries=1,principal_identity_proven=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,258 @@
|
|||||||
|
/* 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;
|
||||||
|
if (!i || 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_IDENTIFY;
|
||||||
|
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_IDENTIFY;
|
||||||
|
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(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,267 @@
|
|||||||
|
#!/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-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-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='RmmClockSystemSpnegoDiagnostic';$case=Join-Path $root ('clock-spnego-trace-'+$id);$exe=Join-Path $case 'ClockSystemSpnegoTrace.exe';$command='"'+$exe+'" --service '+$id
|
||||||
|
function Test-RmmTracePrivate($path,$dir){$i=Get-Item -LiteralPath $path -Force;if($i.PSIsContainer-ne$dir-or($i.Attributes-band[IO.FileAttributes]::ReparsePoint)){throw 'Private object type'};$a=Get-Acl -LiteralPath $path;if($a.GetOwner([Security.Principal.SecurityIdentifier]).Value-notin@('S-1-5-18','S-1-5-32-544')){throw 'Private object owner'};$rules=@($a.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier]));if(!$rules.Count){throw 'Empty private ACL'};foreach($e in $rules){if($e.AccessControlType-ne'Allow'-or$e.IdentityReference.Value-notin@('S-1-5-18','S-1-5-32-544')-or($e.PropagationFlags-band[Security.AccessControl.PropagationFlags]::InheritOnly)){throw 'Broad private ACL'}}}
|
||||||
|
function Write-RmmTraceNew($path,$value){$f=[IO.File]::Open($path,[IO.FileMode]::CreateNew,[IO.FileAccess]::Write,[IO.FileShare]::Read);try{$b=[Text.Encoding]::UTF8.GetBytes(($value|ConvertTo-Json -Depth 12 -Compress));$f.Write($b,0,$b.Length);$f.Flush($true)}finally{$f.Dispose()}}
|
||||||
|
function Get-RmmTraceJson($path){Test-RmmTracePrivate $path $false;if((Get-Item -LiteralPath $path).Length-gt16384){throw 'Small diagnostic receipt'};return(Get-Content -LiteralPath $path -Raw|ConvertFrom-Json)}
|
||||||
|
function Get-RmmTraceService{return(Get-CimInstance Win32_Service -Filter "Name='RmmClockSystemSpnegoDiagnostic'" -OperationTimeoutSec 5)}
|
||||||
|
function Test-RmmTraceService($s){if($s-and($s.PathName-cne$command-or$s.StartName-cne'LocalSystem'-or$s.StartMode-cne'Manual')){throw 'Only own exact temporary service'}}
|
||||||
|
if($p.action-eq'readback'-and!(Test-Path -LiteralPath $case)){@{id=$id;status='remote_case_absent';read_only=$true}|ConvertTo-Json -Compress;exit 0}
|
||||||
|
Test-RmmTracePrivate $root $true
|
||||||
|
if($p.action-eq'prepare'){if((Test-Path -LiteralPath $case)-or(Get-RmmTraceService)){throw 'Existing case/service retained'};New-Item -ItemType Directory -Path $case|Out-Null;Test-RmmTracePrivate $case $true;Write-RmmTraceNew (Join-Path $case 'intent.json') $p;@{id=$id;prepared=$true}|ConvertTo-Json -Compress;exit 0}
|
||||||
|
Test-RmmTracePrivate $case $true;$old=Get-RmmTraceJson (Join-Path $case 'intent.json')
|
||||||
|
foreach($field in @('id','profile','binary_sha256','manifest_sha256','script_sha256','binary_bytes')){if($old.$field-cne$p.$field){throw 'Original exact diagnostic intent'}}
|
||||||
|
Test-RmmTracePrivate $exe $false;if((Get-Item -LiteralPath $exe).Length-ne$p.binary_bytes-or(Get-FileHash -LiteralPath $exe -Algorithm SHA256).Hash.ToLowerInvariant()-cne$p.binary_sha256){throw 'Exact diagnostic executable'}
|
||||||
|
$s=Get-RmmTraceService;Test-RmmTraceService $s
|
||||||
|
if($p.action-eq'start'){
|
||||||
|
if($s-or(Test-Path -LiteralPath (Join-Path $case 'start-intent.json'))){throw 'No repeated start; original readback only'}
|
||||||
|
Write-RmmTraceNew (Join-Path $case 'start-intent.json') @{id=$id;command=$command;binary_sha256=$p.binary_sha256;create_once=$true}
|
||||||
|
New-Service -Name $name -BinaryPathName $command -StartupType Manual|Out-Null
|
||||||
|
$s=Get-RmmTraceService;Test-RmmTraceService $s;if(!$s){throw 'Own service creation missing'}
|
||||||
|
Write-RmmTraceNew (Join-Path $case 'service-created.json') @{id=$id;command=$command;start_name=$s.StartName}
|
||||||
|
Write-RmmTraceNew (Join-Path $case 'service-start-intent.json') @{start_once=$true}
|
||||||
|
Start-Service -Name $name
|
||||||
|
$deadline=[DateTime]::UtcNow.AddSeconds(20)
|
||||||
|
do{$s=Get-RmmTraceService;Test-RmmTraceService $s;if(!$s-or$s.State-eq'Stopped'){break};Start-Sleep -Milliseconds 100}while([DateTime]::UtcNow-lt$deadline)
|
||||||
|
}
|
||||||
|
if($p.action-eq'cleanup'){
|
||||||
|
if(!$s){if(!(Test-Path -LiteralPath (Join-Path $case 'cleanup-intent.json'))){throw 'Missing service without bound cleanup'};@{id=$id;cleanup_verified=$true;already_absent=$true;read_only=$true}|ConvertTo-Json -Compress;exit 0}
|
||||||
|
if($s.State-cne'Stopped'){throw 'Cleanup only own bound stopped service'}
|
||||||
|
$created=Get-RmmTraceJson (Join-Path $case 'service-created.json');if($created.id-cne$id-or$created.command-cne$command-or$created.start_name-cne'LocalSystem'){throw 'Original service creation binding'}
|
||||||
|
if(Test-Path -LiteralPath (Join-Path $case 'cleanup-intent.json')){throw 'Cleanup already attempted; readback only'}
|
||||||
|
Write-RmmTraceNew (Join-Path $case 'cleanup-intent.json') @{id=$id;command=$command;delete_once=$true}
|
||||||
|
& "$env:WINDIR\System32\sc.exe" delete $name|Out-Null;if($LASTEXITCODE-ne0){throw 'Own stopped service deletion incomplete'}
|
||||||
|
if(Get-RmmTraceService){throw 'Own service still registered; readback only'}
|
||||||
|
Write-RmmTraceNew (Join-Path $case 'cleanup-completed.json') @{id=$id;service_absent=$true}
|
||||||
|
@{id=$id;cleanup_verified=$true;already_absent=$false;read_only=$false}|ConvertTo-Json -Compress;exit 0
|
||||||
|
}
|
||||||
|
$report=$null;$result=Join-Path $case 'result.json';if(Test-Path -LiteralPath $result){$report=Get-RmmTraceJson $result}
|
||||||
|
$token=$null;$tokenFile=Join-Path $case 'token.json';if(Test-Path -LiteralPath $tokenFile){$token=Get-RmmTraceJson $tokenFile}
|
||||||
|
$cleaned=$false;$cleanupReceipt=Join-Path $case 'cleanup-completed.json';if(Test-Path -LiteralPath $cleanupReceipt){$c=Get-RmmTraceJson $cleanupReceipt;if($c.id-cne$id-or$c.service_absent-ne$true){throw 'Bound cleanup receipt'};$cleaned=$true}
|
||||||
|
@{id=$id;service_present=[bool]$s;service_state=$(if($s){$s.State}else{$null});service_exit_code=$(if($s){$s.ExitCode}else{$null});start_intent_present=(Test-Path -LiteralPath (Join-Path $case 'service-start-intent.json'));cleanup_intent_present=(Test-Path -LiteralPath (Join-Path $case 'cleanup-intent.json'));cleanup_completed=$cleaned;report=$report;token_before_rpc=$token;read_only=($p.action-eq'readback');no_rmm_jobs=$true;no_w32time_change=$true;no_agent_change=$true}|ConvertTo-Json -Depth 12 -Compress
|
||||||
|
'''
|
||||||
|
|
||||||
|
|
||||||
|
def encoded_command():
|
||||||
|
script = 'try {\n'+SCRIPT+'\n} catch {[pscustomobject]@{bootstrap_error=$true;error_id=$_.FullyQualifiedErrorId;line=$_.InvocationInfo.ScriptLineNumber}|ConvertTo-Json -Compress;exit 1}'
|
||||||
|
return 'powershell.exe -NoLogo -NoProfile -NonInteractive -EncodedCommand '+base64.b64encode(script.encode('utf-16le')).decode()
|
||||||
|
|
||||||
|
|
||||||
|
def manifest(path):
|
||||||
|
path = path.absolute(); private(path.parent,True)
|
||||||
|
require(path.name == 'manifest.json' and path.parent.parent == STATE and re.fullmatch(r'build-[0-9a-f-]{36}',path.parent.name),'fixed local build manifest')
|
||||||
|
value = load(path)
|
||||||
|
require(value['profile'] == 'clock-system-spnego-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 True and value['max_principal_discoveries']==value['max_status_queries']==1
|
||||||
|
and value['principal_identity_proven'] is False,'no privilege mutation/fallback or principal-as-identity claim')
|
||||||
|
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_report(value,ident):
|
||||||
|
require(value['id'] == ident and value['no_rmm_jobs'] is True and value['no_w32time_change'] is True and value['no_agent_change'] is True,'exact nonproduct diagnostic case')
|
||||||
|
report=value.get('report')
|
||||||
|
if report is None:return False
|
||||||
|
require(report['schema_version'] == 1 and report['profile'] == 'clock-system-spnego-v1' and report['case_id'] == ident
|
||||||
|
and report['token_system'] is True and report['read_only'] is True and report['diagnostic_only'] is True
|
||||||
|
and 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']==2
|
||||||
|
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 1<=auth['principal_units']<=512,'checked nonempty bounded principal')
|
||||||
|
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 1<=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)
|
||||||
|
|
||||||
|
|
||||||
|
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-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-trace-'+ident+'/ClockSystemSpnegoTrace.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,233 @@
|
|||||||
|
/* Isolated SPNEGO diagnostic. Original MIDL remains unchanged. Read the own
|
||||||
|
* SYSTEM token first; one management discovery, then at most one status query.
|
||||||
|
* 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>
|
||||||
|
|
||||||
|
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(RmmClockTrace *trace, RmmClockEeInfo *eeinfo, RmmClockAuthTrace *auth);
|
||||||
|
|
||||||
|
static WCHAR service_name[] = L"RmmClockSystemSpnegoDiagnostic";
|
||||||
|
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-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);
|
||||||
|
}
|
||||||
|
|
||||||
|
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-v1\",\"case_id\":\"%s\","
|
||||||
|
"\"token_system\":true,\"read_only\":true,\"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, (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};
|
||||||
|
DWORD result = own_system_token(&token);
|
||||||
|
DWORD token_write = write_token(&token); /* durable numeric witness before RPC */
|
||||||
|
if (!result) result = token_write;
|
||||||
|
if (!result) {
|
||||||
|
RmmClockTrace trace = {0};
|
||||||
|
RmmClockEeInfo eeinfo = {0};
|
||||||
|
RmmClockAuthTrace auth = {0};
|
||||||
|
uint32_t rpc = rmm_clock_query_trace_spnego(&trace, &eeinfo, &auth);
|
||||||
|
result = write_result(rpc, &trace, &eeinfo, &auth, &token);
|
||||||
|
}
|
||||||
|
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,133 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Local-only SYSTEM trace diagnostic build; no VM and no product source edits."""
|
||||||
|
import base64
|
||||||
|
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-system-trace'
|
||||||
|
IMAGE = 'sha256:1b2fd985d2c1fcc3545ace602405dc68fa899201bd8a73fa319ff96377203fa9'
|
||||||
|
BASELINE = ROOT / 'devstate/windows-clock-midl/diagnostic-builds/181c3a1c-8324-41fd-9b7c-aa8010262912/qualification.json'
|
||||||
|
BASELINE_SHA = '2e0de3acf72ab5c3a8e0baa54e8643d086ea7c03d1b38fd89b6bfc00e45f8cbb'
|
||||||
|
NATIVE = ROOT / 'devstate/windows-clock-midl/native-cases/149bafe2-3469-4580-b133-988812bcc3db'
|
||||||
|
READBACK = NATIVE / 'readback-059c15ef-0f31-41aa-ad1d-ea6b774280d7.json'
|
||||||
|
READBACK_SHA = '0dc2373825f7f8f224cda04ecd5c521dd3c37a6e712bc3ed83bc4fa6d0d89c8c'
|
||||||
|
|
||||||
|
|
||||||
|
def require(value, message):
|
||||||
|
if not value: raise RuntimeError(message)
|
||||||
|
|
||||||
|
|
||||||
|
def sha(path):
|
||||||
|
return hashlib.sha256(Path(path).read_bytes()).hexdigest()
|
||||||
|
|
||||||
|
|
||||||
|
def write(path, raw):
|
||||||
|
path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||||
|
fd = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY | os.O_NOFOLLOW, 0o600)
|
||||||
|
with os.fdopen(fd, 'wb') as output:
|
||||||
|
output.write(raw); output.flush(); os.fsync(output.fileno())
|
||||||
|
|
||||||
|
|
||||||
|
def save(path, value):
|
||||||
|
write(path, (json.dumps(value, indent=2) + '\n').encode())
|
||||||
|
|
||||||
|
|
||||||
|
def original_sources():
|
||||||
|
require(sha(BASELINE) == BASELINE_SHA, 'original b1d3 qualification')
|
||||||
|
value = json.loads(BASELINE.read_bytes())
|
||||||
|
require(len(value['source_files']) == 131 and value['artifact']['sha256'] == 'b1d3da4f393ddf20bc8e48a9894ee314666f2ac3613ef97f5c228e3d089ca560', 'unchanged complete original131 source set')
|
||||||
|
for name, digest in value['source_files'].items():
|
||||||
|
path = ROOT / name
|
||||||
|
require(not path.is_symlink() and path.is_file() and sha(path) == digest, 'original131 input changed')
|
||||||
|
return value
|
||||||
|
|
||||||
|
|
||||||
|
def own_sources():
|
||||||
|
return {str((HERE / name).relative_to(ROOT)):sha(HERE / name) for name in ('system_trace.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
|
||||||
|
wrapper = ROOT / 'crates/agent-windows/native/clock_rpc.c'
|
||||||
|
write(source / 'clock_rpc.c', wrapper.read_bytes()); write(source / 'system_trace.c', (HERE / 'system_trace.c').read_bytes())
|
||||||
|
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), own_system_token_only=True, exactly_one_trace_call=True, no_vm=True))
|
||||||
|
output = folder / 'output'; output.mkdir(mode=0o700)
|
||||||
|
checks = {}
|
||||||
|
def run(name, args):
|
||||||
|
command = ['docker','run','--rm','--network','none','--read-only','--tmpfs','/tmp:rw,size=128m',
|
||||||
|
'-v',str(source)+':/src:ro','-v',str(output)+':/out','--entrypoint',args[0],IMAGE,*args[1:]]
|
||||||
|
done = subprocess.run(command,capture_output=True,timeout=120)
|
||||||
|
write(folder / (name+'.stdout'),done.stdout); write(folder / (name+'.stderr'),done.stderr)
|
||||||
|
checks[name] = dict(exit_code=done.returncode,command=command,stdout_sha256=sha(folder / (name+'.stdout')),stderr_sha256=sha(folder / (name+'.stderr')))
|
||||||
|
save(folder / (name+'.json'),checks[name]); require(done.returncode == 0,'local diagnostic compile/check failure: '+name)
|
||||||
|
return done.stdout
|
||||||
|
flags = ['--target=x86_64-w64-windows-gnu','-fms-extensions','-Wall','-Wextra','-Werror','-D_M_AMD64=100','-I/src','-O2']
|
||||||
|
run('main',['clang',*flags,'-c','/src/system_trace.c','-o','/out/system_trace.o'])
|
||||||
|
run('wrapper',['clang',*flags,'-c','/src/clock_rpc.c','-o','/out/clock_rpc.o'])
|
||||||
|
run('actual-midl',['clang',*flags,'-Wno-error=missing-braces','-Wno-error=unused-const-variable','-c','/src/w32time_c.c','-o','/out/w32time_c.o'])
|
||||||
|
run('link',['x86_64-w64-mingw32-gcc','-static-libgcc','-municode','/out/system_trace.o','/out/clock_rpc.o','/out/w32time_c.o',
|
||||||
|
'-lrpcrt4','-ladvapi32','-lkernel32','-lmincore','-o','/out/ClockSystemTrace.linked.exe'])
|
||||||
|
raw_linked = output / 'ClockSystemTrace.linked.exe'
|
||||||
|
linked = output / 'ClockSystemTrace.original.exe'; delivery = output / 'ClockSystemTrace.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/ClockSystemTrace.exe'])
|
||||||
|
imports = sorted(set(re.findall(r'DLL Name:\s+(\S+)',run('imports',['x86_64-w64-mingw32-objdump','-p','/out/ClockSystemTrace.exe']).decode())))
|
||||||
|
require(imports and {name.lower() for name in imports}.issubset({'kernel32.dll','msvcrt.dll','advapi32.dll','rpcrt4.dll','api-ms-win-core-realtime-l1-1-2.dll'}),'reviewed system DLL imports only')
|
||||||
|
data = delivery.read_bytes(); offset = int.from_bytes(data[60:64],'little')
|
||||||
|
require(data[:2] == b'MZ' and data[offset:offset+6] == b'PE\0\0\x64\x86' and len(data) < 1048576,'bounded standalone C x64 PE')
|
||||||
|
spec = importlib.util.spec_from_file_location('system_trace_native',HERE / 'native.py'); native = importlib.util.module_from_spec(spec); spec.loader.exec_module(native)
|
||||||
|
script = folder / 'native.ps1'; write(script,native.SCRIPT.encode())
|
||||||
|
parser = "$e=$null;$t=$null;[System.Management.Automation.Language.Parser]::ParseFile($args[0],[ref]$t,[ref]$e)|Out-Null;if($e.Count){$e|ForEach-Object{$_.Message};exit 1};'AST_PASS'"
|
||||||
|
parser_path = folder / 'parse-native.ps1'; write(parser_path,parser.encode())
|
||||||
|
parsed = subprocess.run(['/tmp/rmm-powershell-parser/pwsh','-NoLogo','-NoProfile','-NonInteractive','-File',str(parser_path),str(script)],capture_output=True,timeout=15)
|
||||||
|
write(folder / 'powershell-parser.stdout',parsed.stdout); write(folder / 'powershell-parser.stderr',parsed.stderr)
|
||||||
|
require(parsed.returncode == 0 and b'AST_PASS' in parsed.stdout and not parsed.stderr,'actual PowerShell AST')
|
||||||
|
command_chars = len(native.encoded_command())
|
||||||
|
require(command_chars < 32767,'Windows encoded command length')
|
||||||
|
require(original_sources()['source_files'] == baseline['source_files'] and own_sources() == before,'all original131 and new sources unchanged')
|
||||||
|
manifest = dict(schema_version=1,profile='clock-system-trace-v1',image=IMAGE,baseline_sha256=BASELINE_SHA,
|
||||||
|
original131=baseline['source_files'],own_sources=before,wrapper_sha256=sha(wrapper),generated=generated,
|
||||||
|
actual_codegen_readback_sha256=READBACK_SHA,checks=checks,script_sha256=hashlib.sha256(native.SCRIPT.encode()).hexdigest(),
|
||||||
|
powershell_ast_passed=True,encoded_command_characters=command_chars,
|
||||||
|
artifact=dict(path=str(delivery),sha256=sha(delivery),bytes=len(data),imports=imports),
|
||||||
|
linked=dict(path=str(linked),sha256=sha(linked)),raw_linked_sha256=sha(raw_linked),native_executed=False,clock_qualified=False,
|
||||||
|
adapter_qualified=False,product_gate_open=False,no_vm=True,no_rmm_jobs=True)
|
||||||
|
save(folder / 'manifest.json',manifest)
|
||||||
|
print(json.dumps(dict(manifest=str(folder / 'manifest.json'),manifest_sha256=sha(folder / 'manifest.json'),artifact=manifest['artifact'],
|
||||||
|
original131_unchanged=True,powershell_ast=True,command_characters=command_chars,native_executed=False)))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
try: main()
|
||||||
|
except Exception as error:
|
||||||
|
print(json.dumps(dict(error='CLOCK_SYSTEM_TRACE_LOCAL_INCOMPLETE',error_class=type(error).__name__,details_suppressed=True)))
|
||||||
|
raise SystemExit(2) from None
|
||||||
@@ -0,0 +1,222 @@
|
|||||||
|
#!/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-system-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-trace-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='RmmClockSystemDiagnostic';$case=Join-Path $root ('clock-system-trace-'+$id);$exe=Join-Path $case 'ClockSystemTrace.exe';$command='"'+$exe+'" --service '+$id
|
||||||
|
function Test-RmmTracePrivate($path,$dir){$i=Get-Item -LiteralPath $path -Force;if($i.PSIsContainer-ne$dir-or($i.Attributes-band[IO.FileAttributes]::ReparsePoint)){throw 'Private object type'};$a=Get-Acl -LiteralPath $path;if($a.GetOwner([Security.Principal.SecurityIdentifier]).Value-notin@('S-1-5-18','S-1-5-32-544')){throw 'Private object owner'};$rules=@($a.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier]));if(!$rules.Count){throw 'Empty private ACL'};foreach($e in $rules){if($e.AccessControlType-ne'Allow'-or$e.IdentityReference.Value-notin@('S-1-5-18','S-1-5-32-544')-or($e.PropagationFlags-band[Security.AccessControl.PropagationFlags]::InheritOnly)){throw 'Broad private ACL'}}}
|
||||||
|
function Write-RmmTraceNew($path,$value){$f=[IO.File]::Open($path,[IO.FileMode]::CreateNew,[IO.FileAccess]::Write,[IO.FileShare]::Read);try{$b=[Text.Encoding]::UTF8.GetBytes(($value|ConvertTo-Json -Depth 12 -Compress));$f.Write($b,0,$b.Length);$f.Flush($true)}finally{$f.Dispose()}}
|
||||||
|
function Get-RmmTraceJson($path){Test-RmmTracePrivate $path $false;if((Get-Item -LiteralPath $path).Length-gt16384){throw 'Small diagnostic receipt'};return(Get-Content -LiteralPath $path -Raw|ConvertFrom-Json)}
|
||||||
|
function Get-RmmTraceService{return(Get-CimInstance Win32_Service -Filter "Name='RmmClockSystemDiagnostic'" -OperationTimeoutSec 5)}
|
||||||
|
function Test-RmmTraceService($s){if($s-and($s.PathName-cne$command-or$s.StartName-cne'LocalSystem'-or$s.StartMode-cne'Manual')){throw 'Only own exact temporary service'}}
|
||||||
|
if($p.action-eq'readback'-and!(Test-Path -LiteralPath $case)){@{id=$id;status='remote_case_absent';read_only=$true}|ConvertTo-Json -Compress;exit 0}
|
||||||
|
Test-RmmTracePrivate $root $true
|
||||||
|
if($p.action-eq'prepare'){if((Test-Path -LiteralPath $case)-or(Get-RmmTraceService)){throw 'Existing case/service retained'};New-Item -ItemType Directory -Path $case|Out-Null;Test-RmmTracePrivate $case $true;Write-RmmTraceNew (Join-Path $case 'intent.json') $p;@{id=$id;prepared=$true}|ConvertTo-Json -Compress;exit 0}
|
||||||
|
Test-RmmTracePrivate $case $true;$old=Get-RmmTraceJson (Join-Path $case 'intent.json')
|
||||||
|
foreach($field in @('id','profile','binary_sha256','manifest_sha256','script_sha256','binary_bytes')){if($old.$field-cne$p.$field){throw 'Original exact diagnostic intent'}}
|
||||||
|
Test-RmmTracePrivate $exe $false;if((Get-Item -LiteralPath $exe).Length-ne$p.binary_bytes-or(Get-FileHash -LiteralPath $exe -Algorithm SHA256).Hash.ToLowerInvariant()-cne$p.binary_sha256){throw 'Exact diagnostic executable'}
|
||||||
|
$s=Get-RmmTraceService;Test-RmmTraceService $s
|
||||||
|
if($p.action-eq'start'){
|
||||||
|
if($s-or(Test-Path -LiteralPath (Join-Path $case 'start-intent.json'))){throw 'No repeated start; original readback only'}
|
||||||
|
Write-RmmTraceNew (Join-Path $case 'start-intent.json') @{id=$id;command=$command;binary_sha256=$p.binary_sha256;create_once=$true}
|
||||||
|
New-Service -Name $name -BinaryPathName $command -StartupType Manual|Out-Null
|
||||||
|
$s=Get-RmmTraceService;Test-RmmTraceService $s;if(!$s){throw 'Own service creation missing'}
|
||||||
|
Write-RmmTraceNew (Join-Path $case 'service-created.json') @{id=$id;command=$command;start_name=$s.StartName}
|
||||||
|
Write-RmmTraceNew (Join-Path $case 'service-start-intent.json') @{start_once=$true}
|
||||||
|
Start-Service -Name $name
|
||||||
|
$deadline=[DateTime]::UtcNow.AddSeconds(20)
|
||||||
|
do{$s=Get-RmmTraceService;Test-RmmTraceService $s;if(!$s-or$s.State-eq'Stopped'){break};Start-Sleep -Milliseconds 100}while([DateTime]::UtcNow-lt$deadline)
|
||||||
|
}
|
||||||
|
if($p.action-eq'cleanup'){
|
||||||
|
if(!$s){if(!(Test-Path -LiteralPath (Join-Path $case 'cleanup-intent.json'))){throw 'Missing service without bound cleanup'};@{id=$id;cleanup_verified=$true;already_absent=$true;read_only=$true}|ConvertTo-Json -Compress;exit 0}
|
||||||
|
if($s.State-cne'Stopped'){throw 'Cleanup only own bound stopped service'}
|
||||||
|
$created=Get-RmmTraceJson (Join-Path $case 'service-created.json');if($created.id-cne$id-or$created.command-cne$command-or$created.start_name-cne'LocalSystem'){throw 'Original service creation binding'}
|
||||||
|
if(Test-Path -LiteralPath (Join-Path $case 'cleanup-intent.json')){throw 'Cleanup already attempted; readback only'}
|
||||||
|
Write-RmmTraceNew (Join-Path $case 'cleanup-intent.json') @{id=$id;command=$command;delete_once=$true}
|
||||||
|
& "$env:WINDIR\System32\sc.exe" delete $name|Out-Null;if($LASTEXITCODE-ne0){throw 'Own stopped service deletion incomplete'}
|
||||||
|
if(Get-RmmTraceService){throw 'Own service still registered; readback only'}
|
||||||
|
Write-RmmTraceNew (Join-Path $case 'cleanup-completed.json') @{id=$id;service_absent=$true}
|
||||||
|
@{id=$id;cleanup_verified=$true;already_absent=$false;read_only=$false}|ConvertTo-Json -Compress;exit 0
|
||||||
|
}
|
||||||
|
$report=$null;$result=Join-Path $case 'result.json';if(Test-Path -LiteralPath $result){$report=Get-RmmTraceJson $result}
|
||||||
|
$cleaned=$false;$cleanupReceipt=Join-Path $case 'cleanup-completed.json';if(Test-Path -LiteralPath $cleanupReceipt){$c=Get-RmmTraceJson $cleanupReceipt;if($c.id-cne$id-or$c.service_absent-ne$true){throw 'Bound cleanup receipt'};$cleaned=$true}
|
||||||
|
@{id=$id;service_present=[bool]$s;service_state=$(if($s){$s.State}else{$null});service_exit_code=$(if($s){$s.ExitCode}else{$null});start_intent_present=(Test-Path -LiteralPath (Join-Path $case 'service-start-intent.json'));cleanup_intent_present=(Test-Path -LiteralPath (Join-Path $case 'cleanup-intent.json'));cleanup_completed=$cleaned;report=$report;read_only=($p.action-eq'readback');no_rmm_jobs=$true;no_w32time_change=$true;no_agent_change=$true}|ConvertTo-Json -Depth 12 -Compress
|
||||||
|
'''
|
||||||
|
|
||||||
|
|
||||||
|
def encoded_command():
|
||||||
|
script = 'try {\n'+SCRIPT+'\n} catch {[pscustomobject]@{bootstrap_error=$true;error_id=$_.FullyQualifiedErrorId;line=$_.InvocationInfo.ScriptLineNumber}|ConvertTo-Json -Compress;exit 1}'
|
||||||
|
return 'powershell.exe -NoLogo -NoProfile -NonInteractive -EncodedCommand '+base64.b64encode(script.encode('utf-16le')).decode()
|
||||||
|
|
||||||
|
|
||||||
|
def manifest(path):
|
||||||
|
path = path.absolute(); private(path.parent,True)
|
||||||
|
require(path.name == 'manifest.json' and path.parent.parent == STATE and re.fullmatch(r'build-[0-9a-f-]{36}',path.parent.name),'fixed local build manifest')
|
||||||
|
value = load(path)
|
||||||
|
require(value['profile'] == 'clock-system-trace-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')
|
||||||
|
for name,digest in value['own_sources'].items():require(sha(ROOT / name) == digest,'same original local driver source')
|
||||||
|
for name in ('artifact','linked'):
|
||||||
|
item=value[name];p=Path(item['path']);require(p.parent == path.parent / 'output','fixed retained PE path');private(p);require(sha(p) == item['sha256'],'retained exact diagnostic PE')
|
||||||
|
require(Path(value['artifact']['path']).stat().st_size == value['artifact']['bytes'],'exact PE size')
|
||||||
|
return value
|
||||||
|
|
||||||
|
|
||||||
|
def access(root):
|
||||||
|
require(root == ACCESS_ROOT and root.resolve() == root,'existing Main access root only')
|
||||||
|
sys.path.insert(0,str(ROOT / 'deploy'))
|
||||||
|
import vm_access_check
|
||||||
|
config = vm_access_check.load_config(root / 'credentials/server.conf')
|
||||||
|
require(config['address'] == '88.99.80.202' and config['username'] == 'root' and config.get('port','22') == '22','fixed existing cloud reverse jump')
|
||||||
|
record=load(root / 'credentials/windows-dev-access.json');expiry=dt.datetime.fromisoformat(record['expires_at'])
|
||||||
|
require(expiry.utcoffset() is not None and dt.datetime.now(dt.timezone.utc) < expiry,'current existing access only')
|
||||||
|
private(root / 'credentials',True);private(root / 'credentials/windows-dev.known_hosts')
|
||||||
|
key=str(Path(config['ssh_key_path']).expanduser())
|
||||||
|
jump=['ssh','-F','/dev/null','-T','-p','22','-i',key,'-o','StrictHostKeyChecking=yes','-o','BatchMode=yes','-o','ForwardAgent=no','-o','IdentitiesOnly=yes','-W','127.0.0.1:22240','root@88.99.80.202']
|
||||||
|
prefix=['ssh','-F','/dev/null','-T','-i',key,'-o','ProxyCommand='+shlex.join(jump),'-o','HostKeyAlias=rmm-windows-dev','-o','UserKnownHostsFile='+str(root / 'credentials/windows-dev.known_hosts'),'-o','GlobalKnownHostsFile=/dev/null','-o','StrictHostKeyChecking=yes','-o','BatchMode=yes','-o','IdentitiesOnly=yes','-o','ForwardAgent=no','-o','ConnectTimeout=10','rmm-dev@127.0.0.1']
|
||||||
|
require(record['ssh_prefix'] == prefix,'original pinned transport only')
|
||||||
|
return prefix
|
||||||
|
|
||||||
|
|
||||||
|
def run_transport(args,data,folder):
|
||||||
|
try:
|
||||||
|
done=subprocess.run(args,input=data,capture_output=True,timeout=50)
|
||||||
|
save(folder / ('transport-'+str(uuid.uuid4())+'.json'),dict(returncode=done.returncode,stdout_b64=base64.b64encode(done.stdout).decode(),stderr_b64=base64.b64encode(done.stderr).decode()))
|
||||||
|
require(done.returncode == 0,'transport incomplete; original readback only')
|
||||||
|
return done.stdout
|
||||||
|
except subprocess.TimeoutExpired as error:
|
||||||
|
save(folder / ('transport-timeout-'+str(uuid.uuid4())+'.json'),dict(timed_out=True,stdout_b64=base64.b64encode(error.stdout or b'').decode(),stderr_b64=base64.b64encode(error.stderr or b'').decode()))
|
||||||
|
raise RuntimeError('lost reply; no repeated operation') from None
|
||||||
|
|
||||||
|
|
||||||
|
def rpc(prefix,payload,folder):
|
||||||
|
value=json.loads(run_transport(prefix+[encoded_command()],(json.dumps(payload)+'\n').encode(),folder).decode('utf-8-sig'),object_pairs_hook=pairs)
|
||||||
|
require(isinstance(value,dict) and 'bootstrap_error' not in value,'remote diagnostic incomplete')
|
||||||
|
return value
|
||||||
|
|
||||||
|
|
||||||
|
def check_report(value,ident):
|
||||||
|
require(value['id'] == ident and value['no_rmm_jobs'] is True and value['no_w32time_change'] is True and value['no_agent_change'] is True,'exact nonproduct diagnostic case')
|
||||||
|
report=value.get('report')
|
||||||
|
if report is None:return False
|
||||||
|
require(report['schema_version'] == 1 and report['profile'] == 'clock-system-trace-v1' and report['case_id'] == ident
|
||||||
|
and report['token_system'] is True and report['read_only'] is True and report['diagnostic_only'] is True
|
||||||
|
and report['query_invocations'] == 1 and report['clock_qualified'] is False and report['adapter_qualified'] is False
|
||||||
|
and report['product_gate_open'] is False,'actual SYSTEM token and single nonqualifying trace')
|
||||||
|
fields={'stage','native_rpc_return','native_rpc_return_present','rpc_exception','status_present','ul_size','c_entries','p_entries_present'}
|
||||||
|
require(set(report['trace']) == fields and type(report['rpc_code']) is int and 0 <= report['rpc_code'] < 2**32
|
||||||
|
and all(type(n) is int and 0 <= n < 2**32 for n in report['trace'].values()),'bounded numeric trace only')
|
||||||
|
return (value['service_state'] == 'Stopped' and value['service_exit_code'] == 0) or (value['service_present'] is False and value['cleanup_completed'] is True)
|
||||||
|
|
||||||
|
|
||||||
|
def execute(action,path,root,ident):
|
||||||
|
os.umask(0o077);STATE.mkdir(mode=0o700,exist_ok=True);private(STATE,True)
|
||||||
|
value=manifest(path);prefix=access(root)
|
||||||
|
if action == 'prepare':
|
||||||
|
require(not ident,'new diagnostic case only');ident=str(uuid.uuid4());folder=STATE / ident;folder.mkdir(mode=0o700)
|
||||||
|
payload=dict(id=ident,profile='clock-system-trace-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-system-trace-'+ident+'/ClockSystemTrace.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,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,99 @@
|
|||||||
|
/* Standalone diagnostic only. The original C/Auth/MIDL inputs are linked
|
||||||
|
* unchanged. Exactly one trace query, only under this process's SYSTEM token.
|
||||||
|
* No clock setter, token impersonation, NTP/ACL/provider or product gate. */
|
||||||
|
#define _WIN32_WINNT 0x0a00
|
||||||
|
#include <windows.h>
|
||||||
|
#include <stdint.h>
|
||||||
|
#include <stdio.h>
|
||||||
|
#include <wchar.h>
|
||||||
|
|
||||||
|
typedef struct {
|
||||||
|
uint32_t stage, native_rpc_return, native_rpc_return_present, rpc_exception;
|
||||||
|
uint32_t status_present, ul_size, c_entries, p_entries_present;
|
||||||
|
} RmmClockTrace;
|
||||||
|
_Static_assert(sizeof(RmmClockTrace) == 32, "same diagnostic trace ABI");
|
||||||
|
uint32_t rmm_clock_query_trace(RmmClockTrace *trace);
|
||||||
|
|
||||||
|
static WCHAR service_name[] = L"RmmClockSystemDiagnostic";
|
||||||
|
static WCHAR case_id[37];
|
||||||
|
static SERVICE_STATUS_HANDLE status_handle;
|
||||||
|
static SERVICE_STATUS service_status;
|
||||||
|
|
||||||
|
static DWORD WINAPI control(DWORD event, DWORD type, void *data, void *context) {
|
||||||
|
(void)event; (void)type; (void)data; (void)context;
|
||||||
|
return ERROR_CALL_NOT_IMPLEMENTED;
|
||||||
|
}
|
||||||
|
|
||||||
|
static DWORD own_system_token(void) {
|
||||||
|
HANDLE token = NULL;
|
||||||
|
DWORD needed = 0, result = ERROR_SUCCESS;
|
||||||
|
_Alignas(8) BYTE storage[4096];
|
||||||
|
if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &token)) return GetLastError();
|
||||||
|
if (!GetTokenInformation(token, TokenUser, storage, sizeof(storage), &needed)) result = GetLastError();
|
||||||
|
else if (needed > sizeof(storage) || !IsWellKnownSid(((TOKEN_USER *)storage)->User.Sid, WinLocalSystemSid)) result = ERROR_ACCESS_DENIED;
|
||||||
|
CloseHandle(token);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
static DWORD write_result(uint32_t rpc, const RmmClockTrace *trace) {
|
||||||
|
WCHAR path[256];
|
||||||
|
char id[37], report[1536];
|
||||||
|
DWORD written = 0, result = ERROR_SUCCESS;
|
||||||
|
for (unsigned i = 0; i < 37; ++i) id[i] = (char)case_id[i];
|
||||||
|
int count = swprintf(path, sizeof(path) / sizeof(path[0]),
|
||||||
|
L"C:\\ProgramData\\RustDiscoveryBootstrap\\clock-system-trace-%ls\\result.json", case_id);
|
||||||
|
if (count <= 0 || count >= (int)(sizeof(path) / sizeof(path[0]))) return ERROR_INVALID_PARAMETER;
|
||||||
|
count = snprintf(report, sizeof(report),
|
||||||
|
"{\"schema_version\":1,\"profile\":\"clock-system-trace-v1\",\"case_id\":\"%s\","
|
||||||
|
"\"token_system\":true,\"read_only\":true,\"diagnostic_only\":true,\"query_invocations\":1,"
|
||||||
|
"\"clock_qualified\":false,\"adapter_qualified\":false,\"product_gate_open\":false,\"rpc_code\":%lu,"
|
||||||
|
"\"trace\":{\"stage\":%lu,\"native_rpc_return\":%lu,\"native_rpc_return_present\":%lu,"
|
||||||
|
"\"rpc_exception\":%lu,\"status_present\":%lu,\"ul_size\":%lu,\"c_entries\":%lu,\"p_entries_present\":%lu}}\n",
|
||||||
|
id, (unsigned long)rpc, (unsigned long)trace->stage,
|
||||||
|
(unsigned long)trace->native_rpc_return, (unsigned long)trace->native_rpc_return_present,
|
||||||
|
(unsigned long)trace->rpc_exception, (unsigned long)trace->status_present,
|
||||||
|
(unsigned long)trace->ul_size, (unsigned long)trace->c_entries, (unsigned long)trace->p_entries_present);
|
||||||
|
if (count <= 0 || count >= (int)sizeof(report)) return ERROR_BUFFER_OVERFLOW;
|
||||||
|
HANDLE file = CreateFileW(path, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_NEW,
|
||||||
|
FILE_ATTRIBUTE_NORMAL | FILE_FLAG_WRITE_THROUGH, NULL);
|
||||||
|
if (file == INVALID_HANDLE_VALUE) return GetLastError();
|
||||||
|
if (!WriteFile(file, report, (DWORD)count, &written, NULL) || written != (DWORD)count) result = ERROR_WRITE_FAULT;
|
||||||
|
else if (!FlushFileBuffers(file)) result = GetLastError();
|
||||||
|
CloseHandle(file);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
static void WINAPI run_service(DWORD argc, WCHAR **argv) {
|
||||||
|
(void)argc; (void)argv;
|
||||||
|
status_handle = RegisterServiceCtrlHandlerExW(service_name, control, NULL);
|
||||||
|
if (!status_handle) return;
|
||||||
|
ZeroMemory(&service_status, sizeof(service_status));
|
||||||
|
service_status.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
|
||||||
|
service_status.dwCurrentState = SERVICE_RUNNING;
|
||||||
|
service_status.dwControlsAccepted = 0;
|
||||||
|
if (!SetServiceStatus(status_handle, &service_status)) return;
|
||||||
|
DWORD result = own_system_token();
|
||||||
|
if (!result) {
|
||||||
|
RmmClockTrace trace = {0};
|
||||||
|
uint32_t rpc = rmm_clock_query_trace(&trace); /* exactly one fixed call */
|
||||||
|
result = write_result(rpc, &trace);
|
||||||
|
}
|
||||||
|
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,153 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Local-only, separate MIDL readiness crossbuild. Never accesses a VM.
|
||||||
|
|
||||||
|
Preserves all existing runners, product sources, generated outputs and evidence.
|
||||||
|
Each invocation creates a fresh source snapshot and records failed checks too.
|
||||||
|
"""
|
||||||
|
import base64
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
import re
|
||||||
|
import shutil
|
||||||
|
import subprocess
|
||||||
|
import uuid
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parents[2]
|
||||||
|
PACKAGE = Path('deploy/windows/clock-midl-diagnostic')
|
||||||
|
IMAGE = 'sha256:1b2fd985d2c1fcc3545ace602405dc68fa899201bd8a73fa319ff96377203fa9'
|
||||||
|
CODEGEN = ROOT / 'devstate/windows-clock-midl/native-cases/149bafe2-3469-4580-b133-988812bcc3db'
|
||||||
|
READBACK = 'readback-059c15ef-0f31-41aa-ad1d-ea6b774280d7.json'
|
||||||
|
READBACK_SHA = '0dc2373825f7f8f224cda04ecd5c521dd3c37a6e712bc3ed83bc4fa6d0d89c8c'
|
||||||
|
PINNED = {
|
||||||
|
'w32time.h': 'db5dbe5b335eaa58a6512d4abfda44e7273f3aa8a43077dcb0719e4b97ee2bde',
|
||||||
|
'w32time_c.c': 'd806adb431f16724c8afdea0c0751588a4bc6f82b6f0b8391d4d189d6a6f4a38',
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def sha(raw):
|
||||||
|
return hashlib.sha256(raw).hexdigest()
|
||||||
|
|
||||||
|
|
||||||
|
def require(condition, message):
|
||||||
|
if not condition:
|
||||||
|
raise RuntimeError(message)
|
||||||
|
|
||||||
|
|
||||||
|
def write_new(path, raw):
|
||||||
|
path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
with path.open('xb') as out:
|
||||||
|
out.write(raw)
|
||||||
|
out.flush()
|
||||||
|
os.fsync(out.fileno())
|
||||||
|
|
||||||
|
|
||||||
|
def save(path, value):
|
||||||
|
write_new(path, (json.dumps(value, indent=2) + '\n').encode())
|
||||||
|
|
||||||
|
|
||||||
|
def compiler_inputs():
|
||||||
|
paths = [ROOT / name for name in ('Cargo.toml', 'Cargo.lock', 'rust-toolchain.toml')]
|
||||||
|
paths += [p for p in (ROOT / 'crates').rglob('*') if p.is_file() and p.suffix in ('.rs', '.toml', '.c', '.idl')]
|
||||||
|
paths += [p for p in (ROOT / 'proto').rglob('*') if p.is_file()]
|
||||||
|
paths += [ROOT / PACKAGE / name for name in ('Cargo.toml', 'build.rs')]
|
||||||
|
paths += [Path(__file__).resolve()]
|
||||||
|
require(all(not p.is_symlink() for p in paths), 'compiler input symlink')
|
||||||
|
return {str(p.relative_to(ROOT)): sha(p.read_bytes()) for p in sorted(paths)}
|
||||||
|
|
||||||
|
|
||||||
|
def external_packages(lock):
|
||||||
|
# Only compare Cargo-generated fixed string fields; never execute TOML.
|
||||||
|
result = set()
|
||||||
|
for block in lock.split('[[package]]')[1:]:
|
||||||
|
fields = dict(re.findall(r'^(name|version|source|checksum) = "([^"\n]+)"$', block, re.M))
|
||||||
|
if 'source' in fields:
|
||||||
|
require(set(fields) == {'name', 'version', 'source', 'checksum'}, 'unrecognized external lock entry')
|
||||||
|
result.add(tuple(fields[key] for key in ('name', 'version', 'source', 'checksum')))
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
os.umask(0o077)
|
||||||
|
before = compiler_inputs()
|
||||||
|
receipt_raw = (CODEGEN / READBACK).read_bytes()
|
||||||
|
require(sha(receipt_raw) == READBACK_SHA, 'original native readback hash changed')
|
||||||
|
receipt = json.loads(receipt_raw)
|
||||||
|
result = receipt['result']
|
||||||
|
require(receipt['readback_only'] is True and result['complete'] is True and result['no_rpc'] is True
|
||||||
|
and result['run']['exit_code'] == 0 and result['run']['all_own_children_exited'] is True
|
||||||
|
and result['clock_qualified'] is False, 'native codegen readback incomplete')
|
||||||
|
ident = str(uuid.uuid4())
|
||||||
|
case = ROOT / 'devstate/windows-clock-midl/diagnostic-builds' / ident
|
||||||
|
case.mkdir(parents=True, mode=0o700)
|
||||||
|
source = case / 'source'
|
||||||
|
source.mkdir(mode=0o700)
|
||||||
|
for name, digest in before.items():
|
||||||
|
raw = (ROOT / name).read_bytes()
|
||||||
|
require(sha(raw) == digest, 'source changed during snapshot')
|
||||||
|
write_new(source / name, raw)
|
||||||
|
for name, digest in PINNED.items():
|
||||||
|
raw = (CODEGEN / ('native-' + name)).read_bytes()
|
||||||
|
original = next(item for item in receipt['files'] if item['name'] == name)
|
||||||
|
require(sha(raw) == digest == original['sha256'] and len(raw) == original['bytes']
|
||||||
|
and base64.b64decode(original['base64'], validate=True) == raw, 'actual Microsoft output differs')
|
||||||
|
write_new(source / PACKAGE / 'generated' / name, raw)
|
||||||
|
write_new(source / PACKAGE / 'Cargo.lock', (ROOT / 'Cargo.lock').read_bytes())
|
||||||
|
save(case / 'intent.json', dict(id=ident, image=IMAGE, native_case=str(CODEGEN), native_readback_sha256=READBACK_SHA,
|
||||||
|
source_files=before, microsoft_generated=PINNED, no_vm=True, no_jobs=True,
|
||||||
|
production_clock_qualified=False))
|
||||||
|
print('Retained local MIDL diagnostic build ' + ident, flush=True)
|
||||||
|
checks = {}
|
||||||
|
|
||||||
|
def run(name, args):
|
||||||
|
command = ['docker', 'run', '--rm', '--network', 'none', '--read-only', '--tmpfs', '/tmp:rw,size=512m',
|
||||||
|
'-v', str(source) + ':/src:ro', '-v', str(case / 'target') + ':/target',
|
||||||
|
'-v', str(case) + ':/evidence', '-e', 'CARGO_TARGET_DIR=/target',
|
||||||
|
'--entrypoint', args[0], IMAGE] + args[1:]
|
||||||
|
with (case / (name + '.log')).open('xb') as output:
|
||||||
|
completed = subprocess.run(command, stdout=output, stderr=subprocess.STDOUT, timeout=600)
|
||||||
|
checks[name] = dict(exit_code=completed.returncode, command=command, log_sha256=sha((case / (name + '.log')).read_bytes()))
|
||||||
|
save(case / (name + '.check.json'), checks[name])
|
||||||
|
require(completed.returncode == 0, 'local check failed: ' + name)
|
||||||
|
print(name + ' PASS', flush=True)
|
||||||
|
|
||||||
|
manifest = '/src/' + str(PACKAGE / 'Cargo.toml')
|
||||||
|
# Resolve only the new diagnostic leaf against the existing locked versions.
|
||||||
|
# Snapshot manifest directory is temporarily a private writable mount for
|
||||||
|
# this sole metadata step; the source worktree is never writable in Docker.
|
||||||
|
writable = case / 'lock-resolution'
|
||||||
|
shutil.copytree(source, writable)
|
||||||
|
metadata_command = ['docker', 'run', '--rm', '--network', 'none', '--read-only', '--tmpfs', '/tmp:rw,size=128m',
|
||||||
|
'-v', str(writable) + ':/src', '--entrypoint', 'cargo', IMAGE, 'metadata',
|
||||||
|
'--manifest-path', manifest, '--offline', '--format-version', '1']
|
||||||
|
with (case / 'lock-resolution.log').open('xb') as output:
|
||||||
|
lock_result = subprocess.run(metadata_command, stdout=output, stderr=subprocess.STDOUT, timeout=120)
|
||||||
|
require(lock_result.returncode == 0, 'diagnostic lock resolution failed')
|
||||||
|
resolved = (writable / PACKAGE / 'Cargo.lock').read_bytes()
|
||||||
|
require(external_packages(resolved.decode()).issubset(external_packages((ROOT / 'Cargo.lock').read_text())), 'new external dependency version')
|
||||||
|
# Replace only our freshly copied diagnostic lock BEFORE build admission;
|
||||||
|
# this is never an edit to generated NDR/header data or an OUT_DIR patch.
|
||||||
|
(source / PACKAGE / 'Cargo.lock').write_bytes(resolved)
|
||||||
|
save(case / 'resolved-lock.json', dict(sha256=sha(resolved), no_new_external_versions=True))
|
||||||
|
run('fmt', ['cargo', 'fmt', '--manifest-path', manifest, '--', '--check'])
|
||||||
|
run('clippy-windows', ['cargo', 'clippy', '--manifest-path', manifest, '--locked', '--offline', '--target', 'x86_64-pc-windows-gnu', '--all-targets', '--', '-D', 'warnings'])
|
||||||
|
run('linux-clock-tests', ['cargo', 'test', '--manifest-path', manifest, '--locked', '--offline', '--bin', 'clock-midl-readiness', '--', '--test-threads=1'])
|
||||||
|
require('test result: ok. 5 passed; 0 failed; 0 ignored;' in (case / 'linux-clock-tests.log').read_text(), 'actual five clock tests required')
|
||||||
|
run('windows-test-link', ['cargo', 'build', '--manifest-path', manifest, '--locked', '--offline', '--target', 'x86_64-pc-windows-gnu', '--tests'])
|
||||||
|
run('release-link', ['cargo', 'build', '--manifest-path', manifest, '--locked', '--offline', '--target', 'x86_64-pc-windows-gnu', '--release', '--bin', 'clock-midl-readiness'])
|
||||||
|
run('artifact', ['sh', '-c', 'cp /target/x86_64-pc-windows-gnu/release/clock-midl-readiness.exe /evidence/WindowsClockReadiness.linked.exe && cp /evidence/WindowsClockReadiness.linked.exe /evidence/WindowsClockReadiness.exe && x86_64-w64-mingw32-strip /evidence/WindowsClockReadiness.exe && x86_64-w64-mingw32-objdump -p /evidence/WindowsClockReadiness.exe'])
|
||||||
|
require(compiler_inputs() == before, 'source inputs changed during diagnostic build')
|
||||||
|
executable = case / 'WindowsClockReadiness.exe'
|
||||||
|
qualification = dict(id=ident, source_files=before, source_before_after_identical=True, image=IMAGE,
|
||||||
|
native_codegen_case=CODEGEN.name, native_readback_sha256=READBACK_SHA,
|
||||||
|
generated_inputs=PINNED, checks=checks, artifact=dict(path=str(executable), sha256=sha(executable.read_bytes()), bytes=executable.stat().st_size),
|
||||||
|
linked_binary_sha256=sha((case / 'WindowsClockReadiness.linked.exe').read_bytes()),
|
||||||
|
linux_clock_test_count=5, native_windows_execution=False, native_cloud_linux_execution=False,
|
||||||
|
production_clock_qualified=False, no_vm=True, no_jobs=True)
|
||||||
|
save(case / 'qualification.json', qualification)
|
||||||
|
print(json.dumps(dict(id=ident, artifact=qualification['artifact'], qualification_sha256=sha((case / 'qualification.json').read_bytes()), no_vm=True, clock_qualified=False)))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
main()
|
||||||
@@ -0,0 +1,279 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Package existing five portable clock units; only Root invokes native phases.
|
||||||
|
|
||||||
|
No build, Windows/NDR execution, RMM daemon, service, policy, DB or job action.
|
||||||
|
Lost native replies permit readback of the same case only, never another run.
|
||||||
|
"""
|
||||||
|
import argparse
|
||||||
|
import base64
|
||||||
|
import hashlib
|
||||||
|
import inspect
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
import re
|
||||||
|
import shutil
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import uuid
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parents[2]
|
||||||
|
sys.path.insert(0, str(ROOT / 'deploy'))
|
||||||
|
import remote_client_bootstrap as linux
|
||||||
|
import vm_mvp_acceptance as contract
|
||||||
|
|
||||||
|
CASE = ROOT / 'devstate/windows-clock-midl/diagnostic-builds/181c3a1c-8324-41fd-9b7c-aa8010262912'
|
||||||
|
QUALIFICATION_SHA = '2e0de3acf72ab5c3a8e0baa54e8643d086ea7c03d1b38fd89b6bfc00e45f8cbb'
|
||||||
|
STATE = ROOT / 'devstate/windows-clock-midl/linux-native-packs'
|
||||||
|
REMOTE = '/var/lib/rmm-clock-midl-portable-tests'
|
||||||
|
TESTS = (
|
||||||
|
'clock::tests::gate_requires_all_status_and_uncertainty_evidence',
|
||||||
|
'clock::tests::production_clock_stays_closed_until_native_adapter_qualification',
|
||||||
|
'clock::tests::suspend_closes_until_actual_post_resume_sync',
|
||||||
|
'clock::tests::timeout_worker_stays_closed_without_a_second_call',
|
||||||
|
'clock::tests::wall_step_and_overflow_fail_closed',
|
||||||
|
)
|
||||||
|
require = contract.require
|
||||||
|
|
||||||
|
|
||||||
|
def sha(path):
|
||||||
|
return hashlib.sha256(Path(path).read_bytes()).hexdigest()
|
||||||
|
|
||||||
|
|
||||||
|
def support_sources():
|
||||||
|
return {str(Path(module.__file__).resolve().relative_to(ROOT)): sha(module.__file__)
|
||||||
|
for module in (linux, contract, linux.access)}
|
||||||
|
|
||||||
|
|
||||||
|
def native_source_sha256():
|
||||||
|
return hashlib.sha256(inspect.getsource(native_case).encode()).hexdigest()
|
||||||
|
|
||||||
|
|
||||||
|
def save(folder, name, value):
|
||||||
|
fd = os.open(folder / name, os.O_CREAT | os.O_EXCL | os.O_WRONLY | os.O_NOFOLLOW, 0o600)
|
||||||
|
with os.fdopen(fd, 'w') as out:
|
||||||
|
json.dump(value, out, indent=2)
|
||||||
|
out.write('\n')
|
||||||
|
out.flush()
|
||||||
|
os.fsync(out.fileno())
|
||||||
|
|
||||||
|
|
||||||
|
def prepare():
|
||||||
|
require(sha(CASE / 'qualification.json') == QUALIFICATION_SHA, 'original build qualification')
|
||||||
|
qualified = contract.protected_json(CASE / 'qualification.json')
|
||||||
|
require(qualified['linux_clock_test_count'] == 5 and qualified['no_vm'] is True, 'five local portable guards only')
|
||||||
|
original = CASE / 'target/debug/deps/clock_midl_readiness-277aee462cb4f674'
|
||||||
|
raw = original.read_bytes()
|
||||||
|
require(raw[:6] == b'\x7fELF\x02\x01' and raw[18:20] == b'\x3e\x00', 'existing x64 Linux test executable')
|
||||||
|
os.umask(0o077)
|
||||||
|
STATE.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||||
|
folder = STATE / str(uuid.uuid4())
|
||||||
|
folder.mkdir(mode=0o700)
|
||||||
|
binary = folder / 'clock-portable-tests'
|
||||||
|
shutil.copyfile(original, binary)
|
||||||
|
binary.chmod(0o600)
|
||||||
|
require(sha(binary) == sha(original), 'byte-identical existing test executable')
|
||||||
|
for name, args in (
|
||||||
|
('elf', ['readelf', '--wide', '--program-headers', '--dynamic', '--version-info', str(binary)]),
|
||||||
|
('list', ['docker', 'run', '--rm', '--network', 'none', '--read-only', '-v', str(binary) + ':/tests:ro',
|
||||||
|
'--entrypoint', '/lib64/ld-linux-x86-64.so.2', qualified['image'], '/tests', '--list', '--format', 'terse']),
|
||||||
|
):
|
||||||
|
completed = subprocess.run(args, capture_output=True, timeout=15)
|
||||||
|
require(completed.returncode == 0, 'local loader/list metadata failed')
|
||||||
|
fd = os.open(folder / (name + '.log'), os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
|
||||||
|
with os.fdopen(fd, 'wb') as out:
|
||||||
|
out.write(completed.stdout)
|
||||||
|
out.flush()
|
||||||
|
os.fsync(out.fileno())
|
||||||
|
listed = (folder / 'list.log').read_bytes()
|
||||||
|
require(set(re.findall(rb'^(.+): test$', listed, re.M)) == {name.encode() for name in TESTS}, 'exact existing five-test list')
|
||||||
|
info = (folder / 'elf.log').read_text()
|
||||||
|
needed = re.findall(r'\(NEEDED\).*?\[([^\]]+)\]', info)
|
||||||
|
glibc = sorted(set(re.findall(r'GLIBC_[0-9.]+', info)), key=lambda v: tuple(map(int, v[6:].split('.'))))
|
||||||
|
require('/lib64/ld-linux-x86-64.so.2' in info and needed and glibc, 'actual ELF loader dependencies')
|
||||||
|
manifest = dict(schema_version=1, type='rmm.clock.portable-unit-native-pack', original_build=str(CASE),
|
||||||
|
qualification_sha256=QUALIFICATION_SHA, runner_sha256=sha(__file__),
|
||||||
|
support_sources=support_sources(), native_case_sha256=native_source_sha256(),
|
||||||
|
artifact=dict(path=str(binary), bytes=binary.stat().st_size, sha256=sha(binary)),
|
||||||
|
original_test_executable=str(original), selected_tests=list(TESTS),
|
||||||
|
interpreter='/lib64/ld-linux-x86-64.so.2', needed=needed, maximum_glibc=glibc[-1],
|
||||||
|
list_sha256=sha(folder / 'list.log'), elf_sha256=sha(folder / 'elf.log'),
|
||||||
|
compiled_new_code=False, stripped=False, native_vm_executed=False,
|
||||||
|
linux_ndr_tested=False, windows_rpc_tested=False, product_clock_qualified=False)
|
||||||
|
save(folder, 'manifest.json', manifest)
|
||||||
|
print(json.dumps(dict(manifest=str(folder / 'manifest.json'), manifest_sha256=sha(folder / 'manifest.json'),
|
||||||
|
artifact=manifest['artifact'], interpreter=manifest['interpreter'], needed=needed,
|
||||||
|
maximum_glibc=glibc[-1], selected_tests=5, native_vm_executed=False)))
|
||||||
|
|
||||||
|
|
||||||
|
def verified(path):
|
||||||
|
manifest = contract.protected_json(path)
|
||||||
|
require(manifest['runner_sha256'] == sha(__file__) and manifest['selected_tests'] == list(TESTS), 'frozen native pack runner and exact tests')
|
||||||
|
require(manifest['support_sources'] == support_sources() and manifest['native_case_sha256'] == native_source_sha256(), 'frozen native transport/parser sources')
|
||||||
|
require(manifest['qualification_sha256'] == QUALIFICATION_SHA == sha(CASE / 'qualification.json'), 'actual original build')
|
||||||
|
require(manifest['compiled_new_code'] is False and manifest['stripped'] is False and manifest['native_vm_executed'] is False, 'existing portable harness only')
|
||||||
|
binary = Path(manifest['artifact']['path'])
|
||||||
|
require(sha(binary) == manifest['artifact']['sha256'] and binary.stat().st_size == manifest['artifact']['bytes']
|
||||||
|
and sha(manifest['original_test_executable']) == sha(binary), 'unchanged actual original Linux harness')
|
||||||
|
return manifest
|
||||||
|
|
||||||
|
|
||||||
|
def native_case(payload):
|
||||||
|
import resource
|
||||||
|
import stat
|
||||||
|
import time
|
||||||
|
root = Path('/var/lib/rmm-clock-midl-portable-tests')
|
||||||
|
ident = str(uuid.UUID(payload['id']))
|
||||||
|
names = [
|
||||||
|
'clock::tests::gate_requires_all_status_and_uncertainty_evidence',
|
||||||
|
'clock::tests::production_clock_stays_closed_until_native_adapter_qualification',
|
||||||
|
'clock::tests::suspend_closes_until_actual_post_resume_sync',
|
||||||
|
'clock::tests::timeout_worker_stays_closed_without_a_second_call',
|
||||||
|
'clock::tests::wall_step_and_overflow_fail_closed',
|
||||||
|
]
|
||||||
|
require(payload['id'] == ident and payload['action'] in ('prepare', 'run', 'read')
|
||||||
|
and payload['tests'] == names and os.geteuid() == 0, 'fixed exact portable test case')
|
||||||
|
digest = payload['binary_sha256']
|
||||||
|
require(len(digest) == 64 and all(c in '0123456789abcdef' for c in digest), 'fixed binary hash')
|
||||||
|
def safe(path, directory):
|
||||||
|
value = path.lstat()
|
||||||
|
require(value.st_uid == 0 and not value.st_mode & 0o077 and not stat.S_ISLNK(value.st_mode)
|
||||||
|
and (stat.S_ISDIR(value.st_mode) if directory else stat.S_ISREG(value.st_mode)), 'private fixed test path')
|
||||||
|
def write(path, value):
|
||||||
|
fd = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY | os.O_NOFOLLOW, 0o600)
|
||||||
|
with os.fdopen(fd, 'w') as out:
|
||||||
|
json.dump(value, out)
|
||||||
|
out.flush()
|
||||||
|
os.fsync(out.fileno())
|
||||||
|
if payload['action'] == 'prepare' and not root.exists():
|
||||||
|
root.mkdir(mode=0o700)
|
||||||
|
safe(root, True)
|
||||||
|
case = root / ident
|
||||||
|
if payload['action'] == 'prepare':
|
||||||
|
case.mkdir(mode=0o700)
|
||||||
|
write(case / 'intent.json', payload)
|
||||||
|
return dict(prepared=True)
|
||||||
|
safe(case, True)
|
||||||
|
safe(case / 'intent.json', False)
|
||||||
|
intent = json.loads((case / 'intent.json').read_bytes())
|
||||||
|
require(all(intent[key] == payload[key] for key in ('id', 'binary_sha256', 'manifest_sha256', 'tests', 'runner_sha256', 'support_sources', 'native_case_sha256')), 'original create-once intent')
|
||||||
|
if payload['action'] == 'read':
|
||||||
|
safe(case / 'result.json', False)
|
||||||
|
return json.loads((case / 'result.json').read_bytes())
|
||||||
|
binary = case / 'clock-portable-tests'
|
||||||
|
safe(binary, False)
|
||||||
|
require(hashlib.sha256(binary.read_bytes()).hexdigest() == digest, 'actual staged original test bytes')
|
||||||
|
write(case / 'started.json', dict(binary_sha256=digest, tests=names, never_repeat_start=True))
|
||||||
|
binary.chmod(0o500)
|
||||||
|
temporary = case / 'tmp'
|
||||||
|
temporary.mkdir(mode=0o700)
|
||||||
|
env = {'PATH': '/usr/bin:/bin', 'LANG': 'C.UTF-8', 'TMPDIR': str(temporary), 'RUST_BACKTRACE': '0'}
|
||||||
|
namespace = subprocess.run(['/usr/bin/unshare', '--net', '--', '/usr/bin/true'], env=env, capture_output=True, timeout=3)
|
||||||
|
require(namespace.returncode == 0, 'network namespace required; no fallback')
|
||||||
|
loader = subprocess.run(['/lib64/ld-linux-x86-64.so.2', '--list', str(binary)], env=env, capture_output=True, timeout=3)
|
||||||
|
require(loader.returncode == 0 and len(loader.stdout) <= 16384 and len(loader.stderr) <= 16384, 'actual native loader compatibility')
|
||||||
|
def limits():
|
||||||
|
resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
|
||||||
|
resource.setrlimit(resource.RLIMIT_FSIZE, (1048576, 1048576))
|
||||||
|
resource.setrlimit(resource.RLIMIT_CPU, (10, 10))
|
||||||
|
results = []
|
||||||
|
deadline = time.monotonic() + 20
|
||||||
|
for number, name in enumerate(names):
|
||||||
|
output = case / (str(number) + '-stdout.bin')
|
||||||
|
errors = case / (str(number) + '-stderr.bin')
|
||||||
|
timed_out = False
|
||||||
|
with output.open('xb') as stdout, errors.open('xb') as stderr:
|
||||||
|
output.chmod(0o600)
|
||||||
|
errors.chmod(0o600)
|
||||||
|
try:
|
||||||
|
remaining = deadline - time.monotonic()
|
||||||
|
require(remaining > 0, 'aggregate test deadline')
|
||||||
|
child = subprocess.run(['/usr/bin/unshare', '--net', '--', str(binary), '--exact', name, '--test-threads=1'],
|
||||||
|
cwd=case, env=env, stdin=subprocess.DEVNULL, stdout=stdout, stderr=stderr,
|
||||||
|
timeout=min(5, remaining), preexec_fn=limits)
|
||||||
|
code = child.returncode
|
||||||
|
except subprocess.TimeoutExpired:
|
||||||
|
timed_out = True
|
||||||
|
code = None
|
||||||
|
stdout.flush()
|
||||||
|
stderr.flush()
|
||||||
|
os.fsync(stdout.fileno())
|
||||||
|
os.fsync(stderr.fileno())
|
||||||
|
raw, err = output.read_bytes(), errors.read_bytes()
|
||||||
|
require(len(raw) <= 1048576 and len(err) <= 1048576, 'bounded unit output')
|
||||||
|
results.append(dict(name=name, exit_code=code, timed_out=timed_out, stdout_b64=base64.b64encode(raw).decode(), stderr_b64=base64.b64encode(err).decode()))
|
||||||
|
if code != 0:
|
||||||
|
break
|
||||||
|
report = dict(id=ident, binary_sha256=digest, manifest_sha256=payload['manifest_sha256'], results=results,
|
||||||
|
native_platform='linux', network_namespace=True, environment_cleared=True,
|
||||||
|
loader_stdout_sha256=hashlib.sha256(loader.stdout).hexdigest(), linux_ndr_tested=False,
|
||||||
|
windows_rpc_tested=False, product_clock_qualified=False, rmm_jobs_created=False)
|
||||||
|
write(case / 'result.json', report)
|
||||||
|
return report
|
||||||
|
|
||||||
|
|
||||||
|
def native(path, access_root, ident=None):
|
||||||
|
manifest = verified(path)
|
||||||
|
linux.ROOT = linux.access.ROOT = access_root.resolve()
|
||||||
|
os.umask(0o077)
|
||||||
|
if ident is None:
|
||||||
|
ident = str(uuid.uuid4())
|
||||||
|
folder = STATE / ident
|
||||||
|
folder.mkdir(mode=0o700)
|
||||||
|
payload = dict(id=ident, binary_sha256=manifest['artifact']['sha256'], manifest_sha256=sha(path), tests=list(TESTS),
|
||||||
|
runner_sha256=manifest['runner_sha256'], support_sources=manifest['support_sources'], native_case_sha256=manifest['native_case_sha256'])
|
||||||
|
save(folder, 'intent.json', dict(payload=payload, manifest_path=str(path.resolve())))
|
||||||
|
linux.rpc('linux-vm.conf', native_case, dict(payload, action='prepare'))
|
||||||
|
cfg = linux.access.load_config(access_root / 'credentials/linux-vm.conf')
|
||||||
|
args = ['sftp', '-F', '/dev/null', '-P', cfg.get('port', '22'), '-o', 'StrictHostKeyChecking=yes', '-o', 'BatchMode=yes',
|
||||||
|
'-o', 'IdentitiesOnly=yes', '-o', 'ForwardAgent=no', '-o', 'ConnectTimeout=10', '-i', str(Path(cfg['ssh_key_path']).expanduser()),
|
||||||
|
'-b', '-', cfg['username'] + '@' + cfg['address']]
|
||||||
|
result = subprocess.run(args, input=('put ' + json.dumps(manifest['artifact']['path']) + ' ' + json.dumps(REMOTE + '/' + ident + '/clock-portable-tests') + '\n').encode(), capture_output=True, timeout=120)
|
||||||
|
save(folder, 'upload.json', dict(returncode=result.returncode))
|
||||||
|
require(result.returncode == 0, 'fixed portable binary upload')
|
||||||
|
save(folder, 'run-intent.json', dict(execute_only_exact_five_portable_units=True))
|
||||||
|
value = linux.rpc('linux-vm.conf', native_case, dict(payload, action='run'))
|
||||||
|
else:
|
||||||
|
ident = str(uuid.UUID(ident))
|
||||||
|
folder = STATE / ident
|
||||||
|
intent = contract.protected_json(folder / 'intent.json')
|
||||||
|
payload = intent['payload']
|
||||||
|
require(intent['manifest_path'] == str(path.resolve()) and payload['manifest_sha256'] == sha(path), 'original same native case')
|
||||||
|
require(payload['runner_sha256'] == manifest['runner_sha256'] and payload['support_sources'] == manifest['support_sources']
|
||||||
|
and payload['native_case_sha256'] == manifest['native_case_sha256'], 'original same native sources')
|
||||||
|
value = linux.rpc('linux-vm.conf', native_case, dict(payload, action='read'))
|
||||||
|
save(folder, 'readback-' + str(uuid.uuid4()) + '.json', value)
|
||||||
|
require(value['binary_sha256'] == manifest['artifact']['sha256'] and value['manifest_sha256'] == sha(path)
|
||||||
|
and len(value['results']) == 5 and value['product_clock_qualified'] is False, 'all five exact portable results')
|
||||||
|
for result, name in zip(value['results'], TESTS, strict=True):
|
||||||
|
require(result['name'] == name and result['exit_code'] == 0 and result['timed_out'] is False
|
||||||
|
and b'1 passed; 0 failed; 0 ignored;' in base64.b64decode(result['stdout_b64'], validate=True), 'one exact native portable unit passed')
|
||||||
|
proof = dict(verified=True, case_id=ident, native_platform='linux', selected_tests=5, manifest_sha256=sha(path), report=value)
|
||||||
|
if (folder / 'passed.json').exists():
|
||||||
|
require(contract.protected_json(folder / 'passed.json') == proof, 'unchanged original native proof')
|
||||||
|
else:
|
||||||
|
save(folder, 'passed.json', proof)
|
||||||
|
print(json.dumps(dict(verified=True, case_id=ident, selected_native_portable_tests=5, linux_ndr_tested=False, product_clock_qualified=False)))
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
parser = argparse.ArgumentParser(description=__doc__)
|
||||||
|
parser.add_argument('action', choices=('prepare-local', 'native', 'readback'))
|
||||||
|
parser.add_argument('--manifest', type=Path)
|
||||||
|
parser.add_argument('--access-root', type=Path)
|
||||||
|
parser.add_argument('--case')
|
||||||
|
parser.add_argument('--execute-native-tests', action='store_true')
|
||||||
|
args = parser.parse_args()
|
||||||
|
if args.action == 'prepare-local':
|
||||||
|
require(not (args.manifest or args.access_root or args.case or args.execute_native_tests), 'local packaging only')
|
||||||
|
prepare()
|
||||||
|
elif args.action == 'native':
|
||||||
|
require(args.manifest and args.access_root and args.execute_native_tests and not args.case, 'Root explicitly starts one fixed native case')
|
||||||
|
native(args.manifest, args.access_root)
|
||||||
|
else:
|
||||||
|
require(args.manifest and args.access_root and args.case and not args.execute_native_tests, 'same-case readback only')
|
||||||
|
native(args.manifest, args.access_root, args.case)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
main()
|
||||||
@@ -0,0 +1,263 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Exact Microsoft MIDL codegen only; no installer, service, RPC or RMM job.
|
||||||
|
|
||||||
|
Root owns all target calls. Lost replies use readback of the same intent only.
|
||||||
|
"""
|
||||||
|
import argparse
|
||||||
|
import hashlib
|
||||||
|
import importlib
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import uuid
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parents[2]
|
||||||
|
ACCESS = Path('/home/kevin/Schreibtisch/Coding/rust-discovery')
|
||||||
|
STATE = ROOT / 'devstate/windows-clock-midl/native-cases'
|
||||||
|
TOOLS = ROOT / 'devstate/windows-clock-midl/6b7fb9b1-0bb7-4880-850b-e6812d3df1b1/tools'
|
||||||
|
IDL = ROOT / 'crates/agent-windows/native/w32time.idl'
|
||||||
|
PINS = {'midl.exe': ('7a2a717be64f755390ad8b04cb034549b2606acec646ec7cbe44c67516ccba83', 154048),
|
||||||
|
'midlc.exe': ('34293d7bd256f2d43311d197f13bbb8a1ae26c92cc1605d9f35dd3ddfe264b65', 1366464),
|
||||||
|
'w32time.idl': ('37da4acb622daf9acf1aa6f1218ff9f52e5a2def14e58d8d9dd8da65078b3c6c', 2004)}
|
||||||
|
|
||||||
|
# A fixed Codegen job. JOB_LIST is installed before CreateProcessW; no
|
||||||
|
# suspended-process/late-Assign fallback. Child descendants join this same job.
|
||||||
|
CS = r'''
|
||||||
|
using System;using System.IO;using System.Text;using System.Runtime.InteropServices;
|
||||||
|
public static class RmmMidlJob {
|
||||||
|
[StructLayout(LayoutKind.Sequential)]struct SA{public uint cb;public IntPtr sd;[MarshalAs(UnmanagedType.Bool)]public bool inherit;}
|
||||||
|
[StructLayout(LayoutKind.Sequential,CharSet=CharSet.Unicode)]struct SI{public uint cb;public string reserved,desktop,title;public uint x,y,xs,ys,xc,yc,fill,flags;public ushort show,reserved2;public IntPtr reservedp,input,output,error;}
|
||||||
|
[StructLayout(LayoutKind.Sequential)]struct SIX{public SI si;public IntPtr attrs;}
|
||||||
|
[StructLayout(LayoutKind.Sequential)]struct PI{public IntPtr process,thread;public uint pid,tid;}
|
||||||
|
[StructLayout(LayoutKind.Sequential)]struct BASIC{public long processTime,jobTime;public uint flags;public UIntPtr minimum,maximum;public uint active;public UIntPtr affinity;public uint priority,scheduling;}
|
||||||
|
[StructLayout(LayoutKind.Sequential)]struct IO{public ulong a,b,c,d,e,f;}
|
||||||
|
[StructLayout(LayoutKind.Sequential)]struct LIMIT{public BASIC basic;public IO io;public UIntPtr processMemory,jobMemory,peakProcess,peakJob;}
|
||||||
|
[StructLayout(LayoutKind.Sequential)]struct ACCOUNT{public long a,b,c,d;public uint faults,total,active,terminated;}
|
||||||
|
[DllImport("kernel32.dll",SetLastError=true)]static extern IntPtr CreateJobObjectW(IntPtr sa,string name);
|
||||||
|
[DllImport("kernel32.dll",SetLastError=true)]static extern bool SetInformationJobObject(IntPtr job,int kind,ref LIMIT value,uint len);
|
||||||
|
[DllImport("kernel32.dll",SetLastError=true)]static extern bool QueryInformationJobObject(IntPtr job,int kind,out ACCOUNT value,uint len,IntPtr needed);
|
||||||
|
[DllImport("kernel32.dll",SetLastError=true)]static extern bool TerminateJobObject(IntPtr job,uint code);
|
||||||
|
[DllImport("kernel32.dll",SetLastError=true)]static extern bool InitializeProcThreadAttributeList(IntPtr list,int count,uint flags,ref UIntPtr size);
|
||||||
|
[DllImport("kernel32.dll",SetLastError=true)]static extern bool UpdateProcThreadAttribute(IntPtr list,uint flags,UIntPtr attribute,IntPtr value,UIntPtr len,IntPtr old,IntPtr needed);
|
||||||
|
[DllImport("kernel32.dll")]static extern void DeleteProcThreadAttributeList(IntPtr list);
|
||||||
|
[DllImport("kernel32.dll",CharSet=CharSet.Unicode,SetLastError=true)]static extern IntPtr CreateFileW(string path,uint access,uint share,ref SA sa,uint disposition,uint flags,IntPtr template);
|
||||||
|
[DllImport("kernel32.dll",CharSet=CharSet.Unicode,SetLastError=true)]static extern bool CreateProcessW(string app,StringBuilder command,IntPtr pa,IntPtr ta,bool inherit,uint flags,IntPtr environment,string cwd,ref SIX start,out PI pi);
|
||||||
|
[DllImport("kernel32.dll",SetLastError=true)]static extern bool IsProcessInJob(IntPtr process,IntPtr job,out bool member);
|
||||||
|
[DllImport("kernel32.dll",SetLastError=true)]static extern uint ResumeThread(IntPtr thread);
|
||||||
|
[DllImport("kernel32.dll",SetLastError=true)]static extern uint WaitForSingleObject(IntPtr handle,uint ms);
|
||||||
|
[DllImport("kernel32.dll",SetLastError=true)]static extern bool GetExitCodeProcess(IntPtr handle,out uint code);
|
||||||
|
[DllImport("kernel32.dll")]static extern bool CloseHandle(IntPtr handle);
|
||||||
|
static void Need(bool ok,string stage){if(!ok)throw new InvalidOperationException(stage+"_"+Marshal.GetLastWin32Error());}
|
||||||
|
static IntPtr Output(string path,ref SA sa){var h=CreateFileW(path,0x40000000,1,ref sa,1,0,IntPtr.Zero);Need(h!=new IntPtr(-1),"OUTPUT_CREATE");return h;}
|
||||||
|
public sealed class Result {public uint pid,exit_code,active_processes;public bool timed_out,output_exceeded,atomic_job_assignment,all_own_children_exited;}
|
||||||
|
public static Result Run(string folder){
|
||||||
|
Need(IntPtr.Size==8&&Marshal.SizeOf(typeof(SI))==104&&Marshal.SizeOf(typeof(SIX))==112&&Marshal.SizeOf(typeof(LIMIT))==144,"X64_ABI");
|
||||||
|
IntPtr job=IntPtr.Zero,attrs=IntPtr.Zero,jobValue=IntPtr.Zero,handleValue=IntPtr.Zero,input=IntPtr.Zero,output=IntPtr.Zero,error=IntPtr.Zero;bool initialized=false;PI pi=new PI();
|
||||||
|
try{
|
||||||
|
job=CreateJobObjectW(IntPtr.Zero,null);Need(job!=IntPtr.Zero,"JOB_CREATE");
|
||||||
|
LIMIT limit=new LIMIT();limit.basic.flags=0x2000|8;limit.basic.active=2;Need(SetInformationJobObject(job,9,ref limit,(uint)Marshal.SizeOf(typeof(LIMIT))),"JOB_LIMITS");
|
||||||
|
SA sa=new SA();sa.cb=(uint)Marshal.SizeOf(typeof(SA));sa.inherit=true;
|
||||||
|
input=CreateFileW("NUL",0x80000000,3,ref sa,3,0,IntPtr.Zero);Need(input!=new IntPtr(-1),"INPUT_CREATE");
|
||||||
|
output=Output(Path.Combine(folder,"stdout.txt"),ref sa);error=Output(Path.Combine(folder,"stderr.txt"),ref sa);
|
||||||
|
UIntPtr bytes=UIntPtr.Zero;InitializeProcThreadAttributeList(IntPtr.Zero,2,0,ref bytes);Need(bytes.ToUInt64()>0&&bytes.ToUInt64()<65536,"ATTRIBUTE_SIZE");
|
||||||
|
attrs=Marshal.AllocHGlobal((int)bytes.ToUInt64());Need(InitializeProcThreadAttributeList(attrs,2,0,ref bytes),"ATTRIBUTE_INIT");initialized=true;
|
||||||
|
jobValue=Marshal.AllocHGlobal(IntPtr.Size);Marshal.WriteIntPtr(jobValue,job);Need(UpdateProcThreadAttribute(attrs,0,new UIntPtr(0x2000d),jobValue,new UIntPtr((uint)IntPtr.Size),IntPtr.Zero,IntPtr.Zero),"ATOMIC_JOB_LIST");
|
||||||
|
handleValue=Marshal.AllocHGlobal(3*IntPtr.Size);Marshal.WriteIntPtr(handleValue,0,input);Marshal.WriteIntPtr(handleValue,IntPtr.Size,output);Marshal.WriteIntPtr(handleValue,2*IntPtr.Size,error);
|
||||||
|
Need(UpdateProcThreadAttribute(attrs,0,new UIntPtr(0x20002),handleValue,new UIntPtr((uint)(3*IntPtr.Size)),IntPtr.Zero,IntPtr.Zero),"HANDLE_LIST");
|
||||||
|
SIX si=new SIX();si.si.cb=(uint)Marshal.SizeOf(typeof(SIX));si.attrs=attrs;si.si.flags=0x100;si.si.input=input;si.si.output=output;si.si.error=error;
|
||||||
|
string exe=Path.Combine(folder,"input","midl.exe");
|
||||||
|
var cmd=new StringBuilder("\""+exe+"\" /nologo /no_cpp /env amd64 /Oicf /robust /Zp8 /protocol dce /client stub /server none /h w32time.h /cstub w32time_c.c \""+Path.Combine(folder,"input","w32time.idl")+"\"");
|
||||||
|
Need(CreateProcessW(exe,cmd,IntPtr.Zero,IntPtr.Zero,true,0x80000|0x8000000|4,IntPtr.Zero,Path.Combine(folder,"output"),ref si,out pi),"CODEGEN_CREATE");
|
||||||
|
bool member;Need(IsProcessInJob(pi.process,job,out member)&&member,"ATOMIC_JOB_MEMBERSHIP");Need(ResumeThread(pi.thread)!=0xffffffff,"CODEGEN_RESUME");
|
||||||
|
Result result=new Result();result.pid=pi.pid;result.atomic_job_assignment=true;
|
||||||
|
var began=System.Diagnostics.Stopwatch.StartNew();
|
||||||
|
while(true){
|
||||||
|
uint waited=WaitForSingleObject(pi.process,25);Need(waited==0||waited==258,"CODEGEN_WAIT");
|
||||||
|
foreach(string path in new[]{Path.Combine(folder,"stdout.txt"),Path.Combine(folder,"stderr.txt"),Path.Combine(folder,"output","w32time.h"),Path.Combine(folder,"output","w32time_c.c")})if(File.Exists(path)&&new FileInfo(path).Length>262144)result.output_exceeded=true;
|
||||||
|
if(waited==0)break;
|
||||||
|
if(began.ElapsedMilliseconds>=10000||result.output_exceeded){result.timed_out=began.ElapsedMilliseconds>=10000;Need(TerminateJobObject(job,0xdead),"OWN_JOB_TERMINATE");break;}
|
||||||
|
}
|
||||||
|
// One total two-second observation budget, not one timeout per child.
|
||||||
|
var closing=System.Diagnostics.Stopwatch.StartNew();ACCOUNT account;
|
||||||
|
do{Need(QueryInformationJobObject(job,1,out account,(uint)Marshal.SizeOf(typeof(ACCOUNT)),IntPtr.Zero),"JOB_ACCOUNTING");if(account.active==0)break;System.Threading.Thread.Sleep(25);}while(closing.ElapsedMilliseconds<2000);
|
||||||
|
result.active_processes=account.active;result.all_own_children_exited=account.active==0;
|
||||||
|
Need(GetExitCodeProcess(pi.process,out result.exit_code),"CODEGEN_EXIT_CODE");return result;
|
||||||
|
}finally{
|
||||||
|
// Closing only this unnamed job kills any remaining own compiler child.
|
||||||
|
if(job!=IntPtr.Zero)CloseHandle(job);
|
||||||
|
if(pi.thread!=IntPtr.Zero)CloseHandle(pi.thread);if(pi.process!=IntPtr.Zero)CloseHandle(pi.process);
|
||||||
|
if(initialized)DeleteProcThreadAttributeList(attrs);if(attrs!=IntPtr.Zero)Marshal.FreeHGlobal(attrs);if(jobValue!=IntPtr.Zero)Marshal.FreeHGlobal(jobValue);if(handleValue!=IntPtr.Zero)Marshal.FreeHGlobal(handleValue);
|
||||||
|
foreach(var h in new[]{input,output,error})if(h!=IntPtr.Zero&&h!=new IntPtr(-1))CloseHandle(h);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
'''
|
||||||
|
|
||||||
|
SCRIPT = r'''$ErrorActionPreference='Stop'
|
||||||
|
$p=([Console]::In.ReadLine()|ConvertFrom-Json)
|
||||||
|
if([guid]::ParseExact($p.id,'D').ToString()-cne$p.id-or$p.action-notin@('prepare','admit','start','readback')){throw 'Fixed codegen case'}
|
||||||
|
foreach($n in @('runner_sha256','script_sha256')){if($p.$n-notmatch'^[a-f0-9]{64}$'){throw 'Source binding'}}
|
||||||
|
$root='C:\ProgramData\RustDiscoveryBootstrap';$folder=Join-Path $root ('midl-codegen-'+$p.id)
|
||||||
|
$inputsDir=Join-Path $folder 'input';$output=Join-Path $folder 'output'
|
||||||
|
$pins=@(@('midl.exe','7a2a717be64f755390ad8b04cb034549b2606acec646ec7cbe44c67516ccba83',154048),@('midlc.exe','34293d7bd256f2d43311d197f13bbb8a1ae26c92cc1605d9f35dd3ddfe264b65',1366464),@('w32time.idl','37da4acb622daf9acf1aa6f1218ff9f52e5a2def14e58d8d9dd8da65078b3c6c',2004))
|
||||||
|
function Check($path,[bool]$directory){
|
||||||
|
$item=Get-Item -LiteralPath $path -Force;if($item.PSIsContainer-ne$directory-or($item.Attributes-band[IO.FileAttributes]::ReparsePoint)){throw 'Codegen regular private path'}
|
||||||
|
$parent=$item.Parent;if(!$directory){$parent=$item.Directory};while($null-ne$parent){if($parent.Attributes-band[IO.FileAttributes]::ReparsePoint){throw 'Codegen ancestor reparse'};$parent=$parent.Parent}
|
||||||
|
$a=Get-Acl -LiteralPath $path;if($a.GetOwner([Security.Principal.SecurityIdentifier]).Value-notin@('S-1-5-18','S-1-5-32-544')-or!$a.Access.Count){throw 'Codegen private owner'}
|
||||||
|
foreach($r in $a.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier])){if($r.AccessControlType-ne'Allow'-or$r.IdentityReference.Value-notin@('S-1-5-18','S-1-5-32-544')-or[int64]$r.FileSystemRights-ne2032127){throw 'Codegen exact controller ACL'}}
|
||||||
|
}
|
||||||
|
function Protect($path){$a=New-Object Security.AccessControl.DirectorySecurity;$a.SetAccessRuleProtection($true,$false);$a.SetOwner((New-Object Security.Principal.SecurityIdentifier('S-1-5-32-544')));foreach($sid in @('S-1-5-18','S-1-5-32-544')){$a.AddAccessRule((New-Object Security.AccessControl.FileSystemAccessRule((New-Object Security.Principal.SecurityIdentifier($sid)),'FullControl','ContainerInherit,ObjectInherit','None','Allow')))};Set-Acl -LiteralPath $path -AclObject $a;Check $path $true}
|
||||||
|
function NewRecord($name,$value){$path=Join-Path $folder $name;$bytes=[Text.Encoding]::UTF8.GetBytes(($value|ConvertTo-Json -Depth 16 -Compress));$f=[IO.File]::Open($path,'CreateNew','Write','Read');try{$f.Write($bytes,0,$bytes.Length);$f.Flush($true)}finally{$f.Dispose()};Check $path $false}
|
||||||
|
function Hash($path){return(Get-FileHash -LiteralPath $path -Algorithm SHA256).Hash.ToLowerInvariant()}
|
||||||
|
function Intent{
|
||||||
|
Check $folder $true;Check $inputsDir $true;Check $output $true;Check (Join-Path $folder 'intent.json') $false
|
||||||
|
$i=Get-Content -LiteralPath (Join-Path $folder 'intent.json') -Raw|ConvertFrom-Json
|
||||||
|
if($i.id-cne$p.id-or$i.runner_sha256-cne$p.runner_sha256-or$i.script_sha256-cne$p.script_sha256){throw 'Immutable codegen intent'}
|
||||||
|
}
|
||||||
|
function VerifyInputs{
|
||||||
|
$info=@();foreach($pin in $pins){$path=Join-Path $inputsDir $pin[0];Check $path $false;if((Get-Item -LiteralPath $path).Length-ne$pin[2]-or(Hash $path)-cne$pin[1]){throw 'Fixed codegen input bytes'}
|
||||||
|
if($pin[0]-like'*.exe'){
|
||||||
|
$sig=Get-AuthenticodeSignature -LiteralPath $path;if($sig.Status-ne'Valid'-or!$sig.SignerCertificate-or$sig.SignerCertificate.Subject-notmatch'(^|,\s*)O=Microsoft Corporation(,|$)'){throw 'Valid Microsoft Authenticode required'}
|
||||||
|
$chain=New-Object Security.Cryptography.X509Certificates.X509Chain;try{$chain.ChainPolicy.RevocationMode='Online';$chain.ChainPolicy.RevocationFlag='ExcludeRoot';$chain.ChainPolicy.VerificationFlags='NoFlag';$chain.ChainPolicy.UrlRetrievalTimeout=[TimeSpan]::FromSeconds(2);if(!$chain.Build($sig.SignerCertificate)){throw 'Microsoft chain validation required'}}finally{$chain.Dispose()}
|
||||||
|
$v=(Get-Item -LiteralPath $path).VersionInfo;if($v.FileMajorPart-ne8-or$v.FileMinorPart-ne1-or$v.FileBuildPart-ne628-or$v.FilePrivatePart-ne1){throw 'Exact pinned compiler version'}
|
||||||
|
$info+=,[ordered]@{name=$pin[0];sha256=$pin[1];authenticode_status='Valid';signer_thumbprint=$sig.SignerCertificate.Thumbprint;chain_valid=$true;file_version='8.1.628.1'}
|
||||||
|
}
|
||||||
|
};return ,$info
|
||||||
|
}
|
||||||
|
Check $root $true
|
||||||
|
if($p.action-ceq'prepare'){
|
||||||
|
if(Test-Path -LiteralPath $folder){throw 'Existing case: readback only'}
|
||||||
|
New-Item -ItemType Directory -Path $folder|Out-Null;Protect $folder
|
||||||
|
foreach($path in @($inputsDir,$output)){New-Item -ItemType Directory -Path $path|Out-Null;Protect $path}
|
||||||
|
NewRecord 'intent.json' @{id=$p.id;runner_sha256=$p.runner_sha256;script_sha256=$p.script_sha256;inputs=$pins;no_jobs=$true;no_rpc=$true;no_installation=$true}
|
||||||
|
@{prepared=$true;id=$p.id;tool_executed=$false}|ConvertTo-Json -Compress;return
|
||||||
|
}
|
||||||
|
Intent
|
||||||
|
if($p.action-ceq'admit'){$tools=VerifyInputs;NewRecord 'admitted.json' @{id=$p.id;tools=$tools;source_sha256=$pins[2][1];tool_executed=$false};@{admitted=$true;id=$p.id;tools=$tools;tool_executed=$false}|ConvertTo-Json -Depth 8 -Compress;return}
|
||||||
|
if($p.action-ceq'readback'){
|
||||||
|
$report=$null;$reportPath=Join-Path $folder 'result.json';if(Test-Path -LiteralPath $reportPath){Check $reportPath $false;$report=Get-Content -LiteralPath $reportPath -Raw|ConvertFrom-Json}
|
||||||
|
$files=@();foreach($pair in @(@('stdout.txt',$folder),@('stderr.txt',$folder),@('w32time.h',$output),@('w32time_c.c',$output))){$path=Join-Path $pair[1] $pair[0];if(Test-Path -LiteralPath $path){Check $path $false;$size=(Get-Item -LiteralPath $path).Length;if($size-gt262144){throw 'Codegen output bound'};$files+=,@{name=$pair[0];bytes=$size;sha256=(Hash $path);base64=[Convert]::ToBase64String([IO.File]::ReadAllBytes($path))}}}
|
||||||
|
@{id=$p.id;readback_only=$true;started=(Test-Path -LiteralPath (Join-Path $folder 'started.json'));result=$report;files=$files}|ConvertTo-Json -Depth 16 -Compress;return
|
||||||
|
}
|
||||||
|
if(Test-Path -LiteralPath (Join-Path $folder 'started.json')){throw 'No compiler restart: readback only'}
|
||||||
|
Check (Join-Path $folder 'admitted.json') $false
|
||||||
|
$tools=VerifyInputs
|
||||||
|
$held=@();try{
|
||||||
|
foreach($pin in $pins){$held+=,[IO.File]::Open((Join-Path $inputsDir $pin[0]),'Open','Read','Read')}
|
||||||
|
$null=VerifyInputs
|
||||||
|
Add-Type -TypeDefinition @'
|
||||||
|
__CS__
|
||||||
|
'@
|
||||||
|
NewRecord 'started.json' @{id=$p.id;single_start_reserved=$true;atomic_job_list_required=$true;no_rpc=$true;no_jobs=$true}
|
||||||
|
$run=$null
|
||||||
|
try{$run=[RmmMidlJob]::Run($folder);$ok=($run.exit_code-eq0-and!$run.timed_out-and!$run.output_exceeded-and$run.all_own_children_exited)
|
||||||
|
foreach($name in @('w32time.h','w32time_c.c')){$path=Join-Path $output $name;Check $path $false;if((Get-Item -LiteralPath $path).Length-gt262144){$ok=$false}}
|
||||||
|
$other=@(Get-ChildItem -LiteralPath $output -Force|Where-Object{$_.Name-notin@('w32time.h','w32time_c.c')});if($other.Count){$ok=$false}
|
||||||
|
NewRecord 'result.json' @{id=$p.id;complete=$ok;run=$run;tools=$tools;no_jobs=$true;no_rpc=$true;no_installation=$true;clock_qualified=$false}
|
||||||
|
}catch{NewRecord 'result.json' @{id=$p.id;complete=$false;run=$run;error_class=$_.Exception.GetType().Name;error_line=$_.InvocationInfo.ScriptLineNumber;no_retry=$true;clock_qualified=$false};throw}
|
||||||
|
@{id=$p.id;complete=$ok;tool_executed=$true;clock_qualified=$false}|ConvertTo-Json -Compress
|
||||||
|
}finally{foreach($f in $held){$f.Dispose()}}
|
||||||
|
'''.replace('__CS__', CS)
|
||||||
|
|
||||||
|
|
||||||
|
STAGE = r'''$ErrorActionPreference='Stop'
|
||||||
|
$p=([Console]::In.ReadLine()|ConvertFrom-Json)
|
||||||
|
if($p.sha256-notmatch'^[a-f0-9]{64}$'-or$p.bytes-le0-or$p.bytes-gt32768){throw 'Fixed codegen source'}
|
||||||
|
$root='C:\ProgramData\RustDiscoveryBootstrap'
|
||||||
|
function Check($path,[bool]$directory){$i=Get-Item -LiteralPath $path -Force;if($i.PSIsContainer-ne$directory-or($i.Attributes-band[IO.FileAttributes]::ReparsePoint)){throw 'Regular controller source'};$a=Get-Acl -LiteralPath $path;if($a.GetOwner([Security.Principal.SecurityIdentifier]).Value-notin@('S-1-5-18','S-1-5-32-544')-or!$a.Access.Count){throw 'Source owner'};foreach($r in $a.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier])){if($r.AccessControlType-ne'Allow'-or$r.IdentityReference.Value-notin@('S-1-5-18','S-1-5-32-544')-or[int64]$r.FileSystemRights-ne2032127){throw 'Source controller ACL'}}}
|
||||||
|
Check $root $true
|
||||||
|
$dir=Join-Path $root $p.sha256;if(!(Test-Path -LiteralPath $dir)){New-Item -ItemType Directory -Path $dir|Out-Null};Check $dir $true
|
||||||
|
$path=Join-Path $dir 'MidlCodegen.ps1';$exists=Test-Path -LiteralPath $path
|
||||||
|
if($exists){Check $path $false;if((Get-Item -LiteralPath $path).Length-ne$p.bytes-or(Get-FileHash -LiteralPath $path -Algorithm SHA256).Hash.ToLowerInvariant()-cne$p.sha256){throw 'Immutable codegen source'}}
|
||||||
|
@{already_uploaded=$exists}|ConvertTo-Json -Compress
|
||||||
|
'''
|
||||||
|
LAUNCH = r'''$ErrorActionPreference='Stop'
|
||||||
|
$p=([Console]::In.ReadLine()|ConvertFrom-Json)
|
||||||
|
if($p.script_sha256-notmatch'^[a-f0-9]{64}$'){throw 'Fixed codegen source hash'}
|
||||||
|
$file='C:\ProgramData\RustDiscoveryBootstrap\'+$p.script_sha256+'\MidlCodegen.ps1'
|
||||||
|
$i=Get-Item -LiteralPath $file -Force;if($i.PSIsContainer-or($i.Attributes-band[IO.FileAttributes]::ReparsePoint)-or(Get-FileHash -LiteralPath $file -Algorithm SHA256).Hash.ToLowerInvariant()-cne$p.script_sha256){throw 'Immutable codegen source file'}
|
||||||
|
$json=$p|ConvertTo-Json -Depth 8 -Compress
|
||||||
|
$raw=$json|& "$env:WINDIR\System32\WindowsPowerShell\v1.0\powershell.exe" -NoLogo -NoProfile -NonInteractive -ExecutionPolicy RemoteSigned -File $file
|
||||||
|
if($LASTEXITCODE-ne0){throw 'Exact codegen phase failed; retain case and readback only'}
|
||||||
|
$raw
|
||||||
|
'''
|
||||||
|
|
||||||
|
|
||||||
|
def upload(cb, local, remote, folder, label):
|
||||||
|
prefix=cb.contract.protected_json(cb.ROOT/'credentials/windows-dev-access.json')['ssh_prefix']
|
||||||
|
batch='put '+json.dumps(str(local.resolve()))+' '+json.dumps(remote)+'\n'
|
||||||
|
result=subprocess.run(['sftp']+[v for v in prefix[1:-1] if v!='-T']+['-b','-',prefix[-1]],input=batch.encode(),capture_output=True,timeout=40)
|
||||||
|
save(folder,label+'.transfer.json',{'returncode':result.returncode,'stdout_sha256':hashlib.sha256(result.stdout).hexdigest(),'stderr_sha256':hashlib.sha256(result.stderr).hexdigest()})
|
||||||
|
if result.returncode:raise RuntimeError('EXACT_CODEGEN_UPLOAD_FAILED_READBACK_ONLY')
|
||||||
|
|
||||||
|
|
||||||
|
def stage_source(cb, folder, source, digest):
|
||||||
|
meta={'sha256':digest,'bytes':source.stat().st_size}
|
||||||
|
state=cb.powershell(STAGE,meta,timeout=40,remote_signed=True)
|
||||||
|
if not state['already_uploaded']:
|
||||||
|
upload(cb,source,'/C:/ProgramData/RustDiscoveryBootstrap/'+digest+'/MidlCodegen.ps1',folder,'source')
|
||||||
|
if not cb.powershell(STAGE,meta,timeout=40,remote_signed=True)['already_uploaded']:raise RuntimeError('EXACT_SOURCE_READBACK_FAILED')
|
||||||
|
|
||||||
|
|
||||||
|
def sha(path):
|
||||||
|
return hashlib.sha256(Path(path).read_bytes()).hexdigest()
|
||||||
|
|
||||||
|
|
||||||
|
def save(folder, name, value):
|
||||||
|
fd = os.open(folder/name, os.O_WRONLY|os.O_CREAT|os.O_EXCL|os.O_NOFOLLOW, 0o600)
|
||||||
|
with os.fdopen(fd, 'w') as out:
|
||||||
|
json.dump(value, out, indent=2);out.flush();os.fsync(out.fileno())
|
||||||
|
|
||||||
|
|
||||||
|
def transport(access_root):
|
||||||
|
if access_root.resolve() != ACCESS:
|
||||||
|
raise RuntimeError('EXACT_EXISTING_ACCESS_ROOT_REQUIRED')
|
||||||
|
sys.path.insert(0, str(ACCESS/'deploy/windows'))
|
||||||
|
return importlib.import_module('client_bootstrap')
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
p=argparse.ArgumentParser(description=__doc__);p.add_argument('action',choices=('prepare','start','readback'));p.add_argument('--id');p.add_argument('--access-root',type=Path,default=ACCESS);a=p.parse_args()
|
||||||
|
os.umask(0o077);cb=transport(a.access_root)
|
||||||
|
script_sha=hashlib.sha256(SCRIPT.encode()).hexdigest();runner_sha=sha(__file__)
|
||||||
|
if a.action=='prepare':
|
||||||
|
if a.id:raise RuntimeError('FRESH_CREATE_ONLY_CASE_REQUIRED')
|
||||||
|
local={'midl.exe':TOOLS/'midl.exe','midlc.exe':TOOLS/'midlc.exe','w32time.idl':IDL}
|
||||||
|
for name,path in local.items():
|
||||||
|
if path.is_symlink() or not path.is_file() or (sha(path),path.stat().st_size)!=PINS[name]:raise RuntimeError('EXACT_FIXED_INPUTS_REQUIRED')
|
||||||
|
STATE.mkdir(parents=True,exist_ok=True,mode=0o700);folder=STATE/str(uuid.uuid4());folder.mkdir(mode=0o700)
|
||||||
|
payload={'id':folder.name,'runner_sha256':runner_sha,'script_sha256':script_sha}
|
||||||
|
save(folder,'intent.json',{'payload':payload,'inputs':PINS,'transport_sha256':sha(cb.__file__),'no_rpc':True,'no_jobs':True})
|
||||||
|
save(folder,'prepare-attempt.json',{'once':True})
|
||||||
|
source=folder/'MidlCodegen.ps1'
|
||||||
|
with source.open('xb') as out:out.write(SCRIPT.encode());out.flush();os.fsync(out.fileno())
|
||||||
|
stage_source(cb,folder,source,script_sha)
|
||||||
|
result=cb.powershell(LAUNCH,dict(payload,action='prepare'),timeout=40,remote_signed=True);save(folder,'remote-prepared.json',result)
|
||||||
|
for name,path in local.items():
|
||||||
|
upload(cb,path,'/C:/ProgramData/RustDiscoveryBootstrap/midl-codegen-'+folder.name+'/input/'+name,folder,name)
|
||||||
|
admitted=cb.powershell(LAUNCH,dict(payload,action='admit'),timeout=60,remote_signed=True);save(folder,'admitted.json',admitted)
|
||||||
|
print(json.dumps({'case_id':folder.name,'prepared':True,'tool_executed':False}));return
|
||||||
|
if not a.id or str(uuid.UUID(a.id))!=a.id:raise RuntimeError('EXACT_EXISTING_CASE_REQUIRED')
|
||||||
|
folder=STATE/a.id;intent=cb.contract.protected_json(folder/'intent.json');payload=intent['payload']
|
||||||
|
if payload['id']!=a.id or payload['runner_sha256']!=runner_sha or payload['script_sha256']!=script_sha or intent['transport_sha256']!=sha(cb.__file__):raise RuntimeError('IMMUTABLE_RUNNER_AND_TRANSPORT_REQUIRED')
|
||||||
|
if a.action=='start':
|
||||||
|
cb.contract.protected_json(folder/'admitted.json');save(folder,'start-attempt.json',{'once':True,'lost_reply_readback_only':True})
|
||||||
|
result=cb.powershell(LAUNCH,dict(payload,action=a.action),timeout=60,remote_signed=True)
|
||||||
|
save(folder,('start-result.json' if a.action=='start' else 'readback-'+str(uuid.uuid4())+'.json'),result)
|
||||||
|
if a.action=='readback':
|
||||||
|
for item in result['files']:
|
||||||
|
import base64
|
||||||
|
if item['name'] not in ('stdout.txt','stderr.txt','w32time.h','w32time_c.c'):raise RuntimeError('FIXED_OUTPUT_NAME_REQUIRED')
|
||||||
|
raw=base64.b64decode(item['base64'],validate=True)
|
||||||
|
if len(raw)>262144 or len(raw)!=item['bytes'] or hashlib.sha256(raw).hexdigest()!=item['sha256']:raise RuntimeError('EXACT_OUTPUT_BYTES_REQUIRED')
|
||||||
|
dest=folder/('native-'+item['name'])
|
||||||
|
if dest.exists():
|
||||||
|
if sha(dest)!=item['sha256']:raise RuntimeError('RETAINED_OUTPUT_CHANGED')
|
||||||
|
else:
|
||||||
|
with dest.open('xb') as out:out.write(raw);out.flush();os.fsync(out.fileno())
|
||||||
|
report=result.get('result') or result
|
||||||
|
print(json.dumps({'case_id':a.id,'complete':report.get('complete',False),'readback_only':a.action=='readback','clock_qualified':False}))
|
||||||
|
|
||||||
|
if __name__=='__main__':main()
|
||||||
@@ -0,0 +1,219 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Start the existing W32Time once after review; lost replies use readback only.
|
||||||
|
|
||||||
|
This bootstrap never changes service configuration, NTP, policy, ACLs or RMM
|
||||||
|
components. A running W32Time is not evidence of a qualified/trusted clock.
|
||||||
|
"""
|
||||||
|
import argparse
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
import re
|
||||||
|
import stat
|
||||||
|
import uuid
|
||||||
|
|
||||||
|
import client_bootstrap as cb
|
||||||
|
import system_helper_bootstrap as helper
|
||||||
|
import transport_acceptance as source_stage
|
||||||
|
|
||||||
|
STATE = cb.EVIDENCE / 'time-service-start'
|
||||||
|
CONTEXT = cb.EVIDENCE / 'time-service-start-context/888b18b8-da7e-4b9f-9e36-32a23f2ff973/before.json'
|
||||||
|
require = cb.contract.require
|
||||||
|
|
||||||
|
SCRIPT = r'''$ErrorActionPreference='Stop'
|
||||||
|
$p=$global:RmmTimeServiceStartPayload
|
||||||
|
if(!$p-or[guid]::ParseExact($p.id,'D').ToString()-cne$p.id-or$p.action-notin@('state','start','readback')){throw 'Fixed time-service case'}
|
||||||
|
foreach($name in @('agent_sha256','helper_sha256','config_sha256','policy_sha256','pin_sha256')){if($p.$name-notmatch'^[a-f0-9]{64}$'){throw 'Exact retained component pins'}}
|
||||||
|
$boot='C:\ProgramData\RustDiscoveryBootstrap';$folder=Join-Path $boot ('time-service-'+$p.id);$active=Join-Path $boot 'w32time-start-once.json'
|
||||||
|
function HashBytes([byte[]]$bytes){$h=[Security.Cryptography.SHA256]::Create();try{return([BitConverter]::ToString($h.ComputeHash($bytes))).Replace('-','').ToLowerInvariant()}finally{$h.Dispose()}}
|
||||||
|
function JsonHash($value){return HashBytes ([Text.Encoding]::UTF8.GetBytes(($value|ConvertTo-Json -Depth 24 -Compress)))}
|
||||||
|
function CheckControl($path,[bool]$directory){
|
||||||
|
$item=Get-Item -LiteralPath $path -Force
|
||||||
|
if($item.PSIsContainer-ne$directory-or($item.Attributes-band[IO.FileAttributes]::ReparsePoint)){throw 'Fixed private bootstrap path'}
|
||||||
|
$acl=Get-Acl -LiteralPath $path
|
||||||
|
if($acl.GetOwner([Security.Principal.SecurityIdentifier]).Value-notin@('S-1-5-18','S-1-5-32-544')-or!$acl.Access.Count){throw 'Bootstrap owner/DACL'}
|
||||||
|
foreach($r in $acl.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier])){if($r.AccessControlType-ne'Allow'-or$r.IdentityReference.Value-notin@('S-1-5-18','S-1-5-32-544')){throw 'Bootstrap controller only'}}
|
||||||
|
}
|
||||||
|
function WriteNew($path,$value){$bytes=[Text.Encoding]::UTF8.GetBytes(($value|ConvertTo-Json -Depth 24 -Compress));$file=[IO.File]::Open($path,'CreateNew','Write','Read');try{$file.Write($bytes,0,$bytes.Length);$file.Flush($true)}finally{$file.Dispose()};CheckControl $path $false}
|
||||||
|
function FileMeta($path,[bool]$hash){
|
||||||
|
$item=Get-Item -LiteralPath $path -Force;if($item.PSIsContainer-or($item.Attributes-band[IO.FileAttributes]::ReparsePoint)){throw 'Regular original component'}
|
||||||
|
$parent=$item.Directory;while($null-ne$parent){if($parent.Attributes-band[IO.FileAttributes]::ReparsePoint){throw 'Original ancestor reparse'};$parent=$parent.Parent}
|
||||||
|
$acl=Get-Acl -LiteralPath $path
|
||||||
|
return [ordered]@{length=$item.Length;created_filetime=$item.CreationTimeUtc.ToFileTimeUtc().ToString();written_filetime=$item.LastWriteTimeUtc.ToFileTimeUtc().ToString();owner_sid=$acl.GetOwner([Security.Principal.SecurityIdentifier]).Value;acl_sha256=(HashBytes ([Text.Encoding]::UTF8.GetBytes($acl.Sddl)));sha256=if($hash){(Get-FileHash -LiteralPath $path -Algorithm SHA256).Hash.ToLowerInvariant()}else{$null}}
|
||||||
|
}
|
||||||
|
function ServiceState($name){
|
||||||
|
$service=Get-CimInstance Win32_Service -Filter ("Name='"+$name+"'") -OperationTimeoutSec 10
|
||||||
|
if(!$service){throw 'Existing fixed service required'}
|
||||||
|
$security=& "$env:WINDIR\System32\sc.exe" sdshow $name;if($LASTEXITCODE-ne0){throw 'Read service security'}
|
||||||
|
$sidtype=& "$env:WINDIR\System32\sc.exe" qsidtype $name;if($LASTEXITCODE-ne0){throw 'Read service SID type'}
|
||||||
|
$definition=[ordered]@{account=$service.StartName;start_mode=$service.StartMode;image_path=$service.PathName;service_type=$service.ServiceType;security_sha256=(HashBytes ([Text.Encoding]::UTF8.GetBytes(($security-join "`n").Trim())));sid_type_sha256=(HashBytes ([Text.Encoding]::UTF8.GetBytes(($sidtype-join "`n").Trim())))}
|
||||||
|
return [ordered]@{name=$name;state=$service.State;pid=$service.ProcessId;definition=$definition}
|
||||||
|
}
|
||||||
|
function TimeConfigHash{
|
||||||
|
# Selected stable configuration only. Normal synchronization may update other
|
||||||
|
# runtime registry state; neither values nor NTP hostnames leave this function.
|
||||||
|
$specs=@(
|
||||||
|
@('SYSTEM\CurrentControlSet\Services\W32Time',@('Start','DelayedAutoStart','ImagePath','ObjectName','Type')),
|
||||||
|
@('SYSTEM\CurrentControlSet\Services\W32Time\Parameters',@('Type','NtpServer','ServiceDll','ServiceMain')),
|
||||||
|
@('SYSTEM\CurrentControlSet\Services\W32Time\Config',@('AnnounceFlags','MinPollInterval','MaxPollInterval','MaxNegPhaseCorrection','MaxPosPhaseCorrection','UpdateInterval','FrequencyCorrectRate','PhaseCorrectRate','LocalClockDispersion')),
|
||||||
|
@('SYSTEM\CurrentControlSet\Services\W32Time\TimeProviders\NtpClient',@('Enabled','InputProvider','DllName','SpecialPollInterval')),
|
||||||
|
@('SYSTEM\CurrentControlSet\Services\W32Time\TimeProviders\NtpServer',@('Enabled','InputProvider','DllName')),
|
||||||
|
@('SOFTWARE\Policies\Microsoft\W32Time\Parameters',@('Type','NtpServer')),
|
||||||
|
@('SOFTWARE\Policies\Microsoft\W32Time\Config',@('AnnounceFlags','MinPollInterval','MaxPollInterval','MaxNegPhaseCorrection','MaxPosPhaseCorrection','UpdateInterval')),
|
||||||
|
@('SOFTWARE\Policies\Microsoft\W32Time\TimeProviders\NtpClient',@('Enabled','InputProvider','DllName','SpecialPollInterval')),
|
||||||
|
@('SOFTWARE\Policies\Microsoft\W32Time\TimeProviders\NtpServer',@('Enabled','InputProvider','DllName')))
|
||||||
|
$entries=@();foreach($spec in $specs){$path='Registry::HKEY_LOCAL_MACHINE\'+$spec[0];$exists=Test-Path -LiteralPath $path;$values=@()
|
||||||
|
if($exists){$key=Get-Item -LiteralPath $path;try{foreach($name in $spec[1]){if($key.GetValueNames()-ccontains$name){$values+=,[ordered]@{name=$name;kind=$key.GetValueKind($name).ToString();value=$key.GetValue($name,$null,[Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames)}}}}finally{$key.Close()}}
|
||||||
|
$entries+=,[ordered]@{path=$spec[0];exists=$exists;values=$values}
|
||||||
|
};return JsonHash $entries
|
||||||
|
}
|
||||||
|
function Snapshot{
|
||||||
|
$rmm=@();foreach($pair in @(@('RmmDiscoveryWindows','C:\Program Files\RustDiscovery\rmm-agent-windows.exe',$p.agent_sha256),@('RmmDiscoverySystemHelper','C:\Program Files\RustDiscovery\rmm-helper-windows.exe',$p.helper_sha256))){
|
||||||
|
$service=ServiceState $pair[0];if($service.state-cne'Running'-or$service.pid-le0){throw 'Retain both running RMM components'}
|
||||||
|
$proc=[Diagnostics.Process]::GetProcessById([int]$service.pid);try{$birth=$proc.StartTime.ToUniversalTime().ToFileTimeUtc().ToString();$image=$proc.MainModule.FileName}finally{$proc.Dispose()}
|
||||||
|
if(![string]::Equals($image,$pair[1],[StringComparison]::OrdinalIgnoreCase)){throw 'Actual retained RMM image'}
|
||||||
|
$binary=FileMeta $pair[1] $true;if($binary.sha256-cne$pair[2]){throw 'Independently pinned RMM binary'}
|
||||||
|
$rmm+=,[ordered]@{service=$service;process_birth_filetime=$birth;binary=$binary}
|
||||||
|
}
|
||||||
|
$files=[ordered]@{};foreach($pair in @(@('config','C:\ProgramData\RustDiscovery\config.json',$p.config_sha256),@('helper_settings','C:\ProgramData\RustDiscoverySystem\helper.json',$p.policy_sha256),@('agent_pin','C:\ProgramData\RustDiscoverySystem\agent-pin.json',$p.pin_sha256))){$value=FileMeta $pair[1] $true;if($value.sha256-cne$pair[2]){throw 'Retained original config/pins'};$files[$pair[0]]=$value}
|
||||||
|
foreach($pair in @(@('ca','C:\ProgramData\RustDiscovery\server-ca.pem'),@('identity','C:\ProgramData\RustDiscovery\state\identity.json'),@('certificate','C:\ProgramData\RustDiscovery\state\device.pem'))){$files[$pair[0]]=FileMeta $pair[1] $true}
|
||||||
|
$files['private_key_metadata_only']=FileMeta 'C:\ProgramData\RustDiscovery\state\device.key' $false
|
||||||
|
$cfg=Get-Content -LiteralPath 'C:\ProgramData\RustDiscovery\config.json' -Raw|ConvertFrom-Json
|
||||||
|
if(($cfg.PSObject.Properties.Name-ccontains'enable_jobs')-and$cfg.enable_jobs-ne$false){throw 'No RMM jobs enabled'}
|
||||||
|
if(($cfg.PSObject.Properties.Name-ccontains'job_binding_file')-and$null-ne$cfg.job_binding_file){throw 'No new job binding'}
|
||||||
|
$policy=Get-Content -LiteralPath 'C:\ProgramData\RustDiscoverySystem\helper.json' -Raw|ConvertFrom-Json
|
||||||
|
if($policy.enable_effects-ne$false-or$policy.allow_reboot-ne$false-or@($policy.allowed_services).Count-ne0){throw 'Closed original helper policy'}
|
||||||
|
return [ordered]@{rmm=$rmm;original_files=$files;time_service=(ServiceState 'W32Time');selected_time_config_sha256=(TimeConfigHash);time_config_coverage='fixed_service_NTP_and_policy_configuration_values_only'}
|
||||||
|
}
|
||||||
|
function BaselineHash($snapshot){return JsonHash ([ordered]@{rmm=$snapshot.rmm;original_files=$snapshot.original_files;time_definition=$snapshot.time_service.definition;selected_time_config_sha256=$snapshot.selected_time_config_sha256})}
|
||||||
|
function Preserved($before,$after){
|
||||||
|
if((JsonHash $before.rmm)-cne(JsonHash $after.rmm)-or(JsonHash $before.original_files)-cne(JsonHash $after.original_files)){throw 'RMM components or original config/PKI metadata changed'}
|
||||||
|
if((JsonHash $before.time_service.definition)-cne(JsonHash $after.time_service.definition)-or$before.selected_time_config_sha256-cne$after.selected_time_config_sha256){throw 'Service configuration/security or selected NTP/policy values changed'}
|
||||||
|
}
|
||||||
|
CheckControl $boot $true
|
||||||
|
if($p.action-ceq'state'){$snapshot=Snapshot;@{id=$p.id;snapshot=$snapshot;baseline_sha256=(BaselineHash $snapshot);read_only=$true;no_jobs=$true;clock_trust_assessed=$false}|ConvertTo-Json -Depth 24 -Compress;return}
|
||||||
|
if($p.expected_sha256-notmatch'^[a-f0-9]{64}$'-or$p.baseline_sha256-notmatch'^[a-f0-9]{64}$'){throw 'Retained reviewed case hashes'}
|
||||||
|
if($p.action-ceq'readback'){
|
||||||
|
if(!(Test-Path -LiteralPath $folder)){@{id=$p.id;entered=$false;readback_only=$true;start_repeated=$false;current=(Snapshot);clock_trust_assessed=$false}|ConvertTo-Json -Depth 24 -Compress;return}
|
||||||
|
CheckControl $folder $true;CheckControl (Join-Path $folder 'intent.json') $false
|
||||||
|
$intent=Get-Content -LiteralPath (Join-Path $folder 'intent.json') -Raw|ConvertFrom-Json
|
||||||
|
if($intent.id-cne$p.id-or$intent.expected_sha256-cne$p.expected_sha256){throw 'Exact retained time-service intent'}
|
||||||
|
$after=Snapshot;Preserved $intent.before $after
|
||||||
|
$receipt=Join-Path $folder 'result.json';$result=$null;if(Test-Path -LiteralPath $receipt){CheckControl $receipt $false;$result=Get-Content -LiteralPath $receipt -Raw|ConvertFrom-Json}
|
||||||
|
@{id=$p.id;entered=$true;readback_only=$true;start_repeated=$false;original_result=$result;start_intent_exists=(Test-Path -LiteralPath (Join-Path $folder 'start-intent.json'));current=$after;preserved=$true;clock_trust_assessed=$false}|ConvertTo-Json -Depth 24 -Compress;return
|
||||||
|
}
|
||||||
|
if((Test-Path -LiteralPath $folder)-or(Test-Path -LiteralPath $active)){throw 'Existing start case: readback only, never repeat start'}
|
||||||
|
$before=Snapshot
|
||||||
|
if((BaselineHash $before)-cne$p.baseline_sha256){throw 'Exact reviewed baseline changed; do not rebase'}
|
||||||
|
if($before.time_service.state-notin@('Stopped','Running')){throw 'Pending or unknown time-service state: no start'}
|
||||||
|
if($before.time_service.state-ceq'Stopped'){$controller=Get-Service -Name W32Time;try{if(@($controller.ServicesDependedOn).Count-ne0-or$controller.Status-ne[ServiceProcess.ServiceControllerStatus]::Stopped){throw 'No implicit dependency starts or changed service state'}}finally{$controller.Dispose()}}
|
||||||
|
New-Item -ItemType Directory -Path $folder|Out-Null;CheckControl $folder $true
|
||||||
|
WriteNew (Join-Path $folder 'intent.json') @{id=$p.id;expected_sha256=$p.expected_sha256;before=$before;create_only=$true;clock_trust_assessed=$false}
|
||||||
|
if($before.time_service.state-ceq'Running'){
|
||||||
|
$after=Snapshot;Preserved $before $after
|
||||||
|
$result=@{id=$p.id;status='already_running';start_called=$false;already_running_read_only=$true;preserved=$true;clock_trust_assessed=$false;no_jobs=$true}
|
||||||
|
WriteNew (Join-Path $folder 'result.json') $result;$result|ConvertTo-Json -Compress;return
|
||||||
|
}
|
||||||
|
# Durable local and global admission precede the one exact SCM start. Nothing
|
||||||
|
# catches/retries the start; an incomplete receipt can only be read back.
|
||||||
|
WriteNew $active @{id=$p.id;expected_sha256=$p.expected_sha256;service='W32Time';create_only=$true}
|
||||||
|
WriteNew (Join-Path $folder 'start-intent.json') @{id=$p.id;service='W32Time';start_reserved=$true;observed_at=[DateTime]::UtcNow.ToString('o')}
|
||||||
|
Start-Service -Name W32Time
|
||||||
|
$service=Get-Service -Name W32Time
|
||||||
|
$service.WaitForStatus([ServiceProcess.ServiceControllerStatus]::Running,[TimeSpan]::FromSeconds(20))
|
||||||
|
$after=Snapshot;Preserved $before $after
|
||||||
|
if($after.time_service.state-cne'Running'){throw 'No running-state confirmation'}
|
||||||
|
$result=@{id=$p.id;status='started';start_called=$true;preserved=$true;clock_trust_assessed=$false;no_jobs=$true;after=$after}
|
||||||
|
WriteNew (Join-Path $folder 'result.json') $result;$result|ConvertTo-Json -Depth 24 -Compress
|
||||||
|
'''
|
||||||
|
|
||||||
|
PREPARE = source_stage.PREPARE_SCRIPT.replace('TransportAcceptance.ps1', 'TimeServiceStart.ps1')
|
||||||
|
LAUNCH = source_stage.LAUNCH_SCRIPT.replace('TransportAcceptance.ps1', 'TimeServiceStart.ps1').replace('RmmTransportPayload', 'RmmTimeServiceStartPayload')
|
||||||
|
|
||||||
|
|
||||||
|
def digest(path):
|
||||||
|
return hashlib.sha256(Path(path).read_bytes()).hexdigest()
|
||||||
|
|
||||||
|
|
||||||
|
def save(folder, name, value):
|
||||||
|
return helper.store(folder, name, value)
|
||||||
|
|
||||||
|
|
||||||
|
def preserve_failure(folder):
|
||||||
|
path = cb.EVIDENCE / 'bootstrap-private-last-error.json'
|
||||||
|
if not path.exists():
|
||||||
|
return
|
||||||
|
fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW)
|
||||||
|
with os.fdopen(fd, 'rb') as source:
|
||||||
|
info = os.fstat(source.fileno())
|
||||||
|
require(stat.S_ISREG(info.st_mode) and info.st_uid == os.getuid() and info.st_mode & 0o077 == 0 and info.st_size <= 4 * 1024 * 1024, 'private original bootstrap failure')
|
||||||
|
raw = source.read()
|
||||||
|
target = folder / ('retained-bootstrap-error-' + hashlib.sha256(raw).hexdigest() + '.json')
|
||||||
|
if not target.exists():
|
||||||
|
fd = os.open(target, 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 remote(folder, payload):
|
||||||
|
preserve_failure(folder)
|
||||||
|
try:
|
||||||
|
return cb.powershell(LAUNCH, {'sha256': hashlib.sha256(SCRIPT.encode()).hexdigest(), 'payload': payload}, timeout=100, remote_signed=True)
|
||||||
|
finally:
|
||||||
|
preserve_failure(folder)
|
||||||
|
|
||||||
|
|
||||||
|
def prepare(pins):
|
||||||
|
require(all(re.fullmatch('[0-9a-f]{64}', value) for value in pins.values()), 'independently known retained hashes')
|
||||||
|
helper.private_dir(STATE); ident = str(uuid.uuid4()); folder = STATE / ident; folder.mkdir(mode=0o700)
|
||||||
|
source_sha = hashlib.sha256(SCRIPT.encode()).hexdigest()
|
||||||
|
payload = dict(id=ident, **pins)
|
||||||
|
save(folder, 'intent.json', {'schema_version': 1, 'type': 'rmm.windows.time-service-start', 'payload': payload, 'source_file_sha256': digest(__file__), 'script_sha256': source_sha, 'closed_central_before': {'path': str(CONTEXT), 'sha256': digest(CONTEXT)}})
|
||||||
|
source = folder / 'TimeServiceStart.ps1'
|
||||||
|
fd = os.open(source, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600)
|
||||||
|
with os.fdopen(fd, 'wb') as output:
|
||||||
|
output.write(SCRIPT.encode()); output.flush(); os.fsync(output.fileno())
|
||||||
|
preserve_failure(folder)
|
||||||
|
try:
|
||||||
|
helper.transfer(source, 'TimeServiceStart.ps1', source_sha, PREPARE)
|
||||||
|
before = remote(folder, dict(payload, action='state'))
|
||||||
|
finally:
|
||||||
|
preserve_failure(folder)
|
||||||
|
require(before.get('read_only') is True and before.get('clock_trust_assessed') is False, 'actual readonly baseline')
|
||||||
|
save(folder, 'before.json', before)
|
||||||
|
print(json.dumps({'case_id': ident, 'prepared': True, 'time_state': before['snapshot']['time_service']['state'], 'clock_trust_assessed': False, 'start_executed': False}))
|
||||||
|
|
||||||
|
|
||||||
|
def run(ident, action):
|
||||||
|
require(str(uuid.UUID(ident)) == ident, 'exact existing case UUID')
|
||||||
|
folder = STATE / ident; intent = cb.contract.protected_json(folder / 'intent.json')
|
||||||
|
require(intent['source_file_sha256'] == digest(__file__) and intent['script_sha256'] == hashlib.sha256(SCRIPT.encode()).hexdigest(), 'same reviewed source; no case rebase')
|
||||||
|
baseline = cb.contract.protected_json(folder / 'before.json')['snapshot']
|
||||||
|
# Powershell creates its canonical baseline hash during state. It is sent
|
||||||
|
# back verbatim rather than approximating ConvertTo-Json in Python.
|
||||||
|
payload = dict(intent['payload'], action=action, baseline_sha256=cb.contract.protected_json(folder / 'before.json')['baseline_sha256'], expected_sha256=hashlib.sha256(json.dumps(intent['payload'], sort_keys=True, separators=(',', ':')).encode()).hexdigest())
|
||||||
|
require(baseline is not None and digest(CONTEXT) == intent['closed_central_before']['sha256'], 'retained actual baseline and closed central context')
|
||||||
|
if action == 'start':
|
||||||
|
save(folder, 'start-attempt.json', {'case_id': ident, 'once': True, 'lost_reply_readback_only': True})
|
||||||
|
result = remote(folder, payload)
|
||||||
|
save(folder, ('result.json' if action == 'start' else 'readback-' + str(uuid.uuid4()) + '.json'), result)
|
||||||
|
original = result.get('original_result') or result
|
||||||
|
current = result.get('current') or result.get('after')
|
||||||
|
print(json.dumps({'case_id': ident, 'status': original.get('status', 'unconfirmed'), 'running': current['time_service']['state'] == 'Running' if current else original.get('status') == 'already_running', 'preserved': result.get('preserved', False), 'readback_only': result.get('readback_only', False), 'clock_trust_assessed': False}))
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
parser = argparse.ArgumentParser(description=__doc__); parser.add_argument('action', choices=['prepare', 'start', 'readback']); parser.add_argument('--id')
|
||||||
|
for name in ['agent', 'helper', 'config', 'policy', 'pin']:
|
||||||
|
parser.add_argument('--' + name + '-sha256')
|
||||||
|
args = parser.parse_args()
|
||||||
|
if args.action == 'prepare':
|
||||||
|
pins = {name + '_sha256': getattr(args, name + '_sha256') for name in ['agent', 'helper', 'config', 'policy', 'pin']}
|
||||||
|
require(all(isinstance(value, str) for value in pins.values()), 'all five independent hashes required'); prepare(pins)
|
||||||
|
else:
|
||||||
|
require(args.id is not None, 'explicit retained case required'); run(args.id, args.action)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
main()
|
||||||
+46
-2
@@ -53,17 +53,61 @@ Zugänge und private Rohbelege bleiben gitignoriert.
|
|||||||
|
|
||||||
## Aktuelle Windowsfortsetzung
|
## Aktuelle Windowsfortsetzung
|
||||||
|
|
||||||
|
Clockkandidat nach W32Time-Start tatsächlich nativ ausgeführt, Fall `e1f3edbb…`:
|
||||||
|
LocalService bestätigt, beide ALPC-Proben1753, kein Endpunkteintrag; beide
|
||||||
|
Negativkontrollen ebenfalls1753, kein Identitätsnachweis. Named-Pipe-Diagnose1783
|
||||||
|
ohne Status, Ursache noch unbewiesen. Originalbericht separat identisch gelesen,
|
||||||
|
eigener temporärer Dienst entfernt, Zentralstände/Flags erhalten. Clockabnahme
|
||||||
|
**nicht bestanden**, Gatefalse und keine Jobs. Microsoft spezifiziert für
|
||||||
|
MS-W32T Named Pipes, keinen zugesicherten ALPC-Endpunkt. [Native Details](windows-clock-readiness.md).
|
||||||
|
|
||||||
|
Vorhandenes W32Time ausdrücklich autorisiert einmal gestartet, nativer Fall
|
||||||
|
`c3552c3f…`: Running und unveränderte RMM-PIDs5140/6240, Konfiguration,
|
||||||
|
PKI-Metadaten und Dienstdefinition bestätigt. Getrennter Readback identisch,
|
||||||
|
Zentralstände0/0/0/0 und30/30/26/0 sowie geschlossene Flags erhalten. Kein
|
||||||
|
Uhrqualifikations- oder Rebootbeleg; `ADAPTER_QUALIFIED=false`. [Startnachweis](windows-time-service-start.md).
|
||||||
|
|
||||||
|
Separater M3-Branch `codex/windows-eventlog`, Commit `eb38b4b`: fester
|
||||||
|
Application-/Fixtureprovider, begrenzter authentisierter Worker und sichtbarer
|
||||||
|
hashgebundener Plan implementiert und unabhängig geprüft. Lokal238Rust,
|
||||||
|
isolierterPG-Fall und38Webtests/Build/Clippy bestanden; anschließend nativ
|
||||||
|
Cloud-Linux24→Windows23 ohne Skips, Manifest `ed1371e9…`, Fälle `6f9bdfb7…`
|
||||||
|
und `ccb258a7…`. Quellen und beide Abnahmeschritte jeweils gepusht. Dies sind
|
||||||
|
Vertragsunits, keine tatsächliche LocalService-Eventlog-Abfrage oder Jobwirkung.
|
||||||
|
Keine Capability aktiviert, keine Runtime ersetzt. [Quellen und genaue Grenzen](https://gitea.incoso.eu/kevin_janssen/rust-discovery/src/branch/codex/windows-eventlog/docs/windows-eventlog-source.md).
|
||||||
|
|
||||||
|
Separater Profilbranch `codex/windows-powershell-profile`, Commit `207b91f`:
|
||||||
|
RemoteSigned als optionales festes Aktions-/Variantenfeld implementiert, alte
|
||||||
|
Bytes erhalten, UI-Planansichten streng gebunden. Lokal Rust-/Server-/35Web-
|
||||||
|
Prüfungen bestanden; danach nativ Cloud-Linux23 ohne Skips, Fall `f463acc9…`,
|
||||||
|
Manifest `26247a3a…`. Anschließend nativ Windows22 ohne Skips bestanden,
|
||||||
|
Fall `9abd3e0d…`, Proof `47cee8c9…`, an denselben Linuxbeleg gebunden. Keine
|
||||||
|
Profilcapability veröffentlicht und kein PowerShelljob gestartet. Der
|
||||||
|
Hauptcheckout bleibt für die Komponentenwartung unverändert. Quellen/Nachweise:
|
||||||
|
[Profilbranch](https://gitea.incoso.eu/kevin_janssen/rust-discovery/src/branch/codex/windows-powershell-profile).
|
||||||
|
Ein separat tatsächlich bestätigter Schemars-Nullable-Metadatenunterschied
|
||||||
|
betrifft keine Berechtigung; sein enger Attributfix wird im isolierten folgenden
|
||||||
|
M3-Schnitt mitgeführt. Der ursprüngliche Nativebeleg wird nicht umgeschrieben.
|
||||||
|
|
||||||
Neue Userentscheidungen1.18: RemoteSigned nur für den einzelnen zuvor in der
|
Neue Userentscheidungen1.18: RemoteSigned nur für den einzelnen zuvor in der
|
||||||
WebUI genehmigten PowerShell5.1-Jobprozess, vor Genehmigung sichtbar und fest
|
WebUI genehmigten PowerShell5.1-Jobprozess, vor Genehmigung sichtbar und fest
|
||||||
gebunden; bestehendes W32Time gezielt starten ohne Startart-/NTP-/ACLänderung;
|
gebunden; bestehendes W32Time gezielt starten ohne Startart-/NTP-/ACLänderung;
|
||||||
manueller VM-Konsolenneustart erst nach konkreter Zeitabstimmung. Keine Remote-
|
manueller VM-Konsolenneustart erst nach konkreter Zeitabstimmung. Keine Remote-
|
||||||
oder RMM-Rebootfreigabe. Umsetzung des optionalen Skriptprofils noch offen.
|
oder RMM-Rebootfreigabe. Profilquelle und Vertragsunits im oben genannten
|
||||||
|
isolierten Branch vorhanden; tatsächlicher genehmigter Job weiterhin offen.
|
||||||
[Begrenzter Vertrag](windows-powershell-policy.md).
|
[Begrenzter Vertrag](windows-powershell-policy.md).
|
||||||
|
|
||||||
Gemeinsamer Upgradefall `6d2df065…` bisher vor dem Server-Beforecheckpoint
|
Gemeinsamer Upgradefall `6d2df065…` bisher vor dem Server-Beforecheckpoint
|
||||||
abgebrochen, kein Enter-/Stop-/Swap-/Startintent. Bestehender RMM-Agent meldet
|
abgebrochen, kein Enter-/Stop-/Swap-/Startintent. Bestehender RMM-Agent meldet
|
||||||
weiter Heartbeats; Reverse-Tunnellistener vorhanden, aber TCP-Weiterleitung
|
weiter Heartbeats; Reverse-Tunnellistener vorhanden, aber TCP-Weiterleitung
|
||||||
liefert derzeit kein SSH-Banner. Kein Upgradefortschritt daraus ableiten.
|
lieferte zunächst kein SSH-Banner. Ein eng begrenzter Devtransport-Reset im
|
||||||
|
Fall `eed7dad0…` beendete genau den separat identifizierten Tunnel-Sessionchild
|
||||||
|
über sein gepinntes Prozesshandle; kein SSH-Master-/UID-Reset. Der bestehende
|
||||||
|
Windowsloop stellte den Listener neu her; Anmeldung mit unverändert gepinntem
|
||||||
|
Windows-Hostschlüssel und lesender Nachbeleg bestanden. Agent5140 und Helper6240
|
||||||
|
laufen unverändert, W32Time weiterhin gestoppt. Ursache der ursprünglichen
|
||||||
|
Bannerblockade unbewiesen; keine neue Schlüssel-/Port-/Expiryfreigabe und kein
|
||||||
|
VM-Neustart. Kein Upgradefortschritt daraus ableiten.
|
||||||
Konkrete Zeitabstimmung für den bereits zugesagten manuellen Konsolenneustart
|
Konkrete Zeitabstimmung für den bereits zugesagten manuellen Konsolenneustart
|
||||||
wurde angefragt; bis zur Antwort keine Ziel-Neustartaktion und keine Annahme
|
wurde angefragt; bis zur Antwort keine Ziel-Neustartaktion und keine Annahme
|
||||||
eines erfolgten Neustarts. Aktuelle Artefakte weiterhin2bee/921c.
|
eines erfolgten Neustarts. Aktuelle Artefakte weiterhin2bee/921c.
|
||||||
|
|||||||
+2
-1
@@ -1,6 +1,6 @@
|
|||||||
# Entdeckungen und Aufgaben nach dem Linux-MVP
|
# Entdeckungen und Aufgaben nach dem Linux-MVP
|
||||||
|
|
||||||
Stand 2026-11-13. Die begrenzten Linux-[M0–M5-Gates](mvp-gates.md) sind
|
Stand 2026-11-14. Die begrenzten Linux-[M0–M5-Gates](mvp-gates.md) sind
|
||||||
abgeschlossen. Windows wird auf eigenen Auftrag fortgesetzt; seine aktuellen
|
abgeschlossen. Windows wird auf eigenen Auftrag fortgesetzt; seine aktuellen
|
||||||
Voraussetzungen stehen in [Windows-Gates](windows-gates.md) und
|
Voraussetzungen stehen in [Windows-Gates](windows-gates.md) und
|
||||||
[Jobgrenze](windows-job-boundary.md). Diese Liste erweitert den Auftrag nicht.
|
[Jobgrenze](windows-job-boundary.md). Diese Liste erweitert den Auftrag nicht.
|
||||||
@@ -10,6 +10,7 @@ Pfad bleiben dort sofort relevant.
|
|||||||
|
|
||||||
| Entdeckung / späteres Thema | Tatsächlicher heutiger Stand | Spätere Aufgabe |
|
| Entdeckung / späteres Thema | Tatsächlicher heutiger Stand | Spätere Aufgabe |
|
||||||
| --- | --- | --- |
|
| --- | --- | --- |
|
||||||
|
| Dev-Reversetunnel ohne Zielbanner | Windows-RMM-Heartbeats liefen tatsächlich weiter, während Serverlistener/TCP-Verbindung auf127.0.0.1:22240 vorhanden waren, aber kein SSH-Banner durchkam. Der Bootstraploop überwacht nur das äußere ssh.exe und verbindet nach dessen Ende neu; der Task hat kein RestartOnFailure. Konkrete Ursache des blockierten SSH-Ziels unbewiesen. Keine SSH-/Hostkey-/Expirygrenze gelockert. | Nach dem MVP begrenzte Transport-/Workerdiagnose verbessern. Keine automatische Schlüsselverlängerung, öffentliche Windowsportfreigabe oder pauschalen sshd-/UID-Resets. Der aktuelle manuelle Konsolenneustart bleibt ausdrücklich zeitlich abzustimmen und ist kein RMM-Rebootnachweis. |
|
||||||
| Legacy-Syncflag ohne signierten Sync | Bei Clients ohne `rmm.sync.v1` setzt der bisherige Hello-Kompatibilitätspfad `sync_ready=true`. Auf dem passiven Windowsclient nach Serverneustart tatsächlich beobachtet; weiterhin keine Jobcapabilities und kein signierter Syncnachweis. | In Status/API `sync_required`, Unterstützung und tatsächlichen signierten Checkpoint trennen. Das Legacyflag niemals als Windows-Jobabnahme verwenden. |
|
| Legacy-Syncflag ohne signierten Sync | Bei Clients ohne `rmm.sync.v1` setzt der bisherige Hello-Kompatibilitätspfad `sync_ready=true`. Auf dem passiven Windowsclient nach Serverneustart tatsächlich beobachtet; weiterhin keine Jobcapabilities und kein signierter Syncnachweis. | In Status/API `sync_required`, Unterstützung und tatsächlichen signierten Checkpoint trennen. Das Legacyflag niemals als Windows-Jobabnahme verwenden. |
|
||||||
| Nichtstart zwischen Grant und Helperdelegation | Beim Windows-SCM-Source-Review2026-11-14 wurde eine lokale Consumption ohne Helperzeile als strenger Sync-Fault erkannt. Die Linux-Root-Quelle besitzt strukturell denselben frühen Pfad; dieser konkrete Linuxfall wurde noch nicht nativ reproduziert. Aktuelle Rootscope bleibt geschlossen. | Vor Wiederöffnung für weitere Rootjobs den engen Vor-Delegation-Cancel-/Fencefall reproduzieren und analog gebunden lösen; keine Missing-Row-Guardlockerung oder Historienänderung. Der aktuelle Windowsfixvertrag steht in Spec1.17/[Abandonvertrag](windows-system-abandon.md). Historische Linux-Abnahmen werden dadurch nicht rückwirkend als dieser Nachweis ausgegeben. |
|
| Nichtstart zwischen Grant und Helperdelegation | Beim Windows-SCM-Source-Review2026-11-14 wurde eine lokale Consumption ohne Helperzeile als strenger Sync-Fault erkannt. Die Linux-Root-Quelle besitzt strukturell denselben frühen Pfad; dieser konkrete Linuxfall wurde noch nicht nativ reproduziert. Aktuelle Rootscope bleibt geschlossen. | Vor Wiederöffnung für weitere Rootjobs den engen Vor-Delegation-Cancel-/Fencefall reproduzieren und analog gebunden lösen; keine Missing-Row-Guardlockerung oder Historienänderung. Der aktuelle Windowsfixvertrag steht in Spec1.17/[Abandonvertrag](windows-system-abandon.md). Historische Linux-Abnahmen werden dadurch nicht rückwirkend als dieser Nachweis ausgegeben. |
|
||||||
| Rohoutput und kanonischer Sync-Outcome | Das vorhandene Sync-Outcome-Limit von 512 KiB betrifft JSON; Zahlenarrays können den erlaubten Rohoutput deutlich vergrößern. Kleine bisherige MVP-Fixturen sind davon nicht betroffen. | Vor breiter Freigabe großer Ausgaben effektive Adapterlimits, Codec-/Kontrollnachrichtenbudget und gegebenenfalls Artefaktreferenzen konsistent qualifizieren. Keinen erfolglosen Sync als übernommen ausgeben. |
|
| Rohoutput und kanonischer Sync-Outcome | Das vorhandene Sync-Outcome-Limit von 512 KiB betrifft JSON; Zahlenarrays können den erlaubten Rohoutput deutlich vergrößern. Kleine bisherige MVP-Fixturen sind davon nicht betroffen. | Vor breiter Freigabe großer Ausgaben effektive Adapterlimits, Codec-/Kontrollnachrichtenbudget und gegebenenfalls Artefaktreferenzen konsistent qualifizieren. Keinen erfolglosen Sync als übernommen ausgeben. |
|
||||||
|
|||||||
@@ -0,0 +1,132 @@
|
|||||||
|
# ADR-Entwurf: unabhängiger signierter Zeitnachweis für Windows
|
||||||
|
|
||||||
|
Status2026-11-14: **Vorschlag zur Entscheidung, nicht angenommen oder
|
||||||
|
implementiert.** Kein Targetzugriff, Schlüsselsetup oder Clockgatewechsel.
|
||||||
|
Vorausgehender konkreter OSF-Befund:
|
||||||
|
[QOS5-Analyse](windows-clock-rpc-qos5-analysis.md).
|
||||||
|
|
||||||
|
## Entscheidung ist nötig
|
||||||
|
|
||||||
|
Die vollständig gelesene Spezifikation1.18 samt aktuellen Main1.20-Deltas,
|
||||||
|
Projektentscheidungen und Entwicklungsregeln verlangen weiterhin tatsächliche
|
||||||
|
lokale Status-/Boot-/Unsicherheitsnachweise. Der aktuelle Windowsvertrag
|
||||||
|
verlangt lokalen W32Time-Sync höchstens1h alt, maximal2s Unsicherheit und nach
|
||||||
|
Diskontinuität einen neuen Sync; er schließt einen Serverzeitanker ausdrücklich
|
||||||
|
aus. Die VM meldet derzeit W32Time Leap3/Stratum0. Ein signierter Beleg darf
|
||||||
|
diesen Dienstzustand nicht nachträglich als synchronisiert ausgeben.
|
||||||
|
|
||||||
|
Dieser Entwurf wäre eine **andere zulässige Vertrauensquelle**: ein signierter
|
||||||
|
Onlinevergleich qualifiziert die aktuelle lokale Windows-Wallclock; er stellt
|
||||||
|
sie nicht und ersetzt sie nicht durch einen Hello-Zeitwert. Er würde bewusst
|
||||||
|
lokalen W32Time-Sync als alleinige Voraussetzung durch streng begrenzte,
|
||||||
|
kryptografisch belegte Vergleichsqualität ersetzen. Auch „neuer Beleg nach
|
||||||
|
Diskontinuität“ wäre dann ein neuer expliziter Vertrag, kein behaupteter neuer
|
||||||
|
Windows-NTP-Sync. Dafür braucht es eine ausdrückliche normative
|
||||||
|
Produktentscheidung in Kapitel0/Projektentscheidungen, anschließend Review
|
||||||
|
und eigene Qualifikation. Bis dahin bleibt der bisherige Adapter geschlossen.
|
||||||
|
|
||||||
|
## Kleiner vorgeschlagener Vertrag
|
||||||
|
|
||||||
|
Nur der bereits festgelegte Server `discovery.ease-technologies.de` darf mit
|
||||||
|
einem eigenen provisionierten Ed25519-Zeitschlüssel signieren. Domainkennung
|
||||||
|
`RMM-TIME-ATTESTATION/v1`, feste Version und exakte Codecbytes; kein frei
|
||||||
|
wählbarer Algorithmus. Schlüssel strikt getrennt von TLS, Jobs und Updates.
|
||||||
|
Der geschützte Helperpin bindet die erlaubten Zeitpublickeys samt monotoner
|
||||||
|
Konfigurationsgeneration. Der Netzwerkagent kann keinen Publickey ergänzen;
|
||||||
|
Rotation/Entzug brauchen den gesondert geschützten Konfigurationsweg.
|
||||||
|
|
||||||
|
Agent und SYSTEM-Helper prüfen unabhängig. Jeder Verifier erzeugt selbst
|
||||||
|
256Bit CSPRNG-Nonce und eigene zufällige Prozessinkarnation, hält höchstens
|
||||||
|
eine Anfrage und beobachtet selbst Boot-ID, präzise Interrupt-/Unbiasedzeit
|
||||||
|
sowie Wallclock. Der Agent darf Helperanfrage und Antwort nur transportieren.
|
||||||
|
Seine behaupteten Zeiten oder Timer ersetzen keine Helperbeobachtung.
|
||||||
|
|
||||||
|
Der signierte Beleg bindet Nonce, Anfragetype/-hash und Verifierrolle,
|
||||||
|
Serverinstanz/-boot, erlaubten Endpunkt, Tenant/Asset/Agent,
|
||||||
|
Enrollment-/Assignmentgeneration, aktuelle Connectiongeneration,
|
||||||
|
Windows-Boot-ID, Verifierinkarnation sowie beim Helper dessen gepinnten
|
||||||
|
Imagehash und Bindingschema. Serverseitig Tenant/Agent ausschließlich aus
|
||||||
|
gültigem mTLS ableiten; aktuellen Verbindungskontext selbst nachprüfen.
|
||||||
|
Eine solche signierte Kontextbestätigung darf initiale Clockprüfung vor dem
|
||||||
|
normalen Sync ermöglichen, ersetzt aber weder diesen Sync noch ein Startgrant.
|
||||||
|
Striktes TLS/SAN/SNI bleibt Pflicht; falsche OS-Zeit rechtfertigt keinen
|
||||||
|
Zertifikatsprüfungs-Bypass zur vermeintlichen Zeitreparatur.
|
||||||
|
|
||||||
|
## Qualität und konkrete Zeitgrenzen
|
||||||
|
|
||||||
|
Vor jeder Signatur braucht der Server eine frische, nur lesende native
|
||||||
|
Kernel-/Providerprüfung: kein `TIME_ERROR`, `STA_UNSYNC` oder `STA_CLOCKERR`,
|
||||||
|
eindeutige Einheiten, gültiger UTCwert und konservativer Gesamtfehler
|
||||||
|
`epsilon_server <= 500ms`. Die bestehende Linuxfunktion erlaubt Kernel-
|
||||||
|
`maxerror <= 5s`; sie ist dafür **nicht unverändert ausreichend**. Maximal1h
|
||||||
|
seit tatsächlichem letztem guten Quellensync bleibt erforderlich. `timex`
|
||||||
|
enthält Fehler-/Statusfelder, aber keinen universellen Last-good-sync-Zeitpunkt;
|
||||||
|
der tatsächlich vorhandene Zeitprovider muss dafür eine vertrauenswürdige
|
||||||
|
native Schnittstelle liefern. Fehlend bedeutet deny, kein aus Pollzeit oder
|
||||||
|
Heartbeat erfundenes Syncalter.
|
||||||
|
[Linux-UAPI](https://raw.githubusercontent.com/torvalds/linux/master/include/uapi/linux/timex.h).
|
||||||
|
|
||||||
|
Vorläufige bewusst kurze Grenzen: vom verifiereigenen Challengebeginn bis zur
|
||||||
|
konkreten Prüfung maximal1s, davon nach Empfang höchstens100ms. Keine längere
|
||||||
|
Holdover-/Offlinephase. Capture-/Rundungs-/Timerunsicherheit wird explizit mit
|
||||||
|
`delta` berücksichtigt; dessen Höchstbudget50ms braucht einen tatsächlichen
|
||||||
|
Plattformnachweis und darf nicht aus Timerauflösung als Genauigkeit erfunden
|
||||||
|
werden. Microsoft trennt monotone Intervallmessung von UTC und setzt für VMs
|
||||||
|
einen korrekt implementierten Hypervisor voraus; diese OS-/Kernelannahme
|
||||||
|
bleibt ausdrücklich bestehen.
|
||||||
|
[Zeitstempelvertrag](https://learn.microsoft.com/en-us/windows/win32/sysinfo/acquiring-high-resolution-time-stamps).
|
||||||
|
|
||||||
|
Für signiertes Servercapture `T`, Fehler `epsilon_server` und selbst
|
||||||
|
gemessenes Gesamtintervall `R` ist die konservative UTCspanne zum Prüfzeitpunkt
|
||||||
|
`L = T - epsilon_server`, `U = T + epsilon_server + R + delta`.
|
||||||
|
Der gesamte RTT wird berücksichtigt; keine unbelegte Halbierung oder Annahme
|
||||||
|
symmetrischer Paketlaufzeiten. Die gleichzeitig selbst gelesene lokale
|
||||||
|
Wallclock `W` ist nur qualifiziert, wenn
|
||||||
|
`max(abs(W-L), abs(W-U)) <= 2s`. Spätere Vergleiche brauchen wieder einen
|
||||||
|
fristgerechten eigenen Beleg; keine freie Extrapolation einer Serverzeit.
|
||||||
|
|
||||||
|
Deadlineprüfung muss konservativ die ganze Spanne verwenden:
|
||||||
|
`L >= not_before` und `U < start_before`, zusätzlich bestehende monotone
|
||||||
|
Laufzeit-/Verbrauchsgrenzen. Ein einzelnes `SyncClock::now()`-UTCdatum reicht
|
||||||
|
diesen Intervallvertrag nicht automatisch weiter; dessen konkrete Integration
|
||||||
|
ist vor Implementierung zu prüfen. Alte Grantbytes, Fristen und60s-Startfenster
|
||||||
|
werden weder geändert noch durch Belegrefresh verlängert.
|
||||||
|
|
||||||
|
## Restart, Replay und Fehler
|
||||||
|
|
||||||
|
Jeder Boot-/Prozess-/Connectionwechsel verwirft offene Nonces und Bereitschaft.
|
||||||
|
Kein auf Platte gespeicherter Zeitbeleg eröffnet nach Restart oder Restore.
|
||||||
|
Neue zufällige Nonce/Inkarnation und normaler unabhängiger Ledger-/Syncabgleich
|
||||||
|
sind nötig; Journale, Schlüsselidentitäten und Verbrauchshistorie erhalten.
|
||||||
|
Nur Schlüssel-/Konfigurationsgeneration und gebundene Jobprüfbelege werden
|
||||||
|
im bestehenden geschützten Persistenzmodell ergänzt, keine Ledgerresets.
|
||||||
|
|
||||||
|
Rückwärtszähler, Wallstep oder Sleepdifferenz über der bisherigen1s-Grenze,
|
||||||
|
fehlerhafte Bootbeobachtung, falsche Nonce/Rolle/Bindung/Signatur, doppelte
|
||||||
|
Antwort, Überlauf oder Überschreitung einer Grenze sperren. Nach beobachteter
|
||||||
|
Diskontinuität darf nur eine danach erzeugte Challenge Bereitschaft herstellen.
|
||||||
|
Ein neuer Objektkonstruktor löscht keinen bestehenden Diskontinuitätsfence.
|
||||||
|
Ein bösartiger LocalService-Agent kann so höchstens verzögern/verhindern,
|
||||||
|
nicht Helpernonce oder Signatur fälschen. Server-/Zeitschlüsselkompromittierung
|
||||||
|
und bösartiger Hypervisor bleiben Vertrauensgrenzen; Signatur authentifiziert
|
||||||
|
den Beleg, nicht automatisch den vorgelagerten NTPserver.
|
||||||
|
|
||||||
|
Ohne frischen gültigen Beleg `CLOCK_UNTRUSTED`; Telemetrie bleibt möglich.
|
||||||
|
W32Time-Rohstatus bleibt separat sichtbar. Keine Clocksetter, Resyncs,
|
||||||
|
NTP-/ACLänderungen, neue Jobfreigaben oder Ersatz menschlicher WebUI-Genehmigung.
|
||||||
|
|
||||||
|
## Enger Review- und Nachweisplan
|
||||||
|
|
||||||
|
Zuerst ausdrückliche Entscheidung über die andere Trustsource, 2s-/1h-Grenzen
|
||||||
|
und den Post-Diskontinuitätsvertrag. Danach ausschließlich lesend tatsächliche
|
||||||
|
Serverqualität/Provider-API, Windows-Timer und Sync-/Deadline-Integrationspunkte
|
||||||
|
prüfen. Fehlt eine belastbare Qualitäts-/Alters-/Timergrenze, bleibt der
|
||||||
|
Entwurf blockiert; keine Implementierung mit angenommener Güte.
|
||||||
|
|
||||||
|
Nur nach bestandenem Review: wenige Byte-/Signatur-/Bindungs-/Intervallguards,
|
||||||
|
Serverseite zuerst auf der Linux-Cloud-VM qualifizieren, danach getrennt reale
|
||||||
|
Windows-Agent-/SYSTEM-Verifikation samt Replay, Delay, Restart und falscher
|
||||||
|
Rolle/Identität. Suspend/Clockstep zunächst injizierte Validatorinputs; kein
|
||||||
|
unangekündigter OS-Suspend/Uhrsprung. Quellen-/Buildnachweise eröffnen keine
|
||||||
|
Capability. Erst eigene reale Abnahme und anschließend tatsächlicher neuer
|
||||||
|
WebUI-genehmigter Windowsjob belegen eine nutzbare Strecke.
|
||||||
@@ -0,0 +1,133 @@
|
|||||||
|
# V5-Serverdescriptor mit Discoveryprincipal: Fehler87
|
||||||
|
|
||||||
|
2026-11-14. Getrennter nicht qualifizierender Nachfolger der
|
||||||
|
[SID-/Descriptorprobe](windows-clock-identity-result.md). Der ursprüngliche
|
||||||
|
RPC-Befund ist vollständig erhalten. Der separat hängende Cleanupaufruf wurde
|
||||||
|
ohne Wiederholung des Originals aufgelöst; der eigene Diagnosedienst ist
|
||||||
|
inzwischen separat nachgewiesen entfernt. Produktclock und Windowsjobs
|
||||||
|
bleiben geschlossen; Fehler87 ist keine Clockabnahme.
|
||||||
|
|
||||||
|
## Fester Vergleich und tatsächlicher Build
|
||||||
|
|
||||||
|
Die vier eingefrorenen Quellen unter
|
||||||
|
`deploy/windows/clock-spnego-descriptor-trace/` behalten GSS9/Privacy6/
|
||||||
|
Impersonate3 und QOS5 mit Mutual-Auth-Anforderung. Gegenüber dem vorherigen
|
||||||
|
SID-Vergleich verwenden sie `Sid=NULL` und exakt den tatsächlich vorhandenen
|
||||||
|
Discoveryprincipal, einschließlich einer vorhandenen leeren Zeichenfolge.
|
||||||
|
Ein NULL-Discoveryresultat bleibt verweigert. Discovery ist keine
|
||||||
|
Identitätsautorität. Der clientseitige Serverdescriptor bleibt absolut und
|
||||||
|
enthält genau eine feste ACE; keine Änderung einer OS-/Dienst-DACL.
|
||||||
|
|
||||||
|
Kontrolle0 bindet darin die W32Time-Service-SID. Die fest kompilierten
|
||||||
|
Kontrollen1/2 sind falscher SYSTEM-Account beziehungsweise falsche
|
||||||
|
RmmDiscoveryWindows-Service-SID; beide wurden hier nicht nativ ausgeführt.
|
||||||
|
Einmalige Aktivierung und Wiederherstellung des eigenen vorhandenen Privilegs
|
||||||
|
bleiben diagnostische Tokenänderungen. Fremde Prozess-/Tokenhandles bleiben
|
||||||
|
QUERY-only. Kein Fallback, W32Time-Setter oder RMM-Job.
|
||||||
|
|
||||||
|
Der vorbereitete lokale Build bestand C-Werror, unveränderten Microsoft-MIDL-
|
||||||
|
Compile, Link, Importgrenze, PowerShell-AST und Manifestprüfung. Keine erneute
|
||||||
|
Buildbehauptung aus der folgenden reinen Dokumentations-/Readerprüfung.
|
||||||
|
Manifest SHA256
|
||||||
|
`34c51e005a90eb4344ffd31231a4b6df866d7f495f33fa81dcfcb8b34294dec7`;
|
||||||
|
PE117588Byte/SHA256
|
||||||
|
`e7f2abc34b9c5ef5537892825724d15e488fdfd276de0d4468f6e1eae011769a`.
|
||||||
|
Die131 ursprünglichen Produktinputs,27 älteren Diagnoseinputs und die vier
|
||||||
|
neuen Descriptorquellen sind unverändert separat hashgeprüft.
|
||||||
|
|
||||||
|
## Tatsächlicher VM-Befund
|
||||||
|
|
||||||
|
Root führte nur Kontrolle0 im eigenen Fall
|
||||||
|
`4b1ae5cf-1573-4cac-8c01-17d1d36029c3` aus. Eigene Vorbereitung/Übertragung
|
||||||
|
und genau ein SYSTEM-Diagnosedienststart; anschließend getrennte Nur-Lese-
|
||||||
|
Readbacks desselben Falls:
|
||||||
|
|
||||||
|
- SYSTEM-Token bestätigt, DienstStopped/Exit0;
|
||||||
|
- genau eine erfolgreiche Principaldiscovery, tatsächlich non-NULL und leer;
|
||||||
|
- QOS5/Control0 und vorhandener Serverdescriptor;
|
||||||
|
- `RpcBindingSetAuthInfoExW` verweigert87 bei Stage30;
|
||||||
|
- **null Statusqueries**, kein Statusobjekt oder normaler Statusreturn;
|
||||||
|
- EEInfo-Capture versucht, Start1761/keine Records;
|
||||||
|
- Principal- und Bindingfreigabe jeweils erfolgreich;
|
||||||
|
- eigenes Privileg vollständig wiederhergestellt, beobachtete Peertoken
|
||||||
|
unverändert; kein Agent-/W32Time-Konfigurationswechsel oder neuer RMM-Job.
|
||||||
|
|
||||||
|
Original `diagnostic-result.json`, SHA256
|
||||||
|
`27315e9a56735b929527f54309b3aecb372584f8f9a3efe689d7d3d230355121`.
|
||||||
|
`complete=true` bezeichnet den vollständig erhaltenen diagnostischen Fehler,
|
||||||
|
keinen positiven Clock-/Identitätsnachweis oder abgeschlossenen Cleanup.
|
||||||
|
Der Originalbericht enthält ausdrücklich `cleanup_completed=false`.
|
||||||
|
|
||||||
|
Separater Erhaltungsbeleg vor/nach dem Diagnosebefund: sechs native
|
||||||
|
RMM-Bereiche und Servergate erhalten; Windows0/0/0/0, Linux31/31/27/0,
|
||||||
|
Rootpolicycf15 geschlossen, Transportfaults aus. Before-SHA256
|
||||||
|
`54eb250bbdcbb49315bdb4dc23e01509497b8264249f5f4fc4756fe7290025e2`,
|
||||||
|
After-SHA256
|
||||||
|
`eb0ee568745e488e38cc43a68c03424aab697c740168b8b22c31d627c2c035fe`.
|
||||||
|
Dieser Erhaltungsnachweis bestätigt noch keine spätere Cleanupauflösung.
|
||||||
|
|
||||||
|
## Cleanupantwort verloren, eng begrenzter eigener Prozess beendet
|
||||||
|
|
||||||
|
Der separat gestartete ursprüngliche Cleanupaufruf überschritt50s.
|
||||||
|
Sein lokaler Timeoutbeleg bleibt erhalten; remote war kein Cleanupmarker
|
||||||
|
nachgewiesen. Ein wiederholter Originalcleanup wurde ausdrücklich nicht
|
||||||
|
gestartet. Die Nur-Lese-Auflösung fand den eigenen hängenden
|
||||||
|
PowerShell-Bootstrapclient PID4460, exakte Erzeugungs-FILETIME
|
||||||
|
`134391586730921083`.
|
||||||
|
|
||||||
|
Root prüfte dessen gehaltenes Prozesshandle, PID/Erzeugungszeit, Image und
|
||||||
|
genauen ursprünglichen Command und beendete ausschließlich diesen Client
|
||||||
|
einmal. Separater Beleg `spnego-descriptor-own-client-terminate-result.json`
|
||||||
|
im geschützten Pipefall14fb, SHA256
|
||||||
|
`b3312d4abd8a2722f729eaac4a132909f6ae1f5072ced47be62b24ad788e5635`:
|
||||||
|
`terminated=true`, `wait_code=0`, `no_rmm_service_termination=true`,
|
||||||
|
`no_retry_original_cleanup=true`.
|
||||||
|
|
||||||
|
Das beendet den alten Bootstrapclient und war alleine noch kein Beleg für
|
||||||
|
das Entfernen des Diagnosedienstes. Er blieb bis zur folgenden eigenen
|
||||||
|
Auflösung Stopped/registriert. Originalintent/-timeout/-result bleiben
|
||||||
|
unverändert; der Originalcleanup wurde nicht wiederholt.
|
||||||
|
|
||||||
|
## Separate Cleanupauflösung tatsächlich abgeschlossen
|
||||||
|
|
||||||
|
Root führte danach ausschließlich die neue eng gebundene Auflösung aus.
|
||||||
|
Das private Skript hat SHA256
|
||||||
|
`573c0cf7512add7ef51f7c3d76609b1388536963c21ee5e435ba978921ec5d40`.
|
||||||
|
Es hält ein natives SCM-Servicehandle und prüft per `QueryServiceConfigW`/
|
||||||
|
`QueryServiceStatusEx` exakt den ursprünglichen Image-/Argumentcommand,
|
||||||
|
LocalSystem, Manual, Servicetyp16 sowie Stopped/Exit0/PID0. Erst nach diesen
|
||||||
|
Prüfungen einmal `DeleteService`, Handle schließen und Abwesenheit prüfen.
|
||||||
|
Neue Resolution-Intent-/Completedmarker gehören ausschließlich zu dieser
|
||||||
|
separaten Phase; beide alten Remote-Cleanupmarker bleiben nachweislich false.
|
||||||
|
|
||||||
|
Ergebnis `spnego-descriptor-cleanup-resolution-result.json`, SHA256
|
||||||
|
`3c9bc0d4be2c5fb1cf404d4e94c492611662830c1867bc55bb96d53f4b80948d`;
|
||||||
|
separater Nur-Lese-Nachbeleg SHA256
|
||||||
|
`d51b3c5e9811a04265c114ba3197c9d07f2700dd862d538b3735c6a5f4802a28`.
|
||||||
|
Beide bestätigen den eigenen Dienst als abwesend und keinen RMM-Wechsel.
|
||||||
|
Das originale `diagnostic-result.json` behält weiterhin seinen damaligen
|
||||||
|
Wert `cleanup_completed=false`; es wird nicht rückwirkend umgeschrieben.
|
||||||
|
|
||||||
|
Vollständiger neuer Erhaltungsnachbeleg SHA256
|
||||||
|
`df4b241d885d11c83c10562b8f31b9154f4c6dcfc54917e6a3d09257f3dd4c09`:
|
||||||
|
Root verglich erneut die sechs RMM-Erhaltungsbereiche `service`,
|
||||||
|
`helper_service`, `agent_kernel`, `helper_kernel`, `files`, `helper_witness`
|
||||||
|
mit dem vorigen eb0e-Beleg; bestanden. Der komplette Serverrecord ist gleich. Passive
|
||||||
|
Agenttelemetrie/Probe-/Journalbeobachtungen dürfen sich weiterentwickeln;
|
||||||
|
der gesamte native Rohbericht wird deshalb nicht als bytegleich behauptet.
|
||||||
|
Keine neue Diagnosequery, Jobwirkung oder W32Time-Änderung durch diese Auflösung.
|
||||||
|
|
||||||
|
## Lokal nachgelesen und verbleibende Grenzen
|
||||||
|
|
||||||
|
Der unveränderte lokale Manifestreader sowie Report-/Privilegewitnessreader
|
||||||
|
wurden auf den erhaltenen Originaldateien erfolgreich ausgeführt; beide
|
||||||
|
Pythonquellen zusätzlich per AST geparst. Diese Prüfungen starten weder SSH
|
||||||
|
noch einen Prozess auf einem Ziel. `git diff --check` betrifft die vorbereiteten
|
||||||
|
Quellen-/Dokumentationsänderungen. Kein erneuter Compiler-/VM-/Joblauf.
|
||||||
|
|
||||||
|
Die anschließende [statische RPC-Runtimeanalyse](windows-clock-rpc-qos5-analysis.md)
|
||||||
|
grenzt die Verweigerung des konkreten OS-Stands ein. Sie ist kein nachträglich
|
||||||
|
erfundener dynamischer Trace und begründet keinen weiteren Formatclone.
|
||||||
|
Der [Zeitbeleg-ADR](windows-clock-attestation-proposal.md) ist ausschließlich
|
||||||
|
ein entscheidungsbedürftiger Vorschlag; keine angenommene Trustsource oder
|
||||||
|
implementierte Clockalternative. Keine Capability oder Policy aktiviert.
|
||||||
@@ -0,0 +1,190 @@
|
|||||||
|
# Begrenzter EEInfo-Nachfolger: Fehlerlage statt Ursachenbehauptung
|
||||||
|
|
||||||
|
Stand 2026-11-14: **separat implementiert, lokal gebaut und durch den
|
||||||
|
verantwortlichen Rootprozess einmal auf der Windows-VM ausgeführt**. Dieser
|
||||||
|
Subagent führte keine VM-Aktion aus. Der tatsächliche vorherige SYSTEM-Vergleich
|
||||||
|
`562ff9de-67ff-48a1-96f0-c2474b3b0777` meldete wie LocalService RPC5/Stage90
|
||||||
|
ohne Status oder normalen RPCreturn. Die einfache Erklärung durch ausschließlich
|
||||||
|
LocalService ist damit nicht belegt. Authentifizierungs-/Autorisierungsschicht
|
||||||
|
und tatsächliche serverseitige Calleridentität bleiben offen. Kein Produktgate
|
||||||
|
wird aus diesem Befund geöffnet.
|
||||||
|
|
||||||
|
## Microsoft-Quellen und konkrete Grenzen
|
||||||
|
|
||||||
|
Die [V5-QoS-Dokumentation](https://learn.microsoft.com/en-us/windows/win32/api/rpcdce/ns-rpcdce-rpc_security_qos_v5_w)
|
||||||
|
beschreibt den Serverdescriptor nur allgemein. Sie dokumentiert für unser
|
||||||
|
lokales `ncacn_np` keinen vollständigen Vertrag, der genau den tatsächlichen
|
||||||
|
Serverprozesstoken einschließlich W32Time-Service-SID beweist. Die
|
||||||
|
[SDK-Deklaration](https://github.com/microsoft/win32metadata/blob/main/generation/WinSDK/RecompiledIdlHeaders/shared/rpcdce.h)
|
||||||
|
belegt das Layout, nicht diese Laufzeitsemantik. Microsoft warnt außerdem, dass
|
||||||
|
NTLM erfolgreiche Mutual-Auth-Aushandlung melden kann, obwohl echte gegenseitige
|
||||||
|
Authentifizierung fehlt. V5, ein gesetztes Flag oder erfolgreicher SetAuth-Aufruf
|
||||||
|
sind deshalb kein selbständiger Konto-/Service-SID-Nachweis. Das ist eine
|
||||||
|
verbleibende Nachweislücke, keine Behauptung, der Descriptor könne grundsätzlich
|
||||||
|
nie wirksam sein. Microsoft-Q&A-Erfahrungsberichte wurden nicht als verbindliche
|
||||||
|
Produktgarantie verwendet.
|
||||||
|
|
||||||
|
Die LocalService-Beschreibung anonymer **Netzwerk**credentials beweist keinen
|
||||||
|
anonymen SSPI-Caller dieser lokalen NPFS-Verbindung. Laut
|
||||||
|
[RPC-Credentialsvertrag](https://learn.microsoft.com/en-us/windows/win32/rpc/client-authentication-credentials)
|
||||||
|
werden implizite Credentials aus Thread-/Prozesstoken gewonnen. Die tatsächlich
|
||||||
|
vom Server verwendete Identität lässt sich nicht einfach aus einem Client-
|
||||||
|
Account oder den konfigurierten Bindungsoptionen ablesen. Die dokumentierte
|
||||||
|
[Callattributes-Struktur](https://learn.microsoft.com/en-us/windows/win32/api/rpcasync/ns-rpcasync-rpc_call_attributes_v2_w)
|
||||||
|
enthält Authentifizierungsdaten und NullSession, wird jedoch serverseitig mit
|
||||||
|
`RpcServerInqCallAttributes` abgefragt; sie ist keine Clientabfrage in W32Time.
|
||||||
|
|
||||||
|
EEInfo kann die Fehlerlage eingrenzen: Microsoft benennt unter anderem SSP,
|
||||||
|
NPFS/Redirector/Named Pipe und Authz als
|
||||||
|
[GeneratingComponents](https://learn.microsoft.com/en-us/windows/win32/rpc/understanding-extended-error-information).
|
||||||
|
Eine einzelne Zahl beweist weiterhin weder einen anonymen Caller noch die
|
||||||
|
konkrete verweigernde ACL. Fehlende Records sind kein Gegenbeweis:
|
||||||
|
[EEInfo ist standardmäßig grenzüberschreitend deaktiviert](https://learn.microsoft.com/en-us/windows/win32/rpc/security-and-extended-error-information).
|
||||||
|
Der neue Versuch schaltet keine Registry-/Audit-/EEInfo-Policy um.
|
||||||
|
|
||||||
|
## Exakt begrenztes Source-Delta
|
||||||
|
|
||||||
|
Neue sibling-Dateien unter `deploy/windows/clock-eeinfo-trace/`, eigener Dienst
|
||||||
|
`RmmClockSystemEeInfoDiagnostic`, eigene History. Original131, alter Wrapper
|
||||||
|
und vorheriger SYSTEMrunner bleiben unverändert und readbackfähig.
|
||||||
|
|
||||||
|
`clock_rpc_eeinfo.c` ist eine sichtbare Diagnosequellvariante gegenüber
|
||||||
|
`clock_rpc.c`, Original-SHA256
|
||||||
|
`74aceb6e2b70c5dd628fae069a842c356c20300b8c8ab12754258c78eaf295c8`.
|
||||||
|
Der Build speichert `wrapper-source.diff` samt Hash. Änderungen ausschließlich:
|
||||||
|
`rpcasync.h`, fester104Byte-Numerikpuffer, Parameterweitergabe, neuer
|
||||||
|
Diagnoseexport und Capture im bestehenden `RpcExcept` direkt nach dem lokal
|
||||||
|
gespeicherten ursprünglichen Exceptioncode. Auth-/Endpunkt-/NDR-/QoSzeilen
|
||||||
|
bleiben gleich. Originalcode5 wird nicht durch Enum-Returncodes ersetzt.
|
||||||
|
|
||||||
|
Die tatsächlichen SDK-Prototypen werden aus dem Header verwendet:
|
||||||
|
`RpcErrorStartEnumeration(RPC_ERROR_ENUM_HANDLE*)`,
|
||||||
|
`RpcErrorGetNextRecord(RPC_ERROR_ENUM_HANDLE*, BOOL, RPC_EXTENDED_ERROR_INFO*)`
|
||||||
|
und `RpcErrorEndEnumeration(RPC_ERROR_ENUM_HANDLE*)`.
|
||||||
|
Microsoft verlangt den [sofortigen Enumerationsstart](https://learn.microsoft.com/en-us/windows/win32/api/rpcasync/nf-rpcasync-rpcerrorstartenumeration),
|
||||||
|
da spätere Aufrufe die Threaddaten überschreiben können. Der Start steht vor
|
||||||
|
jedem weiteren RPC-/BindingFree-Aufruf im Handler.
|
||||||
|
|
||||||
|
Höchstens vier NextRecord-Aufrufe, keine fünfte Abfrage. Je Record verlassen
|
||||||
|
nur GeneratingComponent, Status, DetectionLocation, Flags und NumberOfParameters
|
||||||
|
C. Keine Parameterwerte, Strings, ComputerName, Binary-/Pointerdaten oder
|
||||||
|
Zeit-/Namensfelder werden kopiert/exportiert. Gemäß
|
||||||
|
[GetNextRecord](https://learn.microsoft.com/en-us/windows/win32/api/rpcasync/nf-rpcasync-rpcerrorgetnextrecord)
|
||||||
|
werden Version, Flags und **MaxNumberOfEEInfoParams** als Eingabekapazität gesetzt;
|
||||||
|
Nullkapazität könnte sonst BUFFER_TOO_SMALL auslösen. CopyStringsFALSE bedeutet
|
||||||
|
geborgte RPC-Daten, die der Aufrufer weder verändert noch freigibt. Bei
|
||||||
|
erfolgreichem Start wird immer
|
||||||
|
[EndEnumeration](https://learn.microsoft.com/en-us/windows/win32/api/rpcasync/nf-rpcasync-rpcerrorendenumeration)
|
||||||
|
aufgerufen. `limit_reached=1` bedeutet ausschließlich erreichtes Viererbudget,
|
||||||
|
keinen Beweis eines weiteren Records.
|
||||||
|
|
||||||
|
Die neue SID18-Servicehülle ruft genau einmal denselben Tracepfad auf. Höchstens
|
||||||
|
4096Bytes Ergebnis, ausschließlich numerische Zusatzdaten und feste Labels;
|
||||||
|
clock/adapter/productgate bleiben false. Keine Impersonationserhöhung,
|
||||||
|
Anonymous-/unauthenticated-Fallbacks, ACL-, NTP- oder Accountänderung.
|
||||||
|
Prepare/Start/Readback/Cleanup bleiben getrennt; Cleanup nur eigener eindeutig
|
||||||
|
gebundener gestoppter Dienst, Remote-Readback ausschließlich lesend.
|
||||||
|
|
||||||
|
## Tatsächlich lokal geprüft
|
||||||
|
|
||||||
|
```text
|
||||||
|
python3 deploy/windows/clock-eeinfo-trace/build.py
|
||||||
|
```
|
||||||
|
|
||||||
|
Offline im gepinnten bisherigen Image gebaut. Neue C-Hülle/Wrapper bestehen
|
||||||
|
`-Wall -Wextra -Werror`; nur dieselben drei bekannten Stilwarnungen am
|
||||||
|
unveränderten echten Microsoft-MIDL-Stub bleiben sichtbar. Kein Typ-/Security-
|
||||||
|
Warning wurde unterdrückt. Link/PE-x64-/Import-/private Manifestguards bestanden,
|
||||||
|
ebenso der tatsächliche PowerShell-AST-Lauf; EncodedCommand16718Zeichen.
|
||||||
|
Imports nur ADVAPI32/KERNEL32/RPCRT4/msvcrt.
|
||||||
|
|
||||||
|
Finaler Manifest:
|
||||||
|
`devstate/windows-clock-eeinfo-trace/build-8d33bc4b-a0ce-430e-aa5b-5d1dc112ecf0/manifest.json`,
|
||||||
|
SHA256 `2b10417c41ff5c293f71e303b703e8d883d3ba7bc361bb047417d5de66124b49`.
|
||||||
|
PE101312Bytes, SHA256
|
||||||
|
`cef50aa281069c76494f88ef893191e3978f9a3c66d162658f5914a5193d2787`.
|
||||||
|
Der frühere lokale Pack `9ca2ff31…` bleibt erhalten und wird nicht für die
|
||||||
|
Probe verwendet; der finale Driver bindet zusätzlich den sichtbaren Diff und
|
||||||
|
prüft ursprünglichen Exceptioncode gegen Originaltrace.
|
||||||
|
|
||||||
|
Acht manipulierte Record-/Reportfälle, Viererbudget, ursprünglicher RPCcode,
|
||||||
|
String-/Parameterverweigerung, kein Datenbeleg bei leerem EEInfo und rein
|
||||||
|
lesendes Readback wurden lokal mit ausdrücklich **simulierten** Reports geprüft.
|
||||||
|
Diese dürfen eine vollständig ausgeführte Diagnose darstellen, beweisen aber
|
||||||
|
keinen echten RPC-/Status-/Clockerfolg. `local-guards.json` kennzeichnet die
|
||||||
|
Mocks und `native_executed=false`; alte SYSTEMdateien wurden bytegleich
|
||||||
|
nachgeprüft. Keine SSH-/VM-/Dienst-/RMM-Aktion durch diesen Subagenten.
|
||||||
|
|
||||||
|
## Tatsächliche einmalige Root-Probe und getrenntes Readback
|
||||||
|
|
||||||
|
Root führte den freigegebenen finalen Pack im Fall
|
||||||
|
`e4e6e12f-6c1b-4bd2-8072-70c5e6634aa6` auf der Windows-VM aus. Der eigene
|
||||||
|
SYSTEM-Diagnosedienst meldete genau einen Queryaufruf und beendete sich mit
|
||||||
|
Service-Exitcode0; die RPC-Abfrage selbst blieb ausdrücklich fehlgeschlagen:
|
||||||
|
`token_system=true`, RPC5, Stage90, Exception5, kein normaler RPCreturn und kein
|
||||||
|
Statusobjekt. Service-Exit0 ist hier ausschließlich Abschluss der Diagnose.
|
||||||
|
Clock-, Adapter- und Produktgate blieben false. Kein RMM-Job entstand.
|
||||||
|
|
||||||
|
Die unmittelbar im Exceptionhandler erfassten numerischen EEInfo-Daten sind:
|
||||||
|
|
||||||
|
| Feld | Tatsächlicher Wert |
|
||||||
|
| --- | --- |
|
||||||
|
| capture_attempted / start_status | 1 / 0 |
|
||||||
|
| next_status / end_status | 1761 / 0 |
|
||||||
|
| count / limit_reached | 1 / 0 |
|
||||||
|
| generating_component / status | 2 / 5 |
|
||||||
|
| detection_location / flags / number_of_parameters | 1750 / 0 / 1 |
|
||||||
|
|
||||||
|
Keine Parameterwerte, Strings, Rechnernamen oder Binary-/Pointerdaten wurden
|
||||||
|
exportiert. Der lokal erhaltene `diagnostic-result.json` hat SHA256
|
||||||
|
`80accca4f99a2ede0ccb3fd0a21730f69a53a6310c6c6ead42aa4d958c56b6f4`.
|
||||||
|
Ein gesonderter lesender Aufruf lieferte dasselbe vollständige Reportobjekt:
|
||||||
|
`readback-2a256a82-5e0d-4895-b3d9-0a67cfa841e8.json`, SHA256
|
||||||
|
`93a1655fa4327579580e6df661ec7243af282af1f175735d882ccbd1ec9002b5`.
|
||||||
|
Die Dateien liegen im privaten ursprünglichen Caseverzeichnis unter
|
||||||
|
`devstate/windows-clock-eeinfo-trace/`; keine Zugangsdaten oder Transportpräfixe
|
||||||
|
gehören zum publizierbaren Beleg.
|
||||||
|
|
||||||
|
Root entfernte anschließend ausschließlich den eigenen gebundenen gestoppten
|
||||||
|
Diagnosedienst. Der separate Cleanupbeleg
|
||||||
|
`readback-a1ef841d-218e-4adc-9075-1af320baf1f5.json`, SHA256
|
||||||
|
`c03b535f21f430399f9ae3fbdca8d1e869b80ae6567b762eded04f208a68fcc3`,
|
||||||
|
meldet `cleanup_verified=true`; das war eine explizite Cleanupaktion, kein
|
||||||
|
lesender Aufruf. Root hat zusätzlich die vollständige Preservationprüfung
|
||||||
|
abgeschlossen: ursprüngliche Agent-/Helperdienste und Prozessgeburten, Codehashes,
|
||||||
|
FileIDs, PKI-/Datenbankzeugen und serverseitiger Zustand stimmen vor/nach exakt
|
||||||
|
überein. Keine neuen Jobs, Clockgate weiterhin false. Vorherbeleg-SHA256
|
||||||
|
`3d508df7a46b3ab181f9d9575432e544627609fed98c77dabb107a7798bcb87b`;
|
||||||
|
Nachherbeleg `eeinfo-trace-after.json` im ursprünglichen privaten
|
||||||
|
`windows-pipe-drain/devstate/windows-client/system-pipe-upgrade/14fb176a-f653-4573-a8d7-6f9fe47a3020/`-Kontext,
|
||||||
|
SHA256 `921cd12b8f90c0921a6a11ec48d3ef61d4fffb2f6f3979f5f8731d2ac6425240`.
|
||||||
|
Das ist ein Erhaltungsnachweis der Diagnose, kein erfolgreicher Clock-/Jobnachweis.
|
||||||
|
|
||||||
|
## Belegte Deutung und verbleibende Grenze
|
||||||
|
|
||||||
|
Microsoft ordnet [GeneratingComponent2 der RPC-Runtime zu](https://learn.microsoft.com/en-us/windows/win32/rpc/understanding-extended-error-information).
|
||||||
|
Status5 bezeichnet [Access denied](https://learn.microsoft.com/en-us/windows/win32/debug/system-error-codes--0-499-).
|
||||||
|
Dies benennt den meldenden Layer und den Fehler, weder die konkrete verweigernde
|
||||||
|
ACL noch den tatsächlichen serverseitigen Caller oder einen anonymen SSPIkontext.
|
||||||
|
|
||||||
|
DetectionLocation ist laut derselben EEInfo-Dokumentation ein von der
|
||||||
|
Implementierungsversion abhängiger interner Codeort. Die öffentliche
|
||||||
|
[Detection-Locations-Tabelle](https://learn.microsoft.com/en-us/windows/win32/rpc/extended-error-information-detection-locations)
|
||||||
|
gilt ausdrücklich für WindowsXP und enthält1750 nicht. Auch
|
||||||
|
[MS-EERR2.2.3](https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-eerr/92064599-dc99-4e86-a887-b377a95ac678)
|
||||||
|
liefert keine Zuordnung für1750/Component2. Die geprüften Primärquellen erklären
|
||||||
|
diesen Windows-11-Codeort somit nicht. Die Zahl1750 ist hier außerdem kein
|
||||||
|
Win32-Returncode und darf nicht als dessen Fehlername dekodiert werden.
|
||||||
|
|
||||||
|
Der Enumstatus1761 ist gemäß [GetNextRecord-Vertrag](https://learn.microsoft.com/en-us/windows/win32/api/rpcasync/nf-rpcasync-rpcerrorgetnextrecord)
|
||||||
|
das normale Ende nach dem letzten erfolgreich gelesenen Record. Ein Record
|
||||||
|
wurde erfasst, das Viererbudget nicht erreicht; dies ist kein Enumfehler anstelle
|
||||||
|
des ursprünglichen RPC5. Flags0 meldet keine Missing-Record-Flags. Microsoft
|
||||||
|
beschreibt EEInfo dennoch ausdrücklich als [best effort und ungeeignet für Produktentscheidungslogik](https://learn.microsoft.com/en-us/windows/win32/rpc/reliability-of-extended-error-information):
|
||||||
|
eine vollständige Ursachen- oder Nichtanonymitätsgarantie folgt daraus nicht.
|
||||||
|
|
||||||
|
Die enge Diagnose hat damit einen tatsächlichen Runtime-EEInfo-Beleg geliefert,
|
||||||
|
keinen W32Time-Status oder Clocknachweis. Eine weitere Deutung des Codeorts
|
||||||
|
braucht einen zum tatsächlichen Windows-/RPC-Build passenden Primärnachweis.
|
||||||
|
Keine ACL-/Konto-/Auth-/NTPänderung und keine Ersatzclock/Brokerarchitektur wird
|
||||||
|
aus diesem Record abgeleitet; sämtliche Produktgates bleiben geschlossen.
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
# V5-SID-/Service-Descriptorprobe: Bindung verweigert
|
||||||
|
|
||||||
|
2026-11-14. Nach dem [erfolgreichen reinen RPC-Vergleich](windows-clock-impersonate-result.md)
|
||||||
|
wurde eine getrennte, ausdrücklich nicht qualifizierende Identitätsprobe
|
||||||
|
vorbereitet. Die Produktdateien und alle früheren Reader/Belege blieben erhalten.
|
||||||
|
|
||||||
|
Die vier Quellen `deploy/windows/clock-spnego-identity-trace/` verwenden
|
||||||
|
GSS9/Privacy6/Impersonate3 sowie QOS5 mit Mutual-Auth-Anforderung, fester
|
||||||
|
Account-SID als dokumentierter Alternative zum Authprincipal und einem
|
||||||
|
clientseitigen Serverdescriptor mit fester Service-SID. Die tatsächlich
|
||||||
|
zurückgegebene Discoveryzeichenfolge wird weiterhin geprüft und freigegeben;
|
||||||
|
sie wird nicht als Identitätsautorität übernommen. Die Bindung verwendet hier
|
||||||
|
ausdrücklich NULL für ServerPrincName und dafür den festen SID-Parameter.
|
||||||
|
[Dokumentierter QOS5-Vertrag](https://learn.microsoft.com/en-us/windows/win32/api/rpcdce/ns-rpcdce-rpc_security_qos_v5_w).
|
||||||
|
|
||||||
|
Drei eng geschlossene Buildkontrollen sind vorgesehen:0 für LocalService/
|
||||||
|
W32Time,1 für falschen Systemaccount,2 für falsche RmmDiscoveryWindows-Service-SID.
|
||||||
|
Die Kontrolle wird fest kompiliert und im Manifest gebunden; der tatsächliche
|
||||||
|
numerische Report muss exakt dazu passen. Kein Setter, Fallback, RMM-Job oder
|
||||||
|
Produktgate. Derselbe eigene Enable-/Restoreablauf mit ausschließlich lesenden
|
||||||
|
fremden Tokenhandles und erhaltener Prozessbindung bleibt bestehen.
|
||||||
|
|
||||||
|
Tatsächliche lokale Prüfung: Der erste Build `bafde30c…` scheiterte vor Link
|
||||||
|
an einer fehlenden QOS5-Typdeklaration im neuen Wrapper. Der fehlende Block
|
||||||
|
wurde danach bytegleich aus dem bisherigen Produktwrapper übernommen,
|
||||||
|
einschließlich x64-/SDK-ABI-Assertions. Kein Compilerfehler wurde unterdrückt.
|
||||||
|
Der neue Build für Kontrolle0 bestand C-Werror, unveränderten Microsoft-MIDL-
|
||||||
|
Compile, Link, Importgrenze, PowerShell-AST und lokalen Manifestreader.
|
||||||
|
Unabhängiger Quellenreview ohne weitere Funktionsblocker;131 Produktinputs
|
||||||
|
und23 frühere Diagnoseinputs unverändert. Kontrollen1/2 wurden noch nicht gebaut
|
||||||
|
oder auf der VM ausgeführt.
|
||||||
|
|
||||||
|
Manifest `d3a6222da8aed64e4e5ad5c07993177a11f56af229d4754ea04f248ee79385bc`,
|
||||||
|
PE117586Byte/SHA256
|
||||||
|
`5c55327f5569723875bb4b2622dd12fda76dbb041ea80d0a64324acc940440ba`.
|
||||||
|
|
||||||
|
## Tatsächlicher VM-Befund
|
||||||
|
|
||||||
|
Root führte ausschließlich Kontrolle0 im eigenen neuen Fall
|
||||||
|
`bcda2ede-d3e0-41bf-94e9-9f44ea785c54` aus. Einmalige Vorbereitung/Übertragung
|
||||||
|
und ein eigener SYSTEM-Dienststart, anschließend separater lesender Readback:
|
||||||
|
|
||||||
|
- DienstStopped/Exit0, Diagnose vollständig aufgezeichnet;
|
||||||
|
- eine erfolgreiche Discovery mit tatsächlich nicht-NULL leerem Principal;
|
||||||
|
- QOS5/Control0, Serverdescriptor vorhanden;
|
||||||
|
- `RpcBindingSetAuthInfoExW` verweigert mit87 bei Stage30;
|
||||||
|
- **null Statusqueries**, kein normaler Statusreturn und kein EEInfo-Record;
|
||||||
|
- eigenes vorhandenes Privileg nach Aktivierung vollständig nachgelesen
|
||||||
|
zurückgesetzt, beobachtete Peertoken unverändert;
|
||||||
|
- anschließend ausschließlich der eigene gestoppte Diagnosedienst entfernt.
|
||||||
|
|
||||||
|
Endbeleg `diagnostic-result.json`, SHA256
|
||||||
|
`ce4004b1fd833b9590f23d31a918daefccf8870e6630be6beb28869fad1f8b5c`.
|
||||||
|
Separater Erhaltungsnachweis: alle sechs bestehenden nativen RMM-Bereiche
|
||||||
|
und Servergate gleich, Windows0/0/0/0 und Linux31/31/27/0, Rootpolicycf15 geschlossen.
|
||||||
|
Before-SHA256 `ee28b23c474958b47ebeb50e03e3c2b21df4bddfc777583908921d5b4982de77`,
|
||||||
|
After-SHA256 `de130d3e6f279d84f8b56cc896fd50ef04415b09f6349eb615eda87971ca97a7`.
|
||||||
|
„Diagnose vollständig“ bedeutet hier einen vollständig erhaltenen Fehlerbefund,
|
||||||
|
keinen positiven Identitäts- oder Clocknachweis. Weil schon die erwartete
|
||||||
|
Identität keinen Statuspfad erreicht, wurden keine negativen Identitätskontrollen
|
||||||
|
als vermeintliche erfolgreiche Sicherheitsabnahme nachgeschoben.
|
||||||
|
|
||||||
|
Der konkrete Parameterverbund ist damit auf dieser VM nicht zugelassen.
|
||||||
|
Welcher einzelne Parameter diese87-Ablehnung verursacht, ist noch nicht isoliert.
|
||||||
|
Insbesondere wird daraus weder eine generelle Nichtunterstützung jeder V5-
|
||||||
|
Named-Pipe-Konfiguration noch eine erlaubte Lockerung der Produktidentität
|
||||||
|
abgeleitet. Eine weitere dokumentierte Parameteralternative benötigt einen
|
||||||
|
separaten Quellen-/Build-/Nativefall. Produktclock/Jobs bleiben geschlossen.
|
||||||
|
NTPresync wartet weiterhin auf die konkrete Benutzerfreigabe.
|
||||||
@@ -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.
|
||||||
@@ -0,0 +1,107 @@
|
|||||||
|
# Nächster Clock-Diagnosekandidat: Microsoft-MIDL-Codegenerierung
|
||||||
|
|
||||||
|
Stand 2026-11-14. **Geplant, nicht auf der Windows-VM ausgeführt.** Der
|
||||||
|
Narrow-IDL-Pointerkandidat `91889303…` liefert laut getrenntem nativen
|
||||||
|
Root-Beleg weiterhin `1783` in Trace-Stage 90, ohne normale RPC-Rückkehr und ohne
|
||||||
|
Status. Seine einzelne Pointeränderung ist damit nicht als ausreichender Fix
|
||||||
|
belegt. Das beweist nicht, dass Pointersemantik irrelevant ist. ALPC `1753` und
|
||||||
|
das geschlossene Clock-Gate werden davon nicht verändert.
|
||||||
|
|
||||||
|
## Enger nächster Nachweis
|
||||||
|
|
||||||
|
Microsoft beschreibt [MIDL-generierte Clientstubs](https://learn.microsoft.com/en-us/windows/win32/midl/files-generated-for-an-rpc-interface)
|
||||||
|
als vorgesehenen Weg; die [NDR-Dokumentation](https://learn.microsoft.com/en-us/windows/win32/rpc/rpc-ndr-engine)
|
||||||
|
rät ausdrücklich von handbearbeiteten Stubdaten ab. Deshalb folgt kein weiterer
|
||||||
|
Formatbytepatch. Ein separat gehaltener Microsoft-Generator soll denselben
|
||||||
|
Quellvertrag erzeugen, bevor ein weiterer RPC-Diagnosekandidat gebaut wird.
|
||||||
|
|
||||||
|
Das offizielle [SDK-NuGet-Paket 10.0.26100.9169](https://www.nuget.org/packages/Microsoft.Windows.SDK.CPP/10.0.26100.9169)
|
||||||
|
wurde ausschließlich auf dem Entwicklungsrechner über verifiziertes TLS geladen
|
||||||
|
und als ZIP aufgelistet, nicht installiert oder ausgeführt. Privater Fall:
|
||||||
|
`devstate/windows-clock-midl/6b7fb9b1-0bb7-4880-850b-e6812d3df1b1`.
|
||||||
|
Paket: 160512239 Bytes, SHA-256
|
||||||
|
`475269434dcd808a67853773272f972c3229c0e10c3ddc821290e70cc0f6904d`.
|
||||||
|
|
||||||
|
Genau die enthaltenen Tools `c/bin/10.0.26100.0/x64/midl.exe` und `midlc.exe`
|
||||||
|
reichen nach statischer Importprüfung als Kandidat: beide importieren nur
|
||||||
|
`KERNEL32.dll` und `msvcrt.dll`. Das ist noch kein Beweis, dass sie auf dem Ziel
|
||||||
|
ohne weitere Abhängigkeit laufen. Tool-SHA-256:
|
||||||
|
|
||||||
|
- `midl.exe`, 154048 Bytes:
|
||||||
|
`7a2a717be64f755390ad8b04cb034549b2606acec646ec7cbe44c67516ccba83`.
|
||||||
|
- `midlc.exe`, 1366464 Bytes:
|
||||||
|
`34293d7bd256f2d43311d197f13bbb8a1ae26c92cc1605d9f35dd3ddfe264b65`.
|
||||||
|
|
||||||
|
**Microsoft-Authenticode und Zertifikatskette sind noch nicht geprüft.**
|
||||||
|
Der Paketdownload und ein berechneter Hash ersetzen diese Prüfung nicht.
|
||||||
|
Vor Toolausführung müssen die exakten Dateien am Ziel einen gültigen erwarteten
|
||||||
|
Microsoft-Signer und dieselben Hashes besitzen. Keine Trust-/Zertifikatänderung.
|
||||||
|
|
||||||
|
## Geplanter begrenzter Ablauf
|
||||||
|
|
||||||
|
Ein eigener create-only Fall erhält Quellen, Toolhashes und vor dem Start einen
|
||||||
|
dauerhaften Startintent. Es werden nur die beiden Tools und die gehashte
|
||||||
|
IDL-Quelle in ein eigenes Administratorverzeichnis übertragen. Keine Installation,
|
||||||
|
kein Registry-/PATH-/Policy-/Servicewechsel und keine RPC-/RMM-Ausführung.
|
||||||
|
Verlorene Antwort bedeutet ausschließlich Readback desselben Falls, keinen
|
||||||
|
neuen Toolstart. Toolausgabe und erzeugte Dateien bleiben als private Originale
|
||||||
|
erhalten; Ausgangsquellen werden nicht überschrieben.
|
||||||
|
|
||||||
|
Geplante feste Argumente:
|
||||||
|
|
||||||
|
```text
|
||||||
|
/nologo /no_cpp /env amd64 /Oicf /robust /Zp8 /protocol dce
|
||||||
|
/client stub /server none /h w32time.h /cstub w32time_c.c w32time.idl
|
||||||
|
```
|
||||||
|
|
||||||
|
[`/no_cpp`](https://learn.microsoft.com/en-us/windows/win32/midl/-no-cpp-nocpp)
|
||||||
|
ist der offizielle Verzicht auf den C-Präprozessor. Die enge Quelle besitzt keine
|
||||||
|
Includes oder Präprozessordirektiven; ein fehlendes CL soll nicht durch
|
||||||
|
Installation/Policyänderung kompensiert werden. [`/env amd64`](https://learn.microsoft.com/en-us/windows/win32/midl/-env)
|
||||||
|
setzt das tatsächliche x64-Ziel und 8er-Packung;
|
||||||
|
[`/protocol dce`](https://learn.microsoft.com/en-us/windows/win32/midl/-protocol)
|
||||||
|
hält die bisherige DCE-NDR-Transfersyntax konstant. Es gibt keine stillschweigende
|
||||||
|
NDR64-Umstellung.
|
||||||
|
|
||||||
|
Zuerst werden die originale [Microsoft-Voll-IDL](https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-w32t/5793e908-22ef-4cea-962f-fca8a72c485a)
|
||||||
|
und die unveränderte enge Quelle separat generiert. Zu vergleichen sind der
|
||||||
|
Opnum-6-Vertrag, der vollständige Pointerpfad, expliziter Bindinghandle, alle
|
||||||
|
19 Statusfelder und der 120-Byte-x64-ABI. Die Voll-IDL ist ausschließlich
|
||||||
|
Vergleichseingabe; ihre anderen Operationen werden niemals aufgerufen.
|
||||||
|
|
||||||
|
Nur nach erhaltenem nativen Codegenbeleg kann ein neuer separat gehashter
|
||||||
|
Diagnosebuild mit **unverändertem generiertem** Clientstub und bisherigem
|
||||||
|
C-Wrapper untersucht werden. Ein konkretes Compiler-/Headerproblem muss offen
|
||||||
|
benannt werden; kein manuelles Umschreiben von NDR-Daten. Authentisierung,
|
||||||
|
Endpoint, SEH-Grenze, Allocatorgrenze, Statusguard und `ADAPTER_QUALIFIED=false`
|
||||||
|
bleiben unverändert. Ein lesbarer Named-Pipe-Status allein ist keine qualifizierte
|
||||||
|
Clock oder Helper-Zeitautorität.
|
||||||
|
|
||||||
|
## Vorbereiteter Runner (weiterhin kein Zielnachweis)
|
||||||
|
|
||||||
|
`deploy/windows/midl_codegen.py` implementiert die getrennten Aktionen
|
||||||
|
`prepare`, `start`, `readback` und verwendet ausschließlich den streng geparsten
|
||||||
|
bestehenden SSH-Bootstrapzugang aus dem expliziten Hauptrepo-Accessroot. Der
|
||||||
|
15-KiB-Body wird als gehashte `MidlCodegen.ps1` übertragen und regulär mit
|
||||||
|
prozessbezogenem `RemoteSigned` als Datei aufgerufen; kein großer
|
||||||
|
EncodedCommand und kein ScriptBlock-Dateiausführungsersatz.
|
||||||
|
|
||||||
|
Vor Start prüft der Runner gültiges Microsoft-Authenticode, die Onlinekette,
|
||||||
|
Hash, Länge und die tatsächliche feste Tool-Dateiversion `8.1.628.1`. Die
|
||||||
|
zugehörigen lokalen PE-Zertifikatsmetadaten wurden lediglich gelesen; das ist
|
||||||
|
noch keine Authenticodeprüfung. Ein vor `CreateProcessW` installierter
|
||||||
|
`PROC_THREAD_ATTRIBUTE_JOB_LIST` ordnet den MIDL-Prozess samt seinen eigenen
|
||||||
|
Nachkommen atomar einem unbenannten Kill-on-close-Job zu; höchstens zwei
|
||||||
|
Prozesse, ausschließlich drei Standardhandles geerbt, kein später
|
||||||
|
Assign-Fallback. Nach zehn Sekunden oder überschrittenem Outputlimit wird nur
|
||||||
|
dieser eigene Job beendet, höchstens insgesamt zwei weitere Sekunden beobachtet
|
||||||
|
und dann geschlossen. Auch die Pfade für Header und Clientstub sind fest,
|
||||||
|
jeweils höchstens 256 KiB. Kein globales Compiler-/Installer-Kill.
|
||||||
|
|
||||||
|
Lokale Qualification:
|
||||||
|
`devstate/windows-clock-midl/6b7fb9b1-0bb7-4880-850b-e6812d3df1b1/runner-final-qualification/qualification.json`,
|
||||||
|
SHA-256 `dab36fbab3e407cbae6d97f27068abe8f57cc13243b94b4fd95fe9108dc7a508`.
|
||||||
|
Python-Syntax, drei PowerShell-ASTs ohne Fehler und reine C#-Deklarationskompilierung
|
||||||
|
bestanden; keine Win32-Funktion aufgerufen, keine Zielverbindung.
|
||||||
|
Runner-SHA-256:
|
||||||
|
`078bf2303979dbeccdb7eb84e116325e7f155146d93d0dc0fff6b3e6bdd1b2eb`.
|
||||||
@@ -0,0 +1,237 @@
|
|||||||
|
# Getrennter Diagnosebuild mit tatsächlichem Microsoft-MIDL-Output
|
||||||
|
|
||||||
|
Stand 2026-11-14. Eigene Buildquelle; keine Änderung des Produktbuilders,
|
||||||
|
der bisherigen Runner oder früherer Binär-/Abnahmebelege. Kein VM-Zugriff,
|
||||||
|
kein RMM-Job und keine Clockqualifikation durch diesen lokalen Build.
|
||||||
|
|
||||||
|
## Tatsächliche Eingangsdaten
|
||||||
|
|
||||||
|
Root hat MIDL auf der Windows-VM im eigenen Fall
|
||||||
|
`149bafe2-3469-4580-b133-988812bcc3db` ausgeführt und anschließend denselben
|
||||||
|
Fall separat nur gelesen. Der neue lokale Builder prüft dessen vollständigen
|
||||||
|
Readback gegen SHA256
|
||||||
|
`0dc2373825f7f8f224cda04ecd5c521dd3c37a6e712bc3ed83bc4fa6d0d89c8c`.
|
||||||
|
Der Beleg enthält erfolgreiche Microsoft-Authenticode-/Kettenprüfung der
|
||||||
|
festen Tools, Codegenexit0 und das Ende aller eigenen Prozesse. Es fand kein
|
||||||
|
RPC-Aufruf statt; `clock_qualified=false` bleibt ausdrücklich erhalten.
|
||||||
|
|
||||||
|
Die zwei zurückgelesenen tatsächlichen Outputs werden unverändert als neue
|
||||||
|
Buildinputs kopiert und sowohl gegen die Originalbytes im Readback als auch
|
||||||
|
gegen feste Hashes geprüft:
|
||||||
|
|
||||||
|
| Datei | Bytes | SHA256 |
|
||||||
|
|---|---:|---|
|
||||||
|
| `w32time.h` | 3779 | `db5dbe5b335eaa58a6512d4abfda44e7273f3aa8a43077dcb0719e4b97ee2bde` |
|
||||||
|
| `w32time_c.c` | 18866 | `d806adb431f16724c8afdea0c0751588a4bc6f82b6f0b8391d4d189d6a6f4a38` |
|
||||||
|
|
||||||
|
`deploy/windows/clock_midl_diagnostic_build.py` erstellt pro lokalem Aufruf einen
|
||||||
|
neuen privaten Fall unter `devstate/windows-clock-midl/diagnostic-builds/`.
|
||||||
|
Er kopiert einen gehashten Quellsnapshot und verwendet ausschließlich diesen
|
||||||
|
Snapshot. Das separate Cargo-Paket unter
|
||||||
|
`deploy/windows/clock-midl-diagnostic/` bindet das vorhandene originale
|
||||||
|
`examples/clock_readiness.rs` und dessen originales `src/clock.rs` ein. C-Wrapper,
|
||||||
|
Endpointcode und Narrow-IDL sind ebenfalls unverändert und im neuen build.rs
|
||||||
|
zusätzlich fest gepinnt. `ADAPTER_QUALIFIED=false`, Authentisierung, Statusguard,
|
||||||
|
SEH- und Allocatorgrenzen werden nicht verändert.
|
||||||
|
|
||||||
|
Es wird weder ein Compilerwrapper anstelle von WIDL ausgegeben noch ein
|
||||||
|
bestehendes OUT_DIR nachträglich verändert. Das neue build.rs kompiliert die
|
||||||
|
zuvor geprüften Originaloutputs direkt, ohne Generatorfallback oder NDR-Patch.
|
||||||
|
Der vorhandene Produktpfad `crates/agent-windows/build.rs` bleibt unverändert.
|
||||||
|
Der Lockfileabgleich erlaubt keine neue externe Paketversion gegenüber dem
|
||||||
|
ursprünglichen Root-Lockfile. Alle nachfolgenden Cargobefehle verwenden
|
||||||
|
`--locked --offline`; Docker läuft ohne Netzwerk und mit read-only Rootfilesystem.
|
||||||
|
|
||||||
|
## Tatsächliche Compiler-/Linkerbefunde
|
||||||
|
|
||||||
|
Die Microsoft-Quelldatei schützt ihren AMD64-Code mit `_M_AMD64`; Clang/GNU
|
||||||
|
definiert diesen Makronamen nicht selbst. Nur im getrennten tatsächlichen
|
||||||
|
x64-Build wird deshalb `_M_AMD64=100` gesetzt. Weder `_MSC_VER` noch
|
||||||
|
`__RPCNDR_H_VERSION__` werden definiert oder erhöht. Der echte MinGW-Header
|
||||||
|
meldet475; der originale Microsoft-Header verlangt475.
|
||||||
|
|
||||||
|
Der unveränderte Microsoftstub enthält legale C-Klammerelision an einem
|
||||||
|
Unioninitializer sowie zwei unbenutzte konstante Tabellen. Der erste strikte
|
||||||
|
Versuch scheiterte an `-Wmissing-braces`; der zweite bewahrte zusätzlich die
|
||||||
|
konkreten `-Wunused-const-variable`-Befunde. Nur die exakt gepinnte generierte
|
||||||
|
Stubunit erhält `-Wno-error=missing-braces` und
|
||||||
|
`-Wno-error=unused-const-variable`: Die drei Warnungen bleiben im Log sichtbar,
|
||||||
|
alle übrigen Diagnosen bleiben Fehler. Die beiden unveränderten C-Wrapper
|
||||||
|
werden getrennt weiterhin mit `-Wall -Wextra -Werror` kompiliert. Kein
|
||||||
|
Typfehler, Strukturassert oder Sicherheitscheck wird abgeschaltet.
|
||||||
|
|
||||||
|
Das isolierte kleine Rustpaket benötigt außerdem `mincore` zum Linken der
|
||||||
|
beiden unveränderten präzisen Interruptzeitgetter. Das vorhandene
|
||||||
|
MinGW-Kernel32-Importarchiv kennt sie nicht; `libmincore.a` enthält die
|
||||||
|
Windows-Realtime-API-Imports. Bereits die vorherige Readiness-EXE91889303…
|
||||||
|
importierte beide Getter über `api-ms-win-core-realtime-l1-1-1.dll`.
|
||||||
|
Es gibt keinen Ersatzgetter, keine Zeitberechnung aus Serverzeit und keinen
|
||||||
|
Runtimefallback. Die neuen PE-Imports werden separat erhalten.
|
||||||
|
Der tatsächlich erfolgreiche neue Link wählt für diese beiden Getter
|
||||||
|
`api-ms-win-core-realtime-l1-1-2.dll`, der frühere918…-Link dagegen
|
||||||
|
`api-ms-win-core-realtime-l1-1-1.dll`. Das ist eine zusätzliche tatsächliche
|
||||||
|
Linkdifferenz, kein reiner Einvariablenvergleich ausschließlich des Generators.
|
||||||
|
Ihre native Zulässigkeit wird hier nicht behauptet.
|
||||||
|
|
||||||
|
Die unvollständigen Fälle `4ce00b43-4ca1-4e50-9f65-e89bd82f9364`,
|
||||||
|
`81b5503a-d78f-49be-b323-380c254cedff` und
|
||||||
|
`81d93ea1-f886-4853-8db4-f4e1c95f33ea` bleiben samt Eingängen und Logs erhalten.
|
||||||
|
Der letzte enthält bereits erfolgreiche Windows-Clippy- und fünf tatsächliche
|
||||||
|
Linux-Clocktests, aber einen fehlgeschlagenen Windows-Testlink. Diese Fälle
|
||||||
|
sind keine erfolgreichen vollständigen Diagnosebuilds.
|
||||||
|
|
||||||
|
## Ausführung und Nachweisgrenzen
|
||||||
|
|
||||||
|
Lokaler Buildbefehl, keine VM-Aktion:
|
||||||
|
|
||||||
|
```text
|
||||||
|
python3 deploy/windows/clock_midl_diagnostic_build.py
|
||||||
|
```
|
||||||
|
|
||||||
|
Jeder Fall erhält Intent, genaue Compiler-/Lock-/Quellhashes und einzelne
|
||||||
|
Checklogs. Nur nach erfolgreichen fünf tatsächlichen Clocktests, Windows-
|
||||||
|
Clippy/-Testlink und Release-Link wird eine finale Qualifikation geschrieben.
|
||||||
|
Original-Linkdatei und separat gestrippte `WindowsClockReadiness.exe` bleiben
|
||||||
|
beide erhalten. Ein Windows-Crosslink ist kein nativer Windows-Lauf.
|
||||||
|
|
||||||
|
Vollständiger tatsächlich erfolgreicher Fall:
|
||||||
|
`181c3a1c-8324-41fd-9b7c-aa8010262912`.131Compilerinputs vor/nach identisch;
|
||||||
|
Fmt, Windows-Alltargets-Clippy mit Rust-Warnungen als Fehler, alle fünf
|
||||||
|
Linux-Clocktests ohne Skip, Windows-Unitlink, Release-Link und PE-Importausgabe
|
||||||
|
bestanden. Die sichtbaren drei C-Stilwarnungen gelten ausschließlich für die
|
||||||
|
oben beschriebene gepinnte Microsoftstubunit.
|
||||||
|
|
||||||
|
- Finale EXE:1217536Bytes, SHA256
|
||||||
|
`b1d3da4f393ddf20bc8e48a9894ee314666f2ac3613ef97f5c228e3d089ca560`.
|
||||||
|
- Original-Linkdatei SHA256:
|
||||||
|
`5efcbbbdfe9c9d8b5954e4d550ba8f35fbaf1bcffefa610bd25b0c3797340d1c`.
|
||||||
|
- Finale `qualification.json` SHA256:
|
||||||
|
`2e0de3acf72ab5c3a8e0baa54e8643d086ea7c03d1b38fd89b6bfc00e45f8cbb`.
|
||||||
|
|
||||||
|
Python-Syntaxprüfung des neuen Builders wurde ebenfalls tatsächlich ausgeführt.
|
||||||
|
Das ist lokale Crossbuild-/Vertragsqualifikation, kein Cloud-Linux- oder
|
||||||
|
Windows-VM-Nachweis und kein bestätigter Fix für die bisherige RPC1783-Ausnahme.
|
||||||
|
|
||||||
|
Eine spätere tatsächliche Ausführung bleibt eine eigene Root-geführte
|
||||||
|
Diagnose mit konkretem Binaryhash und dem bestehenden Readinessrunner.
|
||||||
|
Selbst ein erfolgreicher Statusreturn würde weder die Named-Pipe-Serveridentität
|
||||||
|
noch Clockauthority oder den SYSTEM-/Jobpfad qualifizieren. Keine automatische
|
||||||
|
Wiederholung früherer RPC-Aufrufe und keine Genehmigungsabkürzung.
|
||||||
|
|
||||||
|
## Ursprüngliche Vorbereitung der portablen Linux-Vorstufe
|
||||||
|
|
||||||
|
`deploy/windows/clock_midl_linux_native.py prepare-local` wurde tatsächlich
|
||||||
|
lokal ausgeführt. Es kopiert ausschließlich die bereits im erfolgreichen
|
||||||
|
Build181c… ausgeführte Linux-Testexe; kein neuer Build und kein Strip.
|
||||||
|
Der separate Packfall lautet `f5d85873-96b2-41d5-97be-4c8f5c6baaef`, unter
|
||||||
|
`devstate/windows-clock-midl/linux-native-packs/`. Finale Manifest-SHA256:
|
||||||
|
`dcd6351898a1893253b352dce144d52dd45cd71aa1453295e648aa9d41afa67c`.
|
||||||
|
|
||||||
|
Die tatsächlichen unveränderten26577504Bytes besitzen SHA256
|
||||||
|
`6b3153d0d781798454f483c1c5b58089dcd2fe98b03c43aea3d928fd6107a9c8`.
|
||||||
|
ELF-Metadaten: x86-64, Interpreter `/lib64/ld-linux-x86-64.so.2`, höchste
|
||||||
|
benötigte Version `GLIBC_2.34`, direkte Abhängigkeiten `libc.so.6`,
|
||||||
|
`ld-linux-x86-64.so.2`, `libgcc_s.so.1`. Containerseitiges reines Listing
|
||||||
|
derselben Bytes bestätigt genau diese fünf bereits bestehenden Tests:
|
||||||
|
|
||||||
|
```text
|
||||||
|
clock::tests::gate_requires_all_status_and_uncertainty_evidence
|
||||||
|
clock::tests::production_clock_stays_closed_until_native_adapter_qualification
|
||||||
|
clock::tests::suspend_closes_until_actual_post_resume_sync
|
||||||
|
clock::tests::timeout_worker_stays_closed_without_a_second_call
|
||||||
|
clock::tests::wall_step_and_overflow_fail_closed
|
||||||
|
```
|
||||||
|
|
||||||
|
Der neue Runner besitzt die getrennten Aktionen `native` und `readback`.
|
||||||
|
Nur Root führt `native --execute-native-tests --access-root <Hauptrepo>
|
||||||
|
--manifest <dieser lokale Manifestpfad>` aus. Der bestehende strikte
|
||||||
|
SSH-/Credentialparser wird ausschließlich dann aufgerufen. Der Zielpfad
|
||||||
|
`/var/lib/rmm-clock-midl-portable-tests/<neue UUID>` ist privat und create-only.
|
||||||
|
Originalintent, Startmarker vor dem ersten Prozess und finales Ergebnis werden
|
||||||
|
dauerhaft gespeichert. Verlorene Antwort erlaubt nur `readback --case <dieselbe
|
||||||
|
UUID>`; kein zweiter Start. Ausschließlich die fünf hart codierten Tests dürfen
|
||||||
|
laufen, mit eigener Netzwerknamespace, bereinigter Umgebung, fünf Sekunden
|
||||||
|
je Test, zwanzig Sekunden Gesamtbudget und begrenzter Ausgabe. ELF-Loaderprüfung
|
||||||
|
erfolgt zusätzlich auf dem tatsächlichen Linuxziel. Keine bestehenden Dienste,
|
||||||
|
Jobs, Journale, Policies, Schlüssel oder Zeitdienstkonfiguration werden benutzt.
|
||||||
|
|
||||||
|
Python-Syntax und lokales ELF-/Listpaket sind geprüft. **Der Autor dieses
|
||||||
|
Quellschnitts hat keine VM-Verbindung oder native Testausführung vorgenommen.**
|
||||||
|
Ein späterer Linux5/5-Beleg betrifft ausschließlich portable Clockguards,
|
||||||
|
keine Linux-NDR-Prüfung und keinerlei Windows-RPC-/Serveridentitäts- oder
|
||||||
|
Clockauthority-Nachweis. Root führt Windowsdiagnostik getrennt danach aus.
|
||||||
|
|
||||||
|
### Readbackkorrektur vor der ersten nativen Ausführung
|
||||||
|
|
||||||
|
Root-Review fand im zuvor vorbereiteten Linuxrunner einen konkreten Fehler:
|
||||||
|
Auch `read` hätte bei fehlender Zielwurzel ein Verzeichnis angelegt. Die
|
||||||
|
Korrektur beschränkt diese einzige Wurzelanlage auf `prepare`; `read` und
|
||||||
|
`run` verweigern eine fehlende Wurzel ausschließlich lesend. Der äußere
|
||||||
|
Readbackzweig ruft nur `action=read` auf, ohne Prepare, Upload oder Teststart.
|
||||||
|
Das ursprüngliche Pack f5d85873… bleibt erhalten, ist durch seinen alten
|
||||||
|
Runnerhash aber für den korrigierten Runner nicht mehr verwendbar.
|
||||||
|
|
||||||
|
Der neue Packfall **68c5b69c-3391-4ff9-943d-3e5955be4e1f** enthält dieselben
|
||||||
|
unveränderten Testexebytes und dieselbe ursprüngliche Buildqualifikation.
|
||||||
|
Neues `manifest.json` SHA256:
|
||||||
|
`eceec2cc3f778cc46d58d1c10679fc38e5fcc7c7bee6eac99ef9454162f7ce48`.
|
||||||
|
Runner-SHA256:
|
||||||
|
`27a6a62e24a3908765bfe3c94d5ae75022210ebc6ab35ffc7f659bfe45844956`.
|
||||||
|
Die tatsächliche `native_case`-Teilquelle ist zusätzlich separat mit SHA256
|
||||||
|
`ab7cd86e03684a6e7167d0c6814bc71edb39046e07b5794cfb0d6f195e2b6828`
|
||||||
|
gebunden. Manifest und spätere Originalintents binden außerdem die drei
|
||||||
|
Supportquellen `remote_client_bootstrap.py`, `vm_mvp_acceptance.py` und
|
||||||
|
`vm_access_check.py`. Jeder Native-/Readbackaufruf prüft diese Bindungen vor
|
||||||
|
dem ersten SSH-Aufruf; Sourceänderung verweigert den Zugriff.
|
||||||
|
|
||||||
|
Tatsächlich lokal mit gemockten Ziel-/Transportobjekten geprüft: `read` bei
|
||||||
|
fehlender Wurzel ohne mkdir/open/Prozessstart; gleiches für `run`; äußerer
|
||||||
|
Readback genau ein Read-RPC ohne mkdir/SFTP/Testlauf; geänderte Supporthashes
|
||||||
|
vor RPC verweigert. Vier Guards bestanden, kein realer Zielzugriff. Beleg:
|
||||||
|
`readback-guards.json` im neuen Pack, SHA256
|
||||||
|
`4db073802235d86b5233255a5fbf42be87808307abe32f47c4f6bb059ae8de31`.
|
||||||
|
Python-Syntax und erneutes reines ELF-/Testlisting bestanden. Alle ursprünglichen
|
||||||
|
131 Windowsbuildinputs wurden erneut gegen181c… verglichen und sind exakt
|
||||||
|
unverändert. Kein neuer Build, kein Strip und keine native Ausführung.
|
||||||
|
|
||||||
|
## Danach tatsächlich: Cloud-Linux5 und Windowsdiagnose
|
||||||
|
|
||||||
|
Root führte den korrigierten Pack68c5b69c nativ auf der Cloud-Linux-Test-VM
|
||||||
|
aus. Fall `222a0d60-4ddb-41c3-961c-2fa04138db28`: alle fünf festen portablen
|
||||||
|
Clocktests bestanden, jeder als exakter eigener Fall, keine ignorierten Fälle.
|
||||||
|
Originalbytes/Loader, Netzwerknamespace, begrenzte Ausgabe und feste Budgets
|
||||||
|
geprüft. `passed.json`-SHA256:
|
||||||
|
`b045ddccba9fff80ecba3b81649e14330b58f79b04990b5b257b1d6a3df39d3e`.
|
||||||
|
Keine Linux-NDR- oder Windows-RPC-Prüfung aus diesem Erfolg ableiten.
|
||||||
|
|
||||||
|
Erst danach wurde Windows-EXEb1d3da4f im neuen eigenen LocalService-
|
||||||
|
Diagnosefall `94562d81-f75f-45c8-ab6b-28b70d12bd81` einmal ausgeführt.
|
||||||
|
Der bestehende Readinessrunner blieb unverändert; anschließend wurde derselbe
|
||||||
|
Originalbericht separat nur lesend identisch bestätigt. Der eigene temporäre
|
||||||
|
Dienst wurde entfernt. ResultatSHA256:
|
||||||
|
`91176b2c6832573786de9a8a15f9f239a0f93d7b0d5fef5eb36ac39f992b9232`.
|
||||||
|
|
||||||
|
Tatsächliches Token: SID19/LocalService, kein Administrator und kein SYSTEM.
|
||||||
|
Beide ALPC-Versuche sowie deren falsche Account-/Servicekontrollen liefern
|
||||||
|
weiter1753 ohne Status; damit ist keine Identitätsverweigerung bewiesen.
|
||||||
|
Die getrennte Named-Pipe-Diagnose liefert jetzt **RPC5/AccessDenied** statt
|
||||||
|
des früheren1783. Trace: Stage90, `rpc_exception=5`, kein normaler nativer
|
||||||
|
Return und kein Status. Dies ist eine neue konkrete Fehlerbeobachtung,
|
||||||
|
**keine erfolgreiche W32Time-Abfrage** und kein isolierter Ursachennachweis;
|
||||||
|
die dokumentierte APIset-Linkdifferenz bleibt Bestandteil dieses Kandidaten.
|
||||||
|
|
||||||
|
Ein separater Vorher-/Nachherabgleich des tatsächlich laufenden Agent-/
|
||||||
|
Helperpaars prüfte PIDs/Geburt, Dateien/PKI/DB-/Lock-Datei-IDs, Helperwitness und
|
||||||
|
geschlossene Serverzähler/Flags unverändert. NachherbelegSHA256:
|
||||||
|
`09493104ca46b53b235df677f70289ef48bbfd718c8f5c82790921986db27bc8`.
|
||||||
|
Keine W32Time-ACL-/Konto-/NTP-Änderung, kein Agentwechsel oder RMM-Job.
|
||||||
|
|
||||||
|
Microsoft dokumentiert für LocalService anonyme Netzwerkanmeldedaten und für
|
||||||
|
MS-W32T den authentisierten Named-Pipe-Endpunkt W32TIME_ALT.
|
||||||
|
[LocalService](https://learn.microsoft.com/en-us/windows/win32/services/localservice-account),
|
||||||
|
[MS-W32T-Transport](https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-w32t/e0803f6b-e175-4b87-ba63-bbcf51175655).
|
||||||
|
Ein Token-/Authentisierungseinfluss ist damit eine begründete **Hypothese**,
|
||||||
|
keine bewiesene Ursache des konkreten5. Als nächster enger Diagnoseschritt wird
|
||||||
|
ein eigener lesender SYSTEM-Vergleich mit unveränderten C-/Auth-/MIDLinputs
|
||||||
|
vorbereitet; kein Lockern der bestehenden LocalService-Prüfung oder
|
||||||
|
Zeitdienstrechte. Produktgate/Clock/Jobs bleiben geschlossen.
|
||||||
@@ -0,0 +1,92 @@
|
|||||||
|
# Clock: nächste Diagnosegrenzen, noch keine Implementierungsfreigabe
|
||||||
|
|
||||||
|
Historische Planungsnotiz vor der nativen MIDL-/EEInfo-Probe; deren tatsächliche
|
||||||
|
Ergebnisse stehen in [EEInfo-Diagnose](windows-clock-eeinfo-trace.md). Die hier
|
||||||
|
beschriebenen weiteren V5-Vergleiche wurden nicht ausgeführt.
|
||||||
|
|
||||||
|
Stand 2026-11-14. Diese Notiz ändert weder den eingefrorenen MIDL-Runner
|
||||||
|
`078bf230…` noch Clock-/RPC-Produktquellen. Keine Zielverbindung ausgeführt.
|
||||||
|
|
||||||
|
## MIDL-Signatur: tatsächlich statisch gelesene öffentliche Metadaten
|
||||||
|
|
||||||
|
Die gehashten NuGet-PE-Dateien `midl.exe` und `midlc.exe` enthalten denselben
|
||||||
|
Microsoft-Corporation-Code-Signing-Leaf, SHA-256
|
||||||
|
`0ba22e4765f7a160178ec90535c37f024916fbce0d9da63118d69662b5fed7eb`.
|
||||||
|
Sein Gültigkeitsintervall ist **2026-03-05 19:58:26 UTC bis
|
||||||
|
2027-03-03 19:58:26 UTC**, einschließlich Code-Signing-EKU. Das enthaltene
|
||||||
|
Zwischenzertifikat Microsoft Windows Code Signing PCA 2024 ist von
|
||||||
|
2024-08-08 bis 2035-06-23 datiert. Damit widerspricht eine Prüfung zum
|
||||||
|
14.11.2026 diesen eingebetteten Zeitintervallen nicht.
|
||||||
|
|
||||||
|
Der private Beleg `public-certificate-time-metadata.json` im MIDL-Downloadfall
|
||||||
|
`6b7fb9b1-0bb7-4880-850b-e6812d3df1b1` enthält die exakten Toolhashes und beide
|
||||||
|
öffentlichen Zertifikatsbags. Dies ist **kein** Nachweis von PE-Signatur,
|
||||||
|
Signerauswahl, Zertifikatskette, Widerruf oder vertrauenswürdigem Zeitstempel.
|
||||||
|
Die Ziel-Vertrauensspeicher und Online-Widerrufsprüfung bleiben ungeprüft.
|
||||||
|
|
||||||
|
Die zusätzliche `X509Chain.Build(SignerCertificate)`-Prüfung benutzt ohne
|
||||||
|
explizite VerificationTime das aktuelle Datum; die
|
||||||
|
[Microsoft-.NET-Framework-Quelle](https://github.com/microsoft/referencesource/blob/main/System/security/system/security/cryptography/x509/x509chainpolicy.cs)
|
||||||
|
setzt beim Reset `DateTime.Now`. Eine Dateisignatur mit gültigem vertrauenswürdigem
|
||||||
|
Timestamp kann dagegen auch nach Ablauf des Signierzertifikats zulässig bleiben,
|
||||||
|
wie Microsoft für [Authenticode-Zeitstempel](https://learn.microsoft.com/en-us/windows/win32/seccrypto/time-stamping-authenticode-signatures)
|
||||||
|
beschreibt. Eine separate heutige Blattkettenprüfung ist deshalb kein allgemeiner
|
||||||
|
Ersatz für die vollständige Dateisignatur-/Timestamp-Policy.
|
||||||
|
|
||||||
|
Für die **jetzt fest gepinnten** Tools besteht nach den gelesenen Metadaten kein
|
||||||
|
solcher Ablaufkonflikt. Der Runner bleibt unverändert streng. Scheitert die
|
||||||
|
native Prüfung, muss der genaue Grund erhalten werden; kein IgnoreNotTimeValid,
|
||||||
|
kein abgeschalteter Widerruf und kein neu importierter Trustanker als Abkürzung.
|
||||||
|
Soll später ein anderer, abgelaufener, aber timestamp-signierter Input nötig
|
||||||
|
werden, verlangt das einen eigenen geprüften Verifiervertrag: vollständige
|
||||||
|
[Authenticode-Dateipolicy](https://learn.microsoft.com/en-us/windows/win32/api/wintrust/nf-wintrust-winverifytrust),
|
||||||
|
Dateidigest, erlaubter Signer und belegte Timestamp-/Kettenprüfung statt eines
|
||||||
|
frei gesetzten historischen Prüfdatenwerts.
|
||||||
|
|
||||||
|
## Geplanter enger Named-Pipe-V5-Diagnosevergleich
|
||||||
|
|
||||||
|
Voraussetzung ist zuerst ein **tatsächlich zurückgelesener** MIDL-Header/-Stub
|
||||||
|
und ein nativer Opnum-6-Statusbeleg. Ein weiterer gleicher NDR-Fehler 1783 ist
|
||||||
|
kein Identitätsnachweis und darf nicht als negatives Sicherheitskontrollergebnis
|
||||||
|
gezählt werden. Produktive Clockbereitschaft bleibt unabhängig davon false.
|
||||||
|
|
||||||
|
Die [RPC-V5-Dokumentation](https://learn.microsoft.com/en-us/windows/win32/api/rpcdce/ns-rpcdce-rpc_security_qos_v5_w)
|
||||||
|
beschreibt `ServerSecurityDescriptor` zur Serveridentifikation und warnt, dass
|
||||||
|
NTLM trotz fehlender gegenseitiger Authentifizierung erfolgreiche
|
||||||
|
MUTUAL_AUTH-Verhandlung melden kann. `Sid` ist insbesondere für `ncalrpc`
|
||||||
|
beschrieben; die Wirkung der gewählten Kombination auf `ncacn_np` ist noch
|
||||||
|
nativ nachzuweisen. Ein gesetztes Flag oder erfolgreiche SetAuthInfo-Rückgabe
|
||||||
|
qualifiziert diese Kombination nicht.
|
||||||
|
|
||||||
|
Kleinster **noch nicht implementierter** Vergleich, getrennt vom bisherigen
|
||||||
|
Named-Pipe-/ALPC-Pfad:
|
||||||
|
|
||||||
|
1. Exakter lokaler authentifizierter Endpunkt `\\pipe\\W32TIME_ALT`, Interface
|
||||||
|
4.1/Opnum 6, bestehender C-SEH-/Allocator-/Statusvertrag und PacketPrivacy.
|
||||||
|
Kein Remotehost, alternativer Endpunkt oder automatischer Fallback.
|
||||||
|
2. V5 mit festem erwarteten LocalService-SID und lokal konstruiertem Descriptor,
|
||||||
|
dessen einzige Allow-ACE den echten `NT SERVICE\W32Time`-SID bezeichnet.
|
||||||
|
Account und Service-SID kommen niemals aus der Endpointantwort. Descriptor,
|
||||||
|
ACL und beide SIDs leben bis nach dem vollständigen RPC-Aufruf.
|
||||||
|
3. Derselbe Statusaufruf mit ausschließlich falschem erwartetem Account
|
||||||
|
(LocalSystem statt LocalService), korrektem W32Time-Descriptor.
|
||||||
|
4. Derselbe Statusaufruf mit korrektem Account, aber ausschließlich falschem
|
||||||
|
Service-SID (`RmmDiscoveryWindows` statt W32Time). Damit wird die Trennung
|
||||||
|
gegenüber dem ebenfalls als LocalService laufenden Network-Agent getestet.
|
||||||
|
|
||||||
|
Erforderlich wären echter positiver Return mit validem Status **und** zwei
|
||||||
|
nachvollziehbare Identitätsverweigerungen ohne gelieferten Status, unter
|
||||||
|
identischem frischem Dienst-/Boot-/Binarykontext. Timeout, fehlender Endpunkt,
|
||||||
|
ungültiger Stub oder derselbe 1783-Fehler auf allen Varianten sind unzureichend.
|
||||||
|
Eine akzeptierte falsche Identität falsifiziert den Kandidaten; keine Abschwächung
|
||||||
|
auf Account-only. Der tatsächlich aktivierte W32Time-Service-SID und die feste
|
||||||
|
Dienstkonfiguration müssen zuvor rein lesend belegt sein. Fehlende SID-Isolation
|
||||||
|
darf nicht durch eine Service-/Token-/ACL-Änderung für die Diagnose repariert
|
||||||
|
werden.
|
||||||
|
|
||||||
|
Die spätere Probe benötigt einen einzelnen begrenzten Diagnoseworker, feste
|
||||||
|
Varianten und numerische Stage-/Return-/Status-Presencefelder. Kein freier
|
||||||
|
SID-/Endpunktparameter, kein Ersatzthread nach hängendem Call und kein Retry
|
||||||
|
mit schwächerer Authentisierung. Erst diese technischen Diagnosen wären eine
|
||||||
|
Grundlage für eine separate Clockvertrauensentscheidung; sie öffnen weder
|
||||||
|
`ADAPTER_QUALIFIED` noch Jobcapabilities oder den SYSTEM-Helperpfad.
|
||||||
@@ -0,0 +1,240 @@
|
|||||||
|
# Plan: einmaliger Clockvergleich mit vorhandenem Prozessprivileg
|
||||||
|
|
||||||
|
Ursprünglicher Plan 2026-11-14, vor Implementierung verfasst; die inzwischen erfolgte lokale Umsetzung steht im letzten Abschnitt.
|
||||||
|
**Keine Implementierung, kein Build und keine Zielaktion für diesen Nachfolger.**
|
||||||
|
Die Freigabe der konkreten Tokenabgrenzung und des Diagnoseumfangs liegt beim
|
||||||
|
Hauptagenten. Alle bisherigen Empty-, F6-, SYSTEM-, EEInfo- und Produktquellen
|
||||||
|
sowie deren Casebelege bleiben unverändert.
|
||||||
|
|
||||||
|
## Ausgangspunkt und begrenzte Fragestellung
|
||||||
|
|
||||||
|
Der Hauptagent meldet aus dem tatsächlichen Empty-Case
|
||||||
|
`5e0e8ce9-b9a3-4c4a-b739-3f84d714dc94`: eine Statusquery, RPC5/Stage90,
|
||||||
|
ein numerischer EEInfo-Record; vorhandenes SeSystemtimePrivilege mit
|
||||||
|
Attributen0/Enabled0. Dieser Plan ergänzt keinen abgeschlossenen
|
||||||
|
Readback-/Cleanup-/Preservationnachweis und leitet daraus keine Fehlerursache ab.
|
||||||
|
|
||||||
|
Der nächste Vergleich soll ausschließlich prüfen, ob sich das Ergebnis eines
|
||||||
|
einzelnen lesenden Opnum6 ändert, wenn genau das bereits vorhandene
|
||||||
|
SeSystemtimePrivilege des getrennten Diagnoseprozesses vorübergehend aktiviert
|
||||||
|
ist. Es werden keine Kontorechte zugewiesen. Auch ein erfolgreicher Vergleich
|
||||||
|
wäre weder Produktionsfreigabe noch ausreichende Clock-/Serveridentitätsprüfung.
|
||||||
|
|
||||||
|
## Geprüfte Microsoft-Verträge
|
||||||
|
|
||||||
|
AdjustTokenPrivileges wirkt auf das übergebene Tokenobjekt. Es benötigt
|
||||||
|
TOKEN_ADJUST_PRIVILEGES, mit PreviousState zusätzlich TOKEN_QUERY. TRUE allein
|
||||||
|
bedeutet nicht, dass alle angeforderten Rechte angepasst wurden:
|
||||||
|
GetLastError ist unmittelbar auszuwerten; ERROR_NOT_ALL_ASSIGNED verweigert den
|
||||||
|
Diagnoseaufruf. Vorhandene Rechte können aktiviert werden, neue werden nicht
|
||||||
|
hinzugefügt. PreviousState enthält die tatsächlich geänderten ursprünglichen
|
||||||
|
Zustände und dient als NewState einer Wiederherstellung. Ein zu kleiner
|
||||||
|
PreviousState-Puffer führt ohne Anpassung zum Fehler.
|
||||||
|
[AdjustTokenPrivileges](https://learn.microsoft.com/en-us/windows/win32/api/securitybaseapi/nf-securitybaseapi-adjusttokenprivileges)
|
||||||
|
|
||||||
|
OpenProcessToken öffnet das einem Prozess zugeordnete Token. Dieser Aufruf ist
|
||||||
|
kein eigenständiger Vertrag über die Exklusivität aller Referenzen auf dieses
|
||||||
|
Tokenobjekt.
|
||||||
|
[OpenProcessToken](https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-openprocesstoken)
|
||||||
|
|
||||||
|
TokenStatistics.TokenId identifiziert die konkrete Tokenobjektinstanz.
|
||||||
|
AuthenticationId identifiziert eine Anmeldesitzung, zu der viele Tokens gehören
|
||||||
|
können. ModifiedId ändert sich bei Tokenänderung. Deshalb weder gleiche
|
||||||
|
AuthenticationId als Tokenidentität noch gleiche ModifiedId nach Wiederherstellung
|
||||||
|
fordern; die ursprüngliche ModifiedId lässt sich nicht durch Zurücksetzen der
|
||||||
|
Privilegattribute wiederherstellen.
|
||||||
|
[TOKEN_STATISTICS](https://learn.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-token_statistics)
|
||||||
|
|
||||||
|
Jeder Prozess hat ein Primärtoken; ein impersonierender Thread kann zusätzlich
|
||||||
|
ein Threadtoken besitzen. Der Vergleich soll weiterhin ohne Impersonation und
|
||||||
|
ohne Tokenwechsel laufen.
|
||||||
|
[Access Tokens](https://learn.microsoft.com/en-us/windows/win32/secauthz/access-tokens)
|
||||||
|
|
||||||
|
LocalSystem-Dienste erben den Sicherheitskontext des SCM. Diese Aussage und
|
||||||
|
derselbe SYSTEM-SID belegen für sich allein keine verschiedenen TokenIds.
|
||||||
|
SeSystemtimePrivilege ist in Microsofts LocalSystem-Beschreibung standardmäßig
|
||||||
|
deaktiviert; das erklärt nicht allein den konkreten RPC5.
|
||||||
|
[LocalSystem Account](https://learn.microsoft.com/en-us/windows/win32/services/localsystem-account)
|
||||||
|
|
||||||
|
SERVICE_WIN32_OWN_PROCESS belegt einen eigenen Prozess, nicht durch seine bloße
|
||||||
|
Bezeichnung eine geprüfte Trennung sämtlicher Tokenreferenzen.
|
||||||
|
[CreateServiceW](https://learn.microsoft.com/en-us/windows/win32/api/winsvc/nf-winsvc-createservicew)
|
||||||
|
|
||||||
|
## Noch vom Hauptagenten zu entscheidende Beweisgrenze
|
||||||
|
|
||||||
|
Vorgeschlagener enger Gate: Vor jeder Anpassung rein lesend TokenId und
|
||||||
|
TokenStatistics des Diagnoseprozesses, des SCM-Prozesses und der aktuell an
|
||||||
|
W32Time, RMM-Agent und RMM-Helper gebundenen Prozesse erfassen. Prozesshandles
|
||||||
|
und Startzeiten binden die Ablesung gegen PID-Wiederverwendung; Dienst-PID und
|
||||||
|
Prozessbindung direkt danach erneut prüfen. Nur TOKEN_QUERY gegenüber fremden
|
||||||
|
Tokens; kein SE_DEBUG_ENABLE, kein fremdes TOKEN_ADJUST_PRIVILEGES.
|
||||||
|
Bei fehlender erforderlicher Probe, Prozesswechsel, gemeinsamem TokenId,
|
||||||
|
falschem SYSTEM-Primärtoken oder vorhandenem Threadtoken: Abbruch vor Anpassung
|
||||||
|
und vor RPC. Gleiche AuthenticationId allein ist kein Fehler.
|
||||||
|
|
||||||
|
Dies belegt lediglich Trennung von den tatsächlich abgefragten Peer-Tokenobjekten.
|
||||||
|
Es beweist nicht, dass kein weiterer Prozess/Thread irgendeine Referenz auf das
|
||||||
|
Diagnosetoken hält. Die ausgewerteten primären Verträge liefern hierfür keine
|
||||||
|
ausreichende universelle Exklusivitätsgarantie. **Ohne ausdrückliche Akzeptanz
|
||||||
|
dieser Grenze wird kein Anpassungscode erstellt.** Alternativ ist zuerst ein
|
||||||
|
rein lesender TokenId-Vergleich vorzubereiten. Ein dupliziertes Token plus
|
||||||
|
Impersonation oder neuer Childprozess ist ein anderer Vergleich und wird nicht
|
||||||
|
stillschweigend als Ersatz eingebaut.
|
||||||
|
|
||||||
|
## Vorgeschlagene neue Quellen, erst nach dieser Entscheidung
|
||||||
|
|
||||||
|
Vier neue Dateien unter `deploy/windows/clock-spnego-privilege-trace/`:
|
||||||
|
|
||||||
|
- `clock_rpc_spnego_privilege.c`: bytegleicher Empty-RPCpfad bis auf das neue
|
||||||
|
öffentliche Symbolsuffix. Tatsächlich zurückgegebenen nicht-NULL Emptystring
|
||||||
|
unverändert weitergeben; GSS9/Privacy6/Identify2, kein Authfallback. Maximal
|
||||||
|
eine Managementdiscovery und bei erfüllten Vorbedingungen eine Opnum6-Query;
|
||||||
|
Setupfehler bedeuten null Queries. EEInfo weiter maximal vier numerische
|
||||||
|
Records. Kein Setter und keine neue Serveridentitätsbehauptung.
|
||||||
|
- `system_trace_spnego_privilege.c`: eigener, einmalig gestarteter
|
||||||
|
SYSTEM-OWN_PROCESS-Dienst mit dem nachstehend beschriebenen Tokenablauf.
|
||||||
|
- `build.py`: alter Compiler/MIDL/Header/SDK/DLL-Vertrag unverändert, neue
|
||||||
|
vier Inputs sowie Empty-Manifest und tatsächlichen Ausgangscase hashen;
|
||||||
|
alte Inputs nur vergleichen und unverändert erhalten.
|
||||||
|
- `native.py`: eigene Case-/Service-/Profilbindung, create-once prepare/start,
|
||||||
|
rein lesender same-case Readback und getrenntes Cleanup nur des eigenen
|
||||||
|
gestoppten Dienstes. Antwortverlust erlaubt keine Wiederholung des Starts.
|
||||||
|
|
||||||
|
Vorgeschlagene Namen: `RmmClockSpnegoPrivilegeDiagnostic`,
|
||||||
|
`clock-system-spnego-privilege-v1`, `ClockSpnegoPrivilegeTrace.exe`,
|
||||||
|
`C:\ProgramData\RustDiscoveryBootstrap\clock-spnego-privilege-trace-<UUID>`.
|
||||||
|
|
||||||
|
## Geplanter Tokenablauf und Fehlerverhalten
|
||||||
|
|
||||||
|
1. Vor Anpassung eigenes gehaltenes Primärtoken mit exakt TOKEN_QUERY und
|
||||||
|
TOKEN_ADJUST_PRIVILEGES öffnen; keine Vererbung oder Weitergabe des Handles.
|
||||||
|
SYSTEM, Primärtoken und fehlendes Threadtoken prüfen. Vollständige begrenzte
|
||||||
|
Privilegliste auslesen, LUIDs numerisch sortieren und auf Duplikate prüfen.
|
||||||
|
SeSystemtimePrivilege muss genau einmal vorhanden sein, Attribut0 haben und
|
||||||
|
weder enabled noch removed sein. Abweichung verweigert den Vergleich.
|
||||||
|
2. Eigenes PID/Startzeit/TokenStatistics und Peer-Proben samt ursprünglicher
|
||||||
|
numerischer Privilegliste create-once vor Anpassung dauerhaft ablegen.
|
||||||
|
Geplantes Limit: höchstens256 Privilegien und derselbe4096Byte-Tokenpuffer.
|
||||||
|
Keine Namen, Anmeldeinformationen oder Tokenhandles als Ausgabedaten.
|
||||||
|
3. Ein einziges AdjustTokenPrivileges mit DisableAllPrivileges=FALSE,
|
||||||
|
PrivilegeCount=1, exakter vorhandener LUID und SE_PRIVILEGE_ENABLED.
|
||||||
|
Ausreichender fester PreviousState-Puffer für genau eine Änderung;
|
||||||
|
BOOL und sofortiges GetLastError getrennt speichern. Nur TRUE+ERROR_SUCCESS
|
||||||
|
und genau ein gültiger PreviousState-Eintrag derselben LUID/Attribut0
|
||||||
|
erlauben den weiteren Ablauf. Kein SE_PRIVILEGE_REMOVED/DisableAllPrivileges.
|
||||||
|
4. Direkt am gehaltenen eigenen Token nachlesen: gleiche TokenId,
|
||||||
|
AuthenticationId und TokenType, unveränderte Privilegmenge sowie lediglich
|
||||||
|
der erwartete Enablebit-Wechsel. Direkt vor RPC fehlendes Threadtoken erneut
|
||||||
|
prüfen. Fehler springen zuerst in Restore, nicht in RPC. Der Enablezeitraum
|
||||||
|
umfasst den unveränderten Discovery-/Authsetup-/Querypfad; es wird keine
|
||||||
|
Behauptung aufgestellt, dass das Bit nur während des einzelnen Opnum6 aktiv ist.
|
||||||
|
5. Bestehende RPCfunktion höchstens einmal aufrufen; RPCexception/Fehler bleibt
|
||||||
|
ihr numerischer Befund. Unmittelbar danach Restore auf demselben gehaltenen
|
||||||
|
eigenen Token mit PreviousState als NewState. Jeder normale Fehlerpfad nach
|
||||||
|
Anpassungsbeginn erreicht denselben Cleanupblock, bevor Berichtschreiben
|
||||||
|
oder Dienstende. Auch fehlgeschlagene Nachprüfung löst Restore aus.
|
||||||
|
Bei unerwartetem PreviousState ist kein RPC erlaubt; der bereits separat
|
||||||
|
gesicherte eine ursprüngliche LUID/Attribut0 ist die begrenzte Restoreeingabe.
|
||||||
|
Keine Wiederholung eines RPCs oder Aktivierungsversuchs.
|
||||||
|
6. Restore-BOOL und unmittelbaren Fehlercode separat erfassen. Vollständige
|
||||||
|
Privilegliste erneut lesen; exakt ursprüngliche Attribute/Menge fordern.
|
||||||
|
TokenId/AuthenticationId/TokenType müssen gleich sein. ModifiedId darf und
|
||||||
|
wird gegebenenfalls anders sein; dies ist keine fehlgeschlagene Rücksetzung.
|
||||||
|
Peer-TokenIds/Attribute erneut rein lesend prüfen; Wechsel/Fehler ehrlich
|
||||||
|
als nicht nachgewiesene Erhaltung melden, nicht durch fremden Schreibzugriff
|
||||||
|
reparieren. Danach Ergebnis plus before/enabled/restored-Snapshots speichern.
|
||||||
|
|
||||||
|
Ein Restorefehler kann nicht durch eine Erfolgsmeldung verdeckt werden und
|
||||||
|
beweist keine erfolgreiche Erhaltung; Dienstexit wird Fehler, kein weiterer
|
||||||
|
RPC. Unvorhersehbarer Prozessabbruch, TerminateProcess oder Stromverlust kann
|
||||||
|
keinen benutzerseitigen finally-Block garantieren. Ohne gespeicherte und
|
||||||
|
nachgelesene Wiederherstellung lautet der Nachweis daher `unknown`, auch wenn
|
||||||
|
der Prozess bereits beendet ist. Es wird keine universelle Rücksetzgarantie
|
||||||
|
für solche Abbrüche behauptet.
|
||||||
|
|
||||||
|
Die Statusquery bleibt fachlich lesend; der neue Diagnoseprozess insgesamt ist
|
||||||
|
wegen AdjustTokenPrivileges **nicht rein lesend**. Maschinen-/Kontorechte,
|
||||||
|
ACL/GPO, W32Time-Konfiguration, Dienstkonten und Uhrzeit werden nicht geändert.
|
||||||
|
Die Erzeugung des eigenen Diagnosedienstes bleibt eine gesonderte ausdrückliche
|
||||||
|
Bootstrapwirkung. Kein Produktgate und keine Job-/Freigabe-/Policyänderung.
|
||||||
|
|
||||||
|
## Geplante lokale und native Nachweise, sämtlich noch nicht ausgeführt
|
||||||
|
|
||||||
|
Nach akzeptiertem Scope zunächst Quellenreview: genau ein Enable, ein gebundener
|
||||||
|
Restorepfad, kein Tokenwechsel, keine fremden Tokenwrites, bestehender RPCpfad
|
||||||
|
bis auf Symbol bytegleich. Lokale gezielte Guardfälle: TRUE mit1300 verweigern,
|
||||||
|
fehlendes/removed/dupliziertes Recht, bereits enabled, falscher PreviousState,
|
||||||
|
fremder gleicher TokenId, Peerwechsel, nichtlesbarer Peer, aktiver Threadtoken,
|
||||||
|
Nachprüfungsfehler, RPCexception sowie Restorefehler. Nicht jeder synthetisch
|
||||||
|
abgedeckte Fehler ist damit ein nativer Windowsnachweis.
|
||||||
|
|
||||||
|
Erst nach getrenntem Source-/Buildreview kann der Hauptagent einen neuen nativen
|
||||||
|
Case ausdrücklich starten. Benötigte Belege: originale Snapshots vor Anpassung,
|
||||||
|
sichtbare einzelne Enableänderung, exakter RPC-/EEInfo-Befund, nachgelesener
|
||||||
|
Restore, unveränderte Peer-Zustände, gestoppter eigener Dienst, same-case
|
||||||
|
Readback sowie getrenntes Cleanup/Preservation bestehender RMM-Dienste. Keine
|
||||||
|
Clockqualifikation allein aus einem erfolgreichen Statusqueryreturn ableiten.
|
||||||
|
|
||||||
|
|
||||||
|
## Lokale Umsetzung nach ausdrücklicher Rootfreigabe
|
||||||
|
|
||||||
|
Der Hauptagent hat die begrenzte TokenId-Trennung zu gehaltenen SCM-/W32Time-/
|
||||||
|
Agent-/Helper-Prozessen ausdrücklich akzeptiert. Universelle Exklusivität aller
|
||||||
|
Referenzen wird weiterhin nicht behauptet. Der ursprüngliche176Zeilen-Plan
|
||||||
|
mit SHA25627b1035c… ist zusätzlich create-once unter
|
||||||
|
`devstate/windows-clock-spnego-privilege-trace/local-review/accepted-plan.md`
|
||||||
|
erhalten. Dieser Abschnitt ersetzt keine Freigabe einer Zielaktion.
|
||||||
|
|
||||||
|
Die vier oben benannten neuen Dateien sind jetzt lokal implementiert.
|
||||||
|
Vorher werden eigene TokenUser/SYSTEM, Primärtoken, fehlender Threadtoken und
|
||||||
|
vollständige numerische Privilegliste geprüft. SCM wird eindeutig über
|
||||||
|
services.exe samt Systempfad ermittelt; die anderen drei Prozesse sind über
|
||||||
|
gehaltene Service-/Prozesshandles, Running/PID, Erstellzeit und feste Images
|
||||||
|
gebunden. Fremde Tokenhandles verlangen ausschließlich TOKEN_QUERY. Der eigene
|
||||||
|
Tokenhandle verlangt QUERY|ADJUST_PRIVILEGES. Vor Enable wird der vollständige
|
||||||
|
Beforebeleg create-once geschrieben. Der unmittelbare Enable-Rückgabecode und
|
||||||
|
GetLastError, PreviousState und volle Nachlese begrenzen den einzigen RPCpfad.
|
||||||
|
|
||||||
|
Alle kontrollierten Fehlerpfade nach Enable erreichen dieselbe einzelne
|
||||||
|
Restorestelle; danach werden volle ursprüngliche Attribute und die
|
||||||
|
unveränderten numerischen Peer-Privilegzustände/TokenIds/ModifiedIds geprüft.
|
||||||
|
ModifiedId des eigenen Tokens darf nach korrektem Restore geändert sein.
|
||||||
|
Berichte kennzeichnen die gesamte Diagnose ausdrücklich als read_only=false;
|
||||||
|
SYSTEM wird nur bei erfolgreicher tatsächlicher Probe ausgewiesen. Ein eigener
|
||||||
|
Cleanupreceipt erhält den vorherigen Dienstexitcode, damit Serviceentfernung
|
||||||
|
keinen fehlgeschlagenen Ablauf nachträglich als vollständig erscheinen lässt.
|
||||||
|
|
||||||
|
Finaler lokaler Build:
|
||||||
|
`devstate/windows-clock-spnego-privilege-trace/build-b56e3f3d-8904-4fd8-9c34-0e55e57c8f07/manifest.json`, SHA256
|
||||||
|
`6c97658307ec66e6605574dca27cdbc79efefa9cd7f386e6e2cb3f73d9b5c6d3`.
|
||||||
|
PE114087Bytes, SHA256
|
||||||
|
`68a217914c15f28b19c52a2f5adfd595854f88210fbb0b69c20e73a59952b65e`.
|
||||||
|
Originales Microsoft-MIDL/Header und gepinnter Compiler unverändert; eigene
|
||||||
|
C-Units Wall/Wextra/Werror, gleiche vier DLL-Imports ADVAPI32/KERNEL32/RPCRT4/
|
||||||
|
msvcrt. PowerShell-AST bestanden, EncodedCommand18858Zeichen unter32767.
|
||||||
|
Alle131Produktinputs,15bisherige Diagnosequellen sowie F6-/Empty-Manifeste und
|
||||||
|
Ergebnisbelege unverändert geprüft. Der RPCwrapper unterscheidet sich vom
|
||||||
|
Empty-Elternteil ausschließlich durch das öffentliche Symbolsuffix.
|
||||||
|
|
||||||
|
Gezielte lokale Nachweise, keine Windows-API- oder RPC-Ausführung: der tatsächliche
|
||||||
|
C-run_service-Block wurde bytegleich extrahiert und mit kontrollierten lokalen
|
||||||
|
API-Stubs übersetzt/ausgeführt.13Fälle bestanden, unter anderem TRUE/1300,
|
||||||
|
FALSE, ungültiger PreviousState, aktive Attributabweichung, Own-/Peerprobe-Fehler,
|
||||||
|
Restorefehler, fehlgeschlagene Nachlese sowie Writefehler vor/nach Enable.
|
||||||
|
Jeder Fall prüft höchstens1Enable, genau1Restore je Enable und höchstens1RPC.
|
||||||
|
Der echte Python-Reader akzeptierte zwei synthetische gültige Berichte und
|
||||||
|
verweigerte17Fälschungen/Fehler einschließlich fremdem TokenId, nicht erhaltenen
|
||||||
|
Attributen, Peerdrift, schwächerer Privacy und verstecktem Fehlerexit nach Cleanup.
|
||||||
|
Guardreceipt `local-review/guards.json`, SHA256
|
||||||
|
`c12c5d06ecad63101874f7c66af1f49eb9f6d9b51dbba9c75e367462660fa831`.
|
||||||
|
Dies sind lokale Fehlerpfadbelege, keine nativen Token-/Erhaltungsnachweise.
|
||||||
|
|
||||||
|
**Bis zum Abschluss dieser lokalen Vorbereitung war kein Privilegvergleich auf
|
||||||
|
Windows ausgeführt. Der Subagent hat keinen VM-/SSH-/SCM-Start vorgenommen und
|
||||||
|
keinen Produktcode/Clockgate geändert.** Das erforderliche unabhängige
|
||||||
|
Source-/Manifestreview und die spätere native Ausführung durch den Hauptagenten
|
||||||
|
sind inzwischen im [tatsächlichen Ergebnis](windows-clock-process-privilege-result.md)
|
||||||
|
mit Startfehler, separatem Readback, Restore, Cleanup und Preservation dokumentiert.
|
||||||
|
Auch eine künftig erfolgreiche Query ließe produktive LocalService-Privilegien,
|
||||||
|
gebundene Serveridentität und Transport-Positiv-/Negativnachweise weiter offen;
|
||||||
|
Discovery/NTLM/Mutualauth-Flags allein ersetzen diese nicht.
|
||||||
@@ -0,0 +1,185 @@
|
|||||||
|
# Tatsächlicher Prozessprivilegvergleich auf der Windows-VM
|
||||||
|
|
||||||
|
Stand 2026-11-14: eigener Diagnoseablauf, separater Readback, Cleanup und
|
||||||
|
After-Preservation durch den Hauptagenten abgeschlossen. Die W32Time-Statusquery
|
||||||
|
scheitert weiterhin mit RPC5. Kein Produktgate geöffnet, kein RMM-Job ausgeführt.
|
||||||
|
|
||||||
|
## Verwendeter Quellen- und Buildstand
|
||||||
|
|
||||||
|
Reviewter Nachfolger unter `deploy/windows/clock-spnego-privilege-trace/`, vier
|
||||||
|
Dateien; ursprünglicher Scope und lokale Nachweise:
|
||||||
|
[Prozessprivilegplan](windows-clock-process-privilege-plan.md).
|
||||||
|
|
||||||
|
Buildmanifest:
|
||||||
|
`devstate/windows-clock-spnego-privilege-trace/build-b56e3f3d-8904-4fd8-9c34-0e55e57c8f07/manifest.json`, SHA256
|
||||||
|
`6c97658307ec66e6605574dca27cdbc79efefa9cd7f386e6e2cb3f73d9b5c6d3`.
|
||||||
|
Windows-PE114087Bytes, SHA256
|
||||||
|
`68a217914c15f28b19c52a2f5adfd595854f88210fbb0b69c20e73a59952b65e`.
|
||||||
|
Der Hauptagent und sein unabhängiger Reviewer haben Quelle, Manifest und PE
|
||||||
|
geprüft. Die vier Quellen wurden für den nativen Vergleich nicht verändert.
|
||||||
|
|
||||||
|
## Fehlgeschlagener Startaufruf und getrennte Nachlese
|
||||||
|
|
||||||
|
Neuer einmaliger Case: `6de04277-6bec-477d-b1c9-bfca88a9cd78`.
|
||||||
|
Der ursprüngliche Startaufruf meldet tatsächlich
|
||||||
|
`StartServiceFailed,Microsoft.PowerShell.Commands.StartServiceCommand` an Zeile26.
|
||||||
|
Transportbeleg `transport-6e33c04b-f149-426b-8da1-309129ff3469.json`, SHA256
|
||||||
|
`83ccfd7db60ad27dd901ddbef223cde8f69ecc9e635373038f20ca864b954ba6`.
|
||||||
|
Dieser Aufruf bleibt als fehlgeschlagen dokumentiert. **Kein Startretry.**
|
||||||
|
|
||||||
|
Anschließend gewinnt der Hauptagent ausschließlich durch einen separaten,
|
||||||
|
rein lesenden same-case Readback den vollständigen Diagnosebericht. Der eigene
|
||||||
|
Dienst ist gestoppt, Dienstexit0. Readback
|
||||||
|
`readback-9039311f-1b98-4d0c-b516-02a543fb2d7b.json`, SHA256
|
||||||
|
`c5dcf129d329b879be00c801eead32d2047d9b73ffed0e0e692615e9a7459c07`.
|
||||||
|
Der gebundene vollständige Ergebnisbeleg `diagnostic-result.json` hat SHA256
|
||||||
|
`c7556589a015fc5ab53feffe3caf74a3904b7f5a65b70066f256cc0693ff8152`.
|
||||||
|
Exit0 und complete=true belegen den abgeschlossenen Diagnose-/Restoreablauf,
|
||||||
|
keinen gelungenen W32Time-Aufruf. Die Ursache der anfänglichen Startfehlermeldung
|
||||||
|
ist nicht nachgewiesen; eine SCM-Race wird nicht als Erklärung behauptet.
|
||||||
|
|
||||||
|
## Tatsächliche Token- und RPC-Ergebnisse
|
||||||
|
|
||||||
|
Eigenes gehaltenes SYSTEM-Primärtoken; kein Threadtoken. Der vorhandene
|
||||||
|
SeSystemtimePrivilege-LUID ist12,0, ursprüngliches Attribut0. Genau ein
|
||||||
|
Enableversuch: BOOLtrue/GetLastError0, PreviousStateCount1,16Bytes, derselbe
|
||||||
|
LUID12,0 und ursprüngliches Attribut0. Die anschließende vollständige Nachlese
|
||||||
|
zeigt ausschließlich den vorgesehenen Enablebit-Wechsel auf2.
|
||||||
|
|
||||||
|
Genau eine Wiederherstellung auf dem gehaltenen eigenen Token mit dem geprüften
|
||||||
|
PreviousState: BOOLtrue/GetLastError0. Danach sind die vollständige ursprüngliche
|
||||||
|
Privilegmenge und Attribute0 wiederhergestellt, restoration_verified1,
|
||||||
|
restored_status0, flow_status0. Vorher-/Nachher-TokenId und Authentifizierungs-ID
|
||||||
|
bleiben gebunden; eine geänderte eigene ModifiedId ist keine unerwartete
|
||||||
|
Attributabweichung. Die beobachteten gehaltenen Peer-Tokens für SCM, W32Time,
|
||||||
|
Agent und Helper behalten ihre TokenIds, ModifiedIds und Privilegattribute.
|
||||||
|
Dies ist der vereinbarte begrenzte Peer-Nachweis, keine universelle Behauptung
|
||||||
|
über sämtliche Tokenreferenzen des Betriebssystems. Fremdtokens werden nur gelesen.
|
||||||
|
|
||||||
|
Eine SPNEGO-Managementdiscovery gelingt mit Status0 und normalem Return. Der
|
||||||
|
tatsächlich gelieferte Principalpointer ist nicht-NULL, UTF16-Länge0. GSS9,
|
||||||
|
PacketPrivacy6 und Identify2 bleiben unverändert. Danach genau ein Opnum6:
|
||||||
|
RPCexception5/Stage90, kein normaler Return, kein Statusobjekt. Unmittelbar
|
||||||
|
erfasst wird ein numerischer EEInfo-Record: Komponente2, Status5,
|
||||||
|
DetectionLocation1750, Flags0, Parameteranzahl1. Keine Parameterinhalte gelesen.
|
||||||
|
Principal-/Bindingfreigabe werden jeweils einmal erfolgreich ausgeführt.
|
||||||
|
|
||||||
|
Der Unterschied zum vorherigen Emptyvergleich ist damit tatsächlich geprüft:
|
||||||
|
Aktivieren dieses vorhandenen Prozessprivilegs beseitigt den beobachteten RPC5
|
||||||
|
nicht. Daraus folgt weder, dass jede Privilegprüfung erfolgreich war, noch eine
|
||||||
|
eindeutige Aussage über den vom Server geprüften Credential-/Impersonationkontext.
|
||||||
|
Keine Uhr-, Kontorechte-, ACL-, GPO-, Policy- oder W32Time-Konfigurationsänderung.
|
||||||
|
Die gesamte Privilegdiagnose kennzeichnet sich korrekt als read_only=false;
|
||||||
|
die einzige W32Time-Methodenquery selbst ist lesend.
|
||||||
|
|
||||||
|
## Cleanup und Erhaltung
|
||||||
|
|
||||||
|
Der Hauptagent bereinigt ausschließlich den eigenen gestoppten Diagnosedienst.
|
||||||
|
Cleanupreceipt `readback-d02e8c7a-5154-488b-a29f-4d4d8155ec7a.json`, SHA256
|
||||||
|
`e163d7d4790ea4900f1cc1caedf11ff2619f30cf7b25388eabffa9afd75d8d50`,
|
||||||
|
bestätigt cleanup_verified=true; der eigene Dienst ist anschließend nicht mehr
|
||||||
|
registriert. Kein Retry, Reset oder zusätzlicher RMM-Job.
|
||||||
|
|
||||||
|
Vorherbeleg SHA256
|
||||||
|
`a4b321f965f4ccc968724fae9abd856cca5f799b5fc96a54d04f5316b95ab05b`;
|
||||||
|
Afterbeleg im Pipeworktree:
|
||||||
|
`devstate/windows-client/system-pipe-upgrade/14fb176a-f653-4573-a8d7-6f9fe47a3020/spnego-privilege-trace-after.json`, SHA256
|
||||||
|
`f37a2e866ebc5dfd1ae13bfd18b7c5355da42dfd01b7e7e69f478555c60eb830`.
|
||||||
|
Alle sechs nativen Bereiche service/helper_service/agent_kernel/helper_kernel/
|
||||||
|
files/helper_witness sind exakt gleich. Serverzustand ebenfalls gleich:
|
||||||
|
Windows0/0/0/0, Linux31/31/27/0, geschlossene Rootpolicycf15. Der separate
|
||||||
|
Nachweis meldet verified=true, read_only=true, no_jobs=true, clock_qualified=false.
|
||||||
|
|
||||||
|
## Tatsächlicher Builtinvergleich und Primärquellen
|
||||||
|
|
||||||
|
Der Hauptagent hat separat den vorhandenen Microsoft-Builtin
|
||||||
|
`w32tm /query /status /verbose` über den bestehenden Administratortransport
|
||||||
|
abgefragt. Beim ersten lesenden Aufruf scheitert der Texttransport an einer
|
||||||
|
UTF8-Dekodierung mit Byte0x84; Resultbytes wurden nicht erhalten. Dies ist kein
|
||||||
|
brauchbarer Status- oder Exitcodenachweis dieses ersten Prozesses. Ein zweiter,
|
||||||
|
separater lesender Query verwendet danach eine ASCII-JSON-Hülle und Base64
|
||||||
|
für den ausdrücklich UTF8-kodierten Ausgabetext. Keine wiederholte Wirkung eines
|
||||||
|
RMM-Jobs; beide Bootstrapbefehle sind Statusabfragen, kein resync/config/register.
|
||||||
|
|
||||||
|
Der zweite Aufruf liefert Exit0. Receipt im Pipeworktree unter demselben14fb-Pfad:
|
||||||
|
`builtin-w32tm-status-base64-result.json`, SHA256
|
||||||
|
`4e5ea093ee8f9508b5327e664bbe9c824895c08feecdd8f425fe18f9d2ece262`.
|
||||||
|
Der erhaltene native Status meldet Leap3/nicht synchronisiert, Stratum0,
|
||||||
|
Rootdispersion8.8814534Sekunden, Phase-1.1113519Sekunden, letzte Synchronisation
|
||||||
|
14.11.2026 15:26:24, Alter15703Sekunden und letzte Synchronisationsfehlermeldung1/
|
||||||
|
keine Zeitdaten. Konfigurierte Quelle: time.windows.com,0x9. Dies sind die Werte
|
||||||
|
im erhaltenen Statuszeitpunkt, keine aktuelle fortlaufende Messung und kein
|
||||||
|
vertrauenswürdiger Synchronisationsnachweis.
|
||||||
|
|
||||||
|
Damit sind zwei getrennte Hindernisse belegt: der eigene SYSTEM-/SPNEGO-RPCpfad
|
||||||
|
scheitert weiterhin mit5, während der Builtin unter dem Administratortransport
|
||||||
|
Status lesen kann; zusätzlich zeigt der tatsächlich gelesene W32Time-Status
|
||||||
|
keine vertrauenswürdige Synchronisation. Exit0 des Tools behebt keines dieser
|
||||||
|
Produktgates und beweist kein bestimmtes internes Authentifizierungsverfahren.
|
||||||
|
Eine Netzprobe oder spätere Zeitsynchronisierung ist kein Bestandteil dieses
|
||||||
|
Schritts; daraus folgt keine Freigabe für Uhr-/NTP-/Serviceänderungen.
|
||||||
|
|
||||||
|
Microsoft beschreibt /query /status als Statusanzeige, ohne /computer
|
||||||
|
standardmäßig lokal, und verlangt für lokale Toolnutzung Administratorberechtigung.
|
||||||
|
Die Quelle legt weder das konkrete interne Binding noch Authn-/Impersonation-
|
||||||
|
parameter dieses konkreten Builtinlaufs offen.
|
||||||
|
[Windows Time Service Tools and Settings](https://learn.microsoft.com/en-us/windows-server/networking/windows-time-service/windows-time-service-tools-and-settings)
|
||||||
|
|
||||||
|
MS-W32T AppendixB33 beschreibt eine zusätzliche Prüfung des Rechts zur
|
||||||
|
Systemzeitänderung; auch eine nicht durchführbare Prüfung kann den Aufruf
|
||||||
|
verweigern. Der dokumentierte Clientpfad verwendet SPNEGO/Privacy mit dem
|
||||||
|
Discoveryergebnis. Daraus lässt sich ohne weitere Beobachtung nicht schließen,
|
||||||
|
welche Prüfung den konkreten RPC5 verursacht hat.
|
||||||
|
[MS-W32T Appendix B](https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-w32t/bb576d39-587b-484a-86a4-e1d378cf9497)
|
||||||
|
|
||||||
|
Ein serverseitiger RPC-Securitycallback kann Zugriffe prüfen; eine Ablehnung
|
||||||
|
wird zum Client als RPC_S_ACCESS_DENIED abgebildet. Der Zahlenwert5 identifiziert
|
||||||
|
deshalb keine einzelne fehlgeschlagene Prüfung und keinen bestimmten Callback.
|
||||||
|
[RPC_IF_CALLBACK_FN](https://learn.microsoft.com/en-us/windows/win32/api/rpcdce/nc-rpcdce-rpc_if_callback_fn)
|
||||||
|
|
||||||
|
Authentifizierung, Clientcredential-Snapshot, SSP-Verhalten und zulässige
|
||||||
|
serverseitige Impersonation sind getrennte Eigenschaften. Ein NULL-AuthIdentity
|
||||||
|
verwendet den aktuellen Login-Kontext, nicht explizit anonyme Credentials.
|
||||||
|
Der Authsetup-Aufruf nimmt einen Credentialsnapshot; die QoS-Unterscheidung
|
||||||
|
Static/Dynamic und Identify/Impersonate enthält SSP-/Transportsonderfälle.
|
||||||
|
Diese Unterschiede bleiben Hypothesen bis zu einem passenden Nachweis.
|
||||||
|
[RpcBindingSetAuthInfoExW](https://learn.microsoft.com/en-us/windows/win32/api/rpcdce/nf-rpcdce-rpcbindingsetauthinfoexw),
|
||||||
|
[RPC_SECURITY_QOS](https://learn.microsoft.com/en-us/windows/win32/api/rpcdce/ns-rpcdce-rpc_security_qos)
|
||||||
|
|
||||||
|
Produktiver Transport, LocalService-Rechte und gebundene W32Time-Serveridentität
|
||||||
|
einschließlich Positiv-/Negativnachweisen bleiben offen. Discovery, Negotiate,
|
||||||
|
NTLM oder ein Mutualauth-Flag allein ersetzen keinen sicheren Identitätsbeweis.
|
||||||
|
Keine weitere Diagnosequelle und keine Produktfunktion als Teil dieses Schritts.
|
||||||
|
|
||||||
|
|
||||||
|
## Enger Quellenvergleich nach dem Builtinergebnis
|
||||||
|
|
||||||
|
Die Microsoft-Methode W32TimeQueryStatus ist ausdrücklich Opnum6. Sie hat genau
|
||||||
|
zwei Parameter: das primitive handle_t hBinding und den äußeren out/ref-Zeiger
|
||||||
|
auf PW32TIME_STATUS_INFO. Kein ulInfoLevel, Providername oder weiterer
|
||||||
|
Eingabeparameter ist für diese Methode beschrieben. Das ursprüngliche gepinnte
|
||||||
|
IDL bewahrt sechs unaufgerufene Slots davor; unser tatsächlicher Aufruf ist
|
||||||
|
RmmW32TimeQueryStatus(binding,&status). Der erhaltene Microsoft-MIDL-Header149b
|
||||||
|
hat denselben Zweiparameterprototyp. Dieser Vergleich liefert deshalb keinen
|
||||||
|
Hinweis auf einen fehlenden Infolevel-/Providerparameter bei unserer Opnum6.
|
||||||
|
[W32TimeQueryStatus, Opnum6](https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-w32t/7e80a465-f5f4-4c3c-87ef-12f76e45f8d1)
|
||||||
|
|
||||||
|
Der eigene Code aktiviert das vorhandene Recht vor dem Aufruf der gesamten
|
||||||
|
RPCfunktion. Erst danach entstehen in diesem neuen Prozess Binding, Discovery
|
||||||
|
und Authsetup. Die einfache Erklärung, unser eigener statischer
|
||||||
|
Credentialsnapshot sei bereits vor Enable erstellt worden, passt daher nicht
|
||||||
|
zu dieser nachgewiesenen Codefolge. Welche Identität und Privilegabbildung die
|
||||||
|
Gegenseite tatsächlich geprüft hat, bleibt ohne passenden Nachweis offen.
|
||||||
|
|
||||||
|
Als Unterschiede zum Builtin bleiben Authn-/SSP-Auswahl, der tatsächlich beim
|
||||||
|
Server ausgewertete Clientcredential-Kontext und dessen zulässige Impersonation
|
||||||
|
zu untersuchen. Identify2 hat provider-/transportabhängige Sonderfälle; ein
|
||||||
|
Wechsel auf Impersonate3 würde zusätzliche Autorität erlauben und wird aus diesem
|
||||||
|
Befund weder still vorgenommen noch als Produktionsfix empfohlen. Die reine
|
||||||
|
Builtin-Ausgabe offenbart diese internen Einstellungen nicht. Es werden keine
|
||||||
|
Servercallbackursache oder DetectionLocation1750-Zuordnung erfunden.
|
||||||
|
|
||||||
|
Die originalen IDL-Kommentare nennen teilweise ältere Kapitelnummern. Der hier
|
||||||
|
verifizierte Vertrag stammt aus der aktuellen Methodenbeschreibung3.2.5.7 und
|
||||||
|
der dort gebundenen Statusstruktur2.2.17; ein Kommentarfix kann nach dem MVP
|
||||||
|
folgen. Gepinnte IDL-/MIDL-/Produktquellen bleiben in diesem Abnahmeschritt bytegleich.
|
||||||
@@ -262,3 +262,47 @@ SDK-Struktur bleibt aufx64 begrenzt und wird beim MSVC-Build zusätzlich direkt
|
|||||||
gegen die native SDK-Deklaration geprüft. Dies ersetzt weder einen nativen
|
gegen die native SDK-Deklaration geprüft. Dies ersetzt weder einen nativen
|
||||||
MSVC- noch einen tatsächlichen W32Time-Nachweis. W32Time ist weiterhin gestoppt;
|
MSVC- noch einen tatsächlichen W32Time-Nachweis. W32Time ist weiterhin gestoppt;
|
||||||
Produktgate unverändert `ADAPTER_QUALIFIED=false`.
|
Produktgate unverändert `ADAPTER_QUALIFIED=false`.
|
||||||
|
|
||||||
|
## Autorisierter Dienststart — noch keine Clockabnahme
|
||||||
|
|
||||||
|
Nach ausdrücklicher Userentscheidung1.18 wurde das vorhandene W32Time im Fall
|
||||||
|
`c3552c3f…` genau einmal gestartet und separat lesend als Running bestätigt.
|
||||||
|
RMM-Agent/Helper samt ursprünglichen PIDs, Definitionen und PKI-Metadaten,
|
||||||
|
ausgewählte NTP-/Policywerte und zentrale Jobzählungen/Flags sind erhalten.
|
||||||
|
Keine Startart-/NTP-/ACLänderung oder Resynchronisierung angefordert; normale
|
||||||
|
Synchronisierung durch den Dienst ist erlaubt. [Genauer Beleg](windows-time-service-start.md).
|
||||||
|
|
||||||
|
Ein neuer GNU-Diagnosebuild `a817cf61…`, EXE `f5003f96…`, wurde lokal mit
|
||||||
|
identischen Quellbindungen vor/nach gebaut. Sein tatsächlicher ALPC-/Status-/
|
||||||
|
Identitätskontrolllauf ist inzwischen ausgeführt; Ergebnis folgt unten. Der
|
||||||
|
Dienststart allein öffnet weder Clock- noch Jobgate.
|
||||||
|
|
||||||
|
## Tatsächlicher Kandidatenlauf nach Dienststart: nicht qualifiziert
|
||||||
|
|
||||||
|
Fall `e1f3edbb-5a2f-4d82-a449-0432913c6bd7`, EXE `f5003f96…`, nativ als
|
||||||
|
separater LocalService-Dienst: TokenSID19, kein Administratormitglied/SYSTEM,
|
||||||
|
zwei Statusproben und beide Identitätskontrollen ausgeführt. ALPC meldet jeweils
|
||||||
|
`1753`/`CLOCK_UNSUPPORTED`; die Endpunktenumeration meldet Erfolg mit0Einträgen.
|
||||||
|
Beide Negativkontrollen ebenfalls1753, **kein Ablehnungs-/Identitätsbeweis**.
|
||||||
|
Die zusätzliche Named-Pipe-Diagnose meldet1783 ohne Status. Noch unbewiesen,
|
||||||
|
ob dessen Quelle RPC/NDR oder der eigene strikte Strukturguard ist. Keine
|
||||||
|
stillschweigende Status-/Authentisierungs-/Transportlockerung.
|
||||||
|
|
||||||
|
Der eigene temporäre Dienst wurde nach Stopped entfernt; der normale Agent und
|
||||||
|
SYSTEM-Helper wurden nicht gestoppt oder verändert. Separater Readback bestätigt
|
||||||
|
identischen Originalbericht. Zentralstände0/0/0/0 und30/30/26/0 sowie geschlossene
|
||||||
|
Flags/Rootpolicyhash vor/nach unverändert. Privater Fallabschluss
|
||||||
|
`assessment.json`, SHA256
|
||||||
|
`d80e5f39cbd6d332deb12bf4f21e1372c88025b551db4ef33a190e3f82b3300a`.
|
||||||
|
Native Ausführung belegt, **Clockabnahme fehlgeschlagen**; Produktionsgatefalse,
|
||||||
|
keine Windowsjobs oder Capabilities aktiviert.
|
||||||
|
|
||||||
|
Nach dem Lauf erneut gegen Microsoft geprüft: MS-W32T2.1 verlangt Named-Pipe-
|
||||||
|
Transport und nennt den authentisierten Endpunkt `W32TIME_ALT`; ein ALPC-
|
||||||
|
Endpunkt ist damit kein zugesicherter Plattformvertrag. Der bisherige ALPC-
|
||||||
|
Kandidat war ein zu qualifizierender Zusatz, keine native Windowsgarantie.
|
||||||
|
[Transportvertrag](https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-w32t/e0803f6b-e175-4b87-ba63-bbcf51175655),
|
||||||
|
[vollständiges IDL](https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-w32t/5793e908-22ef-4cea-962f-fca8a72c485a).
|
||||||
|
Die konkrete1783-Ursache wird separat rein diagnostisch eingegrenzt; eine
|
||||||
|
erfolgreiche unqualifizierte Pipeabfrage würde die Clockgrenze weiterhin nicht
|
||||||
|
öffnen. Bereits vorhandene Originalfehler bleiben unverändert erhalten.
|
||||||
|
|||||||
@@ -0,0 +1,108 @@
|
|||||||
|
# QOS5-Fehler87: statischer Befund der tatsächlichen RPC-Runtime
|
||||||
|
|
||||||
|
2026-11-14. Die beiden nativen QOS5-Diagnosen erreichen keine Statusquery.
|
||||||
|
Die folgende ausschließlich lokale Analyse grenzt ihre Parameterverweigerung
|
||||||
|
an der bereits nur lesend gesicherten Windows-System-DLL ein. Sie führt keine
|
||||||
|
PE-Datei, keinen neuen Dienst und keinen RMM-Job aus. Die bestehenden131
|
||||||
|
Produktinputs und31 Diagnoseinputs bleiben bytegleich. Produktclock und
|
||||||
|
Windowsjobgate bleiben geschlossen.
|
||||||
|
|
||||||
|
## Primärvertrag und gesicherte Artefakte
|
||||||
|
|
||||||
|
Microsoft beschreibt `ServerSecurityDescriptor` in QOS5 als clientseitigen
|
||||||
|
Serveridentifikationsdescriptor. Die öffentliche Dokumentation präzisiert
|
||||||
|
weder seine Auswertung für Named Pipes noch eine Pflicht zum selbstrelativen
|
||||||
|
Format. Die SID ist eine Alternative zum erwarteten Serverprincipal; ein
|
||||||
|
erfolgreich gesetztes Mutual-Auth-Flag alleine belegt bei NTLM keine
|
||||||
|
gegenseitige Authentifizierung.
|
||||||
|
[QOS5-Vertrag](https://learn.microsoft.com/en-us/windows/win32/api/rpcdce/ns-rpcdce-rpc_security_qos_v5_w),
|
||||||
|
[SetAuthInfoExW](https://learn.microsoft.com/en-us/windows/win32/api/rpcdce/nf-rpcdce-rpcbindingsetauthinfoexw).
|
||||||
|
|
||||||
|
Die tatsächlich auf der Windows-VM nur lesend kopierte `RPCRT4.dll` hat
|
||||||
|
1182928Byte und SHA256
|
||||||
|
`35fa5f92f985cba9b33bc5f17968211d84ebb910d639ba2db8f35596befca6a6`.
|
||||||
|
Die getrennten nativen Before-/Aftermetadaten melden denselben Hash, dieselbe
|
||||||
|
Länge und Windows-Authenticode-Status `Valid`. Die lokale Kopie stimmt damit
|
||||||
|
überein. Das ist der untersuchte konkrete OS-Stand, keine Zusage für jede
|
||||||
|
Windowsversion oder jeden Transport.
|
||||||
|
|
||||||
|
Die über den offiziellen Microsoft-Symbolserver zum CodeView-Schlüssel
|
||||||
|
`E9DD14015C33891F220822884DBE17FA1` geladene öffentliche `rpcrt4.pdb` hat
|
||||||
|
905216Byte und SHA256
|
||||||
|
`1e31c17cb9f42e6bd503d149793104a50683dfc4421b3139a09836549aa3dd6c`.
|
||||||
|
GUID `e9dd1401-5c33-891f-2208-22884dbe17fa` stimmt überein.
|
||||||
|
DLL-CodeView-Age und PDB-DBI-Age sind jeweils1; der PDB-Informationsstream
|
||||||
|
meldet dagegen3. Diese Werte werden getrennt erhalten, kein vollständiger
|
||||||
|
Age-Gleichstand behauptet. Die unten genannten Codeadressen und der
|
||||||
|
Vtableslot sind zusätzlich unmittelbar gegen die DLL-Bytes geprüft.
|
||||||
|
|
||||||
|
Alle OS-Binärdateien, PDB, vollständigen Disassemblies und Rohbelege bleiben
|
||||||
|
privat unter `devstate/windows-builtin-clock/f2de6c29-38f3-4e4d-813e-e9e498a870a6/`
|
||||||
|
im Hauptcheckout. Sie werden nicht ins Repository übernommen.
|
||||||
|
|
||||||
|
## Frühere Verweigerung bei tatsächlich leerem Principal
|
||||||
|
|
||||||
|
Der Export `RpcBindingSetAuthInfoExW` beginnt bei RVA`0x405f0`. Sein
|
||||||
|
Mutual-Auth-Parametercheck behandelt sowohl NULL als auch einen vorhandenen
|
||||||
|
Principal mit erstem UTF-16-Codeunit0 als fehlenden erwarteten Namen:
|
||||||
|
RVA`0x40962` prüft genau diese leere Zeichenfolge. Dieser Pfad verlangt
|
||||||
|
anschließend QOS-Version mindestens3 und eine vorhandene SID bei QOS-Offset
|
||||||
|
`0x20` (RVA`0x40771` bis`0x4077e`). Andernfalls liefert RVA`0x409b2` direkt87.
|
||||||
|
Der V5-Descriptor bei Offset`0x30` wird erst später betrachtet.
|
||||||
|
|
||||||
|
Das erklärt den ersten erreichbaren Verweigerungszweig der nativen
|
||||||
|
Descriptorprobe `4b1ae5cf…`: ihr tatsächlich vorhandener Discoveryprincipal
|
||||||
|
ist leer, `Sid=NULL` und Mutual Auth ist gesetzt. Ein Wechsel nur vom absoluten
|
||||||
|
zum selbstrelativen Descriptor würde diesen früheren Check nicht verändern.
|
||||||
|
Dies ist eine aus den unveränderten konkreten Eingabewerten und DLL-Bytes
|
||||||
|
abgeleitete statische Erklärung; keine nachträglich erfundene dynamische
|
||||||
|
Debuggeraufzeichnung des ursprünglichen Falls.
|
||||||
|
|
||||||
|
## Zusätzliche Descriptorverweigerung im OSF-Pfad
|
||||||
|
|
||||||
|
Auch ein nichtleerer erwarteter Principal löst den nächsten Blocker nicht:
|
||||||
|
|
||||||
|
- QOS5-Descriptor wird bei RVA`0x4099d` aus Offset`0x30` geladen und als letztes
|
||||||
|
Stackargument bei Caller-Offset`0x88` weitergereicht (RVA`0x40862`).
|
||||||
|
- Der virtuelle Aufruf benutzt Slot`0xd8`. Die tatsächliche
|
||||||
|
`OSF_BINDING_HANDLE`-Vtable bei RVA`0xdd408` verweist dort auf
|
||||||
|
`BINDING_HANDLE::SetAuthInformation`, RVA`0x7b110`.
|
||||||
|
- Dessen Prolog legt den Framepointer64Byte unter den vorherigen Callerstapel.
|
||||||
|
Somit bezeichnet `[rbp+0xc8]` genau das weitergereichte letzte Argument.
|
||||||
|
RVA`0x7b169` prüft dieses auf NULL; bei non-NULL führt RVA`0x7b170` unmittelbar
|
||||||
|
zu RVA`0x7b6a2`, Rückgabe87. Der Zweig liegt vor der Securityproviderarbeit.
|
||||||
|
|
||||||
|
Der hier verwendete verbindungsorientierte Named-Pipe-/OSF-Pfad nimmt folglich
|
||||||
|
keinen non-NULL-Serverdescriptor an, unabhängig von dessen Format. Die native
|
||||||
|
SID-/Descriptorprobe `bcda2ede…` mit fester SID und NULL-Principal ist mit diesem
|
||||||
|
weiteren Blocker konsistent. Nicht behauptet wird, ein Debugger habe genau
|
||||||
|
diesen Branch beim damaligen Prozess beobachtet. Ein isolierter
|
||||||
|
`MakeSelfRelativeSD`-Nachfolger oder ein weiterer Descriptorvergleich mit
|
||||||
|
anderem SPN würde diese Runtimeverweigerung nicht beseitigen.
|
||||||
|
|
||||||
|
## Tatsächliche Prüfung und verbleibende Grenze
|
||||||
|
|
||||||
|
GNU `objdump` wurde lokal auf der gesicherten DLL ausgeführt. Ein eigener
|
||||||
|
lokaler Analysereader prüft DLL-/PDB-Hashes, GUID sowie alle getrennten
|
||||||
|
Agewerte, öffentliche Symbolpositionen, den echten Vtableslot und neun enge
|
||||||
|
Instruktionsbytesfolgen. Er prüft zusätzlich die unveränderten131 ursprünglichen
|
||||||
|
Produktinputs,27 älteren Diagnosedateien und die vier eingefrorenen
|
||||||
|
Descriptorquellen. Der erste lokale Readerlauf verweigerte ausdrücklich am
|
||||||
|
unterschiedlichen PDB-Info-Age; die anschließende Fassung erhält diese
|
||||||
|
Abweichung und bindet DBI-Age/Adressen/Bytes getrennt. Linker-Absolute-Symbole
|
||||||
|
werden nicht als PE-Sektionsadressen behandelt.
|
||||||
|
|
||||||
|
Der abschließende statische Bericht `rpcrt4-qos5-static-analysis.json` hat
|
||||||
|
SHA256 `86328105c109e49f08b06bac9e33e1fc74c7debba88ac3951e565c63d0497a19`.
|
||||||
|
Kein neuer Native-, Build-, Identitäts-, Synchronisierungs- oder Clocknachweis
|
||||||
|
wird dadurch behauptet. Insbesondere bleiben der erfolgreiche reine
|
||||||
|
GSS9/Privacy6/Impersonate3-Statusabruf und die fehlende unabhängige Dienstbindung
|
||||||
|
getrennte Ergebnisse.
|
||||||
|
|
||||||
|
Ein vorher separat per Pipehandle beobachteter SCM-PID-/Tokenbeleg bindet
|
||||||
|
nicht automatisch die andere, vom RPC-Runtimehandle eröffnete Verbindung.
|
||||||
|
Er darf daher keinen Ersatz für die fehlende Dienstidentitätsbindung bilden.
|
||||||
|
Ein gleichwertiger, auf der tatsächlichen Verbindung wirksamer OS-Vertrag
|
||||||
|
ist noch offen; keine Lockerung auf bloße Discovery-, Mutual-Auth-Flags oder
|
||||||
|
CLI-Textinterpretation. Auch eine positive OS-Zeitsynchronisierung würde diese
|
||||||
|
unabhängige Identitätslücke alleine nicht schließen.
|
||||||
@@ -0,0 +1,197 @@
|
|||||||
|
# Isolierter Vergleich mit tatsächlich zurückgegebenem leerem Principal
|
||||||
|
|
||||||
|
Stand2026-11-14: neuer getrennter Diagnosenachfolger lokal gebaut/geprüft.
|
||||||
|
**Native Ausführung, separater Readback und Cleanup durch den Hauptagenten inzwischen erfolgt; der Subagent hat keine VM-/SSH-Aktion ausgeführt.**
|
||||||
|
Produktcode, Clockgate, ursprüngliche131Quellen sowie WINNT-/SYSTEM-/EEInfo- und
|
||||||
|
F6-SPNEGO-Proben bleiben unverändert und mit ihren ursprünglichen Treibern lesbar.
|
||||||
|
|
||||||
|
## Tatsächlicher Ausgangsbefund
|
||||||
|
|
||||||
|
Der ursprüngliche SPNEGO-Case
|
||||||
|
`0f512772-3599-4c83-b877-41c74fe50fb0` verwendet Manifest
|
||||||
|
`f6b5cd23b1599c2db4fc803fd7232dfd3522dead840e492f659e4efd7a6be001`.
|
||||||
|
Sein unveränderter `diagnostic-result.json` hat SHA256
|
||||||
|
`4c99b34b8c64f877dbbf0fe860d59499f1c054de7d036016e80b84581448cfc9`.
|
||||||
|
Der tatsächliche Bericht meldet Discovery1/Status0/normaler Return1,
|
||||||
|
Principalpointer vorhanden1 und UTF16-Länge0. Die eigene Nichtleerprüfung
|
||||||
|
verweigert dies mit123/Stage26, vor dem Authsetup und vor Opnum6; Statusaufrufe0.
|
||||||
|
Das ist kein Nachweis eines W32Time-Statusqueryfehlers.
|
||||||
|
|
||||||
|
Die eigene SYSTEM-Primärtokenprobe wurde vorher erhalten: kein Threadtoken,
|
||||||
|
SeSystemtimePrivilege vorhanden1, Attribute0, Enabled0. Das bleibt eine reine
|
||||||
|
Beobachtung; weder daraus noch aus dem Leerstring werden Workgroup-, Domain-,
|
||||||
|
Provider-, ACL- oder Privilegursachen abgeleitet. Readback und Cleanup des alten
|
||||||
|
Cases erfolgen ausschließlich durch den Hauptagenten mit dessen originalem
|
||||||
|
Treiber; dieser Nachfolger ersetzt keinen historischen Beleg.
|
||||||
|
|
||||||
|
## Primärquellen und Schlussgrenze
|
||||||
|
|
||||||
|
Die Microsoft-API beschreibt den zurückgegebenen Principal als vom RPC-Runtime
|
||||||
|
allokierte Zeichenfolge, die anschließend mit RpcStringFree freizugeben ist.
|
||||||
|
Eine zusätzliche Mindestlänge wird dort nicht festgelegt.
|
||||||
|
[RpcMgmtInqServerPrincNameW](https://learn.microsoft.com/en-us/windows/win32/api/rpcdce/nf-rpcdce-rpcmgmtinqserverprincnamew)
|
||||||
|
|
||||||
|
Die Syntax und Bedeutung des Authentifizierungs-Zielnamens bestimmt der
|
||||||
|
verwendete SSP. Das ist keine allgemeine Garantie, dass jeder SSP einen leeren
|
||||||
|
Namen akzeptiert.
|
||||||
|
[RpcBindingSetAuthInfoExW](https://learn.microsoft.com/en-us/windows/win32/api/rpcdce/nf-rpcdce-rpcbindingsetauthinfoexw)
|
||||||
|
|
||||||
|
Microsoft nennt Systemdienste, für die manche Provider keinen Principalnamen
|
||||||
|
führen, und warnt ausdrücklich vor Principaldiscovery als sicherem
|
||||||
|
Serveridentitätsnachweis. Ein erfolgreicher Discoveryaufruf oder ein weiter
|
||||||
|
gelungener Statusaufruf beweist hier deshalb keine unabhängig gepinnte
|
||||||
|
Serveridentität.
|
||||||
|
[Principal Names](https://learn.microsoft.com/en-us/windows/win32/rpc/principal-names)
|
||||||
|
|
||||||
|
MS-W32T AppendixB Fußnote16 beschreibt erfolgreiche Managementdiscovery und
|
||||||
|
danach den tatsächlich gelieferten Namen mit SPNEGO/PacketPrivacy. Sie fügt
|
||||||
|
keine Nichtleerbedingung hinzu. Die dort ebenfalls beschriebene unauthentisierte
|
||||||
|
Fallbackvariante wird hier ausdrücklich nicht implementiert. Fußnote33 beschreibt
|
||||||
|
eine zusätzliche Privilegprüfung aller authentisierten Methoden; sie erklärt
|
||||||
|
weder den jetzigen eigenen Stage26-Abbruch noch allein die Bedeutung von
|
||||||
|
Present/Enabled in unserem Tokenbefund.
|
||||||
|
[MS-W32T Appendix B, Fußnoten16/33](https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-w32t/bb576d39-587b-484a-86a4-e1d378cf9497)
|
||||||
|
|
||||||
|
Der engere Schluss ist daher lediglich eine begründete **Diagnosehypothese**:
|
||||||
|
die eigene Nichtleer-Zusatzprüfung einmal isoliert entfernen und die exakte
|
||||||
|
Runtimeantwort an den unveränderten SSP übergeben. Es wurde keine konkrete
|
||||||
|
Primärquellenpflicht gefunden, die genau diesen Diagnosevergleich verbietet.
|
||||||
|
Es wird weder universelle Leerstring-Zulässigkeit noch Produktionsfähigkeit
|
||||||
|
behauptet.
|
||||||
|
|
||||||
|
## Exakter neuer Scope
|
||||||
|
|
||||||
|
Vier neue Dateien unter `deploy/windows/clock-spnego-empty-trace/`:
|
||||||
|
|
||||||
|
- `clock_rpc_spnego_empty.c`: im vorhandenen UTF16-Prüfer entfällt allein das
|
||||||
|
`!i`-Verbot am terminierenden Nullzeichen. NULL-Pointer bleiben Fehler,
|
||||||
|
Hoch-/Niedrigsurrogate, Steuerzeichen und die512-Unit-Grenze bleiben geprüft.
|
||||||
|
Der tatsächlich von RpcMgmt gelieferte Pointer wird unverändert und nicht-NULL
|
||||||
|
an RpcBindingSetAuthInfoExW weitergereicht, auch wenn er auf eine leere
|
||||||
|
terminierte Zeichenfolge zeigt. Kein erfundener SPN und keine NULL-Ersetzung.
|
||||||
|
- `system_trace_spnego_empty.c`: gleiches Token-/RPC-/EEInfo-Verhalten;
|
||||||
|
ausschließlich getrennte Symbol-, Service-, Profil- und Casepfadnamen.
|
||||||
|
`own_system_token` ist byteidentisch zum Original.
|
||||||
|
- `native.py`: eigene Case-/Manifest-/Servicebindung; Ergebnisprüfung erlaubt
|
||||||
|
nun0..512Units nur bei weiterhin vorhandenem und geprüftem Principal.
|
||||||
|
Ohne erfolgreiche einzelne Discovery kein Statusaufruf.
|
||||||
|
- `build.py`: gleicher lokaler Compiler-/MIDL-/SDKpfad; bindet zusätzlich
|
||||||
|
unverändertes F6, dessen beobachteten Ausgangscase und alle vier alten
|
||||||
|
SPNEGO-Quellen. Der kleine direkte Eltern-Wrapperdiff wird separat erhalten.
|
||||||
|
|
||||||
|
Eigenes SCM-Serviceobjekt: `RmmClockSpnegoEmptyDiagnostic`; eigenes Profil:
|
||||||
|
`clock-system-spnego-empty-v1`; eigener Pfad:
|
||||||
|
`C:\ProgramData\RustDiscoveryBootstrap\clock-spnego-empty-trace-<UUID>`.
|
||||||
|
Originale Services/Cases werden weder adressiert noch ersetzt.
|
||||||
|
|
||||||
|
Unverändert bleiben GSS_NEGOTIATE9, PacketPrivacy6, Identify2, genau eine
|
||||||
|
Managementdiscovery und höchstens ein Opnum6 auf dem bereits bekannten
|
||||||
|
authentisierten W32TIME_ALT-Pfad. Fehler führen weder zu anderem SSP noch zu
|
||||||
|
anonymer oder unauthentisierter Wiederholung. Das unveränderte AuthIdentity-NULL
|
||||||
|
bedeutet die bestehende eigene Prozessidentität, keine neu gewählte anonyme
|
||||||
|
Identität. Die Principal-Pointer-Unterscheidung wird davon getrennt behandelt.
|
||||||
|
Maximal vier ausschließlich numerische EEInfo-Records, unmittelbare Aufnahme
|
||||||
|
vor weiterem RPC/Cleanup, keine Namen oder Parameterinhalte.
|
||||||
|
|
||||||
|
Vor RPC werden ausschließlich das eigene SYSTEM-Token und dessen vorhandene
|
||||||
|
Privileginformationen gelesen und als numerischer Beleg create-once geschrieben.
|
||||||
|
Kein AdjustTokenPrivileges, kein Impersonate, keine Uhr-, ACL-, Policy-, NTP-,
|
||||||
|
W32Time- oder RMM-Änderung. Ein temporärer Diagnoseservice ist ausschließlich
|
||||||
|
separate explizite Bootstrapwirkung des späteren Hauptagenten, kein RMM-Job.
|
||||||
|
Readback bleibt rein lesend; Cleanup ist ein separater expliziter Vorgang nur
|
||||||
|
für den gebundenen eigenen gestoppten Service. Nach Antwortverlust kein Startretry.
|
||||||
|
|
||||||
|
## Tatsächlicher lokaler Build
|
||||||
|
|
||||||
|
Buildcase:
|
||||||
|
`devstate/windows-clock-spnego-empty-trace/build-9daffc05-64d1-45c2-954a-4ec642c5ef70`.
|
||||||
|
Manifest-SHA256:
|
||||||
|
`768293c37702e40876a83bbab4a24186a3b4e284cf9a193c40550dd72ef32548`.
|
||||||
|
Windows-x64-PE `ClockSpnegoEmptyTrace.exe`:99727Bytes, SHA256
|
||||||
|
`7ca7cd51cc84678068f00d9ae5344a76485db6a600557757f925f6fcb3228fe5`.
|
||||||
|
|
||||||
|
Verwendet wurde dasselbe gepinnte Image1b2fd985… und die ursprüngliche
|
||||||
|
Microsoft-MIDL-Ausgabe aus149bafe2 mit Headerhashdb5dbe5b… und Stubhashd806adb4….
|
||||||
|
Keine Codegenerierung mit WIDL, kein Header- oder OUT_DIR-Patch. Beide eigenen
|
||||||
|
C-Units wurden mit Wall/Wextra/Werror übersetzt. Für die unveränderte tatsächliche
|
||||||
|
MIDL-Unit bleiben genau die bereits überprüften zwei sichtbaren Warnklassen
|
||||||
|
ohne Werror-Eskalation erhalten. Link, Strip, Importprüfung und echter
|
||||||
|
PowerShell-AST-Parse erfolgreich. EncodedCommand17146Zeichen, unter32767.
|
||||||
|
|
||||||
|
Die DLL-Importliste stimmt **exakt** mit F6 überein:
|
||||||
|
ADVAPI32.dll, KERNEL32.dll, RPCRT4.dll und msvcrt.dll. Alle131Originaldateien und
|
||||||
|
die elf bisherigen Diagnosequellen blieben beim Build byteidentisch; das
|
||||||
|
ursprüngliche F6-Manifest und sein Ergebnisbeleg sind zusätzlich gehasht gebunden.
|
||||||
|
Vorhandene Primärunterlagen-Snapshots wurden nicht verändert.
|
||||||
|
|
||||||
|
Der tatsächliche neue C-Prüfer wurde außerdem lokal mit einem temporären
|
||||||
|
uint16-Fixturetreiber ausgeführt: zehn Fälle einschließlich NULL, nicht-NULL
|
||||||
|
Leerstring, gültiger Surrogatfolge, ungültiger Unicode-/Steuerzeichen und
|
||||||
|
512/513Grenze bestanden. Die echte Python-Ergebnisprüfung wurde mit synthetischem
|
||||||
|
Empty-Query-Bericht geprüft und verweigerte neun Änderungen an Pointer-/Valid-
|
||||||
|
Status, Länge, Discovery-/Queryzahl, Authparametern und Tokenbefund. Das erzeugt
|
||||||
|
keinen Windows-RPC-Nachweis. Beleg `empty-local-guards.json`, SHA256
|
||||||
|
`9d276e59c3376be3e47cc2580238904ac76bfeda08e4665b2edd5ff39011362a`.
|
||||||
|
|
||||||
|
## Geplante native Fortsetzung, nicht ausgeführt
|
||||||
|
|
||||||
|
Erst nach unabhängigem Rootreview dieses Source-/Manifeststands:
|
||||||
|
|
||||||
|
```text
|
||||||
|
python3 deploy/windows/clock-spnego-empty-trace/native.py prepare --manifest ABSOLUTE_NEW_MANIFEST --access-root /home/kevin/Schreibtisch/Coding/rust-discovery --execute-native
|
||||||
|
python3 deploy/windows/clock-spnego-empty-trace/native.py start --manifest ABSOLUTE_NEW_MANIFEST --access-root /home/kevin/Schreibtisch/Coding/rust-discovery --id NEW_CASE --execute-native
|
||||||
|
python3 deploy/windows/clock-spnego-empty-trace/native.py readback --manifest ABSOLUTE_NEW_MANIFEST --access-root /home/kevin/Schreibtisch/Coding/rust-discovery --id NEW_CASE
|
||||||
|
python3 deploy/windows/clock-spnego-empty-trace/native.py cleanup --manifest ABSOLUTE_NEW_MANIFEST --access-root /home/kevin/Schreibtisch/Coding/rust-discovery --id NEW_CASE --execute-native
|
||||||
|
```
|
||||||
|
|
||||||
|
Der ursprüngliche0f512772-Case bleibt beim alten F6-Treiber. Der neue Vergleich
|
||||||
|
beansprucht weder Clock-/Adapterqualifikation noch Serveridentitätsnachweis,
|
||||||
|
Produktgate, Signier-/Jobrecht oder eine tatsächliche native Messung. Auch ein
|
||||||
|
eventueller RPC-Return0 wäre erst ein Diagnoseergebnis; die vollständige
|
||||||
|
Zeitvertrags- und Sicherheitsabnahme bliebe gesondert erforderlich.
|
||||||
|
|
||||||
|
|
||||||
|
## Tatsächlicher nativer Emptyvergleich 2026-11-14
|
||||||
|
|
||||||
|
Der Hauptagent hat ausschließlich den neuen Case
|
||||||
|
`5e0e8ce9-b9a3-4c4a-b739-3f84d714dc94` mit obigem unverändertem
|
||||||
|
Manifest768293c3… nativ ausgeführt. Der erhaltene Ergebnisbeleg
|
||||||
|
`diagnostic-result.json` hat SHA256
|
||||||
|
`c53378d5b6e1099a781bb007e2480609e4105b94498ce443df937a0a591ff307`.
|
||||||
|
Discovery1/Status0/Return1 liefert tatsächlich weiterhin einen nicht-NULL
|
||||||
|
Principal mit0UTF16-Units. Dieser wird unverändert akzeptiert und weitergegeben.
|
||||||
|
Danach wird genau eine Opnum6-Statusquery versucht. Ergebnis: RPCexception5,
|
||||||
|
Stage90, kein normaler RPCreturn und kein Statusobjekt. Der unmittelbar erfasste
|
||||||
|
numerische EEInfo-Befund enthält genau einen Record: Komponente2, Status5,
|
||||||
|
DetectionLocation1750, Flags0, Parameteranzahl1; Parameterinhalte werden nicht
|
||||||
|
gelesen. Eigenes SYSTEM-Primärtoken: Recht vorhanden1, Attribute0/Enabled0,
|
||||||
|
kein Threadtoken. Daraus folgt keine nachgewiesene Privileg-/ACL-/Providerursache.
|
||||||
|
|
||||||
|
Separater rein lesender Readback
|
||||||
|
`readback-03d099ce-a024-49c7-8a80-6c30f0228756.json`, SHA256
|
||||||
|
`7751477d29844f6f8b1e90f8c7322473014c631323aa5d88c54773445eb5f7ea`,
|
||||||
|
bestätigt den gleichen Bericht, den eigenen gestoppten Dienst und Exit0.
|
||||||
|
Exit0 bezeichnet den abgeschlossenen Diagnosebericht, keinen erfolgreichen
|
||||||
|
W32Time-Statusquery. Anschließend hat der Hauptagent den eigenen gestoppten
|
||||||
|
Diagnosedienst getrennt bereinigt. Cleanupreceipt
|
||||||
|
`readback-8786048c-06a9-43f1-bede-b62a1ef21e22.json`, SHA256
|
||||||
|
`1eb2fdef2aef832973897bd4bb6c01f459ab30e544c603e6feb81e1a318b3bb1`,
|
||||||
|
meldet cleanup_verified=true und already_absent=false.
|
||||||
|
|
||||||
|
Readback und eigenes Cleanup sind damit nachgewiesen. Nach dem separaten
|
||||||
|
ScopeClose hat der Hauptagent auch den After-Preservationvergleich gewonnen:
|
||||||
|
`rust-discovery-windows-pipe-drain/devstate/windows-client/system-pipe-upgrade/14fb176a-f653-4573-a8d7-6f9fe47a3020/spnego-empty-trace-after.json`, SHA256
|
||||||
|
`a8ab4396c1c8ed4fa2f0f3b06434efb0ecb058865c69aeba278744a850dd910f`.
|
||||||
|
Alle sechs nativen Bereiche `service`, `helper_service`, `agent_kernel`,
|
||||||
|
`helper_kernel`, `files` und `helper_witness` sind exakt zum Before unverändert.
|
||||||
|
Serverflags bleiben gleich, Rootpolicycf15 geschlossen, Hooksfalse; die
|
||||||
|
Windows-spezifischen Job-/Outbox-/Permit-/Unresolved-Zähler bleiben0/0/0/0.
|
||||||
|
|
||||||
|
Die global beobachteten Linux-Serverzähler sind ausdrücklich nicht unverändert:
|
||||||
|
30/30/26 wurden31/31/27, weiterhin unresolved0. Der Hauptagent belegt dies durch
|
||||||
|
den parallel tatsächlich über MCP beantragten und in der WebUI genehmigten
|
||||||
|
Linux-Fullscript-Caseced97b4d mit bestandenem Ergebnisbeleg89dcb583….
|
||||||
|
Diese autorisierte parallele Wirkung wird nicht als Wirkung der Emptyprobe oder
|
||||||
|
als globale Preservationgleichheit dargestellt. Der Empty-Abnahmeschritt ist als
|
||||||
|
Diagnose abgeschlossen; sein Ergebnis bleibt RPC5. Clock-/Adapterqualifikation,
|
||||||
|
Serveridentität und Produktgate bleiben nicht nachgewiesen/geschlossen.
|
||||||
@@ -0,0 +1,169 @@
|
|||||||
|
# Isolierter SPNEGO-/Privilegdiagnosevergleich
|
||||||
|
|
||||||
|
Stand2026-11-14: separat implementiert, lokal gebaut/geprüft; **keine VM-Aktion
|
||||||
|
durch diesen Subagenten**. Kein Produktclockgate, kein neuer Agentadapter und
|
||||||
|
keine Änderung der ursprünglichen WINNT-/LocalService-/SYSTEM-/EEInfo-Proben.
|
||||||
|
Die tatsächlichen früheren Vergleiche bleiben RPC5/Stage90 ohne normalen Return
|
||||||
|
oder Status. Ihr einzelner Runtime-EEInfo-Record mit Detection1750 beweist keine
|
||||||
|
bestimmte ACL-, Privileg- oder Anonymitätsursache.
|
||||||
|
|
||||||
|
## Primärbefund und begrenzte Hypothese
|
||||||
|
|
||||||
|
[MS-W32T AppendixB, Fußnoten16/32/33](https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-w32t/bb576d39-587b-484a-86a4-e1d378cf9497)
|
||||||
|
beschreibt den Windowsclient mit Principalabfrage für SPNEGO und anschließend
|
||||||
|
GSS_NEGOTIATE/PacketPrivacy. W32Time prüft bei allen authentisierten Methoden
|
||||||
|
zusätzlich das Systemzeitänderungsrecht. Der bisherige feste WINNT-/NULL-
|
||||||
|
Principalpfad unterscheidet sich davon. Dies begründet einen Diagnosevergleich,
|
||||||
|
keine erwiesene Fehlerursache und keine Erlaubnis, Produktprüfungen zu lockern.
|
||||||
|
|
||||||
|
[LocalSystem](https://learn.microsoft.com/en-us/windows/win32/services/localsystem-account)
|
||||||
|
besitzt `SeSystemtimePrivilege` standardmäßig deaktiviert. Zusätzlich kann SCM
|
||||||
|
bei ausdrücklich eingeschränkten
|
||||||
|
[RequiredPrivileges](https://learn.microsoft.com/en-us/windows/win32/api/winsvc/ns-winsvc-service_required_privileges_infow)
|
||||||
|
nicht benötigte Privilegien vollständig entfernen. SID18 bedeutet daher weder
|
||||||
|
„vorhanden“ noch „aktiviert“. Die eigene neue Diagnose verwendet einen separaten
|
||||||
|
SCM-Dienst; sie beweist keinen identischen Token des Produkthelpers. Kein
|
||||||
|
RequiredPrivileges-, Konto-, SID-, ACL-, NTP- oder Maschinenrichtlinienwechsel.
|
||||||
|
|
||||||
|
## Exakte neue Sourcegrenze
|
||||||
|
|
||||||
|
Vier eigene sibling-Inputs unter `deploy/windows/clock-spnego-trace/`:
|
||||||
|
`clock_rpc_spnego.c`, `system_trace_spnego.c`, `build.py`, `native.py`.
|
||||||
|
Eigener temporärer Dienst `RmmClockSystemSpnegoDiagnostic`, eigener Casepfad und
|
||||||
|
eigene create-only History. Die131 ursprünglichen Quellen und sieben bestehenden
|
||||||
|
SYSTEM-/WINNT-/EEInfo-Diagnoseinputs werden vor/nach dem Build gehasht und müssen
|
||||||
|
unverändert bleiben. Neuer Wrapperdiff gegen Original74aceb6e wird erhalten;
|
||||||
|
das tatsächliche Microsoft-MIDL-Header-/Stubpaar bleibt byteidentisch.
|
||||||
|
|
||||||
|
Vor dem ersten RPC-Aufruf liest die Hülle ausschließlich den eigenen Token mit
|
||||||
|
TOKEN_QUERY. Primärer SID18-Token ist Pflicht; ein vorhandener Threadtoken oder
|
||||||
|
ein anderer Tokenfehler beendet den Versuch, ohne Impersonation/Revert. Fester
|
||||||
|
Lookup von `SeSystemtimePrivilege`, höchstens256 SDK-`LUID_AND_ATTRIBUTES` in
|
||||||
|
4096Bytes; SDK-Buffermengen werden geprüft. Vorhandensein, rohe Attribute,
|
||||||
|
Enabled/EnabledByDefault/Removed und numerische APIfehler werden getrennt
|
||||||
|
erhalten. `token.json` wird create-only und fsync-gesichert **vor** dem fremden
|
||||||
|
RPC-Code geschrieben. Fehlendes/deaktiviertes Privileg wird beobachtet; die
|
||||||
|
Diagnose aktiviert oder vergibt es nicht. Keine Passwort-/Credentialabfrage,
|
||||||
|
kein AdjustTokenPrivileges oder sonstiger Tokenänderungsaufruf.
|
||||||
|
|
||||||
|
Der feste lokale `ncacn_np`-Endpunkt bleibt `\\pipe\\W32TIME_ALT`. Calltimeout1500ms
|
||||||
|
wird vor der Principalabfrage gesetzt. Genau eine
|
||||||
|
[RpcMgmtInqServerPrincNameW](https://learn.microsoft.com/en-us/windows/win32/api/rpcdce/nf-rpcdce-rpcmgmtinqserverprincnamew)-Abfrage
|
||||||
|
für GSS_NEGOTIATE darf stattfinden. Diese Managementabfrage ist gesondert gezählt;
|
||||||
|
sie ist keine W32Time-Statusabfrage. Nur APIstatus0, Nonnull und ein binnen512
|
||||||
|
UTF16-Einheiten NUL-terminierter, nicht leerer und strukturell gültiger String
|
||||||
|
ohne C0/C1-Steuerzeichen darf an SetAuthInfoEx weitergegeben werden. Strings,
|
||||||
|
Principalname, Parameterwerte oder Pointer werden niemals ausgegeben. Die API
|
||||||
|
allokiert den String intern; die512-Grenze beschränkt Prüfung/Weiterverwendung,
|
||||||
|
**keine behauptete Vorabgrenze der internen RPC-Allokation**.
|
||||||
|
|
||||||
|
Danach ausschließlich GSS_NEGOTIATE, PacketPrivacy, IDENTIFY, statische implizite
|
||||||
|
eigene Credentials und genau dieser Principal. Kein NULL-, WINNT-, anonymer oder
|
||||||
|
anderer Auth-/Transportfallback. Die erwartete Identität des Servers wird dadurch
|
||||||
|
nicht unabhängig bewiesen; der vom Endpunkt gelieferte Principal ist ausschließlich
|
||||||
|
Diagnoseeingabe. Kein Produkt-Trust, Konto-/Service-SID-Beweis oder persistierter
|
||||||
|
Identitypin entsteht daraus.
|
||||||
|
|
||||||
|
Höchstens eine tatsächliche Opnum6-Invocation; bei fehlender Discovery,
|
||||||
|
Stringprüfung oder Auth-/Arenafehler auch null. Der Zähler steht unmittelbar vor
|
||||||
|
dem echten generierten Methodenaufruf. Unveränderte Größen-/Statusprüfung und
|
||||||
|
64KiB-Arena, begrenztes numerisches EEInfo mit höchstens vier Records. Ursprung
|
||||||
|
der EEInfo wird numerisch zwischen Discovery, SetAuth und Status unterschieden.
|
||||||
|
Originale Fehlercodes werden vor jedem Cleanup erhalten. Principal wird auf
|
||||||
|
jedem vorhandenen Pfad mit RpcStringFreeW freigegeben, danach BindingFree; beide
|
||||||
|
Cleanupstatuses sind eigene Zahlen. Kein Probe-Retry.
|
||||||
|
|
||||||
|
Neue Phasen25/26 kennzeichnen Discovery/Stringprüfung,91 eine enthaltene
|
||||||
|
Discoveryexception;90 bleibt eine Status-RPCexception. Ein Diagnose-Serviceexit0
|
||||||
|
heißt ausschließlich Bericht geschrieben. `clock_qualified`, `adapter_qualified`
|
||||||
|
und `product_gate_open` bleiben stets false, auch wenn künftig ein Status käme.
|
||||||
|
|
||||||
|
## Build und geplanter Zielablauf
|
||||||
|
|
||||||
|
Der bekannte Offlinebuilder wird mit read-only Quellmount verwendet. Hülle und
|
||||||
|
Wrapper mit `-Wall -Wextra -Werror`; nur die drei unveränderten bekannten
|
||||||
|
MIDL-Stilwarnungen bleiben sichtbar. Keine Typ-/Securitywarnungsunterdrückung.
|
||||||
|
Nur bisherige ADVAPI32/KERNEL32/RPCRT4/msvcrt-Imports; kein neues SDK, Broker,
|
||||||
|
WMI- oder Produktfeature. Benötigte RpcMgmt-/GSS-/Tokenbindings wurden im
|
||||||
|
vorhandenen Builderheader tatsächlich gelesen, keine eigenen ABIdeklarationen.
|
||||||
|
|
||||||
|
Der frühere lokale Pack153a1030 enthält den ersten vollständig gebauten Stand,
|
||||||
|
noch vor zusätzlichen strikten Reportkonsistenzchecks. Er bleibt historisch
|
||||||
|
erhalten und wird nicht für eine VM-Probe verwendet. Der finale separate Pack
|
||||||
|
ist nach diesen Checks erneut quellgebunden bereitgestellt. Keine native
|
||||||
|
Ausführung oder Produktqualifikation ist ein Ergebnis des Builders.
|
||||||
|
|
||||||
|
Geplant, nicht ausgeführt: Rootreview, unveränderte vorherige Preservationzeugen,
|
||||||
|
einmaliges Prepare/Upload und genau ein Start über den vorhandenen geprüften
|
||||||
|
Bootstrapweg. Der Reader liest nur den ursprünglichen Case einschließlich des
|
||||||
|
vor RPC gespeicherten Tokenzeugen. Antwortverlust erlaubt nur Readback, keinen
|
||||||
|
erneuten Start. Cleanup ist eine getrennte explizite Phase ausschließlich für
|
||||||
|
den eigenen nachgewiesen gestoppten, exakt gebundenen Diagnosedienst; Dateien
|
||||||
|
und Originalbelege bleiben erhalten. Anschließend eigene Preservationprüfung
|
||||||
|
von RMM-/W32Time-Prozessen, Kontrollen, FileIDs/PKI/DB/Serverzustand. Keine
|
||||||
|
W32Timeänderung, kein RMM-Job und keine WebUI-Genehmigungsabkürzung.
|
||||||
|
|
||||||
|
## Tatsächliche lokale Guards
|
||||||
|
|
||||||
|
Die tatsächliche Reportprüffunktion akzeptierte ausdrücklich synthetische
|
||||||
|
SYSTEM-RPCfehler- und Discoveryfehler-ohne-Query-Belege und verweigerte15
|
||||||
|
unabhängige Manipulationen von Aufrufzahl, Authstärke, Impersonation, Privileg-
|
||||||
|
Attributen, Tokenzeugen, Principal-/Parameterstrings, EEInfo-Ursprung und Gates.
|
||||||
|
Die tatsächliche extrahierte C-Principalprüffunktion wurde lokal mit leerem/
|
||||||
|
fehlendem Namen, gepaarten/ungepaarten Surrogaten, C1-Steuerzeichen sowie exakt512
|
||||||
|
und513Einheiten kompiliert und ausgeführt. Dies sind reine lokale Guards,
|
||||||
|
keine echten Token-/RPC-/Clock- oder VM-Ergebnisse.
|
||||||
|
|
||||||
|
Der finale Pack liegt unter
|
||||||
|
`devstate/windows-clock-spnego-trace/build-2ebcfe9c-1e2b-4a50-99c5-3370640aeb77/`.
|
||||||
|
Manifest-SHA256
|
||||||
|
`f6b5cd23b1599c2db4fc803fd7232dfd3522dead840e492f659e4efd7a6be001`;
|
||||||
|
PE99721Bytes, SHA256
|
||||||
|
`ce11b0f0c400160b1580e8f68666530eaa324626a557a267ad684dc069cf2fba`.
|
||||||
|
Alle ursprünglichen131 und sieben früheren Diagnoseinputs bleiben unverändert.
|
||||||
|
Aktueller PowerShell-AST-Parser bestanden; EncodedCommand17122Zeichen.
|
||||||
|
Hülle/Wrapper ohne Warnungen unter `-Werror`; unveränderter Microsoftstub mit
|
||||||
|
genau den drei bekannten sichtbaren Stilwarnungen. Imports ausschließlich
|
||||||
|
ADVAPI32/KERNEL32/RPCRT4/msvcrt. Der tatsächliche PE-Importdump enthält keine
|
||||||
|
Token-/Privileg-/Uhränderungsimporte.
|
||||||
|
|
||||||
|
Die aktuelle strengere Reportprüffunktion wurde anschließend erneut mit zwei
|
||||||
|
synthetischen gültigen Fehlerbelegen und **16** unabhängigen Manipulationen
|
||||||
|
ausgeführt, einschließlich einer Boolzahl statt numerischem Aufrufzähler.
|
||||||
|
Die tatsächliche extrahierte C-JSONformatierfunktion wurde lokal mit kleinem
|
||||||
|
Fehlerbericht und maximalen32Bit-Zahlen/vier EEInfo-Records kompiliert und
|
||||||
|
ausgeführt; beide Berichte waren gültiges JSON, höchstens2074Bytes. Sie ersetzt
|
||||||
|
keine native Windowsausführung. `local-guards.json` im finalen Pack kennzeichnet
|
||||||
|
`native_executed=false` und `target_called=false`. Kein Zielaufruf oder Gitaktion
|
||||||
|
durch diesen Subagenten; der Pack ist ausschließlich für Rootreview vorbereitet.
|
||||||
|
|
||||||
|
|
||||||
|
## Tatsächliche isolierte Windows-Probe
|
||||||
|
|
||||||
|
Root hat den finalen Pack im separaten Fall
|
||||||
|
`0f512772-3599-4c83-b877-41c74fe50fb0` einmal gestartet. Das ursprüngliche
|
||||||
|
Resultat (SHA256 `4c99b34b8c64f877dbbf0fe860d59499f1c054de7d036016e80b84581448cfc9`)
|
||||||
|
wurde zusätzlich getrennt identisch zurückgelesen. Eigener gestoppter
|
||||||
|
Diagnosedienst anschließend explizit entfernt; kein Start/Stop an W32Time oder
|
||||||
|
RMM-Diensten und keine Privilegaktivierung.
|
||||||
|
|
||||||
|
Tatsächlich: eigenes SYSTEM-Primarytoken ohne Threadtoken, Systemzeitprivileg
|
||||||
|
vorhanden, Attribute0, enabled0/default0/removed0. Genau eine Principaldiscovery
|
||||||
|
mit Status0 und nichtleerem Zeiger, aber **Stringlänge0**. Deshalb verweigerte
|
||||||
|
der eigene Nonempty-Guard mit123/Stage26; es gab **keine** Opnum6-Abfrage,
|
||||||
|
keinen Status, keine RPCexception und keinen EEInfo-Record.123 ist in diesem
|
||||||
|
Fall das eigene Guardergebnis, kein W32Time-Status und keine neue Bestätigung
|
||||||
|
der Ursache des vorherigen RPC5.
|
||||||
|
|
||||||
|
Vorher-/Nachher-Erhaltung der tatsächlichen RMM-Prozessgeburten/Codehashes,
|
||||||
|
Dienste, FileIDs, PKI-/DBzeugen und des Serverzustands bestanden; Vorher-SHA256
|
||||||
|
`c4704d1b1ce0bbb7f7e3c062274167fa2031e7a78652acfd535d31af725f720d`,
|
||||||
|
Nachher-SHA256 `e69960b20dd96e3c5c1b667ad1cc0a41fb0d0bb623e8d3f03fcf99398fc43f61`.
|
||||||
|
Windows0Jobs/Outbox/Grants/ungeklärt, Linux30/30/26/0; Clockgate bleibtfalse.
|
||||||
|
|
||||||
|
Microsoft beschreibt die Principal-Syntax als SSP-abhängig und nennt
|
||||||
|
[Systemdienste ohne Principalnamen](https://learn.microsoft.com/en-us/windows/win32/rpc/principal-names).
|
||||||
|
Das beweist weder eine konkrete Workgroupkonfiguration noch eine RPC5-Ursache.
|
||||||
|
Die Discovery ist laut derselben Quelle kein sicherer Serveridentitätsnachweis.
|
||||||
|
Ein begrenzter separater Diagnosevergleich für den tatsächlich zurückgegebenen
|
||||||
|
leeren String wird vorbereitet; Originalfall und Quelle bleiben unverändert.
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
# Numerische Windows-Zeitdienstdiagnose
|
||||||
|
|
||||||
|
Stand2026-11-14: Diagnosequelle implementiert und unabhängig vom Produktions-
|
||||||
|
Clockpfad gebaut. Keine Lockerung von Statusguard, ALPC-/Identitätsprüfung,
|
||||||
|
`NativeClock.now()` oder `ADAPTER_QUALIFIED=false`. Keine neue Clockauthority.
|
||||||
|
Die feste zusätzliche Named-Pipe-Statusabfrage liefert ausschließlich acht
|
||||||
|
numerische Felder: Phase, tatsächliche RPC-Rückgabe samt Presenceflag,
|
||||||
|
aufgefangene Ausnahme und Strukturgrößen-/Zeigerpräsenz. Keine Quellen-/Peer-
|
||||||
|
Namen, Pointerwerte oder zusätzlichen Rückgabeeinträge werden veröffentlicht.
|
||||||
|
Eigener begrenzter Diagnoseworker; nach Timeout kein Ersatz/Retry.
|
||||||
|
|
||||||
|
Lokal tatsächlich bestanden: Windows-Example-Clippy mit Warnungen als Fehler,
|
||||||
|
fünf Linux-Clocktests, Windows-Testlink (nicht nativ ausgeführt) und Release-
|
||||||
|
Link.125Quellinputs vorher/nachher identisch. Originale Werkzeugabweichung
|
||||||
|
(Buildimage ohne WIDL) privat erhalten; erfolgreicher Build mit vorhandenem
|
||||||
|
unveränderlichem Clockimage. Artefakt `ecad703ad7208d55681c63ba9513fcf4c73b671951d4d1b5db1af9df49f43bdf`,
|
||||||
|
1779541Bytes. Privater Build `release-ca9a63b8-127c-4933-a45d-9e82449d6980`,
|
||||||
|
Qualifikation `36ce552e…`.
|
||||||
|
|
||||||
|
Danach tatsächlich auf der Windows-VM unter dem separaten LocalService-
|
||||||
|
Bootstrapdienst ausgeführt, Fall `2996df8c-b261-466a-8963-a526babf7f67`.
|
||||||
|
NativeReport und getrennter Readback identisch, eigener Dienst entfernt.
|
||||||
|
ALPC weiter1753/kein Endpunkt, keine erfolgreichen Identitätsnegativkontrollen.
|
||||||
|
Zusätzliche unabhängige Abfrage:1783, `stage=90`, `rpc_exception=1783`,
|
||||||
|
`native_rpc_return_present=0`, `status_present=0`. **Eine aufgefangene RPC-/
|
||||||
|
NDR-Ausnahme vor normaler Stub-Rückkehr ist belegt; der eigene nachgelagerte
|
||||||
|
Strukturguard wurde nicht erreicht.** Das Nullwertfeld `native_rpc_return=0`
|
||||||
|
ist ohne Presenceflag ausdrücklich kein erfolgreicher nativer Return.
|
||||||
|
|
||||||
|
Die genaue RPC-/NDR-Ursache bleibt offen. Source-/IDL-Prüfung folgt anhand
|
||||||
|
des [Microsoft-IDL](https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-w32t/5793e908-22ef-4cea-962f-fca8a72c485a).
|
||||||
|
W32Time wurde für diese Diagnose nicht umkonfiguriert, keine Uhr gesetzt und
|
||||||
|
kein RMM-Job ausgeführt. Zentrale Windows0/0/0/0 und Linux30/30/26/0 samt
|
||||||
|
geschlossenen Testhooks/Rootpolicy erhalten. Dieses Ergebnis qualifiziert
|
||||||
|
weder Named-Pipe-Serveridentität noch eine vertrauenswürdige Uhr. Erst recht
|
||||||
|
öffnet es keinen Grant-/Jobpfad.
|
||||||
|
|
||||||
|
## Enger WIDL-Zeigervertrag: lokal korrigierter Kandidat
|
||||||
|
|
||||||
|
Die erhaltene generierte WIDL7-Typbeschreibung kodiert den ursprünglichen
|
||||||
|
Status-Ausgabeparameter als `FC_RP→FC_RP→STATUS`. Der dokumentierte Vertrag
|
||||||
|
verlangt außen eine Referenz, innen den Unique-Statuspointer. Auch die neu aus
|
||||||
|
Microsofts vollständigem IDL erzeugte WIDL7-Datei zeigt den doppelten Ref:
|
||||||
|
Es handelt sich präziser um die rekursive Parameterattributbehandlung dieses
|
||||||
|
Compilers, nicht lediglich um eine andere Schreibweise unseres Narrow-IDL.
|
||||||
|
[Pointerregeln](https://learn.microsoft.com/en-us/windows/win32/rpc/three-pointer-types),
|
||||||
|
[Typformat](https://learn.microsoft.com/en-us/windows/win32/rpc/pointers-tfs),
|
||||||
|
[WIDL7-Compilerquelle](https://raw.githubusercontent.com/wine-mirror/wine/wine-7.0/tools/widl/typegen.c).
|
||||||
|
|
||||||
|
Der enge Kandidat deklariert den inneren Typ ausdrücklich `[unique]` und lässt
|
||||||
|
das redundante äußere `[ref]` zugunsten des dokumentierten Parameterdefaults
|
||||||
|
weg. WIDL erzeugt tatsächlich `FC_RP→FC_UP→STATUS`; kein Stubbyte wurde gepatcht.
|
||||||
|
Ganze Procedureformatfolge/Opnum6 unverändert, alle19Statusfeldoffsets und120B-
|
||||||
|
Struktur gegen frisch erzeugte Microsoft-Full-IDL-Header per AMD64-Clangassert
|
||||||
|
geprüft. C/Auth/Statusguard/Clockgate unverändert. MicrosoftMIDL wurde mangels
|
||||||
|
nativer Werkzeuge ausdrücklich noch nicht ausgeführt.
|
||||||
|
|
||||||
|
Neuer privater Buildfall `f5805176-4a5a-468d-b1b2-088030253c8d`, Qualifikation
|
||||||
|
`e96baaf6…`:63Compilerinputs vorher/nachher gleich, fünf Clocktests tatsächlich
|
||||||
|
bestanden, beide WindowsGNU-Alltargets-Clippyprofile, Release- und Unitlink
|
||||||
|
bestanden. Ein zunächst0Tests selektierender Aufruf und ein falscher lokaler
|
||||||
|
Harnesslink bleiben als unvollständige Vorgängerlogs erhalten. Neues Artefakt
|
||||||
|
`91889303e1650d8612b946512f069a3421eb686c7bed315426c48bd62b18a1fd`,
|
||||||
|
Original-Linkdatei erhalten. Nur `native/w32time.idl` geändert, SHA `37da4acb…`.
|
||||||
|
|
||||||
|
**Native Prüfung dieses Kandidaten noch nicht ausgeführt.** Der tatsächliche
|
||||||
|
Auslöser der bisherigen1783-Ausnahme ist damit weiter nicht bewiesen. Kein
|
||||||
|
Clockvertrauen aus Codegenerierung oder lokalem Build, keine Rückstufung vom
|
||||||
|
unqualifizierten ALPC-Pfad auf eine nur vermeintlich authentisierte Pipe.
|
||||||
@@ -0,0 +1,142 @@
|
|||||||
|
# Getrennter SYSTEM-Vergleich für die W32Time-RPC-Diagnose
|
||||||
|
|
||||||
|
Stand 2026-11-14: **implementiert und lokal gebaut, nicht auf der VM ausgeführt**.
|
||||||
|
Der User-/Orchestratorauftrag erlaubt hier ausschließlich einen neuen separaten
|
||||||
|
SID18-Diagnosedienst mit genau einem lesenden Traceaufruf. Bestehende Readiness,
|
||||||
|
RPC-/Clock-Produktquellen und sämtliche131 bisherigen Buildinputs bleiben
|
||||||
|
unverändert. Keine Produktgate-/Policy-/Konto-/NTP-/W32Time-ACLänderung.
|
||||||
|
|
||||||
|
Ausgangsbefund ist der tatsächlich ausgeführte LocalService-MIDL-Diagnosefall
|
||||||
|
`94562d81-f75f-45c8-ab6b-28b70d12bd81`: Named Pipe meldete RPC5/Stage90 ohne
|
||||||
|
Status, ALPC weiterhin1753. Der Unterschied zu früher1783 ist kein positiver
|
||||||
|
Status-/Clocknachweis. Microsoft beschreibt unterschiedliche Netzwerkidentitäten
|
||||||
|
für [LocalService](https://learn.microsoft.com/en-us/windows/win32/services/localservice-account)
|
||||||
|
und [LocalSystem](https://learn.microsoft.com/en-us/windows/win32/services/localsystem-account).
|
||||||
|
Dies begründet den Vergleich, beweist aber keine konkrete Ursache. Auch ein
|
||||||
|
abweichendes SYSTEM-Ergebnis unterscheidet für sich weder SSPI-Credentials von
|
||||||
|
serverseitiger Token-/ACLautorisierung noch schließt es alle Harnessunterschiede
|
||||||
|
aus. Der ALPC-Endpunktbefund bleibt eine eigene offene Frage.
|
||||||
|
|
||||||
|
## Enger neuer Quellschnitt
|
||||||
|
|
||||||
|
Nur neue Dateien unter `deploy/windows/clock-system-trace/`:
|
||||||
|
|
||||||
|
- `system_trace.c`: eigenständige einmalige SCM-Servicehülle
|
||||||
|
`RmmClockSystemDiagnostic`; prüft den tatsächlichen eigenen Prozesstoken mit
|
||||||
|
`OpenProcessToken`/`GetTokenInformation`/`IsWellKnownSid` auf SYSTEM und ruft
|
||||||
|
danach exakt einmal `rmm_clock_query_trace` auf. Kein Tokenwechsel und keine
|
||||||
|
Impersonation. Numerische RPC-/Tracefelder, feste Booleans und Fall-ID;
|
||||||
|
Ausgabedatei create-only, begrenzt und dauerhaft geflusht.
|
||||||
|
- `build.py`: eigenständiger Offline-C-Build mit originalem `clock_rpc.c` und
|
||||||
|
exakt denselben tatsächlich von Microsoft-MIDL erzeugten Header-/Stubbytes
|
||||||
|
aus Fall `149bafe2-3469-4580-b133-988812bcc3db`. Keine NDR-/Headerbearbeitung,
|
||||||
|
kein WIDL-Fallback und kein Patch im alten Build-/OUT_DIR.
|
||||||
|
- `native.py`: Root-Orchestrator mit getrennten expliziten Phasen `prepare`,
|
||||||
|
`start`, `readback`, `cleanup`. Vor Start dauerhaftes einmaliges Intent;
|
||||||
|
verlorener Reply erlaubt nur ursprüngliches Readback. Remote-Readback liest
|
||||||
|
ausschließlich, ändert weder ACLs noch Servicezustand und bereinigt nichts.
|
||||||
|
Cleanup darf ausschließlich den eindeutig gebundenen **gestoppten eigenen**
|
||||||
|
Diagnosedienst löschen. Alle Dateien/Originalbelege bleiben erhalten.
|
||||||
|
|
||||||
|
Die vorhandene ReadinessEXE verweigert SYSTEM weiterhin absichtlich; sie wird
|
||||||
|
weder verändert noch als Launcher eingesetzt. C-Wrapper, Named-Pipe-Endpunkt,
|
||||||
|
WINNT/PacketPrivacy und QoS bleiben identisch zur bisherigen Diagnose. Das
|
||||||
|
Programm bewertet keinen Clockstatus und setzt `clock_qualified=false`,
|
||||||
|
`adapter_qualified=false`, `product_gate_open=false` auch bei RPC0.
|
||||||
|
|
||||||
|
## Tatsächlich lokale Prüfungen
|
||||||
|
|
||||||
|
```text
|
||||||
|
python3 deploy/windows/clock-system-trace/build.py
|
||||||
|
```
|
||||||
|
|
||||||
|
Gepinntes Image `sha256:1b2fd985d2c1fcc3545ace602405dc68fa899201bd8a73fa319ff96377203fa9`,
|
||||||
|
Netzwerk deaktiviert, Quellsnapshot nur lesbar, eigenes Ausgabe-/Belegverzeichnis.
|
||||||
|
Neue C-Hülle und unveränderter Wrapper bestanden Clang `-Wall -Wextra -Werror`.
|
||||||
|
Für den unveränderten generierten MIDL-Stub bleiben nur dieselben drei bekannten
|
||||||
|
Stilwarnungen sichtbar: fehlende Initialisierungsbrace und zwei unbenutzte
|
||||||
|
Konstanten; keine Typ-/Securitywarnung wurde abgeschaltet. MinGW-GCC-Link,
|
||||||
|
PE-x64-/Größen-/Importprüfung und tatsächlicher PowerShell-AST-Lauf bestanden.
|
||||||
|
Der fertige EncodedCommand umfasst16666Zeichen und liegt unter32767.
|
||||||
|
|
||||||
|
Aktueller Manifest:
|
||||||
|
`devstate/windows-clock-system-trace/build-8b5fc22c-3dbe-4924-a431-9e889d6a4b7c/manifest.json`,
|
||||||
|
SHA256 `3b2c397eec9f3aa4a1e82ba10f2812f986c9b7e69e235c8f105ebaec221eaf5e`.
|
||||||
|
Standalone-PE98028Bytes, SHA256
|
||||||
|
`0035fee43333b7cb8d34e70b9c53b31dae49e4793abb0f1e00271572c75b7922`.
|
||||||
|
Beobachtete Imports ausschließlich `ADVAPI32.dll`, `KERNEL32.dll`, `RPCRT4.dll`,
|
||||||
|
`msvcrt.dll`. `kernel32` wird vor `mincore` aufgelöst; dieser C-Trace benötigt
|
||||||
|
keine zusätzlichen präzisen Zeit-APIimporte der Rust-Readinesshülle.
|
||||||
|
Das sind Builddaten, noch kein nativer Loader-/RPCbeleg.
|
||||||
|
|
||||||
|
Erhaltene frühere lokale Fälle werden nicht umgeschrieben: `58611089…`
|
||||||
|
scheiterte am Clang-Linkerpfad zu GCC-Runtimearchiven; `b900df4d…` wurde wegen
|
||||||
|
zusätzlicher aus `mincore` aufgelöster API-Set-Imports verweigert; der zunächst
|
||||||
|
fertig gebaute Pack `4d49b432…` scheiterte im nachfolgenden privaten
|
||||||
|
Manifestguard am Docker-root-eigenen Linkartefakt. Der neue Pack erhält nun
|
||||||
|
zusätzlich eine bytegleiche, vom Aufrufer besessene private Originalkopie.
|
||||||
|
Keine dieser Korrekturen verändert C/Auth/MIDL oder bestehende Produktdateien.
|
||||||
|
|
||||||
|
Sechs manipulierte Berichtsfälle, nur numerische Ausgabe, historischer Bericht
|
||||||
|
nach gebundenem Cleanup und Readback ohne Upload/Start/Cleanup wurden lokal
|
||||||
|
mit ausdrücklich **simulierten** Transport-/Reportdaten geprüft.
|
||||||
|
`local-guards.json` beim aktuellen Manifest kennzeichnet `simulated_reports_only`,
|
||||||
|
`ssh_executed=false`, `native_executed=false`. Das ist keine simuliert als echt
|
||||||
|
ausgegebene SYSTEM-/RPC-/VM-Abnahme. Original131 und sämtliche neuen Inputs
|
||||||
|
wurden vor/nach dem Build unverändert gehasht.
|
||||||
|
|
||||||
|
## Ursprünglich geplante Root-Ausführung
|
||||||
|
|
||||||
|
Nur der Orchestrator benutzt den vorhandenen bestätigten Zugang zur festgelegten
|
||||||
|
Windows-Test-VM. Zugang bleibt in den privaten `credentials/` des Maincheckouts;
|
||||||
|
keine VM-Adresse oder Transportpräfixe in diesem Beleg. Der Notebook-Host
|
||||||
|
führt keinen Agenten und keinen Diagnosedienst aus.
|
||||||
|
|
||||||
|
Zuerst `native.py prepare --manifest <aktueller Manifest> --access-root <Maincheckout>
|
||||||
|
--execute-native`: neuer privater Remote-Scratchfall und create-once Upload;
|
||||||
|
der Dienst startet dabei noch nicht. Anschließend `start` mit genau dieser
|
||||||
|
`--id` und `--execute-native`: eigener LocalSystem-Dienst wird einmal angelegt
|
||||||
|
und gestartet. Ein Create-once-Marker steht vor jeder möglichen Wirkung.
|
||||||
|
|
||||||
|
`readback --id <ursprüngliche UUID>` braucht **kein** `--execute-native` und
|
||||||
|
liest ausschließlich denselben Fall. Bei fehlendem/unklarem Ergebnis kein
|
||||||
|
neuer Start und kein erneuter Upload. Der tatsächliche numerische RPCcode
|
||||||
|
kann auch bei vollständig ausgeführter Diagnose ein Fehler sein; das ist
|
||||||
|
kein bestandener Status-/Clockbeleg.
|
||||||
|
|
||||||
|
Erst danach gesondertes `cleanup --id <dieselbe UUID> --execute-native`.
|
||||||
|
Es verweigert fremde Binär-/Intent-/Servicekonfiguration, laufenden Dienst
|
||||||
|
oder wiederholte unklare Löschung. Bei Antwortverlust nur Readback.
|
||||||
|
Keine automatische Bereinigung im Leseweg, kein Stop fremder Dienste,
|
||||||
|
kein impliziter Reboot, kein Gatewechsel und kein RMM-Auftrag.
|
||||||
|
|
||||||
|
## Tatsächlicher SYSTEM-Vergleich und getrennter Abschluss
|
||||||
|
|
||||||
|
Root führte nach Source-/Manifest-/PowerShell-Parserprüfung den aktuellen
|
||||||
|
Pack8b5fc22c auf der Windows-Test-VM aus. Eigener Fall
|
||||||
|
`562ff9de-67ff-48a1-96f0-c2474b3b0777`: erst create-only Vorbereitung/Upload,
|
||||||
|
danach einmaliger eigener Dienststart. Das C-Programm bestätigte seinen
|
||||||
|
tatsächlichen SYSTEM-Token und führte genau einen Status-Traceaufruf aus.
|
||||||
|
|
||||||
|
Tatsächliches Ergebnis: **RPC5, Stage90**, `rpc_exception=5`, kein normaler
|
||||||
|
nativer Return, kein Status. Der Dienst stoppte mit Exitcode0; dieser bestätigt
|
||||||
|
ausschließlich den abgeschlossenen Diagnosebericht, keinen erfolgreichen RPC.
|
||||||
|
Originalbericht danach im selben Fall separat rein lesend identisch bestätigt.
|
||||||
|
`diagnostic-result.json`-SHA256:
|
||||||
|
`5d8475f70a9cd6ef8713edb0264fa0d560499fa6abb6f5483e47b2332a4e6ca5`.
|
||||||
|
|
||||||
|
Der Vergleich löst die Verweigerung durch den Callerwechsel nicht auf. Die
|
||||||
|
Erklärung allein durch LocalService ist damit nicht belegt. Ob SSPI, NPFS,
|
||||||
|
Serverautorisierung oder eine andere RPCschicht5 erzeugt, bleibt offen. Keine
|
||||||
|
beobachtete tatsächliche serverseitige Caller-/Service-SID und kein
|
||||||
|
Serveridentitäts- oder TrustedClock-Nachweis.
|
||||||
|
|
||||||
|
Anschließend wurde ausschließlich der eigene exakt gebundene gestoppte Dienst
|
||||||
|
mit dem separaten Cleanupaufruf entfernt. Kein Stop eines bestehenden Diensts,
|
||||||
|
keine W32Time-ACL-/NTP-/Kontoänderung. Vorher/Nachher-RMM-/Serverabgleich
|
||||||
|
bestätigt dieselben PIDs/Prozessgeburten, Code-/Policydateien, PKI-/DB-/Lock-
|
||||||
|
Datei-IDs, Helperwitness und geschlossene Zähler/Flags. NachherbelegSHA256:
|
||||||
|
`65a9e98b6933a5c5f45acd8e6edcca837eaf28a7aeab0e8637ade8b09bf6c18c`.
|
||||||
|
Produktclock, Capabilities und Jobs bleiben gesperrt. Der nächste getrennte
|
||||||
|
Diagnosevorschlag erfasst ausschließlich begrenzte numerische RPC-EEInfo direkt
|
||||||
|
am Fehler; keine schwächere Authentisierung, Impersonation oder ACLänderung.
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
# Windows-Client: Abnahmegates
|
# Windows-Client: Abnahmegates
|
||||||
|
|
||||||
Stand 2026-11-14, Spezifikation 1.17. Der Windows-11-x64-Gast ist ein eigenes
|
Stand 2026-11-14, Spezifikation 1.18. Der Windows-11-x64-Gast ist ein eigenes
|
||||||
Testgerät. Der Notebook-Host bleibt ausschließlich Entwicklungsrechner;
|
Testgerät. Der Notebook-Host bleibt ausschließlich Entwicklungsrechner;
|
||||||
Server ist `discovery.ease-technologies.de`. Das abgeschlossene Linux-MVP
|
Server ist `discovery.ease-technologies.de`. Das abgeschlossene Linux-MVP
|
||||||
bleibt eine eigenständige Abnahme. Dieser Bericht erweitert dessen Umfang nicht.
|
bleibt eine eigenständige Abnahme. Dieser Bericht erweitert dessen Umfang nicht.
|
||||||
@@ -12,9 +12,10 @@ bleibt eine eigenständige Abnahme. Dieser Bericht erweitert dessen Umfang nicht
|
|||||||
| HTTPS/Fallback | Explizites HTTPS und automatischer Fallback nach zwei tatsächlichen mTLS-WSS503 unter LocalService nativ bestanden, jeweils mit frischen Heartbeats und Inventar-ACK. Testhooks geschlossen. Anschließend bestehende VM separat dauerhaft auf `auto` gestellt und bevorzugtes WSS erneut mit zwei frischen Heartbeats/ACK geprüft; Identität und ACLs erhalten, 0 Jobs/Grants. | Transportnachweise abgeschlossen; kein automatischer HTTPS→WSS-Switchback nachgewiesen. Installerdefault ebenfalls `auto`, aber keine neue Installationsabnahme. |
|
| HTTPS/Fallback | Explizites HTTPS und automatischer Fallback nach zwei tatsächlichen mTLS-WSS503 unter LocalService nativ bestanden, jeweils mit frischen Heartbeats und Inventar-ACK. Testhooks geschlossen. Anschließend bestehende VM separat dauerhaft auf `auto` gestellt und bevorzugtes WSS erneut mit zwei frischen Heartbeats/ACK geprüft; Identität und ACLs erhalten, 0 Jobs/Grants. | Transportnachweise abgeschlossen; kein automatischer HTTPS→WSS-Switchback nachgewiesen. Installerdefault ebenfalls `auto`, aber keine neue Installationsabnahme. |
|
||||||
| TLS-Lifecycle | Falsche CA, falscher Name und abgelaufenes Clientzertifikat mit gültigen Kontrollen nativ als getrennte Admin-TLS-Proben bestanden. Permanente Identität/Dienst unverändert. | Rotation und Widerruf noch gesondert sicher implementieren und prüfen. Permanente Identität nicht widerrufen oder ersetzen. |
|
| TLS-Lifecycle | Falsche CA, falscher Name und abgelaufenes Clientzertifikat mit gültigen Kontrollen nativ als getrennte Admin-TLS-Proben bestanden. Permanente Identität/Dienst unverändert. | Rotation und Widerruf noch gesondert sicher implementieren und prüfen. Permanente Identität nicht widerrufen oder ersetzen. |
|
||||||
| Signierter Jobkern | Gemeinsamer Kern zuletzt nativ Linux80→Windows58 qualifiziert. Neuer enger SYSTEM-Delegationsadapter mit dauerhaftem Intent, deny-only Abandon und unabhängigem RawMirror implementiert; native23+7Units bestanden. Bestehender laufender passiver Client bleibt unverändert; neue Artefakte noch nicht installiert. Jobs bleiben deaktiviert. | Tatsächlichen signierten Dienst-Sync, qualifizierte Uhr und vollständige Startgrenze nachweisen. Units ersetzen keinen LocalService-/SYSTEM- oder Jobnachweis; [Quellenstand](windows-system-delegation-source.md). |
|
| Signierter Jobkern | Gemeinsamer Kern zuletzt nativ Linux80→Windows58 qualifiziert. Neuer enger SYSTEM-Delegationsadapter mit dauerhaftem Intent, deny-only Abandon und unabhängigem RawMirror implementiert; native23+7Units bestanden. Bestehender laufender passiver Client bleibt unverändert; neue Artefakte noch nicht installiert. Jobs bleiben deaktiviert. | Tatsächlichen signierten Dienst-Sync, qualifizierte Uhr und vollständige Startgrenze nachweisen. Units ersetzen keinen LocalService-/SYSTEM- oder Jobnachweis; [Quellenstand](windows-system-delegation-source.md). |
|
||||||
| PowerShell | Begrenzter5.1-Executor implementiert; exakte Skriptbytes, atomarer Prozessbaum, Rohbytes und Unknown bei unklarer Wirkung. Server/UI unterstützen feste Plattformvarianten. Keine tatsächliche Ausführung, Richtlinie derzeit geerbt. | Ausstehende konkrete Richtlinienentscheidung beachten, Encoding/Prozessgrenzen unter LocalService tatsächlich qualifizieren; ausschließlich vollständiger Antrag und tatsächlicher WebUI-Klick. |
|
| PowerShell | Begrenzter5.1-Executor implementiert; exakte Skriptbytes, atomarer Prozessbaum, Rohbytes und Unknown bei unklarer Wirkung. Separates optionales festes RemoteSigned-Prozessprofil ausdrücklich erlaubt, sichtbar an Plan/Grant gebunden; native Vertragsunits zuerst Linux23, danach Windows22 bestanden, Quellenbranch gepusht. Keine tatsächliche Jobausführung oder Profilcapability. | Profilquelle in die laufende Strecke übernehmen, Encoding/Prozessgrenzen unter LocalService tatsächlich qualifizieren; ausschließlich vollständiger Antrag und tatsächlicher WebUI-Klick. Maschinen-/Gruppenrichtlinien unverändert. |
|
||||||
| Privilegierte Aktionen | Eigener SYSTEM-Helper nativ installiert und einmal gestartet, Manual/LocalSystem, leere Aktionsliste und Wirkungen/Reboot gesperrt. Die echte LocalService-Agentprobe scheitert derzeit; kein positiver Peer-/Sync-/Wirkungsnachweis. | Fehler ohne Erweiterung der Sicherheitsgrenze diagnostizieren; gegenseitige SID/PID/Binary-/Dateibindung und unabhängigen Sync nativ prüfen. |
|
| Privilegierte Aktionen | Eigener SYSTEM-Helper nativ installiert und einmal gestartet, Manual/LocalSystem, leere Aktionsliste und Wirkungen/Reboot gesperrt. Die echte LocalService-Agentprobe scheitert derzeit; kein positiver Peer-/Sync-/Wirkungsnachweis. | Fehler ohne Erweiterung der Sicherheitsgrenze diagnostizieren; gegenseitige SID/PID/Binary-/Dateibindung und unabhängigen Sync nativ prüfen. |
|
||||||
| Pakete/Dienste/Logs | Kleines MSI1.0.0 auf der VM erstellt, nur lesend geprüft und nach Download gehasht; keine Installation. Dienst-/Eventlog-/Paketquellen teilweise vorbereitet, keine native Aktionsabnahme. | Unveränderliche Tenantrezepte integrieren; UI-genehmigte MSI-/EXE-Installation/Upgrade/Noop, Dienste und Logs mit unabhängigen Nachbedingungen prüfen. |
|
| Pakete/Dienste/Logs | Kleines MSI1.0.0 auf der VM erstellt, nur lesend geprüft und nach Download gehasht; keine Installation. Dienst-/Eventlog-/Paketquellen teilweise vorbereitet, keine native Aktionsabnahme. | Unveränderliche Tenantrezepte integrieren; UI-genehmigte MSI-/EXE-Installation/Upgrade/Noop, Dienste und Logs mit unabhängigen Nachbedingungen prüfen. |
|
||||||
|
| Eventlog-Vertrag | Im separaten Branch `codex/windows-eventlog` fester Application-/Fixtureprovider, authentisierter begrenzter Worker und hashgebundene UI implementiert/geprüft. Lokal238Rust/PG1/Web38 bestanden; nativ Linux24→Windows23 Vertragsunits ohne Skips. Keine Live-API-Abfrage, Runtimeinstallation oder Capabilityaktivierung. | Tatsächlichen LocalService-Provider und ausschließlich WebUI-genehmigten Job samt Grenzen/Fehlern auf dem Windowsgast qualifizieren. |
|
||||||
| Dauerhafte Jobs/Fehlerfälle | Linuxnachweise vorhanden; sie ersetzen keine nativen Windowsnachweise. | Redelivery/ACK-Verlust, Prozessabbruch, Offline/Ablauf/Entzug und Wiederanlauf am tatsächlichen Windows-Jobpfad prüfen. |
|
| Dauerhafte Jobs/Fehlerfälle | Linuxnachweise vorhanden; sie ersetzen keine nativen Windowsnachweise. | Redelivery/ACK-Verlust, Prozessabbruch, Offline/Ablauf/Entzug und Wiederanlauf am tatsächlichen Windows-Jobpfad prüfen. |
|
||||||
| Mischplattform | Windows/Linux sind separat inventarisierbar; noch keine gemischte Skriptabnahme. | AT-15 mit festen Varianten/Zielen, passenden Interpretern und nachvollziehbaren Einzelresultaten. |
|
| Mischplattform | Windows/Linux sind separat inventarisierbar; noch keine gemischte Skriptabnahme. | AT-15 mit festen Varianten/Zielen, passenden Interpretern und nachvollziehbaren Einzelresultaten. |
|
||||||
| Reboot/Installer | Entwicklungsbuild unsigniert, GNU-Crossbuild; kein MSVC-/signierter Installer-/Windows-Rebootnachweis. | Eigene Abnahmen; kein Windows-Reboot ist durch den bereits ausgeführten Linux-Testreboot autorisiert. |
|
| Reboot/Installer | Entwicklungsbuild unsigniert, GNU-Crossbuild; kein MSVC-/signierter Installer-/Windows-Rebootnachweis. | Eigene Abnahmen; kein Windows-Reboot ist durch den bereits ausgeführten Linux-Testreboot autorisiert. |
|
||||||
|
|||||||
@@ -0,0 +1,40 @@
|
|||||||
|
# Microsoft-MIDL-Codegen tatsächlich auf der Windows-VM bestanden
|
||||||
|
|
||||||
|
Der separate Bootstrapfall `149bafe2-3469-4580-b133-988812bcc3db` führte
|
||||||
|
ausschließlich die zwei festen Microsoft-SDK-Codegentools auf der Windows-VM
|
||||||
|
aus. Keine Installation, kein RPC-Aufruf, keine Produktdienst-/Registry-/PATH-
|
||||||
|
Änderung und kein RMM-Job. Die originale Quelle
|
||||||
|
`deploy/windows/midl_codegen.py` bleibt mit SHA256
|
||||||
|
`078bf2303979dbeccdb7eb84e116325e7f155146d93d0dc0fff6b3e6bdd1b2eb`
|
||||||
|
unverändert.
|
||||||
|
|
||||||
|
Vor dem Toolstart wurden beide Dateien tatsächlich nativ zugelassen:
|
||||||
|
AuthenticodeValid und OnlineChainValid, Microsoftsigner mit Thumbprint
|
||||||
|
`B835FC295FFB94EA2FCA23B0E9C1EDA3FBA4E07D`, Dateiversion8.1.628.1.
|
||||||
|
Der Zulassungsbeleg hat SHA256
|
||||||
|
`4b10a0639cf8f77f9cf0a9c5031b708fe4d2d73344673fba2eecd92cd0a78cc2`.
|
||||||
|
Diese vorherige Prüfung führte die Tools noch nicht aus.
|
||||||
|
|
||||||
|
Der anschließende eigene Codegenprozess wurde einmal unter den vorbereiteten
|
||||||
|
JobObject-/Handle-/Zeit-/Dateigrenzen ausgeführt und meldete `complete=true`.
|
||||||
|
Danach wurden die vier festen Ausgabedateien separat im selben Fall nur lesend
|
||||||
|
zurückgelesen, Base64/Länge/SHA geprüft und bytegleich privat gespeichert.
|
||||||
|
ReadbackSHA256:
|
||||||
|
`0dc2373825f7f8f224cda04ecd5c521dd3c37a6e712bc3ed83bc4fa6d0d89c8c`.
|
||||||
|
|
||||||
|
| Tatsächliche Datei | Bytes | SHA256 |
|
||||||
|
|---|---:|---|
|
||||||
|
| `w32time.h` |3779|`db5dbe5b335eaa58a6512d4abfda44e7273f3aa8a43077dcb0719e4b97ee2bde`|
|
||||||
|
| `w32time_c.c` |18866|`d806adb431f16724c8afdea0c0751588a4bc6f82b6f0b8391d4d189d6a6f4a38`|
|
||||||
|
| `stdout.txt` |125|Im privaten vollständigen Readback gebunden; Meldung64Bit-Verarbeitung der festen IDL|
|
||||||
|
| `stderr.txt` |0|Leere tatsächliche Fehlerausgabe|
|
||||||
|
|
||||||
|
Die erzeugten Dateien bleiben unverändert. Der nächste getrennte Build darf
|
||||||
|
diese tatsächlichen Microsoftoutputs als explizite hashgebundene Inputs
|
||||||
|
verwenden. Kein Patch bereits erzeugter OUT_DIR-Dateien, keine erfundenen
|
||||||
|
RPCNDR-Header-Versionen und keine manuell korrigierten NDR-Bytes. Frühere WIDL-
|
||||||
|
Kandidaten/1783-Berichte bleiben erhalten.
|
||||||
|
|
||||||
|
Dieser Nachweis qualifiziert ausschließlich den Codegeneratorlauf. Noch keine
|
||||||
|
erfolgreiche Statusabfrage, TrustedClock-Qualifikation, Systemscriptausführung
|
||||||
|
oder Windows-MVP-Abnahme. Das Produktgate bleibt `ADAPTER_QUALIFIED=false`.
|
||||||
@@ -0,0 +1,75 @@
|
|||||||
|
# Einmaliger Start des vorhandenen Windows-Zeitdiensts
|
||||||
|
|
||||||
|
Stand 2026-11-14: [Bootstrapquelle](../deploy/windows/time_service_start.py)
|
||||||
|
implementiert, unabhängig quellgeprüft, Python-Syntax und PowerShell-AST lokal
|
||||||
|
bestanden. **Einmaliger nativer Start und separater Readback bestanden.**
|
||||||
|
Der Nutzer hat den Start des vorhandenen
|
||||||
|
W32Time ausdrücklich erlaubt. Die Ausführung übernimmt der Root-Orchestrator
|
||||||
|
nach Quellenprüfung auf der Windows-VM; das Notebook bleibt Entwicklungsrechner.
|
||||||
|
|
||||||
|
Der einzige Dienstbefehl ist `Start-Service -Name W32Time`. Startart,
|
||||||
|
Dienstkonto, Imagepfad, Dienst-SDDL, SID-Typ, NTP-Konfiguration und Richtlinien
|
||||||
|
werden nicht geschrieben. Für einen gestoppten Dienst müssen außerdem null
|
||||||
|
Dienstabhängigkeiten vorliegen; sonst erfolgt kein Start. Pending-/unbekannte
|
||||||
|
Zustände blockieren. Ein bereits laufender Dienst wird nur als
|
||||||
|
`already_running` dokumentiert. Es gibt keinen Resyncbefehl, kein Policyupdate,
|
||||||
|
keinen RMM-Job und keinen Reboot. Ein natürlicher Zeitsync durch den gestarteten
|
||||||
|
Dienst ist erlaubt, aber **kein Nachweis einer qualifizierten Uhr**.
|
||||||
|
|
||||||
|
`prepare` verlangt die fünf unabhängig bekannten SHA256-Werte für Agent,
|
||||||
|
Helper, Agentkonfiguration, Helperkonfiguration und Agentpin. Es legt einen
|
||||||
|
privaten lokalen Fall an, bindet den bereits gespeicherten zentralen
|
||||||
|
Beforekontext `time-service-start-context/888b18b8-da7e-4b9f-9e36-32a23f2ff973`,
|
||||||
|
überträgt ausschließlich die feste, hashgeprüfte Bootstrapquelle und liest
|
||||||
|
den tatsächlichen Ausgangszustand. Der Start verwendet diese Originalpins und
|
||||||
|
diesen Fall unverändert. RMM-PIDs, Prozessentstehung, Dienstdefinitionen,
|
||||||
|
Binaryhashes sowie Konfigurations-/PKI-Metadaten müssen erhalten bleiben.
|
||||||
|
Der private Geräteschlüssel wird nur über Dateimetadaten und ACL-Hash geprüft;
|
||||||
|
seine Bytes werden nicht gelesen oder exportiert.
|
||||||
|
|
||||||
|
Die Registryprüfung hasht nur ausdrücklich aufgeführte stabile Dienst-, NTP-
|
||||||
|
und Policy-Konfigurationswerte. Sie gibt keine Rohwerte/NTP-Hostnamen aus.
|
||||||
|
Volatile LastSync-/Laufzeitwerte werden nicht als unveränderlich vorausgesetzt;
|
||||||
|
der Hash behauptet keine vollständige Abdeckung sämtlicher Registrywerte.
|
||||||
|
W32Time-Status und dessen PID dürfen sich durch den erlaubten Start ändern.
|
||||||
|
|
||||||
|
Vor dem einzigen Startaufruf werden ein privater Originalbeleg und zwei
|
||||||
|
dauerhafte, ausschließlich neu anlegbare Startreservierungen gespeichert:
|
||||||
|
im Fallverzeichnis und als globaler W32Time-Einmalbeleg. Auch lokal entsteht
|
||||||
|
vor dem SSH-Aufruf ein ausschließlich neu anlegbarer Startversuchsbeleg.
|
||||||
|
Eine verlorene Antwort, ein Fehler oder ein unvollständiger Beleg erlaubt nur
|
||||||
|
`readback --id ORIGINALFALL`; weder Startwiederholung noch automatischer
|
||||||
|
Rollback sind implementiert. Readback meldet den tatsächlichen aktuellen
|
||||||
|
Zustand und bewahrt unbestätigte Ergebnisse als solche. Frühere private
|
||||||
|
SSH-Fehler werden vor/nach Aufrufen versioniert erhalten.
|
||||||
|
|
||||||
|
Die folgenden Befehle sind **Aufrufvorlagen**; die Hashplatzhalter
|
||||||
|
müssen aus dem unabhängig bekannten aktuellen Deployment stammen:
|
||||||
|
|
||||||
|
```text
|
||||||
|
python3 deploy/windows/time_service_start.py prepare --agent-sha256 HASH --helper-sha256 HASH --config-sha256 HASH --policy-sha256 HASH --pin-sha256 HASH
|
||||||
|
python3 deploy/windows/time_service_start.py start --id ORIGINALFALL
|
||||||
|
python3 deploy/windows/time_service_start.py readback --id ORIGINALFALL
|
||||||
|
```
|
||||||
|
|
||||||
|
Vollständige Metadaten bleiben in geschützten lokalen/VM-Fallbelegen. Die CLI
|
||||||
|
gibt nur Fallkennung, Status, Running-/Erhaltungs-/Readback-Merkmale und den
|
||||||
|
ausdrücklich nicht geprüften Uhrvertrauensstatus aus. Lokaler Quellnachweis:
|
||||||
|
`devstate/windows-client/time-service-start-source/225c3208-4a3f-4528-8c17-b3846b70812f/qualification.json`;
|
||||||
|
PowerShell nur geparst, kein Windows-API-/VM-Aufruf und keine Produkttestsuite.
|
||||||
|
|
||||||
|
## Tatsächliche Ausführung
|
||||||
|
|
||||||
|
Fall `c3552c3f-24d1-4713-bd0b-544aee4ffd18` auf dem Windowsgast:
|
||||||
|
Vorbereitung bestätigte Stopped und die bekannten Originalhashes. Anschließend
|
||||||
|
genau ein `Start-Service W32Time`, Status Running, Erhaltungsprüfung bestanden.
|
||||||
|
Getrennter späterer Readback bestätigte denselben Originalresultbeleg und
|
||||||
|
Running ohne Startwiederholung. Agent5140 und Helper6240 unverändert;
|
||||||
|
Dienstdefinition/SDDL und ausgewählte NTP-/Policy-Konfigurationswerte erhalten.
|
||||||
|
Kein privater Schlüsselinhalt gelesen und keine Konfiguration geschrieben.
|
||||||
|
|
||||||
|
Zentraler Kontrollstand vorher/nachher identisch: Windows0Jobs/0Outbox/0Grants/
|
||||||
|
0ungeklärt, Linux30/30/26/0; Rootpolicyhash und geschlossene Transporthooks
|
||||||
|
unverändert. Geschützter Abschlussbeleg `acceptance.json` im Originalfall,
|
||||||
|
SHA256 `365d897d94f6fb16b3112fcb5126bdc09224b34e0a6ef46940ca8e7a651807fb`.
|
||||||
|
Quellhash `ef5d4ce8…`. **Kein Uhrqualifikations-, RMM-Job- oder Rebootbeleg.**
|
||||||
Reference in New Issue
Block a user