Compare commits
36
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
45ab784c1b | ||
|
|
7a64002f74 | ||
|
|
bddfb26e67 | ||
|
|
00ecbb58ac | ||
|
|
ba43aee4a9 | ||
|
|
92b50f25e3 | ||
|
|
cd0257fbe9 | ||
|
|
bd0a426019 | ||
|
|
eb3fa560d6 | ||
|
|
cf2c1a632b | ||
|
|
45ce622370 | ||
|
|
fcec400ec6 | ||
|
|
dffdd401c5 | ||
|
|
97d4f86940 | ||
|
|
6fb973a247 | ||
|
|
e32f6330a0 | ||
|
|
c41c8c7286 | ||
|
|
0902a44671 | ||
|
|
e7cf1aed73 | ||
|
|
b614b6f5be | ||
|
|
242641de72 | ||
|
|
454e08f942 | ||
|
|
38e6df51ea | ||
|
|
5adf209f1e | ||
|
|
48662f97e3 | ||
|
|
16c9c3cefe | ||
|
|
07c5b0e12d | ||
|
|
c46873ff95 | ||
|
|
1a502a1c46 | ||
|
|
a5ec061a92 | ||
|
|
9a6599fddd | ||
|
|
f023d790a4 | ||
|
|
5f21b753ed | ||
|
|
0b32859d74 | ||
|
|
331cdddac5 | ||
|
|
00717e4283 |
@@ -39,6 +39,51 @@ struct Config {
|
||||
// Explicit protected opt-in only; this flag never qualifies a clock or pins.
|
||||
#[serde(default)]
|
||||
enable_jobs: bool,
|
||||
#[serde(
|
||||
default,
|
||||
deserialize_with = "rmm_domain::jobs::deserialize_windows_execution_profile"
|
||||
)]
|
||||
windows_execution_profile: Option<rmm_domain::jobs::WindowsExecutionProfile>,
|
||||
}
|
||||
impl Config {
|
||||
fn profile_enabled(&self, profile: rmm_domain::jobs::WindowsExecutionProfile) -> bool {
|
||||
self.enable_jobs
|
||||
&& self.job_binding_file.is_some()
|
||||
&& cfg!(feature = "system-helper")
|
||||
&& self.windows_execution_profile == Some(profile)
|
||||
}
|
||||
fn read(path: &Path) -> Result<Self> {
|
||||
let raw = protected_read(path, 32768)?;
|
||||
let config: Self = serde_json::from_slice(&raw)?;
|
||||
if let Some(profile) = config.windows_execution_profile {
|
||||
ensure!(
|
||||
config.profile_enabled(profile),
|
||||
"WINDOWS_PROFILE_REQUIRES_JOB_CONFIGURATION"
|
||||
);
|
||||
#[cfg(feature = "system-helper")]
|
||||
{
|
||||
use rmm_agent_windows::helper_ipc::PinnedFile;
|
||||
use std::io::Read;
|
||||
// Verify the exact bytes used for the opt-in under the existing
|
||||
// administrator-owned, service-read-only file and directory ACLs.
|
||||
let readers = [native::service_sid()?];
|
||||
let mut parent = PinnedFile::open(
|
||||
path.parent().context("CONFIG_PARENT")?,
|
||||
true,
|
||||
&readers,
|
||||
&[],
|
||||
false,
|
||||
)?;
|
||||
let mut pin = PinnedFile::open(path, false, &readers, &[], false)?;
|
||||
let mut verified = Vec::new();
|
||||
(&mut pin.file).take(32769).read_to_end(&mut verified)?;
|
||||
ensure!(verified == raw, "WINDOWS_PROFILE_CONFIGURATION_CHANGED");
|
||||
pin.check()?;
|
||||
parent.check()?;
|
||||
}
|
||||
}
|
||||
Ok(config)
|
||||
}
|
||||
}
|
||||
fn create_private(path: &Path, bytes: &[u8]) -> Result<()> {
|
||||
use std::io::Write;
|
||||
@@ -830,6 +875,13 @@ impl Agent {
|
||||
return false;
|
||||
}
|
||||
if rmm_agent_windows::actions::supported(job) {
|
||||
if let rmm_domain::jobs::Action::RunScript {
|
||||
windows_execution_profile: Some(profile),
|
||||
..
|
||||
} = &job.action
|
||||
{
|
||||
return self.binding.is_some() && self.config.profile_enabled(*profile);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
#[cfg(feature = "system-helper")]
|
||||
@@ -859,9 +911,12 @@ impl Agent {
|
||||
{
|
||||
caps.extend(["rmm.sync.v1", "refresh_inventory"].map(str::to_string));
|
||||
if rmm_agent_windows::actions::powershell().is_ok() {
|
||||
// The process_remote_signed profile is implemented but remains
|
||||
// unpublished until its separate native qualification passes.
|
||||
caps.extend(["run_script", "script.powershell/1"].map(str::to_string));
|
||||
if self.config.profile_enabled(
|
||||
rmm_domain::jobs::WindowsExecutionProfile::PowerShell51RemoteSigned,
|
||||
) {
|
||||
caps.push(rmm_agent_windows::actions::REMOTE_SIGNED_PROFILE_CAPABILITY.into());
|
||||
}
|
||||
}
|
||||
}
|
||||
caps
|
||||
@@ -1810,7 +1865,7 @@ fn service_run(stop: &'static AtomicBool) -> Result<()> {
|
||||
);
|
||||
let path = Path::new(&arguments[2]);
|
||||
ensure!(path.is_absolute(), "ABSOLUTE_CONFIG_REQUIRED");
|
||||
let config: Config = serde_json::from_slice(&protected_read(path, 32768)?)?;
|
||||
let config = Config::read(path)?;
|
||||
native::require_local_service()?;
|
||||
ensure!(
|
||||
config.state_directory.is_absolute(),
|
||||
@@ -1951,7 +2006,7 @@ pub fn main() -> Result<()> {
|
||||
args.len() == 3 && args[1] == "--config",
|
||||
"SERVICE_ARGUMENTS"
|
||||
);
|
||||
let config: Config = serde_json::from_slice(&protected_read(Path::new(&args[2]), 32768)?)?;
|
||||
let config = Config::read(Path::new(&args[2]))?;
|
||||
// Shared transport reads its one DNS identity. Set it before SCM dispatch
|
||||
// creates its service thread and before any Tokio/collector threads exist.
|
||||
unsafe {
|
||||
@@ -2053,15 +2108,58 @@ mod tests {
|
||||
}
|
||||
#[test]
|
||||
fn old_passive_configuration_cannot_enable_jobs_or_read_the_clock() {
|
||||
let config:Config=serde_json::from_value(serde_json::json!({"server_name":"example.invalid","connect_address":"127.0.0.1:443","ca_file":"C:/fixture/ca.pem","state_directory":"C:/fixture/state","enrollment_token_file":"C:/fixture/token","transport":"auto"})).unwrap();
|
||||
let config: Config = serde_json::from_value(passive_test_config()).unwrap();
|
||||
assert!(!config.enable_jobs);
|
||||
assert!(config.job_binding_file.is_none());
|
||||
assert!(config.windows_execution_profile.is_none());
|
||||
let clock = JobClock::new(config.enable_jobs);
|
||||
assert_eq!(
|
||||
clock.now().unwrap_err().to_string(),
|
||||
"WINDOWS_JOBS_NOT_ENABLED"
|
||||
);
|
||||
}
|
||||
fn passive_test_config() -> serde_json::Value {
|
||||
serde_json::json!({
|
||||
"server_name":"example.invalid","connect_address":"127.0.0.1:443",
|
||||
"ca_file":"C:/fixture/ca.pem","state_directory":"C:/fixture/state",
|
||||
"enrollment_token_file":"C:/fixture/token","transport":"auto"
|
||||
})
|
||||
}
|
||||
#[test]
|
||||
fn remote_signed_requires_explicit_profile_jobs_and_binding() {
|
||||
let profile = rmm_domain::jobs::WindowsExecutionProfile::PowerShell51RemoteSigned;
|
||||
let mut config: Config = serde_json::from_value(passive_test_config()).unwrap();
|
||||
config.enable_jobs = true;
|
||||
config.job_binding_file = Some("C:/fixture/binding.json".into());
|
||||
assert!(!config.profile_enabled(profile));
|
||||
config.windows_execution_profile = Some(profile);
|
||||
assert_eq!(
|
||||
config.profile_enabled(profile),
|
||||
cfg!(feature = "system-helper")
|
||||
);
|
||||
config.enable_jobs = false;
|
||||
assert!(!config.profile_enabled(profile));
|
||||
config.enable_jobs = true;
|
||||
config.job_binding_file = None;
|
||||
assert!(!config.profile_enabled(profile));
|
||||
|
||||
let mut value = passive_test_config();
|
||||
value["windows_execution_profile"] = serde_json::json!("powershell_51_remote_signed");
|
||||
assert_eq!(
|
||||
serde_json::from_value::<Config>(value.clone())
|
||||
.unwrap()
|
||||
.windows_execution_profile,
|
||||
Some(profile)
|
||||
);
|
||||
for invalid in [
|
||||
serde_json::Value::Null,
|
||||
serde_json::json!(true),
|
||||
serde_json::json!("Bypass"),
|
||||
] {
|
||||
value["windows_execution_profile"] = invalid;
|
||||
assert!(serde_json::from_value::<Config>(value.clone()).is_err());
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn legacy_inventory_keeps_original_bytes_until_concrete_core_ack() {
|
||||
let directory =
|
||||
|
||||
@@ -2,15 +2,32 @@
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const crypto = require('node:crypto');
|
||||
const { isDeepStrictEqual } = require('node:util');
|
||||
const { chromium } = require('../../web/node_modules/playwright');
|
||||
const root = path.resolve(__dirname, '../..');
|
||||
const assert = (value) => { if (!value) throw new Error('UI contract mismatch'); };
|
||||
function checkWindowsHello(job, planBytes) {
|
||||
const payload = job.payload;
|
||||
const action = {
|
||||
action: 'run_script', interpreter: 'powershell', script_utf8: "Write-Output 'Zeitprofil-Test'\r\n",
|
||||
arguments: [], expected_stdout: 'Zeitprofil-Test\r\n', windows_execution_profile: 'powershell_51_remote_signed',
|
||||
};
|
||||
const stored = JSON.parse(Buffer.from(planBytes).toString('utf8'));
|
||||
assert(stored.jobs.length === 1 && isDeepStrictEqual(stored.jobs[0].payload, payload));
|
||||
assert(payload.tenant_id === '11111111-1111-4111-8111-111111111111'
|
||||
&& payload.agent_id === '63ea15b2-0643-403d-b5b4-cba1288dbea3'
|
||||
&& payload.asset_id === 'a176520e-8a91-4e93-a78b-8e7620f430e0'
|
||||
&& payload.execution_identity === 'agent_service' && isDeepStrictEqual(payload.action, action));
|
||||
assert(stored.jobs[0].job_payload_hash === job.job_payload_hash
|
||||
&& stored.jobs[0].script_sha256 === job.script_sha256
|
||||
&& crypto.createHash('sha256').update(action.script_utf8, 'utf8').digest('hex') === job.script_sha256);
|
||||
}
|
||||
(async () => {
|
||||
const file = path.resolve(process.argv[2]);
|
||||
const stat = fs.lstatSync(file);
|
||||
assert(stat.isFile() && !stat.isSymbolicLink() && stat.uid === process.getuid() && (stat.mode & 0o777) === 0o600);
|
||||
const expected = JSON.parse(fs.readFileSync(file, 'utf8'));
|
||||
assert(expected.profile === 'dev/test' && ['hello', 'refresh_inventory', 'cancel_queued'].includes(expected.case));
|
||||
assert(expected.profile === 'dev/test' && ['hello', 'refresh_inventory', 'cancel_queued', 'windows_hello'].includes(expected.case));
|
||||
assert(expected.expected_principal === 'simulated-testprincipal-a');
|
||||
const loginFile = path.join(root, 'credentials/server-browser-login.json');
|
||||
const loginStat = fs.lstatSync(loginFile);
|
||||
@@ -38,7 +55,7 @@ const assert = (value) => { if (!value) throw new Error('UI contract mismatch');
|
||||
assert(pending.approval_state === 'pending_approval' && pending.job_count === 0 && pending.execution_state === null);
|
||||
await op.getByRole('button', { name: 'Unveränderlichen Plan zur Prüfung öffnen', exact: true }).click();
|
||||
const detail = page.locator('section').filter({ has: page.getByRole('heading', { name: 'Unveränderlicher Plan / Genehmigungsdetail', exact: true }) });
|
||||
const rendered = JSON.parse(await detail.locator('pre').first().innerText());
|
||||
const rendered = JSON.parse(await detail.getByLabel('Alle festen Zielpreviews, exakte Skriptinhalte/Hashes, Parameter, Rechte, Fristen, Rollout und Nachbedingungen', { exact: true }).innerText());
|
||||
assert(rendered.plan_hash === expected.plan.plan_hash && crypto.createHash('sha256').update(Buffer.from(rendered.plan_payload_bytes)).digest('hex') === expected.plan.plan_hash);
|
||||
assert(JSON.stringify(rendered.plan_payload_bytes) === JSON.stringify(expected.plan.plan_payload_bytes));
|
||||
assert(rendered.jobs.length === 1 && rendered.resolved_targets.length === 1);
|
||||
@@ -47,7 +64,15 @@ const assert = (value) => { if (!value) throw new Error('UI contract mismatch');
|
||||
assert(payload.agent_id === expected.agent_id && payload.asset_id === expected.asset_id && payload.tenant_id === expected.tenant_id);
|
||||
assert(payload.execution_identity === 'agent_service' && payload.max_runtime_seconds === 60 && payload.max_output_bytes <= 65536);
|
||||
assert(Date.parse(payload.start_before) > Date.now());
|
||||
if (expected.case === 'hello' || expected.case === 'cancel_queued') assert(payload.action.action === 'run_script' && payload.action.interpreter === 'posix_sh' && payload.action.script_utf8 === "printf '%s\\n' 'Hello World'\n" && payload.action.expected_stdout === 'Hello World\n');
|
||||
if (expected.case === 'windows_hello') {
|
||||
checkWindowsHello(job, rendered.plan_payload_bytes);
|
||||
assert(expected.stage === 'pending_approval' && expected.preapproval.jobs === 0
|
||||
&& expected.preapproval.outbox === 0 && expected.preapproval.permits === 0);
|
||||
assert(pending.plan_id === rendered.plan_id && pending.operation_id === expected.operation_id);
|
||||
await detail.getByLabel('Feste PowerShell-Prozessprofile', { exact: true })
|
||||
.getByText('Asset: ' + payload.asset_id + ' · Windows PowerShell5.1 · agent_service · RemoteSigned · nur Jobprozess', { exact: true }).waitFor();
|
||||
}
|
||||
else if (expected.case === 'hello' || expected.case === 'cancel_queued') assert(payload.action.action === 'run_script' && payload.action.interpreter === 'posix_sh' && payload.action.script_utf8 === "printf '%s\\n' 'Hello World'\n" && payload.action.expected_stdout === 'Hello World\n');
|
||||
else assert(payload.action.action === 'refresh_inventory' && payload.action.scope === 'linux.base');
|
||||
const approve = detail.getByRole('button', { name: 'SIMULIERT: Diesen festen Plan ausdrücklich genehmigen', exact: true });
|
||||
assert(await approve.isDisabled());
|
||||
|
||||
@@ -6,6 +6,7 @@ Credentials stay on the cloud server; the browser reads its protected login
|
||||
file. All SQL is fixed read-only evidence, scoped to the one cloud VM.
|
||||
"""
|
||||
import argparse
|
||||
from datetime import timedelta
|
||||
import hashlib
|
||||
import http.client
|
||||
import json
|
||||
@@ -24,6 +25,38 @@ import vm_mvp_acceptance as contract
|
||||
ROOT = bootstrap.ROOT
|
||||
TENANT = bootstrap.TENANT
|
||||
require = bootstrap.require
|
||||
WINDOWS_AGENT = '63ea15b2-0643-403d-b5b4-cba1288dbea3'
|
||||
WINDOWS_ASSET = 'a176520e-8a91-4e93-a78b-8e7620f430e0'
|
||||
WINDOWS_SCRIPT = "Write-Output 'Zeitprofil-Test'\r\n"
|
||||
WINDOWS_STDOUT = 'Zeitprofil-Test\r\n'
|
||||
|
||||
|
||||
def windows_hello_input():
|
||||
start = contract.now()
|
||||
return dict(
|
||||
tenant_id=TENANT, action='run_script', targets=dict(asset_ids=[WINDOWS_ASSET]),
|
||||
parameters=dict(
|
||||
execution_identity='agent_service', timeout_seconds=60, max_output_bytes=65536,
|
||||
arguments=[], expected_stdout=WINDOWS_STDOUT,
|
||||
variants=[dict(os_family='windows', interpreter='powershell', encoding='utf-8',
|
||||
script_utf8=WINDOWS_SCRIPT, windows_execution_profile='powershell_51_remote_signed')]),
|
||||
schedule=contract.schedule(start, start + timedelta(minutes=15)),
|
||||
rollout=dict(max_parallel=1, halt_after_failures=1),
|
||||
reason='Erste genehmigte PowerShell-Textausgabe auf der Windows-Test-VM')
|
||||
|
||||
|
||||
def verify_windows_hello(result):
|
||||
report = result['result']
|
||||
proof = report['evidence']
|
||||
contract.require(result['state'] == 'succeeded' and report['exit_code'] == 0
|
||||
and bytes(report['stdout']) == WINDOWS_STDOUT.encode() and bytes(report['stderr']) == b''
|
||||
and report['output_truncated'] is False and proof['postconditions_passed'] is True
|
||||
and proof['execution_sid'] == 'S-1-5-19' and proof['interpreter'] == 'powershell'
|
||||
and proof['script_sha256'] == hashlib.sha256(WINDOWS_SCRIPT.encode()).hexdigest()
|
||||
and proof['windows_execution_profile'] == 'powershell_51_remote_signed'
|
||||
and proof['execution_policy'] == 'process_remote_signed_requested'
|
||||
and proof['execution_policy_requested'] == 'RemoteSigned'
|
||||
and proof['execution_policy_scope'] == 'process', 'windows_hello_evidence')
|
||||
|
||||
|
||||
def prepare_browser():
|
||||
@@ -147,13 +180,18 @@ class Backend:
|
||||
def main():
|
||||
parser=argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--execute-dev-test-ui',action='store_true',required=True)
|
||||
parser.add_argument('--case',choices=('hello','refresh_inventory','cancel_queued'),default='hello')
|
||||
parser.add_argument('--case',choices=('hello','refresh_inventory','cancel_queued','windows_hello'),default='hello')
|
||||
parser.add_argument('--transport',choices=('wss','https'))
|
||||
args=parser.parse_args();os.umask(0o077)
|
||||
contract.require(not (Path.home()/'.local/share/rust-discovery/remote-agent').exists(),'notebook_must_not_have_client')
|
||||
prepare_browser()
|
||||
installed=contract.protected_json(ROOT/'devstate/remote-vm.json')
|
||||
identity=installed['identity']
|
||||
windows = args.case == 'windows_hello'
|
||||
if windows:
|
||||
contract.require(args.transport is None, 'windows_keep_current_transport')
|
||||
identity = dict(agent_id=WINDOWS_AGENT, asset_id=WINDOWS_ASSET)
|
||||
else:
|
||||
prepare_browser()
|
||||
installed=contract.protected_json(ROOT/'devstate/remote-vm.json')
|
||||
identity=installed['identity']
|
||||
settings=dict(tenant_id=TENANT,**identity)
|
||||
def evidence(kind,**extra):
|
||||
return bootstrap.rpc('server.conf',server,dict(kind=kind,tenant_id=TENANT,agent_id=identity['agent_id'],**extra))
|
||||
@@ -172,11 +210,18 @@ def main():
|
||||
observed=bootstrap.rpc('server.conf',bootstrap.server,dict(action='observe',agent_id=identity['agent_id']))
|
||||
contract.require(observed['sync_ready'] and not observed['restore_blocked'],'signed_sync_gate_required')
|
||||
needed={'refresh_inventory' if args.case=='refresh_inventory' else 'run_script','rmm.sync.v1'}
|
||||
if windows:
|
||||
needed.update(('windows.base/1', 'script.powershell/1', 'script.powershell.process_remote_signed/1'))
|
||||
contract.require(needed<=set(device['capabilities']),'actual_vm_capability_required')
|
||||
request=contract.case_input(args.case,settings)
|
||||
if windows:
|
||||
prepare_browser()
|
||||
request=windows_hello_input() if windows else contract.case_input(args.case,settings)
|
||||
plan=backend.call('operations.plan',dict(tenant_id=TENANT,input=request))
|
||||
contract.require(hashlib.sha256(bytes(plan['plan_payload_bytes'])).hexdigest()==plan['plan_hash'] and len(plan['jobs'])==1,'immutable_plan')
|
||||
job=plan['jobs'][0]
|
||||
if windows:
|
||||
contract.require(job['payload']['agent_id']==WINDOWS_AGENT and job['payload']['asset_id']==WINDOWS_ASSET
|
||||
and job['payload']['tenant_id']==TENANT, 'fixed_windows_target_required')
|
||||
folder=ROOT/'devstate/cloud-acceptance'/uuid.uuid4().hex;folder.mkdir(mode=0o700,parents=True)
|
||||
checkpoint=dict(profile='dev/test',case=args.case,expected_principal='simulated-testprincipal-a',**settings,
|
||||
plan=plan,job=job,stage='planned',no_retry=True,transport=observed['transport'],server_connection=observed)
|
||||
@@ -205,6 +250,8 @@ def main():
|
||||
contract.require(result['state']=='succeeded' and result['result']['evidence']['postconditions_passed'],'native_postconditions_required')
|
||||
if args.case=='hello':
|
||||
contract.require(result['result']['exit_code']==0 and bytes(result['result']['stdout'])==b'Hello World\n','exact_stdout_required')
|
||||
elif windows:
|
||||
verify_windows_hello(result)
|
||||
elif args.case=='refresh_inventory':
|
||||
contract.require(contract.timestamp(result['result']['evidence']['observed_at'])>=contract.timestamp(request['schedule']['not_before']),'fresh_inventory_required')
|
||||
gate=evidence('gate',job_id=job['job_id']);audit=evidence('audit',operation_id=pending['operation_id'])
|
||||
|
||||
@@ -2,7 +2,10 @@
|
||||
#requires -RunAsAdministrator
|
||||
# Finish the single, console-verified public-file publication on the test VM.
|
||||
# Run in a fresh Windows PowerShell process. No SSH or RMM job is involved.
|
||||
[CmdletBinding()]
|
||||
param([switch]$InitialCreate, [switch]$ResumeEmpty)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
if ($InitialCreate -and $ResumeEmpty) { throw 'Choose one publication operation' }
|
||||
$caseId = 'ad9fd154-b2be-4f5d-9e17-65abb721ceaf'
|
||||
$controllerHash = 'd8b4fd4fd9ca5310cc1591ce3c2ccae5bd72a2ade43b21a8187cfdfb960b3427'
|
||||
$configHash = '2b4a8a7080770304b80e2a665fa5f5ee1ebbd9182e7c80b184e75b114575b42b'
|
||||
@@ -49,10 +52,34 @@ $aclDone = Get-Content -LiteralPath (Join-Path $folder 'directory-acl-done.json'
|
||||
$staged = Join-Path $folder 'time-attestation.candidate.json'
|
||||
$resultPath = Join-Path $folder 'result.json'
|
||||
$reservation = Join-Path $folder 'console-finalization-intent.json'
|
||||
foreach ($path in @($target,$resultPath,$reservation)) {
|
||||
$initialReservation = Join-Path $folder 'console-initial-create-intent.json'
|
||||
$initialResult = Join-Path $folder 'console-initial-create-result.json'
|
||||
$initialError = Join-Path $folder 'console-initial-create-error.json'
|
||||
$initialVerified = Join-Path $folder 'console-initial-create-verified.json'
|
||||
$resumeReservation = Join-Path $folder 'console-resume-empty-intent.json'
|
||||
$resumeVerified = Join-Path $folder 'console-resume-empty-verified.json'
|
||||
$resumeResult = Join-Path $folder 'console-resume-empty-result.json'
|
||||
$resumeError = Join-Path $folder 'console-resume-empty-error.json'
|
||||
$absent = @($resultPath,$initialVerified,$initialResult,$resumeReservation,$resumeVerified,$resumeResult,$resumeError)
|
||||
if (!$ResumeEmpty) { $absent += @($target,$initialReservation,$initialError) }
|
||||
if ($InitialCreate -or $ResumeEmpty) {
|
||||
$priorError = Join-Path $folder 'console-finalization-error.json'
|
||||
CheckControl $reservation $false
|
||||
CheckControl $priorError $false
|
||||
$priorReservation = Get-Content -LiteralPath $reservation -Raw | ConvertFrom-Json
|
||||
$priorFailure = Get-Content -LiteralPath $priorError -Raw | ConvertFrom-Json
|
||||
if ($priorReservation.id -cne $caseId -or $priorReservation.config_sha256 -cne $configHash -or
|
||||
$priorFailure.id -cne $caseId -or $priorFailure.phase -cne 'File.Move' -or
|
||||
$priorFailure.hresult -cne '0x80070020' -or $priorFailure.exception -cne 'System.IO.IOException') {
|
||||
throw 'Expected the recorded sharing violation from the original single finalization attempt'
|
||||
}
|
||||
} else {
|
||||
$absent += $reservation
|
||||
}
|
||||
foreach ($path in $absent) {
|
||||
if (Test-Path -LiteralPath $path) { throw 'Existing target or finalization record: read original case' }
|
||||
}
|
||||
$null = ReadAcl $staged $false
|
||||
$stagedAcl = ReadAcl $staged $false
|
||||
$rootAcl = ReadAcl $helperRoot $true
|
||||
$expected = @{
|
||||
volume_serial = '9815088561147542064'
|
||||
@@ -67,6 +94,19 @@ if ($publish.create_once -ne $true -or $publish.config_sha256 -cne $configHash -
|
||||
(AclHash $helperRoot) -cne '186d85132cf0e16cbb9623ad9636b7777741939a8cae3d689a2af1eb267a7f49') {
|
||||
throw 'Original file identity or permissions changed'
|
||||
}
|
||||
if ($ResumeEmpty) {
|
||||
CheckControl $initialReservation $false
|
||||
CheckControl $initialError $false
|
||||
$creation = Get-Content -LiteralPath $initialReservation -Raw | ConvertFrom-Json
|
||||
$failure = Get-Content -LiteralPath $initialError -Raw | ConvertFrom-Json
|
||||
if ($creation.id -cne $caseId -or $creation.config_sha256 -cne $configHash -or
|
||||
$creation.create_new -isnot [bool] -or !$creation.create_new -or !$creation.utc -or
|
||||
!(JsonEqual $expected $creation.staged) -or $failure.id -cne $caseId -or
|
||||
$failure.phase -cne 'verify_creation' -or $failure.hresult -cne '0x80131501' -or
|
||||
$failure.exception -cne 'System.Management.Automation.RuntimeException') {
|
||||
throw 'Unexpected initial creation intent or failure'
|
||||
}
|
||||
}
|
||||
if ($p.probe_sha256 -cne '727732fb4b38ac5431a330527bd52a3ab80af8f189ae75a7b48eceb1d4b69cac' -or
|
||||
$p.system_probe_sha256 -cne '77a344912c61b7ac4a92152ae1b534ca7c36fe6f7dc4675783f20558c3a7f434') {
|
||||
throw 'Unexpected native status probes'
|
||||
@@ -77,12 +117,288 @@ SameLive $intent.before $before
|
||||
if ($before.agent_kernel.creation_filetime -cne '134392294174782153' -or
|
||||
$before.helper_kernel.creation_filetime -cne '134392294130218261') { throw 'Service generation changed' }
|
||||
|
||||
# FileStandardInfo supplies the hard-link count and directory/delete-pending state
|
||||
# from the same exclusive handle used to write, flush, hash and publish the DACL.
|
||||
function Initialize-InitialProfileNative {
|
||||
Add-Type -TypeDefinition @'
|
||||
using System;
|
||||
using System.ComponentModel;
|
||||
using System.IO;
|
||||
using System.Runtime.InteropServices;
|
||||
using Microsoft.Win32.SafeHandles;
|
||||
|
||||
public static class RmmInitialProfileFile {
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
private struct StandardInfo {
|
||||
public long AllocationSize, EndOfFile;
|
||||
public uint NumberOfLinks;
|
||||
public byte DeletePending, Directory;
|
||||
}
|
||||
[DllImport("kernel32.dll", SetLastError=true)]
|
||||
private static extern bool GetFileInformationByHandleEx(
|
||||
SafeFileHandle handle, int infoClass, out StandardInfo info, uint size);
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
private struct TagInfo { public uint Attributes, ReparseTag; }
|
||||
|
||||
[DllImport("kernel32.dll", SetLastError=true)]
|
||||
private static extern bool GetFileInformationByHandleEx(
|
||||
SafeFileHandle handle, int infoClass, out TagInfo info, uint size);
|
||||
[DllImport("kernel32.dll", CharSet=CharSet.Unicode, ExactSpelling=true, SetLastError=true)]
|
||||
private static extern SafeFileHandle CreateFileW(string path, uint access, uint sharing,
|
||||
IntPtr security, uint disposition, uint flags, IntPtr template);
|
||||
|
||||
private static void CheckAttributes(SafeFileHandle handle, bool directory) {
|
||||
TagInfo info;
|
||||
if (!GetFileInformationByHandleEx(handle, 9, out info, (uint)Marshal.SizeOf(typeof(TagInfo))))
|
||||
throw new Win32Exception(Marshal.GetLastWin32Error());
|
||||
if ((info.Attributes & (uint)FileAttributes.ReparsePoint) != 0 ||
|
||||
((info.Attributes & (uint)FileAttributes.Directory) != 0) != directory)
|
||||
throw new InvalidOperationException("Unexpected file type or reparse point");
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
private struct UnicodeString { public ushort Length, MaximumLength; public IntPtr Buffer; }
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
private struct ObjectAttributes {
|
||||
public int Length;
|
||||
public IntPtr RootDirectory, ObjectName;
|
||||
public uint Attributes;
|
||||
public IntPtr SecurityDescriptor, SecurityQoS;
|
||||
}
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
private struct IoStatus { public IntPtr Status, Information; }
|
||||
[DllImport("ntdll.dll")]
|
||||
private static extern int NtOpenFile(out SafeFileHandle file, uint access, ref ObjectAttributes attributes,
|
||||
out IoStatus io, uint share, uint options);
|
||||
[DllImport("ntdll.dll")]
|
||||
private static extern uint RtlNtStatusToDosError(int status);
|
||||
|
||||
// Open-only, relative to the held volume root. OBJ_DONT_REPARSE applies to
|
||||
// the complete relative path, including ProgramData and the helper directory.
|
||||
public static FileStream OpenExistingTarget() {
|
||||
const string relativePath = @"ProgramData\RustDiscoverySystem\time-attestation.json";
|
||||
const uint backupSemanticsNoFollow = 0x02200000;
|
||||
using (SafeFileHandle root = CreateFileW(@"C:\", 0xA0, 7, IntPtr.Zero, 3,
|
||||
backupSemanticsNoFollow, IntPtr.Zero)) {
|
||||
if (root.IsInvalid) throw new Win32Exception(Marshal.GetLastWin32Error());
|
||||
CheckAttributes(root, true);
|
||||
UnicodeString name = new UnicodeString();
|
||||
name.Length = checked((ushort)(relativePath.Length * sizeof(char)));
|
||||
name.MaximumLength = name.Length;
|
||||
name.Buffer = Marshal.StringToHGlobalUni(relativePath);
|
||||
IntPtr nativeName = IntPtr.Zero;
|
||||
try {
|
||||
nativeName = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(UnicodeString)));
|
||||
Marshal.StructureToPtr(name, nativeName, false);
|
||||
ObjectAttributes attributes = new ObjectAttributes();
|
||||
attributes.Length = Marshal.SizeOf(typeof(ObjectAttributes));
|
||||
attributes.RootDirectory = root.DangerousGetHandle();
|
||||
attributes.ObjectName = nativeName;
|
||||
attributes.Attributes = 0x1040; // OBJ_DONT_REPARSE | OBJ_CASE_INSENSITIVE
|
||||
const uint readWriteAcl = 0x00160083; // synchronize, WRITE_DAC, READ_CONTROL, attributes and data
|
||||
const uint options = 0x62; // FILE_NON_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT | FILE_WRITE_THROUGH
|
||||
IoStatus io;
|
||||
SafeFileHandle h;
|
||||
int status = NtOpenFile(out h, readWriteAcl, ref attributes, out io, 0, options);
|
||||
if (status != 0) throw new Win32Exception((int)RtlNtStatusToDosError(status));
|
||||
try {
|
||||
CheckSingleFile(h, 0);
|
||||
return new FileStream(h, FileAccess.ReadWrite);
|
||||
} catch { h.Dispose(); throw; }
|
||||
} finally {
|
||||
Marshal.FreeHGlobal(nativeName);
|
||||
Marshal.FreeHGlobal(name.Buffer);
|
||||
}
|
||||
}
|
||||
}
|
||||
public static void CheckSingleFile(SafeFileHandle handle, long expectedLength) {
|
||||
CheckAttributes(handle, false);
|
||||
StandardInfo info;
|
||||
if (!GetFileInformationByHandleEx(handle, 1, out info, (uint)Marshal.SizeOf(typeof(StandardInfo))))
|
||||
throw new Win32Exception(Marshal.GetLastWin32Error());
|
||||
if (info.NumberOfLinks != 1 || info.DeletePending != 0 || info.Directory != 0 ||
|
||||
info.EndOfFile != expectedLength)
|
||||
throw new InvalidOperationException("Expected one regular file of the exact size");
|
||||
}
|
||||
}
|
||||
'@
|
||||
}
|
||||
|
||||
function Get-HeldProfileFileId([IO.FileStream]$Stream) {
|
||||
$id = New-Object RmmPipeNative+FileId
|
||||
if (![RmmPipeNative]::GetFileInformationByHandleEx($Stream.SafeFileHandle, 18, [ref]$id, 24)) {
|
||||
throw 'New file identity unavailable'
|
||||
}
|
||||
return @{
|
||||
volume_serial=$id.Volume.ToString([Globalization.CultureInfo]::InvariantCulture)
|
||||
file_id=([BitConverter]::ToString($id.Id)).Replace('-','').ToLowerInvariant()
|
||||
}
|
||||
}
|
||||
|
||||
function Get-HeldProfileIdentity([IO.FileStream]$Stream) {
|
||||
[RmmInitialProfileFile]::CheckSingleFile($Stream.SafeFileHandle, 1177)
|
||||
$identity = Get-HeldProfileFileId $Stream
|
||||
$Stream.Position = 0
|
||||
$algorithm = [Security.Cryptography.SHA256]::Create()
|
||||
try { $digest = [BitConverter]::ToString($algorithm.ComputeHash($Stream)).Replace('-','').ToLowerInvariant() }
|
||||
finally { $algorithm.Dispose() }
|
||||
$sddl = $Stream.GetAccessControl().GetSecurityDescriptorSddlForm($aclSections)
|
||||
$identity.bytes = $Stream.Length
|
||||
$identity.sha256 = $digest
|
||||
$identity.acl_sha256 = BytesHash ([Text.Encoding]::UTF8.GetBytes($sddl))
|
||||
return $identity
|
||||
}
|
||||
|
||||
# Both accepted strings retain the protected DACL, owner, group and all ACEs.
|
||||
# Windows stored the newly created file without the auto-inherited marker.
|
||||
function Test-ProfileDescriptor([string]$ExpectedSddl, [string]$ActualSddl) {
|
||||
if (!$ExpectedSddl.StartsWith('O:BAG:BAD:PAI(', [StringComparison]::Ordinal)) { return $false }
|
||||
return $ActualSddl -ceq $ExpectedSddl -or $ActualSddl -ceq $ExpectedSddl.Replace('D:PAI(', 'D:P(')
|
||||
}
|
||||
|
||||
function New-OriginalPublicProfile {
|
||||
Initialize-InitialProfileNative
|
||||
$aclSections = [Security.AccessControl.AccessControlSections]'Owner,Group,Access'
|
||||
$accessOnly = [Security.AccessControl.AccessControlSections]::Access
|
||||
$draftAcl = [Security.AccessControl.FileSecurity]::new()
|
||||
$draftAcl.SetSecurityDescriptorSddlForm($stagedAcl.Sddl, $aclSections)
|
||||
foreach ($sid in @($agentSid,$helperSid)) {
|
||||
$deny = [Security.AccessControl.FileSystemAccessRule]::new(
|
||||
[Security.Principal.SecurityIdentifier]::new($sid),
|
||||
[Security.AccessControl.FileSystemRights]::ReadData, [Security.AccessControl.AccessControlType]::Deny)
|
||||
$draftAcl.AddAccessRule($deny)
|
||||
}
|
||||
$draftSddl = $draftAcl.GetSecurityDescriptorSddlForm($aclSections)
|
||||
if (!$draftAcl.AreAccessRulesProtected -or $draftSddl -ceq $stagedAcl.Sddl) { throw 'Initial protected DACL required' }
|
||||
|
||||
if ((BytesHash ([Text.Encoding]::UTF8.GetBytes($draftSddl))) -cne
|
||||
'd4726c7973c9b0cd8a66c1b129d1b5eb58d2bbfc1b103018e0a31a71fb1d9020') {
|
||||
throw 'Unexpected draft descriptor for this case'
|
||||
}
|
||||
$reserved = $false
|
||||
$phase = 'CreateNew'
|
||||
$descriptorFailure = $null
|
||||
if ($ResumeEmpty) {
|
||||
$attemptResult = $resumeResult
|
||||
$attemptError = $resumeError
|
||||
$attemptVerified = $resumeVerified
|
||||
} else {
|
||||
$attemptResult = $initialResult
|
||||
$attemptError = $initialError
|
||||
$attemptVerified = $initialVerified
|
||||
}
|
||||
try {
|
||||
if ($ResumeEmpty) {
|
||||
$phase = 'open_existing_empty'
|
||||
$stream = [RmmInitialProfileFile]::OpenExistingTarget()
|
||||
} else {
|
||||
$since = [DateTime]::UtcNow.ToString('o')
|
||||
WriteNew $initialReservation @{id=$caseId; config_sha256=$configHash; utc=$since; staged=$expected; create_new=$true}
|
||||
$reserved = $true
|
||||
$rights = [Security.AccessControl.FileSystemRights]'ReadData,WriteData,ReadAttributes,ReadPermissions,ChangePermissions,Synchronize'
|
||||
$stream = [IO.FileStream]::new($target, [IO.FileMode]::CreateNew,
|
||||
$rights, [IO.FileShare]::None, 4096,
|
||||
[IO.FileOptions]::WriteThrough, $draftAcl)
|
||||
}
|
||||
try {
|
||||
$phase = 'verify_creation'
|
||||
$actualSddl = $stream.GetAccessControl().GetSecurityDescriptorSddlForm($aclSections)
|
||||
if (!(Test-ProfileDescriptor $draftSddl $actualSddl)) {
|
||||
$descriptorFailure = @{expected_sddl=$draftSddl; actual_sddl=$actualSddl; bytes=$null}
|
||||
try {
|
||||
$descriptorFailure.bytes = $stream.Length
|
||||
$fileId = Get-HeldProfileFileId $stream
|
||||
$descriptorFailure.file_id = $fileId.file_id
|
||||
$descriptorFailure.volume_serial = $fileId.volume_serial
|
||||
} catch {
|
||||
$descriptorFailure.metadata_hresult = '0x{0:X8}' -f $_.Exception.GetBaseException().HResult
|
||||
}
|
||||
throw 'Unexpected security descriptor on new file'
|
||||
}
|
||||
[RmmInitialProfileFile]::CheckSingleFile($stream.SafeFileHandle, 0)
|
||||
$emptyId = Get-HeldProfileFileId $stream
|
||||
if ($emptyId.volume_serial -cne $expected.volume_serial -or
|
||||
$emptyId.file_id -ceq $expected.file_id -or $emptyId.file_id -ceq ('0' * 32)) {
|
||||
throw 'Unexpected volume or identity on held empty target'
|
||||
}
|
||||
$draftHash = BytesHash ([Text.Encoding]::UTF8.GetBytes($actualSddl))
|
||||
if ($ResumeEmpty) {
|
||||
$since = [DateTime]::UtcNow.ToString('o')
|
||||
WriteNew $resumeReservation @{
|
||||
id=$caseId; utc=$since; config_sha256=$configHash; target_id=$emptyId.file_id
|
||||
volume_serial=$emptyId.volume_serial; draft_acl_sha256=$draftHash; bytes=0
|
||||
}
|
||||
$reserved = $true
|
||||
}
|
||||
$phase = 'write_verify'
|
||||
$stream.Write($bytes, 0, $bytes.Length)
|
||||
$stream.Flush($true)
|
||||
$new = Get-HeldProfileIdentity $stream
|
||||
if ($new.volume_serial -cne $expected.volume_serial -or $new.file_id -ceq $expected.file_id -or
|
||||
$new.file_id -cne $emptyId.file_id -or $new.sha256 -cne $configHash -or
|
||||
$new.acl_sha256 -cne $draftHash) {
|
||||
throw 'New held bytes, identity or staging permissions differ'
|
||||
}
|
||||
SameLive $before (ActualState $true)
|
||||
$null = Kernel 'agent' $before.service $heldAgent
|
||||
$null = Kernel 'helper' $before.helper_service $heldHelper
|
||||
if (!(JsonEqual $expected (FileIdentity $staged)) -or (AclHash $helperRoot) -cne $rootAclHash) {
|
||||
throw 'Original source or target directory changed before publication'
|
||||
}
|
||||
WriteNew $attemptVerified @{
|
||||
id=$caseId; utc=$since; original_candidate=$expected; held_target=$new
|
||||
}
|
||||
# Change only the DACL by handle after the verified bytes and FileID
|
||||
# are durable. A crash before this point leaves service reads denied.
|
||||
$phase = 'publish_dacl'
|
||||
$final = $stream.GetAccessControl()
|
||||
$final.SetSecurityDescriptorSddlForm($stagedAcl.Sddl, $accessOnly)
|
||||
$stream.SetAccessControl($final)
|
||||
$stream.Flush($true)
|
||||
$actualFinal = $stream.GetAccessControl().GetSecurityDescriptorSddlForm($aclSections)
|
||||
if (!(Test-ProfileDescriptor $stagedAcl.Sddl $actualFinal)) { throw 'Unexpected final descriptor' }
|
||||
$new.acl_sha256 = BytesHash ([Text.Encoding]::UTF8.GetBytes($actualFinal))
|
||||
if (!(JsonEqual $new (Get-HeldProfileIdentity $stream))) { throw 'Held publication readback failed' }
|
||||
} finally { $stream.Dispose() }
|
||||
|
||||
$phase = 'readback'
|
||||
$null = ReadAcl $target $false
|
||||
$published = FileIdentity $target
|
||||
if (!(JsonEqual $new $published) -or !(JsonEqual $expected (FileIdentity $staged)) -or
|
||||
(AclHash $helperRoot) -cne $rootAclHash) { throw 'Final source/target binding failed' }
|
||||
$after = ActualState $true
|
||||
SameLive $before $after
|
||||
$null = Kernel 'agent' $before.service $heldAgent
|
||||
$null = Kernel 'helper' $before.helper_service $heldHelper
|
||||
$outcome = @{
|
||||
id=$caseId; installed=$true; publication_since=$since; configuration=$published
|
||||
original_candidate=$expected; source_candidate_preserved=$true; initial_create=$true
|
||||
native=$after; clock_runtime_qualified=$false; services_changed=$false; private_key_read=$false
|
||||
no_jobs=$true; original_move_failed=$true
|
||||
}
|
||||
if ($ResumeEmpty) { $outcome.resumed_empty = $true }
|
||||
WriteNew $attemptResult $outcome
|
||||
} catch {
|
||||
$cause = $_.Exception.GetBaseException()
|
||||
$failure = @{id=$caseId; phase=$phase; hresult=('0x{0:X8}' -f $cause.HResult); exception=$cause.GetType().FullName}
|
||||
if ($null -ne $descriptorFailure) { $failure.creation_descriptor = $descriptorFailure }
|
||||
if ($reserved) { WriteNew $attemptError $failure }
|
||||
throw
|
||||
}
|
||||
}
|
||||
|
||||
$heldAgent = [RmmPipeNative]::Open([int]$before.service.pid)
|
||||
try {
|
||||
$heldHelper = [RmmPipeNative]::Open([int]$before.helper_service.pid)
|
||||
try {
|
||||
$null = Kernel 'agent' $before.service $heldAgent
|
||||
$null = Kernel 'helper' $before.helper_service $heldHelper
|
||||
if ($InitialCreate -or $ResumeEmpty) {
|
||||
$rootAclHash = '186d85132cf0e16cbb9623ad9636b7777741939a8cae3d689a2af1eb267a7f49'
|
||||
New-OriginalPublicProfile
|
||||
'Zeitprofil am gebundenen Dateihandle veroeffentlicht und nachgelesen.'
|
||||
return
|
||||
}
|
||||
# WriteNew uses CreateNew. Concurrent or later invocations cannot republish.
|
||||
WriteNew $reservation @{id=$caseId; config_sha256=$configHash; utc=[DateTime]::UtcNow.ToString('o')}
|
||||
try {
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
#requires -Version 5.1
|
||||
#requires -RunAsAdministrator
|
||||
# The relay receives a fixed public receipt. There is no command reader.
|
||||
param([Parameter(Mandatory)][DateTimeOffset]$Until, [switch]$ResumeEmpty)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$until = [DateTimeOffset]::Parse('2026-11-15T17:00:00+00:00')
|
||||
$deadline = [DateTimeOffset]::UtcNow.AddMinutes(12)
|
||||
if ($deadline -gt $until) { $deadline = $until }
|
||||
if ($deadline -le [DateTimeOffset]::UtcNow) { throw 'Das Wartungsfenster ist abgelaufen.' }
|
||||
|
||||
$base = 'https://gitea.incoso.eu/kevin_janssen/rust-discovery/raw/commit/577132fb422bf854276b3afb5bafdb12d2c08427/deploy/windows'
|
||||
$base = 'https://gitea.incoso.eu/kevin_janssen/rust-discovery/raw/commit/b614b6f5be9d700eef20586a038aa9643356049a/deploy/windows'
|
||||
$bootstrap = 'C:\ProgramData\RustDiscoveryBootstrap'
|
||||
$caseId = 'ad9fd154-b2be-4f5d-9e17-65abb721ceaf'
|
||||
$case = Join-Path $bootstrap "time-profile-$caseId"
|
||||
@@ -24,7 +24,7 @@ $null = New-Item -ItemType Directory -Path $work
|
||||
$listener = $null
|
||||
$ssh = $null
|
||||
$scripts = [ordered]@{
|
||||
'Complete-OriginalTimeProfile.ps1' = '5ad85ae7a3a513d3cc2f5f5dca3e48eb42fd863522c3384f9c64cdcf0273ef1a'
|
||||
'Complete-OriginalTimeProfile.ps1' = 'aacc56321dccc6efe496a782d4cf67defba5b0be6759cba08d9e0b775913210b'
|
||||
'Read-PassiveTimeSamples.ps1' = 'd9e2b9344c19af1296b86ec70ba754ef820f369ac5ec897979bd4233e0722d04'
|
||||
}
|
||||
try {
|
||||
@@ -45,21 +45,54 @@ try {
|
||||
$ssh = Start-Process -FilePath "$sshBin\ssh.exe" -ArgumentList $options -PassThru -NoNewWindow
|
||||
if ($ssh.WaitForExit(1800)) { throw "SSH Exit $($ssh.ExitCode)" }
|
||||
Write-Host 'Wartungsfenster aktiv. Dieses Fenster offen lassen. Strg+C beendet es.'
|
||||
$receipt = [ordered]@{session=$session; case_id=$caseId; phase='preflight'; read_only_channel=$true}
|
||||
$result = Join-Path $case 'result.json'
|
||||
$method = 'initial_create'
|
||||
$prefix = 'console-initial-create'
|
||||
$arguments = @{ InitialCreate=$true }
|
||||
if ($ResumeEmpty) {
|
||||
$method = 'resume_empty'
|
||||
$prefix = 'console-resume-empty'
|
||||
$arguments = @{ ResumeEmpty=$true }
|
||||
}
|
||||
$receipt = [ordered]@{session=$session; case_id=$caseId; method=$method; phase='preflight'; read_only_channel=$true}
|
||||
$result = Join-Path $case "$prefix-result.json"
|
||||
$intentPath = Join-Path $case "$prefix-intent.json"
|
||||
$failurePath = Join-Path $case "$prefix-error.json"
|
||||
$receipt.finalizer_invoked = $false
|
||||
try {
|
||||
if (Test-Path -LiteralPath $failurePath) { throw 'Previous profile finalization error recorded' }
|
||||
if (!(Test-Path -LiteralPath $result)) {
|
||||
$null = & (Join-Path $work 'Complete-OriginalTimeProfile.ps1')
|
||||
if (Test-Path -LiteralPath $intentPath) { throw 'Previous profile finalization intent without result' }
|
||||
$receipt.finalizer_invoked = $true
|
||||
$null = & (Join-Path $work 'Complete-OriginalTimeProfile.ps1') @arguments
|
||||
}
|
||||
$record = Get-Content -LiteralPath $result -Raw | ConvertFrom-Json
|
||||
$actual = Get-FileHash -LiteralPath 'C:\ProgramData\RustDiscoverySystem\time-attestation.json'
|
||||
if ($record.id -cne $caseId -or $record.installed -ne $true -or
|
||||
$record.console_finalized -ne $true -or $record.clock_runtime_qualified -ne $false -or
|
||||
$record.initial_create -ne $true -or $record.source_candidate_preserved -ne $true -or
|
||||
$record.services_changed -ne $false -or $record.private_key_read -ne $false -or $record.clock_runtime_qualified -ne $false -or
|
||||
$actual.Hash -ne '2b4a8a7080770304b80e2a665fa5f5ee1ebbd9182e7c80b184e75b114575b42b') { throw 'Unexpected publication result' }
|
||||
$marker = Get-Content -LiteralPath (Join-Path $case 'console-finalization-intent.json') -Raw | ConvertFrom-Json
|
||||
if ($marker.id -cne $caseId -or $marker.config_sha256 -ne $actual.Hash) { throw 'Unexpected finalization intent' }
|
||||
$marker = Get-Content -LiteralPath $intentPath -Raw | ConvertFrom-Json
|
||||
if ($marker.id -cne $caseId -or $marker.utc -cne $record.publication_since -or
|
||||
$marker.config_sha256 -ne $actual.Hash -or $record.configuration.sha256 -ne $actual.Hash -or
|
||||
$record.original_candidate.file_id -cne '6d990300000003000000000000000000' -or
|
||||
$record.configuration.file_id -cnotmatch '^[0-9a-f]{32}$' -or $record.configuration.file_id -ceq '6d990300000003000000000000000000') { throw 'Unexpected finalization intent' }
|
||||
if ($ResumeEmpty) {
|
||||
if ($record.resumed_empty -ne $true -or $marker.target_id -cne $record.configuration.file_id) {
|
||||
throw 'Recovered profile file identity differs from the recovery intent'
|
||||
}
|
||||
$receipt.resumed_empty = $true
|
||||
$receipt.reserved_target_id = $marker.target_id
|
||||
}
|
||||
$receipt.phase = 'published'
|
||||
$receipt.publication_since = $marker.utc
|
||||
$receipt.publication_since = $record.publication_since
|
||||
$receipt.initial_create = $record.initial_create
|
||||
$receipt.source_candidate_preserved = $record.source_candidate_preserved
|
||||
$receipt.services_changed = $record.services_changed
|
||||
$receipt.private_key_read = $record.private_key_read
|
||||
$receipt.clock_runtime_qualified = $record.clock_runtime_qualified
|
||||
$receipt.source_id = $record.original_candidate.file_id
|
||||
$receipt.target_id = $record.configuration.file_id
|
||||
$receipt.config_sha256 = $actual.Hash.ToLowerInvariant()
|
||||
$receipt.result_sha256 = (Get-FileHash -LiteralPath $result).Hash
|
||||
} catch {
|
||||
$receipt.phase = 'finalization_failed'
|
||||
@@ -67,10 +100,24 @@ try {
|
||||
$receipt.line = $_.InvocationInfo.ScriptLineNumber
|
||||
$receipt.file = [IO.Path]::GetFileName($_.InvocationInfo.ScriptName)
|
||||
Write-Warning $_.Exception.Message
|
||||
$failurePath = Join-Path $case 'console-finalization-error.json'
|
||||
if (Test-Path -LiteralPath $failurePath) {
|
||||
$failure = Get-Content -LiteralPath $failurePath -Raw | ConvertFrom-Json
|
||||
if ($failure.id -ceq $caseId -and $failure.hresult -cmatch '^0x[0-9A-Fa-f]{8}$') { $receipt.move_hresult = $failure.hresult }
|
||||
if ($failure.id -ceq $caseId -and $failure.hresult -cmatch '^0x[0-9A-Fa-f]{8}$') {
|
||||
$receipt.hresult = $failure.hresult
|
||||
if ($failure.phase -cmatch '^[A-Za-z][A-Za-z0-9_.-]{0,63}$') { $receipt.failure_phase = $failure.phase }
|
||||
$descriptor = $failure.creation_descriptor
|
||||
if ($failure.phase -ceq 'verify_creation' -and $null -ne $descriptor -and
|
||||
$descriptor.expected_sddl -is [string] -and $descriptor.expected_sddl.Length -le 4096 -and
|
||||
$descriptor.actual_sddl -is [string] -and $descriptor.actual_sddl.Length -le 4096) {
|
||||
$receipt.creation_descriptor = @{
|
||||
expected_sddl=$descriptor.expected_sddl; actual_sddl=$descriptor.actual_sddl; bytes=$descriptor.bytes
|
||||
}
|
||||
if ($descriptor.file_id -cmatch '^[0-9a-f]{32}$' -and $descriptor.volume_serial -cmatch '^[0-9]{1,20}$') {
|
||||
$receipt.creation_descriptor.file_id = $descriptor.file_id
|
||||
$receipt.creation_descriptor.volume_serial = $descriptor.volume_serial
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
$readScript = Join-Path $work 'Read-PassiveTimeSamples.ps1'
|
||||
|
||||
@@ -0,0 +1,212 @@
|
||||
#requires -Version 5.1
|
||||
#requires -RunAsAdministrator
|
||||
# Publish the next trusted-OS profile from actual passive service observations.
|
||||
[CmdletBinding()]
|
||||
param([Parameter(Mandatory)][ValidateSet('Prepare','Publish','Read','FinishStarts')][string]$Action)
|
||||
$ErrorActionPreference='Stop'
|
||||
$commonHash='c54e36b32a2fcccb072f2cca52a38b6c4da31755d86205599016c5d180f5cec4'
|
||||
$common=Join-Path $PSScriptRoot 'Set-PassiveJobPair.ps1'
|
||||
if ((Get-FileHash -LiteralPath $common -Algorithm SHA256).Hash -ne $commonHash) {
|
||||
throw 'The reviewed passive-pair controller must be next to this script'
|
||||
}
|
||||
$text=[Text.Encoding]::UTF8.GetString([IO.File]::ReadAllBytes($common))
|
||||
$first="`n`$originalCase = "
|
||||
$last="`nif (`$Mode -eq 'Read') {"
|
||||
$i=$text.IndexOf($first,[StringComparison]::Ordinal)
|
||||
$j=$text.IndexOf($last,[StringComparison]::Ordinal)
|
||||
if ($i -lt 0 -or $j -le $i -or $i -ne $text.LastIndexOf($first,[StringComparison]::Ordinal) -or
|
||||
$j -ne $text.LastIndexOf($last,[StringComparison]::Ordinal)) { throw 'Passive-pair definition boundary' }
|
||||
# Fixed declarations and functions only. Its Prepare, Install and Restore bodies are excluded.
|
||||
. ([scriptblock]::Create($text.Substring($i,$j-$i)))
|
||||
CheckControl $work $true
|
||||
$activation=(Marker 'profile-publish-intent')
|
||||
$ready=(Marker 'profile-prepared')
|
||||
$success=(Marker 'profile-published')
|
||||
function RequireNewPassivePair {
|
||||
if ((Hash $config) -cne $configHash -or (Hash $helperBinary) -cne $helperHash -or
|
||||
(Test-Path -LiteralPath (Marker 'restore-intent'))) { throw 'Passive successor pair required' }
|
||||
VerifyFiles (CurrentFiles) $newHashes
|
||||
}
|
||||
function RoleDigests($platformHash,$installedHash,$independentHash,$previous) {
|
||||
$out=@{}
|
||||
foreach ($name in @('agent','system_helper')) {
|
||||
$bound=$installed.agent
|
||||
if ($name -ceq 'system_helper') { $bound=$installed.helper }
|
||||
$old=@($previous.trusted_os_active_guest.qualifications | Where-Object { $_.role -ceq $name })
|
||||
if ($old.Count -ne 1) { throw 'Expected one predecessor witness per role' }
|
||||
$archive=Join-Path $oldFolder ($name+'-qualification.json')
|
||||
CheckControl $archive $false
|
||||
if ((Hash $archive) -cne $old[0].qualification_sha256) { throw 'Original role provenance changed' }
|
||||
$archived=Get-Content -LiteralPath $archive -Raw | ConvertFrom-Json
|
||||
$build='a003dfa8cc2397a99933aceeb2d8dab51f883ab9cdf27876fbfc94a78873044c'
|
||||
if ($name -ceq 'system_helper') {
|
||||
# The old pair receipt linked the later agent and referenced the
|
||||
# separately built helper. Identify the actual helper link itself.
|
||||
$build='04ed34e6e850aca77c1fd4677ddb271f7ccd9492a97f5d4e00ead4c1f032f29d'
|
||||
}
|
||||
Record ('profile-role-'+$name) ([ordered]@{
|
||||
profile='rmm.windows.trusted-os.product-role-prerequisite.v1';role=$name
|
||||
binary_sha256=$bound.image_file.sha256; service=$bound.service; kernel=$bound.kernel
|
||||
image_file=$bound.image_file; predecessor_qualification_sha256=$old[0].qualification_sha256
|
||||
pair_case_id=$id; pair_result_sha256=$installedHash; independent_pair_readback_sha256=$independentHash
|
||||
product_build_receipt_sha256=$build; platform_provenance_sha256=$platformHash
|
||||
raw_capture=$archived.raw_capture; signed_runtime_verified=$false; physical_calibration_claimed=$false
|
||||
})
|
||||
$out[$name]=Hash (Marker ('profile-role-'+$name))
|
||||
}
|
||||
return $out
|
||||
}
|
||||
function BuildSuccessor {
|
||||
$installedHash=Hash (Marker 'installed')
|
||||
$unit=Join-Path $boot 'profile-unit-fcec400-result.json'
|
||||
if ((Hash $unit) -cne '48de474d842ebc87550ba2e27b66086e6aa573973f252f4b8e19ac7b12b75a63') { throw 'Windows unit evidence changed' }
|
||||
$independent=[ordered]@{agent=(LiveRole 'agent' $newHashes.agent);helper=(LiveRole 'helper' $helperHash);files=(CurrentFiles);device=(PreservedDevice)}
|
||||
foreach ($field in $independent.Keys) {
|
||||
if (!(JsonEqual $installed.$field $independent.$field)) { throw "Independent native pair read differs: $field" }
|
||||
}
|
||||
$independent.utc=[DateTime]::UtcNow.ToString('o')
|
||||
$independent.pair_case=$id
|
||||
Record 'profile-independent-native-read' $independent
|
||||
$independentHash=Hash (Marker 'profile-independent-native-read')
|
||||
$old=Get-Content -LiteralPath $target -Raw | ConvertFrom-Json
|
||||
if ($old.schema_version -ne 2 -or $old.key_generation -ne 1 -or
|
||||
$old.server_instance -cne 'c6f9657a-446f-49af-8fb8-bd8932939568' -or
|
||||
$old.trusted_os_active_guest.operating_assumption -cne 'active_guest_no_pause_save_restore_snapshot_migration_host_suspend' -or
|
||||
$old.trusted_os_active_guest.platform -cne 'kvm_qemu_hypervclock' -or
|
||||
@($old.trusted_os_active_guest.qualifications).Count -ne 2) { throw 'Unexpected original V2 contract' }
|
||||
$platform=Join-Path $oldFolder 'platform-provenance.json'
|
||||
CheckControl $platform $false
|
||||
$oldPlatformHash=Hash $platform
|
||||
if ($oldPlatformHash -cne $old.trusted_os_active_guest.platform_provenance_sha256) { throw 'Original platform provenance changed' }
|
||||
Record 'profile-platform' ([ordered]@{
|
||||
profile='rmm.windows.trusted-os.platform-provenance.v1';operating_assumption=$old.trusted_os_active_guest.operating_assumption
|
||||
platform=$old.trusted_os_active_guest.platform;previous_platform_provenance_sha256=$oldPlatformHash
|
||||
predecessor_profile_sha256=$profileHash;pair_case_id=$id;pair_result_sha256=$installedHash
|
||||
independent_pair_readback_sha256=$independentHash;independent_physical_calibration_claimed=$false
|
||||
agent_build_receipt_sha256='a003dfa8cc2397a99933aceeb2d8dab51f883ab9cdf27876fbfc94a78873044c'
|
||||
linux_profile_unit_sha256='ee3a2c99651491a2fd876f1a3463919dc32d9509d9f9ef4eb73a36aa848bb56d'
|
||||
windows_profile_unit_sha256=(Hash $unit)
|
||||
})
|
||||
$platformHash=Hash (Marker 'profile-platform')
|
||||
$roles=RoleDigests $platformHash $installedHash $independentHash $old
|
||||
$profileText=[Text.Encoding]::UTF8.GetString([IO.File]::ReadAllBytes($target))
|
||||
$changes=[ordered]@{}
|
||||
$changes[$oldHashes.agent]=$newHashes.agent
|
||||
$changes[$oldPlatformHash]=$platformHash
|
||||
foreach ($r in $old.trusted_os_active_guest.qualifications) {
|
||||
$changes[$r.qualification_sha256]=$roles[$r.role]
|
||||
}
|
||||
if ($changes.Count -ne 4) { throw 'Expected four independent substitutions' }
|
||||
foreach ($oldValue in $changes.Keys) {
|
||||
$pos=$profileText.IndexOf($oldValue,[StringComparison]::Ordinal)
|
||||
if ($pos -lt 0 -or $pos -ne $profileText.LastIndexOf($oldValue,[StringComparison]::Ordinal)) { throw 'Cannot uniquely bind successor' }
|
||||
$profileText=$profileText.Replace($oldValue,$changes[$oldValue])
|
||||
}
|
||||
$updated=$profileText | ConvertFrom-Json
|
||||
if ($updated.key_generation -ne $old.key_generation -or $updated.server_instance -cne $old.server_instance -or
|
||||
!(JsonEqual $old.binding $updated.binding) -or !(JsonEqual $old.public_keys_hex $updated.public_keys_hex)) {
|
||||
throw 'Unexpected trust-root changes'
|
||||
}
|
||||
$draft=Join-Path $work 'new-time-profile'
|
||||
WriteBytes $draft ([Text.UTF8Encoding]::new($false).GetBytes($profileText))
|
||||
CheckControl $draft $false
|
||||
$oldCopy=Join-Path $work 'old-time-profile'
|
||||
WriteBytes $oldCopy ([IO.File]::ReadAllBytes($target))
|
||||
if ((Hash $oldCopy) -cne $profileHash) { throw 'Time profile predecessor changed' }
|
||||
Record 'profile-prepared' ([ordered]@{
|
||||
id=$id;utc=[DateTime]::UtcNow.ToString('o');predecessor=(FileIdentity $target);successor_sha256=(Hash $draft)
|
||||
source_sha256=$installedHash;independent_sha256=$independentHash;platform_sha256=$platformHash;role_sha256=$roles
|
||||
original_publish_result_sha256='62a04be9c7d08d3687b51eacd6adbe290b91e16ba934d6b5bb531e8764a56cf5'
|
||||
predecessor_revision=1;successor_revision=2;signing_key_generation=$old.key_generation;clock_qualified=$false
|
||||
})
|
||||
}
|
||||
function CheckPrepared {
|
||||
if ($prepared.id -cne $id -or $prepared.predecessor.sha256 -cne $profileHash -or
|
||||
$prepared.successor_revision -ne 2 -or $prepared.predecessor_revision -ne 1 -or $prepared.signing_key_generation -ne 1 -or
|
||||
$prepared.source_sha256 -cne (Hash (Marker 'installed')) -or
|
||||
$prepared.independent_sha256 -cne (Hash (Marker 'profile-independent-native-read')) -or
|
||||
$prepared.platform_sha256 -cne (Hash (Marker 'profile-platform')) -or
|
||||
$prepared.successor_sha256 -cne (Hash (Join-Path $work 'new-time-profile')) -or
|
||||
$prepared.successor_sha256 -ceq $profileHash -or
|
||||
(Hash (Join-Path $work 'old-time-profile')) -cne $profileHash) { throw 'Successor preparation inconsistent' }
|
||||
foreach ($name in @('agent','system_helper')) {
|
||||
if ($prepared.role_sha256.$name -cne (Hash (Marker ('profile-role-'+$name)))) { throw 'Role proof changed' }
|
||||
}
|
||||
}
|
||||
function FinishPublication {
|
||||
$intent=LoadRecord 'profile-publish-intent'
|
||||
$actual=FileIdentity $target
|
||||
if ($intent.id -cne $id -or $intent.prepared_sha256 -cne (Hash $ready) -or
|
||||
$actual.sha256 -cne $prepared.successor_sha256 -or
|
||||
$actual.acl_sha256 -cne $prepared.predecessor.acl_sha256) { throw 'Successor readback failed' }
|
||||
if (Test-Path -LiteralPath (Marker 'time-installed-time')) {
|
||||
if (!(JsonEqual (LoadRecord 'time-installed-time') $actual)) { throw 'Installed profile identity changed' }
|
||||
} else {
|
||||
# An interrupted Replace can finish before the final journal write.
|
||||
# Recognize the recorded candidate and native backup without another Replace.
|
||||
StopCheck
|
||||
$attempt=LoadRecord 'time-replace-time'
|
||||
$previous=FileIdentity (Join-Path $work 'time-replaced-time')
|
||||
if (!(JsonEqual $attempt.previous $prepared.predecessor) -or
|
||||
$previous.sha256 -cne $prepared.predecessor.sha256 -or $previous.file_id -cne $prepared.predecessor.file_id -or
|
||||
$actual.file_id -cne $attempt.candidate.file_id -or $actual.volume_serial -cne $attempt.candidate.volume_serial) {
|
||||
throw 'Unconfirmed profile replacement: inspect current state'
|
||||
}
|
||||
Record 'time-installed-time' $actual
|
||||
}
|
||||
if (Test-Path -LiteralPath $success) { throw 'Already published: use Read' }
|
||||
foreach ($role in @('helper','agent')) {
|
||||
$hash=$newHashes.agent;$name=$agentName
|
||||
if ($role -eq 'helper') { $hash=$helperHash;$name=$helperName }
|
||||
$s=Service $role
|
||||
if ($s.state -ceq 'Stopped') {
|
||||
if (Test-Path -LiteralPath (Marker ('time-start-'+$role))) { throw "Existing unconfirmed $role start; read current state" }
|
||||
StartKnownRole $role $name $hash 'time'
|
||||
} elseif ($s.state -ceq 'Running') {
|
||||
if (!(Test-Path -LiteralPath (Marker ('time-start-'+$role)))) { throw "Unexpected independently started $role" }
|
||||
$null=LiveRole $role $hash
|
||||
} else { throw "Unexpected state $role" }
|
||||
}
|
||||
Record 'profile-published' ([ordered]@{
|
||||
id=$id;utc=[DateTime]::UtcNow.ToString('o');configuration=(FileIdentity $target)
|
||||
predecessor=$prepared.predecessor; successor_revision=2; signing_key_generation=1
|
||||
role_proofs=$prepared.role_sha256; publication_since=$intent.utc
|
||||
agent=(LiveRole 'agent' $newHashes.agent); helper=(LiveRole 'helper' $helperHash)
|
||||
signed_runtime_verified=$false; job_mode=$false;privileged_effects=$false
|
||||
})
|
||||
Write-Output "Published successor profile $id"
|
||||
}
|
||||
if ($Action -ceq 'Read') {
|
||||
$o=[ordered]@{id=$id;read_only=$true;configuration=(FileIdentity $target);agent=(Service 'agent');helper=(Service 'helper');marks=@()}
|
||||
$o.marks=@(Get-ChildItem -LiteralPath $work -Filter 'profile-*.json' -File | Select-Object -ExpandProperty Name)
|
||||
if (Test-Path -LiteralPath $success) { $o.published=LoadRecord 'profile-published' }
|
||||
$o|ConvertTo-Json -Depth 15 -Compress
|
||||
return
|
||||
}
|
||||
RequireNewPassivePair
|
||||
$installed=LoadRecord 'installed'
|
||||
if ($installed.id -cne $id -or $installed.job_mode -ne $false -or $installed.clock_qualified -ne $false) { throw 'Expected passive installation' }
|
||||
if ($Action -ceq 'Prepare') {
|
||||
VerifyPassiveContext
|
||||
if (Test-Path -LiteralPath $activation) { throw 'Already began publication' }
|
||||
BuildSuccessor
|
||||
Write-Output "Prepared successor profile from independent passive service proofs $id"
|
||||
return
|
||||
}
|
||||
$prepared=LoadRecord 'profile-prepared'
|
||||
CheckPrepared
|
||||
if ($Action -ceq 'FinishStarts') { FinishPublication;return }
|
||||
VerifyPassiveContext
|
||||
$held=LoadRecord 'profile-independent-native-read'
|
||||
if (!(JsonEqual $held.agent (LiveRole 'agent' $newHashes.agent)) -or
|
||||
!(JsonEqual $held.helper (LiveRole 'helper' $helperHash)) -or
|
||||
!(JsonEqual $held.device (PreservedDevice)) -or !(JsonEqual $prepared.predecessor (FileIdentity $target))) {
|
||||
throw 'Positive, unchanged passive pair and original time profile required before publication'
|
||||
}
|
||||
Record 'profile-publish-intent' ([ordered]@{id=$id;utc=[DateTime]::UtcNow.ToString('o');prepared_sha256=(Hash $ready)})
|
||||
StopKnownRole 'agent' $agentName $held.agent 'time'
|
||||
StopKnownRole 'helper' $helperName $held.helper 'time'
|
||||
$locations.Add('time',$target)
|
||||
SwapFile 'time' (Join-Path $work 'new-time-profile') $prepared.predecessor $prepared.successor_sha256 'time'
|
||||
$locations.Remove('time')
|
||||
FinishPublication
|
||||
@@ -0,0 +1,184 @@
|
||||
#requires -Version 5.1
|
||||
#requires -RunAsAdministrator
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[Parameter(Mandatory)][ValidateRange(1,9223372036854775807)][long]$Generation,
|
||||
[switch]$AfterRestart
|
||||
)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$caseId = '49c230d8-fb5d-4c64-96b6-e0edce03ed90'
|
||||
$bootDir = 'C:\ProgramData\RustDiscoveryBootstrap'
|
||||
$caseDir = Join-Path $bootDir "job-passive-pair-$caseId"
|
||||
$publication = Join-Path $caseDir 'profile-published.json'
|
||||
$profile = 'C:\ProgramData\RustDiscoverySystem\time-attestation.json'
|
||||
$reader = Join-Path $PSScriptRoot 'Read-PassiveTimeSamples.ps1'
|
||||
$readerHash = 'd9e2b9344c19af1296b86ec70ba754ef820f369ac5ec897979bd4233e0722d04'
|
||||
$agentHash = 'df80b00fc2119b973d690053b9f9e4bdedd8fbc211f67599c3301eeb42e7702f'
|
||||
$helperHash = '59675a3cbb3a5d213fc764f38379d6b81baaf9d47a7124470cc2767d4985763e'
|
||||
$sessionId = [guid]::NewGuid().ToString()
|
||||
|
||||
function Assert-CasePath([string]$Path, [bool]$Directory) {
|
||||
$item = Get-Item -LiteralPath $Path -Force
|
||||
if ($item.PSIsContainer -ne $Directory -or ($item.Attributes -band [IO.FileAttributes]::ReparsePoint)) {
|
||||
throw 'Unexpected local evidence path type'
|
||||
}
|
||||
$sid = [Security.Principal.SecurityIdentifier]
|
||||
$trusted = @('S-1-5-18','S-1-5-32-544')
|
||||
$acl = Get-Acl -LiteralPath $Path
|
||||
$rules = @($acl.GetAccessRules($true,$true,$sid))
|
||||
if ($acl.GetOwner($sid).Value -notin $trusted -or !$rules.Count) { throw 'Unprotected local evidence path' }
|
||||
foreach ($rule in $rules) {
|
||||
if ($rule.AccessControlType -ne 'Allow' -or $rule.IdentityReference.Value -notin $trusted) {
|
||||
throw 'Unexpected local evidence path access'
|
||||
}
|
||||
}
|
||||
}
|
||||
function Get-FileDigest([string]$Path) {
|
||||
return (Get-FileHash -LiteralPath $Path -Algorithm SHA256).Hash.ToLowerInvariant()
|
||||
}
|
||||
function Get-ByteDigest([byte[]]$Bytes) {
|
||||
$hash = [Security.Cryptography.SHA256]::Create()
|
||||
try { return [BitConverter]::ToString($hash.ComputeHash($Bytes)).Replace('-','').ToLowerInvariant() }
|
||||
finally { $hash.Dispose() }
|
||||
}
|
||||
function Get-BootUuid([string]$Ticks) {
|
||||
if ($Ticks -cnotmatch '^[0-9]{17,19}$') { throw 'Invalid CIM boot ticks' }
|
||||
$hash = Get-ByteDigest ([Text.Encoding]::ASCII.GetBytes("rmm.windows.boot.cim.ticks.v1:$Ticks"))
|
||||
$variant = '89ab'[[Convert]::ToInt32($hash.Substring(16,1),16) -band 3]
|
||||
return $hash.Substring(0,8)+'-'+$hash.Substring(8,4)+'-8'+$hash.Substring(13,3)+'-'+$variant+$hash.Substring(17,3)+'-'+$hash.Substring(20,12)
|
||||
}
|
||||
function Get-UtcNs($Value) {
|
||||
if ($Value -is [datetime]) { $Value = $Value.ToUniversalTime().ToString('o') }
|
||||
if ($Value -cnotmatch '^(\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d)(?:\.(\d{1,9}))?Z$') { throw 'Expected UTC timestamp' }
|
||||
$fraction = ([string]$Matches[2]).PadRight(9,'0')
|
||||
$seconds = [datetime]::ParseExact($Matches[1],"yyyy-MM-dd'T'HH:mm:ss",[Globalization.CultureInfo]::InvariantCulture)
|
||||
return [decimal]$seconds.Ticks * 100 + [decimal]$fraction
|
||||
}
|
||||
function Get-FiletimeNs([string]$Value) {
|
||||
if ($Value -cnotmatch '^[0-9]{1,19}$') { throw 'Invalid filetime' }
|
||||
return [decimal]([datetime]::FromFileTimeUtc([long]$Value).Ticks) * 100
|
||||
}
|
||||
function Get-VerifiedRecord($Wrapped, [string]$Role, $Native, $BootUuid, [decimal]$Since, [decimal]$Now) {
|
||||
if ($null -eq $Wrapped) { throw 'Waiting for both service samples' }
|
||||
$raw = [Convert]::FromBase64String($Wrapped.raw_base64)
|
||||
if ($raw.Length -lt 1 -or $raw.Length -gt 8192 -or (Get-ByteDigest $raw) -cne $Wrapped.sha256 -or $Wrapped.metadata.dacl_checked -ne $true) {
|
||||
throw 'Invalid wrapped report'
|
||||
}
|
||||
# Preserve JSON scalar types and duplicate keys, including all nine fractional digits.
|
||||
$xmlReader = [Runtime.Serialization.Json.JsonReaderWriterFactory]::CreateJsonReader($raw,[Xml.XmlDictionaryReaderQuotas]::Max)
|
||||
try { $doc = [xml]::new(); $doc.Load($xmlReader) } finally { $xmlReader.Close() }
|
||||
$fields = @{}
|
||||
$numbers = @('schema_version','agent_pid','connection_generation')
|
||||
$strings = @('observed_at','role','windows_boot_id','verifier_incarnation','request_sha256','response_sha256')
|
||||
if ($doc.DocumentElement.GetAttribute('type') -cne 'object') { throw 'Invalid report root' }
|
||||
foreach ($node in $doc.DocumentElement.ChildNodes) {
|
||||
$name = $node.Name
|
||||
if ($fields.ContainsKey($name)) { throw 'Duplicate report field' }
|
||||
$type = $node.GetAttribute('type')
|
||||
if ($name -cin $numbers -and $type -ceq 'number' -and $node.InnerText -cmatch '^[1-9][0-9]*$') {
|
||||
$fields[$name] = [long]$node.InnerText
|
||||
} elseif ($name -cin $strings -and $type -ceq 'string') {
|
||||
$fields[$name] = $node.InnerText
|
||||
} else { throw 'Unrecognized report field or type' }
|
||||
}
|
||||
if ($fields.Count -ne 9 -or $fields.schema_version -ne 1 -or $fields.role -cne $Role -or
|
||||
$fields.windows_boot_id -cne $BootUuid -or $fields.agent_pid -ne $Native.runtime.agent.pid -or
|
||||
$fields.connection_generation -ne $Generation) { throw 'Waiting for current role, process, boot and generation' }
|
||||
$uuid = [guid]::ParseExact($fields.verifier_incarnation,'D')
|
||||
if ($uuid -eq [guid]::Empty -or $uuid.ToString() -cne $fields.verifier_incarnation -or
|
||||
$fields.request_sha256 -cnotmatch '^[a-f0-9]{64}$' -or $fields.response_sha256 -cnotmatch '^[a-f0-9]{64}$') { throw 'Invalid report identity' }
|
||||
$observed = Get-UtcNs $fields.observed_at
|
||||
$written = Get-FiletimeNs $Wrapped.metadata.last_write_filetime
|
||||
$birth = Get-FiletimeNs $Native.runtime.agent.birth_filetime
|
||||
if ($Role -ceq 'system_helper') { $birth = [math]::Max($birth,(Get-FiletimeNs $Native.runtime.helper.birth_filetime)) }
|
||||
if ($observed -lt $Since -or $observed -lt $birth -or $Now -lt $observed -or $Now -lt $written -or
|
||||
$Now-$observed -gt 180000000000 -or $Now-$written -gt 180000000000 -or
|
||||
$written-$observed -lt -2000000000 -or $written-$observed -gt 90000000000) { throw 'Waiting for fresh samples from current services' }
|
||||
return $fields
|
||||
}
|
||||
function Read-NativeSamples([string]$Request) {
|
||||
$start = [Diagnostics.ProcessStartInfo]::new()
|
||||
$start.FileName = Join-Path ([Environment]::SystemDirectory) 'WindowsPowerShell\v1.0\powershell.exe'
|
||||
$start.Arguments = '-NoProfile -NonInteractive -ExecutionPolicy RemoteSigned -File "'+$reader+'"'
|
||||
$start.UseShellExecute = $false
|
||||
$start.RedirectStandardInput = $true
|
||||
$start.RedirectStandardOutput = $true
|
||||
$start.RedirectStandardError = $true
|
||||
$child = [Diagnostics.Process]::Start($start)
|
||||
try {
|
||||
$out = $child.StandardOutput.ReadToEndAsync()
|
||||
$err = $child.StandardError.ReadToEndAsync()
|
||||
$child.StandardInput.WriteLine($Request)
|
||||
$child.StandardInput.Close()
|
||||
if (!$child.WaitForExit(30000)) { throw 'Bounded public report read timed out' }
|
||||
if (!$out.Wait(2000) -or !$err.Wait(2000) -or $child.ExitCode -ne 0 -or $err.Result.Length -gt 0 -or
|
||||
$out.Result.Length -gt 65536) { throw 'Original reader did not return a complete native observation' }
|
||||
return ($out.Result | ConvertFrom-Json)
|
||||
} finally {
|
||||
try { if (!$child.HasExited) { $child.Kill() } } finally { $child.Dispose() }
|
||||
}
|
||||
}
|
||||
|
||||
Assert-CasePath $bootDir $true
|
||||
Assert-CasePath $caseDir $true
|
||||
Assert-CasePath $publication $false
|
||||
$publishedHash = Get-FileDigest $publication
|
||||
$pub = Get-Content -LiteralPath $publication -Raw | ConvertFrom-Json
|
||||
$profileHash = Get-FileDigest $profile
|
||||
if ($pub.id -cne $caseId -or $pub.configuration.sha256 -cne $profileHash -or
|
||||
$pub.agent.image_file.sha256 -cne $agentHash -or $pub.helper.image_file.sha256 -cne $helperHash -or
|
||||
$pub.successor_revision -ne 2 -or $pub.job_mode -ne $false) { throw 'Unexpected pair publication' }
|
||||
$since = Get-UtcNs $pub.publication_since
|
||||
$request = @{id=$sessionId;agent_sha256=$agentHash;helper_sha256=$helperHash} | ConvertTo-Json -Compress
|
||||
$clock = [Diagnostics.Stopwatch]::StartNew()
|
||||
$mode = 'passive'
|
||||
if ($AfterRestart) { $mode = 'after-restart' }
|
||||
$readerHandle = [IO.File]::Open($reader,'Open','Read','Read')
|
||||
try {
|
||||
if ((Get-FileDigest $reader) -cne $readerHash) { throw 'Original public sample reader changed' }
|
||||
do {
|
||||
$native = Read-NativeSamples $request
|
||||
if ($native.id -cne $sessionId -or $native.read_only -ne $true) { throw 'Invalid read response' }
|
||||
$agent = $native.runtime.agent
|
||||
$helper = $native.runtime.helper
|
||||
if ($helper.birth_filetime -cne $pub.helper.kernel.creation_filetime -or $helper.pid -ne $pub.helper.kernel.pid) { throw 'Helper generation changed' }
|
||||
if ($AfterRestart) {
|
||||
if ([long]$agent.birth_filetime -le [long]$pub.agent.kernel.creation_filetime) { throw 'Waiting for a later agent generation' }
|
||||
} elseif ($agent.birth_filetime -cne $pub.agent.kernel.creation_filetime -or $agent.pid -ne $pub.agent.kernel.pid) { throw 'Published agent generation changed' }
|
||||
$bootId = Get-BootUuid $native.boot_ticks
|
||||
$now = Get-UtcNs $native.observed_at
|
||||
try {
|
||||
$agentFile = $native.reports.'agent-time-sample.json'
|
||||
$helperFile = $native.reports.'helper-time-sample.json'
|
||||
$a = Get-VerifiedRecord $agentFile 'agent' $native $bootId $since $now
|
||||
$h = Get-VerifiedRecord $helperFile 'system_helper' $native $bootId $since $now
|
||||
foreach ($key in 'verifier_incarnation','request_sha256','response_sha256') {
|
||||
if ($a[$key] -ceq $h[$key]) { throw 'Time roles are not independent' }
|
||||
}
|
||||
break
|
||||
} catch {
|
||||
if (!$_.Exception.Message.StartsWith('Waiting for ') -or $clock.Elapsed.TotalSeconds -ge 120) { throw }
|
||||
Start-Sleep -Seconds 2
|
||||
}
|
||||
} while ($true)
|
||||
} finally { $readerHandle.Dispose() }
|
||||
if ((Get-FileDigest $profile) -cne $profileHash -or (Get-FileDigest $publication) -cne $publishedHash) { throw 'Profile changed during read' }
|
||||
$result = [ordered]@{
|
||||
session_id=$sessionId; pair_case_id=$caseId; mode=$mode; profile_sha256=$profileHash
|
||||
profile_receipt_sha256=$publishedHash; publication_since=$pub.publication_since; observed_at=$native.observed_at
|
||||
agent_pid=$agent.pid; agent_birth_filetime=$agent.birth_filetime; helper_pid=$helper.pid; helper_birth_filetime=$helper.birth_filetime
|
||||
windows_boot_id=$bootId; connection_generation=$Generation; agent_sample_sha256=$agentFile.sha256; helper_sample_sha256=$helperFile.sha256
|
||||
agent_observed_at=$a.observed_at; helper_observed_at=$h.observed_at; agent_verifier_id=$a.verifier_incarnation; helper_verifier_id=$h.verifier_incarnation
|
||||
reader_sha256=$readerHash
|
||||
}
|
||||
$result.native = $native
|
||||
$bytes = [Text.Encoding]::UTF8.GetBytes(($result | ConvertTo-Json -Depth 16 -Compress))
|
||||
$file = Join-Path $caseDir "samples-$mode-$sessionId.json"
|
||||
$out = [IO.File]::Open($file,'CreateNew','Write','None')
|
||||
try { $out.Write($bytes,0,$bytes.Length); $out.Flush($true) } finally { $out.Dispose() }
|
||||
Assert-CasePath $file $false
|
||||
$receiptHash = Get-FileDigest $file
|
||||
if ($receiptHash -cne (Get-ByteDigest $bytes)) { throw 'Receipt readback failed' }
|
||||
$result.Remove('native')
|
||||
$result.receipt_sha256 = $receiptHash
|
||||
$result | ConvertTo-Json -Depth 5 -Compress
|
||||
@@ -0,0 +1,136 @@
|
||||
#requires -Version 5.1
|
||||
#requires -RunAsAdministrator
|
||||
# Resume the single observed interrupted first staging copy on the test VM.
|
||||
[CmdletBinding()]
|
||||
param([Parameter(Mandatory)][ValidateSet('Read','Resume')][string]$Action)
|
||||
$ErrorActionPreference='Stop'
|
||||
$base=Join-Path $PSScriptRoot 'Set-PassiveJobPair.ps1'
|
||||
$baseHash='c54e36b32a2fcccb072f2cca52a38b6c4da31755d86205599016c5d180f5cec4'
|
||||
if ((Get-FileHash -LiteralPath $base).Hash -ne $baseHash) { throw 'Original passive-pair controller differs' }
|
||||
$text=[IO.File]::ReadAllText($base)
|
||||
$i=$text.IndexOf("`n`$originalCase = ",[StringComparison]::Ordinal)
|
||||
$j=$text.IndexOf("`nif (`$Mode -eq 'Read') {",[StringComparison]::Ordinal)
|
||||
if ($i -le 0 -or $j -le $i) { throw 'Original fixed declaration boundary' }
|
||||
. ([scriptblock]::Create($text.Substring($i,$j-$i)))
|
||||
Add-Type -TypeDefinition @'
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.ComponentModel;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Security.Cryptography;
|
||||
using Microsoft.Win32.SafeHandles;
|
||||
|
||||
public static class RmmPassiveStage {
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
private struct Basic { public long Created,Accessed,Written,Changed; public uint Attributes; }
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
private struct Standard { public long Allocated,End; public uint Links; public byte Pending,Directory; }
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
private struct Id { public ulong Volume, Low, High; }
|
||||
[DllImport("kernel32.dll",CharSet=CharSet.Unicode,ExactSpelling=true,SetLastError=true)]
|
||||
private static extern SafeFileHandle CreateFileW(string path,uint access,uint sharing,IntPtr security,uint disposition,uint flags,IntPtr template);
|
||||
[DllImport("kernel32.dll",SetLastError=true)]
|
||||
private static extern bool GetFileInformationByHandleEx(SafeFileHandle h,int k,out Basic b,uint n);
|
||||
[DllImport("kernel32.dll",SetLastError=true)]
|
||||
private static extern bool GetFileInformationByHandleEx(SafeFileHandle h,int k,out Standard s,uint n);
|
||||
[DllImport("kernel32.dll",SetLastError=true)]
|
||||
private static extern bool GetFileInformationByHandleEx(SafeFileHandle h,int k,out Id id,uint n);
|
||||
[DllImport("kernel32.dll",SetLastError=true)]
|
||||
private static extern bool SetFileInformationByHandle(SafeFileHandle h,int k,ref Basic b,uint n);
|
||||
private static string Hex(byte[] bytes) { return BitConverter.ToString(bytes).Replace("-","").ToLowerInvariant(); }
|
||||
public static uint Check(string expectedId,string digest,string volume,bool clear) {
|
||||
const string path=@"C:\ProgramData\RustDiscoveryBootstrap\job-passive-pair-49c230d8-fb5d-4c64-96b6-e0edce03ed90\install-stage-agent";
|
||||
using (SafeFileHandle h=CreateFileW(path,clear?0x181u:0x81u,0,IntPtr.Zero,3,0x00200000,IntPtr.Zero)) {
|
||||
if (h.IsInvalid) throw new Win32Exception();
|
||||
Basic b; Standard s; Id id;
|
||||
uint nb=(uint)Marshal.SizeOf(typeof(Basic));
|
||||
if (!GetFileInformationByHandleEx(h,0,out b,nb) ||
|
||||
!GetFileInformationByHandleEx(h,1,out s,(uint)Marshal.SizeOf(typeof(Standard))) ||
|
||||
!GetFileInformationByHandleEx(h,18,out id,(uint)Marshal.SizeOf(typeof(Id)))) throw new Win32Exception();
|
||||
string hexId=Hex(BitConverter.GetBytes(id.Low))+Hex(BitConverter.GetBytes(id.High));
|
||||
if (s.Directory!=0 || s.Pending!=0 || s.End!=23541484 || s.Links!=1 || (b.Attributes & 0x410)!=0 ||
|
||||
id.Volume.ToString(System.Globalization.CultureInfo.InvariantCulture)!=volume || expectedId!=hexId)
|
||||
throw new InvalidDataException("Unexpected stage identity/type/links");
|
||||
using (var fs=new FileStream(h,FileAccess.Read))
|
||||
using (var hash=SHA256.Create()) {
|
||||
if (Hex(hash.ComputeHash(fs))!=digest) throw new InvalidDataException("Staged image hash changed");
|
||||
uint original=b.Attributes;
|
||||
if (clear) {
|
||||
if ((original & 1)==0) throw new InvalidDataException("ReadOnly not present");
|
||||
Basic changed=new Basic();changed.Attributes=original & ~1u;
|
||||
if (changed.Attributes==0) changed.Attributes=0x80; // FILE_ATTRIBUTE_NORMAL
|
||||
if (!SetFileInformationByHandle(h,0,ref changed,nb) ||
|
||||
!GetFileInformationByHandleEx(h,0,out b,nb)) throw new Win32Exception();
|
||||
if (b.Attributes!=changed.Attributes) throw new InvalidDataException("Attribute verification");
|
||||
}
|
||||
return original;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
'@
|
||||
VerifyPassiveContext
|
||||
StopCheck
|
||||
CheckControl $work $true
|
||||
$expected=@('prepared.json','install-intent.json','install-stop-agent.json','install-stop-helper.json',
|
||||
'old-agent','old-settings','old-pin','new-settings','new-pin','install-stage-agent')
|
||||
$found=@(Get-ChildItem -LiteralPath $work -Force | ForEach-Object { $_.Name })
|
||||
if (@(Compare-Object -CaseSensitive ($expected|Sort-Object) ($found|Sort-Object)).Count) {
|
||||
throw 'Only the original completed preparation, two stops and first private staging copy may exist'
|
||||
}
|
||||
foreach ($f in $expected) { CheckControl (Join-Path $work $f) $false }
|
||||
$prep=LoadRecord 'prepared';$intent=LoadRecord 'install-intent'
|
||||
if ($prep.id -cne $id -or $intent.id -cne $id -or !(JsonEqual $prep.files (CurrentFiles)) -or
|
||||
!(JsonEqual $prep.device (PreservedDevice)) -or !(JsonEqual $prep.agent (LoadRecord 'install-stop-agent')) -or
|
||||
!(JsonEqual $prep.helper (LoadRecord 'install-stop-helper'))) { throw 'Stored original stop, device or protected file identity changed' }
|
||||
VerifyFiles $prep.files $oldHashes
|
||||
foreach ($n in $locations.Keys) {
|
||||
if ((Hash (Join-Path $work ('old-'+$n))) -cne $oldHashes.$n) { throw 'Recovery backup changed' }
|
||||
}
|
||||
foreach ($n in @('settings','pin')) {
|
||||
if ((Hash (Join-Path $work ('new-'+$n))) -cne $newHashes.$n) { throw 'Settings candidate changed' }
|
||||
}
|
||||
CheckControl (Split-Path $source) $true
|
||||
CheckControl $source $false
|
||||
$stagedPath=Join-Path $work 'install-stage-agent'
|
||||
$originalCopy=FileIdentity $stagedPath
|
||||
$sourceId=FileIdentity $source
|
||||
if ($sourceId.sha256 -cne $newHashes.agent -or $originalCopy.sha256 -cne $newHashes.agent -or
|
||||
$originalCopy.file_id -ceq $sourceId.file_id -or $originalCopy.volume_serial -cne $prep.files.agent.volume_serial -or
|
||||
$originalCopy.file_id -ceq $prep.files.agent.file_id) { throw 'Staged copy not separately bound to expected image' }
|
||||
$flags=[RmmPassiveStage]::Check($originalCopy.file_id,$newHashes.agent,$originalCopy.volume_serial,$false)
|
||||
if ($Action -ceq 'Read') {
|
||||
[ordered]@{id=$id;both_services_stopped=$true;no_replacement_markers=$true;private_stage=$originalCopy
|
||||
attributes=[string]([IO.FileAttributes]$flags);readonly=[bool]($flags -band 1);links=1;source_id=$sourceId.file_id} |
|
||||
ConvertTo-Json -Depth 6 -Compress
|
||||
return
|
||||
}
|
||||
if ($flags -ne 0x2021 -or (Get-Item -LiteralPath $source -Force).Attributes -ne [IO.FileAttributes]0x2021) {
|
||||
throw 'Source and own staging copy must have the observed ReadOnly, Archive, NotContentIndexed attributes'
|
||||
}
|
||||
Record 'install-resume-stage-intent' @{id=$id;utc=[DateTime]::UtcNow.ToString('o');stage=$originalCopy;attributes=$flags;source=$sourceId}
|
||||
$null=[RmmPassiveStage]::Check($originalCopy.file_id,$newHashes.agent,$originalCopy.volume_serial,$true)
|
||||
if (!(JsonEqual $originalCopy (FileIdentity $stagedPath))) { throw 'Changed staged file after clearing its copy-only attribute' }
|
||||
# Run the original checked swap from FlushFile onward for the existing first stage.
|
||||
# For the two JSON files retain the original CreateNew-style copy in full.
|
||||
$from=$text.IndexOf('function SwapFile(',[StringComparison]::Ordinal)
|
||||
$to=$text.IndexOf('function StartKnownRole(',[StringComparison]::Ordinal)
|
||||
$swap=$text.Substring($from,$to-$from)
|
||||
$copy='[IO.File]::Copy($inputPath,$stage,$false)'
|
||||
if (!$swap.Contains($copy) -or $swap.IndexOf($copy) -ne $swap.LastIndexOf($copy)) { throw 'Copy resume boundary' }
|
||||
$branch='if ($name -ceq "agent") { if (!(JsonEqual $originalCopy (FileIdentity $stage))) { throw "Existing private copy changed" } } else { '+$copy+' }'
|
||||
. ([scriptblock]::Create($swap.Replace($copy,$branch)))
|
||||
foreach ($name in $locations.Keys) {
|
||||
$inputPath=Join-Path $work ('new-'+$name)
|
||||
if ($name -ceq 'agent') { $inputPath=$source }
|
||||
SwapFile $name $inputPath $prep.files.$name $newHashes.$name 'install'
|
||||
}
|
||||
VerifyFiles (CurrentFiles) $newHashes
|
||||
StartKnownRole 'helper' $helperName $helperHash 'install'
|
||||
StartKnownRole 'agent' $agentName $newHashes.agent 'install'
|
||||
$a=LiveRole 'agent' $newHashes.agent
|
||||
$h=LiveRole 'helper' $helperHash
|
||||
if (!(JsonEqual $prep.device (PreservedDevice))) { throw 'Device changed after passive restart' }
|
||||
Record 'installed' ([ordered]@{id=$id;utc=[DateTime]::UtcNow.ToString('o');agent=$a;helper=$h;files=(CurrentFiles)
|
||||
device=$prep.device;job_mode=$false;clock_qualified=$false})
|
||||
Write-Output "Installed passive pair from confirmed read-only copy $id"
|
||||
@@ -0,0 +1,215 @@
|
||||
#requires -Version 5.1
|
||||
#requires -RunAsAdministrator
|
||||
[CmdletBinding()]
|
||||
param([Parameter(Mandatory)][ValidateSet('Inspect','Prepare','Activate','Readback')][string]$Mode)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$caseId = '49c230d8-fb5d-4c64-96b6-e0edce03ed90'
|
||||
$boot = 'C:\ProgramData\RustDiscoveryBootstrap'
|
||||
$case = Join-Path $boot "job-config-$caseId"
|
||||
$root = 'C:\ProgramData\RustDiscovery'
|
||||
$state = Join-Path $root 'state'
|
||||
$config = Join-Path $root 'config.json'
|
||||
$binding = Join-Path $root 'binding.json'
|
||||
$jobs = Join-Path $state 'jobs'
|
||||
$systemRoot = 'C:\ProgramData\RustDiscoverySystem'
|
||||
$pin = Join-Path $systemRoot 'agent-pin.json'
|
||||
$clock = Join-Path $systemRoot 'time-attestation.json'
|
||||
$image = 'C:\Program Files\RustDiscovery\rmm-agent-windows.exe'
|
||||
$helperImage = 'C:\Program Files\RustDiscovery\rmm-helper-windows.exe'
|
||||
$oldConfig = '7c9f6f3642ef84337c3cd761d8a4788c4babe81522fdd987a3eb9b819bc8d851'
|
||||
$oldConfigAcl = '014e89cc8674259dd9ac7f490ffef056b85ada96c6e3574c23f27668b7a9b991'
|
||||
$expectedBinding = '9239ee9f4142735867e77451478bf309fbf449d730a0ede6c958bc8018830dde'
|
||||
$oldAgent = '0549d9ebea73cff996938f859b92192cc333de194128d7c6859a3f1d2e85893c'
|
||||
$newAgent = 'df80b00fc2119b973d690053b9f9e4bdedd8fbc211f67599c3301eeb42e7702f'
|
||||
$helper = '59675a3cbb3a5d213fc764f38379d6b81baaf9d47a7124470cc2767d4985763e'
|
||||
$agentSid = ([Security.Principal.NTAccount]::new('NT SERVICE','RmmDiscoveryWindows')).Translate([Security.Principal.SecurityIdentifier]).Value
|
||||
$utf8 = [Text.UTF8Encoding]::new($false,$true)
|
||||
$sidType = [Security.Principal.SecurityIdentifier]
|
||||
$admins = @('S-1-5-18','S-1-5-32-544')
|
||||
$ready = Join-Path $case 'prepared.json'
|
||||
$entered = Join-Path $case 'activation-intent.json'
|
||||
$done = Join-Path $case 'activated.json'
|
||||
$candidate = Join-Path $case 'job-config.candidate.json'
|
||||
$original = Join-Path $case 'passive-config.original.json'
|
||||
$publicBinding = Join-Path $case 'public-binding.json'
|
||||
$next = Join-Path $root "config-$caseId.next"
|
||||
$backup = Join-Path $case 'replaced.original.json'
|
||||
|
||||
function Assert-NormalPath([string]$Path,[bool]$Directory) {
|
||||
$item = Get-Item -LiteralPath $Path -Force
|
||||
if ($item.PSIsContainer -ne $Directory) { throw "Unerwarteter Pfadtyp: $Path" }
|
||||
while ($null -ne $item) {
|
||||
if (($item.Attributes -band [IO.FileAttributes]::ReparsePoint) -ne 0) { throw "Reparsepunkt: $Path" }
|
||||
if ($item -is [IO.FileInfo]) { $item = $item.Directory } else { $item = $item.Parent }
|
||||
}
|
||||
}
|
||||
function Get-PublicHash([string]$Path) {
|
||||
Assert-NormalPath $Path $false
|
||||
return (Get-FileHash -LiteralPath $Path -Algorithm SHA256).Hash.ToLowerInvariant()
|
||||
}
|
||||
function Get-BytesDigest([byte[]]$Bytes) {
|
||||
$alg = [Security.Cryptography.SHA256]::Create()
|
||||
try { return [BitConverter]::ToString($alg.ComputeHash($Bytes)).Replace('-','').ToLowerInvariant() }
|
||||
finally { $alg.Dispose() }
|
||||
}
|
||||
function Assert-DirectoryAcl([string]$Path,[bool]$AgentCanRead) {
|
||||
Assert-NormalPath $Path $true
|
||||
$acl = Get-Acl -LiteralPath $Path
|
||||
if ($acl.GetOwner($sidType).Value -notin $admins) { throw "Verzeichniseigentuemer: $Path" }
|
||||
$rules = @($acl.GetAccessRules($true,$true,$sidType))
|
||||
if (!$rules.Count) { throw "Leere DACL: $Path" }
|
||||
foreach ($rule in $rules) {
|
||||
$sid = $rule.IdentityReference.Value
|
||||
if ($rule.AccessControlType -ne 'Allow' -or
|
||||
($sid -notin $admins -and !($AgentCanRead -and $sid -ceq $agentSid -and
|
||||
(([long]$rule.FileSystemRights -band (-bnot 0x1200a9)) -eq 0)))) { throw "Verzeichnisrechte: $Path" }
|
||||
}
|
||||
}
|
||||
function Write-Once([string]$Path,[byte[]]$Bytes,[Security.AccessControl.FileSecurity]$Acl) {
|
||||
if ($null -eq $Acl) {
|
||||
$stream = [IO.File]::Open($Path,'CreateNew','Write','None')
|
||||
} else {
|
||||
$stream = [IO.FileStream]::new($Path,[IO.FileMode]::CreateNew,[Security.AccessControl.FileSystemRights]::Write,
|
||||
[IO.FileShare]::None,4096,[IO.FileOptions]::WriteThrough,$Acl)
|
||||
}
|
||||
try { $stream.Write($Bytes,0,$Bytes.Length); $stream.Flush($true) } finally { $stream.Dispose() }
|
||||
}
|
||||
function Save-Record([string]$Path,$Record) {
|
||||
Write-Once $Path ($utf8.GetBytes(($Record | ConvertTo-Json -Depth 8 -Compress))) $null
|
||||
}
|
||||
function Read-PublicJson([string]$Path) {
|
||||
Assert-NormalPath $Path $false
|
||||
if ((Get-Item -LiteralPath $Path).Length -gt 32768) { throw "Datei zu gross: $Path" }
|
||||
return ($utf8.GetString([IO.File]::ReadAllBytes($Path)) | ConvertFrom-Json)
|
||||
}
|
||||
function Get-OriginalAcl {
|
||||
$acl = Get-Acl -LiteralPath $config
|
||||
if ((Get-BytesDigest ($utf8.GetBytes($acl.Sddl))) -cne $oldConfigAcl) { throw 'Originale Konfigurations-DACL abweichend' }
|
||||
return $acl
|
||||
}
|
||||
function Assert-FileAcl([string]$Path,$Expected) {
|
||||
$sections = [Security.AccessControl.AccessControlSections]'Owner,Group,Access'
|
||||
$actual = (Get-Acl -LiteralPath $Path).GetSecurityDescriptorSddlForm($sections)
|
||||
$wanted = $Expected.GetSecurityDescriptorSddlForm($sections)
|
||||
# File creation can omit the auto-inherited marker on this VM. Owner,
|
||||
# group, protected DACL, access masks and ACE sequence must all match.
|
||||
if ($actual -cne $wanted -and $actual -cne $wanted.Replace('D:PAI(', 'D:P(')) {
|
||||
throw "Dateiberechtigungen abweichend: $Path"
|
||||
}
|
||||
}
|
||||
function Get-ConfigurationInputs {
|
||||
if ((Get-PublicHash $config) -cne $oldConfig) { throw 'Passive Originalkonfiguration abweichend' }
|
||||
$null = Get-OriginalAcl
|
||||
$value = Read-PublicJson $config
|
||||
$names = @($value.PSObject.Properties.Name | Sort-Object)
|
||||
if (($names -join ',') -cne 'ca_file,connect_address,enrollment_token_file,server_name,state_directory,transport' -or
|
||||
$value.server_name -cne 'discovery.ease-technologies.de' -or $value.state_directory -ine $state -or $value.transport -cne 'auto') {
|
||||
throw 'Unerwartete passive Konfigurationsfelder'
|
||||
}
|
||||
$value | Add-Member -NotePropertyName job_binding_file -NotePropertyValue $binding
|
||||
$value | Add-Member -NotePropertyName enable_jobs -NotePropertyValue $true
|
||||
$value | Add-Member -NotePropertyName windows_execution_profile -NotePropertyValue 'powershell_51_remote_signed'
|
||||
$peer = Read-PublicJson $pin
|
||||
$b = $peer.binding
|
||||
$canonical = [ordered]@{agent_id=$b.agent_id;asset_id=$b.asset_id;assignment_version=$b.assignment_version;
|
||||
enrollment_generation=$b.enrollment_generation;public_key_hex=$b.public_key_hex;tenant_id=$b.tenant_id}
|
||||
$bindingBytes = $utf8.GetBytes(($canonical | ConvertTo-Json -Compress))
|
||||
if ((Get-BytesDigest $bindingBytes) -cne $expectedBinding) { throw 'Oeffentliche Jobbindung abweichend' }
|
||||
return @{config=$utf8.GetBytes(($value | ConvertTo-Json -Compress)); binding=$bindingBytes}
|
||||
}
|
||||
function Get-JobsAcl {
|
||||
$acl = [Security.AccessControl.DirectorySecurity]::new()
|
||||
$acl.SetSecurityDescriptorSddlForm("O:BAG:BAD:P(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)(A;OICI;0x1301bf;;;$agentSid)")
|
||||
return $acl
|
||||
}
|
||||
function Assert-JobsAcl {
|
||||
Assert-NormalPath $jobs $true
|
||||
$acl = Get-Acl -LiteralPath $jobs
|
||||
if (!$acl.AreAccessRulesProtected -or $acl.GetOwner($sidType).Value -notin $admins) { throw 'Jobverzeichnis nicht geschuetzt' }
|
||||
$expected = (Get-JobsAcl).GetAccessRules($true,$false,$sidType)
|
||||
$rules = $acl.GetAccessRules($true,$true,$sidType)
|
||||
if ($rules.Count -ne $expected.Count) { throw 'Job-DACL Anzahl' }
|
||||
foreach ($e in $expected) {
|
||||
$match = @($rules | Where-Object { !$_.IsInherited -and $_.IdentityReference.Value -ceq $e.IdentityReference.Value -and
|
||||
$_.FileSystemRights -eq $e.FileSystemRights -and $_.AccessControlType -eq $e.AccessControlType -and
|
||||
$_.InheritanceFlags -eq $e.InheritanceFlags -and $_.PropagationFlags -eq $e.PropagationFlags })
|
||||
if ($match.Count -ne 1) { throw 'Job-DACL abweichend' }
|
||||
}
|
||||
}
|
||||
function Get-Readback {
|
||||
$files = [ordered]@{}
|
||||
foreach ($p in @($config,$binding,$candidate,$publicBinding,$original,$next,$backup,$ready,$entered,$done,$image,$helperImage,$clock)) {
|
||||
$files[$p] = if ([IO.File]::Exists($p)) { Get-PublicHash $p } else { $null }
|
||||
}
|
||||
$jobsAcl = $null
|
||||
if (Test-Path -LiteralPath $jobs) {
|
||||
try { Assert-JobsAcl; $jobsAcl = $true } catch { $jobsAcl = $false }
|
||||
}
|
||||
$aclHashes = [ordered]@{}
|
||||
foreach ($p in @($root,$state,$config,$binding,$jobs,$case)) {
|
||||
if (Test-Path -LiteralPath $p) {
|
||||
Assert-NormalPath $p ([IO.Directory]::Exists($p))
|
||||
$aclHashes[$p] = Get-BytesDigest ($utf8.GetBytes((Get-Acl -LiteralPath $p).Sddl))
|
||||
}
|
||||
}
|
||||
$live = Read-PublicJson $config
|
||||
return [ordered]@{case_id=$caseId; agent_state=[string](Get-Service RmmDiscoveryWindows).Status;
|
||||
helper_state=[string](Get-Service RmmDiscoverySystemHelper).Status; files=$files;
|
||||
acl_sha256=$aclHashes; job_profile=$live.windows_execution_profile; jobs_enabled=($live.enable_jobs -eq $true);
|
||||
binding_path_matches=($live.job_binding_file -ceq $binding);
|
||||
jobs_directory=[IO.Directory]::Exists($jobs); jobs_acl_verified=$jobsAcl}
|
||||
}
|
||||
Assert-DirectoryAcl $boot $false
|
||||
Assert-DirectoryAcl $root $true
|
||||
Assert-NormalPath $state $true
|
||||
if (Test-Path -LiteralPath $case) { Assert-DirectoryAcl $case $false }
|
||||
if ($Mode -in @('Inspect','Readback')) { Get-Readback | ConvertTo-Json -Depth 5; return }
|
||||
if ((Get-PublicHash $helperImage) -cne $helper) { throw 'Helper-Build abweichend' }
|
||||
$inputs = Get-ConfigurationInputs
|
||||
$configHash = Get-BytesDigest $inputs.config
|
||||
foreach ($p in @($jobs,$binding,$next,$backup,$entered,$done)) {
|
||||
if (Test-Path -LiteralPath $p) { throw 'Frueherer oder teilweiser Wechsel: Readback verwenden' }
|
||||
}
|
||||
if ($Mode -eq 'Prepare') {
|
||||
if ((Get-PublicHash $image) -cne $oldAgent -or (Get-Service RmmDiscoveryWindows).Status -ne 'Running') { throw 'Passiver Ausgangsagent erforderlich' }
|
||||
if (Test-Path -LiteralPath $case) { throw 'Vorhandener Vorbereitungsfall: Readback verwenden' }
|
||||
$caseAcl = [Security.AccessControl.DirectorySecurity]::new()
|
||||
$caseAcl.SetSecurityDescriptorSddlForm('O:BAG:BAD:P(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)')
|
||||
$null = [IO.Directory]::CreateDirectory($case,$caseAcl)
|
||||
Assert-DirectoryAcl $case $false
|
||||
Write-Once $original ([IO.File]::ReadAllBytes($config)) $null
|
||||
Write-Once $candidate $inputs.config $null
|
||||
Write-Once $publicBinding $inputs.binding $null
|
||||
if ((Get-PublicHash $candidate) -cne $configHash -or (Get-PublicHash $original) -cne $oldConfig -or
|
||||
(Get-PublicHash $publicBinding) -cne $expectedBinding) { throw 'Vorbereitungsdateien abweichend' }
|
||||
Save-Record $ready @{case_id=$caseId; config_sha256=$configHash; original_sha256=$oldConfig; binding_sha256=$expectedBinding}
|
||||
Get-Readback | ConvertTo-Json -Depth 5
|
||||
return
|
||||
}
|
||||
$prepared = Read-PublicJson $ready
|
||||
if ($prepared.case_id -cne $caseId -or $prepared.config_sha256 -cne $configHash -or
|
||||
(Get-PublicHash $candidate) -cne $configHash -or (Get-PublicHash $original) -cne $oldConfig -or
|
||||
(Get-PublicHash $publicBinding) -cne $expectedBinding) { throw 'Vorbereitungsbeleg abweichend' }
|
||||
if ((Get-PublicHash $image) -cne $newAgent -or (Get-Service RmmDiscoveryWindows).Status -ne 'Stopped') { throw 'Neues Agentimage und gestoppter Dienst erforderlich' }
|
||||
$peer = Read-PublicJson $pin
|
||||
$time = Read-PublicJson $clock
|
||||
$roles = @($time.trusted_os_active_guest.qualifications)
|
||||
if ($peer.agent.binary_sha256 -cne $newAgent -or $peer.helper.binary_sha256 -cne $helper -or
|
||||
$roles.Count -ne 2 -or @($roles | Where-Object { $_.role -ceq 'agent' -and $_.binary_sha256 -ceq $newAgent }).Count -ne 1 -or
|
||||
@($roles | Where-Object { $_.role -ceq 'system_helper' -and $_.binary_sha256 -ceq $helper }).Count -ne 1) { throw 'Paar-Pins und Zeitprofil abweichend' }
|
||||
$acl = Get-OriginalAcl
|
||||
Save-Record $entered @{case_id=$caseId; utc=[DateTime]::UtcNow.ToString('o'); config_sha256=$configHash; binding_sha256=$expectedBinding}
|
||||
Write-Once $binding $inputs.binding $acl
|
||||
Assert-FileAcl $binding $acl
|
||||
$null = [IO.Directory]::CreateDirectory($jobs,(Get-JobsAcl))
|
||||
Assert-JobsAcl
|
||||
Write-Once $next $inputs.config $acl
|
||||
Assert-FileAcl $next $acl
|
||||
if ((Get-PublicHash $binding) -cne $expectedBinding -or (Get-PublicHash $next) -cne $configHash -or
|
||||
(Get-PublicHash $config) -cne $oldConfig) { throw 'Vor Austausch unerwartete Dateien' }
|
||||
[IO.File]::Replace($next,$config,$backup,$false)
|
||||
Assert-FileAcl $config $acl
|
||||
if ((Get-PublicHash $config) -cne $configHash -or (Get-PublicHash $backup) -cne $oldConfig) { throw 'Konfigurationswechsel nicht bestaetigt' }
|
||||
Save-Record $done @{case_id=$caseId; utc=[DateTime]::UtcNow.ToString('o'); config_sha256=$configHash; binding_sha256=$expectedBinding}
|
||||
Get-Readback | ConvertTo-Json -Depth 5
|
||||
@@ -0,0 +1,278 @@
|
||||
#requires -Version 5.1
|
||||
#requires -RunAsAdministrator
|
||||
# Fixed console maintenance of the passive test guest. No queue, network, or script job.
|
||||
[CmdletBinding()]
|
||||
param([Parameter(Mandatory)][ValidateSet('Prepare','InstallPassive','Read','RestorePrevious')][string]$Mode)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$originalCase = 'ad9fd154-b2be-4f5d-9e17-65abb721ceaf'
|
||||
$originalHash = 'd8b4fd4fd9ca5310cc1591ce3c2ccae5bd72a2ade43b21a8187cfdfb960b3427'
|
||||
$bootstrap = 'C:\ProgramData\RustDiscoveryBootstrap'
|
||||
$oldFolder = Join-Path $bootstrap "time-profile-$originalCase"
|
||||
$original = Join-Path (Join-Path $bootstrap $originalHash) 'InstallPublicTimeProfile.ps1'
|
||||
$raw = [IO.File]::ReadAllBytes($original)
|
||||
$digest = [Security.Cryptography.SHA256]::Create()
|
||||
try { $actual = [BitConverter]::ToString($digest.ComputeHash($raw)).Replace('-','') }
|
||||
finally { $digest.Dispose() }
|
||||
if ($actual -ne $originalHash) { throw 'Original controller hash changed' }
|
||||
$src = [Text.Encoding]::UTF8.GetString($raw)
|
||||
$boundary = "`nCheckControl `$boot `$true`n"
|
||||
$end = $src.IndexOf($boundary,[StringComparison]::Ordinal)
|
||||
if ($end -le 0 -or $end -ne $src.LastIndexOf($boundary,[StringComparison]::Ordinal)) {
|
||||
throw 'Expected the original fixed definition boundary'
|
||||
}
|
||||
$originalIntent = Get-Content -LiteralPath (Join-Path $oldFolder 'intent.json') -Raw | ConvertFrom-Json
|
||||
if ($originalIntent.id -cne $originalCase -or $originalIntent.request.script_sha256 -cne $originalHash) {
|
||||
throw 'Unexpected original case'
|
||||
}
|
||||
$global:RmmTimeProfilePayload = $originalIntent.request
|
||||
. ([scriptblock]::Create($src.Substring(0,$end)))
|
||||
$id = '49c230d8-fb5d-4c64-96b6-e0edce03ed90'
|
||||
$work = Join-Path $boot "job-passive-pair-$id"
|
||||
$oldHashes = [ordered]@{
|
||||
agent='0549d9ebea73cff996938f859b92192cc333de194128d7c6859a3f1d2e85893c'
|
||||
settings='bbccd710fd564eb5ad57eec5732b413359d09bcb5953f5de9501ccfe826bd3c2'
|
||||
pin='66ef481bd9ded320d6f3dcc82b0ddaf34fdef7d80ac15d06820ff7da75a18c56'
|
||||
}
|
||||
$newHashes = [ordered]@{
|
||||
agent='df80b00fc2119b973d690053b9f9e4bdedd8fbc211f67599c3301eeb42e7702f'
|
||||
settings='7172456d56a55cced2f6ed4af1e9141499f09e67cbb16db32e2308396f9de929'
|
||||
pin='b9517517cec801b10adb5d53e470fc143b8909c45e3bb95b8e4a34281f303623'
|
||||
}
|
||||
$locations = [ordered]@{agent=$agentBinary;settings=$settings;pin=$pin}
|
||||
$profileHash = '2b4a8a7080770304b80e2a665fa5f5ee1ebbd9182e7c80b184e75b114575b42b'
|
||||
$helperHash = '59675a3cbb3a5d213fc764f38379d6b81baaf9d47a7124470cc2767d4985763e'
|
||||
$configHash = '7c9f6f3642ef84337c3cd761d8a4788c4babe81522fdd987a3eb9b819bc8d851'
|
||||
$source = Join-Path (Join-Path $boot $newHashes.agent) 'rmm-agent-windows.exe'
|
||||
CheckControl $boot $true
|
||||
CheckControl $oldFolder $true
|
||||
if ((Hash (Join-Path $oldFolder 'console-resume-empty-result.json')) -cne '62a04be9c7d08d3687b51eacd6adbe290b91e16ba934d6b5bb531e8764a56cf5') {
|
||||
throw 'Unexpected original publication result'
|
||||
}
|
||||
|
||||
function Marker($name) { Join-Path $work ($name+'.json') }
|
||||
function Record($name,$value) { WriteNew (Marker $name) $value }
|
||||
function LoadRecord($name) {
|
||||
$path = Marker $name
|
||||
CheckControl $path $false
|
||||
return (Get-Content -LiteralPath $path -Raw | ConvertFrom-Json)
|
||||
}
|
||||
function VerifyPassiveContext {
|
||||
if ((Hash $config) -cne $configHash -or (Hash $target) -cne $profileHash -or
|
||||
(Hash $helperBinary) -cne $helperHash) { throw 'Passive config, predecessor time profile or unchanged helper differs' }
|
||||
foreach ($dir in @((Split-Path $agentBinary),$agentRoot,$helperRoot)) { $null=ReadAcl $dir $true }
|
||||
foreach ($file in @($config,$settings,$pin,$target,$agentBinary,$helperBinary)) { $null=ReadAcl $file $false }
|
||||
$unitProof=Join-Path $boot 'profile-unit-fcec400-result.json'
|
||||
CheckControl $unitProof $false
|
||||
if ((Hash $unitProof) -cne '48de474d842ebc87550ba2e27b66086e6aa573973f252f4b8e19ac7b12b75a63') {
|
||||
throw 'Current native Windows profile unit receipt differs'
|
||||
}
|
||||
}
|
||||
function CurrentFiles {
|
||||
$files=[ordered]@{}
|
||||
foreach ($name in $locations.Keys) { $files[$name]=FileIdentity $locations[$name] }
|
||||
return $files
|
||||
}
|
||||
function VerifyFiles($files,$hashes) {
|
||||
foreach ($name in $locations.Keys) {
|
||||
if ($files.$name.sha256 -cne $hashes.$name) { throw "Unexpected $name bytes" }
|
||||
}
|
||||
}
|
||||
function LiveRole($role,$expectedHash) {
|
||||
$s=Service $role
|
||||
if ($s.state -cne 'Running') { throw "$role must be running" }
|
||||
$handle=[RmmPipeNative]::Open([int]$s.pid)
|
||||
try {
|
||||
$k=Kernel $role $s $handle
|
||||
$f=FileIdentity $k.image
|
||||
if ($f.sha256 -cne $expectedHash -or !(JsonEqual $s (Service $role)) -or ![RmmPipeNative]::Alive($handle)) {
|
||||
throw "$role generation or image changed"
|
||||
}
|
||||
return [ordered]@{service=$s; kernel=$k; image_file=$f}
|
||||
} finally { $handle.Dispose() }
|
||||
}
|
||||
function PreservedDevice {
|
||||
return [ordered]@{
|
||||
config=(FileIdentity $config)
|
||||
identity=(FileIdentity (Join-Path $agentState 'identity.json') $true)
|
||||
certificate=(FileIdentity (Join-Path $agentState 'device.pem') $true)
|
||||
private_key_metadata=(FileIdentityMetadata (Join-Path $agentState 'device.key'))
|
||||
helper=(FileIdentity $helperBinary)
|
||||
time_profile=(FileIdentity $target)
|
||||
}
|
||||
}
|
||||
function FlushFile($path) {
|
||||
$f=[IO.File]::Open($path,'Open','ReadWrite','Read')
|
||||
try { $f.Flush($true) } finally { $f.Dispose() }
|
||||
}
|
||||
function StopKnownRole($role,$name,$bound,$prefix) {
|
||||
$s=Service $role
|
||||
if (!(JsonEqual $s $bound.service)) { throw "$role changed before stop" }
|
||||
$h=[RmmPipeNative]::Open([int]$s.pid)
|
||||
try {
|
||||
if (!(JsonEqual (Kernel $role $s $h) $bound.kernel)) { throw 'Kernel role changed' }
|
||||
Record ($prefix+'-stop-'+$role) $bound
|
||||
Stop-Service -Name $name
|
||||
(Get-Service -Name $name).WaitForStatus('Stopped',[TimeSpan]::FromSeconds(30))
|
||||
if (![RmmPipeNative]::Exited($h,5000)) { throw "$role did not exit" }
|
||||
} finally { $h.Dispose() }
|
||||
}
|
||||
function StopCheck {
|
||||
if ((Service 'agent').state -cne 'Stopped' -or (Service 'helper').state -cne 'Stopped') {
|
||||
throw 'Both services must be stopped'
|
||||
}
|
||||
}
|
||||
function SwapFile($name,$inputPath,$oldId,$newHash,$prefix) {
|
||||
StopCheck
|
||||
$dest=$locations[$name]
|
||||
$backup=Join-Path $work ($prefix+'-replaced-'+$name)
|
||||
$stage=Join-Path $work ($prefix+'-stage-'+$name)
|
||||
CheckControl $inputPath $false
|
||||
if (!(JsonEqual $oldId (FileIdentity $dest)) -or (Hash $inputPath) -cne $newHash -or (Test-Path -LiteralPath $backup)) {
|
||||
throw "Replacement precondition $name"
|
||||
}
|
||||
[IO.File]::Copy($inputPath,$stage,$false)
|
||||
FlushFile $stage
|
||||
$candidate=FileIdentity $stage
|
||||
if ($candidate.sha256 -cne $newHash -or $candidate.volume_serial -cne $oldId.volume_serial) { throw 'Invalid same-volume candidate' }
|
||||
$originalAcl=Get-Acl -LiteralPath $dest
|
||||
Record ($prefix+'-replace-'+$name) ([ordered]@{previous=$oldId;candidate=$candidate})
|
||||
if (!(JsonEqual $oldId (FileIdentity $dest)) -or !(JsonEqual $candidate (FileIdentity $stage))) { throw 'Changed replacement identities' }
|
||||
[IO.File]::Replace($stage,$dest,$backup)
|
||||
$privateAcl=New-Object Security.AccessControl.FileSecurity
|
||||
$privateAcl.SetSecurityDescriptorSddlForm('O:BAG:BAD:P(A;;FA;;;SY)(A;;FA;;;BA)')
|
||||
Set-Acl -LiteralPath $backup -AclObject $privateAcl
|
||||
CheckControl $backup $false
|
||||
if ((AclHash $dest) -cne $oldId.acl_sha256) {
|
||||
Set-Acl -LiteralPath $dest -AclObject $originalAcl
|
||||
}
|
||||
FlushFile $dest
|
||||
$new=FileIdentity $dest
|
||||
if ($new.sha256 -cne $newHash -or $new.acl_sha256 -cne $oldId.acl_sha256 -or (Hash $backup) -cne $oldId.sha256) {
|
||||
throw "Replacement readback $name"
|
||||
}
|
||||
Record ($prefix+'-installed-'+$name) $new
|
||||
}
|
||||
function StartKnownRole($role,$name,$hash,$prefix) {
|
||||
if ((Service $role).state -cne 'Stopped') { throw "$role not stopped" }
|
||||
Record ($prefix+'-start-'+$role) @{old_state='Stopped';expected_hash=$hash}
|
||||
Start-Service -Name $name
|
||||
(Get-Service -Name $name).WaitForStatus('Running',[TimeSpan]::FromSeconds(30))
|
||||
Record ($prefix+'-started-'+$role) (LiveRole $role $hash)
|
||||
}
|
||||
function PrepareFiles($before) {
|
||||
CheckControl (Split-Path $source) $true
|
||||
CheckControl $source $false
|
||||
if ((FileIdentity $source).sha256 -cne $newHashes.agent) { throw 'New agent hash' }
|
||||
foreach ($name in $locations.Keys) {
|
||||
$copy=Join-Path $work ('old-'+$name)
|
||||
[IO.File]::Copy($locations[$name],$copy,$false)
|
||||
# Copy can retain the source descriptor. Restrict backups to the case.
|
||||
$acl=New-Object Security.AccessControl.FileSecurity
|
||||
$acl.SetSecurityDescriptorSddlForm('O:BAG:BAD:P(A;;FA;;;SY)(A;;FA;;;BA)')
|
||||
Set-Acl -LiteralPath $copy -AclObject $acl
|
||||
CheckControl $copy $false
|
||||
FlushFile $copy
|
||||
if ((Hash $copy) -cne $oldHashes.$name) { throw "Backup $name" }
|
||||
}
|
||||
$utf8=[Text.UTF8Encoding]::new($false,$true)
|
||||
foreach ($name in @('settings','pin')) {
|
||||
$data=$utf8.GetString([IO.File]::ReadAllBytes($locations[$name])).Replace($oldHashes.agent,$newHashes.agent)
|
||||
if ($name -eq 'pin') { $data=$data.Replace($oldHashes.settings,$newHashes.settings) }
|
||||
$path=Join-Path $work ('new-'+$name)
|
||||
WriteBytes $path ($utf8.GetBytes($data))
|
||||
if ((Hash $path) -cne $newHashes.$name) { throw "Closed successor bytes $name" }
|
||||
}
|
||||
if (!(JsonEqual $before (CurrentFiles))) { throw 'Original inputs changed during copy' }
|
||||
}
|
||||
if ($Mode -eq 'Read') {
|
||||
$r=[ordered]@{id=$id;mode='read_only';files=(CurrentFiles);agent=(Service 'agent');helper=(Service 'helper');markers=@()}
|
||||
if (Test-Path -LiteralPath $work) {
|
||||
CheckControl $work $true
|
||||
$r.markers=@(Get-ChildItem -LiteralPath $work -Filter '*.json' -File | Select-Object -ExpandProperty Name)
|
||||
if ((Test-Path -LiteralPath (Marker 'installed')) -and $r.files.agent.sha256 -ceq $newHashes.agent -and
|
||||
$r.agent.state -ceq 'Running' -and $r.helper.state -ceq 'Running') {
|
||||
$r.new_agent=LiveRole 'agent' $newHashes.agent
|
||||
$r.unchanged_helper=LiveRole 'helper' $helperHash
|
||||
}
|
||||
}
|
||||
$r|ConvertTo-Json -Depth 12 -Compress
|
||||
return
|
||||
}
|
||||
VerifyPassiveContext
|
||||
if ($Mode -eq 'Prepare') {
|
||||
$before=CurrentFiles
|
||||
VerifyFiles $before $oldHashes
|
||||
$agent=LiveRole 'agent' $oldHashes.agent
|
||||
$helper=LiveRole 'helper' $helperHash
|
||||
$device=PreservedDevice
|
||||
CheckControl (Split-Path $source) $true
|
||||
CheckControl $source $false
|
||||
if ((Hash $source) -cne $newHashes.agent) { throw 'Candidate absent or incorrect before preparation' }
|
||||
[RmmTimeProfileCase]::CreatePrivateOnce($work)
|
||||
CheckControl $work $true
|
||||
PrepareFiles $before
|
||||
Record 'prepared' ([ordered]@{id=$id;utc=[DateTime]::UtcNow.ToString('o');files=$before;device=$device;agent=$agent;helper=$helper})
|
||||
Write-Output "Prepared passive pair $id"
|
||||
return
|
||||
}
|
||||
CheckControl $work $true
|
||||
$prep=LoadRecord 'prepared'
|
||||
if ($prep.id -cne $id -or !(JsonEqual $prep.device (PreservedDevice))) { throw 'Prepared case or preserved device changed' }
|
||||
if ($Mode -eq 'InstallPassive') {
|
||||
if (!(JsonEqual $prep.files (CurrentFiles)) -or !(JsonEqual $prep.agent (LiveRole 'agent' $oldHashes.agent)) -or
|
||||
!(JsonEqual $prep.helper (LiveRole 'helper' $helperHash))) { throw 'Prepared baseline changed' }
|
||||
foreach ($name in $locations.Keys) {
|
||||
if ((Hash (Join-Path $work ('old-'+$name))) -cne $oldHashes.$name) { throw 'Recovery backup changed' }
|
||||
}
|
||||
foreach ($name in @('settings','pin')) {
|
||||
if ((Hash (Join-Path $work ('new-'+$name))) -cne $newHashes.$name) { throw 'Prepared successor changed' }
|
||||
}
|
||||
CheckControl $source $false
|
||||
if ((Hash $source) -cne $newHashes.agent) { throw 'New binary changed' }
|
||||
Record 'install-intent' @{id=$id;utc=[DateTime]::UtcNow.ToString('o')}
|
||||
StopKnownRole 'agent' $agentName $prep.agent 'install'
|
||||
StopKnownRole 'helper' $helperName $prep.helper 'install'
|
||||
foreach ($name in $locations.Keys) {
|
||||
$inputPath=Join-Path $work ('new-'+$name)
|
||||
if ($name -eq 'agent') { $inputPath=$source }
|
||||
SwapFile $name $inputPath $prep.files.$name $newHashes.$name 'install'
|
||||
}
|
||||
VerifyFiles (CurrentFiles) $newHashes
|
||||
StartKnownRole 'helper' $helperName $helperHash 'install'
|
||||
StartKnownRole 'agent' $agentName $newHashes.agent 'install'
|
||||
$a=LiveRole 'agent' $newHashes.agent
|
||||
$h=LiveRole 'helper' $helperHash
|
||||
if (!(JsonEqual $prep.device (PreservedDevice))) { throw 'Device changed after passive restart' }
|
||||
Record 'installed' ([ordered]@{id=$id;utc=[DateTime]::UtcNow.ToString('o');agent=$a;helper=$h;files=(CurrentFiles);device=$prep.device;job_mode=$false;clock_qualified=$false})
|
||||
Write-Output "Installed passive pair $id"
|
||||
return
|
||||
}
|
||||
# An explicit recovery is valid only before publishing any successor time profile
|
||||
# or enabling jobs. Verify all present files against the two known generations.
|
||||
$null=LoadRecord 'install-intent'
|
||||
$observed=CurrentFiles
|
||||
foreach ($name in $locations.Keys) {
|
||||
$hash=$observed.$name.sha256
|
||||
if ($hash -cnotin @($oldHashes.$name,$newHashes.$name) -or
|
||||
(Hash (Join-Path $work ('old-'+$name))) -cne $oldHashes.$name) { throw "Unknown recovery input $name" }
|
||||
}
|
||||
Record 'restore-intent' @{id=$id;utc=[DateTime]::UtcNow.ToString('o')}
|
||||
foreach ($role in @('agent','helper')) {
|
||||
$service=(Service $role)
|
||||
$name=$agentName
|
||||
$imageHash=$observed.agent.sha256
|
||||
if ($role -eq 'helper') { $name=$helperName; $imageHash=$helperHash }
|
||||
if ($service.state -ceq 'Running') { StopKnownRole $role $name (LiveRole $role $imageHash) 'restore' }
|
||||
elseif ($service.state -cne 'Stopped') { throw "Unknown service transition $role" }
|
||||
}
|
||||
StopCheck
|
||||
foreach ($name in $locations.Keys) {
|
||||
if ($observed.$name.sha256 -cne $oldHashes.$name) {
|
||||
SwapFile $name (Join-Path $work ('old-'+$name)) $observed.$name $oldHashes.$name 'restore'
|
||||
}
|
||||
}
|
||||
VerifyFiles (CurrentFiles) $oldHashes
|
||||
StartKnownRole 'helper' $helperName $helperHash 'restore'
|
||||
StartKnownRole 'agent' $agentName $oldHashes.agent 'restore'
|
||||
Record 'restored' @{id=$id;agent=(LiveRole 'agent' $oldHashes.agent);helper=(LiveRole 'helper' $helperHash)}
|
||||
Write-Output "Restored passive predecessor $id"
|
||||
@@ -0,0 +1,100 @@
|
||||
#requires -Version 5.1
|
||||
#requires -RunAsAdministrator
|
||||
[CmdletBinding()]
|
||||
param()
|
||||
$ErrorActionPreference = 'Stop'
|
||||
|
||||
function Assert-PrivateUnitPath([string]$Path, [bool]$Directory) {
|
||||
$item = Get-Item -LiteralPath $Path -Force
|
||||
if ($item.PSIsContainer -ne $Directory -or ($item.Attributes -band [IO.FileAttributes]::ReparsePoint)) {
|
||||
throw 'Unexpected unit path type'
|
||||
}
|
||||
$acl = Get-Acl -LiteralPath $Path
|
||||
$trusted = @('S-1-5-18', 'S-1-5-32-544')
|
||||
$sidType = [Security.Principal.SecurityIdentifier]
|
||||
if ($acl.GetOwner($sidType).Value -notin $trusted) { throw 'Unexpected unit path owner' }
|
||||
$rules = @($acl.GetAccessRules($true, $true, $sidType))
|
||||
if (!$rules.Count) { throw 'Missing unit path ACL' }
|
||||
foreach ($rule in $rules) {
|
||||
if ($rule.AccessControlType -ne 'Allow' -or $rule.IdentityReference.Value -notin $trusted) {
|
||||
throw 'Unexpected unit path ACL'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$bootstrap = 'C:\ProgramData\RustDiscoveryBootstrap'
|
||||
$unit = Join-Path $PSScriptRoot 'rmm_agent_windows-9b3e91d827c6ff16.exe'
|
||||
$unitHash = '7d1715dc105c1eb482405511e1b3abf4437c448e186e73923c43dd3c7938710e'
|
||||
$test = 'runtime::tests::remote_signed_requires_explicit_profile_jobs_and_binding'
|
||||
if ((Split-Path -Parent $PSScriptRoot) -ne $bootstrap) { throw 'Private bootstrap directory required' }
|
||||
Assert-PrivateUnitPath $bootstrap $true
|
||||
Assert-PrivateUnitPath $PSScriptRoot $true
|
||||
Assert-PrivateUnitPath $PSCommandPath $false
|
||||
Assert-PrivateUnitPath $unit $false
|
||||
foreach ($entry in (Get-ChildItem -LiteralPath $PSScriptRoot -Force)) {
|
||||
if ($entry.Name -notin @([IO.Path]::GetFileName($PSCommandPath), [IO.Path]::GetFileName($unit))) {
|
||||
throw 'Unit staging directory must contain only the runner and the unit executable'
|
||||
}
|
||||
}
|
||||
$system32 = [Environment]::SystemDirectory
|
||||
$shell = Join-Path $system32 'WindowsPowerShell\v1.0\powershell.exe'
|
||||
if (![Environment]::Is64BitProcess -or [Diagnostics.Process]::GetCurrentProcess().MainModule.FileName -ne $shell -or
|
||||
$PSVersionTable.PSEdition -ne 'Desktop' -or $PSVersionTable.PSVersion.Major -ne 5 -or $PSVersionTable.PSVersion.Minor -ne 1) {
|
||||
throw 'Run with the installed 64-bit Windows PowerShell 5.1'
|
||||
}
|
||||
$policies = [ordered]@{}
|
||||
foreach ($scope in 'MachinePolicy','UserPolicy','Process','CurrentUser','LocalMachine') {
|
||||
$policies[$scope] = [string](Microsoft.PowerShell.Security\Get-ExecutionPolicy -Scope $scope)
|
||||
}
|
||||
|
||||
$handle = [IO.File]::Open($unit, 'Open', 'Read', 'Read')
|
||||
try {
|
||||
$hasher = [Security.Cryptography.SHA256]::Create()
|
||||
try { $actual = [BitConverter]::ToString($hasher.ComputeHash($handle)).Replace('-','').ToLowerInvariant() }
|
||||
finally { $hasher.Dispose() }
|
||||
if ($actual -cne $unitHash -or $handle.Length -ne 18608199) { throw 'Unexpected unit executable' }
|
||||
$start = New-Object Diagnostics.ProcessStartInfo
|
||||
$start.FileName = $unit
|
||||
$start.Arguments = "--exact $test --test-threads=1 --color never"
|
||||
$start.WorkingDirectory = $PSScriptRoot
|
||||
$start.UseShellExecute = $false
|
||||
$start.CreateNoWindow = $true
|
||||
$start.RedirectStandardOutput = $true
|
||||
$start.RedirectStandardError = $true
|
||||
$start.EnvironmentVariables.Clear()
|
||||
$windows = Split-Path -Parent $system32
|
||||
$start.EnvironmentVariables['SystemRoot'] = $windows
|
||||
$start.EnvironmentVariables['WINDIR'] = $windows
|
||||
$start.EnvironmentVariables['SystemDrive'] = [IO.Path]::GetPathRoot($windows).TrimEnd('\')
|
||||
$start.EnvironmentVariables['PATH'] = $system32
|
||||
$proc = [Diagnostics.Process]::Start($start)
|
||||
try {
|
||||
$stdout = $proc.StandardOutput.ReadToEndAsync()
|
||||
$stderr = $proc.StandardError.ReadToEndAsync()
|
||||
if (!$proc.WaitForExit(30000)) {
|
||||
$proc.Kill()
|
||||
throw 'Fixed unit test timed out'
|
||||
}
|
||||
if (!$stdout.Wait(2000) -or !$stderr.Wait(2000) -or $proc.ExitCode -ne 0 -or $stderr.Result.Length -gt 0) {
|
||||
throw 'Fixed unit test failed'
|
||||
}
|
||||
$lines = @($stdout.Result -split '\r?\n' | Where-Object { $_ })
|
||||
if ($lines.Count -ne 3 -or $lines[0] -cne 'running 1 test' -or $lines[1] -cne "test $test ... ok" -or
|
||||
$lines[2] -cnotmatch '^test result: ok\. 1 passed; 0 failed; 0 ignored; 0 measured; (\d+) filtered out; finished in \d+(?:\.\d+)?s$') {
|
||||
throw 'Unexpected test result or filter count'
|
||||
}
|
||||
$filtered = [int]$Matches[1]
|
||||
} finally { $proc.Dispose() }
|
||||
} finally { $handle.Dispose() }
|
||||
|
||||
[ordered]@{
|
||||
observed_at = [DateTimeOffset]::UtcNow.ToString('o')
|
||||
unit_sha256 = $actual
|
||||
test_name = $test
|
||||
passed = 1
|
||||
filtered_out = $filtered
|
||||
powershell_path = $shell
|
||||
powershell_sha256 = (Get-FileHash -LiteralPath $shell -Algorithm SHA256).Hash.ToLowerInvariant()
|
||||
powershell_version = $PSVersionTable.PSVersion.ToString()
|
||||
admin_host_policy_scopes = $policies
|
||||
} | ConvertTo-Json -Depth 3 -Compress
|
||||
+21
-7
@@ -22,13 +22,27 @@ Image. MCP bestätigte zwei neue Windows-Heartbeats um **16:39:46 und
|
||||
vor dem Dienstwechsel. Die Cloud-Linux-VM meldete sich weiterhin als online.
|
||||
[Dienstwechsel und Telemetrienachweis](windows-signed-clock-upgrade-plan.md)
|
||||
|
||||
Die Zeitprofilinstallation scheiterte beim Veröffentlichen der Datei mit einer
|
||||
`IOException`. Eine separate Abfrage auf der VM bestätigte, dass die Zieldatei
|
||||
fehlte und die Dienste weiterliefen. Das SSH-Fenster endete um 16:30 Uhr MEZ.
|
||||
Für die nächste Gastprüfung muss der bestehende Teilzustand berücksichtigt
|
||||
werden. Die Zeitprüfung in beiden installierten Rollen und der erste über die
|
||||
WebUI genehmigte PowerShell-Auftrag stehen aus.
|
||||
[Zeitprofil und Originalbefund](windows-time-profile-config.md)
|
||||
Die Erstinstallation des Windows-Zeitprofils ist auf der VM belegt. Der Server empfing zunächst um
|
||||
17:05:36 Uhr MEZ den Fehlercode `0x80070020` beim Verschieben in das
|
||||
Zielverzeichnis. Der Helper hält dort einen Verzeichnishandle, der diesen
|
||||
Schreibzugriff sperrt. Im korrigierten Quellstand erlauben die Handles für
|
||||
das öffentliche Verzeichnis diesen Zugriff. Löschsperre, DACL- und
|
||||
Dateiidentitätsprüfungen bleiben aktiv. Agent und Helper wurden damit für
|
||||
Windows x86-64 gebaut; dieser Build ist noch nicht auf der VM installiert
|
||||
oder dort abgenommen. Beim anschließenden Versuch um 20:24 Uhr MEZ konnte der Gast
|
||||
die neue Zieldatei öffnen. Der Sicherheitsdeskriptor entsprach beim Lesen
|
||||
nicht exakt dem erwarteten Wert. Der Controller stoppte vor dem Schreiben
|
||||
der Profilbytes. Die anschließende Konsolenlesung bestätigte 0 Byte.
|
||||
Eigentümer, Gruppe, DACL-Schutz und alle sechs expliziten Zugriffsregeln
|
||||
stimmten überein. Nur das DACL-Steuerbit für automatische Vererbung (`AI`)
|
||||
fehlte im gelesenen Deskriptor. Um 20:40 Uhr MEZ gelang der Abschluss.
|
||||
Der Gast las die 1177 Profilbytes mit dem erwarteten SHA-256 und derselben
|
||||
Dateikennung zurück, die er vor dem Schreiben festgehalten hatte.
|
||||
Um 20:41 Uhr MEZ bestätigte der Projektserver die ersten zwei getrennten
|
||||
signierten Zeitvergleiche des laufenden Agenten und SYSTEM-Helpers.
|
||||
Die Windows-Skript- und Paketabnahmen stehen aus.
|
||||
[Zeitbelege beider Dienste](windows-passive-time-closeout.md)
|
||||
[VM-Fehlerbeleg und Buildprüfung](windows-time-profile-config.md)
|
||||
|
||||
Die passive Zertifikatserneuerung ist implementiert. Fünf Wiederanlauf- und
|
||||
Fehlerfälle mit Testidentitäten bestanden auch auf Windows. Das Anlegen,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# Lesender Abschluss zweier passiver Windows-Zeitbeobachtungen
|
||||
|
||||
Der Collector `deploy/windows/passive_time_closeout.py` ist lokal vorbereitet
|
||||
und ausführbar. **Noch kein Zielaufruf oder nativer Abschlussnachweis.** Die
|
||||
und ausführbar. Der native Abschluss über den auf dem Server laufenden Empfänger ist unten dokumentiert. Die
|
||||
V2-Profileinrichtung und ihr ausdrücklich gemeldetes Zeitfenster stehen vor
|
||||
dem Aufruf. Tunnel-/Zugangserneuerung, Profileinrichtung und Dienstwartung sind
|
||||
keine Aktionen dieses Collectors.
|
||||
@@ -129,3 +129,62 @@ Pipeeingrenzung helfen. Sie enthalten keinen vollständigen Timeworkerfehler;
|
||||
auch Metadaten vorhandener fester `.agent-time.pending`/`.helper-time.pending`
|
||||
können eine unterbrochene Publikation erklären. Dieser Collector liest oder
|
||||
ändert diese zusätzlichen Dateien nicht und löst keine Diagnose aus.
|
||||
|
||||
### Nativer Abschluss am 15. November 2026
|
||||
|
||||
Der Empfänger auf dem permanenten Server prüfte um **20:41:27 Uhr MEZ**
|
||||
beide nach der Veröffentlichung des Profils entstandenen Belege. Der Agent
|
||||
beobachtete seinen Vergleich um `19:40:52.455414900Z`, der SYSTEM-Helper
|
||||
seinen um `19:40:52.524631100Z`. Beide gehörten zu Verbindungsgeneration 145
|
||||
und demselben Windows-Boot. Verifier-UUIDs und die Hashes der beiden
|
||||
Anfragen und Antworten unterschieden sich. Der Agent hatte PID 4420, der
|
||||
Helper PID 10264. Die Serverzeugen vor und nach der Lesung stimmten überein.
|
||||
|
||||
Fall `c23245b7-017e-4643-9872-849f262faf21`, Lesung 36. Der SHA-256 des
|
||||
empfangenen Datensatzes lautet
|
||||
`40d45a9cb3145f8b1159b7c5da0509dd043355aca23d4bec860f37205e3a8551`,
|
||||
der des Abschlussbelegs
|
||||
`f1a79eed223487fa61890ccb274986660b33f2596ae33e1689e9b2afdc7b8884`.
|
||||
Beim separaten Rücklesen stimmten die zwei ursprünglichen Rollenberichte
|
||||
mit den validierten Einträgen überein. Der Server führte weiterhin nur
|
||||
`windows.base/1`, `heartbeat/1` und `agent.update/1`. Für einen späteren
|
||||
Auftrag muss die Uhr beim Prüfen des Grants erneut die Frischegrenzen erfüllen.
|
||||
|
||||
### Konsolenlesung des nachfolgenden Dienstpaars
|
||||
|
||||
`deploy/windows/Read-JobPairTimeSamples.ps1` bindet den ursprünglichen Leser
|
||||
mit SHA-256 `d9e2b9344c19af1296b86ec70ba754ef820f369ac5ec897979bd4233e0722d04`
|
||||
an den Paarfall `49c230d8-fb5d-4c64-96b6-e0edce03ed90`. Vor dem Aufruf
|
||||
muss die tatsächliche Verbindungsgeneration auf dem Projektserver gelesen
|
||||
werden. Der Wrapper prüft die aktuelle Profilquittung und die Prozessgeburt
|
||||
beider Dienste, die Rechte und Dateikennungen anhand der Leserausgabe,
|
||||
den CIM-Bootbezug, die zwei unterschiedlichen Rollen und die Frische der
|
||||
ungeschmälerten Originalreports. Bei fehlenden oder alten Beispielen liest
|
||||
er bis zu zwei Minuten erneut. Für einen bereits laufenden Leseprozess
|
||||
gilt ein maximales Einzelbudget von 30 Sekunden.
|
||||
|
||||
**Geplanter Aufruf als Administrator auf dem Gast:**
|
||||
`Read-JobPairTimeSamples.ps1 -Generation <aktuelle Servergeneration>`.
|
||||
Der unveränderte `Read-PassiveTimeSamples.ps1` muss daneben liegen. Die
|
||||
lokale Quittung entsteht je Aufruf einmalig als
|
||||
`samples-passive-<Sitzungs-ID>.json` im Paarfall. Sie enthält die
|
||||
Originalreports in Base64, ihre SHA-256, Sicherheits-/Dateimetadaten und
|
||||
Prozesszeugen. Die Konsolenausgabe nennt den SHA-256 der Quittung. Für
|
||||
die vollständige Abnahme muss der Betreiber danach die identische
|
||||
Servergeneration und denselben Windows-Boot sowie die Zeit des Reads
|
||||
unabhängig anhand der Serveruhr bestätigen. Der Wrapper meldet seinen
|
||||
lokalen Befund, ohne eine serverseitige Prüfung zu behaupten.
|
||||
|
||||
`-AfterRestart` verlangt die Geburt eines später gestarteten Agentprozesses
|
||||
und aktuelle Belege für genau diese Instanz. Der Build `fcec400` publiziert
|
||||
die Dateien jeweils beim ersten erfolgreichen Vergleich einer **passiven**
|
||||
Verbindung. Nach Umschaltung auf Jobbetrieb müssen Job-Sync und
|
||||
Startgrant die aktuelle Freigabe belegen. Dateien aus einem früheren
|
||||
Prozess können diesen Nachweis nicht erbringen.
|
||||
|
||||
Lokal bestanden die Parserprüfung, je ein unverändertes Fixture für Agent
|
||||
und Helper sowie neun Ablehnungsfälle für doppelte Felder, falschen Typ,
|
||||
PID, Boot, Rolle, Generation, Schema und Zeitgrenzen. Die Boot-ID stimmte
|
||||
mit dem vorhandenen Python-Prüfer überein. Zeitvergleiche unterschieden
|
||||
eine Nanosekunde auch bei der neunstelligen Rust-Ausgabe. Die lokale Prüfung
|
||||
enthielt keine Ausführung des Lesers auf dem Windowsgast.
|
||||
|
||||
@@ -63,3 +63,130 @@ Produktquellen erzwingen keine neue native Ausführung und verhindern ihren
|
||||
Readback nicht. Neue Starts benötigen weiterhin die exakt qualifizierten
|
||||
aktuellen Quellen. Vollständige Ausgaben/Transportfehler bleiben privat,
|
||||
Standardausgabe enthält nur Status, Fallkennung und Nachweishashes.
|
||||
|
||||
### MCP-Planprüfung nach dem nativen Zeitvergleich am 15. November 2026
|
||||
|
||||
Um 20:44 Uhr MEZ las MCP die Windows-VM über ihre bestehende Geräteidentität
|
||||
als online. Sie meldete über WSS weiterhin `windows.base/1`, `heartbeat/1`
|
||||
und `agent.update/1`. Ein erster lesender Vorabcheck brach vor der Planung
|
||||
ab, weil er für diese passive Verbindung fälschlich `sync_ready=false`
|
||||
erwartete. Der Gateway setzt beim Hello ohne `rmm.sync.v1` den Wert
|
||||
`sync_required=false` und damit `sync_ready=true`. Ein signierter
|
||||
Job-Sync ist daraus nicht abzuleiten.
|
||||
|
||||
Um 20:44:47 Uhr MEZ wies `operations.plan` für genau diese Windows-VM eine
|
||||
PowerShell-Ausgabe einer festen Textzeile unter `agent_service` mit dem Profil
|
||||
`powershell_51_remote_signed` als `UNSUPPORTED_CAPABILITY` zurück. Der
|
||||
Windows-Agent veröffentlicht weder die Skript- noch die Profilfähigkeit.
|
||||
Vor und nach der Plananfrage standen Jobs, Outbox-Einträge, Ausführungspermits
|
||||
und offene Jobs dieses Geräts jeweils auf null. Es erfolgte kein Submit.
|
||||
MCP-Korrelations-ID `b87605ab-69ce-4697-b9ed-9f5b1eeba22c`,
|
||||
Beleg-SHA-256 `0df80d11f7e0ef5e300c4c9657dca3850dad839582b3ba945c1e69795fc68ecc`.
|
||||
|
||||
Für die erste erfolgreiche Skriptabnahme braucht der Dienst die an das Gerät
|
||||
gebundene Jobkonfiguration, qualifizierte Profilfähigkeit, signierten
|
||||
Auftragsabgleich und beim Start erneut frische Zeitbelege. Darauf folgt der
|
||||
unveränderliche Antrag mit Genehmigung in der WebUI.
|
||||
|
||||
### Erster LocalService-Auftrag, Stand 15. November 2026, 21:44 Uhr MEZ
|
||||
|
||||
Der gemeinsame Abnahmelauf kennt jetzt den festen Fall `windows_hello`.
|
||||
Er adressiert ausschließlich die bestehende Windows-Test-VM. Das Skript
|
||||
`Write-Output 'Zeitprofil-Test'` und die erwartete Ausgabe enden jeweils
|
||||
mit CRLF. Der Plan bindet `agent_service` und
|
||||
`powershell_51_remote_signed`. Der Browser prüft diese Angaben am gespeicherten
|
||||
Plan und die sichtbare Prozessoption vor der Freigabe. Der Ergebnisvergleich
|
||||
fordert neben Exit 0 und vollständiger Ausgabe auch die LocalService-SID,
|
||||
den Skripthash und den prozessgebundenen Policybeleg. Die vorhandenen
|
||||
Prüfungen für das Pending, den Freigabeaudit und die Anzahl der Startpermits
|
||||
gelten für diesen Fall.
|
||||
|
||||
Lokal bestanden beim Browser-Planvergleich ein positiver und elf negative
|
||||
Fälle. Der Python-Lauf prüfte den festen Planinput, eine passende
|
||||
Ergebnisquittung und neun abweichende Ergebnisse. Beim ersten lokalen
|
||||
Negativlauf fing der Test eine andere Ausnahmeklasse ab als der Prüfer
|
||||
warf. Der korrigierte Lauf mit dem gemeinsamen Abnahmefehler bestand.
|
||||
|
||||
Tatsächlich ausgeführt wurde
|
||||
`python3 deploy/cloud_mvp_acceptance.py --case windows_hello --execute-dev-test-ui`.
|
||||
Der Lauf stoppte vor der Planung bei `actual_vm_capability_required`.
|
||||
Der gespeicherte MCP-Kontakt um 21:42:59 Uhr MEZ war online, die
|
||||
Verbindungsgeneration betrug 146. Das Gerät meldete seine drei passiven
|
||||
Fähigkeiten. Jobs, Outbox, Permits und offene Aufträge standen auf null.
|
||||
SHA-256 des serverseitig nachgelesenen Zustands im lokalen Beleg
|
||||
`fd0c9af5f4df03a655fcb491212eb62c7777182f02a4e0a69633e5602985943c`.
|
||||
Um 21:44:08 Uhr MEZ bestätigte eine lesende Transaktion für dieselbe
|
||||
Generation `sync_required=false`, `sync_ready=true`,
|
||||
`helper_sync_ready=false` und null Sync-Checkpoints. Ein neuer Plan,
|
||||
eine WebUI-Genehmigung und eine Windows-Ausführung stehen aus.
|
||||
|
||||
Der Browser erreichte um 21:46 Uhr MEZ die echte, private WebUI des
|
||||
Projektservers über deren SSH-Weiterleitung mit TLS-Prüfung. Anmeldung,
|
||||
sichtbare Kennzeichnung `SIMULIERT` und Abmeldung als
|
||||
`simulated-testprincipal-a` gelangen. Die Sitzung meldete
|
||||
`approval_origin=dev_test_browser_simulation` und `testsimulation=true`.
|
||||
Der Server lieferte das Frontend-Bundle `index-CTgvl2jr.js` mit der
|
||||
PowerShell-Profilanzeige. Der Browser öffnete und genehmigte bei diesem
|
||||
Zugangscheck keinen Antrag.
|
||||
|
||||
### Cloud-Linux-Nachweis für die explizite Profilaktivierung
|
||||
|
||||
Am 15. November 2026 um 21:54:37 Uhr MEZ bestand auf der festgelegten
|
||||
Cloud-Linux-VM der portable Test
|
||||
`tests::remote_signed_requires_explicit_profile_jobs_and_binding`.
|
||||
Die Konfigurationsdefinition, die Methode `profile_enabled` und der Test
|
||||
stimmen als Quelltextabschnitte mit dem Windows-Agent in `fcec400` überein.
|
||||
Mit dem Buildfeature `system-helper` akzeptiert die Konfiguration das
|
||||
benannte Prozessprofil nur mit Job-Opt-in und Bindingpfad. Der Test
|
||||
verweigerte einen fehlenden Opt-in, deaktivierten Jobbetrieb, einen
|
||||
fehlenden Bindingpfad sowie ungültige Profilwerte einschließlich `Bypass`.
|
||||
|
||||
Die x86-64-Testdatei lief mit UID 65534, ohne ergänzende Gruppen, mit
|
||||
`no_new_privs` und in einem eigenen Netzwerk-Namespace. Der Aufruf mit
|
||||
exaktem Testnamen endete mit Exit 0, einem bestandenen Test, null
|
||||
ausgefilterten Tests und leerem stderr. Der Bootstrap entfernte das
|
||||
temporäre Testverzeichnis auf der VM. Der Test verwendete lokale
|
||||
Konfigurations-Fixtures. Windows-Dateirechte, LocalService-Jobbetrieb und
|
||||
die Genehmigung in der WebUI brauchen eigene Nachweise.
|
||||
|
||||
| Prüfgegenstand | SHA-256 |
|
||||
| --- | --- |
|
||||
| Originalquelle `runtime.rs` aus `fcec400` | `4f94cce2c0557436cef4ea5accffb4778af2a3faeb7339cea16592c30872b479` |
|
||||
| Extrahierte Testquelle | `2f338af46f38ebe72471dbdc81b0416947a20000bfad18be5b2f626c5c8a5812` |
|
||||
| Testmanifest | `df3fadfa8e94a710de99546c21b6b74635ac9ea70e8a157583ef7bae05cd76e8` |
|
||||
| Linux-Testdatei | `2168e5a6c31e2349b67ad81bcc58a711c3e37a0f03b7fecf0ca24281c5b72b6b` |
|
||||
| VM-Beleg im Fall `28fac5aa-66e4-466f-93fc-f97062031d43` | `ee3a2c99651491a2fd876f1a3463919dc32d9509d9f9ef4eb73a36aa848bb56d` |
|
||||
|
||||
### Native Windows-Profilprüfung des neuen Agenten
|
||||
|
||||
Am 15. November 2026 um 21:56:30 Uhr MEZ bestand auf der Windows-VM genau
|
||||
`runtime::tests::remote_signed_requires_explicit_profile_jobs_and_binding`
|
||||
aus dem Release-Testprogramm des Commits `fcec400`. Ergebnis 1 bestanden,
|
||||
7 gefiltert, Exit 0. Der vor dem Start nachgelesene SHA-256 der EXE war
|
||||
`7d1715dc105c1eb482405511e1b3abf4437c448e186e73923c43dd3c7938710e`.
|
||||
Der Konsolencontroller meldete Windows PowerShell **5.1.26100.9818** (x64).
|
||||
SHA-256 des auf dem Gast erzeugten JSON-Belegs
|
||||
`48de474d842ebc87550ba2e27b66086e6aa573973f252f4b8e19ac7b12b75a63`.
|
||||
Für die Übertragung diente ein temporäres schreibgeschütztes Testmedium.
|
||||
Der Test lief in der bereitgestellten Administratorkonsole. Er prüfte die
|
||||
Profilwahl im neuen Build. Die Ausführung als auftragsverarbeitender
|
||||
LocalService-Dienst muss weiterhin über die normale Genehmigungsstrecke folgen.
|
||||
|
||||
Im selben Gast wurde der neue Agent mit SHA-256
|
||||
`df80b00fc2119b973d690053b9f9e4bdedd8fbc211f67599c3301eeb42e7702f`
|
||||
in das geschützte Bootstrap-Verzeichnis kopiert und dort erneut gehasht.
|
||||
Im Wartungsfall `49c230d8-fb5d-4c64-96b6-e0edce03ed90` bestätigten die
|
||||
beiden Controller ihre Vorbereitung. Sie prüften den laufenden Vorgänger,
|
||||
seine öffentliche Bindung und die Dateirechte und legten die Kandidaten und
|
||||
Rückkehrkopien an. Die Dienstkonfiguration blieb dabei passiv.
|
||||
|
||||
Beim passiven Dienstwechsel stoppte der Controller Agent und Helper. Vor
|
||||
dem ersten Dateitausch scheiterte das Öffnen der Arbeitskopie für
|
||||
`FlushFile` mit „Zugriff verweigert“. Der erste diagnostische Leseaufruf
|
||||
verwendete einen falschen Fallverzeichnisnamen. Der korrigierte Aufruf las
|
||||
den ursprünglichen Fall und bestätigte bei Agent, Helperkonfiguration
|
||||
und Gegenstellen-Pin jeweils ursprüngliche FileID, Hash und ACL-Hash.
|
||||
Beide Dienste waren gestoppt. Es gab die Vorbereitungs- und Stoppbelege,
|
||||
aber keinen Ersetzungsbeleg. Quelle und Arbeitskopie waren 23.541.484
|
||||
Bytes groß, hatten den erwarteten SHA-256 des neuen Agenten und trugen
|
||||
das vom Installationsmedium übernommene Windows-Dateiattribut `ReadOnly`.
|
||||
|
||||
@@ -376,3 +376,196 @@ Fall `time-profile-receipt-f7f56e9f` ab. Für Zeitbelege verwendet er die
|
||||
bestehende Rollen-, Boot-, Generations- und Altersprüfung mit je einer
|
||||
Datenbanklesung vor und nach dem Empfang. Die Bereitstellung des Empfängers
|
||||
belegt noch keine Profilveröffentlichung auf dem Gast.
|
||||
|
||||
## Rückmeldung der Windows-VM am 15. November um 17:05:36 Uhr MEZ
|
||||
|
||||
Der Empfänger hat im Fall `time-profile-receipt-f7f56e9f` die Antwort
|
||||
`finalization_failed` gespeichert. Der Abschlussbefehl bestand die Prüfungen
|
||||
auf Kandidat, Berechtigungen und Dienstgenerationen bis zur Veröffentlichung.
|
||||
Der Aufruf von `File.Move` meldete HRESULT **0x80070020**
|
||||
(`ERROR_SHARING_VIOLATION`). Zeile 94 gibt diesen Fehler an den Aufrufer
|
||||
weiter. Empfangsbeleg SHA-256
|
||||
`7cc51d44abfbe7949b0896053a463f3bd140b1844229e9ba206683db34d6f2ba`,
|
||||
Ergebnis `172edeaf54ca08f4e5b1ad3662884da6ec217636ca30bbd8274e73140f6ef35b`.
|
||||
|
||||
Der Code des installierten Helpers öffnet das öffentliche Stammverzeichnis
|
||||
mit Lesezugriff und ausschließlich `FILE_SHARE_READ` und hält diesen Handle
|
||||
im laufenden Dienst. Ein Rename aus einem anderen Verzeichnis benötigt am
|
||||
Zielverzeichnis `FILE_ADD_FILE`. Das erklärt einen konkreten Konflikt.
|
||||
Die VM-Rückmeldung enthält keine Liste der tatsächlich offenen Handles.
|
||||
Für den älteren Installationsaufruf ohne HRESULT bleibt der Fehlercode
|
||||
unbekannt. Das laufende Konsolenskript hat keine weitere Veröffentlichung
|
||||
versucht. Für diesen Lauf liegt keine erfolgreiche Zeitprüfung vor.
|
||||
[Windows-Dateisystemregeln für Rename](https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-fsa/87f86c9b-6c2a-4803-84b7-131a74a434fa)
|
||||
|
||||
Nach der fehlgeschlagenen Erstveröffentlichung ergab eine unabhängige Abfrage
|
||||
von `inventory.get_device` über den permanenten Server einen neuen Kontakt
|
||||
um 17:12:44 Uhr MEZ, Präsenz `online` und Quelle `windows.base`.
|
||||
Geräte-ID, Agent-ID, Assignment, Enrollmentgeneration und authentifiziertes
|
||||
Zertifikat stimmten mit der Telemetrieabnahme vor dem Profilversuch überein.
|
||||
Der Agent meldete weiterhin die drei passiven Fähigkeiten `heartbeat/1`,
|
||||
`windows.base/1` und `agent.update/1`.
|
||||
### Erstprovisionierung nach dem belegten Sharingkonflikt
|
||||
|
||||
`Complete-OriginalTimeProfile.ps1 -InitialCreate` ist eine eigene Reparatur
|
||||
für das bislang fehlende Ziel. Sie setzt den vorhandenen Abschlussintent und
|
||||
den gespeicherten Fehler `File.Move / System.IO.IOException / 0x80070020`
|
||||
voraus. Die ursprünglichen Quell-, ACL-, Dienst-, Geräte- und
|
||||
Kandidatenbindungen gelten weiter. Der ursprüngliche Kandidat bleibt als
|
||||
Referenz erhalten. Der alte Move-Erfolg und dessen `result.json` werden durch
|
||||
diesen Pfad nicht nachträglich erzeugt.
|
||||
|
||||
Der feste neue Name wird genau einmal mit `CreateNew` angelegt. Windows
|
||||
erhält dabei bereits eine geschützte DACL mit explizitem Leseverbot für die
|
||||
beiden Service-SIDs. Der kontrollierende Prozess besitzt den einzigen
|
||||
Datenhandle. Er schreibt und flusht die 1177 qualifizierten Bytes und liest sie
|
||||
über denselben Handle vollständig zurück. Er prüft Hash, Volume, neue FileID,
|
||||
einzigen Hardlink, Länge und DACL. Dann prüft er die ursprüngliche
|
||||
Kandidatenidentität und die laufenden Dienste noch einmal und schreibt einen
|
||||
Prüfbeleg. Erst jetzt setzt er die bereits gebundene endgültige DACL auf dem
|
||||
gehaltenen Handle und prüft Identität, Hash und DACL erneut. Nach Schließen
|
||||
folgt eine separate Prüfung beider Pfade und Dienste. Damit wird eine neue
|
||||
Ziel-FileID dokumentiert. Die DACL des öffentlichen Ordners bleibt unverändert.
|
||||
[Windows-Dateierstellung](https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-fsa/498a5eeb-afc9-445f-99ed-a7e4b73c648b)
|
||||
[.NET-Framework-Konstruktor mit Erstellungs-DACL](https://learn.microsoft.com/en-us/dotnet/api/system.io.filestream.-ctor?view=netframework-4.8)
|
||||
|
||||
Eine vor der DACL-Freigabe unterbrochene Erstellung kann eine vorhandene
|
||||
Teildatei mit gesperrtem Dienstzugriff hinterlassen. Nach erfolgter
|
||||
DACL-Freigabe ist die Datei lesbar, auch wenn der Prozess vor dem
|
||||
abschließenden Ergebnis ausfällt. Ein neuer Versuch wird in beiden Fällen
|
||||
verweigert. Die getrennten `console-initial-create-*`-Dateien dokumentieren
|
||||
Intent, verifizierte neue Zielidentität und tatsächlichen Abschluss oder
|
||||
Fehlerphase. Das Ergebnis weist `clock_runtime_qualified=false` aus. Für
|
||||
dessen positive Bewertung sind weiterhin die unabhängigen Zeitbelege der
|
||||
installierten Dienste erforderlich.
|
||||
|
||||
Lokal bestanden Parserprüfung, Kompilierung des kleinen nativen
|
||||
Handle-Readers, Prüfung seines Strukturlayouts und drei simulierte
|
||||
Entscheidungsfälle mit echtem beziehungsweise verändertem Fehlerbeleg.
|
||||
Der frühere lokale Prüfharness wählte beim ersten Strukturlayoutaufruf die
|
||||
falsche .NET-Überladung; nach Angabe des Typs bestand die Prüfung. Der
|
||||
Original-Kandidaten-/FileID-Vergleich und die acht bisherigen Profilfixtures
|
||||
bestanden ebenfalls. Dieser Stand wurde auf der Windows-VM noch nicht
|
||||
ausgeführt.
|
||||
|
||||
Das passende Konsolenfenster ruft ausschließlich die Variante `-InitialCreate`
|
||||
auf. Der neue Empfänger `time-profile-receipt-f0488aba` war vor Übergabe des
|
||||
Befehls aktiv und hat die erwartete Geräte- und Gatewaybindung geprüft. Er
|
||||
unterscheidet die neue Rückmeldung von der alten Move-Fehlermeldung und
|
||||
speichert die Erstveröffentlichung und den signierten Rollenvergleich getrennt.
|
||||
Für diesen Skriptstand liegen bei Bereitstellung ausschließlich lokale Prüfungen
|
||||
vor. Die Bestätigung der VM steht aus.
|
||||
|
||||
Am 15. November endete die Freigabe um 18:00 Uhr MEZ. Der Empfänger für
|
||||
die Erstveröffentlichung schloss mit `window_expired`. Es lag keine
|
||||
entsprechende Gastquittung vor. Für die Fortsetzung wurde derselbe
|
||||
Weiterleitungsschlüssel bis 23:45 Uhr MEZ freigegeben. Frist und aktiver
|
||||
Abschalttimer wurden auf dem Server geprüft. Der neue Empfänger
|
||||
`time-profile-receipt-a6bb4e2f` hat den Gateway- und Gerätebezug geprüft
|
||||
und ist bereit. Der Konsolenstarter nimmt die Serverfrist als Parameter
|
||||
`-Until` entgegen und begrenzt jeden lokalen Start weiterhin auf zwölf Minuten.
|
||||
|
||||
### Rückmeldung aus dem Abendfenster
|
||||
|
||||
Um 20:24:02 Uhr MEZ empfing der Server im Fall `time-profile-receipt-a6bb4e2f`
|
||||
die Gastquittung `finalization_failed`. Der Aufruf mit `CreateNew` hatte das
|
||||
Ziel geöffnet. Bei der ersten Prüfung am offenen Handle wich die vom Kernel
|
||||
gelesene SDDL-Zeichenfolge vom vorbereiteten Sicherheitsdeskriptor ab. Der
|
||||
Controller brach in `verify_creation` in Zeile 176 mit `0x80131501` ab.
|
||||
Der Abbruch lag vor dem ersten Schreiben von Profilbytes und vor der Freigabe
|
||||
der Datei für die Dienste. Der HRESULT stammt von der ausgelösten
|
||||
PowerShell-Ausnahme. Er identifiziert keine abweichende Berechtigung.
|
||||
|
||||
Die Quittung enthält weder die beiden Deskriptoren noch eine spätere Nachlese
|
||||
der Zieldatei. Der konkrete Unterschied und der aktuelle Dateizustand bleiben
|
||||
zu prüfen. Der Empfänger beendete sich nach diesem Fehler wie vorgesehen.
|
||||
Es gibt aus diesem Lauf keinen erfolgreichen signierten Rollenvergleich.
|
||||
SHA-256 der Gastantwort samt Serverkontext:
|
||||
`a1725dbc532f022857e828080bec107ec32efd58836e22dd250909b9d7c2d28b`.
|
||||
|
||||
Ein separater MCP-Abruf bestätigte anschließend einen neuen Windows-Heartbeat
|
||||
um 20:25:35 Uhr MEZ. Präsenz war `online`, die Quelle `windows.base`.
|
||||
Gerät, Agent, Assignment, Enrollmentgeneration und authentifiziertes Zertifikat
|
||||
stimmten mit dem früheren Abnahmebeleg überein. Beleg-SHA-256
|
||||
`7ea828b42b3c7948956aad56845502ffa52192ce6ca14728203f8574d70a28ec`.
|
||||
|
||||
Der Konsolenstarter prüft im aktualisierten Quellstand vor einem Aufruf des
|
||||
Abschlussbefehls auf einen vorhandenen Fehler oder einen offenen Intent.
|
||||
In beiden Fällen liest er den vorhandenen Stand. Die Rückmeldung kennzeichnet
|
||||
mit `finalizer_invoked`, ob dieser Start den Abschlussbefehl aufgerufen hat.
|
||||
Enthält der Fehlerbeleg die bei der Erstellung verglichenen Deskriptoren,
|
||||
überträgt der Starter sie mit der Länge und den vorhandenen Datei-IDs an den
|
||||
Ergebnisempfänger. Ältere Fehlerbelege bleiben ohne diese Angaben lesbar.
|
||||
|
||||
Der PowerShell-Parser und fünf lokale Fälle bestanden: erster Aufruf,
|
||||
vorliegender Fehler, offener Intent, bereits vorliegender Erfolg und
|
||||
widersprüchliche Erfolgs-/Fehlermarker. Nur der erste Fall rief im Test den
|
||||
simulierten Abschluss auf. Diese Prüfung lief auf dem Entwicklungsrechner.
|
||||
|
||||
### Fehlerbeleg beim ersten Vergleich des Sicherheitsdeskriptors
|
||||
|
||||
Unterscheiden sich Soll- und Ist-SDDL an der neu angelegten Datei, erfasst der
|
||||
Controller beide Werte für Besitzer, Gruppe und DACL am exklusiv gehaltenen
|
||||
Dateihandle. Der private Fehlerbeleg enthält dazu das optionale Feld
|
||||
`creation_descriptor` mit `expected_sddl`, `actual_sddl` und `bytes`.
|
||||
Bei erfolgreicher nativer Identitätsabfrage kommen `file_id` und
|
||||
`volume_serial` hinzu. Scheitert das Lesen der Zusatzmetadaten, hält
|
||||
`metadata_hresult` dessen Fehlercode fest. Die ursprüngliche Abweichung
|
||||
bricht den Aufruf vor dem Schreiben der Profilbytes und der Rechtefreigabe ab.
|
||||
Der ältere Gastbeleg enthält diese neuen Felder noch nicht.
|
||||
|
||||
Lokal bestanden die Parserprüfung, vier PowerShell-Fälle für Vergleich und
|
||||
Fehlerbeleg sowie die acht vorhandenen Profiltests. Die vier Fälle umfassten
|
||||
ungleiche Deskriptoren mit lesbarer beziehungsweise fehlender FileID, einen
|
||||
gleichen Deskriptor und einen unabhängigen Folgefehler. Die FileID-Abfrage war
|
||||
simuliert. Eine native Abnahme dieser Belegerweiterung steht aus.
|
||||
|
||||
### Konsolennachweis der leeren Zieldatei
|
||||
|
||||
Die Bedienperson las den festen Zielpfad auf dem Windows-Gast. Die
|
||||
Dateigröße betrug 0 Byte. Beim Vergleich der ungebrochenen SDDL-Texte
|
||||
unterschieden sich ausschließlich die DACL-Steuerflags: erwartet `PAI`,
|
||||
gelesen `P`. Beide Deskriptoren enthalten denselben Eigentümer und dieselbe
|
||||
Gruppe (BUILTIN-Administratoren), die geschützte DACL und dieselben sechs
|
||||
expliziten ACEs in identischer Reihenfolge. Die beiden Dienst-SIDs haben
|
||||
je eine explizite Verweigerung von ReadData. Der Befund erklärt den
|
||||
Textvergleichsabbruch. Er belegt keine Freigabe der Datei.
|
||||
|
||||
SHA-256 der UTF-8-Texte ohne die Zeilenumbrüche der Konsolendarstellung:
|
||||
erwartet `d4726c7973c9b0cd8a66c1b129d1b5eb58d2bbfc1b103018e0a31a71fb1d9020`,
|
||||
gelesen `a0e1d856ed3bdbe884b23599f7c53d8a281d6409a42bbfa48649127b2aa22793`.
|
||||
Die erste Fehlerquittung enthielt keine FileID der leeren Zieldatei.
|
||||
|
||||
Der Modus `-ResumeEmpty` prüft die bestehenden Fallbelege und öffnet das
|
||||
leere Ziel exklusiv. Vor dem Schreiben protokolliert er dessen jetzt
|
||||
festgestellte FileID. Dieselbe Kennung muss nach dem Schreiben und nach
|
||||
der Freigabe der Leserechte wieder vorliegen. Beim DACL-Vergleich sind nur
|
||||
die beiden für diesen Fall beschriebenen Formen zulässig. Der Starter
|
||||
vergleicht die FileID zusätzlich mit der Quittung. Der Rückkanal überträgt
|
||||
das Ergebnis und die passiven Zeitmessungen.
|
||||
|
||||
Lokal bestanden acht Profiltests, die PowerShell-Parserprüfung, die
|
||||
C#-Kompilierung, fünf AMD64-Strukturlayoutprüfungen und 20 Vergleiche
|
||||
von Sicherheitsdeskriptoren. Acht lokale Fälle prüften die Auswahl des
|
||||
Startmodus und das Verhalten bei vorhandenen Markern. Die Anwendung auf
|
||||
dem Windowsgast und signierte Zeitmessungen beider Dienste stehen aus.
|
||||
|
||||
### Windows-VM, 15. November 2026, 20:40 Uhr MEZ
|
||||
|
||||
Der Controller schloss die Profilinstallation im Fall
|
||||
`ad9fd154-b2be-4f5d-9e17-65abb721ceaf` ab. Ab
|
||||
`2026-11-15T19:40:47.0850024Z` schrieb er die vorbereiteten 1177 Bytes.
|
||||
Beim Rücklesen stimmten der erwartete SHA-256
|
||||
`2b4a8a7080770304b80e2a665fa5f5ee1ebbd9182e7c80b184e75b114575b42b`
|
||||
und die bei leerer Datei protokollierte FileID
|
||||
`95990300000007000000000000000000` überein. Der Kandidat blieb erhalten.
|
||||
Agent und Helper liefen während der Veröffentlichung weiter.
|
||||
|
||||
Der Empfänger auf dem Projektserver bestätigte die Quittung in Sitzung
|
||||
`d8b4b255-8e3f-4aa7-8377-684ce9adbea1`.
|
||||
SHA-256 des Gast-Ergebnisbelegs
|
||||
`62a04be9c7d08d3687b51eacd6adbe290b91e16ba934d6b5bb531e8764a56cf5`,
|
||||
SHA-256 der serverseitigen Publikationsquittung
|
||||
`1a0ce65c852523072d6822024541591482e0bae3788834993c2548e9cbf7647e`.
|
||||
Um 20:40:59 Uhr MEZ fehlte beim anschließenden Lesen noch mindestens
|
||||
einer der beiden passiven Zeitbelege.
|
||||
|
||||
Reference in New Issue
Block a user