Safety precautions

wang xiao bo 's photo
wang xiao bo
·Feb 11, 2022·

7 min read

Subscribe to my newsletter and never miss my upcoming articles


Involving interview questions: What is an XSS attack? How to prevent XSS attacks? What is CSP?

To put it simply, XSS means that attackers do everything possible to inject executable code into web pages.

There are many types of XSS, but in general I think they fall into two categories: persistent and non-persistent.

Persistence means that the code of the attack is written into the database by the server. This attack is very harmful, because if the website has a large number of visits, it will cause a large number of users who normally visit the page to be attacked.

For example, for the comment function, it is necessary to protect against persistent XSS attacks, because I can enter the following in the comment

In this case, if the front and back ends are not well defended, this comment will be stored in the database, so that every user who opens the page will be attacked.

Compared with the former, the non-persistent type is much less harmful. Generally, the attack code is added by modifying the URL parameters to induce the user to visit the link to carry out the attack.

For example, if the page needs to get certain parameters from the URL as content, the attack code will be executed without filtering

<!--<script>alert(1)</script> -->

But for this attack method, if the user uses a browser such as Chrome, the browser can automatically help the user defend against the attack. But we can't prevent such attacks because I can't be sure that users are using such browsers.

There are usually two ways to defend against XSS attacks.

First, user input should never be trusted. The most common practice is to escape the content of input and output, and escape quotation marks, angle brackets, and slashes

function escape(str) {
  str = str.replace(/&/g, '&amp;')
  str = str.replace(/</g, '&lt;')
  str = str.replace(/>/g, '&gt;')
  str = str.replace(/"/g, '&quto;')
  str = str.replace(/'/g, '&#39;')
  str = str.replace(/`/g, '&#96;')
  str = str.replace(/\//g, '&#x2F;')
  return str

By escaping the attack code can become

// -> &lt;script&gt;alert(1)&lt;&#x2F;script&gt;

But for displaying rich text, obviously all characters cannot be escaped by the above method, because this will also filter out the required format. In this case, the whitelist filtering method is usually adopted, and of course, the blacklist filtering method can also be used, but considering that there are too many tags and tag attributes to be filtered, the whitelist method is more recommended.

const xss = require('xss')
let html = xss('<h1 id="title">XSS Demo</h1><script>alert("xss");</script>')
// -> <h1>XSS Demo</h1>&lt;script&gt;alert("xss");&lt;/script&gt;

The above example uses js-xss to implement, you can see that the h1 tag is preserved in the output and the script tag is filtered.


CSP essentially establishes a whitelist, and the developer explicitly tells the browser which external resources can be loaded and executed. We only need to configure the rules, how to intercept is implemented by the browser itself. We can minimize XSS attacks in this way.

There are usually two ways to enable CSP:

1.Set Content-Security-Policy in HTTP Header 2.How to set meta tags

Here is an example of setting HTTP Header

  • Only allow loading of resources from this site
  • Content-Security-Policy: default-src ‘self’
  • Only allow HTTPS protocol images to be loaded
  • Content-Security-Policy: img-src https://*
  • Allow any source frame to be loaded
  • Content-Security-Policy: child-src 'none'

Of course, the properties that can be set are far more than these. You can learn by consulting the documentation. I won't go into details about other properties here.

In this way, as long as the developer configures the correct rules, even if the website has vulnerabilities, the attacker cannot execute its attack code, and the compatibility of CSP is also good.


Involving interview questions: What is a CSRF attack? How to prevent CSRF attacks?

CSRF Chinese name is Cross-Site Request Forgery. The principle is that the attacker constructs a backend request address to induce the user to click or automatically initiate a request through some means. If the user is in the logged-in state, the backend assumes that the user is operating and performs corresponding logic.

For example, suppose there is an interface for submitting user comments through GET requests, then an attacker can add a picture to the phishing website, and the address of the picture is the comment interface.

<img src="'attack'"/>

So do you think that using POST to submit requests does not have this problem? In fact, it is not, and it is not 100% safe to use this method. An attacker can also induce users to enter a certain page and submit a POST request through a form on the page.

The following rules can be followed to prevent CSRF attacks:

1.Get requests do not modify the data

2.Prevent third-party sites from accessing user cookies

3.Block third-party website request interface

4.The request is accompanied by verification information, such as verification code or Token SameSiteSameSite

The SameSite attribute can be set on cookies. This attribute indicates that cookies are not sent with cross-domain requests, which can greatly reduce CSRF attacks, but this attribute is currently not compatible with all browsers.

For requests that need to prevent CSRF, we can verify whether the request is initiated by a third-party website by verifying the Referer. TokenToken

The server issues a random Token, which is carried every time a request is initiated, and the server verifies whether the Token is valid.

Involving interview questions: What is clickjacking? How to prevent clickjacking?

Clickjacking is a visual deception attack. The attacker embeds the website to be attacked into his own web page by nesting iframes, and sets the iframe to be transparent, revealing a button on the page to induce users to click.

There are two recommended defense methods for this attack method. X-FRAME-OPTIONSX-FRAME-OPTIONS

X-FRAME-OPTIONS is an HTTP response header that has good support in modern browsers. This HTTP response header is for defense against clickjacking attacks nested with iframes.

The response header has three optional values, which are

-DENY means that the page is not allowed to be displayed through iframe

-SAMEORIGIN, indicating that the page can be displayed in an iframe under the same domain name

-ALLOW-FROM, indicating that the page can be displayed in an iframe of the specified origin

For some ancient browsers, the above method cannot be supported, so we can only defend against click hijacking through JS.

  <style id="click-jack">
    html {
      display: none !important;
    if (self == top) {
      var style = document.getElementById('click-jack')
    } else {
      top.location = self.location

The function of the above code is that when the page is loaded by iframe, the attacker's web page does not display all the content directly. 中间人攻击man-in-the-middle attack

Involving interview questions: What is a man-in-the-middle attack? How to prevent man-in-the-middle attacks?

A man-in-the-middle attack is that the attacker establishes a connection with the server and the client at the same time, and makes the other party think that the connection is secure, but in fact the entire communication process is controlled by the attacker. The attacker can not only obtain the communication information of both parties, but also modify the communication information.

Generally speaking, using public Wi-Fi is not recommended because of the possibility of man-in-the-middle attacks. If you involve some sensitive information in the process of communication, it is completely exposed to the attacker.

Of course, defending against man-in-the-middle attacks is not difficult, just add a secure channel to transmit information. HTTPS can be used to defend against man-in-the-middle attacks, but it doesn't mean that using HTTPS can be a peace of mind, because if you don't completely shut down HTTP access, attackers can downgrade HTTPS to HTTP in some way to achieve man-in-the-middle attacks.

In this chapter, we learned some common front-end security aspects and how to defend against these attacks. However, the field of security is quite large, and these contents are only a drop in the ocean. If you are interested in security, you can read the contents of this repository to learn and practice this knowledge.

Share this


JavaScript Ruby on Rails