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/interp.rs b/crates/js/src/interp.rs index 517caa9c06..dac4a0c729 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -544,7 +544,29 @@ fn index_names_bytes(len: usize, per_entry: usize) -> usize { /// random source (the browser's crypto on the web), or the standard library's randomly keyed /// hasher when that fails; never zero. fn random_seed() -> u64 { - random_seed_from(getrandom::u64()) + random_seed_from(os_random()) +} + +#[cfg(test)] +thread_local! { + /// What the OS random source returns to realms made on this thread, when set. + pub(crate) static TEST_OS_RANDOM: std::cell::Cell>> = const { std::cell::Cell::new(None) }; +} + +/// The OS random source (in tests, what `TEST_OS_RANDOM` holds when set). +fn os_random() -> Result { + test_os_random().unwrap_or_else(getrandom::u64) +} + +/// What a test set in `TEST_OS_RANDOM`. +#[cfg(test)] +fn test_os_random() -> Option> { + TEST_OS_RANDOM.with(std::cell::Cell::get) +} + +#[cfg(not(test))] +fn test_os_random() -> Option> { + None } /// [`random_seed`] from what the OS random source returned. diff --git a/crates/js/src/realm.rs b/crates/js/src/realm.rs index d673c92d26..822477780f 100644 --- a/crates/js/src/realm.rs +++ b/crates/js/src/realm.rs @@ -209,6 +209,17 @@ 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. The realm is made by [`Realm::new`], so its seed comes through the same + /// path as any other realm's. + #[cfg(test)] + pub(crate) fn with_os_random(os: Result) -> Self { + crate::interp::TEST_OS_RANDOM.with(|c| c.set(Some(os))); + let realm = Self::new(); + crate::interp::TEST_OS_RANDOM.with(|c| c.set(None)); + 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..e9d845756c 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`]). //! @@ -168,14 +168,49 @@ struct Entropy { counter: u64, } +/// What the OS random source returned, and the time. +type SeedSources = (Result<[u8; 32], getrandom::Error>, i64); + +#[cfg(test)] +thread_local! { + /// What the OS random source and the clock return to [`Entropy::new`] on this thread, when set. + pub(crate) static TEST_SEED_SOURCES: std::cell::Cell> = const { std::cell::Cell::new(None) }; +} + +/// 32 bytes from the OS random source, and the time. +fn seed_sources() -> SeedSources { + test_seed_sources().unwrap_or_else(|| { + let mut os = [0u8; 32]; + let os = getrandom::fill(&mut os).map(|()| os); + (os, vectorcraft_doc::metadata::now_unix().unwrap_or_default()) + }) +} + +/// What a test set in `TEST_SEED_SOURCES`. +#[cfg(test)] +fn test_seed_sources() -> Option { + TEST_SEED_SOURCES.with(std::cell::Cell::get) +} + +#[cfg(not(test))] +fn test_seed_sources() -> Option { + None +} + 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, now) = seed_sources(); + Self::seeded(os, now, 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. + 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); diff --git a/crates/pdf/src/tests/encrypt.rs b/crates/pdf/src/tests/encrypt.rs index c6b8772ff3..5e586bec6f 100644 --- a/crates/pdf/src/tests/encrypt.rs +++ b/crates/pdf/src/tests/encrypt.rs @@ -193,8 +193,26 @@ 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. The exports set what the OS and the clock return. + use crate::encrypt::TEST_SEED_SOURCES; + let mut opts = PdfOptions::default(); + opts.settings.compatibility = Compatibility::Pdf20; + let plain = export(&doc(), &opts).unwrap(); + opts.settings.security = security("pw", "own"); + let protect_with = |os: Result<[u8; 32], getrandom::Error>| { + TEST_SEED_SOURCES.with(|c| c.set(Some((os, 1_700_000_000)))); + let out = protect(plain.clone(), &opts.settings); + TEST_SEED_SOURCES.with(|c| c.set(None)); + out + }; + let dict = |os: [u8; 32]| match protect_with(Ok(os)) { + Ok(bytes) => encrypt_dict(&bytes), + Err(e) => panic!("{e:?}"), + }; + assert_eq!(dict([7; 32]), dict([7; 32])); + assert_ne!(dict([7; 32]), dict([8; 32])); + // A failed OS read is an error, not a weaker seed. + assert!(protect_with(Err(getrandom::Error::UNSUPPORTED)).is_err()); }