Merge "Use CamelCase in both ConfirmEmail and InvalidateEmail page names."
[mediawiki.git] / includes / CryptRand.php
blob95905fb6173398ab5eab7fa7aaf81b4edc06c89e
1 <?php
2 /**
3 * A cryptographic random generator class used for generating secret keys
5 * This is based in part on Drupal code as well as what we used in our own code
6 * prior to introduction of this class.
8 * @author Daniel Friesen
9 * @file
12 class MWCryptRand {
14 /**
15 * Minimum number of iterations we want to make in our drift calculations.
17 const MIN_ITERATIONS = 1000;
19 /**
20 * Number of milliseconds we want to spend generating each separate byte
21 * of the final generated bytes.
22 * This is used in combination with the hash length to determine the duration
23 * we should spend doing drift calculations.
25 const MSEC_PER_BYTE = 0.5;
27 /**
28 * Singleton instance for public use
30 protected static $singleton = null;
32 /**
33 * The hash algorithm being used
35 protected $algo = null;
37 /**
38 * The number of bytes outputted by the hash algorithm
40 protected $hashLength = null;
42 /**
43 * A boolean indicating whether the previous random generation was done using
44 * cryptographically strong random number generator or not.
46 protected $strong = null;
48 /**
49 * Initialize an initial random state based off of whatever we can find
51 protected function initialRandomState() {
52 // $_SERVER contains a variety of unstable user and system specific information
53 // It'll vary a little with each page, and vary even more with separate users
54 // It'll also vary slightly across different machines
55 $state = serialize( $_SERVER );
57 // To try vary the system information of the state a bit more
58 // by including the system's hostname into the state
59 $state .= wfHostname();
61 // Try to gather a little entropy from the different php rand sources
62 $state .= rand() . uniqid( mt_rand(), true );
64 // Include some information about the filesystem's current state in the random state
65 $files = array();
67 // We know this file is here so grab some info about ourself
68 $files[] = __FILE__;
70 // We must also have a parent folder, and with the usual file structure, a grandparent
71 $files[] = dirname( __FILE__ );
72 $files[] = dirname( dirname( __FILE__ ) );
74 // The config file is likely the most often edited file we know should be around
75 // so include its stat info into the state.
76 // The constant with its location will almost always be defined, as WebStart.php defines
77 // MW_CONFIG_FILE to $IP/LocalSettings.php unless being configured with MW_CONFIG_CALLBACK (eg. the installer)
78 if ( defined( 'MW_CONFIG_FILE' ) ) {
79 $files[] = MW_CONFIG_FILE;
82 foreach ( $files as $file ) {
83 wfSuppressWarnings();
84 $stat = stat( $file );
85 wfRestoreWarnings();
86 if ( $stat ) {
87 // stat() duplicates data into numeric and string keys so kill off all the numeric ones
88 foreach ( $stat as $k => $v ) {
89 if ( is_numeric( $k ) ) {
90 unset( $k );
93 // The absolute filename itself will differ from install to install so don't leave it out
94 $state .= realpath( $file );
95 $state .= implode( '', $stat );
96 } else {
97 // The fact that the file isn't there is worth at least a
98 // minuscule amount of entropy.
99 $state .= '0';
103 // Try and make this a little more unstable by including the varying process
104 // id of the php process we are running inside of if we are able to access it
105 if ( function_exists( 'getmypid' ) ) {
106 $state .= getmypid();
109 // If available try to increase the instability of the data by throwing in
110 // the precise amount of memory that we happen to be using at the moment.
111 if ( function_exists( 'memory_get_usage' ) ) {
112 $state .= memory_get_usage( true );
115 // It's mostly worthless but throw the wiki's id into the data for a little more variance
116 $state .= wfWikiID();
118 // If we have a secret key or proxy key set then throw it into the state as well
119 global $wgSecretKey, $wgProxyKey;
120 if ( $wgSecretKey ) {
121 $state .= $wgSecretKey;
122 } elseif ( $wgProxyKey ) {
123 $state .= $wgProxyKey;
126 return $state;
130 * Randomly hash data while mixing in clock drift data for randomness
132 * @param $data string The data to randomly hash.
133 * @return String The hashed bytes
134 * @author Tim Starling
136 protected function driftHash( $data ) {
137 // Minimum number of iterations (to avoid slow operations causing the loop to gather little entropy)
138 $minIterations = self::MIN_ITERATIONS;
139 // Duration of time to spend doing calculations (in seconds)
140 $duration = ( self::MSEC_PER_BYTE / 1000 ) * $this->hashLength();
141 // Create a buffer to use to trigger memory operations
142 $bufLength = 10000000;
143 $buffer = str_repeat( ' ', $bufLength );
144 $bufPos = 0;
146 // Iterate for $duration seconds or at least $minIerations number of iterations
147 $iterations = 0;
148 $startTime = microtime( true );
149 $currentTime = $startTime;
150 while ( $iterations < $minIterations || $currentTime - $startTime < $duration ) {
151 // Trigger some memory writing to trigger some bus activity
152 // This may create variance in the time between iterations
153 $bufPos = ( $bufPos + 13 ) % $bufLength;
154 $buffer[$bufPos] = ' ';
155 // Add the drift between this iteration and the last in as entropy
156 $nextTime = microtime( true );
157 $delta = (int)( ( $nextTime - $currentTime ) * 1000000 );
158 $data .= $delta;
159 // Every 100 iterations hash the data and entropy
160 if ( $iterations % 100 === 0 ) {
161 $data = sha1( $data );
163 $currentTime = $nextTime;
164 $iterations++;
166 $timeTaken = $currentTime - $startTime;
167 $data = $this->hash( $data );
169 wfDebug( __METHOD__ . ": Clock drift calculation " .
170 "(time-taken=" . ( $timeTaken * 1000 ) . "ms, " .
171 "iterations=$iterations, " .
172 "time-per-iteration=" . ( $timeTaken / $iterations * 1e6 ) . "us)\n" );
173 return $data;
177 * Return a rolling random state initially build using data from unstable sources
178 * @return string A new weak random state
180 protected function randomState() {
181 static $state = null;
182 if ( is_null( $state ) ) {
183 // Initialize the state with whatever unstable data we can find
184 // It's important that this data is hashed right afterwards to prevent
185 // it from being leaked into the output stream
186 $state = $this->hash( $this->initialRandomState() );
188 // Generate a new random state based on the initial random state or previous
189 // random state by combining it with clock drift
190 $state = $this->driftHash( $state );
191 return $state;
195 * Decide on the best acceptable hash algorithm we have available for hash()
196 * @throws MWException
197 * @return String A hash algorithm
199 protected function hashAlgo() {
200 if ( !is_null( $this->algo ) ) {
201 return $this->algo;
204 $algos = hash_algos();
205 $preference = array( 'whirlpool', 'sha256', 'sha1', 'md5' );
207 foreach ( $preference as $algorithm ) {
208 if ( in_array( $algorithm, $algos ) ) {
209 $this->algo = $algorithm;
210 wfDebug( __METHOD__ . ": Using the {$this->algo} hash algorithm.\n" );
211 return $this->algo;
215 // We only reach here if no acceptable hash is found in the list, this should
216 // be a technical impossibility since most of php's hash list is fixed and
217 // some of the ones we list are available as their own native functions
218 // But since we already require at least 5.2 and hash() was default in
219 // 5.1.2 we don't bother falling back to methods like sha1 and md5.
220 throw new MWException( "Could not find an acceptable hashing function in hash_algos()" );
224 * Return the byte-length output of the hash algorithm we are
225 * using in self::hash and self::hmac.
227 * @return int Number of bytes the hash outputs
229 protected function hashLength() {
230 if ( is_null( $this->hashLength ) ) {
231 $this->hashLength = strlen( $this->hash( '' ) );
233 return $this->hashLength;
237 * Generate an acceptably unstable one-way-hash of some text
238 * making use of the best hash algorithm that we have available.
240 * @param $data string
241 * @return String A raw hash of the data
243 protected function hash( $data ) {
244 return hash( $this->hashAlgo(), $data, true );
248 * Generate an acceptably unstable one-way-hmac of some text
249 * making use of the best hash algorithm that we have available.
251 * @param $data string
252 * @param $key string
253 * @return String A raw hash of the data
255 protected function hmac( $data, $key ) {
256 return hash_hmac( $this->hashAlgo(), $data, $key, true );
260 * @see self::wasStrong()
262 public function realWasStrong() {
263 if ( is_null( $this->strong ) ) {
264 throw new MWException( __METHOD__ . ' called before generation of random data' );
266 return $this->strong;
270 * @see self::generate()
272 public function realGenerate( $bytes, $forceStrong = false ) {
273 wfProfileIn( __METHOD__ );
275 wfDebug( __METHOD__ . ": Generating cryptographic random bytes for " . wfGetAllCallers( 5 ) . "\n" );
277 $bytes = floor( $bytes );
278 static $buffer = '';
279 if ( is_null( $this->strong ) ) {
280 // Set strength to false initially until we know what source data is coming from
281 $this->strong = true;
284 if ( strlen( $buffer ) < $bytes ) {
285 // If available make use of mcrypt_create_iv URANDOM source to generate randomness
286 // On unix-like systems this reads from /dev/urandom but does it without any buffering
287 // and bypasses openbasedir restrictions, so it's preferable to reading directly
288 // On Windows starting in PHP 5.3.0 Windows' native CryptGenRandom is used to generate
289 // entropy so this is also preferable to just trying to read urandom because it may work
290 // on Windows systems as well.
291 if ( function_exists( 'mcrypt_create_iv' ) ) {
292 wfProfileIn( __METHOD__ . '-mcrypt' );
293 $rem = $bytes - strlen( $buffer );
294 $iv = mcrypt_create_iv( $rem, MCRYPT_DEV_URANDOM );
295 if ( $iv === false ) {
296 wfDebug( __METHOD__ . ": mcrypt_create_iv returned false.\n" );
297 } else {
298 $buffer .= $iv;
299 wfDebug( __METHOD__ . ": mcrypt_create_iv generated " . strlen( $iv ) . " bytes of randomness.\n" );
301 wfProfileOut( __METHOD__ . '-mcrypt' );
305 if ( strlen( $buffer ) < $bytes ) {
306 // If available make use of openssl's random_pseudo_bytes method to attempt to generate randomness.
307 // However don't do this on Windows with PHP < 5.3.4 due to a bug:
308 // http://stackoverflow.com/questions/1940168/openssl-random-pseudo-bytes-is-slow-php
309 // http://git.php.net/?p=php-src.git;a=commitdiff;h=cd62a70863c261b07f6dadedad9464f7e213cad5
310 if ( function_exists( 'openssl_random_pseudo_bytes' )
311 && ( !wfIsWindows() || version_compare( PHP_VERSION, '5.3.4', '>=' ) )
313 wfProfileIn( __METHOD__ . '-openssl' );
314 $rem = $bytes - strlen( $buffer );
315 $openssl_bytes = openssl_random_pseudo_bytes( $rem, $openssl_strong );
316 if ( $openssl_bytes === false ) {
317 wfDebug( __METHOD__ . ": openssl_random_pseudo_bytes returned false.\n" );
318 } else {
319 $buffer .= $openssl_bytes;
320 wfDebug( __METHOD__ . ": openssl_random_pseudo_bytes generated " . strlen( $openssl_bytes ) . " bytes of " . ( $openssl_strong ? "strong" : "weak" ) . " randomness.\n" );
322 if ( strlen( $buffer ) >= $bytes ) {
323 // openssl tells us if the random source was strong, if some of our data was generated
324 // using it use it's say on whether the randomness is strong
325 $this->strong = !!$openssl_strong;
327 wfProfileOut( __METHOD__ . '-openssl' );
331 // Only read from urandom if we can control the buffer size or were passed forceStrong
332 if ( strlen( $buffer ) < $bytes && ( function_exists( 'stream_set_read_buffer' ) || $forceStrong ) ) {
333 wfProfileIn( __METHOD__ . '-fopen-urandom' );
334 $rem = $bytes - strlen( $buffer );
335 if ( !function_exists( 'stream_set_read_buffer' ) && $forceStrong ) {
336 wfDebug( __METHOD__ . ": Was forced to read from /dev/urandom without control over the buffer size.\n" );
338 // /dev/urandom is generally considered the best possible commonly
339 // available random source, and is available on most *nix systems.
340 wfSuppressWarnings();
341 $urandom = fopen( "/dev/urandom", "rb" );
342 wfRestoreWarnings();
344 // Attempt to read all our random data from urandom
345 // php's fread always does buffered reads based on the stream's chunk_size
346 // so in reality it will usually read more than the amount of data we're
347 // asked for and not storing that risks depleting the system's random pool.
348 // If stream_set_read_buffer is available set the chunk_size to the amount
349 // of data we need. Otherwise read 8k, php's default chunk_size.
350 if ( $urandom ) {
351 // php's default chunk_size is 8k
352 $chunk_size = 1024 * 8;
353 if ( function_exists( 'stream_set_read_buffer' ) ) {
354 // If possible set the chunk_size to the amount of data we need
355 stream_set_read_buffer( $urandom, $rem );
356 $chunk_size = $rem;
358 $random_bytes = fread( $urandom, max( $chunk_size, $rem ) );
359 $buffer .= $random_bytes;
360 fclose( $urandom );
361 wfDebug( __METHOD__ . ": /dev/urandom generated " . strlen( $random_bytes ) . " bytes of randomness.\n" );
362 if ( strlen( $buffer ) >= $bytes ) {
363 // urandom is always strong, set to true if all our data was generated using it
364 $this->strong = true;
366 } else {
367 wfDebug( __METHOD__ . ": /dev/urandom could not be opened.\n" );
369 wfProfileOut( __METHOD__ . '-fopen-urandom' );
372 // If we cannot use or generate enough data from a secure source
373 // use this loop to generate a good set of pseudo random data.
374 // This works by initializing a random state using a pile of unstable data
375 // and continually shoving it through a hash along with a variable salt.
376 // We hash the random state with more salt to avoid the state from leaking
377 // out and being used to predict the /randomness/ that follows.
378 if ( strlen( $buffer ) < $bytes ) {
379 wfDebug( __METHOD__ . ": Falling back to using a pseudo random state to generate randomness.\n" );
381 while ( strlen( $buffer ) < $bytes ) {
382 wfProfileIn( __METHOD__ . '-fallback' );
383 $buffer .= $this->hmac( $this->randomState(), mt_rand() );
384 // This code is never really cryptographically strong, if we use it
385 // at all, then set strong to false.
386 $this->strong = false;
387 wfProfileOut( __METHOD__ . '-fallback' );
390 // Once the buffer has been filled up with enough random data to fulfill
391 // the request shift off enough data to handle the request and leave the
392 // unused portion left inside the buffer for the next request for random data
393 $generated = substr( $buffer, 0, $bytes );
394 $buffer = substr( $buffer, $bytes );
396 wfDebug( __METHOD__ . ": " . strlen( $buffer ) . " bytes of randomness leftover in the buffer.\n" );
398 wfProfileOut( __METHOD__ );
399 return $generated;
403 * @see self::generateHex()
405 public function realGenerateHex( $chars, $forceStrong = false ) {
406 // hex strings are 2x the length of raw binary so we divide the length in half
407 // odd numbers will result in a .5 that leads the generate() being 1 character
408 // short, so we use ceil() to ensure that we always have enough bytes
409 $bytes = ceil( $chars / 2 );
410 // Generate the data and then convert it to a hex string
411 $hex = bin2hex( $this->generate( $bytes, $forceStrong ) );
412 // A bit of paranoia here, the caller asked for a specific length of string
413 // here, and it's possible (eg when given an odd number) that we may actually
414 // have at least 1 char more than they asked for. Just in case they made this
415 // call intending to insert it into a database that does truncation we don't
416 // want to give them too much and end up with their database and their live
417 // code having two different values because part of what we gave them is truncated
418 // hence, we strip out any run of characters longer than what we were asked for.
419 return substr( $hex, 0, $chars );
422 /** Publicly exposed static methods **/
425 * Return a singleton instance of MWCryptRand
426 * @return MWCryptRand
428 protected static function singleton() {
429 if ( is_null( self::$singleton ) ) {
430 self::$singleton = new self;
432 return self::$singleton;
436 * Return a boolean indicating whether or not the source used for cryptographic
437 * random bytes generation in the previously run generate* call
438 * was cryptographically strong.
440 * @return bool Returns true if the source was strong, false if not.
442 public static function wasStrong() {
443 return self::singleton()->realWasStrong();
447 * Generate a run of (ideally) cryptographically random data and return
448 * it in raw binary form.
449 * You can use MWCryptRand::wasStrong() if you wish to know if the source used
450 * was cryptographically strong.
452 * @param $bytes int the number of bytes of random data to generate
453 * @param $forceStrong bool Pass true if you want generate to prefer cryptographically
454 * strong sources of entropy even if reading from them may steal
455 * more entropy from the system than optimal.
456 * @return String Raw binary random data
458 public static function generate( $bytes, $forceStrong = false ) {
459 return self::singleton()->realGenerate( $bytes, $forceStrong );
463 * Generate a run of (ideally) cryptographically random data and return
464 * it in hexadecimal string format.
465 * You can use MWCryptRand::wasStrong() if you wish to know if the source used
466 * was cryptographically strong.
468 * @param $chars int the number of hex chars of random data to generate
469 * @param $forceStrong bool Pass true if you want generate to prefer cryptographically
470 * strong sources of entropy even if reading from them may steal
471 * more entropy from the system than optimal.
472 * @return String Hexadecimal random data
474 public static function generateHex( $chars, $forceStrong = false ) {
475 return self::singleton()->realGenerateHex( $chars, $forceStrong );