Random.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  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 Integer $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 this would call rand() on windows hence the function_exists('class_alias') call.
  69. // ie. class_alias is a function that was introduced in PHP 5.3
  70. if (function_exists('mcrypt_create_iv') && function_exists('class_alias')) {
  71. return mcrypt_create_iv($length);
  72. }
  73. // method 2. openssl_random_pseudo_bytes was introduced in PHP 5.3.0 but prior to PHP 5.3.4 there was,
  74. // to quote <http://php.net/ChangeLog-5.php#5.3.4>, "possible blocking behavior". as of 5.3.4
  75. // openssl_random_pseudo_bytes and mcrypt_create_iv do the exact same thing on Windows. ie. they both
  76. // call php_win32_get_random_bytes():
  77. //
  78. // https://github.com/php/php-src/blob/7014a0eb6d1611151a286c0ff4f2238f92c120d6/ext/openssl/openssl.c#L5008
  79. // https://github.com/php/php-src/blob/7014a0eb6d1611151a286c0ff4f2238f92c120d6/ext/mcrypt/mcrypt.c#L1392
  80. //
  81. // php_win32_get_random_bytes() is defined thusly:
  82. //
  83. // https://github.com/php/php-src/blob/7014a0eb6d1611151a286c0ff4f2238f92c120d6/win32/winutil.c#L80
  84. //
  85. // we're calling it, all the same, in the off chance that the mcrypt extension is not available
  86. if (function_exists('openssl_random_pseudo_bytes') && version_compare(PHP_VERSION, '5.3.4', '>=')) {
  87. return openssl_random_pseudo_bytes($length);
  88. }
  89. } else {
  90. // method 1. the fastest
  91. if (function_exists('openssl_random_pseudo_bytes')) {
  92. return openssl_random_pseudo_bytes($length);
  93. }
  94. // method 2
  95. static $fp = true;
  96. if ($fp === true) {
  97. // warning's will be output unles the error suppression operator is used. errors such as
  98. // "open_basedir restriction in effect", "Permission denied", "No such file or directory", etc.
  99. $fp = @fopen('/dev/urandom', 'rb');
  100. }
  101. if ($fp !== true && $fp !== false) { // surprisingly faster than !is_bool() or is_resource()
  102. return fread($fp, $length);
  103. }
  104. // method 3. pretty much does the same thing as method 2 per the following url:
  105. // https://github.com/php/php-src/blob/7014a0eb6d1611151a286c0ff4f2238f92c120d6/ext/mcrypt/mcrypt.c#L1391
  106. // surprisingly slower than method 2. maybe that's because mcrypt_create_iv does a bunch of error checking that we're
  107. // not doing. regardless, this'll only be called if this PHP script couldn't open /dev/urandom due to open_basedir
  108. // restrictions or some such
  109. if (function_exists('mcrypt_create_iv')) {
  110. return mcrypt_create_iv($length, MCRYPT_DEV_URANDOM);
  111. }
  112. }
  113. // at this point we have no choice but to use a pure-PHP CSPRNG
  114. // cascade entropy across multiple PHP instances by fixing the session and collecting all
  115. // environmental variables, including the previous session data and the current session
  116. // data.
  117. //
  118. // mt_rand seeds itself by looking at the PID and the time, both of which are (relatively)
  119. // easy to guess at. linux uses mouse clicks, keyboard timings, etc, as entropy sources, but
  120. // PHP isn't low level to be able to use those as sources and on a web server there's not likely
  121. // going to be a ton of keyboard or mouse action. web servers do have one thing that we can use
  122. // however, a ton of people visiting the website. obviously you don't want to base your seeding
  123. // soley on parameters a potential attacker sends but (1) not everything in $_SERVER is controlled
  124. // by the user and (2) this isn't just looking at the data sent by the current user - it's based
  125. // on the data sent by all users. one user requests the page and a hash of their info is saved.
  126. // another user visits the page and the serialization of their data is utilized along with the
  127. // server envirnment stuff and a hash of the previous http request data (which itself utilizes
  128. // a hash of the session data before that). certainly an attacker should be assumed to have
  129. // full control over his own http requests. he, however, is not going to have control over
  130. // everyone's http requests.
  131. static $crypto = false, $v;
  132. if ($crypto === false) {
  133. // save old session data
  134. $old_session_id = session_id();
  135. $old_use_cookies = ini_get('session.use_cookies');
  136. $old_session_cache_limiter = session_cache_limiter();
  137. $_OLD_SESSION = isset($_SESSION) ? $_SESSION : false;
  138. if ($old_session_id != '') {
  139. session_write_close();
  140. }
  141. session_id(1);
  142. ini_set('session.use_cookies', 0);
  143. session_cache_limiter('');
  144. session_start();
  145. $v = $seed = $_SESSION['seed'] = pack('H*', sha1(
  146. serialize($_SERVER) .
  147. serialize($_POST) .
  148. serialize($_GET) .
  149. serialize($_COOKIE) .
  150. serialize($GLOBALS) .
  151. serialize($_SESSION) .
  152. serialize($_OLD_SESSION)
  153. ));
  154. if (!isset($_SESSION['count'])) {
  155. $_SESSION['count'] = 0;
  156. }
  157. $_SESSION['count']++;
  158. session_write_close();
  159. // restore old session data
  160. if ($old_session_id != '') {
  161. session_id($old_session_id);
  162. session_start();
  163. ini_set('session.use_cookies', $old_use_cookies);
  164. session_cache_limiter($old_session_cache_limiter);
  165. } else {
  166. if ($_OLD_SESSION !== false) {
  167. $_SESSION = $_OLD_SESSION;
  168. unset($_OLD_SESSION);
  169. } else {
  170. unset($_SESSION);
  171. }
  172. }
  173. // in SSH2 a shared secret and an exchange hash are generated through the key exchange process.
  174. // 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.
  175. // if the hash doesn't produce enough a key or an IV that's long enough concat successive hashes of the
  176. // original hash and the current hash. we'll be emulating that. for more info see the following URL:
  177. //
  178. // http://tools.ietf.org/html/rfc4253#section-7.2
  179. //
  180. // see the is_string($crypto) part for an example of how to expand the keys
  181. $key = pack('H*', sha1($seed . 'A'));
  182. $iv = pack('H*', sha1($seed . 'C'));
  183. // ciphers are used as per the nist.gov link below. also, see this link:
  184. //
  185. // http://en.wikipedia.org/wiki/Cryptographically_secure_pseudorandom_number_generator#Designs_based_on_cryptographic_primitives
  186. switch (true) {
  187. case phpseclib_resolve_include_path('Crypt/AES.php'):
  188. if (!class_exists('Crypt_AES')) {
  189. include_once 'AES.php';
  190. }
  191. $crypto = new Crypt_AES(CRYPT_AES_MODE_CTR);
  192. break;
  193. case phpseclib_resolve_include_path('Crypt/Twofish.php'):
  194. if (!class_exists('Crypt_Twofish')) {
  195. include_once 'Twofish.php';
  196. }
  197. $crypto = new Crypt_Twofish(CRYPT_TWOFISH_MODE_CTR);
  198. break;
  199. case phpseclib_resolve_include_path('Crypt/Blowfish.php'):
  200. if (!class_exists('Crypt_Blowfish')) {
  201. include_once 'Blowfish.php';
  202. }
  203. $crypto = new Crypt_Blowfish(CRYPT_BLOWFISH_MODE_CTR);
  204. break;
  205. case phpseclib_resolve_include_path('Crypt/TripleDES.php'):
  206. if (!class_exists('Crypt_TripleDES')) {
  207. include_once 'TripleDES.php';
  208. }
  209. $crypto = new Crypt_TripleDES(CRYPT_DES_MODE_CTR);
  210. break;
  211. case phpseclib_resolve_include_path('Crypt/DES.php'):
  212. if (!class_exists('Crypt_DES')) {
  213. include_once 'DES.php';
  214. }
  215. $crypto = new Crypt_DES(CRYPT_DES_MODE_CTR);
  216. break;
  217. case phpseclib_resolve_include_path('Crypt/RC4.php'):
  218. if (!class_exists('Crypt_RC4')) {
  219. include_once 'RC4.php';
  220. }
  221. $crypto = new Crypt_RC4();
  222. break;
  223. default:
  224. user_error('crypt_random_string requires at least one symmetric cipher be loaded');
  225. return false;
  226. }
  227. $crypto->setKey($key);
  228. $crypto->setIV($iv);
  229. $crypto->enableContinuousBuffer();
  230. }
  231. //return $crypto->encrypt(str_repeat("\0", $length));
  232. // the following is based off of ANSI X9.31:
  233. //
  234. // http://csrc.nist.gov/groups/STM/cavp/documents/rng/931rngext.pdf
  235. //
  236. // OpenSSL uses that same standard for it's random numbers:
  237. //
  238. // http://www.opensource.apple.com/source/OpenSSL/OpenSSL-38/openssl/fips-1.0/rand/fips_rand.c
  239. // (do a search for "ANS X9.31 A.2.4")
  240. $result = '';
  241. while (strlen($result) < $length) {
  242. $i = $crypto->encrypt(microtime()); // strlen(microtime()) == 21
  243. $r = $crypto->encrypt($i ^ $v); // strlen($v) == 20
  244. $v = $crypto->encrypt($r ^ $i); // strlen($r) == 20
  245. $result.= $r;
  246. }
  247. return substr($result, 0, $length);
  248. }
  249. }
  250. if (!function_exists('phpseclib_resolve_include_path')) {
  251. /**
  252. * Resolve filename against the include path.
  253. *
  254. * Wrapper around stream_resolve_include_path() (which was introduced in
  255. * PHP 5.3.2) with fallback implementation for earlier PHP versions.
  256. *
  257. * @param string $filename
  258. * @return mixed Filename (string) on success, false otherwise.
  259. * @access public
  260. */
  261. function phpseclib_resolve_include_path($filename)
  262. {
  263. if (function_exists('stream_resolve_include_path')) {
  264. return stream_resolve_include_path($filename);
  265. }
  266. // handle non-relative paths
  267. if (file_exists($filename)) {
  268. return realpath($filename);
  269. }
  270. $paths = PATH_SEPARATOR == ':' ?
  271. preg_split('#(?<!phar):#', get_include_path()) :
  272. explode(PATH_SEPARATOR, get_include_path());
  273. foreach ($paths as $prefix) {
  274. // path's specified in include_path don't always end in /
  275. $ds = substr($prefix, -1) == DIRECTORY_SEPARATOR ? '' : DIRECTORY_SEPARATOR;
  276. $file = $prefix . $ds . $filename;
  277. if (file_exists($file)) {
  278. return realpath($file);
  279. }
  280. }
  281. return false;
  282. }
  283. }