Completed
Push — development ( 1d4607...f5b9c1 )
by Nils
13:38 queued 06:16
created

install.queries.php ➔ encryptFollowingDefuse()   C

Complexity

Conditions 7
Paths 12

Size

Total Lines 36
Code Lines 27

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 7
eloc 27
nc 12
nop 2
dl 0
loc 36
rs 6.7272
c 0
b 0
f 0
1
<?php
2
/**
3
 * @file          install.queries.php
4
 * @author        Nils Laumaillé
5
 * @version       2.1.27
6
 * @copyright     (c) 2009-2017 Nils Laumaillé
7
 * @licensing     GNU AFFERO GPL 3.0
8
 * @link          http://www.teampass.net
9
 *
10
 * This library is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
13
 */
14
require_once('../sources/SecureHandler.php');
15
session_start();
16
error_reporting(E_ERROR | E_PARSE);
17
header("Content-type: text/html; charset=utf-8");
18
$session_db_encoding = "utf8";
19
20 View Code Duplication
function chmodRecursive($dir, $dirPermissions, $filePermissions)
0 ignored issues
show
Duplication introduced by
This function seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
21
{
22
    $pointer_dir = opendir($dir);
0 ignored issues
show
Security File Exposure introduced by
$dir can contain request data and is used in file inclusion context(s) leading to a potential security vulnerability.

1 path for user data to reach this point

  1. Read from $_GET
    in includes/libraries/protect/SuperGlobal/SuperGlobal.php on line 45
  2. SuperGlobal::get() returns tainted data, and $session_abspath is assigned
    in install/install.queries.php on line 130
  3. $session_abspath is passed to chmodRecursive()
    in install/install.queries.php on line 1145

General Strategies to prevent injection

In general, it is advisable to prevent any user-data to reach this point. This can be done by white-listing certain values:

if ( ! in_array($value, array('this-is-allowed', 'and-this-too'), true)) {
    throw new \InvalidArgumentException('This input is not allowed.');
}

For numeric data, we recommend to explicitly cast the data:

$sanitized = (integer) $tainted;
Loading history...
23
    $res = true;
24
    while ($file = readdir($pointer_dir)) {
25
        if (($file == ".") || ($file == "..")) {
26
            continue;
27
        }
28
29
        $fullPath = $dir."/".$file;
30
31
        if (is_dir($fullPath)) {
32
            if ($res = @chmod($fullPath, $dirPermissions)) {
0 ignored issues
show
Security File Manipulation introduced by
$fullPath can contain request data and is used in file manipulation context(s) leading to a potential security vulnerability.

1 path for user data to reach this point

  1. Read from $_GET
    in includes/libraries/protect/SuperGlobal/SuperGlobal.php on line 45
  2. SuperGlobal::get() returns tainted data, and $session_abspath is assigned
    in install/install.queries.php on line 130
  3. $session_abspath is passed to chmodRecursive()
    in install/install.queries.php on line 1145
  4. $fullPath is assigned
    in install/install.queries.php on line 29

General Strategies to prevent injection

In general, it is advisable to prevent any user-data to reach this point. This can be done by white-listing certain values:

if ( ! in_array($value, array('this-is-allowed', 'and-this-too'), true)) {
    throw new \InvalidArgumentException('This input is not allowed.');
}

For numeric data, we recommend to explicitly cast the data:

$sanitized = (integer) $tainted;
Loading history...
33
                $res = @chmodRecursive($fullPath, $dirPermissions, $filePermissions);
34
            }
35
        } else {
36
            $res = chmod($fullPath, $filePermissions);
0 ignored issues
show
Security File Manipulation introduced by
$fullPath can contain request data and is used in file manipulation context(s) leading to a potential security vulnerability.

1 path for user data to reach this point

  1. Read from $_GET
    in includes/libraries/protect/SuperGlobal/SuperGlobal.php on line 45
  2. SuperGlobal::get() returns tainted data, and $session_abspath is assigned
    in install/install.queries.php on line 130
  3. $session_abspath is passed to chmodRecursive()
    in install/install.queries.php on line 1145
  4. $fullPath is assigned
    in install/install.queries.php on line 29

General Strategies to prevent injection

In general, it is advisable to prevent any user-data to reach this point. This can be done by white-listing certain values:

if ( ! in_array($value, array('this-is-allowed', 'and-this-too'), true)) {
    throw new \InvalidArgumentException('This input is not allowed.');
}

For numeric data, we recommend to explicitly cast the data:

$sanitized = (integer) $tainted;
Loading history...
37
        }
38
        if (!$res) {
39
            closedir($pointer_dir);
40
            return false;
41
        }
42
    }
43
    closedir($pointer_dir);
44
    if (is_dir($dir) && $res) {
45
            $res = @chmod($dir, $dirPermissions);
0 ignored issues
show
Security File Manipulation introduced by
$dir can contain request data and is used in file manipulation context(s) leading to a potential security vulnerability.

1 path for user data to reach this point

  1. Read from $_GET
    in includes/libraries/protect/SuperGlobal/SuperGlobal.php on line 45
  2. SuperGlobal::get() returns tainted data, and $session_abspath is assigned
    in install/install.queries.php on line 130
  3. $session_abspath is passed to chmodRecursive()
    in install/install.queries.php on line 1145

General Strategies to prevent injection

In general, it is advisable to prevent any user-data to reach this point. This can be done by white-listing certain values:

if ( ! in_array($value, array('this-is-allowed', 'and-this-too'), true)) {
    throw new \InvalidArgumentException('This input is not allowed.');
}

For numeric data, we recommend to explicitly cast the data:

$sanitized = (integer) $tainted;
Loading history...
46
    }
47
48
    return $res;
49
}
50
51
/**
52
 * genHash()
53
 *
54
 * Generate a hash for user login
55
 * @param string $password
56
 */
57 View Code Duplication
function bCrypt($password, $cost)
0 ignored issues
show
Duplication introduced by
This function seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
58
{
59
    $salt = sprintf('$2y$%02d$', $cost);
60
    if (function_exists('openssl_random_pseudo_bytes')) {
61
        $salt .= bin2hex(openssl_random_pseudo_bytes(11));
62
    } else {
63
        $chars = './ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
64
        for ($i = 0; $i < 22; $i++) {
65
            $salt .= $chars[mt_rand(0, 63)];
66
        }
67
    }
68
    return crypt($password, $salt);
69
}
70
71
/**
72
 * Permits to encrypt a message using Defuse
73
 * @param  string $message   Message to encrypt
74
 * @param  string $ascii_key Key to hash
75
 * @return array             String + Error
76
 */
77
function encryptFollowingDefuse($message, $ascii_key)
78
{
79
    // load PhpEncryption library
80
    $path = '../includes/libraries/Encryption/Encryption/';
81
    require_once $path.'Crypto.php';
82
    require_once $path.'Encoding.php';
83
    require_once $path.'DerivedKeys.php';
84
    require_once $path.'Key.php';
85
    require_once $path.'KeyOrPassword.php';
86
    require_once $path.'File.php';
87
    require_once $path.'RuntimeTests.php';
88
    require_once $path.'KeyProtectedByPassword.php';
89
    require_once $path.'Core.php';
90
91
    // convert KEY
92
    $key = \Defuse\Crypto\Key::loadFromAsciiSafeString($ascii_key);
93
94
    try {
95
        $text = \Defuse\Crypto\Crypto::encrypt($message, $key);
96
    } catch (Defuse\Crypto\Exception\WrongKeyOrModifiedCiphertextException $ex) {
97
        $err = "an attack! either the wrong key was loaded, or the ciphertext has changed since it was created either corrupted in the database or intentionally modified by someone trying to carry out an attack.";
98
    } catch (Defuse\Crypto\Exception\BadFormatException $ex) {
99
        $err = $ex;
100
    } catch (Defuse\Crypto\Exception\EnvironmentIsBrokenException $ex) {
101
        $err = $ex;
102
    } catch (Defuse\Crypto\Exception\CryptoException $ex) {
103
        $err = $ex;
104
    } catch (Defuse\Crypto\Exception\IOException $ex) {
105
        $err = $ex;
106
    }
107
108
    return array(
109
        'string' => isset($text) ? $text : "",
110
        'error' => $err
0 ignored issues
show
Bug introduced by
The variable $err does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
111
    );
112
}
113
114
115
// Prepare POST variables
116
$post_type = filter_input(INPUT_POST, 'type', FILTER_SANITIZE_STRING);
117
$post_data = filter_input(INPUT_POST, 'data', FILTER_SANITIZE_STRING, FILTER_FLAG_NO_ENCODE_QUOTES);
118
$post_activity = filter_input(INPUT_POST, 'activity', FILTER_SANITIZE_STRING);
119
$post_task = filter_input(INPUT_POST, 'task', FILTER_SANITIZE_STRING);
120
$post_index = filter_input(INPUT_POST, 'index', FILTER_SANITIZE_NUMBER_INT);
121
$post_multiple = filter_input(INPUT_POST, 'multiple', FILTER_SANITIZE_STRING);
122
$post_db = filter_input(INPUT_POST, 'db', FILTER_SANITIZE_STRING);
123
124
// Load libraries
125
require_once '../includes/libraries/protect/SuperGlobal/SuperGlobal.php';
126
$superGlobal = new protect\SuperGlobal\SuperGlobal();
127
128
// Prepare SESSION variables
129
$session_url_path = $superGlobal->get("url_path", "SESSION");
130
$session_abspath = $superGlobal->get("abspath", "SESSION");
131
$session_db_encoding = $superGlobal->get("db_encoding", "SESSION");
132
133
$superGlobal->put("CPM", 1, "SESSION");
134
135
if (null !== $post_type) {
136
    switch ($post_type) {
137
        case "step_2":
138
            //decrypt
139
            require_once 'libs/aesctr.php'; // AES Counter Mode implementation
140
            $json = Encryption\Crypt\aesctr::decrypt($post_data, "cpm", 128);
0 ignored issues
show
Documentation introduced by
'cpm' is of type string, but the function expects a object<Encryption\Crypt\the>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
141
            $data = json_decode($json, true);
142
            $json = Encryption\Crypt\aesctr::decrypt($post_activity, "cpm", 128);
0 ignored issues
show
Documentation introduced by
'cpm' is of type string, but the function expects a object<Encryption\Crypt\the>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
143
            $data = array_merge($data, array("activity" => $json));
144
            $json = Encryption\Crypt\aesctr::decrypt($post_task, "cpm", 128);
0 ignored issues
show
Documentation introduced by
'cpm' is of type string, but the function expects a object<Encryption\Crypt\the>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
145
            $data = array_merge($data, array("task" => $json));
146
147
            $abspath = str_replace('\\', '/', $data['root_path']);
148 View Code Duplication
            if (substr($abspath, strlen($abspath) - 1) == "/") {
149
                $abspath = substr($abspath, 0, strlen($abspath) - 1);
150
            }
151
            $session_abspath = $abspath;
152
            $session_url_path = $data['url_path'];
153
154
            if (isset($data['activity']) && $data['activity'] === "folder") {
155
                if (is_writable($abspath."/".$data['task']."/") === true) {
156
                    echo '[{"error" : "", "index" : "'.$post_index.'", "multiple" : "'.$post_multiple.'"}]';
157
                } else {
158
                    echo '[{"error" : " Path '.$data['task'].' is not writable!", "index" : "'.$post_index.'", "multiple" : "'.$post_multiple.'"}]';
159
                }
160
                break;
161
            }
162
163 View Code Duplication
            if (isset($data['activity']) && $data['activity'] === "extension") {
164
                if (extension_loaded($data['task'])) {
165
                    echo '[{"error" : "", "index" : "'.$post_index.'", "multiple" : "'.$post_multiple.'"}]';
166
                } else {
167
                    echo '[{"error" : " Extension '.$data['task'].' is not loaded!", "index" : "'.$post_index.'", "multiple" : "'.$post_multiple.'"}]';
168
                }
169
                break;
170
            }
171
172 View Code Duplication
            if (isset($data['activity']) && $data['activity'] === "function") {
173
                if (function_exists($data['task'])) {
174
                    echo '[{"error" : "", "index" : "'.$post_index.'", "multiple" : "'.$post_multiple.'"}]';
175
                } else {
176
                    echo '[{"error" : " Function '.$data['task'].' is not available!", "index" : "'.$post_index.'", "multiple" : "'.$post_multiple.'"}]';
177
                }
178
                break;
179
            }
180
181
            if (isset($data['activity']) && $data['activity'] === "version") {
182 View Code Duplication
                if (version_compare(phpversion(), '5.5.0', '>=')) {
183
                    echo '[{"error" : "", "index" : "'.$post_index.'", "multiple" : "'.$post_multiple.'"}]';
184
                } else {
185
                    echo '[{"error" : "PHP version '.phpversion().' is not OK (minimum is 5.5.0)", "index" : "'.$post_index.'", "multiple" : "'.$post_multiple.'"}]';
186
                }
187
                break;
188
            }
189
190
            if (isset($data['activity']) && $data['activity'] === "ini") {
191 View Code Duplication
                if (ini_get($data['task']) >= 60) {
192
                    echo '[{"error" : "", "index" : "'.$post_index.'"}]';
193
                } else {
194
                    echo '[{"error" : "PHP \"Maximum execution time\" is set to '.ini_get('max_execution_time').' seconds. Please try to set to 60s at least during installation.", "index" : "'.$post_index.'", "multiple" : "'.$post_multiple.'"}]';
195
                }
196
                break;
197
            }
198
            break;
199
200
        case "step_3":
201
            //decrypt
202
            require_once 'libs/aesctr.php'; // AES Counter Mode implementation
203
            $json = Encryption\Crypt\aesctr::decrypt($post_data, "cpm", 128);
0 ignored issues
show
Documentation introduced by
'cpm' is of type string, but the function expects a object<Encryption\Crypt\the>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
204
            $data = json_decode($json, true);
205
            $json = Encryption\Crypt\aesctr::decrypt($post_db, "cpm", 128);
0 ignored issues
show
Documentation introduced by
'cpm' is of type string, but the function expects a object<Encryption\Crypt\the>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
206
            $db = json_decode($json, true);
207
208
            // launch
209
            if ($dbTmp = mysqli_connect($db['db_host'], $db['db_login'], $db['db_pw'], $db['db_bdd'], $db['db_port'])) {
210
                // create temporary INSTALL mysqli table
211
                $mysqli_result = mysqli_query(
212
                    $dbTmp,
213
                    "CREATE TABLE IF NOT EXISTS `_install` (
214
                    `key` varchar(100) NOT NULL,
215
                    `value` varchar(500) NOT NULL
216
                    ) CHARSET=utf8;"
217
                );
218
                // store values
219 View Code Duplication
                foreach ($data as $key => $value) {
220
                    $superGlobal->put($key, $value, "SESSION");
221
                    $tmp = mysqli_num_rows(mysqli_query($db_link, "SELECT * FROM `_install` WHERE `key` = '".$key."'"));
222
                    if (intval($tmp) === 0) {
223
                        mysqli_query($dbTmp, "INSERT INTO `_install` (`key`, `value`) VALUES ('".$key."', '".$value."');");
224
                    } else {
225
                        mysqli_query($dbTmp, "UPDATE `_install` SET `value` = '".$value."' WHERE `key` = '".$key."';");
226
                    }
227
                }
228
                $tmp = mysqli_num_rows(mysqli_query($db_link, "SELECT * FROM `_install` WHERE `key` = 'url_path'"));
229 View Code Duplication
                if (intval($tmp) === 0) {
230
                    mysqli_query($dbTmp, "INSERT INTO `_install` (`key`, `value`) VALUES ('url_path', '", empty($session_url_path) ? $db['url_path'] : $session_url_path, "');");
231
                } else {
232
                    mysqli_query($dbTmp, "UPDATE `_install` SET `value` = '", empty($session_url_path) ? $db['url_path'] : $session_url_path, "' WHERE `key` = 'url_path';");
233
                }
234
                $tmp = mysqli_num_rows(mysqli_query($db_link, "SELECT * FROM `_install` WHERE `key` = 'abspath'"));
235 View Code Duplication
                if (intval($tmp) === 0) {
236
                    mysqli_query($dbTmp, "INSERT INTO `_install` (`key`, `value`) VALUES ('abspath', '", empty($session_abspath) ? $db['abspath'] : $session_abspath, "');");
237
                } else {
238
                    mysqli_query($dbTmp, "UPDATE `_install` SET `value` = '", empty($session_abspath) ? $db['abspath'] : $session_abspath, "' WHERE `key` = 'abspath';");
239
                }
240
241
                echo '[{"error" : "", "result" : "Connection is successful", "multiple" : ""}]';
242 View Code Duplication
            } else {
243
                echo '[{"error" : "'.addslashes(str_replace(array("'", "\n", "\r"), array('"', '', ''), mysqli_connect_error())).'", "result" : "Failed", "multiple" : ""}]';
244
            }
245
            mysqli_close($dbTmp);
246
            break;
247
248
        case "step_4":
249
            //decrypt
250
            require_once 'libs/aesctr.php'; // AES Counter Mode implementation
251
            $json = Encryption\Crypt\aesctr::decrypt($post_data, "cpm", 128);
0 ignored issues
show
Documentation introduced by
'cpm' is of type string, but the function expects a object<Encryption\Crypt\the>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
252
            $data = json_decode($json, true);
253
            $json = Encryption\Crypt\aesctr::decrypt($post_db, "cpm", 128);
0 ignored issues
show
Documentation introduced by
'cpm' is of type string, but the function expects a object<Encryption\Crypt\the>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
254
            $db = json_decode($json, true);
255
256
            $dbTmp = mysqli_connect($db['db_host'], $db['db_login'], $db['db_pw'], $db['db_bdd'], $db['db_port']);
257
258
            // prepare data
259
            foreach ($data as $key => $value) {
260
                $data[$key] = str_replace(array('&quot;', '&#92;'), array('""', '\\\\'), $value);
261
            }
262
263
            // check skpath
264
            if (empty($data['sk_path'])) {
265
                $data['sk_path'] = $session_abspath."/includes";
266
            } else {
267
                $data['sk_path'] = str_replace("&#92;", "/", $data['sk_path']);
268
            }
269
            if (substr($data['sk_path'], strlen($data['sk_path']) - 1) == "/" || substr($data['sk_path'], strlen($data['sk_path']) - 1) == "\"") {
270
                $data['sk_path'] = substr($data['sk_path'], 0, strlen($data['sk_path']) - 1);
271
            }
272
            if (is_dir($data['sk_path'])) {
273
                if (is_writable($data['sk_path'])) {
274
                    // store all variables in SESSION
275 View Code Duplication
                    foreach ($data as $key => $value) {
276
                        $superGlobal->put($key, $value, "SESSION");
277
                        $tmp = mysqli_num_rows(mysqli_query($db_link, "SELECT * FROM `_install` WHERE `key` = '".$key."'"));
0 ignored issues
show
Security SQL Injection introduced by
'SELECT * FROM `_install...ey` = \'' . $key . '\'' can contain request data and is used in sql context(s) leading to a potential security vulnerability.

1 path for user data to reach this point

  1. Read from $_GET
    in includes/libraries/protect/SuperGlobal/SuperGlobal.php on line 45
  2. SuperGlobal::get() returns tainted data, and $session_abspath is assigned
    in install/install.queries.php on line 130
  3. $data is assigned
    in install/install.queries.php on line 265
  4. $key is assigned
    in install/install.queries.php on line 275

Preventing SQL Injection

There are two options to prevent SQL injection. Generally, it is recommended to use parameter binding:

$stmt = mysqli_prepare("SELECT * FROM users WHERE name = ?");
$stmt->bind_param("s", $taintedUserName);

An alternative – although generally not recommended – is to escape your data manually:

$mysqli = new mysqli('localhost', 'user', 'pass', 'dbname');

$escaped = $mysqli->real_escape_string($taintedUserName);
$mysqli->query("SELECT * FROM users WHERE name = '".$escaped."'");

General Strategies to prevent injection

In general, it is advisable to prevent any user-data to reach this point. This can be done by white-listing certain values:

if ( ! in_array($value, array('this-is-allowed', 'and-this-too'), true)) {
    throw new \InvalidArgumentException('This input is not allowed.');
}

For numeric data, we recommend to explicitly cast the data:

$sanitized = (integer) $tainted;
Loading history...
278
                        if (intval($tmp) === 0) {
279
                            mysqli_query($dbTmp, "INSERT INTO `_install` (`key`, `value`) VALUES ('".$key."', '".$value."');");
0 ignored issues
show
Security SQL Injection introduced by
'INSERT INTO `_install` ..., \'' . $value . '\');' can contain request data and is used in sql context(s) leading to a potential security vulnerability.

1 path for user data to reach this point

  1. Read from $_GET
    in includes/libraries/protect/SuperGlobal/SuperGlobal.php on line 45
  2. SuperGlobal::get() returns tainted data, and $session_abspath is assigned
    in install/install.queries.php on line 130
  3. $data is assigned
    in install/install.queries.php on line 265
  4. $key is assigned
    in install/install.queries.php on line 275

Preventing SQL Injection

There are two options to prevent SQL injection. Generally, it is recommended to use parameter binding:

$stmt = mysqli_prepare("SELECT * FROM users WHERE name = ?");
$stmt->bind_param("s", $taintedUserName);

An alternative – although generally not recommended – is to escape your data manually:

$mysqli = new mysqli('localhost', 'user', 'pass', 'dbname');

$escaped = $mysqli->real_escape_string($taintedUserName);
$mysqli->query("SELECT * FROM users WHERE name = '".$escaped."'");

General Strategies to prevent injection

In general, it is advisable to prevent any user-data to reach this point. This can be done by white-listing certain values:

if ( ! in_array($value, array('this-is-allowed', 'and-this-too'), true)) {
    throw new \InvalidArgumentException('This input is not allowed.');
}

For numeric data, we recommend to explicitly cast the data:

$sanitized = (integer) $tainted;
Loading history...
280
                        } else {
281
                            mysqli_query($dbTmp, "UPDATE `_install` SET `value` = '".$value."' WHERE `key` = '".$key."';");
0 ignored issues
show
Security SQL Injection introduced by
'UPDATE `_install` SET `...y` = \'' . $key . '\';' can contain request data and is used in sql context(s) leading to a potential security vulnerability.

1 path for user data to reach this point

  1. Read from $_GET
    in includes/libraries/protect/SuperGlobal/SuperGlobal.php on line 45
  2. SuperGlobal::get() returns tainted data, and $session_abspath is assigned
    in install/install.queries.php on line 130
  3. $data is assigned
    in install/install.queries.php on line 265
  4. $value is assigned
    in install/install.queries.php on line 275

Preventing SQL Injection

There are two options to prevent SQL injection. Generally, it is recommended to use parameter binding:

$stmt = mysqli_prepare("SELECT * FROM users WHERE name = ?");
$stmt->bind_param("s", $taintedUserName);

An alternative – although generally not recommended – is to escape your data manually:

$mysqli = new mysqli('localhost', 'user', 'pass', 'dbname');

$escaped = $mysqli->real_escape_string($taintedUserName);
$mysqli->query("SELECT * FROM users WHERE name = '".$escaped."'");

General Strategies to prevent injection

In general, it is advisable to prevent any user-data to reach this point. This can be done by white-listing certain values:

if ( ! in_array($value, array('this-is-allowed', 'and-this-too'), true)) {
    throw new \InvalidArgumentException('This input is not allowed.');
}

For numeric data, we recommend to explicitly cast the data:

$sanitized = (integer) $tainted;
Loading history...
282
                        }
283
                    }
284
                    echo '[{"error" : "", "result" : "Information stored", "multiple" : ""}]';
285
                } else {
286
                    echo '[{"error" : "The Directory must be writable!", "result" : "Information stored", "multiple" : ""}]';
287
                }
288
            } else {
289
                echo '[{"error" : "'.$data['sk_path'].' is not a Directory!", "result" : "Information stored", "multiple" : ""}]';
0 ignored issues
show
Security Cross-Site Scripting introduced by
'[{"error" : "' . $data[...ed", "multiple" : ""}]' can contain request data and is used in output context(s) leading to a potential security vulnerability.

1 path for user data to reach this point

  1. Read from $_GET
    in includes/libraries/protect/SuperGlobal/SuperGlobal.php on line 45
  2. SuperGlobal::get() returns tainted data, and $session_abspath is assigned
    in install/install.queries.php on line 130
  3. $data is assigned
    in install/install.queries.php on line 265

Preventing Cross-Site-Scripting Attacks

Cross-Site-Scripting allows an attacker to inject malicious code into your website - in particular Javascript code, and have that code executed with the privileges of a visiting user. This can be used to obtain data, or perform actions on behalf of that visiting user.

In order to prevent this, make sure to escape all user-provided data:

// for HTML
$sanitized = htmlentities($tainted, ENT_QUOTES);

// for URLs
$sanitized = urlencode($tainted);

General Strategies to prevent injection

In general, it is advisable to prevent any user-data to reach this point. This can be done by white-listing certain values:

if ( ! in_array($value, array('this-is-allowed', 'and-this-too'), true)) {
    throw new \InvalidArgumentException('This input is not allowed.');
}

For numeric data, we recommend to explicitly cast the data:

$sanitized = (integer) $tainted;
Loading history...
290
            }
291
            mysqli_close($dbTmp);
292
            break;
293
294
        case "step_5":
295
            //decrypt
296
            require_once 'libs/aesctr.php'; // AES Counter Mode implementation
297
            $activity = Encryption\Crypt\aesctr::decrypt($post_activity, "cpm", 128);
0 ignored issues
show
Documentation introduced by
'cpm' is of type string, but the function expects a object<Encryption\Crypt\the>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
298
            $task = Encryption\Crypt\aesctr::decrypt($post_task, "cpm", 128);
0 ignored issues
show
Documentation introduced by
'cpm' is of type string, but the function expects a object<Encryption\Crypt\the>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
299
            $json = Encryption\Crypt\aesctr::decrypt($post_db, "cpm", 128);
0 ignored issues
show
Documentation introduced by
'cpm' is of type string, but the function expects a object<Encryption\Crypt\the>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
300
            $db = json_decode($json, true);
301
302
            // launch
303
            $dbTmp = mysqli_connect($db['db_host'], $db['db_login'], $db['db_pw'], $db['db_bdd'], $db['db_port']);
304
            $dbBdd = $db['db_bdd'];
305
            if ($dbTmp) {
306
                $mysqli_result = "";
307
308
                // read install variables
309
                $result = mysqli_query($dbTmp, "SELECT * FROM `_install`");
310
                while ($row = $result->fetch_array()) {
311
                    $var[$row[0]] = $row[1];
312
                }
313
314
                if ($activity === "table") {
315
                    //FORCE UTF8 DATABASE
316
                    mysqli_query($dbTmp, "ALTER DATABASE `".$dbBdd."` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci");
317
                    if ($task === "items") {
318
                        $mysqli_result = mysqli_query(
319
                            $dbTmp,
320
                            "CREATE TABLE IF NOT EXISTS `".$var['tbl_prefix']."items` (
321
                            `id` int(12) NOT null AUTO_INCREMENT,
322
                            `label` varchar(500) NOT NULL,
323
                            `description` text DEFAULT NULL,
324
                            `pw` text DEFAULT NULL,
325
                            `pw_iv` text DEFAULT NULL,
326
                            `pw_len` int(5) NOT NULL DEFAULT '0',
327
                            `url` varchar(500) DEFAULT NULL,
328
                            `id_tree` varchar(10) DEFAULT NULL,
329
                            `perso` tinyint(1) NOT null DEFAULT '0',
330
                            `login` varchar(200) DEFAULT NULL,
331
                            `inactif` tinyint(1) NOT null DEFAULT '0',
332
                            `restricted_to` varchar(200) DEFAULT NULL,
333
                            `anyone_can_modify` tinyint(1) NOT null DEFAULT '0',
334
                            `email` varchar(100) DEFAULT NULL,
335
                            `notification` varchar(250) DEFAULT NULL,
336
                            `viewed_no` int(12) NOT null DEFAULT '0',
337
                            `complexity_level` varchar(3) NOT null DEFAULT '-1',
338
                            `auto_update_pwd_frequency` tinyint(2) NOT null DEFAULT '0',
339
                            `auto_update_pwd_next_date` varchar(100) NOT null DEFAULT '0',
340
                            `encryption_type` VARCHAR(20) NOT NULL DEFAULT 'not_set',
341
                            PRIMARY KEY (`id`),
342
                            KEY    `restricted_inactif_idx` (`restricted_to`,`inactif`)
343
                            ) CHARSET=utf8;"
344
                        );
345 View Code Duplication
                    } elseif ($task === "log_items") {
346
                        $mysqli_result = mysqli_query(
347
                            $dbTmp,
348
                            "CREATE TABLE IF NOT EXISTS `".$var['tbl_prefix']."log_items` (
349
                            `id_item` int(8) NOT NULL,
350
                            `date` varchar(50) NOT NULL,
351
                            `id_user` int(8) NOT NULL,
352
                            `action` varchar(250) NULL,
353
                            `raison` text NULL,
354
                            `raison_iv` text NULL,
355
                            `encryption_type` VARCHAR(20) NOT NULL DEFAULT 'not_set'
356
                            ) CHARSET=utf8;"
357
                        );
358
                        // create index
359
                        mysqli_query(
360
                            $dbTmp,
361
                            "CREATE INDEX teampass_log_items_id_item_IDX ON ".$var['tbl_prefix']."log_items (id_item,date);"
362
                        );
363
                    } elseif ($task === "misc") {
364
                        $mysqli_result = mysqli_query(
365
                            $dbTmp,
366
                            "CREATE TABLE IF NOT EXISTS `".$var['tbl_prefix']."misc` (
367
                            `increment_id` int(12) NOT null AUTO_INCREMENT,
368
                            `type` varchar(50) NOT NULL,
369
                            `intitule` varchar(100) NOT NULL,
370
                            `valeur` varchar(500) NOT NULL,
371
                            PRIMARY KEY (`increment_id`)
372
                            ) CHARSET=utf8;"
373
                        );
374
375
                        // include constants
376
                        require_once "../includes/config/include.php";
377
378
                        // prepare config file
379
                        $tp_config_file = "../includes/config/tp.config.php";
380 View Code Duplication
                        if (file_exists($tp_config_file)) {
381
                            if (!copy($tp_config_file, $tp_config_file.'.'.date("Y_m_d", mktime(0, 0, 0, date('m'), date('d'), date('y'))))) {
382
                                echo '[{"error" : "includes/config/tp.config.php file already exists and cannot be renamed. Please do it by yourself and click on button Launch.", "result":"", "index" : "'.$post_index.'", "multiple" : "'.$post_multiple.'"}]';
383
                                break;
384
                            } else {
385
                                unlink($tp_config_file);
386
                            }
387
                        }
388
                        $file_handler = fopen($tp_config_file, 'w');
389
                        $config_text = "<?php
390
global \$SETTINGS;
391
\$SETTINGS = array (";
392
393
                        // add by default settings
394
                        $aMiscVal = array(
395
                            array('admin', 'max_latest_items', '10'),
396
                            array('admin', 'enable_favourites', '1'),
397
                            array('admin', 'show_last_items', '1'),
398
                            array('admin', 'enable_pf_feature', '0'),
399
                            array('admin', 'log_connections', '0'),
400
                            array('admin', 'log_accessed', '1'),
401
                            array('admin', 'time_format', 'H:i:s'),
402
                            array('admin', 'date_format', 'd/m/Y'),
403
                            array('admin', 'duplicate_folder', '0'),
404
                            array('admin', 'item_duplicate_in_same_folder', '0'),
405
                            array('admin', 'duplicate_item', '0'),
406
                            array('admin', 'number_of_used_pw', '3'),
407
                            array('admin', 'manager_edit', '1'),
408
                            array('admin', 'cpassman_dir', $var['abspath']),
409
                            array('admin', 'cpassman_url', $var['url_path']),
410
                            array('admin', 'favicon', $var['url_path'].'/favicon.ico'),
411
                            array('admin', 'path_to_upload_folder', $var['abspath'].'/upload'),
412
                            array('admin', 'url_to_upload_folder', $var['url_path'].'/upload'),
413
                            array('admin', 'path_to_files_folder', $var['abspath'].'/files'),
414
                            array('admin', 'url_to_files_folder', $var['url_path'].'/files'),
415
                            array('admin', 'activate_expiration', '0'),
416
                            array('admin', 'pw_life_duration', '0'),
417
                            array('admin', 'maintenance_mode', '1'),
418
                            array('admin', 'enable_sts', '0'),
419
                            array('admin', 'encryptClientServer', '1'),
420
                            array('admin', 'cpassman_version', $SETTINGS_EXT['version']),
421
                            array('admin', 'ldap_mode', '0'),
422
                            array('admin', 'ldap_type', '0'),
423
                            array('admin', 'ldap_suffix', '0'),
424
                            array('admin', 'ldap_domain_dn', '0'),
425
                            array('admin', 'ldap_domain_controler', '0'),
426
                            array('admin', 'ldap_user_attribute', '0'),
427
                            array('admin', 'ldap_ssl', '0'),
428
                            array('admin', 'ldap_tls', '0'),
429
                            array('admin', 'ldap_elusers', '0'),
430
                            array('admin', 'ldap_search_base', '0'),
431
                            array('admin', 'richtext', '0'),
432
                            array('admin', 'allow_print', '0'),
433
                            array('admin', 'roles_allowed_to_print', '0'),
434
                            array('admin', 'show_description', '1'),
435
                            array('admin', 'anyone_can_modify', '0'),
436
                            array('admin', 'anyone_can_modify_bydefault', '0'),
437
                            array('admin', 'nb_bad_authentication', '0'),
438
                            array('admin', 'utf8_enabled', '1'),
439
                            array('admin', 'restricted_to', '0'),
440
                            array('admin', 'restricted_to_roles', '0'),
441
                            array('admin', 'enable_send_email_on_user_login', '0'),
442
                            array('admin', 'enable_user_can_create_folders', '0'),
443
                            array('admin', 'insert_manual_entry_item_history', '0'),
444
                            array('admin', 'enable_kb', '0'),
445
                            array('admin', 'enable_email_notification_on_item_shown', '0'),
446
                            array('admin', 'enable_email_notification_on_user_pw_change', '0'),
447
                            array('admin', 'custom_logo', ''),
448
                            array('admin', 'custom_login_text', ''),
449
                            array('admin', 'default_language', 'english'),
450
                            array('admin', 'send_stats', '0'),
451
                            array('admin', 'send_statistics_items', 'stat_country;stat_users;stat_items;stat_items_shared;stat_folders;stat_folders_shared;stat_admins;stat_managers;stat_ro;stat_mysqlversion;stat_phpversion;stat_teampassversion;stat_languages;stat_kb;stat_suggestion;stat_customfields;stat_api;stat_2fa;stat_agses;stat_duo;stat_ldap;stat_syslog;stat_stricthttps;stat_fav;stat_pf;'),
452
                            array('admin', 'send_stats_time', time() - 2592000),
453
                            array('admin', 'get_tp_info', '1'),
454
                            array('admin', 'send_mail_on_user_login', '0'),
455
                            array('cron', 'sending_emails', '0'),
456
                            array('admin', 'nb_items_by_query', 'auto'),
457
                            array('admin', 'enable_delete_after_consultation', '0'),
458
                            array('admin', 'enable_personal_saltkey_cookie', '0'),
459
                            array('admin', 'personal_saltkey_cookie_duration', '31'),
460
                            array('admin', 'email_smtp_server', ''),
461
                            array('admin', 'email_smtp_auth', ''),
462
                            array('admin', 'email_auth_username', ''),
463
                            array('admin', 'email_auth_pwd', ''),
464
                            array('admin', 'email_port', ''),
465
                            array('admin', 'email_security', ''),
466
                            array('admin', 'email_server_url', ''),
467
                            array('admin', 'email_from', ''),
468
                            array('admin', 'email_from_name', ''),
469
                            array('admin', 'pwd_maximum_length', '40'),
470
                            array('admin', 'google_authentication', '0'),
471
                            array('admin', 'delay_item_edition', '0'),
472
                            array('admin', 'allow_import', '0'),
473
                            array('admin', 'proxy_ip', ''),
474
                            array('admin', 'proxy_port', ''),
475
                            array('admin', 'upload_maxfilesize', '10mb'),
476
                            array('admin', 'upload_docext', 'doc,docx,dotx,xls,xlsx,xltx,rtf,csv,txt,pdf,ppt,pptx,pot,dotx,xltx'),
477
                            array('admin', 'upload_imagesext', 'jpg,jpeg,gif,png'),
478
                            array('admin', 'upload_pkgext', '7z,rar,tar,zip'),
479
                            array('admin', 'upload_otherext', 'sql,xml'),
480
                            array('admin', 'upload_imageresize_options', '1'),
481
                            array('admin', 'upload_imageresize_width', '800'),
482
                            array('admin', 'upload_imageresize_height', '600'),
483
                            array('admin', 'upload_imageresize_quality', '90'),
484
                            array('admin', 'use_md5_password_as_salt', '0'),
485
                            array('admin', 'ga_website_name', 'TeamPass for ChangeMe'),
486
                            array('admin', 'api', '0'),
487
                            array('admin', 'subfolder_rights_as_parent', '0'),
488
                            array('admin', 'show_only_accessible_folders', '0'),
489
                            array('admin', 'enable_suggestion', '0'),
490
                            array('admin', 'otv_expiration_period', '7'),
491
                            array('admin', 'default_session_expiration_time', '60'),
492
                            array('admin', 'duo', '0'),
493
                            array('admin', 'enable_server_password_change', '0'),
494
                            array('admin', 'ldap_object_class', '0'),
495
                            array('admin', 'bck_script_path', $var['abspath']."/backups"),
496
                            array('admin', 'bck_script_filename', 'bck_teampass'),
497
                            array('admin', 'syslog_enable', '0'),
498
                            array('admin', 'syslog_host', 'localhost'),
499
                            array('admin', 'syslog_port', '514'),
500
                            array('admin', 'manager_move_item', '0'),
501
                            array('admin', 'create_item_without_password', '0'),
502
                            array('admin', 'otv_is_enabled', '0'),
503
                            array('admin', 'agses_authentication_enabled', '0'),
504
                            array('admin', 'item_extra_fields', '0'),
505
                            array('admin', 'saltkey_ante_2127', 'none'),
506
                            array('admin', 'migration_to_2127', 'done'),
507
                            array('admin', 'files_with_defuse', 'done'),
508
                            array('admin', 'timezone', 'UTC')
509
                        );
510
                        foreach ($aMiscVal as $elem) {
511
                            //Check if exists before inserting
512
                            $tmp = mysqli_num_rows(
513
                                mysqli_query(
514
                                    $dbTmp,
515
                                    "SELECT * FROM `".$var['tbl_prefix']."misc`
516
                                    WHERE type='".$elem[0]."' AND intitule='".$elem[1]."'"
517
                                )
518
                            );
519
                            if (intval($tmp) === 0) {
520
                                $queryRes = mysqli_query(
521
                                    $dbTmp,
522
                                    "INSERT INTO `".$var['tbl_prefix']."misc`
523
                                    (`type`, `intitule`, `valeur`) VALUES
524
                                    ('".$elem[0]."', '".$elem[1]."', '".
525
                                    str_replace("'", "", $elem[2])."');"
526
                                ); // or die(mysqli_error($dbTmp))
0 ignored issues
show
Unused Code Comprehensibility introduced by
70% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
527
                            }
528
529
                            // append new setting in config file
530
                            $config_text .= "
531
    '".$elem[1]."' => '".str_replace("'", "", $elem[2])."',";
532
                        }
533
534
                        // write to config file
535
                        $result = fwrite(
536
                            $file_handler,
537
                            utf8_encode(
538
                                substr_replace($config_text, "", -1)."
539
);"
540
                            )
541
                        );
542
                        fclose($file_handler);
543
                    } elseif ($task === "nested_tree") {
544
                        $mysqli_result = mysqli_query(
545
                            $dbTmp,
546
                            "CREATE TABLE IF NOT EXISTS `".$var['tbl_prefix']."nested_tree` (
547
                            `id` bigint(20) unsigned NOT null AUTO_INCREMENT,
548
                            `parent_id` int(11) NOT NULL,
549
                            `title` varchar(255) NOT NULL,
550
                            `nleft` int(11) NOT NULL DEFAULT '0',
551
                            `nright` int(11) NOT NULL DEFAULT '0',
552
                            `nlevel` int(11) NOT NULL DEFAULT '0',
553
                            `bloquer_creation` tinyint(1) NOT null DEFAULT '0',
554
                            `bloquer_modification` tinyint(1) NOT null DEFAULT '0',
555
                            `personal_folder` tinyint(1) NOT null DEFAULT '0',
556
                            `renewal_period` TINYINT(4) NOT null DEFAULT '0',
557
                            PRIMARY KEY (`id`),
558
                            UNIQUE KEY `id` (`id`),
559
                            KEY `nested_tree_parent_id` (`parent_id`),
560
                            KEY `nested_tree_nleft` (`nleft`),
561
                            KEY `nested_tree_nright` (`nright`),
562
                            KEY `nested_tree_nlevel` (`nlevel`),
563
                            KEY `personal_folder_idx` (`personal_folder`)
564
                            ) CHARSET=utf8;"
565
                        );
566
                    } elseif ($task === "rights") {
567
                        $mysqli_result = mysqli_query(
568
                            $dbTmp,
569
                            "CREATE TABLE IF NOT EXISTS `".$var['tbl_prefix']."rights` (
570
                            `id` int(12) NOT null AUTO_INCREMENT,
571
                            `tree_id` int(12) NOT NULL,
572
                            `fonction_id` int(12) NOT NULL,
573
                            `authorized` tinyint(1) NOT null DEFAULT '0',
574
                            PRIMARY KEY (`id`)
575
                            ) CHARSET=utf8;"
576
                        );
577
                    } elseif ($task === "users") {
578
                        $mysqli_result = mysqli_query(
579
                            $dbTmp,
580
                            "CREATE TABLE IF NOT EXISTS `".$var['tbl_prefix']."users` (
581
                            `id` int(12) NOT null AUTO_INCREMENT,
582
                            `login` varchar(50) NOT NULL,
583
                            `pw` varchar(400) NOT NULL,
584
                            `groupes_visibles` varchar(250) NOT NULL,
585
                            `derniers` text NULL,
586
                            `key_tempo` varchar(100) NULL,
587
                            `last_pw_change` varchar(30) NULL,
588
                            `last_pw` text NULL,
589
                            `admin` tinyint(1) NOT null DEFAULT '0',
590
                            `fonction_id` varchar(255) NULL,
591
                            `groupes_interdits` varchar(255) NULL,
592
                            `last_connexion` varchar(30) NULL,
593
                            `gestionnaire` int(11) NOT null DEFAULT '0',
594
                            `email` varchar(300) NOT NULL DEFAULT 'none',
595
                            `favourites` varchar(300) NULL,
596
                            `latest_items` varchar(300) NULL,
597
                            `personal_folder` int(1) NOT null DEFAULT '0',
598
                            `disabled` tinyint(1) NOT null DEFAULT '0',
599
                            `no_bad_attempts` tinyint(1) NOT null DEFAULT '0',
600
                            `can_create_root_folder` tinyint(1) NOT null DEFAULT '0',
601
                            `read_only` tinyint(1) NOT null DEFAULT '0',
602
                            `timestamp` varchar(30) NOT null DEFAULT '0',
603
                            `user_language` varchar(50) NOT null DEFAULT '0',
604
                            `name` varchar(100) NULL,
605
                            `lastname` varchar(100) NULL,
606
                            `session_end` varchar(30) NULL,
607
                            `isAdministratedByRole` tinyint(5) NOT null DEFAULT '0',
608
                            `psk` varchar(400) NULL,
609
                            `ga` varchar(50) NULL,
610
                            `ga_temporary_code` VARCHAR(20) NOT NULL DEFAULT 'none',
611
                            `avatar` varchar(255) NULL,
612
                            `avatar_thumb` varchar(255) NULL,
613
                            `upgrade_needed` BOOLEAN NOT NULL DEFAULT FALSE,
614
                            `treeloadstrategy` varchar(30) NOT null DEFAULT 'full',
615
                            `can_manage_all_users` tinyint(1) NOT NULL DEFAULT '0',
616
                            `usertimezone` VARCHAR(50) NOT NULL DEFAULT 'not_defined',
617
                            `agses-usercardid` VARCHAR(50) NOT NULL DEFAULT '0',
618
                            `encrypted_psk` text NULL,
619
                            `user_ip` varchar(400) NOT null DEFAULT 'none',
620
                            PRIMARY KEY (`id`),
621
                            UNIQUE KEY `login` (`login`)
622
                            ) CHARSET=utf8;"
623
                        );
624
625
                        require_once "../includes/config/include.php";
626
                        // check that admin accounts doesn't exist
627
                        $tmp = mysqli_num_rows(mysqli_query($dbTmp, "SELECT * FROM `".$var['tbl_prefix']."users` WHERE login = 'admin'"));
628
                        if ($tmp === 0) {
629
                            $mysqli_result = mysqli_query(
630
                                $dbTmp,
631
                                "INSERT INTO `".$var['tbl_prefix']."users` (`id`, `login`, `pw`, `admin`, `gestionnaire`, `personal_folder`, `groupes_visibles`, `email`, `encrypted_psk`, `last_pw_change`) VALUES ('1', 'admin', '".bCrypt($var['admin_pwd'], '13')."', '1', '0', '0', '', '', '', '".time()."')"
632
                            );
633
                        } else {
634
                            $mysqli_result = mysqli_query($dbTmp, "UPDATE `".$var['tbl_prefix']."users` SET `pw` = '".bCrypt($var['admin_pwd'], '13')."' WHERE login = 'admin' AND id = '1'");
635
                        }
636
637
                        // check that API doesn't exist
638
                        $tmp = mysqli_num_rows(mysqli_query($dbTmp, "SELECT * FROM `".$var['tbl_prefix']."users` WHERE id = '".API_USER_ID."'"));
639
                        if ($tmp === 0) {
640
                            $mysqli_result = mysqli_query(
641
                                $dbTmp,
642
                                "INSERT INTO `".$var['tbl_prefix']."users` (`id`, `login`, `pw`, `groupes_visibles`, `derniers`, `key_tempo`, `last_pw_change`, `last_pw`, `admin`, `fonction_id`, `groupes_interdits`, `last_connexion`, `gestionnaire`, `email`, `favourites`, `latest_items`, `personal_folder`) VALUES ('".API_USER_ID."', 'API', '', '', '', '', '', '', '1', '', '', '', '0', '', '', '', '0')"
643
                            );
644
                        }
645
646
                        // check that OTV doesn't exist
647
                        $tmp = mysqli_num_rows(mysqli_query($dbTmp, "SELECT * FROM `".$var['tbl_prefix']."users` WHERE id = '".OTV_USER_ID."'"));
648
                        if ($tmp === 0) {
649
                            $mysqli_result = mysqli_query(
650
                                $dbTmp,
651
                                "INSERT INTO `".$var['tbl_prefix']."users` (`id`, `login`, `pw`, `groupes_visibles`, `derniers`, `key_tempo`, `last_pw_change`, `last_pw`, `admin`, `fonction_id`, `groupes_interdits`, `last_connexion`, `gestionnaire`, `email`, `favourites`, `latest_items`, `personal_folder`) VALUES ('".OTV_USER_ID."', 'OTV', '', '', '', '', '', '', '1', '', '', '', '0', '', '', '', '0')"
652
                            );
653
                        }
654
                    } elseif ($task === "tags") {
655
                        $mysqli_result = mysqli_query(
656
                            $dbTmp,
657
                            "CREATE TABLE IF NOT EXISTS `".$var['tbl_prefix']."tags` (
658
                            `id` int(12) NOT null AUTO_INCREMENT,
659
                            `tag` varchar(30) NOT NULL,
660
                            `item_id` int(12) NOT NULL,
661
                            PRIMARY KEY (`id`),
662
                            UNIQUE KEY `id` (`id`)
663
                            ) CHARSET=utf8;"
664
                        );
665
                    } elseif ($task === "log_system") {
666
                        $mysqli_result = mysqli_query(
667
                            $dbTmp,
668
                            "CREATE TABLE IF NOT EXISTS `".$var['tbl_prefix']."log_system` (
669
                            `id` int(12) NOT null AUTO_INCREMENT,
670
                            `type` varchar(20) NOT NULL,
671
                            `date` varchar(30) NOT NULL,
672
                            `label` text NOT NULL,
673
                            `qui` varchar(255) NOT NULL,
674
                            `field_1` varchar(250) DEFAULT NULL,
675
                            PRIMARY KEY (`id`)
676
                            ) CHARSET=utf8;"
677
                        );
678
                    } elseif ($task === "files") {
679
                        $mysqli_result = mysqli_query(
680
                            $dbTmp,
681
                            "CREATE TABLE IF NOT EXISTS `".$var['tbl_prefix']."files` (
682
                            `id` int(11) NOT null AUTO_INCREMENT,
683
                            `id_item` int(11) NOT NULL,
684
                            `name` varchar(100) NOT NULL,
685
                            `size` int(10) NOT NULL,
686
                            `extension` varchar(10) NOT NULL,
687
                            `type` varchar(255) NOT NULL,
688
                            `file` varchar(50) NOT NULL,
689
                            `status` varchar(50) NOT NULL DEFAULT '0',
690
                            PRIMARY KEY (`id`)
691
                           ) CHARSET=utf8;"
692
                        );
693
                    } elseif ($task === "cache") {
694
                        $mysqli_result = mysqli_query(
695
                            $dbTmp,
696
                            "CREATE TABLE IF NOT EXISTS `".$var['tbl_prefix']."cache` (
697
                            `id` int(12) NOT NULL,
698
                            `label` varchar(500) NOT NULL,
699
                            `description` text NOT NULL,
700
                            `tags` text DEFAULT NULL,
701
                            `id_tree` int(12) NOT NULL,
702
                            `perso` tinyint(1) NOT NULL,
703
                            `restricted_to` varchar(200) DEFAULT NULL,
704
                            `login` varchar(200) DEFAULT NULL,
705
                            `folder` varchar(300) NOT NULL,
706
                            `author` varchar(50) NOT NULL,
707
                            `renewal_period` tinyint(4) NOT NULL DEFAULT '0',
708
                            `timestamp` varchar(50) DEFAULT NULL,
709
                            `url` varchar(500) NOT NULL DEFAULT '0',
710
                            `encryption_type` VARCHAR(50) DEFAULT NULL DEFAULT '0'
711
                            ) CHARSET=utf8;"
712
                        );
713
                    } elseif ($task === "roles_title") {
714
                        $mysqli_result = mysqli_query(
715
                            $dbTmp,
716
                            "CREATE TABLE IF NOT EXISTS `".$var['tbl_prefix']."roles_title` (
717
                            `id` int(12) NOT null AUTO_INCREMENT,
718
                            `title` varchar(50) NOT NULL,
719
                            `allow_pw_change` TINYINT(1) NOT null DEFAULT '0',
720
                            `complexity` INT(5) NOT null DEFAULT '0',
721
                            `creator_id` int(11) NOT null DEFAULT '0',
722
                            PRIMARY KEY (`id`)
723
                            ) CHARSET=utf8;"
724
                        );
725
                    } elseif ($task === "roles_values") {
726
                        $mysqli_result = mysqli_query(
727
                            $dbTmp,
728
                            "CREATE TABLE IF NOT EXISTS `".$var['tbl_prefix']."roles_values` (
729
                            `role_id` int(12) NOT NULL,
730
                            `folder_id` int(12) NOT NULL,
731
                            `type` varchar(5) NOT NULL DEFAULT 'R',
732
                            KEY `role_id_idx` (`role_id`)
733
                            ) CHARSET=utf8;"
734
                        );
735
                    } elseif ($task === "kb") {
736
                        $mysqli_result = mysqli_query(
737
                            $dbTmp,
738
                            "CREATE TABLE IF NOT EXISTS `".$var['tbl_prefix']."kb` (
739
                            `id` int(12) NOT null AUTO_INCREMENT,
740
                            `category_id` int(12) NOT NULL,
741
                            `label` varchar(200) NOT NULL,
742
                            `description` text NOT NULL,
743
                            `author_id` int(12) NOT NULL,
744
                            `anyone_can_modify` tinyint(1) NOT null DEFAULT '0',
745
                            PRIMARY KEY (`id`)
746
                            ) CHARSET=utf8;"
747
                        );
748
                    } elseif ($task === "kb_categories") {
749
                        $mysqli_result = mysqli_query(
750
                            $dbTmp,
751
                            "CREATE TABLE IF NOT EXISTS `".$var['tbl_prefix']."kb_categories` (
752
                            `id` int(12) NOT null AUTO_INCREMENT,
753
                            `category` varchar(50) NOT NULL,
754
                            PRIMARY KEY (`id`)
755
                            ) CHARSET=utf8;"
756
                        );
757
                    } elseif ($task === "kb_items") {
758
                        $mysqli_result = mysqli_query(
759
                            $dbTmp,
760
                            "CREATE TABLE IF NOT EXISTS `".$var['tbl_prefix']."kb_items` (
761
                            `kb_id` int(12) NOT NULL,
762
                            `item_id` int(12) NOT NULL
763
                           ) CHARSET=utf8;"
764
                        );
765
                    } elseif ($task == "restriction_to_roles") {
766
                        $mysqli_result = mysqli_query(
767
                            $dbTmp,
768
                            "CREATE TABLE IF NOT EXISTS `".$var['tbl_prefix']."restriction_to_roles` (
769
                            `role_id` int(12) NOT NULL,
770
                            `item_id` int(12) NOT NULL,
771
                            KEY `role_id_idx`  (`role_id`)
772
                            ) CHARSET=utf8;"
773
                        );
774
                    } elseif ($task === "languages") {
775
                        $mysqli_result = mysqli_query(
776
                            $dbTmp,
777
                            "CREATE TABLE IF NOT EXISTS `".$var['tbl_prefix']."languages` (
778
                            `id` INT(10) NOT null AUTO_INCREMENT PRIMARY KEY ,
779
                            `name` VARCHAR(50) NOT null ,
780
                            `label` VARCHAR(50) NOT null ,
781
                            `code` VARCHAR(10) NOT null ,
782
                            `flag` VARCHAR(30) NOT NULL
783
                            ) CHARSET=utf8;"
784
                        );
785
786
                        // add lanaguages
787
                        $tmp = mysqli_num_rows(mysqli_query($dbTmp, "SELECT * FROM `".$var['tbl_prefix']."languages` WHERE name = 'french'"));
788
                        if ($tmp[0] == 0) {
789
                            $mysql_result = mysqli_query(
790
                                $dbTmp,
791
                                "INSERT INTO `".$var['tbl_prefix']."languages` (`name`, `label`, `code`, `flag`) VALUES
792
                                ('french', 'French' , 'fr', 'fr.png'),
793
                                ('english', 'English' , 'us', 'us.png'),
794
                                ('spanish', 'Spanish' , 'es', 'es.png'),
795
                                ('german', 'German' , 'de', 'de.png'),
796
                                ('czech', 'Czech' , 'cz', 'cz.png'),
797
                                ('italian', 'Italian' , 'it', 'it.png'),
798
                                ('russian', 'Russian' , 'ru', 'ru.png'),
799
                                ('turkish', 'Turkish' , 'tr', 'tr.png'),
800
                                ('norwegian', 'Norwegian' , 'no', 'no.png'),
801
                                ('japanese', 'Japanese' , 'ja', 'ja.png'),
802
                                ('portuguese', 'Portuguese' , 'pr', 'pr.png'),
803
                                ('portuguese_br', 'Portuguese (Brazil)' , 'pr-bt', 'pr-bt.png'),
804
                                ('chinese', 'Chinese' , 'cn', 'cn.png'),
805
                                ('swedish', 'Swedish' , 'se', 'se.png'),
806
                                ('dutch', 'Dutch' , 'nl', 'nl.png'),
807
                                ('catalan', 'Catalan' , 'ct', 'ct.png'),
808
                                ('vietnamese', 'Vietnamese' , 'vi', 'vi.png'),
809
                                ('estonian', 'Estonian' , 'ee', 'ee.png');"
810
                            );
811
                        }
812
                    } elseif ($task === "emails") {
813
                        $mysqli_result = mysqli_query(
814
                            $dbTmp,
815
                            "CREATE TABLE IF NOT EXISTS `".$var['tbl_prefix']."emails` (
816
                            `timestamp` INT(30) NOT null ,
817
                            `subject` VARCHAR(255) NOT null ,
818
                            `body` TEXT NOT null ,
819
                            `receivers` VARCHAR(255) NOT null ,
820
                            `status` VARCHAR(30) NOT NULL
821
                            ) CHARSET=utf8;"
822
                        );
823
                    } elseif ($task === "automatic_del") {
824
                        $mysqli_result = mysqli_query(
825
                            $dbTmp,
826
                            "CREATE TABLE IF NOT EXISTS `".$var['tbl_prefix']."automatic_del` (
827
                            `item_id` int(11) NOT NULL,
828
                            `del_enabled` tinyint(1) NOT NULL,
829
                            `del_type` tinyint(1) NOT NULL,
830
                            `del_value` varchar(35) NOT NULL
831
                            ) CHARSET=utf8;"
832
                        );
833
                    } elseif ($task === "items_edition") {
834
                        $mysqli_result = mysqli_query(
835
                            $dbTmp,
836
                            "CREATE TABLE IF NOT EXISTS `".$var['tbl_prefix']."items_edition` (
837
                            `item_id` int(11) NOT NULL,
838
                            `user_id` int(12) NOT NULL,
839
                            `timestamp` varchar(50) NOT NULL
840
                            ) CHARSET=utf8;"
841
                        );
842
                    } elseif ($task === "categories") {
843
                        $mysqli_result = mysqli_query(
844
                            $dbTmp,
845
                            "CREATE TABLE IF NOT EXISTS `".$var['tbl_prefix']."categories` (
846
                            `id` int(12) NOT NULL AUTO_INCREMENT,
847
                            `parent_id` int(12) NOT NULL,
848
                            `title` varchar(255) NOT NULL,
849
                            `level` int(2) NOT NULL,
850
                            `description` text NULL,
851
                            `type` varchar(50) NULL default '',
852
                            `order` int(12) NOT NULL default '0',
853
                            `encrypted_data` tinyint(1) NOT NULL default '1',
854
                            PRIMARY KEY (`id`)
855
                            ) CHARSET=utf8;"
856
                        );
857
                    } elseif ($task === "categories_items") {
858
                        $mysqli_result = mysqli_query(
859
                            $dbTmp,
860
                            "CREATE TABLE IF NOT EXISTS `".$var['tbl_prefix']."categories_items` (
861
                            `id` int(12) NOT NULL AUTO_INCREMENT,
862
                            `field_id` int(11) NOT NULL,
863
                            `item_id` int(11) NOT NULL,
864
                            `data` text NOT NULL,
865
                            `data_iv` text NOT NULL,
866
                            `encryption_type` VARCHAR(20) NOT NULL DEFAULT 'not_set',
867
                            PRIMARY KEY (`id`)
868
                            ) CHARSET=utf8;"
869
                        );
870
                    } elseif ($task === "categories_folders") {
871
                        $mysqli_result = mysqli_query(
872
                            $dbTmp,
873
                            "CREATE TABLE IF NOT EXISTS `".$var['tbl_prefix']."categories_folders` (
874
                            `id_category` int(12) NOT NULL,
875
                            `id_folder` int(12) NOT NULL
876
                            ) CHARSET=utf8;"
877
                        );
878
                    } elseif ($task === "api") {
879
                        $mysqli_result = mysqli_query(
880
                            $dbTmp,
881
                            "CREATE TABLE IF NOT EXISTS `".$var['tbl_prefix']."api` (
882
                            `id` int(20) NOT NULL AUTO_INCREMENT,
883
                            `type` varchar(15) NOT NULL,
884
                            `label` varchar(255) NOT NULL,
885
                            `value` varchar(255) NOT NULL,
886
                            `timestamp` varchar(50) NOT NULL,
887
                            PRIMARY KEY (`id`)
888
                            ) CHARSET=utf8;"
889
                        );
890
                    } elseif ($task === "otv") {
891
                        $mysqli_result = mysqli_query(
892
                            $dbTmp,
893
                            "CREATE TABLE IF NOT EXISTS `".$var['tbl_prefix']."otv` (
894
                            `id` int(10) NOT NULL AUTO_INCREMENT,
895
                            `timestamp` text NOT NULL,
896
                            `code` varchar(100) NOT NULL,
897
                            `item_id` int(12) NOT NULL,
898
                            `originator` int(12) NOT NULL,
899
                            PRIMARY KEY (`id`)
900
                            ) CHARSET=utf8;"
901
                        );
902 View Code Duplication
                    } elseif ($task === "suggestion") {
903
                        $mysqli_result = mysqli_query(
904
                            $dbTmp,
905
                            "CREATE TABLE IF NOT EXISTS `".$var['tbl_prefix']."suggestion` (
906
                            `id` tinyint(12) NOT NULL AUTO_INCREMENT,
907
                            `label` varchar(255) NOT NULL,
908
                            `pw` text NOT NULL,
909
                            `pw_iv` text NOT NULL,
910
                            `pw_len` int(5) NOT NULL,
911
                            `description` text NOT NULL,
912
                            `author_id` int(12) NOT NULL,
913
                            `folder_id` int(12) NOT NULL,
914
                            `comment` text NOT NULL,
915
                            `suggestion_type` varchar(10) NOT NULL default 'new',
916
                            PRIMARY KEY (`id`)
917
                            ) CHARSET=utf8;"
918
                        );
919
920
                        $mysqli_result = mysqli_query(
921
                            $dbTmp,
922
                            "CREATE TABLE IF NOT EXISTS `".$var['tbl_prefix']."export` (
923
                            `id` int(12) NOT NULL,
924
                            `label` varchar(500) NOT NULL,
925
                            `login` varchar(100) NOT NULL,
926
                            `description` text NOT NULL,
927
                            `pw` text NOT NULL,
928
                            `path` varchar(500) NOT NULL,
929
                            `email` varchar(500) NOT NULL default 'none',
930
                            `url` varchar(500) NOT NULL default 'none',
931
                            `kbs` varchar(500) NOT NULL default 'none',
932
                            `tags` varchar(500) NOT NULL default 'none'
933
                            ) CHARSET=utf8;"
934
                        );
935
                    } elseif ($task === "tokens") {
936
                        $mysqli_result = mysqli_query(
937
                            $dbTmp,
938
                            "CREATE TABLE IF NOT EXISTS `".$var['tbl_prefix']."tokens` (
939
                            `id` int(12) NOT NULL AUTO_INCREMENT,
940
                            `user_id` int(12) NOT NULL,
941
                            `token` varchar(255) NOT NULL,
942
                            `reason` varchar(255) NOT NULL,
943
                            `creation_timestamp` varchar(50) NOT NULL,
944
                            `end_timestamp` varchar(50) NOT NULL,
945
                            PRIMARY KEY (`id`)
946
                            ) CHARSET=utf8;"
947
                        );
948
                    } elseif ($task === "items_change") {
949
                        $mysqli_result = mysqli_query(
950
                            $dbTmp,
951
                            "CREATE TABLE IF NOT EXISTS `".$var['tbl_prefix']."items_change` (
952
                            `id` int(12) NOT NULL AUTO_INCREMENT,
953
                            `item_id` int(12) NOT NULL,
954
                            `label` varchar(255) NOT NULL DEFAULT 'none',
955
                            `pw` text NOT NULL,
956
                            `login` varchar(255) NOT NULL DEFAULT 'none',
957
                            `email` varchar(255) NOT NULL DEFAULT 'none',
958
                            `url` varchar(255) NOT NULL DEFAULT 'none',
959
                            `description` text NOT NULL,
960
                            `comment` text NOT NULL,
961
                            `folder_id` tinyint(12) NOT NULL,
962
                            `user_id` int(12) NOT NULL,
963
                            `timestamp` varchar(50) NOT NULL DEFAULT 'none',
964
                            PRIMARY KEY (`id`)
965
                            ) CHARSET=utf8;"
966
                        );
967
                    }
968
                }
969
                // answer back
970
                if ($mysqli_result) {
971
                    echo '[{"error" : "", "index" : "'.$post_index.'", "multiple" : "'.$post_multiple.'", "task" : "'.$task.'", "activity" : "'.$activity.'"}]';
972
                } else {
973
                    echo '[{"error" : "'.addslashes(str_replace(array("'", "\n", "\r"), array('"', '', ''), mysqli_error())).'", "index" : "'.$post_index.'", "multiple" : "'.$post_multiple.'", "table" : "'.$task.'"}]';
974
                }
975 View Code Duplication
            } else {
976
                echo '[{"error" : "'.addslashes(str_replace(array("'", "\n", "\r"), array('"', '', ''), mysqli_connect_error())).'", "result" : "Failed", "multiple" : ""}]';
977
            }
978
979
            mysqli_close($dbTmp);
980
            // Destroy session without writing to disk
981
            define('NODESTROY_SESSION', 'true');
982
            session_destroy();
983
            break;
984
985
        case "step_6":
986
            //decrypt
987
            require_once 'libs/aesctr.php'; // AES Counter Mode implementation
988
            $activity = Encryption\Crypt\aesctr::decrypt($post_activity, "cpm", 128);
0 ignored issues
show
Documentation introduced by
'cpm' is of type string, but the function expects a object<Encryption\Crypt\the>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
989
            $data_sent = Encryption\Crypt\aesctr::decrypt($post_data, "cpm", 128);
0 ignored issues
show
Documentation introduced by
'cpm' is of type string, but the function expects a object<Encryption\Crypt\the>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
990
            $data_sent = json_decode($data_sent, true);
991
            $task = Encryption\Crypt\aesctr::decrypt($post_task, "cpm", 128);
0 ignored issues
show
Documentation introduced by
'cpm' is of type string, but the function expects a object<Encryption\Crypt\the>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
992
            $json = Encryption\Crypt\aesctr::decrypt($post_db, "cpm", 128);
0 ignored issues
show
Documentation introduced by
'cpm' is of type string, but the function expects a object<Encryption\Crypt\the>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
993
            $db = json_decode($json, true);
994
995
            $dbTmp = mysqli_connect(
996
                $db['db_host'],
997
                $db['db_login'],
998
                $db['db_pw'],
999
                $db['db_bdd'],
1000
                $db['db_port']
1001
            );
1002
1003
            // read install variables
1004
            $result = mysqli_query($dbTmp, "SELECT * FROM `_install`");
1005
            while ($row = $result->fetch_array()) {
1006
                $var[$row[0]] = $row[1];
1007
            }
1008
1009
            // launch
1010
            if (empty($var['sk_path'])) {
1011
                $skFile = $var['abspath'].'/includes/sk.php';
1012
                $securePath = $var['abspath'];
1013
            } else {
1014
                //ensure $var['sk_path'] has no trailing slash
1015
                $var['sk_path'] = rtrim($var['sk_path'], '/\\');
1016
                $skFile = $var['sk_path'].'/sk.php';
1017
                $securePath = $var['sk_path'];
1018
            }
1019
1020
            $events = "";
1021
1022
            if ($activity === "file") {
1023
                if ($task === "settings.php") {
1024
                    // first is to create teampass-seckey.txt
1025
                    // 0- check if exists
1026
                    $filename_seckey = $securePath."/teampass-seckey.txt";
1027
1028 View Code Duplication
                    if (file_exists($filename_seckey)) {
1029
                        if (!copy($filename_seckey, $filename_seckey.'.'.date("Y_m_d", mktime(0, 0, 0, date('m'), date('d'), date('y'))))) {
1030
                            echo '[{"error" : "File `$filename_seckey` already exists and cannot be renamed. Please do it by yourself and click on button Launch.", "result":"", "index" : "'.$post_index.'", "multiple" : "'.$post_multiple.'"}]';
1031
                            break;
1032
                        } else {
1033
                            unlink($filename);
1034
                        }
1035
                    }
1036
1037
                    // 1- generate saltkey
1038
                    require_once '../includes/libraries/Encryption/Encryption/Crypto.php';
1039
                    require_once '../includes/libraries/Encryption/Encryption/Encoding.php';
1040
                    require_once '../includes/libraries/Encryption/Encryption/DerivedKeys.php';
1041
                    require_once '../includes/libraries/Encryption/Encryption/Key.php';
1042
                    require_once '../includes/libraries/Encryption/Encryption/KeyOrPassword.php';
1043
                    require_once '../includes/libraries/Encryption/Encryption/File.php';
1044
                    require_once '../includes/libraries/Encryption/Encryption/RuntimeTests.php';
1045
                    require_once '../includes/libraries/Encryption/Encryption/KeyProtectedByPassword.php';
1046
                    require_once '../includes/libraries/Encryption/Encryption/Core.php';
1047
1048
                    $key = \Defuse\Crypto\Key::createNewRandomKey();
1049
                    $new_salt = $key->saveToAsciiSafeString();
1050
1051
                    // 2- store key in file
1052
                    file_put_contents(
1053
                        $filename_seckey,
1054
                        $new_salt
1055
                    );
1056
1057
                    // Now create settings file
1058
                    $filename = "../includes/config/settings.php";
1059
1060 View Code Duplication
                    if (file_exists($filename)) {
1061
                        if (!copy($filename, $filename.'.'.date("Y_m_d", mktime(0, 0, 0, date('m'), date('d'), date('y'))))) {
1062
                            echo '[{"error" : "Setting.php file already exists and cannot be renamed. Please do it by yourself and click on button Launch.", "result":"", "index" : "'.$post_index.'", "multiple" : "'.$post_multiple.'"}]';
1063
                            break;
1064
                        } else {
1065
                            unlink($filename);
1066
                        }
1067
                    }
1068
1069
                    // Encrypt the DB password
1070
                    $encrypted_text = encryptFollowingDefuse(
1071
                        $db['db_pw'],
1072
                        $new_salt
1073
                    )['string'];
1074
1075
                    // Open and write Settings file
1076
                    $file_handler = fopen($filename, 'w');
1077
                    $result = fwrite(
1078
                        $file_handler,
1079
                        utf8_encode(
0 ignored issues
show
Security File Manipulation introduced by
utf8_encode('<?php globa.../', $skFile) . '"; } ') can contain request data and is used in file manipulation context(s) leading to a potential security vulnerability.

1 path for user data to reach this point

  1. Read from $_GET
    in includes/libraries/protect/SuperGlobal/SuperGlobal.php on line 45
  2. SuperGlobal::get() returns tainted data, and $session_db_encoding is assigned
    in install/install.queries.php on line 131
  3. ``'$lang, $txt, $pathTeampas, $urlTeampass, $pwComplexity, $mngPages; global $server, $user, $pass, $database, $pre, $db, $port, $encoding; ### DATABASE connexion parameters ### $server = "' . $db['db_host'] . '"; $user = "' . $db['db_login'] . '"; $pass = "' . str_replace('$', '\\$', $encrypted_text) . '"; $database = "' . $db['db_bdd'] . '"; $pre = "' . $var['tbl_prefix'] . '"; $port = ' . $db['db_port'] . '; $encoding = "' . $session_db_encoding . '"; @date_default_timezone_set($_SESSION[\'settings\'][\'timezone\']); @define(\'SECUREPATH\', \'' . $securePath . '\'); if (file_exists("' . str_replace('\\', '/', $skFile) . '")) { require_once "' . str_replace('\\', '/', $skFile) . '"; } '`` is passed through utf8_encode()
    in install/install.queries.php on line 1080

General Strategies to prevent injection

In general, it is advisable to prevent any user-data to reach this point. This can be done by white-listing certain values:

if ( ! in_array($value, array('this-is-allowed', 'and-this-too'), true)) {
    throw new \InvalidArgumentException('This input is not allowed.');
}

For numeric data, we recommend to explicitly cast the data:

$sanitized = (integer) $tainted;
Loading history...
1080
                            "<?php
1081
global \$lang, \$txt, \$pathTeampas, \$urlTeampass, \$pwComplexity, \$mngPages;
1082
global \$server, \$user, \$pass, \$database, \$pre, \$db, \$port, \$encoding;
1083
1084
### DATABASE connexion parameters ###
1085
\$server = \"".$db['db_host']."\";
1086
\$user = \"".$db['db_login']."\";
1087
\$pass = \"".str_replace("$", "\\$", $encrypted_text)."\";
1088
\$database = \"".$db['db_bdd']."\";
1089
\$pre = \"".$var['tbl_prefix']."\";
1090
\$port = ".$db['db_port'].";
1091
\$encoding = \"".$session_db_encoding."\";
1092
1093
@date_default_timezone_set(\$_SESSION['settings']['timezone']);
1094
@define('SECUREPATH', '".$securePath."');
1095
if (file_exists(\"".str_replace('\\', '/', $skFile)."\")) {
1096
    require_once \"".str_replace('\\', '/', $skFile)."\";
1097
}
1098
"
1099
                        )
1100
                    );
1101
                    fclose($file_handler);
1102 View Code Duplication
                    if ($result === false) {
1103
                        echo '[{"error" : "Setting.php file could not be created. Please check the path and the rights", "result":"", "index" : "'.$post_index.'", "multiple" : "'.$post_multiple.'"}]';
1104
                    } else {
1105
                        echo '[{"error" : "", "index" : "'.$post_index.'", "multiple" : "'.$post_multiple.'"}]';
1106
                    }
1107
                } elseif ($task === "sk.php") {
1108
//Create sk.php file
1109 View Code Duplication
                    if (file_exists($skFile)) {
1110
                        if (!copy($skFile, $skFile.'.'.date("Y_m_d", mktime(0, 0, 0, date('m'), date('d'), date('y'))))) {
1111
                            echo '[{"error" : "sk.php file already exists and cannot be renamed. Please do it by yourself and click on button Launch.", "result":"", "index" : "'.$post_index.'", "multiple" : "'.$post_multiple.'"}]';
1112
                            break;
1113
                        } else {
1114
                            unlink($skFile);
1115
                        }
1116
                    }
1117
                    $file_handler = fopen($skFile, 'w');
1118
1119
                    $result = fwrite(
1120
                        $file_handler,
1121
                        utf8_encode(
1122
                            "<?php
1123
@define('COST', '13'); // Don't change this.
1124
@define('AKEY', '');
1125
@define('IKEY', '');
1126
@define('SKEY', '');
1127
@define('HOST', '');
1128
?>"
1129
                        )
1130
                    );
1131
                    fclose($file_handler);
1132
1133
                    // finalize
1134 View Code Duplication
                    if ($result === false) {
1135
                        echo '[{"error" : "sk.php file could not be created. Please check the path and the rights.", "result":"", "index" : "'.$post_index.'", "multiple" : "'.$post_multiple.'"}]';
1136
                    } else {
1137
                        echo '[{"error" : "", "index" : "'.$post_index.'", "multiple" : "'.$post_multiple.'"}]';
1138
                    }
1139
                } elseif ($task === "security") {
1140
                    # Sort out the file permissions
1141
1142
                    // is server Windows or Linux?
1143
                    if (strtoupper(substr(PHP_OS, 0, 3)) != 'WIN') {
1144
                        // Change directory permissions
1145
                        $result = chmodRecursive($session_abspath, 0770, 0740);
1146
                        if ($result) {
1147
                            $result = chmodRecursive($session_abspath.'/files', 0770, 0770);
1148
                        }
1149
                        if ($result) {
1150
                            $result = chmodRecursive($session_abspath.'/upload', 0770, 0770);
1151
                        }
1152
                    }
1153
1154 View Code Duplication
                    if ($result === false) {
1155
                        echo '[{"error" : "Cannot change directory permissions - please fix manually", "result":"", "index" : "'.$post_index.'", "multiple" : "'.$post_multiple.'"}]';
1156
                    } else {
1157
                        echo '[{"error" : "", "index" : "'.$post_index.'", "multiple" : "'.$post_multiple.'"}]';
1158
                    }
1159
                } elseif ($task === "csrfp-token") {
1160
                    // update CSRFP TOKEN
1161
                    $csrfp_file_sample = "../includes/libraries/csrfp/libs/csrfp.config.sample.php";
1162
                    $csrfp_file = "../includes/libraries/csrfp/libs/csrfp.config.php";
1163 View Code Duplication
                    if (file_exists($csrfp_file)) {
1164
                        if (!copy($csrfp_file, $csrfp_file.'.'.date("Y_m_d", mktime(0, 0, 0, date('m'), date('d'), date('y'))))) {
1165
                            echo '[{"error" : "csrfp.config.php file already exists and cannot be renamed. Please do it by yourself and click on button Launch.", "result":"", "index" : "'.$post_index.'", "multiple" : "'.$post_multiple.'"}]';
1166
                            break;
1167
                        } else {
1168
                            $events .= "The file $csrfp_file already exist. A copy has been created.<br />";
1169
                        }
1170
                    }
1171
                    unlink($csrfp_file); // delete existing csrfp.config file
1172
                    copy($csrfp_file_sample, $csrfp_file); // make a copy of csrfp.config.sample file
1173
                    $data = file_get_contents($csrfp_file);
1174
                    $newdata = str_replace('"CSRFP_TOKEN" => ""', '"CSRFP_TOKEN" => "'.bin2hex(openssl_random_pseudo_bytes(25)).'"', $data);
1175
                    $jsUrl = $data_sent['url_path'].'/includes/libraries/csrfp/js/csrfprotector.js';
1176
                    $newdata = str_replace('"jsUrl" => ""', '"jsUrl" => "'.$jsUrl.'"', $newdata);
1177
                    file_put_contents("../includes/libraries/csrfp/libs/csrfp.config.php", $newdata);
1178
1179
                    echo '[{"error" : "", "index" : "'.$post_index.'", "multiple" : "'.$post_multiple.'"}]';
1180
                }
1181
            } elseif ($activity === "install") {
1182
                if ($task === "cleanup") {
1183
                    // Mark a tag to force Install stuff (folders, files and table) to be cleanup while first login
1184
                    mysqli_query($dbTmp, "INSERT INTO `".$var['tbl_prefix']."misc` (`type`, `intitule`, `valeur`) VALUES ('install', 'clear_install_folder', 'true')");
1185
1186
                    echo '[{"error" : "", "index" : "'.$post_index.'", "multiple" : "'.$post_multiple.'"}]';
1187
                }
1188
            }
1189
1190
            mysqli_close($dbTmp);
1191
            // Destroy session without writing to disk
1192
            define('NODESTROY_SESSION', 'true');
1193
            session_destroy();
1194
            break;
1195
    }
1196
}
1197