Five common ASP. NET security defects and asp.net security defects

Source: Internet
Author: User
Tags net domain

Five common ASP. NET security defects and asp.net security defects

Ensure that the ApplicationSecurityYou should start with the first line of code. The reason is simple. As the application grows, the cost for fixing security vulnerabilities also increases rapidly. According to research by the IBM SystemsSciencesInstitute, fixing defects after software deployment costs 15 times that of detecting and eliminating defects during development.

To ensure the security of applications at minimal cost, developers should take more responsibilities in terms of code security and Attack resistance. However, to ensure program security from the initial stage of development, you must have the corresponding skills and tools, but not many developers can really master these skills and tools. Although it is a complicated process to learn to write secure code, it is best to complete it at university, internal training sessions, and industry meetings, as long as you have mastered the following five common ASP. NET application security defects and recommended correction solutions can take the lead to integrate indispensable security factors into the birth of the application.

1. Do not blindly trust user input

In Web application development, the biggest mistake for developers is to trust user input unconditionally. It is assumed that users (even malicious users) are always restricted by browsers and always interact with servers through browsers, this opens the door to attack Web applications. In fact, there are many tools for hackers to attack and operate Web sites, and they do not have to be limited to browsers, from the original interface (such as telnet) with the lowest level of character mode ), to CGI script scanners, Web proxies, and Web application scanners, malicious users may adopt many attack modes and methods.

Therefore, only by strictly verifying the legality of user input can we effectively resist hacker attacks. Applications can perform verification using multiple methods (or even methods with overlapping verification ranges), such as performing verification before authorizing user input to ensure that user input only contains valid characters, in addition, the content length of all input fields does not exceed the range (to prevent possible buffer overflow attacks). On this basis, other verification is performed to ensure that the data entered by the user is not only legal but reasonable. When necessary, you can not only adopt a mandatory length restriction policy, but also verify the input content according to the clearly defined feature set. The following suggestions will help you verify user input data correctly:

1. Verification is always performed on all user input, and the verification must be performed on a reliable platform and on multiple layers of the application.

2. Do not allow any other content except the data required for the input and output functions.

3. Set up a "trusted code base" to allow complete data verification before entering the trusted environment.

4. Check the data type before logging on to the data.

5. Define each data format in detail, such as the buffer length and integer type.

6. strictly define valid user requests and reject all other requests.

7. Check whether the test data meets valid conditions, rather than illegal conditions. This is because the data is not legal and is difficult to list in detail.

Ii. Five common ASP. NET security defects

The following five examples illustrate how to enhance the security of applications according to the above suggestions. These examples demonstrate possible defects in the Code, the security risks they bring, and how to rewrite the least code to effectively reduce the attack risk.

2.1 tampering parameters ---UseASP. NET domain validators

Blindly trusting user input is the first enemy to ensure the security of Web applications. The main source of user input is the parameters submitted in the HTML form. If you cannot strictly verify the validity of these parameters, the security of the server may be compromised.

The following C # code queries the backend SQLServer database. Assume that the values of the user and password variables are directly taken from the user input:

SqlDataAdaptermy_query=newSqlDataAdapter("SELECT*FROM accounts WHER Eacc_user='"+user+"' AND acc_password='"+password+"'",the_connection);

On the surface, these lines of code are no problem, but may actually lead to SQL injection attacks. An attacker can log on to the system smoothly by entering "OR 1 = 1" in the user input field, OR execute any Shell command by adding an appropriate call after the query.

■ Risk Analysis

When writing these lines of code, the developer has no intention of making the assumption that the user's input content only contains "normal" data-username words and passwords that meet people's common habits, but it does not contain special characters such as quotation marks, which is the root cause of SQL injection attacks. Hackers can use characters with special meanings to change the query intention and call any function or process.

■ Solution

Domain validatorsIs a way for ASP. NET developersLimits domain valuesFor example, to restrict user input, the domain value must match a specific expression.

To prevent such attacks, the first method is to prohibit Special Character Input such as quotation marks, and the second method is stricter, that is, to limit that the content of the input field must belong to a set of valid characters, example: [a-zA-Z0-9] *.

2.2 tamper with parameter 2-prevent Authentication Vulnerability 

However, the introduction of validators for each input field alone cannot prevent all attacks by modifying parameters. When performing a value range check, you must specify the correct data type.

That is to say, when using the ASP. NET range check control, you should specify the appropriate Type Attribute Based on the Data Type required by the input field, because the default value of Type is String.

<! -- The input value must be a number between 1 and 9 -->
<Asp: RangeValidator... MinimumValue = "1" MaximumValue = "9".../>

■ Risk Analysis

Because the Type attribute value is not specified, the above Code assumes that the Type of the input value is String. Therefore, the RangeValidator validators can only ensure that the String starts with a character between 0-9, and "0abcd" is also recognized.

■ Solution

To ensure that the input value is indeed an Integer, the correct method is to specify the Type attribute as Integer:

<! -- The input value must be a number between 1 and 9 -->
<Asp: RangeValidator... MinimumValue = "1" MaximumValue = "9" Type = "Integer"/>

2.3 Information Leakage ---Makes hidden domains more secure

In ASP. NET applications, information about applications can be found in almost all the _ VIEWSTATE hidden fields on HTML pages. Because_ VIEWSTATE is base64-encodedTherefore, it is often ignored, but hackers can easily decode BASE64 data and get the details provided by _ VIEWSTATE without any effort.

■ Risk Analysis

By default, __viewstate data will include:

1. Dynamic Data from page controls.

2. The developer explicitly saves the data in ViewState.

3. the password of the above data is signed.

■ Solution

EnableViewStatMAC = "true", enabled_ VIEWSTATE Data Encryption. ThenMachineKeySet the verification type3DES (as mentioned earlier ~)ASP. NET is required to use the TripleDES symmetric encryption algorithm to encrypt ViewState data.

2.4SQL injection attacks ---Use SQL parameter API

As described in the "Tampering Parameters" section above, attackers can insert special characters in the input domain to change the meaning of SQL queries and fool the database server to execute malicious queries.

■ Risk Analysis

Malicious queries may obtain any information stored in the backend database, such as the list of customer credit card numbers.

■ Solution

In addition to the method described earlier-use program code to ensure that the input content only contains valid characters. Another more robust method isUse SQL parameter API(For example, the API provided by ADO. NET) allows the underlying API (rather than the programmer) of the programming environment to construct the query.

When using these APIs, the developer can either provide a query template or a stored procedure, and then specify a series of parameter values. The underlying API can embed the parameter values into the query template, then, the constructed query is submitted to the server for query. The advantage of this method is to ensure that the parameters can be correctly embedded. For example, the system will escape the quotation marks to fundamentally prevent the occurrence of SQL injection attacks. At the same time, the quotation marks in the form are still valid characters that can be entered, which is also an advantage of using the underlying API.

Follow these steps to modify the preceding example of "Tampering with Parameters". The result is as follows:

SqlDataAdapter my_query = new SqlDataAdapter("SELECT * FROMaccounts  WHER Eacc_user=@user AND acc_password=@pass", the_connection);
SqlParameter userParam = my_query.Select_Command.Parameters.Add("@user", SqlDb.VarChar, 20);
userParam.Value = user;
SqlParameter passwordParam = my_query.Select_Command.Parameters.Add("@pass", SqlDb.VarChar, 20);
passwordParam.Value = password;

2.5 cross-site scripting ---Encode external data

Cross-site scripting (XSS) refers to embedding malicious user input into the response (HTML) page.

For example, although the following ASP. NET page is simple, it contains a major security defect:

<% @ PageLanguage = "vb" %>
<Asp: Labelid = "Label1" runat = "server"> label text </asp: label> <form method = "post" runat = "server" ID = "Form1"> enter feedback here <br>
<Asp: TextboxID = "feedback" runat = "server"/> <br> <asp: Buttonid = "cmdSubmit" runat = "server" Text = "Submit! "OnClick =" do_feedback "> </asp: Button>
</Form>
<Scriptrunat = "server"> Subdo_feedback (senderAsObject, eAsSystem. EventArgs) Label1.Text = feedback. Text EndSub
</Script>

■ Risk Analysis

Attackers can use JavaScript code to construct a malicious query. When a link is clicked, JavaScript will run. For example, the script can be embedded using the following user input:

<script>alert(document.cookie) </script>

■ Solution

In a dual-layer security system, the browser performs input verification and HTML encoding on outgoing user data displayed on the HTML page to ensure that the browser only treats user input data as pure text, instead of other content with special meanings, such as HTML code and JavaScript scripts.

In this example, you only need to add an HtmlEncode call:

Label1.Text=Server.HtmlEncode(feedback.Text);

In this way, the response HTML stream contains the HTML-encoded version of the user's input content. That is to say, the browser does not execute the JavaScript code entered by the user because there is no HTML "<SCRIPT>" tag, the characters "<" and ">" entered by the user have been replaced with HTML-encoded versions, namely "<" and "> ".

Iii. Use automatic security testing tools

Due to the constantly changing customer requirements, some organizations need to deploy new applications every three months on average. At the same time, due to the flow of people, developers are expected to develop robust and high-quality code quickly. Although it is necessary to train all developers in code security technology, it is undeniable that tools that automatically detect code security vulnerabilities can also help to quickly develop secure applications.

So far, tools commonly used by developers can only cover specific aspects of functional testing, such as performance testing and BUG/fault point detection. Manual check code has many inherent limitations and requires developers to have rich code security experience. Therefore, for writing high-quality applications, application-oriented security and tools for malicious environment downlink are also critical.

To quickly improve the quality and security of applications, the most effective way is to provide developers with a tool to automatically test applications. During the unit test, if the tool detects the security defects of the application and embeds the repair suggestions into the code, the developer can immediately identify the errors in the code, it not only facilitates modification of existing errors, but also helps avoid making the same mistakes in the future and continuously improve the Code's ability to resist attacks.

Conclusion: Web service applications are exploding, and more applications are being pushed out of the firewall. Web applications with weak security only face increasing risks. At the same time, developers are facing increasing pressure to quickly complete application development before the deadline. Pay attention to the security issues during code writing and Invest necessary resources to prepare for future Web service applications and ensure the high quality of the current applications. Only by taking the right measures from the date of birth of the application to ensure its security can we construct high-quality and secure applications.

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.