Solved

SQL Injection Prevention Best Practices

Posted on 2011-02-10
10
444 Views
Last Modified: 2012-05-11
   <tr>
    <td>
    <asp:Label ID="lblEmailAddressConfirm" runat="server" CssClass="mainlabel">Confirm Email</asp:Label>
    <asp:TextBox ID="txbEmailAddressConfirm" runat="server" CssClass="maintextbox"></asp:TextBox><br />
    <hr class="hrclear" />
    <p class="instructions">Confirm your email address in the field above.</p>    
    </td>
    </tr>
0
Comment
Question by:jsvb1977
10 Comments
 
LVL 39

Expert Comment

by:Kyle Abrahams
Comment Utility
http://msdn.microsoft.com/en-us/library/ff648339.aspx

Step 1. Constrain input.
Step 2. Use parameters with stored procedures.
Step 3. Use parameters with dynamic SQL.

0
 
LVL 51

Expert Comment

by:HainKurt
Comment Utility
one subject line and 5 lines of code without explanation does not mean too much...
0
 
LVL 8

Expert Comment

by:gothamite
Comment Utility
Also limit the permissions of the web server user(s) to the minimum possible level for example only grant EXEC on the stored procedures that website/page should be able to call. Don't add the user as a member of any of the predefined server or database roles. This will mean that if someone does manage to execute arbitrary code on your SQL Server at least they won't be able to do much.
0
 

Author Comment

by:jsvb1977
Comment Utility
Here is a test post. I am having trouble submitting and posting for some reason.

That is why the question is truncated / incomplete.
0
 

Author Comment

by:jsvb1977
Comment Utility
Here is an attempt at posting the meat of my question:

I have identified, through googling, the following methods for preventing sql injection attacks:

1. Replace single quote with two single quotes
2. Allow only 'safe' characters and a few common special characters
3. Deny Dangerous strings, Such as EXEC, UPDATE, DROP
4. Lock Down SQL User Permissions
5. Pass variables through to Stored Procedures via SQL Parameters

The last item in my list above is what my question is about.

Isn't the code below the same thing as passing variables through to a stored procedure as parameters?

Dim SSN as String = Request.QueryString("SSN")

Dim cmd As new SqlCommand("SELECT au_lname, au_fname FROM authors WHERE au_id = @au_id")
Dim param = new SqlParameter("au_id", SqlDbType.VarChar)
param.Value = SSN
cmd.Parameters.Add(param) 

Open in new window


1. If not, what is the difference?
2. Is this just a .net Code Behind version of a stored procedure parameter?
3. Should one method be used over another, or should both be used in tandem?
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 

Author Comment

by:jsvb1977
Comment Utility
Grrrr... for some reason I am unable to submit the rest of my question. I contacted EE Support and they say there is nothing wrong on their side -- must be me.

Anyway -- the last part of my question is not a question, but rather examples of the routines I am using to check the strings for unsafe code.

I will try to post it again in a few minutes.
Jason
0
 

Author Comment

by:jsvb1977
Comment Utility
I will try attaching the routines instead of embedding them:


[code]
    Public Function fncReplaceQuote(ByVal strToReplace As String) As String

        strToReplace.Replace("'", "''")

        Return strToReplace
    End Function
[/code]

[code]
    Public Function fncAllowedCharacters(ByVal strToCheck As String) As Boolean

        Dim strAllowedChar As String = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'- ,.?!@$_"

        For i = 1 To Len(strToCheck)
            Dim c As String = Mid(strToCheck, i, 1)
            If (InStr(strAllowedChar, c) = 0) Then
                Return False
            End If
        Next

        Return True
    End Function
[/code]

[code]
    Public Function fncDeniedStrings(ByVal strToCheck As String) As Boolean

        Dim i As Integer
        strToCheck = strToCheck.ToUpper
        ' The following strings are not needed because they contain characters which we already to not allow via the fncAllowedCharacters
        ' "EXEC(", "/SCRIPT", "<SCRIPT", "CAST(", "INSERT INTO", "DELETE FROM", "DROP TABLE",

        Dim arrDeniedStrings() As String = {"INSERT ", "UPDATE ", "CREATE ", "DROP ", "DELETE ", "SELECT ", "--", "SCRIPT ", "EXEC ", "EXECUTE ", "TRUNCATE ", "SET ", "0x", "@@", "DECLARE", "VARCHAR", "SP_", "XP_"}

        For i = 0 To 20
            If strToCheck.IndexOf(arrDeniedStrings(i)) > -1 Then
                Return False
            End If
        Next

        Return True
    End Function
[/code]

[code]
    Public Function fncCheckEmailAddressFormat(ByVal strToCheck As String) As Boolean

        Dim pattern As String = "^[a-zA-Z][\w\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$"
        Dim emailAddressMatch As Match = Regex.Match(strToCheck, pattern)

        If emailAddressMatch.Success Then
            Return True
        End If

        Return False
    End Function
[/code]

Open in new window

0
 
LVL 7

Accepted Solution

by:
Chris-Chambers earned 500 total points
Comment Utility
Hi,

The answer to:

'Isn't the code below the same thing as passing variables through to a stored procedure as parameters?'

is no, but using an 'SqlParameter' as you have done is generally almost as safe in terms of sql injection as using a stored procedure with parameters.
The real reason everyone recommends stored procedures over dynamic sql is more than just sql injection safety. They are much easier to maintain, much quicker to execute, and once you've done a few, they are quicker to write.

Hope this helps,

Chris.
0
 
LVL 39

Expert Comment

by:Kyle Abrahams
Comment Utility
jsvb1977:  your paramater post was fine, you just need a small correction:

'ADDED @ symbol.
Dim param = new SqlParameter("@au_id", SqlDbType.VarChar)
0
 
LVL 39

Expert Comment

by:Kyle Abrahams
Comment Utility
Further post:

Agreed with Chris regarding the quicker portion of things.     Stored procedures can be quicker as they can be compiled as long as they don't make use of the wildcard.  Also the statements are NOT the same.  (see article at end).

from an execution point of view
select * from tbl

will execute the same in sql and stored_proc as the column list needs to be built at run time.

A good article here:
http://blogs.msdn.com/b/raulga/archive/2007/01/04/dynamic-sql-sql-injection.aspx


select id, test from tbl
will execute faster in stored_proc because it knows the return types once compiled.    

0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Composite queries are used to retrieve the results from joining multiple queries after applying any filters. UNION, INTERSECT, MINUS, and UNION ALL are some of the operators used to get certain desired results.​
This article explains how to reset the password of the sa account on a Microsoft SQL Server.  The steps in this article work in SQL 2005, 2008, 2008 R2, 2012, 2014 and 2016.
This video demonstrates how to create an example email signature rule for a department in a company using CodeTwo Exchange Rules. The signature will be inserted beneath users' latest emails in conversations and will be displayed in users' Sent Items…
You have products, that come in variants and want to set different prices for them? Watch this micro tutorial that describes how to configure prices for Magento super attributes. Assigning simple products to configurable: We assigned simple products…

772 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now