Random.php 9.3 KB

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