Skip to main content

laminapdf_syntax/crypt/
perms.rs

1//! Permission flags (`/P`, ISO 32000-2 §7.6.4.2 Table 22) and the R5/R6 `/Perms` check.
2
3use super::aes;
4
5/// The user access permissions of an encrypted document, from `/P` (ISO 32000-2 Table 22).
6///
7/// `/P` is read as a 32-bit two's-complement value and only the defined bits are looked at
8/// (§7.6.4.2; research ch. 04 §7.3). Under revision 2 the R3-only bits (9–12) don't exist and
9/// their operations follow bits 3–6, as qpdf and Acrobat interpret them.
10///
11/// These are a policy marker the file asks readers to honour, not access control: anyone who can
12/// open the file can decrypt it (research ch. 04 §7.5). Enforcing them is the caller's choice.
13///
14/// ```
15/// use laminapdf_syntax::crypt::Permissions;
16///
17/// let p = Permissions::new(-3116, 4); // print, copy, form filling, accessibility; reserved bits set
18/// assert!(p.print_low_res() && p.extract() && p.fill_forms() && p.accessibility());
19/// assert!(!p.modify() && !p.print_high_res());
20/// ```
21///
22/// Added in 0.2.0.
23#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
24pub struct Permissions {
25    bits: u32,
26    revision: u8,
27}
28
29impl Permissions {
30    /// Bit 3: print.
31    const PRINT: u32 = 1 << 2;
32    /// Bit 4: modify contents (other than by bits 6, 9, 11).
33    const MODIFY: u32 = 1 << 3;
34    /// Bit 5: copy or extract text and graphics.
35    const EXTRACT: u32 = 1 << 4;
36    /// Bit 6: add or modify annotations, fill fields.
37    const ANNOTATE: u32 = 1 << 5;
38    /// Bit 9 (R3+): fill existing form fields.
39    const FILL_FORMS: u32 = 1 << 8;
40    /// Bit 10 (R3+): extract for accessibility.
41    const ACCESSIBILITY: u32 = 1 << 9;
42    /// Bit 11 (R3+): assemble (insert, rotate, delete pages; bookmarks; thumbnails).
43    const ASSEMBLE: u32 = 1 << 10;
44    /// Bit 12 (R3+): high-quality print.
45    const PRINT_HIGH: u32 = 1 << 11;
46
47    /// Permissions from a `/P` value (any integer; its low 32 bits are used) and the handler's
48    /// revision `/R`.
49    ///
50    /// Added in 0.2.0.
51    #[must_use]
52    pub const fn new(p: i64, revision: u8) -> Self {
53        #[expect(
54            clippy::cast_possible_truncation,
55            clippy::cast_sign_loss,
56            reason = "/P is a 32-bit two's-complement field: keeping the low 32 bits is the point"
57        )]
58        let bits = p as u32;
59        Self { bits, revision }
60    }
61
62    /// The `/P` bits as an unsigned 32-bit value, unmasked.
63    ///
64    /// Added in 0.2.0.
65    #[must_use]
66    pub const fn raw(&self) -> u32 {
67        self.bits
68    }
69
70    /// The defined bits only: 3–6, plus 9–12 from revision 3 on.
71    ///
72    /// Added in 0.2.0.
73    #[must_use]
74    pub const fn bits(&self) -> u32 {
75        let r2 = Self::PRINT | Self::MODIFY | Self::EXTRACT | Self::ANNOTATE;
76        let r3 = Self::FILL_FORMS | Self::ACCESSIBILITY | Self::ASSEMBLE | Self::PRINT_HIGH;
77        self.bits & if self.revision >= 3 { r2 | r3 } else { r2 }
78    }
79
80    const fn has(self, bit: u32) -> bool {
81        self.bits & bit != 0
82    }
83
84    const fn r2(self) -> bool {
85        self.revision < 3
86    }
87
88    /// Bit 3: printing is allowed (possibly only at low quality, see [`Self::print_high_res`]).
89    ///
90    /// Added in 0.2.0.
91    #[must_use]
92    pub const fn print_low_res(&self) -> bool {
93        self.has(Self::PRINT)
94    }
95
96    /// Bits 3 and 12: faithful (high-quality) printing is allowed. Under R2, bit 3 alone.
97    ///
98    /// Added in 0.2.0.
99    #[must_use]
100    pub const fn print_high_res(&self) -> bool {
101        self.has(Self::PRINT) && (self.r2() || self.has(Self::PRINT_HIGH))
102    }
103
104    /// Bit 4: modifying the contents is allowed (other than by annotation, forms or assembly).
105    ///
106    /// Added in 0.2.0.
107    #[must_use]
108    pub const fn modify(&self) -> bool {
109        self.has(Self::MODIFY)
110    }
111
112    /// Bit 5: copying or extracting text and graphics is allowed.
113    ///
114    /// Added in 0.2.0.
115    #[must_use]
116    pub const fn extract(&self) -> bool {
117        self.has(Self::EXTRACT)
118    }
119
120    /// Bit 6: adding or modifying annotations (and filling fields) is allowed.
121    ///
122    /// Added in 0.2.0.
123    #[must_use]
124    pub const fn annotate(&self) -> bool {
125        self.has(Self::ANNOTATE)
126    }
127
128    /// Bit 6 or (R3+) bit 9: filling existing form fields is allowed. Table 22: bit 6 allows
129    /// filling fields, and bit 9 allows it "even if bit 6 is clear". (qpdf's "modify forms"
130    /// reports bit 9 alone for R3+.)
131    ///
132    /// Added in 0.2.0.
133    #[must_use]
134    pub const fn fill_forms(&self) -> bool {
135        self.has(Self::ANNOTATE) || (!self.r2() && self.has(Self::FILL_FORMS))
136    }
137
138    /// Bit 10: extraction for accessibility is allowed. Under R2, bit 5. (PDF 2.0 deprecates
139    /// the bit and asks readers to treat it as set; this reports what the file says.)
140    ///
141    /// Added in 0.2.0.
142    #[must_use]
143    pub const fn accessibility(&self) -> bool {
144        self.has(if self.r2() { Self::EXTRACT } else { Self::ACCESSIBILITY })
145    }
146
147    /// Bit 11 (R3+): assembling the document is allowed, "even if bit 4 is clear" (Table 22); bit
148    /// 4 itself excludes assembly from R3 on. Under R2 assembly falls under bit 4.
149    ///
150    /// Added in 0.2.0.
151    #[must_use]
152    pub const fn assemble(&self) -> bool {
153        self.has(if self.r2() { Self::MODIFY } else { Self::ASSEMBLE })
154    }
155}
156
157/// Whether `/Perms` (R5/R6) decrypts, under the file key, to `P ‖ FF FF FF FF ‖ T|F ‖ "adb"`
158/// matching `/P` and `/EncryptMetadata` (ISO 32000-2 Algorithm 13).
159pub(crate) fn perms_match(file_key: &[u8], perms: &[u8], p: u32, encrypt_metadata: bool) -> bool {
160    let Some(plain) = perms
161        .get(..16)
162        .and_then(|block| aes::ecb_decrypt_block(file_key, block))
163    else {
164        return false;
165    };
166    let flag = if encrypt_metadata { b'T' } else { b'F' };
167    plain.get(..4) == Some(&p.to_le_bytes()[..]) && plain.get(8) == Some(&flag) && plain.get(9..12) == Some(b"adb")
168}
169
170#[cfg(test)]
171mod tests {
172    use super::Permissions;
173
174    #[test]
175    fn new_reads_p_as_32_bit_twos_complement() {
176        assert_eq!(Permissions::new(-4, 4).raw(), 0xFFFF_FFFC);
177    }
178
179    #[test]
180    fn bits_keeps_only_defined_bits() {
181        assert_eq!(Permissions::new(-1, 4).bits(), 0b1111_0011_1100);
182    }
183
184    #[test]
185    fn bits_under_r2_drops_r3_only_bits() {
186        assert_eq!(Permissions::new(-1, 2).bits(), 0b11_1100);
187    }
188
189    #[test]
190    fn fill_forms_under_r2_follows_bit_6() {
191        assert!(Permissions::new(32, 2).fill_forms());
192    }
193
194    #[test]
195    fn fill_forms_from_r3_follows_bit_6_or_bit_9() {
196        assert_eq!(
197            (
198                Permissions::new(32, 3).fill_forms(),
199                Permissions::new(256, 3).fill_forms(),
200                Permissions::new(0, 3).fill_forms()
201            ),
202            (true, true, false)
203        );
204    }
205
206    #[test]
207    fn assemble_from_r3_ignores_bit_4() {
208        assert!(!Permissions::new(8, 3).assemble());
209    }
210
211    #[test]
212    fn print_high_res_needs_bit_12_from_r3() {
213        assert!(!Permissions::new(4, 3).print_high_res());
214    }
215}