Compare commits
79
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 | ||
|
|
715287a559 | ||
|
|
a5ec061a92 | ||
|
|
9a6599fddd | ||
|
|
f023d790a4 | ||
|
|
5f21b753ed | ||
|
|
0b32859d74 | ||
|
|
331cdddac5 | ||
|
|
e952698f5e | ||
|
|
00717e4283 | ||
|
|
aa36b178aa | ||
|
|
d37160ba41 | ||
|
|
577132fb42 | ||
|
|
ca588abce4 | ||
|
|
53d17757ab | ||
|
|
27bb6a1257 | ||
|
|
cd80745d44 | ||
|
|
81d78aaf8f | ||
|
|
0ecfb98204 | ||
|
|
cd44bdb735 | ||
|
|
b0076d14be | ||
|
|
e46f11d3f9 | ||
|
|
895d107918 | ||
|
|
b5c7292f45 | ||
|
|
abdf392f31 | ||
|
|
1c1685bb40 | ||
|
|
2812bdaf27 | ||
|
|
54db5b72a3 | ||
|
|
03e5964474 | ||
|
|
5d3141f1df | ||
|
|
4ba243998c | ||
|
|
d3cd373d5e | ||
|
|
b47677b3a5 | ||
|
|
0c970dc6c0 | ||
|
|
99aedc14b1 | ||
|
|
4c6874a92b | ||
|
|
b5425fc152 | ||
|
|
8d1e6c99d7 | ||
|
|
2f9e45302a | ||
|
|
3ec30d373d | ||
|
|
43e696ff3f | ||
|
|
16eb5f86cf | ||
|
|
4e55e04b97 | ||
|
|
8bee0ad5e6 | ||
|
|
7f4066b337 | ||
|
|
725cddd5b2 | ||
|
|
ef509b3eb2 | ||
|
|
0ef1959c07 | ||
|
|
d9c1311332 | ||
|
|
64214fc41a | ||
|
|
95bcd201fc |
@@ -53,7 +53,7 @@ impl Client {
|
|||||||
ipc::service_sid(crate::SERVICE_NAME)?,
|
ipc::service_sid(crate::SERVICE_NAME)?,
|
||||||
ipc::service_sid(ipc::HELPER_SERVICE)?,
|
ipc::service_sid(ipc::HELPER_SERVICE)?,
|
||||||
];
|
];
|
||||||
let _root = ipc::PinnedFile::open(Path::new(PUBLIC_ROOT), true, &readers, &[], false)?;
|
let _root = ipc::PinnedFile::open_read_shared(Path::new(PUBLIC_ROOT), true, &readers, &[])?;
|
||||||
let mut file = ipc::PinnedFile::open(Path::new(PIN_PATH), false, &readers, &[], false)?;
|
let mut file = ipc::PinnedFile::open(Path::new(PIN_PATH), false, &readers, &[], false)?;
|
||||||
ensure!(file.file.metadata()?.len() <= 16384, "HELPER_PIN_SIZE");
|
ensure!(file.file.metadata()?.len() <= 16384, "HELPER_PIN_SIZE");
|
||||||
let mut bytes = Vec::new();
|
let mut bytes = Vec::new();
|
||||||
|
|||||||
@@ -216,7 +216,9 @@ pub fn read_settings() -> Result<(Settings, Vec<PinnedFile>)> {
|
|||||||
let agent = ipc::service_sid(crate::SERVICE_NAME)?;
|
let agent = ipc::service_sid(crate::SERVICE_NAME)?;
|
||||||
let helper = ipc::service_sid(ipc::HELPER_SERVICE)?;
|
let helper = ipc::service_sid(ipc::HELPER_SERVICE)?;
|
||||||
let readers = vec![agent, helper];
|
let readers = vec![agent, helper];
|
||||||
let root = PinnedFile::open(Path::new(PUBLIC_ROOT), true, &readers, &[], false)?;
|
// A rename into PUBLIC_ROOT opens the directory with FILE_ADD_FILE.
|
||||||
|
// The handle stays read-only and denies deletion of the pinned directory.
|
||||||
|
let root = PinnedFile::open_read_shared(Path::new(PUBLIC_ROOT), true, &readers, &[])?;
|
||||||
let mut file = PinnedFile::open(Path::new(CONFIG_PATH), false, &readers, &[], false)?;
|
let mut file = PinnedFile::open(Path::new(CONFIG_PATH), false, &readers, &[], false)?;
|
||||||
ensure!(file.file.metadata()?.len() <= 32768, "SYSTEM_CONFIG_SIZE");
|
ensure!(file.file.metadata()?.len() <= 32768, "SYSTEM_CONFIG_SIZE");
|
||||||
use std::io::Read;
|
use std::io::Read;
|
||||||
|
|||||||
@@ -39,6 +39,51 @@ struct Config {
|
|||||||
// Explicit protected opt-in only; this flag never qualifies a clock or pins.
|
// Explicit protected opt-in only; this flag never qualifies a clock or pins.
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
enable_jobs: bool,
|
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<()> {
|
fn create_private(path: &Path, bytes: &[u8]) -> Result<()> {
|
||||||
use std::io::Write;
|
use std::io::Write;
|
||||||
@@ -830,6 +875,13 @@ impl Agent {
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
if rmm_agent_windows::actions::supported(job) {
|
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;
|
return true;
|
||||||
}
|
}
|
||||||
#[cfg(feature = "system-helper")]
|
#[cfg(feature = "system-helper")]
|
||||||
@@ -859,9 +911,12 @@ impl Agent {
|
|||||||
{
|
{
|
||||||
caps.extend(["rmm.sync.v1", "refresh_inventory"].map(str::to_string));
|
caps.extend(["rmm.sync.v1", "refresh_inventory"].map(str::to_string));
|
||||||
if rmm_agent_windows::actions::powershell().is_ok() {
|
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));
|
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
|
caps
|
||||||
@@ -1810,7 +1865,7 @@ fn service_run(stop: &'static AtomicBool) -> Result<()> {
|
|||||||
);
|
);
|
||||||
let path = Path::new(&arguments[2]);
|
let path = Path::new(&arguments[2]);
|
||||||
ensure!(path.is_absolute(), "ABSOLUTE_CONFIG_REQUIRED");
|
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()?;
|
native::require_local_service()?;
|
||||||
ensure!(
|
ensure!(
|
||||||
config.state_directory.is_absolute(),
|
config.state_directory.is_absolute(),
|
||||||
@@ -1951,7 +2006,7 @@ pub fn main() -> Result<()> {
|
|||||||
args.len() == 3 && args[1] == "--config",
|
args.len() == 3 && args[1] == "--config",
|
||||||
"SERVICE_ARGUMENTS"
|
"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
|
// Shared transport reads its one DNS identity. Set it before SCM dispatch
|
||||||
// creates its service thread and before any Tokio/collector threads exist.
|
// creates its service thread and before any Tokio/collector threads exist.
|
||||||
unsafe {
|
unsafe {
|
||||||
@@ -2053,15 +2108,58 @@ mod tests {
|
|||||||
}
|
}
|
||||||
#[test]
|
#[test]
|
||||||
fn old_passive_configuration_cannot_enable_jobs_or_read_the_clock() {
|
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.enable_jobs);
|
||||||
assert!(config.job_binding_file.is_none());
|
assert!(config.job_binding_file.is_none());
|
||||||
|
assert!(config.windows_execution_profile.is_none());
|
||||||
let clock = JobClock::new(config.enable_jobs);
|
let clock = JobClock::new(config.enable_jobs);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
clock.now().unwrap_err().to_string(),
|
clock.now().unwrap_err().to_string(),
|
||||||
"WINDOWS_JOBS_NOT_ENABLED"
|
"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]
|
#[test]
|
||||||
fn legacy_inventory_keeps_original_bytes_until_concrete_core_ack() {
|
fn legacy_inventory_keeps_original_bytes_until_concrete_core_ack() {
|
||||||
let directory =
|
let directory =
|
||||||
|
|||||||
@@ -751,12 +751,11 @@ mod installed {
|
|||||||
settings.agent.service_sid.clone(),
|
settings.agent.service_sid.clone(),
|
||||||
settings.helper.service_sid.clone(),
|
settings.helper.service_sid.clone(),
|
||||||
];
|
];
|
||||||
files.push(PinnedFile::open(
|
files.push(PinnedFile::open_read_shared(
|
||||||
Path::new(PUBLIC_ROOT),
|
Path::new(PUBLIC_ROOT),
|
||||||
true,
|
true,
|
||||||
&readers,
|
&readers,
|
||||||
&[],
|
&[],
|
||||||
false,
|
|
||||||
)?);
|
)?);
|
||||||
let mut config_file =
|
let mut config_file =
|
||||||
PinnedFile::open(Path::new(CONFIG_PATH), false, &readers, &[], false)?;
|
PinnedFile::open(Path::new(CONFIG_PATH), false, &readers, &[], false)?;
|
||||||
|
|||||||
@@ -128,7 +128,7 @@ async fn device_list(
|
|||||||
.map_err(|e| e.0)?;
|
.map_err(|e| e.0)?;
|
||||||
let mut page =
|
let mut page =
|
||||||
crate::pagination::Cursor::parse(state, &principal, "devices:agent_id:asc", query)?;
|
crate::pagination::Cursor::parse(state, &principal, "devices:agent_id:asc", query)?;
|
||||||
let rows = sqlx::query("SELECT a.agent_id,a.asset_id,a.revoked_at,a.last_contact_at,a.certificate_sha256,a.last_authenticated_certificate_sha256,a.last_authenticated_at,a.capabilities,a.enrollment_generation,a.assignment_version,o.observed_at,o.received_at,o.data,o.source_id FROM agent_installations a LEFT JOIN LATERAL (SELECT observed_at,received_at,data,source_id FROM observations WHERE tenant_id=a.tenant_id AND agent_id=a.agent_id AND received_at<=$2 ORDER BY observed_at DESC, received_at DESC LIMIT 1) o ON true WHERE ($1::uuid IS NULL OR a.asset_id=$1) AND a.agent_id>$3 AND a.created_at<=$2 ORDER BY a.agent_id LIMIT $4")
|
let rows = sqlx::query("SELECT a.agent_id,a.asset_id,a.revoked_at,a.last_contact_at,a.certificate_sha256,a.last_authenticated_certificate_sha256,a.last_authenticated_at,a.capabilities,a.enrollment_generation,a.assignment_version,o.observed_at,o.received_at,o.data,o.source_id FROM agent_installations a LEFT JOIN LATERAL (SELECT observed_at,received_at,data,source_id FROM observations WHERE tenant_id=a.tenant_id AND agent_id=a.agent_id AND source_id IN ('linux.base','windows.base') AND received_at<=$2 ORDER BY observed_at DESC, received_at DESC LIMIT 1) o ON true WHERE ($1::uuid IS NULL OR a.asset_id=$1) AND a.agent_id>$3 AND a.created_at<=$2 ORDER BY a.agent_id LIMIT $4")
|
||||||
.bind(asset)
|
.bind(asset)
|
||||||
.bind(page.as_of).bind(page.last).bind(i64::from(page.limit)+1)
|
.bind(page.as_of).bind(page.last).bind(i64::from(page.limit)+1)
|
||||||
.fetch_all(&mut *tx).await.map_err(|_| StatusCode::SERVICE_UNAVAILABLE)?;
|
.fetch_all(&mut *tx).await.map_err(|_| StatusCode::SERVICE_UNAVAILABLE)?;
|
||||||
|
|||||||
@@ -2,15 +2,32 @@
|
|||||||
const fs = require('node:fs');
|
const fs = require('node:fs');
|
||||||
const path = require('node:path');
|
const path = require('node:path');
|
||||||
const crypto = require('node:crypto');
|
const crypto = require('node:crypto');
|
||||||
|
const { isDeepStrictEqual } = require('node:util');
|
||||||
const { chromium } = require('../../web/node_modules/playwright');
|
const { chromium } = require('../../web/node_modules/playwright');
|
||||||
const root = path.resolve(__dirname, '../..');
|
const root = path.resolve(__dirname, '../..');
|
||||||
const assert = (value) => { if (!value) throw new Error('UI contract mismatch'); };
|
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 () => {
|
(async () => {
|
||||||
const file = path.resolve(process.argv[2]);
|
const file = path.resolve(process.argv[2]);
|
||||||
const stat = fs.lstatSync(file);
|
const stat = fs.lstatSync(file);
|
||||||
assert(stat.isFile() && !stat.isSymbolicLink() && stat.uid === process.getuid() && (stat.mode & 0o777) === 0o600);
|
assert(stat.isFile() && !stat.isSymbolicLink() && stat.uid === process.getuid() && (stat.mode & 0o777) === 0o600);
|
||||||
const expected = JSON.parse(fs.readFileSync(file, 'utf8'));
|
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');
|
assert(expected.expected_principal === 'simulated-testprincipal-a');
|
||||||
const loginFile = path.join(root, 'credentials/server-browser-login.json');
|
const loginFile = path.join(root, 'credentials/server-browser-login.json');
|
||||||
const loginStat = fs.lstatSync(loginFile);
|
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);
|
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();
|
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 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(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(JSON.stringify(rendered.plan_payload_bytes) === JSON.stringify(expected.plan.plan_payload_bytes));
|
||||||
assert(rendered.jobs.length === 1 && rendered.resolved_targets.length === 1);
|
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.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(payload.execution_identity === 'agent_service' && payload.max_runtime_seconds === 60 && payload.max_output_bytes <= 65536);
|
||||||
assert(Date.parse(payload.start_before) > Date.now());
|
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');
|
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 });
|
const approve = detail.getByRole('button', { name: 'SIMULIERT: Diesen festen Plan ausdrücklich genehmigen', exact: true });
|
||||||
assert(await approve.isDisabled());
|
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.
|
file. All SQL is fixed read-only evidence, scoped to the one cloud VM.
|
||||||
"""
|
"""
|
||||||
import argparse
|
import argparse
|
||||||
|
from datetime import timedelta
|
||||||
import hashlib
|
import hashlib
|
||||||
import http.client
|
import http.client
|
||||||
import json
|
import json
|
||||||
@@ -24,6 +25,38 @@ import vm_mvp_acceptance as contract
|
|||||||
ROOT = bootstrap.ROOT
|
ROOT = bootstrap.ROOT
|
||||||
TENANT = bootstrap.TENANT
|
TENANT = bootstrap.TENANT
|
||||||
require = bootstrap.require
|
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():
|
def prepare_browser():
|
||||||
@@ -147,10 +180,15 @@ class Backend:
|
|||||||
def main():
|
def main():
|
||||||
parser=argparse.ArgumentParser(description=__doc__)
|
parser=argparse.ArgumentParser(description=__doc__)
|
||||||
parser.add_argument('--execute-dev-test-ui',action='store_true',required=True)
|
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'))
|
parser.add_argument('--transport',choices=('wss','https'))
|
||||||
args=parser.parse_args();os.umask(0o077)
|
args=parser.parse_args();os.umask(0o077)
|
||||||
contract.require(not (Path.home()/'.local/share/rust-discovery/remote-agent').exists(),'notebook_must_not_have_client')
|
contract.require(not (Path.home()/'.local/share/rust-discovery/remote-agent').exists(),'notebook_must_not_have_client')
|
||||||
|
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()
|
prepare_browser()
|
||||||
installed=contract.protected_json(ROOT/'devstate/remote-vm.json')
|
installed=contract.protected_json(ROOT/'devstate/remote-vm.json')
|
||||||
identity=installed['identity']
|
identity=installed['identity']
|
||||||
@@ -172,11 +210,18 @@ def main():
|
|||||||
observed=bootstrap.rpc('server.conf',bootstrap.server,dict(action='observe',agent_id=identity['agent_id']))
|
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')
|
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'}
|
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')
|
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))
|
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')
|
contract.require(hashlib.sha256(bytes(plan['plan_payload_bytes'])).hexdigest()==plan['plan_hash'] and len(plan['jobs'])==1,'immutable_plan')
|
||||||
job=plan['jobs'][0]
|
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)
|
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,
|
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)
|
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')
|
contract.require(result['state']=='succeeded' and result['result']['evidence']['postconditions_passed'],'native_postconditions_required')
|
||||||
if args.case=='hello':
|
if args.case=='hello':
|
||||||
contract.require(result['result']['exit_code']==0 and bytes(result['result']['stdout'])==b'Hello World\n','exact_stdout_required')
|
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':
|
elif args.case=='refresh_inventory':
|
||||||
contract.require(contract.timestamp(result['result']['evidence']['observed_at'])>=contract.timestamp(request['schedule']['not_before']),'fresh_inventory_required')
|
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'])
|
gate=evidence('gate',job_id=job['job_id']);audit=evidence('audit',operation_id=pending['operation_id'])
|
||||||
|
|||||||
@@ -0,0 +1,428 @@
|
|||||||
|
#requires -Version 5.1
|
||||||
|
#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'
|
||||||
|
$bootstrap = 'C:\ProgramData\RustDiscoveryBootstrap'
|
||||||
|
$casePath = Join-Path $bootstrap "time-profile-$caseId"
|
||||||
|
$original = Join-Path (Join-Path $bootstrap $controllerHash) 'InstallPublicTimeProfile.ps1'
|
||||||
|
$originalBytes = [IO.File]::ReadAllBytes($original)
|
||||||
|
$sha = [Security.Cryptography.SHA256]::Create()
|
||||||
|
try {
|
||||||
|
$digest = [BitConverter]::ToString($sha.ComputeHash($originalBytes)).Replace('-', '')
|
||||||
|
} finally { $sha.Dispose() }
|
||||||
|
if ($digest -ne $controllerHash) { throw 'Unexpected original controller' }
|
||||||
|
|
||||||
|
# Import the verified definitions (including native FileID/SCM checks) from the
|
||||||
|
# installed original. Its first top-level preflight and install body are excluded.
|
||||||
|
$source = [Text.Encoding]::UTF8.GetString($originalBytes)
|
||||||
|
$boundary = "`nCheckControl `$boot `$true`n"
|
||||||
|
$index = $source.IndexOf($boundary, [StringComparison]::Ordinal)
|
||||||
|
if ($index -lt 1 -or $index -ne $source.LastIndexOf($boundary, [StringComparison]::Ordinal)) {
|
||||||
|
throw 'Original controller definition boundary missing'
|
||||||
|
}
|
||||||
|
$intent = Get-Content -LiteralPath (Join-Path $casePath 'intent.json') -Raw | ConvertFrom-Json
|
||||||
|
if ($intent.id -cne $caseId -or $intent.request.id -cne $caseId -or
|
||||||
|
$intent.request.script_sha256 -cne $controllerHash -or $intent.request.config_sha256 -cne $configHash) {
|
||||||
|
throw 'Unexpected original intent'
|
||||||
|
}
|
||||||
|
$global:RmmTimeProfilePayload = $intent.request
|
||||||
|
. ([scriptblock]::Create($source.Substring(0, $index)))
|
||||||
|
|
||||||
|
CheckControl $boot $true
|
||||||
|
CheckControl $folder $true
|
||||||
|
foreach ($leaf in 'intent.json','publish-intent.json','directory-acl-intent.json','directory-acl-done.json') {
|
||||||
|
CheckControl (Join-Path $folder $leaf) $false
|
||||||
|
}
|
||||||
|
CheckControl $active $false
|
||||||
|
$activeRecord = Get-Content -LiteralPath $active -Raw | ConvertFrom-Json
|
||||||
|
if ($activeRecord.id -cne $caseId -or $activeRecord.script_sha256 -cne $controllerHash -or
|
||||||
|
$activeRecord.config_sha256 -cne $configHash -or $activeRecord.no_retry -ne $true) {
|
||||||
|
throw 'Unexpected active publication record'
|
||||||
|
}
|
||||||
|
$bytes = ConfigBytes
|
||||||
|
$publish = Get-Content -LiteralPath (Join-Path $folder 'publish-intent.json') -Raw | ConvertFrom-Json
|
||||||
|
$aclDone = Get-Content -LiteralPath (Join-Path $folder 'directory-acl-done.json') -Raw | ConvertFrom-Json
|
||||||
|
$staged = Join-Path $folder 'time-attestation.candidate.json'
|
||||||
|
$resultPath = Join-Path $folder 'result.json'
|
||||||
|
$reservation = Join-Path $folder 'console-finalization-intent.json'
|
||||||
|
$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' }
|
||||||
|
}
|
||||||
|
$stagedAcl = ReadAcl $staged $false
|
||||||
|
$rootAcl = ReadAcl $helperRoot $true
|
||||||
|
$expected = @{
|
||||||
|
volume_serial = '9815088561147542064'
|
||||||
|
file_id = '6d990300000003000000000000000000'
|
||||||
|
bytes = 1177
|
||||||
|
acl_sha256 = '3a426f649cd6ff4e82bf70205c8ecc7d5b2c0775fa1e10fc30ce35de9bb12493'
|
||||||
|
sha256 = $configHash
|
||||||
|
}
|
||||||
|
if ($publish.create_once -ne $true -or $publish.config_sha256 -cne $configHash -or
|
||||||
|
!(JsonEqual $expected $publish.staged) -or !(JsonEqual $expected (FileIdentity $staged)) -or
|
||||||
|
(FileVolume $helperRoot) -cne $expected.volume_serial -or $rootAcl.Sddl -cne $aclDone.sddl -or
|
||||||
|
(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'
|
||||||
|
}
|
||||||
|
$before = ActualState $true
|
||||||
|
SameLive $request.expected_native $before
|
||||||
|
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 {
|
||||||
|
[IO.File]::Move($staged, $target)
|
||||||
|
} catch {
|
||||||
|
$cause = $_.Exception.GetBaseException()
|
||||||
|
$failure = @{id=$caseId; phase='File.Move'; hresult=('0x{0:X8}' -f $cause.HResult); exception=$cause.GetType().FullName}
|
||||||
|
WriteNew (Join-Path $folder 'console-finalization-error.json') $failure
|
||||||
|
throw ("File.Move: {0} ({1})." -f $failure.exception, $failure.hresult)
|
||||||
|
}
|
||||||
|
$null = ReadAcl $target $false
|
||||||
|
$published = FileIdentity $target
|
||||||
|
if (!(JsonEqual $expected $published) -or (Test-Path -LiteralPath $staged)) { throw 'Publication postcheck failed' }
|
||||||
|
$after = ActualState $true
|
||||||
|
SameLive $before $after
|
||||||
|
$null = Kernel 'agent' $before.service $heldAgent
|
||||||
|
$null = Kernel 'helper' $before.helper_service $heldHelper
|
||||||
|
WriteNew $resultPath @{
|
||||||
|
id=$caseId; installed=$true; install_not_before=$intent.install_not_before
|
||||||
|
configuration=$published; native=$after; original_root_sddl=$intent.original_root_sddl
|
||||||
|
root_sddl=(Get-Acl -LiteralPath $helperRoot).Sddl; no_jobs=$true
|
||||||
|
clock_runtime_qualified=$false; services_changed=$false; private_key_read=$false
|
||||||
|
console_finalized=$true; original_move_failed=$true
|
||||||
|
}
|
||||||
|
'Zeitprofil veroeffentlicht; Dateiidentitaet und Dienstgenerationen geprueft.'
|
||||||
|
} finally { $heldHelper.Dispose() }
|
||||||
|
} finally { $heldAgent.Dispose() }
|
||||||
@@ -3,7 +3,8 @@
|
|||||||
[CmdletBinding()]
|
[CmdletBinding()]
|
||||||
param(
|
param(
|
||||||
[Parameter(Mandatory)][DateTimeOffset]$PreviousExpiry,
|
[Parameter(Mandatory)][DateTimeOffset]$PreviousExpiry,
|
||||||
[Parameter(Mandatory)][DateTimeOffset]$Until
|
[Parameter(Mandatory)][DateTimeOffset]$Until,
|
||||||
|
[switch]$ResumeInterrupted
|
||||||
)
|
)
|
||||||
$ErrorActionPreference = 'Stop'
|
$ErrorActionPreference = 'Stop'
|
||||||
$utcNow = [DateTimeOffset]::UtcNow
|
$utcNow = [DateTimeOffset]::UtcNow
|
||||||
@@ -16,11 +17,25 @@ $raw = [IO.File]::ReadAllText($configPath)
|
|||||||
$cfg = $raw | ConvertFrom-Json
|
$cfg = $raw | ConvertFrom-Json
|
||||||
$user = Get-LocalUser -Name 'rmm-dev'
|
$user = Get-LocalUser -Name 'rmm-dev'
|
||||||
$task = Get-ScheduledTask -TaskPath '\' -TaskName 'RmmDevReverseTunnel'
|
$task = Get-ScheduledTask -TaskPath '\' -TaskName 'RmmDevReverseTunnel'
|
||||||
if ($task.State -ne 'Ready' -or !$user.Enabled -or !$user.AccountExpires -or
|
$expectedState = if ($ResumeInterrupted) { 'Disabled' } else { 'Ready' }
|
||||||
$user.AccountExpires.ToUniversalTime() -ne $PreviousExpiry.UtcDateTime -or
|
$expectedExpiry = if ($ResumeInterrupted) { $Until } else { $PreviousExpiry }
|
||||||
[DateTimeOffset]::Parse($cfg.expires_at) -ne $PreviousExpiry -or
|
$mismatches = @(
|
||||||
$cfg.server -cne 'discovery.ease-technologies.de' -or (Get-Service sshd).Status -ne 'Running') {
|
if ($task.State -ne $expectedState) { "task state $($task.State) (expected $expectedState)" }
|
||||||
throw 'Unexpected account, task, server or previous expiry.'
|
if (!$user.Enabled) { 'rmm-dev is disabled' }
|
||||||
|
if (!$user.AccountExpires) {
|
||||||
|
'rmm-dev has no account expiry'
|
||||||
|
} elseif ($user.AccountExpires.ToUniversalTime() -ne $expectedExpiry.UtcDateTime) {
|
||||||
|
"account expiry $($user.AccountExpires.ToUniversalTime().ToString('o')) (expected $($expectedExpiry.UtcDateTime.ToString('o')))"
|
||||||
|
}
|
||||||
|
if ([DateTimeOffset]::Parse($cfg.expires_at) -ne $expectedExpiry) {
|
||||||
|
"configuration expiry $($cfg.expires_at) (expected $($expectedExpiry.UtcDateTime.ToString('o')))"
|
||||||
|
}
|
||||||
|
if ($cfg.server -cne 'discovery.ease-technologies.de') { 'configured server differs' }
|
||||||
|
$sshdState = (Get-Service -Name sshd).Status
|
||||||
|
if ($sshdState -ne 'Running') { "sshd state $sshdState (expected Running)" }
|
||||||
|
)
|
||||||
|
if ($mismatches.Count -gt 0) {
|
||||||
|
throw ('Maintenance window preflight failed: ' + ($mismatches -join ', '))
|
||||||
}
|
}
|
||||||
$pinned = (Get-Content -LiteralPath (Join-Path $dir 'known_hosts') -Raw).Trim()
|
$pinned = (Get-Content -LiteralPath (Join-Path $dir 'known_hosts') -Raw).Trim()
|
||||||
if ($pinned -cne ('discovery.ease-technologies.de ' + $cfg.server_host_key)) {
|
if ($pinned -cne ('discovery.ease-technologies.de ' + $cfg.server_host_key)) {
|
||||||
@@ -31,9 +46,27 @@ if ($listeners.Count -ne 1 -or $listeners[0].LocalAddress -ne '127.0.0.1') {
|
|||||||
throw 'Expected only the original loopback SSH listener.'
|
throw 'Expected only the original loopback SSH listener.'
|
||||||
}
|
}
|
||||||
$backup = Join-Path $dir ('console-window-' + [guid]::NewGuid().ToString() + '.bak')
|
$backup = Join-Path $dir ('console-window-' + [guid]::NewGuid().ToString() + '.bak')
|
||||||
|
$originalRaw = $raw
|
||||||
|
if ($ResumeInterrupted) {
|
||||||
|
$owners = @(Get-CimInstance Win32_Process -Filter "Name='powershell.exe' OR Name='pwsh.exe' OR Name='ssh.exe'" | Where-Object {
|
||||||
|
$_.ProcessId -ne $PID -and ($_.CommandLine -match '(?:rmm-window-[0-9a-f-]+|Open-ConsoleMaintenanceWindow)\.ps1' -or
|
||||||
|
($_.Name -eq 'ssh.exe' -and $_.CommandLine -match '127\.0\.0\.1:22240:127\.0\.0\.1:22222'))
|
||||||
|
})
|
||||||
|
if ($owners.Count) { throw 'An existing maintenance console or forwarding process is still active. End the original console with Ctrl+C first.' }
|
||||||
|
$copies = @(Get-ChildItem -LiteralPath $dir -Filter 'console-window-*.bak' -File -Force)
|
||||||
|
if ($copies.Count -ne 1 -or $copies[0].Name -notmatch '^console-window-[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}\.bak$' -or
|
||||||
|
($copies[0].Attributes -band [IO.FileAttributes]::ReparsePoint) -or $copies[0].Length -gt 32768) {
|
||||||
|
throw 'Expected one original maintenance-window backup.'
|
||||||
|
}
|
||||||
|
$backup = $copies[0].FullName
|
||||||
|
if (Test-Path -LiteralPath ($backup + '.closed')) { throw 'Backup already closed.' }
|
||||||
|
$originalRaw = [IO.File]::ReadAllText($backup)
|
||||||
|
$original = $originalRaw | ConvertFrom-Json
|
||||||
|
if ([DateTimeOffset]::Parse($original.expires_at) -ne $PreviousExpiry) { throw 'Backup expiry differs.' }
|
||||||
|
$original.expires_at = $Until.ToUniversalTime().ToString('yyyy-MM-ddTHH:mm:sszzz')
|
||||||
|
if (($original | ConvertTo-Json -Compress) -cne $raw) { throw 'Backup does not reconstruct the current public configuration.' }
|
||||||
|
}
|
||||||
$candidate = $backup + '.new'
|
$candidate = $backup + '.new'
|
||||||
$cfg.expires_at = $Until.ToUniversalTime().ToString('yyyy-MM-ddTHH:mm:sszzz')
|
|
||||||
[IO.File]::WriteAllText($candidate, ($cfg | ConvertTo-Json -Compress), (New-Object Text.UTF8Encoding($false)))
|
|
||||||
$sshArgs = @('-F','NUL','-N','-T','-o','BatchMode=yes','-o','IdentitiesOnly=yes',
|
$sshArgs = @('-F','NUL','-N','-T','-o','BatchMode=yes','-o','IdentitiesOnly=yes',
|
||||||
'-o','ForwardAgent=no','-o','StrictHostKeyChecking=yes','-o','GlobalKnownHostsFile=NUL',
|
'-o','ForwardAgent=no','-o','StrictHostKeyChecking=yes','-o','GlobalKnownHostsFile=NUL',
|
||||||
'-o',('UserKnownHostsFile=' + $dir + '\known_hosts'),'-o','ExitOnForwardFailure=yes',
|
'-o',('UserKnownHostsFile=' + $dir + '\known_hosts'),'-o','ExitOnForwardFailure=yes',
|
||||||
@@ -44,12 +77,20 @@ $ssh = $null
|
|||||||
$disabled = $false
|
$disabled = $false
|
||||||
$accountChanged = $false
|
$accountChanged = $false
|
||||||
try {
|
try {
|
||||||
|
if (!$ResumeInterrupted) {
|
||||||
|
$cfg.expires_at = $Until.ToUniversalTime().ToString('yyyy-MM-ddTHH:mm:sszzz')
|
||||||
|
[IO.File]::WriteAllText($candidate, ($cfg | ConvertTo-Json -Compress), (New-Object Text.UTF8Encoding($false)))
|
||||||
Disable-ScheduledTask -InputObject $task | Out-Null
|
Disable-ScheduledTask -InputObject $task | Out-Null
|
||||||
$disabled = $true
|
$disabled = $true
|
||||||
|
}
|
||||||
if ((Get-ScheduledTask -TaskPath '\' -TaskName $task.TaskName).State -ne 'Disabled' -or
|
if ((Get-ScheduledTask -TaskPath '\' -TaskName $task.TaskName).State -ne 'Disabled' -or
|
||||||
[IO.File]::ReadAllText($configPath) -cne $raw) { throw 'Existing bootstrap changed.' }
|
[IO.File]::ReadAllText($configPath) -cne $raw) { throw 'Existing bootstrap changed.' }
|
||||||
|
if ($ResumeInterrupted) {
|
||||||
|
$disabled = $true
|
||||||
|
} else {
|
||||||
[IO.File]::Replace($candidate, $configPath, $backup)
|
[IO.File]::Replace($candidate, $configPath, $backup)
|
||||||
Set-LocalUser -SID $user.SID -AccountExpires $Until.LocalDateTime
|
Set-LocalUser -SID $user.SID -AccountExpires $Until.LocalDateTime
|
||||||
|
}
|
||||||
$accountChanged = $true
|
$accountChanged = $true
|
||||||
if ((Get-LocalUser -SID $user.SID).AccountExpires.ToUniversalTime() -ne $Until.UtcDateTime) {
|
if ((Get-LocalUser -SID $user.SID).AccountExpires.ToUniversalTime() -ne $Until.UtcDateTime) {
|
||||||
throw 'Unexpected account expiry after renewal.'
|
throw 'Unexpected account expiry after renewal.'
|
||||||
@@ -65,7 +106,7 @@ try {
|
|||||||
try { if (!$ssh.HasExited) { $ssh.Kill(); $ssh.WaitForExit() } } finally { $ssh.Dispose() }
|
try { if (!$ssh.HasExited) { $ssh.Kill(); $ssh.WaitForExit() } } finally { $ssh.Dispose() }
|
||||||
}
|
}
|
||||||
if ($accountChanged) { Set-LocalUser -SID $user.SID -AccountExpires $PreviousExpiry.LocalDateTime }
|
if ($accountChanged) { Set-LocalUser -SID $user.SID -AccountExpires $PreviousExpiry.LocalDateTime }
|
||||||
if (Test-Path -LiteralPath $backup) { [IO.File]::Replace($backup, $configPath, ($backup + '.closed')) }
|
if ($disabled -and (Test-Path -LiteralPath $backup)) { [IO.File]::Replace($backup, $configPath, ($backup + '.closed')) }
|
||||||
if ($disabled -and [IO.File]::ReadAllText($configPath) -ceq $raw) { Enable-ScheduledTask -InputObject $task | Out-Null }
|
if ($disabled -and [IO.File]::ReadAllText($configPath) -ceq $originalRaw) { Enable-ScheduledTask -InputObject $task | Out-Null }
|
||||||
if (Test-Path -LiteralPath $candidate) { Remove-Item -LiteralPath $candidate }
|
if (!$ResumeInterrupted -and (Test-Path -LiteralPath $candidate)) { Remove-Item -LiteralPath $candidate }
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,152 @@
|
|||||||
|
#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'
|
||||||
|
$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/b614b6f5be9d700eef20586a038aa9643356049a/deploy/windows'
|
||||||
|
$bootstrap = 'C:\ProgramData\RustDiscoveryBootstrap'
|
||||||
|
$caseId = 'ad9fd154-b2be-4f5d-9e17-65abb721ceaf'
|
||||||
|
$case = Join-Path $bootstrap "time-profile-$caseId"
|
||||||
|
$access = 'C:\ProgramData\RmmDevAccess'
|
||||||
|
$sshBin = Join-Path $env:WINDIR 'System32\OpenSSH'
|
||||||
|
$known = Join-Path $access 'known_hosts'
|
||||||
|
$key = Join-Path $access 'tunnel_ed25519'
|
||||||
|
$fp = & "$sshBin\ssh-keygen.exe" -lf $known
|
||||||
|
if ($LASTEXITCODE -ne 0 -or @($fp).Count -ne 1 -or
|
||||||
|
$fp.Split(' ')[1] -cne 'SHA256:+NEin4XJc3CbhjQi7/ZpMIgxOrXn8AT2tlpTaXW5quw') { throw 'Server-Hostpin stimmt nicht.' }
|
||||||
|
$session = [guid]::NewGuid().ToString()
|
||||||
|
$work = Join-Path $bootstrap "time-receipt-$session"
|
||||||
|
$null = New-Item -ItemType Directory -Path $work
|
||||||
|
$listener = $null
|
||||||
|
$ssh = $null
|
||||||
|
$scripts = [ordered]@{
|
||||||
|
'Complete-OriginalTimeProfile.ps1' = 'aacc56321dccc6efe496a782d4cf67defba5b0be6759cba08d9e0b775913210b'
|
||||||
|
'Read-PassiveTimeSamples.ps1' = 'd9e2b9344c19af1296b86ec70ba754ef820f369ac5ec897979bd4233e0722d04'
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
foreach ($name in $scripts.Keys) {
|
||||||
|
$path = Join-Path $work $name
|
||||||
|
Invoke-WebRequest -UseBasicParsing -Uri "$base/$name" -OutFile $path -TimeoutSec 30
|
||||||
|
if ((Get-FileHash -LiteralPath $path).Hash -ne $scripts[$name]) { throw "Downloadhash: $name" }
|
||||||
|
Unblock-File -LiteralPath $path
|
||||||
|
}
|
||||||
|
$listener = [Net.Sockets.TcpListener]::new([Net.IPAddress]::Loopback, 0)
|
||||||
|
$listener.Start(4)
|
||||||
|
$port = $listener.LocalEndpoint.Port
|
||||||
|
$options = @('-F','NUL','-N','-T','-o','BatchMode=yes','-o','IdentitiesOnly=yes',
|
||||||
|
'-o','ForwardAgent=no','-o','StrictHostKeyChecking=yes','-o','GlobalKnownHostsFile=NUL',
|
||||||
|
'-o',"UserKnownHostsFile=$known",'-o','ExitOnForwardFailure=yes','-o','ConnectTimeout=10',
|
||||||
|
'-o','ServerAliveInterval=15','-o','ServerAliveCountMax=2','-i',$key,
|
||||||
|
'-R',"127.0.0.1:22240:127.0.0.1:$port",'rmm-win-tunnel@discovery.ease-technologies.de')
|
||||||
|
$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.'
|
||||||
|
$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)) {
|
||||||
|
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.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 $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 = $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'
|
||||||
|
$receipt.exception_type = $_.Exception.GetBaseException().GetType().FullName
|
||||||
|
$receipt.line = $_.InvocationInfo.ScriptLineNumber
|
||||||
|
$receipt.file = [IO.Path]::GetFileName($_.InvocationInfo.ScriptName)
|
||||||
|
Write-Warning $_.Exception.Message
|
||||||
|
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.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'
|
||||||
|
$readInput = @{id=$session; agent_sha256='0549d9ebea73cff996938f859b92192cc333de194128d7c6859a3f1d2e85893c'; helper_sha256='59675a3cbb3a5d213fc764f38379d6b81baaf9d47a7124470cc2767d4985763e'} | ConvertTo-Json -Compress
|
||||||
|
while ([DateTimeOffset]::UtcNow -lt $deadline -and !$ssh.HasExited) {
|
||||||
|
if (!$listener.Pending()) { Start-Sleep -Milliseconds 250; continue }
|
||||||
|
$client = $listener.AcceptTcpClient()
|
||||||
|
try {
|
||||||
|
if ($receipt.phase -eq 'published') {
|
||||||
|
$receipt.native = $null
|
||||||
|
try {
|
||||||
|
$json = $readInput | & "$env:WINDIR\System32\WindowsPowerShell\v1.0\powershell.exe" -NoProfile -ExecutionPolicy RemoteSigned -File $readScript
|
||||||
|
if ($LASTEXITCODE -eq 0) { $receipt.native = ($json -join "`n") | ConvertFrom-Json }
|
||||||
|
} catch { Write-Warning 'Passive Zeitbelege aktuell nicht lesbar.' }
|
||||||
|
}
|
||||||
|
$client.SendTimeout = 3000
|
||||||
|
$body = [Text.Encoding]::UTF8.GetBytes(($receipt | ConvertTo-Json -Depth 16 -Compress))
|
||||||
|
if ($body.Length -gt 65536) { throw 'Ergebnis zu gross.' }
|
||||||
|
$client.GetStream().Write($body,0,$body.Length)
|
||||||
|
} catch { Write-Warning $_.Exception.Message } finally { $client.Dispose() }
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
if ($null -ne $ssh) {
|
||||||
|
try { if (!$ssh.HasExited) { $ssh.Kill(); $ssh.WaitForExit() } } finally { $ssh.Dispose() }
|
||||||
|
}
|
||||||
|
if ($null -ne $listener) { $listener.Stop() }
|
||||||
|
foreach ($name in $scripts.Keys) {
|
||||||
|
$path = Join-Path $work $name
|
||||||
|
if (Test-Path -LiteralPath $path) { Remove-Item -LiteralPath $path }
|
||||||
|
}
|
||||||
|
if ((Get-ChildItem -LiteralPath $work -Force | Measure-Object).Count -eq 0) { [IO.Directory]::Delete($work) }
|
||||||
|
}
|
||||||
@@ -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,63 @@
|
|||||||
|
$ErrorActionPreference='Stop';$p=([Console]::In.ReadLine()|ConvertFrom-Json)
|
||||||
|
if((($p.PSObject.Properties.Name|Sort-Object)-join',')-cne'agent_sha256,helper_sha256,id'-or[guid]::ParseExact($p.id,'D').ToString()-cne$p.id-or$p.agent_sha256-cnotmatch'^[0-9a-f]{64}$'-or$p.helper_sha256-cnotmatch'^[0-9a-f]{64}$'){throw 'Fixed public sample read'}
|
||||||
|
$state='C:\ProgramData\RustDiscovery\state';$agent='RmmDiscoveryWindows';$helper='RmmDiscoverySystemHelper'
|
||||||
|
$agentSid=(New-Object Security.Principal.NTAccount('NT SERVICE',$agent)).Translate([Security.Principal.SecurityIdentifier]).Value
|
||||||
|
$allowed=@('S-1-5-18','S-1-5-32-544',$agentSid)
|
||||||
|
function Check($path,[bool]$directory){
|
||||||
|
$i=Get-Item -LiteralPath $path -Force
|
||||||
|
if($i.PSIsContainer-ne$directory-or($i.Attributes-band[IO.FileAttributes]::ReparsePoint)){throw 'Regular public report path'}
|
||||||
|
$ancestor=$i.Directory;if($directory){$ancestor=$i.Parent};while($null-ne$ancestor){if($ancestor.Attributes-band[IO.FileAttributes]::ReparsePoint){throw 'Public report reparse ancestry'};$ancestor=$ancestor.Parent}
|
||||||
|
$acl=Get-Acl -LiteralPath $path;$owner=$acl.GetOwner([Security.Principal.SecurityIdentifier]).Value
|
||||||
|
if($owner-cnotin$allowed-and!(!$directory-and$owner-ceq'S-1-5-19')){throw 'Public report owner'}
|
||||||
|
$rules=@($acl.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier]));if(!$rules.Count){throw 'Public report empty DACL'}
|
||||||
|
foreach($r in $rules){if($r.AccessControlType-ne'Allow'-or$r.IdentityReference.Value-cnotin$allowed){throw 'Public report broad DACL'}}
|
||||||
|
if($directory-and!$acl.AreAccessRulesProtected){throw 'Protected public report directory'}
|
||||||
|
return @{owner_sid=$owner;sddl=$acl.Sddl;dacl_checked=$true}
|
||||||
|
}
|
||||||
|
Add-Type -TypeDefinition @'
|
||||||
|
using System; using System.Text; using System.Runtime.InteropServices; using Microsoft.Win32.SafeHandles;
|
||||||
|
public static class RmmPassiveTimeRead {
|
||||||
|
[StructLayout(LayoutKind.Sequential)] public struct Info {public uint Attr,CL,CH,AL,AH,WL,WH,Volume,SizeH,SizeL,Links,IndexH,IndexL;}
|
||||||
|
[DllImport("kernel32.dll",SetLastError=true)] public static extern bool GetFileInformationByHandle(SafeFileHandle h,out Info i);
|
||||||
|
[DllImport("kernel32.dll",SetLastError=true)] static extern IntPtr OpenProcess(uint access,bool inherit,int pid);
|
||||||
|
[DllImport("kernel32.dll",SetLastError=true,CharSet=CharSet.Unicode)] static extern bool QueryFullProcessImageName(IntPtr h,uint flags,StringBuilder text,ref uint size);
|
||||||
|
[DllImport("kernel32.dll",SetLastError=true)] static extern bool GetProcessTimes(IntPtr h,out long creation,out long exit,out long kernel,out long user);
|
||||||
|
[DllImport("kernel32.dll",SetLastError=true)] static extern bool GetExitCodeProcess(IntPtr h,out uint code);
|
||||||
|
[DllImport("kernel32.dll")] static extern bool CloseHandle(IntPtr h);
|
||||||
|
public static string[] Process(int pid){IntPtr h=OpenProcess(0x1000,false,pid);if(h==IntPtr.Zero)throw new InvalidOperationException("QUERY_PROCESS");try{long c,e,k,u;uint code,size=32768;StringBuilder image=new StringBuilder((int)size);if(!GetProcessTimes(h,out c,out e,out k,out u)||!QueryFullProcessImageName(h,0,image,ref size)||!GetExitCodeProcess(h,out code)||code!=259)throw new InvalidOperationException("LIVE_PROCESS");return new string[]{c.ToString(System.Globalization.CultureInfo.InvariantCulture),image.ToString()};}finally{CloseHandle(h);}}
|
||||||
|
}
|
||||||
|
'@
|
||||||
|
function Hash([byte[]]$bytes){$h=[Security.Cryptography.SHA256]::Create();try{return([BitConverter]::ToString($h.ComputeHash($bytes))).Replace('-','').ToLowerInvariant()}finally{$h.Dispose()}}
|
||||||
|
function Runtime($role){
|
||||||
|
$name=$agent;$image='C:\Program Files\RustDiscovery\rmm-agent-windows.exe';$owner='NT AUTHORITY\LocalService';$mode='Auto';$sha=$p.agent_sha256
|
||||||
|
if($role-ceq'helper'){$name=$helper;$image='C:\Program Files\RustDiscovery\rmm-helper-windows.exe';$owner='LocalSystem';$mode='Manual';$sha=$p.helper_sha256}
|
||||||
|
$s=Get-CimInstance Win32_Service -Filter ("Name='"+$name+"'") -OperationTimeoutSec 5
|
||||||
|
if(!$s-or$s.State-cne'Running'-or$s.StartName-cne$owner-or$s.StartMode-cne$mode-or$s.ProcessId-le0-or$s.ServiceType-cne'Own Process'){throw 'Current fixed service role'}
|
||||||
|
$expected='"'+$image+'" --service';if($role-ceq'agent'){$expected+=' --config "C:\ProgramData\RustDiscovery\config.json"'}
|
||||||
|
if($s.PathName-cne$expected){throw 'Current fixed service command'}
|
||||||
|
$native=[RmmPassiveTimeRead]::Process([int]$s.ProcessId)
|
||||||
|
if($native[1]-cne$image-or(Get-FileHash -LiteralPath $image -Algorithm SHA256).Hash.ToLowerInvariant()-cne$sha){throw 'Current fixed service image'}
|
||||||
|
return [ordered]@{pid=[uint32]$s.ProcessId;birth_filetime=$native[0];image=$native[1];sha256=$sha;start_name=$s.StartName;start_mode=$s.StartMode;command=$s.PathName}
|
||||||
|
}
|
||||||
|
function Boot{return (Get-CimInstance Win32_OperatingSystem -Property LastBootUpTime -OperationTimeoutSec 5).LastBootUpTime.ToUniversalTime().Ticks.ToString([Globalization.CultureInfo]::InvariantCulture)}
|
||||||
|
$null=Check 'C:\ProgramData\RustDiscovery' $true;$directory=Check $state $true
|
||||||
|
$boot=Boot;$before=[ordered]@{agent=(Runtime 'agent');helper=(Runtime 'helper')};$reports=[ordered]@{}
|
||||||
|
foreach($name in @('agent-time-sample.json','helper-time-sample.json')){
|
||||||
|
$path=Join-Path $state $name
|
||||||
|
if(!(Test-Path -LiteralPath $path)){$reports[$name]=$null;continue}
|
||||||
|
$stream=[IO.File]::Open($path,[IO.FileMode]::Open,[IO.FileAccess]::Read,[IO.FileShare]::Read)
|
||||||
|
try{
|
||||||
|
$meta=Check $path $false;$info=New-Object RmmPassiveTimeRead+Info
|
||||||
|
if(![RmmPassiveTimeRead]::GetFileInformationByHandle($stream.SafeFileHandle,[ref]$info)-or$info.Links-ne1-or($info.Attr-band0x410)-ne0-or$info.SizeH-ne0-or$info.SizeL-lt1-or$info.SizeL-gt8192-or$stream.Length-ne$info.SizeL){throw 'Single-link bounded public report'}
|
||||||
|
$raw=New-Object byte[] $info.SizeL;$offset=0;while($offset-lt$raw.Length){$count=$stream.Read($raw,$offset,$raw.Length-$offset);if($count-le0){throw 'Complete held public report'};$offset+=$count}
|
||||||
|
$after=New-Object RmmPassiveTimeRead+Info
|
||||||
|
if(![RmmPassiveTimeRead]::GetFileInformationByHandle($stream.SafeFileHandle,[ref]$after)-or$after.IndexH-ne$info.IndexH-or$after.IndexL-ne$info.IndexL-or$after.WH-ne$info.WH-or$after.WL-ne$info.WL-or$after.SizeL-ne$info.SizeL-or$after.Links-ne1){throw 'Stable held public report'}
|
||||||
|
$again=Check $path $false;if($again.sddl-cne$meta.sddl-or$again.owner_sid-cne$meta.owner_sid){throw 'Stable public report security'}
|
||||||
|
$meta['volume']=$info.Volume;$meta['index_high']=$info.IndexH;$meta['index_low']=$info.IndexL;$meta['last_write_filetime']=(([uint64]$info.WH-shl32)-bor$info.WL).ToString([Globalization.CultureInfo]::InvariantCulture)
|
||||||
|
$reports[$name]=@{raw_base64=[Convert]::ToBase64String($raw);sha256=(Hash $raw);metadata=$meta}
|
||||||
|
}finally{$stream.Dispose()}
|
||||||
|
}
|
||||||
|
$after=[ordered]@{agent=(Runtime 'agent');helper=(Runtime 'helper')}
|
||||||
|
$directoryAfter=Check $state $true
|
||||||
|
if(($before|ConvertTo-Json -Depth 8 -Compress)-cne($after|ConvertTo-Json -Depth 8 -Compress)-or(Boot)-cne$boot-or$directory.sddl-cne$directoryAfter.sddl){throw 'Stable process, directory and boot during public read'}
|
||||||
|
@{id=$p.id;read_only=$true;boot_ticks=$boot;runtime=$after;state_metadata=$directory;reports=$reports;observed_at=[DateTime]::UtcNow.ToString('o')}|ConvertTo-Json -Depth 12 -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
|
||||||
@@ -27,70 +27,7 @@ SECOND_NS = 1_000_000_000
|
|||||||
# No report is requested from a service. The only content reads on the guest
|
# No report is requested from a service. The only content reads on the guest
|
||||||
# are these two public JSONs and public executable hashes. CIM/process queries
|
# are these two public JSONs and public executable hashes. CIM/process queries
|
||||||
# obtain current boot/SCM/image/birth metadata without starting another binary.
|
# obtain current boot/SCM/image/birth metadata without starting another binary.
|
||||||
SCRIPT = r'''$ErrorActionPreference='Stop';$p=([Console]::In.ReadLine()|ConvertFrom-Json)
|
SCRIPT = Path(__file__).with_name('Read-PassiveTimeSamples.ps1').read_text(encoding='utf-8')
|
||||||
if((($p.PSObject.Properties.Name|Sort-Object)-join',')-cne'agent_sha256,helper_sha256,id'-or[guid]::ParseExact($p.id,'D').ToString()-cne$p.id-or$p.agent_sha256-cnotmatch'^[0-9a-f]{64}$'-or$p.helper_sha256-cnotmatch'^[0-9a-f]{64}$'){throw 'Fixed public sample read'}
|
|
||||||
$state='C:\ProgramData\RustDiscovery\state';$agent='RmmDiscoveryWindows';$helper='RmmDiscoverySystemHelper'
|
|
||||||
$agentSid=(New-Object Security.Principal.NTAccount('NT SERVICE',$agent)).Translate([Security.Principal.SecurityIdentifier]).Value
|
|
||||||
$allowed=@('S-1-5-18','S-1-5-32-544',$agentSid)
|
|
||||||
function Check($path,[bool]$directory){
|
|
||||||
$i=Get-Item -LiteralPath $path -Force
|
|
||||||
if($i.PSIsContainer-ne$directory-or($i.Attributes-band[IO.FileAttributes]::ReparsePoint)){throw 'Regular public report path'}
|
|
||||||
$ancestor=$i.Directory;if($directory){$ancestor=$i.Parent};while($null-ne$ancestor){if($ancestor.Attributes-band[IO.FileAttributes]::ReparsePoint){throw 'Public report reparse ancestry'};$ancestor=$ancestor.Parent}
|
|
||||||
$acl=Get-Acl -LiteralPath $path;$owner=$acl.GetOwner([Security.Principal.SecurityIdentifier]).Value
|
|
||||||
if($owner-cnotin$allowed-and!(!$directory-and$owner-ceq'S-1-5-19')){throw 'Public report owner'}
|
|
||||||
$rules=@($acl.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier]));if(!$rules.Count){throw 'Public report empty DACL'}
|
|
||||||
foreach($r in $rules){if($r.AccessControlType-ne'Allow'-or$r.IdentityReference.Value-cnotin$allowed){throw 'Public report broad DACL'}}
|
|
||||||
if($directory-and!$acl.AreAccessRulesProtected){throw 'Protected public report directory'}
|
|
||||||
return @{owner_sid=$owner;sddl=$acl.Sddl;dacl_checked=$true}
|
|
||||||
}
|
|
||||||
Add-Type -TypeDefinition @'
|
|
||||||
using System; using System.Text; using System.Runtime.InteropServices; using Microsoft.Win32.SafeHandles;
|
|
||||||
public static class RmmPassiveTimeRead {
|
|
||||||
[StructLayout(LayoutKind.Sequential)] public struct Info {public uint Attr,CL,CH,AL,AH,WL,WH,Volume,SizeH,SizeL,Links,IndexH,IndexL;}
|
|
||||||
[DllImport("kernel32.dll",SetLastError=true)] public static extern bool GetFileInformationByHandle(SafeFileHandle h,out Info i);
|
|
||||||
[DllImport("kernel32.dll",SetLastError=true)] static extern IntPtr OpenProcess(uint access,bool inherit,int pid);
|
|
||||||
[DllImport("kernel32.dll",SetLastError=true,CharSet=CharSet.Unicode)] static extern bool QueryFullProcessImageName(IntPtr h,uint flags,StringBuilder text,ref uint size);
|
|
||||||
[DllImport("kernel32.dll",SetLastError=true)] static extern bool GetProcessTimes(IntPtr h,out long creation,out long exit,out long kernel,out long user);
|
|
||||||
[DllImport("kernel32.dll",SetLastError=true)] static extern bool GetExitCodeProcess(IntPtr h,out uint code);
|
|
||||||
[DllImport("kernel32.dll")] static extern bool CloseHandle(IntPtr h);
|
|
||||||
public static string[] Process(int pid){IntPtr h=OpenProcess(0x1000,false,pid);if(h==IntPtr.Zero)throw new InvalidOperationException("QUERY_PROCESS");try{long c,e,k,u;uint code,size=32768;StringBuilder image=new StringBuilder((int)size);if(!GetProcessTimes(h,out c,out e,out k,out u)||!QueryFullProcessImageName(h,0,image,ref size)||!GetExitCodeProcess(h,out code)||code!=259)throw new InvalidOperationException("LIVE_PROCESS");return new string[]{c.ToString(System.Globalization.CultureInfo.InvariantCulture),image.ToString()};}finally{CloseHandle(h);}}
|
|
||||||
}
|
|
||||||
'@
|
|
||||||
function Hash([byte[]]$bytes){$h=[Security.Cryptography.SHA256]::Create();try{return([BitConverter]::ToString($h.ComputeHash($bytes))).Replace('-','').ToLowerInvariant()}finally{$h.Dispose()}}
|
|
||||||
function Runtime($role){
|
|
||||||
$name=$agent;$image='C:\Program Files\RustDiscovery\rmm-agent-windows.exe';$owner='NT AUTHORITY\LocalService';$mode='Auto';$sha=$p.agent_sha256
|
|
||||||
if($role-ceq'helper'){$name=$helper;$image='C:\Program Files\RustDiscovery\rmm-helper-windows.exe';$owner='LocalSystem';$mode='Manual';$sha=$p.helper_sha256}
|
|
||||||
$s=Get-CimInstance Win32_Service -Filter ("Name='"+$name+"'") -OperationTimeoutSec 5
|
|
||||||
if(!$s-or$s.State-cne'Running'-or$s.StartName-cne$owner-or$s.StartMode-cne$mode-or$s.ProcessId-le0-or$s.ServiceType-cne'Own Process'){throw 'Current fixed service role'}
|
|
||||||
$expected='"'+$image+'" --service';if($role-ceq'agent'){$expected+=' --config "C:\ProgramData\RustDiscovery\config.json"'}
|
|
||||||
if($s.PathName-cne$expected){throw 'Current fixed service command'}
|
|
||||||
$native=[RmmPassiveTimeRead]::Process([int]$s.ProcessId)
|
|
||||||
if($native[1]-cne$image-or(Get-FileHash -LiteralPath $image -Algorithm SHA256).Hash.ToLowerInvariant()-cne$sha){throw 'Current fixed service image'}
|
|
||||||
return [ordered]@{pid=[uint32]$s.ProcessId;birth_filetime=$native[0];image=$native[1];sha256=$sha;start_name=$s.StartName;start_mode=$s.StartMode;command=$s.PathName}
|
|
||||||
}
|
|
||||||
function Boot{return (Get-CimInstance Win32_OperatingSystem -Property LastBootUpTime -OperationTimeoutSec 5).LastBootUpTime.ToUniversalTime().Ticks.ToString([Globalization.CultureInfo]::InvariantCulture)}
|
|
||||||
$null=Check 'C:\ProgramData\RustDiscovery' $true;$directory=Check $state $true
|
|
||||||
$boot=Boot;$before=[ordered]@{agent=(Runtime 'agent');helper=(Runtime 'helper')};$reports=[ordered]@{}
|
|
||||||
foreach($name in @('agent-time-sample.json','helper-time-sample.json')){
|
|
||||||
$path=Join-Path $state $name
|
|
||||||
if(!(Test-Path -LiteralPath $path)){$reports[$name]=$null;continue}
|
|
||||||
$stream=[IO.File]::Open($path,[IO.FileMode]::Open,[IO.FileAccess]::Read,[IO.FileShare]::Read)
|
|
||||||
try{
|
|
||||||
$meta=Check $path $false;$info=New-Object RmmPassiveTimeRead+Info
|
|
||||||
if(![RmmPassiveTimeRead]::GetFileInformationByHandle($stream.SafeFileHandle,[ref]$info)-or$info.Links-ne1-or($info.Attr-band0x410)-ne0-or$info.SizeH-ne0-or$info.SizeL-lt1-or$info.SizeL-gt8192-or$stream.Length-ne$info.SizeL){throw 'Single-link bounded public report'}
|
|
||||||
$raw=New-Object byte[] $info.SizeL;$offset=0;while($offset-lt$raw.Length){$count=$stream.Read($raw,$offset,$raw.Length-$offset);if($count-le0){throw 'Complete held public report'};$offset+=$count}
|
|
||||||
$after=New-Object RmmPassiveTimeRead+Info
|
|
||||||
if(![RmmPassiveTimeRead]::GetFileInformationByHandle($stream.SafeFileHandle,[ref]$after)-or$after.IndexH-ne$info.IndexH-or$after.IndexL-ne$info.IndexL-or$after.WH-ne$info.WH-or$after.WL-ne$info.WL-or$after.SizeL-ne$info.SizeL-or$after.Links-ne1){throw 'Stable held public report'}
|
|
||||||
$again=Check $path $false;if($again.sddl-cne$meta.sddl-or$again.owner_sid-cne$meta.owner_sid){throw 'Stable public report security'}
|
|
||||||
$meta['volume']=$info.Volume;$meta['index_high']=$info.IndexH;$meta['index_low']=$info.IndexL;$meta['last_write_filetime']=(([uint64]$info.WH-shl32)-bor$info.WL).ToString([Globalization.CultureInfo]::InvariantCulture)
|
|
||||||
$reports[$name]=@{raw_base64=[Convert]::ToBase64String($raw);sha256=(Hash $raw);metadata=$meta}
|
|
||||||
}finally{$stream.Dispose()}
|
|
||||||
}
|
|
||||||
$after=[ordered]@{agent=(Runtime 'agent');helper=(Runtime 'helper')}
|
|
||||||
$directoryAfter=Check $state $true
|
|
||||||
if(($before|ConvertTo-Json -Depth 8 -Compress)-cne($after|ConvertTo-Json -Depth 8 -Compress)-or(Boot)-cne$boot-or$directory.sddl-cne$directoryAfter.sddl){throw 'Stable process, directory and boot during public read'}
|
|
||||||
@{id=$p.id;read_only=$true;boot_ticks=$boot;runtime=$after;state_metadata=$directory;reports=$reports;observed_at=[DateTime]::UtcNow.ToString('o')}|ConvertTo-Json -Depth 12 -Compress
|
|
||||||
'''
|
|
||||||
|
|
||||||
|
|
||||||
def need(value, tag):
|
def need(value, tag):
|
||||||
|
|||||||
@@ -32,10 +32,15 @@ RUNTIME_INDEX = 'e49231e72aff7b001189b8507200c6c701f73e47f77c29194116cf1da41ca0c
|
|||||||
COMPONENT_INDEX = '005317e652f50de3e1277be3bc42717318226208015e7c8011e1b73469cc7562'
|
COMPONENT_INDEX = '005317e652f50de3e1277be3bc42717318226208015e7c8011e1b73469cc7562'
|
||||||
ORIGINAL_RESULT = 'd5c4996821911a5bdac5014e9f985c56bbb592b803f2e33411dd28bb986b8eed'
|
ORIGINAL_RESULT = 'd5c4996821911a5bdac5014e9f985c56bbb592b803f2e33411dd28bb986b8eed'
|
||||||
ORIGINAL_INTENT = '374adc97bec41bd798409f7c4f8c7716b085e20d2b6fb64b33f7ab675e6483e2'
|
ORIGINAL_INTENT = '374adc97bec41bd798409f7c4f8c7716b085e20d2b6fb64b33f7ab675e6483e2'
|
||||||
CANDIDATE = ROOT / 'devstate/windows-signed-clock/trusted-os-candidate-link-542cbf43-afb2-4994-b141-06e003e5e2e8'
|
HELPER_CANDIDATE = ROOT / 'devstate/windows-signed-clock/trusted-os-candidate-link-542cbf43-afb2-4994-b141-06e003e5e2e8'
|
||||||
CANDIDATE_RECEIPT = '04ed34e6e850aca77c1fd4677ddb271f7ccd9492a97f5d4e00ead4c1f032f29d'
|
HELPER_RECEIPT = '04ed34e6e850aca77c1fd4677ddb271f7ccd9492a97f5d4e00ead4c1f032f29d'
|
||||||
QUALIFICATION = '96b05fe13f4d459b4b3ef78292beea33827b1ea47293ffb5921c685940e82a4d'
|
HELPER_QUALIFICATION = '96b05fe13f4d459b4b3ef78292beea33827b1ea47293ffb5921c685940e82a4d'
|
||||||
NEW_AGENT = '26dc9d2f6928c5a41050ac9324e041c065e7a9ae52324416f3bb6222c002ae6b'
|
CANDIDATE = MAIN / 'devstate/windows-client/operator-window-20261115/observed-agent-build'
|
||||||
|
# Closed until Root supplies the actual completed native qualification receipt.
|
||||||
|
CANDIDATE_RECEIPT = 'f04024f78c2f11f5c66bbdf9278467f5bcc50da5c2bd7336623851bca42dd446'
|
||||||
|
QUALIFICATION = 'f04024f78c2f11f5c66bbdf9278467f5bcc50da5c2bd7336623851bca42dd446'
|
||||||
|
SOURCE_INPUTS = '11717fab51bd1d6bf103b1821cc1e2a84699f46cac21f2cc614acf4b68381fa4'
|
||||||
|
NEW_AGENT = '0549d9ebea73cff996938f859b92192cc333de194128d7c6859a3f1d2e85893c'
|
||||||
NEW_HELPER = '59675a3cbb3a5d213fc764f38379d6b81baaf9d47a7124470cc2767d4985763e'
|
NEW_HELPER = '59675a3cbb3a5d213fc764f38379d6b81baaf9d47a7124470cc2767d4985763e'
|
||||||
PROBE = '727732fb4b38ac5431a330527bd52a3ab80af8f189ae75a7b48eceb1d4b69cac'
|
PROBE = '727732fb4b38ac5431a330527bd52a3ab80af8f189ae75a7b48eceb1d4b69cac'
|
||||||
SYSTEM_PROBE = '77a344912c61b7ac4a92152ae1b534ca7c36fe6f7dc4675783f20558c3a7f434'
|
SYSTEM_PROBE = '77a344912c61b7ac4a92152ae1b534ca7c36fe6f7dc4675783f20558c3a7f434'
|
||||||
@@ -77,6 +82,15 @@ def controller():
|
|||||||
r'''function CanonicalStateValue($value,[int]$depth=0){
|
r'''function CanonicalStateValue($value,[int]$depth=0){
|
||||||
if($depth-gt40){throw 'Bounded state comparison depth'}
|
if($depth-gt40){throw 'Bounded state comparison depth'}
|
||||||
if($null-eq$value){return $null}
|
if($null-eq$value){return $null}
|
||||||
|
# ETS wrapping does not turn a CLR JSON scalar into a JSON object.
|
||||||
|
$base=$value.PSObject.BaseObject;$culture=[Globalization.CultureInfo]::InvariantCulture
|
||||||
|
if($base-is[string]){return [string]::new($base.ToCharArray())}
|
||||||
|
if($base-is[char]){return [string]::new([char[]]@($base))}
|
||||||
|
if($base-is[bool]){return [bool]::Parse($base.ToString())}
|
||||||
|
if($base-is[sbyte]-or$base-is[int16]-or$base-is[int32]-or$base-is[int64]){return [int64]::Parse($base.ToString($culture),$culture)}
|
||||||
|
if($base-is[byte]-or$base-is[uint16]-or$base-is[uint32]-or$base-is[uint64]){return [uint64]::Parse($base.ToString($culture),$culture)}
|
||||||
|
if($base-is[single]-or$base-is[double]){$number=[double]::Parse($base.ToString('R',$culture),$culture);if([double]::IsNaN($number)-or[double]::IsInfinity($number)){throw 'Finite JSON state number required'};return $number}
|
||||||
|
if($base-is[decimal]){return [decimal]::Parse($base.ToString($culture),$culture)}
|
||||||
if($value-is[Collections.IDictionary]){$result=[ordered]@{};foreach($key in @($value.Keys|Sort-Object -CaseSensitive)){if($key-isnot[string]-or$result.Contains($key)){throw 'Nonunique state object key'};$result[$key]=CanonicalStateValue $value[$key] ($depth+1)};return $result}
|
if($value-is[Collections.IDictionary]){$result=[ordered]@{};foreach($key in @($value.Keys|Sort-Object -CaseSensitive)){if($key-isnot[string]-or$result.Contains($key)){throw 'Nonunique state object key'};$result[$key]=CanonicalStateValue $value[$key] ($depth+1)};return $result}
|
||||||
if($value-is[pscustomobject]){$result=[ordered]@{};foreach($property in @($value.PSObject.Properties|Sort-Object -Property Name -CaseSensitive)){if($property.Name-isnot[string]-or$result.Contains($property.Name)){throw 'Nonunique state object key'};$result[$property.Name]=CanonicalStateValue $property.Value ($depth+1)};return $result}
|
if($value-is[pscustomobject]){$result=[ordered]@{};foreach($property in @($value.PSObject.Properties|Sort-Object -Property Name -CaseSensitive)){if($property.Name-isnot[string]-or$result.Contains($property.Name)){throw 'Nonunique state object key'};$result[$property.Name]=CanonicalStateValue $property.Value ($depth+1)};return $result}
|
||||||
if($value-is[Collections.IEnumerable]-and$value-isnot[string]){$result=New-Object 'Collections.Generic.List[object]';foreach($item in $value){$result.Add((CanonicalStateValue $item ($depth+1)))};return ,$result.ToArray()}
|
if($value-is[Collections.IEnumerable]-and$value-isnot[string]){$result=New-Object 'Collections.Generic.List[object]';foreach($item in $value){$result.Add((CanonicalStateValue $item ($depth+1)))};return ,$result.ToArray()}
|
||||||
@@ -169,6 +183,7 @@ def write(path, raw):
|
|||||||
|
|
||||||
|
|
||||||
def prepare(script):
|
def prepare(script):
|
||||||
|
require(type(CANDIDATE_RECEIPT) is str and len(CANDIDATE_RECEIPT)==64 and QUALIFICATION==CANDIDATE_RECEIPT,'actual final native agent qualification receipt not yet bound')
|
||||||
result, old_intent, settings, pin, policy = original()
|
result, old_intent, settings, pin, policy = original()
|
||||||
grant = prior.cb.contract.protected_json(MAIN/'credentials/windows-dev-access.json')
|
grant = prior.cb.contract.protected_json(MAIN/'credentials/windows-dev-access.json')
|
||||||
expiry = grant.get('expires_at')
|
expiry = grant.get('expires_at')
|
||||||
@@ -177,11 +192,18 @@ def prepare(script):
|
|||||||
deadline = dt.datetime.fromisoformat(expiry.replace('Z','+00:00'))
|
deadline = dt.datetime.fromisoformat(expiry.replace('Z','+00:00'))
|
||||||
require((deadline-dt.datetime.now(dt.timezone.utc)).total_seconds() >= 420,'current authorization window has insufficient total maintenance/readback budget')
|
require((deadline-dt.datetime.now(dt.timezone.utc)).total_seconds() >= 420,'current authorization window has insufficient total maintenance/readback budget')
|
||||||
receipt = protected(CANDIDATE/'receipt.json', CANDIDATE_RECEIPT)
|
receipt = protected(CANDIDATE/'receipt.json', CANDIDATE_RECEIPT)
|
||||||
require(receipt['source_receipt_sha256'] == QUALIFICATION and receipt['input_count'] == 202
|
helper_receipt = protected(HELPER_CANDIDATE/'receipt.json', HELPER_RECEIPT)
|
||||||
and receipt['link_exit'] == 0 and receipt['target_called'] is False
|
require(receipt['source_inputs_sha256']==SOURCE_INPUTS and receipt['source_verified_before_after'] is True
|
||||||
and receipt['artifacts']['rmm-agent-windows.exe']['sha256'] == NEW_AGENT
|
and receipt['link_exit']==0 and receipt['original_helper_sha256']==NEW_HELPER
|
||||||
and receipt['artifacts']['rmm-helper-windows.exe']['sha256'] == NEW_HELPER,
|
and receipt['artifacts']['rmm-agent-windows.exe']['sha256']==NEW_AGENT,
|
||||||
'actual new offline-linked freshness pair, no native qualification inferred')
|
'actual final source-verified locally linked and natively qualified passive agent')
|
||||||
|
require(helper_receipt['source_receipt_sha256']==HELPER_QUALIFICATION and helper_receipt['link_exit']==0
|
||||||
|
and helper_receipt['artifacts']['rmm-helper-windows.exe']['sha256']==NEW_HELPER,
|
||||||
|
'unchanged independently linked original helper')
|
||||||
|
artifact_sources={'rmm-agent-windows.exe':CANDIDATE/'rmm-agent-windows.exe',
|
||||||
|
'rmm-helper-windows.exe':HELPER_CANDIDATE/'rmm-helper-windows.exe'}
|
||||||
|
artifacts={'rmm-agent-windows.exe':receipt['artifacts']['rmm-agent-windows.exe'],
|
||||||
|
'rmm-helper-windows.exe':helper_receipt['artifacts']['rmm-helper-windows.exe']}
|
||||||
ident = str(uuid.uuid4()); folder = STATE/ident; folder.mkdir(mode=0o700,parents=True)
|
ident = str(uuid.uuid4()); folder = STATE/ident; folder.mkdir(mode=0o700,parents=True)
|
||||||
script_sha = raw_sha(script.encode())
|
script_sha = raw_sha(script.encode())
|
||||||
draft = dict(id=ident,access_expiry_utc=expiry,old_agent=OLD_AGENT,old_helper=OLD_HELPER,old_policy=OLD_POLICY,old_pin=OLD_PIN,
|
draft = dict(id=ident,access_expiry_utc=expiry,old_agent=OLD_AGENT,old_helper=OLD_HELPER,old_policy=OLD_POLICY,old_pin=OLD_PIN,
|
||||||
@@ -196,7 +218,7 @@ def prepare(script):
|
|||||||
for name,raw in items.items():
|
for name,raw in items.items():
|
||||||
write(folder/name,raw);files[name]=dict(bytes=len(raw),sha256=raw_sha(raw))
|
write(folder/name,raw);files[name]=dict(bytes=len(raw),sha256=raw_sha(raw))
|
||||||
for name,expected in [('rmm-agent-windows.exe',NEW_AGENT),('rmm-helper-windows.exe',NEW_HELPER)]:
|
for name,expected in [('rmm-agent-windows.exe',NEW_AGENT),('rmm-helper-windows.exe',NEW_HELPER)]:
|
||||||
source=CANDIDATE/name;metadata=source.lstat()
|
source=artifact_sources[name];metadata=source.lstat()
|
||||||
require(metadata.st_nlink == 1 and metadata.st_mode&0o777 == 0o500 and sha(source) == expected,
|
require(metadata.st_nlink == 1 and metadata.st_mode&0o777 == 0o500 and sha(source) == expected,
|
||||||
'exact private linked candidate artifact')
|
'exact private linked candidate artifact')
|
||||||
dependencies=prior.dependencies();dependencies[str(Path(prior.__file__).relative_to(ROOT))]=PRIOR_SOURCE
|
dependencies=prior.dependencies();dependencies[str(Path(prior.__file__).relative_to(ROOT))]=PRIOR_SOURCE
|
||||||
@@ -205,7 +227,8 @@ def prepare(script):
|
|||||||
original_case=OLD_CASE,original_result_sha256=ORIGINAL_RESULT,original_intent_sha256=ORIGINAL_INTENT,
|
original_case=OLD_CASE,original_result_sha256=ORIGINAL_RESULT,original_intent_sha256=ORIGINAL_INTENT,
|
||||||
original_runtime_index_sha256=RUNTIME_INDEX,original_component_index_sha256=COMPONENT_INDEX,
|
original_runtime_index_sha256=RUNTIME_INDEX,original_component_index_sha256=COMPONENT_INDEX,
|
||||||
candidate_receipt_sha256=CANDIDATE_RECEIPT,qualification_sha256=QUALIFICATION,
|
candidate_receipt_sha256=CANDIDATE_RECEIPT,qualification_sha256=QUALIFICATION,
|
||||||
artifacts={name:receipt['artifacts'][name] for name in ('rmm-agent-windows.exe','rmm-helper-windows.exe')},
|
artifacts=artifacts,helper_receipt_sha256=HELPER_RECEIPT,helper_qualification_sha256=HELPER_QUALIFICATION,source_inputs_sha256=SOURCE_INPUTS,
|
||||||
|
linux_result_sha256=receipt['linux_result_sha256'],windows_result_sha256=receipt['windows_result_sha256'],
|
||||||
access_expiry_utc=expiry,access_expiry_source='protected current windows-dev-access.json public expires_at; exact VM account/bootstrap-public match before effects',
|
access_expiry_utc=expiry,access_expiry_source='protected current windows-dev-access.json public expires_at; exact VM account/bootstrap-public match before effects',
|
||||||
server_qualification_bound=True,enter_enabled=True,time_configuration_created=False,
|
server_qualification_bound=True,enter_enabled=True,time_configuration_created=False,
|
||||||
calibration_created=False,target_called=False,main_indices_modified=False,
|
calibration_created=False,target_called=False,main_indices_modified=False,
|
||||||
|
|||||||
@@ -0,0 +1,140 @@
|
|||||||
|
"""Local contract fixtures only; no native qualification or target calls."""
|
||||||
|
import base64
|
||||||
|
import copy
|
||||||
|
import json
|
||||||
|
import tempfile
|
||||||
|
import unittest
|
||||||
|
from pathlib import Path
|
||||||
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
import time_profile_config as t
|
||||||
|
from vm_mvp_acceptance import GuardError
|
||||||
|
|
||||||
|
|
||||||
|
def fixture():
|
||||||
|
binding = {'tenant_id':'11111111-1111-4111-8111-111111111111',
|
||||||
|
'agent_id':'22222222-2222-4222-8222-222222222222',
|
||||||
|
'asset_id':'33333333-3333-4333-8333-333333333333',
|
||||||
|
'enrollment_generation':1,'assignment_version':1,'public_key_hex':'11'*32}
|
||||||
|
public = {'public-binding.json':binding,'qualified-time-public-key.json':{
|
||||||
|
'key_generation':1,'server_instance':'44444444-4444-4444-8444-444444444444',
|
||||||
|
'key_id':'local_fixture_only','public_key_hex':'22'*32},'public-platform.json':{'fixture_only':True}}
|
||||||
|
agent_sid = 'S-1-5-80-1-2-3-4-5';helper_sid = 'S-1-5-80-1-2-3-4-6'
|
||||||
|
result = {'id':'55555555-5555-4555-8555-555555555555','verified':True,'completed':True,
|
||||||
|
'no_jobs':True,'windows_jobs_enabled':False,'helper_effects_enabled':False,
|
||||||
|
'clock_authority_not_proven':True,'private_key_read':False}
|
||||||
|
native = dict(agent_id=binding['agent_id'],asset_id=binding['asset_id'],
|
||||||
|
binary_sha256=t.IMAGES['agent'],helper_sha256=t.IMAGES['system_helper'],
|
||||||
|
policy_sha256='a'*64,pin_sha256='b'*64,files={})
|
||||||
|
for role, service, kernel, label, user, image in (
|
||||||
|
('agent','service','agent_kernel','agent','S-1-5-19','rmm-agent-windows.exe'),
|
||||||
|
('system_helper','helper_service','helper_kernel','helper','S-1-5-18','rmm-helper-windows.exe')):
|
||||||
|
native[service] = dict(state='Running',pid=42,creation_filetime='123',owner_sid=user)
|
||||||
|
native[kernel] = dict(pid=42,creation_filetime='123',owner_sid=user,service_sid=agent_sid if role=='agent' else helper_sid,
|
||||||
|
kernel_handle_bound=True,service_sid_enabled=True,
|
||||||
|
image='C:\\Program Files\\RustDiscovery\\'+image)
|
||||||
|
native['files'][label] = dict(file_id='a'*32,sha256=t.IMAGES[role])
|
||||||
|
result['native'] = native
|
||||||
|
settings = dict(binding=binding,enable_effects=False,agent=dict(service_sid=agent_sid),helper=dict(service_sid=helper_sid))
|
||||||
|
payload = dict(new_agent=t.IMAGES['agent'],new_helper=t.IMAGES['system_helper'],
|
||||||
|
new_policy='a'*64,new_pin='b'*64,qualification_sha256=t.LINK_RECEIPT,
|
||||||
|
manifest_sha256=t.LINK_RECEIPT,settings_base64=base64.b64encode(t.canonical(settings)).decode())
|
||||||
|
return public,result,payload,{'local-service':{'fixture_only':True},'system':{'fixture_only':True}}
|
||||||
|
|
||||||
|
|
||||||
|
class PublicProfileContract(unittest.TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
self.values = fixture()
|
||||||
|
self.pair = patch.object(t,'PAIR_ID',self.values[1]['id']);self.pair.start();self.addCleanup(self.pair.stop)
|
||||||
|
|
||||||
|
def render(self, values=None):
|
||||||
|
return t.produce(*(values or self.values),'c'*64,'d'*64)[0]
|
||||||
|
|
||||||
|
def test_v2_fixture_links_both_exact_roles_without_runtime_success(self):
|
||||||
|
items = self.render();config=json.loads(items['time-attestation.json'])
|
||||||
|
self.assertEqual(config['schema_version'],2)
|
||||||
|
self.assertNotIn('base_error_ns',config)
|
||||||
|
for role in config['trusted_os_active_guest']['qualifications']:
|
||||||
|
raw=items[role['role']+'-qualification.json'];value=json.loads(raw)
|
||||||
|
self.assertEqual(t.sha(raw),role['qualification_sha256'])
|
||||||
|
self.assertFalse(value['signed_runtime_verified']);self.assertFalse(value['physical_calibration_claimed'])
|
||||||
|
self.assertEqual(value['source_sha256'],t.SOURCE_SHA if role['role']=='agent' else t.ORIGINAL_SOURCE_SHA)
|
||||||
|
|
||||||
|
def test_missing_or_not_completed_actual_pair_is_denied(self):
|
||||||
|
for field in ('verified','completed','no_jobs'):
|
||||||
|
values=copy.deepcopy(self.values);values[1].pop(field)
|
||||||
|
with self.assertRaises(GuardError):self.render(values)
|
||||||
|
|
||||||
|
def test_wrong_kernel_birth_account_sid_image_or_fileid_is_denied(self):
|
||||||
|
for field,value in [('creation_filetime','124'),('owner_sid','S-1-5-18'),
|
||||||
|
('service_sid_enabled',False),('kernel_handle_bound',False),
|
||||||
|
('service_sid','S-1-5-18'),('image','C:\\wrong.exe')]:
|
||||||
|
values=copy.deepcopy(self.values);values[1]['native']['agent_kernel'][field]=value
|
||||||
|
with self.assertRaises(GuardError):self.render(values)
|
||||||
|
values=copy.deepcopy(self.values);values[1]['native']['files']['agent']['file_id']='bad'
|
||||||
|
with self.assertRaises(GuardError):self.render(values)
|
||||||
|
|
||||||
|
def test_image_build_policy_and_identity_drift_is_denied(self):
|
||||||
|
for field in ('new_agent','new_helper','new_policy','new_pin','qualification_sha256','manifest_sha256'):
|
||||||
|
values=copy.deepcopy(self.values);values[2][field]='0'*64
|
||||||
|
with self.assertRaises(GuardError):self.render(values)
|
||||||
|
values=copy.deepcopy(self.values);values[0]['public-binding.json']['agent_id']='99999999-9999-4999-8999-999999999999'
|
||||||
|
with self.assertRaises(GuardError):self.render(values)
|
||||||
|
|
||||||
|
def test_no_actual_pair_pins_blocks_before_creating_any_case(self):
|
||||||
|
with tempfile.TemporaryDirectory() as root, patch.object(t,'STATE',Path(root)/'absent'),patch.object(t,'PAIR_ID',None):
|
||||||
|
with self.assertRaises(GuardError):t.prepare()
|
||||||
|
self.assertFalse(t.STATE.exists())
|
||||||
|
|
||||||
|
def test_bounded_nofollow_read_duplicate_json_and_createonce(self):
|
||||||
|
with tempfile.TemporaryDirectory() as root:
|
||||||
|
path=Path(root)/'value.json';t.write(path,b'{"a":1}\n')
|
||||||
|
self.assertEqual(t.read(path)[1],{'a':1})
|
||||||
|
with self.assertRaises(FileExistsError):t.write(path,b'{}')
|
||||||
|
with self.assertRaises(GuardError):t.read(path,'0'*64)
|
||||||
|
link=Path(root)/'link';link.symlink_to(path)
|
||||||
|
with self.assertRaises(OSError):t.read(link)
|
||||||
|
bad=Path(root)/'duplicate.json';t.write(bad,b'{"a":1,"a":2}')
|
||||||
|
with self.assertRaises(GuardError):t.read(bad)
|
||||||
|
with self.assertRaises(GuardError):t.read(path,limit=1)
|
||||||
|
|
||||||
|
|
||||||
|
class OriginalPartialDiagnosticContract(unittest.TestCase):
|
||||||
|
def test_closed_reader_cannot_publish_or_repair(self):
|
||||||
|
source=t.partial_reader()
|
||||||
|
self.assertIn('time-profile-'+t.PARTIAL_ID,source)
|
||||||
|
self.assertIn('time-attestation.candidate.json',source)
|
||||||
|
self.assertIn('old_move_hresult_unknown=$true',source)
|
||||||
|
for forbidden in ('[IO.File]::Move','Set-Acl','WriteBytes','WriteNew','Start-Service','Stop-Service','CreateDirectory'):
|
||||||
|
self.assertNotIn(forbidden,source)
|
||||||
|
|
||||||
|
def test_diagnostic_executes_bound_reader_without_legacy_load_or_target_success(self):
|
||||||
|
import datetime as dt
|
||||||
|
from unittest.mock import Mock
|
||||||
|
manifest={'id':t.PARTIAL_ID,'generator_sha256':t.PARTIAL_GENERATOR_SHA,
|
||||||
|
'script_sha256':t.PARTIAL_SCRIPT_SHA,'request':{'config_sha256':t.PARTIAL_CONFIG_SHA}}
|
||||||
|
result={'id':t.PARTIAL_ID,'read_only':True,'retry_authorized':False,
|
||||||
|
'installation_verified':False,'clock_runtime_qualified':False}
|
||||||
|
access=Mock();access.powershell.return_value=result
|
||||||
|
expiry=(dt.datetime.now(dt.timezone.utc)+dt.timedelta(hours=1)).isoformat()
|
||||||
|
with tempfile.TemporaryDirectory() as root,patch.object(t,'ROOT',Path(root)), \
|
||||||
|
patch.object(t,'read',side_effect=[(b'original',manifest),(b'staged',None)]), \
|
||||||
|
patch.object(t,'load_case',side_effect=AssertionError('original case must not adopt new generator')), \
|
||||||
|
patch.object(t.raw_capture,'CaptureAccess',return_value=access), \
|
||||||
|
patch.object(t.prior.cb.contract,'protected_json',return_value={'expires_at':expiry}):
|
||||||
|
t.diagnose_partial()
|
||||||
|
call=access.powershell.call_args
|
||||||
|
executed=base64.b64decode(call.args[1]['source_base64'])
|
||||||
|
self.assertIn(t.sha(executed),call.args[0])
|
||||||
|
cases=list((Path(root)/'devstate/windows-time-profile-diagnostics').iterdir())
|
||||||
|
self.assertEqual(len(cases),1)
|
||||||
|
intent=json.loads((cases[0]/'intent.json').read_bytes())
|
||||||
|
receipt=json.loads((cases[0]/'receipt.json').read_bytes())
|
||||||
|
self.assertEqual(intent['reader_sha256'],t.sha(executed))
|
||||||
|
self.assertEqual(receipt['reader_sha256'],t.sha(executed))
|
||||||
|
self.assertTrue(receipt['old_move_hresult_unknown'])
|
||||||
|
self.assertEqual((cases[0]/'reader.ps1').read_bytes(),executed)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
unittest.main()
|
||||||
@@ -0,0 +1,613 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""First public V2 time pin for one actual qualified Windows product pair.
|
||||||
|
|
||||||
|
prepare/guards are local only. No target operation happens on import.
|
||||||
|
Missing native product-role/readback evidence blocks preparation; diagnostics
|
||||||
|
are never relabelled as calibrated product clocks or signed runtime success.
|
||||||
|
"""
|
||||||
|
import argparse
|
||||||
|
import base64
|
||||||
|
import copy
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
import re
|
||||||
|
import stat
|
||||||
|
import uuid
|
||||||
|
|
||||||
|
import system_pipe_upgrade as prior
|
||||||
|
import signed_clock_capture_acceptance as raw_capture
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parents[2]
|
||||||
|
CLOCK = ROOT.parent / 'rust-discovery-signed-clock'
|
||||||
|
MAIN = ROOT.parent / 'rust-discovery'
|
||||||
|
STATE = ROOT / 'devstate/windows-time-profile-config'
|
||||||
|
PUBLIC = CLOCK / 'devstate/windows-time-profile-public-preparation/c3077acf-12da-410e-9f55-e75a1cd0a75f'
|
||||||
|
PAIR_ID = '4887940a-4c9c-4807-aaf2-6fbc94faad46'
|
||||||
|
PAIR_RESULT_SHA = '2898a72b4b0d84159cc11d80765cbfa4206faf7038d0e860429c8b1a57538ee2'
|
||||||
|
PAIR_INTENT_SHA = '40e9cd557225504429b51dcecd4322b32d7f0973bcbb8e2a2e52516917907b85'
|
||||||
|
PAIR_READBACK_SHA = '63e453fb915cadee028407a6aeaa8c7d209ae88ed12a6d4d4307d4fd25e4c539'
|
||||||
|
PAIR_ROOT = CLOCK / 'devstate/windows-signed-clock/passive-pair-upgrade'
|
||||||
|
SOURCE_CASE = CLOCK / 'devstate/windows-signed-clock/trusted-os-qualification-c4679433-b632-4d6e-8668-f0f2fb54a542'
|
||||||
|
LINK_CASE = MAIN / 'devstate/windows-client/operator-window-20261115/observed-agent-build'
|
||||||
|
ORIGINAL_SOURCE_SHA = 'd8594c1eba2c2cc5d5fde4a462b2110aa2e7e64081452b742c4ed81a2cfb477d'
|
||||||
|
SOURCE_SHA = '342494c4f9e7eca439c059745591a8e907026da20f56b223fcb0eb0707aa6d82'
|
||||||
|
SOURCE_RECEIPT = '96b05fe13f4d459b4b3ef78292beea33827b1ea47293ffb5921c685940e82a4d'
|
||||||
|
LINK_RECEIPT = 'f04024f78c2f11f5c66bbdf9278467f5bcc50da5c2bd7336623851bca42dd446'
|
||||||
|
LINK_INPUTS = '11717fab51bd1d6bf103b1821cc1e2a84699f46cac21f2cc614acf4b68381fa4'
|
||||||
|
ORIGINAL_LINK_RECEIPT = '04ed34e6e850aca77c1fd4677ddb271f7ccd9492a97f5d4e00ead4c1f032f29d'
|
||||||
|
NATIVE_RESULTS = {
|
||||||
|
'linux': ('84592e7a-6554-4a7d-a73f-2bdebdb9e9a8', '150954b0ab290d8e9fbda5616f6df071168efd88a9f1d8b48b2bd8a5f5de7c20'),
|
||||||
|
'windows': ('44059065-c17e-43c3-86aa-d4d131454ccb', 'b235bdd444c112ff91cbc5f160d39d69ef79fb419b9b2ab7ccdcec06009d5c6b')}
|
||||||
|
ORIGINAL_IMAGES = {'agent': '26dc9d2f6928c5a41050ac9324e041c065e7a9ae52324416f3bb6222c002ae6b',
|
||||||
|
'system_helper': '59675a3cbb3a5d213fc764f38379d6b81baaf9d47a7124470cc2767d4985763e'}
|
||||||
|
IMAGES = {'agent': '0549d9ebea73cff996938f859b92192cc333de194128d7c6859a3f1d2e85893c',
|
||||||
|
'system_helper': ORIGINAL_IMAGES['system_helper']}
|
||||||
|
ASSUMPTION = 'active_guest_no_pause_save_restore_snapshot_migration_host_suspend'
|
||||||
|
PUBLIC_SHAS = {'qualified-time-public-key.json': 'c31d31d2d61f881d04f55f704abbbf98f4822650c016f39e39d4d2318bc3f6e2',
|
||||||
|
'public-platform.json': '94ae865e0e3449f6901f4d5f593aacbd5829b06340e296e19e6f0159a157cba3',
|
||||||
|
'public-binding.json': '9239ee9f4142735867e77451478bf309fbf449d730a0ede6c958bc8018830dde',
|
||||||
|
'input-provenance.json': '1c0db66cd0692024f68bddd71949692d274380a86e4b880fea0756479ceb5d0c',
|
||||||
|
'receipt.json': '97e4db147f31f3cff134d2bc596d7d73ea5330b8b5a87971f215bb03a9751391'}
|
||||||
|
RAW = CLOCK / 'devstate/windows-signed-clock-capture-completion/ccba6d8f-c58f-4d2d-a51c-1efb3bfbabdf'
|
||||||
|
RAW_RECEIPTS = {'local-service': '10dd411be265d018489bf9477747ce2d5846ac04128f583425aec4b3c9d5252b',
|
||||||
|
'system': '7409309ea6d586566373f570d6950c60ce2597cf939f261e6d2ea4def004a22f'}
|
||||||
|
require = prior.require
|
||||||
|
|
||||||
|
def sha(raw):
|
||||||
|
return hashlib.sha256(raw).hexdigest()
|
||||||
|
|
||||||
|
def canonical(value):
|
||||||
|
return (json.dumps(value, sort_keys=True, separators=(',', ':'), ensure_ascii=False) + '\n').encode()
|
||||||
|
|
||||||
|
def strict_object(items):
|
||||||
|
value = {}
|
||||||
|
for key, item in items:
|
||||||
|
require(key not in value, 'duplicate public JSON field')
|
||||||
|
value[key] = item
|
||||||
|
return value
|
||||||
|
|
||||||
|
def read(path, expected=None, limit=2*1024*1024, decode=True, public=False):
|
||||||
|
fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)
|
||||||
|
with os.fdopen(fd, 'rb') as stream:
|
||||||
|
before = os.fstat(stream.fileno())
|
||||||
|
modes = (0o600,0o644,0o664) if public and expected is not None else (0o600,)
|
||||||
|
require(stat.S_ISREG(before.st_mode) and before.st_uid == os.getuid() and before.st_nlink == 1
|
||||||
|
and stat.S_IMODE(before.st_mode) in modes and 0 < before.st_size <= limit,
|
||||||
|
'private bounded actual public evidence')
|
||||||
|
raw = stream.read(limit + 1); after = os.fstat(stream.fileno())
|
||||||
|
require((before.st_dev,before.st_ino,before.st_size,before.st_mtime_ns,before.st_ctime_ns)
|
||||||
|
== (after.st_dev,after.st_ino,after.st_size,after.st_mtime_ns,after.st_ctime_ns)
|
||||||
|
and len(raw) == before.st_size and (expected is None or sha(raw) == expected),
|
||||||
|
'unchanged independently pinned public evidence')
|
||||||
|
return raw, json.loads(raw, object_pairs_hook=strict_object) if decode else None
|
||||||
|
|
||||||
|
def write(path, raw):
|
||||||
|
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600)
|
||||||
|
with os.fdopen(fd,'wb') as stream:
|
||||||
|
stream.write(raw); stream.flush(); os.fsync(stream.fileno())
|
||||||
|
fd = os.open(path.parent,os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
|
||||||
|
try: os.fsync(fd)
|
||||||
|
finally: os.close(fd)
|
||||||
|
|
||||||
|
def public_inputs():
|
||||||
|
values = {name: read(PUBLIC/name,digest)[1] for name,digest in PUBLIC_SHAS.items()}
|
||||||
|
pin, platform, binding = (values[n] for n in ('qualified-time-public-key.json','public-platform.json','public-binding.json'))
|
||||||
|
require(set(pin) == {'algorithm','schema_version','key_generation','key_id','server_instance','public_key_hex'}
|
||||||
|
and pin['algorithm'] == 'Ed25519' and pin['schema_version'] == 1
|
||||||
|
and type(pin['key_generation']) is int and pin['key_generation'] > 0
|
||||||
|
and re.fullmatch('[A-Za-z0-9_-]{1,64}',pin['key_id'])
|
||||||
|
and re.fullmatch('[a-f0-9]{64}',pin['public_key_hex']), 'actual separate public time key')
|
||||||
|
require(str(uuid.UUID(pin['server_instance'])) == pin['server_instance'] and uuid.UUID(pin['server_instance']).int > 0,
|
||||||
|
'actual server instance')
|
||||||
|
require(set(binding) == {'tenant_id','asset_id','agent_id','enrollment_generation','assignment_version','public_key_hex'}
|
||||||
|
and all(str(uuid.UUID(binding[k])) == binding[k] and uuid.UUID(binding[k]).int > 0 for k in ('tenant_id','asset_id','agent_id'))
|
||||||
|
and type(binding['enrollment_generation']) is int and binding['enrollment_generation'] == 1
|
||||||
|
and type(binding['assignment_version']) is int and binding['assignment_version'] == 1
|
||||||
|
and bytes.fromhex(pin['public_key_hex']) != bytes.fromhex(binding['public_key_hex']), 'unchanged actual identity and distinct time/job keys')
|
||||||
|
require(platform['schema'] == 1 and platform['hypervisor'] == 'kvm' and platform['state'] == 'running'
|
||||||
|
and platform['domain_uuid'] == '1ec0d319-24bc-4953-a6b2-52b85449be07'
|
||||||
|
and platform['has_genid'] is False
|
||||||
|
and {'name':'hypervclock','present':'yes'} in platform['timers'], 'actual selectively observed active KVM platform')
|
||||||
|
provenance = values['input-provenance.json']
|
||||||
|
require(provenance['candidate_images'] == ORIGINAL_IMAGES and provenance['operating_assumption'] == ASSUMPTION
|
||||||
|
and provenance['platform'] == 'kvm_qemu_hypervclock' and provenance['roles_qualified'] is False
|
||||||
|
and provenance['time_config_created'] is False and provenance['target_called'] is False,
|
||||||
|
'original incomplete public preparation stays incomplete and unchanged')
|
||||||
|
return values
|
||||||
|
|
||||||
|
def source_inputs():
|
||||||
|
_, source = read(SOURCE_CASE/'receipt.json',SOURCE_RECEIPT)
|
||||||
|
read(SOURCE_CASE/'source/crates/agent-windows/src/signed_clock.rs',ORIGINAL_SOURCE_SHA,decode=False)
|
||||||
|
_, link = read(LINK_CASE/'receipt.json',LINK_RECEIPT)
|
||||||
|
_, inputs = read(LINK_CASE/'source-inputs.json',LINK_INPUTS)
|
||||||
|
require(len(inputs) == 202 and len({item['path'] for item in inputs}) == 202,
|
||||||
|
'exact updated source input set')
|
||||||
|
clock = [item for item in inputs if item['path'] == 'crates/agent-windows/src/signed_clock.rs']
|
||||||
|
require(len(clock) == 1 and clock[0]['sha256'] == SOURCE_SHA, 'same qualified V2 clock source')
|
||||||
|
read(LINK_CASE/'source/crates/agent-windows/src/signed_clock.rs',SOURCE_SHA,decode=False)
|
||||||
|
original_path = CLOCK/'devstate/windows-signed-clock/trusted-os-candidate-link-542cbf43-afb2-4994-b141-06e003e5e2e8'
|
||||||
|
_, original = read(original_path/'receipt.json',ORIGINAL_LINK_RECEIPT)
|
||||||
|
require(source['source_sha256'] == original['source_sha256'] == ORIGINAL_SOURCE_SHA
|
||||||
|
and source['input_count'] == link['input_count'] == 202
|
||||||
|
and source['inputs_sha256'] == original['inputs_sha256']
|
||||||
|
and original['source_receipt_sha256'] == SOURCE_RECEIPT
|
||||||
|
and link['source_receipt_sha256'] == ORIGINAL_LINK_RECEIPT
|
||||||
|
and link['source_inputs_sha256'] == LINK_INPUTS
|
||||||
|
and source['inputs_verified_before_after'] is True and link['source_verified_before_after'] is True
|
||||||
|
and source['checks']['linux_signed_clock_guards']['passed'] == 8
|
||||||
|
and link['link_exit'] == 0 and link['original_helper_sha256'] == IMAGES['system_helper']
|
||||||
|
and link['target'] == 'x86_64-pc-windows-gnu' and link['patches'] == ['656102b','cc82124'],
|
||||||
|
'actual fixed V2 source and linked product pair, no runtime success inferred')
|
||||||
|
for artifact, role in ((link['artifacts']['rmm-agent-windows.exe'],'agent'),
|
||||||
|
(original['artifacts']['rmm-helper-windows.exe'],'system_helper')):
|
||||||
|
require(artifact['sha256'] == IMAGES[role] and artifact['machine'] == 'PE_AMD64', 'same actual linked role image')
|
||||||
|
for platform in ('linux','windows'):
|
||||||
|
case, binary_sha = NATIVE_RESULTS[platform]
|
||||||
|
_, result = read(LINK_CASE.parent/case/'result.json',link[platform+'_result_sha256'],public=True)
|
||||||
|
output = result['stdout'] if platform == 'linux' else '\n'.join(result['lines'])
|
||||||
|
names = re.findall(r'^test (signed_clock::tests::[a-z_]+) \.\.\. ok$', output, re.MULTILINE)
|
||||||
|
expected = set(source['checks']['linux_signed_clock_guards']['selected']) | {
|
||||||
|
'signed_clock::tests::passive_sampling_requires_a_profile_and_uses_heartbeat_cadence'}
|
||||||
|
require(result['test_binary_sha256'] == binary_sha
|
||||||
|
and result['exit' if platform=='linux' else 'exit_code'] == 0
|
||||||
|
and len(names) == 9 and set(names) == expected
|
||||||
|
and '9 passed; 0 failed; 0 ignored' in output, 'same-source actual native nine guards')
|
||||||
|
return source,link
|
||||||
|
|
||||||
|
def raw_inputs():
|
||||||
|
require(sha(Path(raw_capture.__file__).read_bytes()) ==
|
||||||
|
'dd6c575a119751429448e40e6f306cf79efa3a86c49bf2cd32a7783937177770',
|
||||||
|
'unchanged original raw-role decoder')
|
||||||
|
records = {}
|
||||||
|
for role, digest in RAW_RECEIPTS.items():
|
||||||
|
_, receipt = read(RAW/('start-'+role+'-receipt.json'),digest)
|
||||||
|
raw_link = receipt['raw_reply']
|
||||||
|
require(raw_link['filename'] == 'start-'+role+'-reply.json', 'fixed original raw role namespace')
|
||||||
|
_, reply = read(RAW/raw_link['filename'],raw_link['sha256'])
|
||||||
|
require(receipt['calibrated'] is False and receipt['clock_authority'] is False
|
||||||
|
and reply['calibrated'] is False and reply['clock_authority'] is False,
|
||||||
|
'raw probe is never a product calibration')
|
||||||
|
for key in ('native_witness','server_witness','preservation'):
|
||||||
|
item = receipt[key]
|
||||||
|
require(Path(item['filename']).name == item['filename'], 'fixed sibling evidence leaf')
|
||||||
|
read(RAW/item['filename'],item['sha256'])
|
||||||
|
raw_capture.validate_role(role,reply['roles'][role],'efd17b43-7e04-49a7-9bd4-862d13365eec')
|
||||||
|
records[role] = {'receipt_sha256':digest,'probe_image_sha256':raw_capture.EXE_SHA,
|
||||||
|
'raw_report_sha256':reply['roles'][role]['raw_report_sha256']}
|
||||||
|
return records
|
||||||
|
|
||||||
|
def validate_pair(result, intent):
|
||||||
|
require(result.get('id') == PAIR_ID and result.get('verified') is True and result.get('completed') is True
|
||||||
|
and result.get('no_jobs') is True and result.get('windows_jobs_enabled') is False
|
||||||
|
and result.get('helper_effects_enabled') is False and result.get('clock_authority_not_proven') is True
|
||||||
|
and result.get('private_key_read') is False, 'actual completed passive pair required; no missing or dummy result')
|
||||||
|
payload = intent.get('payload',intent)
|
||||||
|
require(payload['new_agent'] == IMAGES['agent'] and payload['new_helper'] == IMAGES['system_helper']
|
||||||
|
and payload['qualification_sha256'] == LINK_RECEIPT and payload['manifest_sha256'] == LINK_RECEIPT,
|
||||||
|
'actual exact V2 pair source chain')
|
||||||
|
native = result['native']
|
||||||
|
require(native['binary_sha256'] == IMAGES['agent'] and native['helper_sha256'] == IMAGES['system_helper']
|
||||||
|
and native['policy_sha256'] == payload['new_policy'] and native['pin_sha256'] == payload['new_pin'], 'complete native image/pin pair')
|
||||||
|
qualifications = []
|
||||||
|
for role,service,kernel,label,user in [('agent','service','agent_kernel','agent','S-1-5-19'),('system_helper','helper_service','helper_kernel','helper','S-1-5-18')]:
|
||||||
|
s,k,f = native[service],native[kernel],native['files'][label]
|
||||||
|
require(s['state'] == 'Running' and type(s['pid']) is int and s['pid'] > 0
|
||||||
|
and k['pid'] == s['pid'] and k['creation_filetime'] == s['creation_filetime']
|
||||||
|
and k['owner_sid'] == s['owner_sid'] == user and k['service_sid_enabled'] is True
|
||||||
|
and k['kernel_handle_bound'] is True and f['sha256'] == IMAGES[role]
|
||||||
|
and k['image'] == ('C:\\Program Files\\RustDiscovery\\rmm-agent-windows.exe' if role=='agent'
|
||||||
|
else 'C:\\Program Files\\RustDiscovery\\rmm-helper-windows.exe')
|
||||||
|
and re.fullmatch(r'S-1-5-80-(?:[0-9]+-){4}[0-9]+',k['service_sid'])
|
||||||
|
and re.fullmatch('[0-9]+',k['creation_filetime']) and re.fullmatch('[a-f0-9]{32}',f['file_id']),
|
||||||
|
'actual SCM/kernel account, enabled service SID, birth and image FileID')
|
||||||
|
qualifications.append({'role':role,'binary_sha256':IMAGES[role],'service':copy.deepcopy(s),
|
||||||
|
'kernel':copy.deepcopy(k),'image_file':copy.deepcopy(f)})
|
||||||
|
return native,payload,qualifications
|
||||||
|
|
||||||
|
def produce(public, pair_result, pair_intent, raw, result_sha, intent_sha):
|
||||||
|
native,payload,roles = validate_pair(pair_result,pair_intent)
|
||||||
|
binding = public['public-binding.json']; pin=public['qualified-time-public-key.json']
|
||||||
|
require(native['agent_id'] == binding['agent_id'] and native['asset_id'] == binding['asset_id'], 'same actual device binding')
|
||||||
|
settings = json.loads(base64.b64decode(payload['settings_base64'],validate=True),object_pairs_hook=strict_object)
|
||||||
|
require(settings['binding'] == binding and settings['enable_effects'] is False
|
||||||
|
and settings['agent']['service_sid'] == roles[0]['kernel']['service_sid']
|
||||||
|
and settings['helper']['service_sid'] == roles[1]['kernel']['service_sid']
|
||||||
|
and settings['agent']['service_sid'] != settings['helper']['service_sid'], 'actual reciprocal settings and distinct service roles')
|
||||||
|
platform = {'profile':'rmm.windows.trusted-os.platform-provenance.v1','operating_assumption':ASSUMPTION,
|
||||||
|
'platform':'kvm_qemu_hypervclock','public_platform_sha256':PUBLIC_SHAS['public-platform.json'],
|
||||||
|
'original_public_preparation_sha256':PUBLIC_SHAS['input-provenance.json'],
|
||||||
|
'source_sha256':SOURCE_SHA,'source_receipt_sha256':SOURCE_RECEIPT,
|
||||||
|
'product_pair_receipt_sha256':LINK_RECEIPT,'pair_result_sha256':result_sha,
|
||||||
|
'pair_intent_sha256':intent_sha,'independent_pair_readback_sha256':PAIR_READBACK_SHA,
|
||||||
|
'independent_physical_calibration_claimed':False}
|
||||||
|
items={'platform-provenance.json':canonical(platform),'public-platform.json':canonical(public['public-platform.json'])}
|
||||||
|
# The original platform file is separately retained below using its actual
|
||||||
|
# bytes; this canonical descriptive copy is never mislabelled as its hash.
|
||||||
|
references=[]
|
||||||
|
for role in roles:
|
||||||
|
role.update(profile='rmm.windows.trusted-os.product-role-prerequisite.v1',pair_case_id=PAIR_ID,
|
||||||
|
pair_result_sha256=result_sha,pair_intent_sha256=intent_sha,
|
||||||
|
independent_pair_readback_sha256=PAIR_READBACK_SHA,
|
||||||
|
source_sha256=SOURCE_SHA if role['role']=='agent' else ORIGINAL_SOURCE_SHA,
|
||||||
|
original_source_receipt_sha256=SOURCE_RECEIPT,product_pair_receipt_sha256=LINK_RECEIPT,
|
||||||
|
platform_provenance_sha256=sha(items['platform-provenance.json']),
|
||||||
|
raw_capture=raw['local-service' if role['role']=='agent' else 'system'],
|
||||||
|
signed_runtime_verified=False,physical_calibration_claimed=False)
|
||||||
|
name=role['role']+'-qualification.json';items[name]=canonical(role)
|
||||||
|
references.append({'role':role['role'],'binary_sha256':role['binary_sha256'],'qualification_sha256':sha(items[name])})
|
||||||
|
value={'schema_version':2,'key_generation':pin['key_generation'],'server_instance':pin['server_instance'],
|
||||||
|
'binding':binding,'public_keys_hex':{pin['key_id']:pin['public_key_hex']},
|
||||||
|
'trusted_os_active_guest':{'operating_assumption':ASSUMPTION,'platform':'kvm_qemu_hypervclock',
|
||||||
|
'platform_provenance_sha256':sha(items['platform-provenance.json']),'qualifications':references}}
|
||||||
|
items['time-attestation.json']=canonical(value)
|
||||||
|
require(len(items['time-attestation.json'])<=16384, 'real bounded public V2 configuration')
|
||||||
|
return items,native,payload
|
||||||
|
|
||||||
|
# Controller and transport are defined below; no remote action on import.
|
||||||
|
|
||||||
|
HEADER = r'''
|
||||||
|
$ErrorActionPreference='Stop';$request=$global:RmmTimeProfilePayload
|
||||||
|
if(!$request-or$request.action-isnot[string]-or$request.action-cnotin@('install','read')-or[guid]::ParseExact($request.id,'D').ToString()-cne$request.id-or$request.profile-cne'rmm.windows.initial-public-time-profile.v2'){throw 'Exact initial time-profile operation'}
|
||||||
|
$p=$request.pair_payload
|
||||||
|
$boot='C:\ProgramData\RustDiscoveryBootstrap';$folder=Join-Path $boot ('time-profile-'+$request.id)
|
||||||
|
$agentRoot='C:\ProgramData\RustDiscovery';$agentState=Join-Path $agentRoot 'state';$helperRoot='C:\ProgramData\RustDiscoverySystem';$helperState=Join-Path $helperRoot 'state'
|
||||||
|
$config=Join-Path $agentRoot 'config.json';$settings=Join-Path $helperRoot 'helper.json';$pin=Join-Path $helperRoot 'agent-pin.json'
|
||||||
|
$agentBinary='C:\Program Files\RustDiscovery\rmm-agent-windows.exe';$helperBinary='C:\Program Files\RustDiscovery\rmm-helper-windows.exe'
|
||||||
|
$agentName='RmmDiscoveryWindows';$helperName='RmmDiscoverySystemHelper';$sys='S-1-5-18';$admin='S-1-5-32-544'
|
||||||
|
$agentSid=(New-Object Security.Principal.NTAccount('NT SERVICE',$agentName)).Translate([Security.Principal.SecurityIdentifier]).Value
|
||||||
|
$helperSid=(New-Object Security.Principal.NTAccount('NT SERVICE',$helperName)).Translate([Security.Principal.SecurityIdentifier]).Value
|
||||||
|
$target=Join-Path $helperRoot 'time-attestation.json';$active=Join-Path $boot 'time-profile-initial-active.json'
|
||||||
|
'''
|
||||||
|
|
||||||
|
BODY = r'''
|
||||||
|
function ReadAcl($path,[bool]$directory){
|
||||||
|
Check $path $directory;$acl=Get-Acl -LiteralPath $path
|
||||||
|
if($acl.GetOwner([Security.Principal.SecurityIdentifier]).Value-cnotin@($sys,$admin)){throw 'Public pin owner must remain SYSTEM/Administrators'}
|
||||||
|
$seen=@{};foreach($rule in $acl.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier])){
|
||||||
|
$id=$rule.IdentityReference.Value;$rights=[int64]$rule.FileSystemRights
|
||||||
|
if($rule.AccessControlType-cne'Allow'-or$id-cnotin@($sys,$admin,$agentSid,$helperSid)-or($id-cnotin@($sys,$admin)-and($rights-band(-bnot 0x1200a9))-ne0)){throw 'Only exact native reader rights, no foreign writer'}
|
||||||
|
$seen[$id]=$true
|
||||||
|
};foreach($id in @($sys,$admin)){if(!$seen[$id]){throw 'Privileged public-pin role missing'}}
|
||||||
|
return $acl
|
||||||
|
}
|
||||||
|
function GrantRootReaders{
|
||||||
|
$acl=ReadAcl $helperRoot $true
|
||||||
|
foreach($id in @($agentSid,$helperSid)){
|
||||||
|
$present=$false;foreach($rule in $acl.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier])){if($rule.IdentityReference.Value-ceq$id-and([int64]$rule.FileSystemRights-band0x1200a9)-eq0x1200a9){$present=$true}}
|
||||||
|
if(!$present){$acl.AddAccessRule((New-Object Security.AccessControl.FileSystemAccessRule((New-Object Security.Principal.SecurityIdentifier($id)),[Security.AccessControl.FileSystemRights]0x1200a9,'None','None','Allow')))}
|
||||||
|
}
|
||||||
|
# This-folder-only ACEs: do not expose state/PKI/ledger/intent descendants.
|
||||||
|
Set-Acl -LiteralPath $helperRoot -AclObject $acl;$null=ReadAcl $helperRoot $true
|
||||||
|
}
|
||||||
|
function SetPinAcl($path){
|
||||||
|
$acl=New-Object Security.AccessControl.FileSecurity;$acl.SetSecurityDescriptorSddlForm(('O:BAG:BAD:P(A;;FA;;;SY)(A;;FA;;;BA)(A;;0x1200a9;;;'+$agentSid+')(A;;0x1200a9;;;'+$helperSid+')'))
|
||||||
|
Set-Acl -LiteralPath $path -AclObject $acl;$null=ReadAcl $path $false
|
||||||
|
}
|
||||||
|
function NewPrivateCase{
|
||||||
|
[RmmTimeProfileCase]::CreatePrivateOnce($folder);CheckControl $folder $true
|
||||||
|
}
|
||||||
|
function FileVolume($path){
|
||||||
|
$handle=[RmmPipeNative]::CreateFile($path,0x80,7,[IntPtr]::Zero,3,0x2200000,[IntPtr]::Zero)
|
||||||
|
try{if($handle.IsInvalid){throw 'Protected directory identity handle'};$id=New-Object RmmPipeNative+FileId;if(![RmmPipeNative]::GetFileInformationByHandleEx($handle,18,[ref]$id,24)){throw 'Protected directory volume'};return $id.Volume.ToString([Globalization.CultureInfo]::InvariantCulture)}finally{$handle.Dispose()}
|
||||||
|
}
|
||||||
|
function SameLive($before,$after){
|
||||||
|
Preserved $before $after $false
|
||||||
|
foreach($field in @('files','service','helper_service','agent_kernel','helper_kernel')){if(!(JsonEqual $before.$field $after.$field)){throw 'Same original data/PKI/FileIDs/services/process generations required'}}
|
||||||
|
}
|
||||||
|
function ConfigBytes{
|
||||||
|
$bytes=[Convert]::FromBase64String($request.config_base64)
|
||||||
|
if($bytes.Length-gt16384-or$bytes.Length-lt1-or(BytesHash $bytes)-cne$request.config_sha256){throw 'Fixed complete public config bytes'}
|
||||||
|
$value=[Text.Encoding]::UTF8.GetString($bytes)|ConvertFrom-Json
|
||||||
|
if($value.schema_version-ne2-or$value.key_generation-ne$request.key_generation-or$value.server_instance-cne$request.server_instance-or!(JsonEqual $value.binding $request.binding)-or$value.trusted_os_active_guest.operating_assumption-cne'active_guest_no_pause_save_restore_snapshot_migration_host_suspend'-or$value.trusted_os_active_guest.platform-cne'kvm_qemu_hypervclock'-or@($value.trusted_os_active_guest.qualifications).Count-ne2-or$value.trusted_os_active_guest.qualifications[0].role-cne'agent'-or$value.trusted_os_active_guest.qualifications[0].binary_sha256-cne$p.new_agent-or$value.trusted_os_active_guest.qualifications[1].role-cne'system_helper'-or$value.trusted_os_active_guest.qualifications[1].binary_sha256-cne$p.new_helper){throw 'Closed real schema2/profile/role binding'}
|
||||||
|
return ,$bytes
|
||||||
|
}
|
||||||
|
CheckControl $boot $true
|
||||||
|
if($PSCommandPath-cne(Join-Path (Join-Path $boot $request.script_sha256) 'InstallPublicTimeProfile.ps1')-or(Hash $PSCommandPath)-cne$request.script_sha256){throw 'Exact reviewed public-pin controller'}
|
||||||
|
CheckControl $PSCommandPath $false
|
||||||
|
$expected=$request.expected_native
|
||||||
|
$before=ActualState $true;SameLive $expected $before
|
||||||
|
if($before.agent_kernel.service_sid-cne$agentSid-or$before.helper_kernel.service_sid-cne$helperSid){throw 'Same actual qualified service SIDs'}
|
||||||
|
$null=ReadAcl $helperRoot $true
|
||||||
|
if($request.action-ceq'read'){
|
||||||
|
$records=[ordered]@{};if(Test-Path -LiteralPath $folder){CheckControl $folder $true;foreach($name in @('intent.json','directory-acl-intent.json','directory-acl-done.json','publish-intent.json','result.json')){$path=Join-Path $folder $name;$records[$name]=$null;if(Test-Path -LiteralPath $path){CheckControl $path $false;if((Get-Item -LiteralPath $path -Force).Length-gt2097152){throw 'Bounded original public-pin history'};$records[$name]=Get-Content -LiteralPath $path -Raw|ConvertFrom-Json}}}
|
||||||
|
if($records['intent.json']){foreach($field in $request.PSObject.Properties.Name){if($field-cne'action'-and!(JsonEqual $records['intent.json'].request.$field $request.$field)){throw 'Same original public-pin intent only'}}}
|
||||||
|
$activeRecord=$null;if(Test-Path -LiteralPath $active){CheckControl $active $false;if((Get-Item -LiteralPath $active -Force).Length-gt8192){throw 'Bounded public-pin active marker'};$activeRecord=Get-Content -LiteralPath $active -Raw|ConvertFrom-Json;if($activeRecord.id-cne$request.id-or$activeRecord.config_sha256-cne$request.config_sha256-or$activeRecord.script_sha256-cne$request.script_sha256){throw 'Another initial public-pin case; no adoption'}}
|
||||||
|
$current=$null;if(Test-Path -LiteralPath $target){$null=ReadAcl $target $false;$current=FileIdentity $target;if($current.sha256-cne$request.config_sha256){throw 'Unexpected existing configuration; no adoption'}}
|
||||||
|
@{id=$request.id;read_only=$true;records=$records;active=$activeRecord;configuration=$current;native=$before;root_sddl=(Get-Acl -LiteralPath $helperRoot).Sddl;clock_runtime_qualified=$false;no_jobs=$true}|ConvertTo-Json -Depth 50 -Compress;exit0
|
||||||
|
}
|
||||||
|
if($request.action-cne'install'){throw 'Exact install action only'}
|
||||||
|
if((Test-Path -LiteralPath $target)-or(Test-Path -LiteralPath $folder)-or(Test-Path -LiteralPath $active)){throw 'Existing initial time profile or partial attempt: original read only'}
|
||||||
|
$bytes=ConfigBytes
|
||||||
|
$rootSddl=(Get-Acl -LiteralPath $helperRoot).Sddl
|
||||||
|
$heldAgent=[RmmPipeNative]::Open([int]$before.service.pid);$heldHelper=[RmmPipeNative]::Open([int]$before.helper_service.pid)
|
||||||
|
try{
|
||||||
|
$null=Kernel 'agent' $before.service $heldAgent;$null=Kernel 'helper' $before.helper_service $heldHelper
|
||||||
|
$installNotBefore=[DateTime]::UtcNow.ToString('o')
|
||||||
|
NewPrivateCase
|
||||||
|
WriteNew (Join-Path $folder 'intent.json') @{id=$request.id;request=$request;before=$before;original_root_sddl=$rootSddl;install_not_before=$installNotBefore;no_retry=$true}
|
||||||
|
WriteNew $active @{id=$request.id;config_sha256=$request.config_sha256;script_sha256=$request.script_sha256;no_retry=$true}
|
||||||
|
foreach($item in $request.provenance.PSObject.Properties){if($item.Name-cnotmatch'^(platform-provenance|public-platform|original-public-platform|agent-qualification|system_helper-qualification|qualified-time-public-key|public-binding)\.json$'){throw 'Closed public provenance leaves'};$raw=[Convert]::FromBase64String($item.Value);if($raw.Length-gt65536){throw 'Bounded public provenance'};WriteBytes (Join-Path $folder $item.Name) $raw}
|
||||||
|
$staged=Join-Path $folder 'time-attestation.candidate.json';WriteBytes $staged $bytes;SetPinAcl $staged
|
||||||
|
if((FileIdentity $staged).sha256-cne$request.config_sha256-or(FileVolume $folder)-cne(FileVolume $helperRoot)){throw 'Verified complete same-volume public pin'}
|
||||||
|
SameLive $before (ActualState $true)
|
||||||
|
if((Get-Acl -LiteralPath $helperRoot).Sddl-cne$rootSddl){throw 'Immediate directory ACL CAS'}
|
||||||
|
WriteNew (Join-Path $folder 'directory-acl-intent.json') @{old_sddl=$rootSddl;readers=@($agentSid,$helperSid);this_folder_only=$true}
|
||||||
|
GrantRootReaders
|
||||||
|
WriteNew (Join-Path $folder 'directory-acl-done.json') @{sddl=(Get-Acl -LiteralPath $helperRoot).Sddl}
|
||||||
|
SameLive $before (ActualState $true)
|
||||||
|
$null=Kernel 'agent' $before.service $heldAgent;$null=Kernel 'helper' $before.helper_service $heldHelper
|
||||||
|
if(Test-Path -LiteralPath $target){throw 'Target appeared before no-overwrite publication'}
|
||||||
|
$stagedId=FileIdentity $staged
|
||||||
|
WriteNew (Join-Path $folder 'publish-intent.json') @{config_sha256=$request.config_sha256;staged=$stagedId;create_once=$true}
|
||||||
|
[IO.File]::Move($staged,$target)
|
||||||
|
$null=ReadAcl $target $false;$published=FileIdentity $target
|
||||||
|
if(!(JsonEqual $published $stagedId)){throw 'Exact same file identity/hash/ACL after publication'}
|
||||||
|
$after=ActualState $true;SameLive $before $after
|
||||||
|
$null=Kernel 'agent' $before.service $heldAgent;$null=Kernel 'helper' $before.helper_service $heldHelper
|
||||||
|
$result=@{id=$request.id;installed=$true;install_not_before=$installNotBefore;configuration=$published;native=$after;original_root_sddl=$rootSddl;root_sddl=(Get-Acl -LiteralPath $helperRoot).Sddl;no_jobs=$true;clock_runtime_qualified=$false;services_changed=$false;private_key_read=$false}
|
||||||
|
WriteNew (Join-Path $folder 'result.json') $result;$result|ConvertTo-Json -Depth 50 -Compress
|
||||||
|
}finally{$heldAgent.Dispose();$heldHelper.Dispose()}
|
||||||
|
'''.replace('exit0','exit 0')
|
||||||
|
|
||||||
|
|
||||||
|
def controller():
|
||||||
|
"""Reuse only existing read-only witnesses, not any old phase/repair code."""
|
||||||
|
require(sha(Path(prior.__file__).read_bytes()) == 'e466576673a0e5c332cfc1613ae88a62f5b526015ced76b1d22473e292a995e0'
|
||||||
|
and sha(Path(prior.u.__file__).read_bytes()) == 'f8dc1c8fbc064e253b1fbe130fb628afef58cf45c2bafb6837d6716125b42d38', 'unchanged reviewed original readonly witness sources')
|
||||||
|
source = prior.u.SCRIPT
|
||||||
|
# Every selected section ends at the next named function. No StartOnce,
|
||||||
|
# StopPinned, Swap, Backup, original phase, or old payload dispatch is copied.
|
||||||
|
names = ['Check','BytesHash','Hash','AclHash','CheckControl','Service','Probe','Diagnostic','RawAgentProbe','EmptyIntentStore','State','Preserved']
|
||||||
|
functions=[]
|
||||||
|
for name in names:
|
||||||
|
start=source.index('function '+name+'(') if 'function '+name+'(' in source else source.index('function '+name+'{')
|
||||||
|
end=source.find('\nfunction ',start+1)
|
||||||
|
require(end>start, 'closed existing readonly witness boundary')
|
||||||
|
functions.append(source[start:end])
|
||||||
|
# File writers are new, closed by the controller's fixed namespace only.
|
||||||
|
writers=r'''function WriteBytes($path,[byte[]]$bytes){$file=[IO.File]::Open($path,[IO.FileMode]::CreateNew,[IO.FileAccess]::Write,[IO.FileShare]::Read);try{$file.Write($bytes,0,$bytes.Length);$file.Flush($true)}finally{$file.Dispose()}}
|
||||||
|
function WriteNew($path,$value){WriteBytes $path ([Text.Encoding]::UTF8.GetBytes(($value|ConvertTo-Json -Depth 50 -Compress)))}'''
|
||||||
|
return HEADER+'\n'+STRUCTURAL+'\n'+'\n'.join(functions)+'\n'+prior.NATIVE+'\n'+CASE_NATIVE+'\n'+writers+'\n'+BODY
|
||||||
|
|
||||||
|
# Same reviewed structural comparison as e6debe5; member order is not identity.
|
||||||
|
STRUCTURAL = r'''function CanonicalStateValue($value,[int]$depth=0){
|
||||||
|
if($depth-gt40){throw 'Bounded state comparison depth'}
|
||||||
|
if($null-eq$value){return $null}
|
||||||
|
# ETS wrapping does not turn a CLR JSON scalar into a JSON object.
|
||||||
|
$base=$value.PSObject.BaseObject;$culture=[Globalization.CultureInfo]::InvariantCulture
|
||||||
|
if($base-is[string]){return [string]::new($base.ToCharArray())}
|
||||||
|
if($base-is[char]){return [string]::new([char[]]@($base))}
|
||||||
|
if($base-is[bool]){return [bool]::Parse($base.ToString())}
|
||||||
|
if($base-is[sbyte]-or$base-is[int16]-or$base-is[int32]-or$base-is[int64]){return [int64]::Parse($base.ToString($culture),$culture)}
|
||||||
|
if($base-is[byte]-or$base-is[uint16]-or$base-is[uint32]-or$base-is[uint64]){return [uint64]::Parse($base.ToString($culture),$culture)}
|
||||||
|
if($base-is[single]-or$base-is[double]){$number=[double]::Parse($base.ToString('R',$culture),$culture);if([double]::IsNaN($number)-or[double]::IsInfinity($number)){throw 'Finite JSON state number required'};return $number}
|
||||||
|
if($base-is[decimal]){return [decimal]::Parse($base.ToString($culture),$culture)}
|
||||||
|
if($value-is[Collections.IDictionary]){$result=[ordered]@{};foreach($key in @($value.Keys|Sort-Object -CaseSensitive)){if($key-isnot[string]-or$result.Contains($key)){throw 'Nonunique state object key'};$result[$key]=CanonicalStateValue $value[$key] ($depth+1)};return $result}
|
||||||
|
if($value-is[pscustomobject]){$result=[ordered]@{};foreach($property in @($value.PSObject.Properties|Sort-Object -Property Name -CaseSensitive)){if($property.Name-isnot[string]-or$result.Contains($property.Name)){throw 'Nonunique state object key'};$result[$property.Name]=CanonicalStateValue $property.Value ($depth+1)};return $result}
|
||||||
|
if($value-is[Collections.IEnumerable]-and$value-isnot[string]){$result=New-Object 'Collections.Generic.List[object]';foreach($item in $value){$result.Add((CanonicalStateValue $item ($depth+1)))};return ,$result.ToArray()}
|
||||||
|
return $value
|
||||||
|
}
|
||||||
|
function JsonEqual($a,$b){return((ConvertTo-Json -InputObject (CanonicalStateValue $a) -Depth 40 -Compress)-ceq(ConvertTo-Json -InputObject (CanonicalStateValue $b) -Depth 40 -Compress))}'''
|
||||||
|
CASE_NATIVE = r'''Add-Type -TypeDefinition @'
|
||||||
|
using System;
|
||||||
|
using System.ComponentModel;
|
||||||
|
using System.Runtime.InteropServices;
|
||||||
|
using System.Security.AccessControl;
|
||||||
|
public static class RmmTimeProfileCase {
|
||||||
|
[StructLayout(LayoutKind.Sequential)] struct Attributes {public int Length;public IntPtr Descriptor;public int Inherit;}
|
||||||
|
[DllImport("kernel32.dll",EntryPoint="CreateDirectoryW",ExactSpelling=true,CharSet=CharSet.Unicode,SetLastError=true)]
|
||||||
|
[return:MarshalAs(UnmanagedType.Bool)] static extern bool CreateDirectory(string path,ref Attributes security);
|
||||||
|
public static void CreatePrivateOnce(string path){
|
||||||
|
RawSecurityDescriptor sd=new RawSecurityDescriptor("O:BAG:BAD:P(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)");
|
||||||
|
byte[] raw=new byte[sd.BinaryLength];sd.GetBinaryForm(raw,0);GCHandle pin=GCHandle.Alloc(raw,GCHandleType.Pinned);
|
||||||
|
try{Attributes attributes=new Attributes{Length=Marshal.SizeOf(typeof(Attributes)),Descriptor=pin.AddrOfPinnedObject(),Inherit=0};
|
||||||
|
if(!CreateDirectory(path,ref attributes))throw new Win32Exception(Marshal.GetLastWin32Error(),"TIME_PROFILE_PRIVATE_CREATE_ONCE");
|
||||||
|
}finally{pin.Free();}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
'@'''
|
||||||
|
|
||||||
|
LAUNCH = r'''$ErrorActionPreference='Stop';$request=([Console]::In.ReadLine()|ConvertFrom-Json)
|
||||||
|
if(!$request-or$request.action-isnot[string]-or$request.action-cnotin@('install','read')-or$request.script_sha256-cnotmatch'^[a-f0-9]{64}$'){throw 'Fixed public-pin launch'}
|
||||||
|
$script=Join-Path (Join-Path 'C:\ProgramData\RustDiscoveryBootstrap' $request.script_sha256) 'InstallPublicTimeProfile.ps1'
|
||||||
|
$item=Get-Item -LiteralPath $script -Force;if($item.PSIsContainer-or($item.Attributes-band[IO.FileAttributes]::ReparsePoint)-or$item.Length-gt100000-or(Get-FileHash -LiteralPath $script -Algorithm SHA256).Hash.ToLowerInvariant()-cne$request.script_sha256){throw 'Exact bounded immutable time-pin script'}
|
||||||
|
$acl=Get-Acl -LiteralPath $script;if($acl.GetOwner([Security.Principal.SecurityIdentifier]).Value-cnotin@('S-1-5-18','S-1-5-32-544')){throw 'Private launch owner'}
|
||||||
|
foreach($rule in $acl.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier])){if($rule.AccessControlType-cne'Allow'-or$rule.IdentityReference.Value-cnotin@('S-1-5-18','S-1-5-32-544')){throw 'Private launch DACL'}}
|
||||||
|
$global:RmmTimeProfilePayload=$request;& $script
|
||||||
|
'''
|
||||||
|
|
||||||
|
def guards():
|
||||||
|
script=controller()
|
||||||
|
for forbidden in ('Stop-Service','Start-Service','Restart-Computer','Set-Date','AdjustTokenPrivileges',
|
||||||
|
'function Swap','function Backup','function StartOnce','CreateService(', 'DeleteService('):
|
||||||
|
require(forbidden not in script, 'no service/clock/job effect imported')
|
||||||
|
require("$request.action-cnotin@('install','read')" in script
|
||||||
|
and "if($request.action-cne'install')" in script
|
||||||
|
and '[IO.File]::Move($staged,$target)' in script
|
||||||
|
and script.index("'publish-intent.json') @") < script.index('[IO.File]::Move($staged,$target)')
|
||||||
|
and 'This-folder-only ACEs' in script and '0x1200a9' in script
|
||||||
|
and 'CreatePrivateOnce' in script, 'closed create-once public-pin effects')
|
||||||
|
return script
|
||||||
|
|
||||||
|
def prepare():
|
||||||
|
# All prerequisites are checked BEFORE creating a local installation case.
|
||||||
|
# Source/link/role constants deliberately remain unset until actual evidence.
|
||||||
|
require(PAIR_ID is not None and str(uuid.UUID(PAIR_ID)) == PAIR_ID
|
||||||
|
and all(isinstance(value,str) and re.fullmatch('[a-f0-9]{64}',value)
|
||||||
|
for value in (PAIR_RESULT_SHA,PAIR_INTENT_SHA,PAIR_READBACK_SHA)),
|
||||||
|
'actual completed new pair and independently pinned role readback required')
|
||||||
|
public=public_inputs(); source_inputs(); raw=raw_inputs()
|
||||||
|
pair=PAIR_ROOT/PAIR_ID
|
||||||
|
result_raw,result=read(pair/'result.json',PAIR_RESULT_SHA)
|
||||||
|
intent_path=pair/'intent.json'
|
||||||
|
if not intent_path.exists(): intent_path=pair/'bound-payload.json'
|
||||||
|
intent_raw,intent=read(intent_path,PAIR_INTENT_SHA)
|
||||||
|
_, independent=read(pair/'independent-readback.json',PAIR_READBACK_SHA)
|
||||||
|
require(independent.get('id') == PAIR_ID and independent.get('completed') is True
|
||||||
|
and independent.get('read_only') is True and independent.get('no_job') is True
|
||||||
|
and independent.get('no_service_action') is True
|
||||||
|
and result['independent_readback_sha256'] == PAIR_READBACK_SHA
|
||||||
|
and result['intent_sha256'] == PAIR_INTENT_SHA
|
||||||
|
and all(independent['native'][key] == result['native'][key]
|
||||||
|
for key in ('files','service','helper_service','agent_kernel','helper_kernel')),
|
||||||
|
'original independent same-generation role and file readback')
|
||||||
|
items,native,payload=produce(public,result,intent,raw,sha(result_raw),sha(intent_raw))
|
||||||
|
items['original-public-platform.json']=read(PUBLIC/'public-platform.json',PUBLIC_SHAS['public-platform.json'])[0]
|
||||||
|
for name in ('qualified-time-public-key.json','public-binding.json'):
|
||||||
|
items[name]=read(PUBLIC/name,PUBLIC_SHAS[name])[0]
|
||||||
|
script=guards().encode(); ident=str(uuid.uuid4()); script_sha=sha(script)
|
||||||
|
keep=('old_agent','old_helper','new_agent','new_helper','old_policy','old_pin','new_policy','new_pin',
|
||||||
|
'config_sha256','probe_sha256','system_probe_sha256','intent_leaves')
|
||||||
|
public_payload={key:payload[key] for key in keep}
|
||||||
|
request={'profile':'rmm.windows.initial-public-time-profile.v2','id':ident,'action':'read',
|
||||||
|
'script_sha256':script_sha,'config_sha256':sha(items['time-attestation.json']),
|
||||||
|
'config_base64':base64.b64encode(items.pop('time-attestation.json')).decode(),
|
||||||
|
'pair_payload':public_payload,'expected_native':native,'binding':public['public-binding.json'],
|
||||||
|
'key_generation':public['qualified-time-public-key.json']['key_generation'],
|
||||||
|
'server_instance':public['qualified-time-public-key.json']['server_instance'],
|
||||||
|
'provenance':{name:base64.b64encode(value).decode() for name,value in items.items()}}
|
||||||
|
# Existing transport passes the payload on stdin, not on the command line.
|
||||||
|
require(len(canonical(request))<=128*1024,'bounded public bootstrap request')
|
||||||
|
STATE.mkdir(mode=0o700,parents=True,exist_ok=True);ident_dir=STATE/ident;ident_dir.mkdir(mode=0o700)
|
||||||
|
write(ident_dir/'InstallPublicTimeProfile.ps1',script)
|
||||||
|
write(ident_dir/'time-attestation.json',base64.b64decode(request['config_base64'],validate=True))
|
||||||
|
for name,value in items.items(): write(ident_dir/name,value)
|
||||||
|
manifest={'profile':request['profile'],'id':ident,'generator_sha256':sha(Path(__file__).read_bytes()),
|
||||||
|
'script_sha256':script_sha,'request':request,'pair_result_sha256':sha(result_raw),
|
||||||
|
'pair_intent_sha256':sha(intent_raw),'source_receipt_sha256':SOURCE_RECEIPT,
|
||||||
|
'product_link_receipt_sha256':LINK_RECEIPT,'target_called':False,'clock_runtime_qualified':False,
|
||||||
|
'files':{name:{'sha256':sha(value),'bytes':len(value)} for name,value in items.items()}}
|
||||||
|
write(ident_dir/'manifest.json',canonical(manifest))
|
||||||
|
print(json.dumps({'id':ident,'prepared_locally':True,'target_called':False,
|
||||||
|
'config_sha256':request['config_sha256'],'manifest_sha256':sha(canonical(manifest))}))
|
||||||
|
|
||||||
|
def load_case(ident):
|
||||||
|
require(str(uuid.UUID(ident))==ident and uuid.UUID(ident).version==4,'canonical original time-pin case')
|
||||||
|
folder=STATE/ident; _,manifest=read(folder/'manifest.json')
|
||||||
|
require(manifest['id']==ident and manifest['generator_sha256']==sha(Path(__file__).read_bytes())
|
||||||
|
and manifest['script_sha256']==sha(guards().encode()),'same exact reviewed operator and case')
|
||||||
|
require(read(folder/'InstallPublicTimeProfile.ps1',decode=False)[0]==guards().encode(), 'same controller bytes')
|
||||||
|
request=manifest['request'];read(folder/'time-attestation.json',request['config_sha256'])
|
||||||
|
for name,item in manifest['files'].items(): read(folder/name,item['sha256'])
|
||||||
|
return folder,manifest
|
||||||
|
|
||||||
|
def target(action,ident):
|
||||||
|
"""Only Root invokes these explicit phases after independent review."""
|
||||||
|
folder,manifest=load_case(ident)
|
||||||
|
require(action in ('stage','install','read'),'closed public-pin phase')
|
||||||
|
if action!='read':
|
||||||
|
write(folder/(action+'-attempt.json'),canonical({'id':ident,'action':action,'once':True,'lost_reply_read_original_case_only':True}))
|
||||||
|
access=raw_capture.CaptureAccess(MAIN)
|
||||||
|
if action=='stage':
|
||||||
|
path=folder/'InstallPublicTimeProfile.ps1';digest=manifest['script_sha256']
|
||||||
|
stage=prior.u.transport.PREPARE_SCRIPT.replace('TransportAcceptance.ps1',path.name)
|
||||||
|
observed=access.powershell(stage,{'sha256':digest})
|
||||||
|
if not observed['already_uploaded']:
|
||||||
|
import subprocess
|
||||||
|
config=prior.cb.contract.protected_json(MAIN/'credentials/windows-dev-access.json')
|
||||||
|
prefix=config['ssh_prefix'];args=['sftp']+[p for p in prefix[1:-1] if p!='-T']+['-b','-',prefix[-1]]
|
||||||
|
remote='/C:/ProgramData/RustDiscoveryBootstrap/'+digest+'/'+path.name
|
||||||
|
reply=subprocess.run(args,input=('put '+json.dumps(str(path.resolve()))+' '+json.dumps(remote)+'\n').encode(),capture_output=True,timeout=60)
|
||||||
|
write(folder/'stage-transport.json',canonical({'returncode':reply.returncode,'stdout_b64':base64.b64encode(reply.stdout).decode(),'stderr_b64':base64.b64encode(reply.stderr).decode()}))
|
||||||
|
require(reply.returncode==0,'once-only fixed script transfer; lost reply read only')
|
||||||
|
observed=access.powershell(stage,{'sha256':digest})
|
||||||
|
require(observed['already_uploaded'] is True and observed['sha256']==digest,'exact staged public-pin controller')
|
||||||
|
result={'id':ident,'staged':True,'script_sha256':digest,'configuration_installed':False}
|
||||||
|
else:
|
||||||
|
request=copy.deepcopy(manifest['request']);request['action']=action
|
||||||
|
result=access.powershell(LAUNCH,request,timeout=120)
|
||||||
|
require(result['id']==ident and result.get('no_jobs') is True and result.get('clock_runtime_qualified') is False,
|
||||||
|
'same native public-pin result, never clock readiness')
|
||||||
|
output=folder/((action+'-'+str(uuid.uuid4()) if action=='read' else action)+'-reply.json')
|
||||||
|
write(output,canonical(result))
|
||||||
|
print(json.dumps({'id':ident,'action':action,'reply_sha256':sha(canonical(result)),'clock_runtime_qualified':False}))
|
||||||
|
|
||||||
|
# Dedicated read-only path for the already attempted original case. It never
|
||||||
|
# passes through load_case(): changing the generator must not rewrite or adopt
|
||||||
|
# the original staged controller/intent hash binding.
|
||||||
|
PARTIAL_ID = 'ad9fd154-b2be-4f5d-9e17-65abb721ceaf'
|
||||||
|
PARTIAL_MANIFEST_SHA = '0c9a3ffeed490757f7bd8c63d7e2ec28156212945094621f511e20679ce0b3b0'
|
||||||
|
PARTIAL_GENERATOR_SHA = 'a8d55b60d413c1d68f568c173e6ea32727cef8645e61eb772d24f98e22b0b10a'
|
||||||
|
PARTIAL_SCRIPT_SHA = 'd8b4fd4fd9ca5310cc1591ce3c2ccae5bd72a2ade43b21a8187cfdfb960b3427'
|
||||||
|
PARTIAL_CONFIG_SHA = '2b4a8a7080770304b80e2a665fa5f5ee1ebbd9182e7c80b184e75b114575b42b'
|
||||||
|
PARTIAL_CASE = ROOT.parent/'rust-discovery-agent-updater'/'devstate/windows-time-profile-config'/PARTIAL_ID
|
||||||
|
|
||||||
|
|
||||||
|
def partial_reader():
|
||||||
|
"""Fixed file/ACL/marker observation only; no service or publication code."""
|
||||||
|
require(sha(Path(prior.__file__).read_bytes())=='e466576673a0e5c332cfc1613ae88a62f5b526015ced76b1d22473e292a995e0'
|
||||||
|
and sha(Path(prior.u.__file__).read_bytes())=='f8dc1c8fbc064e253b1fbe130fb628afef58cf45c2bafb6837d6716125b42d38',
|
||||||
|
'exact original metadata-only primitive sources')
|
||||||
|
source = prior.u.SCRIPT
|
||||||
|
functions = []
|
||||||
|
for name in ('Check','BytesHash','Hash','AclHash','CheckControl'):
|
||||||
|
start=source.index('function '+name+'(');end=source.find('\nfunction ',start+1)
|
||||||
|
require(end>start,'closed original read-only function');functions.append(source[start:end])
|
||||||
|
native=prior.NATIVE.split('function FileIdentity(',1)[0]
|
||||||
|
identity='function FileIdentity('+prior.NATIVE.split('function FileIdentity(',1)[1].split('function Kernel(',1)[0]
|
||||||
|
header=r'''$ErrorActionPreference='Stop';$inputRecord=$global:RmmPartialReaderInput
|
||||||
|
if((($inputRecord.PSObject.Properties.Name|Sort-Object)-join',')-cne'kind'-or$inputRecord.kind-cne'original-public-time-profile-ad9-readonly'){throw 'Fixed original partial profile observation'}
|
||||||
|
$sys='S-1-5-18';$admin='S-1-5-32-544';$agentSid=(New-Object Security.Principal.NTAccount('NT SERVICE','RmmDiscoveryWindows')).Translate([Security.Principal.SecurityIdentifier]).Value;$helperSid=(New-Object Security.Principal.NTAccount('NT SERVICE','RmmDiscoverySystemHelper')).Translate([Security.Principal.SecurityIdentifier]).Value
|
||||||
|
$folder='C:\ProgramData\RustDiscoveryBootstrap\time-profile-ad9fd154-b2be-4f5d-9e17-65abb721ceaf';$root='C:\ProgramData\RustDiscoverySystem';$active='C:\ProgramData\RustDiscoveryBootstrap\time-profile-initial-active.json'
|
||||||
|
'''
|
||||||
|
body=r'''function ErrorNumber($errorRecord){$ex=$errorRecord.Exception.GetBaseException();$h=[int64]$ex.HResult-band0xffffffffL;$win32=$null;if(($h-band0xffff0000L)-eq0x80070000L){$win32=$h-band0xffffL};return @{exception_type=$ex.GetType().FullName;hresult_hex=('0x{0:x8}'-f$h);win32_code=$win32}}
|
||||||
|
function ObservePublic($path){
|
||||||
|
if(!(Test-Path -LiteralPath $path)){return @{present=$false}}
|
||||||
|
try{Check $path $false;$item=Get-Item -LiteralPath $path -Force;if($item.Length-gt16384){throw 'Bounded public profile only'};$identity=FileIdentity $path;return @{present=$true;identity=$identity;attributes=[int64]$item.Attributes;creation_filetime=$item.CreationTimeUtc.ToFileTimeUtc().ToString();last_write_filetime=$item.LastWriteTimeUtc.ToFileTimeUtc().ToString();expected_hash=($identity.sha256-ceq'2b4a8a7080770304b80e2a665fa5f5ee1ebbd9182e7c80b184e75b114575b42b')}}catch{return @{present=$true;observation_failed=$true;error=(ErrorNumber $_)}}
|
||||||
|
}
|
||||||
|
CheckControl $folder $true;Check $root $true
|
||||||
|
$records=[ordered]@{};foreach($name in @('intent.json','directory-acl-intent.json','directory-acl-done.json','publish-intent.json','publish-failure.json','result.json')){$path=Join-Path $folder $name;if(!(Test-Path -LiteralPath $path)){$records[$name]=@{present=$false};continue};CheckControl $path $false;$item=Get-Item -LiteralPath $path -Force;if($item.Length-gt2097152){throw 'Bounded original marker'};$value=Get-Content -LiteralPath $path -Raw|ConvertFrom-Json
|
||||||
|
$record=@{present=$true;sha256=(Hash $path);bytes=$item.Length}
|
||||||
|
if($name-ceq'intent.json'){if($value.id-cne'ad9fd154-b2be-4f5d-9e17-65abb721ceaf'-or$value.request.config_sha256-cne'2b4a8a7080770304b80e2a665fa5f5ee1ebbd9182e7c80b184e75b114575b42b'-or$value.request.script_sha256-cne'd8b4fd4fd9ca5310cc1591ce3c2ccae5bd72a2ade43b21a8187cfdfb960b3427'){throw 'Original intent binding'};$record.install_not_before=$value.install_not_before;$record.no_retry=$value.no_retry}
|
||||||
|
if($name-ceq'publish-intent.json'){if($value.config_sha256-cne'2b4a8a7080770304b80e2a665fa5f5ee1ebbd9182e7c80b184e75b114575b42b'-or$value.create_once-ne$true){throw 'Original publication binding'};$record.staged=$value.staged}
|
||||||
|
if($name-ceq'directory-acl-intent.json'){$record.old_sddl=$value.old_sddl};if($name-ceq'directory-acl-done.json'){$record.sddl=$value.sddl}
|
||||||
|
if($name-ceq'publish-failure.json'){$record.failure=@{exception_type=$value.exception_type;hresult_hex=$value.hresult_hex;win32_code=$value.win32_code}}
|
||||||
|
$records[$name]=$record
|
||||||
|
}
|
||||||
|
$activeRecord=@{present=$false};if(Test-Path -LiteralPath $active){CheckControl $active $false;if((Get-Item -LiteralPath $active).Length-gt8192){throw 'Bounded active original marker'};$a=Get-Content -LiteralPath $active -Raw|ConvertFrom-Json;if($a.id-cne'ad9fd154-b2be-4f5d-9e17-65abb721ceaf'-or$a.config_sha256-cne'2b4a8a7080770304b80e2a665fa5f5ee1ebbd9182e7c80b184e75b114575b42b'-or$a.script_sha256-cne'd8b4fd4fd9ca5310cc1591ce3c2ccae5bd72a2ade43b21a8187cfdfb960b3427'){throw 'Original active binding'};$activeRecord=@{present=$true;sha256=(Hash $active);id=$a.id;config_sha256=$a.config_sha256;script_sha256=$a.script_sha256}}
|
||||||
|
@{id='ad9fd154-b2be-4f5d-9e17-65abb721ceaf';read_only=$true;candidate=(ObservePublic (Join-Path $folder 'time-attestation.candidate.json'));target=(ObservePublic (Join-Path $root 'time-attestation.json'));records=$records;active=$activeRecord;root_sddl=(Get-Acl -LiteralPath $root).Sddl;old_move_hresult_unknown=$true;retry_authorized=$false;installation_verified=$false;clock_runtime_qualified=$false;private_key_read=$false;service_action=$false}|ConvertTo-Json -Depth 20 -Compress
|
||||||
|
'''
|
||||||
|
reader=header+'\n'+'\n'.join(functions)+'\n'+native+identity+'\n'+body
|
||||||
|
require(all(token not in reader for token in ('[IO.File]::Move','Set-Acl','WriteBytes','WriteNew','Start-Service','Stop-Service','CreateDirectory','function State','function Probe')),'read-only original partial observer')
|
||||||
|
return reader
|
||||||
|
|
||||||
|
|
||||||
|
def diagnose_partial():
|
||||||
|
# Only a future explicitly authorized maintenance window may call this.
|
||||||
|
# The original install/read code and original markers stay untouched.
|
||||||
|
import datetime as dt
|
||||||
|
import subprocess
|
||||||
|
raw,manifest=read(PARTIAL_CASE/'manifest.json',PARTIAL_MANIFEST_SHA)
|
||||||
|
require(manifest['id']==PARTIAL_ID and manifest['generator_sha256']==PARTIAL_GENERATOR_SHA
|
||||||
|
and manifest['script_sha256']==PARTIAL_SCRIPT_SHA
|
||||||
|
and manifest['request']['config_sha256']==PARTIAL_CONFIG_SHA,'fixed original failed installation only')
|
||||||
|
read(PARTIAL_CASE/'InstallPublicTimeProfile.ps1',PARTIAL_SCRIPT_SHA,decode=False)
|
||||||
|
access=raw_capture.CaptureAccess(MAIN)
|
||||||
|
grant=prior.cb.contract.protected_json(MAIN/'credentials/windows-dev-access.json')
|
||||||
|
expiry=dt.datetime.fromisoformat(grant['expires_at'].replace('Z','+00:00'))
|
||||||
|
require((expiry-dt.datetime.now(dt.timezone.utc)).total_seconds()>=60,'current confirmed access window required for read')
|
||||||
|
source=partial_reader();digest=sha(source.encode());root=ROOT/'devstate/windows-time-profile-diagnostics';root.mkdir(mode=0o700,parents=True,exist_ok=True)
|
||||||
|
folder=root/str(uuid.uuid4());folder.mkdir(mode=0o700)
|
||||||
|
write(folder/'intent.json',canonical({'id':folder.name,'original_case':PARTIAL_ID,'original_manifest_sha256':PARTIAL_MANIFEST_SHA,'reader_sha256':digest,'read_only':True,'no_retry':True}))
|
||||||
|
# A small launcher avoids Windows' command-line limit. The source hash is
|
||||||
|
# generated from this closed reader, never accepted from a caller.
|
||||||
|
launcher=r'''$ErrorActionPreference='Stop';$q=([Console]::In.ReadLine()|ConvertFrom-Json);$raw=[Convert]::FromBase64String($q.source_base64);$h=[Security.Cryptography.SHA256]::Create();try{$s=([BitConverter]::ToString($h.ComputeHash($raw))).Replace('-','').ToLowerInvariant()}finally{$h.Dispose()};if($s-cne'READER_SHA'){throw 'Exact original partial reader'};$global:RmmPartialReaderInput=$q.input_record;&([scriptblock]::Create([Text.Encoding]::UTF8.GetString($raw)))'''.replace('READER_SHA',digest)
|
||||||
|
write(folder/'reader.ps1',source.encode())
|
||||||
|
try:result=access.powershell(launcher,{'source_base64':base64.b64encode(source.encode()).decode(),'input_record':{'kind':'original-public-time-profile-ad9-readonly'}},timeout=45)
|
||||||
|
except subprocess.TimeoutExpired:
|
||||||
|
write(folder/'timeout.json',canonical({'read_only':True,'timeout_seconds':45,'old_move_hresult_unknown':True}));raise RuntimeError('original diagnostic read timed out; no publication attempted') from None
|
||||||
|
write(folder/'reply.json',canonical(result))
|
||||||
|
require(result['id']==PARTIAL_ID and result['read_only'] is True and result['retry_authorized'] is False
|
||||||
|
and result['installation_verified'] is False and result['clock_runtime_qualified'] is False,'diagnostic observation is no installation success or authority')
|
||||||
|
write(folder/'receipt.json',canonical({'id':folder.name,'original_case':PARTIAL_ID,'reader_sha256':digest,'original_manifest_sha256':PARTIAL_MANIFEST_SHA,'reply_sha256':sha(canonical(result)),'read_only':True,'old_move_hresult_unknown':True}))
|
||||||
|
print(json.dumps({'id':folder.name,'original_case':PARTIAL_ID,'read_only':True,'receipt_sha256':sha((folder/'receipt.json').read_bytes())}))
|
||||||
|
|
||||||
|
if __name__=='__main__':
|
||||||
|
parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('action',choices=('guards','prepare','stage','install','read','diagnose-partial'));parser.add_argument('--case');arguments=parser.parse_args()
|
||||||
|
if arguments.action=='guards': guards();print('PASS closed public-profile source guards; no target action')
|
||||||
|
elif arguments.action=='prepare': prepare()
|
||||||
|
elif arguments.action=='diagnose-partial':
|
||||||
|
require(arguments.case is None,'diagnostic is fixed to the original ad9 case');diagnose_partial()
|
||||||
|
else: target(arguments.action,arguments.case)
|
||||||
@@ -0,0 +1,89 @@
|
|||||||
|
# Migration0016: passives Updateinventar annehmen
|
||||||
|
|
||||||
|
Am2026-11-15 ist Migration0016 tatsächlich auf dem permanenten Server mit dem
|
||||||
|
regulären SQLx-Migrationspfad ausgeführt und separat nachgelesen worden. Der
|
||||||
|
bisherige Check `observations_source_id_check` ließ nur `linux.base` und
|
||||||
|
`windows.base` zu. Die laufende Gatewayversion kannte bereits die passive
|
||||||
|
`agent.update`-Beobachtung; der Datenbankcheck verweigerte deren Speicherung.
|
||||||
|
Nach dem neuen Windowsagentenwechsel waren15 entsprechende Fehler beobachtet
|
||||||
|
worden. Diese verweigerten Nachrichten werden nicht nachträglich als gespeichert
|
||||||
|
ausgegeben.
|
||||||
|
|
||||||
|
Die additive Datei `migrations/0016_agent_update_observation_scope.sql` erweitert
|
||||||
|
ausschließlich diese feste Dreiermenge. Freie Scopes bleiben verboten. Im
|
||||||
|
normalen SQLx-Transactionrahmen wird der alte Check ersetzt und der neue Check
|
||||||
|
validiert; ein Fehler rollt die Transaktion zurück. `lock_timeout=3s` begrenzt
|
||||||
|
das Warten auf Tabellenlocks, `statement_timeout=15s` jedes DDL-Statement.
|
||||||
|
Keine DML-, RLS-, FK-, PK-, Tenant-/Geräte-/Zertifikats-, Job-, Grant- oder
|
||||||
|
Policyänderung gehört zur Migration.
|
||||||
|
|
||||||
|
Tatsächlicher Fall: `cc3ea56d-6186-425a-8ef3-90562212fb1b`. Verwendet wurde das
|
||||||
|
bereits vom Orchestrator nativ ARM64 gebaute Image
|
||||||
|
`sha256:6a76343bf65c126458244f5540d4cb740988144fc77877b409f790251e7ddcc7`.
|
||||||
|
Es enthält den vorhandenen `rmm-server migrate`-Entrypoint und die echte
|
||||||
|
SQLx-`migrate!`-Migrationseinbettung. Es wurde kein zusätzlicher Builderlauf
|
||||||
|
gestartet und keine SQLx-Tabellenzeile manuell angelegt oder geändert.
|
||||||
|
|
||||||
|
Ein eigenes privates Compose-Overlay wählte ausschließlich für den temporären
|
||||||
|
`migrate`-Container dieses bereits vorhandene Image (`pull_policy: never`,
|
||||||
|
read-only RootFS, CapDropALL, NoNewPrivileges). Die vorhandene Migration-URL
|
||||||
|
blieb im normalen Compose-/Prozesskontext; sie wurde nicht ausgegeben. Der
|
||||||
|
unterstützte `docker compose … run --no-deps … migrate` führte genau einen
|
||||||
|
wirklichen SQLx-Lauf aus, Exit0. Der eigene gestoppte Container wurde nach
|
||||||
|
seinem Exit-/Image-/Falllabelbeleg entfernt. Kein API-, Gateway- oder
|
||||||
|
PostgreSQLdienst wurde durch diesen Agenten ersetzt oder neu gestartet.
|
||||||
|
API-Filterung und API-only-Deployment sind ein eigener Orchestratorschnitt.
|
||||||
|
|
||||||
|
Die tatsächliche SQLx-Historie besitzt danach Versionen1–16 jeweils mit
|
||||||
|
`success=true`; die alten15 Checksums stimmen unverändert mit den Quellinputs
|
||||||
|
überein. Version16 heißt `agent update observation scope` und besitzt SHA384
|
||||||
|
`e66ec49233c210555b5107d20b925ca6715925871aa2bf94dfb86bd5cfb39c6dc769fdf0049b615fcad503332e1cd8fc`.
|
||||||
|
Die SQL-Datei hat SHA256
|
||||||
|
`fa0953262e3a8da7f3f0366db6f3fa77ad7976ec04327b126036739eea46eebb`.
|
||||||
|
|
||||||
|
Vor dem echten SQLx-Start wurden3127 bestehende Observationzeilen serverseitig
|
||||||
|
über ihre vollständige JSON-Zeilendarstellung gehasht; unmittelbar danach waren alle
|
||||||
|
unverändert. Der ursprüngliche Fallbaseline enthielt3123Zeilen. Deren
|
||||||
|
unveränderte Fingerprints und die vollständige RLS-/Owner-/ACL-/Policy-,
|
||||||
|
FK-/PK-/sonstige Check- und Job-/Plan-/Authorization-/Outbox-/Permit-/Receipt-
|
||||||
|
Zeugen wurden nochmals in einem getrennten Read-only-SQL-Aufruf bestätigt.
|
||||||
|
Neue passive Zeilen durften parallel regulär hinzukommen. Die neue Constraint
|
||||||
|
war tatsächlich `VALIDATED` und enthielt genau
|
||||||
|
`linux.base`, `windows.base`, `agent.update`. API und Gateway liefen während
|
||||||
|
dieser Migration unverändert mit Image422c2c28; PostgreSQL behielt seine
|
||||||
|
ursprüngliche Container-/Imageidentität.
|
||||||
|
|
||||||
|
Ein weiterer lesender Serverabgleich fand bereits drei angenommene
|
||||||
|
`agent.update`-Zeilen, zuletzt15:40:50UTC. Das beweist die normale Speicherung
|
||||||
|
dieses Scopes nach der Migration, keinen separat geprüften Windows-ACK,
|
||||||
|
keine neue Basisinventarabnahme und keine Zeit-/Jobbereitschaft.
|
||||||
|
|
||||||
|
Die Vorherarchive enthalten Katalog-/Migrations-/Policyzeugen und
|
||||||
|
Zeilenfingerprints; ein vollständiger **Vorher-`pg_dump` wurde nicht angelegt**.
|
||||||
|
Ein vollständiger privater Customformat-Dump wurde ausdrücklich **nach** der
|
||||||
|
Migration archiviert: `after-migration-0016.pg_dump`,49,455,447Bytes, SHA256
|
||||||
|
`b89e74eaaea7ec2faa17a44358acca3aead1db0fcf9ccf673e2c5808b3259398`.
|
||||||
|
Er bleibt ausschließlich im Root0700-Fall auf dem Server, Datei0600, und wurde
|
||||||
|
nicht heruntergeladen oder als Vorherbackup bezeichnet. Ein Restoretest wurde
|
||||||
|
hier nicht ausgeführt.
|
||||||
|
|
||||||
|
Zwei harmlose Vorbedingungen scheiterten vor dem eigentlichen SQLx-Lauf und
|
||||||
|
bleiben erhalten: zunächst die Annahme eines vollständigen Buildkontexts
|
||||||
|
statt des tatsächlichen Minimal-Kontexts; danach ein hier nicht unterstütztes
|
||||||
|
Compose-Flag `--no-build`. Für letzteren Fall waren Exit1, Ledger15 und die
|
||||||
|
Abwesenheit eines eigenen Containers belegt. Nach Roots konkreter Korrektur
|
||||||
|
wurde derselbe Originalfall mit einem neuen Create-only-Fortsetzungsintent
|
||||||
|
verwendet; alte Fehler-/Vorherdateien wurden nicht überschrieben. Ein weiterer
|
||||||
|
reiner Absenzmatcher wurde an die tatsächliche Kleinschreibung der Docker-
|
||||||
|
Fehlermeldung angepasst, ebenfalls vor jedem Container-/SQLx-Start. Keine
|
||||||
|
verlorene SQLx-Wirkung wurde blind wiederholt.
|
||||||
|
|
||||||
|
Geschütztes Serverarchiv:
|
||||||
|
`/opt/rust-discovery/devstate/observation-scope-migration-cc3ea56d-6186-425a-8ef3-90562212fb1b/`.
|
||||||
|
Lokaler Belegordner im eigenen Worktree:
|
||||||
|
`devstate/observation-scope-migration/cc3ea56d-6186-425a-8ef3-90562212fb1b/`.
|
||||||
|
Die separate lokale `receipt.json` bindet Originalintent, Fehler, tatsächlichen
|
||||||
|
SQLx-Erfolg, getrennten Read und Nachbackup; SHA256
|
||||||
|
`00ff8f8ffa689bf3917937ce14ae23457e464b921ae7793e9091eab9a83d76c7`.
|
||||||
|
Private Zugangsdaten und
|
||||||
|
Datenbankinhalte wurden weder veröffentlicht noch in Git aufgenommen.
|
||||||
+41
-7
@@ -6,15 +6,49 @@ Mandant und eine alte Verbindung wurden abgewiesen. Die Cloud-Linux-VM und
|
|||||||
der Windowsgast melden sich selbständig und sind über MCP abrufbar.
|
der Windowsgast melden sich selbständig und sind über MCP abrufbar.
|
||||||
[Gateway](server-time-gateway-deploy.md) · [Windows-Protokolltest](windows-time-route-operator.md)
|
[Gateway](server-time-gateway-deploy.md) · [Windows-Protokolltest](windows-time-route-operator.md)
|
||||||
|
|
||||||
Die bestehende Windows-Dienstinstallation ist weiterhin passiv und online.
|
Am 15. November liefen auf dem Windowsgast nach dem einmaligen Dienstwechsel
|
||||||
Der vorbereitete Dienstwechsel benötigt ein neues befristetes Wartungsfenster.
|
der neue Agent unter LocalService und der neue Helper unter SYSTEM. Die
|
||||||
Danach folgen der Zeitabgleich in den beiden Dienstprozessen und der erste
|
separate Nachprüfung bestätigte beide Prozessstarts, das Gerätezertifikat,
|
||||||
in der WebUI genehmigte Windows-Skriptauftrag mit Ausgabe.
|
die Geräteidentität und die bisherigen Journalstrukturen. Der erste Online-Kontakt
|
||||||
[Stand des Dienstwechsels](windows-signed-clock-upgrade-plan.md)
|
nach dem Wechsel gelang. Danach wies PostgreSQL den passiven Updatestatus
|
||||||
|
`agent.update` zurück. Der letzte reguläre Kontakt vor der Störung lag um
|
||||||
|
16:17:32 Uhr MEZ. Für die Korrektur wurden auf dem permanenten Server die
|
||||||
|
gefilterte Basisinventarabfrage und Migration 16 aus dem zum laufenden
|
||||||
|
ARM64-Image passenden Builder offline gebaut. Docker meldete Exit 0 für
|
||||||
|
Image `6a76343bf65c` (Buildfall `5ad7c74c-67a1-40b8-8960-d3ba016565af`).
|
||||||
|
Die Migration lief anschließend erfolgreich. Die API arbeitet mit diesem
|
||||||
|
Image. MCP bestätigte zwei neue Windows-Heartbeats um **16:39:46 und
|
||||||
|
16:40:17 Uhr MEZ**, jeweils mit derselben Geräte- und Zertifikatsidentität wie
|
||||||
|
vor dem Dienstwechsel. Die Cloud-Linux-VM meldete sich weiterhin als online.
|
||||||
|
[Dienstwechsel und Telemetrienachweis](windows-signed-clock-upgrade-plan.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
|
Die passive Zertifikatserneuerung ist implementiert. Fünf Wiederanlauf- und
|
||||||
Fehlerfälle mit Testidentitäten bestanden auch auf Windows. Die Erneuerung
|
Fehlerfälle mit Testidentitäten bestanden auch auf Windows. Das Anlegen,
|
||||||
durch den installierten LocalService-Dienst steht aus.
|
Schützen und Wiederöffnen einer separaten Testschlüsseldatei bestand auf
|
||||||
|
der Windows-VM unter dem Entwicklungskonto. Die Erneuerung durch den
|
||||||
|
installierten LocalService-Dienst steht aus.
|
||||||
[Zertifikatserneuerung](windows-certificate-renewal.md)
|
[Zertifikatserneuerung](windows-certificate-renewal.md)
|
||||||
|
|
||||||
Der Linux-Agent kann einen signierten Releasekatalog über mTLS prüfen und das
|
Der Linux-Agent kann einen signierten Releasekatalog über mTLS prüfen und das
|
||||||
|
|||||||
@@ -1,5 +1,16 @@
|
|||||||
# Tatsächlicher Implementierungsstand
|
# Tatsächlicher Implementierungsstand
|
||||||
|
|
||||||
|
## Agent-Update-Telemetrie: Migration0016 tatsächlich angewendet — 2026-11-15
|
||||||
|
|
||||||
|
Der permanente Server akzeptiert nun zusätzlich den festen passiven Scope
|
||||||
|
`agent.update`. Regulärer SQLx-Runner aus dem vorhandenen ARM64-Kandidaten6a7634,
|
||||||
|
Exit0 und separate Read-only-Nachprüfung von Version16/Checksum/VALIDATED-Check
|
||||||
|
bestanden. Ursprüngliche Zeilen, RLS/FKs/PK/ACL und Corezeugen erhalten; keine
|
||||||
|
laufenden Dienste durch diesen Schnitt ersetzt. Erste drei regulär angenommene
|
||||||
|
Updatebeobachtungen belegt. API-Basisfilterung ist getrennt. Vorherfingerprints
|
||||||
|
und ausdrücklich erst nachher angelegter privater pg_dump sind dokumentiert;
|
||||||
|
kein vorgetäuschter Vorherbackup-/Restoretest. [Beleg](agent-update-observation-scope.md).
|
||||||
|
|
||||||
## Passiver Windows-Zeitabschluss vorbereitet — 2026-11-15
|
## Passiver Windows-Zeitabschluss vorbereitet — 2026-11-15
|
||||||
|
|
||||||
Ein kleiner rein lesender Collector für die beiden historischen Rollenbelege
|
Ein kleiner rein lesender Collector für die beiden historischen Rollenbelege
|
||||||
|
|||||||
@@ -289,3 +289,52 @@ Autostarttask. Beide installierten Dienste liefen beim Readback mit ihren
|
|||||||
bisherigen Prozess-IDs: Agent 5528 als LocalService, Helper 9464 als LocalSystem.
|
bisherigen Prozess-IDs: Agent 5528 als LocalService, Helper 9464 als LocalSystem.
|
||||||
Danach wurde die Ablaufzeit im lokalen Zugangsdatensatz an die geprüfte
|
Danach wurde die Ablaufzeit im lokalen Zugangsdatensatz an die geprüfte
|
||||||
Gastfrist angepasst. Dies ist der Nachweis für den Entwicklungszugang.
|
Gastfrist angepasst. Dies ist der Nachweis für den Entwicklungszugang.
|
||||||
|
|
||||||
|
### Unterbrechung nach Ruhezustand des Notebooks
|
||||||
|
|
||||||
|
Das Hostjournal belegt Suspend zwischen 14:48:24 und 15:39:01 Uhr MEZ.
|
||||||
|
Danach blieb die Windows-VM im KVM-Status `running`. Der Entwicklungszugang
|
||||||
|
lieferte bei der SSH-Begrüßung einen Timeout. Auch direkt am bestätigten
|
||||||
|
Loopback-Listener des Servers kam keine Begrüßung an. Um 15:47 Uhr wurde
|
||||||
|
nur die anhand von Konto, Prozess und Listener erneut identifizierte alte
|
||||||
|
Forwarding-Sitzung geschlossen. Schlüssel und vereinbarte Frist von
|
||||||
|
16:30 Uhr MEZ blieben erhalten. Zum erneuten Aufbau ist die VM-Konsole nötig.
|
||||||
|
|
||||||
|
Der Produktagent meldete sich nach dem Resume beim permanenten Server. MCP
|
||||||
|
lieferte bei der Abfrage um 15:48 Uhr MEZ für den Windows-Gast `online`,
|
||||||
|
Quelle `windows.base`, letzter Kontakt 15:47:51 Uhr MEZ. Beim Unterbruch war
|
||||||
|
der Dienstwechsel noch nicht in die Ausführungsphase gelangt.
|
||||||
|
|
||||||
|
Eine weitere reine MCP-Abfrage bestätigte das nach dem Aufwachen neu
|
||||||
|
eingegangene Windows-Inventar. Beobachtungszeit 15:39:13 Uhr MEZ, späterer
|
||||||
|
Kontakt 15:52:23 Uhr MEZ. Betriebssystem, Volumes, Hardware und Software
|
||||||
|
lagen jeweils als `valid/partial` vor. CPU-Anzahl, Verhältnis von freiem zu
|
||||||
|
gesamtem Speicher und die Volumenwerte bestanden die Plausibilitätsprüfung.
|
||||||
|
Windows-Inodes waren ausdrücklich `unsupported` mit leerem Zahlenwert.
|
||||||
|
Beleg-SHA-256 `cce907d4c5e4ca9b788bab4aad8aac1f082b59f6a2922484289f19be061a1162`.
|
||||||
|
Die Abfrage nutzte gespeicherte Telemetrie und erforderte keine SSH-Verbindung.
|
||||||
|
|
||||||
|
Beim erneuten Konsolenstart meldete der Gast die Sammelmeldung
|
||||||
|
`Unexpected account, task, server or previous expiry.`. Sie stammt aus der
|
||||||
|
Vorprüfung vor der ersten Änderung. Welcher Gastwert abweicht, steht bis zum
|
||||||
|
Konsolen-Readback offen. Die Serverfrist wurde zu diesem Zeitpunkt nochmals
|
||||||
|
mit 15:30 UTC bestätigt. Neuere Versionen des Konsolenskripts benennen die
|
||||||
|
abweichenden Felder einzeln. Drei lokal simulierte Vorprüfungen bestanden
|
||||||
|
(Ausgangszustand, drei abweichende Werte, alle sechs Bedingungen abweichend).
|
||||||
|
|
||||||
|
Der Konsolenreadback vom 15. November um 15:59:11 Uhr MEZ ergab
|
||||||
|
`Disabled`, aktives Konto, Konto und Konfiguration beide mit Frist 16:30 Uhr
|
||||||
|
MEZ, passender Servername, laufender sshd und genau eine ausstehende Sicherung.
|
||||||
|
Der Bediener kann diesen konkreten Zustand mit `-ResumeInterrupted` im selben
|
||||||
|
Zeitfenster übernehmen. Das Skript prüft die ursprüngliche Frist der Sicherung
|
||||||
|
und rekonstruiert daraus die aktuelle Konfiguration. Bereits laufende
|
||||||
|
Wartungsprozesse verhindern einen Doppelstart. Bei regulärem Ende verwendet
|
||||||
|
es die ursprüngliche Sicherung zur Rücksetzung. Lokaler Parser- und Fixturetest
|
||||||
|
für passende Sicherung, aktiven Prozess, Konfigurations- und Fristabweichungen
|
||||||
|
bestanden. Die Wiederaufnahme muss auf der Windows-Konsole erfolgen.
|
||||||
|
|
||||||
|
Um 16:04:25 Uhr MEZ war der Windows-Gast über die vom Bediener wieder
|
||||||
|
geöffnete Verbindung erreichbar. Der Gast bestätigte für Konto und Konfiguration
|
||||||
|
denselben Ablauf um 16:30 Uhr MEZ, den erwarteten Servernamen und den
|
||||||
|
deaktivierten Autostarttask. Agent und Helper liefen weiterhin mit ihren
|
||||||
|
ursprünglichen PIDs 5528 und 9464 als LocalService beziehungsweise LocalSystem.
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
# Lesender Abschluss zweier passiver Windows-Zeitbeobachtungen
|
# Lesender Abschluss zweier passiver Windows-Zeitbeobachtungen
|
||||||
|
|
||||||
Der Collector `deploy/windows/passive_time_closeout.py` ist lokal vorbereitet
|
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
|
V2-Profileinrichtung und ihr ausdrücklich gemeldetes Zeitfenster stehen vor
|
||||||
dem Aufruf. Tunnel-/Zugangserneuerung, Profileinrichtung und Dienstwartung sind
|
dem Aufruf. Tunnel-/Zugangserneuerung, Profileinrichtung und Dienstwartung sind
|
||||||
keine Aktionen dieses Collectors.
|
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`
|
auch Metadaten vorhandener fester `.agent-time.pending`/`.helper-time.pending`
|
||||||
können eine unterbrochene Publikation erklären. Dieser Collector liest oder
|
können eine unterbrochene Publikation erklären. Dieser Collector liest oder
|
||||||
ändert diese zusätzlichen Dateien nicht und löst keine Diagnose aus.
|
ä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
|
Readback nicht. Neue Starts benötigen weiterhin die exakt qualifizierten
|
||||||
aktuellen Quellen. Vollständige Ausgaben/Transportfehler bleiben privat,
|
aktuellen Quellen. Vollständige Ausgaben/Transportfehler bleiben privat,
|
||||||
Standardausgabe enthält nur Status, Fallkennung und Nachweishashes.
|
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`.
|
||||||
|
|||||||
@@ -247,3 +247,215 @@ Der Agent-Zwischenbuild `34b7458d…` wurde nicht installiert.
|
|||||||
Die neun gezielten Zeitprüfungen aus diesem konkreten Quellstand bestanden auf
|
Die neun gezielten Zeitprüfungen aus diesem konkreten Quellstand bestanden auf
|
||||||
der Cloud-Linux-VM als UID 65534, Exit 0. SHA-256 der Ergebnisquittung
|
der Cloud-Linux-VM als UID 65534, Exit 0. SHA-256 der Ergebnisquittung
|
||||||
`333f8d2dba3b35dcd79faafd8faf5c88da321942c9672c0a80f1f2c8fceb24a3`.
|
`333f8d2dba3b35dcd79faafd8faf5c88da321942c9672c0a80f1f2c8fceb24a3`.
|
||||||
|
|
||||||
|
Anschließend bestanden die gleichen neun Tests auf der Windows-VM aus dem
|
||||||
|
separat gebauten AMD64-Librarytestbinary desselben Release-Quellstands, Exit 0.
|
||||||
|
Die Ergebnisquittung hat SHA-256
|
||||||
|
`7700096145afdca74e7473e56c6dd2e65651252e889a696f84bb1fc2441ff513`.
|
||||||
|
Nach erneutem Abgleich aller 202 Quelldateien, des PE-Headers und des Helperhashs
|
||||||
|
wurde das Buildreceipt
|
||||||
|
`f04024f78c2f11f5c66bbdf9278467f5bcc50da5c2bd7336623851bca42dd446`
|
||||||
|
für den einmaligen Dienstwechsel erstellt. Der Windows-Testprozess hat weder
|
||||||
|
einen Dienst ausgetauscht noch einen Agentjob ausgeführt.
|
||||||
|
|
||||||
|
Der exakt gebaute Quellstand für das neue Agentbild liegt in Gitea auf
|
||||||
|
`codex/windows-passive-time-candidate`, Commit
|
||||||
|
`c6c4037d072a96d62136264066d0257782c7a932`. Alle 202 Build-Inputs wurden
|
||||||
|
byteweise mit dem Release-Manifest abgeglichen. Der Ausgangsstand der
|
||||||
|
ursprünglichen Qualifikation entspricht für dieselben 202 Dateien
|
||||||
|
`b8ca8266bbb3b4806f4d20a3039f25196638804e`.
|
||||||
|
|
||||||
|
## Endgültiger passiver Agent und erneute Transportverweigerung
|
||||||
|
|
||||||
|
Root qualifizierte für genau den beobachtbaren passiven Stand cc82124 den
|
||||||
|
Agent0549d9ebea73cff996938f859b92192cc333de194128d7c6859a3f1d2e85893c.
|
||||||
|
Tatsächliche Linux9-/Windows9-Guards und Release-Link sind im Receipt
|
||||||
|
f04024f78c2f11f5c66bbdf9278467f5bcc50da5c2bd7336623851bca42dd446 gebunden,
|
||||||
|
Sourceinputs11717fab51bd1d6bf103b1821cc1e2a84699f46cac21f2cc614acf4b68381fa4.
|
||||||
|
Helper5967… bleibt aus dem ursprünglichen04ed-Produktreceipt unverändert.
|
||||||
|
Der Generator bindet diese beiden getrennten tatsächlichen Artefaktquellen,
|
||||||
|
keinen nochmals eingebauten26dc-Agenten. Der öffentliche neue lokale Receipt
|
||||||
|
war zunächst0664; nur sein Modus wurde auf0600 gehärtet, Bytes/SHA unverändert.
|
||||||
|
|
||||||
|
Neuer unveränderlicher Fall570c7a86-6509-49e6-b95e-8f0df74b18bf,
|
||||||
|
Controller67d2fb1f9fdfec05b08f53a37be9a7df4cc3bb39f6cde8f950a226286474fd45,
|
||||||
|
bindet das bestätigte15:30UTC-Fenster. Sein allererster kleiner Stage-Read wurde
|
||||||
|
jedoch bereits beim SSHtransport verweigert: return255, stdout0, stderr89Bytes.
|
||||||
|
Ein einzelner begrenzter Statusversuch klassifizierte CONNECTION_TIMEOUT,
|
||||||
|
keinen Authentifizierungs-/Hostkeyfehler. Kein neuer Agenttransfer, kein Enter,
|
||||||
|
keine Dienständerung oder Wiederholung unklarer Wirkung durch diesen Fall.
|
||||||
|
|
||||||
|
Root belegte danach Notebook-System-Suspend13:48:24–14:39:01UTC und einen nicht
|
||||||
|
mehr antwortenden alten Forwardingkanal. Damals existierte weiterhin keine
|
||||||
|
V2-Konfiguration/Zeitauthorität; beide ursprünglichen Produktdienste waren passiv.
|
||||||
|
Root beendete ausschließlich den separat kernelgebundenen alten Bastionforwarder
|
||||||
|
und forderte kontrolliertes Neuöffnen desselben Fensters an. Dieser Wartungsagent
|
||||||
|
änderte weder Tunnel, Konto, Schlüssel noch SSHkonfiguration. Seit Roots Sperre
|
||||||
|
keine weiteren VM-Aufrufe bis bestätigtem Transportreadback.
|
||||||
|
|
||||||
|
Abschließender lokaler Check: Pythoncompile, bestehende Quellguards, exakte
|
||||||
|
saved-controller-/Generatorbytes, neues Agentimage, unverändertes Helperimage,
|
||||||
|
Source-/Native-Receipt und geschützte15:30-Payloadbindung PASS. Beleg
|
||||||
|
74ca4c2572872eb64cecc250aefd4bbffa5d8e4dc9b3729b5b83c19ac07a670f,
|
||||||
|
`final-local-check.json` im570c-Fall. Neue native Baseline, tatsächlicher
|
||||||
|
Paarwechsel und unabhängige Nachlese bleiben offen. Es wird kein Windowsabschluss
|
||||||
|
oder funktionierender installierter Zeitvergleich behauptet.
|
||||||
|
|
||||||
|
## Transport wieder bestätigt: endgültiger570c-Stand nativ bereit
|
||||||
|
|
||||||
|
Nach Roots tatsächlichem Konsolen-/Transportreadback15:04:25UTC wurde ausschließlich
|
||||||
|
der vorhandene570c-Fall fortgesetzt, unverändertes Ende15:30UTC. Tatsächliche
|
||||||
|
Stagebestätigung für Helper5967…, endgültigen Agent0549… und Controller67d2…
|
||||||
|
bestanden. Volle neue native Baseline bestätigt ursprüngliche Running-PIDs5528/9464,
|
||||||
|
unveränderte config/PKI/ACLs und vollständigen bisherigen Helper-DB-/Lock-/Intent-
|
||||||
|
zustand. BaselineSHA
|
||||||
|
b1a7928f89ad2bb9c63720dedea6f343d644c9882052877b5144dc200537f5e7.
|
||||||
|
Geschlossene Serverflags und Windows0-/Linux31/31/27-Zähler unverändert.
|
||||||
|
Noch keine Dienständerung bis zu diesem Baselinebeleg. Nächster Schritt ist die
|
||||||
|
genau einmalige, an diese neuen tatsächlichen Bytes gebundene Enterphase.
|
||||||
|
|
||||||
|
## ETS-Skalartypfehler vor erster Wirkung behoben
|
||||||
|
|
||||||
|
Die einmalige570c-Enterphase verweigerte `Original SCM invariant`. Die reine
|
||||||
|
Nachlese zeigt erneut eigenen Ordner/active-intent und alle Stopmarker absent;
|
||||||
|
Originaldienste laufen5528/9464. Keine Enterwiederholung und keine Dienstwirkung.
|
||||||
|
Isolierter Vergleich aller sechs SCM-Felder inklusive CLR-/Basistyp und Wrapping
|
||||||
|
belegt ausschließlich `sid_type`: Baseline und live beide System.Int32=1, aber
|
||||||
|
der ETS-wrapped Registrywert erfüllt zusätzlich `-is[pscustomobject]` und wurde
|
||||||
|
irrtümlich zu `{}` normalisiert. Die anderen fünf Felder stimmten exakt überein.
|
||||||
|
|
||||||
|
Der Vergleich rekonstruiert jetzt JSON-Skalare aus ihrem CLR-Basiswert vor dem
|
||||||
|
Objektpfad (primitive Strings/Bool/Integer/finite Double/Decimal), ohne ETS-Notes
|
||||||
|
als fachlichen Objektinhalt umzudeuten. Echte JSON-Objekte behalten alle Keys;
|
||||||
|
Casekollisionen/Arrayreihenfolge/Null/Tiefengrenze bleiben geschützt. Unabhängiger
|
||||||
|
enger Review der Quelle90c2708c… ohne weiteren konkreten Befund.
|
||||||
|
|
||||||
|
Tatsächlich anschließend auf derselben VM: vollständiges originales
|
||||||
|
`SameOriginal` gegen gespeicherte Baseline und frischen LiveState bestanden.
|
||||||
|
Zusätzlich native ETS-Add-Member-Fälle für Integer/String/Bool gleich,
|
||||||
|
Scalaränderung/Arrayumkehr/Null gegenüber leerem Array weiterhin verweigert.
|
||||||
|
Result82c4ebe75bff95005ebd946ae99e206ec69648bec93adb17cf683c46fc46212a,
|
||||||
|
`typed-full-pre-effect-comparison.json` im570c-Fall. Weiterhin keine Ordner/active-
|
||||||
|
Marker und keine Dienständerung. Neuer Controllerfall folgt getrennt;570c bleibt
|
||||||
|
als fehlgeschlagene Vorwirkungsphase erhalten.
|
||||||
|
|
||||||
|
## Neuer typkorrigierter Fall4887 nativ bereit
|
||||||
|
|
||||||
|
Fall4887940a-4c9c-4807-aaf2-6fbc94faad46 bindet unverändert Agent0549/Helper5967,
|
||||||
|
denselben echten Quell-/Linux9-/Windows9-Beleg und das unveränderte15:30-Fenster.
|
||||||
|
Controller66ca45e15e8f790c4614db74dd491137d5e28104e2d28ee658cc287debcd021f.
|
||||||
|
Alle festen Stagebytes erneut nativ bestätigt; volle frische Baseline einschließlich
|
||||||
|
ursprünglicher PIDs5528/9464, config/PKI/ACLs und Helper-DB/Lock/Intents bestanden.
|
||||||
|
Baseline00bf31bd5355dc77e0aadd73d2ab57ea32410956ef764f3f2aeb195bd218479e.
|
||||||
|
Geschlossene Servergates unverändert, bis hier weiterhin kein Serviceeffekt.
|
||||||
|
4887 besitzt noch keinen Enterversuch;570c bleibt getrennt vor Wirkung verweigert.
|
||||||
|
|
||||||
|
Nach dem tatsächlichen Dienstwechsel bestätigten SCM und MCP zunächst beide
|
||||||
|
laufenden Dienste und die bisherige Geräteidentität. Der letzte Kontakt blieb
|
||||||
|
dann bei 16:17:32 Uhr MEZ stehen. Um 16:21:38 Uhr authentifizierte der Agent
|
||||||
|
sich weiterhin erfolgreich. Die drei serverseitigen Sperren für Restore,
|
||||||
|
Sequenzregression und Sync-Recovery waren alle aus. Der neue Agent meldet
|
||||||
|
`agent.update/1` und sendet eine passive `not_configured`-Beobachtung. Auf
|
||||||
|
dem Server ließ der CHECK von `observations.source_id` ausschließlich
|
||||||
|
`linux.base` und `windows.base` zu. PostgreSQL protokollierte seit dem Wechsel
|
||||||
|
15 Verletzungen genau dieses CHECKs. Der erste Online-Status war damit kein
|
||||||
|
Nachweis für fortlaufende Heartbeats.
|
||||||
|
|
||||||
|
Die Geräteansicht selektiert im geänderten API-Quellstand gezielt den neuesten
|
||||||
|
Basisdatensatz. Die aus dem Produktcode extrahierte LATERAL-Abfrage lieferte in
|
||||||
|
einer lesenden PostgreSQL-Prüfung auf dem Server die erwarteten Windows- und
|
||||||
|
Linux-Werte sowie NULL für ein Gerät mit ausschließlich Updatebeobachtungen.
|
||||||
|
Auch Mandant und Seitenstichtag wurden im Datensatz gegengeprüft.
|
||||||
|
|
||||||
|
## Tatsächlicher einmaliger Paarwechsel, Abschluss nur lesend wiedergewonnen
|
||||||
|
|
||||||
|
4887 führte den tatsächlichen Paarwechsel genau einmal aus: beide ursprünglichen
|
||||||
|
Prozesse kontrolliert beendet, vier Originaldateien gesichert, Agent/Helper und
|
||||||
|
reziproke geschlossene Settings/Pins vollständig ersetzt, danach Helper und Agent
|
||||||
|
jeweils einmal gestartet. Neue tatsächlich laufende Kernel-/Serviceinstanzen:
|
||||||
|
Agent0549… PID4420, Helper5967… PID10264. Der ursprüngliche Enteraufruf meldete
|
||||||
|
allerdings beim abschließenden Schemaerhaltungscheck einen Fehler; er wurde
|
||||||
|
**nicht** erneut aufgerufen. Originalmarker belegen alle vier Replacements und
|
||||||
|
beide tatsächlichen Starts; `entered.json` wurde wegen des Nachprüfungsfehlers
|
||||||
|
nicht geschrieben. Der erste Postcheck bleibt fehlgeschlagen.
|
||||||
|
|
||||||
|
Der exakte Nachbefund: Telemetriedatei-ID, Creation und Geräteidentitätshash sind
|
||||||
|
identisch. Alle bisherigen Schemaeinträge/Trigger sind bytegleich erhalten;
|
||||||
|
ausschließlich `update_health_inventory` wurde additiv angelegt. Deren komplette
|
||||||
|
DDL entspricht der tatsächlich qualifizierten eingefrorenen Quelle
|
||||||
|
`agent-core/src/update_health_inventory.rs` (Sourceinputs11717fab…). Dies ist
|
||||||
|
keine globale Lockerung des Schemaerhalts: der Abschlussleser verlangt exakt
|
||||||
|
einen zusätzlichen Eintrag, exakt diesen Typ/Namen/DDL und unveränderte übrige
|
||||||
|
Einträge. Die neue Tabelle wurde nicht auf Zeileninhalt abgefragt; es wird keine
|
||||||
|
solche Prüfung behauptet. Bestehende Job-/Reconcilezähler bleiben vollständig0,
|
||||||
|
Serverjob-/Outbox-/Permitgates ebenfalls unverändert geschlossen.
|
||||||
|
|
||||||
|
Eine erste reine Abschlusslesung verweigerte fälschlich wegen PowerShell-
|
||||||
|
Pipelineflattening der Schema-Tupel; nach Beschränkung auf explizite Listen
|
||||||
|
bestand derselbe ausschließlich lesende Originalfallvergleich. Keine weitere
|
||||||
|
Service-/Datei-/Jobmutation war Teil dieser Recovery. Der Reader prüft zusätzlich
|
||||||
|
Originalintent/active-Bindung, vollständigen Config-/PKI-/Privatekeymetadaten-/
|
||||||
|
DB-/Lock-/Helperrowerhalt sowie exakte beiden gespeicherten einzelnen neuen
|
||||||
|
Service-/Kernelstarts. Native tatsächliche Zeitquelle/Clockfreigabe wird dadurch
|
||||||
|
nicht behauptet.
|
||||||
|
|
||||||
|
Anschließend unabhängiger zweiter Originalfallread: dieselben neuen Prozesse,
|
||||||
|
Images und Dateiidentitäten, sämtliche Erhaltungsbedingungen erneut bestanden.
|
||||||
|
Belege im4887-Fall:
|
||||||
|
|
||||||
|
- `completion-readback.json`:13448d833b32dedfb5e07cb4e76f046e666522488ffabbb3a38a57d2d485d1b8
|
||||||
|
- `independent-readback.json`:63e453fb915cadee028407a6aeaa8c7d209ae88ed12a6d4d4307d4fd25e4c539
|
||||||
|
- `intent.json`:40e9cd557225504429b51dcecd4322b32d7f0973bcbb8e2a2e52516917907b85
|
||||||
|
- `bound-payload.json`:074a13fd3e4cdefd85aedb5a9fc17d247994e0e515b71e4e0925f713d37774f7
|
||||||
|
- `result.json`:2898a72b4b0d84159cc11d80765cbfa4206faf7038d0e860429c8b1a57538ee2
|
||||||
|
|
||||||
|
Das Resultat kennzeichnet ausdrücklich `recovered_postcondition_read=true` und
|
||||||
|
`original_enter_postcheck_failed=true`. Es meldet keine erfundene erfolgreiche
|
||||||
|
ursprüngliche Enterantwort. Kein Jobmodus, Effektgate, VM-Reboot, Enrollment,
|
||||||
|
Gerätezertifikatswechsel oder Zeitprofil wurde durch diese Wartung aktiviert.
|
||||||
|
|
||||||
|
Getrennt offen: Parent bestätigte einmaligen korrekten neuen Hello/Identität und
|
||||||
|
unverändertes Gerätezertifikat/Enrollment/Assignment, jedoch noch keine zwei
|
||||||
|
fortlaufenden Heartbeats; gespeicherte Präsenz wurde später stale. Die zusätzliche
|
||||||
|
Capability `agent.update/1` stammt aus dem konkret installierten passiven
|
||||||
|
not_configured-Schema. Heartbeatkontinuität und installierte Clockautorität
|
||||||
|
bleiben im Resultat ausdrücklich **nicht bewiesen**. Windows-MVP damit nicht
|
||||||
|
vollständig abgenommen. Wichtige spätere Werkzeugverbesserung: erwartete additive
|
||||||
|
Schemaentwicklung vor Wartung aus dem qualifizierten Quellstand planen; hierfür
|
||||||
|
jetzt keinen allgemeinen Migrations-/Resumeframework bauen.
|
||||||
|
|
||||||
|
## Serverkorrektur für die passive Telemetrie am 15. November 2026
|
||||||
|
|
||||||
|
Nach SQLx-Migration 16 wurde um 16:39:24 Uhr MEZ ausschließlich der
|
||||||
|
API-Container auf dem permanenten Server neu gestartet. Sein ARM64-Image
|
||||||
|
`6a76343bf65c126458244f5540d4cb740988144fc77877b409f790251e7ddcc7`
|
||||||
|
enthält die Änderung an der Basisinventarabfrage und die Migration.
|
||||||
|
Gateway und PostgreSQL behielten Container-ID und Startzeit.
|
||||||
|
|
||||||
|
Der erste Nachvergleich schlug beim direkten Listenvergleich der
|
||||||
|
Containerkonfiguration fehl. Eine separate lesende Prüfung verglich die Mounts
|
||||||
|
nach Zielpfad. Docker lieferte sie in anderer Reihenfolge. Quelle, Ziel,
|
||||||
|
Modus und übrige Mountattribute stimmten vollständig mit dem vorherigen
|
||||||
|
Container überein. API-Umgebung und Startkonfiguration entsprachen Compose
|
||||||
|
und Image. Verifiziert wurden zudem die Loopback-Bindung, UID/GID 10001,
|
||||||
|
Read-only-Rootfs, CapDrop ALL und no-new-privileges. Es gab genau einen
|
||||||
|
API-Wechsel. Die weitere Prüfung erfolgte am laufenden Container.
|
||||||
|
|
||||||
|
### Erneute Abnahme über MCP
|
||||||
|
|
||||||
|
Zwei getrennte, nach Beginn der Prüfung eingegangene Kontakte des Windows-11-
|
||||||
|
Agenten wurden am 15. November um 16:39:46 und 16:40:17 Uhr MEZ aus
|
||||||
|
`inventory.get_device` gelesen. Beide hatten Präsenz `online`, dasselbe
|
||||||
|
Gerät, dieselbe Agent-ID, Zuordnung, Enrollmentgeneration und dasselbe
|
||||||
|
authentifizierte Zertifikat wie vor dem Paarwechsel. Der Agent meldet
|
||||||
|
`heartbeat/1`, `windows.base/1` und `agent.update/1`.
|
||||||
|
Beleg-SHA-256 `837c7580b9e7cd68de09533f50d91622272c2f2bc288da70d8b4624d2f6a747e`.
|
||||||
|
|
||||||
|
Die MCP-Geräteansicht lieferte das gespeicherte Windows-Basisinventar mit fünf
|
||||||
|
Bereichen und für die Cloud-Linux-VM den Datensatz `linux.base`. Das
|
||||||
|
Windows-Basisinventar stammte von 16:16:59 Uhr MEZ. Die Kontaktzeiten wurden
|
||||||
|
unabhängig davon aktualisiert. PostgreSQL speicherte die separaten
|
||||||
|
Updatemeldungen des Windowsagenten um 16:38:43, 16:39:45 und 16:40:50 Uhr MEZ.
|
||||||
|
Der zuletzt gelesene Updatezustand war `not_configured`. Die Windows-Jobtabelle
|
||||||
|
enthielt für dieses Gerät null Aufträge. Die Prüfung las gespeicherte
|
||||||
|
Telemetrie über den permanenten Server nach Ablauf des SSH-Fensters.
|
||||||
|
|||||||
@@ -0,0 +1,571 @@
|
|||||||
|
# Erste öffentliche Windows-Zeitkonfiguration V2
|
||||||
|
|
||||||
|
Stand 2026-11-15: Der reale Paarfall `4887940a-4c9c-4807-aaf2-6fbc94faad46`
|
||||||
|
ist nach abgeschlossener unabhängiger Nachlese gebunden (Result `2898a72b…`,
|
||||||
|
Originalintent `40e9cd55…`, separater Read `63e453fb…`). Die vorherige
|
||||||
|
Verweigerung mit fehlenden Rollenbelegen bleibt als historischer lokaler Test
|
||||||
|
nachgewiesen. Ein Zeitvertrauen oder durchgehende Heartbeats sind durch den
|
||||||
|
Paarabschluss ausdrücklich nicht bewiesen.
|
||||||
|
|
||||||
|
Der Operator prüft die unveränderten öffentlichen Vorbereitungsbelege
|
||||||
|
`c3077acf-12da-410e-9f55-e75a1cd0a75f`, deren getrennten Ed25519-Zeitschlüssel,
|
||||||
|
Gerätebindung und tatsächlich gelesene KVM-Plattform. Die ursprüngliche
|
||||||
|
Vorbereitung bleibt mit `roles_qualified=false` unverändert. Die akzeptierte
|
||||||
|
Betriebsannahme ist ausdrücklich
|
||||||
|
`active_guest_no_pause_save_restore_snapshot_migration_host_suspend`; das ist
|
||||||
|
keine physikalische Kalibrierung und keine automatische Überwachung dieser
|
||||||
|
Betriebsannahme.
|
||||||
|
|
||||||
|
Der neue Agent ist an SHA256
|
||||||
|
`0549d9ebea73cff996938f859b92192cc333de194128d7c6859a3f1d2e85893c`
|
||||||
|
und Buildreceipt `f04024f78c2f11f5c66bbdf9278467f5bcc50da5c2bd7336623851bca42dd446`
|
||||||
|
gebunden. Seine 202 Quellinputs sind durch `11717fab…` fixiert; das tatsächlich
|
||||||
|
erweiterte Zeitmodul hat SHA256 `342494c4…`. Gegen die ursprüngliche Quelle
|
||||||
|
`d8594c1e…` kamen die passive Sampling-Auswahl und deren neunte Prüfung hinzu.
|
||||||
|
Der Helper bleibt `59675a3c…`, aus dem ursprünglichen Linkbeleg `04ed34e6…`
|
||||||
|
und Quellbeleg `96b05fe1…`. Diese unterschiedlichen Provenienzen werden nicht
|
||||||
|
gleichgesetzt. Der tatsächliche neue Paar-Payload verwendet für
|
||||||
|
`qualification_sha256` und `manifest_sha256` jeweils den neuen Beleg `f04024f7…`;
|
||||||
|
der alte Helper-Quellbeleg ist kein Ersatz dafür.
|
||||||
|
|
||||||
|
Bevor ein Fall erstellt werden kann, müssen ein abgeschlossener passiver
|
||||||
|
Paarwechsel und unabhängig fixierte Originalbelege vorliegen. Für beide Rollen
|
||||||
|
werden SCM-Status, PID, Kernel-Prozessgeburt, tatsächliches Konto, aktivierte
|
||||||
|
Service-SID, gehaltener Prozesshandle, Imagepfad, Imagehash und native FileID
|
||||||
|
verknüpft. Die alten numerischen 601-Proben bleiben ausdrücklich rohe
|
||||||
|
Voraussetzungsbelege; sie qualifizieren kein Produktimage. Der Producer erzeugt
|
||||||
|
öffentliche Rollen- und Plattformbelege und daraus das vorhandene strikte
|
||||||
|
V2-Format mit genau beiden Rollen. Er behauptet weder signierte Laufzeitprüfung
|
||||||
|
noch physikalische Genauigkeit. Fehlende oder widersprüchliche Belege sperren.
|
||||||
|
|
||||||
|
## Geplanter Ablauf nach neuem realem Paar-Readback
|
||||||
|
|
||||||
|
Die folgenden Phasen sind **vorbereitet, nicht auf dem Ziel ausgeführt**:
|
||||||
|
|
||||||
|
1. Root bestätigt Original-Paarfall und Originalbeleg-Hashes; diese werden als
|
||||||
|
konkrete Quellenkonstanten gebunden und nochmals geprüft.
|
||||||
|
2. `prepare` liest ausschließlich öffentliche lokale Belege und erzeugt einen
|
||||||
|
privaten, einmaligen Fall. `stage --case <id>` überträgt ausschließlich den
|
||||||
|
fixierten Controller über den bestehenden bestätigten SSH-Transport.
|
||||||
|
3. `install --case <id>` darf genau eine bisher fehlende feste öffentliche Datei
|
||||||
|
veröffentlichen. Bereits vorhandene Datei, aktiver Marker oder Teilfall
|
||||||
|
verweigern einen neuen Installationsversuch. Ein verlorener Antwortweg führt
|
||||||
|
ausschließlich zu `read --case <id>`, nicht zu Wiederholung oder Rollback.
|
||||||
|
4. Root liest den ursprünglichen Fall separat und prüft danach die echten
|
||||||
|
passiven Agent-/Helper-Zeitbelege. Eine erfolgreiche Veröffentlichung allein
|
||||||
|
setzt `clock_runtime_qualified` ausdrücklich nicht auf true.
|
||||||
|
|
||||||
|
## Begrenzte Wirkung und Erhaltungsnachweis
|
||||||
|
|
||||||
|
Der Controller verwendet ausschließlich die vorhandenen lesenden SCM-,
|
||||||
|
Kernel-, FileID-, PKI-Metadaten- und Journalzeugen. Er importiert keine alten
|
||||||
|
Stop-/Start-/Swap-/Repair-Phasen. Die aktuelle Prozessgeneration, beide Images,
|
||||||
|
vier Code-/Policydateien, Konfiguration, Geräteidentität, Zertifikat,
|
||||||
|
Schlüsselmetadaten, Telemetrieidentität, Sequenzmonotonie und leere
|
||||||
|
Job-/Helper-Intents werden vor, während und nach der Veröffentlichung geprüft.
|
||||||
|
Der private Schlüssel wird weder gelesen noch gehasht.
|
||||||
|
|
||||||
|
Eine neue private Bootstrap-Falldirectory wird nativ exklusiv mit geschützter
|
||||||
|
SYSTEM-/Administrators-DACL angelegt. Alle Originalmarker werden create-only
|
||||||
|
geschrieben und geflusht. Nur der öffentliche Helper-Stamm erhält bei Bedarf
|
||||||
|
fehlende `0x001200a9`-Leserechte für beide **Service-SIDs**, ausschließlich für
|
||||||
|
diesen Ordner, ohne Vererbung auf State/PKI/Ledger. Fremde oder weiter gehende
|
||||||
|
Service-Rechte werden verweigert. Die Kandidatdatei erhält vor Veröffentlichung
|
||||||
|
SYSTEM/Administrators-Vollzugriff und dieselben begrenzten Leser. Die feste
|
||||||
|
Zieldatei wird nach durablem Publish-Intent mit einem gleichvolumigen,
|
||||||
|
überschreibungsfreien Move veröffentlicht; anschließend müssen FileID, Hash
|
||||||
|
und DACL unverändert sein. Keine allgemeine Stromausfall-Atomizität wird daraus
|
||||||
|
abgeleitet. Teilzustände bleiben im Originalfall lesbar, ohne automatische
|
||||||
|
Reparatur oder Rechte-Rücksetzung.
|
||||||
|
|
||||||
|
Unmittelbar vor der ersten Erstellung wird `install_not_before` aus der
|
||||||
|
nativen VM-UTC gelesen und im ursprünglichen Intent sowie Ergebnis erhalten.
|
||||||
|
Das ist eine Herkunftsuntergrenze für die nachfolgende separate Nachlese und
|
||||||
|
den passiven Collector, keine eigenständige Uhrvertrauensbehauptung.
|
||||||
|
|
||||||
|
## Laden und tatsächliche Grenzen
|
||||||
|
|
||||||
|
Das vorhandene `signed_clock::native::SignedClock::open` lädt bei jedem Öffnen
|
||||||
|
geschützte Settings, beweist den eigenen Dienstprozess und öffnet den festen
|
||||||
|
Stamm sowie die maximal 16384 Byte große Datei über `PinnedFile`. Besitzer
|
||||||
|
müssen SYSTEM/Administrators bleiben; zusätzliche Leser dürfen nur die
|
||||||
|
festgelegte Lesemaske besitzen. Beide Images müssen zu den Settings passen.
|
||||||
|
Die Prüfung bindet Dateiinhalt und FileID; spätere Rechecks öffnen denselben
|
||||||
|
Namen erneut und verwerfen Austausch oder Änderungen. Fehlerhaft beobachtete
|
||||||
|
Konfigurationen oder fehlgeschlagene Reads stellen alte Autorität nicht wieder
|
||||||
|
her; geänderte Bytes derselben Generation gelten als Fork.
|
||||||
|
|
||||||
|
Im neuen Agenten versucht die passive Heartbeat-Schleife das Setup bei bisher
|
||||||
|
fehlendem Profil erneut. Ein erster Pin benötigt daher nach Quellenvertrag
|
||||||
|
keinen Dienstneustart. Das ist **noch kein VM-Nachweis**. Der Agent schreibt erst
|
||||||
|
nach tatsächlich erfolgreichem `complete` pro Verbindung öffentliche historische
|
||||||
|
`agent-time-sample.json` und `helper-time-sample.json` in sein bestehendes
|
||||||
|
geschütztes State-Verzeichnis. Der Helper-State bleibt unverändert. Root muss
|
||||||
|
diese Originalbelege noch für die tatsächlich installierten Rollen und
|
||||||
|
Konfigurationsbytes prüfen. Ein Statusfile ersetzt kein aktuelles Job-Startgate.
|
||||||
|
|
||||||
|
## Tatsächlich lokal ausgeführt
|
||||||
|
|
||||||
|
- Python-Syntaxprüfung und geschlossene Sourceguards: PASS.
|
||||||
|
- Sechs lokale Vertragsfälle: PASS. Sie prüfen die reinen Referenzbytes,
|
||||||
|
fehlende Paarbelege, falsche Rollen/Images/Geburt/SID/FileID/Policy/Identität,
|
||||||
|
create-only, begrenztes Lesen, Symlink- und Duplicate-JSON-Verweigerung.
|
||||||
|
Positive In-Memory-Fixtures sind ausdrücklich keine native Qualifikation.
|
||||||
|
- Beide erzeugten PowerShell-ASTs mit vorhandenem lokalem Parser: PASS.
|
||||||
|
- Lokale ETS-Integer-/Bool-/String-Reproduktion sowie Objekt-/Arrayreihenfolge:
|
||||||
|
PASS. Der unveränderte Vergleich aus `e6debe5` war unter Windows PowerShell 5
|
||||||
|
unzureichend: ETS-verpacktes `System.Int32=1` konnte im Objektzweig zu `{}`
|
||||||
|
werden. Der exakt übernommene Comparator aus der getrennt geprüften
|
||||||
|
Clockquelle `90c2708c…` rekonstruiert CLR-Skalare vor dem Objektzweig als
|
||||||
|
unadornierte Werte. Der Clockoperator hat diesen Vergleich außerdem tatsächlich
|
||||||
|
gegen den vollständigen alten Livezustand und ETS-Positiv-/Negativfälle
|
||||||
|
geprüft (`82c4ebe7…`). Das ist kein Profilinstallationsnachweis.
|
||||||
|
- Die festgehaltenen öffentlichen Eingänge, rohen Rollenbelege und realen
|
||||||
|
Quell-/Buildbelege werden vom Operator lokal erfolgreich gelesen. Die durch
|
||||||
|
Root tatsächlich ausgeführten neun Linux- und neun Windows-Zeitmodulprüfungen
|
||||||
|
sind über deren Originalbeleg-Hashes und exakte Testnamen angebunden.
|
||||||
|
- `prepare` ohne reale Paarbelege: erwartete Verweigerung ohne angelegten Fall.
|
||||||
|
|
||||||
|
Im ursprünglichen lokalen Quellprüfstand noch nicht ausgeführt: Übertragung,
|
||||||
|
ACL-Änderung, Konfigurationsinstallation,
|
||||||
|
Produktdienst-Laden/Reopen auf der VM, signierte passive Laufzeitabnahme,
|
||||||
|
WebUI-Genehmigung oder RMM-Job. Der damalige Transportausfall nach Notebook-Suspend war später im
|
||||||
|
bestätigten Wartungsfenster behoben. Der vorbereitete Fall `570c7a86…` bleibt
|
||||||
|
unverändert ohne neue Rollenbelege; der tatsächliche neue Paarbeleg ist4887.
|
||||||
|
|
||||||
|
## Tatsächlicher gebundener Vorbereitungsschritt und Transfer
|
||||||
|
|
||||||
|
Lokale Vorbereitung `ad9fd154-b2be-4f5d-9e17-65abb721ceaf` bestanden;
|
||||||
|
Config-SHA256 `2b4a8a7080770304b80e2a665fa5f5ee1ebbd9182e7c80b184e75b114575b42b`,
|
||||||
|
Manifest `0c9a3ffeed490757f7bd8c63d7e2ec28156212945094621f511e20679ce0b3b0`.
|
||||||
|
Der getrennte Bindungsreview des Operators `a8d55b60…` hat bestanden.
|
||||||
|
Erste tatsächliche Transferphase begann nach `2026-11-15T15:27:41Z`.
|
||||||
|
Der fixierte Controller wurde einmalig übertragen und separat hashgeprüft;
|
||||||
|
Originalantwort `stage-reply.json` im genannten privaten lokalen Fall,
|
||||||
|
SHA256 `29f7654f766ebb53045832bb8c5ed6c83d2cbd96e0a5e1ce6df494cef0c026e6`.
|
||||||
|
Noch kein Konfigurationsinstallations- oder Laufzeitnachweis aus diesem Schritt.
|
||||||
|
|
||||||
|
## Tatsächliche Installation: Teilzustand, nicht abgeschlossen
|
||||||
|
|
||||||
|
Der einmalige Installationsaufruf begann nach `2026-11-15T15:28:18Z`.
|
||||||
|
Die VM hielt vor der ersten Erstellung die Originaluntergrenze
|
||||||
|
`2026-11-15T15:28:24.1309868Z` im Intent fest. Der Bootstrap endete mit
|
||||||
|
`IOException` an Controllerzeile294, dem einzigen
|
||||||
|
`[IO.File]::Move($staged,$target)`. Der ursprüngliche sichere Fehlerbeleg
|
||||||
|
`windows-client/system-pipe-upgrade/remote-error-b01d395c-9141-4bc6-ad70-1b67fb936881.json`
|
||||||
|
enthält Exit1, Fehlerklasse und Zeile, keinen privaten Fehlertext. Die genaue
|
||||||
|
I/O-Ursache ist damit noch nicht geklärt; es wird kein Sharing-/ACL- oder
|
||||||
|
Antivirusproblem als bewiesen ausgegeben. Es gab keinen zweiten Installversuch.
|
||||||
|
|
||||||
|
Ein eigener ausschließlich lesender Originalaufruf begann nach
|
||||||
|
`2026-11-15T15:28:37Z` und bestand. Originalantwort im privaten Fall
|
||||||
|
`ad9fd154-b2be-4f5d-9e17-65abb721ceaf`:
|
||||||
|
`read-51eea530-4155-42d7-9053-1008e84059b6-reply.json`, SHA256
|
||||||
|
`93143fc05e7c814e9b164cd322abd411eee0dedcb485fbb5547a1db8f1975cd2`.
|
||||||
|
Die feste Zieldatei ist **nicht vorhanden**. Der ursprüngliche Intent, aktive
|
||||||
|
NoRetry-Marker, Directory-ACL-Intent und dessen Abschluss sowie der
|
||||||
|
Publish-Intent sind vorhanden; ein `result.json` fehlt. Die nur für diesen
|
||||||
|
Ordner erlaubten Service-Leserechte wurden somit gesetzt, die Konfiguration
|
||||||
|
wurde nicht veröffentlicht. Originale FileIDs/Hashes/PKI-Metadaten, laufende
|
||||||
|
Agent-/Helper-Prozessgenerationen, Jobfreiheit und Journalzeugen bestanden die
|
||||||
|
lesende Erhaltungsprüfung.
|
||||||
|
|
||||||
|
Der Teilzustand bleibt unverändert; kein Retry, Rollback, Dienstwechsel oder
|
||||||
|
RMM-Job wurde ausgeführt. Der passive Zeit-Collector wurde ausdrücklich
|
||||||
|
**nicht** gestartet. `clock_runtime_qualified=false` bleibt bestehen. Nach dem
|
||||||
|
bestätigten Wartungsfenster bis15:30UTC erfolgen keine weiteren VM-Aufrufe.
|
||||||
|
Die gesonderte serverseitige `agent.update`-Inventar-Constraintkorrektur und
|
||||||
|
anschließend frische Heartbeats/ACKs sowie echte signierte Zeitbelege bleiben
|
||||||
|
getrennt zu prüfen. Eine spätere Fortsetzung benötigt zuerst eine lesende
|
||||||
|
Ursachenklärung und einen konkret geprüften Vertrag für den ursprünglichen
|
||||||
|
Teilfall; ein neuer Fall darf diesen Marker nicht umgehen.
|
||||||
|
|
||||||
|
## Sharing-Verletzung bei der Konsolenfinalisierung
|
||||||
|
|
||||||
|
Die VM meldete beim gesonderten Konsolenabschluss für `File.Move` den HRESULT
|
||||||
|
`0x80070020` (Win32 32, Sharing-Verletzung). Der Helper hielt seit seinem
|
||||||
|
Start einen Lesehandle auf `C:\ProgramData\RustDiscoverySystem`. Der Code
|
||||||
|
erlaubte ausschließlich `FILE_SHARE_READ`. Beim Verschieben des Kandidaten
|
||||||
|
aus dem Bootstrap-Verzeichnis öffnet Windows den **Zielordner** für
|
||||||
|
`FILE_ADD_FILE`. Dieser Zugriff kollidiert mit dem gehaltenen Handle. Die
|
||||||
|
native Fehlermeldung nennt keine Prozess-ID. Die Zuordnung folgt aus den
|
||||||
|
Öffnungsmodi des Helpers und der dokumentierten Windows-Rename-Operation.
|
||||||
|
[Windows-Rename](https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-fsa/87f86c9b-6c2a-4803-84b7-131a74a434fa)
|
||||||
|
· [Windows-Sharingprüfung](https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-fsa/8c0e3f4f-0729-49f4-a14d-7f7add593819)
|
||||||
|
|
||||||
|
Im korrigierten Quellstand öffnen der Helper, der Agent beim Laden des
|
||||||
|
Peer-Pins und die Zeitprüfung genau diesen öffentlichen Stamm über
|
||||||
|
`PinnedFile::open_read_shared`. Der Lesehandle lässt auch einen berechtigten
|
||||||
|
Schreibzugriff auf den Ordner zu. Weiterhin sperrt er das Löschen und
|
||||||
|
Umbenennen des Ordners. Über Kinddateien entscheiden deren eigene DACL und
|
||||||
|
gehaltene Datei-Pins. Einstellungen, Peer-Pin und Zeitprofildatei werden
|
||||||
|
weiterhin mit geteiltem Lesezugriff geöffnet. Die vorhandenen Prüfungen von
|
||||||
|
Owner, DACL, Reparse-Attributen und Dateiidentität laufen bei jedem Pin.
|
||||||
|
|
||||||
|
Workspace-Formatprüfung, Cargo-Check aller Windows-Ziele mit `system-helper`
|
||||||
|
und Clippy mit `-D warnings` bestanden im Windows-Clock-Builder offline.
|
||||||
|
Beide x86-64-PE-Debugprogramme wurden dort gelinkt. Agent-SHA-256
|
||||||
|
`b5fe5ea55c857415c979f06851e54a2d1fbe4cbfe2fe7ad1660e209aae3fa583`,
|
||||||
|
Helper-SHA-256 `c6b41b0867df23f2c04c2550a39678672ef66d35a4b41215769265924deaf8a1`.
|
||||||
|
Der erste Buildversuch endete in einem anderen Builder wegen fehlendem
|
||||||
|
`widl`. Die Windows-VM hat diese Änderungen bisher weder ausgeführt noch
|
||||||
|
durch erneute Profilveröffentlichung und zwei passive Rollenbelege bestätigt.
|
||||||
|
|
||||||
|
### Optimiertes Release-Paar für die nächste Windows-Abnahme
|
||||||
|
|
||||||
|
Am 15. November 2026 wurden Agent und Helper aus Commit
|
||||||
|
`e952698f5e2bab808e816858a727ef40347f6142` auf dem Entwicklungsrechner
|
||||||
|
gebaut. Der Quellstand kam aus einem schreibgeschützt eingebundenen Git-Archiv.
|
||||||
|
Der unabhängige Vergleich nach dem Build bestätigte alle 708 Quelldateien
|
||||||
|
gegen Git-Tree `708c88b4d6a92d9f9cbebc70146250062532f45f`.
|
||||||
|
Rust 1.99.1 und Cargo 1.99.1 liefen im vorhandenen Clock-Builder ohne Netzwerk.
|
||||||
|
Der ausgeführte Befehl war
|
||||||
|
|
||||||
|
```sh
|
||||||
|
cargo build --release --target x86_64-pc-windows-gnu --features system-helper --locked --offline -p rmm-agent-windows --bin rmm-agent-windows --bin rmm-helper-windows
|
||||||
|
```
|
||||||
|
|
||||||
|
| Datei | Bytes | SHA-256 |
|
||||||
|
| --- | ---: | --- |
|
||||||
|
| `rmm-agent-windows.exe` | 23 543 434 | `2dd64e743431ad4c8244e43bef30c4c1c2123ad26a094853811a418626bb87e7` |
|
||||||
|
| `rmm-helper-windows.exe` | 17 191 183 | `9c313c07a20c82797cbd8c8ca7c289c1d227b0bd6a4a686f38c4db3bbdded199` |
|
||||||
|
|
||||||
|
Beide Dateien haben einen ausführbaren PE32+-Header mit AMD64-Maschinenkennung
|
||||||
|
`0x8664`. Der private Originalbeleg `profile-share-release-e952698/receipt.json`
|
||||||
|
hat SHA-256 `1ec1ec472043e8673e5b92f9029fd809434451d9452e3b24bbd85b21f017017d`.
|
||||||
|
Das erste Prüfskript traf auf dem Notebook auf eine ältere Python-Hashlib ohne
|
||||||
|
`file_digest`. Die Nachprüfung lief mit SHA-256 über dieselben fertigen Bytes.
|
||||||
|
Die Installation dieses Paars und die native Profilveröffentlichung mit den
|
||||||
|
zu diesen Binaries passenden Zeitprofilbindungen stehen aus.
|
||||||
|
|
||||||
|
## Unabhängiger lokaler Review des Move-Fehlers und fester Diagnosepfad
|
||||||
|
|
||||||
|
Der nachfolgende Review liest ausschließlich Quellen und vorhandene öffentliche
|
||||||
|
Originalbelege auf dem Entwicklungsrechner. Kein Gast-/Serverzugriff, keine
|
||||||
|
Installation, kein Retry und keine Freigabe wurden dabei ausgeführt.
|
||||||
|
|
||||||
|
Belegt ist der Ablauf bis zum Publish-Intent mit Kandidathash
|
||||||
|
`2b4a8a7080770304b80e2a665fa5f5ee1ebbd9182e7c80b184e75b114575b42b`,
|
||||||
|
1177Bytes, Volume9815088561147542064 und FileID6d990300000003000000000000000000.
|
||||||
|
Der spätere originale Read93143fc0… belegt das fehlende Ziel und fehlendes Resultat.
|
||||||
|
Er fragt jedoch die Kandidatdatei selbst nicht ab. Ihr aktueller Bestand ist
|
||||||
|
somit **nicht** nachgewiesen. Original-rootSDDL im Intent, ACL-done-SDDL und spätere
|
||||||
|
rootSDDL sind bytegleich: die ACL-Phase wurde ausgeführt, ohne effektive Rechte
|
||||||
|
zu ändern. Bestehende NoRetry-Marker bleiben bestehen.
|
||||||
|
|
||||||
|
Die genaue Ursache der IOException ist mit diesen Belegen nicht bestimmbar.
|
||||||
|
Der alte Fehlerbeleg enthält weder HRESULT noch nativen Fehlercode. Die statisch
|
||||||
|
geprüften WriteBytes-, FileIdentity- und FileVolume-Handles werden in `finally`
|
||||||
|
geschlossen; ein eigener Handleleak ist daraus nicht belegt. Das rechtfertigt
|
||||||
|
weder eine Sharing-Lockerung noch Dienststopp, ACL-Änderung, Antivirusausnahme,
|
||||||
|
Copy/Delete-Fallback oder erneuten Move. Microsoft beschreibt für
|
||||||
|
[File.Move](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.move)
|
||||||
|
mehrere IOException-Ursachen; die Regeln für vorhandene Handles stehen getrennt
|
||||||
|
in [CreateFile](https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-createfilew).
|
||||||
|
Sharing, Defender oder ein konkreter Win32-Code bleiben hier ausdrücklich
|
||||||
|
Hypothesen. Der ursprüngliche HRESULT darf aus späteren Lesefehlern nicht
|
||||||
|
rückwirkend abgeleitet werden.
|
||||||
|
|
||||||
|
Der bestehende Pythonoperator hat deshalb einen **separaten, ausschließlich
|
||||||
|
lesenden** Originalfallpfad `diagnose-partial` erhalten. Er bindet ausschließlich
|
||||||
|
Fallad9fd154-b2be-4f5d-9e17-65abb721ceaf, dessen Manifest0c9a3ffe…,
|
||||||
|
Originalgeneratora8d55b60…, Originalcontrollerd8b4fd4f… und Konfigurationshash2b4a….
|
||||||
|
Die vorhandenen Marker und Originaldateien werden nicht geändert. `load_case`
|
||||||
|
wird absichtlich nicht verwendet: dessen Generatorbindung darf nicht auf die
|
||||||
|
neue Quelle umgedeutet werden. Ebenso wird keine neue Skript-SHA als ursprüngliche
|
||||||
|
`request.script_sha256` ausgegeben. Der neue Reader hat eine eigene Source-SHA,
|
||||||
|
die der kleine In-Memory-Launcher vor der Ausführung prüft; genau ausgeführte
|
||||||
|
Readerbytes, Intent, rohe Antwort und separater Receipt werden ausschließlich
|
||||||
|
in einem neuen lokalen700/600-Diagnosefall gespeichert.
|
||||||
|
|
||||||
|
Geplanter Aufruf, **hier nicht ausgeführt**, erst nach erneut ausdrücklich
|
||||||
|
bestätigtem Zugang und dessen erfolgreichem Readback:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
python3 /home/kevin/Schreibtisch/Coding/rust-discovery-signed-clock/deploy/windows/time_profile_config.py diagnose-partial
|
||||||
|
```
|
||||||
|
|
||||||
|
Kein `--case`: der Reader akzeptiert keine andere Fall-ID oder frei wählbare
|
||||||
|
Pfade. Die lokalen Originalbelege liegen weiterhin im Agent-Updater-Worktree.
|
||||||
|
Die geschützte aktuelle Zugangskonfiguration muss noch mindestens60s zulassen;
|
||||||
|
sonst erfolgt kein SSHaufruf. Native PowerShell-AST-/VM-Ausführung dieses neuen
|
||||||
|
Readers sind noch offen. Er enthält keine Publish-/ACL-/Serviceoperation und
|
||||||
|
fragt weder Uhrqualität noch Dienst-Snapshot ab.
|
||||||
|
|
||||||
|
Der Reader liefert nur aktuelle Kandidat-/Zielidentität, Größe, Hash, DACLhash,
|
||||||
|
Attribute und Zeiten sowie feste Originalmarker/active-Bindung und Root-SDDL.
|
||||||
|
Aktuelle Lesefehler werden mit Exceptiontyp/HRESULT und nur bei passender
|
||||||
|
HRESULT-Facility mit Win32-Code aufgezeichnet, ohne freien Fehlertext. Diese
|
||||||
|
Nummern gehören ausschließlich zum **neuen Leseversuch**. Er setzt immer
|
||||||
|
`old_move_hresult_unknown=true`, `retry_authorized=false`,
|
||||||
|
`installation_verified=false` und `clock_runtime_qualified=false`.
|
||||||
|
|
||||||
|
Das Ergebnis ist Grundlage einer späteren Entscheidung, keine Retryerlaubnis:
|
||||||
|
|
||||||
|
- Kandidat unverändert und Ziel fehlt: Veröffentlichung weiterhin nicht erfolgt;
|
||||||
|
im nächsten aktiven Wartungsfenster anhand des Originalzustands mit einem
|
||||||
|
überprüften Finalisierungsbefehl fertigstellen. Das MVP-/Profilvorhaben ist
|
||||||
|
bereits beauftragt; dafür keine pauschale zusätzliche Chatgenehmigung verlangen.
|
||||||
|
- Ziel vorhanden: weder Move noch Install erneut aufrufen; zuerst Ziel-/Kandidat-
|
||||||
|
FileID-/Hash-/ACLbindung und tatsächliche Laufzeitwirkung getrennt beurteilen.
|
||||||
|
- Fehlender/veränderter Kandidat, widersprüchliche Marker, andere Dateiidentität
|
||||||
|
oder Lesefehler: Teilzustand erhalten, keine automatische Rekonstruktion,
|
||||||
|
Löschung oder Rechte-/Dienständerung.
|
||||||
|
|
||||||
|
Lokal tatsächlich bestanden: Pythoncompile, bestehende Sourceguards und acht
|
||||||
|
Vertragsfälle, davon zwei neue für den geschlossenen Reader und seine exakte
|
||||||
|
Source-/Intent-/Receiptbindung ohne Legacy-Hashadoption. Der Transport ist dabei
|
||||||
|
vollständig gemockt; dies ist kein nativer Befund. Die Kontrollbelege des alten
|
||||||
|
fehlgeschlagenen Installationsfalls bleiben bytegleich erhalten. Ein konkreter
|
||||||
|
Publikationsfix wurde mangels belegter nativer Fehlerursache nicht erfunden.
|
||||||
|
|
||||||
|
## Nachlese durch die Bedienperson auf der Windows-VM
|
||||||
|
|
||||||
|
In der administrativen VM-Konsole konnte die Bedienperson den Kandidaten
|
||||||
|
`time-attestation.candidate.json` lesen. SHA-256 stimmte mit dem im
|
||||||
|
Publish-Intent hinterlegten Wert `2b4a8a7080770304b80e2a665fa5f5ee1ebbd9182e7c80b184e75b114575b42b`
|
||||||
|
überein. Für den festen Zielpfad unter `RustDiscoverySystem` meldete
|
||||||
|
PowerShell `ObjectNotFound`. Dieser Konsolenbefund ergänzt den früheren
|
||||||
|
Readback um den Inhalt des verbliebenen Kandidaten. FileID, DACL und
|
||||||
|
Dienstgeneration wurden bei dieser Konsolenabfrage nicht erfasst.
|
||||||
|
|
||||||
|
Für die Fortsetzung an derselben VM-Konsole liegt
|
||||||
|
[`Complete-OriginalTimeProfile.ps1`](../deploy/windows/Complete-OriginalTimeProfile.ps1)
|
||||||
|
bereit. Der Befehl übernimmt die Prüffunktionen aus den SHA-256-geprüften
|
||||||
|
Bytes des bereits installierten Controllers. Vor der Veröffentlichung prüft er
|
||||||
|
die ursprüngliche Datei-ID und das Volume, den Inhalt, die DACL, die
|
||||||
|
ursprünglichen Marker und beide laufenden Dienstgenerationen. Er hält die
|
||||||
|
beiden Prozesshandles während der Veröffentlichung offen. Ein exklusiv
|
||||||
|
erstellter zusätzlicher Marker verhindert eine doppelte Ausführung.
|
||||||
|
|
||||||
|
Nach der Verschiebung an den festen Zielpfad vergleicht das Skript die
|
||||||
|
Dateiidentität und die Dienstzustände erneut. Bei einem neuen Move-Fehler erfasst
|
||||||
|
es Fehlerklasse und HRESULT für diesen Aufruf. Ein erneuter Start trifft auf
|
||||||
|
den Abschlussmarker oder den vorhandenen Zielpfad und beendet sich. Das
|
||||||
|
Ergebnis einer erfolgreichen Veröffentlichung hält die separate
|
||||||
|
Laufzeitprüfung der beiden Dienstrollen ausdrücklich offen.
|
||||||
|
|
||||||
|
Lokal geprüft wurden die PowerShell-Syntax, die Bindung an die gespeicherten
|
||||||
|
Originalbelege und der Vergleich mit der tatsächlichen Kandidatenidentität.
|
||||||
|
Eine veränderte FileID wurde im lokalen Vergleich abgewiesen. Die Ausführung
|
||||||
|
des Abschlussbefehls auf der VM und die anschließende Zeitprüfung stehen aus.
|
||||||
|
|
||||||
|
## Ergebnis vom Konsolenschritt automatisch abholen
|
||||||
|
|
||||||
|
Für den vorbereiteten Profilabschluss steht `Open-TimeProfileReceiptWindow.ps1`
|
||||||
|
zur Verfügung. Die Bedienperson startet es auf der Windows-VM. Das Skript prüft
|
||||||
|
die beiden Downloads gegen feste SHA-256-Werte, öffnet den vorhandenen
|
||||||
|
Reverse-SSH-Transport und führt den festen Abschluss lokal aus. Die
|
||||||
|
Weiterleitung auf dem Server ist an `127.0.0.1:22240` gebunden. Auf der VM
|
||||||
|
endet sie an einem temporären Loopback-Port. Der Prozess sendet dort den
|
||||||
|
Abschlussstatus und die öffentlichen Belege der beiden Zeitdienstrollen.
|
||||||
|
Er liest keine Befehle vom Socket. Die Gast-Kontofrist und die Aufgabenplanung
|
||||||
|
werden nicht geändert. Strg+C oder zwölf Minuten beenden das Vordergrundfenster.
|
||||||
|
|
||||||
|
Die serverseitige Frist für den vorhandenen Transportschlüssel und der aktive
|
||||||
|
Abschalttimer wurden für den 15. November 2026, 18:00 Uhr MEZ, geprüft.
|
||||||
|
Beim Bereitstellen wurden der PowerShell-Parser, die Downloadhashes, die
|
||||||
|
bestehenden Quellprüfungen und die sechs lokalen Prüffälle für die Zeitbelege
|
||||||
|
ausgeführt. Ein Ergebnis von der VM liegt bei Bereitstellung noch nicht vor.
|
||||||
|
|
||||||
|
Der Ergebnisempfänger auf dem permanenten Server wurde anschließend gestartet.
|
||||||
|
Seine Anfangsprüfung des laufenden Gateways und der gespeicherten
|
||||||
|
Windows-Gerätebindung war erfolgreich. Der Server fragt den Loopback-Port
|
||||||
|
nur bei vorhandenem SSH-Listener ab und legt eingehende Belege im privaten
|
||||||
|
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.
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
-- Passive agent-update observations share the existing tenant/device-bound
|
||||||
|
-- ingest path. Preserve both base scopes and every existing row/RLS/FK.
|
||||||
|
-- SQLx applies this file transactionally and records its normal checksum.
|
||||||
|
SET LOCAL lock_timeout = '3s';
|
||||||
|
SET LOCAL statement_timeout = '15s';
|
||||||
|
ALTER TABLE observations DROP CONSTRAINT observations_source_id_check;
|
||||||
|
ALTER TABLE observations ADD CONSTRAINT observations_source_id_check
|
||||||
|
CHECK (source_id IN ('linux.base', 'windows.base', 'agent.update')) NOT VALID;
|
||||||
|
ALTER TABLE observations VALIDATE CONSTRAINT observations_source_id_check;
|
||||||
Reference in New Issue
Block a user