1use ssh_key::{PrivateKey, SigningKey};
17
18pub const FAILURE: u8 = 5;
19pub const REQUEST_IDENTITIES: u8 = 11;
20pub const IDENTITIES_ANSWER: u8 = 12;
21pub const SIGN_REQUEST: u8 = 13;
22pub const SIGN_RESPONSE: u8 = 14;
23
24pub const MAX_MESSAGE: usize = 256 * 1024;
27
28pub struct AgentKey {
30 pub blob: Vec<u8>,
31 pub comment: String,
32 private: PrivateKey,
33}
34
35impl AgentKey {
36 pub fn from_pem(pem: &str, fallback_comment: &str) -> Result<Self, String> {
39 let private = PrivateKey::from_openssh(pem.trim()).map_err(|e| e.to_string())?;
40 if private.is_encrypted() {
41 return Err("the key is encrypted".into());
42 }
43 if private.algorithm() != ssh_key::Algorithm::Ed25519 {
44 return Err(format!("{} keys are not supported", private.algorithm()));
45 }
46 let blob = private.public_key().to_bytes().map_err(|e| e.to_string())?;
47 let comment = if private.comment().is_empty() {
48 fallback_comment.to_string()
49 } else {
50 private.comment().to_string()
51 };
52 Ok(Self {
53 blob,
54 comment,
55 private,
56 })
57 }
58
59 fn sign(&self, data: &[u8]) -> Result<Vec<u8>, String> {
61 sign_with(&self.private, data)
62 }
63}
64
65fn sign_with<K: SigningKey>(key: &K, data: &[u8]) -> Result<Vec<u8>, String> {
66 let sig = key.try_sign(data).map_err(|e| e.to_string())?;
67 Vec::<u8>::try_from(sig).map_err(|e| e.to_string())
68}
69
70fn put_u32(out: &mut Vec<u8>, v: u32) {
71 out.extend_from_slice(&v.to_be_bytes());
72}
73
74fn put_string(out: &mut Vec<u8>, s: &[u8]) {
75 put_u32(out, s.len() as u32);
76 out.extend_from_slice(s);
77}
78
79fn take_u32(buf: &mut &[u8]) -> Option<u32> {
81 let (head, rest) = buf.split_first_chunk::<4>()?;
82 *buf = rest;
83 Some(u32::from_be_bytes(*head))
84}
85
86fn take_string<'a>(buf: &mut &'a [u8]) -> Option<&'a [u8]> {
88 let n = take_u32(buf)? as usize;
89 if n > buf.len() {
90 return None;
91 }
92 let (s, rest) = buf.split_at(n);
93 *buf = rest;
94 Some(s)
95}
96
97pub fn handle(request: &[u8], keys: &[AgentKey]) -> (Vec<u8>, Option<String>) {
101 let failure = || (vec![FAILURE], None);
102 let Some((&kind, mut body)) = request.split_first() else {
103 return failure();
104 };
105 match kind {
106 REQUEST_IDENTITIES => {
107 let mut out = vec![IDENTITIES_ANSWER];
108 put_u32(&mut out, keys.len() as u32);
109 for k in keys {
110 put_string(&mut out, &k.blob);
111 put_string(&mut out, k.comment.as_bytes());
112 }
113 (out, None)
114 }
115 SIGN_REQUEST => {
116 let (Some(blob), Some(data), Some(_flags)) = (
117 take_string(&mut body),
118 take_string(&mut body),
119 take_u32(&mut body),
120 ) else {
121 return failure();
122 };
123 let Some(key) = keys.iter().find(|k| k.blob == blob) else {
124 return failure();
125 };
126 match key.sign(data) {
127 Ok(sig) => {
128 let mut out = vec![SIGN_RESPONSE];
129 put_string(&mut out, &sig);
130 (out, Some(key.comment.clone()))
131 }
132 Err(_) => failure(),
133 }
134 }
135 _ => failure(),
136 }
137}
138
139pub fn serve<S: std::io::Read + std::io::Write>(
142 stream: &mut S,
143 keys: &[AgentKey],
144 mut signed: impl FnMut(&str),
145) -> std::io::Result<()> {
146 loop {
147 let mut len = [0u8; 4];
148 match stream.read_exact(&mut len) {
149 Ok(()) => {}
150 Err(e) if e.kind() == std::io::ErrorKind::UnexpectedEof => return Ok(()),
151 Err(e) => return Err(e),
152 }
153 let n = u32::from_be_bytes(len) as usize;
154 if n == 0 || n > MAX_MESSAGE {
155 return Err(std::io::Error::new(
156 std::io::ErrorKind::InvalidData,
157 "message length out of range",
158 ));
159 }
160 let mut payload = vec![0u8; n];
161 stream.read_exact(&mut payload)?;
162 let (reply, by) = handle(&payload, keys);
163 if let Some(comment) = by {
164 signed(&comment);
165 }
166 stream.write_all(&(reply.len() as u32).to_be_bytes())?;
167 stream.write_all(&reply)?;
168 stream.flush()?;
169 }
170}
171
172#[cfg(test)]
173mod tests {
174 use super::*;
175 use crate::entropy::Source;
176
177 fn key(comment: &str) -> (AgentKey, Vec<u8>) {
180 let made = crate::generate_ssh_keypair(comment, &Source::Os).unwrap();
181 let pem = made["private_key"].as_str().unwrap().to_string();
182 let parsed = PrivateKey::from_openssh(pem.trim()).unwrap();
183 let seed = parsed
184 .key_data()
185 .ed25519()
186 .unwrap()
187 .private
188 .to_bytes()
189 .to_vec();
190 (AgentKey::from_pem(&pem, "fallback").unwrap(), seed)
191 }
192
193 fn sign_request(blob: &[u8], data: &[u8]) -> Vec<u8> {
194 let mut r = vec![SIGN_REQUEST];
195 put_string(&mut r, blob);
196 put_string(&mut r, data);
197 put_u32(&mut r, 0);
198 r
199 }
200
201 #[test]
202 fn identities_list_each_public_blob_and_comment_and_no_private_bytes() {
203 let (a, seed_a) = key("alpha");
204 let (b, seed_b) = key("beta");
205 let (reply, by) = handle(&[REQUEST_IDENTITIES], &[a, b]);
206 assert_eq!(reply[0], IDENTITIES_ANSWER);
207 assert_eq!(u32::from_be_bytes(reply[1..5].try_into().unwrap()), 2);
208 assert!(by.is_none());
209 for seed in [seed_a, seed_b] {
210 assert!(
211 !reply.windows(seed.len()).any(|w| w == seed.as_slice()),
212 "a private key must never be in an answer"
213 );
214 }
215 let text = String::from_utf8_lossy(&reply);
216 assert!(text.contains("alpha") && text.contains("beta"));
217 }
218
219 #[test]
220 fn a_signature_is_an_ed25519_blob_and_names_the_key_that_made_it() {
221 let (a, seed) = key("alpha");
222 let blob = a.blob.clone();
223 let (reply, by) = handle(&sign_request(&blob, b"challenge"), &[a]);
224 assert_eq!(reply[0], SIGN_RESPONSE);
225 assert_eq!(by.as_deref(), Some("alpha"));
226 let mut rest = &reply[1..];
227 let sig = take_string(&mut rest).unwrap();
228 let mut s = sig;
230 assert_eq!(take_string(&mut s).unwrap(), b"ssh-ed25519");
231 assert_eq!(take_string(&mut s).unwrap().len(), 64);
232 assert!(!reply.windows(seed.len()).any(|w| w == seed.as_slice()));
233 }
234
235 #[test]
236 fn an_unknown_key_a_short_request_and_every_other_request_are_refused() {
237 let (a, _) = key("alpha");
238 let keys = [a];
239 for bad in [
240 vec![],
241 vec![SIGN_REQUEST],
242 sign_request(b"not a held key", b"x"),
243 vec![17, 0, 0, 0, 0],
244 vec![18, 0, 0, 0, 1, 1],
245 vec![9],
246 ] {
247 let (reply, by) = handle(&bad, &keys);
248 assert_eq!(reply, vec![FAILURE], "{bad:?}");
249 assert!(by.is_none());
250 }
251 }
252
253 #[test]
254 fn a_string_longer_than_the_message_is_refused_not_read() {
255 let (a, _) = key("alpha");
256 let mut r = vec![SIGN_REQUEST];
257 put_u32(&mut r, u32::MAX);
258 r.extend_from_slice(b"short");
259 assert_eq!(handle(&r, &[a]).0, vec![FAILURE]);
260 }
261
262 #[test]
263 fn text_that_is_not_a_key_is_refused_at_load() {
264 assert!(AgentKey::from_pem("not a key", "c").is_err());
265 }
266
267 #[test]
268 fn the_fallback_comment_is_used_when_the_key_has_none() {
269 let made = crate::generate_ssh_keypair("", &Source::Os).unwrap();
270 let pem = made["private_key"].as_str().unwrap();
271 let k = AgentKey::from_pem(pem, "from the entry name").unwrap();
272 assert_eq!(k.comment, "from the entry name");
273 }
274
275 struct Duplex {
277 r: std::io::Cursor<Vec<u8>>,
278 w: Vec<u8>,
279 }
280 impl std::io::Read for Duplex {
281 fn read(&mut self, b: &mut [u8]) -> std::io::Result<usize> {
282 std::io::Read::read(&mut self.r, b)
283 }
284 }
285 impl std::io::Write for Duplex {
286 fn write(&mut self, b: &[u8]) -> std::io::Result<usize> {
287 self.w.write(b)
288 }
289 fn flush(&mut self) -> std::io::Result<()> {
290 Ok(())
291 }
292 }
293
294 #[test]
295 fn serve_answers_framed_requests_in_order_audits_signatures_and_ends_on_close() {
296 let (a, _) = key("alpha");
297 let blob = a.blob.clone();
298 let mut input = Vec::new();
299 for req in [vec![REQUEST_IDENTITIES], sign_request(&blob, b"d")] {
300 input.extend_from_slice(&(req.len() as u32).to_be_bytes());
301 input.extend_from_slice(&req);
302 }
303 let mut d = Duplex {
304 r: std::io::Cursor::new(input),
305 w: Vec::new(),
306 };
307 let mut audited = Vec::new();
308 serve(&mut d, &[a], |c| audited.push(c.to_string())).unwrap();
309 assert_eq!(audited, vec!["alpha"]);
310 let first = u32::from_be_bytes(d.w[0..4].try_into().unwrap()) as usize;
311 assert_eq!(d.w[4], IDENTITIES_ANSWER);
312 assert_eq!(d.w[4 + first + 4], SIGN_RESPONSE);
314 }
315
316 #[test]
317 fn an_oversized_or_empty_frame_ends_the_connection_unread() {
318 for len in [0u32, (MAX_MESSAGE as u32) + 1] {
319 let mut d = Duplex {
320 r: std::io::Cursor::new(len.to_be_bytes().to_vec()),
321 w: Vec::new(),
322 };
323 assert!(serve(&mut d, &[], |_| {}).is_err());
324 assert!(d.w.is_empty());
325 }
326 }
327}