Skip to content

Commit

Permalink
Merge pull request #973 from oricgn/phorum_5_2_compat_random
Browse files Browse the repository at this point in the history
Random Extension
  • Loading branch information
oricgn committed Apr 11, 2016
2 parents 9834d44 + 7b3b7ff commit 9586c52
Show file tree
Hide file tree
Showing 31 changed files with 1,909 additions and 28 deletions.
13 changes: 11 additions & 2 deletions common.php
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,7 @@
"stuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
$private_key = "";
for ($i = 0; $i<40; $i++) {
$private_key .= substr($chars, rand(0, strlen($chars)-1), 1);
$private_key .= substr($chars, random_int(0, strlen($chars)-1), 1);
}
$PHORUM["private_key"] = $private_key;
phorum_db_update_settings(array("private_key" => $PHORUM["private_key"]));
Expand Down Expand Up @@ -236,7 +236,7 @@
// ----------------------------------------------------------------------

// Thanks a lot for magic quotes :-/
// In PHP6, magic quotes are (finally) removed, so we have to check for
// In PHP7, magic quotes are (finally) removed, so we have to check for
// the get_magic_quotes_gpc() function here. The "@" is for suppressing
// deprecation warnings that are spawned by PHP 5.3 and higher when
// using the get_magic_quotes_gpc() function.
Expand Down Expand Up @@ -2376,4 +2376,13 @@ function mb_substr($str, $start, $length = NULL, $encoding = NULL)
}
}

// PHP 5.x fallback for random_bytes and random_int functions.
//
// Thanks to Paragon Initiative Enterprises for the implementation of his
// Random_* Compatibility Library. See: https://github.com/paragonie/random_compat
if (!function_exists('random_int') || !function_exists('random_bytes'))
{
require_once('./include/random_compat-2.0.2/lib/random.php');
}

?>
2 changes: 1 addition & 1 deletion include/api/modules.php
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,7 @@ function phorum_api_modules_list()
$req = phorum_parse_version($required_ver);

// If an admin is using a development or snapshot release,
// the we asume that he knows what he's doing.
// then we asume that he knows what he's doing.
if ($cur[0] == 'snapshot' ||
$cur[0] == 'development') {
// noop
Expand Down
2 changes: 1 addition & 1 deletion include/controlcenter/email.php
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@
$email_temp_part="";
} elseif($PHORUM['registration_control'] && !empty($_POST['email']) && strtolower($_POST['email']) != strtolower($PHORUM["DATA"]["PROFILE"]['email'])) {
// ... generate the confirmation-code ... //
$conf_code= mt_rand ( 1000000, 9999999);
$conf_code= random_int(1000000, 9999999);
$_POST['email_temp']=$_POST['email']."|".$conf_code;
// ... send email ... //
$maildata=array(
Expand Down
2 changes: 1 addition & 1 deletion include/posting/action_post.php
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@

// Create a unique message id.
$suffix = preg_replace("/[^a-z0-9]/i", "", $PHORUM["name"]);
$message["msgid"] = md5(uniqid(rand())) . ".$suffix";
$message["msgid"] = md5(uniqid(random_int(0, getrandmax()))) . ".$suffix";

// Add attachments to meta data. Because there might be inconsistencies in
// the list due to going backward in the browser after deleting attachments,
Expand Down
4 changes: 2 additions & 2 deletions include/profile_functions.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ function phorum_gen_password($charpart=4, $numpart=3)
$password="";

for($i = 0; $i < $charpart; $i++){
$password .= $cons[mt_rand(0, $num_cons - 1)] . $vowels[mt_rand(0, $num_vowels - 1)];
$password .= $cons[random_int(0, $num_cons - 1)] . $vowels[random_int(0, $num_vowels - 1)];
}

$password = substr($password, 0, $charpart);
Expand All @@ -40,7 +40,7 @@ function phorum_gen_password($charpart=4, $numpart=3)
$max=(int)str_pad("", $numpart, "9");
$min=(int)str_pad("1", $numpart, "0");

$num=(string)mt_rand($min, $max);
$num=(string)random_int($min, $max);
}

return strtolower($password.$num);
Expand Down
260 changes: 260 additions & 0 deletions include/random_compat-2.0.2/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,260 @@
### Version 2.0.2 - 2016-04-03

Added a consistency check (discovered by Taylor Hornby in his
[PHP encryption library](https://github.com/defuse/php-encryption)). It
wasn't likely causing any trouble for us.

### Version 2.0.1 - 2016-03-18

Update comment in random.php

### Version 2.0.0 - 2016-03-18

Due to downstream errors, the OpenSSL removal now belongs in version
2.0.0.

### Version 1.3.1 - 2016-03-18

* Add more possible values to `open_baseir` check.

### Version 1.3.0 - 2016-03-17

* Removed `openssl_random_pseudo_bytes()` entirely. If you are using
random_compat in PHP on a Unix-like OS but cannot access
`/dev/urandom`, version 1.3+ will throw an `Exception`. If you want to
trust OpenSSL, feel free to write your own fallback code. e.g.

```php
try {
$bytes = random_bytes(32);
} catch (Exception $ex) {
$strong = false;
$bytes = openssl_random_pseudo_bytes(32, $strong);
if (!$strong) {
throw $ex;
}
}
```

### Version 1.2.2 - 2016-03-11

* To prevent applications from hanging, if `/dev/urandom` is not
accessible to PHP, skip mcrypt (which just fails before giving OpenSSL
a chance and was morally equivalent to not offering OpenSSL at all).

### Version 1.2.1 - 2016-02-29

* PHP 5.6.10 - 5.6.12 will hang when mcrypt is used on Unix-based operating
systems ([PHP bug 69833](https://bugs.php.net/bug.php?id=69833)). If you are
running one of these versions, please upgrade (or make sure `/dev/urandom` is
readable) otherwise you're relying on OpenSSL.

### Version 1.2.0 - 2016-02-05

* Whitespace and other cosmetic changes
* Added a changelog.
* We now ship with a command line utility to build a PHP Archive from the
command line.

Every time we publish a new release, we will also upload a .phar
to Github. Our public key is signed by our GPG key.

### Version 1.1.6 - 2016-01-29

* Eliminate `open_basedir` warnings by detecting this configuration setting.
(Thanks [@oucil](https://github.com/oucil) for reporting this.)
* Added install instructions to the README.
* Documentation cleanup (there is, in fact, no `MCRYPT_CREATE_IV` constant, I
meant to write `MCRYPT_DEV_URANDOM`)

### Version 1.1.5 - 2016-01-06

Prevent fatal errors on platforms with older versions of libsodium.

### Version 1.1.4 - 2015-12-10

Thanks [@narfbg](https://github.com/narfbg) for [critiquing the previous patch](https://github.com/paragonie/random_compat/issues/79#issuecomment-163590589)
and suggesting a fix.

### Version 1.1.3 - 2015-12-09

The test for COM in disabled_classes is now case-insensitive.

### Version 1.1.2 - 2015-12-09

Don't instantiate COM if it's a disabled class. Removes the E_WARNING on Windows.

### Version 1.1.1 - 2015-11-30

Fix a performance issue with `/dev/urandom` buffering.

### Version 1.1.0 - 2015-11-09

Fix performance issues with ancient versions of PHP on Windows, but dropped
support for PHP < 5.4.1 without mcrypt on Windows 7+ in the process. Since this
is a BC break, semver dictates a minor version bump.

### Version 1.0.10 - 2015-10-23

* Avoid a performance killer with OpenSSL on Windows PHP 5.3.0 - 5.3.3 that was
affecting [WordPress users](https://core.trac.wordpress.org/ticket/34409).
* Use `$var = null` instead of `unset($var)` to avoid triggering the garbage
collector and slowing things down.

### Version 1.0.9 - 2015-10-20

There is an outstanding issue `mcrypt_create_iv()` and PHP 7's `random_bytes()`
on Windows reported by [@nicolas-grekas](https://github.com/nicolas-grekas) caused by `proc_open()` and environment
variable handling (discovered by Appveyor when developing Symfony).

Since the break is consistent, it's not our responsibility to fix it, but we
should fail the same way PHP 7 will (i.e. throw an `Exception` rather than raise
an error and then throw an `Exception`).

### Version 1.0.8 - 2015-10-18

* Fix usability issues with Windows (`new COM('CAPICOM.Utilities.1')` is not
always available).
* You can now test all the possible drivers by running `phpunit.sh each` in the
`tests` directory.

### Version 1.0.7 - 2015-10-16

Several large integer handling bugfixes were contributed by [@oittaa](https://github.com/oittaa).

### Version 1.0.6 - 2015-10-15

Don't let the version number fool you, this was a pretty significant change.

1. Added support for ext-libsodium, if it exists on the system. This is morally
equivalent to adding `getrandom(2)` support without having to expose the
syscall interface in PHP-land.
2. Relaxed open_basedir restrictions. In previous versions, if open_basedir was
set, PHP wouldn't even try to read from `/dev/urandom`. Now it will still do
so if you can.
3. Fixed integer casting inconsistencies between random_compat and PHP 7.
4. Handle edge cases where an integer overflow turns one of the parameters into
a float.

One change that we discussed was making `random_bytes()` and `random_int()`
strict typed; meaning you could *only* pass integers to either function. While
most veteran programmers are probably only doing this already (we strongly
encourage it), it wouldn't be consistent with how these functions behave in PHP
7. Please use these functions responsibly.

We've had even more of the PHP community involved in this release; the
contributors list has been updated. If I forgot anybody, I promise you it's not
because your contributions (either code or ideas) aren't valued, it's because
I'm a bit overloaded with information at the moment. Please let me know
immediately and I will correct my oversight.

Thanks everyone for helping make random_compat better.

### Version 1.0.5 - 2015-10-08

Got rid of the methods in the `Throwable` interface, which was causing problems
on PHP 5.2. While we would normally not care about 5.2 (since [5.4 and earlier are EOL'd](https://secure.php.net/supported-versions.php)),
we do want to encourage widespread adoption (e.g. [Wordpress](https://core.trac.wordpress.org/ticket/28633)).

### Version 1.0.4 - 2015-10-02

Removed redundant `if()` checks, since `lib/random.php` is the entrypoint people
should use.

### Version 1.0.3 - 2015-10-02

This release contains bug fixes contributed by the community.

* Avoid a PHP Notice when PHP is running without the mbstring extension
* Use a compatible version of PHPUnit for testing on older versions of PHP

Although none of these bugs were outright security-affecting, updating ASAP is
still strongly encouraged.

### Version 1.0.2 - 2015-09-23

Less strict input validation on `random_int()` parameters. PHP 7's `random_int()`
accepts strings and floats that look like numbers, so we should too.

Thanks [@dd32](https://github.com/@dd32) for correcting this oversight.

### Version 1.0.1 - 2015-09-10

Instead of throwing an Exception immediately on insecure platforms, only do so
when `random_bytes()` is invoked.

### Version 1.0.0 - 2015-09-07

Our API is now stable and forward-compatible with the CSPRNG features in PHP 7
(as of 7.0.0 RC3).

A lot of great people have contributed their time and expertise to make this
compatibility library possible. That this library has reached a stable release
is more a reflection on the community than it is on PIE.

We are confident that random_compat will serve as the simplest and most secure
CSPRNG interface available for PHP5 projects.

### Version 0.9.7 (pre-release) - 2015-09-01

An attempt to achieve compatibility with Error/TypeError in the RFC.

This should be identical to 1.0.0 sans any last-minute changes or performance enhancements.

### Version 0.9.6 (pre-release) - 2015-08-06

* Split the implementations into their own file (for ease of auditing)
* Corrected the file type check after `/dev/urandom` has been opened (thanks
[@narfbg](https://github.com/narfbg) and [@jedisct1](https://github.com/jedisct1))

### Version 0.9.5 (pre-release) - 2015-07-31

* Validate that `/dev/urandom` is a character device
* Reported by [@lokdnet](https://twitter.com/lokdnet)
* Investigated by [@narfbg](https://github.com/narfbg) and [frymaster](http://stackoverflow.com/users/1226810/frymaster) on [StackOverflow](http://stackoverflow.com/q/31631066/2224584)
* Remove support for `/dev/arandom` which is an old OpenBSD feature, thanks [@jedisct1](https://github.com/jedisct1)
* Prevent race conditions on the `filetype()` check, thanks [@jedisct1](https://github.com/jedisct1)
* Buffer file reads to 8 bytes (performance optimization; PHP defaults to 8192 bytes)

### Version 0.9.4 (pre-release) - 2015-07-27

* Add logic to verify that `/dev/arandom` and `/dev/urandom` are actually devices.
* Some clean-up in the comments

### Version 0.9.3 (pre-release) - 2015-07-22

Unless the Exceptions change to PHP 7 fails, this should be the last pre-release
version. If need be, we'll make one more pre-release version with compatible
behavior.

Changes since 0.9.2:

* Prioritize `/dev/arandom` and `/dev/urandom` over mcrypt.
[@oittaa](https://github.com/oittaa) removed the -1 and +1 juggling on `$range` calculations for `random_int()`
* Whitespace and comment clean-up, plus better variable names
* Actually put a description in the composer.json file...

### Version 0.9.2 (pre-release) - 2015-07-16

* Consolidated `$range > PHP_INT_MAX` logic with `$range <= PHP_INT_MAX` (thanks
[@oittaa](https://github.com/oittaa) and [@CodesInChaos](https://github.com/CodesInChaos))
* `tests/phpunit.sh` now also runs the tests with `mbstring.func_overload` and
`open_basedir`
* Style consistency, whitespace cleanup, more meaningful variable names

### Version 0.9.1 (pre-release) - 2015-07-09

* Return random values on integer ranges > `PHP_INT_MAX` (thanks [@CodesInChaos](https://github.com/CodesInChaos))
* Determined CSPRNG preference:
1. `mcrypt_create_iv()` with `MCRYPT_DEV_URANDOM`
2. `/dev/arandom`
3. `/dev/urandom`
4. `openssl_random_pseudo_bytes()`
* Optimized backend selection (thanks [@lt](https://github.com/lt))
* Fix #3 (thanks [@scottchiefbaker](https://github.com/scottchiefbaker))

### Version 0.9.0 (pre-release) - 2015-07-07

This should be a sane polyfill for PHP 7's `random_bytes()` and `random_int()`.
We hesitate to call it production ready until it has received sufficient third
party review.
34 changes: 34 additions & 0 deletions include/random_compat-2.0.2/ERRATA.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
## Errata (Design Decisions)

### Reasoning Behind the Order of Preferred Random Data Sources

The order is:

1. `libsodium if available`
2. `fread() /dev/urandom if available`
3. `mcrypt_create_iv($bytes, MCRYPT_DEV_URANDOM)`
4. `COM('CAPICOM.Utilities.1')->GetRandom()`

If libsodium is available, we get random data from it. This is the preferred
method on all OSes, but libsodium is not very widely installed, so other
fallbacks are available.

Next, we read `/dev/urandom` (if it exists). This is the preferred file to read
for random data for cryptographic purposes for BSD and Linux.

Despite [strongly urging people not to use mcrypt in their projects](https://paragonie.com/blog/2015/05/if-you-re-typing-word-mcrypt-into-your-code-you-re-doing-it-wrong),
because libmcrypt is abandonware and the API puts too much responsibility on the
implementor, we prioritize `mcrypt_create_iv()` with `MCRYPT_DEV_URANDOM` above
the remaining implementations.

The reason is simple: `mcrypt_create_iv()` is part of PHP's `ext/mcrypt` code,
and is not part `libmcrypt`. It actually does the right thing:

* On Unix-based operating systems, it reads from `/dev/urandom`, which unlike `/dev/random`
is the sane and correct thing to do.
* On Windows, it reads from `CryptGenRandom`, which is an exclusively Windows
way to get random bytes.

If we're on Windows and don't have access to `mcrypt`, we use `CAPICOM.Utilities.1`.

As of random_compat 1.3, we no longer fall through to OpenSSL.
22 changes: 22 additions & 0 deletions include/random_compat-2.0.2/LICENSE
Original file line number Diff line number Diff line change
@@ -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.

Loading

0 comments on commit 9586c52

Please sign in to comment.