Skip to content

PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust

fix(engine): generate Protect keys and salts with getrandom (#4000)

jonathanwxh-cellc05f00c67a14
diff --git a/Cargo.lock b/Cargo.lock
index a95014924..caa23b266 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -4109,6 +4109,7 @@ version = "0.11.0"
dependencies = [
"chrono",
"craft-docpath",
+ "getrandom 0.4.3",
"icu_properties",
"idna",
"image",
diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml
index f5e35088b..6dae6adf0 100644
--- a/crates/engine/Cargo.toml
+++ b/crates/engine/Cargo.toml
@@ -51,6 +51,10 @@ unicode-segmentation = "1.13"
# Already in the graph through lopdf; used only for the local UTC offset ("today"). The workspace
# entry is std-only; this target adds `clock` for `chrono::Local::now`.
chrono = { workspace = true, features = ["clock"] }
+getrandom = "0.4"
+
+[target.'cfg(target_arch = "wasm32")'.dependencies]
+getrandom = { version = "0.4", features = ["wasm_js"] }
[dev-dependencies]
pdfcraft-testkit = { workspace = true }
diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs
index e20cbc596..e61d5fef3 100644
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@ -2349,6 +2349,7 @@ struct EditCtx {
today: (i64, u32, u32),
seed: u64,
count: u64,
+ rng: fn(&mut [u8]) -> Result<(), getrandom::Error>,
/// Fields the edit renamed to keep imported names separate (old → new), for the repair
/// log and the undo label.
renamed_fields: Vec<(String, String)>,
@@ -2377,23 +2378,20 @@ impl EditCtx {
today: (1970, 1, 1),
seed,
count: 0,
+ rng: getrandom::fill,
renamed_fields: Vec::new(),
}
}
- /// 32 bytes of entropy for new encryption keys and salts. `RandomState` is seeded by the
- /// operating system, so no extra dependency is needed.
- fn entropy(&mut self) -> [u8; 32] {
- use std::hash::{BuildHasher, Hasher};
+ /// 32 bytes of entropy for new encryption keys, salts and generated owner passwords from the
+ /// platform CSPRNG. Fails closed when secure randomness is unavailable.
+ fn entropy(&mut self) -> Result<[u8; 32], EditError> {
let mut out = [0u8; 32];
- for (i, chunk) in out.chunks_mut(8).enumerate() {
- let mut h = std::collections::hash_map::RandomState::new().build_hasher();
- h.write_u64(self.seed ^ i as u64);
- h.write_u64(self.count);
- self.count += 1;
- chunk.copy_from_slice(&h.finish().to_le_bytes());
+ (self.rng)(&mut out).map_err(|e| EditError::Protection(format!("no secure randomness available: {e}")))?;
+ if out == [0u8; 32] {
+ return Err(EditError::Protection("no secure randomness available".into()));
}
- out
+ Ok(out)
}
/// A fresh `/NM`: a random-looking UUID (version 4 layout) from a splitmix64 stream.
@@ -2806,10 +2804,13 @@ fn run_edit(doc: &mut pdfcraft_cos::Document, edit: &Edit, cx: &mut EditCtx) ->
}
Edit::Protect(p) => {
p.validate()?;
- let seed = cx.entropy();
+ let seed = cx.entropy()?;
// Without a permissions password nothing is restricted, so the owner password is a
// random one nobody needs.
- let random_owner: String = cx.entropy().iter().map(|b| format!("{b:02x}")).collect();
+ let random_owner = match p.permissions_password {
+ Some(_) => String::new(),
+ None => cx.entropy()?.iter().map(|b| format!("{b:02x}")).collect(),
+ };
let params = pdfcraft_cos::NewEncryption {
algorithm: p.algorithm,
user_password: p.open_password.as_deref().unwrap_or(""),
diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs
index 0df176226..6895f188f 100644
--- a/crates/engine/src/tests.rs
+++ b/crates/engine/src/tests.rs
@@ -1884,6 +1884,78 @@ fn passwords_that_encryption_would_make_empty_or_equal_are_refused() {
}
}
+#[test]
+fn fresh_sessions_protecting_identical_documents_produce_different_salts() {
+ let raw = Arc::new(fixture(1));
+ let encrypt_bytes = |saved: Arc<Vec<u8>>, key: &[u8]| -> Vec<u8> {
+ let doc = pdfcraft_cos::Document::open_with_password(saved, Some("secret")).unwrap();
+ let enc = doc.trailer().get(b"Encrypt").map(|o| doc.resolve(o)).unwrap();
+ enc.as_dict().unwrap().get(key).map(|o| doc.resolve(o)).unwrap().as_string().unwrap().bytes.clone()
+ };
+ let protect_once = |p: Protection| -> Arc<Vec<u8>> {
+ let mut s = Session::new();
+ let id = s.open("same.pdf", None, raw.clone(), None).unwrap();
+ s.apply(id, Edit::Protect(p)).unwrap();
+ s.save_bytes(id).unwrap()
+ };
+ let a = protect_once(protection(Some("secret"), None));
+ let b = protect_once(protection(Some("secret"), None));
+ let (u_a, u_b) = (encrypt_bytes(a.clone(), b"U"), encrypt_bytes(b.clone(), b"U"));
+ let (o_a, o_b) = (encrypt_bytes(a.clone(), b"O"), encrypt_bytes(b.clone(), b"O"));
+ let (ue_a, ue_b) = (encrypt_bytes(a.clone(), b"UE"), encrypt_bytes(b.clone(), b"UE"));
+ let (oe_a, oe_b) = (encrypt_bytes(a, b"OE"), encrypt_bytes(b, b"OE"));
+ assert_eq!((u_a.len(), u_b.len(), o_a.len(), o_b.len()), (48, 48, 48, 48));
+ assert_ne!(&u_a[32..48], &u_b[32..48], "user validation and key salts must differ across fresh sessions");
+ assert_ne!(&o_a[32..48], &o_b[32..48], "owner validation and key salts must differ across fresh sessions");
+ assert_ne!(ue_a, ue_b, "wrapped user file keys must differ across fresh sessions");
+ assert_ne!(oe_a, oe_b, "wrapped owner file keys must differ across fresh sessions");
+
+ // Generated owner passwords in R4 (AES-128) must also come from CSPRNG entropy, even when the
+ // document already carries a fixed /ID and only an open password is set.
+ let mut with_id = pdfcraft_cos::Document::open(raw).unwrap();
+ let fixed_id = pdfcraft_cos::Object::String(pdfcraft_cos::PdfString { bytes: b"0123456789abcdef".to_vec(), hex: true });
+ with_id.trailer_mut().set(b"ID".to_vec(), pdfcraft_cos::Object::Array(vec![fixed_id.clone(), fixed_id]));
+ let raw_with_id = Arc::new(pdfcraft_cos::write_full(&with_id, &Default::default()).unwrap());
+ let protect_r4 = || -> Vec<u8> {
+ let mut s = Session::new();
+ let id = s.open("same.pdf", None, raw_with_id.clone(), None).unwrap();
+ let p = Protection { algorithm: pdfcraft_cos::Algorithm::Aes128, ..protection(Some("secret"), None) };
+ s.apply(id, Edit::Protect(p)).unwrap();
+ encrypt_bytes(s.save_bytes(id).unwrap(), b"O")
+ };
+ assert_ne!(protect_r4(), protect_r4(), "generated owner passwords must differ across fresh sessions");
+}
+
+#[test]
+fn protect_fails_closed_when_randomness_is_unavailable() {
+ use std::sync::atomic::{AtomicUsize, Ordering};
+ static CALLS: AtomicUsize = AtomicUsize::new(0);
+ fn fail_rng(_: &mut [u8]) -> Result<(), getrandom::Error> {
+ Err(getrandom::Error::UNSUPPORTED)
+ }
+ fn zero_rng(out: &mut [u8]) -> Result<(), getrandom::Error> {
+ out.fill(0);
+ Ok(())
+ }
+ fn fail_second_rng(out: &mut [u8]) -> Result<(), getrandom::Error> {
+ if CALLS.fetch_add(1, Ordering::SeqCst) == 0 {
+ out.fill(0xA5);
+ Ok(())
+ } else {
+ Err(getrandom::Error::UNSUPPORTED)
+ }
+ }
+ CALLS.store(0, Ordering::SeqCst);
+ for rng in [fail_rng, zero_rng, fail_second_rng] {
+ let mut doc = pdfcraft_cos::Document::open(Arc::new(fixture(1))).unwrap();
+ let mut cx = EditCtx::new(None, 0);
+ cx.rng = rng;
+ let err = run_edit(&mut doc, &Edit::Protect(protection(Some("secret"), None)), &mut cx);
+ assert!(matches!(err, Err(EditError::Protection(_))), "Protect must fail closed when CSPRNG fails: {err:?}");
+ assert!(doc.output_handler().is_none(), "document must stay unprotected when CSPRNG fails");
+ }
+}
+
/// A one-page form: a text field and a check box (with appearance states).
fn form_fixture() -> Vec<u8> {
let objs = [