itsdangerous.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873
  1. # -*- coding: utf-8 -*-
  2. """
  3. itsdangerous
  4. ~~~~~~~~~~~~
  5. A module that implements various functions to deal with untrusted
  6. sources. Mainly useful for web applications.
  7. :copyright: (c) 2014 by Armin Ronacher and the Django Software Foundation.
  8. :license: BSD, see LICENSE for more details.
  9. """
  10. import sys
  11. import hmac
  12. import zlib
  13. import time
  14. import base64
  15. import hashlib
  16. import operator
  17. from datetime import datetime
  18. PY2 = sys.version_info[0] == 2
  19. if PY2:
  20. from itertools import izip
  21. text_type = unicode
  22. int_to_byte = chr
  23. number_types = (int, long, float)
  24. else:
  25. from functools import reduce
  26. izip = zip
  27. text_type = str
  28. int_to_byte = operator.methodcaller('to_bytes', 1, 'big')
  29. number_types = (int, float)
  30. try:
  31. import simplejson as json
  32. except ImportError:
  33. import json
  34. class _CompactJSON(object):
  35. """Wrapper around simplejson that strips whitespace.
  36. """
  37. def loads(self, payload):
  38. return json.loads(payload)
  39. def dumps(self, obj):
  40. return json.dumps(obj, separators=(',', ':'))
  41. compact_json = _CompactJSON()
  42. # 2011/01/01 in UTC
  43. EPOCH = 1293840000
  44. def want_bytes(s, encoding='utf-8', errors='strict'):
  45. if isinstance(s, text_type):
  46. s = s.encode(encoding, errors)
  47. return s
  48. def is_text_serializer(serializer):
  49. """Checks wheather a serializer generates text or binary."""
  50. return isinstance(serializer.dumps({}), text_type)
  51. # Starting with 3.3 the standard library has a c-implementation for
  52. # constant time string compares.
  53. _builtin_constant_time_compare = getattr(hmac, 'compare_digest', None)
  54. def constant_time_compare(val1, val2):
  55. """Returns True if the two strings are equal, False otherwise.
  56. The time taken is independent of the number of characters that match. Do
  57. not use this function for anything else than comparision with known
  58. length targets.
  59. This is should be implemented in C in order to get it completely right.
  60. """
  61. if _builtin_constant_time_compare is not None:
  62. return _builtin_constant_time_compare(val1, val2)
  63. len_eq = len(val1) == len(val2)
  64. if len_eq:
  65. result = 0
  66. left = val1
  67. else:
  68. result = 1
  69. left = val2
  70. for x, y in izip(bytearray(left), bytearray(val2)):
  71. result |= x ^ y
  72. return result == 0
  73. class BadData(Exception):
  74. """Raised if bad data of any sort was encountered. This is the
  75. base for all exceptions that itsdangerous is currently using.
  76. .. versionadded:: 0.15
  77. """
  78. message = None
  79. def __init__(self, message):
  80. Exception.__init__(self, message)
  81. self.message = message
  82. def __str__(self):
  83. return text_type(self.message)
  84. if PY2:
  85. __unicode__ = __str__
  86. def __str__(self):
  87. return self.__unicode__().encode('utf-8')
  88. class BadPayload(BadData):
  89. """This error is raised in situations when payload is loaded without
  90. checking the signature first and an exception happend as a result of
  91. that. The original exception that caused that will be stored on the
  92. exception as :attr:`original_error`.
  93. This can also happen with a :class:`JSONWebSignatureSerializer` that
  94. is subclassed and uses a different serializer for the payload than
  95. the expected one.
  96. .. versionadded:: 0.15
  97. """
  98. def __init__(self, message, original_error=None):
  99. BadData.__init__(self, message)
  100. #: If available, the error that indicates why the payload
  101. #: was not valid. This might be `None`.
  102. self.original_error = original_error
  103. class BadSignature(BadData):
  104. """This error is raised if a signature does not match. As of
  105. itsdangerous 0.14 there are helpful attributes on the exception
  106. instances. You can also catch down the baseclass :exc:`BadData`.
  107. """
  108. def __init__(self, message, payload=None):
  109. BadData.__init__(self, message)
  110. #: The payload that failed the signature test. In some
  111. #: situations you might still want to inspect this, even if
  112. #: you know it was tampered with.
  113. #:
  114. #: .. versionadded:: 0.14
  115. self.payload = payload
  116. class BadTimeSignature(BadSignature):
  117. """Raised for time based signatures that fail. This is a subclass
  118. of :class:`BadSignature` so you can catch those down as well.
  119. """
  120. def __init__(self, message, payload=None, date_signed=None):
  121. BadSignature.__init__(self, message, payload)
  122. #: If the signature expired this exposes the date of when the
  123. #: signature was created. This can be helpful in order to
  124. #: tell the user how long a link has been gone stale.
  125. #:
  126. #: .. versionadded:: 0.14
  127. self.date_signed = date_signed
  128. class BadHeader(BadSignature):
  129. """Raised if a signed header is invalid in some form. This only
  130. happens for serializers that have a header that goes with the
  131. signature.
  132. .. versionadded:: 0.24
  133. """
  134. def __init__(self, message, payload=None, header=None,
  135. original_error=None):
  136. BadSignature.__init__(self, message, payload)
  137. #: If the header is actually available but just malformed it
  138. #: might be stored here.
  139. self.header = header
  140. #: If available, the error that indicates why the payload
  141. #: was not valid. This might be `None`.
  142. self.original_error = original_error
  143. class SignatureExpired(BadTimeSignature):
  144. """Signature timestamp is older than required max_age. This is a
  145. subclass of :exc:`BadTimeSignature` so you can use the baseclass for
  146. catching the error.
  147. """
  148. def base64_encode(string):
  149. """base64 encodes a single bytestring (and is tolerant to getting
  150. called with a unicode string).
  151. The resulting bytestring is safe for putting into URLs.
  152. """
  153. string = want_bytes(string)
  154. return base64.urlsafe_b64encode(string).strip(b'=')
  155. def base64_decode(string):
  156. """base64 decodes a single bytestring (and is tolerant to getting
  157. called with a unicode string).
  158. The result is also a bytestring.
  159. """
  160. string = want_bytes(string, encoding='ascii', errors='ignore')
  161. return base64.urlsafe_b64decode(string + b'=' * (-len(string) % 4))
  162. def int_to_bytes(num):
  163. assert num >= 0
  164. rv = []
  165. while num:
  166. rv.append(int_to_byte(num & 0xff))
  167. num >>= 8
  168. return b''.join(reversed(rv))
  169. def bytes_to_int(bytestr):
  170. return reduce(lambda a, b: a << 8 | b, bytearray(bytestr), 0)
  171. class SigningAlgorithm(object):
  172. """Subclasses of `SigningAlgorithm` have to implement `get_signature` to
  173. provide signature generation functionality.
  174. """
  175. def get_signature(self, key, value):
  176. """Returns the signature for the given key and value"""
  177. raise NotImplementedError()
  178. def verify_signature(self, key, value, sig):
  179. """Verifies the given signature matches the expected signature"""
  180. return constant_time_compare(sig, self.get_signature(key, value))
  181. class NoneAlgorithm(SigningAlgorithm):
  182. """This class provides a algorithm that does not perform any signing and
  183. returns an empty signature.
  184. """
  185. def get_signature(self, key, value):
  186. return b''
  187. class HMACAlgorithm(SigningAlgorithm):
  188. """This class provides signature generation using HMACs."""
  189. #: The digest method to use with the MAC algorithm. This defaults to sha1
  190. #: but can be changed for any other function in the hashlib module.
  191. default_digest_method = staticmethod(hashlib.sha1)
  192. def __init__(self, digest_method=None):
  193. if digest_method is None:
  194. digest_method = self.default_digest_method
  195. self.digest_method = digest_method
  196. def get_signature(self, key, value):
  197. mac = hmac.new(key, msg=value, digestmod=self.digest_method)
  198. return mac.digest()
  199. class Signer(object):
  200. """This class can sign bytes and unsign it and validate the signature
  201. provided.
  202. Salt can be used to namespace the hash, so that a signed string is only
  203. valid for a given namespace. Leaving this at the default value or re-using
  204. a salt value across different parts of your application where the same
  205. signed value in one part can mean something different in another part
  206. is a security risk.
  207. See :ref:`the-salt` for an example of what the salt is doing and how you
  208. can utilize it.
  209. .. versionadded:: 0.14
  210. `key_derivation` and `digest_method` were added as arguments to the
  211. class constructor.
  212. .. versionadded:: 0.18
  213. `algorithm` was added as an argument to the class constructor.
  214. """
  215. #: The digest method to use for the signer. This defaults to sha1 but can
  216. #: be changed for any other function in the hashlib module.
  217. #:
  218. #: .. versionchanged:: 0.14
  219. default_digest_method = staticmethod(hashlib.sha1)
  220. #: Controls how the key is derived. The default is Django style
  221. #: concatenation. Possible values are ``concat``, ``django-concat``
  222. #: and ``hmac``. This is used for deriving a key from the secret key
  223. #: with an added salt.
  224. #:
  225. #: .. versionadded:: 0.14
  226. default_key_derivation = 'django-concat'
  227. def __init__(self, secret_key, salt=None, sep='.', key_derivation=None,
  228. digest_method=None, algorithm=None):
  229. self.secret_key = want_bytes(secret_key)
  230. self.sep = sep
  231. self.salt = 'itsdangerous.Signer' if salt is None else salt
  232. if key_derivation is None:
  233. key_derivation = self.default_key_derivation
  234. self.key_derivation = key_derivation
  235. if digest_method is None:
  236. digest_method = self.default_digest_method
  237. self.digest_method = digest_method
  238. if algorithm is None:
  239. algorithm = HMACAlgorithm(self.digest_method)
  240. self.algorithm = algorithm
  241. def derive_key(self):
  242. """This method is called to derive the key. If you're unhappy with
  243. the default key derivation choices you can override them here.
  244. Keep in mind that the key derivation in itsdangerous is not intended
  245. to be used as a security method to make a complex key out of a short
  246. password. Instead you should use large random secret keys.
  247. """
  248. salt = want_bytes(self.salt)
  249. if self.key_derivation == 'concat':
  250. return self.digest_method(salt + self.secret_key).digest()
  251. elif self.key_derivation == 'django-concat':
  252. return self.digest_method(salt + b'signer' +
  253. self.secret_key).digest()
  254. elif self.key_derivation == 'hmac':
  255. mac = hmac.new(self.secret_key, digestmod=self.digest_method)
  256. mac.update(salt)
  257. return mac.digest()
  258. elif self.key_derivation == 'none':
  259. return self.secret_key
  260. else:
  261. raise TypeError('Unknown key derivation method')
  262. def get_signature(self, value):
  263. """Returns the signature for the given value"""
  264. value = want_bytes(value)
  265. key = self.derive_key()
  266. sig = self.algorithm.get_signature(key, value)
  267. return base64_encode(sig)
  268. def sign(self, value):
  269. """Signs the given string."""
  270. return value + want_bytes(self.sep) + self.get_signature(value)
  271. def verify_signature(self, value, sig):
  272. """Verifies the signature for the given value."""
  273. key = self.derive_key()
  274. try:
  275. sig = base64_decode(sig)
  276. except Exception:
  277. return False
  278. return self.algorithm.verify_signature(key, value, sig)
  279. def unsign(self, signed_value):
  280. """Unsigns the given string."""
  281. signed_value = want_bytes(signed_value)
  282. sep = want_bytes(self.sep)
  283. if sep not in signed_value:
  284. raise BadSignature('No %r found in value' % self.sep)
  285. value, sig = signed_value.rsplit(sep, 1)
  286. if self.verify_signature(value, sig):
  287. return value
  288. raise BadSignature('Signature %r does not match' % sig,
  289. payload=value)
  290. def validate(self, signed_value):
  291. """Just validates the given signed value. Returns `True` if the
  292. signature exists and is valid, `False` otherwise."""
  293. try:
  294. self.unsign(signed_value)
  295. return True
  296. except BadSignature:
  297. return False
  298. class TimestampSigner(Signer):
  299. """Works like the regular :class:`Signer` but also records the time
  300. of the signing and can be used to expire signatures. The unsign
  301. method can rause a :exc:`SignatureExpired` method if the unsigning
  302. failed because the signature is expired. This exception is a subclass
  303. of :exc:`BadSignature`.
  304. """
  305. def get_timestamp(self):
  306. """Returns the current timestamp. This implementation returns the
  307. seconds since 1/1/2011. The function must return an integer.
  308. """
  309. return int(time.time() - EPOCH)
  310. def timestamp_to_datetime(self, ts):
  311. """Used to convert the timestamp from `get_timestamp` into a
  312. datetime object.
  313. """
  314. return datetime.utcfromtimestamp(ts + EPOCH)
  315. def sign(self, value):
  316. """Signs the given string and also attaches a time information."""
  317. value = want_bytes(value)
  318. timestamp = base64_encode(int_to_bytes(self.get_timestamp()))
  319. sep = want_bytes(self.sep)
  320. value = value + sep + timestamp
  321. return value + sep + self.get_signature(value)
  322. def unsign(self, value, max_age=None, return_timestamp=False):
  323. """Works like the regular :meth:`~Signer.unsign` but can also
  324. validate the time. See the base docstring of the class for
  325. the general behavior. If `return_timestamp` is set to `True`
  326. the timestamp of the signature will be returned as naive
  327. :class:`datetime.datetime` object in UTC.
  328. """
  329. try:
  330. result = Signer.unsign(self, value)
  331. sig_error = None
  332. except BadSignature as e:
  333. sig_error = e
  334. result = e.payload or b''
  335. sep = want_bytes(self.sep)
  336. # If there is no timestamp in the result there is something
  337. # seriously wrong. In case there was a signature error, we raise
  338. # that one directly, otherwise we have a weird situation in which
  339. # we shouldn't have come except someone uses a time-based serializer
  340. # on non-timestamp data, so catch that.
  341. if not sep in result:
  342. if sig_error:
  343. raise sig_error
  344. raise BadTimeSignature('timestamp missing', payload=result)
  345. value, timestamp = result.rsplit(sep, 1)
  346. try:
  347. timestamp = bytes_to_int(base64_decode(timestamp))
  348. except Exception:
  349. timestamp = None
  350. # Signature is *not* okay. Raise a proper error now that we have
  351. # split the value and the timestamp.
  352. if sig_error is not None:
  353. raise BadTimeSignature(text_type(sig_error), payload=value,
  354. date_signed=timestamp)
  355. # Signature was okay but the timestamp is actually not there or
  356. # malformed. Should not happen, but well. We handle it nonetheless
  357. if timestamp is None:
  358. raise BadTimeSignature('Malformed timestamp', payload=value)
  359. # Check timestamp is not older than max_age
  360. if max_age is not None:
  361. age = self.get_timestamp() - timestamp
  362. if age > max_age:
  363. raise SignatureExpired(
  364. 'Signature age %s > %s seconds' % (age, max_age),
  365. payload=value,
  366. date_signed=self.timestamp_to_datetime(timestamp))
  367. if return_timestamp:
  368. return value, self.timestamp_to_datetime(timestamp)
  369. return value
  370. def validate(self, signed_value, max_age=None):
  371. """Just validates the given signed value. Returns `True` if the
  372. signature exists and is valid, `False` otherwise."""
  373. try:
  374. self.unsign(signed_value, max_age=max_age)
  375. return True
  376. except BadSignature:
  377. return False
  378. class Serializer(object):
  379. """This class provides a serialization interface on top of the
  380. signer. It provides a similar API to json/pickle and other modules but is
  381. slightly differently structured internally. If you want to change the
  382. underlying implementation for parsing and loading you have to override the
  383. :meth:`load_payload` and :meth:`dump_payload` functions.
  384. This implementation uses simplejson if available for dumping and loading
  385. and will fall back to the standard library's json module if it's not
  386. available.
  387. Starting with 0.14 you do not need to subclass this class in order to
  388. switch out or customer the :class:`Signer`. You can instead also pass a
  389. different class to the constructor as well as keyword arguments as
  390. dictionary that should be forwarded::
  391. s = Serializer(signer_kwargs={'key_derivation': 'hmac'})
  392. .. versionchanged:: 0.14:
  393. The `signer` and `signer_kwargs` parameters were added to the
  394. constructor.
  395. """
  396. #: If a serializer module or class is not passed to the constructor
  397. #: this one is picked up. This currently defaults to :mod:`json`.
  398. default_serializer = json
  399. #: The default :class:`Signer` class that is being used by this
  400. #: serializer.
  401. #:
  402. #: .. versionadded:: 0.14
  403. default_signer = Signer
  404. def __init__(self, secret_key, salt=b'itsdangerous', serializer=None,
  405. signer=None, signer_kwargs=None):
  406. self.secret_key = want_bytes(secret_key)
  407. self.salt = want_bytes(salt)
  408. if serializer is None:
  409. serializer = self.default_serializer
  410. self.serializer = serializer
  411. self.is_text_serializer = is_text_serializer(serializer)
  412. if signer is None:
  413. signer = self.default_signer
  414. self.signer = signer
  415. self.signer_kwargs = signer_kwargs or {}
  416. def load_payload(self, payload, serializer=None):
  417. """Loads the encoded object. This function raises :class:`BadPayload`
  418. if the payload is not valid. The `serializer` parameter can be used to
  419. override the serializer stored on the class. The encoded payload is
  420. always byte based.
  421. """
  422. if serializer is None:
  423. serializer = self.serializer
  424. is_text = self.is_text_serializer
  425. else:
  426. is_text = is_text_serializer(serializer)
  427. try:
  428. if is_text:
  429. payload = payload.decode('utf-8')
  430. return serializer.loads(payload)
  431. except Exception as e:
  432. raise BadPayload('Could not load the payload because an '
  433. 'exception occurred on unserializing the data',
  434. original_error=e)
  435. def dump_payload(self, obj):
  436. """Dumps the encoded object. The return value is always a
  437. bytestring. If the internal serializer is text based the value
  438. will automatically be encoded to utf-8.
  439. """
  440. return want_bytes(self.serializer.dumps(obj))
  441. def make_signer(self, salt=None):
  442. """A method that creates a new instance of the signer to be used.
  443. The default implementation uses the :class:`Signer` baseclass.
  444. """
  445. if salt is None:
  446. salt = self.salt
  447. return self.signer(self.secret_key, salt=salt, **self.signer_kwargs)
  448. def dumps(self, obj, salt=None):
  449. """Returns a signed string serialized with the internal serializer.
  450. The return value can be either a byte or unicode string depending
  451. on the format of the internal serializer.
  452. """
  453. payload = want_bytes(self.dump_payload(obj))
  454. rv = self.make_signer(salt).sign(payload)
  455. if self.is_text_serializer:
  456. rv = rv.decode('utf-8')
  457. return rv
  458. def dump(self, obj, f, salt=None):
  459. """Like :meth:`dumps` but dumps into a file. The file handle has
  460. to be compatible with what the internal serializer expects.
  461. """
  462. f.write(self.dumps(obj, salt))
  463. def loads(self, s, salt=None):
  464. """Reverse of :meth:`dumps`, raises :exc:`BadSignature` if the
  465. signature validation fails.
  466. """
  467. s = want_bytes(s)
  468. return self.load_payload(self.make_signer(salt).unsign(s))
  469. def load(self, f, salt=None):
  470. """Like :meth:`loads` but loads from a file."""
  471. return self.loads(f.read(), salt)
  472. def loads_unsafe(self, s, salt=None):
  473. """Like :meth:`loads` but without verifying the signature. This is
  474. potentially very dangerous to use depending on how your serializer
  475. works. The return value is ``(signature_okay, payload)`` instead of
  476. just the payload. The first item will be a boolean that indicates
  477. if the signature is okay (``True``) or if it failed. This function
  478. never fails.
  479. Use it for debugging only and if you know that your serializer module
  480. is not exploitable (eg: do not use it with a pickle serializer).
  481. .. versionadded:: 0.15
  482. """
  483. return self._loads_unsafe_impl(s, salt)
  484. def _loads_unsafe_impl(self, s, salt, load_kwargs=None,
  485. load_payload_kwargs=None):
  486. """Lowlevel helper function to implement :meth:`loads_unsafe` in
  487. serializer subclasses.
  488. """
  489. try:
  490. return True, self.loads(s, salt=salt, **(load_kwargs or {}))
  491. except BadSignature as e:
  492. if e.payload is None:
  493. return False, None
  494. try:
  495. return False, self.load_payload(e.payload,
  496. **(load_payload_kwargs or {}))
  497. except BadPayload:
  498. return False, None
  499. def load_unsafe(self, f, *args, **kwargs):
  500. """Like :meth:`loads_unsafe` but loads from a file.
  501. .. versionadded:: 0.15
  502. """
  503. return self.loads_unsafe(f.read(), *args, **kwargs)
  504. class TimedSerializer(Serializer):
  505. """Uses the :class:`TimestampSigner` instead of the default
  506. :meth:`Signer`.
  507. """
  508. default_signer = TimestampSigner
  509. def loads(self, s, max_age=None, return_timestamp=False, salt=None):
  510. """Reverse of :meth:`dumps`, raises :exc:`BadSignature` if the
  511. signature validation fails. If a `max_age` is provided it will
  512. ensure the signature is not older than that time in seconds. In
  513. case the signature is outdated, :exc:`SignatureExpired` is raised
  514. which is a subclass of :exc:`BadSignature`. All arguments are
  515. forwarded to the signer's :meth:`~TimestampSigner.unsign` method.
  516. """
  517. base64d, timestamp = self.make_signer(salt) \
  518. .unsign(s, max_age, return_timestamp=True)
  519. payload = self.load_payload(base64d)
  520. if return_timestamp:
  521. return payload, timestamp
  522. return payload
  523. def loads_unsafe(self, s, max_age=None, salt=None):
  524. load_kwargs = {'max_age': max_age}
  525. load_payload_kwargs = {}
  526. return self._loads_unsafe_impl(s, salt, load_kwargs, load_payload_kwargs)
  527. class JSONWebSignatureSerializer(Serializer):
  528. """This serializer implements JSON Web Signature (JWS) support. Only
  529. supports the JWS Compact Serialization.
  530. """
  531. jws_algorithms = {
  532. 'HS256': HMACAlgorithm(hashlib.sha256),
  533. 'HS384': HMACAlgorithm(hashlib.sha384),
  534. 'HS512': HMACAlgorithm(hashlib.sha512),
  535. 'none': NoneAlgorithm(),
  536. }
  537. #: The default algorithm to use for signature generation
  538. default_algorithm = 'HS256'
  539. default_serializer = compact_json
  540. def __init__(self, secret_key, salt=None, serializer=None,
  541. signer=None, signer_kwargs=None, algorithm_name=None):
  542. Serializer.__init__(self, secret_key, salt, serializer,
  543. signer, signer_kwargs)
  544. if algorithm_name is None:
  545. algorithm_name = self.default_algorithm
  546. self.algorithm_name = algorithm_name
  547. self.algorithm = self.make_algorithm(algorithm_name)
  548. def load_payload(self, payload, return_header=False):
  549. payload = want_bytes(payload)
  550. if b'.' not in payload:
  551. raise BadPayload('No "." found in value')
  552. base64d_header, base64d_payload = payload.split(b'.', 1)
  553. try:
  554. json_header = base64_decode(base64d_header)
  555. except Exception as e:
  556. raise BadHeader('Could not base64 decode the header because of '
  557. 'an exception', original_error=e)
  558. try:
  559. json_payload = base64_decode(base64d_payload)
  560. except Exception as e:
  561. raise BadPayload('Could not base64 decode the payload because of '
  562. 'an exception', original_error=e)
  563. try:
  564. header = Serializer.load_payload(self, json_header,
  565. serializer=json)
  566. except BadData as e:
  567. raise BadHeader('Could not unserialize header because it was '
  568. 'malformed', original_error=e)
  569. if not isinstance(header, dict):
  570. raise BadHeader('Header payload is not a JSON object',
  571. header=header)
  572. payload = Serializer.load_payload(self, json_payload)
  573. if return_header:
  574. return payload, header
  575. return payload
  576. def dump_payload(self, header, obj):
  577. base64d_header = base64_encode(self.serializer.dumps(header))
  578. base64d_payload = base64_encode(self.serializer.dumps(obj))
  579. return base64d_header + b'.' + base64d_payload
  580. def make_algorithm(self, algorithm_name):
  581. try:
  582. return self.jws_algorithms[algorithm_name]
  583. except KeyError:
  584. raise NotImplementedError('Algorithm not supported')
  585. def make_signer(self, salt=None, algorithm=None):
  586. if salt is None:
  587. salt = self.salt
  588. key_derivation = 'none' if salt is None else None
  589. if algorithm is None:
  590. algorithm = self.algorithm
  591. return self.signer(self.secret_key, salt=salt, sep='.',
  592. key_derivation=key_derivation, algorithm=algorithm)
  593. def make_header(self, header_fields):
  594. header = header_fields.copy() if header_fields else {}
  595. header['alg'] = self.algorithm_name
  596. return header
  597. def dumps(self, obj, salt=None, header_fields=None):
  598. """Like :meth:`~Serializer.dumps` but creates a JSON Web Signature. It
  599. also allows for specifying additional fields to be included in the JWS
  600. Header.
  601. """
  602. header = self.make_header(header_fields)
  603. signer = self.make_signer(salt, self.algorithm)
  604. return signer.sign(self.dump_payload(header, obj))
  605. def loads(self, s, salt=None, return_header=False):
  606. """Reverse of :meth:`dumps`. If requested via `return_header` it will
  607. return a tuple of payload and header.
  608. """
  609. payload, header = self.load_payload(
  610. self.make_signer(salt, self.algorithm).unsign(want_bytes(s)),
  611. return_header=True)
  612. if header.get('alg') != self.algorithm_name:
  613. raise BadHeader('Algorithm mismatch', header=header,
  614. payload=payload)
  615. if return_header:
  616. return payload, header
  617. return payload
  618. def loads_unsafe(self, s, salt=None, return_header=False):
  619. kwargs = {'return_header': return_header}
  620. return self._loads_unsafe_impl(s, salt, kwargs, kwargs)
  621. class TimedJSONWebSignatureSerializer(JSONWebSignatureSerializer):
  622. """Works like the regular :class:`JSONWebSignatureSerializer` but also
  623. records the time of the signing and can be used to expire signatures.
  624. JWS currently does not specify this behavior but it mentions a possibility
  625. extension like this in the spec. Expiry date is encoded into the header
  626. similarily as specified in `draft-ietf-oauth-json-web-token
  627. <http://self-issued.info/docs/draft-ietf-oauth-json-web-token.html#expDef`_.
  628. The unsign method can raise a :exc:`SignatureExpired` method if the
  629. unsigning failed because the signature is expired. This exception is a
  630. subclass of :exc:`BadSignature`.
  631. """
  632. DEFAULT_EXPIRES_IN = 3600
  633. def __init__(self, secret_key, expires_in=None, **kwargs):
  634. JSONWebSignatureSerializer.__init__(self, secret_key, **kwargs)
  635. if expires_in is None:
  636. expires_in = self.DEFAULT_EXPIRES_IN
  637. self.expires_in = expires_in
  638. def make_header(self, header_fields):
  639. header = JSONWebSignatureSerializer.make_header(self, header_fields)
  640. iat = self.now()
  641. exp = iat + self.expires_in
  642. header['iat'] = iat
  643. header['exp'] = exp
  644. return header
  645. def loads(self, s, salt=None, return_header=False):
  646. payload, header = JSONWebSignatureSerializer.loads(
  647. self, s, salt, return_header=True)
  648. if 'exp' not in header:
  649. raise BadSignature('Missing expiry date', payload=payload)
  650. if not (isinstance(header['exp'], number_types)
  651. and header['exp'] > 0):
  652. raise BadSignature('expiry date is not an IntDate',
  653. payload=payload)
  654. if header['exp'] < self.now():
  655. raise SignatureExpired('Signature expired', payload=payload,
  656. date_signed=self.get_issue_date(header))
  657. if return_header:
  658. return payload, header
  659. return payload
  660. def get_issue_date(self, header):
  661. rv = header.get('iat')
  662. if isinstance(rv, number_types):
  663. return datetime.utcfromtimestamp(int(rv))
  664. def now(self):
  665. return int(time.time())
  666. class URLSafeSerializerMixin(object):
  667. """Mixed in with a regular serializer it will attempt to zlib compress
  668. the string to make it shorter if necessary. It will also base64 encode
  669. the string so that it can safely be placed in a URL.
  670. """
  671. def load_payload(self, payload):
  672. decompress = False
  673. if payload.startswith(b'.'):
  674. payload = payload[1:]
  675. decompress = True
  676. try:
  677. json = base64_decode(payload)
  678. except Exception as e:
  679. raise BadPayload('Could not base64 decode the payload because of '
  680. 'an exception', original_error=e)
  681. if decompress:
  682. try:
  683. json = zlib.decompress(json)
  684. except Exception as e:
  685. raise BadPayload('Could not zlib decompress the payload before '
  686. 'decoding the payload', original_error=e)
  687. return super(URLSafeSerializerMixin, self).load_payload(json)
  688. def dump_payload(self, obj):
  689. json = super(URLSafeSerializerMixin, self).dump_payload(obj)
  690. is_compressed = False
  691. compressed = zlib.compress(json)
  692. if len(compressed) < (len(json) - 1):
  693. json = compressed
  694. is_compressed = True
  695. base64d = base64_encode(json)
  696. if is_compressed:
  697. base64d = b'.' + base64d
  698. return base64d
  699. class URLSafeSerializer(URLSafeSerializerMixin, Serializer):
  700. """Works like :class:`Serializer` but dumps and loads into a URL
  701. safe string consisting of the upper and lowercase character of the
  702. alphabet as well as ``'_'``, ``'-'`` and ``'.'``.
  703. """
  704. default_serializer = compact_json
  705. class URLSafeTimedSerializer(URLSafeSerializerMixin, TimedSerializer):
  706. """Works like :class:`TimedSerializer` but dumps and loads into a URL
  707. safe string consisting of the upper and lowercase character of the
  708. alphabet as well as ``'_'``, ``'-'`` and ``'.'``.
  709. """
  710. default_serializer = compact_json