CHAPTER 6
MOBILE SERVICES AND MOBILE WEB

Mobile clients get all the attention nowadays—the dominant market share held by both Android and iOS devices is a testament to their current popularity. However, despite all the excitement on the client-side of mobile, vulnerabilities identified on the server-side often represent a higher business risk. Given a client-side SQL injection vulnerability in a mobile application, an attacker would usually have to target a specific client in order to extract the information stored in a SQLite database residing on a single mobile device, likely related to a single user, which may not contain much data of value if the application developers avoided storing sensitive data on the client-side. On the other hand, by exploiting a server-side SQL injection vulnerability within a web service or web application, an attacker may have access to all the application’s data, which, depending on the system, could include highly sensitive information such as email addresses, usernames, passwords, credit card information, and social security numbers for every user of the application. To paraphrase infamous bank robber Willie Sutton when asked why he robbed banks: because the server’s where the data is.

Not only is the business risk usually greater, the attack surface on some mobile systems is larger on the server-side. Given a thin client, which provides the user with an interface to interact with a SOAP-based web service associated with a financial institution, we could undoubtedly identify security issues in how the client parses XML documents, handles logging, stores data, or interacts with other processes on the mobile device. By definition, however, the larger attack surface exists on the server-side because it encompasses endpoints for all of these interfaces plus most of the business logic, internal interfaces, databases, partner interfaces, and so on. Therefore, the server-side components should never be brushed aside and ignored during a security assessment of a mobile application.

Given that the attack surface is often greater on the server-side and server-side vulnerabilities hold a greater business risk for most organizations, this chapter is an important part of this book. The first section provides high-level guidance pertaining to web service security. The next section dives into a set of vulnerabilities that we have often seen in XML-based web services. We focus on attacks against XML-based web services as an example because we see them predominantly in our mobile consulting work, but JSON-based and RESTful web services are also commonly used by mobile applications. We then briefly review popular authentication and authorization frameworks and their associated common vulnerabilities and then finally review blended attacks in which traditional web application vulnerabilities, such as cross-site scripting, can be exploited to leverage exposed native mobile functionality.

GENERAL WEB SERVICE SECURITY GUIDELINES

Understanding what types of attacks will be launched against your organization is crucial before taking on the task of strengthening your defenses. Since 2004, The Open Web Application Security Project (OWASP) has been compiling a list of the “ten most critical web application security risks” to raise awareness of security issues plaguing web-based software. At the time of this writing, the most recent listing was 2010 and is located here: owasp.org/index.php/Top_10_2010. The 2013 release candidate of the Top 10 list is available, but has not been finalized yet; you can find it at owasp.org/index.php/Top_10_2013.

Bug parade lists such as the OWASP Top 10 or CWE/SANS Top 25 Most Dangerous Software errors are successful at raising awareness of common vulnerabilities, and they certainly help security practitioners by providing them with a basic checklist during audits. However, Top X bug lists focus too heavily on a small set of bugs, are not comprehensive, and do not effectively teach developers and architects to design systems defensively. For a more comprehensive list, review MITRE’s Common Weakness Enumeration website (cwe.mitre.org), which includes over 700 types of implementation bugs and design flaws that can lead to exploitable vulnerabilities.

Penetration testers wanting to get up to speed should start by reviewing the common bug lists, such as the OWASP Top 10 and SANS Top 25, and then move on to reviewing free online resources such as the OWASP Testing Guide (owasp.org/index.php/OWASP_Testing_Project), which does contain a section specifically for XML-based web services, and the WS-Attacks project, which documents some of the more obscure web service attacks (clawslab.nds.rub.de/wiki/index.php/Main_Page). Besides online resources, we also recommend picking up Hacking Exposed Web Applications by Joel Scambray, Vincent Liu, and Caleb Sima (McGraw-Hill Professional, 2010) and The Web Application Hacker’s Handbook by Dafydd Stuttard and Marcos Pinto (Wiley, 2011) for additional information on performing a thorough penetration test of a web application or web service. Developers, on the other hand, should focus on understanding how to perform input validation and output encoding securely, how to safely manage error handling and logging, how to implement authentication/authorization, and how to use application programming interfaces properly as opposed to myopically fixating on bug lists. For developers, we recommend Software Security by Gary McGraw (Addison-Wesley, 2006), Security Engineering by Ross Anderson (Wiley, 2008), or Writing Secure Code by Michael Howard and David LeBlanc (Microsoft Press, 2003).

ATTACKS AGAINST XML-BASED WEB SERVICES

We first focus on common vulnerabilities that we have seen in many XML-based web services such as SOAP web services during real-world security assessments. This discussion is by no means comprehensive as a wide range of vulnerabilities can affect XML-based web services, ranging from obscure types of injection vulnerabilities to denial of service vulnerabilities related to administering file handles improperly. This section, however, describes a number of vulnerabilities related specifically to handling XML processing improperly. When assessing the security of a XML-based web service associated with a mobile device, start with the following steps:

1. Identify web service endpoints. Decompile or disassemble the mobile client to find references to web service URLs (use techniques described in Chapter 4). Alternatively, use a web proxy tool or network sniffer while actively using the target application to identify the web service URLs during runtime.

2. Craft legitimate web service requests for all the endpoints and operations identified. Either base these requests on observed requests via network traffic analysis or build these requests manually by analyzing the Web Services Description Language (WSDL) files associated with the web services. SoapUI is a useful tool for this process because it can build a set of base test cases given a URL to an identified WSDL.

3. Now comes the fun part, vulnerability discovery. Alter the structure or contents of the XML documents sent to the web service endpoints to violate confidentially, integrity, or availability of the target system, and observe the response for any anomalies.

image XML Injection

Web services that fail to perform input validation or output encoding on user input employed to construct XML responses are vulnerable to XML injection attacks. The injection of unintended XML structures by an attacker can alter an application’s business logic. Exploitation is, therefore, highly application specific. Consider a scenario in which a mobile application interacts with a web application displayed within a WebView component in order to purchase widgets. On the back-end, the web application queries a set of XML-based web services to retrieve product information, process payments, and finalize orders. When a user adds a product to his or her cart, the web application sends the following XML document to a web service:

Image

The web service responds by providing the product’s price so the web application can now update the cart total properly to $199.99 plus tax, but the web service also reflects part of the user input (the product identifier) verbatim:

Image

In this example, we assume that neither the web application nor the web service performs input validation or output encoding on the product identifier value provided by the user and that the web service simply casts the user input into a numeric data type to find the relevant product order, but reflects the user input verbatim. So let’s consider the outcome when a malicious user provides the following:

Image

The web service would return the following XML document to the web application, which includes XML structures provided by the attacker:

Image

Whether the attacker is able to purchase items for dirt cheap is dependent on how the web application parses the above response. Most applications would extract out the first ProductResponse element, possibly using an XPath query, and use the attacker-provided pricing information to update the cart information. To carry out such an attack, the attacker needs detailed knowledge of the XML response structure sent from the web service to the web application. Therefore, access to the relevant WSDLs or access to the source code of the relevant web application or web services would be extremely beneficial to an attacker.

image XML Injection Countermeasures

Similar to cross-site scripting vulnerabilities, developers can remediate XML injection vulnerabilities via input validation, preferably using a whitelisting approach, and output encoding. The purpose of output encoding is to convert potentially dangerous control characters into characters that can be safely displayed as data. At the very least the less-than (<), greater-than (>), and ampersand (&) characters should be encoded into their corresponding XML entities, as shown in the following example. We strongly recommend relying on encoding functions provided by a well-known security framework such as OWASP’s Enterprise Security API (ESAPI) or the XML parser as opposed to creating your own set of encoding functions. Here’s our prior “bad” example rewritten with improved security through encoding:

Image

image XML Entity Expansion

XML entity expansion attacks exploit XML features that allow users to build documents dynamically at process time by defining XML entities. Additionally, XML parsers allow entities to be defined recursively. Therefore, XML parsers that do not place limitations on the depth of entity expansions are vulnerable to a denial of service attack dubbed the Billion Laughs attack because an attacker could submit an XML document containing a large number of recursive entity references, causing the parser to expand multiple entities and consume a significant amount of memory and CPU time in order to parse the document.

The following XML document shows a single internal entity declaration, which refers to a string. When the XML parser sees the entity in the body of the XML document, it performs a lookup and replaces &a1; (which we’ve highlighted in bold type) with the string defined in the document type definition (DTD):

Image

After parsing the document and replacing the entity with the definition of the entity, the XML parser produces the following:

Image

Now that you understand how to define internal entities, consider the following HTTP request that includes a XML document with recursive entity definitions:

Image

The XML parser expands the &a20; entity into 219 &a1; strings. In this example, the attacker sends an XML document that is only 662 bytes to the web service, and the web service is forced to expand the document to a size greater than 20MB. An attacker could easily craft a small XML document that forces a XML parser to consume gigabytes of memory by using additional recursive entities, which could trigger a denial of service condition on the target system. Such an attack is much more effective than denial of service attacks that seek to flood the target server with an excessive amount of network traffic because this type of attack could be launched by a single malicious actor with limited bandwidth. An attacker could send a single HTTP request that causes the web service to stop operating.

image XML Entity Expansion Countermeasures

To prevent XML entity expansion attacks, developers can disable the use of DTDs in the XML parser or developers can configure the XML parser to enforce a limit on the depth of entity expansions. For example, if you are using Java API for XML Processing (JAXP) 1.3 or later, then you can enable the FEATURE_SECURE_PROCESSING feature to limit the number of entity expansions allowed to mitigate the risk of denial of service attacks. The programmatic configuration for a DocumentBuilderFactory object looks like this:

Image

After enabling this feature, the XML parser rejects our previous example, as shown by the following Java exception. Ultimately, the configuration options will vary among parsers, so review carefully the XML parser documentation used by your web services to determine how to best lock down its features.

Image

Be aware that the same type of attack can also be launched against a client that is processing XML responses from a web service. For example, if an Android application uses the SAXParser class to process XML either from a web service or from an untrusted source such as another Android application, then the application should either disable the use of DTDs or limit the number of entity expansions, similar to how back-end systems can be hardened against denial of service attacks. On the iOS side, the NSXMLParser catches the XML entity expansion attack and throws an NSXMLParserEntityRefLoopError exception before a denial of service condition occurs, but developers who decide to use an XML parser other than the one provided by Apple should carefully review the parser’s options.

image XML Entity Reference

Besides causing a denial of service condition, an attacker can also abuse XML entities to acquire the contents of local files stored on the web server. Consider the following example, which shows an XML document that defines an external entity reference called fileContents that points to the host file on Windows and then uses the defined entity later in the document:

Image

If the XML parser supports DTDs with external entities, which many XML parsers do by default, then the XML parser fetches the host file from the file system and may display the contents of the file within the HTTP response to the attacker. Which files an attacker can steal via this vulnerability depends on the permissions granted to the process responsible for handling web service requests. A web service running under the guise of the administrator or root user is clearly the worst-case scenario. The attacker could also exploit this type of vulnerability to trigger a denial of service condition by forcing the XML parser to access a special device file or forcing the XML parser to make a large number of HTTP requests to access remote resources in order to exhaust the network connection pool.

image XML Entity Reference Countermeasures

As previously stated, for most XML-based web services that do not require DTD processing within the web service request, we recommend simply disabling DTDs altogether. Under some circumstances, however, developers may want to configure their XML parsers to handle DTDs that contain general entities but prevent the processing of external entities. Within JAXP, you can disable the external-general-entities and external-parameter-entities features to prevent the attack since the XML parser will no longer handle external general entities, external parameter entities, or external DTDs. The following Java code shows how a developer can use the setFeature method to set the underlying XML parser’s features to disable the handling of external entities:

Image

Alternatively, you could also hook the entity resolution process by setting up an EntityResolver object that returns an empty string as opposed to the requested system resource. This technique could be used if you want to allow external entities, but only want to allow access to specific resources defined within a whitelist.

Image

Similar to XML entity expansion attacks, XML entity reference attacks can also be carried out against Android and iOS applications. For the most part, the same remediation advice applies to preventing the attack against Android applications. For iOS applications, the NSXMLParser class, by default, does not handle external entities, but a developer might enable this dangerous functionality by calling the setShouldResolveExternal-Entities method. In general, any type of application should avoid handling external entities unless the XML document comes from a trusted source.

COMMON AUTHENTICATION AND AUTHORIZATION FRAMEWORKS

Although a client can authenticate with a server in numerous ways, most web applications authenticate users via password-based authentication, and mobile applications are no different. To make matters worse, users typically do not want to have to type in their credentials every time they access a mobile application, which forces application developers to make some hard decisions. From a security perspective, we have to consider the possibility of device theft and the resulting compromise of all files stored on the mobile device, but we do not recommend storing the user’s credentials in plaintext just so a user does not have to type in his or her credentials every time the user starts a social networking mobile application.

Barring access to a tamper-resistant hardware component such as a Secure Element (SE), in which we could more securely store cryptographic information used for authentication, one possible improvement is to use an authorization framework such as OAuth to first authenticate a user using traditional password-based authentication. The resulting authentication token is then stored on the mobile device as opposed to storing the user’s password in plaintext. In this case, if an attacker physically steals a mobile device, then the attacker only has access to the authentication token and not the victim’s password, which is likely reused by the victim in a multitude of systems. Granted, the attacker now has a token that can be used to perform actions on behalf of the victim, but the back-end systems can minimize the damage by setting reasonable expiration dates, restricting the token’s scope, and revoking tokens that are known to be compromised.

If the storage of a plaintext token is not acceptable, and we do not deem it acceptable for most financial applications that could perform highly sensitive operations, then we suggest forcing the user to authenticate every time he or she uses the mobile application to avoid any type of client-side data storage of credentials or authentication tokens.

Let’s take a look at attacks and countermeasures for some popular authentication/authorization frameworks.

OAuth 2

OAuth, which stands for Open Authorization, is a popular authorization framework utilized by a number of popular organizations such as Google, Facebook, Yahoo!, LinkedIn, and PayPal, many of whom reuse OAuth for their mobile applications. OAuth seeks to provide applications with an authorization framework that allows one application to access the protected resources housed in another application without knowing the user’s credentials associated with the protected resources. Note that we focus on the OAuth 2 specification within this section. OAuth 2 implementations are not compatible with OAuth 1.x implementations, and the security implications are significantly different. There are four main actors within the OAuth protocol:

Resource owner The end-user who has access to the credentials and owns the protected resources.

Resource server The server hosting protected resources. Provided with a valid access token, the resource server should provide the client application with the protected resources.

Client The client application seeking to access protected resources on behalf of the resource owner. The client could be a mobile application or a web application that wants to gain access to protected resources.

Authorization server The server that provides the client application with access tokens after the resource owner has provided the authorization server with valid credentials.

How the client application acquires an access token to gain access to protected resources varies depending on which type of authorization grant the system uses. OAuth 2 defines four different grant types. Understanding each configuration helps us understand the threats inherit to systems that utilize OAuth.

OAuth Authorization Code Grant Type

The first grant type is the authorization code grant type, which is shown in Figure 6-1.

Image

Figure 6-1 Authorization code grant type

Here the steps are explained in more detail:

1. The client starts the process by directing the resource owner’s user-agent to the authorization endpoint. For a mobile device, the user-agent is either the mobile browser or a WebView component embedded within the mobile application. This request includes the client identifier, requested scope, local state, and redirection URI.

2. The resource owner provides the authorization endpoint with his or her credentials, which are typically a username and password.

3. Assuming that the resource owner has decided to grant the client access and provided the proper credentials to the authorization endpoint, the authorization server redirects back to the client application using the redirection URI provided previously. This request provides the client with the authorization code.

4. The client application requests an access token from the authorization server by providing the authorization code and the redirection URI.

5. The authorization server verifies the authorization code and verifies that the redirection URI matches the redirection URI used to redirect to the client earlier. If both values are valid, then the authorization server provides the client with an access token. The client can now use the access token to access protected resources on the resource server.

There are a number of important security implications of using this grant type, which enable potential attacks.

image Using Mobile WebView to Steal Credentials

In theory, with this grant type the client application cannot access the resource owner’s credentials used to authenticate to the authorization server because the resource owner types his or her credentials on the authorization server’s web page via the user-agent, which is typically a browser. This assumption works well when the client and authorization servers are web applications, but this assumption is false if the mobile application is using a WebView component as its user-agent, as opposed to the external mobile browser, because the host application can execute arbitrary JavaScript within any domain. Therefore, using a WebView component with this grant type turns this into an overly complicated version of the resource owner password credentials grant type because the client application could steal the resource owner’s credentials by injecting malicious JavaScript into the page. For example, a malicious application pretending to be a legitimate iOS application could use the UIWebView’s stringByEvaluatingJavaScriptFromString method to inject password stealing JavaScript code into the authorization server’s login page.

image URL Redirection Attacks

Validating the redirection URI is also important. All client redirection URIs should be registered prior to this workflow and validated during step 1, and the redirection URI in steps 1 and 4 must match before the authorization coughs up the access token in step 5 (Figure 6-1). Validating the redirection URIs allows the authorization server to prevent open URL redirection attacks that trick the victim into going to http://www.somerandomevilsite.com. Not only can this vulnerability be used to phish unsuspecting users, but it could also be used to acquire valid access tokens.

OAuth Implicit Grant Type

The next type of authorization grant type is the implicit grant type shown in Figure 6-2.

Image

Figure 6-2 Implicit grant type

The steps of implicit grant type are as follows:

1. The client starts the process by directing the resource owner’s user-agent to the authorization endpoint. This request includes the client identifier, requested scope, local state, and redirection URI.

2. The resource owner provides the authorization endpoint with his or her credentials, which are typically a username and password.

3. Assuming that the resource owner decided to grant the client access and provided the proper credentials to the authorization endpoint, the authorization server redirects back to the client application using the redirection URI provided previously. The access token is provided within the fragment of the URI.

4. The user-agent makes a request to the web-hosted client resource, which, in theory, does not include the fragment (no access token).

5. The webhost client resource provides JavaScript code designed to extract out the access token and any other parameters included in the fragment.

6. The user-agent executes the JavaScript code and passes the access token to the client application.

The implicit grant workflow is similar to the authorization grant workflow but is simplified for client applications written in a scripting language such as JavaScript and solely existing in the browser. In this case, the access token is returned to the client as part of the URI fragment. This approach is interesting because the URI fragment is never sent by user-agents as part of a HTTP request; therefore, intermediate servers can neither see data stored in the fragment nor would a fragment appear in an unencrypted form in client or web server logs, thus limiting some types of information leakage vulnerabilities. But the client JavaScript code can still extract the access token for use at a later time, or be extracted by an attacker via cross-site scripting attacks.

OAuth Resource Owner Password Credentials Grant Type

The next type of authorization grant type is the resource owner password credentials grant type shown in Figure 6-3 and detailed in the following steps:

Image

Figure 6-3 Resource owner password credentials grant type

1. The resource owner starts the process by providing his or her credentials directly to the client application.

2. The client then requests an access token by providing the user’s credentials to the authorization server.

3. The authorization server provides the client application with an access token assuming that the credentials are valid.

In this case, the client application is trusted with the resource owner’s credentials, but it does not need to retain the credentials for future use because the credentials can be discarded after acquiring an access token. This approach is acceptable when the client application is trusted not to leak the credentials to a third party, and the authorization server, resource server, and client application are controlled by the same entity, which is applicable to many mobile applications.

An evil client could impersonate the resource owner and potentially break into other servers on “behalf” of the resource owner, or a poorly written client could leak the password credentials to a third party, but the use of this grant type is an improvement over storing the credentials in plaintext on the mobile device and submitting them in every HTTP request via basic access authentication, which we still encounter during security assessments.

OAuth Client Credentials Grant

The final type of authorization grant type is the client credentials grant type, which is shown in Figure 6-4. It is clearly the simplest grant type supported by OAuth.

Image

Figure 6-4 Client credentials grant

1. The client starts the process by authenticating itself with the authorization server.

2. The authorization server then sends the client the access token, assuming the proper credentials are provided by the client.

The OAuth specification makes it clear that the client credential grant type should only be used for confidential clients—meaning clients that are capable maintaining the confidentiality of their credentials. Most mobile applications do not meet these criteria because in a device theft scenario the confidentiality of the credentials will be breached. Therefore, this grant type should be avoided.

This grant type would be acceptable if the mobile application has access to a tamper-resistant hardware component such as a secure element (SE). For instance, the client application first authenticates with an applet within the secure element using credentials, such as a PIN, provided by the resource owner, and then the SE applet provides the client application with client authentication information that is later passed to the authorization server. A lockout mechanism also needs to be implemented within the SE applet to prevent brute-force attacks, but this is fairly standard for Java Card applets.

Since most mobile applications cannot interface with a SE, however, this grant type should not be used unless the mobile application takes additional steps to protect client authentication information. One possibility involves forcing the user to type in a password of sufficient entropy every time the application launches. The password would be used to derive an encryption key using a key derivation function and that encryption key would be used to decrypt the client authentication information before transmitting the data to the authorization server. There are still problems with this approach, such as how do you securely provision the client with the authentication information?

image General OAuth Threats

Although we have briefly discussed a number of security implications by describing the different grant types, OAuth 2’s attack surface is large. The official threat model for OAuth 2 is almost as long as the actual specification of the authorization framework. Additionally, design flaws and implementation bugs are bound to exist in the applications that use OAuth and the frameworks based on this complicated specification. The following are some of the more serious vulnerabilities that would concern us most when reviewing any system utilizing OAuth. This list is by no means complete given the complexity of the framework.

Lack of TLS enforcement OAuth does not support message-level confidentiality or integrity, so always use TLS to prevent trivial disclosure of authorization tokens, refresh tokens, access tokens, and resource owner credentials while in transit.

Cross-site request forgery (CSRF) Unlike previous versions of OAuth, which used a request token throughout the process, the authorization code grant type and implicit grant type flows are vulnerable to CSRF unless the implementation uses the “state” parameter, which sadly is described as an optional, but recommended, parameter within the 2.0 specification. For example, an attacker can complete the first step of the authorization code grant workflow to acquire an authorization code for his or her own account. The attacker can then craft a malicious web page and trick users into visiting it (<img src="http://www.example.com/oauth_endpoint?code=attacker_code” />), which could result in the victim’s client using an access token associated with the attacker’s protected resource, not the victim’s.

Improper storage of sensitive data Bulk compromise of any of the tokens or credentials used for OAuth represent a large risk. Therefore, the server-side application should take sufficient steps to protect the sensitive data with cryptographic controls.

Overly scoped access tokens Scope represents the level of authorization associated with a specific access token. Does the access token allow the possessor to send messages on your behalf on a social networking application (send spam to all your friends, for instance), or does the access token only allow the possessor to view portions of your social networking profile? Follow the principle of least privilege and restrict the scope of access tokens when feasible.

Lack of token expiration Tokens that do not expire and are overly scoped are almost as good as stealing the resource owner’s credentials.

SAML

The Security Assertion Markup Language (SAML) standard is an XML-based framework designed to exchange authentication and authorization data between security domains. The authentication and authorization data is transmitted between an identify provider (IdP), which produces assertions about an identity, and a service provider (SP), which consumes the assertions and provides access to protected resources. Since SAML has been widely adopted by a variety of organizations, it is no surprise that mobile web applications also utilize this framework for authentication and authorization purposes, especially for single sign-on (SSO). SAML seeks to address three primary use cases in which authentication and authorization data needs to be exchanged between security domains:

Single sign-on The goal of SSO is to allow a user to gain access to multiple separate systems without having to log into each system separately. A user only has to log into one system and the authentication/authorization information is shared with the other systems without forcing the user to reauthenticate.

Federated identity Identity federation seeks to establish an agreement on how to refer to a specific user across multiple systems. Each system may store different information pertaining to the user, but all systems have agreed on a name identifier associated with the user. Federated identity seeks to reduce the amount of work required to maintain users across separate systems since typically each system does not need to maintain identity-related information such as passwords.

Web service security SAML is flexible in the sense that the security assertion format can also be used to protect SOAP-based web services.

SAML defines a set of profiles to describe how to use SAML protocol messages to solve the different use cases. The following is a description of the SP-Initiated Web Browser SSO profile that uses the Redirect/POST bindings, which is shown in Figure 6-5. The Web Browser SSO profile is by far the most commonly used SAML profile that we have seen in security assessments of mobile web applications.

Image

Figure 6-5 SAML SP-Initiated Web Browser SSO

1. The user attempts to access a protected resource on the SP via his or her user-agent, but the user currently does not have an active session with the SP.

2. The SP responds to the user-agent with a HTTP redirect (302 or 303), which includes the AuthnRequest message within a URL query parameter named SAMLRequest. The user-agent redirects to the IdP.

3. The IdP determines whether the user is already logged in. If not, then the IdP asks the user to provide valid credentials.

4. The user provides the IdP with his or her credentials, which is typically performed through a HTML form. SAML does not dictate what types of credentials must be used with the IdP for authentication purposes, but generally the user provides a username and password.

5. After successful authentication, the IdP builds a SAML assertion. The SAML assertion describes who the user is and any relevant authorization information. The SAML assertion must be signed via the XML Signature specification and is included within a Response message.

6. The user-agent uses a HTTP POST request to send the Response message, which includes the assertion, to the SP. This step is typically achieved via a HTML form that is automatically submitted using JavaScript as a POST request.

7. The SP validates the SAML assertion using the included digital signature and then returns the protected resource to the user-agent assuming that the signature is valid and the user should have access to the resource. This step assumes that the SP has the IdP public key to validate the digital signature properly.

image General SAML Threats

Like OAuth, the attack surface for SAML-based systems is large. The official SAML threat model describes five attacks that developers and architects creating SAML-based systems should be concerned about.

Collusion Two or more actors may collude to attack another actor within the system. For example, multiple SPs may collude against users and/or the IdP.

Denial of service attacks An attack designed to make the target system unavailable to legitimate users. We have already discussed DoS attacks that can be launched against XML-based web services, such as XML entity expansion attacks and XML external entity attacks, but there are many other examples such as an oversized XML DoS or a XML encryption transformation DoS that targets XML parsers. Or, an attacker could launch a more traditional DoS attack designed to flood the target with network traffic.

Man-in-the-middle attacks An attacker intercepts, and could manipulate, messages between two parties. For example, an attacker may intercept SAML assertions, user credentials, or session identifiers in order to hijack a user’s accounts. The main mitigation against MiTM attacks is to use TLS or IPSec. If transport layer security is not enough because some of the intermediary nodes cannot be trusted, then the system should adopt message-level encryption and integrity.

Replay attacks An attacker could intercept a message and replay it to the endpoint, or the originator of the message could replay it multiple times if the message should only be used once. For example, a hostile SP may attempt to replay a received SAML assertion from a user/IdP to a second SP. If the second SP accepts this assertion, then the hostile SP can impersonate the victim and retrieve protected resources associated with the victim on the second SP.

Session hijacking attacks An attacker hijacks an existing session by acquiring or predicting the session identifier used. An attacker may intercept a session identifier via a MiTM attack or steal a session identifier via a cross-site scripting attack. Or an attacker may use a session fixation vulnerability to fixate a victim’s session identifier to a known value.

Other types of attacks exist against SAML besides the ones described in the official threat model. Consider the ability for a malicious actor to manipulate the contents of a SAML assertion passed to a SP. If a SP is unable to determine that the SAML assertion has been manipulated by the attacker, then the attacker is able to impersonate anyone in the system. Normally, a SP is able to detect that the assertion has been modified by utilizing the XML Signature standard, since all assertions must be signed by the IdP using this standard, but the SP may contain implementation bugs that affect the handling of assertion signature validation and processing. One way to pull off this type of attack is by exploiting an XML Signature wrapping (XSW) vulnerability in a vulnerable implementation of a SAML framework.

image XML Signature Wrapping Attacks

During an XSW attack against a SAML-based system, an attacker captures a legitimate SAML response (possibly because the attacker is a legitimate user of the target system or because the attacker can launch a MiTM attack), modifies the structure and contents of the XML, and then sends the modified response to the SP. If the SP does not handle signature validation and assertion processing properly, then the SP is unable to detect the malicious modifications to the XML document. Therefore, the attacker is able to impersonate other users within the system by altering the SAML response. For example, the attacker can manipulate the Subject portion of the assertion in order to claim to be an administrator or another normal user in the system.

XSW attacks were originally discussed in an academic paper entitled “The Curse of Namespaces in the Domain of XML Signature” by Meiko Jensen, Lijun Liao, and Jörg Schwenk (cs.jhu.edu/~sdoshi/jhuisi650/papers/spimacs/SPIMACS_CD/sws/p29.pdf). Although XSW attacks apply to any system that utilizes the XML Signature standard, it was disclosed in 2012 that most of the popular SAML frameworks in use were vulnerable to XSW attacks (see the paper entitled “On Breaking SAML: Be Whoever You Want to Be” by Juraj Somorovsky, Andreas Mayer, Jörg Schwenk, Marco Kampmann, and Meiko Jensen, nds.rub.de/media/nds/veroeffentlichungen/2012/08/22/BreakingSAML_3.pdf). Of the analyzed SAML frameworks, 11 out of 14 were vulnerable to serious XSW attacks that would allow authentication and authorization mechanisms to be bypassed in systems that utilized these frameworks. Although the researchers worked with the vendors to fix the affected frameworks, many older systems certainly still rely on previous versions of these SAML frameworks and even newly developed systems may continue to use older versions of these vulnerable SAML frameworks.

XML Signatures are typically processed by two separate modules: a signature validation module and a business logic processing module. Consider the XML structure of a typical SAML response in Figure 6-6. The SAML specifications state that the assertion must have an enveloped signature, so the Signature element must be a child of the Assertion element. The Reference element within the Signature element has an URI attribute, which refers to the element that should be digitally signed (Assertion element). Normally, the application invokes the signature validation module to determine whether the assertion is properly signed using the IdP’s public key. Then the business logic processing module extracts the assertion to provide the application with identification information contained within the signed assertion.

Image

Figure 6-6 The structure of a normal SAML response

The easiest related attack to try out against a SP is simply to remove the Signature element from within the Assertion element and send the modified XML document to the SP. This attack is dubbed the signature exclusion attack, and surprisingly, Apache Axis 2 and OpenAthens frameworks were actually vulnerable to this type of attack in the past. In this case, the signature validation module of the vulnerable frameworks would always incorrectly state that the assertion was properly signed when the Signature element did not exist, and the business logic processing module operated as if nothing was wrong.

The simplest version of a XSW attack is shown in Figure 6-7. The attacker adds a new Assertion element (EVIL_ID) claiming to be a different user under the Response element, but this added assertion does not have an enveloped signature because the attacker does not have the IdP private key and, therefore, cannot generate a valid signature for this assertion. Higgins, Apache Axis2, and IBM XS 40 Security Gateway were all vulnerable to this type of attack. The signature validation module would find all the assertions that contained an enveloped signature, possibly using an XPath query looking for only Assertion elements with a Signature element as a child node, and then would validate the signatures. Therefore, the signature validation module would return successfully because the attacker did not modify the original assertion with the signature (SOME_ID), but the business logic processing module would actually use the first assertion found (EVIL_ID) in the XML document to identify the user. The academic study goes on to describe a large number of permutations of XSW attacks, including attacks that do not conform to the SAML specifications and attacks in which the signatures are invalid. These attack permutations should be understood and tested for in existing systems that use SAML.

Image

Figure 6-7 A modified SAML response that includes an assertion included by the attacker

image XML Signature Wrapping Countermeasures

In the study, only the Windows Identity Foundation, developed by Microsoft, and SimpleSAMLphp were found to be not vulnerable to signature exclusion attacks or any type of XSW attack that was tried. SimpleSAMLphp resists attacks by first performing XML Schema validation based on the SAML schemas. Then SimpleSAMLphp extracts each assertion contained in the XML document into a separate DOM tree. For each extracted DOM tree, SimpleSAMLphp makes sure that each assertion is protected by an enveloped signature and then checks the validity of each signature for each assertion. Finally, SimpleSAMLphp processes the assertions assuming that every assertion is protected by a valid signature. Essentially, SimpleSAMLphp meticulously performs input validation to prevent complicated XSW attacks.

Because these vulnerabilities were identified in widely used frameworks, developers should make sure they are using the latest version of their SAML framework of choice. In general, developers and testers who rely on these SAML frameworks should understand the complexity of the underlying SAML and XML Signature standards and validate that their systems are not vulnerable to similar attacks.

MOBILE WEB BROWSER AND WEBVIEW SECURITY

The mobile web browser, and the commonly used WebView component in Android and iOS applications, is an important part of the overall mobile attack surface and should not be forgotten. Organizations that wish to support multiple mobile platforms (iOS, Android, BlackBerry, and Windows Mobile) are daunted by the prospect of developing multiple separate codebases, so developers are actively seeking cross-platform development frameworks (see Chapter 8), which allow for the development of platform agnostic code. Developing a mobile web application utilizing HTML5 and JavaScript bridges to interface with native mobile functionality is one option to limit how much platform-specific code must be constructed to support diverse platforms. Understanding vulnerabilities that affect traditional web applications and services will remain important, but understanding the security implications of such cross-platform development frameworks will be increasingly important as adoption increases.

Exploiting Custom URI Schemes

iOS and Android both allow applications to define custom URI schemes, which can be triggered within the mobile browser or within another mobile application, such as an email client, as an IPC mechanism. This functionality also allows malicious JavaScript or HTML code to invoke native mobile functionality and is similar to a cross-site request forgery (CSRF) attack. Whereas CSRF attacks exploit the existing trust between the browser and the target site, these attacks can exploit the trust between the browser and the target mobile application. The attacker may seek to trick the victim into visiting a hostile website by sending the victim an email or SMS, or the attacker might exploit this functionality when crafting an exploit for more traditional web application vulnerabilities such as cross-site scripting.

Both operating systems support a number of default URI schemes, such as the tel scheme, which can be used to invoke the dialer from within the mobile browser. For example, if a user visits a web page that contains the following HTML code, then the phone application will open on the Android device, but the number will not be dialed unless the user also taps on the Call button, as shown in Figure 6-8. Similarly on iOS, users are prompted as to whether they actually wants to dial the number provided in the URL, as shown in Figure 6-9. From a security perspective, requiring additional user interaction before actually calling the phone number provided in the URL is the correct action to take. Plenty of applications use custom URI schemes (handleopenurl.com/ currently lists over 600 custom URI schemes for iOS), but do they use them securely?

Image

Figure 6-8 The dialer application on Android triggered by the tel URI scheme

Image

Figure 6-9 The dialer application on iOS triggered by the tel URI scheme

Image

image Abusing Custom URI Schemes via Skype

In 2010, Nitesh Dhanjani documented that the Skype application for iOS supported a custom URI scheme (skype) but failed to prompt the user before performing actions such as dialing a phone number assuming the user’s credentials were cached. Therefore, if the victim has Skype installed on his or her phone and visits a hostile web page with the following HTML, then Skype dials the number without any user interaction:

Image

image Abusing Unstructured Supplementary Service Data Codes

In a more extreme case, Ravi Borgaonkar revealed in 2012 at the ekoparty Security Conference that it was possible to trigger the parsing of unstructured supplementary service data (USSD) codes without user interaction on some Android devices via the tel URI scheme. Therefore, an attacker could send the victim an SMS message using the tel URI scheme, trick the victim into going to a malicious page that includes an IFRAME, which uses the tel URI scheme, or craft a NFC tag that uses the tel URI scheme in order to force the dialer application to process a USSD code. The USSD protocol is normally used to communicate between mobile devices and the computers of a mobile network operator (MNO) as opposed to SMS, which is a protocol designed for communication between two mobile devices on the network. Handset manufacturers and MNOs are free to define their own USSD services, hence the name. Therefore, USSD codes that are supported on one type of mobile device or MNO might not be supported on a different mobile device or MNO. For example, on T-Mobile devices, dialing #686# returns your phone number, dialing #225# returns your current account balance, and #793# resets your voicemail password to the last four digits of your phone number (wouldn’t want that to be triggered remotely would we?).

To determine if your specific mobile device is vulnerable, type tel:*%2306%23 into your mobile browser. One harmless USSD code is *#06#, which shows the device’s IMEI number. On a vulnerable phone, the dialer application will open and the IMEI number will be displayed without any user interaction, as shown in Figure 6-10. While many possibilities exist, Ravi Borganonkar demonstrated remotely triggering a factory reset USSD code that was specific to Samsung devices, such as the Samsung Galaxy S III, which, as one might guess, will simply wipe your phone. The following HTML code demonstrates this exploit, which we strongly recommend not trying on an unpatched device unless you’re OK with losing all your data. A number of other Android devices were also identified as vulnerable, but only Samsung was shown to expose factory reset functionality via a USSD code.

Image

Figure 6-10 A vulnerable Android device that processes USSD codes without user interaction via the tel URI scheme

Image

Now that you are aware of the inherent danger of exposing custom URI schemes that allow websites displayed in a mobile browser to trigger native mobile functionality without any user interaction, we’ll review how to identify vulnerable Android and iOS applications.

image Custom URI Schemes in Android

As we mentioned in Chapter 4 on Android security, intents are the primary IPC mechanism used by Android applications. The following code snippet from the AndroidManifest.xml file shows how a developer could define a custom URI scheme (someapp) within this configuration file. Visiting a URL using this scheme will cause this activity to execute. Note that this activity is exposed to external applications other than the browser because any application on the device could send an intent to this activity (android:exported attribute not set to false).

Image

The following Java code is designed to handle the intent. In this case, the code validates the URI scheme used and then sends out an SMS message based on parameters from the query string using Android’s SmsManager class:

Image

Exploitation is relatively simple. The attacker tricks the victim into visiting the following malicious page in his or her mobile browser, and the phone sends an SMS message to 5555555555 without the user knowing. Exposing this type of functionality via a custom URI scheme could be abused to conduct toll fraud remotely or harass users.

Image

image Android Custom URI Scheme Countermeasures

Preventing exploitation of custom URI schemes is similar to preventing exploitation of intent-based attacks as described previously in Chapter 4 on Android security:

• Restrict access to the component via the android:exported attribute within the AndroidManifest.xml file.

• Perform input validation on all data received from intents.

• Use signature-level permissions if you need to implement an IPC mechanism between two trusted applications.

image Custom URI Schemes in iOS

The primary form of IPC on iOS is custom URI schemes, so we commonly see this type of mechanism during iOS application security assessments. To determine if an iOS application defines a custom URI scheme, you can inspect the Info.plist file using the plutil command, which is the property list utility on Mac OS X, but it can also be acquired on a rooted iOS device via Cydia (plutil /User/Applications/[APP_ID]/[APP_NAME].app/Info.plist). The following is a snippet from the property list file that shows how an application can register for a protocol handler by setting the CFBundleURLSchemes key and its associated value, which is an array of URI schemes (only someapp in this case):

Image

The application’s UIApplicationDelegate handles the URL via the handleOpenURL method after the mobile browser encounters the someapp scheme or another application on the device invokes this scheme. In this case, the vulnerable Objective-C code uses parameters from the query string to create a new file on the file system:

Image

Again, exploiting this type of vulnerability is straightforward. The attacker can trick the victim into visiting a hostile web page or send the victim a link via email or SMS to the victim’s mobile device and hope he or she clicks it. The following HTML code demonstrates this technique and exploits the vulnerable code to generate a new file within the /tmp directory:

Image

image iOS Custom URI Scheme Countermeasures

In addition to performing strict input validation on the provided URL, you can move away from using the deprecated handleOpenURL method and use the openURL method instead, which is available in iOS 4.2 and later versions. The openURL method takes two additional arguments that could be validated, such as sourceApplication, which is the bundle identifier of the requesting application, and annotation, which is a propertylist object defined by the requesting application. For example, when the custom URI scheme is used within Mobile Safari, then the sourceApplication argument is set to com.apple.mobilesafari. The following Objective-C code shows how you could validate the sourceApplication argument to make sure it matches the bundle identifier of the receiving application before handling the URL for additional processing. Installing applications with duplicate bundle identifiers is not allowed on iOS, but this type of IPC authentication is arguably weaker than Android’s signature-based permission checks.

Image

Exploiting JavaScript Bridges

Both Android and iOS applications often use a WebView object to embed a browser component within the application in order to display mobile web content. This allows developers to deliver a web application within a simple thin client, which is easy to port across platforms. For example, the following code from an Android application shows the Google home page within an Activity.

Image

Both platforms allow developers to tweak the WebView’s settings and build bridges between native mobile functionality and JavaScript code executing within the WebView. Exposing additional native functionality to mobile web applications written in HTML and JavaScript is a common practice, but can have disastrous security implications if implemented poorly. In this section, we explore a number of different ways that JavaScript bridges can be constructed and how they can be exploited by attackers who can load their own content within the victim’s WebView component. Similar to the exploitation of global custom URI schemes, attackers can use a number of techniques to load their own content into the victim’s WebView, such as the abuse of traditional web application vulnerabilities such as cross-site scripting, open URL redirection, or MiTM attacks, or attackers may be able to trigger loading of untrusted content via an IPC mechanism supported by the OS. While traditional web application vulnerabilities may be involved, attackers can typically do more damage this way because they have access to native mobile functionality via JavaScript.

image Android addJavaScriptInterface WebView Injection

An Android application can inject Java objects into a WebView via the addJavascriptInterface function. This allows JavaScript code to call the public methods of the injected Java object. Exposing Java objects to JavaScript could have some negative security implications, such as allowing JavaScript to invoke native phone functionality (sending SMS to premium numbers, accessing account information, and so on) or allowing JavaScript to subvert existing browser security controls such as the same origin policy.

Android’s API documentation has always warned against using this feature because an injected Java object can manipulate the host application in unintended ways, but not much information exists documenting how to fully exploit these issues. An academic paper titled “Attacks on WebView in the Android System” by Tongbo Luo, Hao Hao, Wenliang Du, Yifei Wang, and Heng Yin (www.cis.syr.edu/~wedu/Research/paper/webview_acsac2011.pdf) explores a number of unique attacks and describes a situation in which a file utilities object is exposed to JavaScript code, thus allowing attackers to manipulate the file system if an attacker can control any of the content rendered in a WebView via MiTM, JavaScript injection, or redirection attacks. The following example code from the paper shows that the vulnerable application injects a FileUtils object into the JavaScript, which allows the JavaScript to write to the file system:

Image

The paper goes on to state that, “In our case studies, 30% Android apps use addJavascriptInterface. How severe the problems of those apps are depends on the types of interfaces they provide and the permissions assigned to them.” Certainly, the permissions of the host application matter unless the attacker can also identify ways of bypassing Android’s security model, but do the types of interfaces exposed matter as implied by this academic research? The following code exposes the SmokeyBear class to JavaScript, but only declares one public function that returns a string. Is this interface safe to expose?

Image

Probably not, prior to API level 17 (Android 4.2); if an application uses the addJavascriptInterface and allows an attacker to control the content rendered in a WebView, then an attacker can take control of the host application regardless of the type of interface exposed, contrary to popular belief within the development communities. Consider the following code that uses reflection to acquire a reference to a Runtime object via the SmokeyBear interface in order to write an ARM executable to the target application’s data directory and then execute it via Linux commands. The entire executable is omitted for brevity, but we created a simple executable using the Android ARM tool chain to test this type of vulnerability that sends all files stored on the SD card to a remote web server to steal photos, videos, and any other data improperly stored on the SD card. This type of payload works against unrooted and rooted devices, since anything on the SD card is world readable and writable. If the attacker wants to break out of the Android application sandbox, an attacker could use this same technique to drop a root exploit onto the device (GingerBreak, RageAgainstTheCage, zergRush, psneuter, and so on) and then execute it.

Image

image Android WebView Injection Countermeasures

Applications targeted to API level 17, and above in the future, protect against the previous reflection-based attack by requiring programmers to annotate exposed functions (@JavascriptInterface), as demonstrated by the following code. However, currently less than 2 percent of devices support API level 17, according to the Android platform versions dashboard (developer.android.com/about/dashboards/index.html), so we cannot realistically recommend using annotations to prevent this type of attack for a couple years until adoption of newer versions of Android is more widespread.

Image

In the meantime, we recommend the following:

• Only use the addJavascriptInterface if the application truly loads trusted content into the WebView, so avoid loading anything acquired over the network or via an IPC mechanism into a WebView exposing a JavaScript interface.

• Develop a custom JavaScript bridge using the shouldOverrideUrlLoading function, which is described in the next section. Although, developers still need to carefully think about what type of functionality is exposed via this bridge.

• Reconsider why a bridge between JavaScript and Java is a necessity for this Android application and remove the bridge if feasible.

image Android WebView JavaScript Bridge Exploitation via shouldInterceptRequest

As mentioned in the last section, an Android application can intercept URL requests by overriding the WebViewClient’s shouldInterceptRequest function as demonstrated by the following Java code. In this case, the application checks the URI scheme used and if it matches someapp, then the application uses reflection to acquire an instance of an object and invokes a function based on parameters from the query string. Although this example may seem unrealistic to some developers, we have seen very similar vulnerable code during security assessments:

Image

Exploiting this vulnerability is similar to how global URI schemes are exploited. If the following HTML and JavaScript code is loaded into the WebView, then an instance of the Runtime object will be acquired, the exec function will be invoked, and the UNIX touch command will be executed to create a new file on the SD card. In this example, we are assuming that the host application has permission to write to the SD card (android.permission.WRITE_EXTERNAL_STORAGE), which is relatively common.

Image

image Android WebView Bridge Exploitation Countermeasures

An application that checks the newly loaded URL for a custom URI scheme and responds accordingly should be careful about what functionality is exposed via this custom URI scheme, and use input validation and output encoding to prevent common injection attacks. Exposing the ability to use reflection to untrusted content is exceedingly dangerous without performing strict input validation to restrict which classes can be instantiated and which functions can be invoked.

image iOS UIWebView JavaScript Bridge Exploitation

iOS also supports the ability to embed web content within an application via the UIWebView class, but it does not support an explicit JavaScript bridge such as Android’s addJavascriptInterface. However, like an Android application, an iOS application can intercept URL requests by defining a shouldStartLoadWithRequest delegate method as part of a UIWebViewDelegate implementation, as demonstrated by the following Objective-C code. Just like the previous Android example, the application checks the URI scheme used and if it matches someapp, then the application uses reflection to acquire an instance of a class and invokes a function based on a JSON payload within the query string of the URL.

Image
Image

Again, exploiting this vulnerability is similar to how global URI schemes are exploited. If the following HTML and JavaScript code is loaded into the WebView, then the attacker forces the iOS application to instantiate an object of the cigDbAccess class, which we are assuming is defined elsewhere in the application, and invokes the executeQuery to execute a SQL query against a SQLite database. In this example, the attacker is abusing functionality existing within the application’s codebase, but the attacker could also abuse standard iOS API functions to access other native mobile functionality.

Image

image iOS UIWebView JavaScript Bridge Exploitation Countermeasures

The same countermeasures for Android apply for iOS, such as strict input validation and output encoding of user input, while developing a custom URI scheme defined for a local WebView component using a UIWebViewDelegate. Again, be wary of code that performs reflection using tainted input.

image Mozilla Rhino JavaScript Bridges

Some developers may want to write a large portion of their mobile applications in JavaScript and expose native mobile functionality to the JavaScript via well-defined interfaces. This allows developers to create a hybrid application of native code and platform agnostic JavaScript code so at least part of the codebase remains common across Android, iOS, and BlackBerry devices. Additionally, developers may not want to rely on executing JavaScript within a WebView component because they may not need the other features and overhead provided by a browser component, such as a complex user interface. The WebView components on Android use the V8 JavaScript engine, which was developed by Google and converts JavaScript to native ARM code before executing, but developers are unable to access this JavaScript directly. An alternative solution involves using the Mozilla Rhino JavaScript engine, which can operate in either an interpretive mode or a compilation mode by compiling JavaScript into Java byte code.

Mozilla originally developed Rhino because it needed to create a JavaScript engine in Java in order to create the “Javagator” browser, which never saw the light of day, but Sun later licensed the technology, so development of this JavaScript engine continued. One of the interesting features of this engine is called LiveConnect, which allows JavaScript code to interact with Java objects without any additional bridging code. Although certainly convenient, LiveConnect is insecure by default and cannot be disabled, so developers need to take additional steps to limit the damage from JavaScript injection attacks in their applications so exploitation does not result in full compromise of the host application.

Consider the following example, which uses the Mozilla Rhino engine to interpret some JavaScript code. We first associate the current thread with a Context object, and then we create a top-level scope with all the standard objects by calling the initStandardObjects function. We also add the na property, which is an instance of the NetworkAccess class to the scope. In this example, the NetworkAccess class is designed to be called from JavaScript to make a JSON web service request to a web server and acquire the JSON payload. The evaluated JavaScript acquires the JSON payload and uses the eval function to parse it. While convenient and powerful, direct execution of a JSON payload that contains user-controlled data poses a significant security risk. The risk is exacerbated by the ability of the JavaScript to interact with arbitrary Java classes via LiveConnect.

Image
Image

The application developer is expecting a harmless JSON payload from the web service that will look like the following. This JSON payload is clearly harmless.

Image

But consider the following JSON payload, which when evaluated invokes the doSomethingBad function associated with the NetworkAccess class. The developer may expect that JavaScript code will only invoke certain “safe” functions associated with the NetworkAccess class and not any functions that could do damage. The client application may be dealing with a hostile, or compromised, JSON web service, or the web service may be vulnerable to JSON injection attacks, thus allowing the attacker to alter the structure of the JSON payloads in the HTTP responses.

Image

And finally, consider the following JSON payload, which when evaluated uses reflection to acquire a reference to the Runtime object and then invokes the exec function to execute a Unix command. Like the exploit code from the previous section, we are assuming that the host application has permission to write to the SD card; otherwise, creating the file on the SD card would fail. Again, the developer is not expecting the JavaScript code to invoke the getClass function, which is available in all Java objects.

Image

image Mozilla Rhino JavaScript Bridges Countermeasures

Because Java objects can be accessed via LiveConnect, developers need to go out of their way to sandbox JavaScript code executed by the Mozilla Rhino JavaScript engine. Thankfully, Rhino does support sandboxing based on full class names, although these steps are not well documented in the official documentation. For example, we can define the following class that implements Mozilla’s ClassShutter interface. This class is required to implement one function named visibleToScripts, which should return true if the provided full class name should be exposed to the JavaScript code. So we can implement a simple class name whitelist to prevent access to arbitrary Java classes. After instantiating a ClassShutter object, we need to provide this object to the current context via the setClassShutter function.

Image

Restricting which classes can be accessed via JavaScript is a good start, but in some applications, you need to be able to restrict which fields are accessible as well. In our vulnerable code example, we would not want JavaScript code to be able to access the doSomethingBad function. In addition to the ClassShutter, we could extend the NativeJavaObject to override the get function to define a field level whitelist, as demonstrated in the following Java code. After defining our customized NativeJavaObject, we also have to define a custom WrapFactory and ContextFactory to make sure our customized class is used to restrict access to only a specific set of fields, such as the makeHttpRequest function and the getJsonPayload function.

Image

SUMMARY

As you have seen, developing secure web services and web applications remains crucial when developing secure mobile applications because these two activities are deeply intertwined. Classical web application and web service vulnerabilities are not going away any time soon. You should also not lose sight as to how the mobile web browser, or WebView component, is handling interactions with web applications and what native mobile functionality is exposed to these web applications as developers may gravitate to using techniques that allow for the development of more platform-agnostic code.