Compare commits
14
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b4dbeba9c6 | ||
|
|
68c1b11d0c | ||
|
|
e7dcad9c10 | ||
|
|
900e19d471 | ||
|
|
fc2d01d3c4 | ||
|
|
330087c050 | ||
|
|
3d152aee41 | ||
|
|
7cf34c267d | ||
|
|
1d8cdda1ab | ||
|
|
5a1de712cf | ||
|
|
0be13da6d7 | ||
|
|
c4efe8a4b4 | ||
|
|
bbdfe59380 | ||
|
|
548996eb36 |
@@ -7,6 +7,7 @@ use rmm_agent_core::{
|
||||
};
|
||||
use rmm_domain::jobs::hash;
|
||||
use serde::{Deserialize, Serialize, de::DeserializeOwned};
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::{
|
||||
ffi::c_void,
|
||||
fs::File,
|
||||
@@ -29,7 +30,13 @@ use windows_sys::Win32::{
|
||||
};
|
||||
|
||||
pub const HELPER_SERVICE: &str = "RmmDiscoverySystemHelper";
|
||||
pub const PIPE_NAME: &str = r"\\.\pipe\RustDiscovery-System-v1";
|
||||
// Framing v2 is deliberately a separate endpoint. Old peers cannot send a
|
||||
// v1 call to this server or interpret the drain receipt as another reply.
|
||||
pub const PIPE_NAME: &str = r"\\.\pipe\RustDiscovery-System-v2";
|
||||
const FRAME_TAG: [u8; 8] = *b"RDPIPC02";
|
||||
const DRAIN_TAG: [u8; 8] = *b"RDPACK02";
|
||||
const FRAME_HEADER_LEN: usize = 12;
|
||||
const DRAIN_RECEIPT_LEN: usize = 56;
|
||||
pub const FRAME_LIMIT: usize = 1024 * 1024;
|
||||
pub const CLIENT_PIPE_RIGHTS: u32 = 0x0012_0083; // data R/W, attributes R, RC, synchronize; no bit4
|
||||
const READ_MASK: u32 = 0x0012_00a9;
|
||||
@@ -44,6 +51,7 @@ pub enum Stage {
|
||||
ClientSendFrame,
|
||||
ClientReadReply,
|
||||
ClientReplyBinding,
|
||||
ClientDrainReceipt,
|
||||
ClientReport,
|
||||
ServerConnect,
|
||||
ServerReadHeader,
|
||||
@@ -54,6 +62,7 @@ pub enum Stage {
|
||||
ServerCallBinding,
|
||||
ServerRecheckPeer,
|
||||
ServerReply,
|
||||
ServerDrainReceipt,
|
||||
Unclassified,
|
||||
}
|
||||
impl Stage {
|
||||
@@ -66,6 +75,7 @@ impl Stage {
|
||||
Self::ClientSendFrame => "client_send_frame",
|
||||
Self::ClientReadReply => "client_read_reply",
|
||||
Self::ClientReplyBinding => "client_reply_binding",
|
||||
Self::ClientDrainReceipt => "client_drain_receipt",
|
||||
Self::ClientReport => "client_report",
|
||||
Self::ServerConnect => "server_connect",
|
||||
Self::ServerReadHeader => "server_read_header",
|
||||
@@ -76,6 +86,7 @@ impl Stage {
|
||||
Self::ServerCallBinding => "server_call_binding",
|
||||
Self::ServerRecheckPeer => "server_recheck_peer",
|
||||
Self::ServerReply => "server_reply",
|
||||
Self::ServerDrainReceipt => "server_drain_receipt",
|
||||
Self::Unclassified => "unclassified",
|
||||
}
|
||||
}
|
||||
@@ -123,6 +134,8 @@ fn known_code(text: &str) -> Option<&'static str> {
|
||||
"HELPER_FRAME_CAPACITY",
|
||||
"HELPER_FRAME_EMPTY",
|
||||
"HELPER_FRAME_LENGTH",
|
||||
"HELPER_FRAME_VERSION",
|
||||
"HELPER_DRAIN_RECEIPT",
|
||||
"HELPER_HANDLE",
|
||||
"HELPER_IMAGE_PARENT",
|
||||
"HELPER_IMAGE_SIZE",
|
||||
@@ -1189,27 +1202,60 @@ fn encode(value: &impl Serialize) -> Result<Vec<u8>> {
|
||||
ensure!(!writer.0.is_empty(), "HELPER_FRAME_EMPTY");
|
||||
Ok(writer.0)
|
||||
}
|
||||
fn send(pipe: HANDLE, value: &impl Serialize, deadline: Instant) -> Result<()> {
|
||||
let mut bytes = encode(value)?;
|
||||
let mut header = u32::try_from(bytes.len())?.to_be_bytes();
|
||||
transfer(pipe, &mut header, true, deadline)?;
|
||||
transfer(pipe, &mut bytes, true, deadline)
|
||||
fn frame_header(len: usize) -> Result<[u8; FRAME_HEADER_LEN]> {
|
||||
ensure!((1..=FRAME_LIMIT).contains(&len), "HELPER_FRAME_LENGTH");
|
||||
let mut header = [0; FRAME_HEADER_LEN];
|
||||
header[..8].copy_from_slice(&FRAME_TAG);
|
||||
header[8..].copy_from_slice(&u32::try_from(len)?.to_be_bytes());
|
||||
Ok(header)
|
||||
}
|
||||
fn frame_length(header: [u8; 4]) -> Result<usize> {
|
||||
let len = u32::from_be_bytes(header) as usize;
|
||||
fn send_bytes(pipe: HANDLE, bytes: &mut [u8], deadline: Instant) -> Result<()> {
|
||||
let mut header = frame_header(bytes.len())?;
|
||||
transfer(pipe, &mut header, true, deadline)?;
|
||||
transfer(pipe, bytes, true, deadline)
|
||||
}
|
||||
fn send(pipe: HANDLE, value: &impl Serialize, deadline: Instant) -> Result<()> {
|
||||
send_bytes(pipe, &mut encode(value)?, deadline)
|
||||
}
|
||||
fn frame_length(header: [u8; FRAME_HEADER_LEN]) -> Result<usize> {
|
||||
ensure!(header[..8] == FRAME_TAG, "HELPER_FRAME_VERSION");
|
||||
let len = u32::from_be_bytes(header[8..].try_into()?) as usize;
|
||||
ensure!((1..=FRAME_LIMIT).contains(&len), "HELPER_FRAME_LENGTH");
|
||||
Ok(len)
|
||||
}
|
||||
fn length(pipe: HANDLE, deadline: Instant) -> Result<usize> {
|
||||
let mut header = [0u8; 4];
|
||||
let mut header = [0u8; FRAME_HEADER_LEN];
|
||||
transfer(pipe, &mut header, false, deadline)?;
|
||||
frame_length(header)
|
||||
}
|
||||
fn body<T: DeserializeOwned>(pipe: HANDLE, len: usize, deadline: Instant) -> Result<T> {
|
||||
fn body_bytes(pipe: HANDLE, len: usize, deadline: Instant) -> Result<Vec<u8>> {
|
||||
ensure!((1..=FRAME_LIMIT).contains(&len), "HELPER_FRAME_LENGTH");
|
||||
let mut bytes = vec![0u8; len];
|
||||
transfer(pipe, &mut bytes, false, deadline)?;
|
||||
Ok(serde_json::from_slice(&bytes)?)
|
||||
Ok(bytes)
|
||||
}
|
||||
fn body<T: DeserializeOwned>(pipe: HANDLE, len: usize, deadline: Instant) -> Result<T> {
|
||||
Ok(serde_json::from_slice(&body_bytes(pipe, len, deadline)?)?)
|
||||
}
|
||||
// This fixed-size receipt only acknowledges receipt of these transport bytes.
|
||||
// It never acknowledges durable evidence, clears state, or permits an effect.
|
||||
fn drain_receipt(challenge: Uuid, reply_bytes: &[u8]) -> [u8; DRAIN_RECEIPT_LEN] {
|
||||
let mut receipt = [0; DRAIN_RECEIPT_LEN];
|
||||
receipt[..8].copy_from_slice(&DRAIN_TAG);
|
||||
receipt[8..24].copy_from_slice(challenge.as_bytes());
|
||||
receipt[24..].copy_from_slice(&Sha256::digest(reply_bytes));
|
||||
receipt
|
||||
}
|
||||
fn verify_drain_receipt(
|
||||
receipt: &[u8; DRAIN_RECEIPT_LEN],
|
||||
challenge: Uuid,
|
||||
reply_bytes: &[u8],
|
||||
) -> Result<()> {
|
||||
ensure!(
|
||||
*receipt == drain_receipt(challenge, reply_bytes),
|
||||
"HELPER_DRAIN_RECEIPT"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub struct Server {
|
||||
@@ -1305,13 +1351,24 @@ impl Server {
|
||||
peer.check().context(Stage::ServerRecheckPeer)?;
|
||||
Ok(Some(Received { call, peer }))
|
||||
}
|
||||
pub fn reply(&self, value: &Reply) -> Result<()> {
|
||||
send(
|
||||
self.pipe.as_raw_handle(),
|
||||
value,
|
||||
Instant::now() + Duration::from_secs(5),
|
||||
)
|
||||
.context(Stage::ServerReply)
|
||||
pub fn reply(&self, value: &Reply, peer: &mut PeerProof) -> Result<()> {
|
||||
// Do not disconnect after WriteFile merely copied bytes into a pipe
|
||||
// buffer. Wait for a receipt from the same fully pinned peer within
|
||||
// the original reply deadline, without an unbounded FlushFileBuffers.
|
||||
let deadline = Instant::now() + Duration::from_secs(5);
|
||||
peer.check().context(Stage::ServerRecheckPeer)?;
|
||||
let mut bytes = encode(value).context(Stage::ServerReply)?;
|
||||
send_bytes(self.pipe.as_raw_handle(), &mut bytes, deadline).context(Stage::ServerReply)?;
|
||||
let mut receipt = [0; DRAIN_RECEIPT_LEN];
|
||||
transfer(self.pipe.as_raw_handle(), &mut receipt, false, deadline)
|
||||
.context(Stage::ServerDrainReceipt)?;
|
||||
verify_drain_receipt(&receipt, value.challenge, &bytes)
|
||||
.context(Stage::ServerDrainReceipt)?;
|
||||
peer.check().context(Stage::ServerRecheckPeer)?;
|
||||
if Instant::now() >= deadline {
|
||||
return Err(anyhow::anyhow!("HELPER_PIPE_TIMEOUT")).context(Stage::ServerDrainReceipt);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub fn disconnect(&self) {
|
||||
unsafe {
|
||||
@@ -1345,7 +1402,9 @@ pub fn exchange(pin: &Pin, call: &Call, timeout: Duration) -> Result<Reply> {
|
||||
.context(Stage::ClientHelperPeer)?;
|
||||
send(pipe.as_raw_handle(), call, deadline).context(Stage::ClientSendFrame)?;
|
||||
let len = length(pipe.as_raw_handle(), deadline).context(Stage::ClientReadReply)?;
|
||||
let reply: Reply = body(pipe.as_raw_handle(), len, deadline).context(Stage::ClientReadReply)?;
|
||||
let reply_bytes =
|
||||
body_bytes(pipe.as_raw_handle(), len, deadline).context(Stage::ClientReadReply)?;
|
||||
let reply: Reply = serde_json::from_slice(&reply_bytes).context(Stage::ClientReadReply)?;
|
||||
peer.check().context(Stage::ClientHelperPeer)?;
|
||||
if !(reply.schema_version == 1
|
||||
&& reply.challenge == call.challenge
|
||||
@@ -1366,6 +1425,11 @@ pub fn exchange(pin: &Pin, call: &Call, timeout: Duration) -> Result<Reply> {
|
||||
) {
|
||||
return Err(anyhow::anyhow!("HELPER_REPLY_OPERATION")).context(Stage::ClientReplyBinding);
|
||||
}
|
||||
// Only a complete, authenticated, bound and operation-checked reply gets
|
||||
// this receipt. Hash the received bytes, never a JSON re-serialization.
|
||||
let mut receipt = drain_receipt(call.challenge, &reply_bytes);
|
||||
transfer(pipe.as_raw_handle(), &mut receipt, true, deadline)
|
||||
.context(Stage::ClientDrainReceipt)?;
|
||||
Ok(reply)
|
||||
}
|
||||
|
||||
@@ -1388,12 +1452,21 @@ mod tests {
|
||||
#[test]
|
||||
fn untrusted_lengths_are_rejected_before_body_allocation() {
|
||||
for n in [0, (FRAME_LIMIT + 1) as u32, u32::MAX] {
|
||||
assert!(frame_length(n.to_be_bytes()).is_err());
|
||||
let mut header = [0; FRAME_HEADER_LEN];
|
||||
header[..8].copy_from_slice(&FRAME_TAG);
|
||||
header[8..].copy_from_slice(&n.to_be_bytes());
|
||||
assert!(frame_length(header).is_err());
|
||||
assert!(frame_header(n as usize).is_err());
|
||||
}
|
||||
assert_eq!(
|
||||
frame_length((FRAME_LIMIT as u32).to_be_bytes()).unwrap(),
|
||||
FRAME_LIMIT
|
||||
);
|
||||
let header = frame_header(FRAME_LIMIT).unwrap();
|
||||
assert_eq!(frame_length(header).unwrap(), FRAME_LIMIT);
|
||||
// Neither a v1 length prefix nor another framing version is accepted.
|
||||
let mut old = [0; FRAME_HEADER_LEN];
|
||||
old[..4].copy_from_slice(&1u32.to_be_bytes());
|
||||
assert!(frame_length(old).is_err());
|
||||
let mut foreign = header;
|
||||
foreign[7] = b'1';
|
||||
assert!(frame_length(foreign).is_err());
|
||||
}
|
||||
#[test]
|
||||
fn protocol_does_not_accept_a_shell_operation() {
|
||||
@@ -1417,6 +1490,22 @@ mod tests {
|
||||
assert_eq!(diagnostic(&caller).code, "UNCLASSIFIED_IO_OR_CODEC");
|
||||
let remote = remote_denial(Stage::ClientReplyBinding, "caller-payload-private-marker");
|
||||
assert_eq!(diagnostic(&remote).code, "UNCLASSIFIED_REMOTE_DENIAL");
|
||||
let challenge = Uuid::from_u128(1);
|
||||
let raw = br#"{"a":1,"b":2}"#;
|
||||
let receipt = drain_receipt(challenge, raw);
|
||||
assert!(verify_drain_receipt(&receipt, challenge, raw).is_ok());
|
||||
// Same JSON meaning, different exact bytes must not drain this reply.
|
||||
assert!(verify_drain_receipt(&receipt, challenge, br#"{"b":2,"a":1}"#).is_err());
|
||||
assert!(verify_drain_receipt(&receipt, Uuid::from_u128(2), raw).is_err());
|
||||
for offset in [0, 7, 8, 23, 24, DRAIN_RECEIPT_LEN - 1] {
|
||||
let mut changed = receipt;
|
||||
changed[offset] ^= 1;
|
||||
let error = verify_drain_receipt(&changed, challenge, raw)
|
||||
.unwrap_err()
|
||||
.context(Stage::ServerDrainReceipt);
|
||||
assert_eq!(diagnostic(&error).code, "HELPER_DRAIN_RECEIPT");
|
||||
assert_eq!(diagnostic(&error).stage, "server_drain_receipt");
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn reconfigured_service_cannot_adopt_an_old_running_identity() {
|
||||
|
||||
@@ -1179,7 +1179,7 @@ unsafe extern "system" fn service_main(_: u32, _: *mut *mut u16) {
|
||||
match server.receive() {
|
||||
Ok(Some(mut incoming)) => {
|
||||
let reply = helper.handle(&incoming.call, &mut incoming.peer);
|
||||
if let Err(error) = server.reply(&reply) {
|
||||
if let Err(error) = server.reply(&reply, &mut incoming.peer) {
|
||||
if let Some(sync) = &mut helper.sync {
|
||||
sync.close();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Local CreateNew correction of the public recovery hash function alias clash.
|
||||
|
||||
The User's H/Get-History error occurred in the old pre-effect case/config guard.
|
||||
Keep the same console case and untouched original files. No target/server call,
|
||||
alias mutation or retry of an effect; the same case-absence guard still applies.
|
||||
"""
|
||||
import argparse
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
|
||||
import console_access_precision as previous
|
||||
|
||||
require, sha, save = previous.require, previous.sha, previous.save
|
||||
CASE = '5c96d3d8-1657-40c8-a6ec-c00b63a98210'
|
||||
OLD_SHA = '4977665fb092723998473f1c4be6685b1d93975176f8957bc3287d7e2f61cb69'
|
||||
OLD_NAME = 'Recover-ExistingDevAccess.ps1'
|
||||
NEW_NAME = 'Recover-ExistingDevAccess-HashFix.ps1'
|
||||
NAME = 'Get-RmmRecoveryFileSha256'
|
||||
STATE = previous.original.cb.EVIDENCE / 'dev-access-console-hash-correction'
|
||||
|
||||
|
||||
def corrected(raw):
|
||||
require(previous.original.pair.raw_sha(raw) == OLD_SHA, 'exact original reviewed 5c96 public script')
|
||||
source = raw.decode('utf-8')
|
||||
require(source.count('function H(') == 1 and NAME not in source, 'one original hash function and fresh unique name')
|
||||
calls = re.findall(r'\(H\s', source)
|
||||
require(len(calls) == source.count('(H ') and calls, 'all original H calls have the reviewed spelling')
|
||||
result = source.replace('function H(', 'function ' + NAME + '(').replace('(H ', '(' + NAME + ' ')
|
||||
require('function H(' not in result and not re.search(r'\(H\s', result), 'no alias-sensitive hash call remains')
|
||||
require(result.replace('function ' + NAME + '(', 'function H(').replace('(' + NAME + ' ', '(H ') == source, 'only function/command spelling changed; all effects/pins/case bytes preserved')
|
||||
return result.encode(), len(calls)
|
||||
|
||||
|
||||
def build():
|
||||
folder = previous.STATE / CASE
|
||||
raw = (folder / OLD_NAME).read_bytes()
|
||||
new, calls = corrected(raw)
|
||||
STATE.mkdir(mode=0o700, parents=True, exist_ok=False)
|
||||
previous.original.pair.write_bytes(STATE / NEW_NAME, new)
|
||||
digest = previous.original.pair.raw_sha(new)
|
||||
# Literal replacement, UTF8 without BOM, CreateNew, both independent hashes.
|
||||
# No free script content, Remove-Alias, persistent policy or registry change.
|
||||
patch = r'''$ErrorActionPreference='Stop'
|
||||
$oldPath=Join-Path (Get-Location) 'Recover-ExistingDevAccess.ps1'
|
||||
$newPath=Join-Path (Get-Location) 'Recover-ExistingDevAccess-HashFix.ps1'
|
||||
if((Get-FileHash -LiteralPath $oldPath -Algorithm SHA256).Hash.ToLowerInvariant()-cne'@@OLD@@'){throw 'Falsche Originaldatei; nichts ausfuehren'}
|
||||
if(Test-Path -LiteralPath $newPath){throw 'Korrekturdatei existiert bereits; nur lesend pruefen'}
|
||||
$text=[Text.Encoding]::UTF8.GetString([IO.File]::ReadAllBytes($oldPath))
|
||||
$text=$text.Replace('function H(','function Get-RmmRecoveryFileSha256(').Replace('(H ','(Get-RmmRecoveryFileSha256 ')
|
||||
$bytes=(New-Object Text.UTF8Encoding($false)).GetBytes($text)
|
||||
$out=[IO.File]::Open($newPath,[IO.FileMode]::CreateNew,[IO.FileAccess]::Write,[IO.FileShare]::Read)
|
||||
try{$out.Write($bytes,0,$bytes.Length);$out.Flush($true)}finally{$out.Dispose()}
|
||||
if((Get-FileHash -LiteralPath $newPath -Algorithm SHA256).Hash.ToLowerInvariant()-cne'@@NEW@@'){throw 'Korrekturhash stimmt nicht; nichts ausfuehren'}
|
||||
powershell.exe -NoProfile -ExecutionPolicy RemoteSigned -File $newPath
|
||||
'''.replace('@@OLD@@', OLD_SHA).replace('@@NEW@@', digest)
|
||||
previous.original.pair.write_bytes(STATE / 'Create-VerifiedHashFix.ps1', patch.encode())
|
||||
save(STATE / 'qualification.json', dict(source_sha256=sha(__file__), source_only=True, same_console_case=CASE, original_script_sha256=OLD_SHA, corrected_script_sha256=digest, renamed_call_count=calls, exact_inverse_spelling_transform=True, all_other_bytes_unchanged=True, original_script_and_zip_unchanged=True, case_absence_guard_retained=True, no_alias_mutation=True, no_server_or_vm_call=True, original_failure='Get-History/IdCannotConvert before New-Item/case or any effect'))
|
||||
print('corrected_script_sha256=' + digest)
|
||||
print('patch_sha256=' + sha(STATE / 'Create-VerifiedHashFix.ps1'))
|
||||
print('renamed_hash_calls=' + str(calls))
|
||||
print('patch=' + str((STATE / 'Create-VerifiedHashFix.ps1').resolve()))
|
||||
|
||||
|
||||
def main():
|
||||
os.umask(0o077)
|
||||
parser = argparse.ArgumentParser(description=__doc__); parser.add_argument('phase', choices=('build',)); parser.parse_args(); build()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,77 @@
|
||||
#!/usr/bin/env python3
|
||||
"""One local provenance correction: pin the actually deployed original bootstrap.
|
||||
|
||||
Actual User readonly values identify the published original file, not an unknown
|
||||
hash. Preserve the same absent console case and every other byte/guard/effect.
|
||||
No Windows/server access, new expiry, alias/policy change or effect retry.
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import zipfile
|
||||
|
||||
import console_access_hash_command as previous
|
||||
|
||||
require, sha, save = previous.require, previous.sha, previous.save
|
||||
STATE = previous.previous.original.cb.EVIDENCE / 'dev-access-console-original-bootstrap-correction'
|
||||
MAIN = Path('/home/kevin/Schreibtisch/Coding/rust-discovery')
|
||||
OLD_NAME = 'Recover-ExistingDevAccess-HashFix.ps1'
|
||||
NEW_NAME = 'Recover-ExistingDevAccess-OriginalBootstrap.ps1'
|
||||
OLD_SCRIPT_SHA = 'd366ae1705dac3252726dedf369c04462e42534ddcf6e15dc27bba8583427d2c'
|
||||
PARENT_SOURCE_SHA = 'b682ced57bf7ac71c0b1ba67eb5a51a20dde814fe361e1ae2cc17872147444ad'
|
||||
REPO_BOOTSTRAP_SHA = '9e992602034026efbe17f833d4d6be694da3e223ac6b4a394c502eb140ec0189'
|
||||
PUBLISHED_BOOTSTRAP_SHA = '332ceeedf49f597eac353e0ef1f6e614c85cef20a5a20cce68d947085aa9d50f'
|
||||
CONFIG_SHA = '4ad28ec55027718a4e384c79ff7cc15ec9c798411a991a5d479e960310ed6823'
|
||||
BUNDLE_SHA = 'cba159469efad9039562633fd60213d8f6a62f169fc3d1bba915e49d22c764d2'
|
||||
REPAIR_BUNDLE_SHA = '2558448b7812b95de1612fca5f11da8f4a868764fb45666b128d03eb0c423eb4'
|
||||
|
||||
|
||||
def build(facts_path):
|
||||
require(sha(previous.__file__) == PARENT_SOURCE_SHA, 'immutable reviewed parent hash fix source')
|
||||
facts = previous.previous.original.cb.contract.protected_json(facts_path)
|
||||
require(set(facts) == {'case_present', 'config_sha256', 'bootstrap_sha256', 'configured_expiry', 'account_expiry_filetime'} and facts['case_present'] is False and facts['config_sha256'] == CONFIG_SHA and facts['bootstrap_sha256'] == PUBLISHED_BOOTSTRAP_SHA and facts['configured_expiry'] == '2026-11-14T12:55:31.254999+00:00' and facts['account_expiry_filetime'] == '134391345312549990', 'exact actual User readonly original baseline, no unknown hash adoption')
|
||||
public = MAIN / 'devstate/windows-bootstrap'
|
||||
require(sha(public / 'windows-dev-access.zip') == BUNDLE_SHA and sha(public / 'windows-dev-repair.zip') == REPAIR_BUNDLE_SHA, 'immutable originally published bundles')
|
||||
with zipfile.ZipFile(public / 'windows-dev-access.zip') as archive:
|
||||
bootstrap = archive.read('Bootstrap-DevAccess.ps1'); config = archive.read('bootstrap-public.json')
|
||||
with zipfile.ZipFile(public / 'windows-dev-repair.zip') as archive:
|
||||
repair = json.loads(archive.read('repair-public.json'))
|
||||
raw_sha = previous.previous.original.pair.raw_sha
|
||||
require(raw_sha(bootstrap) == PUBLISHED_BOOTSTRAP_SHA == repair['previous_bootstrap_sha256'] and raw_sha(config) == CONFIG_SHA, 'actual file equals original publication and independently pinned repair prerequisite')
|
||||
original_path = previous.STATE / OLD_NAME
|
||||
require(sha(original_path) == OLD_SCRIPT_SHA, 'exact reviewed parent PS1')
|
||||
source = original_path.read_bytes().decode('utf-8')
|
||||
old = "$expectedBootstrap='" + REPO_BOOTSTRAP_SHA + "'"
|
||||
new = "$expectedBootstrap='" + PUBLISHED_BOOTSTRAP_SHA + "'"
|
||||
require(source.count(old) == 1 and new not in source, 'single exact original constant')
|
||||
corrected = source.replace(old, new, 1)
|
||||
require(corrected.replace(new, old, 1) == source, 'all other bytes including expiry/case/alias/clock/effects unchanged')
|
||||
STATE.mkdir(mode=0o700, parents=True, exist_ok=False)
|
||||
save(STATE / 'actual-user-readonly.json', facts)
|
||||
previous.previous.original.pair.write_bytes(STATE / NEW_NAME, corrected.encode())
|
||||
digest = raw_sha(corrected.encode())
|
||||
patch = r'''$ErrorActionPreference='Stop'
|
||||
$inputPath=Join-Path (Get-Location) 'Recover-ExistingDevAccess-HashFix.ps1';$newPath=Join-Path (Get-Location) 'Recover-ExistingDevAccess-OriginalBootstrap.ps1'
|
||||
if((Get-FileHash -LiteralPath $inputPath -Algorithm SHA256).Hash.ToLowerInvariant()-cne'@@INPUT@@'-or(Test-Path -LiteralPath $newPath)){throw 'Originalhash falsch oder neue Datei bereits vorhanden; nichts ausfuehren'}
|
||||
$text=[Text.Encoding]::UTF8.GetString([IO.File]::ReadAllBytes($inputPath));$text=$text.Replace("`$expectedBootstrap='@@OLD@@'","`$expectedBootstrap='@@PIN@@'");$bytes=(New-Object Text.UTF8Encoding($false)).GetBytes($text);$file=[IO.File]::Open($newPath,'CreateNew','Write','Read');try{$file.Write($bytes,0,$bytes.Length);$file.Flush($true)}finally{$file.Dispose()}
|
||||
if((Get-FileHash -LiteralPath $newPath -Algorithm SHA256).Hash.ToLowerInvariant()-cne'@@OUTPUT@@'){throw 'Neuer Hash falsch; nichts ausfuehren'}
|
||||
powershell.exe -NoProfile -ExecutionPolicy RemoteSigned -File $newPath
|
||||
'''
|
||||
for token, value in {'INPUT': OLD_SCRIPT_SHA, 'OLD': REPO_BOOTSTRAP_SHA, 'PIN': PUBLISHED_BOOTSTRAP_SHA, 'OUTPUT': digest}.items():
|
||||
patch = patch.replace('@@' + token + '@@', value)
|
||||
previous.previous.original.pair.write_bytes(STATE / 'Create-VerifiedOriginalBootstrapFix.ps1', patch.encode())
|
||||
save(STATE / 'qualification.json', dict(source_only=True, source_sha256=sha(__file__), parent_source_sha256=PARENT_SOURCE_SHA, actual_user_readonly_sha256=sha(STATE / 'actual-user-readonly.json'), same_console_case=previous.CASE, input_script_sha256=OLD_SCRIPT_SHA, corrected_script_sha256=digest, original_bundle_sha256=BUNDLE_SHA, repair_bundle_sha256=REPAIR_BUNDLE_SHA, published_bootstrap_sha256=PUBLISHED_BOOTSTRAP_SHA, corrected_exactly_one_constant=True, all_other_bytes_unchanged=True, no_unknown_hash_adoption=True, original_scripts_and_zip_retained=True, no_windows_or_server_access=True))
|
||||
print('source_sha256=' + sha(__file__))
|
||||
print('corrected_script_sha256=' + digest)
|
||||
print('patch_sha256=' + sha(STATE / 'Create-VerifiedOriginalBootstrapFix.ps1'))
|
||||
print('patch=' + str((STATE / 'Create-VerifiedOriginalBootstrapFix.ps1').resolve()))
|
||||
|
||||
|
||||
def main():
|
||||
os.umask(0o077)
|
||||
parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('phase',choices=('build',));parser.add_argument('--actual-user-readonly',required=True,type=Path);args=parser.parse_args();build(args.actual_user_readonly)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,101 @@
|
||||
#!/usr/bin/env python3
|
||||
"""New public console package correcting only the old AccountExpires guard.
|
||||
|
||||
Local only: reads the immutable completed server-only recovery case and its
|
||||
public package, never contacts Windows/server and cannot change a server lease.
|
||||
The same active server expiry/key/pins remain bound. The old package is retained.
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import uuid
|
||||
import zipfile
|
||||
|
||||
import console_access_recovery as original
|
||||
|
||||
require, sha, save = original.require, original.sha, original.save
|
||||
STATE = original.cb.EVIDENCE / 'dev-access-console-precision-correction'
|
||||
PARENT_ID = '4b6506a7-6c3e-4cca-a497-618fa8666300'
|
||||
PARENT_SOURCE_SHA = '703fb5e4ae04d8555bad858c5d7b2ac4880e06d6fa951010acd43f7201a58053'
|
||||
PARENT_INTENT_SHA = 'cd827d4056fb0045f23bff1fd9bd21b6137b53f063fe8215ad0945c2013cc44a'
|
||||
PARENT_ENTER_SHA = '2185a88fc32db72119a584d84a46fb25cfca5f32f6e0c4ee5b7cf0728a361317'
|
||||
PARENT_READBACK = 'readback-754e47df-25e0-4c0b-a411-56b3d350ace5.json'
|
||||
PARENT_READBACK_SHA = 'f6e3f69a6cd4f006d00c90cadd8bfd47f94e954f1297bea5f6eecc4fd27d3787'
|
||||
EXPIRY = '2026-11-15T13:05:58+00:00'
|
||||
AUTHORIZED_SHA = 'fef4db300dd39fba9b52428817f453451c251c7768dd2fb6a76b39dd110dbbf2'
|
||||
NAMES = ('Recover-ExistingDevAccess.ps1', 'public-recovery.json', 'README.txt')
|
||||
|
||||
|
||||
def replace_once(text, old, new):
|
||||
require(text.count(old) == 1, 'one exact reviewed precision/provenance replacement')
|
||||
return text.replace(old, new, 1)
|
||||
|
||||
|
||||
def corrected_script(source, ident):
|
||||
require(str(uuid.UUID(ident)) == ident, 'new canonical console UUID')
|
||||
# The original cfg bytes/hash and its exact expiry string have already been
|
||||
# verified before this line. Derive ONE full 64-bit FILETIME, no rounding,
|
||||
# alternative value, tolerance or claim of a measured VM account value.
|
||||
old = "$account=Get-LocalUser -Name 'rmm-dev';if(!$account.Enabled-or!$account.AccountExpires-or$account.AccountExpires.ToUniversalTime().ToFileTimeUtc().ToString()-cne'134391345310000000'){throw 'Existing original expired account only'}"
|
||||
new = "$expectedOldAccountFiletime=[DateTimeOffset]::Parse($cfg.expires_at).UtcDateTime.ToFileTimeUtc().ToString()\n$account=Get-LocalUser -Name 'rmm-dev';if(!$account.Enabled-or!$account.AccountExpires-or$account.AccountExpires.ToUniversalTime().ToFileTimeUtc().ToString()-cne$expectedOldAccountFiletime){throw 'Existing original expired account precision mismatch; stop for readonly inspection'}"
|
||||
result = replace_once(source, old, new)
|
||||
result = replace_once(result, "$recoveryId='" + PARENT_ID + "'", "$recoveryId='" + ident + "'")
|
||||
result = replace_once(result, "@{id=$recoveryId;new_expiry=$newExpiry;original_config_sha256=", "@{id=$recoveryId;parent_server_case='" + PARENT_ID + "';parent_server_enter_sha256='" + PARENT_ENTER_SHA + "';new_expiry=$newExpiry;original_config_sha256=")
|
||||
effect = '[IO.File]::Replace($candidate,$config,$nativeBackup)'
|
||||
require(result.split(effect, 1)[1] == source.split(effect, 1)[1], 'all three mutation steps/start behavior unchanged')
|
||||
require(result.count('Start-ScheduledTask -TaskName $taskName') == 1 and '134391345310000000' not in result, 'one original task start, no obsolete rounded guard')
|
||||
return result
|
||||
|
||||
|
||||
def parent():
|
||||
require(sha(original.__file__) == PARENT_SOURCE_SHA, 'immutable historical source, no rebase')
|
||||
folder = original.STATE / PARENT_ID
|
||||
require(sha(folder / 'intent.json') == PARENT_INTENT_SHA and sha(folder / 'server-entered.json') == PARENT_ENTER_SHA and sha(folder / PARENT_READBACK) == PARENT_READBACK_SHA, 'exact existing server-only CAS and independent readback')
|
||||
intent = original.cb.contract.protected_json(folder / 'intent.json')
|
||||
entered = original.cb.contract.protected_json(folder / 'server-entered.json')
|
||||
readback = original.cb.contract.protected_json(folder / PARENT_READBACK)
|
||||
require(intent['id'] == PARENT_ID and intent['source_sha256'] == PARENT_SOURCE_SHA and intent['payload']['new_expiry'] == EXPIRY and entered['completed'] is True and entered['authorized_sha256'] == readback['authorized_sha256'] == AUTHORIZED_SHA and entered['expiry'] == readback['expiry'] == '20261115130558Z' and readback['read_only'] is True and readback['completed'] is True, 'same already completed server lease; never a new CAS')
|
||||
before = intent['payload']['server_before']
|
||||
require(all(readback[field] == before[field] for field in ('profile_sha256', 'effective_sha256', 'server_host_key_sha256', 'tunnel_public_key_sha256', 'uid', 'gid', 'home', 'shell')), 'original forwarding authority/key/profile/account unchanged')
|
||||
for name, field in ((NAMES[0], 'console_sha256'), ('README.txt', 'readme_sha256'), ('public-recovery.json', 'public_json_sha256'), ('windows-dev-access-recovery.zip', 'bundle_sha256')):
|
||||
require(sha(folder / name) == intent[field], 'immutable original public package files')
|
||||
return folder, intent
|
||||
|
||||
|
||||
def build():
|
||||
old_folder, old_intent = parent()
|
||||
require(original.cb.contract.now() < original.dt.datetime.fromisoformat(EXPIRY), 'existing server lease still in its fixed window')
|
||||
ident = str(uuid.uuid4()); folder = STATE / ident; folder.mkdir(mode=0o700, parents=True)
|
||||
save(folder / 'prepare-intent.json', dict(id=ident, source_sha256=sha(__file__), parent_server_case=PARENT_ID, parent_server_enter_sha256=PARENT_ENTER_SHA, new_server_cas=False, no_windows_or_server_access=True))
|
||||
script = corrected_script((old_folder / NAMES[0]).read_text(), ident)
|
||||
original.pair.write_bytes(folder / NAMES[0], script.encode())
|
||||
digest = original.pair.raw_sha(script.encode())
|
||||
public = dict(schema_version=1, id=ident, parent_server_case=PARENT_ID, parent_source_sha256=PARENT_SOURCE_SHA, parent_server_enter_sha256=PARENT_ENTER_SHA, parent_server_readback_sha256=PARENT_READBACK_SHA, new_expiry=EXPIRY, script_sha256=digest, no_private_keys=True, new_server_cas=False, old_account_guard='exact_derived_from_verified_config_utc_filetime', actual_vm_account_filetime_measured=False)
|
||||
save(folder / 'public-recovery.json', public)
|
||||
readme = (old_folder / 'README.txt').read_text()
|
||||
require(old_intent['console_sha256'] in readme, 'original independent PS1 hash instructions')
|
||||
readme = readme.replace(old_intent['console_sha256'], digest)
|
||||
readme += ('\nPraezisionskorrektur: neues Konsolenpaket, neuer Fall ' + ident + '.\n'
|
||||
'Verwendet ausschliesslich den bereits bestaetigten Serverfall ' + PARENT_ID + ' und dieselbe UTC-Frist ' + EXPIRY + '. Keine neue Serververlaengerung.\n'
|
||||
'Der alte AccountExpires-Sollwert wird exakt aus der unveraenderten alten Config-UTC-Zeit einschliesslich Bruchteilen abgeleitet. Dies ist kein gemessener VM-Accountwert.\n'
|
||||
'Keine Rundung, Toleranz oder alternativer Sollwert. Bei Abweichung abbrechen und nur lesend pruefen lassen.\n'
|
||||
'Falls ein frueheres Paket bereits erfolgreich ausgefuehrt wurde: dieses Paket NICHT als Retry verwenden; der alte Config-Hashguard muss dann verweigern.\n')
|
||||
original.pair.write_bytes(folder / 'README.txt', readme.encode())
|
||||
bundle = folder / 'windows-dev-access-recovery.zip'
|
||||
with zipfile.ZipFile(bundle, 'x', compression=zipfile.ZIP_DEFLATED) as archive:
|
||||
for name in NAMES: archive.write(folder / name, name)
|
||||
bundle.chmod(0o600)
|
||||
intent = dict(schema_version=1, id=ident, source_sha256=sha(__file__), parent_server_case=PARENT_ID, parent_intent_sha256=PARENT_INTENT_SHA, parent_server_enter_sha256=PARENT_ENTER_SHA, parent_server_readback_sha256=PARENT_READBACK_SHA, original_bundle_sha256=old_intent['bundle_sha256'], new_expiry=EXPIRY, console_sha256=digest, public_json_sha256=sha(folder / 'public-recovery.json'), readme_sha256=sha(folder / 'README.txt'), bundle_sha256=sha(bundle), no_windows_or_server_access=True, new_server_cas=False)
|
||||
save(folder / 'intent.json', intent)
|
||||
print(json.dumps(dict(id=ident, intent_sha256=sha(folder / 'intent.json'), bundle=str(bundle.resolve()), bundle_sha256=intent['bundle_sha256'], console_source=str((folder / NAMES[0]).resolve()), console_sha256=digest, new_expiry=EXPIRY, parent_server_case=PARENT_ID, new_server_cas=False, no_windows_or_server_access=True)))
|
||||
|
||||
|
||||
def main():
|
||||
os.umask(0o077)
|
||||
parser = argparse.ArgumentParser(description=__doc__); parser.add_argument('phase', choices=('build',)); parser.parse_args(); build()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
try: main()
|
||||
except Exception as error: print('CONSOLE_PRECISION_CORRECTION_INCOMPLETE:' + type(error).__name__); raise SystemExit(2) from None
|
||||
@@ -0,0 +1,189 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Expired development tunnel recovery: server-only CAS + fixed public console code.
|
||||
|
||||
No Windows access, key generation, SSH profile edit, port/download/RMM change.
|
||||
Root renews the one expired restricted authorized key first, then hands the
|
||||
reviewed public PowerShell to the User's elevated Windows console.
|
||||
"""
|
||||
import argparse
|
||||
import base64
|
||||
import datetime as dt
|
||||
import hashlib
|
||||
import inspect
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import uuid
|
||||
import zipfile
|
||||
import client_bootstrap as cb
|
||||
import system_pipe_upgrade as pair
|
||||
import dev_access_renewal as previous
|
||||
require,sha,save=pair.require,pair.sha,pair.save
|
||||
STATE=cb.EVIDENCE/'dev-access-console-recovery'
|
||||
OLD_EXPIRY='2026-11-14T12:55:31.254999+00:00'
|
||||
|
||||
def recover_server(payload):
|
||||
import datetime as dt
|
||||
import re
|
||||
import stat
|
||||
root=Path('/opt/rust-discovery/devstate/windows-bootstrap')
|
||||
authorized=Path('/var/lib/rmm-win-tunnel/.ssh/authorized_keys')
|
||||
profile=Path('/etc/ssh/sshd_config.d/80-rmm-windows-tunnel.conf')
|
||||
ident=str(uuid.UUID(payload['id']));case=root/('console-recovery-'+ident)
|
||||
require(payload['phase'] in ('state','enter','readback'),'fixed renewal phase')
|
||||
def check(path,mode):
|
||||
s=path.lstat();require(not path.is_symlink() and stat.S_ISREG(s.st_mode) and s.st_uid==0 and stat.S_IMODE(s.st_mode)==mode and s.st_size<65536,'protected original transport file')
|
||||
def digest(path):return hashlib.sha256(path.read_bytes()).hexdigest()
|
||||
check(authorized,0o644);check(profile,0o644)
|
||||
account=pwd.getpwnam('rmm-win-tunnel');require(account.pw_dir=='/var/lib/rmm-win-tunnel' and account.pw_shell=='/usr/sbin/nologin','existing forwarding-only account')
|
||||
public=' '.join(Path('/etc/ssh/ssh_host_ed25519_key.pub').read_text().split()[:2])
|
||||
fingerprint=subprocess.run(['ssh-keygen','-lf','/etc/ssh/ssh_host_ed25519_key.pub'],capture_output=True,check=True,timeout=10).stdout.decode().split()[1]
|
||||
require(fingerprint=='SHA256:+NEin4XJc3CbhjQi7/ZpMIgxOrXn8AT2tlpTaXW5quw','confirmed original server host key')
|
||||
raw=authorized.read_text();match=re.fullmatch(r'restrict,port-forwarding,permitlisten="127\.0\.0\.1:22240",expiry-time="(\d{14}Z)" (ssh-ed25519 [A-Za-z0-9+/=]{68})\n',raw)
|
||||
require(match is not None and match[2]==payload['tunnel_public_key'],'exact unchanged forwarding key/options')
|
||||
effective=subprocess.run(['/usr/sbin/sshd','-T','-C','user=rmm-win-tunnel,host=localhost,addr=127.0.0.1'],capture_output=True,check=True,timeout=10).stdout
|
||||
for line in (b'allowtcpforwarding remote\n',b'permitlisten 127.0.0.1:22240\n',b'permitopen none\n',b'gatewayports no\n',b'maxsessions 0\n',b'passwordauthentication no\n'):require(line in effective,'same restricted forwarding-only profile')
|
||||
def state():return dict(read_only=True,authorized_sha256=digest(authorized),profile_sha256=digest(profile),effective_sha256=hashlib.sha256(effective).hexdigest(),server_host_key_sha256=hashlib.sha256(public.encode()).hexdigest(),tunnel_public_key_sha256=hashlib.sha256(match[2].encode()).hexdigest(),expiry=match[1],uid=account.pw_uid,gid=account.pw_gid,home=account.pw_dir,shell=account.pw_shell)
|
||||
if payload['phase']=='state':return state()
|
||||
if payload['phase']=='readback':
|
||||
value=state();value['case_exists']=case.exists();value['replace_intent']=case.exists() and (case/'replace-intent.json').exists();value['completed']=case.exists() and (case/'completed.json').exists();return value
|
||||
old=dt.datetime.fromisoformat(payload['old_expiry']).astimezone(dt.timezone.utc);new=dt.datetime.fromisoformat(payload['new_expiry']).astimezone(dt.timezone.utc)
|
||||
require(old.isoformat()=='2026-11-14T12:55:31.254999+00:00' and old<dt.datetime.now(dt.timezone.utc)<new<=dt.datetime.now(dt.timezone.utc)+dt.timedelta(hours=24) and state()==payload['server_before'],'exact EXPIRED original key/CAS and bounded fresh 24h console recovery')
|
||||
require(not case.exists(),'existing server renewal: readback only');case.mkdir(mode=0o700)
|
||||
def write(path,data,mode=0o600):
|
||||
fd=os.open(path,os.O_WRONLY|os.O_CREAT|os.O_EXCL|os.O_NOFOLLOW,mode)
|
||||
with os.fdopen(fd,'wb') as out:out.write(data);out.flush();os.fsync(out.fileno());os.fchmod(out.fileno(),mode)
|
||||
write(case/'intent.json',json.dumps(payload).encode());write(case/'authorized_keys.original',raw.encode())
|
||||
replacement=raw.replace('expiry-time="'+old.strftime('%Y%m%d%H%M%SZ')+'"','expiry-time="'+new.strftime('%Y%m%d%H%M%SZ')+'"')
|
||||
require(replacement!=raw and replacement.replace(new.strftime('%Y%m%d%H%M%SZ'),old.strftime('%Y%m%d%H%M%SZ'))==raw,'expiry only, key/options unchanged')
|
||||
candidate=authorized.parent/('renew-'+ident+'.next');write(candidate,replacement.encode(),0o644)
|
||||
write(case/'replace-intent.json',json.dumps(dict(old_sha256=digest(authorized),new_sha256=hashlib.sha256(replacement.encode()).hexdigest())).encode())
|
||||
require(digest(authorized)==payload['server_before']['authorized_sha256'] and digest(profile)==payload['server_before']['profile_sha256'],'immediate original server CAS')
|
||||
os.replace(candidate,authorized);directory=os.open(authorized.parent,os.O_RDONLY);os.fsync(directory);os.close(directory)
|
||||
require(authorized.read_text()==replacement,'actual exact renewed authorization');write(case/'completed.json',json.dumps(dict(completed=True,new_expiry=payload['new_expiry'],download_lease_changed=False)).encode())
|
||||
return dict(completed=True,authorized_sha256=digest(authorized),expiry=new.strftime('%Y%m%d%H%M%SZ'),no_new_authority=True,download_lease_changed=False)
|
||||
|
||||
CONSOLE = r'''
|
||||
# Paste this complete reviewed block into elevated Windows PowerShell 5.1.
|
||||
# Bootstrap SSH recovery only. No RMM job, policy/ACL change, installation or reboot.
|
||||
$ErrorActionPreference='Stop'
|
||||
if(!([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)){throw 'Elevated Windows console required'}
|
||||
$recoveryId='@@ID@@';$newExpiry='@@EXPIRY@@';$expectedConfig='@@CONFIG@@';$expectedBootstrap='@@BOOTSTRAP@@'
|
||||
$expectedTunnel='@@TUNNEL@@';$expectedWindowsHost='@@HOST@@';$root='C:\ProgramData\RmmDevAccess';$config=Join-Path $root 'bootstrap-public.json';$case=Join-Path $root ('console-recovery-'+$recoveryId);$taskName='RmmDevReverseTunnel'
|
||||
function H($path){$item=Get-Item -LiteralPath $path -Force;if($item.PSIsContainer-or($item.Attributes-band[IO.FileAttributes]::ReparsePoint)){throw 'Only regular fixed public/bootstrap file'};$parent=$item.Directory;while($null-ne$parent){if($parent.Attributes-band[IO.FileAttributes]::ReparsePoint){throw 'No reparse ancestor'};$parent=$parent.Parent};return(Get-FileHash -LiteralPath $path -Algorithm SHA256).Hash.ToLowerInvariant()}
|
||||
function B([string]$text){$h=[Security.Cryptography.SHA256]::Create();try{return([BitConverter]::ToString($h.ComputeHash([Text.Encoding]::UTF8.GetBytes($text)))).Replace('-','').ToLowerInvariant()}finally{$h.Dispose()}}
|
||||
function NewReceipt($path,$value){$bytes=[Text.Encoding]::UTF8.GetBytes(($value|ConvertTo-Json -Depth 12 -Compress));$f=[IO.File]::Open($path,'CreateNew','Write','Read');try{$f.Write($bytes,0,$bytes.Length);$f.Flush($true)}finally{$f.Dispose()}}
|
||||
$directory=Get-Item -LiteralPath $root -Force;$acl=Get-Acl -LiteralPath $root
|
||||
if(!$directory.PSIsContainer-or($directory.Attributes-band[IO.FileAttributes]::ReparsePoint)-or$acl.GetOwner([Security.Principal.SecurityIdentifier]).Value-notin@('S-1-5-18','S-1-5-32-544')){throw 'Original protected bootstrap directory'}
|
||||
foreach($rule in $acl.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier])){if($rule.AccessControlType-ne'Allow'-or$rule.IdentityReference.Value-notin@('S-1-5-18','S-1-5-32-544')){throw 'Original private directory ACL'}}
|
||||
if((Test-Path -LiteralPath $case)-or(H $config)-cne$expectedConfig-or(H (Join-Path $root 'Bootstrap-DevAccess.ps1'))-cne$expectedBootstrap){throw 'Only untouched original expired bootstrap; existing recovery means readback only'}
|
||||
$cfg=Get-Content -LiteralPath $config -Raw|ConvertFrom-Json
|
||||
if((($cfg.PSObject.Properties.Name|Sort-Object)-join',')-cne'expires_at,notebook_public_key,schema_version,server,server_host_key'-or$cfg.schema_version-ne1-or$cfg.server-cne'discovery.ease-technologies.de'-or$cfg.expires_at-cne'2026-11-14T12:55:31.254999+00:00'){throw 'Exact original public config and old expiry'}
|
||||
$expiry=[DateTimeOffset]::Parse($newExpiry);if($expiry-le[DateTimeOffset]::UtcNow-or$expiry-gt[DateTimeOffset]::UtcNow.AddHours(24)){throw 'Bounded reviewed new UTC expiry'}
|
||||
$tunnelPublic=((Get-Content -LiteralPath (Join-Path $root 'tunnel_ed25519.pub') -Raw).Trim()-split'\s+')[0..1]-join' '
|
||||
$windowsHostPublic=((Get-Content -LiteralPath 'C:\ProgramData\ssh\ssh_host_ed25519_key.pub' -Raw).Trim()-split'\s+')[0..1]-join' '
|
||||
if($tunnelPublic-cne$expectedTunnel-or$windowsHostPublic-cne$expectedWindowsHost-or(Get-Content -LiteralPath (Join-Path $root 'known_hosts') -Raw)-cne('discovery.ease-technologies.de '+$cfg.server_host_key+"`n")-or(Get-Content -LiteralPath 'C:\ProgramData\ssh\administrators_authorized_keys' -Raw)-cne($cfg.notebook_public_key+"`n")){throw 'Original tunnel/server/Windows/notebook public pins'}
|
||||
$account=Get-LocalUser -Name 'rmm-dev';if(!$account.Enabled-or!$account.AccountExpires-or$account.AccountExpires.ToUniversalTime().ToFileTimeUtc().ToString()-cne'134391345310000000'){throw 'Existing original expired account only'}
|
||||
$task=Get-ScheduledTask -TaskName $taskName;$actions=@($task.Actions)
|
||||
if($task.State-cne'Ready'-or$actions.Count-ne1-or$actions[0].Execute-ine'C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe'-or$actions[0].Arguments-cne'-NoProfile -NonInteractive -ExecutionPolicy RemoteSigned -File "C:\ProgramData\RmmDevAccess\Bootstrap-DevAccess.ps1" -MaintainTunnel'-or$task.Principal.UserId-notin@('SYSTEM','S-1-5-18')-or$task.Principal.LogonType-cne'ServiceAccount'-or$task.Principal.RunLevel-cne'Highest'){throw 'Unchanged original SYSTEM task must be Ready'}
|
||||
$active=@(Get-CimInstance Win32_Process -Filter "Name='powershell.exe' OR Name='ssh.exe'" -OperationTimeoutSec 10|Where-Object{$_.CommandLine-like'*Bootstrap-DevAccess.ps1* -MaintainTunnel*'-or$_.CommandLine-like'*C:\ProgramData\RmmDevAccess\tunnel_ed25519*'})
|
||||
if($active.Count){throw 'Old maintainer/tunnel must exit naturally; no kill or duplicate start'}
|
||||
$taskXml=Export-ScheduledTask -TaskName $taskName;$fixed=[ordered]@{}
|
||||
foreach($path in @((Join-Path $root 'known_hosts'),(Join-Path $root 'Bootstrap-DevAccess.ps1'),(Join-Path $root 'tunnel_ed25519.pub'),'C:\ProgramData\ssh\ssh_host_ed25519_key.pub','C:\ProgramData\ssh\sshd_config','C:\ProgramData\ssh\administrators_authorized_keys')){$item=Get-Item -LiteralPath $path -Force;if($item.PSIsContainer-or($item.Attributes-band[IO.FileAttributes]::ReparsePoint)){throw 'No reparse public/bootstrap file'};$fixed[$path]=@{sha256=(H $path);sddl=(Get-Acl -LiteralPath $path).Sddl}}
|
||||
$private=[ordered]@{};foreach($path in @((Join-Path $root 'tunnel_ed25519'),'C:\ProgramData\ssh\ssh_host_ed25519_key','C:\ProgramData\ssh\ssh_host_rsa_key','C:\ProgramData\ssh\ssh_host_ecdsa_key')){if(Test-Path -LiteralPath $path){$item=Get-Item -LiteralPath $path -Force;if($item.PSIsContainer-or($item.Attributes-band[IO.FileAttributes]::ReparsePoint)){throw 'No reparse private key'};$private[$path]=@{bytes=$item.Length;created=$item.CreationTimeUtc.Ticks.ToString();written=$item.LastWriteTimeUtc.Ticks.ToString();sddl=(Get-Acl -LiteralPath $path).Sddl}}}
|
||||
New-Item -ItemType Directory -Path $case|Out-Null
|
||||
NewReceipt (Join-Path $case 'intent.json') @{id=$recoveryId;new_expiry=$newExpiry;original_config_sha256=$expectedConfig;account_sid=$account.SID.Value;task_xml_sha256=(B $taskXml);fixed=$fixed;private_metadata=$private;private_keys_read=$false;no_new_authority=$true}
|
||||
$backup=Join-Path $case 'bootstrap-public.original';[IO.File]::Copy($config,$backup,$false)
|
||||
$cfg.expires_at=$newExpiry;$candidate=Join-Path $case 'bootstrap-public.next';NewReceipt $candidate $cfg;$nativeBackup=Join-Path $case 'bootstrap-public.native-original'
|
||||
NewReceipt (Join-Path $case 'config-replace-intent.json') @{old_sha256=$expectedConfig;new_expiry=$newExpiry;native_backup=$nativeBackup}
|
||||
if((H $config)-cne$expectedConfig-or(Test-Path -LiteralPath $nativeBackup)){throw 'Immediate original config CAS'};$originalAcl=Get-Acl -LiteralPath $config
|
||||
[IO.File]::Replace($candidate,$config,$nativeBackup);Set-Acl -LiteralPath $config -AclObject $originalAcl
|
||||
NewReceipt (Join-Path $case 'account-expiry-intent.json') @{existing_sid=$account.SID.Value;new_expiry=$newExpiry}
|
||||
if((Get-LocalUser -Name 'rmm-dev').SID.Value-cne$account.SID.Value){throw 'Original account changed'}
|
||||
Set-LocalUser -Name 'rmm-dev' -AccountExpires $expiry.LocalDateTime
|
||||
if((Get-LocalUser -Name 'rmm-dev').AccountExpires.ToUniversalTime().ToFileTimeUtc().ToString()-cne'@@FILETIME@@'){throw 'Exact renewed account expiry'}
|
||||
foreach($path in $fixed.Keys){if((H $path)-cne$fixed[$path].sha256-or(Get-Acl -LiteralPath $path).Sddl-cne$fixed[$path].sddl){throw 'Original fixed bootstrap/key bytes or ACL changed'}}
|
||||
foreach($path in $private.Keys){$item=Get-Item -LiteralPath $path -Force;$meta=@{bytes=$item.Length;created=$item.CreationTimeUtc.Ticks.ToString();written=$item.LastWriteTimeUtc.Ticks.ToString();sddl=(Get-Acl -LiteralPath $path).Sddl};foreach($field in @('bytes','created','written','sddl')){if($meta[$field]-cne$private[$path][$field]){throw 'Private key metadata changed'}}}
|
||||
if((Export-ScheduledTask -TaskName $taskName)-cne$taskXml-or(Get-ScheduledTask -TaskName $taskName).State-cne'Ready'){throw 'Original task changed; no start'}
|
||||
NewReceipt (Join-Path $case 'original-task-start-intent.json') @{start_once=$true;task_xml_sha256=(B $taskXml)}
|
||||
Start-ScheduledTask -TaskName $taskName
|
||||
NewReceipt (Join-Path $case 'console-completed.json') @{completed=$true;new_expiry=$newExpiry;original_task_start_requested_once=$true;private_keys_read=$false;no_keys_ports_policy_acl_install_reboot_or_rmm_change=$true}
|
||||
Write-Host ('Bestehender SSH-Zugang erneuert bis '+$newExpiry+'. Originaltunnel einmal gestartet. Bitte diese Zeile zurueckmelden; keine Schluessel senden.')
|
||||
'''
|
||||
|
||||
|
||||
class ServerAccess:
|
||||
def __init__(self,root):self.root=Path(root).absolute();require(self.root==self.root.resolve() and self.root!=cb.ROOT,'separate protected Main access root')
|
||||
def rpc(self,payload):
|
||||
cloud=pair.u.transport.cloud;cfg=cloud.bootstrap.access.load_config(self.root/'credentials/server.conf')
|
||||
ssh=['ssh','-F','/dev/null','-T','-p',cfg.get('port','22'),'-o','StrictHostKeyChecking=yes','-o','BatchMode=yes','-o','IdentitiesOnly=yes','-o','ForwardAgent=no','-i',str(Path(cfg['ssh_key_path']).expanduser()),cfg['username']+'@'+cfg['address'],'python3 -']
|
||||
code='import os,json,subprocess,base64,hashlib,uuid,pwd\nfrom pathlib import Path\n'+inspect.getsource(cloud.bootstrap.require)+'\n'+inspect.getsource(recover_server)+'\ntry:\n print(json.dumps(recover_server('+repr(payload)+')))\nexcept Exception as e:\n print(json.dumps(dict(error=type(e).__name__)))\n'
|
||||
result=subprocess.run(ssh,input=code.encode(),capture_output=True,timeout=60);require(result.returncode==0,'fixed server-only recovery RPC')
|
||||
value=json.loads(result.stdout,object_pairs_hook=cb.contract.strict_object);require('error' not in value,'server-only recovery incomplete; readback only');return value
|
||||
|
||||
|
||||
def prepare(access):
|
||||
require(cb.contract.now()>dt.datetime.fromisoformat(OLD_EXPIRY),'original lease actually expired')
|
||||
ident=str(uuid.uuid4());folder=STATE/ident;folder.mkdir(mode=0o700,parents=True)
|
||||
expiry=(cb.contract.now()+dt.timedelta(hours=24)).replace(microsecond=0)
|
||||
console=cb.contract.protected_json(access.root/'devstate/windows-bootstrap/console-registration.json')
|
||||
with zipfile.ZipFile(access.root/'devstate/windows-bootstrap/windows-dev-access.zip') as bundle:
|
||||
original=bundle.read('bootstrap-public.json')
|
||||
public=json.loads(original,object_pairs_hook=cb.contract.strict_object)
|
||||
require(public['expires_at']==OLD_EXPIRY and public['server']=='discovery.ease-technologies.de','original public-only bundle')
|
||||
payload=dict(id=ident,phase='state',old_expiry=OLD_EXPIRY,new_expiry=expiry.isoformat(),tunnel_public_key=console['tunnel_public_key'])
|
||||
save(folder/'prepare-intent.json',dict(id=ident,source_sha256=sha(__file__),new_expiry=payload['new_expiry'],no_windows_access=True))
|
||||
baseline=access.rpc(payload);require(baseline['expiry']==dt.datetime.fromisoformat(OLD_EXPIRY).strftime('%Y%m%d%H%M%SZ'),'only original expired key')
|
||||
payload['server_before']=baseline
|
||||
script=CONSOLE
|
||||
for key,value in {'ID':ident,'EXPIRY':payload['new_expiry'],'CONFIG':hashlib.sha256(original).hexdigest(),'BOOTSTRAP':sha(cb.ROOT/'deploy/windows/Bootstrap-DevAccess.ps1'),'TUNNEL':console['tunnel_public_key'],'HOST':console['windows_host_public_key'],'FILETIME':str((int(expiry.timestamp())+11644473600)*10000000)}.items():
|
||||
token='@@'+key+'@@';require(script.count(token)==1,'exact fixed public console field');script=script.replace(token,value)
|
||||
require('@@' not in script,'complete fixed public instructions')
|
||||
pair.write_bytes(folder/'Recover-ExistingDevAccess.ps1',script.encode())
|
||||
save(folder/'public-recovery.json',dict(id=ident,new_expiry=payload['new_expiry'],script_sha256=pair.raw_sha(script.encode()),no_private_keys=True))
|
||||
readme=('Bestehenden Windows-Entwicklungszugang wiederherstellen\r\n\r\n'
|
||||
'Nur in dieser Windows-Test-VM ausfuehren, in einer als Administrator gestarteten PowerShell.\r\n'
|
||||
'Der Cloudserver muss zuvor durch den Entwickler fuer diese feste Frist erneuert worden sein.\r\n'
|
||||
'Neue UTC-Frist: '+payload['new_expiry']+'\r\n'
|
||||
'ZIP-SHA256 mit dem unabhaengig mitgeteilten Downloadhash vergleichen; dann hier entpacken.\r\n'
|
||||
'Folgende Befehle im entpackten Verzeichnis ausfuehren:\r\n\r\n'
|
||||
"$recoveryScript = Join-Path (Get-Location) 'Recover-ExistingDevAccess.ps1'\r\n"
|
||||
"if ((Get-FileHash -LiteralPath $recoveryScript -Algorithm SHA256).Hash.ToLowerInvariant() -cne '"+pair.raw_sha(script.encode())+"') { throw 'Falsche Recoverydatei' }\r\n"
|
||||
'Unblock-File -LiteralPath $recoveryScript\r\n'
|
||||
'powershell.exe -NoProfile -ExecutionPolicy RemoteSigned -File $recoveryScript\r\n\r\n'
|
||||
'Unblock-File betrifft nur diese exakt gepruefte heruntergeladene Datei; RemoteSigned nur diesen Bootstrapprozess.\r\n'
|
||||
'Keine globale Policy/GPO aendern. Falls eine Richtlinie oder Pruefung verweigert: stoppen, Fehlermeldung melden, nicht erneut ausfuehren.\r\n'
|
||||
'Das Skript behaelt Schluessel, Pins, SSH-Profil und Taskdefinition bei, erneuert nur die Ablaufzeit und startet den Originaltunnel einmal.\r\n'
|
||||
'Keine Installation, ACL-Reparatur, RMM-Aktion, Reboot oder Update. Private Schluessel werden nicht gelesen/ausgegeben.\r\n'
|
||||
'Nach Erfolg bitte nur die Abschlusszeile melden, keine Schluessel oder Zugangsdaten. Bei Fehler den Zustand fuer lesende Kontrolle behalten.\r\n')
|
||||
pair.write_bytes(folder/'README.txt',readme.encode('utf-8'))
|
||||
bundle=folder/'windows-dev-access-recovery.zip'
|
||||
with zipfile.ZipFile(bundle,'x',compression=zipfile.ZIP_DEFLATED) as archive:
|
||||
for name in ('Recover-ExistingDevAccess.ps1','public-recovery.json','README.txt'):
|
||||
archive.write(folder/name,name)
|
||||
bundle.chmod(0o600)
|
||||
intent=dict(id=ident,source_sha256=sha(__file__),access_root=str(access.root),payload=payload,console_sha256=pair.raw_sha(script.encode()),bundle_sha256=sha(bundle),readme_sha256=sha(folder/'README.txt'),public_json_sha256=sha(folder/'public-recovery.json'))
|
||||
save(folder/'intent.json',intent)
|
||||
print(json.dumps(dict(id=ident,review_sha256=sha(folder/'intent.json'),console_source=str((folder/'Recover-ExistingDevAccess.ps1').resolve()),console_sha256=intent['console_sha256'],bundle=str(bundle.resolve()),bundle_sha256=sha(bundle),new_expiry=payload['new_expiry'],windows_not_accessed=True)))
|
||||
|
||||
|
||||
def run(access,ident,phase,review_sha):
|
||||
require(str(uuid.UUID(ident))==ident,'canonical original recovery');folder=STATE/ident;intent=cb.contract.protected_json(folder/'intent.json')
|
||||
require(intent['source_sha256']==sha(__file__) and intent['access_root']==str(access.root) and sha(folder/'Recover-ExistingDevAccess.ps1')==intent['console_sha256'] and sha(folder/'windows-dev-access-recovery.zip')==intent['bundle_sha256'] and sha(folder/'README.txt')==intent['readme_sha256'] and sha(folder/'public-recovery.json')==intent['public_json_sha256'],'same immutable console recovery source/public package')
|
||||
if phase=='server-enter':
|
||||
require(review_sha==sha(folder/'intent.json'),'explicit reviewed server-only CAS');save(folder/'server-enter-intent.json',dict(once=True))
|
||||
payload=dict(intent['payload'],phase='enter' if phase=='server-enter' else 'readback')
|
||||
result=access.rpc(payload);save(folder/('server-entered.json' if phase=='server-enter' else 'readback-'+str(uuid.uuid4())+'.json'),result)
|
||||
print(json.dumps(dict(id=ident,result=result,windows_not_accessed=True,console_handoff_allowed=result.get('completed') is True)))
|
||||
|
||||
|
||||
def main():
|
||||
os.umask(0o077);parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('phase',choices=('prepare','server-enter','readback'));parser.add_argument('--access-root',required=True,type=Path);parser.add_argument('--id');parser.add_argument('--review-sha256');args=parser.parse_args();access=ServerAccess(args.access_root)
|
||||
if args.phase=='prepare':require(not(args.id or args.review_sha256),'fresh server-only preparation');prepare(access)
|
||||
else:require(args.id and ((args.phase=='server-enter')==bool(args.review_sha256)),'same case, reviewed CAS once');run(access,args.id,args.phase,args.review_sha256)
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
try:main()
|
||||
except Exception as error:print('CONSOLE_ACCESS_RECOVERY_INCOMPLETE:'+type(error).__name__);raise SystemExit(2) from None
|
||||
@@ -0,0 +1,238 @@
|
||||
#!/usr/bin/env python3
|
||||
"""One 24h renewal of the existing restricted development SSH transport.
|
||||
|
||||
No new key, port, shell, RMM setting, download lease, stop/kill or reboot.
|
||||
The unchanged tunnel expires naturally; one SYSTEM worker starts its original
|
||||
scheduled task at original expiry+60s. This deliberately permits a short gap.
|
||||
Lost mutation replies allow readback only. Main config publication is Root work.
|
||||
"""
|
||||
import argparse
|
||||
import base64
|
||||
import datetime as dt
|
||||
import inspect
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import uuid
|
||||
|
||||
import client_bootstrap as cb
|
||||
import system_pipe_upgrade as pair
|
||||
|
||||
require, sha, canonical, save = pair.require, pair.sha, pair.canonical, pair.save
|
||||
STATE = cb.EVIDENCE / 'dev-access-renewal'
|
||||
OLD_EXPIRY = '2026-11-14T12:55:31.254999+00:00'
|
||||
OLD_UTC = dt.datetime.fromisoformat(OLD_EXPIRY)
|
||||
NEW_UTC = OLD_UTC.replace(microsecond=0) + dt.timedelta(hours=24)
|
||||
START_UTC = OLD_UTC.replace(microsecond=0) + dt.timedelta(seconds=60)
|
||||
|
||||
|
||||
def server(payload):
|
||||
import datetime as dt
|
||||
import re
|
||||
import stat
|
||||
root=Path('/opt/rust-discovery/devstate/windows-bootstrap')
|
||||
authorized=Path('/var/lib/rmm-win-tunnel/.ssh/authorized_keys')
|
||||
profile=Path('/etc/ssh/sshd_config.d/80-rmm-windows-tunnel.conf')
|
||||
ident=str(uuid.UUID(payload['id']));case=root/('renew-'+ident)
|
||||
require(payload['phase'] in ('state','enter','readback'),'fixed renewal phase')
|
||||
def check(path,mode):
|
||||
s=path.lstat();require(not path.is_symlink() and stat.S_ISREG(s.st_mode) and s.st_uid==0 and stat.S_IMODE(s.st_mode)==mode and s.st_size<65536,'protected original transport file')
|
||||
def digest(path):return hashlib.sha256(path.read_bytes()).hexdigest()
|
||||
check(authorized,0o644);check(profile,0o644)
|
||||
account=pwd.getpwnam('rmm-win-tunnel');require(account.pw_dir=='/var/lib/rmm-win-tunnel' and account.pw_shell=='/usr/sbin/nologin','existing forwarding-only account')
|
||||
public=' '.join(Path('/etc/ssh/ssh_host_ed25519_key.pub').read_text().split()[:2])
|
||||
fingerprint=subprocess.run(['ssh-keygen','-lf','/etc/ssh/ssh_host_ed25519_key.pub'],capture_output=True,check=True,timeout=10).stdout.decode().split()[1]
|
||||
require(fingerprint=='SHA256:+NEin4XJc3CbhjQi7/ZpMIgxOrXn8AT2tlpTaXW5quw','confirmed original server host key')
|
||||
raw=authorized.read_text();match=re.fullmatch(r'restrict,port-forwarding,permitlisten="127\.0\.0\.1:22240",expiry-time="(\d{14}Z)" (ssh-ed25519 [A-Za-z0-9+/=]{68})\n',raw)
|
||||
require(match is not None and match[2]==payload['tunnel_public_key'],'exact unchanged forwarding key/options')
|
||||
effective=subprocess.run(['/usr/sbin/sshd','-T','-C','user=rmm-win-tunnel,host=localhost,addr=127.0.0.1'],capture_output=True,check=True,timeout=10).stdout
|
||||
for line in (b'allowtcpforwarding remote\n',b'permitlisten 127.0.0.1:22240\n',b'permitopen none\n',b'gatewayports no\n',b'maxsessions 0\n',b'passwordauthentication no\n'):require(line in effective,'same restricted forwarding-only profile')
|
||||
def state():return dict(read_only=True,authorized_sha256=digest(authorized),profile_sha256=digest(profile),effective_sha256=hashlib.sha256(effective).hexdigest(),server_host_key_sha256=hashlib.sha256(public.encode()).hexdigest(),tunnel_public_key_sha256=hashlib.sha256(match[2].encode()).hexdigest(),expiry=match[1],uid=account.pw_uid,gid=account.pw_gid,home=account.pw_dir,shell=account.pw_shell)
|
||||
if payload['phase']=='state':return state()
|
||||
if payload['phase']=='readback':
|
||||
value=state();value['case_exists']=case.exists();value['replace_intent']=case.exists() and (case/'replace-intent.json').exists();value['completed']=case.exists() and (case/'completed.json').exists();return value
|
||||
old=dt.datetime.fromisoformat(payload['old_expiry']).astimezone(dt.timezone.utc);new=dt.datetime.fromisoformat(payload['new_expiry']).astimezone(dt.timezone.utc)
|
||||
require(old.isoformat()=='2026-11-14T12:55:31.254999+00:00' and new==old.replace(microsecond=0)+dt.timedelta(hours=24) and dt.datetime.now(dt.timezone.utc)<old and state()==payload['server_before'],'exact original server expiry/CAS and single 24h extension')
|
||||
require(not case.exists(),'existing server renewal: readback only');case.mkdir(mode=0o700)
|
||||
def write(path,data,mode=0o600):
|
||||
fd=os.open(path,os.O_WRONLY|os.O_CREAT|os.O_EXCL|os.O_NOFOLLOW,mode)
|
||||
with os.fdopen(fd,'wb') as out:out.write(data);out.flush();os.fsync(out.fileno());os.fchmod(out.fileno(),mode)
|
||||
write(case/'intent.json',json.dumps(payload).encode());write(case/'authorized_keys.original',raw.encode())
|
||||
replacement=raw.replace('expiry-time="'+old.strftime('%Y%m%d%H%M%SZ')+'"','expiry-time="'+new.strftime('%Y%m%d%H%M%SZ')+'"')
|
||||
require(replacement!=raw and replacement.replace(new.strftime('%Y%m%d%H%M%SZ'),old.strftime('%Y%m%d%H%M%SZ'))==raw,'expiry only, key/options unchanged')
|
||||
candidate=authorized.parent/('renew-'+ident+'.next');write(candidate,replacement.encode(),0o644)
|
||||
write(case/'replace-intent.json',json.dumps(dict(old_sha256=digest(authorized),new_sha256=hashlib.sha256(replacement.encode()).hexdigest())).encode())
|
||||
require(digest(authorized)==payload['server_before']['authorized_sha256'] and digest(profile)==payload['server_before']['profile_sha256'],'immediate original server CAS')
|
||||
os.replace(candidate,authorized);directory=os.open(authorized.parent,os.O_RDONLY);os.fsync(directory);os.close(directory)
|
||||
require(authorized.read_text()==replacement,'actual exact renewed authorization');write(case/'completed.json',json.dumps(dict(completed=True,new_expiry=payload['new_expiry'],download_lease_changed=False)).encode())
|
||||
return dict(completed=True,authorized_sha256=digest(authorized),expiry=new.strftime('%Y%m%d%H%M%SZ'),no_new_authority=True,download_lease_changed=False)
|
||||
|
||||
|
||||
COMMON = r'''
|
||||
$ErrorActionPreference='Stop';$p=$global:RmmRenewalPayload
|
||||
if(!$p-or[guid]::ParseExact($p.id,'D').ToString()-cne$p.id-or$p.phase-notin@('state','enter','readback','worker')){throw 'Fixed access renewal'}
|
||||
$root='C:\ProgramData\RmmDevAccess';$case=Join-Path $root ('renew-'+$p.id);$config=Join-Path $root 'bootstrap-public.json';$taskName='RmmDevReverseTunnel';$workerName='RmmDevAccessRenew-'+$p.id
|
||||
$sys='S-1-5-18';$admin='S-1-5-32-544'
|
||||
function Safe($path,$directory){$i=Get-Item -LiteralPath $path -Force;if($i.PSIsContainer-ne$directory-or($i.Attributes-band[IO.FileAttributes]::ReparsePoint)){throw 'Original regular transport path'};$a=Get-Acl -LiteralPath $path;if($a.GetOwner([Security.Principal.SecurityIdentifier]).Value-notin@($sys,$admin)){throw 'Transport owner'};$rules=@($a.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier]));if(!$rules.Count){throw 'Empty transport ACL'};foreach($r in $rules){if($r.AccessControlType-ne'Allow'-or$r.IdentityReference.Value-notin@($sys,$admin)){throw 'Private transport ACL'}}}
|
||||
function SafePublic($path){
|
||||
if($path-notin@((Join-Path $root 'tunnel_ed25519.pub'),'C:\ProgramData\ssh\ssh_host_ed25519_key.pub')){throw 'Only two fixed public key files'}
|
||||
$i=Get-Item -LiteralPath $path -Force;if($i.PSIsContainer-or($i.Attributes-band[IO.FileAttributes]::ReparsePoint)-or$i.Length-gt4096){throw 'Bounded regular public key'};Safe $i.Directory.FullName $true
|
||||
$ancestor=$i.Directory;while($null-ne$ancestor){if($ancestor.Attributes-band[IO.FileAttributes]::ReparsePoint){throw 'Public key reparse ancestor'};$ancestor=$ancestor.Parent}
|
||||
$builtin=@(Get-LocalUser|Where-Object{$_.SID.Value-like'*-500'});if($builtin.Count-ne1){throw 'Actual builtin Administrator SID'};$builtinSid=$builtin[0].SID.Value
|
||||
if(@(Get-LocalGroupMember -SID $admin|Where-Object{$_.SID.Value-ceq$builtinSid}).Count-ne1){throw 'Builtin Administrator membership'}
|
||||
$a=Get-Acl -LiteralPath $path;if($a.GetOwner([Security.Principal.SecurityIdentifier]).Value-notin@($sys,$admin,$builtinSid)){throw 'Public key trusted owner'};$rules=@($a.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier]));if(!$rules.Count){throw 'Empty public DACL'}
|
||||
foreach($r in $rules){if($r.AccessControlType-ne'Allow'){throw 'Public key DACL shape'};if($r.IdentityReference.Value-notin@($sys,$admin,$builtinSid)-and([int64]$r.FileSystemRights-band(-bnot[int64]0x1200a9))-ne0){throw 'No public file writer beyond SYSTEM/Admin/builtin Administrator'}}
|
||||
}
|
||||
function HashPublic($path){SafePublic $path;return(Get-FileHash -LiteralPath $path -Algorithm SHA256).Hash.ToLowerInvariant()}
|
||||
function HashBytes([byte[]]$b){$h=[Security.Cryptography.SHA256]::Create();try{return([BitConverter]::ToString($h.ComputeHash($b))).Replace('-','').ToLowerInvariant()}finally{$h.Dispose()}}
|
||||
function Hash($path){Safe $path $false;return(Get-FileHash -LiteralPath $path -Algorithm SHA256).Hash.ToLowerInvariant()}
|
||||
function Acl($path){return HashBytes ([Text.Encoding]::UTF8.GetBytes((Get-Acl -LiteralPath $path).Sddl))}
|
||||
function WriteBytes($path,[byte[]]$b){$f=[IO.File]::Open($path,'CreateNew','Write','Read');try{$f.Write($b,0,$b.Length);$f.Flush($true)}finally{$f.Dispose()}}
|
||||
function WriteNew($path,$value){WriteBytes $path ([Text.Encoding]::UTF8.GetBytes(($value|ConvertTo-Json -Depth 16 -Compress)))}
|
||||
function Equal($a,$b){return(($a|ConvertTo-Json -Depth 16 -Compress)-ceq($b|ConvertTo-Json -Depth 16 -Compress))}
|
||||
function ProcessRecord($process){
|
||||
if(!$process){return $null};$owner=(Invoke-CimMethod -InputObject $process -MethodName GetOwnerSid -OperationTimeoutSec 10).Sid;if($owner-cne$sys){throw 'Actual own SYSTEM task process'};$native=[Diagnostics.Process]::GetProcessById([int]$process.ProcessId)
|
||||
try{if($native.HasExited){throw 'Own process exited while pinning'};$birth=$native.StartTime.ToUniversalTime().ToFileTimeUtc().ToString()}finally{$native.Dispose()}
|
||||
return @{pid=[uint32]$process.ProcessId;parent_pid=[uint32]$process.ParentProcessId;creation_filetime=$birth;owner_sid=$owner;image=$process.ExecutablePath;image_sha256=(Get-FileHash -LiteralPath $process.ExecutablePath -Algorithm SHA256).Hash.ToLowerInvariant();command_sha256=(HashBytes ([Text.Encoding]::UTF8.GetBytes($process.CommandLine)))}
|
||||
}
|
||||
function OriginalTask{
|
||||
$task=Get-ScheduledTask -TaskName $taskName;$action=@($task.Actions);$expected='-NoProfile -NonInteractive -ExecutionPolicy RemoteSigned -File "C:\ProgramData\RmmDevAccess\Bootstrap-DevAccess.ps1" -MaintainTunnel'
|
||||
if($action.Count-ne1-or$action[0].Execute-ine'C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe'-or$action[0].Arguments-cne$expected-or$task.Principal.UserId-notin@('SYSTEM',$sys)-or$task.Principal.LogonType-cne'ServiceAccount'-or$task.Principal.RunLevel-cne'Highest'-or$task.Settings.MultipleInstances-cne'IgnoreNew'){throw 'Original task definition/authority'}
|
||||
return @{xml_sha256=(HashBytes ([Text.Encoding]::UTF8.GetBytes((Export-ScheduledTask -TaskName $taskName))));action_execute=$action[0].Execute;action_arguments_sha256=(HashBytes ([Text.Encoding]::UTF8.GetBytes($action[0].Arguments)));principal=$task.Principal.UserId;logon_type=[string]$task.Principal.LogonType;run_level=[string]$task.Principal.RunLevel;state=[string]$task.State}
|
||||
}
|
||||
function State{
|
||||
Safe $root $true;Safe $config $false;$cfg=Get-Content -LiteralPath $config -Raw|ConvertFrom-Json
|
||||
if((($cfg.PSObject.Properties.Name|Sort-Object)-join',')-cne'expires_at,notebook_public_key,schema_version,server,server_host_key'-or$cfg.schema_version-ne1-or$cfg.server-cne'discovery.ease-technologies.de'){throw 'Original public transport schema'}
|
||||
$user=Get-LocalUser -Name 'rmm-dev';if(!$user.Enabled-or!$user.AccountExpires){throw 'Original enabled temporary access account'}
|
||||
$files=[ordered]@{};foreach($entry in @(@('bootstrap',(Join-Path $root 'Bootstrap-DevAccess.ps1')),@('known_hosts',(Join-Path $root 'known_hosts')),@('public_key',(Join-Path $root 'tunnel_ed25519.pub')),@('sshd_config','C:\ProgramData\ssh\sshd_config'),@('authorized','C:\ProgramData\ssh\administrators_authorized_keys'),@('host_public','C:\ProgramData\ssh\ssh_host_ed25519_key.pub'))){$digest=$null;if($entry[0]-in@('public_key','host_public')){$digest=HashPublic $entry[1]}else{$digest=Hash $entry[1]};$files[$entry[0]]=@{sha256=$digest;acl_sha256=(Acl $entry[1])}}
|
||||
$key=Join-Path $root 'tunnel_ed25519';Safe $key $false;$k=Get-Item -LiteralPath $key -Force
|
||||
$known=[IO.File]::ReadAllText((Join-Path $root 'known_hosts'));if($known-cne('discovery.ease-technologies.de '+$cfg.server_host_key+"`n")){throw 'Original strict server host pin'}
|
||||
$public=((Get-Content -LiteralPath (Join-Path $root 'tunnel_ed25519.pub') -Raw).Trim()-split'\s+')[0..1]-join' ';if($public-cne$p.tunnel_public_key){throw 'Original VM tunnel public key'}
|
||||
$hostPublic=((Get-Content -LiteralPath 'C:\ProgramData\ssh\ssh_host_ed25519_key.pub' -Raw).Trim()-split'\s+')[0..1]-join' ';if($hostPublic-cne$p.windows_host_public_key){throw 'Console-confirmed original VM host pin'}
|
||||
if((Get-Content -LiteralPath 'C:\ProgramData\ssh\administrators_authorized_keys' -Raw)-cne($cfg.notebook_public_key+"`n")){throw 'Original only notebook public key'}
|
||||
$t=OriginalTask;$all=@(Get-CimInstance Win32_Process -Filter "Name='powershell.exe'" -OperationTimeoutSec 10|Where-Object{$_.CommandLine-like'*Bootstrap-DevAccess.ps1* -MaintainTunnel*'});if($all.Count-gt1){throw 'Only original maintainer instance'};$maintainer=$null;$child=$null
|
||||
if($all.Count-eq1){if($all[0].ExecutablePath-ine$t.action_execute){throw 'Original maintainer image'};$maintainer=ProcessRecord $all[0];$children=@(Get-CimInstance Win32_Process -Filter ('ParentProcessId='+$maintainer.pid) -OperationTimeoutSec 10|Where-Object{$_.Name-ceq'ssh.exe'});if($children.Count-gt1){throw 'Only original SSH child'};if($children.Count-eq1){if($children[0].ExecutablePath-ine'C:\Windows\System32\OpenSSH\ssh.exe'-or$children[0].CommandLine-notlike'*-R*127.0.0.1:22240:127.0.0.1:22222*rmm-win-tunnel@discovery.ease-technologies.de*'){throw 'Original restricted SSH child'};$child=ProcessRecord $children[0]}}
|
||||
$listeners=@(Get-NetTCPConnection -State Listen -LocalPort 22222 -ErrorAction SilentlyContinue);if(!$listeners.Count-or@($listeners|Where-Object{$_.LocalAddress-cne'127.0.0.1'}).Count){throw 'Existing SSH loopback-only listener'}
|
||||
return @{config_sha256=(Hash $config);config_acl_sha256=(Acl $config);expires_at=$cfg.expires_at;account_sid=$user.SID.Value;account_expires_filetime=$user.AccountExpires.ToUniversalTime().ToFileTimeUtc().ToString();files=$files;private_key_metadata=@{bytes=$k.Length;created=$k.CreationTimeUtc.Ticks.ToString();written=$k.LastWriteTimeUtc.Ticks.ToString();acl_sha256=(Acl $key);private_key_read=$false};server_host_key_sha256=(HashBytes ([Text.Encoding]::UTF8.GetBytes($cfg.server_host_key)));task=$t;maintainer=$maintainer;ssh_child=$child}
|
||||
}
|
||||
function ReadIntent{Safe $case $true;Safe (Join-Path $case 'intent.json') $false;$i=Get-Content -LiteralPath (Join-Path $case 'intent.json') -Raw|ConvertFrom-Json;foreach($field in $p.PSObject.Properties.Name){if($field-cne'phase'-and!(Equal $i.$field $p.$field)){throw 'Same exact original renewal intent'}};return $i}
|
||||
'''
|
||||
WORKER = COMMON + r'''
|
||||
$p=Get-Content -LiteralPath (Join-Path $PSScriptRoot 'intent.json') -Raw|ConvertFrom-Json;$p.phase='worker';$null=ReadIntent
|
||||
if((Hash $PSCommandPath)-cne$p.worker_sha256-or$PSCommandPath-cne(Join-Path $case 'Renew-Transport.ps1')){throw 'Actual fixed own worker source'}
|
||||
WriteNew (Join-Path $case 'worker-started.json') @{once=$true;utc=[DateTimeOffset]::UtcNow.ToString('o')}
|
||||
$registration=Get-Content -LiteralPath (Join-Path $case 'worker-registered.json') -Raw|ConvertFrom-Json;if((HashBytes ([Text.Encoding]::UTF8.GetBytes((Export-ScheduledTask -TaskName $workerName))))-cne$registration.worker_xml_sha256){throw 'Exact own worker task definition'}
|
||||
$now=[DateTimeOffset]::UtcNow;if($p.start_at-cne'2026-11-14T12:56:31+00:00'-or$now-lt[DateTimeOffset]::Parse($p.start_at)-or$now-gt[DateTimeOffset]::Parse($p.start_at).AddMinutes(5)){throw 'Only narrow original expiry+60s worker window'}
|
||||
$state=State;if($state.expires_at-cne$p.new_expiry-or$state.account_expires_filetime-cne$p.new_account_filetime-or$state.task.state-cne'Ready'-or$null-ne$state.maintainer-or$null-ne$state.ssh_child){throw 'Old task/child must have naturally exited; never kill or repeat'}
|
||||
foreach($field in @('files','private_key_metadata','account_sid','config_acl_sha256','server_host_key_sha256')){if(!(Equal $p.before.$field $state.$field)){throw 'Original transport identity/ACL changed'}}
|
||||
if($state.task.xml_sha256-cne$p.before.task.xml_sha256){throw 'Original task XML unchanged'}
|
||||
foreach($record in @($p.before.maintainer,$p.before.ssh_child)){$current=Get-Process -Id $record.pid -ErrorAction SilentlyContinue;if($current){try{if($current.StartTime.ToUniversalTime().ToFileTimeUtc().ToString()-ceq$record.creation_filetime-and!$current.HasExited){throw 'Original pinned process still alive'}}finally{$current.Dispose()}}}
|
||||
WriteNew (Join-Path $case 'original-task-start-attempt.json') @{once=$true;original_task=$taskName;original_xml_sha256=$state.task.xml_sha256}
|
||||
Start-ScheduledTask -TaskName $taskName
|
||||
$deadline=[DateTimeOffset]::UtcNow.AddSeconds(30);do{Start-Sleep -Seconds 1;$after=State;if($after.task.state-ceq'Running'-and$null-ne$after.maintainer-and$null-ne$after.ssh_child){break}}while([DateTimeOffset]::UtcNow-lt$deadline)
|
||||
if($after.task.state-cne'Running'-or$null-eq$after.maintainer-or$null-eq$after.ssh_child-or$after.task.xml_sha256-cne$p.before.task.xml_sha256){throw 'One fresh original tunnel task start not verified'}
|
||||
WriteNew (Join-Path $case 'completed.json') @{completed=$true;new_expiry=$p.new_expiry;new_state=$after;no_kill=$true;no_new_authority=$true;download_lease_changed=$false}
|
||||
Disable-ScheduledTask -TaskName $workerName|Out-Null
|
||||
WriteNew (Join-Path $case 'worker-disabled.json') @{disabled=$true;retained=$true}
|
||||
'''
|
||||
SCRIPT = COMMON + r'''
|
||||
if($p.phase-ceq'state'){State|ConvertTo-Json -Depth 16 -Compress;exit 0}
|
||||
if($p.phase-ceq'readback'){$value=@{read_only=$true;state=(State);case_exists=(Test-Path -LiteralPath $case)};if($value.case_exists){$null=ReadIntent;$value['phases']=@{};foreach($name in @('config-replace-attempt','config-replaced','account-expiry-attempt','account-expiry-set','worker-register-attempt','worker-registered','worker-started','original-task-start-attempt','completed','worker-disabled')){$value.phases[$name]=Test-Path -LiteralPath (Join-Path $case ($name+'.json'))}};$value|ConvertTo-Json -Depth 16 -Compress;exit 0}
|
||||
if($p.phase-cne'enter'-or(Test-Path -LiteralPath $case)-or(Get-ScheduledTask -TaskName $workerName -ErrorAction SilentlyContinue)){throw 'Single new renewal admission; readback only'}
|
||||
if($p.old_expiry-cne'2026-11-14T12:55:31.254999+00:00'-or[DateTimeOffset]::Parse($p.new_expiry)-ne[DateTimeOffset]::Parse($p.old_expiry).AddHours(24).AddTicks(-2549990)-or[DateTimeOffset]::UtcNow-ge[DateTimeOffset]::Parse($p.old_expiry)){throw 'Exact original window and 24h renewal'}
|
||||
$before=State;if(!(Equal $before $p.before)-or$before.task.state-cne'Running'-or$null-eq$before.maintainer-or$null-eq$before.ssh_child){throw 'Concrete original live transport CAS'}
|
||||
New-Item -ItemType Directory -Path $case|Out-Null;Safe $case $true;WriteNew (Join-Path $case 'intent.json') $p
|
||||
$original=Join-Path $case 'bootstrap-public.original';[IO.File]::Copy($config,$original,$false);Safe $original $false
|
||||
$cfg=Get-Content -LiteralPath $config -Raw|ConvertFrom-Json;$cfg.expires_at=$p.new_expiry;$candidate=Join-Path $case 'bootstrap-public.next';WriteNew $candidate $cfg;$nativeBackup=Join-Path $case 'bootstrap-public.native-original'
|
||||
WriteNew (Join-Path $case 'config-replace-attempt.json') @{original_sha256=$before.config_sha256;native_backup=$nativeBackup}
|
||||
if((Hash $config)-cne$before.config_sha256-or(Test-Path -LiteralPath $nativeBackup)){throw 'Immediate original config CAS'};$sddl=(Get-Acl -LiteralPath $config).Sddl;[IO.File]::Replace($candidate,$config,$nativeBackup);$acl=New-Object Security.AccessControl.FileSecurity;$acl.SetSecurityDescriptorSddlForm($sddl);Set-Acl -LiteralPath $config -AclObject $acl
|
||||
WriteNew (Join-Path $case 'config-replaced.json') @{sha256=(Hash $config);native_backup_sha256=(Hash $nativeBackup)}
|
||||
WriteNew (Join-Path $case 'account-expiry-attempt.json') @{account='rmm-dev';old_filetime=$before.account_expires_filetime;new_filetime=$p.new_account_filetime}
|
||||
$currentUser=Get-LocalUser -Name 'rmm-dev';if($currentUser.SID.Value-cne$before.account_sid-or$currentUser.AccountExpires.ToUniversalTime().ToFileTimeUtc().ToString()-cne$before.account_expires_filetime){throw 'Immediate original account SID/expiry CAS'}
|
||||
Set-LocalUser -Name 'rmm-dev' -AccountExpires ([DateTimeOffset]::Parse($p.new_expiry).LocalDateTime)
|
||||
if((Get-LocalUser -Name 'rmm-dev').AccountExpires.ToUniversalTime().ToFileTimeUtc().ToString()-cne$p.new_account_filetime){throw 'Actual exact account expiry'};WriteNew (Join-Path $case 'account-expiry-set.json') @{new_filetime=$p.new_account_filetime}
|
||||
$worker=Join-Path $case 'Renew-Transport.ps1';$bytes=[Convert]::FromBase64String($p.worker_base64);if((HashBytes $bytes)-cne$p.worker_sha256){throw 'Exact reviewed renewal worker'};WriteBytes $worker $bytes;Safe $worker $false
|
||||
$action=New-ScheduledTaskAction -Execute 'C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe' -Argument ('-NoProfile -NonInteractive -ExecutionPolicy RemoteSigned -File "'+$worker+'"')
|
||||
$principal=New-ScheduledTaskPrincipal -UserId 'SYSTEM' -LogonType ServiceAccount -RunLevel Highest
|
||||
$settings=New-ScheduledTaskSettingsSet -MultipleInstances IgnoreNew -ExecutionTimeLimit ([TimeSpan]::FromMinutes(2)) -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries
|
||||
$trigger=New-ScheduledTaskTrigger -Once -At ([DateTimeOffset]::Parse($p.start_at).LocalDateTime)
|
||||
WriteNew (Join-Path $case 'worker-register-attempt.json') @{name=$workerName;source_sha256=$p.worker_sha256;once=$true;start_at=$p.start_at}
|
||||
Register-ScheduledTask -TaskName $workerName -Action $action -Trigger $trigger -Settings $settings -Principal $principal|Out-Null
|
||||
WriteNew (Join-Path $case 'worker-registered.json') @{registered=$true;original_task_unmodified=$true;worker_xml_sha256=(HashBytes ([Text.Encoding]::UTF8.GetBytes((Export-ScheduledTask -TaskName $workerName))))}
|
||||
@{entered=$true;planned_gap=$true;start_at=$p.start_at;new_expiry=$p.new_expiry;original_task_restarted_now=$false;download_lease_changed=$false}|ConvertTo-Json -Compress
|
||||
'''
|
||||
# Worker sets its own fixed payload before COMMON examines it.
|
||||
WORKER = "$global:RmmRenewalPayload=Get-Content -LiteralPath (Join-Path $PSScriptRoot 'intent.json') -Raw|ConvertFrom-Json;$global:RmmRenewalPayload.phase='worker'\n" + WORKER
|
||||
|
||||
|
||||
class Access(pair.Access):
|
||||
def stage_controller(self,path):
|
||||
name='DevAccessRenewal.ps1';digest=sha(path)
|
||||
prepare=pair.u.transport.PREPARE_SCRIPT.replace('TransportAcceptance.ps1',name)
|
||||
observed=self.powershell(prepare,dict(sha256=digest))
|
||||
if not observed['already_uploaded']:
|
||||
access=cb.contract.protected_json(self.root/'credentials/windows-dev-access.json');prefix=access['ssh_prefix']
|
||||
args=['sftp']+[p for p in prefix[1:-1] if p!='-T']+['-b','-',prefix[-1]]
|
||||
target='/C:/ProgramData/RustDiscoveryBootstrap/'+digest+'/'+name
|
||||
result=subprocess.run(args,input=('put '+json.dumps(str(path.resolve()))+' '+json.dumps(target)+'\n').encode(),capture_output=True,timeout=60)
|
||||
require(result.returncode==0,'single exact renewal source transfer; no retry')
|
||||
require(self.powershell(prepare,dict(sha256=digest))['already_uploaded'] is True,'exact staged controller')
|
||||
|
||||
def rpc(self, payload):
|
||||
cloud=pair.u.transport.cloud;cfg=cloud.bootstrap.access.load_config(self.root/'credentials/server.conf')
|
||||
ssh=['ssh','-F','/dev/null','-T','-p',cfg.get('port','22'),'-o','StrictHostKeyChecking=yes','-o','BatchMode=yes','-o','IdentitiesOnly=yes','-o','ForwardAgent=no','-i',str(Path(cfg['ssh_key_path']).expanduser()),cfg['username']+'@'+cfg['address'],'python3 -']
|
||||
code='import os,json,subprocess,base64,hashlib,uuid,pwd\nfrom pathlib import Path\n'+inspect.getsource(cloud.bootstrap.require)+'\n'+inspect.getsource(server)+'\ntry:\n print(json.dumps(server('+repr(payload)+')))\nexcept Exception as e:\n print(json.dumps(dict(error=type(e).__name__)))\n'
|
||||
result=subprocess.run(ssh,input=code.encode(),capture_output=True,timeout=60);require(result.returncode==0,'fixed renewal server RPC')
|
||||
value=json.loads(result.stdout,object_pairs_hook=cb.contract.strict_object);require('error' not in value,'server renewal incomplete; readback only');return value
|
||||
|
||||
def windows(self,payload):
|
||||
# Existing fixed access bridge; no credentials copy or Main writes.
|
||||
launch=pair.LAUNCH.replace('SystemPipeUpgrade.ps1','DevAccessRenewal.ps1').replace('RmmPipeUpgradePayload','RmmRenewalPayload')
|
||||
return self.powershell(launch,dict(sha256=pair.raw_sha(SCRIPT.encode()),payload=payload),timeout=150)
|
||||
|
||||
|
||||
def load(access,ident):
|
||||
require(str(uuid.UUID(ident))==ident,'canonical case');folder=STATE/ident;intent=cb.contract.protected_json(folder/'intent.json')
|
||||
require(intent['runner_sha256']==sha(__file__) and intent['worker_sha256']==pair.raw_sha(WORKER.encode()) and intent['access_root']==str(access.root),'original immutable renewal source/accessroot')
|
||||
return folder,intent
|
||||
|
||||
|
||||
def prepare(access):
|
||||
ident=str(uuid.uuid4());folder=STATE/ident;folder.mkdir(mode=0o700,parents=True)
|
||||
console=cb.contract.protected_json(access.root/'devstate/windows-bootstrap/console-registration.json')
|
||||
payload=dict(id=ident,phase='state',tunnel_public_key=console['tunnel_public_key'],windows_host_public_key=console['windows_host_public_key'],old_expiry=OLD_EXPIRY,new_expiry=NEW_UTC.isoformat(),start_at=START_UTC.isoformat(),new_account_filetime=str((int(NEW_UTC.timestamp())+11644473600)*10000000),worker_sha256=pair.raw_sha(WORKER.encode()),worker_base64=base64.b64encode(WORKER.encode()).decode())
|
||||
require(cb.contract.now()<OLD_UTC,'original lease still active')
|
||||
save(folder/'prepare-intent.json',dict(id=ident,runner_sha256=sha(__file__),no_new_authority=True))
|
||||
source=folder/'DevAccessRenewal.ps1';pair.write_bytes(source,SCRIPT.encode());access.stage_controller(source)
|
||||
before=access.windows(payload);server_before=access.rpc(payload)
|
||||
require(before['files']['bootstrap']['sha256']==sha(cb.ROOT/'deploy/windows/Bootstrap-DevAccess.ps1'),'original fixed maintainer source')
|
||||
require(before['expires_at']==OLD_EXPIRY and before['server_host_key_sha256']==server_before['server_host_key_sha256'] and server_before['expiry']==OLD_UTC.strftime('%Y%m%d%H%M%SZ'),'same original windows/server expiry/host pin')
|
||||
payload.update(before=before,server_before=server_before)
|
||||
intent=dict(id=ident,runner_sha256=sha(__file__),worker_sha256=payload['worker_sha256'],access_root=str(access.root),payload=payload)
|
||||
save(folder/'intent.json',intent)
|
||||
print(json.dumps(dict(id=ident,prepared=True,review_sha256=sha(folder/'intent.json'),new_expiry=payload['new_expiry'],start_at=payload['start_at'],planned_short_gap=True)))
|
||||
|
||||
|
||||
def run(access,ident,phase,review_sha=None):
|
||||
folder,intent=load(access,ident);payload=dict(intent['payload'],phase='readback' if phase=='readback' else 'enter')
|
||||
if phase=='enter':
|
||||
require(review_sha==sha(folder/'intent.json'),'explicit reviewed renewal intent SHA')
|
||||
save(folder/'server-enter-attempt.json',dict(once=True))
|
||||
server_result=access.rpc(payload);require(server_result.get('completed') is True,'server expiry CAS first');save(folder/'server-entered.json',server_result)
|
||||
save(folder/'windows-enter-attempt.json',dict(once=True))
|
||||
observed=access.windows(payload);save(folder/'windows-entered.json',observed)
|
||||
else:
|
||||
server_result=access.rpc(payload);observed=access.windows(payload);save(folder/('readback-'+str(uuid.uuid4())+'.json'),dict(server=server_result,windows=observed))
|
||||
print(json.dumps(dict(id=ident,phase=phase,server_expiry=server_result.get('expiry'),windows=observed,main_config_updated=False)))
|
||||
|
||||
|
||||
def main():
|
||||
os.umask(0o077);parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('phase',choices=('prepare','enter','readback'));parser.add_argument('--access-root',required=True,type=Path);parser.add_argument('--id');parser.add_argument('--review-sha256');args=parser.parse_args();access=Access(args.access_root)
|
||||
if args.phase=='prepare':require(not(args.id or args.review_sha256),'new readonly renewal baseline');prepare(access)
|
||||
else:require(args.id and ((args.phase=='enter')==bool(args.review_sha256)),'same case and reviewed intent for enter');run(access,args.id,args.phase,args.review_sha256)
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
try:main()
|
||||
except Exception as error:print('DEV_ACCESS_RENEWAL_INCOMPLETE:'+type(error).__name__);raise SystemExit(2) from None
|
||||
@@ -0,0 +1,193 @@
|
||||
#!/usr/bin/env python3
|
||||
"""One reviewed recovery of the unchanged failed6d2 joint upgrade; no retries.
|
||||
|
||||
Uses explicit File.Replace backup paths, preserving the original failed source,
|
||||
attempt, four backups, journals and intent. Readback never swaps or starts.
|
||||
"""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import uuid
|
||||
|
||||
import client_bootstrap as cb
|
||||
import system_delegation_upgrade as u
|
||||
|
||||
CASE = '6d2df065-0877-41c4-983c-2c9fdb6e5437'
|
||||
ORIGINAL_SOURCE = 'f8dc1c8fbc064e253b1fbe130fb628afef58cf45c2bafb6837d6716125b42d38'
|
||||
STATE = cb.EVIDENCE / 'system-delegation-recovery'
|
||||
require = cb.contract.require
|
||||
PREFIX = u.SCRIPT.split('\nCheckControl $boot $true\n', 1)[0]
|
||||
|
||||
SCRIPT = PREFIX + r'''
|
||||
$r=$global:RmmDelegationRecoveryPayload
|
||||
if(!$r-or[guid]::ParseExact($r.recovery_id,'D').ToString()-cne$r.recovery_id-or$r.phase-notin@('prepare','enter','readback')-or$p.id-cne'6d2df065-0877-41c4-983c-2c9fdb6e5437'-or$r.script_sha256-notmatch'^[a-f0-9]{64}$'){throw 'Only the original failed6d recovery'}
|
||||
CheckControl $boot $true
|
||||
$ownScript=Join-Path (Join-Path $boot $r.script_sha256) 'SystemDelegationRecovery.ps1'
|
||||
if($PSCommandPath-cne$ownScript-or(Hash $PSCommandPath)-cne$r.script_sha256){throw 'Exact actually executing recovery source'}
|
||||
CheckControl $ownScript $false
|
||||
$intent=ReadIntent
|
||||
$recovery=Join-Path $boot ('system-delegation-recovery-'+$r.recovery_id)
|
||||
$recoveryActive=Join-Path $boot 'system-delegation-6d2-recovery-once.json'
|
||||
function ReadService($role){$name=$agentName;if($role-ceq'helper'){$name=$helperName};$s=Get-CimInstance Win32_Service -Filter ("Name='"+$name+"'") -OperationTimeoutSec 10;if(!$s){throw 'Fixed existing service'};return @{state=$s.State;pid=$s.ProcessId;account=$s.StartName;mode=$s.StartMode;path=$s.PathName;exit_code=$s.ExitCode}}
|
||||
function MaybeHash($path){if(!(Test-Path -LiteralPath $path)){return $null};return Hash $path}
|
||||
function RecoveryReadback{
|
||||
$original=[ordered]@{};foreach($name in @('agent-stop-attempt','agent-stopped','helper-stop-attempt','helper-stopped','frozen','agent-backup','helper-backup','settings-backup','pin-backup','agent-replace-attempt','helper-replace-attempt','settings-replace-attempt','pin-replace-attempt','agent-replaced','helper-replaced','settings-replaced','pin-replaced','swapped','helper-start-attempt','helper-started','agent-start-attempt','agent-started','entered')){$original[$name]=Test-Path -LiteralPath (Join-Path $folder ($name+'.json'))}
|
||||
$own=[ordered]@{};foreach($name in @('intent','prepared','enter-attempt','agent-replace-attempt','agent-replaced','helper-replace-attempt','helper-replaced','settings-replace-attempt','settings-replaced','pin-replace-attempt','pin-replaced','swapped','helper-start-intent','agent-start-intent','entered')){$own[$name]=Test-Path -LiteralPath (Join-Path $recovery ($name+'.json'))}
|
||||
return @{read_only=$true;original_id=$p.id;recovery_id=$r.recovery_id;hashes=@{agent=(MaybeHash $agentBinary);helper=(MaybeHash $helperBinary);settings=(MaybeHash $settings);pin=(MaybeHash $pin)};service=(ReadService 'agent');helper_service=(ReadService 'helper');original_phases=$original;recovery_phases=$own;recovery_active_exists=(Test-Path -LiteralPath $recoveryActive);no_repeated_start=$true}
|
||||
}
|
||||
if($r.phase-ceq'readback'){RecoveryReadback|ConvertTo-Json -Depth 20 -Compress;exit 0}
|
||||
Add-Type -TypeDefinition @'
|
||||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
using Microsoft.Win32.SafeHandles;
|
||||
public static class RmmDelegationRecoveryFileId {
|
||||
[StructLayout(LayoutKind.Sequential)] public struct Id {
|
||||
public ulong VolumeSerialNumber;
|
||||
[MarshalAs(UnmanagedType.ByValArray, SizeConst=16)] public byte[] FileId;
|
||||
}
|
||||
[DllImport("kernel32.dll", SetLastError=true)]
|
||||
public static extern bool GetFileInformationByHandleEx(SafeFileHandle handle, int kind, out Id info, uint length);
|
||||
}
|
||||
'@
|
||||
function FileIdentity($path){
|
||||
Check $path $false;$file=[IO.File]::Open($path,[IO.FileMode]::Open,[IO.FileAccess]::Read,[IO.FileShare]::Read)
|
||||
try{$id=New-Object RmmDelegationRecoveryFileId+Id;$size=[Runtime.InteropServices.Marshal]::SizeOf([type][RmmDelegationRecoveryFileId+Id]);if($size-ne24-or![RmmDelegationRecoveryFileId]::GetFileInformationByHandleEx($file.SafeFileHandle,18,[ref]$id,[uint32]$size)){throw 'Exact native file identity'}
|
||||
return [ordered]@{volume_serial=$id.VolumeSerialNumber.ToString([Globalization.CultureInfo]::InvariantCulture);file_id=([BitConverter]::ToString($id.FileId)).Replace('-','').ToLowerInvariant();bytes=$file.Length;acl_sha256=(AclHash $path);sha256=(Hash $path)}
|
||||
}finally{$file.Dispose()}
|
||||
}
|
||||
function CheckOriginalStopped{
|
||||
foreach($name in @('intent','agent-stop-attempt','agent-stopped','helper-stop-attempt','helper-stopped','frozen','agent-backup','helper-backup','settings-backup','pin-backup','agent-replace-attempt')){CheckControl (Join-Path $folder ($name+'.json')) $false}
|
||||
foreach($name in @('helper-replace-attempt','settings-replace-attempt','pin-replace-attempt','agent-replaced','helper-replaced','settings-replaced','pin-replaced','swapped','helper-start-attempt','helper-started','agent-start-attempt','agent-started','entered')){if(Test-Path -LiteralPath (Join-Path $folder ($name+'.json'))){throw 'Original case progressed; no recovery replay'}}
|
||||
$frozen=Get-Content -LiteralPath (Join-Path $folder 'frozen.json') -Raw|ConvertFrom-Json
|
||||
$current=State $false
|
||||
if($current.service.state-cne'Stopped'-or$current.helper_service.state-cne'Stopped'){throw 'Both own original services must remain stopped'}
|
||||
Preserved $frozen $current $true
|
||||
$checks=@(@('agent',$p.old_agent,$p.new_agent),@('helper',$p.old_helper,$p.new_helper),@('settings',$p.old_policy,$p.new_policy),@('pin',$p.old_pin,$p.new_pin))
|
||||
foreach($item in $checks){$backup=Join-Path $folder ($item[0]+'-original');CheckControl $backup $false;if((Hash $backup)-cne$item[1]){throw 'Original exact backup'};$receipt=Get-Content -LiteralPath (Join-Path $folder ($item[0]+'-backup.json')) -Raw|ConvertFrom-Json;if($receipt.sha256-cne$item[1]){throw 'Original backup receipt'}}
|
||||
$attempt=Get-Content -LiteralPath (Join-Path $folder 'agent-replace-attempt.json') -Raw|ConvertFrom-Json
|
||||
if($attempt.old_sha256-cne$p.old_agent-or$attempt.new_sha256-cne$p.new_agent){throw 'Original unchanged failed agent attempt'}
|
||||
if((Hash (Join-Path $folder 'agent-candidate'))-cne$p.new_agent){throw 'Retain exact original agent candidate'}
|
||||
foreach($label in @('helper','settings','pin')){if(Test-Path -LiteralPath (Join-Path $folder ($label+'-candidate'))){throw 'No other old candidate expected'}}
|
||||
if((Hash (Join-Path (Join-Path $boot $p.new_agent) 'rmm-agent-windows.exe'))-cne$p.new_agent-or(Hash (Join-Path (Join-Path $boot $p.new_helper) 'rmm-helper-windows.exe'))-cne$p.new_helper-or(Hash (Join-Path $folder 'new-helper.json'))-cne$p.new_policy-or(Hash (Join-Path $folder 'new-agent-pin.json'))-cne$p.new_pin){throw 'All four complete new sources'}
|
||||
$current['recovery_file_identities']=[ordered]@{agent=(FileIdentity $agentBinary);helper=(FileIdentity $helperBinary);settings=(FileIdentity $settings);pin=(FileIdentity $pin);agent_candidate=(FileIdentity (Join-Path $folder 'agent-candidate'))}
|
||||
return $current
|
||||
}
|
||||
if($r.phase-ceq'prepare'){
|
||||
if((Test-Path -LiteralPath $recovery)-or(Test-Path -LiteralPath $recoveryActive)){throw 'Existing recovery: readback only'}
|
||||
$before=CheckOriginalStopped
|
||||
New-Item -ItemType Directory -Path $recovery|Out-Null;CheckControl $recovery $true
|
||||
WriteNew $recoveryActive @{original_id=$p.id;recovery_id=$r.recovery_id;script_sha256=$r.script_sha256;create_only=$true}
|
||||
WriteNew (Join-Path $recovery 'intent.json') @{original_id=$p.id;recovery_id=$r.recovery_id;script_sha256=$r.script_sha256;original_payload=$p;before=$before}
|
||||
WriteNew (Join-Path $recovery 'prepared.json') @{prepared=$true;no_service_changes=$true;original_failed_attempt_retained=$true}
|
||||
@{prepared=$true;original_id=$p.id;recovery_id=$r.recovery_id;both_stopped=$true;preserved=$true}|ConvertTo-Json -Compress;exit 0
|
||||
}
|
||||
CheckControl $recovery $true;foreach($name in @('intent.json','prepared.json')){CheckControl (Join-Path $recovery $name) $false};CheckControl $recoveryActive $false
|
||||
$saved=Get-Content -LiteralPath (Join-Path $recovery 'intent.json') -Raw|ConvertFrom-Json;$currentActive=Get-Content -LiteralPath $recoveryActive -Raw|ConvertFrom-Json
|
||||
if($saved.original_id-cne$p.id-or$saved.recovery_id-cne$r.recovery_id-or$saved.script_sha256-cne$r.script_sha256-or!(JsonEqual $saved.original_payload $p)-or$currentActive.original_id-cne$p.id-or$currentActive.recovery_id-cne$r.recovery_id-or$currentActive.script_sha256-cne$r.script_sha256){throw 'Exact original recovery admission'}
|
||||
if(Test-Path -LiteralPath (Join-Path $recovery 'enter-attempt.json')){throw 'Recovery already attempted: readback only'}
|
||||
$before=CheckOriginalStopped;Preserved $saved.before $before $true
|
||||
if(!(JsonEqual $saved.before.recovery_file_identities $before.recovery_file_identities)){throw 'Original destination/candidate file IDs or ACL/bytes changed'}
|
||||
WriteNew (Join-Path $recovery 'enter-attempt.json') @{enter_once=$true;recovery_id=$r.recovery_id;script_sha256=$r.script_sha256}
|
||||
function RecoverSwap($label,$destination,$source,$oldHash,$newHash,[bool]$reuse){
|
||||
if((Service 'agent').state-cne'Stopped'-or(Service 'helper').state-cne'Stopped'){throw 'No component start during four-file recovery'}
|
||||
$candidate=Join-Path $folder ($label+'-candidate');$nativeBackup=Join-Path $recovery ($label+'-native-original')
|
||||
$oldReceipt=Get-Content -LiteralPath (Join-Path $folder ($label+'-backup.json')) -Raw|ConvertFrom-Json;$sddl=$oldReceipt.original_sddl
|
||||
if((Hash $destination)-cne$oldHash-or(Hash $source)-cne$newHash-or(Hash (Join-Path $folder ($label+'-original')))-cne$oldHash-or(AclHash $destination)-cne(BytesHash ([Text.Encoding]::UTF8.GetBytes($sddl)))-or(Test-Path -LiteralPath $nativeBackup)){throw 'Exact old destination/backup/ACL and new source CAS'}
|
||||
if($reuse){if((Hash $candidate)-cne$newHash){throw 'Retain original exact candidate'}}else{if(Test-Path -LiteralPath $candidate){throw 'Candidate exists; no overwrite'};[IO.File]::Copy($source,$candidate,$false);FlushCopy $candidate}
|
||||
if((Hash $candidate)-cne$newHash){throw 'Complete candidate'}
|
||||
$destinationIdentity=FileIdentity $destination;$candidateIdentity=FileIdentity $candidate
|
||||
if(!(JsonEqual $destinationIdentity $before.recovery_file_identities.$label)-or($reuse-and!(JsonEqual $candidateIdentity $before.recovery_file_identities.agent_candidate))){throw 'Fresh native CAS identities/ACL/bytes'}
|
||||
WriteNew (Join-Path $recovery ($label+'-replace-attempt.json')) @{old_sha256=$oldHash;new_sha256=$newHash;native_backup=$nativeBackup;recovery_id=$r.recovery_id;source_sha256=$r.script_sha256;destination_identity=$destinationIdentity;candidate_identity=$candidateIdentity}
|
||||
[IO.File]::Replace($candidate,$destination,$nativeBackup)
|
||||
PrivateBackupAcl $nativeBackup
|
||||
$acl=New-Object Security.AccessControl.FileSecurity;$acl.SetSecurityDescriptorSddlForm($sddl);Set-Acl -LiteralPath $destination -AclObject $acl;FlushCopy $destination
|
||||
if((Hash $destination)-cne$newHash-or(Hash $nativeBackup)-cne$oldHash-or(AclHash $destination)-cne(BytesHash ([Text.Encoding]::UTF8.GetBytes($sddl)))){throw 'Actual exact replacement and explicit original backup'}
|
||||
$receipt=@{old_sha256=$oldHash;new_sha256=$newHash;backup_sha256=(Hash (Join-Path $folder ($label+'-original')));acl_sha256=(AclHash $destination);native_backup_sha256=(Hash $nativeBackup);recovery_id=$r.recovery_id;source_sha256=$r.script_sha256}
|
||||
WriteNew (Join-Path $recovery ($label+'-replaced.json')) $receipt
|
||||
WriteNew (Join-Path $folder ($label+'-replaced.json')) $receipt
|
||||
}
|
||||
try{
|
||||
RecoverSwap 'agent' $agentBinary (Join-Path (Join-Path $boot $p.new_agent) 'rmm-agent-windows.exe') $p.old_agent $p.new_agent $true
|
||||
RecoverSwap 'helper' $helperBinary (Join-Path (Join-Path $boot $p.new_helper) 'rmm-helper-windows.exe') $p.old_helper $p.new_helper $false
|
||||
RecoverSwap 'settings' $settings (Join-Path $folder 'new-helper.json') $p.old_policy $p.new_policy $false
|
||||
RecoverSwap 'pin' $pin (Join-Path $folder 'new-agent-pin.json') $p.old_pin $p.new_pin $false
|
||||
$swapped=State $true;Preserved $before $swapped $true
|
||||
if($swapped.service.state-cne'Stopped'-or$swapped.helper_service.state-cne'Stopped'){throw 'All four new files checked before first start'}
|
||||
$swapped['recovery_id']=$r.recovery_id;$swapped['recovery_source_sha256']=$r.script_sha256
|
||||
WriteNew (Join-Path $recovery 'swapped.json') $swapped;WriteNew (Join-Path $folder 'swapped.json') $swapped
|
||||
WriteNew (Join-Path $recovery 'helper-start-intent.json') @{recovery_id=$r.recovery_id;source_sha256=$r.script_sha256};StartOnce 'helper'
|
||||
WriteNew (Join-Path $recovery 'agent-start-intent.json') @{recovery_id=$r.recovery_id;source_sha256=$r.script_sha256};StartOnce 'agent'
|
||||
$after=State $true;Preserved $intent.before $after $false;Preserved $before $after $false
|
||||
$after['recovery_id']=$r.recovery_id;$after['recovery_source_sha256']=$r.script_sha256
|
||||
WriteNew (Join-Path $recovery 'entered.json') $after;WriteNew (Join-Path $folder 'entered.json') $after
|
||||
@{entered=$true;original_id=$p.id;recovery_id=$r.recovery_id;no_jobs=$true;no_reboot=$true;no_clock_change=$true}|ConvertTo-Json -Compress
|
||||
}catch{WriteNew (Join-Path $recovery ('incomplete-'+[guid]::NewGuid().ToString()+'.json')) @{error_type=$_.Exception.GetType().FullName;line=$_.InvocationInfo.ScriptLineNumber;readback_only=$true;no_retry=$true};throw}
|
||||
'''
|
||||
|
||||
PREPARE = u.transport.PREPARE_SCRIPT.replace('TransportAcceptance.ps1', 'SystemDelegationRecovery.ps1')
|
||||
LAUNCH = u.transport.LAUNCH_SCRIPT.replace('TransportAcceptance.ps1', 'SystemDelegationRecovery.ps1').replace('RmmTransportPayload', 'RmmDelegationRecoveryPayload')
|
||||
# Prefix reads the immutable original payload; the recovery data is separate.
|
||||
LAUNCH = LAUNCH.replace('& $script', '$global:RmmDelegationUpgradePayload=$p.payload.original_payload\n& $script')
|
||||
|
||||
|
||||
def load(recovery_id):
|
||||
require(str(uuid.UUID(recovery_id)) == recovery_id, 'canonical recovery UUID')
|
||||
folder = STATE / recovery_id; intent = cb.contract.protected_json(folder / 'intent.json')
|
||||
require(u.sha(u.__file__) == ORIGINAL_SOURCE and intent['runner_sha256'] == u.sha(__file__) and intent['script_sha256'] == u.raw_sha(SCRIPT.encode()), 'original and new source remain immutable')
|
||||
_, original = u.load_case(CASE)
|
||||
require(intent['original_intent_sha256'] == u.sha(u.STATE / CASE / 'intent.json') and intent['original_payload'] == original['payload'], 'unchanged original case')
|
||||
return folder, intent
|
||||
|
||||
|
||||
def remote(intent, phase):
|
||||
original_action = 'readback' if phase == 'readback' else 'enter'
|
||||
payload = dict(recovery_id=intent['recovery_id'], phase=phase, script_sha256=intent['script_sha256'], original_payload=dict(intent['original_payload'], action=original_action))
|
||||
return cb.powershell(LAUNCH, dict(sha256=intent['script_sha256'], payload=payload), timeout=180, remote_signed=True)
|
||||
|
||||
|
||||
def prepare():
|
||||
require(u.sha(u.__file__) == ORIGINAL_SOURCE, 'original failed runner must not change')
|
||||
_, original = u.load_case(CASE)
|
||||
original_folder = u.STATE / CASE
|
||||
require((original_folder / 'enter-attempt.json').is_file() and (original_folder / 'reply-incomplete.json').is_file(), 'actual original failed entry retained')
|
||||
u.original_helper.private_dir(STATE)
|
||||
recovery_id = str(uuid.uuid4()); folder = STATE / recovery_id; folder.mkdir(mode=0o700)
|
||||
intent = dict(schema_version=1, type='rmm.windows.passive-joint-recovery', recovery_id=recovery_id, original_id=CASE, original_payload=original['payload'], original_intent_sha256=u.sha(original_folder / 'intent.json'), runner_sha256=u.sha(__file__), script_sha256=u.raw_sha(SCRIPT.encode()))
|
||||
u.save(folder / 'intent.json', intent)
|
||||
source = folder / 'SystemDelegationRecovery.ps1'
|
||||
fd = os.open(source, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600)
|
||||
with os.fdopen(fd, 'wb') as output:
|
||||
output.write(SCRIPT.encode()); output.flush(); os.fsync(output.fileno())
|
||||
u.original_helper.transfer(source, 'SystemDelegationRecovery.ps1', intent['script_sha256'], PREPARE)
|
||||
result = remote(intent, 'prepare'); u.save(folder / 'prepared.json', result)
|
||||
require(result.get('prepared') is True and result.get('both_stopped') is True and result.get('preserved') is True, 'actual preserved recovery admission')
|
||||
print(json.dumps({'original_id': CASE, 'recovery_id': recovery_id, 'prepared': True, 'no_start': True}))
|
||||
|
||||
|
||||
def run(recovery_id, phase):
|
||||
folder, intent = load(recovery_id)
|
||||
if phase == 'enter':
|
||||
require(cb.contract.protected_json(folder / 'prepared.json')['prepared'] is True, 'actual prepared admission')
|
||||
u.save(folder / 'enter-attempt.json', {'once': True, 'lost_reply_readback_only': True})
|
||||
try:
|
||||
result = remote(intent, phase)
|
||||
except Exception as error:
|
||||
u.save(folder / ('reply-incomplete-' + str(uuid.uuid4()) + '.json'), {'error_type': type(error).__name__, 'readback_only': True})
|
||||
raise
|
||||
u.save(folder / ('entered.json' if phase == 'enter' else 'readback-' + str(uuid.uuid4()) + '.json'), result)
|
||||
print(json.dumps({'original_id': CASE, 'recovery_id': recovery_id, 'entered': result.get('entered', False), 'read_only': result.get('read_only', False), 'original_phases': result.get('original_phases'), 'recovery_phases': result.get('recovery_phases')}))
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__); parser.add_argument('phase', choices=['prepare', 'enter', 'readback']); parser.add_argument('--id'); args = parser.parse_args()
|
||||
os.umask(0o077)
|
||||
if args.phase == 'prepare':
|
||||
require(args.id is None, 'create a new recovery admission'); prepare()
|
||||
else:
|
||||
require(args.id is not None, 'exact existing recovery UUID required'); run(args.id, args.phase)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,368 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Source-bound Pipe-v2 pack and create-once native units, never deployment.
|
||||
|
||||
The access root only supplies the existing pinned SSH transport and immutable
|
||||
native Core proofs. No credentials/devstate symlinks, copies, services or jobs.
|
||||
"""
|
||||
import argparse
|
||||
import base64
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import shutil
|
||||
import stat
|
||||
import subprocess
|
||||
import sys
|
||||
import uuid
|
||||
|
||||
CODE = Path(__file__).resolve().parents[2]
|
||||
ACCESS = Path('/home/kevin/Schreibtisch/Coding/rust-discovery')
|
||||
sys.path.insert(0, str(ACCESS / 'deploy/windows'))
|
||||
sys.path.insert(0, str(ACCESS / 'deploy'))
|
||||
import client_bootstrap as cb
|
||||
import auto_transport_acceptance as auto
|
||||
import runtime_upgrade as previous
|
||||
|
||||
require = cb.contract.require
|
||||
BUILD = CODE / 'devstate/windows-pipe-drain-build'
|
||||
NATIVE = CODE / 'devstate/windows-client/native-pipe-v2'
|
||||
# These imported transports read their original protected access configuration.
|
||||
# Their new local upload/error receipts belong to this isolated checkout.
|
||||
cb.EVIDENCE = CODE / 'devstate/windows-client'
|
||||
CORE = ACCESS / 'devstate/core-no-start/build-de37ee99-11bf-465b-9519-45ad8f6e5b87/manifest.json'
|
||||
CORE_SHA = '1bc082031fcad20d5a519b0004f63d499dbba2ea9ce25d56230d48d2556d474b'
|
||||
LOCAL = CODE / 'devstate/windows-pipe-drain/qualification-1e0f2b22-1e74-41af-b8ed-0a356be054ba/qualification.json'
|
||||
LOCAL_SHA = 'a7e3c604d4ad19feed0323ac23aa7a0290b6fb93bc57649cafbadbe5f293b1d4'
|
||||
TARGET = 'x86_64-pc-windows-gnu'
|
||||
NAMES = {'agent': 'rmm-agent-windows.exe', 'helper': 'rmm-helper-windows.exe',
|
||||
'probe': 'RuntimeStateProbe.exe', 'system_probe': 'SystemStateProbe.exe',
|
||||
'lib': 'windows-tests-lib.exe', 'bin': 'windows-tests-bin.exe'}
|
||||
# Expected V2 native lists: unchanged names, two existing codec cases extended.
|
||||
TESTS = {
|
||||
'lib': sorted([
|
||||
'clock::tests::gate_requires_all_status_and_uncertainty_evidence',
|
||||
'clock::tests::production_clock_stays_closed_until_native_adapter_qualification',
|
||||
'clock::tests::suspend_closes_until_actual_post_resume_sync',
|
||||
'clock::tests::timeout_worker_stays_closed_without_a_second_call',
|
||||
'clock::tests::wall_step_and_overflow_fail_closed',
|
||||
'helper_ipc::tests::pipe_client_rights_cannot_create_an_instance',
|
||||
'helper_ipc::tests::protocol_does_not_accept_a_shell_operation',
|
||||
'helper_ipc::tests::reconfigured_service_cannot_adopt_an_old_running_identity',
|
||||
'helper_ipc::tests::serialization_refuses_oversized_frame',
|
||||
'helper_ipc::tests::untrusted_lengths_are_rejected_before_body_allocation',
|
||||
'helper_runtime::intent::tests::cancel_and_dispatch_cas_are_exclusive_and_history_cannot_be_rewritten',
|
||||
'helper_runtime::tests::system_route_binds_original_request_shape_budget_and_reply_scope',
|
||||
'helper_system::tests::completed_scm_state_cannot_override_elapsed_runtime',
|
||||
'helper_system::tests::fixture_recovery_cannot_add_commands_reboots_or_restart_attempts',
|
||||
'helper_system::tests::service_adapter_exposes_only_implemented_states',
|
||||
'helper_system::tests::single_fixture_cannot_start_services_or_groups_as_dependencies',
|
||||
'journal::tests::bounded_existing_journal_preserves_identity_sequence_and_unacked_bytes',
|
||||
'journal::tests::durable_reopen_ack_identity_and_single_process',
|
||||
'journal::tests::migrates_original_passive_schema_without_rewriting_pending_envelopes',
|
||||
'journal::tests::unsupported_page_size_is_refused_without_mutating_existing_data',
|
||||
'native::tests::boot_identity_survives_independent_native_queries',
|
||||
'native::tests::native_inventory_has_real_windows_sources_and_no_fake_inodes',
|
||||
'process::tests::arguments_never_become_shell_code_and_trailing_slashes_are_quoted']),
|
||||
'bin': sorted([
|
||||
'https_channel::endpoint_tests::configured_dns_identity_cannot_inject_a_url_or_disable_name_checks',
|
||||
'runtime::tests::bound_helper_unknown_repairs_generic_crash_gap_without_ack_or_duplicate_result',
|
||||
'runtime::tests::legacy_inventory_keeps_original_bytes_until_concrete_core_ack',
|
||||
'runtime::tests::old_passive_configuration_cannot_enable_jobs_or_read_the_clock',
|
||||
'runtime::tests::worker_fence_requires_same_generation_and_entire_clock_interval',
|
||||
'wire_channel::tests::auto_fallback_classifies_upgrade_refusal_but_never_authentication',
|
||||
'wire_channel::tests::explicit_transport_names_cannot_enable_verification_bypasses'])}
|
||||
COUNTS = {'lib': 23, 'bin': 7}
|
||||
|
||||
|
||||
def sha(path):
|
||||
return hashlib.sha256(Path(path).read_bytes()).hexdigest()
|
||||
|
||||
|
||||
def save(path, value):
|
||||
path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
cb.contract.write_private(path, value)
|
||||
|
||||
|
||||
def private_file(path):
|
||||
path = Path(path)
|
||||
require(not path.is_symlink() and not path.parent.is_symlink(), 'private regular path')
|
||||
info = path.lstat()
|
||||
require(stat.S_ISREG(info.st_mode) and info.st_uid == os.getuid()
|
||||
and stat.S_IMODE(info.st_mode) == 0o600, 'private regular owner/mode')
|
||||
return path
|
||||
|
||||
|
||||
def sources():
|
||||
require(ACCESS.is_dir() and not ACCESS.is_symlink() and cb.ROOT == ACCESS,
|
||||
'original access checkout only; no copied configuration')
|
||||
names = {'Cargo.toml', 'Cargo.lock', 'rust-toolchain.toml', 'proto/agent.proto',
|
||||
'deploy/windows/system_pipe_acceptance.py', 'docs/windows-helper-pipe-drain.md'}
|
||||
names.update(str(p.relative_to(CODE)) for p in (CODE / 'crates').glob('*/Cargo.toml'))
|
||||
for crate in ('agent-windows', 'agent-core', 'domain', 'protocol'):
|
||||
names.update(str(p.relative_to(CODE)) for p in (CODE / 'crates' / crate).rglob('*')
|
||||
if p.is_file() and p.suffix in ('.rs', '.c', '.h', '.idl', '.toml'))
|
||||
names.update('crates/agent/src/' + n + '.rs' for n in ('https_channel', 'transport', 'wire_channel'))
|
||||
require(all((CODE / n).is_file() and not (CODE / n).is_symlink() for n in names), 'complete fixed build sources')
|
||||
transport = {}
|
||||
for module in tuple(sys.modules.values()):
|
||||
raw = getattr(module, '__file__', None)
|
||||
if raw:
|
||||
path = Path(raw).resolve()
|
||||
if path.is_relative_to(ACCESS / 'deploy') and path.suffix == '.py':
|
||||
transport[str(path.relative_to(ACCESS))] = sha(path)
|
||||
require('deploy/windows/client_bootstrap.py' in transport, 'actual transport source binding')
|
||||
return {'code': {n: sha(CODE / n) for n in sorted(names)}, 'access_transport': dict(sorted(transport.items()))}
|
||||
|
||||
|
||||
def core_proof():
|
||||
require(sha(CORE) == CORE_SHA, 'exact original Linux-first Core manifest')
|
||||
manifest = cb.contract.protected_json(CORE)
|
||||
result = {'manifest_sha256': CORE_SHA}
|
||||
for platform, count in (('linux', 80), ('windows', 58)):
|
||||
path = CORE.parent / (platform + '-passed.json')
|
||||
proof = cb.contract.protected_json(path)
|
||||
require(proof['verified'] is True and proof['platform'] == platform
|
||||
and proof['manifest_sha256'] == CORE_SHA, 'actual same-manifest native Core proof')
|
||||
actual = proof['native']['reports']
|
||||
require(set(actual) == set(manifest['test_counts'][platform])
|
||||
and sum(len(v['names']) for v in actual.values()) == count, 'all native Core reports')
|
||||
for kind, item in actual.items():
|
||||
n = manifest['test_counts'][platform][kind]
|
||||
output = base64.b64decode(item['stdout_b64'], validate=True)
|
||||
require(item['exit_code'] == 0 and item['timed_out'] is False
|
||||
and item['names'] == manifest['test_names'][platform][kind]
|
||||
and item['sha256'] == manifest['artifacts'][platform][kind]['sha256']
|
||||
and re.search(rb'test result: ok\. ' + str(n).encode()
|
||||
+ rb' passed; 0 failed; 0 ignored; 0 measured; 0 filtered out;', output),
|
||||
'complete actual native Core result')
|
||||
result[platform] = {'proof_sha256': sha(path), 'case_id': proof['case_id']}
|
||||
for name, digest in manifest['source_files'].items():
|
||||
if name.startswith(('crates/agent-core/', 'crates/domain/', 'crates/protocol/', 'proto/')):
|
||||
require(sha(CODE / name) == digest, 'isolated common source equals actual native Core proof')
|
||||
return result
|
||||
|
||||
|
||||
def reused_qualification():
|
||||
require(sha(LOCAL) == LOCAL_SHA, 'exact retained local qualification')
|
||||
value = cb.contract.protected_json(LOCAL)
|
||||
require(value['type'] == 'rmm.windows.pipe-drain-local-qualification'
|
||||
and value['source_before_after_equal'] is True and value['native_executed'] is False
|
||||
and value['clock_qualified'] is False and value['native_counts_expected'] == COUNTS
|
||||
and len(value['commands']) == 4 and all(c['exit_code'] == 0 for c in value['commands']),
|
||||
'actual previous cross-Clippy/release/unit-link qualification')
|
||||
for name, digest in value['source_files'].items():
|
||||
require(sha(CODE / name) == digest, 'all original qualified inputs remain unchanged')
|
||||
for item in list(value['artifacts'].values()) + list(value['unit_links'].values()):
|
||||
path = Path(item['path'])
|
||||
target = LOCAL.parent / 'target'
|
||||
require(path.is_relative_to(target), 'qualified link under private target')
|
||||
current = target
|
||||
for part in ('',) + path.relative_to(target).parts:
|
||||
if part:
|
||||
current = current / part
|
||||
info = current.lstat()
|
||||
require(not stat.S_ISLNK(info.st_mode) and info.st_uid in (0, os.getuid())
|
||||
and info.st_mode & 0o022 == 0, 'protected original compiler output')
|
||||
require(stat.S_ISREG(path.lstat().st_mode) and sha(path) == item['sha256']
|
||||
and path.stat().st_size == item['bytes'], 'retained exact qualified links')
|
||||
require(re.search(r'^pub const ADAPTER_QUALIFIED: bool = false;$',
|
||||
(CODE / 'crates/agent-windows/src/clock.rs').read_text(), re.M), 'production clock remains closed')
|
||||
return value
|
||||
|
||||
|
||||
def command(args, folder, name):
|
||||
with (folder / (name + '.stdout')).open('xb') as out, (folder / (name + '.stderr')).open('xb') as err:
|
||||
result = subprocess.run(args, stdout=out, stderr=err)
|
||||
save(folder / (name + '.json'), {'exit_code': result.returncode, 'local_only': True, 'arguments': args})
|
||||
require(result.returncode == 0, 'local build failed; original stdout/stderr retained')
|
||||
|
||||
|
||||
def build():
|
||||
before, common, prior = sources(), core_proof(), reused_qualification()
|
||||
folder = BUILD / ('build-' + str(uuid.uuid4()))
|
||||
folder.mkdir(mode=0o700, parents=True)
|
||||
save(folder / 'source-before.json', before)
|
||||
save(folder / 'reused-qualification.json', {'path': str(LOCAL), 'sha256': LOCAL_SHA, 'value': prior})
|
||||
image = prior['build_image']
|
||||
require(re.fullmatch(r'sha256:[a-f0-9]{64}', image), 'immutable compiler image')
|
||||
target = LOCAL.parent / 'target'
|
||||
# Only these two RELEASE examples were missing. Original Clippy, EXEs and
|
||||
# unit links are hash-bound above and are deliberately not rerun/rebuilt.
|
||||
command(['docker', 'run', '--rm', '--network', 'none', '--read-only', '--tmpfs', '/tmp:rw,size=512m',
|
||||
'-v', str(CODE) + ':/src:ro', '-v', str(target) + ':/target', '-e', 'CARGO_TARGET_DIR=/target',
|
||||
'--entrypoint', 'cargo', image, 'build', '--manifest-path', '/src/Cargo.toml', '--locked', '--offline',
|
||||
'--target', TARGET, '-p', 'rmm-agent-windows', '--features', 'system-helper', '--release',
|
||||
'--example', 'runtime_state', '--example', 'system_state'], folder, 'release-examples')
|
||||
selected = {'agent': Path(prior['artifacts']['agent']['path']), 'helper': Path(prior['artifacts']['helper']['path']),
|
||||
'lib': Path(prior['unit_links']['lib']['path']), 'bin': Path(prior['unit_links']['bin']['path']),
|
||||
'probe': target / TARGET / 'release/examples/runtime_state.exe',
|
||||
'system_probe': target / TARGET / 'release/examples/system_state.exe'}
|
||||
artifacts = {}
|
||||
for kind, original in selected.items():
|
||||
output, retained = folder / NAMES[kind], folder / (NAMES[kind] + '.linked')
|
||||
original_sha = sha(original)
|
||||
for destination in (retained, output):
|
||||
shutil.copyfile(original, destination)
|
||||
destination.chmod(0o600)
|
||||
if kind in COUNTS:
|
||||
command(['docker', 'run', '--rm', '--network', 'none', '--read-only', '-v', str(folder) + ':/artifacts',
|
||||
'--entrypoint', 'x86_64-w64-mingw32-strip', image, '--strip-debug', '/artifacts/' + NAMES[kind]],
|
||||
folder, 'strip-' + kind)
|
||||
require(sha(original) == sha(retained) == original_sha, 'original links retained unchanged')
|
||||
data = output.read_bytes()
|
||||
offset = int.from_bytes(data[60:64], 'little')
|
||||
require(data[:2] == b'MZ' and data[offset:offset + 6] == b'PE\0\0\x64\x86', 'Windows AMD64 PE')
|
||||
artifacts[kind] = {'path': str(output), 'name': NAMES[kind], 'sha256': sha(output), 'bytes': len(data),
|
||||
'original_link_path': str(retained), 'original_link_sha256': original_sha,
|
||||
'release_build': kind not in COUNTS, 'debug_stripped': kind in COUNTS}
|
||||
require(sources() == before and core_proof() == common and reused_qualification() == prior,
|
||||
'compiler inputs, original links and native Core proof unchanged before/after')
|
||||
manifest = {'schema_version': 1, 'type': 'rmm.windows.pipe-v2-build', 'source_files': before,
|
||||
'source_before_after_equal': True, 'code_root': str(CODE), 'access_root': str(ACCESS),
|
||||
'artifacts': artifacts, 'test_names_expected': TESTS, 'native_counts_expected': COUNTS,
|
||||
'core_native_proofs': common, 'reused_local_qualification': {'path': str(LOCAL), 'sha256': LOCAL_SHA},
|
||||
'build_image_id': image, 'transport_version': 2, 'raw_v1_controls_qualified': False,
|
||||
'production_clock_qualified': False, 'native_executed': False}
|
||||
save(folder / 'manifest.json', manifest)
|
||||
print(json.dumps({'manifest': str(folder / 'manifest.json'), 'native_executed': False}))
|
||||
|
||||
|
||||
SCRIPT = r'''
|
||||
$ErrorActionPreference='Stop';$p=([Console]::In.ReadLine()|ConvertFrom-Json)
|
||||
if([string]([guid]$p.id)-cne$p.id-or$p.action-notin@('run','read')-or$p.manifest_sha256-notmatch'^[a-f0-9]{64}$'){throw 'Fixed Pipe V2 unit case'}
|
||||
$root='C:\ProgramData\RustDiscoveryBootstrap';$case=Join-Path $root ('native-pipe-v2-'+$p.id)
|
||||
function Safe($path,$dir){$i=Get-Item -LiteralPath $path -Force;if($i.PSIsContainer-ne$dir-or($i.Attributes-band[IO.FileAttributes]::ReparsePoint)){throw 'Private unit type'};$a=Get-Acl -LiteralPath $path;if($a.GetOwner([Security.Principal.SecurityIdentifier]).Value-notin@('S-1-5-18','S-1-5-32-544')){throw 'Unit owner'};$rules=@($a.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier]));if(!$rules.Count){throw 'Empty unit ACL'};foreach($r in $rules){if($r.AccessControlType-ne'Allow'-or$r.IdentityReference.Value-notin@('S-1-5-18','S-1-5-32-544')){throw 'Unit ACL'}}}
|
||||
function WriteNew($path,$value){$b=[Text.Encoding]::UTF8.GetBytes(($value|ConvertTo-Json -Depth 16 -Compress));$f=[IO.File]::Open($path,'CreateNew','Write','Read');try{$f.Write($b,0,$b.Length);$f.Flush($true)}finally{$f.Dispose()}}
|
||||
function ReadPrivate($path){Safe $path $false;if((Get-Item -LiteralPath $path).Length-gt196608){throw 'Unit report bound'};return (Get-Content -LiteralPath $path -Raw|ConvertFrom-Json)}
|
||||
Safe $root $true
|
||||
if($p.action-eq'read'){
|
||||
if(!(Test-Path -LiteralPath $case)){@{case_exists=$false;completed=$false;readback_only=$true}|ConvertTo-Json -Compress;exit 0}
|
||||
Safe $case $true;$i=ReadPrivate (Join-Path $case 'intent.json');if($i.manifest_sha256-cne$p.manifest_sha256){throw 'Original unit intent'}
|
||||
$result=Join-Path $case 'result.json';if(Test-Path -LiteralPath $result){ReadPrivate $result|ConvertTo-Json -Depth 16 -Compress;exit 0}
|
||||
$lists=@{};$reports=@{};foreach($kind in @('lib','bin')){$file=Join-Path $case ('list-'+$kind+'.json');if(Test-Path -LiteralPath $file){$lists[$kind]=ReadPrivate $file};$file=Join-Path $case ('report-'+$kind+'.json');if(Test-Path -LiteralPath $file){$reports[$kind]=ReadPrivate $file}}
|
||||
@{case_exists=$true;completed=$false;readback_only=$true;started=(Test-Path -LiteralPath (Join-Path $case 'started.json'));lists=$lists;reports=$reports}|ConvertTo-Json -Depth 16 -Compress;exit 0
|
||||
}
|
||||
if(Test-Path -LiteralPath $case){throw 'Existing unit case: readback only'};New-Item -ItemType Directory -Path $case|Out-Null;Safe $case $true;WriteNew (Join-Path $case 'intent.json') $p
|
||||
function Run($exe,$arguments){$s=New-Object Diagnostics.ProcessStartInfo;$s.FileName=$exe;$s.Arguments=$arguments;$s.UseShellExecute=$false;$s.CreateNoWindow=$true;$s.RedirectStandardOutput=$true;$s.RedirectStandardError=$true;$c=New-Object Diagnostics.Process;$c.StartInfo=$s;if(!$c.Start()){throw 'Unit process start'};try{$o=$c.StandardOutput.ReadToEndAsync();$e=$c.StandardError.ReadToEndAsync();$timed=$false;if(!$c.WaitForExit(30000)){$timed=$true;$c.Kill();if(!$c.WaitForExit(2000)){throw 'Own unit process did not exit'}};if(!$o.Wait(2000)-or!$e.Wait(2000)-or$o.Result.Length-gt65536-or$e.Result.Length-gt65536){throw 'Bounded unit output collection'};return @{exit_code=$c.ExitCode;timed_out=$timed;stdout=$o.Result;stderr=$e.Result}}finally{$c.Dispose()}}
|
||||
$lists=@{};$paths=@{}
|
||||
foreach($kind in @('lib','bin')){
|
||||
$a=$p.artifacts.$kind;if($a.sha256-notmatch'^[a-f0-9]{64}$'-or$a.name-cne('windows-tests-'+$kind+'.exe')){throw 'Fixed test artifact'};$folder=Join-Path $root $a.sha256;Safe $folder $true;$exe=Join-Path $folder $a.name;Safe $exe $false;if((Get-FileHash -LiteralPath $exe -Algorithm SHA256).Hash.ToLowerInvariant()-cne$a.sha256-or(Get-Item -LiteralPath $exe).Length-ne$a.bytes){throw 'Exact unit artifact'}
|
||||
$listed=Run $exe '--list --format terse';[string[]]$names=@($listed.stdout-split'\r?\n'|Where-Object{$_-match': test$'}|ForEach-Object{$_-replace': test$',''});[Array]::Sort($names,[StringComparer]::Ordinal)
|
||||
$value=@{sha256=$a.sha256;names=$names;listed=$listed};WriteNew (Join-Path $case ('list-'+$kind+'.json')) $value
|
||||
if($listed.exit_code-ne0-or$listed.timed_out-or$names.Count-ne$p.counts.$kind-or(($names-join"`n")-cne(@($p.test_names.$kind)-join"`n"))){throw 'Exact complete native list before ANY tests'};$lists[$kind]=$value;$paths[$kind]=$exe
|
||||
}
|
||||
WriteNew (Join-Path $case 'both-lists-verified.json') @{manifest_sha256=$p.manifest_sha256;both_lists_verified_before_any_test=$true}
|
||||
WriteNew (Join-Path $case 'started.json') @{start_once=$true};$reports=@{}
|
||||
foreach($kind in @('lib','bin')){$run=Run $paths[$kind] '--test-threads=1';$value=@{sha256=$lists[$kind].sha256;names=$lists[$kind].names;listed=$lists[$kind].listed;result=$run};WriteNew (Join-Path $case ('report-'+$kind+'.json')) $value;$reports[$kind]=$value;if($run.exit_code-ne0-or$run.timed_out){throw 'Native unit execution failed; readback only'}}
|
||||
$value=@{completed=$true;manifest_sha256=$p.manifest_sha256;reports=$reports;both_lists_verified_before_any_test=$true;bootstrap_administrator_units=$true;local_service_proof=$false;native_pipe_proof=$false;rmm_jobs=$false;product_state_writes=$false};WriteNew (Join-Path $case 'result.json') $value;$value|ConvertTo-Json -Depth 16 -Compress
|
||||
'''
|
||||
|
||||
|
||||
def verified(path, current=True):
|
||||
path = private_file(path)
|
||||
require(path.parent.parent == BUILD and path.parent.name.startswith('build-')
|
||||
and str(uuid.UUID(path.parent.name[6:])) == path.parent.name[6:], 'fixed private build namespace')
|
||||
value = cb.contract.protected_json(path)
|
||||
require(value['type'] == 'rmm.windows.pipe-v2-build' and value['schema_version'] == 1
|
||||
and value['source_before_after_equal'] is True and value['production_clock_qualified'] is False
|
||||
and value['transport_version'] == 2 and value['raw_v1_controls_qualified'] is False
|
||||
and value['native_executed'] is False
|
||||
and value['reused_local_qualification'] == {'path': str(LOCAL), 'sha256': LOCAL_SHA}
|
||||
and value['native_counts_expected'] == COUNTS and value['test_names_expected'] == TESTS
|
||||
and value['code_root'] == str(CODE) and value['access_root'] == str(ACCESS), 'exact V2 build profile')
|
||||
if current:
|
||||
require(value['source_files'] == sources() and value['core_native_proofs'] == core_proof(), 'current source/Core proof binding')
|
||||
require(set(value['artifacts']) == set(NAMES), 'six exact artifacts')
|
||||
for kind, item in value['artifacts'].items():
|
||||
output, original = private_file(item['path']), private_file(item['original_link_path'])
|
||||
require(output == path.parent / NAMES[kind] and original == path.parent / (NAMES[kind] + '.linked')
|
||||
and sha(output) == item['sha256'] and output.stat().st_size == item['bytes']
|
||||
and sha(original) == item['original_link_sha256']
|
||||
and item['release_build'] is (kind not in COUNTS)
|
||||
and item['debug_stripped'] is (kind in COUNTS), 'exact retained delivery and original link')
|
||||
return value
|
||||
|
||||
|
||||
def native(path, ident=None):
|
||||
path = path.resolve()
|
||||
manifest = verified(path, current=ident is None)
|
||||
if ident is None:
|
||||
ident = str(uuid.uuid4());folder = NATIVE / ident;folder.mkdir(mode=0o700, parents=True)
|
||||
save(folder / 'intent.json', {'id': ident, 'manifest_path': str(path), 'manifest_sha256': sha(path),
|
||||
'runner_sha256': sha(__file__), 'script_sha256': hashlib.sha256(SCRIPT.encode()).hexdigest()})
|
||||
before = {'counts': auto.scopes(), 'flags': auto.status()}
|
||||
require(auto.flags_disabled(before['flags']), 'closed fault flags before native units')
|
||||
save(folder / 'server-before.json', before)
|
||||
for kind in COUNTS:
|
||||
previous.upload(manifest['artifacts'][kind])
|
||||
save(folder / 'started-local.json', {'start_once': True})
|
||||
action = 'run'
|
||||
else:
|
||||
require(str(uuid.UUID(ident)) == ident, 'canonical original native case')
|
||||
folder = NATIVE / ident;intent = cb.contract.protected_json(folder / 'intent.json')
|
||||
require(intent['manifest_sha256'] == sha(path) and intent['manifest_path'] == str(path)
|
||||
and intent['runner_sha256'] == sha(__file__)
|
||||
and intent['script_sha256'] == hashlib.sha256(SCRIPT.encode()).hexdigest(), 'same original case; readback only')
|
||||
action = 'read'
|
||||
result = cb.powershell(SCRIPT, {'id': ident, 'action': action, 'manifest_sha256': sha(path),
|
||||
'artifacts': {k: manifest['artifacts'][k] for k in COUNTS},
|
||||
'counts': COUNTS, 'test_names': TESTS}, timeout=150)
|
||||
save(folder / ('readback-' + str(uuid.uuid4()) + '.json'), result)
|
||||
if result.get('completed') is not True:
|
||||
print(json.dumps({'verified': False, 'case_id': ident, 'readback_only': True, 'completed': False,
|
||||
'case_exists': result.get('case_exists'), 'tests_repeated': False}))
|
||||
return
|
||||
require(result['manifest_sha256'] == sha(path) and set(result['reports']) == set(COUNTS)
|
||||
and result['both_lists_verified_before_any_test'] is True
|
||||
and result['rmm_jobs'] is False and result['product_state_writes'] is False
|
||||
and result['local_service_proof'] is False and result['native_pipe_proof'] is False,
|
||||
'actual narrow unit result, no runtime proof')
|
||||
for kind, actual in result['reports'].items():
|
||||
run, listed = actual['result'], actual['listed']
|
||||
names = re.findall(r'^(.+): test\r?$', listed['stdout'], re.M)
|
||||
require(actual['sha256'] == manifest['artifacts'][kind]['sha256']
|
||||
and names == actual['names'] == TESTS[kind] and len(set(names)) == COUNTS[kind]
|
||||
and listed['exit_code'] == run['exit_code'] == 0 and not listed['timed_out'] and not run['timed_out']
|
||||
and re.search(r'test result: ok\. ' + str(COUNTS[kind])
|
||||
+ r' passed; 0 failed; 0 ignored; 0 measured; 0 filtered out;', run['stdout']),
|
||||
'every exact named native unit passed, none skipped/filtered')
|
||||
before = cb.contract.protected_json(folder / 'server-before.json')
|
||||
require(auto.scopes() == before['counts'] and auto.status() == before['flags'], 'both central counts and closed flags unchanged')
|
||||
if action == 'run':
|
||||
verified(path) # Full before/after source and retained-artifact check.
|
||||
proof = {'verified': True, 'case_id': ident, 'manifest_path': str(path), 'manifest_sha256': sha(path),
|
||||
'native': result, 'no_jobs': True, 'clock_adapter_qualified': False,
|
||||
'local_service_proof': False, 'native_pipe_proof': False}
|
||||
destination = folder / 'passed.json'
|
||||
if destination.exists():
|
||||
require(cb.contract.protected_json(destination) == proof, 'retain exact original proof')
|
||||
else:
|
||||
save(destination, proof)
|
||||
print(json.dumps({'verified': True, 'case_id': ident, 'tests': COUNTS, 'proof': str(destination)}))
|
||||
|
||||
|
||||
def main():
|
||||
os.umask(0o077)
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('phase', choices=('build-local', 'native-units', 'readback'))
|
||||
parser.add_argument('--access-root', required=True, type=Path)
|
||||
parser.add_argument('--manifest', type=Path)
|
||||
parser.add_argument('--case')
|
||||
args = parser.parse_args()
|
||||
require(args.access_root == ACCESS and not args.access_root.is_symlink(), 'exact existing access root')
|
||||
if args.phase == 'build-local':
|
||||
require(args.manifest is None and args.case is None, 'build only')
|
||||
build()
|
||||
else:
|
||||
require(args.manifest is not None and ((args.phase == 'readback') == bool(args.case)), 'explicit manifest and original readback case')
|
||||
native(args.manifest, args.case)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
main()
|
||||
except Exception as error:
|
||||
print('WINDOWS_PIPE_V2_QUALIFICATION_INCOMPLETE:' + type(error).__name__)
|
||||
raise SystemExit(2) from None
|
||||
@@ -0,0 +1,564 @@
|
||||
#!/usr/bin/env python3
|
||||
"""One preserving passive pipe-v2 pair upgrade; no target actions by default.
|
||||
|
||||
prepare stages immutable bootstrap artifacts and captures a read-only baseline.
|
||||
enter needs that exact separately reviewed baseline hash and runs once. A lost
|
||||
reply permits readback/finish only. Main access-root is read-only, including the
|
||||
current indices: Root publishes those separately after reviewing this result.
|
||||
"""
|
||||
import argparse
|
||||
import base64
|
||||
import hashlib
|
||||
import inspect
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
|
||||
import client_bootstrap as cb
|
||||
import system_delegation_upgrade as u
|
||||
|
||||
require = cb.contract.require
|
||||
ROOT = cb.ROOT
|
||||
STATE = cb.EVIDENCE / 'system-pipe-upgrade'
|
||||
ORIGINAL_RUNNER = 'f8dc1c8fbc064e253b1fbe130fb628afef58cf45c2bafb6837d6716125b42d38'
|
||||
OLD_AGENT = '89004ad3475af3fb8a03bdb1e63c3ef1f2a08d31d0d97193e02fe770a1d7f676'
|
||||
OLD_HELPER = 'e6aacbdd691c8c56612a2ba205c48396defe70e7d527e031aa3a76a8ae5a3662'
|
||||
OLD_POLICY = '007adf5f4932dcf68fa4c0c3ba601ec1996b350e7e3e1d14e89a31dd712e5703'
|
||||
OLD_PIN = '126670bc6ed71aad76438ec588b739d3bc02d36ae305ce8f8b5613e4a9e11a15'
|
||||
OLD_CASE = '6d2df065-0877-41c4-983c-2c9fdb6e5437'
|
||||
OLD_RESULT_SHA = 'ac00411fe1e109b18b28fd9c020245f462c179bb3ac99a37b69c7cff39c38460'
|
||||
PIPE_VERIFIER_SHA = '2ac6bd55e608e7dbb0f0cf65cf37e7bbccc42b862d09c50b37e9162f29f4bbdf'
|
||||
sha, raw_sha, canonical, save = u.sha, u.raw_sha, u.canonical, u.save
|
||||
|
||||
|
||||
def replace_once(text, old, new):
|
||||
require(text.count(old) == 1, 'exact reviewed bootstrap splice')
|
||||
return text.replace(old, new, 1)
|
||||
|
||||
|
||||
def write_bytes(path, data):
|
||||
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600)
|
||||
with os.fdopen(fd, 'wb') as output:
|
||||
output.write(data); output.flush(); os.fsync(output.fileno())
|
||||
|
||||
|
||||
# Reuse read-only witnesses only, bound to the historical runner hash below.
|
||||
# None of its original hard-PID stop, File.Replace(NULL), start, or case logic
|
||||
# is included. Every new mutation is visible in this file.
|
||||
PREFIX = u.SCRIPT.split('\nfunction ReadIntent', 1)[0]
|
||||
PREFIX = replace_once(PREFIX, 'RmmDelegationUpgradePayload', 'RmmPipeUpgradePayload')
|
||||
PREFIX = replace_once(PREFIX, "@('state','enter','finish','readback')", "@('baseline','enter','finish','readback')")
|
||||
PREFIX = replace_once(PREFIX, "('system-delegation-'+$p.id)", "('system-pipe-'+$p.id)")
|
||||
PREFIX = replace_once(PREFIX, "'system-delegation-active-intent.json'", "'system-pipe-active-intent.json'")
|
||||
for old, new in ((u.OLD_AGENT, OLD_AGENT), (u.OLD_HELPER, OLD_HELPER), (u.OLD_POLICY, OLD_POLICY), (u.OLD_PIN, OLD_PIN)):
|
||||
PREFIX = replace_once(PREFIX, old, new)
|
||||
|
||||
NATIVE = r'''
|
||||
Add-Type -TypeDefinition @'
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Security.Principal;
|
||||
using System.Text;
|
||||
using Microsoft.Win32.SafeHandles;
|
||||
public static class RmmPipeNative {
|
||||
public sealed class Held : SafeHandleZeroOrMinusOneIsInvalid {
|
||||
public Held(IntPtr h):base(true){SetHandle(h);}
|
||||
protected override bool ReleaseHandle(){return CloseHandle(handle);}
|
||||
}
|
||||
[StructLayout(LayoutKind.Sequential)] public struct FileId {
|
||||
public ulong Volume;
|
||||
[MarshalAs(UnmanagedType.ByValArray,SizeConst=16)] public byte[] Id;
|
||||
}
|
||||
[StructLayout(LayoutKind.Sequential)] struct SidAndAttributes {public IntPtr Sid;public uint Attributes;}
|
||||
[StructLayout(LayoutKind.Sequential)] struct Groups {public uint Count;public SidAndAttributes First;}
|
||||
[DllImport("kernel32.dll",SetLastError=true)] static extern IntPtr OpenProcess(uint access,bool inherit,int pid);
|
||||
[DllImport("kernel32.dll",SetLastError=true)] static extern bool CloseHandle(IntPtr h);
|
||||
[DllImport("kernel32.dll",SetLastError=true)] static extern bool GetProcessTimes(Held h,out long creation,out long exit,out long kernel,out long user);
|
||||
[DllImport("kernel32.dll",SetLastError=true,CharSet=CharSet.Unicode)] static extern bool QueryFullProcessImageName(Held h,uint flags,StringBuilder image,ref uint size);
|
||||
[DllImport("kernel32.dll",SetLastError=true)] static extern uint WaitForSingleObject(Held h,uint millis);
|
||||
[DllImport("advapi32.dll",SetLastError=true)] static extern bool OpenProcessToken(Held process,uint access,out IntPtr token);
|
||||
[DllImport("advapi32.dll",SetLastError=true)] static extern bool GetTokenInformation(IntPtr token,int kind,IntPtr data,int bytes,out int needed);
|
||||
[DllImport("kernel32.dll",SetLastError=true)] public static extern bool GetFileInformationByHandleEx(SafeFileHandle h,int kind,out FileId id,uint size);
|
||||
[DllImport("kernel32.dll",SetLastError=true,CharSet=CharSet.Unicode)] public static extern SafeFileHandle CreateFile(string path,uint access,uint share,IntPtr security,uint creation,uint flags,IntPtr template);
|
||||
public static Held Open(int pid){IntPtr h=OpenProcess(0x101000,false,pid);if(h==IntPtr.Zero)throw new Win32Exception();return new Held(h);}
|
||||
public static bool Alive(Held h){return WaitForSingleObject(h,0)==258;}
|
||||
public static bool Exited(Held h,uint timeout){return WaitForSingleObject(h,timeout)==0;}
|
||||
static IntPtr Info(IntPtr token,int kind,out int bytes){
|
||||
int needed;GetTokenInformation(token,kind,IntPtr.Zero,0,out needed);
|
||||
if(needed<=0||needed>65536)throw new InvalidOperationException("Token size");
|
||||
IntPtr p=Marshal.AllocHGlobal(needed);if(!GetTokenInformation(token,kind,p,needed,out bytes)){Marshal.FreeHGlobal(p);throw new Win32Exception();}return p;
|
||||
}
|
||||
public static Dictionary<string,object> Proof(Held h,int pid,string owner,string serviceSid,string image){
|
||||
if(!Alive(h))throw new InvalidOperationException("Process not alive");
|
||||
long creation,exit,kernel,user;if(!GetProcessTimes(h,out creation,out exit,out kernel,out user))throw new Win32Exception();
|
||||
StringBuilder path=new StringBuilder(32768);uint length=32768;if(!QueryFullProcessImageName(h,0,path,ref length)||!String.Equals(path.ToString(),image,StringComparison.OrdinalIgnoreCase))throw new InvalidOperationException("Process image");
|
||||
IntPtr token;if(!OpenProcessToken(h,8,out token))throw new Win32Exception();
|
||||
try {
|
||||
int bytes;IntPtr info=Info(token,1,out bytes);string actual;
|
||||
try {actual=new SecurityIdentifier(Marshal.ReadIntPtr(info)).Value;}finally{Marshal.FreeHGlobal(info);}
|
||||
if(actual!=owner)throw new InvalidOperationException("Process owner");
|
||||
info=Info(token,2,out bytes);bool found=false;
|
||||
try {int count=Marshal.ReadInt32(info);int offset=(int)Marshal.OffsetOf(typeof(Groups),"First");int stride=Marshal.SizeOf(typeof(SidAndAttributes));
|
||||
if(count<0||count>1024||offset+(long)count*stride>bytes)throw new InvalidOperationException("Groups size");
|
||||
for(int n=0;n<count;n++){SidAndAttributes g=(SidAndAttributes)Marshal.PtrToStructure(IntPtr.Add(info,offset+n*stride),typeof(SidAndAttributes));if(new SecurityIdentifier(g.Sid).Value==serviceSid&&(g.Attributes&4)!=0&&(g.Attributes&16)==0)found=true;}
|
||||
}finally{Marshal.FreeHGlobal(info);}
|
||||
if(!found||!Alive(h))throw new InvalidOperationException("Enabled service SID/process liveness");
|
||||
return new Dictionary<string,object>{{"pid",pid},{"creation_filetime",creation.ToString(System.Globalization.CultureInfo.InvariantCulture)},{"owner_sid",actual},{"service_sid",serviceSid},{"service_sid_enabled",true},{"image",path.ToString()},{"kernel_handle_bound",true}};
|
||||
}finally{CloseHandle(token);}
|
||||
}
|
||||
}
|
||||
'@
|
||||
function FileIdentity($path,[bool]$actor=$false){
|
||||
Check $path $false $actor;$file=[IO.File]::Open($path,[IO.FileMode]::Open,[IO.FileAccess]::Read,[IO.FileShare]::Read)
|
||||
try{$id=New-Object RmmPipeNative+FileId;$size=[Runtime.InteropServices.Marshal]::SizeOf([type][RmmPipeNative+FileId]);if($size-ne24-or![RmmPipeNative]::GetFileInformationByHandleEx($file.SafeFileHandle,18,[ref]$id,[uint32]$size)){throw 'Native file identity'}
|
||||
return [ordered]@{volume_serial=$id.Volume.ToString([Globalization.CultureInfo]::InvariantCulture);file_id=([BitConverter]::ToString($id.Id)).Replace('-','').ToLowerInvariant();bytes=$file.Length;acl_sha256=(AclHash $path);sha256=(Hash $path $actor)}
|
||||
}finally{$file.Dispose()}
|
||||
}
|
||||
function Kernel($role,$record,$held){
|
||||
$owner='S-1-5-19';$sid=$agentSid;$image=$agentBinary;if($role-ceq'helper'){$owner=$sys;$sid=$helperSid;$image=$helperBinary}
|
||||
$proof=[RmmPipeNative]::Proof($held,[int]$record.pid,$owner,$sid,$image)
|
||||
if($proof.creation_filetime-cne$record.creation_filetime-or$proof.owner_sid-cne$record.owner_sid){throw 'SCM/kernel process identity mismatch'};return $proof
|
||||
}
|
||||
function ActualState([bool]$new){
|
||||
$value=State $new
|
||||
$value['files']=[ordered]@{agent=(FileIdentity $agentBinary);helper=(FileIdentity $helperBinary);settings=(FileIdentity $settings);pin=(FileIdentity $pin);config=(FileIdentity $config);ca=(FileIdentity (Join-Path $agentRoot 'server-ca.pem') $true);identity=(FileIdentity (Join-Path $agentState 'identity.json') $true);certificate=(FileIdentity (Join-Path $agentState 'device.pem') $true);private_key=(FileIdentityMetadata (Join-Path $agentState 'device.key'))}
|
||||
foreach($role in @('agent','helper')){$record=$value.service;if($role-ceq'helper'){$record=$value.helper_service}
|
||||
$proof=$null;if($record.state-ceq'Running'){$held=[RmmPipeNative]::Open([int]$record.pid);try{$proof=Kernel $role $record $held;if(!(JsonEqual $record (Service $role))-or![RmmPipeNative]::Alive($held)){throw 'SCM/kernel generation changed during proof'}}finally{$held.Dispose()}}
|
||||
$value[$role+'_kernel']=$proof
|
||||
};return $value
|
||||
}
|
||||
# FILE_READ_ATTRIBUTES only: no key content read/hash/export. This also binds
|
||||
# the private key's actual native FileID, not merely a timestamp/name.
|
||||
function FileIdentityMetadata($path){
|
||||
Check $path $false $true;$i=Get-Item -LiteralPath $path -Force;$h=[RmmPipeNative]::CreateFile($path,0x80,7,[IntPtr]::Zero,3,0,[IntPtr]::Zero)
|
||||
try{if($h.IsInvalid){throw 'Private metadata-only handle'};$id=New-Object RmmPipeNative+FileId;if(![RmmPipeNative]::GetFileInformationByHandleEx($h,18,[ref]$id,24)){throw 'Private metadata-only native FileID'};return @{volume_serial=$id.Volume.ToString([Globalization.CultureInfo]::InvariantCulture);file_id=([BitConverter]::ToString($id.Id)).Replace('-','').ToLowerInvariant();bytes=$i.Length;creation_ticks=$i.CreationTimeUtc.Ticks.ToString();last_write_ticks=$i.LastWriteTimeUtc.Ticks.ToString();acl_sha256=(AclHash $path);private_key_read=$false}}finally{$h.Dispose()}
|
||||
}
|
||||
function SameOriginal($before,$after){
|
||||
Preserved $before $after $false
|
||||
if(!(JsonEqual $before.files $after.files)){throw 'Original four files/config/private metadata CAS'}
|
||||
foreach($role in @('service','helper_service','agent_kernel','helper_kernel')){if(!(JsonEqual $before.$role $after.$role)){throw 'Fresh original kernel/SCM generation changed; new reviewed baseline required'}}
|
||||
}
|
||||
function PreserveImmutableFiles($before,$after,[bool]$frozen){
|
||||
Preserved $before $after $frozen
|
||||
foreach($label in @('config','ca','identity','certificate','private_key')){if(!(JsonEqual $before.files.$label $after.files.$label)){throw 'Original immutable PKI/config native FileID/metadata changed'}}
|
||||
}
|
||||
'''
|
||||
|
||||
# The original fixed-role SCM configuration checks are reused exactly. Unlike
|
||||
# Service(), this readback projection makes no running-process proof claim and
|
||||
# honestly exposes pending/raw State/PID without changing a service.
|
||||
READBACK_SERVICE = "\nfunction ReadbackService($role){" + u.SCRIPT.split('function Service($role){', 1)[1].split(' $processId=', 1)[0] + r'''
|
||||
$state=[string]$service.State;if(!$state-or$state.Length-gt64){throw 'Bounded raw SCM state'}
|
||||
return [ordered]@{state=$state;pid=[uint32]$service.ProcessId;start_name=$service.StartName;start_mode=$service.StartMode;path=$service.PathName;service_type=$service.ServiceType;sid_type=$sidType;service_acl_sha256=(BytesHash ([Text.Encoding]::UTF8.GetBytes($text)));process_identity_verified=$false;read_only=$true}
|
||||
}
|
||||
'''
|
||||
|
||||
PHASES = r'''
|
||||
CheckControl $boot $true
|
||||
if($p.script_sha256-notmatch'^[a-f0-9]{64}$'-or$PSCommandPath-cne(Join-Path (Join-Path $boot $p.script_sha256) 'SystemPipeUpgrade.ps1')-or(Hash $PSCommandPath)-cne$p.script_sha256){throw 'Actual executing pipe-upgrade source'}
|
||||
if($p.action-ceq'baseline'){$before=ActualState $false;if($before.service.state-cne'Running'-or$before.helper_service.state-notin@('Running','Stopped')-or$before.journal.pending_inventory_events-ne0){throw 'Settled original passive baseline'};$before|ConvertTo-Json -Depth 40 -Compress;exit 0}
|
||||
function ReadCase{
|
||||
CheckControl $folder $true;CheckControl (Join-Path $folder 'intent.json') $false;CheckControl $active $false
|
||||
$i=Get-Content -LiteralPath (Join-Path $folder 'intent.json') -Raw|ConvertFrom-Json;$a=Get-Content -LiteralPath $active -Raw|ConvertFrom-Json
|
||||
if((($i.payload.PSObject.Properties.Name|Sort-Object)-join',')-cne(($p.PSObject.Properties.Name|Sort-Object)-join',')){throw 'Original exact pipe payload shape'}
|
||||
foreach($field in $p.PSObject.Properties.Name){if($field-cne'action'-and!(JsonEqual $i.payload.$field $p.$field)){throw 'Original exact pipe intent'}}
|
||||
if($a.id-cne$p.id-or$a.script_sha256-cne$p.script_sha256-or$a.baseline_sha256-cne$p.baseline_sha256){throw 'Original active pipe intent'};return $i
|
||||
}
|
||||
if($p.action-ceq'readback'){
|
||||
function MaybeHash($path){if(!(Test-Path -LiteralPath $path)){return $null};return Hash $path}
|
||||
$i=ReadCase;$phases=[ordered]@{};foreach($label in @('agent-stop-attempt','agent-stopped','helper-stop-attempt','helper-stopped','helper-already-stopped','frozen','agent-backup','helper-backup','settings-backup','pin-backup','agent-replace-attempt','agent-replaced','helper-replace-attempt','helper-replaced','settings-replace-attempt','settings-replaced','pin-replace-attempt','pin-replaced','swapped','helper-start-attempt','helper-started','agent-start-attempt','agent-started','entered')){$phases[$label]=Test-Path -LiteralPath (Join-Path $folder ($label+'.json'))}
|
||||
@{read_only=$true;id=$p.id;phase_receipts=$phases;service=(ReadbackService 'agent');helper_service=(ReadbackService 'helper');hashes=@{agent=(MaybeHash $agentBinary);helper=(MaybeHash $helperBinary);settings=(MaybeHash $settings);pin=(MaybeHash $pin)}}|ConvertTo-Json -Depth 40 -Compress;exit 0
|
||||
}
|
||||
if($p.action-ceq'finish'){
|
||||
$i=ReadCase;$after=ActualState $true;PreserveImmutableFiles $i.before $after $false
|
||||
CheckControl (Join-Path $folder 'frozen.json') $false;$frozen=Get-Content -LiteralPath (Join-Path $folder 'frozen.json') -Raw|ConvertFrom-Json;PreserveImmutableFiles $frozen $after $false
|
||||
foreach($role in @('agent','helper')){CheckControl (Join-Path $folder ($role+'-started.json')) $false;$started=Get-Content -LiteralPath (Join-Path $folder ($role+'-started.json')) -Raw|ConvertFrom-Json;$live=$after.service;if($role-ceq'helper'){$live=$after.helper_service};if($live.state-cne'Running'-or!(JsonEqual $started.service $live)-or!(JsonEqual $started.kernel $after.($role+'_kernel'))){throw 'Same single-start actual component instance required'}}
|
||||
@{read_only=$true;completed=$true;id=$p.id;native=$after;original=$i.before;frozen=$frozen}|ConvertTo-Json -Depth 40 -Compress;exit 0
|
||||
}
|
||||
if((Test-Path -LiteralPath $folder)-or(Test-Path -LiteralPath $active)){throw 'Existing pipe intent: readback only'}
|
||||
$baselineBytes=[Convert]::FromBase64String($p.baseline_base64);if((BytesHash $baselineBytes)-cne$p.baseline_sha256){throw 'Exact separately reviewed baseline bytes'};$baseline=[Text.Encoding]::UTF8.GetString($baselineBytes)|ConvertFrom-Json
|
||||
$before=ActualState $false;SameOriginal $baseline $before
|
||||
if($before.journal.pending_inventory_events-ne0-or$before.service.state-cne'Running'){throw 'Original ACK and running agent required'}
|
||||
$heldAgent=[RmmPipeNative]::Open([int]$before.service.pid);$heldHelper=$null
|
||||
try{
|
||||
$null=Kernel 'agent' $before.service $heldAgent
|
||||
if($before.helper_service.state-ceq'Running'){$heldHelper=[RmmPipeNative]::Open([int]$before.helper_service.pid);$null=Kernel 'helper' $before.helper_service $heldHelper}
|
||||
New-Item -ItemType Directory -Path $folder|Out-Null;CheckControl $folder $true
|
||||
WriteNew (Join-Path $folder 'intent.json') @{payload=$p;before=$before};WriteNew $active @{id=$p.id;script_sha256=$p.script_sha256;baseline_sha256=$p.baseline_sha256;no_jobs=$true}
|
||||
function StopHeld($role,$record,$held){
|
||||
$live=Service $role;if(!(JsonEqual $record $live)){throw 'SCM identity changed before own stop'};$null=Kernel $role $record $held
|
||||
$name=$agentName;if($role-ceq'helper'){$name=$helperName};WriteNew (Join-Path $folder ($role+'-stop-attempt.json')) @{stop_once=$true;service=$record}
|
||||
Stop-Service -Name $name;(Get-Service -Name $name).WaitForStatus([ServiceProcess.ServiceControllerStatus]::Stopped,[TimeSpan]::FromSeconds(20));if(![RmmPipeNative]::Exited($held,20000)){throw 'Pinned original process not exited'}
|
||||
WriteNew (Join-Path $folder ($role+'-stopped.json')) @{original=$record;kernel_process_exited=$true}
|
||||
}
|
||||
StopHeld 'agent' $before.service $heldAgent
|
||||
if($null-ne$heldHelper){StopHeld 'helper' $before.helper_service $heldHelper}else{if((Service 'helper').state-cne'Stopped'){throw 'Manual helper changed since reviewed stopped baseline'};WriteNew (Join-Path $folder 'helper-already-stopped.json') @{observed_stopped=$true;stop_called=$false;start_called=$false}}
|
||||
$frozen=ActualState $false;Preserved $before $frozen $false;if($frozen.service.state-cne'Stopped'-or$frozen.helper_service.state-cne'Stopped'-or$frozen.journal.pending_inventory_events-ne0-or!(JsonEqual $before.files $frozen.files)){throw 'Stopped original complete pair/file identities'};WriteNew (Join-Path $folder 'frozen.json') $frozen
|
||||
function Backup($label,$path,$expected){
|
||||
$identity=FileIdentity $path;if(!(JsonEqual $identity $before.files.$label)-or$identity.sha256-cne$expected){throw 'Original backup file identity/hash/ACL'}
|
||||
$backup=Join-Path $folder ($label+'-original');[IO.File]::Copy($path,$backup,$false);PrivateBackupAcl $backup;FlushCopy $backup
|
||||
if((Hash $backup)-cne$expected){throw 'Exact private backup bytes'};WriteNew (Join-Path $folder ($label+'-backup.json')) @{original=$identity;backup=(FileIdentity $backup);original_sddl=(Get-Acl -LiteralPath $path).Sddl}
|
||||
}
|
||||
Backup 'agent' $agentBinary $p.old_agent;Backup 'helper' $helperBinary $p.old_helper;Backup 'settings' $settings $p.old_policy;Backup 'pin' $pin $p.old_pin
|
||||
$settingBytes=[Convert]::FromBase64String($p.settings_base64);$pinBytes=[Convert]::FromBase64String($p.pin_base64);if((BytesHash $settingBytes)-cne$p.new_policy-or(BytesHash $pinBytes)-cne$p.new_pin){throw 'Deterministic closed reciprocal settings'}
|
||||
WriteBytes (Join-Path $folder 'new-helper.json') $settingBytes;WriteBytes (Join-Path $folder 'new-agent-pin.json') $pinBytes
|
||||
function Swap($label,$destination,$source,$oldHash,$newHash){
|
||||
if((Service 'agent').state-cne'Stopped'-or(Service 'helper').state-cne'Stopped'){throw 'Both stopped for all four file replacements'}
|
||||
foreach($other in @('agent','helper','settings','pin')){CheckControl (Join-Path $folder ($other+'-backup.json')) $false;if(!(Test-Path -LiteralPath (Join-Path $folder ($other+'-original')))){throw 'All four private backups precede first replacement'}}
|
||||
$old=FileIdentity $destination;$sddl=(Get-Acl -LiteralPath $destination).Sddl;$nativeBackup=Join-Path $folder ($label+'-native-original');$candidate=Join-Path $folder ($label+'-candidate')
|
||||
if(!(JsonEqual $old $before.files.$label)-or$old.sha256-cne$oldHash-or(Hash $source)-cne$newHash-or(Hash (Join-Path $folder ($label+'-original')))-cne$oldHash-or(Test-Path -LiteralPath $nativeBackup)){throw 'Fresh destination/source/backup CAS'}
|
||||
[IO.File]::Copy($source,$candidate,$false);FlushCopy $candidate;$candidateId=FileIdentity $candidate;if($candidateId.sha256-cne$newHash){throw 'Complete staged replacement'}
|
||||
WriteNew (Join-Path $folder ($label+'-replace-attempt.json')) @{old=$old;candidate=$candidateId;native_backup=$nativeBackup;source_sha256=$p.script_sha256}
|
||||
if(!(JsonEqual (FileIdentity $destination) $old)-or!(JsonEqual (FileIdentity $candidate) $candidateId)-or(Test-Path -LiteralPath $nativeBackup)){throw 'Immediate file-ID/hash/ACL CAS'}
|
||||
[IO.File]::Replace($candidate,$destination,$nativeBackup)
|
||||
PrivateBackupAcl $nativeBackup;$acl=New-Object Security.AccessControl.FileSecurity;$acl.SetSecurityDescriptorSddlForm($sddl);Set-Acl -LiteralPath $destination -AclObject $acl;FlushCopy $destination
|
||||
if((Hash $destination)-cne$newHash-or(Hash $nativeBackup)-cne$oldHash-or(AclHash $destination)-cne$old.acl_sha256){throw 'Exact actual replacement/explicit native backup/ACL'}
|
||||
WriteNew (Join-Path $folder ($label+'-replaced.json')) @{original=$old;current=(FileIdentity $destination);native_backup=(FileIdentity $nativeBackup);original_backup=(FileIdentity (Join-Path $folder ($label+'-original')))}
|
||||
}
|
||||
Swap 'agent' $agentBinary (Join-Path (Join-Path $boot $p.new_agent) 'rmm-agent-windows.exe') $p.old_agent $p.new_agent
|
||||
Swap 'helper' $helperBinary (Join-Path (Join-Path $boot $p.new_helper) 'rmm-helper-windows.exe') $p.old_helper $p.new_helper
|
||||
Swap 'settings' $settings (Join-Path $folder 'new-helper.json') $p.old_policy $p.new_policy
|
||||
Swap 'pin' $pin (Join-Path $folder 'new-agent-pin.json') $p.old_pin $p.new_pin
|
||||
$swapped=ActualState $true;PreserveImmutableFiles $frozen $swapped $true;if($swapped.service.state-cne'Stopped'-or$swapped.helper_service.state-cne'Stopped'){throw 'All four new files while both stopped'};WriteNew (Join-Path $folder 'swapped.json') $swapped
|
||||
function StartOnce($role){
|
||||
$checked=ActualState $true;PreserveImmutableFiles $frozen $checked $false;if((Service $role).state-cne'Stopped'){throw 'First exact selected start only'};$name=$helperName;if($role-ceq'agent'){$name=$agentName}
|
||||
WriteNew (Join-Path $folder ($role+'-start-attempt.json')) @{start_once=$true;all_four_files_verified=$true}
|
||||
Start-Service -Name $name;(Get-Service -Name $name).WaitForStatus([ServiceProcess.ServiceControllerStatus]::Running,[TimeSpan]::FromSeconds(20))
|
||||
$s=Service $role;$held=[RmmPipeNative]::Open([int]$s.pid);try{$kernel=Kernel $role $s $held;WriteNew (Join-Path $folder ($role+'-started.json')) @{service=$s;kernel=$kernel}}finally{$held.Dispose()}
|
||||
}
|
||||
StartOnce 'helper';StartOnce 'agent';$after=ActualState $true;PreserveImmutableFiles $before $after $false;WriteNew (Join-Path $folder 'entered.json') $after
|
||||
@{entered=$true;id=$p.id;no_jobs=$true;no_reboot=$true;no_clock_change=$true}|ConvertTo-Json -Compress
|
||||
}finally{$heldAgent.Dispose();if($null-ne$heldHelper){$heldHelper.Dispose()}}
|
||||
'''
|
||||
SCRIPT = PREFIX + '\n' + NATIVE + READBACK_SERVICE + '\n' + PHASES
|
||||
PREPARE = u.transport.PREPARE_SCRIPT.replace('TransportAcceptance.ps1', 'SystemPipeUpgrade.ps1')
|
||||
LAUNCH = u.transport.LAUNCH_SCRIPT.replace('TransportAcceptance.ps1', 'SystemPipeUpgrade.ps1').replace('RmmTransportPayload', 'RmmPipeUpgradePayload')
|
||||
|
||||
|
||||
class Access:
|
||||
"""Explicit read-only access roots; never redirects source/manifest globals."""
|
||||
def __init__(self, root):
|
||||
self.root = Path(root).absolute()
|
||||
require(self.root == self.root.resolve() and self.root != ROOT.resolve(), 'separate real access root, no symlink/copy')
|
||||
self.evidence = self.root / 'devstate/windows-client'
|
||||
|
||||
def powershell(self, source, payload, timeout=180):
|
||||
access = cb.contract.protected_json(self.root / 'credentials/windows-dev-access.json')
|
||||
wrapped = "try {\n" + source + "\n} catch {[pscustomobject]@{bootstrap_error=$true;error_id=$_.FullyQualifiedErrorId;line=$_.InvocationInfo.ScriptLineNumber}|ConvertTo-Json -Compress;exit 1}"
|
||||
command = 'powershell.exe -NoLogo -NoProfile -NonInteractive -ExecutionPolicy RemoteSigned -EncodedCommand ' + base64.b64encode(wrapped.encode('utf-16le')).decode()
|
||||
result = subprocess.run(access['ssh_prefix'] + [command], input=canonical(payload) + b'\n', capture_output=True, timeout=timeout)
|
||||
if result.returncode:
|
||||
# Fixed error identifiers/line only; never raw stderr/payload/commands.
|
||||
safe = dict(returncode=result.returncode, stdout_bytes=len(result.stdout), stderr_bytes=len(result.stderr))
|
||||
try:
|
||||
error = json.loads(result.stdout.decode('utf-8-sig'), object_pairs_hook=cb.contract.strict_object)
|
||||
if error.get('bootstrap_error') is True:
|
||||
safe.update(error_id=error.get('error_id'), line=error.get('line'))
|
||||
except (ValueError, AttributeError):
|
||||
pass
|
||||
save(STATE / ('remote-error-' + str(uuid.uuid4()) + '.json'), safe)
|
||||
raise RuntimeError('fixed pipe upgrade bootstrap incomplete; readback only')
|
||||
return json.loads(result.stdout.decode('utf-8-sig'), object_pairs_hook=cb.contract.strict_object)
|
||||
|
||||
def stage(self, path, name):
|
||||
require(name in ('rmm-agent-windows.exe', 'rmm-helper-windows.exe', 'RuntimeStateProbe.exe', 'SystemStateProbe.exe', 'SystemPipeUpgrade.ps1'), 'fixed stage names')
|
||||
path = Path(path)
|
||||
digest = sha(path)
|
||||
prepare = u.transport.PREPARE_SCRIPT.replace('TransportAcceptance.ps1', name)
|
||||
observed = self.powershell(prepare, dict(sha256=digest))
|
||||
if not observed['already_uploaded']:
|
||||
access = cb.contract.protected_json(self.root / 'credentials/windows-dev-access.json')
|
||||
prefix = access['ssh_prefix']
|
||||
args = ['sftp'] + [p for p in prefix[1:-1] if p != '-T'] + ['-b', '-', prefix[-1]]
|
||||
target = '/C:/ProgramData/RustDiscoveryBootstrap/' + digest + '/' + name
|
||||
result = subprocess.run(args, input=('put ' + json.dumps(str(path.resolve())) + ' ' + json.dumps(target) + '\n').encode(), capture_output=True, timeout=60)
|
||||
require(result.returncode == 0, 'immutable exact bootstrap transfer; no retry')
|
||||
observed = self.powershell(prepare, dict(sha256=digest))
|
||||
require(observed['already_uploaded'] is True and observed['sha256'] == digest, 'same exact existing-or-new stage')
|
||||
|
||||
def server(self, function, payload):
|
||||
cloud = u.transport.cloud
|
||||
require(function in (cloud.server, u.auto.server_state, u.transport.server_transport.server_evidence), 'fixed read-only server witnesses')
|
||||
# The inherited parser is strict data parsing, not source/eval. Its ROOT
|
||||
# only checks the source .gitignore; its supplied path remains Main.
|
||||
cfg = cloud.bootstrap.access.load_config(self.root / 'credentials/server.conf')
|
||||
ssh = ['ssh', '-F', '/dev/null', '-T', '-p', cfg.get('port', '22'), '-o', 'StrictHostKeyChecking=yes', '-o', 'BatchMode=yes', '-o', 'IdentitiesOnly=yes', '-o', 'ForwardAgent=no', '-o', 'ConnectTimeout=10', '-i', str(Path(cfg['ssh_key_path']).expanduser()), cfg['username'] + '@' + cfg['address'], 'python3 -']
|
||||
code = ('import os,json,subprocess,base64,hashlib,ssl,http.client,socket,uuid,pwd\nfrom pathlib import Path\n' + inspect.getsource(cloud.bootstrap.require) + '\n' + inspect.getsource(function) + '\ntry:\n print(json.dumps(' + function.__name__ + '(' + repr(payload) + ')))\nexcept Exception as error:\n print(json.dumps(dict(error="READONLY_WITNESS_INCOMPLETE",kind=type(error).__name__)))\n')
|
||||
result = subprocess.run(ssh, input=code.encode(), capture_output=True, timeout=60)
|
||||
require(result.returncode == 0 and len(result.stdout) <= 1024 * 1024, 'bounded readonly server witness')
|
||||
value = json.loads(result.stdout, object_pairs_hook=cb.contract.strict_object)
|
||||
require('error' not in value, 'readonly server witness incomplete')
|
||||
return value
|
||||
|
||||
def server_state(self):
|
||||
cloud = u.transport.cloud
|
||||
linux = cb.contract.protected_json(self.root / 'devstate/cloud-mvp-final-closeout.json')
|
||||
require(linux['verified'] is True, 'accepted Linux target only')
|
||||
counts = {name: self.server(cloud.server, dict(kind='gate', tenant_id=tenant, agent_id=agent)) for name, tenant, agent in (
|
||||
('windows', cloud.TENANT, u.transport.AGENT), ('linux', linux['target']['tenant_id'], linux['target']['agent_id']))}
|
||||
flags = self.server(u.auto.server_state, {})
|
||||
require(u.auto.flags_disabled(flags) and counts['windows'] == dict(jobs=0, outbox=0, permits=0, unresolved=0), 'closed hooks and Windows zero-job gate')
|
||||
return dict(counts=counts, flags=flags)
|
||||
|
||||
def observe(self, ident):
|
||||
return self.server(u.transport.server_transport.server_evidence, dict(tenant_id=u.transport.cloud.TENANT, agent_id=u.transport.AGENT, fault_id=ident))
|
||||
|
||||
def device_and_denials(self):
|
||||
bridge = self
|
||||
class ReadBackend(u.transport.cloud.Backend):
|
||||
def request(self, body):
|
||||
if body['method'] == 'tools/call':
|
||||
require(body['params']['name'] == 'inventory.get_device', 'only stored inventory reads')
|
||||
else:
|
||||
require(body['method'] in ('initialize', 'notifications/initialized'), 'only MCP read session')
|
||||
return bridge.server(u.transport.cloud.server, dict(kind='http', path='/mcp', method='POST', headers=self.headers, body=body, principal=self.principal))
|
||||
device = ReadBackend().call('inventory.get_device', dict(tenant_id=u.transport.cloud.TENANT, asset_id=u.transport.ASSET))
|
||||
require(device['agent_id'] == u.transport.AGENT and device['source_id'] == 'windows.base' and set(device['capabilities']) == {'windows.base/1', 'heartbeat/1'} and device['presence'] == 'online', 'honest unchanged passive inventory')
|
||||
denied = []
|
||||
backend = ReadBackend('b')
|
||||
for tenant in (u.transport.cloud.TENANT, '22222222-2222-4222-8222-222222222222'):
|
||||
backend.sequence += 1
|
||||
response = backend.request(dict(jsonrpc='2.0', id=backend.sequence, method='tools/call', params=dict(name='inventory.get_device', arguments=dict(tenant_id=tenant, asset_id=u.transport.ASSET))))
|
||||
data = response.get('data', {})
|
||||
require('error' in data or data.get('result', {}).get('isError'), 'foreign tenant denied')
|
||||
denied.append(dict(tenant_id=tenant, denied=True))
|
||||
return device, denied
|
||||
|
||||
|
||||
def dependencies():
|
||||
modules = [cb, cb.contract, u, u.transport, u.auto, u.transport.cloud, u.transport.cloud.bootstrap, u.transport.cloud.bootstrap.access, u.transport.server_transport, u.qualification, u.qualification.feature, u.qualification.previous, u.original_helper]
|
||||
return {str(Path(m.__file__).resolve().relative_to(ROOT)): sha(m.__file__) for m in modules}
|
||||
|
||||
|
||||
def guards():
|
||||
require(sha(u.__file__) == ORIGINAL_RUNNER, 'immutable original read-only witness source')
|
||||
require('function PinProcess' not in PREFIX and 'function Swap' not in PREFIX and 'function StopPinned' not in PREFIX and 'function StartOnce' not in PREFIX, 'historical mutations excluded')
|
||||
require('[IO.File]::Replace($candidate,$destination,$nativeBackup)' in SCRIPT and '[IO.File]::Replace($candidate,$destination,$null)' not in SCRIPT, 'explicit additional absent native backup')
|
||||
ordered = [SCRIPT.index(token) for token in (" StopHeld 'agent'", " Backup 'agent'", "Backup 'pin'", " Swap 'agent'", "Swap 'pin'", '$swapped=ActualState $true', " StartOnce 'helper'", "StartOnce 'agent'")]
|
||||
require(ordered == sorted(ordered), 'all backups before any replacement; all replacements before helper/agent starts')
|
||||
require(SCRIPT.count('Start-Service -Name $name') == SCRIPT.count('Stop-Service -Name $name') == 1, 'single fixed-role control primitives')
|
||||
require(all(word not in SCRIPT + LAUNCH for word in ('Restart-Service', 'Restart-Computer', 'Stop-Computer', 'Set-Service', 'New-Service', 'Remove-Item', 'Invoke-Expression', 'Bypass')), 'no install/reconfigure/cleanup/reboot/automatic rollback')
|
||||
|
||||
|
||||
# Fresh isolated interpreter: the Pipe pack deliberately imports its transport
|
||||
# modules from Main. Reusing its module in this interpreter would accidentally
|
||||
# reuse our cached worktree client_bootstrap and corrupt the source/access split.
|
||||
# This code calls verification/read-only proof parsing ONLY, never native().
|
||||
VERIFY_PACK = r'''
|
||||
import hashlib,importlib.util,json,re,sys,uuid
|
||||
from pathlib import Path
|
||||
path=Path(sys.argv[1]);spec=importlib.util.spec_from_file_location('fixed_pipe_pack',path)
|
||||
pack=importlib.util.module_from_spec(spec);spec.loader.exec_module(pack)
|
||||
manifest_path=Path(sys.argv[2]).resolve();proof_path=Path(sys.argv[3]).resolve()
|
||||
manifest=pack.verified(manifest_path) # full current code/access hashes + Linux80/Windows58 Core proofs
|
||||
proof=pack.cb.contract.protected_json(pack.private_file(proof_path));require=pack.require
|
||||
case=proof['case_id'];require(str(uuid.UUID(case))==case and proof_path==pack.NATIVE/case/'passed.json','exact native pipe case namespace')
|
||||
require(proof['verified'] is True and proof['manifest_path']==str(manifest_path) and proof['manifest_sha256']==pack.sha(manifest_path) and proof['no_jobs'] is True and proof['clock_adapter_qualified'] is False and proof['local_service_proof'] is False and proof['native_pipe_proof'] is False,'actual same pipe manifest units, no runtime capability')
|
||||
intent=pack.cb.contract.protected_json(proof_path.parent/'intent.json')
|
||||
require(intent['id']==case and intent['manifest_path']==str(manifest_path) and intent['manifest_sha256']==pack.sha(manifest_path) and intent['runner_sha256']==pack.sha(path) and intent['script_sha256']==hashlib.sha256(pack.SCRIPT.encode()).hexdigest(),'exact executed native unit source/manifest')
|
||||
require(pack.cb.contract.protected_json(proof_path.parent/'started-local.json')['start_once'] is True,'original create-once native execution intent')
|
||||
before=pack.cb.contract.protected_json(proof_path.parent/'server-before.json')
|
||||
require(pack.auto.flags_disabled(before['flags']) and before['counts']['windows']==dict(jobs=0,outbox=0,permits=0,unresolved=0),'original closed native zero-job scope')
|
||||
actual=proof['native']
|
||||
require(actual['completed'] is True and actual['manifest_sha256']==pack.sha(manifest_path) and set(actual['reports'])==set(pack.COUNTS) and actual['both_lists_verified_before_any_test'] is True and actual['bootstrap_administrator_units'] is True and actual['local_service_proof'] is False and actual['native_pipe_proof'] is False and actual['rmm_jobs'] is False and actual['product_state_writes'] is False,'actual completed narrow units only')
|
||||
for kind,count in pack.COUNTS.items():
|
||||
report=actual['reports'][kind];listed=report['listed'];run=report['result']
|
||||
names=re.findall(r'^(.+): test\r?$',listed['stdout'],re.M)
|
||||
require(report['sha256']==manifest['artifacts'][kind]['sha256'] and names==report['names']==pack.TESTS[kind] and len(set(names))==count and type(listed['exit_code']) is int and listed['exit_code']==0 and type(run['exit_code']) is int and run['exit_code']==0 and listed['timed_out'] is False and run['timed_out'] is False and re.search(r'test result: ok\. '+str(count)+r' passed; 0 failed; 0 ignored; 0 measured; 0 filtered out;',run['stdout']),'all exact 23/7 native cases, no ignored/filtered/timeout')
|
||||
print(json.dumps(manifest))
|
||||
'''
|
||||
|
||||
|
||||
def qualified(manifest_path, proof_path):
|
||||
verifier = ROOT / 'deploy/windows/system_pipe_acceptance.py'
|
||||
require(sha(verifier) == PIPE_VERIFIER_SHA, 'exact independently reviewed Pipe-v2 pack verifier')
|
||||
result = subprocess.run([sys.executable, '-I', '-c', VERIFY_PACK, str(verifier), str(manifest_path), str(proof_path)], capture_output=True, timeout=60)
|
||||
require(result.returncode == 0 and len(result.stdout) <= 1024 * 1024, 'fresh isolated read-only Pipe verifier/native proof; details withheld')
|
||||
value = json.loads(result.stdout, object_pairs_hook=cb.contract.strict_object)
|
||||
require(value['type'] == 'rmm.windows.pipe-v2-build' and value['transport_version'] == 2 and value['native_counts_expected'] == dict(lib=23, bin=7), 'Pipe-v2 manifest, never historical delegation relabeling')
|
||||
return value
|
||||
|
||||
|
||||
def prior(access):
|
||||
runtime_path = access.evidence / 'current-runtime.json'
|
||||
components_path = access.evidence / 'current-components.json'
|
||||
runtime = cb.contract.protected_json(runtime_path)
|
||||
components = cb.contract.protected_json(components_path)
|
||||
result_path = access.evidence / ('system-delegation-upgrade/' + OLD_CASE + '/result.json')
|
||||
require(sha(result_path) == OLD_RESULT_SHA, 'independently accepted original joint result')
|
||||
result = cb.contract.protected_json(result_path)
|
||||
require(result['verified'] is True and result['completed'] is True and result['no_jobs'] is True and result['windows_jobs_enabled'] is False and result['clock_adapter_qualified'] is False, 'accepted closed passive generation')
|
||||
evidence = dict(path=str(result_path.resolve()), sha256=OLD_RESULT_SHA)
|
||||
require(runtime['case_id'] == components['case_id'] == OLD_CASE and runtime['evidence'] == components['evidence'] == evidence and runtime['binary_sha256'] == components['agent_sha256'] == OLD_AGENT and components['helper_sha256'] == OLD_HELPER and components['policy_sha256'] == OLD_POLICY and components['pin_sha256'] == OLD_PIN and runtime['transport'] == 'auto' and runtime['windows_jobs_enabled'] is False and runtime['clock_adapter_qualified'] is False and runtime['system_helper_client_feature'] is True and components['windows_jobs_enabled'] is False and components['clock_adapter_qualified'] is False and components['helper_effects_enabled'] is False, 'current accepted four-file indices, no adoption of readback')
|
||||
recovery = access.evidence / 'system-delegation-recovery/595dd1da-0d7f-4364-9040-a75e16c6da83/acceptance.json'
|
||||
require(sha(recovery) == '5ad5925c8928f49cd0f9d48a64f81018281b5b6e3704c799bae64a42898322bb' and cb.contract.protected_json(recovery)['verified'] is True, 'accepted original explicit-backup recovery preserved')
|
||||
original = cb.contract.protected_json(result_path.parent / 'intent.json')
|
||||
settings = base64.b64decode(original['payload']['settings_base64'], validate=True)
|
||||
require(raw_sha(settings) == OLD_POLICY and raw_sha(base64.b64decode(original['payload']['pin_base64'], validate=True)) == OLD_PIN, 'exact original reciprocal public settings')
|
||||
return dict(runtime=runtime, components=components, runtime_sha256=sha(runtime_path), components_sha256=sha(components_path), result_sha256=OLD_RESULT_SHA), result, json.loads(settings, object_pairs_hook=cb.contract.strict_object)
|
||||
|
||||
|
||||
def passive_settings(old, agent, helper):
|
||||
require(set(old) == {'schema_version', 'binding', 'agent', 'helper', 'allowed_services', 'max_runtime_seconds', 'enable_effects', 'allow_reboot'} and type(old['schema_version']) is int and old['schema_version'] == 1 and old['allowed_services'] == [] and old['enable_effects'] is False and old['allow_reboot'] is False and type(old['max_runtime_seconds']) is int and old['max_runtime_seconds'] == 30 and old['agent']['binary_sha256'] == OLD_AGENT and old['helper']['binary_sha256'] == OLD_HELPER, 'exact original closed public settings')
|
||||
require(all(isinstance(h, str) and len(h) == 64 and all(c in '0123456789abcdef' for c in h) for h in (agent, helper)), 'qualified new image hashes')
|
||||
new = json.loads(canonical(old)); new['agent']['binary_sha256'] = agent; new['helper']['binary_sha256'] = helper
|
||||
settings = canonical(new); policy = raw_sha(settings)
|
||||
pin = canonical(dict(schema_version=1, binding=new['binding'], policy_sha256=policy, agent=new['agent'], helper=new['helper']))
|
||||
return settings, pin, policy
|
||||
|
||||
|
||||
def leaves(access):
|
||||
path = access.evidence / 'system-intent-bootstrap/f322a4d2-c537-4842-bf04-658ad8f814b0/acceptance.json'
|
||||
require(sha(path) == u.INTENT_PREPARATION_SHA, 'accepted original empty-leaf preparation')
|
||||
proof = cb.contract.protected_json(path)
|
||||
require(proof['verified'] is True and proof['sqlite_initialized'] is False, 'not a store/SQLite qualification')
|
||||
created_path = path.parent / 'created.json'
|
||||
require(sha(created_path) == proof['native_created_sha256'], 'original native empty-leaf receipt')
|
||||
created = cb.contract.protected_json(created_path)
|
||||
items = {v['name']: v for v in created['leaves']}
|
||||
require(set(items) == {'system-intents.sqlite', 'system-intents.sqlite-journal'} and all(v['length'] == 0 for v in items.values()), 'exact two original zero-byte leaves')
|
||||
return {label: dict(name=name, acl_sha256=raw_sha(items[name]['sddl'].encode())) for label, name in [('database', 'system-intents.sqlite'), ('journal', 'system-intents.sqlite-journal')]}
|
||||
|
||||
|
||||
def remote(access, intent, action):
|
||||
require(intent['script_sha256'] == raw_sha(SCRIPT.encode()), 'immutable new pipe bootstrap source')
|
||||
return access.powershell(LAUNCH, dict(sha256=intent['script_sha256'], payload=dict(intent['payload'], action=action)))
|
||||
|
||||
|
||||
def load(ident, access):
|
||||
require(str(uuid.UUID(ident)) == ident, 'canonical original case UUID')
|
||||
folder = STATE / ident
|
||||
intent = cb.contract.protected_json(folder / 'intent.json')
|
||||
require(intent['id'] == ident and intent['runner_sha256'] == sha(__file__) and intent['script_sha256'] == raw_sha(SCRIPT.encode()) and intent['dependencies'] == dependencies() and intent['access_root'] == str(access.root), 'same source/dependencies/access root case')
|
||||
manifest = qualified(Path(intent['manifest_path']), Path(intent['qualification_path']))
|
||||
require(sha(intent['manifest_path']) == intent['payload']['manifest_sha256'] and sha(intent['qualification_path']) == intent['payload']['qualification_sha256'] and manifest['artifacts']['agent']['sha256'] == intent['payload']['new_agent'] and manifest['artifacts']['helper']['sha256'] == intent['payload']['new_helper'], 'same actually native-qualified new pair')
|
||||
return folder, intent
|
||||
|
||||
|
||||
def prepare(access, manifest_path, proof_path):
|
||||
guards()
|
||||
manifest = qualified(manifest_path, proof_path)
|
||||
indices, accepted, old = prior(access)
|
||||
settings, pin, policy = passive_settings(old, manifest['artifacts']['agent']['sha256'], manifest['artifacts']['helper']['sha256'])
|
||||
require(manifest['artifacts']['agent']['sha256'] != OLD_AGENT and manifest['artifacts']['helper']['sha256'] != OLD_HELPER, 'new coordinated pipe pair, no old source round')
|
||||
ident = str(uuid.uuid4()); folder = STATE / ident; folder.mkdir(mode=0o700, parents=True)
|
||||
script_sha = raw_sha(SCRIPT.encode())
|
||||
payload = dict(id=ident, old_agent=OLD_AGENT, old_helper=OLD_HELPER, old_policy=OLD_POLICY, old_pin=OLD_PIN, new_agent=manifest['artifacts']['agent']['sha256'], new_helper=manifest['artifacts']['helper']['sha256'], new_policy=policy, new_pin=raw_sha(pin), config_sha256=accepted['native']['config_sha256'], probe_sha256=manifest['artifacts']['probe']['sha256'], system_probe_sha256=manifest['artifacts']['system_probe']['sha256'], manifest_sha256=sha(manifest_path), qualification_sha256=sha(proof_path), script_sha256=script_sha, settings_base64=base64.b64encode(settings).decode(), pin_base64=base64.b64encode(pin).decode(), intent_leaves=leaves(access))
|
||||
draft = dict(id=ident, started_at=cb.contract.now().isoformat(), access_root=str(access.root), runner_sha256=sha(__file__), script_sha256=script_sha, manifest_path=str(manifest_path.resolve()), qualification_path=str(proof_path.resolve()), dependencies=dependencies(), original_indices=indices, payload=payload, no_jobs=True)
|
||||
save(folder / 'prepare-intent.json', draft)
|
||||
for name, data in [('runner.py', Path(__file__).read_bytes()), ('SystemPipeUpgrade.ps1', SCRIPT.encode())]:
|
||||
write_bytes(folder / name, data)
|
||||
for kind in ('agent', 'helper', 'probe', 'system_probe'):
|
||||
item = manifest['artifacts'][kind]
|
||||
require(sha(item['path']) == item['sha256'], 'qualified staged artifact bytes')
|
||||
access.stage(item['path'], item['name'])
|
||||
access.stage(folder / 'SystemPipeUpgrade.ps1', 'SystemPipeUpgrade.ps1')
|
||||
before = remote(access, draft, 'baseline')
|
||||
expected = accepted['native']
|
||||
for field in ('agent_id', 'asset_id', 'binary_sha256', 'helper_sha256', 'policy_sha256', 'pin_sha256', 'config_sha256', 'config_acl_sha256', 'binary_acl_sha256', 'helper_binary_acl_sha256', 'settings_acl_sha256', 'pin_acl_sha256', 'public_hashes', 'identity_acls', 'private_key_metadata'):
|
||||
require(before[field] == expected[field], 'accepted original identity/PKI/config/four-file ACLs; no private key read')
|
||||
for field in ('database_file_id', 'database_creation', 'identity_sha256', 'schema'):
|
||||
require(before['journal'][field] == expected['journal'][field], 'same actual original telemetry database identity')
|
||||
for field in ('helper_ledger', 'executor_lock', 'intent_store'):
|
||||
require(before['helper_witness'][field] == expected['helper_witness'][field], 'same actual helper DB/lock/FileIDs/zero-byte leaves')
|
||||
for role in ('service', 'helper_service'):
|
||||
for field in ('start_name', 'start_mode', 'path', 'service_type', 'sid_type', 'service_acl_sha256'):
|
||||
require(before[role][field] == expected[role][field], 'original exact SCM account/config/ACL')
|
||||
baseline = canonical(before)
|
||||
write_bytes(folder / 'baseline.json', baseline)
|
||||
payload.update(baseline_base64=base64.b64encode(baseline).decode(), baseline_sha256=raw_sha(baseline))
|
||||
draft['payload'] = payload
|
||||
save(folder / 'intent.json', draft)
|
||||
save(folder / 'server-before.json', access.server_state())
|
||||
central = access.observe(ident)['device']; require(central and central['agent_id'] == u.transport.AGENT, 'original stored authenticated device')
|
||||
save(folder / 'central-before.json', central)
|
||||
print(json.dumps(dict(id=ident, prepared=True, no_component_mutation=True, baseline_sha256=raw_sha(baseline), needs_explicit_review_before_enter=True)))
|
||||
|
||||
|
||||
def enter(access, ident, baseline_sha):
|
||||
folder, intent = load(ident, access)
|
||||
require(sha(folder / 'baseline.json') == intent['payload']['baseline_sha256'] == baseline_sha, 'explicit reviewed exact baseline required')
|
||||
indices, _, _ = prior(access)
|
||||
require(indices == intent['original_indices'] and access.server_state() == cb.contract.protected_json(folder / 'server-before.json'), 'both original current indices and server gates unchanged')
|
||||
save(folder / 'enter-attempt.json', dict(enter_once=True, baseline_sha256=baseline_sha, lost_reply_readback_only=True))
|
||||
result = remote(access, intent, 'enter')
|
||||
require(result.get('entered') is True and result['id'] == ident, 'actual same single transition reply')
|
||||
save(folder / 'entered.json', result)
|
||||
print(json.dumps(dict(id=ident, entered=True, continuation='finish/readback only; never repeat enter')))
|
||||
|
||||
|
||||
def finish(access, ident, read_only=False):
|
||||
folder, intent = load(ident, access)
|
||||
action = 'readback' if read_only else 'finish'
|
||||
observed = remote(access, intent, action)
|
||||
save(folder / ('readback-' + str(uuid.uuid4()) + '.json'), observed)
|
||||
require(observed['read_only'] is True and observed['id'] == ident, 'only existing case readback')
|
||||
if read_only:
|
||||
print(json.dumps(dict(id=ident, read_only=True, phase_receipts=observed['phase_receipts']))); return
|
||||
require(observed['completed'] is True, 'actual complete pair preservation')
|
||||
result_path = folder / 'result.json'
|
||||
if result_path.exists():
|
||||
previous = cb.contract.protected_json(result_path)
|
||||
require(previous['verified'] is True and all(previous['native'][role] == observed['native'][role] for role in ('service', 'helper_service')), 'same completed current instances; no republication or mutation')
|
||||
print(json.dumps(dict(id=ident, verified=True, retained_original_result=True, main_indices_published=False))); return
|
||||
# Two genuinely new server heartbeats after both single starts, not cached
|
||||
# contacts from baseline, and no new network-agent jobs/capabilities.
|
||||
after = cb.contract.timestamp(intent['started_at']); baseline = cb.contract.protected_json(folder / 'central-before.json')
|
||||
watermark = access.observe(ident)['device']
|
||||
require(watermark and watermark['agent_id'] == u.transport.AGENT and watermark['last_contact_at'], 'post-finish server heartbeat watermark')
|
||||
deadline = time.monotonic() + 150; first = None
|
||||
while True:
|
||||
evidence = access.observe(ident); device = evidence['device']
|
||||
if device and device['transport'] == 'wss' and device['last_contact_at'] and cb.contract.timestamp(device['last_contact_at']) > cb.contract.timestamp(watermark['last_contact_at']):
|
||||
require(all(device[k] == baseline[k] for k in ('agent_id', 'asset_id', 'enrollment_generation', 'assignment_version', 'certificate_sha256')), 'same original mTLS identity')
|
||||
if first is None: first = evidence
|
||||
elif device['last_contact_at'] != first['device']['last_contact_at']: break
|
||||
require(time.monotonic() < deadline, 'two native post-upgrade heartbeats missing')
|
||||
time.sleep(2)
|
||||
final = remote(access, intent, 'finish'); native = final['native']
|
||||
original = json.loads(base64.b64decode(intent['payload']['baseline_base64']), object_pairs_hook=cb.contract.strict_object)
|
||||
require(native['journal']['pending_inventory_events'] == 0 and native['journal']['sequence'] > original['journal']['sequence'], 'fresh telemetry sequence and concrete inventory ACK')
|
||||
device, denied = access.device_and_denials()
|
||||
require(cb.contract.timestamp(device['observed_at']) >= after, 'fresh original stored inventory')
|
||||
require(access.server_state() == cb.contract.protected_json(folder / 'server-before.json'), 'both target counts/policies/hooks unchanged')
|
||||
indices, _, _ = prior(access)
|
||||
require(indices == intent['original_indices'], 'Main current indices still original; Root owns later CAS publication')
|
||||
pipe = u.actual_pipe_proof(native, intent)
|
||||
result = dict(verified=True, completed=True, id=ident, original=final['original'], frozen=final['frozen'], native=native, online=dict(watermark=watermark, first=first, second=evidence), stored_inventory=device, foreign_denied=denied, native_pipe_peer_test=pipe, pipe_framing_version=2, no_jobs=True, windows_jobs_enabled=False, clock_adapter_qualified=False, system_helper_client_feature=True, helper_effects_enabled=False, no_reboot=True, no_clock_change=True, private_key_read=False, original_indices=intent['original_indices'], main_indices_published=False, manifest_path=intent['manifest_path'], manifest_sha256=intent['payload']['manifest_sha256'], qualification_sha256=intent['payload']['qualification_sha256'], runner_sha256=intent['runner_sha256'], script_sha256=intent['script_sha256'])
|
||||
save(result_path, result)
|
||||
print(json.dumps(dict(id=ident, verified=True, passive_preservation=True, native_pipe_peer_test=pipe, main_indices_published=False)))
|
||||
|
||||
|
||||
def main():
|
||||
os.umask(0o077)
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('phase', choices=('prepare', 'enter', 'finish', 'readback', 'guards'))
|
||||
parser.add_argument('--access-root', type=Path); parser.add_argument('--manifest', type=Path); parser.add_argument('--qualification', type=Path); parser.add_argument('--id'); parser.add_argument('--baseline-sha256')
|
||||
args = parser.parse_args(); guards()
|
||||
if args.phase == 'guards':
|
||||
require(not any((args.access_root, args.manifest, args.qualification, args.id, args.baseline_sha256)), 'local source guards only'); print('PASS: local source guards; no VM action'); return
|
||||
require(args.access_root, 'explicit separate read-only Main access root')
|
||||
access = Access(args.access_root)
|
||||
if args.phase == 'prepare':
|
||||
require(args.manifest and args.qualification and not (args.id or args.baseline_sha256), 'qualified new pair and read-only baseline preparation')
|
||||
prepare(access, args.manifest, args.qualification)
|
||||
elif args.phase == 'enter':
|
||||
require(args.id and args.baseline_sha256 and not (args.manifest or args.qualification), 'same prepared case and reviewed baseline hash')
|
||||
enter(access, args.id, args.baseline_sha256)
|
||||
else:
|
||||
require(args.id and not (args.manifest or args.qualification or args.baseline_sha256), 'same original case readback/finish')
|
||||
finish(access, args.id, args.phase == 'readback')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
try: main()
|
||||
except Exception as error:
|
||||
print('WINDOWS_PIPE_UPGRADE_INCOMPLETE:' + type(error).__name__)
|
||||
raise SystemExit(2) from None
|
||||
@@ -0,0 +1,70 @@
|
||||
"""Four local orchestration guards; no credentials/VM/Windows API calls."""
|
||||
import contextlib
|
||||
import copy
|
||||
import io
|
||||
import json
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest.mock import Mock, patch
|
||||
|
||||
import system_pipe_upgrade as p
|
||||
|
||||
|
||||
def settings():
|
||||
return dict(schema_version=1, binding={'public_fixture': True}, agent=dict(binary_sha256=p.OLD_AGENT), helper=dict(binary_sha256=p.OLD_HELPER), allowed_services=[], max_runtime_seconds=30, enable_effects=False, allow_reboot=False)
|
||||
|
||||
|
||||
class PipeUpgradeGuards(unittest.TestCase):
|
||||
def test_closed_reciprocal_settings_only_change_two_image_pins(self):
|
||||
original = settings(); preserved = copy.deepcopy(original)
|
||||
raw, pin, policy = p.passive_settings(original, 'a' * 64, 'b' * 64)
|
||||
changed = json.loads(raw); changed['agent']['binary_sha256'] = p.OLD_AGENT; changed['helper']['binary_sha256'] = p.OLD_HELPER
|
||||
self.assertEqual(changed, preserved); self.assertEqual(original, preserved)
|
||||
self.assertEqual(p.raw_sha(raw), policy); self.assertEqual(json.loads(pin)['policy_sha256'], policy)
|
||||
for field, value in [('enable_effects', True), ('allow_reboot', True), ('allowed_services', ['foreign']), ('max_runtime_seconds', 120), ('schema_version', True)]:
|
||||
bad = settings(); bad[field] = value
|
||||
with self.subTest(field=field), self.assertRaises(RuntimeError): p.passive_settings(bad, 'a' * 64, 'b' * 64)
|
||||
|
||||
def test_historical_mutation_helpers_excluded_and_explicit_backups_ordered(self):
|
||||
p.guards()
|
||||
self.assertNotIn('function PinProcess', p.PREFIX)
|
||||
self.assertNotIn('[IO.File]::Replace($candidate,$destination,$null)', p.SCRIPT)
|
||||
self.assertIn('[RmmPipeNative]::Open([int]$before.service.pid)', p.SCRIPT)
|
||||
self.assertNotIn('$expected=5140', p.SCRIPT)
|
||||
self.assertIn("'helper-already-stopped.json'", p.SCRIPT)
|
||||
self.assertIn('stop_called=$false;start_called=$false', p.SCRIPT)
|
||||
self.assertIn("@('config','ca','identity','certificate','private_key')", p.SCRIPT)
|
||||
self.assertEqual(p.SCRIPT.count('PreserveImmutableFiles '), 5)
|
||||
readback = p.PHASES.split("if($p.action-ceq'readback'){", 1)[1].split("if($p.action-ceq'finish'){", 1)[0]
|
||||
self.assertIn("(ReadbackService 'agent')", readback)
|
||||
self.assertNotIn('(Service ', readback)
|
||||
self.assertIn('process_identity_verified=$false', p.READBACK_SERVICE)
|
||||
self.assertIn('pack.verified(manifest_path)', p.VERIFY_PACK)
|
||||
self.assertIn("names==report['names']==pack.TESTS[kind]", p.VERIFY_PACK)
|
||||
with patch.object(p.subprocess, 'run', return_value=Mock(returncode=0, stdout=b'{"type":"rmm.windows.system-delegation-build"}')):
|
||||
with self.assertRaises(RuntimeError): p.qualified(Path('unused-fixture'), Path('unused-proof'))
|
||||
|
||||
def test_lost_enter_reply_cannot_repeat_target_mutation(self):
|
||||
with tempfile.TemporaryDirectory() as temporary:
|
||||
folder = Path(temporary); p.write_bytes(folder / 'baseline.json', b'{}')
|
||||
digest = p.sha(folder / 'baseline.json'); indices = {'unit_fixture': True}
|
||||
intent = dict(payload=dict(baseline_sha256=digest), original_indices=indices)
|
||||
p.save(folder / 'server-before.json', {'unit_counts': 0})
|
||||
access = Mock(); access.server_state.return_value = {'unit_counts': 0}
|
||||
with patch.object(p, 'load', return_value=(folder, intent)), patch.object(p, 'prior', return_value=(indices, {}, {})), patch.object(p, 'remote', side_effect=TimeoutError('unit fixture lost reply')) as remote:
|
||||
with self.assertRaises(TimeoutError): p.enter(access, 'fixture', digest)
|
||||
self.assertTrue((folder / 'enter-attempt.json').exists())
|
||||
with self.assertRaises(FileExistsError): p.enter(access, 'fixture', digest)
|
||||
self.assertEqual(remote.call_count, 1)
|
||||
|
||||
def test_readback_never_queries_server_starts_or_publishes_main_indices(self):
|
||||
with tempfile.TemporaryDirectory() as temporary:
|
||||
access = Mock(); access.server_state.side_effect = AssertionError('server unavailable in readback')
|
||||
with patch.object(p, 'load', return_value=(Path(temporary), {})), patch.object(p, 'remote', return_value=dict(read_only=True, id='fixture', phase_receipts={})) as remote, contextlib.redirect_stdout(io.StringIO()):
|
||||
p.finish(access, 'fixture', read_only=True)
|
||||
remote.assert_called_once_with(access, {}, 'readback')
|
||||
self.assertFalse(access.server_state.called)
|
||||
|
||||
|
||||
if __name__ == '__main__': unittest.main()
|
||||
@@ -0,0 +1,219 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Start the existing W32Time once after review; lost replies use readback only.
|
||||
|
||||
This bootstrap never changes service configuration, NTP, policy, ACLs or RMM
|
||||
components. A running W32Time is not evidence of a qualified/trusted clock.
|
||||
"""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import stat
|
||||
import uuid
|
||||
|
||||
import client_bootstrap as cb
|
||||
import system_helper_bootstrap as helper
|
||||
import transport_acceptance as source_stage
|
||||
|
||||
STATE = cb.EVIDENCE / 'time-service-start'
|
||||
CONTEXT = cb.EVIDENCE / 'time-service-start-context/888b18b8-da7e-4b9f-9e36-32a23f2ff973/before.json'
|
||||
require = cb.contract.require
|
||||
|
||||
SCRIPT = r'''$ErrorActionPreference='Stop'
|
||||
$p=$global:RmmTimeServiceStartPayload
|
||||
if(!$p-or[guid]::ParseExact($p.id,'D').ToString()-cne$p.id-or$p.action-notin@('state','start','readback')){throw 'Fixed time-service case'}
|
||||
foreach($name in @('agent_sha256','helper_sha256','config_sha256','policy_sha256','pin_sha256')){if($p.$name-notmatch'^[a-f0-9]{64}$'){throw 'Exact retained component pins'}}
|
||||
$boot='C:\ProgramData\RustDiscoveryBootstrap';$folder=Join-Path $boot ('time-service-'+$p.id);$active=Join-Path $boot 'w32time-start-once.json'
|
||||
function HashBytes([byte[]]$bytes){$h=[Security.Cryptography.SHA256]::Create();try{return([BitConverter]::ToString($h.ComputeHash($bytes))).Replace('-','').ToLowerInvariant()}finally{$h.Dispose()}}
|
||||
function JsonHash($value){return HashBytes ([Text.Encoding]::UTF8.GetBytes(($value|ConvertTo-Json -Depth 24 -Compress)))}
|
||||
function CheckControl($path,[bool]$directory){
|
||||
$item=Get-Item -LiteralPath $path -Force
|
||||
if($item.PSIsContainer-ne$directory-or($item.Attributes-band[IO.FileAttributes]::ReparsePoint)){throw 'Fixed private bootstrap path'}
|
||||
$acl=Get-Acl -LiteralPath $path
|
||||
if($acl.GetOwner([Security.Principal.SecurityIdentifier]).Value-notin@('S-1-5-18','S-1-5-32-544')-or!$acl.Access.Count){throw 'Bootstrap owner/DACL'}
|
||||
foreach($r in $acl.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier])){if($r.AccessControlType-ne'Allow'-or$r.IdentityReference.Value-notin@('S-1-5-18','S-1-5-32-544')){throw 'Bootstrap controller only'}}
|
||||
}
|
||||
function WriteNew($path,$value){$bytes=[Text.Encoding]::UTF8.GetBytes(($value|ConvertTo-Json -Depth 24 -Compress));$file=[IO.File]::Open($path,'CreateNew','Write','Read');try{$file.Write($bytes,0,$bytes.Length);$file.Flush($true)}finally{$file.Dispose()};CheckControl $path $false}
|
||||
function FileMeta($path,[bool]$hash){
|
||||
$item=Get-Item -LiteralPath $path -Force;if($item.PSIsContainer-or($item.Attributes-band[IO.FileAttributes]::ReparsePoint)){throw 'Regular original component'}
|
||||
$parent=$item.Directory;while($null-ne$parent){if($parent.Attributes-band[IO.FileAttributes]::ReparsePoint){throw 'Original ancestor reparse'};$parent=$parent.Parent}
|
||||
$acl=Get-Acl -LiteralPath $path
|
||||
return [ordered]@{length=$item.Length;created_filetime=$item.CreationTimeUtc.ToFileTimeUtc().ToString();written_filetime=$item.LastWriteTimeUtc.ToFileTimeUtc().ToString();owner_sid=$acl.GetOwner([Security.Principal.SecurityIdentifier]).Value;acl_sha256=(HashBytes ([Text.Encoding]::UTF8.GetBytes($acl.Sddl)));sha256=if($hash){(Get-FileHash -LiteralPath $path -Algorithm SHA256).Hash.ToLowerInvariant()}else{$null}}
|
||||
}
|
||||
function ServiceState($name){
|
||||
$service=Get-CimInstance Win32_Service -Filter ("Name='"+$name+"'") -OperationTimeoutSec 10
|
||||
if(!$service){throw 'Existing fixed service required'}
|
||||
$security=& "$env:WINDIR\System32\sc.exe" sdshow $name;if($LASTEXITCODE-ne0){throw 'Read service security'}
|
||||
$sidtype=& "$env:WINDIR\System32\sc.exe" qsidtype $name;if($LASTEXITCODE-ne0){throw 'Read service SID type'}
|
||||
$definition=[ordered]@{account=$service.StartName;start_mode=$service.StartMode;image_path=$service.PathName;service_type=$service.ServiceType;security_sha256=(HashBytes ([Text.Encoding]::UTF8.GetBytes(($security-join "`n").Trim())));sid_type_sha256=(HashBytes ([Text.Encoding]::UTF8.GetBytes(($sidtype-join "`n").Trim())))}
|
||||
return [ordered]@{name=$name;state=$service.State;pid=$service.ProcessId;definition=$definition}
|
||||
}
|
||||
function TimeConfigHash{
|
||||
# Selected stable configuration only. Normal synchronization may update other
|
||||
# runtime registry state; neither values nor NTP hostnames leave this function.
|
||||
$specs=@(
|
||||
@('SYSTEM\CurrentControlSet\Services\W32Time',@('Start','DelayedAutoStart','ImagePath','ObjectName','Type')),
|
||||
@('SYSTEM\CurrentControlSet\Services\W32Time\Parameters',@('Type','NtpServer','ServiceDll','ServiceMain')),
|
||||
@('SYSTEM\CurrentControlSet\Services\W32Time\Config',@('AnnounceFlags','MinPollInterval','MaxPollInterval','MaxNegPhaseCorrection','MaxPosPhaseCorrection','UpdateInterval','FrequencyCorrectRate','PhaseCorrectRate','LocalClockDispersion')),
|
||||
@('SYSTEM\CurrentControlSet\Services\W32Time\TimeProviders\NtpClient',@('Enabled','InputProvider','DllName','SpecialPollInterval')),
|
||||
@('SYSTEM\CurrentControlSet\Services\W32Time\TimeProviders\NtpServer',@('Enabled','InputProvider','DllName')),
|
||||
@('SOFTWARE\Policies\Microsoft\W32Time\Parameters',@('Type','NtpServer')),
|
||||
@('SOFTWARE\Policies\Microsoft\W32Time\Config',@('AnnounceFlags','MinPollInterval','MaxPollInterval','MaxNegPhaseCorrection','MaxPosPhaseCorrection','UpdateInterval')),
|
||||
@('SOFTWARE\Policies\Microsoft\W32Time\TimeProviders\NtpClient',@('Enabled','InputProvider','DllName','SpecialPollInterval')),
|
||||
@('SOFTWARE\Policies\Microsoft\W32Time\TimeProviders\NtpServer',@('Enabled','InputProvider','DllName')))
|
||||
$entries=@();foreach($spec in $specs){$path='Registry::HKEY_LOCAL_MACHINE\'+$spec[0];$exists=Test-Path -LiteralPath $path;$values=@()
|
||||
if($exists){$key=Get-Item -LiteralPath $path;try{foreach($name in $spec[1]){if($key.GetValueNames()-ccontains$name){$values+=,[ordered]@{name=$name;kind=$key.GetValueKind($name).ToString();value=$key.GetValue($name,$null,[Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames)}}}}finally{$key.Close()}}
|
||||
$entries+=,[ordered]@{path=$spec[0];exists=$exists;values=$values}
|
||||
};return JsonHash $entries
|
||||
}
|
||||
function Snapshot{
|
||||
$rmm=@();foreach($pair in @(@('RmmDiscoveryWindows','C:\Program Files\RustDiscovery\rmm-agent-windows.exe',$p.agent_sha256),@('RmmDiscoverySystemHelper','C:\Program Files\RustDiscovery\rmm-helper-windows.exe',$p.helper_sha256))){
|
||||
$service=ServiceState $pair[0];if($service.state-cne'Running'-or$service.pid-le0){throw 'Retain both running RMM components'}
|
||||
$proc=[Diagnostics.Process]::GetProcessById([int]$service.pid);try{$birth=$proc.StartTime.ToUniversalTime().ToFileTimeUtc().ToString();$image=$proc.MainModule.FileName}finally{$proc.Dispose()}
|
||||
if(![string]::Equals($image,$pair[1],[StringComparison]::OrdinalIgnoreCase)){throw 'Actual retained RMM image'}
|
||||
$binary=FileMeta $pair[1] $true;if($binary.sha256-cne$pair[2]){throw 'Independently pinned RMM binary'}
|
||||
$rmm+=,[ordered]@{service=$service;process_birth_filetime=$birth;binary=$binary}
|
||||
}
|
||||
$files=[ordered]@{};foreach($pair in @(@('config','C:\ProgramData\RustDiscovery\config.json',$p.config_sha256),@('helper_settings','C:\ProgramData\RustDiscoverySystem\helper.json',$p.policy_sha256),@('agent_pin','C:\ProgramData\RustDiscoverySystem\agent-pin.json',$p.pin_sha256))){$value=FileMeta $pair[1] $true;if($value.sha256-cne$pair[2]){throw 'Retained original config/pins'};$files[$pair[0]]=$value}
|
||||
foreach($pair in @(@('ca','C:\ProgramData\RustDiscovery\server-ca.pem'),@('identity','C:\ProgramData\RustDiscovery\state\identity.json'),@('certificate','C:\ProgramData\RustDiscovery\state\device.pem'))){$files[$pair[0]]=FileMeta $pair[1] $true}
|
||||
$files['private_key_metadata_only']=FileMeta 'C:\ProgramData\RustDiscovery\state\device.key' $false
|
||||
$cfg=Get-Content -LiteralPath 'C:\ProgramData\RustDiscovery\config.json' -Raw|ConvertFrom-Json
|
||||
if(($cfg.PSObject.Properties.Name-ccontains'enable_jobs')-and$cfg.enable_jobs-ne$false){throw 'No RMM jobs enabled'}
|
||||
if(($cfg.PSObject.Properties.Name-ccontains'job_binding_file')-and$null-ne$cfg.job_binding_file){throw 'No new job binding'}
|
||||
$policy=Get-Content -LiteralPath 'C:\ProgramData\RustDiscoverySystem\helper.json' -Raw|ConvertFrom-Json
|
||||
if($policy.enable_effects-ne$false-or$policy.allow_reboot-ne$false-or@($policy.allowed_services).Count-ne0){throw 'Closed original helper policy'}
|
||||
return [ordered]@{rmm=$rmm;original_files=$files;time_service=(ServiceState 'W32Time');selected_time_config_sha256=(TimeConfigHash);time_config_coverage='fixed_service_NTP_and_policy_configuration_values_only'}
|
||||
}
|
||||
function BaselineHash($snapshot){return JsonHash ([ordered]@{rmm=$snapshot.rmm;original_files=$snapshot.original_files;time_definition=$snapshot.time_service.definition;selected_time_config_sha256=$snapshot.selected_time_config_sha256})}
|
||||
function Preserved($before,$after){
|
||||
if((JsonHash $before.rmm)-cne(JsonHash $after.rmm)-or(JsonHash $before.original_files)-cne(JsonHash $after.original_files)){throw 'RMM components or original config/PKI metadata changed'}
|
||||
if((JsonHash $before.time_service.definition)-cne(JsonHash $after.time_service.definition)-or$before.selected_time_config_sha256-cne$after.selected_time_config_sha256){throw 'Service configuration/security or selected NTP/policy values changed'}
|
||||
}
|
||||
CheckControl $boot $true
|
||||
if($p.action-ceq'state'){$snapshot=Snapshot;@{id=$p.id;snapshot=$snapshot;baseline_sha256=(BaselineHash $snapshot);read_only=$true;no_jobs=$true;clock_trust_assessed=$false}|ConvertTo-Json -Depth 24 -Compress;return}
|
||||
if($p.expected_sha256-notmatch'^[a-f0-9]{64}$'-or$p.baseline_sha256-notmatch'^[a-f0-9]{64}$'){throw 'Retained reviewed case hashes'}
|
||||
if($p.action-ceq'readback'){
|
||||
if(!(Test-Path -LiteralPath $folder)){@{id=$p.id;entered=$false;readback_only=$true;start_repeated=$false;current=(Snapshot);clock_trust_assessed=$false}|ConvertTo-Json -Depth 24 -Compress;return}
|
||||
CheckControl $folder $true;CheckControl (Join-Path $folder 'intent.json') $false
|
||||
$intent=Get-Content -LiteralPath (Join-Path $folder 'intent.json') -Raw|ConvertFrom-Json
|
||||
if($intent.id-cne$p.id-or$intent.expected_sha256-cne$p.expected_sha256){throw 'Exact retained time-service intent'}
|
||||
$after=Snapshot;Preserved $intent.before $after
|
||||
$receipt=Join-Path $folder 'result.json';$result=$null;if(Test-Path -LiteralPath $receipt){CheckControl $receipt $false;$result=Get-Content -LiteralPath $receipt -Raw|ConvertFrom-Json}
|
||||
@{id=$p.id;entered=$true;readback_only=$true;start_repeated=$false;original_result=$result;start_intent_exists=(Test-Path -LiteralPath (Join-Path $folder 'start-intent.json'));current=$after;preserved=$true;clock_trust_assessed=$false}|ConvertTo-Json -Depth 24 -Compress;return
|
||||
}
|
||||
if((Test-Path -LiteralPath $folder)-or(Test-Path -LiteralPath $active)){throw 'Existing start case: readback only, never repeat start'}
|
||||
$before=Snapshot
|
||||
if((BaselineHash $before)-cne$p.baseline_sha256){throw 'Exact reviewed baseline changed; do not rebase'}
|
||||
if($before.time_service.state-notin@('Stopped','Running')){throw 'Pending or unknown time-service state: no start'}
|
||||
if($before.time_service.state-ceq'Stopped'){$controller=Get-Service -Name W32Time;try{if(@($controller.ServicesDependedOn).Count-ne0-or$controller.Status-ne[ServiceProcess.ServiceControllerStatus]::Stopped){throw 'No implicit dependency starts or changed service state'}}finally{$controller.Dispose()}}
|
||||
New-Item -ItemType Directory -Path $folder|Out-Null;CheckControl $folder $true
|
||||
WriteNew (Join-Path $folder 'intent.json') @{id=$p.id;expected_sha256=$p.expected_sha256;before=$before;create_only=$true;clock_trust_assessed=$false}
|
||||
if($before.time_service.state-ceq'Running'){
|
||||
$after=Snapshot;Preserved $before $after
|
||||
$result=@{id=$p.id;status='already_running';start_called=$false;already_running_read_only=$true;preserved=$true;clock_trust_assessed=$false;no_jobs=$true}
|
||||
WriteNew (Join-Path $folder 'result.json') $result;$result|ConvertTo-Json -Compress;return
|
||||
}
|
||||
# Durable local and global admission precede the one exact SCM start. Nothing
|
||||
# catches/retries the start; an incomplete receipt can only be read back.
|
||||
WriteNew $active @{id=$p.id;expected_sha256=$p.expected_sha256;service='W32Time';create_only=$true}
|
||||
WriteNew (Join-Path $folder 'start-intent.json') @{id=$p.id;service='W32Time';start_reserved=$true;observed_at=[DateTime]::UtcNow.ToString('o')}
|
||||
Start-Service -Name W32Time
|
||||
$service=Get-Service -Name W32Time
|
||||
$service.WaitForStatus([ServiceProcess.ServiceControllerStatus]::Running,[TimeSpan]::FromSeconds(20))
|
||||
$after=Snapshot;Preserved $before $after
|
||||
if($after.time_service.state-cne'Running'){throw 'No running-state confirmation'}
|
||||
$result=@{id=$p.id;status='started';start_called=$true;preserved=$true;clock_trust_assessed=$false;no_jobs=$true;after=$after}
|
||||
WriteNew (Join-Path $folder 'result.json') $result;$result|ConvertTo-Json -Depth 24 -Compress
|
||||
'''
|
||||
|
||||
PREPARE = source_stage.PREPARE_SCRIPT.replace('TransportAcceptance.ps1', 'TimeServiceStart.ps1')
|
||||
LAUNCH = source_stage.LAUNCH_SCRIPT.replace('TransportAcceptance.ps1', 'TimeServiceStart.ps1').replace('RmmTransportPayload', 'RmmTimeServiceStartPayload')
|
||||
|
||||
|
||||
def digest(path):
|
||||
return hashlib.sha256(Path(path).read_bytes()).hexdigest()
|
||||
|
||||
|
||||
def save(folder, name, value):
|
||||
return helper.store(folder, name, value)
|
||||
|
||||
|
||||
def preserve_failure(folder):
|
||||
path = cb.EVIDENCE / 'bootstrap-private-last-error.json'
|
||||
if not path.exists():
|
||||
return
|
||||
fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW)
|
||||
with os.fdopen(fd, 'rb') as source:
|
||||
info = os.fstat(source.fileno())
|
||||
require(stat.S_ISREG(info.st_mode) and info.st_uid == os.getuid() and info.st_mode & 0o077 == 0 and info.st_size <= 4 * 1024 * 1024, 'private original bootstrap failure')
|
||||
raw = source.read()
|
||||
target = folder / ('retained-bootstrap-error-' + hashlib.sha256(raw).hexdigest() + '.json')
|
||||
if not target.exists():
|
||||
fd = os.open(target, os.O_CREAT | os.O_EXCL | os.O_WRONLY | os.O_NOFOLLOW, 0o600)
|
||||
with os.fdopen(fd, 'wb') as output:
|
||||
output.write(raw); output.flush(); os.fsync(output.fileno())
|
||||
|
||||
|
||||
def remote(folder, payload):
|
||||
preserve_failure(folder)
|
||||
try:
|
||||
return cb.powershell(LAUNCH, {'sha256': hashlib.sha256(SCRIPT.encode()).hexdigest(), 'payload': payload}, timeout=100, remote_signed=True)
|
||||
finally:
|
||||
preserve_failure(folder)
|
||||
|
||||
|
||||
def prepare(pins):
|
||||
require(all(re.fullmatch('[0-9a-f]{64}', value) for value in pins.values()), 'independently known retained hashes')
|
||||
helper.private_dir(STATE); ident = str(uuid.uuid4()); folder = STATE / ident; folder.mkdir(mode=0o700)
|
||||
source_sha = hashlib.sha256(SCRIPT.encode()).hexdigest()
|
||||
payload = dict(id=ident, **pins)
|
||||
save(folder, 'intent.json', {'schema_version': 1, 'type': 'rmm.windows.time-service-start', 'payload': payload, 'source_file_sha256': digest(__file__), 'script_sha256': source_sha, 'closed_central_before': {'path': str(CONTEXT), 'sha256': digest(CONTEXT)}})
|
||||
source = folder / 'TimeServiceStart.ps1'
|
||||
fd = os.open(source, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600)
|
||||
with os.fdopen(fd, 'wb') as output:
|
||||
output.write(SCRIPT.encode()); output.flush(); os.fsync(output.fileno())
|
||||
preserve_failure(folder)
|
||||
try:
|
||||
helper.transfer(source, 'TimeServiceStart.ps1', source_sha, PREPARE)
|
||||
before = remote(folder, dict(payload, action='state'))
|
||||
finally:
|
||||
preserve_failure(folder)
|
||||
require(before.get('read_only') is True and before.get('clock_trust_assessed') is False, 'actual readonly baseline')
|
||||
save(folder, 'before.json', before)
|
||||
print(json.dumps({'case_id': ident, 'prepared': True, 'time_state': before['snapshot']['time_service']['state'], 'clock_trust_assessed': False, 'start_executed': False}))
|
||||
|
||||
|
||||
def run(ident, action):
|
||||
require(str(uuid.UUID(ident)) == ident, 'exact existing case UUID')
|
||||
folder = STATE / ident; intent = cb.contract.protected_json(folder / 'intent.json')
|
||||
require(intent['source_file_sha256'] == digest(__file__) and intent['script_sha256'] == hashlib.sha256(SCRIPT.encode()).hexdigest(), 'same reviewed source; no case rebase')
|
||||
baseline = cb.contract.protected_json(folder / 'before.json')['snapshot']
|
||||
# Powershell creates its canonical baseline hash during state. It is sent
|
||||
# back verbatim rather than approximating ConvertTo-Json in Python.
|
||||
payload = dict(intent['payload'], action=action, baseline_sha256=cb.contract.protected_json(folder / 'before.json')['baseline_sha256'], expected_sha256=hashlib.sha256(json.dumps(intent['payload'], sort_keys=True, separators=(',', ':')).encode()).hexdigest())
|
||||
require(baseline is not None and digest(CONTEXT) == intent['closed_central_before']['sha256'], 'retained actual baseline and closed central context')
|
||||
if action == 'start':
|
||||
save(folder, 'start-attempt.json', {'case_id': ident, 'once': True, 'lost_reply_readback_only': True})
|
||||
result = remote(folder, payload)
|
||||
save(folder, ('result.json' if action == 'start' else 'readback-' + str(uuid.uuid4()) + '.json'), result)
|
||||
original = result.get('original_result') or result
|
||||
current = result.get('current') or result.get('after')
|
||||
print(json.dumps({'case_id': ident, 'status': original.get('status', 'unconfirmed'), 'running': current['time_service']['state'] == 'Running' if current else original.get('status') == 'already_running', 'preserved': result.get('preserved', False), 'readback_only': result.get('readback_only', False), 'clock_trust_assessed': False}))
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__); parser.add_argument('action', choices=['prepare', 'start', 'readback']); parser.add_argument('--id')
|
||||
for name in ['agent', 'helper', 'config', 'policy', 'pin']:
|
||||
parser.add_argument('--' + name + '-sha256')
|
||||
args = parser.parse_args()
|
||||
if args.action == 'prepare':
|
||||
pins = {name + '_sha256': getattr(args, name + '_sha256') for name in ['agent', 'helper', 'config', 'policy', 'pin']}
|
||||
require(all(isinstance(value, str) for value in pins.values()), 'all five independent hashes required'); prepare(pins)
|
||||
else:
|
||||
require(args.id is not None, 'explicit retained case required'); run(args.id, args.action)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
+63
-2
@@ -53,17 +53,78 @@ Zugänge und private Rohbelege bleiben gitignoriert.
|
||||
|
||||
## Aktuelle Windowsfortsetzung
|
||||
|
||||
Gemeinsame passive Komponentenwartung nach dokumentiertem ersten APIfehler
|
||||
abgeschlossen, Originalfall `6d2df065…` und separate Recovery `595dd1da…`.
|
||||
ActualAgent `89004ad3…` LocalService/Auto PID8108; Helper `e6aacbdd…`
|
||||
SYSTEM/Manual PID2620; Policy `007adf5f…`, Pin `126670bc…`. Alle vier Dateien
|
||||
mit expliziten Nativebackups und Datei-ID-/ACL-/Frozenprüfungen ersetzt,
|
||||
danach beide eigenen Dienste jeweils einmal gestartet. Zwei frische WSS-
|
||||
Heartbeats, konkretes Inventar-ACK, Tenantverweigerung und Erhaltung bestanden.
|
||||
Runtime-/Komponentenindex per CAS veröffentlicht; Ursprung/Fehler/Backups erhalten.
|
||||
Abschluss `ac00411f…`, Recoveryacceptance `5ad5925c…`. Keine Jobs/Bindings,
|
||||
Clockfalse, Wirkungen/Rebootfalse, Intentablage weiter0B. Die ursprünglichen
|
||||
Stoppedabschnitte unten sind jetzt historische Zwischenstände.
|
||||
|
||||
Positive Pipeabnahme weiterhin **fehlgeschlagen**: tatsächlicher neuer Agent
|
||||
8108 meldet `client_read_reply`/`HELPER_PIPE_IO`/Win32233; privater Helper-
|
||||
Diagnosebeleg fehlt. Das grenzt den Clientpfad ein, beweist aber keine konkrete
|
||||
Serverursache. [Wartung/Recovery](windows-system-delegation-upgrade.md).
|
||||
|
||||
Clockkandidat nach W32Time-Start tatsächlich nativ ausgeführt, Fall `e1f3edbb…`:
|
||||
LocalService bestätigt, beide ALPC-Proben1753, kein Endpunkteintrag; beide
|
||||
Negativkontrollen ebenfalls1753, kein Identitätsnachweis. Named-Pipe-Diagnose1783
|
||||
ohne Status, Ursache noch unbewiesen. Originalbericht separat identisch gelesen,
|
||||
eigener temporärer Dienst entfernt, Zentralstände/Flags erhalten. Clockabnahme
|
||||
**nicht bestanden**, Gatefalse und keine Jobs. Microsoft spezifiziert für
|
||||
MS-W32T Named Pipes, keinen zugesicherten ALPC-Endpunkt. [Native Details](windows-clock-readiness.md).
|
||||
|
||||
Vorhandenes W32Time ausdrücklich autorisiert einmal gestartet, nativer Fall
|
||||
`c3552c3f…`: Running und unveränderte RMM-PIDs5140/6240, Konfiguration,
|
||||
PKI-Metadaten und Dienstdefinition bestätigt. Getrennter Readback identisch,
|
||||
Zentralstände0/0/0/0 und30/30/26/0 sowie geschlossene Flags erhalten. Kein
|
||||
Uhrqualifikations- oder Rebootbeleg; `ADAPTER_QUALIFIED=false`. [Startnachweis](windows-time-service-start.md).
|
||||
|
||||
Separater M3-Branch `codex/windows-eventlog`, Commit `eb38b4b`: fester
|
||||
Application-/Fixtureprovider, begrenzter authentisierter Worker und sichtbarer
|
||||
hashgebundener Plan implementiert und unabhängig geprüft. Lokal238Rust,
|
||||
isolierterPG-Fall und38Webtests/Build/Clippy bestanden; anschließend nativ
|
||||
Cloud-Linux24→Windows23 ohne Skips, Manifest `ed1371e9…`, Fälle `6f9bdfb7…`
|
||||
und `ccb258a7…`. Quellen und beide Abnahmeschritte jeweils gepusht. Dies sind
|
||||
Vertragsunits, keine tatsächliche LocalService-Eventlog-Abfrage oder Jobwirkung.
|
||||
Keine Capability aktiviert, keine Runtime ersetzt. [Quellen und genaue Grenzen](https://gitea.incoso.eu/kevin_janssen/rust-discovery/src/branch/codex/windows-eventlog/docs/windows-eventlog-source.md).
|
||||
|
||||
Separater Profilbranch `codex/windows-powershell-profile`, Commit `207b91f`:
|
||||
RemoteSigned als optionales festes Aktions-/Variantenfeld implementiert, alte
|
||||
Bytes erhalten, UI-Planansichten streng gebunden. Lokal Rust-/Server-/35Web-
|
||||
Prüfungen bestanden; danach nativ Cloud-Linux23 ohne Skips, Fall `f463acc9…`,
|
||||
Manifest `26247a3a…`. Anschließend nativ Windows22 ohne Skips bestanden,
|
||||
Fall `9abd3e0d…`, Proof `47cee8c9…`, an denselben Linuxbeleg gebunden. Keine
|
||||
Profilcapability veröffentlicht und kein PowerShelljob gestartet. Der
|
||||
Hauptcheckout bleibt für die Komponentenwartung unverändert. Quellen/Nachweise:
|
||||
[Profilbranch](https://gitea.incoso.eu/kevin_janssen/rust-discovery/src/branch/codex/windows-powershell-profile).
|
||||
Ein separat tatsächlich bestätigter Schemars-Nullable-Metadatenunterschied
|
||||
betrifft keine Berechtigung; sein enger Attributfix wird im isolierten folgenden
|
||||
M3-Schnitt mitgeführt. Der ursprüngliche Nativebeleg wird nicht umgeschrieben.
|
||||
|
||||
Neue Userentscheidungen1.18: RemoteSigned nur für den einzelnen zuvor in der
|
||||
WebUI genehmigten PowerShell5.1-Jobprozess, vor Genehmigung sichtbar und fest
|
||||
gebunden; bestehendes W32Time gezielt starten ohne Startart-/NTP-/ACLänderung;
|
||||
manueller VM-Konsolenneustart erst nach konkreter Zeitabstimmung. Keine Remote-
|
||||
oder RMM-Rebootfreigabe. Umsetzung des optionalen Skriptprofils noch offen.
|
||||
oder RMM-Rebootfreigabe. Profilquelle und Vertragsunits im oben genannten
|
||||
isolierten Branch vorhanden; tatsächlicher genehmigter Job weiterhin offen.
|
||||
[Begrenzter Vertrag](windows-powershell-policy.md).
|
||||
|
||||
Gemeinsamer Upgradefall `6d2df065…` bisher vor dem Server-Beforecheckpoint
|
||||
abgebrochen, kein Enter-/Stop-/Swap-/Startintent. Bestehender RMM-Agent meldet
|
||||
weiter Heartbeats; Reverse-Tunnellistener vorhanden, aber TCP-Weiterleitung
|
||||
liefert derzeit kein SSH-Banner. Kein Upgradefortschritt daraus ableiten.
|
||||
lieferte zunächst kein SSH-Banner. Ein eng begrenzter Devtransport-Reset im
|
||||
Fall `eed7dad0…` beendete genau den separat identifizierten Tunnel-Sessionchild
|
||||
über sein gepinntes Prozesshandle; kein SSH-Master-/UID-Reset. Der bestehende
|
||||
Windowsloop stellte den Listener neu her; Anmeldung mit unverändert gepinntem
|
||||
Windows-Hostschlüssel und lesender Nachbeleg bestanden. Agent5140 und Helper6240
|
||||
laufen unverändert, W32Time weiterhin gestoppt. Ursache der ursprünglichen
|
||||
Bannerblockade unbewiesen; keine neue Schlüssel-/Port-/Expiryfreigabe und kein
|
||||
VM-Neustart. Kein Upgradefortschritt daraus ableiten.
|
||||
Konkrete Zeitabstimmung für den bereits zugesagten manuellen Konsolenneustart
|
||||
wurde angefragt; bis zur Antwort keine Ziel-Neustartaktion und keine Annahme
|
||||
eines erfolgten Neustarts. Aktuelle Artefakte weiterhin2bee/921c.
|
||||
|
||||
+2
-1
@@ -1,6 +1,6 @@
|
||||
# Entdeckungen und Aufgaben nach dem Linux-MVP
|
||||
|
||||
Stand 2026-11-13. Die begrenzten Linux-[M0–M5-Gates](mvp-gates.md) sind
|
||||
Stand 2026-11-14. Die begrenzten Linux-[M0–M5-Gates](mvp-gates.md) sind
|
||||
abgeschlossen. Windows wird auf eigenen Auftrag fortgesetzt; seine aktuellen
|
||||
Voraussetzungen stehen in [Windows-Gates](windows-gates.md) und
|
||||
[Jobgrenze](windows-job-boundary.md). Diese Liste erweitert den Auftrag nicht.
|
||||
@@ -10,6 +10,7 @@ Pfad bleiben dort sofort relevant.
|
||||
|
||||
| Entdeckung / späteres Thema | Tatsächlicher heutiger Stand | Spätere Aufgabe |
|
||||
| --- | --- | --- |
|
||||
| Dev-Reversetunnel ohne Zielbanner | Windows-RMM-Heartbeats liefen tatsächlich weiter, während Serverlistener/TCP-Verbindung auf127.0.0.1:22240 vorhanden waren, aber kein SSH-Banner durchkam. Der Bootstraploop überwacht nur das äußere ssh.exe und verbindet nach dessen Ende neu; der Task hat kein RestartOnFailure. Konkrete Ursache des blockierten SSH-Ziels unbewiesen. Keine SSH-/Hostkey-/Expirygrenze gelockert. | Nach dem MVP begrenzte Transport-/Workerdiagnose verbessern. Keine automatische Schlüsselverlängerung, öffentliche Windowsportfreigabe oder pauschalen sshd-/UID-Resets. Der aktuelle manuelle Konsolenneustart bleibt ausdrücklich zeitlich abzustimmen und ist kein RMM-Rebootnachweis. |
|
||||
| Legacy-Syncflag ohne signierten Sync | Bei Clients ohne `rmm.sync.v1` setzt der bisherige Hello-Kompatibilitätspfad `sync_ready=true`. Auf dem passiven Windowsclient nach Serverneustart tatsächlich beobachtet; weiterhin keine Jobcapabilities und kein signierter Syncnachweis. | In Status/API `sync_required`, Unterstützung und tatsächlichen signierten Checkpoint trennen. Das Legacyflag niemals als Windows-Jobabnahme verwenden. |
|
||||
| Nichtstart zwischen Grant und Helperdelegation | Beim Windows-SCM-Source-Review2026-11-14 wurde eine lokale Consumption ohne Helperzeile als strenger Sync-Fault erkannt. Die Linux-Root-Quelle besitzt strukturell denselben frühen Pfad; dieser konkrete Linuxfall wurde noch nicht nativ reproduziert. Aktuelle Rootscope bleibt geschlossen. | Vor Wiederöffnung für weitere Rootjobs den engen Vor-Delegation-Cancel-/Fencefall reproduzieren und analog gebunden lösen; keine Missing-Row-Guardlockerung oder Historienänderung. Der aktuelle Windowsfixvertrag steht in Spec1.17/[Abandonvertrag](windows-system-abandon.md). Historische Linux-Abnahmen werden dadurch nicht rückwirkend als dieser Nachweis ausgegeben. |
|
||||
| Rohoutput und kanonischer Sync-Outcome | Das vorhandene Sync-Outcome-Limit von 512 KiB betrifft JSON; Zahlenarrays können den erlaubten Rohoutput deutlich vergrößern. Kleine bisherige MVP-Fixturen sind davon nicht betroffen. | Vor breiter Freigabe großer Ausgaben effektive Adapterlimits, Codec-/Kontrollnachrichtenbudget und gegebenenfalls Artefaktreferenzen konsistent qualifizieren. Keinen erfolglosen Sync als übernommen ausgeben. |
|
||||
|
||||
@@ -262,3 +262,47 @@ SDK-Struktur bleibt aufx64 begrenzt und wird beim MSVC-Build zusätzlich direkt
|
||||
gegen die native SDK-Deklaration geprüft. Dies ersetzt weder einen nativen
|
||||
MSVC- noch einen tatsächlichen W32Time-Nachweis. W32Time ist weiterhin gestoppt;
|
||||
Produktgate unverändert `ADAPTER_QUALIFIED=false`.
|
||||
|
||||
## Autorisierter Dienststart — noch keine Clockabnahme
|
||||
|
||||
Nach ausdrücklicher Userentscheidung1.18 wurde das vorhandene W32Time im Fall
|
||||
`c3552c3f…` genau einmal gestartet und separat lesend als Running bestätigt.
|
||||
RMM-Agent/Helper samt ursprünglichen PIDs, Definitionen und PKI-Metadaten,
|
||||
ausgewählte NTP-/Policywerte und zentrale Jobzählungen/Flags sind erhalten.
|
||||
Keine Startart-/NTP-/ACLänderung oder Resynchronisierung angefordert; normale
|
||||
Synchronisierung durch den Dienst ist erlaubt. [Genauer Beleg](windows-time-service-start.md).
|
||||
|
||||
Ein neuer GNU-Diagnosebuild `a817cf61…`, EXE `f5003f96…`, wurde lokal mit
|
||||
identischen Quellbindungen vor/nach gebaut. Sein tatsächlicher ALPC-/Status-/
|
||||
Identitätskontrolllauf ist inzwischen ausgeführt; Ergebnis folgt unten. Der
|
||||
Dienststart allein öffnet weder Clock- noch Jobgate.
|
||||
|
||||
## Tatsächlicher Kandidatenlauf nach Dienststart: nicht qualifiziert
|
||||
|
||||
Fall `e1f3edbb-5a2f-4d82-a449-0432913c6bd7`, EXE `f5003f96…`, nativ als
|
||||
separater LocalService-Dienst: TokenSID19, kein Administratormitglied/SYSTEM,
|
||||
zwei Statusproben und beide Identitätskontrollen ausgeführt. ALPC meldet jeweils
|
||||
`1753`/`CLOCK_UNSUPPORTED`; die Endpunktenumeration meldet Erfolg mit0Einträgen.
|
||||
Beide Negativkontrollen ebenfalls1753, **kein Ablehnungs-/Identitätsbeweis**.
|
||||
Die zusätzliche Named-Pipe-Diagnose meldet1783 ohne Status. Noch unbewiesen,
|
||||
ob dessen Quelle RPC/NDR oder der eigene strikte Strukturguard ist. Keine
|
||||
stillschweigende Status-/Authentisierungs-/Transportlockerung.
|
||||
|
||||
Der eigene temporäre Dienst wurde nach Stopped entfernt; der normale Agent und
|
||||
SYSTEM-Helper wurden nicht gestoppt oder verändert. Separater Readback bestätigt
|
||||
identischen Originalbericht. Zentralstände0/0/0/0 und30/30/26/0 sowie geschlossene
|
||||
Flags/Rootpolicyhash vor/nach unverändert. Privater Fallabschluss
|
||||
`assessment.json`, SHA256
|
||||
`d80e5f39cbd6d332deb12bf4f21e1372c88025b551db4ef33a190e3f82b3300a`.
|
||||
Native Ausführung belegt, **Clockabnahme fehlgeschlagen**; Produktionsgatefalse,
|
||||
keine Windowsjobs oder Capabilities aktiviert.
|
||||
|
||||
Nach dem Lauf erneut gegen Microsoft geprüft: MS-W32T2.1 verlangt Named-Pipe-
|
||||
Transport und nennt den authentisierten Endpunkt `W32TIME_ALT`; ein ALPC-
|
||||
Endpunkt ist damit kein zugesicherter Plattformvertrag. Der bisherige ALPC-
|
||||
Kandidat war ein zu qualifizierender Zusatz, keine native Windowsgarantie.
|
||||
[Transportvertrag](https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-w32t/e0803f6b-e175-4b87-ba63-bbcf51175655),
|
||||
[vollständiges IDL](https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-w32t/5793e908-22ef-4cea-962f-fca8a72c485a).
|
||||
Die konkrete1783-Ursache wird separat rein diagnostisch eingegrenzt; eine
|
||||
erfolgreiche unqualifizierte Pipeabfrage würde die Clockgrenze weiterhin nicht
|
||||
öffnen. Bereits vorhandene Originalfehler bleiben unverändert erhalten.
|
||||
|
||||
@@ -0,0 +1,262 @@
|
||||
# Windows-Entwicklungszugang: Ablauf und vorbereitete Konsolenwiederherstellung
|
||||
|
||||
Stand: 2026-11-14. Der bisherige SSH-Entwicklungszugang lief am
|
||||
**2026-11-14T12:55:31.254999+00:00** ab. Die vorher vorbereitete automatische
|
||||
Verlängerung wurde **nicht betreten**: kein Server- oder Windows-Enter, keine
|
||||
Ablaufzeitänderung und kein angelegter Renewalworker. Die drei fehlgeschlagenen
|
||||
Vorbereitungen und ihre Quellen bleiben historische Belege.
|
||||
|
||||
**Aktueller Stand:** Die spätere User-Konsolenwiederherstellung wurde
|
||||
erfolgreich ausgeführt; Root bestätigte anschließend die tatsächliche Rückkehr
|
||||
des gepinnten SSH-Zugangs. Auch der getrennte vollständige Key-/Task-
|
||||
Erhaltungsabgleich und der lokale Accessmetadaten-CAS sind inzwischen bestanden.
|
||||
Einzelheiten stehen im neuen Abschlussabschnitt dieser Verlaufserfassung.
|
||||
|
||||
Diese Entwicklungshilfe ist SSH-Bootstrap, keine RMM-Aktion und kein Ersatz für
|
||||
Geräte-mTLS, Tenantgrenzen, TrustedClock, signierte Grants oder die
|
||||
WebUI-Genehmigung. Das Notebook bleibt ausschließlich Entwicklungsrechner.
|
||||
|
||||
## Tatsächliche abgebrochene Vorbereitungen
|
||||
|
||||
| Fall unter `devstate/windows-client/dev-access-renewal/` | Tatsächliches Ergebnis |
|
||||
| --- | --- |
|
||||
| `45626a0c-edc4-4f35-9f36-921692bccbc1` | Rein lesende Windows-Vorbereitung verweigerte `Transport owner` vor dem Serveraufruf. Die zwei öffentlichen `.pub`-Dateien gehörten dem tatsächlichen lokalen Builtin-Administrator mit SID-Endung `-500`; deren bestehende öffentlichen Leserechte waren für die ursprüngliche private Dateiprüfung zu weit. Nur die separate öffentliche Metadatenprüfung wurde später präzisiert; keine ACL-Reparatur. |
|
||||
| `d40c06a4-d6d3-4dc0-9ef6-b1ef1197bcc9` | Rein lesende Windows-Vorbereitung verweigerte `VariableNotWritable`: die Hilfsvariable `$host` kollidierte mit PowerShells schreibgeschütztem `$Host`. Die Quelle wurde anschließend auf `$hostPublic` korrigiert. Keine Server- oder Windowsmutation. |
|
||||
| `6988fd11-0e0a-4fd7-878d-96b130d83aee` | Der lokale Datums-/Fristguard verweigerte nach Ablauf der alten Frist, noch vor `prepare-intent.json`. Dies war kein weiterer ausgeführter Windows-Readonly-Test. Der leere lokale Fall bleibt erhalten. |
|
||||
|
||||
Die ersten beiden Fälle enthalten nur Vorbereitungsintent und Controllerkopie;
|
||||
keiner enthält einen Server-/Windows-Enterintent. Root bestätigte zusätzlich,
|
||||
dass kein Renewal-Enter und kein Worker ausgeführt wurden. Ablauf und Fehler
|
||||
werden nicht nachträglich als erfolgreiche Verlängerung ausgegeben.
|
||||
|
||||
## Getrennte Wiederherstellung des bereits abgelaufenen Zugangs
|
||||
|
||||
Die neue Quelle
|
||||
[`console_access_recovery.py`](../deploy/windows/console_access_recovery.py)
|
||||
hat SHA-256
|
||||
`703fb5e4ae04d8555bad858c5d7b2ac4880e06d6fa951010acd43f7201a58053`.
|
||||
Sie trennt den Server-CAS von der erst anschließend durch den User in der
|
||||
Windows-Administratorkonsole auszuführenden Phase. Die frühere
|
||||
[`dev_access_renewal.py`](../deploy/windows/dev_access_renewal.py) wird für den
|
||||
abgelaufenen Lease nicht umgedeutet oder erneut gestartet.
|
||||
|
||||
Root führte ausschließlich den Serverteil im neuen Fall
|
||||
`4b6506a7-6c3e-4cca-a497-618fa8666300` aus. Dessen `server-entered.json`
|
||||
meldet `completed=true`; ein getrennt gespeicherter lesender Readback bestätigt
|
||||
dieselbe neue Autorisierungsdatei und Frist:
|
||||
|
||||
| Bindung | Tatsächlicher Beleg |
|
||||
| --- | --- |
|
||||
| Neue feste UTC-Frist | `2026-11-15T13:05:58+00:00` |
|
||||
| `authorized_keys` nach CAS | `fef4db300dd39fba9b52428817f453451c251c7768dd2fb6a76b39dd110dbbf2` |
|
||||
| Unverändertes SSH-Profil | `932adc2ad3e88c3a47054c3d09e44024f21918cf144f0bb349bd8763e844e482` |
|
||||
| Unveränderte effektive SSH-Konfiguration | `3a345912fdd4bb9bb29628d670a8bdbdfbbc22b3e308ab56fb3bafb7bc15533a` |
|
||||
| Server-Enterbeleg | SHA `2185a88fc32db72119a584d84a46fb25cfca5f32f6e0c4ee5b7cf0728a361317` |
|
||||
| Getrennter Readback | SHA `f6e3f69a6cd4f006d00c90cadd8bfd47f94e954f1297bea5f6eecc4fd27d3787` |
|
||||
|
||||
Der Serverteil ersetzte ausschließlich den Ablaufwert des gleichen bestehenden
|
||||
restriktiven Tunnelkeys. Keybytes und Optionen, Loopbacklistener
|
||||
`127.0.0.1:22240`, SSH-Profil, Serverhostpin und der Account
|
||||
`rmm-win-tunnel` mit Shell `/usr/sbin/nologin` blieben gebunden. Historische
|
||||
`prepared.json`/`registered.json` wurden nicht überschrieben. Dieser CAS
|
||||
veränderte weder einen Downloadlease noch die RMM-Konfiguration.
|
||||
|
||||
## Öffentliches Paket und noch offene Userphase
|
||||
|
||||
Unter dem privaten Consolefall liegt das **inzwischen zurückgezogene,
|
||||
historisch erhaltene** öffentliche Paket mit genau
|
||||
`Recover-ExistingDevAccess.ps1`, `public-recovery.json` und `README.txt`.
|
||||
Es enthält öffentliche Pins und feste Parameter, keine privaten Schlüssel oder
|
||||
Tokens. Die Paketdateien sind zusätzlich im unveränderlichen Intent gebunden.
|
||||
|
||||
| Datei | SHA-256 |
|
||||
| --- | --- |
|
||||
| `windows-dev-access-recovery.zip` | `7bf4f7bb8336fb50852f72eec2f3e370e96cb7009b14ee15aa7232c025a38ed7` |
|
||||
| `Recover-ExistingDevAccess.ps1` | `564da57d70ef06df7bd9adc37565b7e28ef446a6c69b984711c5b77b28441e8a` |
|
||||
| Consoleintent | `cd827d4056fb0045f23bff1fd9bd21b6137b53f063fe8215ad0945c2013cc44a` |
|
||||
|
||||
Vor der Userausführung fand Root im Konsolenguard eine unbelegte
|
||||
Ganzsekundenannahme für den alten `AccountExpires`-Wert. Der feste Wert
|
||||
`134391345310000000` ließ den Bruchteil `.254999` der ursprünglichen
|
||||
Konfigurationszeit weg. Ein lokaler .NET-Roundtrip derselben vollständigen
|
||||
UTC-Zeit ergibt `134391345312549990`. Dieser lokale Roundtrip allein war ein
|
||||
**abgeleiteter Sollwert**, noch kein gemessener Windows-VM-Accountwert. Der
|
||||
spätere tatsächliche Userreadback ist unten getrennt dokumentiert. Das alte Paket wird deshalb nicht zur
|
||||
Ausführung weitergegeben; sein gültiger getrennter Server-CAS bleibt erhalten.
|
||||
|
||||
Die kleine neue Quelle
|
||||
[`console_access_precision.py`](../deploy/windows/console_access_precision.py)
|
||||
mit SHA
|
||||
`8b4d14edf0794c4ef662d7587b4538f8e7aebc06c11db76c3cafc2c24c11a37b`
|
||||
erzeugte den neuen lokalen Consolefall
|
||||
`5c96d3d8-1657-40c8-a6ec-c00b63a98210`. Sie bindet den ursprünglichen
|
||||
Serverintent, Enterbeleg und getrennten Readback des Falls `4b6506…` sowie
|
||||
sämtliche alten Paketdateihashes. Es gibt weder einen Serveraufruf noch eine
|
||||
erneute Fristverlängerung: `2026-11-15T13:05:58+00:00` bleibt unverändert.
|
||||
|
||||
Der neue Guard berechnet genau einen erwarteten 64-Bit-Wert über
|
||||
`[DateTimeOffset]::Parse($cfg.expires_at).UtcDateTime.ToFileTimeUtc()` aus der
|
||||
zuvor anhand der Originalbytes und der exakten alten Zeit geprüften Config.
|
||||
Keine Rundung, Toleranz oder alternative Zeit wird akzeptiert. UUID und
|
||||
Provenienzbeleg sind neu; die drei Mutationsschritte ab `File.Replace` bis
|
||||
zum Ende sind gegenüber dem alten Paket bytegleich. Falls ein früheres Paket
|
||||
entgegen dem bisherigen Kontrollstand bereits erfolgreich ausgeführt wurde,
|
||||
muss der alte Config-Hashguard verweigern. Dann nur lesen und durch Root
|
||||
abgleichen, kein neuer Versuch.
|
||||
|
||||
| Neues Korrekturartefakt | SHA-256 |
|
||||
| --- | --- |
|
||||
| ZIP im Fall `5c96d3d8…` | `dbcd5ca863c0b09f89b67eb10eeaeaf89b941bbc5840079f1bb0c36dc6ff3b3e` |
|
||||
| Neues `Recover-ExistingDevAccess.ps1` | `4977665fb092723998473f1c4be6685b1d93975176f8957bc3287d7e2f61cb69` |
|
||||
| Neuer unveränderlicher Intent | `eae7995b5735bf1e8f0fafc0ae6ccf6bdd4576566663c1256a511f6c3408e32e` |
|
||||
|
||||
Die Userphase mit dem Konsolenskript des Falls `5c96…` wurde inzwischen begonnen,
|
||||
scheiterte aber vor jeder Wirkung an `Get-History / IdCannotConvert`: PowerShells
|
||||
standardmäßiger Alias `h` wird auch unter `-NoProfile` vor der Funktion `H`
|
||||
aufgelöst. Der Fehler trat im ersten Case-/Configguard vor `New-Item` auf.
|
||||
Es wurde damit keine Konfigurations-/Accountablaufzeit geändert und kein
|
||||
Tunneltask gestartet. Die unveränderte Case-Abwesenheitsprüfung bleibt für die
|
||||
erste tatsächlich noch unerreichte Wirkung verbindlich.
|
||||
|
||||
Die separate lokale Quelle
|
||||
[`console_access_hash_command.py`](../deploy/windows/console_access_hash_command.py)
|
||||
hat SHA `b682ced57bf7ac71c0b1ba67eb5a51a20dde814fe361e1ae2cc17872147444ad`.
|
||||
Sie erzeugt `Recover-ExistingDevAccess-HashFix.ps1` mit SHA
|
||||
`d366ae1705dac3252726dedf369c04462e42534ddcf6e15dc27bba8583427d2c`.
|
||||
Ausschließlich die eine Funktionsdefinition und alle fünf Aufrufe heißen nun
|
||||
`Get-RmmRecoveryFileSha256`; eine inverse Ersetzung ergibt exakt die alten
|
||||
PS1-Bytes. Alle übrigen Guards, Pins, Fristen, die gleiche Console-UUID und
|
||||
Mutationsschritte bleiben erhalten. Kein Alias wird entfernt oder geändert.
|
||||
|
||||
Der kleine Userpatch `Create-VerifiedHashFix.ps1` mit SHA
|
||||
`385a388476cef0c85f02bca236ade48f28a041476330d3e309ab1ca2f22bb9f5`
|
||||
prüft zuerst den ursprünglichen PS1-Hash `4977665f…`, erzeugt ausschließlich
|
||||
eine zuvor fehlende neue Datei mit UTF-8 ohne BOM, verlangt deren vollständigen
|
||||
Hash `d366ae17…` und startet erst dann den separaten Bootstrapprozess mit
|
||||
`-NoProfile -ExecutionPolicy RemoteSigned`. Kein neuer Download ist für diese
|
||||
lokale Korrektur erforderlich. Bereits vorhandene Korrekturdateien werden
|
||||
nicht überschrieben und eine unklare frühere Wirkung wird nicht wiederholt.
|
||||
|
||||
ASTs, vollständige Command-AST-Ersetzung sowie ein tatsächlicher lokaler
|
||||
Hashfunktionsaufruf bei unverändert vorhandenem Alias `h=Get-History` bestanden;
|
||||
der unabhängige Review bestätigte die reine Namensänderung. Das sind lokale
|
||||
PowerShellprüfungen, kein weiterer Windows-VM-Erfolgsnachweis. Alte Quellen,
|
||||
ZIPs und Fehlerbelege bleiben unverändert.
|
||||
|
||||
Die anschließende tatsächliche Userausführung des HashFix-Skripts `d366ae17…`
|
||||
verweigerte im kombinierten anfänglichen Case-/Config-/Bootstrapguard weiterhin
|
||||
vor Wirkung. Root ließ zunächst ausschließlich fünf Werte lesend ausgeben.
|
||||
Der Userreadback ergab:
|
||||
|
||||
| Tatsächlicher Konsolenwert | Ergebnis |
|
||||
| --- | --- |
|
||||
| Recoverycase vorhanden | `false` |
|
||||
| Config-SHA | `4ad28ec55027718a4e384c79ff7cc15ec9c798411a991a5d479e960310ed6823` |
|
||||
| Bootstrap-SHA | `332ceeedf49f597eac353e0ef1f6e614c85cef20a5a20cce68d947085aa9d50f` |
|
||||
| Configablaufzeit | `2026-11-14T12:55:31.254999+00:00` |
|
||||
| Tatsächliches Account-FILETIME | `134391345312549990` |
|
||||
|
||||
Damit ist dieser Guardfehler konkret erklärt: die Recoveryquelle erwartete
|
||||
den späteren Repositoryhash `9e992602…`, obwohl die VM exakt das ursprünglich
|
||||
veröffentlichte Bootstrap mit Hash `332ceeed…` behielt. Das erhaltene Original-ZIP
|
||||
`cba15946…` enthält genau diese Datei und die Config `4ad28ec5…`; das ebenfalls
|
||||
veröffentlichte Reparaturpaket `2558448b…` bindet denselben Bootstraphash als
|
||||
Voraussetzung und ersetzt Bootstrap/Config nicht. Der Maintainerteil beider
|
||||
Bootstrapquellen ist bytegleich. Es wird somit keine unbekannte Datei anhand
|
||||
eines beliebigen neuen Readbacks übernommen.
|
||||
|
||||
Die getrennte lokale Quelle
|
||||
[`console_access_original_bootstrap.py`](../deploy/windows/console_access_original_bootstrap.py)
|
||||
mit SHA `c0816055407c17af4c0bf4b5bd5ce3055e5a9d44fe7f2334f5aa7913520478c6`
|
||||
bindet den tatsächlichen Userreadback und beide publizierten Originalpakete.
|
||||
Sie erzeugt `Recover-ExistingDevAccess-OriginalBootstrap.ps1` mit SHA
|
||||
`aba0a5a4152347e639266e95a05eae4343a99be9070a94fa4fc6501bfc3283d2`.
|
||||
Ausschließlich die eine Bootstrap-Sollhashkonstante wird von `9e992602…` auf
|
||||
das bestätigte Original `332ceeed…` berichtigt. Alle anderen Bytes des
|
||||
`d366ae17…`-Skripts, einschließlich gleicher Case-Abwesenheit, voller UTC-
|
||||
Präzision, Aliasfix, Fristen und Wirkungsschritte, bleiben identisch.
|
||||
|
||||
Der Userpatch `Create-VerifiedOriginalBootstrapFix.ps1` hat SHA
|
||||
`64f1d62ea3a87d4db7103ca01f7d735689caf54a7cc4b2458908956624062549`.
|
||||
Er verlangt den vollständigen Eingabehash `d366ae17…`, schreibt nur eine
|
||||
zuvor fehlende neue Datei, prüft deren vollständigen Hash `aba0a5a4…` und
|
||||
startet erst danach den separaten Bootstrapprozess. Lokaler Python-/AST-Test,
|
||||
ein tatsächlicher lokaler PowerShelllauf des Patchpräfixes ohne Kindstart und
|
||||
der unabhängige byteweise Review bestanden. Dadurch wird die Userausführung
|
||||
der korrigierten Wirkung noch nicht vorweggenommen. Kein Serveraufruf und keine
|
||||
weitere Serverfriständerung wurden durch diese lokale Korrektur ausgeführt.
|
||||
|
||||
Eine erfolgreiche Windows-Konsolenphase und Tunnelwiederkehr sind **noch nicht
|
||||
nachgewiesen**. Die korrigierte Strecke prüft die alten
|
||||
Config-/Bootstrapbytes und öffentlichen Pins, den bestehenden Account sowie den
|
||||
unveränderten SYSTEM-Tunneltask. Erst bei `Ready` und ohne verbliebenen
|
||||
Maintainer/SSH-Kindprozess darf sie die vorhandene Konfigurations- und
|
||||
Accountablaufzeit erneuern und den Originaltask mit dauerhaftem Startintent
|
||||
**einmal** starten. Private Keydateien werden nur über Metadaten beobachtet,
|
||||
nicht inhaltlich gelesen. Keine Installation, ACL-Reparatur, neue Schlüssel,
|
||||
zusätzlichen SSH-Rechte, Prozesskills, Reboots oder RMM-Wirkungen.
|
||||
|
||||
Die README verlangt den unabhängig mitgeteilten Downloadhash und den festen
|
||||
PS1-Hash. Ein etwaiges `Unblock-File` betrifft nur diese exakt geprüfte
|
||||
Download-Datei; `RemoteSigned` nur den separaten Bootstrapprozess. Eine
|
||||
verweigernde GPO oder ein fehlgeschlagener Guard wird nicht umgangen. Ein
|
||||
bereits vorhandener Recoveryfall bleibt zur lesenden Inspektion erhalten.
|
||||
|
||||
Eine gesonderte, auf 45 Minuten begrenzte Veröffentlichung über den vorhandenen
|
||||
öffentlichen TLS-Bootstrapdienst wird durch Root separat behandelt. Dieser
|
||||
Server-CAS und diese Dokumentation belegen noch keine Downloadveröffentlichung.
|
||||
Nach der Userausführung bleiben tatsächliche Tunnelwiederkehr, ursprüngliche
|
||||
SSH-Hostidentität, erhaltene Schlüssel/Taskdefinition und die lokale
|
||||
Accessmetadatenfortschreibung durch Root zu prüfen. **Neuer Windowszugriff ist
|
||||
bis dahin nicht nachgewiesen.**
|
||||
|
||||
Lokale Python-/AST- und Paketprüfungen sowie unabhängige Source-Reviews bestanden.
|
||||
Der lokale Paketfixture verwendete einen gemockten Serveraufruf und ist kein
|
||||
zusätzlicher nativer Recoverybeleg. Kein RMM-Job, keine Capability oder
|
||||
Clockbereitschaft folgt aus der Zugangswiederherstellung.
|
||||
|
||||
## Update: User-Konsolenerfolg und tatsächlicher gepinnter SSH-Kontakt
|
||||
|
||||
Der User meldete die erfolgreiche Ausführung der korrigierten Konsolenstrecke
|
||||
`Recover-ExistingDevAccess-OriginalBootstrap.ps1` mit Hash `aba0a5a4…`.
|
||||
Root erhielt danach über den bereits gepinnten SSH-Zugang tatsächlich eine
|
||||
getrennte rein lesende Antwort. Der lokale Verifikationsfall ist
|
||||
`fc7a6ad5-5ec5-4280-b629-851aad2529b2`; sein `readback.json` hat SHA
|
||||
`bb0e2b4747068433bcb7c950743ef56007f22206ca5d4b458f6b8221a4a031e2`.
|
||||
Der Beleg nennt weiterhin den ursprünglichen Consolefall
|
||||
`5c96d3d8-1657-40c8-a6ec-c00b63a98210`, `read_only=true`,
|
||||
`completed=true` und `no_jobs=true`.
|
||||
|
||||
| Tatsächlich beobachteter Wert | Ergebnis |
|
||||
| --- | --- |
|
||||
| Configablaufzeit | `2026-11-15T13:05:58+00:00` |
|
||||
| Accountablaufzeit als FILETIME | `134392215580000000` |
|
||||
| Originaler Reverse-Tunneltask | `Running` |
|
||||
| `RmmDiscoveryWindows` | `Running`, PID `3172`, `NT AUTHORITY\LocalService`, Startart `Auto` |
|
||||
| `RmmDiscoverySystemHelper` | `Stopped`, PID `0`, `LocalSystem`, Startart `Manual` |
|
||||
| `W32Time` | `Running`, PID `3488`, `NT AUTHORITY\LocalService`, Startart `Manual` |
|
||||
|
||||
Damit ist die Rückkehr des Entwicklungszugangs belegt. Die früheren Aussagen
|
||||
zur noch offenen Userphase bleiben historische Zwischenstände. Der zusätzliche
|
||||
rein lesende Erhaltungsbeleg desselben Falls (`preservation.json`, SHA256
|
||||
`490e01809ca1e4225f1dbb6a0a4414cf77f7822be31233366480b3a0d4810592`)
|
||||
bestätigt alle sechs festen öffentlichen Dateien samt SHA/SDDL, Metadaten und
|
||||
SDDL der vier privaten SSH-Schlüssel ohne Lesen ihrer Inhalte, den exakten
|
||||
Originaltask-XML-Hash und Runningzustand, Account-SID sowie alle öffentlichen
|
||||
Pins. Danach wurde lokal ausschließlich die Frist im Accessmetadaten-JSON per
|
||||
CAS auf `2026-11-15T13:05:58+00:00` fortgeschrieben. Der SSH-Präfix blieb exakt
|
||||
erhalten; Original und neuer Metadatenbeleg sind privat archiviert. Die alten
|
||||
Fehlerfälle, Pakete und Korrekturquellen bleiben erhalten.
|
||||
|
||||
Der Readback ist kein Paarupgrade-, TrustedClock-, Boot- oder RMM-Jobnachweis.
|
||||
Insbesondere eröffnet `W32Time=Running` keine Clockbereitschaft. Der Helper
|
||||
war tatsächlich noch gestoppt; daraus wird kein authentisierter neuer
|
||||
Agent-/Helper-Pipeaustausch abgeleitet. Root führt die getrennten Pipe-/MIDL-
|
||||
Prüfungen erst anschließend fort.
|
||||
|
||||
Der User hat den nächsten Arbeitsfokus ausdrücklich auf die Skriptkonsole mit
|
||||
vollständigem Shell-/PowerShellinhalt, tatsächlicher WebUI-Plangenehmigung,
|
||||
Ausgabe und expliziten Root-/SYSTEM-Ausführungsrechten gelegt. Paketabnahmen
|
||||
sind nachgeordnet. Der erneuerte SSH-Bootstrapzugang verleiht selbst keine
|
||||
RMM-Ausführungsrechte und ersetzt keine dieser noch separat nachzuweisenden
|
||||
Genehmigungs- und Ausführungsgrenzen.
|
||||
@@ -1,6 +1,6 @@
|
||||
# Windows-Client: Abnahmegates
|
||||
|
||||
Stand 2026-11-14, Spezifikation 1.17. Der Windows-11-x64-Gast ist ein eigenes
|
||||
Stand 2026-11-14, Spezifikation 1.18. Der Windows-11-x64-Gast ist ein eigenes
|
||||
Testgerät. Der Notebook-Host bleibt ausschließlich Entwicklungsrechner;
|
||||
Server ist `discovery.ease-technologies.de`. Das abgeschlossene Linux-MVP
|
||||
bleibt eine eigenständige Abnahme. Dieser Bericht erweitert dessen Umfang nicht.
|
||||
@@ -12,9 +12,10 @@ bleibt eine eigenständige Abnahme. Dieser Bericht erweitert dessen Umfang nicht
|
||||
| HTTPS/Fallback | Explizites HTTPS und automatischer Fallback nach zwei tatsächlichen mTLS-WSS503 unter LocalService nativ bestanden, jeweils mit frischen Heartbeats und Inventar-ACK. Testhooks geschlossen. Anschließend bestehende VM separat dauerhaft auf `auto` gestellt und bevorzugtes WSS erneut mit zwei frischen Heartbeats/ACK geprüft; Identität und ACLs erhalten, 0 Jobs/Grants. | Transportnachweise abgeschlossen; kein automatischer HTTPS→WSS-Switchback nachgewiesen. Installerdefault ebenfalls `auto`, aber keine neue Installationsabnahme. |
|
||||
| TLS-Lifecycle | Falsche CA, falscher Name und abgelaufenes Clientzertifikat mit gültigen Kontrollen nativ als getrennte Admin-TLS-Proben bestanden. Permanente Identität/Dienst unverändert. | Rotation und Widerruf noch gesondert sicher implementieren und prüfen. Permanente Identität nicht widerrufen oder ersetzen. |
|
||||
| Signierter Jobkern | Gemeinsamer Kern zuletzt nativ Linux80→Windows58 qualifiziert. Neuer enger SYSTEM-Delegationsadapter mit dauerhaftem Intent, deny-only Abandon und unabhängigem RawMirror implementiert; native23+7Units bestanden. Bestehender laufender passiver Client bleibt unverändert; neue Artefakte noch nicht installiert. Jobs bleiben deaktiviert. | Tatsächlichen signierten Dienst-Sync, qualifizierte Uhr und vollständige Startgrenze nachweisen. Units ersetzen keinen LocalService-/SYSTEM- oder Jobnachweis; [Quellenstand](windows-system-delegation-source.md). |
|
||||
| PowerShell | Begrenzter5.1-Executor implementiert; exakte Skriptbytes, atomarer Prozessbaum, Rohbytes und Unknown bei unklarer Wirkung. Server/UI unterstützen feste Plattformvarianten. Keine tatsächliche Ausführung, Richtlinie derzeit geerbt. | Ausstehende konkrete Richtlinienentscheidung beachten, Encoding/Prozessgrenzen unter LocalService tatsächlich qualifizieren; ausschließlich vollständiger Antrag und tatsächlicher WebUI-Klick. |
|
||||
| PowerShell | Begrenzter5.1-Executor implementiert; exakte Skriptbytes, atomarer Prozessbaum, Rohbytes und Unknown bei unklarer Wirkung. Separates optionales festes RemoteSigned-Prozessprofil ausdrücklich erlaubt, sichtbar an Plan/Grant gebunden; native Vertragsunits zuerst Linux23, danach Windows22 bestanden, Quellenbranch gepusht. Keine tatsächliche Jobausführung oder Profilcapability. | Profilquelle in die laufende Strecke übernehmen, Encoding/Prozessgrenzen unter LocalService tatsächlich qualifizieren; ausschließlich vollständiger Antrag und tatsächlicher WebUI-Klick. Maschinen-/Gruppenrichtlinien unverändert. |
|
||||
| Privilegierte Aktionen | Eigener SYSTEM-Helper nativ installiert und einmal gestartet, Manual/LocalSystem, leere Aktionsliste und Wirkungen/Reboot gesperrt. Die echte LocalService-Agentprobe scheitert derzeit; kein positiver Peer-/Sync-/Wirkungsnachweis. | Fehler ohne Erweiterung der Sicherheitsgrenze diagnostizieren; gegenseitige SID/PID/Binary-/Dateibindung und unabhängigen Sync nativ prüfen. |
|
||||
| Pakete/Dienste/Logs | Kleines MSI1.0.0 auf der VM erstellt, nur lesend geprüft und nach Download gehasht; keine Installation. Dienst-/Eventlog-/Paketquellen teilweise vorbereitet, keine native Aktionsabnahme. | Unveränderliche Tenantrezepte integrieren; UI-genehmigte MSI-/EXE-Installation/Upgrade/Noop, Dienste und Logs mit unabhängigen Nachbedingungen prüfen. |
|
||||
| Eventlog-Vertrag | Im separaten Branch `codex/windows-eventlog` fester Application-/Fixtureprovider, authentisierter begrenzter Worker und hashgebundene UI implementiert/geprüft. Lokal238Rust/PG1/Web38 bestanden; nativ Linux24→Windows23 Vertragsunits ohne Skips. Keine Live-API-Abfrage, Runtimeinstallation oder Capabilityaktivierung. | Tatsächlichen LocalService-Provider und ausschließlich WebUI-genehmigten Job samt Grenzen/Fehlern auf dem Windowsgast qualifizieren. |
|
||||
| Dauerhafte Jobs/Fehlerfälle | Linuxnachweise vorhanden; sie ersetzen keine nativen Windowsnachweise. | Redelivery/ACK-Verlust, Prozessabbruch, Offline/Ablauf/Entzug und Wiederanlauf am tatsächlichen Windows-Jobpfad prüfen. |
|
||||
| Mischplattform | Windows/Linux sind separat inventarisierbar; noch keine gemischte Skriptabnahme. | AT-15 mit festen Varianten/Zielen, passenden Interpretern und nachvollziehbaren Einzelresultaten. |
|
||||
| Reboot/Installer | Entwicklungsbuild unsigniert, GNU-Crossbuild; kein MSVC-/signierter Installer-/Windows-Rebootnachweis. | Eigene Abnahmen; kein Windows-Reboot ist durch den bereits ausgeführten Linux-Testreboot autorisiert. |
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
# Windows Helper: begrenzte Transportbestätigung
|
||||
|
||||
Dieser Schnitt ist im isolierten Zweig `codex/windows-pipe-drain` implementiert.
|
||||
Eine native Ausführung des neuen Framings und ein Komponentenupgrade sind noch
|
||||
nicht nachgewiesen. Die bestehenden Nachweise des Agenten `89004ad3…` und Helpers
|
||||
`e6aacbdd…` bleiben historische Belege ihres ursprünglichen Framings.
|
||||
|
||||
## Anlass und Beleggrenze
|
||||
|
||||
Beim tatsächlichen Agenten wurde `client_read_reply / HELPER_PIPE_IO / 233`
|
||||
beobachtet; die Helperdiagnose war nicht vorhanden. Der bisherige Dienst rief
|
||||
auch nach erfolgreichem Schreiben der Antwort sofort `DisconnectNamedPipe` auf.
|
||||
Microsoft dokumentiert, dass dabei ungelesene Pipebytes verworfen werden. Das
|
||||
ist ein konkreter möglicher Fehlerpfad, aber kein Nachweis, dass genau dieser
|
||||
Pfad die beobachtete Störung verursacht hat.
|
||||
[DisconnectNamedPipe](https://learn.microsoft.com/en-us/windows/win32/api/namedpipeapi/nf-namedpipeapi-disconnectnamedpipe)
|
||||
|
||||
Eine fehlende Diagnose beweist weder einen erfolgreichen Peercheck noch eine
|
||||
bestimmte Ablehnung: strukturierte `Denied`-Antworten erzeugen keinen privaten
|
||||
Pipefehlerbeleg, Connect-Leerlauf kann ohne Beleg enden, und das begrenzte
|
||||
Diagnoseschreiben selbst kann fehlschlagen. Diese Pfade werden hier nicht
|
||||
umgedeutet oder gelockert.
|
||||
|
||||
## Framing v2 und Reihenfolge
|
||||
|
||||
Agent und Helper verwenden ausschließlich `\\.\pipe\RustDiscovery-System-v2`.
|
||||
Jeder JSON-Frame beginnt mit acht ASCIIbytes `RDPIPC02`, gefolgt von vier Bytes
|
||||
Länge in Big Endian und den bisherigen, maximal 1 MiB großen JSONbytes.
|
||||
V1 und V2 haben unterschiedliche Endpunkte; zusätzlich verweigert der V2-Parser
|
||||
alte oder fremde Framingtags. Es gibt keinen stillen Fallback. Beide EXEs müssen
|
||||
als gemeinsam qualifiziertes, gegenseitig gepinntes Paar bereitgestellt werden.
|
||||
Die JSONschemas von Call/Reply, `helper.system.v1`, Systempolicy-Schema 1 und
|
||||
RMM-Jobbytes ändern sich nicht.
|
||||
|
||||
Nach dem vollständigen Lesen der Antwort prüft der Agent weiterhin den tatsächlichen
|
||||
Helperprozess, Schema, Challenge, Enrollmentbindung, Policyhash, Helperbinaryhash
|
||||
und die Operation/Antwort-Zuordnung. Erst danach schreibt er genau 56 Bytes:
|
||||
`RDPACK02` (8), ursprüngliche UUID-Challenge in UUID-Bytefolge (16), SHA-256 der
|
||||
**exakt empfangenen JSON-Antwortbytes** (32). Es findet keine Re-Serialisierung
|
||||
für diese Prüfsumme statt. Auch eine vollständig geprüfte `Denied`-Antwort wird
|
||||
so transportseitig bestätigt, ohne sie in einen Erfolg umzuwandeln.
|
||||
|
||||
Der Helper prüft denselben bereits authentifizierten Peer vor dem Schreiben und
|
||||
nach dem Lesen der Bestätigung. Schreiben, Empfang und Prüfung der Bestätigung
|
||||
teilen dieselbe bisherige Antwortdeadline von fünf Sekunden; der Client behält
|
||||
seine bisherige Gesamtdeadline. Erst danach trennt die Dienstschleife die Pipe.
|
||||
Fehlende, falsche oder verspätete Bestätigung schließt den bestehenden Syncgate
|
||||
und trennt die Verbindung über den bisherigen Fehlerpfad; statische Diagnosen
|
||||
unterscheiden `server_drain_receipt` und `client_drain_receipt`. Es gibt keinen
|
||||
weiteren Aufruf, Retry oder erneute Ausführung.
|
||||
|
||||
Diese Bestätigung bestätigt nur den Empfang der Antwortbytes. Sie ist kein
|
||||
JobResult-, Journal-, SignedSync-, Grant-, Freigabe- oder Wirkungsbeleg und löscht
|
||||
keinen dauerhaften Zustand. Ein bereits ausgeführter Auftrag wird durch einen
|
||||
fehlenden Transport-ACK nicht zurückgenommen oder wiederholt.
|
||||
|
||||
`FlushFileBuffers` wird nicht verwendet: dieser synchrone Pipeaufruf wartet laut
|
||||
Microsoft bis zum Lesen aller gepufferten Daten und bietet hier keine passende
|
||||
begrenzte Warteoperation.
|
||||
[FlushFileBuffers](https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-flushfilebuffers)
|
||||
|
||||
## Prüfung und verbleibender nativer Nachweis
|
||||
|
||||
Die bestehenden IPC-Codecfälle prüfen zusätzlich fremde/alte Frameversionen,
|
||||
begrenzte Längen sowie manipulierte ACK-Tags, Challenge und Prüfsumme. Eine andere
|
||||
JSON-Bytefolge mit gleichem JSON-Inhalt darf den ursprünglichen Frame nicht
|
||||
bestätigen. Die bestehenden Unitfallzahlen bleiben dadurch unverändert.
|
||||
Lokale Qualifikation wird separat in einem geschützten `devstate/`-Beleg mit
|
||||
Quellen- und Artefakthashes erfasst. Cross-Clippy und Linken sind kein nativer
|
||||
Pipebeleg. Vor einem Zielupgrade sind unabhängiger Quellreview, die nativen
|
||||
Windows-Units des gleichen Manifests und ein eigener erhaltender Paarupgrade mit
|
||||
explizitem Backup sowie anschließendem tatsächlichen Agent/Helper-Austausch
|
||||
notwendig. Alle Produktgates bleiben geschlossen.
|
||||
|
||||
Lokale Ausführung: Default- und `system-helper`-Clippy für alle Windows-GNU-Targets
|
||||
mit `-D warnings`, Release-Build beider EXEs und Linken beider Unitprogramme waren
|
||||
erfolgreich. 61 gebundene Quelldateien blieben vor/nach dem Lauf gleich. Die
|
||||
bestehenden 23 Library- und 7 Binary-Unitfälle sind weiterhin die **erwartete**
|
||||
native Liste; hier wurde kein Windows-Testprogramm ausgeführt. Geschützter
|
||||
Beleg: `devstate/windows-pipe-drain/qualification-1e0f2b22-1e74-41af-b8ed-0a356be054ba/qualification.json`.
|
||||
|
||||
## Separater Build-/Unitrunner
|
||||
|
||||
`deploy/windows/system_pipe_acceptance.py` erstellt einen neuen Pack unter
|
||||
`devstate/windows-pipe-drain-build/`. Er prüft den unveränderten lokalen
|
||||
Qualifikationsbeleg samt ursprünglichen Links und verwendet die bereits
|
||||
bestandenen Clippy-/Release-/Unitlinkschritte wieder. Nur die fehlenden beiden
|
||||
Release-Stateprobes werden ergänzt. Alle sechs Auslieferungsdateien erhalten
|
||||
eine unveränderte `.linked`-Kopie; ausschließlich die Unit-Auslieferungskopien
|
||||
werden von Debuginformationen befreit. Neue Quellen einschließlich Runner,
|
||||
Compilerimage, Cargo-/Protoinputs und tatsächlich verwendeter Bootstrapmodule
|
||||
sind vor/nach dem Build gebunden.
|
||||
|
||||
`--access-root` muss der ursprüngliche Hauptcheckout sein. Nur dort werden die
|
||||
vorhandenen geschützten Zugangskonfigurationen für den bereits gepinnten
|
||||
Bootstraptransport und die tatsächlichen Linux-80-/Windows-58-Corebelege gelesen.
|
||||
Es werden keine Zugangsdaten oder Main-`devstate`-Bäume kopiert oder verlinkt.
|
||||
Neue Build-, Upload- und Unitfallbelege gehören zum isolierten Pipeworktree.
|
||||
|
||||
Der Native-Unitfall verwendet den neuen Namespace `native-pipe-v2`. **Beide**
|
||||
vollständigen nativen Listen müssen exakt den erwarteten 23 Library- und 7
|
||||
Binary-Namen entsprechen, bevor irgendein Unitfall ausgeführt wird. Intent,
|
||||
Listen, Start und einzelne Testergebnisse werden create-only gespeichert.
|
||||
Nach einem Antwortverlust darf ausschließlich derselbe Fall gelesen werden;
|
||||
auch ein fehlender oder unvollständiger Fall löst keinen erneuten Start aus.
|
||||
Die Units laufen als Bootstrapadministrator, nicht als Produkt-LocalService,
|
||||
und beweisen keinen tatsächlichen Pipeaustausch. Zentral gespeicherte
|
||||
Gerätezähler und geschlossene Fault-/Policyflags werden vor/nach verglichen.
|
||||
|
||||
Der bestehende rohe `helper_peer_controls::raw`-Probe schreibt weiterhin einen
|
||||
V1-Header. Sein Ablehnungsresultat ist deshalb **kein** V2-Peernegativnachweis;
|
||||
Runner und Manifest behaupten ausdrücklich keine solche Qualifikation.
|
||||
@@ -1,7 +1,8 @@
|
||||
# Gemeinsames passives Windows-Komponentenupgrade
|
||||
|
||||
Stand 2026-11-14: **Source vorbereitet; dieser Upgradefall wurde noch nicht auf
|
||||
der VM ausgeführt.** Lokale Guards und PowerShell-Parserprüfung ersetzen weder
|
||||
Stand 2026-11-14: **Passive Wartung nach separat dokumentiertem ersten APIfehler und
|
||||
enger Recovery abgeschlossen. Positive Pipeabnahme weiterhin fehlgeschlagen.**
|
||||
Lokale Guards und PowerShell-Parserprüfung ersetzen weder
|
||||
die neuen nativen Unitnachweise noch den tatsächlichen Erhaltungs-/Pipebeleg.
|
||||
Der Notebookhost bleibt ausschließlich Entwicklungsrechner.
|
||||
|
||||
@@ -72,10 +73,78 @@ Runtimeindex per lokalem CAS um einen neuen Komponentenbeleg ergänzt. Ein noch
|
||||
fehlgeschlagener Pipebeleg bleibt ausdrücklich fehlgeschlagen; ein erfolgreiches
|
||||
passives Komponentenupgrade behauptet keine Jobfähigkeit.
|
||||
|
||||
Geplante Befehle, **nicht ausgeführt**:
|
||||
Aufrufvorlagen; tatsächlichen Fallstand unten beachten:
|
||||
|
||||
```text
|
||||
python3 deploy/windows/system_delegation_upgrade.py upgrade-passive --manifest <manifest.json> --qualification <passed.json>
|
||||
python3 deploy/windows/system_delegation_upgrade.py readback --id <ursprüngliche UUID>
|
||||
python3 deploy/windows/system_delegation_upgrade.py finish --id <ursprüngliche UUID>
|
||||
```
|
||||
|
||||
## Tatsächlicher Fall6d2df065: erster Dateiaufruf fehlgeschlagen
|
||||
|
||||
Originalfall `6d2df065-0877-41c4-983c-2c9fdb6e5437` scheiterte zunächst vor dem
|
||||
Server-Beforecheckpoint. Nach wiederhergestelltem gepinntem SSH-Zugang wurden
|
||||
fehlender entfernter Fall/Activeintent und unveränderte Originalprozesse separat
|
||||
lesend bestätigt. Ein zusätzlicher dauerhafter Fortsetzungsintent führte
|
||||
ausschließlich die erste zuvor nicht erreichte Phase desselben Falls aus.
|
||||
Originale Fehlermeldung und Quellen blieben erhalten, kein neuer Enrollment-
|
||||
oder RMM-Jobkontext.
|
||||
|
||||
Native Stopps beider eigenen Dienste bestanden. Frozenbeleg und sämtliche vier
|
||||
privaten Originalbackups wurden gespeichert. Beim ersten Dateitausch meldete
|
||||
`[IO.File]::Replace($candidate,$destination,$null)` eine ArgumentException.
|
||||
Sofortiger gesonderter Readback: Agent/HelperStopped, vier Zielhashesoriginal,
|
||||
keine Replaced-/Swapped-/Startmarker. Eine weitere Nur-Leseprüfung bestätigt
|
||||
Frozen-DBbytes, Zeilen, tatsächliche Dateiidentitäten und PKI-Metadaten erhalten.
|
||||
Nur der erste Agentcandidate (exakter neuer Hash) und sein ursprünglicher
|
||||
Replaceversuchsmarker existieren; andere Candidates/Replaceversuche fehlen.
|
||||
|
||||
Eigene native Einbyte-API-Fixture `45a21a07-a115-47ec-93e1-694aa519520a`:
|
||||
Nullbackupaufruf reproduziert ArgumentException, Quelle/Destination unverändert;
|
||||
separater Aufruf mit explizitem Backup schreibt erwartete Destination und
|
||||
Originalbackup. Keine Runtime-Datei wurde durch diese Fixture berührt. Die
|
||||
genauere interne PowerShell-/Framework-Konvertierungsursache wird daraus nicht
|
||||
als bewiesen behauptet.
|
||||
|
||||
Der ursprüngliche Enter wird nicht erneut ausgeführt, Originalmarker und
|
||||
Quellen nicht geändert. Eine separate create-only Recovery muss vor jeder
|
||||
Fortsetzung diesen konkreten Vier-Dateien-/Frozen-/Nichtstartzustand bestätigen,
|
||||
den existierenden ersten Candidate hashgeprüft erhalten und einen ausdrücklich
|
||||
benannten zusätzlichen Nativebackup verwenden. Erst nach allen vier neuen
|
||||
Datei-/ACL-/Frozenbelegen dürfen die bisher noch nicht versuchten eigenen
|
||||
Helper-/Agentstarts folgen. Kein automatischer Retry oder Rücksetzen.
|
||||
|
||||
## Tatsächliche enge Recovery und Abschluss
|
||||
|
||||
Neue Quelle `deploy/windows/system_delegation_recovery.py`, SHA `64ced170…`,
|
||||
Script `65e480f2…`, unabhängig geprüft und lokal Python-/PS-AST geprüft. Originale
|
||||
Quelle `f8dc1c8f…` unverändert. Recoveryfall
|
||||
`595dd1da-0d7f-4364-9040-a75e16c6da83` bestätigte separat den vollständigen
|
||||
Stopped-/Frozen-/Datei-ID-/Candidatekontext und führte einmal vier Tausche mit
|
||||
expliziten zusätzlichen Nativebackups durch. Alle vier neuen Dateien, ACLs und
|
||||
Frozen-Datenbanken wurden vor dem ersten Start geprüft. Anschließend Helper,
|
||||
danach Agent jeweils einmal gestartet; getrenntes Readback bindet dieselben
|
||||
Phasen. Originalmarker und erste ArgumentException bleiben erhalten.
|
||||
|
||||
Originales `finish` war danach ausschließlich lesend: zwei frische WSS-
|
||||
Heartbeats, konkretes Inventar-ACK/fortgeschrittene Sequenz, gleicher Tenant/
|
||||
Geräteidentität und fremder Tenant verweigert. Journale/Dateiidentitäten/Zeilen,
|
||||
Konfiguration und PKI-Metadaten erhalten. ZählerWindows0/0/0/0, Linux30/30/26/0
|
||||
und geschlossene Flags/Rootpolicy unverändert. Runtime-/Komponentenindex erst
|
||||
nach diesen Belegen lokal per CAS veröffentlicht. Kein OS-Reboot, kein Job,
|
||||
kein Binding oder neuer Clock-/Wirkungsgate; Intentdateien weiter0Byte.
|
||||
|
||||
Tatsächlicher Agent `89004ad3…`, LocalService/Auto, PID8108, Geburtswert
|
||||
`134391259111815072`; Helper `e6aacbdd…`, SYSTEM/Manual, PID2620, Geburtswert
|
||||
`134391259068713651`. Policy `007adf5f…`, reziproker Pin `126670bc…`.
|
||||
Privater Originalabschluss `result.json` SHA256
|
||||
`ac00411fe1e109b18b28fd9c020245f462c179bb3ac99a37b69c7cff39c38460`;
|
||||
Recoveryabschluss `acceptance.json` SHA256
|
||||
`5ad5925c8928f49cd0f9d48a64f81018281b5b6e3704c799bae64a42898322bb`.
|
||||
|
||||
Die positive Pipeprobe bleibt ausdrücklich fehlgeschlagen: tatsächlicher neuer
|
||||
Agent meldet `client_read_reply`/`HELPER_PIPE_IO`, Win32233, kein authentisierter
|
||||
Austausch und kein privater Helperdiagnosebeleg. Dies ist ein erfolgreicher
|
||||
passiver Erhaltungs-/Wartungsnachweis, kein SYSTEM-Sync-/Job-/Clocknachweis.
|
||||
Kein erneutes Enter oder Wiederverwenden der ursprünglichen Startbefehle.
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
# Windows-Pipe v2: tatsächlicher Unitnachweis
|
||||
|
||||
Dieser Ergebnisnachtrag ergänzt den unveränderten, im Buildmanifest gebundenen
|
||||
[Framing-/Drain-Entwurf](windows-helper-pipe-drain.md). Der Entwurf bleibt als
|
||||
historischer Quellenstand erhalten; dieser Nachtrag verändert weder seinen Hash
|
||||
noch das ursprüngliche Manifest.
|
||||
|
||||
## Tatsächlich auf Windows bestanden
|
||||
|
||||
Root führte im eigenen nativen Fall
|
||||
`db25cd4a-bfd2-45d5-9f80-1881950853f7` die beiden konkreten Testprogramme des
|
||||
Pipe-v2-Packs aus. Beide vollständigen nativen Listen wurden vor irgendeinem
|
||||
Unitfall exakt geprüft. Alle23 Libraryfälle und alle7 Binaryfälle bestanden;
|
||||
kein Fall war fehlgeschlagen, ignoriert oder gefiltert. Beide Listenprozesse
|
||||
und beide Testprozesse endeten mit Exit0 ohne Timeout. Die gemeldete Testdauer
|
||||
betrug2,76s für die Library und0,07s für das Binary.
|
||||
|
||||
| Gebundener Beleg | SHA256 |
|
||||
| --- | --- |
|
||||
| Neues Pipe-v2-Buildmanifest | `b2f77713a4f70deddb6472fb1e869a85443ce1028914f62ccee71f8001fbadb4` |
|
||||
| Tatsächlicher Native-PASS | `19a8ccd95b7225f7e8657a696055bea4b52ed2f80f6caa3f42c9396ce6272713` |
|
||||
| Begrenzter Unitrunner | `2ac6bd55e608e7dbb0f0cf65cf37e7bbccc42b862d09c50b37e9162f29f4bbdf` |
|
||||
| Library-Lieferdatei | `3fc2b7314d755f5c5235c8383cf605cbe848180180497bb30540482f4910c2a1` |
|
||||
| Binary-Lieferdatei | `a3b8f44e87df7af54f82c1d052753217e9a03c495fb28c8a16ba9fe7e1a0af23` |
|
||||
|
||||
Geschützter nativer Beleg im isolierten Pipeworktree:
|
||||
`devstate/windows-client/native-pipe-v2/db25cd4a-bfd2-45d5-9f80-1881950853f7/passed.json`.
|
||||
Das zugehörige unveränderliche Buildmanifest liegt unter
|
||||
`devstate/windows-pipe-drain-build/build-59623db2-15ca-40cd-8728-861f84b2a550/manifest.json`.
|
||||
Die vorherige Manifestgeneration `928841e7…`, ihre Links und sämtliche früheren
|
||||
Belege bleiben erhalten.
|
||||
|
||||
## Was dieser PASS belegt
|
||||
|
||||
Die vorhandenen IPC-Codec-/Sicherheits-/Journal-/Runtimefälle liefen tatsächlich
|
||||
auf Windows als Bootstrapadministrator. Der Beleg weist `no_jobs=true` aus.
|
||||
Der Unitrunner begrenzt nach einem Timeout die Wartezeit auf das eigene
|
||||
Testprozessende und auf beide Ausgabe-Tasks; eine verlorene Antwort erlaubt nur
|
||||
den create-only gespeicherten Fall zu lesen. Das ist keine Änderung des
|
||||
Produktjob- oder Installerabbruchs.
|
||||
|
||||
`local_service_proof`, `native_pipe_proof` und `clock_adapter_qualified` sind im
|
||||
Native-PASS ausdrücklich weiterhin `false`. Dieser Unitlauf ist kein
|
||||
Produkt-LocalService-zu-SYSTEM-Austausch, kein Nachweis, dass Drain v2 die zuvor
|
||||
beobachtete233-Störung tatsächlich behebt, und keine SYSTEM-/Clock-/Jobfreigabe.
|
||||
Der bestehende rohe V1-Control ist kein V2-Peernegativnachweis.
|
||||
|
||||
Der erhaltende Paarupgrade, die Bindung an den nach dem Konsolenneustart
|
||||
vorhandenen tatsächlichen Prozesskontext und der anschließende reale
|
||||
Agent/Helper-Austausch bleiben gesondert zu prüfen. Vor dessen Ausführung stehen
|
||||
noch der unabhängige fokussierte Quellreview des neuen Upgrade-Runners und die
|
||||
explizite Root-Zielaktion. Keine Paket-, SCM-Fixture-, Reboot- oder sonstige
|
||||
RMM-Wirkung folgt aus dieser Unitabnahme.
|
||||
@@ -0,0 +1,148 @@
|
||||
# Windows Pipe-v2: erhaltender Paarupgrade nativ bestanden
|
||||
|
||||
Stand: 2026-11-14. Paarupgrade und tatsächlicher authentisierter Austausch des
|
||||
laufenden LocalService-Agenten mit seinem SYSTEM-Helper sind bestanden.
|
||||
Die ursprünglichen Vorbereitungsabschnitte unten bleiben Verlauf. RMM-Jobs,
|
||||
TrustedClock und Helperwirkungen bleiben weiterhin gesperrt.
|
||||
|
||||
Die ursprüngliche quellengebundene
|
||||
[Framingdokumentation](windows-helper-pipe-drain.md) bleibt unverändert. Diese
|
||||
separate Datei beschreibt ausschließlich die späteren Upgradevorbereitungen.
|
||||
Der Notebookhost bleibt reiner Entwicklungsrechner; Ziel ist die eigene
|
||||
Windows-VM am endgültigen Cloudserver.
|
||||
|
||||
## Geprüfter Kandidat und begrenzter Bootstrapvertrag
|
||||
|
||||
Der neue Runner
|
||||
[`system_pipe_upgrade.py`](../deploy/windows/system_pipe_upgrade.py) ist mit
|
||||
SHA `e466576673a0e5c332cfc1613ae88a62f5b526015ced76b1d22473e292a995e0`
|
||||
eingefroren. Sein frischer isolierter Prüfer bindet den neuen Pipe-Packtyp und
|
||||
dessen Originalquellen, genaue native Listen mit **23 Library- und 7
|
||||
Binarytests** sowie die erhaltenen Linux-first-Corebelege mit 80 Linux- und
|
||||
58 Windowsfällen. Es gibt keine Umbenennung alter Delegationsmanifeste und
|
||||
keine Umleitung des eigenen Source-Roots auf Main.
|
||||
|
||||
Der gebundene Pipe-Pack hat Manifest-SHA
|
||||
`b2f77713a4f70deddb6472fb1e869a85443ce1028914f62ccee71f8001fbadb4`.
|
||||
Die tatsächlichen 23+7 Windows-Administratorunits bestanden im Fall
|
||||
`db25cd4a-bfd2-45d5-9f80-1881950853f7`; dessen `passed.json` hat SHA
|
||||
`19a8ccd95b7225f7e8657a696055bea4b52ed2f80f6caa3f42c9396ce6272713`.
|
||||
Das sind Unitnachweise, kein LocalService-/Pipe-/Clock-Erfolgsbeleg.
|
||||
|
||||
Die vorbereitete Mutation verlangt eine separat geprüfte frische Baseline mit
|
||||
SCM-/Kernel-PID und tatsächlicher Prozessgeburt, Konto, aktivem Service-SID,
|
||||
Imagehash und ACLs. Ein bereits gestoppter Manual-Helper erhält keinen
|
||||
Vorabstart. Vor der ersten Ersetzung werden vier private Sicherungen erstellt;
|
||||
jede Ersetzung verlangt zusätzlich einen eigenen zuvor fehlenden nativen
|
||||
Backupnamen und frische Datei-ID-/Hash-/ACL-CAS-Prüfungen. Beide Dienste bleiben
|
||||
bis zur vollständigen neuen EXE-/Policy-/Pingeneration gestoppt. Danach sind
|
||||
Helper- und Agentstart jeweils create-once. Config-/CA-/Identitäts-/Zertifikats-
|
||||
und Private-Key-Metadaten samt Datei-IDs werden auch nach den Ersetzungen,
|
||||
vor dem Start und beim Finish unverändert verlangt.
|
||||
|
||||
`readback` ist rein lesend und kann auch einen fehlenden Zielpfad sowie einen
|
||||
SCM-Pendingzustand ehrlich zeigen. Baseline, Enter und Finish behalten ihre
|
||||
strengen Identitätsprüfungen. Nach verlorener Mutationsantwort gibt es keinen
|
||||
automatischen Enter-/Start-/Rollbackretry. Ein Finish benötigt neue passive
|
||||
Heartbeats und konkrete Inventar-ACKs; es schreibt nur einen lokalen Beleg.
|
||||
Main-Indizes werden ausschließlich durch Root separat per CAS fortgeschrieben.
|
||||
|
||||
## Tatsächlicher Fall 14fb: Timeout und geprüfte erste Fortsetzung
|
||||
|
||||
Fallverzeichnis:
|
||||
`devstate/windows-client/system-pipe-upgrade/14fb176a-f653-4573-a8d7-6f9fe47a3020/`.
|
||||
Der erste `prepare`-Aufruf begann am `2026-11-14T12:39:48.414511+00:00`
|
||||
und endete nach 180 Sekunden mit `TimeoutExpired` während des ersten
|
||||
Stagingaufrufs. Zu diesem Zeitpunkt gab es lokal nur den Prepareintent und
|
||||
Quellkopien, keine Baseline und keinen Enterintent. Die genaue Ursache des
|
||||
SSH-/Bootstraptimeouts ist nicht nachgewiesen.
|
||||
|
||||
Ein danach gesondert ausgeführter lesender Check bestätigte: beide neuen
|
||||
EXE-Stagingverzeichnisse, der neue entfernte Komponentenfall und der neue
|
||||
Active-Marker waren noch nicht vorhanden. Der alte Agent lief, der alte Helper
|
||||
war gestoppt. Auf dieser Abwesenheit beruhte die explizite create-once
|
||||
Fortsetzung der tatsächlich noch unerreichten Vorbereitungsphase im selben
|
||||
Fall; kein neuer Upgradefall und kein wiederholtes Enter.
|
||||
|
||||
| Erhaltener Beleg | SHA-256 |
|
||||
| --- | --- |
|
||||
| `prepare-first-stage-timeout.json` | `535faf7c6c4c7b3dba1f8d7b7889bc59acdee09fd51c2830fe397c3c9076f1e9` |
|
||||
| `first-prepare-readonly-absence.json` | `983b38fcc2cdc8e907436eb3053f32ad2cd131e765a82dd1e9930346e1c6877b` |
|
||||
| Private Fortsetzungsquelle `continue-first-prepare.py` | `86453aef4a1d59f73e423993b548e58ad0541205961a5952c80807403881cf3b` |
|
||||
| `continue-first-prepare-intent.json` | `7420622b7866e7b43b34087d5334599444a046b95a89e7f48503aca0f4e03be0` |
|
||||
| Neue lesende `baseline.json` | `57b79e9c918df6165cac0bb451b33fcd0c207933f15351afcd2ad6c400f4e2d7` |
|
||||
|
||||
Die Fortsetzung erzeugte schließlich den Baseline-/Intentbeleg und die
|
||||
serverseitigen Vorherbeobachtungen. Das ursprüngliche Timeout und seine
|
||||
Abwesenheitsmessung wurden nicht überschrieben.
|
||||
|
||||
## Baseline und verbleibende tatsächliche Abnahme
|
||||
|
||||
Die frische Baseline zeigt den weiterhin vorhandenen Agenten `89004ad3…`
|
||||
unter LocalService (`S-1-5-19`), `Running/Auto`, PID `3172`, mit exakter
|
||||
Kernel-FILETIME `134391328200102621`. Der vorhandene Helper `e6aacbdd…`
|
||||
ist `Stopped/Manual`, PID `0`; dafür wird kein laufender Prozess behauptet.
|
||||
Policy `007adf5f…` und Pin `126670bc…` gehören weiterhin zur alten Generation.
|
||||
Die Telemetriedatenbank wurde lesend mit `integrity=ok`, Sequenz `2564` und
|
||||
`pending_inventory_events=0` beobachtet. Ursprüngliche PKI-/DB-/Lock-Datei-IDs,
|
||||
ACLs und die beiden uninitialisierten Nullbyte-Intentleaves sind im privaten
|
||||
Baselinebeleg gebunden.
|
||||
|
||||
Vorherige Serverzählungen blieben:
|
||||
Windows `jobs/outbox/permits/unresolved = 0/0/0/0`, Linux
|
||||
`30/30/26/0`. Die beobachteten API-/Gateway-Transportfaultflags waren geschlossen;
|
||||
dies ist eine konkrete Vorhermessung, kein künftiger Nachherbeleg.
|
||||
|
||||
Der vorbereitete Kandidat umfasst Agent `f10c78dd…`, Helper `5f8c62fa…`,
|
||||
Policy `a3024467…` und Pin `af518db8…`. **Es existiert für diesen Fall noch kein
|
||||
Enterintent oder tatsächlicher Stop-/Swap-/Start-/Finishbeleg.** Staging ist
|
||||
keine Installation oder laufende Nutzung der neuen EXEs. Der alte SSH-Zugang
|
||||
lief anschließend aus; seine getrennte
|
||||
[Konsolenwiederherstellung](windows-dev-access-recovery.md) ist eine notwendige
|
||||
Zugangsstrecke und kein Paarupgrade.
|
||||
|
||||
Nach tatsächlicher Wiederherstellung des Zugangs muss Root die Baseline vor
|
||||
Mutation erneut bewerten. Geänderte PID/Birth-, Datei-, Index- oder andere
|
||||
gebundene Werte dürfen nicht still übernommen werden. Erst danach können der
|
||||
einmalige erhaltende Paarupgrade, zwei neue tatsächliche WSS-Heartbeats,
|
||||
Inventar-ACK, Tenantverweigerung und unveränderte Job-/Policygrenzen geprüft
|
||||
werden. Ein tatsächlicher authentisierter Austausch des laufenden
|
||||
LocalService-Agenten mit dem neuen SYSTEM-Helper bleibt offen. Jobfreigabe,
|
||||
Helperwirkungen und Clockqualifikation bleiben geschlossen.
|
||||
|
||||
## Tatsächlicher Abschluss im selben Fall
|
||||
|
||||
Nach der getrennt verifizierten SSH-Zugangswiederherstellung wurde derselbe
|
||||
Fall14fb genau einmal betreten. Die frische CAS-Prüfung bestätigte vor der
|
||||
Mutation die unveränderte ursprüngliche Baseline, beide lokalen Runtimeindizes
|
||||
und die geschlossenen Serverzähler/Policies. Der bereits gestoppte Helper
|
||||
wurde nicht vorab gestartet. Beide Dienste blieben während aller vier
|
||||
Dateiersetzungen gestoppt; Originale und native Backups sind erhalten.
|
||||
|
||||
Das anschließende rein lesende Finish bestätigt:
|
||||
|
||||
- Agent `f10c78dd738e7fb277e0c4d24fadf0f61ae3269458399b9224570ba5e66abc2c`
|
||||
läuft als LocalService/Auto, PID5528, Geburt `134391415551175930`.
|
||||
- Helper `5f8c62fab6bc8ea1bbb009166b3d0e741c034c36690a4e32ea4e3cb2d7729a79`
|
||||
läuft als SYSTEM/Manual, PID9464, Geburt `134391415512591188`.
|
||||
- Tatsächliche Agentprobe: `authenticated_pipe_exchange=true` und
|
||||
`client_service_pid_verified_by_helper=true`; Helperkonto/Service-SID und
|
||||
feste EXE-/Policybindungen geprüft. Der frühere Win32233-Lauf bleibt
|
||||
fehlgeschlagen; daraus wird keine rückwirkend bewiesene Fehlerursache.
|
||||
- Zwei neue WSS-Heartbeats, ursprüngliche mTLS-Geräteidentität,
|
||||
Inventar-ACK/Sequenz2813 und Tenantverweigerung bestätigt. Agent-/Helper-
|
||||
DB-/Lock-/PKI-Datei-IDs, Historie und leere Intentleaves erhalten.
|
||||
- Windows0/0/0/0, Linux30/30/26/0, geschlossene Testflags/Policies,
|
||||
`helper_ready=false`, `helper_clock_qualified=false`, keine SYSTEMcapability
|
||||
und keine Jobs oder Wirkung. Private Schlüssel wurden nicht gelesen.
|
||||
|
||||
Originaler `result.json`-SHA256:
|
||||
`d5c4996821911a5bdac5014e9f985c56bbb592b803f2e33411dd28bb986b8eed`.
|
||||
Er wurde samt Intent/Baseline bytegleich im privaten Main-Evidenzpfad
|
||||
archiviert. Erst danach veröffentlichte Root lokal beide Indizes per CAS unter
|
||||
einem gemeinsamen Lock, mit erhaltenen Vorgängerdateien und eigener
|
||||
Publikationsreceipt. Keine erneute Zielmutation:
|
||||
Runtimeindex `e49231e72aff7b001189b8507200c6c701f73e47f77c29194116cf1da41ca0c2`,
|
||||
Komponentenindex `005317e652f50de3e1277be3bc42717318226208015e7c8011e1b73469cc7562`.
|
||||
Der Nachweis qualifiziert den Pipe-v2-Peertransport und die passive Erhaltung,
|
||||
keine Clock, SYSTEM-Skriptkonsole oder Paketwirkung.
|
||||
@@ -0,0 +1,75 @@
|
||||
# Einmaliger Start des vorhandenen Windows-Zeitdiensts
|
||||
|
||||
Stand 2026-11-14: [Bootstrapquelle](../deploy/windows/time_service_start.py)
|
||||
implementiert, unabhängig quellgeprüft, Python-Syntax und PowerShell-AST lokal
|
||||
bestanden. **Einmaliger nativer Start und separater Readback bestanden.**
|
||||
Der Nutzer hat den Start des vorhandenen
|
||||
W32Time ausdrücklich erlaubt. Die Ausführung übernimmt der Root-Orchestrator
|
||||
nach Quellenprüfung auf der Windows-VM; das Notebook bleibt Entwicklungsrechner.
|
||||
|
||||
Der einzige Dienstbefehl ist `Start-Service -Name W32Time`. Startart,
|
||||
Dienstkonto, Imagepfad, Dienst-SDDL, SID-Typ, NTP-Konfiguration und Richtlinien
|
||||
werden nicht geschrieben. Für einen gestoppten Dienst müssen außerdem null
|
||||
Dienstabhängigkeiten vorliegen; sonst erfolgt kein Start. Pending-/unbekannte
|
||||
Zustände blockieren. Ein bereits laufender Dienst wird nur als
|
||||
`already_running` dokumentiert. Es gibt keinen Resyncbefehl, kein Policyupdate,
|
||||
keinen RMM-Job und keinen Reboot. Ein natürlicher Zeitsync durch den gestarteten
|
||||
Dienst ist erlaubt, aber **kein Nachweis einer qualifizierten Uhr**.
|
||||
|
||||
`prepare` verlangt die fünf unabhängig bekannten SHA256-Werte für Agent,
|
||||
Helper, Agentkonfiguration, Helperkonfiguration und Agentpin. Es legt einen
|
||||
privaten lokalen Fall an, bindet den bereits gespeicherten zentralen
|
||||
Beforekontext `time-service-start-context/888b18b8-da7e-4b9f-9e36-32a23f2ff973`,
|
||||
überträgt ausschließlich die feste, hashgeprüfte Bootstrapquelle und liest
|
||||
den tatsächlichen Ausgangszustand. Der Start verwendet diese Originalpins und
|
||||
diesen Fall unverändert. RMM-PIDs, Prozessentstehung, Dienstdefinitionen,
|
||||
Binaryhashes sowie Konfigurations-/PKI-Metadaten müssen erhalten bleiben.
|
||||
Der private Geräteschlüssel wird nur über Dateimetadaten und ACL-Hash geprüft;
|
||||
seine Bytes werden nicht gelesen oder exportiert.
|
||||
|
||||
Die Registryprüfung hasht nur ausdrücklich aufgeführte stabile Dienst-, NTP-
|
||||
und Policy-Konfigurationswerte. Sie gibt keine Rohwerte/NTP-Hostnamen aus.
|
||||
Volatile LastSync-/Laufzeitwerte werden nicht als unveränderlich vorausgesetzt;
|
||||
der Hash behauptet keine vollständige Abdeckung sämtlicher Registrywerte.
|
||||
W32Time-Status und dessen PID dürfen sich durch den erlaubten Start ändern.
|
||||
|
||||
Vor dem einzigen Startaufruf werden ein privater Originalbeleg und zwei
|
||||
dauerhafte, ausschließlich neu anlegbare Startreservierungen gespeichert:
|
||||
im Fallverzeichnis und als globaler W32Time-Einmalbeleg. Auch lokal entsteht
|
||||
vor dem SSH-Aufruf ein ausschließlich neu anlegbarer Startversuchsbeleg.
|
||||
Eine verlorene Antwort, ein Fehler oder ein unvollständiger Beleg erlaubt nur
|
||||
`readback --id ORIGINALFALL`; weder Startwiederholung noch automatischer
|
||||
Rollback sind implementiert. Readback meldet den tatsächlichen aktuellen
|
||||
Zustand und bewahrt unbestätigte Ergebnisse als solche. Frühere private
|
||||
SSH-Fehler werden vor/nach Aufrufen versioniert erhalten.
|
||||
|
||||
Die folgenden Befehle sind **Aufrufvorlagen**; die Hashplatzhalter
|
||||
müssen aus dem unabhängig bekannten aktuellen Deployment stammen:
|
||||
|
||||
```text
|
||||
python3 deploy/windows/time_service_start.py prepare --agent-sha256 HASH --helper-sha256 HASH --config-sha256 HASH --policy-sha256 HASH --pin-sha256 HASH
|
||||
python3 deploy/windows/time_service_start.py start --id ORIGINALFALL
|
||||
python3 deploy/windows/time_service_start.py readback --id ORIGINALFALL
|
||||
```
|
||||
|
||||
Vollständige Metadaten bleiben in geschützten lokalen/VM-Fallbelegen. Die CLI
|
||||
gibt nur Fallkennung, Status, Running-/Erhaltungs-/Readback-Merkmale und den
|
||||
ausdrücklich nicht geprüften Uhrvertrauensstatus aus. Lokaler Quellnachweis:
|
||||
`devstate/windows-client/time-service-start-source/225c3208-4a3f-4528-8c17-b3846b70812f/qualification.json`;
|
||||
PowerShell nur geparst, kein Windows-API-/VM-Aufruf und keine Produkttestsuite.
|
||||
|
||||
## Tatsächliche Ausführung
|
||||
|
||||
Fall `c3552c3f-24d1-4713-bd0b-544aee4ffd18` auf dem Windowsgast:
|
||||
Vorbereitung bestätigte Stopped und die bekannten Originalhashes. Anschließend
|
||||
genau ein `Start-Service W32Time`, Status Running, Erhaltungsprüfung bestanden.
|
||||
Getrennter späterer Readback bestätigte denselben Originalresultbeleg und
|
||||
Running ohne Startwiederholung. Agent5140 und Helper6240 unverändert;
|
||||
Dienstdefinition/SDDL und ausgewählte NTP-/Policy-Konfigurationswerte erhalten.
|
||||
Kein privater Schlüsselinhalt gelesen und keine Konfiguration geschrieben.
|
||||
|
||||
Zentraler Kontrollstand vorher/nachher identisch: Windows0Jobs/0Outbox/0Grants/
|
||||
0ungeklärt, Linux30/30/26/0; Rootpolicyhash und geschlossene Transporthooks
|
||||
unverändert. Geschützter Abschlussbeleg `acceptance.json` im Originalfall,
|
||||
SHA256 `365d897d94f6fb16b3112fcb5126bdc09224b34e0a6ef46940ca8e7a651807fb`.
|
||||
Quellhash `ef5d4ce8…`. **Kein Uhrqualifikations-, RMM-Job- oder Rebootbeleg.**
|
||||
Reference in New Issue
Block a user