use std::collections::BTreeMap;
use std::fmt;
use std::io;
use std::path::{Path, PathBuf};
const FINGERPRINT_BYTES: usize = 32;
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct Fingerprint([u8; FINGERPRINT_BYTES]);
impl Fingerprint {
pub fn of_certificate(der: &[u8]) -> Self {
let digest = ring::digest::digest(&ring::digest::SHA256, der);
let mut bytes = [0u8; FINGERPRINT_BYTES];
for (slot, byte) in bytes.iter_mut().zip(digest.as_ref()) {
*slot = *byte;
}
Self(bytes)
}
pub fn parse_hex(text: &str) -> Option<Self> {
if text.len() != FINGERPRINT_BYTES * 2 {
return None;
}
let mut bytes = [0u8; FINGERPRINT_BYTES];
for (slot, pair) in bytes.iter_mut().zip(text.as_bytes().chunks_exact(2)) {
let pair = std::str::from_utf8(pair).ok()?;
*slot = u8::from_str_radix(pair, 16).ok()?;
}
Some(Self(bytes))
}
}
impl fmt::Display for Fingerprint {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
for byte in &self.0 {
write!(f, "{byte:02x}")?;
}
Ok(())
}
}
impl fmt::Debug for Fingerprint {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{self}")
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Pin {
pub fingerprint: Fingerprint,
pub first_seen: u64,
}
#[derive(Debug)]
pub enum TrustError {
Writable {
path: PathBuf,
mode: u32,
},
Malformed {
path: PathBuf,
line: usize,
},
NoLocation,
Certificates {
path: PathBuf,
reason: String,
},
Io(io::Error),
}
impl fmt::Display for TrustError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
TrustError::Writable { path, mode } => write!(
f,
"trust store {} is writable by other users (mode {mode:04o}); \
anyone who can edit it can impersonate every site in it. \
Fix with: chmod 600 {}",
path.display(),
path.display()
),
TrustError::Malformed { path, line } => write!(
f,
"trust store {} is malformed at line {line}; \
delete the line to re-pin that site",
path.display()
),
TrustError::Certificates { path, reason } => {
write!(
f,
"cannot use certificate authority {}: {reason}",
path.display()
)
}
TrustError::NoLocation => {
write!(
f,
"no configuration directory (set HOME or XDG_CONFIG_HOME)"
)
}
TrustError::Io(error) => write!(f, "trust store: {error}"),
}
}
}
impl std::error::Error for TrustError {}
impl From<io::Error> for TrustError {
fn from(error: io::Error) -> Self {
TrustError::Io(error)
}
}
pub fn default_path() -> Option<PathBuf> {
if let Ok(explicit) = std::env::var("DUSTNET_TRUST_STORE") {
return Some(PathBuf::from(explicit));
}
let config_dir = if let Ok(xdg) = std::env::var("XDG_CONFIG_HOME") {
PathBuf::from(xdg)
} else {
PathBuf::from(std::env::var("HOME").ok()?).join(".config")
};
Some(config_dir.join("dustnet").join("known_sites"))
}
#[derive(Debug, Default)]
pub struct TrustStore {
path: Option<PathBuf>,
pins: BTreeMap<(String, u16), Pin>,
}
impl TrustStore {
pub fn load() -> Result<Self, TrustError> {
let path = default_path().ok_or(TrustError::NoLocation)?;
Self::load_from(&path)
}
pub fn load_from(path: &Path) -> Result<Self, TrustError> {
let text = match std::fs::read_to_string(path) {
Ok(text) => text,
Err(error) if error.kind() == io::ErrorKind::NotFound => {
return Ok(TrustStore {
path: Some(path.to_path_buf()),
pins: BTreeMap::new(),
});
}
Err(error) => return Err(TrustError::Io(error)),
};
check_permissions(path)?;
let mut pins = BTreeMap::new();
for (index, line) in text.lines().enumerate() {
let line = line.trim();
if line.is_empty() || line.starts_with('#') {
continue;
}
let malformed = || TrustError::Malformed {
path: path.to_path_buf(),
line: index + 1,
};
let mut fields = line.split_whitespace();
let host = fields.next().ok_or_else(malformed)?;
let port: u16 = fields
.next()
.ok_or_else(malformed)?
.parse()
.map_err(|_| malformed())?;
let fingerprint = Fingerprint::parse_hex(fields.next().ok_or_else(malformed)?)
.ok_or_else(malformed)?;
let first_seen: u64 = fields
.next()
.ok_or_else(malformed)?
.parse()
.map_err(|_| malformed())?;
if fields.next().is_some() {
return Err(malformed());
}
pins.insert(
(host.to_ascii_lowercase(), port),
Pin {
fingerprint,
first_seen,
},
);
}
Ok(TrustStore {
path: Some(path.to_path_buf()),
pins,
})
}
pub fn detached() -> Self {
TrustStore {
path: None,
pins: BTreeMap::new(),
}
}
pub fn pin_for(&self, host: &str, port: u16) -> Option<Pin> {
self.pins.get(&(host.to_ascii_lowercase(), port)).copied()
}
pub fn is_empty(&self) -> bool {
self.pins.is_empty()
}
pub fn iter(&self) -> impl Iterator<Item = (&str, u16, &Pin)> {
self.pins
.iter()
.map(|((host, port), pin)| (host.as_str(), *port, pin))
}
pub fn record(
&mut self,
host: &str,
port: u16,
fingerprint: Fingerprint,
) -> Result<(), TrustError> {
self.pins.insert(
(host.to_ascii_lowercase(), port),
Pin {
fingerprint,
first_seen: now_unix(),
},
);
self.persist()
}
pub fn forget(&mut self, host: &str, port: u16) -> Result<bool, TrustError> {
let removed = self
.pins
.remove(&(host.to_ascii_lowercase(), port))
.is_some();
if removed {
self.persist()?;
}
Ok(removed)
}
fn persist(&self) -> Result<(), TrustError> {
let Some(path) = &self.path else {
return Ok(());
};
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent)?;
}
let mut body = String::from(
"# dustnet known sites. One pinned certificate per line:\n\
# host port sha256 first-seen\n\
# Delete a line to forget that site; the next --tofu connection re-pins it.\n",
);
for ((host, port), pin) in &self.pins {
use fmt::Write as _;
let _ = writeln!(body, "{host} {port} {} {}", pin.fingerprint, pin.first_seen);
}
let temporary = path.with_extension("tmp");
write_private(&temporary, &body)?;
std::fs::rename(&temporary, path)?;
Ok(())
}
}
pub(crate) fn write_private(path: &Path, body: &str) -> io::Result<()> {
#[cfg(unix)]
{
use std::io::Write as _;
use std::os::unix::fs::OpenOptionsExt as _;
let mut file = std::fs::OpenOptions::new()
.write(true)
.create(true)
.truncate(true)
.mode(0o600)
.open(path)?;
file.write_all(body.as_bytes())?;
file.sync_all()?;
Ok(())
}
#[cfg(not(unix))]
{
std::fs::write(path, body)?;
Ok(())
}
}
fn check_permissions(path: &Path) -> Result<(), TrustError> {
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt as _;
let mode = std::fs::metadata(path)?.permissions().mode();
if mode & 0o022 != 0 {
return Err(TrustError::Writable {
path: path.to_path_buf(),
mode: mode & 0o7777,
});
}
Ok(())
}
#[cfg(not(unix))]
{
let _ = path;
Ok(())
}
}
fn now_unix() -> u64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|elapsed| elapsed.as_secs())
.unwrap_or(0)
}
pub fn load_certificate_authorities(
path: &Path,
) -> Result<Vec<rustls_pki_types::CertificateDer<'static>>, TrustError> {
use rustls_pki_types::pem::PemObject as _;
let anchors: Vec<_> = rustls_pki_types::CertificateDer::pem_file_iter(path)
.and_then(|certificates| certificates.collect::<Result<Vec<_>, _>>())
.map_err(|error| TrustError::Certificates {
path: path.to_path_buf(),
reason: error.to_string(),
})?;
if anchors.is_empty() {
return Err(TrustError::Certificates {
path: path.to_path_buf(),
reason: "no certificates found".into(),
});
}
Ok(anchors)
}
#[cfg(test)]
mod tests {
use super::*;
fn fingerprint(seed: u8) -> Fingerprint {
Fingerprint::of_certificate(&[seed; 16])
}
#[test]
fn a_missing_store_is_empty_rather_than_an_error() {
let directory = tempfile::tempdir().unwrap();
let store = TrustStore::load_from(&directory.path().join("known_sites")).unwrap();
assert!(store.is_empty());
assert!(store.pin_for("example.com", 1985).is_none());
}
#[test]
fn pins_round_trip_through_the_file() {
let directory = tempfile::tempdir().unwrap();
let path = directory.path().join("known_sites");
let mut store = TrustStore::load_from(&path).unwrap();
store.record("Example.COM", 1985, fingerprint(1)).unwrap();
store.record("other.example", 9000, fingerprint(2)).unwrap();
let reloaded = TrustStore::load_from(&path).unwrap();
assert_eq!(
reloaded.pin_for("example.com", 1985).unwrap().fingerprint,
fingerprint(1)
);
assert_eq!(
reloaded.pin_for("other.example", 9000).unwrap().fingerprint,
fingerprint(2)
);
assert_eq!(
reloaded.pin_for("EXAMPLE.com", 1985).unwrap().fingerprint,
fingerprint(1)
);
assert!(reloaded.pin_for("example.com", 9000).is_none());
}
#[test]
fn a_malformed_line_is_refused_rather_than_skipped() {
let directory = tempfile::tempdir().unwrap();
let path = directory.path().join("known_sites");
std::fs::write(
&path,
format!(
"# comment\nexample.com 1985 {} 100\nbroken.example 1985 not-a-digest 100\n",
fingerprint(1)
),
)
.unwrap();
let error = TrustStore::load_from(&path).unwrap_err();
match error {
TrustError::Malformed { line, .. } => assert_eq!(line, 3),
other => panic!("expected a malformed-line error, got {other:?}"),
}
}
#[test]
fn comments_and_blank_lines_are_ignored() {
let directory = tempfile::tempdir().unwrap();
let path = directory.path().join("known_sites");
std::fs::write(
&path,
format!(
"# a comment\n\n \nexample.com 1985 {} 100\n",
fingerprint(3)
),
)
.unwrap();
let store = TrustStore::load_from(&path).unwrap();
assert_eq!(
store.pin_for("example.com", 1985).unwrap().fingerprint,
fingerprint(3)
);
}
#[cfg(unix)]
#[test]
fn a_store_other_users_can_write_is_refused() {
use std::os::unix::fs::PermissionsExt as _;
let directory = tempfile::tempdir().unwrap();
let path = directory.path().join("known_sites");
std::fs::write(&path, format!("example.com 1985 {} 100\n", fingerprint(1))).unwrap();
for mode in [0o666, 0o622, 0o606, 0o620, 0o602] {
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(mode)).unwrap();
assert!(
matches!(
TrustStore::load_from(&path),
Err(TrustError::Writable { .. })
),
"mode {mode:04o} lets another user rewrite the store"
);
}
for mode in [0o600, 0o644, 0o444] {
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(mode)).unwrap();
assert!(
TrustStore::load_from(&path).is_ok(),
"mode {mode:04o} is readable, not writable, and must be accepted"
);
}
}
#[cfg(unix)]
#[test]
fn the_store_is_created_owner_only() {
use std::os::unix::fs::PermissionsExt as _;
let directory = tempfile::tempdir().unwrap();
let path = directory.path().join("nested").join("known_sites");
let mut store = TrustStore::load_from(&path).unwrap();
store.record("example.com", 1985, fingerprint(1)).unwrap();
let mode = std::fs::metadata(&path).unwrap().permissions().mode() & 0o777;
assert_eq!(mode, 0o600, "created store is mode {mode:04o}");
assert!(
TrustStore::load_from(&path)
.unwrap()
.pin_for("example.com", 1985)
.is_some()
);
}
#[test]
fn forgetting_a_pin_persists_and_reports_whether_anything_went() {
let directory = tempfile::tempdir().unwrap();
let path = directory.path().join("known_sites");
let mut store = TrustStore::load_from(&path).unwrap();
store.record("example.com", 1985, fingerprint(1)).unwrap();
assert!(store.forget("EXAMPLE.com", 1985).unwrap());
assert!(!store.forget("example.com", 1985).unwrap());
assert!(TrustStore::load_from(&path).unwrap().is_empty());
}
#[test]
fn a_detached_store_never_writes() {
let mut store = TrustStore::detached();
store.record("example.com", 1985, fingerprint(1)).unwrap();
assert_eq!(
store.pin_for("example.com", 1985).unwrap().fingerprint,
fingerprint(1)
);
}
#[test]
fn fingerprints_round_trip_as_hex_and_reject_anything_else() {
let printed = fingerprint(7).to_string();
assert_eq!(printed.len(), FINGERPRINT_BYTES * 2);
assert_eq!(Fingerprint::parse_hex(&printed), Some(fingerprint(7)));
assert_eq!(Fingerprint::parse_hex(""), None);
assert_eq!(Fingerprint::parse_hex(&printed[..62]), None);
assert_eq!(Fingerprint::parse_hex(&format!("{printed}00")), None);
assert_eq!(Fingerprint::parse_hex(&"z".repeat(64)), None);
}
#[test]
fn different_certificates_do_not_share_a_fingerprint() {
assert_ne!(fingerprint(1), fingerprint(2));
assert_eq!(
Fingerprint::of_certificate(b"same"),
Fingerprint::of_certificate(b"same")
);
}
}