Debian Codegraph @

rpython/translator/sandbox/sandlib.py

raw symbols SCIP
1 """
2 A Python library to execute and communicate with a subprocess that
3 was translated from RPython code with --sandbox. This library is
4 for the outer process, which can run CPython or PyPy.
5 """
6 from __future__ import print_function
7
8 import sys, os, posixpath, errno, stat, time
9 import subprocess
10 from rpython.tool.killsubprocess import killsubprocess
11 from rpython.translator.sandbox.vfs import UID, GID
12 import py
13
14 WIN32 = os.name == "nt"
15
16
17 def create_log():
18 """Make and return a log for the sandbox to use, if needed."""
19 from rpython.tool.ansi_print import AnsiLogger
20 return AnsiLogger("sandlib")
21
22 # Note: we use lib_pypy/marshal.py instead of the built-in marshal
23 # for two reasons. The built-in module could be made to segfault
24 # or be attackable in other ways by sending malicious input to
25 # load(). Also, marshal.load(f) blocks with the GIL held when
26 # f is a pipe with no data immediately avaialble, preventing the
27 # _waiting_thread to run.
28 from rpython.translator.sandbox import _marshal as marshal
29
30 # Non-marshal result types
31 RESULTTYPE_STATRESULT = object()
32 RESULTTYPE_LONGLONG = object()
33
34 def read_message(f):
35 return marshal.load(f)
36
37 def write_message(g, msg, resulttype=None):
38 if resulttype is None:
39 if sys.version_info < (2, 4):
40 marshal.dump(msg, g)
41 else:
42 marshal.dump(msg, g, 0)
43 elif resulttype is RESULTTYPE_STATRESULT:
44 # Hand-coded marshal for stat results that mimics what rmarshal expects.
45 # marshal.dump(tuple(msg)) would have been too easy. rmarshal insists
46 # on 64-bit ints at places, even when the value fits in 32 bits.
47 import struct
48 st = tuple(msg)
49 fmt = "iIIiiiIfff"
50 buf = []
51 buf.append(struct.pack("<ci", '(', len(st)))
52 for c, v in zip(fmt, st):
53 if c == 'i':
54 buf.append(struct.pack("<ci", c, v))
55 elif c == 'I':
56 buf.append(struct.pack("<cq", c, v))
57 elif c == 'f':
58 fstr = "%g" % v
59 buf.append(struct.pack("<cB", c, len(fstr)))
60 buf.append(fstr)
61 g.write(''.join(buf))
62 elif resulttype is RESULTTYPE_LONGLONG:
63 import struct
64 g.write(struct.pack("<cq", 'I', msg))
65 else:
66 raise Exception("Can't marshal: %r (%r)" % (msg, resulttype))
67
68 # keep the table in sync with rsandbox.reraise_error()
69 EXCEPTION_TABLE = [
70 (1, OSError),
71 (2, IOError),
72 (3, OverflowError),
73 (4, ValueError),
74 (5, ZeroDivisionError),
75 (6, MemoryError),
76 (7, KeyError),
77 (8, IndexError),
78 (9, RuntimeError),
79 ]
80
81 def write_exception(g, exception, tb=None):
82 for i, excclass in EXCEPTION_TABLE:
83 if isinstance(exception, excclass):
84 write_message(g, i)
85 if excclass is OSError:
86 error = exception.errno
87 if error is None:
88 error = errno.EPERM
89 write_message(g, error)
90 g.flush()
91 break
92 else:
93 # just re-raise the exception
94 raise exception.__class__, exception, tb
95
96 def shortrepr(x):
97 r = repr(x)
98 if len(r) >= 80:
99 r = r[:20] + '...' + r[-8:]
100 return r
101
102 def signal_name(n):
103 import signal
104 for key, value in signal.__dict__.items():
105 if key.startswith('SIG') and not key.startswith('SIG_') and value == n:
106 return key
107 return 'signal %d' % (n,)
108
109
110 class SandboxedProc(object):
111 """Base class to control a sandboxed subprocess.
112 Inherit from this class and implement all the do_xxx() methods
113 for the external functions xxx that you want to support.
114 """
115 debug = False
116 log = None
117 os_level_sandboxing = False # Linux only: /proc/PID/seccomp
118
119 def __init__(self, args, executable=None):
120 """'args' should a sequence of argument for the subprocess,
121 starting with the full path of the executable.
122 """
123 self.popen = subprocess.Popen(args, executable=executable,
124 bufsize=-1,
125 stdin=subprocess.PIPE,
126 stdout=subprocess.PIPE,
127 close_fds=False if WIN32 else True,
128 env={})
129 self.popenlock = None
130 self.currenttimeout = None
131 self.currentlyidlefrom = None
132
133 if self.debug:
134 self.log = create_log()
135
136 def withlock(self, function, *args, **kwds):
137 lock = self.popenlock
138 if lock is not None:
139 lock.acquire()
140 try:
141 return function(*args, **kwds)
142 finally:
143 if lock is not None:
144 lock.release()
145
146 def settimeout(self, timeout, interrupt_main=False):
147 """Start a timeout that will kill the subprocess after the given
148 amount of time. Only one timeout can be active at a time.
149 """
150 import thread
151
152 def _waiting_thread():
153 while True:
154 while self.currentlyidlefrom is not None:
155 time.sleep(1) # can't timeout while idle
156 t = self.currenttimeout
157 if t is None:
158 return # cancelled
159 delay = t - time.time()
160 if delay <= 0.0:
161 break # expired!
162 time.sleep(min(delay*1.001, 1))
163 if self.log:
164 self.log.timeout("timeout!")
165 self.kill()
166 #if interrupt_main:
167 # if hasattr(os, 'kill'):
168 # import signal
169 # os.kill(os.getpid(), signal.SIGINT)
170 # else:
171 # thread.interrupt_main()
172
173 def _settimeout():
174 need_new_thread = self.currenttimeout is None
175 self.currenttimeout = time.time() + timeout
176 if need_new_thread:
177 thread.start_new_thread(_waiting_thread, ())
178
179 if self.popenlock is None:
180 self.popenlock = thread.allocate_lock()
181 self.withlock(_settimeout)
182
183 def canceltimeout(self):
184 """Cancel the current timeout."""
185 self.currenttimeout = None
186 self.currentlyidlefrom = None
187
188 def enter_idle(self):
189 self.currentlyidlefrom = time.time()
190
191 def leave_idle(self):
192 def _postpone_timeout():
193 t = self.currentlyidlefrom
194 if t is not None and self.currenttimeout is not None:
195 self.currenttimeout += time.time() - t
196 try:
197 self.withlock(_postpone_timeout)
198 finally:
199 self.currentlyidlefrom = None
200
201 def poll(self):
202 returncode = self.withlock(self.popen.poll)
203 if returncode is not None:
204 self.canceltimeout()
205 return returncode
206
207 def wait(self):
208 returncode = self.withlock(self.popen.wait)
209 if returncode is not None:
210 self.canceltimeout()
211 return returncode
212
213 def kill(self):
214 self.withlock(killsubprocess, self.popen)
215
216 def handle_forever(self):
217 returncode = self.handle_until_return()
218 if returncode != 0:
219 raise OSError("the sandboxed subprocess exited with code %d" % (
220 returncode,))
221
222 def handle_until_return(self):
223 child_stdin = self.popen.stdin
224 child_stdout = self.popen.stdout
225 if self.os_level_sandboxing and sys.platform.startswith('linux'):
226 # rationale: we wait until the child process started completely,
227 # letting the C library do any system calls it wants for
228 # initialization. When the RPython code starts up, it quickly
229 # does its first system call. At this point we turn seccomp on.
230 import select
231 select.select([child_stdout], [], [])
232 f = open('/proc/%d/seccomp' % self.popen.pid, 'w')
233 print(1, file=f)
234 f.close()
235 while True:
236 try:
237 fnname = read_message(child_stdout)
238 args = read_message(child_stdout)
239 except EOFError as e:
240 break
241 if self.log and not self.is_spam(fnname, *args):
242 self.log.call('%s(%s)' % (fnname,
243 ', '.join([shortrepr(x) for x in args])))
244 try:
245 answer, resulttype = self.handle_message(fnname, *args)
246 except Exception as e:
247 tb = sys.exc_info()[2]
248 write_exception(child_stdin, e, tb)
249 if self.log:
250 if str(e):
251 self.log.exception('%s: %s' % (e.__class__.__name__, e))
252 else:
253 self.log.exception('%s' % (e.__class__.__name__,))
254 else:
255 if self.log and not self.is_spam(fnname, *args):
256 self.log.result(shortrepr(answer))
257 try:
258 write_message(child_stdin, 0) # error code - 0 for ok
259 write_message(child_stdin, answer, resulttype)
260 child_stdin.flush()
261 except (IOError, OSError):
262 # likely cause: subprocess is dead, child_stdin closed
263 if self.poll() is not None:
264 break
265 else:
266 raise
267 returncode = self.wait()
268 return returncode
269
270 def is_spam(self, fnname, *args):
271 # To hide the spamming amounts of reads and writes to stdin and stdout
272 # in interactive sessions
273 return (fnname in ('ll_os.ll_os_read', 'll_os.ll_os_write') and
274 args[0] in (0, 1, 2))
275
276 def handle_message(self, fnname, *args):
277 if '__' in fnname:
278 raise ValueError("unsafe fnname")
279 try:
280 handler = getattr(self, 'do_' + fnname.replace('.', '__'))
281 except AttributeError:
282 raise RuntimeError("no handler for this function")
283 resulttype = getattr(handler, 'resulttype', None)
284 return handler(*args), resulttype
285
286
287 class SimpleIOSandboxedProc(SandboxedProc):
288 """Control a sandboxed subprocess which is only allowed to read from
289 its stdin and write to its stdout and stderr.
290 """
291 _input = None
292 _output = None
293 _error = None
294 inputlogfile = None
295
296 def communicate(self, input=None):
297 """Send data to stdin. Read data from stdout and stderr,
298 until end-of-file is reached. Wait for process to terminate.
299 """
300 import cStringIO
301 if input:
302 if isinstance(input, str):
303 input = cStringIO.StringIO(input)
304 self._input = input
305 self._output = cStringIO.StringIO()
306 self._error = cStringIO.StringIO()
307 self.handle_forever()
308 output = self._output.getvalue()
309 self._output = None
310 error = self._error.getvalue()
311 self._error = None
312 return (output, error)
313
314 def interact(self, stdin=None, stdout=None, stderr=None):
315 """Interact with the subprocess. By default, stdin, stdout and
316 stderr are set to the ones from 'sys'."""
317 import sys
318 self._input = stdin or sys.stdin
319 self._output = stdout or sys.stdout
320 self._error = stderr or sys.stderr
321 returncode = self.handle_until_return()
322 if returncode != 0:
323 if os.name == 'posix' and returncode < 0:
324 print("[Subprocess killed by %s]" %
325 (signal_name(-returncode),), file=self._error)
326 else:
327 print("[Subprocess exit code: %d]" % (returncode,),
328 file=self._error)
329 self._input = None
330 self._output = None
331 self._error = None
332 return returncode
333
334 def setlogfile(self, filename):
335 self.inputlogfile = open(filename, 'a')
336
337 def do_ll_os__ll_os_read(self, fd, size):
338 if fd == 0:
339 if self._input is None:
340 return ""
341 elif (getattr(self, 'virtual_console_isatty', False) or
342 self._input.isatty()):
343 # don't wait for all 'size' chars if reading from a tty,
344 # to avoid blocking. Instead, stop after reading a line.
345
346 # For now, waiting at the interactive console is the
347 # only time that counts as idle.
348 self.enter_idle()
349 try:
350 inputdata = self._input.readline(size)
351 finally:
352 self.leave_idle()
353 else:
354 inputdata = self._input.read(size)
355 if self.inputlogfile is not None:
356 self.inputlogfile.write(inputdata)
357 return inputdata
358 raise OSError("trying to read from fd %d" % (fd,))
359
360 def do_ll_os__ll_os_write(self, fd, data):
361 if fd == 1:
362 self._output.write(data)
363 return len(data)
364 if fd == 2:
365 self._error.write(data)
366 return len(data)
367 raise OSError("trying to write to fd %d" % (fd,))
368
369 # let's allow access to the real time
370 def do_ll_time__ll_time_sleep(self, seconds):
371 # regularly check for timeouts that could have killed the
372 # subprocess
373 while seconds > 5.0:
374 time.sleep(5.0)
375 seconds -= 5.0
376 if self.poll() is not None: # subprocess finished?
377 return
378 time.sleep(seconds)
379
380 def do_ll_time__ll_time_time(self):
381 return time.time()
382
383 def do_ll_time__ll_time_clock(self):
384 # measuring the CPU time of the controller process has
385 # not much meaning, so let's emulate this and return
386 # the real time elapsed since the first call to clock()
387 # (this is one of the behaviors allowed by the docs)
388 try:
389 starttime = self.starttime
390 except AttributeError:
391 starttime = self.starttime = time.time()
392 return time.time() - starttime
393
394 class VirtualizedSandboxedProc(SandboxedProc):
395 """Control a virtualized sandboxed process, which is given a custom
396 view on the filesystem and a custom environment.
397 """
398 virtual_env = {}
399 virtual_cwd = '/tmp'
400 virtual_console_isatty = False
401 virtual_fd_range = range(3, 50)
402
403 def __init__(self, *args, **kwds):
404 super(VirtualizedSandboxedProc, self).__init__(*args, **kwds)
405 self.virtual_root = self.build_virtual_root()
406 self.open_fds = {} # {virtual_fd: (real_file_object, node)}
407
408 def build_virtual_root(self):
409 raise NotImplementedError("must be overridden")
410
411 def do_ll_os__ll_os_envitems(self):
412 return self.virtual_env.items()
413
414 def do_ll_os__ll_os_getenv(self, name):
415 return self.virtual_env.get(name)
416
417 def translate_path(self, vpath):
418 # XXX this assumes posix vpaths for now, but os-specific real paths
419 vpath = posixpath.normpath(posixpath.join(self.virtual_cwd, vpath))
420 dirnode = self.virtual_root
421 components = [component for component in vpath.split('/')]
422 for component in components[:-1]:
423 if component:
424 dirnode = dirnode.join(component)
425 if dirnode.kind != stat.S_IFDIR:
426 raise OSError(errno.ENOTDIR, component)
427 return dirnode, components[-1]
428
429 def get_node(self, vpath):
430 dirnode, name = self.translate_path(vpath)
431 if name:
432 node = dirnode.join(name)
433 else:
434 node = dirnode
435 if self.log:
436 self.log.vpath('%r => %r' % (vpath, node))
437 return node
438
439 def do_ll_os__ll_os_stat(self, vpathname):
440 node = self.get_node(vpathname)
441 return node.stat()
442 do_ll_os__ll_os_stat.resulttype = RESULTTYPE_STATRESULT
443
444 do_ll_os__ll_os_lstat = do_ll_os__ll_os_stat
445
446 def do_ll_os__ll_os_access(self, vpathname, mode):
447 try:
448 node = self.get_node(vpathname)
449 except OSError as e:
450 if e.errno == errno.ENOENT:
451 return False
452 raise
453 return node.access(mode)
454
455 def do_ll_os__ll_os_isatty(self, fd):
456 return self.virtual_console_isatty and fd in (0, 1, 2)
457
458 def allocate_fd(self, f, node=None):
459 for fd in self.virtual_fd_range:
460 if fd not in self.open_fds:
461 self.open_fds[fd] = (f, node)
462 return fd
463 else:
464 raise OSError(errno.EMFILE, "trying to open too many files")
465
466 def get_fd(self, fd, throw=True):
467 """Get the objects implementing file descriptor `fd`.
468
469 Returns a pair, (open file, vfs node)
470
471 `throw`: if true, raise OSError for bad fd, else return (None, None).
472 """
473 try:
474 f, node = self.open_fds[fd]
475 except KeyError:
476 if throw:
477 raise OSError(errno.EBADF, "bad file descriptor")
478 return None, None
479 return f, node
480
481 def get_file(self, fd, throw=True):
482 """Return the open file for file descriptor `fd`."""
483 return self.get_fd(fd, throw)[0]
484
485 def do_ll_os__ll_os_open(self, vpathname, flags, mode):
486 node = self.get_node(vpathname)
487 if flags & (os.O_RDONLY|os.O_WRONLY|os.O_RDWR) != os.O_RDONLY:
488 raise OSError(errno.EPERM, "write access denied")
489 # all other flags are ignored
490 f = node.open()
491 return self.allocate_fd(f, node)
492
493 def do_ll_os__ll_os_close(self, fd):
494 f = self.get_file(fd)
495 del self.open_fds[fd]
496 f.close()
497
498 def do_ll_os__ll_os_read(self, fd, size):
499 f = self.get_file(fd, throw=False)
500 if f is None:
501 return super(VirtualizedSandboxedProc, self).do_ll_os__ll_os_read(
502 fd, size)
503 else:
504 if not (0 <= size <= sys.maxint):
505 raise OSError(errno.EINVAL, "invalid read size")
506 # don't try to read more than 256KB at once here
507 return f.read(min(size, 256*1024))
508
509 def do_ll_os__ll_os_fstat(self, fd):
510 f, node = self.get_fd(fd)
511 return node.stat()
512 do_ll_os__ll_os_fstat.resulttype = RESULTTYPE_STATRESULT
513
514 def do_ll_os__ll_os_lseek(self, fd, pos, how):
515 f = self.get_file(fd)
516 f.seek(pos, how)
517 return f.tell()
518 do_ll_os__ll_os_lseek.resulttype = RESULTTYPE_LONGLONG
519
520 def do_ll_os__ll_os_getcwd(self):
521 return self.virtual_cwd
522
523 def do_ll_os__ll_os_strerror(self, errnum):
524 # unsure if this shouldn't be considered safeboxsafe
525 return os.strerror(errnum) or ('Unknown error %d' % (errnum,))
526
527 def do_ll_os__ll_os_listdir(self, vpathname):
528 node = self.get_node(vpathname)
529 return node.keys()
530
531 def do_ll_os__ll_os_unlink(self, vpathname):
532 raise OSError(errno.EPERM, "write access denied")
533
534 def do_ll_os__ll_os_mkdir(self, vpathname, mode=None):
535 raise OSError(errno.EPERM, "write access denied")
536
537 def do_ll_os__ll_os_getuid(self):
538 return UID
539 do_ll_os__ll_os_geteuid = do_ll_os__ll_os_getuid
540
541 def do_ll_os__ll_os_getgid(self):
542 return GID
543 do_ll_os__ll_os_getegid = do_ll_os__ll_os_getgid
544
545
546 class VirtualizedSocketProc(VirtualizedSandboxedProc):
547 """ Extends VirtualizedSandboxProc with socket
548 options, ie tcp://host:port as args to os.open
549 """
550 def __init__(self, *args, **kwds):
551 super(VirtualizedSocketProc, self).__init__(*args, **kwds)
552 self.sockets = {}
553
554 def do_ll_os__ll_os_open(self, name, flags, mode):
555 if not name.startswith("tcp://"):
556 return super(VirtualizedSocketProc, self).do_ll_os__ll_os_open(
557 name, flags, mode)
558 import socket
559 host, port = name[6:].split(":")
560 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
561 sock.connect((host, int(port)))
562 fd = self.allocate_fd(sock)
563 self.sockets[fd] = True
564 return fd
565
566 def do_ll_os__ll_os_read(self, fd, size):
567 if fd in self.sockets:
568 return self.get_file(fd).recv(size)
569 return super(VirtualizedSocketProc, self).do_ll_os__ll_os_read(
570 fd, size)
571
572 def do_ll_os__ll_os_write(self, fd, data):
573 if fd in self.sockets:
574 return self.get_file(fd).send(data)
575 return super(VirtualizedSocketProc, self).do_ll_os__ll_os_write(
576 fd, data)