Attack and Defense of Web front-end security policies XSS and CSRF

This is the 12th day of my participation in Gwen Challenge

With the continuous innovation of front-end technology, front-end is no longer simply do pages. Now front-end websites will involve a large number of user data and privacy, that user data security? The answer is not yes. Therefore, this time front-end security is particularly important. If a website does not have a security policy, it will be easy for attackers to obtain users’ private information through some unknown operations. In the following article, front-end security policies XSS and CSRF! Find out

XSS cross-site request attack

1. What is XSS

Cross-site Scripting (XSS) attacks exploit vulnerabilities of web pages to inject malicious code into web pages so that users can execute the injected malicious code when loading the web pages.

2. Scene simulation

Suppose you have a blog site, and the blog site is poorly secured. So NOW I’m going to publish a blog on this site, and in the published blog, I embedded a paragraph and sent it to my server (server coordination cross domain).

After writing it, I managed to send it out. Now, as long as someone views this blog post on this site, I can easily harvest the cookies of my visitors, which is a simple XSS attack process.

After understanding the definition of XSS, let’s look at the types of XSS attacks.

3. Attack types of XSS

There are three types of XSS:

  • Nonpersistent span (also called reflex)
  • Persistent cross-site (also called storage)
  • DOM cross-site

(1) Non-persistent cross-station (reflective)

① Attack Procedure

  • The attacker constructs a specialURL, which contains malicious code.
  • The user opens with malicious codeURLWhen, the web server will send malicious code fromURLTake out, splice inHTMLIs returned 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.

② Attack Scenario

Reflective XSS (also known as non-persistent XSS) vulnerabilities are common in functions that pass parameters through urls, such as web site searches, jumps, and so on.

③ Attack mode

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.

Reflective XSS can also be triggered by the contents of a POST, but the trigger condition is more stringent (the form submission page needs to be constructed and the user is directed to click), so it is very rare.

(2) Persistent cross-site (storage)

① Attack Procedure

  • The attacker submits malicious code to the database of the target website.
  • 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.
  • 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.

② Attack Scenario

Stored XSS attacks (also known as persistent XSS) are common on sites where users save data, such as forum posts, product reviews, and user messages.

(3) hazards

It is one of the most dangerous types of cross-site scripting, more inside-out and more harmful than reflective and DOM XSS because it does not require manual triggering by the user.

Any Web program that allows users to store data may have stored XSS vulnerability. When an attacker submits a piece of XSS code, it will be received and stored by the server and XSS will be used when all visitors visit a page.

(3) DOM cross-site

① Attack Procedure

  • The attacker constructs a specialURL, which contains malicious code.
  • The user opens with malicious codeURL
  • The user browser receives the response and parses it to the front endJavaScriptTake out theURLAnd execute the malicious code.
  • 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.

(2) the harm

DOM, which typically represents objects in HTML, XHTML, and XML, allows programs and scripts to dynamically access and update the content, structure, and style of documents. It does not require the direct involvement of the server in parsing the response, triggering XSS relies on browser-side DOM parsing.

A summary of the above three types of XSS attacks:

The differences between reflective and memory types are:

Stored XSS malicious code is stored in the database, reflective XSS malicious code is stored in the URL.

The first two differences of DOM are:

DOM TYPE XSS attack, the extraction and execution of malicious code is completed by the browser side, which is a security vulnerability of front-end JavaScript itself, while the other two XSS are security vulnerabilities of the server side.

Comparison of the three:

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

4. How to defend against XSS

Wherever there is input data, there can be XSS hazards.

(1) Set HttpOnly

After the HttpOnly attribute is set in the cookie, the JS script cannot read the cookie information.

(2) Escape strings

Most XSS attacks are carried out by the input and output of data as attack points. Therefore, data is filtered for these attack points.

Data includes input and output of front-end data and input and output of back-end data.

So what is data filtering? How do you filter the data?

Data filtering checks input formats, such as email, phone number, user name, password… Etc., input in accordance with the specified format. It’s not just the front end, the back end does the same filtering checks. Without data filtering, an attacker can bypass the normal input process and send Settings directly to the server using the relevant interface.

Therefore, the data can be filtered by encapsulating filtering functions to divert common input from several attackers without the browser parsing into script code.

function escape(str) {
  str = str.replace(/&/g.'& ');
  str = str.replace(/</g.'< ');
  str = str.replace(/>/g.'> ');
  str = str.replace(/"/g.'&quto; ');
  str = str.replace(/'/g.'& # 39; ');
  str = str.replace(/`/g.'the & # 96; ');
  str = str.replace(/\//g.'/ ');
  return str;
}
Copy the code

(3) Whitelist

For displaying rich text, it is not possible to escape all characters as this would filter out the required format. In this case, whitelist filtering is usually adopted. You can also filter through the blacklist. However, because there are too many tags and tag attributes to be filtered, whitelist filtering is recommended.

XSRF cross-site request forgery

1. What is CSRF

Cross-site Request Forgery, also known as one-click attack or Session riding, commonly abbreviated CSRF or XSRF, Is a method of hijacking a user to perform unintentional actions ** on a currently logged Web application.

For example, the attacker induces the victim to enter a third party website, where he or she sends a 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.

2. Scene simulation

(1) Scenario 1

So let’s say you’re shopping, and you value something, and the item ID is 100. At the same time, the payment interface of this product is xxx.com/pay?id=100, but there is no verification. At this time I was the attacker, I saw a commodity, ID is 200. So, how do I get you to pay for me?

At this time, I sent you an email with a very attractive title. But the message body is hidden . As soon as you checked the email and clicked on it, you helped me buy the product with ID 200.

(2) Scenario 2

To complete a CSRF attack, the victim must complete two steps in sequence:

  • Log on to trusted sitesAAnd generate it locallyCookie
  • Without logoutAIn the case of visiting dangerous websitesB

Looking at this, you might say, “If I don’t meet one of these two criteria, I won’t be attacked by CSRF.” Yes, that’s true, but there’s probably no way to guarantee that this won’t happen! Such as:

  • You can’t guarantee that after you log in to a website, you won’t open another onetabPage and visit another site.
  • You are not guaranteed to close your browser after you have done so locallyCookieIt will expire immediately. Your last session has ended. (Actually, closing a browser doesn’t end a session, but most people doUnder the illusion thatClose the browser to log out/end the session……)

The site mentioned above may be a trusted and frequently visited site with other vulnerabilities.

3. 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.
  • Instead of stealing data directly, the attack uses the victim’s login credentials on the targeted site to impersonate the victim to submit the action.
  • The attacker can not obtain the login credentials of the victim during the whole process, just “fake”.

4. CSRF attack mode

Cross-site requests can be made in a variety of ways:

  • The pictureURL , hyperlinks,CORSFormSubmit and so on. Part of the request can be directly embedded in third-party forums, articles, difficult to track.
  • CSRF is typically cross-domain because outdomains are usually more easily controlled by attackers. However, if the local domain has easily exploited functions, such as Posting pictures and links to the forum and comment area, the attack can be directly carried out in the local domain, and this way of attack is more dangerous!

5. Common types of CSRF attacks

1) CSRF of GET type

GET CSRF is an easy way to attack. It requires only one HTTP request. Attackers generally perform the following operations:

<img src="http://bank.example/withdraw? amount=10000&for=hacker" > 
Copy the code

After the victim visits the page containing this IMG, the browser automatically directs the page to bank.example/withdraw? Ac… The HTTP request. Bank.example will receive a cross-domain request containing the victim’s login information.

2) POST CSRF

This type of CSRF attack usually uses 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.

3) CSRF of link type

Link-type CSRF is less common than the other two cases where the user opens the page and falls victim, because it requires the user to click on the link to trigger the attack. This type usually embeds malicious links in pictures published on forums or other platforms, or induces 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"Word-wrap: break-word! Important; "> <a/>Copy the code

6. How to defend against CSRF

1) Verification code

Add authentication, such as password, SMS verification code, fingerprint, and so on, forcing the user to interact with the application before completing the final request. This method can contain CSRF well, but the user experience is relatively poor.

2) Referer check

Referer represents the source of the request and cannot be forged. The backend can check the referer in the headers request by writing a filter to see if it is a request from the site. The downside is that browsers can turn referer off, and older browsers run the risk of forging referers.

The difference between Referer and Origin is that only post requests carry the Origin request header, whereas referer does in either case.

3) token

Token is the most common defense method. The backend creates a token, then stores the token in the database and sends it to the front-end. Then the front-end carries the token when it sends a request. To determine whether this site is a request.

Example: The user enters the account password and requests the login interface. When the user’s login information is correct, the backend puts the token into the database and returns the token to the front-end, which stores the token in the localstorage. Any subsequent request will put the token in the header. Write a filter on the backend to intercept POST requests and ignore requests that do not require tokens, such as login interfaces and interfaces that obtain tokens, so as to avoid checking tokens before obtaining them. Verification rule: If the TOKEN in the database is the same as the token in the front-end header in the POST request, the verification is successful and the client releases the request.

Iii. Differences between CSRF and XSS

CSRF differs from XSS in the following two aspects:

  • Generally speakingCSRFIs made up ofXSSThe implementation,CSRFIt is often calledXSRF(CSRFThis can also be done by issuing a request directly from the command line.
  • So essentially,XSSCode injection problems.CSRFHTTP problem.XSSIt’s the unfiltered content that causes the browser to execute the attacker’s input as code,CSRFThe browser is sending itHTTPWhen requested.

Fourth, concluding remarks

For the front end, it’s important to guard against attacks, because you never know when the site you’re writing will be attacked.

This article is very shallow about the Web front-end security in the two attack modes, I hope to help you!

  • Pay attention to the public number Monday laboratory, the first time to pay attention to learning dry goods, more interesting columns for you to unlock ~
  • If this article is useful to you, be sure to like it and follow it