
module Msf

###
#
# This module provides methods for browser exploitation via javascript
#
###
module Exploit::Remote::HttpServer::BrowserExploit

  include Msf::Exploit::Remote::HttpServer

  def initialize(info = {})
    super
    register_advanced_options(
      [
        OptBool.new('DEBUG_EXPLOIT', [false, 'Show debug information during exploitation', false]),
      ], Exploit::Remote::HttpServer::BrowserExploit
    )
  end

  def start_service(opts = {})
    super(opts)

    if datastore['DEBUG_EXPLOIT']
      add_print_status_resource
    end
  end

  def add_print_status_resource
    proc = Proc.new do |cli, req|
      print_status("[*] #{req.body}")
      send_response(cli, '')
    end

    vprint_status('Adding hardcoded URI /print')
    begin
      add_resource('Path' => '/print', 'Proc' => proc)
    rescue RuntimeError => e
      print_warning(e.message)
    end
  end

  def add_debug_print_js(jscript)
    if datastore['DEBUG_EXPLOIT']
      debugjs = <<~JS
        print = function(arg) {
          var request = new XMLHttpRequest();
          request.open("POST", "/print", false);
          request.send("" + arg);
        };
      JS

      jscript = "#{debugjs}#{jscript}"
    else
      jscript.gsub!(%r{//.*$}, '') # strip comments
      jscript.gsub!(/^\s*print\s*\(.*?\);\s*$/, '') # strip print(*);
    end
    jscript
  end

end

end
