preface
With the rapid development of the Internet, information security has become one of the focus of the industry. Generally speaking, security is a very complex field. In the era of mobile Internet, front-end personnel often encounter new security problems such as network hijacking and illegal invocation of Hybrid API in addition to traditional SECURITY problems such as XSS and CSRF. This article will introduce some common security problems and how to prevent the content, in today’s fact that security problems are more and more important, has gradually become a front-end development skills.
If this article helps you, ❤️ follow + like ❤️ to encourage the author, the article public account first, followThe front nine south
Get the latest articles for the first time
Front-end safety issues
Cross-site scripting (XSS)
Cross-site Scripting (XSS) is a code injection attack. The attacker injects malicious scripts on the target website to run on the user’s browser. Using these malicious scripts, attackers can obtain sensitive user information such as cookies and sessionIDS, thus compromising data security.
To distinguish it from CSS, the first letter of the attack has been changed to X, so it is called XSS.
There are three ways to inject malicious scripts:
Reflex XSS attack
As the name suggests, malicious JavaScript scripts are part of the request that the user sends to the web site, which is then returned to the user, where the malicious script is executed on the page. This occurs when the server logic changes the final web page code.
Attack steps of reflective XSS:
- The attacker constructs 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, splices it into HTML and returns it to the browser.
- When the user’s browser receives the response, it parses it and executes the malicious code mixed in.
- Malicious code steals user data and sends it to the attacker’s website, or impersonates the user’s behavior and calls the target website interface to perform the operations specified by the attacker.
DOM based XSS attack
Currently, projects with separate front and back ends are more popular, and reflective XSS is useless. But this attack does not need to go through the server, as we know that the JavaScript of the web page itself can also change the HTML, which is used by hackers to insert malicious scripts.
Steps of DOM-based XSS attack:
- The attacker constructs a special URL that contains malicious code.
- The user opens a URL with malicious code.
- When the user’s browser receives the response, it parses it and executes it. The front-end JavaScript picks up 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 user’s behavior and calls the target website interface to perform the operations specified by the attacker.
Stored XSS attack
Also known as persistent XSS, as the name implies, hackers store malicious JavaScript scripts in server-side databases for a long time. Once users access relevant page data, malicious scripts are executed. Common in search, weibo, community post bar comments, etc.
Storage XSS attack steps:
- The attacker submits malicious code to the database of the target website.
- When the user opens the target website, the website server takes the malicious code out of the database, splices it into HTML and returns it to the browser.
- When the user’s browser receives the response, it parses it and executes the malicious code mixed in.
- Malicious code steals user data and sends it to the attacker’s website, or impersonates the user’s behavior and calls the target website interface to perform the operations specified by the attacker.
The differences between these types of XSS attacks
-
Reflective XSS malicious scripts are stored in URLS, and stored XSS malicious code is stored in databases.
-
Reflective XSS attacks are common in functions that pass parameters through urls, such as web site searches, jumps, and so on.
-
Stored XSS attacks are common on web features with user-saved data, such as forum posts, product reviews, and user messages.
-
However, in DOM-based XSS attacks, taking out and executing malicious code is completed by the browser side, which is a security vulnerability of the front-end JavaScript itself, while the other two XSS attacks are security vulnerabilities of the server side.
XSS precautions
From the introduction of XSS attack, we know that there are two main steps of XSS attack:
- The attacker submits malicious code
- The browser executes malicious code
So we can take preventive measures against these two points:
The input filter
It is not feasible to filter input from the front end and then submit it to the back end when the user submits, because an attacker could bypass the front end and directly construct the request to submit malicious code. Typically, the back end filters the input data before writing to the database. While input-side filtering can solve specific XSS problems in some cases, it introduces significant uncertainty and garble problems. This approach should be avoided when defending against XSS attacks.
Protects against stored and reflective XSS attacks
- Change to pure front-end rendering, separating code from data.
- Fully escape HTML.
Prevents DOM XSS attacks
DOM TYPE XSS attack is actually the site’s front-end JavaScript code itself is not strict enough, the untrusted data as code execution.
Be careful when using.innerhtml,.outerhtml, and document.write(). Do not insert untrusted data into the page as HTML. Instead, use.textContent,.setAttribute(), etc.
If using the Vue/React technology stack, and do not use the v – HTML/dangerouslySetInnerHTML function, on the front end render phase avoid innerHTML, outerHTML XSS concerns.
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 and passed to these apis, it is easy to create a security risk that must be avoided.
<! Inline event listener contains malicious code --><img onclick="UNTRUSTED" onerror="UNTRUSTED" src="data:image/png,">
<! Link contains malicious code -->
<a href="UNTRUSTED">1</a>
<script>
// call malicious code in setTimeout()/setInterval()
setTimeout("UNTRUSTED")
setInterval("UNTRUSTED")
// location calls malicious code
location.href = 'UNTRUSTED'
// call malicious code in eval()
eval("UNTRUSTED")
</script>
Copy the code
Content Security Policy
Strict CSP can play the following roles in XSS prevention:
- Prohibit loading outfield code to prevent complex attack logic.
- Prohibit submission from the outdomain. After a website is attacked, user data will not be leaked to the outdomain.
- Forbid inline script execution (strict rules, currently found to be used on GitHub).
- Disable unauthorized script execution (new feature, in use with Google Map Mobile).
- Proper use of reports can discover XSS in a timely manner, which helps to rectify problems as soon as possible.
Use the W3C proposalContent Security Policy (CSP)
To whitelist domain names
Other measures
- Set up the
The HttpOnly cookies
Property to prohibit JavaScript from reading cookies - Verification code: Prevents scripts from posing as users to submit dangerous operations.
XSS attack case
-
In 2005, Samy Kamkar launched the XSS Worm attack on MySpace.com when he was just 19 years old. Samy Kamkar’s worm infected 1m users in a matter of hours by adding the phrase “but most of all, Samy is my hero” to each user’s self-introduction. This is the first heavyweight XSS Worm in the history of Web security and is a milestone.
-
In December 2007, Baidu space received worm attacks, users began to forward spam short messages.
-
The domain name of QQ mailbox m.exmail.qq.com was found to reflect XSS vulnerability
-
In 2011, Sina Weibo was attacked by hackers called XSS, who induced users to click on an enticing link and automatically sent a tweet with the same enticing link. Expanded attack range, is also a worm attack.
Cross-site Request Forgery (CSRF)
Cross-site Request Forgery (CSRF) : An attacker induces the victim to access a third-party website and sends cross-site request to the attacked website. Using the victim in the attacked website has obtained the registration certificate, bypassing the background user authentication, to impersonate the user to perform a certain operation on the attacked website.
How does CSRF attack?
A typical CSRF attack looks like this:
- Victim login
A
Website, and retain the login credentials (cookies) - The attacker lured the victim to visit
B
Web site B
Web site toA
The web site sends A request (this is the way to forge the request described below), and the browser request header carries the Cookie of Website A by defaultA
The web server receives the request, verifies that the user is logged in, and processes the request
Common TYPES of CSRF attacks
CSRF of the GET type
CSRF utilization of the GET type is very simple and requires only one HTTP request. It is typically utilized as follows:
<img src="http://bank.example/withdraw? amount=10000&for=hacker" >
Copy the code
After the victim to visit the page containing the img, the browser will automatically to http://bank.example/withdraw? Account =xiaoming&amount=10000&for=hacker Sends an HTTP request. Bank.example will receive a cross-domain request containing the victim’s login information.
CSRF of the POST type
This type of CSRF is typically exploited using an auto-submitted form, such as:
<form action="http://bank.example/withdraw" method=POST>
<input type="hidden" name="account" value="xiaoming" />
<input type="hidden" name="amount" value="10000" />
<input type="hidden" name="for" value="hacker" />
</form>
<script> document.forms[0].submit(); </script>
Copy the code
When you visit the page, the form is automatically submitted, simulating a POST operation.
Post-type attacks are generally a little more stringent than GET, but still not complex. Any personal website, blog, website uploaded by hackers may be the source of attacks, back-end interface can not rely on the security of POST only above.
CSRF of link type
Link-type CSRFS are uncommon and require the user to click a link to trigger them, compared to the other two cases where the user opens the page and is caught. This type is usually in the forum published in the picture embedded malicious links, or in the form of advertising to induce users to be lured, attackers will usually be more exaggerated words to lure users to click
<a href="http://test.com/csrf/withdraw.php?amount=1000&for=hacker" taget="_blank">Big news!!<a/>
Copy the code
The characteristics of CSRF
- Attacks are generally launched on third party sites, not the site being attacked. The attacked site cannot prevent the attack from happening.
- Attack using the victim’s login credentials in the attacked website, posing as the victim to submit operations; Instead of stealing data directly.
- The attacker can not obtain the login credentials of the victim during the whole process, just “fake”.
- Cross-site requests can be made in a variety of ways: image urls, hyperlinks, CORS, Form submissions, and more. Part of the request can be directly embedded in third-party forums, articles, difficult to track.
CSRF precautions
As we know from the introduction of CSRF above, CSRF usually occurs in the domain name of the third party, and CSRF attackers cannot obtain the victim’s cookie and other information, but only use their login status to forge requests. So we can take preventive measures against these two points:
Homologous detection
Since most CSRFS come from third party sites, we simply prohibit third party domain names (or untrusted domain names) from making requests to us.
In HTTP, each asynchronous request carries two headers, which mark the domain name of the source:
- Origin Header
- Referer Header
These two headers are carried automatically in most cases when the browser makes a request, and the content cannot be customized by the front end. The server can determine the source domain of the request by resolving the domain names in the two headers. Also, the server should preferentially detect Origin. For security reasons, in contrast to Referer, Origin contains only the domain name and no path.
CSRF Token
-
When the browser makes a request to the server, the server generates a CSRF Token. The CSRF Token is a random string generated by the server and then inserted into the returned page, usually in a hidden input box in the form. This protects the CSRF Token from being leaked.
-
When the browser sends a request again, it needs to submit it with the CSRF Token value.
-
The server verifies whether the CSRF Token is consistent. Requests from third-party websites cannot obtain the CSRF Token value in user pages.
Set the appropriate SameSite for the Cookie
After 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 Cookie in the request header of the third-party site is completely disabled. For example, when requesting the interface of website A 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, this is called loose mode, and is a bit more restrictive than Strict: if the request is one of these (changing the current page or opening a new page) and is also a GET request, the Cookie can be a third-party Cookie. (the default)
-
None is carried in any case;
ClickJacking
Clickjacking is a means to attack by means of visual deception. In most cases, attackers embed the target website with iframe in their own web pages, and set iframe as transparent through opacity and other means, making it invisible to the naked eye. In this way, when users operate on the attacker’s website, such as clicking a button (the top layer of the button is actually an IFrame), So that the target site is clickjacked.
Click hijacking precautions
-
Add x-frame-options to HTTP entries. This property controls whether pages can be embedded in iframe
- DENY: cannot be nested or loaded by all websites.
- SAMEORIGIN: Can only be nested or loaded by same-domain sites;
- Allow-from URL: can be nested or loaded by a specified site.
-
Determines whether the current web page is nested by iframe
HTTP Strict Transport Security (HSTS)
HTTP Strict Transport Security (HSTS) is a security feature that web servers use to tell browsers to communicate only with HTTPS, not HTTP.
HSTS stands for HTTP Strict Transport Security, as specified by the IETF in RFC 6797 of 2012. It was created to force the browser to use a secure connection when the site is running over HTTPS. It is the Security header that you added to the Web server and is reflected in the response header as strict-transport-Security. HSTS is important because it addresses the following issues:
- Any attempt by visitors to use an insecure version of your site’s pages (HTTP://)) will be automatically forwarded to the secure version (HTTPS://)).
- Old HTTP bookmarks and people entering the HTTP version of your site can leave you open to man-in-the-middle attacks. In these attacks, attackers alter communications between parties and trick them into thinking 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 session cookies over an insecure connection. Cookies can contain all kinds of valuable information, such as credit card information, names, addresses, and so on.
Note that HSTS does not work if you have not previously accessed the site using HTTPS, and only if the browser has created a secure connection with the server and the site has told the browser over HTTPS that it supports HSTS will the browser then force HTTPS, even if the link has been changed to 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
Open the HSTS
Enable HSTS in Apache
Add the following code to your virtual host file.
Header always set Strict-Transport-Security max-age=31536000
Copy the code
Enable HSTS in NGINX
Add the following code to your NGINX configuration.
add_header Strict-Transport-Security max-age=31536000
Copy the code
In fact, there are performance advantages to adding HSTS headers. If someone tries to access your site over HTTP, instead of making an HTTP request, it simply redirects to the HTTPS version.
CDN hijacked
CDN principles?
It’s called the CDN — Content Delivery Network. To be specific, CDN is to adopt more cache servers (CDN edge nodes), which are placed in areas or networks with relatively concentrated user access. When the user visits the website, the global load technology is used to direct the user’s access to the nearest cache server, and the cache server responds to the user request. (Sort of like a local warehouse for e-commerce, right?) CDN is widely used and supports content acceleration in various industries and scenarios, such as image small file, large file download, VIDEO and audio on demand, live streaming media, whole station acceleration and security acceleration.
What is CDN hijacking?
In order to enable users to log in to their own developed phishing websites, there are many hackers on the Network, through the method of hijacking the CDN, so that users can automatically transfer to their own developed websites. Many users are often unaware that they have been hijacked. In fact, the way to verify the hijacking, is to enter any url to see if the webpage opened and their input is the same url,
CDN hijacking prevention measures
Use SRI to solve CDN hijacking
SRI, Subresource Integrity, refers to a security feature that browsers use to verify the Integrity of a resource (usually obtained from a CDN) to determine whether it has been tampered with.
SRI can be turned on by adding integrity to the link tag or script tag, for example
<script type="text/javascript" src="//s.url.cn/xxxx/aaa.js"
integrity="sha256-xxx sha384-yyy"
crossorigin="anonymous"></script>
Copy the code
The integrity value is divided into two parts. The first part specifies the hash generation algorithm (SHA256, SHA384, and SHA512), and the second part is the actual hash encoded in Base64, separated by a short bar (-). The integrity value can contain multiple space-separated hashes, and as long as the file matches any one of the hashes, the resource can be verified and loaded. Enabling SRI can effectively ensure the integrity of page reference resources and avoid malicious code execution.
How do browsers handle SRI
- When the browser encounters an integrity attribute in a script or link tag, it compares the hash value of the loaded file to the expected hash value before executing the script or applying the stylesheet.
- When the hash value of a script or stylesheet does not match the expected value, the browser must refuse to execute the script or apply the stylesheet, and must return a network error saying that obtaining the script or stylesheet failed.
Content Security Policy (CSP)
A Content Security Policy (CSP) explicitly tells the client browser which external resources on the current page can be loaded and executed, and which cannot.
The meaning of the CSP
XSS and other attacks. The essence of CSP is whitelisting. The developer clearly tells the client 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 the developer only needs to provide the configuration. CSP greatly enhances the security of web pages. Even if an attacker discovers a vulnerability, he cannot inject scripts unless he also controls a whitelisted trusted host.
The classification of the CSP
Content-Security-Policy
Once configured and enabled, external resources that do not comply with CSP are prevented from loading.Content-Security-Policy-Report-Only
Indicates that the restriction option is not enforced, but only the violation of the restriction is logged. It must be withreport-uri
Options are used together.
The use of CSP
- Through HTTP header configuration
Content-Security-Policy
The following configuration indicates that the page allows only the current source andhttps://apis.google.com
Scripts load and execute from these 2 sources:
Content-Security-Policy: script-src 'self' https://apis.google.com
Copy the code
- Through the page
<meta>
Label configuration:
<meta http-equiv="Content-Security-Policy" content="script-src 'self' https://apis.google.com">
Copy the code
Security Sandbox
The multi-process browser architecture will be divided into two main parts: the browser kernel and the rendering kernel. The security sandbox limits the access and modification of the operating system resources by the rendering process, and the internal rendering process does not have the ability to read and write the operating system. These are implemented in the browser kernel, including persistent storage, network access and user interaction and a series of functions directly interacting with the operating system. The browser kernel and the rendering kernel have separate responsibilities, and when they need to transfer data, they do so through IPC.
The work of rendering process is the parsing of HTML, CSS, JavaScript execution, and so on. This part of the content is directly exposed to the user, so it is also the most vulnerable place to be attacked by hackers. If hackers attack here, they may obtain the permission of rendering process, and then threaten the operating system. So you need a wall to keep untrusted code running in an environment that restricts untrusted code from accessing resources outside the quarantine, and the wall is the browser’s security sandbox.
The security sandbox exists to protect the client operating system from hackers, but it does not stop XSS and CSRF.
The security sandbox takes advantage of security techniques provided by the operating system so that the renderer cannot retrieve or modify data in the operating system while running. The least isolated unit of the security sandbox is the process, so single-process browsers cannot be protected.
Iframe
Iframe brings more rich content and capabilities to our pages, but also brings a lot of security risks. Because the content in an IFrame is provided by a third party, they are not under our control by default, and they can run JavaScirpt scripts, Flash plug-ins, pop-up dialog boxes, and so on inside the IFrame, which can ruin the front-end user experience.
How to prevent your website from being referenced by other websites’ iframe?
-
Js defense: Place the following code before the tag of your web page so that when someone references your web page through the iframe framework, the browser automatically redirects to the page referenced by your web page.
<script> if (self == top) { var theBody = document.getElementsByTagName('body') [0]; theBody.style.display = "block"; } else { top.location = self.location; } </script> Copy the code
-
Prevent Web pages from being iframe with X-frame-options: X-frame-options is an HTTP header proposed by Microsoft to defend against clickjacking attacks using nested iframes.
DENY // Reject any domain loads SAMEORIGIN // Allow loading under homologous domain ALLOW-FROM // You can define the page address to allow frame loading Copy the code
How do I disable iframe from being used for certain operations on the current site?
Sandbox is a new property in HTML5 that is designed to improve IFrame security. Iframes are notorious for security issues, mainly because they are often used to embed themselves in third parties and then perform malicious operations. Now there is a scenario where my website needs an iframe to reference a site, but I don’t want the site to manipulate the DOM, I don’t want to load some JS (ads, pop-ups, etc.), the current window is forced to jump to the link, etc. We can set the Sandbox property:
- Allow-same-origin: allows users to be treated as same-origin and operate the parent DOM or cookie
- Allow-top-navigation: Allows current iframe referenced web pages to jump links or load by URL
- Allow-forms: Allows form submission
- Allow-scripts: allows script files to be executed
- Allow-popups: allows the browser to open a new window
- “: If this parameter is set to empty, all permissions are disabled
Recommended reading
- Why are big factories using GIF as a burying point?
- Reflow & Repaint, and how to optimize?
- What is the difference between Promise, Generator, and Async?
- 【Vue source code learning 】 rely on collection
- 【Vue source code learning 】 responsive principle exploration
- Causes and solutions of unreliable JS timer execution
- From how to use to how to implement a Promise
- Explains the page loading process in great detail
Welcome to pay attention to the public account “Front-end South Jiu”
I’m Nan Jiu, and we’ll see you next time!!