Qualify tenant-scoped bootstrap rotation and fresh Windows scripting
This commit is contained in:
@@ -238,7 +238,7 @@ fn verify_envelope_with_keyring(
|
||||
keyring_generation: config.generation,
|
||||
protocol_major: 1,
|
||||
state_schema: 1,
|
||||
updater_version: 1,
|
||||
updater_version: if binding.is_none() && decoded.manifest.platform == Platform::WindowsGnuX64 { 2 } else { 1 },
|
||||
minimum_release_sequence: 0,
|
||||
active_release: None,
|
||||
};
|
||||
|
||||
@@ -123,7 +123,7 @@ try {
|
||||
Set-Text $ring ($meta.keyring | ConvertTo-Json -Depth 16 -Compress)
|
||||
Set-Text $envelope ($meta.release_envelope | ConvertTo-Json -Depth 16 -Compress)
|
||||
$updater = Join-Path $appStage 'rmm-updater-windows.exe'
|
||||
Get-Download ('/agent/v1/bootstrap/updater' + $query) $updater $meta.updater.bytes $true
|
||||
Get-Download ('/agent/v1/bootstrap/updater' + $query + '&sha256=' + $meta.updater.sha256) $updater $meta.updater.bytes $true
|
||||
if ((Get-Hash $updater) -cne $meta.updater.sha256) { throw 'Bootstrap updater digest mismatch.' }
|
||||
$roles = @('agent', 'helper')
|
||||
for ($i = 0; $i -lt $roles.Count; $i++) {
|
||||
@@ -145,6 +145,25 @@ try {
|
||||
$ca = Join-Path $data 'server-ca.pem'
|
||||
Set-Text (Join-Path $dataStage 'server-ca.pem') $meta.ca_pem
|
||||
$config = [ordered]@{server_name=$gateway.DnsSafeHost; connect_address=$endpoint.ToString(); ca_file=$ca; state_directory=$state; enrollment_token_file=$tokenPath; transport='https'}
|
||||
$localJobs = $verified.minimum_updater_version -ge 2
|
||||
if ($localJobs) {
|
||||
$features = & $agentPath --release-capabilities
|
||||
if ($LASTEXITCODE -ne 0 -or $features -cne 'enrolled-localservice/1') { throw 'Signed agent lacks its required LocalService profile.' }
|
||||
$features = & $updater --release-capabilities
|
||||
if ($LASTEXITCODE -ne 0 -or $features -cne 'release-job-lock/1') { throw 'Stable updater lacks coordinated job draining.' }
|
||||
$trust = $meta.windows_time_trust
|
||||
if (-not $trust -or $meta.job_signing_public_key_hex -cnotmatch '^[0-9a-f]{64}$' -or
|
||||
$trust.key_generation -lt 1 -or @($trust.public_keys_hex.PSObject.Properties).Count -notin (1..8)) { throw 'Missing enrolled Windows job trust.' }
|
||||
foreach ($key in $trust.public_keys_hex.PSObject.Properties) {
|
||||
if ($key.Value -cnotmatch '^[0-9a-f]{64}$' -or $key.Value -ceq $meta.job_signing_public_key_hex) { throw 'Invalid independent time signing key.' }
|
||||
}
|
||||
$policy = [ordered]@{schema_version=1; tenant_id=$tenant; job_signing_public_key_hex=$meta.job_signing_public_key_hex; key_generation=$trust.key_generation; server_instance=(Get-Id $trust.server_instance); public_keys_hex=$trust.public_keys_hex}
|
||||
Set-Text (Join-Path $dataStage 'job-time.json') ($policy | ConvertTo-Json -Depth 8 -Compress)
|
||||
Set-Text (Join-Path $dataStage 'release-job.lock') ''
|
||||
$config['enable_jobs'] = $true
|
||||
$config['localservice_time_policy'] = Join-Path $data 'job-time.json'
|
||||
$config['windows_execution_profile'] = 'powershell_51_remote_signed'
|
||||
}
|
||||
Set-Text (Join-Path $dataStage 'config.json') ($config | ConvertTo-Json -Compress)
|
||||
$baseline = [ordered]@{schema_version=1; tenant_id=$tenant; release_id=$releaseId; release_sequence=$verified.release_sequence; manifest_sha256=(Get-Hash (Join-Path $images 'manifest.json'))}
|
||||
Set-Text (Join-Path $dataStage 'installed-release.json') ($baseline | ConvertTo-Json -Compress)
|
||||
@@ -165,6 +184,7 @@ try {
|
||||
Set-Acl -LiteralPath $app -AclObject (Get-DirectoryAcl $sid 'ReadAndExecute')
|
||||
Set-Acl -LiteralPath $data -AclObject (Get-DirectoryAcl $sid 'ReadAndExecute')
|
||||
[void][IO.Directory]::CreateDirectory($state, (Get-DirectoryAcl $sid 'Modify'))
|
||||
if ($localJobs) { [void][IO.Directory]::CreateDirectory((Join-Path $state 'jobs'), (Get-DirectoryAcl $sid 'Modify')) }
|
||||
# Agent-side private-path checks authenticate the owner as well as the DACL.
|
||||
foreach ($root in @($app, $data)) {
|
||||
foreach ($item in @(Get-ChildItem -LiteralPath $root -Recurse -Force)) {
|
||||
|
||||
@@ -117,7 +117,10 @@ def device_get(route, size=None, digest=None):
|
||||
def device_idle():
|
||||
# The root worker holds the admission lock before consulting this journal.
|
||||
with sqlite3.connect(f'file:{STATE}/journal.sqlite?mode=ro', uri=True) as conn:
|
||||
busy, = conn.execute("SELECT EXISTS(SELECT 1 FROM job_attempts WHERE state IN ('requesting','running','verifying'))").fetchone()
|
||||
busy, = conn.execute(
|
||||
"SELECT EXISTS(SELECT 1 FROM job_attempts "
|
||||
"WHERE state IN ('requesting','running','verifying','unknown','awaiting_reboot'))"
|
||||
).fetchone()
|
||||
print('busy' if busy else 'idle')
|
||||
|
||||
|
||||
@@ -248,7 +251,7 @@ def enable():
|
||||
else:
|
||||
save(path, data.encode())
|
||||
service('daemon-reload')
|
||||
service('enable', '--now', SERVICE, TIMER)
|
||||
service('enable', '--now', SERVICE)
|
||||
|
||||
|
||||
def enrollment_token(path):
|
||||
@@ -279,6 +282,7 @@ def install(base, token_file):
|
||||
save_token(ROOT, token, pwd.getpwnam('rmm-discovery').pw_gid)
|
||||
enable()
|
||||
require(healthy(read(ROOT / 'current/manifest.json')['version'], 0), 'awaiting authenticated device heartbeat')
|
||||
service('enable', '--now', TIMER)
|
||||
(ROOT / 'first.token').unlink(missing_ok=True)
|
||||
return
|
||||
require(not STATE.exists() and not any((UNIT_DIR/name).exists() for name in units()),
|
||||
@@ -302,7 +306,7 @@ def install(base, token_file):
|
||||
save(staging / 'config.json', {'bootstrap': base, 'gateway': origin(doc['gateway_origin']),
|
||||
'tenant': canonical_id(doc['tenant_id'])})
|
||||
updater = staging / 'updater'
|
||||
remote((base, token), '/agent/v1/bootstrap/updater?platform=' + PLATFORM, updater, doc['updater'])
|
||||
remote((base, token), '/agent/v1/bootstrap/updater?platform=' + PLATFORM + '&sha256=' + doc['updater']['sha256'], updater, doc['updater'])
|
||||
updater.chmod(0o755)
|
||||
releases = staging / 'releases'
|
||||
releases.mkdir()
|
||||
@@ -318,6 +322,9 @@ def install(base, token_file):
|
||||
os.rename(staging, ROOT)
|
||||
enable()
|
||||
require(healthy(manifest['version'], 0), 'installed, awaiting authenticated device heartbeat')
|
||||
# OnBootSec may already be in the past on a running machine. The first
|
||||
# timer check can run immediately once the device has reported its platform.
|
||||
service('enable', '--now', TIMER)
|
||||
(ROOT / 'first.token').unlink(missing_ok=True)
|
||||
|
||||
|
||||
|
||||
@@ -9,14 +9,41 @@ struct Config {
|
||||
updater_sha256: String,
|
||||
updater_bytes: u64,
|
||||
}
|
||||
fn config(platform: Platform) -> Result<Config, Error> {
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Pin { sha256: String, bytes: u64 }
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Previous { pin: Pin, expires_at: i64 }
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct TenantPins { current: Pin, previous: Vec<Previous> }
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub(super) struct UpdaterQuery { platform: Platform, sha256: Option<String> }
|
||||
|
||||
fn config(platform: Platform, tenant: Uuid, wanted: Option<&str>) -> Result<Config, Error> {
|
||||
let slot = match platform {
|
||||
Platform::LinuxX64 => "RMM_AGENT_BOOTSTRAP_LINUX_FILE",
|
||||
Platform::WindowsX64 => "RMM_AGENT_BOOTSTRAP_WINDOWS_FILE",
|
||||
Platform::WindowsGnuX64 => "RMM_AGENT_BOOTSTRAP_WINDOWS_GNU_FILE",
|
||||
};
|
||||
let path = std::env::var(slot).map_err(|_| fail("BOOTSTRAP_NOT_CONFIGURED"))?;
|
||||
let config: Config = serde_json::from_slice(&protected_file(FsPath::new(&path), 8192)?)?;
|
||||
let path = FsPath::new(&path);
|
||||
let mut config: Config = serde_json::from_slice(&protected_file(path, 8192)?)?;
|
||||
let scoped = path.with_extension(format!("{tenant}.json"));
|
||||
if scoped.try_exists().map_err(|_| fail("BOOTSTRAP_CONFIGURATION_INVALID"))? {
|
||||
let pins: TenantPins = serde_json::from_slice(&protected_file(&scoped, 32768)?)?;
|
||||
let selected = match wanted {
|
||||
Some(digest) if pins.current.sha256 != digest => pins.previous.into_iter()
|
||||
.find(|p| p.pin.sha256 == digest && p.expires_at > chrono::Utc::now().timestamp())
|
||||
.map(|p| p.pin).ok_or_else(missing)?,
|
||||
_ => pins.current,
|
||||
};
|
||||
config.updater_sha256 = selected.sha256;
|
||||
config.updater_bytes = selected.bytes;
|
||||
}
|
||||
if wanted.is_some_and(|digest| digest != config.updater_sha256) { return Err(missing()); }
|
||||
let url = url::Url::parse(&config.gateway_origin).map_err(|_| invalid())?;
|
||||
if url.scheme() != "https"
|
||||
|| url.domain().is_none()
|
||||
@@ -143,7 +170,7 @@ pub(super) async fn current(
|
||||
Query(q): Query<Current>,
|
||||
) -> Result<Response, Error> {
|
||||
let t = token_tenant(&s, &headers).await?;
|
||||
let c = config(q.platform)?;
|
||||
let c = config(q.platform, t, None)?;
|
||||
let mut tx = rmm_persistence::tenant_tx(&s.pool, t).await?;
|
||||
let release: Uuid = sqlx::query_scalar("SELECT release_id FROM agent_update_releases WHERE platform=$1 ORDER BY release_sequence DESC LIMIT 1")
|
||||
.bind(platform_name(q.platform)).fetch_optional(&mut *tx).await?.ok_or_else(missing)?;
|
||||
@@ -187,9 +214,9 @@ pub(super) async fn artifact(
|
||||
pub(super) async fn updater(
|
||||
State(s): State<crate::State>,
|
||||
headers: HeaderMap,
|
||||
Query(q): Query<Current>,
|
||||
Query(q): Query<UpdaterQuery>,
|
||||
) -> Result<Response, Error> {
|
||||
let tenant = token_tenant(&s, &headers).await?;
|
||||
let c = config(q.platform)?;
|
||||
let c = config(q.platform, tenant, q.sha256.as_deref())?;
|
||||
verified_binary(tenant, c.updater_sha256, c.updater_bytes).await
|
||||
}
|
||||
|
||||
@@ -124,10 +124,7 @@ impl SystemScope {
|
||||
.allowed_script_profiles
|
||||
.as_deref()
|
||||
.is_none_or(|v| v == [rmm_domain::jobs::PrivilegedScriptProfile::FullMaintenanceV1])
|
||||
&& rmm_domain::jobs::valid_windows_update_limit(
|
||||
self.windows_update_max_runtime_seconds,
|
||||
self.allowed_script_profiles.as_deref(),
|
||||
)
|
||||
&& rmm_domain::jobs::valid_windows_update_limit(self.windows_update_max_runtime_seconds)
|
||||
&& (1..=120).contains(&self.max_runtime_seconds)
|
||||
}
|
||||
fn permits(
|
||||
@@ -184,11 +181,11 @@ impl SystemScope {
|
||||
Action::RunScript { .. } => {
|
||||
allow_scripts
|
||||
&& job.action.full_maintenance()
|
||||
&& self.allowed_script_profiles.as_ref().is_some_and(|v| {
|
||||
&& (self.allowed_script_profiles.as_ref().is_some_and(|v| {
|
||||
v.contains(
|
||||
&rmm_domain::jobs::PrivilegedScriptProfile::FullMaintenanceV1,
|
||||
)
|
||||
})
|
||||
}) || (self.windows_update_max_runtime_seconds.is_some() && job.action.is_windows_update_template()))
|
||||
&& job.action.validate()
|
||||
&& job
|
||||
.action
|
||||
|
||||
Reference in New Issue
Block a user