diff --git a/src/app.rs b/src/app.rs index 3a1e643..48a08a1 100644 --- a/src/app.rs +++ b/src/app.rs @@ -1,4 +1,6 @@ -use crate::core::ssh::{SshCommand, SshEvent, SshSession, spawn_ssh_session}; +use crate::core::ssh::{ + HostKeyDecision, HostKeyPrompt, SshCommand, SshEvent, SshSession, spawn_ssh_session, +}; use crate::core::terminal::TerminalState; use crate::i18n::tr; use crate::storage::gist_sync::{ @@ -6,6 +8,9 @@ use crate::storage::gist_sync::{ fetch_vault_gist, find_existing_vault_gist, load_sync_config, merge_vaults, save_sync_config, update_vault_gist, }; +use crate::storage::known_hosts::{ + HostKeyCheckResult, KnownHostEntry, load_os_known_hosts, now_unix_secs, remove_os_known_host, +}; use crate::storage::ssh_config::{find_unimported_ssh_hosts, import_ssh_config_into_vault}; use crate::storage::store::{ AppSettings, default_settings_path, default_sync_config_path, default_vault_path, @@ -16,6 +21,7 @@ use crate::ui::background::paint_backdrop; use crate::ui::connecting::{ConnectingAction, render_connecting_screen}; use crate::ui::host_grid::{HostGridAction, HostSortMode, HostViewMode, render_host_grid}; use crate::ui::host_modal::{HostModalAction, HostModalState, render_host_panel}; +use crate::ui::icons::{self, IconStyle}; use crate::ui::settings_modal::{ SettingsModalState, SyncOnboardingStep, SyncUiAction, render_settings_modal, }; @@ -95,6 +101,12 @@ pub struct RustmiusApp { master_password: Option, sync_tx: mpsc::UnboundedSender, sync_rx: mpsc::UnboundedReceiver, + pending_host_key: Option, +} + +struct PendingHostKey { + prompt: HostKeyPrompt, + reply: std::sync::Arc>>>, } impl RustmiusApp { @@ -159,6 +171,7 @@ impl RustmiusApp { master_password, sync_tx, sync_rx, + pending_host_key: None, }; if initial_pull { app.spawn_pull(cc.egui_ctx.clone()); @@ -373,7 +386,14 @@ impl RustmiusApp { fn connect_host(&mut self, host: Host, ctx: &egui::Context) { let id = Uuid::new_v4(); - let ssh = spawn_ssh_session(self.rt.handle(), host.clone(), 80, 24, ctx.clone()); + let ssh = spawn_ssh_session( + self.rt.handle(), + host.clone(), + 80, + 24, + self.vault.known_hosts.clone(), + ctx.clone(), + ); let initial_log = format!( "Connecting to {}@{}:{}...", host.username, host.hostname, host.port @@ -448,6 +468,9 @@ impl RustmiusApp { .as_bytes(), ); } + SshEvent::HostKeyVerification(prompt, reply) => { + self.pending_host_key = Some(PendingHostKey { prompt, reply }); + } } } } @@ -592,6 +615,603 @@ fn placeholder(ui: &mut egui::Ui, text: &str) { ); } +impl RustmiusApp { + fn render_host_key_modal(&mut self, ctx: &egui::Context) { + let Some(pending) = self.pending_host_key.take() else { + return; + }; + let s = tr(self.app_settings.language); + let mut decision: Option = None; + let is_changed = matches!(pending.prompt.status, HostKeyCheckResult::Changed { .. }); + + let screen = ctx.content_rect(); + egui::Area::new(egui::Id::new("host_key_backdrop")) + .order(egui::Order::Middle) + .fixed_pos(screen.min) + .show(ctx, |ui| { + let _ = ui.allocate_response(screen.size(), egui::Sense::click()); + ui.painter() + .rect_filled(screen, 0.0, Color32::from_black_alpha(95)); + }); + + let modal_w = (screen.width() - 64.0).min(520.0); + let modal_h = if is_changed { 386.0 } else { 276.0 }; + let modal_rect = egui::Rect::from_center_size(screen.center(), vec2(modal_w, modal_h)); + + egui::Area::new(egui::Id::new("host_key_modal")) + .order(egui::Order::Foreground) + .fixed_pos(modal_rect.min) + .show(ctx, |ui| { + let (rect, _) = + ui.allocate_exact_size(vec2(modal_w, modal_h), egui::Sense::hover()); + let painter = ui.painter(); + painter.rect_filled( + rect.translate(vec2(0.0, 6.0)), + CornerRadius::same(12), + Color32::from_black_alpha(45), + ); + painter.rect_filled( + rect, + CornerRadius::same(12), + Color32::from_rgb(0xE8, 0xED, 0xEF), + ); + painter.rect_stroke( + rect, + CornerRadius::same(12), + Stroke::new(1.0, theme::shade(24)), + egui::StrokeKind::Inside, + ); + + // Header bar + let header_h = 48.0; + let header = egui::Rect::from_min_size(rect.min, vec2(modal_w, header_h)); + painter.hline( + header.x_range(), + header.bottom(), + Stroke::new(1.0, theme::SEPARATOR), + ); + let header_icon_color = if is_changed { + theme::DANGER + } else { + theme::ACCENT_BLUE + }; + icons::paint( + painter, + egui::pos2(header.left() + 24.0, header.center().y), + icons::regular::VAULT, + 17.0, + header_icon_color, + IconStyle::Regular, + ); + let title = if is_changed { + s.kh_modal_changed_title + } else { + s.kh_modal_unknown_title + }; + painter.text( + egui::pos2(header.left() + 42.0, header.center().y), + Align2::LEFT_CENTER, + title, + theme::semibold(14.5), + theme::TEXT_PRIMARY, + ); + + let close_r = egui::Rect::from_center_size( + egui::pos2(header.right() - 24.0, header.center().y), + vec2(28.0, 28.0), + ); + let close_resp = ui + .interact( + close_r, + ui.id().with("kh_modal_close"), + egui::Sense::click(), + ) + .on_hover_cursor(CursorIcon::PointingHand); + if close_resp.hovered() { + painter.rect_filled(close_r, CornerRadius::same(6), theme::shade(16)); + } + icons::paint( + painter, + close_r.center(), + icons::regular::X, + 14.0, + theme::TEXT_MUTED, + IconStyle::Regular, + ); + if close_resp.clicked() { + decision = Some(HostKeyDecision::Cancel); + } + + // Footer bar separator + let footer_h = 64.0; + let footer_rect = egui::Rect::from_min_max( + egui::pos2(rect.left(), rect.bottom() - footer_h), + rect.max, + ); + painter.hline( + footer_rect.x_range(), + footer_rect.top(), + Stroke::new(1.0, theme::SEPARATOR), + ); + + // Body + let body_rect = egui::Rect::from_min_max( + egui::pos2(rect.left() + 20.0, header.bottom() + 16.0), + egui::pos2(rect.right() - 20.0, footer_rect.top() - 12.0), + ); + let mut child = ui.new_child( + egui::UiBuilder::new() + .max_rect(body_rect) + .layout(egui::Layout::top_down(egui::Align::LEFT)), + ); + + if let HostKeyCheckResult::Changed { + old_fingerprint, + old_algorithm, + } = &pending.prompt.status + { + egui::Frame::NONE + .fill(Color32::from_rgb(0xFC, 0xE8, 0xE8)) + .stroke(Stroke::new(1.0, Color32::from_rgb(0xF5, 0xA3, 0xA3))) + .corner_radius(CornerRadius::same(10)) + .inner_margin(egui::Margin::symmetric(14, 10)) + .show(&mut child, |ui| { + ui.set_width(ui.available_width()); + ui.label( + RichText::new(s.kh_modal_changed_banner) + .font(theme::semibold(13.0)) + .color(Color32::from_rgb(0xB9, 0x1C, 0x1C)), + ); + ui.add_space(2.0); + ui.label( + RichText::new(s.kh_modal_changed_desc) + .font(theme::regular(12.0)) + .color(Color32::from_rgb(0x7F, 0x1D, 0x1D)), + ); + }); + child.add_space(12.0); + + egui::Frame::NONE + .fill(theme::light(110)) + .stroke(Stroke::new(1.0, theme::shade(14))) + .corner_radius(CornerRadius::same(10)) + .inner_margin(egui::Margin::same(14)) + .show(&mut child, |ui| { + ui.set_width(ui.available_width()); + ui.horizontal(|ui| { + ui.label( + RichText::new(format!("{}:", s.kh_host_label)) + .font(theme::medium(12.0)) + .color(theme::TEXT_MUTED), + ); + ui.label( + RichText::new(format!( + "{}:{}", + pending.prompt.host, pending.prompt.port + )) + .font(theme::semibold(13.0)) + .color(theme::TEXT_PRIMARY), + ); + }); + ui.add_space(8.0); + ui.label( + RichText::new(format!("{} ({old_algorithm})", s.kh_old_key_label)) + .font(theme::medium(11.5)) + .color(theme::TEXT_MUTED), + ); + ui.label( + RichText::new(old_fingerprint) + .monospace() + .size(11.5) + .color(theme::TEXT_MUTED), + ); + ui.add_space(8.0); + ui.label( + RichText::new(format!( + "{} ({})", + s.kh_new_key_label, pending.prompt.algorithm + )) + .font(theme::medium(11.5)) + .color(Color32::from_rgb(0xB9, 0x1C, 0x1C)), + ); + ui.label( + RichText::new(&pending.prompt.fingerprint_sha256) + .monospace() + .size(11.5) + .color(theme::TEXT_PRIMARY), + ); + }); + } else { + child.label( + RichText::new(s.kh_modal_unknown_desc) + .font(theme::regular(12.5)) + .color(theme::TEXT_MUTED), + ); + child.add_space(12.0); + + egui::Frame::NONE + .fill(theme::light(110)) + .stroke(Stroke::new(1.0, theme::shade(14))) + .corner_radius(CornerRadius::same(10)) + .inner_margin(egui::Margin::same(14)) + .show(&mut child, |ui| { + ui.set_width(ui.available_width()); + ui.horizontal(|ui| { + ui.label( + RichText::new(format!("{}:", s.kh_host_label)) + .font(theme::medium(12.0)) + .color(theme::TEXT_MUTED), + ); + ui.label( + RichText::new(format!( + "{}:{}", + pending.prompt.host, pending.prompt.port + )) + .font(theme::semibold(13.0)) + .color(theme::TEXT_PRIMARY), + ); + ui.add_space(4.0); + egui::Frame::NONE + .fill(theme::shade(12)) + .corner_radius(CornerRadius::same(4)) + .inner_margin(egui::Margin::symmetric(6, 2)) + .show(ui, |ui| { + ui.label( + RichText::new(&pending.prompt.algorithm) + .font(theme::medium(11.0)) + .color(theme::TEXT_MUTED), + ); + }); + }); + ui.add_space(8.0); + ui.label( + RichText::new(s.kh_fingerprint_label) + .font(theme::medium(11.5)) + .color(theme::TEXT_MUTED), + ); + ui.add_space(2.0); + ui.label( + RichText::new(&pending.prompt.fingerprint_sha256) + .monospace() + .size(12.0) + .color(theme::TEXT_PRIMARY), + ); + }); + } + + // Footer action buttons (centered vertically inside dedicated footer bar) + let footer_inner = egui::Rect::from_min_max( + egui::pos2(footer_rect.left() + 20.0, footer_rect.top() + 14.0), + egui::pos2(footer_rect.right() - 20.0, footer_rect.bottom() - 14.0), + ); + let mut footer_ui = ui.new_child( + egui::UiBuilder::new() + .max_rect(footer_inner) + .layout(egui::Layout::left_to_right(egui::Align::Center)), + ); + footer_ui.spacing_mut().button_padding = vec2(14.0, 0.0); + footer_ui.spacing_mut().item_spacing.x = 8.0; + + let secondary_btn = |ui: &mut egui::Ui, label: &str| { + ui.add( + egui::Button::new( + RichText::new(label) + .font(theme::semibold(13.0)) + .color(theme::TEXT_PRIMARY), + ) + .fill(theme::shade(18)) + .stroke(Stroke::NONE) + .corner_radius(CornerRadius::same(7)) + .min_size(vec2(0.0, 36.0)), + ) + .on_hover_cursor(CursorIcon::PointingHand) + }; + + // Cancel on the left + let cancel_label = if is_changed { + s.kh_btn_cancel_conn + } else { + s.kh_btn_cancel + }; + if secondary_btn(&mut footer_ui, cancel_label).clicked() { + decision = Some(HostKeyDecision::Cancel); + } + + // Primary + Allow once on the right + footer_ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + ui.spacing_mut().button_padding = vec2(14.0, 0.0); + ui.spacing_mut().item_spacing.x = 8.0; + if is_changed { + if ui + .add( + egui::Button::new( + RichText::new(s.kh_btn_replace) + .font(theme::semibold(13.0)) + .color(Color32::WHITE), + ) + .fill(theme::DANGER) + .stroke(Stroke::NONE) + .corner_radius(CornerRadius::same(7)) + .min_size(vec2(0.0, 36.0)), + ) + .on_hover_cursor(CursorIcon::PointingHand) + .clicked() + { + decision = Some(HostKeyDecision::TrustAndSave); + } + if secondary_btn(ui, s.kh_btn_once).clicked() { + decision = Some(HostKeyDecision::AllowOnce); + } + } else { + if ui + .add( + egui::Button::new( + RichText::new(s.kh_btn_add) + .font(theme::semibold(13.0)) + .color(Color32::WHITE), + ) + .fill(theme::ACCENT_BLUE) + .stroke(Stroke::NONE) + .corner_radius(CornerRadius::same(7)) + .min_size(vec2(0.0, 36.0)), + ) + .on_hover_cursor(CursorIcon::PointingHand) + .clicked() + { + decision = Some(HostKeyDecision::TrustAndSave); + } + if secondary_btn(ui, s.kh_btn_once).clicked() { + decision = Some(HostKeyDecision::AllowOnce); + } + } + }); + }); + + if let Some(dec) = decision { + if dec == HostKeyDecision::TrustAndSave { + let entry = KnownHostEntry { + host: pending.prompt.host.clone(), + port: pending.prompt.port, + algorithm: pending.prompt.algorithm.clone(), + public_key_b64: pending.prompt.public_key_b64.clone(), + fingerprint_sha256: pending.prompt.fingerprint_sha256.clone(), + added_at: now_unix_secs(), + }; + self.vault.known_hosts.retain(|e| { + !(e.host.eq_ignore_ascii_case(&entry.host) && e.port == entry.port) + }); + self.vault.known_hosts.push(entry); + self.persist_vault(Some(ctx)); + } + if let Ok(mut guard) = pending.reply.lock() + && let Some(tx) = guard.take() + { + let _ = tx.send(dec); + } + } else { + self.pending_host_key = Some(pending); + } + } + + fn render_known_hosts_view(&mut self, ui: &mut egui::Ui, ctx: &egui::Context) { + let s = tr(self.app_settings.language); + let os_entries = load_os_known_hosts(); + let mut combined: Vec<(KnownHostEntry, bool)> = self + .vault + .known_hosts + .iter() + .cloned() + .map(|e| (e, true)) + .collect(); + for os_e in os_entries { + if !combined + .iter() + .any(|(e, _)| e.host.eq_ignore_ascii_case(&os_e.host) && e.port == os_e.port) + { + combined.push((os_e, false)); + } + } + + let mut to_remove: Option<(String, u16)> = None; + + egui::Frame::NONE + .inner_margin(egui::Margin::symmetric(24, 20)) + .show(ui, |ui| { + // Header + ui.horizontal(|ui| { + ui.label( + RichText::new(s.nav_known_hosts) + .font(theme::semibold(18.0)) + .color(theme::TEXT_PRIMARY), + ); + ui.add_space(6.0); + egui::Frame::NONE + .fill(theme::shade(14)) + .corner_radius(CornerRadius::same(10)) + .inner_margin(egui::Margin::symmetric(8, 2)) + .show(ui, |ui| { + ui.label( + RichText::new(combined.len().to_string()) + .font(theme::semibold(11.5)) + .color(theme::TEXT_MUTED), + ); + }); + }); + ui.add_space(4.0); + ui.label( + RichText::new(s.kh_subtitle) + .font(theme::regular(12.5)) + .color(theme::TEXT_MUTED), + ); + ui.add_space(16.0); + + if combined.is_empty() { + ui.vertical_centered(|ui| { + ui.add_space(60.0); + ui.label( + RichText::new(icons::regular::GLOBE) + .font(icons::font(36.0, IconStyle::Regular)) + .color(theme::TEXT_MUTED), + ); + ui.add_space(8.0); + ui.label( + RichText::new(s.kh_empty) + .font(theme::medium(13.5)) + .color(theme::TEXT_MUTED), + ); + }); + return; + } + + egui::ScrollArea::vertical() + .auto_shrink([false, false]) + .show(ui, |ui| { + for (entry, in_vault) in &combined { + egui::Frame::NONE + .fill(theme::light(115)) + .stroke(Stroke::new(1.0, theme::shade(16))) + .corner_radius(CornerRadius::same(10)) + .inner_margin(egui::Margin::symmetric(16, 12)) + .show(ui, |ui| { + ui.set_width(ui.available_width()); + ui.horizontal(|ui| { + // Left icon badge + let (icon_rect, _) = ui.allocate_exact_size( + vec2(36.0, 36.0), + egui::Sense::hover(), + ); + ui.painter().rect_filled( + icon_rect, + CornerRadius::same(8), + theme::shade(10), + ); + icons::paint( + ui.painter(), + icon_rect.center(), + if *in_vault { + icons::regular::VAULT + } else { + icons::regular::GLOBE + }, + 18.0, + if *in_vault { + theme::ACCENT_BLUE + } else { + theme::ICON_DARK + }, + IconStyle::Regular, + ); + + ui.add_space(8.0); + + // Host info + ui.vertical(|ui| { + ui.horizontal(|ui| { + let host_label = if entry.port == 22 { + entry.host.clone() + } else { + format!("{}:{}", entry.host, entry.port) + }; + ui.label( + RichText::new(host_label) + .font(theme::semibold(13.5)) + .color(theme::TEXT_PRIMARY), + ); + ui.add_space(4.0); + egui::Frame::NONE + .fill(theme::shade(12)) + .corner_radius(CornerRadius::same(4)) + .inner_margin(egui::Margin::symmetric(6, 2)) + .show(ui, |ui| { + ui.label( + RichText::new(&entry.algorithm) + .font(theme::medium(10.5)) + .color(theme::TEXT_MUTED), + ); + }); + let (src_text, src_bg, src_fg) = if *in_vault { + ( + s.kh_source_vault_os, + Color32::from_rgba_unmultiplied( + 0x24, 0x96, 0xEE, 28, + ), + theme::ACCENT_BLUE, + ) + } else { + ( + s.kh_source_os, + theme::shade(10), + theme::TEXT_MUTED, + ) + }; + egui::Frame::NONE + .fill(src_bg) + .corner_radius(CornerRadius::same(4)) + .inner_margin(egui::Margin::symmetric(6, 2)) + .show(ui, |ui| { + ui.label( + RichText::new(src_text) + .font(theme::medium(10.5)) + .color(src_fg), + ); + }); + }); + ui.add_space(3.0); + ui.label( + RichText::new(&entry.fingerprint_sha256) + .monospace() + .size(11.5) + .color(theme::TEXT_MUTED), + ); + }); + + // Right delete button + ui.with_layout( + egui::Layout::right_to_left(egui::Align::Center), + |ui| { + let del_btn = ui + .add( + egui::Button::new( + RichText::new(s.kh_delete) + .font(theme::medium(12.0)) + .color(theme::DANGER), + ) + .fill(Color32::from_rgba_unmultiplied( + 0xEF, 0x44, 0x44, 18, + )) + .stroke(Stroke::new( + 1.0, + Color32::from_rgba_unmultiplied( + 0xEF, 0x44, 0x44, 55, + ), + )) + .corner_radius(CornerRadius::same(6)) + .min_size(vec2(0.0, 28.0)), + ) + .on_hover_cursor(CursorIcon::PointingHand); + if del_btn.clicked() { + to_remove = + Some((entry.host.clone(), entry.port)); + } + }, + ); + }); + }); + ui.add_space(8.0); + } + }); + }); + + if let Some((h, p)) = to_remove { + self.vault + .known_hosts + .retain(|e| !(e.host.eq_ignore_ascii_case(&h) && e.port == p)); + let _ = remove_os_known_host(&h, p); + self.persist_vault(Some(ctx)); + } + } +} + impl eframe::App for RustmiusApp { fn clear_color(&self, _visuals: &egui::Visuals) -> [f32; 4] { theme::BG_BASE.to_normalized_gamma_f32() @@ -950,7 +1570,7 @@ impl eframe::App for RustmiusApp { placeholder(ui, &format!("{} — {}", s.nav_snippets, s.coming_soon)) } NavSection::KnownHosts => { - placeholder(ui, &format!("{} — {}", s.nav_known_hosts, s.coming_soon)) + self.render_known_hosts_view(ui, ctx); } NavSection::Logs => { placeholder(ui, &format!("{} — {}", s.nav_logs, s.coming_soon)) @@ -971,6 +1591,7 @@ impl eframe::App for RustmiusApp { if settings_changed { let _ = save_app_settings(&self.settings_path, &self.app_settings); } + self.render_host_key_modal(ctx); match sync_action { SyncUiAction::CreateNew { token, password } => { self.spawn_create_sync(token, password, ctx.clone()); diff --git a/src/core/ssh.rs b/src/core/ssh.rs index d7a07c5..7d9ccdf 100644 --- a/src/core/ssh.rs +++ b/src/core/ssh.rs @@ -1,3 +1,6 @@ +use crate::storage::known_hosts::{ + HostKeyCheckResult, KnownHostEntry, extract_key_info, upsert_os_known_host, verify_host_key, +}; use crate::storage::{AuthMethod, Host, OsKind}; use anyhow::{Context, Result}; use russh::client::{self, Handle}; @@ -14,6 +17,23 @@ pub enum SshCommand { Close, } +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum HostKeyDecision { + TrustAndSave, + AllowOnce, + Cancel, +} + +#[derive(Debug, Clone)] +pub struct HostKeyPrompt { + pub host: String, + pub port: u16, + pub algorithm: String, + pub public_key_b64: String, + pub fingerprint_sha256: String, + pub status: HostKeyCheckResult, +} + #[derive(Debug)] pub enum SshEvent { Connected, @@ -21,6 +41,10 @@ pub enum SshEvent { Output(Vec), Error(String), Closed, + HostKeyVerification( + HostKeyPrompt, + Arc>>>, + ), } pub struct SshSession { @@ -35,17 +59,64 @@ impl SshSession { } } -struct ClientHandler; +struct ClientHandler { + host: String, + port: u16, + vault_known_hosts: Vec, + evt_tx: mpsc::UnboundedSender, + ctx: egui::Context, +} impl client::Handler for ClientHandler { type Error = russh::Error; async fn check_server_key( &mut self, - _server_public_key: &russh::keys::PublicKeyOrCertificate, + server_public_key: &russh::keys::PublicKeyOrCertificate, ) -> Result { - // TODO: verify ~/.ssh/known_hosts and prompt for TOFU confirmation - Ok(true) + let status = verify_host_key( + &self.host, + self.port, + server_public_key, + &self.vault_known_hosts, + ); + if matches!(status, HostKeyCheckResult::Trusted) { + return Ok(true); + } + + let (algorithm, public_key_b64, fingerprint_sha256) = extract_key_info(server_public_key); + let prompt = HostKeyPrompt { + host: self.host.clone(), + port: self.port, + algorithm: algorithm.clone(), + public_key_b64: public_key_b64.clone(), + fingerprint_sha256, + status, + }; + + let (tx, rx) = tokio::sync::oneshot::channel(); + let reply = Arc::new(std::sync::Mutex::new(Some(tx))); + if self + .evt_tx + .send(SshEvent::HostKeyVerification(prompt, reply)) + .is_err() + { + return Ok(false); + } + self.ctx.request_repaint(); + + match rx.await { + Ok(HostKeyDecision::TrustAndSave) => { + if let Err(err) = + upsert_os_known_host(&self.host, self.port, &algorithm, &public_key_b64) + { + tracing::warn!("Failed to update ~/.ssh/known_hosts: {err:#}"); + } + Ok(true) + } + Ok(HostKeyDecision::AllowOnce) => Ok(true), + Ok(HostKeyDecision::Cancel) | Err(_) => Ok(false), + } } } @@ -54,13 +125,24 @@ pub fn spawn_ssh_session( host: Host, cols: u32, rows: u32, + vault_known_hosts: Vec, ctx: egui::Context, ) -> SshSession { let (cmd_tx, cmd_rx) = mpsc::unbounded_channel(); let (evt_tx, evt_rx) = mpsc::unbounded_channel(); let join_handle = rt.spawn(async move { - if let Err(err) = run_ssh(host, cols, rows, cmd_rx, evt_tx.clone(), ctx.clone()).await { + if let Err(err) = run_ssh( + host, + cols, + rows, + vault_known_hosts, + cmd_rx, + evt_tx.clone(), + ctx.clone(), + ) + .await + { let _ = evt_tx.send(SshEvent::Error(format!("{err:#}"))); ctx.request_repaint(); } @@ -191,24 +273,30 @@ async fn run_ssh( host: Host, cols: u32, rows: u32, + vault_known_hosts: Vec, mut cmd_rx: mpsc::UnboundedReceiver, evt_tx: mpsc::UnboundedSender, ctx: egui::Context, ) -> Result<()> { let config = Arc::new(client::Config::default()); let addr = format!("{}:{}", host.hostname, host.port); - let mut session = tokio::time::timeout( - CONNECT_TIMEOUT, - client::connect(config, &addr, ClientHandler), - ) - .await - .map_err(|_| { - anyhow::anyhow!( - "Connection timed out to {addr} after {}s", - CONNECT_TIMEOUT.as_secs() - ) - })? - .with_context(|| format!("TCP connection failed to {addr}"))?; + let handler = ClientHandler { + host: host.hostname.clone(), + port: host.port, + vault_known_hosts, + evt_tx: evt_tx.clone(), + ctx: ctx.clone(), + }; + let mut session = + tokio::time::timeout(CONNECT_TIMEOUT, client::connect(config, &addr, handler)) + .await + .map_err(|_| { + anyhow::anyhow!( + "Connection timed out to {addr} after {}s", + CONNECT_TIMEOUT.as_secs() + ) + })? + .with_context(|| format!("TCP connection failed to {addr}"))?; if !authenticate(&mut session, &host).await? { anyhow::bail!("SSH authentication failed for {}@{addr}", host.username); diff --git a/src/i18n.rs b/src/i18n.rs index 4f8e26e..36be26d 100644 --- a/src/i18n.rs +++ b/src/i18n.rs @@ -144,6 +144,27 @@ pub struct Strings { pub unlock_title: &'static str, pub unlock_desc: &'static str, pub unlock_btn: &'static str, + + // Known Hosts & Host Key Verification + pub kh_subtitle: &'static str, + pub kh_empty: &'static str, + pub kh_source_vault_os: &'static str, + pub kh_source_os: &'static str, + pub kh_delete: &'static str, + pub kh_modal_unknown_title: &'static str, + pub kh_modal_unknown_desc: &'static str, + pub kh_modal_changed_title: &'static str, + pub kh_modal_changed_banner: &'static str, + pub kh_modal_changed_desc: &'static str, + pub kh_host_label: &'static str, + pub kh_fingerprint_label: &'static str, + pub kh_old_key_label: &'static str, + pub kh_new_key_label: &'static str, + pub kh_btn_add: &'static str, + pub kh_btn_once: &'static str, + pub kh_btn_cancel: &'static str, + pub kh_btn_cancel_conn: &'static str, + pub kh_btn_replace: &'static str, } pub const EN: Strings = Strings { @@ -262,6 +283,26 @@ pub const EN: Strings = Strings { unlock_title: "Unlock Sync Vault", unlock_desc: "Enter your master password to unlock and sync your vault.", unlock_btn: "Unlock", + + kh_subtitle: "Synced with ~/.ssh/known_hosts and your GitHub Gist vault.", + kh_empty: "No known hosts saved yet.", + kh_source_vault_os: "Vault + OS", + kh_source_os: "OS (~/.ssh/known_hosts)", + kh_delete: "Remove", + kh_modal_unknown_title: "Unknown Host Key", + kh_modal_unknown_desc: "The authenticity of this host cannot be established yet. Verify the fingerprint before continuing.", + kh_modal_changed_title: "Host Key Changed", + kh_modal_changed_banner: "Warning: This host's public key has changed!", + kh_modal_changed_desc: "This could indicate a Man-in-the-Middle attack, or that the server's SSH host key was regenerated or reinstalled.", + kh_host_label: "Host", + kh_fingerprint_label: "SHA-256 Fingerprint", + kh_old_key_label: "Previous key", + kh_new_key_label: "New key", + kh_btn_add: "Add new host", + kh_btn_once: "Allow once", + kh_btn_cancel: "Cancel", + kh_btn_cancel_conn: "Cancel connection", + kh_btn_replace: "Replace old key", }; pub const FR: Strings = Strings { @@ -380,6 +421,26 @@ pub const FR: Strings = Strings { unlock_title: "Déverrouiller Sync Vault", unlock_desc: "Entrez votre mot de passe maître pour déverrouiller et synchroniser votre coffre.", unlock_btn: "Déverrouiller", + + kh_subtitle: "Synchronisé avec ~/.ssh/known_hosts et votre coffre GitHub Gist.", + kh_empty: "Aucun hôte connu enregistré pour le moment.", + kh_source_vault_os: "Coffre + OS", + kh_source_os: "OS (~/.ssh/known_hosts)", + kh_delete: "Supprimer", + kh_modal_unknown_title: "Nouvel hôte inconnu", + kh_modal_unknown_desc: "L'authenticité de cet hôte ne peut pas encore être vérifiée. Contrôlez l'empreinte avant de continuer.", + kh_modal_changed_title: "Clé d'hôte modifiée", + kh_modal_changed_banner: "Attention : la clé publique de cet hôte a changé !", + kh_modal_changed_desc: "Cela peut indiquer une interception (MITM) ou une réinstallation / régénération de la clé SSH du serveur.", + kh_host_label: "Hôte", + kh_fingerprint_label: "Empreinte SHA-256", + kh_old_key_label: "Ancienne clé", + kh_new_key_label: "Nouvelle clé", + kh_btn_add: "Ajouter le nouvel hôte", + kh_btn_once: "Autoriser une fois", + kh_btn_cancel: "Annuler", + kh_btn_cancel_conn: "Annuler la connexion", + kh_btn_replace: "Remplacer l'ancienne clé", }; pub fn tr(lang: Language) -> &'static Strings { diff --git a/src/storage/gist_sync.rs b/src/storage/gist_sync.rs index 5a92cf6..20bb73f 100644 --- a/src/storage/gist_sync.rs +++ b/src/storage/gist_sync.rs @@ -102,11 +102,26 @@ pub fn merge_vaults(local: &Vault, remote: &Vault) -> Vault { .or_insert_with(|| g.clone()); } + let mut known_hosts_map: HashMap<(String, u16), crate::storage::known_hosts::KnownHostEntry> = + HashMap::new(); + for kh in local.known_hosts.iter().chain(remote.known_hosts.iter()) { + let key = (kh.host.to_lowercase(), kh.port); + known_hosts_map + .entry(key) + .and_modify(|existing| { + if kh.added_at > existing.added_at { + *existing = kh.clone(); + } + }) + .or_insert_with(|| kh.clone()); + } + Vault { version: local.version.max(remote.version).max(1), hosts: hosts_map.into_values().collect(), groups: groups_map.into_values().collect(), deleted_hosts, + known_hosts: known_hosts_map.into_values().collect(), } } @@ -246,12 +261,14 @@ mod tests { hosts: vec![h1], groups: vec![], deleted_hosts: HashMap::new(), + known_hosts: vec![], }; let remote = Vault { version: 1, hosts: vec![h1_newer, h2.clone()], groups: vec![], deleted_hosts: HashMap::new(), + known_hosts: vec![], }; let merged = merge_vaults(&local, &remote); diff --git a/src/storage/known_hosts.rs b/src/storage/known_hosts.rs new file mode 100644 index 0000000..17f1aea --- /dev/null +++ b/src/storage/known_hosts.rs @@ -0,0 +1,225 @@ +use anyhow::{Context, Result}; +use russh::keys::{HashAlg, PublicKey, PublicKeyBase64, PublicKeyOrCertificate}; +use serde::{Deserialize, Serialize}; +use std::path::PathBuf; +use std::time::{SystemTime, UNIX_EPOCH}; + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +pub struct KnownHostEntry { + pub host: String, + pub port: u16, + pub algorithm: String, + pub public_key_b64: String, + pub fingerprint_sha256: String, + pub added_at: u64, +} + +#[derive(Debug, Clone)] +pub enum HostKeyCheckResult { + Trusted, + Unknown, + Changed { + old_fingerprint: String, + old_algorithm: String, + }, +} + +pub fn now_unix_secs() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default() + .as_secs() +} + +pub fn os_known_hosts_path() -> Option { + directories::UserDirs::new().map(|d| d.home_dir().join(".ssh").join("known_hosts")) +} + +pub fn format_host_pattern(host: &str, port: u16) -> String { + if port == 22 { + host.to_string() + } else { + format!("[{host}]:{port}") + } +} + +pub fn extract_key_info(key: &PublicKeyOrCertificate) -> (String, String, String) { + match key { + PublicKeyOrCertificate::PublicKey { key: pk, .. } => ( + pk.algorithm().to_string(), + pk.public_key_base64(), + pk.fingerprint(HashAlg::Sha256).to_string(), + ), + PublicKeyOrCertificate::Certificate(cert) => { + let pk = PublicKey::new(cert.public_key().clone(), ""); + ( + pk.algorithm().to_string(), + pk.public_key_base64(), + pk.fingerprint(HashAlg::Sha256).to_string(), + ) + } + } +} + +fn parse_host_token(token: &str) -> Option<(String, u16)> { + if token.starts_with('|') { + // Hashed known_hosts entry; skip for plain-text listing. + return None; + } + if let Some(rest) = token.strip_prefix('[') + && let Some((host, port_str)) = rest.split_once("]:") + && let Ok(port) = port_str.parse::() + { + return Some((host.to_string(), port)); + } + Some((token.to_string(), 22)) +} + +fn line_matches_host(line: &str, host: &str, port: u16) -> bool { + let trimmed = line.trim(); + if trimmed.is_empty() || trimmed.starts_with('#') || trimmed.starts_with('@') { + return false; + } + let Some(hosts_part) = trimmed.split_whitespace().next() else { + return false; + }; + hosts_part + .split(',') + .filter_map(parse_host_token) + .any(|(h, p)| h.eq_ignore_ascii_case(host) && p == port) +} + +pub fn load_os_known_hosts() -> Vec { + let Some(path) = os_known_hosts_path() else { + return Vec::new(); + }; + let Ok(content) = std::fs::read_to_string(path) else { + return Vec::new(); + }; + + let mut entries = Vec::new(); + for line in content.lines() { + let trimmed = line.trim(); + if trimmed.is_empty() || trimmed.starts_with('#') || trimmed.starts_with('@') { + continue; + } + let mut parts = trimmed.split_whitespace(); + let (Some(hosts_part), Some(algo), Some(key_b64)) = + (parts.next(), parts.next(), parts.next()) + else { + continue; + }; + + let fingerprint_sha256 = PublicKey::from_openssh(&format!("{algo} {key_b64}")) + .map(|pk| pk.fingerprint(HashAlg::Sha256).to_string()) + .unwrap_or_else(|_| "unknown".to_string()); + + for token in hosts_part.split(',') { + if let Some((host, port)) = parse_host_token(token) { + entries.push(KnownHostEntry { + host, + port, + algorithm: algo.to_string(), + public_key_b64: key_b64.to_string(), + fingerprint_sha256: fingerprint_sha256.clone(), + added_at: 0, + }); + } + } + } + entries +} + +pub fn verify_host_key( + host: &str, + port: u16, + key: &PublicKeyOrCertificate, + vault_hosts: &[KnownHostEntry], +) -> HostKeyCheckResult { + let (_algo, key_b64, _fp) = extract_key_info(key); + + // Check vault first, then OS ~/.ssh/known_hosts. + if let Some(entry) = vault_hosts + .iter() + .find(|e| e.host.eq_ignore_ascii_case(host) && e.port == port) + { + if entry.public_key_b64 == key_b64 { + return HostKeyCheckResult::Trusted; + } + return HostKeyCheckResult::Changed { + old_fingerprint: entry.fingerprint_sha256.clone(), + old_algorithm: entry.algorithm.clone(), + }; + } + + let os_hosts = load_os_known_hosts(); + if let Some(entry) = os_hosts + .iter() + .find(|e| e.host.eq_ignore_ascii_case(host) && e.port == port) + { + if entry.public_key_b64 == key_b64 { + return HostKeyCheckResult::Trusted; + } + return HostKeyCheckResult::Changed { + old_fingerprint: entry.fingerprint_sha256.clone(), + old_algorithm: entry.algorithm.clone(), + }; + } + + HostKeyCheckResult::Unknown +} + +pub fn upsert_os_known_host( + host: &str, + port: u16, + algorithm: &str, + public_key_b64: &str, +) -> Result<()> { + let path = os_known_hosts_path().context("Could not determine home directory")?; + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent).context("Failed to create ~/.ssh directory")?; + } + + let mut lines: Vec = if path.exists() { + std::fs::read_to_string(&path) + .unwrap_or_default() + .lines() + .filter(|l| !line_matches_host(l, host, port)) + .map(|l| l.to_string()) + .collect() + } else { + Vec::new() + }; + + let pattern = format_host_pattern(host, port); + lines.push(format!("{pattern} {algorithm} {public_key_b64}")); + + let mut out = lines.join("\n"); + if !out.ends_with('\n') { + out.push('\n'); + } + std::fs::write(&path, out).context("Failed to write ~/.ssh/known_hosts")?; + Ok(()) +} + +pub fn remove_os_known_host(host: &str, port: u16) -> Result<()> { + let Some(path) = os_known_hosts_path() else { + return Ok(()); + }; + if !path.exists() { + return Ok(()); + } + let lines: Vec = std::fs::read_to_string(&path) + .unwrap_or_default() + .lines() + .filter(|l| !line_matches_host(l, host, port)) + .map(|l| l.to_string()) + .collect(); + + let mut out = lines.join("\n"); + if !out.is_empty() && !out.ends_with('\n') { + out.push('\n'); + } + std::fs::write(&path, out).context("Failed to update ~/.ssh/known_hosts")?; + Ok(()) +} diff --git a/src/storage/mod.rs b/src/storage/mod.rs index 3d511d5..aea25ff 100644 --- a/src/storage/mod.rs +++ b/src/storage/mod.rs @@ -1,4 +1,5 @@ pub mod gist_sync; +pub mod known_hosts; pub mod ssh_config; pub mod store; @@ -109,6 +110,8 @@ pub struct Vault { pub groups: Vec, #[serde(default)] pub deleted_hosts: HashMap>, + #[serde(default)] + pub known_hosts: Vec, } impl Vault { @@ -118,6 +121,7 @@ impl Vault { hosts: Vec::new(), groups: Vec::new(), deleted_hosts: HashMap::new(), + known_hosts: Vec::new(), } } }