[FIXED] python pyodbc SQLite sql injections

Issue

I use pyodbc in my python flask Project for the SQLite DB connection. I know and understand SQL Injections but this is my first time dealing with it. I tried to execute some

I have a function which concatenates the SQL String in my database.py file:

    def open_issue(self, data_object):
        cursor = self.conn.cursor()

        # data_object is the issue i get from the user
        name = data_object["name"]
        text = data_object["text"]
        rating_sum = 0

        # if the user provides an issue
        if name:

            # check if issue is already in db
            test = cursor.execute(f'''SELECT name FROM issue WHERE name = "{name}"''')
            data = test.fetchall()

            # if not in db insert
            if len(data) == 0:

                # insert the issue
                cursor.executescript(f'''INSERT INTO issue (name, text, rating_sum)
                                    VALUES ("{name}", "{text}", {rating_sum})''')
            else:
                print("nothing inserted!")

In the api.py file the open_issue() function gets called:

        @self.app.route('/open_issue')
        def insertdata():

            # data sent from client
            # data_object = flask.request.json

            # unit test dictionary
            data_object = {"name": "injection-test-table",
                           "text": "'; CREATE TABLE 'injected_table-1337';--"}
            DB().open_issue(data_object)

The "'; CREATE TABLE 'injected_table-1337';--" sql injection has not created the injected_table-1337, instead it got inserted normally like a string into the text column of the injection-test-table.

So i don't really know if i am safe for the standard ways of SQL injection (this project will only be hosted locally but good security is always welcome)

And secondary: are there ways with pyodbc to check if a string contains sql syntax or symbols, so that nothing will get inserted in my example or do i need to check the strings manually?

Thanks a lot


Solution

As it turns out, with SQLite you are at much less risk of SQL injection issues because by default neither Python's built-in sqlite3 module nor the SQLite ODBC driver allow multiple statements to be executed in a single .execute call (commonly known as an "anonymous code block"). This code:

thing = "'; CREATE TABLE bobby (id int primary key); --"
sql = f"SELECT * FROM table1 WHERE txt='{thing}'"
crsr.execute(sql)

throws this for sqlite3

sqlite3.Warning: You can only execute one statement at a time.

and this for SQLite ODBC

pyodbc.Error: ('HY000', '[HY000] only one SQL statement allowed (-1) (SQLExecDirectW)')

Still, you should follow best practices and use a proper parameterized query

thing = "'; CREATE TABLE bobby (id int primary key); --"
sql = "SELECT * FROM table1 WHERE txt=?"
crsr.execute(sql, (thing, ))

because this will also correctly handle parameter values that would cause errors if injected directly, e.g.,

thing = "it's good to avoid SQL injection"


Answered By - Gord Thompson
Answer Checked By - Willingham (sql.easybugfix Volunteer)

Related Posts

Post a Comment