[ 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                  $temp = fread($fp, $length);
 101                  if (strlen($temp) == $length) {
 102                      return $temp;
 103                  }
 104              }
 105              // method 3. pretty much does the same thing as method 2 per the following url:
 106              // https://github.com/php/php-src/blob/7014a0eb6d1611151a286c0ff4f2238f92c120d6/ext/mcrypt/mcrypt.c#L1391
 107              // surprisingly slower than method 2. maybe that's because mcrypt_create_iv does a bunch of error checking that we're
 108              // not doing. regardless, this'll only be called if this PHP script couldn't open /dev/urandom due to open_basedir
 109              // restrictions or some such
 110              if (extension_loaded('mcrypt')) {
 111                  return @mcrypt_create_iv($length, MCRYPT_DEV_URANDOM);
 112              }
 113          }
 114          // at this point we have no choice but to use a pure-PHP CSPRNG
 115  
 116          // cascade entropy across multiple PHP instances by fixing the session and collecting all
 117          // environmental variables, including the previous session data and the current session
 118          // data.
 119          //
 120          // mt_rand seeds itself by looking at the PID and the time, both of which are (relatively)
 121          // easy to guess at. linux uses mouse clicks, keyboard timings, etc, as entropy sources, but
 122          // PHP isn't low level to be able to use those as sources and on a web server there's not likely
 123          // going to be a ton of keyboard or mouse action. web servers do have one thing that we can use
 124          // however, a ton of people visiting the website. obviously you don't want to base your seeding
 125          // soley on parameters a potential attacker sends but (1) not everything in $_SERVER is controlled
 126          // by the user and (2) this isn't just looking at the data sent by the current user - it's based
 127          // on the data sent by all users. one user requests the page and a hash of their info is saved.
 128          // another user visits the page and the serialization of their data is utilized along with the
 129          // server envirnment stuff and a hash of the previous http request data (which itself utilizes
 130          // a hash of the session data before that). certainly an attacker should be assumed to have
 131          // full control over his own http requests. he, however, is not going to have control over
 132          // everyone's http requests.
 133          static $crypto = false, $v;
 134          if ($crypto === false) {
 135              // save old session data
 136              $old_session_id = session_id();
 137              $old_use_cookies = ini_get('session.use_cookies');
 138              $old_session_cache_limiter = session_cache_limiter();
 139              $_OLD_SESSION = isset($_SESSION) ? $_SESSION : false;
 140              if ($old_session_id != '') {
 141                  session_write_close();
 142              }
 143  
 144              session_id(1);
 145              ini_set('session.use_cookies', 0);
 146              session_cache_limiter('');
 147              session_start();
 148  
 149              $v = $seed = $_SESSION['seed'] = pack('H*', sha1(
 150                  (isset($_SERVER) ? phpseclib_safe_serialize($_SERVER) : '') .
 151                  (isset($_POST) ? phpseclib_safe_serialize($_POST) : '') .
 152                  (isset($_GET) ? phpseclib_safe_serialize($_GET) : '') .
 153                  (isset($_COOKIE) ? phpseclib_safe_serialize($_COOKIE) : '') .
 154                  phpseclib_safe_serialize($GLOBALS) .
 155                  phpseclib_safe_serialize($_SESSION) .
 156                  phpseclib_safe_serialize($_OLD_SESSION)
 157              ));
 158              if (!isset($_SESSION['count'])) {
 159                  $_SESSION['count'] = 0;
 160              }
 161              $_SESSION['count']++;
 162  
 163              session_write_close();
 164  
 165              // restore old session data
 166              if ($old_session_id != '') {
 167                  session_id($old_session_id);
 168                  session_start();
 169                  ini_set('session.use_cookies', $old_use_cookies);
 170                  session_cache_limiter($old_session_cache_limiter);
 171              } else {
 172                  if ($_OLD_SESSION !== false) {
 173                      $_SESSION = $_OLD_SESSION;
 174                      unset($_OLD_SESSION);
 175                  } else {
 176                      unset($_SESSION);
 177                  }
 178              }
 179  
 180              // in SSH2 a shared secret and an exchange hash are generated through the key exchange process.
 181              // 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.
 182              // if the hash doesn't produce enough a key or an IV that's long enough concat successive hashes of the
 183              // original hash and the current hash. we'll be emulating that. for more info see the following URL:
 184              //
 185              // http://tools.ietf.org/html/rfc4253#section-7.2
 186              //
 187              // see the is_string($crypto) part for an example of how to expand the keys
 188              $key = pack('H*', sha1($seed . 'A'));
 189              $iv = pack('H*', sha1($seed . 'C'));
 190  
 191              // ciphers are used as per the nist.gov link below. also, see this link:
 192              //
 193              // http://en.wikipedia.org/wiki/Cryptographically_secure_pseudorandom_number_generator#Designs_based_on_cryptographic_primitives
 194              switch (true) {
 195                  case class_exists('\phpseclib\Crypt\AES'):
 196                      $crypto = new AES(Base::MODE_CTR);
 197                      break;
 198                  case class_exists('\phpseclib\Crypt\Twofish'):
 199                      $crypto = new Twofish(Base::MODE_CTR);
 200                      break;
 201                  case class_exists('\phpseclib\Crypt\Blowfish'):
 202                      $crypto = new Blowfish(Base::MODE_CTR);
 203                      break;
 204                  case class_exists('\phpseclib\Crypt\TripleDES'):
 205                      $crypto = new TripleDES(Base::MODE_CTR);
 206                      break;
 207                  case class_exists('\phpseclib\Crypt\DES'):
 208                      $crypto = new DES(Base::MODE_CTR);
 209                      break;
 210                  case class_exists('\phpseclib\Crypt\RC4'):
 211                      $crypto = new RC4();
 212                      break;
 213                  default:
 214                      user_error(__CLASS__ . ' requires at least one symmetric cipher be loaded');
 215                      return false;
 216              }
 217  
 218              $crypto->setKey($key);
 219              $crypto->setIV($iv);
 220              $crypto->enableContinuousBuffer();
 221          }
 222  
 223          //return $crypto->encrypt(str_repeat("\0", $length));
 224  
 225          // the following is based off of ANSI X9.31:
 226          //
 227          // http://csrc.nist.gov/groups/STM/cavp/documents/rng/931rngext.pdf
 228          //
 229          // OpenSSL uses that same standard for it's random numbers:
 230          //
 231          // http://www.opensource.apple.com/source/OpenSSL/OpenSSL-38/openssl/fips-1.0/rand/fips_rand.c
 232          // (do a search for "ANS X9.31 A.2.4")
 233          $result = '';
 234          while (strlen($result) < $length) {
 235              $i = $crypto->encrypt(microtime()); // strlen(microtime()) == 21
 236              $r = $crypto->encrypt($i ^ $v); // strlen($v) == 20
 237              $v = $crypto->encrypt($r ^ $i); // strlen($r) == 20
 238              $result.= $r;
 239          }
 240          return substr($result, 0, $length);
 241      }
 242  }
 243  
 244  if (!function_exists('phpseclib_safe_serialize')) {
 245      /**
 246       * Safely serialize variables
 247       *
 248       * If a class has a private __sleep() method it'll give a fatal error on PHP 5.2 and earlier.
 249       * PHP 5.3 will emit a warning.
 250       *
 251       * @param mixed $arr
 252       * @access public
 253       */
 254      function phpseclib_safe_serialize(&$arr)
 255      {
 256          if (is_object($arr)) {
 257              return '';
 258          }
 259          if (!is_array($arr)) {
 260              return serialize($arr);
 261          }
 262          // prevent circular array recursion
 263          if (isset($arr['__phpseclib_marker'])) {
 264              return '';
 265          }
 266          $safearr = array();
 267          $arr['__phpseclib_marker'] = true;
 268          foreach (array_keys($arr) as $key) {
 269              // do not recurse on the '__phpseclib_marker' key itself, for smaller memory usage
 270              if ($key !== '__phpseclib_marker') {
 271                  $safearr[$key] = phpseclib_safe_serialize($arr[$key]);
 272              }
 273          }
 274          unset($arr['__phpseclib_marker']);
 275          return serialize($safearr);
 276      }
 277  }