Radha
Radha

Reputation: 81

Query causing sql injection issue

Type entryEntityType = entry.Entity.GetType();
string tableName = GetTableName(entryEntityType);
string primaryKeyName = GetPrimaryKeyName(entryEntityType);
string deletequery = string.Format("UPDATE {0} SET IsDeleted = 1 WHERE {1} = @id", tableName, primaryKeyName);         
    
Database.ExecuteSqlCommand(deletequery, new SqlParameter("@id", entry.OriginalValues[primaryKeyName]));

After running the sonar scan above query is giving a security hotspot for sql injection.How can this be handled?

Upvotes: -1

Views: 172

Answers (2)

David Browne - Microsoft
David Browne - Microsoft

Reputation: 89361

Also when injecting identifiers into dynamic SQL for SQL Server, you should sanitize the string by using a delimited identifier.

In TSQL you do this with the QUOTENAME function, and here's a C# version of it.

private static string QuoteName(string identifier)
{
    var sb = new StringBuilder(identifier.Length + 3, 1024);
    sb.Append('[');
    foreach (var c in identifier)
    {
        if (c == ']')
            sb.Append(']');
        sb.Append(c);
    }
    sb.Append(']');
    return sb.ToString();
}

Upvotes: 1

Palle Due
Palle Due

Reputation: 6302

It doesn't look like table name and primary key name are dependent on user input, so I would suppress the Sonar error around this code. If you insist on fixing it you can do something like this (pseudo code):

Do this once, if you will, make it static:

var deleteQueries = new Dictionary<Type, string>();
foreach (Type entryEntityType in AllEntityTypes) // I don't know how you will get all entities
{
    string tableName = GetTableName(entryEntityType);
    string primaryKeyName = GetPrimaryKeyName(entryEntityType);
    string deletequery = string.Format("UPDATE {0} SET IsDeleted = 1 WHERE {1} = @id", tableName, primaryKeyName);         
    deleteQueries.Add(entryEntityType, deleteQuery);
}

When executing delete do this:

Type entryEntityType = entry.Entity.GetType();
string deleteQuery = deleteQueries[entryEntityType];
string primaryKeyName = GetPrimaryKeyName(entryEntityType);
Database.ExecuteSqlCommand(deletequery, new SqlParameter("@id", entry.OriginalValues[primaryKeyName]));

As I said, I would just suppress the error.

Upvotes: 2

Related Questions