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