Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.
 
 
 
 

312 rindas
11 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. class MissingBackendError(RuntimeError):
  17. """Error raised if multi-backend handler has no available backends;
  18. or if specifically requested backend is not available.
  19. :exc:`!MissingBackendError` derives
  20. from :exc:`RuntimeError`, since it usually indicates
  21. lack of an external library or OS feature.
  22. This is primarily raised by handlers which depend on
  23. external libraries (which is currently just
  24. :class:`~passlib.hash.bcrypt`).
  25. """
  26. class PasswordSizeError(ValueError):
  27. """
  28. Error raised if a password exceeds the maximum size allowed
  29. by Passlib (by default, 4096 characters); or if password exceeds
  30. a hash-specific size limitation.
  31. Many password hash algorithms take proportionately larger amounts of time and/or
  32. memory depending on the size of the password provided. This could present
  33. a potential denial of service (DOS) situation if a maliciously large
  34. password is provided to an application. Because of this, Passlib enforces
  35. a maximum size limit, but one which should be *much* larger
  36. than any legitimate password. :exc:`!PasswordSizeError` derives
  37. from :exc:`!ValueError`.
  38. .. note::
  39. Applications wishing to use a different limit should set the
  40. ``PASSLIB_MAX_PASSWORD_SIZE`` environmental variable before
  41. Passlib is loaded. The value can be any large positive integer.
  42. .. attribute:: max_size
  43. indicates the maximum allowed size.
  44. .. versionadded:: 1.6
  45. """
  46. max_size = None
  47. def __init__(self, max_size, msg=None):
  48. self.max_size = max_size
  49. if msg is None:
  50. msg = "password exceeds maximum allowed size"
  51. ValueError.__init__(self, msg)
  52. # this also prevents a glibc crypt segfault issue, detailed here ...
  53. # http://www.openwall.com/lists/oss-security/2011/11/15/1
  54. class PasswordTruncateError(PasswordSizeError):
  55. """
  56. Error raised if password would be truncated by hash.
  57. This derives from :exc:`PasswordSizeError` and :exc:`ValueError`.
  58. Hashers such as :class:`~passlib.hash.bcrypt` can be configured to raises
  59. this error by setting ``truncate_error=True``.
  60. .. attribute:: max_size
  61. indicates the maximum allowed size.
  62. .. versionadded:: 1.7
  63. """
  64. def __init__(self, cls, msg=None):
  65. if msg is None:
  66. msg = ("Password too long (%s truncates to %d characters)" %
  67. (cls.name, cls.truncate_size))
  68. PasswordSizeError.__init__(self, cls.truncate_size, msg)
  69. class PasslibSecurityError(RuntimeError):
  70. """
  71. Error raised if critical security issue is detected
  72. (e.g. an attempt is made to use a vulnerable version of a bcrypt backend).
  73. .. versionadded:: 1.6.3
  74. """
  75. class TokenError(ValueError):
  76. """
  77. Base error raised by v:mod:`passlib.totp` when
  78. a token can't be parsed / isn't valid / etc.
  79. Derives from :exc:`!ValueError`.
  80. Usually one of the more specific subclasses below will be raised:
  81. * :class:`MalformedTokenError` -- invalid chars, too few digits
  82. * :class:`InvalidTokenError` -- no match found
  83. * :class:`UsedTokenError` -- match found, but token already used
  84. .. versionadded:: 1.7
  85. """
  86. #: default message to use if none provided -- subclasses may fill this in
  87. _default_message = 'Token not acceptable'
  88. def __init__(self, msg=None, *args, **kwds):
  89. if msg is None:
  90. msg = self._default_message
  91. ValueError.__init__(self, msg, *args, **kwds)
  92. class MalformedTokenError(TokenError):
  93. """
  94. Error raised by :mod:`passlib.totp` when a token isn't formatted correctly
  95. (contains invalid characters, wrong number of digits, etc)
  96. """
  97. _default_message = "Unrecognized token"
  98. class InvalidTokenError(TokenError):
  99. """
  100. Error raised by :mod:`passlib.totp` when a token is formatted correctly,
  101. but doesn't match any tokens within valid range.
  102. """
  103. _default_message = "Token did not match"
  104. class UsedTokenError(TokenError):
  105. """
  106. Error raised by :mod:`passlib.totp` if a token is reused.
  107. Derives from :exc:`TokenError`.
  108. .. autoattribute:: expire_time
  109. .. versionadded:: 1.7
  110. """
  111. _default_message = "Token has already been used, please wait for another."
  112. #: optional value indicating when current counter period will end,
  113. #: and a new token can be generated.
  114. expire_time = None
  115. def __init__(self, *args, **kwds):
  116. self.expire_time = kwds.pop("expire_time", None)
  117. TokenError.__init__(self, *args, **kwds)
  118. class UnknownHashError(ValueError):
  119. """Error raised by :class:`~passlib.crypto.lookup_hash` if hash name is not recognized.
  120. This exception derives from :exc:`!ValueError`.
  121. .. versionadded:: 1.7
  122. """
  123. def __init__(self, name):
  124. self.name = name
  125. ValueError.__init__(self, "unknown hash algorithm: %r" % name)
  126. #=============================================================================
  127. # warnings
  128. #=============================================================================
  129. class PasslibWarning(UserWarning):
  130. """base class for Passlib's user warnings,
  131. derives from the builtin :exc:`UserWarning`.
  132. .. versionadded:: 1.6
  133. """
  134. # XXX: there's only one reference to this class, and it will go away in 2.0;
  135. # so can probably remove this along with this / roll this into PasslibHashWarning.
  136. class PasslibConfigWarning(PasslibWarning):
  137. """Warning issued when non-fatal issue is found related to the configuration
  138. of a :class:`~passlib.context.CryptContext` instance.
  139. This occurs primarily in one of two cases:
  140. * The CryptContext contains rounds limits which exceed the hard limits
  141. imposed by the underlying algorithm.
  142. * An explicit rounds value was provided which exceeds the limits
  143. imposed by the CryptContext.
  144. In both of these cases, the code will perform correctly & securely;
  145. but the warning is issued as a sign the configuration may need updating.
  146. .. versionadded:: 1.6
  147. """
  148. class PasslibHashWarning(PasslibWarning):
  149. """Warning issued when non-fatal issue is found with parameters
  150. or hash string passed to a passlib hash class.
  151. This occurs primarily in one of two cases:
  152. * A rounds value or other setting was explicitly provided which
  153. exceeded the handler's limits (and has been clamped
  154. by the :ref:`relaxed<relaxed-keyword>` flag).
  155. * A malformed hash string was encountered which (while parsable)
  156. should be re-encoded.
  157. .. versionadded:: 1.6
  158. """
  159. class PasslibRuntimeWarning(PasslibWarning):
  160. """Warning issued when something unexpected happens during runtime.
  161. The fact that it's a warning instead of an error means Passlib
  162. was able to correct for the issue, but that it's anomalous enough
  163. that the developers would love to hear under what conditions it occurred.
  164. .. versionadded:: 1.6
  165. """
  166. class PasslibSecurityWarning(PasslibWarning):
  167. """Special warning issued when Passlib encounters something
  168. that might affect security.
  169. .. versionadded:: 1.6
  170. """
  171. #=============================================================================
  172. # error constructors
  173. #
  174. # note: these functions are used by the hashes in Passlib to raise common
  175. # error messages. They are currently just functions which return ValueError,
  176. # rather than subclasses of ValueError, since the specificity isn't needed
  177. # yet; and who wants to import a bunch of error classes when catching
  178. # ValueError will do?
  179. #=============================================================================
  180. def _get_name(handler):
  181. return handler.name if handler else "<unnamed>"
  182. #------------------------------------------------------------------------
  183. # generic helpers
  184. #------------------------------------------------------------------------
  185. def type_name(value):
  186. """return pretty-printed string containing name of value's type"""
  187. cls = value.__class__
  188. if cls.__module__ and cls.__module__ not in ["__builtin__", "builtins"]:
  189. return "%s.%s" % (cls.__module__, cls.__name__)
  190. elif value is None:
  191. return 'None'
  192. else:
  193. return cls.__name__
  194. def ExpectedTypeError(value, expected, param):
  195. """error message when param was supposed to be one type, but found another"""
  196. # NOTE: value is never displayed, since it may sometimes be a password.
  197. name = type_name(value)
  198. return TypeError("%s must be %s, not %s" % (param, expected, name))
  199. def ExpectedStringError(value, param):
  200. """error message when param was supposed to be unicode or bytes"""
  201. return ExpectedTypeError(value, "unicode or bytes", param)
  202. #------------------------------------------------------------------------
  203. # hash/verify parameter errors
  204. #------------------------------------------------------------------------
  205. def MissingDigestError(handler=None):
  206. """raised when verify() method gets passed config string instead of hash"""
  207. name = _get_name(handler)
  208. return ValueError("expected %s hash, got %s config string instead" %
  209. (name, name))
  210. def NullPasswordError(handler=None):
  211. """raised by OS crypt() supporting hashes, which forbid NULLs in password"""
  212. name = _get_name(handler)
  213. return ValueError("%s does not allow NULL bytes in password" % name)
  214. #------------------------------------------------------------------------
  215. # errors when parsing hashes
  216. #------------------------------------------------------------------------
  217. def InvalidHashError(handler=None):
  218. """error raised if unrecognized hash provided to handler"""
  219. return ValueError("not a valid %s hash" % _get_name(handler))
  220. def MalformedHashError(handler=None, reason=None):
  221. """error raised if recognized-but-malformed hash provided to handler"""
  222. text = "malformed %s hash" % _get_name(handler)
  223. if reason:
  224. text = "%s (%s)" % (text, reason)
  225. return ValueError(text)
  226. def ZeroPaddedRoundsError(handler=None):
  227. """error raised if hash was recognized but contained zero-padded rounds field"""
  228. return MalformedHashError(handler, "zero-padded rounds")
  229. #------------------------------------------------------------------------
  230. # settings / hash component errors
  231. #------------------------------------------------------------------------
  232. def ChecksumSizeError(handler, raw=False):
  233. """error raised if hash was recognized, but checksum was wrong size"""
  234. # TODO: if handler.use_defaults is set, this came from app-provided value,
  235. # not from parsing a hash string, might want different error msg.
  236. checksum_size = handler.checksum_size
  237. unit = "bytes" if raw else "chars"
  238. reason = "checksum must be exactly %d %s" % (checksum_size, unit)
  239. return MalformedHashError(handler, reason)
  240. #=============================================================================
  241. # eof
  242. #=============================================================================