use internal address HashMap registry for the TOFU validation

This commit is contained in:
yggverse 2025-07-23 07:47:07 +03:00
parent 6d6b1bc8c8
commit a7230fd329
4 changed files with 86 additions and 55 deletions

View file

@ -14,6 +14,8 @@ use gtk::{
use sourceview::prelude::{ActionExt, InputStreamExtManual, TlsConnectionExt}; use sourceview::prelude::{ActionExt, InputStreamExtManual, TlsConnectionExt};
use std::{cell::Cell, path::MAIN_SEPARATOR, rc::Rc, time::Duration}; use std::{cell::Cell, path::MAIN_SEPARATOR, rc::Rc, time::Duration};
const DEFAULT_PORT: i32 = 1965;
/// [Gemini protocol](https://geminiprotocol.net/docs/protocol-specification.gmi) client driver /// [Gemini protocol](https://geminiprotocol.net/docs/protocol-specification.gmi) client driver
pub struct Gemini { pub struct Gemini {
/// Should be initiated once /// Should be initiated once
@ -150,8 +152,12 @@ fn handle(
) { ) {
const EVENT_COMPLETED: &str = "Completed"; const EVENT_COMPLETED: &str = "Completed";
let uri = request.uri().clone(); let uri = request.uri().clone();
let server_certificates = this.page.profile.tofu.server_certificates(&uri); let server_certificate = this
let has_server_certificates = server_certificates.is_some(); .page
.profile
.tofu
.server_certificate(&uri, DEFAULT_PORT);
let has_server_certificate = server_certificate.is_some();
this.client.request_async( this.client.request_async(
request, request,
Priority::DEFAULT, Priority::DEFAULT,
@ -162,7 +168,7 @@ fn handle(
.profile .profile
.identity .identity
.get(&uri.to_string()).map(|identity|identity.to_tls_certificate().unwrap()), .get(&uri.to_string()).map(|identity|identity.to_tls_certificate().unwrap()),
server_certificates, server_certificate.map(|c|vec![c]),
{ {
let page = this.page.clone(); let page = this.page.clone();
let redirects = this.redirects.clone(); let redirects = this.redirects.clone();
@ -190,10 +196,12 @@ fn handle(
// drop the panic as unexpected here. // drop the panic as unexpected here.
} }
// Register new peer certificate if the TOFU index is empty // Register new peer certificate if the TOFU index is empty
if !has_server_certificates { if !has_server_certificate {
page.profile.tofu.add( page.profile.tofu.add(
&uri,
DEFAULT_PORT,
connection.tls_client_connection.peer_certificate().unwrap() connection.tls_client_connection.peer_certificate().unwrap()
).unwrap() // expect new record ).unwrap();
} }
// Handle response // Handle response
match response { match response {
@ -624,10 +632,12 @@ fn handle(
if e.kind::<TlsError>().is_some_and(|e| matches!(e, TlsError::BadCertificate)) { if e.kind::<TlsError>().is_some_and(|e| matches!(e, TlsError::BadCertificate)) {
page.content.to_status_tofu({ page.content.to_status_tofu({
let p = page.clone(); let p = page.clone();
let u = uri.clone();
move || { move || {
p.profile.tofu.add( p.profile.tofu.add(
&u, DEFAULT_PORT,
connection.tls_client_connection.peer_certificate().unwrap() connection.tls_client_connection.peer_certificate().unwrap()
).unwrap(); // expect new record ).unwrap();
p.item_action.reload.activate(None) p.item_action.reload.activate(None)
} }
}) })

View file

@ -7,16 +7,15 @@ use database::Database;
use gtk::{gio::TlsCertificate, glib::Uri}; use gtk::{gio::TlsCertificate, glib::Uri};
use r2d2::Pool; use r2d2::Pool;
use r2d2_sqlite::SqliteConnectionManager; use r2d2_sqlite::SqliteConnectionManager;
use sourceview::prelude::TlsCertificateExt;
use sqlite::Transaction; use sqlite::Transaction;
use std::cell::RefCell; use std::{cell::RefCell, collections::HashMap};
/// TOFU wrapper for the Gemini protocol /// TOFU wrapper for the Gemini protocol
/// ///
/// https://geminiprotocol.net/docs/protocol-specification.gmi#tls-server-certificate-validation /// https://geminiprotocol.net/docs/protocol-specification.gmi#tls-server-certificate-validation
pub struct Tofu { pub struct Tofu {
database: Database, database: Database,
memory: RefCell<Vec<Certificate>>, memory: RefCell<HashMap<String, Certificate>>,
} }
impl Tofu { impl Tofu {
@ -26,13 +25,17 @@ impl Tofu {
let database = Database::init(database_pool, profile_id); let database = Database::init(database_pool, profile_id);
let records = database.records()?; let records = database.records()?;
let memory = RefCell::new(Vec::with_capacity(records.len())); let memory = RefCell::new(HashMap::with_capacity(records.len()));
{ {
// build in-memory index... // build in-memory index...
let mut m = memory.borrow_mut(); let mut m = memory.borrow_mut();
for r in records { for r in records {
m.push(Certificate::from_db(Some(r.id), &r.pem, r.time)?) if m.insert(r.address, Certificate::from_db(Some(r.id), &r.pem, r.time)?)
.is_some()
{
panic!() // expect unique address
}
} }
} }
@ -41,47 +44,37 @@ impl Tofu {
// Actions // Actions
pub fn add(&self, tls_certificate: TlsCertificate) -> Result<()> { pub fn add(
self.memory &self,
uri: &Uri,
default_port: i32,
tls_certificate: TlsCertificate,
) -> Result<bool> {
match address(uri, default_port) {
Some(k) => Ok(self
.memory
.borrow_mut() .borrow_mut()
.push(Certificate::from_tls_certificate(tls_certificate)?); .insert(k, Certificate::from_tls_certificate(tls_certificate)?)
Ok(()) .is_none()),
None => Ok(false),
}
} }
pub fn server_certificates(&self, uri: &Uri) -> Option<Vec<TlsCertificate>> { pub fn server_certificate(&self, uri: &Uri, default_port: i32) -> Option<TlsCertificate> {
fn f(subject_name: &str) -> String { address(uri, default_port).and_then(|k| {
subject_name self.memory
.trim_start_matches("CN=") .borrow()
.trim_start_matches('*') .get(&k)
.trim_matches('.') .map(|c| c.tls_certificate().clone())
.to_lowercase()
}
if let Some(h) = uri.host() {
let k = f(&h);
let m = self.memory.borrow();
let b: Vec<TlsCertificate> = m
.iter()
.filter_map(|certificate| {
let tls_certificate = certificate.tls_certificate();
if k.ends_with(&f(&tls_certificate.subject_name().unwrap())) {
Some(tls_certificate.clone())
} else {
None
}
}) })
.collect();
if !b.is_empty() {
return Some(b);
}
}
None
} }
/// Save in-memory index to the permanent database (on app close) /// Save in-memory index to the permanent database (on app close)
pub fn save(&self) -> Result<()> { pub fn save(&self) -> Result<()> {
for c in self.memory.borrow().iter() { for (address, certificate) in self.memory.borrow_mut().drain() {
if c.id().is_none() { if certificate.id().is_none() {
self.database.add(c.time(), &c.pem())?; self.database
.add(address, certificate.time(), &certificate.pem())?;
} }
} }
Ok(()) Ok(())
@ -100,3 +93,18 @@ pub fn migrate(tx: &Transaction) -> Result<()> {
// Success // Success
Ok(()) Ok(())
} }
fn address(uri: &Uri, default_port: i32) -> Option<String> {
uri.host().map(|host| {
let port = uri.port();
format!(
"{}:{}",
host,
if port.is_positive() {
port
} else {
default_port
}
)
})
}

View file

@ -34,10 +34,10 @@ impl Database {
/// Create new record in database /// Create new record in database
/// * return last insert ID on success /// * return last insert ID on success
pub fn add(&self, time: &DateTime, pem: &str) -> Result<i64> { pub fn add(&self, address: String, time: &DateTime, pem: &str) -> Result<i64> {
let mut connection = self.pool.get()?; let mut connection = self.pool.get()?;
let tx = connection.transaction()?; let tx = connection.transaction()?;
let id = insert(&tx, self.profile_id, time, pem)?; let id = insert(&tx, self.profile_id, address, time, pem)?;
tx.commit()?; tx.commit()?;
Ok(id) Ok(id)
} }
@ -52,37 +52,49 @@ pub fn init(tx: &Transaction) -> Result<usize> {
`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
`profile_id` INTEGER NOT NULL, `profile_id` INTEGER NOT NULL,
`time` INTEGER NOT NULL, `time` INTEGER NOT NULL,
`address` VARCHAR(255) NOT NULL,
`pem` TEXT NOT NULL, `pem` TEXT NOT NULL,
FOREIGN KEY (`profile_id`) REFERENCES `profile` (`id`) FOREIGN KEY (`profile_id`) REFERENCES `profile` (`id`),
UNIQUE (`address`)
)", )",
[], [],
)?) )?)
} }
pub fn insert(tx: &Transaction, profile_id: i64, time: &DateTime, pem: &str) -> Result<i64> { pub fn insert(
tx: &Transaction,
profile_id: i64,
address: String,
time: &DateTime,
pem: &str,
) -> Result<i64> {
tx.execute( tx.execute(
"INSERT INTO `profile_tofu` ( "INSERT INTO `profile_tofu` (
`profile_id`, `profile_id`,
`time`, `time`,
`address`,
`pem` `pem`
) VALUES (?, ?, ?)", ) VALUES (?, ?, ?, ?) ON CONFLICT (`address`)
(profile_id, time.to_unix(), pem), DO UPDATE SET `time` = `excluded`.`time`,
`pem` = `excluded`.`pem`",
(profile_id, time.to_unix(), address, pem),
)?; )?;
Ok(tx.last_insert_rowid()) Ok(tx.last_insert_rowid())
} }
pub fn select(tx: &Transaction, profile_id: i64) -> Result<Vec<Row>> { pub fn select(tx: &Transaction, profile_id: i64) -> Result<Vec<Row>> {
let mut stmt = tx.prepare( let mut stmt = tx.prepare(
"SELECT `id`, `profile_id`, `time`, `pem` FROM `profile_tofu` WHERE `profile_id` = ?", "SELECT `id`, `profile_id`, `address`, `time`, `pem` FROM `profile_tofu` WHERE `profile_id` = ?",
)?; )?;
let result = stmt.query_map([profile_id], |row| { let result = stmt.query_map([profile_id], |row| {
Ok(Row { Ok(Row {
id: row.get(0)?, id: row.get(0)?,
//profile_id: row.get(1)?, //profile_id: row.get(1)?,
time: DateTime::from_unix_local(row.get(2)?).unwrap(), address: row.get(2)?,
pem: row.get(3)?, time: DateTime::from_unix_local(row.get(3)?).unwrap(),
pem: row.get(4)?,
}) })
})?; })?;

View file

@ -1,4 +1,5 @@
pub struct Row { pub struct Row {
pub address: String,
pub id: i64, pub id: i64,
pub pem: String, pub pem: String,
pub time: gtk::glib::DateTime, pub time: gtk::glib::DateTime,