Language: s/error_log/wfWarn/
[lhc/web/wiklou.git] / includes / utils / MWCryptRand.php
1 <?php
2 /**
3 * A cryptographic random generator class used for generating secret keys
4 *
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.
7 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21 * http://www.gnu.org/copyleft/gpl.html
22 *
23 * @author Daniel Friesen
24 * @file
25 */
26
27 class MWCryptRand {
28 /**
29 * Minimum number of iterations we want to make in our drift calculations.
30 */
31 const MIN_ITERATIONS = 1000;
32
33 /**
34 * Number of milliseconds we want to spend generating each separate byte
35 * of the final generated bytes.
36 * This is used in combination with the hash length to determine the duration
37 * we should spend doing drift calculations.
38 */
39 const MSEC_PER_BYTE = 0.5;
40
41 /**
42 * Singleton instance for public use
43 */
44 protected static $singleton = null;
45
46 /**
47 * The hash algorithm being used
48 */
49 protected $algo = null;
50
51 /**
52 * The number of bytes outputted by the hash algorithm
53 */
54 protected $hashLength = null;
55
56 /**
57 * A boolean indicating whether the previous random generation was done using
58 * cryptographically strong random number generator or not.
59 */
60 protected $strong = null;
61
62 /**
63 * Initialize an initial random state based off of whatever we can find
64 */
65 protected function initialRandomState() {
66 // $_SERVER contains a variety of unstable user and system specific information
67 // It'll vary a little with each page, and vary even more with separate users
68 // It'll also vary slightly across different machines
69 $state = serialize( $_SERVER );
70
71 // To try vary the system information of the state a bit more
72 // by including the system's hostname into the state
73 $state .= wfHostname();
74
75 // Try to gather a little entropy from the different php rand sources
76 $state .= rand() . uniqid( mt_rand(), true );
77
78 // Include some information about the filesystem's current state in the random state
79 $files = array();
80
81 // We know this file is here so grab some info about ourselves
82 $files[] = __FILE__;
83
84 // We must also have a parent folder, and with the usual file structure, a grandparent
85 $files[] = __DIR__;
86 $files[] = dirname( __DIR__ );
87
88 // The config file is likely the most often edited file we know should
89 // be around so include its stat info into the state.
90 // The constant with its location will almost always be defined, as
91 // WebStart.php defines MW_CONFIG_FILE to $IP/LocalSettings.php unless
92 // being configured with MW_CONFIG_CALLBACK (e.g. the installer).
93 if ( defined( 'MW_CONFIG_FILE' ) ) {
94 $files[] = MW_CONFIG_FILE;
95 }
96
97 foreach ( $files as $file ) {
98 wfSuppressWarnings();
99 $stat = stat( $file );
100 wfRestoreWarnings();
101 if ( $stat ) {
102 // stat() duplicates data into numeric and string keys so kill off all the numeric ones
103 foreach ( $stat as $k => $v ) {
104 if ( is_numeric( $k ) ) {
105 unset( $k );
106 }
107 }
108 // The absolute filename itself will differ from install to install so don't leave it out
109 if ( ( $path = realpath( $file ) ) !== false ) {
110 $state .= $path;
111 } else {
112 $state .= $file;
113 }
114 $state .= implode( '', $stat );
115 } else {
116 // The fact that the file isn't there is worth at least a
117 // minuscule amount of entropy.
118 $state .= '0';
119 }
120 }
121
122 // Try and make this a little more unstable by including the varying process
123 // id of the php process we are running inside of if we are able to access it
124 if ( function_exists( 'getmypid' ) ) {
125 $state .= getmypid();
126 }
127
128 // If available try to increase the instability of the data by throwing in
129 // the precise amount of memory that we happen to be using at the moment.
130 if ( function_exists( 'memory_get_usage' ) ) {
131 $state .= memory_get_usage( true );
132 }
133
134 // It's mostly worthless but throw the wiki's id into the data for a little more variance
135 $state .= wfWikiID();
136
137 // If we have a secret key set then throw it into the state as well
138 global $wgSecretKey;
139 if ( $wgSecretKey ) {
140 $state .= $wgSecretKey;
141 }
142
143 return $state;
144 }
145
146 /**
147 * Randomly hash data while mixing in clock drift data for randomness
148 *
149 * @param string $data The data to randomly hash.
150 * @return string The hashed bytes
151 * @author Tim Starling
152 */
153 protected function driftHash( $data ) {
154 // Minimum number of iterations (to avoid slow operations causing the
155 // loop to gather little entropy)
156 $minIterations = self::MIN_ITERATIONS;
157 // Duration of time to spend doing calculations (in seconds)
158 $duration = ( self::MSEC_PER_BYTE / 1000 ) * $this->hashLength();
159 // Create a buffer to use to trigger memory operations
160 $bufLength = 10000000;
161 $buffer = str_repeat( ' ', $bufLength );
162 $bufPos = 0;
163
164 // Iterate for $duration seconds or at least $minIterations number of iterations
165 $iterations = 0;
166 $startTime = microtime( true );
167 $currentTime = $startTime;
168 while ( $iterations < $minIterations || $currentTime - $startTime < $duration ) {
169 // Trigger some memory writing to trigger some bus activity
170 // This may create variance in the time between iterations
171 $bufPos = ( $bufPos + 13 ) % $bufLength;
172 $buffer[$bufPos] = ' ';
173 // Add the drift between this iteration and the last in as entropy
174 $nextTime = microtime( true );
175 $delta = (int)( ( $nextTime - $currentTime ) * 1000000 );
176 $data .= $delta;
177 // Every 100 iterations hash the data and entropy
178 if ( $iterations % 100 === 0 ) {
179 $data = sha1( $data );
180 }
181 $currentTime = $nextTime;
182 $iterations++;
183 }
184 $timeTaken = $currentTime - $startTime;
185 $data = $this->hash( $data );
186
187 wfDebug( __METHOD__ . ": Clock drift calculation " .
188 "(time-taken=" . ( $timeTaken * 1000 ) . "ms, " .
189 "iterations=$iterations, " .
190 "time-per-iteration=" . ( $timeTaken / $iterations * 1e6 ) . "us)\n" );
191
192 return $data;
193 }
194
195 /**
196 * Return a rolling random state initially build using data from unstable sources
197 * @return string A new weak random state
198 */
199 protected function randomState() {
200 static $state = null;
201 if ( is_null( $state ) ) {
202 // Initialize the state with whatever unstable data we can find
203 // It's important that this data is hashed right afterwards to prevent
204 // it from being leaked into the output stream
205 $state = $this->hash( $this->initialRandomState() );
206 }
207 // Generate a new random state based on the initial random state or previous
208 // random state by combining it with clock drift
209 $state = $this->driftHash( $state );
210
211 return $state;
212 }
213
214 /**
215 * Decide on the best acceptable hash algorithm we have available for hash()
216 * @throws MWException
217 * @return string A hash algorithm
218 */
219 protected function hashAlgo() {
220 if ( !is_null( $this->algo ) ) {
221 return $this->algo;
222 }
223
224 $algos = hash_algos();
225 $preference = array( 'whirlpool', 'sha256', 'sha1', 'md5' );
226
227 foreach ( $preference as $algorithm ) {
228 if ( in_array( $algorithm, $algos ) ) {
229 $this->algo = $algorithm;
230 wfDebug( __METHOD__ . ": Using the {$this->algo} hash algorithm.\n" );
231
232 return $this->algo;
233 }
234 }
235
236 // We only reach here if no acceptable hash is found in the list, this should
237 // be a technical impossibility since most of php's hash list is fixed and
238 // some of the ones we list are available as their own native functions
239 // But since we already require at least 5.2 and hash() was default in
240 // 5.1.2 we don't bother falling back to methods like sha1 and md5.
241 throw new MWException( "Could not find an acceptable hashing function in hash_algos()" );
242 }
243
244 /**
245 * Return the byte-length output of the hash algorithm we are
246 * using in self::hash and self::hmac.
247 *
248 * @return int Number of bytes the hash outputs
249 */
250 protected function hashLength() {
251 if ( is_null( $this->hashLength ) ) {
252 $this->hashLength = strlen( $this->hash( '' ) );
253 }
254
255 return $this->hashLength;
256 }
257
258 /**
259 * Generate an acceptably unstable one-way-hash of some text
260 * making use of the best hash algorithm that we have available.
261 *
262 * @param string $data
263 * @return string A raw hash of the data
264 */
265 protected function hash( $data ) {
266 return hash( $this->hashAlgo(), $data, true );
267 }
268
269 /**
270 * Generate an acceptably unstable one-way-hmac of some text
271 * making use of the best hash algorithm that we have available.
272 *
273 * @param string $data
274 * @param string $key
275 * @return string A raw hash of the data
276 */
277 protected function hmac( $data, $key ) {
278 return hash_hmac( $this->hashAlgo(), $data, $key, true );
279 }
280
281 /**
282 * @see self::wasStrong()
283 */
284 public function realWasStrong() {
285 if ( is_null( $this->strong ) ) {
286 throw new MWException( __METHOD__ . ' called before generation of random data' );
287 }
288
289 return $this->strong;
290 }
291
292 /**
293 * @see self::generate()
294 */
295 public function realGenerate( $bytes, $forceStrong = false ) {
296 wfProfileIn( __METHOD__ );
297
298 wfDebug( __METHOD__ . ": Generating cryptographic random bytes for " .
299 wfGetAllCallers( 5 ) . "\n" );
300
301 $bytes = floor( $bytes );
302 static $buffer = '';
303 if ( is_null( $this->strong ) ) {
304 // Set strength to false initially until we know what source data is coming from
305 $this->strong = true;
306 }
307
308 if ( strlen( $buffer ) < $bytes ) {
309 // If available make use of mcrypt_create_iv URANDOM source to generate randomness
310 // On unix-like systems this reads from /dev/urandom but does it without any buffering
311 // and bypasses openbasedir restrictions, so it's preferable to reading directly
312 // On Windows starting in PHP 5.3.0 Windows' native CryptGenRandom is used to generate
313 // entropy so this is also preferable to just trying to read urandom because it may work
314 // on Windows systems as well.
315 if ( function_exists( 'mcrypt_create_iv' ) ) {
316 wfProfileIn( __METHOD__ . '-mcrypt' );
317 $rem = $bytes - strlen( $buffer );
318 $iv = mcrypt_create_iv( $rem, MCRYPT_DEV_URANDOM );
319 if ( $iv === false ) {
320 wfDebug( __METHOD__ . ": mcrypt_create_iv returned false.\n" );
321 } else {
322 $buffer .= $iv;
323 wfDebug( __METHOD__ . ": mcrypt_create_iv generated " . strlen( $iv ) .
324 " bytes of randomness.\n" );
325 }
326 wfProfileOut( __METHOD__ . '-mcrypt' );
327 }
328 }
329
330 if ( strlen( $buffer ) < $bytes ) {
331 // If available make use of openssl's random_pseudo_bytes method to
332 // attempt to generate randomness. However don't do this on Windows
333 // with PHP < 5.3.4 due to a bug:
334 // http://stackoverflow.com/questions/1940168/openssl-random-pseudo-bytes-is-slow-php
335 // http://git.php.net/?p=php-src.git;a=commitdiff;h=cd62a70863c261b07f6dadedad9464f7e213cad5
336 if ( function_exists( 'openssl_random_pseudo_bytes' )
337 && ( !wfIsWindows() || version_compare( PHP_VERSION, '5.3.4', '>=' ) )
338 ) {
339 wfProfileIn( __METHOD__ . '-openssl' );
340 $rem = $bytes - strlen( $buffer );
341 $openssl_bytes = openssl_random_pseudo_bytes( $rem, $openssl_strong );
342 if ( $openssl_bytes === false ) {
343 wfDebug( __METHOD__ . ": openssl_random_pseudo_bytes returned false.\n" );
344 } else {
345 $buffer .= $openssl_bytes;
346 wfDebug( __METHOD__ . ": openssl_random_pseudo_bytes generated " .
347 strlen( $openssl_bytes ) . " bytes of " .
348 ( $openssl_strong ? "strong" : "weak" ) . " randomness.\n" );
349 }
350 if ( strlen( $buffer ) >= $bytes ) {
351 // openssl tells us if the random source was strong, if some of our data was generated
352 // using it use it's say on whether the randomness is strong
353 $this->strong = !!$openssl_strong;
354 }
355 wfProfileOut( __METHOD__ . '-openssl' );
356 }
357 }
358
359 // Only read from urandom if we can control the buffer size or were passed forceStrong
360 if ( strlen( $buffer ) < $bytes &&
361 ( function_exists( 'stream_set_read_buffer' ) || $forceStrong )
362 ) {
363 wfProfileIn( __METHOD__ . '-fopen-urandom' );
364 $rem = $bytes - strlen( $buffer );
365 if ( !function_exists( 'stream_set_read_buffer' ) && $forceStrong ) {
366 wfDebug( __METHOD__ . ": Was forced to read from /dev/urandom " .
367 "without control over the buffer size.\n" );
368 }
369 // /dev/urandom is generally considered the best possible commonly
370 // available random source, and is available on most *nix systems.
371 wfSuppressWarnings();
372 $urandom = fopen( "/dev/urandom", "rb" );
373 wfRestoreWarnings();
374
375 // Attempt to read all our random data from urandom
376 // php's fread always does buffered reads based on the stream's chunk_size
377 // so in reality it will usually read more than the amount of data we're
378 // asked for and not storing that risks depleting the system's random pool.
379 // If stream_set_read_buffer is available set the chunk_size to the amount
380 // of data we need. Otherwise read 8k, php's default chunk_size.
381 if ( $urandom ) {
382 // php's default chunk_size is 8k
383 $chunk_size = 1024 * 8;
384 if ( function_exists( 'stream_set_read_buffer' ) ) {
385 // If possible set the chunk_size to the amount of data we need
386 stream_set_read_buffer( $urandom, $rem );
387 $chunk_size = $rem;
388 }
389 $random_bytes = fread( $urandom, max( $chunk_size, $rem ) );
390 $buffer .= $random_bytes;
391 fclose( $urandom );
392 wfDebug( __METHOD__ . ": /dev/urandom generated " . strlen( $random_bytes ) .
393 " bytes of randomness.\n" );
394
395 if ( strlen( $buffer ) >= $bytes ) {
396 // urandom is always strong, set to true if all our data was generated using it
397 $this->strong = true;
398 }
399 } else {
400 wfDebug( __METHOD__ . ": /dev/urandom could not be opened.\n" );
401 }
402 wfProfileOut( __METHOD__ . '-fopen-urandom' );
403 }
404
405 // If we cannot use or generate enough data from a secure source
406 // use this loop to generate a good set of pseudo random data.
407 // This works by initializing a random state using a pile of unstable data
408 // and continually shoving it through a hash along with a variable salt.
409 // We hash the random state with more salt to avoid the state from leaking
410 // out and being used to predict the /randomness/ that follows.
411 if ( strlen( $buffer ) < $bytes ) {
412 wfDebug( __METHOD__ .
413 ": Falling back to using a pseudo random state to generate randomness.\n" );
414 }
415 while ( strlen( $buffer ) < $bytes ) {
416 wfProfileIn( __METHOD__ . '-fallback' );
417 $buffer .= $this->hmac( $this->randomState(), mt_rand() );
418 // This code is never really cryptographically strong, if we use it
419 // at all, then set strong to false.
420 $this->strong = false;
421 wfProfileOut( __METHOD__ . '-fallback' );
422 }
423
424 // Once the buffer has been filled up with enough random data to fulfill
425 // the request shift off enough data to handle the request and leave the
426 // unused portion left inside the buffer for the next request for random data
427 $generated = substr( $buffer, 0, $bytes );
428 $buffer = substr( $buffer, $bytes );
429
430 wfDebug( __METHOD__ . ": " . strlen( $buffer ) .
431 " bytes of randomness leftover in the buffer.\n" );
432
433 wfProfileOut( __METHOD__ );
434
435 return $generated;
436 }
437
438 /**
439 * @see self::generateHex()
440 */
441 public function realGenerateHex( $chars, $forceStrong = false ) {
442 // hex strings are 2x the length of raw binary so we divide the length in half
443 // odd numbers will result in a .5 that leads the generate() being 1 character
444 // short, so we use ceil() to ensure that we always have enough bytes
445 $bytes = ceil( $chars / 2 );
446 // Generate the data and then convert it to a hex string
447 $hex = bin2hex( $this->generate( $bytes, $forceStrong ) );
448
449 // A bit of paranoia here, the caller asked for a specific length of string
450 // here, and it's possible (eg when given an odd number) that we may actually
451 // have at least 1 char more than they asked for. Just in case they made this
452 // call intending to insert it into a database that does truncation we don't
453 // want to give them too much and end up with their database and their live
454 // code having two different values because part of what we gave them is truncated
455 // hence, we strip out any run of characters longer than what we were asked for.
456 return substr( $hex, 0, $chars );
457 }
458
459 /** Publicly exposed static methods **/
460
461 /**
462 * Return a singleton instance of MWCryptRand
463 * @return MWCryptRand
464 */
465 protected static function singleton() {
466 if ( is_null( self::$singleton ) ) {
467 self::$singleton = new self;
468 }
469
470 return self::$singleton;
471 }
472
473 /**
474 * Return a boolean indicating whether or not the source used for cryptographic
475 * random bytes generation in the previously run generate* call
476 * was cryptographically strong.
477 *
478 * @return bool Returns true if the source was strong, false if not.
479 */
480 public static function wasStrong() {
481 return self::singleton()->realWasStrong();
482 }
483
484 /**
485 * Generate a run of (ideally) cryptographically random data and return
486 * it in raw binary form.
487 * You can use MWCryptRand::wasStrong() if you wish to know if the source used
488 * was cryptographically strong.
489 *
490 * @param int $bytes The number of bytes of random data to generate
491 * @param bool $forceStrong Pass true if you want generate to prefer cryptographically
492 * strong sources of entropy even if reading from them may steal
493 * more entropy from the system than optimal.
494 * @return string Raw binary random data
495 */
496 public static function generate( $bytes, $forceStrong = false ) {
497 return self::singleton()->realGenerate( $bytes, $forceStrong );
498 }
499
500 /**
501 * Generate a run of (ideally) cryptographically random data and return
502 * it in hexadecimal string format.
503 * You can use MWCryptRand::wasStrong() if you wish to know if the source used
504 * was cryptographically strong.
505 *
506 * @param int $chars The number of hex chars of random data to generate
507 * @param bool $forceStrong Pass true if you want generate to prefer cryptographically
508 * strong sources of entropy even if reading from them may steal
509 * more entropy from the system than optimal.
510 * @return string Hexadecimal random data
511 */
512 public static function generateHex( $chars, $forceStrong = false ) {
513 return self::singleton()->realGenerateHex( $chars, $forceStrong );
514 }
515 }