From ffb0a804c6eba81d6ed15e11b88f9fbb670d0cfe Mon Sep 17 00:00:00 2001 From: Georg Brandl Date: Tue, 6 Mar 2007 18:44:35 +0000 Subject: [PATCH] Patch #1638879: don't accept strings with embedded NUL bytes in long(). (backport from rev. 54173) --- Lib/test/test_builtin.py | 5 +++++ Misc/NEWS | 2 ++ Objects/longobject.c | 19 ++++++++++++++++++- 3 files changed, 25 insertions(+), 1 deletion(-) diff --git a/Lib/test/test_builtin.py b/Lib/test/test_builtin.py index 72b696690b5..da2afbac35a 100644 --- a/Lib/test/test_builtin.py +++ b/Lib/test/test_builtin.py @@ -1017,6 +1017,11 @@ class BuiltinTest(unittest.TestCase): self.assertRaises(ValueError, long, '53', 40) self.assertRaises(TypeError, long, 1, 12) + # SF patch #1638879: embedded NULs were not detected with + # explicit base + self.assertRaises(ValueError, long, '123\0', 10) + self.assertRaises(ValueError, long, '123\x00 245', 20) + self.assertEqual(long('100000000000000000000000000000000', 2), 4294967296) self.assertEqual(long('102002022201221111211', 3), 4294967296) diff --git a/Misc/NEWS b/Misc/NEWS index c51b690d42c..f6ebc242224 100644 --- a/Misc/NEWS +++ b/Misc/NEWS @@ -12,6 +12,8 @@ What's New in Python 2.5.1c1? Core and builtins ----------------- +- Patch #1638879: don't accept strings with embedded NUL bytes in long(). + - Bug #1674503: close the file opened by execfile() in an error condition. - Patch #1674228: when assigning a slice (old-style), check for the diff --git a/Objects/longobject.c b/Objects/longobject.c index 4d886cd7242..cb4900d9d03 100644 --- a/Objects/longobject.c +++ b/Objects/longobject.c @@ -3287,8 +3287,25 @@ long_new(PyTypeObject *type, PyObject *args, PyObject *kwds) return PyLong_FromLong(0L); if (base == -909) return PyNumber_Long(x); - else if (PyString_Check(x)) + else if (PyString_Check(x)) { + /* Since PyLong_FromString doesn't have a length parameter, + * check here for possible NULs in the string. */ + char *string = PyString_AS_STRING(x); + if (strlen(string) != PyString_Size(x)) { + /* create a repr() of the input string, + * just like PyLong_FromString does. */ + PyObject *srepr; + srepr = PyObject_Repr(x); + if (srepr == NULL) + return NULL; + PyErr_Format(PyExc_ValueError, + "invalid literal for long() with base %d: %s", + base, PyString_AS_STRING(srepr)); + Py_DECREF(srepr); + return NULL; + } return PyLong_FromString(PyString_AS_STRING(x), NULL, base); + } #ifdef Py_USING_UNICODE else if (PyUnicode_Check(x)) return PyLong_FromUnicode(PyUnicode_AS_UNICODE(x),