pavanarya

Let us share the knowledge

XSS Attacks in .Net

with 3 comments

Hi in this post i want to write about Xss attacks and sql injection attacks.

XSS Attacks

An Xss atatck can also be called as “Cross Site Scripting” attack.
An XSS attack is an attack that takes places in Web application if we don’t take proper measures. It enables an attacker to inject malicious client side code into the web pages and which can effect genuine users.

What an attacker can do with XSS attack:

There are number of issues that can be caused by XSS attcks and i am discussing few of them.

1.Suppose if a website is storing secure information in the cookies then the attacker can alter or view that information using java script.

2.If some information like userid or username or password were stored in cookies without encrypting that can create lot of damage as the attacker can change the cookie randomly and access the data of other users.

3.Another major issue is an attacker can create unwanted alert boxes in the real or production sites.

4.Breaking a website by injecting javascript that can lead to other exception like Buffer overflow.

5. Another major issue is the attacker can create a fake site which looks exactly like your site and redirect users of your site to his site .There can all the information that you provide(This is also called as Phishing).

6.Attacker can send email’s to people and these url’s they look good but in the query string parameters sometimes they append some malicious java script code and if we click on that url then they will execute malicious code on our machine like worms and trojons.

Now let us see how our web applications can be attacked using some code

Examples Of XSS Attacks In .Net

Getting cookie value

I am creating a simple aspx page that contains a label that dispalys the username retrieving from database.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" ValidateRequest="false" EnableEventValidation="false" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>
    </title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <h2><asp:Label ID="displayUser" runat=server></asp:Label></h2>
    </div>
    </form>
</body>
</html>

Now in the aspx.cs file i am having the code that returns username and password values from the login database table.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;

public partial class Default2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        
        SqlConnection con = new SqlConnection(@"Data Source=PAVAN-0C7A4C6E4\SQLEXPRESS;Initial Catalog=Express; Trusted_Connection = True");
        con.Open();
        String sql = "select * from login1";
        SqlCommand cmd = new SqlCommand(sql);
        cmd.Connection = con;
        SqlDataReader reader= cmd.ExecuteReader();
        string username = "";
        string password = "";
        while (reader.Read())
        {
           username = Convert.ToString(reader["username"]);
            password = Convert.ToString(reader["password"]);
        }
        con.Close();
       displayUser.Text = username;
        HttpCookie cookuser=new HttpCookie("username",username);
        HttpCookie cookpass=new HttpCookie("password",password);

        Response.Cookies.Add(cookuser);
        Response.Cookies.Add(cookpass);
    }
}

In the above file we are getting data from login1 table and assign the value to the label in aspx page and then we are keeping the username and password values in the cookies so that we can make use of them across the application.

After running the application an attacker can get this cookie information by entering the following script in the address bar of the browser and it will display all the cookies information in an alert box.

javascript:alert(document.cookie);

In the similar fashion if we have any sensitive data in the cookie then the attacker can get that.

Modifying cookie value

Generally some websites they store some information like userid and username in the cookies without encrypting and they will make use of this cookie data in some other pages.

Now the attacker can get the cookie data as mentioned in the above process and modify the cookie information. Now if he navigates to a page that is making use of userid from cookie then the attacker will be getting all the information of the user that was modified in the cookie.

Code for modifying the cookie information.

javascript: void(document.cookie="username=arya;path=/");

There are number of attributes for a cookie like path,domain and expiration time and we can also set them just like above one.

Now let us see how to inject the javascript into the web pages.

Injecting Javascript Into Web Pages

For demonstrating this i am creating 2 aspx pages.
1.Registration.aspx
2.Default.aspx

in registration.aspx i am having 2 text box one for username and the other for password and i am inserting the data entered in these input controls and without validation i am going to insert them into database.
In Default.aspx i am retrieving the data from the database table and displaying that to the end user

Default.aspx and Default.aspx.cs code was already given in one of the examples above. Just to prevent redundancy i am not repeating that.

Code for Registration.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Registration.aspx.cs" Inherits="Registration" EnableEventValidation="false" ValidateRequest="false" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    Username:<asp:TextBox runat="server" ID="tst"></asp:TextBox>
    Password:<asp:TextBox runat="server" ID="pwd"></asp:TextBox>
    <asp:Button runat="server" ID="btn" onclick="btn_Click" />
    </div>
    </form>
</body>
</html>

in the above code i am having 2 input controls(text boxes) and a button and on button click event i am inserting the data entered into databse without any validation

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;

public partial class Registration : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }
    protected void btn_Click(object sender, EventArgs e)
    {
        try
        {
           SqlConnection con = new SqlConnection(@"Data Source=PAVAN-0C7A4C6E4\SQLEXPRESS;Initial Catalog=Express; Trusted_Connection = True");
            string Username = tst.Text;
            string password = pwd.Text;
            con.Open();
            String sql = "insert into login values ('"+ Username + "','" + password + "','Pavan','Aryasomayajulu')";
            SqlCommand cmd = new SqlCommand(sql);
            cmd.Connection = con;
            cmd.ExecuteNonQuery();
            con.Close();
        }
        catch (Exception ex)
        {
        }
    }
}

The mistake that we are doing in the above code is we are not validating the inputs given by the user and inserting that into database.

Now the user can enter some javascript values into the database for username and when are rendering that in default.aspx page by assigning the value username to the text box then the javascript code will be executed.

Now i will show how the application reacts for different inputs by the attacker.

1. Creating unwanted alert box.

Let us assume that user A he opened the registration.aspx page and gave below javascript in the username textbox.

<script>alert('You are attacked by the malware')</script>

After sometime User B opens Default.aspx page to see the list of users present in the application then he will be getting an alert box displaying “You are attacked by a malware”.

2.Injecting code that creates buffer over flow
User A enters below code that calls a javascript function recursively
for username

<script>function pavan() {pavan();}pavan();</script>

3. Redirecting the user to attackers website

In registration page enter below javascript code

<script>window.location.href("http:\\pavanarya.wordpress.com")</script>                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      

So when ever some user tries to visit Default.aspx then it will be automatically redirected to the above mentioned url.

Preventing XSS Attacks

So from my above examples what we understand the reasons for XSS attacks.

1. If we don’t protect our cookies by encrypting the values present in the cookie there are chances of xss attacks on our site.

2. By declaring cookies as secure and https only we can prevent these attacks on cookies to some extent.

3.Validating the user inputs can save us from xss atatcks to maximum extent.

4. Escaping or encoding the the response that we are going to write to a web page.
Like alert(‘hai’)
can be encoded to <script>alert(‘hai’);</script>
So that this prevent the execution of script when the out is written to a page.

Important Note

Asp.Net has inbuilt protection from Xss atatcks.There is a page level attribute called ValidateRequest. By default this is set to true and if we want to make it false the we can do that by seeting the value to false

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" ValidateRequest="false" EnableEventValidation="false" %>

In all my above example i made it false to show how xss attacks take place.
Thanks,
Pavan

About these ads

Written by pavanarya

January 26, 2012 at 10:29 pm

Posted in Asp.net, Java script

3 Responses

Subscribe to comments with RSS.

  1. good article but in asp.net 4.0 by setting ValidateRequest=”false” will not allow any script to entered to database (suppose we have no validation) .4.0 will never allow .in my case a message comes to me “A potentially dangerous Request.Form value was detected from the client (Address=”alert(‘You a…”). “.
    To insert script code to our database through c# code we have to set in web.config under System.Web tag only then after the ValidateRequest=”false” will work in 4.0…………………………

    rahul rathore

    June 21, 2012 at 11:45 am

  2. alert(‘hai’);

    tom

    August 6, 2013 at 12:24 pm


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 69 other followers

%d bloggers like this: