feat: harden fcry format and IO policy

Introduce a central policy module for format and resource validation, then
route header parsing, KDF acceptance, range arithmetic, and pipeline sizing
through that policy. New encryptions now write v3 headers that include an
authenticated key commitment, which lets decrypt reject wrong keys or
passphrases before chunk processing while preserving valid v1/v2 decrypt
compatibility inside the configured caps.

Replace process-list-visible raw key input with --key-file, add passphrase NFC
normalization, enforce stronger new-encryption passphrase/KDF floors unless
--allow-weak-kdf is supplied, and add a configurable decrypt Argon2 memory
ceiling. Chunk buffers in the serial, parallel, and lookahead paths now use
zeroizing storage.

Rework output handling around randomized create-new temporary files with Unix
0600 mode, file fsync before persist, best-effort parent directory fsync,
default no-overwrite behavior, safe in-place replacement, --force, --temp-dir,
and --buffer-verify for decrypt-to-stdout.

Known caveat: --key-file currently reads with a single read call. That is fine
for regular files but can reject short reads from pipes or process
substitution. A follow-up fix will make key-file reads loop before EOF.

Test Plan:
- cargo fmt --check
- cargo clippy --all-targets -- -D warnings
- cargo test
- git diff --check
- cargo run -- --help

Refs: fcry security hardening plan
This commit is contained in:
2026-06-09 23:45:02 +02:00
parent d7b0127d20
commit 81ac1475ad
12 changed files with 1625 additions and 227 deletions
+91 -10
View File
@@ -14,6 +14,7 @@
//! kdf_params variable (depends on kdf_id)
//! nonce_prefix [u8; 19] 19 (STREAM nonce prefix)
//! plaintext_length u64 LE 8 (only if version >= 2 and flags & 0x01)
//! key_commitment [u8; 32] 32 (only if version >= 3 and flags & 0x02)
//! --- end of header ---
//! chunk[0..N] each chunk_size + 16 bytes,
//! last may be shorter
@@ -28,13 +29,16 @@
//! * v2 — adds `FLAG_LENGTH_COMMITTED` (bit 0); when set, the total plaintext
//! length is appended after `nonce_prefix`. This enables random-access
//! decryption without scanning predecessors.
//! * v3 — adds `FLAG_KEY_COMMITTED` (bit 1) and an authenticated key
//! commitment for fast wrong-key detection before chunk processing.
use std::io::Read;
use crate::error::FcryError;
use crate::policy;
const MAGIC: [u8; 4] = *b"fcry";
pub const VERSION_CURRENT: u8 = 2;
pub const VERSION_CURRENT: u8 = 3;
const VERSION_MIN: u8 = 1;
pub const NONCE_PREFIX_LEN: usize = 19;
@@ -43,9 +47,11 @@ pub const TAG_LEN: usize = 16;
/// Set in `flags` when the header carries an authenticated `plaintext_length`
/// field. Required for random-access decryption.
pub const FLAG_LENGTH_COMMITTED: u8 = 0x01;
pub const FLAG_KEY_COMMITTED: u8 = 0x02;
/// Mask of all flag bits this build understands. Unknown bits → reject.
const FLAG_KNOWN_MASK: u8 = FLAG_LENGTH_COMMITTED;
const FLAG_KNOWN_MASK: u8 = FLAG_LENGTH_COMMITTED | FLAG_KEY_COMMITTED;
pub const KEY_COMMITMENT_LEN: usize = 32;
#[repr(u8)]
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
@@ -142,11 +148,13 @@ pub struct Header {
pub nonce_prefix: [u8; NONCE_PREFIX_LEN],
/// Total plaintext byte count. `Some` iff `flags & FLAG_LENGTH_COMMITTED`.
pub plaintext_length: Option<u64>,
/// v3 key commitment. `Some` iff `flags & FLAG_KEY_COMMITTED`.
pub key_commitment: Option<[u8; KEY_COMMITMENT_LEN]>,
}
impl Header {
pub fn encode(&self) -> Vec<u8> {
let mut out = Vec::with_capacity(72);
fn encode_without_commitment(&self) -> Vec<u8> {
let mut out = Vec::with_capacity(104);
out.extend_from_slice(&MAGIC);
out.push(self.version);
out.push(self.alg as u8);
@@ -165,7 +173,30 @@ impl Header {
out
}
pub fn encode(&self) -> Vec<u8> {
let mut out = self.encode_without_commitment();
if (self.flags & FLAG_KEY_COMMITTED) != 0 {
let commitment = self
.key_commitment
.expect("FLAG_KEY_COMMITTED set but key_commitment is None");
out.extend_from_slice(&commitment);
}
out
}
pub fn commitment_input_encoding(&self) -> Vec<u8> {
self.encode_without_commitment()
}
#[allow(dead_code)]
pub fn read(r: &mut impl Read) -> Result<Self, FcryError> {
Self::read_with_argon_cap(r, policy::default_argon_decrypt_cap_mib())
}
pub fn read_with_argon_cap(
r: &mut impl Read,
max_argon_memory_mib: u32,
) -> Result<Self, FcryError> {
let mut magic = [0u8; 4];
r.read_exact(&mut magic)?;
if magic != MAGIC {
@@ -189,18 +220,25 @@ impl Header {
if version < 2 && flags != 0 {
return Err(FcryError::Format("v1 header must have flags == 0".into()));
}
if version < 3 && (flags & FLAG_KEY_COMMITTED) != 0 {
return Err(FcryError::Format(
"key commitment flag requires v3 header".into(),
));
}
if version >= 3 && (flags & FLAG_KEY_COMMITTED) == 0 {
return Err(FcryError::Format("v3 header must commit the key".into()));
}
let alg = AlgId::from_u8(alg_id)?;
let mut chunk_size_bytes = [0u8; 4];
r.read_exact(&mut chunk_size_bytes)?;
let chunk_size = u32::from_le_bytes(chunk_size_bytes);
if chunk_size == 0 {
return Err(FcryError::Format("chunk_size must be > 0".into()));
}
policy::validate_chunk_size(chunk_size)?;
let mut kdf_id = [0u8; 1];
r.read_exact(&mut kdf_id)?;
let kdf = KdfParams::read_from(kdf_id[0], r)?;
policy::validate_header_kdf(&kdf, max_argon_memory_mib)?;
let mut nonce_prefix = [0u8; NONCE_PREFIX_LEN];
r.read_exact(&mut nonce_prefix)?;
@@ -213,6 +251,14 @@ impl Header {
None
};
let key_commitment = if (flags & FLAG_KEY_COMMITTED) != 0 {
let mut b = [0u8; KEY_COMMITMENT_LEN];
r.read_exact(&mut b)?;
Some(b)
} else {
None
};
Ok(Self {
version,
alg,
@@ -221,6 +267,7 @@ impl Header {
kdf,
nonce_prefix,
plaintext_length,
key_commitment,
})
}
}
@@ -235,11 +282,12 @@ mod tests {
let h = Header {
version: VERSION_CURRENT,
alg: AlgId::XChaCha20Poly1305,
flags: 0,
flags: FLAG_KEY_COMMITTED,
chunk_size: 1024 * 1024,
kdf: KdfParams::Raw,
nonce_prefix: [7u8; NONCE_PREFIX_LEN],
plaintext_length: None,
key_commitment: Some([1u8; KEY_COMMITMENT_LEN]),
};
let bytes = h.encode();
let mut cur = Cursor::new(&bytes);
@@ -250,6 +298,7 @@ mod tests {
assert_eq!(parsed.chunk_size, h.chunk_size);
assert_eq!(parsed.nonce_prefix, h.nonce_prefix);
assert_eq!(parsed.plaintext_length, None);
assert_eq!(parsed.key_commitment, h.key_commitment);
assert_eq!(cur.position() as usize, bytes.len());
}
@@ -258,20 +307,49 @@ mod tests {
let h = Header {
version: VERSION_CURRENT,
alg: AlgId::XChaCha20Poly1305,
flags: FLAG_LENGTH_COMMITTED,
flags: FLAG_LENGTH_COMMITTED | FLAG_KEY_COMMITTED,
chunk_size: 65536,
kdf: KdfParams::Raw,
nonce_prefix: [9u8; NONCE_PREFIX_LEN],
plaintext_length: Some(123_456_789),
key_commitment: Some([2u8; KEY_COMMITMENT_LEN]),
};
let bytes = h.encode();
let mut cur = Cursor::new(&bytes);
let parsed = Header::read(&mut cur).unwrap();
assert_eq!(parsed.flags, FLAG_LENGTH_COMMITTED);
assert_eq!(parsed.flags, FLAG_LENGTH_COMMITTED | FLAG_KEY_COMMITTED);
assert_eq!(parsed.plaintext_length, Some(123_456_789));
assert_eq!(parsed.key_commitment, h.key_commitment);
assert_eq!(cur.position() as usize, bytes.len());
}
#[test]
fn v3_encoding_layout_stable() {
let h = Header {
version: VERSION_CURRENT,
alg: AlgId::XChaCha20Poly1305,
flags: FLAG_LENGTH_COMMITTED | FLAG_KEY_COMMITTED,
chunk_size: 0x0102_0304,
kdf: KdfParams::Raw,
nonce_prefix: [0x55u8; NONCE_PREFIX_LEN],
plaintext_length: Some(0x0807_0605_0403_0201),
key_commitment: Some([0xaau8; KEY_COMMITMENT_LEN]),
};
let commitment_input = h.commitment_input_encoding();
assert_eq!(commitment_input.len(), 40);
assert_eq!(&commitment_input[..4], b"fcry");
assert_eq!(commitment_input[4], 3);
assert_eq!(
&commitment_input[32..40],
&0x0807_0605_0403_0201u64.to_le_bytes()
);
let aad = h.encode();
assert_eq!(aad.len(), 72);
assert_eq!(&aad[..40], &commitment_input);
assert_eq!(&aad[40..], &[0xaau8; KEY_COMMITMENT_LEN]);
}
#[test]
fn rejects_bad_magic() {
let mut bytes = Header {
@@ -282,6 +360,7 @@ mod tests {
kdf: KdfParams::Raw,
nonce_prefix: [0u8; NONCE_PREFIX_LEN],
plaintext_length: None,
key_commitment: Some([3u8; KEY_COMMITMENT_LEN]),
}
.encode();
bytes[0] ^= 1;
@@ -301,6 +380,7 @@ mod tests {
kdf: KdfParams::Raw,
nonce_prefix: [0u8; NONCE_PREFIX_LEN],
plaintext_length: None,
key_commitment: Some([4u8; KEY_COMMITMENT_LEN]),
}
.encode();
// flags byte is at offset 6 (4 magic + version + alg)
@@ -328,6 +408,7 @@ mod tests {
assert_eq!(parsed.flags, 0);
assert_eq!(parsed.chunk_size, 1024);
assert_eq!(parsed.plaintext_length, None);
assert_eq!(parsed.key_commitment, None);
// Re-encoding must reproduce the original v1 bytes exactly so the
// recomputed AAD matches what the file was authenticated with.
assert_eq!(parsed.encode(), bytes);