diff options
Diffstat (limited to 'src')
| -rw-r--r-- | src/access/challenge.rs | 34 | ||||
| -rw-r--r-- | src/access/token.rs | 38 | ||||
| -rw-r--r-- | src/api/access.rs | 62 | ||||
| -rw-r--r-- | src/api/login.rs | 81 | ||||
| -rw-r--r-- | src/api/mod.rs | 93 | ||||
| -rw-r--r-- | src/federation/fold.rs | 16 | ||||
| -rw-r--r-- | src/federation/keys.rs | 136 |
7 files changed, 362 insertions, 98 deletions
diff --git a/src/access/challenge.rs b/src/access/challenge.rs index e61ea85..8df0f08 100644 --- a/src/access/challenge.rs +++ b/src/access/challenge.rs @@ -79,6 +79,31 @@ pub(crate) fn take( used: &mut Used, per_user: usize, ) -> Result<(), String> { + take_with(key, challenge, user, now, used, per_user, |challenge| { + 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())); + } + Ok(()) + }) +} + +/// Takes `challenge` as a login of `user`, where `check` says that `user` signed it: a +/// challenge of `key`'s node, unexpired at `now`, not used before (then used, in `used`), +/// with fewer than `per_user` of `user`'s own still remembered. Why not, if not. +pub(crate) fn take_with( + key: &NodeKey, + challenge: &str, + user: &str, + now: u64, + used: &mut Used, + per_user: usize, + check: impl FnOnce(&str) -> Result<(), String>, +) -> Result<(), String> { let mut parts = challenge.split('.'); let (Some(PREFIX), Some(payload), Some(signed), None) = (parts.next(), parts.next(), parts.next(), parts.next()) @@ -116,14 +141,7 @@ pub(crate) fn take( 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())); - } + check(challenge)?; used.0.insert(payload.nonce, (payload.exp, user.to_owned())); Ok(()) } diff --git a/src/access/token.rs b/src/access/token.rs index 0920410..650a5c4 100644 --- a/src/access/token.rs +++ b/src/access/token.rs @@ -58,6 +58,13 @@ pub(crate) struct Claims { /// Less than the user may do: only what these allow too. #[serde(default, skip_serializing_if = "Option::is_none")] pub(crate) limit: Option<Vec<Capability>>, + /// Of a party's session, on a node holding a federated store: the key, as the + /// federation spells it, that `user`, the party, logged in with + /// (`api::login::login_party`). Such a token does federation work alone, while that + /// key signs for the party (`api::access::federated`); a build from before it reads + /// none (`deny_unknown_fields`), so never takes it for its user's. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub(crate) party: Option<String>, } /// `claims`, signed by `key`, as a token. @@ -243,6 +250,7 @@ mod tests { session_exp: 10_000, login_exp: 10_000, limit: None, + party: None, } } @@ -251,6 +259,36 @@ mod tests { change(doc, |tx| store::write_path(tx, &path, &json!({})).unwrap()); } + /// A party's session names the key it logged in with, which a token of a user's + /// leaves out: a build from before it reads none (its claims deny fields it doesn't + /// know), so never takes it for its user's. + #[test] + fn a_partys_session_names_its_key() { + let key = NodeKey::from_seed([1; 32]); + let mut doc = Document::new(); + member(&mut doc, &key); + let party = Claims { + user: "tv".to_owned(), + login: "party".to_owned(), + party: Some("ssh-ed25519 AAAA".to_owned()), + ..claims(&key) + }; + let token = issue(&key, &party); + assert_eq!(verify(&doc, &token, "s", 1_500), Ok(party)); + let (_, payload) = token.split_once('.').unwrap(); + let (payload, _) = payload.split_once('.').unwrap(); + let payload = String::from_utf8(BASE64URL.decode(payload).unwrap()).unwrap(); + assert!( + payload.contains(r#""party":"ssh-ed25519 AAAA""#), + "{payload}" + ); + let user = issue(&key, &claims(&key)); + let (_, payload) = user.split_once('.').unwrap(); + let (payload, _) = payload.split_once('.').unwrap(); + let payload = String::from_utf8(BASE64URL.decode(payload).unwrap()).unwrap(); + assert!(!payload.contains("party"), "{payload}"); + } + #[test] fn issued_and_taken() { let key = NodeKey::from_seed([1; 32]); diff --git a/src/api/access.rs b/src/api/access.rs index 47e24ba..339d9de 100644 --- a/src/api/access.rs +++ b/src/api/access.rs @@ -394,33 +394,61 @@ pub(crate) async fn authorize( } /// On a node holding a federated store, what its users who aren't its operators may do: a -/// user of `--store-readers` reads the federation (`federation_work`), and nothing else. -/// Its other users are its operators, who may do everything. The answer refusing the -/// request, where it is refused. +/// party's session (a token from a party's key, `login::login_party`) does federation work +/// (`federation_work`), putting events too, while the key it logged in with signs for +/// the party (`fold::State::signing_keys`); a user of `--store-readers` reads the +/// federation; and neither does anything else. Its other users are its operators, who may +/// do everything. The answer refusing the request, where it is refused. #[cfg(feature = "federation")] fn federated(state: &AppState, request: &Request<Body>, user: &str) -> Option<Response> { - if !state.store_readers.contains(user) { + let party_key = request + .extensions() + .get::<super::login::Token>() + .and_then(|token| token.claims.party.clone()); + if party_key.is_none() && !state.store_readers.contains(user) { return None; } - if state.holding.with(|_| ()).is_none() { - return Some(error_response( - StatusCode::FORBIDDEN, - format!("{user} reads a federated store here alone, and this node holds none"), - None, - )); + let signs = state.holding.with(|store| { + let read = store.state(); + party_key + .as_ref() + .is_none_or(|key| read.signing_keys(user, read.current()).contains(key)) + }); + let refused = |status: StatusCode, why: String| { + debug!(user = %user, method = %request.method(), path = %request.uri().path(), reason = %why, "Refused a request of a party or a reader"); + Some(error_response(status, why, None)) + }; + match signs { + None => { + return refused( + StatusCode::FORBIDDEN, + format!("{user} works with a federated store here alone, and this node holds none"), + ); + } + Some(false) => { + return refused( + StatusCode::UNAUTHORIZED, + format!("the key {user} logged in with signs for it no more: log in again"), + ); + } + Some(true) => {} } - if federation_work(request.method(), request.uri().path(), false) { + let puts = party_key.is_some(); + if federation_work(request.method(), request.uri().path(), puts) { return None; } - debug!(user = %user, method = %request.method(), path = %request.uri().path(), "Refused a reader's request that doesn't read the federation"); - Some(error_response( - StatusCode::FORBIDDEN, + let why = if puts { + format!( + "a session of {user}, a party, does federation work alone: reading and putting \ + events (docs/guides/federation/running-a-node.md, Its API)" + ) + } else { format!( "{user} reads the federation here, and does nothing else (--store-readers; \ docs/guides/federation/running-a-node.md, Its API)" - ), - None, - )) + ) + }; + refused(StatusCode::FORBIDDEN, why) } /// Whether a request is federation work: reading the events API (`GET` and `HEAD` of diff --git a/src/api/login.rs b/src/api/login.rs index 0658a69..ffcf9b8 100644 --- a/src/api/login.rs +++ b/src/api/login.rs @@ -8,6 +8,9 @@ //! * `POST /auth/challenge` and `POST /auth/login/key`, without a password: a challenge //! to sign with one of the user's keys, then the same token for it, signed //! (`access::challenge`). +//! * `POST /auth/login/party`, without a password, on a node holding a federated store: a +//! token as a party, for a challenge signed with one of the keys that sign for it there, +//! which does federation work alone (`login_party`). //! * `POST /auth/refresh`, with a token: a new one for the same login, signed by this //! node, optionally narrower still (`limit`, within the token's). //! * `POST /auth/logout`: every token of the user, of every login, no longer taken @@ -279,6 +282,7 @@ fn new_login( session_exp, login_exp: session_exp, limit, + party: None, } } @@ -322,6 +326,82 @@ pub(crate) struct KeyLogin { limit: Option<Vec<CapRequest>>, } +/// A party's login by one of its keys (`POST /auth/login/party`). +#[cfg(feature = "federation")] +#[derive(Deserialize)] +pub(crate) struct PartyLogin { + party: String, + challenge: String, + /// Armored, as `ssh-keygen -Y sign -n continuum-login` writes it, or its blob in base64. + signature: String, +} + +/// `POST /auth/login/party`: on a node holding a federated store, a token as `party` for a +/// challenge signed with one of the keys that sign for it there, as its current version +/// and its key set say (`fold::State::signing_keys`), as `ssh-keygen -Y sign -n +/// continuum-login` signs, an ECDSA signature's `s` low (`401` if not, saying why): a +/// party's session, which does federation work alone, while that key signs for the +/// party (`api::access::federated`). `409` on a node holding none. +#[cfg(feature = "federation")] +pub(crate) async fn login_party( + State(state): State<AppState>, + Json(request): Json<PartyLogin>, +) -> Result<Response, ApiError> { + let (swarm, now) = issuing(&state).await?; + let key = state + .node_key + .as_ref() + .ok_or(ApiError(StatusCode::SERVICE_UNAVAILABLE, None))?; + let party = request.party.as_str(); + let keys = state + .holding + .with(|store| { + let read = store.state(); + read.signing_keys(party, read.current()) + }) + .ok_or_else(|| { + ApiError( + StatusCode::CONFLICT, + Some("no federated store here, whose parties' keys log in".to_owned()), + ) + })?; + let signer = { + let mut used = state.challenges.lock_or_recover(); + let mut signer = None; + challenge::take_with( + key, + &request.challenge, + &format!("party {party}"), + now, + &mut used, + state.key_logins_per_user, + |challenge| { + if keys.is_empty() { + return Err(format!("{party} is no party of the current version")); + } + let found = crate::federation::keys::signer( + &keys, + challenge::NAMESPACE, + &request.signature, + challenge.as_bytes(), + ) + .ok_or_else(|| format!("signed by none of the keys that sign for {party}"))?; + signer = Some(found.to_owned()); + Ok(()) + }, + ) + .map_err(|why| { + debug!(party = %party, reason = %why, "Refused a party's login"); + ApiError(StatusCode::UNAUTHORIZED, Some(why)) + })?; + signer + }; + let mut claims = new_login(&state, swarm, now, party, "party", None, None); + claims.party = signer; + info!(party = %party, login = "party", session = %claims.session, "A party logged in"); + answer(&state, &claims) +} + /// `POST /auth/login/key`: a token, as `POST /auth/login` gives one, for a challenge /// signed by one of the user's keys (`401` if not, saying why); `409` in a swarm without /// a registry, which holds no keys. @@ -745,6 +825,7 @@ pub(crate) async fn whoami( "session": token.claims.session, "sessionExpiresAt": token.claims.session_exp, "limit": token.claims.limit, + "party": token.claims.party, }) }); Json(json!({ diff --git a/src/api/mod.rs b/src/api/mod.rs index d91c434..c4265fb 100644 --- a/src/api/mod.rs +++ b/src/api/mod.rs @@ -44,7 +44,8 @@ use crate::state::AppState; /// Builds the complete HTTP router. Everything except the API description (`/swagger-ui`, /// `/openapi.yaml`), `/health`, `/ready` and logging in by key (`/auth/challenge`, -/// `/auth/login/key`, which prove the user themselves) is authenticated. +/// `/auth/login/key`, `/auth/login/party`, which prove the user themselves) is +/// authenticated. pub(crate) fn router(state: AppState, auth_state: AuthState, debug_api: bool) -> Router { let mut api: Router<AppState> = Router::new() .route("/store", get(store::get_store_root)) @@ -118,48 +119,54 @@ pub(crate) fn router(state: AppState, auth_state: AuthState, debug_api: bool) -> } // Inside authentication, which finds the user: what the user may do. - api.layer(middleware::from_fn_with_state( - state.clone(), - access::authorize, - )) - .layer(middleware::from_fn_with_state( - auth_state.clone(), - basic_auth, - )) - // Who has a password here (`/auth/keys`: a user's last key goes only then). - .layer(axum::Extension(auth_state)) - // A stream answered to a token ends with it (expired, revoked, its session ended). - .layer(middleware::from_fn_with_state( - state.clone(), - login::streams_end, - )) - // Outside authentication: a token, if the request brings one, names the user. - .layer(middleware::from_fn_with_state(state.clone(), login::bearer)) - // Outermost: pages of other origins, and their preflights, which bring no - // credentials. - .layer(middleware::from_fn_with_state(state.clone(), cors::cors)) - // The hand-written spec (`docs/openapi.yaml`), and the Swagger UI showing it. - .merge( - // Relative to the UI's page (`/swagger-ui/`), so it is found behind a proxy that - // serves the API under a path of its own too. - SwaggerUi::new("/swagger-ui").config(utoipa_swagger_ui::Config::from("../openapi.yaml")), - ) - .route("/openapi.yaml", get(openapi_spec)) - // Logging in by key: a challenge, and the token for it signed, without a password. - .route("/auth/challenge", axum::routing::post(login::challenge)) - .route("/auth/login/key", axum::routing::post(login::login_key)) - .route("/health", get(health::node_health)) - // To log in to the dashboard on, and the dashboard's page, without authentication - // (they hold nothing). - .route("/login", get(dashboard_login)) - .route("/admin/dashboard", get(dashboard_page)) - .route("/ready", get(health::ready)) - // Outermost, so authentication failures get the error body too. - .layer(middleware::from_fn(json_errors)) - .layer(middleware::from_fn(relative_redirects)) - // A line per request, as it is answered. - .layer(middleware::from_fn(request_log::log_requests)) - .with_state(state) + let router = api + .layer(middleware::from_fn_with_state( + state.clone(), + access::authorize, + )) + .layer(middleware::from_fn_with_state( + auth_state.clone(), + basic_auth, + )) + // Who has a password here (`/auth/keys`: a user's last key goes only then). + .layer(axum::Extension(auth_state)) + // A stream answered to a token ends with it (expired, revoked, its session ended). + .layer(middleware::from_fn_with_state( + state.clone(), + login::streams_end, + )) + // Outside authentication: a token, if the request brings one, names the user. + .layer(middleware::from_fn_with_state(state.clone(), login::bearer)) + // Outermost: pages of other origins, and their preflights, which bring no + // credentials. + .layer(middleware::from_fn_with_state(state.clone(), cors::cors)) + // The hand-written spec (`docs/openapi.yaml`), and the Swagger UI showing it. + .merge( + // Relative to the UI's page (`/swagger-ui/`), so it is found behind a proxy that + // serves the API under a path of its own too. + SwaggerUi::new("/swagger-ui") + .config(utoipa_swagger_ui::Config::from("../openapi.yaml")), + ) + .route("/openapi.yaml", get(openapi_spec)) + // Logging in by key: a challenge, and the token for it signed, without a password. + .route("/auth/challenge", axum::routing::post(login::challenge)) + .route("/auth/login/key", axum::routing::post(login::login_key)); + // A party's login by its key, on a node holding a federated store. + #[cfg(feature = "federation")] + let router = router.route("/auth/login/party", axum::routing::post(login::login_party)); + router + .route("/health", get(health::node_health)) + // To log in to the dashboard on, and the dashboard's page, without authentication + // (they hold nothing). + .route("/login", get(dashboard_login)) + .route("/admin/dashboard", get(dashboard_page)) + .route("/ready", get(health::ready)) + // Outermost, so authentication failures get the error body too. + .layer(middleware::from_fn(json_errors)) + .layer(middleware::from_fn(relative_redirects)) + // A line per request, as it is answered. + .layer(middleware::from_fn(request_log::log_requests)) + .with_state(state) } /// The HTTP router of a node that only relays (`--relay-only`): its figures and the log diff --git a/src/federation/fold.rs b/src/federation/fold.rs index 46dad27..dbe8d4f 100644 --- a/src/federation/fold.rs +++ b/src/federation/fold.rs @@ -221,6 +221,22 @@ impl State { self.latest(&candidates) } + /// The keys that sign for `party` by `current`, whatever they sign: those its version + /// names, and those of its key set as it counts; none where it is no party of it. + pub(crate) fn signing_keys(&self, party: &str, current: &Version) -> Vec<String> { + let mut keys = current + .parties + .get(party) + .map(|given| given.keys.clone()) + .unwrap_or_default(); + for key in self.keys_of(party, current) { + if !keys.contains(&key) { + keys.push(key); + } + } + keys + } + /// The keys of `party` by `current`: those of its key set, or those its version names. pub(crate) fn keys_of(&self, party: &str, current: &Version) -> Vec<String> { let Some(given) = current.parties.get(party) else { diff --git a/src/federation/keys.rs b/src/federation/keys.rs index aff7792..cf0f366 100644 --- a/src/federation/keys.rs +++ b/src/federation/keys.rs @@ -135,6 +135,12 @@ pub(crate) fn node_of(key: &Key) -> Option<String> { /// 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 { + verifies_in(NAMESPACE, key, sig, message) +} + +/// Whether `sig` is `key`'s signature of `message` for `namespace`, spelled as the +/// federation spells one but for its namespace: a party's login (`access::challenge`). +pub(crate) fn verifies_in(namespace: &str, key: &Key, sig: &str, message: &[u8]) -> bool { let Ok(blob) = BASE64.decode(sig) else { return false; }; @@ -143,23 +149,23 @@ pub(crate) fn verifies(key: &Key, sig: &str, message: &[u8]) -> bool { } // 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 { + let Some(signature) = blob.get(written(namespace, key, &[]).len()..) else { return false; }; - if blob != written(key, signature) { + if blob != written(namespace, key, signature) { return false; } match key { Key::Ed25519(public) => { - sshsig::verify_blob(&blob, NAMESPACE, message).is_ok_and(|signer| signer == *public) + sshsig::verify_blob(&blob, namespace, message).is_ok_and(|signer| signer == *public) } - Key::P256(point) => p256_verifies(point, signature, message), + Key::P256(point) => p256_verifies(namespace, 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 { +/// `message` for `namespace`, spelled one way: each mpint its shortest, `s` low. +fn p256_verifies(namespace: &str, point: &[u8; 65], signature: &[u8], message: &[u8]) -> bool { let Some(parsed) = ecdsa_signature(signature) else { return false; }; @@ -167,7 +173,7 @@ fn p256_verifies(point: &[u8; 65], signature: &[u8], message: &[u8]) -> bool { return false; } p256::ecdsa::VerifyingKey::from_sec1_bytes(point) - .is_ok_and(|key| key.verify(&signed(message), &parsed).is_ok()) + .is_ok_and(|key| key.verify(&signed(namespace, message), &parsed).is_ok()) } /// An ECDSA signature from `r` and `s`, SSH's mpints, where each is an integer from 1 to @@ -207,10 +213,35 @@ fn mpints(signature: &p256::ecdsa::Signature) -> Vec<u8> { out } +/// Of `keys`, as the federation spells them, the one whose signature of `message` for +/// `namespace` `signature` is: spelled as the federation spells one but for its namespace, +/// or armored, as `ssh-keygen -Y sign` writes it. None where it is none of theirs. +pub(crate) fn signer<'a>( + keys: &'a [String], + namespace: &str, + signature: &str, + message: &[u8], +) -> Option<&'a str> { + let signature = signature.trim(); + let sig = if signature.starts_with("-----BEGIN") { + BASE64.encode(sshsig::dearmor(signature).ok()?) + } else { + signature.to_owned() + }; + keys.iter() + .find(|line| key(line).is_some_and(|key| verifies_in(namespace, &key, &sig, message))) + .map(String::as_str) +} + /// `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)) + sign_in(NAMESPACE, key, message) +} + +/// As `sign`, for `namespace`. +pub(crate) fn sign_in(namespace: &str, key: &SigningKey, message: &[u8]) -> String { + let blob = sshsig::dearmor(&sshsig::sign(key, namespace, message)) .expect("a signature made here dearmors"); BASE64.encode(blob) } @@ -219,14 +250,24 @@ pub(crate) fn sign(key: &SigningKey, message: &[u8]) -> String { /// 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)) + sign_through_in(NAMESPACE, socket, key, message) +} + +/// As `sign_through`, for `namespace`. +pub(crate) fn sign_through_in( + namespace: &str, + socket: &Path, + key: &Key, + message: &[u8], +) -> Result<String, String> { + let answer = super::agent::sign(socket, &key.blob(), &signed(namespace, message)) .map_err(|why| format!("{}: {why}", key.line()))?; - from_agent(key, &answer, message) + from_agent(namespace, 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> { +/// The signature of `message` for `namespace` by `key` from `answer`, the signature the +/// agent made of what SSHSIG signs, as SSH encodes one. +fn from_agent(namespace: &str, 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())); @@ -241,34 +282,35 @@ fn from_agent(key: &Key, answer: &[u8], message: &[u8]) -> Result<String, String .normalize_s(), ), }; - let sig = BASE64.encode(written(key, &signature)); - if !verifies(key, &sig, message) { + let sig = BASE64.encode(written(namespace, key, &signature)); + if !verifies_in(namespace, 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> { +/// What a signature of `message` for `namespace` is made over: SSHSIG's signed data, hashed +/// with `sha512`. +fn signed(namespace: &str, message: &[u8]) -> Vec<u8> { sshsig::signed_data( - NAMESPACE.as_bytes(), + 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> { +/// The SSHSIG blob of a signature by `key`, of version 1, for `namespace`, its reserved +/// field empty, hashed with `sha512`: as `ssh-keygen` writes it around `signature`, the +/// key type's own. +fn written(namespace: &str, 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, namespace.as_bytes()); string(&mut blob, b""); string(&mut blob, b"sha512"); string(&mut blob, &inner); @@ -281,7 +323,7 @@ fn written(key: &Key, signature: &[u8]) -> Vec<u8> { #[cfg(test)] pub(crate) fn respelled(key: &Key, sig: &str) -> [String; 2] { let blob = BASE64.decode(sig).expect("base64"); - let rs = &blob[written(key, &[]).len()..]; + let rs = &blob[written(NAMESPACE, key, &[]).len()..]; let (r, s) = ecdsa_signature(rs).expect("r and s").split_scalars(); let high = p256::ecdsa::Signature::from_scalars(r, -s).expect("a signature"); let mut reader = Reader(rs); @@ -289,7 +331,7 @@ pub(crate) fn respelled(key: &Key, sig: &str) -> [String; 2] { let mut longer = Vec::new(); string(&mut longer, &[&[0], r].concat()); string(&mut longer, s); - [mpints(&high), longer].map(|numbers| BASE64.encode(written(key, &numbers))) + [mpints(&high), longer].map(|numbers| BASE64.encode(written(NAMESPACE, key, &numbers))) } #[cfg(test)] @@ -368,6 +410,36 @@ mod tests { assert!(!verifies(&public(&key), &elsewhere, b"an event")); } + /// Of a party's keys, the one that signed a login, for the login's namespace: spelled + /// as the federation spells a signature, or armored as `ssh-keygen` writes it; none + /// for another namespace, an event's included, or by another key. + #[test] + fn the_key_a_login_is_signed_with() { + let (tv, laptop) = (signer(6), signer(7)); + let keys = [public(&tv).line(), public(&laptop).line()]; + let login = "continuum-login"; + let sig = sign_in(login, &laptop, b"cc1.challenge"); + assert_eq!( + super::signer(&keys, login, &sig, b"cc1.challenge"), + Some(keys[1].as_str()) + ); + let armored = sshsig::sign(&laptop, login, b"cc1.challenge"); + assert_eq!( + super::signer(&keys, login, &armored, b"cc1.challenge"), + Some(keys[1].as_str()) + ); + assert_eq!(super::signer(&keys, login, &sig, b"cc1.other"), None); + let event = sign(&laptop, b"cc1.challenge"); + assert_eq!(super::signer(&keys, login, &event, b"cc1.challenge"), None); + let stranger = sign_in(login, &signer(8), b"cc1.challenge"); + assert_eq!( + super::signer(&keys, login, &stranger, b"cc1.challenge"), + None + ); + assert!(verifies_in(login, &public(&laptop), &sig, b"cc1.challenge")); + assert!(!verifies(&public(&laptop), &sig, b"cc1.challenge")); + } + #[test] fn a_signature_with_a_reserved_field_is_none() { let key = signer(5); @@ -399,7 +471,7 @@ mod tests { /// 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()..] + &sig[written(NAMESPACE, key, &[]).len()..] } #[test] @@ -410,7 +482,7 @@ mod tests { 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)); + let other = BASE64.encode(written(NAMESPACE, &key, rs)); assert!(!verifies(&key, &other, &message)); assert!(Event::read(ECDSA_WRITE.replace(&sig, &other).as_bytes()).is_none()); }; @@ -421,7 +493,11 @@ mod tests { 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!( + verifying + .verify(&signed(NAMESPACE, &message), &twin) + .is_ok() + ); assert_ne!(twin, ours); assert_eq!(twin.normalize_s(), ours); refused(&mpints(&twin)); @@ -532,7 +608,7 @@ mod tests { message.as_bytes(), ); if let Key::P256(_) = key { - let data = signed(message.as_bytes()); + let data = signed(NAMESPACE, message.as_bytes()); let high = (0..64) .map(|_| { super::super::agent::sign(&socket, &key.blob(), &data).expect("signed") @@ -545,7 +621,7 @@ mod tests { }) .expect("a high `s` among 64 signatures"); checked( - &from_agent(&key, &high, message.as_bytes()).expect("made low"), + &from_agent(NAMESPACE, &key, &high, message.as_bytes()).expect("made low"), message.as_bytes(), ); } |
