Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

This article also participated in the “Digitalstar Project” to win a creative gift package and creative incentive money

preface

In fact, the front end rarely takes full precautions against network security in the process of development projects, and the project planning will not be listed in the development plan. As a result, front-end developers are increasingly weak on this knowledge. In fact, this is often asked in the interview, so I suggest you learn more, maybe one day you can use it

1. XSS

What is an XSS attack? How do I prevent XSS attacks

1.1 Basic analysis

Cross-site Scripting (XSS) is a code injection attack. The attacker injects malicious scripts on the target website to run on the user’s browser. Using these malicious scripts, attackers can obtain sensitive user information such as cookies and sessionIDS, thus compromising data security.

The hazards of XSS attacks include:

1. Steal all kinds of user accounts, such as machine login accounts, user online banking accounts, and all kinds of administrator accounts

2. Control enterprise data, including the ability to read, tamper with, add and delete sensitive enterprise data

3. Stealing important data of commercial value from enterprises

4. Illegal money transfers

5. Force email

6, the website hanging horse

7. Control the victim’s machine to launch attacks on other websites

1.2 Cause Analysis

Main reason: too much trust in the data submitted by the client!

Solution: Do not trust the data submitted by the client. Filter the data submitted by the client before proceeding to the next step.

Further analysis:

The data submitted by the client itself is required by the application, but the disgusting attacker takes advantage of the website’s trust in the data submitted by the client, inserts some symbols and JavaScript code into the data, and then these data will become a part of the application code, so the attacker can carry out unscrupulous attacks

Therefore, we must not trust any data submitted by the client

According to the attack sources, XSS attacks can be classified into storage, reflection and DOM attacks

1.3 type

1.3.1 Storage (Persistence)

Persistent attack code is written into the database, this attack is very harmful, if the site is very large, it will lead to a large number of normal access to the page, will lead to a large number of normal access to the page users are attacked.

Common scenarios and cases:

Case: Microblog forums and other places where users post, submit articles and comments

  1. Commit malicious code to the database

  2. The database stores it

  3. Other users view posts or comments

  4. The server returns malicious code that is spliced into the client page

  5. Malicious codes may pop up advertisements or obtain users’ personal privacy such as cookies and report them to the attacker database through self-execution or user click execution

1.3.2 Non-persistent (Reflective)

Non-persistent XSS means that when a request is sent, the XSS code appears in the URL of the request and is submitted as a parameter to the server, which parses and responds. The response result contains XSS code, which is finally parsed and executed by the browser. Conceptually, reflective XSS code first appears in the URL, then needs to be parsed by the server, and finally needs to be attacked by XSS code behind the browser

Common scenarios and cases:

Case in point: button emails with leading links, etc.

1. The attacker adds malicious code into the parameters of some links and induces users to click

2. The user clicks to pass the request parameters to the server

3. The server obtains parameters and returns them to the client

4. The client executes malicious codes to impersonate users for permission operation or steal users’ personal privacy such as cookies and report to the attacker database

1.3.3 DOM Attacks

DOM and reflex are both performed by inducing the user to click on a link and are temporary, but reflex is a server-side security vulnerability and DOM is a client-side security vulnerability

Common scenarios and cases:

1. The attacker constructs a special URL that contains malicious code.

2. The user opens the URL with malicious code.

3. The user browser parses the response and executes it. The front-end JavaScript takes out the malicious code in the URL and executes it.

4. Malicious code steals user data and sends it to the attacker’s website, or impersonates the user and calls the target website interface to perform the operations specified by the attacker.

1.4 Defense Methods

#### is usually defended in two ways

1.4.1 Escape Characters

First, user input should never be trusted. The most common approach is to escape input and output, such as parentheses, Angle brackets, and slashes

First, user input should never be trusted. The most common approach is to escape input and output, such as parentheses, Angle brackets, and slashes

function escape(str) {
  str = str.replace(/&/g.'& ')
  str = str.replace(/</g.'< ')
  str = str.replace(/>/g.'> ')
  str = str.replace(/"/g.'&quto; ')
  str = str.replace(/'/g.'& # 39; ')
  str = str.replace(/`/g.'the & # 96; ')
  str = str.replace(/\//g.'/ ')
  return str
}
Copy the code

The attack code can be changed by escaping

// -> < script> alert(1)< / script>
escape('<script>alert(1)</script>')
Copy the code

But for displaying rich text, you obviously can’t escape all characters in this way, because that would filter out the required format as well. In this case, whitelist filtering is usually used. You can also filter through the blacklist. However, considering that there are too many tags and tag attributes to be filtered, whitelist filtering is recommended.

const xss = require('xss')
let html = xss('

XSS Demo

'
) // ->

XSS Demo

< script> alert("xss"); < /script>
console.log(html) Copy the code
1.4.2 CSP

Content Security Policies (CSP) are an additional layer of security designed to detect and weaken certain types of attacks, including cross-site scripting (XSS) and data injection attacks. Whether it is data theft, website content contamination or the distribution of malicious software, these attacks are the main means

The primary goal of the CSP is to reduce and report XSS attacks that exploit the browser’s trust in content retrieved from the server. Malicious scripts run in the victim’s browser because the browser trusts the source of the content, even if the script doesn’t come from where it’s supposed to.

By specifying valid domains — that is, valid sources of browser-approved executable scripts — the CSP gives server administrators the ability to reduce or eliminate vectors on which XSS attacks depend. A CSP-compatible browser will execute only the script files retrieved from the whitelist field, ignoring all other scripts (including inline scripts and HTML event handling attributes).

As a form of ultimate protection, sites that do not always allow scripting can choose to disable scripting altogether

A CSP is essentially a whitelist, where the developer explicitly tells the browser what external resources can be loaded and executed. We just need to configure the rules, and how to block them is up to the browser. You can use the Content-security-policy HTTP header to specify your Policy, like this:

Set content-security-policy: Policy in the HTTP Header

2 Set the meta tag

Meta HTTP – equiv = “Content ws-security – Policy” Content = “default – SRC ‘self’; img-src https://*; The child – SRC “none”;” >

Common use cases (setting HTTP headers as an example)

  • A site administrator who wants all content to come from the same source (excluding subdomains) is only allowed to load resources from the site

The Content ws-security – Policy: the default – SRC ‘self’

  • A site manager allows content from trusted domain names and their subdomains (domain names do not have to be the same as the domain where the CSP is set up)

The Content ws-security – Policy: the default – the SRC ‘self’ *. Trusted.com

  • A web administrator allows web application users to include images from any source in their own content, but limits audio or video to be sourced from a trusted source provider, and all scripts must fetch trusted code from a specific host server.

The Content ws-security – Policy: the default – SRC ‘self’; img-src *; media-src media1.com media2.com; script-src userscripts.example.com

  • Only HTTPS images can be loaded

Content-Security-Policy: img-src https://*

  • Allows loading of any source framework

The Content ws-security – Policy: child – SRC ‘none’

In this case, the developer has to configure the right rules so that even if the site is vulnerable, the attacker cannot execute its attack code, and CSP compatibility is good.

2. CSRF

Interview question: What is a CSRF attack? How do I defend against CSRF attacks

2.1 Basic analysis

Cross-site Request Forgery (CSRF) : An attacker induces the victim to access a third-party website and sends cross-site request to the attacked website. Using the victim in the attacked website has obtained the registration certificate, bypassing the background user authentication, to impersonate the user to perform a certain operation on the attacked website.

2.2 the principle

The principle is that the attacker constructs a back-end request address to induce users to click or automatically initiate a request through some means. If the user is logged in, the backend assumes that the user is operating and performs the corresponding logic

To complete a CSRF attack, the victim must complete two steps in sequence:

  1. Log in to trusted web sites and generate cookies locally
  2. Visit dangerous sites without logging out of trusted sites

You may be wondering: if I don’t meet either of these two criteria, I won’t receive a CSRF attack.

That’s true, but you can’t guarantee that:

  1. You can’t guarantee that once you log in to a site, you won’t open a TAB page and visit another one
  2. There is no guarantee that your local Cookie will expire immediately after you close the browser and your last session will have ended.

2.3 Hazards (What CSRF can do)

Attackers steal your identity, send malicious requests in your name,CSRF can do: send emails in your name, steal your account and even purchase goods, virtual currency transfer, personal privacy disclosure and property security

2.4 type

2.4.1 Active Attack
  1. The victim visits a.com and leaves the login status of a.com on his browser

  2. The attacker directed the victim to visit the tripartite website b.com

  3. The third party website b.com has malicious code (delete/add/modify, etc.) that accesses the interface of a.com.

  4. When the victim clicks on B.com, B.com carries out malicious operations on A.com by pretending to be the victim user with the login credentials of a.com

2.4.2 Passive Attack
  1. Attackers post posts or comments on the website with malicious links (submit an induced IMG /form/ A tag with changes and additions to the website)

  2. When other victims with login status click on the malicious link of the comment to launch an attack using the victim login credentials

CSRF mainly uses the victim’s login credentials to initiate malicious additions, deleters and changes without stealing the victim’s private information

2.5 How do I Prevent CSRF Attacks

  1. Disable third-party sites from obtaining cookies, for example by setting Chrome’s SameSite property

Cons: SameSite isn’t very compatible during the trial phase

  1. The server uses the Referer Header and Origin Header for source authentication

Drawback 1: Attackers can partially modify or hide referer

Downside 2: Some browsers or operations may lose the Origin header, such as the 302 redirect

Drawback 3: When HTTPS pages jump to HTTP pages, all browser referers are lost.

Drawback 4: Can’t recognize passive attack

Others: Some older browsers are not very stable with Origin and Referer, with all sorts of unexpected results that are extremely unstable

  1. Using token to authenticate, the three-party cross-site request cannot obtain the token in the header. The interface of this site will add token in the request header before the request for identity authentication, and the three-party request will not carry token

Disadvantage 1: Token authentication puts a lot of pressure on the server. Therefore, a dedicated server can be used for token authentication, which costs the server and increases the request time

Drawback 2: For page Ajax, FETCH and other asynchronous requests, such as form submission and A link, token needs to be added one by one, so unified entry for token addition cannot be formed, and some omissions exist

Relatively speaking, token authentication is a better defense measure

  1. The use of double cookie authentication, in each request parameters are additional scrfCookie=’ random number ‘defense parameter, and in the cookie mixed with the defense parameter value, the server will request header cookie defense parameter and request parameters with the parameter comparison

Disadvantages: For example, the front-end www.xx.com, the back-end interface is api.xx.com. To get the cookies under the back-end interface domain, the front-end must put the cookies under xx.com to ensure that all subdomains can get them. This increases the risk of XSS attacks more than it costs

3. The DOS attack

3.1 Basic analysis

DOS attacks disable the entire process of a website by attacking every link of the website and paralyze the service. The most common is when the server is overloaded with requests and goes down

3.2 Preventive Measures

  • Expand servers [rich companies play]
  • Implement real-time monitoring and block some malicious intensive REQUEST IP segments
  • Added interface authentication to limit the number of accesses from a single IP address for certain sensitive interfaces
  • Static resource caching, isolated access to source files, such as CDN acceleration

4. Page hijacking

4.1 Basic analysis

The attacker modifs the data through the requested data transfer process, or performs a generic domain name resolution to redirect the site, and injects advertisements into the site

4.2 type

  1. Jump transformation hijacking, through the pan-domain name resolution and other pages will be visited by users to other websites, in order to carry out malicious competition, or hit some phishing websites for personal interests of users and the interests of other websites reputation infringement

  2. Injection-type hijacking, intercepting and modifying the requested resources of the website, adding malicious code or advertising

4.3 How Can I Prevent Network Hijacking

  • The most effective and violent option is to switch to HTTPS and establish a secure channel
  • Monitor vulnerabilities and make adjustments according to the actual situation

5. To summarize

Clickjacking is an attack that many people don’t pay much attention to. It requires the user to interact with the page, which is more expensive to carry out. Alternatively, the developer may feel that the user is stupid and does not take this attack seriously.

Brief Introduction: Man-in-the-middle attacks

What is a man-in-the-middle attack? How do I protect against man-in-the-middle attacks

Man-in-the-middle attack (MITM attack for short) is a kind of “indirect” invasion attack. This attack mode uses various technical means to place a computer controlled by the intruder virtually between two communicating computers in the network connection. This computer is called “the Man in the middle”.

In a man-in-the-middle attack, an attacker establishes a connection with both the server and the client and makes the other party think the connection is secure, but in fact the whole communication process is controlled by the attacker. Attackers can not only gain access to communications between the two sides, but also modify them.

It is generally not recommended to use public Wi-Fi because of the likelihood of a man-in-the-middle attack. If you are communicating with sensitive information, you are completely exposed to the attacker.

Of course, it is not difficult to defend against man-in-the-middle attacks, just need to add a secure channel to transmit information. HTTPS can be used to defend against man-in-the-middle attacks, but using HTTPS is not a safe bet, because if you do not completely turn off HTTP access, there are ways in which an attacker can degrade HTTPS to HTTP to implement man-in-the-middle attacks.