CHAPTER 8
WebOS Security

image

WebOS is a relatively new mobile operating system created by Palm, Inc, that makes liberal use of web technologies at the application layer, including HTML, CSS, and JavaScript. Palm first announced at the Consumer Electronics Show (CES) in 2008 and the first WebOS phone, the Palm Pre, was released in June 2009.

NOTE

WebOS is entirely different from the previous operating system used on Palm devices, organically known as Palm OS. Palm OS and WebOS are completely different.

Introduction to the Platform

WebOS is based on Linux and uses several open-source packages. These packages are freely available for download on Palm’s website (http://opensource.palm.com). The page has a list of the open-source packages included with WebOS, the original tarballs, and any custom Palm patches. This list transparently shows which open-source components have been used and how they have been modified for the platform. The packages were released to fulfill Palm’s Open Source licensing obligations.

At the time of this writing, the Palm Pre has been released, but the SDK is still in beta and is changing from release to release. For example, the main HTML escaping security setting changed in release 1.0.4. Because the platform’s security model is still changing, any major changes to the model after release 1.2.0 are not included in this chapter. Expect changes in the future, especially the addition of new security functionality and the adoption of more secure default behavior.

To understand WebOS application security and how to develop secure applications on the platform, you need to know the following items, all of which are discussed in this chapter:

image    WebOS architecture

image    Developing applications

image    Security testing of the platform and its applications

image    Debugging and disassembly

image    Code security

image    Application packaging

image    Permissions and users controls

image    Secure storage

WebOS System Architecture

The WebOS architecture is very similar to that of a normal desktop PC. At the lowest level, WebOS runs a custom Linux distribution using the Linux 2.6 kernel. The Linux kernel manages devices, schedules applications, and provides general OS functionality (for example, the file system and process scheduling). Unlike many other embedded devices that run Linux, the Linux internals are almost completely abstracted from third-party WebOS applications. However, curious developers are still able to explore the system by connecting to the device after placing it in developer mode.

On top of the kernel, running in user mode, are several system processes and the UI System Manager. This WebOS-specific component is responsible for managing the life cycle of WebOS applications and deciding what to show the user. The UI System Manager is referred to as Luna and lives within /usr/bin/LunaSysMgr. It is actually a modified version of WebKit, the open-source web engine used by several browsers, most notably Safari on Mac OS X and Google Chrome. However, unlike those versions of WebKit, Luna is not used solely for web page rendering. Rather, all third-party WebOS native applications are authored using web technologies (HTML, JavaScript, CSS) and actually execute within Luna. So what appears in Linux as one process is in reality internally running several WebOS processes. Luna’s internal Application Manager controls the life cycle of these processes.

It is important to draw a distinction between WebOS processes, such as the e-mail application, and system processes, such as the Wi-Fi service. The former runs entirely within Luna and is not scheduled by Linux. The Wi-Fi service and others like it are traditional Linux processes scheduled by Linux kernel’s scheduler. All Linux processes, including Luna, run with super-user (a.k.a. root) permissions. This does not mean that all WebOS applications can completely control the device. Quite the contrary: Luna enforces per-application permissions and ensures that malicious applications cannot completely compromise the device. The chink in this sandbox’s armor is that a bug in Luna or its web-rendering engine could be exploited by malicious code to compromise the sandbox and abuse Luna’s super-user permissions.

WebOS uses Google’s V8 JavaScript engine (http://code.google.com/p/v8/), a high-performance JavaScript engine that first shipped with Google’s Chrome browser. The V8 runtime creates a sandbox that prevents JavaScript from directly modifying memory or controlling the device’s hardware. For example, WebOS applications are prevented from directly opening files or devices such as /dev/kmem. This sandbox enables multiple processes at different privilege levels to cohabit the same Luna process. However, having applications that aren’t actually allowed to use the phone’s capabilities wouldn’t be that compelling.

The “Mojo” framework provides the bridge between the JavaScript sandbox and the device. Mojo refers broadly to a collection of services and plug-ins that are exposed to JavaScript and may be used by applications to access device functionality. For third-party application developers, Mojo is the window to leveraging the device’s capabilities.

There are two broad categories of extensions provided by Mojo: services and plug-ins. Plug-ins are written in C or C++ and implement the Netscape Plugin API (NPAPI). This API provides a bridge between JavaScript, Webkit, and objects written in other languages. The Camera, for example, needed to be written as a plug-in because it accesses device hardware directly. Because Luna knows how to communicate with plug-ins, Luna can load the plug-ins and display them on the same screen along with traditional Mojo framework UI elements. Each plug-in exposes some JavaScript methods that can be used to change the plug-in’s behavior or receive plug-in events. Third-party developers do not generally use plug-ins directly; instead, they use Mojo APIs that will end up invoking the plug-ins.

Services differ from plug-ins because they execute outside of the main Luna process. Services are long-running programs responsible for carrying out specialized tasks or monitoring critical data points. Services may also be isolated so as to separate native code from Luna and prevent a service process crash from affecting Luna. System services may be written in Java or C. With the current version of the SDK, the service interface is not exposed to legitimate third-party developers. However, portions of the service interface have been reverse engineered by the hobbyist community and third-party services will likely appear soon, even if they are not officially sanctioned by Palm.

Each service has a remote procedure call (RPC) interface that applications can use to communicate with the service. Some of these interfaces are documented, some are not. Palm does not grant permission to use undocumented interfaces. This lack of documentation is not a security boundary, and the system does not stop third-party applications from calling undocumented service methods.

Communication occurs over the “Palm Bus,” a communications bus based on the open-source D-Bus. The bus is a generic communication router that may be used to send and receive messages between applications. Its interface is much easier to use than standard IPC, and the bus manages the grunt work of serialization/deserialization, authorization, and listener registration. System applications can register with the bus to receive messages and access the bus to send messages to other applications. Only Palm applications are currently allowed to register as listeners on the bus. However, all applications use the bus extensively—either directly by using the service API or indirectly by using Mojo APIs that execute D-Bus calls under the covers.

All WebOS applications are identified using the “reverse-dns” naming convention. For example, an application published by iSEC Partners may be called com.isecpartners.webos.SampleApplication. This naming convention first originated with Java applications and is widely used to identify application owners and prevent naming collisions between applications. Not all applications must use this convention. Some applications use the standard D-bus notation), which is the complete path to the executable on disk (for example, /usr/bin/mediaserver). These applications are the extreme exception, and all third-party applications are named using reverse-dns notation.

The naming convention and the Palm Bus work together to play an important role in overall service security. The Palm Bus is divided into two channels: the public channel and the private channel. Not all services listen on both channels. For example, the sensitive SystemManager service only listens on the private channel. The Palm Bus only allows applications under the com.palm.* namespace to send messages to private-channel services. Services that want to be available to all applications, such as the Contacts service, listen on the public channel. Some services listen on both, but expose different service interfaces to each bus. This “permission gradient” is one of the only privilege gradients that exists in WebOS.

A final note on JavaScript and WebOS architecture. You may be familiar with JavaScript from programming web applications. WebOS JavaScript is the same, and the application is exposed to the JavaScript as a Document Object Model (DOM). This makes manipulating the application just like manipulating a web page. WebOS even includes the popular and useful Prototype JavaScript library. Because web developers are already familiar with these technologies, they can quickly learn how to create WebOS applications.

However, there are some subtle but important differences between the WebOS JavaScript execution environment and that of a standard web browser. Most notably, WebOS applications are not restricted by the Same Origin Policy. Regardless of their origin, applications can make requests to any site. Although developers may find this capability useful, malware authors may abuse the lack of a Same Origin Policy to communicate with multiple sites in ways that they cannot do within a web browser. The Same Origin Policy still applies to JavaScript executing in WebOS’s web browser, and the standard web application security model is not changed when simply browsing the Web.

Model-View-Controller

WebOS applications implement the Model-View-Controller (MVC) architectural pattern, a popular design pattern that emphasizes the separation of data access (the model), presentation instructions (the view), and input and business logic (the controller). Segregating components along functional lines makes applications more maintainable and increases the probability that components may be reused.

WebOS adds an additional component to the MVC architecture called an assistant. Assistants coordinate the interaction of the model, view, and controller, and most of an application’s JavaScript code will be implemented within the assistant.

The boundaries between the model, view, and controller are not simply logical. Each type of component has its own directory within the application package. For example, models are stored within the “models” subdirectory, and views within the “views” subdirectory. Additionally, views are HTML files whereas models, controllers, and assistants are all JavaScript. Be aware that JavaScript can be included in any of these components, so take care to prevent script injection into any application context.

Stages and Scenes, Assistants and Views

Every WebOS application is composed of a series of stages and scenes. The stage is the platform on which the entire application executes. Each application must have at least one stage, but it may have many. Generally, only applications that operate in different perspectives will have multiple stages. For example, a Sports application could have two different perspectives: a full-screen perspective and a more minimal perspective that shows updated sports information in the dashboard at the bottom of the screen. A stage is used to implement each of these perspectives.

Scenes are particular screens within stages. For example, the Sports application would show one scene listing all of the football teams. Once the user selects a team, the scene would transition to a detail scene focused solely on the selected team.

Internally, every WebOS application maintains a scene stack. As the user navigates through the application, new scenes are pushed onto and popped off the stack. Users can navigate through the stack using forward and back gestures, a behavior very similar to that of a standard web browser. The most important security detail to know about an application’s scene stack is that scenes from different applications may exist within the same stack. The consequences of this are explored later in this chapter.

Working behind the scenes are the assistants, which implement the actual application logic and conduct the heavy lifting (such as making web requests) required to complete the application’s purpose. The assistant is the master of the scene stack and coordinates the controller to push and remove scenes.

Assistants are bound to scenes and the application via filenaming conventions and the sources.json file, which exists in the root of the application’s package. Every application must have at least one scene assistant and one stage assistant. An application assistant is not required, but larger apps that have multiple stages tend to have one. The stage and application assistants are accessible to all the scenes within an application stage and are generally used to coordinate and contain global variables.

Views are HTML pages defining the semantic markup of the application. Standard Cascading Style Sheets (CSS) can be used to change the look and feel of the view. Palm provides WebOS developers with a collection of common controls, known as widgets, to speed development and provide a consistent user experience. Developers specify which widgets to include in their views by inserting special “div” tags into the output HTML document. For example, the following tag includes a button widget:

<div id=“MyButton” name=“MyButton1” x-mojo-element=“Button”></div>

Development and Security Testing

Palm has been very forthcoming with its SDK, and third-party applications are obviously a priority. The WebOS SDK (a.k.a. the Mojo SDK) may be downloaded for free from http://developer.palm.com. Developers are required to register before they are allowed to access the SDK. Registration is free. The Mojo SDK is available for Linux, Mac OS X, and Windows. This author slightly prefers the Mac OS X environment over Windows because of stronger terminal support when actually logging into and accessing the device.

As of this writing, the SDK is in beta and there have been several changes as Palm integrates feedback from application developers and continues to develop new features. Be vigilant of SDK changes, especially as they relate to changes in security behavior. A precedent for this already exists—Palm changed the default behavior of HTML escaping in a previous release. Thankfully, this change was made from an insecure default to a secure one, but who knows what changes the future may bring.

Developers can use their favorite web development environment. Palm recommends using Eclipse (www.eclipse.org) with the Aptana plug-ins. More instructions on how to configure this environment are available from http://developer.palm.com as part of the Getting Started how-to guide. Once Eclipse is running, developers may install a WebOS Eclipse plug-in. This plug-in adds wizards for creating applications and scenes as well as for packaging code and installing it on the device.

Developer Mode

By default, developers cannot access the terminal on the device or install unsigned applications. To be allowed to carry out these actions, developer mode must first be enabled. To do so, follow these instructions:

NOTE

For more information, refer to “Command Line Tools” on the Palm website (http://developer.palm.com/index.php?option=com_content&view=article&id=1552).

1. Boot the WebOS device.

2. Once the main launcher screen is on top, type upupdowndownleftrightleftrightbastart. While you type this, the search UI will pop up and nothing will appear to be happening.

3. Once the entire code has been entered, the Developer Mode Application will appear. Select it by clicking on it.

4. Toggle developer mode by setting the value of the slider in the top right to On.

5. Exit the Developer Mode Application and reset the device.

The emulator enables developer mode by default, so the preceding instructions are unnecessary when you’re using the emulator.

When the phone is enabled in developer mode, many of the security protections are disabled. Only use development mode on development devices or temporarily when performing testing. Do not leave your personal phone in development mode.

Accessing Linux

WebOS stands apart from other mobile platforms due to the unprecedented access Palm provides to the underlying Linux OS. To connect a terminal to Linux, follow these steps:

1. Plug in the WebOS device or start the emulator.

2. If you’re on Windows:

a. Open a command prompt.

b. Run novacom –t open tty://.

c. This will open a root terminal on the device. Note that pressing CTRL-C will cause novacom to exit but will not actually kill the shell process running on the device.

3. If you’re on Mac OS X or Linux:

a. Open a terminal window.

b. Run novaterm.

c. A root terminal will open on the device.

If more than one device is connected (for example, the emulator and a physical device), you can choose which device to connect to by using the -d parameter. For example, use the following for devices connected via USB:

    novaterm -d usb

Once connected to Linux, you can explore the device’s file system. Because all WebOS applications are written in JavaScript, the original source code can be reviewed to determine how the applications actually work. Most interesting are the following folders:

image

Emulator

The WebOS emulator runs on Mac OS X, Windows, and Linux using the Virtual Box virtualization software (see Figure 8-1). The emulator can be used for most testing but does not exactly mimic a device. First of all, the emulator always has developer mode enabled. Second, you can use the “luna-send” tool to simulate call events. This virtual radio simulator is a great benefit of using the emulator for rapid development.

image


Figure 8-1 The WebOS emulator running on Mac OS X

To send fake text messages, do the following:

NOTE

For more information, refer to “Radio Simulator” on the Palm website (http://developer.palm.com/index.php?option=com_content&view=article&id=1662).

1. Open a terminal to the emulator.

2. Run the luna-send tool and send a message to the com.palm.pmradiosimulator system service. The luna-send tool sends messages across the Palm Bus and can be used for testing applications and service calls without the overhead of writing an application.

luna-send -n 1 luna://com.palm.pmradiosimulator/set_incomingsms

{“number”:“2065551212”,

“message”:“‘I love security reviewing the Pre!’”}

Debugging and Disassembly

First the good news: Because WebOS applications are written in JavaScript, they are extremely easy to reverse-engineer and disassemble. Simply find the application’s location on the file system and review the JavaScript manually. This technique is useful not just for finding security vulnerabilities, but also for discovering system service interfaces and learning more about WebOS application development.

Some system services are written using Java or C. To disassemble Java services, use the JD-Gui Java decompiler (http://java.decompiler.free.fr/) and use IDA Pro (http://hex-rays.com/) for C disassembly. In general, neither of these tools will be required by WebOS application developers striving to write secure applications.

Unfortunately, the WebOS debuggers are somewhat deficient and not as easy to use as other mobile development environments. Currently the Palm debugging toolkit consists of three tools: the D8 JavaScript debugger, the Palm Inspector (shown in Figure 8-2), and log statements that are printed into /var/log/messages. Currently the best way to debug is to use log messages for standard tracing/debugging, debug complicated logic problems using the D8 debugger, and use the Palm Inspector for UI debugging.

To launch the debugger, open a root terminal and run the “debug” command. This will start D8, the JavaScript debugger for the V8 engine. The debugger attaches to Luna and debugs all JavaScript processes simultaneously. Unfortunately, there is no way, other than intelligently setting breakpoints, to scope debugging to a single process. Here are some of the more useful commands (type help to view the complete command list).

image


Figure 8-2 The Palm Inspector tool

image

The Palm Inspector shows the currently displayed DOM and the styles being applied in the current scene. Unlike D8, Palm Inspector runs on the developer’s PC. Before an application can be inspected, the application must be launched for inspection. Do this using the “palm-launch” tool:

1. Open a command prompt or terminal window on the development PC. This is a local terminal; do not connect to the device.

2. Run the command palm-launch -i <application_name> [{parameters}].

a. The -i parameter indicates to start the application for inspection. This parameter must be specified.

b. <application_name> is the name of the application to run (for example, com.isecpartners.sports).

c. [{parameters}] is a JSON object of parameters to specify. The parameters are optional but some applications may require them.

3. Start the Palm Inspector tool. It will automatically connect to the running application and show the DOM. From here, the application’s styles may be adjusted and JavaScript can be executed in the bottom panel.

Code Security

The JavaScript runtime manages memory, removing the need for third-party developers to worry about traditional coding errors such as buffer and integer overflows or other memory corruption errors. Not to say that these problems won’t exist—they will. But they will occur in platform applications such as WebKit, and memory corruption errors should not be a primary concern for third-party application developers.

Instead, application developers must focus on preventing application-level flaws, including script injection, SQL injection, and business logic flaws. These three attack classes are real risks on WebOS and take some effort to avoid. This section outlines the common coding errors, their impact, why they occur, and how to prevent them. An analysis of unique WebOS behaviors is also presented.

Script Injection

One of the most common web application vulnerabilities is cross-site scripting (XSS). This vulnerability occurs when a web application accepts user data and inserts that user data directly into a generated web page or AJAX response. If the user data is malicious and includes JavaScript, the script will execute in the context of the web application and allow the user to abuse the user session.

NOTE

For more information on web application vulnerabilities, refer to http://www.owasp.org/index.php/Top_10_2007.

XSS results when the web application fails to encode or reject the user-supplied data when generating web pages. When the web browser receives the page, it cannot differentiate between JavaScript the developer supplied and the JavaScript that the attacker has injected. Because it can’t tell the difference, the browser errors on the side of execution and runs any script it finds. To prevent these vulnerabilities, the web application must encode user data before inserting it into the web page. The browser will not treat encoded data as JavaScript and the attacker’s exploit won’t execute.

WebOS script injection is very similar to XSS. If attackers provide data to applications and that data is either treated as JavaScript or inserted into scene bodies without escaping, the Mojo framework will run the script as part of the application. WebOS JavaScript is much less constrained than the web browser sandboxe’s web JavaScript. Once the attacker’s JavaScript is executing, the attacker can send messages to the public bus, access per-application private data, and attack the rest of the device. Script injection in com.palm.* applications is even more worrisome because these applications can access the private bus and sensitive data, including text messages and e-mail.

At the time of this writing, Palm has already released patches for two script injection vulnerabilities, demonstrating that script injection vulnerabilities are a concern.

Three broad categories of script injection affect WebOS: direct evaluation, programmatic insertion, and template injection. Regardless of category, the severity is still critical. The categories only differ in the ways in which the vulnerability’s manifest.

Note that this research is extremely young, and new forms of script injection will likely appear in the future. Remember to handle all user data with suspicion, especially when combining it with executable JavaScript or HTML.

Direct Evaluation

Direct evaluation vulnerabilities occur when applications take user data and execute it, either by using the eval statement or by improperly handling the data when serializing or deserializing objects. JavaScript, and its associated frameworks, provides many methods to directly execute code. Because of the flexibility that dynamic execution enables, direct evaluation is a surprisingly common pattern in modern web applications. The following two methods are the most common source of direct evaluation script injection vulnerabilities in WebOS.

eval

The JavaScript eval() statement accepts a string parameter containing JavaScript, compiles the parameter into JavaScript bytecode, and then executes the newly compiled statement. Frameworks commonly use eval() when dynamically generating classes or creating framework objects. If attackers are able to insert unescaped data when the eval() statement is being assembled, the attacker’s JavaScript will be compiled and evaluated as legitimate user-supplied code. To prevent this vulnerability, do not generate eval() statements that include user data. Very few WebOS applications should require using eval(), and its common use may be an indication of poor design. Prefer designs that do not commonly use eval().

If eval() is the only option, ensure that the data comes from a trusted source and use the JavaScript “escape” function when processing untrusted data.

For example, this function is vulnerable to direct script injection via eval:

//user_data contains un-escaped and potentially malicious user-data
var j = eval(‘executeRequest(‘ + user_data + ‘)’);

The developer is intending to call executeRequest with user_data as a parameter. However, attackers could supply a string for user_data that includes script. Here’s an example:

);evil(

After this string is concatenated into the preceding eval() statement, the evil function will be called.

To mitigate this vulnerability, change the code to the following:

//The built-in escape function will render malicious data harmless
var user_data_escaped = escape(user_data);
var j = eval(‘executeRequest(‘ + user_data_escaped + ‘)’);

The JavaScript escape() function encodes JavaScript meta-characters so that they will not be interpreted as JavaScript when the eval() statement executes.

JSON Injection

Another form of direct evaluation vulnerabilities occurs when parsing objects serialized using JavaScript Object Notation (JSON). This notation describes objects as a series of key/value pairs. An advantage of JSON is that the serialized blob is actually JavaScript. This makes using JSON extremely easy because string JSON can be deserialized with the eval() function. WebOS uses JSON extensively as the message interchange format for serialization requests.

An object with two properties (key1 and key2) serialized as a JSON string looks similar to the following:

“{
    key1 : “value”;
    key2 : “value2”;
}”

Prototype’s evalJSON() method is used to deserialize this string back to a native JSON object. The attacker can abuse the deserialization process by supplying objects containing JavaScript expressions as parameter values.

Here’s a malicious JSON object:

“{
    key1 : Mojo.Log.error(‘Exploited’);
    key2 : 42;
}”

When the JavaScript runtime deserializes this object using eval() or Prototype’s evalJSON(), the attacker-supplied logging statement will execute. Of course, logging statements are fairly benign. Attackers can always supply more damaging exploit code.

To mitigate JSON injection, never use eval() to deserialize JSON objects. Always use Prototype’s evalJSON() string method and pass “true” for the “sanitize” parameter. This parameter forces Prototype to reject any property value that contains an executable statement. Always use Prototype rather than “rolling your own” because the Prototype library is widely used and has been well reviewed.

Here’s an example of using the evalJSON() method to correctly ignore JavaScript during JSON deserialization:

var fruits = user_data.evalJSON(true);

Programmatic Data Injection

Script injection can also occur when data is programmatically inserted into Views by either manipulating the DOM directly or by calling Mojo functions which update the DOM. Once the attacker can affect the DOM, they can inject JavaScript and execute their exploit code.

innerHTML Injection

A simple form of script injection occurs when unescaped user data is assigned to an HTML element’s innerHTML property. This property accepts raw HTML and actually replaces the HTML of the parent element. Attackers can easily abuse this behavior to inject script tags into the WebOS application’s DOM.

For example, consider the following example from a sports application. The “user_data” variable contains unvalidated and untrusted user data.

var updatedScores = “<b>” + user_data + “</b>”;
this.sportsScoreElement.innerHTML = updatedScores;

In general, it is unsafe to use innerHTML for updating the WebOS DOM. Most of the time, developers follow this pattern because they are building HTML through string concatenation. This method of generating HTML is very dangerous and should be avoided if at all possible.

update() Injection

Many WebOS applications use the sceneController’s update() method to refresh screen elements and force a redraw. Unescaped user data must never be passed directly to the update() method because this can allow malicious JavaScript to be injected into the DOM.

Here are two vulnerable examples:

var updated_scores = “<b>” + user_data + “</b>”;
this.controller.update($(‘SportsScores’), updated_scores);

Or more directly:

this.controller.update($(‘SportsScores’), user_data);

In both of these instances, the SportsScores element is being updated with user_data, which may be malicious and provide attackers with the opportunity to inject script.

Avoiding innerHTML and update() Injections

Avoid concatenating user data with HTML tags. Not only is this practice less efficient, but it makes finding and removing script injection very difficult. The best solution is to design out the string concatenation.

If that is not possible, and sometimes it won’t be, then make sure to escape HTML data before sending it into the DOM. To do so, use Prototype’s escapeHTML() function. This method replaces all of the potentially dangerous characters with their “safe” versions. For example, < becomes &lt;. After this transformation, the < will no longer be interpreted as part of the document’s structure and attackers will no longer be able to insert script. The preceding vulnerable snippets could be rewritten as follows:

var updatedScores = “<b>” + user_data.escapeHTML() + “</b>”;

this.controller.update($(’SportsScores’), updated_scores);

and

this.controller.update($(’SportsScores’), user_data);

Unfortunately, this method is far from foolproof, and its success relies on never forgetting to apply the escapeHTML() function to potentially malicious data. Given the size of modern applications, errors will likely slip through. A still better option is to use WebOS templates for inserting user data into the DOM.

Template Injection

The final category of script injection flaws are template injection flaws. Generically, templates are snippets of HTML containing placeholders where user data can be inserted. They are used heavily within views and are helpful to developers looking to avoid writing large amounts of presentation-generation code.

WebOS overloads the term template. There are actually two types of templates, and their behavior is similar but different in a scary and impactful way. The two types of templates are WebOS widget templates and Prototype templates. Most developers will only use WebOS templates because they are much more integrated into the overall Mojo framework.

WebOS Templates

When some widgets (such as the List widget) are used, a formatting template file may be specified. WebOS will invoke this template for each row that it inserts into the output list. The template contains HTML with simple placeholders that will be replaced by values from the template’s model. This system lets the developer avoid having to write complicated formatting code for configuring UI elements.

For example, the following HTML snippet formats will be applied to each list row and cause each element to have two divs—one for the team_name and one for the team_score. The contents of the #{team_name} and #{score} elements will be replaced with data from the row’s model object.

<div class=“row textfield” >
    <div class=“score_tuple”>
        <div class=“team_name”>Team Name: #{team_name}</p>
        <div class=“team_score”>Score: #{score}</div>
    </div>
</div>

By default, the data substituted for the #{team_name} and #{score} tokens will be HTML-escaped. Therefore, script injection vulnerabilities, like the ones discussed in the “innerHTML Injection” section, will be prevented. This is obviously a clear advantage templates have over other formatting mechanisms.

However, the automatic escaping can be disabled by editing the application’s framework_config.json file and setting the value of the escapeHTMLInTemplates property to false. The framework_config.json file is stored in the application’s root directory and contains a list of properties that configure the Mojo framework itself. Try to avoid setting this property to false. Otherwise, the entire application must be reviewed for locations where unescaped and potentially malicious user data is formatted into templates. This is a time-consuming and expensive process, especially when compared to the cost of writing proper templates.

Instead of globally disabling HTML escaping, instruct the framework to disable it on a token-by-token basis. Do this by placing a hyphen (-) at the beginning of the replacement tokens. The framework will skip HTML-escaping these elements.

Here’s an updated version of the preceding team_name div. The #{team_name} replacement token will not be escaped.

<div class=“team_name”>Team Name: #{-team_name}</p>

Use this behavior sparingly. If an element is excluded from HTML escaping, ensure that models used for formatting do not contain any unescaped user data.

Prototype Templates

The Prototype JavaScript framework, included with WebOS, has its own template functionality that is very similar to standard WebOS view templates. However, these templates are not governed by the escapeHTMLInTemplates property. Therefore, any data formatted into Prototype templates must be manually escaped.

For example, the following template-formatting routine is vulnerable to script injection when user_data contains malicious data:

var score_template = new Template(“<b> #{new_score} </b>”);
sports_score = score_template.evaluate({“new_score” : user_data});
this.controller.update($(‘SportsScores’), sports_score);

To make this function safe, manually escape the data using Prototype’s escapeHTML() function.

Local Data Injection

Data from web pages, e-mails, and text messages is obviously malicious, but an additional, and often forgotten about, attack surface is the local one. With the rise of mobile malware, it is highly likely that users will install a malicious application at one point or another. WebOS makes some attempts to protect applications from each other: Sensitive data, such as e-mails and SMS messages, is directly accessible only through the private bus, and each application is able to store private data using either the cookie or depot storage API. Therefore, in order for mobile malware to compromise another application’s data, the malware must find a way to inject script into the target application.

Unfortunately, there are several ways this may happen, and they are not all well documented. This section outlines the various vectors available to malware attempting to inject script.

Application Launch Parameter Script Injection

One method attackers may use to inject script is by providing parameters containing script values. These parameters will be passed to the StageAssistant and/or AppAssistant when the application starts. The system provides no guarantees about the quality of this data, and parameter data certainly cannot be trusted.

To launch another application, applications dispatch a “launch” service request to the ApplicationManager service. Here’s an example:

this.controller.serviceRequest(“palm://com.palm.applicationManager”,
{
    “method” : “launch”,
    “parameters” : {
        “id” : “com.isecpartners.movietimes”,
        “params”: {
            movie_title : “Indiana Jones”,
            server_url: “http://www.isecpartners.com/movies”
        }
    }
});

All applications are permitted to launch any other installed application and supply any parameter values they wish. Applications need to handle potentially malicious launch parameters. If the launched application doesn’t handle the data appropriately—perhaps by improper use of templates or the update method—the malware could inject JavaScript that will execute in the context of the target application.

There are legitimate uses for launch parameters. For example, a movie application may take a “movie_title” parameter that it uses to search the Internet for movie show times. Because malware may have caused the application launch, the movie application must be careful about how it treats the “movie_title” data. Otherwise, formatting the search query into a template or evaluating it as JSON will likely result in script injection.

Script injection is not the only concern; malicious values may be supplied to exploit the application’s business logic. For example, our movie application could take a “server_url” parameter that tells the application which server to run the search query against. Assume that along with this search request, the application sends an authentication token. Obviously, an attacker would like to gain access to this token. By supplying their own value for the “server_url” parameter, the attacker may be able to force the application to post the attacker’s malicious server. This technique could be used to harvest a large number of authentication tokens.

Do not trust launch parameter values and, if possible, limit the set of allowed values to a predefined whitelist. Avoid sending data, especially sensitive data, to launch parameter-specified server addresses. If a request will leak sensitive data, consider asking the user before issuing the request.

To test an application’s resistance to malicious launch parameters, start the application using the luna-send command-line tool. This tool must be run from a WebOS command prompt and enables sending serviceRequests directly to services.

To use luna-send to launch an application, do the following:

1. Open a novaterm shell to the device.

2. Run the following command. The terminal requires the additional backslashes be used for escaping quotes.

luna-send -n 1 “palm://com.palm.applicationManager/launch”

“{“id”:“com.isecpartners.helloworld”,

“params”:“{foo:\“bar\”}”}”

Directly Launching Scenes

A slightly less well understood boundary is the scene boundary. Quite simply, any application can push a scene from any other application onto its scene stack. When this happens, the application that owns the scene is started and the execution context switches to the newly pushed scene.

This behavior is legitimately used throughout WebOS to elevate privileges and to provide a consistent user experience. For example, applications are prohibited from using the Camera plug in directly, but they can push the capture scene from the Camera application onto their stack. When they do so, the Camera scene runs and provides the user interface and permissions for taking the camera shot.

The Camera capture scene is an example of a scene that was designed to be included by other applications. However, not all scenes are designed this way, and attackers may be able to abuse scenes by invoking them out of order or supplying malicious parameters. Vulnerabilities resulting from the direct instantiation of scenes are similar to application launch vulnerabilities. Applications can invoke a scene directly using the Mojo.Controller.StageController.pushScene(scene, args) method, as shown here:

this.controller.stageController.pushScene(
    { appId: ‘com.isecpartners.movie_app’, name: ‘PurchaseScene’ },
    { tickets: “2”});

The second (args) parameter to the pushScene() method is an object that will be passed to the PurchaseScene’s scene assistant. Just like parameters passed on application launch, scene parameters must not be trusted. Also be aware that your scene may be called out of order. Imagine the following scenario:

1. A movie application allows you to look up nearby movie times and purchase tickets. To ease the purchase process, the movie application stores your account information.

2. When you make the purchase, the application takes you through a three-step process: Search Movies, Select Theater and Time, and Purchase.

3. The Purchase scene takes a movie ticket ID and the e-mail address to send the tickets to as scene parameters.

4. When the Purchase scene starts, it performs the purchase automatically and then shows the results to the user.

Malware can abuse this process by skipping the first two scenes and directly invoking the Purchase scene. Because the application didn’t verify the e-mail address parameter, the tickets are sent to the attacker’s e-mail address instead of to the legitimate user.

The process may sound contrived, but vulnerabilities extremely similar to this have been found in several WebOS applications. Unfortunately, being vigilant is the only solution. Always design scenes so that they are resistant to malicious parameters and do not execute sensitive actions without first asking the user for confirmation.

Opening Documents and Service Requests

Two additional methods for launching applications and communicating between applications involve using the Application Manager’s “open” method and directly making a serviceRequest. In the current version of the SDK, third-party applications are unable to register to be launched using either of these methods. If third-party services or document handling are ever allowed, though, risks similar to those outlined in the previous two sections will likely apply.

Application Packaging

Applications are packaged using the Itsy Package Manager System (ipkg). This is a commonly used application distribution format for embedded devices, and it bundles the entire application into a single easy-to-distribute file. The package files have the extension .ipk and are actually tar’d and gzip’d files (.tar.gz). To uncompress IPKs on Windows, simply use an extractor, such as 7-Zip, to extract the package’s contents.

IPKs may have an embedded signature, although Palm has not yet released the details on their signing process. Very few, if any details are currently available about the signatures that will be required for WebOS applications. The best guidance comes from the Terms of Service (http://developer.palm.com/termsofservice.html), which states that “applications which access or make use of Palm’s APIs may not be installed or used on Palm Devices, except in a test environment, without first being signed by a certificate issued by or for Palm.” In the future, developers will likely have to register with Palm and receive a developer certificate. Applications currently being distributed through the App Store are signed with a certificate owned by Palm. Details about this process will soon be added to the Palm Developer Portal, so check there for the most current information (http://developer.palm.com).

The package embeds the signature as three disjointed files: a certificate in PEM format, a public key, and a detached signature. It is unclear which content this signature covers, but it likely includes all files and directories within the IPK.

Permissions and User Controls

WebOS implements a very simple permission system that is not nearly as expressive as the system on Android or BlackBerry. As explained earlier in the WebOS architecture discussion, WebOS places an application into one of two buckets: com.palm.* or everything else. The com.palm.* applications can access the private bus and relatively unrestricted service interfaces. Using these APIs, com.palm.* applications can access and control much of the phone’s functionality, including gaining unrestricted access to e-mail.

Third-party applications are restricted to using the public Service APIs. This set of APIs only exposes functionality that most users would deem as acceptable. For example, applications may launch the phone dialer application with a prepopulated number, but the user must press the dial button before a phone call can be made. These pauses in behaviors interject decision points where users can make security decisions without realizing they are. Additionally, applications cannot read e-mail or message data from the internal messaging stores using the e-mail Service APIs.

Storage

WebOS developers have a myriad of storage options to choose from, including structured Depot storage, HTML 5 databases, JSON Cookie objects, and files (using the File Picker UI). Each of these options has its own peculiarities.

Cookie Objects

The most basic form of WebOS storage objects are cookie objects. These objects should be used for storing small amounts of data. User application preferences or browser favorites are good examples of potential cookie data. Palm recommends a maximum of 4KB per cookie, but this is not a hard-and-fast limit. Only the application that created a cookie is allowed to read the cookie’s data. For this reason, cookies are recommended for per-application data storage of small amounts of data. Interestingly, Luna enforces this restriction using a method similar to how desktop WebKit isolates cookies between websites. When the cookie object is created, Luna generates a fake domain name that will be unique to the application. This domain is stored along with the cookie in the application cookie database. When applications attempt to load the cookie, their domain name is checked against the database before the cookie is returned. Any requests for cookies not belonging to the application are rejected. Use the Mojo.Model.Cookie interface to create cookies.

NOTE

For more information on Cookie objects, see “Storage Overview” on the Palm website (http://developer.palm.com/index.php?option=com_content&view=article&id=1734).

Depots

Depots are structured storage used for storing JavaScript objects as key/value pairs. The simple Depot interface consists of simple key/value put methods. Luna enforces Depot security by partitioning Depots per application. The Depot receives a unique name generated from the application identifier, and this name is used regardless of the name the application uses to refer to the Depot. In this way, Depots are very similar to Cookie objects. Smaller Depots that are less than 1MB in size can be stored within the application’s directory. Depots larger than 1MB must be stored within the file system’s media partition. To force a Depot to the media partition, specify the keyword “ext” as part of the Depot’s name, as shown here:

var isec_depot = new Mojo.Depot({name:“ext:iSEC”}, onSuccess, onFailure);

Do not store Depots containing sensitive data on the media partition unless absolutely necessary because this partition becomes browsable when the device is connected to a PC (http://developer.palm.com/index.php?option=com_content&view=article&id=1734).

Depots are currently built on top of HTML 5 databases, but this is an implementation detail and may change in the future. Create Depot objects using the Mojo.Depot() API.

HTML 5 Databases

WebOS includes full support for HTML 5 Database objects. Like their server brethren, these databases have tables and are queried using the SQL query language. Like Depots and Cookie objects, databases are unique per application. To create a database, use the openDatabase() method. To query a database, use the executeSQL() method.

WebOS applications using databases need to be careful to avoid SQL injection, a common web application vulnerability. Similar to script injection, this vulnerability results from inserting unescaped user data directly into queries. Depending on the application, this may allow malware to corrupt the application’s database or steal sensitive data. The risk on WebOS is smaller than the risk to web applications because databases are per-application and there aren’t different authentication stages.

Even though the risk is less, it is worth preventing SQL injection by using parameterized queries and never building SQL queries using string concatenation. Parameterized queries are created by using the “?” placeholder instead of the actual value when authoring the query. The parameter’s value is then provided in a separate argument array. Because the query and the data are provided separately, the database engine does not become confused and accidentally interpret the user data as part of the queries’ executable portion. Here’s an example:

transaction.executeSql(‘SELECT * FROM Vulnerabilities WHERE Id = ?’,
                         [ vuln_id ],
                         onSuccess,
                         onError);

In this example, we are selecting entries from the Vulnerabilities table that have the ID matching the vuln_id argument. An arbitrary number of parameters and values may be specified for any query. To prevent SQL injection, always use parameterized queries.

File Storage

WebOS devices have internal storage for storing documents, media files, and other large data. Developers do not have access to file APIs for reading and writing data, but they can invoke the FilePicker control, which will present users with a list of files to choose from. The chosen filename will then be returned to the user. Application developers can then launch a viewer for the file using the ApplicationManager’s “launch” action.

Networking

Applications are able to connect to other servers using the XmlHTTPRequest object and receive push notifications using the Palm messaging service. Applications are not allowed to use raw TCP sockets directly. XmlHTTPRequest behaves exactly the same as standard XmlHTTPRequest objects, except the Same Origin Policy is not applied. Applications can make HTTP requests to any site, port, and scheme.

The Palm messaging service is an Extensible Messaging and Presence Protocol (XMPP) service that is still in development. When completed, it will allow applications to register for and receive push notifications of events. An example of an event might be an updated time for a flight or the latest sports scores. The security architecture of the messaging system will have to be explored in more depth once it is finalized.

Conclusion

WebOS is an exciting new mobile operating system and innovates with its use of web technologies for application development. However, with these innovations come new security challenges. The risk of traditional web vulnerabilities such as script and SQL injection is especially troubling. As the platform matures, expect Palm to adopt more proactive defense measures such as automatic input filtering and output encoding. Some positive security changes have already been made to the platform. Hopefully this trend will continue.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.152.87