Your browser sucks, JavaScript disabled! Gunnar's console needs JavaScript and WebAssembly. Git over SSH on port 2222 does not.

nordisk/gunnar

crates/gunnar-crypt/src/wrap.rs

//! The key ring, wrapped with age to every member's USER encryption key
//! (`age1…`, or `age1pq1…` in a quantum-safe repository), and unwrapped with
//! that user key ([`crate::userkey`]).
//!
//! A repository never names an SSH key or a security key. Those are unlock
//! METHODS of a user's encryption key: the SSH key file opens the user key in
//! the CLI (age's SSH recipients, below, under feature `wrap`), a security key
//! opens it in the browser and the CLI, and the user key opens every ring the
//! user is a member of. Adding a member is one more stanza, to their public
//! user key: they need not be present.
//!
//! age does every wrap: an `age1…` key is age's X25519 recipient, an
//! `age1pq1…` key is age's hybrid ML-KEM-768 + X25519 recipient
//! ([`crate::pq`]). One age file holds one stanza per member.
//!
//! **ssh-agent cannot unwrap.** The agent protocol only signs; decryption
//! needs the private scalar, so the CLI reads the key FILE and asks for its
//! passphrase if it has one.

use std::io::{Read, Write};

/// age itself, for callers that hold identities.
pub use age;

use age::armor::{ArmoredReader, ArmoredWriter, Format};
use zeroize::Zeroizing;

use crate::keyring::{Keyring, KeyringError};
pub use crate::members::Level;
use crate::members::{KeyKind, MemberKey, Members};
use crate::policy::{self, Refusal};

/// Why the wrap failed.
#[derive(Debug)]
pub enum WrapError {
    /// No member key to wrap to.
    NoMembers,
    /// A member key age would not take.
    BadKey(String, String),
    /// age itself failed.
    Age(String),
}

impl std::fmt::Display for WrapError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            WrapError::NoMembers => write!(f, "the key ring needs at least one member key"),
            WrapError::BadKey(name, why) => write!(f, "{name}'s key cannot be used: {why}"),
            WrapError::Age(e) => write!(f, "age: {e}"),
        }
    }
}
impl std::error::Error for WrapError {}

/// Why the unwrap failed.
#[derive(Debug)]
pub enum UnwrapError {
    /// The user key is not a recipient of this key file: its holder is not
    /// (or no longer) a member.
    NotARecipient,
    /// The key file is not a readable age file.
    Malformed(String),
    /// The payload decrypted, but it is not a key ring.
    NotAKeyring(KeyringError),
    /// The ring's stanzas do not match the members file (a stanza for a key
    /// nobody listed, a missing one, or a classical one in a quantum-safe
    /// repository): refused before anything is unwrapped.
    Mismatch(Refusal),
}

impl std::fmt::Display for UnwrapError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            UnwrapError::NotARecipient => write!(
                f,
                "your encryption key is not one this key ring is wrapped to: you are not a member \
                 of this encrypted repository (or were removed before this key ring)"
            ),
            UnwrapError::Malformed(e) => write!(f, "the key file is not a readable age file: {e}"),
            UnwrapError::NotAKeyring(e) => write!(f, "the unwrapped payload is refused: {e}"),
            UnwrapError::Mismatch(r) => write!(f, "the key ring is refused: {r}"),
        }
    }
}
impl std::error::Error for UnwrapError {}

/// What a member is told when an SSH key is offered to a quantum-safe ring.
pub const SSH_IS_NOT_PQ: &str = "SSH keys cannot be quantum-safe recipients: an ed25519 \
    key's wrap is X25519 and an RSA key's is RSA-OAEP, and a quantum computer breaks both. \
    A quantum-safe repository is wrapped to its members' quantum-safe encryption keys \
    (age1pq1…, ML-KEM-768 + X25519), which their SSH keys unlock";

/// The age recipient of one member line: a user's encryption key.
pub fn recipient(key: &MemberKey) -> Result<Box<dyn age::Recipient + Send>, String> {
    match key.kind {
        KeyKind::Age => key
            .key
            .trim()
            .parse::<age::x25519::Recipient>()
            .map(|r| Box::new(r) as Box<dyn age::Recipient + Send>)
            .map_err(|e| e.to_string()),
        #[cfg(feature = "pq")]
        KeyKind::AgePq => key
            .key
            .parse::<crate::pq::Recipient>()
            .map(|r| Box::new(r) as Box<dyn age::Recipient + Send>)
            .map_err(str::to_string),
        #[cfg(not(feature = "pq"))]
        KeyKind::AgePq => {
            Err("a quantum-safe key ring needs gunnar-crypt's `pq` feature".to_string())
        }
        KeyKind::SshEd25519 | KeyKind::SshRsa => Err(
            "an SSH key is an unlock method of its owner's encryption key, never a member key"
                .to_string(),
        ),
    }
}

/// Wrap `ring` to every key in `members`, with the scheme of its level;
/// returns the armored age file (the content of `.gunnar-crypt/keys`).
pub fn wrap(ring: &Keyring, members: &Members) -> Result<String, WrapError> {
    if members.is_empty() {
        return Err(WrapError::NoMembers);
    }
    let mut recipients = Vec::new();
    for m in members.entries() {
        recipients.push(recipient(m).map_err(|e| WrapError::BadKey(m.name.clone(), e))?);
    }
    let encryptor = age::Encryptor::with_recipients(
        recipients.iter().map(|r| r.as_ref() as &dyn age::Recipient),
    )
    .map_err(|e| WrapError::Age(e.to_string()))?;
    let mut out = Vec::new();
    let armor = ArmoredWriter::wrap_output(&mut out, Format::AsciiArmor)
        .map_err(|e| WrapError::Age(e.to_string()))?;
    let mut w = encryptor
        .wrap_output(armor)
        .map_err(|e| WrapError::Age(e.to_string()))?;
    w.write_all(ring.to_text().as_bytes())
        .map_err(|e| WrapError::Age(e.to_string()))?;
    w.finish()
        .and_then(|a| a.finish())
        .map_err(|e| WrapError::Age(e.to_string()))?;
    String::from_utf8(out).map_err(|e| WrapError::Age(e.to_string()))
}

/// Unwrap a key file with the given identities. The payload must be a key
/// ring; anything else is refused and dropped (zeroed).
pub fn unwrap(keys_file: &[u8], identities: &[&dyn age::Identity]) -> Result<Keyring, UnwrapError> {
    // `new_buffered`, not `new`: age's unbuffered header reader asks for the
    // bytes it still needs a few at a time and re-parses the header from its
    // start after each read, which is quadratic in the header's size — a
    // 500-member quantum-safe ring (a ~1 MB header) never finished
    // (MEASURED 2026-10-06, `tests/pq_stress.rs` and `examples/pq_bench.rs`).
    // The buffered reader parses what the buffer holds, once.
    let decryptor = age::Decryptor::new_buffered(ArmoredReader::new(keys_file))
        .map_err(|e| UnwrapError::Malformed(e.to_string()))?;
    let mut reader = match decryptor.decrypt(identities.iter().copied()) {
        Ok(r) => r,
        Err(age::DecryptError::NoMatchingKeys) => return Err(UnwrapError::NotARecipient),
        Err(e) => return Err(UnwrapError::Malformed(e.to_string())),
    };
    let mut buf = Zeroizing::new(Vec::new());
    reader
        .read_to_end(&mut buf)
        .map_err(|e| UnwrapError::Malformed(e.to_string()))?;
    let text = std::str::from_utf8(&buf)
        .map_err(|_| UnwrapError::NotAKeyring(KeyringError::NotAKeyring))?;
    Keyring::parse(text).map_err(UnwrapError::NotAKeyring)
}

/// [`unwrap`], after the ring's stanzas are checked against the members file
/// ([`policy::check_ring`]): one stanza per listed key, the SSH ones by their
/// tags, no type the repository's level does not allow. A ring with a stanza
/// for someone the members file does not name is refused before anything is
/// unwrapped.
pub fn unwrap_checked(
    keys_file: &[u8],
    members: &str,
    identities: &[&dyn age::Identity],
) -> Result<Keyring, UnwrapError> {
    policy::check_ring(members, keys_file).map_err(UnwrapError::Mismatch)?;
    unwrap(keys_file, identities)
}

/// A post-quantum identity file (`gunnar crypt keygen`, or `age-keygen -pq`)
/// as an age identity.
#[cfg(feature = "pq")]
pub fn pq_identity(text: &str) -> Result<Box<dyn age::Identity + Send + Sync>, IdentityError> {
    crate::pq::parse_identity_file(text)
        .map(|id| Box::new(id) as Box<dyn age::Identity + Send + Sync>)
        .map_err(|e| IdentityError::Read(e.to_string()))
}

/// Why a key file could not be used as an identity.
#[derive(Debug)]
pub enum IdentityError {
    /// Could not read or parse the file.
    Read(String),
    /// A key type age cannot decrypt with (for example a security-key `sk-`
    /// key, which only signs).
    Unsupported(String),
}

impl std::fmt::Display for IdentityError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            IdentityError::Read(e) => write!(f, "{e}"),
            IdentityError::Unsupported(e) => write!(
                f,
                "{e}. A security-key (sk-) SSH key can only sign and cannot decrypt; \
                 use an ordinary ed25519 key"
            ),
        }
    }
}
impl std::error::Error for IdentityError {}

#[cfg(feature = "wrap")]
pub use ssh::*;

#[cfg(feature = "wrap")]
mod ssh {
    use super::*;

    /// A passphrase source for an encrypted SSH key file.
    pub trait Passphrase: Clone + Send + Sync + 'static {
        /// Ask for the passphrase of the key `description` names; `None` gives up.
        fn ask(&self, description: &str) -> Option<String>;
    }

    #[derive(Clone)]
    struct Callbacks<P: Passphrase>(P);

    impl<P: Passphrase> age::Callbacks for Callbacks<P> {
        fn display_message(&self, message: &str) {
            eprintln!("{message}");
        }
        fn confirm(&self, _: &str, _: &str, _: Option<&str>) -> Option<bool> {
            None
        }
        fn request_public_string(&self, _: &str) -> Option<String> {
            None
        }
        fn request_passphrase(&self, description: &str) -> Option<age::secrecy::SecretString> {
            self.0
                .ask(description)
                .map(age::secrecy::SecretString::from)
        }
    }

    /// An SSH private key file as an age identity. An encrypted key asks
    /// `passphrase` when it is first needed.
    pub fn ssh_identity<P: Passphrase>(
        pem: &[u8],
        filename: Option<String>,
        passphrase: P,
    ) -> Result<Box<dyn age::Identity>, IdentityError> {
        let id = age::ssh::Identity::from_buffer(pem, filename)
            .map_err(|e| IdentityError::Read(e.to_string()))?;
        if let age::ssh::Identity::Unsupported(u) = &id {
            return Err(IdentityError::Unsupported(format!("{u:?}")));
        }
        Ok(Box::new(id.with_callbacks(Callbacks(passphrase))))
    }

    /// An SSH private key file as an age identity, decrypted NOW: an encrypted
    /// key asks `passphrase` once, here, rather than later in the middle of an
    /// unwrap: a passphrase is typed once, at start.
    pub fn ssh_identity_unlocked(
        pem: &[u8],
        passphrase: impl Fn(&str) -> Option<String>,
    ) -> Result<Box<dyn age::Identity + Send + Sync>, IdentityError> {
        let id = age::ssh::Identity::from_buffer(pem, None)
            .map_err(|e| IdentityError::Read(e.to_string()))?;
        match id {
            age::ssh::Identity::Unencrypted(_) => Ok(Box::new(id)),
            age::ssh::Identity::Encrypted(enc) => {
                let pass = passphrase("Passphrase for the SSH key")
                    .ok_or_else(|| IdentityError::Read("no passphrase given".into()))?;
                let key = enc
                    .decrypt(age::secrecy::SecretString::from(pass))
                    .map_err(|_| IdentityError::Read("wrong passphrase".into()))?;
                Ok(Box::new(age::ssh::Identity::from(key)))
            }
            age::ssh::Identity::Unsupported(u) => Err(IdentityError::Unsupported(format!("{u:?}"))),
        }
    }

    /// A passphrase source that never answers: for key files without one.
    #[derive(Clone, Copy, Debug)]
    pub struct NoPassphrase;

    impl Passphrase for NoPassphrase {
        fn ask(&self, _: &str) -> Option<String> {
            None
        }
    }
}