Manipulating data 71 in asp.net 2.0: Protecting connection strings and other settings information _ self-study process

Source: Internet
Author: User
Tags decrypt microsoft sql server require connectionstrings

Introduction:

Asp. NET application settings are usually stored in an XML file named Web.config. We have modified the web.config file several times in the earlier part of the tutorial. For example, in the first chapter, when we create a dataset named Northwind, the database connection string information is automatically added to the Web.config file <connectionstrings > Nodes. Later, in the 3rd chapter, we manually updated the Web.config file, added a <pages> element, and applied datawebcontrols themes to all asp.net pages.

Because the Web.config file contains sensitive information, such as a connection string, it is important to ensure that the contents of the Web.config file are secure, and that sensitive information should be hidden from unauthorized visitors. By default, any HTTP requests to a file of the. config suffix are handled by the ASP.net engine , it returns the information for "This type of page isn't served", as shown in Figure 1. This means that visitors cannot type ' http://www ' in their browser's address bar. Yourserver.com/web.config ' to visit your Web.config file.


Figure 1: Accessing Web.config through the browser will return the information "This type of page isn't served"

But what if an attacker finds other ways to access the contents of your Web.config file? What kind of modifications would he make? What steps do we take to protect this information from Web.config files? Fortunately, the vast majority of nodes in the Web.config file do not contain sensitive information. What if an attacker knew the name of the default theme used by your asp.net page?

Some nodes of the Web.config file contain sensitive information, such as: connection strings, user names, passwords, server names, encryption Keys and so on. We can find this information at the following nodes:

.<appsettings>
.<connectionstrings>
.<identity>
.<sessionstate>

In this article we will examine techniques for protecting these sensitive information. As we will see, the. NET Framework version 2.0 contains a protection configuration system that we can use to easily encrypt and decrypt selected configuration nodes.

Note : At the end of this article, we will see Microsoft's recommendation to connect to a database from a asp.net application. In addition to encrypting the connection string, we can also connect to a "Safe mode" database to make your system more powerful.

Step One: Review the protection configuration options for ASP.net 2.0

ASP.net 2.0 contains a protection configuration system to encrypt and decrypt configuration information. These methods are included in the. NET Framework, which you can use to programmatically encrypt and decrypt configuration information. This protection configuration system uses provider model mode. It allows developers to choose which encryption to perform.

The. NET framework contains 2 kinds of protected configuration providers:

. RsaProtectedConfigurationProvider: Using the asymmetric RSA algorithm when encrypting and decrypting (RSA algorithm)

. Dpapiprotectedconfigurationprovider: Using the Windows Data Protection API (DPAPI) when encrypting and decrypting

Because the protection configuration system performs the provider design pattern, we can create our own protected configuration provider and apply it to our own programs. The specific process can be read in the article "Implementing a" Protected Configuration Provider "(Http://msdn2.microsoft.com/en-us/library/wfc2t3az (vs.80). aspx)

RSA providers and DPAPI providers use the keys when encrypting and decrypting, which can be stored in machine-level (Machine-level) and user-level (user-level). Machine-level keys are ideal in this case: Each Web application runs on its own proprietary server, or multiple applications on a server share the same encrypted information. User-level keys are the ideal security option in a shared server environment. At this point, other programs on the same server cannot decrypt your encrypted configuration information.

The example in this tutorial will use the DPAPI provider and machine-level keys. Specifically, we will encrypt the <connectionStrings> nodes in the Web.config file. to RSA For more information on provider and user-level keys, please refer to the extension readings at the end of this article.

  Note: RsaProtectedConfigurationProvider and Dpapiprotectedconfigurationprovider Providers in the Machine.config documents were separately set into RsaProtectedConfigurationProvider and DataProtectionConfigurationProvider. when we encrypt or decrypt the configuration information we need to provide the corresponding provider name (that is, rsaprotectedconfigurationprovider or DataProtectionConfigurationProvider) rather than the actual type name (that is, RsaProtectedConfigurationProvider and Dpapiprotectedconfigurationprovider). You can find machine.config files in the $windows$/microsoft.net/framework/version/config folder.

Step two: Programmatically encrypt and decrypt configuration nodes

With a provider, we only need a few lines of code to encrypt or decrypt a configuration node. The code simply needs to refer to the appropriate configuration node, call its ProtectSection or Unprotectsection method, And then call the Save method to execute. In addition, the. NET framework contains a very useful command-line feature for encryption and decryption, and we will examine that feature in step 3rd.

For demonstration purposes, we need to create a ASP.net page containing buttons to encrypt and decrypt the <connectionStrings> node of the Web.config file.

Open the Encryptingconfigsections.aspx page in the Advanceddal folder, drag a TextBox control to the page, and set its ID to Webconfigcontents;textmode property to Multiline;width and rows Sex was 95% and 15. The TextBox control is used to display the contents of the Web.config file to see if its contents are encrypted. Of course, in a real-world program, we can't show the contents of the Web.config file.

Add 2 button controls below the TextBox control with IDs Encryptconnstrings and Decryptconnstrings respectively, and set their Text property to "Encrypt Connection Strings" and " Decrypt Connection Strings ".

At this point your interface looks similar to the following:


Figure 2: Adding a TextBox control and 2 button controls on the page

Next, we need to display the contents of the Web.config file in the TextBox control with ID webconfigcontents when the page is first logged in. Add the following code in the background class of the page, which adds a method named Displaywebconfig that, in the Page_Load event handler, calls the method when Page.IsPostBack is false:

protected void Page_Load (object sender, EventArgs e)
{
 //on the Page visit, call Displaywebconfig method
   if (! Page.IsPostBack)
 displaywebconfig ();
}

private void Displaywebconfig ()
{
 //reads in the contents of Web.config and displays them in the TextBox
 stre Amreader Webconfigstream =
 file.opentext (path.combine (Request.physicalapplicationpath, "Web.config"));
 String configcontents = Webconfigstream.readtoend ();
 Webconfigstream.close ();

 Webconfigcontents.text = configcontents;
}

The Displaywebconfig method calls the file class class to open the Web.config file of the application, and the call StreamReader class class reads the content into a string; class to get the physical address of the Web.config file. All 3 classes are located in the System.IO namespace. So we should add a using System.IO declaration at the top of the background class, or add "System.IO" to the front of those classes. Prefix.

Next, we need to add event handlers for the click events for these 2 buttons, and use machine-level keys in a DPAPI provider to <connectionStrings> The node is encrypted and decrypted. In the designer, double-click the 2 buttons to add the Click event handler and add the following code:

protected void Encryptconnstrings_click (object sender, EventArgs e) {//Get configuration information about Web.config

 Configuration config = webconfigurationmanager.openwebconfiguration (request.applicationpath); Let's work with the <connectionStrings> section configurationsection connectionstrings = config.
 GetSection ("connectionstrings"); if (connectionstrings!= null)//Only encrypt the section if it's not already protected if (!connectionstrings.section information.isprotected) {//Encrypt the <connectionStrings> section using the//DATAPROTECTIONCONFIGURATIONP
  Rovider provider ConnectionStrings.SectionInformation.ProtectSection ("DataProtectionConfigurationProvider"); Config.
  
  Save ();
 Refresh the web.config display Displaywebconfig (); } protected void Decryptconnstrings_click (object sender, EventArgs e) {//Get configuration information about Web.con Fig Configuration config = webconfigurationmanager.openwebconfiguration (Request.

 Applicationpath); Let's work with the <connectionStrings> section configurationsection connectionstrings = config.
 GetSection ("connectionstrings"); if (connectionstrings!= null)//Only decrypt the section if it is protected if (connectionstrings.sectioninformation.i sprotected) {//Decrypt the <connectionStrings> section connectionStrings.SectionInformation.UnprotectSection (
  ); Config.

  Save ();
 Refresh the web.config display Displaywebconfig ();

 }
}

The 2-button event handler code is almost the same. They start by WebConfigurationManager the class class Openwebconfiguration method to get information about the Web.config file for the current application. This method returns a Web configuration file based on the specified valid path. Next, access the <connectionStrings> of web.config files via the GetSection (sectionname) method of the Configuration class class Node. This method returns a ConfigurationSection object.

The ConfigurationSection object contains a Sectioninformation attribute that describes other relevant information about the encrypted node. As the above code shows, we determine whether the configuration node is encrypted by looking at the Sectioninformation isprotected property. In addition, you can also pass the protectsection of Sectioninformation ( Provider) and Unprotectsection methods to encrypt or decrypt a node.

The ProtectSection (provider) method has a string-type input parameter that specifies the name of the protected configuration provider to encrypt. In the event handler for the Encryptconnstring button, we pass "DataProtectionConfigurationProvider" to the ProtectSection (provider) method, Therefore, the use of DPAPI provider is indicated. The Unprotectsection method can determine the provider that is used for encryption and therefore does not require any input parameters.

After invoking the protectsection (provider) or Unprotectsection method, I must also invoke the Save methods method of the configuration object for specific operations. Once the encryption or decryption is complete and saved, we call the Displaywebconfig method to upload the contents of the updated Web.config file to the TextBox control.

After typing the above code, test the encryptingconfigsections.aspx page in the browser, you will first see the page will web.config the file <connectionStrings> The contents of the node are displayed in plain text.


Figure 3: Displaying the contents of <connectionStrings> nodes

Now, click on the "Encrypt Connection Strings" button, if "Request confirmation" (requesting validation) is active, A HttpRequestValidationException exception is thrown when the page is returned, displaying a message: "A potentially dangerous request.form value is detected from the Client. ". This request validation, in ASP.net 2.0 Rimmer, is considered active and prevents the server from accepting content that contains HTML that is not encoded. It is designed to protect the server from injection script attacks. You can disable this feature from a page or an application. We disabled it on this page, and validaterequest set to False in the @page tag at the top of the page declaration code, as follows:

<%@ Page validaterequest= "False" ...%>

After disabling the feature, click the "Encrypt Connection Strings" button again, and the page will return to the configuration file and encrypt the <connectionStrings> node with DPAPI provider. The TextBox control then displays the updated contents of the Web.config file, as shown in Figure 4, the information for the,<connectionstrings> node is now encrypted.


Figure 4: Click the "Encrypt Connection Strings" button to encrypt the <connectionString> node

Before encrypting, I temporarily shifted the contents of the <CipherData> elements:

<connectionstrings
 configprotectionprovider= "DataProtectionConfigurationProvider" >
 < encrypteddata>
 <CipherData>
 <ciphervalue>aqaaancmnd8bfderjhoawe/...zchw==</ ciphervalue>
 </CipherData>
 </EncryptedData>
</connectionStrings>

  Note The:<connectionstrings> element specifies the provider (that is, dataprotectionconfigurationprovider) to encrypt. When clicked "Decrypt Connection Strings button, the Unprotectsection method will use this information. For encrypted connection strings, the system can automatically decrypt them. In short, we do not need to add any additional code to the encrypted <connectionString> node. let's do a validation and open the previous tutorials, such as (~/basicreporting/simpledisplay.aspx page), as shown in Figure 5, the page works as expected, This indicates that the encrypted connection string was automatically decrypted by the ASP.net page.


Figure 5: The data access layer automatically decrypts the connection string information

To restore the encrypted <connectionStrings> node to a plain text style, click the "Decrypt Connection Strings" button. After the page returns, you will see the connection string in the Web.config file revert to the plain text style. At this point, the screen looks like it was originally logged in (see Figure 3)

Step three: Encrypt the configuration node with Aspnet_regiis.exe

The. NET Framework contains a number of command-line tools that you can find in the $windows$/microsoft.net/framework/version/folder folder. In the 59th chapter, the Using SQL cache dependency SqlCacheDependency For example, we use the Aspnet_regsql.exe command-line tools to add the necessary architecture for SQL cache dependencies. Another useful tool in this folder is ASP.net IIS Registration tool (Aspnet_regiis.exe). As its name implies, this asp.net IIS registration tool is primarily used to register ASP.net 2.0 applications on the Microsoft Professional Web Server,iis.

In addition to its IIS-related properties, the ASP.net IIS registration tool can also encrypt and decrypt the configuration node of a Web.config file. The following is a general code that encrypts the configuration node using the Aspnet_regiis.exe command-line tool:

ASPNET_REGIIS.EXE-PEF Section Physical_directory-prov Provider

Where section is the configuration node to encrypt (such as "connectionstrings"), Physical_directory is the complete physical path of the Web application root node; provider is used protected The name of the configuration provider (such as "DataProtectionConfigurationProvider"). In addition, if you register your Web application in IIS, you can use a considerable path instead of an absolute path:

Aspnet_regiis.exe-pe Section-app Virtual_directory-prov Provider

The following is an example of using aspnet_regiis.exe, which encrypts <connectionStrings> nodes with DPAPI provider, machine-level keys:

Aspnet_regiis.exe-pef
"connectionstrings" "C:/websites/aspnet_data_tutorial_73_cs"
-prov "DataProtectionConfigurationProvider"

Similarly, the Aspnet_regiis.exe command-line tool can also be used to decrypt configuration nodes, but we will replace-PEF with-pdf or-PD. Of course, you do not need to specify the provider name when decrypting.

Aspnet_regiis.exe-pdf Section Physical_directory--
 or--
aspnet_regiis.exe-pd Section-app virtual_directory

  Note: Because we are using the DPAPI provider, it uses the key that is specified by the computer, so you must run the Aspnet_regiis.exe tool on the same computer where the Web page is stored. For example, if you run this command line on your local computer, the encrypted connection string is then uploaded to another server and cannot be decrypted by the server because the cryptographic key is specified on the local computer. This limitation does not exist if you are using RSA provider, because RSA Provider can pass the secret key (RSA keys) to another computer.

Understanding Database Authentication Options

Before any application issues a select,insert,update to a Microsoft SQL server database, or a delete request, the database first determines the identity of the requester. This process can be divided into 2 authentication modes: Authentication and SQL Server provides:

. Windows Authentication: When you run a asp.net application in asp.net Development server in Visual Studio 2005, ASP. NET application assumes identity is the current logged-on user. If you are running on Microsoft Internet Information Server (IIS), ASP. NET applications assume that identity is the Domainname/machinename or domainname/network SERVICE, although these can be customized by users.

. SQL authentication: You need to provide a user ID and password when validating, and with SQL authentication, you can supply IDs and password by a connection string.

Windows Authentication mode is generally used because it is more secure. In Windows Authentication mode, the connection string does not require a username and password, and if the Web server and database server are separate computers, Credentials) authentication is not transmitted across the network in plain text format. In the case of SQL authentication mode, the connection string is hard-coded, and authentication is transmitted in plain text between the Web server and the database server.

This tutorial uses Windows authentication. We can use the connection string to see what kind of authentication is being used. The connection string for the Web.config file in this tutorial is as follows:

Data source=./sqlexpress; attachdbfilename=| Datadirectory|/northwnd. MDF; Integrated security=true; User Instance=true

The term "Integrated security=true" and the lack of a username and password all indicate that we are using Windows Authentication mode. However, replace "integrated security=true" with the term "Trusted connection=yes" or "Integrated SECURITY=SSPI" in some connection strings, but they all indicate the use of Windows Authentication.

The following code shows the use of SQL authentication:

Server=servername; Database=northwind; Uid=userid; Pwd=password

Imagine an attacker who can view the Web.config file for your application. If you are using SQL authentication mode to connect to a database over the Internet, an attacker can use the connection string to pass through the SQL Management The ASP.net page on studio or his own website is connected to your database. To reduce risk, we need to encrypt the connection string for the Web.config file.

  Note: For more information about different authentication modes in SQL Server, see the article "Building Secure asp.net applications:authentication, Authorization, and secure Communication "(http://msdn2.microsoft.com/en-us/library/aa302392.aspx); about Windows and SQL For more examples of authentication differences, you should refer to the Connectionstrings.com Web site.

Conclusion:

By default, ASP. NET application, all files with the. config suffix are not accessible through the browser. This is because these files may contain sensitive information, such as database connection strings, user names and passwords, and so on.. NET The protection configuration system contained in 2.0 can be protected by encrypting the specified configuration node. There are 2 built-in protected configuration providers: one using the RSA algorithm and the other using Windows Data Protection API (DPAPI).

This article examines the use of DPAPI provider to encrypt and decrypt configuration information. We can do this programmatically, as we discussed in step 2nd, or by using the Aspnet_regiis.exe command-line tool, as discussed in step 3rd. For more information about using RSA provider and user-level keys, please refer to the extended readings in this article.

I wish you a happy programming!

Author Introduction

Scott Mitchell, author of this series of tutorials, has six asp/asp. NET book, is the founder of 4GuysFromRolla.com, has been applying Microsoft Web technology since 1998. You can click to see all Tutorials "[translation]scott Mitchell asp.net 2.0 data tutorial," I hope to learn asp.net help.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.