Random.php 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  1. <?php
  2. /**
  3. * Random Number Generator
  4. *
  5. * PHP version 5
  6. *
  7. * Here's a short example of how to use this library:
  8. * <code>
  9. * <?php
  10. * include 'vendor/autoload.php';
  11. *
  12. * echo bin2hex(\phpseclib\Crypt\Random::string(8));
  13. * ?>
  14. * </code>
  15. *
  16. * @category Crypt
  17. * @package Random
  18. * @author Jim Wigginton <terrafrost@php.net>
  19. * @copyright 2007 Jim Wigginton
  20. * @license http://www.opensource.org/licenses/mit-license.html MIT License
  21. * @link http://phpseclib.sourceforge.net
  22. */
  23. namespace phpseclib\Crypt;
  24. /**
  25. * Pure-PHP Random Number Generator
  26. *
  27. * @package Random
  28. * @author Jim Wigginton <terrafrost@php.net>
  29. * @access public
  30. */
  31. class Random
  32. {
  33. /**
  34. * Generate a random string.
  35. *
  36. * Although microoptimizations are generally discouraged as they impair readability this function is ripe with
  37. * microoptimizations because this function has the potential of being called a huge number of times.
  38. * eg. for RSA key generation.
  39. *
  40. * @param int $length
  41. * @throws \RuntimeException if a symmetric cipher is needed but not loaded
  42. * @return string
  43. */
  44. static function string($length)
  45. {
  46. try {
  47. return \random_bytes($length);
  48. } catch (\Exception $e) {
  49. // random_compat will throw an Exception, which in PHP 5 does not implement Throwable
  50. } catch (\Throwable $e) {
  51. // If a sufficient source of randomness is unavailable, random_bytes() will throw an
  52. // object that implements the Throwable interface (Exception, TypeError, Error).
  53. // We don't actually need to do anything here. The string() method should just continue
  54. // as normal. Note, however, that if we don't have a sufficient source of randomness for
  55. // random_bytes(), most of the other calls here will fail too, so we'll end up using
  56. // the PHP implementation.
  57. }
  58. // at this point we have no choice but to use a pure-PHP CSPRNG
  59. // cascade entropy across multiple PHP instances by fixing the session and collecting all
  60. // environmental variables, including the previous session data and the current session
  61. // data.
  62. //
  63. // mt_rand seeds itself by looking at the PID and the time, both of which are (relatively)
  64. // easy to guess at. linux uses mouse clicks, keyboard timings, etc, as entropy sources, but
  65. // PHP isn't low level to be able to use those as sources and on a web server there's not likely
  66. // going to be a ton of keyboard or mouse action. web servers do have one thing that we can use
  67. // however, a ton of people visiting the website. obviously you don't want to base your seeding
  68. // soley on parameters a potential attacker sends but (1) not everything in $_SERVER is controlled
  69. // by the user and (2) this isn't just looking at the data sent by the current user - it's based
  70. // on the data sent by all users. one user requests the page and a hash of their info is saved.
  71. // another user visits the page and the serialization of their data is utilized along with the
  72. // server envirnment stuff and a hash of the previous http request data (which itself utilizes
  73. // a hash of the session data before that). certainly an attacker should be assumed to have
  74. // full control over his own http requests. he, however, is not going to have control over
  75. // everyone's http requests.
  76. static $crypto = false, $v;
  77. if ($crypto === false) {
  78. // save old session data
  79. $old_session_id = session_id();
  80. $old_use_cookies = ini_get('session.use_cookies');
  81. $old_session_cache_limiter = session_cache_limiter();
  82. $_OLD_SESSION = isset($_SESSION) ? $_SESSION : false;
  83. if ($old_session_id != '') {
  84. session_write_close();
  85. }
  86. session_id(1);
  87. ini_set('session.use_cookies', 0);
  88. session_cache_limiter('');
  89. session_start();
  90. $v = (isset($_SERVER) ? self::safe_serialize($_SERVER) : '') .
  91. (isset($_POST) ? self::safe_serialize($_POST) : '') .
  92. (isset($_GET) ? self::safe_serialize($_GET) : '') .
  93. (isset($_COOKIE) ? self::safe_serialize($_COOKIE) : '') .
  94. self::safe_serialize($GLOBALS) .
  95. self::safe_serialize($_SESSION) .
  96. self::safe_serialize($_OLD_SESSION);
  97. $v = $seed = $_SESSION['seed'] = sha1($v, true);
  98. if (!isset($_SESSION['count'])) {
  99. $_SESSION['count'] = 0;
  100. }
  101. $_SESSION['count']++;
  102. session_write_close();
  103. // restore old session data
  104. if ($old_session_id != '') {
  105. session_id($old_session_id);
  106. session_start();
  107. ini_set('session.use_cookies', $old_use_cookies);
  108. session_cache_limiter($old_session_cache_limiter);
  109. } else {
  110. if ($_OLD_SESSION !== false) {
  111. $_SESSION = $_OLD_SESSION;
  112. unset($_OLD_SESSION);
  113. } else {
  114. unset($_SESSION);
  115. }
  116. }
  117. // in SSH2 a shared secret and an exchange hash are generated through the key exchange process.
  118. // the IV client to server is the hash of that "nonce" with the letter A and for the encryption key it's the letter C.
  119. // if the hash doesn't produce enough a key or an IV that's long enough concat successive hashes of the
  120. // original hash and the current hash. we'll be emulating that. for more info see the following URL:
  121. //
  122. // http://tools.ietf.org/html/rfc4253#section-7.2
  123. //
  124. // see the is_string($crypto) part for an example of how to expand the keys
  125. $key = sha1($seed . 'A', true);
  126. $iv = sha1($seed . 'C', true);
  127. // ciphers are used as per the nist.gov link below. also, see this link:
  128. //
  129. // http://en.wikipedia.org/wiki/Cryptographically_secure_pseudorandom_number_generator#Designs_based_on_cryptographic_primitives
  130. switch (true) {
  131. case class_exists('\phpseclib\Crypt\AES'):
  132. $crypto = new AES(Base::MODE_CTR);
  133. break;
  134. case class_exists('\phpseclib\Crypt\Twofish'):
  135. $crypto = new Twofish(Base::MODE_CTR);
  136. break;
  137. case class_exists('\phpseclib\Crypt\Blowfish'):
  138. $crypto = new Blowfish(Base::MODE_CTR);
  139. break;
  140. case class_exists('\phpseclib\Crypt\TripleDES'):
  141. $crypto = new TripleDES(Base::MODE_CTR);
  142. break;
  143. case class_exists('\phpseclib\Crypt\DES'):
  144. $crypto = new DES(Base::MODE_CTR);
  145. break;
  146. case class_exists('\phpseclib\Crypt\RC4'):
  147. $crypto = new RC4();
  148. break;
  149. default:
  150. throw new \RuntimeException(__CLASS__ . ' requires at least one symmetric cipher be loaded');
  151. }
  152. $crypto->setKey($key);
  153. $crypto->setIV($iv);
  154. $crypto->enableContinuousBuffer();
  155. }
  156. //return $crypto->encrypt(str_repeat("\0", $length));
  157. // the following is based off of ANSI X9.31:
  158. //
  159. // http://csrc.nist.gov/groups/STM/cavp/documents/rng/931rngext.pdf
  160. //
  161. // OpenSSL uses that same standard for it's random numbers:
  162. //
  163. // http://www.opensource.apple.com/source/OpenSSL/OpenSSL-38/openssl/fips-1.0/rand/fips_rand.c
  164. // (do a search for "ANS X9.31 A.2.4")
  165. $result = '';
  166. while (strlen($result) < $length) {
  167. $i = $crypto->encrypt(microtime()); // strlen(microtime()) == 21
  168. $r = $crypto->encrypt($i ^ $v); // strlen($v) == 20
  169. $v = $crypto->encrypt($r ^ $i); // strlen($r) == 20
  170. $result.= $r;
  171. }
  172. return substr($result, 0, $length);
  173. }
  174. /**
  175. * Safely serialize variables
  176. *
  177. * If a class has a private __sleep() it'll emit a warning
  178. *
  179. * @param mixed $arr
  180. * @access public
  181. */
  182. function safe_serialize(&$arr)
  183. {
  184. if (is_object($arr)) {
  185. return '';
  186. }
  187. if (!is_array($arr)) {
  188. return serialize($arr);
  189. }
  190. // prevent circular array recursion
  191. if (isset($arr['__phpseclib_marker'])) {
  192. return '';
  193. }
  194. $safearr = array();
  195. $arr['__phpseclib_marker'] = true;
  196. foreach (array_keys($arr) as $key) {
  197. // do not recurse on the '__phpseclib_marker' key itself, for smaller memory usage
  198. if ($key !== '__phpseclib_marker') {
  199. $safearr[$key] = self::safe_serialize($arr[$key]);
  200. }
  201. }
  202. unset($arr['__phpseclib_marker']);
  203. return serialize($safearr);
  204. }
  205. }