+91 20 24210201/301 info@genex.co.in

Web Security Vulnerabilities Prevention Cheat Sheet

Cross Site Scripting (XSS):

XSS is an attack in which script is maliciously injected into a user’s browsing session, generally without the user’s knowledge. These types of attacks have become quite familiar to many people because of incidents in which a large social networking site was struck and its users had messages posted they didn’t authorize. If an attacker posts malicious script that he can cause the browser to execute, this script is executed in the context of the victim’s session, essentially enabling the attacker to do anything he wants to the DOM—including showing fake login dialogs or stealing cookies. Such an attack could even install an HTML key logger on the current page to continually send input from that window to a remote site.
How Do You Prevent XSS?
  1. Ensure all of your output is HTML-encoded.
  2. Don’t allow user-supplied text to end up in any HTML element attribute string.
  3. Prevent the use of Internet Explorer 6 by your application by checking Request.Browser
  4. Know your control’s behavior and whether it HTML encodes its output. If it doesn’t, encode the data going to the control.
  5. Use the Microsoft Anti-Cross Site Scripting Library (AntiXSS) and set it as your default HTML encoder.
  6. Use the AntiXSS Sanitizer object (this library is a separate download and is addressed later in this article) to call GetSafeHtml or GetSafeHtmlFragment before saving HTML data to the database; don’t encode the data before saving.
  7. For Web Forms, don’t set EnableRequestValidation=false in your Web pages. Unfortunately, most user group postings on the Web advise disabling this setting if there’s an error. The setting is there for a reason and will stop the request if the character combination “
  8. Use the HttpOnly cookie option : This prevents client-side scripts from accessing a cookie from the document.cookie property.
  9. Use the innerText Property Instead of innerHTML:
    If you use the innerHTML property to build a page and the HTML is based on potentially untrusted input, you must use HtmlEncode to make it safe. To avoid having to remember to do this, use innerText instead. The innerText property renders content safe and ensures that scripts are not executed. (e.g. ,
    and etc.)

Cross-Site Request Forgery (CSRF):

Cross-site request forgery, also known as a one-click attack or session riding and abbreviated as CSRF (sometimes pronounced sea-surf). CSRF is an attack that occurs when someone takes advantage of the trust between your browser and a Web site to execute a command using the innocent user’s session.
How Do You Prevent CSRF?
Cross-Site Request Forgery (CSRF) is an attack where a malicious site sends a request to a vulnerable site where the user is currently logged in.
  1. ViewStateUserKey = Session.SessionID then viewstate will act as a form token.
  2. Protect SessionID using Hashing and Encryption.
  3. Use SSL to prevent sniffing of SessionID and ViewState
  4. Either create a BasePage and add the following code in that and check ViewState for forms and inherit all the pages from this base page. 
ASP.NET has an option to maintain your ViewState. The ViewState indicates the status of a page when submitted to the server. The status is defined through a hidden field placed on each page with a control. Viewstate can be used as a CSRF defense, as it is difficult for an attacker to forge a valid Viewstate. It is not impossible to forge a valid Viewstate since it is feasible that parameter values could be obtained or guessed by the attacker. However, if the current session ID is added to the ViewState, it then makes each Viewstate unique, and thus immune to CSRF. 
To use the ViewStateUserKey property within the Viewstate to protect against spoofed post backs. Add the following in the OnInit virtual method of the Page-derived class (This property must be set in the Page.Init event).

Injection Flaws:

Step 1: Use ASP.NET Request Validation
Step 2: Constrain Input
  • Use server-side input validation: Use client-side validation in addition to server-side validation to reduce round trips to the server and to improve the user experience.
  • Validate length, range, format and type: Make sure that any input meets your guidelines for known good input.
  • Use strong data typing: Assign numeric values to numeric data types such as Integer or Double. Assign string values to string data types. Assign dates to the Date Time data type.
For Web form applications that obtain input through server controls, use the ASP.NET validator controls to constrain the input. For other sources of input data, such as query strings, cookies, and HTTP headers, constrain input by using the Regex class from the System.Text.RegularExpressions namespace.
  • To allow restricted HTML input:
    • Disable ASP.NET request validation by the adding the ValidateRequest="false" attribute to the @ Page directive.
    • Encode the string input with the HtmlEncode method.
    • Use a String Builder and call its Replace method to selectively remove the encoding on the HTML elements that you want to permit.
  • Validate Query String/Cookie Values
    • Validate query string/cookie values for length, range, format, and type.
  • Validate File and URL Paths
    • If your application has to accept input file names, file paths, or URL paths, you need to validate that the path is in the correct format and that it points to a valid location within the context of your application.
  • Validating File Paths
    • If you must accept file names as input, use the full name of the file by using System.IO.Path.GetFileName.
    • If you must accept file paths as input, use the full file path by using System.IO.Path.GetFullPath.
Using MapPath to Prevent Cross Application Mapping.
If you use MapPath to map a supplied virtual path to a physical path on the server, use the overload of Request.MapPath that accepts a bool parameter so that you can prevent cross-application mapping.
Step 3: Encode Unsafe Output
If you write text output to a Web page, encode it using HttpUtility.HtmlEncode. Do this if the text came from user input, a database, or a local file.

  • Use HtmlEncode to Encode Unsafe Output.
  • Use UrlEncode to Encode Unsafe URLs
Step 4: Use Command Parameters for SQL Queries
Use strongly typed Parameterized Queries, such as SqlCommand with SqlParameter or an ORM like Hibernate.

Information Leakage & Improper Error Handling:

Verify that ASP.NET Errors Are Not Returned to the Client.

You can use the element to configure custom, generic error messages that should be returned to the client in the event of an application exception condition.


Broken Authentication & Session Management

Broken Authentication and Session Management attacks are anonymous attacks generated to try and retrieve passwords, user IDs, account details and other information. For example, a webmaster running an online forum or participating in a social network is extremely prone to these types of incidents.
These attacks normally begin when the attacker impersonates the target by relying on information they’ve gathered from other users on the same platform. By doing so, the attacker can ask for (and often receive) valuable information which can in turn lead to account hijacking, identity theft and other critical issues.

Insecure Cryptographic Storage

Many web applications do not properly protect sensitive data, such as credit cards, tax ids, and authentication credentials. Attackers may steal or modify such weakly protected data to conduct identity theft, credit card fraud, or other crimes. Sensitive data deserves extra protection such as encryption at rest or in transit, as well as special precautions when exchanged with the browser.
  1. Encrypted any sensitive data that will be stored long term.
  2. Insure that only authorized users can access decrypted copies of the data.
  3. Insure that a strong encryption algorithm is used. (Approved public algorithms such as AES, RSA public key cryptography, for hashing use SHA-256 or better. Do not use weak algorithms, such as MD5 or SHA1.)
  4. Only use widely accepted implementations of cryptographic algorithms rather than implementing an algorithm on your own. 

Read More

Factory Design Pattern

Factory Design pattern is based on Encapsulation object oriented concept. Factory method is used to create different object from factory often refereed as Item and it encapsulate the creation code. So instead of having object creation code on client side we encapsulate inside Factory method.

Factory design pattern is used to create objects and it provides loose coupling and high cohesion. Factory pattern encapsulate object creation logic which makes it easy to change it later when you change how object gets created or you can even introduce new object with just change in one class. In GOF pattern list Factory pattern is listed as Creation design pattern. Factory should be an interface and clients first either creates factory or get factory which later used to create objects.

Problem which is solved by Factory method Pattern:
Whenever we talk about object oriented language it will based upon some concept like abstraction, polymorphism etc. and on that encapsulation and delegation are important concept any design will be called good if task are delegated to different object and some kind of encapsulation is there.

Sometime our application or framework will not know that what kind of object it has to create at run-time it knows only the interface or abstract class and as we know we cannot create object of interface or abstract class so main problem is frame work knows when it has to create but don’t know what kind of object.

Whenever we create object using new() we violate principle of programming for interface rather than implementation which eventually result in inflexible code and difficult to change in maintenance. By using Factory design pattern we get rid of this problem.

Another problem we can face is class needs to contain objects of other classes or class hierarchies within it; this can be very easily achieved by just using the new keyword and the class constructor. The problem with this approach is that it is a very hard coded approach to create objects as this creates dependency between the two classes.

So factory pattern solve this problem very easily by model an interface for creating an object which at creation time can let its subclasses decide which class to instantiate, Factory Pattern promotes loose coupling by eliminating the need to bind application-specific classes into the code. The factory methods are typically implemented as virtual methods, so this pattern is also referred to as the “Virtual Constructor”. These methods create the objects of the products or target classes.

When to use Factory design pattern:

  • Static Factory methods are common in frameworks where library code needs to create objects of types which may be sub classed by applications using the framework. 
  • Some or all concrete products can be created in multiple ways, or we want to leave open the option that in the future there may be new ways to create the concrete product.
  • Factory method is used when Products don’t need to know how they are created.
  • We can use factory pattern where we have to create an object of any one of sub-classes depending on the data provided. 

    Advantage of Factory method Pattern:
  • Factory method design pattern decouples the calling class from the target class, which result in less coupled and highly cohesive code?
  • Factory pattern enables the subclasses to provide extended version of an object, because creating an object inside factory is more flexible than creating an object directly in the client. Since client is working on interface level any time you can enhance the implementation and return from Factory.
  • Another benefit of using Factory design pattern is that it encourages consistency in Code since every time object is created using Factory rather than using different constructor at different client side.
  • Code written using Factory design pattern is also easy to debug and troubleshoot because you have a centralized method for object creation and every client is getting object from same place.
Example (C#):

using System;
class Program
    abstract class Position
public abstract string Title { get; }
    class Manager : Position
public override string Title
return "Manager";
    class Clerk : Position
public override string Title
return "Clerk";
    class Programmer : Position
public override string Title
return "Programmer";
    static class Factory
/// Decides which class to instantiate.
public static Position Get(int id)
   switch (id)
case 0:
   return new Manager();
case 1:
case 2:
   return new Clerk();
case 3:
   return new Programmer();
    static void Main()
for (int i = 0; i <= 3; i++)
   var position = Factory.Get(i);
   Console.WriteLine("Where id = {0}, position = {1} ", i, position.Title);

Read More

.NET Framework 4 vs .NET Framework 4 Client Profile

In .NET Framework 4 we have introduced a streamlined subset and more compact version of the .NET Framework called the Microsoft .NET Framework 4 Client Profile (aka NET4 Client Profile). The Microsoft .NET Framework 4 which is the Full Framework (aka NET4 Full) still exists and it is a superset of the Client Profile.

What are the reasons for a Client Profile?

Although the NET4 Client Profile is smaller and faster to install compared to the NET4 Full Framework (NET4 is 7-8MB smaller in size than the Full Framework), the main reasons are not just better deployment size/time but also:

  • Reduce the Framework deployment failures.
  • By keeping ASP.Net and other components (that are mostly needed for servers) out of the Client Profile, we can reduce the attack surface and the number of future servicing events which may be caused by server component (such as ASP.Net) and are not needed for desktop scenarios.
  • Making NET4 Client Profile available on Windows Update will make sure that most desktop machines will include NET4 Client Profile over time and apps that target the Client Profile will not need to carry or install the Framework which will improve the overall deployment experience.
  • Enable us to add features and grow the size of overall Framework in future versions but still have a smaller core.
When to use NET4 Client Profile and when to use NET4 Full Framework?

NET4 Client Profile:

Always target NET4 Client Profile for all your client desktop applications (including Windows Forms and WPF apps).

NET4 Full framework:
Target NET4 Full only if the features or assemblies that your app need are not included in the Client Profile. This includes:
  • If you are building Server apps. Such as:
    1) ASP.Net apps
    2) Server-side ASMX based web services
  • If you use legacy client scenarios. Such as:
    1) Use System.Data.OracleClient.dll which is deprecated in NET4 and not included in the Client Profile.
    2) Use legacy Windows Workflow Foundation 3.0 or 3.5 (WF3.0 , WF3.5)
  • If you targeting developer scenarios and need tool such as MSBuild or need access to design assemblies such as System.Design.dll

    Reference Links:
    1) http://blogs.msdn.com/b/jgoldb/archive/2010/04/12/what-s-new-in-net-framework-4-client-profile-rtm.aspx

Read More

Push notifications for Windows Phone 8

It is very easy to send push notification on Windows Phone 8. Just doing few steps.

Creating a push client to receive toast notifications:
1) Create a new Windows Phone 8 app.

2) Name the project GenexToastClient.

3) Add the following using directives to the top of the MainPage.xaml.cs file.

  using Microsoft.Phone.Notification;

3) Add following code in MainPage.xaml.cs file.

 public MainPage()
      HttpNotificationChannel pushChannel;
      string channelName = "ToastDemo";
      pushChannel = HttpNotificationChannel.Find(channelName);
     if (pushChannel == null)
            pushChannel = new HttpNotificationChannel(channelName);
            pushChannel.ChannelUriUpdated += new EventHandler(PushChannel_ChannelUriUpdated);
            pushChannel.ChannelUriUpdated += new EventHandler(PushChannel_ChannelUriUpdated);
            MessageBox.Show(String.Format("Channel Uri is {0}", pushChannel.ChannelUri.ToString()));

    void PushChannel_ChannelUriUpdated(object sender, NotificationChannelUriEventArgs e)

            Dispatcher.BeginInvoke(() =>
                //Normally, the URI would be passed back to your web service at this point.

                MessageBox.Show(String.Format("Channel Uri is {0}", e.ChannelUri.ToString()));


Sending a Toast Notification:
1) Create new ASP.Net web application

Add one button on default.aspx page  and put the following code in side the button_onclick event
//Run GenexToastClient app. Windows Phone Emulator initializes, and then the app starts. After a moment or two,
//the app should display a message with the push channel URI.  This URI also will be displayed in the Visual Studio debugger Output window.
//copy this URI and pass to ChannelUri variable in following code.

string ChannelUri = "http://db3.notify.live.net/throttledthirdparty/01.00/AQGshG_QxJs2QIO1OID6wTLxAgAAAAADAQAAAAQUZm52OkJCMjg1QTg1QkZDMkUxREQFBkVVTk8wMQ";

                HttpWebRequest sendNotificationRequest = (HttpWebRequest)WebRequest.Create(ChannelUri);
                sendNotificationRequest.Method = "POST";


              // Set the notification payload to send.
                byte[] notificationMessage = Encoding.Default.GetBytes(toastMessage);

                // Set the web request content length.
                sendNotificationRequest.ContentLength = notificationMessage.Length;
                sendNotificationRequest.ContentType = "text/xml";
                sendNotificationRequest.Headers.Add("X-WindowsPhone-Target", "toast");
                sendNotificationRequest.Headers.Add("X-NotificationClass", "2");

                using (Stream requestStream = sendNotificationRequest.GetRequestStream())
                    requestStream.Write(notificationMessage, 0, notificationMessage.Length);

                // Send the notification and get the response.
                HttpWebResponse response = (HttpWebResponse)sendNotificationRequest.GetResponse();
                string notificationStatus = response.Headers["X-NotificationStatus"];
                string notificationChannelStatus = response.Headers["X-SubscriptionStatus"];
                string deviceConnectionStatus = response.Headers["X-DeviceConnectionStatus"];

3) Run web app and  Press the button on default.aspx page. you will get the notification on your windows phone.

Happy Coding   smiley

Read More

Getting your BackBone HTML5 app ready (compatible) for HTML4 browsers

Building single-page web apps or complicated user interfaces will get extremely difficult by simply using jquery. The problem is standard JavaScript libraries are great at what they do and without realizing it you can build an entire application without any formal structure. You will with ease turn your application into a nested pile of jquery callbacks, all tied to concrete DOM elements. As I said jquery can build an entire application without any formal structure and hence we need something with good structural format, which incorporates with full functional jquery, HTML5 and CSS3.
The web is currently trending such that all data/content will be exposed through an API. This is because the browser is no longer the only client; we now have mobile devices, tablet devices, Google Goggles and electronic fridges etc.

Backbone.js gives structure to web applications, models with key-value binding, collections with a rich API of enumerable functions, views with declarative event handling. Backbone.js enforces that communication to the server should be done entirely through a RESTful API. Backbone is an incredibly small library for the amount of functionality and structure it gives you. It is essentially MVC for the client and allows you to make your code modular.
And it works great in modern browsers. So what’s the problem area then? The problem arises when you wanted same application with all the features working on HTML4 browsers. The HTML4 browsers don’t support HTML5 behavior like history, pushstate and requirestate that require for navigation purpose in Backbone.js instead the HTML4 browsers supports hash fragments navigation for pure jquery.
The modern browsers support properties like crossDomain in ajax call to support request across the different domains, while HTML4 browsers supports conventional ajax call. The most vulnerable problem with HTML4 browsers is after first ajax call it caches all the request and afterward it fetches from cache, which gives impression that the application not saving or updating the values.
Backbone Router provides methods for routing client-side pages, and connecting them to actions and events. Backbone Router with History API uses standard URLs (/page) instead of traditional hash fragments (#page). During page load, after your application has finished creating all of its routers, be sure to call Backbone.history.start(), or Backbone.history.start({pushState: true}) to route the initial URL.
Following is the workaround you can try for getting your BackBone app ready for HTML4 browsers:
·         The History API the pushState value should be false.
·         Include Modernizr a JavaScript library that detects HTML5 and CSS3 features in the browser.
·         Check whether the browser supports History API instead check whether the browser supports the HTML5 properties and here is the example how to achieve the same.
//when your application starts up
Backbone.history.start({ pushState: Modernizr.history });
if(!Modernizr.history) {
    var rootLength = Backbone.history.options.root.length;
    var fragment = window.location.pathname.substr(rootLength);
    Backbone.history.navigate(fragment, { trigger: true });
} else {
·         If you are using ajax call in the application, should not use the crossDomain property of ajax, it will break your request in the browsers which don’t support HTML5.
·         Check whether any broken tags and appropriate function completion. Most common mistake is trailing commas after callback function and property declaration.
·         The most common problem of the browsers which don’t support HTML5 is ajax cache. The browser caches the request and response data for the first time and provides the response from cache thereafter. You should manually turn the cache off by setting the property cache:false to ajax call.
·         If you are using the HTML5 tags in the application, you should include html5shiv.js JavaScript library that enables the HTML5 basic tags for the browsers which don’t support HTML5.
·         For proper working of CSS classes, you can use IE filter and CSS hack attributes in CSS class. The IE filter attributes are mainly helpful for gradient and opacity effect and the CSS hack attributes helps to adjust auto property which is not supported by HTML4 browsers.

Read More
 Page 1 of 2