-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathsynapse_ldap_password_provider.py
544 lines (482 loc) · 19.8 KB
/
synapse_ldap_password_provider.py
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
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
# -*- coding: utf-8 -*-
# Copyright 2018 Pavel Kardash <[email protected]>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import unicode_literals
from synapse.types import UserID
from twisted.internet import defer, threads
from synapse.api.constants import LoginType
import logging
import time
__version__ = '3'
logger = logging.getLogger('ldap')
try:
import ldap3
import ldap3.core.exceptions
try:
LDAP_AUTH_SIMPLE = ldap3.AUTH_SIMPLE
except AttributeError:
LDAP_AUTH_SIMPLE = ldap3.SIMPLE
try:
ldap3.set_config_parameter('DEFAULT_ENCODING', 'UTF-8')
ldap3.set_config_parameter('ADDITIONAL_ENCODINGS', ['cp1251', 'koi8-r', 'latin1'])
except AttributeError:
pass
except ldap3.core.exceptions.LDAPConfigurationParameterError:
pass
except ImportError:
ldap3 = None
pass
class LDAPPasswordProvider(object):
__version__ = '3'
def __init__(self, config, account_handler):
self.account_handler = account_handler
if not ldap3:
raise RuntimeError(
'Missing ldap3 library. '
'This is required for LDAP Authentication.'
)
self.ldap_mode = config.mode
self.ldap_uri = config.uri
self.ldap_start_tls = config.start_tls
self.ldap_base = config.base
self.ldap_attributes = config.attributes
if self.ldap_mode == 'search':
self.ldap_bind_dn = config.bind_dn
self.ldap_bind_password = config.bind_password
self.ldap_filter = config.filter
# If you do not want your internal users to be blocked from outside
# by scrambling passwords through this service, then you need
# implement a more rigid account lockout policy then in yor LDAP server
self.ldap_alp_exists = config.account_lockout_policy_exists
if self.ldap_alp_exists:
self.ldap_alp = config.account_lockout_policy
self.bad_login_attemps = {}
def get_supported_login_types(self):
""" Returns suported login types """
return {LoginType.PASSWORD: (u"password",)}
@defer.inlineCallbacks
def check_auth(self, username, login_type, login_dict):
""" check auth for supported login type """
if login_type not in self.get_supported_login_types().keys():
logger.error(
'Unsupported login type \"%s\" for user \"%s\" auth.' %
(login_type, username)
)
yield defer.returnValue(None)
auth = yield self.check_passwd(username, login_dict['password'])
if not username.startswith('@'):
username = UserID(
username,
self.account_handler.hs.hostname
).to_string()
if auth:
logger.info(
'SUCCES user \"%s\" auth with login_type \"%s\"' %
(username, login_type)
)
yield defer.returnValue((username, None))
logger.warn(
'FAILED user \"%s\" auth with login_type \"%s\"' %
(username, login_type)
)
yield defer.returnValue(None)
@defer.inlineCallbacks
def check_passwd(self, user_id, password):
""" Authenticate a user against an LDAP Server
and register an account if none exists.
Returns:
True if authentication against LDAP was successful
"""
if user_id.startswith("@"):
localpart = user_id.split(":", 1)[0][1:]
else:
localpart = user_id
user_id = UserID(localpart, self.account_handler.hs.hostname).to_string()
now = time.time()
if localpart in self.bad_login_attemps.keys():
if self.bad_login_attemps[localpart]['count'] >= self.ldap_alp['attemps']:
unlock_time = self.bad_login_attemps[localpart]['ts'] + \
self.ldap_alp['locktime_s']
if now <= unlock_time:
logger.error(
'User %s is locked by account lockout policy. '
'This login attemp will fail. '
'Seconds to unlock: %d' %
(user_id, unlock_time - now)
)
defer.returnValue(False)
try:
server = ldap3.Server(self.ldap_uri, get_info=None)
logger.debug(
'LDAP connection with %s',
self.ldap_uri
)
if self.ldap_mode == 'simple':
bind_dn = "{prop}={value},{base}".format(
prop=self.ldap_attributes['uid'],
value=localpart,
base=self.ldap_base
)
result, conn = yield self._ldap_simple_bind(
server=server, bind_dn=bind_dn, password=password
)
logger.debug(
'LDAP authentication method simple bind returned: '
'%s (conn: %s)',
result,
conn
)
if not result:
if self.ldap_alp_exists:
if localpart in self.bad_login_attemps.keys():
self.bad_login_attemps[localpart]['count'] += 1
self.bad_login_attemps[localpart]['ts'] = now
else:
self.bad_login_attemps[localpart] = {
'count': 1,
'ts': now
}
defer.returnValue(False)
elif self.ldap_mode == 'search':
result, conn = yield self._ldap_authenticated_search(
server=server, localpart=localpart, password=password
)
logger.debug(
'LDAP auth method authenticated search returned: '
'%s ',
result
)
if not result:
if self.ldap_alp_exists:
if localpart in self.bad_login_attemps.keys():
self.bad_login_attemps[localpart]['count'] += 1
self.bad_login_attemps[localpart]['ts'] = now
else:
self.bad_login_attemps[localpart] = {
'count': 1,
'ts': now
}
defer.returnValue(False)
else:
raise RuntimeError(
'Invalid LDAP mode specified: {%s}' %
self.ldap_mode
)
if not conn:
logger.error(
'Authentication method yielded no LDAP connection, '
'aborting!'
)
defer.returnValue(False)
query = '({prop}={value})'.format(
prop=self.ldap_attributes['uid'],
value=localpart
)
if self.ldap_mode == 'search' and self.ldap_filter:
query = '(&{filter}{user_filter})'.format(
filter=query,
user_filter=self.ldap_filter
)
logger.debug(
'LDAP search filter: %s',
query
)
yield threads.deferToThread(
conn.search,
search_base=self.ldap_base,
search_filter=query,
attributes=self.ldap_attributes.values()
)
responses = [
response
for response
in conn.response
if response['type'] == 'searchResEntry'
]
if len(responses) == 1:
attrs = responses[0]['attributes']
try:
name = attrs[self.ldap_attributes['name']][0]
except Exception:
name = None
store = self.account_handler.hs.get_profile_handler().store
users = yield store.get_users_by_id_case_insensitive(user_id)
if not users:
# Create account if not exists
logger.info(
'FIRST login for user %s' %
user_id
)
user_id, access_token = (
yield self.account_handler.register(localpart=localpart)
)
if name is not None:
# Update user Display Name
store.set_profile_displayname(localpart, name)
profile = yield store.get_profileinfo(localpart)
user_dir_handler = self.account_handler.hs.get_user_directory_handler()
yield user_dir_handler.handle_local_profile_change(
user_id, profile
)
if 'mail' in self.ldap_attributes:
for mail in attrs[self.ldap_attributes['mail']]:
# Update user email
validated_at = self.account_handler.hs.get_clock().time_msec()
user_id_by_threepid = yield store.get_user_id_by_threepid(
'email',
mail
)
# add email only if not exists
if not user_id_by_threepid:
store.user_add_threepid(
user_id,
'email',
mail,
validated_at,
validated_at
)
elif not user_id_by_threepid.lower() == user_id.lower():
logger.error(
'Auth user %s with %s email but user %s'
'already have same email' % (
user_id,
mail,
user_id_by_threepid
)
)
if 'msisdn' in self.ldap_attributes:
for msisdn in attrs[self.ldap_attributes['msisdn']]:
# Update user msisdn
validated_at = self.account_handler.hs.get_clock().time_msec()
user_id_by_threepid = yield store.get_user_id_by_threepid(
'msisdn',
msisdn
)
# add msisdn only if not exists
if not user_id_by_threepid:
store.user_add_threepid(
user_id,
'msisdn',
msisdn,
validated_at,
validated_at
)
elif not user_id_by_threepid.lower() == user_id.lower():
logger.error(
'Auth user %s with %s msisdn but user %s'
'already have same msisdn' % (
user_id,
msisdn,
user_id_by_threepid
)
)
logger.info(
'Auth based on LDAP data was successful: '
'%s: %s (%s)',
user_id, localpart, name
)
if localpart in self.bad_login_attemps:
del self.bad_login_attemps[localpart]
defer.returnValue(True)
else:
if len(responses) == 0:
logger.warning('LDAP auth failed, no result.')
else:
logger.warning(
'LDAP auth failed, too many results (%s)',
len(responses)
)
defer.returnValue(False)
defer.returnValue(False)
except ldap3.core.exceptions.LDAPException as e:
logger.warning('Error during ldap authentication: %s', e)
defer.returnValue(False)
@staticmethod
def parse_config(config):
class _LdapConfig(object):
pass
def _require_keys(config, required):
missing = [key for key in required if key not in config]
if missing:
raise Exception(
'LDAP enabled but missing required config values: %s' %
', '.join(missing)
)
ldap_config = _LdapConfig()
ldap_config.enabled = config.get('enabled', False)
ldap_config.mode = 'simple'
# verify config sanity
_require_keys(config, [
'uri',
'base',
'attributes',
])
ldap_config.uri = config['uri']
ldap_config.start_tls = config.get('start_tls', False)
ldap_config.base = config['base']
ldap_config.attributes = config['attributes']
if 'bind_dn' in config:
ldap_config.mode = 'search'
_require_keys(config, [
'bind_dn',
'bind_password',
])
ldap_config.bind_dn = config['bind_dn']
ldap_config.bind_password = config['bind_password']
ldap_config.filter = config.get('filter', None)
# verify attribute lookup
_require_keys(config['attributes'], [
'uid',
'name',
])
if 'account_lockout_policy' in config:
ldap_config.account_lockout_policy_exists = True
ldap_config.account_lockout_policy = config['account_lockout_policy']
_require_keys(config['account_lockout_policy'], [
'attemps',
'locktime_s',
])
else:
ldap_config.account_lockout_policy_exists = False
ldap_config.gprefix = config.get('group_prefix', '')
return ldap_config
@defer.inlineCallbacks
def _ldap_simple_bind(self, server, bind_dn, password):
""" Attempt a simple bind with the credentials
given by the user against the LDAP server.
Returns True, LDAP3Connection
if the bind was successful
Returns False, None
if an error occured
"""
try:
# bind with the the local users ldap credentials
conn = yield threads.deferToThread(
ldap3.Connection,
server, bind_dn, password,
authentication=LDAP_AUTH_SIMPLE,
read_only=True,
)
logger.debug(
'LDAP connection in simple bind mode.'
)
if self.ldap_start_tls:
yield threads.deferToThread(conn.open)
yield threads.deferToThread(conn.start_tls)
logger.debug(
'Upgraded LDAP connection in simple bind mode through '
'StartTLS'
)
if (yield threads.deferToThread(conn.bind)):
logger.debug('LDAP Bind successful in simple bind mode.')
defer.returnValue((True, conn))
logger.info(
'LDAP bind failed for %s failed: %s',
bind_dn, conn.result['description']
)
yield threads.deferToThread(conn.unbind)
defer.returnValue((False, None))
except ldap3.core.exceptions.LDAPException as e:
logger.warning('LDAP authentication error: %s', e)
defer.returnValue((False, None))
@defer.inlineCallbacks
def _ldap_authenticated_search(self, server, localpart, password):
""" Attempt to login with the preconfigured bind_dn
and then continue searching and filtering within
the base_dn
Returns (True, LDAP3Connection)
if a single matching DN within the base was found
that matched the filter expression, and with which
a successful bind was achieved
The LDAP3Connection returned is the instance that was used to
verify the password not the one using the configured bind_dn.
Returns (False, None)
if an error occured
"""
try:
conn = yield threads.deferToThread(
ldap3.Connection,
server,
self.ldap_bind_dn,
self.ldap_bind_password
)
logger.debug(
'LDAP connection in search mode: %s',
conn
)
if self.ldap_start_tls:
yield threads.deferToThread(conn.open)
yield threads.deferToThread(conn.start_tls)
logger.debug(
'Upgraded LDAP connection in search mode through '
'StartTLS: %s',
conn
)
if not (yield threads.deferToThread(conn.bind)):
logger.warning(
'LDAP bind with `bind_dn` failed: %s',
conn.result['description']
)
yield threads.deferToThread(conn.unbind)
defer.returnValue((False, None))
# construct search_filter like (uid=localpart)
query = '({prop}={value})'.format(
prop=self.ldap_attributes['uid'],
value=localpart
)
if self.ldap_filter:
# combine with the AND expression
query = '(&{query}{filter})'.format(
query=query,
filter=self.ldap_filter
)
logger.debug(
'LDAP search filter: %s',
query
)
yield threads.deferToThread(
conn.search,
search_base=self.ldap_base,
search_filter=query
)
responses = [
response
for response
in conn.response
if response['type'] == 'searchResEntry'
]
if len(responses) == 1:
user_dn = responses[0]['dn']
logger.debug('LDAP search found dn: %s', user_dn)
yield threads.deferToThread(conn.unbind)
result = yield self._ldap_simple_bind(
server=server, bind_dn=user_dn, password=password
)
defer.returnValue(result)
else:
if len(responses) == 0:
logger.info(
'LDAP search returned no results for %s',
localpart
)
else:
logger.info(
'LDAP search returned too many (%s) results for %s',
len(responses), localpart
)
yield threads.deferToThread(conn.unbind)
defer.returnValue((False, None))
except ldap3.core.exceptions.LDAPException as e:
logger.warning('LDAP authentication error: %s', e)
defer.returnValue((False, None))