diff --git a/docs/config.md b/docs/config.md index 9b445b5..84021a1 100644 --- a/docs/config.md +++ b/docs/config.md @@ -136,8 +136,21 @@ with the same rules. nonce before the ciphertext. The key file is made through a temp file and a hard link, so it never exists half written; on a file system without hard links (some network, FUSE and Docker bind mounts) it is made in place with `create_new`, and a start that meets it mid-write waits for it. - Two Koppels starting together end up with one key either way. Data Protection's key ring is no longer used. As before, anyone who can - read the keys directory on Linux can decrypt the files. + Two Koppels starting together end up with one key either way. Data Protection's key ring is no longer used. By default anyone who can + read the keys directory on Linux can decrypt the files, since the key sits beside them; a key from + `KOPPEL_KEY_FILE`, a systemd credential or a Docker secret moves it out (see "Keeping the key outside + the volume" in `docs/security.md`). +- **The key ring:** the box reads every key it can find and seals with one. A key from outside the + volume seals when there is one (and `koppel-secrets.key` in the keys directory is then only read, + never made); otherwise `koppel-secrets.key` seals. `koppel-secrets..key` files are older + keys, only read. A file's key id says which key opens it, and at every start the secret files + (and `ui-session.key`) that an older key sealed are written again with the current one, so a + rotation, or a move of the key out of the volume, is one start. A key from outside is any secret + of 32 to 4096 bytes; the AES key and the id come from it by HKDF-SHA256. +- **Secrets in memory:** the secret fields of the file structs are `Secret`, which prints + `Secret()`, wipes itself when dropped and reads and writes as the string it holds, so the + files do not change. The plaintext of a file being read or written is wiped after use. No copy of a + file's JSON is kept to see whether it changed (a SHA-256 of the bytes and a typed compare do that). - **The upgrade from 0.1.x:** at the first start, each of `secrets.json`, `connection.json` and `ui-auth.json` that is still a Data Protection payload is decrypted with the 0.1.x key ring (machine DPAPI on Windows, plain XML on Linux) and written again in the new format, with the same JSON inside. diff --git a/docs/decisions.md b/docs/decisions.md index e292b76..51c593e 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -64,3 +64,15 @@ - **Names.** `KOPPEL_` and the option in capitals (`KOPPEL_UI_PORT`), flat, not `KOPPEL_PORTS_UI`: the section half of 0.1.x's names only mirrored .NET's configuration tree. 0.1.x's names are aliases that log once as deprecated and are kept through 0.2.1; dropping them is the owner's call for a later release. The aliases are rewritten to the new options before clap reads anything, so there is one parser and one set of rules, and a test checks that every variable in the struct has an old name and every old name has an option. - **`healthcheck` is a TLS handshake and one fixed request, not an HTTP client.** Measured on the same build: the hyper client version was 7,824,896 bytes, the raw version 7,795,712, so 29,184 bytes (0.4 percent) less, and `koppel` no longer asks for hyper's `client` feature or the `hyper-util` and `http-body-util` crates. The code is shorter too: it sends `GET /healthz HTTP/1.1` with `Connection: close` and reads only as far as the status line. The certificate check is still off, for the same reason as before (see `healthcheck.rs`). The saving is small; what decided it is that an HTTP client was more machinery than a status line needs. - **Blank is unset.** A blank value (`KOPPEL_UI_PORT=` from a compose file's `${VAR:-}`) leaves the setting at its default, as a blank value did in 0.1.x. + + +## Secrets at rest decisions (2026-11-12) + +- **A key outside the volume, not a passphrase.** Koppel starts unattended, so nothing can ask for a passphrase. `KOPPEL_KEY_FILE`, a systemd credential and a Docker secret keep the key apart from the volume, which is what a backup copies. All three are a file; one code path reads them. They are tried in that order, and a `KOPPEL_KEY_FILE` that names nothing stops start-up instead of quietly falling back to a key beside the files. +- **The key file is any secret, derived with HKDF.** An admin makes it with `openssl rand -base64 32` rather than a Koppel tool. HKDF-SHA256 (ring, already a dependency) turns it into the AES key and the key id, so the id stays stable and says which files the key opened. Considered: requiring Koppel's own `KPSK` format. That would need a command to make one for a Docker secret or a credential, for no gain. +- **A key ring of every readable key, sealing with one.** The container already carried a key id and refused any other, so a rotation was a dead end. The ring is cheap: the keys directory's `koppel-secrets.key`, any `koppel-secrets..key` (older keys) and the outside key. The sealing key is the outside key when there is one, otherwise `koppel-secrets.key`. "Newest by file time" was rejected as fragile; the name decides. Files sealed with another key are written again at start, so a rotation or a move is one restart. +- **Password hash stays PBKDF2-SHA256 through ring.** 600,000 iterations is the OWASP figure for PBKDF2-HMAC-SHA256. Argon2id would be better against GPUs, but it needs a new dependency (the RustCrypto `argon2` crate), a second hash format next to the 0.1.x one that carried over from existing installs (so a login would verify two formats and rehash), and the hash only protects a password that is already behind a rate limit, a lock-out and a 128 character cap, inside a file that is encrypted. The gain is small and the migration is not. Revisit if the hash ever leaves the encrypted file. +- **Client secrets stay retrievable (`KeepClientSecrets`).** Showing a secret once and keeping only its hash would stop an admin copying it again from the client's row, which they do. The gain is small: the token signing key sits in the same encrypted file and lets whoever reads it forge a token for any client, so a reader of the file does not need the client secrets. It would also change the UI. If that file's confidentiality is ever split (signing key kept elsewhere), show-once becomes worth it. +- **`Secret` over a hand-written `Debug` per struct.** A newtype cannot be forgotten on a new field the way an impl can, and it carries the wipe on drop. Cost: `.as_deref()` on an optional secret gives `&String`, and code that builds the structs needs `.into()`. +- **No proptest, no cargo-fuzz.** The properties (seal then open is the identity, a flipped byte or a truncation is an error and never a panic, the PKCS#12 reader never panics on random or damaged DER) run as ordinary tests on a fixed xorshift generator, thousands of cases in about a second. proptest would add a dev dependency tree and shrinking, which short byte inputs do not need. A cargo-fuzz harness needs nightly and a separate crate; add one if the PKCS#12 reader is ever opened to input from outside a file the admin carried over. +- **The 0.1.x key ring is not deleted after conversion.** Deleting it would stop a rollback to 0.1.x, and the code that converts is being moved out of the daemon (issue #144). It is documented in the threat model instead. diff --git a/docs/security.md b/docs/security.md index 3289951..e8f76ff 100644 --- a/docs/security.md +++ b/docs/security.md @@ -48,6 +48,29 @@ The UI on port 5240 (HTTPS) needs a password. There is one admin password and no & "C:\Program Files\Matumi\Koppel\Koppel.exe" reset-password ``` +### Keeping the key outside the volume + +The files are sealed with AES-256-GCM. The key can come from a file kept apart from the config and keys directories, so a backup or a copy of the volume does not carry it. The first of these that applies is used: + +1. **`KOPPEL_KEY_FILE`**: the path of a file. When it is set the file must exist, otherwise Koppel stops and says so. +2. **A systemd credential** named `koppel-key`: `LoadCredential=koppel-key:/etc/koppel/key` (or `ImportCredential=`) in the unit makes `$CREDENTIALS_DIRECTORY/koppel-key`, readable by the service only and not by the other users on the machine. +3. **A Docker secret** named `koppel-key`: mounted at `/run/secrets/koppel-key`. In Compose, list it under `secrets:` for the service and under the top level `secrets:` as a `file:` or `external` secret. + +The file is any secret of 32 bytes or more, up to 4096; a trailing line break is ignored. Make one with: + +```sh +openssl rand -base64 32 > koppel-key +chmod 600 koppel-key +``` + +The AES key and a key id are derived from it with HKDF-SHA256, so the same file is the same key every time. Windows ignores all of this and keeps DPAPI (Koppel warns if `KOPPEL_KEY_FILE` is set there). + +Moving an install over: set the source and start Koppel. The old `koppel-secrets.key` in the keys directory is then only read, never made again, and at start every secret file sealed with it is written again with the new key (the log says how many). Once the log says so, stop Koppel, move `koppel-secrets.key` out of the keys directory (keep a copy with your offline backup, not in the volume), and start again. Losing the key outside the volume makes the secret files unreadable, as losing the keys directory does: see "If the key is lost" in `docs/config.md`. Back the key up separately from the volume. + +Rotating the key, with the key in the keys directory: stop Koppel, rename `koppel-secrets.key` to `koppel-secrets..key`, start Koppel. It makes a new `koppel-secrets.key`, reads the renamed one, and seals every file again with the new key. When the log says so, delete the renamed file. Rotating a key from outside the volume is the same with a new key file: copy the old key file into the keys directory as `koppel-secrets..key` (a retired key may be a Koppel key file or a plain secret like the ones above), point the source at the new one, start Koppel, and delete the copy once the log says the files were sealed again. + +What this buys: a copy of the volume alone, such as a backup, a snapshot or a disk image of the data folder, no longer opens `secrets.json`, `connection.json` and `ui-auth.json`. What it does not: a copy of the machine's whole file system, or root on the running machine, still has the key. + ### Guards on the web surface - **Origin and header (UI surface):** an `Origin` that does not match the request's own scheme, host and port gets 403 on any `/api/*` call, the live push included. Behind a TLS proxy the scheme comes from `X-Forwarded-Proto`. A change (anything but GET or HEAD) also needs `X-Koppel-UI: 1`, otherwise 403. A page on another site cannot add that header without a CORS preflight, which this server never grants. The UI adds it in `api/http.ts` (`uiFetch`, used by every mutating fetch). The live push is a GET, so it needs no header, which an `EventSource` cannot send. @@ -75,5 +98,10 @@ What it does not cover: - `KOPPEL_UI_ALLOW_FROM` and the per-caller limits on sign-in and pairing go by the caller's address as Koppel sees it; forwarded headers are not read. Behind NAT, such as port publishing that rewrites the source address, every caller arrives from one address: the local network check then lets everyone in, and one caller's wrong passwords lock out everyone else's address too. - The gateway on 3242 is plain USB/IP with no login (see ["USB client"](usb.md#usb-client)). Whoever reaches it uses the client's access to the server. On native Windows with a loopback address only the kernel's own connections get in, and only for imports Koppel asked the driver for; elsewhere, such as a container, the port publishing is all that keeps it local. - A registered client and the server it is paired with trust each other's USB/IP traffic: what one sends goes to the other's kernel driver (`usbip-host`, `vhci_hcd` or usbip-win2's driver) as it comes, and an attached device can be any device, a keyboard that types included. Koppel checks the bus ID and VID:PID of an import, not the traffic after it. -- Anyone who can read the keys directory can decrypt the secret files, unless `Paths:KeyCertificate` protects the key ring (see ["Config on disk"](config.md#config-on-disk)). That setting is deprecated and goes in 0.2.0. +- **On Linux and in Docker the key sits beside the files it protects.** By default `koppel-secrets.key` is in the keys directory, and the keys and config directories are one volume (`/koppel` in the image). A backup or a copy of the volume holds the key and the ciphertext together, so the encryption then protects only a copy of the config directory on its own. Anyone who can read the keys directory can decrypt the secret files. Keep the key elsewhere to change that (see "Keeping the key outside the volume" below). On Windows the key is machine-scope DPAPI: any process on the machine can unseal the files, as with 0.1.x. +- **The key is not a passphrase.** Koppel has to start unattended after a power cut, so nothing asks for one at start. A key kept outside the volume is still a file that Koppel reads at start, and root on the machine can read that file, or the process's memory, as it can for any service. +- **Memory.** Secrets are decrypted into memory while Koppel runs: the signing key, the certificate's private key, client secrets, the UI password hash. The values Koppel owns are wiped when they are dropped (`Secret`, and the buffers holding a decrypted file). That is best effort: the JSON parser's intermediate copies, the TLS stack's keys and the AES key schedule are not wiped, nothing is locked out of swap, and a core dump holds them. Turn core dumps off on a machine that matters (`LimitCORE=0` in the service, `--ulimit core=0` in Docker). +- **Logs.** The config structs print `Secret()` for every secret, so a `{:?}` of one cannot leak it. A test holds that line. Koppel's own log messages do not carry secrets; a log line written by hand that formats a secret is the way one gets out, and the `Secret` type has no `Display` to make that easy. +- **The 0.1.x key ring stays.** After a 0.1.x install is converted, its Data Protection key ring (`keys/aspnet`, plain XML on Linux) is left where it was, so the install can go back to 0.1.x. Until you delete it, it can decrypt whatever 0.1.x sealed. Keep it with the backup or delete it once you are sure. +- **Client secrets can be read again.** Koppel keeps each client's secret inside the encrypted `secrets.json` so the admin can copy it again from the client's row. Anyone who can read the decrypted file can read them; see "Show-once client secrets" in `docs/decisions.md`. - The Linux container is privileged and runs as root, and the Windows service runs as LocalSystem. A flaw in Koppel is a flaw with that reach. diff --git a/src/Cargo.lock b/src/Cargo.lock index 37fc83d..0f98959 100644 --- a/src/Cargo.lock +++ b/src/Cargo.lock @@ -1055,6 +1055,7 @@ dependencies = [ "tokio-rustls", "tracing", "windows", + "zeroize", ] [[package]] diff --git a/src/Cargo.toml b/src/Cargo.toml index f391e31..734c481 100644 --- a/src/Cargo.toml +++ b/src/Cargo.toml @@ -99,6 +99,9 @@ serde_json = { version = "1.0.154", features = ["raw_value", "preserve_order"] } base64 = "0.23.1" time = "0.3.55" ring = "0.17.14" +# Wiping a secret when it is dropped (koppel-config's `Secret`). zeroize (MIT OR Apache-2.0, RustCrypto) is already here +# through the crypto crates. +zeroize = "1.9.1" # What ring lacks for reading 0.1.x's files: AES-256-CBC for Data Protection payloads and 3DES-CBC # for .NET's PKCS#12 export. RustCrypto, MIT OR Apache-2.0. aes = "0.9.4" diff --git a/src/koppel-config/Cargo.toml b/src/koppel-config/Cargo.toml index a03452b..c21f42b 100644 --- a/src/koppel-config/Cargo.toml +++ b/src/koppel-config/Cargo.toml @@ -16,6 +16,7 @@ time.workspace = true tokio.workspace = true tracing.workspace = true ring.workspace = true +zeroize.workspace = true rustls.workspace = true aes.workspace = true cbc.workspace = true diff --git a/src/koppel-config/src/file.rs b/src/koppel-config/src/file.rs index 9bd4b33..edfc098 100644 --- a/src/koppel-config/src/file.rs +++ b/src/koppel-config/src/file.rs @@ -45,6 +45,7 @@ use serde_json::Value; use time::OffsetDateTime; use tokio::sync::{mpsc, oneshot}; use tokio::task::JoinHandle; +use zeroize::Zeroizing; use crate::json; @@ -501,7 +502,7 @@ where } async fn write(&self, value: &T) -> Result { - let json = versioned_json(value); + let json = Zeroizing::new(versioned_json(value)); let path = self.path.clone(); let codec = self.codec.clone(); tokio::task::spawn_blocking(move || { @@ -774,13 +775,14 @@ fn load_blocking( if known == Some(seen.hash) { return Ok(Loaded::Same(seen)); } - let text = codec.decode(&bytes).map_err(|e| { + // The plaintext of an encrypted file is wiped when this function is done with it. + let text = Zeroizing::new(codec.decode(&bytes).map_err(|e| { ConfigFileError::new( path, ConfigErrorKind::Decrypt, format!("it could not be decrypted ({e})"), ) - })?; + })?); let not_json = |e: serde_json::Error| { ConfigFileError::new( path, diff --git a/src/koppel-config/src/files.rs b/src/koppel-config/src/files.rs index 51d82a2..fb06640 100644 --- a/src/koppel-config/src/files.rs +++ b/src/koppel-config/src/files.rs @@ -9,6 +9,7 @@ use serde::{Deserialize, Serialize, Serializer}; use time::OffsetDateTime; use crate::json::{self, OrderedMap}; +use crate::redact::Secret; /// Which side of the link this machine plays. Written as `server`, `client` or `both`. #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] @@ -173,7 +174,7 @@ pub struct ClientConnection { #[serde(default)] pub client_id: Option, #[serde(default)] - pub client_secret: Option, + pub client_secret: Option>, /// The certificate the server said it will switch to, trusted as well until then. #[serde(default)] pub next_server_fingerprint: Option, @@ -197,7 +198,7 @@ impl Serialize for ClientConnection { server_url: &'a Option, server_fingerprint: &'a Option, client_id: &'a Option, - client_secret: &'a Option, + client_secret: &'a Option>, next_server_fingerprint: &'a Option, is_complete: bool, } @@ -219,7 +220,7 @@ impl Serialize for ClientConnection { #[serde(rename_all = "camelCase")] pub struct UiCredentials { #[serde(default)] - pub password_hash: Option, + pub password_hash: Option>, #[serde(default)] pub security_stamp: Option, #[serde(default, with = "json::date_map")] @@ -256,7 +257,7 @@ impl Serialize for UiCredentials { #[derive(Serialize)] #[serde(rename_all = "camelCase")] struct Written<'a> { - password_hash: &'a Option, + password_hash: &'a Option>, security_stamp: &'a Option, #[serde(with = "json::date_map")] revoked_sessions: &'a Option>, @@ -299,10 +300,10 @@ pub struct ServerSecrets { pub skakel: Option, /// Koppel 0.1.0: the RSA signing key, base64 PKCS#8. #[serde(default)] - pub signing_key: Option, + pub signing_key: Option>, /// Koppel 0.1.0: the certificate, base64 PKCS#12. #[serde(default)] - pub certificate_pfx: Option, + pub certificate_pfx: Option>, /// Koppel 0.1.0: the registered clients. #[serde(default)] pub clients: Option>, @@ -337,7 +338,7 @@ pub struct SkakelState { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub retired_signing_keys: Vec, /// The certificate the server presents: base64 PKCS#12 with its private key and no password. - pub certificate_pfx: String, + pub certificate_pfx: Secret, /// The certificate prepared for a handover. #[serde(default)] pub next_certificate: Option, @@ -361,7 +362,7 @@ pub struct SkakelClientRecord { pub generation: i32, /// The secret itself: Koppel sets Skakel's `KeepClientSecrets`. #[serde(default)] - pub secret: Option, + pub secret: Option>, } /// A token signing key: RSA, base64 PKCS#8. @@ -369,7 +370,7 @@ pub struct SkakelClientRecord { #[serde(rename_all = "camelCase")] pub struct SkakelKeyRecord { pub key_id: String, - pub private_key: String, + pub private_key: Secret, #[serde(with = "json::date_time_offset")] pub created_at: OffsetDateTime, #[serde(default, with = "json::date_time_offset::option")] @@ -380,7 +381,7 @@ pub struct SkakelKeyRecord { #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct SkakelNextCertificateRecord { - pub pfx: String, + pub pfx: Secret, #[serde(with = "json::date_time_offset")] pub prepared_at: OffsetDateTime, pub received_by: Vec, @@ -396,7 +397,7 @@ pub struct LegacyClient { #[serde(with = "json::date_time_offset")] pub created_at: OffsetDateTime, #[serde(default)] - pub secret: Option, + pub secret: Option>, #[serde(default = "first_generation")] pub generation: i32, } @@ -405,7 +406,7 @@ pub struct LegacyClient { #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct LegacyNextCertificate { - pub pfx: String, + pub pfx: Secret, #[serde(with = "json::date_time_offset")] pub prepared_at: OffsetDateTime, pub received_by: Vec, @@ -572,6 +573,101 @@ mod tests { assert!(written.contains("\"hasPassword\": false")); } + /// Every secret in every file struct is a sentinel here; none may come out of `{:?}`, plain or + /// pretty, however deep the struct is nested. + #[test] + fn formatting_a_config_struct_shows_no_secret() { + let now = OffsetDateTime::UNIX_EPOCH; + let state = SkakelState { + clients: vec![SkakelClientRecord { + id: "client-1".into(), + name: "bench".into(), + secret_hash: "sha256$AAAA".into(), + created_at: now, + generation: 1, + secret: Some("SENTINEL-CLIENT-SECRET".into()), + }], + signing_key: Some(SkakelKeyRecord { + key_id: "k1".into(), + private_key: "SENTINEL-SIGNING-KEY".into(), + created_at: now, + accept_until: None, + }), + retired_signing_keys: vec![SkakelKeyRecord { + key_id: "k0".into(), + private_key: "SENTINEL-RETIRED-KEY".into(), + created_at: now, + accept_until: None, + }], + certificate_pfx: "SENTINEL-PFX".into(), + next_certificate: Some(SkakelNextCertificateRecord { + pfx: "SENTINEL-NEXT-PFX".into(), + prepared_at: now, + received_by: Vec::new(), + }), + }; + let legacy = ServerSecrets { + skakel: Some(state.clone()), + signing_key: Some("SENTINEL-LEGACY-KEY".into()), + certificate_pfx: Some("SENTINEL-LEGACY-PFX".into()), + clients: Some(vec![LegacyClient { + id: "c".into(), + name: "n".into(), + secret_hash: "pbkdf2".into(), + created_at: now, + secret: Some("SENTINEL-LEGACY-SECRET".into()), + generation: 1, + }]), + signing_key_id: None, + signing_key_since: None, + next_certificate: Some(LegacyNextCertificate { + pfx: "SENTINEL-LEGACY-NEXT".into(), + prepared_at: now, + received_by: Vec::new(), + }), + }; + let connection = ClientConnection { + server_url: Some("https://a:5240".into()), + server_fingerprint: Some("AA".into()), + client_id: Some("client-1".into()), + client_secret: Some("SENTINEL-LINK-SECRET".into()), + next_server_fingerprint: None, + }; + let credentials = UiCredentials { + password_hash: Some("SENTINEL-PASSWORD-HASH".into()), + ..UiCredentials::empty() + }; + + let shown = [ + format!( + "{state:?} +{state:#?}" + ), + format!( + "{legacy:?} +{legacy:#?}" + ), + format!( + "{connection:?} +{connection:#?}" + ), + format!( + "{credentials:?} +{credentials:#?}" + ), + ] + .join( + " +", + ); + + assert!(!shown.contains("SENTINEL"), "{shown}"); + assert!(shown.contains("Secret()")); + // Redacted in memory only: the files still hold the values. + let written = String::from_utf8(json::to_vec(&connection).unwrap()).unwrap(); + assert!(written.contains("SENTINEL-LINK-SECRET")); + } + #[test] fn password_hashes_are_checked_as_0_1_checks_them() { let good = "pbkdf2-sha256$600000$Buc4cbpmUJFP6mXwVKll2w==$MLwUOgSKos+g2yhMD07OXIyRt6tOX9c/UXzB50xrRzY="; diff --git a/src/koppel-config/src/lib.rs b/src/koppel-config/src/lib.rs index b270260..82c0a4a 100644 --- a/src/koppel-config/src/lib.rs +++ b/src/koppel-config/src/lib.rs @@ -24,6 +24,7 @@ pub mod json; mod migrate; mod paths; pub mod pkcs12; +mod redact; mod secret; use std::sync::Arc; @@ -39,7 +40,8 @@ pub use file::{ pub use harden::harden_directory; pub use migrate::{Conversion, ConversionError, convert_0_1_secrets}; pub use paths::{KoppelPaths, default_root}; -pub use secret::{SecretBox, SecretError, SecretFormat, format_of}; +pub use redact::Secret; +pub use secret::{KeySource, KeySources, SecretBox, SecretError, SecretFormat, format_of}; use files::{ AttachedDevices, ClientConnection, KoppelSettings, ServerSecrets, SharedDevices, UiCredentials, diff --git a/src/koppel-config/src/redact.rs b/src/koppel-config/src/redact.rs new file mode 100644 index 0000000..6831085 --- /dev/null +++ b/src/koppel-config/src/redact.rs @@ -0,0 +1,154 @@ +//! A value that must not end up in a log: [`Secret`]. + +use std::fmt; +use std::ops::Deref; + +use serde::{Deserialize, Deserializer, Serialize, Serializer}; +use zeroize::Zeroize; + +/// A secret value (a client secret, a private key, a password hash, a certificate with its key). +/// +/// - `Debug` prints `Secret()`, so a `{:?}` of a config struct cannot leak it. +/// - The bytes are overwritten when the value is dropped, as far as `zeroize` can: a clone is a +/// second copy that is wiped when it is dropped in turn, and the `serde_json` values a file is +/// parsed through are not wiped (see "Threat model" in docs/security.md). +/// - It reads and writes as the value it holds, so the files do not change. +/// - It dereferences to the value, so `&secret` works where a `&str` or `&String` does. +/// +/// There is no `Display`: a secret is put into a message only on purpose, through +/// [`Secret::expose`]. +pub struct Secret(T); + +impl Secret { + pub fn new(value: T) -> Self { + Self(value) + } + + /// The value. Named so that a use of it is easy to find. + pub fn expose(&self) -> &T { + &self.0 + } +} + +impl Drop for Secret { + fn drop(&mut self) { + self.0.zeroize(); + } +} + +impl fmt::Debug for Secret { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("Secret()") + } +} + +impl Deref for Secret { + type Target = T; + + fn deref(&self) -> &T { + &self.0 + } +} + +impl AsRef for Secret { + fn as_ref(&self) -> &str { + &self.0 + } +} + +impl AsRef<[u8]> for Secret { + fn as_ref(&self) -> &[u8] { + self.0.as_bytes() + } +} + +impl Clone for Secret { + fn clone(&self) -> Self { + Self(self.0.clone()) + } +} + +impl Default for Secret { + fn default() -> Self { + Self(T::default()) + } +} + +impl PartialEq for Secret { + fn eq(&self, other: &Self) -> bool { + self.0 == other.0 + } +} + +impl Eq for Secret {} + +impl From for Secret { + fn from(value: T) -> Self { + Self(value) + } +} + +impl From<&str> for Secret { + fn from(value: &str) -> Self { + Self(value.to_owned()) + } +} + +impl Serialize for Secret { + fn serialize(&self, serializer: S) -> Result { + self.0.serialize(serializer) + } +} + +impl<'de, T: Zeroize + Deserialize<'de>> Deserialize<'de> for Secret { + fn deserialize>(deserializer: D) -> Result { + T::deserialize(deserializer).map(Self) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn debug_hides_the_value_also_inside_other_types() { + let secret = Secret::new("hunter2".to_string()); + assert_eq!(format!("{secret:?}"), "Secret()"); + assert!(!format!("{:?}", Some(&secret)).contains("hunter2")); + assert!(!format!("{:#?}", vec![secret]).contains("hunter2")); + } + + #[test] + fn it_reads_and_writes_as_the_value_it_holds() { + let secret: Secret = serde_json::from_str("\"abc\"").unwrap(); + assert_eq!(&*secret, "abc"); + assert_eq!(serde_json::to_string(&secret).unwrap(), "\"abc\""); + let none: Option> = serde_json::from_str("null").unwrap(); + assert!(none.is_none()); + } + + #[test] + fn dropping_wipes_the_value() { + use std::sync::Arc; + use std::sync::atomic::{AtomicUsize, Ordering}; + + /// Counts how often it was wiped. + struct Probe(Arc); + impl Zeroize for Probe { + fn zeroize(&mut self) { + self.0.fetch_add(1, Ordering::SeqCst); + } + } + + let wiped = Arc::new(AtomicUsize::new(0)); + let secret = Secret::new(Probe(wiped.clone())); + assert_eq!(wiped.load(Ordering::SeqCst), 0); + drop(secret); + assert_eq!(wiped.load(Ordering::SeqCst), 1); + + // And the real thing wipes a string in place. + let mut text = String::from("secret"); + text.zeroize(); + assert!(text.is_empty()); + } +} diff --git a/src/koppel-config/src/secret.rs b/src/koppel-config/src/secret.rs index 4a3726f..62ba2bd 100644 --- a/src/koppel-config/src/secret.rs +++ b/src/koppel-config/src/secret.rs @@ -22,7 +22,9 @@ use std::sync::Arc; use std::time::Duration; use ring::aead::{AES_256_GCM, Aad, LessSafeKey, NONCE_LEN, Nonce, UnboundKey}; +use ring::hkdf; use ring::rand::{SecureRandom, SystemRandom}; +use zeroize::Zeroizing; use crate::dataprotection; use crate::file::{CodecError, FileCodec, create_private, sync_directory}; @@ -40,6 +42,10 @@ pub const SCHEME_KEY_FILE: u8 = 2; pub const DPAPI_ENTROPY: &[u8] = b"Koppel secret file"; /// The key file's name in the keys directory. pub const KEY_FILE: &str = "koppel-secrets.key"; +/// The environment variable that names a key file outside the keys directory. +pub const KEY_FILE_VARIABLE: &str = "KOPPEL_KEY_FILE"; +/// The name of the systemd credential and of the Docker secret that hold a key. +pub const KEY_SOURCE_NAME: &str = "koppel-key"; const KEY_MAGIC: [u8; 4] = *b"KPSK"; const KEY_ID_LEN: usize = 16; @@ -48,6 +54,8 @@ const HEADER_LEN: usize = 6; const KEY_FILE_LEN: usize = 5 + KEY_ID_LEN + KEY_LEN; const KEY_FILE_WAITS: u32 = 30; const KEY_FILE_WAIT: Duration = Duration::from_millis(100); +const MIN_SOURCE_LEN: usize = 32; +const MAX_SOURCE_LEN: usize = 4096; /// Why a secret could not be sealed, opened, or its key loaded. #[derive(Debug)] @@ -99,92 +107,241 @@ pub fn format_of(bytes: &[u8]) -> SecretFormat { } } +/// One AES-256-GCM key and the id its files carry. +struct KeyEntry { + id: [u8; KEY_ID_LEN], + key: LessSafeKey, +} + +/// The keys of the key file scheme. A file is opened with the key its id names. New files are +/// sealed with `entries[sealing]`. +struct KeyRing { + sealing: usize, + entries: Vec, +} + enum Scheme { #[cfg(windows)] Dpapi, - KeyFile { - id: [u8; KEY_ID_LEN], - key: Box, - }, + KeyFile(KeyRing), +} + +/// Where the key that seals new files comes from. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum KeySource { + /// Windows: machine DPAPI, no key to keep. + Dpapi, + /// `koppel-secrets.key` in the keys directory, beside the files it protects. + KeysDirectory, + /// The file `KOPPEL_KEY_FILE` names. + Environment(PathBuf), + /// A systemd credential: `koppel-key` in `$CREDENTIALS_DIRECTORY`. + Credential(PathBuf), + /// A Docker secret: `/run/secrets/koppel-key`. + DockerSecret(PathBuf), +} + +impl KeySource { + /// True when the key is kept apart from the config and keys volume. + pub fn is_outside_the_volume(&self) -> bool { + !matches!(self, Self::KeysDirectory) + } +} + +impl fmt::Display for KeySource { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Dpapi => f.write_str("Windows DPAPI"), + Self::KeysDirectory => write!(f, "{KEY_FILE} in the keys directory"), + Self::Environment(path) => write!(f, "{KEY_FILE_VARIABLE} ({})", path.display()), + Self::Credential(path) => write!(f, "a systemd credential ({})", path.display()), + Self::DockerSecret(path) => write!(f, "a Docker secret ({})", path.display()), + } + } +} + +/// The places a key can come from other than the keys directory, in the order they are tried. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct KeySources { + /// `KOPPEL_KEY_FILE`. When it is set the file must exist. + pub environment: Option, + /// `$CREDENTIALS_DIRECTORY/koppel-key`, used when it exists. + pub credential: Option, + /// `/run/secrets/koppel-key`, used when it exists. + pub docker_secret: Option, +} + +impl KeySources { + /// None of them: the key lives in the keys directory. + pub fn none() -> Self { + Self::default() + } + + /// From `KOPPEL_KEY_FILE`, `CREDENTIALS_DIRECTORY` and the standard Docker secrets folder. + pub fn from_environment() -> Self { + let set = |name: &str| std::env::var_os(name).filter(|v| !v.is_empty()); + Self { + environment: set(KEY_FILE_VARIABLE).map(PathBuf::from), + credential: set("CREDENTIALS_DIRECTORY") + .map(|directory| PathBuf::from(directory).join(KEY_SOURCE_NAME)), + docker_secret: Some(PathBuf::from("/run/secrets").join(KEY_SOURCE_NAME)), + } + } + + /// The first source that applies. + fn chosen(&self) -> Result, SecretError> { + if let Some(path) = &self.environment { + if !path.is_file() { + return Err(SecretError::KeyFile { + path: path.clone(), + reason: format!("{KEY_FILE_VARIABLE} names it and it is not a file"), + }); + } + return Ok(Some(KeySource::Environment(path.clone()))); + } + if let Some(path) = self.credential.as_ref().filter(|p| p.is_file()) { + return Ok(Some(KeySource::Credential(path.clone()))); + } + if let Some(path) = self.docker_secret.as_ref().filter(|p| p.is_file()) { + return Ok(Some(KeySource::DockerSecret(path.clone()))); + } + Ok(None) + } } /// Seals and opens Koppel's secret files. pub struct SecretBox { scheme: Scheme, + source: KeySource, random: SystemRandom, } impl fmt::Debug for SecretBox { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.write_str(match self.scheme { + match &self.scheme { #[cfg(windows)] - Scheme::Dpapi => "SecretBox(dpapi)", - Scheme::KeyFile { .. } => "SecretBox(key file)", - }) + Scheme::Dpapi => f.write_str("SecretBox(dpapi)"), + Scheme::KeyFile(ring) => write!( + f, + "SecretBox(key file, {} key(s), sealing from {})", + ring.entries.len(), + self.source + ), + } } } impl SecretBox { - /// The box for this platform: machine DPAPI on Windows, and elsewhere the key file in - /// `keys_directory`, made on first use. The directory must exist; [`crate::KoppelPaths::prepare`] - /// makes and restricts it. + /// The box for this platform: machine DPAPI on Windows, and elsewhere a key from + /// [`KeySources::from_environment`] or else the key file in `keys_directory`, made on first + /// use. The directory must exist; [`crate::KoppelPaths::prepare`] makes and restricts it. pub fn open(keys_directory: &Path) -> Result { #[cfg(windows)] { let _ = keys_directory; + if std::env::var_os(KEY_FILE_VARIABLE).is_some() { + tracing::warn!( + "{KEY_FILE_VARIABLE} is set, but Windows seals the secret files with DPAPI and does not read it" + ); + } Ok(Self { scheme: Scheme::Dpapi, + source: KeySource::Dpapi, random: SystemRandom::new(), }) } #[cfg(not(windows))] { - Self::with_key_file(keys_directory) + Self::with_sources(keys_directory, &KeySources::from_environment()) } } - /// The key file scheme on any platform. Makes the key file when there is none. + /// The key file scheme on any platform, with the key in the keys directory. Makes the key file + /// when there is none. pub fn with_key_file(keys_directory: &Path) -> Result { + Self::with_sources(keys_directory, &KeySources::none()) + } + + /// The key file scheme on any platform, with the key from `sources` when one applies. + /// + /// The ring holds every key it can read, and seals with one: + /// + /// - A key from `sources` seals. The key file in the keys directory, when there is one, is + /// then only read, so files sealed before the move still open; [`Self::reseal`] moves them + /// over, after which that file can be deleted. None is made, since a key made beside the + /// files would defeat the point. + /// - Without a source, `koppel-secrets.key` seals, and is made when missing. + /// - `koppel-secrets..key` files are older keys, only read. To rotate the key, rename + /// `koppel-secrets.key` to such a name and start Koppel: it makes a new one and reseals. + pub fn with_sources(keys_directory: &Path, sources: &KeySources) -> Result { let random = SystemRandom::new(); - let path = keys_directory.join(KEY_FILE); - let failed = |reason: String| SecretError::KeyFile { - path: path.clone(), - reason, + let mut entries: Vec = Vec::new(); + let mut keep = |entry: KeyEntry| { + if !entries.iter().any(|known| known.id == entry.id) { + entries.push(entry); + } }; - let bytes = match read_key_file(&path) { - Ok(bytes) => bytes, - Err(e) if e.kind() == io::ErrorKind::NotFound => { - create_key_file(&path, &random).map_err(|e| failed(e.to_string()))? + let source = match sources.chosen()? { + Some( + source @ (KeySource::Environment(_) + | KeySource::Credential(_) + | KeySource::DockerSecret(_)), + ) => { + let (KeySource::Environment(path) + | KeySource::Credential(path) + | KeySource::DockerSecret(path)) = &source + else { + unreachable!("matched above"); + }; + keep(derive_key(path)?); + let primary = keys_directory.join(KEY_FILE); + if primary.exists() { + keep(load_key_file(&primary, &random, false)?); + } + source + } + _ => { + keep(load_key_file( + &keys_directory.join(KEY_FILE), + &random, + true, + )?); + KeySource::KeysDirectory } - Err(e) => return Err(failed(e.to_string())), }; - if bytes.len() != KEY_FILE_LEN || bytes[..4] != KEY_MAGIC { - return Err(failed("it is not a Koppel key file".into())); + for retired in retired_key_files(keys_directory) { + keep(load_retired_key(&retired, &random)?); } - if bytes[4] != VERSION { - return Err(failed(format!( - "it is version {}, and this Koppel reads version {VERSION}", - bytes[4] - ))); - } - let id: [u8; KEY_ID_LEN] = bytes[5..5 + KEY_ID_LEN].try_into().expect("checked length"); - let key = UnboundKey::new(&AES_256_GCM, &bytes[5 + KEY_ID_LEN..]) - .map_err(|_| failed("its key is not usable".into()))?; Ok(Self { - scheme: Scheme::KeyFile { - id, - key: Box::new(LessSafeKey::new(key)), - }, + scheme: Scheme::KeyFile(KeyRing { + sealing: 0, + entries, + }), + source, random, }) } + /// Where the key that seals new files comes from. + pub fn source(&self) -> &KeySource { + &self.source + } + + /// How many keys can open files, the one that seals included. + pub fn keys_read(&self) -> usize { + match &self.scheme { + #[cfg(windows)] + Scheme::Dpapi => 1, + Scheme::KeyFile(ring) => ring.entries.len(), + } + } + /// The scheme this box seals with. pub fn scheme(&self) -> u8 { match self.scheme { #[cfg(windows)] Scheme::Dpapi => SCHEME_DPAPI, - Scheme::KeyFile { .. } => SCHEME_KEY_FILE, + Scheme::KeyFile(_) => SCHEME_KEY_FILE, } } @@ -200,7 +357,8 @@ impl SecretBox { .map_err(|e| SecretError::Seal(format!("DPAPI failed ({e})")))?; out.extend_from_slice(&blob); } - Scheme::KeyFile { id, key } => { + Scheme::KeyFile(ring) => { + let KeyEntry { id, key } = &ring.entries[ring.sealing]; out.extend_from_slice(id); let mut nonce = [0u8; NONCE_LEN]; self.random @@ -208,11 +366,12 @@ impl SecretBox { .map_err(|_| SecretError::Seal("no random bytes".into()))?; let aad = out.clone(); out.extend_from_slice(&nonce); - let mut sealed = plaintext.to_vec(); + // The copy of the plaintext is overwritten by the ciphertext in place. + let mut sealed = Zeroizing::new(plaintext.to_vec()); key.seal_in_place_append_tag( Nonce::assume_unique_for_key(nonce), Aad::from(aad), - &mut sealed, + &mut *sealed, ) .map_err(|_| SecretError::Seal("AES-GCM failed".into()))?; out.extend_from_slice(&sealed); @@ -247,20 +406,22 @@ impl SecretBox { #[cfg(windows)] (SCHEME_DPAPI, Scheme::Dpapi) => crate::dpapi::unprotect(&bytes[HEADER_LEN..], DPAPI_ENTROPY) .map_err(|e| SecretError::Open(format!("DPAPI could not decrypt it, so it was written on another machine or is damaged ({e})"))), - (SCHEME_KEY_FILE, Scheme::KeyFile { id, key }) => { + (SCHEME_KEY_FILE, Scheme::KeyFile(ring)) => { let body = &bytes[HEADER_LEN..]; if body.len() < KEY_ID_LEN + NONCE_LEN + AES_256_GCM.tag_len() { return Err(SecretError::Format("it is too short".into())); } - if body[..KEY_ID_LEN] != id[..] { + let Some(entry) = ring.entries.iter().find(|e| body[..KEY_ID_LEN] == e.id[..]) else { return Err(SecretError::Open(format!( - "it was encrypted with another key file than the {KEY_FILE} in the keys directory" + "it was encrypted with another key than the ones this Koppel has: the {KEY_FILE} in the keys directory, {KEY_FILE_VARIABLE}, a credential or a Docker secret" ))); - } + }; let aad = bytes[..HEADER_LEN + KEY_ID_LEN].to_vec(); let nonce: [u8; NONCE_LEN] = body[KEY_ID_LEN..KEY_ID_LEN + NONCE_LEN].try_into().expect("checked length"); - let mut sealed = body[KEY_ID_LEN + NONCE_LEN..].to_vec(); - let plain = key + // Decrypted in place, so this buffer holds the plaintext until it is wiped. + let mut sealed = Zeroizing::new(body[KEY_ID_LEN + NONCE_LEN..].to_vec()); + let plain = entry + .key .open_in_place(Nonce::assume_unique_for_key(nonce), Aad::from(aad), &mut sealed) .map_err(|_| SecretError::Open("it does not decrypt with the key file: it is damaged".into()))?; Ok(plain.to_vec()) @@ -274,12 +435,177 @@ impl SecretBox { } } + /// Writes again, with the key that seals now, each of `files` that is sealed with another key + /// of the ring: after a rotation, or after moving the key out of the keys directory. A file + /// that is missing, or sealed another way, is left alone, and so is one that does not open: it + /// is named in the log, and its owner stops start-up with the reason when it is read. Returns + /// the files that were written. + // Off Windows the key file scheme is the only one, which makes the `let else` always match. + #[cfg_attr(not(windows), allow(irrefutable_let_patterns))] + pub fn reseal(&self, files: &[PathBuf]) -> Vec { + let Scheme::KeyFile(ring) = &self.scheme else { + return Vec::new(); + }; + let sealing = ring.entries[ring.sealing].id; + let mut done = Vec::new(); + for file in files { + let Ok(bytes) = fs::read(file) else { + continue; + }; + let on_other_key = bytes.starts_with(&MAGIC) + && bytes.len() > HEADER_LEN + KEY_ID_LEN + && bytes[5] == SCHEME_KEY_FILE + && bytes[HEADER_LEN..HEADER_LEN + KEY_ID_LEN] != sealing[..]; + if !on_other_key { + continue; + } + let plain = match self.unprotect(&bytes) { + Ok(plain) => Zeroizing::new(plain), + Err(e) => { + tracing::warn!( + "{} was not sealed again with the current key: {e}", + file.display() + ); + continue; + } + }; + let written = self + .protect(&plain) + .map_err(|e| e.to_string()) + .and_then(|sealed| { + crate::file::write_atomic(file, &sealed) + .map(|_| ()) + .map_err(|e| e.to_string()) + }); + match written { + Ok(()) => done.push(file.clone()), + Err(e) => tracing::warn!("{} could not be sealed again: {e}", file.display()), + } + } + if !done.is_empty() { + tracing::info!( + "Sealed {} file(s) again with the key from {}", + done.len(), + self.source + ); + } + done + } + /// A codec that encrypts a [`crate::ConfigFile`] with this box. pub fn codec(self: &Arc) -> Arc { Arc::new(SecretCodec(self.clone())) } } +/// The key a file from outside the volume stands for. The file is any secret of 32 bytes or more +/// (`openssl rand -base64 32` makes a good one); a trailing line break is ignored. The AES key and +/// the key id come from it by HKDF-SHA256, so the same file is always the same key and the id +/// says which files it opened. +fn derive_key(path: &Path) -> Result { + let failed = |reason: String| SecretError::KeyFile { + path: path.to_path_buf(), + reason, + }; + let raw = Zeroizing::new(fs::read(path).map_err(|e| failed(e.to_string()))?); + let trimmed = raw.trim_ascii_end(); + if trimmed.len() < MIN_SOURCE_LEN { + return Err(failed(format!( + "it holds {} bytes and needs at least {MIN_SOURCE_LEN}: make it with `openssl rand -base64 32`", + trimmed.len() + ))); + } + if trimmed.len() > MAX_SOURCE_LEN { + return Err(failed(format!("it holds more than {MAX_SOURCE_LEN} bytes"))); + } + let salt = hkdf::Salt::new(hkdf::HKDF_SHA256, b"Koppel key source v1"); + let mut material = Zeroizing::new([0u8; KEY_LEN + KEY_ID_LEN]); + salt.extract(trimmed) + .expand(&[b"Koppel secret file key"], OutputLength(material.len())) + .and_then(|okm| okm.fill(&mut *material)) + .map_err(|_| failed("a key could not be made from it".into()))?; + let id: [u8; KEY_ID_LEN] = material[KEY_LEN..].try_into().expect("fixed length"); + let key = UnboundKey::new(&AES_256_GCM, &material[..KEY_LEN]) + .map_err(|_| failed("its key is not usable".into()))?; + Ok(KeyEntry { + id, + key: LessSafeKey::new(key), + }) +} + +/// How many bytes HKDF is asked for. +struct OutputLength(usize); + +impl hkdf::KeyType for OutputLength { + fn len(&self) -> usize { + self.0 + } +} + +/// The older keys beside the current one: `koppel-secrets..key`, by name. +fn retired_key_files(keys_directory: &Path) -> Vec { + let Ok(entries) = fs::read_dir(keys_directory) else { + return Vec::new(); + }; + let mut files: Vec = entries + .flatten() + .filter(|entry| { + let name = entry.file_name(); + let name = name.to_string_lossy(); + name.starts_with("koppel-secrets.") + && name.ends_with(".key") + && name.len() > "koppel-secrets..key".len() + }) + .map(|entry| entry.path()) + .collect(); + files.sort(); + files +} + +/// A retired key: a Koppel key file, or a plain secret as a key source takes. +fn load_retired_key(path: &Path, random: &SystemRandom) -> Result { + let is_key_file = fs::read(path) + .map(|bytes| bytes.starts_with(&KEY_MAGIC) && bytes.len() == KEY_FILE_LEN) + .unwrap_or(false); + if is_key_file { + load_key_file(path, random, false) + } else { + derive_key(path) + } +} + +/// Reads a `KPSK` key file. `make` makes it when it is missing. +fn load_key_file(path: &Path, random: &SystemRandom, make: bool) -> Result { + let failed = |reason: String| SecretError::KeyFile { + path: path.to_path_buf(), + reason, + }; + let bytes = match read_key_file(path) { + Ok(bytes) => bytes, + Err(e) if make && e.kind() == io::ErrorKind::NotFound => { + create_key_file(path, random).map_err(|e| failed(e.to_string()))? + } + Err(e) => return Err(failed(e.to_string())), + }; + let bytes = Zeroizing::new(bytes); + if bytes.len() != KEY_FILE_LEN || bytes[..4] != KEY_MAGIC { + return Err(failed("it is not a Koppel key file".into())); + } + if bytes[4] != VERSION { + return Err(failed(format!( + "it is version {}, and this Koppel reads version {VERSION}", + bytes[4] + ))); + } + let id: [u8; KEY_ID_LEN] = bytes[5..5 + KEY_ID_LEN].try_into().expect("checked length"); + let key = UnboundKey::new(&AES_256_GCM, &bytes[5 + KEY_ID_LEN..]) + .map_err(|_| failed("its key is not usable".into()))?; + Ok(KeyEntry { + id, + key: LessSafeKey::new(key), + }) +} + /// Writes the key file once. The first choice is a temp file with mode `0600`, flushed, then linked /// into place, so it never exists half written and an existing one is never replaced. A file system /// without hard links (some network, FUSE and Docker bind mounts) refuses the link; the key file @@ -423,7 +749,7 @@ mod tests { .unprotect(&sealed) .unwrap_err() .to_string() - .contains("another key file") + .contains("another key") ); let same = SecretBox::with_key_file(&one).unwrap(); diff --git a/src/koppel-config/tests/config_file.rs b/src/koppel-config/tests/config_file.rs index 04d2dc7..fc45313 100644 --- a/src/koppel-config/tests/config_file.rs +++ b/src/koppel-config/tests/config_file.rs @@ -439,7 +439,7 @@ async fn an_encrypted_file_round_trips_and_is_not_readable_as_text() { let again = open::connection(&paths, &secrets); again.start().await.unwrap(); assert_eq!( - again.current().client_secret.as_deref(), + again.current().client_secret.as_deref().map(String::as_str), Some("very secret") ); again.stop(); diff --git a/src/koppel-config/tests/key_sources.rs b/src/koppel-config/tests/key_sources.rs new file mode 100644 index 0000000..5094bc8 --- /dev/null +++ b/src/koppel-config/tests/key_sources.rs @@ -0,0 +1,253 @@ +//! Where the key that seals the secret files comes from: the keys directory, `KOPPEL_KEY_FILE`, a +//! systemd credential or a Docker secret, and what happens to files when it changes. + +use std::fs; +use std::path::{Path, PathBuf}; + +use koppel_config::{KeySource, KeySources, SecretBox}; + +fn temp_dir(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!( + "koppel-keys-{name}-{}-{:?}", + std::process::id(), + std::thread::current().id() + )); + let _ = fs::remove_dir_all(&dir); + fs::create_dir_all(&dir).unwrap(); + dir +} + +fn names(dir: &Path) -> Vec { + let mut names: Vec = fs::read_dir(dir) + .unwrap() + .map(|e| e.unwrap().file_name().to_string_lossy().into_owned()) + .collect(); + names.sort(); + names +} + +fn environment(path: &Path) -> KeySources { + KeySources { + environment: Some(path.to_path_buf()), + ..KeySources::none() + } +} + +const KEY: &str = "Zm9yIHRlc3RzIG9ubHksIGEga2V5IG9mIGF0IGxlYXN0IDMyIGJ5dGVz"; + +#[test] +fn a_key_from_outside_the_volume_seals_and_nothing_is_made_beside_the_files() { + let dir = temp_dir("outside"); + let keys = dir.join("keys"); + fs::create_dir(&keys).unwrap(); + let key_file = dir.join("koppel-key"); + fs::write(&key_file, format!("{KEY}\n")).unwrap(); + + let secrets = SecretBox::with_sources(&keys, &environment(&key_file)).unwrap(); + + assert_eq!(*secrets.source(), KeySource::Environment(key_file.clone())); + assert!(secrets.source().is_outside_the_volume()); + assert!(names(&keys).is_empty(), "no key file is made in the volume"); + let sealed = secrets.protect(b"{\"a\":1}").unwrap(); + + // The same file, with or without its line break, is the same key. + fs::write(&key_file, KEY).unwrap(); + let again = SecretBox::with_sources(&keys, &environment(&key_file)).unwrap(); + assert_eq!(again.unprotect(&sealed).unwrap(), b"{\"a\":1}"); + + // Another key does not open it, and the volume's own key does not either. + fs::write(&key_file, "a different key of at least 32 bytes, for sure").unwrap(); + let other = SecretBox::with_sources(&keys, &environment(&key_file)).unwrap(); + let refused = other.unprotect(&sealed).unwrap_err().to_string(); + assert!(refused.contains("another key"), "{refused}"); + let on_volume = SecretBox::with_key_file(&keys).unwrap(); + assert!(on_volume.unprotect(&sealed).is_err()); + let _ = fs::remove_dir_all(dir); +} + +#[test] +fn a_key_that_is_too_short_or_missing_is_refused_and_named() { + let dir = temp_dir("short"); + let keys = dir.join("keys"); + fs::create_dir(&keys).unwrap(); + let key_file = dir.join("koppel-key"); + fs::write(&key_file, "tiny\n").unwrap(); + + let error = SecretBox::with_sources(&keys, &environment(&key_file)).unwrap_err(); + let message = error.to_string(); + assert!( + message.contains(&key_file.display().to_string()), + "{message}" + ); + assert!(message.contains("needs at least 32"), "{message}"); + + // KOPPEL_KEY_FILE that names nothing is an error, not a quiet fall back to the volume's key. + let error = SecretBox::with_sources(&keys, &environment(&dir.join("missing"))).unwrap_err(); + assert!(error.to_string().contains("not a file"), "{error}"); + assert!(names(&keys).is_empty()); + let _ = fs::remove_dir_all(dir); +} + +#[test] +fn the_sources_are_tried_in_order() { + let dir = temp_dir("order"); + let keys = dir.join("keys"); + fs::create_dir(&keys).unwrap(); + let make = |name: &str, text: &str| { + let path = dir.join(name); + fs::write(&path, text).unwrap(); + path + }; + let env = make("env", "the environment key, 32 bytes or more of it"); + let credential = make("credential", "the credential key, 32 bytes or more of it"); + let secret = make("secret", "the Docker secret key, 32 bytes or more of it"); + let all = KeySources { + environment: Some(env.clone()), + credential: Some(credential.clone()), + docker_secret: Some(secret.clone()), + }; + + let source = |sources: &KeySources| { + SecretBox::with_sources(&keys, sources) + .unwrap() + .source() + .clone() + }; + assert_eq!(source(&all), KeySource::Environment(env)); + let no_env = KeySources { + environment: None, + ..all.clone() + }; + assert_eq!(source(&no_env), KeySource::Credential(credential)); + let only_secret = KeySources { + credential: Some(dir.join("absent")), + ..no_env + }; + assert_eq!(source(&only_secret), KeySource::DockerSecret(secret)); + let nothing = KeySources { + docker_secret: Some(dir.join("absent")), + ..only_secret + }; + assert_eq!(source(¬hing), KeySource::KeysDirectory); + let _ = fs::remove_dir_all(dir); +} + +#[test] +fn files_sealed_beside_them_move_to_a_key_outside_and_reseal() { + let dir = temp_dir("move"); + let keys = dir.join("keys"); + fs::create_dir(&keys).unwrap(); + let file = dir.join("secrets.json"); + let before = SecretBox::with_key_file(&keys).unwrap(); + fs::write(&file, before.protect(b"{\"k\":\"v\"}").unwrap()).unwrap(); + let key_file = dir.join("koppel-key"); + fs::write(&key_file, KEY).unwrap(); + + // With the new key the old file still opens, through the key file kept in the volume. + let moved = SecretBox::with_sources(&keys, &environment(&key_file)).unwrap(); + assert_eq!(moved.keys_read(), 2); + assert_eq!( + moved.unprotect(&fs::read(&file).unwrap()).unwrap(), + b"{\"k\":\"v\"}" + ); + + // Sealing again moves it to the new key; running it twice changes nothing more. + assert_eq!( + moved.reseal(std::slice::from_ref(&file)), + std::slice::from_ref(&file) + ); + let resealed = fs::read(&file).unwrap(); + assert!(moved.reseal(std::slice::from_ref(&file)).is_empty()); + assert_eq!(fs::read(&file).unwrap(), resealed); + + // Now the key file in the volume can go, and the file still opens. + fs::remove_file(keys.join("koppel-secrets.key")).unwrap(); + let alone = SecretBox::with_sources(&keys, &environment(&key_file)).unwrap(); + assert_eq!(alone.keys_read(), 1); + assert_eq!(alone.unprotect(&resealed).unwrap(), b"{\"k\":\"v\"}"); + assert!(names(&keys).is_empty(), "nothing was made in the volume"); + let _ = fs::remove_dir_all(dir); +} + +#[test] +fn a_rotated_key_file_is_read_and_everything_is_sealed_again_with_the_new_one() { + let dir = temp_dir("rotate"); + let keys = dir.join("keys"); + fs::create_dir(&keys).unwrap(); + let file = dir.join("ui-auth.json"); + let old = SecretBox::with_key_file(&keys).unwrap(); + fs::write(&file, old.protect(b"{\"stamp\":1}").unwrap()).unwrap(); + + // The rotation: put the key aside under a name of its own and start. + fs::rename( + keys.join("koppel-secrets.key"), + keys.join("koppel-secrets.2026-11-12.key"), + ) + .unwrap(); + let rotated = SecretBox::with_key_file(&keys).unwrap(); + assert_eq!(rotated.keys_read(), 2); + assert_eq!( + rotated.unprotect(&fs::read(&file).unwrap()).unwrap(), + b"{\"stamp\":1}" + ); + assert_eq!(rotated.reseal(std::slice::from_ref(&file)).len(), 1); + + // The new key alone opens it now, so the old file can be deleted. + fs::remove_file(keys.join("koppel-secrets.2026-11-12.key")).unwrap(); + let new_only = SecretBox::with_key_file(&keys).unwrap(); + assert_eq!(new_only.keys_read(), 1); + assert_eq!( + new_only.unprotect(&fs::read(&file).unwrap()).unwrap(), + b"{\"stamp\":1}" + ); + let _ = fs::remove_dir_all(dir); +} + +#[test] +fn a_file_sealed_with_a_key_that_is_not_in_the_ring_is_left_alone() { + let dir = temp_dir("foreign"); + let (one, two) = (dir.join("one"), dir.join("two")); + fs::create_dir_all(&one).unwrap(); + fs::create_dir_all(&two).unwrap(); + let file = dir.join("connection.json"); + let sealed = SecretBox::with_key_file(&one) + .unwrap() + .protect(b"{}") + .unwrap(); + fs::write(&file, &sealed).unwrap(); + + let ours = SecretBox::with_key_file(&two).unwrap(); + assert!( + ours.reseal(&[file.clone(), dir.join("missing.json")]) + .is_empty() + ); + assert_eq!(fs::read(&file).unwrap(), sealed); + let _ = fs::remove_dir_all(dir); +} + +#[test] +fn an_outside_key_is_rotated_by_keeping_the_old_one_as_a_retired_key() { + let dir = temp_dir("rotate-outside"); + let keys = dir.join("keys"); + fs::create_dir(&keys).unwrap(); + let old_key = dir.join("old-key"); + fs::write(&old_key, KEY).unwrap(); + let file = dir.join("secrets.json"); + let before = SecretBox::with_sources(&keys, &environment(&old_key)).unwrap(); + fs::write(&file, before.protect(b"{\"k\":1}").unwrap()).unwrap(); + + let new_key = dir.join("new-key"); + fs::write(&new_key, "the new key, which is also at least 32 bytes").unwrap(); + fs::copy(&old_key, keys.join("koppel-secrets.2026-11-12.key")).unwrap(); + let rotated = SecretBox::with_sources(&keys, &environment(&new_key)).unwrap(); + assert_eq!(rotated.keys_read(), 2); + assert_eq!(rotated.reseal(std::slice::from_ref(&file)).len(), 1); + + fs::remove_file(keys.join("koppel-secrets.2026-11-12.key")).unwrap(); + let alone = SecretBox::with_sources(&keys, &environment(&new_key)).unwrap(); + assert_eq!( + alone.unprotect(&fs::read(&file).unwrap()).unwrap(), + b"{\"k\":1}" + ); + let _ = fs::remove_dir_all(dir); +} diff --git a/src/koppel-config/tests/secret_properties.rs b/src/koppel-config/tests/secret_properties.rs new file mode 100644 index 0000000..ca0ed2d --- /dev/null +++ b/src/koppel-config/tests/secret_properties.rs @@ -0,0 +1,172 @@ +//! Properties of the secret file format and of the PKCS#12 reader, checked on many random inputs. +//! The generator is fixed, so a failure repeats; the case that failed is in the message. +//! +//! Nothing here may panic, whatever the bytes: the files are read from a disk anyone with access +//! can change, and the certificate comes from a file carried over from another install. + +use std::fs; +use std::path::PathBuf; + +use koppel_config::SecretBox; +use koppel_config::pkcs12; + +/// xorshift64*: enough for test inputs, and the same on every run. +struct Random(u64); + +impl Random { + fn next(&mut self) -> u64 { + self.0 ^= self.0 >> 12; + self.0 ^= self.0 << 25; + self.0 ^= self.0 >> 27; + self.0.wrapping_mul(0x2545_F491_4F6C_DD1D) + } + + fn below(&mut self, limit: usize) -> usize { + (self.next() % limit as u64) as usize + } + + fn bytes(&mut self, length: usize) -> Vec { + (0..length).map(|_| self.next() as u8).collect() + } +} + +fn secret_box(name: &str) -> (SecretBox, PathBuf) { + let dir = std::env::temp_dir().join(format!( + "koppel-props-{name}-{}-{:?}", + std::process::id(), + std::thread::current().id() + )); + let _ = fs::remove_dir_all(&dir); + fs::create_dir_all(&dir).unwrap(); + (SecretBox::with_key_file(&dir).unwrap(), dir) +} + +#[test] +fn what_is_sealed_opens_to_the_same_bytes() { + let (secrets, dir) = secret_box("roundtrip"); + let mut random = Random(0x9E37_79B9_7F4A_7C15); + for case in 0..400 { + let length = if case < 40 { case } else { random.below(8192) }; + let plain = random.bytes(length); + let sealed = secrets.protect(&plain).unwrap(); + assert_eq!( + secrets.unprotect(&sealed).unwrap(), + plain, + "case {case}, {length} bytes" + ); + } + let _ = fs::remove_dir_all(dir); +} + +#[test] +fn a_sealed_file_is_never_the_same_twice() { + let (secrets, dir) = secret_box("nonce"); + let first = secrets.protect(b"same").unwrap(); + let second = secrets.protect(b"same").unwrap(); + assert_ne!(first, second); + let _ = fs::remove_dir_all(dir); +} + +#[test] +fn any_flipped_byte_is_an_error() { + let (secrets, dir) = secret_box("flip"); + let mut random = Random(42); + for length in [0, 1, 17, 200] { + let sealed = secrets.protect(&random.bytes(length)).unwrap(); + for position in 0..sealed.len() { + for bit in [0x01u8, 0x80] { + let mut damaged = sealed.clone(); + damaged[position] ^= bit; + assert!( + secrets.unprotect(&damaged).is_err(), + "byte {position} of {} ^ {bit:#x} opened", + sealed.len() + ); + } + } + } + let _ = fs::remove_dir_all(dir); +} + +#[test] +fn any_truncation_or_extension_is_an_error() { + let (secrets, dir) = secret_box("truncate"); + let sealed = secrets.protect(b"{\"some\":\"json\"}").unwrap(); + for length in 0..sealed.len() { + assert!( + secrets.unprotect(&sealed[..length]).is_err(), + "{length} of {} bytes opened", + sealed.len() + ); + } + let mut longer = sealed.clone(); + longer.push(0); + assert!(secrets.unprotect(&longer).is_err()); + let _ = fs::remove_dir_all(dir); +} + +#[test] +fn random_bytes_and_random_bytes_with_a_good_header_are_errors() { + let (secrets, dir) = secret_box("garbage"); + let sealed = secrets.protect(b"x").unwrap(); + let mut random = Random(7); + for case in 0..2000 { + let length = random.below(200); + let mut bytes = random.bytes(length); + assert!(secrets.unprotect(&bytes).is_err(), "case {case}"); + // The header and key id of a real file, so it gets as far as the cipher. + if bytes.len() < 60 { + bytes.resize(60, 0); + } + bytes[..22].copy_from_slice(&sealed[..22]); + assert!( + secrets.unprotect(&bytes).is_err(), + "case {case} with a header" + ); + } + let _ = fs::remove_dir_all(dir); +} + +#[test] +fn the_pkcs12_reader_never_panics_on_random_input() { + let mut random = Random(0xC0FF_EE00_1234_5678); + for case in 0..3000 { + let length = random.below(400); + let bytes = random.bytes(length); + let _ = pkcs12::parse(&bytes); + + // A DER sequence of the right length, so the reader goes past the first check. + let mut framed = vec![0x30]; + if length < 128 { + framed.push(length as u8); + } else { + framed.extend([0x82, (length >> 8) as u8, length as u8]); + } + framed.extend_from_slice(&bytes); + let _ = pkcs12::parse(&framed); + let _ = case; + } +} + +#[test] +fn the_pkcs12_reader_never_panics_on_a_good_file_that_is_damaged() { + // Any certificate and key bytes do for `write`; it does not look inside them. + let good = pkcs12::write( + &[0x30, 0x03, 0x02, 0x01, 0x05], + &[0x30, 0x03, 0x02, 0x01, 0x07], + ) + .unwrap(); + assert!(pkcs12::parse(&good).is_ok()); + let mut random = Random(99); + for length in 0..good.len() { + let _ = pkcs12::parse(&good[..length]); + } + for _ in 0..3000 { + let mut damaged = good.clone(); + for _ in 0..1 + random.below(3) { + let position = random.below(damaged.len()); + damaged[position] = random.next() as u8; + } + let _ = pkcs12::parse(&damaged); + } +} diff --git a/src/koppel-config/tests/upgrade.rs b/src/koppel-config/tests/upgrade.rs index 726cdb4..59e8085 100644 --- a/src/koppel-config/tests/upgrade.rs +++ b/src/koppel-config/tests/upgrade.rs @@ -262,7 +262,10 @@ async fn a_0_1_2_install_is_converted_and_keeps_its_certificate_clients_connecti .find(|c| c.id == "client-9419f1711c") .unwrap(); assert_eq!( - (bench.name.as_str(), bench.secret.as_deref()), + ( + bench.name.as_str(), + bench.secret.as_deref().map(String::as_str) + ), ("bench", Some("tBQSIdMdQONeoLmAIJ507c791ZpSVOl5YkJtXkIwL9A")) ); let lab = state @@ -280,7 +283,7 @@ async fn a_0_1_2_install_is_converted_and_keeps_its_certificate_clients_connecti Some(LINUX_012_FINGERPRINT) ); assert_eq!( - link.client_secret.as_deref(), + link.client_secret.as_deref().map(String::as_str), Some("tBQSIdMdQONeoLmAIJ507c791ZpSVOl5YkJtXkIwL9A") ); assert!(link.is_complete()); diff --git a/src/koppel-usb/tests/common/mod.rs b/src/koppel-usb/tests/common/mod.rs index bd0917d..9e3d8e8 100644 --- a/src/koppel-usb/tests/common/mod.rs +++ b/src/koppel-usb/tests/common/mod.rs @@ -967,7 +967,7 @@ impl ClientSide { .into(), ), client_id: Some(format!("client-{n}")), - client_secret: Some(format!("secret-{n}")), + client_secret: Some(format!("secret-{n}").into()), next_server_fingerprint: None, }) .await diff --git a/src/koppel-web/src/api/client.rs b/src/koppel-web/src/api/client.rs index 668acb5..3be2304 100644 --- a/src/koppel-web/src/api/client.rs +++ b/src/koppel-web/src/api/client.rs @@ -219,7 +219,7 @@ impl ConnectionUpdate { server_fingerprint: fingerprint.map(normalize), client_id: self.client_id.as_deref().map(|id| id.trim().to_owned()), client_secret: match self.client_secret.as_deref() { - Some(secret) if !secret.is_empty() => Some(secret.to_owned()), + Some(secret) if !secret.is_empty() => Some(secret.into()), _ if keeps => current.client_secret.clone(), _ => None, }, @@ -405,7 +405,10 @@ mod tests { }; assert!(same.keeps_server(¤t)); let applied = same.apply(¤t); - assert_eq!(applied.client_secret.as_deref(), Some("s")); + assert_eq!( + applied.client_secret.as_deref().map(String::as_str), + Some("s") + ); assert_eq!(applied.client_id.as_deref(), Some("c")); let other = ConnectionUpdate { server_url: Some("https://b:5240".into()), diff --git a/src/koppel-web/src/auth/mod.rs b/src/koppel-web/src/auth/mod.rs index e18b5a0..9b13571 100644 --- a/src/koppel-web/src/auth/mod.rs +++ b/src/koppel-web/src/auth/mod.rs @@ -217,7 +217,7 @@ impl UiAuth { let stamp = new_id(); self.file .update(|_| UiCredentials { - password_hash: Some(hash), + password_hash: Some(hash.into()), security_stamp: Some(stamp), revoked_sessions: None, }) @@ -236,7 +236,7 @@ impl UiAuth { lock(&self.keep).insert(stamp.clone(), keep.to_owned()); self.file .update(|current| UiCredentials { - password_hash: Some(hash), + password_hash: Some(hash.into()), security_stamp: Some(stamp), revoked_sessions: current.revoked_sessions.clone(), }) diff --git a/src/koppel-web/src/roles/skakel/client.rs b/src/koppel-web/src/roles/skakel/client.rs index 8548b0a..d68027b 100644 --- a/src/koppel-web/src/roles/skakel/client.rs +++ b/src/koppel-web/src/roles/skakel/client.rs @@ -425,7 +425,7 @@ impl ClientRole for SkakelClientRole { }; let credentials = Credentials::new( saved.client_id.clone().unwrap_or_default(), - saved.client_secret.clone().unwrap_or_default(), + saved.client_secret.as_deref().cloned().unwrap_or_default(), ); let options = ClientOptions::default().request_timeout(TEST_TIMEOUT); let link = match skakel_client::Link::new(&address, pins, credentials, options) { diff --git a/src/koppel-web/src/roles/skakel/links.rs b/src/koppel-web/src/roles/skakel/links.rs index 28e8390..88b826c 100644 --- a/src/koppel-web/src/roles/skakel/links.rs +++ b/src/koppel-web/src/roles/skakel/links.rs @@ -98,7 +98,11 @@ fn make( .map_err(|_| "The saved fingerprint is not a SHA-256 fingerprint.".to_owned())?; let credentials = Credentials::new( connection.client_id.clone().unwrap_or_default(), - connection.client_secret.clone().unwrap_or_default(), + connection + .client_secret + .as_deref() + .cloned() + .unwrap_or_default(), ); skakel_client::Link::new( &address, diff --git a/src/koppel-web/src/roles/skakel/store.rs b/src/koppel-web/src/roles/skakel/store.rs index c7bd9ab..01f9648 100644 --- a/src/koppel-web/src/roles/skakel/store.rs +++ b/src/koppel-web/src/roles/skakel/store.rs @@ -226,7 +226,7 @@ fn from_skakel( { current.certificate_pfx.clone() } - _ => certificate.to_pfx_base64().map_err(|e| e.0)?, + _ => certificate.to_pfx_base64().map_err(|e| e.0)?.into(), }; let next_certificate = match &state.next_certificate { Some(next) => { @@ -238,7 +238,7 @@ fn from_skakel( { kept.pfx.clone() } - _ => next_certificate.to_pfx_base64().map_err(|e| e.0)?, + _ => next_certificate.to_pfx_base64().map_err(|e| e.0)?.into(), }; Some(SkakelNextCertificateRecord { pfx, @@ -258,7 +258,7 @@ fn from_skakel( secret_hash: c.secret_hash.clone(), created_at: c.created_at, generation: i32::try_from(c.generation).unwrap_or(i32::MAX), - secret: c.secret.clone(), + secret: c.secret.clone().map(Into::into), }) .collect(), signing_key: None, @@ -294,7 +294,7 @@ fn new_state(host_name: &str, now: OffsetDateTime) -> Result Result, Box> { ) })?; let secrets = Arc::new(SecretBox::open(&paths.keys)?); + let source = secrets.source(); + if *source == KeySource::KeysDirectory { + tracing::info!( + "The secret files are sealed with the {source}, beside the files it protects: see \"Threat model\" in docs/security.md for a key kept elsewhere" + ); + } else { + tracing::info!("The secret files are sealed with {source}"); + } if let Err(e) = convert_0_1_secrets(&paths, &secrets) { tracing::error!("{e}"); } + // After a rotation, or a move of the key out of the keys directory, files sealed with an older + // key are written again with the current one. + let mut sealed = paths.secret_files().to_vec(); + sealed.push(paths.keys.join("ui-session.key")); + secrets.reseal(&sealed); Ok(secrets) }