This file is indexed.

/usr/share/pyshared/schooltool/app/security.py is in python-schooltool 1:2.1.0-0ubuntu1.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
#
# SchoolTool - common information systems platform for school administration
# Copyright (c) 2005 Shuttleworth Foundation
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
"""
SchoolTool security infrastructure
"""

import urllib

from persistent import Persistent
from zope.component import getUtility, queryUtility
from zope.component import getNextUtility
from zope.container.contained import Contained
from zope.location.interfaces import ILocation
from zope.authentication.interfaces import IAuthentication, ILoginPassword
from zope.authentication.interfaces import IAuthenticatedGroup, IEveryoneGroup
from zope.session.interfaces import ISession
from zope.interface import implements
from schooltool.group.interfaces import IGroupContainer
from zope.security.interfaces import IGroupAwarePrincipal
from zope.security.checker import ProxyFactory
from zope.publisher.browser import FileUpload
from zope.publisher.interfaces.browser import IBrowserRequest
from zope.component.interfaces import ISite
from zope.site import LocalSiteManager
from zope.traversing.browser.absoluteurl import absoluteURL
from zope.traversing.api import traverse

from schooltool.app.interfaces import ISchoolToolApplication
from schooltool.app.interfaces import ISchoolToolAuthentication
from schooltool.app.interfaces import IAsset
from schooltool.person.interfaces import IPerson
from schooltool.app.interfaces import ISchoolToolAuthenticationPlugin
from schooltool.app.interfaces import ICalendarParentCrowd
from schooltool.securitypolicy.interfaces import ICrowdDescription
from schooltool.securitypolicy.crowds import Crowd, Description
from schooltool.securitypolicy.crowds import ManagerGroupCrowd
# XXX: move ConfigurableCrowd here
from schooltool.securitypolicy.crowds import ConfigurableCrowd, ParentCrowd

from schooltool.common import SchoolToolMessage as _


class Principal(Contained):
    implements(IGroupAwarePrincipal)

    def __init__(self, id, title, person=None):
        self.id = id
        self.title = title
        self.description = ""
        self.groups = []
        self._person = person

    def __conform__(self, interface):
        if interface is IPerson:
            return self._person


class PersonContainerAuthenticationPlugin(object):
    implements(ISchoolToolAuthenticationPlugin)

    person_prefix = "sb.person."
    group_prefix = "sb.group."
    session_name = "schooltool.auth"

    def authenticate(self, request):
        """Identify a principal for request.

        Retrieves the username and password from the session.
        """
        session = ISession(request)[self.session_name]
        if 'username' in session and 'password' in session:
            if self._checkHashedPassword(session['username'], session['password']):
                self.restorePOSTData(request)
                return self.getPrincipal('sb.person.' + session['username'])

        # Try HTTP basic too
        creds = ILoginPassword(request, None)
        if creds:
            login = creds.getLogin()
            if self._checkPlainTextPassword(login, creds.getPassword()):
                return self.getPrincipal('sb.person.' + login)

    def _checkPlainTextPassword(self, username, password):
        app = ISchoolToolApplication(None)
        if username in app['persons']:
            person = app['persons'][username]
            return person.checkPassword(password)

    def _checkHashedPassword(self, username, password):
        app = ISchoolToolApplication(None)
        if username in app['persons']:
            person = app['persons'][username]
            return (person._hashed_password is not None
                    and password == person._hashed_password)

    def unauthenticatedPrincipal(self):
        """Return the unauthenticated principal, if one is defined."""
        return None

    def storePOSTData(self, request):
        session = ISession(request)[self.session_name]
        method = request.get('REQUEST_METHOD')
        if method == 'POST':
            i = 0
            while 'form%s' % i in session:
                i += 1
            form_id = 'form%s' % i
            picklable_form = request.form.copy()
            for k, v in request.form.items():
                if isinstance(v, FileUpload):
                    del picklable_form[k]
            session[form_id] = picklable_form
            return form_id

    def restorePOSTData(self, request):
        form = getattr(request, "form", None)
        if form:
            form_id = request.form.get('post_form')
            if form_id:
                session = ISession(request)[self.session_name]
                form = session.get(form_id, None)
                if form is not None:
                    request.form = form
                    del session[form_id]

    def unauthorized(self, id, request):
        """Signal an authorization failure."""
        app = ISchoolToolApplication(None)
        app_url = absoluteURL(app, request)
        query_string = request.getHeader('QUERY_STRING')
        post_form_id = self.storePOSTData(request)

        if query_string:
            query_string = "?%s" % query_string
            if post_form_id:
                query_string += "&post_form=%s" % post_form_id
        else:
            query_string = ""
            if post_form_id:
                query_string += "?post_form=%s" % post_form_id

        full_url = "%s%s" % (str(request.URL), query_string)
        request.response.redirect("%s/auth/@@login.html?forbidden=yes&nexturl=%s"
                                  % (app_url, urllib.quote(full_url)))

    def getPrincipal(self, id):
        """Get principal meta-data.

        Returns principals for groups and persons.
        """
        app = ISchoolToolApplication(None)
        if id.startswith(self.person_prefix):
            username = id[len(self.person_prefix):]
            if username in app['persons']:
                person = app['persons'][username]
                principal = Principal(id, person.title,
                                      person=ProxyFactory(person))
                for group in person.groups:
                    group_principal_id = self.group_prefix + group.__name__
                    principal.groups.append(group_principal_id)
                authenticated = queryUtility(IAuthenticatedGroup)
                if authenticated:
                    principal.groups.append(authenticated.id)
                everyone = queryUtility(IEveryoneGroup)
                if everyone:
                    principal.groups.append(everyone.id)
                return principal
        return None

    def setCredentials(self, request, username, password):
        # avoid circular imports
        from schooltool.person.person import hash_password
        if not self._checkPlainTextPassword(username, password):
            raise ValueError('bad credentials')
        session = ISession(request)[self.session_name]
        session['username'] = username
        session['password'] = hash_password(password)

    def clearCredentials(self, request):
        session = ISession(request)[self.session_name]
        try:
            del session['password']
            del session['username']
        except KeyError:
            pass


class SchoolToolAuthenticationUtility(Persistent, Contained):
    """A local SchoolTool authentication utility.

    This utility serves principals for groups and persons in the
    nearest SchoolToolApplication instance.

    It authenticates the requests containing usernames and passwords
    in the session.
    """

    implements(ISchoolToolAuthentication, ILocation)

    @property
    def authPlugin(self):
        return getUtility(ISchoolToolAuthenticationPlugin)

    def authenticate(self, request):
        return self.authPlugin.authenticate(request)

    def unauthorized(self, id, request):
        if not IBrowserRequest.providedBy(request) or request.method == 'PUT':
            next = getNextUtility(self, IAuthentication)
            return next.unauthorized(id, request)
        if str(request.URL).endswith('.ics'):
            # Special case: testing shows that Mozilla Calendar does not send
            # the Authorization header unless challenged.  It is pointless
            # to redirect an iCalendar client to an HTML login form.
            next = getNextUtility(self, IAuthentication)
            return next.unauthorized(id, request)
        return self.authPlugin.unauthorized(id, request)

    def unauthenticatedPrincipal(self):
        """Return the unauthenticated principal, if one is defined."""
        return self.authPlugin.unauthenticatedPrincipal()

    def getPrincipal(self, id):
        """Get principal meta-data.

        Returns principals for groups and persons.
        """
        principal = self.authPlugin.getPrincipal(id)
        if not principal:
            next = getNextUtility(self, IAuthentication)
            principal = next.getPrincipal(id)

        return principal

    def setCredentials(self, request, username, password):
        self.authPlugin.setCredentials(request, username, password)

    def clearCredentials(self, request):
        self.authPlugin.clearCredentials(request)

    # See ILogout
    logout = clearCredentials


def setUpLocalAuth(site, auth=None):
    """Set up local authentication for SchoolTool.

    Creates a site management folder in a site and sets up local
    authentication.
    """

    if auth is None:
        auth = SchoolToolAuthenticationUtility()

    if not ISite.providedBy(site):
        site.setSiteManager(LocalSiteManager(site))

    # go to the site management folder
    default = traverse(site, '++etc++site/default')
    # if we already have the auth utility registered, we're done
    if 'SchoolToolAuth' in default:
        return
    # otherwise add it and register it
    default['SchoolToolAuth'] = auth
    manager = site.getSiteManager()
    manager.registerUtility(auth, IAuthentication)


def authSetUpSubscriber(app, event):
    """Set up local authentication for newly added SchoolTool apps.

    This is a handler for IObjectAddedEvent.
    """
    setUpLocalAuth(app)


CalendarViewersCrowd = ParentCrowd(
    ICalendarParentCrowd, 'schooltool.view')


CalendarEditorsCrowd = ParentCrowd(
    ICalendarParentCrowd, 'schooltool.edit')


class LeaderCrowd(Crowd):
    """A crowd that contains leaders of an object."""

    title = _(u'Leaders')
    description = _(u'Assigned leaders.')

    def contains(self, principal):
        assert IAsset.providedBy(self.context)
        person = IPerson(principal, None)
        return person in self.context.leaders


class GroupCrowdDescription(Description):
    implements(ICrowdDescription)

    group = None

    def __init__(self, crowd, action, group):
        self.crowd, self.action, self.group = crowd, action, group

    @property
    def user_group(self):
        if self.crowd.group is None:
            return None
        return self.getGroup(self.crowd.group)

    def getGroup(self, group_principal_id):
        prefix = PersonContainerAuthenticationPlugin.group_prefix
        if not group_principal_id.startswith(prefix):
            return None
        groups = IGroupContainer(ISchoolToolApplication(None), None)
        if groups is None:
            return None
        group_id = group_principal_id[len(prefix):]
        return groups.get(group_id, None)

    @property
    def title(self):
        group = self.user_group
        if group is None:
            return ''
        return group.title

    @property
    def description(self):
        group = self.user_group
        if group is None:
            return ''
        return _(u'"$group" group.',
                 mapping={'group': group.title})


class ManagersCrowdDescription(GroupCrowdDescription):

    @property
    def user_group(self):
        return self.getGroup(ManagerGroupCrowd.group)

    @property
    def description(self):
        group = self.user_group
        if group is None:
            return ''
        return _(u'"$group" group and the super user.',
                 mapping={'group': group.title})