aboutsummaryrefslogtreecommitdiffstats
path: root/src/federation/keys.rs
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/keys.rs
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/keys.rs')
-rw-r--r--src/federation/keys.rs146
1 files changed, 146 insertions, 0 deletions
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(),
+ );
+ }
+ }
+ }
}