]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/OStatus/extlib/Crypt/Random.php
d4e48983bf28efd451c5726e80b6cffd2507423f
[quix0rs-gnu-social.git] / plugins / OStatus / extlib / Crypt / Random.php
1 <?php\r
2 /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */\r
3 \r
4 /**\r
5  * Random Number Generator\r
6  *\r
7  * PHP versions 4 and 5\r
8  *\r
9  * Here's a short example of how to use this library:\r
10  * <code>\r
11  * <?php\r
12  *    include('Crypt/Random.php');\r
13  *\r
14  *    echo bin2hex(crypt_random_string(8));\r
15  * ?>\r
16  * </code>\r
17  *\r
18  * LICENSE: Permission is hereby granted, free of charge, to any person obtaining a copy\r
19  * of this software and associated documentation files (the "Software"), to deal\r
20  * in the Software without restriction, including without limitation the rights\r
21  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r
22  * copies of the Software, and to permit persons to whom the Software is\r
23  * furnished to do so, subject to the following conditions:\r
24  * \r
25  * The above copyright notice and this permission notice shall be included in\r
26  * all copies or substantial portions of the Software.\r
27  * \r
28  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r
29  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r
30  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r
31  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r
32  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r
33  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\r
34  * THE SOFTWARE.\r
35  *\r
36  * @category   Crypt\r
37  * @package    Crypt_Random\r
38  * @author     Jim Wigginton <terrafrost@php.net>\r
39  * @copyright  MMVII Jim Wigginton\r
40  * @license    http://www.opensource.org/licenses/mit-license.html  MIT License\r
41  * @link       http://phpseclib.sourceforge.net\r
42  */\r
43 \r
44 /**\r
45  * "Is Windows" test\r
46  *\r
47  * @access private\r
48  */\r
49 define('CRYPT_RANDOM_IS_WINDOWS', strtoupper(substr(PHP_OS, 0, 3)) === 'WIN');\r
50 \r
51 /**\r
52  * Generate a random string.\r
53  *\r
54  * Although microoptimizations are generally discouraged as they impair readability this function is ripe with\r
55  * microoptimizations because this function has the potential of being called a huge number of times.\r
56  * eg. for RSA key generation.\r
57  *\r
58  * @param Integer $length\r
59  * @return String\r
60  * @access public\r
61  */\r
62 function crypt_random_string($length)\r
63 {\r
64     if (CRYPT_RANDOM_IS_WINDOWS) {\r
65         // method 1. prior to PHP 5.3 this would call rand() on windows hence the function_exists('class_alias') call.\r
66         // ie. class_alias is a function that was introduced in PHP 5.3\r
67         if (function_exists('mcrypt_create_iv') && function_exists('class_alias')) {\r
68             return mcrypt_create_iv($length);\r
69         }\r
70         // method 2. openssl_random_pseudo_bytes was introduced in PHP 5.3.0 but prior to PHP 5.3.4 there was,\r
71         // to quote <http://php.net/ChangeLog-5.php#5.3.4>, "possible blocking behavior". as of 5.3.4\r
72         // openssl_random_pseudo_bytes and mcrypt_create_iv do the exact same thing on Windows. ie. they both\r
73         // call php_win32_get_random_bytes():\r
74         //\r
75         // https://github.com/php/php-src/blob/7014a0eb6d1611151a286c0ff4f2238f92c120d6/ext/openssl/openssl.c#L5008\r
76         // https://github.com/php/php-src/blob/7014a0eb6d1611151a286c0ff4f2238f92c120d6/ext/mcrypt/mcrypt.c#L1392\r
77         //\r
78         // php_win32_get_random_bytes() is defined thusly:\r
79         //\r
80         // https://github.com/php/php-src/blob/7014a0eb6d1611151a286c0ff4f2238f92c120d6/win32/winutil.c#L80\r
81         //\r
82         // we're calling it, all the same, in the off chance that the mcrypt extension is not available\r
83         if (function_exists('openssl_random_pseudo_bytes') && version_compare(PHP_VERSION, '5.3.4', '>=')) {\r
84             return openssl_random_pseudo_bytes($length);\r
85         }\r
86     } else {\r
87         // method 1. the fastest\r
88         if (function_exists('openssl_random_pseudo_bytes')) {\r
89             return openssl_random_pseudo_bytes($length);\r
90         }\r
91         // method 2\r
92         static $fp = true;\r
93         if ($fp === true) {\r
94             // warning's will be output unles the error suppression operator is used. errors such as\r
95             // "open_basedir restriction in effect", "Permission denied", "No such file or directory", etc.\r
96             $fp = @fopen('/dev/urandom', 'rb');\r
97         }\r
98         if ($fp !== true && $fp !== false) { // surprisingly faster than !is_bool() or is_resource()\r
99             return fread($fp, $length);\r
100         }\r
101         // method 3. pretty much does the same thing as method 2 per the following url:\r
102         // https://github.com/php/php-src/blob/7014a0eb6d1611151a286c0ff4f2238f92c120d6/ext/mcrypt/mcrypt.c#L1391\r
103         // surprisingly slower than method 2. maybe that's because mcrypt_create_iv does a bunch of error checking that we're\r
104         // not doing. regardless, this'll only be called if this PHP script couldn't open /dev/urandom due to open_basedir\r
105         // restrictions or some such\r
106         if (function_exists('mcrypt_create_iv')) {\r
107             return mcrypt_create_iv($length, MCRYPT_DEV_URANDOM);\r
108         }\r
109     }\r
110     // at this point we have no choice but to use a pure-PHP CSPRNG\r
111 \r
112     // cascade entropy across multiple PHP instances by fixing the session and collecting all\r
113     // environmental variables, including the previous session data and the current session\r
114     // data.\r
115     //\r
116     // mt_rand seeds itself by looking at the PID and the time, both of which are (relatively)\r
117     // easy to guess at. linux uses mouse clicks, keyboard timings, etc, as entropy sources, but\r
118     // PHP isn't low level to be able to use those as sources and on a web server there's not likely\r
119     // going to be a ton of keyboard or mouse action. web servers do have one thing that we can use\r
120     // however. a ton of people visiting the website. obviously you don't want to base your seeding\r
121     // soley on parameters a potential attacker sends but (1) not everything in $_SERVER is controlled\r
122     // by the user and (2) this isn't just looking at the data sent by the current user - it's based\r
123     // on the data sent by all users. one user requests the page and a hash of their info is saved.\r
124     // another user visits the page and the serialization of their data is utilized along with the\r
125     // server envirnment stuff and a hash of the previous http request data (which itself utilizes\r
126     // a hash of the session data before that). certainly an attacker should be assumed to have\r
127     // full control over his own http requests. he, however, is not going to have control over\r
128     // everyone's http requests.\r
129     static $crypto = false, $v;\r
130     if ($crypto === false) {\r
131         // save old session data\r
132         $old_session_id = session_id();\r
133         $old_use_cookies = ini_get('session.use_cookies');\r
134         $old_session_cache_limiter = session_cache_limiter();\r
135         if (isset($_SESSION)) {\r
136             $_OLD_SESSION = $_SESSION;\r
137         }\r
138         if ($old_session_id != '') {\r
139             session_write_close();\r
140         }\r
141 \r
142         session_id(1);\r
143         ini_set('session.use_cookies', 0);\r
144         session_cache_limiter('');\r
145         session_start();\r
146 \r
147         $v = $seed = $_SESSION['seed'] = pack('H*', sha1(\r
148             serialize($_SERVER) .\r
149             serialize($_POST) .\r
150             serialize($_GET) .\r
151             serialize($_COOKIE) .\r
152             serialize($GLOBALS) .\r
153             serialize($_SESSION) .\r
154             serialize($_OLD_SESSION)\r
155         ));\r
156         if (!isset($_SESSION['count'])) {\r
157             $_SESSION['count'] = 0;\r
158         }\r
159         $_SESSION['count']++;\r
160 \r
161         session_write_close();\r
162 \r
163         // restore old session data\r
164         if ($old_session_id != '') {\r
165             session_id($old_session_id);\r
166             session_start();\r
167             ini_set('session.use_cookies', $old_use_cookies);\r
168             session_cache_limiter($old_session_cache_limiter);\r
169         } else {\r
170            if (isset($_OLD_SESSION)) {\r
171                $_SESSION = $_OLD_SESSION;\r
172                unset($_OLD_SESSION);\r
173             } else {\r
174                 unset($_SESSION);\r
175             }\r
176         }\r
177 \r
178         // in SSH2 a shared secret and an exchange hash are generated through the key exchange process.\r
179         // 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.\r
180         // if the hash doesn't produce enough a key or an IV that's long enough concat successive hashes of the\r
181         // original hash and the current hash. we'll be emulating that. for more info see the following URL:\r
182         //\r
183         // http://tools.ietf.org/html/rfc4253#section-7.2\r
184         //\r
185         // see the is_string($crypto) part for an example of how to expand the keys\r
186         $key = pack('H*', sha1($seed . 'A'));\r
187         $iv = pack('H*', sha1($seed . 'C'));\r
188 \r
189         // ciphers are used as per the nist.gov link below. also, see this link:\r
190         //\r
191         // http://en.wikipedia.org/wiki/Cryptographically_secure_pseudorandom_number_generator#Designs_based_on_cryptographic_primitives\r
192         switch (true) {\r
193             case class_exists('Crypt_AES'):\r
194                 $crypto = new Crypt_AES(CRYPT_AES_MODE_CTR);\r
195                 break;\r
196             case class_exists('Crypt_TripleDES'):\r
197                 $crypto = new Crypt_TripleDES(CRYPT_DES_MODE_CTR);\r
198                 break;\r
199             case class_exists('Crypt_DES'):\r
200                 $crypto = new Crypt_DES(CRYPT_DES_MODE_CTR);\r
201                 break;\r
202             case class_exists('Crypt_RC4'):\r
203                 $crypto = new Crypt_RC4();\r
204                 break;\r
205             default:\r
206                 $crypto = $seed;\r
207                 return crypt_random_string($length);\r
208         }\r
209 \r
210         $crypto->setKey($key);\r
211         $crypto->setIV($iv);\r
212         $crypto->enableContinuousBuffer();\r
213     }\r
214 \r
215     if (is_string($crypto)) {\r
216         // the following is based off of ANSI X9.31:\r
217         //\r
218         // http://csrc.nist.gov/groups/STM/cavp/documents/rng/931rngext.pdf\r
219         //\r
220         // OpenSSL uses that same standard for it's random numbers:\r
221         //\r
222         // http://www.opensource.apple.com/source/OpenSSL/OpenSSL-38/openssl/fips-1.0/rand/fips_rand.c\r
223         // (do a search for "ANS X9.31 A.2.4")\r
224         //\r
225         // ANSI X9.31 recommends ciphers be used and phpseclib does use them if they're available (see\r
226         // later on in the code) but if they're not we'll use sha1\r
227         $result = '';\r
228         while (strlen($result) < $length) { // each loop adds 20 bytes\r
229             // microtime() isn't packed as "densely" as it could be but then neither is that the idea.\r
230             // the idea is simply to ensure that each "block" has a unique element to it.\r
231             $i = pack('H*', sha1(microtime()));\r
232             $r = pack('H*', sha1($i ^ $v));\r
233             $v = pack('H*', sha1($r ^ $i));\r
234             $result.= $r;\r
235         }\r
236         return substr($result, 0, $length);\r
237     }\r
238 \r
239     //return $crypto->encrypt(str_repeat("\0", $length));\r
240 \r
241     $result = '';\r
242     while (strlen($result) < $length) {\r
243         $i = $crypto->encrypt(microtime());\r
244         $r = $crypto->encrypt($i ^ $v);\r
245         $v = $crypto->encrypt($r ^ $i);\r
246         $result.= $r;\r
247     }\r
248     return substr($result, 0, $length);\r
249 }\r