diff options
| author | salmonik <salmonik@tuta.io> | 2026-10-29 22:22:27 +0100 |
|---|---|---|
| committer | salmonik <salmonik@tuta.io> | 2026-10-29 22:22:27 +0100 |
| commit | f30b1a519771ac49e2b03640e742fdb0a246bd81 (patch) | |
| tree | b9a78039ba55a364e73df5dc174320dc8222f5c3 /src | |
| parent | formatting (diff) | |
| download | zagan-bet-f30b1a519771ac49e2b03640e742fdb0a246bd81.tar.gz zagan-bet-f30b1a519771ac49e2b03640e742fdb0a246bd81.zip | |
v2.4.0: key stored credentials by certificate fingerprint
Diffstat (limited to '')
| -rw-r--r-- | src/bin/client/connection.rs | 34 | ||||
| -rw-r--r-- | src/bin/client/repl.rs | 57 | ||||
| -rw-r--r-- | src/client/database.rs | 116 | ||||
| -rw-r--r-- | src/client/ui.rs | 4 |
4 files changed, 169 insertions, 42 deletions
diff --git a/src/bin/client/connection.rs b/src/bin/client/connection.rs index 44cfea9..ec5642c 100644 --- a/src/bin/client/connection.rs +++ b/src/bin/client/connection.rs | |||
| @@ -56,10 +56,10 @@ pub fn connect( | |||
| 56 | 56 | ||
| 57 | // TOFU: persist the fingerprint on first contact. | 57 | // TOFU: persist the fingerprint on first contact. |
| 58 | if !unsafe_mode { | 58 | if !unsafe_mode { |
| 59 | if let Some(fp) = observed { | 59 | if let Some(fp) = observed.as_deref() { |
| 60 | if database::get_fingerprint(conn, addr).is_none() { | 60 | if database::get_fingerprint(conn, addr).is_none() { |
| 61 | database::save_fingerprint(conn, addr, &fp)?; | 61 | database::save_fingerprint(conn, addr, fp)?; |
| 62 | for line in first_contact_lines(addr, &fp) { | 62 | for line in first_contact_lines(addr, fp) { |
| 63 | println!("{}", line); | 63 | println!("{}", line); |
| 64 | } | 64 | } |
| 65 | } | 65 | } |
| @@ -80,21 +80,25 @@ pub fn connect( | |||
| 80 | elapsed.as_secs_f64() * 1000.0 | 80 | elapsed.as_secs_f64() * 1000.0 |
| 81 | ); | 81 | ); |
| 82 | 82 | ||
| 83 | if let Some((username, password)) = database::get_credentials(conn, addr) { | 83 | // Credentials are stored per server identity, so any address presenting |
| 84 | let auth_msg = format!("AUTH {} {}", username, password); | 84 | // this certificate key can log in with the same stored account. |
| 85 | tls.write_line(&auth_msg)?; | 85 | let identity = observed |
| 86 | let mut auth_response = String::new(); | 86 | .clone() |
| 87 | tls.read_line(&mut auth_response)?; | 87 | .or_else(|| database::get_fingerprint(conn, addr)); |
| 88 | if auth_response.trim().starts_with("OK") { | 88 | if let Some(identity) = identity { |
| 89 | println!("Authenticated as {}", username); | 89 | if let Some((username, password)) = database::get_credentials(conn, &identity) { |
| 90 | Ok((tls, Some(username))) | 90 | let auth_msg = format!("AUTH {} {}", username, password); |
| 91 | } else { | 91 | tls.write_line(&auth_msg)?; |
| 92 | let mut auth_response = String::new(); | ||
| 93 | tls.read_line(&mut auth_response)?; | ||
| 94 | if auth_response.trim().starts_with("OK") { | ||
| 95 | println!("Authenticated as {}", username); | ||
| 96 | return Ok((tls, Some(username))); | ||
| 97 | } | ||
| 92 | println!("Authentication failed: {}", auth_response.trim()); | 98 | println!("Authentication failed: {}", auth_response.trim()); |
| 93 | Ok((tls, None)) | ||
| 94 | } | 99 | } |
| 95 | } else { | ||
| 96 | Ok((tls, None)) | ||
| 97 | } | 100 | } |
| 101 | Ok((tls, None)) | ||
| 98 | } | 102 | } |
| 99 | 103 | ||
| 100 | /// Wrapper so TLS handshake failures surface as errors with their message | 104 | /// Wrapper so TLS handshake failures surface as errors with their message |
diff --git a/src/bin/client/repl.rs b/src/bin/client/repl.rs index 9af4ea9..d973596 100644 --- a/src/bin/client/repl.rs +++ b/src/bin/client/repl.rs | |||
| @@ -245,7 +245,19 @@ impl ClientState { | |||
| 245 | Effect::ForgetHost(target) => { | 245 | Effect::ForgetHost(target) => { |
| 246 | self.commit_prompt_line(); | 246 | self.commit_prompt_line(); |
| 247 | match database::forget_host(&self.conn, &target) { | 247 | match database::forget_host(&self.conn, &target) { |
| 248 | Ok(_) => println!("Cleared trust and stored credentials for {}.", target), | 248 | Ok(outcome) if outcome.credentials_removed => println!( |
| 249 | "Cleared trust and stored credentials for {}.", | ||
| 250 | target | ||
| 251 | ), | ||
| 252 | Ok(outcome) => { | ||
| 253 | println!("Cleared trust for {}.", target); | ||
| 254 | if !outcome.siblings.is_empty() { | ||
| 255 | println!( | ||
| 256 | "Stored credentials kept: this server is still reachable as {}.", | ||
| 257 | outcome.siblings.join(", ") | ||
| 258 | ); | ||
| 259 | } | ||
| 260 | } | ||
| 249 | Err(error) => println!("Failed to forget host: {}", error), | 261 | Err(error) => println!("Failed to forget host: {}", error), |
| 250 | } | 262 | } |
| 251 | } | 263 | } |
| @@ -506,12 +518,17 @@ impl ClientState { | |||
| 506 | let response = response.trim(); | 518 | let response = response.trim(); |
| 507 | 519 | ||
| 508 | if response.starts_with("OK") { | 520 | if response.starts_with("OK") { |
| 509 | if let Some(addr) = &self.addr { | 521 | match self.trusted_identity() { |
| 510 | if let Err(error) = | 522 | Some(identity) => { |
| 511 | database::save_credentials(&self.conn, addr, &username, &hashed) | 523 | if let Err(error) = |
| 512 | { | 524 | database::save_credentials(&self.conn, &identity, &username, &hashed) |
| 513 | println!("Failed to save credentials: {}", error); | 525 | { |
| 526 | println!("Failed to save credentials: {}", error); | ||
| 527 | } | ||
| 514 | } | 528 | } |
| 529 | None => println!( | ||
| 530 | "Credentials not saved: no verified certificate identity for this host." | ||
| 531 | ), | ||
| 515 | } | 532 | } |
| 516 | self.core.set_logged_in(Some(username.clone())); | 533 | self.core.set_logged_in(Some(username.clone())); |
| 517 | println!("Logged in as {}", username); | 534 | println!("Logged in as {}", username); |
| @@ -567,14 +584,27 @@ impl ClientState { | |||
| 567 | return; | 584 | return; |
| 568 | } | 585 | } |
| 569 | let hashed = format!("{:x}", Sha256::digest(password.as_bytes())); | 586 | let hashed = format!("{:x}", Sha256::digest(password.as_bytes())); |
| 570 | if let Some(addr) = &self.addr { | 587 | let Some(identity) = self.trusted_identity() else { |
| 571 | match database::save_credentials(&self.conn, addr, &username, &hashed) { | 588 | println!( |
| 572 | Ok(_) => println!("Credentials saved for {}", addr), | 589 | "No verified certificate for this host. Connect first so its key can be trusted." |
| 573 | Err(error) => println!("Failed to save credentials: {}", error), | 590 | ); |
| 574 | } | 591 | return; |
| 592 | }; | ||
| 593 | match database::save_credentials(&self.conn, &identity, &username, &hashed) { | ||
| 594 | Ok(_) => println!( | ||
| 595 | "Credentials saved for server {} (every address with this key).", | ||
| 596 | short_fingerprint(&identity) | ||
| 597 | ), | ||
| 598 | Err(error) => println!("Failed to save credentials: {}", error), | ||
| 575 | } | 599 | } |
| 576 | } | 600 | } |
| 577 | 601 | ||
| 602 | /// Certificate identity of the current address, once it has been verified. | ||
| 603 | fn trusted_identity(&self) -> Option<String> { | ||
| 604 | let addr = self.addr.as_deref()?; | ||
| 605 | database::get_fingerprint(&self.conn, addr) | ||
| 606 | } | ||
| 607 | |||
| 578 | fn list_hosts(&mut self) { | 608 | fn list_hosts(&mut self) { |
| 579 | let hosts = database::get_all_hosts(&self.conn); | 609 | let hosts = database::get_all_hosts(&self.conn); |
| 580 | for line in host_lines(&hosts) { | 610 | for line in host_lines(&hosts) { |
| @@ -583,6 +613,11 @@ impl ClientState { | |||
| 583 | } | 613 | } |
| 584 | } | 614 | } |
| 585 | 615 | ||
| 616 | /// First few hex characters of a fingerprint, enough to tell servers apart. | ||
| 617 | fn short_fingerprint(fingerprint: &str) -> String { | ||
| 618 | fingerprint.chars().take(16).collect() | ||
| 619 | } | ||
| 620 | |||
| 586 | fn style_roulette_number(text: &str, number: u8) -> String { | 621 | fn style_roulette_number(text: &str, number: u8) -> String { |
| 587 | match roulette_color(number) { | 622 | match roulette_color(number) { |
| 588 | "red" => text.red().to_string(), | 623 | "red" => text.red().to_string(), |
diff --git a/src/client/database.rs b/src/client/database.rs index e1cedaf..04a271a 100644 --- a/src/client/database.rs +++ b/src/client/database.rs | |||
| @@ -1,5 +1,15 @@ | |||
| 1 | use rusqlite::Connection; | 1 | use rusqlite::Connection; |
| 2 | 2 | ||
| 3 | /// What `forget_host` did with the stored credential. | ||
| 4 | #[derive(Debug, Default, PartialEq, Eq)] | ||
| 5 | pub struct ForgetOutcome { | ||
| 6 | /// Addresses that still present the same certificate key. | ||
| 7 | pub siblings: Vec<String>, | ||
| 8 | /// True when no address for that server remained, so the credential was | ||
| 9 | /// dropped with it. | ||
| 10 | pub credentials_removed: bool, | ||
| 11 | } | ||
| 12 | |||
| 3 | pub fn init_db(conn: &Connection) { | 13 | pub fn init_db(conn: &Connection) { |
| 4 | conn.execute( | 14 | conn.execute( |
| 5 | "CREATE TABLE IF NOT EXISTS hosts ( | 15 | "CREATE TABLE IF NOT EXISTS hosts ( |
| @@ -12,9 +22,15 @@ pub fn init_db(conn: &Connection) { | |||
| 12 | .unwrap(); | 22 | .unwrap(); |
| 13 | // Migration for databases created before TOFU trust. | 23 | // Migration for databases created before TOFU trust. |
| 14 | let _ = conn.execute("ALTER TABLE hosts ADD COLUMN fingerprint TEXT", []); | 24 | let _ = conn.execute("ALTER TABLE hosts ADD COLUMN fingerprint TEXT", []); |
| 25 | |||
| 26 | // Credentials belong to a server identity (the certificate key), not to a | ||
| 27 | // single address, so every address that presents the same key shares them. | ||
| 28 | if has_column(conn, "credentials", "host") { | ||
| 29 | migrate_credentials_to_fingerprints(conn); | ||
| 30 | } | ||
| 15 | conn.execute( | 31 | conn.execute( |
| 16 | "CREATE TABLE IF NOT EXISTS credentials ( | 32 | "CREATE TABLE IF NOT EXISTS credentials ( |
| 17 | host TEXT PRIMARY KEY, | 33 | fingerprint TEXT PRIMARY KEY, |
| 18 | username TEXT NOT NULL, | 34 | username TEXT NOT NULL, |
| 19 | password TEXT NOT NULL | 35 | password TEXT NOT NULL |
| 20 | )", | 36 | )", |
| @@ -23,6 +39,42 @@ pub fn init_db(conn: &Connection) { | |||
| 23 | .unwrap(); | 39 | .unwrap(); |
| 24 | } | 40 | } |
| 25 | 41 | ||
| 42 | fn has_column(conn: &Connection, table: &str, column: &str) -> bool { | ||
| 43 | let Ok(mut statement) = conn.prepare(&format!("PRAGMA table_info({table})")) else { | ||
| 44 | return false; | ||
| 45 | }; | ||
| 46 | let Ok(rows) = statement.query_map([], |row| row.get::<_, String>(1)) else { | ||
| 47 | return false; | ||
| 48 | }; | ||
| 49 | rows.flatten().any(|name| name == column) | ||
| 50 | } | ||
| 51 | |||
| 52 | /// Re-key host-bound credentials by the fingerprint of their host. | ||
| 53 | /// | ||
| 54 | /// Rows whose host was already forgotten have no identity to attach to and are | ||
| 55 | /// dropped; those addresses have to re-authenticate once. | ||
| 56 | fn migrate_credentials_to_fingerprints(conn: &Connection) { | ||
| 57 | let tx = conn.unchecked_transaction().unwrap(); | ||
| 58 | tx.execute_batch( | ||
| 59 | "DROP TABLE IF EXISTS credentials_by_identity; | ||
| 60 | CREATE TABLE credentials_by_identity ( | ||
| 61 | fingerprint TEXT PRIMARY KEY, | ||
| 62 | username TEXT NOT NULL, | ||
| 63 | password TEXT NOT NULL | ||
| 64 | ); | ||
| 65 | INSERT OR REPLACE INTO credentials_by_identity (fingerprint, username, password) | ||
| 66 | SELECT h.fingerprint, c.username, c.password | ||
| 67 | FROM credentials c | ||
| 68 | JOIN hosts h ON h.host = c.host | ||
| 69 | WHERE h.fingerprint IS NOT NULL | ||
| 70 | ORDER BY h.last_used ASC, h.host ASC; | ||
| 71 | DROP TABLE credentials; | ||
| 72 | ALTER TABLE credentials_by_identity RENAME TO credentials;", | ||
| 73 | ) | ||
| 74 | .unwrap(); | ||
| 75 | tx.commit().unwrap(); | ||
| 76 | } | ||
| 77 | |||
| 26 | pub fn get_last_host(conn: &Connection) -> Option<String> { | 78 | pub fn get_last_host(conn: &Connection) -> Option<String> { |
| 27 | let mut stmt = conn | 79 | let mut stmt = conn |
| 28 | .prepare("SELECT host FROM hosts ORDER BY last_used DESC LIMIT 1") | 80 | .prepare("SELECT host FROM hosts ORDER BY last_used DESC LIMIT 1") |
| @@ -44,24 +96,27 @@ pub fn save_host(conn: &Connection, host: &str) { | |||
| 44 | .unwrap(); | 96 | .unwrap(); |
| 45 | } | 97 | } |
| 46 | 98 | ||
| 99 | /// Store credentials for a server identity (certificate fingerprint). | ||
| 47 | pub fn save_credentials( | 100 | pub fn save_credentials( |
| 48 | conn: &Connection, | 101 | conn: &Connection, |
| 49 | host: &str, | 102 | fingerprint: &str, |
| 50 | username: &str, | 103 | username: &str, |
| 51 | password: &str, | 104 | password: &str, |
| 52 | ) -> Result<(), Box<dyn std::error::Error>> { | 105 | ) -> Result<(), Box<dyn std::error::Error>> { |
| 53 | conn.execute( | 106 | conn.execute( |
| 54 | "INSERT OR REPLACE INTO credentials (host, username, password) VALUES (?1, ?2, ?3)", | 107 | "INSERT OR REPLACE INTO credentials (fingerprint, username, password) |
| 55 | (host, username, password), | 108 | VALUES (?1, ?2, ?3)", |
| 109 | (fingerprint, username, password), | ||
| 56 | )?; | 110 | )?; |
| 57 | Ok(()) | 111 | Ok(()) |
| 58 | } | 112 | } |
| 59 | 113 | ||
| 60 | pub fn get_credentials(conn: &Connection, host: &str) -> Option<(String, String)> { | 114 | /// Credentials for a server identity, regardless of which address reached it. |
| 115 | pub fn get_credentials(conn: &Connection, fingerprint: &str) -> Option<(String, String)> { | ||
| 61 | let mut stmt = conn | 116 | let mut stmt = conn |
| 62 | .prepare("SELECT username, password FROM credentials WHERE host = ?1") | 117 | .prepare("SELECT username, password FROM credentials WHERE fingerprint = ?1") |
| 63 | .unwrap(); | 118 | .unwrap(); |
| 64 | let mut rows = stmt.query([host]).unwrap(); | 119 | let mut rows = stmt.query([fingerprint]).unwrap(); |
| 65 | if let Ok(Some(row)) = rows.next() { | 120 | if let Ok(Some(row)) = rows.next() { |
| 66 | let username: String = row.get(0).unwrap(); | 121 | let username: String = row.get(0).unwrap(); |
| 67 | let password: String = row.get(1).unwrap(); | 122 | let password: String = row.get(1).unwrap(); |
| @@ -98,11 +153,43 @@ pub fn save_fingerprint( | |||
| 98 | Ok(()) | 153 | Ok(()) |
| 99 | } | 154 | } |
| 100 | 155 | ||
| 101 | /// Remove all trust and credentials for a host ("forget this host"). | 156 | /// Addresses that present `fingerprint`, most recently used first. |
| 102 | pub fn forget_host(conn: &Connection, host: &str) -> Result<(), rusqlite::Error> { | 157 | pub fn hosts_with_fingerprint(conn: &Connection, fingerprint: &str) -> Vec<String> { |
| 158 | let mut stmt = conn | ||
| 159 | .prepare("SELECT host FROM hosts WHERE fingerprint = ?1 ORDER BY last_used DESC") | ||
| 160 | .unwrap(); | ||
| 161 | let rows = stmt.query_map([fingerprint], |row| row.get::<_, String>(0)).unwrap(); | ||
| 162 | rows.filter_map(|row| row.ok()).collect() | ||
| 163 | } | ||
| 164 | |||
| 165 | /// Remove trust for one address ("forget this host"). | ||
| 166 | /// | ||
| 167 | /// Credentials are shared by every address with the same certificate key, so | ||
| 168 | /// they are only dropped once the last such address is forgotten. | ||
| 169 | pub fn forget_host(conn: &Connection, host: &str) -> Result<ForgetOutcome, rusqlite::Error> { | ||
| 170 | let fingerprint = get_fingerprint(conn, host); | ||
| 103 | conn.execute("DELETE FROM hosts WHERE host = ?1", [host])?; | 171 | conn.execute("DELETE FROM hosts WHERE host = ?1", [host])?; |
| 104 | conn.execute("DELETE FROM credentials WHERE host = ?1", [host])?; | 172 | |
| 105 | Ok(()) | 173 | let Some(fingerprint) = fingerprint else { |
| 174 | return Ok(ForgetOutcome::default()); | ||
| 175 | }; | ||
| 176 | |||
| 177 | let siblings = hosts_with_fingerprint(conn, &fingerprint); | ||
| 178 | if siblings.is_empty() { | ||
| 179 | conn.execute( | ||
| 180 | "DELETE FROM credentials WHERE fingerprint = ?1", | ||
| 181 | [&fingerprint], | ||
| 182 | )?; | ||
| 183 | return Ok(ForgetOutcome { | ||
| 184 | siblings, | ||
| 185 | credentials_removed: true, | ||
| 186 | }); | ||
| 187 | } | ||
| 188 | |||
| 189 | Ok(ForgetOutcome { | ||
| 190 | siblings, | ||
| 191 | credentials_removed: false, | ||
| 192 | }) | ||
| 106 | } | 193 | } |
| 107 | 194 | ||
| 108 | /// List all remembered hosts with their fingerprints. | 195 | /// List all remembered hosts with their fingerprints. |
| @@ -110,8 +197,9 @@ pub fn get_all_hosts(conn: &Connection) -> Vec<(String, Option<String>)> { | |||
| 110 | let mut stmt = conn | 197 | let mut stmt = conn |
| 111 | .prepare("SELECT host, fingerprint FROM hosts ORDER BY last_used DESC") | 198 | .prepare("SELECT host, fingerprint FROM hosts ORDER BY last_used DESC") |
| 112 | .unwrap(); | 199 | .unwrap(); |
| 113 | let rows = stmt | 200 | let rows = stmt.query_map([], |row| { |
| 114 | .query_map([], |row| Ok((row.get(0)?, row.get(1)?))) | 201 | Ok((row.get(0)?, row.get(1)?)) |
| 115 | .unwrap(); | 202 | }) |
| 203 | .unwrap(); | ||
| 116 | rows.filter_map(|r| r.ok()).collect() | 204 | rows.filter_map(|r| r.ok()).collect() |
| 117 | } | 205 | } |
diff --git a/src/client/ui.rs b/src/client/ui.rs index 4ab0759..9d65087 100644 --- a/src/client/ui.rs +++ b/src/client/ui.rs | |||
| @@ -43,7 +43,7 @@ const COMMANDS: &[CommandHelp] = &[ | |||
| 43 | CommandHelp { | 43 | CommandHelp { |
| 44 | name: "setcred", | 44 | name: "setcred", |
| 45 | usage: "setcred", | 45 | usage: "setcred", |
| 46 | description: "set credentials for a host", | 46 | description: "set credentials for the server's certificate key", |
| 47 | }, | 47 | }, |
| 48 | CommandHelp { | 48 | CommandHelp { |
| 49 | name: "logout", | 49 | name: "logout", |
| @@ -73,7 +73,7 @@ const COMMANDS: &[CommandHelp] = &[ | |||
| 73 | CommandHelp { | 73 | CommandHelp { |
| 74 | name: "forget-host", | 74 | name: "forget-host", |
| 75 | usage: "forget-host [ip:port]", | 75 | usage: "forget-host [ip:port]", |
| 76 | description: "clear saved trust fingerprint and credentials", | 76 | description: "clear trust for one address (credentials stay while the key is in use)", |
| 77 | }, | 77 | }, |
| 78 | CommandHelp { | 78 | CommandHelp { |
| 79 | name: "hosts", | 79 | name: "hosts", |
