Teknik coding untuk perlindungan terhadap SQL Injection (Part 4)
-
19 April 2012 6:49Moderator
ASP.NET 1.1 VB.NET
Anda dapat menyaring semua query-string, form dan nilai cookie yang masuk dengan menjalankan kode selama BeginRequest event. Sebuah lokasi pusat untuk mendaftarkan kode ini terdapat dalam website file global.asax. Contoh kode di bawah ini akan memeriksa data yang masuk dan secara otomatis mengarahkan ulang ke halaman yang disebut "Error.aspx" jika urutan karakter yang mencurigakan ditemukan.
Pertama, Anda akan perlu menambahkan namespace import baru di atas file global.asax anda:
<%@ Import namespace="System.Globalization" %>
Lalu tempatkan definisi variabel berikut dan private function di suatu tempat dalam file global.asax anda di tag <script>:
'Defines the set of characters that will be checked.
'You can add to this list, or remove items from this list, as appropriate for your site
Public Shared blackList As String() = {"--", ";--", ";", "/*", "*/", "@@", _
"@", "char", "nchar", "varchar", "nvarchar", "alter", _
"begin", "cast", "create", "cursor", "declare", "delete", _
"drop", "end", "exec", "execute", "fetch", "insert", _
"kill", "open", "select", "sys", "sysobjects", "syscolumns", "table", _
"update"}
'The utility method that performs the blacklist comparisons
'You can change the error handling, and error redirect location to whatever makes sense for your site.
Private Sub CheckInput(ByVal parameter As String)
Dim comparer As CompareInfo = CultureInfo.InvariantCulture.CompareInfo
For i As Integer = 0 To blackList.Length - 1
If (comparer.IndexOf(parameter,blackList(i),CompareOptions.IgnoreCase) >= 0) Then
'
'Handle the discovery of suspicious Sql characters here
'
'generic error page on your site
Response.Redirect("~/Error.aspx")
End If
Next
End Sub
Langkah terakhir tempatkan definisi fungsi berikut dalam tag <script> file global.asax anda. Definisi fungsi ini akan memberitahu ASP.NET untuk menjalankan pemeriksaan string selama BeginRequest event. Jika file global.asax anda sudah memiliki fungsi yang disebut Application_BeginRequest, anda harus menempatkan isi dari definisi fungsi di bawah ini ke dalam versi yang ada dari Application_BeginRequest.
Sub Application_BeginRequest(ByVal sender As Object, ByVal e As EventArgs)
For Each key As String In Request.QueryString
CheckInput(Request.QueryString(key))
Next
For Each key As String In Request.Form
CheckInput(Request.Form(key))
Next
For Each key As String In Request.Cookies
CheckInput(Request.Cookies(key).Value)
Next
End Sub
Berlanjut ke MS Knowledge Base: Teknik coding untuk perlindungan terhadap SQL Injection (Part 5)
Agnes Sannie [MSFT]
MSDN Community Support | Feedback to us
Get or Request Code Sample from Microsoft
Please remember to mark the replies as answers if they help and unmark them if they provide no help.