From d705bcbd98ed9d7f69214c32f2e650ccca6a1589 Mon Sep 17 00:00:00 2001 From: Diogo Cordeiro Date: Sat, 22 Jun 2019 18:57:43 +0100 Subject: [PATCH] [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. --- lib/framework.php | 2 +- lib/util.php | 33 ++++++++++++++------------------- 2 files changed, 15 insertions(+), 20 deletions(-) diff --git a/lib/framework.php b/lib/framework.php index 80c13c92e9..0b34091836 100644 --- a/lib/framework.php +++ b/lib/framework.php @@ -32,7 +32,7 @@ defined('GNUSOCIAL') || die(); define('GNUSOCIAL_ENGINE', 'GNU 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_VERSION', GNUSOCIAL_BASE_VERSION . '-' . GNUSOCIAL_LIFECYCLE); diff --git a/lib/util.php b/lib/util.php index 38bc305b93..45d5b2b8f2 100644 --- a/lib/util.php +++ b/lib/util.php @@ -1744,13 +1744,7 @@ function common_random_rawstr($bytes) */ function common_random_hexstr($bytes) { - $str = common_random_rawstr($bytes); - - $hexstr = ''; - for ($i = 0; $i < $bytes; $i++) { - $hexstr .= sprintf("%02x", ord($str[$i])); - } - return $hexstr; + return bin2hex(random_bytes($bytes)); } function common_urandom($bytes) @@ -2224,20 +2218,21 @@ function common_user_uri(&$user) false); } -// 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits - -function common_confirmation_code($bits) -{ - // 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits - static $codechars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ'; +/** + * Generates cryptographically secure pseudo-random strings out of a allowed chars string + * + * @param $bits int strength of the confirmation code + * @param $codechars allowed characters to be used in the confirmation code, by default we use 36 upper case + * 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); + $codechars_length = strlen($codechars)-1; $code = ''; - for ($i = 0; $i < $chars; $i++) { - // XXX: convert to string and back - $num = hexdec(common_random_hexstr(1)); - // XXX: randomness is too precious to throw away almost - // 40% of the bits we get! - $code .= $codechars[$num%32]; + for($i = 0; $i < $chars; ++$i) { + $random_char = $codechars[random_int(0, $codechars_length)]; + $code .= $random_char; } return $code; } -- 2.39.5