Five common asp.net safety flaws

Source: Internet
Author: User
Tags html form html page range sql injection sql injection attack valid web services net domain
Asp.net| security guarantees that the application's security should start when writing the first line of code, for the simple reason that as the scale of the application grows, the cost of patching up the security vulnerabilities increases rapidly. According to the IBM System Science Association (Systems Sciences Institute), if you wait until the software is deployed to fix the bug, it costs 15 times times as much to detect and eliminate defects during development.
In order to secure the application with minimal cost, developers should assume more responsibility for the security of the code itself, the ability to resist attacks, and so on. However, to protect the security of the program from the earliest stages of development, you must have the appropriate skills and tools, and there are not many developers who really master these skills and tools. While learning to write safe code is a complex process, preferably in universities, in-house training sessions, industry meetings, but as long as you have mastered the following five common asp.net application security flaws as well as recommended corrective solutions, you can lead a step forward to integrate the necessary security factors into the application of the birth of the time.

One, can not blindly believe that user input

In Web application development, developers most often fail to trust user input unconditionally, assuming that users (even malicious users) are always restricted by browsers and always interact through browsers and servers, opening the door to attacking web apps. In fact, many of the tools that hackers attack and manipulate Web sites do not have to be limited to browsers, from the raw interface of the lowest-level character mode (for example, Telnet) to CGI script scanners, web proxies, Web application scanners, and malicious users who may be using a lot of attack patterns and tools.

Therefore, only rigorously verifying the legality of user input can effectively resist hacker attacks. An application can perform validation in a variety of ways, even with a range of validation scopes, for example, to perform validation before authenticating user input, to ensure that user input contains only legitimate characters, and that the content length of all input fields does not exceed the range (to prevent possible buffer overflow attacks). On this basis, other validation is performed to ensure that the data entered by the user is not only legitimate but also reasonable. When necessary, not only can you take a mandatory length restriction policy, but you can also perform validation on the input according to a well-defined set of features. The following recommendations will help you validate user input data correctly:

⑴ always performs validation on all user input, and validation must be performed on a reliable platform and should be performed on multiple layers of the application.

⑵ do not allow anything else except the data that is required for input and output functions.

⑶ establishes a "trusted code base" that allows data to be thoroughly validated before it enters a trusted environment.

Check the data type before ⑷ the login data.

⑸ defines each data format in detail, such as buffer length, integer type, and so on.

⑹ strictly defines legitimate user requests and rejects all other requests.

⑺ test data satisfies legitimate conditions, rather than testing illegal conditions. This is because there are many cases of illegal data and it is difficult to enumerate them in detail.



Two or five kinds of common asp.net safety defects

Here are five examples of how to enhance the security of your application as suggested above. These examples demonstrate possible flaws in your code, the security risks they pose, and how to rewrite the least code to effectively reduce the risk of attack.

2.1 Tamper Parameters

Using the ASP.net domain validator

Blindly trusting user input is the first enemy to secure Web application. The primary source of user input is the parameters submitted in an HTML form, which can be compromised if the legality of these parameters is not rigorously validated.

The following C # code queries the back-end SQL Server database, assuming that the values of the user and password variables are directly taken from user input:

SqlDataAdapter my_query = new SqlDataAdapter (
"SELECT * from Accounts WHERE acc_user= '" + user + "' and acc_password= '" + password, the_connection);
On the face of it, these lines of code have no problems, but they can actually lead to SQL injection attacks. An attacker who enters "OR 1=1" in the user input domain can successfully log on to the system, or execute arbitrary shell commands as long as the appropriate invocation is followed by the query:

'; EXEC Master.. xp_cmdshell (Oshell command here)--
Risk analysis

When you write these lines of code, developers inadvertently make the assumption that the user's input contains only "normal" data-the user's usual custom name, password, but not the special characters such as quotes, which is the root cause of the SQL injection attack to succeed. Hackers can use some characters with special meanings to change the original meaning of the query, and then invoke any function or procedure.

Solution

A domain validator is a mechanism that lets asp.net developers limit the value of a domain, for example, restricting the field values entered by the user must match a particular expression.

To prevent this attack from succeeding, the first approach is to prohibit special character input such as quotes, and the second approach is stricter, that is, the contents of a qualifying input field must belong to a collection of legitimate characters, such as [a-za-z0-9]*.

2.2 Tamper Parameter bis

Avoid a vulnerability to validation actions

However, the introduction of validators for each input domain alone will not prevent all attacks that are implemented by modifying parameters. When you perform a numeric range check, you also specify the correct data type.

That is, when you use the scope of ASP.net to check the control, you should specify the appropriate type property based on the data type required by the input field because the default value for type is string.

<!--require that the input value must be a number between 1-9-->
<asp:rangevalidator ... Minimumvalue= "1" maximumvalue= "9" .../>
Risk analysis

Because no type attribute value is specified, the above code assumes that the type of the input value is string, so the RangeValidator validator 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 way is to specify the type attribute as Integer:

<!--require that the input value must be a number between 1-9-->
<asp:rangevalidator ... Minimumvalue= "1"
Maximumvalue= "9" type= "Integer"
2.3 Information leaks

Make hidden fields more secure

In the ASP.net application, information about the application can be found in almost all __viewstate hidden fields of the HTML page. Since __viewstate is base 64 encoded, it is often ignored, but hackers can easily decode base 64 data, and no effort is needed to get the detailed information __viewstate provides.

Risk analysis

By default, __viewstate data will contain:

⑴ Dynamic Data from a page control.

⑵ the data that developers explicitly save in viewstate.

⑶ the above data to sign the code.

Solution

Set enableviewstatmac= "True" to enable the __viewstate data encryption feature. Then, the machinekey authentication type is set to 3DES, which requires asp.net to encrypt viewstate data with Triple DES symmetric encryption algorithm.

2.4 SQL Injection attack

Using the SQL parameter API

As described in the "Tamper parameters" section of the previous article, an attacker can insert a special character into an input field, altering the intent of the SQL query and tricking the database server into executing a malicious query.

Risk analysis

It is possible for a malicious query to obtain any information that the back-end database holds, such as a list of customer credit card numbers.

Solution

In addition to the approach described earlier--using program code to make sure that the input contains only valid characters, another more robust approach is to use the SQL parameter APIs (such as the APIs provided by Ado.net) to construct queries for the underlying APIs of the programming environment, not programmers.

When using these APIs, the developer either provides a query template, or provides a stored procedure, and then specifies a series of parameter values that the underlying API embeds the parameter values into the query template and submits the constructed query to the server query. The advantage of this approach is to ensure that the parameters are properly embedded, for example, that the system will escape the quotation marks and fundamentally eliminate the occurrence of SQL injection attacks. Also, the quotation marks in the form are still valid characters that allow input, which is an advantage of using the underlying API.

The following examples of modifying the "Tamper Parameters" section of this line of thought are as follows:

SqlDataAdapter my_query = new SqlDataAdapter ("Select * from Accounts
WHERE acc_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 (
"@", sqldb.varchar,20);
Passwordparam.value=password;
2.5 Cross-station script execution

Encode the outgoing data

Cross-site scripting Execution (cross-site scripting) is the embedding of malicious user input into an answer (HTML) page. For example, the following ASP.net page, though simple, contains a major security flaw:

<%@ Page language= "vb"%>
<asp:label id= "Label1" runat= "Server" >
Label text
</asp:Label>
<form method= "POST" runat= "server" id= "Form1" >
Please enter the feedback information here <br>
<asp:textbox id= "Feedback" runat= "Server"/><br>
<asp:button id= "Cmdsubmit" runat= "Server"
text= "Submit!" >
</asp:Button>
</form>
<script runat= "Server" >
Sub Do_feedback (sender as Object, E as System.EventArgs)
Label1.text=feedback. Text
End Sub
</script>
Risk analysis

An attacker could construct a malicious query using JavaScript code, and JavaScript would run when the link was clicked. For example, a script can be embedded by the following user input:

<script>alert (Document.cookie)
</script>
Solution

In a two-tier security system, input validation and HTML encoding are performed on outgoing user data appearing in HTML pages, ensuring that browsers only take user input data as pure text, rather than other content that has special meaning, such as HTML code, JavaScript script.

For this example, just add a HTMLEncode call:

Label1.text=server.htmlencode (feedback. Text)
In this way, the answer HTML stream will contain the HTML-encoded version of the user input, that is, the browser will not execute the JavaScript code entered by the user because there is no HTML "<SCRIPT>" tag, user-entered "<" and ">" Characters have been replaced with HTML-encoded versions, i.e. "<" and ">".


Iii. use of automated safety testing tools

As customer demand changes, some units deploy new applications every three months, and because of the flow of people, they have high expectations for developers to quickly develop robust, high-quality code. While it is essential that all developers are trained in code security technology, it is undeniable that tools that automatically detect code vulnerabilities can also help you quickly develop secure applications.

So far, the tools commonly used by developers can only cover specific aspects of functional testing, such as performance testing, bug/fault detection. Manual inspection of code has many inherent limitations, and requires rich experience in code security, so for the preparation of high-quality applications, application-oriented security and the malicious environment of the tool is also critical.

The most effective way to quickly improve the quality and security of applications is to provide developers with a tool for automated test applications. If during a unit test, the tool detects security flaws in the application and embeds the patch recommendations into the code, enabling developers to immediately identify errors in the code, not only to modify existing bugs, but also to avoid making the same mistakes in the future and continually improve the code's ability to resist attacks.

Conclusion: Web Services applications are exploding, and more and more applications are being launched outside the firewall, and the risk of security-vulnerable Web applications will only increase. At the same time, developers are under increasing pressure to quickly complete application development before pressing deadlines. Focus on security issues while coding, and invest the necessary resources to prepare for future Web service applications while ensuring the high quality of current applications. Only by taking the correct measures to ensure the safety of the application from the date of birth can we construct a high quality and safe application.



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.