blob: 860aab2456f88a30d8325b264de68c1b24d7ad25 [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
24import marshal
25import ihooks
Guido van Rossum9a22de11995-01-12 12:29:47 +000026
Guido van Rossum9a22de11995-01-12 12:29:47 +000027
Guido van Rossum13833561995-08-07 20:19:27 +000028class FileBase:
29
30 ok_file_methods = ('fileno', 'flush', 'isatty', 'read', 'readline',
31 'readlines', 'seek', 'tell', 'write', 'writelines')
32
33
34class FileWrapper(FileBase):
35
Guido van Rossumcd6aab91996-06-28 17:28:51 +000036 # XXX This is just like a Bastion -- should use that!
37
Guido van Rossum13833561995-08-07 20:19:27 +000038 def __init__(self, f):
39 self.f = f
40 for m in self.ok_file_methods:
41 if not hasattr(self, m):
42 setattr(self, m, getattr(f, m))
43
44 def close(f):
45 self.flush()
46
47
48TEMPLATE = """
49def %s(self, *args):
50 return apply(getattr(self.mod, self.name).%s, args)
51"""
52
53class FileDelegate(FileBase):
54
55 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)
61
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):
66 # 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"
Guido van Rossum40d1ea31995-08-04 03:59:03 +000079 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):
83 # Called by RExec instance to complete initialization
84 self.rexec = rexec
85
Guido van Rossum40d1ea31995-08-04 03:59:03 +000086 def is_builtin(self, name):
87 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):
90 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"
96
Guido van Rossumfdd45cb1996-05-28 23:07:17 +000097 def load_dynamic(self, name, filename, file):
98 return self.rexec.load_dynamic(name, filename, file)
Guido van Rossum40d1ea31995-08-04 03:59:03 +000099
100 def add_module(self, name):
101 return self.rexec.add_module(name)
102
103 def modules_dict(self):
104 return self.rexec.modules
105
106 def default_path(self):
107 return self.rexec.modules['sys'].path
108
109
110class RModuleLoader(ihooks.FancyModuleLoader):
111
Guido van Rossum13833561995-08-07 20:19:27 +0000112 def load_module(self, name, stuff):
113 file, filename, info = stuff
114 m = ihooks.FancyModuleLoader.load_module(self, name, stuff)
115 m.__filename__ = filename
116 return m
Guido van Rossum40d1ea31995-08-04 03:59:03 +0000117
118
119class RModuleImporter(ihooks.ModuleImporter):
120
Guido van Rossum13833561995-08-07 20:19:27 +0000121 def reload(self, module, path=None):
122 if path is None and hasattr(module, '__filename__'):
Guido van Rossum18596001995-08-10 19:40:39 +0000123 head, tail = os.path.split(module.__filename__)
Guido van Rossum1035a891995-08-11 13:56:04 +0000124 path = [os.path.join(head, '')]
Guido van Rossum13833561995-08-07 20:19:27 +0000125 return ihooks.ModuleImporter.reload(self, module, path)
Guido van Rossum40d1ea31995-08-04 03:59:03 +0000126
127
128class RExec(ihooks._Verbose):
129
130 """Restricted Execution environment."""
131
132 ok_path = tuple(sys.path) # That's a policy decision
133
Guido van Rossumbebe5151995-08-09 02:32:08 +0000134 ok_builtin_modules = ('array', 'binascii', 'audioop', 'imageop',
135 'marshal', 'math',
Guido van Rossum40d1ea31995-08-04 03:59:03 +0000136 'md5', 'parser', 'regex', 'rotor', 'select',
137 'strop', 'struct', 'time')
138
139 ok_posix_names = ('error', 'fstat', 'listdir', 'lstat', 'readlink',
140 'stat', 'times', 'uname', 'getpid', 'getppid',
141 'getcwd', 'getuid', 'getgid', 'geteuid', 'getegid')
142
143 ok_sys_names = ('ps1', 'ps2', 'copyright', 'version',
144 'platform', 'exit', 'maxint')
145
Guido van Rossum13833561995-08-07 20:19:27 +0000146 nok_builtin_names = ('open', 'reload', '__import__')
Guido van Rossum40d1ea31995-08-04 03:59:03 +0000147
148 def __init__(self, hooks = None, verbose = 0):
149 ihooks._Verbose.__init__(self, verbose)
150 # XXX There's a circular reference here:
Guido van Rossumfdd45cb1996-05-28 23:07:17 +0000151 self.hooks = hooks or RHooks(verbose)
152 self.hooks.set_rexec(self)
Guido van Rossum40d1ea31995-08-04 03:59:03 +0000153 self.modules = {}
Guido van Rossumfdd45cb1996-05-28 23:07:17 +0000154 self.ok_dynamic_modules = self.ok_builtin_modules
155 list = []
156 for mname in self.ok_builtin_modules:
157 if mname in sys.builtin_module_names:
158 list.append(mname)
159 self.ok_builtin_modules = list
160 self.set_trusted_path()
Guido van Rossum40d1ea31995-08-04 03:59:03 +0000161 self.make_builtin()
162 self.make_initial_modules()
163 # make_sys must be last because it adds the already created
164 # modules to its builtin_module_names
165 self.make_sys()
166 self.loader = RModuleLoader(self.hooks, verbose)
167 self.importer = RModuleImporter(self.loader, verbose)
168
Guido van Rossumfdd45cb1996-05-28 23:07:17 +0000169 def set_trusted_path(self):
170 # Set the path from which dynamic modules may be loaded.
171 # Those dynamic modules must also occur in ok_builtin_modules
172 self.trusted_path = filter(os.path.isabs, sys.path)
173
174 def load_dynamic(self, name, filename, file):
175 if name not in self.ok_dynamic_modules:
176 raise ImportError, "untrusted dynamic module: %s" % name
177 if sys.modules.has_key(name):
Guido van Rossum3ada87a1996-05-28 23:34:10 +0000178 src = sys.modules[name]
Guido van Rossumfdd45cb1996-05-28 23:07:17 +0000179 else:
180 import imp
181 src = imp.load_dynamic(name, filename, file)
182 dst = self.copy_except(src, [])
183 return dst
184
Guido van Rossum40d1ea31995-08-04 03:59:03 +0000185 def make_initial_modules(self):
186 self.make_main()
187 self.make_osname()
188
189 # Helpers for RHooks
190
191 def is_builtin(self, mname):
192 return mname in self.ok_builtin_modules
193
194 # The make_* methods create specific built-in modules
195
196 def make_builtin(self):
197 m = self.copy_except(__builtin__, self.nok_builtin_names)
198 m.__import__ = self.r_import
Guido van Rossum13833561995-08-07 20:19:27 +0000199 m.reload = self.r_reload
200 m.open = self.r_open
Guido van Rossum40d1ea31995-08-04 03:59:03 +0000201
202 def make_main(self):
203 m = self.add_module('__main__')
204
205 def make_osname(self):
206 osname = os.name
207 src = __import__(osname)
208 dst = self.copy_only(src, self.ok_posix_names)
209 dst.environ = e = {}
210 for key, value in os.environ.items():
211 e[key] = value
212
213 def make_sys(self):
214 m = self.copy_only(sys, self.ok_sys_names)
215 m.modules = self.modules
216 m.argv = ['RESTRICTED']
217 m.path = map(None, self.ok_path)
218 m = self.modules['sys']
219 m.builtin_module_names = \
220 self.modules.keys() + self.ok_builtin_modules
221 m.builtin_module_names.sort()
222
223 # The copy_* methods copy existing modules with some changes
224
225 def copy_except(self, src, exceptions):
226 dst = self.copy_none(src)
227 for name in dir(src):
Guido van Rossumfdd45cb1996-05-28 23:07:17 +0000228 setattr(dst, name, getattr(src, name))
229 for name in exceptions:
230 try:
231 delattr(dst, name)
Guido van Rossum63f0cf01996-08-20 20:25:08 +0000232 except AttributeError:
Guido van Rossumfdd45cb1996-05-28 23:07:17 +0000233 pass
Guido van Rossum40d1ea31995-08-04 03:59:03 +0000234 return dst
235
236 def copy_only(self, src, names):
237 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
245
246 def copy_none(self, src):
247 return self.add_module(src.__name__)
248
249 # Add a module -- return an existing module or create one
250
251 def add_module(self, mname):
252 if self.modules.has_key(mname):
253 return self.modules[mname]
254 self.modules[mname] = m = self.hooks.new_module(mname)
255 m.__builtins__ = self.modules['__builtin__']
Guido van Rossum9a22de11995-01-12 12:29:47 +0000256 return m
257
Guido van Rossum40d1ea31995-08-04 03:59:03 +0000258 # The r* methods are public interfaces
Guido van Rossum9a22de11995-01-12 12:29:47 +0000259
Guido van Rossum40d1ea31995-08-04 03:59:03 +0000260 def r_exec(self, code):
261 m = self.add_module('__main__')
262 exec code in m.__dict__
Guido van Rossum9a22de11995-01-12 12:29:47 +0000263
Guido van Rossum40d1ea31995-08-04 03:59:03 +0000264 def r_eval(self, code):
265 m = self.add_module('__main__')
266 return eval(code, m.__dict__)
Guido van Rossum9a22de11995-01-12 12:29:47 +0000267
Guido van Rossum40d1ea31995-08-04 03:59:03 +0000268 def r_execfile(self, file):
269 m = self.add_module('__main__')
270 return execfile(file, m.__dict__)
Guido van Rossum9a22de11995-01-12 12:29:47 +0000271
Guido van Rossum40d1ea31995-08-04 03:59:03 +0000272 def r_import(self, mname, globals={}, locals={}, fromlist=[]):
273 return self.importer.import_module(mname, globals, locals, fromlist)
Guido van Rossum9a22de11995-01-12 12:29:47 +0000274
Guido van Rossum13833561995-08-07 20:19:27 +0000275 def r_reload(self, m):
276 return self.importer.reload(m)
Guido van Rossumbebe5151995-08-09 02:32:08 +0000277
278 def r_unload(self, m):
279 return self.importer.unload(m)
Guido van Rossum13833561995-08-07 20:19:27 +0000280
281 # The s_* methods are similar but also swap std{in,out,err}
282
Guido van Rossumcd6aab91996-06-28 17:28:51 +0000283 def make_delegate_files(self):
Guido van Rossum13833561995-08-07 20:19:27 +0000284 s = self.modules['sys']
Guido van Rossumcd6aab91996-06-28 17:28:51 +0000285 self.delegate_stdin = FileDelegate(s, 'stdin')
286 self.delegate_stdout = FileDelegate(s, 'stdout')
287 self.delegate_stderr = FileDelegate(s, 'stderr')
288 self.restricted_stdin = FileWrapper(sys.stdin)
289 self.restricted_stdout = FileWrapper(sys.stdout)
290 self.restricted_stderr = FileWrapper(sys.stderr)
291
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_stdout
301 sys.stdin = self.delegate_stdin
302 sys.stdout = self.delegate_stdout
303 sys.stderr = self.delegate_stderr
304
305 def reset_files(self):
306 self.restore_files()
307 s = self.modules['sys']
308 self.restricted_stdin = s.stdin
309 self.restricted_stdout = s.stdout
310 self.restricted_stdout = s.stderr
311
Guido van Rossum13833561995-08-07 20:19:27 +0000312
313 def save_files(self):
314 self.save_stdin = sys.stdin
315 self.save_stdout = sys.stdout
316 self.save_stderr = sys.stderr
317
Guido van Rossumcd6aab91996-06-28 17:28:51 +0000318 def restore_files(self):
319 sys.stdin = self.save_stdin
Guido van Rossum13833561995-08-07 20:19:27 +0000320 sys.stdout = self.save_stdout
321 sys.stderr = self.save_stderr
322
323 def s_apply(self, func, *args, **kw):
324 self.save_files()
325 try:
326 self.set_files()
327 r = apply(func, args, kw)
328 finally:
329 self.restore_files()
330
331 def s_exec(self, *args):
332 self.s_apply(self.r_exec, args)
333
334 def s_eval(self, *args):
335 self.s_apply(self.r_eval, args)
336
337 def s_execfile(self, *args):
338 self.s_apply(self.r_execfile, args)
339
340 def s_import(self, *args):
341 self.s_apply(self.r_import, args)
342
343 def s_reload(self, *args):
344 self.s_apply(self.r_reload, args)
345
Guido van Rossumbebe5151995-08-09 02:32:08 +0000346 def s_unload(self, *args):
347 self.s_apply(self.r_unload, args)
348
Guido van Rossum13833561995-08-07 20:19:27 +0000349 # Restricted open(...)
350
351 def r_open(self, file, mode='r', buf=-1):
352 if mode not in ('r', 'rb'):
353 raise IOError, "can't open files for writing in restricted mode"
Guido van Rossumbebe5151995-08-09 02:32:08 +0000354 return open(file, mode, buf)
Guido van Rossum13833561995-08-07 20:19:27 +0000355
Guido van Rossum9a22de11995-01-12 12:29:47 +0000356
357def test():
Guido van Rossum40d1ea31995-08-04 03:59:03 +0000358 import traceback
Guido van Rossum63f0cf01996-08-20 20:25:08 +0000359 r = RExec(verbose=('-v' in sys.argv[1:]))
Guido van Rossum40d1ea31995-08-04 03:59:03 +0000360 print "*** RESTRICTED *** Python", sys.version
361 print sys.copyright
362 while 1:
363 try:
364 try:
365 s = raw_input('>>> ')
366 except EOFError:
367 print
368 break
369 if s and s[0] != '#':
370 s = s + '\n'
371 c = compile(s, '<stdin>', 'single')
372 r.r_exec(c)
373 except SystemExit, n:
374 sys.exit(n)
375 except:
376 traceback.print_exc()
377
Guido van Rossum9a22de11995-01-12 12:29:47 +0000378
379if __name__ == '__main__':
Guido van Rossum40d1ea31995-08-04 03:59:03 +0000380 test()