Make OpenSSL use DeterministicRandom as RNG source such that simulation runs stay deterministic w/ e.g. signature ops
| 379 | |
| 380 | // Make OpenSSL use DeterministicRandom as RNG source such that simulation runs stay deterministic w/ e.g. signature ops |
| 381 | void bindDeterministicRandomToOpenssl() { |
| 382 | // TODO: implement ifdef branch for 3.x using provider API |
| 383 | #ifndef OPENSSL_IS_BORINGSSL |
| 384 | static const RAND_METHOD method = { |
| 385 | // replacement for RAND_seed(), which reseeds OpenSSL RNG |
| 386 | [](const void*, int) -> int { return 1; }, |
| 387 | // replacement for RAND_bytes(), which fills given buffer with random byte sequence |
| 388 | [](unsigned char* buf, int length) -> int { |
| 389 | if (g_network) |
| 390 | ASSERT_ABORT(g_network->isSimulated()); |
| 391 | deterministicRandom()->randomBytes(buf, length); |
| 392 | return 1; |
| 393 | }, |
| 394 | // replacement for RAND_cleanup(), a no-op for simulation |
| 395 | []() -> void {}, |
| 396 | // replacement for RAND_add(), which reseeds OpenSSL RNG with randomness hint |
| 397 | [](const void*, int, double) -> int { return 1; }, |
| 398 | // replacement for default pseudobytes getter (same as RAND_bytes by default) |
| 399 | [](unsigned char* buf, int length) -> int { |
| 400 | if (g_network) |
| 401 | ASSERT_ABORT(g_network->isSimulated()); |
| 402 | deterministicRandom()->randomBytes(buf, length); |
| 403 | return 1; |
| 404 | }, |
| 405 | // status function for PRNG readiness check |
| 406 | []() -> int { return 1; }, |
| 407 | }; |
| 408 | |
| 409 | if (1 != ::RAND_set_rand_method(&method)) { |
| 410 | auto ec = ::ERR_get_error(); |
| 411 | char msg[256]{ |
| 412 | 0, |
| 413 | }; |
| 414 | if (ec) { |
| 415 | ::ERR_error_string_n(ec, msg, sizeof(msg)); |
| 416 | } |
| 417 | fprintf(stderr, |
| 418 | "ERROR: Failed to bind DeterministicRandom to OpenSSL RNG\n" |
| 419 | " OpenSSL error message: '%s'\n", |
| 420 | msg); |
| 421 | throw internal_error(); |
| 422 | } else { |
| 423 | printf("DeterministicRandom successfully bound to OpenSSL RNG\n"); |
| 424 | } |
| 425 | #else // OPENSSL_IS_BORINGSSL |
| 426 | static const RAND_METHOD method = { |
| 427 | [](const void*, int) -> void {}, |
| 428 | [](unsigned char* buf, unsigned long length) -> int { |
| 429 | if (g_network) |
| 430 | ASSERT_ABORT(g_network->isSimulated()); |
| 431 | ASSERT(length <= std::numeric_limits<int>::max()); |
| 432 | deterministicRandom()->randomBytes(buf, length); |
| 433 | return 1; |
| 434 | }, |
| 435 | []() -> void {}, |
| 436 | [](const void*, int, double) -> void {}, |
| 437 | [](unsigned char* buf, unsigned long length) -> int { |
| 438 | if (g_network) |
no test coverage detected