Completed
Push — development ( a62382...1718fc )
by Nils
17:49 queued 04:38
created

install.queries.php ➔ chmodRecursive()   D

Complexity

Conditions 9
Paths 13

Size

Total Lines 30
Code Lines 19

Duplication

Lines 30
Ratio 100 %

Importance

Changes 0
Metric Value
cc 9
eloc 19
nc 13
nop 3
dl 30
loc 30
rs 4.909
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 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 1170

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

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
                    PRIMARY KEY (`key`)
217
                    ) CHARSET=utf8;"
218
                );
219
                // store values
220 View Code Duplication
                foreach ($data as $key => $value) {
221
                    $superGlobal->put($key, $value, "SESSION");
222
                    $tmp = mysqli_num_rows(mysqli_query($dbTmp, "SELECT * FROM `_install` WHERE `key` = '".$key."'"));
223
                    if (intval($tmp) === 0) {
224
                        mysqli_query($dbTmp, "INSERT INTO `_install` (`key`, `value`) VALUES ('".$key."', '".$value."');");
225
                    } else {
226
                        mysqli_query($dbTmp, "UPDATE `_install` SET `value` = '".$value."' WHERE `key` = '".$key."';");
227
                    }
228
                }
229
                $tmp = mysqli_num_rows(mysqli_query($dbTmp, "SELECT * FROM `_install` WHERE `key` = 'url_path'"));
230 View Code Duplication
                if (intval($tmp) === 0) {
231
                    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...
232
                } else {
233
                    mysqli_query($dbTmp, "UPDATE `_install` SET `value` = '", empty($session_url_path) ? $db['url_path'] : $session_url_path, "' WHERE `key` = 'url_path';");
234
                }
235
                $tmp = mysqli_num_rows(mysqli_query($dbTmp, "SELECT * FROM `_install` WHERE `key` = 'abspath'"));
236 View Code Duplication
                if (intval($tmp) === 0) {
237
                    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...
238
                } else {
239
                    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...
240
                }
241
242
                echo '[{"error" : "", "result" : "Connection is successful", "multiple" : ""}]';
243 View Code Duplication
            } else {
244
                echo '[{"error" : "'.addslashes(str_replace(array("'", "\n", "\r"), array('"', '', ''), mysqli_connect_error())).'", "result" : "Failed", "multiple" : ""}]';
245
            }
246
            mysqli_close($dbTmp);
247
            break;
248
249
        case "step_4":
250
            //decrypt
251
            require_once 'libs/aesctr.php'; // AES Counter Mode implementation
252
            $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...
253
            $data = json_decode($json, true);
254
            $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...
255
            $db = json_decode($json, true);
256
257
            $dbTmp = mysqli_connect($db['db_host'], $db['db_login'], $db['db_pw'], $db['db_bdd'], $db['db_port']);
258
259
            // prepare data
260
            foreach ($data as $key => $value) {
261
                $data[$key] = str_replace(array('&quot;', '&#92;'), array('""', '\\\\'), $value);
262
            }
263
264
            // check skpath
265
            if (empty($data['sk_path'])) {
266
                $data['sk_path'] = $session_abspath."/includes";
267
            } else {
268
                $data['sk_path'] = str_replace("&#92;", "/", $data['sk_path']);
269
            }
270
            if (substr($data['sk_path'], strlen($data['sk_path']) - 1) == "/" || substr($data['sk_path'], strlen($data['sk_path']) - 1) == "\"") {
271
                $data['sk_path'] = substr($data['sk_path'], 0, strlen($data['sk_path']) - 1);
272
            }
273
            if (is_dir($data['sk_path'])) {
274
                if (is_writable($data['sk_path'])) {
275
                    // store all variables in SESSION
276 View Code Duplication
                    foreach ($data as $key => $value) {
277
                        $superGlobal->put($key, $value, "SESSION");
278
                        $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 266
  4. $key is assigned
    in install/install.queries.php on line 276

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...
279
                        if (intval($tmp) === 0) {
280
                            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 266
  4. $key is assigned
    in install/install.queries.php on line 276

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...
281
                        } else {
282
                            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 266
  4. $value is assigned
    in install/install.queries.php on line 276

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...
283
                        }
284
                    }
285
                    echo '[{"error" : "", "result" : "Information stored", "multiple" : ""}]';
286
                } else {
287
                    echo '[{"error" : "The Directory must be writable!", "result" : "Information stored", "multiple" : ""}]';
288
                }
289
            } else {
290
                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 266

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

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