From a1e398621eec9472ad67f1eafeba9ff23b012c2f Mon Sep 17 00:00:00 2001 From: slopulus Date: Tue, 17 Nov 2026 19:57:56 +0100 Subject: keys: a party's key may be ecdsa-sha2-nistp256, its signature low-S only A party's keys may be held where no file has them, in a Secure Enclave or a phone, and those are ECDSA keys on NIST P-256. Everywhere a party's key counts (a version's keys, a key set, the key an event is signed with) such a key is taken beside an Ed25519 one, spelled as `ssh-keygen` writes it, without a comment: `ecdsa-sha2-nistp256`, a space, and the base64 of its SSH encoding, its point uncompressed and on the curve. Its signature is SSHSIG as an Ed25519 one is, hashed with `sha512`, its inner signature over SHA-256 as SSH signs with such a key. ECDSA signatures are malleable: of `s` and the curve's order less `s`, both check. So the federation takes one spelling alone: `s` low, at most half the order, `r` and `s` each SSH's shortest mpint, and the blob reading back to itself as an Ed25519 one does. What anyone makes of a party's signature is then none, as before. The vectors are a key `ssh-keygen -t ecdsa -b 256` made, a first version naming it, and a write and a key set `ssh-keygen -Y sign` signed with it, each taken; the signature's high-S twin, which checks as ECDSA, and its `r` spelled longer are none. Ed25519 keys and signatures are spelled and checked as they were. --- Cargo.toml | 2 + src/access/sshsig.rs | 16 ++- src/federation/event.rs | 3 +- src/federation/keys.rs | 283 +++++++++++++++++++++++++++++++++++++++++----- src/federation/party.rs | 3 +- src/federation/vectors.rs | 44 +++++++ 6 files changed, 313 insertions(+), 38 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index e4ba66c..4faaaed 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -69,6 +69,8 @@ getrandom = "0.4" # Timestamps written and read as text (RFC 3339, RFC 9110 dates): no time zones needed. jiff = { version = "0.2", default-features = false, features = ["std"] } libc = { version = "0.2", optional = true } +# A party's ECDSA keys on NIST P-256 (`ecdsa-sha2-nistp256`), beside its Ed25519 ones. +p256 = { version = "0.14", default-features = false, features = ["ecdsa"] } password-hash = "0.6" # Its TLS (only for a Mycelium daemon elsewhere, over https) is rustls with ring, which # libp2p's QUIC uses too, rather than reqwest's default aws-lc (a C library, cmake). diff --git a/src/access/sshsig.rs b/src/access/sshsig.rs index e25d8a7..740a727 100644 --- a/src/access/sshsig.rs +++ b/src/access/sshsig.rs @@ -198,7 +198,12 @@ pub(crate) fn sign(key: &SigningKey, namespace: &str, message: &[u8]) -> String } /// What a signature is made over. -fn signed_data(namespace: &[u8], reserved: &[u8], algorithm: &[u8], hash: &[u8]) -> Vec { +pub(crate) fn signed_data( + namespace: &[u8], + reserved: &[u8], + algorithm: &[u8], + hash: &[u8], +) -> Vec { let mut signed = MAGIC.to_vec(); string(&mut signed, namespace); string(&mut signed, reserved); @@ -207,13 +212,14 @@ fn signed_data(namespace: &[u8], reserved: &[u8], algorithm: &[u8], hash: &[u8]) signed } -fn string(out: &mut Vec, bytes: &[u8]) { +/// `bytes` as SSH's string: a big-endian `u32` length, then the bytes. +pub(crate) fn string(out: &mut Vec, bytes: &[u8]) { out.extend_from_slice(&(bytes.len() as u32).to_be_bytes()); out.extend_from_slice(bytes); } /// Reads SSH's encoding. -struct Reader<'a>(&'a [u8]); +pub(crate) struct Reader<'a>(pub(crate) &'a [u8]); impl<'a> Reader<'a> { fn u32(&mut self) -> Result { @@ -222,7 +228,7 @@ impl<'a> Reader<'a> { Ok(u32::from_be_bytes(*bytes)) } - fn string(&mut self) -> Result<&'a [u8], String> { + pub(crate) fn string(&mut self) -> Result<&'a [u8], String> { let length = self.u32()? as usize; if self.0.len() < length { return Err("cut short".to_owned()); @@ -232,7 +238,7 @@ impl<'a> Reader<'a> { Ok(bytes) } - fn end(&self) -> Result<(), String> { + pub(crate) fn end(&self) -> Result<(), String> { if self.0.is_empty() { Ok(()) } else { diff --git a/src/federation/event.rs b/src/federation/event.rs index 00c7018..15cee45 100644 --- a/src/federation/event.rs +++ b/src/federation/event.rs @@ -5,7 +5,6 @@ use super::jcs::{self, Json}; use super::keys; use super::store::Id; use super::version::{self, Version}; -use crate::access::sshsig::PublicKey; /// The most bytes an event may have. pub(crate) const LARGEST: usize = 256 * 1024; @@ -229,7 +228,7 @@ impl Event { } /// The key a signed event is signed with. - pub(crate) fn public(signed: &Signed) -> PublicKey { + pub(crate) fn public(signed: &Signed) -> keys::Key { keys::key(&signed.key).expect("an event's key was read as one") } } diff --git a/src/federation/keys.rs b/src/federation/keys.rs index 7df0bd9..ee5f01e 100644 --- a/src/federation/keys.rs +++ b/src/federation/keys.rs @@ -1,28 +1,109 @@ //! Keys, node IDs and signatures, each spelled one way (`docs/federation.md`, Events): //! -//! * a key: `ssh-ed25519`, one space, and the key's base64, padded and canonical, with no -//! comment, its 32 bytes an Ed25519 public key; +//! * a key: its type, one space, and the base64 of its SSH encoding, padded and canonical, +//! with no comment: `ssh-ed25519`, its 32 bytes an Ed25519 public key, or +//! `ecdsa-sha2-nistp256`, its point on NIST P-256 uncompressed; //! * a node ID: as continuum spells it, `continuum:` and the 64 lower-case hex digits of //! the node's Ed25519 public key; //! * a signature: SSHSIG of version 1 over the event's bytes without `sig`, for the //! namespace `continuum-federation`, hashed with `sha512`, its reserved field empty, its -//! key the event's, in base64, padded and canonical, unarmored; checked strictly. +//! key the event's, in base64, padded and canonical, unarmored; checked strictly. An +//! ECDSA signature's `r` and `s` are SSH's shortest mpints, and its `s` low: at most +//! half the curve's order, as `s` and the order less `s` both check. //! //! So nobody but its signer makes another event of what a party signed. use base64::{Engine, engine::general_purpose::STANDARD as BASE64}; use ed25519_dalek::{SigningKey, VerifyingKey}; +use p256::ecdsa::signature::Verifier; +use sha2::{Digest, Sha512}; -use crate::access::sshsig::{self, PublicKey}; +use crate::access::sshsig::{self, PublicKey, Reader, string}; use crate::identity; /// What a party's signature is for. pub(crate) const NAMESPACE: &str = "continuum-federation"; +const ED25519: &str = "ssh-ed25519"; +const P256: &str = "ecdsa-sha2-nistp256"; +const CURVE: &[u8] = b"nistp256"; + +/// A party's key. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum Key { + Ed25519(PublicKey), + /// ECDSA on NIST P-256: its point, SEC1-encoded, uncompressed. + P256([u8; 65]), +} + +impl Key { + /// From an `authorized_keys` line: its type, its base64, and maybe a comment. + pub(crate) fn parse(line: &str) -> Result { + let mut parts = line.split_whitespace(); + let (Some(kind), Some(encoded)) = (parts.next(), parts.next()) else { + return Err(format!("not `{ED25519}|{P256} [comment]`")); + }; + match kind { + ED25519 => return PublicKey::parse(line).map(Key::Ed25519), + P256 => {} + _ => { + return Err(format!( + "a {kind} key: only {ED25519} and {P256} keys are taken" + )); + } + } + let blob = BASE64 + .decode(encoded) + .map_err(|error| format!("its base64 doesn't decode: {error}"))?; + let mut reader = Reader(&blob); + if reader.string()? != P256.as_bytes() || reader.string()? != CURVE { + return Err(format!("not an {P256} key")); + } + let point: [u8; 65] = reader + .string()? + .try_into() + .map_err(|_| "a point that isn't 65 bytes".to_owned())?; + reader.end()?; + p256::ecdsa::VerifyingKey::from_sec1_bytes(&point) + .map_err(|_| "not a point on NIST P-256".to_owned())?; + Ok(Key::P256(point)) + } + + fn kind(&self) -> &'static str { + match self { + Key::Ed25519(_) => ED25519, + Key::P256(_) => P256, + } + } + + /// Its SSH encoding. + pub(crate) fn blob(&self) -> Vec { + match self { + Key::Ed25519(key) => key.blob(), + Key::P256(point) => { + let mut blob = Vec::new(); + string(&mut blob, P256.as_bytes()); + string(&mut blob, CURVE); + string(&mut blob, point); + blob + } + } + } + + /// As an `authorized_keys` line has it, without a comment. + pub(crate) fn line(&self) -> String { + format!("{} {}", self.kind(), BASE64.encode(self.blob())) + } +} + /// The key `text` spells, where it spells one as the federation does. -pub(crate) fn key(text: &str) -> Option { - let key = PublicKey::parse(text).ok()?; - (key.line() == text && VerifyingKey::from_bytes(&key.0).is_ok()).then_some(key) +pub(crate) fn key(text: &str) -> Option { + let key = Key::parse(text).ok()?; + let valid = match &key { + Key::Ed25519(public) => VerifyingKey::from_bytes(&public.0).is_ok(), + Key::P256(_) => true, + }; + (key.line() == text && valid).then_some(key) } /// Whether `text` is a node ID spelled as continuum spells one. @@ -31,19 +112,77 @@ pub(crate) fn node_id(text: &str) -> bool { } /// Whether `sig` is `key`'s signature of `message`, spelled as the federation spells one. -pub(crate) fn verifies(key: &PublicKey, sig: &str, message: &[u8]) -> bool { +pub(crate) fn verifies(key: &Key, sig: &str, message: &[u8]) -> bool { let Ok(blob) = BASE64.decode(sig) else { return false; }; - if BASE64.encode(&blob) != sig || blob.len() < 64 { + if BASE64.encode(&blob) != sig { return false; } // The blob reads back to itself: what signing with this key writes around its - // signature, the last 64 bytes. - if blob != written(key, &blob[blob.len() - 64..]) { + // signature, all that follows what it writes around none. + let Some(signature) = blob.get(written(key, &[]).len()..) else { + return false; + }; + if blob != written(key, signature) { return false; } - sshsig::verify_blob(&blob, NAMESPACE, message).is_ok_and(|signer| signer == *key) + match key { + Key::Ed25519(public) => { + sshsig::verify_blob(&blob, NAMESPACE, message).is_ok_and(|signer| signer == *public) + } + Key::P256(point) => p256_verifies(point, signature, message), + } +} + +/// Whether `signature`, `r` and `s` as SSH's mpints, is the P-256 key `point`'s of +/// `message`, spelled one way: each mpint its shortest, `s` low. +fn p256_verifies(point: &[u8; 65], signature: &[u8], message: &[u8]) -> bool { + let Some(parsed) = ecdsa_signature(signature) else { + return false; + }; + if mpints(&parsed) != signature || parsed.normalize_s() != parsed { + return false; + } + p256::ecdsa::VerifyingKey::from_sec1_bytes(point) + .is_ok_and(|key| key.verify(&signed(message), &parsed).is_ok()) +} + +/// An ECDSA signature from `r` and `s`, SSH's mpints, where each is an integer from 1 to +/// below the curve's order, spelled any way SSH reads. +fn ecdsa_signature(bytes: &[u8]) -> Option { + /// A non-negative mpint of up to 32 bytes, leading zeros aside, as 32 bytes. + fn scalar(mpint: &[u8]) -> Option<[u8; 32]> { + if mpint.first().is_some_and(|byte| byte & 0x80 != 0) { + return None; + } + let digits = &mpint[mpint.iter().take_while(|byte| **byte == 0).count()..]; + let mut out = [0; 32]; + out.get_mut(32usize.checked_sub(digits.len())?..)? + .copy_from_slice(digits); + Some(out) + } + let mut reader = Reader(bytes); + let r = scalar(reader.string().ok()?)?; + let s = scalar(reader.string().ok()?)?; + reader.end().ok()?; + p256::ecdsa::Signature::from_scalars(r, s).ok() +} + +/// `signature`'s `r` and `s`, each SSH's shortest mpint. +fn mpints(signature: &p256::ecdsa::Signature) -> Vec { + let (r, s) = signature.split_bytes(); + let mut out = Vec::new(); + for value in [r, s] { + let digits = &value[value.iter().take_while(|byte| **byte == 0).count()..]; + let mut mpint = Vec::new(); + if digits.first().is_some_and(|byte| byte & 0x80 != 0) { + mpint.push(0); + } + mpint.extend_from_slice(digits); + string(&mut out, &mpint); + } + out } /// `message` signed with `key`, as the federation spells a signature: what @@ -54,11 +193,22 @@ pub(crate) fn sign(key: &SigningKey, message: &[u8]) -> String { BASE64.encode(blob) } +/// What a signature of `message` is made over: SSHSIG's signed data, hashed with `sha512`. +fn signed(message: &[u8]) -> Vec { + sshsig::signed_data( + NAMESPACE.as_bytes(), + b"", + b"sha512", + &Sha512::digest(message), + ) +} + /// The SSHSIG blob of a signature by `key`, of version 1, for the federation's namespace, -/// its reserved field empty, hashed with `sha512`: as `ssh-keygen` writes it. -fn written(key: &PublicKey, signature: &[u8]) -> Vec { +/// its reserved field empty, hashed with `sha512`: as `ssh-keygen` writes it around +/// `signature`, the key type's own. +fn written(key: &Key, signature: &[u8]) -> Vec { let mut inner = Vec::new(); - string(&mut inner, b"ssh-ed25519"); + string(&mut inner, key.kind().as_bytes()); string(&mut inner, signature); let mut blob = b"SSHSIG".to_vec(); blob.extend_from_slice(&1u32.to_be_bytes()); @@ -70,36 +220,55 @@ fn written(key: &PublicKey, signature: &[u8]) -> Vec { blob } -fn string(out: &mut Vec, bytes: &[u8]) { - out.extend_from_slice(&(bytes.len() as u32).to_be_bytes()); - out.extend_from_slice(bytes); -} - #[cfg(test)] mod tests { use super::*; + use crate::federation::event::Event; + use crate::federation::jcs::{self, Json}; + use crate::federation::vectors::{ECDSA_KEY, ECDSA_WRITE}; fn signer(seed: u8) -> SigningKey { SigningKey::from_bytes(&[seed; 32]) } - fn public(key: &SigningKey) -> PublicKey { - PublicKey(key.verifying_key().to_bytes()) + fn public(key: &SigningKey) -> Key { + Key::Ed25519(PublicKey(key.verifying_key().to_bytes())) } #[test] fn a_key_is_spelled_one_way() { - let line = public(&signer(1)).line(); - assert!(key(&line).is_some()); - assert!(key(&format!("{line} comment")).is_none()); - assert!(key(&line.replacen(' ', " ", 1)).is_none()); - assert!(key(&format!(" {line}")).is_none()); - let unpadded = line.trim_end_matches('='); - if unpadded != line { - assert!(key(unpadded).is_none()); + for line in [public(&signer(1)).line(), ECDSA_KEY.to_owned()] { + assert_eq!(key(&line).map(|key| key.line()), Some(line.clone())); + assert!(key(&format!("{line} comment")).is_none()); + assert!(key(&line.replacen(' ', " ", 1)).is_none()); + assert!(key(&format!(" {line}")).is_none()); + let unpadded = line.trim_end_matches('='); + if unpadded != line { + assert!(key(unpadded).is_none()); + } } } + #[test] + fn an_ecdsa_key_is_a_point_on_the_curve_uncompressed() { + let Some(Key::P256(point)) = key(ECDSA_KEY) else { + panic!("an ECDSA key"); + }; + let line = |point: &[u8]| { + let mut blob = Vec::new(); + string(&mut blob, P256.as_bytes()); + string(&mut blob, CURVE); + string(&mut blob, point); + format!("{P256} {}", BASE64.encode(blob)) + }; + assert_eq!(line(&point), ECDSA_KEY); + let compressed = [&[2 + (point[64] & 1)], &point[1..33]].concat(); + assert!(Key::parse(&line(&compressed)).is_err()); + let mut off = point; + off[64] ^= 1; + assert!(Key::parse(&line(&off)).is_err()); + } + #[test] fn a_node_id_is_spelled_one_way() { let id = identity::node_id_of(&signer(2).verifying_key().to_bytes()); @@ -144,4 +313,58 @@ mod tests { b"an event" )); } + + /// The ECDSA vector's write: its key, its `sig`, and the bytes it signs. + fn ecdsa_write() -> (Key, String, Vec) { + let event = jcs::read(ECDSA_WRITE.as_bytes()).expect("JCS"); + let sig = event.get("sig").and_then(Json::as_str).expect("a sig"); + ( + key(ECDSA_KEY).expect("a key"), + sig.to_owned(), + event.without("sig").bytes(), + ) + } + + /// The `r` and `s` of `sig`, a signature by `key` as the federation spells one. + fn rs<'a>(key: &Key, sig: &'a [u8]) -> &'a [u8] { + &sig[written(key, &[]).len()..] + } + + #[test] + fn an_ecdsa_signature_is_low_s_and_spelled_one_way() { + let (key, sig, message) = ecdsa_write(); + assert!(verifies(&key, &sig, &message)); + assert!(!verifies(&key, &sig, b"another event")); + let blob = BASE64.decode(&sig).expect("base64"); + let ours = ecdsa_signature(rs(&key, &blob)).expect("r and s"); + let refused = |rs: &[u8]| { + let other = BASE64.encode(written(&key, rs)); + assert!(!verifies(&key, &other, &message)); + assert!(Event::read(ECDSA_WRITE.replace(&sig, &other).as_bytes()).is_none()); + }; + // Its twin of the order less `s`, high, checks as ECDSA, and is none here. + let (r, s) = ours.split_scalars(); + let twin = p256::ecdsa::Signature::from_scalars(r, -s).expect("a signature"); + let Key::P256(point) = key else { + unreachable!("an ECDSA key") + }; + let verifying = p256::ecdsa::VerifyingKey::from_sec1_bytes(&point).expect("a point"); + assert!(verifying.verify(&signed(&message), &twin).is_ok()); + assert_ne!(twin, ours); + assert_eq!(twin.normalize_s(), ours); + refused(&mpints(&twin)); + // `r` with a zero byte more in front: the same number to SSH, and none here. + let mut reader = Reader(rs(&key, &blob)); + let (r, s) = (reader.string().unwrap(), reader.string().unwrap()); + let mut longer = Vec::new(); + string(&mut longer, &[&[0], r].concat()); + string(&mut longer, s); + assert_eq!(ecdsa_signature(&longer), Some(ours)); + refused(&longer); + // Nor a negative `r`. + let mut negative = Vec::new(); + string(&mut negative, &[&[0x80], r].concat()); + string(&mut negative, s); + refused(&negative); + } } diff --git a/src/federation/party.rs b/src/federation/party.rs index f0ae288..21e1fb7 100644 --- a/src/federation/party.rs +++ b/src/federation/party.rs @@ -42,6 +42,7 @@ use super::client::{self, Record}; use super::event::{self, Does, Event, Signed}; use super::fold::Federation; use super::jcs::Json; +use super::keys::Key; use super::store::Id; use super::store::memory::Store; use super::version::Version; @@ -282,7 +283,7 @@ pub(crate) async fn main() -> Result<()> { let keys = strings(sub, "keys") .iter() .map(|line| { - PublicKey::parse(line) + Key::parse(line) .map(|key| key.line()) .map_err(|why| anyhow!("{line:?}: {why}")) }) diff --git a/src/federation/vectors.rs b/src/federation/vectors.rs index 25c6a41..3d839c8 100644 --- a/src/federation/vectors.rs +++ b/src/federation/vectors.rs @@ -5,9 +5,11 @@ //! change of the federation, which takes its next number. use super::event::{self, Checkpoint, Event}; +use super::fold::Federation; use super::harness::{self, Party, Spec}; use super::jcs::Json; use super::store::Id; +use super::store::memory::{Offered, Store}; use super::version::{self, Version}; /// A write by tv (keys from seeds: tv's of 1s, lass's of 2s), on the ID of @@ -145,6 +147,48 @@ fn events_at_federation_1s_sizes_and_just_past_them() { assert!(Event::read(&tv.write(&[dep()], "home/tv/n", largest)).is_some()); } +/// tv's key on NIST P-256, made by `ssh-keygen -t ecdsa -b 256`; the first version naming +/// it for tv, beside lass's key of 2s, with tv's node and a namespace each; its root; and a +/// write and a key set tv signed with it, on the root, by `ssh-keygen -Y sign -n +/// continuum-federation`, each signature's `s` low. +pub(crate) const ECDSA_KEY: &str = "ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBI6uK92X+y9N7jbrgH7grypeMRnxRsEFGnbhV97LJ/7UFKmBtDn0p6V5EBz9WAeeb3BUMCMlkFq3VxEvySs35ss="; +const ECDSA_VERSION: &str = r#"{"changes":null,"federation":1,"keys":{"lass":{"keys":["ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIIE5dw6ofRdfVqNUZsNMfszLjYqRtO43ol32D1uPybOU"],"since":0},"tv":{"keys":["ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBI6uK92X+y9N7jbrgH7grypeMRnxRsEFGnbhV97LJ/7UFKmBtDn0p6V5EBz9WAeeb3BUMCMlkFq3VxEvySs35ss="],"since":0}},"nodes":{"lass":{"nodes":[],"since":0},"tv":{"nodes":["continuum:e5687b6d11ccfb632abbafe844f8f1693d160aa582156ed66eea38ab5e7d1e12"],"since":0}},"number":0,"rules":[{"path":"home/{party}/**","writer":"{party}"}]}"#; +const ECDSA_ROOT_ID: &str = "6bca61798e124250309330835c674f3c4e7b4547e13fad954674c41b338d7859"; +pub(crate) const ECDSA_WRITE: &str = r#"{"deps":["6bca61798e124250309330835c674f3c4e7b4547e13fad954674c41b338d7859"],"key":"ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBI6uK92X+y9N7jbrgH7grypeMRnxRsEFGnbhV97LJ/7UFKmBtDn0p6V5EBz9WAeeb3BUMCMlkFq3VxEvySs35ss=","party":"tv","sig":"U1NIU0lHAAAAAQAAAGgAAAATZWNkc2Etc2hhMi1uaXN0cDI1NgAAAAhuaXN0cDI1NgAAAEEEjq4r3Zf7L03uNuuAfuCvKl4xGfFGwQUaduFX3ssn/tQUqYG0OfSnpXkQHP1YB55vcFQwIyWQWrdXES/JKzfmywAAABRjb250aW51dW0tZmVkZXJhdGlvbgAAAAAAAAAGc2hhNTEyAAAAYwAAABNlY2RzYS1zaGEyLW5pc3RwMjU2AAAASAAAACA9LGG7MLFobYksXCVEMCda7M5iGcxB8vunTxypmyf3+wAAACBWct5p0CI3w3+OpKCS4w7DJKqpP8+oxgCbRFkvlhZ73A==","write":{"path":"home/tv/laptop","value":"10.243.7.3"}}"#; +const ECDSA_WRITE_ID: &str = "f1f4bf7c1226d920c37d20a8228d490ea7249a4df4005a38f7d5993bd6923cb2"; +const ECDSA_KEYS: &str = r#"{"deps":["6bca61798e124250309330835c674f3c4e7b4547e13fad954674c41b338d7859"],"key":"ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBI6uK92X+y9N7jbrgH7grypeMRnxRsEFGnbhV97LJ/7UFKmBtDn0p6V5EBz9WAeeb3BUMCMlkFq3VxEvySs35ss=","keys":["ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBI6uK92X+y9N7jbrgH7grypeMRnxRsEFGnbhV97LJ/7UFKmBtDn0p6V5EBz9WAeeb3BUMCMlkFq3VxEvySs35ss=","ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIAzB4a38+wy5iWPeKWbYF5hoHAxLVqYMO73eO8on/XYH"],"party":"tv","sig":"U1NIU0lHAAAAAQAAAGgAAAATZWNkc2Etc2hhMi1uaXN0cDI1NgAAAAhuaXN0cDI1NgAAAEEEjq4r3Zf7L03uNuuAfuCvKl4xGfFGwQUaduFX3ssn/tQUqYG0OfSnpXkQHP1YB55vcFQwIyWQWrdXES/JKzfmywAAABRjb250aW51dW0tZmVkZXJhdGlvbgAAAAAAAAAGc2hhNTEyAAAAZAAAABNlY2RzYS1zaGEyLW5pc3RwMjU2AAAASQAAACEA8W+2M0hB62y5PDq3TrERSA/TJBFjI21dg+u3GJzU7cUAAAAgYqFtgJ/74JtWUWGN/kBQBibbCE5EbXR/Phz4VbzBbko="}"#; +const ECDSA_KEYS_ID: &str = "4703ad7b712372f737fcd52c73c071f81d9c48f8cd63404e91cdec249a33347d"; + +#[test] +fn an_ecdsa_key_and_what_it_signs() { + let (write, keys) = (ECDSA_WRITE.as_bytes(), ECDSA_KEYS.as_bytes()); + assert!( + Event::read(write).is_some(), + "a write signed with an ECDSA key" + ); + assert!( + Event::read(keys).is_some(), + "a key set signed with an ECDSA key" + ); + assert_eq!(Id::of(write).to_string(), ECDSA_WRITE_ID); + assert_eq!(Id::of(keys).to_string(), ECDSA_KEYS_ID); + let mut spec = Spec::first(&[&tv(), &Party::new("lass", 2)], &[]); + spec.parties[0].keys = vec![ECDSA_KEY.to_owned()]; + assert_eq!( + String::from_utf8(spec.json().bytes()).expect("UTF-8"), + ECDSA_VERSION + ); + let root = spec.root(); + assert_eq!(Id::of(&root).to_string(), ECDSA_ROOT_ID); + let mut store = Store::::new(root, Vec::new()).expect("a root"); + for event in [write, keys] { + assert_eq!( + store.offer(event.to_vec()), + Offered::Taken(vec![Id::of(event)]) + ); + } +} + /// The changes founding the swarm of `first`'s root, and those founding the fork whose /// root is `FORK_ROOT`, keeping tv's write: each its hash and its bytes. Automerge encodes /// them, so no script apart computes them; a run of this code printed them, and they were -- cgit v1.3.1 From bcda4d67483239691b045c5b978047f017f3b9e3 Mon Sep 17 00:00:00 2001 From: slopulus Date: Tue, 17 Nov 2026 20:01:42 +0100 Subject: continuum-party: signing through an ssh-agent A key held in hardware is never a file: only an ssh-agent signs with it. Given a public key as `--key` (a `.pub` file, `ssh-ed25519` or `ecdsa-sha2-nistp256`), the client asks the agent at `SSH_AUTH_SOCK` to sign what SSHSIG signs (a sign request with the key's blob, no flags) and writes the blob around the agent's signature as `ssh-keygen -Y sign` does. An ECDSA signature the agent gives with a high `s` is made low, the other of its two spellings, which the federation takes. What it makes is checked before it is used. A private key file signs as it did. A test starts `ssh-agent`, adds an ECDSA and an Ed25519 key to it and deletes their files, signs through it, and has both continuum and `ssh-keygen -Y verify` check each signature, one of an agent's high-S answers among them. Without OpenSSH it asks nothing. --- src/config/mod.rs | 2 +- src/federation/agent.rs | 45 +++++++++++++++ src/federation/event.rs | 22 ++++++-- src/federation/keys.rs | 146 ++++++++++++++++++++++++++++++++++++++++++++++++ src/federation/mod.rs | 1 + src/federation/party.rs | 55 +++++++++++++----- 6 files changed, 251 insertions(+), 20 deletions(-) create mode 100644 src/federation/agent.rs diff --git a/src/config/mod.rs b/src/config/mod.rs index 533b44c..2ff0a45 100644 --- a/src/config/mod.rs +++ b/src/config/mod.rs @@ -752,7 +752,7 @@ pub(crate) const PARTY_OPTIONS: &[OptionSpec] = &[ Kind::Text, "PATH", None, - "The party's key it signs with: an OpenSSH private key file, unencrypted", + "The party's key it signs with: an OpenSSH private key file, unencrypted, of an Ed25519 key; or a public key file (ssh-ed25519 or ecdsa-sha2-nistp256), signed with through the ssh-agent at SSH_AUTH_SOCK", ), option( "record", diff --git a/src/federation/agent.rs b/src/federation/agent.rs new file mode 100644 index 0000000..a41cf1a --- /dev/null +++ b/src/federation/agent.rs @@ -0,0 +1,45 @@ +//! What a party's client asks of an ssh-agent (draft-ietf-sshm-ssh-agent, as OpenSSH's +//! `ssh-agent` speaks it): a signature by a key it holds, so the key itself needn't be a +//! file, or anywhere but the agent. + +use std::io::{Read, Write}; +use std::os::unix::net::UnixStream; +use std::path::Path; + +use crate::access::sshsig::{Reader, string}; + +const SIGN_REQUEST: u8 = 13; +const SIGN_RESPONSE: u8 = 14; +/// The longest answer read: a signature is far shorter. +const LONGEST: usize = 64 * 1024; + +/// The signature of `data` by the key whose SSH encoding is `key`, from the agent at +/// `socket`: its type and its bytes, each a string, as SSH encodes a signature. +pub(crate) fn sign(socket: &Path, key: &[u8], data: &[u8]) -> Result, String> { + let failed = |error: std::io::Error| format!("the ssh-agent at {}: {error}", socket.display()); + let mut request = vec![SIGN_REQUEST]; + string(&mut request, key); + string(&mut request, data); + request.extend_from_slice(&0u32.to_be_bytes()); + let mut message = Vec::new(); + string(&mut message, &request); + let mut stream = UnixStream::connect(socket).map_err(failed)?; + stream.write_all(&message).map_err(failed)?; + let mut length = [0; 4]; + stream.read_exact(&mut length).map_err(failed)?; + let length = u32::from_be_bytes(length) as usize; + if length > LONGEST { + return Err("the ssh-agent's answer is longer than a signature".to_owned()); + } + let mut answer = vec![0; length]; + stream.read_exact(&mut answer).map_err(failed)?; + let Some((&SIGN_RESPONSE, rest)) = answer.split_first() else { + return Err( + "the ssh-agent signs nothing: it holds no such key, or was told not to".to_owned(), + ); + }; + let mut reader = Reader(rest); + let signature = reader.string()?; + reader.end()?; + Ok(signature.to_vec()) +} diff --git a/src/federation/event.rs b/src/federation/event.rs index 15cee45..864bedb 100644 --- a/src/federation/event.rs +++ b/src/federation/event.rs @@ -21,6 +21,21 @@ pub(crate) fn signed( deps: &[Id], does: (&str, Json), ) -> Vec { + signed_by(party, key, deps, does, |bytes| { + Ok(keys::sign(signer, bytes)) + }) + .expect("a key at hand signs") +} + +/// An event `party` signs, its key spelled `key`, on `deps`, doing `does`: its bytes, as +/// JCS, with the signature `sign` makes of them without `sig`, where it makes one. +pub(crate) fn signed_by( + party: &str, + key: &str, + deps: &[Id], + does: (&str, Json), + sign: impl FnOnce(&[u8]) -> Result, +) -> Result, String> { let mut members = vec![ ("deps".to_owned(), ids(deps)), ("party".to_owned(), Json::Str(party.to_owned())), @@ -28,11 +43,8 @@ pub(crate) fn signed( (does.0.to_owned(), does.1), ]; let unsigned = Json::object(members.clone()).expect("names once each"); - members.push(( - "sig".to_owned(), - Json::Str(keys::sign(signer, &unsigned.bytes())), - )); - Json::object(members).expect("names once each").bytes() + members.push(("sig".to_owned(), Json::Str(sign(&unsigned.bytes())?))); + Ok(Json::object(members).expect("names once each").bytes()) } /// What writing `value` at `path` does. diff --git a/src/federation/keys.rs b/src/federation/keys.rs index ee5f01e..a795db7 100644 --- a/src/federation/keys.rs +++ b/src/federation/keys.rs @@ -13,6 +13,8 @@ //! //! So nobody but its signer makes another event of what a party signed. +use std::path::Path; + use base64::{Engine, engine::general_purpose::STANDARD as BASE64}; use ed25519_dalek::{SigningKey, VerifyingKey}; use p256::ecdsa::signature::Verifier; @@ -193,6 +195,38 @@ pub(crate) fn sign(key: &SigningKey, message: &[u8]) -> String { BASE64.encode(blob) } +/// `message` signed with `key` by the ssh-agent at `socket`, as the federation spells a +/// signature: what `ssh-keygen -Y sign -n continuum-federation` makes through the agent, +/// unarmored, an ECDSA signature's `s` made low. +pub(crate) fn sign_through(socket: &Path, key: &Key, message: &[u8]) -> Result { + let answer = super::agent::sign(socket, &key.blob(), &signed(message))?; + from_agent(key, &answer, message) +} + +/// The federation's signature of `message` by `key` from `answer`, the signature the agent +/// made of what SSHSIG signs, as SSH encodes one. +fn from_agent(key: &Key, answer: &[u8], message: &[u8]) -> Result { + let mut reader = Reader(answer); + if reader.string()? != key.kind().as_bytes() { + return Err(format!("the agent's signature isn't an {} one", key.kind())); + } + let signature = reader.string()?; + reader.end()?; + let signature = match key { + Key::Ed25519(_) => signature.to_vec(), + Key::P256(_) => mpints( + &ecdsa_signature(signature) + .ok_or("the agent's signature isn't an ECDSA one")? + .normalize_s(), + ), + }; + let sig = BASE64.encode(written(key, &signature)); + if !verifies(key, &sig, message) { + return Err("the agent's signature doesn't check".to_owned()); + } + Ok(sig) +} + /// What a signature of `message` is made over: SSHSIG's signed data, hashed with `sha512`. fn signed(message: &[u8]) -> Vec { sshsig::signed_data( @@ -367,4 +401,116 @@ mod tests { string(&mut negative, s); refused(&negative); } + + /// A signature through a running `ssh-agent` checks here and with `ssh-keygen -Y + /// verify`, of an ECDSA key the agent alone holds and of an Ed25519 one; of ECDSA, also + /// one the agent gave with a high `s`. Where OpenSSH isn't installed, nothing is asked. + #[test] + fn signs_through_an_ssh_agent() { + use std::process::{Command, Stdio}; + let dir = std::env::temp_dir().join(format!("continuum-agent-{}", std::process::id())); + std::fs::create_dir_all(&dir).expect("a directory"); + let socket = dir.join("agent"); + let agent = match Command::new("ssh-agent") + .arg("-D") + .arg("-a") + .arg(&socket) + .stdout(Stdio::null()) + .spawn() + { + Ok(agent) => agent, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => { + eprintln!("no ssh-agent: skipped"); + return; + } + Err(error) => panic!("ssh-agent: {error}"), + }; + struct Stop(std::process::Child, std::path::PathBuf); + impl Drop for Stop { + fn drop(&mut self) { + let _ = self.0.kill(); + let _ = self.0.wait(); + let _ = std::fs::remove_dir_all(&self.1); + } + } + let _stop = Stop(agent, dir.clone()); + for _ in 0..100 { + if socket.exists() { + break; + } + std::thread::sleep(std::time::Duration::from_millis(50)); + } + let run = |command: &mut Command| { + let out = command + .env("SSH_AUTH_SOCK", &socket) + .output() + .expect("OpenSSH"); + assert!(out.status.success(), "{command:?}: {out:?}"); + }; + for kind in [["-t", "ecdsa", "-b", "256"].as_slice(), &["-t", "ed25519"]] { + let file = dir.join(kind[1]); + run(Command::new("ssh-keygen") + .args(kind) + .args(["-q", "-N", "", "-C", "", "-f"]) + .arg(&file)); + run(Command::new("ssh-add").arg("-q").arg(&file)); + std::fs::remove_file(&file).expect("the private key's file"); + let pub_line = std::fs::read_to_string(file.with_extension("pub")).expect("a .pub"); + let key = Key::parse(&pub_line).expect("a key"); + let allowed = dir.join("allowed"); + std::fs::write(&allowed, format!("party {}\n", key.line())).expect("written"); + let checked = |sig: &str, message: &[u8]| { + assert!(verifies(&key, sig, message)); + let blob = BASE64.decode(sig).expect("base64"); + let mut armored = "-----BEGIN SSH SIGNATURE-----\n".to_owned(); + for line in BASE64.encode(&blob).as_bytes().chunks(70) { + armored.push_str(std::str::from_utf8(line).expect("ASCII")); + armored.push('\n'); + } + armored.push_str("-----END SSH SIGNATURE-----\n"); + let file = dir.join("sig"); + std::fs::write(&file, armored).expect("written"); + let mut verify = Command::new("ssh-keygen") + .args(["-Y", "verify", "-I", "party", "-n", NAMESPACE, "-f"]) + .arg(&allowed) + .arg("-s") + .arg(&file) + .stdin(Stdio::piped()) + .stdout(Stdio::null()) + .spawn() + .expect("ssh-keygen"); + use std::io::Write; + verify + .stdin + .take() + .expect("its input") + .write_all(message) + .expect("written"); + assert!(verify.wait().expect("ssh-keygen").success()); + }; + let message = format!("an event, by {}", kind[1]); + checked( + &sign_through(&socket, &key, message.as_bytes()).expect("signed"), + message.as_bytes(), + ); + if let Key::P256(_) = key { + let data = signed(message.as_bytes()); + let high = (0..64) + .map(|_| { + super::super::agent::sign(&socket, &key.blob(), &data).expect("signed") + }) + .find(|answer| { + let mut reader = Reader(answer); + let _ = reader.string(); + let parsed = ecdsa_signature(reader.string().unwrap()).unwrap(); + parsed.normalize_s() != parsed + }) + .expect("a high `s` among 64 signatures"); + checked( + &from_agent(&key, &high, message.as_bytes()).expect("made low"), + message.as_bytes(), + ); + } + } + } } diff --git a/src/federation/mod.rs b/src/federation/mod.rs index f7853e7..bb14be3 100644 --- a/src/federation/mod.rs +++ b/src/federation/mod.rs @@ -7,6 +7,7 @@ // Built stage by stage: parts of it are used by nothing yet, or by tests alone. #![allow(dead_code)] +pub(crate) mod agent; #[cfg(test)] mod attacks; pub(crate) mod client; diff --git a/src/federation/party.rs b/src/federation/party.rs index 21e1fb7..4ba51ed 100644 --- a/src/federation/party.rs +++ b/src/federation/party.rs @@ -1,9 +1,10 @@ //! `continuum-party`: a party's client of a federation (`docs/federation.md`). It signs its -//! party's events with one of its keys (an OpenSSH private key file, `--key`), puts them -//! through a node's API (`--node`, its user and password in the URL, or `--token`), and -//! keeps its party's record (`--record`, `client::Record`), by which it votes, written -//! before a vote is sent. Its options may be set in configuration files as the node's are -//! (`--config`, `config::PARTY_OPTIONS`): the same format, imports and all. +//! party's events with one of its keys (`--key`: an OpenSSH private key file, or a public +//! key the ssh-agent at `SSH_AUTH_SOCK` holds), puts them through a node's API (`--node`, +//! its user and password in the URL, or `--token`), and keeps its party's record +//! (`--record`, `client::Record`), by which it votes, written before a vote is sent. Its +//! options may be set in configuration files as the node's are (`--config`, +//! `config::PARTY_OPTIONS`): the same format, imports and all. //! //! * `init PARTY`: begins a record of `PARTY`, on the version current now; with `--root //! FILE`, from the file the store's swarm starts from, for a party that never voted in @@ -42,7 +43,7 @@ use super::client::{self, Record}; use super::event::{self, Does, Event, Signed}; use super::fold::Federation; use super::jcs::Json; -use super::keys::Key; +use super::keys::{self, Key}; use super::store::Id; use super::store::memory::Store; use super::version::Version; @@ -342,25 +343,51 @@ fn strings(matches: &ArgMatches, name: &str) -> Vec { .collect() } -fn signing_key(options: &Options) -> Result { +/// The key `--key` names: a private key file's, or a public key's, held by the ssh-agent. +fn signing_key(options: &Options) -> Result { let file = options .key .as_ref() .context("--key names the party's key")?; let text = std::fs::read_to_string(file).with_context(|| format!("Reading {file}"))?; - client::signing_key(&text).map_err(|why| anyhow!("{file}: {why}")) + if let Ok(key) = Key::parse(&text) { + let socket = std::env::var_os("SSH_AUTH_SOCK").with_context(|| { + format!( + "{file} is a public key, signed with through an ssh-agent: SSH_AUTH_SOCK names none" + ) + })?; + return Ok(Signing::Agent(key, PathBuf::from(socket))); + } + let key = client::signing_key(&text).map_err(|why| anyhow!("{file}: {why}"))?; + Ok(Signing::File(key)) +} + +/// What signs: a key at hand, or a key the ssh-agent at a socket holds. +enum Signing { + File(SigningKey), + Agent(Key, PathBuf), } /// Who signs: the party, with one of its keys. struct Signer { - key: SigningKey, + key: Signing, party: String, } impl Signer { - fn sign(&self, deps: &[Id], does: (&str, Json)) -> Vec { - let line = PublicKey(self.key.verifying_key().to_bytes()).line(); - event::signed(&self.key, &self.party, &line, deps, does) + fn sign(&self, deps: &[Id], does: (&str, Json)) -> Result> { + match &self.key { + Signing::File(key) => { + let line = PublicKey(key.verifying_key().to_bytes()).line(); + Ok(event::signed(key, &self.party, &line, deps, does)) + } + Signing::Agent(key, socket) => { + event::signed_by(&self.party, &key.line(), deps, does, |bytes| { + keys::sign_through(socket, key, bytes) + }) + .map_err(|why| anyhow!(why)) + } + } } } @@ -373,7 +400,7 @@ async fn sign( does: (&str, Json), ) -> Result<()> { let (_, heads) = node.summary().await?; - let event = signer.sign(&heads, does); + let event = signer.sign(&heads, does)?; record.signed(&event); record.save(path).map_err(|why| anyhow!(why))?; node.put(&event).await @@ -438,7 +465,7 @@ async fn vote( .map_err(|why| anyhow!(why))?; // On the events proposing it: above the heads it names for a checkpoint wherever they // are, so a version event may be written on it. - let cast = signer.sign(&proposals, event::vote(current.hash, proposal, yes)); + let cast = signer.sign(&proposals, event::vote(current.hash, proposal, yes))?; record.cast(¤t, &cast, kept); record.save(path).map_err(|why| anyhow!(why))?; node.put(&cast).await -- cgit v1.3.1 From 45cdc3c64bedb6eefe4a3645afbde82e62f8112a Mon Sep 17 00:00:00 2001 From: slopulus Date: Tue, 17 Nov 2026 20:01:42 +0100 Subject: federation.md, federation-tests.md: ecdsa-sha2-nistp256 keys, their signature low-S A key is `ssh-ed25519` or `ecdsa-sha2-nistp256`, spelled alike; an ECDSA signature is over SHA-256, its `s` low and `r` and `s` SSH's shortest mpints, so that it is spelled one way. The vectors and the agent test, among the harness's. --- docs/federation-tests.md | 7 +++++-- docs/federation.md | 38 +++++++++++++++++++++++--------------- 2 files changed, 28 insertions(+), 17 deletions(-) diff --git a/docs/federation-tests.md b/docs/federation-tests.md index d7e4a43..6754060 100644 --- a/docs/federation-tests.md +++ b/docs/federation-tests.md @@ -29,7 +29,9 @@ built to: a stage is done when its tests are. ## The harness * **Keys.** Ed25519 keys made from seeds, signing as `ssh-keygen -Y sign` does; a vector - checks one signature against `ssh-keygen` itself. + checks one signature against `ssh-keygen` itself. An ECDSA key `ssh-keygen` made, and + events it signed with it, are vectors; a test signs through a running `ssh-agent`, and + `ssh-keygen -Y verify` checks what it signed, where OpenSSH is installed. * **Events.** A builder for every kind (writes, key sets, node lists, proposals, votes, version events, checkpoints, roots and forks), each from a party, a key and its dependencies, encoded and signed as the design says; and for what is none: bytes that @@ -115,7 +117,8 @@ Vectors for: an event and its ID; an event whose value holds names JCS sorts by UTF-16 units otherwise than by their bytes (one from U+E000 to U+FFFF beside one beyond U+FFFF); events at federation 1's sizes and just past them; a signature, a version and its hash, a checkpoint and its ID, the genesis change of a federation's root and of a -fork's, and a snapshot after a checkpoint. A vector that changes is a change of the +fork's, a snapshot after a checkpoint, and a version naming an ECDSA key, with a write +and a key set `ssh-keygen` signed with it. A vector that changes is a change of the federation, which takes its next number ([`federation.md`](federation.md), Changing the federation). diff --git a/docs/federation.md b/docs/federation.md index 7b453af..f30cdd4 100644 --- a/docs/federation.md +++ b/docs/federation.md @@ -46,7 +46,8 @@ What an adversary can do: * delay or drop messages between any nodes, short of forever between honest ones; * steal another party's key. -What it can't: forge an Ed25519 signature, or find two byte strings with one SHA-256. +What it can't: forge an Ed25519 or ECDSA signature, or find two byte strings with one +SHA-256. Out of scope: keeping anything from being read (every party reads all of it), hiding who talks to whom, and a party's own machine taken over whole (then the adversary is that @@ -125,11 +126,12 @@ Spread out: * **`deps`**: the IDs of its dependencies, as 64 lower-case hex digits, one at least, ascending, none twice; a client gives the heads it read. -* **`party`** and **`key`**: the party that signs it, and the key it signs with: - `ssh-ed25519`, one space, and the key's base64, padded and canonical, with no comment, - its 32 bytes an Ed25519 public key. Keys in a version and a key set are spelled so - too, and node IDs as continuum spells them: `continuum:` and the 64 lower-case hex - digits of the node's Ed25519 public key. +* **`party`** and **`key`**: the party that signs it, and the key it signs with: its + type, one space, and the base64 of its SSH encoding, padded and canonical, with no + comment. Two types: `ssh-ed25519`, its 32 bytes an Ed25519 public key, and + `ecdsa-sha2-nistp256`, its point on NIST P-256 uncompressed. Keys in a version and a + key set are spelled so too, and node IDs as continuum spells them: `continuum:` and + the 64 lower-case hex digits of the node's Ed25519 public key. * **What it does**, one field of: * `write`, `{"path": "", "value": }`: a value at a place (The policy); * `keys`, `["", …]`: the party's key set (Keys); @@ -141,9 +143,14 @@ Spread out: * **`sig`**: an SSH signature (`ssh-keygen -Y sign`, namespace `continuum-federation`) over the event's bytes without `sig`: the SSHSIG blob of version 1, hashed with `sha512`, its key the event's `key`, its reserved field empty, as `ssh-keygen` writes - it, in base64, padded and canonical, unarmored. It is checked as continuum checks a - user's signature, strictly *(checked: `access::sshsig::verify_blob`)*, which takes - `sha256` too, and any reserved field: the federation asks `sha512` and an empty one. + it, in base64, padded and canonical, unarmored. An Ed25519 signature is checked as + continuum checks a user's signature, strictly *(checked: + `access::sshsig::verify_blob`)*, which takes `sha256` too, and any reserved field: the + federation asks `sha512` and an empty one. An ECDSA signature is over the SHA-256 of + what it signs, as SSH signs with such a key. Its `s` and the curve's order less `s` + both check, so the federation takes the low one alone, at most half the order, and `r` + and `s` each as SSH's shortest mpint *(checked: `federation::keys`)*. `ssh-keygen` + makes either; a party's client makes `s` low. Three things no party signs, as their bytes need no signer, each without `party`, `key` and `sig`: a version event (Changing the policy), and a federation's root and a fork's, @@ -193,12 +200,13 @@ current at its heads, Forks). Spread out: * **The federation** it follows, and its **number**, one more than that of the version it changes. * **The parties and their keys** (`keys`): one party at least, each by name, as - continuum's user names, 1 to 64 of `A-Z a-z 0-9 . _ @ -`, with one `ssh-ed25519` key - or more, none twice in the version. With them the party signs its votes and proposals - on this version, its key set and its node list (Keys, Nodes). Its `since` is the - number of the version that named them anew: this one's where it does (a party new in - it, keys the parties replace, or the same keys named anew), else the `since` the - version it changes gives the party, whose keys it then names unchanged. + continuum's user names, 1 to 64 of `A-Z a-z 0-9 . _ @ -`, with one key or more + (`ssh-ed25519` or `ecdsa-sha2-nistp256`, Events), none twice in the version. With them + the party signs its votes and proposals on this version, its key set and its node list + (Keys, Nodes). Its `since` is the number of the version that named them anew: this + one's where it does (a party new in it, keys the parties replace, or the same keys + named anew), else the `since` the version it changes gives the party, whose keys it + then names unchanged. * **The node lists** (`nodes`): every party's, a list of node IDs, none twice, with its `since` as keys have one. The version that lets a party in names its list anew, empty where it gives it no nodes, so that a list it wrote before it was taken out counts no -- cgit v1.3.1 From 2b9bb568603ee10d4f1f3106a687a8642c162df7 Mon Sep 17 00:00:00 2001 From: slopulus Date: Tue, 17 Nov 2026 20:01:42 +0100 Subject: guides: keys in an ssh-agent A party's key is `ssh-ed25519` or `ecdsa-sha2-nistp256`; the client signs with a private key file or through an ssh-agent holding the key, given its public key. Code of its own signing with ECDSA makes `s` low, which `ssh-keygen` does only half the time. --- docs/guides/federation/building-on-the-api.md | 8 +++++--- docs/guides/federation/getting-started.md | 6 ++++-- docs/guides/federation/keys.md | 22 +++++++++++++++++++++- 3 files changed, 30 insertions(+), 6 deletions(-) diff --git a/docs/guides/federation/building-on-the-api.md b/docs/guides/federation/building-on-the-api.md index 9f144be..4f37b91 100644 --- a/docs/guides/federation/building-on-the-api.md +++ b/docs/guides/federation/building-on-the-api.md @@ -41,11 +41,13 @@ sorts them: * `deps`: the heads it read (`heads` in `GET /events`), each as 64 lower-case hex digits, ascending, one at least. -* `key`: the key it signs with, `ssh-ed25519`, a space, the base64 of its blob, no - comment; one of the party's keys. +* `key`: the key it signs with, its type (`ssh-ed25519` or `ecdsa-sha2-nistp256`), a + space, the base64 of its blob, no comment; one of the party's keys. * `sig`: an SSH signature (`ssh-keygen -Y sign`, namespace `continuum-federation`, hashed with `sha512`) over the JCS bytes of the object without `sig`: the SSHSIG blob, its - reserved field empty, in base64, unarmored. + reserved field empty, in base64, unarmored. Of an ECDSA key, its `s` low, at most half + the curve's order: `ssh-keygen` makes a high one half the time, which no node takes; + sign again, or put the order less `s` in its place. * The value is any JSON with integers only, from −2⁵³ to 2⁵³; the event up to 256 KiB. Put its bytes as they are: diff --git a/docs/guides/federation/getting-started.md b/docs/guides/federation/getting-started.md index ce2b614..3570ee3 100644 --- a/docs/guides/federation/getting-started.md +++ b/docs/guides/federation/getting-started.md @@ -17,8 +17,10 @@ That builds the node, `continuum`, and the party's client, `continuum-party`, in ## A key for each party -The version names each party's keys, and the party signs with them. The client reads an -OpenSSH Ed25519 key without a passphrase: +The version names each party's keys, and the party signs with them. A key is +`ssh-ed25519` or `ecdsa-sha2-nistp256`. The client reads an OpenSSH private key file +without a passphrase, of an Ed25519 key, or signs through an ssh-agent holding the key +([`keys.md`](keys.md), Keys in an ssh-agent): ```sh ssh-keygen -t ed25519 -N '' -f tv.key diff --git a/docs/guides/federation/keys.md b/docs/guides/federation/keys.md index 48018a3..a84ed5a 100644 --- a/docs/guides/federation/keys.md +++ b/docs/guides/federation/keys.md @@ -25,12 +25,32 @@ continuum-party --node http://tv:secret@localhost:3000 --key laptop.key \ Each key goes as one argument, an `authorized_keys` line; its comment is left out. A set holds up to 16 keys. A node voting by itself keeps a key its version names on that -node (`--store-vote-key`): one stolen there votes for the party. +node (`--store-vote-key`), an Ed25519 key in a file: one stolen there votes for the +party. A set counts where it is written under a version numbered at least the `since` the current version gives the party's keys: once a version names a party's keys anew, no set written before counts, and the party writes its set again. +## Keys in an ssh-agent + +A key no file holds, in a security key, a phone or a Secure Enclave, signs through an +ssh-agent. Give the client its public key, a `.pub` file, as `--key`: it asks the agent +at `SSH_AUTH_SOCK` to sign, and writes the signature as `ssh-keygen -Y sign` does +through that agent. Such a key is `ecdsa-sha2-nistp256` or `ssh-ed25519`. + +```sh +ssh-add -L # ecdsa-sha2-nistp256 AAAA… tv@phone +ssh-add -L | grep tv@phone > phone.pub +cut -d' ' -f1,2 phone.pub # the key as a version or a set names it +continuum-party --node http://tv:secret@localhost:3000 --key phone.pub \ + --record tv.record write home/tv/motd '"from the phone"' +``` + +Of an ECDSA signature, `s` and the curve's order less `s` both check. The federation +takes the low one alone, so that nobody makes another event of what the party signed; +the client makes `s` low, whichever the agent gives. + ## Changing the keys of a set A write counts only while the key that signed it is among the party's keys: what a key -- cgit v1.3.1 From fcd93f789b254d3e8a8f993d7fbc786f907abbc5 Mon Sep 17 00:00:00 2001 From: tv Date: Wed, 18 Nov 2026 11:12:52 +0000 Subject: Cargo.toml: p256 with the federation alone A party's ECDSA keys are the federation's: without the `federation` feature, p256 isn't built. --- Cargo.toml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 4faaaed..123d91c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -21,7 +21,7 @@ tokio-console = ["dep:console-subscriber"] dashboard = [] # The federation (`docs/federation.md`) and the store it is built on (`docs/store.md`), # stage by stage: without it, continuum builds and behaves as it does. -federation = ["dep:reqwest", "dep:rustls"] +federation = ["dep:reqwest", "dep:rustls", "dep:p256"] # The Mycelium transport (`--mycelium-enable`): through a Mycelium daemon's API, one it # supervises or one running elsewhere. mycelium = ["dep:reqwest", "dep:rustls", "dep:libc"] @@ -70,7 +70,7 @@ getrandom = "0.4" jiff = { version = "0.2", default-features = false, features = ["std"] } libc = { version = "0.2", optional = true } # A party's ECDSA keys on NIST P-256 (`ecdsa-sha2-nistp256`), beside its Ed25519 ones. -p256 = { version = "0.14", default-features = false, features = ["ecdsa"] } +p256 = { version = "0.14", optional = true, default-features = false, features = ["ecdsa"] } password-hash = "0.6" # Its TLS (only for a Mycelium daemon elsewhere, over https) is rustls with ring, which # libp2p's QUIC uses too, rather than reqwest's default aws-lc (a C library, cmake). -- cgit v1.3.1 From cb9c78d0b76c401435aea781fc36845983c8f1f3 Mon Sep 17 00:00:00 2001 From: tv Date: Wed, 18 Nov 2026 11:13:12 +0000 Subject: federation.md, guides: a change taking what was refused keeps the number A change that only has the federation take what it refused, reading nothing it took otherwise, as ecdsa-sha2-nistp256 keys, keeps the federation's number: it is rolled out to every node first, and used after. A node that doesn't take it refuses what uses it, a version naming such a key among them. --- docs/federation.md | 7 +++++++ docs/guides/federation/upgrades.md | 7 +++++++ 2 files changed, 14 insertions(+) diff --git a/docs/federation.md b/docs/federation.md index f30cdd4..9659dbb 100644 --- a/docs/federation.md +++ b/docs/federation.md @@ -794,6 +794,13 @@ moves to it by a version of its policy that names it (`"federation": 2`), which parties pass once their nodes run a continuum that knows it. A node that doesn't know the federation, or a version, its swarm has stops taking events and says so. +A change that only has the federation take what it refused, and reads nothing it took +otherwise, keeps the number: the keys of type `ecdsa-sha2-nistp256` taken beside Ed25519 +ones are such a change. It is rolled out first and used after: every node runs a +continuum that takes it before any party uses it. A node that doesn't refuses what uses +it, a version naming such a key among them, and reads otherwise than the others until +it does. + ## The registry on it The krebs registry today: users, their hosts, the hosts' names, addresses and keys, as diff --git a/docs/guides/federation/upgrades.md b/docs/guides/federation/upgrades.md index 945088d..95dab12 100644 --- a/docs/guides/federation/upgrades.md +++ b/docs/guides/federation/upgrades.md @@ -32,3 +32,10 @@ naming another is taken as a proposal, and a party's client backs none. A change to any of that is a federation of its own, with the next number, and its own design. A swarm moves to it by a version naming it, which the parties pass once their nodes run a continuum that knows it. + +A change that only has the federation take what it refused, and reads nothing it took +otherwise, keeps the number: `ecdsa-sha2-nistp256` keys beside Ed25519 ones. Roll it out +first, then use it: every party's operators upgrade their nodes, and only then does a +party name such a key in a version or a key set, or sign with one. A node not upgraded +refuses what uses it and reads otherwise than the others: a version naming such a key is +none to it, and it stays on the version before. -- cgit v1.3.1 From e95909e1c0bf6e0b87b1dd8bafd44c6110656c0d Mon Sep 17 00:00:00 2001 From: tv Date: Wed, 18 Nov 2026 11:14:05 +0000 Subject: attacks: row 62 with an ECDSA signature spelled otherwise Row 62 names an ECDSA signature's twins, `s` high (the order less `s`) and `r` or `s` with zeros more in front, each none. Its test offers the ECDSA vector's write with each (`keys::respelled`) to a store whose root names that key, and has it take the write as it was signed. --- docs/federation.md | 2 +- src/federation/attacks.rs | 17 +++++++++++++++++ src/federation/keys.rs | 17 +++++++++++++++++ 3 files changed, 35 insertions(+), 1 deletion(-) diff --git a/docs/federation.md b/docs/federation.md index 9659dbb..5faa478 100644 --- a/docs/federation.md +++ b/docs/federation.md @@ -699,7 +699,7 @@ crafted events. *Sim*: a simulation. *Bench*: measured, not judged. | 59 | Two checkpoints proposed at once, by nodes voting by themselves | The votes split; nays from the nodes backing one make the other dead, and its backers are free | sim | | 60 | Two nodes of one party, each voting by itself | They can vote twice, answered as any party voting twice: a party has one node vote by itself | — | | 61 | A key a version names, kept on a node that votes by itself, stolen with it | As 23: it counts while that version is current | unit | -| 62 | A party's event spelled anew by another: its `sig` or `key` encoded otherwise, its signature's S not canonical, its blob naming another key | None: `key` and `sig` read back to themselves, the signature is checked strictly, and the blob's key is `key` | unit | +| 62 | A party's event spelled anew by another: its `sig` or `key` encoded otherwise, its signature's S not canonical (of ECDSA, the order less `s`, or `r` or `s` with zeros more in front), its blob naming another key | None: `key` and `sig` read back to themselves, the signature is checked strictly (of ECDSA, `s` low and `r` and `s` each its shortest), and the blob's key is `key` | unit | | 63 | A node joining from the root is shown a chain old keys grew, beside the one the others took | It takes neither, and reports; once a checkpoint passed, it joins from a pinned one, where that chain is refused | unit | | 64 | Checkpoint heads before the current checkpoint, or at which it isn't current, or one in another's history | No version: a version event naming it is refused | unit | | 65 | After a checkpoint, a party that backed a second proposal once its first was dead, the nays that freed it withheld by those who cast them | Not named: its client keeps those nays with its `true` | unit | diff --git a/src/federation/attacks.rs b/src/federation/attacks.rs index d153f22..0d90461 100644 --- a/src/federation/attacks.rs +++ b/src/federation/attacks.rs @@ -1102,6 +1102,7 @@ fn federation_attack_61() { #[test] fn federation_attack_62() { + use super::vectors::{ECDSA_KEY, ECDSA_WRITE}; use base64::{Engine, engine::general_purpose::STANDARD as BASE64}; let mut fed = three(); let root = fed.root(); @@ -1150,6 +1151,22 @@ fn federation_attack_62() { ), ); assert_eq!(fed.refused(commented), Refusal::None); + // Signed with an ECDSA key (the vectors'), its signature spelled otherwise: `s` high, + // or `r` longer. The write as it was signed is taken. + let mut first = Spec::first(&[&tv, &lass()], &[]); + first.parties[0].keys = vec![ECDSA_KEY.to_owned()]; + let mut fed = Fed { + store: Store::new(first.root(), Vec::new()).expect("a root"), + first, + }; + let event = super::jcs::read(ECDSA_WRITE.as_bytes()).expect("JCS"); + let sig = event.get("sig").and_then(Json::as_str).expect("a sig"); + let key = super::keys::key(ECDSA_KEY).expect("a key"); + for other in super::keys::respelled(&key, sig) { + let respelled = ECDSA_WRITE.replace(sig, &other).into_bytes(); + assert_eq!(fed.refused(respelled), Refusal::None); + } + fed.take(ECDSA_WRITE.as_bytes().to_vec()); } #[test] diff --git a/src/federation/keys.rs b/src/federation/keys.rs index a795db7..fa13ec4 100644 --- a/src/federation/keys.rs +++ b/src/federation/keys.rs @@ -254,6 +254,23 @@ fn written(key: &Key, signature: &[u8]) -> Vec { blob } +/// Of `sig`, an ECDSA signature by `key` as the federation spells it, two others of the +/// same key and message that check as SSH checks them: `s` high, the order less `s`; and +/// `r` with a zero byte more in front, the same number to SSH. +#[cfg(test)] +pub(crate) fn respelled(key: &Key, sig: &str) -> [String; 2] { + let blob = BASE64.decode(sig).expect("base64"); + let rs = &blob[written(key, &[]).len()..]; + let (r, s) = ecdsa_signature(rs).expect("r and s").split_scalars(); + let high = p256::ecdsa::Signature::from_scalars(r, -s).expect("a signature"); + let mut reader = Reader(rs); + let (r, s) = (reader.string().expect("r"), reader.string().expect("s")); + let mut longer = Vec::new(); + string(&mut longer, &[&[0], r].concat()); + string(&mut longer, s); + [mpints(&high), longer].map(|numbers| BASE64.encode(written(key, &numbers))) +} + #[cfg(test)] mod tests { use super::*; -- cgit v1.3.1 From b6a2649f54741e88a886fe8f64e916415e8a4b72 Mon Sep 17 00:00:00 2001 From: tv Date: Wed, 18 Nov 2026 11:14:21 +0000 Subject: guides: which keys an ssh-agent signs a party's events with A smartcard's or a security key's PIV key, through PKCS#11, or a key in a Secure Enclave or a phone, each ecdsa-sha2-nistp256 or ssh-ed25519; a security key's FIDO key (`-t ecdsa-sk`, `-t ed25519-sk`) is no party's key. --- docs/guides/federation/keys.md | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/docs/guides/federation/keys.md b/docs/guides/federation/keys.md index a84ed5a..6448f9e 100644 --- a/docs/guides/federation/keys.md +++ b/docs/guides/federation/keys.md @@ -34,10 +34,16 @@ written before counts, and the party writes its set again. ## Keys in an ssh-agent -A key no file holds, in a security key, a phone or a Secure Enclave, signs through an -ssh-agent. Give the client its public key, a `.pub` file, as `--key`: it asks the agent -at `SSH_AUTH_SOCK` to sign, and writes the signature as `ssh-keygen -Y sign` does -through that agent. Such a key is `ecdsa-sha2-nistp256` or `ssh-ed25519`. +A key no file holds signs through an ssh-agent holding it: a smartcard's or a security +key's PIV key, which the agent reaches through PKCS#11 (`ssh-add -s`), or a key in a +Secure Enclave or a phone, held by an agent there. Such a key is `ecdsa-sha2-nistp256` or +`ssh-ed25519`. A security key's FIDO key (`ssh-keygen -t ecdsa-sk` or `-t ed25519-sk`, +its type ending in `@openssh.com`) is neither: it signs otherwise than the federation +takes, and is no party's key. + +Give the client its public key, a `.pub` file, as `--key`: it asks the agent at +`SSH_AUTH_SOCK` to sign, and writes the signature as `ssh-keygen -Y sign` does through +that agent. ```sh ssh-add -L # ecdsa-sha2-nistp256 AAAA… tv@phone -- cgit v1.3.1 From ecfed5d7e344c617f582d1d91c7395a210a70192 Mon Sep 17 00:00:00 2001 From: tv Date: Wed, 18 Nov 2026 11:14:56 +0000 Subject: files: a test's scratch directory goes when the test ends `scratch_dir` gives a guard (`Scratch`) that removes the directory with all it holds when dropped, the test passing or failing. Each test keeps it for as long as it uses the directory; the dashboard's browser check writes its page into one. --- src/api/dashboard/mod.rs | 5 ++--- src/federation/held.rs | 3 ++- src/files.rs | 29 ++++++++++++++++++++++++----- src/identity.rs | 6 ++++-- src/swarm/auth.rs | 3 ++- 5 files changed, 34 insertions(+), 12 deletions(-) diff --git a/src/api/dashboard/mod.rs b/src/api/dashboard/mod.rs index 15b8cf9..c0de169 100644 --- a/src/api/dashboard/mod.rs +++ b/src/api/dashboard/mod.rs @@ -913,8 +913,8 @@ mod tests { #[test] #[ignore] fn dashboard_in_a_browser() { - let file = - std::env::temp_dir().join(format!("continuum-dashboard-{}.html", std::process::id())); + let dir = crate::files::scratch_dir("dashboard"); + let file = dir.join("page.html"); std::fs::write(&file, &page().1).expect("page written"); let check = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src/api/dashboard/check.js"); @@ -928,7 +928,6 @@ mod tests { PATH, with Playwright's library and its Chromium (check.nix)" ) }); - let _ = std::fs::remove_file(&file); assert!(status.success(), "the browser checks failed"); } diff --git a/src/federation/held.rs b/src/federation/held.rs index 3ca74a9..abb3d30 100644 --- a/src/federation/held.rs +++ b/src/federation/held.rs @@ -1795,7 +1795,8 @@ mod tests { for event in [&write, &beside, &proposal, &yes] { put(&mut doc, event); } - let record = crate::files::scratch_dir("held-votes-above").join("makefu.json"); + let dir = crate::files::scratch_dir("held-votes-above"); + let record = dir.join("makefu.json"); let version = Version::read(&first.json()).unwrap(); let mut begun = Record::begin(Id::of(&root), "makefu", &version); begun.began = Id::of(b"before the federation").to_string(); diff --git a/src/files.rs b/src/files.rs index 3e27066..320543f 100644 --- a/src/files.rs +++ b/src/files.rs @@ -261,13 +261,34 @@ fn with_suffix(path: &Path, suffix: &str) -> PathBuf { } /// An empty directory for the test `name`: `continuum--` in the -/// temporary directory, emptied first. +/// temporary directory, emptied first, and removed with all it holds once dropped, the +/// test passing or failing. #[cfg(test)] -pub(crate) fn scratch_dir(name: &str) -> PathBuf { +pub(crate) fn scratch_dir(name: &str) -> Scratch { let dir = std::env::temp_dir().join(format!("continuum-{name}-{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(&dir).unwrap(); - dir + Scratch(dir) +} + +/// A test's directory (`scratch_dir`), removed when dropped. +#[cfg(test)] +pub(crate) struct Scratch(PathBuf); + +#[cfg(test)] +impl std::ops::Deref for Scratch { + type Target = Path; + + fn deref(&self) -> &Path { + &self.0 + } +} + +#[cfg(test)] +impl Drop for Scratch { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } } #[cfg(test)] @@ -302,7 +323,5 @@ mod tests { ); assert_eq!(files.counts()[0].1.appended_bytes, 1); assert_eq!(files.counts()[1].1.reads, 0); - - std::fs::remove_dir_all(&dir).unwrap(); } } diff --git a/src/identity.rs b/src/identity.rs index 1012d23..23c4f0f 100644 --- a/src/identity.rs +++ b/src/identity.rs @@ -118,7 +118,8 @@ mod tests { #[test] fn created_only_when_asked_and_then_kept() { - let path = scratch_dir("identity-create").join("node.key"); + let dir = scratch_dir("identity-create"); + let path = dir.join("node.key"); assert!(NodeKey::load(&path, false).is_err()); assert!(!path.exists()); @@ -138,7 +139,8 @@ mod tests { #[test] fn a_key_of_the_wrong_size_is_refused() { - let path = scratch_dir("identity-size").join("node.key"); + let dir = scratch_dir("identity-size"); + let path = dir.join("node.key"); std::fs::write(&path, [7u8; 16]).unwrap(); assert!(NodeKey::load(&path, true).is_err()); } diff --git a/src/swarm/auth.rs b/src/swarm/auth.rs index 98a004c..7ac813b 100644 --- a/src/swarm/auth.rs +++ b/src/swarm/auth.rs @@ -166,7 +166,8 @@ mod tests { /// A swarm key file is made only when asked, then read as any other. #[test] fn swarm_key_created_only_when_asked() { - let path = crate::files::scratch_dir("swarm-key-create").join("swarm.key"); + let dir = crate::files::scratch_dir("swarm-key-create"); + let path = dir.join("swarm.key"); assert!(SwarmKey::from_file(&path, false).is_err()); assert!(!path.exists()); let created = SwarmKey::from_file(&path, true).unwrap(); -- cgit v1.3.1 From 2ac20de00d0535dcb2a0d327f73c0b61fbbe4749 Mon Sep 17 00:00:00 2001 From: tv Date: Wed, 18 Nov 2026 11:15:24 +0000 Subject: keys: signing through an ssh-agent tested wherever tests run The test fails without OpenSSH on the machine testing, rather than passing without asking anything. Its directory is a scratch directory, removed when the test ends, the agent stopped before it. --- docs/federation-tests.md | 2 +- src/federation/keys.rs | 42 +++++++++++++++++++++--------------------- 2 files changed, 22 insertions(+), 22 deletions(-) diff --git a/docs/federation-tests.md b/docs/federation-tests.md index 6754060..ba182ad 100644 --- a/docs/federation-tests.md +++ b/docs/federation-tests.md @@ -31,7 +31,7 @@ built to: a stage is done when its tests are. * **Keys.** Ed25519 keys made from seeds, signing as `ssh-keygen -Y sign` does; a vector checks one signature against `ssh-keygen` itself. An ECDSA key `ssh-keygen` made, and events it signed with it, are vectors; a test signs through a running `ssh-agent`, and - `ssh-keygen -Y verify` checks what it signed, where OpenSSH is installed. + `ssh-keygen -Y verify` checks what it signed: the machine testing needs OpenSSH. * **Events.** A builder for every kind (writes, key sets, node lists, proposals, votes, version events, checkpoints, roots and forks), each from a party, a key and its dependencies, encoded and signed as the design says; and for what is none: bytes that diff --git a/src/federation/keys.rs b/src/federation/keys.rs index fa13ec4..ed47b9b 100644 --- a/src/federation/keys.rs +++ b/src/federation/keys.rs @@ -421,47 +421,47 @@ mod tests { /// A signature through a running `ssh-agent` checks here and with `ssh-keygen -Y /// verify`, of an ECDSA key the agent alone holds and of an Ed25519 one; of ECDSA, also - /// one the agent gave with a high `s`. Where OpenSSH isn't installed, nothing is asked. + /// one the agent gave with a high `s`. The machine testing needs OpenSSH (`ssh-agent`, + /// `ssh-add`, `ssh-keygen`): without it, the test fails. #[test] fn signs_through_an_ssh_agent() { use std::process::{Command, Stdio}; - let dir = std::env::temp_dir().join(format!("continuum-agent-{}", std::process::id())); - std::fs::create_dir_all(&dir).expect("a directory"); + let dir = crate::files::scratch_dir("agent"); let socket = dir.join("agent"); - let agent = match Command::new("ssh-agent") - .arg("-D") - .arg("-a") - .arg(&socket) - .stdout(Stdio::null()) - .spawn() - { - Ok(agent) => agent, - Err(error) if error.kind() == std::io::ErrorKind::NotFound => { - eprintln!("no ssh-agent: skipped"); - return; - } - Err(error) => panic!("ssh-agent: {error}"), - }; - struct Stop(std::process::Child, std::path::PathBuf); + // The agent, stopped when the test ends: dropped before its directory, declared + // after it. + struct Stop(std::process::Child); impl Drop for Stop { fn drop(&mut self) { let _ = self.0.kill(); let _ = self.0.wait(); - let _ = std::fs::remove_dir_all(&self.1); } } - let _stop = Stop(agent, dir.clone()); + let _agent = Stop( + Command::new("ssh-agent") + .arg("-D") + .arg("-a") + .arg(&socket) + .stdout(Stdio::null()) + .spawn() + .expect("ssh-agent, of OpenSSH, which this test needs"), + ); for _ in 0..100 { if socket.exists() { break; } std::thread::sleep(std::time::Duration::from_millis(50)); } + assert!( + socket.exists(), + "ssh-agent made no socket at {}", + socket.display() + ); let run = |command: &mut Command| { let out = command .env("SSH_AUTH_SOCK", &socket) .output() - .expect("OpenSSH"); + .expect("OpenSSH, which this test needs"); assert!(out.status.success(), "{command:?}: {out:?}"); }; for kind in [["-t", "ecdsa", "-b", "256"].as_slice(), &["-t", "ed25519"]] { -- cgit v1.3.1 From ac66571a87cf36e769bb8308568808e3a0c2ce31 Mon Sep 17 00:00:00 2001 From: tv Date: Wed, 18 Nov 2026 11:17:06 +0000 Subject: continuum-party: a key the ssh-agent holds, given itself `--key` gives a public key itself, an `authorized_keys` line, as well as a file of them: of a file of several, the first signs, with a warning naming it, and another is given itself to sign with it. An agent that doesn't hold the key given signs nothing, and the client stops before it records or puts what it would have signed, saying which key it asked for. --- docs/configuration.md | 4 ++ docs/guides/federation/keys.md | 17 +++--- src/config/mod.rs | 4 +- src/federation/keys.rs | 3 +- src/federation/party.rs | 123 +++++++++++++++++++++++++++++++++++------ 5 files changed, 123 insertions(+), 28 deletions(-) diff --git a/docs/configuration.md b/docs/configuration.md index d246082..989f268 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -256,4 +256,8 @@ record = "/home/tv/.config/continuum/tv.record" continuum-party --config tv.toml write home/tv/motd '"hello"' ``` +`key` is an OpenSSH private key file, or a public key an ssh-agent holds: the key itself +(`key = "ecdsa-sha2-nistp256 AAAA…"`), or a file of such lines, whose first signs +([`guides/federation/keys.md`](guides/federation/keys.md), Keys in an ssh-agent). + `node` and `token` are secrets: never logged, however they are given. diff --git a/docs/guides/federation/keys.md b/docs/guides/federation/keys.md index 6448f9e..3dd2834 100644 --- a/docs/guides/federation/keys.md +++ b/docs/guides/federation/keys.md @@ -41,16 +41,19 @@ Secure Enclave or a phone, held by an agent there. Such a key is `ecdsa-sha2-nis its type ending in `@openssh.com`) is neither: it signs otherwise than the federation takes, and is no party's key. -Give the client its public key, a `.pub` file, as `--key`: it asks the agent at -`SSH_AUTH_SOCK` to sign, and writes the signature as `ssh-keygen -Y sign` does through -that agent. +Give the client its public key as `--key`, the key itself (an `authorized_keys` line) or +a file holding it: it asks the agent at `SSH_AUTH_SOCK` to sign, and writes the signature +as `ssh-keygen -Y sign` does through that agent. Of a file holding several keys (all +`ssh-add -L` lists, say), the first signs, and the client warns: give another itself to +sign with it. An agent that doesn't hold the key given signs nothing, and the client stops +before it records or puts what it would have signed. ```sh ssh-add -L # ecdsa-sha2-nistp256 AAAA… tv@phone -ssh-add -L | grep tv@phone > phone.pub -cut -d' ' -f1,2 phone.pub # the key as a version or a set names it -continuum-party --node http://tv:secret@localhost:3000 --key phone.pub \ - --record tv.record write home/tv/motd '"from the phone"' +ssh-add -L | grep tv@phone | cut -d' ' -f1,2 # the key as a version or a set names it +continuum-party --node http://tv:secret@localhost:3000 \ + --key "$(ssh-add -L | grep tv@phone)" --record tv.record \ + write home/tv/motd '"from the phone"' ``` Of an ECDSA signature, `s` and the curve's order less `s` both check. The federation diff --git a/src/config/mod.rs b/src/config/mod.rs index 2ff0a45..f74f431 100644 --- a/src/config/mod.rs +++ b/src/config/mod.rs @@ -750,9 +750,9 @@ pub(crate) const PARTY_OPTIONS: &[OptionSpec] = &[ option( "key", Kind::Text, - "PATH", + "KEY", None, - "The party's key it signs with: an OpenSSH private key file, unencrypted, of an Ed25519 key; or a public key file (ssh-ed25519 or ecdsa-sha2-nistp256), signed with through the ssh-agent at SSH_AUTH_SOCK", + "The party's key it signs with: an OpenSSH private key file, unencrypted, of an Ed25519 key; or a public key (ssh-ed25519 or ecdsa-sha2-nistp256), signed with through the ssh-agent at SSH_AUTH_SOCK: itself, as an authorized_keys line, or a file of such lines, whose first signs", ), option( "record", diff --git a/src/federation/keys.rs b/src/federation/keys.rs index ed47b9b..22940ad 100644 --- a/src/federation/keys.rs +++ b/src/federation/keys.rs @@ -199,7 +199,8 @@ pub(crate) fn sign(key: &SigningKey, message: &[u8]) -> String { /// signature: what `ssh-keygen -Y sign -n continuum-federation` makes through the agent, /// unarmored, an ECDSA signature's `s` made low. pub(crate) fn sign_through(socket: &Path, key: &Key, message: &[u8]) -> Result { - let answer = super::agent::sign(socket, &key.blob(), &signed(message))?; + let answer = super::agent::sign(socket, &key.blob(), &signed(message)) + .map_err(|why| format!("{}: {why}", key.line()))?; from_agent(key, &answer, message) } diff --git a/src/federation/party.rs b/src/federation/party.rs index 4ba51ed..5d18eb8 100644 --- a/src/federation/party.rs +++ b/src/federation/party.rs @@ -1,10 +1,10 @@ //! `continuum-party`: a party's client of a federation (`docs/federation.md`). It signs its //! party's events with one of its keys (`--key`: an OpenSSH private key file, or a public -//! key the ssh-agent at `SSH_AUTH_SOCK` holds), puts them through a node's API (`--node`, -//! its user and password in the URL, or `--token`), and keeps its party's record -//! (`--record`, `client::Record`), by which it votes, written before a vote is sent. Its -//! options may be set in configuration files as the node's are (`--config`, -//! `config::PARTY_OPTIONS`): the same format, imports and all. +//! key the ssh-agent at `SSH_AUTH_SOCK` holds, given itself or in a file), puts them +//! through a node's API (`--node`, its user and password in the URL, or `--token`), and +//! keeps its party's record (`--record`, `client::Record`), by which it votes, written +//! before a vote is sent. Its options may be set in configuration files as the node's are +//! (`--config`, `config::PARTY_OPTIONS`): the same format, imports and all. //! //! * `init PARTY`: begins a record of `PARTY`, on the version current now; with `--root //! FILE`, from the file the store's swarm starts from, for a party that never voted in @@ -343,23 +343,70 @@ fn strings(matches: &ArgMatches, name: &str) -> Vec { .collect() } -/// The key `--key` names: a private key file's, or a public key's, held by the ssh-agent. +/// What `--key` gives: a private key, from an OpenSSH private key file; or a public key, +/// given itself (an `authorized_keys` line), or the first of a file of such lines, with +/// how many more the file holds. +enum Given { + Private(SigningKey), + Public(Key, usize), +} + +/// What `given`, `--key`'s value, gives (`Given`). +fn given_key(given: &str) -> Result { + let itself = match Key::parse(given) { + Ok(key) => return Ok(Given::Public(key, 0)), + Err(why) => why, + }; + let text = match std::fs::read_to_string(given) { + Ok(text) => text, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => { + bail!("{given}: no file, nor a key ({itself})") + } + Err(error) => return Err(error).with_context(|| format!("Reading {given}")), + }; + if text.trim_start().starts_with("-----BEGIN") { + let key = client::signing_key(&text).map_err(|why| anyhow!("{given}: {why}"))?; + return Ok(Given::Private(key)); + } + let mut lines = text + .lines() + .map(str::trim) + .filter(|line| !line.is_empty() && !line.starts_with('#')); + let first = lines + .next() + .with_context(|| format!("{given} holds no key"))?; + let key = Key::parse(first).map_err(|why| anyhow!("{given}: {why}"))?; + Ok(Given::Public(key, lines.count())) +} + +/// The key `--key` gives (`given_key`): a private key, signing here; or a public key, +/// signing through the ssh-agent at `SSH_AUTH_SOCK`, which must hold it. Of a file of +/// several public keys, the first, with a warning: another is given as `--key` itself. fn signing_key(options: &Options) -> Result { - let file = options + let given = options .key .as_ref() .context("--key names the party's key")?; - let text = std::fs::read_to_string(file).with_context(|| format!("Reading {file}"))?; - if let Ok(key) = Key::parse(&text) { - let socket = std::env::var_os("SSH_AUTH_SOCK").with_context(|| { - format!( - "{file} is a public key, signed with through an ssh-agent: SSH_AUTH_SOCK names none" - ) - })?; - return Ok(Signing::Agent(key, PathBuf::from(socket))); - } - let key = client::signing_key(&text).map_err(|why| anyhow!("{file}: {why}"))?; - Ok(Signing::File(key)) + let key = match given_key(given)? { + Given::Private(key) => return Ok(Signing::File(key)), + Given::Public(key, 0) => key, + Given::Public(key, more) => { + eprintln!( + "Warning: {given} holds {} keys: signing with the first, {}; to sign with \ + another, give that key itself as --key", + more + 1, + key.line() + ); + key + } + }; + let socket = std::env::var_os("SSH_AUTH_SOCK").with_context(|| { + format!( + "{} signs through an ssh-agent: SSH_AUTH_SOCK names none", + key.line() + ) + })?; + Ok(Signing::Agent(key, PathBuf::from(socket))) } /// What signs: a key at hand, or a key the ssh-agent at a socket holds. @@ -699,6 +746,46 @@ mod tests { super::command().debug_assert(); } + /// `--key` gives a public key itself, or the first of a file's with how many more it + /// holds, or a private key file's key; a file of neither, or none, gives nothing. + #[test] + fn the_key_given() { + use super::{Given, given_key}; + use crate::federation::vectors::ECDSA_KEY; + let ed25519 = crate::federation::harness::key_line(1); + let dir = crate::files::scratch_dir("party-key"); + let file = |name: &str, text: &str| { + let path = dir.join(name); + std::fs::write(&path, text).unwrap(); + path.to_str().unwrap().to_owned() + }; + let public = |given: &str| match given_key(given).unwrap() { + Given::Public(key, more) => (key.line(), more), + Given::Private(_) => panic!("{given}: a private key"), + }; + assert_eq!(public(ECDSA_KEY), (ECDSA_KEY.to_owned(), 0)); + assert_eq!( + public(&format!("{ed25519} tv@laptop")), + (ed25519.clone(), 0) + ); + let one = file("phone.pub", &format!("{ECDSA_KEY} tv@phone\n")); + assert_eq!(public(&one), (ECDSA_KEY.to_owned(), 0)); + let two = file( + "agent.pub", + &format!("{ed25519} tv@laptop\n\n{ECDSA_KEY} tv@phone\n"), + ); + assert_eq!(public(&two), (ed25519, 1)); + assert!(given_key(&file("rsa.pub", "ssh-rsa AAAAB3NzaC1yc2E tv\n")).is_err()); + assert!(given_key(&file("empty.pub", "\n")).is_err()); + assert!(given_key(dir.join("missing").to_str().unwrap()).is_err()); + let private = file( + "tv.key", + "-----BEGIN OPENSSH PRIVATE KEY-----\n-----END OPENSSH PRIVATE KEY-----\n", + ); + let why = given_key(&private).err().expect("no key").to_string(); + assert!(why.contains("OpenSSH private key"), "{why}"); + } + /// Its options come from configuration files as the node's do, arguments winning. #[test] fn its_options_come_from_configuration_files_and_arguments() { -- cgit v1.3.1 From 55f36a960a90aedcb6e899ea963cc642fd630a82 Mon Sep 17 00:00:00 2001 From: tv Date: Wed, 18 Nov 2026 11:17:17 +0000 Subject: continuum-party: why waiting for the ssh-agent may block The client signs one event at a time and does nothing else meanwhile, and an agent may wait for its user as long as that takes. --- src/federation/party.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/federation/party.rs b/src/federation/party.rs index 5d18eb8..9d9c268 100644 --- a/src/federation/party.rs +++ b/src/federation/party.rs @@ -429,6 +429,10 @@ impl Signer { Ok(event::signed(key, &self.party, &line, deps, does)) } Signing::Agent(key, socket) => { + // The agent's answer is waited for blocking the thread, in async code: the + // client signs one event at a time and does nothing else meanwhile, and an + // agent may wait for its user (a touch, a confirmation) as long as that + // takes, which nothing here should cut short. event::signed_by(&self.party, &key.line(), deps, does, |bytes| { keys::sign_through(socket, key, bytes) }) -- cgit v1.3.1