Thursday, July 2, 2009

AJAX

hi....


VISIT THIS SITE HAVING FUN WITH VIDEOS ON AJAX :-

AJAX with www.asp.net/LEARN/ajax-videos/

Monday, May 25, 2009

Navigation From One Page to Another Page with Data.














Navigation From One Page to Another Page with Data.


There are various ways to send the data from one page to other

1> Using QueryString.

e.g.
In first page you can write as follows :

Response.Redirect("mypage.aspx?id=" + value from control or variable or anystring);
mypage.aspx?id=10


Above dummy my page now contains id as the query string
and
It can be retrieved on the other page as follows :

string id = Request.QueryString["id"].ToString();

2> Using Session.
e.g. You can create session in first page like.

Session["id"] = value from control or variable or anystring;
and you can retrive it from other page as following:

string id = Session["id"].ToString();

3>Using Cookies
e.g. You can write cookie as in first page as follows :

Response.Cookies["id"].Value = value from control or variable or anystring;
and to retrive cookie you can request it as follows:

string id = Request.Cookies["BackgroundColor"].Value.ToString();

Friday, May 22, 2009

Advanced Diploma in Software Development






Advanced Diploma in Software Development (ADSD)

About ADSD


Advanced Diploma in Software Development (ADSD) is an autonomous programme that has been specially designed based on IT industry requirements, professional feedback and dynamic research. To achieve the objectives of quality, practical and focused IT education, MET ISDR's ADSD programme ensures excellent IT career opportunities by turning all graduates into industry ready software developers.



ADSD does not require any previous knowledge of programming. Especially for the non-engineering and the non-IT graduates who don't have any programming language in their formal curriculum. This programme requires candidates with good aptitude, analytical and logical skills, so that they can grasp the concepts of programming smoothly.



Right from the Programming Languages & Operating Systems, ADSD will deliver the Enterprise Application Development using the latest platforms so that the students are equipped with all the tools and technologies which will help them in creating their own successful position in the community of knowledge professionals.




Programme Objective


This is a programme specially designed for all the graduates who want to make their career in the IT industry.

Are you eligible?


Successful completion of 10 + 2 + 3 or 4 or equivalent from a recognised University with minimum 50% at degree level.
Computer Science or IT Diploma holders from the recognised technical boards with 2 years of relevant IT experience can apply.


How can I apply?


1. Obtain Application Form and Prospectus, available at MET for Rs. 600/- in cash or DD payable at Mumbai in favour of
'MET ISDR'. You can also pay online (click here) and the same will be sent to you.
2. Fill the Application Form and submit the same with necessary documents (mentioned in the Prospectus).
3. Appear for the Selection Procedure on scheduled date.

Important Dates








1.

Last Date of Form Submission (Registration Closes) June 29, 2009
2.Entrance Exam and Selection Procedure July 05, 2009


Selection Procedure
Based on the performance in the MET CET (consisting of Written Test & Personal Interview).
Programme Modules
The ADSD programme is divided into two parts. Each part consists of four modules. Each module is divided into two units.
Following is the detailed structure:

























Part I - Systems Programming

Part II - Application Programming


Module 1: Programming Foundations

Unit 1: Assembly and C Programming

Unit 2: C++ Programming

Module 5: Web Programming

Unit 1: The Client Side

Unit 2: The Server Side


Module 2: Linux System Programming

Unit 1: The Kernel

Unit 2: The Shell


Module 6: Java Programming

Unit 1: Desktop Java

Unit 2: Distributed Java


Module 3: Windows System Programming

Unit 1: WIN32 Platform SDK

Unit 2: MFC and COM


Module 7: .NET Programming

Unit 1: Desktop .NET

Unit 2: Distributed .NET


Module 4: SE & Project Management
Unit 1: Software Engineering
Unit 2: Project Management


Module 8: Aptitude Skills, Communications & Personality Development
Unit 1: Aptitude Skills
Unit 2: Communications & Personality Development



Each unit spread over 3 weeks, comprises of

1. Theory - 48 hours with maximum of 3 hours daily
2. Practical - 72 hours with minimum of 4 hours daily
Total = 36 weeks (9 months approximately)
* Module 4 & Module 8 will require 15 days each (Total 1 Month)
Total Duration: 10 Months + Project
Programme Fee
The fees for the entire programme is Rs. 1,08,000.
Unique Features
• Unique programme in line with the current requirement of the IT industry
• State-of-the-art computer laboratory
• Interaction with industry professionals on technical & non-technical topics
• Practical hands-on sessions, extended lab sessions
• Industry visits to IT companies
• Educational loan assistance
• Excellent placement assistance
• Free-ships to meritorious and needy students

Opportunites
The Information Technology industry is the fastest growing sector significantly contributing to the Indian economy. The need of trained manpower, professional IT workforce is growing multifold. It is projected that the IT industry will need at least 6,00,000 trained software professionals by this year. And this number is likely to increase in the near future.
ADSD's intensive programme structure is in-line with Industry needs and therefore, assures quality trained IT professionals ready to serve the industry.
Candidates get wide range of opportunities in various sectors of IT Industry. They can make an entry as a Programmer, Software Engineer, Database Programmer, Web Programmer, System Analyst, Business Analyst, Software Tester or join in other departments like Maintenance, Support etc.
Having acquired sound knowledge and skill sets, ADSD graduates can easily accept IT industry challenges, allowing them to succeed in short span of time.

MET has a strong alumni base of over 4000 successful IT professionals worldwide with many of them at top positions in leading companies.
Programme Outline
The unique feature of the APSD programme is that it does not expect any previous knowledge of programming. This way it gives opportunity to all those graduates who have never learnt programming but want to make their career as an IT professional. With their domain knowledge, these professionals will doubtlessly play a key role in meeting the ever-growing demand for quality human resources.
Right from the programming languages & operating systems, this programme will deliver the Enterprise Application Development using the latest platforms so that the students are equipped with all the tools and technologies which will help them in creating their own successful position in the community of knowledge professionals.
Visit Following Site For More Information :
MET ISDR


Sunday, May 3, 2009

In-Depth look at the GridView Control

Introduction:
In this article we will examine more features of the Grid View control. In this article we will see some of the common operations that can be performed using the GridView control. Apart from these operations there are many more functions that can be performed on the control and which we will see in the later articles.

Adding a SqlDataSource and binding to GridView Control:
In this article I will be using the Northwind database which comes with SQL Server 2000. In the last article I explained how easy it is to bind the Grid View control to the SqlDataSource. You can perform all these actions using the wizard. If you want to code and bind the datasource you can easily perform it using the following code sample:

void Page_Load(object sender, EventArgs e)
{

if (!Page.IsPostBack)
{

// Binds the data

BindData();

}

}

public void BindData()
{

// you can use this line

string connectionString = myDataSource.ConnectionString;

// you can also use this line since by using the SqlDataSource it makes an entry in the
// web.config file if that is what choose to do
//string connectionString = (string)ConfigurationSettings.AppSettings["ConnectionString"];
// if you are using Enterprise Library you can also use
//string connectionString = (string)ConfigurationSettings.ConnectionStrings["ConnectionString"];

SqlConnection myConnection = new SqlConnection(connectionString);

SqlDataAdapter ad = new SqlDataAdapter("SELECT * FROM Categories", myConnection);

DataSet ds = new DataSet();

ad.Fill(ds, "Categories");

myGridView.DataSource = ds;

myGridView.DataBind();

}


You will need to set the Bound column in order to see the text in the cells of the grid view control. This can be easily done by using the Smart tag which appears when you right click on the grid view control.



I have also added a Status column to show you the checkbox column feature. The Status column is a simple bit field whose value can be either 1 or 0. If you are using Access database you can choose Yes/No Column. Once you have set up all your columns and execute the page it will display something like this:



At this moment if you try to select the Checkbox column, meaning if you try to check or uncheck the Status column it won't work. Let's see how we can make it work with our grid view control.

In the above image you see that the Checkboxes are not marked. The reason is because in the database the Checkbox column is NULL. If you make the column value to either 1 or 0 you will see check marks where the value is 1. See the image below and you will have a better idea of what I mean.



Editing in the Grid View Control
You can easily add the editing, updating, selecting, paging and sorting capabilities to your grid view control. Just add a new command column and you will be asked to add whatever functionality you desire.

If you are using the SqlDataSource to bind to the GridView control you will get most of the features by just using the SqlDataSource wizard. Since we are binding the control at runtime we need to add most of the functionality manually.

Edit Mode:
The fields that are marked readonly = false will change into TextBoxes when the Row_Editing event triggers. Like DataGrid control its easy to set the fields in the edit mode.

// Editing mode

void myGridView_RowEditing(object sender, GridViewEditEventArgs e)
{

myGridView.EditIndex = e.NewEditIndex;

BindData();

}

Cancel Edit:
If you don't like to edit the row you can press cancel link button which will fire the RowCancelingEdit event. The code to turn the row back to its original form is quite simple and straight forward.

// Cancel Edit Mode

void myGridView_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{

myGridView.EditIndex = -1;

BindData();

}

Selecting Row:
Selecting row event is fired when you make a click on the select link. If you need any particular item in that row you can easily select it using the cells property:

// Selecting row

void myGridView_SelectedIndexChanged(object sender, EventArgs e)
{

// This will contain the selectedValue of the row

string selectedCategory = myGridView.SelectedRow.Cells[1].Text;

}


The Cells start with index '0' which means Cell[0] is CategoryID , Cell[1] is CategoryName and so on.

Update Row:
For Updating the row we first need to get the value from the row that is entered by the user into the TextBox. For this purpose you can change the bound column into a Template column which will make is easier to locate the item.

After changing the CategoryName column to a tem plated column we can easily use the RowUpdating event to find the Text entered by the user.

void myGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
{

GridViewRow row = myGridView.Rows[e.RowIndex];

if (row != null)

{

TextBox t = row.FindControl("TextBox1") as TextBox;

if (t != null)

{

Response.Write("The Text Entered is" + t.Text);

}

}

Paging:
Paging can also be easily enabled in the grid view control. Its just like DataGrid from Asp.net 1.1. First you need to make set the allow paging property to true. And you can also set the page size. Here is a small code sample that will enable paging.

// Grid View Paging

void myGridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
{

myGridView.PageIndex = e.NewPageIndex;

BindData();

}

Here is a small image shown below of paging. I have limited the page size to 3 so that the distribution of page will take place. In the image below we are in the page number 2.



Using SqlDataSource to execute commands:
You can also use the powerful SqlDataSource control to run and make your query. The SqlDataSource also contains the QUERY builder interface which can enhance the user experience in making SQL Queries. Apart from the SELECT query there are also INSERT, DELETE and UPDATE query builders wizards that you can use in your application.

When you use SqlDataSource you gets the advantage of having the paging, sorting implemented automatically which is pretty cool in some cases.

In the next article we will see some more features of the Grid View control. I hope you liked the article

Happy Programming !

Encryption and Decryption Functions

Microsoft provides very good classes for encryption and decryption under the following namespace.
System.Security.Cryptography.
Coding Sample Given as follows:

using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;
using System.Security.Cryptography;

///
/// Class which contains static reusable methods for encrypting a string.
/// Mainly constructed for URL encryption but further can be used for string encryption
/// needed in other operation.
///

public class Cryptex
{
public Cryptex()
{
//
// TODO: Add constructor logic here
//
}

internal static HttpServerUtility sUtil = HttpContext.Current.Server;

///
/// Method used to encrypt a string making use of DES Algorithm.
///

///
///
///
public static string StringEncrypt_DES(string queryString) {

DESCryptoServiceProvider des = new DESCryptoServiceProvider();
string key = ConfigurationManager.AppSettings["DESCryptokey"];

des.Key = Encoding.UTF8.GetBytes(key.Substring(0, 8));
des.IV = Encoding.UTF8.GetBytes(key.Substring(0, 8));
ICryptoTransform cryptotransform = des.CreateEncryptor();
try {
MemoryStream mStream = new MemoryStream();
CryptoStream cryptostream = new CryptoStream(mStream, cryptotransform, CryptoStreamMode.Write);
StreamWriter writer = new StreamWriter(cryptostream);

writer.WriteLine(queryString);
writer.Close();
cryptostream.Close();

byte[] buffer = mStream.ToArray();
mStream.Close();
return Convert.ToBase64String(buffer);
}
catch {
throw;
}
return string.Empty;
}

///
/// Method used to dencrypt a string making use of DES Algorithm.
///

///
///
///
public static string StringDecrypt_DES(string queryString) {

DESCryptoServiceProvider des = new DESCryptoServiceProvider();
string key = ConfigurationManager.AppSettings["DESCryptokey"];

des.Key = Encoding.UTF8.GetBytes(key.Substring(0, 8));
des.IV = Encoding.UTF8.GetBytes(key.Substring(0, 8));
try {
queryString = sUtil.UrlDecode(queryString);

byte[] buffer = Convert.FromBase64String(queryString.Trim());

MemoryStream mStream = new MemoryStream(buffer);
ICryptoTransform cryptotransform = des.CreateDecryptor();
CryptoStream cryptostream = new CryptoStream(mStream, cryptotransform, CryptoStreamMode.Read);

StreamReader reader = new StreamReader(cryptostream);

queryString = reader.ReadLine();
reader.Close();
cryptostream.Close();
mStream.Close();
}
catch {
throw;
}
return queryString;
}

///
/// Method used to encrypt a string making use of RC2 Algorithm.
///

///
///
///
public static string StringEncrypt_RC2(string inputString, string key) {

RC2CryptoServiceProvider rc2 = new RC2CryptoServiceProvider();
rc2.Mode = CipherMode.CBC;

rc2.Key = ASCIIEncoding.ASCII.GetBytes(key);
rc2.IV = ASCIIEncoding.ASCII.GetBytes(key);
ICryptoTransform cryptotransform = rc2.CreateEncryptor();
return encrypt(inputString, cryptotransform);
}
///
/// Method used to dencrypt a string making use of RC2 Algorithm.
///

///
///
///
public static string StringDecrypt_RC2(string inputString, string key) {

RC2CryptoServiceProvider rc2 = new RC2CryptoServiceProvider();
rc2.Mode = CipherMode.CBC;

rc2.Key = ASCIIEncoding.ASCII.GetBytes(key);
rc2.IV = ASCIIEncoding.ASCII.GetBytes(key);
ICryptoTransform cryptotransform = rc2.CreateDecryptor();
return decrypt(inputString, cryptotransform);
}
///
/// Method used to encrypt a string making use of Rijndael Algorithm.
///

///
///
///
public static string StringEncrypt_RIJNDAEL(string inputString, string key) {

Rijndael rijndael = new RijndaelManaged();
rijndael.Mode = CipherMode.CBC;
rijndael.Key = ASCIIEncoding.ASCII.GetBytes(key);
rijndael.IV = ASCIIEncoding.ASCII.GetBytes(key);
ICryptoTransform cryptotransform = rijndael.CreateEncryptor();
return encrypt(inputString, cryptotransform);
}

///
/// Method used to dencrypt a string making use of Rijndael Algorithm.
///

///
///
///
public static string StringDecrypt_RIJNDAEL(string inputString, string key) {

Rijndael rijndael = new RijndaelManaged();
rijndael.Mode = CipherMode.CBC;
rijndael.Key = ASCIIEncoding.ASCII.GetBytes(key);
rijndael.IV = ASCIIEncoding.ASCII.GetBytes(key);
ICryptoTransform cryptotransform = rijndael.CreateDecryptor();
return decrypt(inputString, cryptotransform);
}

protected static string encrypt(string Str, ICryptoTransform cryptotransform) {
try {
MemoryStream mStream = new MemoryStream();
CryptoStream cryptostream = new CryptoStream(mStream, cryptotransform, CryptoStreamMode.Write);
StreamWriter writer = new StreamWriter(cryptostream);

writer.WriteLine(Str.Trim());
writer.Close();
cryptostream.Close();

byte[] buffer = mStream.ToArray();
mStream.Close();
Str = sUtil.UrlEncode(Convert.ToBase64String(buffer));
}
catch{
throw;
}
return Str;
}

protected static string decrypt(string Str, ICryptoTransform cryptotransform) {
try {
Str = sUtil.UrlDecode(Str.Trim());
byte[] buffer = Convert.FromBase64String(Str);

MemoryStream mStream = new MemoryStream(buffer);
CryptoStream cryptostream = new CryptoStream(mStream, cryptotransform, CryptoStreamMode.Read);
StreamReader reader = new StreamReader(cryptostream);
Str = reader.ReadLine();
reader.Close();
cryptostream.Close();
mStream.Close();
}
catch {
throw;
}
return Str;
}

const string DESKey = "AQWSEDRF";
const string DESIV = "AQWSEDRF";

public static string DESDecrypt(string stringToDecrypt)//Decrypt the content
{
byte[] key;
byte[] IV;

byte[] inputByteArray;
try {
key = Convert2ByteArray(DESKey);
IV = Convert2ByteArray(DESIV);
int len = stringToDecrypt.Length; inputByteArray = Convert.FromBase64String(stringToDecrypt);
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(key, IV), CryptoStreamMode.Write);
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
Encoding encoding = Encoding.UTF8; return encoding.GetString(ms.ToArray());
}
catch (System.Exception ex) {
throw ex;
}
}

public static string DESEncrypt(string stringToEncrypt)// Encrypt the content
{
byte[] key;
byte[] IV;

byte[] inputByteArray;
try {
key = Convert2ByteArray(DESKey);
IV = Convert2ByteArray(DESIV);
inputByteArray = Encoding.UTF8.GetBytes(stringToEncrypt);
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(key, IV), CryptoStreamMode.Write);
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
return Convert.ToBase64String(ms.ToArray());
}
catch (System.Exception ex) {
throw ex;
}
}

static byte[] Convert2ByteArray(string strInput) {

int intCounter; char[] arrChar;
arrChar = strInput.ToCharArray();
byte[] arrByte = new byte[arrChar.Length];
for (intCounter = 0; intCounter <= arrByte.Length - 1; intCounter++)
arrByte[intCounter] = Convert.ToByte(arrChar[intCounter]);
return arrByte;
}
}



For More Info Follow Following Link :

http://msdn.microsoft.com/en-us/library/system.security.cryptography.asnencodeddataenumerator.aspx

Friday, March 20, 2009

Read Excel Database using ADO.Net

Excel is nothing but the other database only. It can be set like below
The table example as follows :
e.g. Student.xls
Here
-------------------------------------
Database ---------------Table
(Excel Workbook)------ (Excel Sheet)
-------------------------------------
Student.xls------------- personal_info
-------------------------------------
id ------- Name -------- Address
1 ------- Sachin -------- Patan
2 ------- Sam ---------- New Lands

Now below given code gives you access for the excel database.

C# code snippet

-----------------------------
using System;
using System.Data;
class Test{
public static void Main(){
IDbConnection con = new System.Data.Odbc.OdbcConnection("Driver={Microsoft Excel Driver (*.xls)};DBQ=db\\Student.xls");

// The above line is for connection string.
con.Open();
IDbCommand cmd = con.CreateCommand();
cmd.CommandText = "select id,name,address from [personal_info$]";

//Here the personal_info$ is the worksheet i.e. (table) of Student.xls Workbook i.e. (Database).
IDataReader reader = cmd.ExecuteReader();
while(reader.Read()){
Console.WriteLine("{0, -6}{1}{2}", reader.GetInt32(0), reader[1], reader["address"]);

// We can retrieve data with given three ways

// as reader.GetInt32(0) ----------> Gives first field.

// reader[1] ------------------------>Gives second field.

// reader["address"] --------------->Gives third field.
}
reader.Close();
con.Close();
}
}

Finding or Verifying Credit Card Numbers

With a few simple regular expressions, you can easily verify whether your customer entered a valid credit card number on your order form. You can even determine the type of credit card being used. Each card issuer has its own range of card numbers, identified by the first 4 digits.

You can use a slightly different regular expression to find credit card numbers, or number sequences that might be credit card numbers, within larger documents. This can be very useful to prove in a security audit that you're not improperly exposing your clients' financial details.

We'll start with the order form.

Stripping Spaces and Dashes
The first step is to remove all non-digits from the card number entered by the customer. Physical credit cards have spaces within the card number to group the digits, making it easier for humans to read or type in. So your order form should accept card numbers with spaces or dashes in them.

To remove all non-digits from the card number, simply use the "replace all" function in your scripting language to search for the regex [^0-9]+ and replace it with nothing. If you only want to replace spaces and dashes, you could use [ -]+. If this regex looks odd, remember that in a character class, the hyphen is a literal when it occurs right before the closing bracket (or right after the opening bracket or negating caret).

If you're wondering what the plus is for: that's for performance. If the input has consecutive non-digits, e.g. 1===2, then the regex will match the three equals signs at once, and delete them in one replacement. Without the plus, three replacements would be required. In this case, the savings are only a few microseconds. But it's a good habit to keep regex efficiency in the back of your mind. Though the savings are minimal here, so is the effort of typing the extra plus.

Validating Credit Card Numbers on Your Order Form
Validating credit card numbers is the ideal job for regular expressions. They're just a sequence of 13 to 16 digits, with a few specific digits at the start that identify the card issuer. You can use the specific regular expressions below to alert customers when they try to use a kind of card you don't accept, or to route orders using different cards to different processors. All these regexes were taken from RegexBuddy's library.

Visa: ^4[0-9]{12}(?:[0-9]{3})?$

All Visa card numbers start with a 4. New cards have 16 digits. Old cards have 13.

MasterCard: ^5[1-5][0-9]{14}$

All MasterCard numbers start with the numbers 51 through 55. All have 16 digits.

American Express: ^3[47][0-9]{13}$

American Express card numbers start with 34 or 37 and have 15 digits.

Diners Club: ^3(?:0[0-5][68][0-9])[0-9]{11}$

Diners Club card numbers begin with 300 through 305, 36 or 38. All have 14 digits. There are Diners Club cards that begin with 5 and have 16 digits. These are a joint venture between Diners Club and MasterCard, and should be processed like a MasterCard.

Discover: ^6(?:0115[0-9]{2})[0-9]{12}$

Discover card numbers begin with 6011 or 65. All have 16 digits.

JCB: ^(?:2131180035\d{3})\d{11}$

JCB cards beginning with 2131 or 1800 have 15 digits. JCB cards beginning with 35 have 16 digits.
If you just want to check whether the card number looks valid, without determining the brand, you can combine the above six regexes into
^(?:4[0-9]{12}(?:[0-9]{3})?5[1-5][0-9]{14}6(?:0115[0-9][0-9])[0-9]{12}3[47][0-9]{13}3(?:0[0-5][68][0-9])[0-9]{11}(?:2131180035\d{3})\d{11})$.

You'll see I've simply alternated all the regexes, and used a non-capturing group to put the anchors outside the alternation. You can easily delete the card types you don't accept from the list.

These regular expressions will easily catch numbers that are invalid because the customer entered too many or too few digits. They won't catch numbers with incorrect digits. For that, you need to follow the Luhn algorithm, which cannot be done with a regex. And of course, even if the number is mathematically valid, that doesn't mean a card with this number was issued or if there's money in the account. The benefit or the regular expression is that you can put it in a bit of JavaScript to instantly check for obvious errors, instead of making the customer wait 30 seconds for your credit card processor to fail the order. And if your card processor charges for failed transactions, you'll really want to implement both the regex and the Luhn validation.

Finding Credit Card Numbers in Documents
With two simple modifications, you could use any of the above regexes to find card numbers in larger documents. Simply replace the caret and dollar with a word boundary,
e.g.: \b4[0-9]{12}(?:[0-9]{3})?\b.

If you're planning to search a large document server, a simpler regular expression will speed up the search. Unless your company uses 16-digit numbers for other purposes, you'll have few false positives. The regex \b\d{13,16}\b will find any sequence of 13 to 16 digits.

When searching a hard disk full of files, you can't strip out spaces and dashes first like you can when validating a single card number. To find card numbers with spaces or dashes in them, use \b(?:\d[ -]*){13,16}\b. This regex allows any amount of spaces and dashes anywhere in the number. This is really the only way. Visa and MasterCard put digits in sets of 4, while Amex and Discover use groups of 4, 5 and 6 digits. People typing in the numbers may have different ideas yet.

MVC Pattern of .NET




The Model-View-Controller (MVC) architectural pattern separates an application into three main components: the model, the view, and the controller. The ASP.NET MVC framework provides an alternative to the ASP.NET Web Forms pattern for creating MVC-based Web applications. The ASP.NET MVC framework is a lightweight, highly testable presentation framework that (as with Web Forms-based applications) is integrated with existing ASP.NET features, such as master pages and membership-based authentication. The MVC framework is defined in the System.Web.Mvc namespace and is a fundamental, supported part of the System.Web namespace.

MVC is a standard design pattern that many developers are familiar with. Some types of Web applications will benefit from the MVC framework. Others will continue to use the traditional ASP.NET application pattern that is based on Web Forms and postbacks. Other types of Web applications will combine the two approaches; neither approach excludes the other.

The MVC framework includes the following components:


Figure 01: Invoking a controller action that expects a parameter value (Click to view full-size image)
• Models. Model objects are the parts of the application that implement the logic for the application's data domain. Often, model objects retrieve and store model state in a database. For example, a Product object might retrieve information from a database, operate on it, and then write updated information back to a Products table in SQL Server.

In small applications, the model is often a conceptual separation instead of a physical one. For example, if the application only reads a data set and sends it to the view, the application does not have a physical model layer and associated classes. In that case, the data set takes on the role of a model object.
• Views. Views are the components that display the application's user interface (UI). Typically, this UI is created from the model data. An example would be an edit view of a Products table that displays text boxes, drop-down lists, and check boxes based on the current state of a Products object.

• Controllers. Controllers are the components that handle user interaction, work with the model, and ultimately select a view to render that displays UI. In an MVC application, the view only displays information; the controller handles and responds to user input and interaction. For example, the controller handles query-string values, and passes these values to the model, which in turn queries the database by using the values.

The MVC pattern helps you create applications that separate the different aspects of the application (input logic, business logic, and UI logic), while providing a loose coupling between these elements. The pattern specifies where each kind of logic should be located in the application. The UI logic belongs in the view. Input logic belongs in the controller. Business logic belongs in the model. This separation helps you manage complexity when you build an application, because it enables you to focus on one aspect of the implementation at a time. For example, you can focus on the view without depending on the business logic.

In addition to managing complexity, the MVC pattern makes it easier to test applications than it is to test a Web Forms-based ASP.NET Web application. For example, in a Web Forms-based ASP.NET Web application, a single class is used both to display output and to respond to user input. Writing automated tests for Web Forms-based ASP.NET applications can be complex, because to test an individual page, you must instantiate the page class, all its child controls, and additional dependent classes in the application. Because so many classes are instantiated to run the page, it can be hard to write tests that focus exclusively on individual parts of the application. Tests for Web Forms-based ASP.NET applications can therefore be more difficult to implement than tests in an MVC application. Moreover, tests in a Web Forms-based ASP.NET application require a Web server. The MVC framework decouples the components and makes heavy use of interfaces, which makes it possible to test individual components in isolation from the rest of the framework.

The loose coupling between the three main components of an MVC application also promotes parallel development. For instance, one developer can work on the view, a second developer can work on the controller logic, and a third developer can focus on the business logic in the model.
Deciding When to Create an MVC Application
You must consider carefully whether to implement a Web application by using either the ASP.NET MVC framework or the ASP.NET Web Forms model. The MVC framework does not replace the Web Forms model; you can use either framework for Web applications. (If you have existing Web Forms-based applications, these continue to work exactly as they always have.)

Before you decide to use the MVC framework or the Web Forms model for a specific Web site, weigh the advantages of each approach.
Advantages of an MVC-Based Web Application
The ASP.NET MVC framework offers the following advantages:
• It makes it easier to manage complexity by dividing an application into the model, the view, and the controller.
• It does not use view state or server-based forms. This makes the MVC framework ideal for developers who want full control over the behavior of an application.
• It uses a Front Controller pattern that processes Web application requests through a single controller. This enables you to design an application that supports a rich routing infrastructure. For more information, see Front Controller on the MSDN Web site.
• It provides better support for test-driven development (TDD).
• It works well for Web applications that are supported by large teams of developers and Web designers who need a high degree of control over the application behavior.

Advantages of a Web Forms-Based Web Application
The Web Forms-based framework offers the following advantages:
• It supports an event model that preserves state over HTTP, which benefits line-of-business Web application development. The Web Forms-based application provides dozens of events that are supported in hundreds of server controls.
• It uses a Page Controller pattern that adds functionality to individual pages. For more information, see Page Controller on the MSDN Web site.
• It uses view state or server-based forms, which can make managing state information easier.
• It works well for small teams of Web developers and designers who want to take advantage of the large number of components available for rapid application development.
• In general, it is less complex for application development, because the components (the Page class, controls, and so on) are tightly integrated and usually require less code than the MVC model.
Features of the ASP.NET MVC Framework
The ASP.NET MVC framework provides the following features:
• Separation of application tasks (input logic, business logic, and UI logic), testability, and test-driven development (TDD) by default. All core contracts in the MVC framework are interface-based and can be tested by using mock objects, which are simulated objects that imitate the behavior of actual objects in the application. You can unit-test the application without having to run the controllers in an ASP.NET process, which makes unit testing fast and flexible. You can use any unit-testing framework that is compatible with the .NET Framework.
• An extensible and pluggable framework. The components of the ASP.NET MVC framework are designed so that they can be easily replaced or customized. You can plug in your own view engine, URL routing policy, action-method parameter serialization, and other components. The ASP.NET MVC framework also supports the use of Dependency Injection (DI) and Inversion of Control (IOC) container models. DI allows you to inject objects into a class, instead of relying on the class to create the object itself. IOC specifies that if an object requires another object, the first objects should get the second object from an outside source such as a configuration file. This makes testing easier.
• A powerful URL-mapping component that lets you build applications that have comprehensible and searchable URLs. URLs do not have to include file-name extensions, and are designed to support URL naming patterns that work well for search engine optimization (SEO) and representational state transfer (REST) addressing.
• Support for using the markup in existing ASP.NET page (.aspx files), user control (.ascx files), and master page (.master files) markup files as view templates. You can use existing ASP.NET features with the ASP.NET MVC framework, such as nested master pages, in-line expressions (<%= %>), declarative server controls, templates, data-binding, localization, and so on.
• Support for existing ASP.NET features. ASP.NET MVC lets you use features such as forms authentication and Windows authentication, URL authorization, membership and roles, output and data caching, session and profile state management, health monitoring, the configuration system, and the provider architecture.

Thursday, March 19, 2009

Building Secure ASP.NET Pages and Controls

Threats and Countermeasures
Most Web application attacks require that malicious input is passed within HTTP requests. The general goal is either to coerce the application into performing unauthorized operations or to disrupt its normal operation. This is why thorough input validation is an essential countermeasure to many attacks and should be made a top priority when you develop ASP.NET Web pages and controls. Top threats include:
Code injection
Session hijacking
Identity spoofing
Parameter manipulation
Network eavesdropping
Information disclosure
Figure 10.1 highlights the most common threats to Web applications.
Figure 10.1
Common threats to ASP.NET Web pages and controls
Code Injection
Code injection occurs when an attacker causes arbitrary code to run using your application's security context. The risk increases if your application runs using a privileged account.
Attacks
There are various types of code injection attacks. These include:
Cross-site scripting. Malicious script is sent to a Web application as input. It is echoed back to a user's browser, where it is executed.
Buffer overflows. The type safe verification of managed code reduces the risk significantly, but your application is still vulnerable, especially where it calls unmanaged code. Buffer overflows can allow an attacker to execute arbitrary code inside your Web application process, using its security context.
SQL injection. This attack targets vulnerable data access code. The attacker sends SQL input that alters the intended query or executes completely new queries in the database. Forms authentication logon pages are common targets because the username and password are used to query the user store.
Vulnerabilities
Vulnerabilities that can lead to successful code injection attacks include:
Weak or missing input validation or reliance on client-side input validation
Including unvalidated input in HTML output
Dynamically constructing SQL statements that do not use typed parameters
Use of over-privileged process accounts and database logins
Countermeasures
The following countermeasures can be used to prevent code injection:
Validate input so that an attacker cannot inject script code or cause buffer overflows.
Encode all output that includes input. This prevents potentially malicious script tags from being interpreted as code by the client's browser.
Use stored procedures that accept parameters to prevent malicious SQL input from being treated as executable statements by the database.
Use least privileged process and impersonation accounts. This mitigates risk and reduces the damage that can be done if an attacker manages to execute code using the application's security context.
Session Hijacking
Session hijacking occurs when the attacker captures an authentication token and takes control of another user's session. Authentication tokens are often stored in cookies or in URLs. If the attacker captures the authentication token, he can transmit it to the application along with a request. The application associates the request with the legitimate user's session, which allows the attacker to gain access to the restricted areas of the application that require authenticated access. The attacker then assumes the identity and privileges of the legitimate user.
Vulnerabilities
Common vulnerabilities that make your Web pages and controls susceptible to session hijacking include:
Unprotected session identifiers in URLs
Mixing personalization cookies with authentication cookies
Authentication cookies passed over unencrypted links
Attacks
Session hijacking attacks include:
Cookie replay. The attacker captures the authentication cookie either by using network monitoring software or by some other means, for example, by exploiting an XSS scripting vulnerability.
Query string manipulation. A malicious user changes the session identifier that is clearly visible in the URL query string.
Countermeasures
You can employ the following countermeasures to prevent session hijacking:
Separate personalization and authentication cookies.
Only transmit authentication cookies over HTTPS connections.
Do not pass session identifiers that represent authenticated users in query strings.
Re-authenticate the user before critical operations, such as order placement, money transfers, and so on, are performed.
Identity Spoofing
Identity spoofing occurs when a malicious user assumes the identity of a legitimate user so that he can access the application.
Vulnerabilities
Common vulnerabilities that make your Web pages and controls susceptible to an identity spoofing attack include:
Authentication credentials that are passed over unencrypted links
Authentication cookies that are passed over unencrypted links
Weak passwords and policies
Weak credential storage in the user store
Attacks
Identity spoofing attacks include:
Cookie replay. The attacker steals the authentication cookie either by using network monitoring software or by using an XSS attack. The attacker then sends the cookie to the application to gain spoofed access.
Brute force password attacks. The attacker repeatedly tries username and password combinations.
Dictionary attacks. In this automated form of a brute force password attack, every word in a dictionary is tried as a password.
Countermeasures
You can employ the following countermeasures to prevent identity spoofing:
Only transmit authentication credentials and cookies over HTTPS connections.
Enforce strong passwords. Regular expressions can be used to ensure that user-supplied passwords meet suitable complexity requirements.
Store password verifiers in the database. Store non-reversible password hashes combined with a random salt value to mitigate the risk of dictionary attacks.
For more information about storing password hashes and other secrets in the database, see Chapter 14, "Building Secure Data Access."
Parameter Manipulation
Parameters are the items of data that are passed from the client to the server over the network. They include form fields, query strings, view state, cookies, and HTTP headers. If sensitive data or data that is used to make security decisions on the server are passed using unprotected parameters, your application is potentially vulnerable to information disclosure or unauthorized access.
Vulnerabilities
Vulnerabilities that can lead to parameter manipulation include:
Using hidden form fields or query strings that contain sensitive data
Passing cookies that contain security-sensitive data over unencrypted connections
Attacks
Parameter manipulation attacks include:
Cookie replay attacks. The attacker captures and alters a cookie and then replays it to the application. This can easily lead to identity spoofing and elevation or privileges if the cookie contains data that is used for authentication or authorization on the server.
Manipulation of hidden form fields. These fields contain data used for security decisions on the server.
Manipulation of query string parameters.
Countermeasures
You can employ the following countermeasures to prevent parameter manipulation:
Do not rely on client-side state management options. Avoid using any of the client-side state management options such as view state, cookies, query strings or hidden form fields to store sensitive data.
Store sensitive data on the server. Use a session token to associate the user's session with sensitive data items that are maintained on the server.
Use a message authentication code (MAC) to protect the session token. Pair this with authentication, authorization, and business logic on the server to ensure that the token is not being replayed.
Network Eavesdropping
Network eavesdropping involves using network monitoring software to trace packets of data sent between browser and Web server. This can lead to the disclosure of application-specific confidential data, the retrieval of logon credentials, or the capture of authentication cookies.
Vulnerabilities
Vulnerabilities that can lead to successful network eavesdropping include:
Lack of encryption when sending sensitive data
Sending authentication cookies over unencrypted channels
Attacks
Network eavesdropping attacks are performed by using packet sniffing tools that are placed on the network to capture traffic.
Countermeasures
To counter network eavesdropping, use Secure Sockets Layer (SSL) to provide an encrypted communication channel between browser and Web server. It is imperative that SSL is used whenever credentials, authentication tickets, or sensitive application data are sent over the network.
Information Disclosure
Information disclosure occurs when an attacker probes your Web pages looking for ways to cause exception conditions. This can be a fruitful exercise for the attacker because exception details, which often are returned as HTML and displayed in the browser, can divulge extremely useful information, such as stack traces that contain database connection strings, database names, database schema information, SQL statements, and operating system and platform versions.
Vulnerabilities
Vulnerabilities that lead to information disclosure include:
Weak exception handling
Letting raw exception details propagate to the client
Attacks
There are many attacks that can result in information disclosure. These include:
Buffer overflows.
Sending deliberately malformed input.
Countermeasures
To prevent information disclosure:
Use structured exception handling.
Return generic error pages to the client.
Use default redirect pages that contain generic and harmless error messages.
Design Considerations
Before you develop Web pages and controls, there are a number of important issues that you should consider at design time. The following are the key considerations:
Use server-side input validation.
Partition your Web site.
Consider the identity that is used for resource access.
Protect credentials and authentication tickets.
Fail securely.
Consider authorization granularity.
Place Web controls and user controls in separate assemblies.
Place resource access code in a separate assembly.
Use Server-Side Input Validation
At design time, identify all the various sources of user input that your Web pages and controls process. This includes form fields, query strings, and cookies received from the Web user, as well as data from back-end data sources. The Web user clearly lives outside your application's trust boundary, so all of the input from that source must be validated at the server. Unless you can absolutely trust the data retrieved from back-end data sources, that data should also be validated and sanitized before it is sent to the client. Make sure your solution does not rely on client-side validation because this is easily bypassed.
Partition Your Web Site
Your Web site design should clearly differentiate between publicly accessible areas and restricted areas that require authenticated access. Use separate subdirectories beneath your application's virtual root directory to maintain restricted pages, such as checkout functionality in a classic e-commerce Web site that requires authenticated access and transmits sensitive data such as credit card numbers. Separate subdirectories allow you to apply additional security (for example, by requiring SSL) without incurring SSL performance overhead across the entire site. It also allows you to mitigate the risk of session hijacking by restricting the transmission of authentication cookies to HTTPS connections. Figure 10.2 shows a typical partitioning.
Figure 10.2
A Web site partitioned into public and secure areas
Note that in Figure 10.2, the restricted subfolder is configured in Internet Information Services (IIS) to require SSL access. The first element in Web.config allows all users to access the public area, while the second element prevents unauthenticated users from accessing the contents of the secured subfolder and forces a login.
For more information about restricting authentication cookies so that they are passed only over HTTPS connections and about how to navigate between restricted and non-restricted pages, see "Use Absolute URLs for Navigation" in the "Authentication" section of this chapter.
Consider the Identity That Is Used for Resource Access
By default, ASP.NET applications do not impersonate, and the least privileged ASP.NET process account is used to run ASP.NET Web applications and for resource access. The default is the recommended configuration. There are several situations in which you may want to use a different Windows security context for resource access. These include:
Hosting multiple applications on the same server
You can use IIS to configure each application to use a separate anonymous Internet user account and then enable impersonation. Each application then has a distinct identity for resource access. For more information about this approach, see Chapter 20, "Hosting Multiple ASP.NET Applications."
Note If your applications run on Windows Server 2003 with IIS 6.0, you can use application pools and configure each application to run in its own worker process that provides process-level isolation. By default, all applications run in a default application pool. With application pools, you can configure each process to run using a separate identity and, as a result, you do not need to use impersonation. For more information, see "How To: Improve Security When Hosting Multiple Applications in ASP.NET 2.0."
Accessing a remote resource with specific authentication requirements
If you need to access a specific remote resource (for example, a file share) and have been given a particular Windows account to use, you can use configure this account as the anonymous Web user account for your application. Then you can use programmatic impersonation prior to accessing the specific remote resource. For more information, see "Impersonation" later in this chapter.
Protect Credentials and Authentication Tickets
Your design should factor in how to protect credentials and authentication tickets. Credentials need to be secured if they are passed across the network and while they are in persistent stores such as configuration files. Authentication tickets must be secured over the network because they are vulnerable to hijacking. Encryption provides a solution. SSL or IPSec can be used to protect credentials and tickets over the network and DPAPI provides a good solution for encrypting credentials in configuration files.
Fail Securely
If your application fails with an unrecoverable exception condition, make sure that it fails securely and does not leave the system wide open. Make sure the exception details that are valuable to a malicious user are not allowed to propagate to the client and that generic error pages are returned instead. Plan to handle errors using structured exception handling, rather than relying on method error codes.
Consider Authorization Granularity
Consider the authorization granularity that you use in the authenticated parts of your site. If you have configured a directory to require authentication, should all users have equal access to the pages in that directory? If necessary, you can apply different authorization rules for separate pages based on the identity, or more commonly, the role membership of the caller, by using multiple elements within separate elements.
For example, two pages in the same directory can have different and elements in Web.config.
Place Web Controls and User Controls in Separate Assemblies
When Web controls and user controls are put in their own assemblies, you can configure security for each assembly independently by using code access security policy. This provides additional flexibility for the administrator and it means that you are not forced to grant extended permissions to all controls just to satisfy the requirements of a single control.
Place Resource Access Code in a Separate Assembly
Use separate assemblies and call them from your page classes rather than embedding resource access code in your page class event handlers. This provides greater flexibility for code access security policy and is particularly important for building partial-trust Web applications. For more information, see Chapter 9, "Using Code Access Security with ASP.NET."
Input Validation
If you make unfounded assumptions about the type, length, format, or range of input, your application is unlikely to be robust. Input validation can become a security issue if an attacker discovers that you have made unfounded assumptions. The attacker can then supply carefully crafted input that compromises your application. The misplaced trust of user input is one of the most common and devastating vulnerabilities in Web applications.
Constrain, Then Sanitize
Start by constraining input and check for known good data by validating for type, length, format, and range. Sometimes you also need to sanitize input and make potentially malicious input safe. For example, if your application supports free-format input fields, such as comment fields, you might want to permit certain "safe" HTML elements, such as and , and strip out any other HTML elements. The following table summarizes the options that are available for constraining and sanitizing data:
Table 10.1 Options for Constraining and Sanitizing Data
Requirement
Options
Type checks
.NET Framework type system. Parse string data, convert to a strong type, and then handle FormatExceptions.
Regular expressions. Use ASP.NET RegularExpressionValidator control or Regex class.
Length checks
Regular expressions
String.Length property
Format checks
Regular expressions for pattern matching
.NET Framework type system
Range checks
ASP.NET RangeValidator control (supports currency, date, integer, double, and string data)
Typed data comparisons
Regular Expressions
You can use regular expressions to restrict the range of valid characters, to strip unwanted characters, and to perform length and format checks. You can constrain input format by defining patterns that the input must match. ASP.NET provides the RegularExpressionValidator control and the Regex class is available from the System.Text.RegularExpressions namespace.
If you use the validator controls, validation succeeds if the control is empty. For mandatory fields, use a RequiredFieldValidator. Also, the regular expression validation implementation is slightly different on the client and server. On the client, the regular expression syntax of Microsoft JScript® development software is used. On the server, System.Text.RegularExpressions.Regex syntax is used. Since JScript regular expression syntax is a subset of System.Text.RegularExpressions.Regex syntax, it is recommended that JScript regular expression syntax be used to yield the same results on both the client and the server.
For more information about the full range of ASP.NET validator controls, refer to the .NET Framework documentation.
RegularExpressionValidator Control
To validate Web form field input, you can use the RegularExpressionValidator control. Drag the control onto a Web form and set its ValidationExpression, ControlToValidate, and ErrorMessage properties.
You can set the validation expression using the properties window in Microsoft Visual Studio .NET or you can set the property dynamically in the Page_Load event handler. The latter approach allows you to group together all of the regular expressions for all controls on the page.
Regex Class
If you use regular HTML controls with no runat="server" property (which rules out using the RegularExpressionValidator control), or you need to validate input from other sources such as query strings or cookies, you can use the Regex class either in your page class or in a validation helper method, possibly in a separate assembly. Some examples are shown later in this section.

Secure Your Web.config

1. Custom Errors Disabled------------------------------ When you disable custom errors as shown below, ASP.NET provides a detailed error message to
clients by default.
In itself, knowing the source of an error may not seem like a risk to application security, but
consider this: the more information a hacker can gather about a Web site, the more likely it is that
he will be able to successfully attack it. An error message can be a gold mine of information to an
attacker. A default ASP.NET error message lists the specific versions of ASP.NET and the .NET
framework which are being used by the Web server, as well as the type of exception that was thrown.
Just knowing which Web-based applications are used (in this case ASP.NET) compromises application
security by telling the attacker that the server is running a relatively recent version of Microsoft
Windows and that Microsoft Internet Information Server (IIS) 6.0 or later is being used as the Web
server. The type of exception thrown may also help the attacker to profile Web-based applications;
for example, if a "SqlException" is thrown, then the attacker knows that the application is using
some version of Microsoft SQL Server. You can build up application security to prevent such information leakage by modifying the mode
attribute of the element to "On" or "RemoteOnly." This setting instructs Web-based
applications to display a nondescript, generic error message when an unhandled exception is
generated. Another way to circumvent this application security issue is to redirect the user to a
new page when errors occur by setting the "defaultRedirect" attribute of the element.
This approach can provide even better application security because the default generic error page
still gives away too much information about the system (namely, that it's using a Web.config file,
which reveals that the server is running ASP.NET).
2. Leaving Tracing Enabled in Web-Based ApplicationsThe trace feature of ASP.NET is one of the most useful tools that you can use to ensure application
security by debugging and profiling your Web-based applications. Unfortunately, it is also one of
the most useful tools that a hacker can use to attack your Web-based applications if it is left
enabled in a production environment.


When the element is enabled for remote users of Web-based applications (localOnly="false"),
any user can view an incredibly detailed list of recent requests to the application simply by
browsing to the page "trace.axd." If a detailed exception message is like a gold mine to a hacker
looking to circumvent application security, a trace log is like Fort Knox! A trace log presents a
wealth of information: the .NET and ASP.NET versions that the server is running; a complete trace of
all the page methods that the request caused, including their times of execution; the session state
and application state keys; the request and response cookies; the complete set of request headers,
form variables, and QueryString variables; and finally the complete set of server variables.
A hacker looking for a way around application security would obviously find the form variable
histories useful because these might include email addresses that could be harvested and sold to
spammers, IDs and passwords that could be used to impersonate the user, or credit card and bank
account numbers. Even the most innocent-looking piece of data in the trace collection can be
dangerous in the wrong hands. For example, the "APPL_PHYSICAL_PATH" server variable, which contains
the physical path of Web-based applications on the server, could help an attacker perform directory
traversal attacks against the system.
The best way to prevent a hacker from obtaining trace data from Web-based applications is to disable
the trace viewer completely by setting the "enabled" attribute of the element to "false." If
you have to have the trace viewer enabled, either to debug or to profile your application, then be
sure to set the "localOnly" attribute of the element to "true." That allows users to access
the trace viewer only from the Web server and disables viewing it from any remote machine,
increasing your application security.
3. Debugging EnabledDeploying Web-based applications in debug mode is a very common mistake. Virtually all Web-based
applications require some debugging. Visual Studio 2005 will even automatically modify the
Web.config file to allow debugging when you start to debug your application. And, since deploying
ASP.NET applications is as simple as copying the files from the development folder into the
deployment folder, it's easy to see how development configuration settings can accidentally make it
into production, compromising application security
Like the first two application security vulnerabilities described in this list, leaving debugging
enabled is dangerous because you are providing inside information to end users who shouldn't have
access to it, and who may use it to attack your Web-based applications. For example, if you have
enabled debugging and disabled custom errors in your application, then any error message displayed
to an end user of your Web-based applications will include not only the server information, a
detailed exception message, and a stack trace, but also the actual source code of the page where the
error occurred.
Unfortunately, this configuration setting isn't the only way that source code might be displayed to
the user. Here's a story that illustrates why developers shouldn't concentrate solely on one type of
configuration setting to improve application security. In early versions of Microsoft's ASP.NET AJAX
framework, some controls would return a stack trace with source code to the client browser whenever
exceptions occurred. This behavior happened whenever debugging was enabled, regardless of the custom
error setting in the configuration. So, even if you properly configured your Web-based applications
to display non-descriptive messages when errors occurred, you could still have unexpectedly revealed
your source code to your end users if you forgot to disable debugging.
To disable debugging, set the value of the "debug" attribute of the element to
"false." This is the default value of the setting, but as we will see in part two of this article,
it's safer to explicitly set the desired value rather than relying on the defaults to protect
application security.
4. Cookies Accessible through Client-Side ScriptIn Internet Explorer 6.0, Microsoft introduced a new cookie property called "HttpOnly." While you
can set the property programmatically on a per-cookie basis, you also can set it globally in the
site configuration.
Any cookie marked with this property will be accessible only from server-side code, and not to any
client-side scripting code like JavaScript or VBScript. This shielding of cookies from the client
helps to protect Web-based applications from Cross-Site Scripting attacks. A hacker initiates a
Cross-Site Scripting (also called CSS or XSS) attack by attempting to insert his own script code
into the Web page to get around any application security in place. Any page that accepts input from
a user and echoes that input back is potentially vulnerable. For example, a login page that prompts
for a user name and password and then displays "Welcome back, " on a successful login may
be susceptible to an XSS attack.
Message boards, forums, and wikis are also often vulnerable to application security issues. In these
sites, legitimate users post their thoughts or opinions, which are then visible to all other
visitors to the site. But an attacker, rather than posting about the current topic, will instead
post a message such as "alert(document.cookie);

". The message board now includes
the attacker's script code in its page code-and the browser then interprets and executes it for
future site visitors. Usually attackers use such script code to try to obtain the user's
authentication token (usually stored in a cookie), which they could then use to impersonate the
user. When cookies are marked with the "HttpOnly" property, their values are hidden from the client,
so this attack will fail.
As mentioned earlier, it is possible to enable "HttpOnly" programmatically on any individual cookie
by setting the "HttpOnly" property of the "HttpCookie" object to "true." However, it is easier and
more reliable to configure the application to automatically enable "HttpOnly" for all cookies. To do
this, set the "httpOnlyCookies" attribute of the element to "true."
5. Cookieless Session State EnabledIn the initial 1.0 release of ASP.NET, you had no choice about how to transmit the session token
between requests when your Web application needed to maintain session state: it was always stored in
a cookie. Unfortunately, this meant that users who would not accept cookies could not use your
application. So, in ASP.NET 1.1, Microsoft added support for cookieless session tokens via use of
the "cookieless" setting.

Web applications configured to use cookieless session state now stored the session token in the page
URLs rather than a cookie. For example, the page URL might change from
http://myserver/MyApplication/default.aspx to
http://myserver/MyApplication/(123456789ABCDEFG)/default.aspx. In this case, "123456789ABCDEFG"
represents the current user's session token. A different user browsing the site at the same time
would receive a completely different session token, resulting in a different URL, such as
http://myserver/MyApplication/(ZYXWVU987654321)/default.aspx.
While adding support for cookieless session state did improve the usability of ASP.NET Web
applications for users who would not accept cookies, it also had the side effect of making those
applications much more vulnerable to session hijacking attacks. Session hijacking is basically a
form of identity theft wherein a hacker impersonates a legitimate user by stealing his session
token. When the session token is transmitted in a cookie, and the request is made on a secure
channel (that is, it uses SSL), the token is secure. However, when the session token is included as
part of the URL, it is much easier for a hacker to find and steal it. By using a network monitoring
tool (also known as a "sniffer") or by obtaining a recent request log, hijacking the user's session
becomes a simple matter of browsing to the URL containing the stolen unique session token. The Web
application has no way of knowing that this new request with session token "123456789ABCDEFG" is not
coming from the original, legitimate user. It happily loads the corresponding session state and
returns the response back to the hacker, who has now effectively impersonated the user.
The most effective way to prevent these session hijacking attacks is to force your Web application
to use cookies to store the session token. This is accomplished by setting the "cookieless"
attribute of the element to "UseCookies" or "false." But what about the users who do
not accept cookies? Do you have to choose between making your application available to all users
versus ensuring that it operates securely for all users? A compromise between the two is possible in
ASP.NET 2.0. By setting the "cookieless" attribute to "AutoDetect," the application will store the
session token in a cookie for users who accept them and in the URL for those who won't. This means
that only the users who use cookieless tokens will still be vulnerable to session hijacking. That's
often acceptable, given the alternative-that users who deny cookies wouldn't be able to use the
application at all. It is ironic that many users disable cookies because of privacy concerns when
doing so can actually make them more prone to attack.
6. Cookieless Authentication Enabled
Just as in the "Cookieless Session State Enabled" vulnerability discussed in part one, enabling
cookieless authentication in your Web-based applications can lead to session hijacking and problems
with application security.


When a session or authentication token appears in the request URL rather than in a secure cookie, an
attacker with a network monitoring tool can get around application security, easily take over that
session, and effectively impersonate a legitimate user. However, session hijacking has far more
serious consequences for application security after a user has been authenticated. For example,
online shopping sites generally utilize Web-based applications that allow users to browse without
having to provide an ID and password. But when users are ready to make a purchase, or when they want
to view their order status, they have to login and be authenticated by the system. After logging in,
sites provide access to more sensitive data, such as a user's order history, billing address, and
credit card number. Attackers hijacking this user's session before authentication can't usually
obtain much useful information. But if the attacker hijacks the session after authentication, all
that sensitive information could be compromised.
The best way to prevent session hijacking with Web-based applications is to disable cookieless
authentication and force the use of cookies for storing authentication tokens. This application
security measure is added by changing the cookieless attribute of the forms element to the value
UseCookies.
7. Failure to Require SSL for Authentication Cookies
Web-based applications use the Secure Sockets Layer (SSL) protocol to encrypt data passed between
the Web server and the client. Using SSL for application security means that attackers using network
sniffers will not be able to interpret the exchanged data. Rather than seeing plaintext requests and
responses, they will see only an indecipherable jumble of meaningless characters.
You can require the forms authentication cookie from your Web-based applications to use SSL by
setting the requireSSL attribute of the forms element to true.

The previous section discussed the importance of transmitting the authentication token in a cookie,
rather than embedding it in the request URL. However, disabling cookieless authentication is just
the first step towards securing the authentication token. Unless requests made to the Web server are
encrypted, a network sniffer will still be able to read the authentication token from the request
cookie. An attacker would still be able to hijack the user's session.
At this point, you might be wondering why it is necessary with application security to disable
cookieless authentication, since it is very inconvenient for users who won't accept cookies, and
seeing as how the request still has to be sent over SSL. The answer is that the request URL is often
persisted regardless of whether or not it was sent via SSL. Most major browsers save the complete
URL in the browser history cache. If the history cache were to be compromised, the user's login
credentials would be as well. Therefore, to truly secure the authentication token, you must require
the authentication token to be stored in a cookie, and use SSL to ensure that the cookie be
transmitted securely.
By setting the requireSSL attribute of the forms element to true, ASP.NET Web-based applications
will use a secure connection when transmitting the authentication cookie to the Web server. Note
that IIS requires additional configuration steps to support SSL. You can find instructions to
configure SSL for IIS on MSDN
(http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/56bdf977-14f8-4867-9c51-
34c346d48b04.mspx?mfr=true).
8. Sliding Expiration Used
All authenticated ASP.NET sessions have a timeout interval to protect the application security. The
default timeout value is 30 minutes. So, 30 minutes after a user first logs into any of these
Web-based applications, he will automatically be logged out and forced to re-authenticate his
credentials.
Vulnerable configuration:




Secure configuration:




The slidingExpiration setting is an application security measure used to reduce risk to Web-based
applications in case the authentication token is stolen. When set to false, the specified timeout
interval becomes a fixed period of time from the initial login, rather than a period of inactivity.
Attackers using a stolen authentication token have, at maximum, only the specified length of time to
impersonate the user before the session times out. Because typical attackers of these Web-based
applications have only the token, and don't really know the user's credentials, they can't log back
in as the legitimate user, so the stolen authentication token is now useless and the application
security threat is mitigated. When sliding expiration is enabled, as long as an attacker makes at
least one request to the system every 15 minutes (or half of the timeout interval), the session will
remain open indefinitely. This gives attackers more opportunities to steal information and cause
other mischief in Web-based applications.
To avoid this application security issue altogether, you can disable sliding expiration by setting
the slidingExpiration attribute of the forms element to false.
9. Non-Unique Authentication Cookie Used
Over the last few sections, I hope I have successfully demonstrated the importance of application
security and of storing your application's authentication token in a secure cookie value. But a
cookie is more than just a value; it is a name-value pair. As strange as it seems, an improperly
chosen cookie name can create an application security vulnerability just as dangerous as an
improperly chosen storage location.
Vulnerable configuration:




Secure configuration:




The default value for the name of the authentication cookie is .ASPXAUTH. If you have only one
Web-based application on your server, then .ASPXAUTH is a perfectly secure choice for the cookie
name. In fact, any choice would be secure. But, when your server runs multiple ASP.NET Web-based
applications, it becomes critical to assign a unique authentication cookie name to each application.
If the names are not unique, then users logging into any of the Web-based applications might
inadvertently gain access to all of them. For example, a user logging into the online shopping site
to view his order history might find that he is now able to access the administration application on
the same site and change the prices of the items in his shopping cart.
The best way to ensure that all Web-based applications on your server have their own set of
authorized users is to change the authentication cookie name to a unique value. Globally Unique
Identifiers (GUIDs) are excellent choices for application security since they are guaranteed to be
unique. Microsoft Visual Studio helpfully includes a tool that will automatically generate a GUID
for you. You can find this tool in the Tools menu with the command name "Create GUID". Copy the
generated GUID into the name attribute of the forms element in the configuration file.
10. Hardcoded Credentials Used



A fundamental difficulty of creating software is that the environment in which the application will
be deployed is usually not the same environment in which it is created. In a production environment,
the operating system may be different, the hardware on which the application runs may be more or
less powerful, and test databases are replaced with live databases. This is an issue for creating
Web-based applications that require authentication because developers and administrators often use
test credentials to test the application security. This begs the question: Where do the test
credentials come from?
For convenience, to avoid forcing developers from spending time on creating a credential store used
solely for test purposes (and which would subsequently be discarded when the application went to
production), Microsoft added a section to the Web.config file that you can use to quickly add test
users to Web-based applications. For each test user, the developer adds an element to the
configuration file with the desired user ID and password as shown below:








While undeniably convenient for development purposes, this was never intended for use in a
production environment. Storing login credentials in plaintext in a configuration file is simply not
secure. Anyone with read access to the Web.config file could access the authenticated Web
application. It is possible to store the SHA-1 or MD5 hash of the password value, rather than
storing the password in plaintext. This is somewhat better, but it is still not a secure solution.
Using this method, the user name is still not encrypted. First, providing a known user name to a
potential attacker makes it easier to perform a brute force attack against the system. Second, there
are many reverse-lookup databases of SHA-1 and MD5 hash values available on the Internet. If the
password is simple, such as a word found in a dictionary, then it is almost guaranteed to be found
in one of these hash dictionaries.
The most secure way to store login credentials is to not store them in the configuration file.
Remove the credentials element from your Web.config files in production applications.
You're Not Out of the Woods Yet
Now that you've finished reading the top-ten list, and you've checked your configuration settings,
your applications are secure forever, right? Not just yet. Web.config files operate in a
hierarchical inheritance manner. Every Web.config file inherits values from any Web.config file in a
parent directory. That Web.config file in turn inherits values from any Web.config file in its
parent directory, and so on. All Web.config files on the system inherit from the global
configuration file called Machine.config located in the .NET framework directory. The effect of this
is that the runtime behavior of your application can be altered simply by modifying a configuration
file in a higher directory.
This can sometimes have unexpected consequences. A system administrator might make a change in a
configuration file in response to a problem with a completely separate application, but that change
might create a security vulnerability in your application. For example, a user might report that he
is not able to access the application without enabling cookies in his browser. The administrator,
trying to be helpful, modifies the global configuration file to allow cookieless authentication for
all applications.