Random.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  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. use phpseclib\Crypt\AES;
  25. use phpseclib\Crypt\Base;
  26. use phpseclib\Crypt\Blowfish;
  27. use phpseclib\Crypt\DES;
  28. use phpseclib\Crypt\RC4;
  29. use phpseclib\Crypt\TripleDES;
  30. use phpseclib\Crypt\Twofish;
  31. /**
  32. * Pure-PHP Random Number Generator
  33. *
  34. * @package Random
  35. * @author Jim Wigginton <terrafrost@php.net>
  36. * @access public
  37. */
  38. class Random
  39. {
  40. /**
  41. * Generate a random string.
  42. *
  43. * Although microoptimizations are generally discouraged as they impair readability this function is ripe with
  44. * microoptimizations because this function has the potential of being called a huge number of times.
  45. * eg. for RSA key generation.
  46. *
  47. * @param int $length
  48. * @return string
  49. */
  50. static function string($length)
  51. {
  52. if (version_compare(PHP_VERSION, '7.0.0', '>=')) {
  53. try {
  54. return \random_bytes($length);
  55. } catch (\Throwable $e) {
  56. // If a sufficient source of randomness is unavailable, random_bytes() will throw an
  57. // object that implements the Throwable interface (Exception, TypeError, Error).
  58. // We don't actually need to do anything here. The string() method should just continue
  59. // as normal. Note, however, that if we don't have a sufficient source of randomness for
  60. // random_bytes(), most of the other calls here will fail too, so we'll end up using
  61. // the PHP implementation.
  62. }
  63. }
  64. if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
  65. // method 1. prior to PHP 5.3 this would call rand() on windows hence the function_exists('class_alias') call.
  66. // ie. class_alias is a function that was introduced in PHP 5.3
  67. if (extension_loaded('mcrypt') && function_exists('class_alias')) {
  68. return mcrypt_create_iv($length);
  69. }
  70. // method 2. openssl_random_pseudo_bytes was introduced in PHP 5.3.0 but prior to PHP 5.3.4 there was,
  71. // to quote <http://php.net/ChangeLog-5.php#5.3.4>, "possible blocking behavior". as of 5.3.4
  72. // openssl_random_pseudo_bytes and mcrypt_create_iv do the exact same thing on Windows. ie. they both
  73. // call php_win32_get_random_bytes():
  74. //
  75. // https://github.com/php/php-src/blob/7014a0eb6d1611151a286c0ff4f2238f92c120d6/ext/openssl/openssl.c#L5008
  76. // https://github.com/php/php-src/blob/7014a0eb6d1611151a286c0ff4f2238f92c120d6/ext/mcrypt/mcrypt.c#L1392
  77. //
  78. // php_win32_get_random_bytes() is defined thusly:
  79. //
  80. // https://github.com/php/php-src/blob/7014a0eb6d1611151a286c0ff4f2238f92c120d6/win32/winutil.c#L80
  81. //
  82. // we're calling it, all the same, in the off chance that the mcrypt extension is not available
  83. if (extension_loaded('openssl') && version_compare(PHP_VERSION, '5.3.4', '>=')) {
  84. return openssl_random_pseudo_bytes($length);
  85. }
  86. } else {
  87. // method 1. the fastest
  88. if (extension_loaded('openssl')) {
  89. return openssl_random_pseudo_bytes($length);
  90. }
  91. // method 2
  92. static $fp = true;
  93. if ($fp === true) {
  94. // warning's will be output unles the error suppression operator is used. errors such as
  95. // "open_basedir restriction in effect", "Permission denied", "No such file or directory", etc.
  96. $fp = @fopen('/dev/urandom', 'rb');
  97. }
  98. if ($fp !== true && $fp !== false) { // surprisingly faster than !is_bool() or is_resource()
  99. return fread($fp, $length);
  100. }
  101. // method 3. pretty much does the same thing as method 2 per the following url:
  102. // https://github.com/php/php-src/blob/7014a0eb6d1611151a286c0ff4f2238f92c120d6/ext/mcrypt/mcrypt.c#L1391
  103. // surprisingly slower than method 2. maybe that's because mcrypt_create_iv does a bunch of error checking that we're
  104. // not doing. regardless, this'll only be called if this PHP script couldn't open /dev/urandom due to open_basedir
  105. // restrictions or some such
  106. if (extension_loaded('mcrypt')) {
  107. return mcrypt_create_iv($length, MCRYPT_DEV_URANDOM);
  108. }
  109. }
  110. // at this point we have no choice but to use a pure-PHP CSPRNG
  111. // cascade entropy across multiple PHP instances by fixing the session and collecting all
  112. // environmental variables, including the previous session data and the current session
  113. // data.
  114. //
  115. // mt_rand seeds itself by looking at the PID and the time, both of which are (relatively)
  116. // easy to guess at. linux uses mouse clicks, keyboard timings, etc, as entropy sources, but
  117. // PHP isn't low level to be able to use those as sources and on a web server there's not likely
  118. // going to be a ton of keyboard or mouse action. web servers do have one thing that we can use
  119. // however, a ton of people visiting the website. obviously you don't want to base your seeding
  120. // soley on parameters a potential attacker sends but (1) not everything in $_SERVER is controlled
  121. // by the user and (2) this isn't just looking at the data sent by the current user - it's based
  122. // on the data sent by all users. one user requests the page and a hash of their info is saved.
  123. // another user visits the page and the serialization of their data is utilized along with the
  124. // server envirnment stuff and a hash of the previous http request data (which itself utilizes
  125. // a hash of the session data before that). certainly an attacker should be assumed to have
  126. // full control over his own http requests. he, however, is not going to have control over
  127. // everyone's http requests.
  128. static $crypto = false, $v;
  129. if ($crypto === false) {
  130. // save old session data
  131. $old_session_id = session_id();
  132. $old_use_cookies = ini_get('session.use_cookies');
  133. $old_session_cache_limiter = session_cache_limiter();
  134. $_OLD_SESSION = isset($_SESSION) ? $_SESSION : false;
  135. if ($old_session_id != '') {
  136. session_write_close();
  137. }
  138. session_id(1);
  139. ini_set('session.use_cookies', 0);
  140. session_cache_limiter('');
  141. session_start();
  142. $v = $seed = $_SESSION['seed'] = pack('H*', sha1(
  143. serialize($_SERVER) .
  144. serialize($_POST) .
  145. serialize($_GET) .
  146. serialize($_COOKIE) .
  147. serialize($GLOBALS) .
  148. serialize($_SESSION) .
  149. serialize($_OLD_SESSION)
  150. ));
  151. if (!isset($_SESSION['count'])) {
  152. $_SESSION['count'] = 0;
  153. }
  154. $_SESSION['count']++;
  155. session_write_close();
  156. // restore old session data
  157. if ($old_session_id != '') {
  158. session_id($old_session_id);
  159. session_start();
  160. ini_set('session.use_cookies', $old_use_cookies);
  161. session_cache_limiter($old_session_cache_limiter);
  162. } else {
  163. if ($_OLD_SESSION !== false) {
  164. $_SESSION = $_OLD_SESSION;
  165. unset($_OLD_SESSION);
  166. } else {
  167. unset($_SESSION);
  168. }
  169. }
  170. // in SSH2 a shared secret and an exchange hash are generated through the key exchange process.
  171. // 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.
  172. // if the hash doesn't produce enough a key or an IV that's long enough concat successive hashes of the
  173. // original hash and the current hash. we'll be emulating that. for more info see the following URL:
  174. //
  175. // http://tools.ietf.org/html/rfc4253#section-7.2
  176. //
  177. // see the is_string($crypto) part for an example of how to expand the keys
  178. $key = pack('H*', sha1($seed . 'A'));
  179. $iv = pack('H*', sha1($seed . 'C'));
  180. // ciphers are used as per the nist.gov link below. also, see this link:
  181. //
  182. // http://en.wikipedia.org/wiki/Cryptographically_secure_pseudorandom_number_generator#Designs_based_on_cryptographic_primitives
  183. switch (true) {
  184. case class_exists('\phpseclib\Crypt\AES'):
  185. $crypto = new AES(Base::MODE_CTR);
  186. break;
  187. case class_exists('\phpseclib\Crypt\Twofish'):
  188. $crypto = new Twofish(Base::MODE_CTR);
  189. break;
  190. case class_exists('\phpseclib\Crypt\Blowfish'):
  191. $crypto = new Blowfish(Base::MODE_CTR);
  192. break;
  193. case class_exists('\phpseclib\Crypt\TripleDES'):
  194. $crypto = new TripleDES(Base::MODE_CTR);
  195. break;
  196. case class_exists('\phpseclib\Crypt\DES'):
  197. $crypto = new DES(Base::MODE_CTR);
  198. break;
  199. case class_exists('\phpseclib\Crypt\RC4'):
  200. $crypto = new RC4();
  201. break;
  202. default:
  203. user_error(__CLASS__ . ' requires at least one symmetric cipher be loaded');
  204. return false;
  205. }
  206. $crypto->setKey($key);
  207. $crypto->setIV($iv);
  208. $crypto->enableContinuousBuffer();
  209. }
  210. //return $crypto->encrypt(str_repeat("\0", $length));
  211. // the following is based off of ANSI X9.31:
  212. //
  213. // http://csrc.nist.gov/groups/STM/cavp/documents/rng/931rngext.pdf
  214. //
  215. // OpenSSL uses that same standard for it's random numbers:
  216. //
  217. // http://www.opensource.apple.com/source/OpenSSL/OpenSSL-38/openssl/fips-1.0/rand/fips_rand.c
  218. // (do a search for "ANS X9.31 A.2.4")
  219. $result = '';
  220. while (strlen($result) < $length) {
  221. $i = $crypto->encrypt(microtime()); // strlen(microtime()) == 21
  222. $r = $crypto->encrypt($i ^ $v); // strlen($v) == 20
  223. $v = $crypto->encrypt($r ^ $i); // strlen($r) == 20
  224. $result.= $r;
  225. }
  226. return substr($result, 0, $length);
  227. }
  228. }