Front-end network security to prevent attacks

1. XSS

Cross-site scripting (English: Cross-site scripting, usually abbreviated as: XSS) is a security vulnerability attack of a website application, which is a type of code injection . It allows malicious users to inject code into web pages, which can affect other users viewing the web pages. Such attacks typically involve HTML as well as client-side scripting languages. Short name: cross-site scripting attack

XSS is divided into three types: reflection type, storage type and DOM-based

how to attack

XSS attacks websites by modifying HTML nodes or executing JS code.

For example, get some parameters through the URL


<!-- Website Domain Names, Online Stores & Hosting - Domain.com<script>alert(1)</script> -->

<div>{
   
   {name}}</div>

The above URL input may change the HTML <div><script>alert(1)</script></div>, so that there is an executable script in the page out of thin air. This type of attack is a reflection attack, or DOM-based attack.

There is also another scenario, such as writing an article <script>alert(1)</script>containing , then users who may browse the article will be attacked. This type of attack is a storage attack, or a DOM-based attack, and this attack has a wider range of attacks. how to defend

The most common way 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 be <script>alert(1)</script>turned into

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

escape('<script>alert(1)</script>')

For displaying rich text, you cannot escape all characters by the above method, because this will filter out the required format. In this case, whitelist filtering is usually used. Of course, blacklist filtering can also be used. However, considering that there are too many tags and tag attributes that need to be filtered, it is more recommended to use the whitelist method.

var xss = require('xss')

var html = xss('<h1 id="title">XSS Demo</h1><script>alert("xss");</script>')

// -> <h1>XSS Demo</h1>&lt;script&gt;alert("xss");&lt;/script&gt;

console.log(html)

The above example uses js-xssto achieve. You can see that the tags are preserved and the tags are filtered h1in the outputscript

Vue prevents Xss attacks

1. Use the vue-xss component  

2. Use Xss components, install xss components, add xss verification, global v-html for xss filtering

a. Configuration file

Create a new xss.js file, filter out styles and events

const xss = require('xss')

const options = {
  css: false,
  onTag(tag, html, options) {
    if (tag === 'iframe') {
      return html.replace(/javascript:?/, '')
    }
  },
  // 避免把页面样式过滤掉
  onIgnoreTagAttr(tag, name, value, isWhiteAttr) {
    // 过滤掉标签上的事件
    if (/^[^on]/.test(name)) {
      return name + '="' + xss.escapeAttrValue(value) + '"'
    }
  },
}
const filter = new xss.FilterXSS(options)

export default filter

b. Mount global

main.js

//main.js

import xss from '@/utils/xss'

Vue.prototype.$xss = xss // 挂在全局是为了在 loader中能够通过该方法去过滤全局的 v-html 返回数据

c. Modular preprocessing, configure global instructions

 Add xss configuration to v-html directive in vue.config.js

// vue.config.js

 // global xss rules
    config.module
      .rule('vue')
      .use('vue-loader')
      .loader('vue-loader')
      .tap((options) => {
        options.compilerOptions.directives = {
          html(node, directiveMeta) {
            const props = node.props || (node.props = [])
            props.push({
              name: 'innerHTML',
              value: `$xss.process(_s(${directiveMeta.value}))`,
            })
          },
        }
        return options
      })

2. CSRF

Cross-site request forgery (English: Cross-site request forgery), also known as one-click attack or session riding, usually abbreviated as CSRF or XSRF, is a method that coerces users to execute unintentional The attack method of the operation . [1] In contrast to cross-site scripting (XSS), which exploits the user's trust in a given website, CSRF exploits the website's trust in the user's web browser.

Or to analyze literally, cross-site still refers to pointing from one website to another website. Unlike XSS, it is a request, which means that we send a request on another website, and this request is forged

The user has logged in to site A, and a cookie is recorded locally

When the user does not log out of site A (that is, when the cookie is valid), he visits the lure and dangerous site B provided by the malicious attacker (site B requires access to site A).

Site A does not do any CSRF defense

The attacker induces the victim to enter a third-party website, and in the third-party website, sends a cross-site request to the attacked website. Use the registration credentials that the victim has obtained on the attacked website to bypass the user verification in the background, and achieve the purpose of impersonating the user to perform an operation on the attacked website.

how to defend

To prevent CSRF, you can follow the following rules:

  1. Get requests do not modify data
  2. Do not allow third-party websites to access user cookies
  3. Prevent third-party websites from requesting interfaces
  4. Verification information is attached to the request, such as verification code or token

a.SameSite

SameSiteAttributes can be set on cookies . This property sets the cookie not to be sent with cross-domain requests, which can greatly reduce CSRF attacks, but this property is not currently compatible with all browsers.

b. Verify Referer

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

c.Token (commonly used)

The server issues a random Token (algorithm should not be complicated), carries the Token with each request, and the server verifies whether the Token is valid.

Guess you like

Origin blog.csdn.net/qq_25687271/article/details/125484794