psycopg2 and SQL injection security

后端 未结 3 1661
青春惊慌失措
青春惊慌失措 2020-12-17 17:30

I am writing a class to be used as part of a much larger modeling algorithm. My part does spatial analysis to calculate distances from certain points to other points. Ther

相关标签:
3条回答
  • 2020-12-17 17:32

    AsIs is unsafe, unless you really know what you are doing. You can use it for unit testing for example.

    Passing parameters is not that unsafe, as long as you do not pre-format your sql query. Never do:

    sql_query = 'SELECT * FROM {}'.format(user_input)
    cur.execute(sql_query)
    

    Since user_input could be ';DROP DATABASE;' for instance.

    Instead, do:

    sql_query = 'SELECT * FROM %s'
    cur.execute(sql_query, (user_input,))
    

    pyscopg2 will sanitize your query. Also, you can pre-sanitize the parameters in your code with your own logic, if you really do not trust your user's input.

    Per psycopg2's documentation:

    Warning Never, never, NEVER use Python string concatenation (+) or string parameters interpolation (%) to pass variables to a SQL query string. Not even at gunpoint.

    Also, I would never, ever, let my users tell me which table I should query. Your app's logic (or routes) should tell you that.

    Regarding AsIs(), per psycopg2's documentation :

    Asis()... for objects whose string representation is already valid as SQL representation.

    So, don't use it with user's input.

    0 讨论(0)
  • 2020-12-17 17:34

    If you need to store your query in a variable you can use the SQL method (documentation) :

    from psycopg2 import sql
    
    
    query = sql.SQL("SELECT * FROM Client where id={clientId}").format(clientId=sql.Literal(clientId)
    
    0 讨论(0)
  • 2020-12-17 17:57

    You can use psycopg2.sql to compose dynamic queries. Unlike AsIs it will protect you from SQL injection.

    0 讨论(0)
提交回复
热议问题