Wednesday, April 27, 2011

Security Control in your Application

1.      View State
Set “EnableViewState” property to true for the controls which you think carry some sensitive information in the application. You can enable view state on three levels:

a)Application level
<system.web>
            <pages enableViewState="true" viewStateEncryptionMode="Always">
      </pages>
</system.web>

b)      Page level
<%@ Page Language="VB" EnableViewState="true" AutoEventWireup="false"   CodeFile="index.aspx.vb" Inherits="index" %>

c)       Control level
<asp:TextBox ID="txtpwd" runat="server" EnableViewState="true" Font-
Names="Verdana" Font-Size="10pt" ForeColor="Navy" TabIndex="2" TextMode="Password" Width="160px"></asp:TextBox>

2.      Custom Error
Apply custom error in web.config file
<system.web>
       <customErrors mode="On" defaultRedirect="errorpage.aspx">
            <error statusCode="404" redirect="errorpage.aspx" />
       </customErrors>
   </system.web>
If there will be any runtime error in the application while online it will be redirected to the errpr page specified in the custom error property in web.config.

3.      Validation check
This check should be applied for all the values of the controls like dropdownlist, checkbox, listbox, radiobutton etc. For example in a dropdownlist, the selected value can only be in numeric form then a check should be applied while its selection proceess that if the selected value is not a numeric then it should be redirected to an error page.
This can be done in many ways one of which is :

Protected Sub Dropdownlist1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ddlDepartments.SelectedIndexChanged
        Try
            If Dropdownlist1.SelectedIndex > 0 Then
                Dim r As New Regex("[0-9]") 'Look for these
                Dim m As Match = r.Match(Dropdownlist1.SelectedValue) 'In This
                If m.Success Then
                    // code what you need to do on dropdownlist selection..
                Else
                    Response.Redirect("errorpage.aspx")
                End If
            ElseIf Dropdownlist1.SelectedIndex = 0 Then
                Response.Redirect("samepage.aspx")

            End If
        Catch ex As Exception
            Response.Redirect("errorpage.aspx")
        End Try
    End Sub

4.      Throw Exception
You should apply try catch every where in your code where ever required, but keeping in mind that while throwing an exception it should not display the exception message as it can display the senstive information regarding the server or your database.
     Try
       // statements…
     Catch ex As Exception
       Response.Redirect("errorpage.aspx")   //this is suggested
       Lable1.Text = "There is an error."    //this is suggested
       Lable1.Text = ex.Message              //this is not suggested
     End Try


5.      Session Fixation

For this we need to first set a cookie and a session to null on the login page and then generate an encrypted string, add the same to the cookie and the session.

Session.Add("Authcookie", "")
Response.Cookies.Add(New HttpCookie("ASMSAUTH", ""))
Dim ticket1 As System.Web.Security.FormsAuthenticationTicket
ticket1 = New System.Web.Security.FormsAuthenticationTicket(1, "Test", DateTime.Now, DateTime.Now.AddSeconds(5), False, "")
Dim encryptedText As String =
System.Web.Security.FormsAuthentication.Encrypt(ticket1)
Response.Cookies.Add(New HttpCookie("ASMSAUTH", encryptedText))
Session("Authcookie") = encryptedText

Now on every page_load and on the button_click event on which we are submitting some data to the database or on which we are extracting some data from the database, we need to check that the cookie and session should have the same value.
Below is the code for the same:

If (Request.Cookies("ASMSAUTH") Is Nothing) Then
         sessionreset()
   Else
      If (Request.Cookies("ASMSAUTH").Value = "") Then
                 sessionreset()
      Else
    If Session("Authcookie") <> Request.Cookies("ASMSAUTH").Value Then
                 sessionreset()
            End If
      End If
End If

Private Function sessionreset()
        Session.Clear()
        Session.Abandon()
        Response.Cookies.Add(New HttpCookie("ASMSAUTH", ""))
        Response.Redirect("login.aspx")
    End Function


6.      CSRF – Cross Site Request Forgery

Take an input field of hidden type on the page.

<input id="csrfval" runat="server" name="csrfval" type="hidden" />

Then on the page load generate a random number and assign it to the above declared hidden field and a session variable.

If Not IsPostBack Then
       Session.Add("randomno1", 0)
       Dim randomobj As New Random
       Session("randomno1") = randomobj.Next()
       csrfval.Value = Session("randomno1")
End If

Now we have to compare the value of the hidden field and the session on button click.

If csrfval.Value = Session("randomno1") Then

// your code that you need to fire on button click

ElseIf csrfval.Value <> Session("randomno1") Then
       lblmsg.Visible = True
       lblmsg.Text = "Error!!! Invalid User..."
       Exit Sub
End If
                                                                                                   To Be Continued.......