Sunday, September 14, 2008

Document Security Over IIS Using Form Authentication

We all rely on asp.net authorization technique to protect our forms from anonymous access. But what about documents like pdf, images or other type of documents? By default, if anybody type the direct URL of a document in the browser’s address bar then IIS6 permit them to see the physical document without checking the authentication permission. Its a big threat for secured web-site. To solve the issue, we have to configure IIS such a way so that aspnet_isapi.dll take the control to show the document while request will come. Here is what it can be done:

1. Right click on the virtual directory which need to be secured and select property. From the opened dialogue box select Virtual Directory tab and click on configuration button. Now add a new configuration with the following settings

Executable: aspnet_isapi.dll location

Extension: document extension (like .pdf)

Verbs: GET

clip_image001

2. Add Location path to web.config file

<location path="temp-pdf">

    <system.web>

      <authorization>

        <deny users="?" />

      </authorization>

    </system.web>

  </location>

That’s it. You are done. Now if you want that the document will be handle by custom code for extra security then you can add a entry in the http handler in the following way:

1. Add a entry to httphandlers section to handle the file type for extra security in web.config file

 

<httpHandlers>

      <add verb="*" path="*.pdf" type="PdfHandler" validate="false"/>

</httpHandlers>

2. And create a custom class to App_Code following way:

Public Class PdfHandler

    Implements IHttpHandler

 

    Public Sub New()

    End Sub

    Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest

        Dim path As String = context.Request.PhysicalPath

        Dim name As String = path.Split("\"c)(path.Split("\"c).Length - 1)

        If Not String.IsNullOrEmpty(path) AndAlso path.ToLower().EndsWith(".pdf") Then

            context.Response.ClearHeaders()

            context.Response.ClearContent()

            context.Response.Clear()

 

            context.Response.Charset = Nothing

            context.Response.ContentType = "application/pdf"

            context.Response.AddHeader("Content-Type", "application/pdf")

            context.Response.AppendHeader("Content-Disposition", String.Format("inline;filename={0}", name))

            context.Response.WriteFile(path)

        Else

            Throw New FileNotFoundException("The page requested is invalid", path)

        End If

    End Sub

    Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable

        Get

            Return False

        End Get

    End Property

End Class

 

Note: You can replace the above code with your custom requirements.

Happy Programming!

Advantage and Disadvantage of Using XML and XSLT

After getting request from few of my blog readers, I am here to describe some major advantages and disadvantages of using XML and XSLT:

Advantages:

1. XSLT applies user defined transformations to an XML document and the output can be HTML, XML, or any other structured document. So it is easy to merge XML data into presentation.

2. XPath used by XSLT to locate elements/attribute within an XML document. So it is more convenient way to traverse an XML document rather than a traditional way, by using scripting language.

3. Being template based, XSLT is more resilient to changes in documents than low level DOM and SAX.

4. By separating data (XML document) from the presentation (XSLT), it is very easy to change the output format in any time easily without touching the code-behind.

5. Using XML and XSLT, the application UI script will look clean and will be easier to maintain

6. XSLT templates are based on XPath pattern which is very powerful in terms of performance to process the XML document

7. XSLT can be used as a validation language as it uses tree-pattern-matching approach.

8. XML is platform independent.

9. XML has column flexibility, so it can be update easily rather than a traditional table-row-column approach

10. XML Supports Unicode

11. XML has self-documenting capability

Disadvantages:

1. It is difficult to implement complicate business rules in XSLT

2. Changing variable value in looping, is difficult in XSLT

3. Using XSLT have performance penalty in some cases as its engine don’t optimize code by using caching technique like traditional compiler.

4. XML encourage non-relational data structure(de-normalized)

 

Happy Programming!

Wednesday, August 27, 2008

Browser Back Button Security

Sometimes, we have to work for secured project where even  browser cache can be a problematic things. Normally in ASP.Net web application, every page is cached by the web browser. So, anybody can thief potential information from the web pages using back button if the user forget to close the browser after sign-out. Sometimes its create a embarrassing situation. But we can kill the cache on the spot easily by adding the following two lines in every page’s PageLoad event which will disable the browser back button functionality in ASP.Net application :

Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetAllowResponseInBrowserHistory(false);

The above two line is enough to say the browser not to cache the page. However, you can also add the following three line for better performance

Response.CacheControl = "NO-CACHE";
Response.AddHeader("Pragma", "no-cache");
Response.Expires = -1;

which is the equivalent of the following meta tag

<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Expires" content="-1">
<meta http-equiv="CACHE-CONTROL" content="NO-CACHE">

Also don’t forget to set authorization in configuration file. So that application will force the user to login page:


<location path="admin">
    <system.web>
      <authorization>
        <deny users="?"/>
        <allow users="*"/>
      </authorization>
    </system.web>
  </location>

Enjoy Programming!

Saturday, August 23, 2008

Building ASP.NET Web Server Controls using XML and XSLT

XML(Extensible Markup Language) and XSLT(Extensible Style-sheet Language Transformations) are very popular in terms of use in programming. XML has a vast use in web application because of column flexibility and platform independence ability. Because of column flexibility, programmers can increase or decrease a column anytime without changing much code (like different types of address such as home address, office address, etc). On the other hand, XSLT can traverse XML faster which can operate with lots of XML data quickly and can give the application a dynamic layout without touching any single line of code from the code-behind. So the combination of XML and XSLT can show its own strength and beauty which can boost up our application. Normally XSLT can produce plain XML or HTML without any hassle. But in some cases, plain XML or HTML might not work rather than we might need ASP.Net server controls since they have some valuable events (click event, data binding event, data bound event, etc) and other advanced functionality like state management, input validation, etc. If we want to create our ASP.NET server controls by using XML and XSLT then we should follow some procedures. I have described those procedures with example in my article which has been published in www.aspalliance.com 

Enjoy Programming!!!

read more | digg story

SQL Injection and XSS in Classic ASP

SQL Injection and XSS(cross site scripting) is a big threat for classic asp sites in present days. Before coming ASP.Net in the market, ASP was the very popular scripting language. As a result, there are a good number of e-commerce and enterprise level project already exist using classic asp in the market. According to various source, from the very Beginning of this year, all the asp sites is the main target for SQL Injection and XSS by hackers. Since ASP.net have some built-in mechanism to sanitize input like “ValidateRequest”,”EnableEventValidation”, etc so this is quite safe position regarding XSS. Let me explain very quickly about XSS and SQL Injection:

  • SQL Injection is a technique by which hackers can execute dangerous SQL commands by taking advantage of un-sanitized input opportunities in web application.
  • Cross-Site Scripting(XSS) attacks exploit vulnerabilities in Web page validation by injecting client-side script code. The script code embeds itself in response data, which is sent back to an unsuspecting user. The user's browser then runs the script code. The browser has no way of recognizing that the code is not legitimate, and Microsoft Internet Explorer security zones provide no defense. Cross-site scripting attacks also work over HTTP and HTTPS (SSL) connections.

Several communities have already started a few workarounds on these issues. HP Web Security Research Group published a tool named HP Scrawlr, to find out SQL Injection vulnerabilities in web-sites. Also, Microsoft recently released source code analyzer for SQL Injection. Let me show that how we can protect our valuable site from this threat:

1. A very fast and easy way is to make a central validation system which is very similar approach of ASP.net built-in system. It will inspect all the input variables(form variable, query-string variable, cookie variable,etc) for the vulnerabilities automatically. It will protect the web site not only from SQL injection but also from XSS. Here is one of my research work, how to make such a system. In a really quick description, it will cover the following areas:

  • Sanitize all the input fields
  • How to make exception list to give the user flexibility
  • Default error page forwarding, if any problem found in input fields
  • Implement a automated reporting system while problem found with details information of inputs,IP,referrer page,etc
  • Implement a custom error page

2. Avoid disclosing database error information by using try…catch and custom error page.

3. Use escape character routines to handle special characters. For example replace the single quote(‘) by the following way:

Replace(Request.Form("txtUsername"), "'", "''")

so that any SQL injection code will be treat like a normal string and will be protect to execute.

4. Use Html encode and decode techniques to show html data. This technique will protect the site from XSS specially.

5. Use stored procedures rather than dynamic query where possible and parameterize query incase of dynamic query

6. Use a least privileged database account- only stored procedure will have the permission for update/insert and script will have only read permission

If all the above rules maintain in a site then no worry about SQL injection and XSS. But sometimes it is really very tough; like  to convert all the inline query to stored procedure. In that case, we have to implement as much as possible. The first technique will ensure that site secured from the threat and make a primary security layer. the second technique will make the site more stronger and make second security layer then the third and so on.

Reference:

http://aspalliance.com/1703_SQL_Injection_in_Classic_ASP_and_Possible_Solutions

http://en.wikipedia.org/wiki/Cross-site_scripting

http://en.wikipedia.org/wiki/Sql_injection

Enjoy Programming!

read more| digg story

Friday, June 13, 2008

Add, Update, Delete Key Value in Web Configuration File from Code Behind

Add Key:

Configuration objConfig = WebConfigurationManager.OpenWebConfiguration("~");
AppSettingsSection objAppsettings
=(AppSettingsSection)objConfig.GetSection("appSettings");
objAppsettings.Settings.Add("apiusername", "ehsan4u");
objAppsettings.Settings.Add("apipassword", "ehsan4u");
objConfig.Save();

Note: It is not recommended as any change in the web.config file will restart the Web server and refresh the cache entries.

Read Key Value:

Specific Key Value:

ConfigurationSettings.AppSettings["apiusername"]

All key Value:

Configuration objConfig = WebConfigurationManager.OpenWebConfiguration("~");
AppSettingsSection objAppsettings =
(AppSettingsSection)objConfig.GetSection("appSettings");

if (objAppsettings != null) {

foreach (string key in appSettings.Settings.AllKeys) {
  string value = appSettings.Settings[key].Value;
   Response.Write(string.Format("Key: {0} Value: {1}", key, value));
}
}


Update a Value:

Configuration objConfig = WebConfigurationManager.OpenWebConfiguration("~");
AppSettingsSection objAppsettings =

(AppSettingsSection)objConfig.GetSection("appSettings");

if (objAppsettings != null){

objAppsettings.Settings[strKey].Value = strValue;
objConfig.Save();
}

Remove

Configuration objConfig = WebConfigurationManager.OpenWebConfiguration("~");

AppSettingsSection objAppsettings =

(AppSettingsSection)objConfig.GetSection("appSettings");

if (objAppsettings != null){

objAppsettings.Settings.Remove(key);

objConfig.Save();

}

Reference:

http://msdn.microsoft.com/en-us/library/system.configuration.appsettingssection.aspx

Tuesday, February 26, 2008

Server Application Unavailable

Server Application Unavailable

The web application you are attempting to access on this web server is currently unavailable. Please hit the "Refresh" button in your web browser to retry your request.

Administrator Note: An error message detailing the cause of this specific request failure can be found in the application event log of the web server. Please review this log entry to discover what caused this error to occur.

Today morning, I got the same error in my ASP.Net application as above. I am not getting this error for first time. But the interesting thing is, I solved the error in different way before. I think this problem can be occurs for many reasons. Since I face the problem and spent time to solve this issue, I think it is better to share ideas with others. It may be helpful for those who will get this error in future.

According to http://support.microsoft.com/kb/315158 the problem occurs because of Aspnet_wp.exe fails to start. By default, ASP.NET runs its worker process (Aspnet_wp.exe) with a weak account (the local machine account, which is named ASPNET) to provide a more secure environment. On a domain controller or on a backup domain controller, all user accounts are domain accounts and are not local machine accounts. Therefore, Aspnet_wp.exe fails to start because it cannot find a local account named "localmachinename\ASPNET". To provide a valid user account on the domain controller, you must specify an explicit account in the section of the Machine.config file, or you must use the SYSTEM account.

Solution 1:

1. Check that ‘IUSR_machine’ and ‘IWAM_machine’

Solution 2:

1. Stops the IIS and the ASP.NET state services.

2. Deletes and then re-creates the ASPNET account by using a known temporary password.

3. Reregisters ASP.NET. This step creates a new random password for the account and applies default ASP.NET access control settings for the account.

4. Restarts the Microsoft Internet Information Services (IIS) service.