Skip to main content

luks_and/
lib.rs

1//! luks-and: derive a key that requires BOTH a keyfile AND a passphrase.
2//!
3//! This crate is the pure, side-effect-free core: key derivation, the
4//! descriptor format, the integrity tag, a constant-time compare, and a
5//! known-answer self-test. All process hardening and I/O lives in the binary
6//! (`main.rs`), so everything here is directly testable.
7//!
8//! # Construction (v0.1)
9//!
10//! ```text
11//! pepper = BLAKE2b-512("luks-and/pepper/v0.1" ‖ lp(keyfile))[..32]
12//! key    = Argon2id(password = passphrase,
13//!                   salt     = salt,          // 16 random bytes, in descriptor
14//!                   secret   = pepper,        // Argon2 "K"
15//!                   m, t, p, key_len)
16//! tag    = BLAKE2b-512("luks-and/tag/v0.1" ‖ lp(key))[..16]
17//! ```
18//! where `lp(x) = u64_le(x.len()) ‖ x`.
19//!
20//! The passphrase is memory-hard stretched, so a leaked keyfile does not make
21//! it cheap to brute force; the keyfile is bound in as the Argon2 secret, so a
22//! leaked passphrase is useless without it. The random per-descriptor salt
23//! makes every enrolled key independent, so the same (keyfile, passphrase) pair
24//! yields unrelated keys on different volumes.
25//!
26//! The `tag` is a public 128-bit fingerprint of the derived key. It lets the
27//! caller confirm that a given (keyfile, passphrase, descriptor) reproduces the
28//! enrolled key *before* invoking cryptsetup, and distinguishes wrong inputs
29//! from a corrupt header. It reveals nothing invertible, but IS a brute-force
30//! oracle for anyone who already holds the keyfile — so the descriptor must be
31//! stored with the LUKS header, never with the keyfile.
32
33#![forbid(unsafe_code)]
34
35use core::fmt;
36
37use argon2::{Algorithm, Argon2, Block, Params as A2Params, Version};
38use blake2::{Blake2b512, Digest};
39use zeroize::Zeroizing;
40
41// Constants
42
43/// Length of the random salt stored in a descriptor.
44pub const SALT_LEN: usize = 16;
45/// Length of the integrity tag (128-bit truncation of BLAKE2b-512).
46pub const TAG_LEN: usize = 16;
47/// Length of the derived pepper fed to Argon2 as the secret.
48const PEPPER_LEN: usize = 32;
49
50const DOMAIN_PEPPER: &[u8] = b"luks-and/pepper/v0.1";
51const DOMAIN_TAG: &[u8] = b"luks-and/tag/v0.1";
52
53/// Descriptor magic (first line) and the only supported version / kdf.
54const MAGIC: &str = "luks-and-descriptor";
55const VERSION: &str = "0.1";
56const KDF: &str = "argon2id";
57
58/// Keyfile size sanity bounds. Below the minimum is almost certainly a
59/// truncated copy or a mistake and guts the "leaked passphrase is useless"
60/// half of the scheme; the maximum stops a wrong path (a disk image) from
61/// being silently hashed.
62pub const KEYFILE_MIN: u64 = 16;
63pub const KEYFILE_MAX: u64 = 1 << 20; // 1 MiB
64
65/// Maximum passphrase length accepted from stdin.
66pub const PASSPHRASE_MAX: usize = 64 * 1024;
67
68/// Argon2 parameter bounds. The memory floor keeps a typo'd descriptor from
69/// silently producing a weak KDF; the ceiling stops a hostile descriptor from
70/// requesting an enormous arena.
71pub const MIN_M_COST_KIB: u32 = 8 * 1024; // 8 MiB
72pub const MAX_M_COST_KIB: u32 = 4 * 1024 * 1024; // 4 GiB
73pub const MIN_T_COST: u32 = 1;
74pub const MAX_T_COST: u32 = 1 << 24;
75pub const MIN_P_COST: u32 = 1;
76pub const MAX_P_COST: u32 = 1 << 8;
77pub const MIN_KEY_LEN: usize = 16;
78pub const MAX_KEY_LEN: usize = 1024;
79
80// Errors
81
82#[derive(Debug)]
83pub enum Error {
84    /// Derived key did not match the descriptor's tag: wrong passphrase or
85    /// wrong keyfile. Retryable (typically a typo). Maps to exit code 3.
86    TagMismatch,
87    /// The descriptor file is missing a field, malformed, or out of range.
88    Descriptor(String),
89    /// Invalid KDF parameters.
90    Params(String),
91    /// Argon2 or hashing failed internally.
92    Crypto(String),
93    /// The built-in known-answer self-test failed: this binary does not compute
94    /// the canonical derivation and must not be trusted.
95    SelfTest(String),
96}
97
98impl fmt::Display for Error {
99    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
100        match self {
101            Error::TagMismatch => write!(
102                f,
103                "derived key does not match the descriptor tag: wrong passphrase or wrong keyfile"
104            ),
105            Error::Descriptor(m) => write!(f, "descriptor: {m}"),
106            Error::Params(m) => write!(f, "parameters: {m}"),
107            Error::Crypto(m) => write!(f, "crypto: {m}"),
108            Error::SelfTest(m) => write!(f, "{m}"),
109        }
110    }
111}
112
113impl std::error::Error for Error {}
114
115// Params
116
117/// Argon2id cost parameters plus derived-key length.
118#[derive(Clone, Copy, PartialEq, Eq, Debug)]
119pub struct Params {
120    pub m_cost_kib: u32,
121    pub t_cost: u32,
122    pub p_cost: u32,
123    pub key_len: usize,
124}
125
126impl Params {
127    /// A strong default suitable for a rarely-used recovery path on a machine
128    /// with >=2 GiB RAM. Lower `m_cost_kib` for constrained devices.
129    pub const DEFAULT: Params = Params {
130        m_cost_kib: 1 << 20, // 1 GiB
131        t_cost: 4,
132        p_cost: 1,
133        key_len: 64,
134    };
135
136    /// Validate against the crate's bounds and Argon2's own requirements.
137    pub fn validate(&self) -> Result<(), Error> {
138        if self.m_cost_kib < MIN_M_COST_KIB || self.m_cost_kib > MAX_M_COST_KIB {
139            return Err(Error::Params(format!(
140                "m_cost_kib {} out of range [{}, {}]",
141                self.m_cost_kib, MIN_M_COST_KIB, MAX_M_COST_KIB
142            )));
143        }
144        if self.t_cost < MIN_T_COST || self.t_cost > MAX_T_COST {
145            return Err(Error::Params(format!(
146                "t_cost {} out of range [{}, {}]",
147                self.t_cost, MIN_T_COST, MAX_T_COST
148            )));
149        }
150        if self.p_cost < MIN_P_COST || self.p_cost > MAX_P_COST {
151            return Err(Error::Params(format!(
152                "p_cost {} out of range [{}, {}]",
153                self.p_cost, MIN_P_COST, MAX_P_COST
154            )));
155        }
156        if self.key_len < MIN_KEY_LEN || self.key_len > MAX_KEY_LEN {
157            return Err(Error::Params(format!(
158                "key_len {} out of range [{}, {}]",
159                self.key_len, MIN_KEY_LEN, MAX_KEY_LEN
160            )));
161        }
162        // Argon2 also requires m_cost >= 8 * p_cost; surface any residual error.
163        self.to_argon2().map(|_| ())
164    }
165
166    fn to_argon2(self) -> Result<A2Params, Error> {
167        A2Params::new(self.m_cost_kib, self.t_cost, self.p_cost, Some(self.key_len))
168            .map_err(|e| Error::Params(format!("argon2 rejected parameters: {e}")))
169    }
170}
171
172/// Parse a memory size in KiB. A bare integer is KiB; suffixes `K`/`KiB`,
173/// `M`/`MiB`, `G`/`GiB` (case-insensitive, binary units) scale it. Overflow is
174/// an error rather than a wrap.
175pub fn parse_memory_kib(s: &str) -> Result<u32, Error> {
176    let s = s.trim();
177    if s.is_empty() {
178        return Err(Error::Params("empty memory value".into()));
179    }
180    let lower = s.to_ascii_lowercase();
181    let (num, mult): (&str, u64) = if let Some(n) = strip_suffix_any(&lower, &["gib", "g"]) {
182        (n, 1024 * 1024)
183    } else if let Some(n) = strip_suffix_any(&lower, &["mib", "m"]) {
184        (n, 1024)
185    } else if let Some(n) = strip_suffix_any(&lower, &["kib", "k"]) {
186        (n, 1)
187    } else {
188        (lower.as_str(), 1)
189    };
190    let num = num.trim();
191    if num.is_empty() || !num.bytes().all(|b| b.is_ascii_digit()) {
192        return Err(Error::Params(format!("invalid memory value {s:?}")));
193    }
194    let base: u64 = num
195        .parse()
196        .map_err(|_| Error::Params(format!("invalid memory value {s:?}")))?;
197    let kib = base
198        .checked_mul(mult)
199        .ok_or_else(|| Error::Params(format!("memory value {s:?} overflows")))?;
200    if kib > u32::MAX as u64 {
201        return Err(Error::Params(format!("memory value {s:?} too large")));
202    }
203    Ok(kib as u32)
204}
205
206/// Strict decimal parse: ASCII digits only, non-empty. `str::parse` alone
207/// also accepts a leading `+`, which would make the descriptor format
208/// non-canonical ("t_cost = +4" round-trips to a different byte string).
209pub fn parse_dec_u32(s: &str) -> Option<u32> {
210    if s.is_empty() || !s.bytes().all(|b| b.is_ascii_digit()) {
211        return None;
212    }
213    s.parse().ok()
214}
215
216/// Strip the first matching suffix, returning the remaining numeric part.
217/// `lower` must already be lowercased; suffixes are checked longest-first by the
218/// caller's ordering.
219fn strip_suffix_any<'a>(lower: &'a str, suffixes: &[&str]) -> Option<&'a str> {
220    for suf in suffixes {
221        if let Some(rest) = lower.strip_suffix(suf) {
222            return Some(rest);
223        }
224    }
225    None
226}
227
228// Hashing/Derivation
229
230/// BLAKE2b-512 over a fixed domain tag followed by length-prefixed fields.
231/// Length prefixing makes the field boundaries unambiguous: distinct inputs
232/// cannot alias without a BLAKE2b collision.
233fn tagged_hash(domain: &[u8], fields: &[&[u8]]) -> Zeroizing<[u8; 64]> {
234    let mut h = Blake2b512::new();
235    h.update((domain.len() as u64).to_le_bytes());
236    h.update(domain);
237    for field in fields {
238        h.update((field.len() as u64).to_le_bytes());
239        h.update(field);
240    }
241    let mut out = Zeroizing::new([0u8; 64]);
242    out.copy_from_slice(&h.finalize());
243    out
244}
245
246/// Derive the key from both factors. `salt` must be exactly [`SALT_LEN`] bytes.
247///
248/// The same call is used for enrollment and unlock, so the two derivations are
249/// identical by construction.
250pub fn derive(
251    passphrase: &[u8],
252    keyfile: &[u8],
253    salt: &[u8],
254    params: &Params,
255) -> Result<Zeroizing<Vec<u8>>, Error> {
256    if salt.len() != SALT_LEN {
257        return Err(Error::Crypto(format!(
258            "salt must be {SALT_LEN} bytes, got {}",
259            salt.len()
260        )));
261    }
262    params.validate()?;
263
264    // Bound the Argon2 secret to a fixed size regardless of keyfile length.
265    let pepper_full = tagged_hash(DOMAIN_PEPPER, &[keyfile]);
266    let pepper = &pepper_full[..PEPPER_LEN];
267
268    let a2 = params.to_argon2()?;
269    let block_count = a2.block_count();
270    let argon = Argon2::new_with_secret(pepper, Algorithm::Argon2id, Version::V0x13, a2)
271        .map_err(|e| Error::Crypto(format!("argon2 init: {e}")))?;
272
273    // Provide the working memory ourselves (no `alloc` feature needed). With
274    // argon2's `zeroize` feature, Block: Zeroize, so wrapping the arena in
275    // Zeroizing scrubs ~m_cost of derived material on drop, including on the
276    // error paths below.
277    let mut blocks: Zeroizing<Vec<Block>> = Zeroizing::new(vec![Block::default(); block_count]);
278    let mut out = Zeroizing::new(vec![0u8; params.key_len]);
279    argon
280        .hash_password_into_with_memory(passphrase, salt, &mut out, blocks.as_mut_slice())
281        .map_err(|e| Error::Crypto(format!("argon2 derive: {e}")))?;
282    Ok(out)
283}
284
285/// Public 128-bit integrity fingerprint of a derived key.
286pub fn key_tag(key: &[u8]) -> [u8; TAG_LEN] {
287    let full = tagged_hash(DOMAIN_TAG, &[key]);
288    let mut t = [0u8; TAG_LEN];
289    t.copy_from_slice(&full[..TAG_LEN]);
290    t
291}
292
293/// Constant-time equality. Length is not treated as secret (tags are fixed
294/// length). `black_box` on every accumulator step prevents the compiler from
295/// proving anything about `acc` mid-loop (e.g. exiting early once it
296/// saturates), not merely from short-circuiting the final comparison.
297pub fn ct_eq(a: &[u8], b: &[u8]) -> bool {
298    if a.len() != b.len() {
299        return false;
300    }
301    let mut acc = 0u8;
302    for i in 0..a.len() {
303        acc = core::hint::black_box(acc | (a[i] ^ b[i]));
304    }
305    acc == 0
306}
307
308/// Verify a derived key against an expected tag in constant time.
309pub fn verify_tag(key: &[u8], expected: &[u8; TAG_LEN]) -> Result<(), Error> {
310    if ct_eq(&key_tag(key), expected) {
311        Ok(())
312    } else {
313        Err(Error::TagMismatch)
314    }
315}
316
317// Hex
318
319pub fn hex_encode(bytes: &[u8]) -> String {
320    const HEX: &[u8; 16] = b"0123456789abcdef";
321    let mut s = String::with_capacity(bytes.len() * 2);
322    for &b in bytes {
323        s.push(HEX[(b >> 4) as usize] as char);
324        s.push(HEX[(b & 0x0f) as usize] as char);
325    }
326    s
327}
328
329fn hex_val(c: u8) -> Result<u8, Error> {
330    match c {
331        b'0'..=b'9' => Ok(c - b'0'),
332        b'a'..=b'f' => Ok(c - b'a' + 10),
333        b'A'..=b'F' => Ok(c - b'A' + 10),
334        _ => Err(Error::Descriptor("value is not valid hex".into())),
335    }
336}
337
338/// Decode exactly `out.len()` bytes of lowercase/uppercase hex into `out`.
339pub fn hex_decode_into(s: &str, out: &mut [u8]) -> Result<(), Error> {
340    if s.len() != out.len() * 2 {
341        return Err(Error::Descriptor(format!(
342            "expected {} hex chars, got {}",
343            out.len() * 2,
344            s.len()
345        )));
346    }
347    for (i, chunk) in s.as_bytes().chunks_exact(2).enumerate() {
348        out[i] = (hex_val(chunk[0])? << 4) | hex_val(chunk[1])?;
349    }
350    Ok(())
351}
352
353// Descriptor
354
355/// Non-secret metadata needed to reproduce a derivation: everything except the
356/// keyfile and passphrase. Stored with the LUKS header; never with the keyfile.
357#[derive(Clone, PartialEq, Eq, Debug)]
358pub struct Descriptor {
359    pub params: Params,
360    pub salt: [u8; SALT_LEN],
361    pub tag: [u8; TAG_LEN],
362}
363
364impl Descriptor {
365    /// Render the canonical text form (trailing newline included).
366    pub fn serialize(&self) -> String {
367        format!(
368            "{MAGIC}\n\
369             version = {VERSION}\n\
370             kdf = {KDF}\n\
371             m_cost_kib = {}\n\
372             t_cost = {}\n\
373             p_cost = {}\n\
374             key_len = {}\n\
375             salt = {}\n\
376             tag = {}\n",
377            self.params.m_cost_kib,
378            self.params.t_cost,
379            self.params.p_cost,
380            self.params.key_len,
381            hex_encode(&self.salt),
382            hex_encode(&self.tag),
383        )
384    }
385
386    /// Parse the canonical text form. Strict: the magic line must match, every
387    /// required field must be present exactly once, no unknown fields are
388    /// allowed, and all values must be in range. Never silently defaults.
389    pub fn parse(text: &str) -> Result<Descriptor, Error> {
390        let mut lines = text.lines().map(str::trim).filter(|l| !l.is_empty());
391
392        match lines.next() {
393            Some(MAGIC) => {}
394            Some(other) => {
395                return Err(Error::Descriptor(format!(
396                    "first line is {other:?}, expected {MAGIC:?}"
397                )))
398            }
399            None => return Err(Error::Descriptor("empty descriptor".into())),
400        }
401
402        let mut version: Option<String> = None;
403        let mut kdf: Option<String> = None;
404        let mut m_cost_kib: Option<u32> = None;
405        let mut t_cost: Option<u32> = None;
406        let mut p_cost: Option<u32> = None;
407        let mut key_len: Option<usize> = None;
408        let mut salt: Option<[u8; SALT_LEN]> = None;
409        let mut tag: Option<[u8; TAG_LEN]> = None;
410
411        for line in lines {
412            let (key, value) = line
413                .split_once('=')
414                .ok_or_else(|| Error::Descriptor(format!("line {line:?} is not key = value")))?;
415            let key = key.trim();
416            let value = value.trim();
417
418            macro_rules! set_once {
419                ($slot:ident, $parsed:expr) => {{
420                    if $slot.is_some() {
421                        return Err(Error::Descriptor(format!("duplicate field {key:?}")));
422                    }
423                    $slot = Some($parsed);
424                }};
425            }
426
427            match key {
428                "version" => set_once!(version, value.to_string()),
429                "kdf" => set_once!(kdf, value.to_string()),
430                "m_cost_kib" => set_once!(
431                    m_cost_kib,
432                    parse_dec_u32(value)
433                        .ok_or_else(|| Error::Descriptor(format!("m_cost_kib {value:?} invalid")))?
434                ),
435                "t_cost" => set_once!(
436                    t_cost,
437                    parse_dec_u32(value)
438                        .ok_or_else(|| Error::Descriptor(format!("t_cost {value:?} invalid")))?
439                ),
440                "p_cost" => set_once!(
441                    p_cost,
442                    parse_dec_u32(value)
443                        .ok_or_else(|| Error::Descriptor(format!("p_cost {value:?} invalid")))?
444                ),
445                "key_len" => set_once!(
446                    key_len,
447                    parse_dec_u32(value)
448                        .ok_or_else(|| Error::Descriptor(format!("key_len {value:?} invalid")))?
449                        as usize
450                ),
451                "salt" => {
452                    let mut s = [0u8; SALT_LEN];
453                    hex_decode_into(value, &mut s)?;
454                    set_once!(salt, s);
455                }
456                "tag" => {
457                    let mut t = [0u8; TAG_LEN];
458                    hex_decode_into(value, &mut t)?;
459                    set_once!(tag, t);
460                }
461                other => return Err(Error::Descriptor(format!("unknown field {other:?}"))),
462            }
463        }
464
465        let miss = |name: &str| Error::Descriptor(format!("missing field {name:?}"));
466        let version = version.ok_or_else(|| miss("version"))?;
467        if version != VERSION {
468            return Err(Error::Descriptor(format!(
469                "unsupported version {version:?} (this build handles {VERSION:?})"
470            )));
471        }
472        let kdf = kdf.ok_or_else(|| miss("kdf"))?;
473        if kdf != KDF {
474            return Err(Error::Descriptor(format!(
475                "unsupported kdf {kdf:?} (this build handles {KDF:?})"
476            )));
477        }
478
479        let params = Params {
480            m_cost_kib: m_cost_kib.ok_or_else(|| miss("m_cost_kib"))?,
481            t_cost: t_cost.ok_or_else(|| miss("t_cost"))?,
482            p_cost: p_cost.ok_or_else(|| miss("p_cost"))?,
483            key_len: key_len.ok_or_else(|| miss("key_len"))?,
484        };
485        params.validate()?;
486
487        Ok(Descriptor {
488            params,
489            salt: salt.ok_or_else(|| miss("salt"))?,
490            tag: tag.ok_or_else(|| miss("tag"))?,
491        })
492    }
493}
494
495// Known-answer self-test
496//
497// Proves THIS build computes the canonical derivation before it is trusted to
498// enrol or unlock. Catches a swapped/mis-compiled argon2 or blake2 that the
499// descriptor's declared params cannot: the params say what SHOULD be computed,
500// the KAT checks what IS computed. The vector is over the real derive/key_tag
501// path at cheap fixed params (magnitude does not affect behavior).
502
503const KAT_PASSPHRASE: &[u8] = b"luks-and self-test vector v0.1";
504const KAT_KEYFILE: &[u8] = &[0x5A; 48];
505const KAT_SALT: &[u8; SALT_LEN] = &[
506    0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff,
507];
508const KAT_PARAMS: Params = Params {
509    m_cost_kib: 8192,
510    t_cost: 1,
511    p_cost: 1,
512    key_len: 64,
513};
514// Filled in from the canonical code; see the `kat_print` test.
515const KAT_KEY_HEX: &str = "df460d6e485a25e339a589879c757b9a03d1aa8f88db2119e0410ad0d386280a199492b99c4376cf3adabe47d88646f06cf444517efb541a2b071501ecb353cc";
516const KAT_TAG_HEX: &str = "d68dda296ae80de42598da75a819a497";
517
518/// Run the known-answer test. Returns [`Error::SelfTest`] on any mismatch.
519pub fn selftest() -> Result<(), Error> {
520    let key = derive(KAT_PASSPHRASE, KAT_KEYFILE, KAT_SALT, &KAT_PARAMS)
521        .map_err(|e| Error::SelfTest(format!("selftest derive failed: {e}")))?;
522    let got_key = hex_encode(&key);
523    if got_key != KAT_KEY_HEX {
524        return Err(Error::SelfTest(format!(
525            "SELFTEST FAILED: key vector mismatch (expected {KAT_KEY_HEX}, got {got_key}). \
526             This binary does not compute the canonical luks-and v0.1 derivation \
527             (swapped/mis-compiled argon2 or blake2?); refusing to run."
528        )));
529    }
530    let got_tag = hex_encode(&key_tag(&key));
531    if got_tag != KAT_TAG_HEX {
532        return Err(Error::SelfTest(format!(
533            "SELFTEST FAILED: tag vector mismatch (expected {KAT_TAG_HEX}, got {got_tag}); \
534             refusing to run."
535        )));
536    }
537    Ok(())
538}
539
540/// Human-readable summary of the compiled scheme (all public).
541pub fn scheme_string() -> String {
542    format!("luks-and v{VERSION} kdf={KDF} tag_len={TAG_LEN} salt_len={SALT_LEN}")
543}
544
545#[cfg(test)]
546mod internal_tests {
547    use super::*;
548
549    #[test]
550    fn kat_print() {
551        // Prints the canonical vector for baking into KAT_*_HEX.
552        let key = derive(KAT_PASSPHRASE, KAT_KEYFILE, KAT_SALT, &KAT_PARAMS).unwrap();
553        println!("KAT_KEY_HEX = {}", hex_encode(&key));
554        println!("KAT_TAG_HEX = {}", hex_encode(&key_tag(&key)));
555    }
556
557    #[test]
558    fn selftest_passes_once_baked() {
559        if KAT_KEY_HEX.starts_with("__") {
560            return;
561        }
562        selftest().expect("built-in KAT must pass");
563    }
564}