1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
|
//! Keys, node IDs and signatures, each spelled one way (`docs/federation.md`, Events):
//!
//! * 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. 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 std::path::Path;
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, 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<Key, String> {
let mut parts = line.split_whitespace();
let (Some(kind), Some(encoded)) = (parts.next(), parts.next()) else {
return Err(format!("not `{ED25519}|{P256} <base64> [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<u8> {
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<Key> {
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.
pub(crate) fn node_id(text: &str) -> bool {
identity::public_of(text).is_some_and(|key| VerifyingKey::from_bytes(&key).is_ok())
}
/// Whether `sig` is `key`'s signature of `message`, spelled as the federation spells one.
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 {
return false;
}
// The blob reads back to itself: what signing with this key writes around its
// 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;
}
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<p256::ecdsa::Signature> {
/// 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<u8> {
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
/// `ssh-keygen -Y sign -n continuum-federation` makes, unarmored.
pub(crate) fn sign(key: &SigningKey, message: &[u8]) -> String {
let blob = sshsig::dearmor(&sshsig::sign(key, NAMESPACE, message))
.expect("a signature made here dearmors");
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(
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 around
/// `signature`, the key type's own.
fn written(key: &Key, signature: &[u8]) -> Vec<u8> {
let mut inner = Vec::new();
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());
string(&mut blob, &key.blob());
string(&mut blob, NAMESPACE.as_bytes());
string(&mut blob, b"");
string(&mut blob, b"sha512");
string(&mut blob, &inner);
blob
}
#[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) -> Key {
Key::Ed25519(PublicKey(key.verifying_key().to_bytes()))
}
#[test]
fn a_key_is_spelled_one_way() {
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());
assert!(node_id(&id));
assert!(!node_id(&id.to_uppercase()));
assert!(!node_id(&id.replace("continuum:", "continuum:0")));
assert!(!node_id(&id[..id.len() - 1]));
}
#[test]
fn a_signature_is_its_signers_and_reads_back_to_itself() {
let key = signer(3);
let sig = sign(&key, b"an event");
assert!(verifies(&public(&key), &sig, b"an event"));
assert!(!verifies(&public(&key), &sig, b"another event"));
assert!(!verifies(&public(&signer(4)), &sig, b"an event"));
// Armored, or base64 spelled otherwise: none.
let armored = sshsig::sign(&key, NAMESPACE, b"an event");
assert!(!verifies(&public(&key), &armored, b"an event"));
assert!(!verifies(&public(&key), &format!("{sig}\n"), b"an event"));
// For another namespace: none.
let elsewhere = BASE64.encode(
sshsig::dearmor(&sshsig::sign(&key, "another", b"an event")).expect("dearmors"),
);
assert!(!verifies(&public(&key), &elsewhere, b"an event"));
}
#[test]
fn a_signature_with_a_reserved_field_is_none() {
let key = signer(5);
let blob = BASE64.decode(sign(&key, b"an event")).expect("base64");
// The reserved field, empty, follows the namespace: give it a byte. The signature
// no longer matches, but the blob is refused before that is asked.
let at = 6 + 4 + 4 + public(&key).blob().len() + 4 + NAMESPACE.len();
let mut changed = blob[..at].to_vec();
changed.extend_from_slice(&1u32.to_be_bytes());
changed.push(b'x');
changed.extend_from_slice(&blob[at + 4..]);
assert!(!verifies(
&public(&key),
&BASE64.encode(changed),
b"an event"
));
}
/// The ECDSA vector's write: its key, its `sig`, and the bytes it signs.
fn ecdsa_write() -> (Key, String, Vec<u8>) {
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);
}
/// 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(),
);
}
}
}
}
|