Random.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. <?php
  2. /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
  3. /**
  4. * Random Number Generator
  5. *
  6. * PHP versions 4 and 5
  7. *
  8. * Here's a short example of how to use this library:
  9. * <code>
  10. * <?php
  11. * include('Crypt/Random.php');
  12. *
  13. * echo bin2hex(crypt_random_string(8));
  14. * ?>
  15. * </code>
  16. *
  17. * LICENSE: Permission is hereby granted, free of charge, to any person obtaining a copy
  18. * of this software and associated documentation files (the "Software"), to deal
  19. * in the Software without restriction, including without limitation the rights
  20. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  21. * copies of the Software, and to permit persons to whom the Software is
  22. * furnished to do so, subject to the following conditions:
  23. *
  24. * The above copyright notice and this permission notice shall be included in
  25. * all copies or substantial portions of the Software.
  26. *
  27. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  28. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  29. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  30. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  31. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  32. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  33. * THE SOFTWARE.
  34. *
  35. * @category Crypt
  36. * @package Crypt_Random
  37. * @author Jim Wigginton <terrafrost@php.net>
  38. * @copyright MMVII Jim Wigginton
  39. * @license http://www.opensource.org/licenses/mit-license.html MIT License
  40. * @link http://phpseclib.sourceforge.net
  41. */
  42. /**
  43. * "Is Windows" test
  44. *
  45. * @access private
  46. */
  47. define('CRYPT_RANDOM_IS_WINDOWS', strtoupper(substr(PHP_OS, 0, 3)) === 'WIN');
  48. /**
  49. * Generate a random string.
  50. *
  51. * Although microoptimizations are generally discouraged as they impair readability this function is ripe with
  52. * microoptimizations because this function has the potential of being called a huge number of times.
  53. * eg. for RSA key generation.
  54. *
  55. * @param Integer $length
  56. * @return String
  57. * @access public
  58. */
  59. function crypt_random_string($length)
  60. {
  61. if (CRYPT_RANDOM_IS_WINDOWS) {
  62. // method 1. prior to PHP 5.3 this would call rand() on windows hence the function_exists('class_alias') call.
  63. // ie. class_alias is a function that was introduced in PHP 5.3
  64. if (function_exists('mcrypt_create_iv') && function_exists('class_alias')) {
  65. return mcrypt_create_iv($length);
  66. }
  67. // method 2. openssl_random_pseudo_bytes was introduced in PHP 5.3.0 but prior to PHP 5.3.4 there was,
  68. // to quote <http://php.net/ChangeLog-5.php#5.3.4>, "possible blocking behavior". as of 5.3.4
  69. // openssl_random_pseudo_bytes and mcrypt_create_iv do the exact same thing on Windows. ie. they both
  70. // call php_win32_get_random_bytes():
  71. //
  72. // https://github.com/php/php-src/blob/7014a0eb6d1611151a286c0ff4f2238f92c120d6/ext/openssl/openssl.c#L5008
  73. // https://github.com/php/php-src/blob/7014a0eb6d1611151a286c0ff4f2238f92c120d6/ext/mcrypt/mcrypt.c#L1392
  74. //
  75. // php_win32_get_random_bytes() is defined thusly:
  76. //
  77. // https://github.com/php/php-src/blob/7014a0eb6d1611151a286c0ff4f2238f92c120d6/win32/winutil.c#L80
  78. //
  79. // we're calling it, all the same, in the off chance that the mcrypt extension is not available
  80. if (function_exists('openssl_random_pseudo_bytes') && version_compare(PHP_VERSION, '5.3.4', '>=')) {
  81. return openssl_random_pseudo_bytes($length);
  82. }
  83. } else {
  84. // method 1. the fastest
  85. if (function_exists('openssl_random_pseudo_bytes')) {
  86. return openssl_random_pseudo_bytes($length);
  87. }
  88. // method 2
  89. static $fp = true;
  90. if ($fp === true) {
  91. // warning's will be output unles the error suppression operator is used. errors such as
  92. // "open_basedir restriction in effect", "Permission denied", "No such file or directory", etc.
  93. $fp = @fopen('/dev/urandom', 'rb');
  94. }
  95. if ($fp !== true && $fp !== false) { // surprisingly faster than !is_bool() or is_resource()
  96. return fread($fp, $length);
  97. }
  98. // method 3. pretty much does the same thing as method 2 per the following url:
  99. // https://github.com/php/php-src/blob/7014a0eb6d1611151a286c0ff4f2238f92c120d6/ext/mcrypt/mcrypt.c#L1391
  100. // surprisingly slower than method 2. maybe that's because mcrypt_create_iv does a bunch of error checking that we're
  101. // not doing. regardless, this'll only be called if this PHP script couldn't open /dev/urandom due to open_basedir
  102. // restrictions or some such
  103. if (function_exists('mcrypt_create_iv')) {
  104. return mcrypt_create_iv($length, MCRYPT_DEV_URANDOM);
  105. }
  106. }
  107. // at this point we have no choice but to use a pure-PHP CSPRNG
  108. // cascade entropy across multiple PHP instances by fixing the session and collecting all
  109. // environmental variables, including the previous session data and the current session
  110. // data.
  111. //
  112. // mt_rand seeds itself by looking at the PID and the time, both of which are (relatively)
  113. // easy to guess at. linux uses mouse clicks, keyboard timings, etc, as entropy sources, but
  114. // PHP isn't low level to be able to use those as sources and on a web server there's not likely
  115. // going to be a ton of keyboard or mouse action. web servers do have one thing that we can use
  116. // however. a ton of people visiting the website. obviously you don't want to base your seeding
  117. // soley on parameters a potential attacker sends but (1) not everything in $_SERVER is controlled
  118. // by the user and (2) this isn't just looking at the data sent by the current user - it's based
  119. // on the data sent by all users. one user requests the page and a hash of their info is saved.
  120. // another user visits the page and the serialization of their data is utilized along with the
  121. // server envirnment stuff and a hash of the previous http request data (which itself utilizes
  122. // a hash of the session data before that). certainly an attacker should be assumed to have
  123. // full control over his own http requests. he, however, is not going to have control over
  124. // everyone's http requests.
  125. static $crypto = false, $v;
  126. if ($crypto === false) {
  127. // save old session data
  128. $old_session_id = session_id();
  129. $old_use_cookies = ini_get('session.use_cookies');
  130. $old_session_cache_limiter = session_cache_limiter();
  131. if (isset($_SESSION)) {
  132. $_OLD_SESSION = $_SESSION;
  133. }
  134. if ($old_session_id != '') {
  135. session_write_close();
  136. }
  137. session_id(1);
  138. ini_set('session.use_cookies', 0);
  139. session_cache_limiter('');
  140. session_start();
  141. $v = $seed = $_SESSION['seed'] = pack('H*', sha1(
  142. serialize($_SERVER) .
  143. serialize($_POST) .
  144. serialize($_GET) .
  145. serialize($_COOKIE) .
  146. serialize($GLOBALS) .
  147. serialize($_SESSION) .
  148. serialize($_OLD_SESSION)
  149. ));
  150. if (!isset($_SESSION['count'])) {
  151. $_SESSION['count'] = 0;
  152. }
  153. $_SESSION['count']++;
  154. session_write_close();
  155. // restore old session data
  156. if ($old_session_id != '') {
  157. session_id($old_session_id);
  158. session_start();
  159. ini_set('session.use_cookies', $old_use_cookies);
  160. session_cache_limiter($old_session_cache_limiter);
  161. } else {
  162. if (isset($_OLD_SESSION)) {
  163. $_SESSION = $_OLD_SESSION;
  164. unset($_OLD_SESSION);
  165. } else {
  166. unset($_SESSION);
  167. }
  168. }
  169. // in SSH2 a shared secret and an exchange hash are generated through the key exchange process.
  170. // 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.
  171. // if the hash doesn't produce enough a key or an IV that's long enough concat successive hashes of the
  172. // original hash and the current hash. we'll be emulating that. for more info see the following URL:
  173. //
  174. // http://tools.ietf.org/html/rfc4253#section-7.2
  175. //
  176. // see the is_string($crypto) part for an example of how to expand the keys
  177. $key = pack('H*', sha1($seed . 'A'));
  178. $iv = pack('H*', sha1($seed . 'C'));
  179. // ciphers are used as per the nist.gov link below. also, see this link:
  180. //
  181. // http://en.wikipedia.org/wiki/Cryptographically_secure_pseudorandom_number_generator#Designs_based_on_cryptographic_primitives
  182. switch (true) {
  183. case class_exists('Crypt_AES'):
  184. $crypto = new Crypt_AES(CRYPT_AES_MODE_CTR);
  185. break;
  186. case class_exists('Crypt_TripleDES'):
  187. $crypto = new Crypt_TripleDES(CRYPT_DES_MODE_CTR);
  188. break;
  189. case class_exists('Crypt_DES'):
  190. $crypto = new Crypt_DES(CRYPT_DES_MODE_CTR);
  191. break;
  192. case class_exists('Crypt_RC4'):
  193. $crypto = new Crypt_RC4();
  194. break;
  195. default:
  196. $crypto = $seed;
  197. return crypt_random_string($length);
  198. }
  199. $crypto->setKey($key);
  200. $crypto->setIV($iv);
  201. $crypto->enableContinuousBuffer();
  202. }
  203. if (is_string($crypto)) {
  204. // the following is based off of ANSI X9.31:
  205. //
  206. // http://csrc.nist.gov/groups/STM/cavp/documents/rng/931rngext.pdf
  207. //
  208. // OpenSSL uses that same standard for it's random numbers:
  209. //
  210. // http://www.opensource.apple.com/source/OpenSSL/OpenSSL-38/openssl/fips-1.0/rand/fips_rand.c
  211. // (do a search for "ANS X9.31 A.2.4")
  212. //
  213. // ANSI X9.31 recommends ciphers be used and phpseclib does use them if they're available (see
  214. // later on in the code) but if they're not we'll use sha1
  215. $result = '';
  216. while (strlen($result) < $length) { // each loop adds 20 bytes
  217. // microtime() isn't packed as "densely" as it could be but then neither is that the idea.
  218. // the idea is simply to ensure that each "block" has a unique element to it.
  219. $i = pack('H*', sha1(microtime()));
  220. $r = pack('H*', sha1($i ^ $v));
  221. $v = pack('H*', sha1($r ^ $i));
  222. $result.= $r;
  223. }
  224. return substr($result, 0, $length);
  225. }
  226. //return $crypto->encrypt(str_repeat("\0", $length));
  227. $result = '';
  228. while (strlen($result) < $length) {
  229. $i = $crypto->encrypt(microtime());
  230. $r = $crypto->encrypt($i ^ $v);
  231. $v = $crypto->encrypt($r ^ $i);
  232. $result.= $r;
  233. }
  234. return substr($result, 0, $length);
  235. }