• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 457
  • Last Modified:

SQL Injection Prevention Best Practices

   <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
jsvb1977
Asked:
jsvb1977
1 Solution
 
Kyle AbrahamsSenior .Net DeveloperCommented:
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
 
HainKurtSr. System AnalystCommented:
one subject line and 5 lines of code without explanation does not mean too much...
0
 
gothamiteCommented:
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
Transaction-level recovery for Oracle database

Veeam Explore for Oracle delivers low RTOs and RPOs with agentless transaction log backup and transaction-level recovery of Oracle databases. You can restore the database to a precise point in time, even to a specific transaction.

 
jsvb1977Author Commented:
Here is a test post. I am having trouble submitting and posting for some reason.

That is why the question is truncated / incomplete.
0
 
jsvb1977Author Commented:
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
 
jsvb1977Author Commented:
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
 
jsvb1977Author Commented:
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
 
Chris-ChambersCommented:
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
 
Kyle AbrahamsSenior .Net DeveloperCommented:
jsvb1977:  your paramater post was fine, you just need a small correction:

'ADDED @ symbol.
Dim param = new SqlParameter("@au_id", SqlDbType.VarChar)
0
 
Kyle AbrahamsSenior .Net DeveloperCommented:
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

Hire Technology Freelancers with Gigs

Work with freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely, and get projects done right.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now