MediaWiki
REL1_24
|
00001 <?php 00027 class MWCryptRand { 00031 const MIN_ITERATIONS = 1000; 00032 00039 const MSEC_PER_BYTE = 0.5; 00040 00044 protected static $singleton = null; 00045 00049 protected $algo = null; 00050 00054 protected $hashLength = null; 00055 00060 protected $strong = null; 00061 00066 protected function initialRandomState() { 00067 // $_SERVER contains a variety of unstable user and system specific information 00068 // It'll vary a little with each page, and vary even more with separate users 00069 // It'll also vary slightly across different machines 00070 $state = serialize( $_SERVER ); 00071 00072 // To try vary the system information of the state a bit more 00073 // by including the system's hostname into the state 00074 $state .= wfHostname(); 00075 00076 // Try to gather a little entropy from the different php rand sources 00077 $state .= rand() . uniqid( mt_rand(), true ); 00078 00079 // Include some information about the filesystem's current state in the random state 00080 $files = array(); 00081 00082 // We know this file is here so grab some info about ourselves 00083 $files[] = __FILE__; 00084 00085 // We must also have a parent folder, and with the usual file structure, a grandparent 00086 $files[] = __DIR__; 00087 $files[] = dirname( __DIR__ ); 00088 00089 // The config file is likely the most often edited file we know should 00090 // be around so include its stat info into the state. 00091 // The constant with its location will almost always be defined, as 00092 // WebStart.php defines MW_CONFIG_FILE to $IP/LocalSettings.php unless 00093 // being configured with MW_CONFIG_CALLBACK (e.g. the installer). 00094 if ( defined( 'MW_CONFIG_FILE' ) ) { 00095 $files[] = MW_CONFIG_FILE; 00096 } 00097 00098 foreach ( $files as $file ) { 00099 wfSuppressWarnings(); 00100 $stat = stat( $file ); 00101 wfRestoreWarnings(); 00102 if ( $stat ) { 00103 // stat() duplicates data into numeric and string keys so kill off all the numeric ones 00104 foreach ( $stat as $k => $v ) { 00105 if ( is_numeric( $k ) ) { 00106 unset( $k ); 00107 } 00108 } 00109 // The absolute filename itself will differ from install to install so don't leave it out 00110 if ( ( $path = realpath( $file ) ) !== false ) { 00111 $state .= $path; 00112 } else { 00113 $state .= $file; 00114 } 00115 $state .= implode( '', $stat ); 00116 } else { 00117 // The fact that the file isn't there is worth at least a 00118 // minuscule amount of entropy. 00119 $state .= '0'; 00120 } 00121 } 00122 00123 // Try and make this a little more unstable by including the varying process 00124 // id of the php process we are running inside of if we are able to access it 00125 if ( function_exists( 'getmypid' ) ) { 00126 $state .= getmypid(); 00127 } 00128 00129 // If available try to increase the instability of the data by throwing in 00130 // the precise amount of memory that we happen to be using at the moment. 00131 if ( function_exists( 'memory_get_usage' ) ) { 00132 $state .= memory_get_usage( true ); 00133 } 00134 00135 // It's mostly worthless but throw the wiki's id into the data for a little more variance 00136 $state .= wfWikiID(); 00137 00138 // If we have a secret key set then throw it into the state as well 00139 global $wgSecretKey; 00140 if ( $wgSecretKey ) { 00141 $state .= $wgSecretKey; 00142 } 00143 00144 return $state; 00145 } 00146 00154 protected function driftHash( $data ) { 00155 // Minimum number of iterations (to avoid slow operations causing the 00156 // loop to gather little entropy) 00157 $minIterations = self::MIN_ITERATIONS; 00158 // Duration of time to spend doing calculations (in seconds) 00159 $duration = ( self::MSEC_PER_BYTE / 1000 ) * $this->hashLength(); 00160 // Create a buffer to use to trigger memory operations 00161 $bufLength = 10000000; 00162 $buffer = str_repeat( ' ', $bufLength ); 00163 $bufPos = 0; 00164 00165 // Iterate for $duration seconds or at least $minIterations number of iterations 00166 $iterations = 0; 00167 $startTime = microtime( true ); 00168 $currentTime = $startTime; 00169 while ( $iterations < $minIterations || $currentTime - $startTime < $duration ) { 00170 // Trigger some memory writing to trigger some bus activity 00171 // This may create variance in the time between iterations 00172 $bufPos = ( $bufPos + 13 ) % $bufLength; 00173 $buffer[$bufPos] = ' '; 00174 // Add the drift between this iteration and the last in as entropy 00175 $nextTime = microtime( true ); 00176 $delta = (int)( ( $nextTime - $currentTime ) * 1000000 ); 00177 $data .= $delta; 00178 // Every 100 iterations hash the data and entropy 00179 if ( $iterations % 100 === 0 ) { 00180 $data = sha1( $data ); 00181 } 00182 $currentTime = $nextTime; 00183 $iterations++; 00184 } 00185 $timeTaken = $currentTime - $startTime; 00186 $data = $this->hash( $data ); 00187 00188 wfDebug( __METHOD__ . ": Clock drift calculation " . 00189 "(time-taken=" . ( $timeTaken * 1000 ) . "ms, " . 00190 "iterations=$iterations, " . 00191 "time-per-iteration=" . ( $timeTaken / $iterations * 1e6 ) . "us)\n" ); 00192 00193 return $data; 00194 } 00195 00200 protected function randomState() { 00201 static $state = null; 00202 if ( is_null( $state ) ) { 00203 // Initialize the state with whatever unstable data we can find 00204 // It's important that this data is hashed right afterwards to prevent 00205 // it from being leaked into the output stream 00206 $state = $this->hash( $this->initialRandomState() ); 00207 } 00208 // Generate a new random state based on the initial random state or previous 00209 // random state by combining it with clock drift 00210 $state = $this->driftHash( $state ); 00211 00212 return $state; 00213 } 00214 00220 protected function hashAlgo() { 00221 if ( !is_null( $this->algo ) ) { 00222 return $this->algo; 00223 } 00224 00225 $algos = hash_algos(); 00226 $preference = array( 'whirlpool', 'sha256', 'sha1', 'md5' ); 00227 00228 foreach ( $preference as $algorithm ) { 00229 if ( in_array( $algorithm, $algos ) ) { 00230 $this->algo = $algorithm; 00231 wfDebug( __METHOD__ . ": Using the {$this->algo} hash algorithm.\n" ); 00232 00233 return $this->algo; 00234 } 00235 } 00236 00237 // We only reach here if no acceptable hash is found in the list, this should 00238 // be a technical impossibility since most of php's hash list is fixed and 00239 // some of the ones we list are available as their own native functions 00240 // But since we already require at least 5.2 and hash() was default in 00241 // 5.1.2 we don't bother falling back to methods like sha1 and md5. 00242 throw new MWException( "Could not find an acceptable hashing function in hash_algos()" ); 00243 } 00244 00251 protected function hashLength() { 00252 if ( is_null( $this->hashLength ) ) { 00253 $this->hashLength = strlen( $this->hash( '' ) ); 00254 } 00255 00256 return $this->hashLength; 00257 } 00258 00266 protected function hash( $data ) { 00267 return hash( $this->hashAlgo(), $data, true ); 00268 } 00269 00278 protected function hmac( $data, $key ) { 00279 return hash_hmac( $this->hashAlgo(), $data, $key, true ); 00280 } 00281 00285 public function realWasStrong() { 00286 if ( is_null( $this->strong ) ) { 00287 throw new MWException( __METHOD__ . ' called before generation of random data' ); 00288 } 00289 00290 return $this->strong; 00291 } 00292 00296 public function realGenerate( $bytes, $forceStrong = false ) { 00297 wfProfileIn( __METHOD__ ); 00298 00299 wfDebug( __METHOD__ . ": Generating cryptographic random bytes for " . 00300 wfGetAllCallers( 5 ) . "\n" ); 00301 00302 $bytes = floor( $bytes ); 00303 static $buffer = ''; 00304 if ( is_null( $this->strong ) ) { 00305 // Set strength to false initially until we know what source data is coming from 00306 $this->strong = true; 00307 } 00308 00309 if ( strlen( $buffer ) < $bytes ) { 00310 // If available make use of mcrypt_create_iv URANDOM source to generate randomness 00311 // On unix-like systems this reads from /dev/urandom but does it without any buffering 00312 // and bypasses openbasedir restrictions, so it's preferable to reading directly 00313 // On Windows starting in PHP 5.3.0 Windows' native CryptGenRandom is used to generate 00314 // entropy so this is also preferable to just trying to read urandom because it may work 00315 // on Windows systems as well. 00316 if ( function_exists( 'mcrypt_create_iv' ) ) { 00317 wfProfileIn( __METHOD__ . '-mcrypt' ); 00318 $rem = $bytes - strlen( $buffer ); 00319 $iv = mcrypt_create_iv( $rem, MCRYPT_DEV_URANDOM ); 00320 if ( $iv === false ) { 00321 wfDebug( __METHOD__ . ": mcrypt_create_iv returned false.\n" ); 00322 } else { 00323 $buffer .= $iv; 00324 wfDebug( __METHOD__ . ": mcrypt_create_iv generated " . strlen( $iv ) . 00325 " bytes of randomness.\n" ); 00326 } 00327 wfProfileOut( __METHOD__ . '-mcrypt' ); 00328 } 00329 } 00330 00331 if ( strlen( $buffer ) < $bytes ) { 00332 // If available make use of openssl's random_pseudo_bytes method to 00333 // attempt to generate randomness. However don't do this on Windows 00334 // with PHP < 5.3.4 due to a bug: 00335 // http://stackoverflow.com/questions/1940168/openssl-random-pseudo-bytes-is-slow-php 00336 // http://git.php.net/?p=php-src.git;a=commitdiff;h=cd62a70863c261b07f6dadedad9464f7e213cad5 00337 if ( function_exists( 'openssl_random_pseudo_bytes' ) 00338 && ( !wfIsWindows() || version_compare( PHP_VERSION, '5.3.4', '>=' ) ) 00339 ) { 00340 wfProfileIn( __METHOD__ . '-openssl' ); 00341 $rem = $bytes - strlen( $buffer ); 00342 $openssl_bytes = openssl_random_pseudo_bytes( $rem, $openssl_strong ); 00343 if ( $openssl_bytes === false ) { 00344 wfDebug( __METHOD__ . ": openssl_random_pseudo_bytes returned false.\n" ); 00345 } else { 00346 $buffer .= $openssl_bytes; 00347 wfDebug( __METHOD__ . ": openssl_random_pseudo_bytes generated " . 00348 strlen( $openssl_bytes ) . " bytes of " . 00349 ( $openssl_strong ? "strong" : "weak" ) . " randomness.\n" ); 00350 } 00351 if ( strlen( $buffer ) >= $bytes ) { 00352 // openssl tells us if the random source was strong, if some of our data was generated 00353 // using it use it's say on whether the randomness is strong 00354 $this->strong = !!$openssl_strong; 00355 } 00356 wfProfileOut( __METHOD__ . '-openssl' ); 00357 } 00358 } 00359 00360 // Only read from urandom if we can control the buffer size or were passed forceStrong 00361 if ( strlen( $buffer ) < $bytes && 00362 ( function_exists( 'stream_set_read_buffer' ) || $forceStrong ) 00363 ) { 00364 wfProfileIn( __METHOD__ . '-fopen-urandom' ); 00365 $rem = $bytes - strlen( $buffer ); 00366 if ( !function_exists( 'stream_set_read_buffer' ) && $forceStrong ) { 00367 wfDebug( __METHOD__ . ": Was forced to read from /dev/urandom " . 00368 "without control over the buffer size.\n" ); 00369 } 00370 // /dev/urandom is generally considered the best possible commonly 00371 // available random source, and is available on most *nix systems. 00372 wfSuppressWarnings(); 00373 $urandom = fopen( "/dev/urandom", "rb" ); 00374 wfRestoreWarnings(); 00375 00376 // Attempt to read all our random data from urandom 00377 // php's fread always does buffered reads based on the stream's chunk_size 00378 // so in reality it will usually read more than the amount of data we're 00379 // asked for and not storing that risks depleting the system's random pool. 00380 // If stream_set_read_buffer is available set the chunk_size to the amount 00381 // of data we need. Otherwise read 8k, php's default chunk_size. 00382 if ( $urandom ) { 00383 // php's default chunk_size is 8k 00384 $chunk_size = 1024 * 8; 00385 if ( function_exists( 'stream_set_read_buffer' ) ) { 00386 // If possible set the chunk_size to the amount of data we need 00387 stream_set_read_buffer( $urandom, $rem ); 00388 $chunk_size = $rem; 00389 } 00390 $random_bytes = fread( $urandom, max( $chunk_size, $rem ) ); 00391 $buffer .= $random_bytes; 00392 fclose( $urandom ); 00393 wfDebug( __METHOD__ . ": /dev/urandom generated " . strlen( $random_bytes ) . 00394 " bytes of randomness.\n" ); 00395 00396 if ( strlen( $buffer ) >= $bytes ) { 00397 // urandom is always strong, set to true if all our data was generated using it 00398 $this->strong = true; 00399 } 00400 } else { 00401 wfDebug( __METHOD__ . ": /dev/urandom could not be opened.\n" ); 00402 } 00403 wfProfileOut( __METHOD__ . '-fopen-urandom' ); 00404 } 00405 00406 // If we cannot use or generate enough data from a secure source 00407 // use this loop to generate a good set of pseudo random data. 00408 // This works by initializing a random state using a pile of unstable data 00409 // and continually shoving it through a hash along with a variable salt. 00410 // We hash the random state with more salt to avoid the state from leaking 00411 // out and being used to predict the /randomness/ that follows. 00412 if ( strlen( $buffer ) < $bytes ) { 00413 wfDebug( __METHOD__ . 00414 ": Falling back to using a pseudo random state to generate randomness.\n" ); 00415 } 00416 while ( strlen( $buffer ) < $bytes ) { 00417 wfProfileIn( __METHOD__ . '-fallback' ); 00418 $buffer .= $this->hmac( $this->randomState(), mt_rand() ); 00419 // This code is never really cryptographically strong, if we use it 00420 // at all, then set strong to false. 00421 $this->strong = false; 00422 wfProfileOut( __METHOD__ . '-fallback' ); 00423 } 00424 00425 // Once the buffer has been filled up with enough random data to fulfill 00426 // the request shift off enough data to handle the request and leave the 00427 // unused portion left inside the buffer for the next request for random data 00428 $generated = substr( $buffer, 0, $bytes ); 00429 $buffer = substr( $buffer, $bytes ); 00430 00431 wfDebug( __METHOD__ . ": " . strlen( $buffer ) . 00432 " bytes of randomness leftover in the buffer.\n" ); 00433 00434 wfProfileOut( __METHOD__ ); 00435 00436 return $generated; 00437 } 00438 00442 public function realGenerateHex( $chars, $forceStrong = false ) { 00443 // hex strings are 2x the length of raw binary so we divide the length in half 00444 // odd numbers will result in a .5 that leads the generate() being 1 character 00445 // short, so we use ceil() to ensure that we always have enough bytes 00446 $bytes = ceil( $chars / 2 ); 00447 // Generate the data and then convert it to a hex string 00448 $hex = bin2hex( $this->generate( $bytes, $forceStrong ) ); 00449 00450 // A bit of paranoia here, the caller asked for a specific length of string 00451 // here, and it's possible (eg when given an odd number) that we may actually 00452 // have at least 1 char more than they asked for. Just in case they made this 00453 // call intending to insert it into a database that does truncation we don't 00454 // want to give them too much and end up with their database and their live 00455 // code having two different values because part of what we gave them is truncated 00456 // hence, we strip out any run of characters longer than what we were asked for. 00457 return substr( $hex, 0, $chars ); 00458 } 00459 00466 protected static function singleton() { 00467 if ( is_null( self::$singleton ) ) { 00468 self::$singleton = new self; 00469 } 00470 00471 return self::$singleton; 00472 } 00473 00481 public static function wasStrong() { 00482 return self::singleton()->realWasStrong(); 00483 } 00484 00497 public static function generate( $bytes, $forceStrong = false ) { 00498 return self::singleton()->realGenerate( $bytes, $forceStrong ); 00499 } 00500 00513 public static function generateHex( $chars, $forceStrong = false ) { 00514 return self::singleton()->realGenerateHex( $chars, $forceStrong ); 00515 } 00516 }