nt.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. #
  2. # Random/OSRNG/nt.py : OS entropy source for MS Windows
  3. #
  4. # Written in 2008 by Dwayne C. Litzenberger <dlitz@dlitz.net>
  5. #
  6. # ===================================================================
  7. # The contents of this file are dedicated to the public domain. To
  8. # the extent that dedication to the public domain is not available,
  9. # everyone is granted a worldwide, perpetual, royalty-free,
  10. # non-exclusive license to exercise all rights associated with the
  11. # contents of this file for any purpose whatsoever.
  12. # No rights are reserved.
  13. #
  14. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  15. # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  16. # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  17. # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
  18. # BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
  19. # ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  20. # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  21. # SOFTWARE.
  22. # ===================================================================
  23. __revision__ = "$Id$"
  24. __all__ = ['WindowsRNG']
  25. import winrandom
  26. from rng_base import BaseRNG
  27. class WindowsRNG(BaseRNG):
  28. name = "<CryptGenRandom>"
  29. def __init__(self):
  30. self.__winrand = winrandom.new()
  31. BaseRNG.__init__(self)
  32. def flush(self):
  33. """Work around weakness in Windows RNG.
  34. The CryptGenRandom mechanism in some versions of Windows allows an
  35. attacker to learn 128 KiB of past and future output. As a workaround,
  36. this function reads 128 KiB of 'random' data from Windows and discards
  37. it.
  38. For more information about the weaknesses in CryptGenRandom, see
  39. _Cryptanalysis of the Random Number Generator of the Windows Operating
  40. System_, by Leo Dorrendorf and Zvi Gutterman and Benny Pinkas
  41. http://eprint.iacr.org/2007/419
  42. """
  43. if self.closed:
  44. raise ValueError("I/O operation on closed file")
  45. data = self.__winrand.get_bytes(128*1024)
  46. assert (len(data) == 128*1024)
  47. BaseRNG.flush(self)
  48. def _close(self):
  49. self.__winrand = None
  50. def _read(self, N):
  51. # Unfortunately, research shows that CryptGenRandom doesn't provide
  52. # forward secrecy and fails the next-bit test unless we apply a
  53. # workaround, which we do here. See http://eprint.iacr.org/2007/419
  54. # for information on the vulnerability.
  55. self.flush()
  56. data = self.__winrand.get_bytes(N)
  57. self.flush()
  58. return data
  59. def new(*args, **kwargs):
  60. return WindowsRNG(*args, **kwargs)
  61. # vim:set ts=4 sw=4 sts=4 expandtab: