[CORE] Use random_bytes() if available and improve common_confirmation_code() randomness.

With PHP 7 comes the [random_bytes()](https://php.net/manual/en/function.random-bytes.php) and the [random_int()](https://www.php.net/manual/en/function.random-int.php) function which generates cryptographically secure pseudo-random bytes and integers, respectively.
This commit is contained in:
Diogo Cordeiro 2019-06-22 18:57:43 +01:00
parent f0f5ecb756
commit d705bcbd98
2 changed files with 15 additions and 20 deletions

View File

@ -32,7 +32,7 @@ defined('GNUSOCIAL') || die();
define('GNUSOCIAL_ENGINE', 'GNU social'); define('GNUSOCIAL_ENGINE', 'GNU social');
define('GNUSOCIAL_ENGINE_URL', 'https://www.gnu.org/software/social/'); define('GNUSOCIAL_ENGINE_URL', 'https://www.gnu.org/software/social/');
define('GNUSOCIAL_BASE_VERSION', '1.20.8'); define('GNUSOCIAL_BASE_VERSION', '1.20.9');
define('GNUSOCIAL_LIFECYCLE', 'release'); // 'dev', 'alpha[0-9]+', 'beta[0-9]+', 'rc[0-9]+', 'release' define('GNUSOCIAL_LIFECYCLE', 'release'); // 'dev', 'alpha[0-9]+', 'beta[0-9]+', 'rc[0-9]+', 'release'
define('GNUSOCIAL_VERSION', GNUSOCIAL_BASE_VERSION . '-' . GNUSOCIAL_LIFECYCLE); define('GNUSOCIAL_VERSION', GNUSOCIAL_BASE_VERSION . '-' . GNUSOCIAL_LIFECYCLE);

View File

@ -1744,13 +1744,7 @@ function common_random_rawstr($bytes)
*/ */
function common_random_hexstr($bytes) function common_random_hexstr($bytes)
{ {
$str = common_random_rawstr($bytes); return bin2hex(random_bytes($bytes));
$hexstr = '';
for ($i = 0; $i < $bytes; $i++) {
$hexstr .= sprintf("%02x", ord($str[$i]));
}
return $hexstr;
} }
function common_urandom($bytes) function common_urandom($bytes)
@ -2224,20 +2218,21 @@ function common_user_uri(&$user)
false); false);
} }
// 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits /**
* Generates cryptographically secure pseudo-random strings out of a allowed chars string
function common_confirmation_code($bits) *
{ * @param $bits int strength of the confirmation code
// 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits * @param $codechars allowed characters to be used in the confirmation code, by default we use 36 upper case
static $codechars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ'; * alphanums and remove lookalikes (0, O, 1, I) = 32 chars = 5 bits to make it easy for the user to type in
* @return string confirmation_code of length $bits/5
*/
function common_confirmation_code($bits, $codechars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ') {
$chars = ceil($bits/5); $chars = ceil($bits/5);
$codechars_length = strlen($codechars)-1;
$code = ''; $code = '';
for ($i = 0; $i < $chars; $i++) { for($i = 0; $i < $chars; ++$i) {
// XXX: convert to string and back $random_char = $codechars[random_int(0, $codechars_length)];
$num = hexdec(common_random_hexstr(1)); $code .= $random_char;
// XXX: randomness is too precious to throw away almost
// 40% of the bits we get!
$code .= $codechars[$num%32];
} }
return $code; return $code;
} }