2
# Copyright (C) 2007-2008 The University of Melbourne
4
# This program is free software; you can redistribute it and/or modify
5
# it under the terms of the GNU General Public License as published by
6
# the Free Software Foundation; either version 2 of the License, or
7
# (at your option) any later version.
9
# This program is distributed in the hope that it will be useful,
10
# but WITHOUT ANY WARRANTY; without even the implied warranty of
11
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12
# GNU General Public License for more details.
14
# You should have received a copy of the GNU General Public License
15
# along with this program; if not, write to the Free Software
16
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
22
# Runs a student script in a safe execution environment.
25
from ivle import studpath
26
from ivle.util import IVLEError, IVLEJailError, split_path
35
# TODO: Make progressive output work
36
# Question: Will having a large buffer size stop progressive output from
37
# working on smaller output
39
CGI_BLOCK_SIZE = 65535
41
def interpret_file(req, owner, jail_dir, filename, interpreter, gentle=True):
42
"""Serves a file by interpreting it using one of IVLE's builtin
43
interpreters. All interpreters are intended to run in the user's jail. The
44
jail location is provided as an argument to the interpreter but it is up
45
to the individual interpreters to create the jail.
47
req: An IVLE request object.
48
owner: The user who owns the file being served.
49
jail_dir: Absolute path to the user's jail.
50
filename: Absolute filename within the user's jail.
51
interpreter: A function object to call.
53
# We can't test here whether or not the target file actually exists,
54
# because the apache user may not have permission. Instead we have to
55
# rely on the interpreter generating an error.
56
if filename.startswith(os.sep):
57
filename_abs = filename
58
filename_rel = filename[1:]
60
filename_abs = os.path.join(os.sep, filename)
61
filename_rel = filename
63
# (Note: files are executed by their owners, not the logged in user.
64
# This ensures users are responsible for their own programs and also
65
# allows them to be executed by the public).
67
# Split up req.path again, this time with respect to the jail
68
(working_dir, _) = os.path.split(filename_abs)
69
# jail_dir is the absolute jail directory.
70
# path is the filename relative to the user's jail.
71
# working_dir is the directory containing the file relative to the user's
73
# (Note that paths "relative" to the jail actually begin with a '/' as
74
# they are absolute in the jailspace)
76
return interpreter(owner.unixid, jail_dir, working_dir, filename_abs, req,
80
"""Stores flags regarding the state of reading CGI output.
81
If this is to be gentle, detection of invalid headers will result in an
83
def __init__(self, begentle=True):
84
self.gentle = begentle
85
self.started_cgi_body = False
86
self.got_cgi_headers = False
87
self.wrote_html_warning = False
89
self.headers = {} # Header names : values
91
def execute_cgi(interpreter, uid, jail_dir, working_dir, script_path,
94
trampoline: Full path on the local system to the CGI wrapper program
96
uid: User ID of the owner of the file.
97
jail_dir: Absolute path of owner's jail directory.
98
working_dir: Directory containing the script file relative to owner's
100
script_path: CGI script relative to the owner's jail.
101
req: IVLE request object.
103
The called CGI wrapper application shall be called using popen and receive
104
the HTTP body on stdin. It shall receive the CGI environment variables to
108
trampoline = os.path.join(req.config['paths']['lib'], 'trampoline')
110
# Support no-op trampoline runs.
111
if interpreter is None:
112
interpreter = '/bin/true'
118
# Get the student program's directory and execute it from that context.
119
(tramp_dir, _) = os.path.split(trampoline)
121
# TODO: Don't create a file if the body length is known to be 0
122
# Write the HTTP body to a temporary file so it can be passed as a *real*
125
body = req.read() if not noop else None
129
f.seek(0) # Rewind, for reading
131
# Set up the environment
132
# This automatically asks mod_python to load up the CGI variables into the
133
# environment (which is a good first approximation)
134
old_env = os.environ.copy()
135
for k in os.environ.keys():
137
for (k,v) in req.get_cgi_environ().items():
139
fixup_environ(req, script_path)
141
# usage: tramp uid jail_dir working_dir script_path
142
pid = subprocess.Popen(
143
[trampoline, str(uid), req.config['paths']['jails']['mounts'],
144
req.config['paths']['jails']['src'],
145
req.config['paths']['jails']['template'],
146
jail_dir, working_dir, interpreter, script_path],
147
stdin=f, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
150
# Restore the environment
151
for k in os.environ.keys():
153
for (k,v) in old_env.items():
156
# We don't want any output! Bail out after the process terminates.
161
# process_cgi_line: Reads a single line of CGI output and processes it.
162
# Prints to req, and also does fancy HTML warnings if Content-Type
164
cgiflags = CGIFlags(gentle)
166
# Read from the process's stdout into req
167
data = pid.stdout.read(CGI_BLOCK_SIZE)
169
process_cgi_output(req, data, cgiflags)
170
data = pid.stdout.read(CGI_BLOCK_SIZE)
172
# If we haven't processed headers yet, now is a good time
173
if not cgiflags.started_cgi_body:
174
process_cgi_output(req, '\n', cgiflags)
176
# If we wrote an HTML warning header, write the footer
177
if cgiflags.wrote_html_warning:
183
def process_cgi_output(req, data, cgiflags):
184
"""Processes a chunk of CGI output. data is a string of arbitrary length;
185
some arbitrary chunk of output written by the CGI script."""
186
if cgiflags.started_cgi_body:
187
if cgiflags.wrote_html_warning:
188
# HTML escape text if wrote_html_warning
189
req.write(cgi.escape(data))
193
# Break data into lines of CGI header data.
194
linebuf = cgiflags.linebuf + data
195
# First see if we can split all header data
196
# We need to get the double CRLF- or LF-terminated headers, whichever
197
# is smaller, as either sequence may appear somewhere in the body.
198
usplit = linebuf.split('\n\n', 1)
199
wsplit = linebuf.split('\r\n\r\n', 1)
200
split = len(usplit[0]) > len(wsplit[0]) and wsplit or usplit
202
# Haven't seen all headers yet. Buffer and come back later.
203
cgiflags.linebuf = linebuf
208
cgiflags.linebuf = ""
209
cgiflags.started_cgi_body = True
210
# Process all the header lines
211
split = headers.split('\r\n', 1)
213
split = headers.split('\n', 1)
215
process_cgi_header_line(req, split[0], cgiflags)
216
if len(split) == 1: break
218
if cgiflags.wrote_html_warning:
219
# We're done with headers. Treat the rest as data.
220
data = headers + '\n' + data
222
split = headers.split('\r\n', 1)
224
split = headers.split('\n', 1)
226
# Is this an internal IVLE error condition?
227
hs = cgiflags.headers
228
if 'X-IVLE-Error-Type' in hs:
229
t = hs['X-IVLE-Error-Type']
230
if t == IVLEError.__name__:
231
raise IVLEError(int(hs['X-IVLE-Error-Code']),
232
hs['X-IVLE-Error-Message'])
235
raise IVLEJailError(hs['X-IVLE-Error-Type'],
236
hs['X-IVLE-Error-Message'],
237
hs['X-IVLE-Error-Info'])
239
raise IVLEError(500, 'bad error headers written by CGI')
241
# Check to make sure the required headers were written
242
if cgiflags.wrote_html_warning or not cgiflags.gentle:
243
# We already reported an error, that's enough
245
elif "Content-Type" in cgiflags.headers:
247
elif "Location" in cgiflags.headers:
248
if ("Status" in cgiflags.headers and req.status >= 300
249
and req.status < 400):
252
message = """You did not write a valid status code for
253
the given location. To make a redirect, you may wish to try:</p>
254
<pre style="margin-left: 1em">Status: 302 Found
255
Location: <redirect address></pre>"""
256
write_html_warning(req, message)
257
cgiflags.wrote_html_warning = True
259
message = """You did not print a Content-Type header.
260
CGI requires that you print a "Content-Type". You may wish to try:</p>
261
<pre style="margin-left: 1em">Content-Type: text/html</pre>"""
262
write_html_warning(req, message)
263
cgiflags.wrote_html_warning = True
265
# Call myself to flush out the extra bit of data we read
266
process_cgi_output(req, data, cgiflags)
268
def process_cgi_header_line(req, line, cgiflags):
269
"""Process a line of CGI header data. line is a string representing a
270
complete line of text, stripped and without the newline.
273
name, value = line.split(':', 1)
275
# No colon. The user did not write valid headers.
276
# If we are being gentle, we want to help the user understand what
277
# went wrong. Otherwise, just admit we screwed up.
279
if not cgiflags.gentle:
280
message = """An unexpected server error has occured."""
282
elif len(cgiflags.headers) == 0:
283
# First line was not a header line. We can assume this is not
285
message = """You did not print a CGI header.
286
CGI requires that you print a "Content-Type". You may wish to try:</p>
287
<pre style="margin-left: 1em">Content-Type: text/html</pre>"""
289
# They printed some header at least, but there was an invalid
291
message = """You printed an invalid CGI header. You need to leave
292
a blank line after the headers, before writing the page contents."""
293
write_html_warning(req, message, warning=warning)
294
cgiflags.wrote_html_warning = True
295
# Handle the rest of this line as normal data
296
process_cgi_output(req, line + '\n', cgiflags)
300
value = value.strip()
301
if name == "Content-Type":
302
req.content_type = value
303
elif name == "Location":
305
elif name == "Status":
306
# Must be an integer, followed by a space, and then the status line
307
# which we ignore (seems like Apache has no way to send a custom
310
req.status = int(value.split(' ', 1)[0])
312
if not cgiflags.gentle:
313
# This isn't user code, so it should be good.
314
# Get us out of here!
316
message = """The "Status" CGI header was invalid. You need to
317
print a number followed by a message, such as "302 Found"."""
318
write_html_warning(req, message)
319
cgiflags.wrote_html_warning = True
320
# Handle the rest of this line as normal data
321
process_cgi_output(req, line + '\n', cgiflags)
323
# Generic HTTP header
324
# FIXME: Security risk letting users write arbitrary headers?
325
req.headers_out.add(name, value)
326
cgiflags.headers[name] = value # FIXME: Only the last header will end up here.
328
def write_html_warning(req, text, warning="Warning"):
329
"""Prints an HTML warning about invalid CGI interaction on the part of the
330
user. text may contain HTML markup."""
331
req.content_type = "text/html"
332
req.write("""<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
333
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
334
<html xmlns="http://www.w3.org/1999/xhtml">
336
<meta http-equiv="Content-Type"
337
content="text/html; charset=utf-8" />
339
<body style="margin: 0; padding: 0; font-family: sans-serif;">
340
<div style="background-color: #faa; border-bottom: 1px solid black;
342
<p><strong>%s</strong>: %s
344
<div style="margin: 8px;">
346
""" % (warning, text))
348
# Mapping of interpreter names (as given in conf/app/server.py) to
349
# interpreter functions.
351
interpreter_objects = {
353
: functools.partial(execute_cgi, "/usr/bin/python"),
355
: functools.partial(execute_cgi, None),
361
def fixup_environ(req, script_path):
362
"""Assuming os.environ has been written with the CGI variables from
363
apache, make a few changes for security and correctness.
365
Does not modify req, only reads it.
368
# Comments here are on the heavy side, explained carefully for security
369
# reasons. Please read carefully before making changes.
371
# Remove DOCUMENT_ROOT and SCRIPT_FILENAME. Not part of CGI spec and
372
# exposes unnecessary details about server.
374
del env['DOCUMENT_ROOT']
377
del env['SCRIPT_FILENAME']
380
# Remove PATH. The PATH here is the path on the server machine; not useful
381
# inside the jail. It may be a good idea to add another path, reflecting
382
# the inside of the jail, but not done at this stage.
387
# CGI specifies that REMOTE_HOST SHOULD be set, and MAY just be set to
388
# REMOTE_ADDR. Since Apache does not appear to set this, set it to
390
if 'REMOTE_HOST' not in env and 'REMOTE_ADDR' in env:
391
env['REMOTE_HOST'] = env['REMOTE_ADDR']
393
env['PATH_INFO'] = ''
394
del env['PATH_TRANSLATED']
396
normuri = os.path.normpath(req.uri)
397
env['SCRIPT_NAME'] = normuri
399
# SCRIPT_NAME is the path to the script WITHOUT PATH_INFO.
400
# We don't care about these if the script is null (ie. noop).
401
# XXX: We check for /home because we don't want to interfere with
402
# CGIRequest, which fileservice still uses.
403
if script_path and script_path.startswith('/home'):
404
normscript = os.path.normpath(script_path)
406
uri_into_jail = studpath.to_home_path(os.path.normpath(req.path))
408
# PATH_INFO is wrong because the script doesn't physically exist.
409
env['PATH_INFO'] = uri_into_jail[len(normscript):]
410
if len(env['PATH_INFO']) > 0:
411
env['SCRIPT_NAME'] = normuri[:-len(env['PATH_INFO'])]
413
# SERVER_SOFTWARE is actually not Apache but IVLE, since we are
414
# custom-making the CGI request.
415
env['SERVER_SOFTWARE'] = "IVLE/" + ivle.__version__
417
# Additional environment variables
418
username = split_path(req.path)[0]
419
env['HOME'] = os.path.join('/home', username)
421
class ExecutionError(Exception):
424
def execute_raw(config, user, jail_dir, working_dir, binary, args):
425
'''Execute a binary in a user's jail, returning the raw output.
427
The binary is executed in the given working directory with the given
428
args. A tuple of (stdout, stderr) is returned.
431
tramp = os.path.join(config['paths']['lib'], 'trampoline')
432
tramp_dir = os.path.split(tramp)[0]
434
# Fire up trampoline. Vroom, vroom.
435
proc = subprocess.Popen(
436
[tramp, str(user.unixid), config['paths']['jails']['mounts'],
437
config['paths']['jails']['src'],
438
config['paths']['jails']['template'],
439
jail_dir, working_dir, binary] + args,
440
stdin=subprocess.PIPE, stdout=subprocess.PIPE,
441
stderr=subprocess.PIPE, cwd=tramp_dir, close_fds=True)
443
(stdout, stderr) = proc.communicate()
444
exitcode = proc.returncode
447
raise ExecutionError('subprocess ended with code %d, stderr %s' %
448
(exitcode, proc.stderr.read()))
449
return (stdout, stderr)