PageRenderTime 49ms CodeModel.GetById 12ms RepoModel.GetById 1ms app.codeStats 0ms

/lib-python/2.7/rexec.py

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