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 * 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.
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.
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
23 * @author Daniel Friesen
26 use Psr\Log\LoggerInterface
;
30 * Minimum number of iterations we want to make in our drift calculations.
32 const MIN_ITERATIONS
= 1000;
35 * Number of milliseconds we want to spend generating each separate byte
36 * of the final generated bytes.
37 * This is used in combination with the hash length to determine the duration
38 * we should spend doing drift calculations.
40 const MSEC_PER_BYTE
= 0.5;
43 * A boolean indicating whether the previous random generation was done using
44 * cryptographically strong random number generator or not.
46 protected $strong = null;
49 * List of functions to call to generate some random state
53 protected $randomFuncs = [];
56 * List of files to generate some random state from
60 protected $randomFiles = [];
63 * @var LoggerInterface
67 public function __construct( array $randomFuncs, array $randomFiles, LoggerInterface
$logger ) {
68 $this->randomFuncs
= $randomFuncs;
69 $this->randomFiles
= $randomFiles;
70 $this->logger
= $logger;
74 * Initialize an initial random state based off of whatever we can find
77 protected function initialRandomState() {
78 // $_SERVER contains a variety of unstable user and system specific information
79 // It'll vary a little with each page, and vary even more with separate users
80 // It'll also vary slightly across different machines
81 $state = serialize( $_SERVER );
83 // Try to gather a little entropy from the different php rand sources
84 $state .= rand() . uniqid( mt_rand(), true );
86 // Include some information about the filesystem's current state in the random state
87 $files = $this->randomFiles
;
89 // We know this file is here so grab some info about ourselves
92 // We must also have a parent folder, and with the usual file structure, a grandparent
94 $files[] = dirname( __DIR__
);
96 foreach ( $files as $file ) {
97 MediaWiki\
suppressWarnings();
98 $stat = stat( $file );
99 MediaWiki\restoreWarnings
();
101 // stat() duplicates data into numeric and string keys so kill off all the numeric ones
102 foreach ( $stat as $k => $v ) {
103 if ( is_numeric( $k ) ) {
107 // The absolute filename itself will differ from install to install so don't leave it out
108 $path = realpath( $file );
109 if ( $path !== false ) {
114 $state .= implode( '', $stat );
116 // The fact that the file isn't there is worth at least a
117 // minuscule amount of entropy.
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();
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 );
134 foreach ( $this->randomFuncs
as $randomFunc ) {
135 $state .= call_user_func( $randomFunc );
142 * Randomly hash data while mixing in clock drift data for randomness
144 * @param string $data The data to randomly hash.
145 * @return string The hashed bytes
146 * @author Tim Starling
148 protected function driftHash( $data ) {
149 // Minimum number of iterations (to avoid slow operations causing the
150 // loop to gather little entropy)
151 $minIterations = self
::MIN_ITERATIONS
;
152 // Duration of time to spend doing calculations (in seconds)
153 $duration = ( self
::MSEC_PER_BYTE
/ 1000 ) * MWCryptHash
::hashLength();
154 // Create a buffer to use to trigger memory operations
155 $bufLength = 10000000;
156 $buffer = str_repeat( ' ', $bufLength );
159 // Iterate for $duration seconds or at least $minIterations number of iterations
161 $startTime = microtime( true );
162 $currentTime = $startTime;
163 while ( $iterations < $minIterations ||
$currentTime - $startTime < $duration ) {
164 // Trigger some memory writing to trigger some bus activity
165 // This may create variance in the time between iterations
166 $bufPos = ( $bufPos +
13 ) %
$bufLength;
167 $buffer[$bufPos] = ' ';
168 // Add the drift between this iteration and the last in as entropy
169 $nextTime = microtime( true );
170 $delta = (int)( ( $nextTime - $currentTime ) * 1000000 );
172 // Every 100 iterations hash the data and entropy
173 if ( $iterations %
100 === 0 ) {
174 $data = sha1( $data );
176 $currentTime = $nextTime;
179 $timeTaken = $currentTime - $startTime;
180 $data = MWCryptHash
::hash( $data );
182 $this->logger
->debug( "Clock drift calculation " .
183 "(time-taken=" . ( $timeTaken * 1000 ) . "ms, " .
184 "iterations=$iterations, " .
185 "time-per-iteration=" . ( $timeTaken / $iterations * 1e6
) . "us)\n" );
191 * Return a rolling random state initially build using data from unstable sources
192 * @return string A new weak random state
194 protected function randomState() {
195 static $state = null;
196 if ( is_null( $state ) ) {
197 // Initialize the state with whatever unstable data we can find
198 // It's important that this data is hashed right afterwards to prevent
199 // it from being leaked into the output stream
200 $state = MWCryptHash
::hash( $this->initialRandomState() );
202 // Generate a new random state based on the initial random state or previous
203 // random state by combining it with clock drift
204 $state = $this->driftHash( $state );
210 * Return a boolean indicating whether or not the source used for cryptographic
211 * random bytes generation in the previously run generate* call
212 * was cryptographically strong.
214 * @return bool Returns true if the source was strong, false if not.
216 public function wasStrong() {
217 if ( is_null( $this->strong
) ) {
218 throw new RuntimeException( __METHOD__
. ' called before generation of random data' );
221 return $this->strong
;
225 * Generate a run of (ideally) cryptographically random data and return
226 * it in raw binary form.
227 * You can use CryptRand::wasStrong() if you wish to know if the source used
228 * was cryptographically strong.
230 * @param int $bytes The number of bytes of random data to generate
231 * @param bool $forceStrong Pass true if you want generate to prefer cryptographically
232 * strong sources of entropy even if reading from them may steal
233 * more entropy from the system than optimal.
234 * @return string Raw binary random data
236 public function generate( $bytes, $forceStrong = false ) {
238 $this->logger
->debug( "Generating cryptographic random bytes for\n" );
240 $bytes = floor( $bytes );
242 if ( is_null( $this->strong
) ) {
243 // Set strength to false initially until we know what source data is coming from
244 $this->strong
= true;
247 if ( strlen( $buffer ) < $bytes ) {
248 // If available make use of mcrypt_create_iv URANDOM source to generate randomness
249 // On unix-like systems this reads from /dev/urandom but does it without any buffering
250 // and bypasses openbasedir restrictions, so it's preferable to reading directly
251 // On Windows starting in PHP 5.3.0 Windows' native CryptGenRandom is used to generate
252 // entropy so this is also preferable to just trying to read urandom because it may work
253 // on Windows systems as well.
254 if ( function_exists( 'mcrypt_create_iv' ) ) {
255 $rem = $bytes - strlen( $buffer );
256 $iv = mcrypt_create_iv( $rem, MCRYPT_DEV_URANDOM
);
257 if ( $iv === false ) {
258 $this->logger
->debug( "mcrypt_create_iv returned false.\n" );
261 $this->logger
->debug( "mcrypt_create_iv generated " . strlen( $iv ) .
262 " bytes of randomness.\n" );
267 if ( strlen( $buffer ) < $bytes ) {
268 if ( function_exists( 'openssl_random_pseudo_bytes' ) ) {
269 $rem = $bytes - strlen( $buffer );
270 $openssl_bytes = openssl_random_pseudo_bytes( $rem, $openssl_strong );
271 if ( $openssl_bytes === false ) {
272 $this->logger
->debug( "openssl_random_pseudo_bytes returned false.\n" );
274 $buffer .= $openssl_bytes;
275 $this->logger
->debug( "openssl_random_pseudo_bytes generated " .
276 strlen( $openssl_bytes ) . " bytes of " .
277 ( $openssl_strong ?
"strong" : "weak" ) . " randomness.\n" );
279 if ( strlen( $buffer ) >= $bytes ) {
280 // openssl tells us if the random source was strong, if some of our data was generated
281 // using it use it's say on whether the randomness is strong
282 $this->strong
= !!$openssl_strong;
287 // Only read from urandom if we can control the buffer size or were passed forceStrong
288 if ( strlen( $buffer ) < $bytes &&
289 ( function_exists( 'stream_set_read_buffer' ) ||
$forceStrong )
291 $rem = $bytes - strlen( $buffer );
292 if ( !function_exists( 'stream_set_read_buffer' ) && $forceStrong ) {
293 $this->logger
->debug( "Was forced to read from /dev/urandom " .
294 "without control over the buffer size.\n" );
296 // /dev/urandom is generally considered the best possible commonly
297 // available random source, and is available on most *nix systems.
298 MediaWiki\
suppressWarnings();
299 $urandom = fopen( "/dev/urandom", "rb" );
300 MediaWiki\restoreWarnings
();
302 // Attempt to read all our random data from urandom
303 // php's fread always does buffered reads based on the stream's chunk_size
304 // so in reality it will usually read more than the amount of data we're
305 // asked for and not storing that risks depleting the system's random pool.
306 // If stream_set_read_buffer is available set the chunk_size to the amount
307 // of data we need. Otherwise read 8k, php's default chunk_size.
309 // php's default chunk_size is 8k
310 $chunk_size = 1024 * 8;
311 if ( function_exists( 'stream_set_read_buffer' ) ) {
312 // If possible set the chunk_size to the amount of data we need
313 stream_set_read_buffer( $urandom, $rem );
316 $random_bytes = fread( $urandom, max( $chunk_size, $rem ) );
317 $buffer .= $random_bytes;
319 $this->logger
->debug( "/dev/urandom generated " . strlen( $random_bytes ) .
320 " bytes of randomness.\n" );
322 if ( strlen( $buffer ) >= $bytes ) {
323 // urandom is always strong, set to true if all our data was generated using it
324 $this->strong
= true;
327 $this->logger
->debug( "/dev/urandom could not be opened.\n" );
331 // If we cannot use or generate enough data from a secure source
332 // use this loop to generate a good set of pseudo random data.
333 // This works by initializing a random state using a pile of unstable data
334 // and continually shoving it through a hash along with a variable salt.
335 // We hash the random state with more salt to avoid the state from leaking
336 // out and being used to predict the /randomness/ that follows.
337 if ( strlen( $buffer ) < $bytes ) {
338 $this->logger
->debug( __METHOD__
.
339 ": Falling back to using a pseudo random state to generate randomness.\n" );
341 while ( strlen( $buffer ) < $bytes ) {
342 $buffer .= MWCryptHash
::hmac( $this->randomState(), strval( mt_rand() ) );
343 // This code is never really cryptographically strong, if we use it
344 // at all, then set strong to false.
345 $this->strong
= false;
348 // Once the buffer has been filled up with enough random data to fulfill
349 // the request shift off enough data to handle the request and leave the
350 // unused portion left inside the buffer for the next request for random data
351 $generated = substr( $buffer, 0, $bytes );
352 $buffer = substr( $buffer, $bytes );
354 $this->logger
->debug( strlen( $buffer ) .
355 " bytes of randomness leftover in the buffer.\n" );
361 * Generate a run of (ideally) cryptographically random data and return
362 * it in hexadecimal string format.
363 * You can use CryptRand::wasStrong() if you wish to know if the source used
364 * was cryptographically strong.
366 * @param int $chars The number of hex chars of random data to generate
367 * @param bool $forceStrong Pass true if you want generate to prefer cryptographically
368 * strong sources of entropy even if reading from them may steal
369 * more entropy from the system than optimal.
370 * @return string Hexadecimal random data
372 public function generateHex( $chars, $forceStrong = false ) {
373 // hex strings are 2x the length of raw binary so we divide the length in half
374 // odd numbers will result in a .5 that leads the generate() being 1 character
375 // short, so we use ceil() to ensure that we always have enough bytes
376 $bytes = ceil( $chars / 2 );
377 // Generate the data and then convert it to a hex string
378 $hex = bin2hex( $this->generate( $bytes, $forceStrong ) );
380 // A bit of paranoia here, the caller asked for a specific length of string
381 // here, and it's possible (eg when given an odd number) that we may actually
382 // have at least 1 char more than they asked for. Just in case they made this
383 // call intending to insert it into a database that does truncation we don't
384 // want to give them too much and end up with their database and their live
385 // code having two different values because part of what we gave them is truncated
386 // hence, we strip out any run of characters longer than what we were asked for.
387 return substr( $hex, 0, $chars );