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