Compare commits

..
Author SHA1 Message Date
kevin_janssen dd59052e7c Record native Windows idle performance and SYSTEM acceptance
Rust development slice / linux (push) Failing after 8s
2026-11-18 21:31:48 +01:00
kevin_janssen a4bcebf440 Slow successful Windows helper time refreshes 2026-11-18 21:19:14 +01:00
kevin_janssen aea2d5b379 Expand the passive inventory shown in device details
Rust development slice / linux (push) Failing after 9s
2026-11-18 20:02:41 +01:00
kevin_janssen 38f43f887a Record the native OTRS closure and dashboard verification
Rust development slice / linux (push) Failing after 8s
2026-11-18 19:08:27 +01:00
kevin_janssen 915e126f24 Reconcile a human closure when the helper has no result
Rust development slice / linux (push) Failing after 9s
2026-11-18 19:03:02 +01:00
kevin_janssen abad2022e2 Record the live RAM and CPU dashboard checks
Rust development slice / linux (push) Failing after 8s
2026-11-18 18:54:40 +01:00
kevin_janssen 6ed57c4d0b Show the same capacity bar for RAM and disk space
Rust development slice / linux (push) Failing after 7s
2026-11-18 18:47:46 +01:00
kevin_janssen 7006ce7420 Keep the last valid CPU reading during RAM-only heartbeats
Rust development slice / linux (push) Failing after 8s
2026-11-18 18:46:04 +01:00
kevin_janssen b3fe35b86b Show available RAM and measured CPU usage for devices
Rust development slice / linux (push) Failing after 8s
2026-11-18 18:37:18 +01:00
kevin_janssen fb2376443c Document OTRS ARM64 root-script helper activation
Rust development slice / linux (push) Failing after 7s
2026-11-18 18:21:51 +01:00
kevin_janssen f2a2d44d84 Require pushing completed changes to Gitea
Rust development slice / linux (push) Failing after 7s
2026-11-18 18:14:50 +01:00
kevin_janssen 7215ea9733 Merge remote-tracking branch 'origin/main' into codex/linux-arm64-installer 2026-11-18 18:14:35 +01:00
kevin_janssen b5907d681d Record successful OTRS enrollment and corrected HTTPS installer 2026-11-18 18:13:16 +01:00
kevin_janssen 4b3d0136e9 Wait for the device certificate before probing Linux enrollment 2026-11-18 18:09:52 +01:00
kevin_janssen bfdc3da8af Record native ARM64 HTTPS release and installer verification 2026-11-18 18:07:31 +01:00
kevin_janssen 6d15f1b3f5 Use the shared target triple for the release catalog 2026-11-18 17:59:34 +01:00
kevin_janssen 8b5365f4bc Verify Linux installer architecture selection and display available targets 2026-11-18 17:59:19 +01:00
kevin_janssen 247646a2ba Build and serve signed Linux ARM64 agent releases 2026-11-18 17:58:12 +01:00
kevin_janssen 11a67ca9a4 Record the production machine type rollout on both guests
Rust development slice / linux (push) Failing after 12s
2026-11-18 17:52:09 +01:00
kevin_janssen f1538143cf Check the machine type after the labelled hostname column
Rust development slice / linux (push) Failing after 13s
2026-11-18 17:41:22 +01:00
kevin_janssen c599baa494 Show the detected machine type in device inventory 2026-11-18 17:39:43 +01:00
kevin_janssen 6963ad332c Document the accepted MVP and retire superseded development plans
Rust development slice / linux (push) Failing after 14s
2026-11-18 17:21:12 +01:00
kevin_janssen f37b6dc4f7 Record native Linux and Windows MCP script and reboot results
Rust development slice / linux (push) Failing after 15s
2026-11-18 17:01:00 +01:00
kevin_janssen 92e2050935 Record deployed MCP planning and pending Linux acceptance
Rust development slice / linux (push) Failing after 13s
2026-11-18 16:26:43 +01:00
kevin_janssen c4e064773b Authorize scoped MCP script requests on opted-in managed devices
Rust development slice / linux (push) Failing after 16s
2026-11-18 16:21:12 +01:00
kevin_janssen 5bf844d850 Record native Windows helper recovery and original job result 2026-11-18 14:30:45 +01:00
kevin_janssen e5006b3ecb Recover Windows helper sync after acknowledged result delivery 2026-11-18 14:25:42 +01:00
kevin_janssen 1d58f2e704 Keep installed admin helpers usable after release expiry
Rust development slice / linux (push) Failing after 13s
2026-11-18 13:07:19 +01:00
kevin_janssen bb4e7cbad7 Record public enrollment guide deployment and readback
Rust development slice / linux (push) Failing after 16s
2026-11-18 13:05:03 +01:00
kevin_janssen acbff0060d Explain client enrollment and MCP curl usage in the live WebUI
Rust development slice / linux (push) Failing after 14s
2026-11-18 13:03:37 +01:00
kevin_janssen 7dccb204ec Record both native reboot and follow-up runs through the script channel
Rust development slice / linux (push) Failing after 13s
2026-11-18 12:47:41 +01:00
kevin_janssen fa71f44c36 Provide the native computer name to Windows script processes 2026-11-18 12:38:03 +01:00
kevin_janssen 5889964ea1 Check Windows reboot scheduling through an explicit process result 2026-11-18 12:28:52 +01:00
kevin_janssen 55fad07327 Apply the script-only capability and start contract to every Windows profile 2026-11-18 12:17:52 +01:00
kevin_janssen 4afa6e4a12 Build the Windows updater policy capability probe 2026-11-18 12:12:36 +01:00
kevin_janssen fb07e4b548 Close retired Windows offers before start and verify policy-preserving updater support 2026-11-18 12:11:15 +01:00
kevin_janssen 0f70d8d8f5 Reconcile byte-identical historical offers without allowing another execution 2026-11-18 12:10:27 +01:00
kevin_janssen cd80bfc704 Plan device actions exclusively as approved scripts and provide reboot library revisions 2026-11-18 12:04:58 +01:00
kevin_janssen adc04f0148 Use script-only execution on Linux and preserve the enrolled helper through updates 2026-11-18 12:01:02 +01:00
kevin_janssen c692316abe Bind Windows script contexts to the installed signed helper 2026-11-18 11:58:55 +01:00
kevin_janssen ab20cb0778 Record whole-MVP identity checks and the unqualified typed reboot paths 2026-11-18 11:34:37 +01:00
kevin_janssen 53c713aa3a Record official Windows release, native self-update and retired pairing removal 2026-11-18 11:20:24 +01:00
kevin_janssen 9c7ccbb59b Enable explicitly configured private artifact storage for authenticated production releases 2026-11-18 11:08:53 +01:00
kevin_janssen 0b07baf7be Keep legacy Windows starter worker pins outside official GNU enrollments 2026-11-18 11:03:55 +01:00
kevin_janssen 07154833b3 Remove one retired device pairing and its owned history from the device detail 2026-11-18 11:03:55 +01:00
kevin_janssen 374b7e42d6 Use verified SSH profiles from the primary checkout in linked worktrees 2026-11-18 10:54:35 +01:00
kevin_janssen 663e846415 Ship Windows x64 through a separately signed official GNU release channel 2026-11-18 10:53:16 +01:00
kevin_janssen 7ddd579888 Record live device recovery, role checks and public script results 2026-11-18 10:33:32 +01:00
kevin_janssen b8e4b32a33 Wait for the Linux service launcher to execute its verified binary 2026-11-18 10:27:59 +01:00
kevin_janssen 17f2e6dc91 Roll existing Linux helper pins forward with the verified release pair 2026-11-18 10:23:43 +01:00
kevin_janssen 6d4f53dcae Display Windows CRLF as a line break in stored script output 2026-11-18 10:22:38 +01:00
kevin_janssen a0b3aa46f5 Keep participant checks consistent across submission and dispatch 2026-11-18 10:12:31 +01:00
kevin_janssen 72d95dee11 Keep Windows intent and diagnostic databases read-only with rusqlite 0.41 2026-11-18 10:11:02 +01:00
kevin_janssen 0f15f91f65 Recheck the submitting principal and protect stored log output 2026-11-18 10:10:06 +01:00
kevin_janssen db2f5b407d Ship the corrected bundled SQLite in device components and pinned builds 2026-11-18 10:08:01 +01:00
kevin_janssen 3e6ce7f07c Resume signed Windows reconciliation after a proven missing helper acknowledgement 2026-11-18 10:01:57 +01:00
kevin_janssen 7cec566dfe Record the release readiness checks and the Windows sync blocker 2026-11-18 09:40:48 +01:00
kevin_janssen 9e913b7a51 Record script library filtering and customer navigation acceptance 2026-11-18 09:29:30 +01:00
kevin_janssen 97ef5783c1 Filter the script library and show customer context across pages 2026-11-18 09:28:11 +01:00
kevin_janssen f8e5865412 Record public acceptance of order filters and decision history 2026-11-18 09:18:08 +01:00
kevin_janssen 61688bcd4b Verify the order filter form with accessible labels 2026-11-18 09:17:01 +01:00
kevin_janssen 14a271f61a Make order search, device results and decisions visible in the WebUI 2026-11-18 09:14:42 +01:00
kevin_janssen 5b6e9c9cdb Validate order search and audit decisions against PostgreSQL 2026-11-18 09:12:47 +01:00
kevin_janssen c0754f1d0d Filter orders before pagination and expose recorded decisions and result links 2026-11-18 09:07:28 +01:00
kevin_janssen 973e131c86 Integrate the currently deployed server functionality with the reviewed WebUI 2026-11-18 09:05:06 +01:00
kevin_janssen ea87d8141c Enable per-order privileged scripts on managed devices 2026-11-18 00:02:17 +01:00
kevin_janssen 2712c4f80e Record the deployed WebUI review changes and live readback 2026-11-17 23:54:51 +01:00
kevin_janssen 8e770c6378 Mark release table column headers explicitly 2026-11-17 23:53:59 +01:00
kevin_janssen f6e658ce35 Make execution controls and maintenance workflows easier to use 2026-11-17 23:52:03 +01:00
kevin_janssen a397dd7ae4 Expose the current execution stop to authorized web sessions 2026-11-17 23:46:06 +01:00
kevin_janssen 984c730f5d Add standard diagnostics and typed restart planning 2026-11-17 23:37:14 +01:00
343 changed files with 9750 additions and 37262 deletions
+17 -26
View File
@@ -1,35 +1,26 @@
# Arbeiten an Rust Discovery # Arbeiten an Rust Discovery
## Einstieg für jeden Auftrag Der abgenommene MVP liegt auf dem Branch `main`. Der [Produktvertrag](Rust_RMM_Implementierungsspezifikation.md) beschreibt das Verhalten, die [MVP-Abnahme](docs/mvp-completion-plan.md) die tatsächlich geprüften Geräte und Ergebnisse. Den nächsten Arbeitsumfang bestimmt der aktuelle Nutzerauftrag.
1. Lies das [Produktziel, den geprüften Stand und den nächsten Schritt](docs/mvp-completion-plan.md). **Nur dort** steht die aktive Arbeitsreihenfolge. Die [Übergabe](docs/handover.md) nennt den passenden Betriebszugang. Eine datierte Abnahme oder ein alter Reparaturplan ist ein Beleg für seinen damaligen Stand. ## Einen Auftrag übernehmen
2. Benenne das Nutzerergebnis des gewählten Schritts, den schon vorhandenen Beleg und die fehlende Beobachtung. Lies vor Änderungen den betroffenen Code und Vertrag. Bei Produktentscheidungen gilt [Kapitel 0 der Spezifikation](Rust_RMM_Implementierungsspezifikation.md) mit dem jüngsten einschlägigen Nutzerentscheid. [Entscheidungsbuch](docs/project-decisions.md) und [Entwicklungsweg](docs/development.md) liefern den Hintergrund.
3. Ein Integrator koordiniert Zielgeräte, gemeinsam genutzte Dateien, WebUI und Gitindex. Teilaufträge bekommen einen Dateibereich und ein prüfbares Ergebnis. Vorhandenen WIP mit `git status --short` abgrenzen, funktionierende Teilstrecken wiederverwenden und nur aufgabenbezogene Änderungen aufnehmen.
4. Wenn eine frühere Grenze das Ziel behindert, kläre ihren Zweck und wähle die kleinste begründete Änderung. Technische Vereinfachungen dürfen direkt umgesetzt werden. Eine geänderte Produktentscheidung in Kapitel 0 und im Entscheidungsbuch festhalten. Eine unbekannte Wirkung eines früheren Jobs bleibt dabei unbekannt.
5. Nach einem Schritt den Status **in derselben Planzeile** aktualisieren. Quelle, Artefakt, echter Zielkontakt und fachliche Abnahme getrennt belegen. Bei einem Hindernis die konkrete fehlende Beobachtung festhalten und am nächsten unabhängigen Liefergegenstand weiterarbeiten.
## Was wir liefern 1. Mit `git status --short --branch` den Arbeitsbaum und vorhandene Änderungen prüfen. Für laufende Fremdarbeit einen separaten Branch oder Worktree verwenden.
2. In der [Übergabe](docs/handover.md) den betroffenen Einstiegspunkt finden. Vor Änderungen den tatsächlichen Aufrufer, die Berechtigungsprüfung und die vorhandenen Tests lesen. Ein datierter Beleg in `docs/evidence/` dokumentiert das Ereignis zu seinem Messzeitpunkt.
3. Den normalen Bedienweg und den konkreten Fehlerfall prüfen. Bei einem Linux- oder Windows-spezifischen Verhalten den betreffenden Gast verwenden. Ein Build belegt die Erzeugung des Artefakts. Das Ergebnis des Zielgeräts belegt seine Wirkung.
4. Verändert sich das Produktverhalten, die zuständige Anleitung und den Produktvertrag abgleichen. Eine neue Abnahme im [Prüfstand](docs/mvp-completion-plan.md) mit Quelle, Ziel und beobachtetem Ergebnis nachtragen.
5. Nach jeder abgeschlossenen Änderung die zugehörigen Dateien committen und auf den passenden Branch in Gitea pushen. Das gilt auch für reine Dokuänderungen. Den gepushten Commit in Gitea prüfen. [Entwicklungsablauf](docs/development.md#änderungen-in-gitea-sichern)
Ein Server mit WebUI und MCP verwaltet Linux- und Windows-Clients. Die Clients melden Heartbeats und Inventar, holen optionale Skriptaufträge ab und geben Ergebnisse zurück. Eine benannte, versionierte Skriptbibliothek bedient beide Oberflächen. Windows-Updates sind ein PowerShell-Katalogeintrag. Ein frischer Client lässt sich über ein HTTPS-Installationsskript aufnehmen und aktualisiert seinen eigenen Agenten periodisch aus dem signierten Releasebestand des Servers. Die Abnahmekriterien stehen im Plan. ## Regeln für Änderungen
Für Geräte und Kunden gilt Kapitel 0.7. Änderungen an Kundengrenzen mit beschränktem und globalem Token prüfen, einschließlich Listen, direkter Geräte-IDs und Widerruf. Die Trennung von Bestand und Historie beruht auf der bestätigten Geräteidentität. Bei einem Kundenwechsel neu enrollen und die bisherige Historie beim ursprünglichen Kunden belassen. - Jede neu geplante Geräteaktion nutzt ein Skript. Ein Neustart und ein Betriebssystemupdate durchlaufen denselben Weg wie ein eigenes Shell- oder PowerShell-Skript.
- Jeder eingereichte Skriptplan wartet auf Genehmigung. Eine berechtigte Person bestätigt in der WebUI Ziel, genaue Skriptbytes, Rechte, Zeitfenster und feste Versuche. Diese Entscheidung gehört zur Person. Für produktive Aufträge sind Freigaben durch die KI, einen MCP-Token oder direkte Datenbankzugriffe ausgeschlossen. Separat gekennzeichnete Simulationen gehören ausschließlich zum internen Entwicklungsprofil.
- Beim Zustellen und Wiederverbinden die Signatur-, Zeit-, Geräte- und Versuchsbindung erhalten. Einen bereits gestarteten oder ungeklärten Versuch anhand seines Journals und der Serverdaten abgleichen. Ein neuer Versuch braucht einen eigenen genehmigten Plan. Einen Neustart mit Bootwechsel, authentisiertem Kontakt derselben Installation und erfolgreichem Folgeauftrag prüfen.
- Die Kundenbindung gilt auch für direkte IDs und gespeicherte Ergebnisse. Änderungen an Tokenrechten mit berechtigtem und fremdem Kunden sowie nach Widerruf prüfen. Für einen Kundenwechsel das Gerät neu aufnehmen. Die bisherige Historie gehört zum bisherigen Kunden.
- Ein Administrator-Skript braucht neben den Serverrechten den für diese Installation eingerichteten Helper. Bei `SCRIPT_HELPER_SCOPE_DENIED` zuerst Kunden- und Tokenrechte sowie die zentrale Geräteregel prüfen. [MCP-Zugang](docs/public-access.md)
- Beim Binärwechsel Geräteidentität, Zertifikate, Journale und Dateirechte erhalten. Bei Änderungen am Installer oder Selbstupdate den HTTPS-Installer beziehungsweise den regulären Updateabruf prüfen.
Für Skriptaufträge gilt Kapitel 0.8. Die Bibliothek veröffentlicht Skriptversionen. Gerätezuweisung und Ergebniskontrolle gehören zu „Aufträge“, die interaktive Entscheidung zu „Genehmigungen“. Änderungen an einem dieser Wege am Übergang zum nächsten prüfen. ## In der Entwicklungsumgebung arbeiten
## Betrieb und Freigabe Das Notebook ist der Entwicklungsrechner. Server und beide Testgäste sind getrennte Ziele. Für Builds, Transfer und Aktivierung die [Projektwerkzeuge](docs/development.md) verwenden. Vorhandene Artefakte dürfen für die Entwicklung über gepinntes SSH/SFTP bereitgestellt werden. Zielneustarts, echte Betriebssystemupdates und Löschungen brauchen einen konkreten Auftrag.
- Der dedizierte Server ist `discovery.ease-technologies.de`. Testclients sind die Cloud-Linux-VM und der Windows-11-Gast. Das Notebook dient ausschließlich der Entwicklung. Plattformspezifische Arbeit auf beiden Gästen darf parallel laufen. Plattformfunktionen jeweils nativ nachweisen. `credentials/` bleibt privat und von Git ausgeschlossen. Profile als Daten über die vorhandenen Parser lesen, Zugangswerte weder ausgeben noch ins Repository übernehmen. Zugangsdatenverzeichnis, Dateirechte und Hostprüfung sind in den [Betriebszugängen](docs/operations-access.md) beschrieben.
- Der produktive Geräteverkehr geht vom Client aus. SSH/SFTP ist im Entwicklungsbetrieb ausdrücklich für die direkte Bereitstellung vorhandener Artefakte zulässig. Der [Entwicklungsweg](docs/development.md) beschreibt Build, Transfer und Aktivierung. Zur Produktabnahme von Installer und Selbstupdate den jeweiligen Produktweg benutzen.
- Jeder **Skript- oder Wartungsjob** aus UI, MCP oder Automatik wird zunächst als `pending_approval` gespeichert. Erst eine berechtigte Person genehmigt den unveränderlichen Plan mit Ziel, Skriptbytes, Rechten, Grenzen und festen Versuchen in der WebUI. Vorher bleiben ausführbare Jobs, Outbox, Angebote und Startgrants leer. Policies begrenzen. Direkte API-/DB-Freigaben durch KI oder Automatik sind ausgeschlossen.
- Ausschließlich im expliziten dev/test-Profil darf ein sichtbar **simulierter Testprincipal** die tatsächliche WebUI per Browser bedienen. Audit bindet `approval_origin`, `testsimulation`, Principal und Plan. In Produktion gilt die menschliche Freigabe. Redelivery darf keine zweite Ausführung auslösen. Neue Versuche und Folgejobs brauchen eine eigene feste Freigabe.
- Passive Standardtelemetrie und gespeicherte Lesezugriffe laufen ohne Job. Version 1.33 spezifiziert zusätzlich die automatische Installation **veröffentlichter signierter Agent-Releases**. Der Releasepfad akzeptiert ausschließlich die festgelegten Agentkomponenten. Eine Live-Diagnose oder ein OS-Update ist ein Wartungsjob.
- WebUI und MCP sind öffentlich über HTTPS mit lokalem Passwort/TOTP beziehungsweise scoped Bearer-Tokens erreichbar. Der [öffentliche Zugang](docs/public-access.md) ist der maßgebliche Aufbau seit Spezifikation 1.35. Der separate dev/test-Zugang bleibt intern über den SSH-Tunnel erreichbar. Dockerports an Loopback binden, PostgreSQL intern betreiben. Für die öffentlichen Geräte- und Bootstrapwege TLS-Kette und SAN/SNI prüfen, für registrierte Geräte mTLS und Mandantenbindung durchsetzen. Der öffentliche Installer braucht einen auf dem frischen Gerät bereits vertrauenswürdigen TLS-Anker.
- `credentials/` bleibt ignoriert und privat (0700, Dateien 0600). Die [Zugangsanleitung](docs/operations-access.md) nennt Parser und bestätigte Hostpins. Profile ausschließlich als Daten verarbeiten, kein `source` oder `eval`. Schlüssel, Token und private Diagnoseausgaben gehören weder ins Repository noch in Agentkontexte.
- Bei einem normalen Binärwechsel Identität, PKI, Konfiguration, Journale und Dateirechte erhalten. Im aktuellen Entwicklungssystem dürfen ausdrücklich freigegebene Altanträge und blockierende Testprojektionen gezielt entfernt werden. Nach einer Bereinigung das Fehlen des Auftrags und den frischen Geräteabgleich prüfen. Zielreboots, OS-Updates und destruktive Tests brauchen einen konkreten Auftrag. Vom Status `unknown` führt nur der belegte Abgleich oder der dokumentierte WebUI-Abschluss weiter. Niemals blind wiederholen.
## Nachweise und Umfang
Teste die betroffene Funktion und den konkreten Fehlerpfad. Verwende vorhandene native Belege weiter. Kennzeichne geplante, noch nicht ausgeführte Befehle sowie fehlende Zugänge oder Werkzeuge. Historische APT-/MSI-/Rebootabnahmen, Terminal, RustDesk, PVE/PBS, Cluster und Backups sind keine Voraussetzungen für den aktuellen Lieferplan.
Für ein benötigtes Windows-Update-Wartungsfenster den [dokumentierten Operator](docs/windows-update-dev-window.md) wiederverwenden. Der temporäre SYSTEM-Helper bindet das aktuelle signierte Agentpaar und die Geräteidentität. Nach terminalem Ergebnis das Fenster schließen und den normalen Agent-/Updatebetrieb nachlesen. Eine echte OS-Installation gilt erst mit ihrem eigenen Zielergebnis als nachgewiesen.
Generated
+47 -128
View File
@@ -37,18 +37,6 @@ dependencies = [
"subtle", "subtle",
] ]
[[package]]
name = "ahash"
version = "0.8.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75"
dependencies = [
"cfg-if",
"once_cell",
"version_check",
"zerocopy",
]
[[package]] [[package]]
name = "allocator-api2" name = "allocator-api2"
version = "0.2.21" version = "0.2.21"
@@ -234,9 +222,6 @@ name = "bitflags"
version = "2.13.2" version = "2.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
dependencies = [
"serde_core",
]
[[package]] [[package]]
name = "block-buffer" name = "block-buffer"
@@ -721,17 +706,6 @@ version = "0.1.15"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48"
[[package]]
name = "flume"
version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "da0e4dd2a88388a1f4ccc7c9ce104604dab68d9f408dc34cd45823d5a9069095"
dependencies = [
"futures-core",
"futures-sink",
"spin",
]
[[package]] [[package]]
name = "fnv" name = "fnv"
version = "1.0.7" version = "1.0.7"
@@ -744,6 +718,12 @@ version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2"
[[package]]
name = "foldhash"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"
[[package]] [[package]]
name = "foreign-types" name = "foreign-types"
version = "0.3.2" version = "0.3.2"
@@ -967,15 +947,6 @@ dependencies = [
"tracing", "tracing",
] ]
[[package]]
name = "hashbrown"
version = "0.14.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1"
dependencies = [
"ahash",
]
[[package]] [[package]]
name = "hashbrown" name = "hashbrown"
version = "0.15.5" version = "0.15.5"
@@ -984,7 +955,7 @@ checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1"
dependencies = [ dependencies = [
"allocator-api2", "allocator-api2",
"equivalent", "equivalent",
"foldhash", "foldhash 0.1.5",
] ]
[[package]] [[package]]
@@ -992,14 +963,8 @@ name = "hashbrown"
version = "0.17.1" version = "0.17.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
[[package]]
name = "hashlink"
version = "0.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6ba4ff7128dee98c7dc9794b6a411377e1404dba1c97deb8d1a55297bd25d8af"
dependencies = [ dependencies = [
"hashbrown 0.14.5", "foldhash 0.2.0",
] ]
[[package]] [[package]]
@@ -1011,6 +976,15 @@ dependencies = [
"hashbrown 0.15.5", "hashbrown 0.15.5",
] ]
[[package]]
name = "hashlink"
version = "0.12.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a596f1b20ed2cc5ecac41a164aaebc7258057060f06c0cf7a2ba3991ee7990fb"
dependencies = [
"hashbrown 0.17.1",
]
[[package]] [[package]]
name = "heck" name = "heck"
version = "0.5.0" version = "0.5.0"
@@ -1418,9 +1392,9 @@ dependencies = [
[[package]] [[package]]
name = "libsqlite3-sys" name = "libsqlite3-sys"
version = "0.30.1" version = "0.39.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2e99fb7a497b1e3339bc746195567ed8d3e24945ecd636e3619d20b9de9e9149" checksum = "14a5f01b87b92705d07b433c06f96cbc764637d81a0bffb5734ce17cf0f9a2b3"
dependencies = [ dependencies = [
"cc", "cc",
"pkg-config", "pkg-config",
@@ -2239,7 +2213,7 @@ dependencies = [
[[package]] [[package]]
name = "rmm-agent-windows" name = "rmm-agent-windows"
version = "0.1.0" version = "0.1.16"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"base64 0.22.1", "base64 0.22.1",
@@ -2315,7 +2289,9 @@ name = "rmm-persistence"
version = "0.1.0" version = "0.1.0"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"sqlx", "sqlx-core",
"sqlx-macros",
"sqlx-postgres",
"uuid", "uuid",
] ]
@@ -2538,17 +2514,27 @@ dependencies = [
] ]
[[package]] [[package]]
name = "rusqlite" name = "rsqlite-vfs"
version = "0.32.1" version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7753b721174eb8ff87a9a0e799e2d7bc3749323e773db92e0984debb00019d6e" checksum = "353b74f9810d5b085b6c42c9d86a5f0fdb795553235cdd48753b32e3809d18a7"
dependencies = [
"thiserror",
]
[[package]]
name = "rusqlite"
version = "0.41.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "da9bba6f3506135e120a6586df05be18b48d18896600646a4bec8f993d91a594"
dependencies = [ dependencies = [
"bitflags", "bitflags",
"fallible-iterator", "fallible-iterator",
"fallible-streaming-iterator", "fallible-streaming-iterator",
"hashlink 0.9.1", "hashlink 0.12.2",
"libsqlite3-sys", "libsqlite3-sys",
"smallvec", "smallvec",
"sqlite-wasm-rs",
] ]
[[package]] [[package]]
@@ -2871,9 +2857,6 @@ name = "spin"
version = "0.9.9" version = "0.9.9"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3763264f6b73151db08c50ff20d7d8a0b8796e021cdea7ceedad07b80155fa0e" checksum = "3763264f6b73151db08c50ff20d7d8a0b8796e021cdea7ceedad07b80155fa0e"
dependencies = [
"lock_api",
]
[[package]] [[package]]
name = "spki" name = "spki"
@@ -2885,6 +2868,16 @@ dependencies = [
"der", "der",
] ]
[[package]]
name = "sqlite-wasm-rs"
version = "0.6.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a6cd504cecbfe7eef649988840f9a6cb768d11085efec138f8e99f160632d867"
dependencies = [
"cc",
"rsqlite-vfs",
]
[[package]] [[package]]
name = "sqlx" name = "sqlx"
version = "0.8.6" version = "0.8.6"
@@ -2893,9 +2886,7 @@ checksum = "1fefb893899429669dcdd979aff487bd78f4064e5e7907e4269081e0ef7d97dc"
dependencies = [ dependencies = [
"sqlx-core", "sqlx-core",
"sqlx-macros", "sqlx-macros",
"sqlx-mysql",
"sqlx-postgres", "sqlx-postgres",
"sqlx-sqlite",
] ]
[[package]] [[package]]
@@ -2966,58 +2957,12 @@ dependencies = [
"serde_json", "serde_json",
"sha2 0.10.9", "sha2 0.10.9",
"sqlx-core", "sqlx-core",
"sqlx-mysql",
"sqlx-postgres", "sqlx-postgres",
"sqlx-sqlite",
"syn 2.0.119", "syn 2.0.119",
"tokio", "tokio",
"url", "url",
] ]
[[package]]
name = "sqlx-mysql"
version = "0.8.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aa003f0038df784eb8fecbbac13affe3da23b45194bd57dba231c8f48199c526"
dependencies = [
"atoi",
"base64 0.22.1",
"bitflags",
"byteorder",
"bytes",
"chrono",
"crc",
"digest 0.10.7",
"dotenvy",
"either",
"futures-channel",
"futures-core",
"futures-io",
"futures-util",
"generic-array",
"hex",
"hkdf",
"hmac",
"itoa",
"log",
"md-5",
"memchr",
"once_cell",
"percent-encoding",
"rand 0.8.8",
"rsa",
"serde",
"sha1",
"sha2 0.10.9",
"smallvec",
"sqlx-core",
"stringprep",
"thiserror",
"tracing",
"uuid",
"whoami",
]
[[package]] [[package]]
name = "sqlx-postgres" name = "sqlx-postgres"
version = "0.8.6" version = "0.8.6"
@@ -3057,32 +3002,6 @@ dependencies = [
"whoami", "whoami",
] ]
[[package]]
name = "sqlx-sqlite"
version = "0.8.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2d12fe70b2c1b4401038055f90f151b78208de1f9f89a7dbfd41587a10c3eea"
dependencies = [
"atoi",
"chrono",
"flume",
"futures-channel",
"futures-core",
"futures-executor",
"futures-intrusive",
"futures-util",
"libsqlite3-sys",
"log",
"percent-encoding",
"serde",
"serde_urlencoded",
"sqlx-core",
"thiserror",
"tracing",
"url",
"uuid",
]
[[package]] [[package]]
name = "sse-stream" name = "sse-stream"
version = "0.2.6" version = "0.2.6"
+2 -1
View File
@@ -18,13 +18,14 @@ openssl = "0.10.75"
prost = "0.14.1" prost = "0.14.1"
rand = "0.9.2" rand = "0.9.2"
reqwest = { version = "0.12.24", default-features = false, features = ["rustls-tls", "json"] } reqwest = { version = "0.12.24", default-features = false, features = ["rustls-tls", "json"] }
rusqlite = { version = "0.41.1", features = ["bundled", "fallible_uint"] }
rustls = { version = "0.23.35", default-features = false, features = ["ring", "std", "tls12"] } rustls = { version = "0.23.35", default-features = false, features = ["ring", "std", "tls12"] }
rustls-pemfile = "2.2.0" rustls-pemfile = "2.2.0"
serde = { version = "1.0.228", features = ["derive"] } serde = { version = "1.0.228", features = ["derive"] }
serde_json = "1.0.145" serde_json = "1.0.145"
sha2 = "0.10.9" sha2 = "0.10.9"
schemars = { version = "1", features = ["chrono04", "uuid1"] } schemars = { version = "1", features = ["chrono04", "uuid1"] }
sqlx = { version = "0.8.6", default-features = false, features = ["runtime-tokio-rustls", "postgres", "uuid", "chrono", "json", "migrate", "macros"] } sqlx = { version = "0.8.6", default-features = false, features = ["runtime-tokio-rustls", "postgres"] }
tokio = { version = "1.48.0", features = ["full"] } tokio = { version = "1.48.0", features = ["full"] }
tokio-rustls = { version = "0.26.4", default-features = false, features = ["ring", "tls12"] } tokio-rustls = { version = "0.26.4", default-features = false, features = ["ring", "tls12"] }
tokio-tungstenite = { version = "0.28.0", features = ["rustls-tls-webpki-roots"] } tokio-tungstenite = { version = "0.28.0", features = ["rustls-tls-webpki-roots"] }
+16 -14
View File
@@ -1,22 +1,24 @@
# Rust Discovery # Rust Discovery
Rust Discovery verwaltet Linux- und Windows-Geräte über einen dedizierten Server mit WebUI und MCP. Die Clients melden sich ausgehend per HTTPS, liefern Inventar und Heartbeats, holen genehmigte Skripte ab und melden ihre Ergebnisse zurück. Wiederkehrende Aufgaben lassen sich als versionierte Skripte hinterlegen. Neue Geräte werden über einen HTTPS-Installer aufgenommen und beziehen signierte Agentupdates vom Server. Rust Discovery ist eine Remote-Monitoring- und Management-Plattform für Linux- und Windows-Geräte. Der Server verwaltet Kunden, Geräte, Skripte und Aufträge. Die Agenten melden sich von den Geräten aus, liefern Inventar und Heartbeats, holen genehmigte Skripte ab und melden die Ausgabe zurück.
**[Aktueller Stand und Schritt-für-Schritt-Plan](docs/mvp-completion-plan.md)** · [Entwicklungsbefehle](docs/development.md) · [Übergabe und Zugänge](docs/handover.md) **Der MVP ist abgenommen.** Auf Ubuntu und Windows 11 wurden ein eigenes Administrator-Skript, eine Skriptversion aus der Bibliothek, ein echter Neustart und ein weiterer Auftrag nach der Wiederanmeldung geprüft. Die Abnahme enthält die Ausgaben und den installierten Stand beider Geräte. [MVP-Abnahme](docs/mvp-completion-plan.md)
## Stand am 17. November 2026 ## Von der Geräteauswahl zum Ergebnis
Die beiden über den öffentlichen Installer aufgenommenen Geräte haben ein Bibliotheksskript mit Exitcode 0 zurückgemeldet. WebUI und MCP zeigen das Ergebnis desselben Versuchs. Der Linux-Timer und der Windows-Updaterdienst haben auf den Testgästen selbstständig veröffentlichte Versionen übernommen. Die integrierte Windows-Update-Vorlage erfordert gesondert eingerichtete Wartungsrechte. [Aktueller Prüfstand](docs/mvp-completion-plan.md) 1. In der WebUI den Kunden und unter **Geräte** die Zielmaschine auswählen.
2. Unter **Aufträge** ein eigenes Skript eingeben oder eine feste Version aus **Skripte** auswählen. Ausführungskonto und Zeitfenster prüfen und den Auftrag einreichen.
3. Unter **Genehmigungen** prüft eine berechtigte Person den Skriptinhalt und die Ziele und entscheidet über die Ausführung.
4. Unter **Aufträge** den Auftrag öffnen und pro Gerät Ergebnis, Ausgabe und Exitcode lesen. Über das Gerätedetail sind seine letzten Aufträge ebenfalls erreichbar.
## Einstieg in den Code MCP kann Skriptversionen veröffentlichen, eigene Skripte und Bibliotheksversionen für berechtigte Kunden einreichen sowie Ergebnisse lesen. Die persönliche Genehmigung erfolgt in der WebUI. [WebUI öffnen](https://discovery.ease-technologies.de:8443/) · [Zugang und MCP-Rechte](docs/public-access.md)
| Aufgabe | Einstieg | ## Einstieg ins Projekt
| Ich möchte … | Einstieg |
| --- | --- | | --- | --- |
| Verwaltungs-API, UI und MCP | [Server-Routen](crates/server/src/main.rs), [MCP-Werkzeuge](crates/server/src/mcp.rs), [WebUI](web/src/main.tsx) | | einen Entwicklungsauftrag übernehmen | [Agenthinweise](AGENTS.md) und [Übergabe](docs/handover.md) |
| Gerätekommunikation und Jobs | [HTTPS-Poll](crates/server/src/agent_http.rs), [Jobzustellung](crates/server/src/job_gateway.rs), [gemeinsamer Agentkern](crates/agent-core/src/lib.rs) | | den Funktionsumfang und die Grenzen des MVP verstehen | [Produktvertrag](Rust_RMM_Implementierungsspezifikation.md) |
| Linux- und Windows-Dienst | [Linux-Agent](crates/agent/src/main.rs), [Windows-Laufzeit](crates/agent-windows/src/runtime.rs) | | ein Gerät aufnehmen oder einen Agenten aktualisieren | [Linux](deploy/linux/README.md) oder [Windows](deploy/windows/README.md) |
| Releases und Selbstupdate | [Releasekatalog und Downloads](crates/server/src/agent_updates.rs), [Manifestprüfung](crates/updater/src/manifest.rs) | | eine Änderung bauen, testen oder bereitstellen | [Entwicklung und Deployment](docs/development.md) |
| einen Betriebsvorgang auf dem Testsystem prüfen | [Betriebszugänge](docs/operations-access.md) und [Abnahmebelege](docs/mvp-completion-plan.md) |
Der Server läuft auf `discovery.ease-technologies.de`. Die [öffentliche WebUI](https://discovery.ease-technologies.de:8443/) verwendet Passwort und TOTP. Der [MCP-Endpunkt](https://discovery.ease-technologies.de:8443/mcp) verwendet eigene Bearer-Tokens. [Einrichtung und Betrieb](docs/public-access.md) Die Cloud-Linux-VM und der Windows-11-Gast dienen als Testgeräte. Das Notebook ist der Entwicklungsrechner.
[Agenthinweise](AGENTS.md) · [Spezifikation](Rust_RMM_Implementierungsspezifikation.md) · [Entscheidungen](docs/project-decisions.md) · [Historische Linux-Abnahme](docs/mvp-final-audit.md) · [Windows-Nachweise](docs/windows-gates.md)
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -19,7 +19,7 @@ uuid.workspace = true
rmm-domain = { path = "../domain" } rmm-domain = { path = "../domain" }
rmm-protocol = { path = "../protocol" } rmm-protocol = { path = "../protocol" }
rmm-updater-handoff = { path = "../updater-handoff" } rmm-updater-handoff = { path = "../updater-handoff" }
rusqlite = { version = "0.32.1", features = ["bundled"] } rusqlite.workspace = true
ed25519-dalek = "=2.2.0" ed25519-dalek = "=2.2.0"
[dev-dependencies] [dev-dependencies]
@@ -62,7 +62,7 @@ impl Snapshot {
let db = Connection::open_with_flags(path, OpenFlags::SQLITE_OPEN_READ_ONLY)?; let db = Connection::open_with_flags(path, OpenFlags::SQLITE_OPEN_READ_ONLY)?;
db.execute_batch("PRAGMA query_only=ON; PRAGMA trusted_schema=OFF; BEGIN;")?; db.execute_batch("PRAGMA query_only=ON; PRAGMA trusted_schema=OFF; BEGIN;")?;
ensure!( ensure!(
db.is_readonly(rusqlite::DatabaseName::Main)?, db.is_readonly(rusqlite::MAIN_DB)?,
"read-only database required" "read-only database required"
); );
Ok(Self { db, _held: handles }) Ok(Self { db, _held: handles })
+39 -15
View File
@@ -782,10 +782,10 @@ impl<V: Ed25519Verifier> HelperSync<V> {
let d = decisions let d = decisions
.get(&id) .get(&id)
.context("ROOT_ATTEMPT_OMITTED_FROM_DECISION")?; .context("ROOT_ATTEMPT_OMITTED_FROM_DECISION")?;
validate_summary(row, local)?; let unreported = validate_summary(row, local)?;
validate_decision(row, local, d)?; validate_decision(row, local, d, unreported)?;
if d.unlock { if d.unlock {
let bytes = unlock_outcome(row, d, current_boot)?; let bytes = unlock_outcome(row, d, current_boot, unreported.then_some(local))?;
if d.outcome_state == "closed_unknown" { if d.outcome_state == "closed_unknown" {
crate::ledger::retain_closure_original( crate::ledger::retain_closure_original(
&tx, &tx,
@@ -1636,22 +1636,33 @@ fn definitive(row: &LocalAttempt) -> bool {
"succeeded" | "failed" | "cancelled" | "expired" | "closed_unknown" "succeeded" | "failed" | "cancelled" | "expired" | "closed_unknown"
) && !row.outcome_bytes.is_empty() ) && !row.outcome_bytes.is_empty()
} }
fn validate_summary(row: &LocalAttempt, a: &AttemptView) -> Result<()> { fn validate_summary(row: &LocalAttempt, a: &AttemptView) -> Result<bool> {
let unreported = row.state == "unknown"
&& row.outcome_sha256.is_empty()
&& row.outcome_bytes.is_empty()
&& row.update_handoff_bytes.is_empty()
&& crate::reconcile::uncertain_agent_outcome(&a.state, &a.outcome_bytes, &a.outcome_sha256);
ensure!( ensure!(
a.job_payload_hash == row.job_payload_hash a.job_payload_hash == row.job_payload_hash
&& a.grant_id == row.grant_id.to_string() && a.grant_id == row.grant_id.to_string()
&& a.consumption == "consumed" && a.consumption == "consumed"
&& a.state == row.state
&& a.revision >= row.revision && a.revision >= row.revision
&& a.original_boot_id == row.original_boot_id.to_string() && a.original_boot_id == row.original_boot_id.to_string()
&& a.outcome_sha256 == row.outcome_sha256
&& a.update_handoff_bytes == row.update_handoff_bytes && a.update_handoff_bytes == row.update_handoff_bytes
&& (a.outcome_bytes.is_empty() || a.outcome_bytes == row.outcome_bytes), && (unreported
|| (a.state == row.state
&& a.outcome_sha256 == row.outcome_sha256
&& (a.outcome_bytes.is_empty() || a.outcome_bytes == row.outcome_bytes))),
"ROOT_SNAPSHOT_REQUEST_MISMATCH" "ROOT_SNAPSHOT_REQUEST_MISMATCH"
); );
Ok(()) Ok(unreported)
} }
fn validate_decision(row: &LocalAttempt, a: &AttemptView, d: &AttemptDecision) -> Result<()> { fn validate_decision(
row: &LocalAttempt,
a: &AttemptView,
d: &AttemptDecision,
unreported: bool,
) -> Result<()> {
if !row.update_handoff_bytes.is_empty() { if !row.update_handoff_bytes.is_empty() {
let proof = let proof =
rmm_domain::agent_update::UpdateInflightProof::from_bytes(&row.update_handoff_bytes) rmm_domain::agent_update::UpdateInflightProof::from_bytes(&row.update_handoff_bytes)
@@ -1686,7 +1697,7 @@ fn validate_decision(row: &LocalAttempt, a: &AttemptView, d: &AttemptDecision) -
&& d.original_boot_id == Some(row.original_boot_id) && d.original_boot_id == Some(row.original_boot_id)
&& (d.revision >= a.revision || (!d.unlock && d.outcome_state == "unknown")) && (d.revision >= a.revision || (!d.unlock && d.outcome_state == "unknown"))
&& d.previous_outcome_sha256.as_deref() && d.previous_outcome_sha256.as_deref()
== (!row.outcome_sha256.is_empty()).then_some(row.outcome_sha256.as_str()), == (!a.outcome_sha256.is_empty()).then_some(a.outcome_sha256.as_str()),
"ROOT_SIGNED_ATTEMPT_BINDING" "ROOT_SIGNED_ATTEMPT_BINDING"
); );
ensure!( ensure!(
@@ -1697,11 +1708,26 @@ fn validate_decision(row: &LocalAttempt, a: &AttemptView, d: &AttemptDecision) -
), ),
"UNKNOWN_CANNOT_UNLOCK" "UNKNOWN_CANNOT_UNLOCK"
); );
ensure!(
!unreported
|| (!d.unlock && d.outcome_state == "unknown")
|| (d.unlock
&& d.outcome_state == "closed_unknown"
&& d.reason == "OPERATOR_CLOSED_UNKNOWN"),
"ROOT_UNREPORTED_OUTCOME_CLOSURE_REQUIRED"
);
Ok(()) Ok(())
} }
fn unlock_outcome(row: &LocalAttempt, d: &AttemptDecision, current_boot: Uuid) -> Result<Vec<u8>> { fn unlock_outcome(
row: &LocalAttempt,
d: &AttemptDecision,
current_boot: Uuid,
unreported: Option<&AttemptView>,
) -> Result<Vec<u8>> {
let bytes = if d.outcome_bytes.is_empty() { let bytes = if d.outcome_bytes.is_empty() {
row.outcome_bytes.clone() unreported
.map_or(&row.outcome_bytes, |a| &a.outcome_bytes)
.clone()
} else { } else {
d.outcome_bytes.clone() d.outcome_bytes.clone()
}; };
@@ -1712,9 +1738,7 @@ fn unlock_outcome(row: &LocalAttempt, d: &AttemptDecision, current_boot: Uuid) -
&& o.state == d.outcome_state, && o.state == d.outcome_state,
"ROOT_CANONICAL_UNLOCK_OUTCOME" "ROOT_CANONICAL_UNLOCK_OUTCOME"
); );
if bytes != row.outcome_bytes if bytes != row.outcome_bytes && crate::reconcile::operator_closure(&d.reason, &row.state, &o) {
&& crate::reconcile::operator_closure(&d.reason, &row.state, &o)
{
return Ok(bytes); return Ok(bytes);
} }
if bytes != row.outcome_bytes { if bytes != row.outcome_bytes {
+3 -1
View File
@@ -24,7 +24,6 @@ pub fn accept(
&& hex_hash(&offer.plan_hash), && hex_hash(&offer.plan_hash),
"OFFER_BINDING" "OFFER_BINDING"
); );
ensure!(supported(&job), "UNSUPPORTED_CAPABILITY");
let bytes = offer.encode_to_vec(); let bytes = offer.encode_to_vec();
let existing: Option<Vec<u8>> = db let existing: Option<Vec<u8>> = db
.query_row( .query_row(
@@ -37,6 +36,9 @@ pub fn accept(
ensure!(old == bytes, "OFFER_CONFLICT"); ensure!(old == bytes, "OFFER_CONFLICT");
return Ok(false); return Ok(false);
} }
// An identical journal receipt is evidence of a previous delivery. Current
// executable capabilities apply to newly accepted offers.
ensure!(supported(&job), "UNSUPPORTED_CAPABILITY");
let count: i64 = db.query_row("SELECT count(*) FROM job_attempts", [], |r| r.get(0))?; let count: i64 = db.query_row("SELECT count(*) FROM job_attempts", [], |r| r.get(0))?;
ensure!(count < 10000, "JOURNAL_CAPACITY_NEW_EFFECTS_BLOCKED"); ensure!(count < 10000, "JOURNAL_CAPACITY_NEW_EFFECTS_BLOCKED");
db.execute( db.execute(
+198 -15
View File
@@ -365,7 +365,6 @@ impl<V: Ed25519Verifier> ClientSync<V> {
&& original.helper_previous_decision_id == h.to_string() && original.helper_previous_decision_id == h.to_string()
&& original.previous_request_id.is_empty() && original.previous_request_id.is_empty()
&& original.journal_complete && original.journal_complete
&& original.durable_message_ids.is_empty()
&& decision.issued_at <= now && decision.issued_at <= now
&& decision.connection_generation <= channel.connection_generation && decision.connection_generation <= channel.connection_generation
&& previous.connection_generation <= decision.connection_generation && previous.connection_generation <= decision.connection_generation
@@ -379,6 +378,7 @@ impl<V: Ed25519Verifier> ClientSync<V> {
&& helper.checkpoint >= decision.helper_checkpoint, && helper.checkpoint >= decision.helper_checkpoint,
"CLOSED_CONTROL_EXACT_PARTIAL_EDGE" "CLOSED_CONTROL_EXACT_PARTIAL_EDGE"
); );
verify_closed_result_messages(db, &original, &decision)?;
let current = attempts(db, ledger, &self.binding)?; let current = attempts(db, ledger, &self.binding)?;
ensure!( ensure!(
current.len() == original.attempts.len() current.len() == original.attempts.len()
@@ -399,7 +399,8 @@ impl<V: Ed25519Verifier> ClientSync<V> {
); );
for row in &current { for row in &current {
ensure!( ensure!(
terminal(&row.state) && row.update_handoff_bytes.is_empty(), matches!(row.state.as_str(), "succeeded" | "failed" | "cancelled" | "expired")
&& row.update_handoff_bytes.is_empty(),
"CLOSED_CONTROL_DEFINITIVE_ONLY" "CLOSED_CONTROL_DEFINITIVE_ONLY"
); );
let old = original let old = original
@@ -1018,9 +1019,9 @@ impl<V: Ed25519Verifier> ClientSync<V> {
} else { } else {
for d in decision.attempts.iter().filter(|d| d.unlock) { for d in decision.attempts.iter().filter(|d| d.unlock) {
let grant = d.grant_id.context("UNLOCK_GRANT_MISSING")?; let grant = d.grant_id.context("UNLOCK_GRANT_MISSING")?;
let (agent,generation,job,attempt,previous):(String,u64,String,String,Option<Vec<u8>>)=tx.query_row( let (agent,generation,job,attempt,previous,start):(String,u64,String,String,Option<Vec<u8>>,Option<Vec<u8>>)=tx.query_row(
"SELECT agent,generation,job,attempt,COALESCE((SELECT outcome FROM execution_evidence WHERE execution_evidence.grant_id=consumed.grant_id),result) FROM consumed WHERE grant_id=?1", "SELECT c.agent,c.generation,c.job,c.attempt,COALESCE(e.outcome,c.result),e.start FROM consumed c LEFT JOIN execution_evidence e USING(grant_id) WHERE c.grant_id=?1",
[grant.to_string()],|r|Ok((r.get(0)?,r.get(1)?,r.get(2)?,r.get(3)?,r.get(4)?)))?; [grant.to_string()],|r|Ok((r.get(0)?,r.get(1)?,r.get(2)?,r.get(3)?,r.get(4)?,r.get(5)?)))?;
ensure!( ensure!(
agent == self.binding.agent_id.to_string() agent == self.binding.agent_id.to_string()
&& generation == self.binding.enrollment_generation && generation == self.binding.enrollment_generation
@@ -1033,13 +1034,61 @@ impl<V: Ed25519Verifier> ClientSync<V> {
Some(&self.binding), Some(&self.binding),
grant, grant,
)?; )?;
let previous = resolved let previous = resolved.or(previous);
.or(previous) let summary = gate
.context("LOCAL_UNLOCK_PREVIOUS_OUTCOME_MISSING")?; .request
let original = previous.clone(); .attempts
let prior = canonical_outcome_bytes(&serde_json::from_slice::<ReconciledOutcome>( .iter()
&previous, .find(|a| a.job_id == job && a.attempt_id == attempt)
)?)?; .context("LOCAL_UNLOCK_ATTEMPT_MISSING")?;
let closure = d.reason == "OPERATOR_CLOSED_UNKNOWN"
&& d.outcome_state == "closed_unknown"
&& summary.consumption == "consumed"
&& uncertain_agent_outcome(
&summary.state,
&summary.outcome_bytes,
&summary.outcome_sha256,
);
let prior = match &previous {
Some(bytes) => {
let canonical = canonical_outcome_bytes(&serde_json::from_slice(bytes)?)?;
if closure
&& summary.state == "closed_unknown"
&& uncertain_agent_outcome("unknown", &canonical, &hash(&canonical))
{
summary.outcome_bytes.clone()
} else {
canonical
}
}
None => {
ensure!(closure, "LOCAL_UNLOCK_PREVIOUS_OUTCOME_MISSING");
let start: serde_json::Value = serde_json::from_slice(
&start.context("LOCAL_UNLOCK_ORIGINAL_START_MISSING")?,
)?;
let request: crate::auth::Request =
serde_json::from_value(start["request"].clone())?;
let permit: rmm_domain::jobs::ExecutionPermitPayload =
serde_json::from_slice(&request.permit_bytes)?;
let (original, permit) = self.binding.verify_with(
&request,
permit.not_before,
&self.verifier,
)?;
ensure!(
permit.grant_id == grant
&& original.job_id == d.job_id
&& original.attempt_id == d.attempt_id
&& hash(&request.job_bytes) == d.job_payload_hash
&& Some(permit.authorization_id) == d.authorization_id
&& Some(permit.plan_hash.as_str()) == d.plan_hash.as_deref()
&& start["previous_boot_id"].as_str()
== d.original_boot_id.map(|id| id.to_string()).as_deref(),
"LOCAL_UNLOCK_ORIGINAL_START_BINDING"
);
summary.outcome_bytes.clone()
}
};
ensure!( ensure!(
d.previous_outcome_sha256.as_deref() == Some(hash(&prior).as_str()), d.previous_outcome_sha256.as_deref() == Some(hash(&prior).as_str()),
"LOCAL_UNLOCK_PREVIOUS_OUTCOME_MISMATCH" "LOCAL_UNLOCK_PREVIOUS_OUTCOME_MISMATCH"
@@ -1054,7 +1103,8 @@ impl<V: Ed25519Verifier> ClientSync<V> {
terminal(&outcome.state) terminal(&outcome.state)
&& outcome.state == d.outcome_state && outcome.state == d.outcome_state
&& canonical_outcome_bytes(&outcome)? == bytes && canonical_outcome_bytes(&outcome)? == bytes
&& d.outcome_sha256.as_deref() == Some(hash(&bytes).as_str()), && d.outcome_sha256.as_deref() == Some(hash(&bytes).as_str())
&& (previous.is_some() || operator_closure(&d.reason, "unknown", &outcome)),
"LOCAL_UNLOCK_CANONICAL_OUTCOME" "LOCAL_UNLOCK_CANONICAL_OUTCOME"
); );
let preserve = crate::windows_system_nonstart::preserve_original_unlock( let preserve = crate::windows_system_nonstart::preserve_original_unlock(
@@ -1064,7 +1114,12 @@ impl<V: Ed25519Verifier> ClientSync<V> {
&bytes, &bytes,
)?; )?;
if outcome.state == "closed_unknown" { if outcome.state == "closed_unknown" {
crate::ledger::retain_closure_original(&tx, grant, &original, &bytes)?; crate::ledger::retain_closure_original(
&tx,
grant,
previous.as_deref().unwrap_or_default(),
&bytes,
)?;
} }
tx.execute( tx.execute(
"UPDATE consumed SET result=?2 WHERE grant_id=?1", "UPDATE consumed SET result=?2 WHERE grant_id=?1",
@@ -1170,6 +1225,81 @@ pub fn archive_events(db: &Connection) -> Result<()> {
} }
Ok(()) Ok(())
} }
/// A partial control edge can contain the result that closed an attempt, and
/// an earlier unknown report for that same grant. Only account for archived
/// messages here. Never ACK an event, change its state or replay a result.
fn verify_closed_result_messages(
db: &Connection,
request: &SyncRequest,
decision: &ReconcileDecisionPayload,
) -> Result<()> {
for id in &request.durable_message_ids {
let raw: Vec<u8> = db.query_row(
"SELECT envelope FROM reconcile_results WHERE id=?1",
[id],
|r| r.get(0),
)?;
let envelope = Envelope::decode(raw.as_slice())?;
let Some(Payload::JobResult(result)) = &envelope.payload else {
anyhow::bail!("CLOSED_CONTROL_EXPECTED_RESULT");
};
let attempt = request
.attempts
.iter()
.find(|a| {
a.job_id == result.job_id
&& a.attempt_id == result.attempt_id
&& a.grant_id == result.grant_id
})
.context("CLOSED_CONTROL_ARCHIVED_ATTEMPT")?;
let final_envelope = attempt
.result_envelope
.as_ref()
.context("CLOSED_CONTROL_FINAL_ENVELOPE")?;
let final_id = Uuid::parse_str(&attempt.result_message_id)?;
let persisted: bool = db.query_row(
"SELECT EXISTS(SELECT 1 FROM reconcile_receipts WHERE id=?1 AND decision_id=?2)",
params![attempt.result_message_id, decision.decision_id.to_string()],
|r| r.get(0),
)?;
ensure!(
persisted
&& decision.acknowledged_message_ids.contains(&final_id)
&& request
.durable_message_ids
.contains(&attempt.result_message_id)
&& final_envelope.message_id == attempt.result_message_id
&& envelope.message_id == *id
&& envelope.encode_to_vec() == raw
&& rmm_protocol::valid_envelope(
&envelope,
&decision.agent_id.to_string(),
final_envelope.connection_generation
)
&& envelope.boot_id == final_envelope.boot_id
&& matches!(
attempt.state.as_str(),
"succeeded" | "failed" | "cancelled" | "expired"
)
&& !result.grant_id.is_empty(),
"CLOSED_CONTROL_FINAL_RESULT_RECEIPT"
);
ensure!(
if *id == attempt.result_message_id {
envelope == *final_envelope
&& result.revision == attempt.revision
&& result.state == attempt.state
&& canonical_outcome_bytes(&outcome(result)?)? == attempt.outcome_bytes
} else {
result.state == "unknown"
&& result.revision < attempt.revision
&& envelope.sequence < final_envelope.sequence
},
"CLOSED_CONTROL_CONFLICTING_ARCHIVED_RESULT"
);
}
Ok(())
}
fn pending_ids(db: &Connection) -> Result<Vec<String>> { fn pending_ids(db: &Connection) -> Result<Vec<String>> {
let mut statement = db.prepare("SELECT id,payload FROM job_events ORDER BY id")?; let mut statement = db.prepare("SELECT id,payload FROM job_events ORDER BY id")?;
let rows = statement let rows = statement
@@ -1228,6 +1358,32 @@ pub(crate) fn operator_closure(
&& outcome.evidence["closed_by_human"] == true && outcome.evidence["closed_by_human"] == true
&& outcome.evidence["retry"] == false && outcome.evidence["retry"] == false
} }
/// An interrupted agent can record its own uncertainty while the independently
/// consumed helper grant has no result. Neither witness establishes an effect.
pub(crate) fn uncertain_agent_outcome(state: &str, bytes: &[u8], digest: &str) -> bool {
if bytes.is_empty() || hash(bytes) != digest {
return false;
}
let Ok(outcome) = serde_json::from_slice::<ReconciledOutcome>(bytes) else {
return false;
};
canonical_outcome_bytes(&outcome).is_ok_and(|canonical| canonical == bytes)
&& outcome.state == state
&& !outcome.output_truncated
&& !outcome.reboot_required
&& (operator_closure("OPERATOR_CLOSED_UNKNOWN", "unknown", &outcome)
|| (state == "unknown"
&& matches!(
outcome.error_code.as_str(),
"AGENT_PROCESS_INTERRUPTED" | "HELPER_TRANSPORT_EFFECT_UNKNOWN"
)
&& outcome.exit_code.is_none()
&& outcome.stdout.is_empty()
&& outcome.stderr.is_empty()
&& outcome.evidence["postconditions_passed"] == false))
}
fn optional_uuid(s: &str) -> Result<Option<Uuid>> { fn optional_uuid(s: &str) -> Result<Option<Uuid>> {
if s.is_empty() { if s.is_empty() {
Ok(None) Ok(None)
@@ -1376,6 +1532,24 @@ fn attempts(db: &Connection, ledger: &Connection, binding: &Binding) -> Result<V
result_envelope = Some(envelope); result_envelope = Some(envelope);
} }
} }
// The signed closure projection can commit before either consumption
// ledger. A fresh signed check may then finish the remaining writes.
if state == "closed_unknown"
&& consumption == "consumed"
&& (canonical.is_empty()
|| uncertain_agent_outcome("unknown", &canonical, &hash(&canonical)))
{
let closed: Vec<u8> = db.query_row(
"SELECT outcome FROM reconcile_outcomes WHERE job=?1 AND attempt=?2",
params![offer.job_id, offer.attempt_id],
|r| r.get(0),
)?;
ensure!(
uncertain_agent_outcome(&state, &closed, &hash(&closed)),
"LOCAL_CLOSURE_OUTCOME_MISMATCH"
);
canonical = closed;
}
if !canonical.is_empty() { if !canonical.is_empty() {
let o: ReconciledOutcome = serde_json::from_slice(&canonical)?; let o: ReconciledOutcome = serde_json::from_slice(&canonical)?;
ensure!(o.state == state, "LOCAL_OUTCOME_STATE_MISMATCH"); ensure!(o.state == state, "LOCAL_OUTCOME_STATE_MISMATCH");
@@ -1670,6 +1844,15 @@ fn merge_helper(local: &mut [SyncAttempt], helper: &HelperSnapshot) -> Result<()
"HELPER_ATTEMPT_BINDING" "HELPER_ATTEMPT_BINDING"
); );
if h.consumption != "unconsumed" { if h.consumption != "unconsumed" {
let unreported = h.state == "unknown"
&& h.consumption == "consumed"
&& h.outcome_bytes.is_empty()
&& h.outcome_sha256.is_empty()
&& h.update_handoff_bytes.is_empty()
&& a.consumption == "consumed"
&& a.grant_id == h.grant_id
&& a.original_boot_id == h.original_boot_id
&& uncertain_agent_outcome(&a.state, &a.outcome_bytes, &a.outcome_sha256);
if !h.update_handoff_bytes.is_empty() { if !h.update_handoff_bytes.is_empty() {
ensure!( ensure!(
h.state == "running" && a.state == "running" && a.outcome_bytes.is_empty(), h.state == "running" && a.state == "running" && a.outcome_bytes.is_empty(),
@@ -1680,7 +1863,7 @@ fn merge_helper(local: &mut [SyncAttempt], helper: &HelperSnapshot) -> Result<()
a.grant_id = h.grant_id.clone(); a.grant_id = h.grant_id.clone();
a.consumption = h.consumption.clone(); a.consumption = h.consumption.clone();
ensure!( ensure!(
a.outcome_sha256 == h.outcome_sha256, a.outcome_sha256 == h.outcome_sha256 || unreported,
"HELPER_OUTCOME_MISMATCH" "HELPER_OUTCOME_MISMATCH"
); );
if a.original_boot_id.is_empty() { if a.original_boot_id.is_empty() {
+34
View File
@@ -326,6 +326,40 @@ fn consumed_attempt_and_unknown_lock_survive_reopen_without_reexecution() {
std::fs::remove_file(path).unwrap(); std::fs::remove_file(path).unwrap();
} }
#[test]
fn retired_reboot_redelivery_preserves_the_original_attempt_and_enrollment() {
let (binding, request, permit, _) = fixture();
let mut old = binding.job(&request.job_bytes).unwrap();
old.action = Action::Reboot {
reason: "historical reboot".into(),
reconnect_timeout_seconds: 60,
dependency_group: "test".into(),
};
old.execution_identity = "root".into();
let payload = encode(&old).unwrap();
let offer = JobOffer {
job_id: old.job_id.to_string(),
attempt_id: old.attempt_id.to_string(),
job_payload_hash: hash(&payload),
payload_bytes: payload,
plan_hash: permit.plan_hash,
authorization_id: permit.authorization_id.to_string(),
};
let db = Connection::open_in_memory().unwrap();
db.execute_batch("CREATE TABLE job_attempts(job TEXT,attempt TEXT,offer BLOB,state TEXT,PRIMARY KEY(job,attempt))").unwrap();
assert!(jobs::accept(&db, &binding, &offer, |_| false).is_err());
assert!(jobs::accept(&db, &binding, &offer, |_| true).unwrap());
db.execute("UPDATE job_attempts SET state='unknown'", []).unwrap();
assert!(!jobs::accept(&db, &binding, &offer, |_| panic!("historical delivery invoked the execution probe")).unwrap());
let mut altered = offer.clone();
altered.authorization_id = Uuid::new_v4().to_string();
assert!(jobs::accept(&db, &binding, &altered, |_| false).is_err());
let mut other = binding;
other.enrollment_generation += 1;
assert!(jobs::accept(&db, &other, &offer, |_| true).is_err());
assert_eq!(db.query_row("SELECT count(*) FROM job_attempts WHERE state='unknown'", [], |r| r.get::<_,u32>(0)).unwrap(), 1);
}
#[test] #[test]
fn portable_acceptance_requires_platform_capability_and_exact_redelivery() { fn portable_acceptance_requires_platform_capability_and_exact_redelivery() {
let (binding, request, permit, _) = fixture(); let (binding, request, permit, _) = fixture();
+298
View File
@@ -1091,6 +1091,103 @@ fn windows_unconfirmed_helper_head_cannot_replace_a_committed_decision() {
); );
assert!(!reopened.can_start(&f.channel, false, &f.clock)); assert!(!reopened.can_start(&f.channel, false, &f.clock));
} }
#[test]
fn missed_system_ack_after_result_delivery_requires_archived_definitive_proof() {
let mut f = Fixture::new();
f.helper_identity = HelperIdentity::System;
let mut c = f.client();
let mut helper = HelperSnapshot {
journal_id: Uuid::new_v4(),
checkpoint: 1,
previous_decision_id: None,
attempts: vec![],
};
let first = c
.prepare(
&mut f.db,
&f.ledger,
f.channel.clone(),
Some(&helper),
&f.clock,
)
.unwrap();
let anchor = f.decision(&first, true);
f.apply(&mut c, &anchor).unwrap();
c.apply_consumption(&mut f.ledger, &f.clock).unwrap();
helper.previous_decision_id = Some(anchor.decision_id);
c.confirm_helper(&helper).unwrap();
helper.checkpoint += 1;
let (offer, grant, report) = f.add("unknown", true, Some(success()), script());
let mut prior = report.unwrap();
let Some(Payload::JobResult(result)) = &mut prior.payload else {
unreachable!()
};
result.state = "unknown".into();
f.db.execute(
"UPDATE job_events SET payload=?1 WHERE id=?2",
params![prior.encode_to_vec(), prior.message_id],
)
.unwrap();
let final_report =
persist_original_fixture_result(&mut f, &offer, &grant.unwrap(), completion_outcome());
let edge = c
.prepare(
&mut f.db,
&f.ledger,
f.channel.clone(),
Some(&helper),
&f.clock,
)
.unwrap();
assert_eq!(edge.request.durable_message_ids.len(), 2);
let mut signed = f.decision(&edge, true);
signed
.acknowledged_message_ids
.push(Uuid::parse_str(&final_report.message_id).unwrap());
f.apply(&mut c, &signed).unwrap();
c.apply_consumption(&mut f.ledger, &f.clock).unwrap();
helper.checkpoint += 1;
f.channel.connection_generation += 1;
let mut fresh = f.client();
let prepare = |c: &mut ClientSync, f: &mut Fixture| {
c.prepare_with_closed_control_idle(
&mut f.db,
&f.ledger,
f.channel.clone(),
Some(&helper),
&f.clock,
true,
)
};
assert!(prepare(&mut fresh, &mut f).is_err()); // prior report still pending
rmm_agent_core::jobs::ack(&mut f.db, &prior.message_id).unwrap();
let mut conflicting = prior.clone();
if let Some(Payload::JobResult(r)) = &mut conflicting.payload {
r.state = "failed".into();
}
f.db.execute(
"UPDATE reconcile_results SET envelope=?1 WHERE id=?2",
params![conflicting.encode_to_vec(), prior.message_id],
)
.unwrap();
assert!(prepare(&mut fresh, &mut f).is_err());
f.db.execute(
"UPDATE reconcile_results SET envelope=?1 WHERE id=?2",
params![prior.encode_to_vec(), prior.message_id],
)
.unwrap();
let next = prepare(&mut fresh, &mut f).unwrap();
assert_eq!(
next.request.previous_decision_id,
signed.decision_id.to_string()
);
assert_eq!(
next.request.helper_previous_decision_id,
anchor.decision_id.to_string()
);
assert!(!fresh.can_start(&f.channel, true, &f.clock));
}
#[test] #[test]
fn independent_helper_checkpoint_regression_is_sticky() { fn independent_helper_checkpoint_regression_is_sticky() {
let mut f = Fixture::new(); let mut f = Fixture::new();
@@ -1388,6 +1485,207 @@ fn persist_original_fixture_result(
fn completion_outcome() -> rmm_agent_core::auth::Outcome { fn completion_outcome() -> rmm_agent_core::auth::Outcome {
serde_json::from_slice(&canonical_outcome_bytes(&success()).unwrap()).unwrap() serde_json::from_slice(&canonical_outcome_bytes(&success()).unwrap()).unwrap()
} }
#[test]
fn human_closure_reconciles_agent_interruption_and_a_helper_without_result() {
use rmm_agent_core::helper_reconcile::{self, BootSource, ExecutorLedgerGuard, HelperSync};
struct TestGuard;
impl ExecutorLedgerGuard for TestGuard {
fn check(&self, db: &Connection) -> anyhow::Result<()> {
anyhow::ensure!(
db.is_autocommit(),
"fixture ledger must be outside a transaction"
);
Ok(())
}
}
struct TestBoot(Uuid);
impl BootSource for TestBoot {
fn current_boot(&self) -> anyhow::Result<Uuid> {
Ok(self.0)
}
}
fn map(snapshot: &helper_reconcile::Snapshot) -> HelperSnapshot {
HelperSnapshot {
journal_id: snapshot.journal_id,
checkpoint: snapshot.checkpoint,
previous_decision_id: snapshot.previous_decision_id,
attempts: snapshot
.attempts
.iter()
.map(|a| SyncAttempt {
job_id: a.job_id.to_string(),
attempt_id: a.attempt_id.to_string(),
job_payload_hash: a.job_payload_hash.clone(),
grant_id: a.grant_id.to_string(),
consumption: a.consumption.clone(),
state: a.state.clone(),
revision: a.revision,
original_boot_id: a.original_boot_id.to_string(),
outcome_sha256: a.outcome_sha256.clone(),
outcome_bytes: a.outcome_bytes.clone(),
..Default::default()
})
.collect(),
}
}
let closed = canonical_outcome_bytes(&ReconciledOutcome {
state: "closed_unknown".into(),
stdout: vec![],
stderr: vec![],
exit_code: None,
output_truncated: false,
reboot_required: false,
evidence: serde_json::json!({
"postconditions_passed":false,"effect":"unknown","closed_by_human":true,"retry":false
}),
error_code: "OPERATOR_CLOSED_UNKNOWN".into(),
})
.unwrap();
for interrupt_after_projection in [false, true] {
let mut f = Fixture::new();
reconcile::initialize(&f.db).unwrap();
let (offer, grant, _) = f.add(
"running",
true,
None,
Action::SetServiceState {
unit: "rmm-acceptance.service".into(),
state: "running".into(),
},
);
let grant = grant.unwrap();
let archive = persist_original_fixture_result(
&mut f,
&offer,
&grant,
rmm_agent_core::auth::Outcome::unknown("AGENT_PROCESS_INTERRUPTED"),
);
rmm_agent_core::jobs::ack(&mut f.db, &archive.message_id).unwrap();
let start: Vec<u8> = f
.ledger
.query_row("SELECT start FROM execution_evidence", [], |row| row.get(0))
.unwrap();
let start: serde_json::Value = serde_json::from_slice(&start).unwrap();
let request: Request = serde_json::from_value(start["request"].clone()).unwrap();
let boot = TestBoot(f.channel.boot_id);
let guard = TestGuard;
let mut helper_db = Connection::open_in_memory().unwrap();
rmm_agent_core::ledger::initialize_ledger(&helper_db).unwrap();
rmm_agent_core::ledger::begin_execution(
&mut helper_db,
&grant,
&request,
boot.0,
f.clock.now,
)
.unwrap();
let mut helper = HelperSync::new(f.binding.clone(), &f.clock).unwrap();
let mut client = f.client();
for round in 0..if interrupt_after_projection { 3 } else { 2 } {
let snapshot = map(&helper
.snapshot(
&mut helper_db,
&guard,
f.channel.connection_generation,
&f.clock,
&boot,
)
.unwrap());
assert_eq!(snapshot.attempts[0].state, "unknown");
assert!(snapshot.attempts[0].outcome_bytes.is_empty());
let prepared = client
.prepare(
&mut f.db,
&f.ledger,
f.channel.clone(),
Some(&snapshot),
&f.clock,
)
.unwrap();
let agent_attempt = &prepared.request.attempts[0];
assert!(!agent_attempt.outcome_bytes.is_empty());
let mut d = f.decision(&prepared, round != 0);
d.issued_at = f.clock.now;
if round != 0 {
let attempt = &mut d.attempts[0];
attempt.revision = 3;
attempt.outcome_state = "closed_unknown".into();
attempt.reason = "OPERATOR_CLOSED_UNKNOWN".into();
attempt.unlock = true;
attempt.outcome_sha256 = Some(hash(&closed));
if agent_attempt.state == "unknown" {
attempt.outcome_bytes = closed.clone();
}
}
let signed = f.sign(&d);
client.apply(&mut f.db, &signed, &f.clock).unwrap();
if interrupt_after_projection && round == 1 {
client = f.client();
continue;
}
client.apply_consumption(&mut f.ledger, &f.clock).unwrap();
let raw = prepared.request.encode_to_vec();
let response = helper_reconcile::SignedResponse {
decision_bytes: signed.decision_bytes,
signature: signed.signature,
};
let applied = helper
.apply(&mut helper_db, &guard, &response, &raw, &f.clock, &boot)
.unwrap();
if round == 0 {
assert!(!applied.ready && applied.unlocked_grants.is_empty());
assert!(!client.can_start(&f.channel, false, &f.clock));
} else {
assert!(applied.ready);
assert_eq!(applied.unlocked_grants, vec![grant.grant_id]);
assert!(
helper
.apply(&mut helper_db, &guard, &response, &raw, &f.clock, &boot)
.unwrap()
.unlocked_grants
.is_empty()
);
client.apply_consumption(&mut f.ledger, &f.clock).unwrap();
client.confirm_helper(&map(&applied.snapshot)).unwrap();
assert!(client.can_start(&f.channel, true, &f.clock));
}
}
assert_eq!(
f.db.query_row::<String, _, _>("SELECT state FROM job_attempts", [], |rec| rec.get(0))
.unwrap(),
"closed_unknown"
);
assert_eq!(
f.db.query_row::<Vec<u8>, _, _>("SELECT envelope FROM reconcile_results", [], |rec| {
rec.get(0)
})
.unwrap(),
archive.encode_to_vec()
);
for ledger in [&f.ledger, &helper_db] {
assert_eq!(
ledger
.query_row::<Vec<u8>, _, _>("SELECT result FROM consumed", [], |rec| rec.get(0))
.unwrap(),
closed
);
assert_eq!(
ledger
.query_row::<(Vec<u8>, Vec<u8>), _, _>(
"SELECT original_outcome,closure_outcome FROM unknown_closure_originals",
[],
|rec| Ok((rec.get(0)?, rec.get(1)?))
)
.unwrap(),
(vec![], closed.clone())
);
}
}
}
#[test] #[test]
fn crash_after_durable_outcome_before_result_recovers_original_then_signed_sync_closes() { fn crash_after_durable_outcome_before_result_recovers_original_then_signed_sync_closes() {
let mut f = Fixture::new(); let mut f = Fixture::new();
+233 -24
View File
@@ -4,11 +4,12 @@ use crate::{
actions::{ServiceUnit, reboot_required}, actions::{ServiceUnit, reboot_required},
process, process,
}; };
use rmm_domain::inventory_document::{CpuTimes, DeviceType, firmware_identifier};
use std::{ use std::{
collections::BTreeMap, collections::BTreeMap,
ffi::{CStr, CString}, ffi::{CStr, CString},
fs, fs,
io::Read, io::{BufRead, BufReader, Read},
mem::MaybeUninit, mem::MaybeUninit,
net::{Ipv4Addr, Ipv6Addr}, net::{Ipv4Addr, Ipv6Addr},
path::Path, path::Path,
@@ -168,6 +169,9 @@ pub struct OperatingSystem {
pub hostname: String, pub hostname: String,
pub boot_id: String, pub boot_id: String,
pub uptime_seconds: f64, pub uptime_seconds: f64,
pub booted_at: Option<chrono::DateTime<chrono::Utc>>,
pub installed_at: Option<chrono::DateTime<chrono::Utc>>,
pub install_date_source: Option<&'static str>,
} }
#[derive(Debug, Clone, serde::Serialize)] #[derive(Debug, Clone, serde::Serialize)]
pub struct Interface { pub struct Interface {
@@ -257,6 +261,10 @@ pub struct UpdateStatus {
#[derive(Debug, Clone, serde::Serialize)] #[derive(Debug, Clone, serde::Serialize)]
pub struct Hardware { pub struct Hardware {
pub readable_dmi: BTreeMap<String, String>, pub readable_dmi: BTreeMap<String, String>,
pub device_type: Option<DeviceType>,
pub proxmox_ve: bool,
pub manufacturer: Option<String>,
pub bios_serial_number: Option<String>,
} }
#[derive(Debug, Clone, serde::Serialize)] #[derive(Debug, Clone, serde::Serialize)]
pub struct LinuxInventory { pub struct LinuxInventory {
@@ -268,6 +276,7 @@ pub struct LinuxInventory {
pub dns: Observation<Dns>, pub dns: Observation<Dns>,
pub volumes: Observation<Vec<Observation<Volume>>>, pub volumes: Observation<Vec<Observation<Volume>>>,
pub software: Observation<Vec<SoftwarePackage>>, pub software: Observation<Vec<SoftwarePackage>>,
pub users: Observation<Vec<String>>,
pub updates: Observation<UpdateStatus>, pub updates: Observation<UpdateStatus>,
pub hardware: Observation<Hardware>, pub hardware: Observation<Hardware>,
pub smart: Observation<()>, pub smart: Observation<()>,
@@ -282,6 +291,7 @@ pub fn collect_native() -> LinuxInventory {
dns: dns(), dns: dns(),
volumes: volumes(), volumes: volumes(),
software: software(), software: software(),
users: logged_in_users(),
updates: updates(), updates: updates(),
hardware: hardware(), hardware: hardware(),
smart: Observation::unavailable( smart: Observation::unavailable(
@@ -377,6 +387,22 @@ pub fn capabilities() -> BTreeMap<String, Observation<bool>> {
); );
result result
} }
fn installed_at() -> Option<(chrono::DateTime<chrono::Utc>, &'static str)> {
for (path, source) in [
("/var/log/installer", "installer_directory"),
("/", "root_filesystem"),
] {
if let Some(time) = fs::metadata(path)
.ok()
.and_then(|data| data.created().ok())
.filter(|time| *time > SystemTime::UNIX_EPOCH && *time <= SystemTime::now())
{
return Some((time.into(), source));
}
}
None
}
pub fn operating_system() -> Observation<OperatingSystem> { pub fn operating_system() -> Observation<OperatingSystem> {
let release = read("/etc/os-release", 32 * 1024); let release = read("/etc/os-release", 32 * 1024);
let kernel = read("/proc/sys/kernel/osrelease", 4096); let kernel = read("/proc/sys/kernel/osrelease", 4096);
@@ -414,8 +440,21 @@ pub fn operating_system() -> Observation<OperatingSystem> {
.map(|(k, v)| (k.into(), v.trim_matches('"').into())) .map(|(k, v)| (k.into(), v.trim_matches('"').into()))
}) })
.collect(); .collect();
let booted_at = read("/proc/stat", 256 * 1024)
.data
.as_deref()
.and_then(|stat| {
let seconds = stat
.lines()
.find_map(|line| line.strip_prefix("btime "))?
.trim()
.parse()
.ok()?;
chrono::DateTime::from_timestamp(seconds, 0)
});
let installed = installed_at();
Observation::valid( Observation::valid(
"linux.os:/etc/os-release,/proc", "linux.os:/etc/os-release,/proc,filesystem-birth",
OperatingSystem { OperatingSystem {
release, release,
kernel: kernel.trim().into(), kernel: kernel.trim().into(),
@@ -423,12 +462,109 @@ pub fn operating_system() -> Observation<OperatingSystem> {
hostname: hostname.trim().into(), hostname: hostname.trim().into(),
boot_id, boot_id,
uptime_seconds, uptime_seconds,
booted_at,
installed_at: installed.map(|(time, _)| time),
install_date_source: installed.map(|(_, source)| source),
}, },
) )
} else { } else {
Observation::unavailable("linux.os", Quality::Error, "OS_SOURCE_UNAVAILABLE") Observation::unavailable("linux.os", Quality::Error, "OS_SOURCE_UNAVAILABLE")
} }
} }
fn logged_in_users() -> Observation<Vec<String>> {
const LOGINCTL: &str = "/usr/bin/loginctl";
let listed = command(
LOGINCTL,
&["--no-legend", "--no-pager", "list-sessions"],
16 * 1024,
);
let Some(rows) = &listed.data else {
return map(listed, |_| None);
};
let mut ids = rows
.lines()
.filter_map(|line| line.split_whitespace().next());
let mut args = vec![
"--no-pager",
"--all",
"--property=Name,Class,State",
"show-session",
"--",
];
args.extend(
ids.by_ref()
.take(64)
.filter(|id| id.bytes().all(|c| c.is_ascii_alphanumeric())),
);
let limited = listed.truncated || ids.next().is_some();
if args.len() == 5 {
return Observation::valid("linux.logind:loginctl", Vec::new());
}
let mut report = map(command(LOGINCTL, &args, 16 * 1024), |text| {
let users: std::collections::BTreeSet<_> = text
.split("\n\n")
.filter_map(|block| {
let fields: BTreeMap<_, _> = block
.lines()
.filter_map(|line| line.split_once('='))
.collect();
let class = *fields.get("Class")?;
let state = *fields.get("State")?;
let name = *fields.get("Name")?;
(matches!(
class,
"user" | "user-early" | "user-light" | "user-early-light"
) && matches!(state, "online" | "active")
&& !name.is_empty()
&& name.len() <= 255)
.then(|| name.to_owned())
})
.collect();
Some(users.into_iter().collect())
});
report.source_id = "linux.logind:loginctl".into();
if limited && report.data.is_some() {
report = report.partial("SESSION_LIMIT");
report.truncated = true;
}
report
}
fn aggregate_jiffies(stat: &str) -> Option<Vec<u64>> {
stat.lines()
.find(|line| line.starts_with("cpu "))
.and_then(|line| {
line.split_whitespace()
.skip(1)
.map(str::parse)
.collect::<Result<_, _>>()
.ok()
})
}
fn linux_cpu_times(jiffies: &[u64]) -> Option<CpuTimes> {
// Linux already includes guest and guest_nice in user and nice.
let total = jiffies
.iter()
.take(8)
.try_fold(0_u64, |total, ticks| total.checked_add(*ticks))?;
let idle = jiffies
.get(3)?
.checked_add(jiffies.get(4).copied().unwrap_or_default())?;
Some(CpuTimes { total, idle })
}
pub fn cpu_times() -> Option<CpuTimes> {
let mut line = String::new();
BufReader::new(fs::File::open("/proc/stat").ok()?.take(4096))
.read_line(&mut line)
.ok()?;
if !line.ends_with('\n') {
return None;
}
linux_cpu_times(&aggregate_jiffies(&line)?)
}
pub fn cpu() -> Observation<Cpu> { pub fn cpu() -> Observation<Cpu> {
let info = read("/proc/cpuinfo", 1024 * 1024); let info = read("/proc/cpuinfo", 1024 * 1024);
let stat = read("/proc/stat", 256 * 1024); let stat = read("/proc/stat", 256 * 1024);
@@ -457,15 +593,7 @@ pub fn cpu() -> Observation<Cpu> {
.filter(|(k, _)| k.trim() == "model name") .filter(|(k, _)| k.trim() == "model name")
.map(|(_, v)| v.trim().to_owned()) .map(|(_, v)| v.trim().to_owned())
}); });
let aggregate_jiffies: Option<Vec<u64>> = match aggregate_jiffies(&stat) {
stat.lines().find(|l| l.starts_with("cpu ")).and_then(|l| {
l.split_whitespace()
.skip(1)
.map(str::parse)
.collect::<Result<Vec<_>, _>>()
.ok()
});
match aggregate_jiffies {
Some(aggregate_jiffies) if logical_processors > 0 => Observation::valid( Some(aggregate_jiffies) if logical_processors > 0 => Observation::valid(
"linux.cpu:/proc/cpuinfo,/proc/stat", "linux.cpu:/proc/cpuinfo,/proc/stat",
Cpu { Cpu {
@@ -553,11 +681,12 @@ pub fn interfaces() -> Observation<Vec<Interface>> {
} }
libc::AF_INET6 => { libc::AF_INET6 => {
let addr = &*item.ifa_addr.cast::<libc::sockaddr_in6>(); let addr = &*item.ifa_addr.cast::<libc::sockaddr_in6>();
addresses.push(format!( let ip = Ipv6Addr::from(addr.sin6_addr.s6_addr);
"{}%{}", addresses.push(if addr.sin6_scope_id == 0 {
Ipv6Addr::from(addr.sin6_addr.s6_addr), ip.to_string()
addr.sin6_scope_id } else {
)); format!("{ip}%{}", addr.sin6_scope_id)
});
} }
_ => {} _ => {}
} }
@@ -1116,7 +1245,36 @@ pub fn updates() -> Observation<UpdateStatus> {
} }
result result
} }
fn virtualization_type(output: &process::Output) -> Option<DeviceType> {
if output.timed_out || output.truncated {
return None;
}
match (
output.code,
std::str::from_utf8(&output.stdout).ok()?.trim(),
) {
(Some(1), "none") => Some(DeviceType::Physical),
(Some(0), name) if !name.is_empty() && name != "none" => Some(DeviceType::Virtual),
_ => None,
}
}
fn machine_type(proxmox_ve: bool) -> Option<DeviceType> {
if proxmox_ve {
return Some(DeviceType::Hypervisor);
}
let output = process::run(
"/usr/bin/systemd-detect-virt",
&[],
Duration::from_secs(2),
512,
)
.ok()?;
virtualization_type(&output)
}
pub fn hardware() -> Observation<Hardware> { pub fn hardware() -> Observation<Hardware> {
const SOURCE: &str = "linux.dmi:/sys/class/dmi/id;systemd-detect-virt;pve-manager";
let mut readable_dmi = BTreeMap::new(); let mut readable_dmi = BTreeMap::new();
for field in [ for field in [
"sys_vendor", "sys_vendor",
@@ -1132,15 +1290,36 @@ pub fn hardware() -> Observation<Hardware> {
readable_dmi.insert(field.into(), value); readable_dmi.insert(field.into(), value);
} }
} }
if readable_dmi.is_empty() { let proxmox_ve =
Observation::unavailable( Path::new("/usr/bin/pveversion").is_file() && Path::new("/usr/bin/pvedaemon").is_file();
"linux.dmi:/sys/class/dmi/id", let device_type = machine_type(proxmox_ve);
Quality::Unsupported, let manufacturer = readable_dmi
"DMI_UNAVAILABLE", .get("sys_vendor")
) .and_then(|value| firmware_identifier(value));
let serial_credential = std::env::var_os("CREDENTIALS_DIRECTORY")
.map(|directory| std::path::PathBuf::from(directory).join("rmm-bios-serial"));
let bios_serial_number = [
Some("/sys/class/dmi/id/product_serial"),
Some("/proc/device-tree/serial-number"),
serial_credential.as_deref().and_then(Path::to_str),
]
.into_iter()
.flatten()
.find_map(|path| sys_text(path).and_then(|value| firmware_identifier(&value)));
if readable_dmi.is_empty() && device_type.is_none() && bios_serial_number.is_none() {
Observation::unavailable(SOURCE, Quality::Unsupported, "HARDWARE_UNAVAILABLE")
} else { } else {
Observation::valid("linux.dmi:/sys/class/dmi/id", Hardware { readable_dmi }) Observation::valid(
.partial("READABLE_DMI_ONLY_NO_SMART_OR_ENCRYPTION_PROOF") SOURCE,
Hardware {
readable_dmi,
device_type,
proxmox_ve,
manufacturer,
bios_serial_number,
},
)
.partial("NO_SMART_OR_ENCRYPTION_PROOF")
} }
} }
@@ -1362,6 +1541,36 @@ mod tests {
assert_eq!(request.since_filter, "@100.123457"); assert_eq!(request.since_filter, "@100.123457");
assert_eq!(request.until_filter, "@101.987654"); assert_eq!(request.until_filter, "@101.987654");
} }
#[test]
fn cpu_time_excludes_double_counted_guest_ticks_and_io_wait() {
let before = linux_cpu_times(&[10, 0, 5, 60, 10, 0, 0, 0, 4, 0]).unwrap();
let after = linux_cpu_times(&[30, 0, 5, 120, 30, 0, 0, 0, 20, 0]).unwrap();
assert_eq!(after.usage_since(before), Some(2_000));
assert_eq!(after.usage_since(after), None);
assert_eq!(before.usage_since(after), None);
assert!(linux_cpu_times(&[10, 0, 0]).is_none());
}
#[test]
fn machine_types_distinguish_proxmox_guests_and_probe_failures() {
assert_eq!(machine_type(true), Some(DeviceType::Hypervisor));
let mut output = process::Output {
code: Some(0),
stdout: b"kvm\n".to_vec(),
stderr: vec![],
truncated: false,
timed_out: false,
interrupted: false,
};
assert_eq!(virtualization_type(&output), Some(DeviceType::Virtual));
output.code = Some(1);
assert_eq!(virtualization_type(&output), None);
output.stdout = b"none\n".to_vec();
assert_eq!(virtualization_type(&output), Some(DeviceType::Physical));
output.timed_out = true;
assert_eq!(virtualization_type(&output), None);
}
#[test] #[test]
fn harmless_native_read_providers() { fn harmless_native_read_providers() {
assert_eq!(memory().quality, Quality::Valid); assert_eq!(memory().quality, Quality::Valid);
+14 -4
View File
@@ -1,5 +1,5 @@
//! Additive JSON observation mapping inside the existing snapshot payload. This //! Additive JSON observation mapping inside the existing snapshot payload. This
//! does not introduce a protobuf tag, a fabricated receive time or a new scope. //! does not introduce a protobuf tag or a fabricated receive time.
use anyhow::Result; use anyhow::Result;
use serde_json::{Value, json}; use serde_json::{Value, json};
@@ -14,7 +14,12 @@ pub fn observations(inventory: &crate::inventory::LinuxInventory) -> Result<Vec<
observation["scope"] = json!(format!("linux.{name}")); observation["scope"] = json!(format!("linux.{name}"));
// Bound each scope independently. Never drop unsupported/error metadata // Bound each scope independently. Never drop unsupported/error metadata
// or imply that absent/truncated rows were deleted from a device. // or imply that absent/truncated rows were deleted from a device.
while serde_json::to_vec(&observation)?.len() > 32768 { let max_bytes = if name == "software" {
rmm_domain::inventory_document::SOFTWARE_OBSERVATION_MAX_BYTES
} else {
32768
};
while serde_json::to_vec(&observation)?.len() > max_bytes {
observation["truncated"] = json!(true); observation["truncated"] = json!(true);
observation["completeness"] = json!("partial"); observation["completeness"] = json!("partial");
observation["error_code"] = json!("WIRE_SCOPE_LIMIT"); observation["error_code"] = json!("WIRE_SCOPE_LIMIT");
@@ -49,7 +54,7 @@ mod tests {
fn native_wire_scopes_preserve_quality_time_and_unsupported() { fn native_wire_scopes_preserve_quality_time_and_unsupported() {
let native = crate::inventory::collect_native(); let native = crate::inventory::collect_native();
let mapped = observations(&native).unwrap(); let mapped = observations(&native).unwrap();
assert_eq!(mapped.len(), 11); assert_eq!(mapped.len(), 12);
let smart = mapped.iter().find(|v| v["scope"] == "linux.smart").unwrap(); let smart = mapped.iter().find(|v| v["scope"] == "linux.smart").unwrap();
assert_eq!(smart["quality"], "unsupported"); assert_eq!(smart["quality"], "unsupported");
assert!(smart["data"].is_null()); assert!(smart["data"].is_null());
@@ -61,7 +66,12 @@ mod tests {
); );
assert!(!observation["source_id"].as_str().unwrap().is_empty()); assert!(!observation["source_id"].as_str().unwrap().is_empty());
assert!(observation.get("received_at").is_none()); assert!(observation.get("received_at").is_none());
assert!(serde_json::to_vec(observation).unwrap().len() <= 32768); let limit = if observation["scope"] == "linux.software" {
rmm_domain::inventory_document::SOFTWARE_OBSERVATION_MAX_BYTES
} else {
32768
};
assert!(serde_json::to_vec(observation).unwrap().len() <= limit);
} }
let base = snapshot(false).unwrap(); let base = snapshot(false).unwrap();
assert!(serde_json::from_value::<rmm_domain::Inventory>(base).is_ok()); assert!(serde_json::from_value::<rmm_domain::Inventory>(base).is_ok());
+3 -3
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "rmm-agent-windows" name = "rmm-agent-windows"
version.workspace = true version = "0.1.16"
edition.workspace = true edition.workspace = true
license.workspace = true license.workspace = true
@@ -43,7 +43,7 @@ rmm-updater = { path = "../updater" }
hex.workspace = true hex.workspace = true
ed25519-dalek = "=2.2.0" ed25519-dalek = "=2.2.0"
rmm-update-history = { path = "../update-history" } rmm-update-history = { path = "../update-history" }
rusqlite = { version = "0.32.1", features = ["bundled"] } rusqlite.workspace = true
fs2 = "0.4.3" fs2 = "0.4.3"
x509-parser = { version = "=0.18.1", features = ["verify"] } x509-parser = { version = "=0.18.1", features = ["verify"] }
rcgen = { version = "=0.14.10", default-features = false, features = ["crypto", "ring", "pem"] } rcgen = { version = "=0.14.10", default-features = false, features = ["crypto", "ring", "pem"] }
@@ -52,7 +52,7 @@ rcgen = { version = "=0.14.10", default-features = false, features = ["crypto",
cc = "=1.11.1" cc = "=1.11.1"
[target.'cfg(windows)'.dependencies] [target.'cfg(windows)'.dependencies]
windows-sys = { version = "0.61.2", features = ["Win32_Foundation", "Win32_Security", "Win32_Security_Authorization", "Win32_Storage_FileSystem", "Win32_System_IO", "Win32_System_ApplicationInstallationAndServicing", "Win32_System_EventLog", "Win32_System_Diagnostics_ToolHelp", "Win32_System_JobObjects", "Win32_System_Pipes", "Win32_System_SystemInformation", "Win32_System_Registry", "Win32_System_Memory", "Win32_System_Services", "Win32_System_Threading", "Win32_System_Shutdown"] } windows-sys = { version = "0.61.2", features = ["Win32_Foundation", "Win32_NetworkManagement_IpHelper", "Win32_NetworkManagement_Ndis", "Win32_Networking_WinSock", "Win32_Security", "Win32_Security_Authorization", "Win32_Storage_FileSystem", "Win32_System_IO", "Win32_System_ApplicationInstallationAndServicing", "Win32_System_EventLog", "Win32_System_Diagnostics_ToolHelp", "Win32_System_JobObjects", "Win32_System_Pipes", "Win32_System_RemoteDesktop", "Win32_System_SystemInformation", "Win32_System_Registry", "Win32_System_Memory", "Win32_System_Services", "Win32_System_Threading", "Win32_System_Shutdown"] }
[[example]] [[example]]
name = "windows_reviewed_recovery" name = "windows_reviewed_recovery"
@@ -185,6 +185,7 @@ mod native {
Payload::Heartbeat(Heartbeat { Payload::Heartbeat(Heartbeat {
instance_id: Uuid::new_v4().to_string(), instance_id: Uuid::new_v4().to_string(),
uptime_seconds: 1, uptime_seconds: 1,
system_usage: None,
}), }),
)?; )?;
let acknowledgement = send(client, &heartbeat).await?; let acknowledgement = send(client, &heartbeat).await?;
@@ -8,6 +8,10 @@ fn main() -> anyhow::Result<()> {
println!("enrolled-windows-update/1"); println!("enrolled-windows-update/1");
return Ok(()); return Ok(());
} }
if std::env::args().skip(1).eq(["--managed-script-helper-version"]) {
println!("managed-script-helper/1");
return Ok(());
}
rmm_agent_windows::helper_system::dispatch() rmm_agent_windows::helper_system::dispatch()
} }
#[cfg(not(windows))] #[cfg(not(windows))]
@@ -11,6 +11,14 @@ fn main() -> anyhow::Result<()> {
println!("release-job-lock/1"); println!("release-job-lock/1");
Ok(()) Ok(())
} }
Some(flag) if flag == "--managed-script-helper-version" && args.next().is_none() => {
println!("managed-script-helper/1");
Ok(())
}
Some(flag) if flag == "--managed-script-policy-version" && args.next().is_none() => {
println!("release-preserves-script-policy/1");
Ok(())
}
Some(flag) if flag == "--verify-bootstrap" => { Some(flag) if flag == "--verify-bootstrap" => {
let release = rmm_updater::verify_bootstrap_files( let release = rmm_updater::verify_bootstrap_files(
rmm_agent_windows::release_platform::VERIFY, rmm_agent_windows::release_platform::VERIFY,
+1 -1
View File
@@ -237,7 +237,7 @@ impl Store {
pub fn open_empty_history_snapshot() -> Result<Self> { pub fn open_empty_history_snapshot() -> Result<Self> {
let store = Self::open(false)?; let store = Self::open(false)?;
ensure!( ensure!(
store.db.is_readonly(rusqlite::DatabaseName::Main)?, store.db.is_readonly(rusqlite::MAIN_DB)?,
"read-only intent snapshot required" "read-only intent snapshot required"
); );
store store
+1 -1
View File
@@ -505,7 +505,7 @@ impl Client {
self.check_pin()?; self.check_pin()?;
// Static qualification only; a per-connection clock warm-up must not flap // Static qualification only; a per-connection clock warm-up must not flap
// advertised capabilities (each change forces a reconnect). // advertised capabilities (each change forces a reconnect).
let qualification=crate::system_capabilities::qualified(pin,true,reboot_privilege_available); let qualification=crate::system_capabilities::qualified(pin,true);
let system_qualification_unavailable=qualification.is_err(); let system_qualification_unavailable=qualification.is_err();
// Capability evidence is deny-only. A missing/stale optional record // Capability evidence is deny-only. A missing/stale optional record
// cannot remove the separately authenticated control/SignedSync lane. // cannot remove the separately authenticated control/SignedSync lane.
+28 -4
View File
@@ -107,10 +107,13 @@ impl Settings {
}) })
} }
pub(crate) fn windows_update_only(&self) -> bool { pub(crate) fn windows_update_only(&self) -> bool {
self.schema_version >= 3 && self.enable_effects && self.windows_update_max_runtime_seconds.is_some() (3..=4).contains(&self.schema_version) && self.enable_effects && self.windows_update_max_runtime_seconds.is_some()
&& self.allowed_script_profiles.is_none() && self.allowed_services.is_empty() && self.allowed_script_profiles.is_none() && self.allowed_services.is_empty()
&& self.allowed_msi_recipe_sha256.is_none() && !self.allow_reboot && self.max_runtime_seconds <= 30 && self.allowed_msi_recipe_sha256.is_none() && !self.allow_reboot && self.max_runtime_seconds <= 30
} }
pub(crate) fn managed_scripts(&self) -> bool {
self.schema_version == 5
}
fn permits_script(&self, job: &JobPayload) -> bool { fn permits_script(&self, job: &JobPayload) -> bool {
self.schema_version >= 3 self.schema_version >= 3
&& job.execution_identity == "system" && job.execution_identity == "system"
@@ -133,7 +136,12 @@ impl Settings {
} }
pub fn validate(&self) -> Result<()> { pub fn validate(&self) -> Result<()> {
ensure!( ensure!(
matches!(self.schema_version, 1..=4) matches!(self.schema_version, 1..=5)
&& (!self.managed_scripts()
|| (self.enable_effects && self.allowed_services.is_empty()
&& self.allowed_msi_recipe_sha256.is_none() && !self.allow_reboot
&& self.allowed_script_profiles.as_deref()
== Some(&[rmm_domain::jobs::PrivilegedScriptProfile::FullMaintenanceV1])))
&& (self.schema_version >= 2 || self.allowed_msi_recipe_sha256.is_none()) && (self.schema_version >= 2 || self.allowed_msi_recipe_sha256.is_none())
&& (self.schema_version >= 3 || self.allowed_script_profiles.is_none()) && (self.schema_version >= 3 || self.allowed_script_profiles.is_none())
&& self && self
@@ -891,7 +899,7 @@ impl SystemHelper {
let pin = settings.pin()?; let pin = settings.pin()?;
ipc::publish_self_query_rights(&settings.agent.service_sid, &settings.helper.service_sid)?; ipc::publish_self_query_rights(&settings.agent.service_sid, &settings.helper.service_sid)?;
let (guard, db) = LedgerGuard::acquire(&settings.helper.service_sid, &settings.binding)?; let (guard, db) = LedgerGuard::acquire(&settings.helper.service_sid, &settings.binding)?;
let clock = if settings.windows_update_only() { let clock = if settings.windows_update_only() || settings.managed_scripts() {
RuntimeClock::enrolled_windows_update_helper(settings.binding.clone(), settings.helper.clone()) RuntimeClock::enrolled_windows_update_helper(settings.binding.clone(), settings.helper.clone())
} else { RuntimeClock::new(rmm_time_attestation::Role::SystemHelper) }.for_generation(0); } else { RuntimeClock::new(rmm_time_attestation::Role::SystemHelper) }.for_generation(0);
let boot = WindowsBoot::capture()?; let boot = WindowsBoot::capture()?;
@@ -1083,6 +1091,7 @@ impl SystemHelper {
serde_json::from_slice(&response.decision_bytes)?; serde_json::from_slice(&response.decision_bytes)?;
self.clock self.clock
.require_generation(decision.connection_generation)?; .require_generation(decision.connection_generation)?;
let started = Instant::now();
self.wait_apply_clock(decision.issued_at,decision.valid_until)?; self.wait_apply_clock(decision.issued_at,decision.valid_until)?;
self.sync()?; self.sync()?;
let value = if let Some(grant)=crate::update_control::active_grant(&self.db)? { let value = if let Some(grant)=crate::update_control::active_grant(&self.db)? {
@@ -1091,7 +1100,21 @@ impl SystemHelper {
&self.clock,&self.pin,&budget,grant)?; &self.clock,&self.pin,&budget,grant)?;
self.sync.as_mut().unwrap().apply(&mut self.db,&guard,response,request_bytes,&self.clock,&self.boot)? self.sync.as_mut().unwrap().apply(&mut self.db,&guard,response,request_bytes,&self.clock,&self.boot)?
} else { } else {
self.sync.as_mut().unwrap().apply(&mut self.db,&self.guard,response,request_bytes,&self.clock,&self.boot)? // Refresh only a clock read that the core proves failed before
// its first transaction. Keep the original capture and deadline.
loop {
let result = self.sync.as_mut().unwrap().apply(
&mut self.db, &self.guard, response, request_bytes,
&self.clock, &self.boot,
);
match result {
Err(error) if rmm_agent_core::helper_reconcile::retryable_precommit_clock(&error)
&& started.elapsed() < Duration::from_secs(3) => {
std::thread::sleep(Duration::from_millis(20));
}
other => break other?,
}
}
}; };
let no_start_anchor = if value.ready let no_start_anchor = if value.ready
&& (self.settings.enable_effects && (self.settings.enable_effects
@@ -1130,6 +1153,7 @@ impl SystemHelper {
request, request,
} => { } => {
let job = self.settings.binding.job(&request.job_bytes)?; let job = self.settings.binding.job(&request.job_bytes)?;
ensure!(self.settings.permits_script(&job), "SYSTEM_SCRIPT_REQUIRED");
if matches!(job.action, Action::UpdateAgent { .. }) { if matches!(job.action, Action::UpdateAgent { .. }) {
ensure!( ensure!(
self.pending_update_activation.is_none(), self.pending_update_activation.is_none(),
+169 -13
View File
@@ -2,6 +2,9 @@
//! uninstall commands; registry entries are evidence, not verified MSI state. //! uninstall commands; registry entries are evidence, not verified MSI state.
use anyhow::{Result, ensure}; use anyhow::{Result, ensure};
use chrono::Utc; use chrono::Utc;
use rmm_domain::inventory_document::{
CpuTimes, DeviceType, SOFTWARE_OBSERVATION_MAX_BYTES, firmware_identifier,
};
use serde_json::{Value, json}; use serde_json::{Value, json};
use std::{ use std::{
mem::{size_of, zeroed}, mem::{size_of, zeroed},
@@ -9,8 +12,12 @@ use std::{
time::{Duration, Instant}, time::{Duration, Instant},
}; };
use windows_sys::Win32::{ use windows_sys::Win32::{
Foundation::{ERROR_FILE_NOT_FOUND, ERROR_NO_MORE_ITEMS, ERROR_SUCCESS}, Foundation::{ERROR_FILE_NOT_FOUND, ERROR_NO_MORE_ITEMS, ERROR_SUCCESS, FILETIME},
System::{Registry::*, SystemInformation::*}, System::{
Registry::*,
SystemInformation::*,
Threading::{GetActiveProcessorGroupCount, GetSystemTimes},
},
}; };
struct Registry(HKEY); struct Registry(HKEY);
@@ -64,21 +71,119 @@ fn text(key: HKEY, name: &str) -> Result<Option<String>> {
Ok(Some(String::from_utf16(&data[..count - 1])?)) Ok(Some(String::from_utf16(&data[..count - 1])?))
} }
fn hardware() -> Result<Value> { #[cfg(target_arch = "x86_64")]
let mut system: SYSTEM_INFO = unsafe { zeroed() }; fn non_microsoft_hypervisor() -> bool {
unsafe { use std::arch::x86_64::__cpuid;
GetNativeSystemInfo(&mut system); if __cpuid(1).ecx & (1 << 31) == 0 {
return false;
} }
let vendor = __cpuid(0x4000_0000);
// The Microsoft hypervisor can also be active on physical VBS machines.
[vendor.ebx, vendor.ecx, vendor.edx]
!= [
u32::from_le_bytes(*b"Micr"),
u32::from_le_bytes(*b"osof"),
u32::from_le_bytes(*b"t Hv"),
]
}
#[cfg(not(target_arch = "x86_64"))]
fn non_microsoft_hypervisor() -> bool {
false
}
fn classify_machine(
hyper_v_host: bool,
guest_hypervisor: bool,
manufacturer: Option<&str>,
product: Option<&str>,
) -> Option<DeviceType> {
if hyper_v_host {
return Some(DeviceType::Hypervisor);
}
let manufacturer = manufacturer.unwrap_or_default().trim().to_ascii_lowercase();
let product = product.unwrap_or_default().trim().to_ascii_lowercase();
let virtual_firmware = [
"qemu",
"vmware",
"virtualbox",
"xen",
"parallels",
"bhyve",
"kvm",
"virtual machine",
"virtual platform",
]
.iter()
.any(|prefix| manufacturer.starts_with(prefix) || product.starts_with(prefix));
if guest_hypervisor || virtual_firmware {
return Some(DeviceType::Virtual);
}
(!manufacturer.is_empty() && !product.is_empty()).then_some(DeviceType::Physical)
}
fn machine_type(manufacturer: Option<&str>, product: Option<&str>) -> Option<DeviceType> {
let hyper_v_host = open(
HKEY_LOCAL_MACHINE,
r"SYSTEM\CurrentControlSet\Services\vmms",
KEY_WOW64_64KEY,
)
.is_ok();
classify_machine(
hyper_v_host,
non_microsoft_hypervisor(),
manufacturer,
product,
)
}
fn memory_status() -> Result<MEMORYSTATUSEX> {
let mut memory: MEMORYSTATUSEX = unsafe { zeroed() }; let mut memory: MEMORYSTATUSEX = unsafe { zeroed() };
memory.dwLength = size_of::<MEMORYSTATUSEX>() as u32; memory.dwLength = size_of::<MEMORYSTATUSEX>() as u32;
ensure!( ensure!(
unsafe { GlobalMemoryStatusEx(&mut memory) } != 0 unsafe { GlobalMemoryStatusEx(&mut memory) } != 0
&& system.dwNumberOfProcessors > 0
&& memory.ullTotalPhys > 0 && memory.ullTotalPhys > 0
&& memory.ullAvailPhys <= memory.ullTotalPhys && memory.ullAvailPhys <= memory.ullTotalPhys
&& memory.dwMemoryLoad <= 100, && memory.dwMemoryLoad <= 100,
"NATIVE_HARDWARE_QUERY" "NATIVE_HARDWARE_QUERY"
); );
Ok(memory)
}
pub fn physical_memory() -> Option<(u64, u64)> {
let memory = memory_status().ok()?;
Some((memory.ullAvailPhys, memory.ullTotalPhys))
}
pub fn cpu_times() -> Option<CpuTimes> {
// GetSystemTimes on a multi-group machine only reports the caller's group.
if unsafe { GetActiveProcessorGroupCount() } != 1 {
return None;
}
let (mut idle, mut kernel, mut user) = (
FILETIME::default(),
FILETIME::default(),
FILETIME::default(),
);
if unsafe { GetSystemTimes(&mut idle, &mut kernel, &mut user) } == 0 {
return None;
}
let ticks =
|time: FILETIME| (u64::from(time.dwHighDateTime) << 32) | u64::from(time.dwLowDateTime);
// Windows includes idle time in the kernel counter.
Some(CpuTimes {
total: ticks(kernel).checked_add(ticks(user))?,
idle: ticks(idle),
})
}
fn hardware() -> Result<Value> {
let mut system: SYSTEM_INFO = unsafe { zeroed() };
unsafe {
GetNativeSystemInfo(&mut system);
}
ensure!(system.dwNumberOfProcessors > 0, "NATIVE_HARDWARE_QUERY");
let memory = memory_status()?;
let cpu_model = open( let cpu_model = open(
HKEY_LOCAL_MACHINE, HKEY_LOCAL_MACHINE,
r"HARDWARE\DESCRIPTION\System\CentralProcessor\0", r"HARDWARE\DESCRIPTION\System\CentralProcessor\0",
@@ -88,16 +193,34 @@ fn hardware() -> Result<Value> {
.and_then(|key| text(key.0, "ProcessorNameString").ok().flatten()) .and_then(|key| text(key.0, "ProcessorNameString").ok().flatten())
.map(|name| name.trim().to_owned()) .map(|name| name.trim().to_owned())
.filter(|name| !name.is_empty()); .filter(|name| !name.is_empty());
let bios = open(
HKEY_LOCAL_MACHINE,
r"HARDWARE\DESCRIPTION\System\BIOS",
KEY_WOW64_64KEY,
)
.ok();
let read = |name| {
bios.as_ref()
.and_then(|key| text(key.0, name).ok().flatten())
};
let manufacturer = read("SystemManufacturer").and_then(|value| firmware_identifier(&value));
let product = read("SystemProductName");
let bios_serial_number = read("SystemSerialNumber")
.and_then(|value| firmware_identifier(&value))
.or_else(crate::inventory_sources::bios_serial);
Ok( Ok(
json!({"cpu_model":cpu_model, "logical_processors_visible":system.dwNumberOfProcessors, json!({"cpu_model":cpu_model, "logical_processors_visible":system.dwNumberOfProcessors,
"memory_total_bytes":memory.ullTotalPhys,"memory_available_bytes":memory.ullAvailPhys, "memory_total_bytes":memory.ullTotalPhys,"memory_available_bytes":memory.ullAvailPhys,
"memory_load_percent":memory.dwMemoryLoad}), "memory_load_percent":memory.dwMemoryLoad,
"device_type":machine_type(manufacturer.as_deref(),product.as_deref()),
"manufacturer":manufacturer,"bios_serial_number":bios_serial_number}),
) )
} }
fn software() -> Result<Value> { fn software() -> Result<Value> {
let began = Instant::now(); let began = Instant::now();
let mut entries = Vec::new(); let mut entries = Vec::new();
let mut entry_bytes = 0;
let mut errors = 0u32; let mut errors = 0u32;
let mut scanned = 0u32; let mut scanned = 0u32;
let mut truncated = false; let mut truncated = false;
@@ -119,7 +242,7 @@ fn software() -> Result<Value> {
} }
}; };
for index in 0..2048 { for index in 0..2048 {
if began.elapsed() > Duration::from_millis(250) || entries.len() >= 64 { if began.elapsed() > Duration::from_millis(250) {
truncated = true; truncated = true;
break; break;
} }
@@ -161,12 +284,12 @@ fn software() -> Result<Value> {
})(); })();
match entry { match entry {
Ok(Some(entry)) => { Ok(Some(entry)) => {
entries.push(entry); entry_bytes += serde_json::to_vec(&entry)?.len() + 1;
if serde_json::to_vec(&entries)?.len() > 12288 { if entry_bytes > SOFTWARE_OBSERVATION_MAX_BYTES - 2048 {
entries.pop();
truncated = true; truncated = true;
break; break;
} }
entries.push(entry);
} }
Ok(None) => {} Ok(None) => {}
Err(_) => errors += 1, Err(_) => errors += 1,
@@ -197,7 +320,7 @@ pub fn observations() -> Vec<Value> {
[ [
( (
"windows.hardware", "windows.hardware",
"windows.win32:GetNativeSystemInfo+GlobalMemoryStatusEx;registry:CentralProcessor", "windows.win32:GetNativeSystemInfo+GlobalMemoryStatusEx+GetSystemFirmwareTable;registry:CentralProcessor,BIOS,vmms;cpuid",
hardware as Provider, hardware as Provider,
), ),
( (
@@ -205,6 +328,8 @@ pub fn observations() -> Vec<Value> {
"windows.registry:HKLM.Uninstall:64+32", "windows.registry:HKLM.Uninstall:64+32",
software as Provider, software as Provider,
), ),
("windows.interfaces", "windows.win32:GetAdaptersAddresses", crate::inventory_sources::interfaces as Provider),
("windows.users", "windows.win32:WTSEnumerateSessions", crate::inventory_sources::users as Provider),
] ]
.into_iter() .into_iter()
.map(|(scope, source, collect)| { .map(|(scope, source, collect)| {
@@ -226,3 +351,34 @@ pub fn observations() -> Vec<Value> {
}) })
.collect() .collect()
} }
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn machine_type_distinguishes_hyper_v_hosts_from_guests() {
let guest = (Some("Microsoft Corporation"), Some("Virtual Machine"));
assert_eq!(
classify_machine(false, false, guest.0, guest.1),
Some(DeviceType::Virtual)
);
assert_eq!(
classify_machine(true, false, guest.0, guest.1),
Some(DeviceType::Hypervisor)
);
assert_eq!(
classify_machine(false, false, Some("QEMU"), Some("Standard PC")),
Some(DeviceType::Virtual)
);
assert_eq!(
classify_machine(false, true, None, None),
Some(DeviceType::Virtual)
);
assert_eq!(
classify_machine(false, false, Some("Dell Inc."), Some("Precision")),
Some(DeviceType::Physical)
);
assert_eq!(classify_machine(false, false, None, None), None);
}
}
@@ -0,0 +1,266 @@
//! Local read-only inventory providers. Each result is bounded independently.
use anyhow::{Context, Result, ensure};
use rmm_domain::inventory_document::firmware_identifier;
use serde_json::{Value, json};
use std::{
collections::BTreeSet,
ffi::c_void,
mem::size_of,
net::{Ipv4Addr, Ipv6Addr},
ptr, slice,
};
use windows_sys::Win32::{
Foundation::{ERROR_BUFFER_OVERFLOW, ERROR_NO_DATA, ERROR_SUCCESS},
NetworkManagement::IpHelper::*,
Networking::WinSock::{
AF_INET, AF_INET6, AF_UNSPEC, SOCKADDR_IN, SOCKADDR_IN6, SOCKET_ADDRESS,
},
System::{
RemoteDesktop::*,
SystemInformation::{GetSystemFirmwareTable, RSMB},
},
};
pub(crate) fn bios_serial() -> Option<String> {
let length = unsafe { GetSystemFirmwareTable(RSMB, 0, ptr::null_mut(), 0) };
if !(8..=1024 * 1024).contains(&length) {
return None;
}
let mut data = vec![0; length as usize];
if unsafe { GetSystemFirmwareTable(RSMB, 0, data.as_mut_ptr(), length) } != length {
return None;
}
let count = u32::from_le_bytes(data[4..8].try_into().ok()?) as usize;
smbios_serial(data.get(8..)?.get(..count)?)
}
fn smbios_serial(mut table: &[u8]) -> Option<String> {
while let Some(header) = table.get(..4) {
let length = usize::from(header[1]);
if length < 4 || header[0] == 127 {
break;
}
let strings = table.get(length..)?;
let end = strings.windows(2).position(|pair| pair == [0, 0])?;
if header[0] == 1 {
let offset = usize::from(*table.get(..length)?.get(7)?).checked_sub(1)?;
let serial = strings[..end].split(|&c| c == 0).nth(offset)?;
return firmware_identifier(std::str::from_utf8(serial).ok()?);
}
table = strings.get(end + 2..)?;
}
None
}
// Pointer fields returned by IP Helper refer into its caller-provided buffer.
fn at<T>(buffer: &[u64], pointer: *const T) -> Option<&T> {
let offset = (pointer as usize).checked_sub(buffer.as_ptr() as usize)?;
if offset.checked_add(size_of::<T>())? > std::mem::size_of_val(buffer) || !pointer.is_aligned()
{
return None;
}
Some(unsafe { &*pointer })
}
fn wide_name(buffer: &[u64], pointer: *const u16) -> Option<String> {
let mut text = Vec::new();
for i in 0..256 {
let character = *at(buffer, pointer.wrapping_add(i))?;
if character == 0 {
return (!text.is_empty()).then(|| String::from_utf16_lossy(&text));
}
text.push(character);
}
None
}
fn ip_address(buffer: &[u64], address: SOCKET_ADDRESS) -> Option<String> {
let sockaddr = at(buffer, address.lpSockaddr)?;
match sockaddr.sa_family {
AF_INET if address.iSockaddrLength >= size_of::<SOCKADDR_IN>() as i32 => {
let ipv4 = at(buffer, address.lpSockaddr.cast::<SOCKADDR_IN>())?;
Some(Ipv4Addr::from(unsafe { ipv4.sin_addr.S_un.S_addr }.to_ne_bytes()).to_string())
}
AF_INET6 if address.iSockaddrLength >= size_of::<SOCKADDR_IN6>() as i32 => {
let ipv6 = at(buffer, address.lpSockaddr.cast::<SOCKADDR_IN6>())?;
let ip = Ipv6Addr::from(unsafe { ipv6.sin6_addr.u.Byte });
let scope = unsafe { ipv6.Anonymous.sin6_scope_id };
Some(if scope == 0 {
ip.to_string()
} else {
format!("{ip}%{scope}")
})
}
_ => None,
}
}
pub(crate) fn interfaces() -> Result<Value> {
let mut bytes = 15360_u32;
let mut buffer = vec![0_u64; (bytes as usize).div_ceil(8)];
let flags = GAA_FLAG_SKIP_ANYCAST
| GAA_FLAG_SKIP_MULTICAST
| GAA_FLAG_SKIP_DNS_SERVER
| GAA_FLAG_INCLUDE_ALL_INTERFACES;
let mut status = unsafe {
GetAdaptersAddresses(
u32::from(AF_UNSPEC),
flags,
ptr::null(),
buffer.as_mut_ptr().cast(),
&mut bytes,
)
};
if status == ERROR_BUFFER_OVERFLOW && bytes <= 1024 * 1024 {
buffer.resize((bytes as usize).div_ceil(8), 0);
status = unsafe {
GetAdaptersAddresses(
u32::from(AF_UNSPEC),
flags,
ptr::null(),
buffer.as_mut_ptr().cast(),
&mut bytes,
)
};
}
if status == ERROR_NO_DATA {
return Ok(json!({"entries":[],"truncated":false}));
}
ensure!(status == ERROR_SUCCESS, "ADAPTER_ADDRESSES");
let mut current = buffer.as_ptr().cast::<IP_ADAPTER_ADDRESSES_LH>();
let mut entries = Vec::new();
let mut truncated = false;
let mut size = 0;
while !current.is_null() && entries.len() < 128 {
let adapter = at(&buffer, current).context("ADAPTER_POINTER")?;
let mut next = adapter.FirstUnicastAddress.cast_const();
let mut addresses = BTreeSet::new();
for _ in 0..64 {
if next.is_null() {
break;
}
let address = at(&buffer, next).context("ADAPTER_ADDRESS_POINTER")?;
if let Some(ip) = ip_address(&buffer, address.Address) {
addresses.insert(ip);
}
next = address.Next.cast_const();
}
truncated |= !next.is_null();
let name = wide_name(&buffer, adapter.FriendlyName)
.or_else(|| wide_name(&buffer, adapter.Description))
.unwrap_or_else(|| {
format!("Adapter {}", unsafe {
adapter.Anonymous1.Anonymous.IfIndex
})
});
let mac = adapter
.PhysicalAddress
.get(..adapter.PhysicalAddressLength as usize)
.filter(|bytes| !bytes.is_empty())
.map(|bytes| {
bytes
.iter()
.map(|byte| format!("{byte:02x}"))
.collect::<Vec<_>>()
.join(":")
});
let entry = json!({"name":name,"addresses":addresses,"mac":mac});
size += serde_json::to_vec(&entry)?.len() + 1;
if size > 30 * 1024 {
truncated = true;
break;
}
entries.push(entry);
current = adapter.Next.cast_const();
}
Ok(json!({"entries":entries,"truncated":truncated || !current.is_null()}))
}
struct WtsMemory(*mut c_void);
impl Drop for WtsMemory {
fn drop(&mut self) {
if !self.0.is_null() {
unsafe { WTSFreeMemory(self.0) };
}
}
}
fn session_text(id: u32, class: WTS_INFO_CLASS) -> Option<String> {
let mut text = ptr::null_mut();
let mut bytes = 0;
if unsafe { WTSQuerySessionInformationW(ptr::null_mut(), id, class, &mut text, &mut bytes) }
== 0
{
return None;
}
let _guard = WtsMemory(text.cast());
if text.is_null() || !(2..=512).contains(&bytes) || bytes % 2 != 0 {
return None;
}
let units = unsafe { slice::from_raw_parts(text, (bytes / 2) as usize) };
String::from_utf16(units.split(|c| *c == 0).next()?).ok()
}
pub(crate) fn users() -> Result<Value> {
let mut list = ptr::null_mut();
let mut count = 0;
ensure!(
unsafe { WTSEnumerateSessionsW(ptr::null_mut(), 0, 1, &mut list, &mut count) } != 0,
"SESSION_QUERY"
);
let _guard = WtsMemory(list.cast());
let mut entries = BTreeSet::new();
let mut errors = 0;
let mut truncated = count > 256;
if count != 0 {
ensure!(!list.is_null(), "SESSION_LIST");
for session in unsafe { slice::from_raw_parts(list, count.min(256) as usize) } {
if session.SessionId == 0
|| ![WTSActive, WTSConnected, WTSDisconnected].contains(&session.State)
{
continue;
}
match session_text(session.SessionId, WTSUserName) {
Some(name) if !name.is_empty() => {
let account = match session_text(session.SessionId, WTSDomainName) {
Some(domain) if !domain.is_empty() => format!("{domain}\\{name}"),
_ => name,
};
if entries.len() >= 64 {
truncated = true;
break;
}
if account.len() <= 255 && !account.chars().any(char::is_control) {
entries.insert(account);
} else {
errors += 1;
}
}
Some(_) => {}
None => errors += 1,
}
}
}
ensure!(
errors == 0 || !entries.is_empty(),
"SESSION_INFORMATION_UNAVAILABLE"
);
Ok(json!({"entries":entries,"read_errors":errors,"truncated":truncated}))
}
#[cfg(test)]
mod tests {
use super::smbios_serial;
#[test]
fn reads_the_system_serial_and_rejects_incomplete_entries() {
assert_eq!(
smbios_serial(b"\x01\x08\x00\x00\x01\x00\x00\x02Vendor\0ABC-123\0\0").as_deref(),
Some("ABC-123")
);
assert_eq!(
smbios_serial(b"\x01\x08\x00\x00\x01\x00\x00\x02Vendor\0ABC-123\0"),
None
);
}
}
+1
View File
@@ -24,6 +24,7 @@ pub mod helper_system;
pub mod windows_update_setup; pub mod windows_update_setup;
#[cfg(windows)] #[cfg(windows)]
pub mod inventory; pub mod inventory;
mod inventory_sources;
#[cfg(windows)] #[cfg(windows)]
pub mod job_binding; pub mod job_binding;
pub mod journal; pub mod journal;
+38 -11
View File
@@ -1,6 +1,6 @@
//! Read-only Windows APIs. The kernel's recorded startup time identifies the boot. //! Read-only Windows APIs. The kernel's recorded startup time identifies the boot.
use anyhow::{Context, Result, ensure}; use anyhow::{Context, Result, ensure};
use chrono::Utc; use chrono::{DateTime, Utc};
use serde_json::{Value, json}; use serde_json::{Value, json};
use sha2::{Digest, Sha256}; use sha2::{Digest, Sha256};
use std::{ffi::c_void, os::windows::ffi::OsStrExt, path::Path, ptr, time::Duration}; use std::{ffi::c_void, os::windows::ffi::OsStrExt, path::Path, ptr, time::Duration};
@@ -250,16 +250,36 @@ fn registry_string(name: &str) -> Result<String> {
); );
Ok(String::from_utf16(&bytes[..size as usize / 2 - 1])?) Ok(String::from_utf16(&bytes[..size as usize / 2 - 1])?)
} }
pub fn snapshot() -> Result<Value> { pub(crate) fn computer_name(format: COMPUTER_NAME_FORMAT) -> Result<String> {
let started = Utc::now(); let mut name = [0u16; 256];
let mut hostname = vec![0u16; 256]; let mut len = name.len() as u32;
let mut len = hostname.len() as u32;
ensure!( ensure!(
unsafe { GetComputerNameExW(ComputerNameDnsHostname, hostname.as_mut_ptr(), &mut len) } unsafe { GetComputerNameExW(format, name.as_mut_ptr(), &mut len) } != 0
!= 0, && len > 0 && (len as usize) < name.len(),
"HOSTNAME_QUERY" "HOSTNAME_QUERY"
); );
let hostname = String::from_utf16(&hostname[..len as usize])?; Ok(String::from_utf16(&name[..len as usize])?)
}
fn install_date() -> Option<DateTime<Utc>> {
let key = wide(r"SOFTWARE\Microsoft\Windows NT\CurrentVersion");
let name = wide("InstallDate");
let mut seconds = 0_u32;
let mut bytes = size_of::<u32>() as u32;
let status = unsafe { RegGetValueW(HKEY_LOCAL_MACHINE,key.as_ptr(),name.as_ptr(),RRF_RT_REG_DWORD,
ptr::null_mut(),ptr::from_mut(&mut seconds).cast(),&mut bytes) };
(status == 0 && bytes as usize == size_of::<u32>() && seconds > 0)
.then(|| DateTime::from_timestamp(i64::from(seconds), 0))
.flatten().filter(|time| *time <= Utc::now())
}
pub fn snapshot() -> Result<Value> {
snapshot_with_boot(None)
}
pub fn snapshot_with_boot(booted_at: Option<DateTime<Utc>>) -> Result<Value> {
let started = Utc::now();
let hostname = computer_name(ComputerNameDnsHostname)?;
let volume = wide(std::env::var("SystemDrive").context("SYSTEM_DRIVE")? + "\\"); let volume = wide(std::env::var("SystemDrive").context("SYSTEM_DRIVE")? + "\\");
let mut available = 0; let mut available = 0;
let mut total = 0; let mut total = 0;
@@ -277,7 +297,7 @@ pub fn snapshot() -> Result<Value> {
let mut snapshot = json!({"os":os,"hostname":hostname,"architecture":std::env::consts::ARCH,"root_total_bytes":total,"root_available_bytes":available,"root_available_inodes":null, let mut snapshot = json!({"os":os,"hostname":hostname,"architecture":std::env::consts::ARCH,"root_total_bytes":total,"root_available_bytes":available,"root_available_inodes":null,
"collection_started_at":started,"collection_completed_at":completed, "collection_started_at":started,"collection_completed_at":completed,
"observations":[ "observations":[
{"scope":"windows.os","source_id":"windows.registry:CurrentVersion;GetComputerNameExW","observed_at":completed,"quality":"valid","completeness":"partial","truncated":false,"error_code":null,"data":{"product_name":product,"display_version":display,"build":build}}, {"scope":"windows.os","source_id":"windows.registry:CurrentVersion;GetComputerNameExW;Kernel-General/12","observed_at":completed,"quality":"valid","completeness":"partial","truncated":false,"error_code":null,"data":{"product_name":product,"display_version":display,"build":build,"installed_at":install_date(),"booted_at":booted_at}},
{"scope":"windows.volumes","source_id":"windows.win32:GetDiskFreeSpaceExW","observed_at":completed,"quality":"valid","completeness":"partial","truncated":false,"error_code":null,"data":{"system_volume_total_bytes":total,"system_volume_available_bytes":available}}, {"scope":"windows.volumes","source_id":"windows.win32:GetDiskFreeSpaceExW","observed_at":completed,"quality":"valid","completeness":"partial","truncated":false,"error_code":null,"data":{"system_volume_total_bytes":total,"system_volume_available_bytes":available}},
{"scope":"windows.inodes","source_id":"windows.win32","observed_at":completed,"quality":"unsupported","completeness":"unknown","truncated":false,"error_code":"NOT_APPLICABLE","data":null} {"scope":"windows.inodes","source_id":"windows.win32","observed_at":completed,"quality":"unsupported","completeness":"unknown","truncated":false,"error_code":"NOT_APPLICABLE","data":null}
]}); ]});
@@ -288,7 +308,7 @@ pub fn snapshot() -> Result<Value> {
snapshot["collection_completed_at"] = json!(Utc::now()); snapshot["collection_completed_at"] = json!(Utc::now());
Ok(snapshot) Ok(snapshot)
} }
pub async fn boot_id() -> Result<String> { pub async fn boot_identity() -> Result<(String, DateTime<Utc>)> {
// Fixed passive query only. Never interpolates a job or caller-supplied code. // Fixed passive query only. Never interpolates a job or caller-supplied code.
// Avoid Win32_Product: it can cause MSI consistency checks and repairs. // Avoid Win32_Product: it can cause MSI consistency checks and repairs.
let executable = Path::new(&std::env::var("SystemRoot")?) let executable = Path::new(&std::env::var("SystemRoot")?)
@@ -324,7 +344,14 @@ if ($nodes.Count -ne 1) { throw 'BOOT_START_TIME' }
.try_into()?; .try_into()?;
bytes[6] = (bytes[6] & 15) | 0x80; bytes[6] = (bytes[6] & 15) | 0x80;
bytes[8] = (bytes[8] & 63) | 0x80; bytes[8] = (bytes[8] & 63) | 0x80;
Ok(uuid::Uuid::from_bytes(bytes).to_string()) let ticks = text.parse::<i64>()?.checked_sub(621_355_968_000_000_000).context("BOOT_EPOCH")?;
let time = DateTime::from_timestamp(ticks.div_euclid(10_000_000), ticks.rem_euclid(10_000_000) as u32 * 100)
.context("BOOT_EPOCH")?;
Ok((uuid::Uuid::from_bytes(bytes).to_string(),time))
}
pub async fn boot_id() -> Result<String> {
boot_identity().await.map(|(id, _)| id)
} }
#[cfg(test)] #[cfg(test)]
+15 -1
View File
@@ -299,9 +299,13 @@ pub(crate) fn run_observed(
"SYSTEM_DRIVE_REQUIRED" "SYSTEM_DRIVE_REQUIRED"
); );
let system_drive = &system_text[..2]; let system_drive = &system_text[..2];
let computer = crate::native::computer_name(
windows_sys::Win32::System::SystemInformation::ComputerNameNetBIOS,
)?;
for value in [ for value in [
format!("SystemDrive={system_drive}"), format!("COMPUTERNAME={computer}"),
format!("PATH={}\\System32;{}", system.display(), system.display()), format!("PATH={}\\System32;{}", system.display(), system.display()),
format!("SystemDrive={system_drive}"),
format!("SystemRoot={}", system.display()), format!("SystemRoot={}", system.display()),
format!("TEMP={}", cwd.display()), format!("TEMP={}", cwd.display()),
format!("TMP={}", cwd.display()), format!("TMP={}", cwd.display()),
@@ -455,6 +459,16 @@ pub(crate) fn run_observed(
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
#[test]
fn script_process_receives_the_native_computer_name() {
let args = ["-NoProfile", "-NonInteractive", "-Command",
"if (!$env:COMPUTERNAME -or $env:COMPUTERNAME -ine [Environment]::MachineName) { exit 1 }"]
.map(OsString::from);
let output = run(&crate::actions::powershell().unwrap(), &args,
&std::env::temp_dir(), 20, 4096, &AtomicBool::new(false)).unwrap();
assert_eq!(output.exit_code, Some(0));
}
#[test] #[test]
fn arguments_never_become_shell_code_and_trailing_slashes_are_quoted() { fn arguments_never_become_shell_code_and_trailing_slashes_are_quoted() {
assert_eq!( assert_eq!(
+30 -6
View File
@@ -289,6 +289,25 @@ impl Device {
} }
} }
/// Report the signed release layout of the already authenticated live SCM/IPC pair.
/// The server independently verifies the pair's catalog release and helper digest.
pub(crate) fn managed_script_release(pin: &crate::helper_ipc::Pin) -> Result<Uuid> {
let dir = pin.helper.binary.parent().context("missing installed helper directory")?;
let release = dir.file_name().and_then(|n| n.to_str()).context("missing release directory")?;
let id = Uuid::parse_str(release)?;
ensure!(release == id.to_string() && dir == generation(id)
&& pin.agent.binary == dir.join(AGENT) && pin.helper.binary == dir.join(HELPER),
"managed scripts require a pinned release pair");
let path = dir.join("manifest.json");
let raw = protected(&path, rmm_updater::MAX_MANIFEST_BYTES)?;
let manifest: ReleaseManifest = serde_json::from_slice(&raw)?;
ensure!(manifest.platform == VERIFY && manifest.release_id == id
&& manifest.artifacts[0].sha256 == pin.agent.binary_sha256
&& manifest.artifacts[1].sha256 == pin.helper.binary_sha256,
"managed helper differs from installed release manifest");
Ok(id)
}
fn local_manifest(installed: &Installed) -> Result<ReleaseManifest> { fn local_manifest(installed: &Installed) -> Result<ReleaseManifest> {
let root = generation(installed.release_id); let root = generation(installed.release_id);
let raw = protected(&root.join("manifest.json"), rmm_updater::MAX_MANIFEST_BYTES)?; let raw = protected(&root.join("manifest.json"), rmm_updater::MAX_MANIFEST_BYTES)?;
@@ -319,10 +338,16 @@ fn local_manifest(installed: &Installed) -> Result<ReleaseManifest> {
// Only typed release UUIDs enter the fixed SCM command. The actual service path, // Only typed release UUIDs enter the fixed SCM command. The actual service path,
// LocalService account and absence of an independently provisioned helper are checked again on the target. // LocalService account and absence of an independently provisioned helper are checked again on the target.
fn select(from: Uuid, to: Uuid) -> Result<()> { fn select(from: &Installed, to: &Installed) -> Result<()> {
let manifest = local_manifest(to)?;
let [agent, helper] = manifest.artifacts.as_slice() else {
anyhow::bail!("incomplete installed release pair");
};
let script = include_str!("release_service_switch.ps1") let script = include_str!("release_service_switch.ps1")
.replace("FROM_UUID", &from.to_string()) .replace("FROM_UUID", &from.release_id.to_string())
.replace("TO_UUID", &to.to_string()); .replace("TO_UUID", &to.release_id.to_string())
.replace("SELECTED_AGENT_SHA256", &agent.sha256)
.replace("SELECTED_HELPER_SHA256", &helper.sha256);
let windows = std::env::var_os("SystemRoot").context("Windows directory")?; let windows = std::env::var_os("SystemRoot").context("Windows directory")?;
let ps = Path::new(&windows).join(r"System32\WindowsPowerShell\v1.0\powershell.exe"); let ps = Path::new(&windows).join(r"System32\WindowsPowerShell\v1.0\powershell.exe");
let result = Command::new(ps) let result = Command::new(ps)
@@ -338,8 +363,7 @@ fn select(from: Uuid, to: Uuid) -> Result<()> {
Ok(()) Ok(())
} }
async fn rollback(t: &Transition) -> Result<()> { async fn rollback(t: &Transition) -> Result<()> {
local_manifest(&t.old)?; select(&t.new, &t.old)?;
select(t.new.release_id, t.old.release_id)?;
write_record("rejected-release.json", &t.new)?; write_record("rejected-release.json", &t.new)?;
fs::remove_file(record_path(INTENT))?; fs::remove_file(record_path(INTENT))?;
Ok(()) Ok(())
@@ -494,7 +518,7 @@ async fn cycle() -> Result<()> {
let t = Transition { old: active, new }; let t = Transition { old: active, new };
write_record(INTENT, &t)?; write_record(INTENT, &t)?;
let start = chrono::Utc::now(); let start = chrono::Utc::now();
let selected = select(t.old.release_id, t.new.release_id); let selected = select(&t.old, &t.new);
if selected.is_ok() { if selected.is_ok() {
for _ in 0..18 { for _ in 0..18 {
if let Ok(h) = device.health().await if let Ok(h) = device.health().await
@@ -4,6 +4,31 @@ function Get-Image([string]$Id) {
$image = Join-Path ([Environment]::GetFolderPath('ProgramFiles')) ('RustDiscovery\releases\' + $Id + '\rmm-agent-windows.exe') $image = Join-Path ([Environment]::GetFolderPath('ProgramFiles')) ('RustDiscovery\releases\' + $Id + '\rmm-agent-windows.exe')
return '"' + $image + '" --service --config "' + $configPath + '"' return '"' + $image + '" --service --config "' + $configPath + '"'
} }
function Get-HelperImage([string]$Id) {
Join-Path ([Environment]::GetFolderPath('ProgramFiles')) ('RustDiscovery\releases\' + $Id + '\rmm-helper-windows.exe')
}
function Wait-Stopped([string]$Name) {
$control = Get-Service $Name
if ($control.Status -ne 'Stopped') {
$control.Stop()
$control.WaitForStatus('Stopped', [TimeSpan]::FromSeconds(45))
}
}
function Select-Image($Service, [string]$Image) {
if ($Service.PathName -cne $Image) {
$result = Invoke-CimMethod -InputObject $Service -MethodName Change -Arguments @{PathName=$Image}
if ($result.ReturnValue -ne 0) { throw 'SCM path change failed.' }
}
}
function Replace-Pin([string]$Path, [string]$Value) {
$temp = "$Path.next-$([Guid]::NewGuid())"
try {
[IO.File]::WriteAllText($temp, $Value, [Text.UTF8Encoding]::new($false))
[IO.File]::Replace($temp, $Path, [NullString]::Value)
} finally {
if (Test-Path -LiteralPath $temp) { Remove-Item -LiteralPath $temp }
}
}
$configPath = Join-Path ([Environment]::GetFolderPath('CommonApplicationData')) 'RustDiscovery\config.json' $configPath = Join-Path ([Environment]::GetFolderPath('CommonApplicationData')) 'RustDiscovery\config.json'
$from = Get-Image 'FROM_UUID' $from = Get-Image 'FROM_UUID'
$to = Get-Image 'TO_UUID' $to = Get-Image 'TO_UUID'
@@ -13,16 +38,53 @@ if ($config.PSObject.Properties['enable_jobs'] -and $config.enable_jobs) {
if (-not $config.PSObject.Properties['localservice_time_policy'] -or if (-not $config.PSObject.Properties['localservice_time_policy'] -or
$config.localservice_time_policy -cne (Join-Path (Split-Path $configPath) 'job-time.json')) { throw 'Job-enabled pair requires a coordinated helper handoff.' } $config.localservice_time_policy -cne (Join-Path (Split-Path $configPath) 'job-time.json')) { throw 'Job-enabled pair requires a coordinated helper handoff.' }
} }
$managed = $config.PSObject.Properties['managed_script_helper'] -and $config.managed_script_helper
$helper = Get-CimInstance -ClassName Win32_Service -Filter "Name='RmmDiscoverySystemHelper'"
if (-not $service -or $service.StartName -ine 'NT AUTHORITY\LocalService' -or if (-not $service -or $service.StartName -ine 'NT AUTHORITY\LocalService' -or
$service.PathName -cnotin @($from,$to) -or (Get-Service 'RmmDiscoverySystemHelper' -ErrorAction SilentlyContinue)) { throw 'Unexpected service configuration.' } $service.PathName -cnotin @($from,$to) -or ([bool]$helper -ne [bool]$managed)) { throw 'Unexpected service configuration.' }
if ($service.PathName -cne $to) { if ($managed) {
$control = Get-Service 'RmmDiscoveryWindows' $helperExe = Get-HelperImage 'TO_UUID'
if ($control.Status -ne 'Stopped') { $helperTo = '"' + $helperExe + '" --service'
$control.Stop() $helperFrom = '"' + (Get-HelperImage 'FROM_UUID') + '" --service'
$control.WaitForStatus('Stopped', [TimeSpan]::FromSeconds(45)) if ($helper.StartName -ine 'LocalSystem' -or $helper.PathName -cnotin @($helperFrom,$helperTo)) { throw 'Unexpected managed helper service.' }
$policyRoot = Join-Path ([Environment]::GetFolderPath('CommonApplicationData')) 'RustDiscoverySystem'
$settingsPath = Join-Path $policyRoot 'helper.json'
$settings = Get-Content -LiteralPath $settingsPath -Raw | ConvertFrom-Json
if ($settings.schema_version -ne 5) { throw 'Managed helper settings required.' }
# Old renderers require this input; the successor preserves the complete
# existing scope, including an absent long Windows Update permission.
$longRuntime = 3600
if ($settings.PSObject.Properties['windows_update_max_runtime_seconds']) { $longRuntime = $settings.windows_update_max_runtime_seconds }
$rendered = ([ordered]@{binding=$settings.binding; release_id='TO_UUID'
agent_sha256='SELECTED_AGENT_SHA256'; helper_sha256='SELECTED_HELPER_SHA256'
max_runtime_seconds=$longRuntime; managed_scripts=$true} | ConvertTo-Json -Depth 6 -Compress) |
& $helperExe --prepare-enrolled-windows-update
if ($LASTEXITCODE -ne 0) { throw 'Signed successor helper could not render its pins.' }
$pins = $rendered | ConvertFrom-Json
# Rollback may select an earlier renderer. Compare the complete protected
# policy, allowing only the two release image paths and digests to change.
$scope = $pins.helper_settings | ConvertFrom-Json
if ($scope.agent.binary -cne (Join-Path (Split-Path $helperExe) 'rmm-agent-windows.exe') -or
$scope.helper.binary -cne $helperExe -or $scope.agent.binary_sha256 -cne 'SELECTED_AGENT_SHA256' -or
$scope.helper.binary_sha256 -cne 'SELECTED_HELPER_SHA256') { throw 'Rendered helper image pins differ from the selected release.' }
foreach ($role in @('agent','helper')) {
$scope.$role.binary = $settings.$role.binary
$scope.$role.binary_sha256 = $settings.$role.binary_sha256
} }
$res = Invoke-CimMethod -InputObject $service -MethodName Change -Arguments @{PathName=$to} if (($scope | ConvertTo-Json -Depth 12 -Compress) -cne ($settings | ConvertTo-Json -Depth 12 -Compress)) {
if ($res.ReturnValue -ne 0) { throw 'SCM path change failed.' } throw 'Agent release cannot change the managed script authorization.'
}
Wait-Stopped 'RmmDiscoveryWindows'
Wait-Stopped 'RmmDiscoverySystemHelper'
Replace-Pin $settingsPath $pins.helper_settings
Replace-Pin (Join-Path $policyRoot 'agent-pin.json') $pins.agent_pin
Select-Image $helper $helperTo
Select-Image $service $to
Start-Service 'RmmDiscoverySystemHelper'
(Get-Service 'RmmDiscoverySystemHelper').WaitForStatus('Running', [TimeSpan]::FromSeconds(45))
} elseif ($service.PathName -cne $to) {
Wait-Stopped 'RmmDiscoveryWindows'
Select-Image $service $to
} }
$control = Get-Service 'RmmDiscoveryWindows' $control = Get-Service 'RmmDiscoveryWindows'
if ($control.Status -ne 'Running') { if ($control.Status -ne 'Running') {
+117 -32
View File
@@ -8,7 +8,7 @@ use rmm_agent_core::{
reconcile::{self, SyncClock}, reconcile::{self, SyncClock},
}; };
use rmm_agent_windows::certificate_rotation::{ProtectedKeyFiles, RotationStore}; use rmm_agent_windows::certificate_rotation::{ProtectedKeyFiles, RotationStore};
use rmm_agent_windows::{CAPABILITIES, job_binding::readonly_binding, journal::Journal, native}; use rmm_agent_windows::{CAPABILITIES, inventory, job_binding::readonly_binding, journal::Journal, native};
use rmm_domain::jobs::{Action, ExecutionPermitPayload}; use rmm_domain::jobs::{Action, ExecutionPermitPayload};
use rmm_protocol::*; use rmm_protocol::*;
use rusqlite::{Connection, OptionalExtension}; use rusqlite::{Connection, OptionalExtension};
@@ -40,6 +40,8 @@ struct Config {
localservice_time_policy: Option<PathBuf>, localservice_time_policy: Option<PathBuf>,
#[serde(default)] #[serde(default)]
windows_update_helper: bool, windows_update_helper: bool,
#[serde(default)]
managed_script_helper: bool,
// Explicit protected opt-in only; this flag never qualifies a clock or pins. // Explicit protected opt-in only; this flag never qualifies a clock or pins.
#[serde(default)] #[serde(default)]
enable_jobs: bool, enable_jobs: bool,
@@ -90,6 +92,20 @@ fn rotation_file_id(path: &Path) -> Result<[u32; 3]> {
]) ])
} }
impl Config { impl Config {
fn allows_script_action(&self, action: &Action, identity: &str) -> bool {
let Action::RunScript { interpreter, windows_execution_profile, .. } = action else {
return false;
};
let system = match &self.localservice_time_policy {
Some(_) => (self.managed_script_helper && action.full_maintenance())
|| (self.windows_update_helper && action.windows_update_or_identity_probe()),
None => self.job_binding_file.is_some() && action.full_maintenance(),
};
interpreter == "powershell"
&& windows_execution_profile.is_none_or(|p| self.profile_enabled(p))
&& action.valid_execution_identity(identity)
&& (identity == "agent_service" || (identity == "system" && system))
}
fn profile_enabled(&self, profile: rmm_domain::jobs::WindowsExecutionProfile) -> bool { fn profile_enabled(&self, profile: rmm_domain::jobs::WindowsExecutionProfile) -> bool {
self.enable_jobs self.enable_jobs
&& (self.job_binding_file.is_some() || self.localservice_time_policy.is_some()) && (self.job_binding_file.is_some() || self.localservice_time_policy.is_some())
@@ -99,7 +115,8 @@ impl Config {
fn read(path: &Path) -> Result<Self> { fn read(path: &Path) -> Result<Self> {
let raw = protected_read(path, 32768)?; let raw = protected_read(path, 32768)?;
let config: Self = serde_json::from_slice(&raw)?; let config: Self = serde_json::from_slice(&raw)?;
if config.windows_update_helper { ensure!(!(config.windows_update_helper && config.managed_script_helper), "AMBIGUOUS_ENROLLED_HELPER");
if config.windows_update_helper || config.managed_script_helper {
ensure!(config.localservice_time_policy.is_some() && cfg!(feature = "system-helper"), "ENROLLED_WINDOWS_UPDATE_HELPER_REQUIRED"); ensure!(config.localservice_time_policy.is_some() && cfg!(feature = "system-helper"), "ENROLLED_WINDOWS_UPDATE_HELPER_REQUIRED");
} }
if let Some(policy) = &config.localservice_time_policy { if let Some(policy) = &config.localservice_time_policy {
@@ -614,6 +631,7 @@ struct Agent {
certificates: RotationStore, certificates: RotationStore,
key_files: ProtectedKeyFiles, key_files: ProtectedKeyFiles,
boot: String, boot: String,
booted_at: chrono::DateTime<Utc>,
instance: String, instance: String,
started: Instant, started: Instant,
binding: Option<Binding>, binding: Option<Binding>,
@@ -817,7 +835,8 @@ impl Agent {
&identity.certificate_pem, &identity.certificate_pem,
&identity.private_key_pem, &identity.private_key_pem,
)?; )?;
let helper = if self.config.localservice_time_policy.is_some() && !self.config.windows_update_helper { let helper = if self.config.localservice_time_policy.is_some()
&& !self.config.windows_update_helper && !self.config.managed_script_helper {
None None
} else { rmm_agent_windows::helper_runtime::Client::discover( } else { rmm_agent_windows::helper_runtime::Client::discover(
&self.identity.agent_id, &self.identity.agent_id,
@@ -916,7 +935,7 @@ impl Agent {
let _ = time_helper.time_close(generation).await; let _ = time_helper.time_close(generation).await;
} }
helper_report.record(&helper_state, "system_helper", &result); helper_report.record(&helper_state, "system_helper", &result);
tokio::time::sleep(mode.interval(result.is_ok())).await; tokio::time::sleep(mode.helper_interval(result.is_ok())).await;
} }
let _ = time_helper.time_close(generation).await; let _ = time_helper.time_close(generation).await;
})); }));
@@ -1405,8 +1424,7 @@ impl Agent {
Ok(()) Ok(())
} }
fn supported_job(&self, job: &rmm_domain::jobs::JobPayload) -> bool { fn supported_job(&self, job: &rmm_domain::jobs::JobPayload) -> bool {
if self.config.localservice_time_policy.is_some() && job.execution_identity != "agent_service" if !self.config.allows_script_action(&job.action, &job.execution_identity) {
&& !(self.config.windows_update_helper && job.execution_identity == "system" && job.action.windows_update_or_identity_probe()) {
return false; return false;
} }
if self.config.windows_echo_probe_only if self.config.windows_echo_probe_only
@@ -1558,9 +1576,6 @@ impl Agent {
&& native::require_local_service().is_ok() && native::require_local_service().is_ok()
{ {
caps.push("rmm.sync.v1".into()); caps.push("rmm.sync.v1".into());
if !self.config.windows_echo_probe_only {
caps.push("refresh_inventory".into());
}
if rmm_agent_windows::actions::powershell().is_ok() { if rmm_agent_windows::actions::powershell().is_ok() {
caps.extend(["run_script", "script.powershell/1"].map(str::to_string)); caps.extend(["run_script", "script.powershell/1"].map(str::to_string));
if self.config.profile_enabled( if self.config.profile_enabled(
@@ -1573,10 +1588,10 @@ impl Agent {
if !self.config.windows_echo_probe_only if !self.config.windows_echo_probe_only
&& let Some(helper) = &self.helper && let Some(helper) = &self.helper
{ {
caps.extend(helper.qualified_capabilities()); if self.config.job_binding_file.is_some()
if helper.update_observer_configured() || self.config.managed_script_helper || self.config.windows_update_helper
&& self.update_observer.cached().is_some_and(|r|r.observation.predecessor.as_ref().is_some_and(|p|p.helper_sha256==helper.helper_binary_hash())) { {
for cap in self.update_observer.capabilities(){if !caps.contains(&cap){caps.push(cap);}} caps.extend(helper.qualified_capabilities());
} }
} }
} }
@@ -1778,20 +1793,40 @@ impl Agent {
let prepared = sync.prepare( let prepared = sync.prepare(
self.journal.connection_mut(), self.journal.connection_mut(),
self.ledger.as_ref().context("LEDGER_REQUIRED")?, self.ledger.as_ref().context("LEDGER_REQUIRED")?,
context, context.clone(),
helper, helper,
&self.clock, &self.clock,
); );
#[cfg(feature = "system-helper")] #[cfg(feature = "system-helper")]
if helper.is_some() let prepared = match (prepared, helper) {
&& prepared (Err(error), Some(snapshot)) if error.to_string() == "SYSTEM_HELPER_APPLY_UNCONFIRMED" => {
.as_ref() self.helper_apply_unconfirmed = true;
.is_err_and(|error| error.to_string() == "SYSTEM_HELPER_APPLY_UNCONFIRMED") // The helper supplied a fresh authenticated snapshot on its serialized
{ // lane. Only an idle actor may ask the core to prove an exact missed ACK.
// This authenticated readback already established why another if self.running.is_some() || self.prepared || self.deferred_sync.is_some()
// capture cannot advance this channel. || self.deferred_permit.is_some() || self.helper_control.is_some()
self.helper_apply_unconfirmed = true; || self.helper_probe.is_some() || self.update_pending
} || self.update_prefetch.is_some() || self.update_health.is_some()
{
return Err(error);
}
use rmm_agent_windows::helper_runtime::intent;
let idle = if Path::new(intent::DB).try_exists()? {
intent::Store::open(false)?.pending()?.is_empty()
} else {
snapshot.attempts.is_empty()
};
if !idle {
return Err(error);
}
sync.prepare_with_closed_control_idle(
self.journal.connection_mut(),
self.ledger.as_ref().context("LEDGER_REQUIRED")?,
context, Some(snapshot), &self.clock, true,
)
}
(ordinary, _) => ordinary,
};
let prepared = prepared?; let prepared = prepared?;
#[cfg(feature = "system-helper")] #[cfg(feature = "system-helper")]
{ {
@@ -2386,8 +2421,8 @@ impl Agent {
if self.journal.count()? > 0 || !jobs::events(self.journal.connection())?.is_empty() { if self.journal.count()? > 0 || !jobs::events(self.journal.connection())?.is_empty() {
return Ok(false); return Ok(false);
} }
let data = serde_json::to_vec(&native::snapshot()?)?; let data = serde_json::to_vec(&native::snapshot_with_boot(Some(self.booted_at))?)?;
ensure!(data.len() <= 32768, "WINDOWS_INVENTORY_LIMIT"); ensure!(data.len() <= 256 * 1024, "WINDOWS_INVENTORY_LIMIT");
let envelope = self.envelope( let envelope = self.envelope(
generation, generation,
Payload::InventorySnapshot(InventorySnapshot { Payload::InventorySnapshot(InventorySnapshot {
@@ -2503,7 +2538,7 @@ impl Agent {
}; };
self.renew_certificate(admission.as_deref()).await?; self.renew_certificate(admission.as_deref()).await?;
} }
self.boot = native::boot_id().await?; (self.boot, self.booted_at) = native::boot_identity().await?;
let advertised = self.capabilities(); let advertised = self.capabilities();
let hello = self.envelope( let hello = self.envelope(
0, 0,
@@ -2568,6 +2603,7 @@ impl Agent {
let mut rotation_at = Instant::now(); let mut rotation_at = Instant::now();
let mut rotation_after = Duration::from_secs(30); let mut rotation_after = Duration::from_secs(30);
let mut heartbeat = Instant::now() - Duration::from_secs(60); let mut heartbeat = Instant::now() - Duration::from_secs(60);
let mut previous_cpu = None;
let mut heartbeat_after = Duration::from_secs(30); let mut heartbeat_after = Duration::from_secs(30);
let mut tick = tokio::time::interval(Duration::from_millis(20)); let mut tick = tokio::time::interval(Duration::from_millis(20));
tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip); tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
@@ -2619,9 +2655,12 @@ impl Agent {
// A transiently stale clock skips this tick; it must not end the session. // A transiently stale clock skips this tick; it must not end the session.
if let Ok(now)=self.clock.now() && let Some(offer)=jobs::next_at(self.journal.connection(),now)? { if let Ok(now)=self.clock.now() && let Some(offer)=jobs::next_at(self.journal.connection(),now)? {
let job=self.binding.as_ref().context("JOB_BINDING_REQUIRED")?.job(&offer.payload_bytes)?; let job=self.binding.as_ref().context("JOB_BINDING_REQUIRED")?.job(&offer.payload_bytes)?;
ensure!(self.scope_permits(&offer,&job),"WINDOWS_ECHO_OFFER_OUT_OF_SCOPE");
if now>=job.start_before {self.record(generation,&offer,"",jobs::no_start("expired","START_DEADLINE_EXPIRED"))?;needs_sync=true;} if now>=job.start_before {self.record(generation,&offer,"",jobs::no_start("expired","START_DEADLINE_EXPIRED"))?;needs_sync=true;}
else if now-chrono::Duration::seconds(2)>=job.not_before && self.ready_identity(generation,job.execution_identity=="system") { else if !self.config.allows_script_action(&job.action, &job.execution_identity) || !self.scope_permits(&offer, &job) {
// Only next_at's accepted row is known to have no reserved permit.
self.record(generation, &offer, "", jobs::no_start("failed", "LEGACY_ACTION_RETIRED"))?;
needs_sync = true;
} else if now-chrono::Duration::seconds(2)>=job.not_before && self.ready_identity(generation,job.execution_identity=="system") {
#[cfg(feature="system-helper")] #[cfg(feature="system-helper")]
let prefetched=self.prefetch_update(generation,&offer,&job).await?; let prefetched=self.prefetch_update(generation,&offer,&job).await?;
#[cfg(not(feature="system-helper"))] #[cfg(not(feature="system-helper"))]
@@ -2739,9 +2778,19 @@ impl Agent {
// inventory offline. Retry setup at the next heartbeat. // inventory offline. Retry setup at the next heartbeat.
eprintln!("PASSIVE_SIGNED_TIME_UNAVAILABLE"); eprintln!("PASSIVE_SIGNED_TIME_UNAVAILABLE");
} }
let cpu = inventory::cpu_times();
let cpu_usage_basis_points = cpu.zip(previous_cpu)
.and_then(|(current, previous)| current.usage_since(previous));
previous_cpu = cpu;
let memory = inventory::physical_memory();
let payload = Payload::Heartbeat(Heartbeat { let payload = Payload::Heartbeat(Heartbeat {
instance_id: self.instance.clone(), instance_id: self.instance.clone(),
uptime_seconds: self.started.elapsed().as_secs(), uptime_seconds: self.started.elapsed().as_secs(),
system_usage: Some(SystemUsage {
cpu_usage_basis_points,
ram_available_bytes: memory.map(|(available, _)| available),
ram_total_bytes: memory.map(|(_, total)| total),
}),
}); });
let h = self.envelope(generation, payload)?; let h = self.envelope(generation, payload)?;
channel.send(&h).await?; channel.send(&h).await?;
@@ -2751,6 +2800,7 @@ impl Agent {
Payload::Heartbeat(Heartbeat { Payload::Heartbeat(Heartbeat {
instance_id: self.instance.clone(), instance_id: self.instance.clone(),
uptime_seconds: self.started.elapsed().as_secs(), uptime_seconds: self.started.elapsed().as_secs(),
system_usage: None,
}), }),
)?; )?;
channel.poll(poll).await?; channel.poll(poll).await?;
@@ -2770,7 +2820,7 @@ impl Agent {
self.replay(&channel, generation).await?; self.replay(&channel, generation).await?;
replay = Instant::now(); replay = Instant::now();
} }
if !stop.load(Ordering::SeqCst) && inventory.elapsed() >= Duration::from_secs(86400) { if !stop.load(Ordering::SeqCst) && inventory.elapsed() >= Duration::from_secs(300) {
self.queue_inventory(generation)?; self.queue_inventory(generation)?;
inventory = Instant::now(); inventory = Instant::now();
} }
@@ -2880,7 +2930,7 @@ fn service_run(stop: &'static AtomicBool) -> Result<()> {
let identity = enrollment(&config, &ca).await?; let identity = enrollment(&config, &ca).await?;
let mut journal=journal; let mut journal=journal;
journal.pin_identity(&identity.agent_id)?; journal.pin_identity(&identity.agent_id)?;
let boot = native::boot_id().await?; let (boot, booted_at) = native::boot_identity().await?;
let binding=config.job_binding_file.as_deref().map(readonly_binding).transpose()?; let binding=config.job_binding_file.as_deref().map(readonly_binding).transpose()?;
#[cfg(feature = "system-helper")] #[cfg(feature = "system-helper")]
let binding = if let Some(policy) = &config.localservice_time_policy { let binding = if let Some(policy) = &config.localservice_time_policy {
@@ -2930,6 +2980,7 @@ fn service_run(stop: &'static AtomicBool) -> Result<()> {
certificates, certificates,
key_files, key_files,
boot, boot,
booted_at,
instance: Uuid::new_v4().to_string(), instance: Uuid::new_v4().to_string(),
started: Instant::now(), binding, ledger, _ledger_file:ledger_file, clock, sync, started: Instant::now(), binding, ledger, _ledger_file:ledger_file, clock, sync,
#[cfg(feature="system-helper")] #[cfg(feature="system-helper")]
@@ -3026,8 +3077,8 @@ pub fn main() -> Result<()> {
} }
if args == ["--native-probe"] { if args == ["--native-probe"] {
let runtime = tokio::runtime::Runtime::new()?; let runtime = tokio::runtime::Runtime::new()?;
let boot = runtime.block_on(native::boot_id())?; let (boot, booted_at) = runtime.block_on(native::boot_identity())?;
let inventory = native::snapshot()?; let inventory = native::snapshot_with_boot(Some(booted_at))?;
println!( println!(
"{}", "{}",
serde_json::json!({"platform":"windows","architecture":std::env::consts::ARCH,"hostname_available":!inventory["hostname"].as_str().unwrap_or("").is_empty(),"system_volume_available":inventory["root_available_bytes"].as_u64().is_some(),"inodes":null,"boot_id":boot,"capabilities":CAPABILITIES,"jobs_supported":false}) serde_json::json!({"platform":"windows","architecture":std::env::consts::ARCH,"hostname_available":!inventory["hostname"].as_str().unwrap_or("").is_empty(),"system_volume_available":inventory["root_available_bytes"].as_u64().is_some(),"inodes":null,"boot_id":boot,"capabilities":CAPABILITIES,"jobs_supported":false})
@@ -3067,6 +3118,40 @@ fn record_session_error(state: &Path, error: &anyhow::Error) {
mod tests { mod tests {
use super::*; use super::*;
#[cfg(feature = "system-helper")] #[cfg(feature = "system-helper")]
#[test]
fn accepted_actions_require_the_current_local_script_scope_before_a_permit() {
let mut config: Config = serde_json::from_value(serde_json::json!({
"server_name":"fixture", "connect_address":"127.0.0.1:443", "ca_file":"ca",
"state_directory":"state", "enrollment_token_file":"token", "transport":"https",
"localservice_time_policy":"job-time.json", "enable_jobs":true,
"windows_execution_profile":"powershell_51_remote_signed"
})).unwrap();
let mut script: Action = serde_json::from_value(serde_json::json!({
"action":"run_script","interpreter":"powershell","script_utf8":"Write-Output 1",
"arguments":[],"expected_stdout":null,"windows_execution_profile":"powershell_51_remote_signed"
})).unwrap();
assert!(config.allows_script_action(&script, "agent_service"));
let legacy = Action::RefreshInventory { scope: "windows.base".into() };
assert!(!config.allows_script_action(&legacy, "agent_service"));
assert!(!config.allows_script_action(&script,"system"));
let Action::RunScript { ref mut privileged_script_profile, .. } = script else { unreachable!() };
*privileged_script_profile = Some(rmm_domain::jobs::PrivilegedScriptProfile::FullMaintenanceV1);
config.windows_update_helper = true;
assert!(!config.allows_script_action(&script,"system"));
config.windows_update_helper = false;
config.managed_script_helper = true;
assert!(config.allows_script_action(&script, "system"));
assert!(!config.allows_script_action(&legacy, "system"));
config.localservice_time_policy = None;
config.managed_script_helper = false;
config.job_binding_file = Some("job-binding.json".into());
assert!(!config.allows_script_action(&legacy, "agent_service"));
assert!(!config.allows_script_action(&legacy, "system"));
assert!(config.allows_script_action(&script, "system"));
config.job_binding_file = None;
assert!(!config.allows_script_action(&script, "system"));
}
#[cfg(feature = "system-helper")]
#[tokio::test] #[tokio::test]
async fn gate_close_retains_the_original_helper_apply_worker_without_replaying_it() { async fn gate_close_retains_the_original_helper_apply_worker_without_replaying_it() {
let (sender, receiver) = tokio::sync::oneshot::channel::<()>(); let (sender, receiver) = tokio::sync::oneshot::channel::<()>();
+29
View File
@@ -31,6 +31,15 @@ impl SamplingMode {
(Self::Jobs, false) => Duration::from_millis(500), (Self::Jobs, false) => Duration::from_millis(500),
} }
} }
pub fn helper_interval(self, verified: bool) -> std::time::Duration {
match (self, verified) {
// Each refresh verifies both service images over the pipe. A held
// signed time sample remains usable for up to five minutes.
(Self::Jobs, true) => std::time::Duration::from_secs(5),
_ => self.interval(verified),
}
}
} }
fn independent_time_key(time_key_hex: &str, job_key_hex: &str) -> Result<[u8; 32]> { fn independent_time_key(time_key_hex: &str, job_key_hex: &str) -> Result<[u8; 32]> {
@@ -1637,6 +1646,26 @@ mod tests {
} }
std::fs::remove_dir_all(dir).unwrap(); std::fs::remove_dir_all(dir).unwrap();
} }
#[test]
fn helper_sampling_spaces_successes_and_retries_failures_quickly() {
use std::time::Duration;
assert_eq!(
SamplingMode::Jobs.helper_interval(true),
Duration::from_secs(5)
);
assert_eq!(
SamplingMode::Jobs.helper_interval(false),
Duration::from_millis(500)
);
for verified in [false, true] {
assert_eq!(
SamplingMode::Passive.helper_interval(verified),
Duration::from_secs(30)
);
}
}
fn sample(ns: u64) -> Sample { fn sample(ns: u64) -> Sample {
Sample { Sample {
wall_utc_ns: 1_800_000_000_000_000_000 + ns as i64, wall_utc_ns: 1_800_000_000_000_000_000 + ns as i64,
+28 -63
View File
@@ -34,7 +34,6 @@ struct Qualification {
pub fn qualified( pub fn qualified(
pin: &Pin, pin: &Pin,
clock_qualified: bool, clock_qualified: bool,
reboot_privilege_available: Option<bool>,
) -> Result<Vec<String>> { ) -> Result<Vec<String>> {
if !clock_qualified { if !clock_qualified {
return Ok(vec![]); return Ok(vec![]);
@@ -42,12 +41,24 @@ pub fn qualified(
pin.validate()?; pin.validate()?;
let (settings, _handles) = helper_system::read_settings()?; let (settings, _handles) = helper_system::read_settings()?;
ensure!(serde_json::to_vec(&settings.pin()?)? == serde_json::to_vec(pin)?, "system qualification pin"); ensure!(serde_json::to_vec(&settings.pin()?)? == serde_json::to_vec(pin)?, "system qualification pin");
if settings.windows_update_only() { if settings.windows_update_only() || settings.managed_scripts() {
// The caller has verified an independent helper-role clock and the live // The caller has verified the live enrolled peer and its independent clock.
// peer. Only the two built-in scripts pass both local and server gates. let mut caps = vec![
return Ok(vec!["helper.system.v1".into(), format!("helper.binary.sha256:{}",pin.helper.binary_sha256), "helper.system.v1".into(),
format!("helper.policy.sha256:{}",pin.policy_sha256), "system:run_script".into(), format!("helper.binary.sha256:{}", pin.helper.binary_sha256),
rmm_domain::jobs::WINDOWS_UPDATE_LONG_CAPABILITY.into()]); format!("helper.policy.sha256:{}", pin.policy_sha256),
"system:run_script".into(),
];
if settings.windows_update_max_runtime_seconds.is_some() {
caps.push(rmm_domain::jobs::WINDOWS_UPDATE_LONG_CAPABILITY.into());
}
if settings.managed_scripts() {
caps.push(rmm_domain::jobs::FULL_MAINTENANCE_CAPABILITY.into());
if let Ok(id) = crate::release_service::managed_script_release(pin) {
caps.push(format!("script.helper.release:{id}"));
}
}
return Ok(caps);
} }
let ordinary = load_ordinary(pin); let ordinary = load_ordinary(pin);
let (q, result_bytes) = match ordinary { let (q, result_bytes) = match ordinary {
@@ -80,67 +91,21 @@ pub fn qualified(
&& settings.enable_effects, && settings.enable_effects,
"system qualification effective policy" "system qualification effective policy"
); );
if !q.actions.iter().any(|action| action == "run_script") {
return Ok(vec![]);
}
let general = settings.allowed_script_profiles.as_deref() ==
Some(&[rmm_domain::jobs::PrivilegedScriptProfile::FullMaintenanceV1]);
let windows_update = settings.windows_update_max_runtime_seconds.is_some();
ensure!(settings.schema_version >= 3 && (general || windows_update), "system script qualification policy");
let mut caps = vec![ let mut caps = vec![
"helper.system.v1".into(), "helper.system.v1".into(),
format!("helper.binary.sha256:{}", pin.helper.binary_sha256), format!("helper.binary.sha256:{}", pin.helper.binary_sha256),
format!("helper.policy.sha256:{}", pin.policy_sha256), format!("helper.policy.sha256:{}", pin.policy_sha256),
"system:run_script".into(),
]; ];
for action in q.actions { if general { caps.push(rmm_domain::jobs::FULL_MAINTENANCE_CAPABILITY.into()); }
match action.as_str() { if windows_update { caps.push(rmm_domain::jobs::WINDOWS_UPDATE_LONG_CAPABILITY.into()); }
"run_script" => {
let general = settings.allowed_script_profiles.as_deref() ==
Some(&[rmm_domain::jobs::PrivilegedScriptProfile::FullMaintenanceV1]);
let windows_update = settings.windows_update_max_runtime_seconds.is_some();
ensure!(settings.schema_version >= 3 && (general || windows_update), "system script qualification policy");
caps.push("system:run_script".into());
if general { caps.push(rmm_domain::jobs::FULL_MAINTENANCE_CAPABILITY.to_owned()); }
if windows_update { caps.push(rmm_domain::jobs::WINDOWS_UPDATE_LONG_CAPABILITY.to_owned()); }
}
"set_service_state" => {
ensure!(
!settings.allowed_services.is_empty(),
"system SCM qualification policy"
);
caps.extend(["set_service_state", "system:set_service_state"].map(str::to_string));
}
"ensure_package" => {
ensure!(
settings.schema_version >= 2
&& settings
.allowed_msi_recipe_sha256
.as_ref()
.is_some_and(|v| !v.is_empty())
&& crate::msi_cache::stage_configured(),
"system MSI qualification policy"
);
caps.extend(
[
"ensure_package",
"system:ensure_package",
rmm_domain::windows_execution::MSI_CAPABILITY,
]
.map(str::to_string),
);
}
"reboot" => {
ensure!(
settings.schema_version == 4
&& settings.allow_reboot
&& reboot_privilege_available == Some(true),
"system reboot qualification policy or live token"
);
caps.extend(
[
"reboot",
"system:reboot",
rmm_domain::windows_reboot::CAPABILITY,
]
.map(str::to_string),
);
}
_ => unreachable!("validated qualification action"),
}
}
Ok(caps) Ok(caps)
} }
fn read(path: &Path, max: u64) -> Result<Vec<u8>> { fn read(path: &Path, max: u64) -> Result<Vec<u8>> {
@@ -49,9 +49,5 @@ impl Observer {
pub fn observation(&self,generation:u64)->AgentUpdateObservation{ pub fn observation(&self,generation:u64)->AgentUpdateObservation{
self.cached().filter(|v|v.generation==generation).map(|v|v.observation.clone()).unwrap_or_else(||AgentUpdateObservation::not_configured(rmm_agent_windows::release_platform::WIRE,chrono::Utc::now())) self.cached().filter(|v|v.generation==generation).map(|v|v.observation.clone()).unwrap_or_else(||AgentUpdateObservation::not_configured(rmm_agent_windows::release_platform::WIRE,chrono::Utc::now()))
} }
pub fn capabilities(&self)->Vec<String>{
let Some(value)=self.cached() else{return vec![];};
let(Some(updater),Some(predecessor))=(&value.observation.updater,&value.observation.predecessor) else{return vec![];};
vec![rmm_domain::agent_update::APPLY_CAPABILITY.into(),rmm_domain::agent_update::CHECK_CAPABILITY.into(),"update_agent".into(),"system:update_agent".into(),"helper.system.v1".into(),format!("updater.binary.sha256:{}",updater.binary_sha256),format!("updater.policy.sha256:{}",updater.policy_sha256),format!("helper.binary.sha256:{}",predecessor.helper_sha256)]
}
} }
@@ -1,5 +1,4 @@
//! Render the two public configuration files for the narrowly scoped, enrolled //! Render the enrolled script helper settings and peer pin for installation or a signed pair update.
//! development helper. The operator installs them after reviewing the live pair.
use crate::{ use crate::{
helper_ipc::{self as ipc, PeerPin}, helper_ipc::{self as ipc, PeerPin},
helper_system::Settings, helper_system::Settings,
@@ -20,6 +19,8 @@ struct Input {
agent_sha256: String, agent_sha256: String,
helper_sha256: String, helper_sha256: String,
max_runtime_seconds: u32, max_runtime_seconds: u32,
#[serde(default)]
managed_scripts: bool,
} }
pub fn render() -> Result<()> { pub fn render() -> Result<()> {
@@ -47,8 +48,8 @@ pub fn render() -> Result<()> {
binary_sha256: digest, binary_sha256: digest,
}) })
}; };
let settings = Settings { let mut settings = Settings {
schema_version: 3, schema_version: if data.managed_scripts { 5 } else { 3 },
binding: data.binding, binding: data.binding,
agent: role( agent: role(
crate::SERVICE_NAME, crate::SERVICE_NAME,
@@ -63,13 +64,26 @@ pub fn render() -> Result<()> {
data.helper_sha256, data.helper_sha256,
)?, )?,
allowed_services: vec![], allowed_services: vec![],
max_runtime_seconds: 30, max_runtime_seconds: if data.managed_scripts { 120 } else { 30 },
enable_effects: true, enable_effects: true,
allow_reboot: false, allow_reboot: false,
allowed_msi_recipe_sha256: None, allowed_msi_recipe_sha256: None,
allowed_script_profiles: None, allowed_script_profiles: data.managed_scripts.then(|| {
vec![rmm_domain::jobs::PrivilegedScriptProfile::FullMaintenanceV1]
}),
windows_update_max_runtime_seconds: Some(data.max_runtime_seconds), windows_update_max_runtime_seconds: Some(data.max_runtime_seconds),
}; };
if data.managed_scripts && std::path::Path::new(crate::helper_system::CONFIG_PATH).try_exists()? {
// Older fixed workers call this same renderer without a predecessor
// argument. Read the protected local settings before changing image pins.
let (previous, _pins) = crate::helper_system::read_settings()?;
ensure!(
previous.managed_scripts()
&& ipc::binding_hash(&previous.binding)? == ipc::binding_hash(&settings.binding)?,
"MANAGED_SCRIPT_PREDECESSOR_SCOPE"
);
settings = Settings { agent: settings.agent, helper: settings.helper, ..previous };
}
settings.validate()?; settings.validate()?;
let pin = settings.pin()?; let pin = settings.pin()?;
let result = serde_json::json!({"helper_settings":serde_json::to_string(&settings)?, let result = serde_json::json!({"helper_settings":serde_json::to_string(&settings)?,
+1 -1
View File
@@ -21,7 +21,7 @@ sha2.workspace = true
tokio.workspace = true tokio.workspace = true
tokio-tungstenite.workspace = true tokio-tungstenite.workspace = true
uuid.workspace = true uuid.workspace = true
rusqlite = { version = "0.32.1", features = ["bundled"] } rusqlite.workspace = true
fs2 = "0.4.3" fs2 = "0.4.3"
rmm-domain = { path = "../domain" } rmm-domain = { path = "../domain" }
rmm-protocol = { path = "../protocol" } rmm-protocol = { path = "../protocol" }
+5 -285
View File
@@ -1,241 +1,8 @@
//! Approved artifact prefetch before a grant; Full independently admits the handoff. //! Passive signed-release observations and retained update evidence.
use anyhow::{Context, Result, ensure}; use anyhow::{Context, Result, ensure};
use rmm_domain::{ use rmm_domain::agent_update::Platform;
agent_update::{ use rmm_privileged_helper::Binding;
APPLY_CAPABILITY, ArtifactDescriptor, ArtifactRole, CHECK_CAPABILITY, Platform, use std::path::Path;
},
jobs::{Action, JobPayload},
};
use rmm_privileged_helper::{Binding, Request, control, update_admission::Accepted};
use sha2::{Digest, Sha256};
use std::{
fs::{self, File, OpenOptions},
io::{Read, Write},
os::unix::fs::{MetadataExt, OpenOptionsExt},
path::{Path, PathBuf},
time::{Duration, Instant},
};
const MAXIMUM: u64 = 256 * 1024 * 1024;
const CHUNK: u64 = 512 * 1024;
pub struct Prefetch(pub tokio::task::JoinHandle<Result<()>>);
impl Drop for Prefetch {
fn drop(&mut self) {
self.0.abort();
}
}
fn directory(path: &Path, create: bool) -> Result<()> {
if create && !path.try_exists()? {
std::fs::DirBuilder::new().mode(0o700).create(path)?;
}
let m = fs::symlink_metadata(path)?;
ensure!(
m.is_dir() && !m.file_type().is_symlink() && m.uid() == 993 && m.mode() & 0o777 == 0o700,
"UPDATE_PREFETCH_DIRECTORY"
);
Ok(())
}
use std::os::unix::fs::DirBuilderExt;
fn parent(job: &JobPayload) -> Result<PathBuf> {
ensure!(
unsafe { libc::geteuid() } == 993,
"UPDATE_PREFETCH_AGENT_UID"
);
let base = Path::new("/var/lib/rmm-agent-remote");
directory(base, false)?;
let base = base.join("update-downloads");
directory(&base, true)?;
let base = base.join(job.job_id.to_string());
directory(&base, true)?;
let base = base.join(job.attempt_id.to_string());
directory(&base, true)?;
Ok(base)
}
fn label(a: &ArtifactDescriptor) -> &'static str {
match a.role {
ArtifactRole::Agent => "agent.bin",
ArtifactRole::Helper => "helper.bin",
}
}
fn checked(path: &Path, a: &ArtifactDescriptor) -> Result<()> {
let mut f = OpenOptions::new()
.read(true)
.custom_flags(libc::O_NOFOLLOW | libc::O_CLOEXEC)
.open(path)?;
let m = f.metadata()?;
ensure!(
m.is_file()
&& m.uid() == 993
&& m.mode() & 0o777 == 0o600
&& m.nlink() == 1
&& m.len() == a.bytes,
"UPDATE_PREFETCH_FILE"
);
let mut h = Sha256::new();
let mut n = 0;
let mut buf = [0; 65536];
loop {
let size = f.read(&mut buf)?;
if size == 0 {
break;
}
n += size as u64;
ensure!(n <= a.bytes, "UPDATE_PREFETCH_LENGTH");
h.update(&buf[..size]);
}
ensure!(
n == a.bytes && format!("{:x}", h.finalize()) == a.sha256,
"UPDATE_PREFETCH_DIGEST"
);
Ok(())
}
pub async fn prefetch(client: reqwest::Client, base: String, job: JobPayload) -> Result<()> {
let Action::UpdateAgent { update } = &job.action else {
anyhow::bail!("UPDATE_ACTION_REQUIRED")
};
let manifest = update.manifest().map_err(anyhow::Error::msg)?;
ensure!(
manifest.validate() && manifest.platform == Platform::LinuxX64,
"UPDATE_PREFETCH_MANIFEST"
);
let pjob = job.clone();
let folder = tokio::task::spawn_blocking(move || parent(&pjob)).await??;
let deadline = Instant::now() + Duration::from_secs(600);
for artifact in manifest.artifacts {
ensure!(
artifact.bytes > 0 && artifact.bytes <= MAXIMUM,
"UPDATE_PREFETCH_LIMIT"
);
let path = folder.join(label(&artifact));
let existing = path.clone();
let desc = artifact.clone();
if tokio::task::spawn_blocking(move || -> Result<bool> {
if existing.try_exists()? {
checked(&existing, &desc)?;
Ok(true)
} else {
Ok(false)
}
})
.await??
{
continue;
}
let stage = folder.join(format!("{}.partial", label(&artifact)));
let stage_path = stage.clone();
let mut file = tokio::task::spawn_blocking(move || {
OpenOptions::new()
.write(true)
.create_new(true)
.mode(0o600)
.custom_flags(libc::O_NOFOLLOW | libc::O_CLOEXEC)
.open(stage_path)
})
.await??;
let mut offset = 0;
let mut hash = Sha256::new();
while offset < artifact.bytes {
ensure!(
Instant::now() < deadline && chrono::Utc::now() < job.start_before,
"UPDATE_PREFETCH_EXPIRED"
);
let length = CHUNK.min(artifact.bytes - offset);
let url = format!(
"{base}/agent/v1/update-artifacts/{}?job_id={}&attempt_id={}&offset={offset}&length={length}",
artifact.artifact_id, job.job_id, job.attempt_id
);
let mut response = client.get(&url).send().await?;
let partial = offset != 0 || length != artifact.bytes;
ensure!(
response.url().as_str() == url
&& response.status()
== if partial {
reqwest::StatusCode::PARTIAL_CONTENT
} else {
reqwest::StatusCode::OK
},
"UPDATE_PREFETCH_HTTP"
);
let h = response.headers();
ensure!(
h.get("x-artifact-sha256").and_then(|v| v.to_str().ok())
== Some(artifact.sha256.as_str())
&& h.get("content-type").and_then(|v| v.to_str().ok())
== Some("application/octet-stream")
&& !h.contains_key("content-encoding")
&& response.content_length() == Some(length),
"UPDATE_PREFETCH_HEADERS"
);
if partial {
ensure!(
h.get("content-range").and_then(|v| v.to_str().ok())
== Some(
format!(
"bytes {}-{}/{}",
offset,
offset + length - 1,
artifact.bytes
)
.as_str()
),
"UPDATE_PREFETCH_RANGE"
);
} else {
ensure!(!h.contains_key("content-range"), "UPDATE_PREFETCH_RANGE");
}
let mut bytes = Vec::with_capacity(length as usize);
while let Some(chunk) = response.chunk().await? {
ensure!(
bytes.len() + chunk.len() <= length as usize,
"UPDATE_PREFETCH_BODY_LIMIT"
);
bytes.extend_from_slice(&chunk);
}
ensure!(
bytes.len() == length as usize && Instant::now() < deadline,
"UPDATE_PREFETCH_BODY_LENGTH"
);
hash.update(&bytes);
file = tokio::task::spawn_blocking(move || -> Result<File> {
file.write_all(&bytes)?;
Ok(file)
})
.await??;
offset += length;
}
ensure!(
format!("{:x}", hash.finalize()) == artifact.sha256,
"UPDATE_PREFETCH_DIGEST"
);
let dir = folder.clone();
tokio::task::spawn_blocking(move || -> Result<()> {
file.sync_all()?;
drop(file);
fs::hard_link(&stage, &path)?;
fs::remove_file(stage)?;
File::open(dir)?.sync_all()?;
checked(&path, &artifact)
})
.await??;
}
Ok(())
}
/// No Outcome is invented on acceptance; loss after write stays ambiguous.
pub fn handoff(binding: &Binding, request: &Request, grant: uuid::Uuid) -> Result<Accepted> {
let socket = std::env::var_os("RMM_FULL_MAINTENANCE_HELPER_SOCKET")
.context("UPDATE_FULL_SOCKET_REQUIRED")?;
let pin =
std::env::var_os("RMM_FULL_MAINTENANCE_POLICY_FILE").context("UPDATE_FULL_PIN_REQUIRED")?;
let pin = control::GeneralPin::read(Path::new(&pin), binding)?;
ensure!(
pin.profile == "full_maintenance_v1",
"UPDATE_FULL_PROFILE_REQUIRED"
);
control::general_probe(Path::new(&socket), binding, &pin)?;
let ack: Accepted =
control::exchange(Path::new(&socket), request, Duration::from_secs(50), 4096)?;
ack.matches(request, grant)?;
Ok(ack)
}
/// Opaque public metadata authenticated by the current protected Full peer, /// Opaque public metadata authenticated by the current protected Full peer,
/// with complete guarded history verified there. No caller JSON constructor. /// with complete guarded history verified there. No caller JSON constructor.
@@ -336,57 +103,10 @@ impl Observer {
} }
self.cached() self.cached()
.cloned() .cloned()
.unwrap_or_else(|| Observation::not_configured(Platform::LinuxX64, chrono::Utc::now())) .unwrap_or_else(|| Observation::not_configured(Platform::NATIVE_LINUX, chrono::Utc::now()))
} }
pub fn catalog_record(&self) -> Option<GuardedRecord> { pub fn catalog_record(&self) -> Option<GuardedRecord> {
self.cached()?; self.cached()?;
self.record.clone() self.record.clone()
} }
pub fn capabilities(&self) -> Vec<String> {
let Some(value) = self
.cached()
.filter(|v| v.quality == rmm_domain::agent_update::ObservationQuality::Valid)
else {
return vec![];
};
let (Some(updater), Some(predecessor)) = (&value.updater, &value.predecessor) else {
return vec![];
};
vec![
APPLY_CAPABILITY.into(),
CHECK_CAPABILITY.into(),
"update_agent".into(),
"root:update_agent".into(),
"helper.root.v1".into(),
format!("updater.binary.sha256:{}", updater.binary_sha256),
format!("updater.policy.sha256:{}", updater.policy_sha256),
format!("helper.binary.sha256:{}", predecessor.helper_sha256),
]
}
}
pub fn supported(binding: &Binding, job: &JobPayload) -> bool {
(|| -> Result<bool> {
ensure!(
unsafe { libc::geteuid() } == 993 && job.execution_identity == "root",
"UPDATE_AGENT_PRINCIPAL"
);
let Action::UpdateAgent { update } = &job.action else {
return Ok(false);
};
let observation = rmm_privileged_helper::update_admission::observe(
Path::new("/run/rmm-helper-maintenance/control.sock"),
binding,
Some(update.release_envelope.clone()),
Some(update.updater.keyring_generation),
)?;
Ok(observation.validate()
&& observation.quality == rmm_domain::agent_update::ObservationQuality::Valid
&& observation.predecessor.as_ref() == Some(&update.predecessor)
&& observation.updater.as_ref() == Some(&update.updater)
&& observation.candidate_previews.iter().any(|c| {
c.manifest_sha256 == update.manifest_sha256
&& c.peer_pin_transition == update.peer_pin_transition
}))
})()
.unwrap_or(false)
} }
+9 -7
View File
@@ -15,7 +15,7 @@ use rmm_domain::{
}; };
use rmm_privileged_helper::{Binding, TrustedClock}; use rmm_privileged_helper::{Binding, TrustedClock};
use rmm_updater::{ use rmm_updater::{
ActiveRelease, Platform as ReleasePlatform, ReleaseRelation, SignedRelease, TrustedContext, ActiveRelease, ReleaseRelation, SignedRelease, TrustedContext,
TrustedUpdateKey, UpdateKeyring, verify_release, TrustedUpdateKey, UpdateKeyring, verify_release,
}; };
use serde::Deserialize; use serde::Deserialize;
@@ -346,12 +346,12 @@ impl Trust {
.try_into() .try_into()
.map_err(|_| anyhow::anyhow!("UPDATE_CATALOG_KEY_SIZE"))?; .map_err(|_| anyhow::anyhow!("UPDATE_CATALOG_KEY_SIZE"))?;
ensure!( ensure!(
key.platform == Platform::LinuxX64 && key.public_key_hex != binding.public_key_hex, key.platform == Platform::NATIVE_LINUX && key.public_key_hex != binding.public_key_hex,
"UPDATE_CATALOG_KEY_SEPARATION" "UPDATE_CATALOG_KEY_SEPARATION"
); );
trusted.push(TrustedUpdateKey::new( trusted.push(TrustedUpdateKey::new(
public, public,
ReleasePlatform::LinuxX64, Platform::NATIVE_LINUX.into(),
key.first_sequence, key.first_sequence,
key.last_sequence, key.last_sequence,
key.revoked, key.revoked,
@@ -426,7 +426,7 @@ impl Trust {
}, },
&self.keys, &self.keys,
&TrustedContext { &TrustedContext {
platform: ReleasePlatform::LinuxX64, platform: Platform::NATIVE_LINUX.into(),
now_utc_seconds: now, now_utc_seconds: now,
keyring_generation: self.generation, keyring_generation: self.generation,
protocol_major: self.protocol, protocol_major: self.protocol,
@@ -522,16 +522,18 @@ async fn request(
async fn fetch(client: &reqwest::Client, address: SocketAddr) -> Result<Vec<u8>> { async fn fetch(client: &reqwest::Client, address: SocketAddr) -> Result<Vec<u8>> {
let response = client let response = client
.get(format!( .get(format!(
"https://{}:{}/agent/v1/releases/current?platform=x86_64-unknown-linux-gnu", "https://{}:{}/agent/v1/releases/current?platform={}",
crate::https_channel::server_name()?, crate::https_channel::server_name()?,
address.port() address.port(),
Platform::NATIVE_LINUX.target_triple()
)) ))
.send() .send()
.await?; .await?;
crate::https_channel::bounded_body(response, RESPONSE_LIMIT, "application/json").await crate::https_channel::bounded_body(response, RESPONSE_LIMIT, "application/json").await
} }
#[cfg(test)] // These fixtures provision the legacy x86-64 manual updater profile.
#[cfg(all(test, target_arch = "x86_64"))]
mod tests { mod tests {
use super::*; use super::*;
use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD}; use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};
+1 -1
View File
@@ -319,7 +319,7 @@ pub fn context(
let scope = match job.action { let scope = match job.action {
rmm_domain::jobs::Action::UpdateAgent { ref update } => { rmm_domain::jobs::Action::UpdateAgent { ref update } => {
match update.manifest().map_err(anyhow::Error::msg)?.platform { match update.manifest().map_err(anyhow::Error::msg)?.platform {
update::Platform::LinuxX64 => "linux.base", update::Platform::LinuxX64 | update::Platform::LinuxArm64 => "linux.base",
update::Platform::WindowsX64 | update::Platform::WindowsGnuX64 => "windows.base", update::Platform::WindowsX64 | update::Platform::WindowsGnuX64 => "windows.base",
} }
} }
+4 -357
View File
@@ -1,118 +1,7 @@
//! Dedicated APT route: no fallback to generic helper, shell or SSH. Readiness //! Passive APT observations for installations with a configured planning source.
//! is nonce/root-peer/identity/profile/stack pinned before advertising or use. use anyhow::{Context, Result};
use anyhow::{Context, Result, ensure}; use rmm_privileged_helper::{Binding, readiness};
use rmm_domain::jobs::JobPayload; use std::path::Path;
use rmm_privileged_helper::{Binding, Outcome, Request, apt as provider, readiness};
use std::{
ffi::OsString,
path::{Path, PathBuf},
};
pub fn socket_for(
job: &JobPayload,
general: Option<OsString>,
apt: Option<OsString>,
) -> Result<PathBuf> {
if job.action.full_maintenance() {
return Ok(PathBuf::from(
std::env::var_os("RMM_FULL_MAINTENANCE_HELPER_SOCKET")
.context("FULL_MAINTENANCE_SOCKET_NOT_CONFIGURED")?,
));
}
select_socket(provider::is_apt_action(job), general, apt)
}
fn select_socket(
is_apt: bool,
general: Option<OsString>,
apt: Option<OsString>,
) -> Result<PathBuf> {
if is_apt {
let socket = PathBuf::from(apt.context("APT_HELPER_SOCKET_NOT_CONFIGURED")?);
ensure!(
socket == Path::new(readiness::SOCKET),
"APT_HELPER_SOCKET_PROFILE"
);
Ok(socket)
} else {
Ok(PathBuf::from(
general.context("GENERAL_HELPER_SOCKET_NOT_CONFIGURED")?,
))
}
}
fn status(binding: &Binding) -> Result<readiness::Response> {
let path =
std::env::var_os("RMM_APT_HELPER_PROOF_FILE").context("APT_HELPER_PIN_NOT_CONFIGURED")?;
let pin = readiness::Pin::read(Path::new(&path), binding)?;
let socket =
std::env::var_os("RMM_APT_HELPER_SOCKET").context("APT_HELPER_SOCKET_NOT_CONFIGURED")?;
readiness::probe(Path::new(&socket), binding, &pin)
}
fn recovery_status(binding: &Binding) -> Result<readiness::Response> {
let path =
std::env::var_os("RMM_APT_HELPER_PROOF_FILE").context("APT_RECOVERY_PIN_REQUIRED")?;
let pin = readiness::Pin::read(Path::new(&path), binding)?;
let socket =
std::env::var_os("RMM_APT_HELPER_SOCKET").context("APT_RECOVERY_SOCKET_REQUIRED")?;
readiness::planning_for_recovery(Path::new(&socket), binding, &pin)
}
pub fn capabilities_from(response: &readiness::Response) -> Vec<String> {
if response.profile != "apt_only" {
return vec![];
}
let mut result = vec![];
if response.fixture_acceptance_ready && !response.bootstrap_recipes.is_empty() {
result.push("apt_native_acceptance".into());
}
if !response.accepted_recipes.is_empty() {
result.push("ensure_package".into());
}
if response
.accepted_recipes
.iter()
.any(|r| r == provider::UPDATE_RECIPE)
{
result.push("apply_updates".into());
}
result
}
pub fn capabilities(binding: &Binding) -> Vec<String> {
let normal = status(binding)
.map(|s| {
let mut caps = capabilities_from(&s);
if !caps.is_empty() {
let roots: Vec<String> = caps.iter().map(|c| format!("root:{c}")).collect();
caps.extend(roots);
caps.extend([
"helper.root.v1".into(),
format!("helper.policy.sha256:{}", s.provider_stack_sha256),
"apt.manifest.v2".into(),
]);
if s.fixture_acceptance_ready && !s.bootstrap_recipes.is_empty() {
caps.push("apt.native-acceptance.v1".into());
}
if !s.accepted_recipes.is_empty() {
caps.push("apt.native-accepted.v1".into());
}
}
caps
})
.unwrap_or_default();
if !normal.is_empty() {
return normal;
}
recovery_status(binding)
.map(|s| {
vec![
"apt_native_acceptance".into(),
"root:apt_native_acceptance".into(),
"helper.root.v1".into(),
format!("helper.policy.sha256:{}", s.provider_stack_sha256),
"apt.manifest.v2".into(),
"apt.native-acceptance.v1".into(),
]
})
.unwrap_or_default()
}
/// Called only by the periodic blocking inventory worker, never heartbeat or a /// Called only by the periodic blocking inventory worker, never heartbeat or a
/// caller-selected live query. Failure retains honest unknown/not_configured. /// caller-selected live query. Failure retains honest unknown/not_configured.
@@ -142,103 +31,6 @@ pub fn planning_observation(binding: Option<&Binding>) -> serde_json::Value {
} }
} }
} }
fn recipe_ready(job: &JobPayload, response: &readiness::Response) -> Result<()> {
ensure!(
job.execution_identity == "root" && provider::is_apt_action(job),
"APT_TYPED_ROOT_ACTION_REQUIRED"
);
let action = serde_json::to_value(&job.action)?;
let manifest: provider::AptExecutionManifest = serde_json::from_value(
action
.get("apt_manifest")
.context("APT_MANIFEST_NOT_CONFIGURED")?
.clone(),
)?;
manifest.resolved_apt_transaction.validate_fixture()?;
let recipe = &manifest.resolved_apt_transaction.recipe_id;
if let Some(reference) = &manifest.native_recovery {
let planning = response
.planning
.as_ref()
.context("APT_RECOVERY_PLANNING_REQUIRED")?;
planning.validate(chrono::Utc::now())?;
ensure!(
job.action.name() == "apt_native_acceptance"
&& manifest.schema_version == 4
&& manifest.action == "apt-native-acceptance"
&& planning.native_recovery.as_ref() == Some(reference)
&& planning.baseline_sha256 == manifest.resolved_apt_transaction.baseline_sha256
&& planning.status_fingerprint
== manifest.resolved_apt_transaction.status_fingerprint
&& planning.runtime_sha256 == manifest.runtime_sha256
&& planning.provider_sha256 == manifest.provider_sha256
&& planning.hook_sha256 == manifest.hook_sha256
&& planning.apt_config_sha256 == manifest.apt_config_sha256,
"APT_RECOVERY_FRESH_PLAN_BINDING"
);
return Ok(());
}
if job.action.name() == "apt_native_acceptance" {
ensure!(
manifest.action == "apt-native-acceptance"
&& response.fixture_acceptance_ready
&& response.bootstrap_recipes.contains(recipe),
"APT_FIXTURE_READINESS_REQUIRED"
);
} else {
ensure!(
manifest.action == "apt-execute" && response.accepted_recipes.contains(recipe),
"APT_NATIVE_ACCEPTANCE_REQUIRED"
);
ensure!(
job.action.name() != "apply_updates" || recipe == provider::UPDATE_RECIPE,
"APT_UPDATE_RECIPE_SCOPE"
);
}
Ok(())
}
pub fn supported(binding: &Binding, job: &JobPayload) -> bool {
job_status(binding, job)
.and_then(|s| recipe_ready(job, &s))
.is_ok()
}
fn job_status(binding: &Binding, job: &JobPayload) -> Result<readiness::Response> {
if matches!(&job.action,rmm_domain::jobs::Action::AptNativeAcceptance{apt_manifest,..}if apt_manifest.native_recovery.is_some())
{
recovery_status(binding)
} else {
status(binding)
}
}
pub fn invoke(binding: &Binding, job: &JobPayload, request: &Request) -> Result<Outcome> {
let socket = socket_for(
job,
std::env::var_os("RMM_HELPER_SOCKET"),
std::env::var_os("RMM_APT_HELPER_SOCKET"),
)?;
if provider::is_apt_action(job) {
recipe_ready(job, &job_status(binding, job)?)?;
}
rmm_privileged_helper::invoke(&socket, request, job.max_runtime_seconds)
}
pub fn invoke_with_control(
binding: &Binding,
job: &JobPayload,
request: &Request,
observe: impl FnMut() -> Result<()>,
) -> Result<Outcome> {
if !job.action.full_maintenance() {
return invoke(binding, job, request);
}
ensure!(
crate::helper_sync::general_supported(binding, job),
"FULL_MAINTENANCE_POLICY_REQUIRED"
);
let socket = socket_for(job, None, None)?;
rmm_privileged_helper::invoke_controlled(&socket, request, job.max_runtime_seconds, observe)
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
@@ -251,149 +43,4 @@ mod tests {
assert!(observation["data"].is_null()); assert!(observation["data"].is_null());
assert!(observation.get("received_at").is_none()); assert!(observation.get("received_at").is_none());
} }
#[test]
fn typed_actions_require_their_own_fixture_readiness_or_accepted_recipe() {
let id = uuid::Uuid::new_v4();
let now = chrono::Utc::now();
let tx = serde_json::json!({"schema_version":1,"recipe_id":provider::INSTALL_RECIPE,"recipe_version":"1","platform":"ubuntu-24.04-amd64",
"resolver_config_version":"rmm-apt-local-v1","no_reboot":true,"status_fingerprint":"a".repeat(64),"baseline_sha256":"b".repeat(64),
"packages":[{"name":"rmm-mvp-test","architecture":"all","old_version":null,"new_version":"1.0","origin":"rmm-test",
"sha256":rmm_domain::apt_transaction::INSTALL_SHA,"size":20672,
"archive_path":format!("/var/lib/rmm-apt-transaction/archives/{}.deb",rmm_domain::apt_transaction::INSTALL_SHA)}]});
let bytes = serde_json::to_vec(&tx).unwrap();
let manifest = serde_json::json!({"type":"rmm.apt.helper-action","schema_version":2,"action":"apt-native-acceptance","execution_profile":"dev-test",
"transaction_sha256":rmm_domain::jobs::hash(&bytes),"resolved_apt_transaction":tx,"transaction_bytes":bytes,
"provider_sha256":"a".repeat(64),"hook_sha256":"a".repeat(64),"apt_config_sha256":"a".repeat(64),"runtime_sha256":"a".repeat(64),"test_result_id":"fixture-test"});
let mut job:JobPayload=serde_json::from_value(serde_json::json!({"schema_version":1,"tenant_id":id,"asset_id":id,"agent_id":id,
"enrollment_generation":1,"assignment_version":1,"job_id":id,"attempt_id":id,"execution_identity":"root",
"not_before":now,"start_before":now+chrono::Duration::minutes(1),"max_runtime_seconds":300,"max_output_bytes":4096,
"action":{"action":"apt_native_acceptance","recipe_id":provider::INSTALL_RECIPE,"recipe_version":"1","apt_manifest":manifest}})).unwrap();
assert!(job.action.validate());
let identity = readiness::Identity {
tenant_id: id,
asset_id: id,
agent_id: id,
enrollment_generation: 1,
assignment_version: 1,
signing_key_id: "a".repeat(64),
};
let mut response = readiness::Response {
schema_version: 1,
challenge: id,
identity,
profile: "apt_only".into(),
provider_stack_sha256: "a".repeat(64),
fixture_acceptance_ready: true,
bootstrap_recipes: vec![provider::INSTALL_RECIPE.into()],
accepted_recipes: vec![],
ledger_device: 1,
ledger_inode: 2,
lock_device: 1,
lock_inode: 3,
planning: None,
};
recipe_ready(&job, &response).unwrap();
let mut normal = manifest;
normal["action"] = serde_json::json!("apt-execute");
job.action=serde_json::from_value(serde_json::json!({"action":"ensure_package","provider":"apt","package":"rmm-mvp-test","version":"1.0",
"architecture":"all","recipe_version":"1","installation_context":"system","recipe_id":provider::INSTALL_RECIPE,"apt_manifest":normal})).unwrap();
assert!(job.action.validate());
assert!(recipe_ready(&job, &response).is_err());
response.accepted_recipes = vec![provider::UPDATE_RECIPE.into()];
assert!(recipe_ready(&job, &response).is_err());
response.accepted_recipes = vec![provider::INSTALL_RECIPE.into()];
recipe_ready(&job, &response).unwrap();
}
#[test]
fn apt_route_cannot_fall_back_to_general_or_a_caller_path() {
assert!(select_socket(true, Some("/run/general.sock".into()), None).is_err());
assert!(
select_socket(
true,
Some("/run/general.sock".into()),
Some("/tmp/fake.sock".into())
)
.is_err()
);
assert_eq!(
select_socket(
true,
Some("/run/general.sock".into()),
Some(readiness::SOCKET.into())
)
.unwrap(),
Path::new(readiness::SOCKET)
);
}
#[test]
fn bootstrap_readiness_never_claims_package_acceptance() {
let id = readiness::Identity {
tenant_id: uuid::Uuid::new_v4(),
asset_id: uuid::Uuid::new_v4(),
agent_id: uuid::Uuid::new_v4(),
enrollment_generation: 1,
assignment_version: 1,
signing_key_id: "a".repeat(64),
};
let mut response = readiness::Response {
schema_version: 1,
challenge: uuid::Uuid::new_v4(),
identity: id,
profile: "apt_only".into(),
provider_stack_sha256: "a".repeat(64),
fixture_acceptance_ready: true,
bootstrap_recipes: vec![provider::INSTALL_RECIPE.into()],
accepted_recipes: vec![],
ledger_device: 1,
ledger_inode: 2,
lock_device: 1,
lock_inode: 3,
planning: None,
};
assert_eq!(capabilities_from(&response), vec!["apt_native_acceptance"]);
response.accepted_recipes = vec![provider::INSTALL_RECIPE.into()];
assert!(!capabilities_from(&response).contains(&"apply_updates".into()));
response
.accepted_recipes
.push(provider::UPDATE_RECIPE.into());
assert!(capabilities_from(&response).contains(&"apply_updates".into()));
}
#[test]
fn generic_script_never_uses_apt_socket() {
let now = chrono::Utc::now();
let id = uuid::Uuid::new_v4();
let job = JobPayload {
schema_version: 1,
tenant_id: id,
asset_id: id,
agent_id: id,
enrollment_generation: 1,
assignment_version: 1,
job_id: id,
attempt_id: id,
action: rmm_domain::jobs::Action::RunScript {
interpreter: "posix_sh".into(),
script_utf8: "true".into(),
arguments: vec![],
expected_stdout: None,
windows_execution_profile: None,
privileged_script_profile: None,
},
execution_identity: "root".into(),
not_before: now,
start_before: now + chrono::Duration::minutes(1),
max_runtime_seconds: 300,
max_output_bytes: 4096,
};
assert!(socket_for(&job, None, Some(readiness::SOCKET.into())).is_err());
assert_eq!(
socket_for(
&job,
Some("/run/general.sock".into()),
Some(readiness::SOCKET.into())
)
.unwrap(),
Path::new("/run/general.sock")
);
}
} }
+61 -90
View File
@@ -41,16 +41,12 @@ fn map(s: &root::Snapshot) -> reconcile::HelperSnapshot {
.collect(), .collect(),
} }
} }
fn general(binding: &Binding, full: bool) -> Result<control::Response> { fn script_helper(binding: &Binding) -> Result<control::Response> {
let (socket_name, pin_name, profile) = if full { let (socket_name, pin_name, profile) = (
( "RMM_FULL_MAINTENANCE_HELPER_SOCKET",
"RMM_FULL_MAINTENANCE_HELPER_SOCKET", "RMM_FULL_MAINTENANCE_POLICY_FILE",
"RMM_FULL_MAINTENANCE_POLICY_FILE", "full_maintenance_v1",
"full_maintenance_v1", );
)
} else {
("RMM_HELPER_SOCKET", "RMM_HELPER_POLICY_FILE", "general")
};
let socket = std::env::var_os(socket_name).context("NO_GENERAL_HELPER")?; let socket = std::env::var_os(socket_name).context("NO_GENERAL_HELPER")?;
let path = std::env::var_os(pin_name).context("GENERAL_POLICY_PIN_REQUIRED")?; let path = std::env::var_os(pin_name).context("GENERAL_POLICY_PIN_REQUIRED")?;
let pin = control::GeneralPin::read(Path::new(&path), binding)?; let pin = control::GeneralPin::read(Path::new(&path), binding)?;
@@ -207,97 +203,72 @@ impl Helpers {
Ok(applied.as_ref().map(map)) Ok(applied.as_ref().map(map))
} }
} }
pub fn general_capabilities(binding: &Binding) -> Vec<String> { pub fn script_capabilities(binding: &Binding) -> Vec<String> {
let mut caps = profile_capabilities(binding, false);
caps.extend(profile_capabilities(binding, true));
caps.sort();
caps.dedup();
caps
}
fn profile_capabilities(binding: &Binding, full: bool) -> Vec<String> {
(|| -> Result<Vec<String>> { (|| -> Result<Vec<String>> {
let response = general(binding, full)?; let response = script_helper(binding)?;
let policy = response.policy.context("NO_GENERAL_POLICY")?; let binary = response
.helper_binary_sha256
.context("SCRIPT_HELPER_BINARY_PROOF_REQUIRED")?;
ensure!(
rmm_agent_linux::actions::Interpreter::PosixSh.available(),
"SCRIPT_INTERPRETER_UNAVAILABLE"
);
let mut caps = vec![ let mut caps = vec![
"run_script".into(),
"root:run_script".into(),
"helper.root.v1".into(), "helper.root.v1".into(),
rmm_domain::jobs::FULL_MAINTENANCE_CAPABILITY.into(),
format!("helper.policy.sha256:{}", response.policy_sha256), format!("helper.policy.sha256:{}", response.policy_sha256),
format!("helper.binary.sha256:{binary}"),
]; ];
if full { if let Some(release) = std::env::var("RMM_SCRIPT_HELPER_RELEASE")
ensure!( .ok()
policy.schema_version == 2 .and_then(|value| Uuid::parse_str(&value).ok())
&& policy.profile == "full_maintenance_v1" .filter(|id| !id.is_nil())
&& policy.allowed_script_profiles.as_deref() {
== Some(&[rmm_domain::jobs::PrivilegedScriptProfile::FullMaintenanceV1]), caps.push(format!("script.helper.release:{release}"));
"FULL_MAINTENANCE_POLICY_REQUIRED"
);
let binary = policy
.helper_binary_sha256
.as_ref()
.context("FULL_MAINTENANCE_BINARY_PIN_REQUIRED")?;
ensure!(
response.helper_binary_sha256.as_ref() == Some(binary),
"FULL_MAINTENANCE_BINARY_PROOF_REQUIRED"
);
caps.push(format!("helper.binary.sha256:{binary}"));
caps.push(rmm_domain::jobs::FULL_MAINTENANCE_CAPABILITY.into());
}
let mut actions = vec![];
if policy.allow_root_scripts && rmm_agent_linux::actions::Interpreter::PosixSh.available() {
actions.push("run_script");
}
if !policy.allowed_services.is_empty() {
actions.extend(["set_service_state", "query_logs"]);
}
if policy.allow_reboot {
actions.push("reboot");
}
for action in actions {
caps.push(action.into());
caps.push(format!("root:{action}"));
} }
Ok(caps) Ok(caps)
})() })()
.unwrap_or_default() .unwrap_or_default()
} }
pub fn general_supported(binding: &Binding, job: &rmm_domain::jobs::JobPayload) -> bool {
(|| -> Result<bool> { pub fn script_supported(binding: &Binding, job: &rmm_domain::jobs::JobPayload) -> bool {
let p = general(binding, job.action.full_maintenance())? let rmm_domain::jobs::Action::RunScript { interpreter, .. } = &job.action else {
.policy return false;
.context("NO_GENERAL_POLICY")?; };
Ok(match &job.action { job.execution_identity == "root"
rmm_domain::jobs::Action::RunScript { interpreter, .. } => { && job.action.full_maintenance()
p.allow_root_scripts && job.action.valid_execution_identity(&job.execution_identity)
&& job.action.valid_execution_identity(&job.execution_identity) && job
&& job .action
.action .valid_job_limits(job.max_runtime_seconds, job.max_output_bytes)
.valid_job_limits(job.max_runtime_seconds, job.max_output_bytes) && match interpreter.as_str() {
&& (!job.action.full_maintenance() "posix_sh" => rmm_agent_linux::actions::Interpreter::PosixSh.available(),
|| p.allowed_script_profiles.as_ref().is_some_and(|v| { "bash" => rmm_agent_linux::actions::Interpreter::Bash.available(),
v.contains(
&rmm_domain::jobs::PrivilegedScriptProfile::FullMaintenanceV1,
)
}))
&& match interpreter.as_str() {
"posix_sh" => rmm_agent_linux::actions::Interpreter::PosixSh.available(),
"bash" => rmm_agent_linux::actions::Interpreter::Bash.available(),
_ => false,
}
}
rmm_domain::jobs::Action::SetServiceState { unit, state } => {
p.allowed_services.contains(unit)
&& matches!(state.as_str(), "running" | "stopped")
&& job.max_runtime_seconds >= 180
}
rmm_domain::jobs::Action::QueryLogs { unit, .. } => {
p.allowed_services.contains(unit) && job.max_runtime_seconds >= 20
}
rmm_domain::jobs::Action::Reboot { .. } => {
p.allow_reboot && job.max_runtime_seconds >= 60
}
_ => false, _ => false,
}) }
})() && script_helper(binding).is_ok()
.unwrap_or(false) }
pub fn invoke_script(
binding: &Binding,
job: &rmm_domain::jobs::JobPayload,
request: &rmm_privileged_helper::Request,
observe: impl FnMut() -> Result<()>,
) -> Result<rmm_privileged_helper::Outcome> {
ensure!(
script_supported(binding, job),
"SCRIPT_HELPER_POLICY_REQUIRED"
);
let socket = std::env::var_os("RMM_FULL_MAINTENANCE_HELPER_SOCKET")
.context("SCRIPT_HELPER_SOCKET_REQUIRED")?;
rmm_privileged_helper::invoke_controlled(
Path::new(&socket),
request,
job.max_runtime_seconds,
observe,
)
} }
impl Helpers { impl Helpers {
+45 -225
View File
@@ -1,183 +1,46 @@
use anyhow::{Result, ensure}; use anyhow::Result;
#[cfg(test)] #[cfg(test)]
use prost::Message; use prost::Message;
#[cfg(test)] #[cfg(test)]
use rmm_domain::jobs::hash; use rmm_domain::jobs::hash;
use rmm_domain::jobs::{Action, JobPayload}; use rmm_domain::jobs::{Action, JobPayload};
use rmm_privileged_helper::{Binding, Outcome}; use rmm_privileged_helper::Binding;
use rmm_protocol::*; use rmm_protocol::*;
use rusqlite::Connection; use rusqlite::Connection;
#[cfg(test)] #[cfg(test)]
use uuid::Uuid; use uuid::Uuid;
pub fn supported(job: &JobPayload) -> bool { pub fn supported_with_binding(job: &JobPayload, binding: Option<&Binding>) -> bool {
if rmm_privileged_helper::apt::is_apt_action(job) { let Action::RunScript { interpreter, .. } = &job.action else {
// A configured environment path alone is never a capability proof. return false;
// Caller binding is independently provisioned, not taken from the job. };
if unsafe { libc::geteuid() } == 0
|| !job.action.valid_execution_identity(&job.execution_identity)
{
return false; return false;
} }
// The network process must never execute a script with accidental root. match job.execution_identity.as_str() {
supported_as( "root" => {
job, job.action.full_maintenance()
unsafe { libc::geteuid() }, && binding.is_some_and(|b| crate::helper_sync::script_supported(b, job))
std::env::var_os("RMM_HELPER_SOCKET").is_some(),
)
}
pub fn supported_with_binding(job: &JobPayload, binding: Option<&Binding>) -> bool {
if matches!(job.action, Action::UpdateAgent { .. }) {
return binding.is_some_and(|b| crate::agent_update_apply::supported(b, job));
}
if rmm_privileged_helper::apt::is_apt_action(job) {
// SAFETY: geteuid has no preconditions.
return unsafe { libc::geteuid() } != 0
&& binding.is_some_and(|b| crate::apt::supported(b, job));
}
if job.execution_identity == "root" {
return unsafe { libc::geteuid() } != 0
&& binding.is_some_and(|b| crate::helper_sync::general_supported(b, job));
}
supported(job)
}
fn supported_as(job: &JobPayload, uid: u32, helper_configured: bool) -> bool {
let unprivileged = uid != 0;
if job.execution_identity == "root" && unprivileged {
return helper_configured
&& matches!(
job.action,
Action::RunScript { .. } | Action::SetServiceState { .. } | Action::Reboot { .. }
);
}
job.execution_identity == "agent_service"
&& unprivileged
&& match &job.action {
Action::RunScript { interpreter, .. } => match interpreter.as_str() {
"posix_sh" => rmm_agent_linux::actions::Interpreter::PosixSh.available(),
"bash" => rmm_agent_linux::actions::Interpreter::Bash.available(),
_ => false,
},
Action::RefreshInventory { scope } => scope == "linux.base",
Action::QueryLogs { .. } => log_request(job).is_ok(),
_ => false,
} }
"agent_service" => match interpreter.as_str() {
"posix_sh" => rmm_agent_linux::actions::Interpreter::PosixSh.available(),
"bash" => rmm_agent_linux::actions::Interpreter::Bash.available(),
_ => false,
},
_ => false,
}
} }
pub use rmm_agent_core::jobs::{ pub use rmm_agent_core::jobs::{
denied_request, ack, event, events, interrupted, interrupted_request, next, no_start, permit_request, ack, denied_request, event, events, interrupted, interrupted_request, next, no_start,
recover_interrupted_outcome, requesting, reserve_request, result, transition, permit_request, recover_interrupted_outcome, requesting, reserve_request, result, transition,
}; };
pub fn accept(db: &Connection, binding: &Binding, offer: &JobOffer) -> Result<bool> { pub fn accept(db: &Connection, binding: &Binding, offer: &JobOffer) -> Result<bool> {
rmm_agent_core::jobs::accept(db, binding, offer, |job| { rmm_agent_core::jobs::accept(db, binding, offer, |job| {
supported_with_binding(job, Some(binding)) supported_with_binding(job, Some(binding))
}) })
} }
pub fn execute(job: &JobPayload) -> Outcome {
let result = match &job.action {
Action::RunScript { .. } => rmm_privileged_helper::script(job),
Action::RefreshInventory { .. } => rmm_agent_linux::collect().and_then(|i| {
let bytes = serde_json::to_vec(&i)?;
ensure!(bytes.len() <= job.max_output_bytes as usize, "INVENTORY_OUTPUT_LIMIT");
Ok(Outcome { state: "succeeded".into(), stdout: bytes, stderr: vec![], exit_code: None,
output_truncated: false, reboot_required: false,
evidence: serde_json::json!({"postconditions_passed":true,"source_id":"linux.base","observed_at":chrono::Utc::now(),"completeness":"partial"}), error_code: String::new() })
}),
Action::QueryLogs { .. } => query_logs(job),
_ => Err(anyhow::anyhow!("unsupported action")),
};
result.unwrap_or_else(|_| Outcome::unknown("EXECUTOR_EFFECT_UNKNOWN"))
}
fn allowed_log_units() -> Result<Vec<rmm_agent_linux::actions::ServiceUnit>> {
let path = std::env::var_os("RMM_LOG_UNITS_FILE")
.ok_or_else(|| anyhow::anyhow!("LOG_ALLOWLIST_NOT_CONFIGURED"))?;
let path = std::path::Path::new(&path);
rmm_privileged_helper::private_path(path, unsafe { libc::geteuid() }, false)?;
ensure!(
std::fs::metadata(path)?.len() <= 32768,
"LOG_ALLOWLIST_SIZE"
);
let units: Vec<String> = serde_json::from_slice(&std::fs::read(path)?)?;
ensure!(
!units.is_empty() && units.len() <= 128,
"LOG_ALLOWLIST_SIZE"
);
units
.iter()
.map(|u| rmm_agent_linux::actions::ServiceUnit::new(u))
.collect()
}
pub fn logs_available() -> bool {
allowed_log_units().is_ok()
&& rmm_agent_linux::inventory::capabilities()
.get("logs.journald")
.is_some_and(|o| o.data == Some(true))
}
fn log_request(job: &JobPayload) -> Result<rmm_agent_linux::inventory::JournalRequest> {
log_request_for(job, &allowed_log_units()?)
}
fn log_request_for(
job: &JobPayload,
allowed: &[rmm_agent_linux::actions::ServiceUnit],
) -> Result<rmm_agent_linux::inventory::JournalRequest> {
let Action::QueryLogs {
unit,
since,
until,
max_lines,
} = &job.action
else {
anyhow::bail!("NOT_LOG_QUERY")
};
ensure!(job.max_runtime_seconds >= 20, "LOG_RUNTIME_TOO_SHORT");
rmm_agent_linux::inventory::JournalRequest::new(
rmm_agent_linux::actions::ServiceUnit::new(unit)?,
allowed,
u64::try_from(since.timestamp())?,
u64::try_from(until.timestamp())?,
*max_lines as usize,
(job.max_output_bytes as usize).min(256 * 1024),
)?
.precise_window(*since, *until)
}
fn query_logs(job: &JobPayload) -> Result<Outcome> {
let observation = rmm_agent_linux::inventory::query_journal(&log_request(job)?);
let valid = observation.quality == rmm_agent_linux::inventory::Quality::Valid;
let error = observation.error_code.clone().unwrap_or_default();
let mut value = serde_json::to_value(&observation)?;
while serde_json::to_vec(&value)?.len() > job.max_output_bytes as usize {
let Some(lines) = value["data"]["json_lines"]
.as_array_mut()
.filter(|v| !v.is_empty())
else {
return Ok(Outcome {
state: "failed".into(),
..Outcome::unknown("LOG_RESULT_METADATA_EXCEEDS_OUTPUT_LIMIT")
});
};
lines.remove(0);
value["truncated"] = serde_json::json!(true);
value["completeness"] = serde_json::json!("partial");
value["error_code"] = serde_json::json!("LOG_SERIALIZED_OUTPUT_LIMIT");
}
Ok(Outcome {
state: if valid { "succeeded" } else { "failed" }.into(),
stdout: serde_json::to_vec(&value)?,
stderr: vec![],
exit_code: None,
output_truncated: value["truncated"] == true,
reboot_required: false,
evidence: serde_json::json!({"postconditions_passed":valid,"source_id":observation.source_id,
"observed_at":value["observed_at"],"quality":value["quality"],"completeness":value["completeness"],
"cursor_status":"not_advanced_no_ack_contract","provider_error_code":error}),
error_code: if valid {
String::new()
} else if error.is_empty() {
"LOG_PROVIDER_UNAVAILABLE".into()
} else {
error
},
})
}
/// With no backend SyncResponse contract, a reconnect/restart cannot prove an
/// earlier reservation never started. Telemetry and evidence replay continue;
/// all new effects stop. Do not paper over this with a new start request. /// all new effects stop. Do not paper over this with a new start request.
#[cfg(test)] #[cfg(test)]
pub fn begin_session(db: &Connection) -> Result<bool> { pub fn begin_session(db: &Connection) -> Result<bool> {
@@ -228,8 +91,13 @@ mod tests {
assignment_version: 2, assignment_version: 2,
job_id: Uuid::new_v4(), job_id: Uuid::new_v4(),
attempt_id: Uuid::new_v4(), attempt_id: Uuid::new_v4(),
action: Action::RefreshInventory { action: Action::RunScript {
scope: "linux.base".into(), interpreter: "posix_sh".into(),
script_utf8: "true".into(),
arguments: vec![],
expected_stdout: None,
windows_execution_profile: None,
privileged_script_profile: None,
}, },
execution_identity: "agent_service".into(), execution_identity: "agent_service".into(),
not_before: now, not_before: now,
@@ -254,7 +122,7 @@ mod tests {
let mut db = storage::open(&path).unwrap(); let mut db = storage::open(&path).unwrap();
let job = binding.job(&offer.payload_bytes).unwrap(); let job = binding.job(&offer.payload_bytes).unwrap();
if unsafe { libc::geteuid() } == 0 { if unsafe { libc::geteuid() } == 0 {
assert!(!supported(&job)); assert!(!supported_with_binding(&job, Some(&binding)));
assert!(accept(&db, &binding, &offer).is_err()); assert!(accept(&db, &binding, &offer).is_err());
} else { } else {
assert!(accept(&db, &binding, &offer).unwrap()); assert!(accept(&db, &binding, &offer).unwrap());
@@ -326,20 +194,24 @@ mod tests {
std::fs::remove_dir_all(path).unwrap(); std::fs::remove_dir_all(path).unwrap();
} }
#[test] #[test]
fn network_process_never_executes_as_accidental_root() { fn legacy_actions_and_unbound_root_are_rejected_before_any_reservation() {
let (path, binding, offer) = fixture(); let (path, binding, offer) = fixture();
let mut job = binding.job(&offer.payload_bytes).unwrap(); let mut job = binding.job(&offer.payload_bytes).unwrap();
assert!(!supported_as(&job, 0, false));
assert!(!supported_as(&job, 0, true));
job.execution_identity = "root".into(); job.execution_identity = "root".into();
assert!(!supported_as(&job, 1000, false)); assert!(!supported_with_binding(&job, Some(&binding)));
assert!(!supported_as(&job, 0, true)); for identity in ["agent_service", "root"] {
job.action = Action::Reboot { job.execution_identity = identity.into();
reason: "explicit root only".into(), job.action = Action::Reboot {
reconnect_timeout_seconds: 60, reason: "legacy fixture".into(),
dependency_group: "test".into(), reconnect_timeout_seconds: 60,
}; dependency_group: "test".into(),
assert!(supported_as(&job, 1000, true)); };
assert!(!supported_with_binding(&job, Some(&binding)));
job.action = Action::RefreshInventory {
scope: "linux.base".into(),
};
assert!(!supported_with_binding(&job, Some(&binding)));
}
std::fs::remove_dir_all(path).unwrap(); std::fs::remove_dir_all(path).unwrap();
} }
#[test] #[test]
@@ -363,56 +235,4 @@ mod tests {
drop(db); drop(db);
std::fs::remove_dir_all(path).unwrap(); std::fs::remove_dir_all(path).unwrap();
} }
#[test]
fn live_logs_enforce_actual_action_window_allowlist_limits_and_runtime() {
let (path, binding, offer) = fixture();
let mut job = binding.job(&offer.payload_bytes).unwrap();
let unit = rmm_agent_linux::actions::ServiceUnit::new("rmm-test.service").unwrap();
let now = chrono::Utc::now();
job.max_runtime_seconds = 20;
job.action = Action::QueryLogs {
unit: unit.as_str().into(),
since: now - chrono::Duration::minutes(1),
until: now,
max_lines: 10,
};
assert!(log_request_for(&job, &[]).is_err());
assert!(log_request_for(&job, std::slice::from_ref(&unit)).is_ok());
job.max_runtime_seconds = 10;
assert!(log_request_for(&job, std::slice::from_ref(&unit)).is_err());
job.max_runtime_seconds = 20;
job.action = Action::QueryLogs {
unit: unit.as_str().into(),
since: now - chrono::Duration::hours(25),
until: now,
max_lines: 10,
};
assert!(log_request_for(&job, std::slice::from_ref(&unit)).is_err());
job.action = Action::QueryLogs {
unit: unit.as_str().into(),
since: now - chrono::Duration::minutes(1),
until: now,
max_lines: 1001,
};
assert!(log_request_for(&job, std::slice::from_ref(&unit)).is_err());
std::fs::remove_dir_all(path).unwrap();
}
#[test]
fn refresh_is_a_new_measurement_with_real_observation_time() {
let (path, binding, offer) = fixture();
let job = binding.job(&offer.payload_bytes).unwrap();
let before = chrono::Utc::now();
let outcome = execute(&job);
assert_eq!(outcome.state, "succeeded");
let observed =
chrono::DateTime::parse_from_rfc3339(outcome.evidence["observed_at"].as_str().unwrap())
.unwrap();
assert!(observed >= before);
assert!(
serde_json::from_slice::<rmm_domain::Inventory>(&outcome.stdout)
.unwrap()
.validate()
);
std::fs::remove_dir_all(path).unwrap();
}
} }
+20 -38
View File
@@ -425,15 +425,8 @@ impl<C: reconcile::SyncClock> Agent<C> {
|| binding.verify(&request, Utc::now()).is_err() || binding.verify(&request, Utc::now()).is_err()
{ {
jobs::no_start("failed", "START_WINDOW_OR_CLOCK_INVALID_BEFORE_EFFECT") jobs::no_start("failed", "START_WINDOW_OR_CLOCK_INVALID_BEFORE_EFFECT")
} else if matches!(job.action, rmm_domain::jobs::Action::UpdateAgent { .. }) {
match agent_update_apply::handoff(&binding, &request, grant.grant_id) {
// Full now owns this original. The stable updater may
// stop us. Reconciliation alone supplies its final result.
Ok(_) => return,
Err(_) => rmm_privileged_helper::Outcome::unknown("UPDATE_HANDOFF_UNCONFIRMED"),
}
} else if job.execution_identity == "root" { } else if job.execution_identity == "root" {
apt::invoke_with_control(&binding, &job, &request, || { helper_sync::invoke_script(&binding, &job, &request, || {
ensure!( ensure!(
!cancellation.load(Ordering::SeqCst) !cancellation.load(Ordering::SeqCst)
&& fence.running_generation.load(Ordering::SeqCst) == generation && fence.running_generation.load(Ordering::SeqCst) == generation
@@ -446,7 +439,7 @@ impl<C: reconcile::SyncClock> Agent<C> {
rmm_privileged_helper::Outcome::unknown("HELPER_TRANSPORT_EFFECT_UNKNOWN") rmm_privileged_helper::Outcome::unknown("HELPER_TRANSPORT_EFFECT_UNKNOWN")
}) })
} else { } else {
jobs::execute(&job) rmm_privileged_helper::script(&job).unwrap_or_else(|_| rmm_privileged_helper::Outcome::unknown("EXECUTOR_EFFECT_UNKNOWN"))
}; };
let _ = completed.blocking_send((offer, grant, outcome)); let _ = completed.blocking_send((offer, grant, outcome));
}); });
@@ -472,6 +465,8 @@ impl<C: reconcile::SyncClock> Agent<C> {
"heartbeat/1".into(), "heartbeat/1".into(),
"agent.update/1".into(), "agent.update/1".into(),
]; ];
#[cfg(target_arch = "aarch64")]
capabilities.push(rmm_domain::agent_update::LINUX_ARM64_RELEASE_CAPABILITY.into());
if self.binding.is_some() { if self.binding.is_some() {
capabilities.push("rmm.sync.v1".into()); capabilities.push("rmm.sync.v1".into());
} }
@@ -481,15 +476,7 @@ impl<C: reconcile::SyncClock> Agent<C> {
if rmm_agent_linux::actions::Interpreter::PosixSh.available() { if rmm_agent_linux::actions::Interpreter::PosixSh.available() {
capabilities.push("run_script".into()); capabilities.push("run_script".into());
} }
capabilities.push("refresh_inventory".into()); capabilities.extend(helper_sync::script_capabilities(binding));
if jobs::logs_available() {
capabilities.push("query_logs".into());
}
capabilities.extend(apt::capabilities(binding));
capabilities.extend(helper_sync::general_capabilities(binding));
if self.clock.trusted() {
capabilities.extend(self.update_observer.capabilities());
}
} }
capabilities.sort(); capabilities.sort();
capabilities.dedup(); capabilities.dedup();
@@ -662,6 +649,7 @@ impl<C: reconcile::SyncClock> Agent<C> {
let mut inventory_at = Instant::now(); let mut inventory_at = Instant::now();
let mut update_at = Instant::now(); let mut update_at = Instant::now();
let mut heartbeat_at = Instant::now(); let mut heartbeat_at = Instant::now();
let mut previous_cpu = None;
let mut heartbeat_after = Duration::from_millis(rand::random_range(27_000..33_000)); let mut heartbeat_after = Duration::from_millis(rand::random_range(27_000..33_000));
let mut tick = tokio::time::interval(Duration::from_secs(5)); let mut tick = tokio::time::interval(Duration::from_secs(5));
let mut sync_at = Instant::now(); let mut sync_at = Instant::now();
@@ -670,8 +658,6 @@ impl<C: reconcile::SyncClock> Agent<C> {
let mut first_heartbeat = true; let mut first_heartbeat = true;
let mut health_task: Option<PendingUpdateHealth> = None; let mut health_task: Option<PendingUpdateHealth> = None;
let mut health_inventory_prefix: Option<String> = None; let mut health_inventory_prefix: Option<String> = None;
let mut update_prefetch: Option<(JobOffer, agent_update_apply::Prefetch)> = None;
let mut prefetched = std::collections::HashSet::new();
loop { loop {
tokio::select! { tokio::select! {
Some(result) = self.inventory_rx.recv() => { Some(result) = self.inventory_rx.recv() => {
@@ -748,7 +734,6 @@ impl<C: reconcile::SyncClock> Agent<C> {
// First preserve the original completion without unlocking. // First preserve the original completion without unlocking.
// A startup can replay it if the journal transaction is lost. // A startup can replay it if the journal transaction is lost.
let state = outcome.state.clone(); let state = outcome.state.clone();
let refresh_capabilities=state=="succeeded" && serde_json::from_slice::<rmm_domain::jobs::JobPayload>(&offer.payload_bytes)?.action.name()=="apt_native_acceptance";
rmm_privileged_helper::persist_outcome(&self.ledger,&grant,&outcome)?; rmm_privileged_helper::persist_outcome(&self.ledger,&grant,&outcome)?;
let serialized = serde_json::to_vec(&outcome)?; let serialized = serde_json::to_vec(&outcome)?;
self.record(generation, &offer, &grant.grant_id.to_string(), outcome)?; self.record(generation, &offer, &grant.grant_id.to_string(), outcome)?;
@@ -756,17 +741,9 @@ impl<C: reconcile::SyncClock> Agent<C> {
rmm_privileged_helper::finish(&self.ledger, &grant, &outcome)?; rmm_privileged_helper::finish(&self.ledger, &grant, &outcome)?;
if state == "unknown" { eprintln!("job effect unknown: device execution lock retained"); } if state == "unknown" { eprintln!("job effect unknown: device execution lock retained"); }
needs_sync=true;self.replay(&ws, generation).await?; needs_sync=true;self.replay(&ws, generation).await?;
if refresh_capabilities {return Ok(());}
} }
_ = tick.tick() => { _ = tick.tick() => {
self.replay(&ws, generation).await?; self.replay(&ws, generation).await?;
if update_prefetch.as_ref().is_some_and(|(_,task)|task.0.is_finished()) {
let (offer, mut task)=update_prefetch.take().context("UPDATE_PREFETCH_REQUIRED")?;
match (&mut task.0).await {
Ok(Ok(())) => {prefetched.insert((offer.job_id.clone(),offer.attempt_id.clone()));},
_ => {self.record(generation,&offer,"",jobs::no_start("failed","UPDATE_ARTIFACT_PREFETCH_FAILED"))?;needs_sync=true;}
}
}
let busy:bool=self.db.query_row("SELECT EXISTS(SELECT 1 FROM job_attempts WHERE state IN ('requesting','running','verifying'))",[],|r|r.get(0))?; let busy:bool=self.db.query_row("SELECT EXISTS(SELECT 1 FROM job_attempts WHERE state IN ('requesting','running','verifying'))",[],|r|r.get(0))?;
let update=self.update_proof()?; let update=self.update_proof()?;
let pending_update=self.binding.as_ref().map(|binding|rmm_agent_core::jobs::needs_update_control(&self.db,&self.ledger,binding)).transpose()?.unwrap_or(false); let pending_update=self.binding.as_ref().map(|binding|rmm_agent_core::jobs::needs_update_control(&self.db,&self.ledger,binding)).transpose()?.unwrap_or(false);
@@ -802,18 +779,12 @@ impl<C: reconcile::SyncClock> Agent<C> {
let job = self.binding.as_ref().context("binding")?.job(&offer.payload_bytes)?; let job = self.binding.as_ref().context("binding")?.job(&offer.payload_bytes)?;
if Utc::now() >= job.start_before { if Utc::now() >= job.start_before {
self.record(generation, &offer, "", jobs::no_start("expired", "START_DEADLINE_EXPIRED"))?; self.record(generation, &offer, "", jobs::no_start("expired", "START_DEADLINE_EXPIRED"))?;
} else if !matches!(job.action,rmm_domain::jobs::Action::RunScript{..})
|| (job.execution_identity=="root" && !job.action.full_maintenance()) {
self.record(generation, &offer, "", jobs::no_start("failed","LEGACY_ACTION_RETIRED"))?;
} else if !self.ready(generation,job.execution_identity=="root") { } else if !self.ready(generation,job.execution_identity=="root") {
needs_sync=true; needs_sync=true;
} else if Utc::now() >= job.not_before { } else if Utc::now() >= job.not_before {
if matches!(job.action,rmm_domain::jobs::Action::UpdateAgent{..}) && !prefetched.contains(&(offer.job_id.clone(),offer.attempt_id.clone())) {
if update_prefetch.is_none() {
let identity=self.certificates.current(Utc::now().timestamp())?;
let client=https_channel::mtls_client(self.address,&self.ca,&identity.certificate_pem,&identity.private_key_pem)?;
let base=format!("https://{}:{}",https_channel::server_name()?,self.address.port());
update_prefetch=Some((offer.clone(),agent_update_apply::Prefetch(tokio::spawn(agent_update_apply::prefetch(client,base,job)))));
}
continue;
}
// Reserve before send. A lost response must never cause // Reserve before send. A lost response must never cause
// a second permit request for this attempt. // a second permit request for this attempt.
// The root updater holds this lock exclusively while it checks // The root updater holds this lock exclusively while it checks
@@ -839,11 +810,21 @@ impl<C: reconcile::SyncClock> Agent<C> {
} }
if first_heartbeat || heartbeat_at.elapsed() >= heartbeat_after { if first_heartbeat || heartbeat_at.elapsed() >= heartbeat_after {
first_heartbeat = false; first_heartbeat = false;
let cpu = rmm_agent_linux::inventory::cpu_times();
let cpu_usage_basis_points = cpu.zip(previous_cpu)
.and_then(|(current, previous)| current.usage_since(previous));
previous_cpu = cpu;
let memory = rmm_agent_linux::inventory::memory().data;
let heartbeat = self.envelope( let heartbeat = self.envelope(
generation, generation,
Payload::Heartbeat(Heartbeat { Payload::Heartbeat(Heartbeat {
instance_id: self.instance.clone(), instance_id: self.instance.clone(),
uptime_seconds: self.started.elapsed().as_secs(), uptime_seconds: self.started.elapsed().as_secs(),
system_usage: Some(SystemUsage {
cpu_usage_basis_points,
ram_available_bytes: memory.as_ref().and_then(|m| m.available_bytes),
ram_total_bytes: memory.map(|m| m.total_bytes),
}),
}), }),
)?; )?;
ws.send(&heartbeat).await?; ws.send(&heartbeat).await?;
@@ -853,6 +834,7 @@ impl<C: reconcile::SyncClock> Agent<C> {
Payload::Heartbeat(Heartbeat { Payload::Heartbeat(Heartbeat {
instance_id: self.instance.clone(), instance_id: self.instance.clone(),
uptime_seconds: self.started.elapsed().as_secs(), uptime_seconds: self.started.elapsed().as_secs(),
system_usage: None,
}), }),
)?; )?;
ws.poll(poll).await?; ws.poll(poll).await?;
@@ -42,7 +42,7 @@ fn fixture(platform: Platform, full: bool) -> serde_json::Value {
signature: URL_SAFE_NO_PAD.encode([1_u8; 64]), signature: URL_SAFE_NO_PAD.encode([1_u8; 64]),
}; };
let transition = match platform { let transition = match platform {
Platform::LinuxX64 if full => PeerPinTransition::LinuxGeneralFullV1 { Platform::LinuxX64 | Platform::LinuxArm64 if full => PeerPinTransition::LinuxGeneralFullV1 {
general_pin_sha256: "10".repeat(32), general_pin_sha256: "10".repeat(32),
full: LinuxFullTransition { full: LinuxFullTransition {
schema_version: 1, schema_version: 1,
@@ -57,7 +57,7 @@ fn fixture(platform: Platform, full: bool) -> serde_json::Value {
effective_signing_key_id: "17".repeat(32), effective_signing_key_id: "17".repeat(32),
}, },
}, },
Platform::LinuxX64 => PeerPinTransition::UnchangedGeneralPinV1 { Platform::LinuxX64 | Platform::LinuxArm64 => PeerPinTransition::UnchangedGeneralPinV1 {
general_pin_sha256: "10".repeat(32), general_pin_sha256: "10".repeat(32),
}, },
Platform::WindowsX64 | Platform::WindowsGnuX64 => PeerPinTransition::WindowsCodePairV1 { Platform::WindowsX64 | Platform::WindowsGnuX64 => PeerPinTransition::WindowsCodePairV1 {
@@ -110,7 +110,7 @@ fn fixture(platform: Platform, full: bool) -> serde_json::Value {
update: Box::new(update), update: Box::new(update),
}, },
execution_identity: match platform { execution_identity: match platform {
Platform::LinuxX64 => "root", Platform::LinuxX64 | Platform::LinuxArm64 => "root",
Platform::WindowsX64 | Platform::WindowsGnuX64 => "system", Platform::WindowsX64 | Platform::WindowsGnuX64 => "system",
} }
.into(), .into(),
+24 -1
View File
@@ -50,11 +50,34 @@ impl UpdateKeyringFile {
pub enum Platform { pub enum Platform {
#[serde(rename = "x86_64-unknown-linux-gnu")] #[serde(rename = "x86_64-unknown-linux-gnu")]
LinuxX64, LinuxX64,
#[serde(rename = "aarch64-unknown-linux-gnu")]
LinuxArm64,
#[serde(rename = "x86_64-pc-windows-msvc")] #[serde(rename = "x86_64-pc-windows-msvc")]
WindowsX64, WindowsX64,
#[serde(rename = "x86_64-pc-windows-gnu")] #[serde(rename = "x86_64-pc-windows-gnu")]
WindowsGnuX64, WindowsGnuX64,
} }
pub const LINUX_ARM64_RELEASE_CAPABILITY: &str = "agent.release.linux.arm64/1";
impl Platform {
#[cfg(all(target_os = "linux", target_arch = "aarch64"))]
pub const NATIVE_LINUX: Self = Self::LinuxArm64;
#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
pub const NATIVE_LINUX: Self = Self::LinuxX64;
pub const fn is_linux(self) -> bool {
matches!(self, Self::LinuxX64 | Self::LinuxArm64)
}
pub const fn target_triple(self) -> &'static str {
match self {
Self::LinuxX64 => "x86_64-unknown-linux-gnu",
Self::LinuxArm64 => "aarch64-unknown-linux-gnu",
Self::WindowsX64 => "x86_64-pc-windows-msvc",
Self::WindowsGnuX64 => "x86_64-pc-windows-gnu",
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)] #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(rename_all = "snake_case")] #[serde(rename_all = "snake_case")]
pub enum ArtifactRole { pub enum ArtifactRole {
@@ -708,7 +731,7 @@ impl ResolvedAgentUpdate {
} }
pub fn execution_identity(&self) -> Option<&'static str> { pub fn execution_identity(&self) -> Option<&'static str> {
self.manifest().ok().map(|m| match m.platform { self.manifest().ok().map(|m| match m.platform {
Platform::LinuxX64 => "root", Platform::LinuxX64 | Platform::LinuxArm64 => "root",
Platform::WindowsX64 | Platform::WindowsGnuX64 => "system", Platform::WindowsX64 | Platform::WindowsGnuX64 => "system",
}) })
} }
+47 -3
View File
@@ -1,7 +1,46 @@
//! Additive bounded passive metadata; the strict original Inventory stays intact. //! Additive bounded passive metadata; the strict original Inventory stays intact.
use chrono::{DateTime, Utc}; use chrono::{DateTime, Utc};
use serde::Deserialize; use serde::{Deserialize, Serialize};
use serde_json::Value; use serde_json::Value;
pub const SOFTWARE_OBSERVATION_MAX_BYTES: usize = 128 * 1024;
pub fn firmware_identifier(value: &str) -> Option<String> {
let value = value.trim_matches(|c: char| c == '\0' || c.is_whitespace());
let lower = value.to_ascii_lowercase();
(!value.is_empty()
&& value.len() <= 255
&& !value.chars().any(char::is_control)
&& !matches!(lower.as_str(), "none" | "unknown" | "not specified" | "not applicable"
| "default string" | "to be filled by o.e.m." | "system serial number")
&& !value.bytes().all(|b| b == b'0'))
.then(|| value.to_owned())
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum DeviceType {
Physical,
Virtual,
Hypervisor,
}
#[derive(Clone, Copy)]
pub struct CpuTimes {
pub total: u64,
pub idle: u64,
}
impl CpuTimes {
pub fn usage_since(self, previous: Self) -> Option<u32> {
let total = self.total.checked_sub(previous.total)?;
let idle = self.idle.checked_sub(previous.idle)?;
let busy = total.checked_sub(idle)?;
(total != 0)
.then(|| ((u128::from(busy) * 10_000 + u128::from(total / 2)) / u128::from(total)) as u32)
}
}
#[derive(Deserialize)] #[derive(Deserialize)]
#[serde(deny_unknown_fields)] #[serde(deny_unknown_fields)]
struct Observation { struct Observation {
@@ -66,7 +105,7 @@ pub fn validate_for_scope(
.map_err(|_| "INVALID_AGENT_UPDATE_OBSERVATION")? .map_err(|_| "INVALID_AGENT_UPDATE_OBSERVATION")?
!= update != update
|| !typed.agent_update.validate() || !typed.agent_update.validate()
|| (typed.agent_update.platform == crate::agent_update::Platform::LinuxX64) != (scope == "linux.base") || typed.agent_update.platform.is_linux() != (scope == "linux.base")
|| typed.agent_update.observed_at - now > chrono::Duration::seconds(45) || typed.agent_update.observed_at - now > chrono::Duration::seconds(45)
|| now - typed.agent_update.observed_at > chrono::Duration::hours(72) || now - typed.agent_update.observed_at > chrono::Duration::hours(72)
{ {
@@ -127,10 +166,15 @@ pub fn validate_for_scope(
} }
let mut scopes = std::collections::BTreeSet::new(); let mut scopes = std::collections::BTreeSet::new();
for item in observations { for item in observations {
let max_bytes = match (scope, item["scope"].as_str()) {
("linux.base", Some("linux.software")) | ("windows.base", Some("windows.software")) =>
SOFTWARE_OBSERVATION_MAX_BYTES,
_ => 32768,
};
if serde_json::to_vec(item) if serde_json::to_vec(item)
.map_err(|_| "INVALID_OBSERVATION")? .map_err(|_| "INVALID_OBSERVATION")?
.len() .len()
> 32768 > max_bytes
{ {
return Err("OBSERVATION_SIZE"); return Err("OBSERVATION_SIZE");
} }
-172
View File
@@ -1,172 +0,0 @@
# PostgreSQL pre-auth state adapter
Enable package feature **`postgres-state`**. Dependencies: SQLx 0.8 (PostgreSQL and
Tokio/rustls only; no macros/automatic migrations), RustCrypto `aes-gcm` 0.10.
The default build still has no SQL dependency. No root-workspace changes are needed.
## Migration and least privilege
Export: `rmm_oidc_auth::postgres::MIGRATION_SQL`, exactly the package-owned file
`sql/001_oidc_login_states.sql`. Transfer this SQL into a future **normal server
migration** under the migration/owner identity; the adapter never runs it. It is
deliberately not idempotent and creates a dedicated schema/table:
`rmm_oidc_auth.login_states(state_hash bytea PRIMARY KEY, binding_hash bytea,
expires_at bigint, created_at bigint, encryption_key_ref text,
encryption_nonce bytea, ciphertext bytea)` plus expiry index and integrity checks.
This is **global PREAUTH state**, not tenant data: no tenant IDs, principal IDs,
memberships or user attributes. Use a separate global-auth-service pool/role, not a
tenant transaction with previous RLS context. Grant only:
```sql
GRANT USAGE ON SCHEMA rmm_oidc_auth TO your_auth_service_runtime_role;
GRANT SELECT, INSERT, DELETE ON rmm_oidc_auth.login_states TO your_auth_service_runtime_role;
```
Replace the example role identifier through the normal deployment configuration,
not a request parameter. Runtime must be **non-owner, NOSUPERUSER, NOBYPASSRLS**,
without schema CREATE, UPDATE, TRUNCATE, tenant-table or migration permissions.
No RLS bypass is needed: the global table intentionally has no tenant RLS policy.
Membership and approval checks remain in the tenant-bound application layer.
Use verified PostgreSQL TLS for remote databases and restricted local transport
where appropriate. Never print DB URLs/passwords or enable parameter logging.
## Configuration and public API
```rust,ignore
use rmm_oidc_auth::postgres::PostgresStateStore;
// Pool supplied by the backend with the dedicated restricted global-auth role.
// Configure bounded acquisition timeout (e.g. 5 seconds) and pool size there.
let state_store = PostgresStateStore::new(
global_auth_pool,
secret_resolver.as_ref(),
"secret-store:rmm/oidc-state-key/version-1".into(),
10_000, // global outstanding-state capacity, including expired rows
).await?;
// Pass Arc::new(state_store) as the unchanged StateStore port to
// OidcAuth::discover(..., Profile::Production, ..., ...).
```
`PostgresStateStore::new(PgPool, &dyn SecretResolver, key_ref: String,
capacity: u32) -> Result<Self>` resolves exactly the configured reference, once.
The secret is **32 cryptographically random bytes encoded as unpadded base64url**.
Do not derive it from a password, the OIDC client secret, or a token claim. The
reference must identify an **immutable version**, not a mutable `latest` alias.
Store the key outside PostgreSQL and backups of login-state ciphertext. Ref strings
are metadata, not secret values. Never log the resolved key.
The library does not automatically read environment configuration. A backend may
map e.g. `RMM_OIDC_STATE_BACKEND=postgres`, `RMM_OIDC_STATE_KEY_REF` and a private DB
connection reference to this constructor; these are integration examples, not
implemented server flags. Missing/invalid configuration must fail startup closed.
`is_persistent()` is true for this adapter; `Profile::Production` continues rejecting
the memory adapter independently. No production in-memory fallback is provided.
## Confidentiality, atomicity and lifetime
- The existing flow generates 256-bit opaque state/binding values and passes only
canonical SHA-256 base64url hashes to `StateStore`. PostgreSQL stores their decoded
**32-byte digests**, not raw handles/cookies. Nonce and verifier are validated as
canonical 32-byte random-value encodings before persistence.
- The complete `PendingLogin` JSON is encrypted with **AES-256-GCM**, a fresh random
96-bit encryption nonce and authenticated associated data binding a fixed format
domain/version, state hash, browser-binding hash, expiry and configured key ref.
Plaintext serialization/decryption buffers and resolved key bytes are zeroized.
The store, pending records and key material have no Debug/log implementation.
Hashes, expiry, version reference and ciphertext length remain DB-visible.
A privileged DBA can delete/deny service, but cannot forge a valid encrypted login
without the external key. Protect the auth-service process and secret resolver.
- Insertion refuses expired states, TTL above **300 seconds**, duplicates and
capacity outside 1..=100,000. Database checks independently bound expiry relative
to creation (600 seconds for clock skew); DB clock also rejects expired insertions.
- A transaction-scoped, database-local advisory lock serializes admission checks
across adapter instances. A fresh READ COMMITTED snapshot prevents capacity races,
even on pools with a different default isolation level. All instances sharing a
table must use the **same capacity policy**. No upsert/overwrite path exists.
- Consumption is one parameterized **`DELETE ... WHERE state_hash=$1 AND
binding_hash=$2 AND encryption_key_ref=$3 AND expires_at > GREATEST($4, DB_now)
RETURNING ...`**. Exactly one concurrent callback receives a record. Wrong binding,
wrong key version, missing/replayed or expired state does not delete a valid row.
Thus a guessed-handle/wrong-cookie request cannot burn someone else's state.
- Delete is committed **before** authenticated decryption/parsing. Corruption,
nonce/code-exchange failure or later callback failure never restores state. A
connection failure during commit has uncertain delivery and fails closed: restart
login, never replay a potentially consumed flow.
- `cleanup_expired(batch: u32) -> Result<u64>` deletes only expired rows, at most
`batch` (1..=**1,000**), using the expiry index and one atomic CTE/DELETE.
It intentionally does not use SELECT FOR UPDATE, which would require granting
UPDATE privilege to this read/insert/delete-only role. Concurrent cleanup calls
may select the same expired batch; only one deletes it, another may return zero.
Call periodically from the global auth service; no background scheduler is spawned.
Each adapter transaction uses a 5-second statement timeout and 2-second lock
timeout; pool/network timeouts are the backend's connection policy. Expired rows
count against capacity until cleaned, deliberately failing closed under overload.
Rate-limit login start/callback independently; database capacity is not a rate limit.
- Key rotation for this first adapter is **drain then switch**: pause new logins,
allow outstanding flows to complete/expire, clean expired rows, switch all instances
to a new versioned external key, resume. Do not silently mutate a referenced key or
mix key versions during rolling deployment. Rotate well before 2^32 encryptions per
key. Old/incompatible ciphertext cannot be accepted by a differently configured key.
All queries use fixed schema/table names and bound data. No runtime table/schema
name interpolation, DDL, role changes, tenant RLS changes or session approvals occur.
## Explicit real PostgreSQL test
```sh
python3 crates/oidc-auth/tests/run_postgres.py
```
The runner refuses an existing container named **`rust-discovery-oidc-test`**. It
creates only that disposable PostgreSQL 17.6 container, publishes an automatically
allocated port **only on 127.0.0.1**, generates a private ephemeral password in memory,
and removes its own container/anonymous volumes afterwards. Existing PostgreSQL and
RMM containers are never inspected for credentials, restarted, migrated or reset.
No credential file, stdout secret, host service package or VM change is needed.
The Rust integration test is explicitly ignored in ordinary test runs. The runner
opts in with `RMM_OIDC_TEST_ALLOW_OWNER_DDL=isolated` and a private
`RMM_OIDC_TEST_DATABASE_URL` passed only through process environment; only the
disposable owner test identity applies fixture DDL and creates a separate restricted
runtime role. Do not point these variables at a real server database.
Checks: runtime nonownership/no superuser/no BYPASSRLS/no schema CREATE and actual
DDL rejection; encrypted persistence; wrong-cookie non-burning; caller/DB expiry;
duplicate/replay rejection; exactly one winner among 16 callbacks; authenticated
ciphertext-tamper rejection and consumption; concurrent capacity 2/8; bounded TTL
cleanup; invalid hashes/TTL rejection. This is a local native PostgreSQL test, not
server/VM or external-IdP acceptance. Actual run results are recorded separately.
## Actual local verification — 2026-11-12
Executed on the development Linux host, not the Linux test VM:
- `cargo clippy --manifest-path crates/oidc-auth/Cargo.toml --all-targets --all-features --locked -- -D warnings`: passed.
- `cargo test --manifest-path crates/oidc-auth/Cargo.toml --all-features --locked`:
**13 unit tests passed**, 0 failed; the explicit-owner PostgreSQL test is ignored
in this general run; 0 documentation tests.
- `python3 crates/oidc-auth/tests/run_postgres.py`: **1 actual PostgreSQL integration
test passed**, 0 failed, 0 ignored. PostgreSQL 17.6; restricted non-owner role with
real DDL/UPDATE rejection; **1/16** concurrent consume winners; **2/8** concurrent
capacity admissions. Also checked ciphertext, binding non-burning, DB/caller expiry,
duplicates/replay, tamper consumption, cleanup limits, key-version mismatch,
invalid key/hash and overlong TTL rejection. Own disposable container removed.
- `cargo check --manifest-path crates/oidc-auth/Cargo.toml --lib --no-default-features --locked`: passed.
- `cargo fmt --manifest-path crates/oidc-auth/Cargo.toml --check`: passed.
- `cargo package --manifest-path crates/oidc-auth/Cargo.toml --allow-dirty --features postgres-state --locked`:
packaged **11 files** and verified the extracted package build successfully.
Non-failing warning: package metadata has no description/documentation/homepage/repository.
The first Clippy run rejected a deprecated generic-array nonce constructor; replaced
with array conversion, no lint suppression. The first real database run reached
cleanup but failed there: SELECT FOR UPDATE required UPDATE permission. Cleanup
was changed to a bounded atomic CTE/DELETE, retaining the restricted role rather
than expanding its privileges. Both subsequent real PostgreSQL runs passed, including
the final expanded test. No server DB migration/reset, runtime server restart,
membership change, host package installation, VM effect or production acceptance.
The migration has been applied only to the disposable test database. Applying it
through normal server migrations, provisioning the global auth role/key reference,
and wiring backend configuration/routes remain explicit integration work.
+3 -162
View File
@@ -1,164 +1,5 @@
# RMM OIDC authentication adapter (standalone package) # Authentisierung im MVP
Optional encrypted SQLx/PostgreSQL login-state storage and its migration/permissions Die öffentliche WebUI verwendet ein lokales Konto mit Passwort und TOTP. Der MCP-Server prüft kundengebundene Bearer-Tokens. Die Einrichtung dieser beiden Zugänge steht in der [Betriebsanleitung](../../docs/public-access.md).
contract: **[POSTGRES.md](POSTGRES.md)** (`postgres-state` feature).
This crate is **not wired into the server** and does not change the root workspace. Dieses Rust-Paket wird vom Server als lokale Abhängigkeit eingebunden und enthält den separat konfigurierbaren OIDC-Adapter. Im öffentlichen MVP ist dieser Adapter deaktiviert. [Server-Abhängigkeiten](../server/Cargo.toml) · [Authentisierung im Server](../server/src/auth.rs)
It authenticates against a configured HTTPS OIDC provider using real RSA signatures,
discovery, JWKS and authorization-code exchange. It never grants tenant membership,
roles, approval authority or an RMM session by itself. External IdP configuration is
currently **not_configured**; no external-provider or VM acceptance is claimed.
## Explicit supported provider profile
- RS256 only, RSA signing JWKS with unique `kid`, `alg=RS256`, `use=sig`.
Mixed-algorithm JWKS are deliberately rejected by this initial strict profile.
- Configured issuer is the only authority. Discovery's issuer must match exactly;
authorization, token and JWKS endpoints must be HTTPS, same **origin** (including
port) as that issuer, with no userinfo, fragment or query. Providers using a separate
CDN/origin for JWKS are not supported, rather than automatically trusted.
- Normal rustls trust roots, optional explicitly provisioned CA roots; no HTTP,
insecure certificate mode, HTTP redirects or environment proxy. Administrators
must restrict configured issuers/network egress; user input cannot choose issuers.
- Browser: authorization code, `openid`, PKCE S256, random nonce/state/browser binding,
fixed registered HTTPS callback, `client_secret_post`. The IdP must advertise these
features. PKCE rejection surfaces as `CodeExchange`; response bodies are not logged.
- MCP: RFC 9068 JWT **access** token with `typ=at+jwt`, dedicated resource audience,
approved `client_id`, required `jti`, issuer/signature/expiry/nbf/iat checks, required scopes.
Opaque/introspected tokens and other JWT access-token profiles are unsupported.
Browser ID tokens are never accepted as bearer credentials.
- JWT validity uses zero clock leeway; synchronize clocks. Browser multiple audiences
require matching `azp`; any supplied browser `azp` must match the browser client ID.
- JWKS cache TTL 300 seconds; unknown-kid refresh throttled to once per second,
serialized across callers. A newly rotated key may require retry after one second.
Invalid JWKS/failed refresh clears the old key cache and fails closed. Revocation of
a cached key is bounded by the TTL, not instantaneous. Issuer operator must rotate
to a **new kid** (same-kid replacement is visible on the next TTL refresh).
- HTTP connect timeout 3 seconds, total request timeout 10 seconds, response 128 KiB,
JWT 32 KiB, code 4 KiB, maximum 64 signing keys. No refresh-token persistence.
## Public integration API
```rust,ignore
let auth = OidcAuth::discover(
Config {
issuer: Url::parse("https://idp.example/realms/rmm")?,
browser_client_id: "rmm-browser".into(),
client_secret_ref: "secret-store:rmm/oidc-client".into(),
redirect_uri: Url::parse("https://rmm.example/auth/oidc/callback")?,
mcp_audience: "https://rmm.example/mcp".into(),
mcp_client_ids: BTreeSet::from(["approved-mcp-client".into()]),
},
Profile::Production,
persistent_state_store,
secret_resolver,
vec![], // normal roots; provision a private CA explicitly if necessary
).await?;
let start: LoginStart = auth.login_start().await?;
// Set start.binding_set_cookie and redirect to start.authorization_url.
let identity: Identity = auth.callback(Callback {
code: parsed_query_code,
state: parsed_query_state,
browser_binding: parsed_host_binding_cookie,
}).await?;
let bearer: BearerIdentity = auth
.verify_mcp_bearer(raw_bearer, &["inventory:read"]).await?;
```
`SecretResolver::resolve(reference)` returns `secrecy::SecretString`; resolve from an
authorized secret store, never from a token claim. The adapter exposes only coarse
typed `Error`s, not reqwest errors (which may contain URLs), codes or token bodies.
Do not log callback URLs, authorization URLs, cookies, state records, secrets or JWTs.
Sensitive flow types intentionally do not implement `Debug`.
### Required server/cookie adapter work (not implemented here)
1. Register login start and **GET** callback routes. Rate-limit both; do not allow
caller-supplied issuer, audience, scopes, redirect URI or post-login return URL.
Reject duplicate query/cookie parameters and provider error callbacks. Return
`Cache-Control: no-store` and `Referrer-Policy: no-referrer` on all auth routes;
avoid request/query logging and third-party resources there.
2. Set `LoginStart.binding_set_cookie` verbatim: `__Host-rmm_oidc_binding`, Secure,
HttpOnly, Path=/, **SameSite=Lax**, Max-Age=300, no Domain. Strict would omit this
cookie on the cross-site provider callback. Start replaces an outstanding binding;
multi-tab login is intentionally fail-closed, not a bypass.
3. Pass only parsed code/state and binding cookie value to `callback`. The store must
atomically consume state before token exchange. On terminal callback success or
failure, clear binding with `CLEAR_BINDING_COOKIE`; failures require fresh login.
4. Resolve `Identity { issuer, subject }` to a persistent principal and **current**
scoped memberships. Email and untrusted group/role claims are not identity keys or
memberships (this crate does not expose them). No implicit all-tenant role.
5. On browser success only, rotate/create a new opaque RMM session, bound to that
principal, with bounded expiry and the existing Secure/HttpOnly/host-only
**SameSite=Strict** final session cookie. Keep CSRF token + exact Origin checks
for writes, authorization checks and explicit UI plan approval. An ID token is
not an RMM session cookie or permission to approve a plan.
6. Bearer always wins over browser cookies. Use `verify_mcp_bearer` only for MCP/API
bearer paths; combine returned scopes with persistent memberships on **every**
request. Never construct an interactive browser session or approval context from
a bearer token, even if a principal has an approver membership. Preserve
`pending_approval` and all immutable plan/attempt bindings.
7. Logout must invalidate the **server-side RMM session**, clear the final cookie,
require its normal CSRF/Origin checks and prevent reuse. IdP logout is intentionally
not implemented or falsely advertised; local logout does not end an IdP session.
8. Disable dev identities/simulated principals in production independently of this
crate. Existing dev identity auth is not replaced until the backend is integrated.
### Persistent state store port
Alternative adapters must implement async `StateStore::{insert, consume}` plus `is_persistent() == true` using
shared durable storage. Do not merely return true for a memory-backed adapter.
State lookup keys and browser bindings supplied to the store are SHA-256 base64url
hashes; records contain nonce, verifier and absolute Unix expiry. Protect record
contents at rest and restrict database access. `insert` must enforce unique keys,
bounded capacity and expiry cleanup. `consume` must perform one atomic conditional
delete/return based on `(state_hash, binding_hash, expires_at > now)`; no read-then-
delete race, no restoration after exchange/nonce failure. A SQL transaction or
`DELETE ... WHERE ... RETURNING` is suitable. Store failures must fail closed.
`dev::InMemoryStateStore::new(dev::DevTestOnly)` exists only under the explicit
`dev-memory-store` feature or unit tests. `Profile::Production` rejects it. This is
not a production SQL adapter. The optional PostgreSQL adapter below supplies durable
encrypted storage; applying its migration and server wiring remain integration work.
## Targeted local verification
```sh
cargo fmt --manifest-path crates/oidc-auth/Cargo.toml --check
cargo clippy --manifest-path crates/oidc-auth/Cargo.toml --all-targets --all-features -- -D warnings
cargo test --manifest-path crates/oidc-auth/Cargo.toml --all-features
```
Tests run a native loopback HTTPS OIDC provider with an ephemeral private CA, real
2048-bit RSA signing keys/JWKS, actual one-use authorization codes, real form-encoded
token exchange and server-enforced PKCE. The CA is added only to the test clients,
never to the host truststore. No checked-in private key, external IdP, VM modification,
host-service installation, Docker/server restart or reboot is needed. The provider
is a test double, not a claim of external-provider interoperability or VM acceptance.
Test assertions/counters contain no secret output. Run results are reported separately
by the implementation dispatch, not presumed by these commands.
### Actual local verification (2026-11-12)
Executed on the development Linux host, not the Linux test VM:
- `cargo fmt --manifest-path crates/oidc-auth/Cargo.toml --check`: passed.
- `cargo clippy --manifest-path crates/oidc-auth/Cargo.toml --all-targets --all-features -- -D warnings`: passed.
- `cargo test --manifest-path crates/oidc-auth/Cargo.toml --all-features --locked`:
**13 passed, 0 failed**; 0 documentation tests. Covers real code exchange,
browser binding/replay/expiry/concurrency, PKCE failure, nonce/authorized party,
issuer/audience/expiry/nbf/iat/required claims/scopes, algorithm/signature/ID-token
confusion, JWKS caching/rotation, actual TLS trust/hostname rejection, discovery
origin restrictions, HTTP redirect rejection and response/token size limits.
- `cargo metadata --manifest-path crates/oidc-auth/Cargo.toml --no-deps --format-version 1`:
independent workspace at `crates/oidc-auth`, exactly one member and own lockfile.
Initial build checks found missing URL serde and JWT PEM feature flags; both were
fixed. Clippy found an unnecessary test `format!`, also fixed. The final commands
above passed after those corrections. Pinned lockfile resolves jsonwebtoken 10.4.0,
reqwest 0.12.28 and rustls 0.23.46 on the repository's Rust 1.99.1 toolchain.
Not executed in that initial verification: external real-IdP interoperability, production SQL state adapter,
server routes/cookies/sessions/membership integration, VM execution or browser UI
login against the running RMM server. Timeout values are configured; a deliberately
stalling provider timeout test has not been run. No production acceptance claimed.
+5 -1
View File
@@ -5,5 +5,9 @@ edition.workspace = true
license.workspace = true license.workspace = true
[dependencies] [dependencies]
anyhow.workspace = true anyhow.workspace = true
sqlx.workspace = true # Use the PostgreSQL driver directly. SQLx 0.8's generic migration and type
# features also resolve the obsolete SQLite driver in the shared lockfile.
sqlx = { package = "sqlx-core", version = "=0.8.6", features = ["migrate", "_rt-tokio", "_tls-rustls-ring-webpki"] }
sqlx-macros = { version = "=0.8.6", features = ["migrate"] }
sqlx-postgres = { version = "=0.8.6", features = ["migrate", "chrono", "uuid", "json"] }
uuid.workspace = true uuid.workspace = true
+6 -5
View File
@@ -1,17 +1,18 @@
use anyhow::{Result, ensure}; use anyhow::{Result, ensure};
use sqlx::{PgPool, Postgres, Transaction}; use sqlx::{query::query, query_scalar::query_scalar};
use sqlx_postgres::{PgPool, PgTransaction};
use uuid::Uuid; use uuid::Uuid;
pub async fn tenant_tx(pool: &PgPool, tenant: Uuid) -> Result<Transaction<'_, Postgres>> { pub async fn tenant_tx(pool: &PgPool, tenant: Uuid) -> Result<PgTransaction<'_>> {
let mut tx = pool.begin().await?; let mut tx = pool.begin().await?;
sqlx::query("SELECT set_config('app.tenant_id', $1, true)") query("SELECT set_config('app.tenant_id', $1, true)")
.bind(tenant.to_string()) .bind(tenant.to_string())
.execute(&mut *tx) .execute(&mut *tx)
.await?; .await?;
Ok(tx) Ok(tx)
} }
pub async fn verify_application_role(pool: &PgPool) -> Result<()> { pub async fn verify_application_role(pool: &PgPool) -> Result<()> {
let unsafe_role: bool = sqlx::query_scalar( let unsafe_role: bool = query_scalar(
"SELECT rolsuper OR rolbypassrls OR EXISTS (SELECT 1 FROM pg_tables WHERE schemaname='public' AND tableowner=current_user) FROM pg_roles WHERE rolname=current_user", "SELECT rolsuper OR rolbypassrls OR EXISTS (SELECT 1 FROM pg_tables WHERE schemaname='public' AND tableowner=current_user) FROM pg_roles WHERE rolname=current_user",
).fetch_one(pool).await?; ).fetch_one(pool).await?;
ensure!( ensure!(
@@ -22,7 +23,7 @@ pub async fn verify_application_role(pool: &PgPool) -> Result<()> {
} }
pub async fn migrate(url: &str) -> Result<()> { pub async fn migrate(url: &str) -> Result<()> {
let pool = PgPool::connect(url).await?; let pool = PgPool::connect(url).await?;
sqlx::migrate!("../../migrations").run(&pool).await?; sqlx_macros::migrate!("../../migrations").run(&pool).await?;
pool.close().await; pool.close().await;
Ok(()) Ok(())
} }
+1 -1
View File
@@ -15,7 +15,7 @@ serde_json.workspace = true
uuid.workspace = true uuid.workspace = true
libc = "0.2.177" libc = "0.2.177"
fs2 = "0.4.3" fs2 = "0.4.3"
rusqlite = { version = "0.32.1", features = ["bundled"] } rusqlite.workspace = true
rmm-domain = { path = "../domain" } rmm-domain = { path = "../domain" }
rmm-agent-linux = { path = "../agent-linux" } rmm-agent-linux = { path = "../agent-linux" }
+4 -2
View File
@@ -78,9 +78,11 @@ impl Config {
}) })
} }
fn validate_profile(&self) -> Result<()> { fn validate_profile(&self) -> Result<()> {
let state = self.state.as_path();
ensure!( ensure!(
self.state.as_path() state == std::path::Path::new(rmm_privileged_helper::readiness::SHARED_STATE)
== std::path::Path::new(rmm_privileged_helper::readiness::SHARED_STATE), || (self.profile == HelperProfile::FullMaintenanceV1
&& state == std::path::Path::new("/var/lib/rmm-discovery-helper")),
"SHARED_HELPER_LEDGER_REQUIRED" "SHARED_HELPER_LEDGER_REQUIRED"
); );
if self.profile == HelperProfile::FullMaintenanceV1 { if self.profile == HelperProfile::FullMaintenanceV1 {
@@ -110,7 +110,7 @@ pub fn observe_record(
&& response.ledger_inode != 0 && response.ledger_inode != 0
&& response.lock_inode != 0 && response.lock_inode != 0
&& response.observation.validate() && response.observation.validate()
&& response.observation.platform == Platform::LinuxX64, && response.observation.platform == Platform::NATIVE_LINUX,
"UPDATE_OBSERVER_RESPONSE_BINDING" "UPDATE_OBSERVER_RESPONSE_BINDING"
); );
let record = rmm_domain::agent_update_provisioning::InstalledReleaseRecord::from_bytes( let record = rmm_domain::agent_update_provisioning::InstalledReleaseRecord::from_bytes(
@@ -346,7 +346,7 @@ pub fn collect(db: &Connection, local: Local<'_>, request: &Request) -> Result<R
)); ));
let observation = AgentUpdateObservation { let observation = AgentUpdateObservation {
schema_version: 1, schema_version: 1,
platform: Platform::LinuxX64, platform: Platform::NATIVE_LINUX,
observed_at, observed_at,
quality: ObservationQuality::Valid, quality: ObservationQuality::Valid,
predecessor: Some(trust.predecessor().clone()), predecessor: Some(trust.predecessor().clone()),
+12
View File
@@ -81,6 +81,17 @@ pub struct Heartbeat {
pub instance_id: String, pub instance_id: String,
#[prost(uint64, tag = "2")] #[prost(uint64, tag = "2")]
pub uptime_seconds: u64, pub uptime_seconds: u64,
#[prost(message, optional, tag = "3")]
pub system_usage: Option<SystemUsage>,
}
#[derive(Clone, PartialEq, Message)]
pub struct SystemUsage {
#[prost(uint32, optional, tag = "1")]
pub cpu_usage_basis_points: Option<u32>,
#[prost(uint64, optional, tag = "2")]
pub ram_available_bytes: Option<u64>,
#[prost(uint64, optional, tag = "3")]
pub ram_total_bytes: Option<u64>,
} }
#[derive(Clone, PartialEq, Message)] #[derive(Clone, PartialEq, Message)]
pub struct InventorySnapshot { pub struct InventorySnapshot {
@@ -156,6 +167,7 @@ mod tests {
payload: Some(Payload::Heartbeat(Heartbeat { payload: Some(Payload::Heartbeat(Heartbeat {
instance_id: "x".into(), instance_id: "x".into(),
uptime_seconds: 1, uptime_seconds: 1,
system_usage: None,
})), })),
..Default::default() ..Default::default()
}; };
-200
View File
@@ -1,200 +0,0 @@
# Integrated OIDC/OAuth authentication
The server now wires `rmm-oidc-auth` into real browser, HTTP and MCP paths. External
IdP deployment is **not_configured** unless the administrator supplies configuration.
No external-provider interoperability or production/VM acceptance is implied.
## Configuration
Set `RMM_OIDC_CONFIG_FILE` to an absolute, regular non-symlink **0600** JSON file
with a same-owner, non-group/world-writable parent. All secret references are absolute
0600 private files with that same owner and safe parent. Their contents are never
passed as argv, logged, reflected in errors or read as shell. Example (placeholders):
```json
{
"issuer": "https://idp.example/realms/rmm",
"browser_client_id": "rmm-browser",
"client_secret_ref": "/private/rmm/oidc-client-secret-v1",
"redirect_uri": "https://rmm.example/auth/oidc/callback",
"mcp_audience": "https://rmm.example/mcp",
"mcp_client_ids": ["approved-mcp-client"],
"auth_database_url_ref": "/private/rmm/oidc-auth-database-url",
"state_key_ref": "/private/rmm/oidc-state-key-v1",
"extra_ca_file": null,
"testsimulation": false
}
```
`RMM_UI_ORIGIN` must be the exact HTTPS origin without trailing slash. The callback
must equal that origin plus `/auth/oidc/callback`. Normal roots are used; optional
`extra_ca_file` explicitly provisions a private IdP CA, never an insecure TLS mode.
Issuer discovery/JWKS/endpoints use configured-issuer same-origin HTTPS, no redirects,
fixed RS256 and bounded requests. The supported provider profile is documented in
`../oidc-auth/README.md` (PKCE S256, nonce, client_secret_post; RFC9068 access tokens).
`state_key_ref` contains 32 random bytes encoded as unpadded base64url, with an
immutable versioned reference. The package's AES-256-GCM state protection, 300-second
TTL, atomic binding/consume, capacity and drain-before-key-rotation rules remain intact.
Global state cleanup runs in bounded 1,000-row batches every 30 seconds.
Production requires `RMM_PROFILE=production`, `RMM_DEV_AUTH=false`, configured OIDC
and **no** RMM_DEV_USERNAME/PASSWORD, RMM_OPERATOR_A/B or RMM_VIEWER_A/B values.
Production with dev auth is rejected before connecting. `testsimulation=true` is
accepted only in the explicit development profile, never derived from token claims.
Development retains the existing separately credentialed browser/viewer/operator
paths. Neither profile silently falls back after invalid explicit bearer credentials.
Non-OIDC production gaps remain: the local ArtifactStore is still development-only;
artifact-dependent features fail closed until a production adapter is supplied.
Root/APT selected policies remain development-only and unchanged in their authority.
## Migration and provisioning
Normal migration **0011_oidc_auth.sql** creates global encrypted pre-auth state and
the administrator-maintained external identity index, extends membership kind with
`human` and constrains authorization audit pairs to exactly:
- `dev_test_browser_simulation` + `testsimulation=true`
- `human_webui` + `testsimulation=false`
The runtime does **not** create schemas, tables, identities, memberships or roles.
Apply normal migrations without resetting DB/PKI. Provision a separate global-auth
login identity with only schema USAGE and table SELECT/INSERT/DELETE on
`rmm_oidc_auth.login_states`. The server verifies that this pool is neither superuser,
BYPASSRLS, table owner nor schema creator, and cannot SELECT tenant memberships.
The tenant application pool remains `rmm_app`, nonowner and RLS-bound. Neither needs
a general RLS bypass. Do not reuse the tenant application's database URL for auth state.
An administrator explicitly registers each external `(issuer,subject)` in
`public.oidc_principals` and assigns tenant routing references; the principal ID is:
`oidc:` + lowercase SHA-256 hex of compact UTF-8 JSON `[issuer,subject]`.
Rust helper: `oidc::principal_id`. Email/group claims are never identity or membership.
The index is routing metadata only: each chosen tenant still requires a current,
unrevoked `memberships` row with explicit permissions. Browser login additionally
requires membership kind **human**. No auto-registration, tenant or role grants occur.
Disabling the index entry revokes subsequent auth and persisted permission rechecks,
including start-time rights checks for existing plans. Membership revocation is read
on every authenticated HTTP/MCP call, not cached from an ID token or browser session.
Only narrow, fixed-search-path SECURITY DEFINER lookup functions expose identity
routing/enabled status to rmm_app; they do not bypass/query memberships RLS or return
foreign inventory. MCP/HTTP permissions intersect the validated access-token scopes
with current membership. Script/root operations retain their additional permission
and selected-helper checks. Bearers have no interactive session context, even with
an approver membership/scope plus a valid browser cookie.
## UI-compatible routes and cookie contract
- `GET /auth/config`: `{oidc_configured,oidc_login_url,dev_login_enabled}`.
`oidc_login_url` is `/auth/oidc/login` when configured, otherwise null. UI can show
a nonempty configured-provider sign-in link without knowing secrets.
- `GET /auth/oidc/login`: code-flow redirect, binding cookie
`__Host-rmm_oidc_binding`, Secure/HttpOnly/Path=/, **SameSite=Lax**, 300 seconds.
- `GET /auth/oidc/callback`: code + state (optional issuer response check), duplicate
query/cookie rejection, one-use DB state, token exchange and nonce/PKCE/signature
checks, persistent principal/membership mapping. Clears binding on success/failure.
Establishes a new opaque RMM session and redirects only to `/`, never user input.
- `GET /auth/session`: existing DTO retained (`principal`, `tenant_id`, `permissions`,
`roles`, `csrf_token`, `testsimulation`, `approval_origin`). Final cookie remains
`__Host-rmm_session`, Secure/HttpOnly/host-only, **SameSite=Strict**, one hour.
Sessions remain in memory; restart requires fresh OIDC login, not job resubmission.
- `POST /auth/logout`: exact Origin + session CSRF; server-side invalidation and cookie
clearing. Local RMM logout only; no false claim of IdP logout.
All auth responses are no-store/no-referrer. Do not enable callback/query logging,
browser traces, HAR, screenshots or third-party resources on auth pages. Browser
writes and plan authorizations retain exact Origin/CSRF and immutable plan binding.
Tenant selection comes from the API path, overriding an incoming X-RMM-Tenant header;
MCP dispatch selects its explicit tenant_id. X-RMM-Tenant is only a selection hint for
other calls, never authority: it must exist in the mapped index AND current tenant
membership. `/api/v1/tenants` lists current readable memberships using separate RLS
transactions. Foreign tenant/asset paths remain not-found, not token-controlled routing.
## Targeted integration tests
`python3 tests/oidc/server_integration.py` starts an ephemeral native TLS mock IdP
and native loopback API instance against the existing development PostgreSQL. It
provisions/removes only its own synthetic identity/human membership and a distinct
restricted auth-state login role. No approval/job/permit/VM fixture is fabricated.
It uses a private ephemeral CA, real RSA signatures/JWKS, actual one-use code exchange
and PKCE. The Chromium step uses a temporary NSS truststore, no TLS bypass/artifacts,
and actual provider UI navigation/cross-site callback; **no job approval** occurs.
It also starts a configured production-profile API with simulation false to check
the production auth path, not to claim real-provider/human production acceptance.
Credentials are parsed internally from local private development configuration;
never printed, sourced, passed in argv or included in test failure output.
Existing backend contract, transport, pages/catalog, sync and local integration tests
remain required after deployment. Actual commands/counts are returned by the dispatch;
the descriptions here are not presumed successful test results.
## Verified local auth increment (2026-11-12)
- Native server build and `cargo clippy -p rmm-server --all-targets --locked -- -D warnings`
passed; changed server files passed targeted rustfmt checking.
- Targeted Rust tests: server **7**, domain **11**, protocol **3**, persistence **0**;
all passed. Three server tests cover the added cookie/scope/identity contracts.
- Standalone OIDC package: **13** unit tests passed; the ordinary run explicitly
ignores its owner-opt-in database test, then `tests/run_postgres.py` ran that **1**
real PostgreSQL integration test successfully (1/16 consume, 2/8 capacity).
- Integrated native server/real mock TLS/real PostgreSQL/Chromium test:
**35 assertions passed**, including production-profile startup with OIDC configured,
simulation false and dev login absent, and actual MCP tool scope enforcement.
No plan was approved or executed by this increment.
- Python syntax checks and Node browser-script syntax check passed.
Initial build/harness failures were corrected without weakening checks: root Cargo
needed to exclude the nested standalone OIDC workspace; Python environment merging
needed to avoid duplicate keywords; dev login must not register its JSON extractor
route in production; MCP testing must consume a concrete SSE response instead of
waiting for stream closure. A backend regression also exposed that tenant-denied
authentication must preserve NOT_FOUND in the MCP/HTTP structured error code; the
shared mapper now preserves it instead of calling every failure UNAUTHENTICATED.
External IdP configuration and all VM/real-human production-approval acceptance
remain open. The running development deployment intentionally retains its existing
dev identities unless an administrator provisions the OIDC configuration and the
separate state-pool identity; no sample provider is silently enabled there.
### Final deployed backend verification
Normal additive migrations **0009, 0010 and 0011** were applied without DB/PKI
reset; successful migration history is **1 through 11**. Docker release build of
server **and agent** succeeded after adding the exact embedded helper unit
`deploy/linux/rmm-apt-helper.service` to the Docker COPY/context whitelist. The
unit/helper/provider source and its hardening were not altered by this auth work.
`python3 deploy/dev.py up` rebuilt/recreated only the project server/migration service;
existing PostgreSQL stayed running. Final server observation:
- started **2026-11-12T19:12:38.969913632Z**, status running;
- image `sha256:545318218433a5d0be96c9368096cb2850b059be0b690bee5044ab28aad5cb82`;
- published TLS port only `127.0.0.1:18443`; PostgreSQL has no published port;
- actual `/auth/config` returns dev login enabled, OIDC not configured, login URL null.
All five affected backend integration programs then passed against that deployment:
| Program | Actual PASS assertions |
| --- | ---: |
| `tests/backend_contract.py` | 42 |
| `tests/backend_transport.py` | 20 |
| `tests/backend_pages_catalog.py` | 25 |
| `tests/backend_sync.py` | 28 |
| `tests/local_integration.py` | 35 |
| **Total** | **150** |
These are assertion counts in five integration programs, not 150 Rust test cases.
They cover unchanged immutable pending/approval boundaries, mTLS and rotation,
fencing/housekeeping, catalog/pagination/membership, signing-key/bootstrap,
Sync/reconnect/restore denial, extended native inventory and tenant isolation.
The final NOT_FOUND mapper correction passed the previously failing MCP foreign-
tenant contract. Four additional actual database-boundary assertions passed:
rmm_app cannot directly read pre-auth state or the external identity index, the
narrow lookup rejects a missing identity, and rmm_app remains non-superuser/non-BYPASSRLS.
No VM/systemd/root/APT effect, positive plan approval or privileged-helper execution
was performed by this dispatch. Linux-MVP, positive consumed-job/helper SyncAck and
real external-IdP/human production-approval acceptance remain separate gates.
+2 -3
View File
@@ -36,7 +36,7 @@ pub async fn download(
return Err(Error(StatusCode::BAD_REQUEST, "VALIDATION_ERROR")); return Err(Error(StatusCode::BAD_REQUEST, "VALIDATION_ERROR"));
} }
let mut tx = rmm_persistence::tenant_tx(&s.pool, t).await?; let mut tx = rmm_persistence::tenant_tx(&s.pool, t).await?;
let row=sqlx::query("SELECT j.payload,p.payload AS plan_payload,p.plan_hash,z.principal AS approver,i.asset_id,i.enrollment_generation,i.assignment_version FROM jobs j JOIN operations o ON o.tenant_id=j.tenant_id AND o.operation_id=j.operation_id JOIN authorizations z ON z.tenant_id=o.tenant_id AND z.authorization_id=o.authorization_id JOIN approval_requests r ON r.tenant_id=j.tenant_id AND r.operation_id=j.operation_id JOIN operation_plans p ON p.tenant_id=r.tenant_id AND p.plan_id=r.plan_id JOIN agent_installations i ON i.tenant_id=j.tenant_id AND i.agent_id=j.agent_id WHERE j.agent_id=$1 AND j.job_id=$2 AND j.attempt_id=$3 AND j.state IN ('queued','accepted','running','verifying','awaiting_reboot') AND r.approval_state='approved' AND z.revoked_at IS NULL AND p.expires_at>now() AND i.revoked_at IS NULL").bind(a).bind(q.job_id).bind(q.attempt_id).fetch_optional(&mut *tx).await?.ok_or(Error(StatusCode::NOT_FOUND,"NOT_FOUND"))?; let row=sqlx::query("SELECT j.payload,p.payload AS plan_payload,p.plan_hash,z.principal AS approver,r.principal AS submitter,i.asset_id,i.enrollment_generation,i.assignment_version FROM jobs j JOIN operations o ON o.tenant_id=j.tenant_id AND o.operation_id=j.operation_id JOIN authorizations z ON z.tenant_id=o.tenant_id AND z.authorization_id=o.authorization_id JOIN approval_requests r ON r.tenant_id=j.tenant_id AND r.operation_id=j.operation_id JOIN operation_plans p ON p.tenant_id=r.tenant_id AND p.plan_id=r.plan_id JOIN agent_installations i ON i.tenant_id=j.tenant_id AND i.agent_id=j.agent_id WHERE j.agent_id=$1 AND j.job_id=$2 AND j.attempt_id=$3 AND j.state IN ('queued','accepted','running','verifying','awaiting_reboot') AND r.approval_state='approved' AND z.revoked_at IS NULL AND p.expires_at>now() AND i.revoked_at IS NULL").bind(a).bind(q.job_id).bind(q.attempt_id).fetch_optional(&mut *tx).await?.ok_or(Error(StatusCode::NOT_FOUND,"NOT_FOUND"))?;
let job: JobPayload = serde_json::from_slice(&row.get::<Vec<u8>, _>("payload"))?; let job: JobPayload = serde_json::from_slice(&row.get::<Vec<u8>, _>("payload"))?;
let plan_bytes: Vec<u8> = row.get("plan_payload"); let plan_bytes: Vec<u8> = row.get("plan_payload");
if rmm_domain::jobs::hash(&plan_bytes) != row.get::<String, _>("plan_hash") { if rmm_domain::jobs::hash(&plan_bytes) != row.get::<String, _>("plan_hash") {
@@ -46,8 +46,7 @@ pub async fn download(
if job.action.windows_msi().is_some() { if job.action.windows_msi().is_some() {
crate::windows_msi_catalog::validate_job_binding(&plan, &job)?; crate::windows_msi_catalog::validate_job_binding(&plan, &job)?;
crate::catalog::check(&mut tx, &job.action).await?; crate::catalog::check(&mut tx, &job.action).await?;
crate::root_policy::authorize(&mut tx, &plan.principal, &job).await?; crate::jobs::authorize_approved_job(&s, &mut tx, t, &plan, &job, &row).await?;
crate::root_policy::authorize(&mut tx, &row.get::<String, _>("approver"), &job).await?;
} }
if job.asset_id != row.get::<Uuid, _>("asset_id") if job.asset_id != row.get::<Uuid, _>("asset_id")
+55 -1
View File
@@ -4,6 +4,7 @@ use chrono::{DateTime, Utc};
use prost::Message; use prost::Message;
use rmm_domain::MAX_MESSAGE; use rmm_domain::MAX_MESSAGE;
use rmm_protocol::*; use rmm_protocol::*;
use serde_json::{Value, json};
use sha2::{Digest, Sha256}; use sha2::{Digest, Sha256};
use sqlx::Row; use sqlx::Row;
use uuid::Uuid; use uuid::Uuid;
@@ -146,7 +147,14 @@ pub async fn ingest(
match &e.payload { match &e.payload {
Some(Payload::Heartbeat(h)) => { Some(Payload::Heartbeat(h)) => {
Uuid::parse_str(&h.instance_id)?; Uuid::parse_str(&h.instance_id)?;
sqlx::query("UPDATE agent_installations SET last_contact_at=now() WHERE agent_id=$1 AND revoked_at IS NULL").bind(agent).execute(&mut *tx).await?; let usage = h.system_usage.as_ref().and_then(|sample| system_usage(sample, observed));
sqlx::query("UPDATE agent_installations SET last_contact_at=now(),
system_usage=CASE WHEN $2::jsonb IS NULL THEN system_usage
ELSE COALESCE(system_usage,'{}'::jsonb) || $2 END,
system_usage_observed_at=CASE WHEN $2::jsonb ? 'ram_available_bytes'
THEN $3 ELSE system_usage_observed_at END
WHERE agent_id=$1 AND revoked_at IS NULL")
.bind(agent).bind(usage).bind(observed).execute(&mut *tx).await?;
} }
Some(Payload::InventorySnapshot(s)) => { Some(Payload::InventorySnapshot(s)) => {
ensure!( ensure!(
@@ -197,3 +205,49 @@ pub async fn ingest(
e.connection_generation, e.connection_generation,
)) ))
} }
fn system_usage(sample: &SystemUsage, observed: DateTime<Utc>) -> Option<Value> {
let cpu = sample
.cpu_usage_basis_points
.filter(|&value| value <= 10_000);
let memory = sample
.ram_available_bytes
.zip(sample.ram_total_bytes)
.filter(|&(available, total)| total > 0 && available <= total);
let mut usage = serde_json::Map::new();
if let Some(cpu) = cpu {
usage.insert("cpu_usage_percent".into(), json!(f64::from(cpu) / 100.0));
usage.insert("cpu_usage_observed_at".into(), json!(observed));
}
if let Some((available, total)) = memory {
usage.insert("ram_available_bytes".into(), json!(available));
usage.insert("ram_total_bytes".into(), json!(total));
}
(!usage.is_empty()).then_some(Value::Object(usage))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn accepts_zero_usage_and_ignores_invalid_metrics_without_losing_the_heartbeat() {
let mut sample = SystemUsage {
cpu_usage_basis_points: Some(0),
ram_available_bytes: Some(0),
ram_total_bytes: Some(1),
};
let now = Utc::now();
let measured = system_usage(&sample, now).unwrap();
assert_eq!(measured["cpu_usage_percent"], json!(0.0));
assert_eq!(measured["cpu_usage_observed_at"], json!(now));
assert_eq!(measured["ram_available_bytes"], json!(0));
assert_eq!(measured["ram_total_bytes"], json!(1));
sample.cpu_usage_basis_points = Some(10_001);
let partial = system_usage(&sample, now).unwrap();
assert!(partial.get("cpu_usage_percent").is_none());
assert!(partial.get("cpu_usage_observed_at").is_none());
sample.ram_available_bytes = Some(2);
assert_eq!(system_usage(&sample, now), None);
}
}
+1 -1
View File
@@ -418,7 +418,7 @@ async fn issue(
&& snapshot.sha256 == hex::decode(hash(&snapshot.data)).map_err(|_| denied())?, && snapshot.sha256 == hex::decode(hash(&snapshot.data)).map_err(|_| denied())?,
)?; )?;
let scope = match action.manifest().map_err(|_| denied())?.platform { let scope = match action.manifest().map_err(|_| denied())?.platform {
update::Platform::LinuxX64 => "linux.base", update::Platform::LinuxX64 | update::Platform::LinuxArm64 => "linux.base",
update::Platform::WindowsX64 | update::Platform::WindowsGnuX64 => "windows.base", update::Platform::WindowsX64 | update::Platform::WindowsGnuX64 => "windows.base",
}; };
// Health requires a fresh real base inventory of the restarted platform; // Health requires a fresh real base inventory of the restarted platform;
+159 -63
View File
@@ -14,9 +14,10 @@ use axum::{
response::{IntoResponse, Response}, response::{IntoResponse, Response},
routing::{get, post}, routing::{get, post},
}; };
use chrono::{DateTime, Utc};
use futures_util::StreamExt; use futures_util::StreamExt;
use rmm_domain::{ use rmm_domain::{
agent_update::{ArtifactDescriptor, Platform, ReleaseEnvelope, ReleaseManifest}, agent_update::{ArtifactDescriptor, LINUX_ARM64_RELEASE_CAPABILITY, Platform, ReleaseEnvelope, ReleaseManifest},
jobs::{ArtifactReference, encode, hash}, jobs::{ArtifactReference, encode, hash},
}; };
use serde::Deserialize; use serde::Deserialize;
@@ -41,11 +42,7 @@ fn invalid() -> Error {
Error(StatusCode::BAD_REQUEST, "INVALID_AGENT_RELEASE") Error(StatusCode::BAD_REQUEST, "INVALID_AGENT_RELEASE")
} }
pub fn platform_name(platform: Platform) -> &'static str { pub fn platform_name(platform: Platform) -> &'static str {
match platform { platform.target_triple()
Platform::LinuxX64 => "x86_64-unknown-linux-gnu",
Platform::WindowsX64 => "x86_64-pc-windows-msvc",
Platform::WindowsGnuX64 => "x86_64-pc-windows-gnu",
}
} }
pub fn protected_file(path: &FsPath, maximum: u64) -> Result<Vec<u8>, Error> { pub fn protected_file(path: &FsPath, maximum: u64) -> Result<Vec<u8>, Error> {
let key_path = let key_path =
@@ -123,11 +120,13 @@ pub fn store() -> Result<UpdateArtifacts, Error> {
if !metadata.is_file() || metadata.permissions().mode() & 0o077 != 0 { if !metadata.is_file() || metadata.permissions().mode() & 0o077 != 0 {
return Err(fail("AGENT_UPDATE_NOT_CONFIGURED")); return Err(fail("AGENT_UPDATE_NOT_CONFIGURED"));
} }
let profile = std::env::var("RMM_PROFILE").unwrap_or_default();
Ok(UpdateArtifacts::new( Ok(UpdateArtifacts::new(
&std::env::var("RMM_PROFILE").unwrap_or_default(), &profile,
match std::env::var_os("RMM_AGENT_UPDATE_ARTIFACT_DIR") { match std::env::var_os("RMM_AGENT_UPDATE_ARTIFACT_DIR") {
Some(value) if FsPath::new(&value).is_absolute() => value.into(), Some(value) if FsPath::new(&value).is_absolute() => value.into(),
Some(_) => return Err(fail("AGENT_UPDATE_NOT_CONFIGURED")), Some(_) => return Err(fail("AGENT_UPDATE_NOT_CONFIGURED")),
None if profile != "development" => return Err(fail("AGENT_UPDATE_NOT_CONFIGURED")),
None => path None => path
.parent() .parent()
.ok_or_else(|| fail("AGENT_UPDATE_NOT_CONFIGURED"))? .ok_or_else(|| fail("AGENT_UPDATE_NOT_CONFIGURED"))?
@@ -136,14 +135,7 @@ pub fn store() -> Result<UpdateArtifacts, Error> {
metadata.uid(), metadata.uid(),
)?) )?)
} }
fn verifier_platform(platform: Platform) -> rmm_updater::Platform { /// Network input can choose only among statically named protected
match platform {
Platform::LinuxX64 => rmm_updater::Platform::LinuxX64,
Platform::WindowsX64 => rmm_updater::Platform::WindowsX64,
Platform::WindowsGnuX64 => rmm_updater::Platform::WindowsGnuX64,
}
}
/// Network input can choose only one of two statically named protected
/// configuration slots. It never supplies a path or introduces update trust. /// configuration slots. It never supplies a path or introduces update trust.
fn keyring_path_with( fn keyring_path_with(
platform: Platform, platform: Platform,
@@ -151,8 +143,21 @@ fn keyring_path_with(
) -> Result<std::path::PathBuf, Error> { ) -> Result<std::path::PathBuf, Error> {
let name = match platform { let name = match platform {
Platform::LinuxX64 => "RMM_AGENT_UPDATE_LINUX_KEYRING_FILE", Platform::LinuxX64 => "RMM_AGENT_UPDATE_LINUX_KEYRING_FILE",
Platform::LinuxArm64 => "RMM_AGENT_UPDATE_LINUX_ARM64_KEYRING_FILE",
Platform::WindowsX64 => "RMM_AGENT_UPDATE_WINDOWS_KEYRING_FILE", Platform::WindowsX64 => "RMM_AGENT_UPDATE_WINDOWS_KEYRING_FILE",
Platform::WindowsGnuX64 => "RMM_AGENT_UPDATE_WINDOWS_GNU_KEYRING_FILE", Platform::WindowsGnuX64 => {
// The shared device gateway and both management APIs must select the same
// official trust. A legacy development key is usable only in isolated dev.
let official = "RMM_AGENT_UPDATE_WINDOWS_GNU_OFFICIAL_KEYRING_FILE";
if let Some(path) = lookup(official)? {
return FsPath::new(&path).is_absolute().then(|| path.into())
.ok_or_else(|| fail("AGENT_UPDATE_NOT_CONFIGURED"));
}
if lookup("RMM_PROFILE")?.as_deref() != Some("development") {
return Err(fail("AGENT_UPDATE_NOT_CONFIGURED"));
}
"RMM_AGENT_UPDATE_WINDOWS_GNU_KEYRING_FILE"
}
}; };
if let Some(path) = lookup(name)? { if let Some(path) = lookup(name)? {
if path.is_empty() || !FsPath::new(&path).is_absolute() { if path.is_empty() || !FsPath::new(&path).is_absolute() {
@@ -162,6 +167,9 @@ fn keyring_path_with(
} }
// Exact legacy compatibility only when the platform-specific slot is // Exact legacy compatibility only when the platform-specific slot is
// absent. An invalid explicit slot must never silently choose other trust. // absent. An invalid explicit slot must never silently choose other trust.
if matches!(platform, Platform::LinuxArm64 | Platform::WindowsGnuX64) {
return Err(fail("AGENT_UPDATE_NOT_CONFIGURED"));
}
lookup("RMM_AGENT_UPDATE_KEYRING_FILE")? lookup("RMM_AGENT_UPDATE_KEYRING_FILE")?
.map(Into::into) .map(Into::into)
.ok_or_else(|| fail("AGENT_UPDATE_NOT_CONFIGURED")) .ok_or_else(|| fail("AGENT_UPDATE_NOT_CONFIGURED"))
@@ -170,31 +178,20 @@ pub fn verify_envelope(
envelope: &ReleaseEnvelope, envelope: &ReleaseEnvelope,
binding: Option<&rmm_domain::agent_update::UpdaterBinding>, binding: Option<&rmm_domain::agent_update::UpdaterBinding>,
) -> Result<ReleaseManifest, Error> { ) -> Result<ReleaseManifest, Error> {
let platform = envelope.decode().map_err(|_| invalid())?.manifest.platform; verify_envelope_at(envelope, binding, Utc::now())
if platform == Platform::WindowsGnuX64
&& std::env::var("RMM_PROFILE").as_deref() != Ok("development")
{
return Err(fail("AGENT_UPDATE_DEVELOPMENT_CHANNEL_REQUIRED"));
}
verify_signed_envelope(envelope, platform, binding)
} }
fn verify_envelope_at(
// The public management process can copy an operator-selected release into an empty
// catalog. Network-supplied publications additionally go through the profile check above.
fn verify_signed_envelope(
envelope: &ReleaseEnvelope, envelope: &ReleaseEnvelope,
platform: Platform,
binding: Option<&rmm_domain::agent_update::UpdaterBinding>, binding: Option<&rmm_domain::agent_update::UpdaterBinding>,
time: DateTime<Utc>,
) -> Result<ReleaseManifest, Error> { ) -> Result<ReleaseManifest, Error> {
let platform = envelope.decode().map_err(|_| invalid())?.manifest.platform;
let raw = keyring_bytes(platform)?; let raw = keyring_bytes(platform)?;
verify_envelope_with_keyring( verify_envelope_with_keyring(
envelope, envelope,
binding, binding,
&raw, &raw,
chrono::Utc::now() time.timestamp().try_into().map_err(|_| invalid())?,
.timestamp()
.try_into()
.map_err(|_| invalid())?,
) )
} }
fn keyring_bytes(platform: Platform) -> Result<Vec<u8>, Error> { fn keyring_bytes(platform: Platform) -> Result<Vec<u8>, Error> {
@@ -232,7 +229,7 @@ fn verify_envelope_with_keyring(
rmm_updater::TrustedUpdateKey::new( rmm_updater::TrustedUpdateKey::new(
raw.try_into() raw.try_into()
.map_err(|_| fail("AGENT_UPDATE_TRUST_INVALID"))?, .map_err(|_| fail("AGENT_UPDATE_TRUST_INVALID"))?,
verifier_platform(key.platform), key.platform.into(),
key.first_sequence, key.first_sequence,
key.last_sequence, key.last_sequence,
key.revoked, key.revoked,
@@ -243,7 +240,7 @@ fn verify_envelope_with_keyring(
let keyring = rmm_updater::UpdateKeyring::new(config.generation, keys) let keyring = rmm_updater::UpdateKeyring::new(config.generation, keys)
.map_err(|_| fail("AGENT_UPDATE_TRUST_INVALID"))?; .map_err(|_| fail("AGENT_UPDATE_TRUST_INVALID"))?;
let context = rmm_updater::TrustedContext { let context = rmm_updater::TrustedContext {
platform: verifier_platform(decoded.manifest.platform), platform: decoded.manifest.platform.into(),
now_utc_seconds, now_utc_seconds,
keyring_generation: config.generation, keyring_generation: config.generation,
protocol_major: 1, protocol_major: 1,
@@ -418,15 +415,53 @@ pub async fn upload(
json!({"artifact_id":input.artifact_id,"sha256":input.sha256,"size_bytes":input.size_bytes}), json!({"artifact_id":input.artifact_id,"sha256":input.sha256,"size_bytes":input.size_bytes}),
)) ))
} }
enum CatalogReleaseCheck {
Current,
InstalledHelper,
}
impl CatalogReleaseCheck {
fn verification_time(
self,
registered: DateTime<Utc>,
now: DateTime<Utc>,
) -> Result<DateTime<Utc>, Error> {
match self {
Self::Current => Ok(now),
Self::InstalledHelper if registered <= now => Ok(registered),
Self::InstalledHelper => Err(invalid()),
}
}
}
pub async fn checked_release( pub async fn checked_release(
tx: &mut Transaction<'_, Postgres>, tx: &mut Transaction<'_, Postgres>,
id: Uuid, id: Uuid,
) -> Result<(ReleaseEnvelope, ReleaseManifest), Error> { ) -> Result<(ReleaseEnvelope, ReleaseManifest), Error> {
let row = sqlx::query("SELECT envelope,envelope_sha256,manifest_sha256 FROM agent_update_releases WHERE release_id=$1") checked_catalog_release(tx, id, CatalogReleaseCheck::Current).await
}
/// Used only to attest an enrolled, running helper against its registered release.
/// The immutable catalog timestamp proves that the release was valid when registered.
pub(crate) async fn checked_installed_helper_release(
tx: &mut Transaction<'_, Postgres>,
id: Uuid,
) -> Result<ReleaseManifest, Error> {
let (_, manifest) = checked_catalog_release(tx, id, CatalogReleaseCheck::InstalledHelper).await?;
Ok(manifest)
}
async fn checked_catalog_release(
tx: &mut Transaction<'_, Postgres>,
id: Uuid,
check: CatalogReleaseCheck,
) -> Result<(ReleaseEnvelope, ReleaseManifest), Error> {
let row = sqlx::query("SELECT envelope,envelope_sha256,manifest_sha256,created_at FROM agent_update_releases WHERE release_id=$1")
.bind(id).fetch_optional(&mut **tx).await?.ok_or_else(missing)?; .bind(id).fetch_optional(&mut **tx).await?.ok_or_else(missing)?;
let raw: Vec<u8> = row.get("envelope"); let raw: Vec<u8> = row.get("envelope");
let envelope: ReleaseEnvelope = serde_json::from_slice(&raw)?; let envelope: ReleaseEnvelope = serde_json::from_slice(&raw)?;
let manifest = verify_envelope(&envelope, None)?; let time = check.verification_time(row.get("created_at"), Utc::now())?;
let manifest = verify_envelope_at(&envelope, None, time)?;
if encode(&envelope)? != raw if encode(&envelope)? != raw
|| hash(&raw) != row.get::<String, _>("envelope_sha256") || hash(&raw) != row.get::<String, _>("envelope_sha256")
|| hash(&envelope.decode().map_err(|_| invalid())?.payload_bytes) || hash(&envelope.decode().map_err(|_| invalid())?.payload_bytes)
@@ -586,11 +621,14 @@ async fn installed(
) -> Result<Response, Error> { ) -> Result<Response, Error> {
let (tenant, agent) = device(&s, peer, &headers).await?; let (tenant, agent) = device(&s, peer, &headers).await?;
let mut tx = rmm_persistence::tenant_tx(&s.pool, tenant).await?; let mut tx = rmm_persistence::tenant_tx(&s.pool, tenant).await?;
let row = sqlx::query("SELECT reported_agent_version,connection_generation,last_contact_at FROM agent_installations WHERE agent_id=$1 AND revoked_at IS NULL").bind(agent).fetch_one(&mut *tx).await?; let row = sqlx::query("SELECT asset_id,enrollment_generation,assignment_version,capabilities,reported_agent_version,connection_generation,last_contact_at FROM agent_installations WHERE agent_id=$1 AND revoked_at IS NULL").bind(agent).fetch_one(&mut *tx).await?;
tx.commit().await?; tx.commit().await?;
Ok(( Ok((
[("cache-control", "private, no-store")], [("cache-control", "private, no-store")],
Json(json!({"agent_id":agent, Json(json!({"tenant_id":tenant,"asset_id":row.get::<Uuid,_>("asset_id"),"agent_id":agent,
"enrollment_generation":row.get::<i64,_>("enrollment_generation"),
"assignment_version":row.get::<i64,_>("assignment_version"),
"capabilities":row.get::<Value,_>("capabilities"),
"agent_version":row.get::<Option<String>,_>("reported_agent_version"), "agent_version":row.get::<Option<String>,_>("reported_agent_version"),
"connection_generation":row.get::<i64,_>("connection_generation"), "connection_generation":row.get::<i64,_>("connection_generation"),
"last_contact_at":row.get::<Option<chrono::DateTime<chrono::Utc>>,_>("last_contact_at")})), "last_contact_at":row.get::<Option<chrono::DateTime<chrono::Utc>>,_>("last_contact_at")})),
@@ -610,18 +648,21 @@ async fn check_device_platform(
.fetch_one(&mut **tx) .fetch_one(&mut **tx)
.await?; .await?;
let caps: Vec<String> = serde_json::from_value(caps)?; let caps: Vec<String> = serde_json::from_value(caps)?;
let expected = match platform { if device_supports_release(platform, &caps) {
Platform::LinuxX64 => "linux.base/1", Ok(())
Platform::WindowsX64 if caps.iter().any(|c| c == "agent.release.windows.gnu/1") => { } else {
return Err(missing()); Err(missing())
} }
Platform::WindowsX64 => "windows.base/1", }
Platform::WindowsGnuX64 => "agent.release.windows.gnu/1",
}; fn device_supports_release(platform: Platform, caps: &[String]) -> bool {
if !caps.iter().any(|c| c == expected) { let has = |expected: &str| caps.iter().any(|capability| capability == expected);
return Err(missing()); match platform {
Platform::LinuxX64 => has("linux.base/1") && !has(LINUX_ARM64_RELEASE_CAPABILITY),
Platform::LinuxArm64 => has("linux.base/1") && has(LINUX_ARM64_RELEASE_CAPABILITY),
Platform::WindowsX64 => has("windows.base/1") && !has("agent.release.windows.gnu/1"),
Platform::WindowsGnuX64 => has("agent.release.windows.gnu/1"),
} }
Ok(())
} }
/// A published release grants access to its two fixed binaries for authenticated /// A published release grants access to its two fixed binaries for authenticated
@@ -736,7 +777,7 @@ async fn download(
return Err(invalid()); return Err(invalid());
} }
let mut tx = rmm_persistence::tenant_tx(&s.pool, tenant).await?; let mut tx = rmm_persistence::tenant_tx(&s.pool, tenant).await?;
let row=sqlx::query("SELECT j.payload,p.payload AS plan_payload,p.plan_hash,z.principal AS approver,i.asset_id,i.enrollment_generation,i.assignment_version FROM jobs j JOIN operations o ON o.tenant_id=j.tenant_id AND o.operation_id=j.operation_id JOIN authorizations z ON z.tenant_id=o.tenant_id AND z.authorization_id=o.authorization_id JOIN approval_requests r ON r.tenant_id=j.tenant_id AND r.operation_id=j.operation_id JOIN operation_plans p ON p.tenant_id=r.tenant_id AND p.plan_id=r.plan_id JOIN agent_installations i ON i.tenant_id=j.tenant_id AND i.agent_id=j.agent_id WHERE j.agent_id=$1 AND j.job_id=$2 AND j.attempt_id=$3 AND j.state IN ('queued','accepted','running','verifying') AND r.approval_state='approved' AND z.revoked_at IS NULL AND p.expires_at>now() AND i.revoked_at IS NULL") let row=sqlx::query("SELECT j.payload,p.payload AS plan_payload,p.plan_hash,z.principal AS approver,r.principal AS submitter,i.asset_id,i.enrollment_generation,i.assignment_version FROM jobs j JOIN operations o ON o.tenant_id=j.tenant_id AND o.operation_id=j.operation_id JOIN authorizations z ON z.tenant_id=o.tenant_id AND z.authorization_id=o.authorization_id JOIN approval_requests r ON r.tenant_id=j.tenant_id AND r.operation_id=j.operation_id JOIN operation_plans p ON p.tenant_id=r.tenant_id AND p.plan_id=r.plan_id JOIN agent_installations i ON i.tenant_id=j.tenant_id AND i.agent_id=j.agent_id WHERE j.agent_id=$1 AND j.job_id=$2 AND j.attempt_id=$3 AND j.state IN ('queued','accepted','running','verifying') AND r.approval_state='approved' AND z.revoked_at IS NULL AND p.expires_at>now() AND i.revoked_at IS NULL")
.bind(agent).bind(q.job_id).bind(q.attempt_id).fetch_optional(&mut *tx).await?.ok_or_else(missing)?; .bind(agent).bind(q.job_id).bind(q.attempt_id).fetch_optional(&mut *tx).await?.ok_or_else(missing)?;
let job: rmm_domain::jobs::JobPayload = let job: rmm_domain::jobs::JobPayload =
serde_json::from_slice(&row.get::<Vec<u8>, _>("payload"))?; serde_json::from_slice(&row.get::<Vec<u8>, _>("payload"))?;
@@ -749,8 +790,7 @@ async fn download(
let rmm_domain::jobs::Action::UpdateAgent { update } = &job.action else { let rmm_domain::jobs::Action::UpdateAgent { update } = &job.action else {
return Err(missing()); return Err(missing());
}; };
crate::root_policy::authorize(&mut tx, &plan.principal, &job).await?; crate::jobs::authorize_approved_job(&s, &mut tx, tenant, &plan, &job, &row).await?;
crate::root_policy::authorize(&mut tx, &row.get::<String, _>("approver"), &job).await?;
check_update(&mut tx, update).await?; check_update(&mut tx, update).await?;
if job.tenant_id != tenant if job.tenant_id != tenant
|| job.agent_id != agent || job.agent_id != agent
@@ -1076,6 +1116,21 @@ mod tests {
FsPath::new("legacy-relative.json") FsPath::new("legacy-relative.json")
); );
} }
let dev_only = BTreeMap::from([
("RMM_AGENT_UPDATE_WINDOWS_GNU_KEYRING_FILE", "/trust/dev.json"),
("RMM_AGENT_UPDATE_KEYRING_FILE", "/trust/legacy.json"),
]);
assert!(choose(Platform::WindowsGnuX64, &dev_only).is_err());
let mut mixed = dev_only;
mixed.insert("RMM_PROFILE", "development");
assert_eq!(choose(Platform::WindowsGnuX64, &mixed).unwrap(), FsPath::new("/trust/dev.json"));
mixed.insert("RMM_AGENT_UPDATE_WINDOWS_GNU_OFFICIAL_KEYRING_FILE", "/trust/official.json");
for profile in ["development", "production"] {
mixed.insert("RMM_PROFILE", profile);
assert_eq!(choose(Platform::WindowsGnuX64, &mixed).unwrap(), FsPath::new("/trust/official.json"));
}
mixed.insert("RMM_AGENT_UPDATE_WINDOWS_GNU_OFFICIAL_KEYRING_FILE", "");
assert!(choose(Platform::WindowsGnuX64, &mixed).is_err());
let only_linux = let only_linux =
BTreeMap::from([("RMM_AGENT_UPDATE_LINUX_KEYRING_FILE", "/trust/linux.json")]); BTreeMap::from([("RMM_AGENT_UPDATE_LINUX_KEYRING_FILE", "/trust/linux.json")]);
assert!(choose(Platform::WindowsX64, &only_linux).is_err()); assert!(choose(Platform::WindowsX64, &only_linux).is_err());
@@ -1156,6 +1211,49 @@ mod tests {
}; };
(envelope, keys) (envelope, keys)
}; };
let (official, official_keys) = make(Platform::WindowsGnuX64);
let (development, _) = make(Platform::WindowsGnuX64);
let official_ring = encode(&official_keys).unwrap();
assert!(verify_envelope_with_keyring(&official, None, &official_ring, 100).is_ok());
assert!(verify_envelope_with_keyring(&development, None, &official_ring, 100).is_err());
// At the expiry boundary, installed helpers still use the immutable
// registration time. Bootstrap and update checks use the current time.
let registered = DateTime::from_timestamp(100, 0).unwrap();
let now = DateTime::from_timestamp(200, 0).unwrap();
let check_catalog = |check: CatalogReleaseCheck,
registered: DateTime<Utc>,
envelope: &ReleaseEnvelope,
keyring: &[u8]| {
let at = check.verification_time(registered, now)?.timestamp() as u64;
verify_envelope_with_keyring(envelope, None, keyring, at)
};
let installed = CatalogReleaseCheck::InstalledHelper;
assert!(check_catalog(installed, registered, &official, &official_ring).is_ok());
assert!(
check_catalog(CatalogReleaseCheck::Current, registered, &official, &official_ring)
.is_err()
);
assert!(check_catalog(CatalogReleaseCheck::InstalledHelper, now, &official, &official_ring).is_err());
assert!(
CatalogReleaseCheck::InstalledHelper
.verification_time(now + chrono::Duration::seconds(1), now)
.is_err()
);
assert!(
check_catalog(CatalogReleaseCheck::InstalledHelper, registered, &development, &official_ring)
.is_err()
);
let mut revoked_official = official_keys;
revoked_official.keys[0].revoked = true;
assert!(
check_catalog(
CatalogReleaseCheck::InstalledHelper,
registered,
&official,
&encode(&revoked_official).unwrap()
)
.is_err()
);
let (linux, linux_keys) = make(Platform::LinuxX64); let (linux, linux_keys) = make(Platform::LinuxX64);
let (windows, windows_keys) = make(Platform::WindowsX64); let (windows, windows_keys) = make(Platform::WindowsX64);
let linux_raw = encode(&linux_keys).unwrap(); let linux_raw = encode(&linux_keys).unwrap();
@@ -1235,19 +1333,17 @@ mod tests {
} }
} }
#[test] #[test]
fn plan_request_accepts_release_id_but_never_user_supplied_local_bindings() { fn update_releases_are_not_device_job_plans() {
let mut value = json!({"tenant_id":"11111111-1111-4111-8111-111111111111","action":"update_agent","targets":{"asset_ids":["11111111-1111-4111-8111-111111111112"]}, let mut value = json!({"tenant_id":"11111111-1111-4111-8111-111111111111","action":"update_agent","targets":{"asset_ids":["11111111-1111-4111-8111-111111111112"]},
"parameters":{"release_id":"11111111-1111-4111-8111-111111111113","execution_identity":"root","timeout_seconds":600,"max_output_bytes":65536}, "parameters":{"release_id":"11111111-1111-4111-8111-111111111113","execution_identity":"root","timeout_seconds":600,"max_output_bytes":65536},
"schedule":{"not_before":"2030-01-01T12:00:00Z","start_before":"2030-01-01T12:10:00Z","offline_policy":"wait_until_deadline"},"rollout":{"max_parallel":1,"halt_after_failures":1},"reason":"codec only"}); "schedule":{"not_before":"2030-01-01T12:00:00Z","start_before":"2030-01-01T12:10:00Z","offline_policy":"wait_until_deadline"},"rollout":{"max_parallel":1,"halt_after_failures":1},"reason":"codec only"});
let parsed: crate::jobs::PlanRequest = serde_json::from_value(value.clone()).unwrap(); let tenant = Uuid::parse_str(value["tenant_id"].as_str().unwrap()).unwrap();
assert!(matches!(parsed, crate::jobs::PlanRequest::AgentUpdate(_))); for local_binding in [false, true] {
// The old synchronous resolver cannot manufacture local state. if local_binding {
assert!( value["parameters"]["predecessor"] = json!({"installed_record_sha256":"00".repeat(32)});
parsed }
.resolve(Uuid::parse_str(value["tenant_id"].as_str().unwrap()).unwrap()) let parsed: crate::jobs::PlanRequest = serde_json::from_value(value.clone()).unwrap();
.is_err() assert_eq!(parsed.resolve(tenant).err().unwrap().1, "SCRIPT_ACTION_REQUIRED");
); }
value["parameters"]["predecessor"] = json!({"installed_record_sha256":"00".repeat(32)});
assert!(serde_json::from_value::<crate::jobs::PlanRequest>(value).is_err());
} }
} }
+1
View File
@@ -66,6 +66,7 @@ pub(super) async fn summaries(
"plan_hash":row.get::<String,_>("plan_hash"), "requester":row.get::<String,_>("requester"), "plan_hash":row.get::<String,_>("plan_hash"), "requester":row.get::<String,_>("requester"),
"targets":row.get::<Value,_>("targets"), "created_at":row.get::<DateTime<Utc>,_>("created_at"), "targets":row.get::<Value,_>("targets"), "created_at":row.get::<DateTime<Utc>,_>("created_at"),
"expires_at":row.get::<DateTime<Utc>,_>("expires_at"), "approval_state":row.get::<Option<String>,_>("approval_state"), "expires_at":row.get::<DateTime<Utc>,_>("expires_at"), "approval_state":row.get::<Option<String>,_>("approval_state"),
"decision":row.get::<Option<Value>,_>("decision"),
})); }));
} }
Ok(items) Ok(items)
+26
View File
@@ -71,6 +71,13 @@ async fn inbox_count_cursor_history_and_customer_permissions() {
sqlx::query("INSERT INTO approval_requests(tenant_id,operation_id,plan_id,principal,idempotency_key,request_hash,created_at,approval_state) sqlx::query("INSERT INTO approval_requests(tenant_id,operation_id,plan_id,principal,idempotency_key,request_hash,created_at,approval_state)
VALUES($1,$2,$3,'mcp:fixture',$4,'fixture',$5,$6)") VALUES($1,$2,$3,'mcp:fixture',$4,'fixture',$5,$6)")
.bind(tenant).bind(op_id).bind(plan_id).bind(plan_id.to_string()).bind(stamp).bind(status).execute(&admin).await.unwrap(); .bind(tenant).bind(op_id).bind(plan_id).bind(plan_id.to_string()).bind(stamp).bind(status).execute(&admin).await.unwrap();
if status == "rejected" {
sqlx::query("INSERT INTO audit_events VALUES($1,$2,$3,'plan_authorization',$4,$5)")
.bind(tenant).bind(Uuid::new_v4()).bind(format!("reviewer:{tenant}"))
.bind(json!({"operation_id":op_id,"plan_id":plan_id,"plan_hash":"fixture",
"decision":"reject","testsimulation":true}))
.bind(stamp + chrono::Duration::seconds(5)).execute(&admin).await.unwrap();
}
} }
} }
@@ -173,6 +180,25 @@ async fn inbox_count_cursor_history_and_customer_permissions() {
.collect(); .collect();
assert_eq!(states.len(), 2); assert_eq!(states.len(), 2);
assert!(states.contains(&"expired") && states.contains(&"rejected")); assert!(states.contains(&"expired") && states.contains(&"rejected"));
let items = history["items"].as_array().unwrap();
let rejected = items.iter().find(|item| item["approval_state"] == "rejected").unwrap();
assert_eq!(rejected["decision"]["principal"], format!("reviewer:{a}"));
assert_eq!(rejected["decision"]["testsimulation"], true);
let at: DateTime<Utc> = serde_json::from_value(rejected["decision"]["at"].clone()).unwrap();
assert_eq!(at.timestamp_micros(), (stamp + chrono::Duration::seconds(5)).timestamp_micros());
assert!(items.iter().find(|item| item["approval_state"] == "expired").unwrap()["decision"].is_null());
// Filter the authorized storage rows before applying the page limit.
for (tenant, disclose_names, matches) in [(a, true, 1), (b, false, 0)] {
let mut tx = rmm_persistence::tenant_tx(&state.pool, tenant).await.unwrap();
let rows: Vec<(Uuid, DateTime<Utc>)> = sqlx::query_as(include_str!("../order_filter.sql"))
.bind(Utc::now()).bind(None::<DateTime<Utc>>).bind(Uuid::nil())
.bind(stamp - chrono::Duration::seconds(1)).bind(stamp + chrono::Duration::seconds(1))
.bind("kernel").bind("rejected").bind("Kunde").bind(None::<Uuid>).bind(disclose_names)
.bind(1_i64).fetch_all(&mut *tx).await.unwrap();
assert_eq!(rows.len(), matches);
tx.commit().await.unwrap();
}
let count = list( let count = list(
&state, &state,
&p, &p,
+190 -6
View File
@@ -4,8 +4,9 @@
param( param(
[Parameter(Mandatory)][Uri]$BootstrapBase, [Parameter(Mandatory)][Uri]$BootstrapBase,
[Security.SecureString]$EnrollmentToken, [Security.SecureString]$EnrollmentToken,
[switch]$EnableAdministratorScripts,
[ValidateSet('x86_64-pc-windows-msvc','x86_64-pc-windows-gnu')] [ValidateSet('x86_64-pc-windows-msvc','x86_64-pc-windows-gnu')]
[string]$Platform = 'x86_64-pc-windows-msvc' [string]$Platform = 'x86_64-pc-windows-gnu'
) )
$ErrorActionPreference = 'Stop' $ErrorActionPreference = 'Stop'
Set-StrictMode -Version Latest Set-StrictMode -Version Latest
@@ -66,8 +67,191 @@ function Set-Text([string]$Path, [string]$Value) {
function Get-Hash([string]$Path) { function Get-Hash([string]$Path) {
return (Get-FileHash -LiteralPath $Path -Algorithm SHA256).Hash.ToLowerInvariant() return (Get-FileHash -LiteralPath $Path -Algorithm SHA256).Hash.ToLowerInvariant()
} }
# The network process stays LocalService. Only the pinned local helper consumes
# SYSTEM grants. Its private ledger persists across restarts and signed updates.
function Assert-AdminPath([string]$Path, [string]$StopAt) {
$item = Get-Item -LiteralPath $Path -Force
while ($item) {
if ($item.Attributes -band [IO.FileAttributes]::ReparsePoint) { throw "Unexpected reparse point: $($item.FullName)" }
$acl = Get-Acl -LiteralPath $item.FullName
if ($acl.GetOwner([Security.Principal.SecurityIdentifier]).Value -notin @($administrators.Value,$system.Value)) {
throw "Administrator-owned path required: $($item.FullName)"
}
foreach ($rule in $acl.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier])) {
if ($rule.AccessControlType -eq 'Allow' -and $rule.IdentityReference.Value -notin @($administrators.Value,$system.Value) -and
([int64]$rule.FileSystemRights -band 0x500d0156)) { throw "Writable installation path: $($item.FullName)" }
}
if ($item.FullName -ieq $StopAt) { return }
$item = if ($item -is [IO.FileInfo]) { $item.Directory } else { $item.Parent }
}
throw 'Path outside the expected installation directory.'
}
function Publish-HelperText([string]$Path, [string]$Text) {
$pending = $Path + '.' + [Guid]::NewGuid()
try {
$f = [IO.File]::Open($pending, 'CreateNew')
try {
$bytes = $utf8.GetBytes($Text)
$f.Write($bytes, 0, $bytes.Length)
$f.Flush($true)
} finally { $f.Dispose() }
$acl = Get-Acl -LiteralPath $pending
$acl.SetOwner($administrators)
Set-Acl -LiteralPath $pending -AclObject $acl
[IO.File]::Move($pending, $Path)
} finally { if (Test-Path -LiteralPath $pending) { Remove-Item -LiteralPath $pending } }
}
function Install-ScriptHelper {
# Enrollment and ordinary updates cannot grant SYSTEM execution. This switch
# is a local administrator's choice for this particular installation.
if (!$EnableAdministratorScripts) { return }
$cfg = Join-Path $data 'config.json'
Assert-AdminPath $cfg $data
$guardPath = Join-Path $data 'release-job.lock'
Assert-AdminPath $guardPath $data
$gate = [IO.File]::Open($guardPath,'Open','ReadWrite','None')
try {
$config = [IO.File]::ReadAllText($cfg) | ConvertFrom-Json
if (!$config.PSObject.Properties['enable_jobs'] -or !$config.enable_jobs) { throw 'Local script execution is disabled.' }
$timePath = Join-Path $data 'job-time.json'
if ($config.localservice_time_policy -ine $timePath) { throw 'Expected the enrolled LocalService time policy.' }
if (($config.PSObject.Properties['windows_echo_probe_only'] -and $config.windows_echo_probe_only) -or
($config.PSObject.Properties['windows_update_helper'] -and $config.windows_update_helper)) {
throw 'The existing restricted execution profile must finish and be closed before provisioning.'
}
$alreadyConfigured = $config.PSObject.Properties['managed_script_helper'] -and $config.managed_script_helper
$records = Join-Path $data 'release-state'
if ((Test-Path (Join-Path $records 'release-transition.json')) -or (Test-Path (Join-Path $data 'release-transition.json'))) {
throw 'Agent update in progress. Retry the installer once it completes.'
}
$record = Join-Path $records 'installed-release.json'
if (!(Test-Path -LiteralPath $record)) { $record = Join-Path $data 'installed-release.json' }
Assert-AdminPath $record $data
$installed = [IO.File]::ReadAllText($record) | ConvertFrom-Json
$release = Get-Id $installed.release_id
$images = Join-Path $app ('releases\' + $release)
$agentExe = Join-Path $images 'rmm-agent-windows.exe'
$helperExe = Join-Path $images 'rmm-helper-windows.exe'
$worker = Join-Path $app 'rmm-updater-windows.exe'
$envelope = Join-Path $images 'envelope.json'
$ring = Join-Path $data 'release-keyring.json'
foreach ($path in @($agentExe,$helperExe,$worker,$envelope)) { Assert-AdminPath $path $app }
foreach ($path in @($ring,$timePath)) { Assert-AdminPath $path $data }
$service = Get-CimInstance Win32_Service -Filter "Name='RmmDiscoveryWindows'"
$pull = Get-CimInstance Win32_Service -Filter "Name='RmmDiscoveryReleasePull'"
if (!$service -or $service.StartName -ine 'NT AUTHORITY\LocalService' -or
$service.PathName -cne ('"' + $agentExe + '" --service --config "' + $cfg + '"') -or
!$pull -or $pull.StartName -ine 'LocalSystem' -or $pull.PathName -cne ('"' + $worker + '" --release-service')) {
throw 'Service registrations do not match the installed release.'
}
$verified = & $worker --verify-bootstrap $ring $envelope $agentExe $helperExe
if ($LASTEXITCODE -ne 0 -or ($verified | ConvertFrom-Json).release_id -cne $release) { throw 'Installed code pair failed signature verification.' }
foreach ($binary in @($worker,$helperExe)) {
$supported = & $binary --managed-script-helper-version
if ($LASTEXITCODE -ne 0 -or $supported -cne 'managed-script-helper/1') { throw 'Update the agent pair and stable updater before enabling administrator scripts.' }
}
$preservesPolicy = & $worker --managed-script-policy-version
if ($LASTEXITCODE -ne 0 -or $preservesPolicy -cne 'release-preserves-script-policy/1') {
throw 'Administrator scripts require the stable updater that preserves the local policy during release switches and rollbacks.'
}
$id = [IO.File]::ReadAllText($identity) | ConvertFrom-Json
$policy = [IO.File]::ReadAllText($timePath) | ConvertFrom-Json
if ($policy.tenant_id -cne $installed.tenant_id -or $policy.job_signing_public_key_hex -cnotmatch '^[0-9a-f]{64}$') {
throw 'Enrolled job trust and installed release belong to different configurations.'
}
$binding = [ordered]@{tenant_id=(Get-Id $policy.tenant_id);agent_id=(Get-Id $id.agent_id);asset_id=(Get-Id $id.asset_id)
enrollment_generation=1;assignment_version=1;public_key_hex=$policy.job_signing_public_key_hex}
$helperName = 'RmmDiscoverySystemHelper'
$helperCommand = '"' + $helperExe + '" --service'
$agentSid = [Security.Principal.NTAccount]::new('NT SERVICE',$serviceName).Translate([Security.Principal.SecurityIdentifier])
$root = Join-Path ([Environment]::GetFolderPath('CommonApplicationData')) 'RustDiscoverySystem'
$stamp = Join-Path $root 'script-helper-enrollment.json'
$owner = [ordered]@{agent_id=$binding.agent_id;asset_id=$binding.asset_id;tenant_id=$binding.tenant_id} | ConvertTo-Json -Compress
$helper = Get-CimInstance Win32_Service -Filter "Name='RmmDiscoverySystemHelper'"
if ($helper -and !$alreadyConfigured -and !(Test-Path -LiteralPath $stamp)) {
throw 'Existing local helper registration must be reconciled before provisioning.'
}
if (!(Test-Path -LiteralPath $root)) {
$stage = Join-Path $data ('script-helper-' + [Guid]::NewGuid())
[void][IO.Directory]::CreateDirectory($stage,(Get-DirectoryAcl $agentSid 'ReadAndExecute'))
try {
Publish-HelperText (Join-Path $stage 'script-helper-enrollment.json') $owner
[IO.Directory]::Move($stage,$root)
} finally { if (Test-Path -LiteralPath $stage) { Remove-Item -LiteralPath $stage -Recurse -Force } }
}
Assert-AdminPath $root $root
if (Test-Path -LiteralPath $stamp) {
Assert-AdminPath $stamp $root
if ([IO.File]::ReadAllText($stamp) -cne $owner) { throw 'Local helper belongs to another enrollment.' }
} elseif (!$alreadyConfigured) { throw 'Existing helper state must be reconciled before migration.' }
if ($helper -and ($helper.StartName -ine 'LocalSystem' -or $helper.PathName -cne $helperCommand)) { throw 'Unexpected local helper registration.' }
if (!$helper) { New-Service -Name $helperName -BinaryPathName $helperCommand -StartupType Manual | Out-Null }
& (Join-Path $env:SystemRoot 'System32\sc.exe') sidtype $helperName unrestricted | Out-Null
if ($LASTEXITCODE -ne 0) { throw 'Could not set the local helper service SID.' }
$inputDto = [ordered]@{binding=$binding;release_id=$release;agent_sha256=(Get-Hash $agentExe)
helper_sha256=(Get-Hash $helperExe);max_runtime_seconds=3600;managed_scripts=$true}
$rendered = ($inputDto | ConvertTo-Json -Depth 6 -Compress) | & $helperExe --prepare-enrolled-windows-update
if ($LASTEXITCODE -ne 0) { throw 'Helper could not bind the signed code pair to the enrollment.' }
$pins = $rendered | ConvertFrom-Json
foreach ($kv in @(@('helper.json',$pins.helper_settings),@('agent-pin.json',$pins.agent_pin))) {
$path = Join-Path $root $kv[0]
if (Test-Path -LiteralPath $path) {
Assert-AdminPath $path $root
if ([IO.File]::ReadAllText($path) -cne $kv[1]) { throw 'An existing helper pin differs from this release or enrollment.' }
} else { Publish-HelperText $path $kv[1] }
}
$private = Join-Path $root 'state'
if (!(Test-Path -LiteralPath $private)) { [void][IO.Directory]::CreateDirectory($private,(Get-DirectoryAcl $null '')) }
Assert-AdminPath $private $root
$intents = Join-Path $root 'agent-intents'
if (!(Test-Path -LiteralPath $intents)) { [void][IO.Directory]::CreateDirectory($intents,(Get-DirectoryAcl $agentSid 'ReadAndExecute')) }
Assert-AdminPath $intents $root
foreach ($leaf in @('system-intents.sqlite','system-intents.sqlite-journal')) {
$path = Join-Path $intents $leaf
if (!(Test-Path -LiteralPath $path)) { [IO.File]::Open($path,'CreateNew').Dispose() }
if ((Get-Item -Force -LiteralPath $path).Attributes -band [IO.FileAttributes]::ReparsePoint) { throw 'Unexpected link in intent journal.' }
if (!$alreadyConfigured) {
$acl = [Security.AccessControl.FileSecurity]::new()
$acl.SetOwner($administrators)
$acl.SetAccessRuleProtection($true,$false)
foreach ($sid in @($system,$administrators)) { $acl.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new($sid,'FullControl','Allow')) }
$acl.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new($agentSid,[Security.AccessControl.FileSystemRights]0x12019f,'Allow'))
Set-Acl -LiteralPath $path -AclObject $acl
}
}
if (!$alreadyConfigured) {
Stop-Service $serviceName
$temp = $cfg + '.' + [Guid]::NewGuid()
try {
$config | Add-Member -NotePropertyName managed_script_helper -NotePropertyValue $true -Force
Set-Text $temp ($config | ConvertTo-Json -Depth 12 -Compress)
[IO.File]::Replace($temp,$cfg,[NullString]::Value)
} catch {
Start-Service $serviceName
throw
} finally {
if (Test-Path -LiteralPath $temp) { Remove-Item -LiteralPath $temp }
}
}
try {
Set-Service $helperName -StartupType Automatic
Start-Service $helperName
} finally { Start-Service $serviceName }
} finally { $gate.Dispose() }
}
function Start-ReleaseAfterFirstContact { function Start-ReleaseAfterFirstContact {
$receipt = Join-Path $state 'job-readiness.json' $receipt = Join-Path $state 'job-readiness.json'
# A previous installer can have stopped the enrolled agent just before
# committing its helper configuration. Resume the same local enrollment.
if ((Get-Service $serviceName).Status -eq 'Stopped') {
$agent = Get-CimInstance Win32_Service -Filter "Name='RmmDiscoveryWindows'"
if ($agent.StartName -ine 'NT AUTHORITY\LocalService') { throw 'Unexpected enrolled agent identity.' }
Start-Service $serviceName
}
$until = [DateTime]::UtcNow.AddSeconds(120) $until = [DateTime]::UtcNow.AddSeconds(120)
while ([DateTime]::UtcNow -lt $until) { while ([DateTime]::UtcNow -lt $until) {
if ((Get-Service $serviceName).Status -ne 'Running') { throw 'Agent stopped before first gateway contact. Inspect the installed service.' } if ((Get-Service $serviceName).Status -ne 'Running') { throw 'Agent stopped before first gateway contact. Inspect the installed service.' }
@@ -76,7 +260,7 @@ function Start-ReleaseAfterFirstContact {
$enrolled = [IO.File]::ReadAllText($identity) | ConvertFrom-Json $enrolled = [IO.File]::ReadAllText($identity) | ConvertFrom-Json
$hello = [IO.File]::ReadAllText($receipt) | ConvertFrom-Json $hello = [IO.File]::ReadAllText($receipt) | ConvertFrom-Json
if ($hello.agent_id -ceq $enrolled.agent_id -and $hello.connection_generation -ge 1) { if ($hello.agent_id -ceq $enrolled.agent_id -and $hello.connection_generation -ge 1) {
Start-Service $releaseService try { Install-ScriptHelper } finally { Start-Service $releaseService }
Remove-Item -LiteralPath $firstContact -Force Remove-Item -LiteralPath $firstContact -Force
return return
} }
@@ -85,6 +269,9 @@ function Start-ReleaseAfterFirstContact {
} }
throw 'First authenticated version report is pending. Rerun the installer to finish with this identity.' throw 'First authenticated version report is pending. Rerun the installer to finish with this identity.'
} }
$utf8 = New-Object Text.UTF8Encoding($false)
$administrators = [Security.Principal.SecurityIdentifier]::new('S-1-5-32-544')
$system = [Security.Principal.SecurityIdentifier]::new('S-1-5-18')
$origin = Get-Origin $BootstrapBase $origin = Get-Origin $BootstrapBase
$app = Join-Path ([Environment]::GetFolderPath('ProgramFiles')) 'RustDiscovery' $app = Join-Path ([Environment]::GetFolderPath('ProgramFiles')) 'RustDiscovery'
$data = Join-Path ([Environment]::GetFolderPath('CommonApplicationData')) 'RustDiscovery' $data = Join-Path ([Environment]::GetFolderPath('CommonApplicationData')) 'RustDiscovery'
@@ -95,7 +282,7 @@ $serviceName = 'RmmDiscoveryWindows'
$releaseService = 'RmmDiscoveryReleasePull' $releaseService = 'RmmDiscoveryReleasePull'
$service = Get-Service -Name $serviceName -ErrorAction SilentlyContinue $service = Get-Service -Name $serviceName -ErrorAction SilentlyContinue
if ($service -and (Test-Path -LiteralPath $identity -PathType Leaf)) { if ($service -and (Test-Path -LiteralPath $identity -PathType Leaf)) {
if (Test-Path -LiteralPath $firstContact -PathType Leaf) { Start-ReleaseAfterFirstContact } if (Test-Path -LiteralPath $firstContact -PathType Leaf) { Start-ReleaseAfterFirstContact } else { Install-ScriptHelper }
Write-Output "Rust Discovery is already enrolled. Agent service: $($service.Status)." Write-Output "Rust Discovery is already enrolled. Agent service: $($service.Status)."
return return
} }
@@ -108,9 +295,6 @@ try { $token = [Runtime.InteropServices.Marshal]::PtrToStringBSTR($ptr) }
finally { [Runtime.InteropServices.Marshal]::ZeroFreeBSTR($ptr) } finally { [Runtime.InteropServices.Marshal]::ZeroFreeBSTR($ptr) }
if ($token -cnotmatch '^[0-9a-f]{64}$') { throw 'Invalid one-time enrollment token.' } if ($token -cnotmatch '^[0-9a-f]{64}$') { throw 'Invalid one-time enrollment token.' }
$query = '?platform=' + $platform $query = '?platform=' + $platform
$utf8 = New-Object Text.UTF8Encoding($false)
$administrators = [Security.Principal.SecurityIdentifier]::new('S-1-5-32-544')
$system = [Security.Principal.SecurityIdentifier]::new('S-1-5-18')
$stage = Join-Path ([Environment]::GetFolderPath('ProgramFiles')) ('RustDiscovery-install-' + [Guid]::NewGuid().ToString('N')) $stage = Join-Path ([Environment]::GetFolderPath('ProgramFiles')) ('RustDiscovery-install-' + [Guid]::NewGuid().ToString('N'))
[void][IO.Directory]::CreateDirectory($stage, (Get-DirectoryAcl $null '')) [void][IO.Directory]::CreateDirectory($stage, (Get-DirectoryAcl $null ''))
$madeApp = $false $madeApp = $false
+1 -1
View File
@@ -1,5 +1,5 @@
#!/bin/sh #!/bin/sh
# Usage: sudo sh linux.sh https://bootstrap.example # Linux x86-64 / ARM64. Usage: sudo sh linux.sh https://bootstrap.example [--enable-admin-scripts]
set -eu set -eu
umask 077 umask 077
file=$(mktemp) file=$(mktemp)
+318 -18
View File
@@ -1,9 +1,11 @@
"""Bootstrap a Linux systemd client and maintain its signed release pair.""" """Bootstrap a Linux systemd client and maintain its signed release pair."""
import argparse import argparse
import contextlib
import datetime import datetime
import fcntl import fcntl
import getpass import getpass
import hashlib import hashlib
import io
import json import json
import os import os
from pathlib import Path from pathlib import Path
@@ -14,6 +16,7 @@ import shutil
import socket import socket
import sqlite3 import sqlite3
import ssl import ssl
import stat
import subprocess import subprocess
import sys import sys
import tempfile import tempfile
@@ -26,7 +29,9 @@ ROOT = Path('/opt/rust-discovery-client')
STATE = Path('/var/lib/rmm-discovery') STATE = Path('/var/lib/rmm-discovery')
SERVICE = 'rmm-discovery-agent.service' SERVICE = 'rmm-discovery-agent.service'
TIMER = 'rmm-discovery-update.timer' TIMER = 'rmm-discovery-update.timer'
PLATFORM = 'x86_64-unknown-linux-gnu' HELPER = 'rmm-discovery-managed-script-helper.service'
HELPER_SOCKET = Path('/run/rmm-discovery-script-helper/control.sock')
OLD_HELPER_CONFIG = Path('/etc/rmm-discovery-managed-scripts')
MAX_BINARY = 256 * 1024 * 1024 MAX_BINARY = 256 * 1024 * 1024
UNIT_DIR = Path('/etc/systemd/system') UNIT_DIR = Path('/etc/systemd/system')
@@ -36,6 +41,13 @@ def require(condition, message):
raise ValueError(message) raise ValueError(message)
def release_platform():
machine = platform.machine()
require(platform.system() == 'Linux' and machine in ('x86_64', 'aarch64'),
'Linux x86-64 or ARM64 required')
return machine + '-unknown-linux-gnu'
def origin(value): def origin(value):
parsed = urlsplit(value) parsed = urlsplit(value)
require(parsed.scheme == 'https' and parsed.hostname and parsed.username is None require(parsed.scheme == 'https' and parsed.hostname and parsed.username is None
@@ -145,7 +157,9 @@ def pair(folder, doc, source, updater):
manifest = doc['manifest'] manifest = doc['manifest']
release_id = canonical_id(manifest['release_id']) release_id = canonical_id(manifest['release_id'])
prefix = '/agent/v1/bootstrap/releases' if source else '/agent/v1/releases' prefix = '/agent/v1/bootstrap/releases' if source else '/agent/v1/releases'
suffix = '?platform=' + PLATFORM if source else '' target = release_platform()
require(manifest['platform'] == target, 'release architecture differs from this device')
suffix = '?platform=' + target if source else ''
save(folder / 'envelope.json', doc['release_envelope']) save(folder / 'envelope.json', doc['release_envelope'])
for artifact, role in zip(manifest['artifacts'], ('agent', 'helper'), strict=True): for artifact, role in zip(manifest['artifacts'], ('agent', 'helper'), strict=True):
require(artifact['role'] == role, 'incorrect artifact role') require(artifact['role'] == role, 'incorrect artifact role')
@@ -177,10 +191,15 @@ def installed():
return json.loads(as_device('fetch', '/agent/v1/releases/installed', stdout=subprocess.PIPE).stdout) return json.loads(as_device('fetch', '/agent/v1/releases/installed', stdout=subprocess.PIPE).stdout)
def healthy(version, baseline, duration=90): def healthy(version, baseline, duration=90, pin=None):
until = time.monotonic() + duration until = time.monotonic() + duration
started = time.time() started = time.time()
certificate_pointer = STATE / 'certificates/current.json'
while time.monotonic() < until: while time.monotonic() < until:
# The agent writes this pointer after obtaining its first device certificate.
if not certificate_pointer.is_file():
time.sleep(2)
continue
try: try:
record = installed() record = installed()
contact = record.get('last_contact_at') contact = record.get('last_contact_at')
@@ -188,6 +207,8 @@ def healthy(version, baseline, duration=90):
recent = datetime.datetime.fromisoformat(contact.replace('Z', '+00:00')).timestamp() recent = datetime.datetime.fromisoformat(contact.replace('Z', '+00:00')).timestamp()
if (started - 1 <= recent <= time.time() + 10 and record['agent_version'] == version if (started - 1 <= recent <= time.time() + 10 and record['agent_version'] == version
and record['connection_generation'] > baseline and record['connection_generation'] > baseline
and (pin is None or {'root:run_script', 'helper.policy.sha256:' + pin['policy_sha256'],
'helper.binary.sha256:' + pin['helper_binary_sha256']}.issubset(record['capabilities']))
and subprocess.run(['systemctl', 'is-active', '--quiet', SERVICE], timeout=10).returncode == 0): and subprocess.run(['systemctl', 'is-active', '--quiet', SERVICE], timeout=10).returncode == 0):
return True return True
except (subprocess.SubprocessError, ValueError, OSError): except (subprocess.SubprocessError, ValueError, OSError):
@@ -200,6 +221,212 @@ def service(*args):
subprocess.run(['systemctl', *args], check=True, timeout=60) subprocess.run(['systemctl', *args], check=True, timeout=60)
def active_folder():
release = canonical_id(read(ROOT / 'current/manifest.json')['release_id'])
folder = ROOT / 'releases' / release
require((ROOT / 'current').resolve(strict=True) == folder and folder.resolve() == folder,
'unexpected active generation path')
return folder
@contextlib.contextmanager
def account_file(path, uid):
# Open only a checked inode a second time for TLS. No privileged open of a
# device or FIFO, and no path re-resolution after validation.
fd = os.open(path, os.O_PATH | os.O_NOFOLLOW)
try:
info = os.fstat(fd)
require(stat.S_ISREG(info.st_mode) and info.st_uid == uid and info.st_nlink == 1
and info.st_mode & 0o077 == 0 and 0 < info.st_size <= 65536,
'device credential metadata differs')
yield Path('/proc/self/fd') / str(fd)
finally:
os.close(fd)
def script_binding(account):
# The root helper trusts only the signing key from the original HTTPS
# bootstrap and the binding returned by the authenticated device gateway.
boot = read(ROOT / 'bootstrap.json')
certs = STATE / 'certificates'
with account_file(certs / 'current.json', account.pw_uid) as selector:
version = canonical_id(read(selector)['version'])
creds = certs / 'versions' / version
context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
context.load_verify_locations(cafile=str(ROOT / 'gateway-ca.pem'))
with (account_file(creds / 'device.pem', account.pw_uid) as cert,
account_file(creds / 'device.key', account.pw_uid) as key):
context.load_cert_chain(str(cert), str(key))
response = io.BytesIO()
conf = read(ROOT / 'config.json')
retrieve(conf['gateway'], '/agent/v1/releases/installed', response, context=context)
own = json.loads(response.getvalue())
public_key = boot.get('job_signing_public_key_hex')
if public_key is None:
trust = io.BytesIO()
retrieve(conf['gateway'], '/agent/v1/releases/device-trust', trust, context=context)
public_key = json.loads(trust.getvalue())['job_signing_public_key_hex']
require(re.fullmatch('[0-9a-f]{64}', public_key), 'invalid job signing key')
require(own['tenant_id'] == conf['tenant'] == boot['tenant_id'], 'device binding tenant mismatch')
binding = {field: canonical_id(own[field]) for field in ('tenant_id', 'asset_id', 'agent_id')}
for field in ('enrollment_generation', 'assignment_version'):
require(type(own[field]) is int and own[field] > 0, 'invalid device generation')
binding[field] = own[field]
binding['public_key_hex'] = public_key
return binding
def script_settings(binding, account, digest):
return dict(profile='full_maintenance_v1', binding=binding, agent_uid=account.pw_uid,
socket_gid=account.pw_gid, socket=str(HELPER_SOCKET), state='/var/lib/rmm-discovery-helper',
allowed_services=[], allow_reboot=False, allow_root_scripts=True,
allowed_script_profiles=['full_maintenance_v1'], helper_binary_sha256=digest)
def prepare_script_helper(folder, binding, account):
manifest = json.loads(subprocess.check_output([
ROOT / 'updater', '--verify-bootstrap', ROOT / 'keyring.json', folder / 'envelope.json',
folder / 'agent', folder / 'helper'], timeout=120))
require(manifest == read(folder / 'manifest.json') and manifest['release_id'] == folder.name,
'helper generation differs from signed release')
digest = next(a['sha256'] for a in manifest['artifacts'] if a['role'] == 'helper')
settings = script_settings(binding, account, digest)
config = folder / 'script-helper.json'
if config.exists():
require(read(config) == settings, 'installed helper binding changed')
else:
save(config, settings, 0o600)
raw = subprocess.check_output([folder / 'helper', '--inspect-full-maintenance-profile'],
env={'PATH': '/usr/bin:/bin', 'RMM_HELPER_CONFIG': str(config)}, timeout=30)
pin = json.loads(raw)
require(pin['helper_binary_sha256'] == digest and re.fullmatch('[0-9a-f]{64}', pin['policy_sha256']),
'helper pin differs from signed release')
save(folder / 'script-pin.json', raw)
return pin
def helper_unit(executable, config=None):
command = f'Environment=RMM_HELPER_CONFIG={config}\n' if config else ''
return f"""[Unit]
Description=Rust Discovery helper for approved root scripts
After=time-sync.target
[Service]
User=root
Group=rmm-discovery
StateDirectory=rmm-discovery-helper
StateDirectoryMode=0700
RuntimeDirectory=rmm-discovery-script-helper
RuntimeDirectoryMode=0750
UMask=0077
{command}ExecStart={executable}
Restart=on-failure
RestartSec=5
[Install]
WantedBy=multi-user.target
""".encode()
def helper_unit_files(binding, account):
unit = UNIT_DIR / HELPER
dropdir = UNIT_DIR / (SERVICE + '.d')
dropdir.mkdir(mode=0o755, exist_ok=True)
require(not dropdir.is_symlink() and not dropdir.stat().st_mode & 0o022, 'unsafe service drop-in directory')
drop = dropdir / '50-managed-scripts.conf'
order = f'[Unit]\nAfter={HELPER}\n'.encode()
old_order = (f'[Unit]\nWants={HELPER}\nAfter={HELPER}\n'
f'\n[Service]\nEnvironment=RMM_FULL_MAINTENANCE_HELPER_SOCKET={HELPER_SOCKET}\n'
f'Environment=RMM_FULL_MAINTENANCE_POLICY_FILE={OLD_HELPER_CONFIG}/agent-pin.json\n').encode()
changed = []
for path, desired in (
(unit, helper_unit(f'/usr/bin/python3 -I {ROOT}/lifecycle.py run-helper')),
(drop, order),
):
if path.is_symlink():
raise ValueError('unexpected systemd symlink: ' + str(path))
if path.exists():
current = path.read_bytes()
if current == desired:
continue
old = old_order
if path == unit:
exe = re.search(rb'^ExecStart=(.+)$', current, re.M)
require(exe is not None, 'unrecognized helper service')
candidate = Path(os.fsdecode(exe[1]))
require(candidate == ROOT / 'releases' / canonical_id(candidate.parent.name) / 'helper',
'unexpected legacy helper image')
private = OLD_HELPER_CONFIG / 'helper.json'
old = helper_unit(candidate, private)
settings = read(private)
require(settings == script_settings(binding, account, settings['helper_binary_sha256']),
'existing helper belongs to a different binding or profile')
require(current == old, 'unrecognized managed service file: ' + str(path))
changed.append((path, desired))
return changed
def start_pair():
service('start', HELPER)
until = time.monotonic() + 15
while not HELPER_SOCKET.is_socket():
require(time.monotonic() < until, 'script helper socket unavailable')
time.sleep(.2)
service('start', SERVICE)
def helper_state():
probe = subprocess.run(['systemctl', 'is-enabled', HELPER], stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL, text=True, timeout=10)
return probe.stdout.strip()
def provision_scripts(enable_admin_scripts):
with (ROOT / 'release.lock').open('rb') as lock:
fcntl.flock(lock, fcntl.LOCK_EX)
pending = ROOT / 'pending.json'
if pending.exists():
revert(read(pending))
folder = active_folder()
intent = ROOT / 'script-helper-installing.json'
state = helper_state()
known = (UNIT_DIR / HELPER).exists() or OLD_HELPER_CONFIG.exists() or (folder / 'script-helper.json').exists()
if state != 'enabled':
new = enable_admin_scripts and not known and state in ('', 'not-found')
resume = (enable_admin_scripts and intent.is_file() and read(intent) == folder.name
and state in ('', 'not-found', 'disabled'))
if not (new or resume):
print('Keeping the local script helper activation policy: ' + (state or 'not installed'), file=sys.stderr)
return
else:
require((UNIT_DIR / HELPER).is_file(), 'refusing to replace an externally managed helper unit')
require(as_device('idle', stdout=subprocess.PIPE).stdout.strip() == b'idle', 'active job prevents helper switch')
account = pwd.getpwnam('rmm-discovery')
require(account.pw_uid > 0 and account.pw_gid > 0, 'dedicated service account required')
binding = script_binding(account)
changed = helper_unit_files(binding, account)
if state != 'enabled':
save(intent, folder.name)
pin = prepare_script_helper(folder, binding, account)
observed = installed()
if (not changed and 'root:run_script' in observed['capabilities']
and 'helper.binary.sha256:' + pin['helper_binary_sha256'] in observed['capabilities']
and 'helper.policy.sha256:' + pin['policy_sha256'] in observed['capabilities']):
intent.unlink(missing_ok=True)
return
service('stop', SERVICE)
if (UNIT_DIR / HELPER).exists():
service('stop', HELPER)
for path, raw in changed:
save(path, raw)
service('daemon-reload')
service('enable', HELPER)
start_pair()
require(healthy(read(folder / 'manifest.json')['version'], observed['connection_generation'], pin=pin),
'device has not confirmed the script helper')
intent.unlink(missing_ok=True)
def units(): def units():
program = '/usr/bin/python3 -I ' + str(ROOT / 'lifecycle.py') program = '/usr/bin/python3 -I ' + str(ROOT / 'lifecycle.py')
return { return {
@@ -243,6 +470,30 @@ WantedBy=timers.target
} }
def provision_serial_credential():
# DMI serial files usually require root. Pass this one value to the agent
# through systemd's read-only per-service credentials directory.
source = Path('/sys/class/dmi/id/product_serial')
try:
with source.open('rb') as stream:
serial = stream.read(256).strip()
except OSError:
return
if not serial or len(serial) >= 255:
return
target = ROOT / 'bios-serial'
dropin = UNIT_DIR / (SERVICE + '.d') / '40-inventory-serial.conf'
content = f'[Service]\nLoadCredential=rmm-bios-serial:{target}\n'.encode()
require(not dropin.parent.is_symlink(), 'hardware credential directory conflict')
if dropin.exists() or dropin.is_symlink():
require(not dropin.is_symlink() and dropin.read_bytes() == content, 'hardware credential configuration conflict')
else:
dropin.parent.mkdir(mode=0o755, exist_ok=True)
save(target, serial, 0o600)
if not dropin.exists():
save(dropin, content)
def enable(): def enable():
for name, data in units().items(): for name, data in units().items():
path = UNIT_DIR / name path = UNIT_DIR / name
@@ -250,6 +501,7 @@ def enable():
require(path.read_bytes() == data.encode(), 'service file conflict: ' + name) require(path.read_bytes() == data.encode(), 'service file conflict: ' + name)
else: else:
save(path, data.encode()) save(path, data.encode())
provision_serial_credential()
service('daemon-reload') service('daemon-reload')
service('enable', '--now', SERVICE) service('enable', '--now', SERVICE)
@@ -266,8 +518,8 @@ def save_token(base, token, gid):
os.chown(path, 0, gid) os.chown(path, 0, gid)
def install(base, token_file): def install(base, token_file, enable_admin_scripts=False):
require(platform.machine() == 'x86_64', 'Linux x86-64 required') target = release_platform()
base = origin(base) base = origin(base)
if ROOT.exists(): if ROOT.exists():
config = read(ROOT / 'config.json') config = read(ROOT / 'config.json')
@@ -277,7 +529,7 @@ def install(base, token_file):
token = enrollment_token(token_file) token = enrollment_token(token_file)
with tempfile.TemporaryDirectory() as work: with tempfile.TemporaryDirectory() as work:
metadata = Path(work) / 'bootstrap.json' metadata = Path(work) / 'bootstrap.json'
remote((base, token), '/agent/v1/bootstrap/current?platform=' + PLATFORM, metadata) remote((base, token), '/agent/v1/bootstrap/current?platform=' + target, metadata)
require(read(metadata)['tenant_id'] == config['tenant'], 'different enrollment tenant') require(read(metadata)['tenant_id'] == config['tenant'], 'different enrollment tenant')
save_token(ROOT, token, pwd.getpwnam('rmm-discovery').pw_gid) save_token(ROOT, token, pwd.getpwnam('rmm-discovery').pw_gid)
# An operator rerunning the HTTPS installer can update the lifecycle # An operator rerunning the HTTPS installer can update the lifecycle
@@ -288,8 +540,12 @@ def install(base, token_file):
current = Path(__file__).read_bytes() current = Path(__file__).read_bytes()
if harness.read_bytes() != current: if harness.read_bytes() != current:
save(harness, current) save(harness, current)
pending = ROOT / 'pending.json'
if pending.exists():
revert(read(pending), report_failure=False)
enable() enable()
require(healthy(read(ROOT / 'current/manifest.json')['version'], 0), 'awaiting authenticated device heartbeat') require(healthy(read(ROOT / 'current/manifest.json')['version'], 0), 'awaiting authenticated device heartbeat')
provision_scripts(enable_admin_scripts)
service('enable', '--now', TIMER) service('enable', '--now', TIMER)
(ROOT / 'first.token').unlink(missing_ok=True) (ROOT / 'first.token').unlink(missing_ok=True)
return return
@@ -306,7 +562,7 @@ def install(base, token_file):
with tempfile.TemporaryDirectory(prefix='.rmm-', dir=ROOT.parent) as work: with tempfile.TemporaryDirectory(prefix='.rmm-', dir=ROOT.parent) as work:
staging = Path(work) / 'installation' staging = Path(work) / 'installation'
staging.mkdir() staging.mkdir()
remote((base, token), '/agent/v1/bootstrap/current?platform=' + PLATFORM, staging / 'bootstrap.json') remote((base, token), '/agent/v1/bootstrap/current?platform=' + target, staging / 'bootstrap.json')
doc = read(staging / 'bootstrap.json') doc = read(staging / 'bootstrap.json')
require(doc['schema_version'] == 1, 'unknown bootstrap profile') require(doc['schema_version'] == 1, 'unknown bootstrap profile')
save(staging / 'keyring.json', doc['keyring']) save(staging / 'keyring.json', doc['keyring'])
@@ -314,7 +570,7 @@ def install(base, token_file):
save(staging / 'config.json', {'bootstrap': base, 'gateway': origin(doc['gateway_origin']), save(staging / 'config.json', {'bootstrap': base, 'gateway': origin(doc['gateway_origin']),
'tenant': canonical_id(doc['tenant_id'])}) 'tenant': canonical_id(doc['tenant_id'])})
updater = staging / 'updater' updater = staging / 'updater'
remote((base, token), '/agent/v1/bootstrap/updater?platform=' + PLATFORM + '&sha256=' + doc['updater']['sha256'], updater, doc['updater']) remote((base, token), '/agent/v1/bootstrap/updater?platform=' + target + '&sha256=' + doc['updater']['sha256'], updater, doc['updater'])
updater.chmod(0o755) updater.chmod(0o755)
releases = staging / 'releases' releases = staging / 'releases'
releases.mkdir() releases.mkdir()
@@ -330,6 +586,7 @@ def install(base, token_file):
os.rename(staging, ROOT) os.rename(staging, ROOT)
enable() enable()
require(healthy(manifest['version'], 0), 'installed, awaiting authenticated device heartbeat') require(healthy(manifest['version'], 0), 'installed, awaiting authenticated device heartbeat')
provision_scripts(enable_admin_scripts)
# OnBootSec may already be in the past on a running machine. The first # 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. # timer check can run immediately once the device has reported its platform.
service('enable', '--now', TIMER) service('enable', '--now', TIMER)
@@ -349,20 +606,38 @@ def run_agent():
RMM_ENROLLMENT_TENANT=conf['tenant'], RMM_JOB_SIGNING_KEY_BOOTSTRAP='1', RMM_ENROLLMENT_TENANT=conf['tenant'], RMM_JOB_SIGNING_KEY_BOOTSTRAP='1',
RMM_RELEASE_LOCK=str(ROOT / 'release.lock'), RMM_RELEASE_LOCK=str(ROOT / 'release.lock'),
RMM_INSTALLED_RELEASE_VERSION=read(ROOT / 'current/manifest.json')['version']) RMM_INSTALLED_RELEASE_VERSION=read(ROOT / 'current/manifest.json')['version'])
exe = str(ROOT / 'current/agent') folder = active_folder()
os.environ.pop('RMM_SCRIPT_HELPER_RELEASE', None)
if (folder / 'script-pin.json').is_file() and helper_state() in ('enabled', 'enabled-runtime'):
pins = {'RMM_FULL_MAINTENANCE_HELPER_SOCKET': str(HELPER_SOCKET),
'RMM_FULL_MAINTENANCE_POLICY_FILE': str(folder / 'script-pin.json')}
if all(os.environ.get(name, value) == value for name, value in pins.items()):
os.environ.update(pins, RMM_SCRIPT_HELPER_RELEASE=folder.name)
exe = str(folder / 'agent')
os.execv(exe, [exe]) os.execv(exe, [exe])
def revert(intent): def revert(intent, report_failure=True):
# Persist failed sequence before restoring. An interruption re-enters recovery. # Persist failed sequence before restoring. An interruption re-enters recovery.
save(ROOT / 'failed.json', {'release_sequence': intent['sequence'], 'reason': 'activation_unconfirmed'}) save(ROOT / 'failed.json', {'release_sequence': intent['sequence'], 'reason': 'activation_unconfirmed'})
enabled = intent.get('script_helper') and helper_state() in ('enabled', 'enabled-runtime')
if intent.get('script_helper'):
service('stop', SERVICE, HELPER)
link(ROOT, intent['previous']) link(ROOT, intent['previous'])
service('restart', SERVICE) if enabled:
start_pair()
previous = active_folder()
require(healthy(read(previous / 'manifest.json')['version'], 0, pin=read(previous / 'script-pin.json')),
'predecessor has not yet confirmed the previous script helper')
else:
service('restart', SERVICE)
(ROOT / 'pending.json').unlink() (ROOT / 'pending.json').unlink()
raise RuntimeError('release activation unconfirmed; predecessor selected') if report_failure:
raise RuntimeError('release activation unconfirmed; predecessor selected')
def update(): def update():
target = release_platform()
with (ROOT / 'release.lock').open('rb') as lock: with (ROOT / 'release.lock').open('rb') as lock:
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
pending = ROOT / 'pending.json' pending = ROOT / 'pending.json'
@@ -372,7 +647,7 @@ def update():
with tempfile.TemporaryDirectory(prefix='.incoming-', dir=ROOT / 'releases') as work: with tempfile.TemporaryDirectory(prefix='.incoming-', dir=ROOT / 'releases') as work:
staging = Path(work) / 'generation' staging = Path(work) / 'generation'
staging.mkdir() staging.mkdir()
remote(None, '/agent/v1/releases/current?platform=' + PLATFORM, staging / 'current.json') remote(None, '/agent/v1/releases/current?platform=' + target, staging / 'current.json')
response = read(staging / 'current.json') response = read(staging / 'current.json')
if response['status'] == 'not_configured': if response['status'] == 'not_configured':
return return
@@ -401,10 +676,28 @@ def update():
(staging / 'current.json').unlink() (staging / 'current.json').unlink()
os.rename(staging, dest) os.rename(staging, dest)
intent = {'previous': active['release_id'], 'sequence': manifest['release_sequence']} intent = {'previous': active['release_id'], 'sequence': manifest['release_sequence']}
active_config = active_folder() / 'script-helper.json'
pin = None
if active_config.exists() and helper_state() in ('enabled', 'enabled-runtime'):
settings = read(active_config)
account = pwd.getpwnam('rmm-discovery')
active_hash = next(a['sha256'] for a in active['artifacts'] if a['role'] == 'helper')
require(settings == script_settings(settings['binding'], account, active_hash),
'existing script helper policy changed')
pin = prepare_script_helper(dest, settings['binding'], account)
intent['script_helper'] = True
save(pending, intent) save(pending, intent)
link(ROOT, release) try:
service('restart', SERVICE) if pin:
if not healthy(manifest['version'], previous_health['connection_generation']): service('stop', SERVICE, HELPER)
link(ROOT, release)
if pin:
start_pair()
else:
service('restart', SERVICE)
except (OSError, ValueError, subprocess.SubprocessError):
revert(intent)
if not healthy(manifest['version'], previous_health['connection_generation'], pin=pin):
revert(intent) revert(intent)
pending.unlink() pending.unlink()
(ROOT / 'first.token').unlink(missing_ok=True) (ROOT / 'first.token').unlink(missing_ok=True)
@@ -412,18 +705,25 @@ def update():
def main(): def main():
parser = argparse.ArgumentParser(description=__doc__) parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('action', choices=('install', 'update', 'run-agent', 'fetch', 'idle')) parser.add_argument('action', choices=('install', 'update', 'run-agent', 'run-helper', 'fetch', 'idle'))
parser.add_argument('values', nargs='*') parser.add_argument('values', nargs='*')
parser.add_argument('--token-file') parser.add_argument('--token-file')
parser.add_argument('--enable-admin-scripts', action='store_true',
help='enable this enrolled device to run individually approved root scripts')
args = parser.parse_args() args = parser.parse_args()
if args.action in ('install', 'update'): if args.action in ('install', 'update'):
require(os.geteuid() == 0, 'administrative installation required') require(os.geteuid() == 0, 'administrative installation required')
os.umask(0o022) os.umask(0o022)
if args.action == 'install': if args.action == 'install':
require(len(args.values) == 1, 'one HTTPS bootstrap origin required') require(len(args.values) == 1, 'one HTTPS bootstrap origin required')
install(args.values[0], args.token_file) install(args.values[0], args.token_file, args.enable_admin_scripts)
elif args.action == 'update': elif args.action == 'update':
update() update()
elif args.action == 'run-helper':
require(os.geteuid() == 0, 'privileged script helper service required')
folder = active_folder()
os.environ.setdefault('RMM_HELPER_CONFIG', str(folder / 'script-helper.json'))
os.execv(folder / 'helper', [str(folder / 'helper')])
elif args.action == 'run-agent': elif args.action == 'run-agent':
run_agent() run_agent()
elif args.action == 'fetch': elif args.action == 'fetch':
+8 -2
View File
@@ -23,9 +23,15 @@ struct TenantPins { current: Pin, previous: Vec<Previous> }
#[serde(deny_unknown_fields)] #[serde(deny_unknown_fields)]
pub(super) struct UpdaterQuery { platform: Platform, sha256: Option<String> } pub(super) struct UpdaterQuery { platform: Platform, sha256: Option<String> }
fn official_windows(platform: Platform) -> bool {
platform == Platform::WindowsGnuX64
&& std::env::var_os("RMM_AGENT_UPDATE_WINDOWS_GNU_OFFICIAL_KEYRING_FILE").is_some()
}
async fn config(s: &crate::State, platform: Platform, tenant: Uuid, wanted: Option<&str>) -> Result<Config, Error> { async fn config(s: &crate::State, platform: Platform, tenant: Uuid, wanted: Option<&str>) -> Result<Config, Error> {
let slot = match platform { let slot = match platform {
Platform::LinuxX64 => "RMM_AGENT_BOOTSTRAP_LINUX_FILE", Platform::LinuxX64 => "RMM_AGENT_BOOTSTRAP_LINUX_FILE",
Platform::LinuxArm64 => "RMM_AGENT_BOOTSTRAP_LINUX_ARM64_FILE",
Platform::WindowsX64 => "RMM_AGENT_BOOTSTRAP_WINDOWS_FILE", Platform::WindowsX64 => "RMM_AGENT_BOOTSTRAP_WINDOWS_FILE",
Platform::WindowsGnuX64 => "RMM_AGENT_BOOTSTRAP_WINDOWS_GNU_FILE", Platform::WindowsGnuX64 => "RMM_AGENT_BOOTSTRAP_WINDOWS_GNU_FILE",
}; };
@@ -45,8 +51,8 @@ async fn config(s: &crate::State, platform: Platform, tenant: Uuid, wanted: Opti
config.updater_bytes = selected.bytes; config.updater_bytes = selected.bytes;
} else { } else {
let mut tx = rmm_persistence::tenant_tx(&s.pool, tenant).await?; let mut tx = rmm_persistence::tenant_tx(&s.pool, tenant).await?;
let pin = sqlx::query("SELECT sha256,size_bytes FROM customer_starter_workers WHERE platform=$1") let pin = sqlx::query("SELECT sha256,size_bytes FROM customer_starter_workers WHERE platform=$1 AND official_windows=$2")
.bind(platform_name(platform)).fetch_optional(&mut *tx).await?; .bind(platform_name(platform)).bind(official_windows(platform)).fetch_optional(&mut *tx).await?;
tx.commit().await?; tx.commit().await?;
if let Some(pin) = pin { if let Some(pin) = pin {
config.updater_sha256 = pin.get("sha256"); config.updater_sha256 = pin.get("sha256");
+12 -4
View File
@@ -14,7 +14,9 @@ pub(super) async fn publish_missing(
tx: &mut Transaction<'_, Postgres>, tx: &mut Transaction<'_, Postgres>,
tenant: Uuid, tenant: Uuid,
) -> Result<(), Error> { ) -> Result<(), Error> {
let Some(slot) = std::env::var_os("RMM_AGENT_BOOTSTRAP_LINUX_FILE") else { let Some(slot) = std::env::var_os("RMM_AGENT_BOOTSTRAP_LINUX_FILE")
.or_else(|| std::env::var_os("RMM_AGENT_BOOTSTRAP_LINUX_ARM64_FILE"))
else {
return Ok(()); return Ok(());
}; };
let Some(config_dir) = FsPath::new(&slot).parent() else { let Some(config_dir) = FsPath::new(&slot).parent() else {
@@ -29,6 +31,7 @@ pub(super) async fn publish_missing(
} }
for platform in [ for platform in [
Platform::LinuxX64, Platform::LinuxX64,
Platform::LinuxArm64,
Platform::WindowsGnuX64, Platform::WindowsGnuX64,
Platform::WindowsX64, Platform::WindowsX64,
] { ] {
@@ -42,7 +45,11 @@ pub(super) async fn publish_missing(
if exists { if exists {
continue; continue;
} }
let path = distribution.join(format!("{name}.json")); let path = if official_windows(platform) {
distribution.join(format!("{name}-official.json"))
} else {
distribution.join(format!("{name}.json"))
};
if !path if !path
.try_exists() .try_exists()
.map_err(|_| fail("STARTER_CONFIGURATION"))? .map_err(|_| fail("STARTER_CONFIGURATION"))?
@@ -64,7 +71,7 @@ pub(super) async fn publish_missing(
continue; continue;
} }
let package: Starter = serde_json::from_slice(&protected_file(&path, 65536)?)?; let package: Starter = serde_json::from_slice(&protected_file(&path, 65536)?)?;
let manifest = verify_signed_envelope(&package.envelope, platform, None)?; let manifest = verify_envelope(&package.envelope, None)?;
if manifest.platform != platform { if manifest.platform != platform {
return Err(invalid()); return Err(invalid());
} }
@@ -129,11 +136,12 @@ pub(super) async fn publish_missing(
.bind(tenant).bind(manifest.release_id).bind(name).bind(i64::try_from(manifest.release_sequence).map_err(|_|invalid())?) .bind(tenant).bind(manifest.release_id).bind(name).bind(i64::try_from(manifest.release_sequence).map_err(|_|invalid())?)
.bind(hash(&package.envelope.decode().map_err(|_|invalid())?.payload_bytes)).bind(hash(&raw)).bind(raw) .bind(hash(&package.envelope.decode().map_err(|_|invalid())?.payload_bytes)).bind(hash(&raw)).bind(raw)
.bind(a.artifact_id).bind(&a.sha256).bind(a.bytes as i64).bind(h.artifact_id).bind(&h.sha256).bind(h.bytes as i64).execute(&mut **tx).await?; .bind(a.artifact_id).bind(&a.sha256).bind(a.bytes as i64).bind(h.artifact_id).bind(&h.sha256).bind(h.bytes as i64).execute(&mut **tx).await?;
sqlx::query("INSERT INTO customer_starter_workers VALUES($1,$2,$3,$4)") sqlx::query("INSERT INTO customer_starter_workers(tenant_id,platform,sha256,size_bytes,official_windows) VALUES($1,$2,$3,$4,$5)")
.bind(tenant) .bind(tenant)
.bind(name) .bind(name)
.bind(package.worker.sha256) .bind(package.worker.sha256)
.bind(package.worker.bytes as i64) .bind(package.worker.bytes as i64)
.bind(official_windows(platform))
.execute(&mut **tx) .execute(&mut **tx)
.await?; .await?;
} }
+64 -6
View File
@@ -1,9 +1,9 @@
use crate::jobs::Error; use crate::jobs::Error;
use axum::{ use axum::{
Json, Router, Json, Router,
extract::{Path, State}, extract::{Path, Query, State},
http::{HeaderMap, StatusCode}, http::{HeaderMap, StatusCode},
routing::post, routing::{delete, post},
}; };
use serde::Deserialize; use serde::Deserialize;
use serde_json::{Value, json}; use serde_json::{Value, json};
@@ -25,6 +25,7 @@ pub fn routes(r: Router<crate::State>) -> Router<crate::State> {
"/api/v1/tenants/{tenant}/devices/{asset}/revocation", "/api/v1/tenants/{tenant}/devices/{asset}/revocation",
post(revoke_device), post(revoke_device),
) )
.route("/api/v1/tenants/{tenant}/devices/{asset}", delete(remove_device))
.route( .route(
"/api/v1/tenants/{tenant}/devices/{asset}/archive", "/api/v1/tenants/{tenant}/devices/{asset}/archive",
post(archive_device), post(archive_device),
@@ -33,7 +34,34 @@ pub fn routes(r: Router<crate::State>) -> Router<crate::State> {
"/api/v1/tenants/{tenant}/operation-plans/{plan}/revocation", "/api/v1/tenants/{tenant}/operation-plans/{plan}/revocation",
post(revoke_plan), post(revoke_plan),
) )
.route("/api/v1/tenants/{tenant}/execution-stop", post(stop)) .route(
"/api/v1/tenants/{tenant}/execution-stop",
post(stop).get(stop_status),
)
}
async fn stop_status(
State(s): State<crate::State>,
h: HeaderMap,
Path(tenant): Path<Uuid>,
) -> Result<Json<Value>, Error> {
let principal = crate::jobs::principal(&s, &h, false).await?;
crate::jobs::scope(&principal, tenant, false)?;
if principal.session_hash.is_none() {
return Err(Error(StatusCode::FORBIDDEN, "INTERACTIVE_AUTH_REQUIRED"));
}
let mut tx = rmm_persistence::tenant_tx(&s.pool, tenant).await?;
if !principal.permits_scope("operations:read")
|| !crate::permissions::allowed(&mut tx, &principal.name, "operations:read").await?
{
crate::permissions::require_principal(&mut tx, &principal, "tenant:stop").await?;
}
let stopped: bool = sqlx::query_scalar("SELECT changes_stopped FROM tenants WHERE tenant_id=$1")
.bind(tenant)
.fetch_optional(&mut *tx)
.await?
.ok_or(Error(StatusCode::NOT_FOUND, "NOT_FOUND"))?;
tx.commit().await?;
Ok(Json(json!({"tenant_id":tenant,"changes_stopped":stopped})))
} }
async fn context<'a>( async fn context<'a>(
s: &'a crate::State, s: &'a crate::State,
@@ -100,23 +128,53 @@ async fn archive_device(
tx.commit().await?; tx.commit().await?;
Ok(Json(json!({"asset_id":asset, "archived":input.archived}))) Ok(Json(json!({"asset_id":asset, "archived":input.archived})))
} }
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Pairing {
agent_id: Uuid,
}
async fn remove_device(
State(s): State<crate::State>,
h: HeaderMap,
Path((tenant, asset)): Path<(Uuid, Uuid)>,
Query(pairing): Query<Pairing>,
) -> Result<StatusCode, Error> {
let (p, mut tx) = context(&s, &h, tenant, "devices:revoke", "device_deleted").await?;
let status: String = sqlx::query_scalar("SELECT remove_revoked_device($1,$2,$3,$4)")
.bind(tenant).bind(asset).bind(pairing.agent_id).bind(&p.name)
.fetch_one(&mut *tx).await?;
match status.as_str() {
"deleted" => audit(&mut tx, &p, "device_deleted",
json!({"asset_id":asset, "agent_id":pairing.agent_id})).await?,
"absent" => (),
"active" => return Err(Error(StatusCode::CONFLICT, "DEVICE_REVOCATION_REQUIRED")),
"busy" => return Err(Error(StatusCode::CONFLICT, "DEVICE_HAS_OPEN_WORK")),
"forbidden" => return Err(Error(StatusCode::FORBIDDEN, "FORBIDDEN")),
_ => return Err(Error(StatusCode::INTERNAL_SERVER_ERROR, "DEVICE_DELETION_FAILED")),
}
tx.commit().await?;
Ok(StatusCode::NO_CONTENT)
}
pub async fn revoke_device( pub async fn revoke_device(
State(s): State<crate::State>, State(s): State<crate::State>,
h: HeaderMap, h: HeaderMap,
Path((t, asset)): Path<(Uuid, Uuid)>, Path((t, asset)): Path<(Uuid, Uuid)>,
Query(selection): Query<crate::devices::DetailQuery>,
Json(i): Json<Reason>, Json(i): Json<Reason>,
) -> Result<Json<Value>, Error> { ) -> Result<Json<Value>, Error> {
let (p, mut tx) = context(&s, &h, t, "devices:revoke", &i.reason).await?; let (p, mut tx) = context(&s, &h, t, "devices:revoke", &i.reason).await?;
let n=sqlx::query("UPDATE agent_installations SET revoked_at=COALESCE(revoked_at,now()),connection_generation=connection_generation+1,previous_certificate_sha256=NULL,previous_certificate_until=NULL WHERE asset_id=$1").bind(asset).execute(&mut *tx).await?.rows_affected(); let n=sqlx::query("UPDATE agent_installations SET revoked_at=COALESCE(revoked_at,now()),connection_generation=connection_generation+1,previous_certificate_sha256=NULL,previous_certificate_until=NULL WHERE asset_id=$1 AND ($2::uuid IS NULL OR agent_id=$2)").bind(asset).bind(selection.agent_id).execute(&mut *tx).await?.rows_affected();
if n == 0 { if n == 0 {
return Err(Error(StatusCode::NOT_FOUND, "NOT_FOUND")); return Err(Error(StatusCode::NOT_FOUND, "NOT_FOUND"));
} }
sqlx::query("UPDATE jobs SET cancel_requested=true WHERE asset_id=$1 AND state NOT IN ('succeeded','failed','cancelled','expired','closed_unknown')").bind(asset).execute(&mut *tx).await?; sqlx::query("UPDATE jobs SET cancel_requested=true WHERE asset_id=$1 AND ($2::uuid IS NULL OR agent_id=$2) AND state NOT IN ('succeeded','failed','cancelled','expired','closed_unknown')").bind(asset).bind(selection.agent_id).execute(&mut *tx).await?;
audit( audit(
&mut tx, &mut tx,
&p, &p,
"device_revoked", "device_revoked",
json!({"asset_id":asset,"reason":i.reason}), json!({"asset_id":asset,"agent_id":selection.agent_id,"reason":i.reason}),
) )
.await?; .await?;
tx.commit().await?; tx.commit().await?;
+1
View File
@@ -2,6 +2,7 @@ WITH classified AS (
SELECT a.tenant_id,a.asset_id,a.agent_id,a.created_at,a.revoked_at,a.last_contact_at, SELECT a.tenant_id,a.asset_id,a.agent_id,a.created_at,a.revoked_at,a.last_contact_at,
a.last_authenticated_at,a.last_authenticated_certificate_sha256,a.certificate_sha256, a.last_authenticated_at,a.last_authenticated_certificate_sha256,a.certificate_sha256,
a.enrollment_generation,a.assignment_version,a.capabilities,a.reported_agent_version, a.enrollment_generation,a.assignment_version,a.capabilities,a.reported_agent_version,
a.system_usage,a.system_usage_observed_at,
asset.archived_at,t.name AS customer_name, asset.archived_at,t.name AS customer_name,
CASE CASE
WHEN a.revoked_at IS NOT NULL THEN 'revoked' WHEN a.revoked_at IS NOT NULL THEN 'revoked'
+59 -4
View File
@@ -10,6 +10,7 @@ use axum::{
http::{HeaderMap, HeaderValue, StatusCode}, http::{HeaderMap, HeaderValue, StatusCode},
}; };
use chrono::{DateTime, Utc}; use chrono::{DateTime, Utc};
use rmm_domain::inventory_document::DeviceType;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use serde_json::{Value, json}; use serde_json::{Value, json};
use sqlx::{Postgres, Row, Transaction, postgres::PgRow}; use sqlx::{Postgres, Row, Transaction, postgres::PgRow};
@@ -240,7 +241,16 @@ pub async fn detail(
item["recent_jobs"] = if p.permits_scope("operations:read") item["recent_jobs"] = if p.permits_scope("operations:read")
&& crate::permissions::allowed(&mut tx, &p.name, "operations:read").await? && crate::permissions::allowed(&mut tx, &p.name, "operations:read").await?
{ {
sqlx::query_scalar::<_,Value>("SELECT jsonb_build_object('job_id',j.job_id,'operation_id',j.operation_id,'state',j.state,'created_at',r.created_at) FROM jobs j JOIN approval_requests r USING(tenant_id,operation_id) WHERE j.tenant_id=$1 AND j.asset_id=$2 AND j.agent_id=$3 ORDER BY r.created_at DESC,j.job_id LIMIT 20") sqlx::query_scalar::<_, Value>(
"SELECT jsonb_build_object(
'job_id', j.job_id, 'operation_id', j.operation_id, 'state', j.state, 'created_at', r.created_at,
'title', coalesce(nullif(plan_view.payload#>>'{script_revision,name}', ''), nullif(btrim(plan_view.payload->>'reason'), '')),
'action', convert_from(j.payload, 'UTF8')::jsonb#>>'{action,action}')
FROM jobs j JOIN approval_requests r USING (tenant_id, operation_id)
JOIN operation_plans p USING (tenant_id, plan_id)
CROSS JOIN LATERAL (SELECT convert_from(p.payload, 'UTF8')::jsonb AS payload) AS plan_view
WHERE j.tenant_id=$1 AND j.asset_id=$2 AND j.agent_id=$3
ORDER BY r.created_at DESC, j.job_id LIMIT 20")
.bind(tenant).bind(asset).bind(row.get::<Uuid,_>("agent_id")).fetch_all(&mut *tx).await?.into() .bind(tenant).bind(asset).bind(row.get::<Uuid,_>("agent_id")).fetch_all(&mut *tx).await?.into()
} else { } else {
Value::Null Value::Null
@@ -280,7 +290,17 @@ fn volumes(data: &Value) -> Value {
} }
items.into() items.into()
} }
fn device_type(hardware: &Value) -> Option<DeviceType> {
DeviceType::deserialize(&hardware["device_type"]).ok()
}
fn os_label(data: &Value) -> Option<String> { fn os_label(data: &Value) -> Option<String> {
let linux_hardware = observed(data, "linux.hardware");
if linux_hardware["proxmox_ve"].as_bool() == Some(true)
&& device_type(linux_hardware) == Some(DeviceType::Hypervisor)
{
return Some("Proxmox VE".to_owned());
}
let raw = data["os"].as_str()?; let raw = data["os"].as_str()?;
if let Some(pretty) = observed(data, "linux.os")["release"]["PRETTY_NAME"].as_str() { if let Some(pretty) = observed(data, "linux.os")["release"]["PRETTY_NAME"].as_str() {
return Some(pretty.to_owned()); return Some(pretty.to_owned());
@@ -332,6 +352,21 @@ fn project(row: &PgRow, now: DateTime<Utc>, full: bool) -> Value {
let data = row.get::<Option<Value>, _>("data").unwrap_or(Value::Null); let data = row.get::<Option<Value>, _>("data").unwrap_or(Value::Null);
let cpu = observed(&data, "linux.cpu"); let cpu = observed(&data, "linux.cpu");
let windows = observed(&data, "windows.hardware"); let windows = observed(&data, "windows.hardware");
let linux_memory = observed(&data, "linux.memory");
let usage = row
.get::<Option<Value>, _>("system_usage")
.unwrap_or(Value::Null);
let usage_at: Option<DateTime<Utc>> = row.get("system_usage_observed_at");
let inventory_at: Option<DateTime<Utc>> = row.get("observed_at");
let cpu_observed_at = usage["cpu_usage_observed_at"].as_str();
let cpu_usage = cpu_observed_at.and_then(|_| usage["cpu_usage_percent"].as_f64());
let ram_available = usage["ram_available_bytes"].as_u64();
let ram_total = usage["ram_total_bytes"]
.as_u64()
.or_else(|| linux_memory["total_bytes"].as_u64())
.or_else(|| windows["memory_total_bytes"].as_u64());
let device_type =
device_type(observed(&data, "linux.hardware")).or_else(|| device_type(windows));
let last = row.get::<Option<DateTime<Utc>>, _>("last_contact_at"); let last = row.get::<Option<DateTime<Utc>>, _>("last_contact_at");
let revoked = row.get::<Option<DateTime<Utc>>, _>("revoked_at"); let revoked = row.get::<Option<DateTime<Utc>>, _>("revoked_at");
let presence = match (revoked, last.map(|t| (now - t).num_seconds())) { let presence = match (revoked, last.map(|t| (now - t).num_seconds())) {
@@ -346,13 +381,18 @@ fn project(row: &PgRow, now: DateTime<Utc>, full: bool) -> Value {
"agent_id":row.get::<Uuid,_>("agent_id"),"asset_id":row.get::<Uuid,_>("asset_id"), "agent_id":row.get::<Uuid,_>("agent_id"),"asset_id":row.get::<Uuid,_>("asset_id"),
"status":row.get::<String,_>("status"),"lifecycle":row.get::<String,_>("lifecycle"), "status":row.get::<String,_>("status"),"lifecycle":row.get::<String,_>("lifecycle"),
"archived_at":row.get::<Option<DateTime<Utc>>,_>("archived_at"),"revoked_at":revoked, "archived_at":row.get::<Option<DateTime<Utc>>,_>("archived_at"),"revoked_at":revoked,
"hostname":data["hostname"].as_str(),"os":os_label(&data), "hostname":data["hostname"].as_str(),"device_type":device_type,"os":os_label(&data),
"disk_free_bytes":data["root_available_bytes"].as_u64(),"disk_total_bytes":data["root_total_bytes"].as_u64(), "disk_free_bytes":data["root_available_bytes"].as_u64(),"disk_total_bytes":data["root_total_bytes"].as_u64(),
"cpu_model":cpu["model"].as_str().or_else(||windows["cpu_model"].as_str()), "cpu_model":cpu["model"].as_str().or_else(||windows["cpu_model"].as_str()),
"cpu_logical_count":cpu["logical_processors"].as_u64().or_else(||windows["logical_processors_visible"].as_u64()), "cpu_logical_count":cpu["logical_processors"].as_u64().or_else(||windows["logical_processors_visible"].as_u64()),
"ram_total_bytes":observed(&data,"linux.memory")["total_bytes"].as_u64().or_else(||windows["memory_total_bytes"].as_u64()), "cpu_usage_percent":cpu_usage,
"cpu_usage_observed_at":cpu_observed_at,
"ram_total_bytes":ram_total,
"ram_available_bytes":ram_available.or_else(|| linux_memory["available_bytes"].as_u64().or_else(||windows["memory_available_bytes"].as_u64())
.filter(|available| ram_total.is_some_and(|total| *available <= total))),
"ram_observed_at":if ram_available.is_some() {usage_at} else {inventory_at},
"last_contact_at":last,"agent_version":row.get::<Option<String>,_>("reported_agent_version"), "last_contact_at":last,"agent_version":row.get::<Option<String>,_>("reported_agent_version"),
"presence":presence,"observed_at":row.get::<Option<DateTime<Utc>>,_>("observed_at"), "presence":presence,"observed_at":inventory_at,
"received_at":row.get::<Option<DateTime<Utc>>,_>("received_at"), "received_at":row.get::<Option<DateTime<Utc>>,_>("received_at"),
"source_id":row.get::<Option<String>,_>("source_id"),"quality":if data.is_null(){"unknown"}else{"valid"}, "source_id":row.get::<Option<String>,_>("source_id"),"quality":if data.is_null(){"unknown"}else{"valid"},
"completeness":"partial","health":"unknown" "completeness":"partial","health":"unknown"
@@ -402,6 +442,21 @@ mod tests {
assert!(os_label(&Value::Null).is_none()); assert!(os_label(&Value::Null).is_none());
} }
#[test]
fn proxmox_os_label_requires_a_valid_hypervisor_observation() {
let mut snapshot = json!({
"os": "Debian",
"observations": [{"scope":"linux.hardware","quality":"valid",
"data":{"device_type":"hypervisor","proxmox_ve":true}}]
});
assert_eq!(os_label(&snapshot).as_deref(), Some("Proxmox VE"));
snapshot["observations"][0]["data"]["device_type"] = json!("virtual");
assert_eq!(os_label(&snapshot).as_deref(), Some("Debian"));
snapshot["observations"][0]["quality"] = json!("error");
assert_eq!(device_type(observed(&snapshot, "linux.hardware")), None);
assert_eq!(device_type(&json!({"device_type":"desktop"})), None);
}
#[tokio::test] #[tokio::test]
#[ignore = "requires the disposable RLS database from tests/local_access_database.py"] #[ignore = "requires the disposable RLS database from tests/local_access_database.py"]
async fn visibility_is_filtered_before_the_cursor_limit() { async fn visibility_is_filtered_before_the_cursor_limit() {
+100 -69
View File
@@ -528,7 +528,25 @@ pub async fn permit(
denial_code: code.into(), denial_code: code.into(),
unreserved_request: None, unreserved_request: None,
}; };
let row=sqlx::query("SELECT j.*,a.authorization_id,a.revoked_at,a.principal AS approver,p.plan_hash,p.payload AS plan_payload,r.approval_state,i.enrollment_generation,i.assignment_version,i.asset_id AS bound_asset,i.capabilities,i.revoked_at AS device_revoked,i.connection_generation,t.changes_stopped FROM jobs j JOIN operations o ON o.tenant_id=j.tenant_id AND o.operation_id=j.operation_id JOIN authorizations a ON a.tenant_id=o.tenant_id AND a.authorization_id=o.authorization_id JOIN approval_requests r ON r.tenant_id=j.tenant_id AND r.operation_id=j.operation_id JOIN operation_plans p ON p.tenant_id=j.tenant_id AND p.plan_id=r.plan_id JOIN agent_installations i ON i.tenant_id=j.tenant_id AND i.agent_id=j.agent_id JOIN tenants t ON t.tenant_id=j.tenant_id WHERE j.job_id=$1 AND j.attempt_id=$2 AND j.agent_id=$3 FOR UPDATE OF j").bind(Uuid::parse_str(&r.job_id)?).bind(Uuid::parse_str(&r.attempt_id)?).bind(agent).fetch_optional(&mut *tx).await?; let row = sqlx::query(
"SELECT j.*, a.authorization_id, a.revoked_at, a.principal AS approver, r.principal AS submitter,
p.plan_hash, p.payload AS plan_payload, r.approval_state,
i.enrollment_generation, i.assignment_version, i.asset_id AS bound_asset,
i.capabilities, i.revoked_at AS device_revoked, i.connection_generation, t.changes_stopped
FROM jobs j
JOIN operations o USING (tenant_id,operation_id)
JOIN authorizations a ON a.tenant_id=o.tenant_id AND a.authorization_id=o.authorization_id
JOIN approval_requests r ON r.tenant_id=j.tenant_id AND r.operation_id=j.operation_id
JOIN operation_plans p ON p.tenant_id=r.tenant_id AND p.plan_id=r.plan_id
JOIN agent_installations i ON i.tenant_id=j.tenant_id AND i.agent_id=j.agent_id
JOIN tenants t ON t.tenant_id=j.tenant_id
WHERE j.job_id=$1 AND j.attempt_id=$2 AND j.agent_id=$3 FOR UPDATE OF j",
)
.bind(Uuid::parse_str(&r.job_id)?)
.bind(Uuid::parse_str(&r.attempt_id)?)
.bind(agent)
.fetch_optional(&mut *tx)
.await?;
let Some(row) = row else { let Some(row) = row else {
return Ok(denied("NOT_FOUND")); return Ok(denied("NOT_FOUND"));
}; };
@@ -571,8 +589,6 @@ pub async fn permit(
|| row || row
.get::<Option<chrono::DateTime<Utc>>, _>("device_revoked") .get::<Option<chrono::DateTime<Utc>>, _>("device_revoked")
.is_some() .is_some()
|| !crate::jobs::requester_enabled(state, &mut tx, &plan.principal, tenant).await?
|| !crate::jobs::requester_enabled(state, &mut tx, &row.get::<String, _>("approver"), tenant).await?
{ {
return Ok(denied("AUTHORIZATION_REVOKED")); return Ok(denied("AUTHORIZATION_REVOKED"));
} }
@@ -609,14 +625,7 @@ pub async fn permit(
.bind(agent) .bind(agent)
.fetch_one(&mut *tx) .fetch_one(&mut *tx)
.await?; .await?;
if !helper_ready if !helper_ready {
|| crate::root_policy::authorize(&mut tx, &plan.principal, &payload)
.await
.is_err()
|| crate::root_policy::authorize(&mut tx, &row.get::<String, _>("approver"), &payload)
.await
.is_err()
{
return Ok(denied(if payload.execution_identity == "system" { return Ok(denied(if payload.execution_identity == "system" {
"SYSTEM_SCOPE_OR_HELPER_SYNC_REQUIRED" "SYSTEM_SCOPE_OR_HELPER_SYNC_REQUIRED"
} else { } else {
@@ -684,23 +693,6 @@ pub async fn permit(
{ {
return Ok(denied("ARTIFACT_BINDING_MISMATCH")); return Ok(denied("ARTIFACT_BINDING_MISMATCH"));
} }
let approver: String = row.get("approver");
if matches!(payload.action, Action::QueryLogs { .. })
&& !crate::permissions::allowed(&mut tx, &plan.principal, "logs:read").await?
{
return Ok(denied("AUTHORIZATION_REVOKED"));
}
if !crate::permissions::allowed(&mut tx, &approver, "plans:approve").await?
|| !crate::permissions::allowed(&mut tx, &plan.principal, "operations:submit").await?
|| (matches!(payload.action, Action::RunScript { .. })
&& (!crate::permissions::allowed(&mut tx, &plan.principal, "scripts:execute").await?
|| !crate::permissions::allowed(&mut tx, &approver, "scripts:execute").await?))
|| (matches!(payload.action, Action::UpdateAgent { .. })
&& (!crate::permissions::allowed(&mut tx, &plan.principal, "updates:apply").await?
|| !crate::permissions::allowed(&mut tx, &approver, "updates:apply").await?))
{
return Ok(denied("AUTHORIZATION_REVOKED"));
}
let limits: (i32, i32) = let limits: (i32, i32) =
sqlx::query_as("SELECT starts_per_hour,max_parallel FROM tenant_limits") sqlx::query_as("SELECT starts_per_hour,max_parallel FROM tenant_limits")
.fetch_one(&mut *tx) .fetch_one(&mut *tx)
@@ -743,6 +735,21 @@ pub async fn permit(
if locked { if locked {
return Ok(denied("RESOURCE_LOCKED")); return Ok(denied("RESOURCE_LOCKED"));
} }
let log_sensitive = crate::root_policy::stored_log_sensitivity(&payload);
if let Err(error) =
crate::jobs::authorize_approved_job(state, &mut tx, tenant, &plan, &payload, &row).await
{
if error.0.is_server_error() {
anyhow::bail!("job authorization unavailable");
}
let code = match (error.1, payload.execution_identity.as_str()) {
("AUTHORIZATION_REVOKED" | "FORBIDDEN", _) => "AUTHORIZATION_REVOKED",
(_, "system") => "SYSTEM_SCOPE_OR_HELPER_SYNC_REQUIRED",
(_, "root") => "ROOT_SCOPE_OR_HELPER_SYNC_REQUIRED",
_ => "AUTHORIZATION_REVOKED",
};
return Ok(denied(code));
}
let grant = ExecutionPermitPayload { let grant = ExecutionPermitPayload {
agent_update_plan_id: matches!(payload.action, Action::UpdateAgent { .. }) agent_update_plan_id: matches!(payload.action, Action::UpdateAgent { .. })
.then_some(plan.plan_id), .then_some(plan.plan_id),
@@ -769,8 +776,9 @@ pub async fn permit(
let bytes = encode(&grant)?; let bytes = encode(&grant)?;
let signature = state.job_signer.sign(&bytes)?; let signature = state.job_signer.sign(&bytes)?;
sqlx::query("INSERT INTO execution_permits(tenant_id,grant_id,job_id,attempt_id,payload,signature) VALUES($1,$2,$3,$4,$5,$6)").bind(tenant).bind(grant.grant_id).bind(grant.job_id).bind(grant.attempt_id).bind(&bytes).bind(&signature).execute(&mut *tx).await?; sqlx::query("INSERT INTO execution_permits(tenant_id,grant_id,job_id,attempt_id,payload,signature) VALUES($1,$2,$3,$4,$5,$6)").bind(tenant).bind(grant.grant_id).bind(grant.job_id).bind(grant.attempt_id).bind(&bytes).bind(&signature).execute(&mut *tx).await?;
sqlx::query("UPDATE jobs SET start_reserved=true WHERE job_id=$1") sqlx::query("UPDATE jobs SET start_reserved=true, log_sensitive=$2 WHERE job_id=$1")
.bind(grant.job_id) .bind(grant.job_id)
.bind(log_sensitive)
.execute(&mut *tx) .execute(&mut *tx)
.await?; .await?;
sqlx::query("INSERT INTO audit_events VALUES($1,$2,'job-service','start_reserved',$3,now())") sqlx::query("INSERT INTO audit_events VALUES($1,$2,'job-service','start_reserved',$3,now())")
@@ -804,54 +812,77 @@ pub async fn next(
if let Some(r)=sqlx::query("SELECT job_id,attempt_id FROM jobs WHERE agent_id=$1 AND cancel_requested AND state IN ('accepted','running','verifying','awaiting_reboot') ORDER BY job_id LIMIT 1").bind(agent).fetch_optional(&mut *tx).await?{ if let Some(r)=sqlx::query("SELECT job_id,attempt_id FROM jobs WHERE agent_id=$1 AND cancel_requested AND state IN ('accepted','running','verifying','awaiting_reboot') ORDER BY job_id LIMIT 1").bind(agent).fetch_optional(&mut *tx).await?{
tx.commit().await?;return Ok(Some(Payload::CancelRequest(CancelRequest{job_id:r.get::<Uuid,_>("job_id").to_string(),attempt_id:r.get::<Uuid,_>("attempt_id").to_string(),reason:"operator_cancel_requested".into()}))) tx.commit().await?;return Ok(Some(Payload::CancelRequest(CancelRequest{job_id:r.get::<Uuid,_>("job_id").to_string(),attempt_id:r.get::<Uuid,_>("attempt_id").to_string(),reason:"operator_cancel_requested".into()})))
} }
let row=sqlx::query("SELECT j.job_id,j.attempt_id,j.payload,j.payload_hash,a.authorization_id,a.principal AS approver,p.plan_hash,p.payload AS plan_payload,i.capabilities FROM outbox b JOIN jobs j USING(tenant_id,job_id,attempt_id) JOIN operations o ON o.tenant_id=j.tenant_id AND o.operation_id=j.operation_id JOIN authorizations a ON a.tenant_id=o.tenant_id AND a.authorization_id=o.authorization_id JOIN approval_requests r ON r.tenant_id=j.tenant_id AND r.operation_id=j.operation_id JOIN operation_plans p ON p.tenant_id=j.tenant_id AND p.plan_id=r.plan_id JOIN tenants t ON t.tenant_id=j.tenant_id JOIN agent_installations i ON i.tenant_id=j.tenant_id AND i.agent_id=j.agent_id WHERE j.agent_id=$1 AND j.state='queued' AND NOT j.cancel_requested AND NOT t.changes_stopped AND a.revoked_at IS NULL AND r.approval_state='approved' AND p.expires_at>now() AND b.acknowledged_at IS NULL AND (b.lease_until IS NULL OR b.lease_until<now()) ORDER BY j.job_id FOR UPDATE OF b SKIP LOCKED LIMIT 1").bind(agent).fetch_optional(&mut *tx).await?; // A revoked participant can leave a queued job behind. Skip that job
let Some(row) = row else { // without leasing it so later eligible work on the same device can proceed.
tx.commit().await?; let mut after = None;
return Ok(None); let row = loop {
}; let row = sqlx::query(
let payload: JobPayload = serde_json::from_slice(&row.get::<Vec<u8>, _>("payload"))?; "SELECT j.job_id, j.attempt_id, j.payload, j.payload_hash, a.authorization_id,
let caps: Vec<String> = serde_json::from_value(row.get("capabilities"))?; a.principal AS approver, r.principal AS submitter, p.plan_hash,
if payload.action.windows_msi().is_some() p.payload AS plan_payload, i.capabilities
|| matches!(payload.action, Action::UpdateAgent { .. }) FROM outbox b
{ JOIN jobs j USING (tenant_id,job_id,attempt_id)
JOIN operations o ON o.tenant_id=j.tenant_id AND o.operation_id=j.operation_id
JOIN authorizations a ON a.tenant_id=o.tenant_id AND a.authorization_id=o.authorization_id
JOIN approval_requests r ON r.tenant_id=j.tenant_id AND r.operation_id=j.operation_id
JOIN operation_plans p ON p.tenant_id=r.tenant_id AND p.plan_id=r.plan_id
JOIN tenants t ON t.tenant_id=j.tenant_id
JOIN agent_installations i ON i.tenant_id=j.tenant_id AND i.agent_id=j.agent_id
WHERE j.agent_id=$1 AND ($2::uuid IS NULL OR j.job_id>$2)
AND j.state='queued' AND NOT j.cancel_requested AND NOT t.changes_stopped
AND a.revoked_at IS NULL AND r.approval_state='approved' AND p.expires_at>now()
AND b.acknowledged_at IS NULL AND (b.lease_until IS NULL OR b.lease_until<now())
ORDER BY j.job_id FOR UPDATE OF b SKIP LOCKED LIMIT 1",
)
.bind(agent)
.bind(after)
.fetch_optional(&mut *tx)
.await?;
let Some(row) = row else {
tx.commit().await?;
return Ok(None);
};
after = Some(row.get::<Uuid, _>("job_id"));
let raw: Vec<u8> = row.get("plan_payload"); let raw: Vec<u8> = row.get("plan_payload");
let plan: PlanPayload = serde_json::from_slice(&raw)?; let plan: PlanPayload = serde_json::from_slice(&raw)?;
if hash(&raw) != row.get::<String, _>("plan_hash") if hash(&raw) != row.get::<String, _>("plan_hash") {
|| crate::windows_msi_catalog::validate_job_binding(&plan, &payload).is_err() continue;
|| (matches!(payload.action, Action::UpdateAgent { .. }) }
&& crate::agent_updates::validate_job_binding(&plan, &payload).is_err()) let payload: JobPayload = serde_json::from_slice(&row.get::<Vec<u8>, _>("payload"))?;
|| crate::catalog::check(&mut tx, &payload.action) let caps: Vec<String> = serde_json::from_value(row.get("capabilities"))?;
.await if payload.action.windows_msi().is_some()
.is_err() || matches!(payload.action, Action::UpdateAgent { .. })
{ {
tx.commit().await?; if crate::windows_msi_catalog::validate_job_binding(&plan, &payload).is_err()
return Ok(None); || (matches!(payload.action, Action::UpdateAgent { .. })
&& crate::agent_updates::validate_job_binding(&plan, &payload).is_err())
|| crate::catalog::check(&mut tx, &payload.action)
.await
.is_err()
{
continue;
}
} }
}
if !payload if !payload
.action
.available_for(&payload.execution_identity, &caps)
|| !payload
.action .action
.valid_job_limits(payload.max_runtime_seconds, payload.max_output_bytes) .available_for(&payload.execution_identity, &caps)
{ || !payload
tx.commit().await?; .action
return Ok(None); .valid_job_limits(payload.max_runtime_seconds, payload.max_output_bytes)
}
if crate::root_policy::needs_helper(&payload.execution_identity) {
let plan: PlanPayload = serde_json::from_slice(&row.get::<Vec<u8>, _>("plan_payload"))?;
if crate::root_policy::authorize(&mut tx, &plan.principal, &payload)
.await
.is_err()
|| crate::root_policy::authorize(&mut tx, &row.get::<String, _>("approver"), &payload)
.await
.is_err()
{ {
tx.commit().await?; continue;
return Ok(None);
} }
} if let Err(error) =
crate::jobs::authorize_approved_job(state, &mut tx, tenant, &plan, &payload, &row).await
{
if error.0.is_server_error() {
anyhow::bail!("job authorization unavailable");
}
continue;
}
break row;
};
sqlx::query("UPDATE outbox SET lease_until=now()+interval '30 seconds' WHERE job_id=$1") sqlx::query("UPDATE outbox SET lease_until=now()+interval '30 seconds' WHERE job_id=$1")
.bind(row.get::<Uuid, _>("job_id")) .bind(row.get::<Uuid, _>("job_id"))
.execute(&mut *tx) .execute(&mut *tx)
+366 -424
View File
File diff suppressed because it is too large Load Diff
+45 -5
View File
@@ -316,6 +316,8 @@ async fn consume(pool: &PgPool, account: &Account, step: i64) -> Result<(), Stat
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
mod job_participants;
use super::*; use super::*;
use chrono::Utc; use chrono::Utc;
use serde_json::json; use serde_json::json;
@@ -441,7 +443,8 @@ mod tests {
let fingerprint = hash(asset.as_bytes()); let fingerprint = hash(asset.as_bytes());
sqlx::query("INSERT INTO agent_installations(tenant_id,agent_id,asset_id,certificate_sha256,last_contact_at,last_authenticated_certificate_sha256,last_authenticated_at) VALUES($1,$2,$3,$4,now(),$4,now())") sqlx::query("INSERT INTO agent_installations(tenant_id,agent_id,asset_id,certificate_sha256,last_contact_at,last_authenticated_certificate_sha256,last_authenticated_at) VALUES($1,$2,$3,$4,now(),$4,now())")
.bind(b).bind(Uuid::new_v4()).bind(asset).bind(fingerprint).execute(&admin).await.unwrap(); .bind(b).bind(Uuid::new_v4()).bind(asset).bind(fingerprint).execute(&admin).await.unwrap();
let mut config = sample(&issuer, a, &hex::encode([1; 64])); let password = "test pairing removal";
let mut config = sample(&issuer, a, &hex::encode(derive_password(password.as_bytes(), &[7; 32]).unwrap()));
let mut auth = crate::auth::Auth::from_env("development").await.unwrap(); let mut auth = crate::auth::Auth::from_env("development").await.unwrap();
auth.local = Some(configured(&config)); auth.local = Some(configured(&config));
let key_dir = std::env::temp_dir().join(id.to_string()); let key_dir = std::env::temp_dir().join(id.to_string());
@@ -456,14 +459,16 @@ mod tests {
.unwrap(), .unwrap(),
), ),
}; };
let router = crate::jobs::routes( let router = crate::controls::routes(crate::jobs::routes(
Router::new() Router::new()
.route("/api/v1/tenants", get(crate::api::tenants)) .route("/api/v1/tenants", get(crate::api::tenants))
.route( .route(
"/api/v1/tenants/{tenant}/devices/{asset}", "/api/v1/tenants/{tenant}/devices/{asset}",
get(crate::devices::detail), get(crate::devices::detail),
), ),
) ))
.route("/auth/local/login", axum::routing::post(crate::auth::local_login))
.route("/auth/session", get(crate::auth::session))
.layer(middleware::from_fn(crate::auth::context)) .layer(middleware::from_fn(crate::auth::context))
.with_state(state.clone()); .with_state(state.clone());
let listener = tokio::net::TcpListener::bind(("127.0.0.1", 0)) let listener = tokio::net::TcpListener::bind(("127.0.0.1", 0))
@@ -481,12 +486,13 @@ mod tests {
assert_eq!(directory["items"].as_array().unwrap().len(), 1); assert_eq!(directory["items"].as_array().unwrap().len(), 1);
assert_eq!(directory["items"][0]["tenant_id"], a.to_string()); assert_eq!(directory["items"][0]["tenant_id"], a.to_string());
let now = Utc::now(); let now = Utc::now();
let forbidden_plan = json!({"tenant_id":b,"action":"refresh_inventory","targets":{"asset_ids":[asset]}, let forbidden_plan = json!({"tenant_id":b,"action":"run_script","targets":{"asset_ids":[asset]},
"parameters":{"execution_identity":"agent_service","timeout_seconds":60,"max_output_bytes":4096,"scope":"base"}, "parameters":{"execution_identity":"agent_service","timeout_seconds":60,"max_output_bytes":4096,"variants":[{"os_family":"linux","interpreter":"posix_sh","encoding":"utf-8","script_utf8":":\n"}]},
"schedule":{"not_before":now,"start_before":now+chrono::Duration::minutes(5),"offline_policy":"wait_until_deadline"}, "schedule":{"not_before":now,"start_before":now+chrono::Duration::minutes(5),"offline_policy":"wait_until_deadline"},
"rollout":{"max_parallel":1,"halt_after_failures":1},"reason":"test customer authorization"}); "rollout":{"max_parallel":1,"halt_after_failures":1},"reason":"test customer authorization"});
for request in [ for request in [
client.get(format!("{base}/{b}/devices/{asset}")), client.get(format!("{base}/{b}/devices/{asset}")),
client.delete(format!("{base}/{b}/devices/{asset}?agent_id={id}")),
client client
.post(format!("{base}/{b}/operation-plans")) .post(format!("{base}/{b}/operation-plans"))
.json(&forbidden_plan), .json(&forbidden_plan),
@@ -509,6 +515,40 @@ mod tests {
.await .await
.unwrap(); .unwrap();
assert_eq!(created, 0); assert_eq!(created, 0);
let pair = format!("{base}/{a}/devices/{asset}?agent_id={id}");
let same_customer = client.delete(&pair).bearer_auth(&token).send().await.unwrap();
assert_eq!(same_customer.status(), StatusCode::FORBIDDEN);
let api = base.strip_suffix("/api/v1/tenants").unwrap();
let origin = &state.auth.origin;
let credentials = input(password, &configured(&config).users[0].secret);
let logged_in = client.post(format!("{api}/auth/local/login")).header("origin", origin)
.json(&json!({"username":credentials.username,"password":credentials.password,"totp_code":credentials.totp_code}))
.send().await.unwrap().error_for_status().unwrap();
let cookie = logged_in.headers()["set-cookie"].to_str().unwrap().split(';').next().unwrap();
let session = client.get(format!("{api}/auth/session")).header("cookie", cookie)
.send().await.unwrap().json::<Value>().await.unwrap();
let deletion = || client.delete(&pair).header("origin", origin).header("cookie", cookie);
let csrf = session["csrf_token"].as_str().unwrap();
assert_eq!(deletion().header("x-csrf-token", csrf).send().await.unwrap().status(), StatusCode::FORBIDDEN);
sqlx::query("UPDATE memberships SET permissions=array_append(permissions,'devices:revoke') WHERE tenant_id=$1 AND principal=$2")
.bind(a).bind(&issuer).execute(&admin).await.unwrap();
sqlx::query("INSERT INTO assets(tenant_id,asset_id) VALUES($1,$2)")
.bind(a).bind(asset).execute(&admin).await.unwrap();
sqlx::query("INSERT INTO agent_installations(tenant_id,agent_id,asset_id,certificate_sha256) VALUES($1,$2,$3,$4)")
.bind(a).bind(id).bind(asset).bind(hash(id.as_bytes())).execute(&admin).await.unwrap();
assert_eq!(deletion().send().await.unwrap().status(), StatusCode::FORBIDDEN);
assert_eq!(deletion().header("x-csrf-token",csrf).send().await.unwrap().status(), StatusCode::CONFLICT);
let revoked = client.post(format!("{base}/{a}/devices/{asset}/revocation?agent_id={id}"))
.header("origin", origin).header("cookie",cookie).header("x-csrf-token",csrf)
.json(&json!({"reason":"isolated retirement"})).send().await.unwrap();
assert_eq!(revoked.status(), StatusCode::OK);
for _ in 0..2 {
assert_eq!(deletion().header("x-csrf-token",csrf).send().await.unwrap().status(), StatusCode::NO_CONTENT);
}
let records: i64 = sqlx::query_scalar("SELECT count(*) FROM audit_events WHERE tenant_id=$1 AND event_type='device_deleted' AND data#>>'{decision,agent_id}'=$2")
.bind(a).bind(id.to_string()).fetch_one(&admin).await.unwrap();
assert_eq!(records, 1);
server.abort(); server.abort();
config["users"][0]["disabled"] = json!(true); config["users"][0]["disabled"] = json!(true);
let mut disabled = crate::auth::Auth::from_env("development").await.unwrap(); let mut disabled = crate::auth::Auth::from_env("development").await.unwrap();
@@ -0,0 +1,277 @@
use super::*;
use crate::auth::Principal;
use crate::jobs::{PlanInput, Rollout, Schedule, Submit, Targets};
use rmm_domain::jobs::{Action, PlanPayload, encode};
use rmm_protocol::{Envelope, ExecutionPermitRequest, Payload};
#[tokio::test]
#[ignore = "requires the disposable RLS database from tests/local_access_database.py"]
async fn separate_roles_and_submitter_revocation_at_approval_and_start() {
let admin = PgPool::connect(&std::env::var("RMM_TEST_REPAIR_ADMIN_URL").unwrap())
.await
.unwrap();
let pool = PgPool::connect(&std::env::var("RMM_TEST_REPAIR_APP_URL").unwrap())
.await
.unwrap();
let tenant = Uuid::new_v4();
let agent = Uuid::new_v4();
let planner_name = format!("local:{}", Uuid::new_v4());
let approver_name = format!("local:{}", Uuid::new_v4());
let scopes = ["operations:submit", "operations:read", "scripts:execute"];
sqlx::query("INSERT INTO tenants(tenant_id,name) VALUES($1,$2)")
.bind(tenant)
.bind(format!("Participants {tenant}"))
.execute(&admin)
.await
.unwrap();
for (actor, permissions) in [
(&planner_name, vec!["operations:plan", "scripts:execute"]),
(
&approver_name,
[scopes.as_slice(), &["plans:approve", "tokens:manage"]].concat(),
),
] {
sqlx::query("INSERT INTO memberships(tenant_id,principal,kind,permissions) VALUES($1,$2,'human',$3)")
.bind(tenant).bind(actor).bind(permissions).execute(&admin).await.unwrap();
}
sqlx::query("INSERT INTO assets(tenant_id,asset_id) VALUES($1,$2)")
.bind(tenant)
.bind(agent)
.execute(&admin)
.await
.unwrap();
sqlx::query("INSERT INTO agent_installations(tenant_id,agent_id,asset_id,certificate_sha256,capabilities,connection_generation) VALUES($1,$2,$2,$3,$4,1)")
.bind(tenant).bind(agent).bind(hash(agent.as_bytes())).bind(json!(["linux.base/1","run_script"]))
.execute(&admin).await.unwrap();
let mut accounts = sample(&planner_name, tenant, &"0".repeat(128));
let mut reviewer = sample(&approver_name, tenant, &"0".repeat(128))["users"][0].clone();
reviewer["username"] = json!("reviewer");
accounts["users"].as_array_mut().unwrap().push(reviewer);
let mut auth = crate::auth::Auth::from_env("development").await.unwrap();
auth.local = Some(configured(&accounts));
let key_dir = std::env::temp_dir().join(format!("rmm-roles-{tenant}"));
let state = crate::State {
auth: Arc::new(auth),
pool: pool.clone(),
signer: None,
viewer_a: [0; 32],
viewer_b: [1; 32],
job_signer: Arc::new(
crate::job_signer::JobSigner::load_or_create(&key_dir.join("test.key")).unwrap(),
),
};
let planner = Principal {
tenant,
tenants: vec![tenant],
name: planner_name,
operator: true,
scopes: None,
session_hash: None,
csrf: None,
testsimulation: true,
identity: None,
};
let approver = Principal {
name: approver_name,
..planner.clone()
};
for stage in [
"revoked_before_approval",
"revoked_before_start",
"scope_removed",
"allowed",
] {
let token_id = Uuid::new_v4();
let raw = format!("rmm_mcp_{}AAAAAAAAAAA", token_id.simple());
let mut tx = rmm_persistence::tenant_tx(&pool, tenant).await.unwrap();
sqlx::query("SELECT issue_customer_token($1,$2,'submit fixture',$3,$4,now()+interval '1 hour',false,$5)")
.bind(&approver.name).bind(token_id).bind(hash(raw.as_bytes())).bind(scopes.as_slice())
.bind(vec![tenant]).execute(&mut *tx).await.unwrap();
tx.commit().await.unwrap();
let submitter = crate::mcp_tokens::authenticate(&state, &raw, Some(tenant))
.await
.unwrap();
let now = Utc::now();
let input = PlanInput {
targets: Targets {
asset_ids: vec![agent],
},
action: Action::RunScript {
interpreter: "posix_sh".into(),
script_utf8: ":\n".into(),
arguments: vec![],
expected_stdout: None,
windows_execution_profile: None,
privileged_script_profile: None,
},
execution_identity: "agent_service".into(),
max_runtime_seconds: 30,
max_output_bytes: 1024,
script_variants: vec![],
artifact_ids: vec![],
schedule: Schedule {
not_before: now,
start_before: now + chrono::Duration::hours(1),
},
rollout: Rollout {
max_parallel: 1,
halt_after_failures: 1,
},
reason: stage.into(),
};
let saved = crate::jobs::plan(&state, &planner, tenant, input)
.await
.unwrap();
let plan: PlanPayload = serde_json::from_value(saved["payload"].clone()).unwrap();
let order = crate::jobs::submit(
&state,
&submitter,
tenant,
plan.plan_id,
Submit {
idempotency_key: stage.into(),
},
)
.await
.unwrap();
let op: Uuid = serde_json::from_value(order["operation_id"].clone()).unwrap();
let mut tx = rmm_persistence::tenant_tx(&pool, tenant).await.unwrap();
let stored_submitter: String =
sqlx::query_scalar("SELECT principal FROM approval_requests WHERE operation_id=$1")
.bind(op)
.fetch_one(&mut *tx)
.await
.unwrap();
assert_eq!(stored_submitter, submitter.name);
if stage == "revoked_before_approval" {
assert!(revoke(&mut tx, &approver, token_id).await);
assert_eq!(
crate::jobs::recheck_approval(&state, &mut tx, &plan, &stored_submitter, &approver)
.await
.unwrap_err()
.1,
"AUTHORIZATION_REVOKED"
);
let (status, jobs, permits): (String, i64, i64) = sqlx::query_as(
"SELECT approval_state,(SELECT count(*) FROM jobs WHERE operation_id=$1),(SELECT count(*) FROM execution_permits WHERE job_id=$2) FROM approval_requests WHERE operation_id=$1"
).bind(op).bind(plan.jobs[0].payload.job_id).fetch_one(&mut *tx).await.unwrap();
assert_eq!((status.as_str(), jobs, permits), ("pending_approval", 0, 0));
tx.commit().await.unwrap();
continue;
}
crate::jobs::recheck_approval(&state, &mut tx, &plan, &stored_submitter, &approver)
.await
.unwrap();
tx.commit().await.unwrap();
// Isolated ledger fixture for the normal gateway entry point. No client is connected.
let job = &plan.jobs[0];
let id = Uuid::new_v4();
sqlx::query("UPDATE approval_requests SET approval_state='approved' WHERE operation_id=$1")
.bind(op)
.execute(&admin)
.await
.unwrap();
sqlx::query("INSERT INTO authorizations(tenant_id,authorization_id,operation_id,plan_id,plan_hash,principal,session_hash,approval_origin,testsimulation,policy_version) VALUES($1,$2,$3,$4,$5,$6,'fixture','dev_test_browser_simulation',true,1)")
.bind(tenant).bind(id).bind(op).bind(plan.plan_id).bind(saved["plan_hash"].as_str().unwrap()).bind(&approver.name)
.execute(&admin).await.unwrap();
sqlx::query("INSERT INTO operations VALUES($1,$2,$3)")
.bind(tenant)
.bind(op)
.bind(id)
.execute(&admin)
.await
.unwrap();
sqlx::query("INSERT INTO jobs(tenant_id,job_id,attempt_id,operation_id,agent_id,asset_id,payload,payload_hash,state,resource,journal_proof) VALUES($1,$2,$3,$4,$5,$5,$6,$7,'queued','device_execution','fixture')")
.bind(tenant).bind(job.payload.job_id).bind(job.payload.attempt_id).bind(op).bind(agent)
.bind(encode(&job.payload).unwrap()).bind(&job.job_payload_hash).execute(&admin).await.unwrap();
sqlx::query("INSERT INTO outbox(tenant_id,job_id,attempt_id) VALUES($1,$2,$3)")
.bind(tenant)
.bind(job.payload.job_id)
.bind(job.payload.attempt_id)
.execute(&admin)
.await
.unwrap();
if stage == "revoked_before_start" {
let mut tx = rmm_persistence::tenant_tx(&pool, tenant).await.unwrap();
assert!(revoke(&mut tx, &approver, token_id).await);
tx.commit().await.unwrap();
} else if stage == "scope_removed" {
sqlx::query("UPDATE memberships SET permissions=array_remove(permissions,'scripts:execute') WHERE tenant_id=$1 AND principal=$2")
.bind(tenant).bind(&submitter.name).execute(&admin).await.unwrap();
}
let offer = crate::job_gateway::next(&state, tenant, agent, 1)
.await
.unwrap();
if stage == "allowed" {
assert!(
matches!(offer, Some(Payload::JobOffer(o)) if o.job_id == job.payload.job_id.to_string())
);
} else {
assert!(offer.is_none());
let leased: bool =
sqlx::query_scalar("SELECT lease_until IS NOT NULL FROM outbox WHERE job_id=$1")
.bind(job.payload.job_id)
.fetch_one(&admin)
.await
.unwrap();
assert!(!leased);
}
// Also model acceptance before the same revocation, so the start gate is exercised independently.
sqlx::query("UPDATE jobs SET state='accepted' WHERE job_id=$1")
.bind(job.payload.job_id)
.execute(&admin)
.await
.unwrap();
let envelope = Envelope {
connection_generation: 1,
..Default::default()
};
let request = ExecutionPermitRequest {
job_id: job.payload.job_id.to_string(),
attempt_id: job.payload.attempt_id.to_string(),
job_payload_hash: job.job_payload_hash.clone(),
assignment_version: job.payload.assignment_version,
};
let permit = crate::job_gateway::permit(&state, tenant, agent, &envelope, &request)
.await
.unwrap();
let (reserved, count): (bool, i64) = sqlx::query_as("SELECT start_reserved,(SELECT count(*) FROM execution_permits WHERE job_id=$1) FROM jobs WHERE job_id=$1")
.bind(job.payload.job_id).fetch_one(&admin).await.unwrap();
if stage == "allowed" {
assert_eq!(permit.denial_code, "");
assert!(!permit.signature.is_empty());
assert_eq!((reserved, count), (true, 1));
} else {
assert_eq!(permit.denial_code, "AUTHORIZATION_REVOKED");
assert!(permit.payload_bytes.is_empty() && permit.signature.is_empty());
assert_eq!((reserved, count), (false, 0));
// A still-queued denied fixture must not prevent delivery of the next allowed job.
sqlx::query("UPDATE jobs SET state='queued' WHERE job_id=$1")
.bind(job.payload.job_id)
.execute(&admin)
.await
.unwrap();
}
}
std::fs::remove_dir_all(key_dir).unwrap();
}
async fn revoke(
tx: &mut sqlx::Transaction<'_, sqlx::Postgres>,
approver: &Principal,
id: Uuid,
) -> bool {
sqlx::query_scalar("SELECT revoke_mcp_token($1,$2,$3,$4)")
.bind(&approver.name)
.bind(id)
.bind(Uuid::new_v4())
.bind(&approver.tenants)
.fetch_one(&mut **tx)
.await
.unwrap()
}
+1
View File
@@ -27,6 +27,7 @@ mod oidc;
mod pagination; mod pagination;
mod permissions; mod permissions;
mod root_policy; mod root_policy;
mod managed_scripts;
mod scheduler; mod scheduler;
mod script_library; mod script_library;
mod synchronization; mod synchronization;
+468
View File
@@ -0,0 +1,468 @@
//! Permanent authorization ceilings for installed, pinned script helpers.
//! Plan submission, interactive approval and signed start grants are unchanged.
use crate::{jobs::Error, root_policy::RootScope, windows_policy::SystemScope};
use axum::http::StatusCode;
use rmm_domain::{
agent_update::{ArtifactRole, LINUX_ARM64_RELEASE_CAPABILITY, Platform, ReleaseManifest, digest},
jobs::{Action, FULL_MAINTENANCE_CAPABILITY, JobPayload},
};
use serde::Deserialize;
use sqlx::{Postgres, Transaction};
use std::{fs, os::unix::fs::MetadataExt, path::Path};
use uuid::Uuid;
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Policy {
schema_version: u8,
linux: Vec<RootScope>,
windows: Vec<SystemScope>,
#[serde(default)]
release_anchors: Vec<ReleaseAnchor>,
}
/// Operator-pinned canonical bytes of an already authorized local policy.
/// A signed pair changes only the two image digests and the Windows release directory.
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct ReleaseAnchor {
agent_id: Uuid,
release_id: Uuid,
agent_sha256: String,
helper_sha256: String,
policy_json: String,
}
impl ReleaseAnchor {
fn policy_for(&self, manifest: &ReleaseManifest) -> Option<String> {
if self.policy_json.len() > 8192
|| self.release_id.is_nil()
|| !digest(&self.agent_sha256)
|| !digest(&self.helper_sha256)
|| self.agent_sha256 == self.helper_sha256
{
return None;
}
let next = |role| {
manifest
.artifacts
.iter()
.find(|a| a.role == role)
.map(|a| a.sha256.as_str())
};
let mut raw = self.policy_json.clone();
let mut replace = |from: String, to: String, count| {
if raw.matches(&from).count() != count {
return None;
}
raw = raw.replace(&from, &to);
Some(())
};
let field = |name: &str, value: &str| format!(r#""{name}":"{value}""#);
match manifest.platform {
Platform::LinuxX64 | Platform::LinuxArm64 => replace(
field("helper_binary_sha256", &self.helper_sha256),
field("helper_binary_sha256", next(ArtifactRole::Helper)?),
1,
)?,
Platform::WindowsGnuX64 => {
replace(
field("binary_sha256", &self.agent_sha256),
field("binary_sha256", next(ArtifactRole::Agent)?),
1,
)?;
replace(
field("binary_sha256", &self.helper_sha256),
field("binary_sha256", next(ArtifactRole::Helper)?),
1,
)?;
let directory = |release| format!(r"\\releases\\{release}\\");
replace(
directory(self.release_id),
directory(manifest.release_id),
2,
)?;
}
_ => return None,
}
Some(rmm_domain::jobs::hash(raw.as_bytes()))
}
}
fn invalid() -> Error {
Error(StatusCode::CONFLICT, "MANAGED_SCRIPT_POLICY_INVALID")
}
// Only a managed device scope can opt in. The authenticated principal remains
// the token ID for authorization, the plan record and audit.
const SCOPED_MCP: &str = "mcp:scoped";
#[derive(Clone, Copy)]
enum HelperBinding {
LocalPins,
VerifiedInstalledRelease,
}
impl Policy {
fn permits(
&self,
principal: &str,
job: &JobPayload,
caps: &[String],
binding: HelperBinding,
) -> bool {
if principal == SCOPED_MCP
|| !matches!(job.action, Action::RunScript { .. })
|| !job.action.full_maintenance()
|| !job.action.validate()
|| !job.action.available_for(&job.execution_identity, caps)
|| !job
.action
.valid_job_limits(job.max_runtime_seconds, job.max_output_bytes)
{
return false;
}
let permits_subject = |subject: &str| match job.execution_identity.as_str() {
"root" => self
.linux
.iter()
.any(|scope| scope.permits(subject, job, caps, None)),
"system" => self
.windows
.iter()
.any(|scope| scope.permits(subject, job, caps, false, true, false)),
_ => false,
};
permits_subject(principal)
|| (matches!(binding, HelperBinding::VerifiedInstalledRelease)
&& principal.strip_prefix("mcp:").is_some_and(|id| {
Uuid::parse_str(id).is_ok_and(|uuid| !uuid.is_nil() && uuid.to_string() == id)
})
&& permits_subject(SCOPED_MCP))
}
}
fn binding_error() -> Error {
Error(StatusCode::CONFLICT, "SCRIPT_HELPER_BINDING_INVALID")
}
// Multiple helper roles may coexist on older clients. For the release-managed
// script profile we require exactly one unambiguous release, policy and binary.
fn single_value<'a>(caps: &'a [String], prefix: &str) -> Result<&'a str, Error> {
let mut values = caps.iter().filter_map(|c| c.strip_prefix(prefix));
let value = values.next().ok_or_else(binding_error)?;
if value.is_empty() || values.next().is_some() {
return Err(binding_error());
}
Ok(value)
}
fn check_pair(
manifest: &ReleaseManifest,
version: Option<&str>,
identity: &str,
caps: &[String],
) -> Result<(), Error> {
let platform = match identity {
"root" if caps.iter().any(|cap| cap == LINUX_ARM64_RELEASE_CAPABILITY) => {
Platform::LinuxArm64
}
"root" => Platform::LinuxX64,
"system" => Platform::WindowsGnuX64,
_ => return Err(binding_error()),
};
let binary = single_value(caps, "helper.binary.sha256:")?;
if version != Some(manifest.version.as_str())
|| platform != manifest.platform
|| !digest(single_value(caps, "helper.policy.sha256:")?)
|| !manifest
.artifacts
.iter()
.any(|a| a.role == ArtifactRole::Helper && a.sha256 == binary)
{
return Err(binding_error());
}
Ok(())
}
pub(crate) async fn permits(
tx: &mut Transaction<'_, Postgres>,
principal: &str,
job: &JobPayload,
caps: &[String],
) -> Result<bool, Error> {
if !job.action.full_maintenance() {
return Ok(false);
}
let Some(path) = std::env::var_os("RMM_MANAGED_SCRIPT_POLICY_FILE") else {
return Ok(false);
};
let key = std::env::var_os("RMM_JOB_KEY_FILE").ok_or_else(invalid)?;
let signer = fs::symlink_metadata(key).map_err(|_| invalid())?;
if !signer.is_file() {
return Err(invalid());
}
let bytes = crate::windows_policy::protected_bytes(Path::new(&path), signer.uid())
.map_err(|_| invalid())?;
let policy: Policy = serde_json::from_slice(&bytes).map_err(|_| invalid())?;
if policy.schema_version != 1
|| policy.linux.len() + policy.windows.len() > 64
|| policy.release_anchors.len() > 64
|| policy
.release_anchors
.iter()
.any(|a| a.policy_json.len() > 8192)
|| !policy.windows.iter().all(SystemScope::valid)
{
return Err(invalid());
}
if !caps
.iter()
.any(|cap| cap.starts_with("script.helper.release:"))
{
return Ok(policy.permits(principal, job, caps, HelperBinding::LocalPins));
}
{
let release = Uuid::parse_str(single_value(caps, "script.helper.release:")?)
.map_err(|_| binding_error())?;
if !caps.iter().any(|cap| cap == FULL_MAINTENANCE_CAPABILITY) {
return Err(binding_error());
}
let version: Option<String> = sqlx::query_scalar(
"SELECT reported_agent_version FROM agent_installations WHERE tenant_id=$1 AND agent_id=$2 AND asset_id=$3 AND revoked_at IS NULL",
)
.bind(job.tenant_id)
.bind(job.agent_id)
.bind(job.asset_id)
.fetch_optional(&mut **tx)
.await?
.flatten();
let manifest = crate::agent_updates::checked_installed_helper_release(tx, release)
.await
.map_err(|err| {
if err.0.is_server_error() {
err
} else {
binding_error()
}
})?;
check_pair(&manifest, version.as_deref(), &job.execution_identity, caps)?;
if policy.permits(
principal,
job,
caps,
HelperBinding::VerifiedInstalledRelease,
) {
return Ok(true);
}
let current_policy = single_value(caps, "helper.policy.sha256:")?;
for anchor in policy
.release_anchors
.iter()
.filter(|a| a.agent_id == job.agent_id)
{
if anchor.policy_for(&manifest).as_deref() != Some(current_policy) {
continue;
}
let original = rmm_domain::jobs::hash(anchor.policy_json.as_bytes());
let mut pinned = caps.to_owned();
pinned.retain(|c| {
!c.starts_with("helper.binary.sha256:") && !c.starts_with("helper.policy.sha256:")
});
pinned.push(format!("helper.binary.sha256:{}", anchor.helper_sha256));
pinned.push(format!("helper.policy.sha256:{original}"));
if policy.permits(
principal,
job,
&pinned,
HelperBinding::VerifiedInstalledRelease,
) {
return Ok(true);
}
}
}
Err(Error(StatusCode::FORBIDDEN, "SCRIPT_HELPER_SCOPE_DENIED"))
}
#[cfg(test)]
mod tests {
use super::*;
use rmm_domain::agent_update::ArtifactDescriptor;
use serde_json::json;
#[test]
fn scoped_mcp_requires_a_device_opt_in_and_the_same_pinned_script_scope() {
let token = "mcp:12345678-abcd-4321-b123-123456789abc";
let verified = HelperBinding::VerifiedInstalledRelease;
let local = HelperBinding::LocalPins;
for (platform, identity, interpreter, script) in [
("linux", "root", "posix_sh", "true\n"),
("windows", "system", "powershell", "Write-Output 'ok'\r\n"),
] {
let mut job = JobPayload {
schema_version: 1,
tenant_id: Uuid::new_v4(),
asset_id: Uuid::new_v4(),
agent_id: Uuid::new_v4(),
enrollment_generation: 1,
assignment_version: 1,
job_id: Uuid::new_v4(),
attempt_id: Uuid::new_v4(),
action: Action::RunScript {
interpreter: interpreter.into(),
script_utf8: script.into(),
arguments: vec![],
expected_stdout: None,
windows_execution_profile: None,
privileged_script_profile: Some(
rmm_domain::jobs::PrivilegedScriptProfile::FullMaintenanceV1,
),
},
execution_identity: identity.into(),
not_before: chrono::Utc::now(),
start_before: chrono::Utc::now() + chrono::Duration::minutes(5),
max_runtime_seconds: 30,
max_output_bytes: 4096,
};
let binary = "ab".repeat(32);
let local_policy = "cd".repeat(32);
let mut caps = vec![
format!("{platform}.base/1"),
format!("helper.{identity}.v1"),
format!("{identity}:run_script"),
"run_script".into(),
"rmm.sync.v1".into(),
FULL_MAINTENANCE_CAPABILITY.into(),
format!("helper.policy.sha256:{local_policy}"),
format!("helper.binary.sha256:{binary}"),
];
let mut scope = json!({
"tenant_id": job.tenant_id, "asset_id": job.asset_id, "agent_id": job.agent_id,
"enrollment_generation": 1, "assignment_version": 1, "principals": ["local:reviewer"],
"helper_policy_sha256": local_policy, "helper_binary_sha256": binary,
"acceptance_evidence_id": Uuid::new_v4(), "allowed_services": [],
"allowed_script_profiles": ["full_maintenance_v1"]
});
if platform == "linux" {
scope["allow_root_scripts"] = json!(true);
scope["allow_reboot"] = json!(false);
} else {
scope["max_runtime_seconds"] = json!(30);
scope["allowed_script_sha256"] = json!([rmm_domain::jobs::hash(script.as_bytes())]);
caps.push("script.powershell/1".into());
}
let mut config = json!({"schema_version": 1, "linux": [], "windows": []});
config[platform] = json!([scope]);
let policy: Policy = serde_json::from_value(config.clone()).unwrap();
assert!(policy.permits("local:reviewer", &job, &caps, verified));
assert!(!policy.permits(token, &job, &caps, verified));
config[platform][0]["principals"] = json!(["local:reviewer", SCOPED_MCP]);
let policy: Policy = serde_json::from_value(config).unwrap();
assert!(policy.permits(token, &job, &caps, verified), "{platform}");
assert!(!policy.permits(token, &job, &caps, local));
assert!(policy.permits("local:reviewer", &job, &caps, local));
assert!(policy.permits("local:reviewer", &job, &caps, verified));
for other in [
SCOPED_MCP,
"local:other",
"mcp:not-a-uuid",
"mcp:00000000-0000-0000-0000-000000000000",
"mcp:12345678ABCD4321B123123456789ABC",
] {
assert!(
!policy.permits(other, &job, &caps, verified),
"{platform}: {other}"
);
}
let mut without_binary = caps.clone();
without_binary.retain(|cap| !cap.starts_with("helper.binary.sha256:"));
assert!(!policy.permits(token, &job, &without_binary, verified));
job.assignment_version += 1;
assert!(!policy.permits(token, &job, &caps, verified));
if platform == "windows" {
job.assignment_version -= 1;
if let Action::RunScript { arguments, .. } = &mut job.action {
arguments.push("other".into());
}
assert!(!policy.permits(token, &job, &caps, verified));
if let Action::RunScript {
script_utf8,
arguments,
..
} = &mut job.action
{
arguments.clear();
*script_utf8 = "Write-Output 'changed'\r\n".into();
}
assert!(!policy.permits(token, &job, &caps, verified));
}
}
}
#[test]
fn signed_helper_is_bound_to_platform_reported_version_and_unambiguous_local_pins() {
let binary = "ab".repeat(32);
let policy = "cd".repeat(32);
let artifact = |role, sha256| ArtifactDescriptor {
role,
sha256,
artifact_id: Uuid::new_v4(),
bytes: 4096,
};
let m = ReleaseManifest {
schema_version: 1,
release_id: Uuid::new_v4(),
release_sequence: 7,
version: "0.1.12".into(),
platform: Platform::WindowsGnuX64,
published_at: 10,
expires_at: 500,
protocol_major: 1,
state_schema: 1,
minimum_updater_version: 2,
artifacts: [
artifact(ArtifactRole::Agent, "ef".repeat(32)),
artifact(ArtifactRole::Helper, binary.clone()),
],
};
// Rollover may substitute signed image pins and their release directory only.
let previous = Uuid::new_v4();
let original_agent = "12".repeat(32);
let original_helper = "34".repeat(32);
let windows = |release: Uuid, agent: &str, helper: &str, runtime: u32| {
format!(
r#"{{"agent":{{"binary":"C:\\releases\\{release}\\agent.exe","binary_sha256":"{agent}"}},"helper":{{"binary":"C:\\releases\\{release}\\helper.exe","binary_sha256":"{helper}"}},"max_runtime_seconds":{runtime}}}"#
)
};
let mut anchor = ReleaseAnchor {
agent_id: Uuid::new_v4(),
release_id: previous,
policy_json: windows(previous, &original_agent, &original_helper, 30),
agent_sha256: original_agent,
helper_sha256: original_helper,
};
let next_agent = &m.artifacts[0].sha256;
let expected = |limit| {
rmm_domain::jobs::hash(windows(m.release_id, next_agent, &binary, limit).as_bytes())
};
assert_eq!(anchor.policy_for(&m), Some(expected(30)));
assert_ne!(anchor.policy_for(&m), Some(expected(120)));
anchor
.policy_json
.push_str(&format!(r#","binary_sha256":"{}""#, anchor.helper_sha256));
assert!(anchor.policy_for(&m).is_none());
let mut caps = vec![
format!("helper.binary.sha256:{binary}"),
format!("helper.policy.sha256:{policy}"),
];
assert!(check_pair(&m, Some("0.1.12"), "system", &caps).is_ok());
assert!(check_pair(&m, Some("0.1.11"), "system", &caps).is_err());
assert!(check_pair(&m, Some("0.1.12"), "root", &caps).is_err());
caps.push(format!("helper.binary.sha256:{binary}"));
assert!(check_pair(&m, Some("0.1.12"), "system", &caps).is_err());
caps.remove(0);
caps[1] = format!("helper.binary.sha256:{policy}");
assert!(check_pair(&m, Some("0.1.12"), "system", &caps).is_err());
}
}
+38 -7
View File
@@ -58,6 +58,7 @@ struct Device {
#[serde(deny_unknown_fields)] #[serde(deny_unknown_fields)]
struct Plan { struct Plan {
tenant_id: Uuid, tenant_id: Uuid,
#[schemars(with = "crate::jobs::WebPlanInput")]
input: crate::jobs::PlanRequest, input: crate::jobs::PlanRequest,
} }
#[derive(Deserialize, schemars::JsonSchema)] #[derive(Deserialize, schemars::JsonSchema)]
@@ -126,7 +127,7 @@ fn tools() -> Vec<Tool> {
), ),
tool::<PlanScript>( tool::<PlanScript>(
"scripts.plan", "scripts.plan",
"Plan the selected immutable script revision against fixed assets. Submit the returned plan for WebUI approval via operations.submit.", "Plan the selected immutable script revision against fixed assets. Set input.execution_identity to select agent_service, root on Linux or system on Windows. Omitting it uses the revision default. Submit the plan for WebUI approval via operations.submit.",
), ),
tool::<Devices>( tool::<Devices>(
"updates.list_releases", "updates.list_releases",
@@ -138,11 +139,11 @@ fn tools() -> Vec<Tool> {
), ),
tool::<crate::monitoring::LogQuery>( tool::<crate::monitoring::LogQuery>(
"logs.query", "logs.query",
"Read stored bounded log evidence, or request a live query as a pending approval operation.", "Read stored bounded log evidence. Use a script job for a fresh collection.",
), ),
tool::<Plan>( tool::<Plan>(
"operations.plan", "operations.plan",
"Persist immutable exact job plan. No executable jobs are created.", "Plan a run_script operation for selected devices. The stored script and target list require interactive approval.",
), ),
tool::<Submit>( tool::<Submit>(
"operations.submit", "operations.submit",
@@ -156,10 +157,6 @@ fn tools() -> Vec<Tool> {
"jobs.cancel", "jobs.cancel",
"Request cancellation, not rollback or proof of termination.", "Request cancellation, not rollback or proof of termination.",
), ),
tool::<Tenant>(
"sessions.request",
"Unsupported until after MVP; never opens a shell.",
),
] ]
} }
fn parse<T: serde::de::DeserializeOwned>(v: Value) -> Result<T, crate::jobs::Error> { fn parse<T: serde::de::DeserializeOwned>(v: Value) -> Result<T, crate::jobs::Error> {
@@ -400,3 +397,37 @@ pub fn routes(r: Router<crate::State>, state: crate::State) -> Router<crate::Sta
r.nest_service("/mcp", service) r.nest_service("/mcp", service)
.route_layer(middleware::from_fn_with_state(state, guard)) .route_layer(middleware::from_fn_with_state(state, guard))
} }
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn plan_tool_advertises_the_script_wire_contract() {
let tools = tools();
let plan = tools
.iter()
.find(|tool| tool.name == "operations.plan")
.unwrap();
let schema = serde_json::to_string(&plan.input_schema).unwrap();
for field in [
"run_script",
"script_utf8",
"variants",
"execution_identity",
] {
assert!(schema.contains(field), "{field}");
}
for retired in [
"update_agent",
"reboot",
"query_logs",
"apt_manifest",
"windows_msi_manifest",
"dependency_group",
] {
assert!(!schema.contains(retired), "{retired}");
}
assert!(tools.iter().all(|tool| tool.name != "sessions.request"));
}
}
+4 -2
View File
@@ -17,9 +17,10 @@ use std::collections::BTreeSet;
use uuid::Uuid; use uuid::Uuid;
const PREFIX: &str = "rmm_mcp_"; const PREFIX: &str = "rmm_mcp_";
const SCOPES: [&str; 11] = [ const SCOPES: [&str; 12] = [
"inventory:read", "inventory:read",
"logs:read", "logs:read",
"logs:read_sensitive",
"operations:read", "operations:read",
"operations:plan", "operations:plan",
"operations:submit", "operations:submit",
@@ -371,7 +372,7 @@ async fn authenticate_pool(
name: principal, name: principal,
operator: effective operator: effective
.iter() .iter()
.any(|scope| !READ_SCOPES.contains(&scope.as_str())), .any(|scope| !READ_SCOPES.contains(&scope.as_str()) && scope != "logs:read_sensitive"),
session_hash: None, session_hash: None,
csrf: None, csrf: None,
scopes: Some(effective), scopes: Some(effective),
@@ -427,6 +428,7 @@ async fn enabled(pool: &PgPool, principal: &str, tenant: Uuid) -> bool {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
mod stored_logs;
#[test] #[test]
fn mcp_token_selection_is_explicit_and_bounded() { fn mcp_token_selection_is_explicit_and_bounded() {
@@ -0,0 +1,138 @@
use super::*;
use crate::monitoring::{LogQuery, query};
use std::sync::Arc;
#[tokio::test]
#[ignore = "requires the disposable RLS database from tests/local_access_database.py"]
async fn stored_results_require_current_log_rights_on_both_read_paths() {
let admin = PgPool::connect(&std::env::var("RMM_TEST_REPAIR_ADMIN_URL").unwrap())
.await
.unwrap();
let pool = PgPool::connect(&std::env::var("RMM_TEST_REPAIR_APP_URL").unwrap())
.await
.unwrap();
let tenant = Uuid::parse_str(rmm_domain::TENANT_A).unwrap();
let foreign = Uuid::parse_str(rmm_domain::TENANT_B).unwrap();
let asset = Uuid::new_v4();
let actor = format!("local:{}", Uuid::new_v4());
let temp = std::env::temp_dir().join(format!("stored-logs-{asset}"));
let state = crate::State {
pool,
signer: None,
viewer_a: [0; 32],
viewer_b: [1; 32],
auth: Arc::new(crate::auth::Auth::from_env("development").await.unwrap()),
job_signer: Arc::new(
crate::job_signer::JobSigner::load_or_create(&temp.join("key.pem")).unwrap(),
),
};
sqlx::query("INSERT INTO memberships(tenant_id,principal,kind,permissions) VALUES($1,$2,'human',ARRAY['tokens:manage','operations:read','logs:read','logs:read_sensitive'])")
.bind(tenant).bind(&actor).execute(&admin).await.unwrap();
let mut readers = Vec::new();
for scopes in [
vec!["operations:read"],
vec!["operations:read", "logs:read"],
vec!["operations:read", "logs:read", "logs:read_sensitive"],
] {
let (_, token) = mint(&state.pool, tenant, &actor, &scopes).await;
let p = authenticate_pool(&state.pool, &token, Some(tenant))
.await
.unwrap();
assert!(!p.operator);
readers.push(p);
}
// Terminal history with inert synthetic bytes, no gateway, outbox or permits.
sqlx::query("INSERT INTO assets(tenant_id,asset_id) VALUES($1,$2)")
.bind(tenant)
.bind(asset)
.execute(&admin)
.await
.unwrap();
sqlx::query("INSERT INTO agent_installations(tenant_id,agent_id,asset_id,certificate_sha256) VALUES($1,$2,$2,$3)").bind(tenant).bind(asset).bind(hash(asset.as_bytes())).execute(&admin).await.unwrap();
let operation = Uuid::new_v4();
sqlx::query("INSERT INTO operation_plans(tenant_id,plan_id,principal,payload,plan_hash,expires_at) VALUES($1,$2,$3,'{}','fixture',now())").bind(tenant).bind(operation).bind(&actor).execute(&admin).await.unwrap();
sqlx::query("INSERT INTO approval_requests(tenant_id,operation_id,plan_id,principal,idempotency_key,request_hash,approval_state) VALUES($1,$2,$2,$3,'fixture','fixture','approved')").bind(tenant).bind(operation).bind(&actor).execute(&admin).await.unwrap();
sqlx::query("INSERT INTO authorizations(tenant_id,authorization_id,operation_id,plan_id,plan_hash,principal,session_hash,approval_origin,testsimulation,policy_version) VALUES($1,$2,$2,$2,'fixture',$3,'fixture','dev_test_browser_simulation',true,1)").bind(tenant).bind(operation).bind(&actor).execute(&admin).await.unwrap();
sqlx::query("INSERT INTO operations VALUES($1,$2,$2)")
.bind(tenant)
.bind(operation)
.execute(&admin)
.await
.unwrap();
let until = Utc::now();
let since = until - Duration::minutes(5);
let query_for = |unit: &str| LogQuery {
tenant_id: tenant,
asset_id: asset,
since: since - Duration::seconds(1),
until: until + Duration::seconds(1),
unit: unit.into(),
max_lines: 10,
live: false,
idempotency_key: None,
};
let stored = json!({"exit_code":0,"stdout":[65],"stderr":[66],"evidence":{"fixture":true},"error_code":"fixture"});
let restricted = json!({"exit_code":0,"output_restricted":true});
let mut secure_job = Uuid::nil();
for (unit, classification) in [
("ordinary.service", Some(false)),
("custom-audit.service", Some(true)),
("legacy.service", None),
] {
let job = Uuid::new_v4();
let bytes = serde_json::to_vec(&json!({"action":{"action":"query_logs","unit":unit,"since":since,"until":until,"max_lines":10}})).unwrap();
sqlx::query("INSERT INTO jobs(tenant_id,job_id,attempt_id,operation_id,agent_id,asset_id,payload,payload_hash,state,resource,result,log_sensitive) VALUES($1,$2,$2,$3,$4,$4,$5,'fixture','succeeded','device_execution',$6,$7)")
.bind(tenant).bind(job).bind(operation).bind(asset).bind(bytes).bind(&stored).bind(classification).execute(&admin).await.unwrap();
for (index, p) in readers.iter().enumerate() {
let permitted = index == 2 || (index == 1 && classification == Some(false));
let detail = crate::jobs::job(&state, p, tenant, job).await.unwrap();
assert_eq!(detail["state"], "succeeded");
assert_eq!(
&detail["result"],
if permitted { &stored } else { &restricted }
);
let logs = query(&state, p, query_for(unit)).await;
if permitted {
assert_eq!(logs.unwrap()["items"][0]["result"], stored);
} else {
assert_eq!(logs.unwrap_err().0, StatusCode::FORBIDDEN);
}
}
if classification == Some(true) {
secure_job = job;
}
}
// Keep the previously authenticated reader and remove just the issuer's
// extra permission. The next read must consult current tenant membership.
sqlx::query("UPDATE memberships SET permissions=array_remove(permissions,'logs:read_sensitive') WHERE tenant_id=$1 AND principal=$2")
.bind(tenant).bind(&actor).execute(&admin).await.unwrap();
let reader = &readers[2];
assert_eq!(
crate::jobs::job(&state, reader, tenant, secure_job)
.await
.unwrap()["result"],
restricted
);
assert_eq!(
query(&state, reader, query_for("custom-audit.service"))
.await
.unwrap_err()
.0,
StatusCode::FORBIDDEN
);
assert_eq!(
crate::jobs::job(&state, reader, foreign, secure_job)
.await
.unwrap_err()
.0,
StatusCode::NOT_FOUND
);
let mut other = query_for("custom-audit.service");
other.tenant_id = foreign;
assert_eq!(
query(&state, reader, other).await.unwrap_err().0,
StatusCode::NOT_FOUND
);
std::fs::remove_dir_all(temp).unwrap();
}
+66 -113
View File
@@ -34,15 +34,45 @@ pub struct LogQuery {
pub since: DateTime<Utc>, pub since: DateTime<Utc>,
pub until: DateTime<Utc>, pub until: DateTime<Utc>,
pub max_lines: u32, pub max_lines: u32,
#[serde(default)]
#[schemars(skip)]
pub live: bool, pub live: bool,
#[schemars(skip)]
pub idempotency_key: Option<String>, pub idempotency_key: Option<String>,
} }
/// Both result endpoints use the reader's current token scope and tenant membership.
pub(crate) struct LogReadAccess {
ordinary: bool,
sensitive: bool,
}
impl LogReadAccess {
pub(crate) async fn for_principal(
tx: &mut sqlx::Transaction<'_, sqlx::Postgres>,
p: &crate::auth::Principal,
) -> Result<Self, crate::jobs::Error> {
let ordinary = p.permits_scope("logs:read")
&& crate::permissions::allowed(tx, &p.name, "logs:read").await?;
let sensitive = ordinary
&& p.permits_scope("logs:read_sensitive")
&& crate::permissions::allowed(tx, &p.name, "logs:read_sensitive").await?;
Ok(Self {
ordinary,
sensitive,
})
}
pub(crate) fn permits(&self, stored_sensitivity: Option<bool>) -> bool {
self.ordinary && (stored_sensitivity == Some(false) || self.sensitive)
}
}
pub async fn query( pub async fn query(
s: &crate::State, s: &crate::State,
p: &crate::auth::Principal, p: &crate::auth::Principal,
i: LogQuery, i: LogQuery,
) -> Result<Value, crate::jobs::Error> { ) -> Result<Value, crate::jobs::Error> {
crate::jobs::scope(p, i.tenant_id, true)?; crate::jobs::scope(p, i.tenant_id, i.live)?;
let action = rmm_domain::jobs::Action::QueryLogs { let action = rmm_domain::jobs::Action::QueryLogs {
unit: i.unit.clone(), unit: i.unit.clone(),
since: i.since, since: i.since,
@@ -56,92 +86,16 @@ pub async fn query(
)); ));
} }
if i.live { if i.live {
let request_hash = rmm_domain::jobs::hash(&serde_json::to_vec(&i)?); return Err(crate::jobs::Error(
let mut dedup = rmm_persistence::tenant_tx(&s.pool, i.tenant_id).await?; StatusCode::CONFLICT,
let key = i "SCRIPT_ACTION_REQUIRED",
.idempotency_key ));
.as_ref()
.filter(|k| !k.is_empty() && k.len() <= 128)
.ok_or(crate::jobs::Error(
StatusCode::BAD_REQUEST,
"VALIDATION_ERROR",
))?;
if let Some(row)=sqlx::query("SELECT request_hash,plan_id FROM live_query_requests WHERE principal=$1 AND idempotency_key=$2").bind(&p.name).bind(key).fetch_optional(&mut *dedup).await?{
if row.get::<String,_>("request_hash")!=request_hash{return Err(crate::jobs::Error(StatusCode::CONFLICT,"IDEMPOTENCY_CONFLICT"))}
let plan=row.get("plan_id");let key=key.clone();dedup.commit().await?;
return crate::jobs::submit(s,p,i.tenant_id,plan,crate::jobs::Submit{idempotency_key:key}).await;
}
dedup.commit().await?;
let key = i.idempotency_key.ok_or(crate::jobs::Error(
StatusCode::BAD_REQUEST,
"VALIDATION_ERROR",
))?;
let plan = crate::jobs::plan(
s,
p,
i.tenant_id,
crate::jobs::PlanInput {
targets: crate::jobs::Targets {
asset_ids: vec![i.asset_id],
},
action,
script_variants: vec![],
execution_identity: "agent_service".into(),
schedule: crate::jobs::Schedule {
not_before: Utc::now(),
start_before: Utc::now() + chrono::Duration::hours(1),
},
max_runtime_seconds: 30,
max_output_bytes: 262144,
rollout: crate::jobs::Rollout {
max_parallel: 1,
halt_after_failures: 1,
},
reason: format!("Requested live logs for {}", i.unit),
artifact_ids: vec![],
},
)
.await?;
let id = plan["plan_id"]
.as_str()
.and_then(|v| Uuid::parse_str(v).ok())
.ok_or(crate::jobs::Error(
StatusCode::INTERNAL_SERVER_ERROR,
"VALIDATION_ERROR",
))?;
let mut dedup = rmm_persistence::tenant_tx(&s.pool, i.tenant_id).await?;
sqlx::query(
"INSERT INTO live_query_requests VALUES($1,$2,$3,$4,$5) ON CONFLICT DO NOTHING",
)
.bind(i.tenant_id)
.bind(&p.name)
.bind(&key)
.bind(&request_hash)
.bind(id)
.execute(&mut *dedup)
.await?;
let canonical=sqlx::query("SELECT request_hash,plan_id FROM live_query_requests WHERE principal=$1 AND idempotency_key=$2").bind(&p.name).bind(&key).fetch_one(&mut *dedup).await?;
if canonical.get::<String, _>("request_hash") != request_hash {
return Err(crate::jobs::Error(
StatusCode::CONFLICT,
"IDEMPOTENCY_CONFLICT",
));
}
let id = canonical.get("plan_id");
dedup.commit().await?;
return crate::jobs::submit(
s,
p,
i.tenant_id,
id,
crate::jobs::Submit {
idempotency_key: key,
},
)
.await;
} }
let mut tx = rmm_persistence::tenant_tx(&s.pool, i.tenant_id).await?; let mut tx = rmm_persistence::tenant_tx(&s.pool, i.tenant_id).await?;
crate::permissions::require_principal(&mut tx, p, "logs:read").await?; let access = LogReadAccess::for_principal(&mut tx, p).await?;
if !access.ordinary {
return Err(crate::jobs::Error(StatusCode::FORBIDDEN, "FORBIDDEN"));
}
let exists: bool = sqlx::query_scalar("SELECT EXISTS(SELECT 1 FROM assets WHERE asset_id=$1)") let exists: bool = sqlx::query_scalar("SELECT EXISTS(SELECT 1 FROM assets WHERE asset_id=$1)")
.bind(i.asset_id) .bind(i.asset_id)
.fetch_one(&mut *tx) .fetch_one(&mut *tx)
@@ -149,38 +103,37 @@ pub async fn query(
if !exists { if !exists {
return Err(crate::jobs::Error(StatusCode::NOT_FOUND, "NOT_FOUND")); return Err(crate::jobs::Error(StatusCode::NOT_FOUND, "NOT_FOUND"));
} }
let rows=sqlx::query("SELECT j.job_id,j.payload,j.result FROM jobs j WHERE j.asset_id=$1 AND j.state='succeeded' AND j.result IS NOT NULL ORDER BY job_id LIMIT 100").bind(i.asset_id).fetch_all(&mut *tx).await?; let rows = sqlx::query(
"SELECT job_id, result, log_sensitive, action->>'since' AS observed_from, action->>'until' AS observed_until
FROM jobs CROSS JOIN LATERAL (SELECT convert_from(payload, 'UTF8')::jsonb->'action' AS action) AS log
WHERE asset_id=$1 AND state='succeeded' AND result IS NOT NULL AND action->>'action'='query_logs'
AND action->>'unit'=$2 AND (action->>'since')::timestamptz >= $3 AND (action->>'until')::timestamptz <= $4
ORDER BY job_id LIMIT 101",
).bind(i.asset_id).bind(&i.unit).bind(i.since).bind(i.until).fetch_all(&mut *tx).await?;
let mut items = Vec::new(); let mut items = Vec::new();
let mut size = 0; let mut size = 0;
let mut lines = 0usize; let mut lines = 0usize;
let mut truncated = false; let mut truncated = rows.len() > 100;
for r in rows { for r in rows.into_iter().take(100) {
let payload: rmm_domain::jobs::JobPayload = if !access.permits(r.get("log_sensitive")) {
serde_json::from_slice(&r.get::<Vec<u8>, _>("payload"))?; return Err(crate::jobs::Error(StatusCode::FORBIDDEN, "FORBIDDEN"));
if let rmm_domain::jobs::Action::QueryLogs {
unit, since, until, ..
} = payload.action
&& unit == i.unit
&& since >= i.since
&& until <= i.until
{
let result: Value = r.get("result");
let len = result.to_string().len();
let stdout = result.get("stdout").and_then(Value::as_array);
let count = stdout
.map(|bytes| {
bytes.iter().filter(|v| v.as_u64() == Some(10)).count()
+ usize::from(bytes.last().is_some_and(|v| v.as_u64() != Some(10)))
})
.unwrap_or(0);
if size + len > 262144 || lines + count > i.max_lines as usize {
truncated = true;
break;
}
size += len;
lines += count;
items.push(json!({"job_id":r.get::<Uuid,_>("job_id"),"source_id":unit,"observed_from":since,"observed_until":until,"result":result}));
} }
let result: Value = r.get("result");
let len = result.to_string().len();
let stdout = result.get("stdout").and_then(Value::as_array);
let count = stdout
.map(|bytes| {
bytes.iter().filter(|v| v.as_u64() == Some(10)).count()
+ usize::from(bytes.last().is_some_and(|v| v.as_u64() != Some(10)))
})
.unwrap_or(0);
if size + len > 262144 || lines + count > i.max_lines as usize {
truncated = true;
break;
}
size += len;
lines += count;
items.push(json!({"job_id":r.get::<Uuid,_>("job_id"),"source_id":i.unit,"observed_from":r.get::<String,_>("observed_from"),"observed_until":r.get::<String,_>("observed_until"),"result":result}));
} }
tx.commit().await?; tx.commit().await?;
Ok( Ok(
+41
View File
@@ -0,0 +1,41 @@
SELECT r.operation_id, r.created_at
FROM approval_requests r JOIN operation_plans p USING (tenant_id, plan_id)
CROSS JOIN LATERAL (SELECT convert_from(p.payload, 'UTF8')::jsonb AS payload) AS plan_view
LEFT JOIN LATERAL (
SELECT count(*) AS total, count(*) FILTER (WHERE state = 'unknown') AS unresolved,
count(*) FILTER (WHERE state = 'succeeded') AS succeeded,
count(*) FILTER (WHERE state = 'cancelled') AS cancelled,
count(*) FILTER (WHERE state IN ('succeeded','failed','cancelled','expired','closed_unknown')) AS terminal,
count(*) FILTER (WHERE state IN ('running','verifying','awaiting_reboot')) AS active
FROM jobs j WHERE j.tenant_id = r.tenant_id AND j.operation_id = r.operation_id
AND $7::text IS NOT NULL AND r.approval_state = 'approved'
) execution ON true
WHERE r.created_at <= $1
AND ($2::timestamptz IS NULL OR (r.created_at, r.operation_id) < ($2, $3))
AND ($4::timestamptz IS NULL OR r.created_at >= $4)
AND ($5::timestamptz IS NULL OR r.created_at < $5)
AND ($6::text IS NULL OR
strpos(lower(coalesce(plan_view.payload#>>'{script_revision,name}', '')), lower($6)) > 0 OR
strpos(lower(coalesce(plan_view.payload->>'reason', '')), lower($6)) > 0)
AND ($7::text IS NULL OR $7 = CASE
WHEN r.approval_state = 'pending_approval' AND p.expires_at <= now() THEN 'expired'
WHEN r.approval_state <> 'approved' OR execution.total = 0 THEN r.approval_state
WHEN execution.unresolved > 0 THEN 'needs_attention'
WHEN execution.succeeded = execution.total THEN 'succeeded'
WHEN execution.terminal = execution.total THEN CASE
WHEN execution.succeeded > 0 THEN 'partially_succeeded'
WHEN execution.cancelled = execution.total THEN 'cancelled' ELSE 'failed' END
WHEN execution.active > 0 THEN 'running' ELSE 'queued'
END)
AND ($8::text IS NULL OR EXISTS (
SELECT 1 FROM jsonb_array_elements(plan_view.payload->'jobs') AS job
LEFT JOIN LATERAL (
SELECT o.data->>'hostname' AS hostname FROM observations o
WHERE $10 AND o.tenant_id = r.tenant_id AND o.agent_id = (job#>>'{payload,agent_id}')::uuid
AND o.source_id IN ('linux.base','windows.base')
ORDER BY o.observed_at DESC, o.received_at DESC, o.sequence DESC LIMIT 1
) inventory ON true
WHERE job#>>'{payload,asset_id}' = $9::uuid::text
OR strpos(lower(coalesce(inventory.hostname, '')), lower($8)) > 0
))
ORDER BY r.created_at DESC, r.operation_id DESC LIMIT $11
+23
View File
@@ -13,9 +13,32 @@ SELECT p.tenant_id, p.name AS customer_name, p.plan_id, p.plan_hash,
p.payload#>>'{jobs,0,payload,action,action}' AS action, p.payload#>>'{jobs,0,payload,action,action}' AS action,
CASE WHEN r.approval_state='pending_approval' AND p.expires_at <= now() CASE WHEN r.approval_state='pending_approval' AND p.expires_at <= now()
THEN 'expired' ELSE r.approval_state END AS approval_state, THEN 'expired' ELSE r.approval_state END AS approval_state,
CASE
WHEN decision.event_id IS NOT NULL THEN jsonb_build_object(
'principal', decision.principal, 'at', decision.created_at,
'testsimulation', decision.data->'testsimulation' = 'true'::jsonb)
WHEN r.approval_state = 'approved' AND approved.authorization_id IS NOT NULL THEN jsonb_build_object(
'principal', approved.principal, 'at', approved.created_at,
'testsimulation', approved.testsimulation)
END AS decision,
coalesce(targets.items, '[]'::jsonb) AS targets coalesce(targets.items, '[]'::jsonb) AS targets
FROM selected p FROM selected p
LEFT JOIN approval_requests r USING (tenant_id,plan_id) LEFT JOIN approval_requests r USING (tenant_id,plan_id)
LEFT JOIN authorizations approved ON approved.tenant_id = p.tenant_id
AND approved.operation_id = r.operation_id AND approved.plan_id = p.plan_id
LEFT JOIN LATERAL (
SELECT e.event_id, e.principal, e.created_at, e.data
FROM audit_events e
WHERE e.tenant_id = p.tenant_id AND e.data->>'operation_id' = r.operation_id::text
AND e.data->>'plan_id' = p.plan_id::text
AND e.event_type IN ('plan_revoked', 'plan_authorization')
AND ((r.approval_state = 'revoked' AND e.event_type = 'plan_revoked')
OR (e.event_type = 'plan_authorization'
AND e.data->>'plan_hash' = p.plan_hash
AND e.data->>'decision' = CASE r.approval_state WHEN 'approved' THEN 'approve' WHEN 'rejected' THEN 'reject' END))
ORDER BY e.created_at, e.event_id
LIMIT 1
) decision ON true
LEFT JOIN LATERAL ( LEFT JOIN LATERAL (
SELECT jsonb_agg(jsonb_build_object( SELECT jsonb_agg(jsonb_build_object(
'asset_id', j#>>'{payload,asset_id}', 'agent_id', j#>>'{payload,agent_id}', 'asset_id', j#>>'{payload,asset_id}', 'agent_id', j#>>'{payload,agent_id}',
+57 -21
View File
@@ -20,7 +20,7 @@ pub struct RootPolicy {
} }
#[derive(Deserialize)] #[derive(Deserialize)]
#[serde(deny_unknown_fields)] #[serde(deny_unknown_fields)]
struct RootScope { pub(crate) struct RootScope {
tenant_id: Uuid, tenant_id: Uuid,
asset_id: Uuid, asset_id: Uuid,
agent_id: Uuid, agent_id: Uuid,
@@ -85,6 +85,15 @@ fn parse_log_units(raw: Option<&str>) -> Result<Option<Vec<String>>, Error> {
} }
Ok(Some(units)) Ok(Some(units))
} }
fn configured_sensitive_units() -> Result<Option<Vec<String>>, Error> {
match std::env::var("RMM_ROOT_SENSITIVE_LOG_UNITS") {
Ok(raw) => parse_log_units(Some(&raw)),
Err(std::env::VarError::NotPresent) => Ok(None),
Err(std::env::VarError::NotUnicode(_)) => {
Err(Error(StatusCode::CONFLICT, "ROOT_LOG_ALLOWLIST_INVALID"))
}
}
}
impl RootLogPolicy { impl RootLogPolicy {
fn valid(&self) -> bool { fn valid(&self) -> bool {
self.schema_version == 1 self.schema_version == 1
@@ -92,17 +101,45 @@ impl RootLogPolicy {
&& valid_log_units(&self.sensitive_units) && valid_log_units(&self.sensitive_units)
} }
} }
impl RootPolicy { fn sensitive_log_unit(
fn sensitive_log_unit(&self, job: &JobPayload, unit: &str, extra: Option<&[String]>) -> bool { policy: Option<&RootPolicy>,
matches!(unit, "ssh.service" | "sshd.service" | "auditd.service" | "systemd-logind.service") job: &JobPayload,
|| (unit.starts_with("sshd@") && unit.ends_with(".service")) unit: &str,
|| extra.is_some_and(|units| units.iter().any(|u| u == unit)) extra: Option<&[String]>,
// Classification is shared across matching target scopes, not just ) -> bool {
// the first scope/actor that grants a unit. Another scope cannot matches!(unit, "ssh.service" | "sshd.service" | "auditd.service" | "systemd-logind.service")
// silently declassify a sensitive source. || (unit.starts_with("sshd@") && unit.ends_with(".service"))
|| self.scopes.iter().any(|scope| scope.matches_target(job) || extra.is_some_and(|units| units.iter().any(|u| u == unit))
&& scope.root_logs.as_ref().is_some_and(|logs| logs.sensitive_units.iter().any(|u| u == unit))) // Any matching scope can classify the source, regardless of principal.
} || policy.is_some_and(|p| p.scopes.iter().any(|scope| scope.matches_target(job)
&& scope.root_logs.as_ref().is_some_and(|logs| logs.sensitive_units.iter().any(|u| u == unit))))
}
/// Record the source classification alongside the grant. Readers in a separate
/// API profile cannot reconstruct an expired or replaced gateway policy.
pub(crate) fn stored_log_sensitivity(job: &JobPayload) -> Option<bool> {
let Action::QueryLogs { unit, .. } = &job.action else {
return None;
};
let Ok(extra) = configured_sensitive_units() else {
return Some(true);
};
let policy = if std::env::var_os("RMM_DEV_ROOT_POLICY_FILE").is_some()
|| std::env::var("RMM_DEV_ROOT_ENABLED").as_deref() == Ok("true")
{
let Ok(policy) = load() else {
return Some(true);
};
Some(policy)
} else {
None
};
Some(sensitive_log_unit(
policy.as_ref(),
job,
unit,
extra.as_deref(),
))
} }
fn required_permissions(job: &JobPayload, sensitive_log: bool) -> Vec<&'static str> { fn required_permissions(job: &JobPayload, sensitive_log: bool) -> Vec<&'static str> {
let mut permissions = vec!["root:execute"]; let mut permissions = vec!["root:execute"];
@@ -158,7 +195,7 @@ impl RootScope {
&& self.enrollment_generation == job.enrollment_generation && self.enrollment_generation == job.enrollment_generation
&& self.assignment_version == job.assignment_version && self.assignment_version == job.assignment_version
} }
fn permits( pub(crate) fn permits(
&self, &self,
principal: &str, principal: &str,
job: &JobPayload, job: &JobPayload,
@@ -338,6 +375,11 @@ pub async fn authorize(
for permission in required_permissions(job, false) { for permission in required_permissions(job, false) {
crate::permissions::require(tx, principal, permission).await?; crate::permissions::require(tx, principal, permission).await?;
} }
let caps:serde_json::Value=sqlx::query_scalar("SELECT capabilities FROM agent_installations WHERE agent_id=$1 AND asset_id=$2 AND revoked_at IS NULL AND enrollment_generation=$3 AND assignment_version=$4").bind(job.agent_id).bind(job.asset_id).bind(i64::try_from(job.enrollment_generation).map_err(|_|Error(StatusCode::CONFLICT,"BINDING_MISMATCH"))?).bind(i64::try_from(job.assignment_version).map_err(|_|Error(StatusCode::CONFLICT,"BINDING_MISMATCH"))?).fetch_optional(&mut **tx).await?.ok_or(Error(StatusCode::CONFLICT,"AUTHORIZATION_REVOKED"))?;
let caps: Vec<String> = serde_json::from_value(caps)?;
if crate::managed_scripts::permits(tx, principal, job, &caps).await? {
return Ok(());
}
let policy = load()?; let policy = load()?;
let global_log_units = if matches!(job.action, Action::QueryLogs { .. }) { let global_log_units = if matches!(job.action, Action::QueryLogs { .. }) {
parse_log_units(std::env::var("RMM_ROOT_LOG_UNITS").ok().as_deref())? parse_log_units(std::env::var("RMM_ROOT_LOG_UNITS").ok().as_deref())?
@@ -345,19 +387,13 @@ pub async fn authorize(
None None
}; };
if let Action::QueryLogs { unit, .. } = &job.action { if let Action::QueryLogs { unit, .. } = &job.action {
let sensitive_units = parse_log_units( let sensitive_units = configured_sensitive_units()?;
std::env::var("RMM_ROOT_SENSITIVE_LOG_UNITS") if sensitive_log_unit(Some(&policy), job, unit, sensitive_units.as_deref()) {
.ok()
.as_deref(),
)?;
if policy.sensitive_log_unit(job, unit, sensitive_units.as_deref()) {
// Re-read current membership on every planning/approval/start call. // Re-read current membership on every planning/approval/start call.
// No policy flag, viewer role, capability or test profile grants it. // No policy flag, viewer role, capability or test profile grants it.
crate::permissions::require(tx, principal, "logs:read_sensitive").await?; crate::permissions::require(tx, principal, "logs:read_sensitive").await?;
} }
} }
let caps:serde_json::Value=sqlx::query_scalar("SELECT capabilities FROM agent_installations WHERE agent_id=$1 AND asset_id=$2 AND revoked_at IS NULL AND enrollment_generation=$3 AND assignment_version=$4").bind(job.agent_id).bind(job.asset_id).bind(i64::try_from(job.enrollment_generation).map_err(|_|Error(StatusCode::CONFLICT,"BINDING_MISMATCH"))?).bind(i64::try_from(job.assignment_version).map_err(|_|Error(StatusCode::CONFLICT,"BINDING_MISMATCH"))?).fetch_optional(&mut **tx).await?.ok_or(Error(StatusCode::CONFLICT,"AUTHORIZATION_REVOKED"))?;
let caps: Vec<String> = serde_json::from_value(caps)?;
if !policy if !policy
.scopes .scopes
.iter() .iter()
+71 -3
View File
@@ -38,6 +38,7 @@ pub struct Selection {
pub reason: String, pub reason: String,
pub max_runtime_seconds: u32, pub max_runtime_seconds: u32,
pub max_output_bytes: u32, pub max_output_bytes: u32,
pub execution_identity: Option<String>,
} }
fn script(interpreter: &str, identity: &str, body: String) -> Result<Action, Error> { fn script(interpreter: &str, identity: &str, body: String) -> Result<Action, Error> {
@@ -169,7 +170,9 @@ pub async fn plan(
version: row.get("version"), version: row.get("version"),
script_sha256: hash(body.as_bytes()), script_sha256: hash(body.as_bytes()),
}; };
let identity: String = row.get("execution_identity"); let identity = input
.execution_identity
.unwrap_or_else(|| row.get("execution_identity"));
let action = script(row.get("interpreter"), &identity, body)?; let action = script(row.get("interpreter"), &identity, body)?;
let plan = PlanInput { let plan = PlanInput {
targets: input.targets, targets: input.targets,
@@ -183,7 +186,7 @@ pub async fn plan(
reason: input.reason, reason: input.reason,
artifact_ids: vec![], artifact_ids: vec![],
}; };
jobs::plan_resolved(s, p, tenant, plan, None, Some(reference)).await jobs::plan_resolved(s, p, tenant, plan, Some(reference)).await
} }
pub(crate) fn validate_plan_bindings(plan: &rmm_domain::jobs::PlanPayload) -> Result<(), Error> { pub(crate) fn validate_plan_bindings(plan: &rmm_domain::jobs::PlanPayload) -> Result<(), Error> {
@@ -259,7 +262,71 @@ pub(crate) mod tests {
) { ) {
let tenant = p.tenant; let tenant = p.tenant;
let initial = list(s, p, tenant, PageQuery::default()).await.unwrap(); let initial = list(s, p, tenant, PageQuery::default()).await.unwrap();
let template = &initial["items"][0]; let items = initial["items"].as_array().unwrap();
assert_eq!(items.len(), 16);
for (name, interpreter, identity, version) in [
("Linux neu starten", "posix_sh", "root", 1),
("Windows neu starten", "powershell", "system", 2),
] {
let revision = items.iter().find(|r| r["name"] == name && r["version"] == version).unwrap();
assert_eq!(revision["interpreter"], interpreter);
assert_eq!(revision["execution_identity"], identity);
assert_eq!(
revision["script_sha256"],
hash(revision["script_utf8"].as_str().unwrap().as_bytes())
);
}
let template = items
.iter()
.find(|item| item["name"] == "Windows-Updates installieren")
.unwrap();
for (prefix, interpreter, asset) in [
("Linux · ", "posix_sh", linux),
("Windows · ", "powershell", windows),
] {
let revisions: Vec<_> = items
.iter()
.filter(|item| item["name"].as_str().unwrap().starts_with(prefix))
.collect();
assert_eq!(revisions.len(), 6);
for row in revisions {
let identity = if row["name"] == "Windows · Betriebssystem-Updatebedarf anzeigen" {
"system"
} else {
"agent_service"
};
assert_eq!(row["interpreter"], interpreter);
assert_eq!(row["execution_identity"], identity);
assert_eq!(row["version"], 1);
let id = Uuid::parse_str(row["revision_id"].as_str().unwrap()).unwrap();
let selection = Selection {
targets: Targets {
asset_ids: vec![asset],
},
schedule: Schedule {
not_before: Utc::now(),
start_before: Utc::now() + Duration::minutes(30),
},
rollout: Rollout {
max_parallel: 1,
halt_after_failures: 1,
},
reason: "standard diagnostic library contract".into(),
max_runtime_seconds: 120,
max_output_bytes: 65536,
execution_identity: None,
};
let planned = plan(s, p, tenant, id, selection).await;
if identity == "system" {
assert_eq!(planned.unwrap_err().0, StatusCode::FORBIDDEN);
} else {
assert_eq!(
planned.unwrap()["plan_payload"]["script_revision"]["script_sha256"],
row["script_sha256"]
);
}
}
}
assert_eq!(template["name"], "Windows-Updates installieren"); assert_eq!(template["name"], "Windows-Updates installieren");
assert_eq!(template["interpreter"], "powershell"); assert_eq!(template["interpreter"], "powershell");
let native = script( let native = script(
@@ -343,6 +410,7 @@ pub(crate) mod tests {
reason: "isolated library contract".into(), reason: "isolated library contract".into(),
max_runtime_seconds: 60, max_runtime_seconds: 60,
max_output_bytes: 4096, max_output_bytes: 4096,
execution_identity: None,
}; };
assert_eq!( assert_eq!(
plan(s, p, tenant, id, selection(windows)) plan(s, p, tenant, id, selection(windows))
+5 -3
View File
@@ -51,8 +51,8 @@ fn regular(file: &File, owner: u32, expected_size: u64) -> Result<fs::Metadata>
impl UpdateArtifacts { impl UpdateArtifacts {
pub fn new(profile: &str, root: PathBuf, owner: u32) -> Result<Self> { pub fn new(profile: &str, root: PathBuf, owner: u32) -> Result<Self> {
ensure!( ensure!(
profile == "development", matches!(profile, "development" | "production") && root.is_absolute(),
"update object adapter is development-only" "release store requires a configured profile and absolute path"
); );
Self::private_directory(root, owner) Self::private_directory(root, owner)
} }
@@ -246,7 +246,9 @@ mod tests {
fs::set_permissions(&root, fs::Permissions::from_mode(0o700)).unwrap(); fs::set_permissions(&root, fs::Permissions::from_mode(0o700)).unwrap();
let owner = fs::metadata(&root).unwrap().uid(); let owner = fs::metadata(&root).unwrap().uid();
let store = UpdateArtifacts::new("development", root.clone(), owner).unwrap(); let store = UpdateArtifacts::new("development", root.clone(), owner).unwrap();
assert!(UpdateArtifacts::new("production", root.clone(), owner).is_err()); assert!(UpdateArtifacts::new("production", root.clone(), owner).is_ok());
assert!(UpdateArtifacts::new("unknown", root.clone(), owner).is_err());
assert!(UpdateArtifacts::new("production", PathBuf::from("relative"), owner).is_err());
let tenant = Uuid::new_v4(); let tenant = Uuid::new_v4();
let bytes = vec![37_u8; 300_007]; let bytes = vec![37_u8; 300_007];
let hash = rmm_domain::jobs::hash(&bytes); let hash = rmm_domain::jobs::hash(&bytes);
+5 -2
View File
@@ -6,8 +6,10 @@ use axum::{
extract::{Path, Query, State}, extract::{Path, Query, State},
http::{HeaderMap, StatusCode}, http::{HeaderMap, StatusCode},
}; };
#[cfg(test)]
use rmm_domain::jobs::Action;
use rmm_domain::{ use rmm_domain::{
jobs::{Action, ArtifactReference, JobPayload, PlanPayload, RecipeReference, encode, hash}, jobs::{ArtifactReference, JobPayload, PlanPayload, RecipeReference, encode, hash},
windows_execution::{MSI_PACKAGE_ID, ResolvedWindowsMsi, WindowsMsiRecipe}, windows_execution::{MSI_PACKAGE_ID, ResolvedWindowsMsi, WindowsMsiRecipe},
}; };
use serde_json::{Value, json}; use serde_json::{Value, json};
@@ -72,7 +74,8 @@ pub async fn references(
checked(tx, m).await?; checked(tx, m).await?;
Ok(vec![reference(m)]) Ok(vec![reference(m)])
} }
pub async fn automatic_artifacts( #[cfg(test)]
pub(crate) async fn automatic_artifacts(
tx: &mut Transaction<'_, Postgres>, tx: &mut Transaction<'_, Postgres>,
tenant: Uuid, tenant: Uuid,
action: &Action, action: &Action,
+73 -13
View File
@@ -25,7 +25,7 @@ struct SystemPolicy {
} }
#[derive(Deserialize)] #[derive(Deserialize)]
#[serde(deny_unknown_fields)] #[serde(deny_unknown_fields)]
struct SystemScope { pub(crate) struct SystemScope {
tenant_id: Uuid, tenant_id: Uuid,
asset_id: Uuid, asset_id: Uuid,
agent_id: Uuid, agent_id: Uuid,
@@ -38,6 +38,8 @@ struct SystemScope {
acceptance_evidence_id: Uuid, acceptance_evidence_id: Uuid,
allowed_services: Vec<String>, allowed_services: Vec<String>,
#[serde(default, deserialize_with = "strict_optional_hashes")] #[serde(default, deserialize_with = "strict_optional_hashes")]
allowed_script_sha256: Option<Vec<String>>,
#[serde(default, deserialize_with = "strict_optional_hashes")]
allowed_msi_recipe_sha256: Option<Vec<String>>, allowed_msi_recipe_sha256: Option<Vec<String>>,
max_runtime_seconds: u32, max_runtime_seconds: u32,
#[serde( #[serde(
@@ -76,7 +78,7 @@ fn fixture_service(name: &str) -> bool {
.all(|c| c.is_ascii_alphanumeric() || b"_-".contains(&c)) .all(|c| c.is_ascii_alphanumeric() || b"_-".contains(&c))
} }
impl SystemScope { impl SystemScope {
fn valid(&self) -> bool { pub(crate) fn valid(&self) -> bool {
!self.tenant_id.is_nil() !self.tenant_id.is_nil()
&& !self.asset_id.is_nil() && !self.asset_id.is_nil()
&& !self.agent_id.is_nil() && !self.agent_id.is_nil()
@@ -97,6 +99,15 @@ impl SystemScope {
.collect::<std::collections::BTreeSet<_>>() .collect::<std::collections::BTreeSet<_>>()
.len() .len()
== self.principals.len() == self.principals.len()
&& self.allowed_script_sha256.as_ref().is_none_or(|hashes| {
hashes.len() <= 64
&& hashes.iter().all(|h| digest(h))
&& hashes
.iter()
.collect::<std::collections::BTreeSet<_>>()
.len()
== hashes.len()
})
&& self.allowed_services.len() <= 16 && self.allowed_services.len() <= 16
&& self && self
.allowed_services .allowed_services
@@ -127,7 +138,7 @@ impl SystemScope {
&& rmm_domain::jobs::valid_windows_update_limit(self.windows_update_max_runtime_seconds) && rmm_domain::jobs::valid_windows_update_limit(self.windows_update_max_runtime_seconds)
&& (1..=120).contains(&self.max_runtime_seconds) && (1..=120).contains(&self.max_runtime_seconds)
} }
fn permits( pub(crate) fn permits(
&self, &self,
principal: &str, principal: &str,
job: &JobPayload, job: &JobPayload,
@@ -178,8 +189,16 @@ impl SystemScope {
&& has("system:set_service_state") && has("system:set_service_state")
&& has("set_service_state") && has("set_service_state")
} }
Action::RunScript { .. } => { Action::RunScript {
script_utf8,
arguments,
..
} => {
allow_scripts allow_scripts
&& self.allowed_script_sha256.as_ref().is_none_or(|hashes| {
arguments.is_empty()
&& hashes.contains(&rmm_domain::jobs::hash(script_utf8.as_bytes()))
})
&& job.action.full_maintenance() && 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( v.contains(
@@ -293,7 +312,7 @@ fn protected_parent_chain(path: &Path, owner: u32) -> Result<(), Error> {
} }
Ok(()) Ok(())
} }
fn protected_bytes(path: &Path, owner: u32) -> Result<Vec<u8>, Error> { pub(crate) fn protected_bytes(path: &Path, owner: u32) -> Result<Vec<u8>, Error> {
no_symlink_components(path)?; no_symlink_components(path)?;
protected_parent_chain(path, owner)?; protected_parent_chain(path, owner)?;
let before = fs::symlink_metadata(path).map_err(|_| disabled())?; let before = fs::symlink_metadata(path).map_err(|_| disabled())?;
@@ -374,9 +393,12 @@ pub async fn authorize(
if matches!(job.action, Action::RunScript { .. }) { if matches!(job.action, Action::RunScript { .. }) {
crate::permissions::require(tx, principal, "scripts:execute").await?; crate::permissions::require(tx, principal, "scripts:execute").await?;
} }
let policy = load()?;
let caps:serde_json::Value=sqlx::query_scalar("SELECT capabilities FROM agent_installations WHERE tenant_id=$1 AND agent_id=$2 AND asset_id=$3 AND revoked_at IS NULL AND enrollment_generation=$4 AND assignment_version=$5").bind(job.tenant_id).bind(job.agent_id).bind(job.asset_id).bind(i64::try_from(job.enrollment_generation).map_err(|_|Error(StatusCode::CONFLICT,"BINDING_MISMATCH"))?).bind(i64::try_from(job.assignment_version).map_err(|_|Error(StatusCode::CONFLICT,"BINDING_MISMATCH"))?).fetch_optional(&mut **tx).await?.ok_or(Error(StatusCode::CONFLICT,"AUTHORIZATION_REVOKED"))?; let caps:serde_json::Value=sqlx::query_scalar("SELECT capabilities FROM agent_installations WHERE tenant_id=$1 AND agent_id=$2 AND asset_id=$3 AND revoked_at IS NULL AND enrollment_generation=$4 AND assignment_version=$5").bind(job.tenant_id).bind(job.agent_id).bind(job.asset_id).bind(i64::try_from(job.enrollment_generation).map_err(|_|Error(StatusCode::CONFLICT,"BINDING_MISMATCH"))?).bind(i64::try_from(job.assignment_version).map_err(|_|Error(StatusCode::CONFLICT,"BINDING_MISMATCH"))?).fetch_optional(&mut **tx).await?.ok_or(Error(StatusCode::CONFLICT,"AUTHORIZATION_REVOKED"))?;
let capabilities: Vec<String> = serde_json::from_value(caps)?; let capabilities: Vec<String> = serde_json::from_value(caps)?;
if crate::managed_scripts::permits(tx, principal, job, &capabilities).await? {
return Ok(());
}
let policy = load()?;
if !policy.permits(principal, job, &capabilities, Utc::now()) { if !policy.permits(principal, job, &capabilities, Utc::now()) {
return Err(Error( return Err(Error(
StatusCode::FORBIDDEN, StatusCode::FORBIDDEN,
@@ -566,6 +588,27 @@ mod tests {
policy.schema_version = 3; policy.schema_version = 3;
assert!(policy.permits("selected", &job, &caps, Utc::now())); assert!(policy.permits("selected", &job, &caps, Utc::now()));
assert!(!policy.permits("foreign", &job, &caps, Utc::now())); assert!(!policy.permits("foreign", &job, &caps, Utc::now()));
policy.scopes[0].allowed_script_sha256 = Some(vec![]);
assert!(!policy.permits("selected", &job, &caps, Utc::now()));
policy.scopes[0].allowed_script_sha256 =
Some(vec![rmm_domain::jobs::hash(b"Write-Output 'hi'\r\n")]);
assert!(policy.permits("selected", &job, &caps, Utc::now()));
let mut changed = job.clone();
if let Action::RunScript { arguments, .. } = &mut changed.action {
arguments.push("unexpected".into());
}
assert!(!policy.permits("selected", &changed, &caps, Utc::now()));
if let Action::RunScript {
arguments,
script_utf8,
..
} = &mut changed.action
{
arguments.clear();
script_utf8.push(' ');
}
assert!(!policy.permits("selected", &changed, &caps, Utc::now()));
policy.scopes[0].allowed_script_sha256 = None;
let general = job.action.clone(); let general = job.action.clone();
job.action = Action::RunScript { job.action = Action::RunScript {
interpreter: "powershell".into(), interpreter: "powershell".into(),
@@ -597,13 +640,25 @@ mod tests {
} }
#[test] #[test]
fn windows_update_window_accepts_only_the_two_fixed_scripts() { fn windows_update_window_accepts_only_the_two_fixed_scripts() {
use rmm_domain::jobs::{PrivilegedScriptProfile, WindowsExecutionProfile, WINDOWS_UPDATE_IDENTITY_PROBE, WINDOWS_UPDATE_LONG_CAPABILITY, WINDOWS_UPDATE_SCRIPT_UTF8}; use rmm_domain::jobs::{
PrivilegedScriptProfile, WINDOWS_UPDATE_IDENTITY_PROBE, WINDOWS_UPDATE_LONG_CAPABILITY,
WINDOWS_UPDATE_SCRIPT_UTF8, WindowsExecutionProfile,
};
let (mut policy, mut job, mut caps) = fixture(); let (mut policy, mut job, mut caps) = fixture();
policy.schema_version = 3; policy.schema_version = 3;
let scope = &mut policy.scopes[0]; let scope = &mut policy.scopes[0];
scope.allowed_services.clear(); scope.allowed_services.clear();
scope.windows_update_max_runtime_seconds = Some(3600); scope.windows_update_max_runtime_seconds = Some(3600);
caps.extend(["run_script", "system:run_script", "script.powershell/1", "script.powershell.process_remote_signed/1", WINDOWS_UPDATE_LONG_CAPABILITY].map(str::to_owned)); caps.extend(
[
"run_script",
"system:run_script",
"script.powershell/1",
"script.powershell.process_remote_signed/1",
WINDOWS_UPDATE_LONG_CAPABILITY,
]
.map(str::to_owned),
);
for (script, seconds, expected) in [ for (script, seconds, expected) in [
(WINDOWS_UPDATE_SCRIPT_UTF8, 3600, true), (WINDOWS_UPDATE_SCRIPT_UTF8, 3600, true),
(WINDOWS_UPDATE_IDENTITY_PROBE, 30, true), (WINDOWS_UPDATE_IDENTITY_PROBE, 30, true),
@@ -611,13 +666,18 @@ mod tests {
("Write-Output 12", 30, false), ("Write-Output 12", 30, false),
] { ] {
job.action = Action::RunScript { job.action = Action::RunScript {
interpreter:"powershell".into(), script_utf8:script.into(), interpreter: "powershell".into(),
arguments:vec![], expected_stdout:None, script_utf8: script.into(),
windows_execution_profile:Some(WindowsExecutionProfile::PowerShell51RemoteSigned), arguments: vec![],
privileged_script_profile:Some(PrivilegedScriptProfile::FullMaintenanceV1), expected_stdout: None,
windows_execution_profile: Some(WindowsExecutionProfile::PowerShell51RemoteSigned),
privileged_script_profile: Some(PrivilegedScriptProfile::FullMaintenanceV1),
}; };
job.max_runtime_seconds = seconds; job.max_runtime_seconds = seconds;
assert_eq!(policy.permits("selected", &job, &caps, Utc::now()), expected); assert_eq!(
policy.permits("selected", &job, &caps, Utc::now()),
expected
);
} }
} }
#[test] #[test]
+1 -1
View File
@@ -11,7 +11,7 @@ hex.workspace = true
serde_json.workspace = true serde_json.workspace = true
uuid.workspace = true uuid.workspace = true
ed25519-dalek = "=2.2.0" ed25519-dalek = "=2.2.0"
rusqlite = { version = "0.32.1", features = ["bundled"] } rusqlite.workspace = true
rmm-domain = { path = "../domain" } rmm-domain = { path = "../domain" }
rmm-agent-core = { path = "../agent-core" } rmm-agent-core = { path = "../agent-core" }
rmm-updater = { path = "../updater" } rmm-updater = { path = "../updater" }
+3 -11
View File
@@ -218,11 +218,7 @@ fn current_keyring(file: &UpdateKeyringFile) -> Result<UpdateKeyring> {
.map_err(|_| anyhow::anyhow!("UPDATE_HISTORY_KEY_SIZE"))?; .map_err(|_| anyhow::anyhow!("UPDATE_HISTORY_KEY_SIZE"))?;
keys.push(TrustedUpdateKey::new( keys.push(TrustedUpdateKey::new(
public, public,
match key.platform { key.platform.into(),
Platform::LinuxX64 => ReleasePlatform::LinuxX64,
Platform::WindowsX64 => ReleasePlatform::WindowsX64,
Platform::WindowsGnuX64 => ReleasePlatform::WindowsGnuX64,
},
key.first_sequence, key.first_sequence,
key.last_sequence, key.last_sequence,
key.revoked, key.revoked,
@@ -307,11 +303,7 @@ fn verify_record_release(
.release_envelope .release_envelope
.decode() .decode()
.map_err(anyhow::Error::msg)?; .map_err(anyhow::Error::msg)?;
let platform = match record.platform { let platform = ReleasePlatform::from(record.platform);
Platform::LinuxX64 => ReleasePlatform::LinuxX64,
Platform::WindowsX64 => ReleasePlatform::WindowsX64,
Platform::WindowsGnuX64 => ReleasePlatform::WindowsGnuX64,
};
let envelope: &ReleaseEnvelope = &record.release_envelope; let envelope: &ReleaseEnvelope = &record.release_envelope;
verify_release( verify_release(
SignedRelease { SignedRelease {
@@ -403,7 +395,7 @@ fn verify_update(
ensure!( ensure!(
job.execution_identity job.execution_identity
== match record.platform { == match record.platform {
Platform::LinuxX64 => "root", Platform::LinuxX64 | Platform::LinuxArm64 => "root",
Platform::WindowsX64 | Platform::WindowsGnuX64 => "system", Platform::WindowsX64 | Platform::WindowsGnuX64 => "system",
} }
&& update.release_envelope == record.release_envelope && update.release_envelope == record.release_envelope
+1 -1
View File
@@ -16,7 +16,7 @@ serde.workspace = true
serde_json.workspace = true serde_json.workspace = true
uuid.workspace = true uuid.workspace = true
libc = "0.2.177" libc = "0.2.177"
rusqlite = { version = "0.32.1", features = ["bundled"] } rusqlite.workspace = true
ed25519-dalek = "=2.2.0" ed25519-dalek = "=2.2.0"
base64 = "=0.22.1" base64 = "=0.22.1"
rmm-domain = { path = "../domain" } rmm-domain = { path = "../domain" }
+1 -1
View File
@@ -45,7 +45,7 @@ mod linux {
let args: Vec<_> = std::env::args_os().skip(1).collect(); let args: Vec<_> = std::env::args_os().skip(1).collect();
if args.first().is_some_and(|arg| arg == "--verify-bootstrap") { if args.first().is_some_and(|arg| arg == "--verify-bootstrap") {
let release = let release =
rmm_updater::verify_bootstrap_files(rmm_updater::Platform::LinuxX64, &args[1..])?; rmm_updater::verify_bootstrap_files(rmm_domain::agent_update::Platform::NATIVE_LINUX.into(), &args[1..])?;
println!("{}", serde_json::to_string(release.manifest())?); println!("{}", serde_json::to_string(release.manifest())?);
return Ok(()); return Ok(());
} }
+2 -7
View File
@@ -4,7 +4,7 @@ use crate::{
VerifiedRelease, VerifiedRelease,
}; };
use anyhow::{Context, Result, ensure}; use anyhow::{Context, Result, ensure};
use rmm_domain::agent_update::{Platform as WirePlatform, ReleaseEnvelope, UpdateKeyringFile}; use rmm_domain::agent_update::{ReleaseEnvelope, UpdateKeyringFile};
use std::{ use std::{
ffi::OsString, ffi::OsString,
fs::File, fs::File,
@@ -31,18 +31,13 @@ pub fn verify_bootstrap_files(platform: Platform, args: &[OsString]) -> Result<V
.keys .keys
.into_iter() .into_iter()
.map(|key| { .map(|key| {
let platform = match key.platform {
WirePlatform::LinuxX64 => Platform::LinuxX64,
WirePlatform::WindowsX64 => Platform::WindowsX64,
WirePlatform::WindowsGnuX64 => Platform::WindowsGnuX64,
};
let raw = hex::decode(key.public_key_hex)? let raw = hex::decode(key.public_key_hex)?
.try_into() .try_into()
.ok() .ok()
.context("Ed25519 public key length")?; .context("Ed25519 public key length")?;
TrustedUpdateKey::new( TrustedUpdateKey::new(
raw, raw,
platform, key.platform.into(),
key.first_sequence, key.first_sequence,
key.last_sequence, key.last_sequence,
key.revoked, key.revoked,
+1 -1
View File
@@ -1,7 +1,7 @@
//! Pure release verification. This crate does not install, stage, start services, //! Pure release verification. This crate does not install, stage, start services,
//! grant approval, persist antirollback state, or trust keys from the network. //! grant approval, persist antirollback state, or trust keys from the network.
//! //!
//! See docs/agent-updater-proposal.md for the separate, unfinished integration. //! The release catalog and deployment workflow are described in `docs/development.md`.
mod bootstrap; mod bootstrap;
mod manifest; mod manifest;
+14
View File
@@ -16,12 +16,26 @@ pub const RELEASE_SIGNATURE_DOMAIN: &[u8] = b"rmm.agent-release.v1\0";
pub enum Platform { pub enum Platform {
#[serde(rename = "x86_64-unknown-linux-gnu")] #[serde(rename = "x86_64-unknown-linux-gnu")]
LinuxX64, LinuxX64,
#[serde(rename = "aarch64-unknown-linux-gnu")]
LinuxArm64,
#[serde(rename = "x86_64-pc-windows-msvc")] #[serde(rename = "x86_64-pc-windows-msvc")]
WindowsX64, WindowsX64,
#[serde(rename = "x86_64-pc-windows-gnu")] #[serde(rename = "x86_64-pc-windows-gnu")]
WindowsGnuX64, WindowsGnuX64,
} }
impl From<rmm_domain::agent_update::Platform> for Platform {
fn from(platform: rmm_domain::agent_update::Platform) -> Self {
use rmm_domain::agent_update::Platform as WirePlatform;
match platform {
WirePlatform::LinuxX64 => Self::LinuxX64,
WirePlatform::LinuxArm64 => Self::LinuxArm64,
WirePlatform::WindowsX64 => Self::WindowsX64,
WirePlatform::WindowsGnuX64 => Self::WindowsGnuX64,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")] #[serde(rename_all = "snake_case")]
pub enum ArtifactRole { pub enum ArtifactRole {
+28 -2
View File
@@ -66,11 +66,18 @@ fn manifest() -> ReleaseManifest {
} }
fn verify_bytes(payload: &[u8], context: &TrustedContext) -> anyhow::Result<VerifiedRelease> { fn verify_bytes(payload: &[u8], context: &TrustedContext) -> anyhow::Result<VerifiedRelease> {
verify_bytes_with_key(payload, context, key(false, 1, 20))
}
fn verify_bytes_with_key(
payload: &[u8],
context: &TrustedContext,
pinned: TrustedUpdateKey,
) -> anyhow::Result<VerifiedRelease> {
let signer = SigningKey::from_bytes(&[41; 32]); let signer = SigningKey::from_bytes(&[41; 32]);
let mut message = RELEASE_SIGNATURE_DOMAIN.to_vec(); let mut message = RELEASE_SIGNATURE_DOMAIN.to_vec();
message.extend_from_slice(payload); message.extend_from_slice(payload);
let signature = signer.sign(&message).to_bytes(); let signature = signer.sign(&message).to_bytes();
let pinned = key(false, 1, 20);
let key_id = pinned.key_id().to_owned(); let key_id = pinned.key_id().to_owned();
verify_release( verify_release(
SignedRelease { SignedRelease {
@@ -166,7 +173,7 @@ fn signed_noncanonical_unknown_duplicate_and_oversize_payloads_are_rejected() {
payload.replacen("{", "{\"schema_version\":1,", 1), payload.replacen("{", "{\"schema_version\":1,", 1),
payload.replacen("\"bytes\":11", "\"bytes\":11,\"path\":\"/etc/passwd\"", 1), payload.replacen("\"bytes\":11", "\"bytes\":11,\"path\":\"/etc/passwd\"", 1),
payload.replacen("\"release_sequence\":4", "\"release_sequence\":4.0", 1), payload.replacen("\"release_sequence\":4", "\"release_sequence\":4.0", 1),
payload.replacen("x86_64-unknown-linux-gnu", "aarch64-unknown-linux-gnu", 1), payload.replacen("x86_64-unknown-linux-gnu", "riscv64gc-unknown-linux-gnu", 1),
] { ] {
assert!(verify_bytes(changed.as_bytes(), &context()).is_err()); assert!(verify_bytes(changed.as_bytes(), &context()).is_err());
} }
@@ -174,6 +181,25 @@ fn signed_noncanonical_unknown_duplicate_and_oversize_payloads_are_rejected() {
assert!(verify_bytes(b"", &context()).is_err()); assert!(verify_bytes(b"", &context()).is_err());
} }
#[test]
fn arm64_release_requires_arm64_context_and_key() {
let mut target = manifest();
target.platform = Platform::LinuxArm64;
let mut context = context();
assert!(verify(&target, &context).is_err());
context.platform = Platform::LinuxArm64;
assert!(verify(&target, &context).is_err());
let arm64_key = TrustedUpdateKey::new(
SigningKey::from_bytes(&[41; 32]).verifying_key().to_bytes(),
Platform::LinuxArm64,
1,
20,
false,
).unwrap();
let payload = serde_json::to_vec(&target).unwrap();
assert!(verify_bytes_with_key(&payload, &context, arm64_key).is_ok());
}
#[test] #[test]
fn incompatible_clock_platform_state_protocol_and_trust_contexts_are_rejected() { fn incompatible_clock_platform_state_protocol_and_trust_contexts_are_rejected() {
let mut ctx = context(); let mut ctx = context();
+11 -44
View File
@@ -1,54 +1,21 @@
# Isolated local browser integration — no VM execution # WebUI im Browser prüfen
`run_pending.py` uses existing test bootstrap helpers to enroll a real mTLS device ## Oberflächentests mit Testdaten
fixture on the local dev backend, never a forged database agent identity. It sends
a ClientHello advertising `run_script` only to exercise plan validation; it does
not implement an executor, ask for a permit, authorize or report an execution.
The browser sends a durable pending request via the actual UI. The fixture is
revoked afterwards; its pending request and enrollment history are retained.
An artifact-count guard checks that jobs/outbox/grants did not increase.
Requirements: initialized/running dev Docker backend on loopback 18443, built UI Die Playwright-Spezifikationen für Auftragsdialog, Genehmigungseingang, Kunden und MCP-Tokens starten einen lokalen Testserver und liefern kontrollierte API-Antworten. Sie prüfen die Oberfläche ohne Zugangsdaten und ohne Aufträge auf realen Geräten. Die Befehle beginnen im Repository-Stamm.
served from `web/dist`, public CA `devstate/pki/ca.pem`, private existing browser
login `devstate/browser-login.json` (owned, mode 0600). Credential values are never
CLI arguments, printed or copied into source. No VM credentials are used.
Project-local tools (commands for reproducing setup; actual execution occurred in
the implementation session):
```sh ```sh
cd web cd web
npm ci --ignore-scripts npm ci
PLAYWRIGHT_BROWSERS_PATH="$PWD/node_modules/.cache/playwright-browsers" npx playwright install chromium export PLAYWRIGHT_BROWSERS_PATH="$PWD/node_modules/.cache/playwright-browsers"
mkdir -p node_modules/.cache/nss-tools npx playwright install chromium
cd node_modules/.cache/nss-tools npm run test:browser -- approval-inbox.spec.ts customer-management.spec.ts mcp-token-management.spec.ts order-composer.spec.ts
apt-get download libnss3-tools
dpkg-deb -x libnss3-tools*.deb root
``` ```
No package installed globally. The runner uses installed `certutil` if available, Die [Playwright-Konfiguration](../../web/playwright.config.ts) verwendet einen Worker und den projektspezifischen Reporter. Bei Tests mit Zugangsdaten die vorgegebenen Einstellungen für Reporter, Trace, Video und Screenshots verwenden. Private Browserdaten und Fehlerartefakte liegen im lokalen Cache.
otherwise the locally extracted binary. It imports the **public** CA into isolated
`web/node_modules/.cache/browser-home/.pki/nssdb`, with browser HOME restricted to
that directory. Existing global browser/user trust and hosts files are untouched.
DNS overrides map only fixed test names to 127.0.0.1; TLS/SNI still verifies the
original DNS name. No certificate bypass flag or ignoreHTTPS option exists.
From repository root: ## Abnahme auf Testgeräten
```sh Für den fachlichen Ende-zu-Ende-Nachweis auf einem Testgerät den gespeicherten Plan prüfen, die persönliche WebUI-Entscheidung abwarten und das Ergebnis des gebundenen Versuchs auswerten. Bei einem Neustart zusätzlich Bootwechsel, erneuten authentisierten Kontakt und Erfolg des Folgeauftrags erfassen. Die Nachweise für Linux und Windows enthalten Plan-, Auftrags- und Versuchskennungen. [Produktabnahme](../../docs/mvp-completion-plan.md)
python3 deploy/browser/run_pending.py
```
Real Playwright tests verify normal trusted HTTPS plus rejection of wrong DNS name Ein simulierter Testprincipal ist ausschließlich im getrennten dev/test-Profil zulässig. Dessen WebUI und Audit kennzeichnen die Simulation. Den internen Entwicklungszugang und dessen eigene TLS-Vertrauensstellung beschreibt die [Betriebsanleitung](../../docs/operations-access.md).
and an untrusted CA. The positive UI case only plans/submits and never clicks
approval. CSRF is tested by deleting the token from an actual logout UI request;
403 and continued session visibility are required, followed by valid logout.
No direct API/DB approval path is used. Reporter suppresses raw errors, action logs,
stdout/stderr; traces/screenshots/video are off. Failure artifacts remain private
and must not be published. Sanitized evidence records booleans/statuses only, no
hostnames/keys/passwords. Bounded retries are not automatic: a failing run fails;
a separate rerun must reauthenticate and creates a new explicit pending plan.
`RMM_E2E_MODE=execute` is an additional separate opt-in for the prepared positive
approval/result test, to use only after a real authorized agent path is ready.
This pending-only run is neither native VM evidence nor positive approval proof.
+1 -2
View File
@@ -3,8 +3,7 @@
prepare is offline. inspect/status are remote read-only. build/deploy each launch prepare is offline. inspect/status are remote read-only. build/deploy each launch
one durable, create-once case worker. Lost replies permit status only, not retry. one durable, create-once case worker. Lost replies permit status only, not retry.
The notebook never runs an RMM server/client. Existing deployment tools remain The current server deployment workflow is documented in docs/development.md.
unchanged. See docs/script-console-cloud-upgrade-v1.md before actual use.
""" """
import argparse import argparse
import base64 import base64
+1 -2
View File
@@ -3,8 +3,7 @@
prepare is offline. inspect/status are remote read-only. build/deploy each launch prepare is offline. inspect/status are remote read-only. build/deploy each launch
one durable, create-once case worker. Lost replies permit status only, not retry. one durable, create-once case worker. Lost replies permit status only, not retry.
The notebook never runs an RMM server/client. Existing deployment tools remain The current server deployment workflow is documented in docs/development.md.
unchanged. See docs/script-console-cloud-upgrade-v2.md before actual use.
""" """
import argparse import argparse
import base64 import base64
+18 -269
View File
@@ -1,277 +1,26 @@
# Linux agent/helper bootstrap contract (not a VM acceptance) # Linux-Agent betreiben
**Current integrated runtime contract:** [runtime-README.md](runtime-README.md). Der Linux-Client für `x86_64-unknown-linux-gnu` meldet sich ausgehend per mTLS am Gerätegateway. Als Systembenutzer `rmm-discovery` liefert er Heartbeats und Inventar, holt genehmigte Shell-Skripte ab und meldet Ausgabe und Exitcode zurück. Der optionale Root-Helper gehört zur gleichen signierten Releaseversion wie der Agent.
The module-only blockers and integration steps below record the earlier increments;
they are historical and superseded by that runtime document. In particular Sync,
HTTPS, rotation and authenticated helper apply are now wired in source, not VM-
accepted. Use the current document and installed units for new bootstrap work.
Dedicated APT runner, exact config/unit/CLI/readiness/agent-routing preflight: ## Installation
[`apt-helper-README.md`](apt-helper-README.md). This newer profile does not weaken
the existing general/readiness helper unit. Native VM measurements remain open.
No install/start/reboot command in this document has been executed on the VM. 1. In der WebUI den Zielkunden wählen, **Gerät aufnehmen** öffnen und einen Einmalcode erzeugen.
No RustDesk component is installed. Deploy only the artifacts/configuration for 2. Auf dem x86-64-Linux-Gerät mit systemd und Python 3 den dort angezeigten Linux-Befehl ausführen. Er lädt `/install/linux.sh` über HTTPS und ruft es mit `sudo sh` und dem Bootstrap-Ursprung des Servers auf. Den Einmalcode am verdeckten Prompt eingeben.
the explicitly agreed test; do not copy central signing/TLS private keys. 3. Für Root-Skripte die Administratoroption der WebUI wählen. Sie ergänzt `--enable-admin-scripts`. Auf einem bereits eingeschriebenen Gerät lässt sich der Installer mit demselben Ursprung und dieser Option erneut ausführen. Die Geräteidentität bleibt erhalten.
4. Im Gerätedetail Hostname, Kunde, Agentversion und letzten authentisierten Kontakt kontrollieren. Für einen Root-Auftrag braucht das Gerät den gemeldeten Root-Kontext und eine passende zentrale Geräteregel. Ein MCP-Token benötigt zusätzlich die passenden Rechte für diesen Kunden. [MCP-Zugang](../../docs/public-access.md)
## Built artifacts and process configuration ## Selbstupdate und Diagnose
Planned build command (the debug test/build commands actually executed are listed `rmm-discovery-update.timer` ruft den Releasebestand nach dem Booten und anschließend alle fünf Minuten mit einer zufälligen Verzögerung von bis zu 20 Sekunden ab. Vor dem Wechsel prüft der Updater das signierte Paket und die Auftragsjournale. Eine neue Generation wird durch den frischen Kontakt des Agenten bestätigt. Scheitert die Aktivierung, wählt der Updater den Vorgänger. Ein über den Installer aktivierter Helper wechselt zusammen mit dem Agenten. [Installer und Aktualisierungslogik](../../crates/server/src/bootstrap/lifecycle.py)
in `tests/agent_jobs/README.md`):
```sh | Am Gerät prüfen | Befehl oder Pfad |
cargo build --release -p rmm-agent -p rmm-privileged-helper | --- | --- |
``` | Agent und letzter Update-Lauf | `systemctl status rmm-discovery-agent.service rmm-discovery-update.timer` und `journalctl -u rmm-discovery-update.service -n 50` |
| Installierter Root-Helper | `systemctl status rmm-discovery-managed-script-helper.service` |
| Aktive Generation | `readlink -f /opt/rust-discovery-client/current` |
| Zustand und Identität | `/var/lib/rmm-discovery` gehört dem Dienstkonto. Bei einem Binärwechsel bleiben Gerätedaten, Schlüssel und Journal erhalten. |
| Tatsächlicher Neustart | `cat /proc/sys/kernel/random/boot_id` vor und nach dem Neustart vergleichen. Anschließend denselben Agenten am Gateway und das Ergebnis eines nachfolgenden Skripts prüfen. |
Both binaries are environment-configured, **not** positional-argument CLIs. Die Bibliotheksrevision „Linux neu starten“ kündigt den Neustart mit einer Minute Vorlauf an. Eine Datei unter `/tmp` kann beim Booten gemäß lokaler Systemkonfiguration verschwinden. Für die Beurteilung eines Auftrags zählt die Ausgabe seines konkreten Versuchs. [Native MCP-Abnahme](../../docs/evidence/mcp-scoped-script-requests-20261118.json)
Agent: `RMM_AGENT_STATE` (default `devstate/agent`), `RMM_CA_FILE` (default Für einen neuen Release oder eine direkte Entwicklungsbereitstellung den gemeinsamen [Entwicklungsweg](../../docs/development.md) verwenden.
`devstate/pki/ca.pem`), `RMM_CONNECT_ADDR` (default `127.0.0.1:18443`),
`RMM_ENROLLMENT_TOKEN_FILE` (first registration only), and optional
`RMM_JOB_BINDING_FILE`, plus optional `RMM_HELPER_SOCKET` for explicit-root grants.
The TCP override never changes the TLS DNS/SNI name
`rmm-dev.internal`. No proxy or invalid-certificate bypass. Without a binding,
the agent remains passive. It refuses to advertise/execute actions as UID 0.
Provision a dedicated unprivileged `rmm-agent` system account/group. Install the
agent binary root-owned and non-writable by that account at
`/usr/local/libexec/rmm-agent`. State must be owned by that account, mode 0700;
its files are 0600. The sample service uses systemd `StateDirectory` and no
ambient capabilities. Install only the public CA at `/etc/rmm/ca.pem`. An
optional root-owned 0600 `/etc/rmm/agent.env` supplies the first-enrollment token
**path**, never an inline token. Remove that bootstrap token after registration.
Retain the enrolled VM-generated private device key on the VM.
The operator must provision the job signing key over the authenticated bootstrap
channel: authenticated `GET https://rmm-dev.internal:18443/api/v1/job-signing-key`
using the verified CA, checking `algorithm == "Ed25519"`, `schema_version == 1`,
32-byte `public_key_hex` and `key_id == SHA256(raw_public_key)`. Do not trust a key
sent alongside a job, use an unauthenticated GET, put bearer credentials in
command arguments, or substitute TLS/update keys. This increment does not
rotate this trust anchor. Optional automatic agent fetching is described below;
the helper remains independently provisioned. The authenticated operator/bootstrap
must also resolve the enrolled agent's tenant, asset, generation and assignment
from server records, not accept an offer as identity provisioning.
Agent binding JSON, owned by `rmm-agent`, 0600, in a root-owned configuration
directory (replace every placeholder; invalid placeholders intentionally fail):
```json
{
"tenant_id": "PROVISIONED-TENANT-UUID",
"asset_id": "ENROLLED-ASSET-UUID",
"agent_id": "ENROLLED-AGENT-UUID",
"enrollment_generation": 1,
"assignment_version": 1,
"public_key_hex": "AUTHENTICATED-32-BYTE-KEY-IN-HEX"
}
```
The agent additionally compares asset/agent IDs to its enrollment response.
Generation/assignment changes require an authenticated re-provisioning procedure,
not an in-band config assertion. State lock, integrity check and journal capacity
errors fail closed; never delete journal/consumption files to force a retry.
## Independent helper boundary
Helper: `RMM_HELPER_CONFIG`, default `/etc/rmm/helper.json`. It requires UID 0,
a root-owned 0600 config, root-owned private 0700 state directory, and a
root-owned socket parent not writable by group/others. `/run/rmm-helper` may be
0750 with group `rmm-agent`. The root-owned socket is 0660 with the configured
group; `SO_PEERCRED` additionally requires **exactly** the configured non-root
agent UID. Group membership alone grants no execution authority.
Example `/etc/rmm/helper.json` (root:root, 0600):
```json
{
"binding": {
"tenant_id": "PROVISIONED-TENANT-UUID",
"asset_id": "ENROLLED-ASSET-UUID",
"agent_id": "ENROLLED-AGENT-UUID",
"enrollment_generation": 1,
"assignment_version": 1,
"public_key_hex": "AUTHENTICATED-32-BYTE-KEY-IN-HEX"
},
"agent_uid": 12345,
"socket_gid": 12345,
"socket": "/run/rmm-helper/control.sock",
"state": "/var/lib/rmm-helper",
"allowed_services": ["rmm-acceptance.service"],
"allow_reboot": false,
"allow_root_scripts": false
}
```
Use the actual dedicated account's numeric UID/GID, not the example numbers.
The helper re-verifies exact Ed25519 bytes, all identity/hash/action/parameter
bindings, a <=60-second grant interval, synchronized bounded host clock, explicit
`execution_identity:"root"`, local action policy and its **own** SQLite consumption
ledger before invoking the typed OS provider. A request-provided bearer, key or
identity assertion is never an authority. The config has a separate, default-off
root-script permission; enabling it is consciously broad administration, still
subject to the sample service sandbox. Only exact allowed service units with
running/stopped state and >=180s runtime are accepted; restart is not silently
rewritten as start. Reboot is default-off and never yields exit-code success.
IPC framing: one big-endian u32 length plus JSON `Request` (<=512 KiB) per Unix
connection. Fields are `job_bytes`, `permit_bytes`, `signature` (JSON byte arrays),
`plan_hash`, `authorization_id`. Response has the same framing and an `Outcome`.
Read/write deadlines are 5s. No request errors/secrets are echoed. The server
process is serial; unknown effects retain its global device resource lock, even
after restart. Duplicate consumed grants return stored evidence/unknown, never
execute again. A new grant for an already consumed attempt is also refused.
The helper refuses a preexisting socket; systemd removes its RuntimeDirectory
on stop. Manual stale-socket recovery requires checking that no helper is alive,
not blindly unlinking a path at startup.
## Explicit integration/acceptance blockers
* Backend currently permits only `agent_service`. Network agent intentionally
advertises only `run_script` and `refresh_inventory`, not privileged actions.
Network-agent → Unix-helper invocation is wired for explicit-root signed jobs
when `RMM_HELPER_SOCKET` is configured, with root socket/peer authentication.
A backend-authorized explicit root identity plus helper capability negotiation
must land before service/reboot/root-script E2E tests. Helper policy denies
unconfigured actions independently; the agent never relabels a service-identity
grant into root authority.
* Real APT mutation remains unsupported. A simulation followed by `apt-get`
cannot guarantee exact approved resolution under dpkg fcntl locks or suppress
arbitrary maintainer-script reboots. Neither `ensure_package` nor
`apply_updates` is advertised. No false flock-on-dpkg-lock implementation.
* No backend SyncRequest/Response exists. Only the **first** authenticated session
of a journal may start effects. On reconnect/restart new effects are blocked;
in-flight reservations become unknown, durable evidence still replays and
heartbeats remain fresh. No DB deletion/new-grant shortcut. Existing previously
connected state also needs real synchronization before jobs can be enabled.
* Running-script cancellation is recorded but not claimed as confirmed abort;
bounded execution finishes and reports its real result. A reboot does not
complete without authenticated new-boot evidence; automatic reboot recovery
synchronization is not implemented.
* Extended collectors now map to bounded per-source observations inside the
existing `linux.base` JSON, not new protobuf scopes/tags. Enable only after
backend JSON-extension acceptance is confirmed, as described below.
* No VM deployment, systemd install, root action, package/update/reboot host
effects or real UI approval were performed by this increment.
## Additional environment variables and bootstrap (second increment)
* `RMM_JOB_SIGNING_KEY_BOOTSTRAP=1`: after enrollment, use **device mTLS** to GET
`/api/v1/job-signing-key` over verified TLS. DNS/SNI remains `rmm-dev.internal`;
`RMM_CONNECT_ADDR` changes TCP only. Built-in roots, proxies and redirects are
disabled. The response is bounded to 4096 bytes and Ed25519/schema/key-hash
checked. No bearer is copied into the agent. A preconfigured binding key must
match; an empty key allows initial authenticated provisioning. The resulting
`RMM_AGENT_STATE/job-signing-key.json` is private and create-only. A changed
existing pin **fails**, never silently rotates. Keep the bootstrap flag enabled
on subsequent starts when the binding's key is empty, so the endpoint is
reauthenticated and checked against the cached pin. If the current backend
endpoint accepts bearer identity only, bootstrap fails closed; backend must
explicitly authorize the authenticated enrolled device at that endpoint.
* Helper config optional `"signing_key_file":"/etc/rmm/helper-signing-key.json"`:
root-owned 0600 JSON with `key_id`, `algorithm`, `schema_version`,
`public_key_hex` in the GET response shape. Provision via the trusted operator
bootstrap, **not** from an agent-provided file/path/request. If an inline helper
binding key is present it must match. The helper has no network key-fetch or
auto-replacement operation; agent cache changes cannot change helper trust.
* `RMM_LOG_UNITS_FILE`: private, agent-owned 0600 JSON array of 1–128 exact
`.service` names. `query_logs` is advertised only when this allowlist and a
native journald executable/runtime exist. The signed action must bind an
allowlisted unit, nonnegative UTC window <=24h, <=1000 lines, >=20s runtime and
bounded output. No arbitrary paths or caller-defined journal arguments.
Access/JSON/output failures retain quality/error metadata. The current action
has **no cursor input field**; no cursor is fabricated or advanced. Results
explicitly report `cursor_status:not_advanced_no_ack_contract` and partial
coverage until a concrete durable cursor-ACK contract exists.
* `RMM_EXTENDED_INVENTORY=1`: opt-in additive snapshot JSON fields `observations`,
`collection_started_at`, `collection_completed_at`. Every observation has
`scope`, source, real RFC3339 observation time, quality, completeness,
truncation, error and data. CPU, memory, OS, interfaces, routes, DNS, volumes,
installed packages, local update metadata and DMI are mapped; SMART remains
explicitly unsupported. Per-scope output is <=32 KiB and entire data <=512 KiB.
**Do not enable against a gateway deserializing the old deny-unknown-fields
Inventory struct.** Confirm backend storage accepts these additive JSON fields
first. Default remains compatible base JSON; no wire/protocol file changed.
Passive collection now runs in one bounded-inflight blocking worker with a
bounded completion channel, not inside the network/heartbeat loop. A reconnect
does not spawn a second collector while one is already running. A refresh job
still collects a **new** base observation for its signed `linux.base` scope;
it never returns an old stored passive snapshot as a live measurement.
Awaiting-reboot evidence now persists before effect: original native boot ID,
exact signed request, reservation time and reconnect deadline in each process's
own `execution_evidence` ledger. Awaiting/unknown outcomes persist without
unlocking the consumed attempt. Neither exit code nor a process restart supplies
authenticated new-boot completion. Cancellation arriving while a permit is
outstanding is checked before effect; running cancellation remains conservative.
An earlier future-scheduled job no longer starves later ready jobs.
## Offline package installer (not executed on VM)
`deploy/linux/install.py` is create-only. Planned invocation:
```sh
python3 deploy/linux/install.py --root /PATH/TO/STAGING \
--agent-binary target/release/rmm-agent \
--helper-binary target/release/rmm-privileged-helper --ca-file /PATH/TO/PUBLIC-CA.pem
```
Staging writes only the x86-64 ELF artifacts, public CA and unit files. A live
installation additionally requires root, `--root / --install-live` and an already
provisioned unprivileged `rmm-agent` account. It refuses overwrites, writable or
symlinked install directories, non-x86-64 artifacts and private-key CA inputs.
It does **not** create accounts/config/identities/state, call systemctl, enable or
start anything, install packages, change the network or reboot. Configure trust
and enrollment first; systemd StateDirectory/RuntimeDirectory creates the correct
runtime state when a later explicitly authorized bootstrap starts the units.
The units retain empty agent capabilities, NoNewPrivileges, private temp,
read-only system/home protection and no privileged-shell bypass. Privileged
scripts are separately default-off and remain subject to the helper sandbox.
## Concrete backend contracts needed next
### APT bridge increment (not installed or VM-tested)
The helper's typed APT bridge is implemented at
`crates/privileged-helper/src/apt.rs`, through its existing SO_PEERCRED/signature/
parent-consumption boundary. Root config has optional `apt_provider`; default is
disabled. The exact schema-2 signed manifest, additive domain action fields,
compile-time-known create-only provider installation, pre-grant sealed archive/
baseline layout, context/ledger mapping and conservative outcome contract are
documented in [`../../tools/apt-transaction/HELPER-CONTRACT.md`](../../tools/apt-transaction/HELPER-CONTRACT.md).
This does not remove the package-capability blocker: the domain must preserve
the complete typed `action.apt_manifest`, validate the narrow fixture closure,
and support dedicated `apt_native_acceptance`; the agent remains unchanged.
Legacy package/update actions without this field fail closed. No RunScript
conversion, arbitrary archive URL or unsigned IPC manifest is accepted.
Planned root-only `rmm-privileged-helper --install-apt-provider` installs only
embedded reviewed provider/hook bytes and fixed metadata, create-only. It does
not start services, create grants, install .deb packages or create acceptance.
`provision-fixture-store` prepares only the pinned fixture artifacts before any
final grant. Neither command was executed in this increment.
The existing helper unit's ProtectSystem=strict/other protections are **not**
an APT write/setup profile. A reviewed native fixture runner/unit configuration
and actual VM tests are still required; no unit restriction was relaxed here.
Do not advertise APT merely because the Rust bridge and local tests compile.
Before removing `begin_session`'s fail-closed reconnect gate, agree a versioned
authenticated SyncRequest/Response carrying device identity/assignment and
connection generation, journal identity/checkpoint, fixed job/attempt, payload
hash, grant ID/bytes or reservation ambiguity, local revision/state, original
boot ID, persisted outcomes and concrete durable event receipts. Server must
return an explicit reconciled/fenced decision, not a blanket `ok`. Unknown or
missing old reservations must retain resource locks; no response may authorize a
new attempt or silently manufacture a replacement grant. Restored/mismatched
generations must stay blocked. Reboot success requires authenticated current
envelope boot ID different from persisted original boot and bound postconditions.
Long-poll must deliver the same typed envelopes and concrete ACKs with one active
generation, including late evidence ingestion; no new endpoint/wire assumption
is implemented here. Root planning must bind explicit root identity and local
helper capabilities/policy, never reinterpret `agent_service`. The public key
GET must authorize enrolled device mTLS. Additive inventory JSON acceptance must
be confirmed before enabling extended collection in a real agent.
-60
View File
@@ -1,60 +0,0 @@
# Dev/test root-helper readiness, not package acceptance
`python3 deploy/vm_root_bootstrap.py inspect` is read-only. `build` creates a
private minimal Docker context containing only Rust sources, pinned Cargo files,
migrations and the reviewed APT-tool sources; it never includes credentials.
`install` is the separately authorized create-only systemd bootstrap. It refuses
existing root-helper paths, unresolved VM jobs, an active agent/tunnel, changed
agent identity/signing authority or incompatible artifacts. It never resets an
identity/journal or authorizes a job. Do not retry a partial install blindly.
Fixed resources: `/usr/local/libexec/rmm-privileged-helper`, root-owned 0600
`/etc/rmm/helper-dev-test-v1.json` and `helper-signing-key-v1.json`, private root
state `/var/lib/rmm-helper`, `rmm-helper-dev-test.service`, and root-owned agent
drop-in `10-dev-helper-v1.conf`. The drop-in adds only
`RMM_HELPER_SOCKET=/run/rmm-helper/control.sock`; it does not restart the agent.
The helper's root-owned socket is 0660/group `rmm-agent` in a 0750 root-owned
runtime directory. `SO_PEERCRED` separately checks exactly the provisioned
non-root agent UID; a connect-only readiness probe is not a signed IPC test.
Public signing authority comes from the authenticated, CA/name-verified server
GET and must match the preserved agent binding. No server private key is copied.
Helper trust/ledger remain inaccessible to the network service. The helper is
enabled for its expressly named dev/test service but stopped after readiness
only when its own consumption ledger is confirmed empty. No agent/tunnel is
started. Creation lists, native measurements and sanitized failure class/line
numbers are stored privately; raw stderr, payloads and exceptions are withheld.
## Intentionally disabled execution gates
The dev/test config allows only the future exact `rmm-mvp-test.service` unit;
this bootstrap **does not create or start that test service**. Root scripts and
reboot are disabled. `apt_provider` is null. Installing the compiled-in provider
via `--install-apt-provider` creates trusted code/hook and empty sealed-store
directories/metadata only. No package, fixture archive, baseline, active context,
grant or native-acceptance record is generated. `inspect-runtime` and
`print-config` are measurements, not authority. Their hashes belong to a future
explicitly UI-approved immutable plan.
`inspect-sandbox` is invoked read-only as root in the parent environment. A veto
there is expected and reported as **not passed**, never bypassed with fabricated
`host-namespaces.json`/sandbox-ready files. The actual provider requires its
signed worker context before building the final sandbox.
The new readiness unit preserves restrictive protections; it is deliberately
**not APT-execution-capable**. Package setup requires CAP_SYS_ADMIN for private
mount/PID/network namespaces and mount setup, CAP_MKNOD for the four basic device
nodes, and write access to the actual fixture package payload/dpkg/APT stores.
The final package child must then retain exactly CHOWN, DAC_OVERRIDE, FOWNER,
FSETID, SETGID, SETUID, SETPCAP and SETFCAP, NNP and seccomp; no SYS_ADMIN,
SYS_BOOT, KILL or MKNOD may remain. Host control sockets must be hidden and the
private PID1/mount/network checks must pass. The readiness unit's deny-mount
syscall policy and ProtectSystem=strict prevent this setup. Do not loosen them
blindly: a separately reviewed native APT runner/profile is still required.
Future backend root planning, manifest preservation, helper policy changes and
agent capability negotiation do not follow from installation. Reconnect/sync
must be ready before starting new jobs. Every service/package/update/reboot or
new attempt still needs its own fixed plan and actual dev/test WebUI approval.
Actual commands/results are recorded in `docs/implementation-status.md`; this
document alone claims no VM execution or Linux-MVP acceptance.
-227
View File
@@ -1,227 +0,0 @@
# Dedicated APT runner / VM preflight contract
**Implemented, built and locally tested, not deployed or measured on a VM.**
Every command below is **planned, not executed here**. No host package, service,
reboot, root installation or acceptance operation was executed in this dispatch.
Readiness is not package acceptance or authorization. Existing readiness/general
helper unit is unchanged: no broadening its write paths/capabilities/filters.
## Architecture and fixed paths
Same helper binary, two separate daemon profiles:
| Profile | Socket | Allowed operations |
|---|---|---|
| general (existing/default) | existing configured general socket | existing explicitly permitted root operations, never APT |
| `apt_only` | `/run/rmm-apt-helper/helper.sock` | read-only readiness and typed fixture APT jobs only |
APT profile requires agent UID **993**, root-owned agent-group socket ACL,
empty allowed_services, allow_reboot=false, allow_root_scripts=false and a valid
apt_provider policy. Unknown profiles/actions/CLI programs fail closed. No shell,
service, reboot or generic-program dispatch exists in apt_only. Root administrative
CLI modes are fixed install/probe/inspect operations, not network-callable argv.
**Both daemons must run the same new helper build** and use the exact same
`/var/lib/rmm-helper/consumption.sqlite` and `executor.lock` inodes. All SQLite
sidecars stay in that shared directory (current ledger uses synchronous FULL /
DELETE journal mode; no database/WAL/SHM copy or private bind). Flank lock is now
per actual request/effect, not daemon lifetime, allowing coexistence. Startup DDL
is locked; consume/execute/finish are locked. An unresolved consumed row blocks
all new effects across both profiles, including reboot/package conflicts.
No tombstone deletion, marker reset, database copy or grant replacement shortcut.
APT-owned store: `/var/lib/rmm-apt-transaction` (0700), including archives,
baselines, history, probes, state, log and active handoff. The child sees neither
the shared ledger nor `/etc/rmm` keys/config, `/var/lib/rmm-agent`, home directories,
host manager sockets or inherited private fds. Only the trusted outside root
controller sees the signing-key pin/ledger. Central private signing keys must
never be deployed to the VM.
## Installation order (planned)
1. Authenticated operator installs the reviewed newly built helper at fixed
`/usr/local/libexec/rmm-privileged-helper` using the existing controlled
artifact deployment process. Both helper daemons need this same build; do not
blindly overwrite an active old helper or restart away unknown effects.
2. Before starting the new unit, run the root-only known-payload installer:
```text
/usr/local/libexec/rmm-privileged-helper --install-apt-provider
```
It exclusively creates known embedded provider/hook files, schema-2 install
metadata, the exact `rmm-apt-helper.service` at `/etc/systemd/system/`, private
store directories and empty `/usr/share/rmm-mvp-test`. It does NOT install a
.deb, start systemd, create grants or create an acceptance record. Existing/
partial paths are refused, not overwritten, chmod-repaired or deleted.
3. Root-provision `/etc/rmm/apt-helper.json` (0600) from
`apt-helper.example.json`; replace all invalid placeholders and verify actual
rmm-agent UID is 993 and socket_gid is the actual rmm-agent group GID. Keep
the existing separately authenticated Ed25519 key pin/binding procedure.
4. Inspect the installed provider/config/runtime, including installed helper
binary and exact unit profile:
```text
/usr/bin/python3 -I /usr/lib/rmm-apt-transaction/apt_transaction.py print-config
/usr/bin/python3 -I /usr/lib/rmm-apt-transaction/apt_transaction.py inspect-runtime
```
Set approved apt_config_sha256 from exact config bytes. Set runtime_sha256
from the canonical runtime object **without its trailing newline**. Review
the contents/code/configuration; blindly hashing unreviewed configuration is
not a security review. No timestamp/hash placeholder can enable execution.
5. After valid private config/key provisioning, inspect the helper identity pin:
```text
RMM_HELPER_CONFIG=/etc/rmm/apt-helper.json /usr/local/libexec/rmm-privileged-helper --inspect-apt-profile
```
Operator installs its exact JSON output at e.g.
`/etc/rmm/apt-helper-proof.json`, root:rmm-agent 0640, in root-owned,
non-group/world-writable configuration parents. This pin contains public
identity/hash metadata, no grant or secret. Agent must be able to read it but
not alter it. The inspected executable must match the installed daemon bytes.
6. Validate the unit on the VM before start (`systemd-analyze verify`), then
perform the separately authorized unit bootstrap. `ExecStartPre` executes:
```text
RMM_HELPER_CONFIG=/etc/rmm/apt-helper.json /usr/local/libexec/rmm-privileged-helper --probe-native
```
**The probe runs under the actual dedicated service profile**, not a generic
root shell: controller verification requires NoNewPrivileges, exact ten-bit
setup capability set, zero inherited/ambient caps, the actual
rmm-apt-helper.service cgroup and readonly /usr, /etc and /var. Direct daemon/
probe invocation outside that profile is rejected. `--inspect-apt-profile`
remains a read-only administrative metadata operation and is not readiness.
Controller verification also requires an outer seccomp filter, actual writable
declared targets, and rejects unexpected writable submounts below /usr,/etc,
/var. Inspect effective systemd configuration (`systemctl cat/show`) on the VM;
do not introduce unreviewed drop-ins or substitute a root-shell launch.
## Unit and irreversible worker sandbox
`rmm-apt-helper.service` provides NNP, PrivateTmp/PrivateNetwork, strict readonly
system/home/kernel/control-group protection, AF_UNIX only, native syscall ABI,
mount/PID/net namespaces only, no ambient caps. Bounding set is filesystem/UID
bits 0,1,3,4,6,7,8,31 plus SYS_ADMIN/MKNOD for trusted setup; no SYS_BOOT,
SYS_CHROOT or SYS_TIME. DevicePolicy=strict permits only null/zero/random/urandom
rwm; PrivateDevices=no permits trusted construction of a minimal private /dev.
Outer filter allows mount/unshare/fork/capset/prctl/seccomp trusted setup instead
of an outer @mount prohibition. Reboot/module/raw-io/swap/debug and clock setters
remain denied. The narrow adjtimex exception is necessary for the existing
read-only modes=0 trusted-clock query; mutating adjtimex still needs CAP_SYS_TIME,
which is absent. This is not a clock-verification bypass.
Write paths are **only** `/var/lib/dpkg`, shared helper ledger, private provider
store and precreated `/usr/share/rmm-mvp-test`. No whole /usr, /etc or /var writes.
APT terminal/history logs and dpkg log are explicitly under provider `log/`;
APT cache/state and extended_states are private, no default /var/log/apt write.
These are configured paths, **not natively proven log/write requirements** yet.
Unexpected native write failures must be reported, not fixed with blanket writes.
One common Python setup function serves mutation and readiness. It makes mount
propagation private, hides keys/ledger/sockets/fds, mounts minimal devices and
kernel controls, then irreversibly drops E/P/B to the original eight caps,
clears I/A, retains NNP and installs seccomp. Both clone namespace flags
(including NEWUSER/NEWTIME) and clone3 pointer flags are closed: clone3 returns
ENOSYS for libc's ordinary fork fallback; clone namespace flags return EPERM.
Ordinary fork/exec remains allowed. No reconfiguration/reboot/kexec escape is
allowed after setup. Trusted setup with SYS_ADMIN is explicitly in the TCB.
## Readiness probe: no package transaction
`--probe-native` does NOT create jobs, grants, receipts, launch/effect markers or
native-acceptance records. It exclusively creates a generated private probe dir,
copies host dpkg status (host opened read-only), binds the copy over /var/lib/dpkg
inside the worker namespace, uses source/hook-isolated private APT config, tests
private-db frontend lock conflict and runs positive `apt-get check` on that copy.
The host frontend lock is only observed with O_RDONLY/F_GETLK: never F_SETLK,
flock/lockf, deletion or killing an owner. Invalid-magic/flags reboot/kexec probes
must return EPERM; no valid calls or PID1 signals are attempted.
The worker checks namespaces/PID1, capabilities/NNP/seccomp, readonly control
mounts, hidden sockets and masked sysrq. Parent verifies complete result and
private namespace identities, unchanged host status/runtime and publishes only
root-private `native-readiness.json` (readiness_only=true, native_acceptance=false).
It is boot-/code-/OS-/binary-/unit-bound and invalidated by changes. Partial,
failed or malformed results do not publish new readiness. Acceptance/bootstrap
attempt tombstones are neither created nor reset by this operation.
## Agent environment / read-only IPC API
```
RMM_APT_HELPER_SOCKET=/run/rmm-apt-helper/helper.sock
RMM_APT_HELPER_PROOF_FILE=/etc/rmm/apt-helper-proof.json
```
`RMM_HELPER_SOCKET` remains the general route. Typed ensure_package,
apply_updates and apt_native_acceptance exclusively use the dedicated socket.
Missing/wrong APT socket/pin/readiness never falls back to general helper, SSH,
shell or local execution. The unprivileged agent obtains a fresh read-only probe
before capability advertisement and before use; it authenticates root SO_PEERCRED,
root-owned safe socket/parents and independent root-provisioned pin.
Same u32-big-endian framed JSON socket, a distinct read-only request shape:
```
operation: "apt_readiness_v1"
challenge: fresh nonnil UUID
identity: {tenant_id,asset_id,agent_id,enrollment_generation,assignment_version,signing_key_id}
expected_stack_sha256: independently pinned helper/identity/policy/unit stack hash
```
Response strictly binds nonce, identity, apt_only profile and provider stack;
includes shared ledger/lock dev/inodes and separate fixture_acceptance_ready,
bootstrap_recipes and accepted_recipes. Wrong nonce/identity/generation/profile/
stack/root peer is rejected. An unresolved shared ledger suppresses all APT
readiness/capabilities. This API never consumes a grant or authorizes a job.
Readiness alone advertises **only apt_native_acceptance** for fixed allowed
fixtures. Valid native acceptance records enable only matching fixture recipes:
ensure_package, and apply_updates only for the accepted update recipe. Agent
also checks each actual typed job's manifest recipe, not just aggregate action
capability names. No production/arbitrary catalog capability is manufactured.
## Actual jobs remain UI-authorized
Domain's additive typed schema-2 apt_manifest and dedicated AptNativeAcceptance
are now present; local tests roundtrip the actual domain variant through exact
signed bytes into the helper validator. See
`tools/apt-transaction/HELPER-CONTRACT.md` for the full immutable payload/context
schema. Readiness does not replace independent Ed25519 verification, all target/
tenant/generation/plan/job/attempt/authorization/action/hash/time bindings,
current trusted clock, parent consumption and immutable WebUI approval.
Use provision-fixture-store / prepare-baseline **before** final grant to stage
the two known archives and snapshot. One UI-approved dedicated fixture job may
install 1.0, another may update 1.0 -> 1.1. Same guard/native lock/deadline/hash/
postcondition pipeline, no weak path. Failed/stale/partial/unknown never acceptance.
Armed/unknown outcomes retain both parent resource fencing and effect markers.
One-time failures are not blindly reset: technical no-start recovery needs a
separate durable signed reconciliation procedure, not implemented as a shortcut.
No actual native namespace/APT/service/root execution has been measured here.
The subsequent VM worker must execute this profile/probe and UI-authorized
fixture jobs, retain actual evidence and report all native failures separately.
## Executed local verification (this increment)
* Source-tree rustfmt check passed for helper lib/main and agent main/modules.
* Targeted Clippy `-p rmm-privileged-helper -p rmm-agent --lib --bins -- -D warnings`
passed.
* `cargo test -p rmm-privileged-helper -p rmm-agent --lib --bins`: **37 passed**
(20 helper library, 3 helper binary, 14 agent).
* `PYTHONDONTWRITEBYTECODE=1 python3 -m unittest discover -s tests/apt_transaction -p 'test_*.py' -v`:
**48 passed**; AST syntax checks **7 Python files**; example JSON syntax passed.
* Local unprivileged seccomp invalid-input/clone-flag denial and ordinary
fork/exec really ran. Root setup/installer/APT/probe unit execution was mocked
where unsafe. Temporary mock readiness files are not deployed native evidence.
Package-wide verification has a concurrent-work limitation: the last full
`cargo fmt --check` encountered formatting in the other worker's
`crates/privileged-helper/tests/reconcile.rs`; the last all-target Clippy attempt
failed on missing `validate_history` in its included `src/reconcile.rs`. Those
Sync files were not edited here. The focused source checks/tests above passed
afterwards; this is not a claim that the parallel Sync integration suite passed.
-241
View File
@@ -1,241 +0,0 @@
# Explizite Hostwartung mit full_maintenance_v1
Stand 2026-11-14, Spezifikation1.20. Die Batch-Skriptkonsole und der unabhängig
geprüfte Fullhelper-Binärpinfix sind implementiert, neu quellqualifiziert und nach
tatsächlichem Linux-Unitlauf erhaltend auf der Cloud-Linux-VM bereitgestellt.
Agent, General und Full laufen mit den geprüften Images; signierter Folgeabgleich
und WebUI-genehmigter Fulljob bleiben separat offen. Tatsächliche Teilfehler,
Fortsetzungen und unveränderte Originalbelege:
[Bootstrap-Ergebnisse](../../docs/script-console-bootstrap-results.md).
Cloud-Linux-VM zuerst, Windowsgast separat; Notebook ausschließlich Entwicklung.
## Aktueller korrigierter lokaler Nachweis
Der neue eigenständige Pack liegt privat unter
`devstate/script-console-qualification/run-29461892-343f-42f4-b469-88703535425e/`.
Manifest-SHA256:
`ddd1a78d1cd289b02b1f98572f9652171ec00be84e01ce099fd722d689bcaacd`.
158 vollständige Compiler-/Include-/Fixture-/Deploymentinputs vor/nach identisch.
Sourcearchiv-SHA256:
`fcb57f69ad81ea4acde15af6022d5c2da32f5699ebd39886c530c77882b369cc`.
Tatsächlich ausgeführt: Formatprüfung, Linux-Workspace-Alltargets-Clippy mit
`-D warnings`,285 lokale Tests bestanden (5DB-Fälle zunächst ausgelassen), danach
sämtliche45 Serververträge inklusive dieser5 gegen frisches isoliertes PostgreSQL
bestanden (0ignored). Windows-GNU-Alltargets-Clippy mit -Dwarnings im Default-
und SYSTEM-Helperprofil bestanden. Kein geänderter Test unterdrückt; die neue
Imageprüfung führt auch bei nicht vertrauenswürdigem Dateibesitz echte
Verweigerungsassertions aus, keinen stillen Early-return-Skip.
Neue tatsächliche Linux-Unitlisten: Domain22, Linuxruntime16, Helperpolicy6,
Serververträge45. Auf Cloud-Linux ohne isolierte DB erwartet:84PASS und5explizite
DBignored; diese5 sind separat im lokalen45er-DB-Lauf tatsächlich bestanden.
Alle vier vollständigen Listen müssen vor irgendeinem Unitstart geprüft sein.
Linux-Release-Helper SHA256
`79442727c3ba31cda02a8bc0e67481f14db9f39fc07520a880a90b64f10f1eaf`;
Agent `0a7ad6eefaefda79ee80b6a41b2df904e9e7f50ae6ebeed01b98c25b6ce5c06f`;
Server `610017637a9f9e55a6cb3cd8264937b953996af84e86dd49f2ea00c8e59739cd`.
Keine dieser neuen Binaries ist durch den Builder auf einem Ziel installiert.
Native Cloud-Linux-Units bestanden anschließend tatsächlich; siehe den separaten
Beleg unten. Auch die späteren 36+7 Windows-Units bestanden separat nativ:
[Windows-Nachweis und Grenzen](../../docs/script-console-windows-link.md).
Laufende Windows-SYSTEM-Runtime und WebUI-genehmigter FullMaintenancejob sind
eigenständige, dadurch nicht ersetzte Nachweise.
## Frühere lokale Nachweise und der danach behobene Binärpinbefund
Das eingefrorene Paket liegt ausschließlich privat unter
`devstate/script-console-qualification/run-de34d47c-985e-460c-b18c-3f0d1b3fd315/`.
Manifest-SHA256:
`60a50262f9f8d85c11eb58e1a9e0f6e03be6cd5db7a59bc1745fb7d9dc8a6f65`.
157 Compiler-, Include-, Fixture- und Deploymentinputs wurden vor/nach dem
vollständigen Lauf identisch geprüft. `reviewed-sources.tar.gz`:
`ef822b2e2ec6f8ad3d828f0923b2aa886d462fba328affb61bd80e98acf2c357`.
Tatsächlich lokal ausgeführt: Formatprüfung; Linux-Workspace-Clippy mit allen
Targets und `-D warnings`; Workspace284PASS bei fünf zunächst ausgelassenen
DB-Fällen; anschließend sämtliche45 Servertests mit `--include-ignored` in
frischem isoliertem PostgreSQL17.6:45PASS,0ignored. DB ohne veröffentlichten Port,
Netzwerknamespace ausschließlich intern, frische Rollen/Migrationen, danach
entfernt. Keine Produktionsdatenbank. Windows-GNU-Alltargets-Clippy separat im
Default- und SYSTEM-Helperprofil jeweils bestanden; keine native Windowsausführung.
Linux-Releasebinaries und vier native Linux-Testprogramme dieses früheren
Quellenstands sind gebaut/gehasht, noch nicht auf der Cloud-VM ausgeführt oder
installiert. **Nachträglicher unabhängiger Reviewblocker:** Dieser Pack bindet
noch nicht den tatsächlichen laufenden Linux-Fullhelpercodehash. Er berechtigt
keine Fullprofilaktivierung. Der danach separat geprüfte und im neuen Pack qualifizierte enge Corefix ergänzt ausschließlich
im Fullprofil tatsächliches gehaltenes `/proc/self/exe`, geschützten Binärpin,
authentisierte Probe, zusätzliche Binärcapability und zentrale Hashprüfung.
General/APT lassen neue Metadaten vollständig aus. Der neue lokale Stand steht
oben; dieser alte Pack bleibt ausdrücklich der ursprüngliche Beleg.
Die ersten Packvorbereitungen erzeugten kein qualifiziertes Manifest: Der erste
before/after-Schutz bemerkte die währenddessen vervollständigte Builderinputliste;
der zweite hielt bei PostgreSQLs temporärer Initialisierungsphase an. Der finale
oben genannte Lauf wartet auf den endgültigen TCP-Endpunkt und besteht vollständig.
Diese Vorbereitungsläufe werden nicht zu bestandenen Abnahmen umgedeutet.
## Separater Linux-first-Unitrunner
Der Runner `deploy/script_console_acceptance.py` ist separat reviewbar und kein
Teil der158 eingefrorenen Compilerinputs; er baut und verändert diese nicht.
Er ist ausdrücklich auf den neuen Pack29461892 und dessen Manifestddd1a78d…
gebunden; bei veränderten Compilerinputs wird ein neuer Start verweigert. Die
ursprüngliche Vorbereitung für Packde34 bleibt ein früherer, nie ausgeführter
Runnerstand. Die jetzigen Counts beruhen auf den tatsächlich erzeugten Listen.
Runnerquellhash:
`2b3ba8d548d18627643a9f73c9a4f7bacce4ac2cd5495745c6760d088e078145`.
Supportquellen werden vor Import und jedem Zielaufruf inklusive Readback exakt
geprüft und in Intent/Payload/Result gebunden: Runtime-Bootstraphelper
`833ad8806c90a19342aa6fbc71c33e81975caffb1746550e9b0fbdca7fa0c7ab`,
Zugangsparser
`5c8107ea9151a9f498b2530cdc61c1a7a6d745aff853a9b05710f3395838c0dd`.
Der finale Readback verlangt product_state_writes, rmm_jobs,
capabilities_activated und approvals ausdrücklich jeweils false.
Er verwendet ausschließlich den vorhandenen strikten Bootstraptransport und
`credentials/linux-vm.conf` im ursprünglichen Hauptcheckout, ausschließlich als root auf der festgelegten Linux-Test-VM, mit vorhandenem
SSH-Key und strenger Hostprüfung. Keine
Zugangsdatenkopie ins Scriptworktree, keine alternative IP oder Passwortfallback.
**Tatsächlich ausgeführt:** Alle vier Listen wurden vor jedem Unitstart geprüft;
84 Tests bestanden, fünf ausdrücklich ausgelassene DB-Verträge waren zuvor im
isolierten lokalen PostgreSQL-Lauf bestanden. Fall
`7b61ce46-7913-492b-9c6b-414a0c2b6ffc`, Beleg-SHA256
`a831a70a3cf76a3e8a9bf5820dcca7100d2ef9860dd9388539fe9c13f949f470`.
Der verwendete Aufruf war:
```bash
python3 deploy/script_console_acceptance.py execute-linux
```
Es entstehen nur neue private Scratchdateien unter
`/var/lib/rmm-script-console-contracts/<case-id>/`. Erst werden alle vier exakten
ELF-Hashes und vollständigen Listen geprüft; kein Unitstart vor dem gesamten
Listenbeleg. Danach feste Testargumente, geleerte Umgebung, eigenes TMPDIR,
eigener Netzwerknamespace und CPU-/Speicher-/Dateilimits. Erwartet werden84PASS
und fünf ausdrücklich ausgelassene DB-Fälle auf der VM ohne DB; dieselben fünf
DB-Verträge sind bereits im isolierten lokalen45er-Lauf belegt. Keine Installation,
Enrollment-, Dienst-, Policy-, Paket-, Schlüssel-, Journal- oder Capabilityänderung.
Bei verlorenem Ergebnis ausschließlich denselben ursprünglichen Fall lesen:
```bash
python3 deploy/script_console_acceptance.py read-linux --case <urspruengliche-case-id>
```
Readback erzeugt keinen zweiten Remote-Start. Ein vorhandener Create-once-
Startmarker erlaubt kein erneutes `run`; Teilergebnisse bleiben erhalten. Ein
unvollständiger/fehlender Beleg ist keine bestandene Abnahme und wird nicht blind
wiederholt. Native Units sind keine RMM-Dienst-/WebUI-/FullMaintenanceabnahme.
## Bootstrapvorbereitung nach gesondertem Erhaltungsreview
Der ursprüngliche Erhaltungsplan und die weiterhin geltenden Schutzgrenzen
folgen unten; tatsächliche Ausführung samt fehlgeschlagenen Teilphasen und
separaten Erststartfortsetzungen steht in den
[Bootstrap-Ergebnissen](../../docs/script-console-bootstrap-results.md).
Aktuelle Cloudbelege, Geräte-/Boot-/
Journalidentitäten, Inodes, Verbrauchszeilen und Dienstzustände werden vor einer
Änderung durch den verantwortlichen Rootprozess unabhängig gegengeprüft. Die
bisherigen General-/APT-Units und Pins sowie deren Historie bleiben erhalten;
keine Ledgerkopie, kein Reset und kein stilles Öffnen alter Scopes.
Die neue Unit ist `deploy/linux/rmm-full-maintenance-helper.service` mit eigenem
Runtimeverzeichnis `/run/rmm-helper-maintenance`. Sie verweist auf
`/etc/rmm-remote/helper-full-maintenance.json`. Diese Konfiguration erhält exakt
die bestehende provisionierte öffentliche Bindingidentität und dieselben
Root-Sharedledger-/Lockdateien; neue Auswahl:
```json
{
"profile": "full_maintenance_v1",
"allowed_services": [],
"allow_reboot": false,
"allow_root_scripts": true,
"allowed_script_profiles": ["full_maintenance_v1"],
"helper_binary_sha256": "<tatsaechlicher SHA256 der qualifizierten laufenden Helperbinary>"
}
```
Das ist ein Ausschnitt, keine vollständige einsatzfähige Konfiguration. Socket,
Agent-UID/GID, Zustandspfad und bestehendes Binding müssen aus dem tatsächlich
geprüften Bestand kommen. Kein `apt_provider`. `allow_reboot=false` verweigert
nur die typisierte Rebootaction; genehmigter Rootcode besitzt volle Hostautorität.
Der separat geschützte Policy-Pin bindet Profil `full_maintenance_v1`, bestehende
Identität, tatsächlichen lokalen Policyhash und unabhängig beobachteten
laufenden Binärhash. Das neue Fullprofil benötigt Schema2 im Pin; der Helper
kann diesen nach selbst geprüftem Rootimage mit dem ausdrücklich getrennten
Bootstrapmodus `--inspect-full-maintenance-profile` ausgeben. Generalpin
Schema1 bleibt unverändert. Agentumgebung ausschließlich
additiv um `RMM_FULL_MAINTENANCE_HELPER_SOCKET` und
`RMM_FULL_MAINTENANCE_POLICY_FILE` ergänzen. Kein Fallback auf General/APT und
keine Änderung deren bestehender Umgebung. Die zentrale Rootpolicy braucht
Schema2 und einen ausdrücklich begrenzten Scope mit neuen exakten Helperpins
sowie `allowed_script_profiles=["full_maintenance_v1"]`. Aktuelle Rechte beider
Planakteure, Helper-Sync, TrustedClock, ursprünglicher Grant und Einmalverbrauch
bleiben zusätzlich erforderlich. Eine Policy ist keine Jobgenehmigung.
Vor Installation werden zusammengesetzte systemd-Unit und etwaige Drop-ins
geprüft: Vollwartung darf keine General-Sandbox erben, die Hostdateisystem oder
Netzwerk unerwartet sperrt. Dienst- und Binärwechsel nur mit qualifizierten
Artefakten und explizitem Erhaltungsplan. Insbesondere darf eine neue allgemeine
Helperbinary nicht still die alten APT-Codepins überschreiben/öffnen. Gegebenenfalls
eigenen qualifizierten Binärpfad für die neue FullMaintenanceunit wählen und die
bestehenden Providerpfade unverändert erhalten. Native Erhaltung und Sync nachweisen,
bevor neue Capabilities/Scopes geöffnet werden.
Erster tatsächlicher FullMaintenancejob nur nach bereitgestellter WebUI und
expliziter Genehmigung der unveränderlichen Skript-/Profil-/Ziel-/Rechtebytes.
Abgestimmter Scope: harmlose Identität/stdout/stderr und kontrollierte lesende
Dateisystem-/Netzwerkbeobachtung; kein Betriebssystemupdate oder Neustart. Volle
Hostautorität wird sichtbar erklärt; kein Sandbox-, No-Reboot- oder Rollbackversprechen.
Windows-SYSTEM folgt nach eigenem Clock-/Pipe-/Profilnachweis. Die vorhandene
PipeV2-Datei ist unverändert SHA256
`ce525dab23f2e4faa2c9816280c1a5a8b40e56d0e63a350256e83b2df1d9229d`;
ursprüngliche native Pipebelege werden nicht als Belege der neuen Runtime ausgegeben.
## Anschließend auf der tatsächlichen Cloud-Linux-VM bestanden
Root führte ausschließlich den korrigierten Pack29461892 nativ aus: Fall
`7b61ce46-7913-492b-9c6b-414a0c2b6ffc`, **84PASS,5explizite DBignored**.
Die vier vollständigen tatsächlichen Listen wurden vor irgendeinem Unitstart
exakt geprüft; anschließend liefen alle vier festen ELFs im eigenen Scratch,
mit geleerter Umgebung, Netzwerknamespace und Ressourcenlimits. Die5DB-Verträge
bleiben diesem VM-Lauf ausdrücklich nicht zugerechnet; sie sind im separaten
isolierten45er-PostgreSQL-Lauf belegt. Kein stiller Testskip oder Produktjob.
Beleg `passed-e214cd9b-21ac-48ce-82dc-d10364329d04.json`, SHA256
`a831a70a3cf76a3e8a9bf5820dcca7100d2ef9860dd9388539fe9c13f949f470`.
Keine Agent-/Helperinstallation, Änderung bestehender Dienste/Policies/PKI/
Datenbanken, veröffentlichte Capability oder WebUI-Genehmigung durch diesen
Unitlauf. Der oben ursprünglich geplante Unitaufruf ist damit abgeschlossen.
Der inzwischen erhaltend ausgeführte Bootstrap steht in den separaten
[Bootstrap-Ergebnissen](../../docs/script-console-bootstrap-results.md);
signierter Folgeabgleich und tatsächlicher FullMaintenancejob sind dadurch
noch nicht abgenommen.
## Verbindlicher Generationsentscheid vor dem Bootstrap
Ein eigener neuer Fullhelper bei weiterlaufendem altem Generalhelper reicht
nicht: Alle aktiven Leser des gemeinsamen Root-Ledgers müssen neue
`privileged_script_profile`-Jobbytes unabhängig dekodieren und prüfen können.
Alte Decoder verweigern selbst geschlossene neue Zeilen und können beim
Snapshot/Sync einen sticky Fault schreiben. Deshalb neuer Agent und aktive
General-/Fullhelper gemeinsam auf die neue qualifizierte Generation; bestehende
Generalunit/Sandbox/Config/Policy-/Pinbytes unverändert. APT bleibt disabled/
inactive, ohne Endpoint und mit geschlossenen Scopes. Seine aktuelle Generation
war bereits laut vorherigem Runtimeindex nicht qualifiziert; historische
Abnahmen bleiben erhalten. Vor späterer Wiedereröffnung eigener APT-Stackpin-
/Generationnachweis, kein alter Helper gegen neue Ledgerzeilen.
Der Rootprozess hat die84 native Cloud-Linux-Units tatsächlich ausgeführt:
Fall `7b61ce46-7913-492b-9c6b-414a0c2b6ffc`, Proof-SHA256
`a831a70a3cf76a3e8a9bf5820dcca7100d2ef9860dd9388539fe9c13f949f470`,
84PASS und5 ausdrücklich ausgelassene DB-Fälle. Diese5 sind im isolierten lokalen
45er-Lauf bestanden. Keine RMM-Jobs oder neue Capabilities aus diesem Unitlauf;
der inzwischen ausgeführte Runtimeaustausch ist separat belegt. Tatsächlicher
signierter Folgeabgleich und genehmigter Fulljob bleiben eigene offene Schritte.
Details und Nach-MVP-Entdeckung:
[script-console-helper-generations.md](../../docs/script-console-helper-generations.md).
-311
View File
@@ -1,311 +0,0 @@
# Agent/helper runtime — integrated source, VM acceptance pending
This is the current runtime contract. It supersedes the earlier module-only
handoffs in `README.md` and `tests/agent_sync/README.md`. No installation, target
job, service/reboot/package mutation, SSH tunnel or server restart was performed
by this integration. Actual VM execution/acceptance belongs to the next worker.
Nothing here approves an RMM job or substitutes for the WebUI approval boundary.
## Binaries and complete CLI/environment
Both binaries support `--help`; unknown arguments fail closed. Normal agent
operation has no positional arguments. Planned bootstrap invocation:
```text
RMM_AGENT_STATE=/var/lib/rmm-agent
RMM_CA_FILE=/etc/rmm/ca.pem
RMM_CONNECT_ADDR=127.0.0.1:18443
RMM_TRANSPORT=https
/usr/local/libexec/rmm-agent
```
These are environment assignments, not an instruction to source a credential
file. The trusted CA and TLS name **rmm-dev.internal** are always checked. TCP
override changes neither DNS/SNI nor certificate verification. No proxy trust,
invalid-certificate bypass or public Docker port is introduced.
| Variable | Meaning/default |
|---|---|
| `RMM_AGENT_STATE` | Private 0700 owned agent state; default `devstate/agent` |
| `RMM_CA_FILE` | Public trusted CA; default `devstate/pki/ca.pem` |
| `RMM_CONNECT_ADDR` | Parsed TCP SocketAddr; default `127.0.0.1:18443` |
| `RMM_TRANSPORT` | `auto` (default), `wss`, or `https`; HTTPS can be explicitly selected for VM acceptance |
| `RMM_ENROLLMENT_TOKEN_FILE` | First registration only; remove the bootstrap token after enrollment |
| `RMM_JOB_BINDING_FILE` | Optional private agent-owned JSON Binding; absent means passive, no job capabilities |
| `RMM_JOB_SIGNING_KEY_BOOTSTRAP=1` | Authenticated device-mTLS GET, using the current rotation-store identity; pins without replacing existing trust |
| `RMM_HELPER_SOCKET` | Configured general helper socket, e.g. `/run/rmm-helper/control.sock` |
| `RMM_HELPER_POLICY_FILE` | Root-owned, agent-readable public general policy pin; required with general socket |
| `RMM_APT_HELPER_SOCKET` | Dedicated fixed `/run/rmm-apt-helper/helper.sock`, never generic fallback |
| `RMM_APT_HELPER_PROOF_FILE` | Root-owned public APT stack/profile/identity pin; see `apt-helper-README.md` |
| `RMM_LOG_UNITS_FILE` | Private agent-owned JSON array of exact allowed service units for unprivileged live logs |
| `RMM_EXTENDED_INVENTORY` | `1` by default with the now-compatible backend, `0` for legacy base-only JSON |
| `RMM_AGENT_PROFILE` | `development` required only for the rotation-test interval override |
| `RMM_ROTATION_TEST_AFTER_SECONDS` | Positive development-only certificate-age trigger; never bypasses chain/expiry/EKU/key/identity verification |
Binding fields: tenant_id, asset_id, agent_id, enrollment_generation,
assignment_version, public_key_hex. Device/asset must match enrollment. Empty key
is allowed only with authenticated signing-key bootstrap; later startup must
reauthenticate that bootstrap or use a fully provisioned binding. Key response is
Ed25519/schema 1/raw 32-byte key with SHA-256 key ID, bounded and no redirects.
The immutable agent cache is `job-signing-key.json`. Signing-pin replacement and
identity/assignment recovery are controlled provisioning operations, not automatic
trust in a key from a job. Helper trust stays independently root-provisioned.
The unit leaves the job-binding optional in `/etc/rmm/agent.env`, allowing a first
passive enrollment. Set binding/key-bootstrap/helper variables only after the
authenticated operator resolves the enrolled IDs and provisions their pins.
Do not delete an old identity/journal to get a new first-session shortcut.
## Integrated transport and sync
One bounded actor and one dispatcher serve WSS and HTTPS with identical envelopes,
journal, result receipts, cancellation and signature checks. `auto` tries WSS
first and falls back only after two typed HTTP upgrade-block classifications;
401/403, TLS/identity failures and ambiguous errors never select a bypass.
WSS Ping/Pong are handled. HTTPS uses the existing MessageBatch/25-second poll
contract. Poll cancellation cannot create a new attempt; fresh heartbeat IDs/
sequences are never reused or queued as offline telemetry. Actor queues are bounded.
Every authenticated Hello advertises `rmm.sync.v1` and closes all local effect
gates. Agent obtains actual root snapshots, durably reserves the fresh SyncRequest,
checks exact signed SyncResponse bytes and all device/channel/boot/checkpoint/
request-hash/time bindings, commits targeted journal/receipt changes, applies its
own consumption decisions, forwards the **original** signed response plus original
request protobuf to every configured helper, then confirms actual applied root
checkpoints. No generic ready boolean opens either process.
Both root profiles share actual DB/lock inodes. They join an unchanged pending
root capture created after both process births, so ONE signed response/checkpoint
can be independently applied by both. A new process never inherits readiness
from the shared DB. Stale process captures are fenced; known outcomes may unlock
specifically while an unknown retains the resource and global gates stay closed.
Consumed grant/attempt tombstones are never removed.
Scheduler AND immediate worker effect admission check the current signed lease;
the worker also rechecks fresh grant/time and the disconnect/rotation atomic fence.
Helper checks its own process gate under the same executor guard before consumption.
Unknown, missing authoritative history, clock failure and rollback remain closed.
Clock/helper sync failure does not stop independent passive heartbeat/inventory
traffic. Sync retries are bounded, happen on fresh inventory/result ACK and on a
lease timer, and never retry a lost permit request as a new grant.
After reboot, old/new boot ID alone is not success. Fresh current-boot inventory
is durably ACKed, a new signed decision must bind the persisted original boot and
current authenticated boot plus inventory evidence, then each helper independently
applies that specific canonical terminal outcome/unlock. Thus an initial negative
sync does not deadlock waiting forever without the post-inventory resync.
Result envelopes are archived before concrete ACK deletion in one SQLite
transaction. Historical message identity/output is retained for reconciliation.
Inventory mapping preserves source/time/quality/completeness and unsupported states.
Live journal permission warnings become permission_denied, not a fake empty success.
## Helper bootstrap/policy inspection
Helper normal daemon: `RMM_HELPER_CONFIG=/etc/rmm/helper.json` (root-owned 0600).
Both profiles use `/var/lib/rmm-helper/consumption.sqlite` and `executor.lock`.
Helper config uses the existing binding, optional independent signing_key_file,
agent_uid, socket_gid, socket, shared state, allowed_services, allow_reboot,
allow_root_scripts; APT adds its existing sealed apt_provider configuration.
Public general pin, **planned command, not executed on VM here**:
```text
RMM_HELPER_CONFIG=/etc/rmm/helper.json /usr/local/libexec/rmm-privileged-helper --inspect-general-profile
```
Install the exact JSON as root:rmm-agent 0640 in non-writable root-owned parents,
then set RMM_HELPER_POLICY_FILE. It binds profile, device identity/key and exact
policy hash. General policy probe uses root socket/peer credentials and a fresh
challenge; capabilities reflect actual policy/interpreter availability. Root
scripts remain default-off broad administration. Services are exact allowed
running/stopped units with >=180s runtime, reboot separately enabled with >=60s.
Root jobs are NEVER relabelled into agent_service.
APT install/probe/inspection modes and profile sandbox remain exactly documented
in `apt-helper-README.md`. Both daemons need this same installed build and reviewed
new proof hashes (binary bytes are part of the APT proof). Prefetched sealed
archives, receipts predating the grant and exact baselines are still prerequisites;
this integration introduces no unsafe generic APT download/install/simulation path.
Root native-acceptance and accepted-recipe/manifest capabilities come only from
authenticated real readiness. Successful native acceptance triggers a controlled
reconnect to advertise newly accepted recipes; periodic safe capability refresh
also reconnects rather than silently changing the Hello contract.
## Passive APT planning and declarative no-change
The normal extended inventory worker now runs at startup and every 60 seconds
(one inflight collector; not in the heartbeat handler). Unacknowledged durable
traffic backpressures new collection without deleting old data; job results and
control receipts retain priority. It includes the fixed
`linux.apt.planning` scope from `root-helper:apt_planning_v1`. This currently
refreshes the existing extended inventory scopes too; their actual individual
source timestamps/quality remain intact. There is no arbitrary package query,
requested live diagnosis or software effect hidden in this collector.
`apt_planning_v1` uses the existing UID-authenticated dedicated Unix socket,
fresh challenge, device/generation/signing-key identity, root peer and separately
root-provisioned stack pin. Its response is the readiness envelope with a typed
`planning` result and **empty capability/acceptance fields**. It does not depend
on a prior native-acceptance record and cannot create one. Root validates the
installed code, exact runtime/config policy pins and actual archive bytes, sizes,
ownership/modes/link count and private prefetch receipts. No artifact is fetched
or installed by this RPC. Administratively stage the known fixture archives via
`provision-fixture-store` before planning/the final 60-second grant.
The fixed metadata child has a 4-second whole-process/output budget (32 KiB),
the socket has 5-second IO limits, and root measurement timestamps are preserved.
Dirty dpkg updates/triggers, foreign locks, unsafe/missing receipts, permission
failure, timeout or missing helper yield an unknown observation with null data,
not fake hashes or accepted capability. Runtime policy drift fails closed.
Complete observations contain the suite's `fixture_package`, `baseline_sha256`,
`sealed_baseline_sha256`, `status_fingerprint`, `dpkg_updates_empty`,
`pending_triggers_empty`, `runtime`, `runtime_sha256`, `provider_sha256`,
`hook_sha256`, `apt_config_sha256` and `prefetch`. The full package baseline stays
root-private at `baselines/<sha256>.json`; only hashes, fixture projection and
minimal public runtime/artifact pins cross the wire. Stable sampling is checked
before and after content-addressed exclusive write/file+directory fsync; existing
identical seals are verified, never overwritten. This is passive metadata, not
job authority. The ordinary durable inventory outbox/ACK path persists it.
Normal accepted fixture `ensure_package`/`apply_updates` may return
`POSTCONDITION_ALREADY_MET`, `changed=false`, `already_desired=true`,
`postcondition_already_met=true`, `transaction_executed=false` only when the
**entire selected set** is independently installed at its exact target version
and architecture, clean, matches the current approved baseline/fingerprint and
has the expected fixture payload. Root signature, all original bindings,
expiry/sync/local-policy/resource gates, all manifest/code/runtime/artifact pins,
native accepted-recipe record and durable grant/attempt consumption remain
mandatory. Only the historical `old_version` condition is skipped in this
no-mutation branch. No APT/hook/native launch/effect marker is created. A foreign
lock, dirty/unknown state or changed baseline cannot become success; native
acceptance itself never uses this branch. Other versions still follow the
unchanged no-reinstall/no-downgrade/no-remove mutation guards.
VM suite owner must update its absent/1.0-only adapter: after native update to
1.1, a normal exact desired-1.1 job must use the accepted update recipe with a
fresh planning seal. A desired-1.0 job on 1.1 is still correctly denied; this
implementation does not authorize removal/downgrade to make a stale test pass.
No backend/domain/protobuf signatures or plan bytes have been changed.
Provider source changes change the embedded provider/helper/stack/runtime pins.
Deploy both helpers from this build and provision reviewed new proof/policy
pins **before** native acceptance; old native records cannot silently certify
new runtime bytes. Manifest schema 2 / transaction schema 1 / fixture archives
1.0 and 1.1 (20,672 bytes, unchanged hashes) remain unchanged.
These are implemented source/local-fixture semantics, not VM or MVP acceptance.
## Certificate rotation and recovery
`RMM_AGENT_STATE/certificates/current.json` is the authoritative atomic selector
over private versioned device key/cert files. Existing enrolled files initialize
the store exactly once; later connections/bootstrap use the selected identity.
Rotation checks chain, current validity, exact agent CN, clientAuth purpose and
public/private key match. It persists one pending key/CSR and retries those SAME
CSR bytes after response loss. A verified swap closes the old actor/effect fence
and requires a new Hello/Sync. Agent/enrollment IDs and independent job/helper
signing pins do not change. Expired/revoked/invalid certs remain blocked and need
authorized identity recovery; no auto-reenrollment or TLS downgrade.
## Verification boundaries / concrete remaining policy issue
Local Rust source/unit/integration tests cover actual loopback mTLS dispatcher
WSS/HTTPS clean reconnect, Ping, forged sync rejection, passive traffic with an
untrusted effect clock, journal reopen/replay and independent helper checkpoint/
outcome/boot checks. Unsafe OS providers are mocked or denied; no local service,
APT install or reboot was executed. This is not a real WebUI-approved VM result,
native package acceptance, production auth acceptance or full Linux-MVP sign-off.
Concrete backend policy limitation, not bypassed here: `RootScope::permits` in
`crates/server/src/root_policy.rs` does not match `Action::QueryLogs` and falls
through to false. The typed, bounded root helper log handler exists, and the
unprivileged allowlisted path is live, but a root live-log plan will be denied by
that backend policy until its owner adds an explicit permitted scope. Do NOT
work around it by relabelling identity, direct approval or a generic root shell.
## Executed local verification
Using `/home/Kevin/.cargo/bin/cargo`, actually passed during integration:
```sh
cargo test -p rmm-agent -p rmm-privileged-helper -p rmm-agent-linux --all-targets --locked
cargo clippy -p rmm-agent -p rmm-privileged-helper -p rmm-agent-linux --all-targets --locked -- -D warnings
cargo build -p rmm-agent -p rmm-privileged-helper --locked
cargo fmt -p rmm-agent -p rmm-privileged-helper -p rmm-agent-linux -- --check
python3 tests/agent_jobs/test_install.py
target/debug/rmm-agent --help
target/debug/rmm-privileged-helper --help
```
111 executed Rust test cases passed (including reused transport tests), two
create-only installer guard tests passed, both debug binaries built and both
help commands returned successfully without loading secret configuration. No
warnings/type errors were suppressed. A boxed tungstenite HTTP-response test
constructor was corrected, not bypassed. No coverage percentage was measured.
Coverage boundaries: real loopback TLS/dispatcher WSS and HTTPS reconnect and
forged sync rejection are exercised; helper cryptography/checkpoints/two-process
shared signature and replay/unknown/reboot decisions use real SQLite/signatures
with local fixtures. Native service/APT/reboot effects and positive root UID-0
daemon/VM RPC acceptance are NOT substituted by these tests. The built artifacts
are `target/debug/rmm-agent` and `target/debug/rmm-privileged-helper`; a reviewed
VM-compatible release artifact still needs the target worker's ELF/glibc/library
preflight and actual authorized VM run.
## Executed local verification — planning/no-change increment
After **all** source changes, the following complete targeted block passed with
`/home/Kevin/.cargo/bin` on PATH (2026-11-12):
```sh
cargo test -p rmm-agent -p rmm-privileged-helper -p rmm-agent-linux --all-targets --locked
PYTHONDONTWRITEBYTECODE=1 python3 -m unittest discover -s tests/apt_transaction -p 'test_*.py' -v
cargo clippy -p rmm-agent -p rmm-privileged-helper -p rmm-agent-linux --all-targets --locked -- -D warnings
cargo fmt -p rmm-agent -p rmm-privileged-helper -p rmm-agent-linux -- --check
cargo build -p rmm-agent -p rmm-privileged-helper --locked
cargo build -p rmm-agent -p rmm-privileged-helper --release --locked
python3 tests/agent_jobs/test_install.py
target/debug/rmm-agent --help
target/debug/rmm-privileged-helper --help
```
Results: **115 Rust tests**, **56 Python APT tests**, **2 installer guard tests**
passed; warning-denying all-target Clippy and formatting passed; both Debug and
Release binaries built; both help commands succeeded. Separate final AST parsing
passed for **8 Python files**. No full workspace/backend/web test suite was run.
New regressions cover shared Python/Rust canonical golden bytes/hash, receipt
and timestamp freshness, private content-addressed seal reuse/change without
full-baseline disclosure, sampling drift/dirty/foreign-lock/bad-artifact failure,
normal exact already-desired install/update postconditions, no launch/effect
markers, old-version mutation rejection, wrong architecture/newer version,
audit/payload/expiry rejection, no-change outcome binding and durable duplicate
grant/attempt rejection, honest missing-helper data and collection backpressure.
Root ownership/kernel state and unsafe native package processes are mocked;
existing harmless unprivileged seccomp tests really execute. No native host
package mutation, root systemd/probe/VM action, approval or reboot was performed.
Earlier intermediate failures were corrected, not suppressed: the inherited two
unformatted source edits, a mock reader missing the `limit` keyword argument,
and a newly inserted function accidentally inheriting a test-only cfg attribute.
The final complete block above passed after these corrections.
Final artifact SHA-256 (native developer-PC builds; **not** Bookworm/VM proof):
| Artifact | SHA-256 |
|---|---|
| `target/debug/rmm-agent` | `90a4eab064301740cd938a41a76a510ad3b4abc3e48a188ba12bfe22f123266c` |
| `target/debug/rmm-privileged-helper` | `54db2fe17841fef9af48bbeb446f45bda52f62e442a4900e0543e358095900b7` |
| `target/release/rmm-agent` | `eac5434fd7a1e509c0971e4e05d4e1aedbde1bb90f7d7a8f9ec4d48ab4d34597` |
| `target/release/rmm-privileged-helper` | `581a033478b41365066df2dc9ac0d11e314160909b5fab612be0be97be1bbbdc` |
| `tools/apt-transaction/apt_transaction.py` | `57b695bf57ea2703393e39f92a1b6ef2314b4838f3dfb29e4e70da79687c9987` |
Remaining: suite-owner adapter update for exact desired 1.1 after native upgrade,
reviewed deployment/new pins, actual dedicated-profile metadata RPC and native
UI-approved fixture/no-change VM proof, target ELF/library compatibility, and
VM resource/retention measurements for the new 60-second extended collection.
No real current baseline change was induced on the host/VM: freshness tests use
changed temporary/mock package state, not a disguised package installation.
Linux-MVP and production acceptance remain open. Backend Root QueryLogs policy
is owned by its separate worker and was neither changed nor reverified here.

Some files were not shown because too many files have changed in this diff Show More