Showing posts with label .Net Security. Show all posts
Showing posts with label .Net Security. Show all posts

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.

Friday, May 11, 2012

Cross-Site Scripting (XSS) attack


What is Cross-Site Scripting (XSS) attack? How to prevent XSS attack in ASP.Net?
One of my previous article described about Sql injection attack and the ways to prevent Sql Injection attack in ASP.Net applications. You can read the article in the below link,
What is SQL Injection Attack? How to prevent SQL Injection in ASP.Net?
Moving forward, let’s understand the XSS attack and the ways to prevent XSS attack in ASP.Net applications.

What is Cross-Site Scripting (XSS) attack?
Cross-Site scripting which is commonly called XSS attack is a vulnerability that can be found on any web applications. Using this vulnerability, an attacker can take advantage on your application and insert some malicious script that will get executed automatically to accomplish whatever the attacker wants.  For example, an attacker can insert some JavaScript code with the actual input in an input field which in turn will get executed when it is displayed on the browser.
The XSS attack is broadly categorized into 2 types, Stored and Reflected.
A Stored XSS attack is one where the input with the malicious code is saved permanently into a persistent medium like database and will get executed whenever it is displayed or processed. For example, in a comment field an attacker can insert some malicious script which will get executed whenever it is displayed on the browser.
A Reflected XSS attack is one where the malicious script with the input is just processed by the server and is reflected back. For example, the input will be displayed back to the user in a webpage, commonly seen in search pages like “You have searched for xxxx…” or in some places, when you display an error message by including the input from user like “Your input xxx is invalid.” In these cases, if there is a malicious script injected with the input then it will get executed by the browser.
In next section, let’s see some simple XSS attack in ASP.Net application to understand it better.

Simulate XSS attack in ASP.Net
By default, ASP.Net will not allow any HTML tag in any input controls. In this case, you will receive the below error if you input html tags and submit the page.
Note that, you need to set ValidateRequest="false" in those pages where you need to allow HTML input. Open a new ASP.Net project in your visual studio and for time being, set ValidateRequest="false" in the Page directive of Default.aspx page to understand the XSS attack in this article. Now, drag a textbox and a button control in the aspx page. On click of the button, do a Response.Write() of the contents of textbox. Like below,
ASPX
  <asp:TextBox ID="txtMessage" runat="server" TextMode="MultiLine"></asp:TextBox>
        <asp:Button ID="btnSubmit" runat="server" onclick="btnSubmit_Click"
            Text="Submit" />
CodeBehind
 protected void btnSubmit_Click(object sender, EventArgs e)
    {
        Response.Write(txtMessage.Text);
    }

Execute the above page and type the below string as input in the textbox and click submit.
<script>alert('You are hacked!')</script>

Since, we have set ValidateRequest="false" the above malicious script will be rendered in the output html and will get executed. Hence, you will get a alert box saying ‘You are hacked!’. This is called XSS attack. This is a very basic example where an alert script is being inserted which has no impacts. Assume, there is a comment field in your page where you allow HTML input. Now, an attacker or possibly a spammer can insert some script that can redirect the user to his/her page through which he can divert all the traffic to his site that are supposed to visit your page. For example, in the above textbox try giving the below input.
<meta http-equiv="refresh" content="2;url=http://www.codedigest.com/">

The above script will redirect you to www.codedigest.com when the page is rendered back.

Handling XSS attack in ASP.Net
To handle XSS attack in these pages, you can do a HTML encode of the input before processing it. The input once HTML encoded will become void and it will get simply displayed and without getting executed. Hence, you can prevent the XSS attack in the above example by using the below code,
protected void btnSubmit_Click(object sender, EventArgs e)
    {
        Response.Write(Server.HtmlEncode(txtMessage.Text));
    }

The above code will do html encode on the input which will in turn will make the injected script void. So, the above inputs will become like below after encoding,
&lt;script&gt;alert('You are hacked!')&lt;/script&gt;
&lt;meta http-equiv=&quot;refresh&quot; content=&quot;2;url=http://www.codedigest.com/&quot;&gt;
Now, when this is rendered in the browser the HTML tags will be rendered as text(means, as a non executable). Please see below,
<script>alert('You are hacked!')</script>
<meta http-equiv="refresh" content="2;url=http://www.codedigest.com/">
At times, you may need to allow the users to input HTML tags which is then used to display the input with the HTML formatting done by the users. For example, in article/blog posting pages you may need to allow users to format the text with RTF(Rich Text Editors) editors and save it without encoding. In this case, to prevent XSS attack you can restrict users to do some limited formatting by allowing only some specific formatting tags like <B>,<I>,<font>, etc. Also, you can validate the user input in the server to strip the tags that are not allowed or considered to be vulnerable to XSS attack.






Some common XSS attacks in Web world
This section will list some common XSS attack on the web.
1.      An attacker may post some HTML links that can redirect the visitors to his/her page when the users are clicking it. Mostly, seen in comments, forums, etc.
2.      An attacker may post some script that can automatically redirect the user to his/her page.
3.      An attacker may post some malicious script that can steal the logged in user’s session cookie and send the same to him. With the sessionid, attacker can gain access to whatever the user has by using the same sessionid once the user is logged in.
Note: In JavaScript, you can get the cookie using document.cookie property. You can try some tools like burp proxy which can be used to simulate these scenarios by editing the http request and using the sessionid to get into other user’s session.

Conclusion
Nowadays, most of the modern development framework has all the required mechanism to prevent XSS attack. But, we will still need to be cautious whenever we allow users to input HTML tags. Some points to consider,
1.      Don’t set ValidateRequest="false" at Web.Config level. Always, set at page level only for the required pages.
2.      When you set ValidateRequest="false" for a page, make sure you are doing html encode of the input. Prevent html encode only for the required fields.
3.      When providing RTF editors, allow only minimal customizations. Again, validate for malicious tags like <script>, <applet>, <img>, <iframe> etc in the server side and filter them.
For more information on XSS prevention, read the OWASP XSS prevention cheat sheet.

Wednesday, April 18, 2012

Authentication using WCF and asp.net custom-membership-provider

http://aspguy.wordpress.com/2011/07/30/single-sign-on-with-wcf-and-asp-net-custom-membership-provider/
http://www.codewrecks.com/blog/index.php/2009/11/26/wcf-over-https-authentication-with-asp-net-membership/
http://stackoverflow.com/questions/2615316/using-asp-net-membership-provider-authentincation-in-a-wcf-service

Saturday, March 31, 2012

How to check if Internet Connection Available through Dot Net Code

Checking whether an Internet connection is available isn’t always as easy as it sounds.
Admittedly, there is a Windows API call that can check whether a connection exists, but it’s extremely fragile and returns incorrect results if the machine has never had Internet Explorer configured correctly. Oops.

The best method is to actually make a Web request and see whether it works. If it does, you’ve got your connection. The following neat code snippet does exactly that. Just call IsConnectionAvailable and check the return value:

Public Function IsConnectionAvailable() As Boolean
' Returns True if connection is available
' Replace www.yoursite.com with a site that
' is guaranteed to be online - perhaps your
' corporate site, or microsoft.com
Dim objUrl As New System.Uri("http://www.yoursite.com/")
' Setup WebRequest
Dim objWebReq As System.Net.WebRequest
objWebReq = System.Net.WebRequest.Create(objUrl)
Dim objResp As System.Net.WebResponse
Try
' Attempt to get response and return True
objResp = objWebReq.GetResponse
objResp.Close()
objWebReq = Nothing
Return True
Catch ex As Exception
' Error, exit and return False
objResp.Close()
objWebReq = Nothing
Return False
End Try

Here’s how you might use this function in your application:

If IsConnectionAvailable() = True Then
MessageBox.Show("You are online!")
End If

Friday, January 27, 2012

Encrypt or Decrypt Connection Strings in web.config


Introduction

In this article I will explain how to encrypt or decrypt connection Strings in web.config file using asp.net.

Description

In Previous posts I explained lot of articles regarding Asp.net, Gridview, SQL Server, Ajax, JavaScript etc. In many of articles I used connection Strings section in web.config file to store database connection. The connection Strings section contains sensitive information of database connections including username and password of database. Is it secured to store the sensitive information of database connections in plain text files called web.config and machine.config files?
 
If we are using applications in our internal servers with security then it’s ok if we deploy our applications in shared host environment then we have chance to arise security problems to avoid these problems asp.net 2.0 provided built in protected configuration model functionality to encrypt or decrypt few sections of web.config file those are
 
RSAProtectedConfigurationProvider: This is default provider and uses the RSA public key encryption algorithm to encrypt and decrypt data.
 
DataProtectionConfgurationProvider: This provider uses windows data protection application programming interface to encrypt and decrypt the data.
 
The encrypting and decrypting of connection strings in web.config file will do by using aspnet_regiis.exe command line tool and code behind.

First Method

First we will do encryption and decryption using aspnet_regiis.exe command line tool in file system website
 
To implement encryption and decryption first create one new website using visual studio. 
 
After that open web.config file in application and add sample db connection in connectionStringssection like this 
<connectionStrings>
<add name="dbconnection" connectionString="Data Source=RahulMittal;Integrated Security=true;Initial Catalog=MySampleDB"/>
</connectionStrings >
After add dbconnection in connectionString check the below steps to encrypt or decrypt the connection string in web.config.
 
1. 1) Go to Start >> All Programs >> Microsoft visual studio 2008 >> Visual Studio Tools >> Visual Studio 2008 Command Prompt (Note: if you’re using windows 7 right click on command prompt and select Run as administrator)
 
2. 2) after open command prompt type the following command aspnet_regiis.exe -pef "connectionStrings" "C:\VisualStudio2008\Authorization"
 
Here –pef indicates that the application is built as File System website. Second argumentconnectionStrings indicates that name of the configuration section needs to be encrypted. The Third argument is the physical path of the folder where the web.config file is located.
 
3. 3) after enter the command click enters if everything goes well we will get success message like “Encrypting configuration section… Succeeded!”
 
Now open your application and check connectionStrings in web.config file that would be like this
<connectionStrings configProtectionProvider="RsaProtectedConfigurationProvider">
<EncryptedData Type="http://www.w3.org/2001/04/xmlenc#Element"
xmlns="http://www.w3.org/2001/04/xmlenc#">
<EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#tripledes-cbc" />
<KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
<EncryptedKey xmlns="http://www.w3.org/2001/04/xmlenc#">
<EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-1_5" />
<KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
<KeyName>Rsa Key</KeyName>
</KeyInfo>
<CipherData>
<CipherValue>ZNUbIEnOwlZzC8qbzHj5F2GS9gLYSkWCIgCJGkrgZAX8A+8oEIssyohhxUKvAubD3jizFc5IjbLGt7HNXhoFhXNTUPYz2y6tdKJDVgDmtCgVf8Z2C990zoMRBJG+VXhmgnlo1vtHYhGx8x/bBzE1prT1+xDpep98vHF22d+LrVI=</CipherValue>
</CipherData>
</EncryptedKey>
</KeyInfo>
<CipherData>
<CipherValue>tODWlPD0Q/B/mP14GQ/5tUxcjmhHcy9a0oPunV5osNrMQRztgi2h5V6sxJOEh+NC+G9gQNkv1huXf1s7eoZRRLy5/LDtLXzzqMUOqLSlJUs9igChvi33c9XG4rwGF15Tpn4N34bpQBt94n0rpSkQ18V9HCPzii+UO64PlA+ykDeQhc9aQr4gO3mCfUzmY2S9gsXzRbzdq0oCWBDvx8UkX2uDxaysVHC9Fo7u6IrlpU0+hOdK95Y3/A==</CipherValue>
</CipherData>
</EncryptedData>
</connectionStrings>
Here we don’t want to write any code to decrypt the encrypted connectionString in our application because .NET automatically decrypts it. If we want to use the connection string just call it like normal way
string strconnection = ConfigurationManager.AppSettings["dbconnection"].ToString();
Now if we want to decrypt connectionStrings section in web.config use the following commandaspnet_regiis.exe -pdf "connectionStrings" "C:\VisualStudio2008\Authorization"
 
After command execute we will get message like “Decrypting configuration section… Succeeded!”

Now check your connctionStrings section in your web.config file you will see decrypted connection string.
 
Till now we learned how to encrypt and decrypt connectionStrings section in File system website. If I want to encrypt connection string in IIS based site like i.e. Deployed website for that we need to use the following commands
 
Encrypt connectionStrings in web.config of IIS based site
 
aspnet_regiis.exe -pe "connectionStrings" -app "/SampleWebSite"
Here –pe indicates that the application is built as IIS based site. Second argument connectionStrings is the name of configuration section needs to be encrypted. The Third argument -app indicates virtual directory and last argument is the name of virtual directory where application is deployed.
 
Decrypt connectionStrings in web.config of IIS based site
 
aspnet_regiis.exe -pd "connectionStrings" -app "/SampleWebSite"
Till now we learned how to encrypt and decrypt connectionStrings section in web.config file using aspnet_regiis.exe command line tool now I will explain code behind method to encrypt and decrypt the connection string section in web.config.
 
Second Method: In second method I will use RSAProtectedConfigurationProvider and DataProtectionConfgurationProvider to encrypt and decrypt connectionStrings in web.config using asp.net.
 
First open Default.aspx page and write the following code
<html xmlns="http://www.w3.org/1999/xhtml">
<head  runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1"  runat="server">
<div>
<asp:Button id="btnEncrypt" runat="server" Text="Encrypt" onclick="btnEncrypt_Click" />
<asp:Button ID="btnDecrypt" runat="server" Text="Decrypt" onclick="btnDecrypt_Click" />
</div>
</form>
</body>
</html>
After that open code behind page and add the following namespace references
using System;
using System.Configuration;
using System.Web.Configuration;
After add namespaces write the following code in code behind

C# code

string provider = "RSAProtectedConfigurationProvider";
string section = "connectionStrings";
protected void Page_Load(object sender, EventArgs e)
{
 
}
protected void btnEncrypt_Click(object sender, EventArgs e)
{
   Configuration confg = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
   ConfigurationSection configSect = confg.GetSection(section);
   if (configSect != null)
   {
      configSect.SectionInformation.ProtectSection(provider);
      confg.Save();
   }
}
 
protected void btnDecrypt_Click(object sender, EventArgs e)
{
   Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
   ConfigurationSection configSect = config.GetSection(section);
   if (configSect.SectionInformation.IsProtected)
   {
      configSect.SectionInformation.UnprotectSection();
      config.Save();
   }
}

VB.NET

Imports System.Web.Configuration
Partial Class _Default
   Inherits System.Web.UI.Page
   Private provider As String = "RSAProtectedConfigurationProvider"
   Private section As String = "connectionStrings"
   Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
   End Sub
   Protected Sub btnEncrypt_Click(ByVal sender As Object, ByVal e As EventArgs)
      Dim confg As Configuration = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath)
      Dim confgSect As ConfigurationSection = confg.GetSection(section)
      If confgSect IsNot Nothing Then
         confgSect.SectionInformation.ProtectSection(provider)
         confg.Save()
      End If
   End Sub
   Protected Sub btnDecrypt_Click(ByVal sender As Object, ByVal e As EventArgs)
      Dim config As Configuration = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath)
      Dim confgSect As ConfigurationSection = config.GetSection(section)
      If confgSect.SectionInformation.IsProtected Then
         confgSect.SectionInformation.UnprotectSection()
         config.Save()
      End If
   End Sub
End Class
 
After that open web.config file in application and add sample db connection in connectionStrings section like this 
<connectionStrings>
<add name="dbconnection" connectionString="Data Source=RahulMittal;Integrated Security=true;Initial Catalog=MySampleDB"/>
</connectionStrings >
Now run your application and check your web.config file after click on Encrypt button that would be like this 
<connectionStrings configProtectionProvider="RsaProtectedConfigurationProvider">
<EncryptedData Type="http://www.w3.org/2001/04/xmlenc#Element"
xmlns="http://www.w3.org/2001/04/xmlenc#">
<EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#tripledes-cbc" />
<KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
<EncryptedKey xmlns="http://www.w3.org/2001/04/xmlenc#">
<EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-1_5" />
<KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
<KeyName>Rsa Key</KeyName>
</KeyInfo>
<CipherData>
<CipherValue>WagJ9DDjWTNc1nmYVNQXaQqXalQzXaiCHAOtUJvTWBRZiuT6UK1fBElM80PnL6dC5Umb8qvfHdkSMgoMW9CJzwOTZ0zTy17JBGZqRQmlfW2G9LacoWIil0UrxjhgmJmRXhwXHFpdGwEVl7AoQGVlJGabXuChutaTxmfGOoUbCr0=</CipherValue>
</CipherData>
</EncryptedKey>
</KeyInfo>
<CipherData>
<CipherValue>qry5qnr3qxOgyoNPeP7OKEiHpr/PPTsaeQ2mYUsSK7cg4Kkl9uPO4RyUXgBIkgCTsjbObqLlyndcSBnYyek6bxG/IBL82G1R5J1ci8i1eyt8kIDqouzYOx5vtouErld4z1L+7WGf9Wg37QAH5RiiEfkCHndJJq3dTqjxnnXZSno6NgbxSXDfqzwE/eKDVhGV3oaTQSfjVmO8e5a9wvREYeeyasDhojx8J2mdy7/Q9rEIpv98RTiRxA==</CipherValue>
</CipherData>
</EncryptedData>
</connectionStrings> 
If we want to implement encryption and decryption with “DataProtectionConfigurationProvider” just replace “RSAProtectedConfigurationProvider” with “DataProtectionConfigurationProvider” and use same code.