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

« back to all changes in this revision

Viewing changes to ivle/interpret.py

  • Committer: David Coles
  • Date: 2010-07-17 11:32:50 UTC
  • Revision ID: coles.david@gmail.com-20100717113250-vi18n50bcjmfmzrt
Show warning for CGI header field-names which contain restricted characters.

Forbidden characters are the separators defined by RFC3875. This is mainly to 
fix an issue where printing a dictionary (with no CGI headers) could be 
assumed to be a CGI header with no warnings.

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 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
        # If not executing in gentle mode (which presents CGI violations
 
219
        # to users nicely), check if this an internal IVLE error
 
220
        # condition.
 
221
        if not cgiflags.gentle:
 
222
            hs = cgiflags.headers
 
223
            if 'X-IVLE-Error-Type' in hs:
 
224
                try:
 
225
                    raise IVLEJailError(hs['X-IVLE-Error-Type'],
 
226
                                        hs['X-IVLE-Error-Message'],
 
227
                                        hs['X-IVLE-Error-Info'])
 
228
                except KeyError:
 
229
                    raise AssertionError("Bad error headers written by CGI.")
 
230
 
 
231
        # Check to make sure the required headers were written
 
232
        if cgiflags.wrote_html_warning or not cgiflags.gentle:
 
233
            # We already reported an error, that's enough
 
234
            pass
 
235
        elif "Content-Type" in cgiflags.headers:
 
236
            pass
 
237
        elif "Location" in cgiflags.headers:
 
238
            if ("Status" in cgiflags.headers and req.status >= 300
 
239
                and req.status < 400):
 
240
                pass
 
241
            else:
 
242
                message = """You did not write a valid status code for
 
243
the given location. To make a redirect, you may wish to try:</p>
 
244
<pre style="margin-left: 1em">Status: 302 Found
 
245
Location: &lt;redirect address&gt;</pre>"""
 
246
                write_html_warning(req, message)
 
247
                cgiflags.wrote_html_warning = True
 
248
        else:
 
249
            message = """You did not print a Content-Type header.
 
250
CGI requires that you print a "Content-Type". You may wish to try:</p>
 
251
<pre style="margin-left: 1em">Content-Type: text/html</pre>"""
 
252
            write_html_warning(req, message)
 
253
            cgiflags.wrote_html_warning = True
 
254
 
 
255
        # Call myself to flush out the extra bit of data we read
 
256
        process_cgi_output(req, data, cgiflags)
 
257
 
 
258
def process_cgi_header_line(req, line, cgiflags):
 
259
    """Process a line of CGI header data. line is a string representing a
 
260
    complete line of text, stripped and without the newline.
 
261
    """
 
262
    try:
 
263
        name, value = line.split(':', 1)
 
264
    except ValueError:
 
265
        # No colon. The user did not write valid headers.
 
266
        # If we are being gentle, we want to help the user understand what
 
267
        # went wrong. Otherwise, just admit we screwed up.
 
268
        warning = "Warning"
 
269
        if not cgiflags.gentle:
 
270
            message = """An unexpected server error has occured."""
 
271
            warning = "Error"
 
272
        elif len(cgiflags.headers) == 0:
 
273
            # First line was not a header line. We can assume this is not
 
274
            # a CGI app.
 
275
            message = """You did not print a CGI header.
 
276
CGI requires that you print a "Content-Type". You may wish to try:</p>
 
277
<pre style="margin-left: 1em">Content-Type: text/html</pre>"""
 
278
        else:
 
279
            # They printed some header at least, but there was an invalid
 
280
            # header.
 
281
            message = """You printed an invalid CGI header. You need to leave
 
282
a blank line after the headers, before writing the page contents."""
 
283
        write_html_warning(req, message, warning=warning)
 
284
        cgiflags.wrote_html_warning = True
 
285
        # Handle the rest of this line as normal data
 
286
        process_cgi_output(req, line + '\n', cgiflags)
 
287
        return
 
288
 
 
289
    # Check if CGI field-name is valid
 
290
    CGI_SEPERATORS = set(['(', ')', '<', '>', '@', ',', ';', ':', '\\', '"',
 
291
            '/', '[', ']', '?', '=', '{', '}', ' ', '\t'])
 
292
    if any((char in CGI_SEPERATORS for char in name)):
 
293
        warning = "Warning"
 
294
        if not cgiflags.gentle:
 
295
            message = """An unexpected server error has occured."""
 
296
            warning = "Error"
 
297
        else:
 
298
            # Header contained illegal characters
 
299
            message = """You printed an invalid CGI header. CGI header
 
300
            field-names can not contain any of the following characters: 
 
301
            <code>( ) &lt; &gt; @ , ; : \\ " / [ ] ? = { } <em>SPACE 
 
302
            TAB</em></code>."""
 
303
        write_html_warning(req, message, warning=warning)
 
304
        cgiflags.wrote_html_warning = True
 
305
        # Handle the rest of this line as normal data
 
306
        process_cgi_output(req, line + '\n', cgiflags)
 
307
        return
 
308
 
 
309
    # Read CGI headers
 
310
    value = value.strip()
 
311
    if name == "Content-Type":
 
312
        req.content_type = value
 
313
    elif name == "Location":
 
314
        req.location = value
 
315
    elif name == "Status":
 
316
        # Must be an integer, followed by a space, and then the status line
 
317
        # which we ignore (seems like Apache has no way to send a custom
 
318
        # status line).
 
319
        try:
 
320
            req.status = int(value.split(' ', 1)[0])
 
321
        except ValueError:
 
322
            if not cgiflags.gentle:
 
323
                # This isn't user code, so it should be good.
 
324
                # Get us out of here!
 
325
                raise
 
326
            message = """The "Status" CGI header was invalid. You need to
 
327
print a number followed by a message, such as "302 Found"."""
 
328
            write_html_warning(req, message)
 
329
            cgiflags.wrote_html_warning = True
 
330
            # Handle the rest of this line as normal data
 
331
            process_cgi_output(req, line + '\n', cgiflags)
 
332
    else:
 
333
        # Generic HTTP header
 
334
        # FIXME: Security risk letting users write arbitrary headers?
 
335
        req.headers_out.add(name, value)
 
336
    cgiflags.headers[name] = value # FIXME: Only the last header will end up here.
 
337
 
 
338
def write_html_warning(req, text, warning="Warning"):
 
339
    """Prints an HTML warning about invalid CGI interaction on the part of the
 
340
    user. text may contain HTML markup."""
 
341
    req.content_type = "text/html"
 
342
    req.write("""<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
 
343
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
 
344
<html xmlns="http://www.w3.org/1999/xhtml">
 
345
<head>
 
346
  <meta http-equiv="Content-Type"
 
347
    content="text/html; charset=utf-8" />
 
348
</head>
 
349
<body style="margin: 0; padding: 0; font-family: sans-serif;">
 
350
  <div style="background-color: #faa; border-bottom: 1px solid black;
 
351
    padding: 8px;">
 
352
    <p><strong>%s</strong>: %s
 
353
  </div>
 
354
  <div style="margin: 8px;">
 
355
    <pre>
 
356
""" % (warning, text))
 
357
 
 
358
# Mapping of interpreter names (as given in conf/app/server.py) to
 
359
# interpreter functions.
 
360
 
 
361
interpreter_objects = {
 
362
    'cgi-python'
 
363
        : functools.partial(execute_cgi, "/usr/bin/python"),
 
364
    'noop'
 
365
        : functools.partial(execute_cgi, None),
 
366
    # Should also have:
 
367
    # cgi-generic
 
368
    # python-server-page
 
369
}
 
370
 
 
371
def cgi_environ(req, script_path, user):
 
372
    """Gets CGI variables from apache and makes a few changes for security and 
 
373
    correctness.
 
374
 
 
375
    Does not modify req, only reads it.
 
376
    """
 
377
    env = {}
 
378
    # Comments here are on the heavy side, explained carefully for security
 
379
    # reasons. Please read carefully before making changes.
 
380
    
 
381
    # This automatically asks mod_python to load up the CGI variables into the
 
382
    # environment (which is a good first approximation)
 
383
    for (k,v) in req.get_cgi_environ().items():
 
384
        env[k] = v
 
385
 
 
386
    # Remove DOCUMENT_ROOT and SCRIPT_FILENAME. Not part of CGI spec and
 
387
    # exposes unnecessary details about server.
 
388
    try:
 
389
        del env['DOCUMENT_ROOT']
 
390
    except: pass
 
391
    try:
 
392
        del env['SCRIPT_FILENAME']
 
393
    except: pass
 
394
 
 
395
    # Remove PATH. The PATH here is the path on the server machine; not useful
 
396
    # inside the jail. It may be a good idea to add another path, reflecting
 
397
    # the inside of the jail, but not done at this stage.
 
398
    try:
 
399
        del env['PATH']
 
400
    except: pass
 
401
 
 
402
    # CGI specifies that REMOTE_HOST SHOULD be set, and MAY just be set to
 
403
    # REMOTE_ADDR. Since Apache does not appear to set this, set it to
 
404
    # REMOTE_ADDR.
 
405
    if 'REMOTE_HOST' not in env and 'REMOTE_ADDR' in env:
 
406
        env['REMOTE_HOST'] = env['REMOTE_ADDR']
 
407
 
 
408
    env['PATH_INFO'] = ''
 
409
    del env['PATH_TRANSLATED']
 
410
 
 
411
    normuri = os.path.normpath(req.uri)
 
412
    env['SCRIPT_NAME'] = normuri
 
413
 
 
414
    # SCRIPT_NAME is the path to the script WITHOUT PATH_INFO.
 
415
    # We don't care about these if the script is null (ie. noop).
 
416
    # XXX: We check for /home because we don't want to interfere with
 
417
    # CGIRequest, which fileservice still uses.
 
418
    if script_path and script_path.startswith('/home'):
 
419
        normscript = os.path.normpath(script_path)
 
420
 
 
421
        uri_into_jail = studpath.to_home_path(os.path.normpath(req.path))
 
422
 
 
423
        # PATH_INFO is wrong because the script doesn't physically exist.
 
424
        env['PATH_INFO'] = uri_into_jail[len(normscript):]
 
425
        if len(env['PATH_INFO']) > 0:
 
426
            env['SCRIPT_NAME'] = normuri[:-len(env['PATH_INFO'])]
 
427
 
 
428
    # SERVER_SOFTWARE is actually not Apache but IVLE, since we are
 
429
    # custom-making the CGI request.
 
430
    env['SERVER_SOFTWARE'] = "IVLE/" + ivle.__version__
 
431
 
 
432
    # Additional environment variables
 
433
    username = user.login
 
434
    env['HOME'] = os.path.join('/home', username)
 
435
 
 
436
    return env
 
437
 
 
438
class ExecutionError(Exception):
 
439
    pass
 
440
 
 
441
def execute_raw(config, user, jail_dir, working_dir, binary, args):
 
442
    '''Execute a binary in a user's jail, returning the raw output.
 
443
 
 
444
    The binary is executed in the given working directory with the given
 
445
    args. A tuple of (stdout, stderr) is returned.
 
446
    '''
 
447
 
 
448
    tramp = os.path.join(config['paths']['lib'], 'trampoline')
 
449
    tramp_dir = os.path.split(tramp)[0]
 
450
 
 
451
    # Fire up trampoline. Vroom, vroom.
 
452
    cmd_line = [tramp, str(user.unixid), config['paths']['jails']['mounts'],
 
453
         config['paths']['jails']['src'],
 
454
         config['paths']['jails']['template'],
 
455
         jail_dir, working_dir, binary] + args
 
456
    # Popen doesn't like unicode strings. It hateses them.
 
457
    cmd_line = [(s.encode('utf-8') if isinstance(s, unicode) else s)
 
458
                for s in cmd_line]
 
459
    proc = subprocess.Popen(cmd_line,
 
460
        stdin=subprocess.PIPE, stdout=subprocess.PIPE,
 
461
        stderr=subprocess.PIPE, cwd=tramp_dir, close_fds=True,
 
462
        env={'HOME': os.path.join('/home', user.login),
 
463
             'PATH': PATH,
 
464
             'USER': user.login,
 
465
             'LOGNAME': user.login})
 
466
 
 
467
    (stdout, stderr) = proc.communicate()
 
468
    exitcode = proc.returncode
 
469
 
 
470
    if exitcode != 0:
 
471
        raise ExecutionError('subprocess ended with code %d, stderr: "%s"' %
 
472
                             (exitcode, stderr))
 
473
    return (stdout, stderr)