Thursday, May 17
Sanitization against Sql injection attacks.
Here is what I use to sanitize my text input before inserting into DB. Most of the code is from a msdn article on how to avoid sql injection attacks.
29 ///
30 /// make search text input sql safe.
31 ///
32 ///
33 ///
34 private static string SafeSqlLikeClauseLiteral(string inputSQL)
35 {
36 // Make the following replacements:
37 // ' becomes ''
38 // [ becomes [[]
39 // % becomes [%]
40 // _ becomes [_]
41
42 string s = inputSQL;
43 s = inputSQL.Replace("'", "''");
44 s = s.Replace("[", "[[]");
45 s = s.Replace("%", "[%]");
46 s = s.Replace("_", "[_]");
47 return s;
48 }
49 ///
50 /// make text input sql safe
51 ///
52 ///
53 ///
54 private static string SafeSqlLiteral(string inputSQL)
55 {
56 return inputSQL.Replace("'", "''");
57 }
58 ///
59 /// convert '' to ' when returning to the user, Remember, only to be used
60 /// when returning strings to user.
61 ///
62 ///
63 ///
64 private static string Desanitize(string output)
65 {
66 return output.Replace("''", "'");
67 }
Comments:
<< Home
Thanks for that post. I'm using pass-through SQL for a particular project that I'm working on. I'll eventually convert to sprocs, but not just yet. I think I'll incorporate your observations in the project.
Sql injection is quite common on projects with "Search" functionality and ones that use a lot of dynamic sql. Let me know any best practices that you follow.
Post a Comment
Subscribe to Post Comments [Atom]
<< Home
Subscribe to Posts [Atom]