PageRenderTime 44ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/wp-content/plugins/ssh-sftp-updater-support/phpseclib/Crypt/Random.php

https://gitlab.com/Gashler/dp
PHP | 243 lines | 108 code | 13 blank | 122 comment | 25 complexity | 0201538b873e7dfca8ee8e304119841c MD5 | raw file
  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. * @version $Id: Random.php,v 1.9 2010/04/24 06:40:48 terrafrost Exp $
  41. * @link http://phpseclib.sourceforge.net
  42. */
  43. /**
  44. * Generate a random string.
  45. *
  46. * Although microoptimizations are generally discouraged as they impair readability this function is ripe with
  47. * microoptimizations because this function has the potential of being called a huge number of times.
  48. * eg. for RSA key generation.
  49. *
  50. * @param Integer $length
  51. * @return String
  52. * @access public
  53. */
  54. function crypt_random_string($length) {
  55. // PHP_OS & "\xDF\xDF\xDF" == strtoupper(substr(PHP_OS, 0, 3)), but a lot faster
  56. if ((PHP_OS & "\xDF\xDF\xDF") === 'WIN') {
  57. // method 1. prior to PHP 5.3 this would call rand() on windows hence the function_exists('class_alias') call.
  58. // ie. class_alias is a function that was introduced in PHP 5.3
  59. if (function_exists('mcrypt_create_iv') && function_exists('class_alias')) {
  60. return mcrypt_create_iv($length);
  61. }
  62. // method 2. openssl_random_pseudo_bytes was introduced in PHP 5.3.0 but prior to PHP 5.3.4 there was,
  63. // to quote <http://php.net/ChangeLog-5.php#5.3.4>, "possible blocking behavior". as of 5.3.4
  64. // openssl_random_pseudo_bytes and mcrypt_create_iv do the exact same thing on Windows. ie. they both
  65. // call php_win32_get_random_bytes():
  66. //
  67. // https://github.com/php/php-src/blob/7014a0eb6d1611151a286c0ff4f2238f92c120d6/ext/openssl/openssl.c#L5008
  68. // https://github.com/php/php-src/blob/7014a0eb6d1611151a286c0ff4f2238f92c120d6/ext/mcrypt/mcrypt.c#L1392
  69. //
  70. // php_win32_get_random_bytes() is defined thusly:
  71. //
  72. // https://github.com/php/php-src/blob/7014a0eb6d1611151a286c0ff4f2238f92c120d6/win32/winutil.c#L80
  73. //
  74. // we're calling it, all the same, in the off chance that the mcrypt extension is not available
  75. if (function_exists('openssl_random_pseudo_bytes') && version_compare(PHP_VERSION, '5.3.4', '>=')) {
  76. return openssl_random_pseudo_bytes($length);
  77. }
  78. } else {
  79. // method 1. the fastest
  80. if (function_exists('openssl_random_pseudo_bytes')) {
  81. return openssl_random_pseudo_bytes($length);
  82. }
  83. // method 2
  84. static $fp = true;
  85. if ($fp === true) {
  86. // warning's will be output unles the error suppression operator is used. errors such as
  87. // "open_basedir restriction in effect", "Permission denied", "No such file or directory", etc.
  88. $fp = @fopen('/dev/urandom', 'rb');
  89. }
  90. if ($fp !== true && $fp !== false) { // surprisingly faster than !is_bool() or is_resource()
  91. return fread($fp, $length);
  92. }
  93. // method 3. pretty much does the same thing as method 2 per the following url:
  94. // https://github.com/php/php-src/blob/7014a0eb6d1611151a286c0ff4f2238f92c120d6/ext/mcrypt/mcrypt.c#L1391
  95. // surprisingly slower than method 2. maybe that's because mcrypt_create_iv does a bunch of error checking that we're
  96. // not doing. regardless, this'll only be called if this PHP script couldn't open /dev/urandom due to open_basedir
  97. // restrictions or some such
  98. if (function_exists('mcrypt_create_iv')) {
  99. return mcrypt_create_iv($length, MCRYPT_DEV_URANDOM);
  100. }
  101. }
  102. // at this point we have no choice but to use a pure-PHP CSPRNG
  103. // cascade entropy across multiple PHP instances by fixing the session and collecting all
  104. // environmental variables, including the previous session data and the current session
  105. // data.
  106. //
  107. // mt_rand seeds itself by looking at the PID and the time, both of which are (relatively)
  108. // easy to guess at. linux uses mouse clicks, keyboard timings, etc, as entropy sources, but
  109. // PHP isn't low level to be able to use those as sources and on a web server there's not likely
  110. // going to be a ton of keyboard or mouse action. web servers do have one thing that we can use
  111. // however. a ton of people visiting the website. obviously you don't want to base your seeding
  112. // soley on parameters a potential attacker sends but (1) not everything in $_SERVER is controlled
  113. // by the user and (2) this isn't just looking at the data sent by the current user - it's based
  114. // on the data sent by all users. one user requests the page and a hash of their info is saved.
  115. // another user visits the page and the serialization of their data is utilized along with the
  116. // server envirnment stuff and a hash of the previous http request data (which itself utilizes
  117. // a hash of the session data before that). certainly an attacker should be assumed to have
  118. // full control over his own http requests. he, however, is not going to have control over
  119. // everyone's http requests.
  120. static $crypto = false, $v;
  121. if ($crypto === false) {
  122. // save old session data
  123. $old_session_id = session_id();
  124. $old_use_cookies = ini_get('session.use_cookies');
  125. $old_session_cache_limiter = session_cache_limiter();
  126. if (isset($_SESSION)) {
  127. $_OLD_SESSION = $_SESSION;
  128. }
  129. if ($old_session_id != '') {
  130. session_write_close();
  131. }
  132. session_id(1);
  133. ini_set('session.use_cookies', 0);
  134. session_cache_limiter('');
  135. session_start();
  136. $v = $seed = $_SESSION['seed'] = pack('H*', sha1(
  137. serialize($_SERVER) .
  138. serialize($_POST) .
  139. serialize($_GET) .
  140. serialize($_COOKIE) .
  141. serialize($_GLOBAL) .
  142. serialize($_SESSION) .
  143. serialize($_OLD_SESSION)
  144. ));
  145. if (!isset($_SESSION['count'])) {
  146. $_SESSION['count'] = 0;
  147. }
  148. $_SESSION['count']++;
  149. session_write_close();
  150. // restore old session data
  151. if ($old_session_id != '') {
  152. session_id($old_session_id);
  153. session_start();
  154. ini_set('session.use_cookies', $old_use_cookies);
  155. session_cache_limiter($old_session_cache_limiter);
  156. } else {
  157. if (isset($_OLD_SESSION)) {
  158. $_SESSION = $_OLD_SESSION;
  159. unset($_OLD_SESSION);
  160. } else {
  161. unset($_SESSION);
  162. }
  163. }
  164. // in SSH2 a shared secret and an exchange hash are generated through the key exchange process.
  165. // 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.
  166. // if the hash doesn't produce enough a key or an IV that's long enough concat successive hashes of the
  167. // original hash and the current hash. we'll be emulating that. for more info see the following URL:
  168. //
  169. // http://tools.ietf.org/html/rfc4253#section-7.2
  170. //
  171. // see the is_string($crypto) part for an example of how to expand the keys
  172. $key = pack('H*', sha1($seed . 'A'));
  173. $iv = pack('H*', sha1($seed . 'C'));
  174. // ciphers are used as per the nist.gov link below. also, see this link:
  175. //
  176. // http://en.wikipedia.org/wiki/Cryptographically_secure_pseudorandom_number_generator#Designs_based_on_cryptographic_primitives
  177. switch (true) {
  178. case class_exists('Crypt_AES'):
  179. $crypto = new Crypt_AES(CRYPT_AES_MODE_CTR);
  180. break;
  181. case class_exists('Crypt_TripleDES'):
  182. $crypto = new Crypt_TripleDES(CRYPT_DES_MODE_CTR);
  183. break;
  184. case class_exists('Crypt_DES'):
  185. $crypto = new Crypt_DES(CRYPT_DES_MODE_CTR);
  186. break;
  187. case class_exists('Crypt_RC4'):
  188. $crypto = new Crypt_RC4();
  189. break;
  190. default:
  191. $crypto = $seed;
  192. return crypt_random_string($length);
  193. }
  194. $crypto->setKey($key);
  195. $crypto->setIV($iv);
  196. $crypto->enableContinuousBuffer();
  197. }
  198. if (is_string($crypto)) {
  199. // the following is based off of ANSI X9.31:
  200. //
  201. // http://csrc.nist.gov/groups/STM/cavp/documents/rng/931rngext.pdf
  202. //
  203. // OpenSSL uses that same standard for it's random numbers:
  204. //
  205. // http://www.opensource.apple.com/source/OpenSSL/OpenSSL-38/openssl/fips-1.0/rand/fips_rand.c
  206. // (do a search for "ANS X9.31 A.2.4")
  207. //
  208. // ANSI X9.31 recommends ciphers be used and phpseclib does use them if they're available (see
  209. // later on in the code) but if they're not we'll use sha1
  210. $result = '';
  211. while (strlen($result) < $length) { // each loop adds 20 bytes
  212. // microtime() isn't packed as "densely" as it could be but then neither is that the idea.
  213. // the idea is simply to ensure that each "block" has a unique element to it.
  214. $i = pack('H*', sha1(microtime()));
  215. $r = pack('H*', sha1($i ^ $v));
  216. $v = pack('H*', sha1($r ^ $i));
  217. $result.= $r;
  218. }
  219. return substr($result, 0, $length);
  220. }
  221. //return $crypto->encrypt(str_repeat("\0", $length));
  222. $result = '';
  223. while (strlen($result) < $length) {
  224. $i = $crypto->encrypt(microtime());
  225. $r = $crypto->encrypt($i ^ $v);
  226. $v = $crypto->encrypt($r ^ $i);
  227. $result.= $r;
  228. }
  229. return substr($result, 0, $length);
  230. }