[Interview] Web Security You Must Know in Winter Job Hunting

  Front end, javascript, node.js, Programmer, Web security

With the development of the Internet, various Web applications have become more and more complex, meeting various needs of users. At the same time, various network security problems have followed. As front-end engineers, we can’t escape from this problem either. Today, let’s take a look at what security problems exist in the Web front-end and how we can detect and prevent these problems. Non-front-end attacks will not be discussed in this article (such as SQL injection, DDOS attacks, etc.), after all, the back-end is not my area of expertise.

Famous websites such as QQ mailbox, Sina Weibo, YouTube, WordPress and Baidu have all been attacked. If you have never had security problems, it is not because the website you developed is very safe, but more likely that the traffic flow of your website is very low or there is no value to attack.

This article mainly discusses the following attack methods: XSS attack, CSRF attack, clickjacking and URL jump vulnerability.

<font style=”color: #ff302c”>I hope you can answer the following questions after reading this article.</font>

1. What are the front-end attacks?

2. What is XSS attack? How many types of XSS attacks are there? What if XSS attacks are prevented?

3. What is CSRF attack? How to Prevent CSRF Attacks

4. How to check whether the website is safe?

Before starting, I suggest you clone the code first. I have prepared the sample code for you, and have written detailed comments. you can understand each attack and how to prevent it against the code. after all, no matter how many words you read, you will not be honest. (The operation steps are detailed in Readme):https://github.com/YvetteLau/ …

More quality articles to stamp on: https://github.com/YvetteLau/ …

1. XSS attack

XSS(Cross-Site Scripting) is a code injection attack. The attacker injects malicious code into the target website, and the malicious code will be executed when the attacker logs on the website. These scripts can read cookie, session tokens, or other sensitive website information, carry out phishing fraud on users, and even launch worm attacks.

The essence of XSS is that malicious code is not filtered and mixed with normal code of websites. The browser cannot distinguish which scripts are trusted, resulting in malicious scripts being executed. Because it is executed directly at the user’s terminal, malicious code can directly obtain the user’s information and use this information to impersonate the user to initiate an attacker-defined request to the website.

XSS classification

According to the source of the attack, XSS attacks can be divided into three types: storage type (persistent), reflection type (non-persistent) and DOM type. Let’s take a closer look at these three XSS attacks:

1.1 reflective XSS

When a user clicks on a malicious link, submits a form, or enters a malicious website, the injection script enters the attacked website. The Web server will inject scripts, such as an error message, search results, etc., and return them directly to the user’s browser without filtering.

Attack Steps of Reflective XSS:

  1. The attacker constructed a specialURLWhich contains malicious code.
  2. The user opens the with malicious codeURLWhen, the website server will malicious code fromURLTake it out and splice it in HTML and return it to the browser.
  3. After receiving the response, the user browser parses and executes, and malicious code mixed in it is also executed.
  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 operation specified by the attacker.

Reflective XSS vulnerabilities are common throughURLFunctions of passing parameters, such as website search, jump, etc. Due to the need for users to actively open maliciousURLIn order to be effective, attackers often combine various means to induce users to click.

The content of POST can also trigger reflective XSS, but its triggering conditions are rather harsh (form submission pages need to be constructed and users need to be guided to click), so it is very rare.

See examples of reflective attacks

Please stamp:https://github.com/YvetteLau/ …

According toREADME.mdThe above code is for demonstration only.

pay attention toChromeAndSafariAble to detecturlXss attack on, blocking the web page, but other browsers can’t, such asFirefox

If you don’t want the front end to get the cookie, the back end can set ithttpOnly(but this is notcross site scriptingThe solution, can only reduce the scope of damage)

How to Prevent Reflective XSS Attacks

Encodes strings.

Escape the query parameters of the url before outputting to the page.

app.get('/welcome', function(req, res) {
    //对查询参数进行编码,避免反射型 XSS攻击


DOM-type XSS attack is actually the front endJavaScriptThe code is not rigorous enough to insert untrusted content into the page. In use.innerHTML.outerHTML.appendChilddocument.write()When waiting for API, be careful not to insert untrusted data as HTML on the page and use it as much as possible..innerText.textContent.setAttribute()Wait.

Dom-type XSS attack steps:

  1. Attackers construct special data containing malicious code.
  2. The user browser executed malicious code.
  3. 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 operation specified by the attacker.

How to prevent DOM-type XSS attacks

The core of preventing DOM-type XSS attacks is to escape the input content (both inline event listeners and link jumps in DOM can run strings as code, and their contents need to be checked).

1. RegardingurlLinks (e.g. of picturessrcProperty), then use it directlyencodeURIComponentTo escape.

2. Nourl, we can code like this:

function encodeHtml(str) {
    return str.replace(/"/g, '&quot;')
            .replace(/'/g, '&apos;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;');

In DOM-type XSS attacks, the removal and execution of malicious code is completed by the browser, which is a security vulnerability of the front-end JavaScript itself.

View DOM-type XSS attack examples (follow readme prompts)

Please stamp:https://github.com/YvetteLau/ …

1.3 Storage XSS

Malicious scripts are permanently stored on the target server. When the browser requests data, the script is returned from the server and executed, with a larger scope of influence than reflection and DOM XSS. The reason for the storage XSS attack is still that the data is not filtered properly: when the front end submits the data to the server end, the data is not filtered properly; When the server receives the data, it does not filter it before storing it. The front end requests data from the server without filtering the output.

Attack Steps for Storage XSS:

  1. The attacker submitted malicious code to the database of the target website.
  2. When the user opens the target website, the website server takes out the malicious code from the database, splices it in HTML and returns it to the browser.
  3. After receiving the response, the user browser parses and executes, and malicious code mixed in it is also executed.
  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 operation specified by the attacker.

This kind of attack is common in websites with users’ data storage functions, such as forum posting, merchandise comment, and users’ private letters.

How to Prevent Storage XSS Attacks:

  1. Escape/filter the front-end data before passing it to the server (it cannot prevent the data from being modified by grabbing packets)
  2. The server receives the data and escapes/filters it before storing it in the database.
  3. The front end receives the data transmitted by the server and escapes/filters it before displaying it on the page.

View an example of a storage XSS attack (follow Readme prompts)

Please stamp:https://github.com/YvetteLau/ …

In addition to careful escape, we also need other means to prevent XSS attacks:

1.Content Security Policy

In the server using HTTPContent-Security-PolicyHead to specify the policy, or set at the front endmetaLabel.

For example, the following configuration only allows loading resources under the same domain:

Content-Security-Policy: default-src 'self'
<meta http-equiv="Content-Security-Policy" content="form-action 'self';">

The effect of setting CSP at the front end and the service end is the same, butmetaNot availablereport

More settings can be viewed in [Content-Security-Policy]
](https://developer.mozilla.org …

Strict CSP can play the following roles in XSS prevention:

  1. It is forbidden to load foreign code to prevent complex attack logic.
  2. Foreign domain submission is prohibited. After the website is attacked, the user’s data will not be leaked to foreign domain.
  3. Execution of inline scripts is prohibited (the rules are stricter and GitHub is currently found to be used).
  4. Prohibit unauthorized script execution (new feature, Google Map mobile version in use).
  5. Reasonable use and reporting can discover XSS in time and help to repair the problem as soon as possible.

2. Input content length control

For untrusted input, a reasonable length should be defined. Although XSS cannot be completely prevented, it can increase the difficulty of XSS attacks.

3. Input content restrictions

For partial input, it can be limited not to contain special characters or only to enter numbers, etc.

4. Other security measures

  • HTTP-only Cookie: JavaScript is prohibited from reading some sensitive Cookies, and the attacker cannot steal this Cookie after completing XSS injection.
  • Verification Code: Prevent scripts from posing as users to submit dangerous operations.

1.5 XSS detection

By reading this, I believe you already know what XSS attacks are, the types of XSS attacks, and how to prevent XSS attacks. However, there is a very important question: how do we detect XSS attacks and how do we know if there are XSS vulnerabilities in our pages?

Many large companies have special security departments responsible for this work, but if there is no security department, as developers themselves, how to detect it?

1. Use the generic XSS attack string to manually detect XSS vulnerabilities

For example:jaVasCript:/*-/*`/*\`/*'/*"/**/(/* */oNcliCk=alert() )//%0D%0A%0d%0a//</stYle/</titLe/</teXtarEa/</scRipt/--! >\x3csVg/<sVg/oNloAd=alert()//>\x3e

It can detect XSS vulnerabilities in various contexts such as HTML attributes, HTML text content, HTML comments, jump links, inline JavaScript strings, inline CSS style sheets, etc. It can also detect DOM-type XSS vulnerabilities such as eval (), setTimeout (), setInterval (), Function (), innerHTML, document.write (), etc. and can bypass some XSS filters.

<img src=1 onerror=alert(1)>

2. Scan with third-party tools (see the last section for details)



CSRF(Cross-site request forgery) Cross-Site Request Forgery: An attacker induces a victim to enter a third-party website, where he sends a cross-site request to the attacked website. By using the registration certificate obtained by the victim on the attacked website, the user authentication in the background is bypassed, so as to achieve the purpose of posing as a user to perform certain operation on the attacked website.

Typical CSRF Attack Process:

  1. The victim logged into site a and kept a login certificate (Cookie).
  2. The attacker induced the victim to visit site b.
  3. Site B sends a request to Site A, and the browser will carry Cookie information of Site A by default.
  4. After receiving the request, site a verifies the request and confirms it is the victim’s certificate, mistaking it for a request sent by an innocent victim.
  5. Site A executed Site B’s request on behalf of the victim.
  6. When the attack was completed, the attacker impersonated the victim and completed the attack without the victim’s knowledge.

A picture is worth a thousand words.

Features of CSRF

1. Attacks are usually launched on third-party websites, such as Site B on the figure. Site A cannot prevent attacks.

2. The attack used the victim’s login credentials on the attacked website to impersonate the victim and submit the operation; It does not obtain cookie information (cookies have homologous policies)

3. Cross-site requests can be made in various ways: picture URL, hyperlink, CORS, Form submission, etc. (Do not click on links of unknown origin)

Run the code for a more intuitive understanding

Loki bank deposit 10W.

Yvette bank deposit 1000.

Let’s see how yvette passedCSRFAttack, secretly transfer loki’s money to his account, and according to the tips, see how to defend against CSRF attacks.

Please stamp:https://github.com/YvetteLau/ …[operate according to CSRF section in readme]

CSRF attack defense

1. Add verification code (bad experience)

CAPTCHA can defend against CSRF attacks, but we can’t need CAPTCHA for every interaction, otherwise the user’s experience will be very poor, but we can add CAPTCHA to ensure the security of our account during transfer, transaction and other operations.

2. Determine the source of the request: detect Referer (it is not safe, Referer can be changed)

`Referer` 可以作为一种辅助手段,来判断请求的来源是否是安全的,但是鉴于 `Referer` 本身是可以被修改的,因为不能仅依赖于  `Referer`

3. Use Token (mainstream)


- 服务端给用户生成一个token,加密后传递给用户
- 用户在提交请求时,需要携带这个token
- 服务端验证token是否正确

4. Samesite Cookie attribute

In order to solve this problem from the source, Google drafted a draft to improve the HTTP protocol, adding Samesite attribute to the Set-Cookie response header. It is used to indicate that this Cookie is a “co-sited Cookie”. Co-sited Cookie can only be used as a first-party Cookie but not as a third-party Cookie. Samesite has two attribute values, Strict and Lax.

The deployment is simple and can effectively defend CSRF attacks, but there are compatibility problems.


Samesite=StrictIt is called a strict mode, which indicates that this Cookie cannot be used as a third party Cookie under any circumstances and has the ability to prevent all CSRF attacks. At this time, we will initiate any request to site a under station b, and the Cookie of site a will not be included in the cookie request header.


`Samesite=Lax` 被称为是宽松模式,与 Strict 相比,放宽了限制,允许发送安全 HTTP 方法带上 Cookie,如 `Get` / `OPTIONS` 、`HEAD` 请求.

但是不安全 HTTP 方法,如: `POST`, `PUT`, `DELETE` 请求时,不能作为第三方链接的 Cookie

In order to better defend against CSRF attacks, we can combine the above defense methods.

3. clickjacking

Clickjacking refers to hiding a transparent iframe in a Web page and inducing users to click with an outer fake page. In fact, it triggers a click event on the hidden frame for some operations that users do not know.

Typical clickjacking Attack Process

  1. The attacker built a very attractive web page [I don’t know what is attractive to you, so I won’t write the page, so I’m lazy]
  2. Place the attacked page in theiframeIn
  3. Use styles to overlay iframe over very attractive content
  4. Set iframe to 100% transparent
  5. You were induced to click on the content of the web page. What do you think you clicked on*In fact, you were successfully attacked.

Clickjacking Defense

1. frame busting

Frame busting

if ( top.location != window.location ){
    top.location = window.location

Note: in HTML5, iframe’ssandboxProperty, iframe in IEsecurityProperty, etc., can restrict JavaScript script execution in iframe pages, thus rendering framebusy invalid.

2. X-Frame-Options

X-FRAME-OPTIONS is an http header proposed by Microsoft, which is specially used to defend against clickjacking attacks using iframe nesting. It is also well supported in versions above IE8, Firefox3.6 and Chrome4.

Can be set to the following values:

  • DENY: Deny any domain load
  • SAMEORIGIN: allows loading under the same domain
  • ALLOW-FROM: You can define page addresses that allow frame to load.

4. URL jump vulnerability

URL jump vulnerability refers to a vulnerability that the background server fails to check the legitimacy of the redirection address passed in by the client when informing the browser to jump, causing the user browser to jump to the phishing page.

URL jump is generally implemented in the following ways

  1. Header header jump
  2. Javascript jump
  3. META tag jump

URL jump vulnerability defense

The reason for the jump URL vulnerability is that the server does not check the legitimacy of the jump address passed by the client. Therefore, the way to prevent this attack is to check the jump URL passed by the client.

1. Refere restrictions

If the source of passing URL parameters is determined, we can implement security restrictions in this way to ensure the validity of the URL and prevent malicious users from generating jump links themselves.

2. Add a validation Token

All generated links are guaranteed to come from trusted domains, and the generated links are verified by adding a token which is uncontrollable by the user to the generated links, so that users can be prevented from generating their own malicious links and being utilized.

Security scanning tool

Above we introduced several common front-end security vulnerabilities and also understood some preventive measures, so how do we find the security problems of our website? Companies without security departments can consider the following open source scanning tools:


Arachni is an open source, full-featured and high-performance vulnerability scanning framework based on Ruby. Arachni provides a simple and quick scanning method, which can be started only by inputting the website address of the target website. It can evaluate the accuracy of vulnerability identification and avoid misjudgment by analyzing the information obtained during scanning.

Arachni integrates a large number of detection tools by default, and can implement various attacks such as code injection, CSRF, file inclusion detection, SQL injection, command line injection, path traversal, etc.

At the same time, it also provides various plug-ins, which can realize the functions of form blasting, HTTP blasting, firewall detection, etc.

For large websites, the tool supports session maintenance, browser clustering, snapshots and other functions to help users better implement penetration tests.

2.Mozilla HTTP Observatory

Mozilla HTTP Observatory is a website security analysis tool named Observatory recently released by Mozilla, which aims to encourage developers and system administrators to enhance the security configuration of their websites. The usage is very simple: enter the URL of the website to access and analyze the HTTP header of the website, and then provide numerical scores and the security level represented by letters for website security.

The main scope of inspection includes:

  • Cookie
  • Cross-Source Resource Sharing (CORS)
  • Content Security Policy (CSP)
  • HTTP Public Key Pinning
  • HTTP strict security transfer (HSTS) status
  • Is there an automatic redirection of HTTP to HTTPs
  • Subresource Integrity
  • X-Frame-Options
  • X-XSS-Protection


W3af is a Python-based Web application security scanner. Can help developers and help developers and testers identify vulnerabilities in Web applications.

The scanner can identify more than 200 vulnerabilities, including cross-site scripting, SQL injection, and operating system commands.

Reference articles:

[1]https://github.com/0xsobky/Ha …

[2]https://tech.meituan.com/2018 …

[3]https://zhuanlan.zhihu.com/p/ …

[4]https://mp.weixin.qq.com/s/up …

[5]https://juejin.im/post/5b4e0c …

[6]https://juejin.im/post/5c8a33 …

[7]https://github.com/OWASP/Chea …

Follow-up writing plan (writing order uncertain)

1. The Native JS that You Must Know in Winter Job Hunting Season (Part 2)

2. “CSS You Must Know in Winter Job Hunting Season”

3. Some Browser Knowledge You Must Know in Winter Job Hunting Season

4. Performance Optimization You Must Know in Winter Job Hunting Season

5. The webpack Principles You Must Know in Winter Job Hunting Season

For React technology stack:

1. React series you must understand during the winter job-hunting season

2. The ReactNative series that you must understand during the cold winter job season

Although it took me a lot of time to write this article, I also learned a lot in the process. Thank you for your friends’ willingness to spend precious time reading this article. If this article gives you some help or inspiration, please don’t be stingy with your praise and Star, your affirmation is the biggest motivation for me to move forward.https://github.com/YvetteLau/ …

Recommend to pay attention to my public number: