Skip to content

Commit 22cbdd9

Browse files
LegoclonesAgent-Hellboy
authored andcommitted
pythongh-135241: Make unpickling of booleans in protocol 0 more strict (pythonGH-135242)
The Python pickle module looks for "00" and "01" but _pickle only looked for 2 characters that parsed to 0 or 1, meaning some payloads like "+0" or " 0" would lead to different results in different implementations.
1 parent ae7b999 commit 22cbdd9

File tree

3 files changed

+14
-1
lines changed

3 files changed

+14
-1
lines changed

Lib/test/pickletester.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1012,6 +1012,16 @@ def test_constants(self):
10121012
self.assertIs(self.loads(b'I01\n.'), True)
10131013
self.assertIs(self.loads(b'I00\n.'), False)
10141014

1015+
def test_issue135241(self):
1016+
# C implementation should check for hardcoded values 00 and 01
1017+
# when getting booleans from the INT opcode. Doing a str comparison
1018+
# to bypass truthy/falsy comparisons. These payloads should return
1019+
# 0, not False.
1020+
out1 = self.loads(b'I+0\n.')
1021+
self.assertEqual(str(out1), '0')
1022+
out2 = self.loads(b'I 0\n.')
1023+
self.assertEqual(str(out2), '0')
1024+
10151025
def test_zero_padded_integers(self):
10161026
self.assertEqual(self.loads(b'I010\n.'), 10)
10171027
self.assertEqual(self.loads(b'I-010\n.'), -10)
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
The :code:`INT` opcode of the C accelerator :mod:`!_pickle` module was updated
2+
to look only for "00" and "01" to push booleans onto the stack, aligning with
3+
the Python :mod:`pickle` module.

Modules/_pickle.c

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5255,7 +5255,7 @@ load_int(PickleState *state, UnpicklerObject *self)
52555255
}
52565256
}
52575257
else {
5258-
if (len == 3 && (x == 0 || x == 1)) {
5258+
if (len == 3 && s[0] == '0' && (s[1] == '0' || s[1] == '1')) {
52595259
if ((value = PyBool_FromLong(x)) == NULL)
52605260
return -1;
52615261
}

0 commit comments

Comments
 (0)