Skip to main content

pdf/
encrypt.rs

1// encrypt -- how a document is encrypted when it is written (Document::set_encryption) or
2// written again in full (edit::Update::save_full): the standard security handler of ISO 32000-2
3// (7.6.4) with AES-256 (revision 6, PDF 2.0; in a PDF 1.7 file with Adobe's extension level 8,
4// as qpdf writes it) or AES-128 (revision 4, for readers older than Acrobat X).  RC4 is not
5// written (pdf::read still opens it).
6//
7//   Encryption::aes256(user, owner)      the user password opens the file, the owner password
8//   Encryption::aes128(user, owner)      also lifts the permissions; an empty owner password is
9//                                        the user password (as qpdf has it)
10//     .permissions(Permissions::PRINT | Permissions::COPY)       what the user may do (all)
11//     .encrypt_metadata(false)           XMP metadata stays readable (encrypted)
12//     .with_seed(seed)                   the 32 bytes the key, the salts and the IDs come from
13//   Permissions   PRINT, MODIFY, COPY, ANNOTATE, FILL_FORMS, ACCESSIBILITY, ASSEMBLE, PRINT_HIGH,
14//                 ALL, NONE; from_p / p: the /P value of a file (read::Document::permissions)
15//
16// Passwords of AES-256 are UTF-8, truncated to 127 bytes as ISO 32000-2 says (SASLprep is not
17// applied, as pdf::read does not); those of AES-128 are PDFDocEncoding (as qpdf and Acrobat take
18// them: "€" yes, a no-break space no; other characters are refused) and only their first 32 bytes
19// count.  User and owner passwords that are the same after the cut are refused unless they are
20// the same (an empty owner password): the user's would open the file as the owner's.
21// The key, the salts and the file ID come from the system's random numbers (plat::fill_random),
22// or from the seed given: the same document, the same options and the same seed give the same
23// bytes, and the file key of AES-256 is the seed's, so a seed must be as secret and as random as
24// a key: one seed for two documents gives both the same key, and a seed used again when the
25// passwords change keeps the old key (who knew it still decrypts).  Leave the seed out for real
26// encryption on the systems that have random numbers; fixed seeds are for output that must be
27// reproducible, as in tests.  The browser has no random numbers of plat, so there with_seed is needed
28// (from the page's crypto.getRandomValues).  Permissions are the file's request to the viewer;
29// nothing in the format enforces them.
30
31use alloc::string::String;
32use core::fmt;
33
34/// the cipher of an encrypted document
35#[derive(Clone, Copy, Debug, PartialEq, Eq)]
36#[non_exhaustive]
37pub enum Cipher {
38    /// AES-256 (security handler revision 6): what readers since Acrobat X open
39    Aes256,
40    /// AES-128 (revision 4): for older readers; its password hash (MD5) is weaker
41    Aes128,
42}
43
44/// what a user who opened the document with the user password may do (ISO 32000-1, Table 22)
45#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
46pub struct Permissions(u32);
47
48impl Permissions {
49    /// print (in low quality without PRINT_HIGH)
50    pub const PRINT: Permissions = Permissions(1 << 2);
51    /// change the document otherwise than ANNOTATE, FILL_FORMS and ASSEMBLE allow
52    pub const MODIFY: Permissions = Permissions(1 << 3);
53    /// copy or extract text and graphics
54    pub const COPY: Permissions = Permissions(1 << 4);
55    /// add or change annotations, fill in forms (with MODIFY: create fields)
56    pub const ANNOTATE: Permissions = Permissions(1 << 5);
57    /// fill in forms and sign, also without ANNOTATE
58    pub const FILL_FORMS: Permissions = Permissions(1 << 8);
59    /// extract text and graphics for accessibility
60    pub const ACCESSIBILITY: Permissions = Permissions(1 << 9);
61    /// insert, rotate, delete pages, bookmarks and thumbnails
62    pub const ASSEMBLE: Permissions = Permissions(1 << 10);
63    /// print in full quality
64    pub const PRINT_HIGH: Permissions = Permissions(1 << 11);
65    /// nothing
66    pub const NONE: Permissions = Permissions(0);
67    /// everything
68    pub const ALL: Permissions = Permissions(0xF3C);
69
70    /// the permissions of a /P value (the bits of the eight above)
71    pub fn from_p(p: u32) -> Permissions {
72        Permissions(p & 0xF3C)
73    }
74
75    /// the /P value: these bits, bits 7 and 8 and 13 to 32 set as revisions 3 and later want
76    pub fn p(self) -> u32 {
77        (self.0 & 0xF3C) | 0xFFFF_F0C0
78    }
79
80    pub fn contains(self, other: Permissions) -> bool {
81        self.0 & other.0 == other.0
82    }
83}
84
85impl core::ops::BitOr for Permissions {
86    type Output = Permissions;
87    fn bitor(self, o: Permissions) -> Permissions {
88        Permissions(self.0 | o.0)
89    }
90}
91
92impl core::ops::BitOrAssign for Permissions {
93    fn bitor_assign(&mut self, o: Permissions) {
94        self.0 |= o.0;
95    }
96}
97
98/// how a document is encrypted: the cipher, the passwords, the permissions
99#[derive(Clone, PartialEq, Eq)]
100pub struct Encryption {
101    pub(crate) cipher: Cipher,
102    pub(crate) user: String,
103    pub(crate) owner: String,
104    pub(crate) permissions: Permissions,
105    pub(crate) encrypt_metadata: bool,
106    pub(crate) seed: Option<[u8; 32]>,
107}
108
109// the passwords are not shown
110impl fmt::Debug for Encryption {
111    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
112        f.debug_struct("Encryption").field("cipher", &self.cipher).field("permissions", &self.permissions).field("encrypt_metadata", &self.encrypt_metadata).finish_non_exhaustive()
113    }
114}
115
116impl Encryption {
117    /// AES-256 with these passwords, every permission, metadata encrypted
118    pub fn aes256(user: &str, owner: &str) -> Encryption {
119        Encryption::new(Cipher::Aes256, user, owner)
120    }
121
122    /// AES-128 with these passwords (PDFDocEncoding, the first 32 bytes count), every permission,
123    /// metadata encrypted
124    pub fn aes128(user: &str, owner: &str) -> Encryption {
125        Encryption::new(Cipher::Aes128, user, owner)
126    }
127
128    fn new(cipher: Cipher, user: &str, owner: &str) -> Encryption {
129        let owner = if owner.is_empty() { user } else { owner };
130        Encryption { cipher, user: String::from(user), owner: String::from(owner), permissions: Permissions::ALL, encrypt_metadata: true, seed: None }
131    }
132
133    /// what the user password allows
134    pub fn permissions(mut self, p: Permissions) -> Encryption {
135        self.permissions = p;
136        self
137    }
138
139    /// whether the XMP metadata is encrypted too (true)
140    pub fn encrypt_metadata(mut self, on: bool) -> Encryption {
141        self.encrypt_metadata = on;
142        self
143    }
144
145    /// the bytes the key, the salts and the file ID come from (instead of the system's random
146    /// numbers): the same document and the same seed give the same file.  Keep it as secret as a
147    /// key, random, and fresh for each encryption (a seed used again when the passwords change
148    /// keeps the old key): who knows the seed can decrypt without a password.  Fixed seeds are
149    /// for reproducible output such as tests
150    pub fn with_seed(mut self, seed: [u8; 32]) -> Encryption {
151        self.seed = Some(seed);
152        self
153    }
154
155    pub fn cipher(&self) -> Cipher {
156        self.cipher
157    }
158
159    /// the seed, or 32 random bytes of the system (None in the browser, which has none)
160    pub(crate) fn seed(&self) -> Option<[u8; 32]> {
161        if let Some(s) = self.seed {
162            return Some(s);
163        }
164        #[cfg(any(windows, target_os = "linux", target_vendor = "apple", target_os = "android"))]
165        {
166            Some(plat::random_bytes::<32>())
167        }
168        #[cfg(not(any(windows, target_os = "linux", target_vendor = "apple", target_os = "android")))]
169        {
170            None
171        }
172    }
173}
174
175/// n bytes for `what`, from the seed
176pub(crate) fn derive(seed: &[u8; 32], what: &[u8]) -> [u8; 32] {
177    let mut h = crypto::Sha256::new();
178    h.update(b"jflib pdf encryption ");
179    h.update(what);
180    h.update(seed);
181    h.finalize()
182}