From ded27ce411c22468448496ff6868b124773860cb Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Jos=C3=A9=20Gonz=C3=A1lez?= <jose.gonzalez@pandorafms.com>
Date: Tue, 28 Jun 2022 17:24:22 +0200
Subject: [PATCH] Backend changes

---
 pandora_console/include/api.php             | 30 ++++---
 pandora_console/include/auth/mysql.php      | 98 ++++++---------------
 pandora_console/include/functions_api.php   |  6 +-
 pandora_console/include/functions_users.php |  9 +-
 4 files changed, 54 insertions(+), 89 deletions(-)

diff --git a/pandora_console/include/api.php b/pandora_console/include/api.php
index cb3dae8e72..c9672816a8 100644
--- a/pandora_console/include/api.php
+++ b/pandora_console/include/api.php
@@ -14,7 +14,7 @@
  * |___|   |___._|__|__|_____||_____|__| |___._| |___|   |__|_|__|_______|
  *
  * ============================================================================
- * Copyright (c) 2005-2021 Artica Soluciones Tecnologicas
+ * Copyright (c) 2005-2022 Artica Soluciones Tecnologicas
  * Please see http://pandorafms.org for full contribution list
  * This program is free software; you can redistribute it and/or
  * modify it under the terms of the GNU General Public License
@@ -74,6 +74,7 @@ $password = get_parameter('pass', '');
 $user = get_parameter('user', '');
 $info = get_parameter('info', '');
 $raw_decode = (bool) get_parameter('raw_decode', false);
+$apiToken = (string) get_parameter('token');
 
 $other = parseOtherParameter($otherSerialize, $otherMode, $raw_decode);
 $apiPassword = io_output_password(
@@ -84,6 +85,7 @@ $apiPassword = io_output_password(
     )
 );
 
+$apiTokenValid = (isset($_GET['token']) === true && (bool) api_token_check($apiToken));
 $correctLogin = false;
 $no_login_msg = '';
 
@@ -94,8 +96,8 @@ ob_clean();
 // Special call without checks to retrieve version and build of the Pandora FMS
 // This info is avalable from the web console without login
 // Don't change the format, it is parsed by applications.
-if ($info == 'version') {
-    if (!$config['MR']) {
+if ($info === 'version') {
+    if ((bool) $config['MR'] === false) {
         $config['MR'] = 0;
     }
 
@@ -105,6 +107,7 @@ if ($info == 'version') {
 
 if (empty($apiPassword) === true
     || (empty($apiPassword) === false && $api_password === $apiPassword)
+    || $apiTokenValid === true
 ) {
     if (enterprise_hook('metaconsole_validate_origin', [get_parameter('server_auth')]) === true
         || enterprise_hook('console_validate_origin', [get_parameter('server_auth')])  === true
@@ -118,7 +121,14 @@ if (empty($apiPassword) === true
         $correctLogin = true;
     } else if ((bool) isInACL($ipOrigin) === true) {
         // External access.
-        $user_in_db = process_user_login($user, $password, true);
+        // Token is valid. Bypass the credentials.
+        if ($apiTokenValid === true) {
+            $credentials = db_get_row('tusuario', 'api_token', $apiToken);
+            $user = $credentials['id_user'];
+            $password = $credentials['password'];
+        }
+
+        $user_in_db = process_user_login($user, $password, true, $apiTokenValid);
         if ($user_in_db !== false) {
             $config['id_usuario'] = $user_in_db;
             // Compat.
@@ -144,19 +154,19 @@ if (empty($apiPassword) === true
     $no_login_msg = 'Incorrect given API password';
 }
 
-if ($correctLogin) {
+if ($correctLogin === true) {
     if (($op !== 'get') && ($op !== 'set') && ($op !== 'help')) {
         returnError('no_set_no_get_no_help', $returnType);
     } else {
         $function_name = '';
 
         // Check if is an extension function and get the function name.
-        if ($op2 == 'extension') {
+        if ($op2 === 'extension') {
             $extension_api_url = $config['homedir'].'/'.EXTENSIONS_DIR.'/'.$ext_name.'/'.$ext_name.'.api.php';
             // The extension API file must exist and the extension must be
             // enabled.
-            if (file_exists($extension_api_url)
-                && !in_array($ext_name, extensions_get_disabled_extensions())
+            if (file_exists($extension_api_url) === true
+                && in_array($ext_name, extensions_get_disabled_extensions()) === false
             ) {
                 include_once $extension_api_url;
                 $function_name = 'apiextension_'.$op.'_'.$ext_function;
@@ -164,7 +174,7 @@ if ($correctLogin) {
         } else {
             $function_name = 'api_'.$op.'_'.$op2;
 
-            if ($op == 'set' && $id) {
+            if ($op === 'set' && $id) {
                 switch ($op2) {
                     case 'update_agent':
                     case 'add_module_in_conf':
@@ -173,7 +183,7 @@ if ($correctLogin) {
                         $agent = agents_locate_agent($id);
                         if ($agent !== false) {
                             $id_os = $agent['id_os'];
-                            if ($id_os == 100) {
+                            if ((int) $id_os === 100) {
                                 returnError(
                                     'not_allowed_operation_cluster',
                                     $returnType
diff --git a/pandora_console/include/auth/mysql.php b/pandora_console/include/auth/mysql.php
index 67053ab0be..48e0145c4a 100644
--- a/pandora_console/include/auth/mysql.php
+++ b/pandora_console/include/auth/mysql.php
@@ -78,7 +78,7 @@ $config['admin_can_make_admin'] = true;
  * @return mixed False in case of error or invalid credentials, the username in
  * case it's correct.
  */
-function process_user_login($login, $pass, $api=false)
+function process_user_login($login, $pass, $api=false, $passAlreadyEncrypted=false)
 {
     global $config;
 
@@ -114,10 +114,10 @@ function process_user_login($login, $pass, $api=false)
         if ($config['fallback_local_auth']
             || is_user_admin($login)
             || $local_user === true
-            || strtolower($config['auth']) == 'mysql'
+            || strtolower($config['auth']) === 'mysql'
             || (bool) $user_not_login === true
         ) {
-            return process_user_login_local($login, $pass, $api);
+            return process_user_login_local($login, $pass, $api, $passAlreadyEncrypted);
         } else {
             return false;
         }
@@ -128,88 +128,44 @@ function process_user_login($login, $pass, $api=false)
 }
 
 
-function process_user_login_local($login, $pass, $api=false)
+function process_user_login_local($login, $pass, $api=false, $passAlreadyEncrypted=false)
 {
     global $config, $mysql_cache;
 
-    // Connect to Database
-    switch ($config['dbtype']) {
-        case 'mysql':
-            if (!$api) {
-                $sql = sprintf(
-                    "SELECT `id_user`, `password`
-					FROM `tusuario`
-					WHERE `id_user` = '%s' AND `not_login` = 0
-						AND `disabled` = 0",
-                    $login
-                );
-            } else {
-                $sql = sprintf(
-                    "SELECT `id_user`, `password`
-					FROM `tusuario`
-					WHERE `id_user` = '%s'
-						AND `disabled` = 0",
-                    $login
-                );
-            }
-        break;
-
-        case 'postgresql':
-            if (!$api) {
-                $sql = sprintf(
-                    'SELECT "id_user", "password"
-					FROM "tusuario"
-					WHERE "id_user" = \'%s\' AND "not_login" = 0
-						AND "disabled" = 0',
-                    $login
-                );
-            } else {
-                $sql = sprintf(
-                    'SELECT "id_user", "password"
-					FROM "tusuario"
-					WHERE "id_user" = \'%s\'
-						AND "disabled" = 0',
-                    $login
-                );
-            }
-        break;
-
-        case 'oracle':
-            if (!$api) {
-                $sql = sprintf(
-                    'SELECT id_user, password
-					FROM tusuario
-					WHERE id_user = \'%s\' AND not_login = 0
-						AND disabled = 0',
-                    $login
-                );
-            } else {
-                $sql = sprintf(
-                    'SELECT id_user, password
-					FROM tusuario
-					WHERE id_user = \'%s\'
-						AND disabled = 0',
-                    $login
-                );
-            }
-        break;
+    if ($api === false) {
+        $sql = sprintf(
+            "SELECT `id_user`, `password`
+            FROM `tusuario`
+            WHERE `id_user` = '%s' AND `not_login` = 0
+                AND `disabled` = 0",
+            $login
+        );
+    } else {
+        $sql = sprintf(
+            "SELECT `id_user`, `password`
+            FROM `tusuario`
+            WHERE `id_user` = '%s'
+                AND `disabled` = 0",
+            $login
+        );
     }
 
     $row = db_get_row_sql($sql);
 
-    // Check that row exists, that password is not empty and that password is the same hash
-    if ($row !== false && $row['password'] !== md5('')
-        && $row['password'] == md5($pass)
+    // Check that row exists, that password is not empty and that password is the same hash.
+    if (($row !== false && $row['password'] !== md5('')
+        && (string) $row['password'] === md5($pass))
+        || ($passAlreadyEncrypted === true && (string) $row['password'] === (string) $pass)
     ) {
         // Login OK
         // Nick could be uppercase or lowercase (select in MySQL
         // is not case sensitive)
         // We get DB nick to put in PHP Session variable,
         // to avoid problems with case-sensitive usernames.
-        // Thanks to David Muñiz for Bug discovery :)
+        // Thanks to David Muñiz for Bug discovery :).
         $filter = ['id_usuario' => $login];
         $user_profile = db_get_row_filter('tusuario_perfil', $filter);
-        if (!users_is_admin($login) && !$user_profile) {
+        if ((bool) users_is_admin($login) === false && (bool) $user_profile === false) {
             $mysql_cache['auth_error'] = 'User does not have any profile';
             $config['auth_error'] = 'User does not have any profile';
             return false;
@@ -217,7 +173,7 @@ function process_user_login_local($login, $pass, $api=false)
 
         return $row['id_user'];
     } else {
-        if (!user_can_login($login)) {
+        if (user_can_login($login) === false) {
             $mysql_cache['auth_error'] = 'User only can use the API.';
             $config['auth_error'] = 'User only can use the API.';
         } else {
diff --git a/pandora_console/include/functions_api.php b/pandora_console/include/functions_api.php
index 2e7feb5e4c..29aafad983 100644
--- a/pandora_console/include/functions_api.php
+++ b/pandora_console/include/functions_api.php
@@ -17714,13 +17714,13 @@ function api_set_enable_disable_discovery_task($id_task, $thrash2, $other)
  *
  * @param string $token Token for check.
  *
- * @return integer Id of user. If returns 0 there is not valid token.
+ * @return mixed Id of user. If returns 0 there is not valid token.
  */
 function api_token_check(string $token)
 {
     if (empty($token) === true) {
-        return 0;
+        return -1;
     } else {
-        return (int) db_get_value('id_user', 'tusuario', 'api_token', $token);
+        return db_get_value('id_user', 'tusuario', 'api_token', $token);
     }
 }
diff --git a/pandora_console/include/functions_users.php b/pandora_console/include/functions_users.php
index 808e98d5dd..00a18afda5 100755
--- a/pandora_console/include/functions_users.php
+++ b/pandora_console/include/functions_users.php
@@ -886,6 +886,7 @@ function users_get_users_group_by_group($id_group)
  */
 function api_token_generate()
 {
+    include_once 'functions_api.php';
     // Generate a cryptographically secure chain.
     $generateToken = bin2hex(openssl_random_pseudo_bytes(16));
     // Check if token exists in DB.
@@ -898,15 +899,13 @@ function api_token_generate()
 /**
  * Returns User API Token
  *
- * @param integer $idUser Id of the user.
+ * @param string $idUser Id of the user.
  *
  * @return string
  */
-function users_get_API_token(int $idUser)
+function users_get_API_token(string $idUser)
 {
-    $apiToken = db_get_value('api_token', 'tusuario', 'id_user', $idUser);
-
-    return $apiToken;
+    return db_get_value('api_token', 'tusuario', 'id_user', $idUser);
 }