Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent Sql injection in nhibernate

Tags:

c#

sql

nhibernate

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;
    }
like image 311
user3165200 Avatar asked Jan 06 '14 11:01

user3165200


1 Answers

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!

like image 169
Rippo Avatar answered Oct 13 '22 21:10

Rippo