[ Index ]

PHP Cross Reference of DokuWiki

title

Body

[close]

/vendor/phpseclib/phpseclib/phpseclib/Crypt/ -> Random.php (source)

   1  <?php
   2  
   3  /**
   4   * Random Number Generator
   5   *
   6   * PHP version 5
   7   *
   8   * Here's a short example of how to use this library:
   9   * <code>
  10   * <?php
  11   *    include 'vendor/autoload.php';
  12   *
  13   *    echo bin2hex(\phpseclib\Crypt\Random::string(8));
  14   * ?>
  15   * </code>
  16   *
  17   * @category  Crypt
  18   * @package   Random
  19   * @author    Jim Wigginton <terrafrost@php.net>
  20   * @copyright 2007 Jim Wigginton
  21   * @license   http://www.opensource.org/licenses/mit-license.html  MIT License
  22   * @link      http://phpseclib.sourceforge.net
  23   */
  24  
  25  namespace phpseclib\Crypt;
  26  
  27  /**
  28   * Pure-PHP Random Number Generator
  29   *
  30   * @package Random
  31   * @author  Jim Wigginton <terrafrost@php.net>
  32   * @access  public
  33   */
  34  class Random
  35  {
  36      /**
  37       * Generate a random string.
  38       *
  39       * Although microoptimizations are generally discouraged as they impair readability this function is ripe with
  40       * microoptimizations because this function has the potential of being called a huge number of times.
  41       * eg. for RSA key generation.
  42       *
  43       * @param int $length
  44       * @return string
  45       */
  46      static function string($length)
  47      {
  48          if (!$length) {
  49              return '';
  50          }
  51  
  52          if (version_compare(PHP_VERSION, '7.0.0', '>=')) {
  53              try {
  54                  return \random_bytes($length);
  55              } catch (\Throwable $e) {
  56                  // If a sufficient source of randomness is unavailable, random_bytes() will throw an
  57                  // object that implements the Throwable interface (Exception, TypeError, Error).
  58                  // We don't actually need to do anything here. The string() method should just continue
  59                  // as normal. Note, however, that if we don't have a sufficient source of randomness for
  60                  // random_bytes(), most of the other calls here will fail too, so we'll end up using
  61                  // the PHP implementation.
  62              }
  63          }
  64  
  65          if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
  66              // method 1. prior to PHP 5.3 this would call rand() on windows hence the function_exists('class_alias') call.
  67              // ie. class_alias is a function that was introduced in PHP 5.3
  68              if (extension_loaded('mcrypt') && function_exists('class_alias')) {
  69                  return @mcrypt_create_iv($length);
  70              }
  71              // method 2. openssl_random_pseudo_bytes was introduced in PHP 5.3.0 but prior to PHP 5.3.4 there was,
  72              // to quote <http://php.net/ChangeLog-5.php#5.3.4>, "possible blocking behavior". as of 5.3.4
  73              // openssl_random_pseudo_bytes and mcrypt_create_iv do the exact same thing on Windows. ie. they both
  74              // call php_win32_get_random_bytes():
  75              //
  76              // https://github.com/php/php-src/blob/7014a0eb6d1611151a286c0ff4f2238f92c120d6/ext/openssl/openssl.c#L5008
  77              // https://github.com/php/php-src/blob/7014a0eb6d1611151a286c0ff4f2238f92c120d6/ext/mcrypt/mcrypt.c#L1392
  78              //
  79              // php_win32_get_random_bytes() is defined thusly:
  80              //
  81              // https://github.com/php/php-src/blob/7014a0eb6d1611151a286c0ff4f2238f92c120d6/win32/winutil.c#L80
  82              //
  83              // we're calling it, all the same, in the off chance that the mcrypt extension is not available
  84              if (extension_loaded('openssl') && version_compare(PHP_VERSION, '5.3.4', '>=')) {
  85                  return openssl_random_pseudo_bytes($length);
  86              }
  87          } else {
  88              // method 1. the fastest
  89              if (extension_loaded('openssl')) {
  90                  return openssl_random_pseudo_bytes($length);
  91              }
  92              // method 2
  93              static $fp = true;
  94              if ($fp === true) {
  95                  // warning's will be output unles the error suppression operator is used. errors such as
  96                  // "open_basedir restriction in effect", "Permission denied", "No such file or directory", etc.
  97                  $fp = @fopen('/dev/urandom', 'rb');
  98              }
  99              if ($fp !== true && $fp !== false) { // surprisingly faster than !is_bool() or is_resource()
 100                  return fread($fp, $length);
 101              }
 102              // method 3. pretty much does the same thing as method 2 per the following url:
 103              // https://github.com/php/php-src/blob/7014a0eb6d1611151a286c0ff4f2238f92c120d6/ext/mcrypt/mcrypt.c#L1391
 104              // surprisingly slower than method 2. maybe that's because mcrypt_create_iv does a bunch of error checking that we're
 105              // not doing. regardless, this'll only be called if this PHP script couldn't open /dev/urandom due to open_basedir
 106              // restrictions or some such
 107              if (extension_loaded('mcrypt')) {
 108                  return @mcrypt_create_iv($length, MCRYPT_DEV_URANDOM);
 109              }
 110          }
 111          // at this point we have no choice but to use a pure-PHP CSPRNG
 112  
 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  
 141              session_id(1);
 142              ini_set('session.use_cookies', 0);
 143              session_cache_limiter('');
 144              session_start();
 145  
 146              $v = $seed = $_SESSION['seed'] = pack('H*', sha1(
 147                  (isset($_SERVER) ? phpseclib_safe_serialize($_SERVER) : '') .
 148                  (isset($_POST) ? phpseclib_safe_serialize($_POST) : '') .
 149                  (isset($_GET) ? phpseclib_safe_serialize($_GET) : '') .
 150                  (isset($_COOKIE) ? phpseclib_safe_serialize($_COOKIE) : '') .
 151                  phpseclib_safe_serialize($GLOBALS) .
 152                  phpseclib_safe_serialize($_SESSION) .
 153                  phpseclib_safe_serialize($_OLD_SESSION)
 154              ));
 155              if (!isset($_SESSION['count'])) {
 156                  $_SESSION['count'] = 0;
 157              }
 158              $_SESSION['count']++;
 159  
 160              session_write_close();
 161  
 162              // restore old session data
 163              if ($old_session_id != '') {
 164                  session_id($old_session_id);
 165                  session_start();
 166                  ini_set('session.use_cookies', $old_use_cookies);
 167                  session_cache_limiter($old_session_cache_limiter);
 168              } else {
 169                  if ($_OLD_SESSION !== false) {
 170                      $_SESSION = $_OLD_SESSION;
 171                      unset($_OLD_SESSION);
 172                  } else {
 173                      unset($_SESSION);
 174                  }
 175              }
 176  
 177              // in SSH2 a shared secret and an exchange hash are generated through the key exchange process.
 178              // 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.
 179              // if the hash doesn't produce enough a key or an IV that's long enough concat successive hashes of the
 180              // original hash and the current hash. we'll be emulating that. for more info see the following URL:
 181              //
 182              // http://tools.ietf.org/html/rfc4253#section-7.2
 183              //
 184              // see the is_string($crypto) part for an example of how to expand the keys
 185              $key = pack('H*', sha1($seed . 'A'));
 186              $iv = pack('H*', sha1($seed . 'C'));
 187  
 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 class_exists('\phpseclib\Crypt\AES'):
 193                      $crypto = new AES(Base::MODE_CTR);
 194                      break;
 195                  case class_exists('\phpseclib\Crypt\Twofish'):
 196                      $crypto = new Twofish(Base::MODE_CTR);
 197                      break;
 198                  case class_exists('\phpseclib\Crypt\Blowfish'):
 199                      $crypto = new Blowfish(Base::MODE_CTR);
 200                      break;
 201                  case class_exists('\phpseclib\Crypt\TripleDES'):
 202                      $crypto = new TripleDES(Base::MODE_CTR);
 203                      break;
 204                  case class_exists('\phpseclib\Crypt\DES'):
 205                      $crypto = new DES(Base::MODE_CTR);
 206                      break;
 207                  case class_exists('\phpseclib\Crypt\RC4'):
 208                      $crypto = new RC4();
 209                      break;
 210                  default:
 211                      user_error(__CLASS__ . ' requires at least one symmetric cipher be loaded');
 212                      return false;
 213              }
 214  
 215              $crypto->setKey($key);
 216              $crypto->setIV($iv);
 217              $crypto->enableContinuousBuffer();
 218          }
 219  
 220          //return $crypto->encrypt(str_repeat("\0", $length));
 221  
 222          // the following is based off of ANSI X9.31:
 223          //
 224          // http://csrc.nist.gov/groups/STM/cavp/documents/rng/931rngext.pdf
 225          //
 226          // OpenSSL uses that same standard for it's random numbers:
 227          //
 228          // http://www.opensource.apple.com/source/OpenSSL/OpenSSL-38/openssl/fips-1.0/rand/fips_rand.c
 229          // (do a search for "ANS X9.31 A.2.4")
 230          $result = '';
 231          while (strlen($result) < $length) {
 232              $i = $crypto->encrypt(microtime()); // strlen(microtime()) == 21
 233              $r = $crypto->encrypt($i ^ $v); // strlen($v) == 20
 234              $v = $crypto->encrypt($r ^ $i); // strlen($r) == 20
 235              $result.= $r;
 236          }
 237          return substr($result, 0, $length);
 238      }
 239  }
 240  
 241  if (!function_exists('phpseclib_safe_serialize')) {
 242      /**
 243       * Safely serialize variables
 244       *
 245       * If a class has a private __sleep() method it'll give a fatal error on PHP 5.2 and earlier.
 246       * PHP 5.3 will emit a warning.
 247       *
 248       * @param mixed $arr
 249       * @access public
 250       */
 251      function phpseclib_safe_serialize(&$arr)
 252      {
 253          if (is_object($arr)) {
 254              return '';
 255          }
 256          if (!is_array($arr)) {
 257              return serialize($arr);
 258          }
 259          // prevent circular array recursion
 260          if (isset($arr['__phpseclib_marker'])) {
 261              return '';
 262          }
 263          $safearr = array();
 264          $arr['__phpseclib_marker'] = true;
 265          foreach (array_keys($arr) as $key) {
 266              // do not recurse on the '__phpseclib_marker' key itself, for smaller memory usage
 267              if ($key !== '__phpseclib_marker') {
 268                  $safearr[$key] = phpseclib_safe_serialize($arr[$key]);
 269              }
 270          }
 271          unset($arr['__phpseclib_marker']);
 272          return serialize($safearr);
 273      }
 274  }