ILIAS  release_5-4 Revision v5.4.26-12-gabc799a52e6
Random.php
Go to the documentation of this file.
1<?php
2
25namespace phpseclib\Crypt;
26
34
42class Random
43{
54 static function string($length)
55 {
56 if (version_compare(PHP_VERSION, '7.0.0', '>=')) {
57 try {
58 return \random_bytes($length);
59 } catch (\Throwable $e) {
60 // If a sufficient source of randomness is unavailable, random_bytes() will throw an
61 // object that implements the Throwable interface (Exception, TypeError, Error).
62 // We don't actually need to do anything here. The string() method should just continue
63 // as normal. Note, however, that if we don't have a sufficient source of randomness for
64 // random_bytes(), most of the other calls here will fail too, so we'll end up using
65 // the PHP implementation.
66 }
67 }
68
69 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
70 // method 1. prior to PHP 5.3 this would call rand() on windows hence the function_exists('class_alias') call.
71 // ie. class_alias is a function that was introduced in PHP 5.3
72 if (extension_loaded('mcrypt') && function_exists('class_alias')) {
73 return mcrypt_create_iv($length);
74 }
75 // method 2. openssl_random_pseudo_bytes was introduced in PHP 5.3.0 but prior to PHP 5.3.4 there was,
76 // to quote <http://php.net/ChangeLog-5.php#5.3.4>, "possible blocking behavior". as of 5.3.4
77 // openssl_random_pseudo_bytes and mcrypt_create_iv do the exact same thing on Windows. ie. they both
78 // call php_win32_get_random_bytes():
79 //
80 // https://github.com/php/php-src/blob/7014a0eb6d1611151a286c0ff4f2238f92c120d6/ext/openssl/openssl.c#L5008
81 // https://github.com/php/php-src/blob/7014a0eb6d1611151a286c0ff4f2238f92c120d6/ext/mcrypt/mcrypt.c#L1392
82 //
83 // php_win32_get_random_bytes() is defined thusly:
84 //
85 // https://github.com/php/php-src/blob/7014a0eb6d1611151a286c0ff4f2238f92c120d6/win32/winutil.c#L80
86 //
87 // we're calling it, all the same, in the off chance that the mcrypt extension is not available
88 if (extension_loaded('openssl') && version_compare(PHP_VERSION, '5.3.4', '>=')) {
89 return openssl_random_pseudo_bytes($length);
90 }
91 } else {
92 // method 1. the fastest
93 if (extension_loaded('openssl')) {
94 return openssl_random_pseudo_bytes($length);
95 }
96 // method 2
97 static $fp = true;
98 if ($fp === true) {
99 // warning's will be output unles the error suppression operator is used. errors such as
100 // "open_basedir restriction in effect", "Permission denied", "No such file or directory", etc.
101 $fp = @fopen('/dev/urandom', 'rb');
102 }
103 if ($fp !== true && $fp !== false) { // surprisingly faster than !is_bool() or is_resource()
104 return fread($fp, $length);
105 }
106 // method 3. pretty much does the same thing as method 2 per the following url:
107 // https://github.com/php/php-src/blob/7014a0eb6d1611151a286c0ff4f2238f92c120d6/ext/mcrypt/mcrypt.c#L1391
108 // surprisingly slower than method 2. maybe that's because mcrypt_create_iv does a bunch of error checking that we're
109 // not doing. regardless, this'll only be called if this PHP script couldn't open /dev/urandom due to open_basedir
110 // restrictions or some such
111 if (extension_loaded('mcrypt')) {
112 return mcrypt_create_iv($length, MCRYPT_DEV_URANDOM);
113 }
114 }
115 // at this point we have no choice but to use a pure-PHP CSPRNG
116
117 // cascade entropy across multiple PHP instances by fixing the session and collecting all
118 // environmental variables, including the previous session data and the current session
119 // data.
120 //
121 // mt_rand seeds itself by looking at the PID and the time, both of which are (relatively)
122 // easy to guess at. linux uses mouse clicks, keyboard timings, etc, as entropy sources, but
123 // PHP isn't low level to be able to use those as sources and on a web server there's not likely
124 // going to be a ton of keyboard or mouse action. web servers do have one thing that we can use
125 // however, a ton of people visiting the website. obviously you don't want to base your seeding
126 // soley on parameters a potential attacker sends but (1) not everything in $_SERVER is controlled
127 // by the user and (2) this isn't just looking at the data sent by the current user - it's based
128 // on the data sent by all users. one user requests the page and a hash of their info is saved.
129 // another user visits the page and the serialization of their data is utilized along with the
130 // server envirnment stuff and a hash of the previous http request data (which itself utilizes
131 // a hash of the session data before that). certainly an attacker should be assumed to have
132 // full control over his own http requests. he, however, is not going to have control over
133 // everyone's http requests.
134 static $crypto = false, $v;
135 if ($crypto === false) {
136 // save old session data
137 $old_session_id = session_id();
138 $old_use_cookies = ini_get('session.use_cookies');
139 $old_session_cache_limiter = session_cache_limiter();
140 $_OLD_SESSION = isset($_SESSION) ? $_SESSION : false;
141 if ($old_session_id != '') {
142 session_write_close();
143 }
144
145 session_id(1);
146 ini_set('session.use_cookies', 0);
147 session_cache_limiter('');
148 session_start();
149
150 $v = $seed = $_SESSION['seed'] = pack('H*', sha1(
151 serialize($_SERVER) .
152 serialize($_POST) .
153 serialize($_GET) .
154 serialize($_COOKIE) .
155 serialize($GLOBALS) .
156 serialize($_SESSION) .
157 serialize($_OLD_SESSION)
158 ));
159 if (!isset($_SESSION['count'])) {
160 $_SESSION['count'] = 0;
161 }
162 $_SESSION['count']++;
163
164 session_write_close();
165
166 // restore old session data
167 if ($old_session_id != '') {
168 session_id($old_session_id);
169 session_start();
170 ini_set('session.use_cookies', $old_use_cookies);
171 session_cache_limiter($old_session_cache_limiter);
172 } else {
173 if ($_OLD_SESSION !== false) {
174 $_SESSION = $_OLD_SESSION;
175 unset($_OLD_SESSION);
176 } else {
177 unset($_SESSION);
178 }
179 }
180
181 // in SSH2 a shared secret and an exchange hash are generated through the key exchange process.
182 // 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.
183 // if the hash doesn't produce enough a key or an IV that's long enough concat successive hashes of the
184 // original hash and the current hash. we'll be emulating that. for more info see the following URL:
185 //
186 // http://tools.ietf.org/html/rfc4253#section-7.2
187 //
188 // see the is_string($crypto) part for an example of how to expand the keys
189 $key = pack('H*', sha1($seed . 'A'));
190 $iv = pack('H*', sha1($seed . 'C'));
191
192 // ciphers are used as per the nist.gov link below. also, see this link:
193 //
194 // http://en.wikipedia.org/wiki/Cryptographically_secure_pseudorandom_number_generator#Designs_based_on_cryptographic_primitives
195 switch (true) {
196 case class_exists('\phpseclib\Crypt\AES'):
197 $crypto = new AES(Base::MODE_CTR);
198 break;
199 case class_exists('\phpseclib\Crypt\Twofish'):
200 $crypto = new Twofish(Base::MODE_CTR);
201 break;
202 case class_exists('\phpseclib\Crypt\Blowfish'):
203 $crypto = new Blowfish(Base::MODE_CTR);
204 break;
205 case class_exists('\phpseclib\Crypt\TripleDES'):
206 $crypto = new TripleDES(Base::MODE_CTR);
207 break;
208 case class_exists('\phpseclib\Crypt\DES'):
209 $crypto = new DES(Base::MODE_CTR);
210 break;
211 case class_exists('\phpseclib\Crypt\RC4'):
212 $crypto = new RC4();
213 break;
214 default:
215 user_error(__CLASS__ . ' requires at least one symmetric cipher be loaded');
216 return false;
217 }
218
219 $crypto->setKey($key);
220 $crypto->setIV($iv);
221 $crypto->enableContinuousBuffer();
222 }
223
224 //return $crypto->encrypt(str_repeat("\0", $length));
225
226 // the following is based off of ANSI X9.31:
227 //
228 // http://csrc.nist.gov/groups/STM/cavp/documents/rng/931rngext.pdf
229 //
230 // OpenSSL uses that same standard for it's random numbers:
231 //
232 // http://www.opensource.apple.com/source/OpenSSL/OpenSSL-38/openssl/fips-1.0/rand/fips_rand.c
233 // (do a search for "ANS X9.31 A.2.4")
234 $result = '';
235 while (strlen($result) < $length) {
236 $i = $crypto->encrypt(microtime()); // strlen(microtime()) == 21
237 $r = $crypto->encrypt($i ^ $v); // strlen($v) == 20
238 $v = $crypto->encrypt($r ^ $i); // strlen($r) == 20
239 $result.= $r;
240 }
241 return substr($result, 0, $length);
242 }
243}
$result
$_COOKIE['client_id']
Definition: server.php:9
$_GET["client_id"]
$_POST["username"]
$_SESSION["AccountId"]
An exception for terminatinating execution or to throw for unit testing.
const MODE_CTR
#+ @access public
Definition: Base.php:62
static string($length)
Generate a random string.
Definition: Random.php:54
$key
Definition: croninfo.php:18
$i
Definition: disco.tpl.php:19
$r
Definition: example_031.php:79
$GLOBALS['JPEG_Segment_Names']
Global Variable: XMP_tag_captions.
Pure-PHP implementation of AES.
Pure-PHP implementation of Blowfish.
Pure-PHP implementation of DES.
Pure-PHP implementation of RC4.
Pure-PHP Random Number Generator.
Pure-PHP implementation of Triple DES.
Pure-PHP implementation of Twofish.
Pure-PHP implementations of keyed-hash message authentication codes (HMACs) and various cryptographic...
Definition: AES.php:50
if((!isset($_SERVER['DOCUMENT_ROOT'])) OR(empty($_SERVER['DOCUMENT_ROOT']))) $_SERVER['DOCUMENT_ROOT']