3

I am using PostgreSQL 11 COPY command to import large CSVs into the DB with Python, like the following:

COPY "ns"."table" ("col1", "col2") FROM STDIN WITH CSV HEADER DELIMITER AS ','

I didn't find any recent information if this operation is secure in terms of SQL injection attacks or should I manually go over the CSV and escape every value in the file (which is a very heavy operation).

Thanks!

3
  • Can you show how this would be used in the context of python? While it should not be inherently dangerous, there are surely going to be dangerous ways to do it. Commented Dec 16, 2020 at 17:57
  • @jjanes, curs.copy_expert(sql='COPY ...', file=file_obj) (psycopg2 cursor) Commented Dec 16, 2020 at 18:06
  • That should be safe. If someone can inject \n\\.\n, into file_obj they can get all data after that to be ignored. But they can't get arbitrary commands to run. Commented Dec 16, 2020 at 21:46

1 Answer 1

7

There is no danger of SQL injection with this command.

If a user supplies bad data, then you end up with bad data in the table, or at worst you could get an error because the file is not correct CSV or because a constraint was violated.

But there is no way to subvert security to execute statements, because nothing entered by the user will become part of an SQL statement. With COPY, there is a clear distinction between SQL statement and data.

Sign up to request clarification or add additional context in comments.

4 Comments

Except for [CVE-2019-9193 ](rhaas.blogspot.com/2020/12/cve-2019-9193.html).
@AdrianKlaver This is irrelevant, because here we have COPY ... FROM STDIN. And what you quote is not SQL injection, and it is not a security problem to boot.
Yes but you did not specify COPY ... FROM STDIN, you made a blanket statement about COPY. Also it is security problem, it is just a documented one. Basically a superuser is a superuser, so be careful in how you assign them. And since program could be something that runs SQL it could be SQL injection and furthermore you are using SQL to mount an attack. I personally think the whole thing is over blown, but not providing a heads up is not good either.
C'mon. I wrote "with this command", meaning the statement in the question. Besides, this has nothing to do with SQL injection. What comes from the user are the COPY data, not the COPY statement. Or do you see dynamic SQL anywhere in the question?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.