This is the implementation in code: the schema name comes from a configuration file and is different for each environment. Sonar throws SQL injection alert at this statement:
select *
from dbName.dbo.stu_name; <<dbname is the variable that comes from property file>>
I tried these solutions:
Using
query.setParameter(?,dbname). Tried passing dbname dynamically and vulnerability was fixed. When debugging, the query was throwing an error and did not execute.Used
String.format(select * from \'%s\',tablename.replace("\'","\'\'"))- vulnerability fixed, but query failed to execute
I tried various other solutions and nothing worked.
Can anyone please help me with this?
The "best" defence you can do is not use dynamic SQL. Considering that this is the database that's dynamic, and based on a prior question, I would suggest that this is occurring from an application, so that means you don't need 3-part naming. Instead you parametrise the database name in the connection string and use 2-part naming; no dynamic SQL needed.
If you must use dynamic SQL, then the "best™️" defence would be to validate the database name, and then ensure you properly quote the database name when you inject it into your dynamic statement.
Here I validate the database name in
sys.databasesand then useQUOTENAMEto quote the name appropriately. If the database doesn't exist, no query is run (and no error is returned):