Common: Add Random utilities

This makes it easier to generate random numbers or fill a buffer with
random data in a cryptographically secure way.

This also replaces existing usages of RNG functions in the codebase:

* <random> is pretty hard to use correctly, and std::random_device does
  not give enough guarantees about its results (it's
  implementation-defined, non cryptographically secure and could be
  deterministic on some platforms).
  Doing things correctly is error prone and verbose.

* rand() is terrible and should not be used especially in crypto code.
This commit is contained in:
Léo Lam 2018-05-21 15:48:17 +02:00
parent dd77ace56a
commit fff1db9730
10 changed files with 91 additions and 71 deletions

View file

@ -4,22 +4,12 @@
#include <cstddef>
#include <cstring>
#include <random>
#include <string>
#include "Common/CommonTypes.h"
#include "Common/Logging/Log.h"
#include "Common/MsgHandler.h"
static void GetRandomishBytes(u8* buf, size_t size)
{
// We don't need high quality random numbers (which might not be available),
// just non-repeating numbers!
static std::mt19937 prng(enet_time_get());
static std::uniform_int_distribution<unsigned int> u8_distribution(0, 255);
for (size_t i = 0; i < size; i++)
buf[i] = u8_distribution(prng);
}
#include "Common/Random.h"
TraversalClient::TraversalClient(ENetHost* netHost, const std::string& server, const u16 port)
: m_NetHost(netHost), m_Server(server), m_port(port)
@ -280,7 +270,7 @@ TraversalRequestId TraversalClient::SendTraversalPacket(const TraversalPacket& p
{
OutgoingTraversalPacketInfo info;
info.packet = packet;
GetRandomishBytes((u8*)&info.packet.requestId, sizeof(info.packet.requestId));
Common::Random::Generate(&info.packet.requestId, sizeof(info.packet.requestId));
info.tries = 0;
m_OutgoingTraversalPackets.push_back(info);
ResendPacket(&m_OutgoingTraversalPackets.back());