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