Friday, July 4, 2008

Securing SQL for a .Net website

Preventing SQL injection is more important than ever as any site that is not hacker proof is sure to get hacked.
Hopefully you won't have to find out the hard way.

The No 1 preventive is to use paramaterized SQL queries from your code.
Sometimes this may not be possible as you may not have access to the code or changing the code may be a huge undertaking.

Securing objects at SQL level is something that can easily be done regardless of how secure your code is.
The only caveat is that all data access from your web app should be via Stored Procedures.

The concept is only Grant your application minimum access rights..
1) Access to run SPs
2)Have select permissions on tables. (Or ideally only certain tables). You don't really need to give the user access to tables unless your procs contain any dynamic SQL. Dynamic SQL requires the user to have select permissions on the tables being accessed.

Webcoda standard website set up is as follows.

1. Create a windows account on the server for the application to run under.

2. Under Directory Security in IIS set up the website to run as the new account.



3) In your web.config add the following line.

<system.web>
<identity impersonate="true">
</SYSTEM.WEB>

This reason for doing this is that if your application uses it's own application pool then the site will actually run as the identity of the application pool (by default Network Service). This web.config change will force it to run under the IIS account.

4) In SQL don't assign this user to any roles for the DB but run ths following script

select 'Grant Execute on ' + name + ' to [domain\username]'
from sysobjects where xtype in ('P')

This will generate the script to assign exec permission on all procs.

5) Assign only Select permissions on all tables (optional)