pqbox 1.0.0

Post-quantum crypto toolkit: hybrid ML-KEM-1024 + P-384 sealed boxes, composite ML-DSA-87 signatures, an opt-in paranoid suite adding Classic McEliece and SLH-DSA, AEAD, KDF, hashing and Argon2id
Documentation
//! Cipher suites. One byte in every object header names the suite, so a key, a ciphertext or a
//! signature can never be used with another suite's algorithms.
//!
//! | Id | Name | KEM | Signature |
//! |---|---|---|---|
//! | `0x01` | `xwing` (compat only) | X-Wing (ML-KEM-768 + X25519, IETF draft) | ML-DSA-65 + Ed25519 |
//! | `0x02` | `pqbox-max` (default) | ML-KEM-1024 + ECDH P-384 | ML-DSA-87 + ECDSA P-384 |
//! | `0x03` | `pqbox-paranoid` | ML-KEM-1024 + Classic McEliece 8192128 + ECDH P-384 | ML-DSA-87 + SLH-DSA-SHAKE-256s + ECDSA P-384 |
//!
//! A hybrid stays secure as long as one of its components holds: KEM shared secrets are combined
//! so that breaking one component is not enough, and every signature in a suite must verify.
//! The `xwing` suite exists only for interoperability with X-Wing (hush, age-style tooling); its
//! classical half is a 256-bit curve, so its security rests on ML-KEM-768 and ML-DSA-65 alone.
//!
//! `pqbox-paranoid` is compiled only with the `paranoid` cargo feature (off by default). Its
//! SLH-DSA implementation (`slh-dsa` 0.2.0-rc.5) is a release candidate: treat the suite as
//! experimental.
//!
//! # Suite policy
//!
//! Every function that parses or opens an object it did not create (`from_bytes`,
//! [`crate::seal::open`]) checks the suite in the header against a [`SuitePolicy`]. The default
//! policy accepts only `pqbox-max`, so an attacker cannot steer an application into the compat
//! `xwing` suite or into the large paranoid parsers. Each such function has a
//! `*_with_policy` twin for applications that use the other suites on purpose:
//!
//! ```
//! use pqbox::{Suite, SuitePolicy};
//! let policy = SuitePolicy::default().allow(Suite::XWing);
//! assert!(policy.allows(Suite::Max) && policy.allows(Suite::XWing));
//! ```

use crate::{Error, Result};

/// A cipher suite.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
#[repr(u8)]
pub enum Suite {
    /// `0x01`, compat only: X-Wing KEM and ML-DSA-65 + Ed25519 (NIST category 3), for
    /// interoperability with the X-Wing IETF draft and with hush. Never the default; its security
    /// rests on ML-KEM-768 and ML-DSA-65.
    XWing = 0x01,
    /// `0x02` (default): ML-KEM-1024 + ECDH P-384 and ML-DSA-87 + ECDSA P-384 (NIST category 5).
    #[default]
    Max = 0x02,
    /// `0x03`: adds Classic McEliece 8192128 to the KEM and SLH-DSA-SHAKE-256s to the signatures,
    /// so security survives a break of lattice cryptography as well as of elliptic curves.
    /// Keys and signatures are large (a 1.3 MB public key, 34 KB signatures). Requires the
    /// `paranoid` cargo feature; experimental while `slh-dsa` is a release candidate.
    #[cfg(feature = "paranoid")]
    Paranoid = 0x03,
}

/// The canonical name of the paranoid suite (known even when it is not compiled in).
const PARANOID_NAME: &str = "pqbox-paranoid";

impl Suite {
    /// Every suite compiled into this build, in id order.
    #[cfg(feature = "paranoid")]
    pub const ALL: [Suite; 3] = [Suite::XWing, Suite::Max, Suite::Paranoid];
    /// Every suite compiled into this build, in id order.
    #[cfg(not(feature = "paranoid"))]
    pub const ALL: [Suite; 2] = [Suite::XWing, Suite::Max];

    /// Parses a suite id.
    ///
    /// # Errors
    /// [`Error::UnknownSuite`], or [`Error::SuiteNotEnabled`] for `0x03` in a build without the
    /// `paranoid` feature.
    pub fn from_id(id: u8) -> Result<Self> {
        match id {
            0x01 => Ok(Self::XWing),
            0x02 => Ok(Self::Max),
            #[cfg(feature = "paranoid")]
            0x03 => Ok(Self::Paranoid),
            #[cfg(not(feature = "paranoid"))]
            0x03 => Err(Error::SuiteNotEnabled(PARANOID_NAME)),
            other => Err(Error::UnknownSuite(other)),
        }
    }

    /// The suite id.
    #[must_use]
    pub fn id(self) -> u8 {
        self as u8
    }

    /// The canonical name.
    #[must_use]
    pub fn name(self) -> &'static str {
        match self {
            Self::XWing => "xwing",
            Self::Max => "pqbox-max",
            #[cfg(feature = "paranoid")]
            Self::Paranoid => PARANOID_NAME,
        }
    }

    /// The KEM components, post-quantum first.
    #[must_use]
    pub fn kem_components(self) -> &'static [&'static str] {
        match self {
            Self::XWing => &["ML-KEM-768", "X25519"],
            Self::Max => &["ML-KEM-1024", "ECDH-P384"],
            #[cfg(feature = "paranoid")]
            Self::Paranoid => &["ML-KEM-1024", "Classic-McEliece-8192128", "ECDH-P384"],
        }
    }

    /// The signature components, post-quantum first.
    #[must_use]
    pub fn signature_components(self) -> &'static [&'static str] {
        match self {
            Self::XWing => &["ML-DSA-65", "Ed25519"],
            Self::Max => &["ML-DSA-87", "ECDSA-P384-SHA384"],
            #[cfg(feature = "paranoid")]
            Self::Paranoid => &["ML-DSA-87", "SLH-DSA-SHAKE-256s", "ECDSA-P384-SHA384"],
        }
    }

    /// Whether this suite is kept only for interoperability (never a default).
    #[must_use]
    pub fn is_compat_only(self) -> bool {
        self == Self::XWing
    }

    /// Parses a suite name: `xwing`, `pqbox-max` (or `max`), `pqbox-paranoid` (or `paranoid`).
    ///
    /// # Errors
    /// [`Error::InvalidParams`] for an unknown name, [`Error::SuiteNotEnabled`] for
    /// `pqbox-paranoid` in a build without the `paranoid` feature.
    pub fn from_name(name: &str) -> Result<Self> {
        match name.to_ascii_lowercase().replace('_', "-").as_str() {
            "xwing" | "x-wing" => Ok(Self::XWing),
            "pqbox-max" | "max" => Ok(Self::Max),
            #[cfg(feature = "paranoid")]
            "pqbox-paranoid" | "paranoid" => Ok(Self::Paranoid),
            #[cfg(not(feature = "paranoid"))]
            "pqbox-paranoid" | "paranoid" => Err(Error::SuiteNotEnabled(PARANOID_NAME)),
            _ => Err(Error::InvalidParams("unknown suite")),
        }
    }
}

impl core::fmt::Display for Suite {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.write_str(self.name())
    }
}

impl core::str::FromStr for Suite {
    type Err = Error;
    fn from_str(s: &str) -> Result<Self> {
        Self::from_name(s)
    }
}

/// The suites that parsing and opening accept.
///
/// The default, [`SuitePolicy::DEFAULT`], accepts only `pqbox-max`. `xwing` (compat) and
/// `pqbox-paranoid` must be allowed explicitly with [`SuitePolicy::allow`]. Functions that
/// create objects from an explicit suite (`generate`, `from_raw`) are not subject to a policy.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct SuitePolicy {
    /// Bit `id` set when the suite with that id is allowed.
    mask: u8,
}

impl SuitePolicy {
    /// Only `pqbox-max`.
    pub const DEFAULT: Self = Self::only(Suite::Max);
    /// No suite at all; build up from it with [`SuitePolicy::allow`].
    pub const NONE: Self = Self { mask: 0 };
    /// Every suite compiled into this build. Meant for tools and tests that handle every suite
    /// on purpose.
    pub const ALL: Self = {
        let p = Self::NONE.allow(Suite::XWing).allow(Suite::Max);
        #[cfg(feature = "paranoid")]
        let p = p.allow(Suite::Paranoid);
        p
    };

    /// Exactly one suite.
    #[must_use]
    pub const fn only(suite: Suite) -> Self {
        Self::NONE.allow(suite)
    }

    /// This policy plus `suite`.
    #[must_use]
    pub const fn allow(self, suite: Suite) -> Self {
        Self {
            mask: self.mask | (1 << suite as u8),
        }
    }

    /// Whether `suite` is allowed.
    #[must_use]
    pub const fn allows(self, suite: Suite) -> bool {
        self.mask & (1 << suite as u8) != 0
    }

    /// The allowed suites, in id order.
    pub fn suites(self) -> impl Iterator<Item = Suite> {
        Suite::ALL.into_iter().filter(move |s| self.allows(*s))
    }

    /// Checks `suite` against the policy.
    ///
    /// # Errors
    /// [`Error::SuiteNotAllowed`].
    pub fn check(self, suite: Suite) -> Result<Suite> {
        if self.allows(suite) {
            Ok(suite)
        } else {
            Err(Error::SuiteNotAllowed(suite.name()))
        }
    }

    /// This policy plus the suites named in `names` (see [`Suite::from_name`]), for bindings
    /// and command-line options that take suite names.
    ///
    /// # Errors
    /// [`Error::UnknownSuite`] or [`Error::SuiteNotEnabled`] for a name this build cannot use.
    pub fn allow_names<'a>(self, names: impl IntoIterator<Item = &'a str>) -> Result<Self> {
        names
            .into_iter()
            .try_fold(self, |p, name| Ok(p.allow(Suite::from_name(name)?)))
    }

    /// Parses a suite id from a header and checks it against the policy.
    ///
    /// # Errors
    /// [`Error::UnknownSuite`], [`Error::SuiteNotEnabled`] or [`Error::SuiteNotAllowed`].
    pub fn suite_from_id(self, id: u8) -> Result<Suite> {
        self.check(Suite::from_id(id)?)
    }
}

impl Default for SuitePolicy {
    fn default() -> Self {
        Self::DEFAULT
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn ids_and_names_round_trip() {
        for s in Suite::ALL {
            assert_eq!(Suite::from_id(s.id()).unwrap(), s);
            assert_eq!(Suite::from_name(s.name()).unwrap(), s);
        }
        assert_eq!(Suite::default(), Suite::Max);
        assert_eq!(Suite::from_id(0), Err(Error::UnknownSuite(0)));
        assert_eq!(Suite::from_id(4), Err(Error::UnknownSuite(4)));
        assert!(Suite::from_name("rsa").is_err());
        #[cfg(not(feature = "paranoid"))]
        {
            assert_eq!(Suite::from_id(3), Err(Error::SuiteNotEnabled("pqbox-paranoid")));
            assert_eq!(
                Suite::from_name("paranoid"),
                Err(Error::SuiteNotEnabled("pqbox-paranoid"))
            );
        }
    }

    #[test]
    fn default_policy_accepts_only_max() {
        let p = SuitePolicy::default();
        assert_eq!(p, SuitePolicy::DEFAULT);
        assert!(p.allows(Suite::Max));
        assert!(!p.allows(Suite::XWing));
        assert_eq!(p.check(Suite::XWing), Err(Error::SuiteNotAllowed("xwing")));
        assert_eq!(p.suite_from_id(2), Ok(Suite::Max));
        assert_eq!(p.suite_from_id(1), Err(Error::SuiteNotAllowed("xwing")));
        assert_eq!(p.suite_from_id(9), Err(Error::UnknownSuite(9)));
        assert_eq!(p.suites().collect::<Vec<_>>(), [Suite::Max]);
        #[cfg(feature = "paranoid")]
        {
            assert!(!p.allows(Suite::Paranoid));
            assert_eq!(p.suite_from_id(3), Err(Error::SuiteNotAllowed("pqbox-paranoid")));
        }
        let x = p.allow(Suite::XWing);
        assert!(x.allows(Suite::XWing) && x.allows(Suite::Max));
        assert_eq!(
            SuitePolicy::only(Suite::XWing).check(Suite::Max),
            Err(Error::SuiteNotAllowed("pqbox-max"))
        );
        assert!(!SuitePolicy::NONE.allows(Suite::Max));
        assert_eq!(SuitePolicy::ALL.suites().collect::<Vec<_>>(), Suite::ALL.to_vec());
    }

    /// No default or recommended suite relies on a 256-bit curve, and every one carries ML-KEM
    /// and ML-DSA at category 5.
    #[test]
    fn non_compat_suites_are_post_quantum_with_p384() {
        assert!(!Suite::default().is_compat_only());
        for s in Suite::ALL.into_iter().filter(|s| !s.is_compat_only()) {
            assert!(s.kem_components().contains(&"ML-KEM-1024"), "{s}");
            assert!(s.signature_components().contains(&"ML-DSA-87"), "{s}");
            for c in s.kem_components().iter().chain(s.signature_components()) {
                assert!(!["X25519", "Ed25519", "P-256", "secp256k1"].contains(c), "{s}: {c}");
            }
            assert!(s.kem_components().contains(&"ECDH-P384"), "{s}");
            assert!(s.signature_components().contains(&"ECDSA-P384-SHA384"), "{s}");
        }
        // Every suite, compat included, has a post-quantum KEM and signature.
        for s in Suite::ALL {
            assert!(s.kem_components()[0].starts_with("ML-KEM"), "{s}");
            assert!(s.signature_components()[0].starts_with("ML-DSA"), "{s}");
        }
    }
}