//! Page: SSH keys (`/settings/keys`). Only ed25519 and ECDSA keys are accepted. use base64::prelude::{BASE64_STANDARD, BASE64_STANDARD_NO_PAD, Engine as _}; use forge_core::{AuditAction, SshKey}; use serde::Deserialize; use sha2::{Digest, Sha256}; use topcoat::Result; use topcoat::context::{Cx, app_context}; use topcoat::router::content::Form; use topcoat::router::error::{SeeOther, see_other}; use topcoat::router::{page, route}; use topcoat::view::{View, component, view}; use crate::audit::{self, Actor, Target}; use crate::auth::{require_csrf, require_user}; use crate::i18n::{self, Key, Lang, added_line, t, unsupported_key_type}; use crate::state::AppState; use crate::views::{alert, shell, user_facing_message}; /// Algorithms accepted for web-registered keys. `ssh-rsa` is rejected with its own message. const ACCEPTED: &[&str] = &[ "ssh-ed25519", "ecdsa-sha2-nistp256", "ecdsa-sha2-nistp384", "ecdsa-sha2-nistp521", "sk-ssh-ed25519@openssh.com", "sk-ecdsa-sha2-nistp256@openssh.com", ]; const MAX_KEY_CHARS: usize = 16 * 1024; /// Why a pasted key line is refused. `message` says it in the viewer's language. #[derive(Debug, PartialEq, Eq)] pub enum KeyProblem { Empty, TooLong, MissingBody, Rsa, UnsupportedType(String), BadBase64, Truncated, Mismatch, } impl KeyProblem { pub fn message(&self, lang: Lang) -> String { match self { KeyProblem::Empty => t(lang, Key::ErrKeyEmpty).to_owned(), KeyProblem::TooLong => t(lang, Key::ErrKeyTooLong).to_owned(), KeyProblem::MissingBody => t(lang, Key::ErrKeyMissingBody).to_owned(), KeyProblem::Rsa => t(lang, Key::ErrKeyRsa).to_owned(), KeyProblem::UnsupportedType(algorithm) => unsupported_key_type(lang, algorithm), KeyProblem::BadBase64 => t(lang, Key::ErrKeyBadBase64).to_owned(), KeyProblem::Truncated => t(lang, Key::ErrKeyTruncated).to_owned(), KeyProblem::Mismatch => t(lang, Key::ErrKeyMismatch).to_owned(), } } } /// A parsed OpenSSH public key line. #[derive(Debug, PartialEq, Eq)] pub struct ParsedKey { pub algorithm: String, /// Raw wire-format blob (the base64 body, decoded). pub blob: Vec, pub fingerprint: String, pub comment: String, } /// Parses ` [comment]`. Checks that the algorithm is accepted and that /// the blob's embedded algorithm string matches it. pub fn parse_public_key(input: &str) -> std::result::Result { let line = input.trim(); if line.is_empty() { return Err(KeyProblem::Empty); } if line.len() > MAX_KEY_CHARS { return Err(KeyProblem::TooLong); } let mut parts = line.split_whitespace(); let algorithm = parts.next().unwrap_or_default(); let encoded = parts.next().ok_or(KeyProblem::MissingBody)?; let comment = parts.collect::>().join(" "); if algorithm == "ssh-rsa" { return Err(KeyProblem::Rsa); } if !ACCEPTED.contains(&algorithm) { return Err(KeyProblem::UnsupportedType(algorithm.to_owned())); } let blob = BASE64_STANDARD .decode(encoded) .map_err(|_| KeyProblem::BadBase64)?; let embedded = read_ssh_string(&blob).ok_or(KeyProblem::Truncated)?; if embedded != algorithm.as_bytes() { return Err(KeyProblem::Mismatch); } Ok(ParsedKey { algorithm: algorithm.to_owned(), fingerprint: fingerprint(&blob), blob, comment, }) } /// Reads one SSH wire-format string (u32 big-endian length, then bytes) from the start of `buf`. fn read_ssh_string(buf: &[u8]) -> Option<&[u8]> { let len = u32::from_be_bytes(buf.get(..4)?.try_into().ok()?); let end = 4usize.checked_add(usize::try_from(len).ok()?)?; buf.get(4..end) } /// `SHA256:` followed by unpadded base64 of the SHA-256 of the key blob, as `ssh-keygen -l` prints. pub fn fingerprint(blob: &[u8]) -> String { format!( "SHA256:{}", BASE64_STANDARD_NO_PAD.encode(Sha256::digest(blob)) ) } #[derive(Deserialize)] struct AddKeyForm { #[serde(default)] csrf: String, #[serde(default)] title: String, #[serde(default)] public_key: String, } #[derive(Deserialize)] struct DeleteKeyForm { #[serde(default)] csrf: String, #[serde(default)] id: String, } #[component] async fn keys_view( lang: Lang, csrf: &str, keys: Vec, public_key: &str, error: Option, ) -> Result { Ok(view! {

(t(lang, Key::SshKeys))

if keys.is_empty() {

(t(lang, Key::NoSshKeys))

} else {
    for key in keys.into_iter() {
  • (key.title.clone()) (key.algorithm.clone()) (key.fingerprint.clone()) (added_line(lang, key.created_at.as_str(), key.last_used_at.as_deref()))
  • }
}

(t(lang, Key::AddSshKeyTitle))

if let Some(message) = error { alert(message: message.as_str()) }
}) } #[page("/settings/keys")] async fn keys_page(cx: &Cx) -> Result { let viewer = require_user(cx).await?; let lang = i18n::lang(cx, Some(&viewer.0)); let keys = app_context::(cx) .store .list_ssh_keys(&viewer.0.id) .await?; let csrf = viewer.1.csrf_token.clone(); Ok(view! { shell(title: t(lang, Key::SshKeys), viewer: Some(&viewer), keys_view(lang: lang, csrf: csrf.as_str(), keys: keys, public_key: "", error: None)) }) } #[page(POST "/settings/keys")] async fn keys_add(cx: &Cx, Form(form): Form) -> Result { let viewer = require_csrf(cx, &form.csrf).await?; let lang = i18n::lang(cx, Some(&viewer.0)); let state = app_context::(cx); let store = &state.store; let outcome: std::result::Result<(), String> = match parse_public_key(&form.public_key) { Err(problem) => Err(problem.message(lang)), Ok(parsed) => { let title = match form.title.trim() { "" if !parsed.comment.is_empty() => parsed.comment.clone(), "" => parsed.algorithm.clone(), t => t.to_owned(), }; match store .add_ssh_key( &viewer.0.id, &title, &parsed.algorithm, &parsed.blob, &parsed.fingerprint, ) .await { Ok(key) => { audit::record( store, Some(cx), Actor::User(&viewer.0), AuditAction::SshKeyAdded, Target { kind: "ssh_key", id: &key.id, name: &key.title, }, serde_json::Value::Null, ) .await; crate::signatures::on_keys_changed(state, &viewer.0.id).await; return Err(see_other("/settings/keys").into()); } Err(e) => match user_facing_message(&e) { Some(message) => Err(message), None => return Err(e.into()), }, } } }; let message = outcome.err().unwrap_or_default(); let keys = store.list_ssh_keys(&viewer.0.id).await?; let csrf = viewer.1.csrf_token.clone(); Ok(view! { shell(title: t(lang, Key::SshKeys), viewer: Some(&viewer), keys_view(lang: lang, csrf: csrf.as_str(), keys: keys, public_key: form.public_key.as_str(), error: Some(message))) }) } #[route(POST "/settings/keys/delete")] async fn keys_delete(cx: &Cx, Form(form): Form) -> Result { let (user, _) = require_csrf(cx, &form.csrf).await?; let state = app_context::(cx); if state.store.delete_ssh_key(&user.id, &form.id).await? { audit::record( &state.store, Some(cx), Actor::User(&user), AuditAction::SshKeyRemoved, Target { kind: "ssh_key", id: &form.id, name: "", }, serde_json::Value::Null, ) .await; crate::signatures::on_keys_changed(state, &user.id).await; } Ok(see_other("/settings/keys")) } #[cfg(test)] mod tests { use super::*; /// Generated with `ssh-keygen -t ed25519`; fingerprint checked with `ssh-keygen -lf`. const ED25519: &str = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIPTx1OLAmIEVXGSZou6JBQpDthDq02k21xOH+ZjDgGCT test@forge"; const ED25519_FP: &str = "SHA256:9zi5S6OMkaY6rUdUTVRIyH6rwSW8nKKOhu4IInOmbhk"; /// Generated with `ssh-keygen -t ecdsa -b 256`. const ECDSA: &str = "ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBJKn08r7Jqy5wnRekXOHynUfXBt7rcyVJHzTKk+5oGZoBekmIENVjEfl2TlkYwU+9jCSMCQ8nsU2a0bzuWshqk0= tahinli@tFedora"; const ECDSA_FP: &str = "SHA256:0U8otw1ElxrQ6xL2P3888Sd6V2khCb8gXQZa0A2zRx4"; #[test] fn parses_ed25519_and_matches_ssh_keygen_fingerprint() { let parsed = parse_public_key(ED25519).unwrap(); assert_eq!(parsed.algorithm, "ssh-ed25519"); assert_eq!(parsed.comment, "test@forge"); assert_eq!(parsed.fingerprint, ED25519_FP); } #[test] fn parses_ecdsa_and_matches_ssh_keygen_fingerprint() { let parsed = parse_public_key(ECDSA).unwrap(); assert_eq!(parsed.algorithm, "ecdsa-sha2-nistp256"); assert_eq!(parsed.fingerprint, ECDSA_FP); } #[test] fn fingerprint_is_sha256_unpadded_base64() { let fp = fingerprint(b"blob"); assert!(fp.starts_with("SHA256:")); assert!(!fp.ends_with('=')); assert_eq!(fp, fingerprint(b"blob")); assert_ne!(fp, fingerprint(b"other")); } #[test] fn accepts_the_surrounding_whitespace_and_no_comment() { let bare = ED25519 .split_whitespace() .take(2) .collect::>() .join(" "); let parsed = parse_public_key(&format!(" {bare}\n")).unwrap(); assert_eq!(parsed.comment, ""); assert_eq!(parsed.fingerprint, ED25519_FP); } #[test] fn rejects_rsa_with_the_documented_message() { let rsa = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCn test@host"; assert_eq!(parse_public_key(rsa).unwrap_err(), KeyProblem::Rsa); } #[test] fn rejects_unsupported_types() { let dss = "ssh-dss AAAAB3NzaC1kc3MAAACBAP test@host"; assert_eq!( parse_public_key(dss).unwrap_err(), KeyProblem::UnsupportedType("ssh-dss".into()) ); } #[test] fn rejects_algorithm_that_does_not_match_the_blob() { // Real ed25519 body, relabelled as ECDSA. let relabelled = ED25519.replacen("ssh-ed25519", "ecdsa-sha2-nistp256", 1); assert_eq!( parse_public_key(&relabelled).unwrap_err(), KeyProblem::Mismatch ); } #[test] fn rejects_bad_base64_truncated_and_empty_input() { assert!(parse_public_key("ssh-ed25519 !!!notbase64").is_err()); assert_eq!( parse_public_key("ssh-ed25519 AAAA").unwrap_err(), KeyProblem::Truncated ); assert!(parse_public_key(" ").is_err()); assert!(parse_public_key("ssh-ed25519").is_err()); let huge = format!("ssh-ed25519 {}", "A".repeat(MAX_KEY_CHARS)); assert_eq!(parse_public_key(&huge).unwrap_err(), KeyProblem::TooLong); } #[test] fn rejects_a_length_prefix_past_the_end_of_the_blob() { // Length prefix claims 255 bytes but only 4 follow. let body = BASE64_STANDARD.encode([0u8, 0, 0, 255, b's', b's', b'h', b'!']); let line = format!("ssh-ed25519 {body}"); assert!(parse_public_key(&line).is_err()); } }