diff --git a/crates/js/src/builtins_tests.rs b/crates/js/src/builtins_tests.rs index 6a6867b270..c262216c1c 100644 --- a/crates/js/src/builtins_tests.rs +++ b/crates/js/src/builtins_tests.rs @@ -624,11 +624,14 @@ fn math_functions_follow_the_special_cases() { fn math_random_is_seeded_from_the_os_random_source() { // On wasm32-unknown-unknown `RandomState`'s keys come from memory addresses, which are the // same on every page load: the seed must come from the OS (the browser's crypto) instead. - let src = include_str!("interp.rs"); - let Some(start) = src.find("fn random_seed()") else { panic!("interp.rs has no random_seed") }; - let body = &src[start..]; - let body = &body[..body.find("\n}").unwrap_or(body.len())]; - assert!(body.contains("random_seed_from(getrandom::u64())"), "Math.random isn't seeded from the OS random source"); + // The OS value is the generator's only state: realms given the same value draw the same + // numbers, and a different value draws different ones. + let draws = |os: u64| match Realm::with_os_random(Ok(os)).run("[Math.random(), Math.random(), Math.random()].join()") { + Ok(JsValue::String(s)) => s, + other => panic!("{other:?}"), + }; + assert_eq!(draws(0x1234_5678_9abc_def0), draws(0x1234_5678_9abc_def0)); + assert_ne!(draws(0x1234_5678_9abc_def0), draws(0x0fed_cba9_8765_4321)); // The OS value is the seed, made odd so it's never zero; a failed read still gives a seed. assert_eq!(crate::interp::random_seed_from(Ok(0x40)), 0x41); assert_eq!(crate::interp::random_seed_from(Ok(0)), 1); diff --git a/crates/js/src/realm.rs b/crates/js/src/realm.rs index d673c92d26..1032b01a17 100644 --- a/crates/js/src/realm.rs +++ b/crates/js/src/realm.rs @@ -209,6 +209,15 @@ impl Realm { Self::with_options(Options::default(), Limits::default()) } + /// A realm whose `Math.random` starts from the seed made of `os`, as if the OS random source + /// had returned it. + #[cfg(test)] + pub(crate) fn with_os_random(os: Result) -> Self { + let mut realm = Self::new(); + realm.interp.random = crate::interp::random_seed_from(os); + realm + } + /// A realm whose scripts (and the source given to `eval` and `Function`) are read with /// `options`; [`Options::max_source_units`] caps the source parsed in one run, all of it /// counted together. diff --git a/crates/pdf/src/encrypt.rs b/crates/pdf/src/encrypt.rs index 6ee43ef05d..4807763598 100644 --- a/crates/pdf/src/encrypt.rs +++ b/crates/pdf/src/encrypt.rs @@ -6,7 +6,7 @@ //! algorithm follows the compatibility ([`Encryption`]): 40-bit RC4 for PDF 1.3 (revision 2), //! 128-bit RC4 for PDF 1.4 (revision 3) and 1.5 (revision 4), 128-bit AES for 1.6 (revision 4) and //! 256-bit AES for 1.7 and 2.0 (revision 6). The random file key, salts and initialisation vectors -//! come from a SHA-256 stream seeded with the process's random hash keys, the time and the file +//! come from a SHA-256 stream seeded with the OS random source, the time and the file //! itself. A linearised file is encrypted between its two steps ([`protect_keeping`]): what //! encrypted it then encrypts the hint stream written last ([`Cipher`]). //! @@ -163,7 +163,7 @@ fn hash6(password: &[u8], salt: &[u8], udata: &[u8]) -> Result<[u8; 32], PdfErro } /// Unpredictable bytes: SHA-256 of a seed and a counter. -struct Entropy { +pub(crate) struct Entropy { seed: [u8; 32], counter: u64, } @@ -172,10 +172,17 @@ impl Entropy { /// Seeded from the OS random source, with the time and `material` mixed in. fn new(material: &[&[u8]]) -> Result { let mut os = [0u8; 32]; - getrandom::fill(&mut os).map_err(|e| failed(&format!("no random numbers ({e})")))?; + let os = getrandom::fill(&mut os).map(|()| os); + Self::seeded(os, vectorcraft_doc::metadata::now_unix().unwrap_or_default(), material) + } + + /// [`Entropy::new`] from what the OS random source returned and the time. Nothing else goes + /// into the seed, and a failed OS read is an error. + pub(crate) fn seeded(os: Result<[u8; 32], getrandom::Error>, now: i64, material: &[&[u8]]) -> Result { + let os = os.map_err(|e| failed(&format!("no random numbers ({e})")))?; let mut h = Sha256::new(); h.update(os); - h.update(vectorcraft_doc::metadata::now_unix().unwrap_or_default().to_le_bytes()); + h.update(now.to_le_bytes()); for m in material { h.update((m.len() as u64).to_le_bytes()); h.update(m); @@ -183,7 +190,7 @@ impl Entropy { Ok(Self { seed: h.finalize().into(), counter: 0 }) } - fn bytes(&mut self) -> [u8; N] { + pub(crate) fn bytes(&mut self) -> [u8; N] { let mut out = [0u8; N]; for chunk in out.chunks_mut(32) { self.counter += 1; diff --git a/crates/pdf/src/tests/encrypt.rs b/crates/pdf/src/tests/encrypt.rs index c6b8772ff3..89c2542266 100644 --- a/crates/pdf/src/tests/encrypt.rs +++ b/crates/pdf/src/tests/encrypt.rs @@ -193,8 +193,17 @@ fn the_same_file_and_passwords_get_fresh_keys_each_time() { #[test] fn the_file_key_is_seeded_from_the_os_random_source() { - // `RandomState` is no CSPRNG and its keys are fixed on the web: the seed must come from the OS. - let src = include_str!("../encrypt.rs"); - assert!(!src.contains("RandomState"), "encrypt.rs seeds its keys from RandomState"); - assert!(src.contains("getrandom::fill"), "encrypt.rs doesn't seed its keys from the OS random source"); + // The OS bytes, the time and the file are the whole seed: equal inputs give equal streams, so + // no other source (such as `RandomState`, whose keys are fixed on the web) is mixed in, and + // other OS bytes alone give another stream. + use crate::encrypt::Entropy; + let file: &[&[u8]] = &[b"%PDF-2.0 same file"]; + let stream = |os: [u8; 32]| match Entropy::seeded(Ok(os), 1_700_000_000, file) { + Ok(mut e) => e.bytes::<48>(), + Err(e) => panic!("{e:?}"), + }; + assert_eq!(stream([7; 32]), stream([7; 32])); + assert_ne!(stream([7; 32]), stream([8; 32])); + // A failed OS read is an error, not a weaker seed. + assert!(Entropy::seeded(Err(getrandom::Error::UNSUPPORTED), 1_700_000_000, file).is_err()); }