PageRenderTime 65ms CodeModel.GetById 32ms RepoModel.GetById 0ms app.codeStats 0ms

/includes/CryptRand.php

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