[ Index ] |
PHP Cross Reference of DokuWiki |
[Summary view] [Print] [Text view]
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 // as of PHP 8.1 $GLOBALS can't be accessed by reference, which eliminates 155 // the need for phpseclib_safe_serialize. see https://wiki.php.net/rfc/restrict_globals_usage 156 // for more info 157 (version_compare(PHP_VERSION, '8.1.0', '>=') ? serialize($GLOBALS) : phpseclib_safe_serialize($GLOBALS)) . 158 phpseclib_safe_serialize($_SESSION) . 159 phpseclib_safe_serialize($_OLD_SESSION) 160 )); 161 if (!isset($_SESSION['count'])) { 162 $_SESSION['count'] = 0; 163 } 164 $_SESSION['count']++; 165 166 session_write_close(); 167 168 // restore old session data 169 if ($old_session_id != '') { 170 session_id($old_session_id); 171 session_start(); 172 ini_set('session.use_cookies', $old_use_cookies); 173 session_cache_limiter($old_session_cache_limiter); 174 } else { 175 if ($_OLD_SESSION !== false) { 176 $_SESSION = $_OLD_SESSION; 177 unset($_OLD_SESSION); 178 } else { 179 unset($_SESSION); 180 } 181 } 182 183 // in SSH2 a shared secret and an exchange hash are generated through the key exchange process. 184 // 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. 185 // if the hash doesn't produce enough a key or an IV that's long enough concat successive hashes of the 186 // original hash and the current hash. we'll be emulating that. for more info see the following URL: 187 // 188 // http://tools.ietf.org/html/rfc4253#section-7.2 189 // 190 // see the is_string($crypto) part for an example of how to expand the keys 191 $key = pack('H*', sha1($seed . 'A')); 192 $iv = pack('H*', sha1($seed . 'C')); 193 194 // ciphers are used as per the nist.gov link below. also, see this link: 195 // 196 // http://en.wikipedia.org/wiki/Cryptographically_secure_pseudorandom_number_generator#Designs_based_on_cryptographic_primitives 197 switch (true) { 198 case class_exists('\phpseclib\Crypt\AES'): 199 $crypto = new AES(Base::MODE_CTR); 200 break; 201 case class_exists('\phpseclib\Crypt\Twofish'): 202 $crypto = new Twofish(Base::MODE_CTR); 203 break; 204 case class_exists('\phpseclib\Crypt\Blowfish'): 205 $crypto = new Blowfish(Base::MODE_CTR); 206 break; 207 case class_exists('\phpseclib\Crypt\TripleDES'): 208 $crypto = new TripleDES(Base::MODE_CTR); 209 break; 210 case class_exists('\phpseclib\Crypt\DES'): 211 $crypto = new DES(Base::MODE_CTR); 212 break; 213 case class_exists('\phpseclib\Crypt\RC4'): 214 $crypto = new RC4(); 215 break; 216 default: 217 user_error(__CLASS__ . ' requires at least one symmetric cipher be loaded'); 218 return false; 219 } 220 221 $crypto->setKey($key); 222 $crypto->setIV($iv); 223 $crypto->enableContinuousBuffer(); 224 } 225 226 //return $crypto->encrypt(str_repeat("\0", $length)); 227 228 // the following is based off of ANSI X9.31: 229 // 230 // http://csrc.nist.gov/groups/STM/cavp/documents/rng/931rngext.pdf 231 // 232 // OpenSSL uses that same standard for it's random numbers: 233 // 234 // http://www.opensource.apple.com/source/OpenSSL/OpenSSL-38/openssl/fips-1.0/rand/fips_rand.c 235 // (do a search for "ANS X9.31 A.2.4") 236 $result = ''; 237 while (strlen($result) < $length) { 238 $i = $crypto->encrypt(microtime()); // strlen(microtime()) == 21 239 $r = $crypto->encrypt($i ^ $v); // strlen($v) == 20 240 $v = $crypto->encrypt($r ^ $i); // strlen($r) == 20 241 $result.= $r; 242 } 243 return substr($result, 0, $length); 244 } 245 } 246 247 if (!function_exists('phpseclib_safe_serialize')) { 248 /** 249 * Safely serialize variables 250 * 251 * If a class has a private __sleep() method it'll give a fatal error on PHP 5.2 and earlier. 252 * PHP 5.3 will emit a warning. 253 * 254 * @param mixed $arr 255 * @access public 256 */ 257 function phpseclib_safe_serialize(&$arr) 258 { 259 if (is_object($arr)) { 260 return ''; 261 } 262 if (!is_array($arr)) { 263 return serialize($arr); 264 } 265 // prevent circular array recursion 266 if (isset($arr['__phpseclib_marker'])) { 267 return ''; 268 } 269 $safearr = array(); 270 $arr['__phpseclib_marker'] = true; 271 foreach (array_keys($arr) as $key) { 272 // do not recurse on the '__phpseclib_marker' key itself, for smaller memory usage 273 if ($key !== '__phpseclib_marker') { 274 $safearr[$key] = phpseclib_safe_serialize($arr[$key]); 275 } 276 } 277 unset($arr['__phpseclib_marker']); 278 return serialize($safearr); 279 } 280 }
title
Description
Body
title
Description
Body
title
Description
Body
title
Body