In the era of mobile Internet, information security is becoming more and more important. The front end is also facing more and more security challenges, this paper collected the analysis and summary of the online leaders, will continue to summarize the common security problems and defense measures.

CSRF

CSRF concept

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 registration credentials (cookies, etc.) that the victim has obtained in the attacked website, bypassing the user authentication in the background, and achieving the purpose of impersonating the user to perform an operation on the attacked website.

CSRF attack flow

  1. Victim logina.comAnd retained the login credentials (Cookie).
  2. The attacker lured the victim to visitb.com.
  3. b.coma.comA request was sent:a.com/act=xx. Browsers carry it by defaulta.comCookie.
  4. a.comUpon receipt of the request, the request is validated and identified as the victim’s credentials, mistaking it for a request sent by the victim himself.
  5. a.comExecuted on behalf of the victimact=xx.
  6. The attack is complete, the attacker impersonates the victim without the victim’s knowledge, and letsa.comThe user-defined operation is performed.

CSRF Attack type

GET

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.

POST

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.

link

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 usually involves embedding malicious links in the pictures published in the forum, or inducing users to be lured in the form of advertisements. Attackers usually trick users into clicking with exaggerated words, such as:

<a href="http://test.com/csrf/withdraw.php?amount=1000&for=hacker" taget="_blank">Big news!!<a
/></a>
Copy the code

Since the user logged in to the trusted website A and saved the login status, as long as the user actively accessed the above PHP page, the attack was successful.

CSRF features

  • 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 URL,hyperlinks,CORS,Submit the FormAnd so on. Part of the request can be directly embedded in third-party forums, articles, difficult to track.

CSRF Defense measures

CSRF is usually launched from third-party websites. Attacked websites cannot prevent attacks, but can only enhance their own protection against CSRF to improve security.

Homologous detection

The server can use the Origin and referer fields of the Request Headers to determine the source field of the request.

If the attacker sets the Referrer Policy to hide the referer, it is recommended to block the referer directly (consider excluding search engine searches).

Cookies are not cross-domain accessible, so why CSRF? The browser will attach the domain name cookie based on the loaded domain name. For example, if the user logs in to website A and generates authorized cookies, and then visits website B, site B deliberately constructs the request of site A, such as delete operation, and loads the address of A with tags such as script, img or iframe that are not affected by the same origin. The browser will attach the authorized cookie information of the login user at site A, which constitutes CRSF and will delete the data of the current user.

Token

The CSRF attack succeeds because the server mistook the request sent by the attacker for the user’s own request. Then we can require all user requests to carry a Token that a CSRF attacker cannot obtain. By verifying whether the request carries the correct Token, the server can distinguish the normal request from the attack request and defend against CSRF attacks.

  1. willTokenOutput to the page, for the entire pageDOMAll of the treesaformTags are added afterToken.
  2. The request submitted by the page carries thisToken
  3. Server authenticationTokenWhether it is right

Verification code & Password

Interrupt the CSRF process by asking for a verification code or password to be entered again during a critical request.

Double Cookie authentication

Taking advantage of the fact that CSRF attacks cannot retrieve user cookies, we can require Ajax and form requests to carry a value from a Cookie.

  1. Inject a request domain name when the user visits a web pageCookie, the content is a random string (e.gcsrfcookie=v8g9e4ksfhw).
  2. When a request is made from the front end and back endCookieAnd add toURL(Follow an examplePOST https://www.a.com/comment?csrfcookie=v8g9e4ksfhw).
  3. Back-end interface authenticationCookieField andURLCheck whether the fields in the parameter are consistent. If they are inconsistent, the parameter is rejected.

Samesite properties

Starting with Chrome 51, a SameSite property is added to restrict third-party cookies to prevent CSRF attacks and user tracking.

The value of SameSite can be Strict, Lax, or None.

Currently compatibility and practicality are not very good (does not support subdomain), temporarily use.

XSS

XSS concept

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.

XSS classification

type Storage area The insertion point
Type stored XSS Back-end database HTML
Reflective XSS URL HTML
The DOM model XSS Back-end database/front-end storage /URL The front-end JavaScript

Type stored XSS

  1. The attacker submits 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 and splices it inHTMLIs returned to the browser.
  3. When the user’s browser receives the response, it parses it and executes the malicious code mixed in.
  4. 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.

This kind of attack is common in website functions with user-saved data, such as forum posts, product reviews, and user messages.

Reflective XSS

  1. The attacker constructs a specialURL, which contains malicious code.
  2. The user opens with malicious codeURLWhen, the web server will send malicious code fromURL, spliced back to the browser in HTML.
  3. When the user’s browser receives the response, it parses it and executes the malicious code mixed in.
  4. 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.

Reflective XSS vulnerabilities are common in functions that pass parameters through urls, such as website search, jump, etc. Because users need to take the initiative to open malicious URL to take effect, attackers often combine a variety of means to induce users to click.

The DOM model XSS

  1. The attacker constructs a specialURL, which contains malicious code.
  2. The user opens with malicious codeURL.
  3. The user browser receives the response and parses it to the front endJavaScriptTake out theURLAnd execute the malicious code.
  4. 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 XSS differs from the previous two types of XSS: DOM XSS attacks, in which malicious code is extracted and executed by the browser side, are security vulnerabilities of the front-end JavaScript itself, while the other two types of XSS are security vulnerabilities of the server side.

XSS defenses

Submitting malicious code against attackers

The input filter

Input filtering is unreliable for the front end. Because once an attacker bypasses front-end filtering and constructs the request directly, it can submit malicious code.

Input length control

Untrusted input should be limited to a reasonable length. While you can’t completely prevent XSS from happening, you can make XSS attacks more difficult.

Verification code

Prevent scripts from posing as users to submit dangerous operations.

Execute malicious code against the browser

Pure front-end rendering

In a pure front-end rendering, we explicitly tell the browser whether to set a text (.innertext), an attribute (.setAttribute), a style (.style), etc. Browsers can’t easily be tricked into executing unexpected code.

Escaped HTML

Escaping HTML should be avoided as much as possible. But if it’s not pure front-end rendering, you need to adequately escape the HTML template’s insertion points with a suitable escape library.

Prevents DOM XSS attacks

Defending against stored and reflective XSS is the responsibility of the back-end RD. DOM XSS attacks do not occur on the back end. 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.

CSP

Content Security Policies (CSP) are an additional layer of security designed to detect and weaken certain types of attacks, including cross-site scripting (XSS) and data injection attacks.

Defined by HTTP headers (preferred) :

"Content-Security-Policy:"The policy setCopy the code

Using HTML meta tags:

<meta http-equiv="content-security-policy" content="Policy set" />
Copy the code

More policy

  • 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.
HttpOnly & Secure
  • cookieSet in theHttpOnlyProperty, disableJavaScriptRead some sensitivitiesCookie, the attacker finishesXSSYou cannot steal this after injectionCookie.
  • cookieSet in theSecureAttribute, stipulationcookieOnly in thehttpsProtocol can be sent to the server. Prevent information leakage after being captured by listeners during transmission.

Nested iframe

ClickJacking typically uses a transparent IFrame to overlay the original web page and induce the user to perform certain actions.

Prevent other pages from being referenced by iframe

// Add to your own website
if(top.location ! = self.location) { top.location.href ='http://www.baidu.com'; // Force a jump if referenced by another website
}
Copy the code

X-FRAME-OPTIONS

Or add the HTTP response header: X-frame-options

X-frame-options in the HTTP response header, which indicates whether the browser should load an IFrame page. If there is no X-frame-options in the server response header, the site is at risk of a ClickJacking attack.

Prevent other iframes referenced from tampering with their own pages

Add the Sandbox property

<iframe src="Other pages.html" frameborder="0" sandbox=""></iframe>
Copy the code

opener

A page opened in the following two ways can use window.opener to access the window object of the source page, and then tamper with the original page:

window.open

window.open('http://www.baidu.com');
Copy the code

Defense mode:

let newTab = window.open();
newTab.opener = null;
newTab.location = url;
Copy the code

A tag_blank

<a target="_blank" href="http://www.baidu.com"></a>
Copy the code

Defense mode:

<a target="_blank" href="http://www.baidu.com" rel="noopener noreferrer"></a>
Copy the code

CDN hijacked

For the sake of performance, front-end applications usually store some static resources on Content Delivery Networks (CDN), such as JS scripts and style files. Doing so can significantly speed up access to front-end applications, but it also introduces a new security risk. If the attacker hijacked the CDN or polluted the resources in the CDN, the attacker can arbitrarily tamper with our front-end page and attack users.

What can the front end do to deal with traffic hijacking?

SRI

Introduction of SRI

Sub-resource integrity (SRI) is a security feature that allows the browser to check whether the resources it obtains, such as from a CDN, have been tampered with. It determines whether the resource has been tampered with by verifying that the hash value of the obtained file is the same as the hash value you provided.

SRI is enabled by adding integrity to the link tag or script tag.

<script type="text/javascript" src="/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.

The purpose of Crossorigin =”anonymous” is to introduce cross-domain scripts. Using SRI to ensure resource co-domain or enable cross-domain. If this attribute is not added, the CORS policy is disabled.

Browsers handle SRI principles

  • When the browser is inscriptorlinkEncountered in the tagintegrityProperty to compare 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.

How to use SRI

Script tags containing integrity attributes can be generated by using webpack’s html-webpack-plugin and webpack-subresource-integrity.

import SriPlugin from 'webpack-subresource-integrity';

const compiler = webpack({
  output: {
    crossOriginLoading: 'anonymous',},plugins: [
    new SriPlugin({
      hashFuncNames: ['sha256'.'sha384'].enabled: process.env.NODE_ENV === 'production',})]});Copy the code

The onError event and onSuccess event are then injected into the script via the script-ext-html-webpack-plugin. In the onerror event, the data is requested again, and the consistency of the two data is compared to determine whether the data is hijacked by CDN.

Joint CSP

Also, by adding to the CSP header:

Content-Security-Policy: require-sri-for script;
Copy the code

This directive specifies that all JavaScript must have an integrity property and be verified before it can be loaded.

Man-in-the-middle attack

Attack principle

When users visit a website, they often directly enter the domain name of the website in the browser. The browser makes an HTTP request to the web site, gets a redirect response, and then makes an HTTPS request to get the final response. Since there is a plaintext HTTP request and redirect before the HTTPS connection is established, an attacker can hijack the request in a man-in-man manner for subsequent attacks, such as eavesdropping on data, tampering with requests and responses, and redirecting to phishing sites.

HSTS

The full name of HSTS is HTTP strict-transport-Security. It is a Web Security policy mechanism. The server sets the HTTP Response Header to tell the browser that it can only access the current resource through HTTPS. Not HTTP.

HSTS grammar

Strict-Transport-Security: <max-age=>[; includeSubDomains][; preload]
Copy the code
  • max-ageIs a mandatory parameter. It is a value in secondsHSTS HeaderThe expiration time is usually set to 1 year, or 31536000 seconds.
  • includeSubDomainsThis parameter is optional. If this parameter is included, it indicates that the current domain name and its subdomain names are enabledHSTSProtection.
  • preloadThis parameter is optional and is only required when you apply to add your domain name to the built-in browser list

HSTS more

  • As long as it is within the validity period, the browser will be directly mandatory to initiateHTTPSThe request.
  • HSTSLet the browser force the user to reject unsafe links without giving the user a choice.
  • The first time you visit a site, you still need a clear textHTTPRequest and redirect to switch toHTTPS, and refreshHSTSInformation, which can still be used for a man-in-the-middle attack, for which the browser has a built-in listPreload ListThe browser only uses any domain name on this list at any time or under any circumstancesHTTPSInitiate a connection.

cookie secure

Ensure that your session cookies are not visible to attackers through Cookie Secure to avoid man-in-the-middle attacks.

other

HTTPS

HTTPS=HTTP+SSL

Ensure that all required resources are imported using HTTPS.

SSL/TLS

The Transport Layer Security (TLS) protocol and its predecessor Secure Sockets Layer (SSL) provide end-to-end encryption for browsers and servers, ensuring the Security and reliability of Internet communications. Without TLS, other security measures are vulnerable. TLS is the cornerstone of HTTP security.

Cache Control

Specify a caching policy for the page. It is strongly recommended that you manually specify page caching policies, otherwise the browser and proxy will control whether or not the content is cached. An improper caching policy can lead to performance issues and security issues.

Content Type Options

Typically, browsers identify resource types based on the Content Type field in the response header, but if the Content Type of some resource is wrong or undefined, the browser will enable MIME-Sniffing to guess the Type of the resource, parse the Content, and execute.

X-content-type-options response header to turn off the miME-Sniffing function of the browser:

X-Content-Type-Options: nosniff
Copy the code

Information disclosure

The following should be deleted

  • Server BannerAdd to the response headerServer BannerTo indicate their identity and version number:Server: nginx / 1.10.0 (Ubuntu)
  • WebThere’s a lot of framework informationWebFrameworks set response headers to identify themselves and their versions. These response headers are non-standard and do not affect page rendering, just for the publicity of the framework itself. Such as:X-Powered-By, X-Runtime, X-Version, X-AspNet-Version

Refer to the link

  • Front-end Security Series 1: How do I Prevent XSS attacks?
  • Front-end Security Series ii: How to Prevent CSRF Attacks?
  • The SameSite property of the Cookie
  • Content Security Policy (CSP)
  • Summary of Front-end safety Issues (Actual combat)
  • HSTS,
  • Front-end monitoring solution
  • Use SRI to resolve CDN hijacking
  • HTTP security best practices