aboutsummaryrefslogtreecommitdiffstats
path: root/src/federation
diff options
context:
space:
mode:
authorslopulus <slop@lassul.us>2026-11-17 20:01:42 +0100
committertv <tv@krebsco.de>2026-11-17 21:09:38 +0100
commitbcda4d67483239691b045c5b978047f017f3b9e3 (patch)
treef6a36de02d707969c1c78c03ce589cef171fbad3 /src/federation
parenta1e398621eec9472ad67f1eafeba9ff23b012c2f (diff)
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.
Diffstat (limited to 'src/federation')
-rw-r--r--src/federation/agent.rs45
-rw-r--r--src/federation/event.rs22
-rw-r--r--src/federation/keys.rs146
-rw-r--r--src/federation/mod.rs1
-rw-r--r--src/federation/party.rs55
5 files changed, 250 insertions, 19 deletions
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<Vec<u8>, 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<u8> {
+ 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<String, String>,
+) -> Result<Vec<u8>, 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<String, String> {
+ 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<String, String> {
+ 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<u8> {
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<String> {
.collect()
}
-fn signing_key(options: &Options) -> Result<SigningKey> {
+/// 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<Signing> {
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<u8> {
- 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<Vec<u8>> {
+ 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(&current, &cast, kept);
record.save(path).map_err(|why| anyhow!(why))?;
node.put(&cast).await