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.
24
from ivle import studpath
25
from ivle.util import IVLEError, IVLEJailError
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, trampoline, uid, jail_dir, working_dir,
92
script_path, req, gentle):
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
# Support no-op trampoline runs.
109
if interpreter is None:
110
interpreter = '/bin/true'
116
# Get the student program's directory and execute it from that context.
117
(tramp_dir, _) = os.path.split(trampoline)
119
# TODO: Don't create a file if the body length is known to be 0
120
# Write the HTTP body to a temporary file so it can be passed as a *real*
123
body = req.read() if not noop else None
127
f.seek(0) # Rewind, for reading
129
# Set up the environment
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():
139
# usage: tramp uid jail_dir working_dir script_path
140
pid = subprocess.Popen(
141
[trampoline, str(uid), jail_dir, working_dir, interpreter,
143
stdin=f, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
146
# Restore the environment
147
for k in os.environ.keys():
149
for (k,v) in old_env.items():
152
# We don't want any output! Bail out after the process terminates.
157
# process_cgi_line: Reads a single line of CGI output and processes it.
158
# Prints to req, and also does fancy HTML warnings if Content-Type
160
cgiflags = CGIFlags(gentle)
162
# Read from the process's stdout into req
163
data = pid.stdout.read(CGI_BLOCK_SIZE)
165
process_cgi_output(req, data, cgiflags)
166
data = pid.stdout.read(CGI_BLOCK_SIZE)
168
# If we haven't processed headers yet, now is a good time
169
if not cgiflags.started_cgi_body:
170
process_cgi_output(req, '\n', cgiflags)
172
# If we wrote an HTML warning header, write the footer
173
if cgiflags.wrote_html_warning:
179
def process_cgi_output(req, data, cgiflags):
180
"""Processes a chunk of CGI output. data is a string of arbitrary length;
181
some arbitrary chunk of output written by the CGI script."""
182
if cgiflags.started_cgi_body:
183
if cgiflags.wrote_html_warning:
184
# HTML escape text if wrote_html_warning
185
req.write(cgi.escape(data))
189
# Break data into lines of CGI header data.
190
linebuf = cgiflags.linebuf + data
191
# First see if we can split all header data
192
# We need to get the double CRLF- or LF-terminated headers, whichever
193
# is smaller, as either sequence may appear somewhere in the body.
194
usplit = linebuf.split('\n\n', 1)
195
wsplit = linebuf.split('\r\n\r\n', 1)
196
split = len(usplit[0]) > len(wsplit[0]) and wsplit or usplit
198
# Haven't seen all headers yet. Buffer and come back later.
199
cgiflags.linebuf = linebuf
204
cgiflags.linebuf = ""
205
cgiflags.started_cgi_body = True
206
# Process all the header lines
207
split = headers.split('\r\n', 1)
209
split = headers.split('\n', 1)
211
process_cgi_header_line(req, split[0], cgiflags)
212
if len(split) == 1: break
214
if cgiflags.wrote_html_warning:
215
# We're done with headers. Treat the rest as data.
216
data = headers + '\n' + data
218
split = headers.split('\r\n', 1)
220
split = headers.split('\n', 1)
222
# Is this an internal IVLE error condition?
223
hs = cgiflags.headers
224
if 'X-IVLE-Error-Type' in hs:
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')
237
# Check to make sure the required headers were written
238
if cgiflags.wrote_html_warning or not cgiflags.gentle:
239
# We already reported an error, that's enough
241
elif "Content-Type" in cgiflags.headers:
243
elif "Location" in cgiflags.headers:
244
if ("Status" in cgiflags.headers and req.status >= 300
245
and req.status < 400):
248
message = """You did not write a valid status code for
249
the given location. To make a redirect, you may wish to try:</p>
250
<pre style="margin-left: 1em">Status: 302 Found
251
Location: <redirect address></pre>"""
252
write_html_warning(req, message)
253
cgiflags.wrote_html_warning = True
255
message = """You did not print a Content-Type header.
256
CGI requires that you print a "Content-Type". You may wish to try:</p>
257
<pre style="margin-left: 1em">Content-Type: text/html</pre>"""
258
write_html_warning(req, message)
259
cgiflags.wrote_html_warning = True
261
# Call myself to flush out the extra bit of data we read
262
process_cgi_output(req, data, cgiflags)
264
def process_cgi_header_line(req, line, cgiflags):
265
"""Process a line of CGI header data. line is a string representing a
266
complete line of text, stripped and without the newline.
269
name, value = line.split(':', 1)
271
# No colon. The user did not write valid headers.
272
# If we are being gentle, we want to help the user understand what
273
# went wrong. Otherwise, just admit we screwed up.
275
if not cgiflags.gentle:
276
message = """An unexpected server error has occured."""
278
elif len(cgiflags.headers) == 0:
279
# First line was not a header line. We can assume this is not
281
message = """You did not print a CGI header.
282
CGI requires that you print a "Content-Type". You may wish to try:</p>
283
<pre style="margin-left: 1em">Content-Type: text/html</pre>"""
285
# They printed some header at least, but there was an invalid
287
message = """You printed an invalid CGI header. You need to leave
288
a blank line after the headers, before writing the page contents."""
289
write_html_warning(req, message, warning=warning)
290
cgiflags.wrote_html_warning = True
291
# Handle the rest of this line as normal data
292
process_cgi_output(req, line + '\n', cgiflags)
296
value = value.strip()
297
if name == "Content-Type":
298
req.content_type = value
299
elif name == "Location":
301
elif name == "Status":
302
# Must be an integer, followed by a space, and then the status line
303
# which we ignore (seems like Apache has no way to send a custom
306
req.status = int(value.split(' ', 1)[0])
308
if not cgiflags.gentle:
309
# This isn't user code, so it should be good.
310
# Get us out of here!
312
message = """The "Status" CGI header was invalid. You need to
313
print a number followed by a message, such as "302 Found"."""
314
write_html_warning(req, message)
315
cgiflags.wrote_html_warning = True
316
# Handle the rest of this line as normal data
317
process_cgi_output(req, line + '\n', cgiflags)
319
# Generic HTTP header
320
# FIXME: Security risk letting users write arbitrary headers?
321
req.headers_out.add(name, value)
322
cgiflags.headers[name] = value # FIXME: Only the last header will end up here.
324
def write_html_warning(req, text, warning="Warning"):
325
"""Prints an HTML warning about invalid CGI interaction on the part of the
326
user. text may contain HTML markup."""
327
req.content_type = "text/html"
328
req.write("""<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
329
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
330
<html xmlns="http://www.w3.org/1999/xhtml">
332
<meta http-equiv="Content-Type"
333
content="text/html; charset=utf-8" />
335
<body style="margin: 0; padding: 0; font-family: sans-serif;">
336
<div style="background-color: #faa; border-bottom: 1px solid black;
338
<p><strong>%s</strong>: %s
340
<div style="margin: 8px;">
342
""" % (warning, text))
344
location_cgi_python = os.path.join(ivle.conf.lib_path, "trampoline")
346
# Mapping of interpreter names (as given in conf/app/server.py) to
347
# interpreter functions.
349
interpreter_objects = {
351
: functools.partial(execute_cgi, "/usr/bin/python",
352
location_cgi_python),
354
: functools.partial(execute_cgi, None,
355
location_cgi_python),
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.
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
# 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'] = ''
396
# CGI specifies that REMOTE_HOST SHOULD be set, and MAY just be set to
397
# REMOTE_ADDR. Since Apache does not appear to set this, set it to
399
if 'REMOTE_HOST' not in env and 'REMOTE_ADDR' in env:
400
env['REMOTE_HOST'] = env['REMOTE_ADDR']
402
# SCRIPT_NAME is the path to the script WITHOUT PATH_INFO.
403
script_name = req.uri
404
env['SCRIPT_NAME'] = script_name
406
# SERVER_SOFTWARE is actually not Apache but IVLE, since we are
407
# custom-making the CGI request.
408
env['SERVER_SOFTWARE'] = "IVLE/" + str(ivle.conf.ivle_version)
410
# Additional environment variables
411
username = studpath.url_to_jailpaths(req.path)[0]
412
env['HOME'] = os.path.join('/home', username)
414
class ExecutionError(Exception):
417
def execute_raw(user, jail_dir, working_dir, binary, args):
418
'''Execute a binary in a user's jail, returning the raw output.
420
The binary is executed in the given working directory with the given
421
args. A tuple of (stdout, stderr) is returned.
424
tramp = location_cgi_python
425
tramp_dir = os.path.split(location_cgi_python)[0]
427
# Fire up trampoline. Vroom, vroom.
428
proc = subprocess.Popen(
429
[tramp, str(user.unixid), jail_dir, working_dir, binary] + args,
430
stdin=subprocess.PIPE, stdout=subprocess.PIPE,
431
stderr=subprocess.PIPE, cwd=tramp_dir, close_fds=True)
432
exitcode = proc.wait()
435
raise ExecutionError('subprocess ended with code %d, stderr %s' %
436
(exitcode, proc.stderr.read()))
437
return (proc.stdout.read(), proc.stderr.read())