Completed
Push — development ( 29f013...348c46 )
by Nils
08:32
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 1148

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 1148
  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 1148
  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 1148

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($dbTmp, "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($dbTmp, "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. "');");
0 ignored issues
show
Security SQL Injection introduced by
'INSERT INTO `_install` ...ssion_url_path . '\');' 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_url_path is assigned
    in install/install.queries.php on line 129

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...
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($dbTmp, "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. "');");
0 ignored issues
show
Security SQL Injection introduced by
'INSERT INTO `_install` ...ession_abspath . '\');' 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

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...
237
                } else {
238
                    mysqli_query($dbTmp, "UPDATE `_install` SET `value` = '". empty($session_abspath) ? $db['abspath'] : $session_abspath. "' WHERE `key` = 'abspath';");
0 ignored issues
show
Security SQL Injection introduced by
'UPDATE `_install` SET `...E `key` = \'abspath\';' 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

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...
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($dbTmp, "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
                    if ($task === "utf8") {
316
                        //FORCE UTF8 DATABASE
317
                        mysqli_query($dbTmp, "ALTER DATABASE `".$dbBdd."` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci");
318
                    } elseif ($task === "items") {
319
                        $mysqli_result = mysqli_query(
320
                            $dbTmp,
321
                            "CREATE TABLE IF NOT EXISTS `".$var['tbl_prefix']."items` (
322
                            `id` int(12) NOT null AUTO_INCREMENT,
323
                            `label` varchar(500) NOT NULL,
324
                            `description` text DEFAULT NULL,
325
                            `pw` text DEFAULT NULL,
326
                            `pw_iv` text DEFAULT NULL,
327
                            `pw_len` int(5) NOT NULL DEFAULT '0',
328
                            `url` varchar(500) DEFAULT NULL,
329
                            `id_tree` varchar(10) DEFAULT NULL,
330
                            `perso` tinyint(1) NOT null DEFAULT '0',
331
                            `login` varchar(200) DEFAULT NULL,
332
                            `inactif` tinyint(1) NOT null DEFAULT '0',
333
                            `restricted_to` varchar(200) DEFAULT NULL,
334
                            `anyone_can_modify` tinyint(1) NOT null DEFAULT '0',
335
                            `email` varchar(100) DEFAULT NULL,
336
                            `notification` varchar(250) DEFAULT NULL,
337
                            `viewed_no` int(12) NOT null DEFAULT '0',
338
                            `complexity_level` varchar(3) NOT null DEFAULT '-1',
339
                            `auto_update_pwd_frequency` tinyint(2) NOT null DEFAULT '0',
340
                            `auto_update_pwd_next_date` varchar(100) NOT null DEFAULT '0',
341
                            `encryption_type` VARCHAR(20) NOT NULL DEFAULT 'not_set',
342
                            PRIMARY KEY (`id`),
343
                            KEY    `restricted_inactif_idx` (`restricted_to`,`inactif`)
344
                            ) CHARSET=utf8;"
345
                        );
346
                    } elseif ($task === "log_items") {
347
                        $mysqli_result = mysqli_query(
348
                            $dbTmp,
349
                            "CREATE TABLE IF NOT EXISTS `".$var['tbl_prefix']."log_items` (
350
                            `id_item` int(8) NOT NULL,
351
                            `date` varchar(50) NOT NULL,
352
                            `id_user` int(8) NOT NULL,
353
                            `action` varchar(250) NULL,
354
                            `raison` text NULL,
355
                            `raison_iv` text NULL,
356
                            `encryption_type` VARCHAR(20) NOT NULL DEFAULT 'not_set'
357
                            ) CHARSET=utf8;"
358
                        );
359
                        // create index
360
                        mysqli_query(
361
                            $dbTmp,
362
                            "CREATE INDEX teampass_log_items_id_item_IDX ON ".$var['tbl_prefix']."log_items (id_item,date);"
363
                        );
364
                    } elseif ($task === "misc") {
365
                        $mysqli_result = mysqli_query(
366
                            $dbTmp,
367
                            "CREATE TABLE IF NOT EXISTS `".$var['tbl_prefix']."misc` (
368
                            `increment_id` int(12) NOT null AUTO_INCREMENT,
369
                            `type` varchar(50) NOT NULL,
370
                            `intitule` varchar(100) NOT NULL,
371
                            `valeur` varchar(500) NOT NULL,
372
                            PRIMARY KEY (`increment_id`)
373
                            ) CHARSET=utf8;"
374
                        );
375
376
                        // include constants
377
                        require_once "../includes/config/include.php";
378
379
                        // prepare config file
380
                        $tp_config_file = "../includes/config/tp.config.php";
381 View Code Duplication
                        if (file_exists($tp_config_file)) {
382
                            if (!copy($tp_config_file, $tp_config_file.'.'.date("Y_m_d", mktime(0, 0, 0, date('m'), date('d'), date('y'))))) {
383
                                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.'"}]';
384
                                break;
385
                            } else {
386
                                unlink($tp_config_file);
387
                            }
388
                        }
389
                        $file_handler = fopen($tp_config_file, 'w');
390
                        $config_text = "<?php
391
global \$SETTINGS;
392
\$SETTINGS = array (";
393
394
                        // add by default settings
395
                        $aMiscVal = array(
396
                            array('admin', 'max_latest_items', '10'),
397
                            array('admin', 'enable_favourites', '1'),
398
                            array('admin', 'show_last_items', '1'),
399
                            array('admin', 'enable_pf_feature', '0'),
400
                            array('admin', 'log_connections', '0'),
401
                            array('admin', 'log_accessed', '1'),
402
                            array('admin', 'time_format', 'H:i:s'),
403
                            array('admin', 'date_format', 'd/m/Y'),
404
                            array('admin', 'duplicate_folder', '0'),
405
                            array('admin', 'item_duplicate_in_same_folder', '0'),
406
                            array('admin', 'duplicate_item', '0'),
407
                            array('admin', 'number_of_used_pw', '3'),
408
                            array('admin', 'manager_edit', '1'),
409
                            array('admin', 'cpassman_dir', $var['abspath']),
410
                            array('admin', 'cpassman_url', $var['url_path']),
411
                            array('admin', 'favicon', $var['url_path'].'/favicon.ico'),
412
                            array('admin', 'path_to_upload_folder', $var['abspath'].'/upload'),
413
                            array('admin', 'url_to_upload_folder', $var['url_path'].'/upload'),
414
                            array('admin', 'path_to_files_folder', $var['abspath'].'/files'),
415
                            array('admin', 'url_to_files_folder', $var['url_path'].'/files'),
416
                            array('admin', 'activate_expiration', '0'),
417
                            array('admin', 'pw_life_duration', '0'),
418
                            array('admin', 'maintenance_mode', '1'),
419
                            array('admin', 'enable_sts', '0'),
420
                            array('admin', 'encryptClientServer', '1'),
421
                            array('admin', 'cpassman_version', $SETTINGS_EXT['version']),
422
                            array('admin', 'ldap_mode', '0'),
423
                            array('admin', 'ldap_type', '0'),
424
                            array('admin', 'ldap_suffix', '0'),
425
                            array('admin', 'ldap_domain_dn', '0'),
426
                            array('admin', 'ldap_domain_controler', '0'),
427
                            array('admin', 'ldap_user_attribute', '0'),
428
                            array('admin', 'ldap_ssl', '0'),
429
                            array('admin', 'ldap_tls', '0'),
430
                            array('admin', 'ldap_elusers', '0'),
431
                            array('admin', 'ldap_search_base', '0'),
432
                            array('admin', 'richtext', '0'),
433
                            array('admin', 'allow_print', '0'),
434
                            array('admin', 'roles_allowed_to_print', '0'),
435
                            array('admin', 'show_description', '1'),
436
                            array('admin', 'anyone_can_modify', '0'),
437
                            array('admin', 'anyone_can_modify_bydefault', '0'),
438
                            array('admin', 'nb_bad_authentication', '0'),
439
                            array('admin', 'utf8_enabled', '1'),
440
                            array('admin', 'restricted_to', '0'),
441
                            array('admin', 'restricted_to_roles', '0'),
442
                            array('admin', 'enable_send_email_on_user_login', '0'),
443
                            array('admin', 'enable_user_can_create_folders', '0'),
444
                            array('admin', 'insert_manual_entry_item_history', '0'),
445
                            array('admin', 'enable_kb', '0'),
446
                            array('admin', 'enable_email_notification_on_item_shown', '0'),
447
                            array('admin', 'enable_email_notification_on_user_pw_change', '0'),
448
                            array('admin', 'custom_logo', ''),
449
                            array('admin', 'custom_login_text', ''),
450
                            array('admin', 'default_language', 'english'),
451
                            array('admin', 'send_stats', '0'),
452
                            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;'),
453
                            array('admin', 'send_stats_time', time() - 2592000),
454
                            array('admin', 'get_tp_info', '1'),
455
                            array('admin', 'send_mail_on_user_login', '0'),
456
                            array('cron', 'sending_emails', '0'),
457
                            array('admin', 'nb_items_by_query', 'auto'),
458
                            array('admin', 'enable_delete_after_consultation', '0'),
459
                            array('admin', 'enable_personal_saltkey_cookie', '0'),
460
                            array('admin', 'personal_saltkey_cookie_duration', '31'),
461
                            array('admin', 'email_smtp_server', ''),
462
                            array('admin', 'email_smtp_auth', ''),
463
                            array('admin', 'email_auth_username', ''),
464
                            array('admin', 'email_auth_pwd', ''),
465
                            array('admin', 'email_port', ''),
466
                            array('admin', 'email_security', ''),
467
                            array('admin', 'email_server_url', ''),
468
                            array('admin', 'email_from', ''),
469
                            array('admin', 'email_from_name', ''),
470
                            array('admin', 'pwd_maximum_length', '40'),
471
                            array('admin', 'google_authentication', '0'),
472
                            array('admin', 'delay_item_edition', '0'),
473
                            array('admin', 'allow_import', '0'),
474
                            array('admin', 'proxy_ip', ''),
475
                            array('admin', 'proxy_port', ''),
476
                            array('admin', 'upload_maxfilesize', '10mb'),
477
                            array('admin', 'upload_docext', 'doc,docx,dotx,xls,xlsx,xltx,rtf,csv,txt,pdf,ppt,pptx,pot,dotx,xltx'),
478
                            array('admin', 'upload_imagesext', 'jpg,jpeg,gif,png'),
479
                            array('admin', 'upload_pkgext', '7z,rar,tar,zip'),
480
                            array('admin', 'upload_otherext', 'sql,xml'),
481
                            array('admin', 'upload_imageresize_options', '1'),
482
                            array('admin', 'upload_imageresize_width', '800'),
483
                            array('admin', 'upload_imageresize_height', '600'),
484
                            array('admin', 'upload_imageresize_quality', '90'),
485
                            array('admin', 'use_md5_password_as_salt', '0'),
486
                            array('admin', 'ga_website_name', 'TeamPass for ChangeMe'),
487
                            array('admin', 'api', '0'),
488
                            array('admin', 'subfolder_rights_as_parent', '0'),
489
                            array('admin', 'show_only_accessible_folders', '0'),
490
                            array('admin', 'enable_suggestion', '0'),
491
                            array('admin', 'otv_expiration_period', '7'),
492
                            array('admin', 'default_session_expiration_time', '60'),
493
                            array('admin', 'duo', '0'),
494
                            array('admin', 'enable_server_password_change', '0'),
495
                            array('admin', 'ldap_object_class', '0'),
496
                            array('admin', 'bck_script_path', $var['abspath']."/backups"),
497
                            array('admin', 'bck_script_filename', 'bck_teampass'),
498
                            array('admin', 'syslog_enable', '0'),
499
                            array('admin', 'syslog_host', 'localhost'),
500
                            array('admin', 'syslog_port', '514'),
501
                            array('admin', 'manager_move_item', '0'),
502
                            array('admin', 'create_item_without_password', '0'),
503
                            array('admin', 'otv_is_enabled', '0'),
504
                            array('admin', 'agses_authentication_enabled', '0'),
505
                            array('admin', 'item_extra_fields', '0'),
506
                            array('admin', 'saltkey_ante_2127', 'none'),
507
                            array('admin', 'migration_to_2127', 'done'),
508
                            array('admin', 'files_with_defuse', 'done'),
509
                            array('admin', 'timezone', 'UTC'),
510
                            array('admin', 'enable_attachment_encryption', '1'),
511
                            array('admin', 'personal_saltkey_security_level', '50'),
512
                            array('admin', 'ldap_new_user_is_administrated_by', '0'),
513
                            array('admin', 'disable_show_forgot_pwd_link', '0')
514
                        );
515
                        foreach ($aMiscVal as $elem) {
516
                            //Check if exists before inserting
517
                            $tmp = mysqli_num_rows(
518
                                mysqli_query(
519
                                    $dbTmp,
520
                                    "SELECT * FROM `".$var['tbl_prefix']."misc`
521
                                    WHERE type='".$elem[0]."' AND intitule='".$elem[1]."'"
522
                                )
523
                            );
524
                            if (intval($tmp) === 0) {
525
                                $queryRes = mysqli_query(
526
                                    $dbTmp,
527
                                    "INSERT INTO `".$var['tbl_prefix']."misc`
528
                                    (`type`, `intitule`, `valeur`) VALUES
529
                                    ('".$elem[0]."', '".$elem[1]."', '".
530
                                    str_replace("'", "", $elem[2])."');"
531
                                ); // 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...
532
                            }
533
534
                            // append new setting in config file
535
                            $config_text .= "
536
    '".$elem[1]."' => '".str_replace("'", "", $elem[2])."',";
537
                        }
538
539
                        // write to config file
540
                        $result = fwrite(
541
                            $file_handler,
542
                            utf8_encode(
543
                                $config_text."
544
);"
545
                            )
546
                        );
547
                        fclose($file_handler);
548
                    } elseif ($task === "nested_tree") {
549
                        $mysqli_result = mysqli_query(
550
                            $dbTmp,
551
                            "CREATE TABLE IF NOT EXISTS `".$var['tbl_prefix']."nested_tree` (
552
                            `id` bigint(20) unsigned NOT null AUTO_INCREMENT,
553
                            `parent_id` int(11) NOT NULL,
554
                            `title` varchar(255) NOT NULL,
555
                            `nleft` int(11) NOT NULL DEFAULT '0',
556
                            `nright` int(11) NOT NULL DEFAULT '0',
557
                            `nlevel` int(11) NOT NULL DEFAULT '0',
558
                            `bloquer_creation` tinyint(1) NOT null DEFAULT '0',
559
                            `bloquer_modification` tinyint(1) NOT null DEFAULT '0',
560
                            `personal_folder` tinyint(1) NOT null DEFAULT '0',
561
                            `renewal_period` TINYINT(4) NOT null DEFAULT '0',
562
                            PRIMARY KEY (`id`),
563
                            KEY `nested_tree_parent_id` (`parent_id`),
564
                            KEY `nested_tree_nleft` (`nleft`),
565
                            KEY `nested_tree_nright` (`nright`),
566
                            KEY `nested_tree_nlevel` (`nlevel`),
567
                            KEY `personal_folder_idx` (`personal_folder`)
568
                            ) CHARSET=utf8;"
569
                        );
570
                    } elseif ($task === "rights") {
571
                        $mysqli_result = mysqli_query(
572
                            $dbTmp,
573
                            "CREATE TABLE IF NOT EXISTS `".$var['tbl_prefix']."rights` (
574
                            `id` int(12) NOT null AUTO_INCREMENT,
575
                            `tree_id` int(12) NOT NULL,
576
                            `fonction_id` int(12) NOT NULL,
577
                            `authorized` tinyint(1) NOT null DEFAULT '0',
578
                            PRIMARY KEY (`id`)
579
                            ) CHARSET=utf8;"
580
                        );
581
                    } elseif ($task === "users") {
582
                        $mysqli_result = mysqli_query(
583
                            $dbTmp,
584
                            "CREATE TABLE IF NOT EXISTS `".$var['tbl_prefix']."users` (
585
                            `id` int(12) NOT null AUTO_INCREMENT,
586
                            `login` varchar(50) NOT NULL,
587
                            `pw` varchar(400) NOT NULL,
588
                            `groupes_visibles` varchar(250) NOT NULL,
589
                            `derniers` text NULL,
590
                            `key_tempo` varchar(100) NULL,
591
                            `last_pw_change` varchar(30) NULL,
592
                            `last_pw` text NULL,
593
                            `admin` tinyint(1) NOT null DEFAULT '0',
594
                            `fonction_id` varchar(255) NULL,
595
                            `groupes_interdits` varchar(255) NULL,
596
                            `last_connexion` varchar(30) NULL,
597
                            `gestionnaire` int(11) NOT null DEFAULT '0',
598
                            `email` varchar(300) NOT NULL DEFAULT 'none',
599
                            `favourites` varchar(300) NULL,
600
                            `latest_items` varchar(300) NULL,
601
                            `personal_folder` int(1) NOT null DEFAULT '0',
602
                            `disabled` tinyint(1) NOT null DEFAULT '0',
603
                            `no_bad_attempts` tinyint(1) NOT null DEFAULT '0',
604
                            `can_create_root_folder` tinyint(1) NOT null DEFAULT '0',
605
                            `read_only` tinyint(1) NOT null DEFAULT '0',
606
                            `timestamp` varchar(30) NOT null DEFAULT '0',
607
                            `user_language` varchar(50) NOT null DEFAULT '0',
608
                            `name` varchar(100) NULL,
609
                            `lastname` varchar(100) NULL,
610
                            `session_end` varchar(30) NULL,
611
                            `isAdministratedByRole` tinyint(5) NOT null DEFAULT '0',
612
                            `psk` varchar(400) NULL,
613
                            `ga` varchar(50) NULL,
614
                            `ga_temporary_code` VARCHAR(20) NOT NULL DEFAULT 'none',
615
                            `avatar` varchar(255) NULL,
616
                            `avatar_thumb` varchar(255) NULL,
617
                            `upgrade_needed` BOOLEAN NOT NULL DEFAULT FALSE,
618
                            `treeloadstrategy` varchar(30) NOT null DEFAULT 'full',
619
                            `can_manage_all_users` tinyint(1) NOT NULL DEFAULT '0',
620
                            `usertimezone` VARCHAR(50) NOT NULL DEFAULT 'not_defined',
621
                            `agses-usercardid` VARCHAR(50) NOT NULL DEFAULT '0',
622
                            `encrypted_psk` text NULL,
623
                            `user_ip` varchar(400) NOT null DEFAULT 'none',
624
                            PRIMARY KEY (`id`),
625
                            UNIQUE KEY `login` (`login`)
626
                            ) CHARSET=utf8;"
627
                        );
628
629
                        require_once "../includes/config/include.php";
630
                        // check that admin accounts doesn't exist
631
                        $tmp = mysqli_num_rows(mysqli_query($dbTmp, "SELECT * FROM `".$var['tbl_prefix']."users` WHERE login = 'admin'"));
632
                        if ($tmp === 0) {
633
                            $mysqli_result = mysqli_query(
634
                                $dbTmp,
635
                                "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()."')"
636
                            );
637
                        } else {
638
                            $mysqli_result = mysqli_query($dbTmp, "UPDATE `".$var['tbl_prefix']."users` SET `pw` = '".bCrypt($var['admin_pwd'], '13')."' WHERE login = 'admin' AND id = '1'");
639
                        }
640
641
                        // check that API doesn't exist
642
                        $tmp = mysqli_num_rows(mysqli_query($dbTmp, "SELECT * FROM `".$var['tbl_prefix']."users` WHERE id = '".API_USER_ID."'"));
643
                        if ($tmp === 0) {
644
                            $mysqli_result = mysqli_query(
645
                                $dbTmp,
646
                                "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')"
647
                            );
648
                        }
649
650
                        // check that OTV doesn't exist
651
                        $tmp = mysqli_num_rows(mysqli_query($dbTmp, "SELECT * FROM `".$var['tbl_prefix']."users` WHERE id = '".OTV_USER_ID."'"));
652
                        if ($tmp === 0) {
653
                            $mysqli_result = mysqli_query(
654
                                $dbTmp,
655
                                "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')"
656
                            );
657
                        }
658
                    } elseif ($task === "tags") {
659
                        $mysqli_result = mysqli_query(
660
                            $dbTmp,
661
                            "CREATE TABLE IF NOT EXISTS `".$var['tbl_prefix']."tags` (
662
                            `id` int(12) NOT null AUTO_INCREMENT,
663
                            `tag` varchar(30) NOT NULL,
664
                            `item_id` int(12) NOT NULL,
665
                            PRIMARY KEY (`id`)
666
                            ) CHARSET=utf8;"
667
                        );
668
                    } elseif ($task === "log_system") {
669
                        $mysqli_result = mysqli_query(
670
                            $dbTmp,
671
                            "CREATE TABLE IF NOT EXISTS `".$var['tbl_prefix']."log_system` (
672
                            `id` int(12) NOT null AUTO_INCREMENT,
673
                            `type` varchar(20) NOT NULL,
674
                            `date` varchar(30) NOT NULL,
675
                            `label` text NOT NULL,
676
                            `qui` varchar(255) NOT NULL,
677
                            `field_1` varchar(250) DEFAULT NULL,
678
                            PRIMARY KEY (`id`)
679
                            ) CHARSET=utf8;"
680
                        );
681
                    } elseif ($task === "files") {
682
                        $mysqli_result = mysqli_query(
683
                            $dbTmp,
684
                            "CREATE TABLE IF NOT EXISTS `".$var['tbl_prefix']."files` (
685
                            `id` int(11) NOT null AUTO_INCREMENT,
686
                            `id_item` int(11) NOT NULL,
687
                            `name` varchar(100) NOT NULL,
688
                            `size` int(10) NOT NULL,
689
                            `extension` varchar(10) NOT NULL,
690
                            `type` varchar(255) NOT NULL,
691
                            `file` varchar(50) NOT NULL,
692
                            `status` varchar(50) NOT NULL DEFAULT '0',
693
                            PRIMARY KEY (`id`)
694
                           ) CHARSET=utf8;"
695
                        );
696
                    } elseif ($task === "cache") {
697
                        $mysqli_result = mysqli_query(
698
                            $dbTmp,
699
                            "CREATE TABLE IF NOT EXISTS `".$var['tbl_prefix']."cache` (
700
                            `id` int(12) NOT NULL,
701
                            `label` varchar(500) NOT NULL,
702
                            `description` text NOT NULL,
703
                            `tags` text DEFAULT NULL,
704
                            `id_tree` int(12) NOT NULL,
705
                            `perso` tinyint(1) NOT NULL,
706
                            `restricted_to` varchar(200) DEFAULT NULL,
707
                            `login` varchar(200) DEFAULT NULL,
708
                            `folder` varchar(300) NOT NULL,
709
                            `author` varchar(50) NOT NULL,
710
                            `renewal_period` tinyint(4) NOT NULL DEFAULT '0',
711
                            `timestamp` varchar(50) DEFAULT NULL,
712
                            `url` varchar(500) NOT NULL DEFAULT '0',
713
                            `encryption_type` VARCHAR(50) DEFAULT NULL DEFAULT '0'
714
                            ) CHARSET=utf8;"
715
                        );
716
                    } elseif ($task === "roles_title") {
717
                        $mysqli_result = mysqli_query(
718
                            $dbTmp,
719
                            "CREATE TABLE IF NOT EXISTS `".$var['tbl_prefix']."roles_title` (
720
                            `id` int(12) NOT null AUTO_INCREMENT,
721
                            `title` varchar(50) NOT NULL,
722
                            `allow_pw_change` TINYINT(1) NOT null DEFAULT '0',
723
                            `complexity` INT(5) NOT null DEFAULT '0',
724
                            `creator_id` int(11) NOT null DEFAULT '0',
725
                            PRIMARY KEY (`id`)
726
                            ) CHARSET=utf8;"
727
                        );
728
                    } elseif ($task === "roles_values") {
729
                        $mysqli_result = mysqli_query(
730
                            $dbTmp,
731
                            "CREATE TABLE IF NOT EXISTS `".$var['tbl_prefix']."roles_values` (
732
                            `role_id` int(12) NOT NULL,
733
                            `folder_id` int(12) NOT NULL,
734
                            `type` varchar(5) NOT NULL DEFAULT 'R',
735
                            KEY `role_id_idx` (`role_id`)
736
                            ) CHARSET=utf8;"
737
                        );
738
                    } elseif ($task === "kb") {
739
                        $mysqli_result = mysqli_query(
740
                            $dbTmp,
741
                            "CREATE TABLE IF NOT EXISTS `".$var['tbl_prefix']."kb` (
742
                            `id` int(12) NOT null AUTO_INCREMENT,
743
                            `category_id` int(12) NOT NULL,
744
                            `label` varchar(200) NOT NULL,
745
                            `description` text NOT NULL,
746
                            `author_id` int(12) NOT NULL,
747
                            `anyone_can_modify` tinyint(1) NOT null DEFAULT '0',
748
                            PRIMARY KEY (`id`)
749
                            ) CHARSET=utf8;"
750
                        );
751
                    } elseif ($task === "kb_categories") {
752
                        $mysqli_result = mysqli_query(
753
                            $dbTmp,
754
                            "CREATE TABLE IF NOT EXISTS `".$var['tbl_prefix']."kb_categories` (
755
                            `id` int(12) NOT null AUTO_INCREMENT,
756
                            `category` varchar(50) NOT NULL,
757
                            PRIMARY KEY (`id`)
758
                            ) CHARSET=utf8;"
759
                        );
760
                    } elseif ($task === "kb_items") {
761
                        $mysqli_result = mysqli_query(
762
                            $dbTmp,
763
                            "CREATE TABLE IF NOT EXISTS `".$var['tbl_prefix']."kb_items` (
764
                            `kb_id` int(12) NOT NULL,
765
                            `item_id` int(12) NOT NULL
766
                           ) CHARSET=utf8;"
767
                        );
768
                    } elseif ($task == "restriction_to_roles") {
769
                        $mysqli_result = mysqli_query(
770
                            $dbTmp,
771
                            "CREATE TABLE IF NOT EXISTS `".$var['tbl_prefix']."restriction_to_roles` (
772
                            `role_id` int(12) NOT NULL,
773
                            `item_id` int(12) NOT NULL,
774
                            KEY `role_id_idx`  (`role_id`)
775
                            ) CHARSET=utf8;"
776
                        );
777
                    } elseif ($task === "languages") {
778
                        $mysqli_result = mysqli_query(
779
                            $dbTmp,
780
                            "CREATE TABLE IF NOT EXISTS `".$var['tbl_prefix']."languages` (
781
                            `id` INT(10) NOT null AUTO_INCREMENT PRIMARY KEY ,
782
                            `name` VARCHAR(50) NOT null ,
783
                            `label` VARCHAR(50) NOT null ,
784
                            `code` VARCHAR(10) NOT null ,
785
                            `flag` VARCHAR(30) NOT NULL
786
                            ) CHARSET=utf8;"
787
                        );
788
789
                        // add lanaguages
790
                        $tmp = mysqli_num_rows(mysqli_query($dbTmp, "SELECT * FROM `".$var['tbl_prefix']."languages` WHERE name = 'french'"));
791
                        if ($tmp[0] == 0) {
792
                            $mysql_result = mysqli_query(
793
                                $dbTmp,
794
                                "INSERT INTO `".$var['tbl_prefix']."languages` (`name`, `label`, `code`, `flag`) VALUES
795
                                ('french', 'French' , 'fr', 'fr.png'),
796
                                ('english', 'English' , 'us', 'us.png'),
797
                                ('spanish', 'Spanish' , 'es', 'es.png'),
798
                                ('german', 'German' , 'de', 'de.png'),
799
                                ('czech', 'Czech' , 'cz', 'cz.png'),
800
                                ('italian', 'Italian' , 'it', 'it.png'),
801
                                ('russian', 'Russian' , 'ru', 'ru.png'),
802
                                ('turkish', 'Turkish' , 'tr', 'tr.png'),
803
                                ('norwegian', 'Norwegian' , 'no', 'no.png'),
804
                                ('japanese', 'Japanese' , 'ja', 'ja.png'),
805
                                ('portuguese', 'Portuguese' , 'pr', 'pr.png'),
806
                                ('portuguese_br', 'Portuguese (Brazil)' , 'pr-bt', 'pr-bt.png'),
807
                                ('chinese', 'Chinese' , 'cn', 'cn.png'),
808
                                ('swedish', 'Swedish' , 'se', 'se.png'),
809
                                ('dutch', 'Dutch' , 'nl', 'nl.png'),
810
                                ('catalan', 'Catalan' , 'ct', 'ct.png'),
811
                                ('vietnamese', 'Vietnamese' , 'vi', 'vi.png'),
812
                                ('estonian', 'Estonian' , 'ee', 'ee.png');"
813
                            );
814
                        }
815
                    } elseif ($task === "emails") {
816
                        $mysqli_result = mysqli_query(
817
                            $dbTmp,
818
                            "CREATE TABLE IF NOT EXISTS `".$var['tbl_prefix']."emails` (
819
                            `timestamp` INT(30) NOT null ,
820
                            `subject` VARCHAR(255) NOT null ,
821
                            `body` TEXT NOT null ,
822
                            `receivers` VARCHAR(255) NOT null ,
823
                            `status` VARCHAR(30) NOT NULL
824
                            ) CHARSET=utf8;"
825
                        );
826
                    } elseif ($task === "automatic_del") {
827
                        $mysqli_result = mysqli_query(
828
                            $dbTmp,
829
                            "CREATE TABLE IF NOT EXISTS `".$var['tbl_prefix']."automatic_del` (
830
                            `item_id` int(11) NOT NULL,
831
                            `del_enabled` tinyint(1) NOT NULL,
832
                            `del_type` tinyint(1) NOT NULL,
833
                            `del_value` varchar(35) NOT NULL
834
                            ) CHARSET=utf8;"
835
                        );
836
                    } elseif ($task === "items_edition") {
837
                        $mysqli_result = mysqli_query(
838
                            $dbTmp,
839
                            "CREATE TABLE IF NOT EXISTS `".$var['tbl_prefix']."items_edition` (
840
                            `item_id` int(11) NOT NULL,
841
                            `user_id` int(12) NOT NULL,
842
                            `timestamp` varchar(50) NOT NULL
843
                            ) CHARSET=utf8;"
844
                        );
845
                    } elseif ($task === "categories") {
846
                        $mysqli_result = mysqli_query(
847
                            $dbTmp,
848
                            "CREATE TABLE IF NOT EXISTS `".$var['tbl_prefix']."categories` (
849
                            `id` int(12) NOT NULL AUTO_INCREMENT,
850
                            `parent_id` int(12) NOT NULL,
851
                            `title` varchar(255) NOT NULL,
852
                            `level` int(2) NOT NULL,
853
                            `description` text NULL,
854
                            `type` varchar(50) NULL default '',
855
                            `order` int(12) NOT NULL default '0',
856
                            `encrypted_data` tinyint(1) NOT NULL default '1',
857
                            PRIMARY KEY (`id`)
858
                            ) CHARSET=utf8;"
859
                        );
860
                    } elseif ($task === "categories_items") {
861
                        $mysqli_result = mysqli_query(
862
                            $dbTmp,
863
                            "CREATE TABLE IF NOT EXISTS `".$var['tbl_prefix']."categories_items` (
864
                            `id` int(12) NOT NULL AUTO_INCREMENT,
865
                            `field_id` int(11) NOT NULL,
866
                            `item_id` int(11) NOT NULL,
867
                            `data` text NOT NULL,
868
                            `data_iv` text NOT NULL,
869
                            `encryption_type` VARCHAR(20) NOT NULL DEFAULT 'not_set',
870
                            PRIMARY KEY (`id`)
871
                            ) CHARSET=utf8;"
872
                        );
873
                    } elseif ($task === "categories_folders") {
874
                        $mysqli_result = mysqli_query(
875
                            $dbTmp,
876
                            "CREATE TABLE IF NOT EXISTS `".$var['tbl_prefix']."categories_folders` (
877
                            `id_category` int(12) NOT NULL,
878
                            `id_folder` int(12) NOT NULL
879
                            ) CHARSET=utf8;"
880
                        );
881
                    } elseif ($task === "api") {
882
                        $mysqli_result = mysqli_query(
883
                            $dbTmp,
884
                            "CREATE TABLE IF NOT EXISTS `".$var['tbl_prefix']."api` (
885
                            `id` int(20) NOT NULL AUTO_INCREMENT,
886
                            `type` varchar(15) NOT NULL,
887
                            `label` varchar(255) NOT NULL,
888
                            `value` varchar(255) NOT NULL,
889
                            `timestamp` varchar(50) NOT NULL,
890
                            PRIMARY KEY (`id`)
891
                            ) CHARSET=utf8;"
892
                        );
893
                    } elseif ($task === "otv") {
894
                        $mysqli_result = mysqli_query(
895
                            $dbTmp,
896
                            "CREATE TABLE IF NOT EXISTS `".$var['tbl_prefix']."otv` (
897
                            `id` int(10) NOT NULL AUTO_INCREMENT,
898
                            `timestamp` text NOT NULL,
899
                            `code` varchar(100) NOT NULL,
900
                            `item_id` int(12) NOT NULL,
901
                            `originator` int(12) NOT NULL,
902
                            PRIMARY KEY (`id`)
903
                            ) CHARSET=utf8;"
904
                        );
905
                    } elseif ($task === "suggestion") {
906
                        $mysqli_result = mysqli_query(
907
                            $dbTmp,
908
                            "CREATE TABLE IF NOT EXISTS `".$var['tbl_prefix']."suggestion` (
909
                            `id` tinyint(12) NOT NULL AUTO_INCREMENT,
910
                            `label` varchar(255) NOT NULL,
911
                            `pw` text NOT NULL,
912
                            `pw_iv` text NOT NULL,
913
                            `pw_len` int(5) NOT NULL,
914
                            `description` text NOT NULL,
915
                            `author_id` int(12) NOT NULL,
916
                            `folder_id` int(12) NOT NULL,
917
                            `comment` text NOT NULL,
918
                            `suggestion_type` varchar(10) NOT NULL default 'new',
919
                            PRIMARY KEY (`id`)
920
                            ) CHARSET=utf8;"
921
                        );
922
923
                        $mysqli_result = mysqli_query(
924
                            $dbTmp,
925
                            "CREATE TABLE IF NOT EXISTS `".$var['tbl_prefix']."export` (
926
                            `id` int(12) NOT NULL,
927
                            `label` varchar(500) NOT NULL,
928
                            `login` varchar(100) NOT NULL,
929
                            `description` text NOT NULL,
930
                            `pw` text NOT NULL,
931
                            `path` varchar(500) NOT NULL,
932
                            `email` varchar(500) NOT NULL default 'none',
933
                            `url` varchar(500) NOT NULL default 'none',
934
                            `kbs` varchar(500) NOT NULL default 'none',
935
                            `tags` varchar(500) NOT NULL default 'none'
936
                            ) CHARSET=utf8;"
937
                        );
938
                    } elseif ($task === "tokens") {
939
                        $mysqli_result = mysqli_query(
940
                            $dbTmp,
941
                            "CREATE TABLE IF NOT EXISTS `".$var['tbl_prefix']."tokens` (
942
                            `id` int(12) NOT NULL AUTO_INCREMENT,
943
                            `user_id` int(12) NOT NULL,
944
                            `token` varchar(255) NOT NULL,
945
                            `reason` varchar(255) NOT NULL,
946
                            `creation_timestamp` varchar(50) NOT NULL,
947
                            `end_timestamp` varchar(50) NOT NULL,
948
                            PRIMARY KEY (`id`)
949
                            ) CHARSET=utf8;"
950
                        );
951
                    } elseif ($task === "items_change") {
952
                        $mysqli_result = mysqli_query(
953
                            $dbTmp,
954
                            "CREATE TABLE IF NOT EXISTS `".$var['tbl_prefix']."items_change` (
955
                            `id` int(12) NOT NULL AUTO_INCREMENT,
956
                            `item_id` int(12) NOT NULL,
957
                            `label` varchar(255) NOT NULL DEFAULT 'none',
958
                            `pw` text NOT NULL,
959
                            `login` varchar(255) NOT NULL DEFAULT 'none',
960
                            `email` varchar(255) NOT NULL DEFAULT 'none',
961
                            `url` varchar(255) NOT NULL DEFAULT 'none',
962
                            `description` text NOT NULL,
963
                            `comment` text NOT NULL,
964
                            `folder_id` tinyint(12) NOT NULL,
965
                            `user_id` int(12) NOT NULL,
966
                            `timestamp` varchar(50) NOT NULL DEFAULT 'none',
967
                            PRIMARY KEY (`id`)
968
                            ) CHARSET=utf8;"
969
                        );
970
                    }
971
                }
972
                // answer back
973
                if ($mysqli_result) {
974
                    echo '[{"error" : "", "index" : "'.$post_index.'", "multiple" : "'.$post_multiple.'", "task" : "'.$task.'", "activity" : "'.$activity.'"}]';
975
                } else {
976
                    echo '[{"error" : "'.addslashes(str_replace(array("'", "\n", "\r"), array('"', '', ''), mysqli_error())).'", "index" : "'.$post_index.'", "multiple" : "'.$post_multiple.'", "table" : "'.$task.'"}]';
977
                }
978 View Code Duplication
            } else {
979
                echo '[{"error" : "'.addslashes(str_replace(array("'", "\n", "\r"), array('"', '', ''), mysqli_connect_error())).'", "result" : "Failed", "multiple" : ""}]';
980
            }
981
982
            mysqli_close($dbTmp);
983
            // Destroy session without writing to disk
984
            define('NODESTROY_SESSION', 'true');
985
            session_destroy();
986
            break;
987
988
        case "step_6":
989
            //decrypt
990
            require_once 'libs/aesctr.php'; // AES Counter Mode implementation
991
            $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...
992
            $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...
993
            $data_sent = json_decode($data_sent, true);
994
            $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...
995
            $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...
996
            $db = json_decode($json, true);
997
998
            $dbTmp = mysqli_connect(
999
                $db['db_host'],
1000
                $db['db_login'],
1001
                $db['db_pw'],
1002
                $db['db_bdd'],
1003
                $db['db_port']
1004
            );
1005
1006
            // read install variables
1007
            $result = mysqli_query($dbTmp, "SELECT * FROM `_install`");
1008
            while ($row = $result->fetch_array()) {
1009
                $var[$row[0]] = $row[1];
1010
            }
1011
1012
            // launch
1013
            if (empty($var['sk_path'])) {
1014
                $skFile = $var['abspath'].'/includes/sk.php';
1015
                $securePath = $var['abspath'];
1016
            } else {
1017
                //ensure $var['sk_path'] has no trailing slash
1018
                $var['sk_path'] = rtrim($var['sk_path'], '/\\');
1019
                $skFile = $var['sk_path'].'/sk.php';
1020
                $securePath = $var['sk_path'];
1021
            }
1022
1023
            $events = "";
1024
1025
            if ($activity === "file") {
1026
                if ($task === "settings.php") {
1027
                    // first is to create teampass-seckey.txt
1028
                    // 0- check if exists
1029
                    $filename_seckey = $securePath."/teampass-seckey.txt";
1030
1031 View Code Duplication
                    if (file_exists($filename_seckey)) {
1032
                        if (!copy($filename_seckey, $filename_seckey.'.'.date("Y_m_d", mktime(0, 0, 0, date('m'), date('d'), date('y'))))) {
1033
                            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.'"}]';
1034
                            break;
1035
                        } else {
1036
                            unlink($filename);
1037
                        }
1038
                    }
1039
1040
                    // 1- generate saltkey
1041
                    require_once '../includes/libraries/Encryption/Encryption/Crypto.php';
1042
                    require_once '../includes/libraries/Encryption/Encryption/Encoding.php';
1043
                    require_once '../includes/libraries/Encryption/Encryption/DerivedKeys.php';
1044
                    require_once '../includes/libraries/Encryption/Encryption/Key.php';
1045
                    require_once '../includes/libraries/Encryption/Encryption/KeyOrPassword.php';
1046
                    require_once '../includes/libraries/Encryption/Encryption/File.php';
1047
                    require_once '../includes/libraries/Encryption/Encryption/RuntimeTests.php';
1048
                    require_once '../includes/libraries/Encryption/Encryption/KeyProtectedByPassword.php';
1049
                    require_once '../includes/libraries/Encryption/Encryption/Core.php';
1050
1051
                    $key = \Defuse\Crypto\Key::createNewRandomKey();
1052
                    $new_salt = $key->saveToAsciiSafeString();
1053
1054
                    // 2- store key in file
1055
                    file_put_contents(
1056
                        $filename_seckey,
1057
                        $new_salt
1058
                    );
1059
1060
                    // Now create settings file
1061
                    $filename = "../includes/config/settings.php";
1062
1063 View Code Duplication
                    if (file_exists($filename)) {
1064
                        if (!copy($filename, $filename.'.'.date("Y_m_d", mktime(0, 0, 0, date('m'), date('d'), date('y'))))) {
1065
                            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.'"}]';
1066
                            break;
1067
                        } else {
1068
                            unlink($filename);
1069
                        }
1070
                    }
1071
1072
                    // Encrypt the DB password
1073
                    $encrypted_text = encryptFollowingDefuse(
1074
                        $db['db_pw'],
1075
                        $new_salt
1076
                    )['string'];
1077
1078
                    // Open and write Settings file
1079
                    $file_handler = fopen($filename, 'w');
1080
                    $result = fwrite(
1081
                        $file_handler,
1082
                        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 1083

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