Completed
Push — master ( 20d8fe...40dd32 )
by Harald
09:20 queued 04:54
created

random.php ➔ random_bytes()   B

Complexity

Conditions 5
Paths 4

Size

Total Lines 6
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 17
nc 4
nop 1
dl 0
loc 6
rs 8.8571
c 0
b 0
f 0
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.2
7
 * @released 2016-04-03
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
32
if (!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
if (PHP_VERSION_ID < 70000) {
45
46
    if (!defined('RANDOM_COMPAT_READ_BUFFER')) {
47
        define('RANDOM_COMPAT_READ_BUFFER', 8);
48
    }
49
50
    $RandomCompatDIR = dirname(__FILE__);
51
52
    require_once $RandomCompatDIR.'/byte_safe_strings.php';
53
    require_once $RandomCompatDIR.'/cast_to_int.php';
54
    require_once $RandomCompatDIR.'/error_polyfill.php';
55
56
    if (!is_callable('random_bytes')) {
57
        /**
58
         * PHP 5.2.0 - 5.6.x way to implement random_bytes()
59
         *
60
         * We use conditional statements here to define the function in accordance
61
         * to the operating environment. It's a micro-optimization.
62
         *
63
         * In order of preference:
64
         *   1. Use libsodium if available.
65
         *   2. fread() /dev/urandom if available (never on Windows)
66
         *   3. mcrypt_create_iv($bytes, MCRYPT_DEV_URANDOM)
67
         *   4. COM('CAPICOM.Utilities.1')->GetRandom()
68
         *   5. openssl_random_pseudo_bytes() (absolute last resort)
69
         *
70
         * See ERRATA.md for our reasoning behind this particular order
71
         */
72
        if (extension_loaded('libsodium')) {
73
            // See random_bytes_libsodium.php
74
            if (PHP_VERSION_ID >= 50300 && is_callable('\\Sodium\\randombytes_buf')) {
75
                require_once $RandomCompatDIR.'/random_bytes_libsodium.php';
76
            } elseif (method_exists('Sodium', 'randombytes_buf')) {
77
                require_once $RandomCompatDIR.'/random_bytes_libsodium_legacy.php';
78
            }
79
        }
80
81
        /**
82
         * Reading directly from /dev/urandom:
83
         */
84
        if (DIRECTORY_SEPARATOR === '/') {
85
            // DIRECTORY_SEPARATOR === '/' on Unix-like OSes -- this is a fast
86
            // way to exclude Windows.
87
            $RandomCompatUrandom = true;
88
            $RandomCompat_basedir = ini_get('open_basedir');
89
90
            if (!empty($RandomCompat_basedir)) {
91
                $RandomCompat_open_basedir = explode(
92
                    PATH_SEPARATOR,
93
                    strtolower($RandomCompat_basedir)
94
                );
95
                $RandomCompatUrandom = (array() !== array_intersect(
96
                    array('/dev', '/dev/', '/dev/urandom'),
97
                    $RandomCompat_open_basedir
98
                ));
99
                $RandomCompat_open_basedir = null;
100
            }
101
102
            if (
103
                !is_callable('random_bytes')
104
                &&
105
                $RandomCompatUrandom
106
                &&
107
                @is_readable('/dev/urandom')
108
            ) {
109
                // Error suppression on is_readable() in case of an open_basedir
110
                // or safe_mode failure. All we care about is whether or not we
111
                // can read it at this point. If the PHP environment is going to
112
                // panic over trying to see if the file can be read in the first
113
                // place, that is not helpful to us here.
114
115
                // See random_bytes_dev_urandom.php
116
                require_once $RandomCompatDIR.'/random_bytes_dev_urandom.php';
117
            }
118
            // Unset variables after use
119
            $RandomCompat_basedir = null;
120
        } else {
121
            $RandomCompatUrandom = false;
122
        }
123
124
        /**
125
         * mcrypt_create_iv()
126
         */
127
        if (
128
            !is_callable('random_bytes')
129
            &&
130
            PHP_VERSION_ID >= 50307
131
            &&
132
            extension_loaded('mcrypt')
133
            &&
134
            (DIRECTORY_SEPARATOR !== '/' || $RandomCompatUrandom)
135
        ) {
136
            // Prevent this code from hanging indefinitely on non-Windows;
137
            // see https://bugs.php.net/bug.php?id=69833
138
            if (
139
                DIRECTORY_SEPARATOR !== '/' || 
140
                (PHP_VERSION_ID <= 50609 || PHP_VERSION_ID >= 50613)
141
            ) {
142
                // See random_bytes_mcrypt.php
143
                require_once $RandomCompatDIR.'/random_bytes_mcrypt.php';
144
            }
145
        }
146
        $RandomCompatUrandom = null;
147
148
        if (
149
            !is_callable('random_bytes')
150
            &&
151
            extension_loaded('com_dotnet')
152
            &&
153
            class_exists('COM')
154
        ) {
155
            $RandomCompat_disabled_classes = preg_split(
156
                '#\s*,\s*#',
157
                strtolower(ini_get('disable_classes'))
158
            );
159
160
            if (!in_array('com', $RandomCompat_disabled_classes)) {
161
                try {
162
                    $RandomCompatCOMtest = new COM('CAPICOM.Utilities.1');
163
                    if (method_exists($RandomCompatCOMtest, 'GetRandom')) {
164
                        // See random_bytes_com_dotnet.php
165
                        require_once $RandomCompatDIR.'/random_bytes_com_dotnet.php';
166
                    }
167
                } catch (com_exception $e) {
0 ignored issues
show
Bug introduced by
The class com_exception does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
168
                    // Don't try to use it.
169
                }
170
            }
171
            $RandomCompat_disabled_classes = null;
172
            $RandomCompatCOMtest = null;
173
        }
174
175
        /**
176
         * throw new Exception
177
         */
178
        if (!is_callable('random_bytes')) {
179
            /**
180
             * We don't have any more options, so let's throw an exception right now
181
             * and hope the developer won't let it fail silently.
182
             */
183
            function random_bytes($length)
0 ignored issues
show
Unused Code introduced by
The parameter $length is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
184
            {
185
                throw new Exception(
186
                    'There is no suitable CSPRNG installed on your system'
187
                );
188
            }
189
        }
190
    }
191
192
    if (!is_callable('random_int')) {
193
        require_once $RandomCompatDIR.'/random_int.php';
194
    }
195
196
    $RandomCompatDIR = null;
197
}
198