How to find + stop SQL injection attacks

November 13, 2009 by AcidRaZor · Leave a Comment
Filed under: .NET, Classic ASP, Hosting, IIS 6.0, Programming 101, SQL Server 

There’s a lot of stuff out there about SQL injection attacks, but there’s not much that will help you figure out how to stop these attacks from occurring.

First, let’s talk about what a SQL Injection Attack really is. Some people think it’s a virus of sorts, that is “inside your site.” Not the case. These are bot attacks by other virus infected computers. They simply use a brute force approach of scanning URLs that take POST/GET inputs and attempt to send their own data to them.

So, how do you track these down and stop them? For web sites powered by Microsoft’s IIS, here are our suggestions:

  1. Look at your IIS logs
    Try searching for the word “DECLARE” or “EXECUTE.” If you’ve been hit by an attack, these will more than likely show up in your IIS logs — at least for any attack that was attempted using “GET” posts. If you do find any instances of “DECLARE” or “EXECUTE” these are the pages to start with.
  2. Use centralized database connection handling
    Simple, make a centralized file (e.g. connection.asp if you are using ASP) that handles all of your DB access. This way, it’s easier to make sure that you are SQL encoding your pages. You can easily search queries for “DECLARE” and “EXECUTE” and stop the attacks dead in their tracks.
  3. Implement a site wide solution
    If you are running your own server, we highly recommend ISAPI_Rewrite from HeliconTech (http://www.helicontech.com/isapi_rewrite). This is an ISAPI filter that allows you to do a variety of things, including scan URL data. This will stop 99% of attacks without changing ANY code on your site!\
  4. Never use “sa” as your database user, create a user for the database you’re working from and then remove privileges to read the master dbo. This prevents the attacker from “sniffing” your database structure, however, these attacks have evolved so that sanitized stored procedure based attacks happen even with these types of security in place. See http://www.ngssoftware.com/papers/more_advanced_sql_injection.pdf for more information on this and other ideas in preventing SQL Injection attacks.

If you’ve ever been scratching your head wondering where the leak in your programming is (or have taken over a project from someone else) then the best way to determine through which page the attack happened is by checking out the IIS logs.

There are many scripts available to clean up, but the best tip is to backup hourly, and to follow best practices (some of which I highlighted here). Good luck

How to setup a Windows 2003 Web Server

March 4, 2009 by AcidRaZor · Leave a Comment
Filed under: .NET, Classic ASP, Hosting, IIS 6.0, SQL Server 

Every time we setup a W2K3 box as a Web Server we do the following

Stage 1
1.1 Copy i386 to c:\
1.2 Configure Windows Permissions on all partitions
- Leave
Administrators (Full)
System (Full)
Remove Everything Else
1.3 Rename Administrator
1.4 Rename Machine
1.5 Reboot
1.6 Install Windows Updates (Not the .NET Frameworks)
1.7 Add IP’s to TCP/IP
1.8 Add DNS suffix to TCP/IP (Only if required)
1.9 Disable Shutdown Event Tracker
1.10 Reboot

Stage 2
2.1 Install Support Tools
2.2 Install Resource Kit Tools
2.3 Install KB908521 (Not needed if w2k3 SP2)
2.4 Install SNMP
2.5 Install SNMP Informant
2.6 Configure Windows Time
2.7 Reboot

Stage 3
3.1 Install R2 (Only if you want it)
3.2 Reboot

Stage 4
4.1 Setup Automatic Updates
4.2 Setup MS DNS
4.3 Set TCP/IP to Local DNS
4.4 MSTDC Fix

Stage 5
5.1 Install IIS
5.2 Allow direct Metabase Edit
5.3 Set IIS IP’s to be listened on
5.4 Restart IIS
5.5 Set Default Documents
5.6 Set W3SVC Logs Params
5.7 Install FastCGI
5.8 Install PHP 5.1 & 5.2 (FastCGI Mode)
5.9 Install Zend Optimizer (32bit edition)
5.10 Install Perl
5.11 Install Python
5.12 Configure IIS SMTP
5.13 Disable IIS SMTP Socket Pooling
- http://www.isaserver.org/tutorials/i…etpooling.html
5.14 Reboot

Step 6
6.1 Install .NET Framework 2.0
6.2 Install .NET Framework 2.0 SP1
6.3 Install .NET AJAX 1.0
6.4 Install .NET Framework 3.5 (Make sure you use the installer without SP1)
6.5 Install .NET Framework 3.5 SP1 (Only if using Helm 4.1)
6.6 Reboot

Step 7
7.1 Install ISAPI_ReWrite
7.2 Install JMail.NET
7.3 Install W3JMail
7.4 Install Hotlink Blocker
7.5 Install IIS Password
7.6 Install Winrar
7.7 Install Persists ASP Email
7.8 Install Persists ASP JPeg
7.9 Install Persists ASP Upload
7.10 Reboot

Naturally if the Box isn’t going to be a DNS Server you wouldn’t install MSDNS, instructions apply to both 32bit and 64bit w2k3. I’m not going to explain each step in detail the info is just so you can see what order we do things. It has been very well tested and we haven’t had any issues

At each step we test everything we install so we make sure PHP is working correctly before proceeding onto the next step. If you need to install MySQL or MSSQL I’d do it at Step 8. Once everything is setup you would install Helm as a remote or control.

How to read a remote queue with System.Messaging

February 14, 2009 by AcidRaZor · Leave a Comment
Filed under: .NET, MSMQ, Programming 101 

Seeing as this “feature” is undocumented (or seem to be) on MSDN and most tutorials you’ll find out there reads and writes to private local queues, I thought I’d share how you’d write or read to a remote queue using System.Messaging :

1
msmqqueue.Path = "FormatName:Direct=TCP:127.0.0.1\Private$\queuename"

I hope this information proves valueble for someone that might need it and can’t find any documentation anywhere else.

ZIP extraction with progress bar

February 13, 2009 by AcidRaZor · Leave a Comment
Filed under: .NET, Programming 101 

Using ICSharpCode’s SharpZipLib, I kick off a background worker process (guess what I have been playing around with, lol) and extract ZIP files. Used in combination with my Downloader, it becomes pretty nifty if I may say so myself!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
Delegate Sub zipProgressSafe(ByVal text As String, ByVal percent As Integer)
    Delegate Sub zipCompleteSafe(ByVal cancelled As Boolean)
 
    Dim extractDir As String = Application.StartupPath & "\extracted\"
 
    Private Sub bckZip_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles bckZip.DoWork
        Dim zipFilename As String = Me.whereToSave
 
        If File.Exists(zipFilename) Then
 
            Dim safedelegate As New zipProgressSafe(AddressOf zipProgress)
            Me.Invoke(safedelegate, "Start Unzipping Process...", 0) 'Invoke the TreadsafeDelegate
 
            Dim Redo As Integer = 1
            Dim MyZipInputStream As ZipInputStream
            Dim MyFileStream As FileStream
            MyZipInputStream = New ZipInputStream(New FileStream(zipFilename, FileMode.Open, FileAccess.Read))
 
            Dim MyZipEntry As ZipEntry = MyZipInputStream.GetNextEntry
            Directory.CreateDirectory(extractDir)
 
            Dim nRead, total As Integer
            Dim percent As Integer
 
            While Not MyZipEntry Is Nothing
                Me.Invoke(safedelegate, "Calculating ZIP File Size...", 0)
                total += 1
                MyZipEntry = MyZipInputStream.GetNextEntry
            End While
 
            Me.Invoke(safedelegate, "Resetting ZIP File...", 0)
            MyZipInputStream = New ZipInputStream(New FileStream(zipFilename, FileMode.Open, FileAccess.Read))
            MyZipEntry = MyZipInputStream.GetNextEntry
 
            Me.Invoke(safedelegate, "Start Unzipping file 1 of " & total.ToString, 0)
            While Not MyZipEntry Is Nothing
 
                If bckZip.CancellationPending Then 'If user abort download
                    Exit While
                End If
 
                If (MyZipEntry.IsDirectory) Then
                    Directory.CreateDirectory(extractDir & "\" & MyZipEntry.Name)
                Else
                    If Not Directory.Exists(extractDir & "\" & Path.GetDirectoryName(MyZipEntry.Name)) Then
                        Directory.CreateDirectory(extractDir & "\" & Path.GetDirectoryName(MyZipEntry.Name))
                    End If
                    MyFileStream = New FileStream(extractDir & "\" & MyZipEntry.Name, FileMode.OpenOrCreate, FileAccess.Write)
 
                    Dim count As Integer
                    Dim buffer(4096) As Byte
                    count = MyZipInputStream.Read(buffer, 0, 4096)
 
                    While count > 0
                        MyFileStream.Write(buffer, 0, count)
                        count = MyZipInputStream.Read(buffer, 0, 4096)
                    End While
 
                    MyFileStream.Close()
                End If
 
                nRead += 1
                percent = ((nRead / total) * 100)
                Me.Invoke(safedelegate, "Start Unzipping file " & nRead.ToString & " of " & total.ToString, percent)
 
                Try
                    MyZipEntry = MyZipInputStream.GetNextEntry
                Catch ex As Exception
                    MyZipEntry = Nothing
                End Try
            End While
 
            If Not (MyZipInputStream Is Nothing) Then MyZipInputStream.Close()
            If Not (MyFileStream Is Nothing) Then MyFileStream.Close()
 
            If Me.bckZip.CancellationPending Then
 
                Dim cancelDelegate As New zipCompleteSafe(AddressOf zipComplete)
 
                Me.Invoke(cancelDelegate, True)
 
                Exit Sub
 
            End If
 
            Dim completeDelegate As New zipCompleteSafe(AddressOf zipComplete)
 
            Me.Invoke(completeDelegate, False)
        Else
            Dim cancelDelegate As New zipCompleteSafe(AddressOf zipComplete)
 
            Me.Invoke(cancelDelegate, True)
 
            Exit Sub
        End If
    End Sub
 
    Public Sub zipProgress(ByVal text As String, ByVal percent As Integer)
        Me.Label4.Text = text
        Me.ProgressBar1.Value = percent
    End Sub
 
    Public Sub zipComplete(ByVal cancelled As Boolean)
        If cancelled Then
            Me.Label4.Text = "Cancelled"
        Else
            Me.Label4.Text = "Successfully Unzipped"
        End If
        Me.ProgressBar1.Value = 0
 
    End Sub

Download File calculating speed and progress -Background Worker & Progress bar

February 13, 2009 by AcidRaZor · Leave a Comment
Filed under: .NET, Programming 101 

Here is some code that will make use of VB.NET’s Backgroundworker class and initiate a web request to download a file. It will calculate the file’s speed as well as indicate it’s progress on a progress bar. All the while keeping the Main Form available.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
Dim whereToSave As String 'Where the program save the file
 
    Delegate Sub ChangeTextsSafe(ByVal length As Long, ByVal position As Integer, ByVal percent As Integer, ByVal speed As Double)
    Delegate Sub DownloadCompleteSafe(ByVal cancelled As Boolean)
 
    Public Sub DownloadComplete(ByVal cancelled As Boolean)
        Me.txtFileName.Enabled = True
        Me.btnDownload.Enabled = True
        Me.btnCancel.Enabled = False
 
        If cancelled Then
 
            Me.Label4.Text = "Cancelled"
 
            'MessageBox.Show("Download aborted", "Aborted", MessageBoxButtons.OK, MessageBoxIcon.Information)
 
 
        Else
            Me.Label4.Text = "Successfully downloaded"
 
            'MessageBox.Show("Successfully downloaded!", "All OK", MessageBoxButtons.OK, MessageBoxIcon.Information)
 
        End If
 
        Me.ProgressBar1.Value = 0
        Me.Label5.Text = "Downloading: "
        Me.Label6.Text = "Save to: "
        Me.Label3.Text = "File size: "
        Me.Label2.Text = "Download speed: "
        Me.Label4.Text = ""
 
    End Sub
 
    Public Sub ChangeTexts(ByVal length As Long, ByVal position As Integer, ByVal percent As Integer, ByVal speed As Double)
 
        Me.Label3.Text = "File size: " & Math.Round((length / 1024), 2) & " KB"
 
        Me.Label5.Text = "Downloading: " & Me.txtFileName.Text
 
        Me.Label4.Text = "Downloaded " & Math.Round((position / 1024), 2) & " KB of " & Math.Round((length / 1024), 2) & "KB (" & Me.ProgressBar1.Value & "%)"
 
        If speed = -1 Then
            Me.Label2.Text = "Download speed: calculating..."
        Else
            Me.Label2.Text = "Download speed: " & Math.Round((speed / 1024), 2) & " KB/s"
        End If
 
        Me.ProgressBar1.Value = percent
 
 
    End Sub
 
    Private Sub btnDownload_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDownload.Click
        If Me.txtFileName.Text <> "" AndAlso Me.txtFileName.Text.StartsWith("http://") Then
 
 
            Me.SaveFileDialog1.FileName = Me.txtFileName.Text.Split("/"c)(Me.txtFileName.Text.Split("/"c).Length - 1)
 
            If Me.SaveFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
 
                Me.whereToSave = Me.SaveFileDialog1.FileName
 
                Me.SaveFileDialog1.FileName = ""
 
                Me.Label6.Text = "Save to: " & Me.whereToSave
 
                Me.txtFileName.Enabled = False
                Me.btnDownload.Enabled = False
                Me.btnCancel.Enabled = True
 
                Me.BackgroundWorker1.RunWorkerAsync() 'Start download
 
            End If
 
        Else
 
            MessageBox.Show("Please insert valid URL for download", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning)
 
        End If
    End Sub
 
    Private Sub btnCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancel.Click
        Me.BackgroundWorker1.CancelAsync() 'Send cancel request
        Try
            Me.bckZip.CancelAsync()
        Catch ex As Exception
            'Do Nothing
        End Try
    End Sub
 
    Private Sub BackgroundWorker1_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
 
        'Creating the request and getting the response
        Dim theResponse As HttpWebResponse
        Dim theRequest As HttpWebRequest
        Try 'Checks if the file exist
 
            theRequest = WebRequest.Create(Me.txtFileName.Text)
            theResponse = theRequest.GetResponse
            theRequest.Timeout = 10000000
        Catch ex As Exception
 
            MessageBox.Show("An error occurred while downloading file. Possibe causes:" & ControlChars.CrLf & _
                            "1) File doesn't exist" & ControlChars.CrLf & _
                            "2) Remote server error", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
 
            Dim cancelDelegate As New DownloadCompleteSafe(AddressOf DownloadComplete)
 
            Me.Invoke(cancelDelegate, True)
 
            Exit Sub
        End Try
        Dim length As Long = theResponse.ContentLength 'Size of the response (in bytes)
 
        Dim safedelegate As New ChangeTextsSafe(AddressOf ChangeTexts)
        Me.Invoke(safedelegate, length, 0, 0, 0) 'Invoke the TreadsafeDelegate
 
        Dim writeStream As New IO.FileStream(Me.whereToSave, IO.FileMode.Create)
 
        'Replacement for Stream.Position (webResponse stream doesn't support seek)
        Dim nRead As Integer
 
        'To calculate the download speed
        Dim speedtimer As New Stopwatch
        Dim currentspeed As Double = -1
        Dim readings As Integer = 0
 
        Do
 
            If BackgroundWorker1.CancellationPending Then 'If user abort download
                Exit Do
            End If
 
            speedtimer.Start()
 
            Dim readBytes(4096) As Byte
            Dim bytesread As Integer = theResponse.GetResponseStream.Read(readBytes, 0, 4096)
 
            nRead += bytesread
            Dim percent As Integer = (nRead / length) * 100
 
            Me.Invoke(safedelegate, length, nRead, percent, currentspeed)
 
            If bytesread = 0 Then Exit Do
 
            writeStream.Write(readBytes, 0, bytesread)
 
            speedtimer.Stop()
 
            readings += 1
            If readings >= 5 Then 'For increase precision, the speed it's calculated only every five cicles
                currentspeed = 20480 / (speedtimer.ElapsedMilliseconds / 1000)
                speedtimer.Reset()
                readings = 0
            End If
        Loop
 
        'Close the streams
        theResponse.GetResponseStream.Close()
        writeStream.Close()
 
        If Me.BackgroundWorker1.CancellationPending Then
 
            IO.File.Delete(Me.whereToSave)
 
            Dim cancelDelegate As New DownloadCompleteSafe(AddressOf DownloadComplete)
 
            Me.Invoke(cancelDelegate, True)
 
            Exit Sub
 
        End If
 
        Dim completeDelegate As New DownloadCompleteSafe(AddressOf DownloadComplete)
 
        Me.Invoke(completeDelegate, False)
 
    End Sub

SEO Powered by Platinum SEO from Techblissonline