Front-end security (XSS, CSRF)

Front-end security

1. xss attack

What is xss attack:

XSS (cross-site scripting attack) refers to an attacker injecting malicious code into a web page to achieve the purpose of attack.
XSS (cross-site scripting attack) is a common web attack method. Attackers inject malicious scripts into web pages to steal user information, cookies and session IDs, and destroy the foundation of the website. facilities and other purposes.

XSS attacks are generally divided into the following three types:
1. Reflected XSS

A reflected XSS attack occurs when an attacker injects malicious code into a URL, allowing users to click on the link to trigger the attack. After the server receives the URL parameters, it returns them directly to the browser. The browser parses the malicious script in the URL parameters and executes it, thereby achieving the purpose of the attack.

For example, an attacker can construct a malicious link in the following ways:

http://example.com/search?q=<script>alert('XSS')</script>

When the user clicks on the link, a dialog box pops up showing the "XSS" string.

2. Stored XSS

A stored XSS attack occurs when an attacker submits malicious code to the server, and then when other users visit the website, the server reads the malicious code from the database and returns it to the user, triggering the attack.

For example, an attacker can perform a stored XSS attack by submitting a comment or message. The attacker inserts a piece of JavaScript code into the comment box and then submits the comment to the server. When other users visit the page, the server reads the comment from the database and sends it to the browser. The browser parses the JavaScript code in the comment and executes it, thereby achieving the purpose of the attack.

3. DOM type XSS

DOM-type XSS attacks refer to attackers tampering with the page by modifying the DOM (Document Object Model) nodes in the web page to achieve the purpose of the attack. Attackers use the interfaces or vulnerabilities provided by the website to construct specific parameters and inject malicious code. When the front-end JavaScript code parses the parameters, it directly inserts the parameters into the page as HTML, causing the page structure and style to be tampered with by the attacker.

For example, an attacker can implement a DOM-type XSS attack in the following ways:

<!-- 页面中的某个输入框 -->
<input type="text" id="txt">

<!-- 攻击者构造的 URL 参数 -->
http://example.com/search?q=<script>document.getElementById("txt").value="XSS"</script>

When the user enters any text in the input box, clicks on the link and accesses a page with a malicious script, the input box on the page will automatically be filled with the string "XSS".

How to prevent XSS attacks:

1. Filter and escape user input, such as escaping HTML tags.
(1). Filter sensitive characters

can use regular expressions or special library functions to filter out some special characters, such as < and > symbols, single quotes and double quotes, etc. . After filtering out these characters, you can effectively avoid attacks by entering malicious code.

For example, you can filter HTML tags by:

function filterHtmlTag(str) {
    
    
  return str.replace(/<\/?[^>]*>/g, '');
}

The above code filters out all HTML tags through regular expressions and retains the text content.

(2). Escape special characters

can use special library functions to encode HTML, and convert HTML special characters (such as <, >, ' , ", &, etc.) into entity characters. When returned to the user front-end, it is decoded and restored to the original characters. Doing so can effectively prevent malicious code injection attacks.

For example, you can use the he library for HTML encoding and decoding:

const he = require('he');

// 对字符串进行编码
const html = "<script>alert('XSS');</script>";
const encodedHtml = he.encode(html);

// 输出编码后的字符串
console.log(encodedHtml); // 输出:&lt;script&gt;alert(&#x27;XSS&#x27;);&lt;/script&gt;

// 对编码的字符串进行解码
const decodedHtml = he.decode(encodedHtml);

// 输出解码后的字符串
console.log(decodedHtml); // 输出:"<script>alert('XSS');</script>"

The above code uses the he library to encode and decode HTML special characters and successfully prevents XSS attacks.

In summary, XSS attacks can be effectively avoided by filtering sensitive characters and escaping special characters. In actual development, it is recommended to use specialized library functions for character filtering and encoding to improve efficiency and reduce error rates.

2. Use CSP (Content Security Policy) to configure the website securely and restrict the loading and execution of external resources.

Content Security Policy (CSP) is a security protection mechanism built into browsers that helps developers restrict the loading and execution of external resources in web applications. Here are some best practices for using CSP:

(1). Turn on CSP

To enable CSP, add the Content-Security-Policy field to the HTTP response header and specify a policy. For example, the following code restricts the loading of only JavaScript, CSS, and images from the same origin:

Content-Security-Policy: default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self';

In the above example, default-src is the default policy, which will limit the loading of all resources, while script-src, style-src and img-src specify the restrictions on loading JavaScript, CSS and images respectively.

(2). Limit the loading of external resources

CSP allows web applications to be restricted from loading resources from outside. A common approach is to limit resources to the same origin, or a whitelist mechanism that only allows resources from specific sites to be loaded. This can undoubtedly effectively reduce the probability of malicious script injection.

The following is an example CSP configuration that limits resource loading:

Content-Security-Policy: default-src 'self'; script-src 'self' example.com; style-src 'self'; img-src 'self' *.cdn.example.com;

In the above example, 'self' means that resources are only allowed to be loaded from the same origin, example.com means that JavaScript is only allowed to be loaded from example.com, and a>*.cdn.example.com means that images are only allowed to be loaded from any second-level domain name of cdn.example.com.

(3). Prevent XSS attacks on websites

CSP can also be used to prevent cross-site scripting attacks (XSS), typically by disabling inline scripts and unauthorized script execution. You can use the following code to disable inline script execution:

Content-Security-Policy: default-src 'self'; script-src 'self';

In the above example, by removing unsafe-inline, you can disable the execution of all inline scripts and only allow JavaScript to be loaded from the same origin.

(4). Report CSP violations

In addition to restricting the loading and execution of external resources, CSP also supports reporting violations and logging related information. For example, you can use the following configuration to report violations to a specific URL:

Content-Security-Policy: default-src 'self'; report-uri /csp-report

On the server side, these reports can be processed and CSP violations analyzed to further improve the security of your web application.

In summary, by using CSP, you can limit the resource loading and execution of web applications and improve their security. If you want to learn more about CSP, please refer to the CSP official documentation.

3. It is forbidden to use methods such as eval() and new Function() to dynamically execute code. Use safer parsing methods, such as JSON.parse(): because It can only be used to parse JavaScript Object Notation (JSON), not arbitrary JavaScript code. Therefore, if you are sure you want to dynamically get some data from the outside and parse it into a JavaScript object, it is recommended to use JSON.parse(). .

In order to prohibit the use of dynamic code execution methods such as eval() and new Function(), you can use a CSP-like approach and use strict Content-Security-Policy. Limit the execution of JavaScript code. The specific implementation process is as follows:

(1). It is forbidden to use the eval() method

To disable the use of the eval() method, the script-src CSP needs to be restricted to only allow non-inline Script tags and externally imported JavaScript files.

For example:

Content-Security-Policy: default-src 'self'; script-src 'self' https://cdn.example.com/;

In the above configuration, the script-src CSP is restricted to only allow JavaScript to be loaded from the same origin or from external components under the https://cdn.example.com/ domain name.

(2). It is forbidden to use the new Function() method

Disabling the use of the new Function() method is a bit more complicated, as it cannot be achieved by limiting resources, but you can use a code static analysis library, such as Esprima or Acorn, to check and refuse to parse suspicious strings at runtime.

The implementation sample code is as follows:

const esprima = require('esprima');

function safeEval(code) {
    
    
  const ast = esprima.parseScript(code, {
    
     tolerant: true });
  const hasNewFunction = ast.body.some(node => {
    
    
    if (node.type === 'ExpressionStatement' && node.expression.type === 'NewExpression') {
    
    
      const callee = node.expression.callee;
      if (callee.type === 'Identifier' && callee.name === 'Function' && node.expression.arguments.length > 0) {
    
    
        return true;
      }
    }
    return false;
  });
  if (hasNewFunction) {
    
    
    throw new Error("new Function() expressions are not allowed.");
  }
  return eval(code);
}

In the above code, the code to be executed is first syntactically analyzed. If a new Function() is found, an exception will be thrown. Otherwise, the eval() method will be used to execute the code.

Through the above method, you can prohibit the use of dynamic code execution methods such as eval() and new Function() to enhance the security of JavaScript code.

2. CSRF attack

What is a CSRF attack:

CSRF (cross-site request forgery) means that the attacker uses the victim's logged-in status to initiate malicious requests to the server to achieve the purpose of the attack.

The following is an example of a CSRF attack:

Suppose you have logged into a shopping website and have permission to submit orders on the website. The attacker knows you are logged into the website and directs you to a malicious site. This malicious site embeds a constructed image tag, in which the src attribute is set to the order submission interface URL of the shopping website, and is accompanied by malicious parameters created by the attacker. When you browse this page, your browser will automatically load the image and send a request to the interface. At this time, the malicious parameters in the request will be submitted together. Since you have logged in to the shopping website, the request will contain your login credentials, and the server will consider that the request was submitted by you and execute the order.

How to prevent CSRF attacks:

1. Use token or verification code to verify the legitimacy of the request, and add HTTP Headers such as Referer, Origin or X-Requested-With to the request to limit the source of the request.
2. Confirm the key operation twice, such as a pop-up window prompting the user to confirm whether to perform the operation.
3. Set appropriate cookie policies, such as limiting cookie expiration time, scope, etc.

Guess you like

Origin blog.csdn.net/m0_46412825/article/details/130931706