##// END OF EJS Templates
ldap: use connection ping only in case of single server specifed.
marcink -
r2736:f1074c0b stable
parent child Browse files
Show More
@@ -1,726 +1,783 b''
1 1 # -*- coding: utf-8 -*-
2 2
3 3 # Copyright (C) 2010-2018 RhodeCode GmbH
4 4 #
5 5 # This program is free software: you can redistribute it and/or modify
6 6 # it under the terms of the GNU Affero General Public License, version 3
7 7 # (only), as published by the Free Software Foundation.
8 8 #
9 9 # This program is distributed in the hope that it will be useful,
10 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 12 # GNU General Public License for more details.
13 13 #
14 14 # You should have received a copy of the GNU Affero General Public License
15 15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 16 #
17 17 # This program is dual-licensed. If you wish to learn more about the
18 18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20 20
21 21 """
22 22 Authentication modules
23 23 """
24
24 import socket
25 import string
25 26 import colander
26 27 import copy
27 28 import logging
28 29 import time
29 30 import traceback
30 31 import warnings
31 32 import functools
32 33
33 34 from pyramid.threadlocal import get_current_registry
34 from zope.cachedescriptors.property import Lazy as LazyProperty
35 35
36 36 from rhodecode.authentication.interface import IAuthnPluginRegistry
37 37 from rhodecode.authentication.schema import AuthnPluginSettingsSchemaBase
38 38 from rhodecode.lib import caches
39 39 from rhodecode.lib.auth import PasswordGenerator, _RhodeCodeCryptoBCrypt
40 from rhodecode.lib.utils2 import safe_int
41 from rhodecode.lib.utils2 import safe_str
40 from rhodecode.lib.utils2 import safe_int, safe_str
41 from rhodecode.lib.exceptions import LdapConnectionError
42 42 from rhodecode.model.db import User
43 43 from rhodecode.model.meta import Session
44 44 from rhodecode.model.settings import SettingsModel
45 45 from rhodecode.model.user import UserModel
46 46 from rhodecode.model.user_group import UserGroupModel
47 47
48 48
49 49 log = logging.getLogger(__name__)
50 50
51 51 # auth types that authenticate() function can receive
52 52 VCS_TYPE = 'vcs'
53 53 HTTP_TYPE = 'http'
54 54
55 55
56 56 class hybrid_property(object):
57 57 """
58 58 a property decorator that works both for instance and class
59 59 """
60 60 def __init__(self, fget, fset=None, fdel=None, expr=None):
61 61 self.fget = fget
62 62 self.fset = fset
63 63 self.fdel = fdel
64 64 self.expr = expr or fget
65 65 functools.update_wrapper(self, fget)
66 66
67 67 def __get__(self, instance, owner):
68 68 if instance is None:
69 69 return self.expr(owner)
70 70 else:
71 71 return self.fget(instance)
72 72
73 73 def __set__(self, instance, value):
74 74 self.fset(instance, value)
75 75
76 76 def __delete__(self, instance):
77 77 self.fdel(instance)
78 78
79 79
80 80 class LazyFormencode(object):
81 81 def __init__(self, formencode_obj, *args, **kwargs):
82 82 self.formencode_obj = formencode_obj
83 83 self.args = args
84 84 self.kwargs = kwargs
85 85
86 86 def __call__(self, *args, **kwargs):
87 87 from inspect import isfunction
88 88 formencode_obj = self.formencode_obj
89 89 if isfunction(formencode_obj):
90 90 # case we wrap validators into functions
91 91 formencode_obj = self.formencode_obj(*args, **kwargs)
92 92 return formencode_obj(*self.args, **self.kwargs)
93 93
94 94
95 95 class RhodeCodeAuthPluginBase(object):
96 96 # cache the authentication request for N amount of seconds. Some kind
97 97 # of authentication methods are very heavy and it's very efficient to cache
98 98 # the result of a call. If it's set to None (default) cache is off
99 99 AUTH_CACHE_TTL = None
100 100 AUTH_CACHE = {}
101 101
102 102 auth_func_attrs = {
103 103 "username": "unique username",
104 104 "firstname": "first name",
105 105 "lastname": "last name",
106 106 "email": "email address",
107 107 "groups": '["list", "of", "groups"]',
108 108 "user_group_sync":
109 109 'True|False defines if returned user groups should be synced',
110 110 "extern_name": "name in external source of record",
111 111 "extern_type": "type of external source of record",
112 112 "admin": 'True|False defines if user should be RhodeCode super admin',
113 113 "active":
114 114 'True|False defines active state of user internally for RhodeCode',
115 115 "active_from_extern":
116 116 "True|False\None, active state from the external auth, "
117 117 "None means use definition from RhodeCode extern_type active value"
118 118
119 119 }
120 120 # set on authenticate() method and via set_auth_type func.
121 121 auth_type = None
122 122
123 123 # set on authenticate() method and via set_calling_scope_repo, this is a
124 124 # calling scope repository when doing authentication most likely on VCS
125 125 # operations
126 126 acl_repo_name = None
127 127
128 128 # List of setting names to store encrypted. Plugins may override this list
129 129 # to store settings encrypted.
130 130 _settings_encrypted = []
131 131
132 132 # Mapping of python to DB settings model types. Plugins may override or
133 133 # extend this mapping.
134 134 _settings_type_map = {
135 135 colander.String: 'unicode',
136 136 colander.Integer: 'int',
137 137 colander.Boolean: 'bool',
138 138 colander.List: 'list',
139 139 }
140 140
141 141 # list of keys in settings that are unsafe to be logged, should be passwords
142 142 # or other crucial credentials
143 143 _settings_unsafe_keys = []
144 144
145 145 def __init__(self, plugin_id):
146 146 self._plugin_id = plugin_id
147 147
148 148 def __str__(self):
149 149 return self.get_id()
150 150
151 151 def _get_setting_full_name(self, name):
152 152 """
153 153 Return the full setting name used for storing values in the database.
154 154 """
155 155 # TODO: johbo: Using the name here is problematic. It would be good to
156 156 # introduce either new models in the database to hold Plugin and
157 157 # PluginSetting or to use the plugin id here.
158 158 return 'auth_{}_{}'.format(self.name, name)
159 159
160 160 def _get_setting_type(self, name):
161 161 """
162 162 Return the type of a setting. This type is defined by the SettingsModel
163 163 and determines how the setting is stored in DB. Optionally the suffix
164 164 `.encrypted` is appended to instruct SettingsModel to store it
165 165 encrypted.
166 166 """
167 167 schema_node = self.get_settings_schema().get(name)
168 168 db_type = self._settings_type_map.get(
169 169 type(schema_node.typ), 'unicode')
170 170 if name in self._settings_encrypted:
171 171 db_type = '{}.encrypted'.format(db_type)
172 172 return db_type
173 173
174 174 def is_enabled(self):
175 175 """
176 176 Returns true if this plugin is enabled. An enabled plugin can be
177 177 configured in the admin interface but it is not consulted during
178 178 authentication.
179 179 """
180 180 auth_plugins = SettingsModel().get_auth_plugins()
181 181 return self.get_id() in auth_plugins
182 182
183 183 def is_active(self, plugin_cached_settings=None):
184 184 """
185 185 Returns true if the plugin is activated. An activated plugin is
186 186 consulted during authentication, assumed it is also enabled.
187 187 """
188 188 return self.get_setting_by_name(
189 189 'enabled', plugin_cached_settings=plugin_cached_settings)
190 190
191 191 def get_id(self):
192 192 """
193 193 Returns the plugin id.
194 194 """
195 195 return self._plugin_id
196 196
197 197 def get_display_name(self):
198 198 """
199 199 Returns a translation string for displaying purposes.
200 200 """
201 201 raise NotImplementedError('Not implemented in base class')
202 202
203 203 def get_settings_schema(self):
204 204 """
205 205 Returns a colander schema, representing the plugin settings.
206 206 """
207 207 return AuthnPluginSettingsSchemaBase()
208 208
209 209 def get_settings(self):
210 210 """
211 211 Returns the plugin settings as dictionary.
212 212 """
213 213 settings = {}
214 214 raw_settings = SettingsModel().get_all_settings()
215 215 for node in self.get_settings_schema():
216 216 settings[node.name] = self.get_setting_by_name(
217 217 node.name, plugin_cached_settings=raw_settings)
218 218 return settings
219 219
220 220 def get_setting_by_name(self, name, default=None, plugin_cached_settings=None):
221 221 """
222 222 Returns a plugin setting by name.
223 223 """
224 224 full_name = 'rhodecode_{}'.format(self._get_setting_full_name(name))
225 225 if plugin_cached_settings:
226 226 plugin_settings = plugin_cached_settings
227 227 else:
228 228 plugin_settings = SettingsModel().get_all_settings()
229 229
230 230 if full_name in plugin_settings:
231 231 return plugin_settings[full_name]
232 232 else:
233 233 return default
234 234
235 235 def create_or_update_setting(self, name, value):
236 236 """
237 237 Create or update a setting for this plugin in the persistent storage.
238 238 """
239 239 full_name = self._get_setting_full_name(name)
240 240 type_ = self._get_setting_type(name)
241 241 db_setting = SettingsModel().create_or_update_setting(
242 242 full_name, value, type_)
243 243 return db_setting.app_settings_value
244 244
245 245 def log_safe_settings(self, settings):
246 246 """
247 247 returns a log safe representation of settings, without any secrets
248 248 """
249 249 settings_copy = copy.deepcopy(settings)
250 250 for k in self._settings_unsafe_keys:
251 251 if k in settings_copy:
252 252 del settings_copy[k]
253 253 return settings_copy
254 254
255 255 @hybrid_property
256 256 def name(self):
257 257 """
258 258 Returns the name of this authentication plugin.
259 259
260 260 :returns: string
261 261 """
262 262 raise NotImplementedError("Not implemented in base class")
263 263
264 264 def get_url_slug(self):
265 265 """
266 266 Returns a slug which should be used when constructing URLs which refer
267 267 to this plugin. By default it returns the plugin name. If the name is
268 268 not suitable for using it in an URL the plugin should override this
269 269 method.
270 270 """
271 271 return self.name
272 272
273 273 @property
274 274 def is_headers_auth(self):
275 275 """
276 276 Returns True if this authentication plugin uses HTTP headers as
277 277 authentication method.
278 278 """
279 279 return False
280 280
281 281 @hybrid_property
282 282 def is_container_auth(self):
283 283 """
284 284 Deprecated method that indicates if this authentication plugin uses
285 285 HTTP headers as authentication method.
286 286 """
287 287 warnings.warn(
288 288 'Use is_headers_auth instead.', category=DeprecationWarning)
289 289 return self.is_headers_auth
290 290
291 291 @hybrid_property
292 292 def allows_creating_users(self):
293 293 """
294 294 Defines if Plugin allows users to be created on-the-fly when
295 295 authentication is called. Controls how external plugins should behave
296 296 in terms if they are allowed to create new users, or not. Base plugins
297 297 should not be allowed to, but External ones should be !
298 298
299 299 :return: bool
300 300 """
301 301 return False
302 302
303 303 def set_auth_type(self, auth_type):
304 304 self.auth_type = auth_type
305 305
306 306 def set_calling_scope_repo(self, acl_repo_name):
307 307 self.acl_repo_name = acl_repo_name
308 308
309 309 def allows_authentication_from(
310 310 self, user, allows_non_existing_user=True,
311 311 allowed_auth_plugins=None, allowed_auth_sources=None):
312 312 """
313 313 Checks if this authentication module should accept a request for
314 314 the current user.
315 315
316 316 :param user: user object fetched using plugin's get_user() method.
317 317 :param allows_non_existing_user: if True, don't allow the
318 318 user to be empty, meaning not existing in our database
319 319 :param allowed_auth_plugins: if provided, users extern_type will be
320 320 checked against a list of provided extern types, which are plugin
321 321 auth_names in the end
322 322 :param allowed_auth_sources: authentication type allowed,
323 323 `http` or `vcs` default is both.
324 324 defines if plugin will accept only http authentication vcs
325 325 authentication(git/hg) or both
326 326 :returns: boolean
327 327 """
328 328 if not user and not allows_non_existing_user:
329 329 log.debug('User is empty but plugin does not allow empty users,'
330 330 'not allowed to authenticate')
331 331 return False
332 332
333 333 expected_auth_plugins = allowed_auth_plugins or [self.name]
334 334 if user and (user.extern_type and
335 335 user.extern_type not in expected_auth_plugins):
336 336 log.debug(
337 337 'User `%s` is bound to `%s` auth type. Plugin allows only '
338 338 '%s, skipping', user, user.extern_type, expected_auth_plugins)
339 339
340 340 return False
341 341
342 342 # by default accept both
343 343 expected_auth_from = allowed_auth_sources or [HTTP_TYPE, VCS_TYPE]
344 344 if self.auth_type not in expected_auth_from:
345 345 log.debug('Current auth source is %s but plugin only allows %s',
346 346 self.auth_type, expected_auth_from)
347 347 return False
348 348
349 349 return True
350 350
351 351 def get_user(self, username=None, **kwargs):
352 352 """
353 353 Helper method for user fetching in plugins, by default it's using
354 354 simple fetch by username, but this method can be custimized in plugins
355 355 eg. headers auth plugin to fetch user by environ params
356 356
357 357 :param username: username if given to fetch from database
358 358 :param kwargs: extra arguments needed for user fetching.
359 359 """
360 360 user = None
361 361 log.debug(
362 362 'Trying to fetch user `%s` from RhodeCode database', username)
363 363 if username:
364 364 user = User.get_by_username(username)
365 365 if not user:
366 366 log.debug('User not found, fallback to fetch user in '
367 367 'case insensitive mode')
368 368 user = User.get_by_username(username, case_insensitive=True)
369 369 else:
370 370 log.debug('provided username:`%s` is empty skipping...', username)
371 371 if not user:
372 372 log.debug('User `%s` not found in database', username)
373 373 else:
374 374 log.debug('Got DB user:%s', user)
375 375 return user
376 376
377 377 def user_activation_state(self):
378 378 """
379 379 Defines user activation state when creating new users
380 380
381 381 :returns: boolean
382 382 """
383 383 raise NotImplementedError("Not implemented in base class")
384 384
385 385 def auth(self, userobj, username, passwd, settings, **kwargs):
386 386 """
387 387 Given a user object (which may be null), username, a plaintext
388 388 password, and a settings object (containing all the keys needed as
389 389 listed in settings()), authenticate this user's login attempt.
390 390
391 391 Return None on failure. On success, return a dictionary of the form:
392 392
393 393 see: RhodeCodeAuthPluginBase.auth_func_attrs
394 394 This is later validated for correctness
395 395 """
396 396 raise NotImplementedError("not implemented in base class")
397 397
398 398 def _authenticate(self, userobj, username, passwd, settings, **kwargs):
399 399 """
400 400 Wrapper to call self.auth() that validates call on it
401 401
402 402 :param userobj: userobj
403 403 :param username: username
404 404 :param passwd: plaintext password
405 405 :param settings: plugin settings
406 406 """
407 407 auth = self.auth(userobj, username, passwd, settings, **kwargs)
408 408 if auth:
409 409 auth['_plugin'] = self.name
410 410 auth['_ttl_cache'] = self.get_ttl_cache(settings)
411 411 # check if hash should be migrated ?
412 412 new_hash = auth.get('_hash_migrate')
413 413 if new_hash:
414 414 self._migrate_hash_to_bcrypt(username, passwd, new_hash)
415 415 if 'user_group_sync' not in auth:
416 416 auth['user_group_sync'] = False
417 417 return self._validate_auth_return(auth)
418 418 return auth
419 419
420 420 def _migrate_hash_to_bcrypt(self, username, password, new_hash):
421 421 new_hash_cypher = _RhodeCodeCryptoBCrypt()
422 422 # extra checks, so make sure new hash is correct.
423 423 password_encoded = safe_str(password)
424 424 if new_hash and new_hash_cypher.hash_check(
425 425 password_encoded, new_hash):
426 426 cur_user = User.get_by_username(username)
427 427 cur_user.password = new_hash
428 428 Session().add(cur_user)
429 429 Session().flush()
430 430 log.info('Migrated user %s hash to bcrypt', cur_user)
431 431
432 432 def _validate_auth_return(self, ret):
433 433 if not isinstance(ret, dict):
434 434 raise Exception('returned value from auth must be a dict')
435 435 for k in self.auth_func_attrs:
436 436 if k not in ret:
437 437 raise Exception('Missing %s attribute from returned data' % k)
438 438 return ret
439 439
440 440 def get_ttl_cache(self, settings=None):
441 441 plugin_settings = settings or self.get_settings()
442 442 cache_ttl = 0
443 443
444 444 if isinstance(self.AUTH_CACHE_TTL, (int, long)):
445 445 # plugin cache set inside is more important than the settings value
446 446 cache_ttl = self.AUTH_CACHE_TTL
447 447 elif plugin_settings.get('cache_ttl'):
448 448 cache_ttl = safe_int(plugin_settings.get('cache_ttl'), 0)
449 449
450 450 plugin_cache_active = bool(cache_ttl and cache_ttl > 0)
451 451 return plugin_cache_active, cache_ttl
452 452
453 453
454 454 class RhodeCodeExternalAuthPlugin(RhodeCodeAuthPluginBase):
455 455
456 456 @hybrid_property
457 457 def allows_creating_users(self):
458 458 return True
459 459
460 460 def use_fake_password(self):
461 461 """
462 462 Return a boolean that indicates whether or not we should set the user's
463 463 password to a random value when it is authenticated by this plugin.
464 464 If your plugin provides authentication, then you will generally
465 465 want this.
466 466
467 467 :returns: boolean
468 468 """
469 469 raise NotImplementedError("Not implemented in base class")
470 470
471 471 def _authenticate(self, userobj, username, passwd, settings, **kwargs):
472 472 # at this point _authenticate calls plugin's `auth()` function
473 473 auth = super(RhodeCodeExternalAuthPlugin, self)._authenticate(
474 474 userobj, username, passwd, settings, **kwargs)
475 475
476 476 if auth:
477 477 # maybe plugin will clean the username ?
478 478 # we should use the return value
479 479 username = auth['username']
480 480
481 481 # if external source tells us that user is not active, we should
482 482 # skip rest of the process. This can prevent from creating users in
483 483 # RhodeCode when using external authentication, but if it's
484 484 # inactive user we shouldn't create that user anyway
485 485 if auth['active_from_extern'] is False:
486 486 log.warning(
487 487 "User %s authenticated against %s, but is inactive",
488 488 username, self.__module__)
489 489 return None
490 490
491 491 cur_user = User.get_by_username(username, case_insensitive=True)
492 492 is_user_existing = cur_user is not None
493 493
494 494 if is_user_existing:
495 495 log.debug('Syncing user `%s` from '
496 496 '`%s` plugin', username, self.name)
497 497 else:
498 498 log.debug('Creating non existing user `%s` from '
499 499 '`%s` plugin', username, self.name)
500 500
501 501 if self.allows_creating_users:
502 502 log.debug('Plugin `%s` allows to '
503 503 'create new users', self.name)
504 504 else:
505 505 log.debug('Plugin `%s` does not allow to '
506 506 'create new users', self.name)
507 507
508 508 user_parameters = {
509 509 'username': username,
510 510 'email': auth["email"],
511 511 'firstname': auth["firstname"],
512 512 'lastname': auth["lastname"],
513 513 'active': auth["active"],
514 514 'admin': auth["admin"],
515 515 'extern_name': auth["extern_name"],
516 516 'extern_type': self.name,
517 517 'plugin': self,
518 518 'allow_to_create_user': self.allows_creating_users,
519 519 }
520 520
521 521 if not is_user_existing:
522 522 if self.use_fake_password():
523 523 # Randomize the PW because we don't need it, but don't want
524 524 # them blank either
525 525 passwd = PasswordGenerator().gen_password(length=16)
526 526 user_parameters['password'] = passwd
527 527 else:
528 528 # Since the password is required by create_or_update method of
529 529 # UserModel, we need to set it explicitly.
530 530 # The create_or_update method is smart and recognises the
531 531 # password hashes as well.
532 532 user_parameters['password'] = cur_user.password
533 533
534 534 # we either create or update users, we also pass the flag
535 535 # that controls if this method can actually do that.
536 536 # raises NotAllowedToCreateUserError if it cannot, and we try to.
537 537 user = UserModel().create_or_update(**user_parameters)
538 538 Session().flush()
539 539 # enforce user is just in given groups, all of them has to be ones
540 540 # created from plugins. We store this info in _group_data JSON
541 541 # field
542 542
543 543 if auth['user_group_sync']:
544 544 try:
545 545 groups = auth['groups'] or []
546 546 log.debug(
547 547 'Performing user_group sync based on set `%s` '
548 548 'returned by `%s` plugin', groups, self.name)
549 549 UserGroupModel().enforce_groups(user, groups, self.name)
550 550 except Exception:
551 551 # for any reason group syncing fails, we should
552 552 # proceed with login
553 553 log.error(traceback.format_exc())
554 554
555 555 Session().commit()
556 556 return auth
557 557
558 558
559 class AuthLdapBase(object):
560
561 @classmethod
562 def _build_servers(cls, ldap_server_type, ldap_server, port):
563 def host_resolver(host, port, full_resolve=True):
564 """
565 Main work for this function is to prevent ldap connection issues,
566 and detect them early using a "greenified" sockets
567 """
568 host = host.strip()
569 if not full_resolve:
570 return '{}:{}'.format(host, port)
571
572 log.debug('LDAP: Resolving IP for LDAP host %s', host)
573 try:
574 ip = socket.gethostbyname(host)
575 log.debug('Got LDAP server %s ip %s', host, ip)
576 except Exception:
577 raise LdapConnectionError(
578 'Failed to resolve host: `{}`'.format(host))
579
580 log.debug('LDAP: Checking if IP %s is accessible', ip)
581 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
582 try:
583 s.connect((ip, int(port)))
584 s.shutdown(socket.SHUT_RD)
585 except Exception:
586 raise LdapConnectionError(
587 'Failed to connect to host: `{}:{}`'.format(host, port))
588
589 return '{}:{}'.format(host, port)
590
591 if len(ldap_server) == 1:
592 # in case of single server use resolver to detect potential
593 # connection issues
594 full_resolve = True
595 else:
596 full_resolve = False
597
598 return ', '.join(
599 ["{}://{}".format(
600 ldap_server_type,
601 host_resolver(host, port, full_resolve=full_resolve))
602 for host in ldap_server])
603
604 @classmethod
605 def _get_server_list(cls, servers):
606 return map(string.strip, servers.split(','))
607
608 @classmethod
609 def get_uid(cls, username, server_addresses):
610 uid = username
611 for server_addr in server_addresses:
612 uid = chop_at(username, "@%s" % server_addr)
613 return uid
614
615
559 616 def loadplugin(plugin_id):
560 617 """
561 618 Loads and returns an instantiated authentication plugin.
562 619 Returns the RhodeCodeAuthPluginBase subclass on success,
563 620 or None on failure.
564 621 """
565 622 # TODO: Disusing pyramids thread locals to retrieve the registry.
566 623 authn_registry = get_authn_registry()
567 624 plugin = authn_registry.get_plugin(plugin_id)
568 625 if plugin is None:
569 626 log.error('Authentication plugin not found: "%s"', plugin_id)
570 627 return plugin
571 628
572 629
573 630 def get_authn_registry(registry=None):
574 631 registry = registry or get_current_registry()
575 632 authn_registry = registry.getUtility(IAuthnPluginRegistry)
576 633 return authn_registry
577 634
578 635
579 636 def get_auth_cache_manager(custom_ttl=None, suffix=None):
580 637 cache_name = 'rhodecode.authentication'
581 638 if suffix:
582 639 cache_name = 'rhodecode.authentication.{}'.format(suffix)
583 640 return caches.get_cache_manager(
584 641 'auth_plugins', cache_name, custom_ttl)
585 642
586 643
587 644 def get_perms_cache_manager(custom_ttl=None, suffix=None):
588 645 cache_name = 'rhodecode.permissions'
589 646 if suffix:
590 647 cache_name = 'rhodecode.permissions.{}'.format(suffix)
591 648 return caches.get_cache_manager(
592 649 'auth_plugins', cache_name, custom_ttl)
593 650
594 651
595 652 def authenticate(username, password, environ=None, auth_type=None,
596 653 skip_missing=False, registry=None, acl_repo_name=None):
597 654 """
598 655 Authentication function used for access control,
599 656 It tries to authenticate based on enabled authentication modules.
600 657
601 658 :param username: username can be empty for headers auth
602 659 :param password: password can be empty for headers auth
603 660 :param environ: environ headers passed for headers auth
604 661 :param auth_type: type of authentication, either `HTTP_TYPE` or `VCS_TYPE`
605 662 :param skip_missing: ignores plugins that are in db but not in environment
606 663 :returns: None if auth failed, plugin_user dict if auth is correct
607 664 """
608 665 if not auth_type or auth_type not in [HTTP_TYPE, VCS_TYPE]:
609 666 raise ValueError('auth type must be on of http, vcs got "%s" instead'
610 667 % auth_type)
611 668 headers_only = environ and not (username and password)
612 669
613 670 authn_registry = get_authn_registry(registry)
614 671 plugins_to_check = authn_registry.get_plugins_for_authentication()
615 672 log.debug('Starting ordered authentication chain using %s plugins',
616 plugins_to_check)
673 [x.name for x in plugins_to_check])
617 674 for plugin in plugins_to_check:
618 675 plugin.set_auth_type(auth_type)
619 676 plugin.set_calling_scope_repo(acl_repo_name)
620 677
621 678 if headers_only and not plugin.is_headers_auth:
622 679 log.debug('Auth type is for headers only and plugin `%s` is not '
623 680 'headers plugin, skipping...', plugin.get_id())
624 681 continue
625 682
626 683 log.debug('Trying authentication using ** %s **', plugin.get_id())
627 684
628 685 # load plugin settings from RhodeCode database
629 686 plugin_settings = plugin.get_settings()
630 687 plugin_sanitized_settings = plugin.log_safe_settings(plugin_settings)
631 688 log.debug('Plugin `%s` settings:%s', plugin.get_id(), plugin_sanitized_settings)
632 689
633 690 # use plugin's method of user extraction.
634 691 user = plugin.get_user(username, environ=environ,
635 692 settings=plugin_settings)
636 693 display_user = user.username if user else username
637 694 log.debug(
638 695 'Plugin %s extracted user is `%s`', plugin.get_id(), display_user)
639 696
640 697 if not plugin.allows_authentication_from(user):
641 698 log.debug('Plugin %s does not accept user `%s` for authentication',
642 699 plugin.get_id(), display_user)
643 700 continue
644 701 else:
645 702 log.debug('Plugin %s accepted user `%s` for authentication',
646 703 plugin.get_id(), display_user)
647 704
648 705 log.info('Authenticating user `%s` using %s plugin',
649 706 display_user, plugin.get_id())
650 707
651 708 plugin_cache_active, cache_ttl = plugin.get_ttl_cache(plugin_settings)
652 709
653 710 # get instance of cache manager configured for a namespace
654 711 cache_manager = get_auth_cache_manager(
655 712 custom_ttl=cache_ttl, suffix=user.user_id if user else '')
656 713
657 714 log.debug('AUTH_CACHE_TTL for plugin `%s` active: %s (TTL: %s)',
658 715 plugin.get_id(), plugin_cache_active, cache_ttl)
659 716
660 717 # for environ based password can be empty, but then the validation is
661 718 # on the server that fills in the env data needed for authentication
662 719
663 720 _password_hash = caches.compute_key_from_params(
664 721 plugin.name, username, (password or ''))
665 722
666 723 # _authenticate is a wrapper for .auth() method of plugin.
667 724 # it checks if .auth() sends proper data.
668 725 # For RhodeCodeExternalAuthPlugin it also maps users to
669 726 # Database and maps the attributes returned from .auth()
670 727 # to RhodeCode database. If this function returns data
671 728 # then auth is correct.
672 729 start = time.time()
673 730 log.debug('Running plugin `%s` _authenticate method', plugin.get_id())
674 731
675 732 def auth_func():
676 733 """
677 734 This function is used internally in Cache of Beaker to calculate
678 735 Results
679 736 """
680 737 log.debug('auth: calculating password access now...')
681 738 return plugin._authenticate(
682 739 user, username, password, plugin_settings,
683 740 environ=environ or {})
684 741
685 742 if plugin_cache_active:
686 743 log.debug('Trying to fetch cached auth by pwd hash `...%s`',
687 744 _password_hash[:6])
688 745 plugin_user = cache_manager.get(
689 746 _password_hash, createfunc=auth_func)
690 747 else:
691 748 plugin_user = auth_func()
692 749
693 750 auth_time = time.time() - start
694 751 log.debug('Authentication for plugin `%s` completed in %.3fs, '
695 752 'expiration time of fetched cache %.1fs.',
696 753 plugin.get_id(), auth_time, cache_ttl)
697 754
698 755 log.debug('PLUGIN USER DATA: %s', plugin_user)
699 756
700 757 if plugin_user:
701 758 log.debug('Plugin returned proper authentication data')
702 759 return plugin_user
703 760 # we failed to Auth because .auth() method didn't return proper user
704 761 log.debug("User `%s` failed to authenticate against %s",
705 762 display_user, plugin.get_id())
706 763
707 764 # case when we failed to authenticate against all defined plugins
708 765 return None
709 766
710 767
711 768 def chop_at(s, sub, inclusive=False):
712 769 """Truncate string ``s`` at the first occurrence of ``sub``.
713 770
714 771 If ``inclusive`` is true, truncate just after ``sub`` rather than at it.
715 772
716 773 >>> chop_at("plutocratic brats", "rat")
717 774 'plutoc'
718 775 >>> chop_at("plutocratic brats", "rat", True)
719 776 'plutocrat'
720 777 """
721 778 pos = s.find(sub)
722 779 if pos == -1:
723 780 return s
724 781 if inclusive:
725 782 return s[:pos+len(sub)]
726 783 return s[:pos]
@@ -0,0 +1,19 b''
1 # -*- coding: utf-8 -*-
2
3 # Copyright (C) 2012-2018 RhodeCode GmbH
4 #
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU Affero General Public License, version 3
7 # (only), as published by the Free Software Foundation.
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 Affero General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 #
17 # This program is dual-licensed. If you wish to learn more about the
18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
@@ -1,542 +1,505 b''
1 1 # -*- coding: utf-8 -*-
2 2
3 3 # Copyright (C) 2010-2018 RhodeCode GmbH
4 4 #
5 5 # This program is free software: you can redistribute it and/or modify
6 6 # it under the terms of the GNU Affero General Public License, version 3
7 7 # (only), as published by the Free Software Foundation.
8 8 #
9 9 # This program is distributed in the hope that it will be useful,
10 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 12 # GNU General Public License for more details.
13 13 #
14 14 # You should have received a copy of the GNU Affero General Public License
15 15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 16 #
17 17 # This program is dual-licensed. If you wish to learn more about the
18 18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20 20
21 21 """
22 22 RhodeCode authentication plugin for LDAP
23 23 """
24 24
25 import socket
26 import re
27 import colander
28 25 import logging
29 26 import traceback
30 import string
31 27
28 import colander
32 29 from rhodecode.translation import _
33 30 from rhodecode.authentication.base import (
34 RhodeCodeExternalAuthPlugin, chop_at, hybrid_property)
31 RhodeCodeExternalAuthPlugin, AuthLdapBase, hybrid_property)
35 32 from rhodecode.authentication.schema import AuthnPluginSettingsSchemaBase
36 33 from rhodecode.authentication.routes import AuthnPluginResourceBase
37 34 from rhodecode.lib.colander_utils import strip_whitespace
38 35 from rhodecode.lib.exceptions import (
39 36 LdapConnectionError, LdapUsernameError, LdapPasswordError, LdapImportError
40 37 )
41 38 from rhodecode.lib.utils2 import safe_unicode, safe_str
42 39 from rhodecode.model.db import User
43 40 from rhodecode.model.validators import Missing
44 41
45 42 log = logging.getLogger(__name__)
46 43
47 44 try:
48 45 import ldap
49 46 except ImportError:
50 47 # means that python-ldap is not installed, we use Missing object to mark
51 48 # ldap lib is Missing
52 49 ldap = Missing
53 50
54 51
55 52 class LdapError(Exception):
56 53 pass
57 54
58 55 def plugin_factory(plugin_id, *args, **kwds):
59 56 """
60 57 Factory function that is called during plugin discovery.
61 58 It returns the plugin instance.
62 59 """
63 60 plugin = RhodeCodeAuthPlugin(plugin_id)
64 61 return plugin
65 62
66 63
67 64 class LdapAuthnResource(AuthnPluginResourceBase):
68 65 pass
69 66
70 67
71 68 class LdapSettingsSchema(AuthnPluginSettingsSchemaBase):
72 69 tls_kind_choices = ['PLAIN', 'LDAPS', 'START_TLS']
73 70 tls_reqcert_choices = ['NEVER', 'ALLOW', 'TRY', 'DEMAND', 'HARD']
74 71 search_scope_choices = ['BASE', 'ONELEVEL', 'SUBTREE']
75 72
76 73 host = colander.SchemaNode(
77 74 colander.String(),
78 75 default='',
79 76 description=_('Host[s] of the LDAP Server \n'
80 77 '(e.g., 192.168.2.154, or ldap-server.domain.com.\n '
81 78 'Multiple servers can be specified using commas'),
82 79 preparer=strip_whitespace,
83 80 title=_('LDAP Host'),
84 81 widget='string')
85 82 port = colander.SchemaNode(
86 83 colander.Int(),
87 84 default=389,
88 85 description=_('Custom port that the LDAP server is listening on. '
89 86 'Default value is: 389'),
90 87 preparer=strip_whitespace,
91 88 title=_('Port'),
92 89 validator=colander.Range(min=0, max=65536),
93 90 widget='int')
94 91
95 92 timeout = colander.SchemaNode(
96 93 colander.Int(),
97 94 default=60 * 5,
98 95 description=_('Timeout for LDAP connection'),
99 96 preparer=strip_whitespace,
100 97 title=_('Connection timeout'),
101 98 validator=colander.Range(min=1),
102 99 widget='int')
103 100
104 101 dn_user = colander.SchemaNode(
105 102 colander.String(),
106 103 default='',
107 104 description=_('Optional user DN/account to connect to LDAP if authentication is required. \n'
108 105 'e.g., cn=admin,dc=mydomain,dc=com, or '
109 106 'uid=root,cn=users,dc=mydomain,dc=com, or admin@mydomain.com'),
110 107 missing='',
111 108 preparer=strip_whitespace,
112 109 title=_('Account'),
113 110 widget='string')
114 111 dn_pass = colander.SchemaNode(
115 112 colander.String(),
116 113 default='',
117 114 description=_('Password to authenticate for given user DN.'),
118 115 missing='',
119 116 preparer=strip_whitespace,
120 117 title=_('Password'),
121 118 widget='password')
122 119 tls_kind = colander.SchemaNode(
123 120 colander.String(),
124 121 default=tls_kind_choices[0],
125 122 description=_('TLS Type'),
126 123 title=_('Connection Security'),
127 124 validator=colander.OneOf(tls_kind_choices),
128 125 widget='select')
129 126 tls_reqcert = colander.SchemaNode(
130 127 colander.String(),
131 128 default=tls_reqcert_choices[0],
132 129 description=_('Require Cert over TLS?. Self-signed and custom '
133 130 'certificates can be used when\n `RhodeCode Certificate` '
134 131 'found in admin > settings > system info page is extended.'),
135 132 title=_('Certificate Checks'),
136 133 validator=colander.OneOf(tls_reqcert_choices),
137 134 widget='select')
138 135 base_dn = colander.SchemaNode(
139 136 colander.String(),
140 137 default='',
141 138 description=_('Base DN to search. Dynamic bind is supported. Add `$login` marker '
142 139 'in it to be replaced with current user credentials \n'
143 140 '(e.g., dc=mydomain,dc=com, or ou=Users,dc=mydomain,dc=com)'),
144 141 missing='',
145 142 preparer=strip_whitespace,
146 143 title=_('Base DN'),
147 144 widget='string')
148 145 filter = colander.SchemaNode(
149 146 colander.String(),
150 147 default='',
151 148 description=_('Filter to narrow results \n'
152 149 '(e.g., (&(objectCategory=Person)(objectClass=user)), or \n'
153 150 '(memberof=cn=rc-login,ou=groups,ou=company,dc=mydomain,dc=com)))'),
154 151 missing='',
155 152 preparer=strip_whitespace,
156 153 title=_('LDAP Search Filter'),
157 154 widget='string')
158 155
159 156 search_scope = colander.SchemaNode(
160 157 colander.String(),
161 158 default=search_scope_choices[2],
162 159 description=_('How deep to search LDAP. If unsure set to SUBTREE'),
163 160 title=_('LDAP Search Scope'),
164 161 validator=colander.OneOf(search_scope_choices),
165 162 widget='select')
166 163 attr_login = colander.SchemaNode(
167 164 colander.String(),
168 165 default='uid',
169 166 description=_('LDAP Attribute to map to user name (e.g., uid, or sAMAccountName)'),
170 167 preparer=strip_whitespace,
171 168 title=_('Login Attribute'),
172 169 missing_msg=_('The LDAP Login attribute of the CN must be specified'),
173 170 widget='string')
174 171 attr_firstname = colander.SchemaNode(
175 172 colander.String(),
176 173 default='',
177 174 description=_('LDAP Attribute to map to first name (e.g., givenName)'),
178 175 missing='',
179 176 preparer=strip_whitespace,
180 177 title=_('First Name Attribute'),
181 178 widget='string')
182 179 attr_lastname = colander.SchemaNode(
183 180 colander.String(),
184 181 default='',
185 182 description=_('LDAP Attribute to map to last name (e.g., sn)'),
186 183 missing='',
187 184 preparer=strip_whitespace,
188 185 title=_('Last Name Attribute'),
189 186 widget='string')
190 187 attr_email = colander.SchemaNode(
191 188 colander.String(),
192 189 default='',
193 190 description=_('LDAP Attribute to map to email address (e.g., mail).\n'
194 191 'Emails are a crucial part of RhodeCode. \n'
195 192 'If possible add a valid email attribute to ldap users.'),
196 193 missing='',
197 194 preparer=strip_whitespace,
198 195 title=_('Email Attribute'),
199 196 widget='string')
200 197
201 198
202 class AuthLdap(object):
203
204 def _build_servers(self):
205 def host_resolver(host, port):
206 """
207 Main work for this function is to prevent ldap connection issues,
208 and detect them early using a "greenified" sockets
209 """
210 host = host.strip()
211
212 log.info('Resolving LDAP host %s', host)
213 try:
214 ip = socket.gethostbyname(host)
215 log.info('Got LDAP server %s ip %s', host, ip)
216 except Exception:
217 raise LdapConnectionError(
218 'Failed to resolve host: `{}`'.format(host))
219
220 log.info('Checking LDAP IP access %s', ip)
221 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
222 try:
223 s.connect((ip, int(port)))
224 s.shutdown(socket.SHUT_RD)
225 except Exception:
226 raise LdapConnectionError(
227 'Failed to connect to host: `{}:{}`'.format(host, port))
228
229 return '{}:{}'.format(host, port)
230
231 port = self.LDAP_SERVER_PORT
232 return ', '.join(
233 ["{}://{}".format(
234 self.ldap_server_type, host_resolver(host, port))
235 for host in self.SERVER_ADDRESSES])
199 class AuthLdap(AuthLdapBase):
236 200
237 201 def __init__(self, server, base_dn, port=389, bind_dn='', bind_pass='',
238 202 tls_kind='PLAIN', tls_reqcert='DEMAND', ldap_version=3,
239 203 search_scope='SUBTREE', attr_login='uid',
240 204 ldap_filter='', timeout=None):
241 205 if ldap == Missing:
242 206 raise LdapImportError("Missing or incompatible ldap library")
243 207
244 208 self.debug = False
245 209 self.timeout = timeout or 60 * 5
246 210 self.ldap_version = ldap_version
247 211 self.ldap_server_type = 'ldap'
248 212
249 213 self.TLS_KIND = tls_kind
250 214
251 215 if self.TLS_KIND == 'LDAPS':
252 216 port = port or 689
253 217 self.ldap_server_type += 's'
254 218
255 219 OPT_X_TLS_DEMAND = 2
256 220 self.TLS_REQCERT = getattr(ldap, 'OPT_X_TLS_%s' % tls_reqcert,
257 221 OPT_X_TLS_DEMAND)
222 self.LDAP_SERVER = server
258 223 # split server into list
259 self.SERVER_ADDRESSES = server.split(',')
224 self.SERVER_ADDRESSES = self._get_server_list(server)
260 225 self.LDAP_SERVER_PORT = port
261 226
262 227 # USE FOR READ ONLY BIND TO LDAP SERVER
263 228 self.attr_login = attr_login
264 229
265 230 self.LDAP_BIND_DN = safe_str(bind_dn)
266 231 self.LDAP_BIND_PASS = safe_str(bind_pass)
267 self.LDAP_SERVER = self._build_servers()
232
268 233 self.SEARCH_SCOPE = getattr(ldap, 'SCOPE_%s' % search_scope)
269 234 self.BASE_DN = safe_str(base_dn)
270 235 self.LDAP_FILTER = safe_str(ldap_filter)
271 236
272 237 def _get_ldap_conn(self):
273 log.debug('initializing LDAP connection to:%s', self.LDAP_SERVER)
274 238
275 239 if self.debug:
276 240 ldap.set_option(ldap.OPT_DEBUG_LEVEL, 255)
277 241
278 242 if hasattr(ldap, 'OPT_X_TLS_CACERTDIR'):
279 243 ldap.set_option(ldap.OPT_X_TLS_CACERTDIR, '/etc/openldap/cacerts')
280 244 if self.TLS_KIND != 'PLAIN':
281 245 ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, self.TLS_REQCERT)
282 246
283 247 ldap.set_option(ldap.OPT_REFERRALS, ldap.OPT_OFF)
284 248 ldap.set_option(ldap.OPT_RESTART, ldap.OPT_ON)
285 249
286 250 # init connection now
287 ldap_conn = ldap.initialize(self.LDAP_SERVER)
251 ldap_servers = self._build_servers(
252 self.ldap_server_type, self.SERVER_ADDRESSES, self.LDAP_SERVER_PORT)
253 log.debug('initializing LDAP connection to:%s', ldap_servers)
254 ldap_conn = ldap.initialize(ldap_servers)
288 255 ldap_conn.set_option(ldap.OPT_NETWORK_TIMEOUT, self.timeout)
289 256 ldap_conn.set_option(ldap.OPT_TIMEOUT, self.timeout)
290 257 ldap_conn.timeout = self.timeout
291 258
292 259 if self.ldap_version == 2:
293 260 ldap_conn.protocol = ldap.VERSION2
294 261 else:
295 262 ldap_conn.protocol = ldap.VERSION3
296 263
297 264 if self.TLS_KIND == 'START_TLS':
298 265 ldap_conn.start_tls_s()
299 266
300 267 if self.LDAP_BIND_DN and self.LDAP_BIND_PASS:
301 268 log.debug('Trying simple_bind with password and given login DN: %s',
302 269 self.LDAP_BIND_DN)
303 270 ldap_conn.simple_bind_s(self.LDAP_BIND_DN, self.LDAP_BIND_PASS)
304 271
305 272 return ldap_conn
306 273
307 def get_uid(self, username):
308 uid = username
309 for server_addr in self.SERVER_ADDRESSES:
310 uid = chop_at(username, "@%s" % server_addr)
311 return uid
312
313 274 def fetch_attrs_from_simple_bind(self, server, dn, username, password):
314 275 try:
315 276 log.debug('Trying simple bind with %s', dn)
316 277 server.simple_bind_s(dn, safe_str(password))
317 278 user = server.search_ext_s(
318 279 dn, ldap.SCOPE_BASE, '(objectClass=*)', )[0]
319 280 _, attrs = user
320 281 return attrs
321 282
322 283 except ldap.INVALID_CREDENTIALS:
323 284 log.debug(
324 285 "LDAP rejected password for user '%s': %s, org_exc:",
325 286 username, dn, exc_info=True)
326 287
327 288 def authenticate_ldap(self, username, password):
328 289 """
329 290 Authenticate a user via LDAP and return his/her LDAP properties.
330 291
331 292 Raises AuthenticationError if the credentials are rejected, or
332 293 EnvironmentError if the LDAP server can't be reached.
333 294
334 295 :param username: username
335 296 :param password: password
336 297 """
337 298
338 uid = self.get_uid(username)
299 uid = self.get_uid(username, self.SERVER_ADDRESSES)
300 user_attrs = {}
301 dn = ''
339 302
340 303 if not password:
341 304 msg = "Authenticating user %s with blank password not allowed"
342 305 log.warning(msg, username)
343 306 raise LdapPasswordError(msg)
344 307 if "," in username:
345 308 raise LdapUsernameError(
346 309 "invalid character `,` in username: `{}`".format(username))
347 310 ldap_conn = None
348 311 try:
349 312 ldap_conn = self._get_ldap_conn()
350 313 filter_ = '(&%s(%s=%s))' % (
351 314 self.LDAP_FILTER, self.attr_login, username)
352 log.debug("Authenticating %r filter %s at %s", self.BASE_DN,
353 filter_, self.LDAP_SERVER)
315 log.debug(
316 "Authenticating %r filter %s", self.BASE_DN, filter_)
354 317 lobjects = ldap_conn.search_ext_s(
355 318 self.BASE_DN, self.SEARCH_SCOPE, filter_)
356 319
357 320 if not lobjects:
358 321 log.debug("No matching LDAP objects for authentication "
359 322 "of UID:'%s' username:(%s)", uid, username)
360 323 raise ldap.NO_SUCH_OBJECT()
361 324
362 325 log.debug('Found matching ldap object, trying to authenticate')
363 326 for (dn, _attrs) in lobjects:
364 327 if dn is None:
365 328 continue
366 329
367 330 user_attrs = self.fetch_attrs_from_simple_bind(
368 331 ldap_conn, dn, username, password)
369 332 if user_attrs:
370 333 break
371 334
372 335 else:
373 336 raise LdapPasswordError(
374 337 'Failed to authenticate user `{}`'
375 338 'with given password'.format(username))
376 339
377 340 except ldap.NO_SUCH_OBJECT:
378 341 log.debug("LDAP says no such user '%s' (%s), org_exc:",
379 342 uid, username, exc_info=True)
380 343 raise LdapUsernameError('Unable to find user')
381 344 except ldap.SERVER_DOWN:
382 345 org_exc = traceback.format_exc()
383 346 raise LdapConnectionError(
384 347 "LDAP can't access authentication "
385 348 "server, org_exc:%s" % org_exc)
386 349 finally:
387 350 if ldap_conn:
388 351 log.debug('ldap: connection release')
389 352 try:
390 353 ldap_conn.unbind_s()
391 354 except Exception:
392 355 # for any reason this can raise exception we must catch it
393 356 # to not crush the server
394 357 pass
395 358
396 359 return dn, user_attrs
397 360
398 361
399 362 class RhodeCodeAuthPlugin(RhodeCodeExternalAuthPlugin):
400 363 # used to define dynamic binding in the
401 364 DYNAMIC_BIND_VAR = '$login'
402 365 _settings_unsafe_keys = ['dn_pass']
403 366
404 367 def includeme(self, config):
405 368 config.add_authn_plugin(self)
406 369 config.add_authn_resource(self.get_id(), LdapAuthnResource(self))
407 370 config.add_view(
408 371 'rhodecode.authentication.views.AuthnPluginViewBase',
409 372 attr='settings_get',
410 373 renderer='rhodecode:templates/admin/auth/plugin_settings.mako',
411 374 request_method='GET',
412 375 route_name='auth_home',
413 376 context=LdapAuthnResource)
414 377 config.add_view(
415 378 'rhodecode.authentication.views.AuthnPluginViewBase',
416 379 attr='settings_post',
417 380 renderer='rhodecode:templates/admin/auth/plugin_settings.mako',
418 381 request_method='POST',
419 382 route_name='auth_home',
420 383 context=LdapAuthnResource)
421 384
422 385 def get_settings_schema(self):
423 386 return LdapSettingsSchema()
424 387
425 388 def get_display_name(self):
426 389 return _('LDAP')
427 390
428 391 @hybrid_property
429 392 def name(self):
430 393 return "ldap"
431 394
432 395 def use_fake_password(self):
433 396 return True
434 397
435 398 def user_activation_state(self):
436 399 def_user_perms = User.get_default_user().AuthUser().permissions['global']
437 400 return 'hg.extern_activate.auto' in def_user_perms
438 401
439 402 def try_dynamic_binding(self, username, password, current_args):
440 403 """
441 404 Detects marker inside our original bind, and uses dynamic auth if
442 405 present
443 406 """
444 407
445 408 org_bind = current_args['bind_dn']
446 409 passwd = current_args['bind_pass']
447 410
448 411 def has_bind_marker(username):
449 412 if self.DYNAMIC_BIND_VAR in username:
450 413 return True
451 414
452 415 # we only passed in user with "special" variable
453 416 if org_bind and has_bind_marker(org_bind) and not passwd:
454 417 log.debug('Using dynamic user/password binding for ldap '
455 418 'authentication. Replacing `%s` with username',
456 419 self.DYNAMIC_BIND_VAR)
457 420 current_args['bind_dn'] = org_bind.replace(
458 421 self.DYNAMIC_BIND_VAR, username)
459 422 current_args['bind_pass'] = password
460 423
461 424 return current_args
462 425
463 426 def auth(self, userobj, username, password, settings, **kwargs):
464 427 """
465 428 Given a user object (which may be null), username, a plaintext password,
466 429 and a settings object (containing all the keys needed as listed in
467 430 settings()), authenticate this user's login attempt.
468 431
469 432 Return None on failure. On success, return a dictionary of the form:
470 433
471 434 see: RhodeCodeAuthPluginBase.auth_func_attrs
472 435 This is later validated for correctness
473 436 """
474 437
475 438 if not username or not password:
476 439 log.debug('Empty username or password skipping...')
477 440 return None
478 441
479 442 ldap_args = {
480 443 'server': settings.get('host', ''),
481 444 'base_dn': settings.get('base_dn', ''),
482 445 'port': settings.get('port'),
483 446 'bind_dn': settings.get('dn_user'),
484 447 'bind_pass': settings.get('dn_pass'),
485 448 'tls_kind': settings.get('tls_kind'),
486 449 'tls_reqcert': settings.get('tls_reqcert'),
487 450 'search_scope': settings.get('search_scope'),
488 451 'attr_login': settings.get('attr_login'),
489 452 'ldap_version': 3,
490 453 'ldap_filter': settings.get('filter'),
491 454 'timeout': settings.get('timeout')
492 455 }
493 456
494 457 ldap_attrs = self.try_dynamic_binding(username, password, ldap_args)
495 458
496 459 log.debug('Checking for ldap authentication.')
497 460
498 461 try:
499 462 aldap = AuthLdap(**ldap_args)
500 463 (user_dn, ldap_attrs) = aldap.authenticate_ldap(username, password)
501 464 log.debug('Got ldap DN response %s', user_dn)
502 465
503 466 def get_ldap_attr(k):
504 467 return ldap_attrs.get(settings.get(k), [''])[0]
505 468
506 469 # old attrs fetched from RhodeCode database
507 470 admin = getattr(userobj, 'admin', False)
508 471 active = getattr(userobj, 'active', True)
509 472 email = getattr(userobj, 'email', '')
510 473 username = getattr(userobj, 'username', username)
511 474 firstname = getattr(userobj, 'firstname', '')
512 475 lastname = getattr(userobj, 'lastname', '')
513 476 extern_type = getattr(userobj, 'extern_type', '')
514 477
515 478 groups = []
516 479 user_attrs = {
517 480 'username': username,
518 481 'firstname': safe_unicode(
519 482 get_ldap_attr('attr_firstname') or firstname),
520 483 'lastname': safe_unicode(
521 484 get_ldap_attr('attr_lastname') or lastname),
522 485 'groups': groups,
523 486 'user_group_sync': False,
524 487 'email': get_ldap_attr('attr_email') or email,
525 488 'admin': admin,
526 489 'active': active,
527 490 'active_from_extern': None,
528 491 'extern_name': user_dn,
529 492 'extern_type': extern_type,
530 493 }
531 494 log.debug('ldap user: %s', user_attrs)
532 495 log.info('user `%s` authenticated correctly', user_attrs['username'])
533 496
534 497 return user_attrs
535 498
536 499 except (LdapUsernameError, LdapPasswordError, LdapImportError):
537 500 log.exception("LDAP related exception")
538 501 return None
539 502 except (Exception,):
540 503 log.exception("Other exception")
541 504 return None
542 505
General Comments 0
You need to be logged in to leave comments. Login now