1

I have created a function to search a table using a dictionary (attribute-value pair). I would like to know if designing methods like that would lead to SQL Injection? If so how to properly sanitize the value before it is used to build a query?

SQL Injection on - qry = qry.filter(getattr(ormClass, attr) >= value)
The value comes from the client side as a JSON request.
Env - Python, SQL alchemy, Fast API

def listRequired(session, ormClass, reqData: dict, toSearch: tuple[str, ...]):
    searchParam: dict = {}
    for param in toSearch:
        try:
            searchParam[param] = reqData[param]
        except KeyError:
            raise ExceptionResponse(
                status=Response.KEY_NOT_FOUND,
                details=param + " not found")
    qry = session.query(ormClass)
    for attr, value in searchParam.items():
        qry = qry.filter(getattr(ormClass, attr) >= value)
    print(qry)
    return qry.limit(50)
Thinkal VB
  • 189
  • 3
  • 12
  • 3
    The value will be quoted by the connector package for the dialect used by SQLAlchemy, for example `psycopg2` for `postgresql+psycopg2://...`. So your protection is as good as that offered by the connector. – snakecharmerb Dec 28 '21 at 12:12

0 Answers0