Skip to main content

sheetkit_core/crypt/
mod.rs

1//! Encryption and decryption support for password-protected Excel files.
2//!
3//! Excel files can be encrypted using either Standard Encryption (Office 2007,
4//! AES-128-ECB) or Agile Encryption (Office 2010+, AES-256-CBC). Encrypted
5//! files are stored in an OLE/CFB compound file container rather than a plain
6//! ZIP archive.
7//!
8//! This module provides:
9//! - CFB container reading and writing
10//! - EncryptionInfo parsing (both Standard and Agile formats)
11//! - Standard Encryption decryption (read-only)
12//! - Agile Encryption decryption and encryption (read/write)
13
14mod agile;
15mod cfb_io;
16mod standard;
17
18pub use agile::{
19    encrypt_package_agile, encrypt_package_agile_with_limits, verify_password_agile,
20    verify_password_agile_with_limits, AgileEncryptionInfo, DataIntegrity, KeyData, KeyEncryptor,
21};
22pub use standard::{StandardEncryptionHeader, StandardEncryptionVerifier};
23
24use crate::error::{Error, Result};
25use crate::resource::{
26    ResourceCategory, ResourceDimension, ResourceLimitError, ResourceOperation, ResourceStage,
27};
28
29const MIB: u64 = 1024 * 1024;
30const GIB: u64 = 1024 * MIB;
31const KIB: u64 = 1024;
32
33/// Finite limits for one encrypted-container operation.
34///
35/// Defaults admit 128 MiB CFB/package inputs, 256 named streams, 512 MiB of
36/// declared stream data, 128 MiB of required stream reads, one million KDF
37/// iterations per pass, and three million aggregate KDF iterations.
38#[derive(Debug, Clone, Copy, PartialEq, Eq)]
39pub struct CryptLimits {
40    /// Maximum bytes in the outer CFB input.
41    pub outer_cfb_bytes: u64,
42    /// Maximum number of named streams in the CFB directory.
43    pub named_stream_count: u64,
44    /// Maximum aggregate declared bytes across named CFB streams.
45    pub named_stream_declared_bytes: u64,
46    /// Maximum aggregate bytes read from required named CFB streams.
47    pub named_stream_read_bytes: u64,
48    /// Maximum declared and actual bytes in `/EncryptedPackage`.
49    pub encrypted_package_bytes: u64,
50    /// Maximum Agile KDF iterations in one password-derived pass.
51    pub kdf_iterations: u64,
52    /// Maximum aggregate password-derived hash iterations.
53    pub kdf_work: u64,
54}
55
56impl Default for CryptLimits {
57    fn default() -> Self {
58        Self {
59            outer_cfb_bytes: 128 * MIB,
60            named_stream_count: 256,
61            named_stream_declared_bytes: 512 * MIB,
62            named_stream_read_bytes: 128 * MIB,
63            encrypted_package_bytes: 128 * MIB,
64            kdf_iterations: 1_000_000,
65            kdf_work: 3_000_000,
66        }
67    }
68}
69
70impl CryptLimits {
71    /// Largest supported finite values. These ceilings cannot be disabled.
72    ///
73    /// The ceilings are 2 GiB outer/read/package bytes, 65,536 streams, 4 GiB
74    /// declared bytes, ten million iterations per pass, and thirty million
75    /// aggregate KDF iterations.
76    pub const fn hard_ceiling() -> Self {
77        Self {
78            outer_cfb_bytes: 2 * GIB,
79            named_stream_count: 65_536,
80            named_stream_declared_bytes: 4 * GIB,
81            named_stream_read_bytes: 2 * GIB,
82            encrypted_package_bytes: 2 * GIB,
83            kdf_iterations: 10_000_000,
84            kdf_work: 30_000_000,
85        }
86    }
87
88    fn validate(self, operation: ResourceOperation) -> Result<Self> {
89        let ceiling = Self::hard_ceiling();
90        for (category, dimension, value, maximum) in [
91            (
92                ResourceCategory::Container,
93                ResourceDimension::InputBytes,
94                self.outer_cfb_bytes,
95                ceiling.outer_cfb_bytes,
96            ),
97            (
98                ResourceCategory::Container,
99                ResourceDimension::StreamCount,
100                self.named_stream_count,
101                ceiling.named_stream_count,
102            ),
103            (
104                ResourceCategory::Container,
105                ResourceDimension::AggregateDeclaredBytes,
106                self.named_stream_declared_bytes,
107                ceiling.named_stream_declared_bytes,
108            ),
109            (
110                ResourceCategory::Container,
111                ResourceDimension::AggregateActualBytes,
112                self.named_stream_read_bytes,
113                ceiling.named_stream_read_bytes,
114            ),
115            (
116                ResourceCategory::Encryption,
117                ResourceDimension::InputBytes,
118                self.encrypted_package_bytes,
119                ceiling.encrypted_package_bytes,
120            ),
121            (
122                ResourceCategory::Encryption,
123                ResourceDimension::IterationCount,
124                self.kdf_iterations,
125                ceiling.kdf_iterations,
126            ),
127            (
128                ResourceCategory::Encryption,
129                ResourceDimension::OperationCount,
130                self.kdf_work,
131                ceiling.kdf_work,
132            ),
133        ] {
134            if value == 0 || value > maximum {
135                return Err(limit_error(
136                    operation,
137                    category,
138                    dimension,
139                    maximum,
140                    value.max(maximum.saturating_add(1)),
141                    ResourceStage::Validate,
142                ));
143            }
144        }
145        Ok(self)
146    }
147}
148
149#[derive(Debug, Clone, Copy, PartialEq, Eq)]
150pub(crate) struct EncryptionInfoLimits {
151    pub(crate) input_bytes: u64,
152    pub(crate) element_count: u64,
153    pub(crate) decoded_attribute_bytes: u64,
154}
155
156impl Default for EncryptionInfoLimits {
157    fn default() -> Self {
158        Self {
159            input_bytes: MIB,
160            element_count: 256,
161            decoded_attribute_bytes: 64 * KIB,
162        }
163    }
164}
165
166impl EncryptionInfoLimits {
167    fn validate(self) -> Result<Self> {
168        let ceiling = Self::default();
169        for (dimension, value, maximum) in [
170            (
171                ResourceDimension::InputBytes,
172                self.input_bytes,
173                ceiling.input_bytes,
174            ),
175            (
176                ResourceDimension::NodeCount,
177                self.element_count,
178                ceiling.element_count,
179            ),
180            (
181                ResourceDimension::RetainedBytes,
182                self.decoded_attribute_bytes,
183                ceiling.decoded_attribute_bytes,
184            ),
185        ] {
186            if value == 0 || value > maximum {
187                return Err(limit_error(
188                    ResourceOperation::Decrypt,
189                    ResourceCategory::Encryption,
190                    dimension,
191                    maximum,
192                    value.max(maximum.saturating_add(1)),
193                    ResourceStage::Validate,
194                ));
195            }
196        }
197        Ok(self)
198    }
199}
200
201pub(crate) struct EncryptionInfoBudget {
202    limits: EncryptionInfoLimits,
203    elements: u64,
204    decoded_attribute_bytes: u64,
205}
206
207impl EncryptionInfoBudget {
208    fn new(limits: EncryptionInfoLimits) -> Result<Self> {
209        Ok(Self {
210            limits: limits.validate()?,
211            elements: 0,
212            decoded_attribute_bytes: 0,
213        })
214    }
215
216    fn check_input(&self, observed: u64) -> Result<()> {
217        self.check(
218            ResourceDimension::InputBytes,
219            self.limits.input_bytes,
220            observed,
221            ResourceStage::Inspect,
222        )
223    }
224
225    pub(crate) fn charge_element(&mut self) -> Result<()> {
226        let observed = self.elements.saturating_add(1);
227        self.check(
228            ResourceDimension::NodeCount,
229            self.limits.element_count,
230            observed,
231            ResourceStage::Parse,
232        )?;
233        self.elements = observed;
234        Ok(())
235    }
236
237    pub(crate) fn reserve_decoded_attributes(&mut self, amount: u64) -> Result<()> {
238        let observed = self.decoded_attribute_bytes.saturating_add(amount);
239        self.check(
240            ResourceDimension::RetainedBytes,
241            self.limits.decoded_attribute_bytes,
242            observed,
243            ResourceStage::Decode,
244        )?;
245        self.decoded_attribute_bytes = observed;
246        Ok(())
247    }
248
249    fn check(
250        &self,
251        dimension: ResourceDimension,
252        limit: u64,
253        observed: u64,
254        stage: ResourceStage,
255    ) -> Result<()> {
256        if observed > limit {
257            return Err(limit_error(
258                ResourceOperation::Decrypt,
259                ResourceCategory::Encryption,
260                dimension,
261                limit,
262                observed,
263                stage,
264            ));
265        }
266        Ok(())
267    }
268}
269
270pub(crate) struct CryptBudget {
271    operation: ResourceOperation,
272    limits: CryptLimits,
273    stream_read_bytes: u64,
274    kdf_work: u64,
275}
276
277impl CryptBudget {
278    pub(crate) fn new(operation: ResourceOperation, limits: CryptLimits) -> Result<Self> {
279        Ok(Self {
280            operation,
281            limits: limits.validate(operation)?,
282            stream_read_bytes: 0,
283            kdf_work: 0,
284        })
285    }
286
287    pub(crate) fn check_outer_cfb(&self, observed: u64) -> Result<()> {
288        self.check(
289            ResourceCategory::Container,
290            ResourceDimension::InputBytes,
291            self.limits.outer_cfb_bytes,
292            observed,
293            ResourceStage::Inspect,
294        )
295    }
296
297    pub(crate) fn check_encryption_info_input(&self, observed: u64) -> Result<()> {
298        self.check(
299            ResourceCategory::Encryption,
300            ResourceDimension::InputBytes,
301            EncryptionInfoLimits::default().input_bytes,
302            observed,
303            ResourceStage::Inspect,
304        )
305    }
306
307    pub(crate) fn check_stream_count(&self, observed: u64) -> Result<()> {
308        self.check(
309            ResourceCategory::Container,
310            ResourceDimension::StreamCount,
311            self.limits.named_stream_count,
312            observed,
313            ResourceStage::Inspect,
314        )
315    }
316
317    pub(crate) fn check_stream_declared(&self, observed: u64) -> Result<()> {
318        self.check(
319            ResourceCategory::Container,
320            ResourceDimension::AggregateDeclaredBytes,
321            self.limits.named_stream_declared_bytes,
322            observed,
323            ResourceStage::Inspect,
324        )
325    }
326
327    pub(crate) fn check_encrypted_package(&self, observed: u64) -> Result<()> {
328        self.check(
329            ResourceCategory::Encryption,
330            ResourceDimension::InputBytes,
331            self.limits.encrypted_package_bytes,
332            observed,
333            ResourceStage::Inspect,
334        )
335    }
336
337    pub(crate) fn remaining_stream_read(&self) -> u64 {
338        self.limits
339            .named_stream_read_bytes
340            .saturating_sub(self.stream_read_bytes)
341    }
342
343    pub(crate) fn charge_stream_read(&mut self, amount: u64) -> Result<()> {
344        let observed = self.stream_read_bytes.saturating_add(amount);
345        self.check(
346            ResourceCategory::Container,
347            ResourceDimension::AggregateActualBytes,
348            self.limits.named_stream_read_bytes,
349            observed,
350            ResourceStage::Read,
351        )?;
352        self.stream_read_bytes = observed;
353        Ok(())
354    }
355
356    pub(crate) fn reserve_kdf(&mut self, iterations: u64, passes: u64) -> Result<()> {
357        self.check(
358            ResourceCategory::Encryption,
359            ResourceDimension::IterationCount,
360            self.limits.kdf_iterations,
361            iterations,
362            ResourceStage::Inspect,
363        )?;
364        let work = iterations.saturating_mul(passes);
365        let observed = self.kdf_work.saturating_add(work);
366        self.check(
367            ResourceCategory::Encryption,
368            ResourceDimension::OperationCount,
369            self.limits.kdf_work,
370            observed,
371            ResourceStage::Inspect,
372        )?;
373        self.kdf_work = observed;
374        Ok(())
375    }
376
377    fn check(
378        &self,
379        category: ResourceCategory,
380        dimension: ResourceDimension,
381        limit: u64,
382        observed: u64,
383        stage: ResourceStage,
384    ) -> Result<()> {
385        if observed > limit {
386            return Err(limit_error(
387                self.operation,
388                category,
389                dimension,
390                limit,
391                observed,
392                stage,
393            ));
394        }
395        Ok(())
396    }
397}
398
399pub(crate) fn validate_decrypt_outer_cfb(limits: CryptLimits, observed: u64) -> Result<u64> {
400    let budget = CryptBudget::new(ResourceOperation::Decrypt, limits)?;
401    budget.check_outer_cfb(observed)?;
402    Ok(limits.outer_cfb_bytes)
403}
404
405fn limit_error(
406    operation: ResourceOperation,
407    category: ResourceCategory,
408    dimension: ResourceDimension,
409    limit: u64,
410    observed: u64,
411    stage: ResourceStage,
412) -> Error {
413    match ResourceLimitError::exceeded(operation, category, dimension, limit, observed, Some(stage))
414    {
415        Some(error) => error.into(),
416        None => Error::Internal("invalid crypt resource-limit state".to_string()),
417    }
418}
419
420/// CFB magic bytes: `D0 CF 11 E0 A1 B1 1A E1`.
421const CFB_MAGIC: [u8; 8] = [0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1];
422
423/// ZIP magic bytes: `PK\x03\x04`.
424const ZIP_MAGIC: [u8; 4] = [0x50, 0x4B, 0x03, 0x04];
425
426/// Determines the container format of a file from its leading bytes.
427#[derive(Debug, Clone, Copy, PartialEq, Eq)]
428pub enum ContainerFormat {
429    /// Standard ZIP archive (unencrypted `.xlsx`).
430    Zip,
431    /// OLE/CFB compound file (encrypted `.xlsx`).
432    Cfb,
433}
434
435/// Identifies the container format by inspecting magic bytes.
436pub fn detect_container_format(data: &[u8]) -> Result<ContainerFormat> {
437    if data.len() >= 4 && data[..4] == ZIP_MAGIC {
438        return Ok(ContainerFormat::Zip);
439    }
440    if data.len() >= 8 && data[..8] == CFB_MAGIC {
441        return Ok(ContainerFormat::Cfb);
442    }
443    Err(Error::Internal(
444        "file is neither a ZIP archive nor an OLE/CFB container".to_string(),
445    ))
446}
447
448/// Encryption type detected from the EncryptionInfo stream.
449#[derive(Debug, Clone, Copy, PartialEq, Eq)]
450pub enum EncryptionType {
451    /// Standard Encryption (Office 2007): AES-128-ECB + SHA-1.
452    Standard,
453    /// Agile Encryption (Office 2010+): AES-256-CBC + SHA-512.
454    Agile,
455}
456
457/// Parsed encryption information from the EncryptionInfo stream.
458///
459/// Raw EncryptionInfo parsing is intentionally not a public entry point:
460///
461/// ```compile_fail
462/// use sheetkit_core::crypt::parse_encryption_info;
463/// ```
464#[derive(Debug)]
465pub enum EncryptionInfo {
466    /// Standard Encryption metadata.
467    Standard(StandardEncryptionHeader, StandardEncryptionVerifier),
468    /// Agile Encryption metadata.
469    Agile(AgileEncryptionInfo),
470}
471
472fn parse_encryption_info(data: &[u8]) -> Result<EncryptionInfo> {
473    parse_encryption_info_with_limits(data, EncryptionInfoLimits::default())
474}
475
476fn parse_encryption_info_with_limits(
477    data: &[u8],
478    limits: EncryptionInfoLimits,
479) -> Result<EncryptionInfo> {
480    let mut budget = EncryptionInfoBudget::new(limits)?;
481    budget.check_input(data.len() as u64)?;
482    if data.len() < 8 {
483        return Err(Error::Internal(
484            "EncryptionInfo stream is too short".to_string(),
485        ));
486    }
487
488    let version_major = u16::from_le_bytes([data[0], data[1]]);
489    let version_minor = u16::from_le_bytes([data[2], data[3]]);
490
491    match (version_major, version_minor) {
492        (3, 2) | (4, 2) => {
493            // Standard Encryption: skip 8-byte header (version + flags)
494            let (header, verifier) = standard::parse_standard_encryption_info(&data[8..])?;
495            Ok(EncryptionInfo::Standard(header, verifier))
496        }
497        (4, 4) => {
498            // Agile Encryption: skip 8-byte header, rest is XML
499            let info = agile::parse_agile_encryption_info_with_budget(&data[8..], &mut budget)?;
500            Ok(EncryptionInfo::Agile(info))
501        }
502        _ => Err(Error::UnsupportedEncryption(format!(
503            "version {version_major}.{version_minor}"
504        ))),
505    }
506}
507
508/// Read the EncryptionInfo and EncryptedPackage streams from a CFB container,
509/// verify the password, decrypt the package, and return the raw ZIP bytes.
510pub fn decrypt_xlsx(data: &[u8], password: &str) -> Result<Vec<u8>> {
511    decrypt_xlsx_with_limits(data, password, CryptLimits::default())
512}
513
514/// Decrypt an encrypted Office container using explicit finite limits.
515pub fn decrypt_xlsx_with_limits(
516    data: &[u8],
517    password: &str,
518    limits: CryptLimits,
519) -> Result<Vec<u8>> {
520    let mut budget = CryptBudget::new(ResourceOperation::Decrypt, limits)?;
521    let mut container = cfb_io::CfbReader::open(data, &budget)?;
522    let info_data = container.read_encryption_info(&mut budget)?;
523    let info = parse_encryption_info(&info_data)?;
524
525    match info {
526        EncryptionInfo::Standard(header, verifier) => {
527            budget.reserve_kdf(50_000, 1)?;
528            let key = zeroize::Zeroizing::new(standard::verify_password_standard(
529                password, &header, &verifier,
530            )?);
531            let encrypted_package = container.read_encrypted_package(&mut budget)?;
532            standard::decrypt_package_standard(&encrypted_package, &key)
533        }
534        EncryptionInfo::Agile(info) => {
535            let encryptor = info
536                .key_encryptors
537                .iter()
538                .find(|encryptor| agile::validate_password_encryptor(encryptor).is_ok())
539                .ok_or_else(|| {
540                    Error::UnsupportedEncryption("no usable password key encryptor".to_string())
541                })?;
542            let unwrapped =
543                agile::unwrap_secret_key_agile_with_budget(password, encryptor, &mut budget)?;
544            let secret_key = agile::package_key(&unwrapped, &info.key_data)?;
545            let encrypted_package = container.read_encrypted_package(&mut budget)?;
546            agile::verify_data_integrity(
547                &encrypted_package,
548                &secret_key,
549                &info.key_data,
550                &info.data_integrity,
551            )?;
552            agile::decrypt_package_agile(&encrypted_package, &secret_key, &info.key_data)
553        }
554    }
555}
556
557/// Encrypt a ZIP buffer with a password and write it as a CFB container.
558/// Returns the CFB container bytes.
559pub fn encrypt_xlsx(zip_data: &[u8], password: &str) -> Result<Vec<u8>> {
560    encrypt_xlsx_with_limits(zip_data, password, CryptLimits::default())
561}
562
563/// Encrypt ZIP bytes into an Office container using explicit finite limits.
564pub fn encrypt_xlsx_with_limits(
565    zip_data: &[u8],
566    password: &str,
567    limits: CryptLimits,
568) -> Result<Vec<u8>> {
569    let mut budget = CryptBudget::new(ResourceOperation::Encrypt, limits)?;
570    budget.check_encrypted_package(zip_data.len() as u64)?;
571    let (encrypted_package, encryption_info) =
572        agile::encrypt_package_agile_with_budget(zip_data, password, &mut budget)?;
573    budget.check_encrypted_package(encrypted_package.len() as u64)?;
574    cfb_io::write_cfb_streams(&encryption_info, &encrypted_package)
575}
576
577/// Block key constants used in Agile Encryption key derivation.
578pub mod block_keys {
579    /// Block key for deriving the secret key decryption key.
580    pub const KEY_VALUE: &[u8] = &[0x14, 0x6e, 0x0b, 0xe7, 0xab, 0xac, 0xd0, 0xd6];
581    /// Block key for deriving the verifier hash input decryption key.
582    pub const VERIFIER_HASH_INPUT: &[u8] = &[0xfe, 0xa7, 0xd2, 0x76, 0x3b, 0x4b, 0x9e, 0x79];
583    /// Block key for deriving the verifier hash value decryption key.
584    pub const VERIFIER_HASH_VALUE: &[u8] = &[0xd7, 0xaa, 0x0f, 0x6d, 0x30, 0x61, 0x34, 0x4e];
585    /// Block key for deriving the HMAC key decryption key.
586    pub const HMAC_KEY: &[u8] = &[0x5f, 0xb2, 0xad, 0x01, 0x0c, 0xb9, 0xe1, 0xf6];
587    /// Block key for deriving the HMAC value decryption key.
588    pub const HMAC_VALUE: &[u8] = &[0xa0, 0x67, 0x7f, 0x02, 0xb2, 0x2c, 0x84, 0x33];
589}
590
591#[cfg(test)]
592mod tests {
593    use super::*;
594
595    #[test]
596    fn test_detect_zip_format() {
597        let data = [0x50, 0x4B, 0x03, 0x04, 0x00, 0x00, 0x00, 0x00];
598        assert_eq!(
599            detect_container_format(&data).unwrap(),
600            ContainerFormat::Zip
601        );
602    }
603
604    #[test]
605    fn test_detect_cfb_format() {
606        let data = [0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1];
607        assert_eq!(
608            detect_container_format(&data).unwrap(),
609            ContainerFormat::Cfb
610        );
611    }
612
613    #[test]
614    fn test_detect_unknown_format() {
615        let data = [0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07];
616        assert!(detect_container_format(&data).is_err());
617    }
618
619    #[test]
620    fn test_parse_encryption_info_too_short() {
621        let data = [0x00, 0x01, 0x02];
622        assert!(parse_encryption_info(&data).is_err());
623    }
624
625    #[test]
626    fn test_parse_encryption_info_unsupported_version() {
627        // Version 1.0 is not supported
628        let data = [0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00];
629        let result = parse_encryption_info(&data);
630        assert!(result.is_err());
631        let err = result.unwrap_err();
632        assert!(err.to_string().contains("unsupported encryption method"));
633    }
634
635    #[test]
636    fn encryption_info_input_limit_accepts_exact_and_rejects_plus_one() {
637        let data = [0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00];
638        let exact = EncryptionInfoLimits {
639            input_bytes: data.len() as u64,
640            ..EncryptionInfoLimits::default()
641        };
642        assert!(parse_encryption_info_with_limits(&data, exact).is_err());
643
644        let rejected = EncryptionInfoLimits {
645            input_bytes: data.len() as u64 - 1,
646            ..EncryptionInfoLimits::default()
647        };
648        let error = parse_encryption_info_with_limits(&data, rejected).unwrap_err();
649        let metadata = error.resource_metadata().expect("resource metadata");
650        assert_eq!(metadata.operation(), ResourceOperation::Decrypt);
651        assert_eq!(metadata.category(), ResourceCategory::Encryption);
652        assert_eq!(metadata.dimension(), ResourceDimension::InputBytes);
653        assert_eq!(metadata.limit(), data.len() as u64 - 1);
654        assert_eq!(metadata.observed(), data.len() as u64);
655        assert_eq!(metadata.stage(), Some(ResourceStage::Inspect));
656    }
657}