3

I'm facing a challenge while deploying a backed application built using Python Flask. The codegate scan is catching up some of the code integrated in the CI/CD process as potential vulnerabilities. Below are 2 types of vulnerabilities.

  1. Second order SQL injection.
  2. SQL injection

I'm using raw SQL queries to get the data from the DB in conjunction with Flask SQLAlchemy and Pandas.

Below is a sample code where codegate is pointing the issues for Second order SQL injection.

def get_user_data(user_id: str):
  query: str = USER_ID_QUERY.format(user_id=user_id)
  result = db.session.execute(query)
  result = result.fetchall()
  if len(result) < 1:
    raise Exception("User not Found")
  return result[0][0]

Query

USER_ID_QUERY = """SELECT USER_ID FROM USER WHERE USER_ID = '{user_id}'"""

Vulnerability description - Method get_user_data at line 236 of src\utils.py gets database data from the execute element. This element’s value then flows through the code without being properly sanitized or validated, and is eventually used in a database query in method check_access at line 50 of src\service.py. This may enable an Second-Order SQL Injection attack.

I have tried below solution after digging out the internet by still it is giving the same error.

Binding the parameters using text and bindparams of sqlalchemy

query = text(USER_ID_QUERY).bindparams(user_id=user_id)

Could someone please help me in highlighting what is wrong here or what can be done to resolve these painfull issues?

Vin
  • 968
  • 2
  • 10
  • 22
  • Please edit your question and add definition/content of `USER_ID_QUERY` – Robert Aug 25 '22 at 11:24
  • Added sample query – Vin Aug 25 '22 at 12:05
  • 1
    String formatting is indeed insecure. See here how to do it correct: https://stackoverflow.com/a/19324366/150978 Looks in the end very similar but works a bit different and is thus secure. – Robert Aug 25 '22 at 12:20

0 Answers0