Sivo ENOW big front end

Company official website: CVTE(Guangzhou Shiyuan Shares)

Team: ENOW team of CVTE’s Future Education Sivo Software Platform Center

The author:

preface

Hello, AV8D ~ Today we are going to share the topic of front-end Web security. The importance of Web security is self-evident, is the topic that all Internet enterprises can not be wound around.

In the field of web front end, although the browser has helped us to do a lot of isolation and protection measures at the system level, the open characteristics of web code and THE language features of HTML and JS make hackers still have a lot of opportunities. Google, Facebook and so on have their own vulnerability reward mechanism. To find and fix vulnerabilities before hackers, to minimize corporate losses.

Web security is a commonplace topic, but often said often new, today again comb (c) reason (v) again some of the front end of the Web attack means, let everyone read after this article can learn:

  • Common front end security problems and corresponding solutions;
  • Tips and tips on cyber attacks;
  • Some classic cases of vulnerability attacks;
  • And the new means of attack that have recently entered our sights;

XSS

1. Introduction to XSS

XSS is cross-site Scripting. It refers to the use of loopholes left by the development of web pages, through clever methods to inject malicious instructions to the web pages, users to load and execute the malicious web pages created by the attackers. In general, the hacker’s idea is to make users run their own attack code in the page they visit. Once successful, the hacker may do the following things:

  • Get the current user on this sitecookiesIn order to get the user’s sensitive information;
  • Initiate some non-original operation requests as the current user, such as deleting website friends, Posting, sending private messages and so on;
  • implementationDDosAttack;

Depending on the source of the attack, XSS can be broadly classified as persistent or non-persistent (of course, there are also reflective, stored, and Dom types, but I personally prefer the first category because it is easier to understand).

Non-persistent attacks

Non-persistent XSS is characterized by its immediacy. It does not need to be stored on a server, but can be attacked by cleverly constructing a URL with malicious code and then directing the user to click.

To take a simple example, suppose you have a website like this.

If you are careful, you will find that this page will put the content of the Q parameter above the URL into the page, and you will see the code implementation of the page as follows:

<h1 id="query-key"></h1>
<span>The query results are as follows:</span>
// ...
<script>
  const reg = new RegExp("(^|&)q=([^&]*)(&|$)"."i");
  const res = window.location.search.substr(1).match(reg);
  if(res ! =null) {
      const query = decodeURIComponent(res[2]);
      document.getElementById('query-key').innerHTML = query;
  };
</script>
Copy the code

You almost laughed when you realized that it doesn’t filter the Query, but inserts it directly into the DOM using the innerHTML method: no security awareness! What if you wanted to design a URL for the site to be clicked on and then launch an XSS attack to retrieve the cookies?

It’s not so easy to write an XSS link with the backhand:

http://abcd.com?q=<script>alert(document.cookie)</script>
Copy the code

The page will insert the script tag in the Q parameter into the DOM for execution, and the prompt box will pop up.

Thinking is certainly no problem, but you may find no effect, this is because the browser for some dangerous like script tags made intercepting filter insertion, of course it won’t we, after all, we can’t write on the face, I want to do bad things that doesn’t respect the opponent, so let’s change the gentle way to go:

http://abcd.com?q=<img src="" onerror="alert(document.cookie)" />
Copy the code

Since we’re inserting an image, browsers don’t normally filter and intercept it, so we leave SRC blank and it triggers an onError event, indirectly executing our malicious script. Done!

Persistent attack

The downside of a non-persistent attack is that you need to make your URL visible to the user and induce them to click on it. In other words, you need to increase the visibility of the malicious link! This is very troublesome, is there a way to get rid of it once and for all?

If we can find a way to put the malicious code into the database of the website, then the next site all access to my this malicious data users are not all suffer?

Therefore, if the comment area of a website is not filtered for security processing, then we can submit the malicious script to the background server through the way of comments, and then any user who visits this comment page will execute my code, so as to achieve the purpose of attack.

User A wrote A malicious code in the comment and submitted the background:

When user B visits the comment page, the page loads A’s comment and triggers the malicious code (at this point, user B has done nothing but open up A very formal website and he is caught) :

Therefore, we can summarize the characteristics of durable XXS:

  • Because it is stored in a database, it is persistent;
  • Because there is no need to induce users to click on malicious links to cause attacks, it is easier to achieve the purpose of attack, so durable XSS is more harmful;

2. Defense mode

After introducing the concept, we can know that there are roughly two ways to defend against XSS attacks:

  • Find ways to prevent the injection and execution of malicious code;
  • Using a more secure method to verify and protect the user’s identity credentials to reduce the damage caused by XSS attacks;

1. Use HTML escapes. Always be vigilant about external inserts. For all external inserted code should be an escape, the script, & < > “‘/dangerous characters, such as filtering and escape replacement, at the same time try to avoid using innerHTML, document, write, outerHTML, methods of eval, Use more secure textContent,setAttribute and other methods to do instead;

2. Enable CSP protection. A Content Security Policy (CSP) is designed to defend against XSS attacks. You can configure the Policy by setting content-security-policy in the HTTP header. If the CSP is set to the following mode:

Content-Security-Policy: script-src 'self'
Copy the code

Then the site will:

  • Inline script execution is not allowed;
  • Prohibit loading outland code;
  • Prohibit outland submission;

This will effectively prevent XSS attacks, of course, it is also very strict, may cause some restrictions on their own business development, more about CSP content can see MDN.

3. Set HttpOnly. Of course, this is already a method to reduce the harm of XSS. For all cookies containing sensitive information, httpOnly should be set on the server. The cookie field set httpOnly cannot be obtained through JS, which reduces the risk of privacy leakage of user credentials when XSS attacks.

CSRF

1. Introduction to CSRF

Another familiar, often asked knowledge point interview.

Cross-site Request Forgery (CSRF) : An attacker induces a victim to access a third-party website, and then sends a cross-site request to the attacked website. The registration certificate obtained by the victim from the attacked website is used to bypass the user authentication in the background and to impersonate a user to perform an operation on the attacked website.

The attack process of CSRF is briefly introduced:

  • 1. The victim logs in to the target website A;
  • 2. The victim is somehow exposed to the link of the malicious website B;
  • 3. The victim clicks on the link to visit website B. The JS code in website B executes and secretly sends A request to the target website A;
  • 4. Since the victim had logged in to website A, the request carried the relevant cookie credentials of website A, and the request was successfully executed at last;

Finally, without the victim’s knowledge, the malicious website performs some operations with permission to the target website as a victim, bringing a series of harms and losses to the victim.

The process is easy to understand, and space is limited, so I won’t give you an example to explain it in detail.

As for the cross-domain limitation of the browser, how the malicious website initiates a request to the target website is a part of the knowledge point of how to solve the cross-domain limitation, which can be summarized as the following methods:

  • It’s very easy for GET requests,imgTag links are not subject to browser cross-domain restrictions, so requests can be initiated directly in the form of IMG.
  • For POST requests, the CORS method is still easy to implement;

2. Defense mode

Now that we know the full flow of attacks, we can begin to look at the stages at which we can defend against CSRF attacks.

  • First of all, the attack request is basically initiated from a third party website, so the client seems unable to block the request through code.
  • However, the key step is that the malicious request must be initiated with identity credentials, so that the request can be passed and executed. Then, how to increase the difficulty of obtaining identity credentials for the third-party websites through a series of measures, and improve the authentication method of the server’s identity credentials have become the key work of defending CSRF.

1, SameSite cookies

If we could make it impossible for third party requests to carry relevant cookies, then all the problems would be solved. Fortunately, the browser provides a SameSite attribute for cookies, which indicates that cookies are not sent with cross-domain requests. The proposal was put forward by Google, but it is still in the trial stage and has compatibility problems.

2, CSRF Token

Since the browser temporarily can not help us solve all the problems, let’s find a way to make the identity verification mechanism a little more complex, only relying on cookies does not guarantee security, then add a verification dimension. SCRF tokens are one such solution.

This solution process is: when the user visits the website, the background server generates a Token according to the algorithm, and then puts this Token in seesion. When the website initiates a request, it should not only carry cookie credentials, but also take this Token, and then verify the identity of the background before performing the operation. Since the SCRF Token is placed in the session, when a third-party website initiates a request, it cannot get the SCRF Token. Therefore, the identity verification does not pass, thus achieving the effect of defending against attacks.

3. Homology test

Since CSRF is initiated by three-party websites, if we can determine which websites the server receives the requests from each time, we can filter the requests from those websites with security risks and reduce the risk of being attacked.

Referer and Origin are one of the header fields in an HTTP request that indicate the page from which the request was linked. Therefore, the background server can check whether the field is from its own website link to prevent third-party websites from launching CSRF attacks. However, the reliability of homologous detection is not high. For example, in 302 redirection, in order to protect the source, the HTTP request will not carry the Origin field, and the Referer field will not be sent due to the restrictions of the Referer Policy rule.

4. Add secondary verification

For some risky request operations (such as account deletion, withdrawal and transfer), we can increase the user’s second time, such as the initiation of mobile phone or email verification code, so as to reduce the harm of CSRF calls.

3. Some cases

1) Google Digital Garage is an online educational product of Google. A foreign security engineer wrote on his blog about how to remove personal accounts from Google Digital Garage through CSRF attacks.

2) This article describes a security vulnerability on Facebook’s website, and how CSRF can be used to bypass security protection to achieve account takeover.

XS-Leaks

I believe some friends have begun to fall asleep, after all, the two Web attack methods introduced in front of many people have been familiar, such as the number of precious. The final chapter takes a look at another, perhaps less common, Web attack that is beginning to make a comeback: XS-Leaks.

1. What is XS-Leaks?

Xs-leaks stands for cross-site Leaks. Xs-leaks makes use of a mechanism for querying HTTP caches to infer information about the current user from the resource cache. If you’re hearing xS-Leaks for the first time, I’m sure you’re surprised at how the average HTTP resource cache can leak user information.

The Chrome team has published an article on their developer website stating that after version 86, the browser will start to partition requests for caching resources (by domain name), because the previous caching mechanism may cause privacy issues.

Until then, Chrome’s request caching strategy was simple:

  • 1. The user visits page A and requests an image resource. After the browser gets this image, it will cache this image and take the URL of this image as the key value of cache query;
  • 2. The user then visits page B. If the page also uses the above image, the browser will first query whether this resource has been cached.

Because cache resources are not restricted by domain names, all websites share cache resources. Therefore, this can be used to detect whether a user has visited a specific website: A malicious website can infer a user’s browsing history by making a specific resource request and judging whether the resource is from the cache. For example, if I ask for a LOGO image of a nugget (or some other more unique resource) on my site, if I determine that the image is from the cache, I know that the user visited the nugget site.

Xs-leaks works in a similar way, using the mechanism of querying HTTP caches to retrieve some user data by detecting whether a query has produced results. The main steps of the XS-Leaks attack are as follows:

  • 1. Delete cached resources for a specific site.
  • Force the browser to refresh the site.
  • 3. Check whether the browser caches the resources deleted in (1).

For example, what if we wanted to know if our current visitor to our site was someone from a social networking site (say xxx.com) with the nickname ‘@HelloWorld’?

First of all, we can put the @ the user avatar images of the helloWorld stripped from the social networking site, assuming that the image link long like this: http://xxx.com/user/helloWorld.jpg.

In order to avoid the cache impact of the helloWorld profile picture request caused by the user browsing some pages of social networking sites (such as the post list page), we need to clear the browser cache of the profile picture when the user visits our page. So how can you force clear the cache of an image?

FETCH POST http://xxx.com/user/helloWorld.jpg
Copy the code

Yes, you can clear the browser’s cache of the image by making a POST request (check this out for those of you who are interested).

Next, a request is quietly made using iframe or . Visit the social networking site’s profile page at http://xxx.com/user (this page contains the user’s profile picture).

Then you just need to request again face http://xxx.com/user/helloWorld.jpg, whether it comes from the cache, if it is, that not means just request personal information page contains this picture, you can infer that the user is @ the helloWorld.

So here’s the problem: How do you tell if a request is coming from the cache?

There are many methods. One method is to read the width and height attribute of img to determine whether the image came from the cache:

const img = new Image();
img.onload = () = > {
  // If img does not come from the cache, then the actual witDH value will not be available until onLoad is triggered after the image has been loaded
  console.log(img.width);
}
img.src = 'http://xxx.com/user/helloWorld.jpg';
// This is where the witDH value of the image is read immediately if there is a cache, otherwise 0 is printed
console.log(img.width);
Copy the code

This completes an XS-Leaks attack. We can also request privileged links to determine whether a user has privileged status on a site, and so on. Although the small chestnut seems to harm little, only to achieve the current user and target website account association, but do not underestimate the imagination of hackers, a seemingly insignificant loophole is likely to bring huge losses.

Here is a Github address for xS-Leaks, which records the attack methods, knowledge and practical cases related to XS-Leaks, to help you understand the concepts and attack methods more deeply.

2. Defense mode

With all that said, it’s time to summarize some precautions against XS-Leaks. The XS-Leaks attack also appears to have been launched from third-party sites, using requests to the target sites, similar to the CSRF attack.

Yes, CSRF’s defenses can also make xS-Leaks invalid for authenticated requests, reducing the risk. Of course, sometimes this attack does not require authentication, so CSRF is not a perfect defense, so it is necessary to increase the cache partition at the browser level:

  • Set SameSite Cookie;
  • CSRF Token;
  • Browser support for cache partitioning;

3. Web server cache attack

Xs-leaks exploits a vulnerability in the browser cache, but it’s not just the browser that can cache it. Web servers can also cache it. Server caching is where the requested resource is placed on a dedicated cache server (such as a CDN). When the next user accesses the same resource, the response can be retrieved directly from the cache server, reducing the strain on the Web server.

So if we can somehow put the attack code in a CDN or other cache server, then the user who initiates the same resource request will get the malicious code and be attacked, this does not achieve the XS-Leaks “stored attack”?

The cache server uses the cache-key to determine whether two users are accessing the same resource. This cache-key usually consists of the request method, path, Query, and host headers. Suppose a Web server responds to the following request:

This response adds the x-Forwarded-host value of the request header directly to the content of the Meta tag, which creates the vulnerability of XSS attack. Therefore, we make the following request:

GET /en? dontpoisoneveryone=1 HTTP/1.1
Host: www.redhat.com
X-Forwarded-Host: a."><script>alert(1)</script>
Copy the code

The server returns the following response and caches it to the cache server:

HTTP/1.1 200OK cache-control: public, no-cache... <meta property="og:image" content="https://a."><script>alert(1)</script>"/ >Copy the code

This is because X-forwarded-host is not part of the cache-key. When other users send/EN requests, the server assumes that they are requesting the same resource, applies the cache policy, and sends these malicious requests directly to the user, triggering an attack.

The above example is from the BlackHat2020 issue Web cache poisoning article, which describes the principles and cases of Web server cache attacks in great detail.

Say some what

Although there have been so many measures to cope with and resist various attacks on the Web, there are still one security hole after another was discovered and breached by hackers. Websites as strong as Google and as concise as Google Search were still attacked by XSS in 2019. This attack takes just one line of code:

<noscript><p title="</noscript><img src=x onerror=alert(1)>">
Copy the code

The main reason for this is that Google uses the TEMPLATE tag provided by HTML when escaping the inserted text. Template is a good choice because it can be used to parse HTML without triggering JavaScript execution during parsing. While Template isa javascript-disabled environment, noScript parses differently in a javascript-enabled environment than in a javascript-disabled environment, which leaves the malicious code at risk even after it is parsed and sanitized. Finally, XSS attack is successfully implemented. For those interested, check out this article about this XSS attack.

For example, we often use SVG images. The structure of SVG is very similar to that of HTML. We can insert script or other HTML tags into SVG images using the forginObject tag. If the Web server allows users to upload arbitrary SVG images, then there is a security risk of persistent XSS attacks. HTML escapes sometimes take more than a line or two of code, and when we’re dealing with text editing that requires retaining user-pasted content styles, it’s worth considering how to keep the HTML while avoiding XSS risks.

As we all know, we don’t encounter HTML syntax errors when developing web pages, because the HTML parsing engine is so fault-tolerant that no matter what you write, the browser will parse and render the document for you. However, this fault tolerance and complex parsing logic also allow XSS to constantly find new attacks.

In fact, when I am using a web site online to make two interaction diagrams of the previous chapter, is “accidentally” triggered me the img inside the code, the pop-up dialog box directly, it also illustrates the web security from the side actually in a lot of development team doesn’t get enough attention, but many cases tell us, Our website once suffered the loss may be immeasurable, so we for the Web security, we can not just lip service, talk, or just as an interview of a eight-part essay knowledge point, but should always be vigilant, alarm bell ringing.

Limited by space and energy, this time to share the above three more common Web attack means, I hope to share more knowledge and cases about Web security.

Refer to the article

Front-end Security Series I: How to prevent XSS attacks?

Analyze the six common Web security attacks and defenses

HTTP Cache Cross-Site Leaks

Gaining security and privacy by partitioning the cache

Web cache poisoning