CVE-2022-46169 (published 2022-12-05T21:15Z)

Cacti is an open source platform which provides a robust and extensible operational monitoring and fault management framework for users. In affected versions a command injection vulnerability allows an unauthenticated user to execute arbitrary code on a server running Cacti, if a specific data source was selected for any monitored device. The vulnerability resides in the `remote_agent.php` file. This file can be accessed without authentication. This function retrieves the IP address of the client via `get_client_addr` and resolves this IP address to the corresponding hostname via `gethostbyaddr`. After this, it is verified that an entry within the `poller` table exists, where the hostname corresponds to the resolved hostname. If such an entry was found, the function returns `true` and the client is authorized. This authorization can be bypassed due to the implementation of the `get_client_addr` function. The function is defined in the file `lib/functions.php` and checks serval `$_SERVER` variables to determine the IP address of the client. The variables beginning with `HTTP_` can be arbitrarily set by an attacker. Since there is a default entry in the `poller` table with the hostname of the server running Cacti, an attacker can bypass the authentication e.g. by providing the header `Forwarded-For: <TARGETIP>`. This way the function `get_client_addr` returns the IP address of the server running Cacti. The following call to `gethostbyaddr` will resolve this IP address to the hostname of the server, which will pass the `poller` hostname check because of the default entry. After the authorization of the `remote_agent.php` file is bypassed, an attacker can trigger different actions. One of these actions is called `polldata`. The called function `poll_for_data` retrieves a few request parameters and loads the corresponding `poller_item` entries from the database. If the `action` of a `poller_item` equals `POLLER_ACTION_SCRIPT_PHP`, the function `proc_open` is used to execute a PHP script. The attacker-controlled parameter `$poller_id` is retrieved via the function `get_nfilter_request_var`, which allows arbitrary strings. This variable is later inserted into the string passed to `proc_open`, which leads to a command injection vulnerability. By e.g. providing the `poller_id=;id` the `id` command is executed. In order to reach the vulnerable call, the attacker must provide a `host_id` and `local_data_id`, where the `action` of the corresponding `poller_item` is set to `POLLER_ACTION_SCRIPT_PHP`. Both of these ids (`host_id` and `local_data_id`) can easily be bruteforced. The only requirement is that a `poller_item` with an `POLLER_ACTION_SCRIPT_PHP` action exists. This is very likely on a productive instance because this action is added by some predefined templates like `Device - Uptime` or `Device - Polling Time`.\n\nThis command injection vulnerability allows an unauthenticated user to execute arbitrary commands if a `poller_item` with the `action` type `POLLER_ACTION_SCRIPT_PHP` (`2`) is configured. The authorization bypass should be prevented by not allowing an attacker to make `get_client_addr` (file `lib/functions.php`) return an arbitrary IP address. This could be done by not honoring the `HTTP_...` `$_SERVER` variables. If these should be kept for compatibility reasons it should at least be prevented to fake the IP address of the server running Cacti. This vulnerability has been addressed in both the 1.2.x and 1.3.x release branches with `1.2.23` being the first release containing the patch.

CVSS v3 base score: 9.8, CRITICAL (CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H)

Weakness information:
cwe_id: CWE-78
cwe_name: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')
description: The product constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.
extended_description: 
		   This weakness can lead to a vulnerability in environments in which the attacker does not have direct access to the operating system, such as in web applications. Alternately, if the weakness occurs in a privileged program, it could allow the attacker to specify commands that normally would not be accessible, or to call alternate commands with privileges that the attacker does not have. The problem is exacerbated if the compromised process does not follow the principle of least privilege, because the attacker-controlled commands may run with special system privileges that increases the amount of damage.
            There are at least two subtypes of OS command injection:
               
				 The application intends to execute a single, fixed program that is under its own control. It intends to use externally-supplied inputs as arguments to that program. For example, the program might use system("nslookup [HOSTNAME]") to run nslookup and allow the user to supply a HOSTNAME, which is used as an argument. Attackers cannot prevent nslookup from executing. However, if the program does not remove command separators from the HOSTNAME argument, attackers could place the separators into the arguments, which allows them to execute their own program after nslookup has finished executing.
				 The application accepts an input that it uses to fully select which program to run, as well as which commands to use. The application simply redirects this entire command to the operating system. For example, the program might use "exec([COMMAND])" to execute the [COMMAND] that was supplied by the user. If the COMMAND is under attacker control, then the attacker can execute arbitrary commands or programs. If the command is being executed using functions like exec() and CreateProcess(), the attacker might not be able to combine multiple commands together in the same line.
               
            From a weakness standpoint, these variants represent distinct programmer errors. In the first variant, the programmer clearly intends that input from untrusted parties will be part of the arguments in the command to be executed. In the second variant, the programmer does not intend for the command to be accessible to any untrusted party, but the programmer probably has not accounted for alternate ways in which malicious attackers can provide input.
         
         
cwe_id: CWE-863
cwe_name: Incorrect Authorization
description: The product performs an authorization check when an actor attempts to access a resource or perform an action, but it does not correctly perform the check. This allows attackers to bypass intended access restrictions.
extended_description: 
            Assuming a user with a given identity, authorization is the process of determining whether that user can access a given resource, based on the user's privileges and any permissions or other access-control specifications that apply to the resource.
            When access control checks are incorrectly applied, users are able to access data or perform actions that they should not be allowed to perform. This can lead to a wide range of problems, including information exposures, denial of service, and arbitrary code execution.
         
         

Fix information:
repo_url: https://github.com/Cacti/cacti
commit_details: repo_url: https://github.com/Cacti/cacti
author: Mark Brugnoli-Vinten
author_date: 2022-12-05 08:41:01+00:00
msg: Merge pull request from GHSA-6p93-p743-35gf

* Resolving  CVE-2022-46169

* Provide a restrictive option

* QA: Further restrict allowed headers to those defined in config only

Co-authored-by: TheWitness <thewitness@cacti.net>
repository: repo_url: https://github.com/Cacti/cacti
repo_name: Cacti/cacti
description: Cacti ™
repo_language: PHP
owner: Cacti
file_changes: filename: CHANGELOG
change_type: ModificationType.MODIFY
diff: @@ -46,6 +46,7 @@ Cacti CHANGELOG
 
 1.2.23
 -security#4920: Add .htaccess file to scripts folder
+-security#XXXX: CVE-2022-46169 Unauthenticated Command Injection in Remote Agent
 -issue#4418: When using Single Signon Frameworks like SiteMinder Cacti does not properly detect ticket revocation in callbacks
 -issue#4682: New templates are not installed during the update
 -issue#4838: CLI Based upgrade generates warnings in PHP 8.1

programming_language: Markdown
filename: auth_login.php
change_type: ModificationType.MODIFY
diff: @@ -161,7 +161,7 @@ if (get_nfilter_request_var('action') == 'login' || $auth_method == 2) {
 			cacti_log("LOGIN: Guest User '" . $user['username'] . "' in use", false, 'AUTH');
 		}
 
-		$client_addr = get_client_addr('');
+		$client_addr = get_client_addr();
 
 		db_execute_prepared(
 			'INSERT IGNORE INTO user_log
@@ -269,10 +269,10 @@ if (get_nfilter_request_var('action') == 'login' || $auth_method == 2) {
 			'INSERT IGNORE INTO user_log
 			(username, user_id, result, ip, time)
 			VALUES (?, ?, 0, ?, NOW())',
-			array($username, !empty($id) ? $id : 0, get_client_addr(''))
+			array($username, !empty($id) ? $id : 0, get_client_addr())
 		);
 
-		cacti_log('LOGIN FAILED: ' . $realm_name . " Login Failed for user '" . $username . "' from IP Address '" . get_client_addr('') . "'.", false, 'AUTH');
+		cacti_log('LOGIN FAILED: ' . $realm_name . " Login Failed for user '" . $username . "' from IP Address '" . get_client_addr() . "'.", false, 'AUTH');
 	}
 }
 

programming_language: PHP
filename: config.php.dist
change_type: ModificationType.MODIFY
diff: @@ -164,3 +164,29 @@ $disable_log_rotation = false;
  * are defined in lib/database.php
  */
 # define('DEBUG_SQL_FLOW', true);
+
+/*
+ * Allow the use of Proxy IPs when searching for client
+ * IP to be used
+ *
+ * This can be set to one of the following:
+ *   - false: to use only REMOTE_ADDR
+ *   - true: to use all allowed headers (not advised)
+ *   - array of one or more the following:
+ *		'X-Forwarded-For',
+ *		'X-Client-IP',
+ *		'X-Real-IP',
+ *		'X-ProxyUser-Ip',
+ *		'CF-Connecting-IP',
+ *		'True-Client-IP',
+ *		'HTTP_X_FORWARDED',
+ *		'HTTP_X_FORWARDED_FOR',
+ *		'HTTP_X_CLUSTER_CLIENT_IP',
+ *		'HTTP_FORWARDED_FOR',
+ *		'HTTP_FORWARDED',
+ *		'HTTP_CLIENT_IP',
+ *
+ * NOTE: The following will always be checked:
+ *		'REMOTE_ADDR',
+ */
+$proxy_headers = null;

programming_language: PHP
filename: global.php
change_type: ModificationType.MODIFY
diff: @@ -145,6 +145,9 @@ if (isset($config['cacti_version'])) {
 	exit;
 }
 
+/* Should we allow proxy ip headers? */
+$config['proxy_headers'] = $proxy_headers ?? null;
+
 /* Set the poller_id */
 if (isset($poller_id)) {
 	$config['poller_id'] = $poller_id;

programming_language: PHP
filename: global_arrays.php
change_type: ModificationType.MODIFY
diff: @@ -2931,4 +2931,20 @@ if ($config['cacti_server_os'] == 'unix') {
 	);
 }
 
+$allowed_proxy_headers =	array(
+	'X-Forwarded-For',
+	'X-Client-IP',
+	'X-Real-IP',
+	'X-ProxyUser-Ip',
+	'CF-Connecting-IP',
+	'True-Client-IP',
+	'HTTP_X_FORWARDED',
+	'HTTP_X_FORWARDED_FOR',
+	'HTTP_X_CLUSTER_CLIENT_IP',
+	'HTTP_FORWARDED_FOR',
+	'HTTP_FORWARDED',
+	'HTTP_CLIENT_IP',
+	'REMOTE_ADDR',
+);
+
 api_plugin_hook('config_arrays');

programming_language: PHP
filename: auth.php
change_type: ModificationType.MODIFY
diff: @@ -83,7 +83,7 @@ function set_auth_cookie($user) {
 	if (db_table_exists('user_auth_cache')) {
 		clear_auth_cookie();
 
-		$nssecret = md5($_SERVER['REQUEST_TIME'] .  mt_rand(10000,10000000)) . md5(get_client_addr(''));
+		$nssecret = md5($_SERVER['REQUEST_TIME'] .  mt_rand(10000,10000000)) . md5(get_client_addr());
 
 		$secret = hash('sha512', $nssecret, false);
 
@@ -91,7 +91,7 @@ function set_auth_cookie($user) {
 			(user_id, hostname, last_update, token)
 			VALUES
 			(?, ?, NOW(), ?);',
-			array($user['id'], get_client_addr(''), $secret));
+			array($user['id'], get_client_addr(), $secret));
 
 		cacti_cookie_session_set($user['id'], $user['realm'], $nssecret);
 	}
@@ -161,7 +161,7 @@ function check_auth_cookie() {
 						(username, user_id, result, ip, time)
 						VALUES
 						(?, ?, 2, ?, NOW())',
-						array($user_info['username'], $user_info['id'], get_client_addr(''))
+						array($user_info['username'], $user_info['id'], get_client_addr())
 					);
 
 					return $user_info['id'];
@@ -3430,7 +3430,7 @@ function auth_process_lockout($username, $realm) {
 
 			if (cacti_sizeof($user)) {
 				if ($user['enabled'] == '') {
-					cacti_log("LOGIN FAILED: Local Login Failed for user '" . $username . "' from IP Address '" . get_client_addr('') . "'.  User account Disabled.", false, 'AUTH');
+					cacti_log("LOGIN FAILED: Local Login Failed for user '" . $username . "' from IP Address '" . get_client_addr() . "'.  User account Disabled.", false, 'AUTH');
 
 					$error     = true;
 					$error_msg = __('Access Denied!  Login Disabled.');
@@ -3464,22 +3464,22 @@ function auth_process_lockout($username, $realm) {
 				db_execute_prepared('INSERT IGNORE INTO user_log
 					(username, user_id, result, ip, time)
 					VALUES (?, ?, 0, ?, NOW())',
-					array($username, isset($user['id']) ? $user['id']:0, get_client_addr('')));
+					array($username, isset($user['id']) ? $user['id']:0, get_client_addr()));
 
 				if ($user['locked'] == 'on') {
-					cacti_log("LOGIN FAILED: Local Login Failed for user '" . $username . "' from IP Address '" . get_client_addr('') . "'.  Account is locked out.", false, 'AUTH');
+					cacti_log("LOGIN FAILED: Local Login Failed for user '" . $username . "' from IP Address '" . get_client_addr() . "'.  Account is locked out.", false, 'AUTH');
 
 					$error     = true;
 					$error_msg = __('Your account has been locked.  Please contact your Administrator.');
 				} else {
-					cacti_log("LOGIN FAILED: Local Login Failed for user '" . $username . "' from IP Address '" . get_client_addr('') . "'.", false, 'AUTH');
+					cacti_log("LOGIN FAILED: Local Login Failed for user '" . $username . "' from IP Address '" . get_client_addr() . "'.", false, 'AUTH');
 
 					/* error */
 					$error     = true;
 					$error_msg = __('Access Denied!  Login Failed.');
 				}
 			} elseif ($user['locked'] == 'on') {
-				cacti_log("LOGIN FAILED: Local Login Failed for user '" . $username . "' from IP Address '" . get_client_addr('') . "'.", false, 'AUTH');
+				cacti_log("LOGIN FAILED: Local Login Failed for user '" . $username . "' from IP Address '" . get_client_addr() . "'.", false, 'AUTH');
 
 				$error     = true;
 				$error_msg = __('Access Denied!  Login Failed.');

programming_language: PHP
filename: functions.php
change_type: ModificationType.MODIFY
diff: @@ -7079,37 +7079,50 @@ function get_debug_prefix() {
 	return sprintf('<[ %s | %7d ]> -- ', $dateTime, getmypid());
 }
 
-function get_client_addr($client_addr = false, $restrictive = false) {
-	if (!$restrictive) {
-		$http_addr_headers = array(
-			'X-Forwarded-For',
-			'X-Client-IP',
-			'X-Real-IP',
-			'X-ProxyUser-Ip',
-			'CF-Connecting-IP',
-			'True-Client-IP',
-			'HTTP_X_FORWARDED',
-			'HTTP_X_FORWARDED_FOR',
-			'HTTP_X_CLUSTER_CLIENT_IP',
-			'HTTP_FORWARDED_FOR',
-			'HTTP_FORWARDED',
-			'HTTP_CLIENT_IP',
-			'REMOTE_ADDR',
-		);
-	} else {
-		$http_addr_headers = array(
-			'X-Forwarded-For',
-			'X-Client-IP',
-			'X-Real-IP',
-			'X-ProxyUser-Ip',
-			'CF-Connecting-IP',
-			'True-Client-IP',
-			'REMOTE_ADDR',
-		);
+function get_client_addr() {
+	global $config, $allowed_proxy_headers;
+
+	$proxy_headers = $config['proxy_headers'] ?? null;
+	if ($proxy_headers === null) {
+		$last_time = read_config_option('proxy_alert');
+		if (empty($last_time)) {
+			$last_time = date('Y-m-d');
+		}
+
+		$last_date = new DateTime($last_time);
+		$this_date = new Datetime();
+
+		$this_diff = $this_date->diff($last_date);
+		$this_days = $this_diff->format('%a');
+
+		if ($this_days) {
+			cacti_log('WARNING: Configuration option "proxy_headers" will be automatically false in future releases.  Please set if you require proxy IPs to be used', false, 'AUTH');
+			set_config_option('proxy_alert', date('Y-m-d'));
+		}
+
+		$proxy_headers = true;
+	}
+
+	/* If proxy_headers is true, allow all known headers -- NOT advised
+	 * If proxy_headers is false, allow only REMOTE_ADDR
+	 * IF proxy_headers is an array, filter by known headers
+	 */
+	if ($proxy_headers === true) {
+		$proxy_headers = $allowed_proxy_headers;
+	} elseif (is_array($proxy_headers)) {
+		$proxy_headers = array_intersect($proxy_headers, $allowed_proxy_headers);
+	}
+
+	if (!is_array($proxy_headers)) {
+		$proxy_headers = [];
+	}
+
+	if (!in_array('REMOTE_ADDR', $proxy_headers)) {
+		$proxy_headers[] = 'REMOTE_ADDR';
 	}
 
 	$client_addr = false;
-	foreach ($http_addr_headers as $header) {
+	foreach ($proxy_headers as $header) {
 		if (!empty($_SERVER[$header])) {
 			$header_ips = explode(',', $_SERVER[$header]);
 			foreach ($header_ips as $header_ip) {

programming_language: PHP
filename: remote_agent.php
change_type: ModificationType.MODIFY
diff: @@ -298,7 +298,7 @@ function poll_for_data() {
 
 	$local_data_ids = get_nfilter_request_var('local_data_ids');
 	$host_id        = get_filter_request_var('host_id');
-	$poller_id      = get_nfilter_request_var('poller_id');
+	$poller_id      = get_filter_request_var('poller_id');
 	$return         = array();
 
 	$i = 0;
@@ -382,7 +382,7 @@ function poll_for_data() {
 						);
 
 						if (function_exists('proc_open')) {
-							$cactiphp = proc_open(read_config_option('path_php_binary') . ' -q ' . $config['base_path'] . '/script_server.php realtime ' . $poller_id, $cactides, $pipes);
+							$cactiphp = proc_open(read_config_option('path_php_binary') . ' -q ' . $config['base_path'] . '/script_server.php realtime ' . cacti_escapeshellarg($poller_id), $cactides, $pipes);
 							$output = fgets($pipes[1], 1024);
 							$using_proc_function = true;
 						} else {
@@ -443,8 +443,8 @@ function run_remote_data_query() {
 function run_remote_discovery() {
 	global $config;
 
-	$poller_id = $config['poller_id'];
-	$network   = get_filter_request_var('network');
+	$poller_id = cacti_escapeshellarg($config['poller_id']);
+	$network   = cacti_escapeshellarg(get_filter_request_var('network'));
 	$php       = cacti_escapeshellcmd(read_config_option('path_php_binary'));
 	$path      = cacti_escapeshellarg(read_config_option('path_webroot') . '/poller_automation.php');
 

programming_language: PHP