rexec.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585
  1. """Restricted execution facilities.
  2. The class RExec exports methods r_exec(), r_eval(), r_execfile(), and
  3. r_import(), which correspond roughly to the built-in operations
  4. exec, eval(), execfile() and import, but executing the code in an
  5. environment that only exposes those built-in operations that are
  6. deemed safe. To this end, a modest collection of 'fake' modules is
  7. created which mimics the standard modules by the same names. It is a
  8. policy decision which built-in modules and operations are made
  9. available; this module provides a reasonable default, but derived
  10. classes can change the policies e.g. by overriding or extending class
  11. variables like ok_builtin_modules or methods like make_sys().
  12. XXX To do:
  13. - r_open should allow writing tmp dir
  14. - r_exec etc. with explicit globals/locals? (Use rexec("exec ... in ...")?)
  15. """
  16. import sys
  17. import __builtin__
  18. import os
  19. import ihooks
  20. import imp
  21. __all__ = ["RExec"]
  22. class FileBase:
  23. ok_file_methods = ('fileno', 'flush', 'isatty', 'read', 'readline',
  24. 'readlines', 'seek', 'tell', 'write', 'writelines', 'xreadlines',
  25. '__iter__')
  26. class FileWrapper(FileBase):
  27. # XXX This is just like a Bastion -- should use that!
  28. def __init__(self, f):
  29. for m in self.ok_file_methods:
  30. if not hasattr(self, m) and hasattr(f, m):
  31. setattr(self, m, getattr(f, m))
  32. def close(self):
  33. self.flush()
  34. TEMPLATE = """
  35. def %s(self, *args):
  36. return getattr(self.mod, self.name).%s(*args)
  37. """
  38. class FileDelegate(FileBase):
  39. def __init__(self, mod, name):
  40. self.mod = mod
  41. self.name = name
  42. for m in FileBase.ok_file_methods + ('close',):
  43. exec TEMPLATE % (m, m)
  44. class RHooks(ihooks.Hooks):
  45. def __init__(self, *args):
  46. # Hacks to support both old and new interfaces:
  47. # old interface was RHooks(rexec[, verbose])
  48. # new interface is RHooks([verbose])
  49. verbose = 0
  50. rexec = None
  51. if args and type(args[-1]) == type(0):
  52. verbose = args[-1]
  53. args = args[:-1]
  54. if args and hasattr(args[0], '__class__'):
  55. rexec = args[0]
  56. args = args[1:]
  57. if args:
  58. raise TypeError, "too many arguments"
  59. ihooks.Hooks.__init__(self, verbose)
  60. self.rexec = rexec
  61. def set_rexec(self, rexec):
  62. # Called by RExec instance to complete initialization
  63. self.rexec = rexec
  64. def get_suffixes(self):
  65. return self.rexec.get_suffixes()
  66. def is_builtin(self, name):
  67. return self.rexec.is_builtin(name)
  68. def init_builtin(self, name):
  69. m = __import__(name)
  70. return self.rexec.copy_except(m, ())
  71. def init_frozen(self, name): raise SystemError, "don't use this"
  72. def load_source(self, *args): raise SystemError, "don't use this"
  73. def load_compiled(self, *args): raise SystemError, "don't use this"
  74. def load_package(self, *args): raise SystemError, "don't use this"
  75. def load_dynamic(self, name, filename, file):
  76. return self.rexec.load_dynamic(name, filename, file)
  77. def add_module(self, name):
  78. return self.rexec.add_module(name)
  79. def modules_dict(self):
  80. return self.rexec.modules
  81. def default_path(self):
  82. return self.rexec.modules['sys'].path
  83. # XXX Backwards compatibility
  84. RModuleLoader = ihooks.FancyModuleLoader
  85. RModuleImporter = ihooks.ModuleImporter
  86. class RExec(ihooks._Verbose):
  87. """Basic restricted execution framework.
  88. Code executed in this restricted environment will only have access to
  89. modules and functions that are deemed safe; you can subclass RExec to
  90. add or remove capabilities as desired.
  91. The RExec class can prevent code from performing unsafe operations like
  92. reading or writing disk files, or using TCP/IP sockets. However, it does
  93. not protect against code using extremely large amounts of memory or
  94. processor time.
  95. """
  96. ok_path = tuple(sys.path) # That's a policy decision
  97. ok_builtin_modules = ('audioop', 'array', 'binascii',
  98. 'cmath', 'errno', 'imageop',
  99. 'marshal', 'math', 'md5', 'operator',
  100. 'parser', 'regex', 'select',
  101. 'sha', '_sre', 'strop', 'struct', 'time',
  102. '_weakref')
  103. ok_posix_names = ('error', 'fstat', 'listdir', 'lstat', 'readlink',
  104. 'stat', 'times', 'uname', 'getpid', 'getppid',
  105. 'getcwd', 'getuid', 'getgid', 'geteuid', 'getegid')
  106. ok_sys_names = ('byteorder', 'copyright', 'exit', 'getdefaultencoding',
  107. 'getrefcount', 'hexversion', 'maxint', 'maxunicode',
  108. 'platform', 'ps1', 'ps2', 'version', 'version_info')
  109. nok_builtin_names = ('open', 'file', 'reload', '__import__')
  110. ok_file_types = (imp.C_EXTENSION, imp.PY_SOURCE)
  111. def __init__(self, hooks = None, verbose = 0):
  112. """Returns an instance of the RExec class.
  113. The hooks parameter is an instance of the RHooks class or a subclass
  114. of it. If it is omitted or None, the default RHooks class is
  115. instantiated.
  116. Whenever the RExec module searches for a module (even a built-in one)
  117. or reads a module's code, it doesn't actually go out to the file
  118. system itself. Rather, it calls methods of an RHooks instance that
  119. was passed to or created by its constructor. (Actually, the RExec
  120. object doesn't make these calls --- they are made by a module loader
  121. object that's part of the RExec object. This allows another level of
  122. flexibility, which can be useful when changing the mechanics of
  123. import within the restricted environment.)
  124. By providing an alternate RHooks object, we can control the file
  125. system accesses made to import a module, without changing the
  126. actual algorithm that controls the order in which those accesses are
  127. made. For instance, we could substitute an RHooks object that
  128. passes all filesystem requests to a file server elsewhere, via some
  129. RPC mechanism such as ILU. Grail's applet loader uses this to support
  130. importing applets from a URL for a directory.
  131. If the verbose parameter is true, additional debugging output may be
  132. sent to standard output.
  133. """
  134. raise RuntimeError, "This code is not secure in Python 2.2 and 2.3"
  135. ihooks._Verbose.__init__(self, verbose)
  136. # XXX There's a circular reference here:
  137. self.hooks = hooks or RHooks(verbose)
  138. self.hooks.set_rexec(self)
  139. self.modules = {}
  140. self.ok_dynamic_modules = self.ok_builtin_modules
  141. list = []
  142. for mname in self.ok_builtin_modules:
  143. if mname in sys.builtin_module_names:
  144. list.append(mname)
  145. self.ok_builtin_modules = tuple(list)
  146. self.set_trusted_path()
  147. self.make_builtin()
  148. self.make_initial_modules()
  149. # make_sys must be last because it adds the already created
  150. # modules to its builtin_module_names
  151. self.make_sys()
  152. self.loader = RModuleLoader(self.hooks, verbose)
  153. self.importer = RModuleImporter(self.loader, verbose)
  154. def set_trusted_path(self):
  155. # Set the path from which dynamic modules may be loaded.
  156. # Those dynamic modules must also occur in ok_builtin_modules
  157. self.trusted_path = filter(os.path.isabs, sys.path)
  158. def load_dynamic(self, name, filename, file):
  159. if name not in self.ok_dynamic_modules:
  160. raise ImportError, "untrusted dynamic module: %s" % name
  161. if name in sys.modules:
  162. src = sys.modules[name]
  163. else:
  164. src = imp.load_dynamic(name, filename, file)
  165. dst = self.copy_except(src, [])
  166. return dst
  167. def make_initial_modules(self):
  168. self.make_main()
  169. self.make_osname()
  170. # Helpers for RHooks
  171. def get_suffixes(self):
  172. return [item # (suff, mode, type)
  173. for item in imp.get_suffixes()
  174. if item[2] in self.ok_file_types]
  175. def is_builtin(self, mname):
  176. return mname in self.ok_builtin_modules
  177. # The make_* methods create specific built-in modules
  178. def make_builtin(self):
  179. m = self.copy_except(__builtin__, self.nok_builtin_names)
  180. m.__import__ = self.r_import
  181. m.reload = self.r_reload
  182. m.open = m.file = self.r_open
  183. def make_main(self):
  184. m = self.add_module('__main__')
  185. def make_osname(self):
  186. osname = os.name
  187. src = __import__(osname)
  188. dst = self.copy_only(src, self.ok_posix_names)
  189. dst.environ = e = {}
  190. for key, value in os.environ.items():
  191. e[key] = value
  192. def make_sys(self):
  193. m = self.copy_only(sys, self.ok_sys_names)
  194. m.modules = self.modules
  195. m.argv = ['RESTRICTED']
  196. m.path = map(None, self.ok_path)
  197. m.exc_info = self.r_exc_info
  198. m = self.modules['sys']
  199. l = self.modules.keys() + list(self.ok_builtin_modules)
  200. l.sort()
  201. m.builtin_module_names = tuple(l)
  202. # The copy_* methods copy existing modules with some changes
  203. def copy_except(self, src, exceptions):
  204. dst = self.copy_none(src)
  205. for name in dir(src):
  206. setattr(dst, name, getattr(src, name))
  207. for name in exceptions:
  208. try:
  209. delattr(dst, name)
  210. except AttributeError:
  211. pass
  212. return dst
  213. def copy_only(self, src, names):
  214. dst = self.copy_none(src)
  215. for name in names:
  216. try:
  217. value = getattr(src, name)
  218. except AttributeError:
  219. continue
  220. setattr(dst, name, value)
  221. return dst
  222. def copy_none(self, src):
  223. m = self.add_module(src.__name__)
  224. m.__doc__ = src.__doc__
  225. return m
  226. # Add a module -- return an existing module or create one
  227. def add_module(self, mname):
  228. m = self.modules.get(mname)
  229. if m is None:
  230. self.modules[mname] = m = self.hooks.new_module(mname)
  231. m.__builtins__ = self.modules['__builtin__']
  232. return m
  233. # The r* methods are public interfaces
  234. def r_exec(self, code):
  235. """Execute code within a restricted environment.
  236. The code parameter must either be a string containing one or more
  237. lines of Python code, or a compiled code object, which will be
  238. executed in the restricted environment's __main__ module.
  239. """
  240. m = self.add_module('__main__')
  241. exec code in m.__dict__
  242. def r_eval(self, code):
  243. """Evaluate code within a restricted environment.
  244. The code parameter must either be a string containing a Python
  245. expression, or a compiled code object, which will be evaluated in
  246. the restricted environment's __main__ module. The value of the
  247. expression or code object will be returned.
  248. """
  249. m = self.add_module('__main__')
  250. return eval(code, m.__dict__)
  251. def r_execfile(self, file):
  252. """Execute the Python code in the file in the restricted
  253. environment's __main__ module.
  254. """
  255. m = self.add_module('__main__')
  256. execfile(file, m.__dict__)
  257. def r_import(self, mname, globals={}, locals={}, fromlist=[]):
  258. """Import a module, raising an ImportError exception if the module
  259. is considered unsafe.
  260. This method is implicitly called by code executing in the
  261. restricted environment. Overriding this method in a subclass is
  262. used to change the policies enforced by a restricted environment.
  263. """
  264. return self.importer.import_module(mname, globals, locals, fromlist)
  265. def r_reload(self, m):
  266. """Reload the module object, re-parsing and re-initializing it.
  267. This method is implicitly called by code executing in the
  268. restricted environment. Overriding this method in a subclass is
  269. used to change the policies enforced by a restricted environment.
  270. """
  271. return self.importer.reload(m)
  272. def r_unload(self, m):
  273. """Unload the module.
  274. Removes it from the restricted environment's sys.modules dictionary.
  275. This method is implicitly called by code executing in the
  276. restricted environment. Overriding this method in a subclass is
  277. used to change the policies enforced by a restricted environment.
  278. """
  279. return self.importer.unload(m)
  280. # The s_* methods are similar but also swap std{in,out,err}
  281. def make_delegate_files(self):
  282. s = self.modules['sys']
  283. self.delegate_stdin = FileDelegate(s, 'stdin')
  284. self.delegate_stdout = FileDelegate(s, 'stdout')
  285. self.delegate_stderr = FileDelegate(s, 'stderr')
  286. self.restricted_stdin = FileWrapper(sys.stdin)
  287. self.restricted_stdout = FileWrapper(sys.stdout)
  288. self.restricted_stderr = FileWrapper(sys.stderr)
  289. def set_files(self):
  290. if not hasattr(self, 'save_stdin'):
  291. self.save_files()
  292. if not hasattr(self, 'delegate_stdin'):
  293. self.make_delegate_files()
  294. s = self.modules['sys']
  295. s.stdin = self.restricted_stdin
  296. s.stdout = self.restricted_stdout
  297. s.stderr = self.restricted_stderr
  298. sys.stdin = self.delegate_stdin
  299. sys.stdout = self.delegate_stdout
  300. sys.stderr = self.delegate_stderr
  301. def reset_files(self):
  302. self.restore_files()
  303. s = self.modules['sys']
  304. self.restricted_stdin = s.stdin
  305. self.restricted_stdout = s.stdout
  306. self.restricted_stderr = s.stderr
  307. def save_files(self):
  308. self.save_stdin = sys.stdin
  309. self.save_stdout = sys.stdout
  310. self.save_stderr = sys.stderr
  311. def restore_files(self):
  312. sys.stdin = self.save_stdin
  313. sys.stdout = self.save_stdout
  314. sys.stderr = self.save_stderr
  315. def s_apply(self, func, args=(), kw={}):
  316. self.save_files()
  317. try:
  318. self.set_files()
  319. r = func(*args, **kw)
  320. finally:
  321. self.restore_files()
  322. return r
  323. def s_exec(self, *args):
  324. """Execute code within a restricted environment.
  325. Similar to the r_exec() method, but the code will be granted access
  326. to restricted versions of the standard I/O streams sys.stdin,
  327. sys.stderr, and sys.stdout.
  328. The code parameter must either be a string containing one or more
  329. lines of Python code, or a compiled code object, which will be
  330. executed in the restricted environment's __main__ module.
  331. """
  332. return self.s_apply(self.r_exec, args)
  333. def s_eval(self, *args):
  334. """Evaluate code within a restricted environment.
  335. Similar to the r_eval() method, but the code will be granted access
  336. to restricted versions of the standard I/O streams sys.stdin,
  337. sys.stderr, and sys.stdout.
  338. The code parameter must either be a string containing a Python
  339. expression, or a compiled code object, which will be evaluated in
  340. the restricted environment's __main__ module. The value of the
  341. expression or code object will be returned.
  342. """
  343. return self.s_apply(self.r_eval, args)
  344. def s_execfile(self, *args):
  345. """Execute the Python code in the file in the restricted
  346. environment's __main__ module.
  347. Similar to the r_execfile() method, but the code will be granted
  348. access to restricted versions of the standard I/O streams sys.stdin,
  349. sys.stderr, and sys.stdout.
  350. """
  351. return self.s_apply(self.r_execfile, args)
  352. def s_import(self, *args):
  353. """Import a module, raising an ImportError exception if the module
  354. is considered unsafe.
  355. This method is implicitly called by code executing in the
  356. restricted environment. Overriding this method in a subclass is
  357. used to change the policies enforced by a restricted environment.
  358. Similar to the r_import() method, but has access to restricted
  359. versions of the standard I/O streams sys.stdin, sys.stderr, and
  360. sys.stdout.
  361. """
  362. return self.s_apply(self.r_import, args)
  363. def s_reload(self, *args):
  364. """Reload the module object, re-parsing and re-initializing it.
  365. This method is implicitly called by code executing in the
  366. restricted environment. Overriding this method in a subclass is
  367. used to change the policies enforced by a restricted environment.
  368. Similar to the r_reload() method, but has access to restricted
  369. versions of the standard I/O streams sys.stdin, sys.stderr, and
  370. sys.stdout.
  371. """
  372. return self.s_apply(self.r_reload, args)
  373. def s_unload(self, *args):
  374. """Unload the module.
  375. Removes it from the restricted environment's sys.modules dictionary.
  376. This method is implicitly called by code executing in the
  377. restricted environment. Overriding this method in a subclass is
  378. used to change the policies enforced by a restricted environment.
  379. Similar to the r_unload() method, but has access to restricted
  380. versions of the standard I/O streams sys.stdin, sys.stderr, and
  381. sys.stdout.
  382. """
  383. return self.s_apply(self.r_unload, args)
  384. # Restricted open(...)
  385. def r_open(self, file, mode='r', buf=-1):
  386. """Method called when open() is called in the restricted environment.
  387. The arguments are identical to those of the open() function, and a
  388. file object (or a class instance compatible with file objects)
  389. should be returned. RExec's default behaviour is allow opening
  390. any file for reading, but forbidding any attempt to write a file.
  391. This method is implicitly called by code executing in the
  392. restricted environment. Overriding this method in a subclass is
  393. used to change the policies enforced by a restricted environment.
  394. """
  395. mode = str(mode)
  396. if mode not in ('r', 'rb'):
  397. raise IOError, "can't open files for writing in restricted mode"
  398. return open(file, mode, buf)
  399. # Restricted version of sys.exc_info()
  400. def r_exc_info(self):
  401. ty, va, tr = sys.exc_info()
  402. tr = None
  403. return ty, va, tr
  404. def test():
  405. import getopt, traceback
  406. opts, args = getopt.getopt(sys.argv[1:], 'vt:')
  407. verbose = 0
  408. trusted = []
  409. for o, a in opts:
  410. if o == '-v':
  411. verbose = verbose+1
  412. if o == '-t':
  413. trusted.append(a)
  414. r = RExec(verbose=verbose)
  415. if trusted:
  416. r.ok_builtin_modules = r.ok_builtin_modules + tuple(trusted)
  417. if args:
  418. r.modules['sys'].argv = args
  419. r.modules['sys'].path.insert(0, os.path.dirname(args[0]))
  420. else:
  421. r.modules['sys'].path.insert(0, "")
  422. fp = sys.stdin
  423. if args and args[0] != '-':
  424. try:
  425. fp = open(args[0])
  426. except IOError, msg:
  427. print "%s: can't open file %r" % (sys.argv[0], args[0])
  428. return 1
  429. if fp.isatty():
  430. try:
  431. import readline
  432. except ImportError:
  433. pass
  434. import code
  435. class RestrictedConsole(code.InteractiveConsole):
  436. def runcode(self, co):
  437. self.locals['__builtins__'] = r.modules['__builtin__']
  438. r.s_apply(code.InteractiveConsole.runcode, (self, co))
  439. try:
  440. RestrictedConsole(r.modules['__main__'].__dict__).interact()
  441. except SystemExit, n:
  442. return n
  443. else:
  444. text = fp.read()
  445. fp.close()
  446. c = compile(text, fp.name, 'exec')
  447. try:
  448. r.s_exec(c)
  449. except SystemExit, n:
  450. return n
  451. except:
  452. traceback.print_exc()
  453. return 1
  454. if __name__ == '__main__':
  455. sys.exit(test())