Rev 846 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed
Rev | Author | Line No. | Line |
---|---|---|---|
827 | daniel-mar | 1 | <?php |
2 | |||
3 | /** |
||
4 | * Random Number Generator |
||
5 | * |
||
6 | * PHP version 5 |
||
7 | * |
||
8 | * Here's a short example of how to use this library: |
||
9 | * <code> |
||
10 | * <?php |
||
11 | * include 'vendor/autoload.php'; |
||
12 | * |
||
13 | * echo bin2hex(\phpseclib3\Crypt\Random::string(8)); |
||
14 | * ?> |
||
15 | * </code> |
||
16 | * |
||
874 | daniel-mar | 17 | * @category Crypt |
18 | * @package Random |
||
827 | daniel-mar | 19 | * @author Jim Wigginton <terrafrost@php.net> |
20 | * @copyright 2007 Jim Wigginton |
||
21 | * @license http://www.opensource.org/licenses/mit-license.html MIT License |
||
22 | * @link http://phpseclib.sourceforge.net |
||
23 | */ |
||
24 | |||
25 | namespace phpseclib3\Crypt; |
||
26 | |||
27 | /** |
||
28 | * Pure-PHP Random Number Generator |
||
29 | * |
||
874 | daniel-mar | 30 | * @package Random |
827 | daniel-mar | 31 | * @author Jim Wigginton <terrafrost@php.net> |
874 | daniel-mar | 32 | * @access public |
827 | daniel-mar | 33 | */ |
34 | abstract class Random |
||
35 | { |
||
36 | /** |
||
37 | * Generate a random string. |
||
38 | * |
||
39 | * Although microoptimizations are generally discouraged as they impair readability this function is ripe with |
||
40 | * microoptimizations because this function has the potential of being called a huge number of times. |
||
41 | * eg. for RSA key generation. |
||
42 | * |
||
43 | * @param int $length |
||
44 | * @throws \RuntimeException if a symmetric cipher is needed but not loaded |
||
45 | * @return string |
||
46 | */ |
||
47 | public static function string($length) |
||
48 | { |
||
49 | if (!$length) { |
||
50 | return ''; |
||
51 | } |
||
52 | |||
53 | try { |
||
54 | return random_bytes($length); |
||
55 | } catch (\Exception $e) { |
||
56 | // random_compat will throw an Exception, which in PHP 5 does not implement Throwable |
||
57 | } catch (\Throwable $e) { |
||
58 | // If a sufficient source of randomness is unavailable, random_bytes() will throw an |
||
59 | // object that implements the Throwable interface (Exception, TypeError, Error). |
||
60 | // We don't actually need to do anything here. The string() method should just continue |
||
61 | // as normal. Note, however, that if we don't have a sufficient source of randomness for |
||
62 | // random_bytes(), most of the other calls here will fail too, so we'll end up using |
||
63 | // the PHP implementation. |
||
64 | } |
||
65 | // at this point we have no choice but to use a pure-PHP CSPRNG |
||
66 | |||
67 | // cascade entropy across multiple PHP instances by fixing the session and collecting all |
||
68 | // environmental variables, including the previous session data and the current session |
||
69 | // data. |
||
70 | // |
||
71 | // mt_rand seeds itself by looking at the PID and the time, both of which are (relatively) |
||
72 | // easy to guess at. linux uses mouse clicks, keyboard timings, etc, as entropy sources, but |
||
73 | // PHP isn't low level to be able to use those as sources and on a web server there's not likely |
||
74 | // going to be a ton of keyboard or mouse action. web servers do have one thing that we can use |
||
75 | // however, a ton of people visiting the website. obviously you don't want to base your seeding |
||
76 | // solely on parameters a potential attacker sends but (1) not everything in $_SERVER is controlled |
||
77 | // by the user and (2) this isn't just looking at the data sent by the current user - it's based |
||
78 | // on the data sent by all users. one user requests the page and a hash of their info is saved. |
||
79 | // another user visits the page and the serialization of their data is utilized along with the |
||
80 | // server environment stuff and a hash of the previous http request data (which itself utilizes |
||
81 | // a hash of the session data before that). certainly an attacker should be assumed to have |
||
82 | // full control over his own http requests. he, however, is not going to have control over |
||
83 | // everyone's http requests. |
||
84 | static $crypto = false, $v; |
||
85 | if ($crypto === false) { |
||
86 | // save old session data |
||
87 | $old_session_id = session_id(); |
||
88 | $old_use_cookies = ini_get('session.use_cookies'); |
||
89 | $old_session_cache_limiter = session_cache_limiter(); |
||
90 | $_OLD_SESSION = isset($_SESSION) ? $_SESSION : false; |
||
91 | if ($old_session_id != '') { |
||
92 | session_write_close(); |
||
93 | } |
||
94 | |||
95 | session_id(1); |
||
96 | ini_set('session.use_cookies', 0); |
||
97 | session_cache_limiter(''); |
||
98 | session_start(); |
||
99 | |||
100 | $v = (isset($_SERVER) ? self::safe_serialize($_SERVER) : '') . |
||
101 | (isset($_POST) ? self::safe_serialize($_POST) : '') . |
||
102 | (isset($_GET) ? self::safe_serialize($_GET) : '') . |
||
103 | (isset($_COOKIE) ? self::safe_serialize($_COOKIE) : '') . |
||
104 | self::safe_serialize($GLOBALS) . |
||
105 | self::safe_serialize($_SESSION) . |
||
106 | self::safe_serialize($_OLD_SESSION); |
||
107 | $v = $seed = $_SESSION['seed'] = sha1($v, true); |
||
108 | if (!isset($_SESSION['count'])) { |
||
109 | $_SESSION['count'] = 0; |
||
110 | } |
||
111 | $_SESSION['count']++; |
||
112 | |||
113 | session_write_close(); |
||
114 | |||
115 | // restore old session data |
||
116 | if ($old_session_id != '') { |
||
117 | session_id($old_session_id); |
||
118 | session_start(); |
||
119 | ini_set('session.use_cookies', $old_use_cookies); |
||
120 | session_cache_limiter($old_session_cache_limiter); |
||
121 | } else { |
||
122 | if ($_OLD_SESSION !== false) { |
||
123 | $_SESSION = $_OLD_SESSION; |
||
124 | unset($_OLD_SESSION); |
||
125 | } else { |
||
126 | unset($_SESSION); |
||
127 | } |
||
128 | } |
||
129 | |||
130 | // in SSH2 a shared secret and an exchange hash are generated through the key exchange process. |
||
131 | // the IV client to server is the hash of that "nonce" with the letter A and for the encryption key it's the letter C. |
||
132 | // if the hash doesn't produce enough a key or an IV that's long enough concat successive hashes of the |
||
133 | // original hash and the current hash. we'll be emulating that. for more info see the following URL: |
||
134 | // |
||
135 | // http://tools.ietf.org/html/rfc4253#section-7.2 |
||
136 | // |
||
137 | // see the is_string($crypto) part for an example of how to expand the keys |
||
138 | $key = sha1($seed . 'A', true); |
||
139 | $iv = sha1($seed . 'C', true); |
||
140 | |||
141 | // ciphers are used as per the nist.gov link below. also, see this link: |
||
142 | // |
||
143 | // http://en.wikipedia.org/wiki/Cryptographically_secure_pseudorandom_number_generator#Designs_based_on_cryptographic_primitives |
||
144 | switch (true) { |
||
145 | case class_exists('\phpseclib3\Crypt\AES'): |
||
146 | $crypto = new AES('ctr'); |
||
147 | break; |
||
148 | case class_exists('\phpseclib3\Crypt\Twofish'): |
||
149 | $crypto = new Twofish('ctr'); |
||
150 | break; |
||
151 | case class_exists('\phpseclib3\Crypt\Blowfish'): |
||
152 | $crypto = new Blowfish('ctr'); |
||
153 | break; |
||
154 | case class_exists('\phpseclib3\Crypt\TripleDES'): |
||
155 | $crypto = new TripleDES('ctr'); |
||
156 | break; |
||
157 | case class_exists('\phpseclib3\Crypt\DES'): |
||
158 | $crypto = new DES('ctr'); |
||
159 | break; |
||
160 | case class_exists('\phpseclib3\Crypt\RC4'): |
||
161 | $crypto = new RC4(); |
||
162 | break; |
||
163 | default: |
||
164 | throw new \RuntimeException(__CLASS__ . ' requires at least one symmetric cipher be loaded'); |
||
165 | } |
||
166 | |||
167 | $crypto->setKey(substr($key, 0, $crypto->getKeyLength() >> 3)); |
||
168 | $crypto->setIV(substr($iv, 0, $crypto->getBlockLength() >> 3)); |
||
169 | $crypto->enableContinuousBuffer(); |
||
170 | } |
||
171 | |||
172 | //return $crypto->encrypt(str_repeat("\0", $length)); |
||
173 | |||
174 | // the following is based off of ANSI X9.31: |
||
175 | // |
||
176 | // http://csrc.nist.gov/groups/STM/cavp/documents/rng/931rngext.pdf |
||
177 | // |
||
178 | // OpenSSL uses that same standard for it's random numbers: |
||
179 | // |
||
180 | // http://www.opensource.apple.com/source/OpenSSL/OpenSSL-38/openssl/fips-1.0/rand/fips_rand.c |
||
181 | // (do a search for "ANS X9.31 A.2.4") |
||
182 | $result = ''; |
||
183 | while (strlen($result) < $length) { |
||
184 | $i = $crypto->encrypt(microtime()); // strlen(microtime()) == 21 |
||
185 | $r = $crypto->encrypt($i ^ $v); // strlen($v) == 20 |
||
186 | $v = $crypto->encrypt($r ^ $i); // strlen($r) == 20 |
||
187 | $result .= $r; |
||
188 | } |
||
189 | |||
190 | return substr($result, 0, $length); |
||
191 | } |
||
192 | |||
193 | /** |
||
194 | * Safely serialize variables |
||
195 | * |
||
196 | * If a class has a private __sleep() it'll emit a warning |
||
197 | * @return mixed |
||
198 | * @param mixed $arr |
||
199 | */ |
||
200 | private static function safe_serialize(&$arr) |
||
201 | { |
||
202 | if (is_object($arr)) { |
||
203 | return ''; |
||
204 | } |
||
205 | if (!is_array($arr)) { |
||
206 | return serialize($arr); |
||
207 | } |
||
208 | // prevent circular array recursion |
||
209 | if (isset($arr['__phpseclib_marker'])) { |
||
210 | return ''; |
||
211 | } |
||
212 | $safearr = []; |
||
213 | $arr['__phpseclib_marker'] = true; |
||
214 | foreach (array_keys($arr) as $key) { |
||
215 | // do not recurse on the '__phpseclib_marker' key itself, for smaller memory usage |
||
216 | if ($key !== '__phpseclib_marker') { |
||
217 | $safearr[$key] = self::safe_serialize($arr[$key]); |
||
218 | } |
||
219 | } |
||
220 | unset($arr['__phpseclib_marker']); |
||
221 | return serialize($safearr); |
||
222 | } |
||
223 | } |