Random.php 15 KB

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