1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
|
def banner(): print "=============================================" print " Simple calculator implemented by python " print "=============================================" return
def getexp(): return raw_input(">>> ")
def _hook_import_(name, *args, **kwargs): module_blacklist = ['os', 'sys', 'time', 'bdb', 'bsddb', 'cgi', 'CGIHTTPServer', 'cgitb', 'compileall', 'ctypes', 'dircache', 'doctest', 'dumbdbm', 'filecmp', 'fileinput', 'ftplib', 'gzip', 'getopt', 'getpass', 'gettext', 'httplib', 'importlib', 'imputil', 'linecache', 'macpath', 'mailbox', 'mailcap', 'mhlib', 'mimetools', 'mimetypes', 'modulefinder', 'multiprocessing', 'netrc', 'new', 'optparse', 'pdb', 'pipes', 'pkgutil', 'platform', 'popen2', 'poplib', 'posix', 'posixfile', 'profile', 'pstats', 'pty', 'py_compile', 'pyclbr', 'pydoc', 'rexec', 'runpy', 'shlex', 'shutil', 'SimpleHTTPServer', 'SimpleXMLRPCServer', 'site', 'smtpd', 'socket', 'SocketServer', 'subprocess', 'sysconfig', 'tabnanny', 'tarfile', 'telnetlib', 'tempfile', 'Tix', 'trace', 'turtle', 'urllib', 'urllib2', 'user', 'uu', 'webbrowser', 'whichdb', 'zipfile', 'zipimport'] for forbid in module_blacklist: if name == forbid: raise RuntimeError('No you can\' import {0}!!!'.format(forbid)) return __import__(name, *args, **kwargs)
def sandbox_filter(command): blacklist = ['exec', 'sh', '__getitem__', '__setitem__', '=', 'open', 'read', 'sys', ';', 'os'] for forbid in blacklist: if forbid in command: return 0 return 1
def sandbox_exec(command): result = 0 __sandboxed_builtins__ = dict(__builtins__.__dict__) __sandboxed_builtins__['__import__'] = _hook_import_ del __sandboxed_builtins__['open'] _global = { '__builtins__': __sandboxed_builtins__ } if sandbox_filter(command) == 0: print 'Malicious user input detected!!!' exit(0) command = 'result = ' + command try: exec command in _global except Exception, e: print e return 0 result = _global['result'] return result
banner() while 1: command = getexp() print sandbox_exec(command)
|