Abstract: This article discusses web front-end security issues and countermeasures, browser homology strategy and several solutions for cross-domain access to resources

This article is shared from the HUAWEI Cloud Community " Web Security and Browser Cross-domain Access ", the original author: kg-follower.

Today, I will talk about web security issues related to the front-end and cross-domain issues that are often encountered in the development process.

1. Web security

1.1 XSS

Fundamental

XSS (Cross-Site Scripting), an attack performed by running illegal HTML tags or JavaScript in the user's browser.

Means of attack

The attacker inserts malicious webpage script code into the web page. When the user browses the page, the script code embedded in the web page will be executed, so as to achieve the purpose of stealing user information or infringing the user's security and privacy.

XSS attack classification

reflective xss attack. sends URLs with malicious scripts to the attacked or inserts untrusted content into the page. When the URL address is opened or the page is executed, the browser parses and executes the malicious script.

The reflective xss attack steps: 1. The attacker constructs a special URL or special data; 2. When the user opens a URL with malicious code, the Web server takes the malicious code out of the URL, splicing it in HTML, and returns it to the browser ; 3. The user browser parses and executes the response after receiving the response, and the malicious code mixed in it is also executed; 4. The malicious code steals user data and sends it to the attacker’s website, or pretends to be the user’s behavior, calling the target website interface to execute the attacker The specified operation.
image.png

Defense: 1. All content or data rendered by the Web page must come from the server; 2. The client escalates the content entered by the user with a security character, and the server escalates the submitted content safely; 3. Avoid splicing html.

storage type xss. malicious script is stored on the target server. When the browser requests data, the script is passed from the server back to the browser for execution.
image.png

The steps of the stored xss attack: 1. The attacker submits the malicious code to the database of the target website; 2. When the user browses to the target website, the front-end page will render and execute the malicious script read out in the database.

Defense: To prevent storage XSS attacks, we need to add string filtering: filtering at the front end; filtering at the server side; filtering at the front end output.

There are usually three ways to defend against XSS attacks: 1. Content Security Policy (CSP). CSP essentially creates a whitelist, and the developer clearly tells the browser which external resources can be loaded and executed. We only need to configure the rules, how to block is implemented by the browser itself. We can minimize XSS attacks in this way. It can usually be turned on in two ways, for example, only allowing resources under the same domain to be loaded:

Set the CSP in HTTP Header (Content-Security-Policy: default-src'self')

How to set the meta tag (<meta http-equiv="Content-Security-Policy" content="form-action'self';">)

2. Escape characters. User input can never be trusted. The most common way is to escape the content of input and output, escaping 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
}

But for displaying rich text, it is obvious that all characters cannot be escaped by the above method, because this will also filter out the required formatting. In this case, the whitelist filtering method is usually adopted:

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

After the whitelist filtering, the <script> tag contained in the dom will not be executed.

HTTP-only Cookie: Forbid JavaScript to read some sensitive cookies, so that only http can access cookies.

1.2 CSRF

basic concepts

CSRF (Cross-site request forgery): The attacker induces the victim to enter a third-party website and sends a cross-site request to the attacked website in the third-party website. Using the registration credentials that the victim has obtained on the attacked website, Bypass the user verification in the background to achieve the purpose of impersonating a user to perform an operation on the attacked website.

Types of CSRF attacks

Active attack. The user visits website A and saves A’s login status (cookies and other information) in the browser. The attacker induces the victim to visit website B. Website B contains malicious code to access the A interface. The victim visits B with A’s login status. The attacker can pretend to be a user to perform malicious operations on A.

Passive attack. The attacker posts a comment or content with a malicious link on website A (submitting an inducing tag with additions, deletions and changes to A). When other victims with login status click on the malicious link of the comment, they will pretend to log in with the victim Credentials launch an attack.

CSRF attack prevention

verifies the HTTP Referer field. has a Referer field in the HTTP header. It records the source address of the HTTP request. If the redirected website matches the source address, it is legal. If it does not match, it may be a csrf attack and reject the request.

SameSite. can set SameSite attribute on Cookie. This attribute indicates that cookies are not sent with cross-domain requests, which can greatly reduce CSRF attacks.

Add the token to the request. server generates a token for the user, which is encrypted and passed to the user. The user needs to carry this token when submitting the request. If the server finds that the token does not exist or the token verification is unsuccessful, it rejects the request.

1.3 Traffic hijacking

DNS hijacking

DNS hijacking is by hijacking the DNS server, obtaining the resolution control of a domain name through some means, and then modifying the resolution result of this domain name, causing the access to the domain name to be transferred from the original IP address to the modified IP. The result is that the specific website cannot be accessed or the fake URL is accessed.

Defense: Use https to verify the identity and data integrity of the communicating parties.

Clickjacking

image.png

The attacker built a very attractive web page, placed the attacked page in the iframe of the current page, used styles to superimpose the iframe on top of the very attractive content, and set the iframe to 100% transparent, in fact, through Attacks caused by covering invisible pages and inducing users to click.

Defense measures. 1. X-FRAME-OPTIONS sets the domain that allows iframe loading. 2. Restricts the execution of JavaScript scripts in iframe pages.

Whether it is xss, csrf, or clickjacking, the types of attacks discussed above are front-end attacks, mostly because the developer's script or template code has hidden dangers of insecurity or does not consider network transmission security issues. Let's briefly talk about attacks initiated by malicious attacks using vulnerabilities in the background of the website.

1.4 SQL injection

SQL injection vulnerabilities exist because of splicing SQL parameters. That is, the query parameters used for input are directly spliced into SQL statements, and malicious attackers can construct special SQL statements to bypass security verification.

SQL injection conditions: 1. The attacker can control the input data; 2. The code to be executed by the server is spliced with the controlled data.

SQL injection defense. 1. Strictly limit the operation authority of the database of the web application; 2. The special characters (', ", <, >, &, *,; etc.) entering the database are escaped or converted, similar to the defense against xss attacks It is recommended to use the parameterized query interface provided by the database for all query statements, such as using placeholder parameters or object-relational mapping ORM.

1.5 DDOS attack

DOS attacks attack all links of the website, making the entire process unable to run, in order to achieve the purpose of paralyzing the service. The most common is to send a large number of requests to cause the server to be overloaded and downtime. The principle of DDOS attack is to use distributed clients to initiate a large number of seemingly legitimate requests to the target, consuming/occupying a large amount of resources, thereby achieving the purpose of denial of service.

Attack methods: 1. Port scan; 2. Ping flood; 3. SYN flood; 4. FTP jump attack;

DDOS prevention. 1. Delete unused services on the server and close unused ports. 2. Perform real-time monitoring and block certain malicious intensive request IP segments; 3. Perform static resource caching to isolate source file access, such as CDN acceleration; 4. Hide the real IP address of the server

3 Cross-domain and same-origin policy

The same-origin policy is an important security policy. It is used to restrict how documents from one source or scripts loaded by it can interact with resources from another source. It can help block malicious documents and reduce possible attack vectors. The so-called homology means that the "protocol + domain name + port" are all the same.

The same-origin policy restricts the following behaviors of the client js code:

1. Cookie, LocalStorage and IndexDB cannot be read;

2. DOM node. The js from one source can only read and write the DOM tree of its own source and cannot read the DOM tree of other sources. If two web pages are of different origin, the other's DOM cannot be obtained. Typical examples are iframe windows and windows opened by the window.open method. They cannot communicate with the parent window.

If the website does not enable the same-origin policy, the phishing website can use the iframe tag to load the Bank of China login interface, execute the script, and get the user name and password.

When the same-origin policy is set, an error will be reported when the parent-child window executes the acquisition of each other's DOM.
image.png

3. AJAX request limit

Cross-domain does not mean that the request cannot be sent, the request can be sent, the server can receive the request and return the result normally, but the result is intercepted by the browser.

In addition to setting up a server proxy, there are several ways to avoid homology restrictions: JSONP, WebSocket, CORS. This article discusses the implementation of the latter two methods in detail.

WebSocket. WebSocket is a communication protocol that uses ws:// (non-encrypted) and wss:// (encrypted) as the protocol prefix. This protocol does not implement the same-origin policy, as long as the server supports it, cross-origin communication can be carried out through it. WebSocket is a two-way communication protocol. After a connection is established, both the WebSocket server and client can actively send or receive data to each other. The Websocket request header information contains an origin field, and the server judges whether to allow this communication according to this field.

CORS. CORS cross-domain resource sharing is a W3C standard, and it is the most common solution to cross-domain Ajax requests. The entire CORS communication process is done automatically by the browser and does not require user involvement. For developers, there is no difference between CORS communication and AJAX communication of the same origin, and the code is exactly the same. Once the browser finds that the AJAX request is cross-origin, it will automatically add some additional header information, and sometimes an additional request will be made, but the user will not feel it.

Browsers divide CORS requests into two categories: simple request and not-so-simple request. As long as the following two conditions are met at the same time, it is a simple request:

(1) The request method is one of the following three methods: HEAD, GET, POST

(2) HTTP header information does not exceed the following fields: Accept, Accept-Language, Content-Language, Last-Event-ID, Content-Type: limited to three values application/x-www-form-urlencoded, multipart /form-data, text/plain

For simple requests, the browser directly issues CORS requests. Specifically, in the header information, an Origin field is added, which is used to indicate which source this request comes from. The server decides whether to approve this request based on this value. If the source specified by Origin is not within the permitted scope, the server will return a normal HTTP response. If the header information of the response does not contain the Access-Control-Allow-Origin field, an error is thrown, which is captured by the onerror callback function of XMLHttpRequest. If the domain name specified by Origin is within the permitted range, the response returned by the server will contain several more header fields. The Access-Control-Allow-Origin field is required. Its value is either the value of the Origin field when the request is made, or a *, which means that the request for any domain name is accepted.

For non-simple requests, before the formal communication, an HTTP query request will be added, called a "preflight" request (preflight). The browser first asks the server whether the domain name of the current webpage is in the server's permission list, and which HTTP methods and header fields can be used. The browser will send a formal XMLHttpRequest request only if it gets an affirmative reply, otherwise it will report an error.

The request method used for the "pre-check" request is OPTIONS, which means that this request is for inquiry. In the header information, the key field is Origin, which indicates which source the request comes from.

In addition to the Origin field, the header information of the "preflight" request includes two special fields.

(1) Access-Control-Request-Method. This field is required to list which HTTP methods will be used in the browser's CORS request

(2) Access-Control-Request-Headers. This field is a comma-separated string that specifies the additional header fields that the browser will send in CORS requests.

The response to the preflight request.

After the server receives the "preflight" request, it checks the Origin, Access-Control-Request-Method, and Access-Control-Request-Headers fields, confirms that cross-origin requests are allowed, and can respond. The most critical response is the Access-Control-Allow-Origin field, which indicates that the request from this source is allowed. If there is no CORS-related header information field, the server denies the request. If the server allows, the Access-Control-Allow-Methods field is required, and its value is a comma-separated string indicating the methods supported by the server. If the preflight request contains the Access-Control-Request-Headers field, this field in the return body is also required. It is also a comma-separated string, indicating all header fields supported by the server, not limited to the browser’s "In the requested field. After the preflight request is allowed to respond, the browser sends a normal CORS request.

Recently, when developing a front-end poc project, I encountered the problem of restricted cross-domain resource access. Starting the angular project locally, other people can access static resources through ip, and they are restricted when sending ajax requests. So I want to solve this cross-domain problem by configuring the proxy: create a proxy.conf.json file in the same level as package.json, the target field is the real ip of the back-end service, the changeOrigin field is set to true, and the secure field is turned off .


{
    "/": {
      "target": "http://10.173.99.224:8081/",
      "changeOrigin": true,
      "secure": false,
      "loglevel": "debug"
    }
}

Add in the startup command of package.json

 "scripts": {
    "ng": "ng",
    "start": "ng serve --proxy-config proxy.conf.json --host 0.0.0.0",
    "build": "ng build",
    "watch": "ng build --watch --configuration development",
    "test": "ng test"
  },

--host 0.0.0.0 means the host that listens to all sources. solve

Click to follow, and get to know the fresh technology of Huawei Cloud for the first time~


华为云开发者联盟
1.4k 声望1.8k 粉丝

生于云,长于云,让开发者成为决定性力量