예제 #1
0
def signed_deserialize(serialized, secret, hmac=hmac):
    """ Deserialize the value returned from ``signed_serialize``.  If
    the value cannot be deserialized for any reason, a
    :exc:`ValueError` exception will be raised.

    This function is useful for deserializing a signed cookie value
    created by ``signed_serialize``.  For example:

    .. code-block:: python

       cookieval = request.cookies['signed_cookie']
       data = signed_deserialize(cookieval, 'secret')
    """
    # hmac parameterized only for unit tests
    try:
        input_sig, pickled = (bytes_(serialized[:40]),
                              base64.b64decode(bytes_(serialized[40:])))
    except (binascii.Error, TypeError) as e:
        # Badly formed data can make base64 die
        raise ValueError('Badly formed base64 data: %s' % e)

    try:
        # bw-compat with pyramid <= 1.5b1 where latin1 is the default
        secret = bytes_(secret)
    except UnicodeEncodeError:
        secret = bytes_(secret, 'utf-8')
    sig = bytes_(hmac.new(secret, pickled, hashlib.sha1).hexdigest())

    # Avoid timing attacks (see
    # http://seb.dbzteam.org/crypto/python-oauth-timing-hmac.pdf)
    if strings_differ(sig, input_sig):
        raise ValueError('Invalid signature')

    return pickle.loads(pickled)
예제 #2
0
파일: session.py 프로젝트: AdamG/pyramid
def signed_deserialize(serialized, secret, hmac=hmac):
    """ Deserialize the value returned from ``signed_serialize``.  If
    the value cannot be deserialized for any reason, a
    :exc:`ValueError` exception will be raised.

    This function is useful for deserializing a signed cookie value
    created by ``signed_serialize``.  For example:

    .. code-block:: python

       cookieval = request.cookies['signed_cookie']
       data = signed_deserialize(cookieval, 'secret')
    """
    # hmac parameterized only for unit tests
    try:
        input_sig, pickled = (serialized[:40],
                              base64.b64decode(bytes_(serialized[40:])))
    except (binascii.Error, TypeError) as e:
        # Badly formed data can make base64 die
        raise ValueError('Badly formed base64 data: %s' % e)

    sig = hmac.new(bytes_(secret), pickled, sha1).hexdigest()

    # Avoid timing attacks (see
    # http://seb.dbzteam.org/crypto/python-oauth-timing-hmac.pdf)
    if strings_differ(sig, input_sig):
        raise ValueError('Invalid signature')

    return pickle.loads(pickled)
예제 #3
0
def dummy_signed_deserialize(serialized, secret):
    import base64
    from pyramid.compat import pickle, bytes_

    serialized_data = base64.b64decode(
        serialized[len(base64.b64encode(bytes_(secret))):])
    return pickle.loads(serialized_data)
예제 #4
0
 def loads(self, bstruct):
     """Accept bytes and return a Python object."""
     try:
         return pickle.loads(bstruct)
     # at least ValueError, AttributeError, ImportError but more to be safe
     except Exception:
         raise ValueError
예제 #5
0
파일: session.py 프로젝트: jvanasco/pyramid
 def loads(self, bstruct):
     """Accept bytes and return a Python object."""
     try:
         return pickle.loads(bstruct)
     # at least ValueError, AttributeError, ImportError but more to be safe
     except Exception:
         raise ValueError
예제 #6
0
    def loads(self, encrypted_state):
        """Decrypt session state.

        :type encrypted_state: bytes
        :param encrypted_state: the encrypted session state.

        :rtype: :class:`dict` / picklable mapping
        :returns: the decrypted, unpickled session state, as passed as
                  ``session_state`` to :meth:`dumps`.
        """
        payload = self.box.decrypt(urlsafe_b64decode(encrypted_state))
        return pickle.loads(payload)
        def __init__(self, request):
            self.request = request
            now = time.time()
            created = renewed = now
            new = True
            value = None
            state = {}
            cookieval = self._get_cookie()
            if cookieval:
                value = self._collection.find_one({'_id': cookieval})

            if value is not None:
                try:
                    renewed = float(value.get('accessed'))
                    created = float(value.get('created'))
                    sval = value.get('value')
                    pickled = value.get('pickled')
                    state = sval

                    if pickled:
                        if not PY3:
                            sval = sval.encode('utf-8')  # dammit
                        state = pickle.loads(sval)

                    new = False
                except (TypeError, ValueError, pickle.PickleError):
                    # value failed to unpack properly or renewed was not
                    # a numeric type so we'll fail deserialization here
                    state = {}

            if self._timeout is not None:
                if now - renewed > self._timeout:
                    # expire the session because it was not renewed
                    # before the timeout threshold
                    state = {}

            self.created = created
            self.accessed = renewed
            self.renewed = renewed
            self.new = new

            dict.__init__(self, state)
        def __init__(self, request):
            self.request = request
            now = time.time()
            created = renewed = now
            new = True
            value = None
            state = {}
            cookieval = self._get_cookie()
            if cookieval:
                value = self._collection.find_one({'_id': cookieval})

            if value is not None:
                try:
                    renewed = float(value.get('accessed'))
                    created = float(value.get('created'))
                    sval = value.get('value')
                    pickled = value.get('pickled')
                    state = sval

                    if pickled:
                        if not PY3:
                            sval = sval.encode('utf-8')  # dammit
                        state = pickle.loads(sval)

                    new = False
                except (TypeError, ValueError, pickle.PickleError):
                    # value failed to unpack properly or renewed was not
                    # a numeric type so we'll fail deserialization here
                    state = {}

            if self._timeout is not None:
                if now - renewed > self._timeout:
                    # expire the session because it was not renewed
                    # before the timeout threshold
                    state = {}

            self.created = created
            self.accessed = renewed
            self.renewed = renewed
            self.new = new

            dict.__init__(self, state)
예제 #9
0
 def loads(self, bstruct):
     return pickle.loads(bstruct)
예제 #10
0
 def loads(self, bstruct):
     return pickle.loads(bstruct)
예제 #11
0
def dummy_signed_deserialize(serialized, secret):
    import base64
    from pyramid.compat import pickle, bytes_
    serialized_data = base64.b64decode(
        serialized[len(base64.b64encode(bytes_(secret))):])
    return pickle.loads(serialized_data)
예제 #12
0
 def loads(self, bstruct):
     """Accept bytes and return a Python object."""
     return pickle.loads(bstruct)
예제 #13
0
 def loads(self, bstruct):
     """Accept bytes and return a Python object."""
     return pickle.loads(bstruct)