blob: 6a7c2071a016d787b9ac98e86ebc6b0d56085f61 [file] [log] [blame]
Guido van Rossum40d1ea31995-08-04 03:59:03 +00001"""Restricted execution facilities.
Guido van Rossum9a22de11995-01-12 12:29:47 +00002
Guido van Rossumfdd45cb1996-05-28 23:07:17 +00003The class RExec exports methods r_exec(), r_eval(), r_execfile(), and
4r_import(), which correspond roughly to the built-in operations
Guido van Rossum40d1ea31995-08-04 03:59:03 +00005exec, eval(), execfile() and import, but executing the code in an
6environment that only exposes those built-in operations that are
7deemed safe. To this end, a modest collection of 'fake' modules is
8created which mimics the standard modules by the same names. It is a
9policy decision which built-in modules and operations are made
10available; this module provides a reasonable default, but derived
11classes can change the policies e.g. by overriding or extending class
12variables like ok_builtin_modules or methods like make_sys().
13
Guido van Rossum13833561995-08-07 20:19:27 +000014XXX To do:
15- r_open should allow writing tmp dir
16- r_exec etc. with explicit globals/locals? (Use rexec("exec ... in ...")?)
Guido van Rossum13833561995-08-07 20:19:27 +000017
Guido van Rossum40d1ea31995-08-04 03:59:03 +000018"""
19
20
Guido van Rossum9a22de11995-01-12 12:29:47 +000021import sys
Guido van Rossum40d1ea31995-08-04 03:59:03 +000022import __builtin__
23import os
Guido van Rossum40d1ea31995-08-04 03:59:03 +000024import ihooks
Guido van Rossum9a22de11995-01-12 12:29:47 +000025
Skip Montanaro0de65802001-02-15 22:15:14 +000026__all__ = ["RExec"]
Guido van Rossum9a22de11995-01-12 12:29:47 +000027
Guido van Rossum13833561995-08-07 20:19:27 +000028class FileBase:
29
Guido van Rossum3ec38f01998-03-26 22:10:50 +000030 ok_file_methods = ('fileno', 'flush', 'isatty', 'read', 'readline',
31 'readlines', 'seek', 'tell', 'write', 'writelines')
Guido van Rossum13833561995-08-07 20:19:27 +000032
33
34class FileWrapper(FileBase):
35
Guido van Rossum3ec38f01998-03-26 22:10:50 +000036 # XXX This is just like a Bastion -- should use that!
Guido van Rossumcd6aab91996-06-28 17:28:51 +000037
Guido van Rossum3ec38f01998-03-26 22:10:50 +000038 def __init__(self, f):
39 self.f = f
40 for m in self.ok_file_methods:
41 if not hasattr(self, m) and hasattr(f, m):
42 setattr(self, m, getattr(f, m))
43
44 def close(self):
45 self.flush()
Guido van Rossum13833561995-08-07 20:19:27 +000046
47
48TEMPLATE = """
49def %s(self, *args):
Guido van Rossum3ec38f01998-03-26 22:10:50 +000050 return apply(getattr(self.mod, self.name).%s, args)
Guido van Rossum13833561995-08-07 20:19:27 +000051"""
52
53class FileDelegate(FileBase):
54
Guido van Rossum3ec38f01998-03-26 22:10:50 +000055 def __init__(self, mod, name):
56 self.mod = mod
57 self.name = name
58
59 for m in FileBase.ok_file_methods + ('close',):
60 exec TEMPLATE % (m, m)
Guido van Rossum13833561995-08-07 20:19:27 +000061
62
Guido van Rossum40d1ea31995-08-04 03:59:03 +000063class RHooks(ihooks.Hooks):
Guido van Rossum9a22de11995-01-12 12:29:47 +000064
Guido van Rossumfdd45cb1996-05-28 23:07:17 +000065 def __init__(self, *args):
Guido van Rossum3ec38f01998-03-26 22:10:50 +000066 # Hacks to support both old and new interfaces:
67 # old interface was RHooks(rexec[, verbose])
68 # new interface is RHooks([verbose])
69 verbose = 0
70 rexec = None
71 if args and type(args[-1]) == type(0):
72 verbose = args[-1]
73 args = args[:-1]
74 if args and hasattr(args[0], '__class__'):
75 rexec = args[0]
76 args = args[1:]
77 if args:
78 raise TypeError, "too many arguments"
79 ihooks.Hooks.__init__(self, verbose)
80 self.rexec = rexec
Guido van Rossum9a22de11995-01-12 12:29:47 +000081
Guido van Rossumfdd45cb1996-05-28 23:07:17 +000082 def set_rexec(self, rexec):
Guido van Rossum3ec38f01998-03-26 22:10:50 +000083 # Called by RExec instance to complete initialization
84 self.rexec = rexec
Guido van Rossumfdd45cb1996-05-28 23:07:17 +000085
Guido van Rossum40d1ea31995-08-04 03:59:03 +000086 def is_builtin(self, name):
Guido van Rossum3ec38f01998-03-26 22:10:50 +000087 return self.rexec.is_builtin(name)
Guido van Rossum9a22de11995-01-12 12:29:47 +000088
Guido van Rossum40d1ea31995-08-04 03:59:03 +000089 def init_builtin(self, name):
Guido van Rossum3ec38f01998-03-26 22:10:50 +000090 m = __import__(name)
91 return self.rexec.copy_except(m, ())
Guido van Rossum9a22de11995-01-12 12:29:47 +000092
Guido van Rossum40d1ea31995-08-04 03:59:03 +000093 def init_frozen(self, name): raise SystemError, "don't use this"
94 def load_source(self, *args): raise SystemError, "don't use this"
95 def load_compiled(self, *args): raise SystemError, "don't use this"
Guido van Rossum8b3282b1998-06-29 20:32:57 +000096 def load_package(self, *args): raise SystemError, "don't use this"
Guido van Rossum40d1ea31995-08-04 03:59:03 +000097
Guido van Rossumfdd45cb1996-05-28 23:07:17 +000098 def load_dynamic(self, name, filename, file):
Guido van Rossum3ec38f01998-03-26 22:10:50 +000099 return self.rexec.load_dynamic(name, filename, file)
Guido van Rossum40d1ea31995-08-04 03:59:03 +0000100
101 def add_module(self, name):
Guido van Rossum3ec38f01998-03-26 22:10:50 +0000102 return self.rexec.add_module(name)
Guido van Rossum40d1ea31995-08-04 03:59:03 +0000103
104 def modules_dict(self):
Guido van Rossum3ec38f01998-03-26 22:10:50 +0000105 return self.rexec.modules
Guido van Rossum40d1ea31995-08-04 03:59:03 +0000106
107 def default_path(self):
Guido van Rossum3ec38f01998-03-26 22:10:50 +0000108 return self.rexec.modules['sys'].path
Guido van Rossum40d1ea31995-08-04 03:59:03 +0000109
110
Guido van Rossumf07029e1998-09-21 14:53:26 +0000111# XXX Backwards compatibility
112RModuleLoader = ihooks.FancyModuleLoader
113RModuleImporter = ihooks.ModuleImporter
Guido van Rossum40d1ea31995-08-04 03:59:03 +0000114
115
116class RExec(ihooks._Verbose):
117
118 """Restricted Execution environment."""
119
Guido van Rossum3ec38f01998-03-26 22:10:50 +0000120 ok_path = tuple(sys.path) # That's a policy decision
Guido van Rossum40d1ea31995-08-04 03:59:03 +0000121
Guido van Rossume7b9fde1996-09-25 18:47:39 +0000122 ok_builtin_modules = ('audioop', 'array', 'binascii',
Guido van Rossum3ec38f01998-03-26 22:10:50 +0000123 'cmath', 'errno', 'imageop',
124 'marshal', 'math', 'md5', 'operator',
125 'parser', 'regex', 'pcre', 'rotor', 'select',
126 'strop', 'struct', 'time')
Guido van Rossum40d1ea31995-08-04 03:59:03 +0000127
128 ok_posix_names = ('error', 'fstat', 'listdir', 'lstat', 'readlink',
Guido van Rossum3ec38f01998-03-26 22:10:50 +0000129 'stat', 'times', 'uname', 'getpid', 'getppid',
130 'getcwd', 'getuid', 'getgid', 'geteuid', 'getegid')
Guido van Rossum40d1ea31995-08-04 03:59:03 +0000131
132 ok_sys_names = ('ps1', 'ps2', 'copyright', 'version',
Guido van Rossum3ec38f01998-03-26 22:10:50 +0000133 'platform', 'exit', 'maxint')
Guido van Rossum40d1ea31995-08-04 03:59:03 +0000134
Guido van Rossum13833561995-08-07 20:19:27 +0000135 nok_builtin_names = ('open', 'reload', '__import__')
Guido van Rossum40d1ea31995-08-04 03:59:03 +0000136
137 def __init__(self, hooks = None, verbose = 0):
Guido van Rossum3ec38f01998-03-26 22:10:50 +0000138 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)
Fred Drake034c2a92000-10-05 20:42:44 +0000157 # but since re isn't normally built-in, we can add it at the end;
158 # we need the imported to be set before this can be imported.
159 self.make_re()
Guido van Rossum40d1ea31995-08-04 03:59:03 +0000160
Guido van Rossumfdd45cb1996-05-28 23:07:17 +0000161 def set_trusted_path(self):
Guido van Rossum3ec38f01998-03-26 22:10:50 +0000162 # Set the path from which dynamic modules may be loaded.
163 # Those dynamic modules must also occur in ok_builtin_modules
164 self.trusted_path = filter(os.path.isabs, sys.path)
Guido van Rossumfdd45cb1996-05-28 23:07:17 +0000165
166 def load_dynamic(self, name, filename, file):
Guido van Rossum3ec38f01998-03-26 22:10:50 +0000167 if name not in self.ok_dynamic_modules:
168 raise ImportError, "untrusted dynamic module: %s" % name
169 if sys.modules.has_key(name):
170 src = sys.modules[name]
171 else:
172 import imp
173 src = imp.load_dynamic(name, filename, file)
174 dst = self.copy_except(src, [])
175 return dst
Guido van Rossumfdd45cb1996-05-28 23:07:17 +0000176
Guido van Rossum40d1ea31995-08-04 03:59:03 +0000177 def make_initial_modules(self):
Guido van Rossum3ec38f01998-03-26 22:10:50 +0000178 self.make_main()
179 self.make_osname()
Guido van Rossum40d1ea31995-08-04 03:59:03 +0000180
181 # Helpers for RHooks
182
183 def is_builtin(self, mname):
Guido van Rossum3ec38f01998-03-26 22:10:50 +0000184 return mname in self.ok_builtin_modules
Guido van Rossum40d1ea31995-08-04 03:59:03 +0000185
186 # The make_* methods create specific built-in modules
187
188 def make_builtin(self):
Guido van Rossum3ec38f01998-03-26 22:10:50 +0000189 m = self.copy_except(__builtin__, self.nok_builtin_names)
190 m.__import__ = self.r_import
191 m.reload = self.r_reload
192 m.open = self.r_open
Guido van Rossum40d1ea31995-08-04 03:59:03 +0000193
194 def make_main(self):
Guido van Rossum3ec38f01998-03-26 22:10:50 +0000195 m = self.add_module('__main__')
Guido van Rossum40d1ea31995-08-04 03:59:03 +0000196
197 def make_osname(self):
Guido van Rossum3ec38f01998-03-26 22:10:50 +0000198 osname = os.name
199 src = __import__(osname)
200 dst = self.copy_only(src, self.ok_posix_names)
201 dst.environ = e = {}
202 for key, value in os.environ.items():
203 e[key] = value
Guido van Rossum40d1ea31995-08-04 03:59:03 +0000204
Fred Drake034c2a92000-10-05 20:42:44 +0000205 def make_re(self):
206 dst = self.add_module("re")
207 src = self.r_import("pre")
208 for name in dir(src):
209 if name != "__name__":
210 setattr(dst, name, getattr(src, name))
211
Guido van Rossum40d1ea31995-08-04 03:59:03 +0000212 def make_sys(self):
Guido van Rossum3ec38f01998-03-26 22:10:50 +0000213 m = self.copy_only(sys, self.ok_sys_names)
214 m.modules = self.modules
215 m.argv = ['RESTRICTED']
216 m.path = map(None, self.ok_path)
Guido van Rossumeeb64281998-07-09 13:52:38 +0000217 m.exc_info = self.r_exc_info
Guido van Rossum3ec38f01998-03-26 22:10:50 +0000218 m = self.modules['sys']
219 l = self.modules.keys() + list(self.ok_builtin_modules)
220 l.sort()
221 m.builtin_module_names = tuple(l)
Guido van Rossum40d1ea31995-08-04 03:59:03 +0000222
223 # The copy_* methods copy existing modules with some changes
224
225 def copy_except(self, src, exceptions):
Guido van Rossum3ec38f01998-03-26 22:10:50 +0000226 dst = self.copy_none(src)
227 for name in dir(src):
228 setattr(dst, name, getattr(src, name))
229 for name in exceptions:
230 try:
231 delattr(dst, name)
232 except AttributeError:
233 pass
234 return dst
Guido van Rossum40d1ea31995-08-04 03:59:03 +0000235
236 def copy_only(self, src, names):
Guido van Rossum3ec38f01998-03-26 22:10:50 +0000237 dst = self.copy_none(src)
238 for name in names:
239 try:
240 value = getattr(src, name)
241 except AttributeError:
242 continue
243 setattr(dst, name, value)
244 return dst
Guido van Rossum40d1ea31995-08-04 03:59:03 +0000245
246 def copy_none(self, src):
Guido van Rossum1f40cd61998-06-09 21:33:44 +0000247 m = self.add_module(src.__name__)
248 m.__doc__ = src.__doc__
249 return m
Guido van Rossum40d1ea31995-08-04 03:59:03 +0000250
251 # Add a module -- return an existing module or create one
252
253 def add_module(self, mname):
Guido van Rossum3ec38f01998-03-26 22:10:50 +0000254 if self.modules.has_key(mname):
255 return self.modules[mname]
256 self.modules[mname] = m = self.hooks.new_module(mname)
257 m.__builtins__ = self.modules['__builtin__']
258 return m
Guido van Rossum9a22de11995-01-12 12:29:47 +0000259
Guido van Rossum40d1ea31995-08-04 03:59:03 +0000260 # The r* methods are public interfaces
Guido van Rossum9a22de11995-01-12 12:29:47 +0000261
Guido van Rossum40d1ea31995-08-04 03:59:03 +0000262 def r_exec(self, code):
Guido van Rossum3ec38f01998-03-26 22:10:50 +0000263 m = self.add_module('__main__')
264 exec code in m.__dict__
Guido van Rossum9a22de11995-01-12 12:29:47 +0000265
Guido van Rossum40d1ea31995-08-04 03:59:03 +0000266 def r_eval(self, code):
Guido van Rossum3ec38f01998-03-26 22:10:50 +0000267 m = self.add_module('__main__')
268 return eval(code, m.__dict__)
Guido van Rossum9a22de11995-01-12 12:29:47 +0000269
Guido van Rossum40d1ea31995-08-04 03:59:03 +0000270 def r_execfile(self, file):
Guido van Rossum3ec38f01998-03-26 22:10:50 +0000271 m = self.add_module('__main__')
272 return execfile(file, m.__dict__)
Guido van Rossum9a22de11995-01-12 12:29:47 +0000273
Guido van Rossum40d1ea31995-08-04 03:59:03 +0000274 def r_import(self, mname, globals={}, locals={}, fromlist=[]):
Guido van Rossum3ec38f01998-03-26 22:10:50 +0000275 return self.importer.import_module(mname, globals, locals, fromlist)
Guido van Rossum9a22de11995-01-12 12:29:47 +0000276
Guido van Rossum13833561995-08-07 20:19:27 +0000277 def r_reload(self, m):
278 return self.importer.reload(m)
Guido van Rossumbebe5151995-08-09 02:32:08 +0000279
280 def r_unload(self, m):
281 return self.importer.unload(m)
Tim Peters0c9886d2001-01-15 01:18:21 +0000282
Guido van Rossum13833561995-08-07 20:19:27 +0000283 # The s_* methods are similar but also swap std{in,out,err}
284
Guido van Rossumcd6aab91996-06-28 17:28:51 +0000285 def make_delegate_files(self):
Guido van Rossum13833561995-08-07 20:19:27 +0000286 s = self.modules['sys']
Guido van Rossum3ec38f01998-03-26 22:10:50 +0000287 self.delegate_stdin = FileDelegate(s, 'stdin')
288 self.delegate_stdout = FileDelegate(s, 'stdout')
289 self.delegate_stderr = FileDelegate(s, 'stderr')
Guido van Rossumcd6aab91996-06-28 17:28:51 +0000290 self.restricted_stdin = FileWrapper(sys.stdin)
291 self.restricted_stdout = FileWrapper(sys.stdout)
292 self.restricted_stderr = FileWrapper(sys.stderr)
293
294 def set_files(self):
Guido van Rossum3ec38f01998-03-26 22:10:50 +0000295 if not hasattr(self, 'save_stdin'):
296 self.save_files()
297 if not hasattr(self, 'delegate_stdin'):
298 self.make_delegate_files()
Guido van Rossumcd6aab91996-06-28 17:28:51 +0000299 s = self.modules['sys']
Guido van Rossum3ec38f01998-03-26 22:10:50 +0000300 s.stdin = self.restricted_stdin
301 s.stdout = self.restricted_stdout
302 s.stderr = self.restricted_stderr
303 sys.stdin = self.delegate_stdin
304 sys.stdout = self.delegate_stdout
305 sys.stderr = self.delegate_stderr
Guido van Rossumcd6aab91996-06-28 17:28:51 +0000306
307 def reset_files(self):
Guido van Rossum3ec38f01998-03-26 22:10:50 +0000308 self.restore_files()
Guido van Rossumcd6aab91996-06-28 17:28:51 +0000309 s = self.modules['sys']
Guido van Rossum3ec38f01998-03-26 22:10:50 +0000310 self.restricted_stdin = s.stdin
311 self.restricted_stdout = s.stdout
312 self.restricted_stderr = s.stderr
Tim Peters0c9886d2001-01-15 01:18:21 +0000313
Guido van Rossum13833561995-08-07 20:19:27 +0000314
315 def save_files(self):
316 self.save_stdin = sys.stdin
317 self.save_stdout = sys.stdout
318 self.save_stderr = sys.stderr
319
Guido van Rossumcd6aab91996-06-28 17:28:51 +0000320 def restore_files(self):
Guido van Rossum3ec38f01998-03-26 22:10:50 +0000321 sys.stdin = self.save_stdin
322 sys.stdout = self.save_stdout
323 sys.stderr = self.save_stderr
Tim Peters0c9886d2001-01-15 01:18:21 +0000324
Guido van Rossume7b9fde1996-09-25 18:47:39 +0000325 def s_apply(self, func, args=(), kw=None):
Guido van Rossum3ec38f01998-03-26 22:10:50 +0000326 self.save_files()
327 try:
328 self.set_files()
329 if kw:
330 r = apply(func, args, kw)
331 else:
332 r = apply(func, args)
Guido van Rossum13833561995-08-07 20:19:27 +0000333 finally:
Guido van Rossum3ec38f01998-03-26 22:10:50 +0000334 self.restore_files()
Tim Peters0c9886d2001-01-15 01:18:21 +0000335
Guido van Rossum13833561995-08-07 20:19:27 +0000336 def s_exec(self, *args):
337 self.s_apply(self.r_exec, args)
Tim Peters0c9886d2001-01-15 01:18:21 +0000338
Guido van Rossum13833561995-08-07 20:19:27 +0000339 def s_eval(self, *args):
340 self.s_apply(self.r_eval, args)
Tim Peters0c9886d2001-01-15 01:18:21 +0000341
Guido van Rossum13833561995-08-07 20:19:27 +0000342 def s_execfile(self, *args):
343 self.s_apply(self.r_execfile, args)
Tim Peters0c9886d2001-01-15 01:18:21 +0000344
Guido van Rossum13833561995-08-07 20:19:27 +0000345 def s_import(self, *args):
346 self.s_apply(self.r_import, args)
Tim Peters0c9886d2001-01-15 01:18:21 +0000347
Guido van Rossum13833561995-08-07 20:19:27 +0000348 def s_reload(self, *args):
349 self.s_apply(self.r_reload, args)
Tim Peters0c9886d2001-01-15 01:18:21 +0000350
Guido van Rossumbebe5151995-08-09 02:32:08 +0000351 def s_unload(self, *args):
352 self.s_apply(self.r_unload, args)
Tim Peters0c9886d2001-01-15 01:18:21 +0000353
Guido van Rossum13833561995-08-07 20:19:27 +0000354 # Restricted open(...)
Tim Peters0c9886d2001-01-15 01:18:21 +0000355
Guido van Rossum13833561995-08-07 20:19:27 +0000356 def r_open(self, file, mode='r', buf=-1):
357 if mode not in ('r', 'rb'):
358 raise IOError, "can't open files for writing in restricted mode"
Guido van Rossumbebe5151995-08-09 02:32:08 +0000359 return open(file, mode, buf)
Guido van Rossum13833561995-08-07 20:19:27 +0000360
Guido van Rossumeeb64281998-07-09 13:52:38 +0000361 # Restricted version of sys.exc_info()
362
363 def r_exc_info(self):
364 ty, va, tr = sys.exc_info()
365 tr = None
366 return ty, va, tr
367
Guido van Rossum9a22de11995-01-12 12:29:47 +0000368
369def test():
Guido van Rossumeeb64281998-07-09 13:52:38 +0000370 import sys, getopt, traceback
371 opts, args = getopt.getopt(sys.argv[1:], 'vt:')
372 verbose = 0
373 trusted = []
374 for o, a in opts:
375 if o == '-v':
376 verbose = verbose+1
377 if o == '-t':
378 trusted.append(a)
379 r = RExec(verbose=verbose)
380 if trusted:
381 r.ok_builtin_modules = r.ok_builtin_modules + tuple(trusted)
382 if args:
383 r.modules['sys'].argv = args
384 r.modules['sys'].path.insert(0, os.path.dirname(args[0]))
385 else:
386 r.modules['sys'].path.insert(0, "")
387 fp = sys.stdin
388 if args and args[0] != '-':
Guido van Rossum3ec38f01998-03-26 22:10:50 +0000389 try:
Guido van Rossumeeb64281998-07-09 13:52:38 +0000390 fp = open(args[0])
391 except IOError, msg:
392 print "%s: can't open file %s" % (sys.argv[0], `args[0]`)
393 return 1
394 if fp.isatty():
395 print "*** RESTRICTED *** Python", sys.version
396 print sys.copyright
397 while 1:
Guido van Rossum3ec38f01998-03-26 22:10:50 +0000398 try:
Guido van Rossumeeb64281998-07-09 13:52:38 +0000399 try:
400 s = raw_input('>>> ')
401 except EOFError:
402 print
403 break
404 if s and s[0] != '#':
405 s = s + '\n'
406 c = compile(s, '<stdin>', 'single')
407 r.s_exec(c)
408 except SystemExit, n:
409 return n
410 except:
411 traceback.print_exc()
412 else:
413 text = fp.read()
414 fp.close()
415 c = compile(text, fp.name, 'exec')
416 try:
417 r.s_exec(c)
Guido van Rossum3ec38f01998-03-26 22:10:50 +0000418 except SystemExit, n:
Guido van Rossumeeb64281998-07-09 13:52:38 +0000419 return n
Guido van Rossum3ec38f01998-03-26 22:10:50 +0000420 except:
421 traceback.print_exc()
Guido van Rossumeeb64281998-07-09 13:52:38 +0000422 return 1
Guido van Rossum40d1ea31995-08-04 03:59:03 +0000423
Guido van Rossum9a22de11995-01-12 12:29:47 +0000424
425if __name__ == '__main__':
Guido van Rossumeeb64281998-07-09 13:52:38 +0000426 sys.exit(test())