Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.
 
 
 
 

398 Zeilen
14 KiB

  1. """passlib.exc -- exceptions & warnings raised by passlib"""
  2. #=============================================================================
  3. # exceptions
  4. #=============================================================================
  5. class UnknownBackendError(ValueError):
  6. """
  7. Error raised if multi-backend handler doesn't recognize backend name.
  8. Inherits from :exc:`ValueError`.
  9. .. versionadded:: 1.7
  10. """
  11. def __init__(self, hasher, backend):
  12. self.hasher = hasher
  13. self.backend = backend
  14. message = "%s: unknown backend: %r" % (hasher.name, backend)
  15. ValueError.__init__(self, message)
  16. # XXX: add a PasslibRuntimeError as base for Missing/Internal/Security runtime errors?
  17. class MissingBackendError(RuntimeError):
  18. """Error raised if multi-backend handler has no available backends;
  19. or if specifically requested backend is not available.
  20. :exc:`!MissingBackendError` derives
  21. from :exc:`RuntimeError`, since it usually indicates
  22. lack of an external library or OS feature.
  23. This is primarily raised by handlers which depend on
  24. external libraries (which is currently just
  25. :class:`~passlib.hash.bcrypt`).
  26. """
  27. class InternalBackendError(RuntimeError):
  28. """
  29. Error raised if something unrecoverable goes wrong with backend call;
  30. such as if ``crypt.crypt()`` returning a malformed hash.
  31. .. versionadded:: 1.7.3
  32. """
  33. class PasswordValueError(ValueError):
  34. """
  35. Error raised if a password can't be hashed / verified for various reasons.
  36. This exception derives from the builtin :exc:`!ValueError`.
  37. May be thrown directly when password violates internal invariants of hasher
  38. (e.g. some don't support NULL characters). Hashers may also throw more specific subclasses,
  39. such as :exc:`!PasswordSizeError`.
  40. .. versionadded:: 1.7.3
  41. """
  42. pass
  43. class PasswordSizeError(PasswordValueError):
  44. """
  45. Error raised if a password exceeds the maximum size allowed
  46. by Passlib (by default, 4096 characters); or if password exceeds
  47. a hash-specific size limitation.
  48. This exception derives from :exc:`PasswordValueError` (above).
  49. Many password hash algorithms take proportionately larger amounts of time and/or
  50. memory depending on the size of the password provided. This could present
  51. a potential denial of service (DOS) situation if a maliciously large
  52. password is provided to an application. Because of this, Passlib enforces
  53. a maximum size limit, but one which should be *much* larger
  54. than any legitimate password. :exc:`PasswordSizeError` derives
  55. from :exc:`!ValueError`.
  56. .. note::
  57. Applications wishing to use a different limit should set the
  58. ``PASSLIB_MAX_PASSWORD_SIZE`` environmental variable before
  59. Passlib is loaded. The value can be any large positive integer.
  60. .. attribute:: max_size
  61. indicates the maximum allowed size.
  62. .. versionadded:: 1.6
  63. """
  64. max_size = None
  65. def __init__(self, max_size, msg=None):
  66. self.max_size = max_size
  67. if msg is None:
  68. msg = "password exceeds maximum allowed size"
  69. PasswordValueError.__init__(self, msg)
  70. # this also prevents a glibc crypt segfault issue, detailed here ...
  71. # http://www.openwall.com/lists/oss-security/2011/11/15/1
  72. class PasswordTruncateError(PasswordSizeError):
  73. """
  74. Error raised if password would be truncated by hash.
  75. This derives from :exc:`PasswordSizeError` (above).
  76. Hashers such as :class:`~passlib.hash.bcrypt` can be configured to raises
  77. this error by setting ``truncate_error=True``.
  78. .. attribute:: max_size
  79. indicates the maximum allowed size.
  80. .. versionadded:: 1.7
  81. """
  82. def __init__(self, cls, msg=None):
  83. if msg is None:
  84. msg = ("Password too long (%s truncates to %d characters)" %
  85. (cls.name, cls.truncate_size))
  86. PasswordSizeError.__init__(self, cls.truncate_size, msg)
  87. class PasslibSecurityError(RuntimeError):
  88. """
  89. Error raised if critical security issue is detected
  90. (e.g. an attempt is made to use a vulnerable version of a bcrypt backend).
  91. .. versionadded:: 1.6.3
  92. """
  93. class TokenError(ValueError):
  94. """
  95. Base error raised by v:mod:`passlib.totp` when
  96. a token can't be parsed / isn't valid / etc.
  97. Derives from :exc:`!ValueError`.
  98. Usually one of the more specific subclasses below will be raised:
  99. * :class:`MalformedTokenError` -- invalid chars, too few digits
  100. * :class:`InvalidTokenError` -- no match found
  101. * :class:`UsedTokenError` -- match found, but token already used
  102. .. versionadded:: 1.7
  103. """
  104. #: default message to use if none provided -- subclasses may fill this in
  105. _default_message = 'Token not acceptable'
  106. def __init__(self, msg=None, *args, **kwds):
  107. if msg is None:
  108. msg = self._default_message
  109. ValueError.__init__(self, msg, *args, **kwds)
  110. class MalformedTokenError(TokenError):
  111. """
  112. Error raised by :mod:`passlib.totp` when a token isn't formatted correctly
  113. (contains invalid characters, wrong number of digits, etc)
  114. """
  115. _default_message = "Unrecognized token"
  116. class InvalidTokenError(TokenError):
  117. """
  118. Error raised by :mod:`passlib.totp` when a token is formatted correctly,
  119. but doesn't match any tokens within valid range.
  120. """
  121. _default_message = "Token did not match"
  122. class UsedTokenError(TokenError):
  123. """
  124. Error raised by :mod:`passlib.totp` if a token is reused.
  125. Derives from :exc:`TokenError`.
  126. .. autoattribute:: expire_time
  127. .. versionadded:: 1.7
  128. """
  129. _default_message = "Token has already been used, please wait for another."
  130. #: optional value indicating when current counter period will end,
  131. #: and a new token can be generated.
  132. expire_time = None
  133. def __init__(self, *args, **kwds):
  134. self.expire_time = kwds.pop("expire_time", None)
  135. TokenError.__init__(self, *args, **kwds)
  136. class UnknownHashError(ValueError):
  137. """
  138. Error raised by :class:`~passlib.crypto.lookup_hash` if hash name is not recognized.
  139. This exception derives from :exc:`!ValueError`.
  140. As of version 1.7.3, this may also be raised if hash algorithm is known,
  141. but has been disabled due to FIPS mode (message will include phrase "disabled for fips").
  142. As of version 1.7.4, this may be raised if a :class:`~passlib.context.CryptContext`
  143. is unable to identify the algorithm used by a password hash.
  144. .. versionadded:: 1.7
  145. .. versionchanged: 1.7.3
  146. added 'message' argument.
  147. .. versionchanged:: 1.7.4
  148. altered call signature.
  149. """
  150. def __init__(self, message=None, value=None):
  151. self.value = value
  152. if message is None:
  153. message = "unknown hash algorithm: %r" % value
  154. self.message = message
  155. ValueError.__init__(self, message, value)
  156. def __str__(self):
  157. return self.message
  158. #=============================================================================
  159. # warnings
  160. #=============================================================================
  161. class PasslibWarning(UserWarning):
  162. """base class for Passlib's user warnings,
  163. derives from the builtin :exc:`UserWarning`.
  164. .. versionadded:: 1.6
  165. """
  166. # XXX: there's only one reference to this class, and it will go away in 2.0;
  167. # so can probably remove this along with this / roll this into PasslibHashWarning.
  168. class PasslibConfigWarning(PasslibWarning):
  169. """Warning issued when non-fatal issue is found related to the configuration
  170. of a :class:`~passlib.context.CryptContext` instance.
  171. This occurs primarily in one of two cases:
  172. * The CryptContext contains rounds limits which exceed the hard limits
  173. imposed by the underlying algorithm.
  174. * An explicit rounds value was provided which exceeds the limits
  175. imposed by the CryptContext.
  176. In both of these cases, the code will perform correctly & securely;
  177. but the warning is issued as a sign the configuration may need updating.
  178. .. versionadded:: 1.6
  179. """
  180. class PasslibHashWarning(PasslibWarning):
  181. """Warning issued when non-fatal issue is found with parameters
  182. or hash string passed to a passlib hash class.
  183. This occurs primarily in one of two cases:
  184. * A rounds value or other setting was explicitly provided which
  185. exceeded the handler's limits (and has been clamped
  186. by the :ref:`relaxed<relaxed-keyword>` flag).
  187. * A malformed hash string was encountered which (while parsable)
  188. should be re-encoded.
  189. .. versionadded:: 1.6
  190. """
  191. class PasslibRuntimeWarning(PasslibWarning):
  192. """Warning issued when something unexpected happens during runtime.
  193. The fact that it's a warning instead of an error means Passlib
  194. was able to correct for the issue, but that it's anomalous enough
  195. that the developers would love to hear under what conditions it occurred.
  196. .. versionadded:: 1.6
  197. """
  198. class PasslibSecurityWarning(PasslibWarning):
  199. """Special warning issued when Passlib encounters something
  200. that might affect security.
  201. .. versionadded:: 1.6
  202. """
  203. #=============================================================================
  204. # error constructors
  205. #
  206. # note: these functions are used by the hashes in Passlib to raise common
  207. # error messages. They are currently just functions which return ValueError,
  208. # rather than subclasses of ValueError, since the specificity isn't needed
  209. # yet; and who wants to import a bunch of error classes when catching
  210. # ValueError will do?
  211. #=============================================================================
  212. def _get_name(handler):
  213. return handler.name if handler else "<unnamed>"
  214. #------------------------------------------------------------------------
  215. # generic helpers
  216. #------------------------------------------------------------------------
  217. def type_name(value):
  218. """return pretty-printed string containing name of value's type"""
  219. cls = value.__class__
  220. if cls.__module__ and cls.__module__ not in ["__builtin__", "builtins"]:
  221. return "%s.%s" % (cls.__module__, cls.__name__)
  222. elif value is None:
  223. return 'None'
  224. else:
  225. return cls.__name__
  226. def ExpectedTypeError(value, expected, param):
  227. """error message when param was supposed to be one type, but found another"""
  228. # NOTE: value is never displayed, since it may sometimes be a password.
  229. name = type_name(value)
  230. return TypeError("%s must be %s, not %s" % (param, expected, name))
  231. def ExpectedStringError(value, param):
  232. """error message when param was supposed to be unicode or bytes"""
  233. return ExpectedTypeError(value, "unicode or bytes", param)
  234. #------------------------------------------------------------------------
  235. # hash/verify parameter errors
  236. #------------------------------------------------------------------------
  237. def MissingDigestError(handler=None):
  238. """raised when verify() method gets passed config string instead of hash"""
  239. name = _get_name(handler)
  240. return ValueError("expected %s hash, got %s config string instead" %
  241. (name, name))
  242. def NullPasswordError(handler=None):
  243. """raised by OS crypt() supporting hashes, which forbid NULLs in password"""
  244. name = _get_name(handler)
  245. return PasswordValueError("%s does not allow NULL bytes in password" % name)
  246. #------------------------------------------------------------------------
  247. # errors when parsing hashes
  248. #------------------------------------------------------------------------
  249. def InvalidHashError(handler=None):
  250. """error raised if unrecognized hash provided to handler"""
  251. return ValueError("not a valid %s hash" % _get_name(handler))
  252. def MalformedHashError(handler=None, reason=None):
  253. """error raised if recognized-but-malformed hash provided to handler"""
  254. text = "malformed %s hash" % _get_name(handler)
  255. if reason:
  256. text = "%s (%s)" % (text, reason)
  257. return ValueError(text)
  258. def ZeroPaddedRoundsError(handler=None):
  259. """error raised if hash was recognized but contained zero-padded rounds field"""
  260. return MalformedHashError(handler, "zero-padded rounds")
  261. #------------------------------------------------------------------------
  262. # settings / hash component errors
  263. #------------------------------------------------------------------------
  264. def ChecksumSizeError(handler, raw=False):
  265. """error raised if hash was recognized, but checksum was wrong size"""
  266. # TODO: if handler.use_defaults is set, this came from app-provided value,
  267. # not from parsing a hash string, might want different error msg.
  268. checksum_size = handler.checksum_size
  269. unit = "bytes" if raw else "chars"
  270. reason = "checksum must be exactly %d %s" % (checksum_size, unit)
  271. return MalformedHashError(handler, reason)
  272. #=============================================================================
  273. # sensitive info helpers
  274. #=============================================================================
  275. #: global flag, set temporarily by UTs to allow debug_only_repr() to display sensitive values.
  276. ENABLE_DEBUG_ONLY_REPR = False
  277. def debug_only_repr(value, param="hash"):
  278. """
  279. helper used to display sensitive data (hashes etc) within error messages.
  280. currently returns placeholder test UNLESS unittests are running,
  281. in which case the real value is displayed.
  282. mainly useful to prevent hashes / secrets from being exposed in production tracebacks;
  283. while still being visible from test failures.
  284. NOTE: api subject to change, may formalize this more in the future.
  285. """
  286. if ENABLE_DEBUG_ONLY_REPR or value is None or isinstance(value, bool):
  287. return repr(value)
  288. return "<%s %s value omitted>" % (param, type(value))
  289. def CryptBackendError(handler, config, hash, # *
  290. source="crypt.crypt()"):
  291. """
  292. helper to generate standard message when ``crypt.crypt()`` returns invalid result.
  293. takes care of automatically masking contents of config & hash outside of UTs.
  294. """
  295. name = _get_name(handler)
  296. msg = "%s returned invalid %s hash: config=%s hash=%s" % \
  297. (source, name, debug_only_repr(config), debug_only_repr(hash))
  298. raise InternalBackendError(msg)
  299. #=============================================================================
  300. # eof
  301. #=============================================================================