In my project I have one method which is taking serviceTags as a string parameter input in nhibernate dynamic query and replacing that with ''. Now its already parameterized but still its a threat to sql injection. So my question is to get this kind of functionality without threat what should I do? User input's type/length check is already in my mind and I don't think that will solve the whole threat.
 public Dictionary<string, string> GetCollectionStatus(string serviceTags)
 { using (var session = m_SessionFactory.OpenSession())
        {
           foreach (var resultParts in session.CreateSQLQuery(string.Format("select servicetag , " +
                                                                             "DiagnosticStatus from AssetOverview where servicetag IN ('{0}')", 
                                                                             serviceTags.Replace(",", "','"))).List())
            {
                collectionStatus.Add(((object[])(resultParts))[0].ToString(), ((object[])(resultParts))[1].ToString());
            }
        }
        return collectionStatus;
    }
                To prevent SQL injection, that is to use NHibernate to format your strings, simply do this:-
var q = session.CreateSQLQuery(
   "select servicetag, DiagnosticStatus from AssetOverview 
       where servicetag IN (:list)")
   .SetParameterList("list", serviceTags)
   .List();
NHibernate will escape the single quotes for you.
edit I would do the following as well as I can see that the serviceTags is a comma delimited list...
   .SetParameterList("list", serviceTags.split(','))
Mind you this might give problems if you have leading/trailing spaces or blanks!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With