MediaWiki  REL1_22
MWCryptRand.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 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 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                 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 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         return $data;
00193     }
00194 
00199     protected function randomState() {
00200         static $state = null;
00201         if ( is_null( $state ) ) {
00202             // Initialize the state with whatever unstable data we can find
00203             // It's important that this data is hashed right afterwards to prevent
00204             // it from being leaked into the output stream
00205             $state = $this->hash( $this->initialRandomState() );
00206         }
00207         // Generate a new random state based on the initial random state or previous
00208         // random state by combining it with clock drift
00209         $state = $this->driftHash( $state );
00210         return $state;
00211     }
00212 
00218     protected function hashAlgo() {
00219         if ( !is_null( $this->algo ) ) {
00220             return $this->algo;
00221         }
00222 
00223         $algos = hash_algos();
00224         $preference = array( 'whirlpool', 'sha256', 'sha1', 'md5' );
00225 
00226         foreach ( $preference as $algorithm ) {
00227             if ( in_array( $algorithm, $algos ) ) {
00228                 $this->algo = $algorithm;
00229                 wfDebug( __METHOD__ . ": Using the {$this->algo} hash algorithm.\n" );
00230                 return $this->algo;
00231             }
00232         }
00233 
00234         // We only reach here if no acceptable hash is found in the list, this should
00235         // be a technical impossibility since most of php's hash list is fixed and
00236         // some of the ones we list are available as their own native functions
00237         // But since we already require at least 5.2 and hash() was default in
00238         // 5.1.2 we don't bother falling back to methods like sha1 and md5.
00239         throw new MWException( "Could not find an acceptable hashing function in hash_algos()" );
00240     }
00241 
00248     protected function hashLength() {
00249         if ( is_null( $this->hashLength ) ) {
00250             $this->hashLength = strlen( $this->hash( '' ) );
00251         }
00252         return $this->hashLength;
00253     }
00254 
00262     protected function hash( $data ) {
00263         return hash( $this->hashAlgo(), $data, true );
00264     }
00265 
00274     protected function hmac( $data, $key ) {
00275         return hash_hmac( $this->hashAlgo(), $data, $key, true );
00276     }
00277 
00281     public function realWasStrong() {
00282         if ( is_null( $this->strong ) ) {
00283             throw new MWException( __METHOD__ . ' called before generation of random data' );
00284         }
00285         return $this->strong;
00286     }
00287 
00291     public function realGenerate( $bytes, $forceStrong = false ) {
00292         wfProfileIn( __METHOD__ );
00293 
00294         wfDebug( __METHOD__ . ": Generating cryptographic random bytes for " . wfGetAllCallers( 5 ) . "\n" );
00295 
00296         $bytes = floor( $bytes );
00297         static $buffer = '';
00298         if ( is_null( $this->strong ) ) {
00299             // Set strength to false initially until we know what source data is coming from
00300             $this->strong = true;
00301         }
00302 
00303         if ( strlen( $buffer ) < $bytes ) {
00304             // If available make use of mcrypt_create_iv URANDOM source to generate randomness
00305             // On unix-like systems this reads from /dev/urandom but does it without any buffering
00306             // and bypasses openbasedir restrictions, so it's preferable to reading directly
00307             // On Windows starting in PHP 5.3.0 Windows' native CryptGenRandom is used to generate
00308             // entropy so this is also preferable to just trying to read urandom because it may work
00309             // on Windows systems as well.
00310             if ( function_exists( 'mcrypt_create_iv' ) ) {
00311                 wfProfileIn( __METHOD__ . '-mcrypt' );
00312                 $rem = $bytes - strlen( $buffer );
00313                 $iv = mcrypt_create_iv( $rem, MCRYPT_DEV_URANDOM );
00314                 if ( $iv === false ) {
00315                     wfDebug( __METHOD__ . ": mcrypt_create_iv returned false.\n" );
00316                 } else {
00317                     $buffer .= $iv;
00318                     wfDebug( __METHOD__ . ": mcrypt_create_iv generated " . strlen( $iv ) . " bytes of randomness.\n" );
00319                 }
00320                 wfProfileOut( __METHOD__ . '-mcrypt' );
00321             }
00322         }
00323 
00324         if ( strlen( $buffer ) < $bytes ) {
00325             // If available make use of openssl's random_pseudo_bytes method to attempt to generate randomness.
00326             // However don't do this on Windows with PHP < 5.3.4 due to a bug:
00327             // http://stackoverflow.com/questions/1940168/openssl-random-pseudo-bytes-is-slow-php
00328             // http://git.php.net/?p=php-src.git;a=commitdiff;h=cd62a70863c261b07f6dadedad9464f7e213cad5
00329             if ( function_exists( 'openssl_random_pseudo_bytes' )
00330                 && ( !wfIsWindows() || version_compare( PHP_VERSION, '5.3.4', '>=' ) )
00331             ) {
00332                 wfProfileIn( __METHOD__ . '-openssl' );
00333                 $rem = $bytes - strlen( $buffer );
00334                 $openssl_bytes = openssl_random_pseudo_bytes( $rem, $openssl_strong );
00335                 if ( $openssl_bytes === false ) {
00336                     wfDebug( __METHOD__ . ": openssl_random_pseudo_bytes returned false.\n" );
00337                 } else {
00338                     $buffer .= $openssl_bytes;
00339                     wfDebug( __METHOD__ . ": openssl_random_pseudo_bytes generated " . strlen( $openssl_bytes ) . " bytes of " . ( $openssl_strong ? "strong" : "weak" ) . " randomness.\n" );
00340                 }
00341                 if ( strlen( $buffer ) >= $bytes ) {
00342                     // openssl tells us if the random source was strong, if some of our data was generated
00343                     // using it use it's say on whether the randomness is strong
00344                     $this->strong = !!$openssl_strong;
00345                 }
00346                 wfProfileOut( __METHOD__ . '-openssl' );
00347             }
00348         }
00349 
00350         // Only read from urandom if we can control the buffer size or were passed forceStrong
00351         if ( strlen( $buffer ) < $bytes && ( function_exists( 'stream_set_read_buffer' ) || $forceStrong ) ) {
00352             wfProfileIn( __METHOD__ . '-fopen-urandom' );
00353             $rem = $bytes - strlen( $buffer );
00354             if ( !function_exists( 'stream_set_read_buffer' ) && $forceStrong ) {
00355                 wfDebug( __METHOD__ . ": Was forced to read from /dev/urandom without control over the buffer size.\n" );
00356             }
00357             // /dev/urandom is generally considered the best possible commonly
00358             // available random source, and is available on most *nix systems.
00359             wfSuppressWarnings();
00360             $urandom = fopen( "/dev/urandom", "rb" );
00361             wfRestoreWarnings();
00362 
00363             // Attempt to read all our random data from urandom
00364             // php's fread always does buffered reads based on the stream's chunk_size
00365             // so in reality it will usually read more than the amount of data we're
00366             // asked for and not storing that risks depleting the system's random pool.
00367             // If stream_set_read_buffer is available set the chunk_size to the amount
00368             // of data we need. Otherwise read 8k, php's default chunk_size.
00369             if ( $urandom ) {
00370                 // php's default chunk_size is 8k
00371                 $chunk_size = 1024 * 8;
00372                 if ( function_exists( 'stream_set_read_buffer' ) ) {
00373                     // If possible set the chunk_size to the amount of data we need
00374                     stream_set_read_buffer( $urandom, $rem );
00375                     $chunk_size = $rem;
00376                 }
00377                 $random_bytes = fread( $urandom, max( $chunk_size, $rem ) );
00378                 $buffer .= $random_bytes;
00379                 fclose( $urandom );
00380                 wfDebug( __METHOD__ . ": /dev/urandom generated " . strlen( $random_bytes ) . " bytes of randomness.\n" );
00381                 if ( strlen( $buffer ) >= $bytes ) {
00382                     // urandom is always strong, set to true if all our data was generated using it
00383                     $this->strong = true;
00384                 }
00385             } else {
00386                 wfDebug( __METHOD__ . ": /dev/urandom could not be opened.\n" );
00387             }
00388             wfProfileOut( __METHOD__ . '-fopen-urandom' );
00389         }
00390 
00391         // If we cannot use or generate enough data from a secure source
00392         // use this loop to generate a good set of pseudo random data.
00393         // This works by initializing a random state using a pile of unstable data
00394         // and continually shoving it through a hash along with a variable salt.
00395         // We hash the random state with more salt to avoid the state from leaking
00396         // out and being used to predict the /randomness/ that follows.
00397         if ( strlen( $buffer ) < $bytes ) {
00398             wfDebug( __METHOD__ . ": Falling back to using a pseudo random state to generate randomness.\n" );
00399         }
00400         while ( strlen( $buffer ) < $bytes ) {
00401             wfProfileIn( __METHOD__ . '-fallback' );
00402             $buffer .= $this->hmac( $this->randomState(), mt_rand() );
00403             // This code is never really cryptographically strong, if we use it
00404             // at all, then set strong to false.
00405             $this->strong = false;
00406             wfProfileOut( __METHOD__ . '-fallback' );
00407         }
00408 
00409         // Once the buffer has been filled up with enough random data to fulfill
00410         // the request shift off enough data to handle the request and leave the
00411         // unused portion left inside the buffer for the next request for random data
00412         $generated = substr( $buffer, 0, $bytes );
00413         $buffer = substr( $buffer, $bytes );
00414 
00415         wfDebug( __METHOD__ . ": " . strlen( $buffer ) . " bytes of randomness leftover in the buffer.\n" );
00416 
00417         wfProfileOut( __METHOD__ );
00418         return $generated;
00419     }
00420 
00424     public function realGenerateHex( $chars, $forceStrong = false ) {
00425         // hex strings are 2x the length of raw binary so we divide the length in half
00426         // odd numbers will result in a .5 that leads the generate() being 1 character
00427         // short, so we use ceil() to ensure that we always have enough bytes
00428         $bytes = ceil( $chars / 2 );
00429         // Generate the data and then convert it to a hex string
00430         $hex = bin2hex( $this->generate( $bytes, $forceStrong ) );
00431         // A bit of paranoia here, the caller asked for a specific length of string
00432         // here, and it's possible (eg when given an odd number) that we may actually
00433         // have at least 1 char more than they asked for. Just in case they made this
00434         // call intending to insert it into a database that does truncation we don't
00435         // want to give them too much and end up with their database and their live
00436         // code having two different values because part of what we gave them is truncated
00437         // hence, we strip out any run of characters longer than what we were asked for.
00438         return substr( $hex, 0, $chars );
00439     }
00440 
00447     protected static function singleton() {
00448         if ( is_null( self::$singleton ) ) {
00449             self::$singleton = new self;
00450         }
00451         return self::$singleton;
00452     }
00453 
00461     public static function wasStrong() {
00462         return self::singleton()->realWasStrong();
00463     }
00464 
00477     public static function generate( $bytes, $forceStrong = false ) {
00478         return self::singleton()->realGenerate( $bytes, $forceStrong );
00479     }
00480 
00493     public static function generateHex( $chars, $forceStrong = false ) {
00494         return self::singleton()->realGenerateHex( $chars, $forceStrong );
00495     }
00496 
00497 }