Search code examples
c#asp.netado.netsql-injectionparameterized

Is there a SQL Injection risk with this query? If so, how can I avoid it?


I usually create parameterized queries in order to avoid SQL Injection attacks. However, I have this particular situation where I haven't been totally able to do it:

public DataSet getLiveAccountingDSByParameterAndValue(string parameter, string value)
{
    string sql = "select table_ref as Source, method as Method, sip_code as Code, " +
        " from view_accountandmissed " +
        " where " + parameter + " like @value " +
        " order by time DESC ";
    MySqlCommand cmd = commonDA.createCommand(sql);
    cmd.Parameters.Add("@value", MySqlDbType.String);
    cmd.Parameters["@value"].Value = "%" + value + "%";

    MySqlDataAdapter objDA = commonDA.createDataAdapter(cmd);
    DataSet objDS = new DataSet();
    objDA.Fill(objDS);
    return objDS;
}

As you can see, I am creating @value as a parameter but if I tried to do the same with parameter the query would fail.

So, is there a risk of SQL Injection with this query? Also, take into account that parameter is set by a DropDownList's SelectedValue (not a TextBox, so the input is limited). If so, how can I improve this query?


Solution

  • Yes there is:

    " where " + parameter + " like @value " +
    

    The value in parameter is your risk. In the postback you should check if the selected value is in the set of start values of the dropdown list.

    Make the parameter an enum and pass the enum to your function. That will eliminate the risk (something like: not tested):

    public DataSet getLiveAccountingDSByParameterAndValue(ParameterEnum parameter, string value)
    .....
        " where " + parameter.ToString() + " like @value " +
    

    The ParameterEnum contains a list of all possible values in your dropdown list. In your code behind, parse the selected value to the enum.