Merge pull request #3961 from MrPetovan/task/3946-use-random-bytes

Use random_bytes() in random_string()
This commit is contained in:
Michael Vogel 2017-11-26 14:24:48 +01:00 committed by GitHub
commit 28594f6d25
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
26 changed files with 1588 additions and 20 deletions

View File

@ -18,7 +18,8 @@
"league/html-to-markdown": "~4.4.1",
"defuse/php-encryption": "1.*",
"pear/Text_LanguageDetect": "1.*",
"pear-pear.php.net/Text_Highlighter": "*"
"pear-pear.php.net/Text_Highlighter": "*",
"paragonie/random_compat": "^2.0"
},
"repositories": [
{

50
composer.lock generated
View File

@ -4,7 +4,7 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file",
"This file is @generated automatically"
],
"content-hash": "a6a3dae4b15752d8f377b1fc1e5a2b47",
"content-hash": "a5c0c297b0e8185f2bcd3aad20ec5acc",
"packages": [
{
"name": "defuse/php-encryption",
@ -211,6 +211,54 @@
],
"time": "2017-08-29T18:23:54+00:00"
},
{
"name": "paragonie/random_compat",
"version": "v2.0.11",
"source": {
"type": "git",
"url": "https://github.com/paragonie/random_compat.git",
"reference": "5da4d3c796c275c55f057af5a643ae297d96b4d8"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/paragonie/random_compat/zipball/5da4d3c796c275c55f057af5a643ae297d96b4d8",
"reference": "5da4d3c796c275c55f057af5a643ae297d96b4d8",
"shasum": ""
},
"require": {
"php": ">=5.2.0"
},
"require-dev": {
"phpunit/phpunit": "4.*|5.*"
},
"suggest": {
"ext-libsodium": "Provides a modern crypto API that can be used to generate random bytes."
},
"type": "library",
"autoload": {
"files": [
"lib/random.php"
]
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Paragon Initiative Enterprises",
"email": "security@paragonie.com",
"homepage": "https://paragonie.com"
}
],
"description": "PHP 5.x polyfill for random_bytes() and random_int() from PHP 7",
"keywords": [
"csprng",
"pseudorandom",
"random"
],
"time": "2017-09-27T21:40:39+00:00"
},
{
"name": "pear-pear.php.net/Archive_Tar",
"version": "1.4.3",

View File

@ -41,18 +41,21 @@ function replace_macros($s, $r) {
return $output;
}
/**
* @brief Generates a pseudo-random string of hexadecimal characters
*
* @param int $size
* @return string
*/
function random_string($size = 64)
{
$byte_size = ceil($size / 2);
// random string, there are 86 characters max in text mode, 128 for hex
// output is urlsafe
$bytes = random_bytes($byte_size);
define('RANDOM_STRING_HEX', 0x00);
define('RANDOM_STRING_TEXT', 0x01);
$return = substr(bin2hex($bytes), 0, $size);
function random_string($size = 64, $type = RANDOM_STRING_HEX) {
// generate a bit of entropy and run it through the whirlpool
$s = hash('whirlpool', (string) rand() . uniqid(rand(),true) . (string) rand(), (($type == RANDOM_STRING_TEXT) ? true : false));
$s = (($type == RANDOM_STRING_TEXT) ? str_replace("\n", "", base64url_encode($s,true)) : $s);
return substr($s,0,$size);
return $return;
}
/**
@ -1147,7 +1150,7 @@ function get_mood_verbs() {
/**
* @brief Translate days and months names.
*
*
* @param string $s String with day or month name.
* @return string Translated string.
*/
@ -1165,7 +1168,7 @@ function day_translate($s) {
/**
* @brief Translate short days and months names.
*
*
* @param string $s String with short day or month name.
* @return string Translated string.
*/

View File

@ -616,7 +616,7 @@ function update_1075() {
foreach ($r as $rr) {
$found = true;
do {
$guid = substr(random_string(),0,16);
$guid = random_string(16);
$x = q("SELECT `uid` FROM `user` WHERE `guid` = '%s' LIMIT 1",
dbesc($guid)
);

View File

@ -10,35 +10,71 @@ return array(
'Console_Getopt' => $vendorDir . '/pear-pear.php.net/Console_Getopt/Console/Getopt.php',
'Detection\\MobileDetect' => $vendorDir . '/mobiledetect/mobiledetectlib/namespaced/Detection/MobileDetect.php',
'Friendica\\App' => $baseDir . '/src/App.php',
'Friendica\\BaseObject' => $baseDir . '/src/BaseObject.php',
'Friendica\\Content\\ForumManager' => $baseDir . '/src/Content/ForumManager.php',
'Friendica\\Content\\Smilies' => $baseDir . '/src/Content/Smilies.php',
'Friendica\\Core\\BaseObject' => $baseDir . '/src/Core/BaseObject.php',
'Friendica\\Core\\Cache' => $baseDir . '/src/Core/Cache.php',
'Friendica\\Core\\Config' => $baseDir . '/src/Core/Config.php',
'Friendica\\Core\\Conversation' => $baseDir . '/src/Core/Conversation.php',
'Friendica\\Core\\Item' => $baseDir . '/src/Core/Item.php',
'Friendica\\Core\\NotificationsManager' => $baseDir . '/src/Core/NotificationsManager.php',
'Friendica\\Core\\PConfig' => $baseDir . '/src/Core/PConfig.php',
'Friendica\\Core\\System' => $baseDir . '/src/Core/System.php',
'Friendica\\Core\\Worker' => $baseDir . '/src/Core/Worker.php',
'Friendica\\Database\\DBM' => $baseDir . '/src/Database/DBM.php',
'Friendica\\Model\\GlobalContact' => $baseDir . '/src/Model/GlobalContact.php',
'Friendica\\Model\\User' => $baseDir . '/src/Model/User.php',
'Friendica\\Network\\HTTPException' => $baseDir . '/src/Network/HTTPException.php',
'Friendica\\Network\\HTTPException\\BadGatewayException' => $baseDir . '/src/Network/HTTPException/BadGatewayException.php',
'Friendica\\Network\\HTTPException\\BadRequestException' => $baseDir . '/src/Network/HTTPException/BadRequestException.php',
'Friendica\\Network\\HTTPException\\ConflictException' => $baseDir . '/src/Network/HTTPException/ConflictException.php',
'Friendica\\Network\\HTTPException\\ExpectationFailedException' => $baseDir . '/src/Network/HTTPException/ExpectationFailedException.php',
'Friendica\\Network\\HTTPException\\ForbiddenException' => $baseDir . '/src/Network/HTTPException/ForbiddenException.php',
'Friendica\\Network\\HTTPException\\GatewayTimeoutException' => $baseDir . '/src/Network/HTTPException/GatewayTimeoutException.php',
'Friendica\\Network\\HTTPException\\GoneException' => $baseDir . '/src/Network/HTTPException/GoneException.php',
'Friendica\\Network\\HTTPException\\ImATeapotException' => $baseDir . '/src/Network/HTTPException/ImATeapotException.php',
'Friendica\\Network\\HTTPException\\InternalServerErrorException' => $baseDir . '/src/Network/HTTPException/InternalServerErrorException.php',
'Friendica\\Network\\HTTPException\\LenghtRequiredException' => $baseDir . '/src/Network/HTTPException/LenghtRequiredException.php',
'Friendica\\Network\\HTTPException\\MethodNotAllowedException' => $baseDir . '/src/Network/HTTPException/MethodNotAllowedException.php',
'Friendica\\Network\\HTTPException\\NonAcceptableException' => $baseDir . '/src/Network/HTTPException/NonAcceptableException.php',
'Friendica\\Network\\HTTPException\\NotFoundException' => $baseDir . '/src/Network/HTTPException/NotFoundException.php',
'Friendica\\Network\\HTTPException\\NotImplementedException' => $baseDir . '/src/Network/HTTPException/NotImplementedException.php',
'Friendica\\Network\\HTTPException\\PreconditionFailedException' => $baseDir . '/src/Network/HTTPException/PreconditionFailedException.php',
'Friendica\\Network\\HTTPException\\ServiceUnavaiableException' => $baseDir . '/src/Network/HTTPException/ServiceUnavaiableException.php',
'Friendica\\Network\\HTTPException\\TooManyRequestsException' => $baseDir . '/src/Network/HTTPException/TooManyRequestsException.php',
'Friendica\\Network\\HTTPException\\UnauthorizedException' => $baseDir . '/src/Network/HTTPException/UnauthorizedException.php',
'Friendica\\Network\\HTTPException\\UnprocessableEntityException' => $baseDir . '/src/Network/HTTPException/UnprocessableEntityException.php',
'Friendica\\Network\\HTTPException\\UnsupportedMediaTypeException' => $baseDir . '/src/Network/HTTPException/UnsupportedMediaTypeException.php',
'Friendica\\Network\\Probe' => $baseDir . '/src/Network/Probe.php',
'Friendica\\Object\\Contact' => $baseDir . '/src/Object/Contact.php',
'Friendica\\Object\\Conversation' => $baseDir . '/src/Object/Conversation.php',
'Friendica\\Object\\Item' => $baseDir . '/src/Object/Item.php',
'Friendica\\Object\\Profile' => $baseDir . '/src/Object/Profile.php',
'Friendica\\ParseUrl' => $baseDir . '/src/ParseUrl.php',
'Friendica\\Protocol\\DFRN' => $baseDir . '/src/Protocol/DFRN.php',
'Friendica\\Protocol\\Diaspora' => $baseDir . '/src/Protocol/Diaspora.php',
'Friendica\\Protocol\\OStatus' => $baseDir . '/src/Protocol/OStatus.php',
'Friendica\\Protocol\\PortableContact' => $baseDir . '/src/Protocol/PortableContact.php',
'Friendica\\Render\\ITemplateEngine' => $baseDir . '/src/Render/ITemplateEngine.php',
'Friendica\\Util\\Emailer' => $baseDir . '/src/Util/Emailer.php',
'Friendica\\Util\\ExAuth' => $baseDir . '/src/Util/ExAuth.php',
'Friendica\\Util\\Lock' => $baseDir . '/src/Util/Lock.php',
'Friendica\\Util\\XML' => $baseDir . '/src/Util/XML.php',
'Friendica\\Worker\\CheckVersion' => $baseDir . '/src/Worker/CheckVersion.php',
'Friendica\\Worker\\CreateShadowEntry' => $baseDir . '/src/Worker/CreateShadowEntry.php',
'Friendica\\Worker\\Cron' => $baseDir . '/src/Worker/Cron.php',
'Friendica\\Worker\\CronHooks' => $baseDir . '/src/Worker/CronHooks.php',
'Friendica\\Worker\\CronJobs' => $baseDir . '/src/Worker/CronJobs.php',
'Friendica\\Worker\\DBClean' => $baseDir . '/src/Worker/DBClean.php',
'Friendica\\Worker\\DBUpdate' => $baseDir . '/src/Worker/DBUpdate.php',
'Friendica\\Worker\\Delivery' => $baseDir . '/src/Worker/Delivery.php',
'Friendica\\Worker\\Directory' => $baseDir . '/src/Worker/Directory.php',
'Friendica\\Worker\\DiscoverPoCo' => $baseDir . '/src/Worker/DiscoverPoCo.php',
'Friendica\\Worker\\Expire' => $baseDir . '/src/Worker/Expire.php',
'Friendica\\Worker\\GProbe' => $baseDir . '/src/Worker/GProbe.php',
'Friendica\\Worker\\Notifier' => $baseDir . '/src/Worker/Notifier.php',
'Friendica\\Worker\\OnePoll' => $baseDir . '/src/Worker/OnePoll.php',
'Friendica\\Worker\\ProfileUpdate' => $baseDir . '/src/Worker/ProfileUpdate.php',
'Friendica\\Worker\\PubSubPublish' => $baseDir . '/src/Worker/PubSubPublish.php',
'Friendica\\Worker\\Queue' => $baseDir . '/src/Worker/Queue.php',
'Friendica\\Worker\\RemoveContact' => $baseDir . '/src/Worker/RemoveContact.php',
'Friendica\\Worker\\SpoolPost' => $baseDir . '/src/Worker/SpoolPost.php',
'Friendica\\Worker\\TagUpdate' => $baseDir . '/src/Worker/TagUpdate.php',

View File

@ -8,4 +8,5 @@ $baseDir = dirname($vendorDir);
return array(
'2cffec82183ee1cea088009cef9a6fc3' => $vendorDir . '/ezyang/htmlpurifier/library/HTMLPurifier.composer.php',
'8170285c807a9f24f165f37b15bc9a36' => $vendorDir . '/defuse/php-encryption/Crypto.php',
'5255c38a0faeba867671b61dfda6d864' => $vendorDir . '/paragonie/random_compat/lib/random.php',
);

View File

@ -9,6 +9,7 @@ class ComposerStaticInitFriendica
public static $files = array (
'2cffec82183ee1cea088009cef9a6fc3' => __DIR__ . '/..' . '/ezyang/htmlpurifier/library/HTMLPurifier.composer.php',
'8170285c807a9f24f165f37b15bc9a36' => __DIR__ . '/..' . '/defuse/php-encryption/Crypto.php',
'5255c38a0faeba867671b61dfda6d864' => __DIR__ . '/..' . '/paragonie/random_compat/lib/random.php',
);
public static $prefixLengthsPsr4 = array (
@ -62,35 +63,71 @@ class ComposerStaticInitFriendica
'Console_Getopt' => __DIR__ . '/..' . '/pear-pear.php.net/Console_Getopt/Console/Getopt.php',
'Detection\\MobileDetect' => __DIR__ . '/..' . '/mobiledetect/mobiledetectlib/namespaced/Detection/MobileDetect.php',
'Friendica\\App' => __DIR__ . '/../..' . '/src/App.php',
'Friendica\\BaseObject' => __DIR__ . '/../..' . '/src/BaseObject.php',
'Friendica\\Content\\ForumManager' => __DIR__ . '/../..' . '/src/Content/ForumManager.php',
'Friendica\\Content\\Smilies' => __DIR__ . '/../..' . '/src/Content/Smilies.php',
'Friendica\\Core\\BaseObject' => __DIR__ . '/../..' . '/src/Core/BaseObject.php',
'Friendica\\Core\\Cache' => __DIR__ . '/../..' . '/src/Core/Cache.php',
'Friendica\\Core\\Config' => __DIR__ . '/../..' . '/src/Core/Config.php',
'Friendica\\Core\\Conversation' => __DIR__ . '/../..' . '/src/Core/Conversation.php',
'Friendica\\Core\\Item' => __DIR__ . '/../..' . '/src/Core/Item.php',
'Friendica\\Core\\NotificationsManager' => __DIR__ . '/../..' . '/src/Core/NotificationsManager.php',
'Friendica\\Core\\PConfig' => __DIR__ . '/../..' . '/src/Core/PConfig.php',
'Friendica\\Core\\System' => __DIR__ . '/../..' . '/src/Core/System.php',
'Friendica\\Core\\Worker' => __DIR__ . '/../..' . '/src/Core/Worker.php',
'Friendica\\Database\\DBM' => __DIR__ . '/../..' . '/src/Database/DBM.php',
'Friendica\\Model\\GlobalContact' => __DIR__ . '/../..' . '/src/Model/GlobalContact.php',
'Friendica\\Model\\User' => __DIR__ . '/../..' . '/src/Model/User.php',
'Friendica\\Network\\HTTPException' => __DIR__ . '/../..' . '/src/Network/HTTPException.php',
'Friendica\\Network\\HTTPException\\BadGatewayException' => __DIR__ . '/../..' . '/src/Network/HTTPException/BadGatewayException.php',
'Friendica\\Network\\HTTPException\\BadRequestException' => __DIR__ . '/../..' . '/src/Network/HTTPException/BadRequestException.php',
'Friendica\\Network\\HTTPException\\ConflictException' => __DIR__ . '/../..' . '/src/Network/HTTPException/ConflictException.php',
'Friendica\\Network\\HTTPException\\ExpectationFailedException' => __DIR__ . '/../..' . '/src/Network/HTTPException/ExpectationFailedException.php',
'Friendica\\Network\\HTTPException\\ForbiddenException' => __DIR__ . '/../..' . '/src/Network/HTTPException/ForbiddenException.php',
'Friendica\\Network\\HTTPException\\GatewayTimeoutException' => __DIR__ . '/../..' . '/src/Network/HTTPException/GatewayTimeoutException.php',
'Friendica\\Network\\HTTPException\\GoneException' => __DIR__ . '/../..' . '/src/Network/HTTPException/GoneException.php',
'Friendica\\Network\\HTTPException\\ImATeapotException' => __DIR__ . '/../..' . '/src/Network/HTTPException/ImATeapotException.php',
'Friendica\\Network\\HTTPException\\InternalServerErrorException' => __DIR__ . '/../..' . '/src/Network/HTTPException/InternalServerErrorException.php',
'Friendica\\Network\\HTTPException\\LenghtRequiredException' => __DIR__ . '/../..' . '/src/Network/HTTPException/LenghtRequiredException.php',
'Friendica\\Network\\HTTPException\\MethodNotAllowedException' => __DIR__ . '/../..' . '/src/Network/HTTPException/MethodNotAllowedException.php',
'Friendica\\Network\\HTTPException\\NonAcceptableException' => __DIR__ . '/../..' . '/src/Network/HTTPException/NonAcceptableException.php',
'Friendica\\Network\\HTTPException\\NotFoundException' => __DIR__ . '/../..' . '/src/Network/HTTPException/NotFoundException.php',
'Friendica\\Network\\HTTPException\\NotImplementedException' => __DIR__ . '/../..' . '/src/Network/HTTPException/NotImplementedException.php',
'Friendica\\Network\\HTTPException\\PreconditionFailedException' => __DIR__ . '/../..' . '/src/Network/HTTPException/PreconditionFailedException.php',
'Friendica\\Network\\HTTPException\\ServiceUnavaiableException' => __DIR__ . '/../..' . '/src/Network/HTTPException/ServiceUnavaiableException.php',
'Friendica\\Network\\HTTPException\\TooManyRequestsException' => __DIR__ . '/../..' . '/src/Network/HTTPException/TooManyRequestsException.php',
'Friendica\\Network\\HTTPException\\UnauthorizedException' => __DIR__ . '/../..' . '/src/Network/HTTPException/UnauthorizedException.php',
'Friendica\\Network\\HTTPException\\UnprocessableEntityException' => __DIR__ . '/../..' . '/src/Network/HTTPException/UnprocessableEntityException.php',
'Friendica\\Network\\HTTPException\\UnsupportedMediaTypeException' => __DIR__ . '/../..' . '/src/Network/HTTPException/UnsupportedMediaTypeException.php',
'Friendica\\Network\\Probe' => __DIR__ . '/../..' . '/src/Network/Probe.php',
'Friendica\\Object\\Contact' => __DIR__ . '/../..' . '/src/Object/Contact.php',
'Friendica\\Object\\Conversation' => __DIR__ . '/../..' . '/src/Object/Conversation.php',
'Friendica\\Object\\Item' => __DIR__ . '/../..' . '/src/Object/Item.php',
'Friendica\\Object\\Profile' => __DIR__ . '/../..' . '/src/Object/Profile.php',
'Friendica\\ParseUrl' => __DIR__ . '/../..' . '/src/ParseUrl.php',
'Friendica\\Protocol\\DFRN' => __DIR__ . '/../..' . '/src/Protocol/DFRN.php',
'Friendica\\Protocol\\Diaspora' => __DIR__ . '/../..' . '/src/Protocol/Diaspora.php',
'Friendica\\Protocol\\OStatus' => __DIR__ . '/../..' . '/src/Protocol/OStatus.php',
'Friendica\\Protocol\\PortableContact' => __DIR__ . '/../..' . '/src/Protocol/PortableContact.php',
'Friendica\\Render\\ITemplateEngine' => __DIR__ . '/../..' . '/src/Render/ITemplateEngine.php',
'Friendica\\Util\\Emailer' => __DIR__ . '/../..' . '/src/Util/Emailer.php',
'Friendica\\Util\\ExAuth' => __DIR__ . '/../..' . '/src/Util/ExAuth.php',
'Friendica\\Util\\Lock' => __DIR__ . '/../..' . '/src/Util/Lock.php',
'Friendica\\Util\\XML' => __DIR__ . '/../..' . '/src/Util/XML.php',
'Friendica\\Worker\\CheckVersion' => __DIR__ . '/../..' . '/src/Worker/CheckVersion.php',
'Friendica\\Worker\\CreateShadowEntry' => __DIR__ . '/../..' . '/src/Worker/CreateShadowEntry.php',
'Friendica\\Worker\\Cron' => __DIR__ . '/../..' . '/src/Worker/Cron.php',
'Friendica\\Worker\\CronHooks' => __DIR__ . '/../..' . '/src/Worker/CronHooks.php',
'Friendica\\Worker\\CronJobs' => __DIR__ . '/../..' . '/src/Worker/CronJobs.php',
'Friendica\\Worker\\DBClean' => __DIR__ . '/../..' . '/src/Worker/DBClean.php',
'Friendica\\Worker\\DBUpdate' => __DIR__ . '/../..' . '/src/Worker/DBUpdate.php',
'Friendica\\Worker\\Delivery' => __DIR__ . '/../..' . '/src/Worker/Delivery.php',
'Friendica\\Worker\\Directory' => __DIR__ . '/../..' . '/src/Worker/Directory.php',
'Friendica\\Worker\\DiscoverPoCo' => __DIR__ . '/../..' . '/src/Worker/DiscoverPoCo.php',
'Friendica\\Worker\\Expire' => __DIR__ . '/../..' . '/src/Worker/Expire.php',
'Friendica\\Worker\\GProbe' => __DIR__ . '/../..' . '/src/Worker/GProbe.php',
'Friendica\\Worker\\Notifier' => __DIR__ . '/../..' . '/src/Worker/Notifier.php',
'Friendica\\Worker\\OnePoll' => __DIR__ . '/../..' . '/src/Worker/OnePoll.php',
'Friendica\\Worker\\ProfileUpdate' => __DIR__ . '/../..' . '/src/Worker/ProfileUpdate.php',
'Friendica\\Worker\\PubSubPublish' => __DIR__ . '/../..' . '/src/Worker/PubSubPublish.php',
'Friendica\\Worker\\Queue' => __DIR__ . '/../..' . '/src/Worker/Queue.php',
'Friendica\\Worker\\RemoveContact' => __DIR__ . '/../..' . '/src/Worker/RemoveContact.php',
'Friendica\\Worker\\SpoolPost' => __DIR__ . '/../..' . '/src/Worker/SpoolPost.php',
'Friendica\\Worker\\TagUpdate' => __DIR__ . '/../..' . '/src/Worker/TagUpdate.php',

View File

@ -489,5 +489,55 @@
"mcrypt",
"security"
]
},
{
"name": "paragonie/random_compat",
"version": "v2.0.11",
"version_normalized": "2.0.11.0",
"source": {
"type": "git",
"url": "https://github.com/paragonie/random_compat.git",
"reference": "5da4d3c796c275c55f057af5a643ae297d96b4d8"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/paragonie/random_compat/zipball/5da4d3c796c275c55f057af5a643ae297d96b4d8",
"reference": "5da4d3c796c275c55f057af5a643ae297d96b4d8",
"shasum": ""
},
"require": {
"php": ">=5.2.0"
},
"require-dev": {
"phpunit/phpunit": "4.*|5.*"
},
"suggest": {
"ext-libsodium": "Provides a modern crypto API that can be used to generate random bytes."
},
"time": "2017-09-27T21:40:39+00:00",
"type": "library",
"installation-source": "dist",
"autoload": {
"files": [
"lib/random.php"
]
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Paragon Initiative Enterprises",
"email": "security@paragonie.com",
"homepage": "https://paragonie.com"
}
],
"description": "PHP 5.x polyfill for random_bytes() and random_int() from PHP 7",
"keywords": [
"csprng",
"pseudorandom",
"random"
]
}
]

22
vendor/paragonie/random_compat/LICENSE vendored Normal file
View File

@ -0,0 +1,22 @@
The MIT License (MIT)
Copyright (c) 2015 Paragon Initiative Enterprises
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@ -0,0 +1,5 @@
#!/usr/bin/env bash
basedir=$( dirname $( readlink -f ${BASH_SOURCE[0]} ) )
php -dphar.readonly=0 "$basedir/other/build_phar.php" $*

View File

@ -0,0 +1,37 @@
{
"name": "paragonie/random_compat",
"description": "PHP 5.x polyfill for random_bytes() and random_int() from PHP 7",
"keywords": [
"csprng",
"random",
"pseudorandom"
],
"license": "MIT",
"type": "library",
"authors": [
{
"name": "Paragon Initiative Enterprises",
"email": "security@paragonie.com",
"homepage": "https://paragonie.com"
}
],
"support": {
"issues": "https://github.com/paragonie/random_compat/issues",
"email": "info@paragonie.com",
"source": "https://github.com/paragonie/random_compat"
},
"require": {
"php": ">=5.2.0"
},
"require-dev": {
"phpunit/phpunit": "4.*|5.*"
},
"suggest": {
"ext-libsodium": "Provides a modern crypto API that can be used to generate random bytes."
},
"autoload": {
"files": [
"lib/random.php"
]
}
}

View File

@ -0,0 +1,5 @@
-----BEGIN PUBLIC KEY-----
MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAEEd+wCqJDrx5B4OldM0dQE0ZMX+lx1ZWm
pui0SUqD4G29L3NGsz9UhJ/0HjBdbnkhIK5xviT0X5vtjacF6ajgcCArbTB+ds+p
+h7Q084NuSuIpNb6YPfoUFgC/CL9kAoc
-----END PUBLIC KEY-----

View File

@ -0,0 +1,11 @@
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v2.0.22 (MingW32)
iQEcBAABAgAGBQJWtW1hAAoJEGuXocKCZATaJf0H+wbZGgskK1dcRTsuVJl9IWip
QwGw/qIKI280SD6/ckoUMxKDCJiFuPR14zmqnS36k7N5UNPnpdTJTS8T11jttSpg
1LCmgpbEIpgaTah+cELDqFCav99fS+bEiAL5lWDAHBTE/XPjGVCqeehyPYref4IW
NDBIEsvnHPHPLsn6X5jq4+Yj5oUixgxaMPiR+bcO4Sh+RzOVB6i2D0upWfRXBFXA
NNnsg9/zjvoC7ZW73y9uSH+dPJTt/Vgfeiv52/v41XliyzbUyLalf02GNPY+9goV
JHG1ulEEBJOCiUD9cE1PUIJwHA/HqyhHIvV350YoEFiHl8iSwm7SiZu5kPjaq74=
=B6+8
-----END PGP SIGNATURE-----

View File

@ -0,0 +1,181 @@
<?php
/**
* Random_* Compatibility Library
* for using the new PHP 7 random_* API in PHP 5 projects
*
* The MIT License (MIT)
*
* Copyright (c) 2015 - 2017 Paragon Initiative Enterprises
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
if (!is_callable('RandomCompat_strlen')) {
if (
defined('MB_OVERLOAD_STRING') &&
ini_get('mbstring.func_overload') & MB_OVERLOAD_STRING
) {
/**
* strlen() implementation that isn't brittle to mbstring.func_overload
*
* This version uses mb_strlen() in '8bit' mode to treat strings as raw
* binary rather than UTF-8, ISO-8859-1, etc
*
* @param string $binary_string
*
* @throws TypeError
*
* @return int
*/
function RandomCompat_strlen($binary_string)
{
if (!is_string($binary_string)) {
throw new TypeError(
'RandomCompat_strlen() expects a string'
);
}
return (int) mb_strlen($binary_string, '8bit');
}
} else {
/**
* strlen() implementation that isn't brittle to mbstring.func_overload
*
* This version just used the default strlen()
*
* @param string $binary_string
*
* @throws TypeError
*
* @return int
*/
function RandomCompat_strlen($binary_string)
{
if (!is_string($binary_string)) {
throw new TypeError(
'RandomCompat_strlen() expects a string'
);
}
return (int) strlen($binary_string);
}
}
}
if (!is_callable('RandomCompat_substr')) {
if (
defined('MB_OVERLOAD_STRING')
&&
ini_get('mbstring.func_overload') & MB_OVERLOAD_STRING
) {
/**
* substr() implementation that isn't brittle to mbstring.func_overload
*
* This version uses mb_substr() in '8bit' mode to treat strings as raw
* binary rather than UTF-8, ISO-8859-1, etc
*
* @param string $binary_string
* @param int $start
* @param int $length (optional)
*
* @throws TypeError
*
* @return string
*/
function RandomCompat_substr($binary_string, $start, $length = null)
{
if (!is_string($binary_string)) {
throw new TypeError(
'RandomCompat_substr(): First argument should be a string'
);
}
if (!is_int($start)) {
throw new TypeError(
'RandomCompat_substr(): Second argument should be an integer'
);
}
if ($length === null) {
/**
* mb_substr($str, 0, NULL, '8bit') returns an empty string on
* PHP 5.3, so we have to find the length ourselves.
*/
$length = RandomCompat_strlen($binary_string) - $start;
} elseif (!is_int($length)) {
throw new TypeError(
'RandomCompat_substr(): Third argument should be an integer, or omitted'
);
}
// Consistency with PHP's behavior
if ($start === RandomCompat_strlen($binary_string) && $length === 0) {
return '';
}
if ($start > RandomCompat_strlen($binary_string)) {
return '';
}
return (string) mb_substr($binary_string, $start, $length, '8bit');
}
} else {
/**
* substr() implementation that isn't brittle to mbstring.func_overload
*
* This version just uses the default substr()
*
* @param string $binary_string
* @param int $start
* @param int $length (optional)
*
* @throws TypeError
*
* @return string
*/
function RandomCompat_substr($binary_string, $start, $length = null)
{
if (!is_string($binary_string)) {
throw new TypeError(
'RandomCompat_substr(): First argument should be a string'
);
}
if (!is_int($start)) {
throw new TypeError(
'RandomCompat_substr(): Second argument should be an integer'
);
}
if ($length !== null) {
if (!is_int($length)) {
throw new TypeError(
'RandomCompat_substr(): Third argument should be an integer, or omitted'
);
}
return (string) substr($binary_string, $start, $length);
}
return (string) substr($binary_string, $start);
}
}
}

View File

@ -0,0 +1,75 @@
<?php
/**
* Random_* Compatibility Library
* for using the new PHP 7 random_* API in PHP 5 projects
*
* The MIT License (MIT)
*
* Copyright (c) 2015 - 2017 Paragon Initiative Enterprises
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
if (!is_callable('RandomCompat_intval')) {
/**
* Cast to an integer if we can, safely.
*
* If you pass it a float in the range (~PHP_INT_MAX, PHP_INT_MAX)
* (non-inclusive), it will sanely cast it to an int. If you it's equal to
* ~PHP_INT_MAX or PHP_INT_MAX, we let it fail as not an integer. Floats
* lose precision, so the <= and => operators might accidentally let a float
* through.
*
* @param int|float $number The number we want to convert to an int
* @param bool $fail_open Set to true to not throw an exception
*
* @return float|int
* @psalm-suppress InvalidReturnType
*
* @throws TypeError
*/
function RandomCompat_intval($number, $fail_open = false)
{
if (is_int($number) || is_float($number)) {
$number += 0;
} elseif (is_numeric($number)) {
$number += 0;
}
if (
is_float($number)
&&
$number > ~PHP_INT_MAX
&&
$number < PHP_INT_MAX
) {
$number = (int) $number;
}
if (is_int($number)) {
return (int) $number;
} elseif (!$fail_open) {
throw new TypeError(
'Expected an integer.'
);
}
return $number;
}
}

View File

@ -0,0 +1,49 @@
<?php
/**
* Random_* Compatibility Library
* for using the new PHP 7 random_* API in PHP 5 projects
*
* The MIT License (MIT)
*
* Copyright (c) 2015 - 2017 Paragon Initiative Enterprises
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
if (!class_exists('Error', false)) {
// We can't really avoid making this extend Exception in PHP 5.
class Error extends Exception
{
}
}
if (!class_exists('TypeError', false)) {
if (is_subclass_of('Error', 'Exception')) {
class TypeError extends Error
{
}
} else {
class TypeError extends Exception
{
}
}
}

View File

@ -0,0 +1,223 @@
<?php
/**
* Random_* Compatibility Library
* for using the new PHP 7 random_* API in PHP 5 projects
*
* @version 2.0.10
* @released 2017-03-13
*
* The MIT License (MIT)
*
* Copyright (c) 2015 - 2017 Paragon Initiative Enterprises
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
if (!defined('PHP_VERSION_ID')) {
// This constant was introduced in PHP 5.2.7
$RandomCompatversion = array_map('intval', explode('.', PHP_VERSION));
define(
'PHP_VERSION_ID',
$RandomCompatversion[0] * 10000
+ $RandomCompatversion[1] * 100
+ $RandomCompatversion[2]
);
$RandomCompatversion = null;
}
/**
* PHP 7.0.0 and newer have these functions natively.
*/
if (PHP_VERSION_ID >= 70000) {
return;
}
if (!defined('RANDOM_COMPAT_READ_BUFFER')) {
define('RANDOM_COMPAT_READ_BUFFER', 8);
}
$RandomCompatDIR = dirname(__FILE__);
require_once $RandomCompatDIR . '/byte_safe_strings.php';
require_once $RandomCompatDIR . '/cast_to_int.php';
require_once $RandomCompatDIR . '/error_polyfill.php';
if (!is_callable('random_bytes')) {
/**
* PHP 5.2.0 - 5.6.x way to implement random_bytes()
*
* We use conditional statements here to define the function in accordance
* to the operating environment. It's a micro-optimization.
*
* In order of preference:
* 1. Use libsodium if available.
* 2. fread() /dev/urandom if available (never on Windows)
* 3. mcrypt_create_iv($bytes, MCRYPT_DEV_URANDOM)
* 4. COM('CAPICOM.Utilities.1')->GetRandom()
*
* See RATIONALE.md for our reasoning behind this particular order
*/
if (extension_loaded('libsodium')) {
// See random_bytes_libsodium.php
if (PHP_VERSION_ID >= 50300 && is_callable('\\Sodium\\randombytes_buf')) {
require_once $RandomCompatDIR . '/random_bytes_libsodium.php';
} elseif (method_exists('Sodium', 'randombytes_buf')) {
require_once $RandomCompatDIR . '/random_bytes_libsodium_legacy.php';
}
}
/**
* Reading directly from /dev/urandom:
*/
if (DIRECTORY_SEPARATOR === '/') {
// DIRECTORY_SEPARATOR === '/' on Unix-like OSes -- this is a fast
// way to exclude Windows.
$RandomCompatUrandom = true;
$RandomCompat_basedir = ini_get('open_basedir');
if (!empty($RandomCompat_basedir)) {
$RandomCompat_open_basedir = explode(
PATH_SEPARATOR,
strtolower($RandomCompat_basedir)
);
$RandomCompatUrandom = (array() !== array_intersect(
array('/dev', '/dev/', '/dev/urandom'),
$RandomCompat_open_basedir
));
$RandomCompat_open_basedir = null;
}
if (
!is_callable('random_bytes')
&&
$RandomCompatUrandom
&&
@is_readable('/dev/urandom')
) {
// Error suppression on is_readable() in case of an open_basedir
// or safe_mode failure. All we care about is whether or not we
// can read it at this point. If the PHP environment is going to
// panic over trying to see if the file can be read in the first
// place, that is not helpful to us here.
// See random_bytes_dev_urandom.php
require_once $RandomCompatDIR . '/random_bytes_dev_urandom.php';
}
// Unset variables after use
$RandomCompat_basedir = null;
} else {
$RandomCompatUrandom = false;
}
/**
* mcrypt_create_iv()
*
* We only want to use mcypt_create_iv() if:
*
* - random_bytes() hasn't already been defined
* - the mcrypt extensions is loaded
* - One of these two conditions is true:
* - We're on Windows (DIRECTORY_SEPARATOR !== '/')
* - We're not on Windows and /dev/urandom is readabale
* (i.e. we're not in a chroot jail)
* - Special case:
* - If we're not on Windows, but the PHP version is between
* 5.6.10 and 5.6.12, we don't want to use mcrypt. It will
* hang indefinitely. This is bad.
* - If we're on Windows, we want to use PHP >= 5.3.7 or else
* we get insufficient entropy errors.
*/
if (
!is_callable('random_bytes')
&&
// Windows on PHP < 5.3.7 is broken, but non-Windows is not known to be.
(DIRECTORY_SEPARATOR === '/' || PHP_VERSION_ID >= 50307)
&&
// Prevent this code from hanging indefinitely on non-Windows;
// see https://bugs.php.net/bug.php?id=69833
(
DIRECTORY_SEPARATOR !== '/' ||
(PHP_VERSION_ID <= 50609 || PHP_VERSION_ID >= 50613)
)
&&
extension_loaded('mcrypt')
) {
// See random_bytes_mcrypt.php
require_once $RandomCompatDIR . '/random_bytes_mcrypt.php';
}
$RandomCompatUrandom = null;
/**
* This is a Windows-specific fallback, for when the mcrypt extension
* isn't loaded.
*/
if (
!is_callable('random_bytes')
&&
extension_loaded('com_dotnet')
&&
class_exists('COM')
) {
$RandomCompat_disabled_classes = preg_split(
'#\s*,\s*#',
strtolower(ini_get('disable_classes'))
);
if (!in_array('com', $RandomCompat_disabled_classes)) {
try {
$RandomCompatCOMtest = new COM('CAPICOM.Utilities.1');
if (method_exists($RandomCompatCOMtest, 'GetRandom')) {
// See random_bytes_com_dotnet.php
require_once $RandomCompatDIR . '/random_bytes_com_dotnet.php';
}
} catch (com_exception $e) {
// Don't try to use it.
}
}
$RandomCompat_disabled_classes = null;
$RandomCompatCOMtest = null;
}
/**
* throw new Exception
*/
if (!is_callable('random_bytes')) {
/**
* We don't have any more options, so let's throw an exception right now
* and hope the developer won't let it fail silently.
*
* @param mixed $length
* @return void
* @throws Exception
*/
function random_bytes($length)
{
unset($length); // Suppress "variable not used" warnings.
throw new Exception(
'There is no suitable CSPRNG installed on your system'
);
}
}
}
if (!is_callable('random_int')) {
require_once $RandomCompatDIR . '/random_int.php';
}
$RandomCompatDIR = null;

View File

@ -0,0 +1,88 @@
<?php
/**
* Random_* Compatibility Library
* for using the new PHP 7 random_* API in PHP 5 projects
*
* The MIT License (MIT)
*
* Copyright (c) 2015 - 2017 Paragon Initiative Enterprises
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
if (!is_callable('random_bytes')) {
/**
* Windows with PHP < 5.3.0 will not have the function
* openssl_random_pseudo_bytes() available, so let's use
* CAPICOM to work around this deficiency.
*
* @param int $bytes
*
* @throws Exception
*
* @return string
*/
function random_bytes($bytes)
{
try {
$bytes = RandomCompat_intval($bytes);
} catch (TypeError $ex) {
throw new TypeError(
'random_bytes(): $bytes must be an integer'
);
}
if ($bytes < 1) {
throw new Error(
'Length must be greater than 0'
);
}
$buf = '';
if (!class_exists('COM')) {
throw new Error(
'COM does not exist'
);
}
$util = new COM('CAPICOM.Utilities.1');
$execCount = 0;
/**
* Let's not let it loop forever. If we run N times and fail to
* get N bytes of random data, then CAPICOM has failed us.
*/
do {
$buf .= base64_decode($util->GetRandom($bytes, 0));
if (RandomCompat_strlen($buf) >= $bytes) {
/**
* Return our random entropy buffer here:
*/
return RandomCompat_substr($buf, 0, $bytes);
}
++$execCount;
} while ($execCount < $bytes);
/**
* If we reach here, PHP has failed us.
*/
throw new Exception(
'Could not gather sufficient random data'
);
}
}

View File

@ -0,0 +1,167 @@
<?php
/**
* Random_* Compatibility Library
* for using the new PHP 7 random_* API in PHP 5 projects
*
* The MIT License (MIT)
*
* Copyright (c) 2015 - 2017 Paragon Initiative Enterprises
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
if (!defined('RANDOM_COMPAT_READ_BUFFER')) {
define('RANDOM_COMPAT_READ_BUFFER', 8);
}
if (!is_callable('random_bytes')) {
/**
* Unless open_basedir is enabled, use /dev/urandom for
* random numbers in accordance with best practices
*
* Why we use /dev/urandom and not /dev/random
* @ref http://sockpuppet.org/blog/2014/02/25/safely-generate-random-numbers
*
* @param int $bytes
*
* @throws Exception
*
* @return string
*/
function random_bytes($bytes)
{
static $fp = null;
/**
* This block should only be run once
*/
if (empty($fp)) {
/**
* We use /dev/urandom if it is a char device.
* We never fall back to /dev/random
*/
$fp = fopen('/dev/urandom', 'rb');
if (!empty($fp)) {
$st = fstat($fp);
if (($st['mode'] & 0170000) !== 020000) {
fclose($fp);
$fp = false;
}
}
if (!empty($fp)) {
/**
* stream_set_read_buffer() does not exist in HHVM
*
* If we don't set the stream's read buffer to 0, PHP will
* internally buffer 8192 bytes, which can waste entropy
*
* stream_set_read_buffer returns 0 on success
*/
if (is_callable('stream_set_read_buffer')) {
stream_set_read_buffer($fp, RANDOM_COMPAT_READ_BUFFER);
}
if (is_callable('stream_set_chunk_size')) {
stream_set_chunk_size($fp, RANDOM_COMPAT_READ_BUFFER);
}
}
}
try {
$bytes = RandomCompat_intval($bytes);
} catch (TypeError $ex) {
throw new TypeError(
'random_bytes(): $bytes must be an integer'
);
}
if ($bytes < 1) {
throw new Error(
'Length must be greater than 0'
);
}
/**
* This if() block only runs if we managed to open a file handle
*
* It does not belong in an else {} block, because the above
* if (empty($fp)) line is logic that should only be run once per
* page load.
*/
if (!empty($fp)) {
/**
* @var int
*/
$remaining = $bytes;
/**
* @var string|bool
*/
$buf = '';
/**
* We use fread() in a loop to protect against partial reads
*/
do {
/**
* @var string|bool
*/
$read = fread($fp, $remaining);
if (!is_string($read)) {
if ($read === false) {
/**
* We cannot safely read from the file. Exit the
* do-while loop and trigger the exception condition
*
* @var string|bool
*/
$buf = false;
break;
}
}
/**
* Decrease the number of bytes returned from remaining
*/
$remaining -= RandomCompat_strlen($read);
/**
* @var string|bool
*/
$buf = $buf . $read;
} while ($remaining > 0);
/**
* Is our result valid?
*/
if (is_string($buf)) {
if (RandomCompat_strlen($buf) === $bytes) {
/**
* Return our random entropy buffer here:
*/
return $buf;
}
}
}
/**
* If we reach here, PHP has failed us.
*/
throw new Exception(
'Error reading from source device'
);
}
}

View File

@ -0,0 +1,88 @@
<?php
/**
* Random_* Compatibility Library
* for using the new PHP 7 random_* API in PHP 5 projects
*
* The MIT License (MIT)
*
* Copyright (c) 2015 - 2017 Paragon Initiative Enterprises
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
if (!is_callable('random_bytes')) {
/**
* If the libsodium PHP extension is loaded, we'll use it above any other
* solution.
*
* libsodium-php project:
* @ref https://github.com/jedisct1/libsodium-php
*
* @param int $bytes
*
* @throws Exception
*
* @return string
*/
function random_bytes($bytes)
{
try {
$bytes = RandomCompat_intval($bytes);
} catch (TypeError $ex) {
throw new TypeError(
'random_bytes(): $bytes must be an integer'
);
}
if ($bytes < 1) {
throw new Error(
'Length must be greater than 0'
);
}
/**
* \Sodium\randombytes_buf() doesn't allow more than 2147483647 bytes to be
* generated in one invocation.
*/
if ($bytes > 2147483647) {
$buf = '';
for ($i = 0; $i < $bytes; $i += 1073741824) {
$n = ($bytes - $i) > 1073741824
? 1073741824
: $bytes - $i;
$buf .= \Sodium\randombytes_buf($n);
}
} else {
$buf = \Sodium\randombytes_buf($bytes);
}
if ($buf !== false) {
if (RandomCompat_strlen($buf) === $bytes) {
return $buf;
}
}
/**
* If we reach here, PHP has failed us.
*/
throw new Exception(
'Could not gather sufficient random data'
);
}
}

View File

@ -0,0 +1,92 @@
<?php
/**
* Random_* Compatibility Library
* for using the new PHP 7 random_* API in PHP 5 projects
*
* The MIT License (MIT)
*
* Copyright (c) 2015 - 2017 Paragon Initiative Enterprises
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
if (!is_callable('random_bytes')) {
/**
* If the libsodium PHP extension is loaded, we'll use it above any other
* solution.
*
* libsodium-php project:
* @ref https://github.com/jedisct1/libsodium-php
*
* @param int $bytes
*
* @throws Exception
*
* @return string
*/
function random_bytes($bytes)
{
try {
$bytes = RandomCompat_intval($bytes);
} catch (TypeError $ex) {
throw new TypeError(
'random_bytes(): $bytes must be an integer'
);
}
if ($bytes < 1) {
throw new Error(
'Length must be greater than 0'
);
}
/**
* @var string
*/
$buf = '';
/**
* \Sodium\randombytes_buf() doesn't allow more than 2147483647 bytes to be
* generated in one invocation.
*/
if ($bytes > 2147483647) {
for ($i = 0; $i < $bytes; $i += 1073741824) {
$n = ($bytes - $i) > 1073741824
? 1073741824
: $bytes - $i;
$buf .= Sodium::randombytes_buf((int) $n);
}
} else {
$buf .= Sodium::randombytes_buf((int) $bytes);
}
if (is_string($buf)) {
if (RandomCompat_strlen($buf) === $bytes) {
return $buf;
}
}
/**
* If we reach here, PHP has failed us.
*/
throw new Exception(
'Could not gather sufficient random data'
);
}
}

View File

@ -0,0 +1,77 @@
<?php
/**
* Random_* Compatibility Library
* for using the new PHP 7 random_* API in PHP 5 projects
*
* The MIT License (MIT)
*
* Copyright (c) 2015 - 2017 Paragon Initiative Enterprises
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
if (!is_callable('random_bytes')) {
/**
* Powered by ext/mcrypt (and thankfully NOT libmcrypt)
*
* @ref https://bugs.php.net/bug.php?id=55169
* @ref https://github.com/php/php-src/blob/c568ffe5171d942161fc8dda066bce844bdef676/ext/mcrypt/mcrypt.c#L1321-L1386
*
* @param int $bytes
*
* @throws Exception
*
* @return string
*/
function random_bytes($bytes)
{
try {
$bytes = RandomCompat_intval($bytes);
} catch (TypeError $ex) {
throw new TypeError(
'random_bytes(): $bytes must be an integer'
);
}
if ($bytes < 1) {
throw new Error(
'Length must be greater than 0'
);
}
$buf = @mcrypt_create_iv($bytes, MCRYPT_DEV_URANDOM);
if (
$buf !== false
&&
RandomCompat_strlen($buf) === $bytes
) {
/**
* Return our random entropy buffer here:
*/
return $buf;
}
/**
* If we reach here, PHP has failed us.
*/
throw new Exception(
'Could not gather sufficient random data'
);
}
}

View File

@ -0,0 +1,190 @@
<?php
if (!is_callable('random_int')) {
/**
* Random_* Compatibility Library
* for using the new PHP 7 random_* API in PHP 5 projects
*
* The MIT License (MIT)
*
* Copyright (c) 2015 - 2017 Paragon Initiative Enterprises
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/**
* Fetch a random integer between $min and $max inclusive
*
* @param int $min
* @param int $max
*
* @throws Exception
*
* @return int
*/
function random_int($min, $max)
{
/**
* Type and input logic checks
*
* If you pass it a float in the range (~PHP_INT_MAX, PHP_INT_MAX)
* (non-inclusive), it will sanely cast it to an int. If you it's equal to
* ~PHP_INT_MAX or PHP_INT_MAX, we let it fail as not an integer. Floats
* lose precision, so the <= and => operators might accidentally let a float
* through.
*/
try {
$min = RandomCompat_intval($min);
} catch (TypeError $ex) {
throw new TypeError(
'random_int(): $min must be an integer'
);
}
try {
$max = RandomCompat_intval($max);
} catch (TypeError $ex) {
throw new TypeError(
'random_int(): $max must be an integer'
);
}
/**
* Now that we've verified our weak typing system has given us an integer,
* let's validate the logic then we can move forward with generating random
* integers along a given range.
*/
if ($min > $max) {
throw new Error(
'Minimum value must be less than or equal to the maximum value'
);
}
if ($max === $min) {
return (int) $min;
}
/**
* Initialize variables to 0
*
* We want to store:
* $bytes => the number of random bytes we need
* $mask => an integer bitmask (for use with the &) operator
* so we can minimize the number of discards
*/
$attempts = $bits = $bytes = $mask = $valueShift = 0;
/**
* At this point, $range is a positive number greater than 0. It might
* overflow, however, if $max - $min > PHP_INT_MAX. PHP will cast it to
* a float and we will lose some precision.
*/
$range = $max - $min;
/**
* Test for integer overflow:
*/
if (!is_int($range)) {
/**
* Still safely calculate wider ranges.
* Provided by @CodesInChaos, @oittaa
*
* @ref https://gist.github.com/CodesInChaos/03f9ea0b58e8b2b8d435
*
* We use ~0 as a mask in this case because it generates all 1s
*
* @ref https://eval.in/400356 (32-bit)
* @ref http://3v4l.org/XX9r5 (64-bit)
*/
$bytes = PHP_INT_SIZE;
$mask = ~0;
} else {
/**
* $bits is effectively ceil(log($range, 2)) without dealing with
* type juggling
*/
while ($range > 0) {
if ($bits % 8 === 0) {
++$bytes;
}
++$bits;
$range >>= 1;
$mask = $mask << 1 | 1;
}
$valueShift = $min;
}
$val = 0;
/**
* Now that we have our parameters set up, let's begin generating
* random integers until one falls between $min and $max
*/
do {
/**
* The rejection probability is at most 0.5, so this corresponds
* to a failure probability of 2^-128 for a working RNG
*/
if ($attempts > 128) {
throw new Exception(
'random_int: RNG is broken - too many rejections'
);
}
/**
* Let's grab the necessary number of random bytes
*/
$randomByteString = random_bytes($bytes);
/**
* Let's turn $randomByteString into an integer
*
* This uses bitwise operators (<< and |) to build an integer
* out of the values extracted from ord()
*
* Example: [9F] | [6D] | [32] | [0C] =>
* 159 + 27904 + 3276800 + 201326592 =>
* 204631455
*/
$val &= 0;
for ($i = 0; $i < $bytes; ++$i) {
$val |= ord($randomByteString[$i]) << ($i * 8);
}
/**
* Apply mask
*/
$val &= $mask;
$val += $valueShift;
++$attempts;
/**
* If $val overflows to a floating point number,
* ... or is larger than $max,
* ... or smaller than $min,
* then try again.
*/
} while (!is_int($val) || $val > $max || $val < $min);
return (int) $val;
}
}

View File

@ -0,0 +1,57 @@
<?php
$dist = dirname(__DIR__).'/dist';
if (!is_dir($dist)) {
mkdir($dist, 0755);
}
if (file_exists($dist.'/random_compat.phar')) {
unlink($dist.'/random_compat.phar');
}
$phar = new Phar(
$dist.'/random_compat.phar',
FilesystemIterator::CURRENT_AS_FILEINFO | \FilesystemIterator::KEY_AS_FILENAME,
'random_compat.phar'
);
rename(
dirname(__DIR__).'/lib/random.php',
dirname(__DIR__).'/lib/index.php'
);
$phar->buildFromDirectory(dirname(__DIR__).'/lib');
rename(
dirname(__DIR__).'/lib/index.php',
dirname(__DIR__).'/lib/random.php'
);
/**
* If we pass an (optional) path to a private key as a second argument, we will
* sign the Phar with OpenSSL.
*
* If you leave this out, it will produce an unsigned .phar!
*/
if ($argc > 1) {
if (!@is_readable($argv[1])) {
echo 'Could not read the private key file:', $argv[1], "\n";
exit(255);
}
$pkeyFile = file_get_contents($argv[1]);
$private = openssl_get_privatekey($pkeyFile);
if ($private !== false) {
$pkey = '';
openssl_pkey_export($private, $pkey);
$phar->setSignatureAlgorithm(Phar::OPENSSL, $pkey);
/**
* Save the corresponding public key to the file
*/
if (!@is_readable($dist.'/random_compat.phar.pubkey')) {
$details = openssl_pkey_get_details($private);
file_put_contents(
$dist.'/random_compat.phar.pubkey',
$details['key']
);
}
} else {
echo 'An error occurred reading the private key from OpenSSL.', "\n";
exit(255);
}
}

View File

@ -0,0 +1,9 @@
<?php
require_once 'lib/byte_safe_strings.php';
require_once 'lib/cast_to_int.php';
require_once 'lib/error_polyfill.php';
require_once 'other/ide_stubs/libsodium.php';
require_once 'lib/random.php';
$int = random_int(0, 65536);

View File

@ -0,0 +1,16 @@
<?xml version="1.0"?>
<psalm
autoloader="psalm-autoload.php"
stopOnFirstError="false"
useDocblockTypes="true"
>
<projectFiles>
<directory name="lib" />
</projectFiles>
<issueHandlers>
<DuplicateClass errorLevel="info" />
<InvalidOperand errorLevel="info" />
<UndefinedConstant errorLevel="info" />
<MissingReturnType errorLevel="info" />
</issueHandlers>
</psalm>