Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

catch other pickle errors when loading content #3325

Merged
merged 2 commits into from
Aug 10, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions CHANGES.rst
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,12 @@ Bug Fixes
code. The old ``MIMEAccept`` has been deprecated. The new methods follow the
RFC's more closely. See https://github.com/Pylons/pyramid/pull/3251

- Catch extra errors like ``AttributeError`` when unpickling "trusted"
session cookies with bad pickle data in them. This would occur when sharing
a secret between projects that shouldn't actually share session cookies,
like when reusing secrets between projects in development.
See https://github.com/Pylons/pyramid/pull/3325

Deprecations
------------

Expand Down
6 changes: 5 additions & 1 deletion pyramid/session.py
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,11 @@ def __init__(self, protocol=pickle.HIGHEST_PROTOCOL):

def loads(self, bstruct):
"""Accept bytes and return a Python object."""
return pickle.loads(bstruct)
try:
return pickle.loads(bstruct)
# at least ValueError, AttributeError, ImportError but more to be safe
except Exception:
raise ValueError
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It seems odd that we have no direct unit tests for PickleSerializer.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Well, you can rest easy because we have some for the SimpleSerializer that does nothing. :-)

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Anyway the short answer is that the PickleSerializer was pulled out of existing session code and so I just assumed pyramid was exercising those paths well enough. Turns out it was missing a few things. Certainly it'd be easier to write tests for such things directly to the PickleSerializer if it got pulled out but I'm also not upset with more integration tests for sessions either.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I was going to let this slide but we are looking at changing the default serializer so I pushed some specific PickleSerializer tests so they don't get lost in translation later.


def dumps(self, appstruct):
"""Accept a Python object and return bytes."""
Expand Down
57 changes: 57 additions & 0 deletions pyramid/tests/test_session.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import json
import unittest
from pyramid import testing
from pyramid.compat import pickle

class SharedCookieSessionTests(object):

Expand Down Expand Up @@ -462,6 +463,24 @@ def test_very_long_key(self):
self.assertEqual(result, None)
self.assertTrue('Set-Cookie' in dict(response.headerlist))

def test_bad_pickle(self):
import base64
import hashlib
import hmac

digestmod = lambda: hashlib.new('sha512')
# generated from dumping an object that cannot be found anymore, eg:
# class Foo: pass
# print(pickle.dumps(Foo()))
cstruct = b'(i__main__\nFoo\np0\n(dp1\nb.'
sig = hmac.new(b'pyramid.session.secret', cstruct, digestmod).digest()
cookieval = base64.urlsafe_b64encode(sig + cstruct).rstrip(b'=')

request = testing.DummyRequest()
request.cookies['session'] = cookieval
session = self._makeOne(request, secret='secret')
self.assertEqual(session, {})

class TestUnencryptedCookieSession(SharedCookieSessionTests, unittest.TestCase):
def setUp(self):
super(TestUnencryptedCookieSession, self).setUp()
Expand Down Expand Up @@ -661,6 +680,44 @@ def test_it_with_latin1_secret(self):
self.assertEqual(result, '123')


class TestPickleSerializer(unittest.TestCase):
def _makeOne(self):
from pyramid.session import PickleSerializer
return PickleSerializer()

def test_loads(self):
# generated from dumping Dummy() using protocol=2
cstruct = b'\x80\x02cpyramid.tests.test_session\nDummy\nq\x00)\x81q\x01.'
serializer = self._makeOne()
result = serializer.loads(cstruct)
self.assertIsInstance(result, Dummy)

def test_loads_raises_ValueError_on_invalid_data(self):
cstruct = b'not pickled'
serializer = self._makeOne()
self.assertRaises(ValueError, serializer.loads, cstruct)

def test_loads_raises_ValueError_on_bad_import(self):
# generated from dumping an object that cannot be found anymore, eg:
# class Foo: pass
# print(pickle.dumps(Foo()))
cstruct = b'(i__main__\nFoo\np0\n(dp1\nb.'
serializer = self._makeOne()
self.assertRaises(ValueError, serializer.loads, cstruct)

def test_dumps(self):
obj = Dummy()
serializer = self._makeOne()
result = serializer.dumps(obj)
expected_result = pickle.dumps(obj, protocol=pickle.HIGHEST_PROTOCOL)
self.assertEqual(result, expected_result)
self.assertIsInstance(result, bytes)


class Dummy(object):
pass


class DummySerializer(object):
def dumps(self, value):
return base64.b64encode(json.dumps(value).encode('utf-8'))
Expand Down