blob: 316fc1ca34d4a8bc50bcecbaea3bc2254203578f [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 Rossum40d1ea31995-08-04 03:59:03 +00003The class RExec exports methods rexec(), reval(), rexecfile(), and
4import_module(), which correspond roughly to the built-in operations
5exec, 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 ...")?)
17- r_reload should reload from same location (that's one for ihooks?)
18
Guido van Rossum40d1ea31995-08-04 03:59:03 +000019"""
20
21
Guido van Rossum9a22de11995-01-12 12:29:47 +000022import sys
Guido van Rossum40d1ea31995-08-04 03:59:03 +000023import __builtin__
24import os
25import marshal
26import ihooks
Guido van Rossum9a22de11995-01-12 12:29:47 +000027
Guido van Rossum9a22de11995-01-12 12:29:47 +000028
Guido van Rossum13833561995-08-07 20:19:27 +000029class FileBase:
30
31 ok_file_methods = ('fileno', 'flush', 'isatty', 'read', 'readline',
32 'readlines', 'seek', 'tell', 'write', 'writelines')
33
34
35class FileWrapper(FileBase):
36
37 def __init__(self, f):
38 self.f = f
39 for m in self.ok_file_methods:
40 if not hasattr(self, m):
41 setattr(self, m, getattr(f, m))
42
43 def close(f):
44 self.flush()
45
46
47TEMPLATE = """
48def %s(self, *args):
49 return apply(getattr(self.mod, self.name).%s, args)
50"""
51
52class FileDelegate(FileBase):
53
54 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)
60
61
Guido van Rossum40d1ea31995-08-04 03:59:03 +000062class RHooks(ihooks.Hooks):
Guido van Rossum9a22de11995-01-12 12:29:47 +000063
Guido van Rossum40d1ea31995-08-04 03:59:03 +000064 def __init__(self, rexec, verbose=0):
65 ihooks.Hooks.__init__(self, verbose)
66 self.rexec = rexec
Guido van Rossum9a22de11995-01-12 12:29:47 +000067
Guido van Rossum40d1ea31995-08-04 03:59:03 +000068 def is_builtin(self, name):
69 return self.rexec.is_builtin(name)
Guido van Rossum9a22de11995-01-12 12:29:47 +000070
Guido van Rossum40d1ea31995-08-04 03:59:03 +000071 def init_builtin(self, name):
72 m = __import__(name)
73 return self.rexec.copy_except(m, ())
Guido van Rossum9a22de11995-01-12 12:29:47 +000074
Guido van Rossum40d1ea31995-08-04 03:59:03 +000075 def init_frozen(self, name): raise SystemError, "don't use this"
76 def load_source(self, *args): raise SystemError, "don't use this"
77 def load_compiled(self, *args): raise SystemError, "don't use this"
78
79 def load_dynamic(self, *args):
80 raise ImportError, "import of dynamically loaded modules not allowed"
81
82 def add_module(self, name):
83 return self.rexec.add_module(name)
84
85 def modules_dict(self):
86 return self.rexec.modules
87
88 def default_path(self):
89 return self.rexec.modules['sys'].path
90
91
92class RModuleLoader(ihooks.FancyModuleLoader):
93
Guido van Rossum13833561995-08-07 20:19:27 +000094 def load_module(self, name, stuff):
95 file, filename, info = stuff
96 m = ihooks.FancyModuleLoader.load_module(self, name, stuff)
97 m.__filename__ = filename
98 return m
Guido van Rossum40d1ea31995-08-04 03:59:03 +000099
100
101class RModuleImporter(ihooks.ModuleImporter):
102
Guido van Rossum13833561995-08-07 20:19:27 +0000103 def reload(self, module, path=None):
104 if path is None and hasattr(module, '__filename__'):
105 path = [module.__filename__]
106 return ihooks.ModuleImporter.reload(self, module, path)
Guido van Rossum40d1ea31995-08-04 03:59:03 +0000107
108
109class RExec(ihooks._Verbose):
110
111 """Restricted Execution environment."""
112
113 ok_path = tuple(sys.path) # That's a policy decision
114
115 ok_builtin_modules = ('array', 'audioop', 'imageop', 'marshal', 'math',
116 'md5', 'parser', 'regex', 'rotor', 'select',
117 'strop', 'struct', 'time')
118
119 ok_posix_names = ('error', 'fstat', 'listdir', 'lstat', 'readlink',
120 'stat', 'times', 'uname', 'getpid', 'getppid',
121 'getcwd', 'getuid', 'getgid', 'geteuid', 'getegid')
122
123 ok_sys_names = ('ps1', 'ps2', 'copyright', 'version',
124 'platform', 'exit', 'maxint')
125
Guido van Rossum13833561995-08-07 20:19:27 +0000126 nok_builtin_names = ('open', 'reload', '__import__')
Guido van Rossum40d1ea31995-08-04 03:59:03 +0000127
128 def __init__(self, hooks = None, verbose = 0):
129 ihooks._Verbose.__init__(self, verbose)
130 # XXX There's a circular reference here:
131 self.hooks = hooks or RHooks(self, verbose)
132 self.modules = {}
133 self.ok_builtin_modules = map(None, filter(
134 lambda mname: mname in sys.builtin_module_names,
135 self.ok_builtin_modules))
136 self.make_builtin()
137 self.make_initial_modules()
138 # make_sys must be last because it adds the already created
139 # modules to its builtin_module_names
140 self.make_sys()
141 self.loader = RModuleLoader(self.hooks, verbose)
142 self.importer = RModuleImporter(self.loader, verbose)
143
144 def make_initial_modules(self):
145 self.make_main()
146 self.make_osname()
147
148 # Helpers for RHooks
149
150 def is_builtin(self, mname):
151 return mname in self.ok_builtin_modules
152
153 # The make_* methods create specific built-in modules
154
155 def make_builtin(self):
156 m = self.copy_except(__builtin__, self.nok_builtin_names)
157 m.__import__ = self.r_import
Guido van Rossum13833561995-08-07 20:19:27 +0000158 m.reload = self.r_reload
159 m.open = self.r_open
Guido van Rossum40d1ea31995-08-04 03:59:03 +0000160
161 def make_main(self):
162 m = self.add_module('__main__')
163
164 def make_osname(self):
165 osname = os.name
166 src = __import__(osname)
167 dst = self.copy_only(src, self.ok_posix_names)
168 dst.environ = e = {}
169 for key, value in os.environ.items():
170 e[key] = value
171
172 def make_sys(self):
173 m = self.copy_only(sys, self.ok_sys_names)
174 m.modules = self.modules
175 m.argv = ['RESTRICTED']
176 m.path = map(None, self.ok_path)
177 m = self.modules['sys']
178 m.builtin_module_names = \
179 self.modules.keys() + self.ok_builtin_modules
180 m.builtin_module_names.sort()
181
182 # The copy_* methods copy existing modules with some changes
183
184 def copy_except(self, src, exceptions):
185 dst = self.copy_none(src)
186 for name in dir(src):
187 if name not in exceptions:
188 setattr(dst, name, getattr(src, name))
189 return dst
190
191 def copy_only(self, src, names):
192 dst = self.copy_none(src)
193 for name in names:
194 try:
195 value = getattr(src, name)
196 except AttributeError:
197 continue
198 setattr(dst, name, value)
199 return dst
200
201 def copy_none(self, src):
202 return self.add_module(src.__name__)
203
204 # Add a module -- return an existing module or create one
205
206 def add_module(self, mname):
207 if self.modules.has_key(mname):
208 return self.modules[mname]
209 self.modules[mname] = m = self.hooks.new_module(mname)
210 m.__builtins__ = self.modules['__builtin__']
Guido van Rossum9a22de11995-01-12 12:29:47 +0000211 return m
212
Guido van Rossum40d1ea31995-08-04 03:59:03 +0000213 # The r* methods are public interfaces
Guido van Rossum9a22de11995-01-12 12:29:47 +0000214
Guido van Rossum40d1ea31995-08-04 03:59:03 +0000215 def r_exec(self, code):
216 m = self.add_module('__main__')
217 exec code in m.__dict__
Guido van Rossum9a22de11995-01-12 12:29:47 +0000218
Guido van Rossum40d1ea31995-08-04 03:59:03 +0000219 def r_eval(self, code):
220 m = self.add_module('__main__')
221 return eval(code, m.__dict__)
Guido van Rossum9a22de11995-01-12 12:29:47 +0000222
Guido van Rossum40d1ea31995-08-04 03:59:03 +0000223 def r_execfile(self, file):
224 m = self.add_module('__main__')
225 return execfile(file, m.__dict__)
Guido van Rossum9a22de11995-01-12 12:29:47 +0000226
Guido van Rossum40d1ea31995-08-04 03:59:03 +0000227 def r_import(self, mname, globals={}, locals={}, fromlist=[]):
228 return self.importer.import_module(mname, globals, locals, fromlist)
Guido van Rossum9a22de11995-01-12 12:29:47 +0000229
Guido van Rossum13833561995-08-07 20:19:27 +0000230 def r_reload(self, m):
231 return self.importer.reload(m)
232
233 # The s_* methods are similar but also swap std{in,out,err}
234
235 def set_files(self):
236 s = self.modules['sys']
237 s.stdin = FileWrapper(sys.stdin)
238 s.stdout = FileWrapper(sys.stdout)
239 s.stderr = FileWrapper(sys.stderr)
240 sys.stdin = FileDelegate(s, 'stdin')
241 sys.stdout = FileDelegate(s, 'stdout')
242 sys.stderr = FileDelegate(s, 'stderr')
243
244 def save_files(self):
245 self.save_stdin = sys.stdin
246 self.save_stdout = sys.stdout
247 self.save_stderr = sys.stderr
248
249 def restore_files(files):
250 sys.stdin = self.save_sydin
251 sys.stdout = self.save_stdout
252 sys.stderr = self.save_stderr
253
254 def s_apply(self, func, *args, **kw):
255 self.save_files()
256 try:
257 self.set_files()
258 r = apply(func, args, kw)
259 finally:
260 self.restore_files()
261
262 def s_exec(self, *args):
263 self.s_apply(self.r_exec, args)
264
265 def s_eval(self, *args):
266 self.s_apply(self.r_eval, args)
267
268 def s_execfile(self, *args):
269 self.s_apply(self.r_execfile, args)
270
271 def s_import(self, *args):
272 self.s_apply(self.r_import, args)
273
274 def s_reload(self, *args):
275 self.s_apply(self.r_reload, args)
276
277 # Restricted open(...)
278
279 def r_open(self, file, mode='r', buf=-1):
280 if mode not in ('r', 'rb'):
281 raise IOError, "can't open files for writing in restricted mode"
282 return open(file, 'r', buf)
283
Guido van Rossum9a22de11995-01-12 12:29:47 +0000284
285def test():
Guido van Rossum40d1ea31995-08-04 03:59:03 +0000286 import traceback
287 r = RExec(None, '-v' in sys.argv[1:])
288 print "*** RESTRICTED *** Python", sys.version
289 print sys.copyright
290 while 1:
291 try:
292 try:
293 s = raw_input('>>> ')
294 except EOFError:
295 print
296 break
297 if s and s[0] != '#':
298 s = s + '\n'
299 c = compile(s, '<stdin>', 'single')
300 r.r_exec(c)
301 except SystemExit, n:
302 sys.exit(n)
303 except:
304 traceback.print_exc()
305
Guido van Rossum9a22de11995-01-12 12:29:47 +0000306
307if __name__ == '__main__':
Guido van Rossum40d1ea31995-08-04 03:59:03 +0000308 test()