Network: De-duplicate getting random bytes with fallback

This commit is contained in:
Jonathan G Rennison
2023-06-14 22:18:21 +01:00
parent b18d3c9603
commit 76a9e280c2
3 changed files with 18 additions and 14 deletions

View File

@@ -1315,15 +1315,9 @@ static void NetworkGenerateServerId()
std::string NetworkGenerateRandomKeyString(uint bytes) std::string NetworkGenerateRandomKeyString(uint bytes)
{ {
uint8 *key = AllocaM(uint8, bytes); uint8 *key = AllocaM(uint8, bytes);
char *hex_output = AllocaM(char, bytes * 2); NetworkRandomBytesWithFallback(key, bytes);
if (randombytes(key, bytes) < 0) { char *hex_output = AllocaM(char, bytes * 2);
/* Fallback poor-quality random */
DEBUG(misc, 0, "High quality random source unavailable");
for (uint i = 0; i < bytes; i++) {
key[i] = (uint8)InteractiveRandom();
}
}
char txt[3]; char txt[3];
for (uint i = 0; i < bytes; ++i) { for (uint i = 0; i < bytes; ++i) {
@@ -1401,6 +1395,17 @@ void NetworkShutDown()
NetworkCoreShutdown(); NetworkCoreShutdown();
} }
void NetworkRandomBytesWithFallback(void *buf, size_t bytes)
{
if (randombytes(buf, bytes) < 0) {
/* Fallback poor-quality random */
DEBUG(net, 0, "High quality random source unavailable");
for (uint i = 0; i < bytes; i++) {
reinterpret_cast<byte *>(buf)[i] = (byte)InteractiveRandom();
}
}
}
#ifdef __EMSCRIPTEN__ #ifdef __EMSCRIPTEN__
extern "C" { extern "C" {

View File

@@ -156,4 +156,6 @@ std::string NormalizeConnectionString(const std::string &connection_string, uint
void ClientNetworkEmergencySave(); void ClientNetworkEmergencySave();
void NetworkRandomBytesWithFallback(void *buf, size_t n);
#endif /* NETWORK_INTERNAL_H */ #endif /* NETWORK_INTERNAL_H */

View File

@@ -214,12 +214,9 @@ ServerNetworkGameSocketHandler::ServerNetworkGameSocketHandler(SOCKET s) : Netwo
this->receive_limit = _settings_client.network.bytes_per_frame_burst; this->receive_limit = _settings_client.network.bytes_per_frame_burst;
uint64 seeds[3]; uint64 seeds[3];
if (randombytes(&seeds, sizeof(uint64) * lengthof(seeds)) < 0) { static_assert(sizeof(seeds) == 24);
/* Can't get random data, use InteractiveRandom */ NetworkRandomBytesWithFallback(seeds, sizeof(seeds));
for (uint64 &seed : seeds) {
seed = (uint64)(InteractiveRandom()) | (((uint64)(InteractiveRandom())) << 32);
}
}
this->server_hash_bits = seeds[0]; this->server_hash_bits = seeds[0];
this->rcon_hash_bits = seeds[1]; this->rcon_hash_bits = seeds[1];
this->settings_hash_bits = seeds[2]; this->settings_hash_bits = seeds[2];