Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter SQL statement against malicious injection in Python

Would like to allow a client application to execute SQL queries against our database.

The queries will be requests for data, the client should never be able to modify data.

Is there a way to allow a client to send in a SQL statement, then screen it for malicious injection, then pass it through the the database?

We are using the SQLAlchemy library for Python against a PostgreSQL database.

Thanks!

like image 485
Chris Dutrow Avatar asked Jun 16 '26 14:06

Chris Dutrow


2 Answers

An easier option than trying to interpret queries for malice would be to create a db user with read-only privilege. Your end-users would then use that account to run SELECT queries. You would not need to worry about malicious inserts and deletes because "write" queries would not be allowed. You could also modify permissions further to not allow access to data that you do not want your clients to see etc.

See this SO question and answers for some info on creating "read only" users.

like image 123
Paul Sasik Avatar answered Jun 18 '26 04:06

Paul Sasik


use prepared statement when execute sql queries, using sqlalchemy.sql.expression.text method

from sqlalchemy.sql.expression import text

t = text("SELECT * FROM users WHERE id=:user_id")
result = connection.execute(t, user_id=12)

refer to sqlalchemy docs for full coverage of text method.

but protect your application against user-defined sql statements is really hard even if the DBA block create and writing roles from users. consider reading this blog post before start.

like image 35
MBarsi Avatar answered Jun 18 '26 03:06

MBarsi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!