SQL injection is a way of injecting partial or complete sql query via data input from client to the server. Consider following web application
http://www.sqlinjestiondemo.com/customer?id=1
and now consider following server side code written to serve this request
userId = get id from user input, in this case query string
query = "select * from customer where id = " + userId
In the above scenario user can change input like 1 or 1=1 that will run following query, which will return all the customers from the dB, which is not what the intention was
select * from customer where id = 1 or 1=1
Lets take another example, if you change input to "1 ; drop table customer--" this will run following query which can drop the table
select * from customer where id = 1 ; drop table customer--
Following can be done to minimize chances of sql injection
http://www.sqlinjestiondemo.com/customer?id=1
and now consider following server side code written to serve this request
userId = get id from user input, in this case query string
query = "select * from customer where id = " + userId
In the above scenario user can change input like 1 or 1=1 that will run following query, which will return all the customers from the dB, which is not what the intention was
select * from customer where id = 1 or 1=1
Lets take another example, if you change input to "1 ; drop table customer--" this will run following query which can drop the table
select * from customer where id = 1 ; drop table customer--
Following can be done to minimize chances of sql injection
- Avoid concatenation of user input to partial query as we were doing in the above case. You can parametrize the query or use sproc or use ORM which internally parametrize the query
- User input which can come from query string, post via form, cookies, request header is untrusted data. It should be validated while processing them.
- do a proper type conversion. getting away from string minimizes a lot of risk
- use regular expression to validate string
- list of known good values, like countries,state etc
- Do not send sql exception to the client. This can expose dB info, for example table name, which can then be compromised by sql injecti
- Make sure you give only necessary permission to the a/c under which sql is executed.
There are tools available to test sql injection flaw in your application.
No comments:
Post a Comment