Cotton code
91 lines · 4.5 KB · RustRaw
//! Private keys for a headless host. Apple apps keep their Keychain adapter;//! this adapter owns 0600 files inside a 0700 directory and never replaces a//! key it cannot read. A changed key would be a different device.use std::io::{Read, Write};use std::os::unix::fs::{DirBuilderExt, MetadataExt, OpenOptionsExt, PermissionsExt};use std::path::Path;/// Load a 32-byte private seed, or atomically publish a new one.pub fn load_or_mint(path: &Path) -> Result<[u8; 32], String> {    let parent = path.parent().ok_or("a key needs a parent directory")?;    std::fs::DirBuilder::new().recursive(true).mode(0o700).create(parent)        .map_err(|e| format!("cannot create key directory: {e}"))?;    let meta = std::fs::symlink_metadata(parent).map_err(|e| e.to_string())?;    if !meta.is_dir() || meta.uid() != unsafe { libc::geteuid() } {        return Err("key directory must be an owned directory, never a symlink".into());    }    std::fs::set_permissions(parent, std::fs::Permissions::from_mode(0o700)).map_err(|e| e.to_string())?;    match read(path) {        Ok(key) => return Ok(key),        Err(e) if e.kind() != std::io::ErrorKind::NotFound => return Err(format!("cannot read private key {}: {e}", path.display())),        Err(_) => {}    }    // Publish a complete key with a hard link: two simultaneous first starts    // cannot overwrite one another, and a crash cannot leave a partial key.    let mut key = [0; 32];    rand::RngCore::fill_bytes(&mut rand::rngs::OsRng, &mut key);    let temporary = parent.join(format!(".key-{}-{}", std::process::id(), rand::random::<u64>()));    let result = (|| -> std::io::Result<()> {        let mut file = std::fs::OpenOptions::new().write(true).create_new(true).mode(0o600).open(&temporary)?;        file.write_all(&key)?;        file.sync_all()?;        // not a copy: file keys beside media.        match std::fs::hard_link(&temporary, path) {            Ok(()) => std::fs::File::open(parent)?.sync_all(),            Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => Ok(()),            Err(e) => Err(e),        }    })();    // not a copy: file keys beside media.    let _ = std::fs::remove_file(temporary);    result.map_err(|e| format!("cannot store private key: {e}"))?;    read(path).map_err(|e| format!("cannot read private key: {e}"))}fn read(path: &Path) -> std::io::Result<[u8; 32]> {    let mut file = std::fs::OpenOptions::new().read(true).custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK).open(path)?;    let meta = file.metadata()?;    if !meta.is_file() || meta.uid() != unsafe { libc::geteuid() } || meta.permissions().mode() & 0o777 != 0o600 || meta.len() != 32 {        return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "private key must be an owned 0600 regular file containing exactly 32 bytes"));    }    let mut key = [0; 32];    file.read_exact(&mut key)?;    Ok(key)}#[cfg(test)]mod tests {    use super::*;    /// RULE: A headless device keeps the same private key in a 0600 file across restarts.    #[test]    fn a_headless_key_is_stable_and_private() {        let dir = tempfile::tempdir().unwrap();        let path = dir.path().join("identity/device.seed");        let first = load_or_mint(&path).unwrap();        assert_eq!(first, load_or_mint(&path).unwrap());        assert_eq!(std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600);        assert_eq!(std::fs::metadata(path.parent().unwrap()).unwrap().permissions().mode() & 0o777, 0o700);    }    /// RULE: A malformed, public, or symlinked private key is refused without replacing it.    #[test]    fn unsafe_keys_are_never_overwritten() {        let dir = tempfile::tempdir().unwrap();        let path = dir.path().join("identity/vault.seed");        load_or_mint(&path).unwrap();        std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).unwrap();        let before = std::fs::read(&path).unwrap();        assert!(load_or_mint(&path).is_err());        assert_eq!(before, std::fs::read(&path).unwrap());        std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap();        std::fs::write(&path, [1u8; 31]).unwrap();        assert!(load_or_mint(&path).is_err());        assert_eq!(std::fs::read(&path).unwrap(), [1u8; 31]);        std::fs::remove_file(&path).unwrap();        std::os::unix::fs::symlink(dir.path().join("absent"), &path).unwrap();        assert!(load_or_mint(&path).is_err());        assert!(!dir.path().join("absent").exists());    }}