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(\phpseclib3\Crypt\Random::string(8)); 14 * ?> 15 * </code> 16 * 17 * @author Jim Wigginton <terrafrost@php.net> 18 * @copyright 2007 Jim Wigginton 19 * @license http://www.opensource.org/licenses/mit-license.html MIT License 20 * @link http://phpseclib.sourceforge.net 21 */ 22 23namespace phpseclib3\Crypt; 24 25/** 26 * Pure-PHP Random Number Generator 27 * 28 * @author Jim Wigginton <terrafrost@php.net> 29 */ 30abstract class Random 31{ 32 /** 33 * Generate a random string. 34 * 35 * Although microoptimizations are generally discouraged as they impair readability this function is ripe with 36 * microoptimizations because this function has the potential of being called a huge number of times. 37 * eg. for RSA key generation. 38 * 39 * @param int $length 40 * @throws \RuntimeException if a symmetric cipher is needed but not loaded 41 * @return string 42 */ 43 public static function string($length) 44 { 45 if (!$length) { 46 return ''; 47 } 48 49 try { 50 return random_bytes($length); 51 } catch (\Exception $e) { 52 // random_compat will throw an Exception, which in PHP 5 does not implement Throwable 53 } catch (\Throwable $e) { 54 // If a sufficient source of randomness is unavailable, random_bytes() will throw an 55 // object that implements the Throwable interface (Exception, TypeError, Error). 56 // We don't actually need to do anything here. The string() method should just continue 57 // as normal. Note, however, that if we don't have a sufficient source of randomness for 58 // random_bytes(), most of the other calls here will fail too, so we'll end up using 59 // the PHP implementation. 60 } 61 // at this point we have no choice but to use a pure-PHP CSPRNG 62 63 // cascade entropy across multiple PHP instances by fixing the session and collecting all 64 // environmental variables, including the previous session data and the current session 65 // data. 66 // 67 // mt_rand seeds itself by looking at the PID and the time, both of which are (relatively) 68 // easy to guess at. linux uses mouse clicks, keyboard timings, etc, as entropy sources, but 69 // PHP isn't low level to be able to use those as sources and on a web server there's not likely 70 // going to be a ton of keyboard or mouse action. web servers do have one thing that we can use 71 // however, a ton of people visiting the website. obviously you don't want to base your seeding 72 // solely on parameters a potential attacker sends but (1) not everything in $_SERVER is controlled 73 // by the user and (2) this isn't just looking at the data sent by the current user - it's based 74 // on the data sent by all users. one user requests the page and a hash of their info is saved. 75 // another user visits the page and the serialization of their data is utilized along with the 76 // server environment stuff and a hash of the previous http request data (which itself utilizes 77 // a hash of the session data before that). certainly an attacker should be assumed to have 78 // full control over his own http requests. he, however, is not going to have control over 79 // everyone's http requests. 80 static $crypto = false, $v; 81 if ($crypto === false) { 82 // save old session data 83 $old_session_id = session_id(); 84 $old_use_cookies = ini_get('session.use_cookies'); 85 $old_session_cache_limiter = session_cache_limiter(); 86 $_OLD_SESSION = isset($_SESSION) ? $_SESSION : false; 87 if ($old_session_id != '') { 88 session_write_close(); 89 } 90 91 session_id(1); 92 ini_set('session.use_cookies', 0); 93 session_cache_limiter(''); 94 session_start(); 95 96 $v = (isset($_SERVER) ? self::safe_serialize($_SERVER) : '') . 97 (isset($_POST) ? self::safe_serialize($_POST) : '') . 98 (isset($_GET) ? self::safe_serialize($_GET) : '') . 99 (isset($_COOKIE) ? self::safe_serialize($_COOKIE) : '') . 100 // as of PHP 8.1 $GLOBALS can't be accessed by reference, which eliminates 101 // the need for phpseclib_safe_serialize. see https://wiki.php.net/rfc/restrict_globals_usage 102 // for more info 103 (version_compare(PHP_VERSION, '8.1.0', '>=') ? serialize($GLOBALS) : self::safe_serialize($GLOBALS)) . 104 self::safe_serialize($_SESSION) . 105 self::safe_serialize($_OLD_SESSION); 106 $v = $seed = $_SESSION['seed'] = sha1($v, true); 107 if (!isset($_SESSION['count'])) { 108 $_SESSION['count'] = 0; 109 } 110 $_SESSION['count']++; 111 112 session_write_close(); 113 114 // restore old session data 115 if ($old_session_id != '') { 116 session_id($old_session_id); 117 session_start(); 118 ini_set('session.use_cookies', $old_use_cookies); 119 session_cache_limiter($old_session_cache_limiter); 120 } else { 121 if ($_OLD_SESSION !== false) { 122 $_SESSION = $_OLD_SESSION; 123 unset($_OLD_SESSION); 124 } else { 125 unset($_SESSION); 126 } 127 } 128 129 // in SSH2 a shared secret and an exchange hash are generated through the key exchange process. 130 // 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. 131 // if the hash doesn't produce enough a key or an IV that's long enough concat successive hashes of the 132 // original hash and the current hash. we'll be emulating that. for more info see the following URL: 133 // 134 // http://tools.ietf.org/html/rfc4253#section-7.2 135 // 136 // see the is_string($crypto) part for an example of how to expand the keys 137 $key = sha1($seed . 'A', true); 138 $iv = sha1($seed . 'C', true); 139 140 // ciphers are used as per the nist.gov link below. also, see this link: 141 // 142 // http://en.wikipedia.org/wiki/Cryptographically_secure_pseudorandom_number_generator#Designs_based_on_cryptographic_primitives 143 switch (true) { 144 case class_exists('\phpseclib3\Crypt\AES'): 145 $crypto = new AES('ctr'); 146 break; 147 case class_exists('\phpseclib3\Crypt\Twofish'): 148 $crypto = new Twofish('ctr'); 149 break; 150 case class_exists('\phpseclib3\Crypt\Blowfish'): 151 $crypto = new Blowfish('ctr'); 152 break; 153 case class_exists('\phpseclib3\Crypt\TripleDES'): 154 $crypto = new TripleDES('ctr'); 155 break; 156 case class_exists('\phpseclib3\Crypt\DES'): 157 $crypto = new DES('ctr'); 158 break; 159 case class_exists('\phpseclib3\Crypt\RC4'): 160 $crypto = new RC4(); 161 break; 162 default: 163 throw new \RuntimeException(__CLASS__ . ' requires at least one symmetric cipher be loaded'); 164 } 165 166 $crypto->setKey(substr($key, 0, $crypto->getKeyLength() >> 3)); 167 $crypto->setIV(substr($iv, 0, $crypto->getBlockLength() >> 3)); 168 $crypto->enableContinuousBuffer(); 169 } 170 171 //return $crypto->encrypt(str_repeat("\0", $length)); 172 173 // the following is based off of ANSI X9.31: 174 // 175 // http://csrc.nist.gov/groups/STM/cavp/documents/rng/931rngext.pdf 176 // 177 // OpenSSL uses that same standard for it's random numbers: 178 // 179 // http://www.opensource.apple.com/source/OpenSSL/OpenSSL-38/openssl/fips-1.0/rand/fips_rand.c 180 // (do a search for "ANS X9.31 A.2.4") 181 $result = ''; 182 while (strlen($result) < $length) { 183 $i = $crypto->encrypt(microtime()); // strlen(microtime()) == 21 184 $r = $crypto->encrypt($i ^ $v); // strlen($v) == 20 185 $v = $crypto->encrypt($r ^ $i); // strlen($r) == 20 186 $result .= $r; 187 } 188 189 return substr($result, 0, $length); 190 } 191 192 /** 193 * Safely serialize variables 194 * 195 * If a class has a private __sleep() it'll emit a warning 196 * @return mixed 197 * @param mixed $arr 198 */ 199 private static function safe_serialize(&$arr) 200 { 201 if (is_object($arr)) { 202 return ''; 203 } 204 if (!is_array($arr)) { 205 return serialize($arr); 206 } 207 // prevent circular array recursion 208 if (isset($arr['__phpseclib_marker'])) { 209 return ''; 210 } 211 $safearr = []; 212 $arr['__phpseclib_marker'] = true; 213 foreach (array_keys($arr) as $key) { 214 // do not recurse on the '__phpseclib_marker' key itself, for smaller memory usage 215 if ($key !== '__phpseclib_marker') { 216 $safearr[$key] = self::safe_serialize($arr[$key]); 217 } 218 } 219 unset($arr['__phpseclib_marker']); 220 return serialize($safearr); 221 } 222} 223