psycopg2 and SQL injection security

后端 未结 3 1716
青春惊慌失措
青春惊慌失措 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    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.

提交回复
热议问题