blob: 6ad53b5d8354edcace25271cb28bc62f7f21b01a [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
Guido van Rossum9a22de11995-01-12 12:29:47 +000026
Guido van Rossum13833561995-08-07 20:19:27 +000027class FileBase:
28
Guido van Rossum3ec38f01998-03-26 22:10:50 +000029 ok_file_methods = ('fileno', 'flush', 'isatty', 'read', 'readline',
30 'readlines', 'seek', 'tell', 'write', 'writelines')
Guido van Rossum13833561995-08-07 20:19:27 +000031
32
33class FileWrapper(FileBase):
34
Guido van Rossum3ec38f01998-03-26 22:10:50 +000035 # XXX This is just like a Bastion -- should use that!
Guido van Rossumcd6aab91996-06-28 17:28:51 +000036
Guido van Rossum3ec38f01998-03-26 22:10:50 +000037 def __init__(self, f):
38 self.f = f
39 for m in self.ok_file_methods:
40 if not hasattr(self, m) and hasattr(f, m):
41 setattr(self, m, getattr(f, m))
42
43 def close(self):
44 self.flush()
Guido van Rossum13833561995-08-07 20:19:27 +000045
46
47TEMPLATE = """
48def %s(self, *args):
Guido van Rossum3ec38f01998-03-26 22:10:50 +000049 return apply(getattr(self.mod, self.name).%s, args)
Guido van Rossum13833561995-08-07 20:19:27 +000050"""
51
52class FileDelegate(FileBase):
53
Guido van Rossum3ec38f01998-03-26 22:10:50 +000054 def __init__(self, mod, name):
55 self.mod = mod
56 self.name = name
57
58 for m in FileBase.ok_file_methods + ('close',):
59 exec TEMPLATE % (m, m)
Guido van Rossum13833561995-08-07 20:19:27 +000060
61
Guido van Rossum40d1ea31995-08-04 03:59:03 +000062class RHooks(ihooks.Hooks):
Guido van Rossum9a22de11995-01-12 12:29:47 +000063
Guido van Rossumfdd45cb1996-05-28 23:07:17 +000064 def __init__(self, *args):
Guido van Rossum3ec38f01998-03-26 22:10:50 +000065 # Hacks to support both old and new interfaces:
66 # old interface was RHooks(rexec[, verbose])
67 # new interface is RHooks([verbose])
68 verbose = 0
69 rexec = None
70 if args and type(args[-1]) == type(0):
71 verbose = args[-1]
72 args = args[:-1]
73 if args and hasattr(args[0], '__class__'):
74 rexec = args[0]
75 args = args[1:]
76 if args:
77 raise TypeError, "too many arguments"
78 ihooks.Hooks.__init__(self, verbose)
79 self.rexec = rexec
Guido van Rossum9a22de11995-01-12 12:29:47 +000080
Guido van Rossumfdd45cb1996-05-28 23:07:17 +000081 def set_rexec(self, rexec):
Guido van Rossum3ec38f01998-03-26 22:10:50 +000082 # Called by RExec instance to complete initialization
83 self.rexec = rexec
Guido van Rossumfdd45cb1996-05-28 23:07:17 +000084
Guido van Rossum40d1ea31995-08-04 03:59:03 +000085 def is_builtin(self, name):
Guido van Rossum3ec38f01998-03-26 22:10:50 +000086 return self.rexec.is_builtin(name)
Guido van Rossum9a22de11995-01-12 12:29:47 +000087
Guido van Rossum40d1ea31995-08-04 03:59:03 +000088 def init_builtin(self, name):
Guido van Rossum3ec38f01998-03-26 22:10:50 +000089 m = __import__(name)
90 return self.rexec.copy_except(m, ())
Guido van Rossum9a22de11995-01-12 12:29:47 +000091
Guido van Rossum40d1ea31995-08-04 03:59:03 +000092 def init_frozen(self, name): raise SystemError, "don't use this"
93 def load_source(self, *args): raise SystemError, "don't use this"
94 def load_compiled(self, *args): raise SystemError, "don't use this"
Guido van Rossum8b3282b1998-06-29 20:32:57 +000095 def load_package(self, *args): raise SystemError, "don't use this"
Guido van Rossum40d1ea31995-08-04 03:59:03 +000096
Guido van Rossumfdd45cb1996-05-28 23:07:17 +000097 def load_dynamic(self, name, filename, file):
Guido van Rossum3ec38f01998-03-26 22:10:50 +000098 return self.rexec.load_dynamic(name, filename, file)
Guido van Rossum40d1ea31995-08-04 03:59:03 +000099
100 def add_module(self, name):
Guido van Rossum3ec38f01998-03-26 22:10:50 +0000101 return self.rexec.add_module(name)
Guido van Rossum40d1ea31995-08-04 03:59:03 +0000102
103 def modules_dict(self):
Guido van Rossum3ec38f01998-03-26 22:10:50 +0000104 return self.rexec.modules
Guido van Rossum40d1ea31995-08-04 03:59:03 +0000105
106 def default_path(self):
Guido van Rossum3ec38f01998-03-26 22:10:50 +0000107 return self.rexec.modules['sys'].path
Guido van Rossum40d1ea31995-08-04 03:59:03 +0000108
109
Guido van Rossumf07029e1998-09-21 14:53:26 +0000110# XXX Backwards compatibility
111RModuleLoader = ihooks.FancyModuleLoader
112RModuleImporter = ihooks.ModuleImporter
Guido van Rossum40d1ea31995-08-04 03:59:03 +0000113
114
115class RExec(ihooks._Verbose):
116
117 """Restricted Execution environment."""
118
Guido van Rossum3ec38f01998-03-26 22:10:50 +0000119 ok_path = tuple(sys.path) # That's a policy decision
Guido van Rossum40d1ea31995-08-04 03:59:03 +0000120
Guido van Rossume7b9fde1996-09-25 18:47:39 +0000121 ok_builtin_modules = ('audioop', 'array', 'binascii',
Guido van Rossum3ec38f01998-03-26 22:10:50 +0000122 'cmath', 'errno', 'imageop',
123 'marshal', 'math', 'md5', 'operator',
124 'parser', 'regex', 'pcre', 'rotor', 'select',
125 'strop', 'struct', 'time')
Guido van Rossum40d1ea31995-08-04 03:59:03 +0000126
127 ok_posix_names = ('error', 'fstat', 'listdir', 'lstat', 'readlink',
Guido van Rossum3ec38f01998-03-26 22:10:50 +0000128 'stat', 'times', 'uname', 'getpid', 'getppid',
129 'getcwd', 'getuid', 'getgid', 'geteuid', 'getegid')
Guido van Rossum40d1ea31995-08-04 03:59:03 +0000130
131 ok_sys_names = ('ps1', 'ps2', 'copyright', 'version',
Guido van Rossum3ec38f01998-03-26 22:10:50 +0000132 'platform', 'exit', 'maxint')
Guido van Rossum40d1ea31995-08-04 03:59:03 +0000133
Guido van Rossum13833561995-08-07 20:19:27 +0000134 nok_builtin_names = ('open', 'reload', '__import__')
Guido van Rossum40d1ea31995-08-04 03:59:03 +0000135
136 def __init__(self, hooks = None, verbose = 0):
Guido van Rossum3ec38f01998-03-26 22:10:50 +0000137 ihooks._Verbose.__init__(self, verbose)
138 # XXX There's a circular reference here:
139 self.hooks = hooks or RHooks(verbose)
140 self.hooks.set_rexec(self)
141 self.modules = {}
142 self.ok_dynamic_modules = self.ok_builtin_modules
143 list = []
144 for mname in self.ok_builtin_modules:
145 if mname in sys.builtin_module_names:
146 list.append(mname)
147 self.ok_builtin_modules = tuple(list)
148 self.set_trusted_path()
149 self.make_builtin()
150 self.make_initial_modules()
151 # make_sys must be last because it adds the already created
152 # modules to its builtin_module_names
153 self.make_sys()
154 self.loader = RModuleLoader(self.hooks, verbose)
155 self.importer = RModuleImporter(self.loader, verbose)
Guido van Rossum40d1ea31995-08-04 03:59:03 +0000156
Guido van Rossumfdd45cb1996-05-28 23:07:17 +0000157 def set_trusted_path(self):
Guido van Rossum3ec38f01998-03-26 22:10:50 +0000158 # 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)
Guido van Rossumfdd45cb1996-05-28 23:07:17 +0000161
162 def load_dynamic(self, name, filename, file):
Guido van Rossum3ec38f01998-03-26 22:10:50 +0000163 if name not in self.ok_dynamic_modules:
164 raise ImportError, "untrusted dynamic module: %s" % name
165 if sys.modules.has_key(name):
166 src = sys.modules[name]
167 else:
168 import imp
169 src = imp.load_dynamic(name, filename, file)
170 dst = self.copy_except(src, [])
171 return dst
Guido van Rossumfdd45cb1996-05-28 23:07:17 +0000172
Guido van Rossum40d1ea31995-08-04 03:59:03 +0000173 def make_initial_modules(self):
Guido van Rossum3ec38f01998-03-26 22:10:50 +0000174 self.make_main()
175 self.make_osname()
Guido van Rossum40d1ea31995-08-04 03:59:03 +0000176
177 # Helpers for RHooks
178
179 def is_builtin(self, mname):
Guido van Rossum3ec38f01998-03-26 22:10:50 +0000180 return mname in self.ok_builtin_modules
Guido van Rossum40d1ea31995-08-04 03:59:03 +0000181
182 # The make_* methods create specific built-in modules
183
184 def make_builtin(self):
Guido van Rossum3ec38f01998-03-26 22:10:50 +0000185 m = self.copy_except(__builtin__, self.nok_builtin_names)
186 m.__import__ = self.r_import
187 m.reload = self.r_reload
188 m.open = self.r_open
Guido van Rossum40d1ea31995-08-04 03:59:03 +0000189
190 def make_main(self):
Guido van Rossum3ec38f01998-03-26 22:10:50 +0000191 m = self.add_module('__main__')
Guido van Rossum40d1ea31995-08-04 03:59:03 +0000192
193 def make_osname(self):
Guido van Rossum3ec38f01998-03-26 22:10:50 +0000194 osname = os.name
195 src = __import__(osname)
196 dst = self.copy_only(src, self.ok_posix_names)
197 dst.environ = e = {}
198 for key, value in os.environ.items():
199 e[key] = value
Guido van Rossum40d1ea31995-08-04 03:59:03 +0000200
201 def make_sys(self):
Guido van Rossum3ec38f01998-03-26 22:10:50 +0000202 m = self.copy_only(sys, self.ok_sys_names)
203 m.modules = self.modules
204 m.argv = ['RESTRICTED']
205 m.path = map(None, self.ok_path)
Guido van Rossumeeb64281998-07-09 13:52:38 +0000206 m.exc_info = self.r_exc_info
Guido van Rossum3ec38f01998-03-26 22:10:50 +0000207 m = self.modules['sys']
208 l = self.modules.keys() + list(self.ok_builtin_modules)
209 l.sort()
210 m.builtin_module_names = tuple(l)
Guido van Rossum40d1ea31995-08-04 03:59:03 +0000211
212 # The copy_* methods copy existing modules with some changes
213
214 def copy_except(self, src, exceptions):
Guido van Rossum3ec38f01998-03-26 22:10:50 +0000215 dst = self.copy_none(src)
216 for name in dir(src):
217 setattr(dst, name, getattr(src, name))
218 for name in exceptions:
219 try:
220 delattr(dst, name)
221 except AttributeError:
222 pass
223 return dst
Guido van Rossum40d1ea31995-08-04 03:59:03 +0000224
225 def copy_only(self, src, names):
Guido van Rossum3ec38f01998-03-26 22:10:50 +0000226 dst = self.copy_none(src)
227 for name in names:
228 try:
229 value = getattr(src, name)
230 except AttributeError:
231 continue
232 setattr(dst, name, value)
233 return dst
Guido van Rossum40d1ea31995-08-04 03:59:03 +0000234
235 def copy_none(self, src):
Guido van Rossum1f40cd61998-06-09 21:33:44 +0000236 m = self.add_module(src.__name__)
237 m.__doc__ = src.__doc__
238 return m
Guido van Rossum40d1ea31995-08-04 03:59:03 +0000239
240 # Add a module -- return an existing module or create one
241
242 def add_module(self, mname):
Guido van Rossum3ec38f01998-03-26 22:10:50 +0000243 if self.modules.has_key(mname):
244 return self.modules[mname]
245 self.modules[mname] = m = self.hooks.new_module(mname)
246 m.__builtins__ = self.modules['__builtin__']
247 return m
Guido van Rossum9a22de11995-01-12 12:29:47 +0000248
Guido van Rossum40d1ea31995-08-04 03:59:03 +0000249 # The r* methods are public interfaces
Guido van Rossum9a22de11995-01-12 12:29:47 +0000250
Guido van Rossum40d1ea31995-08-04 03:59:03 +0000251 def r_exec(self, code):
Guido van Rossum3ec38f01998-03-26 22:10:50 +0000252 m = self.add_module('__main__')
253 exec code in m.__dict__
Guido van Rossum9a22de11995-01-12 12:29:47 +0000254
Guido van Rossum40d1ea31995-08-04 03:59:03 +0000255 def r_eval(self, code):
Guido van Rossum3ec38f01998-03-26 22:10:50 +0000256 m = self.add_module('__main__')
257 return eval(code, m.__dict__)
Guido van Rossum9a22de11995-01-12 12:29:47 +0000258
Guido van Rossum40d1ea31995-08-04 03:59:03 +0000259 def r_execfile(self, file):
Guido van Rossum3ec38f01998-03-26 22:10:50 +0000260 m = self.add_module('__main__')
261 return execfile(file, m.__dict__)
Guido van Rossum9a22de11995-01-12 12:29:47 +0000262
Guido van Rossum40d1ea31995-08-04 03:59:03 +0000263 def r_import(self, mname, globals={}, locals={}, fromlist=[]):
Guido van Rossum3ec38f01998-03-26 22:10:50 +0000264 return self.importer.import_module(mname, globals, locals, fromlist)
Guido van Rossum9a22de11995-01-12 12:29:47 +0000265
Guido van Rossum13833561995-08-07 20:19:27 +0000266 def r_reload(self, m):
267 return self.importer.reload(m)
Guido van Rossumbebe5151995-08-09 02:32:08 +0000268
269 def r_unload(self, m):
270 return self.importer.unload(m)
Guido van Rossum13833561995-08-07 20:19:27 +0000271
272 # The s_* methods are similar but also swap std{in,out,err}
273
Guido van Rossumcd6aab91996-06-28 17:28:51 +0000274 def make_delegate_files(self):
Guido van Rossum13833561995-08-07 20:19:27 +0000275 s = self.modules['sys']
Guido van Rossum3ec38f01998-03-26 22:10:50 +0000276 self.delegate_stdin = FileDelegate(s, 'stdin')
277 self.delegate_stdout = FileDelegate(s, 'stdout')
278 self.delegate_stderr = FileDelegate(s, 'stderr')
Guido van Rossumcd6aab91996-06-28 17:28:51 +0000279 self.restricted_stdin = FileWrapper(sys.stdin)
280 self.restricted_stdout = FileWrapper(sys.stdout)
281 self.restricted_stderr = FileWrapper(sys.stderr)
282
283 def set_files(self):
Guido van Rossum3ec38f01998-03-26 22:10:50 +0000284 if not hasattr(self, 'save_stdin'):
285 self.save_files()
286 if not hasattr(self, 'delegate_stdin'):
287 self.make_delegate_files()
Guido van Rossumcd6aab91996-06-28 17:28:51 +0000288 s = self.modules['sys']
Guido van Rossum3ec38f01998-03-26 22:10:50 +0000289 s.stdin = self.restricted_stdin
290 s.stdout = self.restricted_stdout
291 s.stderr = self.restricted_stderr
292 sys.stdin = self.delegate_stdin
293 sys.stdout = self.delegate_stdout
294 sys.stderr = self.delegate_stderr
Guido van Rossumcd6aab91996-06-28 17:28:51 +0000295
296 def reset_files(self):
Guido van Rossum3ec38f01998-03-26 22:10:50 +0000297 self.restore_files()
Guido van Rossumcd6aab91996-06-28 17:28:51 +0000298 s = self.modules['sys']
Guido van Rossum3ec38f01998-03-26 22:10:50 +0000299 self.restricted_stdin = s.stdin
300 self.restricted_stdout = s.stdout
301 self.restricted_stderr = s.stderr
302
Guido van Rossum13833561995-08-07 20:19:27 +0000303
304 def save_files(self):
305 self.save_stdin = sys.stdin
306 self.save_stdout = sys.stdout
307 self.save_stderr = sys.stderr
308
Guido van Rossumcd6aab91996-06-28 17:28:51 +0000309 def restore_files(self):
Guido van Rossum3ec38f01998-03-26 22:10:50 +0000310 sys.stdin = self.save_stdin
311 sys.stdout = self.save_stdout
312 sys.stderr = self.save_stderr
Guido van Rossum13833561995-08-07 20:19:27 +0000313
Guido van Rossume7b9fde1996-09-25 18:47:39 +0000314 def s_apply(self, func, args=(), kw=None):
Guido van Rossum3ec38f01998-03-26 22:10:50 +0000315 self.save_files()
316 try:
317 self.set_files()
318 if kw:
319 r = apply(func, args, kw)
320 else:
321 r = apply(func, args)
Guido van Rossum13833561995-08-07 20:19:27 +0000322 finally:
Guido van Rossum3ec38f01998-03-26 22:10:50 +0000323 self.restore_files()
Guido van Rossum13833561995-08-07 20:19:27 +0000324
325 def s_exec(self, *args):
326 self.s_apply(self.r_exec, args)
327
328 def s_eval(self, *args):
329 self.s_apply(self.r_eval, args)
330
331 def s_execfile(self, *args):
332 self.s_apply(self.r_execfile, args)
333
334 def s_import(self, *args):
335 self.s_apply(self.r_import, args)
336
337 def s_reload(self, *args):
338 self.s_apply(self.r_reload, args)
339
Guido van Rossumbebe5151995-08-09 02:32:08 +0000340 def s_unload(self, *args):
341 self.s_apply(self.r_unload, args)
342
Guido van Rossum13833561995-08-07 20:19:27 +0000343 # Restricted open(...)
344
345 def r_open(self, file, mode='r', buf=-1):
346 if mode not in ('r', 'rb'):
347 raise IOError, "can't open files for writing in restricted mode"
Guido van Rossumbebe5151995-08-09 02:32:08 +0000348 return open(file, mode, buf)
Guido van Rossum13833561995-08-07 20:19:27 +0000349
Guido van Rossumeeb64281998-07-09 13:52:38 +0000350 # Restricted version of sys.exc_info()
351
352 def r_exc_info(self):
353 ty, va, tr = sys.exc_info()
354 tr = None
355 return ty, va, tr
356
Guido van Rossum9a22de11995-01-12 12:29:47 +0000357
358def test():
Guido van Rossumeeb64281998-07-09 13:52:38 +0000359 import sys, getopt, traceback
360 opts, args = getopt.getopt(sys.argv[1:], 'vt:')
361 verbose = 0
362 trusted = []
363 for o, a in opts:
364 if o == '-v':
365 verbose = verbose+1
366 if o == '-t':
367 trusted.append(a)
368 r = RExec(verbose=verbose)
369 if trusted:
370 r.ok_builtin_modules = r.ok_builtin_modules + tuple(trusted)
371 if args:
372 r.modules['sys'].argv = args
373 r.modules['sys'].path.insert(0, os.path.dirname(args[0]))
374 else:
375 r.modules['sys'].path.insert(0, "")
376 fp = sys.stdin
377 if args and args[0] != '-':
Guido van Rossum3ec38f01998-03-26 22:10:50 +0000378 try:
Guido van Rossumeeb64281998-07-09 13:52:38 +0000379 fp = open(args[0])
380 except IOError, msg:
381 print "%s: can't open file %s" % (sys.argv[0], `args[0]`)
382 return 1
383 if fp.isatty():
384 print "*** RESTRICTED *** Python", sys.version
385 print sys.copyright
386 while 1:
Guido van Rossum3ec38f01998-03-26 22:10:50 +0000387 try:
Guido van Rossumeeb64281998-07-09 13:52:38 +0000388 try:
389 s = raw_input('>>> ')
390 except EOFError:
391 print
392 break
393 if s and s[0] != '#':
394 s = s + '\n'
395 c = compile(s, '<stdin>', 'single')
396 r.s_exec(c)
397 except SystemExit, n:
398 return n
399 except:
400 traceback.print_exc()
401 else:
402 text = fp.read()
403 fp.close()
404 c = compile(text, fp.name, 'exec')
405 try:
406 r.s_exec(c)
Guido van Rossum3ec38f01998-03-26 22:10:50 +0000407 except SystemExit, n:
Guido van Rossumeeb64281998-07-09 13:52:38 +0000408 return n
Guido van Rossum3ec38f01998-03-26 22:10:50 +0000409 except:
410 traceback.print_exc()
Guido van Rossumeeb64281998-07-09 13:52:38 +0000411 return 1
Guido van Rossum40d1ea31995-08-04 03:59:03 +0000412
Guido van Rossum9a22de11995-01-12 12:29:47 +0000413
414if __name__ == '__main__':
Guido van Rossumeeb64281998-07-09 13:52:38 +0000415 sys.exit(test())