Skip to main content

laminapdf_syntax/crypt/
write.rs

1//! Writing the standard security handler at revision 6 (ISO 32000-2 §7.6.4: Algorithms 8–10
2//! with 2.B) and encrypting strings and streams (§7.6.3). AES-256 only: nothing here writes RC4,
3//! AES-128 or revisions 2–5 as a *new* handler. [`encrypt`] also covers those ciphers, so a
4//! document opened with one can be saved under the key it was opened with.
5//!
6//! Core has no ambient randomness. Every random value (the salts, the file key and the IVs)
7//! comes from an [`Entropy`] the caller passes; [`SeededEntropy`] expands one 32-byte seed from
8//! `crypto.getRandomValues` or `getrandom`, and gives the same bytes for the same seed, which is
9//! what makes a save reproducible in tests.
10
11use std::fmt;
12
13use sha2::{Digest, Sha256};
14
15use super::{Cipher, FileKey, Permissions, aes, candidates, key, rc4};
16
17/// A source of random bytes, injected by the host (core reads no clock and no OS source).
18///
19/// ```
20/// use laminapdf_syntax::crypt::{Entropy, SeededEntropy};
21///
22/// let mut a = SeededEntropy::new([7; 32]);
23/// let mut b = SeededEntropy::new([7; 32]);
24/// let (mut x, mut y) = ([0u8; 40], [0u8; 40]);
25/// a.fill(&mut x);
26/// b.fill(&mut y);
27/// assert_eq!(x, y);
28/// ```
29///
30/// Added in 0.7.0.
31pub trait Entropy {
32    /// Fills `dest` with random bytes.
33    ///
34    /// Added in 0.7.0.
35    fn fill(&mut self, dest: &mut [u8]);
36}
37
38/// An [`Entropy`] that expands a 32-byte seed with SHA-256 in counter mode (the construction of
39/// NIST SP 800-90A's `Hash_df`): the same seed gives the same stream, and the stream reveals
40/// nothing about the seed.
41///
42/// The host must draw the seed from a cryptographic source (`crypto.getRandomValues`,
43/// `getrandom`). A fixed seed is for tests: a file written with one has predictable keys.
44///
45/// Added in 0.7.0.
46#[derive(Clone, PartialEq, Eq)]
47pub struct SeededEntropy {
48    seed: [u8; 32],
49    counter: u64,
50}
51
52impl SeededEntropy {
53    /// A stream from `seed`.
54    ///
55    /// Added in 0.7.0.
56    #[must_use]
57    pub const fn new(seed: [u8; 32]) -> Self {
58        Self { seed, counter: 0 }
59    }
60}
61
62impl fmt::Debug for SeededEntropy {
63    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
64        f.write_str("SeededEntropy(<redacted>)")
65    }
66}
67
68impl Entropy for SeededEntropy {
69    fn fill(&mut self, dest: &mut [u8]) {
70        for chunk in dest.chunks_mut(32) {
71            let mut h = Sha256::new();
72            h.update(self.seed);
73            h.update(self.counter.to_be_bytes());
74            self.counter = self.counter.wrapping_add(1);
75            let block = h.finalize();
76            for (d, s) in chunk.iter_mut().zip(block.iter()) {
77                *d = *s;
78            }
79        }
80    }
81}
82
83fn random<const N: usize>(entropy: &mut dyn Entropy) -> [u8; N] {
84    let mut out = [0u8; N];
85    entropy.fill(&mut out);
86    out
87}
88
89/// How much of printing a new document allows (Table 22 bits 3 and 12).
90///
91/// Added in 0.7.0.
92#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
93#[non_exhaustive]
94pub enum PrintRight {
95    /// No printing (neither bit).
96    None,
97    /// Low-resolution printing only (bit 3).
98    LowResolution,
99    /// Faithful printing (bits 3 and 12).
100    #[default]
101    HighResolution,
102}
103
104/// What a new handler lets a user without the owner password do: the controls of the Protect
105/// dialog, mapped to `/P` by [`Grant::p`]. Bit 10 (accessibility) is not a field: it is always
106/// set, so a protected file stays readable by assistive technology.
107///
108/// Added in 0.7.0.
109#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
110#[expect(clippy::struct_excessive_bools, reason = "one bool per bit of Table 22")]
111#[non_exhaustive]
112pub struct Grant {
113    /// Printing.
114    pub print: PrintRight,
115    /// Copy text and images (bit 5).
116    pub extract: bool,
117    /// Fill in forms and sign (bit 9).
118    pub fill_forms: bool,
119    /// Add comments (bit 6).
120    pub annotate: bool,
121    /// Insert, rotate or delete pages (bit 11).
122    pub assemble: bool,
123    /// Edit the contents (bit 4).
124    pub modify: bool,
125}
126
127impl Grant {
128    /// Everything allowed.
129    ///
130    /// Added in 0.7.0.
131    #[must_use]
132    pub const fn all() -> Self {
133        Self {
134            print: PrintRight::HighResolution,
135            extract: true,
136            fill_forms: true,
137            annotate: true,
138            assemble: true,
139            modify: true,
140        }
141    }
142
143    /// The `/P` value: the reserved bits ISO 32000-2 Table 22 sets (7, 8 and 13–32), bit 10, and
144    /// the bits this grant allows.
145    ///
146    /// ```
147    /// use laminapdf_syntax::crypt::Grant;
148    ///
149    /// assert_eq!(Grant::all().p(), 0xFFFF_FFFC);
150    /// ```
151    ///
152    /// Added in 0.7.0.
153    #[must_use]
154    pub const fn p(&self) -> u32 {
155        let mut p = 0xFFFF_F0C0 | Permissions::ACCESSIBILITY;
156        if !matches!(self.print, PrintRight::None) {
157            p |= Permissions::PRINT;
158        }
159        if matches!(self.print, PrintRight::HighResolution) {
160            p |= Permissions::PRINT_HIGH;
161        }
162        if self.modify {
163            p |= Permissions::MODIFY;
164        }
165        if self.extract {
166            p |= Permissions::EXTRACT;
167        }
168        if self.annotate {
169            p |= Permissions::ANNOTATE;
170        }
171        if self.fill_forms {
172            p |= Permissions::FILL_FORMS;
173        }
174        if self.assemble {
175            p |= Permissions::ASSEMBLE;
176        }
177        p
178    }
179}
180
181/// What a new R6 handler is made from.
182///
183/// Added in 0.7.0.
184#[derive(Clone, Copy)]
185#[non_exhaustive]
186pub struct NewHandler<'a> {
187    /// The user ("open") password, as typed; empty for none.
188    pub user: &'a [u8],
189    /// The owner ("permissions") password, as typed. Empty is replaced by random bytes, since
190    /// R6 needs a distinct owner entry.
191    pub owner: &'a [u8],
192    /// What a user without the owner password may do.
193    pub grant: Grant,
194    /// Whether the XMP metadata stream is encrypted (`/EncryptMetadata`).
195    pub encrypt_metadata: bool,
196}
197
198impl<'a> NewHandler<'a> {
199    /// A handler with `user` and `owner`, everything granted and metadata encrypted.
200    ///
201    /// Added in 0.7.0.
202    #[must_use]
203    pub const fn new(user: &'a [u8], owner: &'a [u8]) -> Self {
204        Self {
205            user,
206            owner,
207            grant: Grant::all(),
208            encrypt_metadata: true,
209        }
210    }
211}
212
213impl fmt::Debug for NewHandler<'_> {
214    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
215        f.debug_struct("NewHandler")
216            .field("grant", &self.grant)
217            .field("encrypt_metadata", &self.encrypt_metadata)
218            .finish_non_exhaustive()
219    }
220}
221
222/// A written R6 handler: the `/Encrypt` entries and the file key.
223///
224/// Added in 0.7.0.
225#[derive(Clone, PartialEq, Eq)]
226#[non_exhaustive]
227pub struct Handler {
228    /// `/U`: 32-byte hash ‖ validation salt ‖ key salt.
229    pub user: [u8; 48],
230    /// `/UE`.
231    pub user_encryption: [u8; 32],
232    /// `/O`.
233    pub owner: [u8; 48],
234    /// `/OE`.
235    pub owner_encryption: [u8; 32],
236    /// `/Perms`.
237    pub perms: [u8; 16],
238    /// `/P`.
239    pub permissions: u32,
240    /// `/EncryptMetadata`.
241    pub encrypt_metadata: bool,
242    /// The file key (never printed).
243    pub key: FileKey,
244    /// True when the owner password was empty and a random one was made: the caller tells the
245    /// user to keep [`Handler::generated_owner`], since nothing else can unlock the file.
246    pub owner_generated: bool,
247    /// The random owner password, when [`Handler::owner_generated`].
248    generated_owner: Option<Vec<u8>>,
249}
250
251impl Handler {
252    /// The owner password made for an empty one, as hex text; `None` when the caller gave one.
253    ///
254    /// Added in 0.7.0.
255    #[must_use]
256    pub fn generated_owner(&self) -> Option<String> {
257        self.generated_owner.as_ref().map(|bytes| {
258            bytes
259                .iter()
260                .flat_map(|b| [b >> 4, b & 15])
261                .filter_map(|n| char::from_digit(u32::from(n), 16))
262                .collect()
263        })
264    }
265}
266
267impl fmt::Debug for Handler {
268    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
269        f.debug_struct("Handler")
270            .field("permissions", &self.permissions)
271            .field("encrypt_metadata", &self.encrypt_metadata)
272            .field("owner_generated", &self.owner_generated)
273            .finish_non_exhaustive()
274    }
275}
276
277/// The password as the hash takes it (SASLprep, at most 127 bytes), the form
278/// [`authenticate`](super::authenticate) tries first.
279/// Overwritten when dropped, with the other candidates.
280fn prepare(password: &[u8]) -> zeroize::Zeroizing<Vec<u8>> {
281    let mut all = candidates(password, 6);
282    let first = if all.is_empty() { Vec::new() } else { all.swap_remove(0) };
283    zeroize::Zeroize::zeroize(&mut all);
284    zeroize::Zeroizing::new(first)
285}
286
287/// Algorithm 8 (`/U`, `/UE`), Algorithm 9 (`/O`, `/OE`) and Algorithm 10 (`/Perms`).
288///
289/// With both passwords empty the file would open for anyone and could not be changed: the
290/// caller refuses that case (`encryption-no-password`) before it gets here.
291///
292/// Added in 0.7.0.
293#[must_use]
294pub fn new_handler(params: &NewHandler<'_>, entropy: &mut dyn Entropy) -> Handler {
295    let file_key = random::<32>(entropy);
296    let (generated_owner, owner_password) = if params.owner.is_empty() {
297        let bytes = random::<16>(entropy).to_vec();
298        let text = bytes
299            .iter()
300            .flat_map(|b| [b >> 4, b & 15])
301            .filter_map(|n| char::from_digit(u32::from(n), 16))
302            .collect::<String>()
303            .into_bytes();
304        (Some(bytes), zeroize::Zeroizing::new(text))
305    } else {
306        (None, prepare(params.owner))
307    };
308    let user_password = prepare(params.user);
309    let wrap = |password: &[u8], key_salt: &[u8], udata: &[u8]| -> [u8; 32] {
310        let intermediate = key::hash_r6(password, key_salt, udata);
311        let mut wrapped = file_key;
312        // 32 bytes is a whole number of blocks, and the key is 32 bytes: the call cannot fail.
313        let _ = aes::cbc_encrypt_in_place(&intermediate, &[0; 16], &mut wrapped);
314        wrapped
315    };
316    let entry = |password: &[u8], udata: &[u8], entropy: &mut dyn Entropy| -> ([u8; 48], [u8; 32]) {
317        let validation = random::<8>(entropy);
318        let key_salt = random::<8>(entropy);
319        let mut out = [0u8; 48];
320        out[..32].copy_from_slice(&key::hash_r6(password, &validation, udata));
321        out[32..40].copy_from_slice(&validation);
322        out[40..].copy_from_slice(&key_salt);
323        (out, wrap(password, &key_salt, udata))
324    };
325    let (user, user_encryption) = entry(&user_password, &[], entropy);
326    let (owner, owner_encryption) = entry(&owner_password, &user, entropy);
327    let permissions = params.grant.p();
328    let mut perms = [0u8; 16];
329    perms[..4].copy_from_slice(&permissions.to_le_bytes());
330    perms[4..8].fill(0xFF);
331    perms[8] = if params.encrypt_metadata { b'T' } else { b'F' };
332    perms[9..12].copy_from_slice(b"adb");
333    perms[12..].copy_from_slice(&random::<4>(entropy));
334    let perms = aes::ecb_encrypt_block(&file_key, &perms).unwrap_or_default();
335    Handler {
336        user,
337        user_encryption,
338        owner,
339        owner_encryption,
340        perms,
341        permissions,
342        encrypt_metadata: params.encrypt_metadata,
343        key: FileKey::from_bytes(file_key.to_vec()),
344        owner_generated: generated_owner.is_some(),
345        generated_owner,
346    }
347}
348
349/// Encrypts the string or stream data of object `num gen` (ISO 32000-2 §7.6.3, the inverse of
350/// [`decrypt`](super::decrypt)): AES gets a fresh 16-byte IV from `entropy` in front of the
351/// PKCS#5-padded ciphertext, RC4 is the same keystream, [`Cipher::Identity`] copies. `None` when
352/// the key has the wrong length for the cipher: the data is never returned as it was, so a
353/// caller that can't encrypt has to say so.
354///
355/// Added in 0.7.0.
356#[must_use]
357pub fn encrypt(
358    cipher: Cipher,
359    key: &FileKey,
360    num: u32,
361    gen_nr: u16,
362    entropy: &mut dyn Entropy,
363    data: &[u8],
364) -> Option<Vec<u8>> {
365    match cipher {
366        Cipher::Rc4 => Some(rc4::apply(&key::object_key(&key.0, num, gen_nr, false), data)),
367        Cipher::Aes128 => aes::encrypt_padded(&key::object_key(&key.0, num, gen_nr, true), &random(entropy), data),
368        Cipher::Aes256 if key.0.len() == 32 => aes::encrypt_padded(&key.0, &random(entropy), data),
369        Cipher::Aes256 => None,
370        Cipher::Identity => Some(data.to_vec()),
371    }
372}
373
374#[cfg(test)]
375mod tests {
376    use super::*;
377    use crate::crypt::{PasswordKind, StandardSecurity, authenticate, decrypt};
378
379    fn entropy() -> SeededEntropy {
380        SeededEntropy::new([9; 32])
381    }
382
383    fn open(h: &Handler, password: &[u8]) -> Option<crate::crypt::Authenticated> {
384        let sec = StandardSecurity {
385            revision: 6,
386            key_length: 32,
387            owner: &h.owner,
388            user: &h.user,
389            owner_encryption: &h.owner_encryption,
390            user_encryption: &h.user_encryption,
391            perms: Some(&h.perms),
392            permissions: h.permissions,
393            id0: b"",
394            encrypt_metadata: h.encrypt_metadata,
395        };
396        authenticate(&sec, password)
397    }
398
399    #[test]
400    fn the_user_password_opens_the_handler_with_the_file_key() {
401        let h = new_handler(&NewHandler::new(b"open", b"owner"), &mut entropy());
402        let a = open(&h, b"open").unwrap();
403        assert_eq!(
404            (a.matched, a.key == h.key, a.perms_valid),
405            (PasswordKind::User, true, Some(true))
406        );
407    }
408
409    #[test]
410    fn the_owner_password_opens_the_handler_with_the_file_key() {
411        let h = new_handler(&NewHandler::new(b"open", b"owner"), &mut entropy());
412        let a = open(&h, b"owner").unwrap();
413        assert_eq!((a.matched, a.key == h.key), (PasswordKind::Owner, true));
414    }
415
416    #[test]
417    fn another_password_opens_nothing() {
418        let h = new_handler(&NewHandler::new(b"open", b"owner"), &mut entropy());
419        assert!(open(&h, b"guess").is_none() && open(&h, b"").is_none());
420    }
421
422    #[test]
423    fn an_empty_user_password_opens_without_a_prompt() {
424        let h = new_handler(&NewHandler::new(b"", b"owner"), &mut entropy());
425        assert_eq!(open(&h, b"").unwrap().matched, PasswordKind::User);
426    }
427
428    #[test]
429    fn an_empty_owner_password_is_replaced_by_one_that_opens_the_file() {
430        let h = new_handler(&NewHandler::new(b"open", b""), &mut entropy());
431        let made = h.generated_owner().unwrap();
432        assert_eq!((h.owner_generated, made.len()), (true, 32));
433        assert_eq!(open(&h, made.as_bytes()).unwrap().matched, PasswordKind::Owner);
434    }
435
436    #[test]
437    fn a_given_owner_password_is_not_reported_as_generated() {
438        let h = new_handler(&NewHandler::new(b"open", b"owner"), &mut entropy());
439        assert_eq!((h.owner_generated, h.generated_owner()), (false, None));
440    }
441
442    #[test]
443    fn the_same_seed_writes_the_same_handler() {
444        let params = NewHandler::new(b"open", b"owner");
445        let (a, b) = (
446            new_handler(&params, &mut entropy()),
447            new_handler(&params, &mut entropy()),
448        );
449        assert_eq!(
450            (a.user, a.owner, a.perms, a.key == b.key),
451            (b.user, b.owner, b.perms, true)
452        );
453    }
454
455    #[test]
456    fn another_seed_writes_another_file_key() {
457        let params = NewHandler::new(b"open", b"owner");
458        let other = new_handler(&params, &mut SeededEntropy::new([1; 32]));
459        assert_ne!(new_handler(&params, &mut entropy()).key, other.key);
460    }
461
462    #[test]
463    fn perms_records_p_and_the_metadata_flag() {
464        let mut params = NewHandler::new(b"open", b"owner");
465        params.encrypt_metadata = false;
466        let h = new_handler(&params, &mut entropy());
467        let plain = aes::ecb_decrypt_block(&h.key.0, &h.perms).unwrap();
468        assert_eq!(
469            (&plain[..4], &plain[4..8], plain[8], &plain[9..12]),
470            (&h.permissions.to_le_bytes()[..], &[0xFF; 4][..], b'F', &b"adb"[..])
471        );
472    }
473
474    #[test]
475    fn full_rights_make_p_all_ones_but_the_two_low_bits() {
476        assert_eq!(Grant::all().p(), 0xFFFF_FFFC);
477    }
478
479    #[test]
480    fn bit_10_stays_set_when_everything_else_is_refused() {
481        let none = Grant {
482            print: PrintRight::None,
483            extract: false,
484            fill_forms: false,
485            annotate: false,
486            assemble: false,
487            modify: false,
488        };
489        let p = Permissions::new(i64::from(none.p()), 6);
490        assert_eq!(p.bits(), 1 << 9);
491        assert!(p.accessibility() && !p.print_low_res() && !p.extract() && !p.annotate() && !p.modify());
492    }
493
494    #[test]
495    fn each_control_sets_only_its_bits() {
496        let base = Grant {
497            print: PrintRight::None,
498            extract: false,
499            fill_forms: false,
500            annotate: false,
501            assemble: false,
502            modify: false,
503        };
504        let bits = |g: Grant| g.p() ^ base.p();
505        assert_eq!(
506            bits(Grant {
507                print: PrintRight::LowResolution,
508                ..base
509            }),
510            1 << 2
511        );
512        assert_eq!(
513            bits(Grant {
514                print: PrintRight::HighResolution,
515                ..base
516            }),
517            (1 << 2) | (1 << 11)
518        );
519        assert_eq!(bits(Grant { extract: true, ..base }), 1 << 4);
520        assert_eq!(
521            bits(Grant {
522                fill_forms: true,
523                ..base
524            }),
525            1 << 8
526        );
527        assert_eq!(bits(Grant { annotate: true, ..base }), 1 << 5);
528        assert_eq!(bits(Grant { assemble: true, ..base }), 1 << 10);
529        assert_eq!(bits(Grant { modify: true, ..base }), 1 << 3);
530    }
531
532    #[test]
533    fn aes_256_data_decrypts_under_the_file_key() {
534        let key = FileKey::from_bytes(vec![5; 32]);
535        let sealed = encrypt(Cipher::Aes256, &key, 7, 0, &mut entropy(), b"LAMINA-SENTINEL").unwrap();
536        assert_eq!(sealed.len(), 16 + 16);
537        assert!(!sealed.windows(8).any(|w| w == b"SENTINEL"));
538        assert_eq!(decrypt(Cipher::Aes256, &key, 7, 0, &sealed).data, b"LAMINA-SENTINEL");
539    }
540
541    #[test]
542    fn a_whole_block_gets_a_whole_block_of_padding() {
543        let key = FileKey::from_bytes(vec![5; 32]);
544        let sealed = encrypt(Cipher::Aes256, &key, 1, 0, &mut entropy(), &[1; 16]).unwrap();
545        assert_eq!(sealed.len(), 16 + 32);
546    }
547
548    #[test]
549    fn every_encryption_draws_a_new_iv() {
550        let key = FileKey::from_bytes(vec![5; 32]);
551        let mut e = entropy();
552        let a = encrypt(Cipher::Aes256, &key, 1, 0, &mut e, b"same").unwrap();
553        let b = encrypt(Cipher::Aes256, &key, 1, 0, &mut e, b"same").unwrap();
554        assert!(a[..16] != b[..16] && a[16..] != b[16..]);
555    }
556
557    #[test]
558    fn the_older_ciphers_round_trip_for_a_resave_under_the_key_they_opened_with() {
559        let key = FileKey::from_bytes(vec![3; 16]);
560        for cipher in [Cipher::Rc4, Cipher::Aes128] {
561            let sealed = encrypt(cipher, &key, 4, 1, &mut entropy(), b"older").unwrap();
562            assert_eq!(decrypt(cipher, &key, 4, 1, &sealed).data, b"older");
563        }
564    }
565
566    #[test]
567    fn a_key_of_the_wrong_length_refuses_instead_of_returning_plaintext() {
568        let key = FileKey::from_bytes(vec![5; 16]);
569        assert_eq!(encrypt(Cipher::Aes256, &key, 1, 0, &mut entropy(), b"x"), None);
570    }
571
572    #[test]
573    fn entropy_fills_more_than_one_block() {
574        let mut out = [0u8; 100];
575        entropy().fill(&mut out);
576        assert_ne!(out[..32], out[32..64]);
577    }
578
579    #[test]
580    fn debug_output_names_no_secret() {
581        let h = new_handler(&NewHandler::new(b"open", b"owner"), &mut entropy());
582        let text = format!("{h:?} {:?} {:?}", NewHandler::new(b"open", b"owner"), entropy());
583        assert!(!text.contains("open") && !text.contains("owner:") && text.contains("redacted"));
584    }
585}