You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

543 rivejä
20 KiB

  1. """passlib.registry - registry for password hash handlers"""
  2. #=============================================================================
  3. # imports
  4. #=============================================================================
  5. # core
  6. import re
  7. import logging; log = logging.getLogger(__name__)
  8. from warnings import warn
  9. # pkg
  10. from passlib import exc
  11. from passlib.exc import ExpectedTypeError, PasslibWarning
  12. from passlib.ifc import PasswordHash
  13. from passlib.utils import (
  14. is_crypt_handler, has_crypt as os_crypt_present,
  15. unix_crypt_schemes as os_crypt_schemes,
  16. )
  17. from passlib.utils.compat import unicode_or_str
  18. from passlib.utils.decor import memoize_single_value
  19. # local
  20. __all__ = [
  21. "register_crypt_handler_path",
  22. "register_crypt_handler",
  23. "get_crypt_handler",
  24. "list_crypt_handlers",
  25. ]
  26. #=============================================================================
  27. # proxy object used in place of 'passlib.hash' module
  28. #=============================================================================
  29. class _PasslibRegistryProxy(object):
  30. """proxy module passlib.hash
  31. this module is in fact an object which lazy-loads
  32. the requested password hash algorithm from wherever it has been stored.
  33. it acts as a thin wrapper around :func:`passlib.registry.get_crypt_handler`.
  34. """
  35. __name__ = "passlib.hash"
  36. __package__ = None
  37. def __getattr__(self, attr):
  38. if attr.startswith("_"):
  39. raise AttributeError("missing attribute: %r" % (attr,))
  40. handler = get_crypt_handler(attr, None)
  41. if handler:
  42. return handler
  43. else:
  44. raise AttributeError("unknown password hash: %r" % (attr,))
  45. def __setattr__(self, attr, value):
  46. if attr.startswith("_"):
  47. # writing to private attributes should behave normally.
  48. # (required so GAE can write to the __loader__ attribute).
  49. object.__setattr__(self, attr, value)
  50. else:
  51. # writing to public attributes should be treated
  52. # as attempting to register a handler.
  53. register_crypt_handler(value, _attr=attr)
  54. def __repr__(self):
  55. return "<proxy module 'passlib.hash'>"
  56. def __dir__(self):
  57. # this adds in lazy-loaded handler names,
  58. # otherwise this is the standard dir() implementation.
  59. attrs = set(dir(self.__class__))
  60. attrs.update(self.__dict__)
  61. attrs.update(_locations)
  62. return sorted(attrs)
  63. # create single instance - available publically as 'passlib.hash'
  64. _proxy = _PasslibRegistryProxy()
  65. #=============================================================================
  66. # internal registry state
  67. #=============================================================================
  68. # singleton uses to detect omitted keywords
  69. _UNSET = object()
  70. # dict mapping name -> loaded handlers (just uses proxy object's internal dict)
  71. _handlers = _proxy.__dict__
  72. # dict mapping names -> import path for lazy loading.
  73. # * import path should be "module.path" or "module.path:attr"
  74. # * if attr omitted, "name" used as default.
  75. _locations = dict(
  76. # NOTE: this is a hardcoded list of the handlers built into passlib,
  77. # applications should call register_crypt_handler_path()
  78. apr_md5_crypt = "passlib.handlers.md5_crypt",
  79. argon2 = "passlib.handlers.argon2",
  80. atlassian_pbkdf2_sha1 = "passlib.handlers.pbkdf2",
  81. bcrypt = "passlib.handlers.bcrypt",
  82. bcrypt_sha256 = "passlib.handlers.bcrypt",
  83. bigcrypt = "passlib.handlers.des_crypt",
  84. bsd_nthash = "passlib.handlers.windows",
  85. bsdi_crypt = "passlib.handlers.des_crypt",
  86. cisco_pix = "passlib.handlers.cisco",
  87. cisco_asa = "passlib.handlers.cisco",
  88. cisco_type7 = "passlib.handlers.cisco",
  89. cta_pbkdf2_sha1 = "passlib.handlers.pbkdf2",
  90. crypt16 = "passlib.handlers.des_crypt",
  91. des_crypt = "passlib.handlers.des_crypt",
  92. django_argon2 = "passlib.handlers.django",
  93. django_bcrypt = "passlib.handlers.django",
  94. django_bcrypt_sha256 = "passlib.handlers.django",
  95. django_pbkdf2_sha256 = "passlib.handlers.django",
  96. django_pbkdf2_sha1 = "passlib.handlers.django",
  97. django_salted_sha1 = "passlib.handlers.django",
  98. django_salted_md5 = "passlib.handlers.django",
  99. django_des_crypt = "passlib.handlers.django",
  100. django_disabled = "passlib.handlers.django",
  101. dlitz_pbkdf2_sha1 = "passlib.handlers.pbkdf2",
  102. fshp = "passlib.handlers.fshp",
  103. grub_pbkdf2_sha512 = "passlib.handlers.pbkdf2",
  104. hex_md4 = "passlib.handlers.digests",
  105. hex_md5 = "passlib.handlers.digests",
  106. hex_sha1 = "passlib.handlers.digests",
  107. hex_sha256 = "passlib.handlers.digests",
  108. hex_sha512 = "passlib.handlers.digests",
  109. htdigest = "passlib.handlers.digests",
  110. ldap_plaintext = "passlib.handlers.ldap_digests",
  111. ldap_md5 = "passlib.handlers.ldap_digests",
  112. ldap_sha1 = "passlib.handlers.ldap_digests",
  113. ldap_hex_md5 = "passlib.handlers.roundup",
  114. ldap_hex_sha1 = "passlib.handlers.roundup",
  115. ldap_salted_md5 = "passlib.handlers.ldap_digests",
  116. ldap_salted_sha1 = "passlib.handlers.ldap_digests",
  117. ldap_des_crypt = "passlib.handlers.ldap_digests",
  118. ldap_bsdi_crypt = "passlib.handlers.ldap_digests",
  119. ldap_md5_crypt = "passlib.handlers.ldap_digests",
  120. ldap_bcrypt = "passlib.handlers.ldap_digests",
  121. ldap_sha1_crypt = "passlib.handlers.ldap_digests",
  122. ldap_sha256_crypt = "passlib.handlers.ldap_digests",
  123. ldap_sha512_crypt = "passlib.handlers.ldap_digests",
  124. ldap_pbkdf2_sha1 = "passlib.handlers.pbkdf2",
  125. ldap_pbkdf2_sha256 = "passlib.handlers.pbkdf2",
  126. ldap_pbkdf2_sha512 = "passlib.handlers.pbkdf2",
  127. lmhash = "passlib.handlers.windows",
  128. md5_crypt = "passlib.handlers.md5_crypt",
  129. msdcc = "passlib.handlers.windows",
  130. msdcc2 = "passlib.handlers.windows",
  131. mssql2000 = "passlib.handlers.mssql",
  132. mssql2005 = "passlib.handlers.mssql",
  133. mysql323 = "passlib.handlers.mysql",
  134. mysql41 = "passlib.handlers.mysql",
  135. nthash = "passlib.handlers.windows",
  136. oracle10 = "passlib.handlers.oracle",
  137. oracle11 = "passlib.handlers.oracle",
  138. pbkdf2_sha1 = "passlib.handlers.pbkdf2",
  139. pbkdf2_sha256 = "passlib.handlers.pbkdf2",
  140. pbkdf2_sha512 = "passlib.handlers.pbkdf2",
  141. phpass = "passlib.handlers.phpass",
  142. plaintext = "passlib.handlers.misc",
  143. postgres_md5 = "passlib.handlers.postgres",
  144. roundup_plaintext = "passlib.handlers.roundup",
  145. scram = "passlib.handlers.scram",
  146. scrypt = "passlib.handlers.scrypt",
  147. sha1_crypt = "passlib.handlers.sha1_crypt",
  148. sha256_crypt = "passlib.handlers.sha2_crypt",
  149. sha512_crypt = "passlib.handlers.sha2_crypt",
  150. sun_md5_crypt = "passlib.handlers.sun_md5_crypt",
  151. unix_disabled = "passlib.handlers.misc",
  152. unix_fallback = "passlib.handlers.misc",
  153. )
  154. # master regexp for detecting valid handler names
  155. _name_re = re.compile("^[a-z][a-z0-9_]+[a-z0-9]$")
  156. # names which aren't allowed for various reasons
  157. # (mainly keyword conflicts in CryptContext)
  158. _forbidden_names = frozenset(["onload", "policy", "context", "all",
  159. "default", "none", "auto"])
  160. #=============================================================================
  161. # registry frontend functions
  162. #=============================================================================
  163. def _validate_handler_name(name):
  164. """helper to validate handler name
  165. :raises ValueError:
  166. * if empty name
  167. * if name not lower case
  168. * if name contains double underscores
  169. * if name is reserved (e.g. ``context``, ``all``).
  170. """
  171. if not name:
  172. raise ValueError("handler name cannot be empty: %r" % (name,))
  173. if name.lower() != name:
  174. raise ValueError("name must be lower-case: %r" % (name,))
  175. if not _name_re.match(name):
  176. raise ValueError("invalid name (must be 3+ characters, "
  177. " begin with a-z, and contain only underscore, a-z, "
  178. "0-9): %r" % (name,))
  179. if '__' in name:
  180. raise ValueError("name may not contain double-underscores: %r" %
  181. (name,))
  182. if name in _forbidden_names:
  183. raise ValueError("that name is not allowed: %r" % (name,))
  184. return True
  185. def register_crypt_handler_path(name, path):
  186. """register location to lazy-load handler when requested.
  187. custom hashes may be registered via :func:`register_crypt_handler`,
  188. or they may be registered by this function,
  189. which will delay actually importing and loading the handler
  190. until a call to :func:`get_crypt_handler` is made for the specified name.
  191. :arg name: name of handler
  192. :arg path: module import path
  193. the specified module path should contain a password hash handler
  194. called :samp:`{name}`, or the path may contain a colon,
  195. specifying the module and module attribute to use.
  196. for example, the following would cause ``get_handler("myhash")`` to look
  197. for a class named ``myhash`` within the ``myapp.helpers`` module::
  198. >>> from passlib.registry import registry_crypt_handler_path
  199. >>> registry_crypt_handler_path("myhash", "myapp.helpers")
  200. ...while this form would cause ``get_handler("myhash")`` to look
  201. for a class name ``MyHash`` within the ``myapp.helpers`` module::
  202. >>> from passlib.registry import registry_crypt_handler_path
  203. >>> registry_crypt_handler_path("myhash", "myapp.helpers:MyHash")
  204. """
  205. # validate name
  206. _validate_handler_name(name)
  207. # validate path
  208. if path.startswith("."):
  209. raise ValueError("path cannot start with '.'")
  210. if ':' in path:
  211. if path.count(':') > 1:
  212. raise ValueError("path cannot have more than one ':'")
  213. if path.find('.', path.index(':')) > -1:
  214. raise ValueError("path cannot have '.' to right of ':'")
  215. # store location
  216. _locations[name] = path
  217. log.debug("registered path to %r handler: %r", name, path)
  218. def register_crypt_handler(handler, force=False, _attr=None):
  219. """register password hash handler.
  220. this method immediately registers a handler with the internal passlib registry,
  221. so that it will be returned by :func:`get_crypt_handler` when requested.
  222. :arg handler: the password hash handler to register
  223. :param force: force override of existing handler (defaults to False)
  224. :param _attr:
  225. [internal kwd] if specified, ensures ``handler.name``
  226. matches this value, or raises :exc:`ValueError`.
  227. :raises TypeError:
  228. if the specified object does not appear to be a valid handler.
  229. :raises ValueError:
  230. if the specified object's name (or other required attributes)
  231. contain invalid values.
  232. :raises KeyError:
  233. if a (different) handler was already registered with
  234. the same name, and ``force=True`` was not specified.
  235. """
  236. # validate handler
  237. if not is_crypt_handler(handler):
  238. raise ExpectedTypeError(handler, "password hash handler", "handler")
  239. if not handler:
  240. raise AssertionError("``bool(handler)`` must be True")
  241. # validate name
  242. name = handler.name
  243. _validate_handler_name(name)
  244. if _attr and _attr != name:
  245. raise ValueError("handlers must be stored only under their own name (%r != %r)" %
  246. (_attr, name))
  247. # check for existing handler
  248. other = _handlers.get(name)
  249. if other:
  250. if other is handler:
  251. log.debug("same %r handler already registered: %r", name, handler)
  252. return
  253. elif force:
  254. log.warning("overriding previously registered %r handler: %r",
  255. name, other)
  256. else:
  257. raise KeyError("another %r handler has already been registered: %r" %
  258. (name, other))
  259. # register handler
  260. _handlers[name] = handler
  261. log.debug("registered %r handler: %r", name, handler)
  262. def get_crypt_handler(name, default=_UNSET):
  263. """return handler for specified password hash scheme.
  264. this method looks up a handler for the specified scheme.
  265. if the handler is not already loaded,
  266. it checks if the location is known, and loads it first.
  267. :arg name: name of handler to return
  268. :param default: optional default value to return if no handler with specified name is found.
  269. :raises KeyError: if no handler matching that name is found, and no default specified, a KeyError will be raised.
  270. :returns: handler attached to name, or default value (if specified).
  271. """
  272. # catch invalid names before we check _handlers,
  273. # since it's a module dict, and exposes things like __package__, etc.
  274. if name.startswith("_"):
  275. if default is _UNSET:
  276. raise KeyError("invalid handler name: %r" % (name,))
  277. else:
  278. return default
  279. # check if handler is already loaded
  280. try:
  281. return _handlers[name]
  282. except KeyError:
  283. pass
  284. # normalize name (and if changed, check dict again)
  285. assert isinstance(name, unicode_or_str), "name must be string instance"
  286. alt = name.replace("-","_").lower()
  287. if alt != name:
  288. warn("handler names should be lower-case, and use underscores instead "
  289. "of hyphens: %r => %r" % (name, alt), PasslibWarning,
  290. stacklevel=2)
  291. name = alt
  292. # try to load using new name
  293. try:
  294. return _handlers[name]
  295. except KeyError:
  296. pass
  297. # check if lazy load mapping has been specified for this driver
  298. path = _locations.get(name)
  299. if path:
  300. if ':' in path:
  301. modname, modattr = path.split(":")
  302. else:
  303. modname, modattr = path, name
  304. ##log.debug("loading %r handler from path: '%s:%s'", name, modname, modattr)
  305. # try to load the module - any import errors indicate runtime config, usually
  306. # either missing package, or bad path provided to register_crypt_handler_path()
  307. mod = __import__(modname, fromlist=[modattr], level=0)
  308. # first check if importing module triggered register_crypt_handler(),
  309. # (this is discouraged due to its magical implicitness)
  310. handler = _handlers.get(name)
  311. if handler:
  312. # XXX: issue deprecation warning here?
  313. assert is_crypt_handler(handler), "unexpected object: name=%r object=%r" % (name, handler)
  314. return handler
  315. # then get real handler & register it
  316. handler = getattr(mod, modattr)
  317. register_crypt_handler(handler, _attr=name)
  318. return handler
  319. # fail!
  320. if default is _UNSET:
  321. raise KeyError("no crypt handler found for algorithm: %r" % (name,))
  322. else:
  323. return default
  324. def list_crypt_handlers(loaded_only=False):
  325. """return sorted list of all known crypt handler names.
  326. :param loaded_only: if ``True``, only returns names of handlers which have actually been loaded.
  327. :returns: list of names of all known handlers
  328. """
  329. names = set(_handlers)
  330. if not loaded_only:
  331. names.update(_locations)
  332. # strip private attrs out of namespace and sort.
  333. # TODO: make _handlers a separate list, so we don't have module namespace mixed in.
  334. return sorted(name for name in names if not name.startswith("_"))
  335. # NOTE: these two functions mainly exist just for the unittests...
  336. def _has_crypt_handler(name, loaded_only=False):
  337. """check if handler name is known.
  338. this is only useful for two cases:
  339. * quickly checking if handler has already been loaded
  340. * checking if handler exists, without actually loading it
  341. :arg name: name of handler
  342. :param loaded_only: if ``True``, returns False if handler exists but hasn't been loaded
  343. """
  344. return (name in _handlers) or (not loaded_only and name in _locations)
  345. def _unload_handler_name(name, locations=True):
  346. """unloads a handler from the registry.
  347. .. warning::
  348. this is an internal function,
  349. used only by the unittests.
  350. if loaded handler is found with specified name, it's removed.
  351. if path to lazy load handler is found, it's removed.
  352. missing names are a noop.
  353. :arg name: name of handler to unload
  354. :param locations: if False, won't purge registered handler locations (default True)
  355. """
  356. if name in _handlers:
  357. del _handlers[name]
  358. if locations and name in _locations:
  359. del _locations[name]
  360. #=============================================================================
  361. # inspection helpers
  362. #=============================================================================
  363. #------------------------------------------------------------------
  364. # general
  365. #------------------------------------------------------------------
  366. # TODO: needs UTs
  367. def _resolve(hasher, param="value"):
  368. """
  369. internal helper to resolve argument to hasher object
  370. """
  371. if is_crypt_handler(hasher):
  372. return hasher
  373. elif isinstance(hasher, unicode_or_str):
  374. return get_crypt_handler(hasher)
  375. else:
  376. raise exc.ExpectedTypeError(hasher, unicode_or_str, param)
  377. #: backend aliases
  378. ANY = "any"
  379. BUILTIN = "builtin"
  380. OS_CRYPT = "os_crypt"
  381. # TODO: needs UTs
  382. def has_backend(hasher, backend=ANY, safe=False):
  383. """
  384. Test if specified backend is available for hasher.
  385. :param hasher:
  386. Hasher name or object.
  387. :param backend:
  388. Name of backend, or ``"any"`` if any backend will do.
  389. For hashers without multiple backends, will pretend
  390. they have a single backend named ``"builtin"``.
  391. :param safe:
  392. By default, throws error if backend is unknown.
  393. If ``safe=True``, will just return false value.
  394. :raises ValueError:
  395. * if hasher name is unknown.
  396. * if backend is unknown to hasher, and safe=False.
  397. :return:
  398. True if backend available, False if not available,
  399. and None if unknown + safe=True.
  400. """
  401. hasher = _resolve(hasher)
  402. if backend == ANY:
  403. if not hasattr(hasher, "get_backend"):
  404. # single backend, assume it's loaded
  405. return True
  406. # multiple backends, check at least one is loadable
  407. try:
  408. hasher.get_backend()
  409. return True
  410. except exc.MissingBackendError:
  411. return False
  412. # test for specific backend
  413. if hasattr(hasher, "has_backend"):
  414. # multiple backends
  415. if safe and backend not in hasher.backends:
  416. return None
  417. return hasher.has_backend(backend)
  418. # single builtin backend
  419. if backend == BUILTIN:
  420. return True
  421. elif safe:
  422. return None
  423. else:
  424. raise exc.UnknownBackendError(hasher, backend)
  425. #------------------------------------------------------------------
  426. # os crypt
  427. #------------------------------------------------------------------
  428. # TODO: move unix_crypt_schemes list to here.
  429. # os_crypt_schemes -- alias for unix_crypt_schemes above
  430. # TODO: needs UTs
  431. @memoize_single_value
  432. def get_supported_os_crypt_schemes():
  433. """
  434. return tuple of schemes which :func:`crypt.crypt` natively supports.
  435. """
  436. if not os_crypt_present:
  437. return ()
  438. cache = tuple(name for name in os_crypt_schemes
  439. if get_crypt_handler(name).has_backend(OS_CRYPT))
  440. if not cache: # pragma: no cover -- sanity check
  441. # no idea what OS this could happen on...
  442. warn("crypt.crypt() function is present, but doesn't support any "
  443. "formats known to passlib!", exc.PasslibRuntimeWarning)
  444. return cache
  445. # TODO: needs UTs
  446. def has_os_crypt_support(hasher):
  447. """
  448. check if hash is supported by native :func:`crypt.crypt` function.
  449. if :func:`crypt.crypt` is not present, will always return False.
  450. :param hasher:
  451. name or hasher object.
  452. :returns bool:
  453. True if hash format is supported by OS, else False.
  454. """
  455. return os_crypt_present and has_backend(hasher, OS_CRYPT, safe=True)
  456. #=============================================================================
  457. # eof
  458. #=============================================================================