Psycopg2: Strings with NUL bytes are silently truncated in bound parameters

Created on 30 Mar 2016  Â·  4Comments  Â·  Source: psycopg/psycopg2

Minimal repro:

#!python
import psycopg2

conn = psycopg2.connect(host='localhost', dbname='nullbytes')
cursor = conn.cursor()

try:
    cursor.execute("""drop table "user" """)
except:
    pass

cursor.execute("""
CREATE TABLE "user" (
    email_address VARCHAR(60)
)
""")

cursor.execute(
    """INSERT INTO "user" (email_address) VALUES (%(email_address)s)""",
    {'email_address': '[email protected]\x00 foo'})

cursor.execute("""
SELECT "user".email_address
FROM "user"
WHERE "user".email_address = %(email_address_1)s
""", {'email_address_1': '[email protected]\x00 huh??'})


print(cursor.fetchall())

This prints out [('[email protected]',)], which is neither what I tried to insert nor what I tried to query for, which came as a surprise to me! I would have expected some kind of exception to be thrown. This has the potential to cause security flaws if a developer assumes that the string being queried/inserted has passed validation because the query worked.

Most helpful comment

I've fixed this issue here:

https://github.com/psycopg/psycopg2/pull/459

All 4 comments

I'll look into that. However you may know that postgres doesn't accept null bytes in strings, so the right thing to do would be to raise an exception, right?

Yes, raising an exception would be awesome :) Thanks!

On Wed, Mar 30, 2016 at 2:59 PM, Daniele Varrazzo [email protected]
wrote:

I'll look into that. However you may know that postgres doesn't accept
null bytes in strings, so the right thing to do would be to raise an
exception, right?

—
You are receiving this because you authored the thread.
Reply to this email directly or view it on GitHub
https://github.com/psycopg/psycopg2/issues/420#issuecomment-203608491

I've fixed this issue here:

https://github.com/psycopg/psycopg2/pull/459

Amazing, thanks so much!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

psycoteam picture psycoteam  Â·  5Comments

ProgVal picture ProgVal  Â·  6Comments

rofi93 picture rofi93  Â·  4Comments

vitorpontual picture vitorpontual  Â·  5Comments

jiamo picture jiamo  Â·  3Comments