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