xref: /dokuwiki/vendor/paragonie/random_compat/lib/random.php (revision 7a33d2f8a8d3dc5633646a576e37dc7a830c2f89)
1<?php
2/**
3 * Random_* Compatibility Library
4 * for using the new PHP 7 random_* API in PHP 5 projects
5 *
6 * @version 2.0.4
7 * @released 2016-11-07
8 *
9 * The MIT License (MIT)
10 *
11 * Copyright (c) 2015 - 2016 Paragon Initiative Enterprises
12 *
13 * Permission is hereby granted, free of charge, to any person obtaining a copy
14 * of this software and associated documentation files (the "Software"), to deal
15 * in the Software without restriction, including without limitation the rights
16 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
17 * copies of the Software, and to permit persons to whom the Software is
18 * furnished to do so, subject to the following conditions:
19 *
20 * The above copyright notice and this permission notice shall be included in
21 * all copies or substantial portions of the Software.
22 *
23 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
24 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
25 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
26 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
27 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
28 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
29 * SOFTWARE.
30 */
31
32if (!defined('PHP_VERSION_ID')) {
33    // This constant was introduced in PHP 5.2.7
34    $RandomCompatversion = array_map('intval', explode('.', PHP_VERSION));
35    define(
36        'PHP_VERSION_ID',
37        $RandomCompatversion[0] * 10000
38        + $RandomCompatversion[1] * 100
39        + $RandomCompatversion[2]
40    );
41    $RandomCompatversion = null;
42}
43
44/**
45 * PHP 7.0.0 and newer have these functions natively.
46 */
47if (PHP_VERSION_ID < 70000) {
48    if (!defined('RANDOM_COMPAT_READ_BUFFER')) {
49        define('RANDOM_COMPAT_READ_BUFFER', 8);
50    }
51
52    $RandomCompatDIR = dirname(__FILE__);
53
54    require_once $RandomCompatDIR.'/byte_safe_strings.php';
55    require_once $RandomCompatDIR.'/cast_to_int.php';
56    require_once $RandomCompatDIR.'/error_polyfill.php';
57
58    if (!is_callable('random_bytes')) {
59        /**
60         * PHP 5.2.0 - 5.6.x way to implement random_bytes()
61         *
62         * We use conditional statements here to define the function in accordance
63         * to the operating environment. It's a micro-optimization.
64         *
65         * In order of preference:
66         *   1. Use libsodium if available.
67         *   2. fread() /dev/urandom if available (never on Windows)
68         *   3. mcrypt_create_iv($bytes, MCRYPT_DEV_URANDOM)
69         *   4. COM('CAPICOM.Utilities.1')->GetRandom()
70         *   5. openssl_random_pseudo_bytes() (absolute last resort)
71         *
72         * See RATIONALE.md for our reasoning behind this particular order
73         */
74        if (extension_loaded('libsodium')) {
75            // See random_bytes_libsodium.php
76            if (PHP_VERSION_ID >= 50300 && is_callable('\\Sodium\\randombytes_buf')) {
77                require_once $RandomCompatDIR.'/random_bytes_libsodium.php';
78            } elseif (method_exists('Sodium', 'randombytes_buf')) {
79                require_once $RandomCompatDIR.'/random_bytes_libsodium_legacy.php';
80            }
81        }
82
83        /**
84         * Reading directly from /dev/urandom:
85         */
86        if (DIRECTORY_SEPARATOR === '/') {
87            // DIRECTORY_SEPARATOR === '/' on Unix-like OSes -- this is a fast
88            // way to exclude Windows.
89            $RandomCompatUrandom = true;
90            $RandomCompat_basedir = ini_get('open_basedir');
91
92            if (!empty($RandomCompat_basedir)) {
93                $RandomCompat_open_basedir = explode(
94                    PATH_SEPARATOR,
95                    strtolower($RandomCompat_basedir)
96                );
97                $RandomCompatUrandom = (array() !== array_intersect(
98                    array('/dev', '/dev/', '/dev/urandom'),
99                    $RandomCompat_open_basedir
100                ));
101                $RandomCompat_open_basedir = null;
102            }
103
104            if (
105                !is_callable('random_bytes')
106                &&
107                $RandomCompatUrandom
108                &&
109                @is_readable('/dev/urandom')
110            ) {
111                // Error suppression on is_readable() in case of an open_basedir
112                // or safe_mode failure. All we care about is whether or not we
113                // can read it at this point. If the PHP environment is going to
114                // panic over trying to see if the file can be read in the first
115                // place, that is not helpful to us here.
116
117                // See random_bytes_dev_urandom.php
118                require_once $RandomCompatDIR.'/random_bytes_dev_urandom.php';
119            }
120            // Unset variables after use
121            $RandomCompat_basedir = null;
122        } else {
123            $RandomCompatUrandom = false;
124        }
125
126        /**
127         * mcrypt_create_iv()
128         *
129         * We only want to use mcypt_create_iv() if:
130         *
131         * - random_bytes() hasn't already been defined
132         * - PHP >= 5.3.7
133         * - the mcrypt extensions is loaded
134         * - One of these two conditions is true:
135         *   - We're on Windows (DIRECTORY_SEPARATOR !== '/')
136         *   - We're not on Windows and /dev/urandom is readabale
137         *     (i.e. we're not in a chroot jail)
138         * - Special case:
139         *   - If we're not on Windows, but the PHP version is between
140         *     5.6.10 and 5.6.12, we don't want to use mcrypt. It will
141         *     hang indefinitely. This is bad.
142         */
143        if (
144            !is_callable('random_bytes')
145            &&
146            PHP_VERSION_ID >= 50307
147            &&
148            extension_loaded('mcrypt')
149        ) {
150            // Prevent this code from hanging indefinitely on non-Windows;
151            // see https://bugs.php.net/bug.php?id=69833
152            if (
153                DIRECTORY_SEPARATOR !== '/' ||
154                (PHP_VERSION_ID <= 50609 || PHP_VERSION_ID >= 50613)
155            ) {
156                // See random_bytes_mcrypt.php
157                require_once $RandomCompatDIR.'/random_bytes_mcrypt.php';
158            }
159        }
160        $RandomCompatUrandom = null;
161
162        /**
163         * This is a Windows-specific fallback, for when the mcrypt extension
164         * isn't loaded.
165         */
166        if (
167            !is_callable('random_bytes')
168            &&
169            extension_loaded('com_dotnet')
170            &&
171            class_exists('COM')
172        ) {
173            $RandomCompat_disabled_classes = preg_split(
174                '#\s*,\s*#',
175                strtolower(ini_get('disable_classes'))
176            );
177
178            if (!in_array('com', $RandomCompat_disabled_classes)) {
179                try {
180                    $RandomCompatCOMtest = new COM('CAPICOM.Utilities.1');
181                    if (method_exists($RandomCompatCOMtest, 'GetRandom')) {
182                        // See random_bytes_com_dotnet.php
183                        require_once $RandomCompatDIR.'/random_bytes_com_dotnet.php';
184                    }
185                } catch (com_exception $e) {
186                    // Don't try to use it.
187                }
188            }
189            $RandomCompat_disabled_classes = null;
190            $RandomCompatCOMtest = null;
191        }
192
193        /**
194         * throw new Exception
195         */
196        if (!is_callable('random_bytes')) {
197            /**
198             * We don't have any more options, so let's throw an exception right now
199             * and hope the developer won't let it fail silently.
200             */
201            function random_bytes($length)
202            {
203                throw new Exception(
204                    'There is no suitable CSPRNG installed on your system'
205                );
206            }
207        }
208    }
209
210    if (!is_callable('random_int')) {
211        require_once $RandomCompatDIR.'/random_int.php';
212    }
213
214    $RandomCompatDIR = null;
215}
216