SQL injections are code injection technique that exploits a security vulnerability occurring in the database layer of an application. This normally happens when user input is not being validated, or errors are not handled, and displayed to a potential hacker. Successful SQL injection attacks will enable malicious users to execute commands in an application's database.
There are several ways to do this, however I am going to show you how to check for a SQL injection using a method that will check the input, and return true or false.
For a test, I created a Console Application.
1: private static void Main()
2: {
3: Console.WriteLine("Please enter text input to check for
SQL Injection and then press enter.");
4:
5: string userInput = Console.ReadLine();
6:
7: Console.WriteLine(checkForSQLInjection(userInput));
8: Console.ReadLine();
9:
10: }
The following method will check for possible sql injection input, and return true or false.
1: public static string checkForSQLInjection(string userInput)
2: {
3: bool isSQLInjection = false;
4:
5: string[] sqlCheckList = { "--",
6: ";--",
7: ";",
8: "/*",
9: "*/",
10: "@@",
11: "@",
12: "char",
13: "nchar",
14: "varchar",
15: "nvarchar",
16: "alter",
17: "begin",
18: "cast",
19: "create",
20: "cursor",
21: "declare",
22: "delete",
23: "drop",
24: "end",
25: "exec",
26: "execute",
27: "fetch",
28: "insert",
29: "kill",
30: "open",
31: "select",
32: "sys",
33: "sysobjects",
34: "syscolumns",
35: "table",
36: "update"
37: };
38:
39: string CheckString = userInput.Replace("'", "''");
40:
41: for (int i = 0; i <= sqlCheckList.Length - 1; i++)
42: {
43: if ((CheckString.IndexOf(sqlCheckList[i],
StringComparison.OrdinalIgnoreCase) >= 0))
44: {
45: isSQLInjection = true;
46: }
47: }
48:
49: return Convert.ToString(isSQLInjection);
50: }
The result for a string that does not contain any thread will return false.
The result for a string that does contain any thread will return true.