473,408 Members | 2,405 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes and contribute your articles to a community of 473,408 developers and data experts.

The role of Parametrized queries

PsychoCoder
465 Expert Mod 256MB
In this entry we’re going to be looking at ways you can protect yourself & application data from malicious attacks from outside sources. This first entry we’re be looking at parametrized queries to help protect against SQL Injection attacks. So many times I see people, especially new programmers, who are using code that interacts with a database that is formatted like so:

Expand|Select|Wrap|Line Numbers
  1. public bool LoginToSystem(string un, string pwd)
  2. {
  3.     int count = 0;
  4.     using (var conn = new SqlConnection("YourConnectionStringHere"))
  5.     {
  6.         string sql = "SELECT COUNT(userId) FROM users WHERE userName = '" + un + "' AND password = '" + pwd + "'";
  7.         using (var cmd = new SqlCommand(sql, conn))
  8.         {
  9.             conn.Open();
  10.             count = (int)cmd.ExecuteScalar();
  11.         }
  12.     }
  13.  
  14.     return count > 0 ? true : false;
  15. }
Now some will look at that example and at first think “Whats wrong with that?”. Well it’s called SQL Injection, and using code like shown above is prime and ready for this kind of attack.
  • SQL injection is an attack in which malicious code is inserted into strings that are later passed to an instance of SQL Server for parsing and execution.

Given the above example we could provide the values [il]‘ OR ’1' = ’1[/il] for both username and password values and we would be able to log in no problems, as doing this would cause this to be executed in your database:
  • SELECT COUNT(userId) FROM users WHERE userName = ” OR ’1' = ’1' AND password = ” OR ’1' = ’1'

Since 1 always equals 1 someone would then have access to your system, and trust me this isn’t something you want to have happen. That’s a mild result of what could happen if the above sql statement stayed the way it is, so this would then produce the following script to be executed in your database. With the way the statement is formatted someone could add ;DROP TABLE users-- and this, as you can image, would have devastating consequences. If that were to execute then this would be what your database sees:
  • SELECT COUNT(userId) FROM users WHERE userName = ” AND password = ”; DROP TABLE users–

The semi-colon tells the database that one execution is ending and another is beginning, the – at the end of the statement tells SQL that the rest of the statement is a comment so ignore it. What would this do, well it would delete your users table.

So what can you do about this, well one of the biggest steps you can take to protect yourself is by using Parametrized Queries. Using parametrized statements embed your values into the statement, making it that much harder for someone to inject commands into your code.

So let’s take a look at how the above scenario can be remedied by using parametrized queries to protect yourself. Keep in mind this example will be for MSSQL, but I will also show how to do this for Microsoft Access as well. To do this we will use the AddWithValue Method of the SqlParameterCollection Class to create a parametrized query.

The new code (for MSSQL) would look like this:

Expand|Select|Wrap|Line Numbers
  1. public bool LoginToSystemParameterized(string un, string pwd)
  2. {
  3.     int count = 0;
  4.     using (var conn = new SqlConnection("YourConnectionStringHere"))
  5.     {
  6.         string sql = "SELECT COUNT(userId) FROM users WHERE userName = @username AND password = @password";
  7.         using (var cmd = new SqlCommand(sql, conn))
  8.         {
  9.             conn.Open();
  10.             cmd.CommandType = System.Data.CommandType.Text;
  11.             //now add our parameters
  12.             cmd.Parameters.AddWithValue("@username", un);
  13.             cmd.Parameters.AddWithValue("@password", pwd);
  14.             count = (int)cmd.ExecuteScalar();
  15.         }
  16.     }
  17.  
  18.     return count > 0 ? true : false;
  19. }
For Microsoft Access we would have to make a small modification to our statement to look like this

Expand|Select|Wrap|Line Numbers
  1. public bool LoginToSystemParameterized(string un, string pwd)
  2. {
  3.     int count = 0;
  4.     using (var conn = new SqlConnection("YourConnectionStringHere"))
  5.     {
  6.         string sql = "SELECT COUNT(userId) FROM users WHERE userName = ? AND password = ?";
  7.         using (var cmd = new SqlCommand(sql, conn))
  8.         {
  9.             conn.Open();
  10.             cmd.CommandType = System.Data.CommandType.Text;
  11.             //now add our parameters
  12.             cmd.Parameters.AddWithValue("@username", un);
  13.             cmd.Parameters.AddWithValue("@password", pwd);
  14.             count = (int)cmd.ExecuteScalar();
  15.         }
  16.     }
  17.  }
  18.     return count > 0 ? true : false;
  19. }
In MSSQL @parametername is a placeholder for the value we’re embedding into our statement, with Access you use a question mark ? for a place holder. When this new query is sent to SQL Server it’s executed by the system stored procedure
  • sp_executesql. So to SQL Server this query looks like this
    exec sp_executesql N’SELECT COUNT(userId) FROM users WHERE userName = @username AND password = @password,’N@username varchar(15),’N'@password varchar(25)’,@username=’yourname’,@password=’yourp assword’

So as you can see using parametrized queries can go a long way towards protecting yourself, your application & data, and your employer/users from malicious attacks from outside sources
Jun 30 '12 #1
0 22087

Sign in to post your reply or Sign up for a free account.

Similar topics

1
by: Ersin Gençtürk | last post by:
hi , I have 2 tables , tUser and tUserRole and I have a query like : select * from tUser inner join tUserRole on tUserRole.UserId=tUser.UserId where tUser.UserId=1 this will return a user...
5
by: atif | last post by:
Hi all I have read 5-6 books just to find what is the job of Adaptor object in ADO.NET. Non of them clearly defines the job, all of them says that it is used to get data from datasource, then...
7
by: nugget | last post by:
Role-based security for an ASP/ASP.NET mixed environment Hello: My co-worker and I have been charged with designing role-based security for our intranet. The technologies we have to work with...
8
by: beretta819 | last post by:
Ok, so I apologize in advance for the wordiness of what follows... (I am not looking for someone to make this for me, but to point me in the right direction for the steps I need to take.) I was...
0
by: Halimaji Nijazi | last post by:
Hi everybody I've read a lot about parametrized services and now I want to test it. My problem is, how should I create a simple parametrized service? How starting this service whithin .NET? ...
2
by: weird0 | last post by:
Hi! On the recommendation of one of the MVP's on this group....... I tried writing parametrized queries. But the fucking thing does not work and it does not update the data in the table. I...
5
by: rhaazy | last post by:
I am trying to a simple insert statement from a remote application against a sql server 2005 database. To fix the problem I was having, I had to grant the Login I was using the role of sysadmin. ...
3
by: lemonade134 | last post by:
Hello, I'm creating a database in Access 2003 after not using Access for about six years. I used to use nested queries, but don't see a way to do that in the newer form of Access. Instead, the books...
5
by: Jonathan Wood | last post by:
Greetings, I'm using ASP.NET membership and I'd like to query the number of users in a particular role. I don't want the overhead of returning a dataset and then getting the number of items...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.