Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 
 

548 linhas
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_salted_sha256 = "passlib.handlers.ldap_digests",
  118. ldap_salted_sha512 = "passlib.handlers.ldap_digests",
  119. ldap_des_crypt = "passlib.handlers.ldap_digests",
  120. ldap_bsdi_crypt = "passlib.handlers.ldap_digests",
  121. ldap_md5_crypt = "passlib.handlers.ldap_digests",
  122. ldap_bcrypt = "passlib.handlers.ldap_digests",
  123. ldap_sha1_crypt = "passlib.handlers.ldap_digests",
  124. ldap_sha256_crypt = "passlib.handlers.ldap_digests",
  125. ldap_sha512_crypt = "passlib.handlers.ldap_digests",
  126. ldap_pbkdf2_sha1 = "passlib.handlers.pbkdf2",
  127. ldap_pbkdf2_sha256 = "passlib.handlers.pbkdf2",
  128. ldap_pbkdf2_sha512 = "passlib.handlers.pbkdf2",
  129. lmhash = "passlib.handlers.windows",
  130. md5_crypt = "passlib.handlers.md5_crypt",
  131. msdcc = "passlib.handlers.windows",
  132. msdcc2 = "passlib.handlers.windows",
  133. mssql2000 = "passlib.handlers.mssql",
  134. mssql2005 = "passlib.handlers.mssql",
  135. mysql323 = "passlib.handlers.mysql",
  136. mysql41 = "passlib.handlers.mysql",
  137. nthash = "passlib.handlers.windows",
  138. oracle10 = "passlib.handlers.oracle",
  139. oracle11 = "passlib.handlers.oracle",
  140. pbkdf2_sha1 = "passlib.handlers.pbkdf2",
  141. pbkdf2_sha256 = "passlib.handlers.pbkdf2",
  142. pbkdf2_sha512 = "passlib.handlers.pbkdf2",
  143. phpass = "passlib.handlers.phpass",
  144. plaintext = "passlib.handlers.misc",
  145. postgres_md5 = "passlib.handlers.postgres",
  146. roundup_plaintext = "passlib.handlers.roundup",
  147. scram = "passlib.handlers.scram",
  148. scrypt = "passlib.handlers.scrypt",
  149. sha1_crypt = "passlib.handlers.sha1_crypt",
  150. sha256_crypt = "passlib.handlers.sha2_crypt",
  151. sha512_crypt = "passlib.handlers.sha2_crypt",
  152. sun_md5_crypt = "passlib.handlers.sun_md5_crypt",
  153. unix_disabled = "passlib.handlers.misc",
  154. unix_fallback = "passlib.handlers.misc",
  155. )
  156. # master regexp for detecting valid handler names
  157. _name_re = re.compile("^[a-z][a-z0-9_]+[a-z0-9]$")
  158. # names which aren't allowed for various reasons
  159. # (mainly keyword conflicts in CryptContext)
  160. _forbidden_names = frozenset(["onload", "policy", "context", "all",
  161. "default", "none", "auto"])
  162. #=============================================================================
  163. # registry frontend functions
  164. #=============================================================================
  165. def _validate_handler_name(name):
  166. """helper to validate handler name
  167. :raises ValueError:
  168. * if empty name
  169. * if name not lower case
  170. * if name contains double underscores
  171. * if name is reserved (e.g. ``context``, ``all``).
  172. """
  173. if not name:
  174. raise ValueError("handler name cannot be empty: %r" % (name,))
  175. if name.lower() != name:
  176. raise ValueError("name must be lower-case: %r" % (name,))
  177. if not _name_re.match(name):
  178. raise ValueError("invalid name (must be 3+ characters, "
  179. " begin with a-z, and contain only underscore, a-z, "
  180. "0-9): %r" % (name,))
  181. if '__' in name:
  182. raise ValueError("name may not contain double-underscores: %r" %
  183. (name,))
  184. if name in _forbidden_names:
  185. raise ValueError("that name is not allowed: %r" % (name,))
  186. return True
  187. def register_crypt_handler_path(name, path):
  188. """register location to lazy-load handler when requested.
  189. custom hashes may be registered via :func:`register_crypt_handler`,
  190. or they may be registered by this function,
  191. which will delay actually importing and loading the handler
  192. until a call to :func:`get_crypt_handler` is made for the specified name.
  193. :arg name: name of handler
  194. :arg path: module import path
  195. the specified module path should contain a password hash handler
  196. called :samp:`{name}`, or the path may contain a colon,
  197. specifying the module and module attribute to use.
  198. for example, the following would cause ``get_handler("myhash")`` to look
  199. for a class named ``myhash`` within the ``myapp.helpers`` module::
  200. >>> from passlib.registry import registry_crypt_handler_path
  201. >>> registry_crypt_handler_path("myhash", "myapp.helpers")
  202. ...while this form would cause ``get_handler("myhash")`` to look
  203. for a class name ``MyHash`` within the ``myapp.helpers`` module::
  204. >>> from passlib.registry import registry_crypt_handler_path
  205. >>> registry_crypt_handler_path("myhash", "myapp.helpers:MyHash")
  206. """
  207. # validate name
  208. _validate_handler_name(name)
  209. # validate path
  210. if path.startswith("."):
  211. raise ValueError("path cannot start with '.'")
  212. if ':' in path:
  213. if path.count(':') > 1:
  214. raise ValueError("path cannot have more than one ':'")
  215. if path.find('.', path.index(':')) > -1:
  216. raise ValueError("path cannot have '.' to right of ':'")
  217. # store location
  218. _locations[name] = path
  219. log.debug("registered path to %r handler: %r", name, path)
  220. def register_crypt_handler(handler, force=False, _attr=None):
  221. """register password hash handler.
  222. this method immediately registers a handler with the internal passlib registry,
  223. so that it will be returned by :func:`get_crypt_handler` when requested.
  224. :arg handler: the password hash handler to register
  225. :param force: force override of existing handler (defaults to False)
  226. :param _attr:
  227. [internal kwd] if specified, ensures ``handler.name``
  228. matches this value, or raises :exc:`ValueError`.
  229. :raises TypeError:
  230. if the specified object does not appear to be a valid handler.
  231. :raises ValueError:
  232. if the specified object's name (or other required attributes)
  233. contain invalid values.
  234. :raises KeyError:
  235. if a (different) handler was already registered with
  236. the same name, and ``force=True`` was not specified.
  237. """
  238. # validate handler
  239. if not is_crypt_handler(handler):
  240. raise ExpectedTypeError(handler, "password hash handler", "handler")
  241. if not handler:
  242. raise AssertionError("``bool(handler)`` must be True")
  243. # validate name
  244. name = handler.name
  245. _validate_handler_name(name)
  246. if _attr and _attr != name:
  247. raise ValueError("handlers must be stored only under their own name (%r != %r)" %
  248. (_attr, name))
  249. # check for existing handler
  250. other = _handlers.get(name)
  251. if other:
  252. if other is handler:
  253. log.debug("same %r handler already registered: %r", name, handler)
  254. return
  255. elif force:
  256. log.warning("overriding previously registered %r handler: %r",
  257. name, other)
  258. else:
  259. raise KeyError("another %r handler has already been registered: %r" %
  260. (name, other))
  261. # register handler
  262. _handlers[name] = handler
  263. log.debug("registered %r handler: %r", name, handler)
  264. def get_crypt_handler(name, default=_UNSET):
  265. """return handler for specified password hash scheme.
  266. this method looks up a handler for the specified scheme.
  267. if the handler is not already loaded,
  268. it checks if the location is known, and loads it first.
  269. :arg name: name of handler to return
  270. :param default: optional default value to return if no handler with specified name is found.
  271. :raises KeyError: if no handler matching that name is found, and no default specified, a KeyError will be raised.
  272. :returns: handler attached to name, or default value (if specified).
  273. """
  274. # catch invalid names before we check _handlers,
  275. # since it's a module dict, and exposes things like __package__, etc.
  276. if name.startswith("_"):
  277. if default is _UNSET:
  278. raise KeyError("invalid handler name: %r" % (name,))
  279. else:
  280. return default
  281. # check if handler is already loaded
  282. try:
  283. return _handlers[name]
  284. except KeyError:
  285. pass
  286. # normalize name (and if changed, check dict again)
  287. assert isinstance(name, unicode_or_str), "name must be string instance"
  288. alt = name.replace("-","_").lower()
  289. if alt != name:
  290. warn("handler names should be lower-case, and use underscores instead "
  291. "of hyphens: %r => %r" % (name, alt), PasslibWarning,
  292. stacklevel=2)
  293. name = alt
  294. # try to load using new name
  295. try:
  296. return _handlers[name]
  297. except KeyError:
  298. pass
  299. # check if lazy load mapping has been specified for this driver
  300. path = _locations.get(name)
  301. if path:
  302. if ':' in path:
  303. modname, modattr = path.split(":")
  304. else:
  305. modname, modattr = path, name
  306. ##log.debug("loading %r handler from path: '%s:%s'", name, modname, modattr)
  307. # try to load the module - any import errors indicate runtime config, usually
  308. # either missing package, or bad path provided to register_crypt_handler_path()
  309. mod = __import__(modname, fromlist=[modattr], level=0)
  310. # first check if importing module triggered register_crypt_handler(),
  311. # (this is discouraged due to its magical implicitness)
  312. handler = _handlers.get(name)
  313. if handler:
  314. # XXX: issue deprecation warning here?
  315. assert is_crypt_handler(handler), "unexpected object: name=%r object=%r" % (name, handler)
  316. return handler
  317. # then get real handler & register it
  318. handler = getattr(mod, modattr)
  319. register_crypt_handler(handler, _attr=name)
  320. return handler
  321. # fail!
  322. if default is _UNSET:
  323. raise KeyError("no crypt handler found for algorithm: %r" % (name,))
  324. else:
  325. return default
  326. def list_crypt_handlers(loaded_only=False):
  327. """return sorted list of all known crypt handler names.
  328. :param loaded_only: if ``True``, only returns names of handlers which have actually been loaded.
  329. :returns: list of names of all known handlers
  330. """
  331. names = set(_handlers)
  332. if not loaded_only:
  333. names.update(_locations)
  334. # strip private attrs out of namespace and sort.
  335. # TODO: make _handlers a separate list, so we don't have module namespace mixed in.
  336. return sorted(name for name in names if not name.startswith("_"))
  337. # NOTE: these two functions mainly exist just for the unittests...
  338. def _has_crypt_handler(name, loaded_only=False):
  339. """check if handler name is known.
  340. this is only useful for two cases:
  341. * quickly checking if handler has already been loaded
  342. * checking if handler exists, without actually loading it
  343. :arg name: name of handler
  344. :param loaded_only: if ``True``, returns False if handler exists but hasn't been loaded
  345. """
  346. return (name in _handlers) or (not loaded_only and name in _locations)
  347. def _unload_handler_name(name, locations=True):
  348. """unloads a handler from the registry.
  349. .. warning::
  350. this is an internal function,
  351. used only by the unittests.
  352. if loaded handler is found with specified name, it's removed.
  353. if path to lazy load handler is found, it's removed.
  354. missing names are a noop.
  355. :arg name: name of handler to unload
  356. :param locations: if False, won't purge registered handler locations (default True)
  357. """
  358. if name in _handlers:
  359. del _handlers[name]
  360. if locations and name in _locations:
  361. del _locations[name]
  362. #=============================================================================
  363. # inspection helpers
  364. #=============================================================================
  365. #------------------------------------------------------------------
  366. # general
  367. #------------------------------------------------------------------
  368. # TODO: needs UTs
  369. def _resolve(hasher, param="value"):
  370. """
  371. internal helper to resolve argument to hasher object
  372. """
  373. if is_crypt_handler(hasher):
  374. return hasher
  375. elif isinstance(hasher, unicode_or_str):
  376. return get_crypt_handler(hasher)
  377. else:
  378. raise exc.ExpectedTypeError(hasher, unicode_or_str, param)
  379. #: backend aliases
  380. ANY = "any"
  381. BUILTIN = "builtin"
  382. OS_CRYPT = "os_crypt"
  383. # TODO: needs UTs
  384. def has_backend(hasher, backend=ANY, safe=False):
  385. """
  386. Test if specified backend is available for hasher.
  387. :param hasher:
  388. Hasher name or object.
  389. :param backend:
  390. Name of backend, or ``"any"`` if any backend will do.
  391. For hashers without multiple backends, will pretend
  392. they have a single backend named ``"builtin"``.
  393. :param safe:
  394. By default, throws error if backend is unknown.
  395. If ``safe=True``, will just return false value.
  396. :raises ValueError:
  397. * if hasher name is unknown.
  398. * if backend is unknown to hasher, and safe=False.
  399. :return:
  400. True if backend available, False if not available,
  401. and None if unknown + safe=True.
  402. """
  403. hasher = _resolve(hasher)
  404. if backend == ANY:
  405. if not hasattr(hasher, "get_backend"):
  406. # single backend, assume it's loaded
  407. return True
  408. # multiple backends, check at least one is loadable
  409. try:
  410. hasher.get_backend()
  411. return True
  412. except exc.MissingBackendError:
  413. return False
  414. # test for specific backend
  415. if hasattr(hasher, "has_backend"):
  416. # multiple backends
  417. if safe and backend not in hasher.backends:
  418. return None
  419. return hasher.has_backend(backend)
  420. # single builtin backend
  421. if backend == BUILTIN:
  422. return True
  423. elif safe:
  424. return None
  425. else:
  426. raise exc.UnknownBackendError(hasher, backend)
  427. #------------------------------------------------------------------
  428. # os crypt
  429. #------------------------------------------------------------------
  430. # TODO: move unix_crypt_schemes list to here.
  431. # os_crypt_schemes -- alias for unix_crypt_schemes above
  432. # TODO: needs UTs
  433. @memoize_single_value
  434. def get_supported_os_crypt_schemes():
  435. """
  436. return tuple of schemes which :func:`crypt.crypt` natively supports.
  437. """
  438. if not os_crypt_present:
  439. return ()
  440. cache = tuple(name for name in os_crypt_schemes
  441. if get_crypt_handler(name).has_backend(OS_CRYPT))
  442. if not cache: # pragma: no cover -- sanity check
  443. # no idea what OS this could happen on...
  444. import platform
  445. warn("crypt.crypt() function is present, but doesn't support any "
  446. "formats known to passlib! (system=%r release=%r)" %
  447. (platform.system(), platform.release()),
  448. exc.PasslibRuntimeWarning)
  449. return cache
  450. # TODO: needs UTs
  451. def has_os_crypt_support(hasher):
  452. """
  453. check if hash is supported by native :func:`crypt.crypt` function.
  454. if :func:`crypt.crypt` is not present, will always return False.
  455. :param hasher:
  456. name or hasher object.
  457. :returns bool:
  458. True if hash format is supported by OS, else False.
  459. """
  460. return os_crypt_present and has_backend(hasher, OS_CRYPT, safe=True)
  461. #=============================================================================
  462. # eof
  463. #=============================================================================