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