aboutsummaryrefslogtreecommitdiffstats
path: root/src/rng/hmac_rng/hmac_rng.cpp
blob: cc4e4f790ecfa56b78fedcf1b611dfc508a4720b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
/*************************************************
* HMAC_RNG Source File                           *
* (C) 2008 Jack Lloyd                            *
*************************************************/

#include <botan/hmac_rng.h>
#include <botan/entropy.h>
#include <botan/loadstor.h>
#include <botan/xor_buf.h>
#include <botan/util.h>
#include <botan/bit_ops.h>
#include <botan/stl_util.h>
#include <algorithm>

namespace Botan {

namespace {

void hmac_prf(MessageAuthenticationCode* prf,
            MemoryRegion<byte>& K,
            u32bit& counter,
            const std::string& label)
   {
   prf->update(K, K.size());
   prf->update(label);
   for(u32bit i = 0; i != 4; ++i)
      prf->update(get_byte(i, counter));
   prf->final(K);

   ++counter;
   }

}

/*************************************************
* Generate a buffer of random bytes              *
*************************************************/
void HMAC_RNG::randomize(byte out[], u32bit length)
   {
   // Attempt to seed if we are either unseeded or have generated
   // enouch counters that it seems wise to roll over keys
   if(!is_seeded() || counter >= 8192)
      {
      reseed();

      if(!is_seeded())
         throw PRNG_Unseeded(name() + " seeding attempt failed");
      }

   /*
    HMAC KDF as described in E-t-E, using a CTXinfo of "rng"
   */
   while(length)
      {
      hmac_prf(prf, K, counter, "rng");

      const u32bit copied = std::min(K.size(), length);

      copy_mem(out, K.begin(), copied);
      out += copied;
      length -= copied;
      }

   hmac_prf(prf, K, counter, "rng");
   }

/**
* Reseed the internal state, also accepting user input to include
*/
void HMAC_RNG::reseed_with_input(const byte input[], u32bit input_length)
   {
   Entropy_Estimator estimate;

   if(entropy_sources.size())
      {
      SecureVector<byte> buffer(128);

      /**
      Using the terminology of E-t-E, XTR is the MAC function (normally
      HMAC) seeded with XTS (below) and we form SKM, the key material, by
      fast polling each source, and then slow polling as many as we think
      we need (in the following loop), and feeding all of the poll
      results, along with any optional user input, along with, finally,
      feedback of the current PRK value, into the extractor function.
      */

      /*
      Use the first entropy source (which is normally a timer of some
      kind, producing an 8 byte output) as the new random key for the
      extractor.  This takes the function of XTS as described in "On
      Extract-then-Expand Key Derivation Functions and an HMAC-based KDF"
      by Hugo Krawczyk (henceforce, 'E-t-E')

      Set the extractor MAC key to this value: it's OK if the timer is
      guessable. Even if the timer remained constant for a particular
      machine, that is fine, as the only purpose is to parameterize the
      hash function. See Krawczyk's paper for details.
      */
      u32bit got = entropy_sources[0]->fast_poll(buffer, buffer.size());
      extractor->set_key(buffer, got);

      /*
      Fast poll all sources (except the first one, which we used to
      choose XTS, above)
      */

      for(u32bit j = 1; j < entropy_sources.size(); ++j)
         {
         u32bit got = entropy_sources[j]->fast_poll(buffer, buffer.size());

         extractor->update(buffer, got);
         estimate.update(buffer, got, 96);
         }

      /* Limit assumed entropy from fast polls (to ensure we do at
      least a few slow polls)
      */
      estimate.set_upper_bound(256);

      /* Then do a slow poll, until we think we have got enough entropy
      */
      for(u32bit j = 0; j != entropy_sources.size(); ++j)
         {
         u32bit got = entropy_sources[j]->slow_poll(buffer, buffer.size());

         extractor->update(buffer, got);
         estimate.update(buffer, got, 256);

         if(estimate.value() > 8 * extractor->OUTPUT_LENGTH)
            break;
         }
      }

   /*
   And now add the user-provided input, if any
   */
   if(input_length)
      {
      extractor->update(input, input_length);
      estimate.update(input, input_length);
      }

   /*
   It is necessary to feed forward poll data. Otherwise, a good
   poll (collecting a large amount of conditional entropy) followed
   by a bad one (collecting little) would be unsafe. Do this by
   generating new PRF outputs using the previous key and feeding them
   into the extractor function.

   Cycle the RNG once (CTXinfo="rng"), then generate a new PRF output
   using the CTXinfo "reseed". Provide these values as input to the
   extractor function.
   */
   hmac_prf(prf, K, counter, "rng");
   extractor->update(K); // K is the CTXinfo=rng PRF output

   hmac_prf(prf, K, counter, "reseed");
   extractor->update(K); // K is the CTXinfo=reseed PRF output

   /* Now derive the new PRK using everything that has been fed into the extractor,
      and set the PRF key to that
   */
   prf->set_key(extractor->final());

   // Reset state
   K.clear();
   counter = 0;

   // Increase entropy estimate (for is_seeded)
   entropy = std::min<u32bit>(entropy + estimate.value(),
                              8 * extractor->OUTPUT_LENGTH);
   }

/**
* Reseed the internal state
*/
void HMAC_RNG::reseed()
   {
   reseed_with_input(0, 0);
   }

/**
Add user-supplied entropy by reseeding and including this
input among the poll data
*/
void HMAC_RNG::add_entropy(const byte input[], u32bit length)
   {
   reseed_with_input(input, length);
   }

/*************************************************
* Add another entropy source to the list         *
*************************************************/
void HMAC_RNG::add_entropy_source(EntropySource* src)
   {
   entropy_sources.push_back(src);
   }

/*************************************************
* Check if the the pool is seeded                *
*************************************************/
bool HMAC_RNG::is_seeded() const
   {
   return (entropy >= 8 * prf->OUTPUT_LENGTH);
   }

 /*************************************************
* Clear memory of sensitive data                 *
*************************************************/
void HMAC_RNG::clear() throw()
   {
   extractor->clear();
   prf->clear();
   K.clear();
   entropy = 0;
   counter = 0;
   }

/*************************************************
* Return the name of this type                   *
*************************************************/
std::string HMAC_RNG::name() const
   {
   return "HMAC_RNG(" + extractor->name() + "," + prf->name() + ")";
   }

/*************************************************
* HMAC_RNG Constructor                           *
*************************************************/
HMAC_RNG::HMAC_RNG(MessageAuthenticationCode* extractor_mac,
                   MessageAuthenticationCode* prf_mac) :
   extractor(extractor_mac), prf(prf_mac)
   {
   entropy = 0;

   // First PRF inputs are all zero, as specified in section 2
   K.create(prf->OUTPUT_LENGTH);
   counter = 0;

   /*
   Normally we want to feedback PRF output into the input to the
   extractor function to ensure a single bad poll does not damage the
   RNG, but obviously that is meaningless to do on the first poll.

   We will want to use the PRF before we set the first key (in
   reseed_with_input), and it is a pain to keep track if it is set or
   not. Since the first time it doesn't matter anyway, just set it to
   a constant: randomize() will not produce output unless is_seeded()
   returns true, and that will only be the case if the estimated
   entropy counter is high enough. That variable is only set when a
   reseeding is performed.
   */
   std::string prf_key = "Botan HMAC_RNG PRF";
   prf->set_key(reinterpret_cast<const byte*>(prf_key.c_str()),
                prf_key.length());

   /*
   This will only be used as the XTS if no entropy source at all is
   enabled. Normally the first one included (typically a timer) is
   used to choose a new extractor salt each time reseeding is
   performed. However if no entropy sources at all are enabled,
   instead this fixed extractor key will be used.

   If I understand the E-t-E paper correctly (specifically Section 4),
   this is safe to do.
   */
   std::string xts = "Botan HMAC_RNG XTS";
   extractor->set_key(reinterpret_cast<const byte*>(xts.c_str()),
                      xts.length());
   }

/*************************************************
* HMAC_RNG Destructor                            *
*************************************************/
HMAC_RNG::~HMAC_RNG()
   {
   delete extractor;
   delete prf;

   std::for_each(entropy_sources.begin(), entropy_sources.end(),
                 del_fun<EntropySource>());

   entropy = 0;
   counter = 0;
   }

}