/modules/civicrm/vendor/phpseclib/phpseclib/phpseclib/Crypt/Random.php

https://github.com/nysenate/Bluebird-CRM · PHP · 277 lines · 142 code · 16 blank · 119 comment · 31 complexity · ed0c94b0630c9199326b5a67dde07fb9 MD5 · raw file

  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. /**
  25. * Pure-PHP Random Number Generator
  26. *
  27. * @package Random
  28. * @author Jim Wigginton <terrafrost@php.net>
  29. * @access public
  30. */
  31. class Random
  32. {
  33. /**
  34. * Generate a random string.
  35. *
  36. * Although microoptimizations are generally discouraged as they impair readability this function is ripe with
  37. * microoptimizations because this function has the potential of being called a huge number of times.
  38. * eg. for RSA key generation.
  39. *
  40. * @param int $length
  41. * @return string
  42. */
  43. static function string($length)
  44. {
  45. if (!$length) {
  46. return '';
  47. }
  48. if (version_compare(PHP_VERSION, '7.0.0', '>=')) {
  49. try {
  50. return \random_bytes($length);
  51. } catch (\Throwable $e) {
  52. // If a sufficient source of randomness is unavailable, random_bytes() will throw an
  53. // object that implements the Throwable interface (Exception, TypeError, Error).
  54. // We don't actually need to do anything here. The string() method should just continue
  55. // as normal. Note, however, that if we don't have a sufficient source of randomness for
  56. // random_bytes(), most of the other calls here will fail too, so we'll end up using
  57. // the PHP implementation.
  58. }
  59. }
  60. if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
  61. // method 1. prior to PHP 5.3 this would call rand() on windows hence the function_exists('class_alias') call.
  62. // ie. class_alias is a function that was introduced in PHP 5.3
  63. if (extension_loaded('mcrypt') && function_exists('class_alias')) {
  64. return @mcrypt_create_iv($length);
  65. }
  66. // method 2. openssl_random_pseudo_bytes was introduced in PHP 5.3.0 but prior to PHP 5.3.4 there was,
  67. // to quote <http://php.net/ChangeLog-5.php#5.3.4>, "possible blocking behavior". as of 5.3.4
  68. // openssl_random_pseudo_bytes and mcrypt_create_iv do the exact same thing on Windows. ie. they both
  69. // call php_win32_get_random_bytes():
  70. //
  71. // https://github.com/php/php-src/blob/7014a0eb6d1611151a286c0ff4f2238f92c120d6/ext/openssl/openssl.c#L5008
  72. // https://github.com/php/php-src/blob/7014a0eb6d1611151a286c0ff4f2238f92c120d6/ext/mcrypt/mcrypt.c#L1392
  73. //
  74. // php_win32_get_random_bytes() is defined thusly:
  75. //
  76. // https://github.com/php/php-src/blob/7014a0eb6d1611151a286c0ff4f2238f92c120d6/win32/winutil.c#L80
  77. //
  78. // we're calling it, all the same, in the off chance that the mcrypt extension is not available
  79. if (extension_loaded('openssl') && version_compare(PHP_VERSION, '5.3.4', '>=')) {
  80. return openssl_random_pseudo_bytes($length);
  81. }
  82. } else {
  83. // method 1. the fastest
  84. if (extension_loaded('openssl')) {
  85. return openssl_random_pseudo_bytes($length);
  86. }
  87. // method 2
  88. static $fp = true;
  89. if ($fp === true) {
  90. // warning's will be output unles the error suppression operator is used. errors such as
  91. // "open_basedir restriction in effect", "Permission denied", "No such file or directory", etc.
  92. $fp = @fopen('/dev/urandom', 'rb');
  93. }
  94. if ($fp !== true && $fp !== false) { // surprisingly faster than !is_bool() or is_resource()
  95. $temp = fread($fp, $length);
  96. if (strlen($temp) == $length) {
  97. return $temp;
  98. }
  99. }
  100. // method 3. pretty much does the same thing as method 2 per the following url:
  101. // https://github.com/php/php-src/blob/7014a0eb6d1611151a286c0ff4f2238f92c120d6/ext/mcrypt/mcrypt.c#L1391
  102. // surprisingly slower than method 2. maybe that's because mcrypt_create_iv does a bunch of error checking that we're
  103. // not doing. regardless, this'll only be called if this PHP script couldn't open /dev/urandom due to open_basedir
  104. // restrictions or some such
  105. if (extension_loaded('mcrypt')) {
  106. return @mcrypt_create_iv($length, MCRYPT_DEV_URANDOM);
  107. }
  108. }
  109. // at this point we have no choice but to use a pure-PHP CSPRNG
  110. // cascade entropy across multiple PHP instances by fixing the session and collecting all
  111. // environmental variables, including the previous session data and the current session
  112. // data.
  113. //
  114. // mt_rand seeds itself by looking at the PID and the time, both of which are (relatively)
  115. // easy to guess at. linux uses mouse clicks, keyboard timings, etc, as entropy sources, but
  116. // PHP isn't low level to be able to use those as sources and on a web server there's not likely
  117. // going to be a ton of keyboard or mouse action. web servers do have one thing that we can use
  118. // however, a ton of people visiting the website. obviously you don't want to base your seeding
  119. // soley on parameters a potential attacker sends but (1) not everything in $_SERVER is controlled
  120. // by the user and (2) this isn't just looking at the data sent by the current user - it's based
  121. // on the data sent by all users. one user requests the page and a hash of their info is saved.
  122. // another user visits the page and the serialization of their data is utilized along with the
  123. // server envirnment stuff and a hash of the previous http request data (which itself utilizes
  124. // a hash of the session data before that). certainly an attacker should be assumed to have
  125. // full control over his own http requests. he, however, is not going to have control over
  126. // everyone's http requests.
  127. static $crypto = false, $v;
  128. if ($crypto === false) {
  129. // save old session data
  130. $old_session_id = session_id();
  131. $old_use_cookies = ini_get('session.use_cookies');
  132. $old_session_cache_limiter = session_cache_limiter();
  133. $_OLD_SESSION = isset($_SESSION) ? $_SESSION : false;
  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. (isset($_SERVER) ? phpseclib_safe_serialize($_SERVER) : '') .
  143. (isset($_POST) ? phpseclib_safe_serialize($_POST) : '') .
  144. (isset($_GET) ? phpseclib_safe_serialize($_GET) : '') .
  145. (isset($_COOKIE) ? phpseclib_safe_serialize($_COOKIE) : '') .
  146. phpseclib_safe_serialize($GLOBALS) .
  147. phpseclib_safe_serialize($_SESSION) .
  148. phpseclib_safe_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 ($_OLD_SESSION !== false) {
  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('\phpseclib\Crypt\AES'):
  184. $crypto = new AES(Base::MODE_CTR);
  185. break;
  186. case class_exists('\phpseclib\Crypt\Twofish'):
  187. $crypto = new Twofish(Base::MODE_CTR);
  188. break;
  189. case class_exists('\phpseclib\Crypt\Blowfish'):
  190. $crypto = new Blowfish(Base::MODE_CTR);
  191. break;
  192. case class_exists('\phpseclib\Crypt\TripleDES'):
  193. $crypto = new TripleDES(Base::MODE_CTR);
  194. break;
  195. case class_exists('\phpseclib\Crypt\DES'):
  196. $crypto = new DES(Base::MODE_CTR);
  197. break;
  198. case class_exists('\phpseclib\Crypt\RC4'):
  199. $crypto = new RC4();
  200. break;
  201. default:
  202. user_error(__CLASS__ . ' requires at least one symmetric cipher be loaded');
  203. return false;
  204. }
  205. $crypto->setKey($key);
  206. $crypto->setIV($iv);
  207. $crypto->enableContinuousBuffer();
  208. }
  209. //return $crypto->encrypt(str_repeat("\0", $length));
  210. // the following is based off of ANSI X9.31:
  211. //
  212. // http://csrc.nist.gov/groups/STM/cavp/documents/rng/931rngext.pdf
  213. //
  214. // OpenSSL uses that same standard for it's random numbers:
  215. //
  216. // http://www.opensource.apple.com/source/OpenSSL/OpenSSL-38/openssl/fips-1.0/rand/fips_rand.c
  217. // (do a search for "ANS X9.31 A.2.4")
  218. $result = '';
  219. while (strlen($result) < $length) {
  220. $i = $crypto->encrypt(microtime()); // strlen(microtime()) == 21
  221. $r = $crypto->encrypt($i ^ $v); // strlen($v) == 20
  222. $v = $crypto->encrypt($r ^ $i); // strlen($r) == 20
  223. $result.= $r;
  224. }
  225. return substr($result, 0, $length);
  226. }
  227. }
  228. if (!function_exists('phpseclib_safe_serialize')) {
  229. /**
  230. * Safely serialize variables
  231. *
  232. * If a class has a private __sleep() method it'll give a fatal error on PHP 5.2 and earlier.
  233. * PHP 5.3 will emit a warning.
  234. *
  235. * @param mixed $arr
  236. * @access public
  237. */
  238. function phpseclib_safe_serialize(&$arr)
  239. {
  240. if (is_object($arr)) {
  241. return '';
  242. }
  243. if (!is_array($arr)) {
  244. return serialize($arr);
  245. }
  246. // prevent circular array recursion
  247. if (isset($arr['__phpseclib_marker'])) {
  248. return '';
  249. }
  250. $safearr = array();
  251. $arr['__phpseclib_marker'] = true;
  252. foreach (array_keys($arr) as $key) {
  253. // do not recurse on the '__phpseclib_marker' key itself, for smaller memory usage
  254. if ($key !== '__phpseclib_marker') {
  255. $safearr[$key] = phpseclib_safe_serialize($arr[$key]);
  256. }
  257. }
  258. unset($arr['__phpseclib_marker']);
  259. return serialize($safearr);
  260. }
  261. }