random_bytes_dev_urandom.php 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  1. <?php
  2. /**
  3. * Random_* Compatibility Library
  4. * for using the new PHP 7 random_* API in PHP 5 projects
  5. *
  6. * The MIT License (MIT)
  7. *
  8. * Copyright (c) 2015 - 2018 Paragon Initiative Enterprises
  9. *
  10. * Permission is hereby granted, free of charge, to any person obtaining a copy
  11. * of this software and associated documentation files (the "Software"), to deal
  12. * in the Software without restriction, including without limitation the rights
  13. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  14. * copies of the Software, and to permit persons to whom the Software is
  15. * furnished to do so, subject to the following conditions:
  16. *
  17. * The above copyright notice and this permission notice shall be included in
  18. * all copies or substantial portions of the Software.
  19. *
  20. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  21. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  22. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  23. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  24. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  25. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  26. * SOFTWARE.
  27. */
  28. if (!defined('RANDOM_COMPAT_READ_BUFFER')) {
  29. define('RANDOM_COMPAT_READ_BUFFER', 8);
  30. }
  31. if (!is_callable('random_bytes')) {
  32. /**
  33. * Unless open_basedir is enabled, use /dev/urandom for
  34. * random numbers in accordance with best practices
  35. *
  36. * Why we use /dev/urandom and not /dev/random
  37. * @ref https://www.2uo.de/myths-about-urandom
  38. * @ref http://sockpuppet.org/blog/2014/02/25/safely-generate-random-numbers
  39. *
  40. * @param int $bytes
  41. *
  42. * @throws Exception
  43. *
  44. * @return string
  45. */
  46. function random_bytes($bytes)
  47. {
  48. /** @var resource $fp */
  49. static $fp = null;
  50. /**
  51. * This block should only be run once
  52. */
  53. if (empty($fp)) {
  54. /**
  55. * We don't want to ever read C:\dev\random, only /dev/urandom on
  56. * Unix-like operating systems. While we guard against this
  57. * condition in random.php, it doesn't hurt to be defensive in depth
  58. * here.
  59. *
  60. * To that end, we only try to open /dev/urandom if we're on a Unix-
  61. * like operating system (which means the directory separator is set
  62. * to "/" not "\".
  63. */
  64. if (DIRECTORY_SEPARATOR === '/') {
  65. if (!is_readable('/dev/urandom')) {
  66. throw new Exception(
  67. 'Environment misconfiguration: ' .
  68. '/dev/urandom cannot be read.'
  69. );
  70. }
  71. /**
  72. * We use /dev/urandom if it is a char device.
  73. * We never fall back to /dev/random
  74. */
  75. /** @var resource|bool $fp */
  76. $fp = fopen('/dev/urandom', 'rb');
  77. if (is_resource($fp)) {
  78. /** @var array<string, int> $st */
  79. $st = fstat($fp);
  80. if (($st['mode'] & 0170000) !== 020000) {
  81. fclose($fp);
  82. $fp = false;
  83. }
  84. }
  85. }
  86. if (is_resource($fp)) {
  87. /**
  88. * stream_set_read_buffer() does not exist in HHVM
  89. *
  90. * If we don't set the stream's read buffer to 0, PHP will
  91. * internally buffer 8192 bytes, which can waste entropy
  92. *
  93. * stream_set_read_buffer returns 0 on success
  94. */
  95. if (is_callable('stream_set_read_buffer')) {
  96. stream_set_read_buffer($fp, RANDOM_COMPAT_READ_BUFFER);
  97. }
  98. if (is_callable('stream_set_chunk_size')) {
  99. stream_set_chunk_size($fp, RANDOM_COMPAT_READ_BUFFER);
  100. }
  101. }
  102. }
  103. try {
  104. /** @var int $bytes */
  105. $bytes = RandomCompat_intval($bytes);
  106. } catch (TypeError $ex) {
  107. throw new TypeError(
  108. 'random_bytes(): $bytes must be an integer'
  109. );
  110. }
  111. if ($bytes < 1) {
  112. throw new Error(
  113. 'Length must be greater than 0'
  114. );
  115. }
  116. /**
  117. * This if() block only runs if we managed to open a file handle
  118. *
  119. * It does not belong in an else {} block, because the above
  120. * if (empty($fp)) line is logic that should only be run once per
  121. * page load.
  122. */
  123. if (is_resource($fp)) {
  124. /**
  125. * @var int
  126. */
  127. $remaining = $bytes;
  128. /**
  129. * @var string|bool
  130. */
  131. $buf = '';
  132. /**
  133. * We use fread() in a loop to protect against partial reads
  134. */
  135. do {
  136. /**
  137. * @var string|bool
  138. */
  139. $read = fread($fp, $remaining);
  140. if (!is_string($read)) {
  141. /**
  142. * We cannot safely read from the file. Exit the
  143. * do-while loop and trigger the exception condition
  144. *
  145. * @var string|bool
  146. */
  147. $buf = false;
  148. break;
  149. }
  150. /**
  151. * Decrease the number of bytes returned from remaining
  152. */
  153. $remaining -= RandomCompat_strlen($read);
  154. /**
  155. * @var string $buf
  156. */
  157. $buf .= $read;
  158. } while ($remaining > 0);
  159. /**
  160. * Is our result valid?
  161. * @var string|bool $buf
  162. */
  163. if (is_string($buf)) {
  164. if (RandomCompat_strlen($buf) === $bytes) {
  165. /**
  166. * Return our random entropy buffer here:
  167. */
  168. return $buf;
  169. }
  170. }
  171. }
  172. /**
  173. * If we reach here, PHP has failed us.
  174. */
  175. throw new Exception(
  176. 'Error reading from source device'
  177. );
  178. }
  179. }