xref: /openbmc/bmcweb/src/ossl_random.cpp (revision 40e9b92ec19acffb46f83a6e55b18974da5d708e)
1 // SPDX-License-Identifier: Apache-2.0
2 // SPDX-FileCopyrightText: Copyright OpenBMC Authors
3 #include "ossl_random.hpp"
4 
5 #include "logging.hpp"
6 
7 #include <cstddef>
8 #include <cstdint>
9 #include <string_view>
10 
11 extern "C"
12 {
13 #include <openssl/crypto.h>
14 #include <openssl/rand.h>
15 }
16 
17 #include <boost/uuid/basic_random_generator.hpp>
18 #include <boost/uuid/uuid_io.hpp>
19 
20 #include <array>
21 #include <random>
22 #include <string>
23 
24 namespace bmcweb
25 {
operator ()()26 uint8_t OpenSSLGenerator::operator()()
27 {
28     uint8_t index = 0;
29     int rc = RAND_bytes(&index, sizeof(index));
30     if (rc != opensslSuccess)
31     {
32         BMCWEB_LOG_ERROR("Cannot get random number");
33         err = true;
34     }
35 
36     return index;
37 }
38 
getRandomUUID()39 std::string getRandomUUID()
40 {
41     using bmcweb::OpenSSLGenerator;
42     OpenSSLGenerator ossl;
43     return boost::uuids::to_string(
44         boost::uuids::basic_random_generator<OpenSSLGenerator>(ossl)());
45 }
46 
getRandomIdOfLength(size_t length)47 std::string getRandomIdOfLength(size_t length)
48 {
49     static constexpr std::array<char, 62> alphanum = {
50         '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C',
51         'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
52         'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c',
53         'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p',
54         'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
55 
56     std::string token;
57     token.resize(length, '0');
58     std::uniform_int_distribution<size_t> dist(0, alphanum.size() - 1);
59 
60     bmcweb::OpenSSLGenerator gen;
61 
62     for (char& tokenChar : token)
63     {
64         tokenChar = alphanum[dist(gen)];
65         if (gen.error())
66         {
67             return "";
68         }
69     }
70     return token;
71 }
72 
constantTimeStringCompare(std::string_view a,std::string_view b)73 bool constantTimeStringCompare(std::string_view a, std::string_view b)
74 {
75     // Important note, this function is ONLY constant time if the two input
76     // sizes are the same
77     if (a.size() != b.size())
78     {
79         return false;
80     }
81     return CRYPTO_memcmp(a.data(), b.data(), a.size()) == 0;
82 }
83 
operator ()(std::string_view a,std::string_view b) const84 bool ConstantTimeCompare::operator()(std::string_view a,
85                                      std::string_view b) const
86 {
87     return constantTimeStringCompare(a, b);
88 }
89 
90 } // namespace bmcweb
91