user2961127
user2961127

Reputation: 1143

How to avoid SQL injection on query

My SQL query construction in python code is:

query = '''
SELECT {return_col} 
FROM {table_name}   
'''.format(colA, tableA)

When I run Bandit security tool, it says "Possible SQL injection vector through string-based query construction."

How do I avoid it?

Upvotes: 5

Views: 7666

Answers (1)

Serge Ballesta
Serge Ballesta

Reputation: 148975

Best practices recommend to avoid to dynamically build the query and instead use a parameterized query. But the goal is precisely to avoid what you are doing here: prevent a forged parameter to allow an arbitrary query.

If you know why you allow to query any field on any table, and if the account running the query has only SELECT privilege on the database, then you can ignore the warning: it just says that you could allow requests on any table... what you want to do!

But kindly examine the security implications. In some use cases it may be perfectly fine, in others it could be terrible.

Upvotes: 4

Related Questions