I’m trying to demo SQL Injection with a UNION query but I’m not getting results.
This is the C# code and the database is SQL Server 2008 R2:
SqlConnection conn = new SqlConnection(cString);
conn.Open();
string sql = "select * from Users where UserName='" + userName
+ "' and Password='" + password + "'";
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = sql;
SqlDataReader reader = cmd.ExecuteReader();
StringBuilder sb = new StringBuilder(1024);
while (reader.Read())
{
for (int i = 0; i < reader.FieldCount; i++)
{
sb.Append(" " + reader.GetName(i));
sb.Append(": ");
sb.Append(reader[i]);
}
sb.Append("<br />");
}
dataLabel.Text = sb.ToString();
I have a username and password text boxes and the input is passed to this method.
I tried the following but no result:
'UNION SELECT * FROM products --
the Users table and Products table have identical column types (int, nvarchar, nvarchar).
Can someone help? What am I missing?
If you are passing
' UNION SELECT * FROM Productsinto thepasswordparameter, then your query looks like this (assuming you putfooor any other valid or invalid username intousername):Unless you have a row in
Usersthat matches that where clause (even if you use a valid username, which a malicious user might only be able to guess, there is still a blank password which certainly won’t match), why do you expect any rows to come back from theUserstable?And if you are passing this value into username, you end up with this:
Again, unless you have a username with a blank username, why would you expect any rows?
Anyway, there are lots of great materials out there describing SQL injection. Why do you want to re-invent the wheel? Why not just enforce parameterized queries, and let them read the existing materials for the details on why? Here are just a few great resources:
http://en.wikipedia.org/wiki/SQL_injection
http://www.unixwiz.net/techtips/sql-injection.html
http://msdn.microsoft.com/en-us/library/ms161953(v=sql.105).aspx
http://weblogs.sqlteam.com/mladenp/archive/2011/02/16/sql-server-sql-injection-from-start-to-end.aspx