From b9311b0bfc9391e8da2bb4fa7b52c8783034ee22 Mon Sep 17 00:00:00 2001 From: Daniel Lyubomirov <daniel.lyubomirov@vereign.com> Date: Fri, 10 Jul 2020 16:55:00 +0300 Subject: [PATCH] Use crypto random generator for certificate serial numbers --- cpp/src/vereign/crypto/cert.cc | 6 ++---- cpp/src/vereign/crypto/rand.cc | 11 +++++++++++ cpp/src/vereign/crypto/rand.hh | 9 +++++++++ 3 files changed, 22 insertions(+), 4 deletions(-) diff --git a/cpp/src/vereign/crypto/cert.cc b/cpp/src/vereign/crypto/cert.cc index a715c17..bc6f84d 100644 --- a/cpp/src/vereign/crypto/cert.cc +++ b/cpp/src/vereign/crypto/cert.cc @@ -2,6 +2,7 @@ #include <vereign/crypto/bio.hh> #include <vereign/crypto/errors.hh> +#include <vereign/crypto/rand.hh> #include <vereign/encoding/base64.hh> #include <openssl/x509v3.h> @@ -333,10 +334,7 @@ static auto createCert( // set serial number auto serial_number = cert_data.SerialNumber; if (serial_number == 0) { - // FIXME: is using time ok ? - serial_number = std::chrono::duration_cast<std::chrono::milliseconds>( - std::chrono::system_clock::now().time_since_epoch() - ).count(); + serial_number = crypto::RandUint64(); } r = ASN1_INTEGER_set_uint64(X509_get_serialNumber(cert.get()), serial_number); if (r != 1) { diff --git a/cpp/src/vereign/crypto/rand.cc b/cpp/src/vereign/crypto/rand.cc index 2acc168..f612748 100644 --- a/cpp/src/vereign/crypto/rand.cc +++ b/cpp/src/vereign/crypto/rand.cc @@ -23,4 +23,15 @@ auto Rand(std::size_t size) -> bytes::Buffer { return buf; } +auto RandUint64() -> uint64_t { + uint64_t x = 0; + int result = RAND_bytes((uint8_t*) &x, sizeof(x)); + if (result == 0) { + ERR_clear_error(); + throw Error("crypto rand failed"); + } + + return x; +} + } // vereign::crypto diff --git a/cpp/src/vereign/crypto/rand.hh b/cpp/src/vereign/crypto/rand.hh index 4c39799..e377ac8 100644 --- a/cpp/src/vereign/crypto/rand.hh +++ b/cpp/src/vereign/crypto/rand.hh @@ -43,6 +43,15 @@ void Rand(bytes::Buffer& buf, std::size_t size); */ auto Rand(std::size_t size) -> bytes::Buffer; +/** + * Generates random uint64_t. + * + * @returns random unsigned 64 bit integer. + * + * @throws crypto::Error on failure. + */ +auto RandUint64() -> uint64_t; + } // vereign::crypto #endif // __VEREIGN_CRYPTO_RAND_HH -- GitLab