summaryrefslogtreecommitdiffstats
path: root/pykolab/auth/ldap/__init__.py
blob: 5ec2d82f49087282ced446e0550e057c2cd9ee4d (plain)
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
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
# Copyright 2010-2011 Kolab Systems AG (http://www.kolabsys.com)
#
# Jeroen van Meeuwen (Kolab Systems) <vanmeeuwen a kolabsys.com>
#
# 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; version 3 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 Library 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.
#

import _ldap
import ldap
import ldap.async
import ldap.controls
import ldap.resiter
import logging
import time

from pykolab import utils
from pykolab.conf import Conf
from pykolab.constants import *
from pykolab.translate import _

class LDAP(object):
    """
        Abstraction layer for the LDAP authentication / authorization backend,
        for use with Kolab.
    """

    def __init__(self, conf):
        self.conf = conf
        self.log = logging.getLogger('pykolab.ldap')
        self.ldap = None
        self.bind = False

    def _authenticate(self, login, domain):
        print "Authenticating:", login, domain
        self._connect()
        user_dn = self._find_dn(login[0], domain)
        try:
            print "Binding with user_dn %s and password %s" %(user_dn, login[1])
            # Needs to be synchronous or succeeds and continues setting retval to True!!
            self.ldap.simple_bind_s(user_dn, login[1])
            retval = True
        except:
            retval = False
        return retval

    def _connect(self, domain=None):
        if not self.ldap == None:
            return

        if domain == None:
            section = 'ldap'
        elif not self.conf.has_option(domain, uri):
            section = 'ldap'

        self.log.debug(_("Connecting to LDAP..."))

        uri = self.conf.get(section, 'uri')

        self.log.debug(_("Attempting to use LDAP URI %s") %(uri))
        self.ldap = ldap.initialize(uri, trace_level=0)
        self.ldap.protocol_version = 3

    def _bind(self):
        # TODO: Implement some mechanism for r/o, r/w and mgmt binding.
        self._connect()

        if not self.bind:
            # TODO: Use bind credentials for the domain itself.
            bind_dn = self.conf.get('ldap', 'bind_dn')
            bind_pw = self.conf.get('ldap', 'bind_pw')
            # TODO: Binding errors control
            try:
                self.ldap.simple_bind_s(bind_dn, bind_pw)
            except ldap.SERVER_DOWN:
                # Can't contact LDAP server
                #
                # - Service not started
                # - Service faulty
                # - Firewall
                pass

            self.bind = True

    def _unbind(self):
        self.ldap.unbind()
        self.bind = False

    def _reconnect(self):
        self._disconnect()
        self._connect()

    def _disconnect(self):
        self._unbind()
        del self.ldap
        self.ldap = None
        self.bind = False

    def _find_dn(self, login, domain=None):
        self._connect()
        self._bind()

        if domain == None:
            domain = self.conf.get('kolab', 'primary_domain')

        domain_root_dn = self._kolab_domain_root_dn(domain)

        if self.conf.has_option(domain_root_dn, 'user_base_dn'):
            section = domain_root_dn
        else:
            section = 'ldap'

        user_base_dn = self.conf.get_raw(section, 'user_base_dn') %({'base_dn': domain_root_dn})

        print "user_base_dn:", user_base_dn

        if self.conf.has_option(domain_root_dn, 'kolab_user_filter'):
            section = domain_root_dn
        else:
            section = 'ldap'

        kolab_user_filter = self.conf.get(section, 'kolab_user_filter', quiet=True)

        if kolab_user_filter == "":
            kolab_user_filter = self.conf.get('ldap', 'kolab_user_filter')

        search_filter = "(&(%s=%s)%s)" %(self.conf.get('cyrus-sasl', 'result_attribute'),login,kolab_user_filter)

        print search_filter

        _results = self._search(user_base_dn, filterstr=search_filter, attrlist=['dn'])

        if len(_results) == 1:
            (_user_dn, _user_attrs) = _results[0]
        else:
            # Retry to find the user_dn with just uid=%s against the root_dn, if the login is not fully qualified
            if len(login.split('@')) < 2:
                search_filter = "(uid=%s)" %(login)
                _results = self._search(domain_root_dn, filterstr=search_filter, attrlist=['dn'])
                if len(_results) == 1:
                    (_user_dn, _user_attrs) = _results[0]
                else:
                    # Overall fail
                    return False
            else:
                return False

        return _user_dn

    def _search(self, base_dn, scope=ldap.SCOPE_SUBTREE, filterstr="(objectClass=*)", attrlist=None, attrsonly=0, timeout=-1):
        _results = []

        page_size = 500
        critical = True

        server_page_control = ldap.controls.SimplePagedResultsControl(
                        ldap.LDAP_CONTROL_PAGE_OID,
                        critical,
                        (page_size, '')
                    )

        _search = self.ldap.search_ext(
                base_dn,
                scope=scope,
                filterstr=filterstr,
                attrlist=attrlist,
                attrsonly=attrsonly,
                serverctrls=[server_page_control]
            )

        pages = 0
        while True:
            pages += 1
            #print "Getting page %d..." %(pages)
            (_result_type, _result_data, _result_msgid, _result_controls) = self.ldap.result3(_search)
            _results.extend(_result_data)
            if (pages % 2) == 0:
                self.log.debug(_("%d results...") %(len(_results)))

            pctrls = [c for c in _result_controls if c.controlType == ldap.LDAP_CONTROL_PAGE_OID]

            if pctrls:
                est, cookie = pctrls[0].controlValue
                if cookie:
                    server_page_control.controlValue = (page_size, cookie)
                    _search = self.ldap.search_ext(
                            base_dn,
                            scope=scope,
                            filterstr=filterstr,
                            attrlist=attrlist,
                            attrsonly=attrsonly,
                            serverctrls=[server_page_control]
                        )
                else:
                    # TODO: Error out more verbose
                    break
            else:
                # TODO: Error out more verbose
                print "Warning:  Server ignores RFC 2696 control."
                break

        return _results

    def _result(self, msgid=ldap.RES_ANY, all=1, timeout=-1):
        return self.ldap.result(msgid, all, timeout)

    def _domain_default_quota(self, domain):
        domain_root_dn = self._kolab_domain_root_dn(domain)

        if self.conf.has_option(domain_root_dn, 'default_quota'):
            return self.conf.get(domain_root_dn, 'default_quota', quiet=True)
        elif self.conf.has_option('ldap', 'default_quota'):
            return self.conf.get('ldap', 'default_quota', quiet=True)
        elif self.conf.has_option('kolab', 'default_quota'):
            return self.conf.get('kolab', 'default_quota', quiet=True)

    def _domain_section(self, domain):
        domain_root_dn = self._kolab_domain_root_dn(domain)

        if self.conf.has_section(domain_root_dn):
            return domain_root_dn
        else:
            return 'ldap'

    def _get_user_attribute(self, user, attribute):
        self._bind()

        (user_dn, user_attrs) = self._search(user['dn'], ldap.SCOPE_BASE, '(objectclass=*)', [ attribute ])[0]

        user_attrs = utils.normalize(user_attrs)
        if not user_attrs.has_key(attribute):
            user_attrs[attribute] = None

        return user_attrs[attribute]


    def _set_user_attribute(self, user, attribute, value):
        self._bind()

        #print "user:", user

        attribute = attribute.lower()

        # TODO: This should be a schema check!
        if attribute in [ 'mailquota', 'mailalternateaddress' ]:
            if not user.has_key('objectclass'):
                user['objectclass'] = self._get_user_attribute(user,'objectclass')
            if not 'mailrecipient' in user['objectclass']:
                user['objectclass'].append('mailrecipient')
                self._set_user_attribute(user, 'objectclass', user['objectclass'])

        try:
            self.ldap.modify(user['dn'], [(ldap.MOD_REPLACE, attribute, value)])
        except:
            self.log.warning(_("LDAP modification of attribute %s" + \
                " for %s to value %s failed") %(attribute,user_dn,value))

    def _list_domains(self):
        """
            Find the domains related to this Kolab setup, and return a list of
            DNS domain names.

            Returns a list of tuples, each tuple containing the primary domain
            name and a list of secondary domain names.
        """

        self.log.info(_("Listing domains..."))

        self._connect()

        bind_dn = self.conf.get('ldap', 'bind_dn')
        bind_pw = self.conf.get('ldap', 'bind_pw')

        domain_base_dn = self.conf.get('ldap', 'domain_base_dn', quiet=True)

        if domain_base_dn == "":
            # No domains are to be found in LDAP, return an empty list.
            # Note that the Auth() base itself handles this case.
            return []

        # If we haven't returned already, let's continue searching
        kolab_domain_filter = self.conf.get('ldap', 'kolab_domain_filter')

        # TODO: this function should be wrapped for error handling
        self.ldap.simple_bind(bind_dn, bind_pw)

        _search = self.ldap.search(
                domain_base_dn,
                ldap.SCOPE_SUBTREE,
                kolab_domain_filter,
                # TODO: Where we use associateddomain is actually configurable
                [ 'associateddomain' ]
            )

        domains = []
        _result_type = None

        while not _result_type == ldap.RES_SEARCH_RESULT:
            try:
                (_result_type, _domains) = self._result(_search, False, 0)
            except AttributeError, e:
                if self.ldap == None:
                    self._bind()
                continue
            if not _domains == None:
                for _domain in _domains:
                    (domain_dn, _domain_attrs) = _domain
                    primary_domain = None
                    secondary_domains = []

                    _domain_attrs = utils.normalize(_domain_attrs)

                    # TODO: Where we use associateddomain is actually configurable
                    if type(_domain_attrs['associateddomain']) == list:
                        primary_domain = _domain_attrs['associateddomain'].pop(0)
                        secondary_domains = _domain_attrs['associateddomain']
                    else:
                        primary_domain = _domain_attrs['associateddomain']

                    domains.append((primary_domain,secondary_domains))

        return domains

    def _kolab_domain_root_dn(self, domain):
        self._bind()

        print "Finding domain root dn for domain %s" %(domain)

        bind_dn = self.conf.get('ldap', 'bind_dn')
        bind_pw = self.conf.get('ldap', 'bind_pw')

        domain_base_dn = self.conf.get('ldap', 'domain_base_dn', quiet=True)

        print "domain_base_dn:", domain_base_dn

        if not domain_base_dn == "":
            print "domain_base_dn is not \"\""

            # If we haven't returned already, let's continue searching
            domain_name_attribute = self.conf.get('ldap', 'domain_name_attribute')

            _results = self._search(
                    domain_base_dn,
                    ldap.SCOPE_SUBTREE,
                    "(%s=%s)" %(domain_name_attribute,domain)
                )

            domains = []
            for _domain in _results:
                (domain_dn, _domain_attrs) = _domain
                domain_rootdn_attribute = self.conf.get('ldap', 'domain_rootdn_attribute')
                _domain_attrs = utils.normalize(_domain_attrs)
                if _domain_attrs.has_key(domain_rootdn_attribute):
                    return _domain_attrs[domain_rootdn_attribute]

        print "domain_base_dn is \"\""
        return utils.standard_root_dn(domain)

    def _list_users(self, primary_domain, secondary_domains=[]):

        self.log.info(_("Listing users for domain %s (and %s)") %(primary_domain, ' '.join(secondary_domains)))

        self._bind()

        # TODO: Bind with read-only credentials, perhaps even domain-specific, please
        bind_dn = self.conf.get('ldap', 'bind_dn')
        #bind_dn = self.conf.get('ldap', 'ro_bind_dn')
        bind_pw = self.conf.get('ldap', 'bind_pw')
        #bind_pw = self.conf.get('ldap', 'ro_bind_pw')

        domain_root_dn = self._kolab_domain_root_dn(primary_domain)

        if self.conf.has_option(domain_root_dn, 'user_base_dn'):
            section = domain_root_dn
        else:
            section = 'ldap'

        user_base_dn = self.conf.get_raw(section, 'user_base_dn') %({'base_dn': domain_root_dn})

        if self.conf.has_option(domain_root_dn, 'kolab_user_filter'):
            section = domain_root_dn
        else:
            section = 'ldap'

        kolab_user_filter = self.conf.get(section, 'kolab_user_filter', quiet=True)

        if kolab_user_filter == "":
            kolab_user_filter = self.conf.get('ldap', 'kolab_user_filter')

        self.ldap.simple_bind(bind_dn, bind_pw)

        # TODO: The quota and alternative address attributes are actually
        # supposed to be settings.
        _search = self._search(
                user_base_dn,
                ldap.SCOPE_SUBTREE,
                kolab_user_filter,
                attrlist=[ 'dn', 'mail', 'mailquota', 'mailalternateaddress', 'sn', 'givenname', 'cn', 'uid' ],
                attrsonly=0
            )

        self.log.debug(_("Iterating over %d users, making sure we have the necessary attributes...") %(len(_search)))

        #print "SEARCH RESULTS:", _search

        users = []
        _result_type = None

        for user_dn, user_attrs in _search:
            user = {}
            user['dn'] = user_dn
            if not user.has_key('standard_domain'):
                user['standard_domain'] = (primary_domain, secondary_domains)

            user_attrs = utils.normalize(user_attrs)

            #print "USER_ATTRS:", user_attrs

            for attribute in [ 'mail', 'mailalternateaddress', 'sn', 'givenname', 'cn', 'uid' ]:
                if not user_attrs.has_key(attribute):
                    #print "doesn't have attribute"
                    user[attribute] = self._get_user_attribute(user, attribute)
                else:
                    #print "has attribute"
                    user[attribute] = user_attrs[attribute]

            #print "============== EXECING PLUGINS ================="

            if self.conf.has_option(domain_root_dn, 'primary_mail'):
                primary_mail = self.conf.plugins.exec_hook("set_primary_mail",
                        kw={'primary_mail': self.conf.get_raw(domain_root_dn, 'primary_mail')},
                        args=(user_attrs, primary_domain, secondary_domains)
                    )

                if not primary_mail == None and (not user.has_key('mail') or not primary_mail == user['mail']):
                    self._set_user_attribute(user, 'mail', primary_mail)
                    user['mail'] = primary_mail

                if self.conf.has_option(domain_root_dn, 'secondary_mail'):
                    secondary_mail = self.conf.plugins.exec_hook("set_secondary_mail",
                            kw={'secondary_mail': self.conf.get_raw(domain_root_dn, 'secondary_mail')},
                            args=(user_attrs, primary_domain, secondary_domains)
                        )
                    #print "secondary mail:", secondary_mail, len(secondary_mail)

                    if not secondary_mail == None:
                        secondary_mail = list(set(secondary_mail))
                        if not secondary_mail == user['mailalternateaddress']:
                            self._set_user_attribute(user, 'mailalternateaddress', secondary_mail)
                            user['mailalternateaddress'] = secondary_mail

            users.append(user)

        #print "USERS:", users

        return users

#class SyncControl(ldap.controls.LDAPControl):
    #controlType = '(1.3.6.1.4.1.4203.1.9.1.1'
    #def __init__(self, controlType, criticality, controlValue=None, encodedControlValue=None):
        #LDAPControl.__init__(self, controlType, criticality, controlValue, encodedControlValue)

    #def encodeControlValue(self, value):