-1

I'm trying to demonstrate how SQL injection attacks work in a class as a presentation.

I have the following piece of code in Python:

def query(username, password):
    with mysql.connector.connect(**DB_INFO) as conn:
        with conn.cursor() as cursor:
            cursor.execute(f"SELECT * FROM users WHERE username = '{username}' AND password = '{password}';")
            res = cursor.fetchall()
            conn.commit()
            
            return res

The logic works by querying the database with a specific username and password. If the database returns a non-empty list, a user with that specific username and password exists.

But I also need to commit to the database, so for instance when the attacker injects a SQL DELETE FROM users; command in the username or password fields, the command takes effect.

But when I run the function with username: a and password: a'; DELETE FROM users; --, I get the following exception:

_mysql_connector.MySQLInterfaceError: Commands out of sync; you can't run this command now

Is there a way to fix this? Or should I change my code completely to have a function for querying and another function for modifying the database?

Amirreza A.
  • 669
  • 4
  • 10
  • As explained here (https://stackoverflow.com/a/3632320/2681662) you cannot run another query without catching the result of the first one. But what if you write the first one incorrectly and make the first par raise an error. Then expect the second one to run? – MSH May 16 '22 at 11:00

0 Answers0