Thursday, May 31, 2012

Learn LINQ

Introduction

With .NET Framework 3.5 Microsoft released Language Integrated Query aka LINQ. LINQ enables developers to query data sources using a query like syntax with both C# and VB.NET. These data sources can be collections, SQL Server databases, XML, DataSets etc. Other than what is supplied by Microsoft, LINQ is also extensible. This means that you can query data sources beyond what Microsoft ships. Examples of such implementations are LINQ To Flickr, LINQ To Amazon, LINQ to Google etc. In this article I will show you how you can use LINQ To SQL to perform CRUD operations on a SQL Server database. I will use Northwind database and build an ASP.NET application to demonstrated the capabilities of LINQ To SQL. You can download Northwind database here.

Toolset for this article

  1. Visual Studio 2008
  2. .NET Framework 3.5 (This is already installed if you have Visual Studio 2008)
  3. SQL Server 2005 (You can also work with SQL Server Express)

Solution Structure

For this article we will need two projects. One is a data layer (created as a Class Library)which we will generate and the other is an ASP.NET Web Application. The solutions structure looks like this in Solution Explorer.
LINQ

Creating Data Layer

Before we generate our data layer we must create a new connection in Server Explorer which points to Northwind database.
LINQ
We will now generate our data layer using LINQ To SQL. To do this you need to add a new item to the data layer project of type LINQ to SQL Classes. We will name it Northwind as shown below.
LINQ
After adding a LINQ to SQL Class we are presented with a designer surface. Here we can simply drag the tables which will become part of our data layer. For this article we will drag all tables on the designer by selecting them all in one go. Our designer should look like this after dragging all tables on it.
LINQ
We should now build our solution to make sure everything is okay. And that’s it. We have successfully generated our data layer. In Solution Explorer we can see that we have two new files namely Northwind.dbml.layout and Northwind.designer.cs. We can also see that references required to compile and run our code have been added by Visual Studio.
LINQ
The .cs file contains the code for our data layer. Let’s examine the code that has been generated for us. We will look at the Region class.
[Table(Name="dbo.Region")]
public partial class Region : INotifyPropertyChanging, INotifyPropertyChanged
The class itself is decorated with Table attribute and the Name property has been assigned the actual table name we have in our database. Region class also implements INotifyPropertyChanging and INotifyPropertyChanged interfaces. These interfaces are used for databinding. Region class also contains one property per column. Let’s look at the RegionDescription property.
[Column(Storage="_RegionDescription", DbType="NChar(50) NOT NULL",
CanBeNull=false)]
public string RegionDescription
{
  get
  {
    return this._RegionDescription;
  }
  set
  {
    if ((this._RegionDescription != value))
    {
      this.OnRegionDescriptionChanging(value);
      this.SendPropertyChanging();
      this._RegionDescription = value;
      this.SendPropertyChanged("RegionDescription");
      this.OnRegionDescriptionChanged();
    }
  }
}
Columns are decorated with Column attribute and values are passed in for Storage, DbType and CanBeNull which indicates if the column can be null or not.

Using Data Layer

Now that we have generated our data layer. We will work on ASP.NET web application where we will use our data layer. To keep things simple we will create a web forms to search for customers and display search results. We will also create a web form to insert new customers. Let’s start by creating our web form for customer search. For this we will use the Default.aspx page. We will place few controls on the web form. These controls will give us search parameters and a button which will do the search and display results when clicked. This is what the form will look like after placing our controls.
LINQ
We will also place a GridView control on our form to display search results. We will now put in some code in our button’s click event handler to do the search and display results in GridView. Make sure that we have a reference to Data Layer project, System.Data.Linq and appropriate using statement. Here is what our button click event handler will contain.
protected void buttonSearch_Click(object sender, EventArgs e)
{
  using (NorthwindDataContext context = new NorthwindDataContext())
  {
    var customers =
      from c in context.Customers      select c;

    gridViewCustomers.DataSource = customers;
    gridViewCustomers.DataBind();
  }
}
This code will query the customers table in northwind database and will return all customers. We will now modify it slightly to accept customer name and company name as parameters for our query. After modification our event handler looks like this.
protected void buttonSearch_Click(object sender, EventArgs e)
{
  using (NorthwindDataContext context = new NorthwindDataContext())
  {
    var customers =
      from c in context.Customers      where (c.ContactName.Contains(textBoxCustomerName.Text.Trim())
      &&
      c.CompanyName.Contains(textBoxCompanyName.Text.Trim()))
      select c;

    gridViewCustomers.DataSource = customers;
    gridViewCustomers.DataBind();
  }
}
Our search results will now be filtered.
Let us now created a data entry form for customers.  We will insert a new web form in our ASP.NET project and call it CustomerEntry. To start with we will make sure that our form contains fields required to insert a customer. Our form after completion will look like this.
LINQ
We expect a new row to be inserted into customers table when Save Customer button is clicked. This code achieves data insertion into customers table for us.
protected void buttonSave_Click(object sender, EventArgs e)
{
  using (NorthwindDataContext context = new NorthwindDataContext())
  {
    Customer customer = new Customer
    {
      CustomerID = textBoxCustomerID.Text,
      CompanyName = textBoxCompanyName.Text,
      ContactName = textBoxCustomerName.Text,
      ContactTitle = textBoxTitle.Text,
      Address = textBoxAddress.Text,
      City = textBoxCity.Text,
      Region = textBoxRegion.Text,
      PostalCode = textBoxPostalCode.Text,
      Country = textBoxCountry.Text,
      Phone = textBoxPhone.Text,
      Fax = textBoxFax.Text    };

    context.Customers.InsertOnSubmit(customer);
    context.SubmitChanges();
  }
}
Similarly an existing row in database can be updated by first retrieving the data and then submitting it via DataContext.

Conclusion

In this tutorial we have not written a single SQL statement to retrieve or insert data into a database. This is the beauty of LINQ To SQL. Further our retrieval code while in C# looks a lot like a query. We can already appreciate the benefits of such a streamlined and unified approach in dealing with data.

Friday, May 11, 2012

Cross-Site Scripting (XSS) attack


What is Cross-Site Scripting (XSS) attack? How to prevent XSS attack in ASP.Net?
One of my previous article described about Sql injection attack and the ways to prevent Sql Injection attack in ASP.Net applications. You can read the article in the below link,
What is SQL Injection Attack? How to prevent SQL Injection in ASP.Net?
Moving forward, let’s understand the XSS attack and the ways to prevent XSS attack in ASP.Net applications.

What is Cross-Site Scripting (XSS) attack?
Cross-Site scripting which is commonly called XSS attack is a vulnerability that can be found on any web applications. Using this vulnerability, an attacker can take advantage on your application and insert some malicious script that will get executed automatically to accomplish whatever the attacker wants.  For example, an attacker can insert some JavaScript code with the actual input in an input field which in turn will get executed when it is displayed on the browser.
The XSS attack is broadly categorized into 2 types, Stored and Reflected.
A Stored XSS attack is one where the input with the malicious code is saved permanently into a persistent medium like database and will get executed whenever it is displayed or processed. For example, in a comment field an attacker can insert some malicious script which will get executed whenever it is displayed on the browser.
A Reflected XSS attack is one where the malicious script with the input is just processed by the server and is reflected back. For example, the input will be displayed back to the user in a webpage, commonly seen in search pages like “You have searched for xxxx…” or in some places, when you display an error message by including the input from user like “Your input xxx is invalid.” In these cases, if there is a malicious script injected with the input then it will get executed by the browser.
In next section, let’s see some simple XSS attack in ASP.Net application to understand it better.

Simulate XSS attack in ASP.Net
By default, ASP.Net will not allow any HTML tag in any input controls. In this case, you will receive the below error if you input html tags and submit the page.
Note that, you need to set ValidateRequest="false" in those pages where you need to allow HTML input. Open a new ASP.Net project in your visual studio and for time being, set ValidateRequest="false" in the Page directive of Default.aspx page to understand the XSS attack in this article. Now, drag a textbox and a button control in the aspx page. On click of the button, do a Response.Write() of the contents of textbox. Like below,
ASPX
  <asp:TextBox ID="txtMessage" runat="server" TextMode="MultiLine"></asp:TextBox>
        <asp:Button ID="btnSubmit" runat="server" onclick="btnSubmit_Click"
            Text="Submit" />
CodeBehind
 protected void btnSubmit_Click(object sender, EventArgs e)
    {
        Response.Write(txtMessage.Text);
    }

Execute the above page and type the below string as input in the textbox and click submit.
<script>alert('You are hacked!')</script>

Since, we have set ValidateRequest="false" the above malicious script will be rendered in the output html and will get executed. Hence, you will get a alert box saying ‘You are hacked!’. This is called XSS attack. This is a very basic example where an alert script is being inserted which has no impacts. Assume, there is a comment field in your page where you allow HTML input. Now, an attacker or possibly a spammer can insert some script that can redirect the user to his/her page through which he can divert all the traffic to his site that are supposed to visit your page. For example, in the above textbox try giving the below input.
<meta http-equiv="refresh" content="2;url=http://www.codedigest.com/">

The above script will redirect you to www.codedigest.com when the page is rendered back.

Handling XSS attack in ASP.Net
To handle XSS attack in these pages, you can do a HTML encode of the input before processing it. The input once HTML encoded will become void and it will get simply displayed and without getting executed. Hence, you can prevent the XSS attack in the above example by using the below code,
protected void btnSubmit_Click(object sender, EventArgs e)
    {
        Response.Write(Server.HtmlEncode(txtMessage.Text));
    }

The above code will do html encode on the input which will in turn will make the injected script void. So, the above inputs will become like below after encoding,
&lt;script&gt;alert('You are hacked!')&lt;/script&gt;
&lt;meta http-equiv=&quot;refresh&quot; content=&quot;2;url=http://www.codedigest.com/&quot;&gt;
Now, when this is rendered in the browser the HTML tags will be rendered as text(means, as a non executable). Please see below,
<script>alert('You are hacked!')</script>
<meta http-equiv="refresh" content="2;url=http://www.codedigest.com/">
At times, you may need to allow the users to input HTML tags which is then used to display the input with the HTML formatting done by the users. For example, in article/blog posting pages you may need to allow users to format the text with RTF(Rich Text Editors) editors and save it without encoding. In this case, to prevent XSS attack you can restrict users to do some limited formatting by allowing only some specific formatting tags like <B>,<I>,<font>, etc. Also, you can validate the user input in the server to strip the tags that are not allowed or considered to be vulnerable to XSS attack.






Some common XSS attacks in Web world
This section will list some common XSS attack on the web.
1.      An attacker may post some HTML links that can redirect the visitors to his/her page when the users are clicking it. Mostly, seen in comments, forums, etc.
2.      An attacker may post some script that can automatically redirect the user to his/her page.
3.      An attacker may post some malicious script that can steal the logged in user’s session cookie and send the same to him. With the sessionid, attacker can gain access to whatever the user has by using the same sessionid once the user is logged in.
Note: In JavaScript, you can get the cookie using document.cookie property. You can try some tools like burp proxy which can be used to simulate these scenarios by editing the http request and using the sessionid to get into other user’s session.

Conclusion
Nowadays, most of the modern development framework has all the required mechanism to prevent XSS attack. But, we will still need to be cautious whenever we allow users to input HTML tags. Some points to consider,
1.      Don’t set ValidateRequest="false" at Web.Config level. Always, set at page level only for the required pages.
2.      When you set ValidateRequest="false" for a page, make sure you are doing html encode of the input. Prevent html encode only for the required fields.
3.      When providing RTF editors, allow only minimal customizations. Again, validate for malicious tags like <script>, <applet>, <img>, <iframe> etc in the server side and filter them.
For more information on XSS prevention, read the OWASP XSS prevention cheat sheet.