Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Common security problems in web front end and how to prevent them

2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

In this article, the editor introduces in detail "the common security problems in the front end of web and how to prevent them". The content is detailed, the steps are clear, and the details are handled properly. I hope that this article "common security problems in the front end of web and how to prevent them" can help you solve your doubts.

Front-end security issues cross-site scripting attack (XSS)

Cross-Site Scripting (Cross-site scripting attack), referred to as XSS, is a kind of code injection attack. An attacker causes a malicious script to run on a user's browser by injecting malicious scripts into the targeted Web site. Using these malicious scripts, attackers can obtain sensitive information of users, such as Cookie, SessionID, etc., thus endangering data security.

In order to distinguish it from CSS, the first letter of the attack is changed to X, so it is called XSS.

There are generally three ways to inject malicious scripts:

Reflexive XSS attack

As the name implies, a malicious JavaScript script is part of a request sent by a user to the site, which is then returned to the user, and the malicious script is executed on the page. Generally occurs in the front-end integrated application, the server-side logic will change the final web page code.

Attack steps for reflective XSS:

The attacker constructed a special URL that contains malicious code.

When a user opens a URL with malicious code, the web server takes the malicious code out of the URL and splices it back to the browser in HTML.

After receiving the response, the user's browser parses and executes, and the malicious code mixed in it is also executed.

Malicious code steals user data and sends it to the attacker's website, or impersonates the behavior of the user and calls the interface of the target website to perform the actions specified by the attacker.

XSS attack based on DOM

At present, it is more popular to separate the front and rear of the project, the reflective XSS is useless. But this kind of attack does not need to pass through the server, we know that the JavaScript of the web page itself can also change the HTML, and hackers take advantage of this to insert malicious scripts.

DOM-based XSS attack steps:

The attacker constructed a special URL that contains malicious code.

The user opens URL with malicious code.

After receiving the response, the user browser parses and executes, and the front-end JavaScript takes out the malicious code in the URL and executes it.

Malicious code steals user data and sends it to the attacker's website, or impersonates the behavior of the user and calls the interface of the target website to perform the actions specified by the attacker.

Storage XSS attack

Also known as persistent XSS, as the name implies, hackers keep malicious JavaScript scripts in the server database for a long time. Once users visit the relevant page data, malicious scripts will be executed. Common in search, Weibo, community post bar comments and so on.

Attack steps for storage XSS:

The attacker submits malicious code to the database of the target website.

When the user opens the target website, the web server takes the malicious code out of the database and splices it back to the browser in HTML.

After receiving the response, the user's browser parses and executes, and the malicious code mixed in it is also executed.

Malicious code steals user data and sends it to the attacker's website, or impersonates the behavior of the user and calls the interface of the target website to perform the actions specified by the attacker.

The difference between these types of XSS attacks

Malicious scripts for reflective XSS are stored in URL, and malicious code for stored XSS is stored in the database.

Reflective XSS attacks are common in the function of passing parameters through URL, such as website search, redirection and so on.

Storage XSS attacks are common in websites with users saving data, such as forum posts, product reviews, user private messages and so on.

In the XSS attack based on DOM, the extraction and execution of malicious code is completed by the browser, which belongs to the security vulnerabilities of the front-end JavaScript, while the other two XSS belong to the security vulnerabilities of the server.

XSS preventive measures

From the introduction to XSS attacks above, we know that XSS attacks have two main steps:

An attacker submits malicious code

The browser executes malicious code

So we can take precautions against these two points:

Input filtering

When a user submits, the input is filtered by the front end and then submitted to the back end, which is not feasible because an attacker may bypass the front end filter, directly construct the request, and submit malicious code. Generally, the back end filters the input data before it is written to the database. Although input-side filtering can solve specific XSS problems in some cases, it will introduce a lot of uncertainty and garbled problems. Such methods should be avoided when guarding against XSS attacks.

Prevent storage and reflective XSS attacks

Change to pure front-end rendering to separate the code from the data.

Fully escape HTML.

Prevent DOM type XSS attacks

DOM-type XSS attack, in fact, the front-end JavaScript code of the website is not rigorous enough to execute untrusted data as code.

Be especially careful when using [xss_clean], .outerHTML, [xss_clean] (), do not insert untrusted data into the page as HTML, but try to use .textContent, .setAttribute (), and so on.

If you use the Vue/React technology stack and do not use the v-html/dangerouslySetInnerHTML function, you will avoid the XSS hidden dangers of innerHTML and outerHTML in the front-end render phase.

Inline event listeners in DOM, such as location, onclick, onerror, onload, onmouseover, etc., the href attribute of the tag, eval (), setTimeout (), setInterval () of JavaScript, and so on, can run strings as code. If untrusted data is spliced into a string and passed to these API, it is easy to cause security risks, which must be avoided.

1 call malicious code setTimeout ("UNTRUSTED") setInterval ("UNTRUSTED") / / location in / setTimeout () / setInterval () call malicious code eval ("UNTRUSTED") Content Security Policy in location.href = 'UNTRUSTED'// eval ()

Strict CSP can play the following roles in the prevention of XSS:

Disable loading of outfield code to prevent complex attack logic.

External domain submission is prohibited. After the website is attacked, the user's data will not be leaked to the external domain.

Inline script execution is prohibited (strict rules, currently found to be used by GitHub).

Disable unauthorized script execution (new feature, Google Map Mobile is in use).

Reasonable use and reporting can find XSS in time, which is helpful to repair the problem as soon as possible.

Use CSP (Content Security Policy, content security policy) proposed by W3C to define the whitelist of domain names

Other measures

Set the HttpOnly property of Cookie to prevent JavaScript from reading cookie

CAPTCHA: prevents scripts from submitting dangerous actions by impersonating users.

XSS attack case

In 2005, the 19-year-old Samy Kamkar launched a XSS Worm attack on MySpace.com. Samy Kamkar's worm infected 1 million users in just a few hours-adding a sentence to each user's profile: "but most of all, Samy is my hero." (Samy is my idol). This is the first heavyweight XSS Worm in the history of Web security, which is a milestone.

In December 2007, Baidu Space received a worm attack and users began to forward spam short messages.

QQ Mail's m.exmail.qq.com domain name was found to be a reflective XSS vulnerability.

In 2011, Sina Weibo was attacked by a XSS hacker who induced users to click on a seductive link and automatically sent a Weibo with an equally seductive link. The scope of attack is expanded layer by layer, and it is also a kind of worm attack.

Cross-site request forgery (CSRF)

CSRF (Cross-site request forgery) cross-site request forgery: an attacker induces the victim to enter a third-party website, where a cross-site request is sent to the attacked website. Use the registration credentials that the victim has obtained in the attacked website to bypass the background user authentication to achieve the purpose of pretending to be a user to perform an operation on the attacked website.

How did CSRF attack?

A typical CSRF attack looks like this:

The victim logged on to website An and retained his login credentials (Cookie)

The attacker lured the victim to visit the B website.

Website B sends a request to website A (this is how to forge the request described below). The Cookie of website An is carried by default in the browser request header.

After receiving the request, the A website server verifies that the user is logged in, so it will process the request.

Common CSRF attack types CSRF of GET type

The utilization of CSRF of type GET is very simple and requires only one HTTP request, which is generally used as follows:

After the victim visits the page containing the img, the browser automatically sends a HTTP request to http://bank.example/withdraw?account=xiaoming&amount=10000&for=hacker. Bank.example will receive a cross-domain request containing the victim's login information.

CSRF of type POST

This type of CSRF is usually leveraged with an automatically submitted form, such as:

Document.forms [0] .submit ()

After visiting the page, the form is automatically submitted, which is equivalent to simulating the user to complete a POST operation.

POST-type attacks are usually a little more demanding than GET, but they are still not complex. Any personal website, blog or website uploaded by a hacker may be the source of the attack, and the back-end interface cannot place its security on only allowing POST.

CSRF of link type

Link-type CSRF is not common, and it requires users to click on the link to trigger it, compared with the other two situations in which users get hit when they open the page. This type usually embeds malicious links in pictures posted in forums, or induces users in the form of advertisements, and attackers usually trick users into clicking on them with exaggerated words.

Big news! Characteristics of CSRF

Attacks are generally launched on third-party websites, not on the attacked sites. The attacked website cannot prevent the attack from happening.

The attack uses the victim's login credentials on the attacked website to impersonate the victim to submit the operation, rather than directly stealing data.

Throughout the process, the attacker can not get the victim's login credentials, just "fake".

Cross-site requests can be made in a variety of ways: picture URL, hyperlink, CORS, Form submission, and so on. Some of the request methods can be directly embedded in third-party forums and articles, which is difficult to track.

CSRF preventive measures

From the introduction to CSRF above, we know that CSRF usually occurs in a third-party domain name, and CSRF attackers cannot get information such as the victim's cookie, but only borrow their login status to forge requests. So we can take precautions against these two points:

Homology detection

Since most of the CSRF comes from third-party websites, we directly prohibit third-party domain names (or untrusted domain names) from requesting us.

In the HTTP protocol, each asynchronous request carries two Header to mark the source domain name:

Origin Header

Referer Header

These two Header are brought automatically in most cases when the browser initiates a request, and the content cannot be customized by the front end. The server can determine the source domain of the request by parsing the domain names in the two Header. At the same time, the server should give priority to detecting Origin. For security reasons, compared to Referer,Origin, it contains only domain names and no paths.

CSRF Token

When the browser initiates a request to the server, the server generates a CSRF Token. CSRF Token is actually a random string generated by the server, and then the string is implanted into the returned page, usually in the hidden input box of the form, which protects the CSRF Token from being leaked.

When the browser sends the request again, it needs to submit it with this CSRF Token value.

The server verifies that the CSRF Token is consistent; requests from third-party Web sites cannot get the CSRF Token value in the user's page.

Set the appropriate SameSite for Cookie

When logging in from website A, the Cookie information set by the server will be returned from the response header, and if the Cookie carries SameSite=strict, it means that the third-party site request header carrying Cookie is completely disabled. For example, when requesting the A website interface from website B, the browser's request header will not carry the Cookie.

Samesite=Strict, which is called strict mode, indicates that the Cookie cannot be used as a third-party Cookie under any circumstances

Samesite=Lax, known as the loose mode, is a bit more restrictive than Strict: if the request is such a request (changing the current page or opening a new page) and is also a GET request, the Cookie can be used as a third-party Cookie. (default)

None will carry it under any circumstances.

Click to hijack (ClickJacking)

Click hijacking (Clickjacking) is a means to achieve the purpose of attack through visual deception. It is often the attackers who embed the target website into their own web pages through iframe, and set the iframe to be transparent through opacity and other means, making it invisible to the naked eye, so that when users operate in the attacker's website, such as clicking a button (the top layer of this button is actually iframe), the target website is hijacked by clicks.

Click to hijack preventive measures

Add a X-FRAME-OPTIONS attribute to the HTTP input, which controls whether the page can be embedded in the iframe

DENY: cannot be nested or loaded by all websites

SAMEORIGIN: can only be nested or loaded by the same domain site

ALLOW-FROM URL: can be nested or loaded by specified sites.

Determine whether the current web page is nested by iframe

HTTP strict Transport Security (HSTS)

HTTP strict Transport Security (HSTS) is a security feature that the web server uses to tell browsers to communicate with it only with HTTPS, not with HTTP.

HSTS stands for HTTP strict transport security, as specified by IETF in RFC 6797 in 2012. It was created to force browsers to use secure connections when the site is running through HTTPS. It is the security header that you add to the Web server and is reflected as Strict-Transport-Security in the response header. HSTS is important because it solves the following issues:

Any attempt by visitors to use an unsafe version of your site's page (HTTP://) will be automatically forwarded to the secure version (HTTPS://).

Old HTTP bookmarks and people who enter the HTTP version of your site can expose you to man-in-the-middle attacks. In these attacks, the attacker changes the communication between the parties and induces them to think that they are still communicating with each other.

Overwriting invalid certificate messages is not allowed, which in turn protects visitors.

Cookie hijacking: this occurs when someone steals a session cookie over an insecure connection. Cookie can contain all kinds of valuable information, such as credit card information, name, address, and so on.

Note that if you have not visited the site using the HTTPS protocol before, HSTS does not work, and only if the browser has created a secure connection with the server once and the website has told the browser through the HTTPS protocol that it supports HSTS, then the browser will force the use of HTTPS, even if the link is replaced with HTTP.

Although our system prefers the HTTPS version by default, you can also make this more clear to other search engines by redirecting your HTTP site to your HTTPS version and implementing HSTS headers on your server. -- Google Security team

Turn on HSTS

Enable HSTS in Apache

Add the following code to your virtual hosts file.

Header always set Strict-Transport-Security max-age=31536000

Enable HSTS in NGINX

Add the following code to your NGINX configuration.

Add_header Strict-Transport-Security max-age=31536000

In fact, adding HSTS headers has a performance advantage. If someone tries to access your site through HTTP instead of issuing a HTTP request, it is simply redirected to the HTTPS version.

How does CDN hijack CDN?

Its name is CDN--Content Delivery Network, the content delivery network. Specifically, CDN uses more cache servers (CDN edge nodes), which are placed in areas or networks where user access is relatively concentrated. When the user visits the website, the global load technology is used to point the user's access to the nearest cache server, and the cache server responds to the user's request. It's kind of like an e-commerce local warehouse, isn't it? CDN has a wide range of applications and supports content acceleration in a variety of industries and scenarios, such as small image files, large file downloads, video and audio on demand, live streaming, site-wide acceleration, and security acceleration.

What is CDN hijacking?

There are many hackers on the network in order to enable users to log on to the phishing website developed by themselves, they will hijack CDN and let users automatically transfer to the website developed by themselves. However, many users are often unaware that they have been hijacked. In fact, the way to verify that it is hijacked is to enter any URL to see if the opened web page is consistent with the URL you entered.

CDN hijacking Prevention measures use SRI to solve CDN hijacking

SRI full name Subresource Integrity-subresource integrity, refers to the browser by verifying the integrity of the resource (usually obtained from the CDN) to determine whether it has been tampered with the security features.

You can enable the SRI function by adding an integrity attribute to the link tag or the script tag, such as

The integrity value is divided into two parts, the first part specifies the generation algorithm of the hash value (sha256, sha384, and sha512), and the second part is the actual hash value encoded by base64, which is separated by a short horizontal (-). The integrity value can contain multiple hash values separated by spaces, and as long as the file matches any of the hash values, the resource can be verified and loaded. Enabling SRI can effectively ensure the integrity of page reference resources and avoid malicious code execution.

How browsers handle SRI

When the browser encounters the integrity attribute in the script or link tag, it compares the hash value of the loaded file with the expected hash value before executing the script or applying the stylesheet.

When the hash of the script or stylesheet is inconsistent with the expected value, the browser must refuse to execute the script or apply the stylesheet, and must return a network error indicating that it failed to get the script or stylesheet.

Content Security Policy (CSP)

Content Security Policy (Content Security Policy) is referred to as CSP, which can clearly tell the client browser which external resources of the current page can be loaded and executed, and which are not.

The significance of CSP

A sharp weapon against attacks such as XSS. The essence of CSP is a whitelist system. Developers explicitly tell clients which external resources can be loaded and executed, which is equivalent to providing a whitelist. Its implementation and execution are all done by the browser, and developers only need to provide configuration. CSP greatly enhances the security of web pages. Even if an attacker finds a vulnerability, he will not be able to inject a script unless he also controls a trusted host that is whitelisted.

Classification of CSP

When Content-Security-Policy is configured and enabled, external resources that do not conform to CSP are blocked from loading.

Content-Security-Policy-Report-Only indicates that the restriction option is not executed, only that the violation of the restriction is recorded. It must be used with the report-uri option.

The use of CSP

Configure Content-Security-Policy through the HTTP header. The following configuration indicates that this page only allows scripts from the current source and https://apis.google.com sources to be loaded and executed:

Content-Security-Policy: script-src 'self' https://apis.google.com

Configure through the page label:

Security sandbox (Sandbox)

The multi-process browser architecture will be divided into two parts: the browser kernel and the rendering kernel. The security sandbox can restrict the access and modification of the rendering process to the operating system resources, and there is no ability to read and write the operating system within the rendering process, which are implemented in the browser kernel one by one. including persistent storage, network access and user interaction and a series of functions that interact directly with the operating system. The browser kernel and the rendering kernel have their own responsibilities, and when they need to transfer data, they will do so through IPC.

The work of the rendering process is the parsing of HTML and CSS, the execution of JavaScript, etc., and this part of the content is directly exposed to users, so it is also the most vulnerable place for hackers to take advantage of attacks. If hackers attack here, it is possible to obtain the permissions of the rendering process, and then threaten the operating system. So you need a wall to run untrusted code in a certain environment and restrict untrusted code from accessing resources outside the quarantine, and this wall is the browser's security sandbox.

The security sandbox exists to protect the client operating system from hackers, but it does not prevent XSS and CSRF.

The security sandbox makes use of the security technology provided by the operating system, so that the rendering process cannot obtain or modify the data in the operating system. The minimum isolation unit of the security sandbox is the process, so the single process browser cannot be protected.

Iframe

Iframe not only brings more rich content and capabilities to our pages, but also brings a lot of security risks. Because the content in iframe is provided by third parties, they are not under our control by default, and they can run JavaScirpt scripts, Flash plug-ins, pop-up dialogs, and so on in iframe, which may damage the front-end user experience.

How to keep your website from being referenced by the iframe of other sites?

Js's defense: put the following code in front of the tag on the site page so that when someone references your site page through the iframe frame, the browser will automatically jump to the page referenced by your site.

If (self = = top) {var theBody = document.getElementsByTagName ('body') [0]; theBody.style.display = "block";} else {top.location = self.location;}

Using X-Frame-Options to prevent web pages from being iframe:X-FRAME-OPTIONS is a http header put forward by Microsoft, which is specially used to defend against click hijacking attacks nested by iframe.

DENY / / deny any domain load SAMEORIGIN / / allow ALLOW-FROM to be loaded in the same source domain / / you can define how the page address that allows frame to load prevents the used iframe from doing something to the current site?

Sandbox is a new attribute of html5, which is mainly to improve the safety factor of iframe. Iframe is notorious for security issues, mainly because iframe is often used to embed third parties and then perform some malicious operations. [this is different from the Sandbox mentioned above] now there is a scenario: my website needs iframe to reference a website, but does not want to be operated by the website DOM, do not want to load some js (advertising, pop-up boxes, etc.), the current window is forcibly redirected to links, etc., we can set the sandbox attribute:

Allow-same-origin: allow to be regarded as homologous, that is, you can operate parent DOM or cookie, etc.

Allow-top-navigation: allows reference pages of the current iframe to jump to links or load via url

Allow-forms: allow form submission

Allow-scripts: allow script files to be executed

Allow-popups: allows browsers to open new windows to jump

"": disable all of the above when set to empty

Read here, this article "web front-end common security problems and how to prevent measures" article has been introduced, want to master the knowledge of this article still need to be hands-on practice to understand, if you want to know more related articles, welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report