~azzar1/unity/add-show-desktop-key

« back to all changes in this revision

Viewing changes to ivle/interpret.py

  • Committer: David Coles
  • Date: 2010-03-01 09:15:34 UTC
  • Revision ID: coles.david@gmail.com-20100301091534-vnisqvl35j5jmmco
interpret: Don't mutate os.environ for execute_cgi, Set an environ on subprocess.Popen instead.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# IVLE
 
2
# Copyright (C) 2007-2008 The University of Melbourne
 
3
#
 
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.
 
8
#
 
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.
 
13
#
 
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
 
17
 
 
18
# Module: Interpret
 
19
# Author: Matt Giuca
 
20
# Date: 18/1/2008
 
21
 
 
22
# Runs a student script in a safe execution environment.
 
23
 
 
24
import ivle
 
25
from ivle import studpath
 
26
from ivle.util import IVLEError, IVLEJailError, split_path
 
27
 
 
28
import functools
 
29
 
 
30
import os
 
31
import pwd
 
32
import subprocess
 
33
import cgi
 
34
 
 
35
# TODO: Make progressive output work
 
36
# Question: Will having a large buffer size stop progressive output from
 
37
# working on smaller output
 
38
 
 
39
CGI_BLOCK_SIZE = 65535
 
40
PATH = "/usr/local/bin:/usr/bin:/bin"
 
41
 
 
42
def interpret_file(req, owner, jail_dir, filename, interpreter, gentle=True):
 
43
    """Serves a file by interpreting it using one of IVLE's builtin
 
44
    interpreters. All interpreters are intended to run in the user's jail. The
 
45
    jail location is provided as an argument to the interpreter but it is up
 
46
    to the individual interpreters to create the jail.
 
47
 
 
48
    req: An IVLE request object.
 
49
    owner: The user who owns the file being served.
 
50
    jail_dir: Absolute path to the user's jail.
 
51
    filename: Absolute filename within the user's jail.
 
52
    interpreter: A function object to call.
 
53
    """
 
54
    # We can't test here whether or not the target file actually exists,
 
55
    # because the apache user may not have permission. Instead we have to
 
56
    # rely on the interpreter generating an error.
 
57
    if filename.startswith(os.sep):
 
58
        filename_abs = filename
 
59
        filename_rel = filename[1:]
 
60
    else:
 
61
        filename_abs = os.path.join(os.sep, filename)
 
62
        filename_rel = filename
 
63
 
 
64
    # (Note: files are executed by their owners, not the logged in user.
 
65
    # This ensures users are responsible for their own programs and also
 
66
    # allows them to be executed by the public).
 
67
 
 
68
    # Split up req.path again, this time with respect to the jail
 
69
    (working_dir, _) = os.path.split(filename_abs)
 
70
    # jail_dir is the absolute jail directory.
 
71
    # path is the filename relative to the user's jail.
 
72
    # working_dir is the directory containing the file relative to the user's
 
73
    # jail.
 
74
    # (Note that paths "relative" to the jail actually begin with a '/' as
 
75
    # they are absolute in the jailspace)
 
76
 
 
77
    return interpreter(owner, jail_dir, working_dir, filename_abs, req,
 
78
                       gentle)
 
79
 
 
80
class CGIFlags:
 
81
    """Stores flags regarding the state of reading CGI output.
 
82
       If this is to be gentle, detection of invalid headers will result in an
 
83
       HTML warning."""
 
84
    def __init__(self, begentle=True):
 
85
        self.gentle = begentle
 
86
        self.started_cgi_body = False
 
87
        self.got_cgi_headers = False
 
88
        self.wrote_html_warning = False
 
89
        self.linebuf = ""
 
90
        self.headers = {}       # Header names : values
 
91
 
 
92
def execute_cgi(interpreter, owner, jail_dir, working_dir, script_path,
 
93
                req, gentle):
 
94
    """
 
95
    trampoline: Full path on the local system to the CGI wrapper program
 
96
        being executed.
 
97
    owner: User object of the owner of the file.
 
98
    jail_dir: Absolute path of owner's jail directory.
 
99
    working_dir: Directory containing the script file relative to owner's
 
100
        jail.
 
101
    script_path: CGI script relative to the owner's jail.
 
102
    req: IVLE request object.
 
103
 
 
104
    The called CGI wrapper application shall be called using popen and receive
 
105
    the HTTP body on stdin. It shall receive the CGI environment variables to
 
106
    its environment.
 
107
    """
 
108
 
 
109
    trampoline = os.path.join(req.config['paths']['lib'], 'trampoline')
 
110
 
 
111
    # Support no-op trampoline runs.
 
112
    if interpreter is None:
 
113
        interpreter = '/bin/true'
 
114
        script_path = ''
 
115
        noop = True
 
116
    else:
 
117
        noop = False
 
118
 
 
119
    # Get the student program's directory and execute it from that context.
 
120
    (tramp_dir, _) = os.path.split(trampoline)
 
121
 
 
122
    # TODO: Don't create a file if the body length is known to be 0
 
123
    # Write the HTTP body to a temporary file so it can be passed as a *real*
 
124
    # file to popen.
 
125
    f = os.tmpfile()
 
126
    body = req.read() if not noop else None
 
127
    if body is not None:
 
128
        f.write(body)
 
129
        f.flush()
 
130
        f.seek(0)       # Rewind, for reading
 
131
 
 
132
    # Set up the environment
 
133
    environ = cgi_environ(req, script_path, owner)
 
134
 
 
135
    # 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)
 
143
                for s in cmd_line]
 
144
    pid = subprocess.Popen(cmd_line,
 
145
        stdin=f, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
 
146
        cwd=tramp_dir, env=environ)
 
147
 
 
148
    # We don't want any output! Bail out after the process terminates.
 
149
    if noop:
 
150
        pid.communicate()
 
151
        return
 
152
 
 
153
    # process_cgi_line: Reads a single line of CGI output and processes it.
 
154
    # Prints to req, and also does fancy HTML warnings if Content-Type
 
155
    # omitted.
 
156
    cgiflags = CGIFlags(gentle)
 
157
 
 
158
    # Read from the process's stdout into req
 
159
    data = pid.stdout.read(CGI_BLOCK_SIZE)
 
160
    while len(data) > 0:
 
161
        process_cgi_output(req, data, cgiflags)
 
162
        data = pid.stdout.read(CGI_BLOCK_SIZE)
 
163
 
 
164
    # If we haven't processed headers yet, now is a good time
 
165
    if not cgiflags.started_cgi_body:
 
166
        process_cgi_output(req, '\n', cgiflags)
 
167
 
 
168
    # If we wrote an HTML warning header, write the footer
 
169
    if cgiflags.wrote_html_warning:
 
170
        req.write("""</pre>
 
171
  </div>
 
172
</body>
 
173
</html>""")
 
174
 
 
175
def process_cgi_output(req, data, cgiflags):
 
176
    """Processes a chunk of CGI output. data is a string of arbitrary length;
 
177
    some arbitrary chunk of output written by the CGI script."""
 
178
    if cgiflags.started_cgi_body:
 
179
        if cgiflags.wrote_html_warning:
 
180
            # HTML escape text if wrote_html_warning
 
181
            req.write(cgi.escape(data))
 
182
        else:
 
183
            req.write(data)
 
184
    else:
 
185
        # Break data into lines of CGI header data. 
 
186
        linebuf = cgiflags.linebuf + data
 
187
        # First see if we can split all header data
 
188
        # We need to get the double CRLF- or LF-terminated headers, whichever
 
189
        # is smaller, as either sequence may appear somewhere in the body.
 
190
        usplit = linebuf.split('\n\n', 1)
 
191
        wsplit = linebuf.split('\r\n\r\n', 1)
 
192
        split = len(usplit[0]) > len(wsplit[0]) and wsplit or usplit
 
193
        if len(split) == 1:
 
194
            # Haven't seen all headers yet. Buffer and come back later.
 
195
            cgiflags.linebuf = linebuf
 
196
            return
 
197
 
 
198
        headers = split[0]
 
199
        data = split[1]
 
200
        cgiflags.linebuf = ""
 
201
        cgiflags.started_cgi_body = True
 
202
        # Process all the header lines
 
203
        split = headers.split('\r\n', 1)
 
204
        if len(split) == 1:
 
205
            split = headers.split('\n', 1)
 
206
        while True:
 
207
            process_cgi_header_line(req, split[0], cgiflags)
 
208
            if len(split) == 1: break
 
209
            headers = split[1]
 
210
            if cgiflags.wrote_html_warning:
 
211
                # We're done with headers. Treat the rest as data.
 
212
                data = headers + '\n' + data
 
213
                break
 
214
            split = headers.split('\r\n', 1)
 
215
            if len(split) == 1:
 
216
                split = headers.split('\n', 1)
 
217
 
 
218
        # Is this an internal IVLE error condition?
 
219
        hs = cgiflags.headers
 
220
        if 'X-IVLE-Error-Type' in hs:
 
221
            t = hs['X-IVLE-Error-Type']
 
222
            if t == IVLEError.__name__:
 
223
                raise IVLEError(int(hs['X-IVLE-Error-Code']),
 
224
                                hs['X-IVLE-Error-Message'])
 
225
            else:
 
226
                try:
 
227
                    raise IVLEJailError(hs['X-IVLE-Error-Type'],
 
228
                                        hs['X-IVLE-Error-Message'],
 
229
                                        hs['X-IVLE-Error-Info'])
 
230
                except KeyError:
 
231
                    raise IVLEError(500, 'bad error headers written by CGI')
 
232
 
 
233
        # Check to make sure the required headers were written
 
234
        if cgiflags.wrote_html_warning or not cgiflags.gentle:
 
235
            # We already reported an error, that's enough
 
236
            pass
 
237
        elif "Content-Type" in cgiflags.headers:
 
238
            pass
 
239
        elif "Location" in cgiflags.headers:
 
240
            if ("Status" in cgiflags.headers and req.status >= 300
 
241
                and req.status < 400):
 
242
                pass
 
243
            else:
 
244
                message = """You did not write a valid status code for
 
245
the given location. To make a redirect, you may wish to try:</p>
 
246
<pre style="margin-left: 1em">Status: 302 Found
 
247
Location: &lt;redirect address&gt;</pre>"""
 
248
                write_html_warning(req, message)
 
249
                cgiflags.wrote_html_warning = True
 
250
        else:
 
251
            message = """You did not print a Content-Type header.
 
252
CGI requires that you print a "Content-Type". You may wish to try:</p>
 
253
<pre style="margin-left: 1em">Content-Type: text/html</pre>"""
 
254
            write_html_warning(req, message)
 
255
            cgiflags.wrote_html_warning = True
 
256
 
 
257
        # Call myself to flush out the extra bit of data we read
 
258
        process_cgi_output(req, data, cgiflags)
 
259
 
 
260
def process_cgi_header_line(req, line, cgiflags):
 
261
    """Process a line of CGI header data. line is a string representing a
 
262
    complete line of text, stripped and without the newline.
 
263
    """
 
264
    try:
 
265
        name, value = line.split(':', 1)
 
266
    except ValueError:
 
267
        # No colon. The user did not write valid headers.
 
268
        # If we are being gentle, we want to help the user understand what
 
269
        # went wrong. Otherwise, just admit we screwed up.
 
270
        warning = "Warning"
 
271
        if not cgiflags.gentle:
 
272
            message = """An unexpected server error has occured."""
 
273
            warning = "Error"
 
274
        elif len(cgiflags.headers) == 0:
 
275
            # First line was not a header line. We can assume this is not
 
276
            # a CGI app.
 
277
            message = """You did not print a CGI header.
 
278
CGI requires that you print a "Content-Type". You may wish to try:</p>
 
279
<pre style="margin-left: 1em">Content-Type: text/html</pre>"""
 
280
        else:
 
281
            # They printed some header at least, but there was an invalid
 
282
            # header.
 
283
            message = """You printed an invalid CGI header. You need to leave
 
284
a blank line after the headers, before writing the page contents."""
 
285
        write_html_warning(req, message, warning=warning)
 
286
        cgiflags.wrote_html_warning = True
 
287
        # Handle the rest of this line as normal data
 
288
        process_cgi_output(req, line + '\n', cgiflags)
 
289
        return
 
290
 
 
291
    # Read CGI headers
 
292
    value = value.strip()
 
293
    if name == "Content-Type":
 
294
        req.content_type = value
 
295
    elif name == "Location":
 
296
        req.location = value
 
297
    elif name == "Status":
 
298
        # Must be an integer, followed by a space, and then the status line
 
299
        # which we ignore (seems like Apache has no way to send a custom
 
300
        # status line).
 
301
        try:
 
302
            req.status = int(value.split(' ', 1)[0])
 
303
        except ValueError:
 
304
            if not cgiflags.gentle:
 
305
                # This isn't user code, so it should be good.
 
306
                # Get us out of here!
 
307
                raise
 
308
            message = """The "Status" CGI header was invalid. You need to
 
309
print a number followed by a message, such as "302 Found"."""
 
310
            write_html_warning(req, message)
 
311
            cgiflags.wrote_html_warning = True
 
312
            # Handle the rest of this line as normal data
 
313
            process_cgi_output(req, line + '\n', cgiflags)
 
314
    else:
 
315
        # Generic HTTP header
 
316
        # FIXME: Security risk letting users write arbitrary headers?
 
317
        req.headers_out.add(name, value)
 
318
    cgiflags.headers[name] = value # FIXME: Only the last header will end up here.
 
319
 
 
320
def write_html_warning(req, text, warning="Warning"):
 
321
    """Prints an HTML warning about invalid CGI interaction on the part of the
 
322
    user. text may contain HTML markup."""
 
323
    req.content_type = "text/html"
 
324
    req.write("""<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
 
325
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
 
326
<html xmlns="http://www.w3.org/1999/xhtml">
 
327
<head>
 
328
  <meta http-equiv="Content-Type"
 
329
    content="text/html; charset=utf-8" />
 
330
</head>
 
331
<body style="margin: 0; padding: 0; font-family: sans-serif;">
 
332
  <div style="background-color: #faa; border-bottom: 1px solid black;
 
333
    padding: 8px;">
 
334
    <p><strong>%s</strong>: %s
 
335
  </div>
 
336
  <div style="margin: 8px;">
 
337
    <pre>
 
338
""" % (warning, text))
 
339
 
 
340
# Mapping of interpreter names (as given in conf/app/server.py) to
 
341
# interpreter functions.
 
342
 
 
343
interpreter_objects = {
 
344
    'cgi-python'
 
345
        : functools.partial(execute_cgi, "/usr/bin/python"),
 
346
    'noop'
 
347
        : functools.partial(execute_cgi, None),
 
348
    # Should also have:
 
349
    # cgi-generic
 
350
    # python-server-page
 
351
}
 
352
 
 
353
def cgi_environ(req, script_path, user):
 
354
    """Gets CGI variables from apache and makes a few changes for security and 
 
355
    correctness.
 
356
 
 
357
    Does not modify req, only reads it.
 
358
    """
 
359
    env = {}
 
360
    # Comments here are on the heavy side, explained carefully for security
 
361
    # reasons. Please read carefully before making changes.
 
362
    
 
363
    # This automatically asks mod_python to load up the CGI variables into the
 
364
    # environment (which is a good first approximation)
 
365
    for (k,v) in req.get_cgi_environ().items():
 
366
        env[k] = v
 
367
 
 
368
    # Remove DOCUMENT_ROOT and SCRIPT_FILENAME. Not part of CGI spec and
 
369
    # exposes unnecessary details about server.
 
370
    try:
 
371
        del env['DOCUMENT_ROOT']
 
372
    except: pass
 
373
    try:
 
374
        del env['SCRIPT_FILENAME']
 
375
    except: pass
 
376
 
 
377
    # Remove PATH. The PATH here is the path on the server machine; not useful
 
378
    # inside the jail. It may be a good idea to add another path, reflecting
 
379
    # the inside of the jail, but not done at this stage.
 
380
    try:
 
381
        del env['PATH']
 
382
    except: pass
 
383
 
 
384
    # CGI specifies that REMOTE_HOST SHOULD be set, and MAY just be set to
 
385
    # REMOTE_ADDR. Since Apache does not appear to set this, set it to
 
386
    # REMOTE_ADDR.
 
387
    if 'REMOTE_HOST' not in env and 'REMOTE_ADDR' in env:
 
388
        env['REMOTE_HOST'] = env['REMOTE_ADDR']
 
389
 
 
390
    env['PATH_INFO'] = ''
 
391
    del env['PATH_TRANSLATED']
 
392
 
 
393
    normuri = os.path.normpath(req.uri)
 
394
    env['SCRIPT_NAME'] = normuri
 
395
 
 
396
    # SCRIPT_NAME is the path to the script WITHOUT PATH_INFO.
 
397
    # We don't care about these if the script is null (ie. noop).
 
398
    # XXX: We check for /home because we don't want to interfere with
 
399
    # CGIRequest, which fileservice still uses.
 
400
    if script_path and script_path.startswith('/home'):
 
401
        normscript = os.path.normpath(script_path)
 
402
 
 
403
        uri_into_jail = studpath.to_home_path(os.path.normpath(req.path))
 
404
 
 
405
        # PATH_INFO is wrong because the script doesn't physically exist.
 
406
        env['PATH_INFO'] = uri_into_jail[len(normscript):]
 
407
        if len(env['PATH_INFO']) > 0:
 
408
            env['SCRIPT_NAME'] = normuri[:-len(env['PATH_INFO'])]
 
409
 
 
410
    # SERVER_SOFTWARE is actually not Apache but IVLE, since we are
 
411
    # custom-making the CGI request.
 
412
    env['SERVER_SOFTWARE'] = "IVLE/" + ivle.__version__
 
413
 
 
414
    # Additional environment variables
 
415
    username = user.login
 
416
    env['HOME'] = os.path.join('/home', username)
 
417
 
 
418
    return env
 
419
 
 
420
class ExecutionError(Exception):
 
421
    pass
 
422
 
 
423
def execute_raw(config, user, jail_dir, working_dir, binary, args):
 
424
    '''Execute a binary in a user's jail, returning the raw output.
 
425
 
 
426
    The binary is executed in the given working directory with the given
 
427
    args. A tuple of (stdout, stderr) is returned.
 
428
    '''
 
429
 
 
430
    tramp = os.path.join(config['paths']['lib'], 'trampoline')
 
431
    tramp_dir = os.path.split(tramp)[0]
 
432
 
 
433
    # Fire up trampoline. Vroom, vroom.
 
434
    cmd_line = [tramp, str(user.unixid), config['paths']['jails']['mounts'],
 
435
         config['paths']['jails']['src'],
 
436
         config['paths']['jails']['template'],
 
437
         jail_dir, working_dir, binary] + args
 
438
    # Popen doesn't like unicode strings. It hateses them.
 
439
    cmd_line = [(s.encode('utf-8') if isinstance(s, unicode) else s)
 
440
                for s in cmd_line]
 
441
    proc = subprocess.Popen(cmd_line,
 
442
        stdin=subprocess.PIPE, stdout=subprocess.PIPE,
 
443
        stderr=subprocess.PIPE, cwd=tramp_dir, close_fds=True,
 
444
        env={'HOME': os.path.join('/home', user.login),
 
445
             'PATH': PATH,
 
446
             'USER': user.login,
 
447
             'LOGNAME': user.login})
 
448
 
 
449
    (stdout, stderr) = proc.communicate()
 
450
    exitcode = proc.returncode
 
451
 
 
452
    if exitcode != 0:
 
453
        raise ExecutionError('subprocess ended with code %d, stderr: "%s"' %
 
454
                             (exitcode, stderr))
 
455
    return (stdout, stderr)