Random.php 14 KB

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