Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/synapse/blob/main/crates/synapse-bench/src/crypto_vectors/tests.rs # synapse A component of the AienOS ecosystem. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `synapse / crates / synapse-bench / src / crypto_vectors / tests.rs` 729 lines ยท 25480 bytes Raw Blame History 1 //! J3 tests: the vector corpus the Omega port must match, and the build of the Rust 2 //! reference itself. No test asserts a speed. 3 4 use super::*; 5 use `ed25519`_dalek::{Signer, SigningKey}; 6 use std::path::{Path, PathBuf}; 7 use std::process::Command; 8 9 fn repo_root() -> PathBuf { 10 Path::new(env!("CARGO_MANIFEST_DIR")).join("../..") 11 } 12 13 fn unhex(s: &str) -> [u8; N] { 14 hex::decode(s).unwrap().try_into().unwrap() 15 } 16 17 /// FIPS 180-4 example messages with their published SHA-256 digests (NIST "Example 18 /// Algorithms", SHA256.pdf and SHA2_Additional, and FIPS 180-2 Appendix B). 19 const FIPS_SHA256: [(&[u8], &str); 4] = [ 20 ( 21 b"", 22 "`e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855`", 23 ), 24 ( 25 b"abc", 26 "`ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad`", 27 ), 28 ( 29 b"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq", 30 "`248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1`", 31 ), 32 ( 33 b"abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu", 34 "`cf5b16a778af8380036ce59e7b0492370b249b11e8f07a51afac45037afee9d1`", 35 ), 36 ]; 37 38 /// RFC 8032 section 7.1, TEST 1 to TEST 3: (secret key, public key, message, signature). 39 const RFC8032: [(&str, &str, &str, &str); 3] = [ 40 ( 41 "`9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60`", 42 "`d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a`", 43 "", 44 "`e5564300c360ac729086e2cc806e828a84877f1eb8e5d974d873e065224901555fb8821590a33bacc61e39701cf9b46bd25bf5f0595bbe24655141438e7a100b`", 45 ), 46 ( 47 "`4ccd089b28ff96da9db6c346ec114e0f5b8a319f35aba624da8cf6ed4fb8a6fb`", 48 "`3d4017c3e843895a92b70aa74d1b7ebc9c982ccf2ec4968cc0cd55f12af4660c`", 49 "72", 50 "`92a009a9f0d4cab8720e820b5f642540a2b27b5416503f8fb3762223ebdb69da085ac1e43e15996e458f3613d0f11d8c387b2eaeb4302aeeb00d291612bb0c00`", 51 ), 52 ( 53 "`c5aa8df43f9f837bedb7442f31dcb7b166d38535076f094b85ce3a2e0b4458f7`", 54 "`fc51cd8e6218a1a38da47ed00230f0580816ed13ba3303ac5deb911548908025`", 55 "af82", 56 "`6291d657deec24024827e69c3abe01a30ce548a284743a445e3680d7db5ac3ac18ff9b538d16f290ae67f760984dc6594a7c15e9716ed28dc027beceea1ec40a`", 57 ), 58 ]; 59 60 const ALL_ACCEPT: Ed25519Verdict = Ed25519Verdict { 61 key_decodes: true, 62 verify: true, 63 verify_strict: true, 64 }; 65 66 fn has_`ed25519`(c: &[Vector], pk: [u8; 32], sig: [u8; 64], msg: &[u8]) -> Option { 67 c.iter().find_map(|v| match v { 68 Vector::Ed25519 { 69 public_key, 70 signature, 71 message, 72 verdict, 73 } if *public_key == pk && *signature == sig && message == msg => Some(*verdict), 74 _ => None, 75 }) 76 } 77 78 /// The `sha2` 0.10 crate compiles its Armv8 SHA-2 instruction backend (with run-time 79 /// detection and the portable code as fallback) only when its `asm` feature is on 80 /// (`sha2/src/sha256.rs`). The resolved feature set is read from `cargo metadata`; 81 /// without cargo the test fails rather than passes. 82 #[test] 83 fn workspace_sha2_is_built_with_its_aarch64_instruction_backend() { 84 let cargo = std::env::var("CARGO").expect("CARGO is unset: cannot read the resolved features"); 85 let out = Command::new(cargo) 86 .args([ 87 "metadata", 88 "--format-version", 89 "1", 90 "--offline", 91 "--manifest-path", 92 ]) 93 .arg(repo_root().join("Cargo.toml")) 94 .output() 95 .expect("run cargo metadata"); 96 assert!(out.status.success(), "cargo metadata failed"); 97 let meta: serde_json::Value = serde_json::from_slice(&out.stdout).unwrap(); 98 let ids: Vec<&str> = meta["packages"] 99 .as_array() 100 .unwrap() 101 .iter() 102 .filter(|p| p["name"] == "sha2") 103 .map(|p| p["id"].as_str().unwrap()) 104 .collect(); 105 assert!(!ids.is_empty(), "sha2 not in the dependency graph"); 106 for node in meta["resolve"]["nodes"].as_array().unwrap() { 107 if ids.contains(&node["id"].as_str().unwrap()) { 108 let features: Vec<&str> = node["features"] 109 .as_array() 110 .unwrap() 111 .iter() 112 .map(|f| f.as_str().unwrap()) 113 .collect(); 114 assert!( 115 features.contains(&"asm"), 116 "{} is built without its `asm` feature, so aarch64 uses the software backend (features: {features:?})", 117 node["id"] 118 ); 119 } 120 } 121 // The backend actually in use: linked into this binary and selected at run time. 122 assert_sha2_backend(Backend::Instructions); 123 } 124 125 #[test] 126 fn published_sha256_answers_match_the_rust_crate_and_are_in_the_corpus() { 127 let corpus = rust_corpus(); 128 for (msg, want) in FIPS_SHA256 { 129 let want: [u8; 32] = unhex(want); 130 assert_eq!(<[u8; 32]>::from(Sha256::digest(msg)), want); 131 assert!( 132 corpus.contains(&Vector::Sha256 { 133 message: msg.to_vec(), 134 digest: want 135 }), 136 "FIPS message of {} bytes missing from the corpus", 137 msg.len() 138 ); 139 } 140 // One million 'a' (FIPS 180-2 Appendix B.3): checked here only; too large to seal. 141 assert_eq!( 142 hex::encode(Sha256::digest(vec![b'a'; 1_000_000])), 143 "`cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0`" 144 ); 145 } 146 147 #[test] 148 fn every_length_across_the_block_boundaries_is_in_the_corpus() { 149 let corpus = rust_corpus(); 150 let lengths: Vec = corpus 151 .iter() 152 .filter_map(|v| match v { 153 Vector::Sha256 { message, .. } => Some(message.len()), 154 _ => None, 155 }) 156 .collect(); 157 for len in 0..=257 { 158 assert!(lengths.contains(&len), "no SHA-256 vector of {len} bytes"); 159 } 160 // The Gate 4 change size and the A0 probe block. 161 for len in [11_949, 16_384] { 162 assert!(lengths.contains(&len), "no SHA-256 vector of {len} bytes"); 163 } 164 } 165 166 #[test] 167 fn rfc8032_vectors_match_the_rust_crate_and_are_in_the_corpus() { 168 let corpus = rust_corpus(); 169 for (sk, pk, msg, sig) in RFC8032 { 170 let key = SigningKey::from_bytes(&unhex(sk)); 171 let pk: [u8; 32] = unhex(pk); 172 let sig: [u8; 64] = unhex(sig); 173 let msg = hex::decode(msg).unwrap(); 174 assert_eq!(key.verifying_key().to_bytes(), pk); 175 assert_eq!(key.sign(&msg).to_bytes(), sig); 176 assert_eq!( 177 has_`ed25519`(&corpus, pk, sig, &msg), 178 Some(ALL_ACCEPT), 179 "RFC 8032 vector missing or not accepted" 180 ); 181 } 182 } 183 184 /// The corpus must pin the decisions where implementations differ: a small-order key 185 /// (accepted by `verify`, refused by `verify_strict`), a key that does not decode, a 186 /// non-canonical S (S + L), and a changed message. 187 #[test] 188 fn corpus_pins_the_edge_case_decisions() { 189 let corpus = rust_corpus(); 190 let (pk, sig) = (unhex::<32>(RFC8032[0].1), unhex::<64>(RFC8032[0].3)); 191 192 let mut identity = [0u8; 32]; 193 identity[0] = 1; 194 let mut small_sig = [0u8; 64]; 195 small_sig[..32].copy_from_slice(&identity); 196 assert_eq!( 197 has_`ed25519`(&corpus, identity, small_sig, SMALL_ORDER_MESSAGE), 198 Some(Ed25519Verdict { 199 key_decodes: true, 200 verify: true, 201 verify_strict: false 202 }), 203 "small-order key case missing or not split between verify and verify_strict" 204 ); 205 206 // S + L, with L the order of the base point (RFC 8032 section 5.1), little endian. 207 let l: [u8; 32] = unhex("`edd3f55c1a631258d69cf7a2def9de1400000000000000000000000000000010`"); 208 let mut s_plus_l = sig; 209 let mut carry = 0u16; 210 for i in 0..32 { 211 let t = sig[32 + i] as u16 + l[i] as u16 + carry; 212 s_plus_l[32 + i] = t as u8; 213 carry = t >> 8; 214 } 215 assert_eq!(carry, 0); 216 let v = has_`ed25519`(&corpus, pk, s_plus_l, b"").expect("non-canonical S case missing"); 217 assert!(v.key_decodes && !v.verify && !v.verify_strict, "{v:?}"); 218 219 let bad_key = corpus.iter().any(|v| { 220 matches!(v, Vector::Ed25519 { verdict, .. } if *verdict == Ed25519Verdict { 221 key_decodes: false, verify: false, verify_strict: false }) 222 }); 223 assert!(bad_key, "no key that fails to decode"); 224 225 let v = has_`ed25519`(&corpus, pk, sig, b"\x01").expect("changed-message case missing"); 226 assert!(v.key_decodes && !v.verify && !v.verify_strict, "{v:?}"); 227 } 228 229 #[test] 230 fn every_corpus_answer_is_the_rust_crates_answer() { 231 let corpus = rust_corpus(); 232 assert!(!corpus.is_empty()); 233 check_against_rust_crates(&corpus).unwrap(); 234 // A changed digest or verdict must be caught. 235 let mut wrong = corpus.clone(); 236 match &mut wrong[0] { 237 Vector::Sha256 { digest, .. } => digest[0] ^= 1, 238 Vector::Ed25519 { verdict, .. } => verdict.verify = !verdict.verify, 239 } 240 assert_eq!(check_against_rust_crates(&wrong).unwrap_err().index, 0); 241 } 242 243 #[test] 244 fn corpus_round_trips_byte_for_byte() { 245 let corpus = rust_corpus(); 246 let bytes = encode(&corpus); 247 assert_eq!(&bytes[..8], &CORPUS_MAGIC); 248 let back = decode(&bytes).unwrap(); 249 assert_eq!(back, corpus); 250 assert_eq!(encode(&back), bytes); 251 } 252 253 #[test] 254 fn decoder_refuses_malformed_corpora_with_typed_errors() { 255 let one = encode(&[ 256 sha256_vector(b"abc"), 257 `ed25519`_vector(unhex(RFC8032[0].1), unhex(RFC8032[0].3), b""), 258 ]); 259 let reseal = |mut b: Vec| { 260 let n = b.len() - 32; 261 let sum: [u8; 32] = Sha256::digest(&b[..n]).into(); 262 b[n..].copy_from_slice(&sum); 263 b 264 }; 265 266 // Every strict prefix is refused (no panic, no partial result). 267 for n in 0..one.len() { 268 assert!(decode(&one[..n]).is_err(), "prefix of {n} bytes accepted"); 269 } 270 let mut b = one.clone(); 271 b[0] ^= 1; 272 assert_eq!(decode(&b), Err(CorpusError::BadMagic)); 273 let mut b = one.clone(); 274 b[8] = 2; 275 assert_eq!(decode(&reseal(b)), Err(CorpusError::UnsupportedVersion(2))); 276 let mut b = one.clone(); 277 b[10] = 1; 278 assert_eq!(decode(&reseal(b)), Err(CorpusError::ReservedHeaderBits(1))); 279 let mut b = one.clone(); 280 b[16] = 9; 281 assert_eq!( 282 decode(&reseal(b)), 283 Err(CorpusError::UnknownKind { at: 16, kind: 9 }) 284 ); 285 // SHA record: 1 + 4 + 3 + 32 bytes; the Ed25519 verdict byte follows its kind. 286 let ed_at = 16 + 1 + 4 + 3 + 32; 287 let mut b = one.clone(); 288 b[ed_at + 1] |= 0x80; 289 assert!(matches!( 290 decode(&reseal(b)), 291 Err(CorpusError::ReservedVerdictBits { .. }) 292 )); 293 let mut b = one.clone(); 294 b[17..21].copy_from_slice(&(MAX_MESSAGE_BYTES + 1).to_le_bytes()); 295 assert_eq!( 296 decode(&reseal(b)), 297 Err(CorpusError::MessageTooLong { 298 at: 17, 299 len: MAX_MESSAGE_BYTES + 1 300 }) 301 ); 302 let mut b = one.clone(); 303 b[12..16].copy_from_slice(&1u32.to_le_bytes()); 304 assert!(matches!( 305 decode(&reseal(b)), 306 Err(CorpusError::TrailingBytes { .. }) 307 )); 308 let mut b = one.clone(); 309 b[21] ^= 1; // one message bit, checksum left as it was 310 assert_eq!(decode(&b), Err(CorpusError::ChecksumMismatch)); 311 } 312 313 /// The sealed file is exactly what the Rust crates produce today, and decodes. 314 #[test] 315 fn sealed_corpus_matches_the_rust_crates_exactly() { 316 let path = repo_root().join(CORPUS_PATH); 317 let sealed = std::fs::read(&path).unwrap_or_else(|e| panic!("{}: {e}", path.display())); 318 let vectors = decode(&sealed).unwrap(); 319 check_against_rust_crates(&vectors).unwrap(); 320 assert!( 321 sealed == encode(&rust_corpus()), 322 "sealed corpus differs from the Rust crates' corpus" 323 ); 324 } 325 326 /// A second, independent SHA-256 (the A0 probe's own SHA-2 instruction code) gives 327 /// every corpus digest. On aarch64 the instructions must be present: a missing 328 /// instruction set fails the test instead of skipping it. 329 #[cfg(target_arch = "aarch64")] 330 #[test] 331 fn a0_instruction_code_gives_every_corpus_digest() { 332 let corpus = rust_corpus(); 333 let mut n = 0; 334 for v in &corpus { 335 if let Vector::Sha256 { message, digest } = v { 336 let got = crate::bounds::sha256_arm(message).expect("CPU SHA-2 instructions missing"); 337 assert_eq!(&got, digest, "length {}", message.len()); 338 n += 1; 339 } 340 } 341 assert!(n > 0); 342 } 343 344 // --------------------------------------------------------------------------------- 345 // Which sha2 backend runs, and the portable fallback run automatically 346 // --------------------------------------------------------------------------------- 347 348 #[derive(Debug, Clone, Copy, PartialEq, Eq)] 349 enum Backend { 350 Instructions, 351 Portable, 352 } 353 354 /// Path segment of `sha2::sha256::aarch64::sha256_compress` in both the legacy and 355 /// v0 symbol manglings, stored reversed so this constant cannot match itself in the 356 /// binary being searched. 357 const SHA2_AARCH64_SYMBOL_REVERSED: &[u8] = b"sserpmoc_652ahs5146hcraa7652ahs62ahs4"; 358 359 /// `sha2` chooses its SHA-256 backend twice: at build time (the aarch64 module exists 360 /// only with `asm` and without `force-soft`) and at run time (`cpufeatures` checks the 361 /// `sha2` hwcap). Check both for this very test binary; any missing input fails. 362 fn assert_sha2_backend(want: Backend) { 363 let exe = std::fs::read("/proc/self/exe").expect("read own executable"); 364 let symbol: Vec = SHA2_AARCH64_SYMBOL_REVERSED.iter().rev().copied().collect(); 365 let linked = exe.windows(symbol.len()).any(|w| w == symbol); 366 #[cfg(target_arch = "aarch64")] 367 let hwcap = std::arch::is_aarch64_feature_detected!("sha2"); 368 #[cfg(not(target_arch = "aarch64"))] 369 let hwcap = false; 370 let got = if linked && hwcap { 371 Backend::Instructions 372 } else { 373 Backend::Portable 374 }; 375 assert_eq!( 376 got, want, 377 "sha2 backend: instruction code linked = {linked}, CPU reports sha2 = {hwcap}" 378 ); 379 } 380 381 const INNER_ENV: &str = "SYNAPSE_J3_PORTABLE_INNER"; 382 383 /// Run only inside the portable build started by 384 /// `portable_sha2_backend_gives_the_sealed_corpus`. 385 #[test] 386 fn inner_portable_backend_is_in_use() { 387 if std::env::var_os(INNER_ENV).is_none() { 388 return; 389 } 390 assert_sha2_backend(Backend::Portable); 391 } 392 393 /// Builds this crate a second time with `sha2/force-soft` (its portable backend; a 394 /// separate target directory, so no lock is shared with this run) and runs the 395 /// sealed-corpus test and the backend check there. sha2 0.10 fixes its backend at 396 /// build time, so the portable code cannot run inside this process. 397 #[test] 398 fn portable_sha2_backend_gives_the_sealed_corpus() { 399 if std::env::var_os(INNER_ENV).is_some() { 400 return; 401 } 402 let cargo = std::env::var("CARGO").expect("CARGO is unset: cannot build the portable variant"); 403 let out = Command::new(cargo) 404 .current_dir(repo_root()) 405 .env(INNER_ENV, "1") 406 .args([ 407 "test", 408 "--offline", 409 "-p", 410 "synapse-bench", 411 "--lib", 412 "--features", 413 "sha2/force-soft", 414 "--target-dir", 415 ]) 416 .arg(repo_root().join("target/j3-portable-sha2")) 417 .args([ 418 "--", 419 "--exact", 420 "crypto_vectors::tests::sealed_corpus_matches_the_rust_crates_exactly", 421 "crypto_vectors::tests::inner_portable_backend_is_in_use", 422 "crypto_vectors::tests::every_corpus_answer_is_the_rust_crates_answer", 423 ]) 424 .output() 425 .expect("run cargo test for the portable build"); 426 let stdout = String::from_utf8_lossy(&out.stdout); 427 assert!( 428 out.status.success() && stdout.contains("test result: ok. 3 passed"), 429 "portable build failed:\n{stdout}\n{}", 430 String::from_utf8_lossy(&out.stderr) 431 ); 432 } 433 434 // --------------------------------------------------------------------------------- 435 // The sealed corpus is pinned 436 // --------------------------------------------------------------------------------- 437 438 #[test] 439 fn sealed_corpus_digest_is_pinned() { 440 assert_eq!(CORPUS_SHA256.len(), 64, "corpus digest not pinned"); 441 let sealed = std::fs::read(repo_root().join(CORPUS_PATH)).unwrap(); 442 assert_eq!(hex::encode(Sha256::digest(&sealed)), CORPUS_SHA256); 443 assert_eq!( 444 hex::encode(Sha256::digest(encode(&rust_corpus()))), 445 CORPUS_SHA256 446 ); 447 } 448 449 // --------------------------------------------------------------------------------- 450 // Ed25519 edge cases, each shown to separate a wrong implementation 451 // --------------------------------------------------------------------------------- 452 453 mod models { 454 //! Independent models of the two ``ed25519`-dalek` checks, built on 455 //! `curve25519-dalek`, and wrong variants of them. Each wrong variant differs from 456 //! the right one in exactly one rule. 457 use curve25519_dalek::edwards::{CompressedEdwardsY, EdwardsPoint}; 458 use curve25519_dalek::scalar::Scalar; 459 use curve25519_dalek::traits::IsIdentity; 460 use sha2::{Digest, Sha512}; 461 462 pub type Check = fn(&[u8; 32], &[u8; 64], &[u8]) -> bool; 463 464 fn k(r: &[u8], a: &[u8], m: &[u8]) -> Scalar { 465 let mut h = Sha512::new(); 466 h.update(r); 467 h.update(a); 468 h.update(m); 469 Scalar::from_bytes_mod_order_wide(&h.finalize().into()) 470 } 471 472 struct Parts { 473 a: EdwardsPoint, 474 r_bytes: [u8; 32], 475 s_bytes: [u8; 32], 476 } 477 478 fn parts(pk: &[u8; 32], sig: &[u8; 64]) -> Option { 479 Some(Parts { 480 a: CompressedEdwardsY(*pk).decompress()?, 481 r_bytes: sig[..32].try_into().unwrap(), 482 s_bytes: sig[32..].try_into().unwrap(), 483 }) 484 } 485 486 fn canonical_s(p: &Parts) -> Option { 487 Option::from(Scalar::from_canonical_bytes(p.s_bytes)) 488 } 489 490 /// [S]B - [k]A, with k over the encodings as given. 491 fn r_prime(p: &Parts, pk: &[u8], s: &Scalar, m: &[u8]) -> EdwardsPoint { 492 let k = k(&p.r_bytes, pk, m); 493 EdwardsPoint::vartime_double_scalar_mul_basepoint(&k, &-p.a, s) 494 } 495 496 fn small_order_r(p: &Parts) -> Option { 497 Some(CompressedEdwardsY(p.r_bytes).decompress()?.is_small_order()) 498 } 499 500 /// Model of `verify`: canonical S, cofactorless, R compared as bytes. 501 pub fn verify(pk: &[u8; 32], sig: &[u8; 64], m: &[u8]) -> bool { 502 (|| { 503 let p = parts(pk, sig)?; 504 let s = canonical_s(&p)?; 505 Some(r_prime(&p, pk, &s, m).compress().0 == p.r_bytes) 506 })() 507 .unwrap_or(false) 508 } 509 510 /// Model of `verify_strict`: `verify` plus R decodes and neither A nor R has small order. 511 pub fn verify_strict(pk: &[u8; 32], sig: &[u8; 64], m: &[u8]) -> bool { 512 (|| { 513 let p = parts(pk, sig)?; 514 Some(!small_order_r(&p)? && !p.a.is_small_order() && verify(pk, sig, m)) 515 })() 516 .unwrap_or(false) 517 } 518 519 /// WRONG: decodes R and compares points, so non-canonical R encodings pass. 520 pub fn point_compare(pk: &[u8; 32], sig: &[u8; 64], m: &[u8]) -> bool { 521 (|| { 522 let p = parts(pk, sig)?; 523 let s = canonical_s(&p)?; 524 let r = CompressedEdwardsY(p.r_bytes).decompress()?; 525 Some(r_prime(&p, pk, &s, m) == r) 526 })() 527 .unwrap_or(false) 528 } 529 530 /// WRONG: cofactored equation [8]([S]B - [k]A - R) = 0. 531 pub fn cofactored(pk: &[u8; 32], sig: &[u8; 64], m: &[u8]) -> bool { 532 (|| { 533 let p = parts(pk, sig)?; 534 let s = canonical_s(&p)?; 535 let r = CompressedEdwardsY(p.r_bytes).decompress()?; 536 Some((r_prime(&p, pk, &s, m) - r).mul_by_cofactor().is_identity()) 537 })() 538 .unwrap_or(false) 539 } 540 541 /// WRONG: cofactored equation with the strict small-order checks. 542 pub fn cofactored_strict(pk: &[u8; 32], sig: &[u8; 64], m: &[u8]) -> bool { 543 (|| { 544 let p = parts(pk, sig)?; 545 Some(!small_order_r(&p)? && !p.a.is_small_order() && cofactored(pk, sig, m)) 546 })() 547 .unwrap_or(false) 548 } 549 550 /// WRONG: reduces S modulo L instead of refusing S >= L. 551 pub fn s_mod_l(pk: &[u8; 32], sig: &[u8; 64], m: &[u8]) -> bool { 552 (|| { 553 let p = parts(pk, sig)?; 554 let s = Scalar::from_bytes_mod_order(p.s_bytes); 555 Some(r_prime(&p, pk, &s, m).compress().0 == p.r_bytes) 556 })() 557 .unwrap_or(false) 558 } 559 560 /// WRONG: hashes the re-encoded (canonical) A instead of the bytes given. 561 pub fn canonical_a_in_hash(pk: &[u8; 32], sig: &[u8; 64], m: &[u8]) -> bool { 562 (|| { 563 let p = parts(pk, sig)?; 564 let s = canonical_s(&p)?; 565 let a = p.a.compress().0; 566 Some(r_prime(&p, &a, &s, m).compress().0 == p.r_bytes) 567 })() 568 .unwrap_or(false) 569 } 570 571 /// WRONG: also refuses keys with a small-order component (not torsion free). 572 pub fn torsion_free_key(pk: &[u8; 32], sig: &[u8; 64], m: &[u8]) -> bool { 573 parts(pk, sig).is_some_and(|p| p.a.is_torsion_free()) && verify(pk, sig, m) 574 } 575 576 /// WRONG as `verify_strict`: checks A for small order but not R. 577 pub fn strict_without_r_check(pk: &[u8; 32], sig: &[u8; 64], m: &[u8]) -> bool { 578 parts(pk, sig).is_some_and(|p| !p.a.is_small_order()) && verify(pk, sig, m) 579 } 580 581 /// WRONG as `verify_strict`: no small-order checks at all. 582 pub fn strict_without_small_order_checks(pk: &[u8; 32], sig: &[u8; 64], m: &[u8]) -> bool { 583 verify(pk, sig, m) 584 } 585 } 586 587 #[derive(Debug, Clone, Copy)] 588 enum Call { 589 Verify, 590 VerifyStrict, 591 } 592 593 /// Every edge case, the wrong implementation it catches, and the dalek decision it 594 /// is compared with. Cases follow the classes of Chalkias, Garillot and Nikolaenko, 595 /// "Taming the many EdDSAs" (SSR 2020, IACR ePrint 2020/1244): small-order A and R, 596 /// non-canonical A and R, mixed-order A and R, S >= L, and the cofactored versus 597 /// cofactorless split. 598 const SEPARATIONS: [(&str, &str, models::Check, Call); 10] = [ 599 ( 600 "noncanonical_r_y_p_plus_1", 601 "point compare", 602 models::point_compare, 603 Call::Verify, 604 ), 605 ( 606 "noncanonical_r_negative_zero", 607 "point compare", 608 models::point_compare, 609 Call::Verify, 610 ), 611 ( 612 "noncanonical_a_y_p", 613 "canonical A in hash", 614 models::canonical_a_in_hash, 615 Call::Verify, 616 ), 617 ( 618 "small_order_a_and_r", 619 "no small-order checks", 620 models::strict_without_small_order_checks, 621 Call::VerifyStrict, 622 ), 623 ( 624 "small_order_r_valid_key", 625 "no small-order R check", 626 models::strict_without_r_check, 627 Call::VerifyStrict, 628 ), 629 ( 630 "mixed_order_a_k_not_multiple_of_8", 631 "cofactored", 632 models::cofactored, 633 Call::Verify, 634 ), 635 ( 636 "mixed_order_a_k_multiple_of_8", 637 "torsion-free key check", 638 models::torsion_free_key, 639 Call::Verify, 640 ), 641 ( 642 "mixed_order_r", 643 "cofactored", 644 models::cofactored, 645 Call::Verify, 646 ), 647 ( 648 "mixed_order_r", 649 "cofactored strict", 650 models::cofactored_strict, 651 Call::VerifyStrict, 652 ), 653 ( 654 "noncanonical_s_plus_l", 655 "S reduced mod L", 656 models::s_mod_l, 657 Call::Verify, 658 ), 659 ]; 660 661 /// The right models reproduce dalek on every corpus record, so a disagreement of a 662 /// wrong model is due to its one changed rule. 663 #[test] 664 fn models_reproduce_dalek_on_the_whole_corpus() { 665 let mut n = 0; 666 for v in rust_corpus() { 667 if let Vector::Ed25519 { 668 public_key, 669 signature, 670 message, 671 verdict, 672 } = v 673 { 674 assert_eq!( 675 models::verify(&public_key, &signature, &message), 676 verdict.verify 677 ); 678 assert_eq!( 679 models::verify_strict(&public_key, &signature, &message), 680 verdict.verify_strict 681 ); 682 n += 1; 683 } 684 } 685 assert!(n > 0); 686 } 687 688 #[test] 689 fn each_edge_case_is_in_the_corpus_and_catches_a_wrong_implementation() { 690 let corpus = rust_corpus(); 691 let cases = `ed25519`_edge_cases(); 692 for (name, wrong_name, wrong, call) in SEPARATIONS { 693 let (_, v) = cases 694 .iter() 695 .find(|(n, _)| *n == name) 696 .unwrap_or_else(|| panic!("edge case {name} missing")); 697 assert!(corpus.contains(v), "{name} not in the corpus"); 698 let Vector::Ed25519 { 699 public_key, 700 signature, 701 message, 702 verdict, 703 } = v 704 else { 705 panic!("{name} is not an Ed25519 case"); 706 }; 707 let right = match call { 708 Call::Verify => verdict.verify, 709 Call::VerifyStrict => verdict.verify_strict, 710 }; 711 assert_ne!( 712 wrong(public_key, signature, message), 713 right, 714 "{name}: the {wrong_name} implementation gives dalek's {call:?} answer" 715 ); 716 // The wrong implementation is otherwise right: it accepts RFC 8032 TEST 1. 717 let (pk, sig) = (unhex::<32>(RFC8032[0].1), unhex::<64>(RFC8032[0].3)); 718 assert!( 719 wrong(&pk, &sig, b""), 720 "{wrong_name} refuses RFC 8032 TEST 1" 721 ); 722 } 723 for (name, _) in &cases { 724 assert!( 725 SEPARATIONS.iter().any(|s| s.0 == *name), 726 "edge case {name} has no separating implementation" 727 ); 728 } 729 }