Shell Command.

It is possible to execute shell commands through CGI. The subprocess.Popen class is what is necessary. This module is new in python 2.4.os.popen4 can also be used if a hosting provider does not offer 2.4.

The script in this page is for educational purposes only. Read the warning. If you need a CGI Shell use the one on the next page.

This handy getshellcmd.py script gets anything in its query string and execute it as a shell command. It works for Unix with a bash shell only.

#!/usr/bin/python2.4
import cgitb; cgitb.enable()
 
# The subprocess module is new in 2.4
import os, urllib, subprocess as sub
 
# Retrieve the command from the query string
# and unencode the escaped %xx chars
str_command = urllib.unquote(os.environ['QUERY_STRING'])
 
p = sub.Popen(['/bin/bash', '-c', str_command], 
    stdout=sub.PIPE, stderr=sub.STDOUT)
output = urllib.unquote(p.stdout.read())
 
print """\
Content-Type: text/html\n
<html><body>
<pre>
$ %s
%s
</pre>
</body></html>
""" % (str_command, output)





Say you want to install Django in your site. Without this script you would have to download it to your local host, decompress it, and upload the uncompressed files by FTP.

With CGI you download it using curl or wget directly to a directory in your site's hierarchy like a tmp directory:

http://my_site.tld/getshellcmd.py?curl -o tmp/Django-0.95.tar.gz http://media.djangoproject.com/releases/0.95/Django-0.95.tar.gz

The above is one only line. And the output in the browser:
$ curl -o tmp/Django-0.95.tar.gz http://media.djangoproject.com/releases/0.95/Django-0.95.tar.gz
  % Total    % Received % Xferd  Average Speed          Time             Curr.
                                 Dload  Upload Total    Current  Left    Speed
 
  0 1257k    0  2479    0     0   7042      0  0:03:02  0:00:00  0:03:02  7042
  4 1257k    4 62727    0     0    98k      0  0:00:12  0:00:00  0:00:12  217k
 32 1257k   32  404k    0     0   241k      0  0:00:05  0:00:01  0:00:03  303k
 49 1257k   49  623k    0     0   235k      0  0:00:05  0:00:02  0:00:02  270k
 78 1257k   78  983k    0     0   271k      0  0:00:04  0:00:03  0:00:01  299k
100 1257k  100 1257k    0     0   309k      0  0:00:04  0:00:04  0:00:00  338k



Four seconds to download 1,257k in my host provider. Now to untar it issue the tar command as the query string:

http://my_site.tld/getshellcmd.py?tar -xzvf tmp/Django-0.95.tar.gz

Depending on the host absolute directory paths should be declared.

Warning: If you ever use this sample code save it with another name and chmod it to 600 immediately after its use. Otherwise any one in the whole world will be able to execute whatever he wants in your host.

No comments: