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
|
//! Logging in by key (`POST /auth/challenge`, `POST /auth/login/key`): a node hands out
//! a challenge, signed by it, naming it, valid for a while (`issue`); the user signs it
//! with one of its keys, as `ssh-keygen -Y sign -n continuum-login` does
//! (`access::sshsig`), and the node takes the signature once, from the user that key is
//! of in the registry (`registry::User::keys`; `take`). A challenge is checked by its
//! signature, so a node keeps none it handed out, only those used, until they expire
//! (`Used`).
//!
//! A challenge is `cc1.<payload>.<signature>` (each base64url, unpadded): the payload is
//! JSON naming the node, a random nonce and when it expires (Unix ms); the signature is
//! the node's, over `continuum/challenge/1\0` and the payload.
use std::collections::HashMap;
use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD as B64URL};
use serde::{Deserialize, Serialize};
use super::{registry, sshsig};
use crate::document::ReadDoc;
use crate::identity::NodeKey;
/// What a user's signature over a challenge is for (`sshsig`).
pub(crate) const NAMESPACE: &str = "continuum-login";
/// What every challenge starts with.
const PREFIX: &str = "cc1";
/// How long a challenge is valid (ms).
pub(crate) const LIFETIME_MS: u64 = 5 * 60 * 1000;
/// Used challenges kept at most: past it, logins by key wait for some to expire.
const MAX_USED: usize = 10_000;
#[derive(Debug, Serialize, Deserialize)]
struct Payload {
node: String,
nonce: String,
exp: u64,
}
fn message(payload: &[u8]) -> Vec<u8> {
let mut message = b"continuum/challenge/1\0".to_vec();
message.extend_from_slice(payload);
message
}
/// A new challenge by `key`'s node, valid from `now` for `LIFETIME_MS`; with when it
/// expires.
pub(crate) fn issue(key: &NodeKey, now: u64) -> (String, u64) {
let payload = Payload {
node: key.id(),
nonce: registry::new_id(),
exp: now.saturating_add(LIFETIME_MS),
};
let bytes = serde_json::to_vec(&payload).expect("a challenge serializes");
let signature = key.sign(&message(&bytes));
(
format!(
"{PREFIX}.{}.{}",
B64URL.encode(&bytes),
B64URL.encode(signature)
),
payload.exp,
)
}
/// The challenges used, by nonce, with when each expires.
#[derive(Debug, Default)]
pub(crate) struct Used(HashMap<String, u64>);
/// Takes `signature` (armored) over `challenge` as a login of `user`, whose registry
/// `doc` holds: a challenge of `key`'s node, unexpired at `now`, not used before (then
/// used, in `used`), signed by one of `user`'s keys, `user` enabled. Why not, if not.
pub(crate) fn take(
doc: &impl ReadDoc,
key: &NodeKey,
challenge: &str,
signature: &str,
user: &str,
now: u64,
used: &mut Used,
) -> Result<(), String> {
let mut parts = challenge.split('.');
let (Some(PREFIX), Some(payload), Some(signed), None) =
(parts.next(), parts.next(), parts.next(), parts.next())
else {
return Err("not a challenge (cc1.<payload>.<signature>)".to_owned());
};
let bytes = B64URL
.decode(payload)
.map_err(|_| "not a challenge: its payload doesn't decode".to_owned())?;
let by_node: [u8; 64] = B64URL
.decode(signed)
.ok()
.and_then(|signed| signed.try_into().ok())
.ok_or("not a challenge: its signature doesn't decode")?;
if !crate::identity::verify(&key.public(), &message(&bytes), &by_node) {
return Err("not a challenge this node handed out".to_owned());
}
let payload: Payload = serde_json::from_slice(&bytes)
.map_err(|_| "not a challenge: its payload isn't one".to_owned())?;
if payload.node != key.id() {
return Err("a challenge of another node".to_owned());
}
if payload.exp <= now {
return Err("the challenge expired: ask for another".to_owned());
}
used.0.retain(|_, exp| *exp > now);
if used.0.contains_key(&payload.nonce) {
return Err("the challenge was used: ask for another".to_owned());
}
if used.0.len() >= MAX_USED {
return Err("too many logins by key at once: try again in a while".to_owned());
}
let signer = sshsig::verify(signature, NAMESPACE, challenge.as_bytes())?;
let entry = registry::user(doc, user).ok_or_else(|| format!("no user {user}"))?;
if entry.disabled {
return Err(format!("{user} is disabled"));
}
if !entry.keys.values().any(|known| *known == signer) {
return Err(format!("{user} has no key {}", signer.fingerprint()));
}
used.0.insert(payload.nonce, payload.exp);
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::document::Document;
use crate::document::store;
use crate::document::testing::change;
use ed25519_dalek::SigningKey;
use serde_json::json;
/// A registry with alice, holding `key`'s public key, and carol, disabled, holding
/// it too.
fn registry_with(key: &SigningKey) -> Document {
let line = sshsig::PublicKey(key.verifying_key().to_bytes()).line();
let mut doc = Document::new();
change(&mut doc, |doc| {
let mut alice = registry::entry("root", 1, &[]);
alice["keys"] = json!({ "laptop": line });
store::write_path(doc, ®istry::user_path("alice"), &alice).unwrap();
let mut carol = registry::entry("root", 1, &[]);
carol["keys"] = json!({ "laptop": line });
carol["disabled"] = json!(true);
store::write_path(doc, ®istry::user_path("carol"), &carol).unwrap();
store::write_path(
doc,
®istry::user_path("bob"),
®istry::entry("root", 1, &[]),
)
.unwrap();
});
doc
}
/// Signed by one of the user's keys, of this node, unexpired, once: taken; anything
/// else refused.
#[test]
fn what_a_login_by_key_takes() {
let node = NodeKey::from_seed([1; 32]);
let other_node = NodeKey::from_seed([2; 32]);
let key = SigningKey::from_bytes(&[5; 32]);
let stranger = SigningKey::from_bytes(&[6; 32]);
let doc = registry_with(&key);
let mut used = Used::default();
let (challenge, exp) = issue(&node, 1000);
assert_eq!(exp, 1000 + LIFETIME_MS);
let signed = sshsig::sign(&key, NAMESPACE, challenge.as_bytes());
// Another user, a disabled one, an unknown one, another key: refused.
assert!(take(&doc, &node, &challenge, &signed, "bob", 1001, &mut used).is_err());
assert!(take(&doc, &node, &challenge, &signed, "carol", 1001, &mut used).is_err());
assert!(take(&doc, &node, &challenge, &signed, "dave", 1001, &mut used).is_err());
let foreign = sshsig::sign(&stranger, NAMESPACE, challenge.as_bytes());
assert!(take(&doc, &node, &challenge, &foreign, "alice", 1001, &mut used).is_err());
// For another purpose: refused.
let elsewhere = sshsig::sign(&key, "continuum-value", challenge.as_bytes());
assert!(
take(
&doc, &node, &challenge, &elsewhere, "alice", 1001, &mut used
)
.is_err()
);
// Another node's, expired: refused.
assert!(
take(
&doc,
&other_node,
&challenge,
&signed,
"alice",
1001,
&mut used
)
.is_err()
);
assert!(take(&doc, &node, &challenge, &signed, "alice", exp, &mut used).is_err());
// Taken, once.
assert!(take(&doc, &node, &challenge, &signed, "alice", 1001, &mut used).is_ok());
assert!(take(&doc, &node, &challenge, &signed, "alice", 1002, &mut used).is_err());
// Tampered with.
let tampered = challenge.replacen("cc1.", "cc1.e30", 1);
let resigned = sshsig::sign(&key, NAMESPACE, tampered.as_bytes());
assert!(take(&doc, &node, &tampered, &resigned, "alice", 1001, &mut used).is_err());
}
}
|