//! 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()) }