I have this statement:
SELECT [nozzles].[nozzle_tag],[nozzles].[id]
FROM [dispensers]
INNER JOIN [nozzles]
ON [dispenser_id] = [dispensers].[id]
INNER JOIN (SELECT * FROM assets
WHERE [i4_Device_Name] = 'EH004T_SOURCE2'
AND [i4_site_name] = 'Les Loges - H2e Station (EH004R)')assets
ON [asset_id] = [assets].[id]
WHERE [dispenser_tag] ='Dispenser 2';
It works perfectly fine when I execute it inside SSMS.
The problem is, when run this SQL by using SQLcommand
, I get an error with this message:
Incorrect syntax near 'Loges'.
I don't understand why.
The command above is extracted from a log file, it is exactly what is send using SQLCommand
.
C# code is:
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand(HySoSQLCommandBuilder.GetAllNozzleOfDispenser(locationID, dispenserTag), connection))
{
logger.Info("SQL request {request}", HySoSQLCommandBuilder.GetAllNozzleOfDispenser(locationID, dispenserTag));
using (SqlDataReader reader = command.ExecuteReader())
{
try
{
while (reader.Read())
if (reader.HasRows)
{
list.Add(new nozzle((string)reader["nozzle_tag"], (int)reader["id"]));
}
}
catch { }
}
}
With HySoSQLCommandBuilder.GetAllNozzleOfDispenser()
being fairly straight forward:
public static string GetAllNozzleOfDispenser(AssetLocationID assetLocation, string dispenserTag)
{
return $@"SELECT [nozzles].[nozzle_tag],[nozzles].[id]
FROM [dispensers]
INNER JOIN [nozzles]
ON [dispenser_id] = [dispensers].[id]
INNER JOIN (SELECT * FROM assets
WHERE [i4_Device_Name] = '{assetLocation.i4DeviceName}'
AND [i4_site_name] = '{assetLocation.i4SiteName}')assets
ON [asset_id] = [assets].[id]
WHERE [dispenser_tag] ='{dispenserTag}';";
}
None of the injected values are accessible from outside the code. They do not come form a editable field accessible from a user. If SQL injection happens, then that means that it is in the source, done by someone that worked on the code, and can already do whatever they want to the database without the need to encode an SQL injection.