From 03824a1dba8eb4b82fff3fd6c0a8ae513e72a2a1 Mon Sep 17 00:00:00 2001 From: Alexander Schrijver Date: Sun, 17 Jul 2016 16:32:47 +0200 Subject: [PATCH 1/2] Throw an exception when a NUL character is used as a parameter. --- psycopg/utils.c | 7 ++++++- tests/test_quote.py | 9 +++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/psycopg/utils.c b/psycopg/utils.c index 1b10c4aa..b919180c 100644 --- a/psycopg/utils.c +++ b/psycopg/utils.c @@ -50,8 +50,13 @@ psycopg_escape_string(connectionObject *conn, const char *from, Py_ssize_t len, Py_ssize_t ql; int eq = (conn && (conn->equote)) ? 1 : 0; - if (len == 0) + if (len == 0) { len = strlen(from); + } else if (strchr(from, '\0') != from + len) { + PyErr_Format(PyExc_ValueError, "A string literal cannot contain NUL (0x00) characters."); + + return NULL; + } if (to == NULL) { to = (char *)PyMem_Malloc((len * 2 + 4) * sizeof(char)); diff --git a/tests/test_quote.py b/tests/test_quote.py index 25d1d31c..7176e1a6 100755 --- a/tests/test_quote.py +++ b/tests/test_quote.py @@ -62,6 +62,15 @@ class QuotingTestCase(ConnectingTestCase): self.assertEqual(res, data) self.assert_(not self.conn.notices) + def test_string_null_terminator(self): + curs = self.conn.cursor() + data = 'abcd\x01\x00cdefg' + + with self.assertRaises(ValueError) as e: + curs.execute("SELECT %s", (data,)) + + self.assertEquals(e.exception.message, 'A string literal cannot contain NUL (0x00) characters.') + def test_binary(self): data = b("""some data with \000\013 binary stuff into, 'quotes' and \\ a backslash too. From 478f43f0c88ba115f2ec9132b8ecb4b0129794bb Mon Sep 17 00:00:00 2001 From: Daniele Varrazzo Date: Sun, 7 Aug 2016 02:50:50 +0100 Subject: [PATCH 2/2] Mention NULL characters guard in NEWS file Fix #420. --- NEWS | 2 ++ 1 file changed, 2 insertions(+) diff --git a/NEWS b/NEWS index 2c828c2a..7e6fba48 100644 --- a/NEWS +++ b/NEWS @@ -24,6 +24,8 @@ New features: What's new in psycopg 2.6.3 ^^^^^^^^^^^^^^^^^^^^^^^^^^^ +- Throw an exception trying to pass ``NULL`` chars as parameters + (:ticket:`#420). - Make `~psycopg2.extras.Range` objects picklable (:ticket:`#462`).