Tuesday, June 12, 2012

Code Analysis Tool (CAT.NET)

CAT.Net is a binary source code analysis tool that helps in identifying common security flaws in managed code. These vulnerabilities are listed in the below table.

 
Vulnerability
Description


Cross Site Scripting(XSS)
XSS vulnerability allows an attacker to inject a malicious HTML Code or Scripts which gets executed in the Client's browser.
A successful
XSS can lead to modification in application, DOS attack, loss of user data, and execution of malicious command on the web server.


SQL Injection
SQL injection is a technique to exploit application using malicious code passed to Sql server for execution. A successful Sql injection attack results in unauthorized access to database. In some cases the whole system gets compromised
Process Command Injection
If user input is use to create a process in your application e.g. user provides that an argument to the new process, then it is vulnerable to process command execution. In this attack the attacker tries to execute system level commands.

File Canonicalization
Canonicalization is the process of converting data to its canonical form. File paths and URLs are particularly prone to canonicalization issues and many well-known exploits are a direct result of canonicalization bugs.
If user input is used to construct a path or name a resource then your application is vulnerable to file canonicalization

Exception Information
Exception handling is built in mechanism in .Net Framework to handle the errors that occurred at run time. Proper exception/error mechanism should be in place to avoid information disclosure through error message. The information may contain Database, Web server, application path, Source file details etc. which an attacker can misuse to launch an attack.

LDAP Injection
LDAP injection is a technique to exploit application using malicious code that constructs the LDAP query for execution.  The technique is similar to SQL Injection attack.


XPATH Injection
XPATH injection is a technique to exploit application using code that constructs the XPATH query for XML data. A successful XPATH injection can lead to the whole xml data file.

Redirection to User Controlled Site
When an application allows redirection via user supplied parameters in the destination URL like "http://samplewebsite.com/login.aspx?ReturnUrl=Statementview.aspx". If these kinds of url are not validated for allowed destination, an attacker can simply send a malicious URL like "http://samplewebsite.com/login.aspx?ReturnUrl=http://phishingsiteurl" to redirect user to a phishing page.


CAT.Net tool enhances the quality of the source and helps in adopting security best practices.
Microsoft uses this tool for security review. One thing we should always keep in my while using automated code analysis tool is the false positive results.Cat.net sometimes produces the false positive results.

CAT.Net tool must be used during the implementation phase of security development lifecycle (SDL).


There are some limitations when using the CAT.Net i.e. on the size of the dll being analyzed. 18 MB dll is to be analyzed by cat.net. Above this size it throws an exception "Out of memory". The exception will be thrown only on 32 bit not on 64 bit machines.

The CAT.NET tool can be used in four different scenarios:
1.  A snap-in to the Visual Studio IDE,
2.  A command line tool,
3.  As an FxCop rule and
4.  Integrated into VSTF TeamBuild as an MSBuild custom task.
Here in this demo I will be using command line tool.

Ø  Open command prompt and navigate to folder where CATNetCmd64.exe is located.
Ø  Type the command "CATNetCmd64.exe /file:"catnet.dll" where /file accept the assembly name to be analyzed.
Ø  Once done with this you will see the analysis has started and on successful completion it will generate a report. The screen after successful completion of the analysis.



You can view report which is generated in the root path of the ct.net directory named as report.html.

Sample report for the above analysis is shown below.




Download

32 bit- http://www.microsoft.com/downloads/en/details.aspx?FamilyID=0178E2EF-9DA8-445E-9348-C93F24CC9F9D   

64 bit- http://www.microsoft.com/downloads/details.aspx?FamilyId=e0052bba-2d50-4214-b65b-37e5ef44f146
Code Analysis Tool (CAT.NET) is a binary source code analysis tool that helps in identifying common security flaws in managed code. These vulnerabilities are listed in the below table.

AntiXSS Module

In the earlier post we learnt about the AntiXSS Library. Which was very usefull for us to stop any Crosssite scripting attack XSS.
But we cannot mannually go in every field of the project and check it with Antixss Library.
Also it might happen that Some new developer comes in and forgets to encode the new fields he introduced with the Anti XSS Library. Microsoft has also come up with a solution where we can do it Globally.

Introduction

SRE protects applications from Cross-Site Scripting (XSS) attacks by leveraging the Anti-XSS library to encode data. It works by inspecting each control that is being reflected by ASP.NET and then automatically encodes data of vulnerable controls in their appropriate context. Data to be encoded for a specific control is mentioned in the antixssmodule.config file. This is useful for applications which are already deployed in production and when we don't want to rewrite code.

SRE Configuration for Web Applications

  • To download the SRE MSI file, use this link: http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=325.
  • Install SRE and use these DLLs installed (while installation, setup will ask whether to install SRE or AntiXss module or both): AntiXSSLibrary.dll and AntiXssModule.dll.
  • The DLLs will be present in the path (default path): C:\Program Files\Microsoft Information Security\Microsoft Anti-Cross Site Scripting Library v3.1\Security Runtime Engine\Module.
  • Add reference to both DLLs to the web application project, i.e., RxOfficeLegal.
  • Add the below configuration element into the Web config file under the httpmodules section.
  • After adding the above patch, use ConfigGen.exe to generate the config file for the controls.
  • The most important point is, if ConfigGen.exe is not generating the configuration for the controls then use manual configuration for the controls that are are needed with the respective properties (e.g. for Label control, Text property should be configured). Generally the name of the configuration file is antixssmodule.config. (By default the standard antixssmodule.config is generated with the EncodingControls.xml file).
  • Rebuild the solution and see the result on the page rendered.
  • For GridView, and data source controls, we have to manually encode in the code. For GridView, it is mandatory to have the Rowdatabound event present in the .cs file, it is OK even if it is empty.

How SRE Works

SRE works using Reflection, it takes controls from the antimodule.config file and encodes the controls according to the encoding type. There are mainly the following types of encoding in AntiXssModule:
  • GetsafeHtmlMathod
  • HtmlAttributeEncode
  • HtmlEncode
  • JavaScriptEncode
  • UrlEncode
  • GetSafeHtmlFragment(String)
The above encoding types have overloaded methods. Three overloaded methods are listed below:
Example:
  • GetSafeHtmlFragment(String)
  • GetSafeHtml( TextReader sourceReader,Stream destinationStream)
  • GetSafeHtml( TextReader sourceReader,TextWriter destinationWriter)
Note: For manual encoding, we have to add the namespace refernce: "using Microsoft.Security.Application".

AntiXssModule Configuration File and Deployment

The AntiXssModule configuration file contains the following attributes. These attributes are useful to configure the application according to your requirement. The attributes and their description are given below.

<ControlEncodingContexts>

This section lists the controls and encoding contexts supported by SRE. Example:

<ControlEncodingContexts> 
<ControlEncodingContext FullClassName="System.Web.UI.WebControls.Label" PropertyName="Text" 
EncodingContext="Html" /> 
<ControlEncodingContext FullClassName="System.Web.UI.WebControls.HyperLink" PropertyName="Text" 
EncodingContext="Html" /> 
</ControlEncodingContexts>

PropertyName

The name of the property which needs to be encoded.

EncodingContext

The type of encoding which needs to be applied. Valid attribute values are Html, HtmlAttribute.

ControlEncodingContext

This node defines a control and its encoding context. Multiple nodes may exist for different controls; the same class name and property name must not exist twice. With each control, the full class name, property name, and encoding context must be defined. Other attributes are ignored.

<DoubleEncodingFilter Enabled="True" />

This section can be used to configure double encoding support.

<EncodeDerivedControls Enabled="True" />

This section can be used to configure encoding for derived controls.

<MarkAntiXssOutput Enabled="False" Color="Blue"/>

This section can be used to configure color coding of the output.

<Suppressions><Exclude Path="/Page_1.aspx" />

This section includes the configuration for suppressing SRE for the listed files and folders.

Deployment

Follow these steps to deploy the SRE:
  • Use the ConfigGen.exe utility to create an antixssmodule.config file. Alternatively, you copy the default antixssmodule.config from the Security Runtime Engine\Module folder to your web application's root folder.
  • Copy the DLLs from the Security Runtime Engine\Module folder to your web application's \bin folder.
  • Enable the SRE module by modifying your web.config file according to these examples. In IIS 6.0 and IIS 7.0 in Classic .NET Application Pool:
  • <system.web> 
    <httpModules> 
    <add name="AntiXssModule" type="Microsoft.Security.Application.SecurityRuntimeEngine.AntiXssModule"/>
    </httpModules> 
    </system.web>
    In IIS 7.0 pipeline mode:
    <system.webServer> 
    <modules> 
    <add name="AntiXssModule" type="Microsoft.Security.Application.SecurityRuntimeEngine.AntiXssModule"/> 
    </modules> 
    </system.webServer>
    After deployment, if we want to check which part is encoded, use the following setting:
    MarkAntiXssOutput Enabled="True"
    For example: http://www.foosite.com/default.aspx?MarkAntiXSSOutput=true.

Limitations

  1. For GridView and other datasource controls, we have to manually add code for encoding.
  2. SRE ConfigGen not picking up child controls inside DataGrid or DataList: SRE ConfigGen identifies controls that need to be encoded by reflecting controls in the web application binary. Due to the limitations of its implementation, ConfigGen cannot reflect what controls are present in an <ItemTemplate>. You can work around this by manually adding the control detail in antixssmodule.config, or by using the default configuration file from <Installation Folder>\SRE\Module.
  3. SRE encodes data on the server side. That means any ASP.NET control which is configured in the AntiXssModule.config file and which has the runat="server" attribute set can be encoded by SRE.

SRE Success Screenshots

Some testing screenshots of SRE Module testing with Anti-Xss library:
If we use SRE module with the XSS library and set the Label control Text property with malicious content, then it will not execute the malicious content, it will encode the malicious content and prevent its execution.

Example 1

If the text of the Label is populated with a script tag which is not expected as a value of the label as below:
<asp:Label ID="lblUser" CssClass="LastLogin" runat="server" Text="<script>alert('Test')</script>"></asp:Label>
then it will encode the above label on the screen as shown:
<script>alert('Test')</script>
but if the SRE module with XSS library is not used, then it will execute malicious content, which might be harmful to the application. For example:

Example 2

If we try to inject malicious content using an input control in the UI as below:
<script>test</script>
If SRE is used, then it will redirect to an error page:
A potentially dangerous Request.Form value was detected from the client 
(ctl00$mainContentPlaceHolder$txtAddress2="<script>alert('Testi...").
If we don't use the SRE tool, it will show an alert message due to the malicious content executed. If we set the MarkAntiXssOutput tag in the SRE config file antixssmodule.config, then you can see which part (controls) in the page are encoded with a specific color. For example, set in config:
<MarkAntiXssOutput Enabled="true" Color="Yellow"/>
and pass MarkAntiXssOutput=true in request URL: http://testpage.aspx?MarkAntiXssOutput=true, then output will be colorful in yellow color.

Other findings

The SRE tool does not encode child controls, for which we have to manually change the code to encode. Like GridView, DataGrid, and other controls. For that we need to add a Rowbound event prototype in the code. For example:
protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e) 
{ 
}

References

Anti XSS Library Stopping XSS Attacks

Using AntiXss as the default encoder for ASP.NET
 See: http://antixss.codeplex.com/

ASP.NET 4 includes a new extensibility point which allows you to replace the default encoding logic with your own anywhere ASP.NET does encoding.
All it requires is to write a class which derives from System.Web.Util.HttpEncoder and register that class in Web.config via the encoderType attribute of the httpRuntime element.

Walkthrough

In the following section, I’ll walk you through setting this up. First, you’re going to need to download the AntiXSS library which is at version 3.1 at the time of this writing.

On my machine, that dropped the AntiXSSLibrary.dll file at the following location: C:\Program Files (x86)\Microsoft Information Security\Microsoft Anti-Cross Site Scripting Library v3.1\Library

Create a new ASP.NET MVC application (note, this works for *any* ASP.NET application).

Copy the assembly into the project directory somewhere where you’ll be able to find it. I typically have a “lib” folder or a “Dependencies” folder for this purpose. Right clicke on the References node of the project to add a reference to the assembly.

add-reference Add-Reference-dialog

The next step is to write a class that derives from HttpEncoder. Note that in the following listing, some methods were excluded which are included in the project.
using System;
using System.IO;
using System.Web.Util;
using Microsoft.Security.Application;

/// <summary>
/// Summary description for AntiXss
/// </summary>
public class AntiXssEncoder : HttpEncoder
{
  public AntiXssEncoder() { }

  protected override void HtmlEncode(string value, TextWriter output)
  {
    output.Write(AntiXss.HtmlEncode(value));
  }

  protected override void HtmlAttributeEncode(string value, TextWriter output)
  {
    output.Write(AntiXss.HtmlAttributeEncode(value));
  }

  protected override void HtmlDecode(string value, TextWriter output)
  {
      base.HtmlDecode(value, output);
  }

  // Some code omitted but included in the sample
}
Finally, register the type in web.config.
...
  <system.web>
    <httpRuntime encoderType="AntiXssEncoder, AssemblyName"/>
...
Note that you’ll need to replace AssemblyName with the actual name of your assembly. Also, in the sample included with this blog post, AntiXssEncoder is not in any namespace. If you put your encoder in a namespace, you’ll need to make sure to provide the fully qualified type name.
To prove that this is working, run the project in the debugger and set a breakpoint in the encoding method.

debugger-breakpoint
With that, you are all set to take full control over how strings are encoded in your application.