Is this SQL query, injection safe

165 views Asked by At

I think the initial code is fine:

SqlCommand param = new SqlCommand();
SqlGeometry point = SqlGeometry.Point(center_lat,center_lng,0);
SqlGeometry poly = SqlGeometry.STPolyFromText(new SqlChars(new SqlString(polygon)),0);
param.CommandText = "INSERT INTO Circle (Center_Point, Circle_Data) VALUES (@point,@poly);";
param.Parameters.Add(new SqlParameter("@point", SqlDbType.Udt));
param.Parameters.Add(new SqlParameter("@poly", SqlDbType.Udt));
param.Parameters["@point"].UdtTypeName = "geometry";
param.Parameters["@poly"].UdtTypeName = "geometry";
param.Parameters["@point"].Value = point;
param.Parameters["@poly"].Value = poly;

However I realised there could be a problem when the polygon string is created.

in javascript - I create it like so:

var Circle_Data = "POLYGON ((";
for (var x = 0; x < pointsToSql.length; x++) { // formatting = 0 0, 150 0, 150 50 etc
    if (x == 360) { Circle_Data += pointsToSql[x].lat.toString() + " " + pointsToSql[x].lng.toString() + "))"; }
    else { Circle_Data += pointsToSql[x].lat.toString() + " " + pointsToSql[x].lng.toString() + ","; }
}

It is then passed to C#. So is this safe? even though the parametrization has happened in the query?

1

There are 1 answers

0
Habib On BEST ANSWER

With the parameter you will be saved from SQL Injection, If some SQL is injected in the POLYGON string, it will error out at SQL Server end.

So for example if you have :

POLYGON(12.33 12.55,13.55; DROP TABLE students;)

SQL server will try to construct a geometry type based on the passed string, and it will fail doing so.