random.php 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  1. <?php
  2. /**
  3. * Random_* Compatibility Library
  4. * for using the new PHP 7 random_* API in PHP 5 projects
  5. *
  6. * @version 2.0.17
  7. * @released 2018-07-04
  8. *
  9. * The MIT License (MIT)
  10. *
  11. * Copyright (c) 2015 - 2018 Paragon Initiative Enterprises
  12. *
  13. * Permission is hereby granted, free of charge, to any person obtaining a copy
  14. * of this software and associated documentation files (the "Software"), to deal
  15. * in the Software without restriction, including without limitation the rights
  16. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  17. * copies of the Software, and to permit persons to whom the Software is
  18. * furnished to do so, subject to the following conditions:
  19. *
  20. * The above copyright notice and this permission notice shall be included in
  21. * all copies or substantial portions of the Software.
  22. *
  23. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  24. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  25. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  26. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  27. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  28. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  29. * SOFTWARE.
  30. */
  31. if (!defined('PHP_VERSION_ID')) {
  32. // This constant was introduced in PHP 5.2.7
  33. $RandomCompatversion = array_map('intval', explode('.', PHP_VERSION));
  34. define(
  35. 'PHP_VERSION_ID',
  36. $RandomCompatversion[0] * 10000
  37. + $RandomCompatversion[1] * 100
  38. + $RandomCompatversion[2]
  39. );
  40. $RandomCompatversion = null;
  41. }
  42. /**
  43. * PHP 7.0.0 and newer have these functions natively.
  44. */
  45. if (PHP_VERSION_ID >= 70000) {
  46. return;
  47. }
  48. if (!defined('RANDOM_COMPAT_READ_BUFFER')) {
  49. define('RANDOM_COMPAT_READ_BUFFER', 8);
  50. }
  51. $RandomCompatDIR = dirname(__FILE__);
  52. require_once $RandomCompatDIR . DIRECTORY_SEPARATOR . 'byte_safe_strings.php';
  53. require_once $RandomCompatDIR . DIRECTORY_SEPARATOR . 'cast_to_int.php';
  54. require_once $RandomCompatDIR . DIRECTORY_SEPARATOR . 'error_polyfill.php';
  55. if (!is_callable('random_bytes')) {
  56. /**
  57. * PHP 5.2.0 - 5.6.x way to implement random_bytes()
  58. *
  59. * We use conditional statements here to define the function in accordance
  60. * to the operating environment. It's a micro-optimization.
  61. *
  62. * In order of preference:
  63. * 1. Use libsodium if available.
  64. * 2. fread() /dev/urandom if available (never on Windows)
  65. * 3. mcrypt_create_iv($bytes, MCRYPT_DEV_URANDOM)
  66. * 4. COM('CAPICOM.Utilities.1')->GetRandom()
  67. *
  68. * See RATIONALE.md for our reasoning behind this particular order
  69. */
  70. if (extension_loaded('libsodium')) {
  71. // See random_bytes_libsodium.php
  72. if (PHP_VERSION_ID >= 50300 && is_callable('\\Sodium\\randombytes_buf')) {
  73. require_once $RandomCompatDIR . DIRECTORY_SEPARATOR . 'random_bytes_libsodium.php';
  74. } elseif (method_exists('Sodium', 'randombytes_buf')) {
  75. require_once $RandomCompatDIR . DIRECTORY_SEPARATOR . 'random_bytes_libsodium_legacy.php';
  76. }
  77. }
  78. /**
  79. * Reading directly from /dev/urandom:
  80. */
  81. if (DIRECTORY_SEPARATOR === '/') {
  82. // DIRECTORY_SEPARATOR === '/' on Unix-like OSes -- this is a fast
  83. // way to exclude Windows.
  84. $RandomCompatUrandom = true;
  85. $RandomCompat_basedir = ini_get('open_basedir');
  86. if (!empty($RandomCompat_basedir)) {
  87. $RandomCompat_open_basedir = explode(
  88. PATH_SEPARATOR,
  89. strtolower($RandomCompat_basedir)
  90. );
  91. $RandomCompatUrandom = (array() !== array_intersect(
  92. array('/dev', '/dev/', '/dev/urandom'),
  93. $RandomCompat_open_basedir
  94. ));
  95. $RandomCompat_open_basedir = null;
  96. }
  97. if (
  98. !is_callable('random_bytes')
  99. &&
  100. $RandomCompatUrandom
  101. &&
  102. @is_readable('/dev/urandom')
  103. ) {
  104. // Error suppression on is_readable() in case of an open_basedir
  105. // or safe_mode failure. All we care about is whether or not we
  106. // can read it at this point. If the PHP environment is going to
  107. // panic over trying to see if the file can be read in the first
  108. // place, that is not helpful to us here.
  109. // See random_bytes_dev_urandom.php
  110. require_once $RandomCompatDIR . DIRECTORY_SEPARATOR . 'random_bytes_dev_urandom.php';
  111. }
  112. // Unset variables after use
  113. $RandomCompat_basedir = null;
  114. } else {
  115. $RandomCompatUrandom = false;
  116. }
  117. /**
  118. * mcrypt_create_iv()
  119. *
  120. * We only want to use mcypt_create_iv() if:
  121. *
  122. * - random_bytes() hasn't already been defined
  123. * - the mcrypt extensions is loaded
  124. * - One of these two conditions is true:
  125. * - We're on Windows (DIRECTORY_SEPARATOR !== '/')
  126. * - We're not on Windows and /dev/urandom is readabale
  127. * (i.e. we're not in a chroot jail)
  128. * - Special case:
  129. * - If we're not on Windows, but the PHP version is between
  130. * 5.6.10 and 5.6.12, we don't want to use mcrypt. It will
  131. * hang indefinitely. This is bad.
  132. * - If we're on Windows, we want to use PHP >= 5.3.7 or else
  133. * we get insufficient entropy errors.
  134. */
  135. if (
  136. !is_callable('random_bytes')
  137. &&
  138. // Windows on PHP < 5.3.7 is broken, but non-Windows is not known to be.
  139. (DIRECTORY_SEPARATOR === '/' || PHP_VERSION_ID >= 50307)
  140. &&
  141. // Prevent this code from hanging indefinitely on non-Windows;
  142. // see https://bugs.php.net/bug.php?id=69833
  143. (
  144. DIRECTORY_SEPARATOR !== '/' ||
  145. (PHP_VERSION_ID <= 50609 || PHP_VERSION_ID >= 50613)
  146. )
  147. &&
  148. extension_loaded('mcrypt')
  149. ) {
  150. // See random_bytes_mcrypt.php
  151. require_once $RandomCompatDIR . DIRECTORY_SEPARATOR . 'random_bytes_mcrypt.php';
  152. }
  153. $RandomCompatUrandom = null;
  154. /**
  155. * This is a Windows-specific fallback, for when the mcrypt extension
  156. * isn't loaded.
  157. */
  158. if (
  159. !is_callable('random_bytes')
  160. &&
  161. extension_loaded('com_dotnet')
  162. &&
  163. class_exists('COM')
  164. ) {
  165. $RandomCompat_disabled_classes = preg_split(
  166. '#\s*,\s*#',
  167. strtolower(ini_get('disable_classes'))
  168. );
  169. if (!in_array('com', $RandomCompat_disabled_classes)) {
  170. try {
  171. $RandomCompatCOMtest = new COM('CAPICOM.Utilities.1');
  172. if (method_exists($RandomCompatCOMtest, 'GetRandom')) {
  173. // See random_bytes_com_dotnet.php
  174. require_once $RandomCompatDIR . DIRECTORY_SEPARATOR . 'random_bytes_com_dotnet.php';
  175. }
  176. } catch (com_exception $e) {
  177. // Don't try to use it.
  178. }
  179. }
  180. $RandomCompat_disabled_classes = null;
  181. $RandomCompatCOMtest = null;
  182. }
  183. /**
  184. * throw new Exception
  185. */
  186. if (!is_callable('random_bytes')) {
  187. /**
  188. * We don't have any more options, so let's throw an exception right now
  189. * and hope the developer won't let it fail silently.
  190. *
  191. * @param mixed $length
  192. * @psalm-suppress InvalidReturnType
  193. * @throws Exception
  194. * @return string
  195. */
  196. function random_bytes($length)
  197. {
  198. unset($length); // Suppress "variable not used" warnings.
  199. throw new Exception(
  200. 'There is no suitable CSPRNG installed on your system'
  201. );
  202. return '';
  203. }
  204. }
  205. }
  206. if (!is_callable('random_int')) {
  207. require_once $RandomCompatDIR . DIRECTORY_SEPARATOR . 'random_int.php';
  208. }
  209. $RandomCompatDIR = null;