FortunaAccumulator.py 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  1. # -*- coding: ascii -*-
  2. #
  3. # FortunaAccumulator.py : Fortuna's internal accumulator
  4. #
  5. # Written in 2008 by Dwayne C. Litzenberger <dlitz@dlitz.net>
  6. #
  7. # ===================================================================
  8. # The contents of this file are dedicated to the public domain. To
  9. # the extent that dedication to the public domain is not available,
  10. # everyone is granted a worldwide, perpetual, royalty-free,
  11. # non-exclusive license to exercise all rights associated with the
  12. # contents of this file for any purpose whatsoever.
  13. # No rights are reserved.
  14. #
  15. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  16. # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  17. # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  18. # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
  19. # BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
  20. # ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  21. # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  22. # SOFTWARE.
  23. # ===================================================================
  24. __revision__ = "$Id$"
  25. import sys
  26. if sys.version_info[0] == 2 and sys.version_info[1] == 1:
  27. from Crypto.Util.py21compat import *
  28. from Crypto.Util.py3compat import *
  29. from binascii import b2a_hex
  30. import time
  31. import warnings
  32. from Crypto.pct_warnings import ClockRewindWarning
  33. import SHAd256
  34. import FortunaGenerator
  35. class FortunaPool(object):
  36. """Fortuna pool type
  37. This object acts like a hash object, with the following differences:
  38. - It keeps a count (the .length attribute) of the number of bytes that
  39. have been added to the pool
  40. - It supports a .reset() method for in-place reinitialization
  41. - The method to add bytes to the pool is .append(), not .update().
  42. """
  43. digest_size = SHAd256.digest_size
  44. def __init__(self):
  45. self.reset()
  46. def append(self, data):
  47. self._h.update(data)
  48. self.length += len(data)
  49. def digest(self):
  50. return self._h.digest()
  51. def hexdigest(self):
  52. if sys.version_info[0] == 2:
  53. return b2a_hex(self.digest())
  54. else:
  55. return b2a_hex(self.digest()).decode()
  56. def reset(self):
  57. self._h = SHAd256.new()
  58. self.length = 0
  59. def which_pools(r):
  60. """Return a list of pools indexes (in range(32)) that are to be included during reseed number r.
  61. According to _Practical Cryptography_, chapter 10.5.2 "Pools":
  62. "Pool P_i is included if 2**i is a divisor of r. Thus P_0 is used
  63. every reseed, P_1 every other reseed, P_2 every fourth reseed, etc."
  64. """
  65. # This is a separate function so that it can be unit-tested.
  66. assert r >= 1
  67. retval = []
  68. mask = 0
  69. for i in range(32):
  70. # "Pool P_i is included if 2**i is a divisor of [reseed_count]"
  71. if (r & mask) == 0:
  72. retval.append(i)
  73. else:
  74. break # optimization. once this fails, it always fails
  75. mask = (mask << 1) | 1L
  76. return retval
  77. class FortunaAccumulator(object):
  78. # An estimate of how many bytes we must append to pool 0 before it will
  79. # contain 128 bits of entropy (with respect to an attack). We reseed the
  80. # generator only after pool 0 contains `min_pool_size` bytes. Note that
  81. # unlike with some other PRNGs, Fortuna's security does not rely on the
  82. # accuracy of this estimate---we can accord to be optimistic here.
  83. min_pool_size = 64 # size in bytes
  84. # If an attacker can predict some (but not all) of our entropy sources, the
  85. # `min_pool_size` check may not be sufficient to prevent a successful state
  86. # compromise extension attack. To resist this attack, Fortuna spreads the
  87. # input across 32 pools, which are then consumed (to reseed the output
  88. # generator) with exponentially decreasing frequency.
  89. #
  90. # In order to prevent an attacker from gaining knowledge of all 32 pools
  91. # before we have a chance to fill them with enough information that the
  92. # attacker cannot predict, we impose a rate limit of 10 reseeds/second (one
  93. # per 100 ms). This ensures that a hypothetical 33rd pool would only be
  94. # needed after a minimum of 13 years of sustained attack.
  95. reseed_interval = 0.100 # time in seconds
  96. def __init__(self):
  97. self.reseed_count = 0
  98. self.generator = FortunaGenerator.AESGenerator()
  99. self.last_reseed = None
  100. # Initialize 32 FortunaPool instances.
  101. # NB: This is _not_ equivalent to [FortunaPool()]*32, which would give
  102. # us 32 references to the _same_ FortunaPool instance (and cause the
  103. # assertion below to fail).
  104. self.pools = [FortunaPool() for i in range(32)] # 32 pools
  105. assert(self.pools[0] is not self.pools[1])
  106. def _forget_last_reseed(self):
  107. # This is not part of the standard Fortuna definition, and using this
  108. # function frequently can weaken Fortuna's ability to resist a state
  109. # compromise extension attack, but we need this in order to properly
  110. # implement Crypto.Random.atfork(). Otherwise, forked child processes
  111. # might continue to use their parent's PRNG state for up to 100ms in
  112. # some cases. (e.g. CVE-2013-1445)
  113. self.last_reseed = None
  114. def random_data(self, bytes):
  115. current_time = time.time()
  116. if (self.last_reseed is not None and self.last_reseed > current_time): # Avoid float comparison to None to make Py3k happy
  117. warnings.warn("Clock rewind detected. Resetting last_reseed.", ClockRewindWarning)
  118. self.last_reseed = None
  119. if (self.pools[0].length >= self.min_pool_size and
  120. (self.last_reseed is None or
  121. current_time > self.last_reseed + self.reseed_interval)):
  122. self._reseed(current_time)
  123. # The following should fail if we haven't seeded the pool yet.
  124. return self.generator.pseudo_random_data(bytes)
  125. def _reseed(self, current_time=None):
  126. if current_time is None:
  127. current_time = time.time()
  128. seed = []
  129. self.reseed_count += 1
  130. self.last_reseed = current_time
  131. for i in which_pools(self.reseed_count):
  132. seed.append(self.pools[i].digest())
  133. self.pools[i].reset()
  134. seed = b("").join(seed)
  135. self.generator.reseed(seed)
  136. def add_random_event(self, source_number, pool_number, data):
  137. assert 1 <= len(data) <= 32
  138. assert 0 <= source_number <= 255
  139. assert 0 <= pool_number <= 31
  140. self.pools[pool_number].append(bchr(source_number))
  141. self.pools[pool_number].append(bchr(len(data)))
  142. self.pools[pool_number].append(data)
  143. # vim:set ts=4 sw=4 sts=4 expandtab: