Merge security follow-ups: host-side PE-cache signing, worker no longer holds the HMAC key (#1014); Akka remoting untrusted-mode + trusted-selection-paths by default, opt-in mutual TLS (#1003)

This commit is contained in:
Joseph Doherty
2026-12-03 15:40:32 -05:00
26 changed files with 1720 additions and 105 deletions
+3
View File
@@ -173,6 +173,9 @@ Security__Ldap__GroupToRole__<AD group>=Viewer
| `Port` | int | `4053` | Cluster transport port. **Duplicated as `ClusterNode.AkkaPort` in the Config DB** — see the note below. |
| `PublicHostname` | string | `127.0.0.1` | Hostname advertised in cluster gossip; must be reachable by peers. **Duplicated as `ClusterNode.Host`** — see the note below. |
| `SeedNodes` | string[] | `[]` | Seed nodes for bootstrapping. **Ordered:** a node that appears in its own list must be entry 0 (only `seed-nodes[0]` can form a new cluster), or the host refuses to start — see [Redundancy.md § Bootstrap: self-first seed ordering](Redundancy.md#bootstrap-self-first-seed-ordering). **Per-pair since Phase 6:** each application `Cluster`'s pair is its own Akka mesh, so a node's `SeedNodes` lists only itself (first) and its own pair partner (second) — never a node from another cluster's pair. |
| `Remoting:UntrustedMode` | bool | `true` | Akka `untrusted-mode` with the trusted selection paths this code base uses (lmxopcua#1003). Receive-side only; a drop is a Warning naming the path. See [security.md § Akka remoting hardening](security.md#akka-remoting-hardening-clusterremoting-lmxopcua1003). |
| `Remoting:AdditionalTrustedSelectionPaths` | string[] | `[]` | Extra `/user/…` / `/system/…` paths a peer may reach by selection. |
| `Remoting:Tls:*` | object | `Enabled=false` | Opt-in mutual TLS on the remoting transport (`CertificatePath`+`CertificatePassword` or `CertificateThumbprint`+store, `RequireMutualAuthentication=true`, `AllowedThumbprints`, `ValidateCertificateHostname`). Both nodes of a pair change together. |
| `Roles` | string[] | `[]` | Cluster roles for this node. When empty, falls back to `OTOPCUA_ROLES` (see the note below). Values are trimmed and (for a plain role) lower-cased; a cluster role's ClusterId suffix keeps the operator's spelling. An unknown role from either source **fails host start**. Allowed values: `admin`, `driver`, `dev`, plus a per-cluster `cluster-{ClusterId}` role (e.g. `cluster-MAIN`, `cluster-SITE-A`) — see [Per-cluster mesh split (Phase 6)](#per-cluster-mesh-split-phase-6-cluster-clusterid-roles--splittopologytransportvalidator) below. |
> **One role authority, one precedence, both consumers (archreview R3-04).** `EffectiveRoles.Resolve` (`ZB.MOM.WW.OtOpcUa.Cluster`) is the SINGLE place a node's roles are decided: `Cluster:Roles` wins outright when non-empty, else `OTOPCUA_ROLES`, else empty. Both `Program.cs`'s conditional host wiring (which subsystems mount) AND the Akka `AkkaClusterOptions.Roles` gossiped to the cluster are the SAME `EffectiveRoles` instance's `Gossiped` list — not two separate derivations that happen to usually agree. The boot banner (`OtOpcUa.Host starting with roles=[...] source=...`) names which source won. Setting both sources to *different* normalized role sets logs a Warning at boot (still resolves from `Cluster:Roles`) — almost certainly not what an operator intended.
+3 -2
View File
@@ -97,7 +97,8 @@ and a Shutdown frame then a kill on host stop. Their stderr lands in the host lo
At startup the host kills workers a dead predecessor of the same install left behind, matched by launch marker
(pid + start time + image, and only when the marker's host is gone). `Scripting:Worker:PeCacheDir`, when set, holds the
compiled-PE cache, its HMAC key and the launch markers: put it outside the install folder (startup refuses a relative path
or one inside the content root) on a directory only the service account can read. The `script-runner` readiness component
or one inside the content root) on a directory only the service account can read. Since lmxopcua#1014 only the host reads
or writes it (workers receive verified images over the pipe, never the key). The `script-runner` readiness component
is at worst Degraded. A self-contained host publish (`dotnet publish … -r win-x64 --self-contained`, the Windows installs, which have no
.NET runtime) ships a **self-contained** worker in `script-worker/` (~97 MB: it carries its own runtime) and the host starts its
`ZB.MOM.WW.OtOpcUa.ScriptWorker.exe` apphost directly; a framework-dependent host (docker-dev) runs the worker's dll through the
@@ -113,7 +114,7 @@ dotnet muxer. See `docs/VirtualTags.md` §"Out-of-process runner".
| Worker identity | A **disabled** anchor service `OtOpcUaScriptWorker` running as `NT SERVICE\OtOpcUaScriptWorker`, so the virtual account exists. It is never started. |
| `Scripting:Worker:Identity` | With `NT SERVICE\OtOpcUaScriptWorker` set (by `-ConfigureHostService`, or in appsettings), the host starts every worker under a **restricted token** derived from its own: every privilege but `SeChangeNotifyPrivilege` removed, and restricting SIDs = the identity + `Everyone` + `BUILTIN\Users` + `RESTRICTED`. Every access the worker makes must pass for the host account **and** for that set. The token's default DACL is host + SYSTEM + identity; the worker is created suspended and put in its Job Object before it runs; `TEMP`/`TMP` point at its per-launch working directory (ACL: host + SYSTEM full, identity Modify); `DOTNET_EnableDiagnostics=0`. The host also adds the identity to its own window station and desktop DACL (enumerate/read, and create-window on the desktop), once per process. USER32 connects to them in its DllMain and the runtime imports USER32, so without the grant `coreclr.dll` fails to load (`ERROR_DLL_INIT_FAILED`, measured on windev). The grant lives on the session's kernel objects and ends with the session; nothing persistent changes. The logon SID, which those objects normally grant, is deliberately not a restricting SID: the host's process DACL gives it `PROCESS_VM_READ`. Windows cannot start an ad-hoc child process *as* a virtual account (only the SCM can, for a service), and a separate local user would need a stored password plus `SeAssignPrimaryTokenPrivilege` on the host account; a restricted copy of the host's own token needs neither. Startup refuses the key off Windows or when malformed. |
| Pipe ACL | On Windows the worker pipe always carries an explicit, protected DACL: the host account and (with an identity) the worker identity, read/write, nobody else. No SYSTEM, no Administrators, no Everyone. The owner is the host token's owner, so the worker's `CurrentUserOnly` check of the server end still holds. |
| `PeCacheDir` | Created with a protected ACL: SYSTEM, Administrators and the host account full control, no Users. `pe\` grants the identity Modify (workers compile and write entries). The HMAC key and `workers\` markers are host-only. |
| `PeCacheDir` | Created with a protected ACL: SYSTEM, Administrators and the host account full control, no Users. `pe\` grants the identity Modify — **unused since lmxopcua#1014**: the host now verifies, compiles and writes every entry and sends verified images over the pipe, so a worker no longer touches the directory (anything it could still drop in `pe\` fails the host's HMAC check; removing the grant is a follow-up). The HMAC key and `workers\` markers are host-only. |
| Install folder | The identity is **denied** read and write on `<InstallRoot>` (inherited: ReadData/List, WriteData/AddFile, AppendData/AddSubdirectory, write attributes/EA, Delete, DeleteChild, ChangePermissions, TakeOwnership; Traverse/Execute, ReadAttributes and ReadPermissions stay so the loader reaches `script-worker\`). The worker cannot read `appsettings*.json`, logs or host binaries even where `Users` can. `script-worker\` grants it read + execute. |
| Sensitive folders (`-DenyPaths`, lmxopcua#890) | The same inherited deny on every listed folder. **Name every folder outside `<InstallRoot>` that holds keys, secrets, stores, logs or backups**: the worker's restricting SIDs include `Everyone` and `BUILTIN\Users`, so anything Users can read is otherwise readable to it (and a data drive usually lets Users create files in subfolders, e.g. a certificate in `pki\trusted\certs`). Name the deployment folder around `<InstallRoot>` (one ACE covers `pki\`, `data\`, `logs\`, `backup\`, old `app.bak.*`) **and** `pki\` and `data\` themselves, so the deny holds even on a folder whose DACL does not inherit. Drive and share roots, `script-worker\` and the PE cache are refused; each folder must exist. The list is recorded under `HKLM\…\Services\OtOpcUaScriptWorker\Parameters` (`DenyPaths`): a re-run removes the deny from folders dropped from the list, and `-Uninstall` removes every recorded one without repeating `-DenyPaths`. After an apply the installer WARNs about any item under a denied folder whose DACL is protected and has no deny of its own (the inherited deny does not reach it); without `-DenyPaths` it WARNs about `pki`/`data`/`logs`/`backup`/`config`/`secrets` siblings of `<InstallRoot>`. Wonder layout: `-InstallRoot E:\ApiInstall\OtOpcUa\app -DenyPaths E:\ApiInstall\OtOpcUa,E:\ApiInstall\OtOpcUa\pki,E:\ApiInstall\OtOpcUa\data,C:\ProgramData\ZB\kek` plus, box-wide (lmxopcua#891), every other app folder under `E:\ApiInstall` and the staging folders `E:\psrem-stage`, `E:\psrem`; keep deploy backups (`.reg` exports, appsettings copies) in a folder with a protected SYSTEM + Administrators ACL. |
| Firewall | Outbound **block** rule `OtOpcUa-ScriptWorker-BlockOutbound` on `script-worker\ZB.MOM.WW.OtOpcUa.ScriptWorker.exe`, every profile. It covers the self-contained apphost the Windows installs run. A framework-dependent worker runs under `dotnet.exe` and is not covered, so there the analyzer's `System.Net` ban is the only network control. |
+27 -9
View File
@@ -147,15 +147,33 @@ processes:
`Unavailable`: one Error is logged, evaluations answer `script runner unavailable` at once instead of each waiting out
`UnavailableGrace`, and the shards keep retrying at the backoff cap.
- **Compiled-PE cache** (`Scripting:Worker:PeCacheDir`, optional; absolute and outside the content root, or startup
fails). Workers write each compiled image to `<dir>/pe/<id>.pe`, authenticated with HMAC-SHA256 under a per-node
random key (`<dir>/pe-cache.key`, created by the host; 0600 / directory 0700 on Linux and macOS, the directory ACL on
Windows), and a restarted worker loads the image instead of re-entering Roslyn. The id is SHA-256 over the source, the
context kind and a compile fingerprint (Roslyn version, the `Core.Scripting` build — analyzer, wrapper, stack guard —,
the sandbox reference set, the runtime), so a compiler or analyzer change misses every old entry. An entry that fails
verification (edited, truncated, another key, copied under another id) is deleted and the source recompiled; the
worker never loads bytes that did not verify. The key reaches the worker in `Hello`, never on disk or in its
environment. Entries unused for 30 days, and the least recently used beyond 50 000, are pruned at startup; the
directory can be deleted at any time. Measured on macOS (40 scripts, restart to every first result): 820 ms with no
fails). Each compiled image lives in `<dir>/pe/<id>.pe`, authenticated with HMAC-SHA256 under a per-node random key
(`<dir>/pe-cache.key`, created by the host; 0600 / directory 0700 on Linux and macOS, the directory ACL on Windows), and
a restarted worker loads the image instead of re-entering Roslyn. The id is SHA-256 over the source, the context kind
and a compile fingerprint (Roslyn version, the `Core.Scripting` build — analyzer, wrapper, stack guard —, the sandbox
reference set, the runtime), so a compiler or analyzer change misses every old entry. An entry that fails verification
(edited, truncated, another key, copied under another id) is deleted and the source recompiled. Entries unused for 30
days, and the least recently used beyond 50 000, are pruned at startup; the directory can be deleted at any time.
- **The host owns the cache; the worker holds no key (lmxopcua#1014, review K-1 option 4).** Until #1014 the worker read,
verified and *wrote* entries with the key it was handed in `Hello`, and a verified image is loaded without re-running
the analyzer — so code that escaped inside a worker could sign an entry for any script's source and persist across
restarts and redeploys. Now the host reads and verifies the entry and ships the image inside the load
(`ScriptSource.pe_image`); on a miss the worker compiles as before and, only once that compile has **succeeded**, the
host queues **its own** compile of the same source (one background thread, below-normal priority, de-duplicated; the
same pipeline and analyzer as the in-process runner and the deploy gate, never loaded in the host) and writes the
signed entry. Filling after the worker's success keeps a source that crashes Roslyn inside the worker's isolation
machinery. `Hello` carries neither the key nor the directory, so the worker never opens the cache.
- **Compatibility.** The host compiles against its own runtime, so it ships images only to a worker whose
`Ready.pe_image_abi` (`ScriptSandbox.ImageAbi`: runtime version + the pinned assemblies' full names) equals its own;
any other worker compiles every script (one Warning per distinct value). An image that does not load in the worker is
reported `rejected`, the source compiled, and the host evicts and refills the entry.
- **Upgrade.** The entry format moved to version 2: every entry a pre-#1014 worker wrote (any of which may have been
forged) fails the magic check on first use, is deleted, and is refilled by the host — the first start after the
upgrade is a cold one. `Scripting:Worker:PeCacheDir` and the directory layout are unchanged; nothing to configure. The
installer's `pe\` Modify grant to the worker identity is now unused (a worker could only drop or add files the host
then rejects); removing it is a follow-up.
- **Cost.** A miss now compiles twice — once in the worker (to run), once in the host (to cache), off the evaluation
path. The host loads Roslyn the first time it fills. Measured on macOS (40 scripts, restart to every first result): 820 ms with no
cache, 840 ms with an empty one, **85 ms warm**; on windev (Windows) 9.5 s / 9.4 s / **1.0 s**. An unusable directory is a Warning and a cache-less runner.
- **Orphan sweep.** Every launched worker gets a marker (`<PeCacheDir>/workers/<pid>.worker`, or a per-install
directory under temp) naming its pid, start time and image, and the host's pid and start time. At startup the runner
+75 -4
View File
@@ -1826,7 +1826,76 @@ The page used to feed `?node=` (or the typed host:port box) straight into an Akk
The page policy stays `AuthenticatedRead`: `/fleet` and `/hosts`, which link to it and show the same driver-health data, are the same tier, and with the closed set a Viewer can no longer steer the admin node's outbound connections.
**Open (not fixed here): Akka remoting is not hardened.** The embedded HOCON (`Cluster/Resources/akka.conf`) sets no `akka.remote.untrusted-mode` / `trusted-selection-paths`, and `WithRemoting` configures no TLS. Untrusted mode is not a drop-in switch on a cluster node (it blocks the system messages and `/system/...` selections that cluster gossip, DistributedPubSub and singletons rely on), so it needs its own design — see the follow-up issue.
**Akka remoting itself** is hardened since lmxopcua#1003 — untrusted mode on by default, mutual TLS opt-in; see the
next section.
### Akka remoting hardening (`Cluster:Remoting`, lmxopcua#1003)
Every node listens for Akka remoting on `Cluster:Port` (4053). Two independent controls, configured under
`Cluster:Remoting`:
**1. Untrusted mode — ON by default.** `akka.remote.untrusted-mode = on` with an explicit
`trusted-selection-paths` list (`RemotingHardening.TrustedSelectionPaths`). What it does in Akka.NET 1.5 (read off
`Akka.Remote.DefaultMessageDispatcher`, the setting's only consumer): an inbound `ActorSelection` is delivered only to a
listed path; messages for the remote daemon (**remote deployment**) are dropped; an `IPossiblyHarmful` message
(`PoisonPill`, `Kill`, …) sent by a peer to any actor reference is dropped; a message a peer asks this node to forward to a
third system is dropped. Messages to actor *references* (DistributedPubSub delivery, replies, `Ask` temp actors) and
system messages (remote watch) are unaffected — so, contrary to the earlier note here, untrusted mode does **not** break
cluster gossip, DPS or singletons, provided their selection paths are trusted. The trusted set is every path this code
base reaches by selection across nodes, enumerated from the Akka 1.5.62 sources and this repo:
| Path | Used by |
|---|---|
| `/system/cluster/core/daemon` | Akka.Cluster gossip, InitJoin/Join/Welcome, the seed-node processes, leave/exiting |
| `/system/cluster/heartbeatReceiver` | cluster failure-detector heartbeats |
| `/system/remote-watcher` | remote-watch heartbeats |
| `/system/distributedPubSubMediator` | DistributedPubSub registry gossip (redundancy-state, the DPS transports, secrets replication) |
| `/user/{name}`, `/user/{name}/{name}` for each singleton (`config-publish`, `admin-operations`, `audit-writer`, `redundancy-state`, `cluster-node-address-reconciler`, `deployment-retention`) | manager-to-manager hand-over; the proxies' `Identify` |
| `/user/driver-host` | `/fleet/diagnostics` (`FleetDiagnosticsClient`), also across meshes |
Coverage is proven, not asserted: `RemotingHardeningClusterTests` (real pairs through the shipped bootstrap — formation,
a singleton reached through its proxy and handed over on leave, DPS across nodes, zero drops; a selection to any other
path dropped; the same selection delivered with the mode off) and `UntrustedModeHarnessTests` (the full two-node Host
stack — every ControlPlane singleton + proxy, the redundancy singleton, runtime actors, deploys from both nodes, the
diagnostics selection, node B restarting — zero drops, with a positive control that the monitor records one).
`RemotingTrustedPathsCoverageTests` fails when a new singleton constant or a new `ActorSelection` in `src/` appears
without its path. A drop is logged as a **Warning** naming the path (once per path; Akka logs it at Debug) and counted on
`otopcua.cluster.remoting.untrusted_drops`.
What it does **not** do: authenticate the peer. The cluster daemon must stay reachable for joining to work, so any host
that can reach the port can still associate — and join. That is what TLS is for.
- **Upgrade:** nothing to configure; the filter is receive-side only, so a mixed old/new pair keeps working through a
rolling upgrade (both send the same selections). If a drop Warning ever names a path OtOpcUa itself uses, add it to
`Cluster:Remoting:AdditionalTrustedSelectionPaths` (and file it); `Cluster:Remoting:UntrustedMode = false` is the
escape hatch.
**2. Mutual TLS — opt-in (`Cluster:Remoting:Tls:Enabled`, default `false`).** The DotNetty transport runs TLS, and with
`RequireMutualAuthentication` (default `true`) the accepting side demands a client certificate too — so only a peer
holding an accepted certificate can associate at all.
| Key | Default | Meaning |
|---|---|---|
| `Enabled` | `false` | TLS on the remoting transport. The address scheme becomes `akka.ssl.tcp`; `Cluster:SeedNodes` may keep `akka.tcp://` (rewritten at startup). |
| `CertificatePath` / `CertificatePassword` | — | The node certificate as an absolute-path `.pfx` with its private key; supply the password as `${secret:…}` or an env var. |
| `CertificateThumbprint` / `CertificateStoreName` / `CertificateStoreLocation` | — / `My` / `LocalMachine` | Alternatively, a certificate in a store (Windows). Exactly one source is required. |
| `RequireMutualAuthentication` | `true` | Demand a client certificate on inbound associations. Turning it off leaves the link encrypted but open to any client. |
| `AllowedThumbprints` | `[]` | SHA-1 thumbprints accepted from peers. Non-empty ⇒ pin only (self-signed works, no CA). Empty ⇒ the peer chain must validate against the machine trust store. |
| `ValidateCertificateHostname` | `false` | Also require the peer certificate's CN/SAN to match the host it was dialled at. |
Startup refuses `Enabled` with no certificate source (or two), a relative or missing `CertificatePath`, a malformed
thumbprint, or a certificate without a private key. Proven by
`RemotingHardeningClusterTests.Mutual_tls_forms_a_mesh_between_pinned_peers_and_keeps_an_unpinned_node_out`.
- **Rollout (TLS is all-or-nothing per link).** A TLS node and a plain node cannot associate, so: issue one certificate
per node (or one per pair), put every peer's thumbprint in `AllowedThumbprints` on **both** nodes of a pair, then
**stop both nodes, set `Cluster:Remoting:Tls` on both, start both** — a one-at-a-time restart leaves the pair split
across the change (each side forms its own cluster ⇒ two Primaries until the second node is converted). An admin
node's `/fleet/diagnostics` dials every node's `driver-host` over remoting, so either convert the whole fleet or
expect diagnostics of a node on the other transport to come back empty (it degrades, it does not fail). The
certificates of the admin nodes must be pinned on the nodes they query.
- Rolling back is the same in reverse (both nodes together).
---
@@ -1966,9 +2035,11 @@ deploy is rejected if any in-use stored script uses an API now refused; see `doc
Residual exposure, by design: a script can still burn CPU and memory up to its budget (`ScriptRunGuard`; pre-emptive
limits need `OutOfProcess`), read any tag through `ctx.GetTag`, and write virtual tags. Extending the allow-list is a
security change — add only types with no I/O, process-wide state, background work, blocking wait or reflection
surface. The out-of-process runner's compiled-PE cache is still HMAC-signed by the **worker** with a key it is handed
in `Hello`; a worker that had escaped could forge entries for other scripts (follow-up from #971: move signing to the
host).
surface. The out-of-process runner's compiled-PE cache is owned by the **host** since lmxopcua#1014: the host verifies
entries under a key only it holds, ships verified images inside the load, and fills misses with its own compile; the
worker is never handed the key or the directory, so a worker that had escaped cannot forge an entry for another script.
Entries written by pre-#1014 workers are rejected on upgrade (format version 2). See `docs/VirtualTags.md`
§"Out-of-process runner" → Compiled-PE cache.
---