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

409 by mattgiuca
Moved www/conf and www/common to a new directory lib. This separates the "web"
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
# NOTE: This script currently disables cookies. This means students will be
25
# unable to write session-based or stateful web applications. This is done for
26
# security reasons (we do not want the students to see the IVLE cookie of
27
# whoever is visiting their pages).
28
# This can be resolved but needs careful sanitisation. See fixup_environ.
29
30
from common import studpath
31
import conf
32
import functools
33
34
import os
35
import pwd
36
import subprocess
37
import cgi
38
39
# TODO: Make progressive output work
40
# Question: Will having a large buffer size stop progressive output from
41
# working on smaller output
42
43
CGI_BLOCK_SIZE = 65535
44
420 by mattgiuca
common.interpret: Changed interface (refactor).
45
def interpret_file(req, owner, jail_dir, filename, interpreter):
409 by mattgiuca
Moved www/conf and www/common to a new directory lib. This separates the "web"
46
    """Serves a file by interpreting it using one of IVLE's builtin
47
    interpreters. All interpreters are intended to run in the user's jail. The
48
    jail location is provided as an argument to the interpreter but it is up
49
    to the individual interpreters to create the jail.
50
51
    req: An IVLE request object.
52
    owner: Username of the user who owns the file being served.
420 by mattgiuca
common.interpret: Changed interface (refactor).
53
    jail_dir: Absolute path to the user's jail.
421 by mattgiuca
apps/fileservice: Added code to call interpret on the trampoline version of
54
    filename: Absolute filename within the user's jail.
409 by mattgiuca
Moved www/conf and www/common to a new directory lib. This separates the "web"
55
    interpreter: A function object to call.
56
    """
57
    # Make sure the file exists (otherwise some interpreters may not actually
58
    # complain).
59
    # Don't test for execute permission, that will only be required for
60
    # certain interpreters.
421 by mattgiuca
apps/fileservice: Added code to call interpret on the trampoline version of
61
    if filename.startswith(os.sep):
62
        filename_abs = filename
63
        filename_rel = filename[1:]
64
    else:
65
        filename_abs = os.path.join(os.sep, filename)
66
        filename_rel = filename
67
68
    if not os.access(os.path.join(jail_dir, filename_rel), os.R_OK):
409 by mattgiuca
Moved www/conf and www/common to a new directory lib. This separates the "web"
69
        req.throw_error(req.HTTP_NOT_FOUND)
70
71
    # Get the UID of the owner of the file
72
    # (Note: files are executed by their owners, not the logged in user.
73
    # This ensures users are responsible for their own programs and also
74
    # allows them to be executed by the public).
505 by mattgiuca
dispatch.html, consoleservice, userservice, interpret:
75
    uid = req.user.unixid
409 by mattgiuca
Moved www/conf and www/common to a new directory lib. This separates the "web"
76
77
    # Split up req.path again, this time with respect to the jail
421 by mattgiuca
apps/fileservice: Added code to call interpret on the trampoline version of
78
    (working_dir, _) = os.path.split(filename_abs)
409 by mattgiuca
Moved www/conf and www/common to a new directory lib. This separates the "web"
79
    # jail_dir is the absolute jail directory.
80
    # path is the filename relative to the user's jail.
81
    # working_dir is the directory containing the file relative to the user's
82
    # jail.
83
    # (Note that paths "relative" to the jail actually begin with a '/' as
84
    # they are absolute in the jailspace)
85
421 by mattgiuca
apps/fileservice: Added code to call interpret on the trampoline version of
86
    return interpreter(uid, jail_dir, working_dir, filename_abs, req)
409 by mattgiuca
Moved www/conf and www/common to a new directory lib. This separates the "web"
87
88
class CGIFlags:
89
    """Stores flags regarding the state of reading CGI output."""
90
    def __init__(self):
91
        self.started_cgi_body = False
92
        self.got_cgi_headers = False
93
        self.wrote_html_warning = False
94
        self.linebuf = ""
95
        self.headers = {}       # Header names : values
96
97
def execute_cgi(interpreter, trampoline, uid, jail_dir, working_dir,
98
                script_path, req):
99
    """
100
    trampoline: Full path on the local system to the CGI wrapper program
101
        being executed.
102
    uid: User ID of the owner of the file.
103
    jail_dir: Absolute path of owner's jail directory.
104
    working_dir: Directory containing the script file relative to owner's
105
        jail.
106
    script_path: CGI script relative to the owner's jail.
107
    req: IVLE request object.
108
109
    The called CGI wrapper application shall be called using popen and receive
110
    the HTTP body on stdin. It shall receive the CGI environment variables to
111
    its environment.
112
    """
113
114
    # Get the student program's directory and execute it from that context.
115
    (tramp_dir, _) = os.path.split(trampoline)
116
117
    # TODO: Don't create a file if the body length is known to be 0
118
    # Write the HTTP body to a temporary file so it can be passed as a *real*
119
    # file to popen.
120
    f = os.tmpfile()
121
    body = req.read()
122
    if body is not None:
123
        f.write(body)
124
        f.flush()
125
        f.seek(0)       # Rewind, for reading
126
127
    # Set up the environment
128
    # This automatically asks mod_python to load up the CGI variables into the
129
    # environment (which is a good first approximation)
130
    old_env = os.environ.copy()
131
    for k in os.environ.keys():
132
        del os.environ[k]
133
    for (k,v) in req.get_cgi_environ().items():
134
        os.environ[k] = v
135
    fixup_environ(req)
136
137
    # usage: tramp uid jail_dir working_dir script_path
138
    pid = subprocess.Popen(
139
        [trampoline, str(uid), jail_dir, working_dir, interpreter,
140
        script_path],
141
        stdin=f, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
142
        cwd=tramp_dir)
143
144
    # Restore the environment
145
    for k in os.environ.keys():
146
        del os.environ[k]
147
    for (k,v) in old_env.items():
148
        os.environ[k] = v
149
150
    # process_cgi_line: Reads a single line of CGI output and processes it.
151
    # Prints to req, and also does fancy HTML warnings if Content-Type
152
    # omitted.
153
    cgiflags = CGIFlags()
154
155
    # Read from the process's stdout into req
156
    data = pid.stdout.read(CGI_BLOCK_SIZE)
157
    while len(data) > 0:
158
        process_cgi_output(req, data, cgiflags)
159
        data = pid.stdout.read(CGI_BLOCK_SIZE)
160
161
    # If we haven't processed headers yet, now is a good time
162
    if not cgiflags.started_cgi_body:
163
        process_cgi_output(req, '\n', cgiflags)
164
165
    # If we wrote an HTML warning header, write the footer
166
    if cgiflags.wrote_html_warning:
167
        req.write("""</pre>
168
  </div>
169
</body>
170
</html>""")
171
172
def process_cgi_output(req, data, cgiflags):
173
    """Processes a chunk of CGI output. data is a string of arbitrary length;
174
    some arbitrary chunk of output written by the CGI script."""
175
    if cgiflags.started_cgi_body:
176
        if cgiflags.wrote_html_warning:
177
            # HTML escape text if wrote_html_warning
178
            req.write(cgi.escape(data))
179
        else:
180
            req.write(data)
181
    else:
182
        # Break data into lines of CGI header data. 
183
        linebuf = cgiflags.linebuf + data
184
        # First see if we can split all header data
185
        split = linebuf.split('\r\n\r\n', 1)
186
        if len(split) == 1:
187
            # Allow UNIX newlines instead
188
            split = linebuf.split('\n\n', 1)
189
        if len(split) == 1:
190
            # Haven't seen all headers yet. Buffer and come back later.
191
            cgiflags.linebuf = linebuf
192
            return
193
194
        headers = split[0]
195
        data = split[1]
196
        cgiflags.linebuf = ""
197
        cgiflags.started_cgi_body = True
198
        # Process all the header lines
199
        split = headers.split('\r\n', 1)
200
        if len(split) == 1:
201
            split = headers.split('\n', 1)
202
        while True:
203
            process_cgi_header_line(req, split[0], cgiflags)
204
            if len(split) == 1: break
205
            headers = split[1]
206
            if cgiflags.wrote_html_warning:
207
                # We're done with headers. Treat the rest as data.
208
                data = headers + '\n' + data
209
                break
210
            split = headers.split('\r\n', 1)
211
            if len(split) == 1:
212
                split = headers.split('\n', 1)
213
214
        # Check to make sure the required headers were written
215
        if cgiflags.wrote_html_warning:
216
            # We already reported an error, that's enough
217
            pass
218
        elif "Content-Type" in cgiflags.headers:
219
            pass
220
        elif "Location" in cgiflags.headers:
221
            if ("Status" in cgiflags.headers and req.status >= 300
222
                and req.status < 400):
223
                pass
224
            else:
225
                message = """You did not write a valid status code for
226
the given location. To make a redirect, you may wish to try:</p>
227
<pre style="margin-left: 1em">Status: 302 Found
228
Location: &lt;redirect address&gt;</pre>"""
229
                write_html_warning(req, message)
230
                cgiflags.wrote_html_warning = True
231
        else:
232
            message = """You did not print a Content-Type header.
233
CGI requires that you print a "Content-Type". You may wish to try:</p>
234
<pre style="margin-left: 1em">Content-Type: text/html</pre>"""
235
            write_html_warning(req, message)
236
            cgiflags.wrote_html_warning = True
237
238
        # Call myself to flush out the extra bit of data we read
239
        process_cgi_output(req, data, cgiflags)
240
241
def process_cgi_header_line(req, line, cgiflags):
242
    """Process a line of CGI header data. line is a string representing a
243
    complete line of text, stripped and without the newline.
244
    """
245
    try:
246
        name, value = line.split(':', 1)
247
    except ValueError:
248
        # No colon. The user did not write valid headers.
249
        if len(cgiflags.headers) == 0:
250
            # First line was not a header line. We can assume this is not
251
            # a CGI app.
252
            message = """You did not print a CGI header.
253
CGI requires that you print a "Content-Type". You may wish to try:</p>
254
<pre style="margin-left: 1em">Content-Type: text/html</pre>"""
255
        else:
256
            # They printed some header at least, but there was an invalid
257
            # header.
258
            message = """You printed an invalid CGI header. You need to leave
259
a blank line after the headers, before writing the page contents."""
260
        write_html_warning(req, message)
261
        cgiflags.wrote_html_warning = True
262
        # Handle the rest of this line as normal data
263
        process_cgi_output(req, line + '\n', cgiflags)
264
        return
265
266
    # Read CGI headers
267
    value = value.strip()
268
    if name == "Content-Type":
269
        req.content_type = value
270
    elif name == "Location":
271
        req.location = value
272
    elif name == "Status":
273
        # Must be an integer, followed by a space, and then the status line
274
        # which we ignore (seems like Apache has no way to send a custom
275
        # status line).
276
        try:
277
            req.status = int(value.split(' ', 1)[0])
278
        except ValueError:
279
            message = """The "Status" CGI header was invalid. You need to
280
print a number followed by a message, such as "302 Found"."""
281
            write_html_warning(req, message)
282
            cgiflags.wrote_html_warning = True
283
            # Handle the rest of this line as normal data
284
            process_cgi_output(req, line + '\n', cgiflags)
285
    else:
286
        # Generic HTTP header
287
        # FIXME: Security risk letting users write arbitrary headers?
288
        req.headers_out[name] = value
289
    cgiflags.headers[name] = value
290
291
def write_html_warning(req, text):
292
    """Prints an HTML warning about invalid CGI interaction on the part of the
293
    user. text may contain HTML markup."""
294
    req.content_type = "text/html"
295
    req.write("""<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
296
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
297
<html xmlns="http://www.w3.org/1999/xhtml">
298
<head>
299
  <meta http-equiv="Content-Type"
300
    content="text/html; charset=utf-8" />
301
</head>
302
<body style="margin: 0; padding: 0; font-family: sans-serif;">
303
  <div style="background-color: #faa; border-bottom: 1px solid black;
304
    padding: 8px;">
305
    <p><strong>Warning</strong>: %s
306
  </div>
307
  <div style="margin: 8px;">
308
    <pre>
309
""" % text)
310
311
location_cgi_python = os.path.join(conf.ivle_install_dir,
312
    "bin/trampoline")
313
314
# Mapping of interpreter names (as given in conf/app/server.py) to
315
# interpreter functions.
316
317
interpreter_objects = {
318
    'cgi-python'
319
        : functools.partial(execute_cgi, "/usr/bin/python",
320
            location_cgi_python),
321
    # Should also have:
322
    # cgi-generic
323
    # python-server-page
324
}
325
326
def fixup_environ(req):
327
    """Assuming os.environ has been written with the CGI variables from
328
    apache, make a few changes for security and correctness.
329
330
    Does not modify req, only reads it.
331
    """
332
    env = os.environ
333
    # Comments here are on the heavy side, explained carefully for security
334
    # reasons. Please read carefully before making changes.
335
336
    # Remove HTTP_COOKIE. It is a security risk to have students see the IVLE
337
    # cookie of their visitors.
338
    try:
339
        del env['HTTP_COOKIE']
340
    except: pass
341
342
    # Remove DOCUMENT_ROOT and SCRIPT_FILENAME. Not part of CGI spec and
343
    # exposes unnecessary details about server.
344
    try:
345
        del env['DOCUMENT_ROOT']
346
    except: pass
347
    try:
348
        del env['SCRIPT_FILENAME']
349
    except: pass
350
351
    # Remove PATH. The PATH here is the path on the server machine; not useful
352
    # inside the jail. It may be a good idea to add another path, reflecting
353
    # the inside of the jail, but not done at this stage.
354
    try:
355
        del env['PATH']
356
    except: pass
357
358
    # Remove SCRIPT_FILENAME. Not part of CGI spec (see SCRIPT_NAME).
359
360
    # PATH_INFO is wrong because the script doesn't physically exist.
361
    # Apache makes it relative to the "serve" app. It should actually be made
362
    # relative to the student's script.
363
    # TODO: At this stage, it is not possible to add a path after the script,
364
    # so PATH_INFO is always "".
365
    path_info = ""
366
    env['PATH_INFO'] = path_info
367
368
    # PATH_TRANSLATED currently points to a non-existant location within the
369
    # local web server directory. Instead make it represent a path within the
370
    # student jail.
371
    (username, _, path_translated) = studpath.url_to_jailpaths(req.path)
372
    if len(path_translated) == 0 or path_translated[0] != os.sep:
373
        path_translated = os.sep + path_translated
374
    env['PATH_TRANSLATED'] = path_translated
375
376
    # CGI specifies that REMOTE_HOST SHOULD be set, and MAY just be set to
377
    # REMOTE_ADDR. Since Apache does not appear to set this, set it to
378
    # REMOTE_ADDR.
379
    if 'REMOTE_HOST' not in env and 'REMOTE_ADDR' in env:
380
        env['REMOTE_HOST'] = env['REMOTE_ADDR']
381
382
    # SCRIPT_NAME is the path to the script WITHOUT PATH_INFO.
383
    script_name = req.uri
384
    if len(path_info) > 0:
385
        script_name = script_name[:-len(path_info)]
386
    env['SCRIPT_NAME'] = script_name
387
388
    # SERVER_SOFTWARE is actually not Apache but IVLE, since we are
389
    # custom-making the CGI request.
390
    env['SERVER_SOFTWARE'] = "IVLE/" + str(conf.ivle_version)
391
392
    # Additional environment variables
393
    env['HOME'] = os.path.join('/home', username)