90
89
self.headers = {} # Header names : values
92
def execute_cgi(interpreter, owner, jail_dir, working_dir, script_path,
91
def execute_cgi(interpreter, trampoline, uid, jail_dir, working_dir,
92
script_path, req, gentle):
95
94
trampoline: Full path on the local system to the CGI wrapper program
97
owner: User object of the owner of the file.
96
uid: User ID of the owner of the file.
98
97
jail_dir: Absolute path of owner's jail directory.
99
98
working_dir: Directory containing the script file relative to owner's
130
127
f.seek(0) # Rewind, for reading
132
129
# Set up the environment
133
environ = cgi_environ(req, script_path, owner)
130
# This automatically asks mod_python to load up the CGI variables into the
131
# environment (which is a good first approximation)
132
old_env = os.environ.copy()
133
for k in os.environ.keys():
135
for (k,v) in req.get_cgi_environ().items():
135
139
# usage: tramp uid jail_dir working_dir script_path
136
cmd_line = [trampoline, str(owner.unixid),
137
req.config['paths']['jails']['mounts'],
138
req.config['paths']['jails']['src'],
139
req.config['paths']['jails']['template'],
140
jail_dir, working_dir, interpreter, script_path]
141
# Popen doesn't like unicode strings. It hateses them.
142
cmd_line = [(s.encode('utf-8') if isinstance(s, unicode) else s)
144
pid = subprocess.Popen(cmd_line,
140
pid = subprocess.Popen(
141
[trampoline, str(uid), jail_dir, working_dir, interpreter,
145
143
stdin=f, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
146
cwd=tramp_dir, env=environ)
146
# Restore the environment
147
for k in os.environ.keys():
149
for (k,v) in old_env.items():
148
152
# We don't want any output! Bail out after the process terminates.
218
222
# Is this an internal IVLE error condition?
219
223
hs = cgiflags.headers
220
224
if 'X-IVLE-Error-Type' in hs:
222
raise IVLEJailError(hs['X-IVLE-Error-Type'],
223
hs['X-IVLE-Error-Message'],
224
hs['X-IVLE-Error-Info'])
226
raise AssertionError("Bad error headers written by CGI.")
225
t = hs['X-IVLE-Error-Type']
226
if t == IVLEError.__name__:
227
raise IVLEError(int(hs['X-IVLE-Error-Code']),
228
hs['X-IVLE-Error-Message'])
231
raise IVLEJailError(hs['X-IVLE-Error-Type'],
232
hs['X-IVLE-Error-Message'],
233
hs['X-IVLE-Error-Info'])
235
raise IVLEError(500, 'bad error headers written by CGI')
228
237
# Check to make sure the required headers were written
229
238
if cgiflags.wrote_html_warning or not cgiflags.gentle:
333
342
""" % (warning, text))
344
location_cgi_python = os.path.join(ivle.conf.lib_path, "trampoline")
335
346
# Mapping of interpreter names (as given in conf/app/server.py) to
336
347
# interpreter functions.
338
349
interpreter_objects = {
340
: functools.partial(execute_cgi, "/usr/bin/python"),
351
: functools.partial(execute_cgi, "/usr/bin/python",
352
location_cgi_python),
342
: functools.partial(execute_cgi, None),
354
: functools.partial(execute_cgi, None,
355
location_cgi_python),
343
356
# Should also have:
345
358
# python-server-page
348
def cgi_environ(req, script_path, user):
349
"""Gets CGI variables from apache and makes a few changes for security and
361
def fixup_environ(req):
362
"""Assuming os.environ has been written with the CGI variables from
363
apache, make a few changes for security and correctness.
352
365
Does not modify req, only reads it.
355
368
# Comments here are on the heavy side, explained carefully for security
356
369
# reasons. Please read carefully before making changes.
358
# This automatically asks mod_python to load up the CGI variables into the
359
# environment (which is a good first approximation)
360
for (k,v) in req.get_cgi_environ().items():
363
371
# Remove DOCUMENT_ROOT and SCRIPT_FILENAME. Not part of CGI spec and
364
372
# exposes unnecessary details about server.
387
# Remove SCRIPT_FILENAME. Not part of CGI spec (see SCRIPT_NAME).
389
# PATH_INFO is wrong because the script doesn't physically exist.
390
# Apache makes it relative to the "serve" app. It should actually be made
391
# relative to the student's script. intepretservice does that in the jail,
392
# so here we just clear it.
393
env['PATH_INFO'] = ''
394
env['PATH_TRANSLATED'] = ''
379
396
# CGI specifies that REMOTE_HOST SHOULD be set, and MAY just be set to
380
397
# REMOTE_ADDR. Since Apache does not appear to set this, set it to
382
399
if 'REMOTE_HOST' not in env and 'REMOTE_ADDR' in env:
383
400
env['REMOTE_HOST'] = env['REMOTE_ADDR']
385
env['PATH_INFO'] = ''
386
del env['PATH_TRANSLATED']
388
normuri = os.path.normpath(req.uri)
389
env['SCRIPT_NAME'] = normuri
391
402
# SCRIPT_NAME is the path to the script WITHOUT PATH_INFO.
392
# We don't care about these if the script is null (ie. noop).
393
# XXX: We check for /home because we don't want to interfere with
394
# CGIRequest, which fileservice still uses.
395
if script_path and script_path.startswith('/home'):
396
normscript = os.path.normpath(script_path)
398
uri_into_jail = studpath.to_home_path(os.path.normpath(req.path))
400
# PATH_INFO is wrong because the script doesn't physically exist.
401
env['PATH_INFO'] = uri_into_jail[len(normscript):]
402
if len(env['PATH_INFO']) > 0:
403
env['SCRIPT_NAME'] = normuri[:-len(env['PATH_INFO'])]
403
script_name = req.uri
404
env['SCRIPT_NAME'] = script_name
405
406
# SERVER_SOFTWARE is actually not Apache but IVLE, since we are
406
407
# custom-making the CGI request.
407
env['SERVER_SOFTWARE'] = "IVLE/" + ivle.__version__
408
env['SERVER_SOFTWARE'] = "IVLE/" + str(ivle.conf.ivle_version)
409
410
# Additional environment variables
410
username = user.login
411
username = studpath.url_to_jailpaths(req.path)[0]
411
412
env['HOME'] = os.path.join('/home', username)
415
414
class ExecutionError(Exception):
418
def execute_raw(config, user, jail_dir, working_dir, binary, args):
417
def execute_raw(user, jail_dir, working_dir, binary, args):
419
418
'''Execute a binary in a user's jail, returning the raw output.
421
420
The binary is executed in the given working directory with the given
422
421
args. A tuple of (stdout, stderr) is returned.
425
tramp = os.path.join(config['paths']['lib'], 'trampoline')
426
tramp_dir = os.path.split(tramp)[0]
424
tramp = location_cgi_python
425
tramp_dir = os.path.split(location_cgi_python)[0]
428
427
# Fire up trampoline. Vroom, vroom.
429
cmd_line = [tramp, str(user.unixid), config['paths']['jails']['mounts'],
430
config['paths']['jails']['src'],
431
config['paths']['jails']['template'],
432
jail_dir, working_dir, binary] + args
433
# Popen doesn't like unicode strings. It hateses them.
434
cmd_line = [(s.encode('utf-8') if isinstance(s, unicode) else s)
436
proc = subprocess.Popen(cmd_line,
428
proc = subprocess.Popen(
429
[tramp, str(user.unixid), jail_dir, working_dir, binary] + args,
437
430
stdin=subprocess.PIPE, stdout=subprocess.PIPE,
438
stderr=subprocess.PIPE, cwd=tramp_dir, close_fds=True,
439
env={'HOME': os.path.join('/home', user.login),
442
'LOGNAME': user.login})
444
(stdout, stderr) = proc.communicate()
445
exitcode = proc.returncode
431
stderr=subprocess.PIPE, cwd=tramp_dir, close_fds=True)
432
exitcode = proc.wait()
447
434
if exitcode != 0:
448
raise ExecutionError('subprocess ended with code %d, stderr: "%s"' %
450
return (stdout, stderr)
435
raise ExecutionError('subprocess ended with code %d, stderr %s' %
436
(exitcode, proc.stderr.read()))
437
return (proc.stdout.read(), proc.stderr.read())