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